diff --git "a/data/dataset_Neurology.csv" "b/data/dataset_Neurology.csv" new file mode 100644--- /dev/null +++ "b/data/dataset_Neurology.csv" @@ -0,0 +1,195831 @@ +"keyword","repo_name","file_path","file_extension","file_size","line_count","content","language" +"Neurology","ChristianGaser/cat12","cat_conf_opts.m",".m","24921","381","function opts = cat_conf_opts(expert) +% Configuration file for CAT SPM options +% +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ +%#ok<*AGROW> + +if ~exist('expert','var') + expert = 0; % switch to de/activate further GUI options +end + + +%------------------------------------------------------------------------ +% various options for estimating the segmentations +%------------------------------------------------------------------------ + + +% tpm: +%------------------------------------------------------------------------ +tpm = cfg_files; +tpm.tag = 'tpm'; +tpm.name = 'Tissue Probability Map'; +tpm.filter = 'image'; +tpm.ufilter = '.*'; +tpm.def = @(val)cat_get_defaults('opts.tpm', val{1}); +tpm.help = { + 'Select the tissue probability image that includes 6 tissue probability classes for (1) grey matter, (2) white matter, (3) cerebrospinal fluid, (4) bone, (5) non-brain soft tissue, and (6) the background. CAT uses the TPM only for the initial SPM segmentation. Hence, it is more independent and allows accurate and robust processing even with the standard TPM in case of strong anatomical differences, e.g. very old/young brains. Nevertheless, for children data we recommend to use customized TPMs created using the Template-O-Matic toolbox. ' + '' + '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 down-sampled to 1.5 mm 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. The algorithm used here will employ these priors for the first initial segmentation and normalization. Six tissue classes are used: grey matter, white matter, cerebrospinal fluid, bone, non-brain soft tissue and air outside of the head and in nose, sinus and ears. 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. Selected tissue probability map must be in multi-volume nifti format and contain all six tissue priors. ' + '' +}; +tpm.num = [1 1]; +tpm.def = @(val)cat_get_defaults('opts.tpm', val{:}); + + +% ngaus: +%------------------------------------------------------------------------ +% The default of SPM12 [GM,WM,CSF,bone,head tissue,BG] was [1,1,2,3,4,2] +% and works very well for most data and the segmentation did not benefit by +% more classes. There are no systematic effects for interferences or +% special anatomical properties (e.g. WMHs)! +%------------------------------------------------------------------------ +ngaus = cfg_entry; +ngaus.tag = 'ngaus'; +ngaus.name = 'Gaussians per class'; +ngaus.strtype = 'n'; +ngaus.num = [1 6]; +ngaus.def = @(val)cat_get_defaults('opts.ngaus', val{:}); +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 one to three for grey and white matter, two for CSF, three for bone, four for other soft tissues and two for air (background).' + '' + ...'Note that if any of the Num. Gaussians is set to non-parametric, then a non-parametric approach will be used to model the tissue intensities. This may work for some images (eg CT), but not others - and it has not been optimised for multi-channel data. Note that it is likely to be especially problematic for images with poorly behaved intensity histograms due to aliasing effects that arise from having discrete values on the images.' + ...'' +}; + + +biasacc = cfg_menu; +biasacc.tag = 'biasacc'; +biasacc.name = 'Strength of SPM Inhomogeneity Correction'; +biasacc.def = @(val)cat_get_defaults('opts.biasstr', val{:}); +biasacc.labels = {'light','medium','strong','heavy'}; +biasacc.values = {0.25 0.50 0.75 1.00}; +biasacc.help = { + 'Strength of the SPM inhomogeneity (bias) correction that simultaneously controls the SPM biasreg, biasfwhm, samp (resolution), and tol (iteration) parameter. Modify this value only if you experience any problems! Use smaller values for slighter corrections (e.g. in synthetic contrasts without visible bias) and higher values for stronger corrections (e.g. in 3 or 7 Tesla data with strong visible bias). Stronger corrections often improve cortical results but can also cause overcorrection in larger GM structures such as the subcortical structurs, thalamus, or amygdala and will take longer. Bias correction is further controlled by the Affine Preprocessing (APP). ' + '' +}; + +%------------------------------------------------------------------------ +% Bias correction +%------------------------------------------------------------------------ +biasstr = cfg_menu; +biasstr.tag = 'biasstr'; +biasstr.name = 'Strength of SPM Inhomogeneity Correction'; +biasstr.def = @(val)cat_get_defaults('opts.biasstr', val{:}); +if ~expert + biasstr.labels = {'light','medium','strong'}; + biasstr.values = {0.25 0.50 0.75}; + %biasstr.labels = {'ultralight','light','medium','strong','heavy'}; + %biasstr.values = {0 0.25 0.50 0.75 1}; + biasstr.help = { + 'Strength of the SPM inhomogeneity (bias) correction that simultaneously controls the SPM biasreg and biasfwhm parameter. Modify this value only if you experience any problems! Use smaller values for slighter corrections (e.g. in synthetic contrasts without visible bias) and higher values for stronger corrections (e.g. in 3 or 7 Tesla data with strong visible bias). Bias correction is further controlled by the Affine Preprocessing (APP). ' + '' + }; +elseif expert>=1 + biasstr.labels = {'ultralight (eps)','light (0.25)','medium (0.50)','strong (0.75)','heavy (1.00)'}; + biasstr.values = {eps 0.25 0.50 0.75 1}; + biasstr.help = { + 'Strength of the SPM inhomogeneity (bias) correction that simultaneously controls the SPM biasreg and biasfwhm parameter. Modify this value only if you experience any problems! Use smaller values (>0) for slighter corrections (e.g. in synthetic contrasts without visible bias) and higher values (<=1) for stronger corrections (e.g. in 7 Tesla data). Bias correction is further controlled by the Affine Preprocessing (APP). ' + '' + ' biasreg = min( 10 , max( 0 , 10^-(biasstr*2 + 2) )) ' + ' biasfwhm = min( inf , max( 30 , 30 + 60*(1-biasstr) )) ' + '' + ' biasstr biasfwhm biasreg' + ' ultralight: eps 90 0.0100 ' + ' light: 0.25 75 0.0032 ' + ' medium: 0.50 60 0.0010 ' + ' strong: 0.75 45 0.0003 ' + ' heavy: 1.00 30 0.0001 ' + }; +%{ +elseif expert==2 + biasstr.labels = {'use SPM bias parameter (0)','ultralight (eps)','light (0.25)','medium (0.50)','strong (0.75)','heavy (1.00)'}; + biasstr.values = {0 eps 0.25 0.50 0.75 1}; + biasstr.help = { + 'Strength of the SPM inhomogeneity (bias) correction that simultaneously controls the SPM biasreg and biasfwhm parameter. Modify this value only if you experience any problems! Use smaller values (>0) for slighter corrections (e.g. in synthetic contrasts without visible bias) and higher values (<=1) for stronger corrections (e.g. in 7 Tesla data). The value 0 will use the original SPM biasreg and biasfwhm parameter of the cat_defaults file. Bias correction is further controlled by the Affine Preprocessing (APP). ' + '' + ' biasreg = min( 10 , max( 0 , 10^-(biasstr*2 + 2) )) ' + ' biasfwhm = min( inf , max( 30 , 30 + 60*(1-biasstr) )) ' + '' + ' biasstr biasfwhm biasreg' + ' SPM parameter: - - - ' + ' ultralight: eps 90 0.0100 ' + ' light: 0.25 75 0.0032 ' + ' medium: 0.50 60 0.0010 ' + ' strong: 0.75 45 0.0003 ' + ' heavy: 1.00 30 0.0001 ' + }; +%} +end + + +% biasreg: +%------------------------------------------------------------------------ +% Test on the BWP and real data demonstrate that 0.001 mm works best in +% average, whereas some image benefit by more regularisation (0.01) and strong +% bias requires less regularisation (0.0001). There are no special cases +% that benefit by a regularisation >0.01 or <0.0001! Hence, I removed +% these entries (RD 2017-03). +%------------------------------------------------------------------------ +biasreg = cfg_menu; +biasreg.tag = 'biasreg'; +biasreg.name = 'Bias regularisation'; +biasreg.def = @(val)cat_get_defaults('opts.biasreg', val{:}); +if 0 + 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, 0.00001, 0.0001, 0.001, 0.01, 0.1, 1.0, 10}; +else + biasreg.labels = {'Very light regularisation (0.0001)','Light regularisation (0.001)','Medium regularisation (0.01)'}; + biasreg.values = {0.0001, 0.001, 0.01}; +end +biasreg.help = { + 'Regularisation of the SPM bias field. This parameter is controlled by the biasreg parameter if biasstr>0. Test on the BWP and real data showed that optimal corrections was in range of 0.01 and 0.0001.' + '' + 'MR images are usually corrupted by a smooth, spatially varying artefact that modulates the intensity of the image (bias). These artefact, 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. 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. ' + '' +}; + + +% biasfwhm: +%------------------------------------------------------------------------ +% Test on the BWP and real data demonstrate that 60 mm works best for most +% datasets. Only 7 Tesla data need further adaptation, larger filter size is +% normaly not required (RD 2017-03)! +% - 30-40 mm: low filter size for very strong fields (e.g. 7 or 3 Tesla data) +% - 50-60 mm: medium filter size works best for >95% of the data, and do not overfit in case of low bias +% - 70-90 mm: high filter size in case of low bias data +% - >90 mm: better to avoid that, because there is mostly a low bias in the data that is normally not visible +%------------------------------------------------------------------------ +biasfwhm = cfg_menu; +biasfwhm.tag = 'biasfwhm'; +biasfwhm.name = 'Bias FWHM'; +if 0 + 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}; +else + biasfwhm.labels = {'30mm cutoff','40mm cutoff','50mm cutoff','60mm cutoff','70mm cutoff','80mm cutoff','90mm cutoff'}; + biasfwhm.values = {30,40,50,60,70,80,90}; +end +biasfwhm.def = @(val)cat_get_defaults('opts.biasfwhm', val{:}); +biasfwhm.help = { + 'FWHM of Gaussian smoothness of bias. This parameter is controlled by the biasreg parameter if biasstr>0. Test on the BWP and real data showed that 50 to 60 mm works best for nearly all datasets and only some 7 Tesla scans require further adaptation! ' + ' 30-40 mm: low filter size for very strong fields (e.g. 7 or 3 Tesla data) ' + ' 50-60 mm: medium filter size works best for >95% of the data, and do not overfit in case of low bias ' + ' 70-90 mm: high filter size in case of low bias data ' + '' + '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. ' + '' +}; + +biasspm = cfg_branch; +biasspm.tag = 'spm'; +biasspm.name = 'Original SPM bias correction parameter'; +biasspm.val = {biasfwhm biasreg}; +biasspm.help = { + 'SPM bias correction parameter biasfwhm and biasreg.' +}; + +bias = cfg_choice; +bias.tag = 'bias'; +bias.name = 'Biascorrection parameter'; +if cat_get_defaults('opts.biasstr')>0 + bias.val = {biasstr}; +else + bias.val = {biasspm}; +end +bias.values = {biasstr biasspm}; +bias.help = { + 'Bias correction parameters.' +}; + + + + + + + +% warpreg: +%------------------------------------------------------------------------ +% no useful changes in the following testcases: +% [0 0.001 0.5 0.05 0.2] % the default setting +% [0 0.0001 0.001 0.01 0.1] % lower initial regularision with stepwise increasement +% [0 0.001 0.01 0.1 0.2] % low initial regularision with stepwise increasement +% [0.5 0.4 0.3 0.2 0.1] % medium initial regularision with stepwise decreasment +% [1.0 0.8 0.6 0.4 0.2] % +% [0.0 0.8 0.2 0.8 0.2] % +%------------------------------------------------------------------------ +warpreg = cfg_entry; +warpreg.def = @(val)cat_get_defaults('opts.warpreg', val{:}); +warpreg.tag = 'warpreg'; +warpreg.name = 'Warping Regularisation'; +warpreg.strtype = 'r'; +warpreg.num = [1 5]; +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. ' + '' +}; + + +% affreg +%------------------------------------------------------------------------ +% no large differences +% - mni was most stable +% - rigid did not work in ~20% of the cases (and is of course not meaningful here) +% - subj and none led to identical results +% - no registration only for animals +%------------------------------------------------------------------------ +affreg = cfg_menu; +affreg.tag = 'affreg'; +affreg.name = 'Affine Regularisation'; +affreg.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.' + '' +}; +if expert + affreg.labels = {'ICBM space template - European brains','ICBM space template - East Asian brains','No regularisation','No Affine Registration'}; + affreg.values = {'mni','eastern','none',''}; + affreg.help = [affreg.help { + 'No affine registration was added for processing of animals, where registration may fail!' + '' + }]; +else + affreg.labels = {'ICBM space template - European brains','ICBM space template - East Asian brains','No regularisation'}; + affreg.values = {'mni','eastern','none'}; +end +affreg.def = @(val)cat_get_defaults('opts.affreg', val{:}); + + + +% samp: +%------------------------------------------------------------------------ +% Surprisingly, there is no systematical advantage in using higher +% resolution! Only very slightly in single cases, e.g. 7 Tesla. +%------------------------------------------------------------------------ +samp = cfg_entry; +samp.tag = 'samp'; +samp.name = 'Sampling distance'; +samp.strtype = 'r'; +samp.num = [1 1]; +samp.def = @(val)cat_get_defaults('opts.samp', val{:}); +samp.help = { + 'This encodes the approximate distance between sampled points when estimating the model parameters. Smaller values use more of the data, but the procedure is slower and needs more memory. Determining the ""best"" setting involves a compromise between speed and accuracy.' + '' +}; + +% SPM processing accuracy +tol = cfg_menu; +tol.tag = 'tol'; +tol.name = 'SPM iteration accuracy'; +tol.help = { ... + 'Parameter to control the iteration stop criteria of SPM preprocessing functions. In most cases the standard value is good enough for the initialization in CAT. However, some images with servere (local) inhomogeneities or atypical anatomy may benefit by further iterations. ' + }; +tol.def = @(val)cat_get_defaults('opts.tol', val{:}); +tol.labels = {'average (default)' 'high (slow)' 'ultra high (very slow)'}; +tol.values = {1e-4 1e-8 1e-16}; +if expert>1 % developer + tol.labels = [{'ultra low (superfast)' 'low (fast)'} tol.labels {'insane'}]; + tol.values = [{1e-1 1e-2} tol.values {1e-32}]; +end + +% single parameter +accspm = cfg_branch; +accspm.tag = 'spm'; +accspm.name = 'Original SPM accuracy parameter'; +accspm.val = {samp tol}; +accspm.help = { + 'Official SPM resolution parameter ""samp"" and internal SPM iteration parameter ""tol"".' +}; + +% combined SPM processing accuracy parameter +accstr = cfg_menu; +accstr.tag = 'accstr'; +accstr.name = 'SPM processing accuracy'; +accstr.help = { ... + 'Parameter to control the accuracy of SPM preprocessing functions. In most images the standard accuracy is good enough for the initialization in CAT. However, some images with severe (local) inhomogeneities or atypical anatomy may benefit by additional iterations and higher resolution. ' + }; +accstr.labels = {'average (default)' 'high (slow)' 'ulta high (very slow)'}; +accstr.values = {0.5 0.75 1.0}; +accstr.def = @(val)cat_get_defaults('opts.accstr', val{:}); % no cat_defaults entry +if expert + %accstr.labels = [{'ultra low (superfast)' 'low (fast)'} accstr.labels]; + %accstr.values = [{0 0.25} accstr.values]; + accstr.help = [accstr.help; + {'' + ['Overview of parameters: ' ... + ' accstr: 0.50 0.75 1.00' ... + ' samp: 3.00 2.00 1.00 (in mm)' ... + ' tol: 1e-4 1e-8 1e-16' ... + '' ... + 'SPM default is samp = 3 mm with tol = 1e-4. ']}]; +end + +% single parameter +acc = cfg_choice; +acc.tag = 'acc'; +acc.name = 'SPM preprocessing accuracy parameters'; +if cat_get_defaults('opts.accstr')>0 + acc.val = {accstr}; +else + acc.val = {accspm}; +end +acc.values = {accstr accspm}; +acc.help = { + 'Choose between single or combined SPM preprocessing accuracy parameters.' +}; + + +redspmres = cfg_entry; +redspmres.tag = 'redspmres'; +redspmres.name = 'SPM preprocessing output resolution limit'; +redspmres.strtype = 'r'; +redspmres.num = [1 1]; +redspmres.def = @(val)cat_get_defaults('opts.redspmres', val{:}); +redspmres.help = {'Limit SPM preprocessing resolution to improve robustness and performance. Use 0 to process data in the full internal resolution.' ''}; + + +%------------------------------------------------------------------------ +opts = cfg_branch; +opts.tag = 'opts'; +opts.name = 'Options for initial SPM12 preprocessing'; +opts.help = { + 'CAT uses the Unified Segmentation of SPM12 for initial registration, bias correction, and segmentation. The parameters used here were optimized for a variety of protocols and anatomies. Only in case of strong inhomogeneity of high-field MR scanners we recommend to increase the biasstr parameter. For children data we recommend to use customized TPMs created by the Template-O-Matic toolbox. ' + '' + }; +if expert>1 + opts.val = {tpm,affreg,ngaus,warpreg,bias,acc,redspmres}; + opts.help = [opts.help; { + 'Increasing the initial sampling resolution to 1.5 or 1.0 mm may help in some cases of strong inhomogeneity but in general it only increases processing time.' + '' + 'Strength of the bias correction ""biasstr"" controls the biasreg and biasfwhm parameter if biasstr>0!' + '' + }]; +elseif expert==1 + opts.val = {tpm,affreg,biasstr,accstr}; + opts.help = [opts.help; { + 'Increasing the initial sampling resolution to 1.5 or 1.0 mm ma help in some cases of strong inhomogeneity but in general it only increases processing time.' + '' + }]; +else + opts.val = {tpm,affreg,biasacc}; + +end + +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_io_handle_pre.m",".m","1621","38","function FO = cat_io_handle_pre(F,pre,addpre,existfile) +% Remove all known cat prefix types from a filename (and check if this file exist). +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + if nargin<4, existfile = 1; end + if nargin<3, addpre = 0; end + + [pp,ff,ee] = fileparts(F); + + if ~addpre + prefix{1} = {'r','m','e'}; + prefix{2} = {'ma','mb','mc','mv','mn','mi','ml', ... % modifications of T + 'pa','pb','p0','p1','p2','p3','p4','p5','pf','pp' ... % segmentations of T + 'en','eb','ev','ei','ej','em', ... % error maps + 't1','t2','t3','t4'}; % thickness and distaces + prefix{3} = {'ra0','ra1','rw0','rw1','rwa','rwb','rwj', ... + 'rd0','rd1','rda','rdb','rdj', ... + 'rcs','lcs','bcs','acs','hcs'}; + prefix{4} = {'ercs','elcs','ebcs','eacs','ehcs'}; + + for pf=1:numel(prefix) + if numel(ff)>pf+1 && any(strcmp(ff(1:pf),prefix{pf})) && ... + (~existfile || exist(fullfile(pp,[ff(pf+1:end) ee]),'file')) + FN = cat_io_handle_pre(fullfile(pp,[ff(pf+1:end) ee]),'',addpre,existfile); + if (~existfile || exist(FN,'file')), [ppn,ffn] = fileparts(FN); ff=ffn; end + end + end + end + + FO = fullfile(pp,[pre ff ee]); +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_io_matlabversion.m",".m","867","33","function year = cat_io_matlabversion(varargin) +% return Matlab version year +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + + if strcmpi(spm_check_version,'octave') + year = 20201; + return + end + + vers = version; + [t1,t2,t3,year] = regexp(vers,'\(R.....\)'); + switch year{1}(end-1) + case 'a', year = [year{1}(3:end-2) '1']; + case 'b', year = [year{1}(3:end-2) '2']; + otherwise, year = [year{1}(3:end-2) '0']; + end + year = str2double(year); + + if nargin==1 + year = varargin{1}==year; + end + if nargin==2 + year = varargin{1}<=year && year<=varargin{1}; + end +end","MATLAB" +"Neurology","ChristianGaser/cat12","optimizer3d.h",".h","682","14","/* $Id$ */ +/* (c) John Ashburner (2007) */ +extern void fmg3(int n0[], float *a0, float *b0, int rtype, double param[], int c, int nit, + float *u0, float *scratch); +extern void cgs3(int dm[], float A[], float b[], int rtype, double param[], double tol, int nit, + float x[], float r[], float p[], float Ap[]); +extern void resize(int na[], float *a, int nc[], float *c, float *b); +extern float norm(int m, float a[]); +extern void LtLf_be(int dm[], float f[], double s[], float g[]); +extern void LtLf_me(int dm[], float f[], double s[], float g[]); +extern void LtLf_le(int dm[], float f[], double s[], float g[]); +extern int fmg3_scratchsize(int n0[]); + +","Unknown" +"Neurology","ChristianGaser/cat12","cat_io_json.m",".m","632","34","function S = cat_io_json(varargin) +%cat_io_json. Read json file. + + S = struct(); + + if nargin == 1 + if isstruct(varargin{1}) + % job case + files = job.files; + else + % just a file + files = cellstr(varargin{1}); + end + end + + for fi = 1:numel(files) + if ~exist(files{fi},'file') + cat_io_cprintf('err','ERROR: Miss ""%s""\n',files{fi}) + else + fid = fopen(files{fi}); + raw = fread(fid,inf); + str = char(raw'); + fclose(fid); + val = jsondecode(str); + + if fi == 1 + S = val; + else + S = cat_io_mergeStruct(S,val); + end + end + end +end + ","MATLAB" +"Neurology","ChristianGaser/cat12","cat_stat_nanmedian.m",".m","2576","89","function out = cat_stat_nanmedian(in, dim) +% ---------------------------------------------------------------------- +% Median, not considering NaN values. Similar usage like median() or +% MATLAB nanmedian of the statistic toolbox. Process input as double +% due to errors in large single arrays and set data class of ""out"" +% to the data class of ""in"" at the end of the processing, +% Use dim==0 to evaluate in(:) in case of dimension selection +% (e.g., in(:,:,:,2) ). +% +% out = cat_stat_nanmedian(in,dim) +% +% Example 1: +% a = rand(4,6,3); +% a(rand(size(a))>0.5)=nan; +% av = cat_stat_nanmedian(a,3); +% am = nanmedian(a,3); % of the statistical toolbox ... +% fprintf('%0.4f %0.4f\n',([av(:),am(:)])'); +% +% Example 2 - special test call of example 1: +% cat_stat_nanmedian('test') +% +% See also cat_stat_nansum, cat_stat_nanstd, cat_stat_nanmean. +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + if nargin < 1 + help cat_stat_nanmedian; + return; + end; + + if ischar(in) && strcmp(in,'test') + a = rand(4,6,3); + a(rand(size(a))>0.5)=nan; + av = cat_stat_nanmedian(a,3); + am = nanmedian(a,3); % of the statistical toolbox ... + fprintf('%0.4f %0.4f\n',([av(:),am(:)])'); + out = nanmean(av(:) - am(:)); + return; + end + + if nargin < 2 + if size(in,1) ~= 1 + dim = 1; + elseif size(in,2) ~= 1 + dim = 2; + else + dim = 3; + end; + end; + + if dim == 0 + in = in(:); + dim = 1; + end + + sz = size(in); + + if isempty(in), out = nan; return; end + tp = class(in); + in = double(in); % single failed in large arrays + + % reduce to 2d matrix + pm = [dim:max(length(size(in)),dim) 1:dim-1]; + in = reshape(permute(in,pm),size(in,dim),prod(sz)/size(in,dim)); + + in = sort(in,1); + s = size(in,1) - sum(isnan(in)); + + % estimate median in loop + out = zeros(size(s)); + for i = 1:length(s) + if s(i)>0, out(i) = cat_stat_nanmean([in(floor((s(i)+1)/2),i),in(ceil((s(i)+1)/2),i)]); else out(i)=nan; end + end + + % estimate median as matrix ... doesn't work :/ + %out = nan(size(s)); si=1:numel(s); + %out(s>0) = nanmean( [ in(([floor((s(s>0)+1)/2);si(s>0)])'); in(ceil((s(s>0)+1)/2),si(s>0)) ] ); + + % correct for permutation + sz(dim) = 1; out = ipermute(reshape(out,sz(pm)),pm); + + eval(sprintf('out = %s(out);',tp)); +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_io_mergeStruct.m",".m","2571","93","function S=cat_io_mergeStruct(S,SN,ri,id) +% _________________________________________________________________________ +% Merge to structures 'S' and 'SN'. +% +% S = cat_io_mergeStruct(S,SN[,[],id]) +% +% where id>0 updates elements S(id) +% +% WARNING: +% This function is still in developent! Be careful by using it, due to +% unexpected behaviour. Updating of structures is a complex topic with +% many subcases and here only a simple alignment is used! +% +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + % check input + maxri = 20; + if ~exist('id','var') || isempty(id), id=0; end + if ~exist('ri','var') || isempty(ri), ri=0; end + + SFN = fieldnames(S); + SNFN = fieldnames(SN); + + %% add new empty fields in additional element in S + NSFN = setdiff(SNFN,SFN); + if ~isempty(NSFN) + ne = numel(S)+1; + for ni = 1:numel(NSFN) + if isnumeric(SN(1).(NSFN{ni})) + S(ne).(NSFN{ni}) = []; + elseif islogical(SN(1).(NSFN{ni})) + S(ne).(NSFN{ni}) = false; + elseif ischar(SN(1).(NSFN{ni})) + S(ne).(NSFN{ni}) = ''; + elseif isstruct(SN(1).(NSFN{ni})) + if ri +%#ok<*INUSL> +%#ok<*INUSD> +%#ok<*TRYNC> + + + + +% we need to hide some options ... +expert = 2; %cat_get_defaults('extopts.expertgui'); +try + cat_get_defaults('print.dpi'); +catch + cat_get_defaults('print.dpi',150); +end +try + cat_get_defaults('print.type'); +catch + cat_get_defaults('print.type','.png'); +end + + + +%-Input parameters +%-------------------------------------------------------------------------- +if ~nargin, action = 'Disp'; end + +if ~ischar(action) + varargin = {action varargin{:}}; + action = 'Disp'; +end + +if nargout, varargout = {[]}; end + +%-Action +%-------------------------------------------------------------------------- +switch lower(action) + + %-Display + %====================================================================== + case 'disp' + if isempty(varargin) + [M, sts] = spm_select(1,'any','Select surface mesh file'); + if ~sts, return; end + varargin{1} = cellstr(M); + else + M = varargin{1}; + end + + + %% + %-Figure & Axis + %------------------------------------------------------------------ + O = getOptions(varargin{2:end}); + if isfield(O,'parent') + H.issubfigure = 1; + H.axis = O.parent; + H.figure = ancestor(H.axis,'figure'); + % this brings the figure to the foreground :/ + %figure(H.figure); axes(H.axis); + else + H.issubfigure = 0; + H.figure = figure('Color',[1 1 1]); + H.axis = axes('Parent',H.figure,'Visible','off'); + end + if isfield(O,'pcdata'), O.pcdata = cellstr(O.pcdata); end + if isfield(O,'pmesh'), O.pmesh = cellstr(O.pmesh); end + renderer = get(H.figure,'Renderer'); + + %{ + try + % warning to error + val = feval('set',H.figure,'Renderer','OpenGL'); + if isempty(val)==0 + error('OpenGLerr') + end + catch + cat_io_cprintf('err','OpenGL error - cannot display surface\n'); + return + end + %} + if ~isstruct(varargin{1}) && ~isa(varargin{1},'gifti') + % surface info + if nargin>=3 + sinfo = cat_surf_info(varargin{3}); + elseif nargin>=1 + if ischar(varargin{1}) + %% + for i=1:size(varargin{1},1) + [pp,ff,ee] = spm_fileparts(varargin{1}(i,:)); + varargin{1}(i,:) = fullfile(pp,[ff strrep(ee,'.dat','.gii')]); + end + else + for i=1:numel(varargin{1}) + [pp,ff,ee] = spm_fileparts(varargin{1}{i}); + varargin{1}{i} = fullfile(pp,[ff strrep(ee,'.dat','.gii')]); + end + end + sinfo = cat_surf_info(varargin{1}); + else + sinfo = cat_surf_info(M); + end + if ischar(varargin{1}) + sinfo(1).Pmesh = varargin{1}; + end + + %% + labelmap = zeros(0); labelnam = cell(0); labelmapclim = zeros(1,2); labeloid = zeros(0); labelid = zeros(0); nid=1; + for pi=1:numel(sinfo) + + if ~exist(sinfo(pi).fname,'file') + error('cat_surf_render:nofile','The file ""%s"" does not exist!',sinfo(pi).fname); + end + + H.filename{pi} = sinfo(pi).fname; + + % load mesh + [pp,ff,ee] = spm_fileparts(sinfo(pi).Pmesh); + switch ee + case '.gii' + S = gifti(sinfo(pi).Pmesh); + otherwise + S = gifti(cat_io_FreeSurfer('read_surf',sinfo(pi).Pmesh)); + end + + + if ~isfield(S,'cdata') && ~isempty(O) && isfield(O,'pcdata') + % load texture + [pp,ff,ee] = spm_fileparts(sinfo(pi).Pdata); + switch sinfo(pi).ee + case '.gii' + cdata = gifti(O.pcdata{pi}); + cdatap = export(cdata,'patch'); + if isfield(cdatap,'facevertexcdata') + cdata = cdatap.facevertexcdata; + elseif isfield(cdata,'cdata') + if isnumeric(cdata.cdata) + cdata = cdata.cdata; + else + fname = cdata.cdata.fname; + fid = fopen(fname, 'r', 'b') ; + if (fid < 0) + str = sprintf('could not open curvature file %s', fname) ; + error(str) ; + end + cdata = fread(fid, 'double') ; + fclose(fid); + + end + end + if isnumeric(cdata) + labelmapclim = [min(cdata) max(cdata)]; + else + if isfield(cdata,'cdata') + labelmapclim = [min(cdata.cdata) max(cdata.cdata)]; + elseif isfield(cdata,'vertices') + labelmapclim = [0 0]; + cdata = zeros(size(cdata.vertices,1),1,'single'); + else + labelmapclim = []; + cdata = []; + end + end + case '.annot' + %% + [fsv,cdatao,colortable] = cat_io_FreeSurfer('read_annotation',O.pcdata{pi}); clear fsv; + cdata = zeros(size(cdatao)); + entries = round(unique(cdatao)); + + for ei = 1:numel(entries) + cid = find( labeloid == entries(ei) ,1); % previous imported label? + if ~isempty(cid) % previous imported label + cdata( round(cdatao) == entries(ei) ) = labelid(cid); + else % new label > new entry + id = find( colortable.table(:,5)==entries(ei) , 1); + if ~isempty(id) + cdata( round(cdatao) == entries(ei) ) = nid; + labelmap(nid,:) = colortable.table(id,1:3)/255; + labelnam(nid) = colortable.struct_names(id); + labeloid(nid) = entries(ei); + labelid(nid) = nid; + labelmapclim(2) = nid; + nid = nid+1; + end + end + end + + otherwise + St = gifti(struct('cdata',cat_io_FreeSurfer('read_surf_data',sinfo(pi).Pdata))); + cdata = St.cdata; clear St; + labelmapclim = [min(cdata) max(cdata)]; + end + S.cdata = cdata; clear cdata; + S = export(S,'patch'); + elseif isfield(S,'cdata') + S = export(S,'patch'); + labelmapclim = [min(S.facevertexcdata) max(S.facevertexcdata)]; + end + % ignore this warning writing gifti with int32 (eg. cat_surf_createCS:580 > gifti/subsref:45) + warning off MATLAB:subscripting:noSubscriptsSpecified + % flip faces in case of defect surfaces + if mean(max(S.vertices + spm_mesh_normals(S)) - max(S.vertices))>0 + %if strcmp(sinfo(1).texture,'defects'), + S.faces = S.faces(:,[2,1,3]); + end + % use original colormap from annot file otherwise use jet + if ~strcmp(sinfo(pi).ee,'.annot') + labelmap = jet; + end + + + % Patch + % ---------------------------------------------------------- + P = struct('vertices',S.vertices, 'faces',double(S.faces)); + H.patch(pi) = patch(P,... + 'FaceColor', [0.6 0.6 0.6],... + 'EdgeColor', 'none',... + 'FaceLighting', 'gouraud',... + 'SpecularStrength', 0.0,... 0.7 + 'AmbientStrength', 0.4,... 0.1 + 'DiffuseStrength', 0.6,... 0.7 + 'SpecularExponent', 10,... + 'Clipping', 'off',... + 'DeleteFcn', {@myDeleteFcn, renderer},... + 'Visible', 'off',... + 'Tag', 'CATSurfRender',... + 'Parent', H.axis); + setappdata(H.patch(pi),'patch',P); + + %% -Label connected components of the mesh + %------------------------------------------------------------------ + C = spm_mesh_label(P); + setappdata(H.patch(pi),'cclabel',C); + + %-Compute mesh curvature + %------------------------------------------------------------------ + curv = spm_mesh_curvature(P); %$ > 0; + setappdata(H.patch(pi),'curvature',curv); + + %-Apply texture to mesh + %------------------------------------------------------------------ + if isfield(S,'cdata') + T = S.cdata; + elseif isfield(S,'facevertexcdata') + T = S.facevertexcdata; + else + T = []; + end + try + updateTexture(H,T,pi); + end + + H.cdata = T; % remove this later ... + clear S P; + end + H.sinfo = sinfo; + else + labelmap = jet; + if 0 %flip + S.vertices = [varargin{1}.vertices(:,2) varargin{1}.vertices(:,1) varargin{1}.vertices(:,3)]; + else + S.vertices = varargin{1}.vertices; + end + S.faces = varargin{1}.faces; + if isfield(varargin{1},'facevertexcdata'), S.cdata = varargin{1}.facevertexcdata; end + S = gifti(S); + S = export(S,'patch'); + warning off; + curv = spm_mesh_curvature(S); %$ > 0; + warning on; + + labelnam = cell(0); %labelmapclim = zeros(1,2); labeloid = zeros(0); labelid = zeros(0); nid=1; + P = struct('vertices',S.vertices, 'faces',double(S.faces)); + H.patch(1) = patch(P,... + 'FaceColor', [0.6 0.6 0.6],... + 'EdgeColor', 'none',... + 'FaceLighting', 'gouraud',... + 'SpecularStrength', 0.0,... 0.7 + 'AmbientStrength', 0.4,... 0.1 + 'DiffuseStrength', 0.6,... 0.7 + 'SpecularExponent', 10,... + 'Clipping', 'off',... + 'DeleteFcn', {@myDeleteFcn, renderer},... + 'Visible', 'off',... + 'Tag', 'CATSurfRender',... + 'Parent', H.axis); + setappdata(H.patch(1),'patch',P); + C = spm_mesh_label(P); + setappdata(H.patch(1),'cclabel',C); + setappdata(H.patch(1),'curvature',curv); + + if isfield(varargin{1},'cdata') + try + T = gifti(varargin{1}.cdata); + catch + T = gifti(varargin{1}); + end + T = T.cdata; + elseif isfield(varargin{1},'facevertexcdata') + try + T = gifti(varargin{1}.facevertexcdata); + catch + T = gifti(varargin{1}); + end + T = T.cdata; + else + T = []; + end + try + warning off; + updateTexture(H,T,1); + warning on; + catch + warning on; + end + labelmapclim = [min(T) max(T)]; + H.filename{1} = ''; + H.cdata = T; + sinfo = cat_surf_info(''); + H.sinfo = sinfo; + + if mean(max(S.vertices + spm_mesh_normals(S)) - max(S.vertices))>0 + %if strcmp(sinfo(1).texture,'defects'), + S.faces = S.faces(:,[2,1,3]); + end + %if strcmp(sinfo(1).texture,'defects'), S.faces = S.faces(:,[2,1,3]); end + end + + + %% -Set viewpoint, light and manipulation options + %------------------------------------------------------------------ + axis(H.axis,'image'); + axis(H.axis,'off'); + material(H.figure,'dull'); + + % default lighting + if 1 && ismac, H.catLighting = 'inner'; else H.catLighting = 'cam'; end + + + [caz,cel] = view; + H.light(1) = camlight('headlight','infinite'); + set(H.light(1),'Parent',H.axis,'Tag','camlight'); + switch H.catLighting + case 'inner' + % switch off local light (camlight) + set(H.light(1),'visible','off','parent',H.axis); + + % set inner light + H.light(2) = light('Position',[0 0 0],'parent',H.axis,'Tag','centerlight'); + for pi=1:numel(H.patch) + set(H.patch(pi),'BackFaceLighting','unlit'); + end + end + + + if ~H.issubfigure + H.rotate3d = rotate3d(H.axis); + set(H.rotate3d,'Enable','on'); + set(H.rotate3d,'ActionPostCallback',{@myPostCallback, H}); + end + + + %-Store handles + %------------------------------------------------------------------ + setappdata(H.axis,'handles',H); + for pi=1:numel(H.patch) + set(H.patch(pi),'Visible','on'); + setappdata(H.patch(pi),'clip',[false NaN NaN]); + end + + + for pi=1:numel(H.patch) + setappdata(H.patch(pi),'colourmap',labelmap); + end + try + cat_surf_render2('clim',H.axis,labelmapclim); % RD20221129: Sometimes problems in fast surfaces + end + colormap(labelmap); try caxis(labelmapclim); end + + if numel(labelnam)>0 + %% + H = cat_surf_render2('ColorBar',H.axis,'on'); + labelnam2 = [{''} labelnam]; for lni=1:numel(labelnam2),labelnam2{lni} = [' ' labelnam2{lni} ' ']; end + + labellength = min(100,max(cellfun('length',labelnam2))); + ss = max(1,round(diff(labelmapclim+1)/60)); + ytick = labelmapclim(1):ss:labelmapclim(2); + + set(H.colourbar,'ytick',ytick,'yticklabel',labelnam2(1:ss:end),... + 'Position',[max(0.75,0.98-0.008*labellength) 0.05 0.02 0.9]); + try, set(H.colourbar,'TickLabelInterpreter','none'); end + set(H.axis,'Position',[0.1 0.1 min(0.6,0.98-0.008*labellength - 0.2) 0.8]) + + H.labelmap = struct('colormap',labelmap,'ytick',ytick,'labelnam2',{labelnam2}); + setappdata(H.axis,'handles',H); + end + + + % annotation for colormap ... + %if ~H.issubfigure + % [pp,ff,ee] = fileparts(H.filename{1}); + % H.text = annotation('textbox','string',[ff ee],'position',[0.0,0.97,0.2,0.03],'LineStyle','none','Interpreter','none'); + %end + + + %-Add context menu + %------------------------------------------------------------------ + if ~isfield(O,'parent') + %try + cat_surf_render2('ContextMenu',H); + %end + end + + if strcmp(renderer,'painters') + + end + + % set default view + cat_surf_render2('view',H,[ 0 90]); + if numel(H.patch)==1 + if strcmp(H.sinfo(1).side,'lh'); cat_surf_render2('view',H,[ -90 0]); end + if strcmp(H.sinfo(1).side,'rh'); cat_surf_render2('view',H,[ 90 0]); end + %if strcmp(H.sinfo(1).side,'ch'); cat_surf_render2('view',H,[ 0 90]); end + end + + % remember this zoom level + axis vis3d; %zoom(1.15); + zoom reset + + + %-Context Menu + %====================================================================== + case 'contextmenu' + + if isempty(varargin), varargin{1} = gca; end + H = getHandles(varargin{1}); + sinfo1 = cat_surf_info(H.filename); + if ~isempty(get(H.patch(1),'UIContextMenu')), return; end + + cmenu = uicontextmenu('Callback',{@myMenuCallback, H}); + checked = {'off','on'}; + + + + + %% -- Textures -- + if ~isempty(sinfo1(1).fname) + c = uimenu(cmenu, 'Label', 'Textures'); + for pi=1:numel(sinfo1) + if sinfo1(pi).resampled + if sinfo1(pi).resampled_32k + tfiles = cat_vol_findfiles(sinfo1(pi).pp,sprintf('*%s.*.resampled_32k.%s*',sinfo1(pi).side,sinfo1(pi).name),struct('maxdepth',1)); + else + tfiles = cat_vol_findfiles(sinfo1(pi).pp,sprintf('*%s.*.resampled.%s*',sinfo1(pi).side,sinfo1(pi).name),struct('maxdepth',1)); + end + sfiles = {'.central.','.sphere.','.sphere.reg.','.hull.','.inflate.','.core.','.white.','.pial.','.inner.','.outer.','.annot.','.defects.','.layer4.'}; + for i=1:numel(sfiles) + tfiles(cellfun('isempty',strfind(tfiles,sfiles{i}))==0) = []; + end + else + tfiles = cat_vol_findfiles(sinfo1(pi).pp,sprintf('%s.*.%s*',sinfo1(pi).side,sinfo1(pi).name),struct('maxdepth',1)); + sfiles = {'.central.','.sphere.','.sphere.reg.','.hull.','.inflate.','.core.','.white.','.pial.','.inner.','.outer.','.annot.','.defects.','.toroGI.','.lGI.','.layer4.'}; + for i=1:numel(sfiles) + tfiles(cellfun('isempty',strfind(tfiles,sfiles{i}))==0) = []; + end + end + if pi==1, H.textures = cell(numel(tfiles),1+numel(sinfo1)); end + if numel(tfiles) + for i=1:numel(tfiles) + H.textures{i,1+pi} = cat_surf_info(tfiles{i}); + H.textures{i,1} = H.textures{i,1+pi}.dataname; + end + usetexture = cellfun('isempty',strfind(tfiles,H.filename{1}))==0; + else + usetexture = 0; + end + end + set(c,'UserData',H.textures); + uimenu(c, 'Label', 'Synchronise Views', 'Visible','off','Checked','off', 'Tag','SynchroMenu', 'Callback',{@mySynchroniseTexture, H}); + uimenu(c, 'Label','none', 'Interruptible','off','Separator','off','Checked',checked{2-any(usetexture)}, 'Callback',{@myChangeTexture, H}); + if strcmp(H.sinfo(1).texture,'defects'), set(c,'Enable','off'); end + if numel(tfiles) + uimenu(c, 'Label', H.textures{1,1},'Interruptible','off','Separator','on','Checked',checked{usetexture(1)+1},'Callback',{@myChangeTexture, H}); + for i=2:numel(tfiles) + uimenu(c, 'Label', H.textures{i,1},'Interruptible','off','Checked',checked{usetexture(i)+1},'Callback',{@myChangeTexture, H}); + end + end + uimenu(c, 'Label','Custom...', 'Interruptible','off','Separator','on', 'Callback',{@myUnderlay, H}); + + + + + %% -- Atlas textures --- + H.atlases = { + 'Neuromorphometrics' 'neuromorphometrics'; + 'LPBA40' 'lpba40'; + 'Hammers' 'hammers'; + 'Mori' 'mori'; + 'AAL' 'aal3'; + ... + 'DK40' 'aparc_DK40'; + ...'Destrieux2005' 'aparc_a2005s'; + 'Destrieux' 'aparc_a2009s'; + 'HCP multi-modal parcellation' 'aparc_HCP_MMP1'; + ...'FreeSurfer' 'aparc_freesurfer'; + ...'Bordmann' 'PALS_B12_Brodmann'; + ...'Lobes' 'PALS_B12_Lobes'; + }; + if expert>1 + vatlas = { + 'Neuromorphometrics' 'neuromorphometrics'; + 'LPBA40' 'lpba40'; + 'Hammers' 'hammers'; + 'Mori' 'mori'; + 'AAL' 'aal3'; + }; + satlas = { + 'DK40' 'aparc_DK40'; + 'Destrieux' 'aparc_a2009s'; + 'HCP multi-modal parcellation' 'aparc_HCP_MMP1'; + 'JuluchBrain3' 'JulichBrainAtlas_3.1'; + ...'Destrieux2005' 'aparc_a2005s'; + ...'Bordmann' 'PALS_B12_Brodmann'; + ...'FreeSurfer' 'aparc_freesurfer'; + ...'Lobes' 'PALS_B12_Lobes'; + }; + elseif expert==1 + vatlas = { + 'Neuromorphometrics' 'neuromorphometrics'; + 'LPBA40' 'lpba40'; + 'Hammers' 'hammers'; + 'Mori' 'mori'; + 'AAL' 'aal3'; + }; + satlas = { + 'DK40' 'aparc_DK40'; + 'Destrieux' 'aparc_a2009s'; + 'HCP multi-modal parcellation' 'aparc_HCP_MMP1'; + 'JuluchBrain3' 'JulichBrainAtlas_3.1'; + ...'Bordmann' 'PALS_B12_Brodmann'; + ...'Lobes' 'PALS_B12_Lobes'; + }; + else + vatlas = { + 'Neuromorphometrics' 'neuromorphometrics'; + 'LPBA40' 'lpba40'; + 'Hammers' 'hammers'; + }; + satlas = { + 'DK40' 'aparc_DK40'; + 'Destrieux' 'aparc_a2009s'; + 'HCP multi-modal parcellation' 'aparc_HCP_MMP1'; + 'JuluchBrain3' 'JulichBrainAtlas_3.1'; + }; + end + H.atlas.vatlas = vatlas; + H.atlas.satlas = satlas; + % ... it would be better to use the cat_defaults ... + %catatlases = cat_get_defaults('extopts.atlas'); + %for i=1:size(catatlases,1), + % [ppa,ffa] = spm_fileparts(catatlases{i,1}); + %end + + + if ~isempty(strfind(fileparts(sinfo1(1).Pmesh),'_32k')) + str32k = '_32k'; + else + str32k = ''; + end + + vafiles = vatlas(:,1); safiles = satlas(:,1); + for ai = 1:size(vatlas,1) + vafiles{ai} = fullfile(fileparts(mfilename('fullpath')),['atlases_surfaces' str32k],... + sprintf('%s.%s.%s',sinfo1(1).side,vatlas{ai,2},cat_get_defaults('extopts.shootingsurf'))); + end + for ai = 1:size(satlas,1) + safiles{ai} = fullfile(fileparts(mfilename('fullpath')),['atlases_surfaces' str32k],... + sprintf('%s.%s.freesurfer.annot',sinfo1(1).side,satlas{ai,2})); + end + ntextures = size(H.textures,1); + for i=1:size(satlas,1) + H.textures{ntextures + i,2} = cat_surf_info(safiles{i,1}); + H.textures{ntextures + i,1} = satlas{i,1}; %H.textures{ntextures + i,2}.dataname; + end + ntextures2 = size(H.textures,1); + for i = 1:size(vatlas,1) + H.textures{ntextures2 + i,2} = cat_surf_info(vafiles{i,1}); + H.textures{ntextures2 + i,1} = H.textures{ntextures2 + i,2}.dataname; + end + + useatlas = [zeros(ntextures,1); cellfun('isempty',strfind(safiles,H.filename{1}))==0]; + useatlas2 = [zeros(ntextures2,1); cellfun('isempty',strfind(vafiles,H.filename{1}))==0]; + + % atlas menu + if sinfo1(1).resampled || strcmp(sinfo1(1).ee,'.annot') + c = uimenu(cmenu, 'Label', 'Atlases'); + if strcmp(H.sinfo(1).texture,'defects'), set(c,'Enable','off'); end + uimenu(c, 'Label','none', 'Interruptible','off','Checked','off','Callback',{@myChangeTexture, H}); + uimenu(c, 'Label', H.textures{ntextures+1,1},'Interruptible','off',... + 'Checked',checked{useatlas2(ntextures+1)+1},'Separator','on','Callback',{@myChangeTexture, H}); + for i=ntextures + 2 : numel(useatlas) + uimenu(c, 'Label', H.textures{i,1},'Interruptible','off','Checked',checked{useatlas(i)+1},'Callback',{@myChangeTexture, H}); + end + uimenu(c, 'Label', H.textures{ntextures2+1,1},'Interruptible','off',... + 'Checked',checked{useatlas2(ntextures2+1)+1},'Separator','on','Callback',{@myChangeTexture, H}); + for i=ntextures2+2:size(H.textures,1) + uimenu(c, 'Label', H.textures{i,1},'Interruptible','off','Checked',checked{useatlas2(i)+1},'Callback',{@myChangeTexture, H}); + end + %uimenu(c, 'Label','Custom...', 'Interruptible','off','Separator','on', 'Callback',{@myUnderlay, H}); + end + + + + + %% -- ROIs -- + % ROI auswertung noch unklar + % - bei vols w?re das xml einer person mit verschiedenen atlaten + % (subject als auch subject template) + % >> auswahl von xml-files aus dem label dir? + % >> Liste von Atlanten und labels, die den atlasnamen enthalten, + % der aus dem atlasdir geladen werden (und gemappt werden) + % muss + % >> anschlie?end m?ssen die werte der rois auf den atlas + % ?bertragen werden + % - bei csv h?tte man dann einen atlas f?r mehrere personen, was + % nur bei resampled sinnvoll w?re + % >> auwahl von csv-files + try + % volume/surface-based atlas data + [mrifolder, reportfolder, surffolder, labelfolder] = cat_io_subfolders(sinfo1(1).fname); + if cat_get_defaults('extopts.subfolders') + labeldir = strrep(sinfo1(1).pp,[filesep surffolder],[filesep labelfolder]); + else + labeldir = sinfo1(1).pp; + end + % find xml-files + H.RBM.vlabelfile = cat_vol_findfiles(labeldir,sprintf('catROI_%s.xml',sinfo1(1).name),struct('maxdepth',1)); + H.RBM.slabelfile = cat_vol_findfiles(labeldir,sprintf('catROIs_%s.xml',sinfo1(1).name),struct('maxdepth',1)); + + % read xml-files ... this is realy slow for real XMLs >> MAT solution! + % atlas-names + % texture-names of volumen/surface ROIs + + if ~isempty(H.RBM.vlabelfile) + H.RBM.vcatROI = cat_io_xml( H.RBM.vlabelfile ); + H.RBM.vatlas = fieldnames( H.RBM.vcatROI ); + for ai=1:numel( H.RBM.vatlas ) + H.RBM.vmeasures{ai} = fieldnames( H.RBM.vcatROI.(H.RBM.vatlas{ai}).data ); + end + else + H.RBM.vatlas = []; + H.RBM.vmeasures = {}; + end + if ~isempty(H.RBM.slabelfile) + H.RBM.scatROI = cat_io_xml( H.RBM.slabelfile ); + H.RBM.satlas = fieldnames( H.RBM.scatROI ); + for ai=1:numel( H.RBM.satlas ) + H.RBM.smeasures{ai} = fieldnames( H.RBM.scatROI.(H.RBM.satlas{ai}).data ); + end + else + H.RBM.satlas = []; + H.RBM.smeasures = {}; + end + + + % create ROI data menu + c = uimenu(cmenu, 'Label', 'ROIs'); + % volume measures + uimenu(c, 'Label','none', 'Interruptible','off','Checked','off','Callback',{@myChangeTexture, H}); + for i=1:numel(H.RBM.vatlas)' + if i==1 + c1 = uimenu(c, 'Label', H.RBM.vatlas{i},'Checked','off','Separator','on'); + else + c1 = uimenu(c, 'Label', H.RBM.vatlas{i},'Checked','off'); + end + for j=1:numel(H.RBM.vmeasures{i}) + uimenu(c1, 'Label', H.RBM.vmeasures{i}{j},'Checked','off','Callback',{@myChangeROI, H}); + end + end + % surface measures + for i=1:numel(H.RBM.satlas) + if i==1 + c1 = uimenu(c, 'Label', H.RBM.satlas{i},'Checked','off','Separator','on'); + else + c1 = uimenu(c, 'Label', H.RBM.satlas{i},'Checked','off'); + end + for j=1:numel(H.RBM.smeasures{i}) + uimenu(c1, 'Label', H.RBM.smeasures{i}{j},'Checked','off','Callback',{@myChangeROI, H}); + end + end + % custom ... + % * find further xml files of this subject in the label directory (easy) + % or load a custom ROI where you have to choose the atlas and measure or where you have to create a dynamic menu ... :/ + % * load them and get their atlas fields and for each atlas its measures + % * create a 'other ROIs' menu with subfields for each measure + %uimenu(c, 'Label','Custom...', 'Interruptible','off','Separator','on', 'Callback',{@myChangeROI, H}); + + end + + %% -- Meshes -- + c = uimenu(cmenu, 'Label', 'Meshes'); + if strcmp(H.sinfo(1).texture,'defects'), set(c,'Enable','off'); end + if sinfo1(1).resampled + if ~isempty(strfind(fileparts(sinfo1(1).Pmesh),'_32k')) + str32k = '_32k'; + else + str32k = ''; + end + H.meshs = { + 'Central' ; 'Pial' ; 'White' ; 'Layer4' ; 'Hull' ; ... + 'Average' ; 'Inflated' ; 'Shooting' ; 'Sphere' ; 'Custom' }; + for i=1:numel(H.patch) + H.meshs = [ H.meshs , { + H.patch(i).Vertices; + fullfile(sinfo1(i).pp,[sinfo1(1).side '.pial.resampled.' sinfo1(i).name '.gii']); + fullfile(sinfo1(i).pp,[sinfo1(1).side '.white.resampled.' sinfo1(i).name '.gii']); + fullfile(sinfo1(i).pp,[sinfo1(1).side '.layer4.resampled.' sinfo1(i).name '.gii']); + fullfile(sinfo1(i).pp,[sinfo1(1).side '.hull.resampled.' sinfo1(i).name '.gii']); + fullfile(fileparts(mfilename('fullpath')),['templates_surfaces' str32k],[sinfo1(i).side '.central.freesurfer.gii']); + fullfile(fileparts(mfilename('fullpath')),['templates_surfaces' str32k],[sinfo1(i).side '.inflated.freesurfer.gii']); + fullfile(fileparts(mfilename('fullpath')),['templates_surfaces' str32k],[sinfo1(i).side '.central.' cat_get_defaults('extopts.shootingsurf') '.gii']); + fullfile(fileparts(mfilename('fullpath')),['templates_surfaces' str32k],[sinfo1(i).side '.sphere.freesurfer.gii']); + ''; + }]; + end + + + uimenu(c, 'Label','Central', 'Checked','on', 'Callback',{@myChangeMesh, H}); + uimenu(c, 'Label','Pial', 'Checked','off', 'Callback',{@myChangeMesh, H},'Enable',checked{1+(exist(H.meshs{2,2},'file')>1)}); + uimenu(c, 'Label','White', 'Checked','off', 'Callback',{@myChangeMesh, H},'Enable',checked{1+(exist(H.meshs{3,2},'file')>1)}); + uimenu(c, 'Label','Layer4', 'Checked','off', 'Callback',{@myChangeMesh, H},'Enable',checked{1+(exist(H.meshs{4,2},'file')>1)}); + uimenu(c, 'Label','Hull', 'Checked','off', 'Callback',{@myChangeMesh, H},'Enable',checked{1+(exist(H.meshs{5,2},'file')>1)}); + uimenu(c, 'Label','Average', 'Checked','off', 'Callback',{@myChangeMesh, H},'Separator','on'); + uimenu(c, 'Label','Inflated', 'Checked','off', 'Callback',{@myChangeMesh, H}); + uimenu(c, 'Label','Dartel', 'Checked','off', 'Callback',{@myChangeMesh, H}); + uimenu(c, 'Label','Sphere', 'Checked','off', 'Callback',{@myChangeMesh, H}); + %uimenu(c, 'Label','Sphere', 'Checked','off', 'Callback',{@myChangeMesh, H},'Separator',1); + else + H.meshs = { 'Central'; 'Pial' ; 'White' ; 'Layer4' ; 'Hull' ; 'Core' ; 'Sphere' ; 'Custom' }; + for i=1:numel(H.patch) + H.meshs = [ H.meshs , { + H.patch(i).Vertices; + ...'Inflated' , fullfile(fileparts(mfilename('fullpath')),'templates_surfaces',[sinfo1(1).side '.inflated.freesurfer.gii']); + sinfo1(i).Ppial; + sinfo1(i).Pwhite; + sinfo1(i).Player4 + sinfo1(i).Phull; + sinfo1(i).Pcore; + sinfo1(i).Psphere; + ''; + }]; + end + uimenu(c, 'Label','Central', 'Checked','on', 'Callback',{@myChangeMesh, H},'Enable',checked{1+(exist(sinfo1(1).Pmesh,'file')>1)}); + %uimenu(c, 'Label','Inflated', 'Checked','off', 'Callback',{@myChangeMesh, H},'Enable',checked{1+(exist(sinfo1(1).Pmesh,'file')>1)}); + uimenu(c, 'Label','Pial', 'Checked','off', 'Callback',{@myChangeMesh, H},'Enable',checked{1+(exist(sinfo1(1).Ppial,'file')>1)}); + uimenu(c, 'Label','White', 'Checked','off', 'Callback',{@myChangeMesh, H},'Enable',checked{1+(exist(sinfo1(1).Pwhite,'file')>1)}); + uimenu(c, 'Label','Layer4', 'Checked','off', 'Callback',{@myChangeMesh, H},'Enable',checked{1+(exist(sinfo1(1).Player4,'file')>1)}); + uimenu(c, 'Label','Hull', 'Checked','off', 'Callback',{@myChangeMesh, H},'Enable',checked{1+(exist(sinfo1(1).Phull,'file')>1)}); + uimenu(c, 'Label','Core', 'Checked','off', 'Callback',{@myChangeMesh, H},'Enable',checked{1+(exist(sinfo1(1).Pcore,'file')>1)}); + uimenu(c, 'Label','Sphere', 'Checked','off', 'Callback',{@myChangeMesh, H},'Enable',checked{1+(exist(sinfo1(1).Psphere,'file')>1)}); +% uimenu(c, 'Label','Checkreg', 'Checked','off', 'Callback',{@myCheckreg, H},'Separator',1); + end + uimenu(c, 'Label','Custom...', 'Interruptible','off', 'Separator','on', 'Callback',{@myChangeGeometry, H}); + end + + + % -- Components -- + % this is a nice idea ... I need name the patches + c = uimenu(cmenu, 'Label', 'Connected Components', 'Interruptible','off'); + if strcmp(H.sinfo(1).texture,'defects'), set(c,'Enable','off'); end + C = getappdata(H.patch(1),'cclabel'); + for i=1:length(unique(C)) + uimenu(c, 'Label',sprintf('Component %d',i), 'Checked','on', ... + 'Callback',{@myCCLabel, H}); + end + + + + if ~isempty(sinfo1(1).fname) + % Volume menu + % ----------------------------------------------------------------- + c = uimenu(cmenu, 'Label','Volume', 'Interruptible','off'); %, 'Callback',{@myImageSections, H}); + % -- image --- + [mrifolder, reportfolder, surffolder, labelfolder] = cat_io_subfolders(sinfo1(1).fname); + if cat_get_defaults('extopts.subfolders') + labeldir = strrep(sinfo1(1).pp,[filesep surffolder],[filesep mrifolder]); + else + labeldir = sinfo1(1).pp; + end + % find nii-files + if exist(labeldir,'dir') + H.niftis = [ ... + cat_vol_findfiles(labeldir,sprintf('m%s.nii',sinfo1(1).name),struct('maxdepth',1)); + cat_vol_findfiles(labeldir,sprintf('mi%s.nii',sinfo1(1).name),struct('maxdepth',1)); + cat_vol_findfiles(labeldir,sprintf('p*%s.nii',sinfo1(1).name),struct('maxdepth',1)); + ]; + else + H.niftis = []; + end + + if sinfo1(1).resampled && exist(labeldir,'dir') + H.niftis = [H.niftis; cat_vol_findfiles(labeldir,sprintf('*%s.nii',sinfo1(1).name),struct('maxdepth',1))]; + end + H.niftis = unique( H.niftis ); + H.niftis = [H.niftis H.niftis]; + for i=1:size(H.niftis,1) + [pp,ff,ee] = spm_fileparts(H.niftis{i,1}); + H.niftis{i,1} = strrep(ff,sinfo1(1).name,''); + end + + c1 = uimenu(c, 'Label','Volume selection'); + uimenu(c1, 'Label','none','Interruptible','off', 'Callback',{@myImageSections, H,'none'}); %,'Checked','on'); + for i=1:size(H.niftis,1) + uimenu(c1, 'Label',H.niftis{i,1},'Interruptible','off', 'Callback',{@myImageSections, H,'none'}, 'Separator',checked{1+(i==1)}); + end + uimenu(c1, 'Label','Custom ...', 'Interruptible','off','Separator',checked{1+(size(H.niftis,1)>1)},'Callback',... + {@myImageSections, H,strrep(H.filename{1},[filesep 'surf' filesep],[filesep 'mri' filesep])}); + +%{ + * Intensity changes influence surface colormap :/ + * interaction between colormap and transparency map + * data handling ... caxis + + % -- Intensity -- + c1 = uimenu(c, 'Label','Intensity range'); + uimenu(c1, 'Label','Min-max' , 'Checked','off', 'Callback', {@myVolCaxis, H, 'auto'}); + uimenu(c1, 'Label','2-98 %' , 'Checked','off', 'Callback', {@myVolCaxis, H, '2p'}); + uimenu(c1, 'Label','5-95 %' , 'Checked','off', 'Callback', {@myVolCaxis, H, '5p'}); + uimenu(c1, 'Label','Custom...' , 'Checked','off', 'Callback', {@myVolCaxis, H, 'custom'},'Separator', 'on'); + uimenu(c1, 'Label','Custom %...', 'Checked','off', 'Callback', {@myVolCaxis, H, 'customp'}); + % -- Colormap --- + % ... similar menu to surface ... LATER + + % -- Transparency -- + c1 = uimenu(c, 'Label','Transparency range'); + uimenu(c1, 'Label','Full' , 'Checked','on', 'Callback', {@myVolTransparency, H, 'auto'}); + uimenu(c1, 'Label','Background' , 'Checked','off', 'Callback', {@myVolTransparency, H, 'background'}); + uimenu(c1, 'Label','Custom...' , 'Checked','off', 'Callback', {@myVolTransparency, H, 'custom'},'Separator', 'on'); +%} + + % -- Slice -- ... more than one slice per direction? + c1 = uimenu(c, 'Label','Slices'); + uimenu(c1, 'Label','AC' , 'Interruptible','off', 'Callback',{@mySlices, H, 'AC'},'Checked','on'); + uimenu(c1, 'Label','x+10' , 'Interruptible','off', 'Callback',{@mySlices, H, 'x+10'},'Separator', 'on'); + uimenu(c1, 'Label','x-10' , 'Interruptible','off', 'Callback',{@mySlices, H, 'x-10'}); + uimenu(c1, 'Label','y+10' , 'Interruptible','off', 'Callback',{@mySlices, H, 'y+10'}); + uimenu(c1, 'Label','y-10' , 'Interruptible','off', 'Callback',{@mySlices, H, 'y-10'}); + uimenu(c1, 'Label','z+10' , 'Interruptible','off', 'Callback',{@mySlices, H, 'z+10'}); + uimenu(c1, 'Label','z-10' , 'Interruptible','off', 'Callback',{@mySlices, H, 'z-10'}); + uimenu(c1, 'Label','Custom...' , 'Interruptible','off', 'Callback',{@mySlices, H},'Separator', 'on'); + uimenu(c1, 'Label','Custom mm...' , 'Interruptible','off', 'Callback',{@mySlices, H, 'mm'}); + end + + % ??? + uimenu(cmenu, 'Label','Overlay...', 'Interruptible','off', 'Callback',{@myOverlay, H}); + ind_finite = (isfinite(H.cdata)); + %% + for i=1:numel(H.patch) + sV(i) = size(H.patch(i).Vertices,1); + sF(i) = size(H.patch(i).Faces,1); + EC(i) = size(H.patch(i).Vertices,1) + size(H.patch(i).Faces,1) - ... + size(spm_mesh_edges(struct('vertices',H.patch(i).Vertices','faces',H.patch(i).Faces)),1); + end + c1 = uimenu(cmenu, 'Label','Surface Information'); + uimenu(c1, 'Label', sprintf('Dir: %s' ,spm_str_manip(sinfo1(1).pp, 'a40'))); + uimenu(c1, 'Label', sprintf('File: %s' ,spm_str_manip(sinfo1(1).name,'a40'))); + uimenu(c1, 'Label', sprintf('Side: %s' ,sinfo1(1).side)); + uimenu(c1, 'Label', sprintf('Vertices: %s',sprintf('%0.0f ',sV)), 'Interruptible','off','Separator','on'); + uimenu(c1, 'Label', sprintf('Faces: %s',sprintf('%0.0f ',sF)), 'Interruptible','off'); + uimenu(c1, 'Label', sprintf('Euler Number: %s' ,sprintf('%d ',EC)), 'Interruptible','off'); + if isfield(H,'cdata') + uimenu(c1, 'Tag','SurfDataMenu1','Interruptible','off','Label',sprintf('Data: %s\n',''),'Separator','on'); + uimenu(c1, 'Tag','SurfDataMenu2','Interruptible','off','Label',sprintf(' median: %0.4f\n',median(H.cdata(ind_finite))),'Separator','on'); + uimenu(c1, 'Tag','SurfDataMenu3','Interruptible','off','Label',sprintf(' mean %s std: %0.4f %s %0.4f\n',... + char(177),mean(H.cdata(ind_finite)),char(177),std(H.cdata(ind_finite)))); + uimenu(c1, 'Tag','SurfDataMenu4','Interruptible','off','Label',sprintf(' min / max: %0.4f / %0.4f',min(H.cdata(ind_finite)),max(H.cdata(ind_finite)))); + end + uimenu(c1, 'Label', 'Histogram', 'Interruptible','off','Separator','on','Callback',{@myHist, H}); + uimenu(c1, 'Label', sprintf('Dir: %s' ,spm_str_manip(sinfo1(1).pp, 'a40'))); + %% + % Inflation off ... to slow and unimportant + % uimenu(cmenu, 'Label','Inflate', 'Interruptible','off', 'Callback',{@myInflate, H}); + + + + %% ---------------------------------------------------------------- + + + + % -- Views -- + c = uimenu(cmenu, 'Label','View','Separator','on'); + uimenu(c, 'Label', 'Synchronise Views Once', 'Visible','off','Checked','off', 'Tag','SynchroMenu', 'Callback',{@mySynchroniseViewsOnce, H}); + uimenu(c, 'Label', 'Synchronise Views', 'Visible','off','Checked','off', 'Tag','SynchroMenu', 'Callback',{@mySynchroniseViews, H}); + uimenu(c, 'Label','Zoom in' , 'Checked' ,'off', 'Callback',{@myZoom, H,'zoom in'}); + uimenu(c, 'Label','Zoom out' , 'Checked' ,'off', 'Callback',{@myZoom, H,'zoom out'}); + uimenu(c, 'Label', 'Right', 'Callback', {@myView, H, [90 0]},'Separator','on'); + uimenu(c, 'Label', 'Left', 'Callback', {@myView, H, [-90 0]}); + uimenu(c, 'Label', 'Top', 'Callback', {@myView, H, [0 90]}); + uimenu(c, 'Label', 'Bottom', 'Callback', {@myView, H, [-180 -90]}); + uimenu(c, 'Label', 'Front', 'Callback', {@myView, H, [-180 0]}); + uimenu(c, 'Label', 'Back', 'Callback', {@myView, H, [0 0]}); + + + + + % -- Colormaps -- + c = uimenu(cmenu, 'Label','Colormap'); + % only limited version ... + % clrmp = {'hot' 'jet' 'gray' 'hsv' 'bone' 'copper' 'pink' 'white' ... + % 'flag' 'lines' 'colorcube' 'prism' 'cool' 'autumn' 'spring' 'winter' 'summer'}; + clrmp = {'jet' 'turbo' 'hsv' 'hot' 'winter' 'summer' 'pink' 'gray'}; + uimenu(c, 'Label','Colorbar','Checked','off', 'Callback', {@myColourbar, H}); + uimenu(c, 'Label','Invert Colormap','Checked','off', 'Callback', {@myInvColourmap, H}); + for i=1:numel(clrmp) + if i==1 + uimenu(c, 'Label', clrmp{i}, 'Checked','off', 'Callback', {@myColourmap, H}, 'Separator', 'on'); + else + uimenu(c, 'Label', clrmp{i}, 'Checked','off', 'Callback', {@myColourmap, H}); + end + end + % some further own colormaps + clrmp = {'CAThot','CATcold','CATtissues','CATcold&hot'}; + for i=1:numel(clrmp) + if i==1 + uimenu(c, 'Label', clrmp{i}, 'Checked','off', 'Callback', {@myColourmap, H}, 'Separator', 'on'); + else + uimenu(c, 'Label', clrmp{i}, 'Checked','off', 'Callback', {@myColourmap, H}); + end + end + % custom does not work, as far as I can not update from the + % colormapeditor yet + %uimenu(c, 'Label','Custom...' , 'Checked','off', 'Callback', {@myColourmap, H, 'custom'}, 'Separator', 'on'); + + + + % -- Colorrange -- + c = uimenu(cmenu, 'Label','Colorrange'); + uimenu(c, 'Label','Synchronise colorranges', 'Visible','on', ... + 'Checked','off', 'Tag','SynchroMenu', 'Callback',{@mySynchroniseCaxis, H}); + uimenu(c, 'Label','Min-max' , 'Checked','off', 'Callback', {@myCaxis, H, 'auto'},'Separator', 'on'); + uimenu(c, 'Label','0-100%' , 'Checked','off', 'Callback', {@myCaxis, H, '0p'}); + uimenu(c, 'Label','1-99 %' , 'Checked','off', 'Callback', {@myCaxis, H, '1p'}); + uimenu(c, 'Label','2-98 %' , 'Checked','off', 'Callback', {@myCaxis, H, '2p'}); + uimenu(c, 'Label','5-95 %' , 'Checked','off', 'Callback', {@myCaxis, H, '5p'}); + uimenu(c, 'Label','Thickness 0.5 - 5 mm' , 'Checked','off', 'Callback', {@myCaxis, H, [0.5 5]},'Separator', 'on'); + uimenu(c, 'Label','Thickness 0.0 - 6 mm' , 'Checked','off', 'Callback', {@myCaxis, H, [0 6]},'Separator', 'off'); + uimenu(c, 'Label','Custom...' , 'Checked','off', 'Callback', {@myCaxis, H, 'custom'},'Separator', 'on'); + uimenu(c, 'Label','Custom %...', 'Checked','off', 'Callback', {@myCaxis, H, 'customp'}); + + + + % -- Lighting -- + c = uimenu(cmenu, 'Label','Lighting'); + macon = {'on' 'off'}; isinner = strcmp(H.catLighting,'inner'); + isouter = strcmp(H.catLighting,'outer'); + uimenu(c, 'Label','Cam', 'Checked',macon{isinner+1}, 'Callback', {@myLighting, H,'cam'}); + if ismac %&& ~strcmp(H.sinfo(1).texture,'defects') + uimenu(c, 'Label','Inner', 'Checked',macon{2-isinner}, 'Callback', {@myLighting, H,'inner'}); + uimenu(c, 'Label','Outer', 'Checked',macon{2-isouter}, 'Callback', {@myLighting, H,'outer'}); + end + uimenu(c, 'Label','Set1', 'Checked','off', 'Callback', {@myLighting, H,'set1'}, 'Separator', 'on'); + uimenu(c, 'Label','Set2', 'Checked','off', 'Callback', {@myLighting, H,'set2'}); + uimenu(c, 'Label','Set3', 'Checked','off', 'Callback', {@myLighting, H,'set3'}); + if 0 % expert + uimenu(c, 'Label','Top', 'Checked','off', 'Callback', {@myLighting, H,'top'}, 'Separator', 'on'); + uimenu(c, 'Label','Bottom', 'Checked','off', 'Callback', {@myLighting, H,'bottom'}); + uimenu(c, 'Label','Left', 'Checked','off', 'Callback', {@myLighting, H,'left'}); + uimenu(c, 'Label','Right', 'Checked','off', 'Callback', {@myLighting, H,'right'}); + uimenu(c, 'Label','Front', 'Checked','off', 'Callback', {@myLighting, H,'front'}); + uimenu(c, 'Label','Back', 'Checked','off', 'Callback', {@myLighting, H,'back'}); + end + uimenu(c, 'Label','Brighter', 'Checked','off', 'Callback', {@myLighting, H,'brighter'},'Separator', 'on'); + uimenu(c, 'Label','Darker', 'Checked','off', 'Callback', {@myLighting, H,'darker'}); + uimenu(c, 'Label','None', 'Checked','off', 'Callback', {@myLighting, H,'none'},'Separator', 'on'); + + + + % -- Material -- + c = uimenu(cmenu, 'Label','Material'); + uimenu(c, 'Label','Dull', 'Checked','on', 'Callback', {@myMaterial, H,'dull'}); + uimenu(c, 'Label','Shiny', 'Checked','off', 'Callback', {@myMaterial, H,'shiny'}); + uimenu(c, 'Label','Metalic', 'Checked','off', 'Callback', {@myMaterial, H,'metallic'}); + uimenu(c, 'Label','Edges', 'Checked','off', 'Callback', {@myGrid, H,'grid'}, 'Separator', 'on'); + if expert + uimenu(c, 'Label','Custom...','Checked','off', 'Callback', {@myMaterial, H,'custom'}, 'Separator', 'on'); + end + + + % -- Transparency -- + if expert + c = uimenu(cmenu, 'Label','Transparency'); tlevel = 0:20:80; + uimenu(c, 'Label','TextureTransparency', 'Checked','off', 'Callback', {@myTextureTransparency, H}); + uimenu(c, 'Label',sprintf('%0.0f%%',tlevel(1)), 'Checked','on', 'Callback', {@myTransparency, H}, 'Separator', 'on'); + for ti=2:numel(tlevel) + uimenu(c, 'Label',sprintf('%0.0f%%',tlevel(ti)), 'Checked','off', 'Callback', {@myTransparency, H}); + end + else + uimenu(cmenu, 'Label','TextureTransparency', 'Checked','off', 'Callback', {@myTextureTransparency, H}); + end + + + + % -- Background Color -- + c = uimenu(cmenu, 'Label','Background Color'); + uimenu(c, 'Label','White', 'Checked','on', 'Callback', {@myBackgroundColor, H, [1 1 1]}); + uimenu(c, 'Label','Black', 'Checked','off', 'Callback', {@myBackgroundColor, H, [0 0 0]}); + uimenu(c, 'Label','Custom...', 'Checked','off', 'Callback', {@myBackgroundColor, H, []},'Separator', 'on'); + + + + % -- Interaction -- + c = uimenu(cmenu, 'Label','Interaction'); + %{ + % pan and zoom have there own menu! + uimenu(c, 'Label','Zoom' , 'Callback' , {@myZoom, H,'zoom'},'Separator', 'on'); + uimenu(c, 'Label','Pan' , 'Checked' ,'off', 'Callback',{@myPan,H}); + %} + uimenu(c, 'Label','Rotate' , 'Checked' ,'on' , 'Callback',{@mySwitchRotate, H}); + uimenu(c, 'Label','Data Cursor', 'Callback', {@myDataCursor, H}); + uimenu(c, 'Label','Slider', 'Callback', {@myAddslider, H}); + + if expert + uimenu(c, 'Label','ToolBar', 'Callback', {@myToolBar, H},'Separator', 'on'); + end + + %% ---------------------------------------------------------------- + + + % print resolution + if expert + c = uimenu(cmenu, 'Label','Print resolution','Separator', 'on'); + printres = [75 150 300 600]; + onoff = {'off','on'}; + myprintres = cat_get_defaults('print.dpi'); + if isempty(myprintres), myprintres = 150; end + myres = printres==myprintres; + for ri = 1:numel(printres) + uimenu(c, 'Label',sprintf('%0.0f',printres(ri)), 'Checked',onoff{myres(ri)+1},... + 'Callback', {@myPrintResolution, H, printres(ri)}); + end + % print + uimenu(cmenu, 'Label','Save As...', 'Callback', {@mySavePNG, H}); + else + % print + uimenu(cmenu, 'Label','Save As...','Separator', 'on', 'Callback', {@mySavePNG, H}); + end + + + + try set(H.rotate3d,'enable','off'); end + try set(H.rotate3d,'uicontextmenu',cmenu); end + try set(H.patch(1),'uicontextmenu',cmenu); end + try set(H.rotate3d,'enable','on'); end + + dcm_obj = datacursormode(H.figure); + set(dcm_obj, 'Enable','off', 'SnapToDataVertex','on', ... + 'DisplayStyle','datatip', 'Updatefcn',{@myDataCursorUpdate, H}); + + %-printresolution + %====================================================================== + case 'printresolution' + if isempty(varargin), varargin{1} = gca; end + H = getHandles(varargin{1}); + cat_get_defaults('print.dpi',varargin{3}); + + %-View + %====================================================================== + case 'view' + if numel(varargin)<2, varargin{2} = varargin{1}; varargin{1} = gca; end + H = getHandles(varargin{1}); + if isnumeric(varargin{2}) + myView([],[],H,varargin{2}); + else + switch lower(varargin{2}) + case {'r','right'} + myView([],[],H,[ 90 0]); + case {'l','left' } + myView([],[],H,[ -90 0]); + case {'t','top','i','inferior'} + myView([],[],H,[ 0 90]); + case {'bo','bottom','s','superior'} + myView([],[],H,[-180 -90]); + case {'f','front','a','anterior'} + myView([],[],H,[-180 0]); + case {'ba','back','p','posterior'} + myView([],[],H,[ 0 0]); + otherwise + error('cat_surf_render2:view:unknownView',... + ['Unknown view ""%s"". Use MATLAB view vektor (e.g., [90,0]) or one of the following keywords: \n' ... + '""left"", ""right"", ""top"", ""bottom"", ""front"", ""back"".'],... + varargin{2}); + end + end + + %-SaveAs + %====================================================================== + case 'saveas' + if isempty(varargin), varargin{1} = gca; end + H = getHandles(varargin{1}); + mySavePNG(H.patch(1),[],H, varargin{2}); + + %-Underlay + %====================================================================== + case 'underlay' + if isempty(varargin), varargin{1} = gca; end + H = getHandles(varargin{1}); + if nargin < 3, varargin{2} = []; end + + v = varargin{2}; + if ischar(v) + [p,n,e] = fileparts(v); + if ~strcmp(e,'.mat') && ~strcmp(e,'.nii') && ~strcmp(e,'.gii') && ~strcmp(e,'.img') % freesurfer format + v = cat_io_FreeSurfer('read_surf_data',v); + else + try spm_vol(v); catch, v = gifti(v); end; + end + end + if isa(v,'gifti') + v = v.cdata; + end + + for pi=1:numel(H.patch) + setappdata(H.patch(pi),'curvature',v); + end + setappdata(H.axis,'handles',H); + for pi=1:numel(H.patch) + d = getappdata(H.patch(pi),'data'); + updateTexture(H,d,pi); + end + + %-Overlay + %====================================================================== + case 'overlay' + if isempty(varargin), varargin{1} = gca; end + H = getHandles(varargin{1}); + if nargin < 3, varargin{2} = []; end + for pi=1:numel(H.patch) + updateTexture(H,varargin{2:end},pi); + end + + + %-Slices + %====================================================================== + case 'slices' + if isempty(varargin), varargin{1} = gca; end + H = getHandles(varargin{1}); + if nargin < 3, varargin{2} = []; end + renderSlices(H,varargin{2:end}); + + %-Material + %====================================================================== + case 'material' + if isempty(varargin), varargin{1} = gca; end + H = getHandles(varargin{1}); + + %-Lighting + %====================================================================== + case 'lighting' + if isempty(varargin), varargin{1} = gca; end + H = getHandles(varargin{1}); + + %-ColourBar + %====================================================================== + case {'colourbar', 'colorbar'} + if isempty(varargin), varargin{1} = gca; end + if length(varargin) == 1, varargin{2} = 'on'; end + H = getHandles(varargin{1}); + d = getappdata(H.patch(1),'data'); + col = getappdata(H.patch(1),'colourmap'); + if strcmpi(varargin{2},'off') + if isfield(H,'colourbar') && ishandle(H.colourbar) + %set(H.colourbar,'visible','off') + set(H.axis,'Position',[0.10 0.10 0.8 0.8]); + delete(H.colourbar); + H = rmfield(H,'colourbar'); + setappdata(H.axis,'handles',H); + end + return; + end + %{ + if strcmpi(varargin{2},'on') + if isfield(H,'colourbar') && ishandle(H.colourbar) + set(H.colourbar,'visible','on') + labelnam2 = get(H.colourbar,'yticklabel'); + labellength = min(100,max(cellfun('length',labelnam2))); + set(H.axis,'Position',[0.03 0.03 min(0.94,0.98-0.008*labellength - 0.06) 0.94]) + return + end + end + %} + if nargout && (isempty(d) || ~any(d(:))), varargout = {H}; return; end + if isempty(col), col = hot(256); end + if ~isfield(H,'colourbar') || ~ishandle(H.colourbar) + H.colourbar = colorbar('peer',H.axis); %'EastOutside'); + set(H.colourbar,'Tag','','Position',[.93 0.2 0.02 0.6]); + set(get(H.colourbar,'Children'),'Tag',''); + end + c(1:size(col,1),1,1:size(col,2)) = col; + ic = findobj(H.colourbar,'Type','image'); + clim = getappdata(H.patch(1), 'clim'); + if isempty(clim), clim = [false NaN NaN]; end + + % Update colorbar colors if clipping is used + clip = getappdata(H.patch(1), 'clip'); + if ~isempty(clip) + if ~isnan(clip(2)) && ~isnan(clip(3)) + ncol = length(col); + col_step = (clim(3) - clim(2))/ncol; + cmin = max([1,ceil((clip(2)-clim(2))/col_step)]); + cmax = min([ncol,floor((clip(3)-clim(2))/col_step)]); + col(cmin:cmax,:) = repmat([0.5 0.5 0.5],(cmax-cmin+1),1); + c(1:size(col,1),1,1:size(col,2)) = col; + end + end + if 0% size(d,1) > 1 + set(ic,'CData',c(1:size(d,1),:,:)); + set(ic,'YData',[1 size(d,1)]); + set(H.colourbar,'YLim',[1 size(d,1)]); + set(H.colourbar,'YTickLabel',[]); + else + set(ic,'CData',c); + clim = getappdata(H.patch(1),'clim'); + if isempty(clim), clim = [false min(d) max(d)]; end + if clim(3) > clim(2) + set(ic,'YData',clim(2:3)); + set(H.colourbar,'YLim',clim(2:3)); + end + end + + objatlases = findobj(H.patch(1),'Label','Atlases'); + if isfield(H,'labelmap') && ~isempty(findobj(get(objatlases,'children'),'Checked','on')) + labellength = min(100,max(cellfun('length',H.labelmap.labelnam2))); + ss = diff(H.labelmap.ytick(1:2)); + set(H.colourbar,'ytick',H.labelmap.ytick,'yticklabel',H.labelmap.labelnam2(1:ss:end),... + 'Position',[max(0.75,0.98-0.008*labellength) 0.05 0.02 0.9]); + try, set(H.colourbar,'TickLabelInterpreter','none'); end + set(H.axis,'Position',[0.1 0.1 min(0.6,0.98-0.008*labellength - 0.2) 0.8]) + else +% % delete old colorbar +% set(H.axis,'Position',[0.10 0.10 0.8 0.8]); +% setappdata(H.axis,'handles',H); +% %delete(H.colourbar); +% %H = rmfield(H,'colourbar'); +% +% +% if 0 +% H.colourbar = colorbar('peer',H.axis); %'EastOutside'); +% set(H.colourbar,'Tag','','Position',[.93 0.2 0.02 0.6]); +% set(get(H.colourbar,'Children'),'Tag',''); +% end + end + setappdata(H.axis,'handles',H); + + %-ColourMap + %====================================================================== + case {'colourmap', 'colormap'} + if isempty(varargin), varargin{1} = gca; end + H = getHandles(varargin{1}); + if length(varargin) == 1 && nargout + varargout = { getappdata(H.patch(1),'colourmap') }; + return; + else + for pi=1:numel(H.patch) + setappdata(H.patch(pi),'colourmap',varargin{2}); + d = getappdata(H.patch(pi),'data'); + updateTexture(H,d,pi); + end + end + if nargin>1 + H.colormap = colormap(varargin{2}); + end + if isfield(H,'colourbar') + set(H.colourbar,'YLim',get(H.axis,'clim')); + end + + %{ + switch varargin{1} + case 'onecolor' + dx= spm_input('Color','1','r',[0.7 0.7 0.7],[3,1]); + H=cat_surf_render2('Colourmap',H,feval(get(obj,'Label'),1)); + + if isempty(varargin{1}) + c = uisetcolor(H.figure, ... + 'Pick a background color...'); + if numel(c) == 1, return; end + else + c = varargin{1}; + end + h = findobj(H.figure,'Tag','SPMMeshRenderBackground'); + if isempty(h) + set(H.figure,'Color',c); + whitebg(H.figure,c); + set(H.figure,'Color',c); + else + set(h,'Color',c); + whitebg(h,c); + set(h,'Color',c); + end + case 'colormapeditor' + colormapeditor + H=cat_surf_render2('Colourmap',H,feval(get(obj,'Label'),256)); + end + %} + +% %-ColourMap +% %====================================================================== +% case {'labelmap'} +% if isempty(varargin), varargin{1} = gca; end +% H = getHandles(varargin{1}); +% if length(varargin) == 1 +% varargout = { getappdata(H.patch(1),'labelmap') }; +% return; +% else +% setappdata(H.patch(1),'labelmap',varargin{2}); +% d = getappdata(H.patch(1),'data'); +% updateTexture(H,d,getappdata(H.patch(1),'labelmap'),'flat'); +% end + + + %-CLim + %====================================================================== + case 'clim' + if isempty(varargin), varargin{1} = gca; end + try + H = getHandles(varargin{1}); + catch + varargin = [{gca} varargin{1}]; + H = getHandles(varargin{1}); + end + if length(varargin) == 1 && nargout + c = getappdata(H.patch(1),'clim'); + if ~isempty(c), c = c(2:3); end + varargout = { c }; + return; + else + for pi=1:numel(H.patch) + try + switch varargin{2} + case {'on',''} + setappdata(H.patch(pi),'clim',[false NaN NaN]); + case {'auto','0p','1p','2p','5p'} + myCaxis([],[],H,varargin{2}); + otherwise + if any(~isfinite(varargin{2})) + setappdata(H.patch(pi),'clim',[false NaN NaN]); + else + setappdata(H.patch(pi),'clim',[true varargin{2}]); + end + end + catch + if strcmp(varargin{2},'on') || isempty(varargin{2}) || any(~isfinite(varargin{2})) + setappdata(H.patch(pi),'clim',[false NaN NaN]); + else + setappdata(H.patch(pi),'clim',[true varargin{2}]); + end + end + d = getappdata(H.patch(pi),'data'); + updateTexture(H,d,pi); + end + end + + if nargin>1 && isnumeric(varargin{2}) && numel(varargin{2})==2 + caxis(H.axis,varargin{2} .* [1 1+eps]); + else + caxis(H.axis,[min(d(:)),max(d(:))] .* [1 1+eps]) + %varargin{2} = [min(d),max(d)]; + end + + %{ + if isfield(H,'colourbar') + set(H.colourbar','ticksmode','auto','LimitsMode','auto') + tick = get(H.colourbar,'ticks'); + ticklabel = get(H.colourbar,'ticklabels'); + if ~isnan(str2double(ticklabel{1})) + tickdiff = mean(diff(tick)); + if tick(1)~=varargin{2}(1) && diff([min(d),varargin{2}(1)])>tickdiff*0.05 + tick = [varargin{2}(1),tick]; ticklabel = [sprintf('%0.3f',varargin{2}(1)); ticklabel]; + end + if tick(end)~=varargin{2}(2) && diff([tick(1),varargin{2}(2)])>tickdiff*0.05, + tick = [tick,varargin{2}(2)]; ticklabel = [ticklabel; sprintf('%0.3f',varargin{2}(2))]; + end + set(H.colourbar,'ticks',tick); %,'ticklabels',ticklabel); + end + set(H.colourbar','ticksmode','manual','LimitsMode','manual') + end + %} + + %-CLip + %====================================================================== + case 'clip' + if isempty(varargin), varargin{1} = gca; end + H = getHandles(varargin{1}); + if length(varargin) == 1 && nargout + c = getappdata(H.patch(1),'clip'); + if ~isempty(c), c = c(2:3); end + varargout = { c }; + return; + else + for pi=1:numel(H.patch) + if isempty(varargin{2}) || any(~isfinite(varargin{2})) + setappdata(H.patch(pi),'clip',[false NaN NaN]); + else + setappdata(H.patch(pi),'clip',[true varargin{2}]); + end + d = getappdata(H.patch(pi),'data'); + updateTexture(H,d,pi); + end + end + + %-Register + %====================================================================== + case 'register' + if isempty(varargin), varargin{1} = gca; end + H = getHandles(varargin{1}); + hReg = varargin{2}; + xyz = spm_XYZreg('GetCoords',hReg); + hs = myCrossBar('Create',H,xyz); + set(hs,'UserData',hReg); + spm_XYZreg('Add2Reg',hReg,hs,@myCrossBar); + + %-Slider + %====================================================================== + case 'slider' + if isempty(varargin), varargin{1} = gca; end + if length(varargin) == 1, varargin{2} = 'on'; end + H = getHandles(varargin{1}); + if strcmpi(varargin{2},'off') + if isfield(H,'slider') && ishandle(H.slider) + delete(H.slider); + H = rmfield(H,'slider'); + setappdata(H.axis,'handles',H); + end + return; + else + AddSliders(H); + end + setappdata(H.axis,'handles',H); + + %-TextureTransparency + %====================================================================== + case 'texturetransparency' + if isempty(varargin), varargin{1} = gca; end + H = getHandles(varargin{1}); + myTextureTransparency(H,[],H) + + %-Otherwise... + %====================================================================== + otherwise + % try + H = cat_surf_render2('Disp',action,varargin{:}); + % catch + % error('Unknown action ""%s"".',action); + % end +end + +if nargout, varargout = {H}; end + + +%========================================================================== +function AddSliders(H) + +c = getappdata(H.patch(1),'clim'); +mn = c(2); +mx = c(3); + +% allow slider a more extended range +mnx = 1.5*max([-mn mx]); + +sliderPanel(... + 'Parent' , H.figure, ... + 'Title' , 'Overlay min', ... + 'Position', [0.01 0.01 0.2 0.17], ... + 'Backgroundcolor', [1 1 1],... + 'Min' , -mnx, ... + 'Max' , mnx, ... + 'Value' , mn, ... + 'FontName', 'Verdana', ... + 'FontSize', 8, ... + 'NumFormat', '%f', ... + 'Callback', @slider_clim_min); + +sliderPanel(... + 'Parent' , H.figure, ... + 'Title' , 'Overlay max', ... + 'Position', [0.21 0.01 0.2 0.17], ... + 'Backgroundcolor', [1 1 1],... + 'Min' , -mnx, ... + 'Max' , mnx, ... + 'Value' , mx, ... + 'FontName', 'Verdana', ... + 'FontSize', 8, ... + 'NumFormat', '%f', ... + 'Callback', @slider_clim_max); + +sliderPanel(... + 'Parent' , H.figure, ... + 'Title' , 'Clip min', ... + 'Position', [0.01 0.83 0.2 0.17], ... + 'Backgroundcolor', [1 1 1],... + 'Min' , -mnx, ... + 'Max' , mnx, ... + 'Value' , mn, ... + 'FontName', 'Verdana', ... + 'FontSize', 8, ... + 'NumFormat', '%f', ... + 'Callback', @slider_clip_min); + +sliderPanel(... + 'Parent' , H.figure, ... + 'Title' , 'Clip max', ... + 'Position', [0.21 0.83 0.2 0.17], ... + 'Backgroundcolor', [1 1 1],... + 'Min' , -mnx, ... + 'Max' , mnx, ... + 'Value' , mn, ... + 'FontName', 'Verdana', ... + 'FontSize', 8, ... + 'NumFormat', '%f', ... + 'Callback', @slider_clip_max); + +setappdata(H.patch(1),'clip',[true mn mn]); +setappdata(H.patch(1),'clim',[true mn mx]); + +%========================================================================== +function O = getOptions(varargin) +O = []; +if ~nargin + return; +elseif nargin == 1 && isstruct(varargin{1}) + for i=fieldnames(varargin{1}) + O.(lower(i{1})) = varargin{1}.(i{1}); + end +elseif mod(nargin,2) == 0 + for i=1:2:numel(varargin) + O.(lower(varargin{i})) = varargin{i+1}; + end +else + error('Invalid list of property/value pairs.'); +end + +%========================================================================== +function H = getHandles(H) +if ~nargin || isempty(H), H = gca; end +if ishandle(H) && ~isappdata(H,'handles') + a = H; clear H; + H.axis = a; + H.figure = ancestor(H.axis,'figure'); + H.patch(1) = findobj(H.axis,'type','patch'); + H.light = findobj(H.axis,'type','light'); + H.rotate3d = rotate3d(H.figure); + setappdata(H.axis,'handles',H); +elseif ishandle(H) + H = getappdata(H,'handles'); +else + H = getappdata(H.axis,'handles'); +end + +%========================================================================== +function myMenuCallback(obj,evt,H) +H = getHandles(H); + +h = findobj(obj,'Label','Rotate'); +if strcmpi(get(H.rotate3d,'Enable'),'on') + set(h,'Checked','on'); +else + set(h,'Checked','off'); +end + +h = findobj(obj,'Label','Slider'); +d = getappdata(H.patch(1),'data'); +if isempty(d) || ~any(d(:)), set(h,'Enable','off'); else set(h,'Enable','on'); end + +if isfield(H,'slider') + if ishandle(H.slider) + set(h,'Checked','on'); + else + H = rmfield(H,'slider'); + set(h,'Checked','off'); + end +else + set(h,'Checked','off'); +end + +% enable sphere menu entry, only if there is only one surface +spheremenu = findobj(obj,'Label','Sphere'); +if numel(H.patch)>1 && ~isempty(spheremenu) + set(spheremenu,'Enable','off'); +else + set(spheremenu,'Enable','on'); +end + +if numel(findobj('Tag','CATSurfRender','Type','Patch')) > 1 + h = findobj(obj,'Tag','SynchroMenu'); + set(h,'Visible','on'); + % set view separator + objview = get(findobj('Label','View'),'children'); + if numel(objview)==1 + set(findobj(objview,'Label','Zoom in'),'Separator','on'); + else + if iscell(objview) + for ovi=1:numel(objview) + set(findobj(objview{ovi},'Label','Zoom in'),'Separator','on'); + end + else + for ovi=1:numel(objview) + set(findobj(objview(ovi),'Label','Zoom in'),'Separator','on'); + end + end + end + objcolr = get(findobj('Label','Colorrange'),'children'); + if numel(objcolr)==1 + set(findobj(objcolr,'Label','Zoom in'),'Separator','on'); + else + if iscell(objcolr) + for ovi=1:numel(objcolr) + set(findobj(objcolr{ovi},'Label','Min-max'),'Separator','on'); + end + else + for ovi=1:numel(objcolr) + set(findobj(objcolr(ovi),'Label','Min-max'),'Separator','on'); + end + end + end + % set caxis separator + set(findobj('Label','Synchronise Colorranges','Tag','CATSurfRender','Type','Patch'),'Separator','on'); +else + h = findobj(obj,'Tag','SynchroMenu'); + set(h,'Visible','off'); + % set view separator + objview = get(findobj('Label','View'),'children'); + if numel(objview)==1 + set(findobj(objview,'Label','Right'),'Separator','on'); + else + if iscell(objview) + for ovi=1:numel(objview) + set(findobj(objview{ovi},'Label','Zoom in'),'Separator','off'); + end + else + for ovi=1:numel(objview) + set(findobj(objview(ovi),'Label','Zoom in'),'Separator','off'); + end + end + end + objcolr = get(findobj('Label','Colorrange'),'children'); + if numel(objcolr)==1 + set(findobj(objcolr,'Label','Zoom in'),'Separator','off'); + else + if iscell(objcolr) + for ovi=1:numel(objcolr) + set(findobj(objcolr{ovi},'Label','Min-max'),'Separator','off'); + end + else + for ovi=1:numel(objcolr) + set(findobj(objcolr(ovi),'Label','Min-max'),'Separator','off'); + end + end + end + % set caxis separator + set(findobj('Label','Synchronise Colorranges','Tag','CATSurfRender','Type','Patch'),'Separator','off'); +end + + +% enable texture elements +objtextures = findobj(obj,'Label','Textures'); +objatlases = findobj(obj,'Label','Atlases'); +objcbar = findobj(obj,'Label','Colorbar'); +objcmap = findobj(obj,'Label','Colormap'); +objcrange = findobj(obj,'Label','Colorrange'); +if ~isempty(H.patch(1).FaceVertexCData) + set(objcbar ,'Enable','on'); + set(objcmap ,'Enable','on'); + set(objcrange,'Enable','on'); +elseif ~isempty(findobj(get(objatlases,'children'),'Checked','on')) || ... + (isempty(findobj(get(objtextures,'children'),'Checked','on')) && ... + isempty(findobj(get(objatlases,'children'),'Checked','on'))) || ... + (~isempty(objtextures) && isempty(findobj(findobj(get(objtextures,'children'),'Label','none'),'Checked','off'))) || ... + (~isempty(objatlases) && isempty(findobj(findobj(get(objatlases,'children'),'Label','none'),'Checked','off'))) + + set(objcbar ,'Enable','off'); + set(objcmap ,'Enable','off'); + set(objcrange,'Enable','off'); +else + set(objcbar ,'Enable','on'); + set(objcmap ,'Enable','on'); + set(objcrange,'Enable','on'); +end + + +% enable volume elements +objslices = findobj(get(H.axis,'children'),'type','surf','Tag','volumeSlice'); +objvolmenu = get(findobj(obj,'Label','Volume'),'children'); +objvolload = findobj(objvolmenu,'Label','Volume selection'); +if isempty(objslices) + set(objvolmenu,'Enable','off'); + set(objvolload,'Enable','on'); +else + set(objvolmenu,'Enable','on'); +end + + +% +if isfield(H,'colourbar') + if ishandle(H.colourbar) + set(objcbar,'Checked','on'); + else + H = rmfield(H,'colourbar'); + set(objcbar,'Checked','off'); + end +else + set(objcbar,'Checked','off'); +end +setappdata(H.axis,'handles',H); + +%========================================================================== +function myPostCallback(obj,evt,H) +% lighting and rotation update + if strcmp(get(findobj(obj,'Label','Synchronise Views'),'Checked'),'on') + cam.pos = get(H.axis,'cameraposition'); + cam.tag = get(H.axis,'CameraTarget'); + cam.vec = get(H.axis,'CameraUpVector'); + cam.ang = get(H.axis,'CameraViewAngle'); + P = findobj('Tag','CATSurfRender','Type','Patch'); + P = setxor(H.patch,P); + if strcmp(H.light(1).Visible,'on'), camlight(H.light(1),'headlight','infinite'); end + for i=1:numel(P) + HP = getappdata(ancestor(P(i),'axes'),'handles'); + set(HP.axis,'cameraposition',cam.pos,'CameraUpVector',cam.vec,... + 'CameraViewAngle',cam.ang,'CameraTarget',cam.tag); + axis(HP.axis,'image'); + if strcmp(HP.catLighting,'cam') && ~isempty(HP.light), camlight(HP.light(1),'headlight','infinite'); end + end + else + if strcmp(H.light(1).Visible,'on'), camlight(H.light(1),'headlight','infinite'); end + end + axis vis3d; +%P = findobj(obj,'Tag','CATSurfRender','Type','Patch'); +%if numel(P) == 1 +%else +% for i=1:numel(P) +% H = getappdata(ancestor(P(i),'axes'),'handles'); +% if strcmp(H.light(1).Visible,'on') && ~isempty(H.light), camlight(H.light(1)); end +% end +%end +%========================================================================== +function myCheckreg(H) + +function varargout = myCrossBar(varargin) + +switch lower(varargin{1}) + + case 'create' + %---------------------------------------------------------------------- + % hMe = myCrossBar('Create',H,xyz) + H = varargin{2}; + xyz = varargin{3}; + hold(H.axis,'on'); + hs = plot3(xyz(1),xyz(2),xyz(3),'Marker','+','MarkerSize',60,... + 'parent',H.axis,'Color',[1 1 1],'Tag','CrossBar','ButtonDownFcn',{}); + varargout = {hs}; + + case 'setcoords' + %---------------------------------------------------------------------- + % [xyz,d] = myCrossBar('SetCoords',xyz,hMe) + hMe = varargin{3}; + xyz = varargin{2}; + set(hMe,'XData',xyz(1)); + set(hMe,'YData',xyz(2)); + set(hMe,'ZData',xyz(3)); + varargout = {xyz,[]}; + + otherwise + %---------------------------------------------------------------------- + error('Unknown action string') + +end + +%========================================================================== +function myInflate(obj,evt,H) +for pi=1:numel(H.patch) + spm_mesh_inflate(H.patch(pi),Inf,1); +end +axis(H.axis,'image'); + +%========================================================================== +function myDataSmooth(obj,evt,H) +for pi=1:numel(H.patch) + spm_mesh_smooth(H.patch(pi),H.patch(pi).FaceVertexAlphaData,1); +end +axis(H.axis,'image'); + +%========================================================================== +function myCCLabel(obj,evt,H) +for pi=1:numel(H.patch) + C = getappdata(H.patch(pi),'cclabel'); + F = get(H.patch(pi),'Faces'); + ind = sscanf(get(obj,'Label'),'Component %d'); + V = get(H.patch(pi),'FaceVertexAlphaData'); + Fa = get(H.patch(pi),'FaceAlpha'); + if ~isnumeric(Fa) + if ~isempty(V), Fa = max(V); else Fa = 1; end + if Fa == 0, Fa = 1; end + end + if isempty(V) || numel(V) == 1 + Ve = get(H.patch(pi),'Vertices'); + if isempty(V) || V == 1 + V = Fa * ones(size(Ve,1),1); + else + V = zeros(size(Ve,1),1); + end + end + if strcmpi(get(obj,'Checked'),'on') + V(reshape(F(C==ind,:),[],1)) = 0; + set(obj,'Checked','off'); + else + V(reshape(F(C==ind,:),[],1)) = Fa; + set(obj,'Checked','on'); + end + set(H.patch(pi), 'FaceVertexAlphaData', V); + if all(V) + set(H.patch(pi), 'FaceAlpha', Fa); + else + set(H.patch(pi), 'FaceAlpha', 'interp'); + end +end + +%========================================================================== +function myTransparency(obj,evt,H) +t = 1 - sscanf(get(obj,'Label'),'%d%%') / 100; +for pi=1:numel(H.patch) + set(H.patch(pi),'FaceAlpha',t); +end +set(get(get(obj,'parent'),'children'),'Checked','off'); +set(obj,'Checked','on'); +%========================================================================== +function myTextureTransparency(obj,evt,H) +y = {'on','off'}; toggle = @(x) y{1+strcmpi(x,'on')}; +set(obj,'Checked',toggle(get(obj,'Checked'))); +d = getappdata(H.patch(1),'data'); +updateTexture(H,d); +%========================================================================== +function mySliceTransparency(obj,evt,H) +t = 1 - sscanf(get(obj,'Label'),'%d%%') / 100; +slices = findobj(get(H.axis,'children'),'type','surf','tag','volumeSlice'); +for pi=1:numel(slices) + set(slices(pi),'FaceAlpha',t); +end +set(get(get(obj,'parent'),'children'),'Checked','off'); +set(obj,'Checked','on'); +%========================================================================== +function myVolTransparency(obj,evt,H,rangetype) +if ~exist('action','var'), rangetype = 'full'; end +t = 1 - sscanf(get(obj,'Label'),'%d%%') / 100; +slices = findobj(get(H.axis,'children'),'type','surf','tag','volumeSlice'); + +d = []; for pi=1:numel(slices), d1 = get(slices(pi),'cdata'); d = [d d1(:)']; end; clear d1; %#ok +d(isnan(d) | isinf(d)) = []; +if cat_stat_nanmean(d(:))>0 && cat_stat_nanstd(d(:),1)>0 + switch rangetype + case 'full', + range = [min(d) max(d)]; + case 'background' + range = cat_vol_iscaling(d,[0.20 0.90]); + case 'CSF' + range = mean( d(d>median(d(:)) & d<3*median(d(:))) ) * 1.5; + case 'custom' + fc = gcf; + spm_figure('getwin','Interactive'); + range = cat_vol_iscaling(d,[0.02 0.98]); + d = spm_input('intensity range','1','r',range,[2,1]); + figure(fc); + range = [min(d) max(d)]; + case 'customp' + fc = gcf; + spm_figure('getwin','Interactive'); + dx= spm_input('percentual intensity range','1','r',[2 98],[2,1]); + range = cat_vol_iscaling(d,dx/100); + figure(fc); + otherwise + range = [min(d) max(d)]; + end + if range(1)==range(2), range = range + [-eps eps]; end + if range(1)>range(2), range = fliplr(range); end +end +for pi=1:numel(slices) + d1 = get(slices(pi),'cdata'); if size(d1,3)>1, d1 = d1(:,:,2); end + set(slices(pi),'AlphaData',(d1 - range(1)) / abs(diff(range)) ,... + 'FaceAlpha','flat','alphaDataMapping','none'); +end +set(get(get(obj,'parent'),'children'),'Checked','off'); +set(obj,'Checked','on'); +%========================================================================== +function mySwitchRotate(obj,evt,H) +if strcmpi(get(H.rotate3d,'enable'),'on') + set(H.rotate3d,'enable','off'); + set(obj,'Checked','off'); +else + set(H.rotate3d,'enable','on'); + set(obj,'Checked','on'); +end + +%========================================================================== +function myView(obj,evt,H,varargin) +view(H.axis,varargin{1}); +axis(H.axis,'image'); +if strcmp(H.catLighting,'cam') && ~isempty(H.light), camlight(H.light(1),'headlight','infinite'); end + +%========================================================================== +function myZoom(obj,evt,H,action) +switch lower(action) + case 'zoom in', zoom(10/9); + case 'zoom out', zoom(9/10); + case 'zoom', zoom; + case 'zoom reset', zoom('reset'); +end +%========================================================================== +function myPan(obj,evt,H) +pan; + + +%========================================================================== +function myColourbar(obj,evt,H) +y = {'on','off'}; toggle = @(x) y{1+strcmpi(x,'on')}; +cat_surf_render2('Colourbar',H,toggle(get(obj,'Checked'))); +set(obj,'Checked',toggle(get(obj,'Checked'))); + +%========================================================================== +function myToolBar(obj,evt,H) +y = {'on','off'}; toggle = @(x) y{1+strcmpi(x,'on')}; +d = {'default','none'}; toggle2 = @(x) d{1+strcmpi(x,'on')}; +set(H.figure,'ToolBar',toggle2(get(obj,'Checked'))); +set(H.figure,'MenuBar',toggle2(get(obj,'Checked'))); +set(obj,'Checked',toggle(get(obj,'Checked'))); + +%========================================================================== +function myLighting(obj,evt,H,newcatLighting) +switch newcatLighting + case 'brighter' + l1 = findall(H.axis,'Type','light'); + for li = 1:numel(l1) + set(l1(li),'Color',min(ones(1,3),get(l1(li),'Color')*10/9)); + end + case 'darker' + l1 = findall(H.axis,'Type','light'); + for li = 1:numel(l1) + set(l1(li),'Color',max(zeros(1,3),get(l1(li),'Color')*9/10)); + end + otherwise + y = {'on','off'}; toggle = @(x) y{1+strcmpi(x,'on')}; + % set old lights + H.catLighting = newcatLighting; + delete(findall(H.axis,'Type','light','Tag','')); % remove old infinite lights + delete(findall(H.axis,'Type','light','Tag','centerlight')); + caml = findall(H.axis,'Type','light','Tag','camlight'); % switch off camlight + set(caml,'visible','off'); + + % new lights + for pi=1:numel(H.patch) + set(H.patch(pi),'BackFaceLighting','reverselit'); + end + switch H.catLighting + case 'none' + % nothing to do... + case 'outer' + switch H.sinfo(1).texture + case 'defects' + mylit = 'lit'; + otherwise + mylit = 'unlit'; + end + H.light(2) = light('Position',[0 0 0],'parent',H.axis,'Style','infinite'); + for pi=1:numel(H.patch) + H.patch(1).Faces = [H.patch(1).Faces(:,2),H.patch(1).Faces(:,1),H.patch(1).Faces(:,3)]; + end + for pi=1:numel(H.patch) + ks = get(H.patch(pi),'SpecularStrength'); set(H.patch(pi),'SpecularStrength',min(0.1,ks)); + n = get(H.patch(pi),'SpecularExponent'); set(H.patch(pi),'SpecularExponent',max(2,n)); + set(H.patch(pi),'BackFaceLighting',mylit); + end + + case 'inner' + switch H.sinfo(1).texture + case 'defects' + mylit = 'lit'; + otherwise + mylit = 'unlit'; + end + H.light(2) = light('Position',[0 0 0],'parent',H.axis,'Style','infinite'); + for pi=1:numel(H.patch) + ks = get(H.patch(pi),'SpecularStrength'); set(H.patch(pi),'SpecularStrength',min(0.1,ks)); + n = get(H.patch(pi),'SpecularExponent'); set(H.patch(pi),'SpecularExponent',max(2,n)); + set(H.patch(pi),'BackFaceLighting',mylit); + end + case 'top' + H.light(2) = light('Position',[ 0 0 1],'Color',repmat(1,1,3),'parent',H.axis,'Style','infinite'); %#ok<*REPMAT> + case 'bottom' + H.light(2) = light('Position',[ 0 0 -1],'Color',repmat(1,1,3),'parent',H.axis,'Style','infinite'); + case 'left' + H.light(2) = light('Position',[-1 0 0],'Color',repmat(1,1,3),'parent',H.axis,'Style','infinite'); + case 'right' + H.light(2) = light('Position',[ 1 0 0],'Color',repmat(1,1,3),'parent',H.axis,'Style','infinite'); + case 'front' + H.light(2) = light('Position',[ 0 1 0],'Color',repmat(1,1,3),'parent',H.axis,'Style','infinite'); + case 'back' + H.light(2) = light('Position',[ 0 -1 0],'Color',repmat(1,1,3),'parent',H.axis,'Style','infinite'); + case 'set1' + H.light(2) = light('Position',[ 1 0 .5],'Color',repmat(0.8,1,3),'parent',H.axis,'Style','infinite'); + H.light(3) = light('Position',[-1 0 .5],'Color',repmat(0.8,1,3),'parent',H.axis,'Style','infinite'); + H.light(4) = light('Position',[ 0 1 -.5],'Color',repmat(0.2,1,3),'parent',H.axis,'Style','infinite'); + H.light(5) = light('Position',[ 0 -1 -.5],'Color',repmat(0.2,1,3),'parent',H.axis,'Style','infinite'); + case 'set2' + H.light(2) = light('Position',[ 1 0 1],'Color',repmat(0.7,1,3),'parent',H.axis,'Style','infinite'); + H.light(3) = light('Position',[-1 0 1],'Color',repmat(0.7,1,3),'parent',H.axis,'Style','infinite'); + H.light(4) = light('Position',[ 0 1 .5],'Color',repmat(0.3,1,3),'parent',H.axis,'Style','infinite'); + H.light(5) = light('Position',[ 0 -1 .5],'Color',repmat(0.3,1,3),'parent',H.axis,'Style','infinite'); + H.light(6) = light('Position',[ 0 0 -1],'Color',repmat(0.2,1,3),'parent',H.axis,'Style','infinite'); + case 'set3' + H.light(2) = light('Position',[ 1 0 0],'Color',repmat(0.8,1,3),'parent',H.axis,'Style','infinite'); + H.light(3) = light('Position',[-1 0 0],'Color',repmat(0.8,1,3),'parent',H.axis,'Style','infinite'); + H.light(4) = light('Position',[ 0 1 1],'Color',repmat(0.2,1,3),'parent',H.axis,'Style','infinite'); + H.light(5) = light('Position',[ 0 -1 1],'Color',repmat(0.2,1,3),'parent',H.axis,'Style','infinite'); + H.light(6) = light('Position',[ 0 0 -1],'Color',repmat(0.1,1,3),'parent',H.axis,'Style','infinite'); + case 'cam' + %pause(0.01); % this is necessary to remove lights of previous used lightset ... don't know why, but without it didn't work! + camlight(H.light(1),'headlight','infinite'); + set(caml,'Visible','on'); + end + lighting gouraud + set(get(get(obj,'parent'),'children'),'Checked','off'); + set(obj,'Checked','on'); +end + +%========================================================================== +function myMaterial(obj,evt,H,mat) +y = {'on','off'}; toggle = @(x) y{1+strcmpi(x,'on')}; +for pi=1:numel(H.patch) + set(H.patch(pi),'LineStyle','none'); + switch mat + case 'shiny' + material shiny; + case 'dull' + material dull; + case 'metal' + material metal; + % set(H.patch(pi),'AmbientStrength',0.4,'DiffuseStrength',0.9,'SpecularStrength',0.1,'SpecularExponent',1); + case 'metalic' + set(H.patch(pi),'AmbientStrength',0.3,'DiffuseStrength',0.6,'SpecularStrength',0.3,'SpecularExponent',2); + case 'plastic' + set(H.patch(pi),'AmbientStrength',0.25,'DiffuseStrength',0.5,'SpecularStrength',0.4,'SpecularExponent',0.7); + case 'default' % = dull + set(H.patch(pi),'AmbientStrength',0.4,'DiffuseStrength',0.6,'SpecularStrength',0.0,'SpecularExponent',10); + case 'custom' + spm_figure('getwin','Interactive'); + % actual values + ka = get(H.patch(pi),'AmbientStrength'); + kd = get(H.patch(pi),'DiffuseStrength'); + ks = get(H.patch(pi),'SpecularStrength'); + n = get(H.patch(pi),'SpecularExponent'); + % new values + ka = spm_input('AmbientStrength',1,'r',ka,[1,1]); + kd = spm_input('DiffuseStrength',2,'r',kd,[1,1]); + ks = spm_input('SpecularStrength',3','r',ks,[1,1]); + n = spm_input('SpecularExponent',4,'r',n,[1,1]); + set(H.patch(pi),'AmbientStrength',ka,'DiffuseStrength',kd,'SpecularStrength',ks,'SpecularExponent',n); + otherwise + set(H.patch(pi),'AmbientStrength',0.2,'DiffuseStrength',0.9,'SpecularStrength',0.8,'SpecularExponent',10); + end + set(get(get(obj,'parent'),'children'),'Checked','off'); + set(obj,'Checked','on'); +end +%========================================================================== +function myGrid(obj,evt,H,mat) +y = {'on','off'}; toggle = @(x) y{1+strcmpi(x,'on')}; +set(obj,'Checked',toggle(get(obj,'Checked'))); +for pi=1:numel(H.patch) + if strcmp(get(obj,'Checked'),'on') + set(H.patch(pi),'LineStyle','-','EdgeColor',[0 0 0]); + lighting flat + else + set(H.patch(pi),'LineStyle','none','EdgeColor','none'); + lighting gouraud + end +end + +%========================================================================== +function mySlices(obj,evt,H,type) +if ~exist('type','var'), type = 'voxel'; end +slices = findobj(get(H.axis,'children'),'type','surf','tag','volumeSlice'); +slicedata = get(slices(1),'UserData'); +P = slicedata.fname; +set(get(get(obj,'parent'),'children'),'Checked','off'); +switch type + case 'none', pls = []; + case 'AC', pls = slicedata.AC; + case 'x+10', pls = slicedata.voxel + [ 10 0 0]; + case 'x-10', pls = slicedata.voxel + [-10 0 0]; + case 'y+10', pls = slicedata.voxel + [ 0 10 0]; + case 'y-10', pls = slicedata.voxel + [ 0 -10 0]; + case 'z+10', pls = slicedata.voxel + [ 0 0 10]; + case 'z-10', pls = slicedata.voxel + [ 0 0 -10]; + case 'voxel' + spm_figure('getwin','Interactive'); + pls = spm_input('xyz-Slice','1','i',round(slicedata.voxel),[1,3]); + case 'mm' + spm_figure('getwin','Interactive'); + pls = spm_input('xyz-Slice','1','i',round(slicedata.voxel - slicedata.AC),[1,3]); + pls = pls + slicedata.AC; +end +renderSlices2(H,P,pls) + +if all(pls==slicedata.AC), set(findobj(get(obj,'parent'),'label','AC'),'Checked','on'); end + +%========================================================================== +function myVolCaxis(obj,evt,H,rangetype) +%% d = get(H.patch(1),'FaceVertexCData'); +slices = findobj(get(H.axis,'children'),'type','surf','tag','volumeSlice'); +if ~isempty(slices) + d = []; + for si=1:numel(slices) + d1 = get(slices(si),'CData'); d=[d (d1(:))']; clear d1; %#ok + end + d(isnan(d) | isinf(d)) = []; + if cat_stat_nanmean(d(:))>0 && cat_stat_nanstd(d(:),1)>0 + switch rangetype + case 'min-max', + range = [min(d) max(d)]; + case '1p' + range = cat_vol_iscaling(d,[0.01 0.99]); + case '2p' + range = cat_vol_iscaling(d,[0.02 0.98]); + case '5p' + range = cat_vol_iscaling(d,[0.05 0.95]); + case 'custom' + fc = gcf; + spm_figure('getwin','Interactive'); + range = cat_vol_iscaling(d,[0.02 0.98]); + d = spm_input('intensity range','1','r',range,[2,1]); + figure(fc); + range = [min(d) max(d)]; + case 'customp' + fc = gcf; + spm_figure('getwin','Interactive'); + dx= spm_input('percentual intensity range','1','r',[2 98],[2,1]); + range = cat_vol_iscaling(d,dx/100); + figure(fc); + otherwise + range = [min(d) max(d)]; + end + if range(1)==range(2), range = range + [-eps eps]; end + if range(1)>range(2), range = fliplr(range); end + end + %% + %cat_surf_render2('Clim',H,range); + + set(get(get(obj,'parent'),'children'),'Checked','off'); + set(obj,'Checked','on'); +end +%========================================================================== +function myCaxis(obj,evt,H,rangetype) +%% d = get(H.patch(1),'FaceVertexCData'); +d = getappdata(H.patch(1),'data'); d(isnan(d) | isinf(d)) = []; +if cat_stat_nanmean(d(:))>0 && cat_stat_nanstd(d(:),1)>0 + if isnumeric(rangetype) + range = [min(rangetype) max(rangetype)]; + else + switch rangetype + case 'min-max' + range = [min(d) max(d)]; + case '0p' + range = cat_vol_iscaling(d,[0.001 0.999]); + case '1p' + range = cat_vol_iscaling(d,[0.01 0.99]); + case '2p' + range = cat_vol_iscaling(d,[0.02 0.98]); + case '5p' + range = cat_vol_iscaling(d,[0.05 0.95]); + case 'custom' + fc = gcf; + spm_figure('getwin','Interactive'); + range = cat_vol_iscaling(d,[0.02 0.98]); + d = spm_input('intensity range','1','r',range,[2,1]); + figure(fc); + range = [min(d) max(d)]; + case 'customp' + fc = gcf; + spm_figure('getwin','Interactive'); + dx= spm_input('percentual intensity range','1','r',[2 98],[2,1]); + range = cat_vol_iscaling(d,dx/100); + figure(fc); + otherwise + range = [min(d) max(d)]; + end + end + if range(1)==range(2), range = range + [-eps*100 eps*100]; end + if range(1)>range(2), range = fliplr(range); end + cat_surf_render2('Clim',H,range); +end +set(get(get(obj,'parent'),'children'),'Checked','off'); +set(obj,'Checked','on'); +%========================================================================== +function myHist(obj,evt,H) +objTextures = findobj(get(findobj(get(get(obj,'parent'),'parent'),'Label','Textures'),'Children'),'Checked','on'); +if isfield( H , 'textures') + currentTexture = cellfun('isempty',strfind( H.textures(:,1) , objTextures.Label ))==0 & cellfun('length',H.textures(:,1)) == length(objTextures.Label); + cat_plot_histogram( H.textures{currentTexture,2}.fname ) +else + cat_plot_histogram( H.cdata ); +end +%========================================================================== +function mySynchroniseCaxis(obj,evt,H) +P = findobj('Tag','CATSurfRender','Type','Patch'); +range = getappdata(H.patch(1), 'clim'); +range = range(2:3); + +for i=1:numel(P) + H = getappdata(ancestor(P(i),'axes'),'handles'); + cat_surf_render2('Clim',H,range); +end +%========================================================================== +function myInvColourmap(obj,evt,H,varargin) +y = {'on','off'}; toggle = @(x) y{1+strcmpi(x,'on')}; +col = getappdata(H.patch(1),'colourmap'); +for pi=1:numel(H.patch) + setappdata(H.patch(pi),'colourmap',flipud(col)); +end +cat_surf_render2('Colourmap',H,flipud(col)); +set(obj,'Checked',toggle(get(obj,'Checked'))); + +%========================================================================== +function myColourmap(obj,evt,H,varargin) +range = getappdata(H.patch(1), 'clim'); +inv = strcmp(get(findobj(get(obj,'parent'),'Label','Invert Colormap'),'Checked'),'on'); +if ~isempty(varargin) + switch varargin{1} + case 'color' + c = uisetcolor(H.figure,'Pick a surface color...'); + H = cat_surf_render2('Colourmap',H,c); + case 'custom' + c = colormap; clow = c(1:4:256,:); + H = cat_surf_render2('Colourmap',H,clow,16); colormap(clow); + colormapeditor; + %cn = colormap; [GX,GY] = meshgrid(0.5+eps:size(cn,1)/256:size(cn,1)+.5-eps,1:3); + %cnhigh = interp2(cn,GY,GX); + %H = cat_surf_render2('Colourmap',H,cnhigh); colormap(cnhigh); + otherwise + if inv + H=cat_surf_render2('Colourmap',H,feval(get(obj,'Label'),256)); + else + H=cat_surf_render2('Colourmap',H,flipud(feval(get(obj,'Label'),256))); + end + end +else + switch get(obj,'Label') + case {'CAThot','CAThotinv','CATcold','CATcoldinv'} + catcm = get(obj,'Label'); catcm(1:3) = []; + cm = cat_io_colormaps(catcm,256); + case 'turbo' + cm = cat_io_colormaps('turbo',256); + case 'CATtissues' + cm = cat_io_colormaps('BCGWHw',256); + case 'CATcold&hot' + cm = cat_io_colormaps('BWR',256); + otherwise + cm = feval(get(obj,'Label'),256); + end + if inv + H=cat_surf_render2('Colourmap',H,flipud(cm)); + else + H=cat_surf_render2('Colourmap',H,cm); + end +end +set(setdiff(get(get(obj,'parent'),'children'),... + [findobj(get(obj,'parent'),'Label','Colorbar'),... + findobj(get(obj,'parent'),'Label','Invert Colormap')]),'Checked','off'); + +% update colorrange +cat_surf_render2('Clim',H,range(2:3)); +set(obj,'Checked','on'); + +%========================================================================== +function myAddslider(obj,evt,H) +y = {'on','off'}; toggle = @(x) y{1+strcmpi(x,'on')}; +cat_surf_render2('Slider',H,toggle(get(obj,'Checked'))); + +%========================================================================== +function mySynchroniseViewsOnce(obj,evt,H) +P = findobj('Tag','CATSurfRender','Type','Patch'); +v = get(H.axis,'cameraposition'); +a = get(H.axis,'CameraUpVector'); +b = get(H.axis,'CameraViewAngle'); +for i=1:numel(P) + H = getappdata(ancestor(P(i),'axes'),'handles'); + set(H.axis,'cameraposition',v,'CameraUpVector',a,'CameraViewAngle',b); + axis(H.axis,'image'); + if strcmp(H.catLighting,'cam') && ~isempty(H.light), camlight(H.light(1),'headlight','infinite'); end +end + +%========================================================================== +function mySynchroniseViews(obj,evt,H) +y = {'on','off'}; toggle = @(x) y{1+strcmpi(x,'on')}; +HP = findobj(obj,'Label','Synchronise Views'); +check = toggle(get(obj,'Checked')); +for HPi=1:numel(HP) + set(HP(HPi),'Checked',check); +end +%========================================================================== +function mySynchroniseTexture(obj,evt,H) +tex = get(obj,'parent'); +curTex = setdiff( findobj( get(tex,'children'),'Checked','on'), tex); +oT = setdiff( findobj('Label',get(curTex,'Label')) , curTex); +P = setdiff( findobj('Tag','CATSurfRender','Type','Patch'), H.patch); +otex = setdiff( findobj('Label','Textures'),tex); +for i=1:numel(oT) + try + Hi = getappdata(ancestor(P(i),'axes'),'handles'); + Hi.textures = get(otex(i),'Userdata'); + myChangeTexture(oT(i),evt,Hi); + end + mySynchroniseCaxis(obj,evt,Hi); + %mySynchroniseCaxis(oT(i),evt,Hi) +end +%========================================================================== +function myDataCursor(obj,evt,H) +dcm_obj = datacursormode(H.figure); +set(dcm_obj, 'Enable','on', 'SnapToDataVertex','on', ... + 'DisplayStyle','Window', 'Updatefcn',{@myDataCursorUpdate, H}); + +%========================================================================== +function txt = myDataCursorUpdate(obj,evt,H) +pos = get(evt,'Position'); +txt = {['X: ',num2str(pos(1))],... + ['Y: ',num2str(pos(2))],... + ['Z: ',num2str(pos(3))]}; +i = ismember(get(H.patch(1),'vertices'),pos,'rows'); +txt = {['Node: ' num2str(find(i))] txt{:}}; +d = getappdata(H.patch(1),'data'); +if ~isempty(d) && any(d(:)) + if any(i), txt = {txt{:} ['T: ',num2str(d(i))]}; end +end +hMe = findobj(H.axis,'Tag','CrossBar'); +if ~isempty(hMe) + ws = warning('off'); + spm_XYZreg('SetCoords',pos,get(hMe,'UserData')); + warning(ws); +end + +%========================================================================== +function myBackgroundColor(obj,evt,H,varargin) +if isempty(varargin{1}) + c = uisetcolor(H.figure, ... + 'Pick a background color...'); + if numel(c) == 1, return; end +else + c = varargin{1}; +end +h = findobj(H.figure,'Tag','SPMMeshRenderBackground'); +if isempty(h) + set(H.figure,'Color',c); + whitebg(H.figure,c); + set(H.figure,'Color',c); +else + set(h,'Color',c); + whitebg(h,c); + set(h,'Color',c); +end +set(get(get(obj,'parent'),'children'),'Checked','off'); % deactivate all +set(obj,'Checked','on'); + +%========================================================================== +function myPrintResolution(obj,evt,H,varargin) +y = {'on','off'}; toggle = @(x) y{1+strcmpi(x,'on')}; +cat_surf_render2('printresolution',H,toggle(get(obj,'Checked')),varargin{1}); + +obji = findobj('Tag','','type','uimenu','label','Print resolution'); +for i=1:numel(obji) + set(get(obji(i),'children'),'Checked','off'); % deactivate all + + % active the one + objj = findobj(get(obji(i),'children'),'label',obj.Label); + for j=1:numel(objj) + set(objj(j),'Checked','on'); + end +end + +%========================================================================== +function mySavePNG(obj,evt,H,filename) + %% + if ~exist('filename','var') + filename = get(H.figure,'Name'); + end + + [pth,nam,ext] = fileparts(filename); + if isempty(pth), pth = cd; end + if ~strcmp({'.gii','.png'},ext), nam = [nam ext]; end + if isempty(nam) || exist(fullfile(pth,[nam '.png']),'file') || ~exist(pth,'dir') || pth(1)=='.' + [filename,filepath] = uiputfile({... + '*.png' 'PNG files (*.png)'}, 'Save as',nam); + else + [filepath,ff,ee] = spm_fileparts(fullfile(pth,[nam '.png'])); + filename = [ff ee]; + end + + u = get(H.axis,'units'); + set(H.axis,'units','pixels'); + p = get(H.figure,'Position'); + r = get(H.figure,'Renderer'); + hc = findobj(H.figure,'Tag','SPMMeshRenderBackground'); + if isempty(hc) + c = get(H.figure,'Color'); + else + c = get(hc,'Color'); + end + h = figure('Position',p+[0 0 0 0], ... + 'InvertHardcopy','off', ... + 'Color',c, ... + 'Renderer',r); + copyobj(H.axis,h); + copyobj(H.axis,h); + set(H.axis,'units',u); + set(get(h,'children'),'visible','off'); + + if ~strcmp(H.sinfo(1).texture,'defects') && ~strcmp(H.sinfo(1).texture,'central') + colorbar('Position',[.93 0.2 0.02 0.6]); + end + colormap(getappdata(H.patch(1),'colourmap')); + + if isempty(cat_get_defaults('print.dpi')) + cat_get_defaults('print.dpi',300); + end + + [pp,ff,ee] = fileparts(H.filename{1}); + %H.text = annotation('textbox','string',[ff ee],'position',[0.0,0.97,0.2,0.03],'LineStyle','none','Interpreter','none'); + %a = get(h,'children'); + %set(a,'Position',get(a,'Position').*[0 0 1 1]+[10 10 0 0]); + if isdeployed + deployprint(h, '-dpng', '-opengl',sprintf('-r%d',cat_get_defaults('print.dpi')), fullfile(filepath,filename)); + else + print(h, '-dpng', '-opengl', sprintf('-r%d',cat_get_defaults('print.dpi')), fullfile(filepath,filename)); + end + fprintf('Save as ""%s"".\n',fullfile(filepath,filename)) + for pi=1:numel(H.patch) + if get(H.patch(pi),'LineWidth')>0; set(H.patch(pi),'LineWidth',0.5); end % restore mesh default + end + close(h); + set(getappdata(obj,'fig'),'renderer',r); + +%========================================================================== +function mySave(obj,evt,H) + filename = get(H.figure,'Name'); + + [pth,nam,ext] = fileparts(filename); + if ~strcmp({'.gii','.png'},ext), nam = [nam ext]; end + [filename, pathname, filterindex] = uiputfile({... + '*.png' 'PNG files (*.png)';... + '*.gii' 'GIfTI files (*.gii)'; ... + '*.dae' 'Collada files (*.dae)';... + '*.idtf' 'IDTF files (*.idtf)'}, 'Save as',nam); + +if ~isequal(filename,0) && ~isequal(pathname,0) + [pth,nam,ext] = fileparts(filename); + switch ext + case '.gii' + filterindex = 1; + case '.png' + filterindex = 2; + case '.dae' + filterindex = 3; + case '.idtf' + filterindex = 4; + otherwise + switch filterindex + case 1 + filename = [filename '.gii']; + case 2 + filename = [filename '.png']; + case 3 + filename = [filename '.dae']; + end + end + switch filterindex + case 1 + G = gifti(H.patch(1)); + [p,n,e] = fileparts(filename); + [p,n,e] = fileparts(n); + switch lower(e) + case '.func' + save(gifti(getappdata(H.patch(1),'data')),... + fullfile(pathname, filename)); + case '.surf' + save(gifti(struct('vertices',G.vertices,'faces',G.faces)),... + fullfile(pathname, filename)); + case '.rgba' + save(gifti(G.cdata),fullfile(pathname, filename)); + otherwise + save(G,fullfile(pathname, filename)); + end + case 2 + u = get(H.axis,'units'); + set(H.axis,'units','pixels'); + p = get(H.figure,'Position'); % axis + r = get(H.figure,'Renderer'); + hc = findobj(H.figure,'Tag','SPMMeshRenderBackground'); + if isempty(hc) + c = get(H.figure,'Color'); + else + c = get(hc,'Color'); + end + h = figure('Position',p+[0 0 0 0], ... [0 0 10 10] + 'InvertHardcopy','off', ... + 'Color',c, ... + 'Renderer',r); + copyobj(H.axis,h); + set(H.axis,'units',u); + set(get(h,'children'),'visible','off'); + + % set colorbar + textures = findobj(get(findobj(H.figure,'Label','Textures'),'children'),'checked','on'); + atlases = findobj(get(findobj(H.figure,'Label','Atlases'),'children'),'checked','on'); + if ~strcmp(H.sinfo(1).texture,'defects') && ... + ( (~isempty(textures) && ~strcmp(textures.Label,'none')) || ... + (~isempty(atlases) && ~strcmp(atlases.Label,'none')) || ... + (~isempty(H.patch.FaceVertexCData)) ) + colorbar('Position',[.93 0.2 0.02 0.6]); + colormap(getappdata(H.patch(1),'colourmap')); + end + + [pp,ff,ee] = fileparts(H.filename{1}); + %H.text = annotation('textbox','string',[ff ee],'position',[0.0,0.97,0.2,0.03],'LineStyle','none','Interpreter','none'); + %a = get(h,'children'); + %set(a,'Position',get(a,'Position').*[0 0 1 1]+[10 10 0 0]); + for pi=1:numel(H.patch) + if get(H.patch(pi),'LineWidth')>0; set(H.patch(pi),'LineWidth',0.125); end % thin mesh lines, if mesh is visible + end + if isdeployed + deployprint(h, '-dpng', '-opengl',sprintf('-r%d',cat_get_defaults('print.dpi')), fullfile(pathname, filename)); + else + print(h, '-dpng', '-opengl', sprintf('-r%d',cat_get_defaults('print.dpi')), fullfile(pathname, filename)); + end + for pi=1:numel(H.patch) + if get(H.patch(pi),'LineWidth')>0; set(H.patch(pi),'LineWidth',0.5); end % restore mesh default + end + close(h); + set(getappdata(obj,'fig'),'renderer',r); + case 3 + for pi=1:numel(H.patch) + save(gifti(H.patch(pi)),fullfile(pathname, filename),'collada'); + end + case 4 + for pi=1:numel(H.patch) + save(gifti(H.patch(pi)),fullfile(pathname, filename),'idtf'); + end + end +end + +%========================================================================== +function myDeleteFcn(obj,evt,renderer) +try rotate3d(get(obj,'parent'),'off'); end +set(ancestor(obj,'figure'),'Renderer',renderer); + +%========================================================================== +function myOverlay(obj,evt,H) +[P, sts] = spm_select(1,'any','Select file to overlay'); +if ~sts, return; end +cat_surf_render2('Overlay',H,P); + +%========================================================================== +function myChangeMesh(obj,evt,H) +set(get(get(obj,'parent'),'children'),'Checked','off'); +set(obj,'Checked','on'); + +% remove slices ... +oldslices = findobj(get(H.axis,'children'),'type','surf','Tag','volumeSlice'); +delete(oldslices); + +id = find(cellfun('isempty',strfind(H.meshs(:,1),obj.Label))==0); +for i=1:numel(H.patch) + if ischar(H.meshs{id,1+i}) + [pp,ff,ee] = spm_fileparts(H.meshs{id,1+i}); + switch ee + case '.gii' + M = gifti(H.meshs{id,1+i}); + otherwise + M = cat_io_FreeSurfer('read_surf',H.meshs{id,1+i}); + M = gifti(M); + end + H.patch(i).Vertices = M.vertices; + else + H.patch(i).Vertices = H.meshs{id,1+i}; + end +end +%========================================================================== +function myChangeROI(obj,evt,H) +% set checks +mainMenu = get(get(get(obj,'parent'),'parent'),'parent'); +objTextures = findobj(mainMenu,'Label','Textures'); +objAtlases = findobj(mainMenu,'Label','Atlases'); +objROIs = findobj(mainMenu,'Label','ROIs'); +set(get(objTextures,'children'),'Checked','off'); +set(get(objAtlases ,'children'),'Checked','off'); +set(get(objROIs ,'children'),'Checked','off'); +set(obj,'Checked','on'); +set(get(obj,'parent'),'Checked','on'); + +% update colormap and colorrange +objcmap = findobj(get(get(obj,'parent'),'parent'),'Label','Colormap'); +objcrange = findobj(get(get(obj,'parent'),'parent'),'Label','Colorrange'); +if strcmp(get(get(obj,'parent'),'Label'),'Textures') || strcmp(get(get(obj,'parent'),'Label'),'ROIs') + set(objcmap,'Enable','on'); + set(objcrange,'Enable','on'); + myColourmap(findobj(get(objcmap,'children'),'Label','jet'),evt,H) +elseif strcmp(get(get(obj,'parent'),'Label'),'Atlases') + set(objcmap,'Enable','off'); + set(objcrange,'Enable','off'); +end + +%% internal ROIs +atlas = get(get(obj,'parent'),'Label'); +measure = get(obj,'Label'); +if ~isempty(H.RBM.vatlas) && any(~cellfun('isempty',strfind(H.RBM.vatlas,atlas))), ROItype = 'v'; +elseif ~isempty(H.RBM.satlas) && any(~cellfun('isempty',strfind(H.RBM.satlas,atlas))), ROItype = 's'; +end + +% names +fileFD = [ROItype 'labelfile']; +atlasFD = [ROItype 'catROI']; + +%% +if isstruct(H.RBM.(atlasFD).(atlas)) + rID = H.RBM.(atlasFD).(atlas).ids; + rname = H.RBM.(atlasFD).(atlas).names; + rdata = H.RBM.(atlasFD).(atlas).data.(measure); +else % volume + rID = H.RBM.(atlasFD).ROI.(atlas)(2:end,1); + rname = H.RBM.(atlasFD).ROI.(atlas)(2:end,2); + if 2+measureID < size(H.RBM.(atlasFD).ROI.(atlas),2) + rdata = cell2mat(H.RBM.(atlasFD).ROI.(atlas)(2:end,2+measureID)); + else + rdata = nan(size(rname)); + end +end + + +%% hier muss ich den atlas haben ... frage ist ob ich den dynamisch hier +% lade oder einfach einmal am anfang? +aID = find(0==cellfun('isempty',strfind(lower(H.atlases(:,2)),lower(atlas))),1); +aID = find(0==cellfun('isempty',strfind(lower(H.textures(:,1)),lower(H.atlases(aID,1)))),1); + +% update data +for fi=1:numel(H.filename) + %% + sinfo = cat_surf_info(H.filename(fi)); + cdata = H.cdata; + + if ~isempty(H.textures{aID,2}) + ainfo = H.textures{aID,2}; + switch ainfo.ee + case '.gii' + M = gifti(ainfo.fname); + adata = M.cdata; + case '.annot' + [fsv,adata,colortable] = cat_io_FreeSurfer('read_annotation',ainfo.fname); clear fsv colortable; + otherwise + adata = cat_io_FreeSurfer('read_surf_data',ainfo.fname); + end + end + + cdata(adata==0) = nan; + for roii=1:size(rname,1) + if rname{roii}(1)==sinfo(1).side(1) + cdata(adata==rID(roii)) = rdata(roii); + end + end + + set(H.patch(fi),'cdata',cdata); +end + +setappdata(H.patch(1),'data',cdata); +cat_surf_render2('Colourbar',H,'off'); +cat_surf_render2('Colourbar',H,'on'); +myCaxis(obj,evt,H,'1p') +set(H.figure,'Name',spm_file(sprintf('%s|%s|%s',H.RBM.(fileFD){1},atlas,measure),'short80')); + + +%========================================================================== +function myChangeTexture(obj,evt,H) +% set checks +objTextures = findobj(get(get(obj,'parent'),'parent'),'Label','Textures'); +objAtlases = findobj(get(get(obj,'parent'),'parent'),'Label','Atlases'); +objROIs = findobj(get(get(obj,'parent'),'parent'),'Label','ROIs'); +set(get(objTextures,'children'),'Checked','off'); +set(get(objAtlases ,'children'),'Checked','off'); +set(get(objROIs ,'children'),'Checked','off'); +set(obj,'Checked','on'); + +% update colormap and colorrange +objcmap = findobj(get(get(obj,'parent'),'parent'),'Label','Colormap'); +objcrange = findobj(get(get(obj,'parent'),'parent'),'Label','Colorrange'); +if strcmp(get(get(obj,'parent'),'Label'),'Textures') || strcmp(get(get(obj,'parent'),'Label'),'ROIs') + set(objcmap,'Enable','on'); + set(objcrange,'Enable','on'); +elseif strcmp(get(get(obj,'parent'),'Label'),'Atlases') + set(objcmap,'Enable','off'); + set(objcrange,'Enable','off'); +end + +id = find(strcmp(H.textures(:,1),obj.Label)); +if isempty(id) + updateTexture(H,[]); + cat_surf_render2('Colourbar',H,'off'); + set(objcmap,'Enable','off'); + set(objcrange,'Enable','off'); + return +end +for pi=1:numel(H.patch) + if isstruct(H.textures{id,1+pi}) + [pp,ff,ee] = spm_fileparts(H.textures{id,1+pi}.fname); + switch ee + case '.gii' + M = gifti(H.textures{id,1+pi}.fname); + case '.annot' + %% + labelmap = zeros(0); labelnam = cell(0); labelmapclim = zeros(1,2); labeloid = zeros(0); labelid = zeros(0); nid=1; + + [fsv,cdatao,colortable] = cat_io_FreeSurfer('read_annotation',H.textures{id,2}.fname); clear fsv; + cdata = zeros(size(cdatao)); + + entries = unique(cdatao); + for ei = 1:numel(entries) + cid = find( labeloid == entries(ei) ,1); % previous imported label? + if ~isempty(cid) % previous imported label + cdata( round(cdatao) == entries(ei) ) = labelid(cid); + else + idx = find( colortable.table(:,5)==entries(ei) , 1); + if ~isempty(idx) + cdata( round(cdatao) == entries(ei) ) = nid; + labelmap(nid,:) = colortable.table(idx,1:3)/255; + labelnam(nid) = colortable.struct_names(idx); + labelnam(nid) = strrep( labelnam(nid) , '_' , ' '); %'\_' ); + labelnam{nid} = [labelnam{nid} sprintf(' [%d]',entries(ei))]; + labeloid(nid) = entries(ei); + labelid(nid) = nid; + labelmapclim(2) = nid; + nid = nid+1; + end + end + end + + setappdata(H.patch(pi),'data',cdata); + set(H.patch(pi),'cdata',cdata); + setappdata(H.patch(pi),'colourmap',labelmap); + cat_surf_render2('clim',H.axis,labelmapclim); + %% colormap(labelmap); %caxis(labelmapclim - [1 0]); + H2.colourbar = findobj(get(H.figure,'children'),'type','colorbar'); + if isempty(H2.colourbar) %strcmp(get(findobj(H.figure,'Label','Colorbar'),'checked'),'off') + H2 = cat_surf_render2('ColorBar',H.axis,'on'); + end + H2.colourbar.Limits = labelmapclim; + colormap(H2.colourbar,[labelmap(2:end,:);labelmap(1,:)]) + H2.colourbar.TickLength = 0; + labelnam2 = labelnam; for lni=1:numel(labelnam2),labelnam2{lni} = [' ' labelnam2{lni} ' ']; end + %% labelnam2(end+1) = {''}; labelnam2(end+1) = {''}; + labellength = min(100,max(cellfun('length',labelnam2))); + ss = 1; %max(1,round(diff(labelmapclim+1)/30)); + ytick = labelmapclim(1)-0.5:ss:labelmapclim(2)+0.5; + set(H2.colourbar,'ytick',ytick,'yticklabel',labelnam2(1:ss:end),... + 'Position',[max(0.75,0.98-0.01*labellength) 0.05 0.02 0.9]); + try, set(H.colourbar,'TickLabelInterpreter','none'); end + set(H.axis,'Position',[0.1 0.1 min(0.8,max(0.6,0.8-0.01*labellength)) 0.8]) + H.labelmap = struct('colormap',labelmap,'ytick',ytick,'labelnam2',{labelnam2}); + setappdata(H.axis,'handles',H); + + + + + %% + return + %labelnam = colortable.struct_names(id); + otherwise + M = cat_io_FreeSurfer('read_surf_data',H.textures{id,2}.fname); + M = gifti(struct('cdata',double(M))); + end + setappdata(H.patch(pi),'data',M.cdata); + set(H.patch(pi),'cdata',M.cdata); + %% colormap(labelmap); %caxis(labelmapclim - [1 0]); + H2.colourbar = findobj(get(H.figure,'children'),'type','colorbar'); + if ~isempty(H2.colourbar), delete(H2.colourbar); end + H2.colourbar = findobj(get(H.figure,'children'),'type','ContextMenu'); + if isempty(H2.colourbar) %strcmp(get(findobj(H.figure,'Label','Colorbar'),'checked'),'off') + H2 = cat_surf_render2('ColorBar',H.axis); + else + + end + cat_surf_render2('Colormap',H.axis,jet); + %{ + menu = findobj(get(H.figure,'children'),'type','uicontextmenu'); + colourbarmenu = get(findobj(menu.Children,'Label','Colormap'),'Children'); + set(findobj(colourbarmenu,'Label','jet'),'Checked','On'); + setappdata(H.patch(pi),'colourmap',jet); + colormap(H2.colourbar,jet) + %} + set(H.axis,'Position',[0.1 0.1 0.8 0.8]); + + if H.textures{id,1+pi}.smoothed==0 + myCaxis(obj,evt,H,'1p') + else + myCaxis(obj,evt,H,'min-max') + end + set(H.figure,'Name',spm_file(H.textures{id,1+pi}.fname,'short80')); + end +end + +%========================================================================== +function myUnderlay(obj,evt,H) +[P, sts] = spm_select(1,'any','Select texture file to underlay',{},fullfile(fileparts(mfilename('fullpath')),'templates_surfaces'),'[lr]h.mc.*'); +if ~sts, return; end +cat_surf_render2('Underlay',H,P); + +%========================================================================== +function myImageSections(obj,evt,H,fname) +if ~exist('fname','var'), fname = []; end +ffile = zeros(size(H.niftis(:,1))); +for i=1:numel(ffile) + ffile(i) = strcmp(H.niftis(i,1),get(obj,'Label')); +end +if any(ffile) + renderSlices2(H,H.niftis(find(ffile,1,'first'),2)); +elseif ~strcmp(fname,'none') + if isempty(fname) + [P, sts] = spm_select(1,'image','Select image to render'); + else + [P, sts] = spm_select(1,'image','Select image to render',[],fileparts(fname)); + end + if ~sts, return; end + renderSlices2(H,P); +else + % remove old slices ... + oldslices = findobj(get(H.axis,'children'),'type','surf','Tag','volumeSlice'); + delete(oldslices); +end + +%========================================================================== +function myChangeGeometry(obj,evt,H) +[P, sts] = spm_select(1,'mesh','Select new geometry mesh'); +if ~sts, return; end +G = gifti(P); + +% remove slices ... +oldslices = findobj(get(H.axis,'children'),'type','surf','Tag','volumeSlice'); +delete(oldslices); + +if size(get(H.patch(1),'Vertices'),1) ~= size(G.vertices,1) + error('Number of vertices must match.'); +end +set(H.patch(1),'Vertices',G.vertices) +set(H.patch(1),'Faces',G.faces) +view(H.axis,[-90 0]); + +%========================================================================== +function renderSlices(H,P,pls) +if nargin <3 + pls = 0.05:0.2:0.9; +end +N = nifti(P); +d = size(N.dat); +pls = round(pls.*d(3)); +hold(H.axis,'on'); +for i=1:numel(pls) + [x,y,z] = ndgrid(1:d(1),1:d(2),pls(i)); + f = N.dat(:,:,pls(i)); + x1 = N.mat(1,1)*x + N.mat(1,2)*y + N.mat(1,3)*z + N.mat(1,4); + y1 = N.mat(2,1)*x + N.mat(2,2)*y + N.mat(2,3)*z + N.mat(2,4); + z1 = N.mat(3,1)*x + N.mat(3,2)*y + N.mat(3,3)*z + N.mat(3,4); + surf(x1,y1,z1, repmat(f,[1 1 3]), 'EdgeColor','none', ... + 'Clipping','off', 'Parent',H.axis); +end +hold(H.axis,'off'); +axis(H.axis,'image'); + +%========================================================================== +function renderSlices2(H,P,pls) +N = nifti(P); +d = size(N.dat); +AC = inv(N.mat) * [0;0;0;1]; AC = AC(1:3)'; +if nargin <3 + pls = AC; + voxel = AC; +else + voxel = pls; +end +pls = round(pls); %.*d(3)); +pls = max(ones(1,3),min(d,pls)); + +% remove old slices ... +oldslices = findobj(get(H.axis,'children'),'type','surf','Tag','volumeSlice'); +delete(oldslices); + +% default intensity range +irange = cat_vol_iscaling(N.dat(:),[0.05 0.95]); +trange = [ (irange(1) + diff(irange)*0.2) (irange(1) + diff(irange)*0.5)]; + +zoom reset; +hold(H.axis,'on'); +% render new slices +if ~isinf(pls(1)) && ~isnan(pls(1)) && pls(1)>=1 &&pls(1)<=d(1) + [x,y,z] = ndgrid(pls(1),1:d(2),1:d(3)); + f = N.dat(pls(1),:,:); + fd = (f-irange(1)) / abs(diff(irange)); + ft = (f-trange(1)) / abs(diff(trange)); + x1 = N.mat(1,1)*x + N.mat(1,2)*y + N.mat(1,3)*z + N.mat(1,4); + y1 = N.mat(2,1)*x + N.mat(2,2)*y + N.mat(2,3)*z + N.mat(2,4); + z1 = N.mat(3,1)*x + N.mat(3,2)*y + N.mat(3,3)*z + N.mat(3,4); + s1 = surf(shiftdim(x1),shiftdim(y1),shiftdim(z1),repmat(shiftdim(fd),[1 1 3]),... + 'EdgeColor','none','Clipping','off', 'Parent',H.axis,'Tag','volumeSlice'); + set(s1,'AmbientStrength',1,'DiffuseStrength',0,'SpecularStrength',0,'SpecularExponent',1); + set(s1,'AlphaData',shiftdim(ft),'FaceAlpha','flat','alphaDataMapping','none'); + set(s1,'UserData',struct('fname',P,'AC',AC,'voxel',voxel)); +end +if ~isinf(pls(1)) && ~isnan(pls(1)) && pls(1)>=1 &&pls(1)<=d(1) + [x,y,z] = ndgrid(1:d(1),pls(2),1:d(3)); + f = N.dat(:,pls(2),:); + fd = (f-irange(1)) / abs(diff(irange)); + ft = (f-trange(1)) / abs(diff(trange)); + x1 = N.mat(1,1)*x + N.mat(1,2)*y + N.mat(1,3)*z + N.mat(1,4); + y1 = N.mat(2,1)*x + N.mat(2,2)*y + N.mat(2,3)*z + N.mat(2,4); + z1 = N.mat(3,1)*x + N.mat(3,2)*y + N.mat(3,3)*z + N.mat(3,4); + s2 = surf(shiftdim(x1,2),shiftdim(y1,2),shiftdim(z1,2),repmat(shiftdim(fd,2),[1 1 3]), ... + 'EdgeColor','none','Clipping','off', 'Parent',H.axis,'Tag','volumeSlice'); + set(s2,'AmbientStrength',1,'DiffuseStrength',0,'SpecularStrength',0,'SpecularExponent',1); + set(s2,'AlphaData',shiftdim(ft,2),'FaceAlpha','flat','alphaDataMapping','none'); + set(s2,'UserData',struct('fname',P,'AC',AC,'voxel',voxel)); +end +if ~isinf(pls(1)) && ~isnan(pls(1)) && pls(1)>=1 &&pls(1)<=d(1) + [x,y,z] = ndgrid(1:d(1),1:d(2),pls(3)); + f = N.dat(:,:,pls(3)); + fd = (f-irange(1)) / abs(diff(irange)); + ft = (f-trange(1)) / abs(diff(trange)); + x1 = N.mat(1,1)*x + N.mat(1,2)*y + N.mat(1,3)*z + N.mat(1,4); + y1 = N.mat(2,1)*x + N.mat(2,2)*y + N.mat(2,3)*z + N.mat(2,4); + z1 = N.mat(3,1)*x + N.mat(3,2)*y + N.mat(3,3)*z + N.mat(3,4); + s3 = surf(x1,y1,z1, repmat(fd,[1 1 3]), ... + 'EdgeColor','none','Clipping','off', 'Parent',H.axis,'Tag','volumeSlice'); + set(s3,'AmbientStrength',1,'DiffuseStrength',0,'SpecularStrength',0,'SpecularExponent',1); + set(s3,'AlphaData',ft,'FaceAlpha','flat','alphaDataMapping','none'); + set(s3,'UserData',struct('fname',P,'AC',AC,'voxel',voxel)); +end +hold(H.axis,'off'); +axis(H.axis,'image'); +zoom out; + +%========================================================================== +function C = updateTexture(H,v,pis)%$,FaceColor) +if ~exist('pis','var'), pis = 1:numel(H.patch); end +for pi=pis + %-Get colourmap + %-------------------------------------------------------------------------- + if ~exist('col','var'), col = getappdata(H.patch(pi),'colourmap'); end + if isempty(col), col = hot(256); end + if ~exist('FaceColor','var'), FaceColor = 'interp'; end + setappdata(H.patch(pi),'colourmap',col); + + %-Get curvature + %-------------------------------------------------------------------------- + curv = getappdata(H.patch(pi),'curvature'); + + if size(curv,2) == 1 + th = 0.15; + curv((curv<-th)) = -th; + curv((curv>th)) = th; + curv = 0.5*(curv + th)/(2*th); + curv = 0.5 + repmat(curv,1,3); + end + + %-Project data onto surface mesh + %-------------------------------------------------------------------------- + if nargin < 2, v = []; end + if ischar(v) + [p,n,e] = fileparts(v); + if ~strcmp(e,'.mat') && ~strcmp(e,'.nii') && ~strcmp(e,'.gii') && ~strcmp(e,'.img') % freesurfer format + v = cat_io_FreeSurfer('read_surf_data',v); + else + if strcmp([n e],'SPM.mat') + swd = pwd; + spm_figure('GetWin','Interactive'); + [SPM,v] = spm_getSPM(struct('swd',p)); + cd(swd); + else + try spm_vol(v); catch, v = gifti(v); end; + end + end + end + if isa(v,'gifti'), v = v.cdata; end + if isa(v,'file_array'), v = v(); end + if isempty(v) + v = zeros(size(curv))'; + elseif ischar(v) || iscellstr(v) || isstruct(v) + v = spm_mesh_project(H.patch(pi),v); + elseif isnumeric(v) || islogical(v) + if size(v,2) == 1 + v = v'; + end + else + error('Unknown data type.'); + end + v(isinf(v)) = NaN; + + setappdata(H.patch(pi),'data',v); + + %-Create RGB representation of data according to colourmap + %-------------------------------------------------------------------------- + C = zeros(size(v,2),3); + clim = getappdata(H.patch(pi), 'clim'); + if isempty(clim), clim = [false NaN NaN]; end + mi = clim(2); ma = clim(3); + if any(v(:)) + if size(col,1)>3 && size(col,1) ~= size(v,1) + if size(v,1) == 1 + if ~clim(1), mi = min(v(:)); ma = max(v(:)); end + C = squeeze(ind2rgb(floor(((v(:)-mi)/(ma-mi))*size(col,1)),col)); + elseif isequal(size(v),[size(curv,1) 3]) + C = v; v = v'; + else + if ~clim(1), mi = min(v(:)); ma = max(v(:)); end + for i=1:size(v,1) + C = C + squeeze(ind2rgb(floor(((v(i,:)-mi)/(ma-mi))*size(col,1)),col)); + end + end + else + if ~clim(1), ma = max(v(:)); end + for i=1:size(v,1) + C = C + v(i,:)'/ma * col(i,:); + end + end + end + + clip = getappdata(H.patch(pi), 'clip'); + if ~isempty(clip) + v(v>clip(2) & vBrian Amberg, 2008 +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ +","MATLAB" +"Neurology","ChristianGaser/cat12","optimizer3d.c",".c","62734","1832","/* ______________________________________________________________________ + * + * Christian Gaser, Robert Dahnke + * Structural Brain Mapping Group (https://neuro-jena.github.io) + * Departments of Neurology and Psychiatry + * Jena University Hospital + * ______________________________________________________________________ + * $Id$ + * (c) John Ashburner (2007) */ + +#include +#include +extern double log(double x); + +#include ""optimizer3d.h"" + +#ifdef NEUMANN + /* Neumann boundary condition */ + static int neumann(int i, int m) + { + if (m==1) + return(0); + else + { + int m2 = m*2; + i = (i<0) ? (-i-m2*((-i)/m2)-1) : (i-m2*(i/m2)); + if (m<=i) + return(m2-i-1); + else + return(i); + } + } +# define BOUND(i,m) neumann(i,m) +#else + /* circulant boundary condition */ +# define BOUND(i,m) (((i)>=0) ? (i)%(m) : ((m)+(i)%(m))%m) +#endif + +static double sumsq_le_noa(int dm[], float b[], double s[], float u[]) +{ + double ss = 0.0; + int k; + double mu = s[3], lam = s[4], id = s[5]; + double wx0, wx1, wx2, wy0, wy1, wy2, wz0, wz1, wz2, wxy, wxz, wyz; + + wx0 = 2*mu*(s[1]*s[1]+s[2]*s[2])+(4*mu+2*lam)*s[0]*s[0] + id; + wy0 = 2*mu*(s[0]*s[0]+s[2]*s[2])+(4*mu+2*lam)*s[1]*s[1] + id; + wz0 = 2*mu*(s[0]*s[0]+s[1]*s[1])+(4*mu+2*lam)*s[2]*s[2] + id; + + wx1 = -(2*mu+lam)*s[0]*s[0]; + wy1 = -(2*mu+lam)*s[1]*s[1]; + wz1 = -(2*mu+lam)*s[2]*s[2]; + + wx2 = -mu*s[0]*s[0]; + wy2 = -mu*s[1]*s[1]; + wz2 = -mu*s[2]*s[2]; + + wxy = 0.25*(lam+mu)*s[0]*s[1]; + wxz = 0.25*(lam+mu)*s[0]*s[2]; + wyz = 0.25*(lam+mu)*s[1]*s[2]; + + for(k=0; k>1)&1; j>2)&1; i>1)&1; j>2)&1; i tol*norm(b), + p = r + beta*p; + Ap = A*p; + alpha = rtr/(p'*Ap); + x = x + alpha*p; + r = r - alpha*Ap; + rtrold = rtr; + rtr = r'*r; + beta = rtr/rtrold; + + it = it+1; + if it>nit, break; end; +end; +*/ + +void cgs3(int dm[], float A[], float b[], int rtype, double param[], double tol, int nit, + float x[], float r[], float p[], float Ap[]) +{ + int i, m = dm[0]*dm[1]*dm[2]*3, it; + double rtr, nb, rtrold, alpha, beta; + void (*Atimesp)(); + + /* printf(""\n **** %dx%d ****\n"",dm[0],dm[1]); */ + if (rtype == 0) + Atimesp = Atimesp_le; + else if (rtype == 1) + Atimesp = Atimesp_me; + else + Atimesp = Atimesp_be; + + nb = tol*norm(m,b); + +# ifdef NEVER + /* Assuming starting estimates of zeros */ + /* x = zeros(size(b)); */ + for(i=0; i=0; j--) + { + int jc; + prolong(3,n[j+1],u[j+1],n[j],u[j],rbuf); + if(j>0) copy(3*m[j],bo[j],b[j]); + for(jc=0; jc=j; jj--) + { + prolong(3,n[jj+1],u[jj+1],n[jj],res,rbuf); + addto(3*m[jj], u[jj], res); + relax(n[jj], a[jj], b[jj], param[jj], nit, u[jj]); + } + } + } + } + else + { + int jc; + for(j=1; j=0; jj--) + { + prolong(3,n[jj+1],u[jj+1],n[jj],res,rbuf); + addto(3*m[jj], u[jj], res); + relax(n[jj], a[jj], b[jj], param[jj], nit, u[jj]); + } + } + } + /* printf(""end=%g\n"", sumsq(n0, a0, b0, param[0], u0)); */ +} + +int fmg3_scratchsize_noa(int n0[]) +{ + int n[32][3], m[32], bs, j; + bs = 0; + n[0][0] = n0[0]; + n[0][1] = n0[1]; + n[0][2] = n0[2]; + + for(j=1; j<16; j++) + { + n[j][0] = ceil(n[j-1][0]/2.0); + n[j][1] = ceil(n[j-1][1]/2.0); + n[j][2] = ceil(n[j-1][2]/2.0); + m[j] = n[j][0]*n[j][1]*n[j][2]; + bs += m[j]; + if ((n[j][0]<2) && (n[j][1]<2) && (n[j][2]<2)) + break; + } + return((3*n0[0]*n0[1]*n0[2] + n[0][0]*n[1][1]+3*n[0][0]*n[0][1] + 9*bs)); +} + +/* + Full Multigrid solver. See Numerical Recipes (second edition) for more + information +*/ +void fmg3_noa(int n0[], float *b0, int rtype, double param0[], int c, int nit, + float *u0, float *scratch) +{ + int i, j, ng, bs; + int n[32][3], m[32]; + float *bo[32], *b[32], *u[32], *res, *rbuf; + double param[32][6]; + void (*relax)(), (*LtLf)(); + double (*sumsq)(); + + if (rtype == 0) + { + relax = relax_le_noa; + LtLf = LtLf_le; + sumsq = sumsq_le_noa; + } + else + return; + + bo[0] = b0; + b[0] = b0; + u[0] = u0; + n[0][0] = n0[0]; + n[0][1] = n0[1]; + n[0][2] = n0[2]; + m[0] = n0[0]*n0[1]*n0[2]; + param[0][0] = param0[0]; + param[0][1] = param0[1]; + param[0][2] = param0[2]; + param[0][3] = param0[3]; + param[0][4] = param0[4]; + param[0][5] = param0[5]; + + ng = 1; + bs = 0; + for(j=1; j<16; j++) + { + n[j][0] = ceil(n[j-1][0]/2.0); + n[j][1] = ceil(n[j-1][1]/2.0); + n[j][2] = ceil(n[j-1][2]/2.0); + m[j] = n[j][0]*n[j][1]*n[j][2]; + ng ++; + bs += m[j]; + if ((n[j][0]<2) && (n[j][1]<2) && (n[j][2]<2)) + break; + } + + res = scratch; + rbuf = scratch + 3*m[0]; + bo[1] = scratch + 3*m[0] + n[0][0]*n[1][1]+3*n[0][0]*n[0][1]; + b[1] = scratch + 3*m[0] + n[0][0]*n[1][1]+3*n[0][0]*n[0][1] + 3*bs; + u[1] = scratch + 3*m[0] + n[0][0]*n[1][1]+3*n[0][0]*n[0][1] + 6*bs; + + for(j=2; j=0; j--) + { + int jc; + prolong(3,n[j+1],u[j+1],n[j],u[j],rbuf); + if(j>0) copy(3*m[j],bo[j],b[j]); + for(jc=0; jc=j; jj--) + { + prolong(3,n[jj+1],u[jj+1],n[jj],res,rbuf); + addto(3*m[jj], u[jj], res); + relax(n[jj], b[jj], param[jj], nit, u[jj]); + } + } + } + } + else + { + int jc; + for(j=1; j=0; jj--) + { + prolong(3,n[jj+1],u[jj+1],n[jj],res,rbuf); + addto(3*m[jj], u[jj], res); + relax(n[jj], b[jj], param[jj], nit, u[jj]); + } + } + } +} + +","C" +"Neurology","ChristianGaser/cat12","cat_surf_createCS2.m",".m","96812","1892","function [Yth,S,P,EC,defect_size,res] = cat_surf_createCS2(V,V0,Ym,Ya,YMF,Ytemplate,opt,job) +% ______________________________________________________________________ +% Surface creation and thickness estimation. +% +% [Yth1,S,P,EC]=cat_surf_createCS2(V,V0,Ym,Ya,YMF,Ytemplate,opt) +% +% Yth1 .. thickness map +% S .. structure with surfaces, like the left hemisphere, that contains +% vertices, faces, GM thickness (th1) +% Psurf .. name of surface files +% EC .. Euler characteristic +% defect_size .. size of topology defects +% res .. intermediate and final surface creation information +% V .. spm_vol-structure of internally interpolated image +% V0 .. spm_vol-structure of original image +% Ym .. the (local) intensity, noise, and bias corrected T1 image +% Ya .. the atlas map with the ROIs for left and right hemispheres +% (this is generated with cat_vol_partvol) +% YMF .. a logical map with the area that has to be filled +% (this is generated with cat_vol_partvol) +% Ytemplate .. Shooting template to improve cerebellar surface +% reconstruction +% +% opt.surf = {'lh','rh'[,'lc','rc']} - side +% .reduceCS = 100000 - number of faces +% +% Options set by cat_defaults.m +% .interpV = 0.5 - mm-resolution for thickness estimation +% +% Here we used the intensity normalized image Ym, rather that the Yp0 +% image, because it has more information about sulci that we need +% especially for asymmetrical sulci. +% Furthermore, all non-cortical regions and blood vessels were removed +% (for left and right surface). Blood vessels (with high contrast) can +% lead to strong error in the topology correction. Higher resolution +% also helps to reduce artifacts. +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +%#ok<*AGROW,*STREMP,*ASGLU,*SFLD,*STFLD> +%#ok<*CLOCK,*DETIM> + + % Turn off gifti data warning in gifti/subsref (line 45) + % Warning: A value of class ""int32"" was indexed with no subscripts specified. + % Currently the result of this operation is the indexed value itself, + % but in a future release, it will be an error. + warning('off','MATLAB:subscripting:noSubscriptsSpecified'); + cstime = clock; + + if strcmpi(spm_check_version,'octave') + cat_io_addwarning('cat_surf_createCS2:noSRP','Correction of surface collisions is not yet available under Octave.',2,[1 1]) + opt.SRP = 0; + end + + % set debugging variable + dbs = dbstatus; debug = 0; for dbsi=1:numel(dbs), if strcmp(dbs(dbsi).name,mfilename); debug = 1; break; end; end + S = struct(); + + % set defaults + if ~exist('opt','var'), opt = struct(); end % create variable if not exist + vx_vol = sqrt(sum(V.mat(1:3,1:3).^2)); % further interpolation based on internal resolution + def.verb = cat_get_defaults('extopts.expertgui'); % 0-none, 1-minimal, 2-default, 3-details, 4-debug + def.surf = {'lh','rh'}; % surface reconstruction setting with {'lh','rh','cb'} + % reducepatch has some issues with self intersections + % There is a new SPM approach spm_mesh_reduce that is maybe more robust. + % Higher resolution is at least required for animal preprocessing that is given by cat_main. + def.LAB = cat_get_defaults('extopts.LAB'); % brain regions + def.pbtmethod = 'pbtsimple'; % projection-based thickness (PBT) estimation ('pbt2x' (with minimum setting), 'pbt2', or 'pbtsimple') + def.sharpenCB = 1; % sharpening function for the cerebellum (in development, RD2017-2019) + def.thick_measure = 0; % 0-PBT; 1-Tfs (Freesurfer method using mean(TnearIS,TnearOS)) + def.foldingcorrection = 0; % tickness correction that is influence by folding + def.thick_limit = 5; % 5mm upper limit for thickness (same limit as used in Freesurfer) + def.SRP = 2; % correction of surface collisions: 0 - none; 1 - SI, 2 - SIC with optimization + def.surf_measures = 1; % 0 - none, 1 - only thickness, 2 - expert maps (myelin,defects), 3 - developer (WM & CSF thicknes, ...), + % 4 - debug output, 5 - debug extended (more substeps and mex output) + def.fsavgDir = fullfile(fileparts(mfilename('fullpath')),'templates_surfaces'); + def.add_parahipp = cat_get_defaults('extopts.add_parahipp'); + def.scale_cortex = cat_get_defaults('extopts.scale_cortex'); + def.close_parahipp = cat_get_defaults('extopts.close_parahipp'); + def.localsmooth = 1; % 0 - no smoothing, 1 - smoothing areas with high change of self-intersections (~ high curvature*thickness*sampling) + def.reduce_mesh = 1; % 0 - surface creation on PBT resolution, no mesh-reduction (very slow) + % 1 - optimal resolution depending on final mesh resolution, no mesh-reduction + % 2 - internal resolution, no mesh-reduction (slow for highres data) + % 3/4 - SPM/MATLAB reduce on initial surface - there seems to be a bug in the c-function that kills matlab + % 5/6 - SPM/MATLAB reduce on initial and final surface - there seems to be a bug in the c-function that kills matlab + % 7 - call matlab reduce in external matlab + def.outputpp.native = 0; % output of Ypp map for cortical orientation in EEG/MEG + def.outputpp.warped = 0; + def.outputpp.dartel = 0; + + % options that rely on other options + opt = cat_io_updateStruct(def,opt); clear def; + opt.vol = any(~cellfun('isempty',strfind(opt.surf,'v'))); % only volume-based thickness estimation + opt.surf = cat_io_strrep(opt.surf,'v',''); % after definition of the 'vol' variable we simplify 'surf' + opt.interpV = max(0.1,min([opt.interpV,1.5])); % general limitation of the PBT resolution + + + % distance between vertices that can be set directly by ""vdist"" or indirectly by ""interpV"" + % - surface should have more than 80k faces to look nice, whereas more than 400k does not improve the visual quality + % - controlled by power function to avoid a quadratic grow of the number of faces + % - vdisto = [4 2 1 0.5] => [100k 200k 400k 800k] faces + % - vdisto .. 4/3 as default maybe to slow + %max( 0.5 , min( 2 , min( opt.interpV , mean(vx_vol0) ))); % use square to use sqrt in general + if ~isfield(opt,'vdist') || opt.vdist == 0, opt.vdist = 4/3; end + opt.vdisto = opt.vdist; + opt.vdist = sqrt(opt.vdist * 2); % here we use the sqrt to support linear mesh resolution increase (default input is [4 2 1 0.5]) + + % Another parameter to control runtime is the accuracy of the surface + % deformation. As far as we primary adapt the mesh resolution above, it + % is useful to use sqrt values rather than linear values to avoid square + % processing times for higher quality levels. Otherwise, we can simple + % avoid changes here ... so we can define this parameter utilizing the + % vdist parameter by simply divide it by 100. + def.reduceCS = (300000 * sqrt(4/3 * 2) ) ./ opt.vdist; % to test ... fprintf('%g ',300000 * sqrt(1.3*2) ./ (( [4 2 1.3 1 0.5] * 2).^0.5)) + opt = cat_io_updateStruct(def,opt); + + if opt.surf_measures > 4, opt.verb = 3; end + + % function to estimate the number of interactions of the surface deformation: d=distance in mm and a=accuracy + QMC = cat_io_colormaps('marks+',17); + color = @(m) QMC(max(1,min(size(QMC,1),round(((m-1)*3)+1))),:); + rate = @(x,best,worst) min(6,max(1, max(0,x-best) ./ (worst-best) * 5 + 1)); + + + % some internal overview for developers + if opt.verb>2 + fprintf('\nSurface reconstruction: %s\n',.... + sprintf('%s',char( cellfun(@(x) [x ' '],opt.surf,'UniformOutput',0) )')); + fprintf(' PBT resolution: %0.3f\n',opt.interpV); + fprintf(' lower face limit: %g\n',opt.reduceCS); + fprintf(' maximal vertex distance: %0.3f mm\n',opt.vdist); + fprintf(' SRP / reduce_mesh: %d / %d',20 + opt.SRP,opt.reduce_mesh); + end + + if exist('job','var') + [mrifolder, reportfolder, surffolder, labelfolder] = cat_io_subfolders(V0.fname,job); + else + [mrifolder, reportfolder, surffolder, labelfolder] = cat_io_subfolders(V0.fname); + end + + % get original filename without 'n' + [pp0,ff] = spm_fileparts(V0.fname); + + % correct '../' parts in directory for BIDS structure + [stat, val] = fileattrib(fullfile(pp0,surffolder)); + if stat + pp0_surffolder = val.Name; + else + pp0_surffolder = fullfile(pp0,surffolder); + end + if ~exist(fullfile(pp0_surffolder),'dir'), mkdir(fullfile(pp0_surffolder)); end + + + %% get both sides in the atlas map + NS = @(Ys,s) Ys==s | Ys==s+1; + + % noise reduction for higher resolutions (>=1 mm full correction, 1.5 mm as lower limit) + % (added 20160920 ~R1010 due to severe sulcus reconstruction problems with 1.5 Tesla data) + Yms = Ym + 0; cat_sanlm(Yms,3,1); + mf = min(1,max(0,3-2*mean(vx_vol,2))); + Ym = mf * Yms + (1-mf) * Ym; + clear Yms; + + % filling + Ymf = cat_surf_createCS_fun('fillVentricle',Ym,Ym*0,Ya,YMF,vx_vol); + %{ + Ymf = max(Ym,min(1,YMF & ~NS(Ya,opt.LAB.HC) & ~( cat_vol_morph( NS(Ya,opt.LAB.HC),'dd',2,vx_vol) ))); + Ymfs = cat_vol_smooth3X(Ymf,1); + Ytmp = cat_vol_morph(YMF,'dd',3,vx_vol) & Ymfs>2.1/3; + Ymf(Ytmp) = max(min(Ym(Ytmp),0),Ymfs(Ytmp)); clear Ytmp Ymfs; + Ymf = Ymf * 3; + %} + + % removing fine WM structures in the hippocampus area to reduce topological and geometrical defects (added RD20190912) + % use erode to reduce probability of cutting other gyri + HCmask = cat_vol_morph( NS(Ya,opt.LAB.HC) , 'de', 1.5, vx_vol) & ~YMF; % RD202501: open only not filled regions + Ymf( HCmask ) = min(2,Ymf( HCmask )); clear HCmask; + + % surface output and evaluation parameter + res = struct('euler_characteristic',nan,'defect_size',nan,'lh',struct(),'rh',struct()); + % initialize WM/CSF thickness/width/depth maps + Yth = zeros(size(Ymf),'single'); + Ypp = -ones(size(Ymf),'single'); + + + % reduction of artifact, blood vessel, and meninges close to the skull + Ymf = refineYmf(Ymf,Ya,vx_vol,opt,1); % last var = doit + + + % complete atlas map + [D,I] = cat_vbdist(single(Ya>0)); Ya = Ya(I); clear D; + + + % cleanup and smoothing of the hippocampus amygdala to remove high + % frequency structures that we cannot preocess yet + Ymf = hippocampus_amygdala_cleanup(Ymf,Ya,vx_vol,opt.close_parahipp,1); % last var = doit + + + % Sharpening of thin structures in the cerebellum (gyri and sulci) + if opt.sharpenCB && any(~cellfun('isempty',strfind(opt.surf,'cb'))) + Ymf = sharpen_cerebellum(Ym,Ymf,Ytemplate,Ya,vx_vol,opt.verb); + end + + + % use sum of EC's and defect sizes for all surfaces, thus set values initially to 0 + EC = 0; + defect_size = 0; + defect_area = 0; + defect_number = 0; + + % prepare file and directory names + [P,pp0,mrifolder,surffolder,surfdir,ff] = cat_surf_createCS_fun('setFileNames',V0,job,opt); + %[P,pp0,mrifolder,surffolder,surfdir,ff] = setFileNames(V0,job,opt); + + % main loop for each surface structure + for si=1:numel(opt.surf) + + % print something + if si==1, fprintf('\n'); end + fprintf('%s:\n',opt.surf{si}); + + % prepare longitudinal case if required + useprior = cat_surf_createCS_fun('setupprior',opt,surfdir,P,si); + + + %% reduce for object area + switch opt.surf{si} + case {'lh'}, Ymfs = Ymf .* (Ya>0) .* ~(NS(Ya,opt.LAB.CB) | NS(Ya,opt.LAB.BV) | NS(Ya,opt.LAB.ON) | NS(Ya,opt.LAB.MB) | NS(Ya,opt.LAB.BS)) .* (mod(Ya,2)==1); Yside = mod(Ya,2)==1; + case {'rh'}, Ymfs = Ymf .* (Ya>0) .* ~(NS(Ya,opt.LAB.CB) | NS(Ya,opt.LAB.BV) | NS(Ya,opt.LAB.ON) | NS(Ya,opt.LAB.MB) | NS(Ya,opt.LAB.BS)) .* (mod(Ya,2)==0); Yside = mod(Ya,2)==0; + case {'cb'}, Ymfs = Ymf .* (Ya>0) .* NS(Ya,opt.LAB.CB); Yside = true(size(Ymfs)); % new full cerebellum reconstruction + end + + + % check for cerebellar processing + iscerebellum = strcmp(opt.surf{si},'cb'); + if ~iscerebellum + % RD202107: Use atlas and Shooting template information to close the + % hippocampal gyrus but open the hippocampal region. + mask_parahipp = opt.close_parahipp & (NS(Ya,opt.LAB.PH) | NS(Ya,opt.LAB.HC) | NS(Ya,opt.LAB.VT)); + if isempty(Ytemplate) + VT = NS(Ya,opt.LAB.PH) | NS(Ya,opt.LAB.HC); % this does not work but also should not create problems + else + VT = Ytemplate .* NS(Ya,opt.LAB.PH) | NS(Ya,opt.LAB.HC); + end + HC = NS(Ya,opt.LAB.HC); + end + + % removing background (smoothing to remove artifacts) + switch opt.surf{si} + case {'lh','rh'}, [Ymfs,Ysidei,mask_parahipp,VT,HC,BB] = cat_vol_resize({Ymfs,Yside,mask_parahipp,VT,HC},'reduceBrain',vx_vol,4,smooth3(Ymfs)>1.5); + case {'cb'}, [Ymfs,Ysidei,BB] = cat_vol_resize({Ymfs,Yside},'reduceBrain',vx_vol,4,smooth3(Ymfs)>1.5); + end + + % interpolation + imethod = 'cubic'; % cubic should be better in general - however, linear is better for small thickness (version?) + [Ymfs,resI] = cat_vol_resize(max(1,Ymfs),'interp',V,opt.interpV,imethod); % interpolate volume + Ysidei = cat_vol_resize(Ysidei,'interp',V,opt.interpV,imethod)>0.5; % interpolate volume (small dilatation) + + if ~iscerebellum + % get dilated mask of gyrus parahippocampalis and hippocampus of both sides + VT = cat_vol_resize(VT,'interp',V,opt.interpV); + HC = cat_vol_resize(HC,'interp',V,opt.interpV); + mask_parahipp = cat_vol_resize(mask_parahipp,'interp',V,opt.interpV)>0.5; % interpolate volume + end + + % PVE with background will lead to a light underestimation? + Ymfs = min(3,max(1,Ymfs)); + + if opt.close_parahipp && ~iscerebellum + %% RD202107: Additional close of parahippocampus for the WM. + % Dynamic closing size. + tmp = Ymfs>2.5 | (Ymfs/2 .* VT)>1.0; + tmp(smooth3(tmp)<0.3) = 0; + tmp = cat_vol_morph(tmp,'lab'); % remove small dots + tmp = cat_vol_morph(tmp,'close',round(1/opt.interpV)); % close wholes + Ymfs(mask_parahipp) = max(Ymfs(mask_parahipp),2.6 * tmp(mask_parahipp) .* (1-HC(mask_parahipp))); + if ~debug, clear tmp; end + end + + + %% pbt calculation + stime = cat_io_cmd(sprintf(' Thickness estimation (%0.2f mm%s)',opt.interpV,native2unicode(179, 'latin1'))); stimet =stime; + if strcmp(opt.pbtmethod,'pbtsimple') + if opt.SRP>3 + [Yth1i,Yppi] = cat_vol_pbtsimpleCS4(Ymfs,opt.interpV); + else + [Yth1i,Yppi] = cat_vol_pbtsimple(Ymfs,opt.interpV,struct('classic',opt.SRP < 4)); + end + else + [Yth1i,Yppi,Ymfs] = cat_vol_pbt(Ymfs,struct('method',opt.pbtmethod,'resV',opt.interpV,'vmat',... + V.mat(1:3,:)*[0 1 0 0; 1 0 0 0; 0 0 1 0; 0 0 0 1],'pbtlas',0)); % avoid underestimated thickness in gyri + % myelination correction option (in development - not working correctly in all data, RD201907) + end + + % back to internal resolution (at least for thickness) + Yth1i(Yth1i>10) = 0; Yppi(isnan(Yppi)) = -1; % general thickness limit + [D,I] = cat_vbdist(Yth1i,Ysidei); Yth1i = Yth1i(I); clear D I; % add further values around the cortex + Yth1t = cat_vol_resize(Yth1i,'deinterp',resI); % back to original resolution + Yth1t = cat_vol_resize(Yth1t+1,'dereduceBrain',BB)-1; % adding background + Yth = max(Yth,Yth1t .* Yside); % save on main image + if ~debug, clear Yth1t Ysidei; end + + + + %% PBT estimation of the gyrus and sulcus width + if opt.surf_measures > 3 + [Ywdt,Ycdt,stime] = estimateGyrusSulcusWidth(Ymf,Ymfs,Yppi,Ym,Ya,opt,vx_vol,BB,resI,V,si,stime); + end + if ~useprior, fprintf('%5.0fs\n',etime(clock,stime)); end + + + + %% Write Ypp for final deformation + % Ytt has the internal resolution (e.g. <1 mm) and is only used temparary + % Write Yppi file with 1 mm resolution for the final deformation, + % because CAT_DeformSurf achieved better results using that resolution + % RD20210401: The +1 is important to avoid problems with negative + % values and boundary effects with zeros. + %################### + % RD20210401: Why are we using only the 1 and not the 0.5 mm resolution? + % Was there still some resoluion issue or was the interpolation as smoothing helpfull? + Yppt = cat_vol_resize(Yppi + 1,'deinterp',resI); % back to original resolution + Yppt = cat_vol_resize(Yppt,'dereduceBrain',BB) - 1; % adding of background + Ypp(Yppt>-1) = max(Ypp(Yppt>-1),Yppt(Yppt>-1)); + + % this is the map that we want to keep in the original image resolution + Vpp = cat_io_writenii(V0,(Ypp+1)/3,mrifolder,sprintf('%s.pp',opt.surf{si}) ,... + 'percentage position map - V2 - pial=1/3, central=1/2, white=2/3, 0 and 1 to stablize white/pial values','uint8',[0,1/255],...'float32',[0 1],... + min([1 1 2],[1 opt.outputpp.warped opt.outputpp.dartel]),opt.trans); + Vpp = Vpp(1); + + % just an internal map with 1 mm resolution + Vppt = cat_io_writenii(V,Yppt,'',sprintf('%s.ppt',opt.surf{si}) ,... + 'percentage position map - V2 - pial=1/3, central=1/2, white=2/3, 0 and 1 to stablize white/pial values','uint8',[0,1/255],[1 0 0]); %clear Yppt + Vpp1 = Vppt(1); + clear M v x3 Vppt; + + if opt.vol + S = struct(); Psurf = ''; + if opt.verb<2, fprintf('%5.0fs',etime(clock,stime)); end + continue; + end + + + + + time_sr = clock; + %% surface creation + % -------------------------------------------------------------------- + % Surface create should be at 0.5 mm to support a useful description + % in even narrow sulci, i.e., for 1 mm thickness the sulci would be + % 2 mm wide were a 1 mm percentage position map is strongly limited. + % The surface is reconstructed by marching cubes on a binary version + % of the PBT radial position map Yppi to use a simple voxel-based + % topology correction to avoid small defects and incorrect + % triangulation (e.g., matlab isosurface function). Next, the + % complexity of the surface is reduced by the spm_mesh_reduce function + % (more accurate and stable than the matlab reduce function?) to + % improve the performance of the following main topology correction. + % However, the reduction can partially lead to very large faces that + % need an additional refine. + % Voxelbased topology optimization is important for the hippo. gyrus. + % -------------------------------------------------------------------- + if opt.verb==1, fprintf('%s %4.0fs\n',repmat(' ',1,66),etime(clock,stimet)); end + nosurfopt = iscerebellum; %#ok + + % surface coordinate transformation matrix + matI = spm_imatrix(V.mat); + matI(7:9) = sign( matI(7:9)) .* repmat( opt.interpV , 1 , 3); + matiBB = spm_imatrix(V.mat * [eye(4,3) [ (BB.BB([1,3,5])' - 1) ; 1]]); + matIBB = matiBB; + matIBB(7:9) = sign( matiBB(7:9)) .* repmat( opt.interpV , 1 , 3); + Smat.matlabi_mm = V.mat * [0 1 0 0; 1 0 0 0; 0 0 1 0; 0 0 0 1]; % CAT internal space + Smat.matlabI_mm = spm_matrix(matI) * [0 1 0 0; 1 0 0 0; 0 0 1 0; 0 0 0 1]; % PBT interpolated space + Smat.matlabIBB_mm = spm_matrix(matIBB) * [0 1 0 0; 1 0 0 0; 0 0 1 0; 0 0 0 1]; % PBT interpolated + Smat.matlabiBB_mm = spm_matrix(matiBB) * [0 1 0 0; 1 0 0 0; 0 0 1 0; 0 0 0 1]; % PBT interpolated + + + + + if useprior + fprintf('\n'); + stime = cat_io_cmd(' Load and refine subject average surface','g5','',opt.verb); %if opt.verb>2, fprintf('\n'); end + CS = loadSurf(P(si).Pcentral); + else + stime = cat_io_cmd(' Create initial surface','g5','',opt.verb); %if opt.verb>2, fprintf('\n'); end + + % scaling correction to reduce topology errors in the parahippocampus + % ### not tested for cerebellum yet (RD201909) ### + if ~iscerebellum + scale_cortex = opt.scale_cortex; %/0.7 * 0.9; + + ind0 = find(Yppi<=0); + Yppisc = scale_cortex * Yppi; + + % smooth mask to have smooth border + mask_parahipp_smoothed = zeros(size(mask_parahipp)); + spm_smooth(double(mask_parahipp),mask_parahipp_smoothed,[4 4 4] / opt.interpV); + Yppisc = Yppisc + opt.add_parahipp / scale_cortex * mask_parahipp_smoothed; + Yppisc(ind0) = 0; clear ind0; %#ok + + % optionally apply closing inside mask for parahippocampal gyrus to get rid + % of the holes that lead to large cuts in gyri after topology correction + if opt.close_parahipp && ~iscerebellum + tmp = cat_vol_morph(Yppisc .* (mask_parahipp | (Ymfs/2 .* VT)>1) ,'close',round(1/opt.interpV)); + Yppisc(mask_parahipp) = tmp(mask_parahipp) .* (1-HC(mask_parahipp)); + if ~debug, clear tmp; end + end + else + scale_cortex = 0.7; + Yppisc = scale_cortex * Yppi; + end + + if iscerebellum + %% thickness depending cortical scaling - this seems to work but need further tests (RD201911) + % RD202103 ... this changes a lot ! + Yth1i = cat_vol_localstat(Yth1i,Yth1i>0,2,2); + Yts = cat_vol_approx(Yth1i); + Yts = 1 + max(-0.5,min(0.5,(Yts - mean(Yth1i(:))) / (2 * mean(Yth1i(:))) )); + if exist('mask_parahipp_smoothed','var') + Yts = Yts .* (1-mask_parahipp_smoothed) + mask_parahipp_smoothed; % no thickness adaptation in the hippocampus! + end + Yppisc = max(0.55 .* (Yppi>=1),min(1.5, Yppisc .* Yts )); % factor 1 is Ypp at 0.5 > limit 0.55 and 1.5 + scale_cortex = scale_cortex * median( Yts(:) ); + end + clear mask_parahipp_smoothed; + + % we use another scaling and can therefore update this map + Yppisc = Yppisc .* Ymfs/2; + Yppisc(smooth3(Yppisc)<0.3) = 0; + Yppisc(smooth3(Yppisc)>0.7) = 1; + Yppisc( Yppisc<0.5 & ~cat_vol_morph(Yppisc<0.5,'l')) = 1; % close major wholes in the WM + Yppisc( Yppisc>0.5 & ~cat_vol_morph(Yppisc>0.5,'l')) = 0; % remove small dots + + + + % Marching cubes surface creation and correction for the boundary box + % used within the surface creation process. It is better to use the + % full voxel resolution in combination with surface reduction rather + % then using lower voxel resolutions! Moreover, it was NOT necessary to + % use surface deformation before the surface reduction! + % ##### + % I am not sure if the topologoy correction is optimal. + % Moreover, a correction should also change the Yppi to avoid self-intersections. + % Maybe a smooth adaptation similar to ""mask_parahipp_smoothed"" can be used here. + % However, this is quite complex and I miss the time go on ... + % RD201911 + % ##### + if iscerebellum + %% region-growing + % Ylt = single( cat_vol_morph(Yppi<0.1,'l') + 2 * cat_vol_morph(Yppi>0.9,'l') ); + Ylt = single( cat_vol_morph(Ymfs<1.9,'l') + 2 * cat_vol_morph(Ymfs>2.5,'l') ); + [Ylt,D] = cat_vol_simgrow(Ylt,Ymfs+Yppi,0.05); Ylt(D>10) = 0; % Yppi is to similiar + [Ylt,D] = cat_vol_simgrow(Ylt,Ymfs+Yppi,0.10); Ylt(D>10) = 0; + [Ylt,D] = cat_vol_simgrow(Ylt,Ymfs+Yppi,0.20); Ylt(D>10) = 0; + [Ylt,D] = cat_vol_simgrow(Ylt,Ymfs+Yppi,0.50); Ylt(D>10) = 0; + Ylts = smooth3(Ylt); + + + %% relative position map between core and hull + % to control opening and closing operations to reduce topology defects + % the topology correction is critical part where we need a quite + % robust inner core to avoid superlarge wholes + + % the hull is quite simple in general + Ycbh = cat_vol_morph(Yppi>0.1 & Ymfs>1.9,'lc',4); + % the core is more complicated because we have assure that something + % is there (at least the highest 20% of the hull distance) + Ycbhd = cat_vbdist( single( ~Ycbh ) ); + Ycbhd = Ycbhd/max(Ycbhd(Ycbhd<1000)); + Ycbc = cat_vol_smooth3X(Yppi + Ymfs/3 + (Ycbhd*0.8) ,2)>2; + Ycbc = cat_vol_smooth3X( cat_vol_morph( cat_vol_morph( cat_vol_morph( Ycbc ,'o',1) ,'l',[2 0.2]), 'lc',2),2) >0.5; + %% moreover we can use the Laplace filter for subtile openen and closing + if debug, tic; end + Yltw = (Yppi>0.6 | cat_vol_morph(Yppi>0.9,'dc',1) | Ycbc)/2 + Ycbc/2; + Yltw = cat_vol_laplace3R(single(Yltw),Yltw>0 & Yltw<1,0.01); + Yltw = max(Yltw,Ycbc | cat_vol_morph( cat_vol_morph( Yltw>0.25 , 'do' , 1.5 ) , 'l' , [2 0.2])); + Yltw = cat_vol_laplace3R(single(Yltw),Yltw>0 & Yltw<1,0.001); + if debug, toc; end + %% + if debug, tic; end + Yltc = Ycbh/2 + (Yltw>0.002)/2; + Yltc = cat_vol_laplace3R(single(Yltc),Yltc>0 & Yltc<1,0.01); + Yltw(Yltc>0.99) = 1; + if debug, toc; end + %% + Ycbc = cat_vol_smooth3X( cat_vol_smooth3X( Yltw , 4)> 0.6 & Yltw>0.5 ,2)>.5 ; + Yppisc = max(0.55 .* (Yppi>=1),min(1.5, Yppisc .* Yts )); % factor 1 is Ypp at 0.5 > limit 0.55 and 1.5 + if debug, clear Yts; end + + %Ycbc = cat_vol_morph( Ycbc , 'd') & Yppi>0.5; + %% distance mapping + if 1 + Ycbhd = cat_vbdist( single( ~Ycbh ) , ~Ycbc ); + Ycbcd = cat_vbdist( single( Ycbc ) , Ycbh ); + else + Ycbhd = single( ~Ycbh ); Ycbhd( Ycbc ) = nan; [Ytmp,Ycbhd] = cat_vol_downcut( Ycbhd , 4-Ymfs , 0.5); + Ycbcd = single( Ycbc ); Ycbcd( ~Ycbh ) = nan; [Ytmp,Ycbcd] = cat_vol_downcut( Ycbcd , Ymfs , 0.5); + end + Ycbpp = min(Ycbh,max(Ycbc,Ycbhd ./ max(eps,Ycbhd+Ycbcd))); + Ycbpp = cat_vol_localstat(Ycbpp,Ycbpp>0,1,1); + Ycbcd = Ycbcd ./ mean(Ycbcd(Ycbcd(:)>0 & Ycbcd(:)<1000)); + Ycbhd = Ycbhd ./ mean(Ycbhd(Ycbhd(:)>0 & Ycbhd(:)<1000)); + if ~debug, clear Ycbc Ycbh; end + + %% + if 0 + % this is too complex ... + + Ycbth = @(lth,pth,mth,cth) max(Ylt,Ylts)>(1.5*lth) & (Yppi - ( 0.5 - Ycbpp )/2 )>pth & Ymfs>mth & ... + ( (cth>=0).*(Ycbpp>cth) | (cth<0).*(Ycbpp<-cth) ); + Ycbth2 = @(lth,pth,mth,cth) max(Ylt,Ylts)>(1.5*lth) & (Yppi - ( 0.5 - Ycbpp )/2 )>pth & Ymfs>mth & ... + ( (cth>=0).*(Ycbcd-cth) ); + if ~debug, clear Ylt Ycbcd; end + + Ycbm = Ycbpp>0.99 | ... + Ycbth(1,0.95,2.5,0.0) | ... + Ycbth(1,0.9,2.1,1/3) | ... + Ycbth(1,0.95,2.5,1/3) | ... + Ycbth(0.8,0.05,2,2/3) | ... + (cat_vol_morph( Ycbth(1,0.9,2.2,-1/3) ,'do',2) ) | ... + (cat_vol_morph(Ycbth2(1,0.95,2.7,2/3) ,'dc',3) & Ycbth2(0,0.3,1.7,1/2)) | ... + (cat_vol_morph( Ycbth(1,0.9,2.2,0) ,'dc',2) & Ycbth(0,0.2,2,2/3)); + %% + Ycbm(smooth3(Ycbm)<0.3) = 0; Ycbm = single(Ycbm); %Ycbm(Ycbpp==0) = nan; + [Ycbm,D] = cat_vol_simgrow(Ycbm,Ymfs+Yppi,0.01); Ycbm(D>2) = 0; + Ycbm = Ycbm | cat_vol_morph( Ycbm ,'dc',1) & (Ycbth(1,0.5,2.4,0) | Ycbth(1,0.5,2.1,0.5)); + Ycbm(smooth3(Ycbm)<0.5) = 0; Ycbm(smooth3(Ycbm)>0.5) = 1; Ycbm(smooth3(Ycbm)>0.3 & Ycbth(1,0,2,0.8)) = 1; + Ycbm = Ycbm .* Ycbth(0,0,0,0.5) + cat_vol_morph(Ycbm,'do',1) .* Ycbth(0,0,0,-0.5); + Ycbm = Ycbm .* Ycbth(0,0,0,0.3) + cat_vol_morph(Ycbm,'do',3) .* Ycbth(0,0,0,-0.2); + Ycbm = cat_vol_morph( Ycbm, 'l'); + Ycbm = single( Ycbm ); + else + %% + Ycbm = Yppi .* min( 0.4 + Ycbhd/5, 0.5 + Ycbpp*0.60); % in sum larger than one to have save core structure + if 1 + Ycbms = smooth3(Ycbm); + % opening by smoothing in outer regions + Ycbppt = max(0,min(1,Ycbpp * 5)); + Ycbm = Ycbms .* (1-Ycbppt) + Ycbm .* Ycbppt; + % closing by smoothing in inner regions + Ycbppt = max(0,min(1,(1 - Ycbpp ) * 5)); + Ycbm = Ycbms .* (1-Ycbppt) + Ycbm .* Ycbppt; + clear Ycbms; + end + end + clear Ycbhd Ycbpp + + + %% + Yppi05c = Ycbm; evalc(sprintf('clear CS; [Yppi05c,CS.faces,CS.vertices] = cat_vol_genus0(Ycbm,0.5,nosurfopt);')); % no_adjustment + [Yvxdef,defect_number0] = spm_bwlabel( double(abs(Yppi05c - (Yppisc>0.5))>0) ); clear Yppi05c; + else + % Main initial surface creation using cat_vol_genus0 + % cat_vol_genus0 uses a ""simple"" marching cube without use of isovalues + % that is used in the MATLAB isosurface function. Our test showed that + % the surface deformation allows the same or better accuracy and also + % that the meshes of cat_vol_genus0 are more regular and also allow + % voxel-based topology optimization. + + if opt.reduce_mesh~=1 % full resolution + + [Yppi05c,CS] = cat_vol_genus0opt(Yppisc,.5,15 * (1-iscerebellum),debug); + [Yvxdef,defect_number0] = spm_bwlabel( double(abs(Yppi05c - (Yppisc>0.5))>0) ); clear Yppi05c; + + else % lower resolutions + rf = min(1.5,max(0.75,opt.vdist)); % because I use V + VI = V; VI.mat = spm_matrix(matI); + + %% Optimized downsampling to avoid blurring of thin gyri/sulci + % We create two maps, one for the thin gyral (Yppi_od) and one + % for thin sulcal regions (Yppi_cd) that are defined as the + % areas that disappiere by using an opening opteration. + % This operion simulate in some way the meandering of the layer 4. + % RD20210722: Refined binary maps to continues model due to problems in the parahippocampal gyrus. + + % first we do a voxelbased topology correction for the intial + % surface treshhold on the original resolution + Yppisc = cat_vol_genus0opt(Yppi,.5,10 * (1-iscerebellum),debug); + + + %% then we estimate the regions that probably disappear when + % we change the resolution + d = max(1,rf / opt.interpV / 2) * 3; %1.5; + distmorph = 1; if distmorph, dm = 'd'; else, dm = ''; end + Yppi_o = cat_vol_morph(Yppisc>0.5,[dm 'o'], d ); % rf / opt.interpV - 1 + Yppi_c = cat_vol_morph(Yppisc<0.5,[dm 'o'], d ); + + Yppi_o2 = cat_vol_morph(Yppisc>0.5,[dm 'o'], d*2 ); % rf / opt.interpV - 1 + Yppi_c2 = cat_vol_morph(Yppisc<0.5,[dm 'o'], d*2 ); + + Yppi_od = cat_vol_morph(Yppisc>0.5 & ~Yppi_o & ~cat_vol_morph(Yppisc<0.5 & ~Yppi_c2,[dm 'd'],d),[dm 'd'], d ); % (rf / opt.interpV - 1)/3 + Yppi_cd = cat_vol_morph(Yppisc<0.5 & ~Yppi_c & ~cat_vol_morph(Yppisc>0.5 & ~Yppi_o2,[dm 'd'],d),[dm 'd'], d ); + if ~debug, clear Yppi_c Yppi_c2 Yppi_o Yppi_o2 ; end + + Yppi_od = smooth3(Yppi_od)>0.5; + Yppi_cd = smooth3(Yppi_cd)>0.5; + + + %% create + if exist('Yppi_mx','var') + Yppi_gyri = Yppi_mn>0.1 & Yppi_od & ~Yppi_cd; + Yppi_sulci = Yppi_mx<0.9 & Yppi_cd & ~Yppi_od; + + Yppi_gyri = Yppi_gyri | (Yppi_mx>0.9 & Yppi>0.3 & Yppi_mn>0.5); + Yppi_sulci = Yppi_sulci | (Yppi_mn<0.1 & Yppi<0.7 & Yppi_mx<0.5); + if ~debug, clear Yppi_mn Yppi_mx; end + else + Yppi_gyri = Yppi_od & ~Yppi_cd; + Yppi_sulci = Yppi_cd & ~Yppi_od; + end + + if ~debug, clear Yppi_od Yppi_cd Yppiscrc Yppiscmn Yppiscmx; end + + % open to remove noisi dots + Yppi_gyri = smooth3(Yppi_gyri)>0.5; + Yppi_sulci = smooth3(Yppi_sulci)>0.5; + + % smoothing to create a softer, better fitting pattern + Yppi_gyri = cat_vol_smooth3X(Yppi_gyri ,1.2)*0.5 + 0.5*cat_vol_smooth3X(Yppi_gyri ,0.6); + Yppi_sulci = cat_vol_smooth3X(Yppi_sulci,1.2)*0.5 + 0.5*cat_vol_smooth3X(Yppi_sulci,0.6); + + % closing of gyri is more important than opening + Yppi_gyri = Yppi_gyri * 1.2; + Yppi_sulci = Yppi_sulci * 1.2; + + % refine the Yppiscr (use for surface creation but not optimization) + % by thickenning of thin gyris and opening of thin gyris + Yppiscr = min(0.5 + 0.5*Yppisc, Yppi); + Yppiscr = max(0,min(1, Yppiscr + max(0,Yppi_gyri - Yppi_sulci) - max(0, Yppi_sulci - Yppi_gyri) )); + + if ~debug, clear Yppi_gyri Yppi_sulci Yppisc; end + clear mask_parahipp; + + if ~debug, clear Yppigyri Yppislci; end + %% + [Yppiscr,resL] = cat_vol_resize(Yppiscr,'interp',VI,rf,1); + %evalc(sprintf('clear CS; [Yppi05c,CS.faces,CS.vertices] = cat_vol_genus0(Yppiscr,0.5,1);')); % no_adjustment + [Yppi05c,CS] = cat_vol_genus0opt(Yppiscr,.5,5 * (1-iscerebellum),debug); + %% + [Yvxdef,defect_number0] = spm_bwlabel( double(abs(Yppi05c - (Yppiscr>0.5))>0) ); clear Yppi05c; + Yvxdef = cat_vol_resize(cat_vol_morph(Yvxdef,'d'),'deinterp',resL); % #### this is not ideal and need refinement ### + if ~debug, clear Yppiscr; end + + CS.vertices = CS.vertices * rf/opt.interpV; + end + end + % + EC0 = size(CS.vertices,1) + size(CS.faces,1) - size(spm_mesh_edges(CS),1); + vdefects = cat_surf_fun('isocolors',CS,cat_vol_morph(Yvxdef,'d'),Smat.matlabIBB_mm)>0; clear Yvxdef; + defect_size0 = sum(vdefects > 0) / length(vdefects) * 100; % percent + defect_area0 = sum(vdefects > 0) / length(vdefects) .* ... + sum(cat_surf_fun('area',CS)) / opt.interpV / 100; % cm2 + if debug % opt.verb>1 && ~useprior + fprintf('\n'); + cat_io_cprintf('g5',sprintf('( SC/EC/DN/DS = %0.2f/',scale_cortex)); + cat_io_cprintf( color( rate( abs( EC0 - 2 ) , 0 ,100 * (1+9*iscerebellum) )) ,sprintf('%d/',EC0)); + cat_io_cprintf( color( rate( defect_number0 , 0 ,100 * (1+9*iscerebellum) )) ,sprintf('%d/',defect_number0)); + cat_io_cprintf( color( rate( defect_size0 , 1 , 10 * (1+9*iscerebellum) )) ,sprintf('%0.2f%%%%' ,defect_size0)); + cat_io_cprintf('g5',' )'); + fprintf(repmat(' ',1,max(0,14 - numel(sprintf('%d/%d/%0.2f%%%% )',EC0,defect_number0,defect_size0))))); + end + + + % translate to mm coordinates + CS = cat_surf_fun('smat',CS,Smat.matlabIBB_mm); + if opt.surf_measures > 1, CSraw0 = CS; end % need this map later to create a common defect map + if ~debug, clear mask_parahipp_smoothed; end + + + % reduce resolution with higher resolution for cerebellum + % ########## + % * Both the SPM as well as the MATLAB function crashed my MATLAB + % multiple times (unreproducible and fatal). + % However, I have no idea why this happens and if its only on my system + % or how I could avoid or catch it because it is not just a simple error. + % > This also happens if I only use double. + % > It also happens on the server. + % RD201911 + % * use the same mesh resolution for the cerebellum for acceptable processing times. + % ########## + if opt.reduce_mesh>2 + CS.vertices = double(CS.vertices); CS.faces = double(CS.faces); + if opt.reduce_mesh == 3 || opt.reduce_mesh == 5 + CS = spm_mesh_reduce(CS, 81920 / (1 + (opt.vdist>2)) * (1 + 0*iscerebellum) ); + elseif opt.reduce_mesh == 4 || opt.reduce_mesh == 6 + CS = reducepatch(CS, 81920 / (1 + (opt.vdist>2)) * (1 + 0*iscerebellum) ); + elseif opt.reduce_mesh == 7 + CS = cat_surf_fun('reduce',CS, 81920 / (1 + (opt.vdist>2)) * (1 + 0*iscerebellum) ); + elseif opt.reduce_mesh == 8 + nCS0 = size(CS.faces,1); + nCS = 81920 / (1 + (opt.vdist>2)) * (1 + 0*iscerebellum); + saveSurf(CS,P(si).Pcentral); + cmd = sprintf('CAT_SurfReduce -aggr ""5"" -ratio ""%0.2f"" ""%s"" ""%s""', nCS/nCS0 , P(si).Pcentral, P(si).Pcentral); %5-0.05*opt.reconres); + cat_system(cmd ,opt.verb-3); + CS = loadSurf(P(si).Pcentral); + end + % remove bad faces + CS = correctReducePatch(CS); + end + + + % remove unconnected meshes + saveSurf(CS,P(si).Praw); + cmd = sprintf('CAT_SeparatePolygon ""%s"" ""%s"" -1',P(si).Praw,P(si).Praw2); + cat_system(cmd,opt.verb-3); + + % sometimes CAT_SeparatePolygon fails and we have to use the raw file + try + CS = loadSurf(P(si).Praw2); + movefile(P(si).Praw2,P(si).Praw); + catch + CS = loadSurf(P(si).Praw); + spm_unlink(P(si).Praw2); + end + + facevertexcdata = cat_surf_fun('isocolors',Yth1i,CS,Smat.matlabIBB_mm); + cat_io_FreeSurfer('write_surf_data',P(si).Ppbt,facevertexcdata); + + cmd = sprintf(['CAT_DeformSurf ""%s"" none 0 0 0 ""%s"" ""%s"" none 0 1 -1 .1 ' ... + 'avg %0.3f %0.3f .2 .1 5 0 ""0.5"" ""0.5"" n 0 0 0 %d %g 0.0 0'], ... + Vpp1.fname,P(si).Praw,P(si).Praw,-0.1, 0.1, 50, 0.01); + cat_system(cmd,opt.verb-3); + + cmd = sprintf('CAT_Central2Pial -equivolume -weight 0.7 ""%s"" ""%s"" ""%s"" 0',P(si).Praw,P(si).Ppbt,P(si).Praw); + cat_system(cmd,opt.verb-3); + + % refine super-large faces with adaptation for cerebellum + cmd = sprintf('CAT_RefineMesh ""%s"" ""%s"" %0.2f', P(si).Praw, P(si).Praw, 3); + cat_system(cmd,opt.verb-3); + + % Create a smooth surface for the topology correction. + % It don't has to be perfect because it will replaced completely! + cmd = sprintf(['CAT_DeformSurf ""%s"" none 0 0 0 ""%s"" ""%s"" none 0 1 -1 .1 ' ... + 'avg %0.3f %0.3f .2 .1 5 0 ""0.5"" ""0.5"" n 0 0 0 %d %g 0.0 0'], ... + Vpp1.fname,P(si).Praw,P(si).Praw,-0.1, 0.1, 50, 0.01); + cat_system(cmd,opt.verb-3); + + % load surf and map thickness + CS = loadSurf(P(si).Praw); + + + % evaluate and save results + if isempty(stime), stime = clock; end + fprintf('%5.0fs',etime(clock,stime)); stime = []; if debug, fprintf('\n'); end + res.(opt.surf{si}).createCS_init = cat_surf_fun('evalCS',CS,cat_surf_fun('isocolors',CS,Yth1i,Smat.matlabIBB_mm),[],Ymfs,Yppi,P(si).Pcentral,Smat.matlabIBB_mm,debug); + if debug + % save surface for further evaluation + cat_surf_fun('saveico',CS,cat_surf_fun('isocolors',Yth1i,CS.vertices,Smat.matlabIBB_mm),P(si).Pcentral,sprintf('createCS_1_init_pbtres%0.2fmm_vdist%0.2fmm',opt.interpV,opt.vdist),Ymfs,Smat.matlabIBB_mm); + else + fprintf('\n'); + end + + + + + %% Topology correction and surface refinement + % -------------------------------------------------------------------- + % This topology correction creates a completely new surface based on + % spherical harmonic functions resulting in a relative unbalanced + % local resolution (i.e., oversampled in the insula) that is corrected + % in the next block. However, this also means the resolution of the + % input surface don't have to be super high (see above). + % -------------------------------------------------------------------- + stime = cat_io_cmd(' Topology correction:','g5','',opt.verb,stime); + + % spherical surface mapping 1 of the uncorrected surface for topology correction + % We do not need so much smoothing as for the final surface but the + % cerebellum needs maybe more due to severe topology defects. + % To fine is to slow ... + cmd = sprintf('CAT_Surf2Sphere ""%s"" ""%s"" %d',P(si).Praw,P(si).Psphere0,... + 5 + round( sqrt( size(CS.faces,1) / 10000 * (1 + 3*iscerebellum) ) )); + cat_system(cmd,opt.verb-3); + + % estimate size of topology defects + cmd = sprintf('CAT_MarkDefects ""%s"" ""%s"" ""%s""',P(si).Praw,P(si).Psphere0,P(si).Pdefects0); + cat_system(cmd); + + % sometimes defects-file is missing for no reasons + if exist(P(si).Pdefects0,'file') + sdefects = cat_io_FreeSurfer('read_surf_data',P(si).Pdefects0); delete(P(si).Pdefects0); + defect_number0 = defect_number0 + max(sdefects); + defect_size0 = defect_size0 + sum(sdefects > 0) / length(sdefects) * 100; % percent + defect_area0 = defect_area0 + sum(sdefects > 0) / length(sdefects) .* ... + sum(cat_surf_fun('area',CS)) / opt.interpV / 100; % cm2 + else + defect_number0 = defect_number0 + NaN; + defect_size0 = defect_size0 + NaN; + defect_area0 = defect_area0 + NaN; + end + % estimate Euler characteristics: EC = #vertices + #faces - #edges + EC0 = (EC0-2) + ( size(CS.vertices,1) + size(CS.faces,1) - size(spm_mesh_edges(CS),1) - 2) + 2; + if any( strcmp( {'lh','rh'} , opt.surf{si} )) + EC = EC + abs(EC0 - 2) + 2; % -2 is the correction for the sphere + defect_size = defect_size + defect_size0; + defect_area = defect_area + defect_area0; + defect_number = defect_number + defect_number0; + end + + % topology correction and surface refinement + % Higher -n will result in larger but still unbalanced meshes and the + % refine_length parameter is more important to obtain nice meshes. + % more points are not allways better ! + if opt.verb>3, fprintf('\n'); end + cmd = sprintf('CAT_FixTopology -lim %d -bw %d -n %d -refine_length %g ""%s"" ""%s"" ""%s""',... + 128 / (1 + iscerebellum),512 / (1 + iscerebellum), 81920, opt.vdist ,P(si).Praw,P(si).Psphere0,P(si).Pcentral); % avoid too long processing in cerebellum + cat_system(cmd,opt.verb-3); + + CS = loadSurf(P(si).Pcentral); + %facevertexcdata = cat_surf_fun('isocolors',Yth1i,CS.vertices,Smat.matlabIBB_mm); + %fprintf('TC: V=%d, MN(CT)=%0.20f, SD(CT)=%0.20f\n',size(CS.vertices,1),mean(facevertexcdata(:)),std(facevertexcdata(:))); + res.(opt.surf{si}).createCS_0_initfast = cat_surf_fun('evalCS',CS,cat_surf_fun('isocolors',CS,Yth1i,Smat.matlabIBB_mm),[],Ymfs,Yppi,P(si).Pcentral,Smat.matlabIBB_mm,opt.verb-2); + + + + + %% Optimize topology corrected mesh: + % -------------------------------------------------------------------- + % Oversampling can lead to problems in the normal transformation to + % obtain the inner and outer surface, especially in the Insula/Amygdala. + % The idea is to reduce the sampling of the mesh and then to refine + % the mesh again. + % However it is highly essential that most regions where not corrected + % and a specific masking of the Insula (relative small triangles in a + % specific area on one/all of the main cortical surfaces or flipping) + % is possible useful. + % ... seems that this is working and it takes only a few seconds! + % -------------------------------------------------------------------- + % refinement - important for sulci .. here we need a lot of details with a similar resolution as the Insula + if opt.reduce_mesh > 4 && opt.reduce_mesh<8 % superinterpolation + stime = cat_io_cmd(' Surface optimization and refinement:','g5','',opt.verb,stime); + meshres = 0.8; % this will create a super resolution that has to be reduced or will result in long processing times + elseif opt.reduce_mesh == 8 + stime = cat_io_cmd(' Surface refinement:','g5','',opt.verb,stime); + meshres = opt.vdist; %min(1.2,opt.vdist); + else + stime = cat_io_cmd(' Surface refinement:','g5','',opt.verb,stime); + meshres = opt.vdist; + end + cmd = sprintf('CAT_RefineMesh ""%s"" ""%s"" %0.2f',P(si).Pcentral,P(si).Pcentral, meshres ); + cat_system(cmd,opt.verb-3); + end + + % surface refinement (this time even before reduction) + cmd = sprintf(['CAT_DeformSurf ""%s"" none 0 0 0 ""%s"" ""%s"" none 0 1 -1 .1 ' ... + 'avg -0.1 0.1 .2 .1 5 0 ""0.5"" ""0.5"" n 0 0 0 %d %g 0.0 0'], ... + Vpp1.fname,P(si).Pcentral,P(si).Pcentral,50,0.01); + cat_system(cmd,opt.verb-3); + + + if ~useprior + % Because the Insula/Amygdala is not so heavily folded compared to + % sulci it is reduced first what helps to avoid self-interesections + CS = loadSurf(P(si).Pcentral); + if opt.reduce_mesh > 4 + rfaces = min( max( 81920 , opt.reduceCS/2 ) , 81920 * 4 ); + CS.vertices = double(CS.vertices); CS.faces = double(CS.faces); + if opt.reduce_mesh == 5 + CS = spm_mesh_reduce(struct('vertices',CS.vertices,'faces',CS.faces),rfaces); + elseif opt.reduce_mesh == 6 + CS = reducepatch(struct('vertices',CS.vertices,'faces',CS.faces),rfaces); + elseif opt.reduce_mesh == 7 + CS = cat_surf_fun('reduce',CS,rfaces); + elseif opt.reduce_mesh == 8 + cmd = sprintf('CAT_SurfReduce -aggr ""5"" -ratio ""%0.2f"" ""%s"" ""%s""', rfaces , P(si).Pcentral, P(si).Pcentral); + cat_system(cmd ,opt.verb-3); + % extra refine + cmd = sprintf('CAT_RefineMesh ""%s"" ""%s"" %0.2f', P(si).Pcentral, P(si).Pcentral, opt.vdist ); + cat_system(cmd ,opt.verb-3); + % surface refinement (this time even before reduction) + cmd = sprintf(['CAT_DeformSurf ""%s"" none 0 0 0 ""%s"" ""%s"" none 0 1 -1 .1 ' ... + 'avg -0.1 0.1 .2 .1 5 0 ""0.5"" ""0.5"" n 0 0 0 %d %g 0.0 0'], ... + Vpp1.fname, P(si).Pcentral, P(si).Pcentral, 50, 0.01); + cat_system(cmd,opt.verb-3); + CS = loadSurf(P(si).Pcentral); + end + % remove bad faces + CS = correctReducePatch(CS); + end + saveSurf(CS,P(si).Pcentral); + end + + + %% EXPERIMENTAL + % ------------------------------------------------------------------ + % RD202107: Local surface smoothing of problematic areas (e.g. areas + % from topology correction) that are defined by highly + % resampled areas: + % (1./abs(C)).^(1./A) + % 3 iterations are used to smooth high sampled structures + % that often cause self-intersections and often represent + % corrected topological defects with inaccurate geometry, + % e.g., cuts in the parahippocamplal or superior temploral + % gyri. Although this works in principle the correction of + % cuts is still not optimal. + % ------------------------------------------------------------------ + if opt.localsmooth + for csxi = 3:-1:1 + M = spm_mesh_smooth(CS); + A = cat_surf_fun('area',CS); + C = spm_mesh_curvature(CS); + OL = spm_mesh_smooth(M, double( max(0.01,min(4,1./abs(C))) .^ max(0.01,min(10,1 ./ max(eps,A))) ) ,40); % + CS = cat_surf_fun('localsurfsmooth',CS,log(max(0,( (OL-100*csxi)/100))),100); + + if csxi > 1 + % + saveSurf(CS,P(si).Pcentral); + cmd = sprintf(['CAT_DeformSurf ""%s"" none 0 0 0 ""%s"" ""%s"" none 0 1 -1 .1 ' ... + 'avg -0.1 0.1 .2 .1 %d 0 ""0.5"" ""0.5"" n 0 0 0 %d %0.2f 0.0 0'], ... pial=1/3, quantil=0.4167 + Vpp.fname,P(si).Pcentral,P(si).Pcentral,1,10,0.01); + cat_system(cmd,opt.verb-3); + CSc = loadSurf(P(si).Pcentral); + OLc = min(1,max(0,OL - 100)); + CS.vertices = CS.vertices .* repmat(1 - OLc,1,3) + CSc.vertices .* repmat(OLc,1,3); + end + end + if ~debug, clear M A C OL CSox CSc OLc; end + end + % ------------------------------------------------------------------ + + + %% + if ~useprior + % remove unconnected meshes + cmd = sprintf('CAT_SeparatePolygon ""%s"" ""%s"" -1',P(si).Pcentral,P(si).Pcentral); + cat_system(cmd,opt.verb-3); + + % refinement - guaranty our default resolution + cmd = sprintf('CAT_RefineMesh ""%s"" ""%s"" %0.2f',P(si).Pcentral,P(si).Pcentral,opt.vdist); + cat_system(cmd,opt.verb-3); + end + + % surface deformation for relaxation after reduction and refinement + cmd = sprintf(['CAT_DeformSurf ""%s"" none 0 0 0 ""%s"" ""%s"" none 0 1 -1 .1 ' ... + 'avg -0.1 0.1 .2 .1 5 0 ""0.5"" ""0.5"" n 0 0 0 %d %g 0.0 0'], ... + Vpp1.fname,P(si).Pcentral,P(si).Pcentral,100,0.01); + cat_system(cmd,opt.verb-3); + % read final surface and map thickness data + CS = loadSurf(P(si).Pcentral); + facevertexcdata = cat_surf_fun('isocolors',Yth1i,CS.vertices,Smat.matlabIBB_mm); + cat_io_FreeSurfer('write_surf_data',P(si).Ppbt,facevertexcdata); + + + % final correction of central surface in highly folded areas + % with high mean curvature with weight of 0.7 and further refinement + % of the mesh and its vertices based on the position map + cmd = sprintf('CAT_Central2Pial -equivolume -weight 0.7 ""%s"" ""%s"" ""%s"" 0',P(si).Pcentral,P(si).Ppbt,P(si).Pcentral); + cat_system(cmd,opt.verb-3); + + % we need some refinement because some vertices are too large to be deformed with high accuracy + if ~useprior + cmd = sprintf('CAT_RefineMesh ""%s"" ""%s"" %0.2f 1',P(si).Pcentral,P(si).Pcentral,opt.vdist); % adaptation for cerebellum + cat_system(cmd,opt.verb-3); + end + + % surface refinement by surface deformation based on the PP map + cmd = sprintf(['CAT_DeformSurf ""%s"" none 0 0 0 ""%s"" ""%s"" none 0 1 -1 .1 ' ... + 'avg -0.1 0.1 .2 .1 %d 0 ""0.5"" ""0.5"" n 0 0 0 %d %0.2f 0.0 0'], ... + Vpp1.fname,P(si).Pcentral,P(si).Pcentral,5,100,0.01); + cat_system(cmd,opt.verb-3); + + % need some more refinement because some vertices are distorted after CAT_DeformSurf + if ~useprior + cmd = sprintf('CAT_RefineMesh ""%s"" ""%s"" %0.2f 1',P(si).Pcentral,P(si).Pcentral,opt.vdist); % adaptation for cerebellum + cat_system(cmd,opt.verb-3); + end + + % final surface refinement + cmd = sprintf(['CAT_DeformSurf ""%s"" none 0 0 0 ""%s"" ""%s"" none 0 1 -1 .1 ' ... + 'avg -0.1 0.1 .5 .1 %d 0 ""0.5"" ""0.5"" n 0 0 0 %d %0.2f 0.0 0'], ... + Vpp1.fname,P(si).Pcentral,P(si).Pcentral,5,200,0.005); + cat_system(cmd,opt.verb-3); + + % read final surface and map thickness data + CS = loadSurf(P(si).Pcentral); + facevertexcdata = cat_surf_fun('isocolors',Yth1i,CS.vertices,Smat.matlabIBB_mm); + cat_io_FreeSurfer('write_surf_data',P(si).Ppbt,facevertexcdata); + + % evaluate and save results + fprintf('%5.0fs\n',etime(clock,stime)); stime = []; + + + if opt.SRP + %% Collision correction by Delaunay triangularization + % -------------------------------------------------------------------- + % New self-intersection correction that uses different detections of + % self-intersections (SIDs; RY vs. PBT) with/without further optimization. + % It does not fully avoid self-intersections because some are already + % in the CS and some other required strong changes that result in worse + % thickness results. + + if opt.SRP == 1 + stime = cat_io_cmd(' Reduction of surface collisions:','g5','',opt.verb,stime); + else + stime = cat_io_cmd(' Reduction of surface collisions with optimization:','g5','',opt.verb,stime); + end + verblc = 0; % verbose level + if debug, if exist('CSO','var'), CS = CSO; facevertexcdata = facevertexcdatao; else, CSO = CS; facevertexcdatao = facevertexcdata; end; stime2 = clock; else, stime2 = []; end + if debug, saveSurf(CS,P(si).Pcentral); cat_io_FreeSurfer('write_surf_data',P(si).Ppbt,facevertexcdata); end + + if 1 + saveSurf(CS,P(si).Pcentral); + cmd = sprintf('CAT_Central2Pial -equivolume -weight 0.6 ""%s"" ""%s"" ""%s"" 0',P(si).Pcentral,P(si).Ppbt,P(si).Pcentral); + cat_system(cmd,opt.verb-3); + CS = loadSurf(P(si).Pcentral); + end + + %% RD202107: do not correct in too problematic regions that suffer from too fine sampling + if opt.localsmooth + for ix = 1:2 % two main interations + M = spm_mesh_smooth(CS); + A = cat_surf_fun('area',CS); + C = spm_mesh_curvature(CS); + OL = spm_mesh_smooth(M, double( max(0.01,min(4,1./abs(C))) .^ max(0.01,min(10,1 ./ max(eps,A))) ) ,40); + for i = 1:5, CS = cat_surf_fun('localsurfsmooth',CS,log(max(0,( (OL-100*csxi)/100))),10); end % more subiterations + clear M A C OL; + end + end + + %% call collision correction + % RD202108: Use further iterations if self-intersections are still very high. + % (test data was an high resolution ex-vivo chimp PD image that had still strong SIs after first correction) + % RD202508: Optimization does not fully work on the simple PP map. + % The optimization torwards 0.05 and 0.95 on the interpolated maps still result in light thickness overestimation. + SIOs = 100; SIs = 80; maxiter = 1; iter = 0; + while SIs>5 && SIs=2,'verb',verblc,'mat',Smat.matlabIBB_mm,'vx_vol',vx_vol,'CS4',0)); %opt.SRP>3)); + if verblc, fprintf('\b\b'); end + if strcmpi(spm_check_version,'octave') && iter == 1 + cat_io_addwarning('cat_surf_createCS2:nofullSRP','Fine correction of surface collisions is not yet available under Octave.',2) + elseif iter == 1 % to keep it fast we just do this once + [CS,facevertexcdata,SIs] = cat_surf_fun('collisionCorrectionRY' ,... + CS,facevertexcdata,Yppi,struct('Pcs',P(si).Pcentral,'verb',verblc,'mat',Smat.matlabIBB_mm,'accuracy',1/2^3)); + end + end + + % RD202504: correction required in case of Rusak2021 thickness phantom + flipped = cat_surf_fun('checkNormalDir',CS); + if flipped, CS.faces = [CS.faces(:,1) CS.faces(:,3) CS.faces(:,2)]; end + saveSurf(CS,P(si).Pcentral); + + + + %% evaluate and save results + if verblc, cat_io_cmd(' ','g5','',opt.verb); end + fprintf('%5.0fs',etime(clock,min([stime2;stime],[],1))); if ~debug, stime = []; end + saveSurf(CS,P(si).Pcentral); cat_io_FreeSurfer('write_surf_data',P(si).Ppbt,facevertexcdata); + fprintf('\n'); + + if ~debug, clear CSO; end + end + + + % Further error measures: + % - Map local noise pattern? + % >> Detection of movement artifacts? + % - Map local bias field? + % >> This finally codes the heat noise of the original image >> input by cat_main + % >> Relevant for local interpretation of results, e.g. low signal (high noise) ares are less reliable. + % ... both aspects are more general QA topics and not so relevant here + % + % - Map collision error? + % >> output of collision detection? - not independent + % >> only relevant for me? + % - Map distance error? + % >> To what? RAW surface? This would include topology defect errors. + % Possibly mask by defect map? And then? + % >> estimate distance of each GM voxels to its closes surface point + % . describes the number of voxels out of thickness range (missing GM voxels - but also artifacts) + % estimate distance of each ~GM brain voxels within the local thickness + % . describes the number of voxels the are in the cortical surface ribbon but should not + % ... the biggest problem are here the artifacts ... + % ... use defect map to avoid counting in some region + + + + % map defects to the final surface + if opt.surf_measures > 1 && ~useprior + writeDefectData(Ymfs,CS,CSraw0,P,vdefects,sdefects,Smat,si) + end + clear CSraw0 vdefects sdefects + + + % Test without surface registration - just a shortcut for manual tests! + if isscalar(opt.surf) + cat_surf_createCS_fun('quickeval',V0,Vpp,Ymfs,Yppi,CS,P,Smat,res,opt,EC0,si,time_sr,2); + return + end + + + + + % skip that part if a prior image is defined + if ~useprior + %% spherical surface mapping and registration of the final corrected surface + % use more iterations for higher surfaces (sqrt due to surface area) + % no extra rule for the cerebellum here because it is has the correct topology. + stime = cat_io_cmd(' Spherical mapping with areal smoothing','g5','',opt.verb,stime); + cmd = sprintf('CAT_Surf2Sphere ""%s"" ""%s"" %d',P(si).Pcentral,P(si).Psphere,... + 5 + round( sqrt( size(CS.faces,1) / 10000 ) + 1 )); % 300k with value 10 + cat_system(cmd,opt.verb-3); + % spherical registration to fsaverage template + stime = cat_io_cmd(' Spherical registration','g5','',opt.verb,stime); + cmd = sprintf('CAT_WarpSurf -steps 2 -avg -i ""%s"" -is ""%s"" -t ""%s"" -ts ""%s"" -ws ""%s""', ... + P(si).Pcentral,P(si).Psphere,P(si).Pfsavg,P(si).Pfsavgsph,P(si).Pspherereg); + cat_system(cmd,opt.verb-3); + fprintf('%5.0fs\n',etime(clock,stime)); + end + + % create white and central surfaces + stime = cat_io_cmd(' Create pial and white surface','g5','',opt.verb,stime); + cat_surf_fun('white',P(si).Pcentral); + cat_surf_fun('pial',P(si).Pcentral); + + + % write myelination map (Ypp intensity of layer 4) + if opt.surf_measures > 1 + cmd = sprintf('CAT_Central2Pial -equivolume -weight 1 ""%s"" ""%s"" ""%s"" 0',P(si).Pcentral,P(si).Ppbt,P(si).Player4); + cat_system(cmd,0); + L4 = gifti(P(si).Player4); + L4v = cat_surf_fun('isocolors',Ymf,L4,Smat.matlabi_mm); clear L4 + cat_io_FreeSurfer('write_surf_data',P(si).PintL4,L4v); clear L4v + end + + + % estimate Freesurfer thickness measure Tfs using mean(Tnear1,Tnear2) + if opt.thick_measure == 1 + % not ready yet + if 0 + cmd = sprintf('CAT_SurfDistance -mean ""%s"" ""%s"" ""%s""',P(si).Pwhite,P(si).Ppial,P(si).Pthick); + cat_system(cmd,opt.verb-3); + else % use central surface and thickness + cmd = sprintf('CAT_SurfDistance -mean -thickness ""%s"" ""%s"" ""%s""',P(si).Ppbt,P(si).Pcentral,P(si).Pthick); + cat_system(cmd,opt.verb-3); + end + + % apply upper thickness limit + facevertexcdata = cat_io_FreeSurfer('read_surf_data',P(si).Pthick); + cat_io_FreeSurfer('write_surf_data', P(si).Pthick, min(opt.thick_limit,facevertexcdata) ); + + % final surface evaluation + if debug || cat_get_defaults('extopts.expertgui')>1, fprintf('\n'); end + if debug + cat_surf_fun('saveico',CS,facevertexcdata,P(si).Pcentral,sprintf('createCS_3_collcorr_%0.2fmm_vdist%0.2fmm',opt.interpV,opt.vdist),Ymfs,Smat.matlabIBB_mm); + end + res.(opt.surf{si}).createCS_final = cat_surf_fun('evalCS',loadSurf(P(si).Pcentral),cat_io_FreeSurfer('read_surf_data',P(si).Ppbt),facevertexcdata,Ymfs,Yppi,P(si).Pcentral,Smat.matlabIBB_mm,debug + (cat_get_defaults('extopts.expertgui')>1),cat_get_defaults('extopts.expertgui')>1); + else % otherwise simply copy ?h.pbt.* to ?h.thickness.* + facevertexcdata = cat_surf_fun('isocolors',Yth1i,CS.vertices,Smat.matlabIBB_mm); + cat_io_FreeSurfer('write_surf_data',P(si).Pthick,facevertexcdata); + + % final surface evaluation + res.(opt.surf{si}).createCS_final = cat_surf_fun('evalCS',loadSurf(P(si).Pcentral),cat_io_FreeSurfer('read_surf_data',P(si).Ppbt),[],Ymfs,Yppi,P(si).Pcentral,Smat.matlabIBB_mm,debug,cat_get_defaults('extopts.expertgui')>1); + + end + + + % correct thickness based on folding pattern + if opt.foldingcorrection + cmd = sprintf('CAT_SurfCorrectThicknessFolding -max ""%f"" ""%s"" ""%s"" ""%s""', opt.thick_limit, P(si).Pcentral, P(si).Pthick, P(si).Pthick); + cat_system(cmd,opt.verb-3); + end + + + + % average final values + FNres = fieldnames( res.(opt.surf{si}).createCS_final ); + for fnr = 1:numel(FNres) + if ~isfield(res,'final') || ~isfield(res.final,FNres{fnr}) + res.final.(FNres{fnr}) = res.(opt.surf{si}).createCS_final.(FNres{fnr}) / numel(opt.surf); + else + res.final.(FNres{fnr}) = res.final.(FNres{fnr}) + res.(opt.surf{si}).createCS_final.(FNres{fnr}) / numel(opt.surf); + end + end + if isfield(res.(opt.surf{si}),'createCS_resampled') + FNres = fieldnames( res.(opt.surf{si}).createCS_resampled ); + for fnr = 1:numel(FNres) + if isfield(res.(opt.surf{si}),'createCS_resampled') + if ~isfield(res,'createCS_resampled') || ~isfield(res.createCS_resampled,FNres{fnr}) + res.resampled.(FNres{fnr}) = res.(opt.surf{si}).createCS_resampled.(FNres{fnr}) / numel(opt.surf); + else + res.resampled.(FNres{fnr}) = res.resampled.(FNres{fnr}) + res.(opt.surf{si}).createCS_resampled.(FNres{fnr}) / numel(opt.surf); + end + end + end + end + + + %% WM and CSF thickness + % Will hopefully be improved in future and may become part of + % cat_surf_parameters and removed here (RD201909) + if opt.surf_measures > 3 + % map WM and CSF width data (corrected by thickness) + facevertexcdata2 = cat_surf_fun('isocolors',Ywdt,CS.vertices,Smat.matlabi_mm); + facevertexcdata2c = max(eps,facevertexcdata2 - facevertexcdata/2); + cat_io_FreeSurfer('write_surf_data',P(si).Pgwo,facevertexcdata2c); % gyrus width WM only + facevertexcdata2c = correctWMdepth(CS,facevertexcdata2c,100,0.2); + cat_io_FreeSurfer('write_surf_data',P(si).Pgww,facevertexcdata2c); % gyrus width WM only + facevertexcdata3c = facevertexcdata2c + facevertexcdata; % ); + cat_io_FreeSurfer('write_surf_data',P(si).Pgw,facevertexcdata3c); clear facevertexcdata3c; % gyrus width (WM and GM) + facevertexcdata4 = estimateWMdepthgradient(CS,facevertexcdata2c); clear facevertexcdata2c; + cat_io_FreeSurfer('write_surf_data',P(si).Pgwwg,facevertexcdata4); clear facevertexcdata4; % gyrus width WM only > gradient + + % smooth resampled values + try %#ok + cmd = sprintf('CAT_BlurSurfHK ""%s"" ""%s"" ""%g"" ""%s""',P(si).Pcentral,P(si).Pgwwg,3,P(si).Pgwwg); + cat_system(cmd,opt.verb-3); + end + + facevertexcdata3 = cat_surf_fun('isocolors',Ycdt,CS.vertices,Smat.matlabi_mm); + facevertexcdata3 = max(eps,facevertexcdata3 - facevertexcdata/2); + cat_io_FreeSurfer('write_surf_data',P(si).Psw,facevertexcdata3); + end + + + % create output structure + S.(opt.surf{si}) = struct('faces',CS.faces,'vertices',CS.vertices,'th1',facevertexcdata); clear facevertexcdata; + if opt.surf_measures > 3 + S.(opt.surf{si}) = setfield(S.(opt.surf{si}),'th2',facevertexcdata2); clear facevertexcdata2; + S.(opt.surf{si}) = setfield(S.(opt.surf{si}),'th3',facevertexcdata3); clear facevertexcdata3; + end + clear Yth1i + + + % we have to delete the original faces, because they have a different + % number of vertices after CAT_FixTopology! + if exist(P(si).Praw ,'file'), delete(P(si).Praw); end + if exist(P(si).Psphere0 ,'file'), delete(P(si).Psphere0); end + if exist(Vpp1.fname ,'file'), delete(Vpp1.fname); end + if exist(Vpp.fname ,'file') && ~opt.outputpp.native, delete(Vpp.fname); end + if opt.verb > 2 && exist(P(si).Pdefects0,'file'), delete(P(si).Pdefects0); end + clear CS + + % processing time per side for manual tests + if si == numel(opt.surf) && si == 1 + cat_io_cmd(' ','g5','',opt.verb); + fprintf('%5ds\n',round(etime(clock,cstime))); + end + end + + % calculate surface quality parameters for all surfaces + res = cat_surf_createCS_fun('addSurfaceQualityMeasures',res,opt); + + % print final stats + cat_surf_createCS_fun('evalProcessing',res,opt,P,V0); + %evalProcessing(res,opt,P,V0) + +end +%========================================================================== +function res = addSurfaceQualityMeasures(res,opt) +%addSurfaceQualityMeasures. Measures to describe surface properties. + res.mnth = []; res.sdth = []; + res.mnRMSE_Ypp = []; res.mnRMSE_Ym = []; + res.SIw = []; res.SIp = []; res.SIwa = []; res.SIpa = []; + for si=1:numel(opt.surf) + if any(strcmp(opt.surf{si},{'lh','rh'})) + if isfield(res.(opt.surf{si}).createCS_final,'fsthickness_mn_sd_md_mx') && ... + ~isnan( res.(opt.surf{si}).createCS_final.fsthickness_mn_sd_md_mx(1) ) + res.mnth = [ res.mnth res.(opt.surf{si}).createCS_final.fsthickness_mn_sd_md_mx(1) ]; + res.sdth = [ res.sdth res.(opt.surf{si}).createCS_final.fsthickness_mn_sd_md_mx(2) ]; + else + res.mnth = [ res.mnth res.(opt.surf{si}).createCS_final.thickness_mn_sd_md_mx(1) ]; + res.sdth = [ res.sdth res.(opt.surf{si}).createCS_final.thickness_mn_sd_md_mx(2) ]; + end + res.mnRMSE_Ym = [ res.mnRMSE_Ym mean([... + res.(opt.surf{si}).createCS_final.RMSE_Ym_layer4 ... + res.(opt.surf{si}).createCS_final.RMSE_Ym_white ... + res.(opt.surf{si}).createCS_final.RMSE_Ym_pial ]) ]; + res.mnRMSE_Ypp = [ res.mnRMSE_Ypp mean([... + res.(opt.surf{si}).createCS_final.RMSE_Ypp_central ... + res.(opt.surf{si}).createCS_final.RMSE_Ypp_white ... + res.(opt.surf{si}).createCS_final.RMSE_Ypp_pial ]) ]; + if isfield(res.(opt.surf{si}).createCS_final,'white_self_interections') + res.SIw = [ res.SIw res.(opt.surf{si}).createCS_final.white_self_interections ]; + res.SIp = [ res.SIp res.(opt.surf{si}).createCS_final.pial_self_interections ]; + res.SIwa = [ res.SIwa res.(opt.surf{si}).createCS_final.white_self_interection_area ]; + res.SIpa = [ res.SIpa res.(opt.surf{si}).createCS_final.pial_self_interection_area ]; + end + end + end + + % final res structure + res.EC = NaN; + res.defect_size = NaN; + res.defect_area = NaN; + res.defects = NaN; + res.mnth = mean(res.mnth); + res.sdth = mean(res.sdth); + res.RMSE_Ym = mean(res.mnRMSE_Ym); + res.RMSE_Ypp = mean(res.mnRMSE_Ypp); + if isfield(res.(opt.surf{si}).createCS_final,'white_self_interections') + res.self_intersections = mean([res.SIw,res.SIp]); + res.self_intersections_area = mean([res.SIwa,res.SIpa]); + end +end +%========================================================================== +function evalProcessing(res,opt,P,V0) + if opt.verb && ~opt.vol + % display some evaluation + % - For normal use we limited the surface measures. + % - Surface intensity would be interesting as cortical measure similar to thickness (also age dependent). + % Especially the outer surface will describe the sulcal blurring in children. + % But the mixing of surface quality and anatomical features is problematic. + % - The position value describes how good the transformation of the PBT map into a surface worked. + % Also the position values depend on age. Children have worse pial values due to sulcal blurring but + % the white surface is may effected by aging, e.g., by WMHs. + % - However, for both intensity and position some (average) maps would be also interesting. + % Especially, some Kappa similar measure that describes the differences to the Ym or Ypp would be nice. + % - What does the Euler characteristic say? Wouldn't the defect number more useful for users? + + if any(~cellfun('isempty',strfind(opt.surf,'cb'))), cbtxt = 'cerebral '; else, cbtxt = ''; end + fprintf('Final %ssurface processing results: \n', cbtxt); + + % function to estimate the number of interactions of the surface deformation: d=distance in mm and a=accuracy + QMC = cat_io_colormaps('marks+',17); + color = @(m) QMC(max(1,min(size(QMC,1),round(((m-1)*3)+1))),:); + rate = @(x,best,worst) min(6,max(1, max(0,x-best) ./ (worst-best) * 5 + 1)); + + if cat_get_defaults('extopts.expertgui') + % color output currently only for expert ... + if isfield(res.(opt.surf{1}).createCS_final,'fsthickness_mn_sd_md_mx') + fprintf(' Average thickness (FS): '); + else + fprintf(' Average thickness (PBT): '); + end + cat_io_cprintf( color( rate( abs( res.mnth - 2.5 ) , 0 , 2.0 )) , sprintf('%0.4f' , res.mnth ) ); fprintf(' %s ',native2unicode(177, 'latin1')); + cat_io_cprintf( color( rate( abs( res.sdth - 0.5 ) , 0 , 1.0 )) , sprintf('%0.4f mm\n', res.sdth ) ); + + fprintf(' Surface intensity / position RMSE: '); + cat_io_cprintf( color( rate( mean(res.mnRMSE_Ym) , 0.05 , 0.3 ) ) , sprintf('%0.4f / ', mean(res.mnRMSE_Ym) ) ); + cat_io_cprintf( color( rate( mean(res.mnRMSE_Ypp) , 0.05 , 0.3 ) ) , sprintf('%0.4f\n', mean(res.mnRMSE_Ypp) ) ); + + if isfield(res.(opt.surf{1}).createCS_final,'white_self_interections') + fprintf(' Pial/white self-intersections: '); + cat_io_cprintf( color( rate( mean([res.SIw,res.SIp]) , 0 , 20 ) ) , sprintf('%0.2f%%%% (%0.2f mm%s)\n' , mean([res.SIw,res.SIp]) , mean([res.SIwa,res.SIpa]) , char(178) ) ); + end + else + fprintf(' Average thickness: %0.4f %s %0.4f mm\n' , res.mnth, native2unicode(177, 'latin1'), res.sdth); + end + + for si=1:numel(P) + fprintf(' Display thickness: %s\n',spm_file(P(si).Pthick,'link','cat_surf_display(''%s'')')); + end + + %% surfaces in spm_orthview + if exist(P(si).Pm,'file'), Po = P(si).Pm; else, Po = V0.fname; end + if ~exist(Po,'file') && exist([V0.fname '.gz'],'file'), Po = [V0.fname '.gz']; end + + Porthfiles = '{'; Porthcolor = '{'; Porthnames = '{'; + for si=1:numel(P) + Porthfiles = [ Porthfiles , sprintf('''%s'',''%s'',',P(si).Ppial, P(si).Pwhite )]; + Porthcolor = [ Porthcolor , '''-g'',''-r'',' ]; + Porthnames = [ Porthnames , '''pial'',''white'',' ]; + end + Porthfiles = [ Porthfiles(1:end-1) '}']; + Porthcolor = [ Porthcolor(1:end-1) '}']; + Porthnames = [ Porthnames(1:end-1) '}']; + + if 1 %debug + fprintf(' Show surfaces in orthview: %s\n',spm_file(Po ,'link',... + sprintf('cat_surf_fun(''show_orthview'',%s,''%s'',%s,%s)',Porthfiles,Po,Porthcolor,Porthnames))) ; + end + + end +end +%======================================================================= +function varargout = cat_vol_genus0opt(Yo,th,limit,debug) +% cat_vol_genus0opt: Voxel-based topology optimization and surface creation +% The correction of large defects is often not optimal and this function +% uses only small corrections. +% +% [Yc,S] = cat_vol_genus0vol(Yo[,limit,debug]) +% +% Yc .. corrected volume +% Yo .. original volume +% S .. surface +% th .. threshold for creating surface +% limit .. maximum number of voxels to correct a defect (default = 30) +% debug .. print details. +% + + if nargin < 2, th = 0.5; end + if nargin < 3, limit = 30; end + if nargin < 4, debug = 0; end + + Yc = Yo; nooptimization = limit==0; %#ok + if limit==0 + % use all corrections + if nargout>1 + txt = evalc(sprintf('[Yc,S.faces,S.vertices] = cat_vol_genus0(Yo,th,nooptimization);')); + else + txt = evalc(sprintf('Yc = cat_vol_genus0(Yo,th,nooptimization);')); + end + + if debug, fprintf(txt); end + else + % use only some corrections + txt = evalc(sprintf('Yc = cat_vol_genus0(Yo,th,nooptimization);')); + + % remove larger corrections + Yvxcorr = abs(Yc - (Yo > th))>0; + Yvxdef = spm_bwlabel( double( Yvxcorr ) ); clear Yppiscrc; + Yvxdef = cat_vol_morph(Yvxdef,'l',[inf limit]) > 0; % large corrections that we remove + + if debug + fprintf(txt); + fprintf(' Number of voxels of genus-topocorr: %d\n Finally used corrections: %0.2f%%\n', ... + sum(Yvxcorr(:)) , 100 * sum(Yvxcorr(:) & ~Yvxdef(:)) / sum(Yvxcorr(:)) ); + end + + Yc = Yc & ~Yvxdef; + + % final surface creation without correction + if nargout>1 + evalc(sprintf('[Yt,S.faces,S.vertices] = cat_vol_genus0( single(Yc) ,th,1);')); + end + + end + + varargout{1} = Yc; + if nargout>1, varargout{2} = S; end +end +%======================================================================= +function saveSurf(CS,P) + save(gifti(struct('faces',CS.faces,'vertices',CS.vertices)),P,'Base64Binary'); %#ok +end +%======================================================================= +function CS1 = loadSurf(P) + if ~exist(P,'file'), error('Surface file %s could not be found due to previous processing errors.',P); end + + try + CS = gifti(P); + catch + error('Surface file %s could not be read due to previous processing errors.',P); + end + + CS1.vertices = CS.vertices; CS1.faces = CS.faces; + if isfield(CS,'cdata'), CS1.cdata = CS.cdata; end +end +%======================================================================= +function CS = correctReducePatch(CS) + % remove bad faces + badv = find( sum( spm_mesh_neighbours(CS)>0,2) == 2); + badf = []; for fi=1:numel(badv); [badfi,badfj] = find( CS.faces == badv(fi) ); badf = [badf;badfi]; end + CS.faces(badf,:) = []; + for fi=numel(badv):-1:1; CS.faces(CS.faces > badv(fi)) = CS.faces(CS.faces > badv(fi)) - 1; end + CS.vertices(badv,:) = []; +end +%======================================================================= +function [cdata,i] = correctWMdepth(CS,cdata,iter,lengthfactor) +% ______________________________________________________________________ +% Correct deep WM depth values that does not fit to the local thickness +% of the local gyri. +% +% length factor should be between 0.2 and 0.4 +% ______________________________________________________________________ + + if ~exist('lengthfactor','var'), lengthfactor = 1/3; end + if ~exist('iter','var'), iter = 100; end + + %% + SV = CS.vertices; % Surface Vertices + SE = unique([CS.faces(:,1:2);CS.faces(:,2:3);CS.faces(:,3:-2:1)],'rows'); % Surface Edges + SEv = single(diff(cat(3,SV(SE(:,1),:),SV(SE(:,2),:)),1,3)); % Surface Edge Vector + SEL = sum(SEv.^2,2).^0.5; % Surface Edge Length + clear SEv + + + %% + i=0; cdatac = cdata+1; pc = 1; oc = 0; + while i0.05 ); + i=i+1; cdatac = cdata; + + M = (cdatac(SE(:,1)) - SEL(SE(:,1))*lengthfactor ) > cdatac(SE(:,2)); + cdata(SE(M,1)) = cdatac(SE(M,2)) + SEL(SE(M,1))*lengthfactor; + M = (cdata(SE(:,2)) - SEL(SE(:,2))*lengthfactor ) > cdatac(SE(:,1)); + cdata(SE(M,2)) = cdatac(SE(M,1)) + SEL(SE(M,1))*lengthfactor; + oc = sum( abs(cdata - cdatac)>0.05 ); + + %fprintf('%d - %8.2f - %d\n',i,sum( abs(cdata - cdatac)>0.05 ),pc~=oc) + + end + +end +%========================================================================== +function Ymf = hippocampus_amygdala_cleanup(Ymf,Ya,vx_vol,close_parahipp,doit) +%% Amygdala hippocampus smoothing. +% We use a median filter to remove the nice details of the hippocampus +% that will cause topology errors and self-intersections. +% Currently, I have no CAT ROI for Amygdala - but it would be more +% robust to filter (simple smoothing) this region strongly because +% the ""random"" details especially in good data introduce more variance. +% (RD 201912) +% RD202107: Added closing of the parahippocampal gyrus. +% +% Ymf = hippocampus_amygdala_cleanup(Ymf,Ya[,doit]) +% +% Ymf .. intensity normalized (WM=3,GM=2,CSF=1) filled and +% skull-stripped image +% Ya .. CAT atlas map +% doit .. do it (default = 1) + + if ~exist('doit','var'), doit = 1; end + + if doit + % remove side definition + NS = @(Ys,s) Ys==s | Ys==s+1; + LAB = cat_get_defaults('extopts.LAB'); + + + %% RD202107: Close CSF region between hippocampus and amygdala + % -------------------------------------------------------------------- + % This could be part of cat_vol_partvol to improve the improve the + % detection of the lower arms of the ventricles. The region has + % slightly increased variance, but much less than the topology problems + % parahippocampal region. Nevertheless, the cuts in some brains that + % trigger the variance are much deeper than we would generally expect + % (e.g. FSaverage) and therefore closing seems appropriate. + % -------------------------------------------------------------------- + if 1 + Ysv = NS(Ya,LAB.PH) & Ymf<1.9 & Ymf>0.5; + Ysv(smooth3(Ysv)<0.5) = 0; + Ysv = cat_vol_morph( Ysv , 'do' , 1.4 , vx_vol); + Ysvd = cat_vol_morph( Ysv , 'dd' , 5 , vx_vol); + Ysvc = cat_vol_morph( (Ysvd & Ymf>2) | Ysv , 'lc', 2 , vx_vol); + Ysvc = smooth3(Ysvc); + Ymf = max( Ymf , Ysvc * 3); + clear Ysv Ysvc Ysvd; + end + + + + %% RD202107: closing parahippocampal gyri + % -------------------------------------------------------------------- + % We are mostly interested in closing of holes in deep parahippocampal + % regions. Hence, we will limit our operations by an enlargements of + % other structures (like sulcal depth). + % Try close parahippocampal gyrus by increasing the intensity of + % GM-WM structures before we filter in the hippocampus. + % -------------------------------------------------------------------- + if close_parahipp + % Limitation by sulcal depth like map. + dd = 1; % this parameter shoulb depend on brain size to work in primates too + Yphn = cat_vol_morph( NS(Ya,LAB.BS) | NS(Ya,LAB.CB) | NS(Ya,LAB.ON) | Ymf==0,'dd',dd * 8, vx_vol) | ... + cat_vol_morph( NS(Ya,LAB.HC),'de',3); % initial definition with extensiion (~ sulcal depth) + Yphn = cat_vol_smooth3X(Yphn,2)>0.5; % soften boundaries + Yphn = cat_vol_morph( Yphn , 'dc' , 4); % close some regions + + % mask by ""obvious"" structures + Ymsk = Ymf>2.1 & cat_vol_morph( NS(Ya,LAB.HC) | NS(Ya,LAB.PH), 'dd' , 3 , vx_vol ) & ~Yphn; + Ymsk(smooth3(Ymsk)<0.5) = 0; + Ymsk = cat_vol_morph( Ymsk , 'dc' , 1.5 , vx_vol ); + + % we need a wider region close to the hippocampus and parahippocampal gyrus + Yg = cat_vol_grad(Ymf); + Ydiv = cat_vol_div(Ymf); + Yphi = cat_vol_morph( NS(Ya,LAB.HC), 'dd' , 5 , vx_vol ) & cat_vol_morph( NS(Ya,LAB.PH), 'dd' , 5 , vx_vol ) & ~Yphn; + Yphx = ( Yphi | cat_vol_morph( NS(Ya,LAB.PH), 'dd' , 2 , vx_vol )) & -Ydiv>(2-Ymf-Yg/3) & ~Yphn; clear Yphi; + Yphx = cat_vol_morph( Yphx & mod(Ya,2)==0, 'l' ) | cat_vol_morph( Yphx & mod(Ya,2)==1, 'l' ); + Yphx = cat_vol_morph( Yphx , 'dc' , 1 , vx_vol ); + clear Yphs Ydiv Yg + + % only one structure per side and only close to the hippocampus and parahippocampal gyrus and closer to the ventricle + % (closing of the deep parahippocampal gyrus) + Yphg = cat_vol_morph( (Ymsk | Yphx ) & mod(Ya,2)==0, 'l' ) | cat_vol_morph( (Ymsk | Yphx ) & mod(Ya,2)==1, 'l' ); + Yphg = Yphg & ~Yphn & cat_vol_morph(NS(Ya,LAB.HC) | NS(Ya,LAB.PH) , 'dd', 3 ); + + % to avoid that our hard changes effect surrounding areas we keep only the inner part in this region + Yphs = cat_vol_morph( cat_vol_morph(Yphg | NS(Ya,LAB.HC) | NS(Ya,LAB.PH),'dc',10) ,'de',2,vx_vol); % we start with the 5 mm of the Yphi! + Yphg = Yphg & Yphs; + + % final corretion + str = 0.5; % higher values = stronger correction) + Ymf = ( (Ymf./3) .^ (1 - str * smooth3(Yphg))) * 3; + Ymf = max( Ymf , min(3,smooth3(Yphg * 4)) ); + else + Yphg = false(size(Ymf)); + end + + + + %% strong cleanup by median filter within the hippocampus + Ymsk = cat_vol_morph( NS(Ya,LAB.PH) | NS(Ya,LAB.ON) | NS(Ya,LAB.BS) , 'dd', 2 ); + Ymsk = Ymf>0 & cat_vol_morph( NS(Ya,LAB.HC) , 'dd' , 3 , vx_vol ) & ~Ymsk & ~Yphg; + Ymf = cat_vol_median3( Ymf , Ymsk ); + Ymf = cat_vol_median3( Ymf , Ymsk ); + + % further cleanup by smoothing + Ymsk = NS(Ya,LAB.PH) | NS(Ya,LAB.ON) | NS(Ya,LAB.BS); + Ymsk = Ymf>0 & NS(Ya,LAB.HC) & ~Ymsk & ~Yphg; + Ymsk = smooth3(Ymsk); + Ymf = min(Ymf,3-Ymsk); + end +end +%========================================================================== +function Ymf = sharpen_cerebellum(Ym,Ymf,Ytemplate,Ya,vx_vol,verb,doit) +%% Sharpening of thin structures in the cerebellum (gyri and sulci) +% Processing of the cerebellum needs a complete updated with a simplified +% reconstruction rather than the maximum level of detail. However, the +% main branches are quite similare and their is a lot of variance in +% aging and between MR protocols. +% (RD 2015-201912) + + dbs = dbstatus; debug = 0; for dbsi=1:numel(dbs), if strcmp(dbs(dbsi).name,mfilename); debug = 1; break; end; end + + if ~exist('doit','var'), doit = 1; end + if ~exist('verb','var'), verb = 0; end + + if doit + if verb>2, fprintf('\n'); stime = cat_io_cmd(' Sharpen cerebellum'); end + %Ytemplate = Ytemplate * 3; + + LAB = cat_get_defaults('extopts.LAB'); + NS = @(Ys,s) Ys==s | Ys==s+1; + Ywmd = cat_vbdist(single(Ymf>2.5),Ymf>1,vx_vol); + + %% normalized Ym divergence + Ydiv = cat_vol_div(max(2,Ymf)); %Ydivl = cat_vol_div(Ymf,vx_vol); + Ydc = cat_vol_localstat(abs(Ydiv),Ymf>0,1,3); + Ydc = cat_vol_localstat(Ydc,Ymf>0,1,1); + Ydiv = Ydiv ./ Ydc; clear Ydc; + Ydiv( abs(Ydiv) > 1.5 ) = 0; + + %% normalized Ytemplate divergence + if ~isempty(Ytemplate) + Ydivt = cat_vol_div(max(2,Ytemplate)); + Ydct = cat_vol_localstat(abs(Ydivt),Ytemplate>0,1,3); + Ydct = cat_vol_localstat(Ydct,Ymf>0,1,1); + Ydivt = Ydivt ./ Ydct; clear Ydct; + Ydivt( abs(Ydivt) > 1.5 ) = 0; + else + Ytemplate = Ymf; + Ydivt = Ydiv; + end + + %% bias-correction based + % WM + Ycsfd = cat_vbdist(single(Ymf<1.8),Ymf>1,vx_vol); + Ymsk = ((cat_vol_morph(NS(Ya,LAB.CB),'e',3) | Ymf) & ( (Ym-Ydiv).*min(1,Ytemplate/3-Ydivt) )>2/3 ) | ... + (NS(Ya,LAB.PH) & ( Ymf>2.2 | (Ymf>2 & Ydiv<-0.01) ) ) | ... % hippocampal gyri + (NS(Ya,LAB.CT) & ( Ymf>2.2 | (Ymf>2 & Ydiv<-0.01 & ... + Ycsfd>cat_stat_nanmean(Ycsfd(Ycsfd(:)>0 & Ycsfd(:)<100)) )*1.0) ); % distant gyri and sulci in the cerebrum + Yi = cat_vol_localstat(Ymf,Ymsk,1,3); + % GM + Ymsk = (NS(Ya,LAB.CB) & ( Ymf>1.9 & Ymf<2.2 & Ycsfd>0 & Ydiv>-0.05) ) | ... % sulci and gyri in the cerebellum + (NS(Ya,LAB.PH) & ( Ymf>1.3 & Ymf<2.2 & Ycsfd>0 ) ) | ... % hippocampal gyri + (NS(Ya,LAB.CT) & ( Ymf>1.3 & Ymf<2.2 & Ycsfd>0 & ... + Ywmd>cat_stat_nanmean(Ywmd(Ywmd(:)>0 & Ywmd(:)<100))*0.2 ) ); % distant gyri and sulci in the cerebrum + Yi = Yi + cat_vol_localstat(Ymf,Yi==0 & Ymsk,1,1)/2*3;%& ( cat_vol_morph(Yi==0,'e') & Ymf>2.2) + Yi = cat_vol_localstat(Yi,Yi>0,1,3); + Yi = cat_vol_localstat(Yi,Yi>0,1,1); + if ~debug, clear Ywmd Ymsk Ycsfd; end + % CSF - instable and not required + Ywi = cat_vol_approx(Yi,'nn',1,1,struct('lfO',2)); clear Yi + + %% only cerebellum + Ycb = cat_vol_smooth3X( NS(Ya,LAB.CB) , 2 ); + Ywi = 3*ones(size(Ywi),'single').*(1-Ycb) + Ycb.*Ywi; clear Ycb + Ymf = Ymf./Ywi * 3; + + % denoising result + Ycb = Ymf .* NS(Ya,LAB.CB); cat_sanlm(Ycb,3,1); Ymf(NS(Ya,LAB.CB)) = Ycb(NS(Ya,LAB.CB)); clear Ycb + + + %% sharpening (RD 201912) + Ycb = (NS(Ya,LAB.CB)>0.5) .* max(0,min(1,min(2,max(-1,(Ymf/3).^2 - 0.1*Ydiv) .* max(-1,Ytemplate/3 - 0.02*Ydivt - 0.03*Ydiv )*3 - 1)/3 + 2/3)); + if ~debug, clear Ydiv; end + for i=1:3, Ycb = max(0,min(1, Ycb - smooth3(cat_vol_median3(Ycb,Ycb>0,Ycb>0) - Ycb) )); end + Ycb = min(1,Ycb); + cat_sanlm(Ycb,3,1); + + %% final mixing + Ymsk = cat_vol_smooth3X(NS(Ya,LAB.CB) & Ycb<1.9/3,0.5); + Ycb = Ycb.*(1-Ymsk) + Ymsk.*Ymf/3; + Ycs = NS(Ya,LAB.CB) .* cat_vol_smooth3X( NS(Ya,LAB.CB) , 4 ); + Ymf = Ymf.*(1-Ycs) + Ycs.*Ycb*3; clear Ycs + + if verb>2, fprintf('%5.0fs\n',etime(clock,stime)); end + end +end +%========================================================================== +function [P,pp0,mrifolder,pp0_surffolder,surffolder,ff] = setFileNames(V0,job,opt) +%setFileNames. Define surface filenames. + + [mrifolder, ~, surffolder] = cat_io_subfolders(V0.fname,job); + + % get original filename without 'n' + [pp0,ff] = spm_fileparts(V0.fname); + + % correct '../' parts in directory for BIDS structure + [stat, val] = fileattrib(fullfile(pp0,surffolder)); + if stat, pp0_surffolder = val.Name; else, pp0_surffolder = fullfile(pp0,surffolder); end + if ~exist(fullfile(pp0_surffolder),'dir'), mkdir(fullfile(pp0_surffolder)); end + + % surface filenames + for si = 1:numel(opt.surf) + P(si).Pm = fullfile(pp0,mrifolder, sprintf('m%s.nii',ff)); % raw + P(si).Pp0 = fullfile(pp0,mrifolder, sprintf('p0%s.nii',ff)); % labelmap + P(si).Praw = fullfile(pp0_surffolder,sprintf('%s.central.nofix.%s.gii',opt.surf{si},ff)); % raw + P(si).Praw2 = fullfile(pp0_surffolder,sprintf('%s.central.nofix_sep.%s.gii',opt.surf{si},ff)); % raw + P(si).Pdefects = fullfile(pp0,mrifolder, sprintf('defects_%s.nii',ff)); % defect + P(si).Pcentral = fullfile(pp0_surffolder,sprintf('%s.central.%s.gii',opt.surf{si},ff)); % central + P(si).Pcentralh = fullfile(pp0_surffolder,sprintf('%s.centralh.%s.gii',opt.surf{si},ff)); % central + P(si).Pcentralr = fullfile(pp0_surffolder,sprintf('%s.central.resampled.%s.gii',opt.surf{si},ff));% central .. used in inactive path + P(si).Ppial = fullfile(pp0_surffolder,sprintf('%s.pial.%s.gii',opt.surf{si},ff)); % pial (GM/CSF) + P(si).Pwhite = fullfile(pp0_surffolder,sprintf('%s.white.%s.gii',opt.surf{si},ff)); % white (WM/GM) + P(si).Pthick = fullfile(pp0_surffolder,sprintf('%s.thickness.%s',opt.surf{si},ff)); % FS thickness / GM depth + P(si).Pmsk = fullfile(pp0_surffolder,sprintf('%s.msk.%s',opt.surf{si},ff)); % msk + P(si).Ppbt = fullfile(pp0_surffolder,sprintf('%s.pbt.%s',opt.surf{si},ff)); % PBT thickness / GM depth + P(si).Psphere0 = fullfile(pp0_surffolder,sprintf('%s.sphere.nofix.%s.gii',opt.surf{si},ff)); % sphere.nofix + P(si).Psphere = fullfile(pp0_surffolder,sprintf('%s.sphere.%s.gii',opt.surf{si},ff)); % sphere + P(si).Pspherereg = fullfile(pp0_surffolder,sprintf('%s.sphere.reg.%s.gii',opt.surf{si},ff)); % sphere.reg + P(si).Pgmt = fullfile(pp0,mrifolder, sprintf('%s_thickness-%s.nii',ff,opt.surf{si})); % temp thickness + P(si).Pppm = fullfile(pp0,mrifolder, sprintf('%s_ppm-%s.nii',ff,opt.surf{si})); % temp position map + P(si).Pfsavg = fullfile(opt.fsavgDir, sprintf('%s.central.freesurfer.gii',opt.surf{si})); % fsaverage central + P(si).Pfsavgsph = fullfile(opt.fsavgDir, sprintf('%s.sphere.freesurfer.gii',opt.surf{si})); % fsaverage sphere + % special maps in CS2 + P(si).Player4 = fullfile(pp0_surffolder,sprintf('%s.layer4.%s.gii',opt.surf{si},ff)); % layer4 + P(si).PintL4 = fullfile(pp0_surffolder,sprintf('%s.intlayer4.%s',opt.surf{si},ff)); % layer4 intensity + P(si).Pgwo = fullfile(pp0_surffolder,sprintf('%s.depthWMo.%s',opt.surf{si},ff)); % gyrus width / GWM depth / gyral span + P(si).Pgw = fullfile(pp0_surffolder,sprintf('%s.depthGWM.%s',opt.surf{si},ff)); % gyrus width / GWM depth / gyral span + P(si).Pgww = fullfile(pp0_surffolder,sprintf('%s.depthWM.%s',opt.surf{si},ff)); % gyrus width of the WM / WM depth + P(si).Pgwwg = fullfile(pp0_surffolder,sprintf('%s.depthWMg.%s',opt.surf{si},ff)); % gyrus width of the WM / WM depth + P(si).Psw = fullfile(pp0_surffolder,sprintf('%s.depthCSF.%s',opt.surf{si},ff)); % sulcus width / CSF depth / sulcal span + P(si).Pdefects0 = fullfile(pp0_surffolder,sprintf('%s.defects0.%s',opt.surf{si},ff)); % defects temporary file + end +end +%========================================================================== +function cdata = estimateWMdepthgradient(CS,cdata) +% _________________________________________________________________________ +% Estimates the maximum local gradient of a surface. +% Major use is the WM depth that grows with increasing sulcal depth. +% It measures the amount of WM behind the cortex, but more relevant is +% the amount of WM fibers that this region will add to the WM depth. +% The width of the street next to a house gives not the connectivity of +% this house, but the width of the entrance does! +% This measure can be improved by further information of sulcal depth. +% _________________________________________________________________________ + + % + SV = CS.vertices; % Surface Vertices + SE = unique([CS.faces(:,1:2);CS.faces(:,2:3);CS.faces(:,3:-2:1)],'rows'); % Surface Edges + SEv = single(diff(cat(3,SV(SE(:,1),:),SV(SE(:,2),:)),1,3)); % Surface Edge Vector + SEL = sum(SEv.^2,2).^0.5; % Surface Edge Length + clear SEv + + % + cdata_l = inf(size(cdata),'single'); + cdata_h = zeros(size(cdata),'single'); + for i=1:size(SE,1) + val = (cdata(SE(i,2)) - cdata(SE(i,1)))*SEL(SE(i,1)); + cdata_l(SE(i,1)) = min([cdata_l(SE(i,1)),val]); + cdata_h(SE(i,1)) = max([cdata_h(SE(i,2)),val]); + end + cdata = cdata_h - cdata_l; +end +%========================================================================== +function Ymf = refineYmf(Ymf,Ya,vx_vol,opt,doit) +%refineYmf. Reduction of artifact, blood vessel, and meninges. +% +% Reduction of artifact, blood vessel, and meninges next to the cortex in +% SPM segmentations that are often visible as very thin structures that +% were added to the WM or removed from the brain. +% +% Ymf = refineYmf(Ymf,vx_vol,doit) +% + + % get both sides in the atlas map + NS = @(Ys,s) Ys==s | Ys==s+1; + + if doit + % estimate helping variables (div for fine 1D structures, Ycsfd and + % yctd to define the area close to the skull); + Ydiv = cat_vol_div(Ymf,vx_vol); + Ycsfd = cat_vbdist(single(Ymf<1.8),Ymf>1,vx_vol); + Yctd = cat_vbdist(single(Ymf<0.5),Ymf>0,vx_vol); + Ysroi = Ymf>2 & Yctd<10 & Ycsfd>0 & Ycsfd<2.0 & ... + cat_vol_morph(~NS(Ya,opt.LAB.HC) & ~NS(Ya,opt.LAB.HI) & ... + ~NS(Ya,opt.LAB.PH) & ~NS(Ya,opt.LAB.VT),'erode',4); + clear Ycsfd Yctd; + + Ybv = cat_vol_morph(Ymf+Ydiv./max(1,Ymf)>3.5,'d') & Ymf>2; + Ymf(Ybv) = 1.4; + Ymfs = cat_vol_median3(Ymf,Ysroi | Ybv,Ymf>eps & ~Ybv,0.1); % median filter + mf = min(1,max(0,3-2*mean(vx_vol,2))); % avoid filtering in low res data + Ymf = min(Ymf, mf * Ymfs + (1-mf) * Ymf); + clear Ysroi Ydiv Ybv Ymfs + end + +end +%========================================================================== +function [Ywdt,Ycdt,stime] = estimateGyrusSulcusWidth(Ymf,Ymfs,Yppi,Ym,Ya,opt,vx_vol,BB,resI,V,si,stime) +% estimateGyrusSulcusWidth. PBT estimation of the gyrus and sulcus width. +% +% gyrus width / WM depth: +% For the WM depth estimation it is better to use the L4 boundary and +% correct later for thickness, because the WM is very thin in gyral +% regions and will cause bad values. +% On the other side we do not want the whole filled block of the Yppi map +% and so we have to mix both the original WM map and the Yppi map. Because +% there is no thickness in pure WM regions no correction is needed. + + Ywd = zeros(size(Ymf),'single'); + Ycd = zeros(size(Ymf),'single'); + + NS = @(Ys,s) Ys==s | Ys==s+1; + + stime = cat_io_cmd(' WM depth estimation','g5','',opt.verb-1,stime); + + [Yar,Ymr] = cat_vol_resize({Ya,Ym},'reduceBrain',vx_vol,BB.BB); % removing background + Yar = uint8(cat_vol_resize(Yar,'interp',V,opt.interpV,'nearest')); % interpolate volume + Ymr = cat_vol_resize(Ymr,'interp',V,opt.interpV); % interpolate volume + switch opt.surf{si} + case {'lh'} + Ymr = Ymr .* (Yar>0) .* ~(NS(Yar,3) | NS(Yar,7) | NS(Yar,11) | NS(Yar,13)) .* (mod(Yar,2)==1); + Ynw = smooth3(cat_vol_morph(NS(Yar,5) | NS(Yar,9) | NS(Yar,15) | NS(Yar,23),'d',2) | ... + (cat_vol_morph(Yppi==1,'e',2) & Ymr>1.7/3 & Ymr<2.5/3) & (mod(Yar,2)==1)); + case {'rh'} + Ymr = Ymr .* (Yar>0) .* ~(NS(Yar,3) | NS(Yar,7) | NS(Yar,11) | NS(Yar,13)) .* (mod(Yar,2)==0); + Ynw = smooth3(cat_vol_morph(NS(Yar,5) | NS(Yar,9) | NS(Yar,15) | NS(Yar,23),'d',2) | ... + (cat_vol_morph(Yppi==1,'e',2) & Ymr>1.7/3 & Ymr<2.5/3) & (mod(Yar,2)==0)); + case {'cb'} + Ymr = Ymr .* (Yar>0) .* NS(Yar,3); + Ynw = true(size(Ymr)); + end + clear Yar; + + % + Yppis = Yppi .* (1-Ynw) + max(0,min(1,Ymr*3-2)) .* Ynw; clear Ynw; % adding real WM map + Ywdt = cat_vol_eidist(1-Yppis,ones(size(Yppis),'single')); % estimate distance map to central/WM surface + Ywdt = cat_vol_pbtp(max(2,4-Ymfs),Ywdt,inf(size(Ywdt),'single'))*opt.interpV; + [D,I] = cat_vbdist(single(Ywdt>0.01),Yppis>0); Ywdt = Ywdt(I); clear D I Yppis; % add further values around the cortex + Ywdt = cat_vol_median3(Ywdt,Ywdt>0.01,Ywdt>0.01); + Ywdt = cat_vol_localstat(Ywdt,Ywdt>0.1,1,1); % smoothing + Ywdt = cat_vol_resize(Ywdt,'deinterp',resI); % back to original resolution + Ywdt = cat_vol_resize(Ywdt,'dereduceBrain',BB); % adding background + Ywdt = max(Ywd,Ywdt); + clear Ywd; + + % sulcus width / CSF depth + % for the CSF depth we cannot use the original data, because of + % sulcal blurring, but we got the PP map at half distance and + % correct later for half thickness + stime = cat_io_cmd(' CSF depth estimation','g5','',opt.verb-1,stime); + YM = single(smooth3(cat_vol_morph(Ymr<0.1,'o',4))<0.5); YM(YM==0)=nan; % smooth CSF/background-skull boundary + Yppis = Yppi .* ((Ymr+0.25)>Yppi) + min(1,Ymr*3-1) .* ((Ymr+0.25)<=Yppi); % we want also CSF within the ventricle (for tests) + Ycdt = cat_vol_eidist(Yppis,YM); % distance to the central/CSF-GM boundary + Ycdt = cat_vol_pbtp(max(2,Ymfs),Ycdt,inf(size(Ycdt),'single'))*opt.interpV; Ycdt(isnan(Ycdt))=0; + [D,I] = cat_vbdist(single(Ycdt>0),Yppis>0 & Yppis<3); Ycdt = Ycdt(I); clear D I Yppis; % add further values around the cortex + Ycdt = cat_vol_median3(Ycdt,Ycdt>0.01,Ycdt>0.01); % median filtering + Ycdt = cat_vol_localstat(Ycdt,Ycdt>0.1,1,1); % smoothing + Ycdt = cat_vol_resize(Ycdt,'deinterp',resI); % back to original resolution + Ycdt = cat_vol_resize(Ycdt,'dereduceBrain',BB); % adding background + Ycdt = max(Ycd,Ycdt); + clear Ywd Ycd; + +end +%========================================================================== +function writeDefectData(Ymfs,CS,CSraw0,P,vdefects,sdefects,Smat,si) + %% + try + CSraw = loadSurf(P(si).Praw); + + Yvdef = cat_surf_fun('surf2vol',struct('vertices',CSraw0.vertices,'faces',CSraw.faces),Ymfs>1.1,(vdefects)>0,'val',struct('mat',Smat.matlabIBB_mm,'verb',0)); + Ysdef = cat_surf_fun('surf2vol',struct('vertices',CSraw.vertices ,'faces',CSraw.faces),Ymfs>1.1,(sdefects)>0,'val',struct('mat',Smat.matlabIBB_mm,'verb',0)); + + Yvdef(isnan(Yvdef)) = 0; + Ysdef(isnan(Ysdef)) = 0; + + Ydef = Yvdef + Ysdef; clear Ysdef; + [Ydef,ndef] = spm_bwlabel(double(Ydef)); + Ydefn = Ydef; + for i = 1:ndef + Ydefn(Ydef==i) = nnz(Ydef(:)==i) / max(1,nnz(Ydef(:)>0)); + end + + defects = cat_surf_fun('isocolors', Ydefn, CS.vertices, Smat.matlabIBB_mm, 'nearest'); + cat_io_FreeSurfer('write_surf_data', P(si).Pdefects, defects); + clear defects Ydef Ydefn; + catch + disp('error'); + end +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_plot_boxplot.m",".m","49460","1490","function [out,s] = cat_plot_boxplot(data,opt) +% _________________________________________________________________________ +% +% usage: [out, s] = cat_plot_boxplot(data,opt); +% +% opt.style = 0; predefined styles: +% 0 - boxplot +% 1 - violinplot +% 2 - violinplot with integrated boxplot +% 3 - densityplot +% 4 - boxplot with jittered data points +% opt.notched = 0; thinner at median [0 1] with 1=0.5 +% opt.symbol = '+o'; outlier symbols +% opt.vertical = 1; boxplot orientation +% opt.maxwhisker = 1.5; +% opt.sort = 0; no sorting +% = 1; sort groups (ascending) +% = 2; sort groups (descending)[inactive] +% = [index]; or by a index matrix +% opt.names = []; array of group names +% opt.fill = 1; filling of boxes: 0 - no filling; 0.5 - half-filled boxes; 1 - filled boxes +% opt.groupnum = 1; add number of elements +% [opt.groupmin = 5;] minimum number of non-nan-elements +% in a group [inactive] +% opt.xlim = [-inf inf]; x-axis scaling +% opt.ylim = [-inf inf]; y-axis scaling +% opt.ygrid = 1; activate y-grid-lines +% opt.gridline = '-'; grid line-style +% opt.box = 1; plot box +% opt.usescatter = 0; use scatter plot (with transparency) for showdata=2 +% opt.outliers = 1; plot outliers +% opt.violin = 0; violin-plot: 0 - box plot; 1 - violin plot; 2 - violin + thin box plot +% opt.boxwidth = 0.8; width of box +% opt.groupcolor = [R G B]; matrix with (group)-bar-color(s) +% default is nejm(numel(data)) +% or other color functions (see also cat_io_colormaps for categorical colormaps) +% opt.symbolcolor = 'r'; color of symbols +% opt.fontsize = []; axis fontsize (important for ygrid size!) +% opt.showdata = 0; show data points: +% 0 - no; +% 1 - as colored points; +% 2 - as jittered points according to density; +% 3 - as short lines (barcode plot); +% opt.datasymbol = '.'; symbol for data points (only valid for showdata = 1 or 2) +% opt.median = 2; show median: 0 - no; 1 - line; 2 - with different fill colors +% opt.edgecolor = 'none'; edge color of box +% opt.changecolor = 0; use brighter values for double color entries, e.g. +% [red red blue blue] becomes [red light-red blue light-blue] +% opt.trans = 0.25; transparency of the box +% opt.switch = 0; switch between rows and column of data for numeric data (non-cell) +% opt.sat = 0.50; saturation of the box +% opt.subsets = false(1,numel(data)); +% opt.hflip = 0; flip x-axis in case of horizontal bars +% opt.darkmode = 0; dark color mode with black background +% opt.I = []; optional definition of replications, subjects, groups and time points to +% support plot of connected data. Replications should be defined in 1st +% column, all other columns are recognized automatically. +% This matrix can be used from SPM.xX.I. +% +% The returned matrix s has one column for each dataset as follows: +% +% 1 minimum +% 2 1st quartile +% 3 2nd quartile (median) +% 4 3rd quartile +% 5 maximum +% 6 lower confidence limit for median +% 7 upper confidence limit for median +% +% The box plot is a graphical display that simultaneously describes several +% important features of a data set, such as center, spread, departure from +% symmetry, and identification of observations that lie unusually far from +% the bulk of the data. +% +% data is a matrix with one column for each dataset, or data is a cell +% vector with one cell for each dataset. +% opt.notched = 1 produces a notched-box plot. Notches represent a robust +% estimate of the uncertainty about the median. +% opt.notched = 0 (default) produces a rectangular box plot. +% opt.notched in (0,1) produces a notch of the specified depth. +% opt.notched values outside [0,1] are amusing if not exactly practical. +% opt.notched sets the notched for the outlier values, default notched for +% points that lie outside 3 times the interquartile range is 'o', +% default opt.notched for points between 1.5 and 3 times the interquartile +% range is '+'. +% +% Examples +% opt.notched = '.' points between 1.5 and 3 times the IQR is marked with +% '.' and points outside 3 times IQR with 'o'. +% opt.notched = ['x','*'] points between 1.5 and 3 times the IQR is marked with +% 'x' and points outside 3 times IQR with '*'. +% opt.vertical = 0 makes the boxes horizontal, by default opt.vertical = 1. +% maxwhisker defines the length of the whiskers as a function of the IQR +% (default = 1.5). If maxwhisker = 0 then boxplot displays all data +% values outside the box using the plotting opt.notched for points that lie +% outside 3 times the IQR. +% +% The returned matrix s has one column for each dataset as follows: +% +% 1 minimum +% 2 1st quartile +% 3 2nd quartile (median) +% 4 3rd quartile +% 5 maximum +% 6 lower confidence limit for median +% 7 upper confidence limit for median +% +% Example +% +% title(""Grade 3 heights""); +% tics(""x"",1:2,[""girls"";""boys""]); +% axis([0,3]); +% cat_plot_boxplot({randn(10,1)*5+140, randn(13,1)*8+135}); +% +% _________________________________________________________________________ +% +% Author: Alberto Terruzzi +% Version: 1.4 +% Created: 6 January 2002 +% Copyright (C) 2002 Alberto Terruzzi +% +% This program is free software; you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation; either version 2 of the License, or +% (at your option) any later version. +% +% This program is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% You should have received a copy of the GNU General Public License +% along with this program; if not, write to the Free Software +% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +% +% modified by Christian Gaser (christian.gaser@uni-jena.de) and +% Robert Dahnke (robert.dahnke@uni-jena.de) +% original version was written for octave by Alberto Terruzzi +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +if nargin==0, help cat_plot_boxplot; return; end + +% batch mode +if isstruct(data) + out = cat_stat_boxplot_batch(data); + return +end + +% default parameter +if ~exist('opt','var'), opt = struct(''); end + +% data has to be defined as cell and should be converted if numeric +if isnumeric(data) + if isfield(opt,'switch') && opt.switch + data = data'; + end + sz = size(data); + tmp = data; clear data + data = cell(sz(2),1); + for i = 1:sz(2) + data{i} = tmp(:,i); + end +end + +% disable connected time points if you have defined more than one sample +offset = 0; +if isfield(opt,'I') && ~isempty(opt.I) + + % transpose if necessary + sz = size(opt.I); + if sz(2) > sz(1), I = I'; sz = size(I); end + + % add replication and group if not defined + if sz(2) == 3 + opt.I = [ones(sz(1),1) opt.I]; + sz = size(opt.I); + elseif sz(2) == 2 + opt.I = [ones(sz(1),1) opt.I(:,1) ones(sz(1),1) opt.I(:,2)]; + end + + if numel(data) > 1 + fprintf('Disable flag for defining time points, because it can only be used for one sample.\n'); + opt.I = []; + else + if numel(data{1}) ~= sz(1) + error('Size mismatch between data (n=%d) and time points (n=%d)',numel(data{1}),sz(1)); + else + + I1 = opt.I; + % column with the maximum value defines subjects + [x,y] = find(I1==max(I1(:))); + col_subj = y(1); + I1(:,col_subj) = 0; % set subject values to zero for further search + + % column with varying numbers for one subject defines time points (or replications) + [x,y] = find(diff(I1(x,:))~=0); + col_tp = y(1); + I1(:,col_tp) = 0; % set replication values to zero for further search + + % get column which defines groups (where maximum number is found in + % remaining values + [x,y] = find(I1==max(I1(:))); + col_group = max(y); + + % remaining column defines replications + ind = 1:4; + ind([col_group col_tp col_subj]) = []; + col_repl = ind; + + % otherwise rebuild data cells according to time points and groups + data0 = data{1}; + opt.I = opt.I(:,[col_tp col_subj col_group col_repl]); + offset = 0; + names = []; + I1 = opt.I; + + for i = 1:max(opt.I(:,col_group)) + ind3 = opt.I(:,col_group) == i; + for j = 1:max(opt.I(ind3,col_tp)) + + % prepare names + names = char(names,sprintf('%d-%d',i,j)); + + ind4 = opt.I(:,col_tp) == j; + data1{j+offset} = data{1}(ind3 & ind4); + + % create new opt.I with new TP number + I1(ind3 & ind4,col_tp) = j + offset; + I1(ind3 & ind4,col_group) = 1; + end + offset = offset + max(opt.I(ind3,col_tp)); + end + data = data1; clear data1 + opt.I = I1; clear I1 + + if ~isfield(opt,'names') + names(1,:) = []; + opt.names = names; + end + end + end +end + +hold off + +def.notched = 0; +def.symbol = '+o'; +def.vertical = 1; +def.maxwhisker = 1.5; +def.sort = 0; +def.names = num2str( (1:numel(data))' ); +def.fill = 1; +def.groupcolor = cat_io_colormaps('nejm',numel(data)); +def.symbolcolor = 'r'; +def.groupnum = 0; +def.groupmin = 5; +def.ylim = []; +def.xlim = []; +def.ygrid = 0; +def.gridline = '-'; +def.boxwidth = 0.8; +def.box = 1; +def.outliers = 1; +def.violin = 0; +def.usescatter = 0; +def.fontsize = []; % empty = default font size +def.showdata = 0; +def.datasymbol = '.'; +def.median = 2; % show median: 0 - no; 1 - line; 2 - with different fill colors +def.edgecolor = 'none'; % edgecolor of boxes +def.changecolor = 0; % use brighter values for double color entries, e.g. + % [red red blue blue] becomes [red light-red blue light-blue] +def.trans = 0.25; % transparency of boxes +def.sat = 0.50; % saturation of boxes +def.subsets = false(1,numel(data)); +def.hflip = 0; % flip x-axis in case of horizontal bars +def.switch = 0; % switch between columns and rows of data +def.darkmode = 0; % switch to dark color mode +def.I = []; + +% use predefined styles +if isfield(opt,'style') + switch opt.style + case 0 % use defaults for boxplot + case 1 + def.violin = 1; def.showdata = 3; def.ygrid = 1; def.gridline = ':'; + case 2 + def.violin = 2; def.showdata = 3; def.ygrid = 1; def.gridline = ':'; + case 3 + def.violin = 1; def.showdata = 1; def.vertical = 0; def.fill = 0.5; + def.median = 1; def.boxwidth = 2.75; def.ygrid = 1; def.gridline = ':'; + case 4 + def.violin = 0; def.showdata = 2; def.ygrid = 1; def.gridline = ':'; + end +end + +opt = cat_io_checkinopt(opt,def); +opt.notched = max(0,min(1,opt.notched)); +opt.trans = max(0,min(1,opt.trans * (opt.sat*4) )); + +% always use connected time points together with plot of raw data as points +if ~isempty(opt.I) && opt.showdata ~= 1 + opt.showdata = 1; +end + +if opt.darkmode + bkg = [0 0 0]; +else + bkg = [1 1 1]; +end + +if max(opt.subsets)>1 + subsets = zeros(1,numel(data)); + subsets(opt.subsets+1) = 1; + opt.subsets = mod(cumsum(subsets),2); +end + +% first data box on the top +if ~opt.vertical + if opt.hflip + for di=1:numel(data), data{di} = -data{di}; end + opt.ylim = fliplr(-opt.ylim); + if isfield(opt,'ytick'), opt.ytick = fliplr(-opt.ytick); end + else + % we have to switch order of data, names and colors + data2 = data; + for i=1:length(data) + data2{length(data)+1-i} = data{i}; + end + data = data2; + opt.names = flipud(opt.names); + opt.groupcolor(1:numel(data),:) = flipud(opt.groupcolor(1:numel(data),:)); + opt.subsets = flipud(opt.subsets); + end +end + +% always use filling for this median plot option +if opt.median == 2 + if opt.fill == 0 + fprintf('Filling will be always enabled if median is set to 2.\n'); + opt.fill = 1; + end +end + +% always use filling for this median plot option +if opt.fill == 0.5 && opt.vertical + fprintf('Filling with 0.5 will only works in horizontal view. Set filling to 1.\n'); + opt.fill = 1; +end + +% either violin or box plot +if opt.violin, opt.box = 0; end +if opt.box, opt.violin = 0; end + +% figure out how many data sets we have +if iscell(data) + nc = length(data); + for nci=1:nc, data{nci}=data{nci}(:); end +else + if isvector(data), data = data(:); end + nc = columns(data); +end + +opt.names = cellstr(opt.names); +if numel(opt.names) < nc + error('ERROR:cat_plot_boxplot:names','ERROR: Too short name list.'); +end + +% update colortable +if size(opt.groupcolor,1)==1 + opt.groupcolor = repmat(opt.groupcolor(1,:),numel(data),1); +end + +% if the same color is used multiple times you may want to change it... +if opt.changecolor + tmpcolor = opt.groupcolor(1,:); + for ci = 2:size(opt.groupcolor,1) + if all(opt.groupcolor(ci,:)==tmpcolor) + opt.groupcolor(ci,:) = max(0,min(1,opt.groupcolor(ci-1,:) .* repmat(1 + 0.02 * opt.changecolor,1,3))); + else + tmpcolor = opt.groupcolor(ci,:); + end + end +end +if numel(opt.sort)>1 && numel(opt.sort) ~= nc + error('ERROR:cat_plot_boxplot:sort','ERROR: Too short list.'); +end + +groupnr = cellfun(@(x) sum(~isnan(x)),data); +out.sortj = 1:length(data); +rmdata = zeros(1,nc); +% remove groups with too few elemnts +% ... require addaption for many other fields like names, color, ... +if 0 && opt.groupmin>0 + rmdata=cellfun('isempty',data) | groupnr 1) + % min,max and quartiles + s(1:5,i) = [min(col) prctile(col,[25 50 75]) max(col)]'; + % confidence interval for the median + est = 1.57*(s(4,i)-s(2,i))/sqrt(nd); + s(6,i) = max([s(3,i)-est, s(2,i)]); + s(7,i) = min([s(3,i)+est, s(4,i)]); + % whiskers out to the last point within the desired inter-quartile range + IQR = opt.maxwhisker*(s(4,i)-s(2,i)); + whisker_y(:,i) = [min(col(col >= s(2,i)-IQR)); s(2,i)]; + whisker_y(:,nc+i) = [max(col(col <= s(4,i)+IQR)); s(4,i)]; + % outliers beyond 1 and 2 inter-quartile ranges + ol = (col < s(2,i)-IQR & col >= s(2,i)-2*IQR) | (col > s(4,i)+IQR & col <= s(4,i)+2*IQR); + ol2 = col < s(2,i)-2*IQR | col > s(4,i)+2*IQR; + outliers = col(ol); + outliers2 = col(ol2); + + oll1 = (col < s(2,i)-IQR & col >= s(2,i)-2*IQR); + olh1 = (col > s(4,i)+IQR & col <= s(4,i)+2*IQR); + oll2 = col < s(2,i)-2*IQR; + olh2 = col > s(4,i)+2*IQR; + + ind = 1:numel(col); + out.names = opt.names; + out.indn.l1{i} = ind(oll1); + out.indn.l2{i} = ind(oll2); + out.indn.h1{i} = ind(olh1); + out.indn.h2{i} = ind(olh2); + out.matn.l1{i} = oll1; + out.matn.l2{i} = oll2; + out.matn.h1{i} = olh1; + out.matn.h2{i} = olh2; + + if exist('sorti','var'), out.sorti = sorti; end + out.indo.l1{out.sortj(i)} = ind(oll1); + out.indo.l2{out.sortj(i)} = ind(oll2); + out.indo.h1{out.sortj(i)} = ind(olh1); + out.indo.h2{out.sortj(i)} = ind(olh2); + out.mato.l1{out.sorti(i)} = oll1; + out.mato.l2{out.sorti(i)} = oll2; + out.mato.h1{out.sorti(i)} = olh1; + out.mato.h2{out.sorti(i)} = olh2; + + outliers_x = [outliers_x; i*ones(size(outliers))]; + outliers_y = [outliers_y; outliers]; + outliers2_x = [outliers2_x; i*ones(size(outliers2))]; + outliers2_y = [outliers2_y; outliers2]; + elseif (nd == 1) + % all statistics collapse to the value of the point + s(:,i) = col; + % single point data sets are plotted as outliers. + outliers_x = [outliers_x; i]; + outliers_y = [outliers_y; col]; + else + % no statistics if no points + s(:,i) = NaN; + end + + if ~isempty(opt.ylim) + outliers_y = max(opt.ylim(1),min(opt.ylim(2),outliers_y)); + outliers2_y = max(opt.ylim(1),min(opt.ylim(2),outliers2_y)); + end + +end + +% Note which boxes don't have enough stats +chop = find(box <= 1); + +% Draw a box around the quartiles, with width proportional to the number of +% items in the box. Draw notches if desired. +if opt.boxwidth<0 + box = repmat(abs(opt.boxwidth) * 0.4,1,numel(box)); +else + box = box*(opt.boxwidth/2/max(box)); +end + +quartile_x = ones(11,1)*[1:nc] + [-a;-1;-1;1;1;a;1;1;-1;-1;-a]*box; +quartile_y = s([3,7,4,4,7,3,6,2,2,6,3],:); + +% thinner boxplot as option for violin plot +quartile_xthin = ones(11,1)*[1:nc] + [-1;-1;-1;1;1;1;1;1;-1;-1;-1]*0.035*ones(1,nc); +quartile_ythin = s([3,7,4,4,7,3,6,2,2,6,3],:); + +% quartiles below median for different filling colors +if ~opt.vertical && opt.hflip + quartile_xl = ones(7,1)*[1:nc] + [a;1;1;-1;-1;-a;a]*box; + quartile_yl = s([3,7,4,4,7,3,3],:); +else + quartile_xl = ones(7,1)*[1:nc] + [a;1;1;-1;-1;-a;a]*box; + quartile_yl = s([3,6,2,2,6,3,3],:); +end + +% Draw a line through the median +median_x = ones(2,1)*[1:nc] + [-a;+a]*box; +median_y = s([3,3],:); + +% Chop all boxes which don't have enough stats +opt.groupcolor2 = opt.groupcolor; +opt.groupcolor2(chop,:) = []; +quartile_x(:,chop) = []; +quartile_y(:,chop) = []; +quartile_xl(:,chop) = []; +quartile_yl(:,chop) = []; +whisker_x(:,[chop,chop+nc]) = []; +whisker_y(:,[chop,chop+nc]) = []; +median_x(:,chop) = []; +median_y(:,chop) = []; + +% Add caps to the remaining whiskers +cap_x = whisker_x; +cap_x(1,:) = cap_x(1,:) - 0.1; +cap_x(2,:) = cap_x(2,:) + 0.1; +cap_y = whisker_y([1,1],:); +datac = cell2mat(data(:)); +vp = 10^(1+round(abs(diff([min(datac(:)),max(datac(:))]))^(1/10) )); + +% use different limits for y-axis for violin plot +if opt.violin + if isempty(opt.ylim) || isinf(opt.ylim(1)), opt.ylim(1) = min(U(:)); end + if numel(opt.ylim)<2 || isinf(opt.ylim(2)), opt.ylim(2) = max(U(:)); end +else + if isempty(opt.ylim) || isinf(opt.ylim(1)), opt.ylim(1) = floor((min(datac(:)) - abs(diff([min(datac(:)),max(datac(:))]))/10) * vp)/vp; end + if numel(opt.ylim)<2 || isinf(opt.ylim(2)), opt.ylim(2) = ceil((max(datac(:)) + abs(diff([min(datac(:)),max(datac(:))]))/10) * vp)/vp; end +end + +%% Do the plot +children0=get(gca,'Children'); + +qn = size(quartile_x,2); + +% switch x and y values for horizontal plot +if ~opt.vertical + tmp = cap_x; cap_x = cap_y; cap_y = tmp; + tmp = quartile_x; quartile_x = quartile_y; quartile_y = tmp; + tmp = quartile_xl; quartile_xl = quartile_yl; quartile_yl = tmp; + tmp = whisker_x; whisker_x = whisker_y; whisker_y = tmp; + tmp = outliers_x; outliers_x = outliers_y; outliers_y = tmp; + tmp = outliers2_x; outliers2_x = outliers2_y; outliers2_y = tmp; + tmp = quartile_xthin; quartile_xthin = quartile_ythin; quartile_ythin = tmp; +end + +% optional add jitter in the range of 0.025..1 +add_jitter = max(0.025,min([1,log10(qn)/10])); + +for i=1:qn + + if opt.fill + tcol = [1 1 1]; + tdef = struct('FaceAlpha',1-opt.trans,'EdgeColor','none'); + fcol = opt.groupcolor(i,:); + fdef = struct('FaceAlpha',opt.sat,'EdgeColor',opt.edgecolor); + fdefm = struct('FaceAlpha',0.25,'EdgeColor','none'); + else + tcol = struct('Color',bkg); + fcol = struct('Color',opt.groupcolor(i,:)); + end + + % offset for filling with 0.5 depending on boxwidth + if opt.fill == 0.5 && ~opt.vertical + offset = max(0.25,sqrt(opt.boxwidth)/4); + else + offset = 0; + end + + % violin plot + if opt.violin + indn = max(find(U(:,i) 0.5 + x = [x;flipud(U(:,i))]; + y = [y;flipud(i-offset-F(:,i))]; + xm = [xm;flipud(U(1:indn,i))]; + ym = [ym;flipud(i-F(1:indn,i))]; + elseif opt.fill == 0.5 + mny = min(y); mxy = max(y); + median_x(:,i) = [mny mxy]; + y(1) = mny; y(end) = mny; + end + end + + if opt.fill + if opt.trans, fill(x,y,tcol,tdef); end % just a white box as background + fill(x,y,fcol,tdef); + if i==1, hold on; end + + if opt.median == 2 + if opt.trans, fill(xm,ym,tcol,tdef); end + fill(xm,ym,0.5*fcol,fdefm); + end + + else + if opt.trans, plot(x,y,tcol); end + plot(x,y,fcol); + if i==1, hold on; end + end + + % add thin box plot + if opt.violin == 2 + if opt.fill + fill(quartile_xthin(:,i), quartile_ythin(:,i)-offset,[0.5 0.5 0.5]); + else + plot(quartile_xthin(:,i), quartile_ythin(:,i),'Color',[0.5 0.5 0.5]); + end + plot(whisker_x(:,[i i+qn]), whisker_y(:,[i i+qn])-offset,'Color',[0.5 0.5 0.5]); + end + + end + + % for dark mode we have to increase visibility + if opt.darkmode, scl = 2; else scl = 1; end + + if opt.box + if opt.fill + if opt.trans, fill(quartile_x(:,i), quartile_y(:,i),'b-','FaceColor',bkg,tdef); end + + fill(quartile_x(:,i), quartile_y(:,i),'b-','FaceColor',opt.groupcolor2(i,:),'FaceAlpha',min([scl*opt.sat,1]),'EdgeColor','none'); + if i==1, hold on; end + + if opt.median == 2 + fill(quartile_xl(:,i), quartile_yl(:,i),'b-','FaceColor',0.5*opt.groupcolor2(i,:),fdef); + end + + else + plot(quartile_x(:,i), quartile_y(:,i),'Color',opt.groupcolor2(i,:)); + if i==1, hold on; end + end + + plot(cap_x(:,[i i+qn]), cap_y(:,[i i+qn]),'Color',[0.5 0.5 0.5]); + plot(whisker_x(:,[i i+qn]), whisker_y(:,[i i+qn]),'Color',[0.5 0.5 0.5]); + if ~strcmp(opt.edgecolor,'none') + plot(quartile_x(:,i), quartile_y(:,i),'Color',opt.edgecolor); + end + + end + + % optionally also show data either as points or short lines + if opt.showdata == 1 + if i==1, hold on; end + if opt.vertical + x = (i-offset)*ones(1,length(data{i})); y = data{i}(:); + else + y = (i-offset)*ones(1,length(data{i})); x = data{i}(:); + end + h = plot(x,y,opt.datasymbol,'Color',scl*0.25*opt.groupcolor2(i,:)); + if opt.fill == 0.5 + set(h, 'MarkerSize',12); + end + + elseif opt.showdata == 2 + if i==1, hold on; end + ii = i; + + % offset for chopped elements + if ~isempty(chop) + ii = ii + cumsum(i>=chop); + end + +try + data{ii}(isnan(data{ii}) | isinf(data{ii})) = []; +catch + continue +end + % estimate kde + n2 = 0; + % Get the next data set from the array or cell array + if iscell(data), col = data{ii}(:); + else col = data(:,ii); end + % estimate # of mesh points w.r.t. data size + n2 = max(n2,ceil(log2(numel(col)))) - 2; + + % create jitter w.r.t. kde + jitter_kde = zeros(1,length(data{ii})); + + % only allow kde estimation if enough data are available + if numel(data{ii})>5 + try + [tmp, f, u] = kde(data{ii},2^n2); + f = (f/max(f)*opt.boxwidth*0.075)'; % width of violin plot is more narrow + catch % kde don't like data without any variance + [tmp, f, u] = kde(data{ii} + eps*randn(size(data{ii})),2^n2); + f = (f/max(f)*opt.boxwidth*0.075)'; % width of violin plot is more narrow + end + % shift sections by step/2 and add one step + u = u + gradient(u)/2; + u = [u 1e15]; + + for k=1:numel(f) + jitter_kde(data{ii}>u(k) & data{ii}<=u(k+1)) = f(k); + end + end + + jitter_kde = jitter_kde.*randn(1,length(data{ii})); + + % make jitter smaller for violinplot + if opt.violin, jitter_kde = 0.5*jitter_kde; end + + % transpose for horizontal view and cut lower half + if ~opt.vertical, jitter_kde = 0.9*abs(jitter_kde)'; end + + if opt.vertical + x = (ii-offset)*ones(1,length(data{ii}))+jitter_kde; y = data{ii}(:); + else + y = (ii-offset)*ones(length(data{ii}),1)+jitter_kde; x = data{ii}(:); + end + if opt.usescatter + sc = scatter(x,y,opt.datasymbol, ... + 'MarkerEdgeColor',scl*0.3*opt.groupcolor(ii,:),... + 'MarkerFaceColor',scl*0.3*opt.groupcolor(ii,:),... + 'MarkerEdgeAlpha',0.05 + 0.25/numel(x).^.3, ... + 'MarkerFaceAlpha',0.05 + 0.25/numel(x).^.3); + if opt.datasymbol, sc.SizeData = 12; end % dotlike but with transparency + else + plot(x,y,opt.datasymbol,'Color',[scl*0.3*opt.groupcolor(ii,:)]); + end + elseif opt.showdata == 3 + if i==1, hold on; end + if opt.vertical + x = ([-.025*ones(length(data{i}),1) .025*ones(length(data{i}),1)]+i)'; y = ([data{i}(:) data{i}(:)])'; + else + y = ([-.025*ones(length(data{i}),1) .025*ones(length(data{i}),1)]+i)'; x = ([data{i}(:) data{i}(:)])'; + end + line(x,y,'Color',scl*0.4*opt.groupcolor(i,:)); + end + + if opt.median == 1 + if opt.groupcolor2(i,1)>0.2 && opt.groupcolor2(i,2)<0.5 && opt.groupcolor2(i,3)<0.5 + col = [0.5 0 0]; + else + col = [1 0 0]; + end + if opt.vertical + plot(median_x(:,i), median_y(:,i),'Color',col) + else + plot(median_y(:,i), median_x(:,i),'Color',col) + end + end + + end + + if opt.symbol(1)~=' ' && opt.outliers + plot(outliers_x, outliers_y-offset ,'MarkerSize',... + max(4,min(8,80/nc)),'Marker',opt.symbol(1),'MarkerEdgeColor',opt.symbolcolor,'LineStyle','none') + end + + if opt.symbol(2)~=' ' && opt.outliers + plot(outliers2_x, outliers2_y-offset,'MarkerSize',... + max(4,min(8,80/nc)),'Marker',opt.symbol(2),'MarkerEdgeColor',opt.symbolcolor,'LineStyle','none'); + end + + if all( cellfun(@all,cellfun(@isnan,data,'uniformOutput',false) )) + hold off; + text(numel(data)/2 + 1/2,0.5,'No (non-NaN) data!','color',[0.8 0 0],'FontWeight','Bold','HorizontalAlignment','center'); + opt.ygrid = 0; + hold on; + end + if ~opt.vertical + set(gca,'YTick',1:numel(opt.names),'YTickLabel',opt.names,'TickLength',[0 0],'ylim',[0.5 numel(opt.names)+0.5]); + if ~isempty(opt.ylim) && diff(opt.ylim)~=0 && ~all( isnan(opt.ylim) ) + xlim(gca,opt.ylim); + end + if ~isempty(opt.xlim) && diff(opt.xlim)~=0 && ~all( isnan(opt.xlim) ) + ylim(gca,opt.xlim); + end + else + set(gca,'XTick',1:numel(opt.names),'XTickLabel',opt.names,'TickLength',[0 0],'xlim',[0.5 numel(opt.names)+0.5]); + if ~isempty(opt.ylim) && diff(opt.ylim)~=0 && ~all( isnan(opt.ylim) ) + ylim(gca,opt.ylim); + end + if ~isempty(opt.xlim) && diff(opt.xlim)~=0 && ~all( isnan(opt.xlim) ) + xlim(gca,opt.xlim); + end + end + + try, set(gca,'TickLabelInterpreter','none'); end + + if ~isempty(opt.fontsize) + set(gca,'FontSize',opt.fontsize); + end + + + % plot yticks + + if opt.ygrid + if strcmp(opt.gridline,'-') + linecolor = [0.8 0.8 0.8]; + else + linecolor = [0.65 0.65 0.65]; + end + %% + if opt.vertical, xytick = 'Ytick'; xylab = 'YTickLabel'; else xytick = 'Xtick'; xylab = 'XTickLabel'; end + if isfield(opt,'ytick') + ytick = opt.ytick; + else + ytick=get(gca,xytick); + if numel(ytick)<5, ytick=interp1(ytick,1:0.5:numel(ytick)); elseif numel(ytick)>10, ytick=ytick(1:2:end); end + end + set(gca,xytick,ytick); + acc = sprintf('%%0.%df',abs(str2double(char(regexp(num2str(min(diff(ytick)),'%e'),'[+-]..','match'))))); + if ~opt.vertical && opt.hflip + set(gca,xylab,num2str(-ytick',acc)); + else + set(gca,xylab,num2str( ytick',acc)); + end + + if ytick(1)<=opt.ylim(1)+eps, ytick(1)=[]; end + if ytick(end)>=opt.ylim(2)-eps, ytick(end)=[]; end + if opt.vertical + x = repmat(xlim',1,numel(ytick)); y = [ytick;ytick]; + else + y = repmat(ylim',1,numel(ytick)); x = [ytick;ytick]; + end + h1 = plot(x,y,'Color',linecolor,'Linestyle',opt.gridline); + uistack(h1,'bottom') + + % subgrid (just a brighter line without value) + if opt.ygrid>1 + %% + ytick1 = get(gca,xytick); + ytick2 = ytick1(1):( diff([ytick1(1),ytick1(end)]) / ((numel(ytick1)-1)*opt.ygrid)):ytick1(end); + ytick2 = setdiff(ytick2,ytick1); + + if opt.vertical + x = repmat([0;numel(opt.names)+1],1,numel(ytick2)); y = [ytick2;ytick2]; + else + y = repmat([0;numel(opt.names)+1],1,numel(ytick2)); x = [ytick2;ytick2]; + end + h2 = plot(x,y,'Color',linecolor*0.25+0.75*ones(1,3),'Linestyle',opt.gridline); + uistack(h2,'bottom') + end + end + + %% subsets + if any(opt.subsets) + f2 = []; + if opt.vertical + %% + for i = find(opt.subsets) + f2 = [f2 fill([i-0.5 i+0.5 i+0.5 i-0.5],sort([ylim ylim]),'b-','FaceColor',1-bkg,'FaceAlpha',0.04,'EdgeColor','none')]; %#ok + end + else + %% + for i = find(opt.subsets) + f2 = [f2 fill(sort([xlim xlim]),[i-0.5 i+0.5 i+0.5 i-0.5],'b-','FaceColor',1-bkg,'FaceAlpha',0.04,'EdgeColor','none')]; %#ok + end + end + for i=1:numel(f2), uistack(f2(i),'bottom'); end + if exist('h1','var'), uistack(h1,'bottom'); end + if opt.ygrid>1, uistack(h2,'bottom'); end + end + +%% + +if ~isempty(opt.I) + + % use different colors for dark mode and later try whether we can use + % transparency or not + if opt.darkmode + col = [0.8 0.8 0.8 0.25]; + col2 = [0.4 0.4 0.4]; + else + col = [0 0 0.5 0.25]; + col2 = [0.8 0.8 0.8]; + end + for j = 1:max(opt.I(:,2)) + ind = find(opt.I(:,2) == j); + if opt.vertical + x = opt.I(ind,4) + offset; y = data0(ind); + else + if opt.fill == 0.5 + x = data0(ind); y = 1 + max(opt.I(:,4)) - opt.I(ind,4) - offset; + else + x = data0(ind); y = opt.I(ind,4) + offset; + end + end + try + line(x,y,'Color',col); + catch + line(x,y,'Color',col2); + end + end + +end + +hold off + +if ~nargout + clear out +end + +end + +function y = prctile(x,p,dim) +%PRCTILE Percentiles of a sample. +% Y = PRCTILE(X,P) returns percentiles of the values in X. P is a scalar +% or a vector of percent values. When X is a vector, Y is the same size +% as P, and Y(i) contains the P(i)-th percentile. When X is a matrix, +% the i-th row of Y contains the P(i)-th percentiles of each column of X. +% For N-D arrays, PRCTILE operates along the first non-singleton +% dimension. +% +% Y = PRCTILE(X,P,DIM) calculates percentiles along dimension DIM. The +% DIM'th dimension of Y has length LENGTH(P). +% +% Percentiles are specified using percentages, from 0 to 100. For an N +% element vector X, PRCTILE computes percentiles as follows: +% 1) The sorted values in X are taken as the 100*(0.5/N), 100*(1.5/N), +% ..., 100*((N-0.5)/N) percentiles. +% 2) Linear interpolation is used to compute percentiles for percent +% values between 100*(0.5/N) and 100*((N-0.5)/N) +% 3) The minimum or maximum values in X are assigned to percentiles +% for percent values outside that range. +% +% PRCTILE treats NaNs as missing values, and removes them. +% +% Examples: +% y = prctile(x,50); % the median of x +% y = prctile(x,[2.5 25 50 75 97.5]); % a useful summary of x +% +% See also IQR, MEDIAN, NANMEDIAN, QUANTILE. + +% Copyright 1993-2004 The MathWorks, Inc. +% $Revision$ $Date$ + + +if ~isvector(p) || numel(p) == 0 + error('stats:prctile:BadPercents', ... + 'P must be a scalar or a non-empty vector.'); +elseif any(p < 0 | p > 100) || ~isreal(p) + error('stats:prctile:BadPercents', ... + 'P must take real values between 0 and 100'); +end + +% Figure out which dimension prctile will work along. +sz = size(x); +if nargin < 3 + dim = find(sz ~= 1,1); + if isempty(dim) + dim = 1; + end + dimArgGiven = false; +else + % Permute the array so that the requested dimension is the first dim. + nDimsX = ndims(x); + perm = [dim:max(nDimsX,dim) 1:dim-1]; + x = permute(x,perm); + % Pad with ones if dim > ndims. + if dim > nDimsX + sz = [sz ones(1,dim-nDimsX)]; + end + sz = sz(perm); + dim = 1; + dimArgGiven = true; +end + +% If X is empty, return all NaNs. +if isempty(x) + if isequal(x,[]) && ~dimArgGiven + y = nan(size(p),class(x)); + else + szout = sz; szout(dim) = numel(p); + y = nan(szout,class(x)); + end + +else + % Drop X's leading singleton dims, and combine its trailing dims. This + % leaves a matrix, and we can work along columns. + nrows = sz(dim); + ncols = prod(sz) ./ nrows; + x = reshape(x, nrows, ncols); + + x = sort(x,1); + nonnans = ~isnan(x); + + % If there are no NaNs, do all cols at once. + if all(nonnans(:)) + n = sz(dim); + if isequal(p,50) % make the median fast + if rem(n,2) % n is odd + y = x((n+1)/2,:); + else % n is even + y = (x(n/2,:) + x(n/2+1,:))/2; + end + else + q = [0 100*(0.5:(n-0.5))./n 100]'; + xx = [x(1,:); x(1:n,:); x(n,:)]; + y = zeros(numel(p), ncols, class(x)); + y(:,:) = interp1q(q,xx,p(:)); + end + + % If there are NaNs, work on each column separately. + else + % Get percentiles of the non-NaN values in each column. + y = nan(numel(p), ncols, class(x)); + for j = 1:ncols + nj = find(nonnans(:,j),1,'last'); + if nj > 0 + if isequal(p,50) % make the median fast + if rem(nj,2) % nj is odd + y(:,j) = x((nj+1)/2,j); + else % nj is even + y(:,j) = (x(nj/2,j) + x(nj/2+1,j))/2; + end + else + q = [0 100*(0.5:(nj-0.5))./nj 100]'; + xx = [x(1,j); x(1:nj,j); x(nj,j)]; + y(:,j) = interp1q(q,xx,p(:)); + end + end + end + end + + % Reshape Y to conform to X's original shape and size. + szout = sz; szout(dim) = numel(p); + y = reshape(y,szout); +end +% undo the DIM permutation +if dimArgGiven + y = ipermute(y,perm); +end + +% If X is a vector, the shape of Y should follow that of P, unless an +% explicit DIM arg was given. +if ~dimArgGiven && isvector(x) + y = reshape(y,size(p)); +end +end + +function [bandwidth,density,xmesh,cdf]=kde(data,n,MIN,MAX) +% Reliable and extremely fast kernel density estimator for one-dimensional data; +% Gaussian kernel is assumed and the bandwidth is chosen automatically; +% Unlike many other implementations, this one is immune to problems +% caused by multimodal densities with widely separated modes (see example). The +% estimation does not deteriorate for multimodal densities, because we never assume +% a parametric model for the data. +% INPUTS: +% data - a vector of data from which the density estimate is constructed; +% n - the number of mesh points used in the uniform discretization of the +% interval [MIN, MAX]; n has to be a power of two; if n is not a power of two, then +% n is rounded up to the next power of two, i.e., n is set to n=2^ceil(log2(n)); +% the default value of n is n=2^12; +% MIN, MAX - defines the interval [MIN,MAX] on which the density estimate is constructed; +% the default values of MIN and MAX are: +% MIN=min(data)-Range/10 and MAX=max(data)+Range/10, where Range=max(data)-min(data); +% OUTPUTS: +% bandwidth - the optimal bandwidth (Gaussian kernel assumed); +% density - column vector of length 'n' with the values of the density +% estimate at the grid points; +% xmesh - the grid over which the density estimate is computed; +% - If no output is requested, then the code automatically plots a graph of +% the density estimate. +% cdf - column vector of length 'n' with the values of the cdf +% Reference: +% Kernel density estimation via diffusion +% Z. I. Botev, J. F. Grotowski, and D. P. Kroese (2010) +% Annals of Statistics, Volume 38, Number 5, pages 2916-2957. + +% +% Example: +% data=[randn(100,1);randn(100,1)*2+35 ;randn(100,1)+55]; +% kde(data,2^14,min(data)-5,max(data)+5); + +data=data(:); %make data a column vector +if nargin<2 % if n is not supplied switch to the default + n=2^14; +end +n=2^ceil(log2(n)); % round up n to the next power of 2; +if nargin<4 %define the default interval [MIN,MAX] + minimum=min(data); maximum=max(data); + Range=maximum-minimum; + MIN=minimum-Range/2; MAX=maximum+Range/2; +end +if MIN==MAX, MIN=MIN-1; MAX=MAX+1; end +% set up the grid over which the density estimate is computed; +R=MAX-MIN; dx=R/(n-1); xmesh=MIN+[0:dx:R]; N=length(unique(data)); +%bin the data uniformly using the grid defined above; +initial_data=histc(data,xmesh)/N; initial_data=initial_data/sum(initial_data); +a=dct1d(initial_data); % discrete cosine transform of initial data +% now compute the optimal bandwidth^2 using the referenced method +I=[1:n-1]'.^2; a2=(a(2:end)/2).^2; +% use fzero to solve the equation t=zeta*gamma^[5](t) +t_star=root(@(t)fixed_point(t,N,I,a2),N); +% smooth the discrete cosine transform of initial data using t_star +a_t=a.*exp(-[0:n-1]'.^2*pi^2*t_star/2); +% now apply the inverse discrete cosine transform +if (nargout>1)|(nargout==0) + density=idct1d(a_t)/R; +end +% take the rescaling of the data into account +bandwidth=sqrt(t_star)*R; +density(density<0)=eps; % remove negatives due to round-off error +if nargout==0 + figure(1), plot(xmesh,density) +end +% for cdf estimation +if nargout>3 + f=2*pi^2*sum(I.*a2.*exp(-I*pi^2*t_star)); + t_cdf=(sqrt(pi)*f*N)^(-2/3); + % now get values of cdf on grid points using IDCT and cumsum function + a_cdf=a.*exp(-[0:n-1]'.^2*pi^2*t_cdf/2); + cdf=cumsum(idct1d(a_cdf))*(dx/R); + % take the rescaling into account if the bandwidth value is required + bandwidth_cdf=sqrt(t_cdf)*R; +end + +end + +%--------------------------------------------- +function out=fixed_point(t,N,I,a2) +% this implements the function t-zeta*gamma^[l](t) +if isempty(a2), a2=0; end +l=7; +f=2*pi^(2*l)*sum(I.^l.*a2.*exp(-I*pi^2*t)); +for s=l-1:-1:2 + K0=prod([1:2:2*s-1])/sqrt(2*pi); const=(1+(1/2)^(s+1/2))/3; + time=(2*const*K0/N/f)^(2/(3+2*s)); + f=2*pi^(2*s)*sum(I.^s.*a2.*exp(-I*pi^2*time)); +end +out=t-(2*N*sqrt(pi)*f)^(-2/5); +end + +%--------------------------------------------- +function out = idct1d(data) + +% computes the inverse discrete cosine transform +[nrows,ncols]=size(data); +% Compute weights +weights = nrows*exp(i*(0:nrows-1)*pi/(2*nrows)).'; +% Compute x tilde using equation (5.93) in Jain +data = real(ifft(weights.*data)); +% Re-order elements of each column according to equations (5.93) and +% (5.94) in Jain +out = zeros(nrows,1); +out(1:2:nrows) = data(1:nrows/2); +out(2:2:nrows) = data(nrows:-1:nrows/2+1); +% Reference: +% A. K. Jain, ""Fundamentals of Digital Image +% Processing"", pp. 150-153. +end +%--------------------------------------------- + +function data=dct1d(data) +% computes the discrete cosine transform of the column vector data +[nrows,ncols]= size(data); +% Compute weights to multiply DFT coefficients +weight = [1;2*(exp(-i*(1:nrows-1)*pi/(2*nrows))).']; +% Re-order the elements of the columns of x +data = [ data(1:2:end,:); data(end:-2:2,:) ]; +% Multiply FFT by weights: +data= real(weight.* fft(data)); +end + +function t=root(f,N) +% try to find smallest root whenever there is more than one +N=50*(N<=50)+1050*(N>=1050)+N*((N<1050)&(N>50)); +tol=10^-12+0.01*(N-50)/1000; +flag=0; +while flag==0 + try + t=fzero(f,[0,tol]); + flag=1; + catch + tol=min(tol*2,.1); % double search interval + end + if tol==.1 % if all else fails + t=fminbnd(@(x)abs(f(x)),0,.1); flag=1; + end +end +end + +function fh = cat_stat_boxplot_batch(job) +% +% TODO +% * andere inputs? +% - volume? +% . volume +% . intensity of non 0/nan? +% - surfaces +% . area +% . values? +% - atlas label data? +% +% * Data +% D: +% . XML-files +% . Name +% E: +% + color +% + ylim +% + subgroup +% +% * output: +% * Table output: +% - ouptut table: none | figure | command line | text ouput of table +% - output of [mean, median, min, max, std] +% - see vbm script +% + + if isfield(job,'set'), job.data = job.set; end + job.extopts.edgecolor = 'none'; + job.output.dpi = 300; + + %% load XML data + xml = cell(1,numel(job.data)); + for gi = 1:numel(job.data) + files = cellstr(char(job.data(gi).files)); + xml{gi} = cat_io_xml( files ); + end + + %% + fh = cell(1,numel(job.xmlfields)); data = fh; + for vi = 1:numel( job.xmlfields ) + % error handling + + % extract the current datafield to a common use data structure + % that is used for cat_plot_boxplot + for gi = 1:numel(job.data) + for fi = 1:numel( job.data(gi).files ) + try + if isfield( job.xmlfields{vi} , 'xmlfields' ) + fname = job.xmlfields{vi}.xmlfields; + eval( sprintf( 'data{vi}{gi}(fi) = double([xml{gi}(fi).%s]);' , job.xmlfields{vi}.xmlfields ) ); + else + fname = job.xmlfields{vi}; + eval( sprintf( 'data{vi}{gi}(fi) = double([xml{gi}(fi).%s]);' , job.xmlfields{vi} ) ); + end + catch + eval( sprintf( 'data{vi}{gi}(fi) = nan;' ) ); + end + end + end + fname = strrep(fname,'_',' '); + + % create the parameter structure for cat_plot_boxplot + jobpara = cat_io_checkinopt( job.opts , job.extopts ); + + % get general groupcolor field before the group-wise settings + if isfield( jobpara , 'colorset' ) + eval(sprintf('jobpara.groupcolor = %s(%d);', jobpara.colorset , numel(job.data))); + end + % group-wise settings of the name and color of each group/box + for gi = 1:numel(job.data) + if ~isempty( job.data(gi).setname ) + jobpara.names{gi} = job.data(gi).setname; + else + jobpara.names{gi} = sprintf('%d',gi); + end + if ~isempty( job.data(gi).setcolor ) + jobpara.groupcolor2(gi,:) = job.data(gi).setcolor; + end + end + + % specific title and ylabel for predefined CAT XML fields + keysets = {'qualitymeasures.','qualityratings.','subjectmeasures.'}; + if ~isempty( strfind( keysets , fname ) ) + point = find( fname=='.' ); + if numel(jobpara.title)>0 && jobpara.title(1)=='+' + jobpara.title = [upper(fname(1)) fname(2:point-1) ' ' upper(fname(point+1)) fname(point+2:end) jobpara.title ' ' jobpara.title(2:end)]; + else + jobpara.title = [upper(fname(1)) fname(2:point-1) ' ' upper(fname(point+1)) fname(point+2:end) jobpara.title]; + end + % jobpara = setval(jobpara,vi,'title', [upper(fname(1)) fname(2:point-1) ' ' upper(fname(point+1)) fname(point+2:end) ]); + jobpara = setval(jobpara,vi,'yname', fname(point+1:end) ); + end + if isfield(jobpara,'FS'), jobpara.FS = jobpara.FS; end + % jobpara = setval(jobpara,vi,'xlabel' ); + + if isfield( job.data(gi) , 'subset') + jobpara.subsets(gi) = job.data(gi).subset; + end + + % create figure + fh{vi} = figure(1033 + vi); + if isfield(jobpara,'fsize') + fh{vi}.PaperPosition(3:4) = jobpara.fsize; + fh{vi}.Position(3:4) = round(jobpara.fsize * 60); %[560 420]/2; + else + fh{vi}.Position(3:4) = [560 420]/2; + end + if isfield( jobpara , 'title') && ~isempty( jobpara.title ) + fh{vi}.Name = jobpara.title; + end + if ~jobpara.menubar + fh{vi}.ToolBar = 'none'; + fh{vi}.MenuBar = 'none'; + end + + + % call cat_plot_boxplot + cat_plot_boxplot( data{vi} ,jobpara ); + ax = gca; + + + % further settings + if isfield( jobpara , 'title') && ~isempty( jobpara.title ) + ax.Title.String = jobpara.title; + end + if isfield( jobpara , 'yname') && ~isempty( jobpara.yname ) + ax.YLabel.String = jobpara.yname; + end + if isfield( jobpara , 'xlabel') && ~isempty( jobpara.xlabel ) + ax.XLabel.String = jobpara.xlabel; + end + if ~isempty( jobpara.FS ) + ax.FontSize = jobpara.FS; + ax.YLabel.FontSize = jobpara.FS*1.2; + ax.XLabel.FontSize = jobpara.FS*1.2; + end + box('on') + + + %% save images + if isempty( job.output.outdir{1} ), outdir = pwd; else, outdir = job.output.outdir{1}; end + pdir = fullfile( outdir, job.output.subdir); + if ~exist(pdir,'dir'), mkdir(pdir); end + types = {'fig','png','jpeg','pdf','epsc'}; + fh{vi}.PaperPosition(3:4) = fh{vi}.PaperPosition(3:4) * 2; % don't know why ... + for ti = 1:numel(types) + if strfind( job.output.type , types{ti} ) + if strcmp( job.output.type , 'fig' ) + savefig(fh{vi}, fullfile(pdir, [job.output.name fname '.' types{ti} ] ) ); + else + try + print(fh{vi}, ['-d' types{ti}], sprintf('-r%d',job.output.dpi), ... + fullfile(pdir, [types{ti} '_' job.output.name fname '.' types{ti} ] ) ); + end + end + end + end + fh{vi}.PaperPosition(3:4) = fh{vi}.PaperPosition(3:4) / 2; + + if job.output.close, close( fh{vi} ); end + end + +end + +function S = setval( S , i , fname , val ) + if isfield( S , fname ) + if iscell( S.(fname) ) && numel( S.(fname) )>=i + if ~isempty( S.(fname){vi} ) + val = S.(fname){i}; + S = rmfield( S.(fname){i} ); + end + S.(fname) = val; + + else + if isempty( S.(fname) ) + S.(fname) = val; + end + end + else + S.(fname) = val; + end +end + + + + +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_io_send_to_server.m",".m","902","30","function cat_io_send_to_server(urlinfo) +% ______________________________________________________________________ +% +% Send status information to Piwik server +% +% cat_io_send_to_server(urlinfo); +% +% urlinfo .. piwik status information +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +urlinfo = regexprep(urlinfo, '\n', '%20'); % replace returns +urlinfo = regexprep(urlinfo, ' ' , '%20'); % replace spaces + +piwikserver = 'http://dbm.neuro.uni-jena.de/piwik/piwik.php?idsite=1&rec=1&action_name='; +url = sprintf('%s%s',piwikserver,urlinfo); + +try + [s,sts] = urlread(url,'Timeout',2); +catch + [s,sts] = urlread(url); +end + +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_io_rmdir.m",".m","1229","43","function cat_io_rmdir(dirs) +% _________________________________________________________________________ +% Recusively remove empty subdirectories, whereas the original MATLAB rmdir +% removes only the deepest empty subdirectory or all subdirectories incl. +% all files ('s' option). +% +% cat_io_rmdir(dirs) +% +% dirs = char or cellstr of directories +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + dirs = cellstr(dirs); + + subdirs = cell(0); + for s=1:numel(dirs) + subdirs = [subdirs;cat_vol_findfiles(dirs{s},'*',struct('dirs',1))]; %#ok + end + subdirs = unique(subdirs); + clear dirs; + + % sort subdirs by length + dsubdirs = cellfun('length',subdirs); + [tmp,si] = sort(dsubdirs,'descend'); %#ok + subdirs = subdirs(si); + clear dsubdirs tmp si; + + % remove empty dirs step by step + for si=1:numel(subdirs) + if exist(subdirs{si},'dir') + try %#ok + rmdir(subdirs{si}); + end + end + end + +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_vol_eidist.m",".m","2974","73","%cat_vol_eidist Voxel-based eikonal distance calculation. +% This function estimates the Euclidean distance D to the closest boundary +% voxel I given by the 0.5 isolevel in B that should contain values +% between 0 and 1 to define the boundary using PVE. To align the closest +% voxel a modified Eikonal distances is estimated on the field L. +% +% For a correct side alignment a harder option ""csf"" is used that avoids +% the diffusion to voxels with greater values of L (L[i]>L[ni] for +% diffusion). +% +% Voxels with NaN and -INF are ignored and produce NaN in D, whereas +% in I the default index is used, because I has to be a integer matrix +% where NaN is not available. With setnan=0, the result of NAN voxel in +% D is changed to INF. +% +% [D,I,Dw] = cat_vol_eidist(B,L,[vx_vol,euclid,csf,setnan,verb]) +% +% D .. Euclidean distance map to the nearest Boundary point in the +% Eikonal field (3d-single-matrix) +% (air distance) +% D .. Euclidean distance map in the Eikonal field (3d-single-matrix) +% (way length) +% I .. index map (3d-uint32-matrix) +% B .. boundary map (3d-single-matrix) +% L .. speed map (3d-single-matrix) +% vx_vol .. voxel size (1x3-double-matrix): default=[1 1 1] +% ... not tested yet +% csf .. option (1x1-double-value): 0-no; 1-yes; default=1 +% euclid .. option (1x1-double-value): 0-no; 1-yes; default=1 +% output euclidean or speed map +% setnan .. option (1x1-double-value): 0-no; 1-yes; default=1 +% verb .. option (1x1-double-value): 0-no, 1-yes; default=0 +% +% +% Examples: +% Definitions of a object matrix A and of a speedmap F: +% +% 1) +% A=zeros(50,50,3,'single'); A(20:30,5:15,2)=10; A = smooth3(A); +% A(20:30,35:45,2) = 1; A(1:5,1:25,:) = nan; A(1:5,26:50,:) = -inf; +% F = ones(size(A),'single'); F(10:40,20,:) = 0.5; F(40,10:40,:) = 0; +% [D,I,T] = cat_vol_eidist(A,F,[1 1 1],1,1); +% ds('d2smns','',1,A - F,D/10,2); title('Euclidean distance') +% ds('d2smns','',1,A - F,T/10,2); title('Eikonal distance') +% +% 2) +% A = zeros(10,20,10,'single'); +% A(:,1:5,:) = 1; A(:,15:end,:) = nan; +% F = ones(size(A),'single'); +% +% 3) +% A = zeros(10,20,10,'single'); +% A(:,1:5,:) = 1; A(:,6,:) = 0.2; A(:,15:end,:) = nan; +% F = ones(size(A),'single'); +% +% 4) +% A = zeros(10,20,10,'single'); A(:,1:5,:) = 1; A(:,15:end,:) = nan; +% F = ones(size(A),'single'); +% +% Process and show data: +% [D,I] = cat_vol_eidist(A,F,[1 1 1],1,1,0,1); +% ds('x2','',1,A,D,D,I,round(size(A,3)/3)); +% +% See also cat_vbdist, compile, ds. +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_batch_long.m",".m","3235","120","function cat_batch_long(namefile,output_surface,long_model,cat_defaults,export_dartel,printlong) +% wrapper for using batch mode (see cat_batch_long.sh) +% +% namefile - array of file names +% output_surface - enable surface estimation +% long_model - 0: use model for large developmental changes (i.i with brain/head growth) +% 1: use model for (small) plasticity changes +% 2: use model for (large) ageing/developmental changes +% 3: use both models 1 and 2 +% cat_defaults - use this default file instead of cat_defaults.m +% export_dartel - export affine registered segmentations for Dartel +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +if nargin < 1 + fprintf('Syntax: cat_batch_long(namefile)\n'); + exit +end + +if nargin < 2 + output_surface = 1; +else + % string argument has to be converted + if isstr(output_surface) + output_surface = str2num(output_surface); + end +end + +if nargin < 3 + long_model = 1; +else + % string argument has to be converted + if isstr(long_model) + long_model = str2num(long_model); + end +end + +fid = fopen(namefile,'r'); +names = textscan(fid,'%s'); +names = names{:}; +fclose(fid); + +n = length(names); + +if n == 0, error('No file found in %s.\n',namefile); end + +global defaults cat matlabbatch + +spm_get_defaults; + +if nargin < 4 + cat_get_defaults; +else + if isempty(cat_defaults) + cat_get_defaults; + else + fprintf('Use defaults in %s.\n',cat_defaults); + [pp, name] = spm_fileparts(cat_defaults); + global cat; + + addpath(pp); + eval(name); + rmpath(pp); + + end +end + +if nargin < 5 + export_dartel = 0; +else + % string argument has to be converted + if isstr(export_dartel) + export_dartel = str2num(export_dartel); + end +end + +if nargin < 6 + printlong = 2; +else + % string argument has to be converted + if isstr(printlong) + printlong = str2num(printlong); + end +end + +matlabbatch{1}.spm.tools.cat.long.datalong.subjects{1} = names; +matlabbatch{1}.spm.tools.cat.long.nproc = 0; +matlabbatch{1}.spm.tools.cat.long.modulate = 1; + +% update parameters +matlabbatch{1}.spm.tools.cat.long.output.surface = output_surface; +matlabbatch{1}.spm.tools.cat.long.longmodel = long_model; +matlabbatch{1}.spm.tools.cat.long.printlong = printlong; +matlabbatch{1}.spm.tools.cat.long.dartel = 2*export_dartel; % affine registered data + +warning off +try + % use expert mode for long. batch + cat12('expert') + spm_jobman('initcfg'); + spm_jobman('run',matlabbatch); +catch %#ok % catch with lasterror is necessary for old matlab versions + caterr = lasterror; %#ok + fprintf('\n%s\nCAT Preprocessing error: %s:\n%s\n', repmat('-',1,72),caterr.identifier,caterr.message,repmat('-',1,72)); + for si=1:numel(caterr.stack), cat_io_cprintf('err',sprintf('%5d - %s\n',caterr.stack(si).line,caterr.stack(si).name)); end; + cat_io_cprintf('err',sprintf('%s\\n',repmat('-',1,72))); + error('Batch failed.'); +end + +spm_unlink(char(namefile)) + +warning off +exit +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_vol_maskimage.m",".m","4058","120","function out = cat_vol_maskimage(job) +% Po = cat_vol_maskimage(job) +% +% job +% .data .. original images +% .mask .. lesion/brain mask images +% .prefix .. filename prefix 'masked_' +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + + def.returnOnlyFilename = 0; + def.prefix = 'masked_'; + def.mask = {''}; + def.bmask = {''}; + def.recalc = 0; + def.lazy = 1; + job = cat_io_checkinopt(job,def); + + job.data = cellstr(job.data); + job.mask = cellstr(job.mask); + job.bmask = cellstr(job.bmask); + + % convert to really empty strings + if isscalar(job.mask) && isempty(job.mask{1}), job.mask = {}; end + if isscalar(job.bmask) && isempty(job.bmask{1}), job.bmask = {}; end + + % create output structure + Po = cell(numel(job.data),1); + + % SPM processbar + if isfield(job,'process_index') && job.verb, spm('FnBanner',mfilename); end + spm_clf('Interactive'); + spm_progress_bar('Init',numel(job.data),'Image masking','Volumes Complete'); + + % set filenames and remove old files + for di=1:numel(job.data) + % set filename + [pp,ff,ee] = spm_fileparts(job.data{di}); + Po{di} = fullfile(pp,[job.prefix ff ee]); + + % for GUI output + if job.returnOnlyFilename + continue; + elseif exist(Po{di},'file') && (job.recalc || job.lazy==1) + delete(Po{di}); + end + end + if job.returnOnlyFilename + return + end + + % error handling in case of missmatching number of files + if isscalar(job.data) && numel(job.mask)>1 && numel(job.bmask)==0 + % ok, multiple masks + elseif( numel(job.data)~=numel(job.mask) && numel(job.mask)>1 ) || ... + ( numel(job.data)~=numel(job.bmask) && numel(job.bmask)>1 ) + error('SPM:CAT:cat_vo_maskimgage','Number of images and mask/brainmask images has to be equal or zero'); + + elseif numel(job.mask)==0 && numel(job.bmask)==0 + for di=1:numel(job.data) + fprintf('No masks. Just copy ""%s""\n',job.data{di}); + [pp,ff,ee] = spm_fileparts(job.data{di}); + copyfile(fullfile(pp,[ff ee]),Po{di}) + end + %fprintf('No mask images. Nothing useful to do!\n'); + return + end + + % mask data + for di=1:numel(job.data) + % load image header to create output structure + if exist(Po{di},'file') % if the output file already exist that use it to add a new mask! + Vi = spm_vol(Po{di}); + else + Vi = spm_vol(job.data{di}); + end + fprintf('Process ""%s""\n',job.data{di}); + + Vo = Vi; + Vo.fname = Po{di}; + + % load other images and use imcalc to mask the images + imcalcopt = struct('verb',0); + if isscalar(job.data) && numel(job.mask)>0 && numel(job.bmask)==0 + Vm = spm_vol(char(job.mask)); + cat_vol_imcalc([Vi;Vm],Vo,sprintf('i1 %s',... + sprintf(' .* ( i%d<0.5 ) ',(1:numel(job.mask))+1)),imcalcopt); + elseif numel(job.data)>1 && numel(job.mask)>0 && numel(job.bmask)==0 + Vm = spm_vol(char(job.mask)); + Vb = spm_vol(char(job.bmask)); + cat_vol_imcalc([Vi;Vm;Vb],Vo,sprintf('i1 %s %s',... + sprintf(' .* ( i%d<0.5 ) ',(1:numel(job.mask))+1),... + sprintf(' .* ( i%d<0.5 ) ',(1:numel(job.bmask))+1)),imcalcopt); + elseif numel(job.mask)>0 && numel(job.bmask)==0 + Vm = spm_vol(job.mask{di}); + cat_vol_imcalc([Vi,Vm],Vo,'i1 .* ( i2<0.5 )',imcalcopt); + elseif numel(job.mask)==0 && numel(job.bmask)>0 + Vb = spm_vol(job.bmask{di}); + cat_vol_imcalc([Vi,Vb],Vo,'i1 .* ( i2>0.5 )',imcalcopt); + elseif numel(job.mask)>0 && numel(job.bmask)>0 + Vm = spm_vol(job.mask{di}); + Vb = spm_vol(job.bmask{di}); + cat_vol_imcalc([Vi,Vm,Vb],Vo,'i1 .* ( i2<0.5 | i3>0.5 )',imcalcopt); + end + + spm_progress_bar('Set',di); + end + + if isfield(job,'process_index') && job.verb, fprintf('Done\n'); end + spm_progress_bar('Clear'); + + out.files = Po; +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_main.m",".m","76702","1609","function Ycls = cat_main(res,tpm,job) +% ______________________________________________________________________ +% Write out CAT preprocessed data +% +% FORMAT Ycls = cat_main(res,tpm,job) +% +% based on John Ashburners version of +% spm_preproc_write8.m 2531 2008-12-05 18:59:26Z john $ +% +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +%#ok<*ASGLU> + + +update_intnorm = 1; %job.extopts.new_release; % RD202101: temporary parameter to control the additional intensity normalization + +if ~isfield(job.extopts,'histth'), job.extopts.histth = [0.96 0.9999]; end % RD20200501: created in cat_run_job but not in cat_run_job1639 + +% if there is a breakpoint in this file set debug=1 and do not clear temporary variables +dbs = dbstatus; debug = 0; for dbsi=1:numel(dbs), if strcmp(dbs(dbsi).name,mfilename); debug = 1; break; end; end + +% error report structure +global cat_err_res + + +%% Update SPM/CAT parameter and add some basic variables +[res,job,VT,VT0,pth,nam,vx_vol,d] = cat_main_updatepara(res,tpm,job); + + + +%% Write SPM preprocessing results +% ------------------------------------------------------------------- +stime = cat_io_cmd('SPM preprocessing 2 (write)'); if job.extopts.verb>1, fprintf('\n'); end +stime2 = cat_io_cmd(' Write Segmentation','g5','',job.extopts.verb-1); +if ~isfield(res,'segsn') + [Ysrc,Ycls,Yy] = cat_spm_preproc_write8(res,zeros(max(res.lkp),4),zeros(1,2),[0 0],0,0); +else + % old SPM segment + [Ysrc,Ycls,Yy] = cat_spm_preproc_write(res.segsn,... + struct('biascor',[1 0 0],'cleanup',[1 0 0],'GM',[1 0 0],'WM',[1 0 0],'CSF',[1 0 0]) ); + YHD = cat_vol_morph( Ysrc > 0.5*min(res.mn(:)),'ldc',5 ) & (Ycls{1} + Ycls{2} + Ycls{3})<.5; + Ycls{4} = uint8(255 .* ( YHD & (Ysrc < 1*min(res.mn(:))))); + Ycls{5} = uint8(255 .* ( YHD & ~(Ysrc < 1*min(res.mn(:))))); + Ycls{6} = uint8(255) - (Ycls{1} + Ycls{2} + Ycls{3} + Ycls{4} + Ycls{5}); +end + + +%% CAT vs. SPMpp Pipeline +if ~isfield(res,'spmpp') + %% Update SPM results in case of reduced SPM preprocessing resolution + % ------------------------------------------------------------------- + if isfield(res,'redspmres') + [Ysrc,Ycls,Yy,res] = cat_main_resspmres(Ysrc,Ycls,Yy,res); + end + P = zeros([size(Ycls{1}) numel(Ycls)],'uint8'); + for i=1:numel(Ycls), P(:,:,:,i) = Ycls{i}; end + clear Ycls; + + + + %% Update SPM preprocessing + % ------------------------------------------------------------------- + % Fix class errors, brainmask etc. + % This is a large and important subfuction that represent the + % starting point of the refined CAT preprocessing. + % RD202006: add ignoreErrors backup + % RD202101: small difference to 1639 + % ------------------------------------------------------------------- + [Ysrc,Ycls,Yb,Yb0,Yy,job,res,trans,T3th,stime2] = cat_main_updateSPM(Ysrc,P,Yy,tpm,job,res,stime,stime2); + %[Ysrc,Ycls,Yb,Yb0,job,res,T3th,stime2] = cat_main_updateSPM1639(Ysrc,P,Yy,tpm,job,res,stime,stime2); + clear P; + + + + %% Check the previous preprocessing in debug mode ### + % ------------------------------------------------------------------- + % If you want to see intermediate steps of the processing use the ""ds"" + % function: + % ds('l2','',vx_vol,Ym,Yb,Ym,Yp0,80) + % that display 4 images (unterlay, overlay, image1, image2) for one + % slice. The images were scaled in a range of 0 to 1. The overlay + % allows up to 20 colors + % ------------------------------------------------------------------- + if debug;; + Ym = Ysrc / max(T3th(1:3)); %#ok % only WM scaling + Yp0 = (single(Ycls{1})/255*2 + single(Ycls{2})/255*3 + single(Ycls{3})/255)/3; %#ok % label map + end + + + + %% Global (and local) intensity normalization and partioning + % --------------------------------------------------------------------- + % Global and local intensity corrections are the basis of most of the + % following functions. The global normalization based on the SPM tissue + % thresholds (res.mn) and were used anyway. For strong differences + % (mostly by the CSF) the median will used, because it is e.g. more + % stable. This will cause a warning by the cat_main_gintnorm. + % + % The local adaptive segmentation include a further bias correction + % and a global and local intensity correction. The local intensity + % correction refines the tissue maps to aproximate the local tissue + % peaks of WM (maximum-based), GM, and CSF. + % + % RD202006: add ignoreErrors backup + % --------------------------------------------------------------------- + stime = cat_io_cmd('Global intensity correction'); + if all(vx_vol < 0.4 ) && strcmp(job.extopts.species,'human')%&& job.extopts.ignoreErros<2 % 1639 + % guaranty average (lower) resolution with >0.7 mm + % RD202006: This solution is not working when cat_main_gintnorm + % optimize the image (e.g. bias correction). Just calling + % Ym = cat_main_gintnorm(Ysrc,Tth); + % would not include the bias correction but also may use + % inacurate peaks that were estimated on slighly different + % image. So it is more save to turn it off because running + % the default case also in highres data only increase time + % and memory demands. + % Possible test subject: ADHD200/ADHD200_HC_BEJ_1050345_T1_SD000000-RS00.nii + [Ysrcr,resGI] = cat_vol_resize(Ysrc , 'reduceV', vx_vol, 0.6, 32, 'meanm'); + Ybr = cat_vol_resize(single(Yb), 'reduceV', vx_vol, 0.6, 32, 'meanm')>0.5; + Yclsr = cell(size(Ycls)); for i=1:6, Yclsr{i} = cat_vol_resize(Ycls{i},'reduceV',vx_vol,0.6,32); end + [Ymr,T3th,Tth,job.inv_weighting,noise] = cat_main_gintnorm(Ysrcr,Yclsr,Ybr,resGI.vx_volr,res,job.extopts); + clear Ymr Ybr Ysrcr Yclsr; + Ym = cat_main_gintnorm(Ysrc,Tth); + else +% [Ym,Yb,T3th,Tth,job.inv_weighting,noise] = cat_main_gintnorm1639(Ysrc,Ycls,Yb,vx_vol,res,Yy,job.extopts); % Yb2 + [Ym,T3th,Tth,job.inv_weighting,noise] = cat_main_gintnorm(Ysrc,Ycls,Yb,vx_vol,res,job.extopts); + end + job.extopts.inv_weighting = job.inv_weighting; + res.ppe.tths.gintnorm.T3th = T3th; + res.ppe.tths.gintnorm.Tth = Tth; + + % RD202101: additional intensity correction + if 0 && update_intnorm + [Ym,tmp,Tthm] = cat_main_update_intnorm(Ym,Ym,Yb,Ycls,job); + res.ppe.tths.uintnorm0postgintnorm.Tthm = Tthm; + clear tmp Tthm; + end + + + + %% Enhanced denoising with intensity (contrast) normalized data + % --------------------------------------------------------------------- + % After the intensity scaling and with correct information about the + % variance of the tissue, a further harder noise correction is meaningful. + % Finally, a stronger NLM-filter is better than a strong MRF filter! + % --------------------------------------------------------------------- + if job.extopts.NCstr~=0 + NCstr.labels = {'none','full','light','medium','strong','heavy'}; + NCstr.values = {0 1 2 -inf 4 5}; + stime = cat_io_cmd(sprintf('SANLM denoising after intensity normalization (%s)',... + NCstr.labels{find(cell2mat(NCstr.values)==job.extopts.NCstr,1,'first')})); + + % filter only within the brain mask for speed up + [Yms,Ybr,BB] = cat_vol_resize({Ym,Yb},'reduceBrain',vx_vol,round(2/cat_stat_nanmean(vx_vol)),Yb); Ybr = Ybr>0.5; + Yms = cat_vol_sanlm(struct('data',res.image0.fname,'verb',0,'NCstr',job.extopts.NCstr),res.image,1,Yms); + Ym(BB.BB(1):BB.BB(2),BB.BB(3):BB.BB(4),BB.BB(5):BB.BB(6)) = Yms .* Ybr + ... + Ym(BB.BB(1):BB.BB(2),BB.BB(3):BB.BB(4),BB.BB(5):BB.BB(6)) .* (1-Ybr); + clear Yms Ybr BB; + + Ysrc = cat_main_gintnormi(Ym,Tth); + + fprintf('%5.0fs\n',etime(clock,stime)); + end + + + + + %% prepared for improved partitioning - RD20170320, RD20180416 + %{ + % Update the initial SPM normalization by a fast version of Shooting + % to improve the skull-stripping, the partitioning and LAS. + % We need stong deformations in the ventricle for the partitioning + % but low deformations for the skull-stripping. Moreover, it has to + % be really fast > low resolution (3 mm) and less iterations. + % The mapping has to be done for the TPM resolution, but we have to + % use the Shooting template for mapping rather then the TPM because + % of the cat12 atlas map. + % + % #### moved fast shooting to the cat_main_updateSPM function #### + % + if 0 % job.extopts.WMHC || job.extopts.SLC + stime = cat_io_cmd(sprintf('Fast registration'),'','',job.extopts.verb); + + res2 = res; + job2 = job; + job2.extopts.verb = debug; % do not display process (people would may get confused) + job2.extopts.vox = abs(res.tpm(1).mat(1)); % TPM resolution to replace old Yy + if job.extopts.regstr>0 + job2.extopts.regstr = 15; % low resolution + job2.extopts.reg.nits = 16; % less iterations + job2.extopts.reg.affreg = 0; % new affine registration + job2.extopts.shootingtpms(3:end) = []; % remove high templates, we only need low frequency corrections + res2 = res; + res2.do_dartel = 2; % use shooting + else + fprintf('\n'); + job2.extopts.verb = 0; + job2.extopts.vox = abs(res.tpm(1).mat(1)); % TPM resolution to replace old Yy + job2.extopts.reg.iterlim = 1; % only 1-2 inner iterations + job2.extopts.reg.affreg = 0; % new affine registration + res2.do_dartel = 1; % use dartel + end + if isfield(res,'Ylesion') && sum(res.Ylesion(:)>0) + [trans,res.ppe.reginitp] = cat_main_registration(job2,res2,Ycls(1:2),Yy,res.Ylesion); + else + [trans,res.ppe.reginitp] = cat_main_registration(job2,res2,Ycls(1:2),Yy); + end + Yy2 = trans.warped.y; + if ~debug, clear trans job2 res2; end + + % Shooting did not include areas outside of the boundary box + % + % ### add to cat_main_registration? + % + Ybd = true(size(Ym)); Ybd(3:end-2,3:end-2,3:end-2) = 0; Ybd(~isnan(Yy2(:,:,:,1))) = 0; Yy2(isnan(Yy2))=0; + for k1=1:3 + Yy2(:,:,:,k1) = Yy(:,:,:,k1) .* Ybd + Yy2(:,:,:,k1) .* (1-Ybd); + Yy2(:,:,:,k1) = cat_vol_approx(Yy2(:,:,:,k1),'nn',vx_vol,3); + end + Yy = Yy2; + clear Yy2; + if ~debug, fprintf('%5.0fs\n',etime(clock,stime)); end + end + %} + + + + %% Local Intensity Correction + % RD202006: Skip LAS in case of inverse contrast or if backup functions + % are forced (ignoreErrors > 2). + % RD202101: There are multiple differnces by intensity scaling that are + % handeled by the AMAP but still affect the surface pipeline + % > added final intensity correction based on the AMAP + % RD202102: Extension of LAS to correct protocoll depending differences + % of cortical GM intensities due to myelination before and + % after the general call of the LAS function. + % > add this later to the LAS function inclusive the denoising + % > this may also work for T2/PD maps + % RD202501: Update the simpler LAS function to support also T2/PD/FLAIR data. + if job.extopts.LASstr>0 && job.extopts.ignoreErrors < 3 + if job.extopts.LASstr>1 || job.extopts.inv_weighting + stime = cat_io_cmd(sprintf('Simplified Local adaptive segmentation (LASstr=%0.2f)',job.extopts.LASstr-1)); + else + stime = cat_io_cmd(sprintf('Local adaptive segmentation (LASstr=%0.2f)',job.extopts.LASstr)); + end + + % RD202102: Extension of LAS to correct protocol depending differences + % of cortical GM intensities due to myelination. + if isfield(job.extopts,'LASmyostr') + LASmyostr = job.extopts.LASmyostr; + else + LASmyostr = job.extopts.LASstr; + end + if job.extopts.inv_weighting + LASmyostr = 1; + end + % LASmyostr = min(1,LASmyostr + 0.5*job.extopts.inv_weighting); % force correction in case of inverse data? + if LASmyostr + stime2 = cat_io_cmd(sprintf('\n LAS myelination correction (LASmyostr=%0.2f)',LASmyostr),'g5','',job.extopts.verb); + % It is better to avoid updating of the Ym and Ysrc here because some + % of the problems depend on inhomogenities that can be corrected by + % LAS and a final correct at the end. + % 0 - none, eps - only Ycls, 0.25 - Ycls + bias correction, .50/.75/1.0 - Ycls + BC + light/medium/strong post correction, ... + [Ym,Ysrc,Ycls,Ycor] = cat_main_correctmyelination(Ym,Ysrc,Ycls,Yb,vx_vol,res.image(1),T3th,LASmyostr,Yy,job.extopts.cat12atlas,res.tpm,res.image.fname); + fprintf('%6.0fs\n',etime(clock,stime2)); clear Ymx Ysrcx; + end + + % LAS main call + if job.extopts.LASstr>1 || job.extopts.inv_weighting + Ymi = cat_main_LASsimple(Ysrc,Ycls,T3th,job.extopts.LASstr); + else + try + [Ymi,Ym,Ycls] = cat_main_LAS(Ysrc,Ycls,Ym,Yb,Yy,T3th,res,vx_vol,job.extopts,Tth); + catch + cat_io_addwarning([mfilename ':cat_main_LAS'],'Error in cat_main_LAS use cat_main_LASsimple.',3,[1 1]); + Ymi = cat_main_LASsimple(Ysrc,Ycls,T3th,job.extopts.LASstr); + end + end + clear Ymt; % use original global scaled ... + stime2 = clock; % not really correct but better than before + + % RD202102: update Ymi since the LAS correction is currently not local enough in case of artefacts + % RD202502: the correction is currently not working/tested for T2/PD/FLAIR + if ~job.extopts.inv_weighting + Ymi = max( min( Yp0/3 , min( 2.25 , Yp0/3 )*0.25 + 0.75*( 2.25 - 0.5 * LASmyostr) / 3 ) , Yp0/3 - Ycor / 3 ); + else + Ymi = max(Ymi,max(Ymi,min(1.1,Ycor*3))); + end + else + % just a node because it is the result of the inverse contrast warning + cat_io_addwarning('cat_main:skipLAS','Skip LAS due to image contrast. Use global normalization.',0,[0 1]); + Ymi = Ym; + end + + % ### indlcude this in cat_main_LAS? ### + if job.extopts.NCstr~=0 + % noise correction of the local normalized image Ymi, whereas only small changes are expected in Ym by the WM bias correction + stimen = cat_io_cmd(sprintf(' SANLM denoising after LAS (%s)',... + NCstr.labels{find(cell2mat(NCstr.values)==job.extopts.NCstr,1,'first')}),'g5','',1,stime2); + + [Ymis,Ymior,BB] = cat_vol_resize({Ymi,Ym},'reduceBrain',vx_vol,round(2/mean(vx_vol)),Yb); + Ymis = cat_vol_sanlm(struct('data',res.image0.fname,'verb',0,'NCstr',job.extopts.NCstr),res.image,1,Ymis); + + Yc = abs(Ymis - Ymior); Yc = Yc * 6 * min(2,max(0,abs(job.extopts.NCstr))); + spm_smooth(Yc,Yc,2./vx_vol); Yc = max(0,min(1,Yc)); clear Ymior; + % mix original and noise corrected image and go back to original resolution + Ybr = Yb(BB.BB(1):BB.BB(2),BB.BB(3):BB.BB(4),BB.BB(5):BB.BB(6)); + Ymi(BB.BB(1):BB.BB(2),BB.BB(3):BB.BB(4),BB.BB(5):BB.BB(6)) = ... + Ymi(BB.BB(1):BB.BB(2),BB.BB(3):BB.BB(4),BB.BB(5):BB.BB(6)) .* (1-Ybr) + ... + (1-Yc) .* Ymi(BB.BB(1):BB.BB(2),BB.BB(3):BB.BB(4),BB.BB(5):BB.BB(6)) .* Ybr + ... + Yc .* Ymis .* Ybr; + + % extreme background denoising to remove wholes? + Ymis = cat_vol_median3(Ymi,Ymi>0 & Ymi<0.4,Ymi<0.4); Ymi = Ymi.*max(0.1,Ymi>0.4) + Ymis.*min(0.9,Ymi<=0.4); + Ymis = cat_vol_median3(Ym,Ym>0 & Ym<0.4,Ym<0.4); Ym = Ym.*max(0.1,Ym>0.4) + Ymis.*min(0.9,Ym<=0.4); + + %cat_io_cmd(' ','','',job.extopts.verb,stimen); + clear Ymis; + else + stimen = stime; + end + + cat_io_cmd(' ','','',job.extopts.verb,stimen); clear stimenc + fprintf('%5.0fs\n',etime(clock,stime)); + + if ~debug; clear Ysrc ; end + + + % RD202101: additional intensity correction + if update_intnorm + try + [Ym,Ymi,Tthm,Tthmi] = cat_main_update_intnorm(Ym,Ymi,Yb,Ycls,job); + res.ppe.tths.uintnorm1postlas.Tthm = Tthm; + res.ppe.tths.uintnorm1postlas.Tthmi = Tthmi; + clear Tthm Tthmi; + catch + cat_io_cprintf('warn','Update of intensities failed!\n'); + res.ppe.tths.uintnorm1postlas.Tthm = nan; + res.ppe.tths.uintnorm1postlas.Tthmi = nan; + end + end + + + + %% Partitioning: + % --------------------------------------------------------------------- + % For most of the following adaptations further knowledge of special + % regions is helpfull. Also Ymi is maybe still a little bit inhomogen + % the alignment should work. Only strong inhomogenities can cause + % problems, especially for the blood vessel detection. + % But for bias correction the ROIs are important too, to avoid over + % corrections in special regions like the cerbellum and subcortex. + % --------------------------------------------------------------------- + + % RD202006: Only correct for WMHs if there is a good contrast + % Add this in the partvol function ? + stime = cat_io_cmd('ROI segmentation (partitioning)'); + if job.extopts.SLC + if isfield(res,'Ylesion') && sum(res.Ylesion(:)>0) + [Yl1,Ycls,YMF] = cat_vol_partvol(Ymi,Ycls,Yb,Yy,vx_vol,job.extopts,tpm.V,noise,job,res.Ylesion); %,Ydt,Ydti); + fprintf('%5.0fs\n',etime(clock,stime)); + else + [Yl1,Ycls,YMF] = cat_vol_partvol(Ymi,Ycls,Yb,Yy,vx_vol,job.extopts,tpm.V,noise,job,false(size(Ym))); + fprintf('%5.0fs\n',etime(clock,stime)); + if isfield(res,'Ylesion') && sum(res.Ylesion(:)==0) && job.extopts.SLC==1 + cat_io_addwarning('cat_main_SLC_noExpDef','SLC is set for manual lesions correction but no lesions were found!',1,[1 1]); + end + end + else + [Yl1,Ycls,YMF] = cat_vol_partvol(Ymi,Ycls,Yb,Yy,vx_vol,job.extopts,tpm.V,noise,job,false(size(Ym))); + fprintf('%5.0fs\n',etime(clock,stime)); + if job.extopts.expertgui && isfield(res,'Ylesion') && sum(res.Ylesion(:))>1000 && job.extopts.ignoreErrors < 2 && ... + ~(res.ppe.affreg.highBG || res.ppe.affreg.skullstripped) && strcmp('human',job.extopts.species) + cat_io_addwarning('cat_main_SLC_noExpDef',sprintf(['SLC is deactivated but there are %0.2f cm' ... + native2unicode(179, 'latin1') ' of voxels with zero value inside the brain!'],prod(vx_vol) .* sum(res.Ylesion(:)) / 1000 ),1,[1 1]); + end + end + if ~debug; clear YBG Ycr Ydt; end + + + + %% Blood Vessel Correction + % --------------------------------------------------------------------- + % Blood vessel correction has to be done before the segmentation to + % remove high frequency strutures and avoid missclassifications. + % Problems can occure for strong biased images, because the partioning + % has to be done before bias correction. + % Of course we only want to do this for highres T1 data! + % --------------------------------------------------------------------- + res.applyBVC = 0; + NS = @(Ys,s) Ys==s | Ys==s+1; + if job.extopts.BVCstr && ~job.inv_weighting && all(vx_vol<2); + % RD202306: test if the BVC is required + if job.extopts.BVCstr>0 && job.extopts.BVCstr<1 + res.applyBVC = ... + sum(NS(Yl1(:),job.extopts.LAB.BV)) > 1000 && ... + median(Ymi(NS(Yl1(:),job.extopts.LAB.BV))) > 0.75; + elseif job.extopts.BVCstr >= 1 % allways or old + res.applyBVC = 1; + end + + if job.extopts.expertgui > 1 % + BVCs = sprintf(' (BVCstr=%0.2f)',job.extopts.BVCstr); + else + BVCs = ''; + end + + if res.applyBVC + stime = cat_io_cmd(sprintf('Apply enhanced blood vessel correction%s',BVCs)); + Ybv = cat_vol_smooth3X(cat_vol_smooth3X( ... + NS(Yl1,7) .* (Ymi*3 - (1.5-(mod(job.extopts.BVCstr,1) + (job.extopts.BVCstr>0)))),0.3).^4,0.1)/3; + else + % here we are only correcting the super high intensity strucutres + stime = cat_io_cmd(sprintf('No enhanced blood vessel correction is required %s',BVCs)); + Ybv = (Ymi>1.1) .* cat_vol_smooth3X(cat_vol_smooth3X( ... + NS(Yl1,7) .* (Ymi*3 - (1.5-(mod(job.extopts.BVCstr,1) + (job.extopts.BVCstr>0)))),0.3).^4,0.1)/3; + end + + + %% correct src images + % - good result but no nice form ... + %Ymi = Ym; + Ymio = Ymi; + Ymi = max( min( max(1/3, 1 - Ybv/4), Ymi ), Ymi - Ybv*2/3 ); + for mi = 1:2, Ymi = cat_vol_median3(Ymi,Ybv > max(0,1 - mi/2) & Ymi~=Ymio ); end + Ymi = cat_vol_median3(Ymi,Ybv > 0); clear Ymio; + + %Ymi = max( min(1/3 + 1/3*cat_vol_morph(Ym>2.5/3 & NS(Yl1,job.extopts.LAB.BV),'dd',1.5,vx_vol) , Ymi) ,Ymi - Ybv*2/3); + % Ymis = cat_vol_smooth3X(Ymi); Ymi(Ybv>0.5) = Ymis(Ybv>0.5); clear Ymis; + + %% update classes + Ycls{1} = min(Ycls{1},cat_vol_ctype(255 - Ybv*127)); + Ycls{2} = min(Ycls{2},cat_vol_ctype(255 - Ybv*127)); + Ycls{3} = max(Ycls{3},cat_vol_ctype(127*Ybv)); + + fprintf('%5.0fs\n',etime(clock,stime)); + clear Ybv p0; + end + + + + %% gcut+: additional skull-stripping using graph-cut + % ------------------------------------------------------------------- + % For skull-stripping gcut is used in general, but a simple and very + % old function is still available as backup solution. + % Furthermore, both parts prepare the initial segmentation map for the + % AMAP function. + % RD202006: cat_main_gcut requires T1 weighed input + % RD202101: this does not realy fit to your strategy of setting up the + % skull-stripping in cat_main_updateSPM and then only refine + % it by cleanup. >> remove this option in future + % ------------------------------------------------------------------- + if job.extopts.gcutstr>0 && job.extopts.gcutstr<=1 && max(res.lkp) ~= 4 + stime = cat_io_cmd(sprintf('Skull-stripping using graph-cut (gcutstr=%0.2f)',job.extopts.gcutstr)); + if job.extopts.ignoreErrors < 3 + try + [Yb,Yl1] = cat_main_gcut(Ym,Yb,Ycls,Yl1,YMF,vx_vol,job.extopts); + + % extend gcut brainmask by brainmask derived from SPM12 segmentations if necessary + if ~job.extopts.inv_weighting, Yb = Yb | Yb0; end + + fprintf('%5.0fs\n',etime(clock,stime)); + catch %#ok + fprintf('\n'); + cat_io_addwarning('cat_main_gcut:err99','Unknown error in cat_main_gcut. Use old brainmask.',1,[1 1]); + job.extopts.gcutstr = 99; + end + else + cat_io_addwarning('cat_main_gcut:err99','No graph-cut backup function. Use old brainmask.',1,[1 1]); + end + end + % correct mask for skull-stripped images (but not ex-vivo brains, where CSF=BG) + if max(res.lkp) == 4 %skullstripped + Yb = Yb .* (spm_read_vols(res.image(1)) > 0); + end + + + + %% AMAP segmentation + % ------------------------------------------------------------------- + % Most corrections were done before and the AMAP routine is used with + % a low level of iterations and no further bias correction, because + % some images get tile artifacts. + % + % prob .. new AMAP segmentation (4D) + % ind* .. index elements to asign a subvolume + % + % RD202006: Updated ignoreErrors pipeline that try to use AMAP if + % ignoreError < 4. + % RD202101: There are differences by using only the new brainmask + % ------------------------------------------------------------------- + job.extopts.AMAPframing = 1; + if 0 % ## AMAPsharpening ## + % RD202509: EXPERIMENTAL: sharpening for AMAP to improve gyral structures in surface reconstruction + Ymi = Ymi + (Ymi - smooth3(Ymi)) / 2; + end + try + % there is a bug with empty images CG7T >> catch with old function + [prob,indx,indy,indz,ath] = cat_main_amap(Ymi,Yb,Yb0,Ycls,job,res); + catch + [prob,indx,indy,indz,ath] = cat_main_amap1639(Ymi,Yb,Yb0,Ycls,job,res); + end + if sum(sum(sum(prob(:,:,:,1)))) < sum(Ycls{1}(:)) * 0.5 + % there is a bug with empty images CG7T >> catch with old function + [prob,indx,indy,indz,ath] = cat_main_amap1639(Ymi,Yb,Yb0,Ycls,job,res); + end + + % RD202101: Update image intensity normalization based on the the AMAP + % segmentation but not the AMAP thresholds + if update_intnorm + [Ym,Ymi,Tthm,Tthmi] = cat_main_update_intnorm(Ym,Ymi,Yb,prob,job,0,indx,indy,indz); + res.ppe.tths.uintnorm2postamap.Tthm = Tthm; + res.ppe.tths.uintnorm2postamap.Tthmi = Tthmi; + clear Tthm Tthmi; + end + + + %% Final Cleanup + % ------------------------------------------------------------------- + % There is one major parameter to control the strength of the cleanup. + % As far as the cleanup has a strong relation to the skull-stripping, + % cleanupstr is controlled by the gcutstr. + % + % Yp0ox = single(prob(:,:,:,1))/255*2 + single(prob(:,:,:,2))/255*3 + single(prob(:,:,:,3))/255; + % Yp0o = zeros(d,'single'); Yp0o(indx,indy,indz) = Yp0ox; + % Yp0 = zeros(d,'uint8'); Yp0(indx,indy,indz) = Yp0b; + % ------------------------------------------------------------------- + if job.extopts.cleanupstr>0 + % classical cleanup with extended version close to the skull in case of + % the AMAP segmentation (not so good for BUSS_2002) + res.xCleanup = max(job.extopts.cleanupstr > 2, 3 * ... + ( isfield(job.extopts,'inv_weighting') && job.extopts.inv_weighting )); + prob = cat_main_clean_gwc(prob,min(1,job.extopts.cleanupstr*2/mean(vx_vol)),res.xCleanup); + + % newer additional cleanup (cleanupstr == 4 to use only the cat_main_clean_gwc for tests) + if job.extopts.cleanupstr < 3 && ~job.extopts.inv_weighting + [Ycls,Yp0b] = cat_main_cleanup(Ycls,prob,Yl1(indx,indy,indz),... + Ym(indx,indy,indz),job.extopts,job.extopts.inv_weighting,vx_vol,indx,indy,indz,res.ppe.affreg.skullstripped); % new cleanup + else + for i=1:3, Ycls{i}(:) = 0; Ycls{i}(indx,indy,indz) = prob(:,:,:,i); end + Yp0b = Yb(indx,indy,indz); + end + else + for i=1:3, Ycls{i}(:) = 0; Ycls{i}(indx,indy,indz) = prob(:,:,:,i); end + Yp0b = Yb(indx,indy,indz); + end + clear prob + % mix Ymi with Yp0 map in case of AMAP mixing strategy (for non-T1 data) ... not working + if 0 %sum(Yrep(:))>0 && ~job.inv_weighting + Yp0 = zeros(d,'single'); Yp0(indx,indy,indz) = Yp0b/3; + Yre = zeros(d,'single'); Yre(indx,indy,indz) = Yrep; + Ymi = Ymi .* (1-Yre) + Yre .* Yp0; clear Yre Yrep; + end + + + + %% ------------------------------------------------------------------- + % Correction of WM hyperintensities + % ------------------------------------------------------------------- + % The correction of WMH should be important for a correct normalization. + % It is only important to close the mayor WMH structures, and further + % closing can lead to problems with small gyri. So keep it simple here + % and maybe add further refinements in the partitioning function. + % ------------------------------------------------------------------- + LAB = job.extopts.LAB; + Yp0 = zeros(d,'uint8'); Yp0(indx,indy,indz) = Yp0b; + qa.software.version_segment = strrep(mfilename,'cat_main',''); % if cat_main# save the # revision number + if isfield(res,'spmpp') && res.spmpp, qa.software.version_segment = 'SPM'; end % if SPM segmentation is used as input + [cat_err_res.init.Yp0,cat_err_res.init.BB] = cat_vol_resize(Yp0,'reduceBrain',vx_vol,2,Yp0>0.5); + clear Ywmhrel Yp0 + + + + % correction for normalization [and final segmentation] + if ( (job.extopts.WMHC && job.extopts.WMHCstr>0) || job.extopts.SLC) && ~job.extopts.inv_weighting % && job.extopts.ignoreErrors < 2 + % display something + %{ + if job.extopts.WMHC==1 + cat_io_cmd(sprintf('Internal WMH correction for spatial normalization')); % (WMHCstr=%0.2f)',job.extopts.WMHCstr)); + elseif job.extopts.WMHC>1 + cat_io_cmd(sprintf('Permanent WMH correction')); % (WMHCstr=%0.2f)',job.extopts.WMHCstr)); + end + fprintf('\n'); + if job.extopts.SLC==1 + cat_io_cmd('Internal stroke lesion correction for spatial normalization'); + elseif job.extopts.SLC>1 + cat_io_cmd('Permanent stroke lesion correction'); + end + fprintf('\n'); + %} + + % prepare correction map + Ynwmh = NS(Yl1,LAB.TH) | NS(Yl1,LAB.BG) | NS(Yl1,LAB.HC) | NS(Yl1,LAB.CB) | NS(Yl1,LAB.BS); + Ynwmh = cat_vol_morph(cat_vol_morph( Ynwmh, 'dd', 8 , vx_vol),'dc',12 , vx_vol) & ... + ~cat_vol_morph( NS(Yl1,LAB.VT), 'dd', 4 , vx_vol); + Ywmh = cat_vol_morph( Ycls{7}>0, 'dd', 1.5); + Ywmh = Ycls{7}>0 | (~Ynwmh & (Ycls{2}==255 | ... + cat_vol_morph( cat_vol_morph(Ycls{2}>128 | Ywmh,'ldc',1) ,'de' , 1.5))); + Ywmh = Ywmh .* cat_vol_smooth3X(Ywmh,0.5); % smooth inside + + + %% transfer tissue from GM and CSF to WMH + if job.extopts.SLC>0 + % WMHs and lesions + if job.extopts.SLC==1 + Yls = res.Ylesion; + Ycls{8} = cat_vol_ctype( Yls*255 ); + elseif job.extopts.SLC==2 + Yls = NS(Yl1,LAB.LE)>0.5 | res.Ylesion; + Ycls{8} = cat_vol_ctype( Yls .* single(Ycls{1}) + Yls .* single(Ycls{3}) + 255*single(res.Ylesion) ); + end + Ycls{7} = cat_vol_ctype( Ywmh .* single(Ycls{1}) + Ywmh .* single(Ycls{3})); + Ycls{1} = cat_vol_ctype( single(Ycls{1}) .* (1 - Ywmh - single(Yls)) ); + Ycls{3} = cat_vol_ctype( single(Ycls{3}) .* (1 - Ywmh - single(Yls)) ); + else + % only WMHS + Ycls{7} = cat_vol_ctype( Ywmh .* single(Ycls{1}) + Ywmh .* single(Ycls{3})); + Ycls{1} = cat_vol_ctype( single(Ycls{1}) .* (1 - Ywmh) ); + Ycls{3} = cat_vol_ctype( single(Ycls{3}) .* (1 - Ywmh) ); + end + if ~debug, clear Ynwmh Ywmh Yls; end + + + % different types of WMH correction as GM, WM or extra class + % different types of lesion correction as CSF or extra class + if numel(Ycls)>7 && job.extopts.SLC==1 + if job.extopts.WMHC<2 + Yp0b = cat_vol_ctype(single(Ycls{1})*2/5 + single(Ycls{2})*3/5 + single(Ycls{3})*1/5 + single(Ycls{7})*2/5 + single(Ycls{8})*1/5,'uint8'); + elseif job.extopts.WMHC==2 + Yp0b = cat_vol_ctype(single(Ycls{1})*2/5 + single(Ycls{2})*3/5 + single(Ycls{3})*1/5 + single(Ycls{7})*3/5 + single(Ycls{8})*1/5,'uint8'); + elseif job.extopts.WMHC==3 + Yp0b = cat_vol_ctype(single(Ycls{1})*2/5 + single(Ycls{2})*3/5 + single(Ycls{3})*1/5 + single(Ycls{7})*4/5 + single(Ycls{8})*1/5,'uint8'); + end + elseif numel(Ycls)>7 && job.extopts.SLC==2 + if job.extopts.WMHC<2 + Yp0b = cat_vol_ctype(single(Ycls{1})*2/5 + single(Ycls{2})*3/5 + single(Ycls{3})*1/5 + single(Ycls{7})*2/5 + single(Ycls{8})*1.5/5,'uint8'); + elseif job.extopts.WMHC==2 + Yp0b = cat_vol_ctype(single(Ycls{1})*2/5 + single(Ycls{2})*3/5 + single(Ycls{3})*1/5 + single(Ycls{7})*3/5 + single(Ycls{8})*1.5/5,'uint8'); + elseif job.extopts.WMHC==3 + Yp0b = cat_vol_ctype(single(Ycls{1})*2/5 + single(Ycls{2})*3/5 + single(Ycls{3})*1/5 + single(Ycls{7})*4/5 + single(Ycls{8})*1.5/5,'uint8'); + end + else % no stroke lesion handling + if job.extopts.WMHC<2 + Yp0b = cat_vol_ctype(single(Ycls{1})*2/5 + single(Ycls{2})*3/5 + single(Ycls{3})*1/5 + single(Ycls{7})*2/5,'uint8'); + elseif job.extopts.WMHC==2 + Yp0b = cat_vol_ctype(single(Ycls{1})*2/5 + single(Ycls{2})*3/5 + single(Ycls{3})*1/5 + single(Ycls{7})*3/5,'uint8'); + elseif job.extopts.WMHC==3 + Yp0b = cat_vol_ctype(single(Ycls{1})*2/5 + single(Ycls{2})*3/5 + single(Ycls{3})*1/5 + single(Ycls{7})*4/5,'uint8'); + end + end + + else + Yp0b = cat_vol_ctype(single(Ycls{1})*2/5 + single(Ycls{2})*3/5 + single(Ycls{3})*1/5,'uint8'); + end + + % update error report structure + [cat_err_res.init.Yp0,cat_err_res.init.BB] = cat_vol_resize(Yp0b,'reduceBrain',vx_vol,2,Yp0b>0.5); + + % store smaller version + Yp0b = Yp0b(indx,indy,indz); + clear Yclsb; + + if job.extopts.verb>2 + tpmci=tpmci+1; tmpmat = fullfile(pth,res.reportfolder,sprintf('%s_%s%02d%s.mat',nam,'write',tpmci,'preDartel')); + save(tmpmat,'Yp0','Ycls','Ymi','T3th','vx_vol','Yl1'); + clear Yp0; + end + +else +%% SPM segmentation input +% ------------------------------------------------------------------------ +% Prepare data for registration and surface processing. +% We simply use the SPM segmentation as it is without further modelling of +% a PVE or other refinements. +% ------------------------------------------------------------------------ + [Ym,Ymi,Yp0b,Yb,Yl1,Yy,YMF,indx,indy,indz,qa,job] = ... + cat_main_SPMpp(Ysrc,Ycls,Yy,job,res,stime); + fprintf('%5.0fs\n',etime(clock,stime)); +end + + + +%% --------------------------------------------------------------------- +% Spatial Registration with Dartel or Shooting +% --------------------------------------------------------------------- + if res.do_dartel + Yclsd = Ycls(1:3); % use only GM and WM for deformation + if job.extopts.WMHC>0 && numel(Ycls)>6 + Yclsd{2} = cat_vol_ctype(min(255,single(Ycls{2}) + single(Ycls{7}))); % set WMHs as WM in some cases + end + + if job.extopts.SLC && isfield(res,'Ylesion') && sum(res.Ylesion(:)>0) + % lesion detection in the original space with the original data + LSstr = 0.5; + Yvt = cat_vol_morph( NS(Yl1,job.extopts.LAB.VT),'do',4,vx_vol); % open to get lesions close to the ventricle + Yvt = cat_vol_morph( Yvt ,'dd',4,vx_vol); % add some voxels for smoothness + res.Ylesion = cat_vol_ctype( single(res.Ylesion) .* (1 - (Yvt & Ym>0.9 & Ym<1.1) )); + if ~debug, clear Yvt Ybgvt Ybgn; end + % add lesion of automatic lesion estimation? - in development + if job.extopts.WMHC>3 + res.Ylesion = cat_vol_ctype( single(res.Ylesion) + ... + 255* smooth3( Ym<1.5/3 & cat_vol_morph(NS(Yl1,job.extopts.LAB.LE),'dd',4*(1-LSstr))) ); + end + Ylesions = cat_vol_smooth3X(single(res.Ylesion)/255,4); % final smoothing to have soft boundaries + else + Ylesions = zeros(size(Ym),'single'); + end + + % call Dartel/Shooting registration + job2 = job; + job2.extopts.verb = debug; % do not display process (people would may get confused) + if isfield(job2,'spmpp') + job2.extopts.reg.affreg = 0; % RD202404: no additional affine registration in case of spm preprocessed data + if isfield(res,'bb') + job2.extopts.bb = res.bb; % RD202404: use bb parameters from SPM processing ??? + end + else + job2.extopts.reg.affreg = 4; % RD202306: do an addition registration based on the skull (i.e. sum(Ycls{1:3})) + % code is working but better result? {'brain','skull','GM','WM'}; + end + + if numel( job.extopts.vox ) > 1 + Yp0 = zeros(d,'single'); Yp0(indx,indy,indz) = single(Yp0b)/255*5; %job2.export = 1; + [trans,res.ppe.reg,res.ppe.affreg.Affine_catfinal] = cat_main_registration(job2,res,Ycls,Yy,Ylesions,Yp0,Ym,Ymi,Yl1); clear Yp0; + else + [trans,res.ppe.reg,res.ppe.affreg.Affine_catfinal] = cat_main_registration(job2,res,Yclsd,Yy,Ylesions); + end + clear Yclsd Ylesions; + else + if job.extopts.regstr == 0 + fprintf('Dartel registration is not required.\n'); + else + fprintf('Shooting registration is not required.\n'); + end + end + + + +%% update WMHs +% --------------------------------------------------------------------- + Ycls = cat_main_updateWMHs(Ym,Ycls,Yy,tpm,job,res,trans); + if ~debug, clear Yy; end + + +%% write results +% --------------------------------------------------------------------- +Yp0 = zeros(d,'single'); Yp0(indx,indy,indz) = single(Yp0b)/255*5; +cat_main_write(Ym,Ymi,Ycls,Yp0,Yl1,job,res,trans); +if 0 + %% just for tests + % Write important maps with push and pull and resolution specific file names. + % Report total tissue volumes in native and modulated warped space. + Yp0 = zeros(d,'single'); Yp0(indx,indy,indz) = single(Yp0b)/255*5; + res2 = res; + job2 = job; + trans2 = trans; + % write all maps + job2.output.GM.warped = 1; % test push/pull in general + job2.output.GM.mod = 3; % test modulation of push/pull + job2.output.label.warped = 1; % test general push/pull without modulation + job2.output.bias.warped = 1; % test general push/pull without modulation + % write push for comparision + [pppush,ffpush,eepush] = spm_fileparts(res2.image0.fname); + res2.image0.fname = fullfile(pppush,sprintf('%s%s%1.2f%s',ffpush,'-push',job.extopts.vox,eepush)); + trans2.warped.push = 1; + trans2.warped.verb = 1; + cat_main_write(Ym,Ymi,Ycls,Yp0,Yl1,job2,res2,trans2); + % write pull for comparision + res2.image0.fname = fullfile(pppush,sprintf('%s%s%1.2f%s',ffpush,'-pull',job.extopts.vox,eepush)); + trans2.warped.push = 0; + cat_main_write(Ym,Ymi,Ycls,Yp0,Yl1,job2,res2,trans2); + clear res2 job2 trans2; +end +if ~debug, clear Yp0; end + + +%% surface creation and thickness estimation +% --------------------------------------------------------------------- +if all( [job.output.surface>0 job.output.surface<9 ] ) || ... + all( [job.output.surface>10 job.output.surface<19 ] ) || (job.output.surface==9 && ... + any( [job.output.ct.native job.output.ct.warped job.output.ct.dartel job.output.ROI] )) + + % prepare some parameter + if ~isfield(job,'useprior'), job.useprior = ''; end + Yp0 = zeros(d,'single'); Yp0(indx,indy,indz) = single(Yp0b)*5/255; + [Ymix,job,surf,stime] = cat_main_surf_preppara(Ymi,Yp0,job,vx_vol); + + %% default surface reconstruction + if job.extopts.SRP >= 20 + surf = unique(surf,'stable'); + if 0 %job.extopts.close_parahipp %any( ~cellfun('isempty', strfind(surf,'cb') )) % ... I want to avoid this if possible - it also seem to be worse to use it + VT1 = spm_vol(cat_get_defaults('extopts.shootingT1')); + fac = abs(tpm.V(1).mat(1)) / abs(VT1.mat(1)); % RD202401: ERROR with tpm variable ""Dot indexing is not supported for variables of this type."" + YT = single(spm_sample_vol(VT1,double(smooth3(Yy(:,:,:,1))*fac),double(smooth3(Yy(:,:,:,2))*fac),double(smooth3(Yy(:,:,:,3))*fac),2)); + YT = reshape(YT,size(Yy(:,:,:,1))); clear Yyi; + else + YT = []; + end + %% further GUI fields ... + if ~isfield(job.extopts,'vdist'), job.extopts.vdist = 0; end + if ~isfield(job.extopts,'scale_cortex'), job.extopts.scale_cortex = cat_get_defaults('extopts.scale_cortex'); end + if ~isfield(job.extopts,'add_parahipp'), job.extopts.add_parahipp = cat_get_defaults('extopts.add_parahipp'); end + if ~isfield(job.extopts,'close_parahipp'), job.extopts.close_parahipp = cat_get_defaults('extopts.close_parahipp'); end + if ~isfield(job.extopts,'pbtmethod'), job.extopts.pbtmethod = cat_get_defaults('extopts.pbtmethod'); end + if ~isfield(job.extopts,'reduce_mesh'), job.extopts.reduce_mesh = 1; end % cat_get_defaults('extopts.reduce_mesh'); end + if ~isfield(job.output,'surf_measures'), job.output.surf_measures = 1; end % developer + + if job.extopts.SRP >= 40 + %% Yb0 was modified in cat_main_amap* for some conditions and we can use it as better mask in + % cat_surf_createCS3 except for inv_weighting or if gcut was not used + if ~(job.extopts.gcutstr>0 && ~job.inv_weighting), Yb0(:) = 1; end + + [Yth1, S, Psurf, qa.createCS] = ... + cat_surf_createCS4(VT,VT0,Ymi,Ymix,Yl1,YMF,Yb0,struct('trans',trans,'reduce_mesh',job.extopts.reduce_mesh,... required for Ypp output + 'interpV',job.extopts.pbtres,'pbtmethod',job.extopts.pbtmethod,'SRP', mod(job.extopts.SRP,10), 'vdist', 2, ... job.extopts.vdist, ... + 'Affine',res.Affine,'surf',{surf},'verb',job.extopts.verb,'useprior',job.useprior),job); + qa.subjectmeasures.EC_abs = NaN; + qa.subjectmeasures.defect_size = NaN; + + elseif job.extopts.SRP >= 30 + % Yb0 was modified in cat_main_amap* for some conditions and we can use it as better mask in + % cat_surf_createCS3 except for inv_weighting or if gcut was not used + if ~(job.extopts.gcutstr>0 && ~job.inv_weighting), Yb0(:) = 1; end + + [Yth1, S, Psurf, qa.createCS] = ... + cat_surf_createCS3(VT,VT0,Ymix,Yl1,YMF,YT,Yb0,struct('trans',trans,'reduce_mesh',job.extopts.reduce_mesh,... required for Ypp output + 'outputpp',job.output.pp,'surf_measures',job.output.surf_measures, ... + 'interpV',job.extopts.pbtres,'pbtmethod',job.extopts.pbtmethod,'SRP', mod(job.extopts.SRP,10), ... + 'scale_cortex', job.extopts.scale_cortex, 'add_parahipp', job.extopts.add_parahipp, 'close_parahipp', job.extopts.close_parahipp, .... + 'Affine',res.Affine,'surf',{surf},'pbtlas',job.extopts.pbtlas, ... % pbtlas is the new parameter to reduce myelination effects + 'inv_weighting',job.inv_weighting,'verb',job.extopts.verb,'useprior',job.useprior),job); + qa.subjectmeasures.EC_abs = NaN; + qa.subjectmeasures.defect_size = NaN; + else + [Yth1, S, Psurf, qa.subjectmeasures.EC_abs, qa.subjectmeasures.defect_size, qa.createCS] = ... + cat_surf_createCS2(VT,VT0,Ymix,Yl1,YMF,YT,struct('trans',trans,'reduce_mesh',job.extopts.reduce_mesh,... required for Ypp output + 'vdist',job.extopts.vdist,'outputpp',job.output.pp,'surf_measures',job.output.surf_measures, ... + 'interpV',job.extopts.pbtres,'pbtmethod',job.extopts.pbtmethod,'SRP',mod(job.extopts.SRP,10),... + 'scale_cortex', job.extopts.scale_cortex, 'add_parahipp', job.extopts.add_parahipp, 'close_parahipp', job.extopts.close_parahipp, .... + 'Affine',res.Affine,'surf',{surf},'pbtlas',job.extopts.pbtlas, ... % pbtlas is the new parameter to reduce myelination effects + 'inv_weighting',job.inv_weighting,'verb',job.extopts.verb,'useprior',job.useprior),job); + end + else + %% createCS1 pipeline + [Yth1,S,Psurf,qa.subjectmeasures.EC_abs,qa.subjectmeasures.defect_size, qa.createCS] = ... + cat_surf_createCS(VT,VT0,Ymix,Yl1,YMF,struct('pbtmethod','pbtsimple',... + 'interpV',job.extopts.pbtres,'extract_pial_white',mod(job.extopts.SRP,10), ... + 'Affine',res.Affine,'surf',{surf},'pbtlas',job.extopts.pbtlas, ... % pbtlas is the new parameter to reduce myelination effects + 'inv_weighting',job.extopts.inv_weighting,'verb',job.extopts.verb,'useprior',job.useprior),job); + end + + % thickness map + if numel(fieldnames(S))==0 && isempty(Psurf), clear S Psurf; end + if isfield(job.output,'ct') + cat_io_writenii(VT0,Yth1,res.mrifolder,'ct','cortical thickness map','uint16',... + [0,0.0001],job.output.ct,trans,single(Ycls{1})/255,0.1); + end + + if job.output.sROI % no fast without registration + stime2 = cat_io_cmd(' Surface ROI estimation'); + + %% estimate surface ROI estimates for thickness + [pp,ff] = spm_fileparts(VT.fname); + [stat, val] = fileattrib(pp); + if stat, pp = val.Name; end + + [mrifolder, reportfolder, surffolder] = cat_io_subfolders(VT.fname,job); + + if cat_get_defaults('extopts.subfolders') && strcmp(mrifolder,'mri') + pp = spm_str_manip(pp,'h'); % remove 'mri' in pathname that already exists + end + surffolder = fullfile(pp,surffolder); + + % get original filename without 'n' + [pp0,ff] = spm_fileparts(VT0.fname); + + Psatlas_lh = job.extopts.satlas( [job.extopts.satlas{:,4}]>0 , 2); + Pthick_lh = cell(1,1); + Pthick_lh{1} = fullfile(surffolder,sprintf('lh.thickness.%s',ff)); + + cat_surf_surf2roi(struct('cdata',{{Pthick_lh}},'rdata',{Psatlas_lh})); + + fprintf('%5.0fs\n',etime(clock,stime2)); + end + + cat_io_cmd('Surface and thickness estimation takes'); + fprintf('%5.0fs\n',etime(clock,stime)); + if ~debug; clear YMF Yp0; end + if ~debug && ~job.output.ROI && job.output.surface, clear Yth1; end + + +else + %if ~debug; clear Ymi; end +end + + + +%% ROI data extraction +% --------------------------------------------------------------------- +% This part estimates individual measurements for different ROIs. +% The ROIs are described in the CAT normalized space and there are two +% ways to estimate them - (1) in subject space, and (2) in normalized +% space. Estimation in normalized space is more direct and avoids further +% transformations. The way over the subject space has the advantage +% that individual anatomical refinements are possible, but this has +% to be done and evaluated for each atlas. +% Test call (type: 1-native,2-push,3-pull*; write: 1-verb,2-imgs): +% cat_main_roi(job,trans,Ycls,Yp0,struct('type',1,'write',1)); +% --------------------------------------------------------------------- +if job.output.ROI + try + Yp0 = zeros(d,'single'); Yp0(indx,indy,indz) = single(Yp0b)/255*5; + cat_main_roi(job,trans,Ycls,Yp0); + catch + cat_io_addwarning([mfilename ':cat_main_roi'],'Error in cat_main_roi.',1,[1 1]); + end +end +if ~debug, clear wYp0 wYcls wYv Yp0; end + + + +%% XML-report and Quality Control +% --------------------------------------------------------------------- +% RD20200725: evaluate difference between res.Affine and res.Affine0 +% create error for too strong differences + +% estimate brain tissue volumes and TIV +qa.subjectmeasures.vol_abs_CGW = [ + prod(vx_vol)/1000/255 .* sum(Ycls{3}(:)), ... CSF + prod(vx_vol)/1000/255 .* sum(Ycls{1}(:)), ... GM + prod(vx_vol)/1000/255 .* sum(Ycls{2}(:)) 0 0]; % WM WMHs SL +qa.subjectmeasures.vol_abs_WMH = 0; % RD202011: just for internal use (cat_report) but ok if people see it +qa.subjectmeasures.vol_rel_WMH = 0; +% stroke lesions +if numel(Ycls)>7, qa.subjectmeasures.vol_abs_CGW(5) = prod(vx_vol)/1000/255 .* sum(Ycls{8}(:)); end +% set WMHs +if numel(Ycls)>6 && numel(Ycls{6})>0 + qa.subjectmeasures.vol_abs_WMH = prod(vx_vol)/1000/255 .* sum(Ycls{7}(:)); + if job.extopts.WMHC > 2 % extra class + qa.subjectmeasures.vol_abs_CGW(4) = prod(vx_vol)/1000/255 .* sum(Ycls{7}(:)); + elseif job.extopts.WMHC == 2 % count as WM + qa.subjectmeasures.vol_abs_CGW(2) = qa.subjectmeasures.vol_abs_CGW(2) + prod(vx_vol)/1000/255 .* sum(Ycls{7}(:)); + else % count as GM + qa.subjectmeasures.vol_abs_CGW(1) = qa.subjectmeasures.vol_abs_CGW(1) + prod(vx_vol)/1000/255 .* sum(Ycls{7}(:)); + end + qa.subjectmeasures.vol_rel_WMH = qa.subjectmeasures.vol_abs_WMH ./ sum(qa.subjectmeasures.vol_abs_CGW); +end +if job.output.surface && isfield(S,'lh') && isfield(S,'rh') + qa.subjectmeasures.surf_TSA = sum( cat_surf_fun('area',S.lh) )/100 + sum( cat_surf_fun('area',S.lh) )/100; +end +qa.subjectmeasures.vol_TIV = sum(qa.subjectmeasures.vol_abs_CGW); +qa.subjectmeasures.vol_rel_CGW = qa.subjectmeasures.vol_abs_CGW ./ qa.subjectmeasures.vol_TIV; +if ~debug, clear Ycls; end +if job.output.surface + qa.qualitymeasures.SurfaceEulerNumber = qa.subjectmeasures.EC_abs; + qa.qualitymeasures.SurfaceDefectArea = qa.subjectmeasures.defect_size; + qa.qualitymeasures.SurfaceDefectNumber = qa.createCS.defects; + qa.qualitymeasures.SurfaceIntensityRMSE = qa.createCS.RMSE_Ym; + qa.qualitymeasures.SurfacePositionRMSE = qa.createCS.RMSE_Ypp; + if isfield(qa,'createCS') && isfield(qa.createCS,'self_intersections') + qa.qualitymeasures.SurfaceSelfIntersections = qa.createCS.self_intersections; + else + qa.qualitymeasures.SurfaceSelfIntersections = []; + end +end +stime = cat_io_cmd('Quality check'); job.stime = stime; +Yp0 = zeros(d,'single'); Yp0(indx,indy,indz) = single(Yp0b)/255*5; Yp0(Yp0>3.1) = nan; % no analysis in WMH regions +% in case of SPM input segmentation we have to add the name here to have a clearly different naming of the CAT output +if isfield(res,'spmpp') && res.spmpp, namspm = 'c1'; else, namspm = ''; end +qa = cat_vol_qa('cat12',Yp0,VT0.fname,Ym,res,job.extopts.species, ... + struct('write_csv',0,'write_xml',1,'method','cat12','job',job,'qa',qa,'prefix',['cat_' namspm]),... + fullfile(spm_file(VT.fname,'fpath'),['p0' nam '.nii'])); +clear Yp0; + +% surface data update +if job.output.surface + if exist('S','var') + if isfield(S,'lh') && isfield(S.lh,'th1'), th=S.lh.th1; else, th=[]; end + if isfield(S,'rh') && isfield(S.rh,'th1'), th=[th; S.rh.th1]; end + qa.subjectmeasures.dist_thickness{1} = [cat_stat_nanmean(th(:)) cat_stat_nanstd(th(:))]; + + if job.extopts.expertgui>1 + if isfield(S,'lh') && isfield(S.lh,'th2'), th2=S.lh.th2; else, th2=[]; end + if isfield(S,'rh') && isfield(S.lh,'th2'), th2=[th2; S.rh.th2]; end + qa.subjectmeasures.dist_gyruswidth{1} = [cat_stat_nanmean(th2(:)) cat_stat_nanstd(th2(:))]; + if isfield(S,'lh') && isfield(S.lh,'th3'), th2=S.lh.th3; else, th2=[]; end + if isfield(S,'rh') && isfield(S.lh,'th3'), th2=[th2; S.rh.th3]; end + qa.subjectmeasures.dist_sulcuswidth{1} = [cat_stat_nanmean(th2(:)) cat_stat_nanstd(th2(:))]; + end + elseif exist('Yth1','var') + qa.subjectmeasures.dist_thickness{1} = [cat_stat_nanmean(Yth1(Yth1(:)>1)) cat_stat_nanstd(Yth1(Yth1(:)>1))]; + th = Yth1(Yth1(:)>1); + % gyrus- and sulcus-width? + end + %% Thickness peaks + % Estimation of kmean peaks to describe the thickess in a better way than + % by using only mean and std that are both biased strongly by outliers. + [thm ,ths, thh ] = cat_stat_kmeans( th , 1 ); % one anatomical average peak + [thma,thsa,thha] = cat_stat_kmeans( th( abs( th - thm ) < ths * 2 ) , 3 ); % 3 anatomical peaks + [thme,thse,thhe] = cat_stat_kmeans( th( (th < thma(1) - 2*thsa(1) ) | (th > thma(end) + 2*thsa(end) )) , 2 ); % 3 anatomical peaks + qa.subjectmeasures.dist_thickness_kmeans = [thm' ths' thh' ]; + qa.subjectmeasures.dist_thickness_kmeans_inner3 = [thma' thsa' thha']; + qa.subjectmeasures.dist_thickness_kmeans_outer2 = [thme' thse' thhe']; + clear th; + + %qam = cat_stat_marks('eval',job.cati,qa,'cat12'); % ... not ready + cat_io_xml(fullfile(pth,res.reportfolder,['cat_' namspm nam '.xml']),struct(... + ... 'subjectratings',qam.subjectmeasures, ... not ready + 'subjectmeasures',qa.subjectmeasures,'ppe',res.ppe),'write+'); % here we have to use the write+! +end +fprintf('%5.0fs\n',etime(clock,stime)); +clear Yth1; + +if qa.subjectmeasures.vol_rel_WMH>0.01 && job.extopts.WMHC<2 + cat_io_addwarning([mfilename ':uncorrectedWMHs'],... + sprintf('Uncorrected WM lesions greater (%2.2f%%%%%%%% of the TIV, %2.2f%%%%%%%% of the WM)!',... + qa.subjectmeasures.vol_rel_WMH * 100, ... + qa.subjectmeasures.vol_abs_WMH / qa.subjectmeasures.vol_abs_CGW(3) * 100),1); +end + + + + +%% CAT reports +% --------------------------------------------------------------------- +% Final report of preprocessing parameter and results in the SPM +% graphics window that is exported as PDF/JPG. The parameter were +% combined in cat_main_reportstr to three text strings that were +% printed in combination with volume (spm_orthviews) and surface +% data (cat_surf_display). The processing is finished by some +% lines in the command line window. +% --------------------------------------------------------------------- +if job.extopts.print + %% + str = cat_main_reportstr(job,res,qa); + Yp0 = zeros(d,'single'); Yp0(indx,indy,indz) = single(Yp0b)/255*5; + if ~exist('Psurf','var'), Psurf = ''; end + cat_main_reportfig(Ymi,Yp0,Yl1,Psurf,job,qa,res,str); +end + +% final command line report +cat_main_reportcmd(job,res,qa); + +return +function [Ysrc,Ycls,Yy,res] = cat_main_resspmres(Ysrc,Ycls,Yy,res) +%% cat_main_resspmres +% --------------------------------------------------------------------- +% Interpolate to internal resolution if lower resultion was used for +% SPM preprocessing +% +% [Ysrc,Ycls,Yy,res] = cat_main_resspmres(Ysrc,Ycls,Yy,res) +% +% --------------------------------------------------------------------- + + % Update Ycls: cleanup on original data + Yb = Ycls{1} + Ycls{2} + Ycls{3}; + for i=1:numel(Ycls) + [Pc(:,:,:,i),BB] = cat_vol_resize(Ycls{i},'reduceBrain',repmat(job.opts.redspmres,1,3),2,Yb); %#ok + end + Pc = cat_main_clean_gwc(Pc,1); + for i=1:numel(Ycls), Ycls{i} = cat_vol_resize(Pc(:,:,:,i),'dereduceBrain',BB); end; clear Pc Yb; + for ci=1:numel(Ycls) + Ycls{ci} = cat_vol_ctype(cat_vol_resize(Ycls{ci},'deinterp',res.redspmres,'linear')); + end + + % Update Yy: + Yy2 = zeros([res.redspmres.sizeO 3],'single'); + for ci=1:size(Yy,4) + Yy2(:,:,:,ci) = cat_vol_ctype(cat_vol_resize(Yy(:,:,:,ci),'deinterp',res.redspmres,'linear')); + end + Yy = Yy2; clear Yy2; + + % Update Ysrc: + Ysrc = cat_vol_resize(Ysrc,'deinterp',res.redspmres,'cubic'); + Ybf = res.image1.dat ./ Ysrc; + Ybf = cat_vol_approx(Ybf .* (Ysrc~=0 & Ybf>0.25 & Ybf<1.5),'nn',1,8); + Ysrc = res.image1.dat ./ Ybf; clear Ybf; + res.image = res.image1; + res = rmfield(res,'image1'); +return + +function [res,job,VT,VT0,pth,nam,vx_vol,d] = cat_main_updatepara(res,tpm,job) +%% Update parameter +% --------------------------------------------------------------------- +% Update CAT/SPM parameter variable job and the SPM preprocessing +% variable res +% +% [res,job] = cat_main_updatepara(res,job) +% +% --------------------------------------------------------------------- + + % this limits ultra high resolution data, i.e. images below ~0.4 mm are reduced to ~0.7mm! + % used in cat_main_partvol, cat_main_gcut, cat_main_LAS + def.extopts.uhrlim = 0.7 * 2; % default 0.7*2 that reduce images below 0.7 mm + def.cati = 0; + def.color.error = [0.8 0.0 0.0]; + def.color.warning = [0.0 0.0 1.0]; + def.color.warning = [0.8 0.9 0.3]; + def.color.highlight = [0.2 0.2 0.8]; + job = cat_io_checkinopt(job,def); + + clear def; + + % complete job structure + defr.ppe = struct(); + res = cat_io_checkinopt(res,defr); + + + % definition of subfolders - add to res variable? + [res.mrifolder, res.reportfolder, res.surffolder, res.labelfolder] = cat_io_subfolders(res.image0(1).fname,job); + + % Sort out bounding box etc + res.bb = spm_get_bbox(tpm.V(1)); + + + if numel(res.image) > 1 + warning('CAT12:noMultiChannel',... + 'CAT12 does not support multiple channels. Only the first channel will be used.'); + end + + % use dartel (do_dartel=1) or shooting (do_dartel=2) normalization + if isempty(job.extopts.darteltpm) || isempty(job.extopts.shootingtpm) + res.do_dartel = 0; + else + res.do_dartel = 1 + (job.extopts.regstr(1)~=0); + if res.do_dartel + tc = [cat(1,job.tissue(:).native) cat(1,job.tissue(:).warped)]; + need_dartel = any(job.output.warps) || ... + job.output.bias.warped || ... + job.output.label.warped || ... + any(any(tc(:,[4 5 6]))) || job.output.jacobian.warped || ... + job.output.ROI || ... + any([job.output.atlas.warped]) || ... + numel(job.extopts.regstr)>1 || ... + numel(job.extopts.vox)>1; + if ~need_dartel + res.do_dartel = 0; + end + end + end + + % Update templates for LAS + if res.do_dartel<2 && job.extopts.regstr(1) == 0 + job.extopts.templates = job.extopts.darteltpms; + else + job.extopts.templates = job.extopts.shootingtpms; + end + + % remove noise/interpolation prefix + VT = res.image(1); % denoised/interpolated n*.nii + VT0 = res.image0(1); % original + [pth,nam] = spm_fileparts(VT0.fname); + + % voxel size parameter + vx_vol = sqrt(sum(VT.mat(1:3,1:3).^2)); % voxel size of the processed image + res.vx_vol = vx_vol; + + % delete old xml file + oldxml = fullfile(pth,res.reportfolder,['cat_' nam '.xml']); + if exist(oldxml,'file'), delete(oldxml); end + clear oldxml + + d = VT.dim(1:3); + +return + +function [Ycls,Ym,Ymi,Yp0b,Yb,Yl1,Yy,YMF,indx,indy,indz,qa,job] = cat_main_SPMpp(Ysrc,Ycls,Yy,job,res,stime) +%% SPM segmentation input +% ------------------------------------------------------------------------ +% Here, DARTEL and PBT processing is prepared. +% We simply use the SPM segmentation as it is, without further modelling +% of the partial volume effect or other refinements. +% ------------------------------------------------------------------------ + + NS = @(Ys,s) Ys==s | Ys==s+1; % for side independent atlas labels + + % QA WMH values required by cat_vol_qa later + qa.subjectmeasures.WMH_abs = nan; % absolute WMH volume without PVE + qa.subjectmeasures.WMH_rel = nan; % relative WMH volume to TIV without PVE + qa.subjectmeasures.WMH_WM_rel = nan; % relative WMH volume to WM without PVE + qa.subjectmeasures.WMH_abs = nan; % absolute WMH volume without PVE in cm^3 + + vx_vol = sqrt(sum(res.image(1).mat(1:3,1:3).^2)); + + %% Update Ycls: cleanup on original data + Yb = Ycls{1} + Ycls{2} + Ycls{3}; + for i=1:numel(Ycls) + [Pc(:,:,:,i),BB] = cat_vol_resize(Ycls{i},'reduceBrain',repmat(job.opts.redspmres,1,3),2,Yb); %#ok + end + Pc = cat_main_clean_gwc(Pc,round(1./mean(vx_vol)),2); + for i=1:3, Ycls{i} = cat_vol_resize(Pc(:,:,:,i),'dereduceBrain',BB); end; clear Pc Yb; + + %% Update Ycls: cleanup on original data + if numel(Ycls)==3 + % in post-mortem data there is no CSF and CSF==BG + Yb = Ycls{1} + Ycls{2}; + [Yb,R] = cat_vol_resize(single(Yb),'reduceV',vx_vol,1,32,'meanm'); % use lower resolution to save time + Yb = cat_vol_morph(Yb>128,'ldo',3,R.vx_volr); % do some cleanup + Yb = cat_vol_morph(Yb,'ldc',8,R.vx_volr); % close mask (even large ventricles) + Yb = cat_vol_morph(Yb,'dd',1,R.vx_volr); % add 1 mm to have some CSF around the brain and simpliefy PVEs + Yb = cat_vol_resize(smooth3(Yb),'dereduceV',R)>0.5; % reinterpolate image and add some space around it + clear R; + + Ycls{3} = cat_vol_ctype(single(Ycls{3}) .* Yb); + Ycls{4} = cat_vol_ctype(255 * (1-Yb)); + else + Yb = Ycls{1} + Ycls{2} + Ycls{3}; + end + for i=1:numel(Ycls) + [Pc(:,:,:,i),BB] = cat_vol_resize(Ycls{i},'reduceBrain',repmat(job.opts.redspmres,1,3),2,Yb); + end + Pc = cat_main_clean_gwc(Pc,round(1./mean(vx_vol)),2); + for i=1:3, Ycls{i} = cat_vol_resize(Pc(:,:,:,i),'dereduceBrain',BB); end; clear Pc Yb; + + %% create (resized) label map and brainmask + Yp0 = single(Ycls{3})/5 + single(Ycls{1})/5*2 + single(Ycls{2})/5*3; + Yb = single(Ycls{3} + Ycls{1} + Ycls{2}) > 128; + + % load original images and get tissue thresholds + clsint = @(x) round( sum(res.mn(res.lkp==x) .* res.mg(res.lkp==x)') * 10^5)/10^5; + + if isfield(job.extopts,'spmAMAP') && job.extopts.spmAMAP + fprintf('%5.0fs\n',etime(clock,stime)); + T3thx = [ clsint(3) clsint(1) clsint(2) ]; + T3thx = [ cat_stat_nanmedian(Ysrc(Ycls{3}(:)>128)) ... + cat_stat_nanmedian(Ysrc(Ycls{1}(:)>128)) ... + cat_stat_nanmedian(Ysrc(Ycls{2}(:)>128)) ]; + + if any( diff( (T3thx-min(T3thx)) / (max(T3thx)-min(T3thx)) ) > .2 ) + % Usefull constrast between ALL tissues? + % Not allways working and especially in such cases AMAP is needed. + % This is expert processing and AMAP is not default! + % It inlcudes also some basic corrections (skull-stripping, bias + % correction, + + %% brain masking + if 0 + Yb = (single(Ycls{3} + Ycls{1} + Ycls{2}) > 64) | ... + cat_vol_morph( single(Ycls{3} + Ycls{1} + Ycls{2}) > 192,'dd',1.5); + Yb = cat_vol_morph( Yb ,'ldc',1.5,vx_vol); + Ycls{3} = max(Ycls{3},cat_vol_ctype(255*Yb) - Ycls{2} - Ycls{1}); + else + P = cat(4,Ycls{1},Ycls{2},Ycls{3},0*Ycls{4},0*Ycls{4},Ycls{4}); + res.isMP2RAGE = 0; + Yb = cat_main_APRG(Ysrc,P,res,double(T3thx)); + Yb = cat_vol_morph( Yb ,'ldc',6,vx_vol); + Yb = cat_vol_smooth3X(Yb,4)>.4; + clear P + end + + %% bias correction + Yg = cat_vol_grad(Ysrc) ./ Ysrc; + if T3thx(2) < T3thx(3) % T1 + Yi = Ysrc .* ( Ycls{2}>128 & Ysrc > cat_stat_nanmedian(T3thx(2:3)) & Ysrc < T3thx(3)*1.2 & Yg < cat_stat_nanmedian(Yg(Yb(:))) ) + ... + Ysrc .* ( Ycls{1}>128 & Ysrc > T3thx(2)*.9 & Ysrc < mean(T3thx(2:3)) & Yg < cat_stat_nanmedian(Yg(Yb(:))) ) * T3thx(3) / T3thx(2); + else % T2/PD + Yi = Ysrc .* ( Ycls{2}>128 & Ysrc < cat_stat_nanmedian(T3thx(2:3)) & Yg < cat_stat_nanmedian(Yg(Yb(:))) ); + Yi = Yi + ... + Ysrc .* ( Ycls{1}>128 & Ysrc > T3thx(1)*.9 & Ysrc > T3thx(1)*1.1 & Yg < cat_stat_nanmedian(Yg(Yb(:)) ) & Yi==0 ) * T3thx(3) / T3thx(2); + Ymsl = ( (Ycls{5}>128 | Ycls{4}>128) & Ysrc > min(T3thx)/4 & Ysrc < min(T3thx)*.8 & smooth3(Yg) < cat_stat_nanmedian(Yg(Yb(:))) & Yi==0 ); + Yi = Yi + ... + Ysrc .* Ymsl * T3thx(3) / cat_stat_nanmedian(Ysrc(Ymsl(:))); + end + Yi = cat_vol_approx(Yi,'rec'); + Ysrc = Ysrc ./ Yi * T3thx(3); + clear Yi; + + %% intensity normalization + if T3thx(2) < T3thx(3) % T1 + T3thx2 = [ cat_stat_nanmedian(Ysrc(Ycls{3}(:)>128 & Yg(:)<.3)) ... + cat_stat_nanmedian(Ysrc(Ycls{1}(:)>128 & Yg(:)<.3)) ... + cat_stat_nanmedian(Ysrc(Ycls{2}(:)>128 & Yg(:)<.3)) ]; + Tth.T3th = [0 .05 1:5]; + Tth.T3thx = sort( [ min(Ysrc(:)) cat_stat_nanmedian([min(Ysrc(:)),T3thx2(1)]) T3thx2 T3thx2(3)+diff(T3thx2(2:3)) max(Ysrc(:)) ] ); + else + T3thx2 = [ cat_stat_nanmedian(Ysrc(Ycls{3}(:)>128 & Yg(:)<.3)) ... ... + cat_stat_nanmedian(Ysrc(Ycls{1}(:)>128 & Yg(:)<.3)) ... + cat_stat_nanmedian(Ysrc(Ycls{2}(:)>128 & Yg(:)<.3)) ]; + Tth.T3th = [0 .05 1:5]; + Tth.T3thx = sort( [ min(Ysrc(:)) cat_stat_nanmedian([min(Ysrc(:)),min(T3thx2)]) T3thx2 max(T3thx2)-diff([max(T3thx2),max([setdiff(T3thx2,max(T3thx2))])]) max(Ysrc(:)) ] ); + end + Ym = cat_main_gintnormi(Ysrc/3,Tth) / 3; + Ym = cat_vol_sanlm(struct('data',res.image.fname,'verb',0,'NCstr',job.extopts.NCstr),res.image,1,Ym); + Yclso=Ycls; + + %% LAS + if 1 + stime = cat_io_cmd(sprintf('Local adaptive segmentation (LASstr=%0.2f)',job.extopts.LASstr)); + %Ymi = cat_main_LAS(Ysrc,Ycls,Ym,Yb,Yy,Tth.T3thx(3:5) ,res,vx_vol,job.extopts,struct('T3thx',Tth.T3th,'T3th',Tth.T3thx)); + Ymi = cat_main_LASsimple(Ysrc,Ycls); %,,job.extopts.LASstr); + Ymi = cat_vol_sanlm(struct('data',res.image0.fname,'verb',0,'NCstr',job.extopts.NCstr),res.image,1,Ymi); + Ym = Ymi; + stime = cat_io_cmd(' ','','',job.extopts.verb,clock); fprintf('%5.0fs\n',etime(clock,stime)); clear Ymx Ysrcx; + else + Ymi = Ym; + end + + %% add missing field and run AMAP + job.inv_weighting = T3thx(2) > T3thx(3); + job.extopts.AMAPframing = 0; + job.extopts.inv_weighting = T3thx(2) > T3thx(3); + [prob,indx,indy,indz] = cat_main_amap(min(10,Ymi+0), Yb & Ymi>1/6, Yb & Ymi>1/6, Ycls, job,res); + stime = cat_io_cmd(' '); + + %% cleanup (just the default value) + if job.extopts.cleanupstr > 0 && T3thx(2) < T3thx(3) + prob = cat_main_clean_gwc1639(prob,min(1,job.extopts.cleanupstr*2/mean(vx_vol))); % default cleanup + for i=1:3, Ycls{i}(:) = 0; Ycls{i}(indx,indy,indz) = prob(:,:,:,i); end + elseif T3thx(2) > T3thx(3) +% close WM in PDw + Yb0 = sum(prob,4) > 0; + Yw = single(prob(:,:,:,2)); + Yw = Yw .* cat_vol_morph(Yw > 0,'l',[.1 10]); + Yw = Yw .* (cat_vol_morph(Yb0,'de',2,vx_vol) | cat_vol_morph(Yw > 0,'ldo',1.9,vx_vol)); + Yw = Yw .* cat_vol_morph(Yw > 0,'l',[.1 10]); + Yw = Yw .* (cat_vol_morph(Yb0,'de',5,vx_vol) | cat_vol_morph(Yw > 0,'ldo',1.2,vx_vol)); + prob(:,:,:,1) = prob(:,:,:,1) + prob(:,:,:,2) .* uint8(Yw==0 & Ym(indx,indy,indz)>1/6 & Ym(indx,indy,indz)<5/6); % GM + prob(:,:,:,3) = prob(:,:,:,3) + prob(:,:,:,2) .* uint8(Yw==0 & Ym(indx,indy,indz)>5/6 & Ym(indx,indy,indz)<6/6); % CSF + prob(:,:,:,2) = prob(:,:,:,2) .* uint8(Yw>0); + clear Yb0 Yw; + + prob = cat_main_clean_gwc1639(prob,min(1,job.extopts.cleanupstr*4/mean(vx_vol))); % default cleanup + for i=1:3, Ycls{i}(:) = 0; Ycls{i}(indx,indy,indz) = prob(:,:,:,i); end + Ycls{3} = max(Ycls{3},cat_vol_ctype(255*Yb) - Ycls{2} - Ycls{1}); + end + Yp0 = single(Ycls{3})/255 + single(Ycls{1})/255*2 + single(Ycls{2})/255*3; + else + % error message + cat_io_addwarning([mfilename ':cat_main_SPMpp:AMAP'],'AMAP selected but insufficient tissue contrast. Keep SPM segmentation!',4,[1 1]); + + % the intensity normalized images are here represented by the segmentation + Ym = Yp0/255*5/3; + Ymi = Yp0/255*5/3; + end + else + % the intensity normalized images are here represented by the segmentation + Ym = Yp0/255*5/3; + Ymi = Yp0/255*5/3; + end + + % RD202506: try updating Ym(i) + if ~( isfield(job.extopts,'spmAMAP') && job.extopts.spmAMAP && any( diff( (T3thx-min(T3thx)) / (max(T3thx)-min(T3thx)) ) > .2 ) ) + % apply intensity normalization with denoising (used for export and surface evaluation) + % bias correction + Ym = Ysrc ./ cat_vol_approx( (Ycls{2}>240).*Ysrc ); + % threshold estimation + Yg = cat_vol_grad(Ym) ./ cat_stat_nanmedian(Ym(Ycls{2}(:)>128)); + if cat_stat_nanmedian(Ym(Ycls{3}(:)>128 & Yg(:)<.6)) < cat_stat_nanmedian(Ym(Ycls{2}(:)>128 & Yg(:)<.3)) + T3thx2 = [ min([ cat_stat_nanmedian(Ym(Ycls{3}(:)>240 & Yg(:)<.05)) cat_stat_nanmedian(Ym(Ycls{3}(:)>192 & Yg(:)<.1)) ]) ... + cat_stat_nanmedian(Ym(Ycls{1}(:)>128 & Yg(:)<.3)) ... + cat_stat_nanmedian(Ym(Ycls{2}(:)>128 & Yg(:)<.3)) ]; + Tth.T3th = [0 .05 1:5]; + Tth.T3thx = sort( [ min(Ym(:)) cat_stat_nanmedian([min(Ym(:)),T3thx2(1)/10]) T3thx2 T3thx2(3)+diff(T3thx2(2:3)) max(Ym(:)) ] ); + else + T3thx2 = [ cat_stat_nanmedian(Ym(Ycls{3}(:)>128 & Yg(:)<.3)) ... + cat_stat_nanmedian(Ym(Ycls{1}(:)>128 & Yg(:)<.3)) ... + cat_stat_nanmedian(Ym(Ycls{2}(:)>128 & Yg(:)<.3)) ]; + Tth.T3th = [0 .05 1:5]; + Tth.T3thx = sort( [ min(Ym(:)) cat_stat_nanmedian([min(Ym(:)),min(T3thx2)]) T3thx2 max(T3thx2)-diff([max(T3thx2),max([setdiff(T3thx2,max(T3thx2))])]) max(Ym(:)) ] ); + end + % global normalization + Ym = cat_main_gintnormi(Ym/3,Tth)/3; + % denoising + cat_sanlm(Ym,1,3); + % local normalization ( higher values are more stable?! ) + Ymi = cat_main_LASsimple(Ym*1000,Ycls); + end + + + % load original images and get tissue thresholds + WMth = double(max(clsint(2),... + cat_stat_nanmedian(cat_stat_nanmedian(cat_stat_nanmedian(Ysrc(Ycls{2}>192)))))); + T3th = [ min([ clsint(1) - diff([clsint(1),WMth]) ,clsint(3)]) , clsint(2) , WMth]; + clear Ysrc + + job.extopts.WMHC = 0; + job.extopts.SLC = 0; + job.extopts.LASmyostr = 0; + job.extopts.inv_weighting = T3th(3)0)); + indx = max((min(indx) - 1),1):min((max(indx) + 1),sz(1)); + indy = max((min(indy) - 1),1):min((max(indy) + 1),sz(2)); + indz = max((min(indz) - 1),1):min((max(indz) + 1),sz(3)); + Yp0b = Yp0(indx,indy,indz); + + + %% load atlas map and prepare filling mask YMF + % compared to CAT default processing, we have here the DARTEL mapping, but no individual refinement + if 1 + Vl1 = spm_vol(job.extopts.cat12atlas{1}); + if isfield(res,'spmpp') && res.spmpp + Yl1 = spm_sample_vol(Vl1,double(Yy(:,:,:,1)),double(Yy(:,:,:,2)),double(Yy(:,:,:,3)),0); + else + Yl1 = cat_vol_ctype( cat_vol_sample(res.tpm(1),Vl1,Yy,0)); % spm_sample_vol(Vl1,double(Yy(:,:,:,1)),double(Yy(:,:,:,2)),double(Yy(:,:,:,3)),0)); + end + Yl1 = reshape(Yl1,size(Ym)); [D,I] = cat_vbdist(single(Yl1>0), Yp0>0); Yl1 = cat_vol_ctype( Yl1(I) ); + YMF = NS(Yl1,job.extopts.LAB.VT) | NS(Yl1,job.extopts.LAB.BG); + YMF = cat_vol_morph( ~(Ycls{2}>128 & NS(Yl1,1)) & cat_vol_morph(YMF | (Ycls{2}>128 & NS(Yl1,1)),'ldc',2),'l',[1 .3]); + else + [Yl1,Ycls,YMF] = cat_vol_partvol1639(Ym*3,Ycls,Yb,Yy,vx_vol,job.extopts,res.tpm,1,job,false(size(Ym))); + end +return + +function [Ycls,Ym,Ymi,Yp0b,Yb,Yl1,Yy,YMF,indx,indy,indz,qa,job] = cat_main_SPMppold(Ysrc,Ycls,Yy,job,res,stime) +%% SPM segmentation input +% ------------------------------------------------------------------------ +% Here, DARTEL and PBT processing is prepared. +% We simply use the SPM segmentation as it is, without further modelling +% of the partial volume effect or other refinements. +% ------------------------------------------------------------------------ + + NS = @(Ys,s) Ys==s | Ys==s+1; % for side independent atlas labels + + % QA WMH values required by cat_vol_qa later + qa.subjectmeasures.WMH_abs = nan; % absolute WMH volume without PVE + qa.subjectmeasures.WMH_rel = nan; % relative WMH volume to TIV without PVE + qa.subjectmeasures.WMH_WM_rel = nan; % relative WMH volume to WM without PVE + qa.subjectmeasures.WMH_abs = nan; % absolute WMH volume without PVE in cm^3 + + vx_vol = sqrt(sum(res.image(1).mat(1:3,1:3).^2)); + + %% Update Ycls: cleanup on original data + Yb = Ycls{1} + Ycls{2} + Ycls{3}; + for i=1:numel(Ycls) + [Pc(:,:,:,i),BB] = cat_vol_resize(Ycls{i},'reduceBrain',repmat(job.opts.redspmres,1,3),2,Yb); %#ok + end + Pc = cat_main_clean_gwc(Pc,round(1./mean(vx_vol)),2); + for i=1:3, Ycls{i} = cat_vol_resize(Pc(:,:,:,i),'dereduceBrain',BB); end; clear Pc Yb; + + %% Update Ycls: cleanup on original data + if numel(Ycls)==3 + % in post-mortem data there is no CSF and CSF==BG + Yb = Ycls{1} + Ycls{2}; + [Yb,R] = cat_vol_resize(single(Yb),'reduceV',vx_vol,1,32,'meanm'); % use lower resolution to save time + Yb = cat_vol_morph(Yb>128,'ldo',3,R.vx_volr); % do some cleanup + Yb = cat_vol_morph(Yb,'ldc',8,R.vx_volr); % close mask (even large ventricles) + Yb = cat_vol_morph(Yb,'dd',1,R.vx_volr); % add 1 mm to have some CSF around the brain and simpliefy PVEs + Yb = cat_vol_resize(smooth3(Yb),'dereduceV',R)>0.5; % reinterpolate image and add some space around it + + Ycls{3} = cat_vol_ctype(single(Ycls{3}) .* Yb); + Ycls{4} = cat_vol_ctype(255 * (1-Yb)); + else + Yb = Ycls{1} + Ycls{2} + Ycls{3}; + end + for i=1:numel(Ycls) + [Pc(:,:,:,i),BB] = cat_vol_resize(Ycls{i},'reduceBrain',repmat(job.opts.redspmres,1,3),2,Yb); + end + Pc = cat_main_clean_gwc(Pc,round(1./mean(vx_vol)),2); + for i=1:3, Ycls{i} = cat_vol_resize(Pc(:,:,:,i),'dereduceBrain',BB); end; clear Pc Yb; + + %% create (resized) label map and brainmask + Yp0 = single(Ycls{3})/5 + single(Ycls{1})/5*2 + single(Ycls{2})/5*3; + Yb = single(Ycls{3} + Ycls{1} + Ycls{2}) > 128; + + % load original images and get tissue thresholds + clsint = @(x) round( sum(res.mn(res.lkp==x) .* res.mg(res.lkp==x)') * 10^5)/10^5; + + if isfield(job.extopts,'spmAMAP') && job.extopts.spmAMAP + fprintf('%5.0fs\n',etime(clock,stime)); + T3thx = [ clsint(3) clsint(1) clsint(2) ]; + T3thx = [ mean([min(Ysrc(Ycls{3}(:)>.5)), cat_stat_nanmedian(Ysrc(Ycls{3}(:)>128))]) ... + cat_stat_nanmedian(Ysrc(Ycls{1}(:)>128)) ... + cat_stat_nanmedian(Ysrc(Ycls{2}(:)>128)) ]; + + if any( diff( (T3thx-min(T3thx)) / (max(T3thx)-min(T3thx)) ) > .2 ) + % Usefull constrast between ALL tissues? + % Not allways working and especially in such cases AMAP is needed. + % This is expert processing and AMAP is not default! + % It inlcudes also some basic corrections (skull-stripping, bias + % correction, + + %% brain masking + if 0 + Yb = (single(Ycls{3} + Ycls{1} + Ycls{2}) > 64) | ... + cat_vol_morph( single(Ycls{3} + Ycls{1} + Ycls{2}) > 192,'dd',1.5); + Yb = cat_vol_morph( Yb ,'ldc',1.5); + Ycls{3} = max(Ycls{3},cat_vol_ctype(255*Yb) - Ycls{2} - Ycls{1}); + else + P = cat(4,Ycls{1},Ycls{2},Ycls{3},0*Ycls{4},0*Ycls{4},Ycls{4}); + res.isMP2RAGE = 0; + Yb = cat_main_APRG(Ysrc,P,res,double(T3thx)); + Yb = cat_vol_morph( Yb ,'ldc',5); + Yb = cat_vol_smooth3X(Yb,4)>.4; + clear P + end + %% bias correction + Yg = cat_vol_grad(Ysrc) ./ Ysrc; + Yi = Ysrc .* ( Ycls{2}>128 & Ysrc > mean(T3thx(2:3)) & Ysrc < T3thx(3)*1.2 & Yg < mean(Yg(Yb(:))) ) + ... + Ysrc .* ( Ycls{1}>128 & Ysrc > T3thx(2)*.9 & Ysrc < mean(T3thx(2:3)) & Yg < mean(Yg(Yb(:))) ) * T3thx(3) / T3thx(2); + Yi = cat_vol_approx(Yi,'rec'); + Ysrc = Ysrc ./ Yi * T3thx(3); + clear Yi; + + %% intensity normalization + T3thx2 = [ mean([min(Ysrc(Ycls{3}(:)>.5)), cat_stat_nanmedian(Ysrc(Ycls{3}(:)>128))]) ... + cat_stat_nanmedian(Ysrc(Ycls{1}(:)>128 & Yg(:)<.3)) ... + cat_stat_nanmedian(Ysrc(Ycls{2}(:)>128 & Yg(:)<.3)) ]; + Tth.T3th = [0 .05 1:5]; + Tth.T3thx = sort( [ min(Ysrc(:)) mean([min(Ysrc(:)),T3thx2(1)]) T3thx2 T3thx2(3)+diff(T3thx2(2:3)) max(Ysrc(:)) ] ); + Ym = cat_main_gintnormi(Ysrc/3,Tth) / 3; + Ym = cat_vol_sanlm(struct('data',res.image.fname,'verb',0,'NCstr',job.extopts.NCstr),res.image,1,Ym); + + %% add missing field and run AMAP + job.inv_weighting = 1; + job.extopts.AMAPframing = 1; + [prob,indx,indy,indz] = cat_main_amap1639(Ym+0,Yb,Yb,Ycls,job,res); + + % cleanup (just the default value) + if 0 %job.extopts.cleanupstr > 0 + prob = cat_main_clean_gwc1639(prob,min(1,job.extopts.cleanupstr*2/mean(vx_vol))); % default cleanup + end + + for i=1:3, Ycls{i}(:) = 0; Ycls{i}(indx,indy,indz) = prob(:,:,:,i); end + Ycls{3} = max(Ycls{3},cat_vol_ctype(255*Yb) - Ycls{2} - Ycls{1}); + Yp0 = single(Ycls{3})/5 + single(Ycls{1})/5*2 + single(Ycls{2})/5*3; + + else + % error message + cat_io_addwarning([mfilename ':cat_main_SPMpp:AMAP'],'AMAP selected but insufficient tissue contrast. Keep SPM segmentation!',4,[1 1]); + end + end + + + % load original images and get tissue thresholds + WMth = double(max(clsint(2),... + cat_stat_nanmedian(cat_stat_nanmedian(cat_stat_nanmedian(Ysrc(Ycls{2}>192)))))); + T3th = [ min([ clsint(1) - diff([clsint(1),WMth]) ,clsint(3)]) , clsint(2) , WMth]; + clear Ysrc + + job.extopts.WMHC = 0; + job.extopts.SLC = 0; + job.extopts.LASmyostr = 0; + job.extopts.inv_weighting = T3th(3)0)); + indx = max((min(indx) - 1),1):min((max(indx) + 1),sz(1)); + indy = max((min(indy) - 1),1):min((max(indy) + 1),sz(2)); + indz = max((min(indz) - 1),1):min((max(indz) + 1),sz(3)); + Yp0b = Yp0(indx,indy,indz); + clear Yp0; + + + %% load atlas map and prepare filling mask YMF + % compared to CAT default processing, we have here the DARTEL mapping, but no individual refinement + Vl1 = spm_vol(job.extopts.cat12atlas{1}); + Yl1 = cat_vol_ctype( cat_vol_sample(res.tpm(1),Vl1,Yy,0)); % spm_sample_vol(Vl1,double(Yy(:,:,:,1)),double(Yy(:,:,:,2)),double(Yy(:,:,:,3)),0)); + Yl1 = reshape(Yl1,size(Ym)); [D,I] = cat_vbdist(single(Yl1>0), Yp0>0); Yl1 = cat_vol_ctype( Yl1(I) ); + YMF = NS(Yl1,job.extopts.LAB.VT) | NS(Yl1,job.extopts.LAB.BG); + % refine closing area on low resolution + [Yp0r,YMFr,BB] = cat_vol_resize({Yp0 ,YMF },'reduceBrain',vx_vol,4,Yb); + [Yp0r,YMFr,resTr] = cat_vol_resize({Yp0r,YMFr},'reduceV',vx_vol,2,64); + YMFr = single( min(1,(YMFr>.5) + 0.5*(Yp0r>2.5))); + YMFr = cat_vol_laplace3R(YMFr,Yp0r<2.5 & ~YMFr,0.01); + YMF = cat_vol_resize(YMFr,'dereduceV',resTr); + YMF = cat_vol_resize(YMF,'dereduceBrain',BB)>.75; + % combine with WM + YMF = smooth3( cat_vol_morph( ~(Ycls{2}>128 & NS(Yl1,1)) & cat_vol_morph(YMF | (Ycls{2}>128 & NS(Yl1,1)),'ldc',2),'l',[1 .3]) ); +return + +function [Ymix,job,surf,stime] = cat_main_surf_preppara(Ymi,Yp0,job,vx_vol) +% ------------------------------------------------------------------------ +% Prepare some variables for the surface processing. +% ------------------------------------------------------------------------ + + stime = cat_io_cmd('Surface and thickness estimation'); + + % specify surface + switch job.output.surface + case {1,11}, surf = {'lh','rh'}; + case {2,12}, surf = {'lh','rh','cb'}; + case {9,19}, surf = {'lhv','rhv'}; % estimate only volumebased thickness + otherwise, surf = {}; + end + if ~job.output.surface && any( [job.output.ct.native job.output.ct.warped job.output.ct.dartel] ) + surf = {'lhv','rhv'}; + end + + % surface creation and thickness estimation input map + Yp0toC = @(c) 1-min(1,abs(Yp0-c)); + Yp0th = @(c) cat_stat_nanmedian( Ymi(Yp0toC(c) > 0.5) ); + if job.output.surface < 10 && ... + ( Yp0th(1) < Yp0th(2) ) && ( Yp0th(2) < Yp0th(3) ) && ( Yp0th(3) > 0.9 ) + Ymix = Ymi .* (Yp0>0.5); % using the locally intensity normalized T1 map Ymi + else + Ymix = Yp0 / 3; % use the AMAP segmentation + end +return +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_vol_iscale.m",".m","26714","565","function [TI,varargout] = cat_vol_iscale(T,action,vx_vol,varargin) +% CAT Preprocessing Intensity Scaling Functions +% ______________________________________________________________________ +% Set of functions for intensity scaling of an image T. +% +% actions: +% - findhead: [TI,H] = cat_vol_iscale(T,'findhead' ,vx_vol); +% - findbrain: [TI,B] = cat_vol_iscale(T,'findbrain',vx_vol); +% - gCGW: [TI,tp] = cat_vol_iscale(T,'gCGW',vx_vol,...); +% +% [TI,varargout] = cat_vol_iscale(T,action,vx_vol,varargin) +% +% T = original 3d-volume +% action = used method {'findhead'|'findbrain'|'gCGW'} +% = test method {'test_findhead_findbrain'}; +% vx_vol = 1x3 matrix with the voxel size (default [1 1 1]) +% +% TI = intensity scaled volumen with BG=0 and WM=1. +% varargout{1} = head mask (for action 'findhead') +% varargout{1} = brain mask (for action 'findbrain') +% varargout{1} = tissue peaks (BG,CSF,GM,WM,high) +% +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% +% $Id$ +% ______________________________________________________________________ + + + if ~exist('T','var') + error('MATLAB:cat_vol_iscale:input','ERROR: Need input image!\n'); + else + T = single(T); + end + if ~exist('action','var') + error('MATLAB:cat_vol_iscale:input','ERROR: Unkown action ''%s''!\n',action); + end + if ~exist('vx_vol','var') + vx_vol=ones(1,3); + end + + + switch action + case 'findhead' + % UPDATE durch findbrain nötig + % __________________________________________________________________ + + %if nargin>3, redres = varargin{1}; end + + % noise estimation is only possible in edge-free regions + [gx,gy,gz] = cat_vol_gradient3(T); G=abs(gx)+abs(gy)+abs(gz); + G=G./max(eps,T); G(isinf(G) | isnan(G) | G<0)=0; clear gx gy gz; + [Tr,Gr,resT] = cat_vol_resize({T,G},'reduceV',vx_vol,12,24); + + Mr = Grmean(Tr(:)); + Gth = cat_stat_nanstat1d(Gr(Mr(:)),'median'); + Mr = cat_vol_morph(Tr>mean(Tr(Gr(:)0; + Tth = cat_stat_nanstat1d(Tr(Mr(:)),'median'); + clear GMr TMr; + + % background estimation + Hr = cat_vol_smooth3X(cat_vol_morph(Tr>Tth*0.3,'ldc',8),1)>0.5; %0.1 %2 % 2 + + TI = T./Tth*0.7; + varargout{1} = cat_vol_resize(Hr,'dereduceV',resT); + + + + case 'findbrain' + % Finds the brain and scale the intensity of a T1 MR image based on + % Eikonal distance and object proberties. + % __________________________________________________________________ + + if nargin>3, redres = varargin{1}; else redres = 4; end + + tic + % save original image + TO = T+0; + + %% reduce to ultra highres images to save time + [T,resTO] = cat_vol_resize(T,'reduceV',vx_vol,1.2); vx_vol=resTO.vx_volr; + + % initial noise correction + TSDs = [round(size(TO) * 2/5);round(size(TO) * 3/5)]; + TSD = single(TO(TSDs(1):TSDs(2),TSDs(3):TSDs(4),TSDs(5):TSDs(6))); + TSD = TSD/cat_stat_nanstat1d(TSD,'median'); + [gx,gy,gz] = cat_vol_gradient3(TSD); GTSD=abs(gx)+abs(gy)+abs(gz); + TSD = cat_vol_localstat(TSD,GTSD<0.2,1,4); + n1 = cat_stat_nanstat1d(TSD(TSD>0),'mean'); + nc = min(1.0,max(1/2,n1*10)); + TS = cat_vol_smooth3X(single(T),nc); + clear TSD TSDs nc GTSD gx gy gz; + % gradient map + [gx,gy,gz] = cat_vol_gradient3(TS); G=abs(gx)+abs(gy)+abs(gz); + G=G./max(0,TS-mean(TS(:)/3)); G(isinf(G) | isnan(G) | G<0)=10; clear gx gy gz; + + + % Intensity scaling for bad contrast pictures, but only for positiv + % minima, because heavy background noise (""sMT01-0003-00001-000176-01_MT"") + % can cause problems in background detection. + [Tr,Gr] = cat_vol_resize({max(0,TS-(G.*TS)),G},'reduceV',vx_vol,4); + minT = max(0,min(Tr(:))); T=T-minT; TS=TS-minT; TO=TO-minT; Tr=Tr-minT; + Mr = Grmean(Tr(:)); + Gth = cat_stat_nanstat1d(Gr(Mr(:)),'median'); + Mr = cat_vol_morph(Tr>mean(Tr(Gr(:)0; +% Tth = cat_stat_nanstat1d(Tr(Mr(:)),'median'); + Tth = peak(Tr(Mr(:))/max(Tr(Mr(:))))*max(Tr(Mr(:))); + clear GMr TMr; + + + + % Addaptive noise correction: + % We filter in every case, because although high field strength + % produce lower noise they have higher bias that lead to stronger + % noise after bias correction for regions with lower intensity. + % For noise estimation a part of the WM region should be used, by + % the labopen function that may remove one hemissphere, but allows + % a better WM peak (Tth) estimation. + M2 = smooth3(TS>Tth*2/3 & TS0.5; M2max=max(TS(M2(:)>0)); + Tth = peak(TS(M2>0)/M2max)*M2max*0.5 + 0.5*cat_stat_nanstat1d(TS(M2(:)),'median'); + M2 = cat_vol_morph(smooth3(TS>Tth*2/3 & TS0.5,'l'); + TSD = cat_vol_localstat(T./Tth,M2,1,4); + n2 = cat_stat_nanstat1d(TSD(TSD>0),'mean'); + nc = min(1.0,max(1/2,n2*10)); + TS = cat_vol_smooth3X(single(T),nc); + clear TSD; + % gradient map update after smoothing + [gx,gy,gz] = cat_vol_gradient3(TS); G=abs(gx)+abs(gy)+abs(gz); + G=G./max(0,TS-mean(TS(:)/3)); G(isinf(G) | isnan(G) | G<0)=10; clear gx gy gz; + + % test functions + % fprintf(' %0.2f %0.2f | %0.3f %0.3f',n1,n2,Gth,Tth); return + % ds('l2','',vx_vol,TS/Tth,M2,G>Gth,TS/Tth,round(size(TS,3)*3/5)); pause(2); return + + %% background and distance estimation to find parts of brain tissue + + % background estimation + [Hr,resTr] = cat_vol_resize(TS./G>0.5 & TS/Tth>0.2,'reduceV',vx_vol,8,8,'nearest'); + Hr = cat_vol_morph(Hr,'dc',3); + H = cat_vol_resize(Hr,'dereduceV',resTr)>0.5; clear Hrr + + % distance estimation to find the brain + [Tr,Hr,resT] = cat_vol_resize({min(1.5,TS/Tth),H},'reduceV',vx_vol,redres,32,'mean'); + [Gr] = cat_vol_resize(G,'reduceV',vx_vol,redres,32,'max'); + HDr = cat_vbdist(single(~Hr),true(size(Hr)),resT.vx_volr); + [Mr,Dr] = cat_vol_downcut(single(~cat_vol_morph(Hr,'e')), ... + 1-Gr,0.1,resT.vx_volr,[double(eps('single')) 1]); + Dr = Dr .* HDr/cat_stat_nanstat1d(HDr(:),'max'); %Dr = max(0,Dr - cat_stat_nanstat1d(Dr(:),'max')/2); + Dr(isnan(Dr) | isinf(Dr))=0; clear Mr; + D = cat_vol_resize(cat_vol_smooth3X(Dr),'dereduceV',resT); + % toc + + + + %% BIAS Correction: + tic + TSO=TS; it=1; itmax=8; CV=0; CVO=inf; CVP=1; CVth=0.001; bs=3; + while it<=itmax && CV=1 + % GM/WM boundary estimation to classify the WM and GM segemnts: + res1 = 2.5; %1.6; + [Gr,Dr,resT1] = cat_vol_resize({G,D},'reduceV',vx_vol,res1,32,'meanm'); + TSr = cat_vol_resize(TS,'reduceV',vx_vol,res1,32,'max'); + M2r = cat_vol_resize(M2,'reduceV',vx_vol,res1,32,'meanm')>0.5; + TSXr = TSr .* cat_vol_morph(Gr0.1,'lo'); TSXr=cat_vol_median3(TSXr,TSXr>0); + + % very rough maximum based correction for better GWM estimation + [WIrr,resT2] = cat_vol_resize(TSXr,'reduceV',vx_vol,4,32,'max'); TSXrr=WIrr>0; + WIrr = cat_vol_approx(WIrr,'nh',resT1.vx_volr,8); WIrr = cat_vol_smooth3X(WIrr,max(2,min(4,Tth/std(WIrr(TSXrr(:)))))); + WIr = cat_vol_resize(WIrr,'dereduceV',resT2); clear WIrr; + WIr = WIr * median(TSr(M2r(:) & Gr(:)WIr(:)*0.95) ./ WIr(M2r(:) & Gr(:)WIr(:)*0.95)); + + %% estimating of the GM-WM threshold GWM + GWMr = TSr .* (smooth3(Gr>Gth/2 & TSr./WIr<1.2 & Gr0)>0.5); + GWMr = TSr .* (GWMr>WIr*(0.6-2*(1 - mean(GWMr(GWMr(:)>0)./WIr(GWMr(:)>0))))) .* (GWMr0; + for i=1:4, GWMrr = cat_vol_localstat(GWMrr,GWMrr>0,2,1); end + GWMrr = cat_vol_approx(GWMrr,'nh',resT2.vx_volr,8); GWMrr = cat_vol_smooth3X(GWMrr,max(2,min(4,Tth/std(GWMrr(TSXrr(:)))))); + GWMr = cat_vol_resize(GWMrr,'dereduceV',resT2); clear GWMrr; + + + % rought maximum based bias correction + TSXOr = cat_vol_morph(GrGWMr*0.95 & TSr0); + [WIrr,resT2] = cat_vol_resize(TSXOr,'reduceV',resT1.vx_volr,4,32,'max'); TSXrr=WIrr>0; + WIrr = cat_vol_localstat(WIrr,WIrr>0,1,3); + WIrr = cat_vol_approx(WIrr,'nh',resT2.vx_volr,8); WIrr = cat_vol_smooth3X(WIrr,max(2,min(4,Tth/std(WIrr(TSXrr(:)))))); + WIr = cat_vol_resize(WIrr,'dereduceV',resT2); clear WIrr; + WIr = WIr * median(TSr(M2r(:) & Gr(:)WIr(:)*0.95) ./ WIr(M2r(:) & Gr(:)WIr(:)*0.95)); + + %% update of the GWM threshold + GWMr = TSr .* (smooth3(Gr>Gth/4 & GrWIr*0.4 & TSr0.5); + [GWMrr,resT2] = cat_vol_resize(GWMr,'reduceV',resT1.vx_volr,8,32,'meanm'); TSXrr=GWMrr>0; + for i=1:2, GWMrr = cat_vol_localstat(GWMrr,GWMrr>0,2,1); end + GWMrr = cat_vol_approx(GWMrr,'nh',resT2.vx_volr,8); GWMrr = cat_vol_smooth3X(GWMrr,max(2,min(4,Tth/std(GWMrr(:))))); + GWMr = cat_vol_resize(GWMrr,'dereduceV',resT2); clear GWMrr; + + + % final inital maximum based bias correction WI + TSXOr = cat_vol_morph(Grmin(WIr*0.9,(GWMr*0.5+0.5*WIr)) & TSr./WIr0); + [WIrr,resT2] = cat_vol_resize(TSXOr,'reduceV',resT1.vx_volr,4,32,'max'); TSXrr=WIrr>0; + WIrr = cat_vol_localstat(WIrr,WIrr>0,1,3); + WIrr = cat_vol_approx(WIrr,'nh',resT2.vx_volr,8); WIrr = cat_vol_smooth3X(WIrr,max(2,min(4,Tth/std(WIrr(TSXrr(:)))))); + WIr = cat_vol_resize(WIrr,'dereduceV',resT2); clear WIrr; + WIr = WIr * median(TSr(M2r(:) & Gr(:)WIr(:)*0.95) ./ WIr(M2r(:) & Gr(:)WIr(:)*0.95)); + + %% rough skull-stripping + % use the head distance map D to find a central tissue (low gradient) with WM intensity + [Grr,Trr,GWMrr,Drr,M2rr,resT4] = cat_vol_resize({Gr,TSr./WIr,GWMr./WIr,Dr,M2r},'reduceV',vx_vol,2,32,'meanm'); + Brr = cat_vol_morph(Trr<1.2 & Trr>max(0.8,GWMrr) & Grr0),1:num); [Hs,Hi] = sort(HST,'descend'); + Hi(min(numel(Hi), max(2,find(HsmaxD; maxD=sumD; maxL=Hi(l); end; + end + Brr = L==maxL; + Brr = cat_vol_morph(Brr | (cat_vol_morph(Brr>0.5,'d',round(4 / mean(resT4.vx_volr))) & Trr>1/2 & Trr<1.2),'dc',10); + Br = cat_vol_resize(cat_vol_smooth3X(Brr),'dereduceV',resT4)>0.5; clear Trr Brr; + + % dereduce maps + %GWM = cat_vol_resize(GWMr./WIr,'dereduceV',resT1); + WI = cat_vol_resize(WIr,'dereduceV',resT1); + B = cat_vol_resize(cat_vol_smooth3X(Br),'dereduceV',resT1)>0.5; + + + + TI=TS./WI; +% [TI,T3th,T3] = cat_vol_CGWscale(TS./WI,G,B,Gth,resT1.vx_vol); + Tr = cat_vol_resize(TI,'reduceV',vx_vol,res1,32,'max'); + Br = Br>0.5 & Tr>4/5 & Tr<8/6 & Gr8/6))=-inf; Br = single(cat_vol_smooth3X(cat_vol_downcut(Br,Tr, 0.02/mean(resTr.vx_volr))>0,1)>0.5); + Br(~Br & (Tr<2/3 | Tr>8/6))=-inf; Br = single(cat_vol_smooth3X(cat_vol_downcut(Br,Tr, 0.01/mean(resTr.vx_volr))>0,1)>0.5); + Br(~Br & (Tr<1/3 | Tr>2/3))=-inf; Br = single(cat_vol_smooth3X(cat_vol_downcut(Br,Tr,-0.01*mean(resTr.vx_volr))>0,1)>0.5); + Br(~Br & (Tr<1/6 | Tr>1/2))=-inf; Br = cat_vol_smooth3X(cat_vol_downcut(Br,Tr,-0.02*mean(resTr.vx_volr))>0,1)>0.5; + [Trr,Brr,resTBr] = cat_vol_resize({Tr,Br},'reduceV',vx_vol,4,32); Brr=Brr>0.5; + Brr = cat_vol_morph(Brr | (cat_vol_morph(Brr,'ldc',4) & Trr<8/6),'lo',2); + Br = (Br.*Tr)>0.5 | (cat_vol_resize(cat_vol_smooth3X(Brr),'dereduceV',resTBr)>0.5 & Tr<1.05); + B = cat_vol_resize(cat_vol_smooth3X(Br),'dereduceV',resT1)>0.5; + end + %toc,tic + %} + + %% Fine correction + % ---------------------------------------------------------------- + % tissue segmentation and intensity scaling + %res1 = 1.6; + + %TI = cat_vol_iscale(TS./WI,'gCGW',vx_vol,T3th); + %{ + % final maximum based bias correction WI3 + %GM = B & cat_vol_resize(cat_vol_smooth3X(T3r{2},0.5),'dereduceV',resT1)>0.5; + %GMC = B & cat_vol_resize(cat_vol_smooth3X(cat_vol_morph(T3r{2},'c',4),0.5),'dereduceV',resT1)>0.5; + GM = B & T3{2}; + [T3r,resT3] = cat_vol_resize(T3{2},'reduceV',resT1.vx_volr,4,32,'max'); + GMC = B & cat_vol_resize(cat_vol_smooth3X(cat_vol_morph(T3r,'c',4),0.5),'dereduceV',resT3)>0.5; + WM = cat_vol_morph(B & TI>0.9 & TI<1.5 & GGWM + WM = WM | (~GM& GMC & TI<1.5 & G0.1) & ~T3{2}; % & TS./WI>GWM + [WI3r,resT6] = cat_vol_resize(TSO.*WM,'reduceV',resT1.vx_volr,1.6,32,'max'); WMrr=WI3r>0; + WI3r = cat_vol_localstat(WI3r,WI3r>0,round(3/mean(resT6.vx_volr)),3); + WI3r = cat_vol_approx(WI3r,'linear',resT6.vx_volr,8); WI3r = cat_vol_smooth3X(WI3r,max(2,min(6,Tth/std(WI3r(WMrr(:)))))); + + WI3 = cat_vol_resize(WI3r,'dereduceV',resT6); %clear WI3r; + [TI,T3th,T3] = cat_vol_CGWscale(TSO./WI3,G,B,Gth,resT1.vx_vol); + WM = cat_vol_morph(B & TI>11/12 & TI<8/6 & G5/6 & TI<1.2 & G0.5; + %} + %{ + [Tr,Br,Gr,BOr,resTr] = cat_vol_resize({TI,single(WM.*B),G,B},'reduceV',vx_vol,res1,32); + Br = BOr>0.5 & Tr>9/12 & Tr<8/6 & Gr8/6))=-inf; Br = single(cat_vol_smooth3X(cat_vol_downcut(Br,Tr, 0.020/mean(resTr.vx_volr))>0,1)>0.5); + Br(~Br & (Tr<5/6 | Tr>8/6))=-inf; Br = single(cat_vol_smooth3X(cat_vol_downcut(Br,Tr, 0.010/mean(resTr.vx_volr))>0,1)>0.5); + Br(~Br & (Tr<2/3 | Tr>8/6))=-inf; Br = single(cat_vol_smooth3X(cat_vol_downcut(Br,Tr, 0.005/mean(resTr.vx_volr))>0,1)>0.5); + Br(~Br & (Tr<1/3 | Tr>2/3))=-inf; Br = cat_vol_smooth3X(cat_vol_downcut(Br,Tr,-0.01*mean(resTr.vx_volr))>0,1)>0.5; + [Trr,Brr,resTBr] = cat_vol_resize({Tr,Br},'reduceV',vx_vol,4,32); Brr=Brr>0.5; + Brr = cat_vol_morph(Brr | (cat_vol_morph(Brr,'ldc',4) & Trr<7/6),'lo',2); + Br = (Br.*Tr)>0.5 | (cat_vol_resize(cat_vol_smooth3X(Brr),'dereduceV',resTBr)>0.5 & Tr<1.05); + B = cat_vol_resize(cat_vol_smooth3X(Br),'dereduceV',resTr)>0.5; + %} + + if it==1, WI3O=ones(size(TS)); else WI3O=WI; end + + WM = cat_vol_morph(B & TI>11/12 & TI<8/6 & G0))/mean( TS(WM(:)>0));% + std( TS(B(:)>0 & GM(:)>0))/mean( TS(B(:)>0 & GM(:)>0)); + CVP = std( T(WM(:)>0))/mean( T(WM(:)>0));% + std( T(B(:)>0 & GM(:)>0))/mean( T(B(:)>0 & GM(:)>0)); + CVO = std(TSO(WM(:)>0))/mean(TSO(WM(:)>0));% + std(TSO(B(:)>0 & GM(:)>0))/mean(TSO(B(:)>0 & GM(:)>0)); + % toc + if CVP> %0.3f > %0.3f\n',CVO,CVP,CV); + end + TS = TSO; %T = T/median(T(WM(:)>0)); + %fprintf('Tissue Peaks: %0.2f %0.2f %0.2f\n',T3th); + + % toc + + %% scull-stipping on low res + tic; clear TSO WI GWM; + res1=1.5; + [Tr,Br,Gr,BOr,resTr] = cat_vol_resize({TI,single(WM.*B),G,B},'reduceV',vx_vol,res1,32); + % Tr = cat_vol_CGWscale(Tr,Gr,BOr,Gth,vx_vol); + Br = BOr>0.5 & Tr>5/6 & Tr<8/6 & Gr8/6))=-inf; Br = single(cat_vol_smooth3X(cat_vol_downcut(Br,Tr, 0.010/mean(resTr.vx_volr))>0,1)>0.5); + Br(~Br & (Tr<2/3 | Tr>5/6))=-inf; Br = single(cat_vol_smooth3X(cat_vol_downcut(Br,Tr, 0.001/mean(resTr.vx_volr))>0,1)>0.5); + Br(~Br & (Tr<1/3 | Tr>2/3))=-inf; Br = cat_vol_smooth3X(cat_vol_downcut(Br,Tr,-0.01*mean(resTr.vx_volr))>0,1)>0.5; + [Trr,Brr,resTBr] = cat_vol_resize({Tr,Br},'reduceV',vx_vol,4,32); Brr=Brr>0.5; + Brr = cat_vol_morph(Brr | (cat_vol_morph(Brr,'lc',1) & Trr<7/6),'lo',2); + Br = (Br.*Tr)>0.5 | (cat_vol_resize(cat_vol_smooth3X(Brr),'dereduceV',resTBr)>0.5 & Tr<1.05); + B = cat_vol_resize(cat_vol_smooth3X(Br),'dereduceV',resTr)>0.5; + % toc,tic + + %% + %T = cat_vol_resize(T ,'dereduceV',resTO); + G = cat_vol_resize(G ,'dereduceV',resTO); + B = cat_vol_resize(B ,'dereduceV',resTO)>0.5; + WI3 = cat_vol_resize(WI3,'dereduceV',resTO); + H = cat_vol_resize(H ,'dereduceV',resTO)>0.5; + WM = cat_vol_resize(WM ,'dereduceV',resTO)>0.5; + + % segment image + %{ + % ds('l2','',vx_vol,T,p0T,TO./WI2,T/Tth,90) + WM = cat_vol_morph(WM,'e'); + TI = cat_vol_CGWscale(TO./WI3,G,B,Gth,vx_vol); + TSD = cat_vol_localstat(TI,WM,1,4); + n3 = cat_stat_nanstat1d(TSD(TSD>0),'mean'); + nc = min(0.9,max(0.3,n3*10)); + BV = B & ((TI>7/6 & ~cat_vol_morph(TI>5/6,'l')) | TI>9/6); BV = 2*cat_vol_morph(BV,'d') - BV; + p0T = max(B,min(3,round(cat_vol_smooth3X(TI,nc)*3).*B)); + p0T(BV & p0T) = min(BV(BV & p0T),p0T(BV & p0T)); + p0T(cat_vol_morph(p0T==3,'l'))=3; % close small WM wholes + %} + %toc + varargout{1} = B; + varargout{2} = WM; +% varargout{3} = H; +% varargout{4} = cat_stat_nanstat1d(TO(WM(:)),'mean'); +% varargout{5} = min(1.2,max(0,(TI*3)-1)/2); %(TO./WI3); +% varargout{5} = varargout{5} / cat_stat_nanstat1d(varargout{5}(WM(:)),'mean'); + % varargout{6} = p0T; + case 'test_findhead_findbrain' + opt.fnamelenght = 40; + + if isempty(T), T = cat_io_checkfilelist(spm_select(Inf,'image','select raw images')); end + V = spm_vol(T); + + fprintf('FindBrainTest: \n'); + for subj = 1:numel(V) + % display subject name and home directory + [pp,ff] = spm_fileparts(V(subj).fname); [pp,hh]=spm_fileparts(pp); + fn = [hh filesep ff]; clear pp ff; + fprintf(1,'%s',fliplr(sprintf(sprintf('%% %ds',opt.fnamelenght),... + fliplr(fn(1:min(numel(fn),opt.fnamelenght)))))); clear space fn; + + % test + vx_vol = sqrt(sum(V(subj).mat(1:3,1:3).^2)); + stime1 = clock; [TH,MH] = cat_vol_iscale(single(spm_read_vols(V(subj))), ... + 'findhead' ,vx_vol,4); + stime2 = clock; [TB,MB] = cat_vol_iscale(single(spm_read_vols(V(subj))), ... + 'findbrain',vx_vol,4); + ds('cat_vol_iscale','',vx_vol,TH,MH,TB,MB,round(size(TH,3)/9*5)); + pause(1); fprintf('\n'); + end + + case 'gCGW' + % __________________________________________________________________ + +% function tp=tissue_peaks(T,GWM) +% [gx,gy,gz] = cat_vol_gradient3(T); G=abs(gx)+abs(gy)+abs(gz); G=G./T; clear gx gy gz; +% tp(3) = cat_stat_nanmedian(T(GWM(:) & T(:)>0.6 & T(:)<1.5 & G(:)0.4 & T(:)2 + if max(varargin{1})==3 + for i=1:3, tp2=cat_stat_nanstat1d(T(varargin{1}(:)==i),'median'); end + tp2(4) = min(4,tp2(3)+diff(tp2(2:3))); + else + B=varargin{1}; + + [gx,gy,gz] = cat_vol_gradient3(T); G=abs(gx)+abs(gy)+abs(gz); + G=G./T; G(isinf(G) | isnan(G) | G<0)=0; clear gx gy gz; + tpa = cat_stat_nanstat1d(T(B & G<0.2 & T>mean(T(B(:)>0))),'median'); T = T / tpa; + + [Tr,Gr,Br] = cat_vol_resize({T,G,B},'reduceV',vx_vol,2); + + + % inital tissues values + WMr = Br & Gr<0.2 & Tr>0.9 & Tr<1.5; + tp0(3) = cat_stat_nanstat1d(Tr(WMr(:)),'median'); + + GMr = Br & Gr<0.3 & Tr<0.9 & Tr>0.4; + tp0(2) = cat_stat_nanstat1d(Tr(GMr(:)),'median'); + + CMr = Br & Gr<0.4 & Trmean(tp0(2:3)) & Trmean(tp0(1:2)) & Tr0),3,100,tp1(1:3)); + WMr = Br & Tr>mean(tp1(2:3)) & Trmean(tp1(1:2)) & Tr + % if inlut is not available... only temporarly!!! + % ################################################################ + + % ################################################################ + end + end + %} + TI = T; + isc = 2; + tp2 = interp1(tp2,1:1/isc:5,'pchip'); + for i=2:numel(tp2) + M = T>tp2(i-1) & T<=tp2(i); + TI(M(:)) = (i-2)/isc/3 + (T(M(:)) - tp2(i-1))/diff(tp2(i-1:i))/isc/3; + end + M = T>=tp2(end); + TI(M(:)) = numel(tp2)/isc/3 + (T(M(:)) - tp2(i))/diff(tp2(end-1:end))/isc/3; + + varargout{1} = tp2; + otherwise + end +end + + +function p=peak(T,ss) + if ~exist('ss','var'), ss=0.01; end + H=hist(T(:),0:ss:2.00); H=smooth(H,20); %'rloess',20); + [v,p]=max(H(:)); p=p*ss; +end + +function HS = smooth(H,span) + window = ones(span,1)/span; + HS = convn(H,window,'same'); +end + +%{ +% working version +function [TI,T3th,T3r] = cat_vol_CGWscale(T,G,B,Gth,vx_vol) + %% T=cat_vol_smooth3X(T,0.5); + + % Los gehts mit dem WM, das wir ja nun schon durch die Biaskorrektur + % kennen und das sich um 1.00 bewegt. + T7{6} = cat_vol_morph(B & G0.9 & T<=1.3,'l'); + T7th(6) = min(1.3,max(0.95,cat_stat_nanstat1d(T(T7{6}),'median'))); + + % Nun können wir uns die Kannte zum GM anschauen, die sich in D<2 zum + % knapp unterhalb des WM. Da diese beide Seiten gleichartig betrifft, + % sollte man so recht gut den GWM peak bestimmen können. Das da teil- + % weise bissel CSF mit dabei sollst schnuppe sein. + T7{5} = (G>Gth & G<0.5 & B & cat_vol_morph(T>T7th(6),'d',1) & TGth/2 & G<0.5 & B & T>0.3 & TT7th(4)-std(T(T7{4}(:))) & T<(T7th(4)*0.2 + T7th(6)*0.8); + T7th(4) = max(0.5*T7th(6),min(0.90*T7th(6),cat_stat_nanstat1d(T(T7{4}),'median'))); + + T7{3} = (G>Gth*2 & G<1 & B & cat_vol_morph(T10 + T7{2} = cat_vol_morph(T7{2},'l'); + T7th(2) = max(0.1*T7th(6),min(0.60*T7th(6),cat_stat_nanstat1d(T(T7{2}),'median'))); + else + T7th(2) = T7th(3) - T7th(4)-diff(T7th([4,6])); + end + T7th(1) = T7th(2)/2; + + % Als dem WM glaub ich, beim GM und CSF ist es schwieriger. + % Ist viel CSF da (Ventrikel), ist es meist eine brauchere Information + % als das GM da dieses halt durch den PVE und Krankheiten in + % Mitleidenschaft gezogen sein kann. Im gesunden fall haben wir aber + % meist zu wenig CSF als das man damit was machen könne, weshalb die + % Abschätzung des CSFs über den GM Wert dann schon wieder besser ist. + T3th(3) = T7th(6); + T3th(2) = T7th(4); + T3th(1) = max(0,min(T7th(2),T7th(4)-diff(T7th([4,6])))); + + TI = cat_vol_iscale(T,'gCGW',vx_vol,T3th); + p0T = max(B,min(3,round(TI*3).*B)); + for i=2:2, T3th(i) = median(T(p0T==i)); end + TI = cat_vol_iscale(T,'gCGW',vx_vol,T3th); + T3r = T7(2:2:end); +end +function p=peak(T,ss) + if ~exist('ss','var'), ss=0.01; end + H=hist(T(:),0:ss:2.00); H=smooth(H,20); %'rloess',20); + [v,p]=max(H(:)); p=p*ss; +end + +function HS = smooth(H,span) + window = ones(span,1)/span; + HS = convn(H,window,'same'); +end +%} +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_vol_reduceRes.m",".m","4017","124","function varargout = cat_vol_reduceRes(varargin) +% ______________________________________________________________________ +% Reduction of the image resolution by merging of voxels with the name +% ""lowresR#x#x#_*.nii with * for the original file name, and # for the +% degree of reduction, with #=2 for the half resolution. +% +% V = cat_vol_reduceRes(job) +% +% job.data = cell of filename, use GUI if empty +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + if nargin == 0 + job.data = cellstr(spm_select([1 Inf],'image','select images to reduce')); + else + job = varargin{1}; + end + + if ~isfield(job,'data') || isempty(job.data) + job.data = cellstr(spm_select([1 Inf],'image','select images to reduce')); + else + job.data = cellstr(job.data); + end + if isempty(job.data) || isempty(job.data{1}) + fprintf('No data!\n'); + return; + end + + def.verb = 1; + def.lazy = 1; + def.prefix = 'lowres'; + job = cat_io_checkinopt(job,def); + spm_clf('Interactive'); + + V = spm_vol(char(job.data)); + vx_vol = sqrt(sum(V(1).mat(1:3,1:3).^2)); + if ~isfield(job,'res'); + job.res = round(max(1,spm_input('Specify reduction factor(s)! ',... + '+1','i',round(min(vx_vol)*2.2 ./ vx_vol),[inf,3]))); + end + if isempty(job.res) + fprintf('No resolution!\n'); + return; + end + + Vr = repmat(V,1,size(job.res,1)); + Vr = rmfield(Vr,'private'); + + spm_clf('Interactive'); + if job.verb, fprintf('cat_vol_reduceRes:\n'); end + cat_progress_bar('Init',numel(job.data) .* size(job.res,1),'Resolution Reduction','Volumes Complete'); + for pi=1:numel(job.data) + % load image + Yi = single(spm_read_vols(V(pi))); + si = size(Yi); + + %% processing + for ri=1:size(job.res,1) + % matrix size parameter + + ss = floor(si ./ job.res(ri,:)); + sx = ss .* job.res(ri,:) + (job.res(ri,:)-1); + if any(si0 + varargout{1} = Vr; + end +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_display_matlab_PID.m",".m","915","31","function varagout = cat_display_matlab_PID +% cat_display_matlab_PID (in development!) +% ______________________________________________________________________ +% +% Display exor return PID of this (Linux/Mac) or the last started +% (Windows) MATLAB instace. +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + % get PID + pid = feature('getpid'); + + % display PID + if nargout==0 + if isnumeric(pid) && ~isempty(pid) + fprintf('CAT parallel processing with MATLAB PID: %d\n',pid); + else + fprintf('CAT parallel processing with MATLAB PID: unknown %s PID %d\n',computer,pids); + end + else + varagout{1} = pid; + end + +end +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_io_struct2cell.m",".m","1580","60","function [FN,C] = cat_io_struct2cell(S,separator) +% cat_io_struct2cell. Recursive use of struct2cell with fieldnames. +% +% [FN,C] = cat_io_struct2cell(S,separator) +% +% FN .. list of full fieldname +% C .. data entry +% S .. struct +% separator .. seperator of fields in FN (default = '.') +% +% Example: +% S = struct('a',1,'b',struct('b1',2,'b2',3)) +% [FN,C] = cat_io_struct2cell(S) +% +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + if ~exist('separator','var') + separator = '.'; + end + + if numel(S) > 1 + error( ... + sprintf('%s:nelment',mfilename),... + 'Only 1 element per (sub)struct supportet yet!'); + end + + FN = fieldnames(S); + C = struct2cell(S); + for ci = numel(C)-1:-1:1 + if isstruct(C{ci}) + % recursive call + [FNi,Ci] = cat_io_struct2cell(C{ci}); + + % extend fieldnames + for FNii = 1:numel(FNi) + FNi{FNii} = sprintf('%s%s%s',FN{ci},separator,FNi{FNii}); + end + + % update fieldnames and cell if not empty + FN = [FN(1:ci-1); FNi; FN(ci+1:end)]; + if numel(Ci) > 0 + try + if size(C,1) > size(C,2) + C = [C(1:ci-1,:); Ci; C(ci+1:end,:)]; + else + C = [C(:,1:ci-1), Ci, C(:,ci+1:end)]; + end + end + end + end + end + +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_main_correctmyelination.m",".m","18025","401","function [Ym2,Ysrc2,Ycls,Ycor,cf] = cat_main_correctmyelination(Ym,Ysrc,Ycls,Yb,vx_vol,V,T3th,LASmyostr,Yy,cat12atlas,tpm,fname) +%cat_main_correctmyelination. Correction of GM myelination/artefacts. +% _________________________________________________________________________ +% This function perform high frequency correction in the GM ribbon. We +% expect a cortical ribbon of about 2-3 mm characterized by increased +% variance. A fast thickness estimation is used to dectect underestimated +% areas and have en estimate for the CSF distance. +% +% [Ym2,Ysrc2,Ycls,Ycor,glcor,cf] = cat_main_correctmyelination(... +% Ym,Ysrc,Ycls,Yb,vx_vol,vx_volo,T3th,LASmyostr,Yy,cat12atlas) +% +% Ym[2] .. intensity normalized image (0 BG, 1/3 CSF, 2/3 GM, 1 WM) +% Ysrc[2] .. bias corrected image with original intensity scaling +% Ycls .. tissue classes (uint8) +% Ycor .. correction map +% Yb .. brain mask +% vx_vol .. voxel volume (internal interpolated) +% vx_volo .. voxel volume (original) +% T3th .. tissue treshholds in Ysrc +% LASmyostr .. correction value +% Yy .. deformation map for atlas +% cat12atlas .. atlas map for cortex setting +% +% Called only from cat_main[#]. +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +% +% TODO: +% * test with PD/T2 weightings +% * tests with different distance estimation resolution +% * e +% . thickness setting should depend on brain size to support animal processing +% (currently only partially relevant as larger marmals also have 1-1.5 mm) + + dbs = dbstatus; debug = 0; for dbsi=1:numel(dbs), if strcmp(dbs(dbsi).name,mfilename); debug = 1; break; end; end + + if LASmyostr == 2 + GMV = single(sum(Ycls{1}(:)))/255 * prod(vx_vol) / 1000; + WMV = single(sum(Ycls{1}(:)))/255 * prod(vx_vol) / 1000; + LASmyostr = min(1,max(0,WMV / GMV - 1)); + end + + Yp0 = single(Ycls{3})/255/3 + single(Ycls{1})/255*2/3 + single(Ycls{2})/255; + + % To save time & memory operations are performed in a timmed subspace + % that is given by the brainmask. + if ~debug + [Ybb,BB] = cat_vol_resize( Yb , 'reduceBrain' , vx_vol , 3 , Yb ); + Ymb = cat_vol_resize( Ym , 'reduceBrain' , vx_vol , BB.BB ); + Yp0b = cat_vol_resize( Yp0 , 'reduceBrain' , vx_vol , BB.BB ); + Ycls1b = cat_vol_resize( Ycls{1} , 'reduceBrain' , vx_vol , BB.BB ); + Ycls2b = cat_vol_resize( Ycls{2} , 'reduceBrain' , vx_vol , BB.BB ); + else + Ybb = Yb; Ymb = Ym; Yp0b = Yp0; + Ycls1b = Ycls{1}; Ycls2b = Ycls{2}; + end + % dilated brainmask to correct possible artefacts + Ybb = cat_vol_morph(Ybb,'d',2); + + + + %% only work in the cortical areas + % ---------------------------------------------------------------------- + % structures without GM ribbon + % get some cortical ROIs to perform the corrections + TIV = sum(Yb(:) * prod(vx_vol)) / 1000; + drad = 0.3 * TIV^(1/3) / mean(vx_vol) ; + if exist('Yy','var') + % if we use an atlas ... + if exist('cat12atlas','var') + NS = @(Ys,s) Ys==s | Ys==s+1; % function to ignore brain hemisphere coding + LAB = cat_get_defaults('extopts.LAB'); + + % map atlas to RAW space + for i=1:5 + try + VA = spm_vol(cat12atlas{1}); + break + catch + % avoid read error in parallel processing + pause(rand(1)) + end + end + YA = cat_vol_ctype( cat_vol_sample(tpm(1),VA,Yy,0) ); + %YA = cat_vol_ctype(round(spm_sample_vol(VA,... + % double(Yy(:,:,:,1)),double(Yy(:,:,:,2)),double(Yy(:,:,:,3)),0))); + else + YA = Yy; + end + YA = reshape(YA,size(Yp0)); + YA = cat_vol_ctype(cat_vol_median3c(single(YA))); + + if ~debug + YA = cat_vol_resize( YA , 'reduceBrain' , vx_vol , BB.BB ); + end + + % extend atlas for all voxels within the brainmask + [D,I] = cat_vbdist(single(YA>0),Ybb); YA = YA(I); clear D I; %#ok + Yct = NS(YA,LAB.CT) & ~cat_vol_morph( NS(YA,LAB.VT) | NS(YA,LAB.LE) | NS(YA,LAB.HC) | NS(YA,LAB.PH) | NS(YA,LAB.BG) | NS(YA,LAB.TH), 'dd' ,drad); + else + % without atlas + YA = ones(size(Ybb),'single'); + Yvt = cat_vol_morph(cat_vol_morph(round(Yp0b*3)==1,'o',2/mean(vx_vol)),'d',2/mean(vx_vol)) & ... + cat_vol_morph(cat_vol_morph(round(Yp0b*3)==3,'o',2/mean(vx_vol)),'d',2/mean(vx_vol)); + Yct = Ybb & ~Yvt; + end + + + + % estimate variance maps to identify the GM and its variance + %Ysdg = cat_vol_localstat(max(1/3,Ymb),Ybb,round(3/mean(vx_vol)),4); % values at the border between CSF and WM have high values + %Ysdw = cat_vol_localstat(max(1/3,Ymb),Yp0b>2.8/3,round(2/mean(vx_vol)),4); % estimate average WM variance + %Ysdw = cat_vol_approx(Ysdw); + + + % gobal evaluation + % - thx: + % - rvth: relative volume threshold: 0 (no correction) to 1 (heavy correction) + % - gwp: gray-white matter proportion (>1 atypical) + for i=1:3, vol(i) = cat_stat_nansum( single( Ycls{i}(:) )/255 ) * prod(vx_vol) / 1000; end + LASmyo.volr = vol ./ sum(vol); + LASmyo.thx = min(2.2,3 - 4*LASmyo.volr(3)); + LASmyo.rvth = [ max(0,1/3 - LASmyo.volr(1)) max(0,LASmyo.volr(2) - 1/3)*3 max(0,1/3 - LASmyo.volr(3))*3 ]; + LASmyo.gwp = LASmyo.volr(2) ./ LASmyo.volr(1); % + % cortical evaluation (maybe not allways defined) + for i=1:3, ctvol(i) = cat_stat_nansum( single( Ycls{i}(Yct(:)) )/255 ) * prod(vx_vol) / 1000; end + LASmyo.ctvolr = ctvol ./ sum(ctvol); + LASmyo.ctthx = min(2.2,3 - 4*LASmyo.ctvolr(3)); + LASmyo.rctvth = max(0,[ 1/3 - LASmyo.ctvolr(1) , LASmyo.ctvolr(2) - 1/3 , 1/3 - LASmyo.ctvolr(3) ]) * 3; + LASmyo.ctgwp = LASmyo.ctvolr(2) ./ LASmyo.ctvolr(1); + + LASmyo.clsrmse = cat_stat_nanmean( (Yp0b(:) - Ymb(:)).^2 .* Ybb(:) .* (Yp0b(:)<1 & Yp0b(:)>1/3)).^.5; % only GM + LASmyo.noise = min( cat_stat_nanstd( Ymb( cat_vol_morph( Yp0b>2.5/3 & Ymb > 2.5/3,'e')) ), ... + cat_stat_nanstd( Ymb( cat_vol_morph( Yp0b<1.5/3 & Yp0b > 0.5/3,'e')) ) ); + + %LASmyo.ctf = LASmyo.rctvth(2) .* LASmyo.rctvth(3) .* LASmyo.ctgwp * 10; + LASmyo.ctf = min(2,sum(LASmyo.rctvth) .* LASmyo.ctgwp * 2); + + + + %% estimate GM and WM thickness + % ---------------------------------------------------------------------- + % This is just a fast approximation with many limitations! + % However, it should allow to detect problematic areas and roughly limit + % out corrections. + % ---------------------------------------------------------------------- + + % resampling for speed and equal voxel size + res = 1.2; % % simple reduce ... hmm, is this required / useful any longer ? - yes for high res denoising ... need testing - first simple + resi = 1; %0.5; % distance/thickness estimation resolution >> higher resolution would need further adaptations +%{ + [YA,redR] = cat_vol_resize(YA ,'reduceV',vx_vol,res,32,'nearest'); + Yp0b = cat_vol_resize(Yp0b,'reduceV',vx_vol,res,32,'meanm'); + Ymb = cat_vol_resize(Ymb ,'reduceV',vx_vol,res,32,'meanm'); + Ybb = cat_vol_resize(single(Ybb) ,'reduceV',vx_vol,res,32,'meanm'); + Yct = cat_vol_resize(single(Yct) ,'reduceV',vx_vol,res,32,'meanm'); + Ycls1b = cat_vol_resize(single(Ycls1b),'reduceV',vx_vol,res,32,'meanm'); + Ycls2b = cat_vol_resize(single(Ycls2b),'reduceV',vx_vol,res,32,'meanm'); +%} + [YA,resI] = cat_vol_resize(YA ,'interp',V,resi,'nearest'); + Yp0b = cat_vol_resize(Yp0b,'interp',V,resi,'linear'); + Ymb = cat_vol_resize(Ymb ,'interp',V,resi,'cubic'); + Ybb = cat_vol_resize(Ybb ,'interp',V,resi,'linear') > .5; + Yct = cat_vol_resize(Yct ,'interp',V,resi,'linear') > .5; + Ycls1b = cat_vol_resize(Ycls1b,'interp',V,resi,'linear') > .5; + Ycls2b = cat_vol_resize(Ycls2b,'interp',V,resi,'linear') > .5; + + + %% estimate ""blurred"" CSF (with sulcual overestimation) and WM distance + + % there are some regions we will ignore + Ydeepgm = NS(YA,LAB.VT) | NS(YA,LAB.BG) | NS(YA,LAB.TH) | NS(YA,LAB.HC); % | NS(YA,LAB.PH) + Ydeepgm = cat_vol_smooth3X( cat_vol_morph( Ydeepgm ,'dd',2,resI.resN) , 4); + + % first distance maps + Ycd = cat_vol_eudist(2-max(Yp0b,Ydeepgm)*3, Yct & Yp0b>1.5/3 & Yp0b<2.5/3, 2, 1); % overestimated in blurred sulci + Ywd = cat_vol_eudist(Ybb .* Yp0b .* 3 - 2 , Yct & Yp0b>1.5/3 & Yp0b<2.5/3, 2, 1); + + % estimate (filtered) thickness + Ygmt = cat_vol_pbtp(Yp0b * 3,Ywd,Ycd); + Ygmta = cat_vol_approx(Ygmt); Ygmt( abs(Ygmt - Ygmta ) > .5 ) = 0; clear Ygmta; + Ygmt = cat_vol_approx(Ygmt); + + % estimate ""real"" CSF distance by using the thickness and WM distance map as Ygmt = Ycd + Ywd + Ycdc = Ygmt - Ywd; Ycdc(Ycd0 & Yct & Yp0b>2.5/3) = 1; + + + %% re-estimate the CSF distance (this time also going deep in the WM) + % the limitation is useful as we only need local gyral information! + % and want to avoid bias by deep Wm + YdeepWM = cat_vol_morph(Ycls2b>.95,'de',5,resi); + Ycdc2 = cat_vol_eudist(smooth3(Ycdc<.5 & Ypp<.75 & ~Ydeepgm), Yct & ~YdeepWM, 2, 1); clear Ycdc + Ycdc2(Ycdc2 > 6 * resi) = 0; + + %% estimate the full tissue thickness (we needed the GM thickness and WM to reconstruct the sulcus) + Ybmt = cat_vol_pbtp( min(3,4-min(2,Yp0b*3)), Ycdc2, Ycdc2*inf); + Ybmt = cat_vol_approx(Ybmt); + + % estimate WM skeleleton distance map (to keep allways a central voxel) + Ywid = (Ybmt - Ycdc2); Ywid(Ywid>10 | Ycdc2==0) = 0; + + % size scaling + Ygmt = Ygmt*resi; Ybmt=Ybmt*resi; Ycdc2=Ycdc2*resi; Ywid=Ywid*resi; + + % eval + LASmyo.mnYgmt = cat_stat_nanmean(Ygmt(Ycls1b(:)>.5 & Yct(:))); + LASmyo.mnYbmt = cat_stat_nanmean(Ybmt(Ycls1b(:)>.5 & Yct(:))) - LASmyo.mnYgmt; + + %% define regions with clear GM, where we don't want to correct + Yisok = cat_vol_morph( cat_vol_morph(Ymb>1.5/3 & Ymb<2.5/3 ,'do',1,resI.resN),'dd',2,resI.resN) & Ymb>1.85/3 & Ymb<2.15/3 & ... + cat_vol_morph( Ymb<2.5/3 ,'dd',2,resI.resN) & Ymb<2.5 & Ywid>2; + Yisok = Yisok | (Ygmt>2.5 & Ycdc2>2.5 & Ymb>1.75/3 & Ymb<2.25/3) | (Ycdc2>3.5); + Yisok = smooth3(Yisok); + + %% avoid high intenisty (WM) edges + % define regions, where we want to correct + Ybd = cat_vbdist( single( ~( (Ycls1b + Ycls2b)>0.5 & cat_vol_morph(Ybb>.5,'e','3',resi) ) ) ); + Ybv = cat_vol_morph( (Ycls1b + Ycls2b)>0.5, 'd') & Ymb>2/3 & Ycdc2<2 & ~cat_vol_morph( (Ycls1b + Ycls2b)>0.5, 'e') & Yct & Ybd<5*resi; + Yisct = Yct & (Ywid>1 | Ybv) & Ydeepgm<.05 & (Ymb>1.5/3 | Yp0b>1.5/3) & ... + (( Ybmt>1 & (Ycdc2 <= Ybmt-1) & (Ycdc2 < max(.5,min(2.5,LASmyo.ctf * LASmyostr*2)))) | ( (Ybmt>1 | Ybv) & Ycdc2 < 1.5)); + Yisct = min(Yisct,cat_vol_smooth3X(Yisct,.6)); % not extend but soften! + %Yisct = max( 0, min( max(1.5, median(Ygmt(Yp0b(:)>1.5/3 & Yp0b(:)<2.5/3))) - Ycdc2/2 * LASmyo.ctf,Yisct)); + Ynpp = max(0,1 - Ycdc2./max(eps,min(median(Ygmt(:)),Ybmt))); Ynpp(Ycdc2==0)=0; Ynpp(Ybv) = 1; +% Yisct = Yisct .* smooth3(max(0,min(1,Ywid/2))); % only thick structures .5 + + Yisct = Yisct .* (1 - Yisok/2); % only critical structures + Yisct = Yisct .* cat_vol_smooth3X(Yct,4) .* (1 - Ydeepgm); % only neocortex + %Yisct = Yisct .* max(smooth3(Ywd+.5),Ybv) .* Ynpp .* (2.5/Ygmt) .* min(1,LASmyo.ctf * LASmyostr*2) .* smooth3(min(1,Ybmt-1 + Ybv*10)); % important to avoid overcorrections + Yisct = Yisct .* max(0,min(2,(Ybmt - Ygmt))) .* Ynpp .* smooth3(median(Ygmt(:))./Ygmt) .* min(1,LASmyo.ctf * LASmyostr) .* smooth3(min(1,Ybmt-1 + Ybv*10)); % important to avoid overcorrections + %Yisct = Yisct .* min(2 , smooth3( max(Ywd/2,Ybv) .* max(0.5,LASmyo.ctf) )); % .* Ynpp .* smooth3(min(1,Ybmt-1 + Ybv*10)); % important to avoid overcorrections + Ym2 = max( min(Ymb , min(2.25 ,Ymb )*0.25 + 0.75*(2.25 - 0.25 * LASmyostr) / 3 ) , Ymb - Yisct / 3 ); + + %% resample data to original space + Yct = cat_vol_resize(single(Yct),'deinterp' ,resI,'linear') > .5; + Yisct = cat_vol_resize(Yisct ,'deinterp' ,resI,'linear'); + %Yct = cat_vol_resize(Yct ,'dereduceV',redR,'linear') > .5; + %Yisct = cat_vol_resize(Yisct ,'dereduceV',redR,'linear'); + clear Yisok Ywid Ybmt Ygmt Ycdc2 Ydeepgm + + %% get back to the orinal space + if ~debug + Yct = cat_vol_resize( Yct , 'dereduceBrain' , BB ); + Yisct = cat_vol_resize( Yisct , 'dereduceBrain' , BB ); + else + Yclso = Ycls; + end + + %% update segmentation + Ygmo = single(Ycls{1}); + Ygm = cat_vol_ctype( single( Ycls{2}) .* Yisct); + Ycls{2} = Ycls{2} - Ygm; + Ycls{1} = Ycls{1} + Ygm; + Ygm = cat_vol_ctype( single( Ycls{3}) .* Yisct); + Ycls{3} = Ycls{3} - Ygm; + Ycls{1} = Ycls{1} + Ygm; + + + %% light bias correction + if LASmyostr > .125 + %% + Tth = [cat_stat_nanmedian( Ym(Ycls{1}(:)>128) ) cat_stat_nanmedian( Ym(Ycls{2}(:)>128) ) cat_stat_nanmedian( Ym(Ycls{3}(:)>128) )]; + Yw = ( ((Ycls{1}+Ycls{2}+Ycls{3})>128) .* Ym) ./ (single(Ycls{1})/255*Tth(1) + single(Ycls{2})/255*Tth(2) + single(Ycls{3})/255*Tth(3)); + Yw = Yw + (single(Ycls{6})>.5); + Yw = cat_vol_approx(Yw); + Yw = cat_vol_smooth3X(Yw,4); + Yw = Yw ./ cat_stat_nanmedian(Yw((Ycls{1}+Ycls{2}+Ycls{3})>128)); + Ym = Ym ./ Yw; + Ysrc = Ysrc ./ Yw; + + % additional intensity normalization + end + + %% final corrections + if 0 % not here ... here only BC LASmyostr >= .5 + Ym2 = max( min(Ym , min(2.25 ,Ym )*0.25 + 0.75*(2.25 - 0.25 * LASmyostr) / 3 ) , Ym - Yisct / 3 ); + Ysrc2 = max( min(Ysrc , min(T3th(2),Ysrc)*0.25 + 0.75*(T3th(3) - 0.5 * LASmyostr) / T3th(3) ) , ... + Ysrc - Yisct * diff(T3th(2:3)) * 3 * (diff(T3th(1:2)) / diff(T3th(2:3)) * 0.5) ); % under/over-correction for high/low contrast + else + Ym2 = Ym; + Ysrc2 = Ysrc; + end + Ycor = Yisct; + + + % eval + for i=1:3, volc(i) = cat_stat_nansum( single( Ycls{i}(:) )/255 ) * prod(vx_vol) / 1000; end + LASmyo.volcr = volc ./ sum(volc); + for i=1:3, volc(i) = cat_stat_nansum( single( Ycls{i}(Yct(:)) )/255 ) * prod(vx_vol) / 1000; end + LASmyo.volcr = volc ./ sum(volc); + LASmyo.change = mean( Ym( Yct(:) & Ym2(:)>1.5/3 & Ym2(:)<2.5/3 ) - Ym2( Yct(:) & Ym2(:)>1.5/3 & Ym2(:)<2.5/3 ) ) / prod(vx_vol) * 1000; + try + cat_io_write2csv(fname,'LASmyo',LASmyo); + end + + + % estiamte modification factor + cf = abs( sum(Ygm(:)) - sum(Ygmo(:)) ) / sum(Ygmo(:)); + + % display changes + if cat_get_defaults('extopts.verb') > 2 + if cf>0.04 || glcor>0.8 + cat_io_cprintf('warn' ,sprintf('\n Myelination correction of %0.2f%%%% of the GM volume (strength=%0.2f)! ', cf*100, glcor/3)); + elseif cf>0.02 || glcor>0.4 + cat_io_cprintf('note' ,sprintf('\n Myelination correction of %0.2f%%%% of the GM volume (strength=%0.2f). ', cf*100, glcor/3)); + else + cat_io_cprintf([0 0 0.5],sprintf('\n Myelination correction of %0.2f%%%% of the GM volume (strength=%0.2f). ', cf*100, glcor/3)); + end + + % display voluminas + for i=1:numel(Ycls), ppe.LASvols(i) = cat_stat_nansum(single(Ycls{i}(:)))/255 .* prod(vx_vol) / 1000; end + cat_io_cprintf('blue',sprintf('\n LAS volumes (CGW=TIV; in mm%s): %7.2f +%7.2f +%7.2f = %4.0f\n',... + native2unicode(179, 'latin1'),ppe.LASvols([3 1 2]),sum(ppe.LASvols(1:3)))); + + cat_io_cmd(' ',' ','',job.extopts.verb); + end +end +function Yd = cat_vol_eudist(Yb, Ymsk, levels, correctoffeset) +%cat_vol_eudist. Euclidean distance estimation to mixed boundaries. +% +% Yd = cat_vol_eudist(Yb, Ymsk, levels, correctoffeset) +% +% Yd .. distance map +% Yb .. boundary map (with PVE) +% Ymsk .. masked regions for distance estimation +% +% levels .. number of dual distance measurements +% optimimum between 2 and 4 +% correctoffeset .. use generalized correction for the additional distance +% estimations, eg., for a more WM like value of 2.75 all +% distance values are assumed to be over +% (0 - none, 1 - default difference, 2 - estimated difference) +% +% see also cat_vol_pbtsimple:cat_vol_cwdist +% + +% +% Todo: +% * Add voxel size? +% * Use as esternal function? +% + + if ~exist('Ymsk','var'), Ymsk = ~Yb; else, Ymsk = Ymsk>.5; end + if ~exist('hss','var') + levels = 4; + elseif levels < 0 + error('cat_vol_eudist:BadLevelValue','Levels must be larger equal 0.') + end + if ~exist('correctoffeset','var'), correctoffeset = 2; end + + % do not estimate the distance for NAN + Ymsk( isnan(Yb) | (isinf(Yb) & Yb<0) ) = 0; + + if levels == 0 + % simple single distance estimation + Yd = cat_vbdist(single(Yb > .5), Ymsk ); + else + + Yd = zeros(size(Yb),'single'); + for si = 1:levels + % estimate the offset of the boundary + offset = max(0,min(.5,si * .5/levels)) / 2; + + % estimate the distance to paired sublevels + Ydl = cat_vbdist(single(Yb > ( 0.5 - offset)), Ymsk ); + Ydh = cat_vbdist(single(Yb > ( 0.5 + offset)), Ymsk ); + + % correct for possible outliers + Ydl(Ydl>max(size(Yb))) = 0; + Ydh(Ydh>max(size(Yb))) = 0; + + % it is possible to correct for the theoretical offset by the + % voxel-wise partial volume effect if two pure tissues are mixed + % (typical tissue boundary vs. the myelinated regions) + if correctoffeset + if correctoffeset==2 + offsetc = cat_stat_nanmedian(Ydl(Ydl > 0) - Ydh(Ydl > 0))/2; + else + offsetc = offset; + end + Ydl(Ydl>0) = max(eps, Ydl(Ydl>0) - (.5 - offsetc )); + Ydh(Ydh>0) = max(eps, Ydh(Ydh>0) + (.5 - offsetc )); + end + + % add the distance from this level + Yd = Yd + .5/levels .* Ydl + .5/levels .* Ydh; + + end + + end + + % correct for possible outliers + Yd(Yd > max(size(Yb))) = 0; + +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_main_cleanup.m",".m","8498","159","function [Ycls,Yp0b] = cat_main_cleanup(Ycls,prob,Yl1b,Ymb,extopts,inv_weighting,vx_vol,indx,indy,indz,skullstripped) +% ----------------------------------------------------------------- +% final cleanup 2.0 +% +% First we need to describe our region of interest. Blood vessels and +% menignes occure in the sulci and next to the skull. Therefore we +% use the brainmask and the label map to identify special regions. +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + dbs = dbstatus; debug = 0; + for dbsi=1:numel(dbs), if strcmp(dbs(dbsi).name,'cat_main_cleanup'); debug = 1; break; end; end + if ~exist('skullstripped','var'), skullstripped = 0; end + + LAB = extopts.LAB; + vxv = 1/max(vx_vol); % use original voxel size!!! + NS = @(Ys,s) Ys==s | Ys==s+1; % remove side alignment from atlas maps + + cleanupstr = min(1,max(0,extopts.cleanupstr * 0.5/(inv_weighting+1) / max(1,mean(vx_vol)) )); + cleanupdist = min(2,max(0,1 + extopts.cleanupstr)); + + stimec = cat_io_cmd(sprintf('Final cleanup (gcutstr=%0.2f)',cleanupstr)); + fprintf('\n'); + stime = cat_io_cmd(' Level 1 cleanup (ROI estimation)','g5','',extopts.verb); %dispc=1; + + %% estimate the ROI + % ------------------------------------------------------------------ + % This part removes menignes next to the skull and between large + % structures. + % ------------------------------------------------------------------ + Yvt = cat_vol_morph(NS(Yl1b,LAB.VT) | NS(Yl1b,LAB.BG),'dd',vxv*3); % ventricle ... no cleanup here + Yp0 = single(prob(:,:,:,1))/255*2 + single(prob(:,:,:,2))/255*3 + single(prob(:,:,:,3))/255; + Ybd = cat_vbdist(single(~cat_vol_morph(Yp0>0,'ldc',vxv)),true(size(Yp0)),vx_vol); + Ybd = cat_vbdist(single(~cat_vol_morph(Yp0>1.5 | Ybd>8,'ldc',vxv)),true(size(Yp0)),vx_vol); + Ycbp = cat_vol_morph(NS(Yl1b,LAB.CB),'dd',cleanupdist*vxv); % next to the cerebellum + Ycbn = NS(Yl1b,LAB.CB); %cat_vol_morph(NS(Yl1b,LAB.CB),'de',min(1,0.2*cleanupdist*vxv)); % not to deep in the cerebellum + Ylhp = cat_vol_morph(Yl1b==1 & Yp0<2.1,'dd',cleanupdist*vxv*2); % GM next to the left hemisphere + Yrhp = cat_vol_morph(Yl1b==2 & Yp0<2.1,'dd',cleanupdist*vxv*2); % GM next to the righ hemishpere + Yroi = Ybd0 & Ybd<6 & cat_vol_morph( (Ylhp & Yrhp) | (~Ycbn & Ycbp & (Ylhp | Yrhp)),'dd',4); + Yroi = (Yroi | Yrbv) & ~NS(Yl1b,LAB.BS) & ~Ycbn; + % bv +% Ycd = cat_vbdist(single(Yp0>2.5 & Yl1b==LAB.CB),Ylhp & Yrhp,vx_vol); +% Ylhd = cat_vbdist(single(Yp0>2.5 & Yl1b==1),Ylhp & Yrhp,vx_vol); +% Yrhd = cat_vbdist(single(Yp0>2.5 & Yl1b==1),Ylhp & Yrhp,vx_vol); +% Ybvx = single(min(cat(4,Ylhd,Yrhd,Ycd),[],4)<8 & (min(cat(4,Ylhd,Yrhd,Ycd),[],4))>3 & Ybd<5 & Ymb>0.3); +% Ywm = single(smooth3(Yp0>2)>0.5); Ybvx(Ymb<0.67 | Yp0==0)=nan; +% Ywm = cat_vol_downcut(Ywm,Ymb,0.1); +% Ybvx(smooth3(Ybvx)<0.7)=0; Ybvx(smooth3(Ybvx)<0.5)=0; Ybvx(Ywm & Ybvx==0)=2; Ybvx(Yp0==0)=nan; +% Ybvx = cat_vol_downcut(Ybvx,Ymb,0.05); + + if ~debug, clear Ycbp Ycbn Ylhp; end + + %% roi to change GM or WM to CSF or background + stime = cat_io_cmd(' Level 1 cleanup (brain masking)','g5','',extopts.verb,stime); %dispc=dispc+1; + Yrw = Yp0>0 & Yroi & Ymb>1.1+Ybd/20 & ~NS(Yl1b,LAB.CB); % basic region with cerebellum + Yrw = Yrw | smooth3(Yrw)>0.4-0.3*cleanupstr; % dilate region + Ygw = cat_vol_morph(Yp0>=1.9 & ~Yrw,'ldo',0); % even one is too much in adrophic brains :/ + Yrw = Yrw | (Yp0>1 & Yroi & ~Ygw); % further dilation + Yrw = Yrw & ~Yvt & ~cat_vol_morph(Ygw,'dd',1.5); + Yrw(smooth3(Yrw)<0.5+0.2*cleanupstr)=0; + Yrw(smooth3(Yrw)<0.5-0.2*cleanupstr)=0; % only larger objects + if ~debug, clear Ygw Yroi; end + + %% update brain masks and class maps + if ~skullstripped + % RD202306: canceled to avoid skull-stripping variance - we just keep the old brainmask + % RD202311: reactivated as the brain mask was less good in ADNI tests + Ybb = cat_vol_morph((Yp0>0 & ~Yrw) | Ybd>2,'ldo',2/vxv); + Ybb(cat_vol_smooth3X(Ybb,2)>0.4 & ~Yrw)=1; + Ybb = cat_vol_morph(Ybb | Ybd>3,'ldc',1/vxv); + Ybb = single(Ybb); spm_smooth(Ybb,Ybb,0.6./vx_vol); Ybb = Ybb>1/3; + else + Ybb = Yp0>0; + end + + %% correct to background + for i=1:3, prob(:,:,:,i)=min(prob(:,:,:,i),uint8(Ybb*255)); end + % correct to CSF + prob(:,:,:,1)=min(prob(:,:,:,1),uint8(~(Ybb & Yrw)*255)); + prob(:,:,:,2)=min(prob(:,:,:,2),uint8(~(Ybb & Yrw)*255)); + prob(:,:,:,3)=max(prob(:,:,:,3),uint8( (Ybb & Yrw)*255)); + if ~debug, clear Yrw; end + + + %% cleanup of meninges + % ------------------------------------------------------------------ + % This removes meninges next to the brain... works quite well. + clear Yrg Yrw Yroi + stime = cat_io_cmd(' Level 2 cleanup (CSF correction)','g5','',extopts.verb,stime); %dispc=dispc+1; + Yp0 = single(prob(:,:,:,1))/255*2 + single(prob(:,:,:,2))/255*3 + single(prob(:,:,:,3))/255; + YM = single(cat_vol_morph((prob(:,:,:,1) + prob(:,:,:,2))>(160 + 32*cleanupstr) & ... + ~cat_vol_morph(Yp0>1 & Yp0<1.5+cleanupstr/2,'do',vxv) ,'l')); + YM2 = cat_vol_morph(YM,'do',min(1,0.7/max(vx_vol))); + YM(NS(Yl1b,1) & YM2==0)=0; + spm_smooth(YM,YM,0.6./vx_vol); % anisotropic smoothing! + YM = ( (YM<0.1*cleanupstr) ) & Ybb & ~Yvt & Ymb>0.25; + prob(:,:,:,1)=min(prob(:,:,:,1),uint8(~YM*255)); + prob(:,:,:,2)=min(prob(:,:,:,2),uint8(~YM*255)); + prob(:,:,:,3)=max(prob(:,:,:,3),uint8( (YM | (Ybb & Yp0==0))*255)); + if debug, Yp0 = single(prob(:,:,:,1))/255*2 + single(prob(:,:,:,2))/255*3 + single(prob(:,:,:,3))/255; end %#ok + + + + %% cleanup WM + % ------------------------------------------------------------------ + % the idea was to close WMH ... but its not stable enough yet + %{ + Ywmh = false(size(Yp0)); + for p0thi=2.1:0.2:2.9 + Ywmh = Ywmh | ~cat_vol_morph(Yp00.1 & NS(Yl1b,1) & Yp0>=2 & Yp0<3; + Yl1b(Ywmh) = LAB.HI + ~mod(Yl1b(Ywmh),2); + clear Ywmh; + %} + % correction later depending on WMHC + + + +%% + % ------------------------------------------------------------------ + % cleanup in regions with PVE between WM and CSF without GM + % ------------------------------------------------------------------ + stime = cat_io_cmd(' Level 3 cleanup (CSF/WM PVE)','g5','',extopts.verb,stime); %dispc=dispc+1; + Yp0 = single(prob(:,:,:,1))/255*2 + single(prob(:,:,:,2))/255*3 + single(prob(:,:,:,3))/255; + Ybs = NS(Yl1b,LAB.BS) & Ymb>2/3; + YpveVB = cat_vol_morph(NS(Yl1b,LAB.VT) | Ybs,'dd',2); % ventricle and brainstem + YpveCC = cat_vol_morph(Yl1b==1,'dd',3*vxv) & cat_vol_morph(Yl1b==2,'dd',3*vxv) & ... + cat_vol_morph(NS(Yl1b,LAB.VT),'dd',2); % corpus callosum + Ynpve = smooth3(NS(Yl1b,LAB.BG) | NS(Yl1b,LAB.TH))>0.3; % no subcortical structure + Yroi = (YpveVB | YpveCC) & ~Ynpve & ... + cat_vol_morph(Yp0==3,'dd',2*vxv) & cat_vol_morph(Yp0==1,'dd',2*vxv) & ... + Yp0<3 & Yp0>1 & ... + smooth3((Yp0<3 & Yp0>1) & ~cat_vol_morph(Yp0<3 & Yp0>1,'do',1.5*vxv))>0.1; + clear YpveVB YpveCC Ybs Ynpve; + Yncm = (3-Yp0)/2.*Yroi; + + for i=1:3, Ycls{i}=zeros(size(Ycls{i}),'uint8'); end + Ycls{1}(indx,indy,indz) = min(prob(:,:,:,1),uint8(~Yroi*255)); + Ycls{2}(indx,indy,indz) = cat_vol_ctype(single(prob(:,:,:,2)).*~Yroi + (Yroi - Yncm)*255,'uint8'); + Ycls{3}(indx,indy,indz) = cat_vol_ctype(single(prob(:,:,:,3)).*~Yroi + Yncm*255,'uint8'); + + Yp0b = cat_vol_ctype(single(Ycls{1})*2/3 + single(Ycls{2}) + single(Ycls{3})*1/3,'uint8'); + Yp0b = Yp0b(indx,indy,indz); + + cat_io_cmd(' ','','',extopts.verb,stime); + fprintf('%5.0fs\n',etime(clock,stimec)); +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_update.m",".m","6704","194","function varargout = cat_update(update) +% check for new CAT updates +% +% FORMAT [sts, msg] = cat_update(update) +% sts - status code: +% NaN - server not accessible +% Inf - no updates available +% 0 - CAT installation up-to-date +% n - new revision is available for download +% msg - string describing outcome, that would otherwise be displayed. +% update - allow installation of update +% +% This function will connect to the SBM server, compare the +% version number of the updates with the one of the CAT12 installation +% currently in the MATLAB path and will display the result. +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +rev = '$Rev$'; + +if isdeployed + sts= Inf; + msg = 'Update function is not working for compiled CAT12. Please check for a new compiled CAT12 version.'; + if ~nargout, fprintf([blanks(9) msg '\n']); + else varargout = {sts, msg}; end + return; +end + +% Github release url +url_github = 'https://api.github.com/repos/ChristianGaser/cat12/releases'; + +if ~nargin + update = false; +else + update = true; +end + +% get current release +r = cat_version; +r = str2double(strrep(r,'CAT','')); + +% get new release +try + [jsonStr, sts] = urlread(url_github,'Timeout',2); +catch + [jsonStr, sts] = urlread(url_github); +end + +if ~sts + msg = sprintf('Cannot access %s. Please check your proxy and/or firewall to allow access.\nYou can download your update at %s\n',url,url); + if ~nargout, fprintf(msg); else varargout = {NaN, msg}; end + return +end + +data = jsondecode(jsonStr); +% get largest release number +rnew = []; +for i = 1:length(data) + rnew = [rnew str2double(data(i).tag_name)]; +end +rnew = max(rnew); + +if rnew > r + sts = rnew; + msg = sprintf(' A new version of CAT12 is available on:\n'); + msg = [msg sprintf(' %s\n',url_github)]; + msg = [msg sprintf(' (Your version: %g - New version: %g)\n',r,rnew)]; + if ~nargout, fprintf(msg); else varargout = {sts, msg}; end +else + sts = 0; + msg = sprintf('Your version of CAT12 is up-to-date.'); + if ~nargout, fprintf([blanks(9) msg '\n']); + else varargout = {sts, msg}; end + return +end + +url = sprintf('https://github.com/ChristianGaser/cat12/releases/download/%g/cat%g.zip',rnew,rnew); + +if update + overwrite = spm_input(sprintf('Update to %g',rnew),1,'m','yes|no|download only',[1 -1 0],1); + d0 = spm('Dir'); + d = fileparts(fileparts(which('cat12'))); + + if overwrite + try + % list mex-files and delete these files to prevent that old + % compiled files are used + mexfiles = dir(fullfile(fileparts(mfilename('fullpath')),'*.mex*')); + for i=1:length(mexfiles) + name = fullfile(fileparts(mfilename('fullpath')),mexfiles(i).name); + spm_unlink(name); + end + + % delete old html folder + htmldir = fullfile(fileparts(mfilename('fullpath')),'html'); + if exist(htmldir,'dir'), rmdir(htmldir, 's'); end + + % delete old CAT12 manual + pdffile = fullfile(fileparts(mfilename('fullpath')),'CAT12-Manual.pdf'); + spm_unlink(pdffile); + + % delete old atlas files + atlasfiles = dir(fullfile(fileparts(mfilename('fullpath')),'atlases_surfaces','*.*')); + for i=1:length(atlasfiles) + name = fullfile(fileparts(mfilename('fullpath')),'atlases_surfaces',atlasfiles(i).name); + spm_unlink(name); + end + + % delete old atlas files with 32k meshes + atlasfiles = dir(fullfile(fileparts(mfilename('fullpath')),'atlases_surfaces_32k','*.*')); + for i=1:length(atlasfiles) + name = fullfile(fileparts(mfilename('fullpath')),'atlases_surfaces_32k',atlasfiles(i).name); + spm_unlink(name); + end + + % delete old surface template files + templatefiles = dir(fullfile(fileparts(mfilename('fullpath')),'templates_surfaces','*.*')); + for i=1:length(templatefiles) + name = fullfile(fileparts(mfilename('fullpath')),'templates_surfaces',templatefiles(i).name); + spm_unlink(name); + end + + % delete old surface template files with 32k meshes + templatefiles = dir(fullfile(fileparts(mfilename('fullpath')),'templates_surfaces_32k','*.*')); + for i=1:length(templatefiles) + name = fullfile(fileparts(mfilename('fullpath')),'templates_surfaces_32k',templatefiles(i).name); + spm_unlink(name); + end + + % delete old volume template files + templatefiles = dir(fullfile(fileparts(mfilename('fullpath')),'templates_MNI152NLin2009cAsym','*.*')); + for i=1:length(templatefiles) + name = fullfile(fileparts(mfilename('fullpath')),'templates_volumes',templatefiles(i).name); + spm_unlink(name); + end + + templatefiles = dir(fullfile(cat_get_defaults('extopts.pth_templates'),'*.*')); + for i=1:length(templatefiles) + name = fullfile(fileparts(mfilename('fullpath')),'templates_volumes',templatefiles(i).name); + spm_unlink(name); + end + + lastwarn(''); + warning off + delete(get(0,'Children')); spm('clean'); evalc('spm_rmpath'); drawnow + m = ' Download and install CAT12...\n'; + if ~nargout, fprintf(m); else varargout = {sts, [msg m]}; end + + s = unzip(url, d); + m = sprintf(' Success: %d files have been updated.\n',numel(s)); + if ~nargout, fprintf(m); else varargout = {sts, [msg m]}; end + addpath(d0); + rehash; + rehash toolboxcache; + if exist('toolbox_path_cache','file'), toolbox_path_cache; end + spm fmri; clear cat_version; spm_cat12 + warning on + catch + le = lasterror; + switch le.identifier + case 'MATLAB:checkfilename:urlwriteError' + fprintf(' Update failed: cannot download update file.\n'); + otherwise + fprintf('\n%s\n',le.message); + end + end + + % open version information if difference between release numbers + % is large enough + if rnew > r+20 + web(fullfile(fileparts(mfilename('fullpath')),'doc','index.html#version')); + end + + [warnmsg, msgid] = lastwarn; + switch msgid + case 'MATLAB:extractArchive:unableToCreate' + fprintf(' Update failed: check folder permission.\n'); + case 'MATLAB:extractArchive:unableToOverwrite' + fprintf(' Update failed: check file permissions.\n'); + otherwise + fprintf(' Warning %s.\n',warnmsg); + end + elseif overwrite == 0 + web(url,'-browser'); + fprintf('Unzip file to %s\n',d); + end +end +","MATLAB" +"Neurology","ChristianGaser/cat12","Bayes.c",".c","8541","305","/* ______________________________________________________________________ + * + * Christian Gaser, Robert Dahnke + * Structural Brain Mapping Group (https://neuro-jena.github.io) + * Departments of Neurology and Psychiatry + * Jena University Hospital + * ______________________________________________________________________ + * $Id$ + */ + +#include +#include +#include +#include ""Amap.h"" + +/* use always 6 classes */ +#define Kb 6 +#define MAXK 30 + +#ifndef isfinite +#define isfinite(x) ((x) * (x) >= 0.) /* check for NaNs */ +#endif + +smooth_subsample_double(double *vol, int dims[3], double separations[3], double s[3], int use_mask, int samp); +void WarpPriors(unsigned char *prob, unsigned char *priors, float *flow, int *dims, int loop, int loop_start, int samp); + +void Bayes(double *src, unsigned char *label, unsigned char *priors, unsigned char *prob, double *separations, int *dims, int correct_nu) +{ + int i, j, k, l, k1, subit, n_loops, subsample_warp, kmax, k2; + int z_area, y_dims, count, subsample, masked_smoothing; + double ll = -HUGE, llr=0.0, *nu, fwhm[3]; + double mn[MAXK], vr[MAXK], mg[MAXK], mn2[MAXK], vr2[MAXK], mg2[MAXK]; + double mom0[MAXK], mom1[MAXK], mom2[MAXK], mgm[MAXK]; + double q[MAXK], bt[MAXK], b[MAXK], qt[MAXK]; + double tol1 = 1e-3, bias_fwhm, sum, sq, qmax, s, psum, p1, oll, val_nu; + float *flow; + + int area = dims[0]*dims[1]; + int vol = area*dims[2]; + int K = 0, K2 = 0; + + /* multiple gaussians are not yet working */ + int ngauss[6] = {1,1,1,1,1,1}; + int iters_EM[5] = {2, 10, 10, 10, 10}; + + int histo[65536], lkp[MAXK]; + double mn_thresh, mx_thresh; + double min_src = HUGE, max_src = -HUGE; + int cumsum[65536], order_priors[6] = {2,0,1,3,4,5}; + + subsample_warp = ROUND(9.0/(separations[0]+separations[1]+separations[2])); + + flow = (float *)malloc(sizeof(float)*vol*3); + /* initialize flow field with zeros */ + for (i = 0; i < (vol*3); i++) flow[i] = 0.0; + + if (correct_nu) nu = (double *)malloc(sizeof(double)*vol); + + bias_fwhm = 60.0; + if (correct_nu) { + /* use larger filter */ + for(i=0; i<3; i++) fwhm[i] = 2*bias_fwhm; + + /* estimate mean */ + count = 0; sum = 0.0; + for (i = 0; i < vol; i++) { + if(src[i]>0) { + sum += src[i]; + count++; + } + } + + if (count==0) return; + + sum /= (double)count; + + + for (i = 0; i < vol; i++) { + if(src[i]>0) + nu[i] = src[i] - sum; + else nu[i] = 0; + } + + /* use subsampling for faster processing */ + subsample = 2; + masked_smoothing = 1; + smooth_subsample_double(nu, dims, separations, fwhm, masked_smoothing, subsample); + + /* and correct bias */ + for (i = 0; i < vol; i++) + if(src[i]>0) + src[i] -= nu[i]; + + } + + for (i=0; i= 1) break; + mn_thresh = (double)i/65535.0*(max_src-min_src); + for (i = 65535; i > 0; i--) if (cumsum[i] <= 999) break; + mx_thresh = (double)i/65535.0*(max_src-min_src); + + /* K = sum(ngauss) */ + for (k1=0; k1mn_thresh) && (src[i] qmax) { + qmax = q[k]; + if (k>K2-1) kmax = 0; else kmax = k + 1; + } + } + + /* prepare prob for warping */ + sq = TINY; + for (k1=0; k10)) WarpPriors(prob, priors, flow, dims, 6, 0, subsample_warp); + + for (k=0; k mn_thresh) && (label[i] < 4)) { + val_nu = src[i]-mn[label[i]-1]; + if (isfinite(val_nu)) + nu[i] = val_nu; + } + } + + /* smoothing of residuals */ + for(i=0; i<3; i++) fwhm[i] = bias_fwhm; + + /* use subsampling for faster processing */ + subsample = 2; + masked_smoothing = 0; + + smooth_subsample_double(nu, dims, separations, fwhm, masked_smoothing, subsample); + + /* apply nu correction to source image */ + for (i=0; i 0.0) + src[i] -= nu[i]; + } + } + } + + for (i=0; i qmax) { + qmax = p1; + kmax = k1 + 1; + } + } + /* label only if sum of all probabilities is > 0 */ + if (psum > 0) + label[i] = kmax; + else + label[i] = 0; + } else label[i] = 0; + } + +/* for (k=0; k 50 + cat_plot_boxplot(roi_values',struct('names',rev,'violin',0,'showdata',1,'outliers',0)); + elseif abs(max(roi_values(:))) > 2 + cat_plot_boxplot(roi_values',struct('names',rev,'violin',0,'showdata',1,'outliers',0,'ylim',[-1 1])); + else + cat_plot_boxplot(roi_values',struct('names',rev,'violin',0,'showdata',1,'outliers',0,'ylim',[-.2 .2])); + end + pos = get(gcf,'Position'); + pos(3:4) = [1000 500]; + set(gcf,'MenuBar','none','Name',name,'Position',pos) + title('Neuromorphometric atlas: Difference to mean [ml]') + saveas(gcf,[name '.png']); + +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_vol_ROIval.c",".c","5733","203","/* function [mn,std,min,max,sum,n,median?] = cat_vol_ROIval(Ya,Yv) + * _____________________________________________________________________ + * Estimation of mean, standard deviation, minimum, maximum, sum, number + * and median (not yet implemented) of Yv in a ROI described by Ya. + * + * Example: + * 1) + * A = rand(50,50,3,'single'); + * for i=1:size(A,2), A(:,i,:) = A(:,i,:) + (( i/size(A,2) ) - 0.5); end + * L = zeros(size(A),'single'); L(round(numel(L)*0.367))=1; + * L(round(numel(L)*0.533))=2; L(round(numel(L)*0.616))=3; + * [D,I] = cat_vbdist(L); L=L(I); L = uint8(round(L)); + * [MN,STD,MIN,MAX,SM,N,MD] = cat_vol_ROIval(A,L); + * ______________________________________________________________________ + * + * Christian Gaser, Robert Dahnke + * Structural Brain Mapping Group (https://neuro-jena.github.io) + * Departments of Neurology and Psychiatry + * Jena University Hospital + * ______________________________________________________________________ + * $Id$ + */ + +#include ""mex.h"" +#include ""math.h"" +#include ""float.h"" + +#ifndef isnan +#define isnan(a) ((a)!=(a)) +#endif +#ifdef _MSC_VER + #define FINFINITY (FLT_MAX+FLT_MAX); + static const unsigned long __nan[2] = {0xffffffff, 0x7fffffff}; + #define FNAN (*(const float *) __nan) +#else + #define FINFINITY 1.0f/0.0f; + #define FNAN 0.0f/0.0f +#endif + + +/* qicksort for median */ +/* +void swap(float *a, float *b) +{ + float t=*a; *a=*b; *b=t; +} + +void sort(float arr[], int beg, int end) +{ + if (end > beg + 1) + { + float piv = arr[beg]; + int l = beg + 1, r = end; + while (l < r) + { + if (arr[l] <= piv) + l++; + else + swap(&arr[l], &arr[--r]); + } + swap(&arr[--l], &arr[beg]); + sort(arr, beg, l); + sort(arr, r, end); + } +} +*/ + +void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) +{ + /* main input handling */ + if (nrhs!=2) + mexErrMsgTxt(""ERROR:cat_vol_ROIval: requires 2 maps. A 3d uint8 atlas map and a single value map.\n""); + if (mxIsUint8(prhs[0])==0 || mxGetNumberOfDimensions(prhs[0])!=3 ) + mexErrMsgTxt(""ERROR:cat_vol_ROIval: 1st input must be an 3d uint8 matrix.\n""); + if (mxIsSingle(prhs[1])==0 || mxGetNumberOfDimensions(prhs[0])!=3 ) + mexErrMsgTxt(""ERROR:cat_vol_ROIval: 2nd input must be an 3d single matrix.\n""); + + /* main information about input data (size, dimensions, ...) */ + const unsigned int n = mxGetNumberOfElements(prhs[0]); + const unsigned int n1 = mxGetNumberOfElements(prhs[1]); + const mwSize *sL0 = mxGetDimensions(prhs[0]); + const mwSize *sL1 = mxGetDimensions(prhs[0]); + if (n!=n1 || sL0[0]!=sL1[0] || sL0[1]!=sL1[1] || sL0[2]!=sL1[2]) + mexErrMsgTxt(""ERROR:cat_vol_ROIval: 1nd and 2nd input must have the same size.\n""); + + /* input data */ + const unsigned char *Ya = (unsigned char *) mxGetPr(prhs[0]); + const float *Yv = (float *) mxGetPr(prhs[1]); + + unsigned int ti, tii, maxYa=0, maxYa2=0; + + + for (int i=0;i=0) { + rn[id] = rn[id] + 1; + rsum[id] = rsum[id] + Yv[i]; + if (rmax[id]Yv[i]) + rmin[id] = Yv[i]; + } + } + + return; + /* correct minimum and maximum for empty ROIs */ + for (int id=0;id0) + rmn[id] = rsum[id] / rn[id]; + else + rmn[id] = FNAN; + } + + /* standard deviation */ + for (int i=0;i=0 & rn[Ya[i]]>0) { + rstd[id] += powf(Yv[i]-rmn[Ya[i]-1],2); + } + } + for (int id=0;id1) + rstd[id] = sqrtf( 1.0 / (rn[id] - 1.0) * rstd[id]); + else { + if (rn[id]==1) + rstd[id] = 1.0; + else + rstd[id] = FNAN; + } + } + + /* median */ + /* + for (id=0;id2) { + + ti=0; + for (i=0;i0 && id==(Ya[i]-1) && ti<16777216) { + Yt[ti] = 1; //Yv[i]; + ti++; + } + } + //printf(""%d-%d-%f\n"",ti,(int) rn[id],Yt[ti]); + //for (tii=0;tii n_subj) + subj_col = cl(1); + n_samples = max(xX.I(:,subj_col)); + + else + if ~isempty(xX.iH) + n_samples = length(xX.iH); + [rw,cl] = find(xX.I == length(xX.iH)); + elseif ~isempty(xX.iC) + n_samples = length(xX.iC); + [rw,cl] = find(xX.I == length(xX.iC)); + else + error('Design cannot be recognized.') + end + end + + % always use last found column + cl = max(cl); + + for i=1:numel(VY) + if ~exist(char(VY(i).fname),'file') + fprintf('Error: File %s could not be found.\nPlease check that data or analysis have not moved.\n',char(VY(i).fname)); + return + end + end + + % select data for each sample + job_check_zscore.data = cell(n_samples,1); + for i=1:n_samples + ind = find(xX.I(:,cl)==i); + job_check_zscore.data{i} = char(VY(ind).fname); + end + + % don't use parameter files for quality measures + job_check_zscore.data_xml = ''; + + % adjust data using whole design matrix + if adjust_data && repeated_anova % Don't adjust data for long. designs + fprintf('Disable adjustment for longitudinal data.\n'); + job_check_zscore.c = []; + elseif adjust_data % adjust using design matrix + job_check_zscore.c{1} = SPM.xX.X; + fprintf('Data are adjusted using design matrix.\n'); + else % Don't adjust data + job_check_zscore.c = []; + end + + % check for global scaling + if ~all(SPM.xGX.gSF==1) + job_check_zscore.gSF = SPM.xGX.gSF; + end + + % batch mode + if nargin > 0 && isfield(job.check_SPM_zscore.do_check_zscore,'save') + job_check_zscore.fname = job.check_SPM_zscore.do_check_zscore.fname; + job_check_zscore.outdir = job.check_SPM_zscore.do_check_zscore.outdir; + job_check_zscore.save = job.check_SPM_zscore.do_check_zscore.save; + end + + % use external defined window + job_check_zscore.new_fig = true; + + % also rescue facatorial design + job_check_zscore.factorial_design = job; + + % rescue mask information + if isfield(SPM,'xM') + job_check_zscore.xM = SPM.xM; + end + + % call old homogeneity check for long. data if long. design was found + repeated_anova = ~isempty(SPM.xX.iB); + if repeated_anova + cat_stat_check_cov_old(job_check_zscore); + else + cat_stat_homogeneity(job_check_zscore); + end +end + +if check_ortho + fprintf('\n-------------------------------------------\n'); + fprintf(' Check design orthogonality\n'); + fprintf('-------------------------------------------\n'); + try + h = check_orthogonality(SPM.xX); + catch + fprintf('ERROR: spm_DesRep cannot be called\n'); + end + + if nargin > 0 && isfield(job.check_SPM_zscore,'do_check_zscore') && isfield(job.check_SPM_zscore.do_check_zscore,'save') + %% + if ~isempty(job.check_SPM_zscore.do_check_zscore.fname) + dpi = cat_get_defaults('print.dpi'); + if isempty(dpi), dpi = 150; end + + if isempty(job.check_SPM_zscore.do_check_zscore.outdir{1}), job.check_SPM_zscore.do_check_zscore.outdir{1} = pwd; end + + % save + warning('OFF','MATLAB:print:UIControlsScaled'); + fname = fullfile(job.check_SPM_zscore.do_check_zscore.outdir{1},[job.check_SPM_zscore.do_check_zscore.fname 'DesignOrthogonality.png']); + try, print(h, '-dpng', '-opengl', sprintf('-r%d',dpi), fname); end + warning('ON','MATLAB:print:UIControlsScaled'); + end + + + if job.check_SPM_zscore.do_check_zscore.save>1 + close(h) + end + end +end + +%--------------------------------------------------------------- + +function h = check_orthogonality(varargin) +% modified function desorth from spm_DesRep.m for checking design orthogonality + +if ~isstruct(varargin{1}) + error('design matrix structure required') +else + xX = varargin{1}; +end + +%-Locate DesMtx (X), scaled DesMtx (nX) & get parameter names (Xnames) +%-------------------------------------------------------------------------- +if isfield(xX,'xKXs') && ~isempty(xX.xKXs) && isstruct(xX.xKXs) + X = xX.xKXs.X; +elseif isfield(xX,'X') && ~isempty(xX.X) + X = xX.X; +else + error('Can''t find DesMtx in this structure!') +end + +[nScan,nPar] = size(X); + +%-Add a scaled design matrix to the design data structure +%-------------------------------------------------------------------------- +if ~isfield(xX,'nKX') + xX.nKX = spm_DesMtx('Sca',xX.X,xX.name); +end + +if isfield(xX,'nKX') && ~isempty(xX.nKX) + inX = 1; else inX = 0; end + +if isfield(xX,'name') && ~isempty(xX.name) + Xnames = xX.name; else Xnames = {}; end + +%-Compute design orthogonality matrix +%-------------------------------------------------------------------------- +% columns with covariates and nuisance parameters must be mean corrected +% to reliably estimate orthogonality +X(:,[xX.iC xX.iG]) = X(:,[xX.iC xX.iG]) - repmat(mean(X(:,[xX.iC xX.iG])), nScan, 1); + +tmp = sqrt(sum(X.^2)); +O = X'*X./kron(tmp',tmp); +tmp = sum(X); +tmp = abs(tmp) 1 + fprintf(' and group factors.\n'); + else fprintf('\n'); end + fprintf('Orthogonality between nuisance parameters and parameters of interest should be carefully checked for high (absolute) values that point to co-linearity (correlation) between these variables.\n'); + fprintf('In case of such a high co-linearity nuisance parameters should be preferably used with global scaling (optionally with AnCova instead of proportional scaling).\n'); + fprintf('For more information please check the manual or the online help.\n\n'); + end + + for i=1:size(ind_ortho,2) + for j=1:size(ind_ortho,2) + if bC(ind_ortho(i),ind_ortho(i)) & i>j + rectangle('Position', [ind_ortho(i)-0.5 ind_ortho(j)-0.5 1 1],... + 'EdgeColor','r'); + fprintf('Orthogonality between %s and %s:\t %g\n',xX.name{ind_ortho(i)},... + xX.name{ind_ortho(j)},O(ind_ortho(i),ind_ortho(j))); + end + end + end +end + +set(hDesO,'Box','off','TickDir','out',... + 'XaxisLocation','top','XTick',PTick,'XTickLabel','',... + 'YaxisLocation','right','YTick',PTick,'YTickLabel','',... + 'YDir','reverse') +tmp = [1,1]'*[[0:nPar]+0.5]; +line('Xdata',tmp(1:end-1)','Ydata',tmp(2:end)') + +xlabel('design orthogonality') +set(get(hDesO,'Xlabel'),'Position',[0.5,nPar,0],... + 'HorizontalAlignment','left',... + 'VerticalAlignment','top') +set(hDesOIm,... + 'UserData',struct('O',O,'bC',bC,'Xnames',{Xnames}),... + 'ButtonDownFcn','spm_DesRep(''SurfDesO_CB'')') + +if ~isempty(Xnames) + axes('Position',[.69 .18 0.01 .2],'Visible','off',... + 'DefaultTextFontSize',FS+1,... + 'DefaultTextInterpreter','TeX',... + 'YDir','reverse','YLim',[0,nPar]+0.5) + for i=PTick + text(0,i,Xnames{i},'HorizontalAlignment','left') + end +end + + +%-Design descriptions +%-------------------------------------------------------------------------- +str = ''; +%line('Parent',hTax,... +% 'XData',[0.3 0.7],'YData',[0.16 0.16],'LineWidth',3,'Color','r') +hAx = axes('Position',[0.03,0.08,0.94,0.08],'Visible','off'); +xs = struct('Measure', ['abs. value of cosine of angle between ',... + 'columns of design matrix'],... + 'Scale', {{ 'black - colinear (cos=+1/-1)';... + 'white - orthogonal (cos=0)';... + 'gray - not orthogonal or colinear'}}); + +set(hAx,'Units','Pixel'); +AxPos = get(hAx,'Position'); +set(hAx,'YLim',[0,AxPos(4)]) + +dy = FS; y0 = floor(AxPos(4)) -dy; y = y0; + +text(0.3,y,str,... + 'HorizontalAlignment','Center',... + 'FontWeight','Bold','FontSize',FS+2) +y=y-2*dy; + +for sf = fieldnames(xs)' + text(0.3,y,[strrep(sf{1},'_',' '),' :'],... + 'HorizontalAlignment','Right','FontWeight','Bold',... + 'FontSize',FS) + s = xs.(sf{1}); + if ~iscellstr(s), s={s}; end + for i=1:numel(s) + text(0.31,y,s{i},'FontSize',FS) + y=y-dy; + end +end + +colormap(gray) + + +%--------------------------------------------------------------- + +function xX = correct_xX(xX) + +% vector of covariates and nuisance variables +iCG = [xX.iC xX.iG]; +iHB = [xX.iH xX.iB]; + +% set columns with covariates and nuisance variables to zero +X = xX.X; +X(:,iCG) = 0; + +ncol = size(X,2); + +% calculate sum of columns +% The idea behind this is that for each factor the sum of all of its columns should be ""1"". +Xsum = zeros(size(X)); +for i=1:ncol + % only sum up columns without covariates and nuisance variables + if isempty(find(iCG==i)) + Xsum(:,i) = sum(X(:,1:i),2); + end +end + +% find columns where all entries are constant except zeros entries +% that indicate columns with covariates and nuisance variables +ind = find(any(diff(Xsum))==0 & sum(Xsum)>0); + +% no more than 2 factors expected +if length(ind) > 2 + error('Weird design was found that cannot be analyzed correctly.'); +end + +% correction is only necessary if 2 factors (iH/iB) were found +if length(ind) > 1 + iF = cell(length(ind),1); + + j = 1; + % skip columns with covariates and nuisance variables + while find(iCG==j), j = j + 1; end + + for i=j:length(ind) + iF{i} = [j:ind(i)]; + + j = ind(i)+1; + % skip columns with covariates and nuisance variables + while find(iCG==j), j = j + 1; end + end + + % not sure whether this will always work but usually iB (subject effects) should be larger than iH (time effects) +% if length(iF{1}) > length(iF{2}) +if 0 % will be probably not always correct + xX.iB = iF{1}; + xX.iH = iF{2}; + else + xX.iB = iF{2}; + xX.iH = iF{1}; + end +end +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_vol_addtruecolourimage.m",".m","2655","96","function cat_vol_addtruecolourimage(P,cmap) +% ______________________________________________________________________ +% Function to show overlays of images either as multiple views or for +% up to 3 overlay images as RGB view +% +% Input: +% P - char array of 2..12 filenames +% cmap - colourmap for overlay (default jet) +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + % transparency + prop = 0.2; + RGBstr = {'R','G','B'}; + + if nargin < 1 + P = spm_select([2 12],'image','Select anatomical image and image(s) to overlay',... + {fullfile(spm('dir'),'toolbox','cat12','templates_MNI152NLin2009cAsym','Template_T1.nii')}); + elseif ~ischar(P) + P = spm_select([2 12],'image','Select anatomical image and image(s) to overlay'); + end + + V = spm_vol(P); + n = numel(V); + rgb_overlay = 0; + spm_orthviews('Reset'); + + if n > 2 && n < 5 + rgb_overlay = spm_input('Overlay',1,'m','Single RGB overlay|Multiple overlays',[true false], 1); + end + + if rgb_overlay + cmap = [((1:64)/64)' zeros(64,2)]; + elseif ~exist('cmap','var') + cmap = jet(64); + end + + if nargin < 2 + if ~rgb_overlay + cmap = spm_input('Colourmap',1,'e','jet'); + end + end + + if rgb_overlay || n == 2 + spm_check_registration(deblank(P(1,:))); + else + spm_check_registration(repmat(deblank(P(1,:)),n-1,1)); + end + + + for i=2:n + if rgb_overlay + if i==3, cmap = [zeros(64,1) ((1:64)/64)' zeros(64,1)]; end + if i==4, cmap = [zeros(64,2) ((1:64)/64)']; end + handle = 1; + else + handle = i - 1; + end + [mn,mx] = mn_mx_val(V(i)); + if (mn < 0) && (mx/mn > -100) + mn = min([-mn mx]); + mx = mn; + mn = -mn; + end + + spm_orthviews('addtruecolourimage',handle,deblank(P(i,:)),cmap,prop,mx,mn); + + [pp,nam] = spm_fileparts(deblank(P(i,:))); + if ~rgb_overlay + spm_orthviews('Caption',i-1,{nam},'FontSize',12,'FontWeight','Bold'); + else + fprintf('%s: %s\n',RGBstr{i-1},nam) + end + end + + spm_orthviews('redraw'); +end + +%_______________________________________________________________________ +function [mn,mx] = mn_mx_val(vol) + mn = Inf; + mx = -Inf; + for i=1:vol.dim(3) + tmp = spm_slice_vol(vol,spm_matrix([0 0 i]),vol.dim(1:2),0); + imx = max(tmp(isfinite(tmp))); + if ~isempty(imx),mx = max(mx,imx);end + imn = min(tmp(isfinite(tmp))); + if ~isempty(imn),mn = min(mn,imn);end + end +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_vol_pbtv.cpp",".cpp","19356","470","/* Project-based volume (PBT) estiamtion + * _____________________________________________________________________________ + * + * This function use the WM distance WMD to define a successor relation + * ship in the cortex. + * + * [GMT,LV,RPM,LVc] = cat_vol_(SEG,WMD,CSFD) + * + * SEG = (single) segment image with low and high boundary bd + * WMD = (single) CSF distance map + * CSFD = (single) CSF distance map + * + * GMT = (single) thickness image + * RPM = (single) radial position map (equi-dist) + * LV = (single) lower volume map that descibe the ""volumetric + * distance"" rather than the distance + * LVc = (single) count the number of successors of a voxel + * + * ______________________________________________________________________ + * + * Christian Gaser, Robert Dahnke + * Structural Brain Mapping Group (https://neuro-jena.github.io) + * Departments of Neurology and Psychiatry + * Jena University Hospital + * ______________________________________________________________________ + * $Id$ + */ + +#include ""mex.h"" +#include ""math.h"" +#include + +/* some options */ +struct opt_type { + int CSFD; /* use CSFD */ + int PVE; /* 0, 1=fast, 2=exact */ + float LB, HB, LLB, HLB, LHB, HHB; /* boundary */ + int sL[3]; + } opt; + + +/* Function to estimate if neighbor *i are successor of *I given by the WM + * distance (WMDi and WMDI). Successors are neighbors of *I that have a + * specificly larger WM distance than the voxel itself, which is defined + * by the a1 and a2 boundary variables with 0 < a1 < 1 < a2 < 2. Small a1 + * and large a2 increase the amount of voxels that are defined as successor + * and create smoother results. + * Furthermore, it is expectd that the voxel *I and its successors *i should + * be in the GM ( projection range: round(SEGI)==2 and round(SEGi)==2 ). + * Moreover, we expect that the intensity of the successors *i are lighly + * smaller that of *I. + */ +bool issuccessor(float SEGi, float SEGI, float WMDi, float WMDI, float NDi, + float a1, float a2, float a3) { + return ( ( SEGi > 1.5 && SEGi <= 2.5 ) && /* projection range - from (1.2 - 2.75) */ + ( SEGI > 1.5 && SEGI <= 2.5 ) && /* projection range - to (1.5 - 2.75) */ + ( ( ( WMDi - NDi * a2 ) <= WMDI ) ) && /* upper boundary - maximum distance */ + ( ( ( WMDi - NDi * a1 ) > WMDI ) ) && /* lower boundary - minimum distance - corrected values outside */ + ( ( ( SEGI - SEGi ) < a3 ) || SEGI>1.8 ) ); /* SEGi should be not to much higher than SEGI */ + //( ( ( SEGI - SEGi ) > (-a3 - (SEGi-1.5)/3 ) && // SEGi should be not to much higher than SEGI +} +bool isprecessor(float SEGi, float SEGI, float WMDi, float WMDI, float NDi, + float a1, float a2, float a3) { + return ( ( SEGi > 1.5 && SEGi <= 2.5 ) && /* projection range - from (1.2 - 2.75) */ + ( SEGI > 1.5 && SEGI <= 2.5 ) && /* projection range - to (1.5 - 2.75) */ + ( ( ( WMDI - NDi * a2 ) <= WMDi ) ) && /* upper boundary - maximum distance */ + ( ( ( WMDI - NDi * a1 ) > WMDi ) ) ); /* lower boundary - minimum distance - corrected values outside */ + // ( ( ( SEGi - SEGI ) < a3 ) || SEGi>1.8 ) ); /* SEGi should be not to much higher than SEGI */ + //( ( ( SEGi - SEGI ) > (-a3 - (SEGI-1.5)/3 ) && +} +bool isneighbor(float SEGi, float SEGI, float WMDi, float WMDI, float NDi, + float a1, float a2, float a3) { + return ( ( SEGi > 1.5 && SEGi <= 2.5 ) && /* projection range - from (1.2 - 2.75) */ + ( SEGI > 1.5 && SEGI <= 2.5 ) && /* projection range - to (1.5 - 2.75) */ + ( fabs( WMDi - WMDI ) <= a1 ) && /* upper boundary - maximum distance */ + ( fabs( SEGi - SEGI ) <= a3 ) ); /* SEGi should be not to much higher than SEGI */ +} + + + +/* Find all successor voxels *i of a voxel *I to map the average thickness + * of the successors to *I. + */ +bool issuccessormax(float GMTi, float SEGi, float SEGI, + float WMDi, float NDi, float WMDI, + float a1, float a2, float a3, float maximum) { + return ( ( GMTi < 1e15 ) && //( maximum < GMTi ) && /* thickness/WMD of neighbors should be larger */ + ( SEGi > 1.5 && SEGi <= 2.5 ) && /* projection range - from (1.2 - 2.75) */ + ( SEGI > 1.5 && SEGI <= 2.5 ) && /* projection range - to (1.5 - 2.75) */ + ( ( ( WMDi - NDi * a2 ) <= WMDI ) ) && /* upper boundary - maximum distance */ + ( ( ( WMDi - NDi * a1 ) > WMDI ) ) && /* lower boundary - minimum distance - corrected values outside */ + ( ( ( SEGI - SEGi ) < a3 ) || SEGI>1.8 ) ); /* SEGi should be not to much higher than SEGI */ + //( ( ( SEGI - SEGi ) > (-a3 - (SEGi-1.5)/3 ) && /* SEGi should be not to much higher than SEGI */ +} + + +float pmax2(const float GMT[], const float WMD[], const float SEG[], const float ND[], + const float WMDI, const float CSFD, const float SEGI, const int sA) { + + float a1 = 0.5; // lower boundary (lower values with include more voxels as successor) 0.6 + float a2 = 1.5; // upper boundary (higher values with include more voxels as successor) 1.3 + float a3 = 0.1; // minimum intensitiy difference between voxels (higher more successor) + + float m2n=1.0, maximum = WMDI; + for (int i=0;i<=sA;i++) { + if ( (SEGI>SEG[i]+0.05) && issuccessor(SEG[i], SEGI, WMD[i], WMDI, ND[i], a1, a2, a3) ) { + maximum = maximum + GMT[i]; m2n++; + } + } + return maximum / m2n; +} + +/* Find all successor voxels *i of a voxel *I to map the average thickness + * of the successors to *I. + */ +float pmax(const float GMT[], const float WMD[], const float SEG[], const float ND[], + const float WMDI, const float CSFD, const float SEGI, const int sA) { //, float & maximum) { + + float T[27]; for (int i=0;i<27;i++) T[i]=-1; float n=0.0; + float maximum = WMDI; + + float a1 = 0.5; // lower boundary (lower values with include more voxels as successor) 0.6 + float a2 = 1.5; // upper boundary (higher values with include more voxels as successor) 1.3 + float a3 = 0.2; // minimum intensitiy difference between voxels (higher more successor) + + /* estiamte the maximum of sibblings */ + /* project volume values and count the siblings */ + for (int i=0;i<=sA;i++) { + if ( issuccessormax(GMT[i], SEG[i], SEGI, WMD[i], ND[i], WMDI, a1, a2, a3, maximum) ) { + maximum = GMT[i]; + } + } + /* use the shortest distance between WM and CSF */ + maximum = fmin( maximum , WMDI + CSFD); + + /* the mean of the highest values of the siblings */ + float maximum2=maximum; float m2n=0.0; + for (int i=0;i<=sA;i++) { + if ( issuccessormax(GMT[i], SEG[i], SEGI, WMD[i], ND[i], WMDI, a1, a2, a3, maximum) ) { + maximum2 = maximum2 + GMT[i]; m2n++; + } + } + if ( m2n > 0 ) maximum = (maximum2 - maximum) / m2n; + return maximum; +} + + + +/* Estimate x,y,z position of index i in an array of size sx, sxy=sx*sy. + * C index value 0,..,n-1 is used here rather than MATLAB index 1,..,n ! + */ +void ind2sub(int i, int *x, int *y, int *z, int snL, int sxy, int sy) { + /* not here ... + * if (i<0) i=0; + * if (i>=snL) i=snL-1; + */ + + *z = (int)floor( (double)i / (double)sxy ) ; + i = i % (sxy); + *y = (int)floor( (double)i / (double)sy ) ; + *x = i % sy ; +} + + + +/* main function */ +void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { + if (nrhs<3) mexErrMsgTxt(""ERROR: not enought input elements\n""); + if (nrhs>4) mexErrMsgTxt(""ERROR: to many input elements.\n""); + if (nlhs>6) mexErrMsgTxt(""ERROR: to many output elements.\n""); + if (mxIsSingle(prhs[0])==0) mexErrMsgTxt(""ERROR: first input must be an 3d single matrix\n""); + + + /* main information about input data (size, dimensions, ...) */ + const mwSize *sL = mxGetDimensions(prhs[0]); + mwSize sSEG[] = {sL[0],sL[1],sL[2]}; + const int dL = mxGetNumberOfDimensions(prhs[0]); + const int nL = mxGetNumberOfElements(prhs[0]); + const int x = sL[0]; + const int y = sL[1]; + const int xy = x*y; + const float s2 = sqrt(2.0); + const float s3 = sqrt(3.0); + const int nr = nrhs; + + /* indices of the neighbor Ni (index distance) and euclidean distance NW */ + const int NI[] = { 0, -1,-x+1, -x,-x-1, -xy+1,-xy,-xy-1, -xy+x+1,-xy+x,-xy+x-1, -xy-x+1,-xy-x,-xy-x-1}; + const float ND[] = {0.0,1.0, s2,1.0, s2, s2,1.0, s2, s3, s2, s3, s3, s2, s3}; + const int sN = sizeof(NI)/4; + float DN[sN],DI[sN],GMTN[sN],WMDN[sN],SEGN[sN],DNm,VOLN[sN],LVm; + float*VOLc[sN]; + + float du, dv, dw, dnu, dnv, dnw, d, dcf, WMu, WMv, WMw, GMu, GMv, GMw, SEGl, SEGu, tmpfloat; + int mi,ni,u,v,w,nu,nv,nw, tmpint, WMC=0, CSFC=0; + + /* main volumes - actual without memory optimation ... */ + plhs[0] = mxCreateNumericArray(dL,sL,mxSINGLE_CLASS,mxREAL); + plhs[1] = mxCreateNumericArray(dL,sL,mxSINGLE_CLASS,mxREAL); + plhs[2] = mxCreateNumericArray(dL,sL,mxSINGLE_CLASS,mxREAL); + plhs[3] = mxCreateNumericArray(dL,sL,mxSINGLE_CLASS,mxREAL); + plhs[4] = mxCreateNumericArray(dL,sL,mxSINGLE_CLASS,mxREAL); + plhs[5] = mxCreateNumericArray(dL,sL,mxSINGLE_CLASS,mxREAL); + + /* input variables */ + float*SEG = (float *)mxGetPr(prhs[0]); + float*WMD = (float *)mxGetPr(prhs[1]); + float*CSFD = (float *)mxGetPr(prhs[2]); + + /* dynamic input did not work >> used hard code */ + /*if ( nrhs>1) { + tmpint = (int)mxGetScalar(mxGetField(prhs[1],1,""CSFD"")); printf(""X=%d"", tmpint); if ( tmpint!=NULL && (tmpint>=0 && tmpint<=1) ) opt.CSFD = tmpint; else opt.CSFD = 1; + tmpint = (int)mxGetScalar(mxGetField(prhs[1],1,""PVE"")); printf(""X=%d"", tmpint); if ( tmpint!=NULL && (tmpint>=0 && tmpint<=2) ) opt.PVE = tmpint; else opt.PVE = 2; + tmpfloat = (float)mxGetScalar(mxGetField(prhs[1],1,""LB"")); printf(""X=%d"", tmpfloat); if ( tmpfloat!=NULL ) opt.LB = tmpfloat; else opt.LB = 1.5; + tmpfloat = (float)mxGetScalar(mxGetField(prhs[1],1,""HB"")); printf(""X=%d"", tmpfloat); if ( tmpfloat!=NULL ) opt.HB = tmpfloat; else opt.HB = 2.5; + } + else */{ opt.CSFD = 1;opt.PVE = 2;opt.LB = 1.5;opt.HB = 2.5; } + opt.LLB=floor(opt.LB), opt.HLB=ceil(opt.LB), opt.LHB=floor(opt.HB), opt.HHB=ceil(opt.HB); + + /* output variables */ + float *GMT = (float *)mxGetPr(plhs[0]); + float *LV = (float *)mxGetPr(plhs[1]); /* volume sum from CSF boundary */ + float *UV = (float *)mxGetPr(plhs[2]); /* volume sum from CSF boundary */ + float *RPM = (float *)mxGetPr(plhs[3]); + float *LVc = (float *)mxGetPr(plhs[4]); /* volume sum counter */ + float *UVc = (float *)mxGetPr(plhs[5]); /* volume sum counter */ + + + /* intitialisiation */ + for (int i=0;i=opt.LB && SEG[i]<=opt.HB); + UVc[i] = LVc[i]; + /* proof distance input */ + if ( SEG[i]>=opt.HB ) WMC++; + if ( SEG[i]<=opt.LB ) CSFC++; + } + if (WMC==0) mexErrMsgTxt(""ERROR: no WM voxel\n""); + if (CSFC==0) opt.CSFD = 0; + + + + /* estimate successor and precessor weighting */ + float a1 = 0.1; // lower boundary (lower values with include more voxels as successor) 0.6 + float a2 = 2.5; // upper boundary (higher values with include more voxels as successor) 1.3 + float a3 = 0.5; // minimum intensitiy difference between voxels (higher more successor) + for (int i=0;iopt.LLB && SEG[i]=nL) || (abs(nu-u)>1) || (abs(nv-v)>1) || (abs(nw-w)>1)) ni=i; + + LVc[i] = LVc[i] + (float)(issuccessor(SEG[ni], SEG[i], WMD[ni], WMD[i], ND[n], a1, a2, a3)); + UVc[i] = UVc[i] + (float)(isprecessor(SEG[ni], SEG[i], WMD[ni], WMD[i], ND[n], a1, a2, a3)); + } + } + } + } + + + + /* volume mapping - CSF to WM */ + int ip; + for (int di=0;di<2;di++) { + if (di==0) ip = 1; else ip = -1; + for (int i=di*(nL-1);i>=0 && iopt.LLB && SEG[i]=nL) || (abs(nu-u)>1) || (abs(nv-v)>1) || (abs(nw-w)>1)) ni=i; + + if ( issuccessor(SEG[ni], SEG[i], WMD[ni], WMD[i], ND[n], a1, a2, a3) ) + LV[i] = LV[i] + LV[ni] / fmax(1,UVc[ni]); + if ( isprecessor(SEG[ni], SEG[i], WMD[ni], WMD[i], ND[n], a1, a2, a3) ) + UV[i] = UV[i] + UV[ni] / fmax(1,LVc[ni]); + } + } + } + } + /* smoothing */ + float nlc, nuc, rpd; + for (int dic=0;dic<4;dic++) { + for (int di=0;di<2;di++) { + if (di==0) ip = 1; else ip = -1; + for (int i=di*(nL-1);i>=0 && iopt.LLB && SEG[i]=nL) || (abs(nu-u)>1) || (abs(nv-v)>1) || (abs(nw-w)>1)) ni=i; + + if ( isneighbor(SEG[ni], SEG[i], WMD[ni], WMD[i], ND[n], 0.4, a2, 0.2) && + (LV[i]/(LV[i] + UV[i]))>0.1 && (UV[i]/(LV[i] + UV[i]))>0.1 ) { + + rpd = fmax(0,1 - fabs( LV[i]/(LV[i] + UV[i]) - LV[ni]/(LV[ni] + UV[ni]) * 4))*0.5; + rpd += fmax(0,1 - fabs( SEG[i] - SEG[ni] ) * 10)*0.5; + + if (rpd>0) { + LV[i] = LV[i] + LV[ni]*rpd; + nlc += rpd; + } + rpd = fmax(0,1 - fabs( UV[i]/(LV[i] + UV[i]) - UV[ni]/(LV[ni] + UV[ni]) * 4))*0.5; + rpd += fmax(0,1 - fabs( SEG[i] - SEG[ni] ) * 10)*0.5; + if ( rpd>0 ) { + UV[i] = UV[i] + UV[ni]*rpd; + nuc += rpd; + } + } + } + LV[i] = LV[i] / nlc; + UV[i] = UV[i] / nuc; + } + } + } + } + + + + /* WMD correction */ + for (int i=0;i 2.0 ) && ( UVc[i] < 20.0 ) && ( LVc[i] > UVc[i] ) && + ( LV[i] > 6.0 ) && ( UV[i] < 2.0 ) && ( LV[i] > UV[i] ) && + ( SEG[i] > 1.9 ) && ( SEG[i] < 2.5 ) ) + WMD[i] = 0.5; + } + for (int di=0;di<2;di++) { + if (di==0) ip = 1; else ip = -1; + for (int i=di*(nL-1);i>=0 && i0 && SEG[i]<2.5) { + ind2sub(i,&u,&v,&w,nL,xy,x); + + /* read neighbor values + * - why didn't you used pointers? + * - why not adding the neighbor loop to the subfunction? + * > create an addition function + * > prepare convertation to C + */ + for (int n=0;n=nL) || (abs(nu-u)>1) || (abs(nv-v)>1) || (abs(nw-w)>1)) ni=i; + if ( ( WMD[ni]>=0.4 ) && ( WMD[i]>=1 ) && ( WMD[i] > WMD[ni] + ND[n]) && + ( SEG[ni]<2.5 ) && ( SEG[ni]>1.5 ) && ( SEG[i]<=SEG[ni]+0.2 ) ) + WMD[i] = WMD[ni] + ND[n]; + } + } + } + } + + + + // printf(""Thickness mapping\n""); + /* Thickness mapping */ + /* ============================================================================= */ +if ( 0 ) { + /* new shorter version that did not run correctly*/ + for (int di=0;di<2;di++) { + if (di==0) ip = 1; else ip = -1; + for (int i=di*(nL-1);i>=0 && iopt.LLB && SEG[i] create an addition function + * > prepare convertation to C + */ + for (int n=0;n=nL) || (abs(nu-u)>1) || (abs(nv-v)>1) || (abs(nw-w)>1)) ni=i; + GMTN[n] = GMT[ni]; WMDN[n] = RPM[ni]; SEGN[n] = SEG[ni]; + } + + // find minimum distance within the neighborhood - forward + if ( di == 0) + GMT[i] = pmax2(GMTN,WMDN,SEGN,ND,WMD[i],CSFD[i],SEG[i],sN); + else { + DNm = pmax2(GMTN,WMDN,SEGN,ND,WMD[i],CSFD[i],SEG[i],sN); + if ( GMT[i] < DNm && DNm>0 ) GMT[i] = DNm; + } + } + } + } +} +else { + /* old long code version that works */ + for (int i=0;iopt.LLB && SEG[i] create an addition function + * > prepare convertation to C + */ + for (int n=0;n=nL) || (abs(nu-u)>1) || (abs(nv-v)>1) || (abs(nw-w)>1)) ni=i; + GMTN[n] = GMT[ni]; WMDN[n] = RPM[ni]; SEGN[n] = SEG[ni]; + } + + /* find minimum distance within the neighborhood - forward */ + + GMT[i] = pmax(GMTN,WMDN,SEGN,ND,WMD[i],CSFD[i],SEG[i],sN); + } + } + + for (int i=nL-1;i>=0;i--) { + if (SEG[i]>opt.LLB && SEG[i]=nL) || (abs(nu-u)>1) || (abs(nv-v)>1) || (abs(nw-w)>1)) ni=i; + GMTN[n] = GMT[ni]; WMDN[n] = RPM[ni]; SEGN[n] = SEG[ni]; + } + + /* find minimum distance within the neighborhood - backward */ + DNm = pmax(GMTN,WMDN,SEGN,ND,WMD[i],CSFD[i],SEG[i],sN); + if ( GMT[i] < DNm && DNm>0 ) GMT[i] = DNm; + } + } +} + + /* final GMT settings */ + for (int i=0;iopt.LB) + GMT[i] = 0; + else + GMT[i] = fmin( GMT[i], CSFD[i] + WMD[i] ); + } + + + + /* estimate RPM */ + for (int i=0;iopt.HB ) + RPM[i]=1.0; + else { + if ( SEG[i]1.0) RPM[i]=1.0; + if (RPM[i]<0.0) RPM[i]=0.0; + } + } + } + +} + + +","C++" +"Neurology","ChristianGaser/cat12","sanlm_float.c",".c","24785","810","/* ______________________________________________________________________ + * + * Christian Gaser, Robert Dahnke + * Structural Brain Mapping Group (https://neuro-jena.github.io) + * Departments of Neurology and Psychiatry + * Jena University Hospital + * ______________________________________________________________________ + * + * $Id$ + * + * + * This code is a modified version of MABONLM3D.c + * Jose V. Manjon - jmanjon@fis.upv.es + * Pierrick Coupe - pierrick.coupe@gmail.com + * Brain Imaging Center, Montreal Neurological Institute. + * Mc Gill University + * + * Copyright (C) 2010 Jose V. Manjon and Pierrick Coupe + + *************************************************************************** + * Adaptive Non-Local Means Denoising of MR Images * + * With Spatially Varying Noise Levels * + * * + * Jose V. Manjon, Pierrick Coupe, Luis Marti-Bonmati, * + * D. Louis Collins and Montserrat Robles * + *************************************************************************** + * + * Details on SANLM filter + *************************************************************************** + * The SANLM filter is described in: * + * * + * Jose V. Manjon, Pierrick Coupe, Luis Marti-Bonmati, Montserrat Robles * + * and D. Louis Collins. * + * Adaptive Non-Local Means Denoising of MR Images with Spatially Varying * + * Noise Levels. Journal of Magnetic Resonance Imaging, 31,192-203, 2010. * + * * + ***************************************************************************/ + +#include +#include +#include +#include + +#ifdef MATLAB_MEX_FILE +#include +#endif + +/* Multithreading stuff*/ +#if defined(_WIN32) || defined(_WIN64) +#include +#include +#else +#include +#endif + +#define PI 3.1415926535 + +typedef struct{ + int rows; + int cols; + int slices; + float* in_image; + float* means_image; + float* var_image; + float* estimate; + float* bias; + unsigned char* label; + int ini; + int fin; + int radioB; + int radioS; +} myargument; + +int rician; +double max; + +#if !defined(_WIN32) && !defined(_WIN64) +pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; +#endif + +/* Returns the modified Bessel function I0(x) for any real x. */ +double bessi0(double x) +{ + double ax,ans,a; + double y; + if ((ax = fabs(x)) < 3.75) + { + y = x/3.75; + y *= y; + ans = 1.0+y*(3.5156229+y*(3.0899424+y*(1.2067492+y*(0.2659732+y*(0.360768e-1+y*0.45813e-2))))); + } + else + { + y = 3.75/ax; + ans = (exp(ax)/sqrt(ax)); + a = y*(0.916281e-2+y*(-0.2057706e-1+y*(0.2635537e-1+y*(-0.1647633e-1+y*0.392377e-2)))); + ans = ans*(0.39894228 + y*(0.1328592e-1 +y*(0.225319e-2+y*(-0.157565e-2+a)))); + } + return ans; +} + +/* Returns the modified Bessel function I1(x) for any real x. */ +double bessi1(double x) +{ + double ax,ans; + double y; + if ((ax = fabs(x)) < 3.75) + { + y = x/3.75; + y *= y; + ans = ax*(0.5+y*(0.87890594+y*(0.51498869+y*(0.15084934+y*(0.2658733e-1+y*(0.301532e-2+y*0.32411e-3)))))); + } + else + { + y = 3.75/ax; + ans = 0.2282967e-1+y*(-0.2895312e-1+y*(0.1787654e-1-y*0.420059e-2)); + ans = 0.39894228+y*(-0.3988024e-1+y*(-0.362018e-2+y*(0.163801e-2+y*(-0.1031555e-1+y*ans)))); + ans *= (exp(ax)/sqrt(ax)); + } + return x < 0.0 ? -ans : ans; +} + +double Epsi(double snr) +{ + double val; + val = 2 + snr*snr - (PI/8)*exp(-(snr*snr)/2)*((2+snr*snr)*bessi0((snr*snr)/4) + + (snr*snr)*bessi1((snr*snr)/4))*((2+snr*snr)*bessi0((snr*snr)/4) + (snr*snr)*bessi1((snr*snr)/4)); + if (val<0.001) val = 1; + if (val>10) val = 1; + return val; +} + +/* Function which compute the weighted average for one block */ +void Average_block(float *ima,int x,int y,int z,int neighborhoodsize,float *average,double weight,int sx,int sy,int sz) +{ + int x_pos,y_pos,z_pos; + int is_outside; + int a,b,c,ns,sxy,index; + + extern int rician; + + ns = 2*neighborhoodsize+1; + sxy = sx*sy; + + for (c = 0; c sz-1)) is_outside = 1; + if ((y_pos < 0) || (y_pos > sy-1)) is_outside = 1; + if ((x_pos < 0) || (x_pos > sx-1)) is_outside = 1; + + index = a + ns*b + ns*ns*c; + + if (rician) + { + if (is_outside) + average[index] += ima[z*(sxy)+(y*sx)+x]*ima[z*(sxy)+(y*sx)+x]*(float)weight; + else average[index] += ima[z_pos*(sxy)+(y_pos*sx)+x_pos]*ima[z_pos*(sxy)+(y_pos*sx)+x_pos]*(float)weight; + } + else + { + if (is_outside) + average[index] += ima[z*(sxy)+(y*sx)+x]*(float)weight; + else average[index] += ima[z_pos*(sxy)+(y_pos*sx)+x_pos]*(float)weight; + } + } + } + } +} + +/* Function which computes the value assigned to each voxel */ +void Value_block(float *Estimate, unsigned char *Label,int x,int y,int z,int neighborhoodsize,float *average,double global_sum,int sx,int sy,int sz) +{ + int x_pos,y_pos,z_pos; + int is_outside; + double value = 0.0; + unsigned char label = 0; + int count = 0 ; + int a,b,c,ns,sxy; + + ns = 2*neighborhoodsize+1; + sxy = sx*sy; + + for (c = 0; c sz-1)) is_outside = 1; + if ((y_pos < 0) || (y_pos > sy-1)) is_outside = 1; + if ((x_pos < 0) || (x_pos > sx-1)) is_outside = 1; + + if (!is_outside) + { + value = (double)Estimate[z_pos*(sxy)+(y_pos*sx)+x_pos]; + value += ((double)average[count]/global_sum); + + label = Label[(x_pos + y_pos*sx + z_pos*sxy)]; + Estimate[z_pos*(sxy)+(y_pos*sx)+x_pos] = (float)value; + Label[(x_pos + y_pos*sx + z_pos *sxy)] = label + 1; + } + count++; + } + } + } +} + +double distance(float* ima,int x,int y,int z,int nx,int ny,int nz,int f,int sx,int sy,int sz) +{ + double d,acu,distancetotal; + int i,j,k,ni1,nj1,ni2,nj2,nk1,nk2; + + distancetotal = 0; + for (k = -f; k <= f; k++) + { + nk1 = z+k; + nk2 = nz+k; + if (nk1<0) nk1 = -nk1; + if (nk2<0) nk2 = -nk2; + if (nk1>= sz) nk1 = 2*sz-nk1-1; + if (nk2>= sz) nk2 = 2*sz-nk2-1; + + for (j = -f; j <= f; j++) + { + nj1 = y+j; + nj2 = ny+j; + if (nj1<0) nj1 = -nj1; + if (nj2<0) nj2 = -nj2; + if (nj1>= sy) nj1 = 2*sy-nj1-1; + if (nj2>= sy) nj2 = 2*sy-nj2-1; + + for (i = -f; i<= f; i++) + { + ni1 = x+i; + ni2 = nx+i; + if (ni1<0) ni1 = -ni1; + if (ni2<0) ni2 = -ni2; + if (ni1>= sx) ni1 = 2*sx-ni1-1; + if (ni2>= sx) ni2 = 2*sx-ni2-1; + + d = ((double)ima[nk1*(sx*sy)+(nj1*sx)+ni1]-(double)ima[nk2*(sx*sy)+(nj2*sx)+ni2]); + distancetotal += d*d; + } + } + } + + acu = (2*f+1)*(2*f+1)*(2*f+1); + d = distancetotal/acu; + + return d; +} + +double distance2(float *ima,float *medias,int x,int y,int z,int nx,int ny,int nz,int f,int sx,int sy,int sz) +{ + double d,acu,distancetotal; + int i,j,k,ni1,nj1,ni2,nj2,nk1,nk2; + + acu = 0; + distancetotal = 0; + + for (k = -f; k <= f; k++) + { + nk1 = z+k; + nk2 = nz+k; + if (nk1<0) nk1 = -nk1; + if (nk2<0) nk2 = -nk2; + if (nk1>= sz) nk1 = 2*sz-nk1-1; + if (nk2>= sz) nk2 = 2*sz-nk2-1; + for (j = -f; j <= f; j++) + { + nj1 = y+j; + nj2 = ny+j; + if (nj1<0) nj1 = -nj1; + if (nj2<0) nj2 = -nj2; + if (nj1>= sy) nj1 = 2*sy-nj1-1; + if (nj2>= sy) nj2 = 2*sy-nj2-1; + for (i = -f; i <= f; i++) + { + ni1 = x+i; + ni2 = nx+i; + if (ni1<0) ni1 = -ni1; + if (ni2<0) ni2 = -ni2; + if (ni1>= sx) ni1 = 2*sx-ni1-1; + if (ni2>= sx) ni2 = 2*sx-ni2-1; + + d = ((double)ima[nk1*(sx*sy)+(nj1*sx)+ni1]-(double)medias[nk1*(sx*sy)+(nj1*sx)+ni1])-((double)ima[nk2*(sx*sy)+(nj2*sx)+ni2]-(double)medias[nk2*(sx*sy)+(nj2*sx)+ni2]); + distancetotal += d*d; + } + } + } + + acu = (2*f+1)*(2*f+1)*(2*f+1); + d = distancetotal/acu; + + return d; +} + +void Regularize(float *in,float *out,int r,int sx,int sy,int sz) +{ + double acu, *temp; + int ind,i,j,k,ni,nj,nk,ii,jj,kk; + + temp = (double *)malloc(sx*sy*sz*sizeof(double)); + + /* separable convolution */ + for (k = 0; k= sx) ni = 2*sx-ni-1; + if (in[k*(sx*sy)+(j*sx)+ni]>0) + { + acu+= (double)in[k*(sx*sy)+(j*sx)+ni]; + ind++; + } + } + if (ind == 0) ind = 1; + out[k*(sx*sy)+(j*sx)+i] = (float)acu/ind; + } + + for (k = 0;k= sy) nj = 2*sy-nj-1; + if (out[k*(sx*sy)+(nj*sx)+i]>0) + { + acu+= (double)out[k*(sx*sy)+(nj*sx)+i]; + ind++; + } + } + if (ind == 0) ind = 1; + temp[k*(sx*sy)+(j*sx)+i] = acu/ind; + } + + for (k = 0;k= sz) nk = 2*sz-nk-1; + if (temp[nk*(sx*sy)+(j*sx)+i]>0) + { + acu+= temp[nk*(sx*sy)+(j*sx)+i]; + ind++; + } + } + if (ind == 0) ind = 1; + out[k*(sx*sy)+(j*sx)+i] = (float)acu/ind; + } + + free(temp); + return; +} + +void* ThreadFunc( void* pArguments ) +{ + float *bias,*Estimate,*ima,*means,*variances,*average; + double epsilon,mu1,var1,totalweight,wmax,t1,t1i,t2,d,w,distanciaminima; + unsigned char *Label; + int rows,cols,slices,ini,fin,v,f,i,j,k,l,rc,ii,jj,kk,ni,nj,nk,Ndims; + + extern int rician; + extern double max; + + myargument arg; + arg=*(myargument *) pArguments; + + rows = arg.rows; + cols = arg.cols; + slices = arg.slices; + ini = arg.ini; + fin = arg.fin; + ima = arg.in_image; + means = arg.means_image; + variances = arg.var_image; + Estimate = arg.estimate; + bias = arg.bias; + Label = arg.label; + v = arg.radioB; + f = arg.radioS; + + /* filter */ + epsilon = 1e-5; + mu1 = 0.95; + var1 = 0.5; + rc = rows*cols; + + Ndims = (2*f+1)*(2*f+1)*(2*f+1); + + average = (float*)malloc(Ndims*sizeof(float)); + + wmax = 0.0; + + for (k = ini; k0 && (means[(k*rc)+(j*cols)+i])>epsilon && (variances[(k*rc)+(j*cols)+i]>epsilon)) + { + /* calculate minimum distance */ + for (kk = -v;kk<= v;kk++) + { + nk = k+kk; + for (jj = -v;jj<= v;jj++) + { + nj = j+jj; + for (ii = -v;ii<= v;ii++) + { + ni = i+ii; + if (ii == 0 && jj == 0 && kk == 0) continue; + + if (ni>= 0 && nj>= 0 && nk>= 0 && ni0 && (means[(nk*rc)+(nj*cols)+ni])> epsilon && (variances[(nk*rc)+(nj*cols)+ni]>epsilon)) + { + t1 = ((double)means[(k*rc)+(j*cols)+i])/((double)means[(nk*rc)+(nj*cols)+ni]); + t1i = (max-(double)means[(k*rc)+(j*cols)+i])/(max-(double)means[(nk*rc)+(nj*cols)+ni]); + t2 = ((double)variances[(k*rc)+(j*cols)+i])/((double)variances[(nk*rc)+(nj*cols)+ni]); + + if ( (t1>mu1 && t1<(1.0/mu1)) || ((t1i>mu1 && t1i<(1.0/mu1)) && t2>var1 && t2<(1.0/var1))) + { + d = distance2(ima,means,i,j,k,ni,nj,nk,f,cols,rows,slices); + if (d= 0 && nj>= 0 && nk>= 0 && ni= 0 && nj>= 0 && nk>= 0 && ni0 && (means[(nk*rc)+(nj*cols)+ni])> epsilon && (variances[(nk*rc)+(nj*cols)+ni]>epsilon)) + { + t1 = ((double)means[(k*rc)+(j*cols)+i])/((double)means[(nk*rc)+(nj*cols)+ni]); + t1i = (max-(double)means[(k*rc)+(j*cols)+i])/(max-(double)means[(nk*rc)+(nj*cols)+ni]); + t2 = ((double)variances[(k*rc)+(j*cols)+i])/((double)variances[(nk*rc)+(nj*cols)+ni]); + + if ( (t1>mu1 && t1<(1.0/mu1)) || ((t1i>mu1 && t1i<(1.0/mu1)) && t2>var1 && t2<(1.0/var1))) + { + d = distance(ima,i,j,k,ni,nj,nk,f,cols,rows,slices); + + if (d>3*distanciaminima) w = 0; + else w = exp(-d/distanciaminima); + + if (w>wmax) wmax = w; + + if (w>0) + { + Average_block(ima,ni,nj,nk,f,average,w,cols,rows,slices); + totalweight = totalweight + w; + } + } + } + } + } + } + } + + if (wmax == 0.0) wmax = 1.0; + Average_block(ima,i,j,k,f,average,wmax,cols,rows,slices); + totalweight = totalweight + wmax; +#if !defined(_WIN32) && !defined(_WIN64) + pthread_mutex_lock(&mutex); +#endif + Value_block(Estimate,Label,i,j,k,f,average,totalweight,cols,rows,slices); +#if !defined(_WIN32) && !defined(_WIN64) + pthread_mutex_unlock(&mutex); +#endif + } + else + { + wmax = 1.0; + Average_block(ima,i,j,k,f,average,wmax,cols,rows,slices); + totalweight = totalweight + wmax; +#if !defined(_WIN32) && !defined(_WIN64) + pthread_mutex_lock(&mutex); +#endif + Value_block(Estimate,Label,i,j,k,f,average,totalweight,cols,rows,slices); +#if !defined(_WIN32) && !defined(_WIN64) + pthread_mutex_unlock(&mutex); +#endif + } + } + +#if defined(_WIN32) || defined(_WIN64) + _endthreadex(0); +#else + pthread_exit(0); +#endif + + free(average); + return 0; +} + + +void anlm(float* ima, int v, int f, int use_rician, const int* dims) +{ + float *means, *variances, *Estimate, *bias; + unsigned char *Label; + int ndim = 3; + double SNR,mean,var,estimate,d; + int vol,slice,label,Ndims,i,j,k,ii,jj,kk,ni,nj,nk,indice,Nthreads,ini,fin,r; + myargument *ThreadArgs; + extern int rician; + +#if defined(_WIN32) || defined(_WIN64) + HANDLE *ThreadList; /* Handles to the worker threads*/ +#else + pthread_t * ThreadList; +#endif + + Ndims = (int)floor(pow((2.0*f+1.0),ndim)); + slice = dims[0]*dims[1]; + vol = dims[0]*dims[1]*dims[2]; + + /* Allocate memory */ + means = (float*)malloc(vol*sizeof(float)); + variances = (float*)malloc(vol*sizeof(float)); + Estimate = (float*)malloc(vol*sizeof(float)); + Label = (unsigned char*)malloc(vol*sizeof(unsigned char)); + + /* set global parameter */ + if (use_rician) + rician = 1; + + if (rician) bias = (float*)malloc(vol*sizeof(float)); + + for (i = 0; i < vol; i++) + { + Estimate[i] = 0.0; + Label[i] = 0; + if (rician) bias[i] = 0.0; + } + + + max = 0.0; + for (k = 0;kmax) max = (double)ima[k*(slice)+(j*dims[0])+i]; + + mean = 0.0; + indice = 0; + for (ii = -1;ii<= 1;ii++) + { + for (jj = -1;jj<= 1;jj++) + { + for (kk = -1;kk<= 1;kk++) + { + ni = i+ii; + nj = j+jj; + nk = k+kk; + + if (ni<0) ni = -ni; + if (nj<0) nj = -nj; + if (nk<0) nk = -nk; + if (ni>= dims[0]) ni = 2*dims[0]-ni-1; + if (nj>= dims[1]) nj = 2*dims[1]-nj-1; + if (nk>= dims[2]) nk = 2*dims[2]-nk-1; + + + mean += (double)ima[nk*(slice)+(nj*dims[0])+ni]; + indice++; + + } + } + } + mean /= (double)indice; + means[k*(slice)+(j*dims[0])+i] = (float)mean; + } + } + } + + for (k = 0;k= 0 && nj>= 0 && nk>0 && ni0.0) + { + SNR = (double)means[i]/sqrt((double)variances[i]); + bias[i] = 2*(variances[i]/(float)Epsi(SNR)); +#if defined(_WIN32) || defined(_WIN64) + if (_isnan(bias[i])) bias[i] = 0.0; +#else + if ( isnan(bias[i])) bias[i] = 0.0; +#endif + } + } + } + + /* Aggregation of the estimators (i.e. means computation) */ + label = 0; + estimate = 0.0; + for (i = 0;i 0) + { + estimate = (double)Estimate[i]; + estimate /= (double)label; + if (rician) + { + estimate = (estimate-(double)bias[i])<0?0:(estimate-(double)bias[i]); + ima[i] = (float)sqrt(estimate); + } + else ima[i] = (float)estimate; + } + } + + free(ThreadList); + free(ThreadArgs); + free(means); + free(variances); + free(Estimate); + free(Label); + if (rician) free(bias); + + return; + +} + +","C" +"Neurology","ChristianGaser/cat12","cat_stat_confplot_spm.m",".m","23891","870","% [signal_change, xyz] = cat_stat_confplot_spm(SPM,xSPM,hReg,names,Ic) +% +% SPM, xSPM, hReg - parameters saved in workspace +% name - optional names of columns given as {'name1','name2'...} +% Ic - number of contrast (usually 1 for effects of interest) +% +% signal_change - signal change +% xyz - coordinates of local cluster maximum +% +% Quick Start Guide: +% 1. Define F-contrast ""effects of interest"" (check CAT12 manual for howto defining that contrast) +% This contrast is only used for plotting the data! +% 2. Call results with CAT12|View Results|Call Results +% 3. Call cat_stat_confplot_spm +% VOI definition: cluster (or what you like) +% Boxplot: colored (or define your own colors) +% Which contrast: effects of interest (from step 1) +% Define names: define names of groups for the boxplots or use the default numbers +% +% The right boxplot shows the adjusted raw data, which are corrected for any nuisance parameters +% (i.e. TIV), but not mean corrected like the parameter plot on the left. You can also enable +% ""Show Raw Data"" and press ""Plot"" to update the boxplot. With this you can also change the +% clusters and then update again with ""Plot"". +% Now the adjusted raw data are stored in the Matlab command line as variable ""y"". So just enter +% ""y"" and copy the output it to your prefered tool. +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +global xY Hc x + +try + [xyz,i] = spm_XYZreg('NearestXYZ',spm_XYZreg('GetCoords',hReg),xSPM.XYZmm); + spm_XYZreg('SetCoords',xyz,hReg); +catch + [hReg, xSPM, SPM] = spm_results_ui('Setup'); + [xyz,i] = spm_XYZreg('NearestXYZ',spm_XYZreg('GetCoords',hReg),xSPM.XYZmm); + spm_XYZreg('SetCoords',xyz,hReg); +end + +CI = 1.6449; % = spm_invNcdf(1 - 0.05); + +%-Colour specifications +%----------------------------------------------------------------------- +Col = [0 0 0; .8 .8 .8; 1 0 0]; + +Cplot = 'Parameter estimates'; + +%-Specify VOI +%----------------------------------------------------------------------- +xY.def = spm_input('VOI definition...',1,'b',... + {'sphere','box','cluster','voxel'},[],4); +Q = ones(1,size(xSPM.XYZmm,2)); + +% default font size and boxplot +if ~exist('Hc','var') || (exist('Hc','var') && isempty(Hc)) + Hc.FS = 18; % font size + Hc.LW = 2; % line width + Hc.MS = 10; % marker size + Hc.boxplot = 1; % show boxplot + Hc.medianplot = 0; % show median line + Hc.rawdata = 0; % show raw data + Hc.adjust = 1; % adjust raw data + Hc.connected = 0; % show connected lines for repeated anova + Hc.legend = 1; % show legend + Hc.line = cell(1,1); % trend line property + Hc.style = 3; % density plot +end + +if ~exist('colored','var') && exist('n_effects','var') + colored = spm_input('Boxplot','+1', 'm',['Colored|Define colors|Grey'],[2 1 0],1); + switch colored + case 0 + groupcolor = [0.7 0.7 0.7]; + case 1 + groupcolor = spm_input('Colors','!+0','r',[],[n_effects 3]); + case 2 + groupcolor = []; + end +end + +switch xY.def + + case 'sphere' + %--------------------------------------------------------------- + xY.spec = spm_input('VOI radius (mm)','!+0','r',0,1,[0,Inf]); + d = [xSPM.XYZmm(1,:) - xyz(1); + xSPM.XYZmm(2,:) - xyz(2); + xSPM.XYZmm(3,:) - xyz(3)]; + Q = find(sum(d.^2) <= xY.spec^2); + XYZstr = sprintf(' averaged in sphere (radius %d mm)', xY.spec); + xY.string = sprintf('sphere_%dmm_at_%g_%g_%gmm',xY.spec,xyz); + + case 'box' + %--------------------------------------------------------------- + xY.spec = spm_input('box dimensions [x y z] {mm}',... + '!+0','r','0 0 0',3); + Q = find(all(abs(xSPM.XYZmm - xyz*Q) <= xY.spec(:)*Q/2)); + XYZstr = sprintf(' averaged in box dimensions (%3.2f %3.2f %3.2f)', xY.spec); + xY.string = sprintf('box_%g_%g_%gmm_at_%g_%g_%gmm',xY.spec,xyz); + + case 'cluster' + %--------------------------------------------------------------- + [x0, i] = spm_XYZreg('NearestXYZ',xyz,xSPM.XYZmm); + A = spm_clusters(xSPM.XYZ); + Q = find(A == A(i)); + XYZstr = sprintf(' averaged in cluster'); + xY.string = sprintf('cluster_at_%g_%g_%gmm',x0); + + case 'voxel' + %--------------------------------------------------------------- + d = [xSPM.XYZmm(1,:) - xyz(1); + xSPM.XYZmm(2,:) - xyz(2); + xSPM.XYZmm(3,:) - xyz(3)]; + d2 = sum(d.^2); + Q = find(d2==min(d2)); + XYZstr = sprintf(' in voxel'); + xY.string = sprintf('voxel_at_%g_%g_%gmm',xyz); +end + +XYZ = xSPM.XYZ(:,Q); % coordinates + +%-Parameter estimates: beta = xX.pKX*xX.K*y; +%-Residual mean square: ResMS = sum(R.^2)/xX.trRV +%--------------------------------------------------------------- + +if ~exist(SPM.Vbeta(end).fname,'file') + error('File %s not found. Please check that you are in your analysis folder!',SPM.Vbeta(end).fname); +end + +beta0 = spm_get_data(SPM.Vbeta, XYZ); +beta = mean(beta0,2); + +try + fprintf('Read raw data...'); + y = spm_get_data(SPM.xY.VY, XYZ); + fprintf(sprintf('%s',repmat('\b',1,150))); + fprintf(sprintf('%s',repmat(' ',1,150))); + Hc.y_found = 1; + + fprintf('\n'); +catch + fprintf('No raw data found! Please check that you have not moved your data.\n'); + Hc.y_found = 0; + clear y + try close(Hc.h12); end +end + +% determine which contrast +%--------------------------------------------------------------- +%if ~exist('Ic','var') + Ic = spm_input('Which contrast?','!+1','m',{SPM.xCon.name}); +%end + +xCon = SPM.xCon(Ic); + +F_contrast_multiple_rows = 0; + +% for F-contrasts if rank is 1 we can use the first row +if strcmp(xCon.STAT,'F') + if rank(xCon.c) ~= 1 + F_contrast_multiple_rows = 1; + else + F_contrast_multiple_rows = 0; + end +end + +% some F-contrasts such as eoi are not yet supported to plot raw data +if F_contrast_multiple_rows + c0 = xCon.c; + c0 = c0(any(c0'),:); + if 0 +% if size(c0,1) > 1 && all(all(c0 == eye(size(c0,1)))) + fprintf('\nFor some F-contrasts (i.e. effects of interest) no plot of raw data is possible!\n'); + Hc.y_found = 0; + try close(Hc.h12); end + end +end + +ResMS = spm_get_data(SPM.VResMS,XYZ); +ResMS = mean(ResMS,2); +Bcov = ResMS*SPM.xX.Bcov; +Bcov = Bcov; + +TITLE = {Cplot XYZstr}; + +% find contrast and related columns in design matrix +%-------------------------------------------------------------- +c0 = xCon.c; + +[indi, indj] = find(c0~=0); +ind_X = unique(indi)'; +X = SPM.xX.X; +X = X(:,ind_X); +n_effects = size(X,2); + +covariate = 0; +nuisance_interaction = 0; + +% check for covariates +if ~isempty(SPM.xX.iC) && n_effects <= 2 + for i=1:n_effects + % contrast is defined at entries of iC + if ~isempty(find(ind_X(i) == SPM.xX.iC)) + covariate = 1; + else + covariate = 0; + end + end + % for factor designs we have to check whether we have + % interactions in the nuisance parameters + if covariate == 0 + rank_covariates = rank(SPM.xX.X(:,SPM.xX.iC)); + sum_covariates_with0 = sum(SPM.xX.X(:,SPM.xX.iC)==0,2); + if all(sum_covariates_with0 < rank_covariates) + nuisance_interaction = 1; + else + nuisance_interaction = 0; + end + else + nuisance_interaction = 0; + end +end + +% no raw data plot if interactions for nuisance parameters were found +if nuisance_interaction + fprintf('\nFor designs whith nuisance interactions no plot of raw data is possible!\n'); + Hc.y_found = 0; + try close(Hc.h12); end + clear y +end + +c0 = c0(ind_X,:); + +if ~exist('names','var') + define_names = spm_input('Define names?',1,'yes|use numbers',[1 0],1); + if define_names + names = []; + for i=1:n_effects + new_name = spm_input(['Name for parameter ' num2str(i)],1,'s'); + names = strvcat(names,new_name); + end + else + names = num2str((1:n_effects)'); + end +end + +% compute contrast of parameter estimates and 90% C.I. +%-------------------------------------------------------------- +signal_change = xCon.c'*beta; +CI = CI*sqrt(diag(xCon.c'*Bcov*xCon.c)); + +if ~exist('repeated_anova','var') + repeated_anova = ~isempty(SPM.xX.iB); + + if repeated_anova + [rw,cl] = find(SPM.xX.I == length(SPM.xX.iB)); % find column which codes subject factor (length(xX.iB) -> n_subj) + subj_col = cl(1); + if subj_col == 3 + group_col = 2; + else + group_col = 3; + end + n_groups = max(SPM.xX.I(:,group_col)); + + % expect that subject factors are 2nd colum, group 3rd column, time 4th column + if cl(1) == 2 + count = 0; + for i=1:n_groups + ind_times{i} = count + (1:max(SPM.xX.I(find(SPM.xX.I(:,3)==i),4))); + count = count + max(SPM.xX.I(find(SPM.xX.I(:,3)==i),4)); + end + n_time = max(SPM.xX.I(:,4)); + n_groupsxtime = n_groups*n_time; + + if n_groupsxtime ~= n_effects + repeated_anova = 0; + end + else + repeated_anova = 0; + end + end +end + +% get groups and subjects from SPM.xX.I for the different designs +if repeated_anova + groups = SPM.xX.I(:,3); + subjects = SPM.xX.I(:,2); +else + groups = SPM.xX.I(:,2); + subjects = SPM.xX.I(:,1); +end +n_groups = max(groups); + +% GUI figure +%-------------------------------------------------------------- + +% estimate maximum available window width for the two windows +Ms = spm('WinSize','0',1); +menu_width = 150; +max_width = floor((Ms(3) - menu_width)/2); +max_width = min(max_width, 800); + +Hc.h10 = figure(10); +clf + +set(Hc.h10,'Position',[0 800 menu_width 550],'MenuBar','none','NumberTitle','off'); +hNewButton = uicontrol(Hc.h10,... + 'Position',[20 500 110 20],... + 'Callback','cat_stat_confplot_spm',... + 'Interruptible','on',... + 'Style','Pushbutton',... + 'String','Plot'); +hClearButton = uicontrol(Hc.h10,... + 'position',[20 460 110 20],... + 'Callback','clear -globalvar Hc;clear names Ic colored groupcolor repeated_anova',... + 'Interruptible','on',... + 'Style','Pushbutton',... + 'String','Reset variables'); +hSaveButton = uicontrol(Hc.h10,... + 'position',[20 420 110 20],... + 'Callback',{@save_image},... + 'Interruptible','on',... + 'Style','Pushbutton',... + 'String','Save images'); +hCloseButton = uicontrol(Hc.h10,... + 'position',[20 380 110 20],... + 'Callback','clear -globalvar Hc;clear names Ic colored groupcolor repeated_anova,close(10,11,12)',... + 'Interruptible','on',... + 'Style','Pushbutton',... + 'String','Close windows'); +htext1 = uicontrol(Hc.h10,... + 'position',[20 340 60 20],... + 'Style','Text',... + 'String','Font Size'); +hedit1 = uicontrol(Hc.h10,... + 'position',[80 340 50 20],... + 'Callback',{@set_font_size},... + 'Interruptible','on',... + 'Style','Edit',... + 'String',num2str(Hc.FS)); +htext2 = uicontrol(Hc.h10,... + 'position',[20 300 60 20],... + 'Visible','off',... + 'Style','Text',... + 'String','Line width'); +hedit2 = uicontrol(Hc.h10,... + 'position',[80 300 50 20],... + 'Callback',{@set_line_width},... + 'Interruptible','on',... + 'Style','Edit',... + 'Visible','off',... + 'String',num2str(Hc.LW)); +htext3 = uicontrol(Hc.h10,... + 'position',[20 270 60 20],... + 'Visible','off',... + 'Style','Text',... + 'String','Marker Size'); +hedit3 = uicontrol(Hc.h10,... + 'position',[80 270 50 20],... + 'Callback',{@set_marker_size},... + 'Interruptible','on',... + 'Style','Edit',... + 'Visible','off',... + 'String',num2str(Hc.MS)); +hAdjustData = uicontrol(Hc.h10,... + 'position',[20 240 110 20],... + 'Callback',(@adjust_data),... + 'Interruptible','on',... + 'Style','CheckBox',... + 'Visible','off',... + 'Value',Hc.adjust,... + 'ToolTip','Adjust raw data for potential covariates and subject effects',... + 'String','Adjust Raw Data'); +hShowBoxplot = uicontrol(Hc.h10,... + 'position',[20 220 110 20],... + 'Callback',(@show_boxplot),... + 'Interruptible','on',... + 'Style','CheckBox',... + 'Visible','off',... + 'Value',Hc.boxplot,... + 'String','Show Boxplot'); +hShowRawdata = uicontrol(Hc.h10,... + 'position',[20 200 110 20],... + 'Callback',(@show_rawdata),... + 'Interruptible','on',... + 'Style','CheckBox',... + 'Visible','off',... + 'Value',Hc.rawdata,... + 'String','Show Raw Data'); +hShowMedianplot = uicontrol(Hc.h10,... + 'position',[20 180 110 20],... + 'Callback',(@show_medianplot),... + 'Interruptible','on',... + 'Style','CheckBox',... + 'Visible','off',... + 'Value',Hc.medianplot,... + 'String','Show Medianplot'); +hShowConnected = uicontrol(Hc.h10,... + 'position',[20 160 110 20],... + 'Callback',(@show_connected),... + 'Interruptible','on',... + 'Style','CheckBox',... + 'Visible','off',... + 'Value',Hc.connected,... + 'String','Connect Lines'); +hShowLegend = uicontrol(Hc.h10,... + 'position',[20 140 110 20],... + 'Callback',(@show_legend),... + 'Interruptible','on',... + 'Style','CheckBox',... + 'Visible','off',... + 'Value',Hc.legend,... + 'String','Show Legend'); + +if Hc.y_found + set(hAdjustData,'Visible','on'); + + if covariate + set(htext2,'Visible','on'); + set(hedit2,'Visible','on'); + set(htext3,'Visible','on'); + set(hedit3,'Visible','on'); + + if repeated_anova + set(hShowConnected,'Visible','on'); + set(hShowLegend,'Visible','on'); + Hc.style = 0; + end + else + set(hShowBoxplot,'Visible','on'); + set(hShowRawdata,'Visible','on'); + + if repeated_anova + set(hShowMedianplot,'Visible','on'); + set(htext2,'Visible','on'); + set(hedit2,'Visible','on'); + Hc.style = 0; + end + end +end + +% % signal change plot +%-------------------------------------------------------------- + +if ~exist('Hc','var') || (exist('Hc','var') && ~isfield(Hc,'h11')) + Hc.h11 = figure(11); + set(Hc.h11,'Position',[menu_width 800 max_width 550],'NumberTitle','off','MenuBar','none','color',[1 1 1]); +else + Hc.h11 = figure(11); +end + +cla +hold on + +% estimates +%-------------------------------------------------------------- +h = bar(signal_change'); +set(h,'FaceColor',Col(2,:)); + +% standard error +%-------------------------------------------------------------- +for j = 1:length(signal_change) + line([j j],([CI(j) 0 - CI(j)] + signal_change(j)),... + 'LineWidth',2,'Color',Col(3,:)) +end + +title(TITLE,'FontSize',14,'FontWeight','bold') +ylabel('parameter estimate','FontSize',12) +set(gca,'XLim',[0.4 (length(signal_change) + 0.6)],'XTick',1:length(signal_change)); + +if exist('names','var') + if size(names,1) == length(signal_change) + set(gca,'XTickLabel',names,'TickLabelInterpreter','none'); + end +end + +hold off + +if repeated_anova + if n_groups > 3 + Hc.col = jet(n_groups); + else + Hc.col = [1 0 0;0 0 1; 0 1 0]; + end +else + Hc.col = [1 0 0;0 0 1; 0 1 0]; +end + +% prepare raw values for boxplot +%-------------------------------------------------------------- +if Hc.y_found + + % adjust raw data + if Hc.adjust + + % define subject effects and potential covariates + G_columns = [SPM.xX.iB SPM.xX.iC]; + + % only consider nuisance parameters and parameters where + % contrast is defined + for i=1:n_effects + G_columns(find(G_columns==ind_X(i))) = []; + end + + % remove nuisance effects from data + if ~isempty(G_columns) + G = SPM.xX.X(:,G_columns); + G = G - mean(G); + y = y - G*(pinv(G)*y); + end + end + + % use mean inside cluster + y = mean(y,2); + + y_label = 'raw signal'; + + % estimate group means for correction for repeated anovas or interaction designs + % expect that subject factors are 2nd colum, group 3rd column, time 4th column + if Hc.adjust && (repeated_anova || ((n_groups > 1) && covariate)) + mean_group = zeros(n_groups,1); + count_times = 1; + for i=1:n_groups + ind_group = find(groups == i); + if repeated_anova + % find subjects effects in that group + ind_subj = unique(subjects(ind_group)); + n_subj_group = numel(ind_subj); + n_times = max(SPM.xX.I(ind_group,4)); + mean_group(i) = sum(beta(SPM.xX.iH(count_times:(count_times+n_times-1))))/n_times + ... + sum(beta(SPM.xX.iB(ind_subj)))/n_subj_group; + count_times = count_times + n_times; + else + mean_group(i) = beta(SPM.xX.iH(i)); + end + y(ind_group,:) = y(ind_group,:) - mean(y(ind_group,:)) + mean_group(i); + end + end + + yy = cell(n_effects,1); + for i=1:n_effects + yy{i} = y(find(X(:,i)~=0),:); + end + + if ~exist('Hc','var') || (exist('Hc','var') && ~isfield(Hc,'h12')) + Hc.h12 = figure(12); + set(Hc.h12,'Position',[max_width+menu_width 800 max_width 550],'NumberTitle','off','MenuBar','none','color',[1 1 1]); + else + Hc.h12 = figure(12); + end + + cla + + if Hc.rawdata + vshowdata = 1; + else + vshowdata = 0; + end + + if Hc.boxplot + vbox = 1; + voutliers = 1; + else + vbox = 0; + voutliers = 0; + end + + vstruct = struct('showdata',vshowdata,'box',vbox,'outliers',voutliers,'style',Hc.style); + if exist('groupcolor','var') && ~isempty(groupcolor) + vstruct.groupcolor = groupcolor; + end + + if isempty(yy{1}), return, end + + title_name = 'raw data '; + if Hc.adjust, title_name = ['adjusted ' title_name]; end + + % don't plot for multiple covariates because the plot might not be correct + if covariate% && numel(SPM.xX.iC) < 2 + + % previous plot must be deleted + clf + + xx = cell(n_effects,1); + % use existing x-variable if available + if exist('x','var') && numel(x)==size(X,1) + xx_array = [min(x) max(x)]; + for i=1:n_effects + xx{i} = X(groups==i); + end + x0 = x; + else + xx_array = [min(X(X~=0)) max(X(X~=0))]; + for i=1:n_effects + xx{i} = X(groups==i,i); + end + x0 = sum(X,2); + end + + hold on + for i=1:n_effects + x2 = xx{i}; + y2 = mean(yy{i},2); + if n_effects > 1 + cat_plot_scatter(x2,y2,'MSize',Hc.MS,'Color',Hc.col(i,:),'PlotType','scatter'); + else + cat_plot_scatter(x2,y2,'MSize',Hc.MS,'Fit_Poly',1); + end + end + + % for repeated anovas also plot connected lines if defined + if repeated_anova && Hc.connected + % coding of subject factor should be hopefully always 2nd column of xX.I + n_subjects = max(subjects); + + y0 = mean(y,2); + for i=1:n_subjects + + ind = find(subjects == i); + x_tmp = x0(ind); + y_tmp = y0(ind); + + if ~isempty(ind) + line(x_tmp,y_tmp,'Color',Hc.col(groups(ind(1)),:)); + end + end + end + + hold off + + if Hc.legend + if n_effects == 2 + legend(['95% CI ' names(1,:)],names(1,:),['Fit ' names(1,:)],['95% CI ' names(2,:)],names(2,:),['Fit ' names(2,:)]) + else + legend('95% CI',names(1,:),'Fit') + end + end + + TITLE = {['Scatterplot of ' title_name] XYZstr}; + else + + cat_plot_boxplot(yy,vstruct); + TITLE = {['Boxplot of ' title_name] XYZstr}; + if Hc.style == 3 + set(gca,'YLim',[0.4 (length(signal_change) + 0.6)],'YTick',1:length(signal_change)); + else + set(gca,'XLim',[0.4 (length(signal_change) + 0.6)],'XTick',1:length(signal_change)); + end + + if exist('names','var') + if size(names,1) == length(signal_change) + if Hc.style == 3 + set(gca,'YTickLabel',names,'TickLabelInterpreter','none'); + else + set(gca,'XTickLabel',names,'TickLabelInterpreter','none'); + end + end + end + + if repeated_anova && Hc.medianplot + hold on + + plot_data = zeros(n_effects,1); + count = 1; + for i=1:n_groups + for j=1:length(ind_times{i}) + plot_data(count) = median(yy{ind_times{i}(j)}); + count = count + 1; + end + Hc.line{i} = plot(ind_times{i},plot_data(ind_times{i}),'Color',Hc.col(i,:),'LineWidth',Hc.LW); + end + hold off + end + end + + title(TITLE,'FontSize',14,'FontWeight','bold') + if Hc.style == 3 + xlabel(y_label,'FontSize',12) + else + ylabel(y_label,'FontSize',12) + end + + set(gca(Hc.h12),'FontSize',Hc.FS); +end + +set(gca(Hc.h11),'FontSize',Hc.FS); + +%========================================================================== +function set_font_size(obj, event_obj) + +global Hc + +Hc.FS = str2num(get(obj,'String')); + +if isempty(Hc.FS) || numel(Hc.FS)>1 + fprintf('Error: Please enter a single number for defining font size\n'); +else + set(gca(Hc.h11),'FontSize',Hc.FS); + if Hc.y_found + set(gca(Hc.h12),'FontSize',Hc.FS); + end +end + +end + +%========================================================================== +function set_line_width(obj, event_obj) + +global Hc + +Hc.LW = str2num(get(obj,'String')); + +if isempty(Hc.LW) || numel(Hc.LW)>1 + fprintf('Error: Please enter a single number for defining line width\n'); +else + if Hc.y_found + if ~isempty(Hc.line{1}) + for i=1:numel(Hc.line) + set(Hc.line{i},'LineWidth',Hc.LW); + end + end + end +end + +end + +%========================================================================== +function set_marker_size(obj, event_obj) + +global Hc + +Hc.MS = str2num(get(obj,'String')); + +if isempty(Hc.MS) || numel(Hc.MS)>1 + fprintf('Error: Please enter a single marker for defining plot symbols\n'); +else + if Hc.y_found + ic = findobj(Hc.h12, 'Type', 'line'); + for i=1:numel(ic) + % Marker has more than two points + if numel(get(ic(i),'XData')) > 2 + set(ic(i),'MarkerSize',Hc.MS); + end + end + end +end + +end + +%========================================================================== +function adjust_data(obj, event_obj, filename) + +global Hc + +Hc.adjust = get(obj, 'Value'); + +end + +%========================================================================== +function show_connected(obj, event_obj, filename) + +global Hc + +Hc.connected = get(obj, 'Value'); + +end + +%========================================================================== +function show_rawdata(obj, event_obj, filename) + +global Hc + +if Hc.boxplot || Hc.medianplot + Hc.rawdata = get(obj, 'Value'); +end + +end + +%========================================================================== +function show_medianplot(obj, event_obj, filename) + +global Hc + +if Hc.rawdata || Hc.boxplot + Hc.medianplot = get(obj, 'Value'); +end + +end + +%========================================================================== +function show_boxplot(obj, event_obj, filename) + +global Hc + +if Hc.rawdata || Hc.medianplot + Hc.boxplot = get(obj, 'Value'); +end + +end + +%========================================================================== +function show_legend(obj, event_obj, filename) + +global Hc + +Hc.legend = get(obj, 'Value'); + +end + +%========================================================================== +function save_image(obj, event_obj, filename) + +global xY Hc + +if ~exist('filename', 'var') + + filename = xY.string; + + [filename, newpth] = uiputfile({ ... + '*.png' 'PNG files (*.png)'}, 'Save as', filename); +else + [pth, nam, ext] = fileparts(filename); + if isempty(pth), pth = cd; end + if isempty(nam) + [filename, newpth] = uiputfile({ ... + '*.png' 'PNG files (*.png)'}, 'Save as', nam); + else + filename = fullfile(pth, nam); + newpth = pth; + end +end + +% remove potential .png +filename = regexprep(filename,'.png',''); + +try + % keep background color + set(Hc.h10, 'InvertHardcopy', 'off', 'PaperPositionMode', 'auto'); + hh = getframe(Hc.h11); + img = hh.cdata; + col = colormap; + saved_file = fullfile(newpth,['estimates_' filename '.png']); + imwrite(img,col,saved_file); + fprintf('File %s saved.\n',saved_file); +catch + fprintf('File %s could not be saved.\n',saved_file); +end + +if Hc.y_found + try + % keep background color + set(Hc.h12, 'InvertHardcopy', 'off', 'PaperPositionMode', 'auto'); + hh = getframe(Hc.h12); + img = hh.cdata; + col = colormap; + saved_file = fullfile(newpth,['boxplot_' filename '.png']); + imwrite(img,col,saved_file); + fprintf('File %s saved.\n',saved_file); + catch + fprintf('File %s could not be saved.\n',saved_file); + end +end + +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_vol_correct_slice_scaling.m",".m","16180","429","function cat_vol_correct_slice_scaling(varargin) +% ______________________________________________________________________ +% Correction of slice artifacts for a set of images. +% +% WARNING: This kind of artifacts are untypical for 98% of the data! +% Apply this filter only for images with slice artifacts, +% because this filter can introduce inhomogeneities! +% +% To control the filter direction and number of iterations we test the +% if one gradient is untpyical high. If this is the case the filter is +% applyed for this direction as long as all gradient get more similar. +% In most cases only 1-3 iterations are necessary. +% The filter use information from the foreground (object/tissue) to +% estimate the correction filed. Background information are used to +% stabilize the estimation of the WM threshhold. +% +% This is only a slice-bias correction and the image will include +% inhomogeneity after correction that requires further correction by +% standard approaches like N3 or the SPM and CAT proprocessings! +% +% cat_vol_correct_slice_scaling(job) +% +% job.data +% job.prefix .. file prefix (default = 'slicecorr_') +% job.s .. filtersize (default = 12) +% job.iter .. maximum number of iterations (default = 5); +% job.verb .. display progress in the command window +% job.lb .. lower intensity boundary +% job.ub .. upper intensity boundary +% +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ +% ______________________________________________________________________ + +% ______________________________________________________________________ +% Further comments: +% - There is a private test script 'cat_tst_BWPsliceartifact.m' that use +% BWP (brain web phantom) or real data to simulate slice artifacts for +% each direction. +% - It is also possible to use the background for correction, but due to +% the low values the division by zero is critical. It is possible to +% smooth i and i+1 separate, but this will increase calculatin time by +% factor 3 and the improvements are only a little. +% - In images with a high intensity low gradient tissues higher than the +% WM like FAT were overcorrected, although the intensity boundies were +% correct. I expect that this depend on the slicewise correction. +% - The most problematic cases is given by images, were the slice +% artifact is in the anatomic x-direction, because the slices around +% the corpus callosum have untpyical high GM tissue. This slices trend +% to be brighter than they should. Using the background as control +% parameter for the WM threshold helps to reduce this problem. +% - The boundaries have to be wide to allow also corrections of block +% artifacts like in IBSR1:5_8 were slice 1-x are normal and x+1 to end +% are 50% brighter. +% +% - Other methods: +% - Slice correction also by 'caret_command -volume-bias-correction'? +% - not full automatic, no direction / iteration criteria +% - SLED log correction? +% - + +% ______________________________________________________________________ + + + +% check / set intput + spm_clf('Interactive'); + + + % data + if nargin == 0 + job.data = cellstr(spm_select([1 Inf],'image','select images to filter')); + else + job = varargin{1}; + end + if ~isfield(job,'data') || isempty(job.data) + job.data = cellstr(spm_select([1 Inf],'image','select images to filter')); + else + job.data = cellstr(job.data); + end + if isempty(job.data), return; end + + + % filter size + if ~isfield(job,'s') + %job.s = min(32,max(8,spm_input('filter size? (8-32)','+1','i',12,1))); + job.s = 12; + end + + if ~isfield(job,'method') + job.method = 1; + end + + + % maximum iteration number + if ~isfield(job,'iter') + %job.iter = min(10,max(1,spm_input('maximum iterations? (1-10)','+1','i',3,1))); + job.iter = 10; + end + + + % tissue limits for WM==1 + if ~isfield(job,'lb') + lb = 0.5; + else + lb = job.lb; + end + if ~isfield(job,'ub') + ub = 2.0; + else + ub = job.ub; + end + + + % force at least one iteration in one direction processing + if ~isfield(job,'force') + force = 3; + else + force = job.force; + end + + + % file prefix + if ~isfield(job,'prefix') + job.prefix = spm_input('file prefix','+1','s',... + sprintf('slicecorrS%02.0f_',job.s),1); + end + if strcmp(job.prefix,'auto') + job.prefix = sprintf('slicecorrF%dS%02.0f_',force,job.s); + end + + + % processing information + if ~isfield(job,'verb') + job.verb = 1; + end + + +% start processing ... + V = spm_vol(char(job.data)); + + cat_progress_bar('Init',numel(job.data),'Slice-Filtering','Volumes Complete'); + if job.verb, fprintf('Correct Slice Scaling:\n'); stime0=clock; end + for j = 1:length(V) + if job.verb, fprintf(' %s:',V(j).fname); stime=clock; end + + Yo = single(spm_read_vols(V(j))); Y=Yo; + [gx,gy,gz] = cat_vol_gradient3(Y); + + % estimate slice error and create a gradient map Yg (tissue) and Ygb + % (background) without the critical direction + calc1 = cat_stat_nanmean([ abs(gx(:)),abs(gy(:)),abs(gz(:))]) / ... + cat_stat_nanmean([ abs(gx(:));abs(gy(:));abs(gz(:))]); + calc = (calc1 > 1.01) & (calc1==max(calc1)); + + % intern noise estimation and correction + signal = cat_stat_nanmedian(Y(Y(:)>cat_stat_nanmedian(Y(:)))); + signal = cat_stat_nanmedian(Y(Y>cat_stat_nanmedian(Y(Y(:)>signal & Y(:)<2*signal)))); + noise = cat_vol_localstat(Y,Y0)); + NSR = double(noise / signal); sx = repmat(NSR * 5,1,3); sx(calc==1) = 0; + Y = double(Y); spm_smooth(Y,Y,sx); Y = single(Y); + + %% + [gx,gy,gz] = cat_vol_gradient3(Y); + Yg = ((calc1(1)<1.05) .* abs(gx) + (calc1(2)<1.05) .* abs(gy) + (calc1(3)<1.05) .* abs(gz)) .* ... + 3/(sum(calc1<1.05)) ./ max(eps,Y); + Ygb = ((calc1(1)<1.05) .* abs(gx) + (calc1(2)<1.05) .* abs(gy) + (calc1(3)<1.05) .* abs(gz)) .* ... + 3/(sum(calc1<1.05)) ./ max(signal*0.3,Y); + + % estimate thresholds for Yg, Ygb, and Y (WM threshold) + gth = cat_stat_nanmean(Yg(Yg(:)cat_stat_nanmean(Y(Yg(:)>0 & Yg(:)cat_stat_nanmean(Y(Yg(:)>0 & Yg(:)Yth*0.5)))); + + % test segments + Ywm = smooth3(YgYthw*0.2)>0.5; + Ybg = smooth3(Ygb./Yg<1.0 & Y0)>0.5; %smooth3(Y0.5; + + Ythb = cat_stat_nanmean(Y(Ybg(:))); + %Ythw = cat_stat_nanmedian(Y(Ywm(:))); + + % estimate slice error to find the affected slice + calc1 = cat_stat_nanmean(abs([ gx(Ywm(:)),gy(Ywm(:)),gz(Ywm(:)) ])) / ... + cat_stat_nanmean(abs([ gx(Ywm(:));gy(Ywm(:));gz(Ywm(:)) ])); + calc3 = calc1; calc5 = calc1; + calc = (calc1 > 1.01) & (calc1==max(calc1)); + clear gx gy gz; + + if force + calcdir = force; + calc = [0 0 1]; + calc1 = ones(1,3); calc1(force) = inf; + calc3 = calc1; + calc5 = calc1; + else + calcdir = find(calc==1); + end + + % adapt boundaries for artifact strenth + lb = max(0.3,lb ./ max(calc1)); + ub = max(2.0,ub .* max(calc1)); + + % ds('l2','',[1 1 1],Y,Ywm + (1-Ybg),Yg,Ywm,90) + + %% + if any(isnan(calc)) || all(calc==0) + fprintf('\n No slice artifact detected! No correction! \n'); + desc = 'not-slicecorreted'; + else + if job.verb==2; xyz='xyz'; fprintf('\n\t%s: %0.3f',xyz(calc==1),mean(abs(calc3-1))); end + Y1 = Y; + Y2 = Yo; + it = 0; + + + + while it < job.iter + it = it + 1; + Yf = Y1; + Yof = Y2; + switch calcdir + case 1 % x-direction + for i = 2:V(j).dim(1) % forward + [Yf(i,:,:),Yof(i,:,:)] = correctslice(Yof(i,:,:),Yf(i,:,:),Yf(i-1,:,:),Ybg(i,:,:),Ybg(i-1,:,:),lb,ub,Ythw,Ythb,job.s,job.method,1); + end + % global intensity correction + Yof = Yof ./ (mean(Yf(Ywm(:)))./mean(Y1(Ywm(:)))); + Yf = Yf ./ (mean(Yf(Ywm(:)))./mean(Y1(Ywm(:)))); + for i = V(j).dim(1)-1:-1:1 % backward + [Yf(i,:,:),Yof(i,:,:)] = correctslice(Yof(i,:,:),Yf(i,:,:),Yf(i+1,:,:),Ybg(i,:,:),Ybg(i+1,:,:),lb,ub,Ythw,Ythb,job.s,job.method,1); + end + case 2 % y-direction + for i = 2:V(j).dim(2) + [Yf(:,i,:),Yof(:,i,:)] = correctslice(Yof(:,i,:),Yf(:,i,:),Yf(:,i-1,:),Ybg(:,i,:),Ybg(:,i-1,:),lb,ub,Ythw,Ythb,job.s,job.method,2); + end + Yof = Yof ./ (mean(Yf(Ywm(:)))./mean(Y1(Ywm(:)))); + Yf = Yf ./ (mean(Yf(Ywm(:)))./mean(Y1(Ywm(:)))); + for i = V(j).dim(2)-1:-1:1 + [Yf(:,i,:),Yof(:,i,:)] = correctslice(Yof(:,i,:),Yf(:,i,:),Yf(:,i+1,:),Ybg(:,i,:),Ybg(:,i+1,:),lb,ub,Ythw,Ythb,job.s,job.method,2); + end + case 3 % z-direction + for i = 2:V(j).dim(3) + [Yf(:,:,i),Yof(:,:,i)] = correctslice(Yof(:,:,i),Yf(:,:,i),Yf(:,:,i-1),Ybg(:,:,i),Ybg(:,:,i-1),lb,ub,Ythw,Ythb,job.s,job.method,3); + end + Yof = Yof ./ (mean(Yf(Ywm(:)))./mean(Y1(Ywm(:)))); + Yf = Yf ./ (mean(Yf(Ywm(:)))./mean(Y1(Ywm(:)))); + for i = V(j).dim(3)-1:-1:1 + [Yf(:,:,i),Yof(:,:,i)] = correctslice(Yof(:,:,i),Yf(:,:,i),Yf(:,:,i+1),Ybg(:,:,i),Ybg(:,:,i+1),lb,ub,Ythw,Ythb,job.s,job.method,3); + end + end + % global intensity correction + Yof = Yof ./ (mean(Yf(Ywm(:)))./mean(Y1(Ywm(:)))); + Yf = Yf ./ (mean(Yf(Ywm(:)))./mean(Y1(Ywm(:)))); + + % estimate artifact size to handly iteration + [calc2,calc4] = estimateError(Yf,Ywm,Ythw); + + if it==1, imp=0.9; else imp=1; end + if mean(abs(calc2-1))/mean(abs(calc3-1)) %0.3f',mean(abs(calc2-1))); end + Y1 = Yf; Y2 = Yof; + else + if job.verb==2, fprintf(' > %0.3fx',mean(abs(calc2-1))); end + if it==1, fprintf('\n No slice artifact detected! No correction! \n'); end + break; + end; + if (mean(abs(calc2-1))/mean(abs(calc3-1))>0.95) || ... + (mean(abs(calc4-1))/mean(abs(calc5-1))>0.95) || calc4(calcdir)<1.01 + break; + end + calc3 = calc2; calc5 = calc4; + end + desc = 'slicecorreted'; + end + + % write result + % ------------------------------------------------------------------ + [pth, nam, ext, num] = spm_fileparts(V(j).fname); + Vc = V; Vc(j).fname = fullfile(pth, [job.prefix nam ext num]); + Vc(j).descrip = sprintf('%s<%s',desc,Vc(j).descrip); + spm_write_vol(Vc(j),Y2); + + cat_progress_bar('Set',j); + if job.verb, fprintf('\t%6.2fs\n',etime(clock,stime)); end + end + cat_progress_bar('Clear'); + if job.verb, fprintf('done (%3.2f Minute(s)).\n',etime(clock,stime0)/60); end +end +function [Ythi,Ythwi] = estimateWMth(Y,Yth,lb,ub) + Ythi = cat_stat_nanmean(Y(Y>cat_stat_nanmean(Y(Y(:)>0)))); % object threshold (lower boundary) + Ythwi = cat_stat_nanmean(Y(Y>cat_stat_nanmean(Y(Y(:)>Ythi)))); % WM threshold for displaying + Ythwi = max(Ythi*lb,min(Yth*ub,Ythwi)); + Ythi = Ythwi .* lb; +end +function [cimgt,cimgo] = correctslice(imgo,imgi,imgj,imgbi,imgbj,lb,ub,Ythw,Ythb,s,method,dim) + +% ds('l2','',[1 1 1],imgi,imgi,imgj/Ythwj,imgi/Ythwi,1) + + imgt = imgi; + + imgb = mean(cat(dim,imgbj,imgbi),dim)==1; % average background + + % background intensity for special cases + Ythbi = mean(imgi(imgb(:))); + Ythbj = mean(imgj(imgb(:))); + + [Ythi,Ythwi] = estimateWMth(imgi,Ythw,lb,ub); + [Ythj,Ythwj] = estimateWMth(imgj,Ythw,lb,ub); + + lb1 = 0.1; + if YthwiYthw*0.3 & imgimgbth*1.5)=0; imgb(img(:)Ythw*0.9 & Yf0)>0.5,'close',2); + calc2 = cat_stat_nanmean([ abs(gx(Ywm(:))),abs(gy(Ywm(:))),abs(gz(Ywm(:)))]) / max(eps,... + cat_stat_nanmean([ abs(gx(Ywm(:)));abs(gy(Ywm(:)));abs(gz(Ywm(:)))])); + calc4 = cat_stat_nanmean([ abs(gx(Ywm2(:))),abs(gy(Ywm2(:))),abs(gz(Ywm2(:)))]) / max(eps,... + cat_stat_nanmean([ abs(gx(Ywm2(:)));abs(gy(Ywm2(:)));abs(gz(Ywm2(:)))])); +end +function cimg = smoothslice(img,s,method,dim) + % filtering by image reduction, smoothing and reinterpolation + % 3d-data required + % not nice, but better than conv2 + if method==1 + switch dim + case 1 + cimg = repmat(img,[3,1,1]); + [cimg,IR1] = cat_vol_resize({cimg},'reduceV',1,s,2,'mean'); + cimg = smooth3(cimg); + cimg = cat_vol_resize({cimg},'dereduceV',IR1); + cimg = smooth3(cimg); + cimg = cimg(2,:,:); + case 2 + cimg = repmat(img,[1,3,1]); + [cimg,IR1] = cat_vol_resize({cimg},'reduceV',1,s,2,'mean'); + cimg = smooth3(cimg); + cimg = cat_vol_resize({cimg},'dereduceV',IR1); + cimg = smooth3(cimg); + cimg = cimg(:,2,:); + case 3 + cimg = repmat(img,[1,1,3]); + [cimg,IR1] = cat_vol_resize({cimg},'reduceV',1,s,2,'mean'); + cimg = smooth3(cimg); + cimg = cat_vol_resize({cimg},'dereduceV',IR1); + cimg = smooth3(cimg); + cimg = cimg(:,:,2); + end + elseif method==2 % spm-smoothing approach - bad boundary properies, even if I correct for the mean intensity + sx = repmat(s,1,3); sx(dim) = 0; ofs = mean(img(:)); + cimg = double(img-ofs); spm_smooth(cimg,cimg,sx); cimg = single(cimg+ofs); + else % christian all smoothing approach - not really smooth + x = [-s:s]; + x = exp(-(x).^2/(2*(s).^2)); + x = x/sum(x); + cimg = conv2(img,x'*x,'same'); + end +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_io_updateStruct.m",".m","2409","69","function S=cat_io_updateStruct(S,SN,RepByEmpty,ind) +% _________________________________________________________________________ +% Add and/or updates entries of the structure 'SN' to the structure 'SI'. +% If 'RepByEmpty=0', fields of SI where only overwriten by nonemtpy fields +% of 'SN'. If the structure has multiple entries, 'ind' can be used to set +% a specific field, otherwise all entries will be replaced. +% +% S = cat_io_updateStruct(SI,SN[,RepByEmpty,ind]) +% +% WARNING: +% This function is still in developent! Be careful by using it, due to +% unexpected behaviour. Updating of structures is a complex topic with +% many subcases and here only a simple alignment is used! +% +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + % check input + if ~exist('RepByEmpty','var'), RepByEmpty = 0; end + if ~exist('ind','var') + if numel(SN) <= 1, ind = 1; else ind = 1:numel(SN); end + end + ind = min(single(intmax),max(1,ind)); + + + if numel(SN) > 1 + % multiple element update + for sni=ind + S = cat_io_updateStruct(S,SN(sni),RepByEmpty,sni); + end + else + % single element update + fnS = fieldnames(SN); + for fnSi=1:numel(fnS) + if isfield(S,fnS{fnSi}) + if (ischar(SN.(fnS{fnSi})) && RepByEmpty) || ~isempty(SN.(fnS{fnSi})) + if isstruct(SN.(fnS{fnSi})) + % if the field is a structure too, cat_io_updateStruct has + % to be used recursive + if ~isstruct(S(1).(fnS{fnSi})) + S = rmfield(S,fnS{fnSi}); + end + if numel(S) + + % get current release number and version + [ver_cat, rev_cat] = cat_version; + ver_cat = ver_cat(4:end); % remove leading CAT + + % init output + QAS = struct(); + QAR = struct(); + %if nargout>0, varargout = cell(1,nargout); end + + try + if strcmp(action,'cat12err') + [mrifolder, reportfolder] = cat_io_subfolders(varargin{1}.job.data,varargin{1}.job); + elseif strcmp(action,'cat12') + [mrifolder, reportfolder] = cat_io_subfolders(varargin{2},varargin{6}.job); + else + [mrifolder, reportfolder] = cat_io_subfolders(varargin{4}.catlog,varargin{6}.job); + end + catch + mrifolder = 'mri'; + reportfolder = 'report'; + end + + % no input and setting of default options + action2 = action; + if nargin==0, action='p0'; end + if isstruct(action) + if isfield(action,'model') + if isfield(action.model,'catp0') + Po = action.images; + Pp0 = action.model.catp0; + if numel(Po)~=numel(Pp0) && numel(Pp0)==1 + Pp0 = repmat(Pp0,numel(Po),1); + end + Pm = action.images; + action.data = Pp0; + end + end + if isfield(action,'data') + Pp0 = action.data; + end + action = 'p0'; + end + if nargin==3 && isstruct(varargin{2}) && isstruct(varargin{2}) + opt = cat_check('checkinopt',varargin{2},defaults); + nopt = 1; + elseif nargin==8 && isstruct(varargin{6}) && isstruct(varargin{6}) + opt = cat_check('checkinopt',varargin{6},defaults); + nopt = 1; + else + if isstruct(action2) + opt = cat_check('checkinopt',action2.opts,defaults); + else + opt = defaults; + end + nopt = 0; + end + + % check input by action + switch action + case {'p0','p0+'} + % segment image cases + if nargin<=3 && ( ~exist('Pp0','var') || isempty(Pp0) ) + if (nargin-nopt)<2 + Pp0 = cellstr(spm_select(inf,'image',... + 'select p0-segment image',{},pwd,'^p0.*')); + if isempty(Pp0{1}), return; end + else + Pp0 = varargin{1}; + end + if numel(action)==2 + Po = Pp0; Pm = Pp0; + for fi=1:numel(Pp0) + [pp,ff,ee] = spm_fileparts(Pp0{fi}); + [ppa,ppb] = spm_fileparts(pp); + if strcmp(ppb,'mri'), ppo = ppa; else, ppo = pp; end + + Po{fi} = fullfile(ppo,[ff(3:end) ee]); + Pm{fi} = fullfile(pp,[opt.mprefix ff(3:end) ee]); + %Pmv{fi} = fullfile(pp,['m' ff(3:end) ee]); %#ok + %if ~exist(Pm{fi},'file') && strcmp(opt.mprefix,'nm') && exist(Pmv{fi},'file') + % fprintf('Preparing %s.\n',Pmv{fi}); + % cat_vol_sanlm(Pmv{fi},'n'); + %end + + if ~exist(Po{fi},'file'), Po{fi}=''; end + if ~exist(Pm{fi},'file'), Pm{fi}=''; end + end + else + Po = cellstr(spm_select(repmat(numel(Pp0),1,2),... + 'image','select original image(s)',{},pwd,'.*')); + Pm = cellstr(spm_select(repmat(numel(Pp0),1,2),... + 'image','select modified image(s)',{},pwd,'.*')); + end + elseif nargin<=5 && ( ~exist('Pp0','var') || isempty(Pp0) ) + Pp0 = varargin{1}; + Po = varargin{2}; + Pm = varargin{3}; + elseif ( ~exist('Pp0','var') || isempty(Pp0) ) + error('MATLAB:cat_vol_qa202205:inputerror',... + 'Wrong number/structure of input elements!'); + end + case {'p#','c#','*#','p#+','c#+','*#+'} + % tissue class image cases + if nargin-1<=2 % GUI + if (nargin-nopt)<2 + if action(1)=='p' || action(1)=='c' + % cat/spm case + Pcsf = cellstr(spm_select(inf,'image',... + 'select p1-segment image',{},pwd,['^' action(1) '1.*'])); + if isempty(Pcsf{1}), return; end + Pgm=Pcsf; Pwm=Pcsf; + for fi=1:numel(Pcsf) + [pp,ff,ee] = spm_fileparts(Pcsf{fi}); + + Pgm{fi} = fullfile(pp,[action(1) '2' ff(3:end) ee]); + Pwm{fi} = fullfile(pp,[action(1) '3' ff(3:end) ee]); + end + else + Pcsf = cellstr(spm_select(inf,'image',... + 'select CSF segment image(s)',{},pwd,'.*')); + if isempty(Pcsf{1}), return; end + %Pgm = cellstr(spm_select(repmat(numel(Pcsf),1,2),... + % 'image','select GM segment image(s)',{},pwd,'.*')); + %Pwm = cellstr(spm_select(repmat(numel(Pcsf),1,2),... + % 'image','select WM segment image(s)',{},pwd,'.*')); + end + if numel(action)==2 + Pp0=Pcsf; Po=Pcsf; Pm=Pcsf; + for fi=1:numel(Pcsf) + [pp,ff,ee] = spm_fileparts(Pcsf{fi}); + Po{fi} = fullfile(pp,[ff(3:end) ee]); + Pm{fi} = fullfile(pp,['m' ff(3:end) ee]); + Pp0{fi} = fullfile(pp,['p0' ff(3:end) ee]); + end + else + Po = cellstr(spm_select(repmat(numel(Pcsf),1,2),... + 'image','select original image(s)',{},pwd,'.*')); + Pm = cellstr(spm_select(repmat(numel(Pcsf),1,2),... + 'image','select modified image(s)',{},pwd,'.*')); + Pp0=Pcsf; + for fi=1:numel(Pcsf) + [pp,ff,ee] = spm_fileparts(Pcsf{fi}); + Pp0{fi} = fullfile(pp,['p0' ff(3:end) ee]); + end + end + + % wie komm ich zum p0??? + else + Pp0 = varargin{1}; + end + elseif nargin==5 || nargin==6 + else + error('MATLAB:cat_vol_qa202205:inputerror',... + 'Wrong number/structure of input elements!'); + end + + Yp0 = 1; + case 'cat12err' + opt = cat_check('checkinopt',varargin{end},defaults); + case 'cat12' + % CAT12 internal input + if nargin>3 + Yp0 = varargin{1}; +% Octave is starting with many warning messages here ... +% if strcmpi(spm_check_version,'octave'), warning off; end + Vo = spm_vol(varargin{2}); +% if strcmpi(spm_check_version,'octave'), warning on; end + Yo = single(spm_read_vols(Vo)); + Ym = varargin{3}; + res = varargin{4}; + V = res.image; + species = varargin{5}; + if isfield(varargin{6},'qa') + if isfield(varargin{6}.qa,'software') && isfield(varargin{6}.qa.software,'version_segment'), QAS.software.version_segment = varargin{6}.qa.software.version_segment; end + if isfield(varargin{6}.qa,'qualitymeasures'), QAS.qualitymeasures = cat_io_updateStruct(QAS,varargin{6}.qa.qualitymeasures); end + if isfield(varargin{6}.qa,'subjectmeasures'), QAS.subjectmeasures = cat_io_updateStruct(QAS,varargin{6}.qa.subjectmeasures); end + end + if nargin>7, Pp0 = varargin{7}; end % nargin count also parameter + % opt = varargin{end} in line 96) + opt.verb = 0; + + % reduce to original native space if it was interpolated + sz = size(Yp0); + if any(sz(1:3)~=Vo.dim(1:3)) + if isfield(Vo,'private'), Vo = rmfield(Vo,'private'); end + if isfield(Vo,'mat0'), Vo = rmfield(Vo,'mat0'); end + Vo.dat = zeros(Vo.dim,'single'); Vo.dt(1) = 16; Vo.pinfo = [1;0;0]; + + Vp0t = res.image; + if isfield(Vp0t,'private'), Vp0t = rmfield(Vp0t,'private'); end + if isfield(Vp0t,'mat0'), Vp0t = rmfield(Vp0t,'mat0'); end + Vp0t.dt(1) = 16; + Vp0t.pinfo = [1;0;0]; + Vp0t.dat = Yp0; + + % resampling and corrections of the Yp0 + % Vp0t = spm_write_vol(Vp0t,double(Yp0)); + [Vtpm,Yp0] = cat_vol_imcalc(Vp0t,Vo,'i1',struct('interp',2,'verb',0)); + rf = 50; + Yp0 = single(Yp0); + Yp0r = round(Yp0*rf)/rf; + YMR = false(size(Yp0)); + for i=1:4, YMR = YMR | (Yp0>(i-1/rf) & Yp0<(i+1/rf)); end + Yp0(YMR) = Yp0r(YMR); clear YMR Ynr; + + % resampling of the corrected image + Vp0t.dat = Ym; + [Vtpm,Ym] = cat_vol_imcalc(Vp0t,Vo,'i1',struct('interp',6,'verb',0)); + Ym = single(Ym); + end + + else + error('MATLAB:cat_vol_qa202205:inputerror',... + 'Wrong number/structure of input elements!'); + end + otherwise + error('MATLAB:cat_vol_qa202205:inputerror',... + 'Wrong number/structure of input elements!'); + end + if ~exist('species','var'), species='human'; end + + + % + % -------------------------------------------------------------------- + [QA,QMAfn] = cat_stat_marks('init'); + stime = clock; + + + + % Print options + % -------------------------------------------------------------------- + opt.snspace = [70,7,3]; + opt.snspace = [100,7,3]; + Cheader = {'scan'}; + Theader = sprintf(sprintf('%%%ds:',opt.snspace(1)-1),'scan'); + Tline = sprintf('%%5d) %%%ds:',opt.snspace(1)-8); + Tline2 = sprintf('%%5d) %%6s%%%ds:',opt.snspace(1)-14); + Tavg = sprintf('%%%ds:',opt.snspace(1)-1); + TlineE = sprintf('%%5d) %%%ds: %%s',opt.snspace(1)-7); + for fi=1:numel(QMAfn) + Cheader = [Cheader QMAfn{fi}]; %#ok + Theader = sprintf(sprintf('%%s%%%ds',opt.snspace(2)),Theader,... + QMAfn{fi}(1:min(opt.snspace(2)-1,numel(QMAfn{fi})))); + Tline = sprintf('%s%%%d.%df',Tline,opt.snspace(2),opt.snspace(3)); + Tline2 = sprintf('%s%%%d.%df',Tline2,opt.snspace(2),opt.snspace(3)); + Tavg = sprintf('%s%%%d.%df',Tavg,opt.snspace(2),opt.snspace(3)); + end + Cheader = [Cheader 'IQR']; + Theader = sprintf(sprintf('%%s%%%ds',opt.snspace(2)),Theader,'IQR'); + Tline = sprintf('%s%%%d.%df',Tline,opt.snspace(2),opt.snspace(3)); + Tline2 = sprintf('%s%%%d.%df',Tline2,opt.snspace(2),opt.snspace(3)); + Tavg = sprintf('%s%%%d.%df',Tavg,opt.snspace(2),opt.snspace(3)); + Cheader = [Cheader 'SIQR']; + Theader = sprintf(sprintf('%%s%%%ds',opt.snspace(2)),Theader,'SIQR'); + Tline = sprintf('%s%%%d.%df\n',Tline,opt.snspace(2),opt.snspace(3)); + Tline2 = sprintf('%s%%%d.%df\n',Tline2,opt.snspace(2),opt.snspace(3)); + Tavg = sprintf('%s%%%d.%df\n',Tavg,opt.snspace(2),opt.snspace(3)); + + + + + + + % estimation part + switch action + case {'p0','p#','c#','*#','p0+','p#+','c#+','*#+'} + % loop for multiple files + % return for empty input + if isempty(Pp0) || (isempty(Pp0{1}) && numel(Pp0)<=1) + cat_io_cprintf('com','No images for QA!\n'); + return + end + + if opt.verb>1 + fprintf('\n%s\n\n%s\n%s\n', ... + sprintf('CAT Preprocessing T1 Quality Control (%s):',... + sprintf('Rev: %s',rev_cat)), Theader,repmat('-',size(Theader))); + end + + qamat = nan(numel(Po),numel(QMAfn)); + qamatm = nan(numel(Po),numel(QMAfn)); + mqamatm = 10.5*ones(numel(Po),2); + + + QAS = struct(); QAR = struct(); + QAR.mark2rps = @(mark) min(100,max(0,105 - mark*10)) + isnan(mark).*mark; + + for fi=1:numel(Pp0) + try + [pp,ff,ee] = spm_fileparts(Po{fi}); + if exist(fullfile(pp,[ff ee]),'file') + Vo = spm_vol(Po{fi}); + else + error('cat_vol_qa202205:noYo','No original image.'); + end + + Vm = spm_vol(Pm{fi}); + Vp0 = spm_vol(Pp0{fi}); + if any(Vp0.dim ~= Vm.dim) + [Vx,Yp0] = cat_vol_imcalc(Vp0,Vm,'i1',struct('interp',2,'verb',0)); + else + Yp0 = single(spm_read_vols(Vp0)); + end + Yp0(isnan(Yp0) | isinf(Yp0)) = 0; + if 0 %~isempty(Pm{fi}) && exist(Pm{fi},'file') + Ym = single(spm_read_vols(spm_vol(Pm{fi}))); + Ym(isnan(Yp0) | isinf(Yp0)) = 0; + elseif 1 %end + %if ~exist(Ym,'var') || round( cat_stat_nanmean(Ym(round(Yp0)==3)) * 100) ~= 100 + Ym = single(spm_read_vols(spm_vol(Po{fi}))); + Ym(isnan(Yp0) | isinf(Yp0)) = 0; + Yw = Yp0>2.95 | cat_vol_morph( Yp0>2.25 , 'e'); + Yb = cat_vol_approx( Ym .* Yw + Yw .* min(Ym(:)) ) - min(Ym(:)); + %Yb = Yb / mean(Ym(Yw(:))); + Ym = Ym ./ max(eps,Yb); + + else + error('cat_vol_qa202205:noYm','No corrected image.'); + end + rmse = (mean(Ym(Yp0(:)>0) - Yp0(Yp0(:)>0)/3).^2).^0.5; + if rmse>0.2 + cat_io_cprintf('warn','Segmentation is maybe not fitting to the image (RMSE(Ym,Yp0)=%0.2f)?:\n %s\n %s',rmse,Pm{fi},Pp0{fi}); + end + + res.image = spm_vol(Pp0{fi}); + [QASfi,QAMfi] = cat_vol_qa202205('cat12',Yp0,Vo,Ym,res,species,opt); + + if isnan(QASfi.qualitymeasures.NCR) + fprintf(''); + end + + + QAS = cat_io_updateStruct(QAS,QASfi,0,fi); + QAR = cat_io_updateStruct(QAR,QAMfi,0,fi); + + + % color for the differen mark cases (opt.process) + for fni=1:numel(QMAfn) + qamat(fi,fni) = QAS(fi).qualitymeasures.(QMAfn{fni}); + qamatm(fi,fni) = QAR(fi).qualityratings.(QMAfn{fni}); + end + mqamatm(fi,1) = QAR(fi).qualityratings.IQR; + mqamatm(fi,1) = max(0,min(10.5, mqamatm(fi,1))); + mqamatm(fi,2) = QAR(fi).qualityratings.SIQR; + mqamatm(fi,2) = max(0,min(10.5, mqamatm(fi,2))); + + + %% print the results for each scan + if opt.verb>1 + if opt.orgval + cat_io_cprintf(opt.MarkColor(max(1,floor( mqamatm(fi,2)/9.5 * ... + size(opt.MarkColor,1))),:),sprintf(Tline,fi,... + QAS(fi).filedata.fnames, ... spm_str_manip(QAS(fi).filedata.file,['f' num2str(opt.snspace(1) - 14)]),... + qamat(fi,:),max(1,min(6,mqamatm(fi,:))))); + else + cat_io_cprintf(opt.MarkColor(max(1,floor( mqamatm(fi,2)/9.5 * ... + size(opt.MarkColor,1))),:),sprintf(Tline,fi,... + QAS(fi).filedata.fnames, ... spm_str_manip(QAS(fi).filedata.file,['f' num2str(opt.snspace(1) - 14)]),... + qamatm(fi,:),max(1,min(6,mqamatm(fi,:))))); + end + end + catch %#ok ... normal ""catch err"" does not work for MATLAB 2007a + try %#ok + e = lasterror; %#ok ... normal ""catch err"" does not work for MATLAB 2007a + + switch e.identifier + case {'cat_vol_qa202205:noYo','cat_vol_qa202205:noYm','cat_vol_qa202205:badSegmentation'} + em = e.identifier; + otherwise + em = ['ERROR:\n' repmat(' ',1,10) e.message '\n']; + for ei=1:numel(e.stack) + em = sprintf('%s%s%5d: %s\n',em,repmat(' ',1,10),... + e.stack(ei).line(end),e.stack(ei).name); + end + end + + [pp,ff] = spm_fileparts(Po{fi}); + QAS(fi).filedata.fnames = [spm_str_manip(pp,sprintf('k%d',floor( (opt.snspace(1)-19) /3) - 1)),'/',... + spm_str_manip(ff,sprintf('k%d',(opt.snspace(1)-19) - floor((opt.snspace(1)-14)/3)))]; + cat_io_cprintf(opt.MarkColor(end,:),sprintf(TlineE,fi,... + QAS(fi).filedata.fnames,[em '\n'])); +% spm_str_manip(Po{fi},['f' num2str(opt.snspace(1) - 14)]),em)); + end + end + end + + + + % sort by mean mark + % ---------------------------------------------------------------- + if opt.sortQATm && numel(Po)>1 + % sort matrix + [smqamatm,smqamatmi] = sort(mqamatm(:,2),'ascend'); + sqamatm = qamatm(smqamatmi,:); + sqamat = qamat(smqamatmi,:); + + % print matrix + if opt.verb>0 + fprintf('%s\n',repmat('-',size(Theader))); + for fi=1:numel(QAS) + if opt.orgval + cat_io_cprintf(opt.MarkColor(min(size(opt.MarkColor,1),... + round( mqamatm(smqamatmi(fi),2)/9.5 * ... + size(opt.MarkColor,1))),:),sprintf(... + Tline2,fi,sprintf('(%d)',smqamatmi(fi)),... + QAS(smqamatmi(fi)).filedata.fnames, ... + ...spm_str_manip(QAS(smqamatmi(fi)).filedata.file,['f' num2str(opt.snspace(1) - 14)]),... + sqamat(fi,:),max(1,min(6,mqamatm(smqamatmi(fi),:))))); + else + cat_io_cprintf(opt.MarkColor(max(1,min(size(opt.MarkColor,1),... + round( mqamatm(smqamatmi(fi),2)/9.5 * ... + size(opt.MarkColor,1)))),:),sprintf(... + Tline2,fi,sprintf('(%d)',smqamatmi(fi)),... + spm_str_manip(Pp0{fi},'l80'), ... QAS(smqamatmi(fi)).filedata.fnames, ... + ...spm_str_manip(QAS(smqamatmi(fi)).filedata.file,['f' num2str(opt.snspace(1) - 14)]),... + sqamatm(fi,:),mqamatm(smqamatmi(fi),:))); + end + end + end + else + %[smqamatm,smqamatmi] = sort(mqamatm,'ascend'); + %sqamatm = qamatm(smqamatmi,:); + end + % print the results for each scan + if opt.verb>1 && numel(Pp0)>1 + fprintf('%s\n',repmat('-',size(Theader))); + if opt.orgval + fprintf(Tavg,'mean',cat_stat_nanmean(qamat,1), cat_stat_nanmean(mqamatm,1)); %#ok + fprintf(Tavg,'std' , cat_stat_nanstd(qamat,1), cat_stat_nanstd(mqamatm,1)); %#ok + else + fprintf(Tavg,'mean',cat_stat_nanmean(qamatm,1), cat_stat_nanmean(mqamatm,1)); %#ok + fprintf(Tavg,'std' , cat_stat_nanstd(qamatm,1), cat_stat_nanstd(mqamatm,1)); %#ok + end + %fprintf('%s\n',repmat('-',size(Theader))); + %fprintf(Tavg,'mean',mean(qamat,1)); + %fprintf(Tavg,'std', std(qamat,1)); + end + if opt.verb>0, fprintf('\n'); end + + + + % result tables (cell structures) + % ---------------------------------------------------------------- + if nargout>2 && opt.write_csv + QAT = [Cheader(1:end-1); ... there is no mean for the original measures + Po , num2cell(qamat); ... + 'mean' , num2cell(cat_stat_nanmean(qamat,1)); ... + 'std' , num2cell( cat_stat_nanstd(qamat,1,1))]; + QATm = [Cheader; ... + Po , num2cell(qamatm) , ... + num2cell(cat_stat_nanmean(qamatm,2)); ... + 'mean' , num2cell(cat_stat_nanmean(qamatm,1)) , ... + num2cell(cat_stat_nanmean(mqamatm,1)); ... + 'std' , num2cell( cat_stat_nanstd(qamatm,1,1)), ... + num2cell( cat_stat_nanstd(mqamatm,1))]; + + + % write csv results + % -------------------------------------------------------------- + if opt.write_csv + pp = spm_fileparts(Pp0{1}); + cat_io_csv(fullfile(pp,reportfolder,[opt.prefix num2str(numel(Vo),'%04d') ... + 'cat_vol_qa202205_values.csv']),QAT); + cat_io_csv(fullfile(pp,reportfolder,[opt.prefix num2str(numel(Vo),'%04d') ... + 'cat_vol_qa202205_marks.csv']),QATm); + end + end + + if opt.verb>0 + fprintf('Quality Control for %d subject was done in %0.0fs\n', ... + numel(Pp0),etime(clock,stime)); fprintf('\n'); + end + + + case 'cat12err' + + % file information + % ---------------------------------------------------------------- + [pp,ff,ee] = spm_fileparts(Vo.fname); + if strcmp(ee,'.gz'), [~,ff] = spm_fileparts(ff); ee = '.nii.gz'; end + [pp0,ff0,ee0] = spm_fileparts(Pp0); + [QAS.filedata.path,QAS.filedata.file] = spm_fileparts(Vo.fname); + QAS.filedata.fname = Vo.fname; + QAS.filedata.F = Vo.fname; + QAS.filedata.Fm = fullfile(pp0,['m' ff ee0]); + QAS.filedata.Fp0 = fullfile(pp0,['p0' ff ee0]); + QAS.filedata.fnames = [spm_str_manip(pp,sprintf('k%d',... + floor( max(opt.snspace(1)-19-ff,opt.snspace(1)-19)/3) - 1)),'/',... + spm_str_manip(ff,sprintf('k%d',... + (opt.snspace(1)-19) - floor((opt.snspace(1)-14)/3)))]; + + + % software, parameter and job information + % ---------------------------------------------------------------- + [nam,rev_spm] = spm('Ver'); + QAS.software.version_spm = rev_spm; + if strcmpi(spm_check_version,'octave') + QAS.software.version_octave = version; + else + A = ver; + for i=1:length(A) + if strcmp(A(i).Name,'MATLAB') + QAS.software.version_matlab = A(i).Version; + end + end + clear A + end + % 1 line: Matlab, SPM12, CAT12 version number and GUI and experimental mode + if ispc, OSname = 'WIN'; + elseif ismac, OSname = 'MAC'; + else, OSname = 'LINUX'; + end + + QAS.software.system = OSname; + QAS.software.version_cat = ver_cat; + if ~isfield(QAS.software,'version_segment') + QAS.software.version_segment = rev_cat; + end + QAS.software.revision_cat = rev_cat; + try + QAS.hardware.numcores = max(cat_get_defaults('extopts.nproc'),1); + catch + QAS.hardware.numcores = 1; + end + + + % save important preprocessing parameter + % remove LAS + QAS.parameter.opts = opt.job.opts; + QAS.parameter.extopts = rmfield(opt.job.extopts,... + {'LAB','atlas','satlas','darteltpms','shootingtpms','fontsize'}); + %QAS.parameter.output = opt.job.output; + QAS.parameter.caterr = opt.caterr; + QAS.error = opt.caterrtxt; + + % export + if opt.write_xml + cat_io_xml(fullfile(pp,reportfolder,[opt.prefix ff '.xml']),QAS,'write'); + end + + case 'cat12' + % estimation of the measures for the single case + +[pp,ff,ee] = spm_fileparts(Vo.fname); Pp0 = fullfile(pp,mrifolder,['p0' ff ee]); +if opt.rerun || cat_io_rerun(Vo.fname, fullfile(pp,reportfolder,[opt.prefix ff '.xml']) ) || ... + cat_io_rerun(Pp0, fullfile(pp,reportfolder,[opt.prefix ff '.xml']) ) + + % file information + % ---------------------------------------------------------------- + [pp,ff,ee] = spm_fileparts(Vo.fname); + if strcmp(ee,'.gz'), [~,ff] = spm_fileparts(ff); ee = '.nii.gz'; end + [pp0,ff0,ee0] = spm_fileparts(Pp0); + [QAS.filedata.path,QAS.filedata.file] = spm_fileparts(Vo.fname); + QAS.filedata.fname = Vo.fname; + QAS.filedata.F = Vo.fname; + QAS.filedata.Fm = fullfile(pp0,['m' ff ee0]); + QAS.filedata.Fp0 = fullfile(pp0,['p0' ff ee0]); + QAS.filedata.fnames = [spm_str_manip(pp,sprintf('k%d',... + floor( max(opt.snspace(1)-19-ff,opt.snspace(1)-19)/3) - 1)),'/',... + spm_str_manip(ff,sprintf('k%d',... + (opt.snspace(1)-19) - floor((opt.snspace(1)-14)/3)))]; + + + % software, parameter and job information + % ---------------------------------------------------------------- + [nam,rev_spm] = spm('Ver'); + if ispc, OSname = 'WIN'; + elseif ismac, OSname = 'MAC'; + else OSname = 'LINUX'; + end + + QAS.software.system = char(OSname); + QAS.software.version_spm = rev_spm; + if strcmpi(spm_check_version,'octave') + QAS.software.version_matlab = ['Octave ' version]; + else + A = ver; + for i=1:length(A) + if strcmp(A(i).Name,'MATLAB') + QAS.software.version_matlab = A(i).Version; + end + end + clear A + end + QAS.software.version_cat = ver_cat; + if ~isfield(QAS.software,'version_segment') + QAS.software.version_segment = rev_cat; + end + QAS.software.revision_cat = rev_cat; + QAS.software.function = which('cat_vol_qa202205'); + QAS.software.markdefs = which('cat_stat_marks'); + QAS.software.qamethod = action; + QAS.software.date = datestr(clock,'yyyymmdd-HHMMSS'); + % RD202007: not requried + %{ + %warning off + %QAS.software.opengl = opengl('INFO'); + %QAS.software.opengldata = opengl('DATA'); + %warning on + %} + QAS.software.cat_warnings = cat_io_addwarning; + % replace matlab newlines by HTML code + for wi = 1:numel( QAS.software.cat_warnings ) + QAS.software.cat_warnings(wi).message = cat_io_strrep( QAS.software.cat_warnings(wi).message , {'\\n', '\n'} , {'
','
'} ); + end + + %QAS.parameter = opt.job; + if isfield(opt,'job') && isfield(opt.job,'opts'), QAS.parameter.opts = opt.job.opts; end + if isfield(opt,'job') && isfield(opt.job,'extopts'), QAS.parameter.opts = opt.job.extopts; end + if exist('res','var') + rf = {'Affine','Affine0','lkp','mn','vr','ll'}; % important SPM preprocessing variables + for rfi=1:numel(rf) + if isfield(res,rf{rfi}), QAS.SPMpreprocessing.(rf{rfi}) = res.(rf{rfi}); end + end + end + + + %% resolution, boundary box + % --------------------------------------------------------------- + vx_vol = sqrt(sum(Vo.mat(1:3,1:3).^2)); + vx_voli = sqrt(sum(V.mat(1:3,1:3).^2)); + Yp0toC = @(Yp0,c) 1-min(1,abs(Yp0-c)); + + % resolution + QAS.qualitymeasures.res_vx_vol = vx_vol; + if 1 % CAT internal resolution + QAS.qualitymeasures.res_vx_voli = vx_voli; + end + QAS.qualitymeasures.res_RMS = cat_stat_nanmean(vx_vol.^2).^0.5; + % further unused measure (just for test/comparison) + %QAS.qualitymeasures.res_isotropy = max(vx_vol)./min(vx_vol); + %QAS.qualitymeasures.res_vol = prod(abs(vx_vol)); + %QAS.qualitymeasures.res_MVR = mean(vx_vol); + + %% boundary box - brain tissue next to image boundary + % RD20220415: + % * Although it is quite rare that the boundary box is to small and the + % brain scan is incomplete, it is of course essential to detect such + % cases: see OpenNeuro:BEANstudy: https://openneuro.org/datasets/ds003877/versions/1.0.1 + % * In addition, inhomogeneities close to image boundaries can be a + % severe problem that can be seen only be trained experts. The bias + % can even result a distorted cortex-like structure with normal + % thickness values. + % * need some tests + Ybw = cat_vbdist(single(Yp0<0.5),true(size(Yp0)),vx_vol) - ... + cat_vbdist(single(Yp0>0.5),true(size(Yp0)),vx_vol); + Ybb = Ybw>0 & Ybw<2*mean(vx_vol); sumYbb = sum(Ybb(:)); % use the brain boundary for normalization + M = ones(size(Yp0),'single'); + dmm = [10 5]; % inner and outer boundary range in mm + Ybw = max(0,Ybw + dmm(2)); % in mm + for bbth = 1:ceil( dmm(1) / cat_stat_nanmean(vx_vol) ) + M(bbth:end-bbth+1,bbth:end-bbth+1,bbth:end-bbth+1) = ... + 2 * (floor( dmm(1) / cat_stat_nanmean(vx_vol) ) - bbth + 1) / floor( dmm(1) / cat_stat_nanmean(vx_vol) ); + end + QAS.qualitymeasures.res_BB = sum( (1+Yp0(:)) .* Ybw(:) .* M(:)) / sumYbb * prod(abs(vx_vol)); + + + %% check segmentation + spec = species; for ai=num2str(0:9); spec = strrep(spec,ai,''); end + bvol = species; for ai=char(65:122); bvol = strrep(bvol,ai,''); end; bvol = str2double(bvol); + + subvol = [sum(Yp0(:)>2.5 & Yp0(:)<3.1)*prod(vx_vol)/1000,... + sum(Yp0(:)>1.5 & Yp0(:)<2.5)*prod(vx_vol)/1000,... + sum(Yp0(:)>0.5 & Yp0(:)<1.5)*prod(vx_vol)/1000]; + + if isempty(bvol) + switch spec + case 'human' + bvol = 1400; + otherwise + warning('cat_vol_qa202205:species',... + sprintf('Unknown species %s (C=%0.0f,G=%0.0f,W=%0.0f).',species,subvol)); %#ok + end + end + if sum(subvol)bvol*3 + warning('cat_vol_qa202205:badSegmentation',... + sprintf('Bad %s segmentation (C=%0.0f,G=%0.0f,W=%0.0f).',species,subvol)) %#ok + end + if ~isfield(QAS,'subjectmeasures') + %% in case of external/batch calls + QAS.subjectmeasures.vol_TIV = sum(Yp0(:)>0) .* prod(vx_vol) / 1000; + for i = 1:3 + QAS.subjectmeasures.vol_abs_CGW(i) = sum( Yp0toC(Yp0(:),i)) .* prod(vx_vol) / 1000; + QAS.subjectmeasures.vol_rel_CGW(i) = QAS.subjectmeasures.vol_abs_CGW(i) ./ ... + QAS.subjectmeasures.vol_TIV; + end + end + + %% estimate QA + % --------------------------------------------------------------- + % remove space arount the brain for speed-up + [Yo,Ym,Yp0] = cat_vol_resize({Yo,Ym,Yp0},'reduceBrain',vx_vol,4,Yp0>1.5); + + % rought contast and noise estimation to get a stable T1 map for threshold estimation + T1th = [cat_stat_nanmedian(Ym(Yp0toC(Yp0(:),1)>0.9)) ... + cat_stat_nanmedian(Ym(Yp0toC(Yp0(:),2)>0.9)) ... + cat_stat_nanmedian(Ym(Yp0toC(Yp0(:),3)>0.9))]; + noise = max(0,min(1,cat_stat_nanstd(Ym(Yp0(:)>2.9)) / min(abs(diff(T1th))))); + + Yms = Ym+0; spm_smooth(Yms,Yms,repmat(double(noise)*4,1,3)); % smoothing to reduce high frequency noise + + % basic tissue classes - erosion to avoid PVE, std to avoid other tissues (like WMHs) + if T1th(1) < T1th(2) && T1th(2) < T1th(3) + voli = @(v) (v ./ (pi * 4./3)).^(1/3); + rad = voli( QAS.subjectmeasures.vol_TIV) ./ cat_stat_nanmean(vx_vol); + Ysc = 1-cat_vol_smooth3X(Yp0<1 | Ym==0,min(24,max(16,rad*2))); % fast 'distance' map + Ycm = cat_vol_morph(Yp0>0.5 & Yp0<1.5 & Yms0.75 & Yp0<1.25;% avoid PVE & ventricle focus + if sum(Ycm(:)>0)<10; Ycm=cat_vol_morph(Yp0>0.5 & Yp0<1.5 & Yms0)<10; Ycm=Yp0>0.5 & Yms0)<10; Ycm=Yp0>0.5 & Yp0<1.5; end + %Ycm = Ycm | (Yp0==1 & Ysc>0.7 & Yms1.1,'e') & cat_vol_morph(Yp0<2.9,'e'); % avoid PVE 2 + Ygm = (Ygm1 | Ygm2) & Ysc<0.9; % avoid PVE & no subcortex + Ywm = cat_vol_morph(Yp0>2.1,'e') & Yp0>2.9 & ... % avoid PVE & subcortex + Yms>min(cat_stat_nanmean(T1th(2:3)),(T1th(2) + 2*noise*abs(diff(T1th(2:3))))); % avoid WMHs2 + else + Ycm = cat_vol_morph(Yp0>0 & Yp0<2,'e'); + Ygm = cat_vol_morph(Yp0>1 & Yp0<3,'e'); + Ywm = cat_vol_morph(Yp0>2 & Yp0<4,'e'); + end + clear Ygm1 Ygm2; % Ysc; + + %% further refinements of the tissue maps + if T1th(1) < T1th(2) && T1th(2) < T1th(3) + T2th = [median(Yms(Ycm)) median(Yms(Ygm)) median(Yms(Ywm))]; + Ycm = Ycm & Yms>(T2th(1)-16*noise*diff(T2th(1:2))) & Ysc &... + Yms<(T2th(1)+0.1*noise*diff(T2th(1:2))); + if sum(Ycm(:)>0)<10; Ycm=cat_vol_morph(Yp0>0.5 & Yp0<1.5 & Yms0)<10; Ycm=Yp0>0.5 & Yms(T2th(2)-2*noise*abs(diff(T1th(2:3)))) & Yms<(T2th(2)+2*noise*abs(diff(T1th(2:3)))); + Ygm(smooth3(Ygm)<0.2) = 0; + end + Ycm = cat_vol_morph(Ycm,'lc'); % to avoid holes + Ywm = cat_vol_morph(Ywm,'lc'); % to avoid holes + Ywe = cat_vol_morph(Ywm,'e'); + + +%% new resolution thing +% ------------------------------------------------------------------------- +% Although voxel resolution is a good measure in most raw data, interpolated +% or resampled data, e.g. by interpolation/resampling/reslicing or directly +% within the protocol/reconstruction process. +% Although the BWP did not ofter a direct independent solution, we can use +% any image and resample or smooth it. Real data test are highly important +% to avoid unforeseen side effects but finaly the evaluation has to take +% place also on the BWP, where the measure have to be tested for possible +% side effects of noise (could be a problem) and inhomogeneities (should +% be ok). +% - interpolate/reduce by a factor: 0.5x, 0.75x, 1.0x (low-res >= 1.0 mm) +% 1.0x, 1.50x, 2.0x (high-res <= 0.7 mm) +% - sampling to a specific resolution: 0.4, 0.6, 0.8, 1.0, 1.2 mm +% - smoothing in mm: 0.2, 0.4, 0.6, 0.8, 1.0 mm +% ------------------------------------------------------------------------- + + +%% A) by gradient (RD20220324) +% ------------------------------------------------------------------------- +% The basic idea is that edges in smoothed and interpolated images are +% softer/smoother and that the slope is simply smaller compared to +% sharp data. There are also the cases of to sharp images, e.g. +% binarized data like the SPM segmention with very hard partial volume +% effect. +% Of course there are side effects from noise but as far as we have an +% independent noise estimation we can maybe include this. +% In addition, edges beween WM and CSF are stronger and the CSF/GM +% boundary is probably blurred. Hence, we quantify only voxels at the +% WM/GM boudnary and limit also the normalized images with some GM-like +% value. +% The first tests are promissing +% ------------------------------------------------------------------------- +for sm = 0 %-1:0.5:1 + %% + Yms = Ym + 0; %sm = -1; + if sm<0, Yms = round(Ym*3)/3*(0-sm) + Yms*(1+sm); end + if sm>0, spm_smooth(Yms,Yms,repmat(max(0,sm),1,3)); end + Ygrad = cat_vol_grad(max(2/3,min(1,Yms) .* (Yp0>0)) , vx_vol); + [res_ECR,b,c] = cat_stat_kmeans(Ygrad(Yp0(:)>2.05 & Yp0(:)<2.95),1); + %QAS.qualitymeasures.res_ECR = (abs(a-1/4) + abs(b - 0.025) ) / mean(vx_vol); + %fprintf(' s=%+0.2f: %0.4f + %0.4f ~ %0.4f , %0.4f \n', sm, a ,b , b-a, abs(a-1/4) + abs(b-0.02) ); + %ds('d2sm','',1,Yms,Ygrad,100) +end + +usekmeans = 1; + + +%% B) by smoothing (RD20220324) +% ------------------------------------------------------------------------- +% The basic idea was that smoothing has low effects on smooth data and +% that the difference between original and smoothed image should be +% neglidable. However, this is of course also effected by noise and +% anatomical features and seems to be not stable enough to been used. +% ------------------------------------------------------------------------- +if 0 + sm = 0.2:0.05:1; clear a b, dx = 1; + smx = 0; Ym2 = Ym + 0; if smx<0, Ym2 = round(Ym2*3)/3*(0-smx) + Ym2*(1+smx); end + if smx>0, spm_smooth(Ym2,Ym2,repmat(max(0,smx),1,3)); end + for smi = 1:numel(sm) + Yms = Ym2 + 0; spm_smooth(Yms,Yms,repmat(sm(smi),3,1)); % #### RD20220617: this line caused an error in some cases ?! ... + Ygrad = (Ym2 - Yms) .* (Yp0>0); + Ymsk = Yp0(:)>2 & Yp0(:)<3; %smooth3( Yp0>2 & Yp0<3 )>0.5; + % ################ KMEANS ################ + if usekmeans + a(smi) = cat_stat_kmeans(Ygrad(Ymsk(:))); %,1); + else + a(smi) = cat_stat_nanmean(Ygrad(Ymsk(:))); %,1); + end + end + cx = diff(a,dx); cx = (cx - min(cx)) ./ ( max(cx) - min(cx)); + %if cx(1)==1; cx=flip(cx); end + switch dx + case 1 + % 0.55 to 0.45 to 0.35 + % fprintf(' s=%+0.2f: %0.4f %0.4f \n', smx, cx(1) , sm( find(diff([cx,inf])>0,1,'first')) ); %ds('d2sm','',1,Yms,Ygrad,100) + case 2 + % fprintf(' s=%+0.2f: %0.4f %0.4f \n', smx, mean( diff(a,dx) ) , sm( find(cx>0.9,1,'first')) ); %ds('d2sm','',1,Yms,Ygrad,100) + end +end +%QAS.qualitymeasures.RESsmooth = +%figure(1000 + round(smx*10)); plot(sm(1:end-dx),cx) +% ------------------------------------------------------------------------- + + +% Image/processing quality: Euler Number of Surface +% ------------------------------------------------------------------------- +% It is known (and was shown) that lower image quality correlates with the +% number of surface defects. However, ""abnormal"" anatomy can also cause +% problems because sulci are blurred in children or gyri are underdeveloped +% /unmyelinated in childen or atrophied in elderly. +% Moreover, we avoid surface-based measures to be open for fast VBM solutions. +% However, it would be possible to create an intial surface based on the +% WM segment and estimate the number of surface defects. +% ------------------------------------------------------------------------- + + + %% low resolution tissue intensity maps (smoothing) + % High frequency noise is mostly uncritical as far as simple smoothing can reduce it. + % Although the very low frequency interferences (inhomogeneity) is unproblematic in most cases, + % but will influence the noise pattern. + % But most important is the noise with the medium high frequencies, that we try do detect by + % reducing the very high and low noise pattern by filtering and pixel smoothing by reduction. + res = 2; vx_volx = 1; + Yos = cat_vol_localstat(Yo,Ywm,1,1); Yo(Yos>0)=Yos(Yos>0); % reduce high frequency noise in WM + Yos = cat_vol_localstat(Yo,Ycm,1,1); Yo(Yos>0)=Yos(Yos>0); % reduce high frequency noise in CSF + + Yc = cat_vol_resize(Yo .* Ycm,'reduceV',vx_volx,res,32,'min'); % CSF thr. (minimum to avoid PVE) + Yg = cat_vol_resize(Yo .* Ygm,'reduceV',vx_volx,res,32,'meanm'); % GM thr. + Yw = cat_vol_resize(Yo .* Ywe,'reduceV',vx_volx,res,32,'meanm'); % WM thr. and bias correction (Ywme) + Ywc = cat_vol_resize(Ym .* Ywe,'reduceV',vx_volx,res,32,'meanm'); % for bias correction + Ywb = cat_vol_resize( (Yo + min(Yo(:))) .* Ywm,'reduceV',vx_volx,res,32,'max') - min(Yo(:)); % for WM inhomogeneity estimation (avoid PVE) + Ywn = cat_vol_resize(Yo .* Ywm,'reduceV',vx_volx,res,32,'meanm'); % for WM noise + Ycn = cat_vol_resize(Yo .* Ycm,'reduceV',vx_volx,res,32,'meanm'); % for CSF noise + Ycm = cat_vol_resize(Ycm ,'reduceV',vx_volx,res,32,'meanm'); % CSF thr. (minimum to avoid PVE) + Ygm = cat_vol_resize(Ygm ,'reduceV',vx_volx,res,32,'meanm'); % GM thr. + Ywm = cat_vol_resize(Ywm ,'reduceV',vx_volx,res,32,'meanm'); % WM thr. and bias correction (Ywme) + Ywe = cat_vol_resize(Ywe ,'reduceV',vx_volx,res,32,'meanm'); % WM thr. and bias correction (Ywme) + + % only voxel that were the product of + Yc = Yc .* (Ycm>=0.5); Yg = Yg .* (Ygm>=0.5); Yw = Yw .* (Ywe>=0.5); + Ywc = Ywc .* (Ywe>=0.5); Ywb = Ywb .* (Ywm>=0.5); Ywn = Ywn .* (Ywm>=0.5); + Ycn = Ycn .* (Ycm>=0.5); + + + %clear Ycm Ygm Ywm Ywme; + [Yo,Ym,Yp0,resr] = cat_vol_resize({Yo,Ym,Yp0},'reduceV',vx_volx,res,32,'meanm'); + resr.vx_volo = vx_vol; vx_vol=resr.vx_red .* resr.vx_volo; + + %% intensity scaling for normalized Ym maps like in CAT12 + +% ################ KMEANS ################ +if usekmeans + if cat_stat_nanmean(Yo(Yp0(:)>2))<0 + Ywc = Ywc .* (cat_stat_kmeans(Yo(Yp0(:)>2))/cat_stat_nanmean(2 - Ym(Yp0(:)>2))); % RD202004: negative values in chimp data showed incorrect scalling + else + Ywc = Ywc .* (cat_stat_kmeans(Yo(Yp0(:)>2))/cat_stat_nanmean(Ym(Yp0(:)>2))); + end +else + if cat_stat_nanmean(Yo(Yp0(:)>2))<0 + Ywc = Ywc .* (cat_stat_nanmean(Yo(Yp0(:)>2))/cat_stat_nanmean(2 - Ym(Yp0(:)>2))); % RD202004: negative values in chimp data showed incorrect scalling + else + Ywc = Ywc .* (cat_stat_nanmean(Yo(Yp0(:)>2))/cat_stat_nanmean(Ym(Yp0(:)>2))); + end +end + %% bias correction for original map, based on the + WI = zeros(size(Yw),'single'); WI(Ywc(:)~=0) = Yw(Ywc(:)~=0)./Ywc(Ywc(:)~=0); WI(isnan(Ywe) | isinf(WI) | Ywe==0) = 0; + WI = cat_vol_approx(WI,'rec',2); + WI = cat_vol_smooth3X(WI,1); + + Ywn = Ywn./max(eps,WI); Ywn = round(Ywn*1000)/1000; + Ymi = Yo ./max(eps,WI); Ymi = round(Ymi*1000)/1000; + Yc = Yc ./max(eps,WI); Yc = round(Yc *1000)/1000; + Yg = Yg ./max(eps,WI); Yg = round(Yg *1000)/1000; + Yw = Yw ./max(eps,WI); Yw = round(Yw *1000)/1000; + + clear WIs ; + + + % tissue segments for contrast estimation etc. + +% ################ KMEANS ################ +if usekmeans + CSFth = cat_stat_kmeans(Yc(~isnan(Yc(:)) & Yc(:)~=0)); + GMth = cat_stat_kmeans(Yg(~isnan(Yg(:)) & Yg(:)~=0)); + WMth = cat_stat_kmeans(Yw(~isnan(Yw(:)) & Yw(:)~=0)); + T3th = [CSFth GMth WMth]; +else + CSFth = cat_stat_nanmean(Yc(~isnan(Yc(:)) & Yc(:)~=0)); + GMth = cat_stat_nanmean(Yg(~isnan(Yg(:)) & Yg(:)~=0)); + WMth = cat_stat_nanmean(Yw(~isnan(Yw(:)) & Yw(:)~=0)); + T3th = [CSFth GMth WMth]; +end + + % estimate background + [Ymir,resYbg] = cat_vol_resize(Ymi,'reduceV',1,6,32,'meanm'); + try + warning 'off' 'MATLAB:cat_vol_morph:NoObject' + BGCth = min(T3th)/2; + Ybgr = cat_vol_morph(cat_vol_morph(Ymir0.5; clear Yosr Ybgr; + if sum(Ybg(:))<32, Ybg = cat_vol_morph(Yo0.5; clear Yosr Ybgr; + if sum(Ybg(:))<32, Ybg = cat_vol_morph(YoGMth + QAS.qualitymeasures.tissue_weighting = 'T1'; + elseif WMth0.5 & ~isinf(Yp0(:)))); + end + QAS.qualitymeasures.tissue_stdr = QAS.qualitymeasures.tissue_std ./ (WMth-BGth); + + % (relative) (mininum) tissue contrast ( CSF-GM-WM ) + % - the CSF threshold varies strongly due to bad segmentations, + % and anatomica variance, so its better to use GM-WM contrast + % and take care of overoptimisation with values strongly >1/3 + % of the relative contrast + contrast = min(abs(diff(QAS.qualitymeasures.tissue_mn(3:4)))) ./ abs(diff([min([CSFth,BGth]),max([WMth,GMth])])); % default contrast + contrast = contrast + min(0,13/36 - contrast) * 1.2; % avoid overoptimsization + QAS.qualitymeasures.contrast = contrast * (max([WMth,GMth])); + QAS.qualitymeasures.contrastr = contrast; + + + + QAS.qualitymeasures.res_ECR = 1 - abs( res_ECR / contrast).^1 ; + %fprintf(' ( %0.4f ) ', QAS.qualitymeasures.res_ECR); + + %% noise estimation (original (bias corrected) image) + % WM variance only in one direction to avoid WMHs! + rms=1; nb=1; + if 1 + NCww = sum(Ywn(:)>0) * prod(vx_vol); + NCwc = sum(Ycn(:)>0) * prod(vx_vol); + [Yos2,YM2,R] = cat_vol_resize({Ywn,Ywn>0},'reduceV',vx_vol,3,16,'meanm'); + signal_intensity = abs( diff( [min(BGth,CSFth) , max(GMth,WMth)] )); + NCRw = estimateNoiseLevel(Yos2,YM2>0.5,nb,rms) / signal_intensity / contrast ; + else + % RD202005: not correct working? + Ywmn = cat_vol_morph(Ywm,'o'); + NCww = sum(Ywmn(:)) * prod(vx_vol); + NCwc = sum(Ycm(:)) * prod(vx_vol); + signal_intensity = abs( diff( [min(BGth,CSFth) , max(GMth,WMth)] )); + [Yos2,YM2,R] = cat_vol_resize({Ywn,Ywmn},'reduceV',vx_vol,max(3 * min(vx_vol) ,3),16,'meanm'); + YM2 = cat_vol_morph(YM2,'o'); % we have to be sure that there are neigbors otherwise the variance is underestimated + NCRw = estimateNoiseLevel(Yos2,YM2>0.5,nb,rms) / signal_intensity / contrast ; + if isnan(NCRw) + NCRw = estimateNoiseLevel(Ywn,Ywmn,nb,rms) / signal_intensity / contrast ; + end + end + NCRw = NCRw * (1 + log(28 - prod(R.vx_red)))/(1 + log(28 - 1)); % compensate voxel averageing + if BGth<-0.1 && WMth<3, NCRw=NCRw/3; end% MT weighting + clear Yos0 Yos1 Yos2 YM0 YM1 YM2; + + %% CSF variance of large ventricle + % for typical T2 images we have too much signal in the CSF and can't use it for noise estimation! + wcth = 200; + if CSFthwcth + if 1 + [Yos2,YM2,red] = cat_vol_resize({Ycn,Ycn>0},'reduceV',vx_vol,3,16,'meanm'); + NCRc = estimateNoiseLevel(Yos2,YM2>0.5,nb,rms) / signal_intensity / contrast ; + else + % RD202005: not correct working? + [Yos2,YM2,red] = cat_vol_resize({Ycn,Ycm},'reduceV',vx_vol,max(3 * min(vx_vol) ,3),16,'meanm'); + NCRc = estimateNoiseLevel(Yos2,YM2>0.5,nb,rms) / signal_intensity / contrast ; + if isnan(NCRc) + NCRc = estimateNoiseLevel(Ycn,Ycm,nb,rms) / signal_intensity / contrast ; + end + end + clear Yos0 Yos1 Yos2 YM0 YM1 YM2; + else + red = R; + NCRc = 0; + NCwc = 0; + end + % 1/sqrt(volume) to compensate for noise differency due to different volumen size. + % Overall there are better chances to correct high resolution noise. + % Nitz W R. Praxiskurs MRT. Page 28. + NCwc = min(wcth,max(0,NCwc-wcth)); NCww = min(wcth,NCww) - NCwc; % use CSF if possible + if NCwc<3*wcth && NCww<10*wcth, NCRc = min(NCRc,NCRw); end + QAS.qualitymeasures.NCR = max(0,NCRw*NCww + NCRc*NCwc)/(NCww+NCwc); + QAS.qualitymeasures.NCR = real( QAS.qualitymeasures.NCR * 3 ); % abs(prod(resr.vx_volo*res))^0.4 * 5/4); %* 7.5; %15; + %QAS.qualitymeasures.CNR = 1 / QAS.qualitymeasures.NCR; +%fprintf('NCRw: %8.3f, NCRc: %8.3f, NCRf: %8.3f\n',NCRw,NCRc,(NCRw*NCww + NCRc*NCwc)/(NCww+NCwc)); + + + %% Bias/Inhomogeneity (original image with smoothed WM segment) + Yosm = cat_vol_resize(Ywb,'reduceV',vx_vol,3,32,'meanm'); Yosmm = Yosm~=0; % resolution and noise reduction + for si=1:max(1,min(3,round(QAS.qualitymeasures.NCR*4))), mth = min(Yosm(:)) + 1; Yosm = cat_vol_localstat(Yosm + mth,Yosmm,1,1) - mth; end + % BWP-like definition + QAS.qualitymeasures.ICR = cat_stat_nanstd(Yosm(Yosmm(:))) / signal_intensity / contrast; + %QAS.qualitymeasures.CIR = 1 / QAS.qualitymeasures.ICR; + % local concept that could work also on the BWP? + Yosm2 = cat_vol_localstat(Yosm,Yosmm,1,4) / mean(red.vx_volr)/3; +% QAS.qualitymeasures.ICRk = cat_stat_kmeans( (Yosm2(Yosmm(:)) / signal_intensity / contrast * 100 + 1).^4 ).^(1/4); +% fprintf('ICR: %8.3f, ICRk: %8.6f\n',QAS.qualitymeasures.ICR,QAS.qualitymeasures.ICRk); + + %% marks + QAR = cat_stat_marks('eval',1,QAS); + + % export + if opt.write_xml + QAS.qualityratings = QAR.qualityratings; + QAS.subjectratings = QAR.subjectratings; + QAS.ratings_help = QAR.help; + + cat_io_xml(fullfile(pp,reportfolder,[opt.prefix ff '.xml']),QAS,'write'); %struct('QAS',QAS,'QAM',QAM) + end +else + QAS = cat_io_xml(fullfile(pp,reportfolder,[opt.prefix ff '.xml']),'load'); %struct('QAS',QAS,'QAM',QAM) + QAR = cat_stat_marks('eval',1,QAS); +end + + clear Yi Ym Yo Yos Ybc + clear Ywm Ygm Ycsf Ybg + + end + + if (isempty(varargin) || isstruct(varargin{1})) && exist('Pp0','var') + varargout{1}.data = Pp0; + action = action2; + else + if nargout>1, varargout{2} = QAR; end + if nargout>0, varargout{1} = QAS; end + end + + +end +%======================================================================= +function def=defaults + % default parameter + def.verb = 2; % verbose level [ 0=nothing | 1=points | 2*=results ] + def.write_csv = 2; % final cms-file [ 0=dont write |1=write | 2=overwrite ] + def.write_xml = 1; % images base xml-file + def.sortQATm = 1; % sort QATm output + def.orgval = 0; % original QAM results (no marks) + def.avgfactor = 2; % + def.prefix = 'cat_'; % intensity scaled image + def.mprefix = 'm'; % prefix of the preprocessed image + def.process = 3; % used image [ 0=T1 | 1=mT1 | 2=avg | 3=both ] + def.calc_MPC = 0; + def.calc_STC = 0; + def.calc_MJD = 0; + def.method = 'spm'; + def.snspace = [70,7,3]; + def.nogui = exist('XT','var'); + def.rerun = 0; + def.MarkColor = cat_io_colormaps('marks+',40); +end + +function noise = estimateNoiseLevel(Ym,YM,r,rms,vx_vol) +% ---------------------------------------------------------------------- +% noise estimation within Ym and YM. +% ---------------------------------------------------------------------- + if ~exist('vx_vol','var') + vx_vol=[1 1 1]; + end + if ~exist('r','var') + r = 1; + else + r = min(10,max(max(vx_vol),r)); + end + if ~exist('rms','var') + rms = 1; + end + + Ysd = cat_vol_localstat(single(Ym),YM,r ,4); + Ysd2 = cat_vol_localstat(single(Ym),YM,r+1,4); % RD20210617: more stable for sub-voxel resolutions ? + Ysd = Ysd * mod(r,1) + (1-mod(r,1)) * Ysd2; % RD20210617: more stable for sub-voxel resolutions ? + %noise = cat_stat_nanstat1d(Ysd(YM).^rms,'median').^(1/rms); % RD20210617: + noise = cat_stat_kmeans(Ysd(YM),1); % RD20210617: more robust ? +end +%======================================================================= +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_io_seg2cgw.m",".m","1073","31","function [c,g,w]=cat_io_seg2cgw(seg) +% ______________________________________________________________________ +% Convert segment image into 3 images for CSF, GM and WM. +% +% [c,g,w]=cat_io_seg2cgw(seg) +% +% seg: p0 tissue segment image (0=BG,1=CSF,2=GM,3=WM) +% [c,g,w]: tissue class map with values from 0 to 1 +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + %if isa(char), fseg=seg; hseg=spm_vol(seg); seg=spm_read_vols(hseg); end + + c = seg .* (seg>0 & seg<1) + (2-seg).*(seg>=1 & seg<2); + g = (seg-1) .* (seg>1 & seg<2) + (3-seg).*(seg>=2 & seg<3); + w = (seg-2) .* (seg>2 & seg<3) + (4-seg).*(seg>=3 & seg<4); + + % for some loops in other functions... + %{ + for ci=1:3 + c1 = (v1-(ci-1)).* (v1>(ci-1) & v1=ci & v1<(ci+1)); + end + %} + +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_spm_preproc8.m",".m","46416","1136","function results = cat_spm_preproc8(obj) +% Combined Segmentation and Spatial Normalisation +% +% FORMAT results = spm_preproc8(obj) +% +% obj is a structure, and must have the following fields... +% image - a structure (array) of handles of individual scans, +% of the sort returned by spm_vol. Data can be +% multispectral, with N channels, but files must be in +% voxel-for-voxel alignment. +% biasfwhm - FWHM of bias field(s). There are N elements, one for +% each channel. +% biasreg - Regularisation of bias field estimation. N elements. +% tpm - Tissue probability map data, as generated by +% spm_load_priors. This would represent Kb different +% tissue classes - including air (background). +% lkp - A lookup table indicating which Gaussians should be used +% with each of the Kb tissue probability maps. For example, +% if there are 6 tissue types, with two Gaussians to +% represent each, except the 5th, which uses 4 Gaussians, +% then lkp=[1,1,2,2,3,3,4,4,5,5,5,5,6,6]. +% Affine - a 4x4 affine transformation matrix, such that the mapping +% from voxels in the individual to those in the template +% is by tpm.M\Affine*obj.image(1).mat. +% reg - Regularisation for the nonlinear registration of the +% template (tissue probability maps) to the individual. +% samp - The distance (mm) between samples. In order to achieve +% a reasonable speed, not all voxels in the images are +% used for the parameter estimation. Better segmentation +% would be expected if all were used, but this would be +% extremely slow. +% fwhm - A smoothness estimate for computing a fudge factor that +% tries to account for spatial covariance in the noise. +% +% obj also has some optional fields... +% mg - a 1xK vector (where K is the lengrh of obj.lkp). This +% represents the mixing proportions within each tissue. +% mn - an NxK matrix containing the means of the Gaussians. +% vr - an NxNxK matrix containing the covariances of each of +% the Gaussians. +% Tbias - a cell array encoding the parameterisation of each bias +% field. +% Twarp - the encoding of the nonlinear deformation field. +% +% Various estimated parameters are saved as fields of the results +% structure. Some of these are taken from the input, whereas others +% are estimated or optimised... +% results.image = obj.image; +% results.tpm = obj.tpm.V; +% results.Affine = obj.Affine; +% results.lkp = obj.lkp; +% results.MT = an affine transform used in conjunction with the +% parameterisation of the warps. +% results.Twarp = obj.Twarp; +% results.Tbias = obj.Tbias; +% results.mg = obj.mg; +% results.mn = obj.mn; +% results.vr = obj.vr; +% results.ll = Log-likelihood. +% +%_______________________________________________________________________ +% The general principles are described in the following paper, but some +% technical details differ. These include a different parameterisation +% of the deformations, the ability to use multi-channel data and the +% use of a fuller set of tissue probability maps. The way the mixing +% proportions are dealt with is also slightly different. +% +% Ashburner J & Friston KJ. ""Unified segmentation"". +% NeuroImage 26(3):839-851 (2005). +%_______________________________________________________________________ +% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging +% John Ashburner +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +% RD20200301: The wp_reg parameter was changed in SPM12 R7771 to 100 but +% we observed several processing problems in the initial SPM +% parameter estimation in cat_run but also in cat_main_gintnorm. +wp_reg = 1; % Bias wp towards 1/kB + +Affine = obj.Affine; +tpm = obj.tpm; +V = obj.image; +M = tpm.M\Affine*V(1).mat; +d0 = V(1).dim(1:3); +vx = sqrt(sum(V(1).mat(1:3,1:3).^2)); +sk = max([1 1 1],round(obj.samp*[1 1 1]./vx)); +[x0,y0,o] = ndgrid(1:sk(1):d0(1),1:sk(2):d0(2),1); +z0 = 1:sk(3):d0(3); +tiny = eps*eps; +lkp = obj.lkp; +if isempty(lkp) + K = 2000; + Kb = numel(tpm.dat); + use_mog = false; +else + K = numel(obj.lkp); + Kb = max(obj.lkp); + use_mog = true; +end + +kron = @(a,b) spm_krutil(a,b); + +% Some random numbers are used, so initialise random number generators to +% give the same results each time. +%rng('default'); + +% These will eventually need changing +% because using character strings to control RAND and RANDN is deprecated. +% Updated RD20200125 +% this function adds noise to the data to stabilize processing and we +% have to define a specific random pattern to get the same results each time +if exist('rng','file') == 2, rng('default'); rng(0); else, rand('state',0); randn('state',0); end + +% Fudge Factor - to (approximately) account for non-independence of voxels. +% Note that variances add, and that Var[a*x + b*y] = a^2*Var[x] + b^2*Var[y] +% Therefore the variance of i.i.d. noise after Gaussian smoothing is equal +% to the sum of the Gaussian function squared times the original variance. +% A Gaussian is given by g=sqrt(2*pi*s^2)^(-1/2)*exp(-0.5*x.^2/s^2); +% After squaring, this is (2*pi*s^2)^(-1)*exp(-x.^2/s^2), which is a scaled +% Gaussian. Letting s2 = 2/sqrt(2), this is equal to +% (4*pi*s^2)^(-1/2)*(2*pi*s2^2)^(-1/2)*exp(-0.5*x.^2/s2^2), from which +% the (4*pi*s^2)^(-1/2) factor comes from. +fwhm = obj.fwhm; % FWHM of image smoothness +vx = sqrt(sum(V(1).mat(1:3,1:3).^2)); % Voxel size +fwhm = fwhm+mean(vx); +s = fwhm/sqrt(8*log(2)); % Standard deviation +ff = prod(4*pi*(s./vx./sk).^2 + 1)^(1/2); + + +spm_diffeo('boundary',1); + +% Initialise Deformation +%----------------------------------------------------------------------- +% This part is fiddly because of the regularisation of the warps. +% The fact that displacement fields are only parameterised every few +% voxels means that the functions in spm_diffeo need tweaking to +% account for the difference between the units of displacement and +% the separation of the voxels (if that makes sense). + +% More work/thought is needed in terms of adjusting regularisation to +% account for different voxel sizes. I'm still not satisfied that +% this (rescaling the regularisaiton by prod(vx.*sk)) is optimal. +% The same thing applies to all the nonlinear warping code in SPM. +param = [sk.*vx prod(vx.*sk)*ff*obj.reg]; % FIX THIS (remove ""prod(vx.*sk)"") + +% Mapping from indices of subsampled voxels to indices of voxels in image(s). +MT = [sk(1) 0 0 (1-sk(1));0 sk(2) 0 (1-sk(2)); 0 0 sk(3) (1-sk(3));0 0 0 1]; + +% For multiplying and dividing displacements to map from the subsampled voxel indices +% and the actual image voxel indices. +sk4 = reshape(sk,[1 1 1 3]); + +d = [size(x0) length(z0)]; +if isfield(obj,'Twarp') + Twarp = obj.Twarp; + llr = -0.5*sum(sum(sum(sum(Twarp.*bsxfun(@times,spm_diffeo('vel2mom',bsxfun(@times,Twarp,1./sk4),param),1./sk4))))); +else + Twarp = zeros([d,3],'single'); + llr = 0; +end + + +% Initialise bias correction +%----------------------------------------------------------------------- +N = numel(V); +cl = cell(N,1); +args = {'C',cl,'B1',cl,'B2',cl,'B3',cl,'T',cl,'ll',cl}; +if use_mog + chan = struct(args{:}); +else + chan = struct(args{:},'hist',cl,'lik',cl,'alph',cl,'grad',cl,'lam',cl,'interscal',cl); +end + +for n=1:N + % GAUSSIAN REGULARISATION for bias correction + fwhm = obj.biasfwhm(n); + biasreg = obj.biasreg(n); + vx = sqrt(sum(V(n).mat(1:3,1:3).^2)); + d0 = V(n).dim; + sd = vx(1)*d0(1)/fwhm; d3(1) = ceil(sd*2); krn_x = exp(-(0:(d3(1)-1)).^2/sd.^2)/sqrt(vx(1)); + sd = vx(2)*d0(2)/fwhm; d3(2) = ceil(sd*2); krn_y = exp(-(0:(d3(2)-1)).^2/sd.^2)/sqrt(vx(2)); + sd = vx(3)*d0(3)/fwhm; d3(3) = ceil(sd*2); krn_z = exp(-(0:(d3(3)-1)).^2/sd.^2)/sqrt(vx(3)); + Cbias = kron(krn_z,kron(krn_y,krn_x)).^(-2)*biasreg*ff; + chan(n).C = sparse(1:length(Cbias),1:length(Cbias),Cbias,length(Cbias),length(Cbias)); + + % Basis functions for bias correction + chan(n).B3 = spm_dctmtx(d0(3),d3(3),z0); + chan(n).B2 = spm_dctmtx(d0(2),d3(2),y0(1,:)'); + chan(n).B1 = spm_dctmtx(d0(1),d3(1),x0(:,1)); + + % Initial parameterisation of bias field + if isfield(obj,'Tbias') && ~isempty(obj.Tbias{n}) + chan(n).T = obj.Tbias{n}; + else + chan(n).T = zeros(d3); + end +end + +% ========================================================================= +outputGUIlevel = 2; % output of command line report of outer iterations +AUCprint = [1 1 1]; % plot different stop criterial in the interactive SPM window +ll = -Inf; % default ll parameter +lllog = []; % ll log paraemter to estimate further ratings +if isfield(obj,'newtol'), newtol = obj.newtol; else, newtol = 1; end % use new interation criteria (0-no,1-yes-optimal,2-accurate) +if isfield(obj,'tol'), tol1 = obj.tol; else, tol1 = 1e-4; end % Stopping critera, for higher accuracy, use a smaller values +if newtol==1 % faster inner iteration, default 1e-4 + tol11 = 1e-2; % should be ok +elseif newtol==2 + tol11 = 1e-4; % SPM default +else + tol11 = tol1; % current CAT default +end +if cat_get_defaults('extopts.expertgui') >= outputGUIlevel + fprintf('\n cat_spm_preproc8: newtol=%d, tol1=%1.0e, tol11=%1.0e', newtol, tol1, tol11); +end +% ========================================================================= +if isfield(obj,'msk') && ~isempty(obj.msk) + VM = spm_vol(obj.msk); + if sum(sum((VM.mat-V(1).mat).^2)) > 1e-6 || any(VM.dim(1:3) ~= V(1).dim(1:3)) + error('Mask must have the same dimensions and orientation as the image.'); + end +end + +% Load the data +%----------------------------------------------------------------------- +nm = 0; % Number of voxels + +scrand = zeros(N,1); +for n=1:N + if spm_type(V(n).dt(1),'intt') + scrand(n) = V(n).pinfo(1); + end +end + +% Overall moments used later for regularising via a ``Wishart-style prior'' +mom0 = zeros(1,N); +mom1 = zeros(1,N); +mom2 = zeros(1,N); + +cl = cell(length(z0),1); +buf = struct('msk',cl,'nm',cl,'f',cl,'dat',cl,'bf',cl); +for z=1:length(z0) + % Load only those voxels that are more than 5mm up + % from the bottom of the tissue probability map. This + % assumes that the affine transformation is pretty close. + + %x1 = M(1,1)*x0 + M(1,2)*y0 + (M(1,3)*z0(z) + M(1,4)); + %y1 = M(2,1)*x0 + M(2,2)*y0 + (M(2,3)*z0(z) + M(2,4)); + z1 = M(3,1)*x0 + M(3,2)*y0 + (M(3,3)*z0(z) + M(3,4)); + e = sqrt(sum(tpm.M(1:3,1:3).^2)); + e = 5./e; % mm from edge of TPM + buf(z).msk = z1>e(3); + + % Initially load all the data, but prepare to exclude + % locations where any of the images is not finite, or + % is zero. We want this to work for skull-stripped + % images too. The -3924 and -1500 options have been + % added for CT data. + fz = cell(1,N); + for n=1:N + fz{n} = spm_sample_vol(V(n),x0,y0,o*z0(z),0); + buf(z).msk = buf(z).msk & isfinite(fz{n}) & (fz{n}~=0) & (fz{n}~=-3024) & (fz{n}~=-1500); + end + + if isfield(obj,'msk') && ~isempty(obj.msk) + % Exclude any voxels to be masked out + msk = spm_sample_vol(VM,x0,y0,o*z0(z),0); + buf(z).msk = buf(z).msk & msk; + end + + % Eliminate unwanted voxels + buf(z).nm = sum(buf(z).msk(:)); + nm = nm + buf(z).nm; + for n=1:N + if scrand(n) + % Data is an integer type, so to prevent aliasing in the histogram, small + % random values are added. It's not elegant, but the alternative would be + % too slow for practical use. + buf(z).f{n} = single(fz{n}(buf(z).msk)+rand(buf(z).nm,1)*scrand(n)-scrand(n)/2); + else + buf(z).f{n} = single(fz{n}(buf(z).msk)); + end + mom0(n) = mom0(n) + buf(z).nm; + mom1(n) = mom1(n) + sum(buf(z).f{n}); + mom2(n) = mom2(n) + sum(buf(z).f{n}.^2); + end + + % Create a buffer for tissue probability info + buf(z).dat = zeros([buf(z).nm,Kb],'single'); +end + +% Construct a ``Wishart-style prior'' (vr0) +vr0 = diag(mom2./mom0 - (mom1./mom0).^2)/Kb^2; +%for n=1:N +% if spm_type(V(n).dt(1),'intt') +% vr0(n,n) = vr0(n,n) + 0.083*V(n).pinfo(1,1); +% end +%end + + +% Create initial bias field +%----------------------------------------------------------------------- +llrb = 0; +for n=1:N + B1 = chan(n).B1; + B2 = chan(n).B2; + B3 = chan(n).B3; + C = chan(n).C; + T = chan(n).T; + chan(n).ll = double(-0.5*T(:)'*C*T(:)); + for z=1:numel(z0) + bf = transf(B1,B2,B3(z,:),T); + tmp = bf(buf(z).msk); + chan(n).ll = chan(n).ll + double(sum(tmp)); + buf(z).bf{n} = single(exp(tmp)); + end + llrb = llrb + chan(n).ll; + clear B1 B2 B3 T C +end + +spm_plot_convergence('Init','Initialising','Log-likelihood','Iteration'); +if isfield(obj,'wp') + wp = obj.wp; +else + wp = ones(1,Kb)/Kb; +end +for iter=1:60 % RD202012: increased from 30 + + % Load the warped prior probability images into the buffer + %------------------------------------------------------------ + for z=1:length(z0) + if ~buf(z).nm, continue; end + [x1,y1,z1] = defs(Twarp,z,x0,y0,z0,M,buf(z).msk); + b = spm_sample_priors8(tpm,x1,y1,z1); + for k1=1:Kb + buf(z).dat(:,k1) = b{k1}; + end + end + + if iter==1 + % Starting estimates for intensity distribution parameters + %----------------------------------------------------------------------- + if use_mog + % Starting estimates for Gaussian parameters + %----------------------------------------------------------------------- + if isfield(obj,'mg') && isfield(obj,'mn') && isfield(obj,'vr') + mg = obj.mg; + mn = obj.mn; + vr = obj.vr; + else + % Begin with moments: + K = Kb; + lkp = 1:Kb; + mm0 = zeros(Kb,1); + mm1 = zeros(N,Kb); + mm2 = zeros(N,N,Kb); + for z=1:length(z0) + cr = zeros(size(buf(z).f{1},1),N); + for n=1:N + cr(:,n) = double(buf(z).f{n}.*buf(z).bf{n}); + end + for k1=1:Kb % Moments + b = double(buf(z).dat(:,k1)); + mm0(k1) = mm0(k1) + sum(b); + mm1(:,k1) = mm1(:,k1) + (b'*cr)'; + mm2(:,:,k1) = mm2(:,:,k1) + (repmat(b,1,N).*cr)'*cr; + end + clear cr + end + + % Use moments to compute means and variances, and then use these + % to initialise the Gaussians + mn = zeros(N,Kb); + vr = zeros(N,N,Kb); + vr1 = zeros(N,N); + for k1=1:Kb + mn(:,k1) = mm1(:,k1)/(mm0(k1)+tiny); + %vr(:,:,k1) = (mm2(:,:,k1) - mm1(:,k1)*mm1(:,k1)'/mm0(k1))/(mm0(k1)+tiny); + vr1 = vr1 + (mm2(:,:,k1) - mm1(:,k1)*mm1(:,k1)'/mm0(k1)); + end + vr1 = (vr1+N*vr0)/(sum(mm0)+N); + for k1=1:Kb + vr(:,:,k1) = vr1; + end + mg = ones(Kb,1); + end + else + % Starting estimates for histograms + %----------------------------------------------------------------------- + for n=1:N + maxval = -Inf; + minval = Inf; + for z=1:length(z0) + if ~buf(z).nm, continue; end + maxval = max(max(buf(z).f{n}),maxval); + minval = min(min(buf(z).f{n}),minval); + end + maxval = max(maxval*1.5,-minval*0.05); % Account for bias correction effects + minval = min(minval*1.5,-maxval*0.05); + chan(n).interscal = [1 minval; 1 maxval]\[1;K]; + h0 = zeros(K,Kb); + for z=1:length(z0) + if ~buf(z).nm, continue; end + cr = round(buf(z).f{n}.*buf(z).bf{n}*chan(n).interscal(2) + chan(n).interscal(1)); + cr = min(max(cr,1),K); + for k1=1:Kb + h0(:,k1) = h0(:,k1) + accumarray(cr,buf(z).dat(:,k1),[K,1]); + end + end + chan(n).hist = h0; + end + end + end + + for iter1=1:8 + 8*(iter==1) % double initial iterations + if use_mog + %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + % Estimate cluster parameters + %------------------------------------------------------------ + for subit=1:20 + oll = ll; + mom0 = zeros(K,1)+tiny; % Initialise moments + mom1 = zeros(N,K); + mom2 = zeros(N,N,K); + mgm = zeros(1,Kb); + ll = llr+llrb; + for z=1:length(z0) + if ~buf(z).nm, continue; end + B = double(buf(z).dat); + s = 1./(B*wp'); + mgm = mgm + s'*B; + [q,dll] = latent(buf(z).f,buf(z).bf,mg,mn,vr,B,lkp,wp); + ll = ll + dll; + + cr = zeros(size(q,1),N); + for n=1:N + cr(:,n) = double(buf(z).f{n}.*buf(z).bf{n}); + end + for k=1:K % Update moments + q(:,k) = q(:,k); + mom0(k) = mom0(k) + sum(q(:,k)); + mom1(:,k) = mom1(:,k) + (q(:,k)'*cr)'; + mom2(:,:,k) = mom2(:,:,k) + (repmat(q(:,k),1,N).*cr)'*cr; + end + clear cr + end + my_fprintf('MOG:\t%g\t%g\t%g\n', ll,llr,llrb); + + % Mixing proportions, Means and Variances from moments + for k=1:K + tmp = mom0(lkp==lkp(k)); + mg(k) = (mom0(k)+tiny)/sum(tmp+tiny); % US eq. 27 (partly) + mn(:,k) = mom1(:,k)/(mom0(k)+tiny); % US eq. 23 + vr(:,:,k) = (mom2(:,:,k) - mom1(:,k)*mom1(:,k)'/mom0(k) + N*vr0)/(mom0(k)+N); % US eq. 25 + end + for k1=1:Kb + wp(k1) = (sum(mom0(lkp==k1)) + wp_reg*1)/(mgm(k1) + wp_reg*Kb); % bias the solution towards 1/kB + end + wp = wp/sum(wp); + + if subit>1 || iter>1 + spm_plot_convergence('Set',ll); + lllog = [lllog ll]; %#ok % RD202202: added to track changes + end + if subit>2 && ll-oll1 + % Improvement is small, so go to next step + break; + end + end + + else + %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + % Estimate histogram parameters + %------------------------------------------------------------ + + % Compute regularisation for histogram smoothing + for n=1:N + %x = (1:K)'; + for k1=1:Kb + %mom0 = sum(chan(n).hist(:,k1)) + eps; + %mom1 = sum(chan(n).hist(:,k1).*x) + eps; + %chan(n).lam(k1) = sum(chan(n).hist(:,k1).*(x-mom1./mom0).^2+1)/(mom0+1)+1; + chan(n).lam(k1) = Kb^2*double(vr0(N,N)*chan(n).interscal(2)^2); + end + end + + for subit=1:20 + oll = ll; + ll = llr+llrb; + for n=1:N + chan(n).lik = spm_smohist(chan(n).hist,chan(n).lam); + chan(n).lik = chan(n).lik*chan(n).interscal(2); + chan(n).alph = log(chan(n).lik+eps); + chan(n).hist = zeros(K,Kb); + end + mgm = zeros(1,Kb); + for z=1:length(z0) + B = double(buf(z).dat); + s = 1./(B*wp'); + mgm = mgm + s'*B; + + [q,dll] = latent_nonpar(buf(z).f,buf(z).bf,chan,buf(z).dat,wp); + ll = ll + dll; + + cr = cell(N,1); + for n=1:N + tmp = buf(z).f{n}.*buf(z).bf{n}*chan(n).interscal(2) + chan(n).interscal(1); + cr{n} = min(max(round(tmp),1),K); + end + for k1=1:Kb + for n=1:N + chan(n).hist(:,k1) = chan(n).hist(:,k1) + accumarray(cr{n},q(:,k1),[K,1]); + end + end + clear cr + end + wp = (sum(chan(1).hist)+wp_reg*1)./(mgm+wp_reg*Kb); + wp = wp/sum(wp); + + my_fprintf('Hist:\t%g\t%g\t%g\n', ll,llr,llrb); + + if subit>1 || iter>1 + spm_plot_convergence('Set',ll); + lllog = [lllog ll]; %#ok % RD202202: added to track changes + end + if subit>2 && ll-oll1 + % Improvement is small, so go to next step + break; + end + end + for n=1:N + chan(n).lik = spm_smohist(chan(n).hist,chan(n).lam); + chan(n).lik = chan(n).lik*chan(n).interscal(2); + chan(n).alph = log(chan(n).lik+eps); + chan(n).grad1 = convn(chan(n).alph,[0.5 0 -0.5]'*chan(n).interscal(2), 'same'); + chan(n).grad2 = convn(chan(n).alph,[1 -2 1 ]'*chan(n).interscal(2)^2,'same'); + end + end + + ooll = ll; + + if iter1 > 2 && ~((ll-ooll)>2*tol11*nm) || isnan(ll), break; end % RD202012: increased to minimum iteration - default was subit>1 + + + %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + % Estimate bias + % Note that for multi-spectral data, the covariances among + % channels are not computed as part of the second derivatives. + % The aim is to save memory, and maybe make the computations + % faster. + %------------------------------------------------------------ + + if use_mog + pr = zeros(size(vr)); % Precisions + for k=1:K, pr(:,:,k) = inv(vr(:,:,k)); end + end + + for subit=1:1 + for n=1:N + d3 = numel(chan(n).T); + if d3>0 + % Compute objective function and its 1st and second derivatives + Alpha = zeros(d3,d3); % Second derivatives + Beta = zeros(d3,1); % First derivatives + %ll = llr+llrb; + for z=1:length(z0) + if ~buf(z).nm, continue; end + + if use_mog + q = latent(buf(z).f,buf(z).bf,mg,mn,vr,buf(z).dat,lkp,wp); + cr = cell(N,1); + for n1=1:N, cr{n1} = double(buf(z).f{n1}).*double(buf(z).bf{n1}); end + + w1 = zeros(buf(z).nm,1); + w2 = zeros(buf(z).nm,1); + for k=1:K + qk = q(:,k); + w0 = zeros(buf(z).nm,1); + for n1=1:N + w0 = w0 + pr(n1,n,k)*(mn(n1,k) - cr{n1}); + end + w1 = w1 + qk.*w0; + w2 = w2 + qk*pr(n,n,k); + end + wt1 = zeros(d(1:2)); + wt1(buf(z).msk) = -(1 + cr{n}.*w1); % US eq. 34 (gradient) + wt2 = zeros(d(1:2)); + wt2(buf(z).msk) = cr{n}.*cr{n}.*w2 + 1; % Simplified Hessian of US eq. 34 + clear cr + else + q = latent_nonpar(buf(z).f,buf(z).bf,chan,buf(z).dat,wp); + cr0 = buf(z).f{n}.*buf(z).bf{n}; + cr = cr0*chan(n).interscal(2) + chan(n).interscal(1); + cr = min(max(round(cr),1),K); + wt1 = zeros(d(1:2)); + wt2 = zeros(d(1:2)); + for k1=1:Kb + qk = q(:,k1); + gr1 = chan(n).grad1(:,k1); + gr1 = gr1(cr); + gr2 = chan(n).grad2(:,k1); + gr2 = min(gr2(cr),0); % Regularise + wt1(buf(z).msk) = wt1(buf(z).msk) - qk.*(gr1.*cr0 + 1); + %wt2(buf(z).msk) = wt2(buf(z).msk) - qk.*(gr1.*cr0 + gr2.*cr0.^2); + wt2(buf(z).msk) = wt2(buf(z).msk) + qk.*(1 - gr2.*cr0.^2); + end + end + + b3 = chan(n).B3(z,:)'; + Beta = Beta + kron(b3,spm_krutil(wt1,chan(n).B1,chan(n).B2,0)); + Alpha = Alpha + kron(b3*b3',spm_krutil(wt2,chan(n).B1,chan(n).B2,1)); + clear wt1 wt2 b3 + end + + oll = ll; + C = chan(n).C; % Inverse covariance of priors + oldT = chan(n).T; + + % Gauss-Newton update of bias field parameters + Update = reshape((Alpha + C)\(Beta + C*chan(n).T(:)),size(chan(n).T)); + clear Alpha Beta + + armijo = 1.0; + for line_search=1:12 + chan(n).T = chan(n).T - armijo*Update; % Backtrack if necessary + + % Re-generate bias field, and compute terms of the objective function + chan(n).ll = double(-0.5*chan(n).T(:)'*C*chan(n).T(:)); + for z=1:length(z0) + if ~buf(z).nm, continue; end + bf = transf(chan(n).B1,chan(n).B2,chan(n).B3(z,:),chan(n).T); + tmp = bf(buf(z).msk); + chan(n).ll = chan(n).ll + double(sum(tmp)); + buf(z).bf{n} = single(exp(tmp)); + end + llrb = 0; + for n1=1:N, llrb = llrb + chan(n1).ll; end + ll = llr+llrb; + for z=1:length(z0) + if ~buf(z).nm, continue; end + if use_mog + [q,dll] = latent(buf(z).f,buf(z).bf,mg,mn,vr,buf(z).dat,lkp,wp); + ll = ll + dll; + else + [q,dll] = latent_nonpar(buf(z).f,buf(z).bf,chan,buf(z).dat,wp); + ll = ll + dll; + end + clear q + end + if ll>=oll + spm_plot_convergence('Set',ll); + my_fprintf('Bias-%d:\t%g\t%g\t%g :o)\n', n, ll, llr,llrb); + break; + else + ll = oll; + chan(n).T = oldT; + armijo = armijo*0.5; + my_fprintf('Bias-%d:\t%g\t%g\t%g :o(\n', n, ll, llr,llrb); + end + end + clear oldT + end + end + if subit > 2 && ~(ll-oll>tol1*nm) || isnan(ll) % RD202012: increased to minimum iteration - default was subit>1 + % Improvement is only small, so go to next step + break; + end + end + + if iter==1 && iter1==1 + % Most of the log-likelihood improvements are in the first iteration. + % Show only improvements after this, as they are more clearly visible. + spm_plot_convergence('Clear'); lllog = []; % reset also the ll-log + spm_plot_convergence('Init','Processing','Log-likelihood','Iteration'); + + if use_mog && numel(obj.lkp) ~= numel(lkp) + mn1 = mn; + vr1 = vr; + lkp = obj.lkp; + K = numel(lkp); + Kb = max(lkp); + + % Use moments to compute means and variances, and then use these + % to initialise the Gaussians + mg = ones(K,1)/K; + mn = ones(N,K); + vr = zeros(N,N,K); + + for k1=1:Kb + % A crude heuristic to replace a single Gaussian by a bunch of Gaussians + % If there is only one Gaussian, then it should be the same as the + % original distribution. + kk = sum(lkp==k1); + w = 1./(1+exp(-(kk-1)*0.25))-0.5; + mn(:,lkp==k1) = sqrtm(vr1(:,:,k1))*randn(N,kk)*w + repmat(mn1(:,k1),[1,kk]); + vr(:,:,lkp==k1) = repmat(vr1(:,:,k1)*(1-w),[1,1,kk]); + mg(lkp==k1) = 1/kk; + end + end + end + end + + + + %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + % Estimate deformations + %------------------------------------------------------------ + ll_const = 0; + ll = llr+llrb; + if use_mog + % Compute likelihoods, and save them in buf.dat + for z=1:length(z0) + if ~buf(z).nm, continue; end + q = zeros(buf(z).nm,Kb); + qt = log_likelihoods(buf(z).f,buf(z).bf,mg,mn,vr); + max_qt = max(qt,[],2); + ll_const = ll_const + sum(max_qt); + B = bsxfun(@times,double(buf(z).dat),wp); + B = bsxfun(@times,B,1./sum(B,2)); + for k1=1:Kb + for k=find(lkp==k1) + q(:,k1) = q(:,k1) + exp(qt(:,k)-max_qt); + end + buf(z).dat(:,k1) = single(q(:,k1)); + end + ll = ll + sum(log(sum(q.*B+tiny,2))); + end + ll = ll + ll_const; + else + % Compute likelihoods, and save them in buf.dat + for z=1:length(z0) + if ~buf(z).nm, continue; end + q = log_likelihoods_nonpar(buf(z).f,buf(z).bf,chan); + max_q = max(q,[],2); + ll_const = ll_const + sum(max_q); + q = exp(bsxfun(@minus,q,max_q)); + B = bsxfun(@times,double(buf(z).dat),wp); + B = bsxfun(@times,B,1./sum(B,2)); + ll = ll + sum(log(sum(q.*B+tiny,2)),1); + buf(z).dat = single(q); + end + ll = ll + ll_const; + end + + oll = ll; + for subit=1:3 + Alpha = zeros([size(x0),numel(z0),6],'single'); + Beta = zeros([size(x0),numel(z0),3],'single'); + for z=1:length(z0) + if ~buf(z).nm, continue; end + + % Deformations from parameters + [x1,y1,z1] = defs(Twarp,z,x0,y0,z0,M,buf(z).msk); + + % Tissue probability map and spatial derivatives + [b,db1,db2,db3] = spm_sample_priors8(tpm,x1,y1,z1); + clear x1 y1 z1 + + % Adjust for tissue weights + s = zeros(size(b{1})); + ds1 = zeros(size(b{1})); + ds2 = zeros(size(b{1})); + ds3 = zeros(size(b{1})); + for k1=1:Kb + b{k1} = wp(k1)*b{k1}; + db1{k1} = wp(k1)*db1{k1}; + db2{k1} = wp(k1)*db2{k1}; + db3{k1} = wp(k1)*db3{k1}; + s = s + b{k1}; + ds1 = ds1 + db1{k1}; + ds2 = ds2 + db2{k1}; + ds3 = ds3 + db3{k1}; + end + for k1=1:Kb + b{k1} = b{k1}./s; + db1{k1} = (db1{k1}-b{k1}.*ds1)./s; + db2{k1} = (db2{k1}-b{k1}.*ds2)./s; + db3{k1} = (db3{k1}-b{k1}.*ds3)./s; + end + clear s ds1 ds2 ds3 + + % Rotate gradients (according to initial affine registration) and + % compute the sums of the tpm and its gradients, times the likelihoods + % (from buf.dat). + p = zeros(buf(z).nm,1)+eps; + dp1 = zeros(buf(z).nm,1); + dp2 = zeros(buf(z).nm,1); + dp3 = zeros(buf(z).nm,1); + MM = M*MT; % Map from sampled voxels to atlas data + for k1=1:Kb + pp = double(buf(z).dat(:,k1)); + p = p + pp.*b{k1}; + dp1 = dp1 + pp.*(MM(1,1)*db1{k1} + MM(2,1)*db2{k1} + MM(3,1)*db3{k1}); + dp2 = dp2 + pp.*(MM(1,2)*db1{k1} + MM(2,2)*db2{k1} + MM(3,2)*db3{k1}); + dp3 = dp3 + pp.*(MM(1,3)*db1{k1} + MM(2,3)*db2{k1} + MM(3,3)*db3{k1}); + end + clear b db1 db2 db3 + + % Compute first and second derivatives of the matching term. Note that + % these can be represented by a vector and tensor field respectively. + tmp = zeros(d(1:2)); + tmp(buf(z).msk) = dp1./p; dp1 = tmp; + tmp(buf(z).msk) = dp2./p; dp2 = tmp; + tmp(buf(z).msk) = dp3./p; dp3 = tmp; + + Beta(:,:,z,1) = -dp1; % First derivatives + Beta(:,:,z,2) = -dp2; + Beta(:,:,z,3) = -dp3; + + Alpha(:,:,z,1) = dp1.*dp1; % Second derivatives + Alpha(:,:,z,2) = dp2.*dp2; + Alpha(:,:,z,3) = dp3.*dp3; + Alpha(:,:,z,4) = dp1.*dp2; + Alpha(:,:,z,5) = dp1.*dp3; + Alpha(:,:,z,6) = dp2.*dp3; + clear tmp p dp1 dp2 dp3 + end + + % Heavy-to-light regularisation + if ~isfield(obj,'Twarp') + switch iter + case 1 + prm = [param(1:3) 256*param(4:8)]; + case 2 + prm = [param(1:3) 128*param(4:8)]; + case 3 + prm = [param(1:3) 64*param(4:8)]; + case 4 + prm = [param(1:3) 32*param(4:8)]; + case 5 + prm = [param(1:3) 16*param(4:8)]; + case 6 + prm = [param(1:3) 8*param(4:8)]; + case 7 + prm = [param(1:3) 4*param(4:8)]; + case 8 + prm = [param(1:3) 2*param(4:8)]; + otherwise + prm = [param(1:3) param(4:8)]; + end + else + prm = [param(1:3) param(4:8)]; + end + + % Add in the first derivatives of the prior term + Beta = Beta + spm_diffeo('vel2mom',bsxfun(@times,Twarp,1./sk4),prm); + + % Gauss-Newton increment + Update = bsxfun(@times,spm_diffeo('fmg',Alpha,Beta,[prm 2 2]),sk4); + + % Line search to ensure objective function improves + armijo = 1.0; + for line_search=1:12 + Twarp1 = Twarp - armijo*Update; % Backtrack if necessary + + % Recompute objective funciton + llr1 = -0.5*sum(sum(sum(sum(Twarp1.*bsxfun(@times,spm_diffeo('vel2mom',bsxfun(@times,Twarp1,1./sk4),prm),1./sk4))))); + ll1 = llr1+llrb+ll_const; + for z=1:length(z0) + if ~buf(z).nm, continue; end + [x1,y1,z1] = defs(Twarp1,z,x0,y0,z0,M,buf(z).msk); + b = spm_sample_priors8(tpm,x1,y1,z1); + clear x1 y1 z1 + s = zeros(size(b{1})); + for k1=1:Kb, b{k1} = b{k1}*wp(k1); s = s + b{k1}; end + for k1=1:Kb, b{k1} = b{k1}./s; end + + sq = zeros(buf(z).nm,1); + for k1=1:Kb + sq = sq + double(buf(z).dat(:,k1)).*double(b{k1}); + end + clear b + ll1 = ll1 + sum(log(sq)); + clear sq + end + + if ll1tol1*nm) + % Registration no longer helping, so move on + break + end + oll = ll; + end + + % RD202202: Estimate something like the AUC to assure that no larger + % changes appear in the last iterations, ie. that the process + % is stable + nlllog = (lllog - min(lllog)) / (max(lllog) - min(lllog)); % save ll + llpc = ((ll - min(lllog)) / (max(lllog) - min(lllog) )) ./ ... + ((ooll - min(lllog)) / (max(lllog) - min(lllog) )); % test relative changes between the outer loops + AUC = sum(nlllog) / numel(nlllog); + AUC(isnan(AUC)) = 1; + + % visualize stop criteria for experts + if cat_get_defaults('extopts.expertgui') >= outputGUIlevel + % print the minimum iteration critieria + Finter = spm_figure('FindWin','Interactive'); + if ~exist('Faxes','var') + Faxes = findobj(Finter,'Type','Axes'); + end + if ~exist('Faxes','var') && isemtpy(Faxes) + ydata = get(findobj(Finter,'Type','Line'),'ydata'); + xdata = get(findobj(Finter,'Type','Line'),'xdata'); + if iscell(ydata) + ydata = ydata{ cellfun(@numel,ydata)>2 }; + xdata = xdata{ cellfun(@numel,xdata)>2 }; + end + ydata(isnan(ydata)) = max(ydata); + maxis = get(Faxes,'ylim'); + % print minimum number of iterations + if iter>9 && AUCprint(3) + hold(Faxes,'on'); AUCprint(3) = 0; + plot(Faxes,[xdata(end),xdata(end)],[maxis(1),ydata(end)],'Color',[0.9 0.9 0.9]); + hold(Faxes,'off'); + end + % print the normal SPM stop criteria as orientation + if iter>9 && ~((ll-ooll)>2*(1e-4)*nm) && AUCprint(2) + hold(Faxes,'on'); AUCprint(2) = 0; + plot(Faxes,[xdata(end),xdata(end)],[maxis(1),ydata(end)],'Color',[0.7 0.7 0.7]); + hold(Faxes,'off'); + end + % print the adapted CAT stop criteria as orientation + if iter>10 && ~((ll-ooll)>2*tol1*nm) && AUCprint(1) + hold(Faxes,'on'); AUCprint(1) = 0; + plot(Faxes,[xdata(end),xdata(end)],[maxis(1),ydata(end)],'Color',[0.5 1 0.5]); + hold(Faxes,'off'); + end + % print the final progress of AUCH + if iter>10 && ~((ll-ooll)>2*tol1*nm) + hold(Faxes,'on'); + plot(Faxes,[xdata(end),xdata(end)],[maxis(1),ydata(end)],'Color',[1 1 1] - [0 1 1]*min(1,max(0,AUC-0.75))*4 ); + hold(Faxes,'off'); + end + end + end + + % command line output for experts + if cat_get_defaults('extopts.expertgui') >= outputGUIlevel + if iter==1 % display also intial values in the first loop + fprintf('\n Iteration %2d - ll: %8.6f, llc: %8.6f, llpc: %8.6f, AUC: %6.4f ', iter-1, lllog(1)/nm, lllog(end)/nm - lllog(1)/nm, inf, 0); + end + fprintf('\n Iteration %2d - ll: %8.6f, llc: %8.6f, llpc: %8.6f, AUC: %6.4f ', iter, ll/nm, lllog(end)/nm - lllog(1)/nm, llpc, AUC); + end + + % final outer iteration stop criterias + if newtol==-1 % old SPM + if iter>9 && ~((ll-ooll)>2*tol1*nm) + % Finished + break + end + elseif newtol==0 % old but adapted criteria with additiona iterations + if iter>19 && ~((ll-ooll)>2*tol1*nm) % RD202012: increased to minimum iteration - default was iter>9 + % Finished + break + end + else % new criteria with less minimum iterations but further tests + % check if there are no big changes within the last 25% of all iterations + dnlllog = nlllog( numel(lllog) ) - nlllog( numel(lllog) - round(numel(lllog)/6) ); + if iter>9 && ... minimum number of iterations of the outer loop (defaults: SPM=9, CAT=19) .. no longer needed but it is ok to keep it + any(llpc < 1.01) && ... % avoid stops when we made some minimum progress + ~((ll-ooll)>2*tol1*nm) && ... stopping criteria based by changes to last outer iteration + ( ~exist('AUCO','var') || AUC > AUCO ) && ... no stronger changes in the last steps - necessary? + ( ( AUC > max( 0.75 , min( 0.96 , 0.74 - 0.01 * log10(tol1) )) && dnlllog < 2*(16 ./ -log10(tol1)) / 100 ) || ... + ... % only small changes over the last major iterations (increase iterations) + ( dnlllog < min(0.1,16 ./ -log10(tol1)) / 100 ) || any(llpc < 1e-4) ) % avoid useless interations + % Finished + if isnan(ll), ll = max(lllog); end % best value without NaN + break + end + end + AUCO = AUC; +end +spm_plot_convergence('Clear'); + +% Save the results +results.image = obj.image; +results.tpm = tpm.V; +results.Affine = Affine; +results.lkp = lkp; +results.MT = MT; +results.Twarp = Twarp; +results.Tbias = {chan(:).T}; +results.wp = wp; +if use_mog + results.mg = mg; + results.mn = mn; + results.vr = vr; +else + for n=1:N + results.intensity(n).lik = chan(n).lik; + results.intensity(n).interscal = chan(n).interscal; + end +end +% RD: further output parameter for later analysis +results.ll = ll / nm; % normalize it +results.llpc = llpc; +results.lllog = lllog ./ nm; +results.AUC = AUC; +return; +%======================================================================= + +%======================================================================= +function t = transf(B1,B2,B3,T) +if ~isempty(T) + d2 = [size(T) 1]; + t1 = reshape(reshape(T, d2(1)*d2(2),d2(3))*B3', d2(1), d2(2)); + t = B1*t1*B2'; +else + t = zeros(size(B1,1),size(B2,1)); +end +return; +%======================================================================= + +%======================================================================= +function [x1,y1,z1] = defs(Twarp,z,x0,y0,z0,M,msk) +x1a = x0 + double(Twarp(:,:,z,1)); +y1a = y0 + double(Twarp(:,:,z,2)); +z1a = z0(z) + double(Twarp(:,:,z,3)); +if nargin>=7 + x1a = x1a(msk); + y1a = y1a(msk); + z1a = z1a(msk); +end +x1 = M(1,1)*x1a + M(1,2)*y1a + M(1,3)*z1a + M(1,4); +y1 = M(2,1)*x1a + M(2,2)*y1a + M(2,3)*z1a + M(2,4); +z1 = M(3,1)*x1a + M(3,2)*y1a + M(3,3)*z1a + M(3,4); +return; +%======================================================================= + +%======================================================================= +function L = log_likelihoods(f,bf,mg,mn,vr) +K = numel(mg); +N = numel(f); +M = numel(f{1}); +cr = zeros(M,N); +for n=1:N + cr(:,n) = double(f{n}(:)).*double(bf{n}(:)); +end +L = zeros(numel(f{1}),K); +for k=1:K + C = chol(vr(:,:,k)); + d = bsxfun(@minus,cr,mn(:,k)')/C; + L(:,k) = log(mg(k)) - (N/2)*log(2*pi) - sum(log(diag(C))) - 0.5*sum(d.*d,2); +end +%======================================================================= + +%======================================================================= +function L = log_likelihoods_nonpar(f,bf,chan) +K = size(chan(1).lik,1); +Kb = size(chan(1).lik,2); +N = numel(chan); +L = zeros(numel(f{1}),Kb); +for n=1:N + tmp = f{n}.*bf{n}*chan(n).interscal(2) + chan(n).interscal(1); + tmp = min(max(round(tmp),1),K); + loglik = chan(n).alph; + for k1=1:Kb + L(:,k1) = L(:,k1)+loglik(tmp,k1); + end +end +%======================================================================= + +%======================================================================= +function B = log_spatial_priors(B,wp) +B = bsxfun(@times,B,wp); +B = log(bsxfun(@times,B,1./sum(B,2))); +%======================================================================= + +%======================================================================= +function [Q,ll] = safe_softmax(Q) +maxQ = max(Q,[],2); +Q = exp(bsxfun(@minus,Q,maxQ)); +sQ = sum(Q,2); +ll = sum(log(sQ)+maxQ); +Q = bsxfun(@rdivide,Q,sQ); +%======================================================================= + +%======================================================================= +function [Q,ll] = latent(f,bf,mg,mn,vr,B,lkp,wp) +B = log_spatial_priors(B,wp); +Q = log_likelihoods(f,bf,mg,mn,vr); +Kb = max(lkp); +for k1=1:Kb + for k=find(lkp==k1) + Q(:,k) = Q(:,k) + B(:,k1); + end +end +[Q,ll] = safe_softmax(Q); +%======================================================================= + +%======================================================================= +function [Q,ll] = latent_nonpar(f,bf,chan,B,wp) +B = log_spatial_priors(B,wp); +Q = log_likelihoods_nonpar(f,bf,chan); +Q = Q + B; +[Q,ll] = safe_softmax(Q); +%======================================================================= + +%======================================================================= +function count = my_fprintf(varargin) +verbose = false; +if verbose + count = fprintf(varargin{:}); +else + count = 0; +end +%======================================================================= + +%======================================================================= + + +","MATLAB" +"Neurology","ChristianGaser/cat12","KmeansMex.c",".c","2786","101","/* ______________________________________________________________________ + * + * Christian Gaser, Robert Dahnke + * Structural Brain Mapping Group (https://neuro-jena.github.io) + * Departments of Neurology and Psychiatry + * Jena University Hospital + * ______________________________________________________________________ + * $Id$ + * + */ + +#include ""mex.h"" +#include ""math.h"" +#include ""stdio.h"" + +extern double Kmeans(double *src, unsigned char *label, unsigned char *mask, int NI, int n_clusters, double *voxelsize, const int *dims, int thresh_mask, int thresh_kmeans, int iters_nu, int pve, double bias_fwhm); + +void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) +{ + unsigned char *label; + unsigned char *mask; + double *src, *bias, voxelsize[3], mx, thresh, thresh_kmeans_int, bias_fwhm; + double *mean, n[100]; + unsigned long nvox, i; + int n_classes, iters_nu; + const unsigned long *dims0; + int dims[3], ind; + + if (nrhs<2) + mexErrMsgTxt(""At least 2 inputs required.""); + else if (nlhs>3) + mexErrMsgTxt(""Too many output arguments.""); + + if (!mxIsDouble(prhs[0])) + mexErrMsgTxt(""Image must be double.""); + + src = (double*)mxGetPr(prhs[0]); + n_classes = (int)mxGetScalar(prhs[1]); + if (nrhs>2) + iters_nu = (int)mxGetScalar(prhs[2]); + else iters_nu = 0; + + dims0 = mxGetDimensions(prhs[0]); + + for (i=0; i<3; i++) { + voxelsize[i] = 1.0; + dims[i] = dims0[i]; + } + + plhs[0] = mxCreateNumericArray(3,dims0,mxUINT8_CLASS,mxREAL); + plhs[1] = mxCreateNumericMatrix(1, n_classes, mxDOUBLE_CLASS, mxREAL); + plhs[2] = mxCreateNumericArray(3,dims0,mxDOUBLE_CLASS,mxREAL); + label = (unsigned char *)mxGetPr(plhs[0]); + mean = (double *)mxGetPr(plhs[1]); + bias = (double *)mxGetPr(plhs[2]); + + thresh = 0; + thresh_kmeans_int = 128; + bias_fwhm = 50.0; + + nvox = dims[0]*dims[1]*dims[2]; + mask = (unsigned char *)mxMalloc(sizeof(unsigned char)*nvox); + if(mask == NULL) { + mexErrMsgTxt(""Memory allocation error\n""); + exit(EXIT_FAILURE); + } + + for (i=0; i 0) + mx = Kmeans(src, label, mask, 25, n_classes, voxelsize, dims, thresh, thresh_kmeans_int, iters_nu, 0, bias_fwhm); +*/ + mx = Kmeans(src, label, mask, 25, n_classes, voxelsize, dims, thresh, thresh_kmeans_int, iters_nu, 0, bias_fwhm); + + for (i=0; i> cat_run_job_APP_init +% >> cat_run_job_APP_final +% * affine registration +% * initial SPM preprocessing +% +% cat_run_job(job,tpm,subj) +% +% job .. SPM job structure with main parameter +% tpm .. tissue probability map (hdr structure) +% subj .. file name +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +%#ok<*WNOFF,*WNON> + + job.test_warnings = 0; % just for tests + job.extopts.histth = [0.96 0.9999]; % histogram thresholds + % use ""lower"" first histth to deal with diffent low intensity BGs that + % is corrected in case of highBG data + job.extopts.input = 0; % 0 - auto (default), 1-with skull (normal), 2-skull-stripped, 3-high BG + + if exist('rng','file') == 2, rng('default'); rng(0); else, rand('state',0); randn('state',0); end + + % if there is a breakpoint in this file set debug=1 and do not clear temporary variables + dbs = dbstatus; debug = 0; for dbsi=1:numel(dbs), if strcmp(dbs(dbsi).name,mfilename); debug = 1; break; end; end + + clearvars -global cat_err_res; + global cat_err_res; % for CAT error report + cat_err_res.stime = clock; + cat_err_res.cat_warnings = cat_io_addwarning('reset'); % reset warnings + stime = clock; + stime0 = stime; % overall processing time + + % create subfolders if not exist + pth = spm_fileparts(job.channel(1).vols{subj}); + [mrifolder, reportfolder, surffolder, labelfolder] = cat_io_subfolders(job.channel(1).vols{subj},job); + + if job.extopts.subfolders + + folders = {mrifolder,reportfolder}; + warning('off', 'MATLAB:MKDIR:DirectoryExists'); + for i=1:numel(folders) + [stat, msg] = mkdir(fullfile(pth,folders{i})); + if ~stat + fprintf('%s: Error while creating directory %s\n\n\n',msg,fullfile(pth,folders{i})); + return + end + end + + if ~exist(fullfile(pth,surffolder),'dir') && job.output.surface + [stat, msg] = mkdir(fullfile(pth,surffolder)); + if ~stat + fprintf('%s: Error while creating directory %s\n\n\n',msg,fullfile(pth,surffolder)); + return + end + end + + if ~exist(fullfile(pth,labelfolder),'dir') && job.output.ROI + [stat, msg] = mkdir(fullfile(pth,labelfolder)); + if ~stat + fprintf('%s: Error while creating directory %s\n\n\n',msg,fullfile(pth,labelfolder)); + return + end + end + + end + + % create subject-wise diary file with the command-line output + [pp,ff,ee,ex] = spm_fileparts(job.data{subj}); %#ok + % sometimes we have to remove .nii from filename if files were zipped + catlog = fullfile(pth,reportfolder,['catlog_' strrep(ff,'.nii','') '.txt']); + if exist(catlog,'file'), delete(catlog); end % write every time a new file, turn this off to have an additional log file + + % check if not another diary is already written that is not the default- or catlog-file. + if ~strcmpi(spm_check_version,'octave') + olddiary = spm_str_manip( get(0,'DiaryFile') , 't'); + usediary = ~isempty(strfind( olddiary , 'diary' )) || ~isempty(strfind( olddiary , 'catlog_' )); + if usediary + diary(catlog); + diary on; + else + cat_io_cprintf('warn',sprintf('External diary log is written to ""%s"".\n',get(0,'DiaryFile'))); + end + else + % always use diary and don't check for old one for Octave + usediary = 1; + diary(catlog); + diary on; + end + + % print current CAT release number and subject file + [n,r] = cat_version; + str = sprintf('%s r%s: %d/%d',n,r,subj,numel(job.channel(1).vols)); + str2 = spm_str_manip(job.channel(1).vols{subj}(1:end-2),['a' num2str(70 - length(str))]); + cat_io_cprintf([0.2 0.2 0.8],'\n%s\n%s: %s%s\n%s\n',... + repmat('-',1,72),str,... + repmat(' ',1,70 - length(str) - length(str2)),str2,... + repmat('-',1,72)); + clear r str str2 + + if job.extopts.ignoreErrors>1 + cat_io_addwarning([mfilename ':ignoreErrors'],'Run pipeline with backup functions (IN DEVELOPMENT).',1,[1 1]); + end + + + % ----------------------------------------------------------------- + % separation of full CAT preprocessing and SPM segmentation + % preprocessing (running DARTEL and PBT with SPM segmentation) + % ----------------------------------------------------------------- + [pp,ff,ee,ex] = spm_fileparts(job.data{subj}); + if exist(fullfile(pp,['c1' ff(3:end) ee]),'file') && ... + exist(fullfile(pp,['c2' ff(3:end) ee]),'file') && ... + exist(fullfile(pp,['c3' ff(3:end) ee]),'file') && ... + exist(fullfile(pp,[ff(3:end) '_seg_sn.mat']),'file') && ... + strcmp(ff(1:2),'c1') + + cat_io_cprintf('blue','Load SPM old-segment segmentation (*seg_sn.mat)\n ') + + % create field also for dependency setup + if ~isfield(job.extopts,'spmAMAP'), job.extopts.spmAMAP = 0; end + + job.data{subj} = fullfile(pp,[ff ee]); + job.channel.vols{subj} = fullfile(pp,[ff ee]); + + % prepare SPM preprocessing structure + images = job.channel(1).vols{subj}; + for n = 2:numel(job.channel) + images = char(images,job.channel(n).vols{subj}); + end + Pseg8 = fullfile(pp,[ff(3:end) '_seg_sn.mat']); + reso = load(Pseg8); + res = reso.flags; + res.segsn = reso; + + % prepare spm classes (the GUI limits this to 3 images + automatic background class) + for ti = 1:numel(res.ngaus) + job.tissue(ti).ngaus = res.ngaus(ti); + job.tissue(ti).tpm = reso.VG(min(ti,numel(reso.VG))).fname; + end + job.tissue(numel(res.ngaus)+1:end) = []; + + % create class parameter variable + res.lkp = []; + if all(isfinite(cat(1,res.ngaus))) + for k=1:numel(res.ngaus) + res.lkp = [res.lkp ones(1,job.tissue(k).ngaus)*k]; + end + end + + % update template data and load template + res.tpm = reso.VG; + if numel(res.lkp) == numel(res.mg) + for lkpi = 1:max(res.lkp) + res.mg(res.lkp==lkpi) = res.mg(res.lkp==lkpi) / sum(res.mg(res.lkp==lkpi)); + end + end + res.mn = res.mn'; + tpm = spm_load_priors8(res.tpm); + + obj.image = spm_vol(images); + obj.fwhm = job.opts.fwhm; + obj.affreg = res.regtype; + obj.biasreg = res.biasreg; + obj.biasfwhm = res.biasfwhm; + obj.tol = NaN; + obj.reg = res.warpreg; + obj.samp = res.samp; + obj.lkp = res.lkp; + obj.tpm = tpm; + + % prepare the internal T1 map + cfname = fullfile(pp,[ff ee]); + ofname = fullfile(pp,[ff(3:end) ee]); + nfname = fullfile(pp,mrifolder,['n' ff '.nii']); + copyfile(ofname,nfname,'f'); + + % update option fields + job.opts.tpm = {reso.VG(1).fname}; + job.opts.biasreg = res.biasreg; + job.opts.biasfwhm = res.biasfwhm; + job.opts.samp = res.samp; + job.opts.tpm = res.tpm(1).fname; + job.opts.biasreg = res.biasreg; + % [abs.-displacement, membran-engery, bending-engery, linear-elasticity 2x ] + job.opts.warpreg = nan(1,5); % this does not fit to the old parameter + job.extopts.shootingT1 = job.extopts.T1; + job.channel(1).vols{subj} = [nfname ex]; + job.channel(1).vols0{subj} = [ofname ex]; + res.image = spm_vol([nfname ex]); + res.image0 = spm_vol([ofname ex]); + res.imagec = spm_vol([cfname ex]); + res.spmpp = 1; + job.spmpp = 1; + + % load volumes + Ysrc0 = single(spm_read_vols(obj.image)); + Ylesion = single(isnan(Ysrc0) | isinf(Ysrc0) | Ysrc0==0); clear Ysrc0; + + % prepare error sturture + cat_err_res.obj = obj; + + elseif exist(fullfile(pp,['c1' ff(3:end) ee]),'file') && ... + exist(fullfile(pp,['c2' ff(3:end) ee]),'file') && ... + exist(fullfile(pp,['c3' ff(3:end) ee]),'file') && ... + exist(fullfile(pp,[ff(3:end) '_seg8.mat']),'file') && strcmp(ff(1:2),'c1') + + cat_io_cprintf('blue','Load SPM segment segmentation (*seg8.mat)\n ') + + % create field also for dependency setup + if ~isfield(job.extopts,'spmAMAP'), job.extopts.spmAMAP = 0; end + + job.data{subj} = fullfile(pp,[ff ee]); + job.channel.vols{subj} = fullfile(pp,[ff ee]); + + % prepare SPM preprocessing structure + images = job.channel(1).vols{subj}; + for n=2:numel(job.channel) + images = char(images,job.channel(n).vols{subj}); + end + + obj.image = spm_vol(images); + obj.fwhm = job.opts.fwhm; + obj.biasreg = cat(1,job.opts.biasreg); + obj.biasfwhm = cat(1,job.opts.biasfwhm); + obj.tol = job.opts.tol; + obj.lkp = []; + obj.reg = job.opts.warpreg; + obj.samp = job.opts.samp; + spm_check_orientations(obj.image); + + if all(isfinite(cat(1,job.tissue.ngaus))) + for k=1:numel(job.tissue) + obj.lkp = [obj.lkp ones(1,job.tissue(k).ngaus)*k]; + end + end + + Pseg8 = fullfile(pp,[ff(3:end) '_seg8.mat']); + if ~exist(Pseg8,'file') + error('cat_run_job:SPMpp_MissSeg8mat','Can''t find ""%s"" file!',Pseg8); + end + res = load(Pseg8); + + % load tpm priors + tpm = spm_load_priors8(res.tpm); + obj.lkp = res.lkp; + obj.tpm = tpm; + + % Special cases with different class numbers in case of SPM input + if max(obj.lkp)==6 + % default cases + elseif max(obj.lkp)==3 + cat_io_addwarning('SPMpp_PostMortem','Detected only 3 classes that are interpretated as GM, WM, and CSF/background.',0,[0 1]) + elseif max(obj.lkp)==4 + cat_io_addwarning('SPMpp_SkullStripped','Detected only 4 classes that are interpretated as GM, WM, CSF, and background',0,[0 1]) + else + cat_io_addwarning('SPMpp_AtypicalClsNumber',sprintf('Atypical number of input classes (max(lkp)=%d).',max(obj.lkp)),2,[0 1]) + end + + + cfname = fullfile(pp,[ff ee]); + ofname = fullfile(pp,[ff(3:end) ee]); + nfname = fullfile(pp,mrifolder,['n' ff '.nii']); + copyfile(ofname,nfname,'f'); + + Ysrc0 = single(spm_read_vols(obj.image)); + Ylesion = single(isnan(Ysrc0) | isinf(Ysrc0) | Ysrc0==0); clear Ysrc0; + + + job.channel(1).vols{subj} = [nfname ex]; + job.channel(1).vols0{subj} = [ofname ex]; + res.image = spm_vol([nfname ex]); + res.image0 = spm_vol([ofname ex]); + res.imagec = spm_vol([cfname ex]); + res.spmpp = 1; + job.spmpp = 1; + + % prepare error sturture + cat_err_res.obj = obj; + else + + % ----------------------------------------------------------------- + % check resolution properties + % ----------------------------------------------------------------- + % There were some images that should not be processed. So we have + % to check for large slice thickness and low spatial resolution. + % RD201909: I tried 4x4x4 and 1x1x8 mm data with default and NLM + % interpolation. Also NLM shows less edges and more + % correct surfaces, the thickness results are worse and + % the limits are ok. + % RD202007: Low resolution data is now allowed if ignoreErrer > 1. + % Tested again NLM and Boeseflug interpolation and there + % are many artefacts and simple spline interpolation is + % more save. + % RD202107: Print warning for reslimit/2 and alert for reslimit. + % ----------------------------------------------------------------- + for n=1:numel(job.channel) + V = spm_vol(job.channel(n).vols{subj}); + vx_vol = sqrt(sum(V.mat(1:3,1:3).^2)); + + % maximum [ slice-thickness , volume^3 , anisotropy ] + reslimits = [5 4 8]; + + % too thin slices + if any( vx_vol > reslimits(1) ) || job.test_warnings + mid = [mfilename 'cat_run_job:TooLowResolution']; + msg = sprintf(['Voxel resolution should be better than %d mm in any dimension for \\\\n' ... + 'reliable preprocessing! This image has a resolution of %0.2fx%0.2fx%0.2f mm%s. '], ... + reslimits(1),vx_vol,native2unicode(179, 'latin1')); + cat_io_addwarning(mid,msg,1 + any( vx_vol > reslimits(1) ) ,[0 1],vx_vol); + end + + % too small voxel volume (smaller than 3x3x3 mm3) + if prod(vx_vol) > (reslimits(2))^3 || job.test_warnings + mid = [mfilename 'cat_run_job:TooLargeVoxelVolume']; + msg = sprintf(['Voxel volume should be smaller than %d mm%s (around %dx%dx%d mm%s) for \\\\n' ... + 'reliable preprocessing! This image has a voxel volume of %0.2f mm%s. '], ... + reslimits(2)^3,native2unicode(179, 'latin1'),reslimits(2),reslimits(2),reslimits(2),... + native2unicode(179, 'latin1'),prod(vx_vol),native2unicode(179, 'latin1')); + cat_io_addwarning(mid,msg,1 + (prod(vx_vol) > reslimits(2)^3),[0 1],vx_vol); + end + + % anisotropy + if max(vx_vol) / min(vx_vol) > reslimits(3) || job.test_warnings + mid = [mfilename 'cat_run_job:TooStrongAnisotropy']; + msg = sprintf(['Voxel anisotropy (max(vx_size)/min(vx_size)) should be smaller than %d for \\\\n' ... + 'reliable preprocessing! This image has a resolution %0.2fx%0.2fx%0.2f mm%s \\\\nand a anisotropy of %0.2f. '], ... + reslimits(3),vx_vol,native2unicode(179, 'latin1'),max(vx_vol)/min(vx_vol)); + cat_io_addwarning(mid,msg,1 + (max(vx_vol) / min(vx_vol) > reslimits(3)/3),[0 1],vx_vol); + end + end + + % save original file name + for n=1:numel(job.channel) + job.channel(n).vols0{subj} = job.channel(n).vols{subj}; + end + + + % always create the n*.nii image because of the real masking of the + % T1 data for spm_preproc8 that includes rewriting the image! + for n=1:numel(job.channel) + [pp,ff,ee] = spm_fileparts(job.channel(n).vols{subj}); + ofname = fullfile(pp,[ff ee]); + nfname = fullfile(pp,mrifolder,['n' ff '.nii']); + if strcmp(ee,'.nii') + if ~copyfile(ofname,nfname,'f') + spm('alert!',sprintf('ERROR: Check file permissions for folder %s.\n',fullfile(pp,mrifolder)),'',spm('CmdLine'),1); + end + elseif strcmp(ee,'.img') + V = spm_vol(job.channel(n).vols{subj}); + Y = spm_read_vols(V); + V.fname = nfname; + spm_write_vol(V,Y); + clear Y; + end + job.channel(n).vols{subj} = nfname; + + %% denoising + if job.extopts.NCstr~=0 + NCstr.labels = {'none','full','light','medium','strong','heavy'}; + NCstr.values = {0 1 2 -inf 4 5}; + stime = cat_io_cmd(sprintf('SANLM denoising (%s)',... + NCstr.labels{find(cell2mat(NCstr.values)==job.extopts.NCstr,1,'first')})); + cat_vol_sanlm(struct('data',nfname,'verb',0,'prefix','','NCstr',job.extopts.NCstr)); + fprintf('%5.0fs\n',etime(clock,stime)); + end + + %% skull-stripping detection + % ------------------------------------------------------------ + % Detect skull-stripping or defaceing because it strongly + % affects SPM segmentation that expects gaussian distribution! + % If a brain mask was used than we expect + % - many zeros (50% for small background - 80-90% for large backgrounds) + % - a smaller volume because of missing skull (below 2500 cm3) + % - only one object (the masked regions) + % - only one background (not in every case?) + % - less variance of tissue intensity (only 3 brain classes) + % - no object close to the boudary + % RD202008: Added detection of high intensity background because + % they require a very low histogram threshold to avoid + % masking of CSF intensities that are then the lowest + % values. + % RD202008: Added variable for manual overwrite that maybe allow + % to skip the processing (but the number are maybe + % intersting in the XML report. + % ------------------------------------------------------------ +% ######## RD202306: not adapted for non-zero backgounds - see cat_run_job1639 later + VFn = spm_vol(nfname); + YF = spm_read_vols(VFn); + [YF,R]= cat_vol_resize(YF,'reduceV',vx_vol,2,32,'meanm'); + YF = cat_stat_histth(YF,job.extopts.histth); + YFm = cat_stat_histth(YF,[0.95 0.95],struct('scale',[0 1])); + Oth = cat_stat_nanmean(YF(abs(YF(:))~=0 & YF(:)>cat_stat_nanmean(YF(:)))); + F0vol = cat_stat_nansum(YFm(:)>0.02) * prod(R.vx_volr) / 1000; + F0std = cat_stat_nanstd(YF(YFm(:)>0.2)/Oth); + % RD202008: improved object detection with gradient + + Yg = cat_vol_grad(YFm,R.vx_volr); + gth = max(0.05,min(0.2,median(Yg(Yg(:)>median(Yg(Yg(:)>0.1)))))); % object edge threshold + YOB = abs(YFm)>0.1 & Yg>gth; % high intensity object edges + YOB = cat_vol_morph(YOB,'ldc',8/mean(R.vx_volr)); % full object + % background + if sum(YOB(:)>0)0)>numel(YOB)*0.1 % if there is a meanful background + YBG = ~cat_vol_morph(YOB,'lc',2/mean(R.vx_volr)); % close noisy background + elseif ppe.affreg.skullstripped % RD20220316: added skull-stripping case to avoid warning + YBG = YF==0; + else + YBG = ~cat_vol_morph(YOB,'lc',2/mean(R.vx_volr)); + msg = [mfilename 'Detection of background failed.']; + cat_io_addwarning('cat_run_job:failedBGD',msg,1,[0 1]); + end + % image pricture frame to test for high intensity background in case of defaced data + hd = max(3,round(0.03 * size(YF))); + YCO = true(size(YF)); YCO(hd(1):end-hd(1)+1,hd(2):end-hd(2)+1,hd(3):end-hd(3)+1) = false; + hd = max(6,round(0.06 * size(YF))); + YCO2 = true(size(YF)); YCO2(hd(1):end-hd(1)+1,hd(2):end-hd(2)+1,hd(3):end-hd(3)+1) = false; + %% skull-stripping + [YL,numo] = spm_bwlabel(double(YF~=0),26); clear YL; %#ok % number of objects + [YL,numi] = spm_bwlabel(double(YBG==0),26); clear YL; %#ok % number of background regions + ppe.affreg.skullstrippedpara = [sum(YBG(:))/numel(YF) numo numi F0vol F0std sum(YCO2(:) .* YOB(:))/sum(YOB(:))]; + ppe.affreg.skullstripped = ... + ppe.affreg.skullstrippedpara(1)>0.5 && ... % many zeros + ppe.affreg.skullstrippedpara(2)<15 && ... % only a few objects + ppe.affreg.skullstrippedpara(3)<10 && ... % only a few background regions + F0vol<2500 && F0std<0.5 && ... % many zeros and not too big + ppe.affreg.skullstrippedpara(3)<0.02; % there should be no object (neck) very close to the boundary + ppe.affreg.skullstripped = ppe.affreg.skullstripped || ... + sum([ppe.affreg.skullstrippedpara(1)>0.8 F0vol<1500 F0std<0.4])>1; % or 2 extreme values + % not automatic detection in animals + ppe.affreg.skullstripped = ppe.affreg.skullstripped && strcmp(job.extopts.species,'human') && job.extopts.gcutstr<10; + %% high intensity background (MP2Rage) + ppe.affreg.highBGpara = [ ... + cat_stat_nanmedian( YFm( YBG(:) > 1/3 )) ... normal background + cat_stat_nanmedian( YFm( YCO(:) > 1/3 )) ... pricture frame background + cat_stat_nanstd( YFm(YBG(:)) > 1/3)]; % I am not sure if we should use the std, because inverted images are maybe quite similar + ppe.affreg.highBG = ... + ppe.affreg.highBGpara(1) > 1/5 || ... + ppe.affreg.highBGpara(2) > 1/5; + + if ~debug, clear YFC YBG YOB YCO YCO2 F0vol F0std numo numi hd; end + + % manual overwrite + switch job.extopts.input + case 1, ppe.affreg.skullstripped = 0; ppe.affreg.highBGpara = 0; + case 2, ppe.affreg.skullstripped = 1; ppe.affreg.highBGpara = 0; + case 3, ppe.affreg.skullstripped = 0; ppe.affreg.highBGpara = 1; + end + + if ppe.affreg.highBG + msg = 'Detected high intensity background use lower histrogram thresholds.'; + cat_io_addwarning([mfilename ':highBG'],msg,1,[0 1],ppe.affreg.highBGpara); + job.extopts.histth(1) = 0.999999; + end + + + + + %% Interpolation + % ----------------------------------------------------------------- + % The interpolation can help reducing problems for morphological + % operations for low resolutions and strong isotropic images. + % Especially for Dartel registration a native resolution larger than the Dartel + % resolution helps to reduce normalization artifacts of the + % deformations. Furthermore, even if artifacts can be reduced by the final smoothing + % it is much better to avoid them. + + % prepare header of resampled volume + Vi = spm_vol(job.channel(n).vols{subj}); + vx_vol = sqrt(sum(Vi.mat(1:3,1:3).^2)); + %vx_vol = round(vx_vol*10^2)/10^2; % avoid small differences + + % we have to look for the name of the field due to the GUI job struct generation! + restype = char(fieldnames(job.extopts.restypes)); + switch restype + case 'native' + vx_voli = vx_vol; + case 'fixed' + vx_voli = min(vx_vol ,job.extopts.restypes.(restype)(1) ./ ... + ((vx_vol > (job.extopts.restypes.(restype)(1)+job.extopts.restypes.(restype)(2)))+eps)); + vx_voli = max(vx_voli,job.extopts.restypes.(restype)(1) .* ... + ( vx_vol < (job.extopts.restypes.(restype)(1)-job.extopts.restypes.(restype)(2)))); + case 'best' + best_vx = max( min(vx_vol) ,job.extopts.restypes.(restype)(1)); + vx_voli = min(vx_vol ,best_vx ./ ((vx_vol > (best_vx + job.extopts.restypes.(restype)(2)))+eps)); + case 'optimal' + %% + aniso = @(vx_vol) (max(vx_vol) / min(vx_vol)^(1/3))^(1/3); % penetration factor + volres = @(vx_vol) repmat( round( aniso(vx_vol) * prod(vx_vol)^(1/3) * 10)/10 , 1 , 3); % volume resolution + optresi = @(vx_vol) min( job.extopts.restypes.(restype)(1) , max( median(vx_vol) , volres(vx_vol) ) ); % optimal resolution + optdiff = @(vx_vol) abs( vx_vol - optresi(vx_vol) ) < job.extopts.restypes.(restype)(2); % tolerance limites + optimal = @(vx_vol) vx_vol .* optdiff(vx_vol) + optresi(vx_vol) .* (1 - optdiff(vx_vol) ); % final optimal resolution + vx_voli = optimal(vx_vol); + otherwise + error('cat_run_job:restype','Unknown resolution type ''%s''. Choose between ''fixed'',''native'',''optimal'', and ''best''.',restype) + end + + % interpolation + if any( (vx_vol ~= vx_voli) ) + stime = cat_io_cmd(sprintf('Internal resampling (%4.2fx%4.2fx%4.2fmm > %4.2fx%4.2fx%4.2fmm)',vx_vol,vx_voli)); + + if 1 + imat = spm_imatrix(Vi.mat); + Vi.dim = round(Vi.dim .* vx_vol./vx_voli); + imat(7:9) = vx_voli .* sign(imat(7:9)); + Vi.mat = spm_matrix(imat); clear imat; + Vn = spm_vol(job.channel(n).vols{subj}); + cat_vol_imcalc(Vn,Vi,'i1',struct('interp',2,'verb',0,'mask',-1)); + else + %% Small improvement for CAT12.9 that uses the cat_vol_resize function rather than the simple interpolation. + % However, postive effects only in case of strong reductions >2, ie. it is nearly useless. + jobr = struct(); + jobr.data = {Vi.fname}; + jobr.interp = -3005; % spline with smoothing in case of downsampling; default without smoothing -5; + jobr.verb = debug; + jobr.lazy = 0; + jobr.prefix = ''; + jobr.restype.res = vx_voli; % use other resolution for test + cat_vol_resize(jobr); + end + vx_vol = vx_voli; + + fprintf('%5.0fs\n',etime(clock,stime)); + else + vx_vol = sqrt(sum(Vi.mat(1:3,1:3).^2)); + end + + clear Vi Vn; + + + %% Affine Preprocessing (APP) with SPM + % ------------------------------------------------------------ + % Bias correction is essential for stable affine registration + % but also the following preprocessing. This approach uses the + % SPM Unified segmentation for intial bias correction of the + % input data with different FWHMs (low to high frequency) and + % resolutions (low to high). + % ------------------------------------------------------------ + if job.extopts.APP == 1 + job.subj = subj; + [Ym,Ybg,WMth] = cat_run_job_APP_SPMinit(job,tpm,ppe,n,... + ofname,nfname,mrifolder,ppe.affreg.skullstripped); + end + end + job.extopts.gcutstr = mod(job.extopts.gcutstr,10); + + + + % MP2RAGE skull-stripping & bias-correction + if ppe.affreg.highBG + stime = cat_io_cmd('Additional MP2RAGE preprocessing'); + + % mp2rage preprocessing options + mp2job.ofiles = {ofname}; + mp2job.files = {nfname}; % list of MP2Rage images + mp2job.headtrimming = 0; % trimming to brain or head (*0-none*,1-brain,2-head) + mp2job.biascorrection = 1; % biascorrection (0-no,1-light(SPM60mm),2-average(SPM60mm+X,3-strong(SPM30+X)) ####### + mp2job.skullstripping = 3; % skull-stripping (0-no, 1-SPM, 2-optimized, 3-*background-removal*) + mp2job.logscale = inf; % use log/exp scaling for more equally distributed + % tissues (0-none, 1-log, -1-exp, inf-*auto*); + mp2job.intnorm = -.25; % contrast normalization using the tan of GM normed + % values with values between 1.0 - 2.0 for light to + % strong adaptiong (0-none, 1..2-manuel, -0..-2-*auto*) + mp2job.restoreLCSFnoise = 1; % restore values below zero (lower CSF noise) + mp2job.prefix = ''; % filename prefix (strong with PARA for parameter + % depending naming, e.g. ... ) + mp2job.spm_preprocessing = 2; % do SPM preprocessing (0-no, 1-yes (if required), 2-always) + mp2job.spm_cleanupfiles = 1; % remove temporary files + mp2job.report = 0; % create a report + mp2job.verb = 0; % be verbose (0-no,1-yes,2-details) + + % adapt tissue class number + job.opts.ngaus(3) = 1; % at least for CSF we should avoid further peaks + if mp2job.skullstripping>0 % no skull-stripping triggered non-T1 case + % with skull-stripping we keep things simple + job.opts.ngaus(4) = 1; + job.opts.ngaus(5) = 1; + job.opts.ngaus(6) = 1; + end + + % call mp2rage preprocessing + cat_vol_mp2rage(mp2job); + ppe.affreg.skullstripped = mp2job.skullstripping==1 | mp2job.skullstripping==2; + + fprintf('%5.0fs\n',etime(clock,stime)); + end + + + % prepare SPM preprocessing structure + images = job.channel(1).vols{subj}; + for n=2:numel(job.channel) + images = char(images,job.channel(n).vols{subj}); + end + obj.image = spm_vol(images); + obj.fwhm = job.opts.fwhm; + obj.biasreg = job.opts.biasreg; + obj.biasfwhm = job.opts.biasfwhm; + obj.tpm = tpm; + obj.reg = job.opts.warpreg; + obj.samp = job.opts.samp; % resolution of SPM preprocessing (def. 3, 1.5 as last highest TPM optimal level) + obj.tol = job.opts.tol; % stopping criteria for SPM iteration of outer/inner loops + obj.newtol = 1 + ( isfield(job,'useprior') && ~isempty(job.useprior) ); + % stopping criteria for outer (=tol) and inner loop: + % -1-old SPM (>9 iters, inner=tol), + % 0-old CAT more outer iterations (>19 iter, inner=tol), + % 1-new optimal/faster with additional AUC criteria to have SPM minimum iterations (>9 iters, inner=1e-2) + % 2-new accurate with additioal AUC criteria but CAT minimum iterations (>19 iter, outer=tol, inner=1e-4) - like 0 + obj.lkp = []; + if ~strcmp('human',job.extopts.species) + % RD202105: There are multiple problems in primates and increased + % accuracy is maybe better (eg. 0.5 - 0.66) + scannorm = 0.7; %prod(obj.image.dims .* vx_vol).^(1/3) / 20; % variance from typical field fo view to normalized parameter + obj.samp = obj.samp * scannorm; % normalize by voxel size + obj.fwhm = obj.fwhm * scannorm; + end + if all(isfinite(cat(1,job.tissue.ngaus))) + for k=1:numel(job.tissue) + obj.lkp = [obj.lkp ones(1,job.tissue(k).ngaus)*k]; + end + end + spm_check_orientations(obj.image); + cat_err_res.obj = obj; + + %% Initial affine registration. + % ----------------------------------------------------------------- + Affine = eye(4); + [pp,ff] = spm_fileparts(job.channel(1).vols{subj}); + Pbt = fullfile(pp,mrifolder,['brainmask_' ff '.nii']); + Pb = char(job.extopts.brainmask); + Pt1 = char(job.extopts.T1); + + if ~isempty(job.opts.affreg) + % first affine registration (with APP) + + % load template and remove the skull if the image is skull-stripped + try + VG = spm_vol(Pt1); + catch + pause(rand(1)) + VG = spm_vol(Pt1); + end + VF = spm_vol(obj.image(1)); + + % skull-stripping of the template + if ppe.affreg.skullstripped || job.extopts.gcutstr<0 + % print a warning for all users that did not turn off skull-stripping + % because processing of skull-stripped data is not standard! + if (job.extopts.gcutstr>=0 || job.test_warnings) && ~ppe.affreg.highBG + msg = [... + 'Detected skull-stripped or strongly masked image. Skip APP. \\n' ... + 'Use skull-stripped initial affine registration template and \\n' ... + 'TPM without head tissues (class 4 and 5)!']; + if job.extopts.verb>1 && job.extopts.expertgui + msg = [msg sprintf(['\\\\n BG: %0.2f%%%%%%%% zeros; %d object(s); %d background region(s) \\\\n' ... + ' %4.0f cm%s; normalized SD of all tissues %0.2f'],... + ppe.affreg.skullstrippedpara(1:4),native2unicode(179, 'latin1'),ppe.affreg.skullstrippedpara(5))]; + end + cat_io_addwarning([mfilename ':skullStrippedInputWithSkullStripping'],msg,1,[0 1],ppe.affreg.skullstrippedpara); + + elseif job.extopts.gcutstr<0 && ~ppe.affreg.skullstripped || job.test_warnings + cat_io_addwarning([mfilename ':noSkullStrippingButSkull'],[... + 'Skull-Stripping is deactivated but skull was detected. \\n' ... + 'Go on without skull-stripping what possibly will fail.'],0,[0 1],ppe.affreg.skullstrippedpara); + end + + % skull-stripping of the template + VB = spm_vol(Pb); + [VB2,YB] = cat_vol_imcalc([VG,VB],Pbt,'i1 .* i2',struct('interp',3,'verb',0,'mask',-1)); + VB2.dat(:,:,:) = eval(sprintf('%s(YB/max(YB(:))*255);',spm_type(VB2.dt))); + VB2.pinfo = repmat([1;0],1,size(YB,3)); + VG = cat_spm_smoothto8bit(VB2,0.5); + clear VB2 YB; + end + + % Rescale images so that globals are better conditioned + VF.pinfo(1:2,:) = VF.pinfo(1:2,:)/spm_global(VF); + VG.pinfo(1:2,:) = VG.pinfo(1:2,:)/spm_global(VG); + + % APP step 1 rough bias correction and preparation of the affine + % registration + % -------------------------------------------------------------- + % Already for the rough initial affine registration a simple + % bias corrected and intensity scaled image is required, because + % large head intensities can disturb the whole process. + % -------------------------------------------------------------- + % ds('l2','',vx_vol,Ym, Yt + 2*Ybg,obj.image.private.dat(:,:,:)/WMth,Ym,60) + if job.extopts.APP == 1070 && ~ppe.affreg.highBG && ... + ( ~isfield(job,'useprior') || isempty(job.useprior) ) + stime = cat_io_cmd('Affine preprocessing (APP)'); + Ysrc = single(obj.image.private.dat(:,:,:)); + try + [Ym,Yt,Ybg,WMth] = cat_run_job_APP_init1070(Ysrc,vx_vol,job.extopts.verb); %#ok + catch apperr + %% very simple affine preprocessing ... only simple warning + cat_io_addwarning([mfilename ':APPerror'],'APP failed. Use simple scaling.',1,[0 0],apperr); + [Ym,Yt,Ybg,WMth] = APPmini(obj,VF,job.extopts.histth); %#ok + if cat_get_defaults('extopts.send_info') + urlinfo = sprintf('%s%s%s%s%s%s%s%s%s%s',cat_version,'%2F',computer,'%2F','errors',... + '%2F','cat_run_job:failedAPP','%2F','WARNING: APP failed. Use simple scaling.','cat_run_job'); + cat_io_send_to_server(urlinfo); + end + end + APPRMS = checkAPP(Ym,Ysrc,job.extopts.histth); + if APPRMS>1 || job.test_warnings + if job.extopts.ignoreErrors < 1 + fprintf('\n'); + error([mfilename ':APPerror'],'Detect problems in APP preprocessing (APPRMS: %0.4f). Do not use APP results. ',APPRMS); + else + cat_io_addwarning([mfilename ':APPerror'],... + sprintf('Detect problems in APP preprocessing (APPRMS: %0.4f). \\\\nDo not use APP results. ',APPRMS),1,[0 1],APPRMS); + end + end + + if ~( job.extopts.setCOM && ~( isfield(job,'useprior') && ~isempty(job.useprior) ) && ~ppe.affreg.highBG ) + stime = cat_io_cmd('Affine registration','','',1,stime); + end + + % write data to VF + VF.dt = [spm_type('UINT8') spm_platform('bigend')]; + VF.dat(:,:,:) = cat_vol_ctype(Ym * 200,'uint8'); + VF.pinfo = repmat([1;0],1,size(Ym,3)); +if 0 % new + % use further data limitation and remove background for affreg + [Ym2,ths] = cat_stat_histth(Ym,job.extopts.histth); + Ym2 = (Ym2 - ths(1)) ./ diff(ths) .* (1 - Ybg); + VF.dat(:,:,:) = cat_vol_ctype(Ym2 * 200,'uint8'); +end + clear WI; + + % smoothing + resa = obj.samp*2; % definine smoothing by sample size + VF1 = spm_smoothto8bit(VF,resa); + VG1 = spm_smoothto8bit(VG,resa); + + elseif job.extopts.APP == 1 + % APP by SPM + VF.dt = [spm_type('UINT8') spm_platform('bigend')]; + VF.dat(:,:,:) = cat_vol_ctype(Ym * 200,'uint8'); + VF.pinfo = repmat([1;0],1,size(Ym,3)); + + % smoothing + resa = obj.samp*2; % definine smoothing by sample size + VF1 = spm_smoothto8bit(VF,resa); + VG1 = spm_smoothto8bit(VG,resa); + + elseif job.extopts.setCOM && ~( isfield(job,'useprior') && ~isempty(job.useprior) ) && ~ppe.affreg.highBG + % standard approach (no APP) with static resa value and no VG smoothing + stime = cat_io_cmd('Coarse affine registration'); + resa = 8; + VF1 = spm_smoothto8bit(VF,resa); + VG1 = VG; + [Ym,Yt,Ybg,WMth] = APPmini(obj,VF,job.extopts.histth); + else + stime = cat_io_cmd('Skip initial affine registration due to high-intensity background','','',1); + VF = spm_vol(obj.image(1)); + [Ym,Yt,Ybg,WMth] = APPmini(obj,VF,job.extopts.histth); + end + + %% prepare affine parameter + aflags = struct('sep',obj.samp,'regtype','subj','WG',[],'WF',[],'globnorm',1); + aflags.sep = max(aflags.sep,max(sqrt(sum(VG(1).mat(1:3,1:3).^2)))); + aflags.sep = max(aflags.sep,max(sqrt(sum(VF(1).mat(1:3,1:3).^2)))); + + % use affine transformation of given (average) data for longitudinal mode + if isfield(job,'useprior') && ~isempty(job.useprior) + % even in the development pipeline the prior is a good start ! + priorname = job.useprior{1}; + [pp,ff,ee,ex] = spm_fileparts(priorname); %#ok + catxml = fullfile(pp,reportfolder,['cat_' ff '.xml']); + + % check that file exists and get affine transformation + if exist(catxml,'file') + if strcmp(job.opts.affreg,'prior') + fprintf('\nUse affine transformation from:\n%s\n',priorname); + else + fprintf('\nInitialize with affine transformation from:\n%s\n',priorname); + end + stime = cat_io_cmd(' ',' ','',job.extopts.verb); + xml = cat_io_xml(catxml); + % sometimes xml file does not contain affine transformation + if ~isfield(xml,'SPMpreprocessing') + cat_io_cprintf('warn',sprintf('WARNING: File ""%s"" does not contain successful affine transformation. Use individual affine transformation\n',catxml)); + Affine = eye(4); + useprior = 0; + else + Affine = xml.SPMpreprocessing.Affine; + affscale = 1; + useprior = 1 + ~strcmp(job.opts.affreg,'prior'); + end + else + cat_io_cprintf('warn',sprintf('WARNING: File ""%s"" not found. Use individual affine transformation\n',catxml)); + Affine = eye(4); + useprior = 0; + end + clear catxml; + + % RD202010: The AVG contains much more background that can + % cause a lot of trouble if not modelled ! + obj.lkp(obj.lkp == 6) = []; + obj.lkp = [ obj.lkp 6*ones(1,8) ]; + else + %% + Affine = eye(4); + useprior = 0; + end + + % correct origin using COM and invert translation and use it as starting value + if job.extopts.setCOM && ~useprior && ~ppe.affreg.highBG + fprintf('\n'); stime = clock; + Affine_com = cat_vol_set_com(VF1); + Affine_com(1:3,4) = -Affine_com(1:3,4); + else + Affine_com = eye(4); + end + + if strcmp('human',job.extopts.species) && ~useprior && ~ppe.affreg.highBG + % affine registration + try + spm_plot_convergence('Init','Coarse affine registration','Mean squared difference','Iteration'); + catch + spm_chi2_plot('Init','Coarse affine registration','Mean squared difference','Iteration'); + end + + try + evalc('[Affine0, affscale] = spm_affreg(VG1, VF1, aflags, Affine_com); Affine = Affine0;'); + catch + affscale = 0; + end + % RD202007: Unimportant information if maff8 works + if job.extopts.expertgui + if affscale>3 || affscale<0.5 + stime = cat_io_cmd(' Coarse affine registration failed. Try fine affine registration.','','',1,stime); + Affine = Affine_com; + end + end + elseif strcmp('human',job.extopts.species) && ~useprior && ppe.affreg.highBG + Affine = Affine_com; + Affine1 = Affine; + end + + + %% APP step 2 - brainmasking and second tissue separated bias correction + % --------------------------------------------------------- + % The second part of APP maps a brainmask to native space and + % refines it by morphologic operations and region-growing to + % adapt for worse initial affine alignments. It is important + % that the mask covers the whole brain, whereas additional + % masked head is here less problematic. + % --------------------------------------------------------- + % ds('l2','',vx_vol,Ym,Yb,Ym,Yp0,90) + + % fine affine registration + if strcmp('human',job.extopts.species) && ~useprior && ~ppe.affreg.highBG + aflags.sep = obj.samp/2; + aflags.sep = max(aflags.sep,max(sqrt(sum(VG(1).mat(1:3,1:3).^2)))); + aflags.sep = max(aflags.sep,max(sqrt(sum(VF(1).mat(1:3,1:3).^2)))); + + stime = cat_io_cmd('Affine registration','','',1,stime); + if job.extopts.APP > 0 + VF.dt = [spm_type('UINT8') spm_platform('bigend')]; + VF.pinfo = repmat([1;0],1,size(Ym,3)); + VF.dat(:,:,:) = cat_vol_ctype(Ym*200); + end + VF1 = spm_smoothto8bit(VF,aflags.sep); + VG1 = spm_smoothto8bit(VG,aflags.sep); + + try + spm_plot_convergence('Init','Affine registration','Mean squared difference','Iteration'); + catch + spm_chi2_plot('Init','Affine registration','Mean squared difference','Iteration'); + end + warning off + if ~exist('affscale','var'), affscale = 1.0; end + evalc('[Affine1,affscale1] = spm_affreg(VG1, VF1, aflags, Affine, affscale);'); + warning on + if ~any(any(isnan(Affine1(1:3,:)))) && affscale1>0.5 && affscale1<3, Affine = Affine1; end + end + clear VG1 VF1 + + else + % no affine registration and preprocessing at all and just prepare the data + VF = spm_vol(obj.image(1)); + [Ym,Yt,Ybg,WMth] = APPmini(obj,VF,job.extopts.histth); %#ok + if ~debug, clear Yt; end + useprior = 0; + Affine = eye(4); + end + + + + %% Lesion masking as zero values of the orignal image (2018-06): + % We do not use NaN and -INF because (i) most images are only (u)int16 + % and do not allow such values, (ii) NaN can be part of the background + % of resliced images, and (iii) multiple options are not required here. + % Zero values can also occure by poor data scaling or processing in the + % background but also by other (large) CSF regions and we have to remove + % these regions later. + % We further discussed to use a separate mask images but finally decided + % to keep this as simple as possible using no additional options! + % Moreover, we have to test here anyway to create warnings in case + % of inoptimal settings (e.g. no SLC but possible large lesions). + obj.image0 = spm_vol(job.channel(1).vols0{subj}); + Ysrc0 = spm_read_vols(obj.image0); + Ylesion = single(Ysrc0==0 | isnan(Ysrc0) | isinf(Ysrc0)); + Ylesion(smooth3(Ylesion)<0.5)=0; % general denoising + if any( obj.image0.dim ~= obj.image.dim ) + mat = obj.image0.mat \ obj.image.mat; + Ylesion = smooth3(Ylesion); + Ylesionr = zeros(obj.image.dim,'single'); + for i=1:obj.image.dim(3) + Ylesionr(:,:,i) = single(spm_slice_vol(Ylesion,mat*spm_matrix([0 0 i]),obj.image.dim(1:2),[1,NaN])); + end + Ylesion = Ylesionr>0.5; clear Ylesionr; + end + if exist('Ybg','var'), Ylesion(Ybg)=0; end % denoising in background + % use brainmask + VFa = VF; VFa.mat = Affine * VF.mat; %Fa.mat = res0(2).Affine * VF.mat; + if isfield(VFa,'dat'), VFa = rmfield(VFa,'dat'); end + if ~ppe.affreg.skullstripped + [Vmsk,Yb] = cat_vol_imcalc([VFa,spm_vol(Pb)],Pbt,'i2',struct('interp',3,'verb',0,'mask',-1)); clear Vmsk; %#ok + else + Yb = smooth3(Ysrc0~=ppe.affreg.skullstrippedBGth); + if any( obj.image0.dim ~= obj.image.dim ) + mat = obj.image0.mat \ obj.image.mat; + Yb = smooth3(Yb); + Ybr = zeros(obj.image.dim,'single'); + for i=1:obj.image.dim(3) + Ybr(:,:,i) = single(spm_slice_vol(Yb,mat*spm_matrix([0 0 i]),obj.image.dim(1:2),[1,NaN])); + end + Yb = Ybr>0.5; clear Ybr; + end + end + Ylesion = Ylesion & ~cat_vol_morph(Yb<0.9,'dd',5); clear Yb Ysrc0; + % check settings + % RD202105: in primates the data, template and affreg is often inoptimal so we skip this test + if sum(Ylesion(:))/prod(vx_vol)/1000 > 1 && ~(ppe.affreg.highBG || ppe.affreg.skullstripped) && strcmp('human',job.extopts.species) + fprintf('%5.0fs\n',etime(clock,stime)); stime = []; + if ~job.extopts.SLC + % this could be critical and we use a warning for >1 cm3 and an alert in case of >10 cm3 + cat_io_addwarning([mfilename ':StrokeLesionButNoCorrection'],sprintf( ... + ['There are %0.2f cm%s of zeros within the brain but Stroke Lesion \\\\n', ... + 'Correction (SLC) inactive (available in the expert mode). '], ... + sum(Ylesion(:))/1000,native2unicode(179, 'latin1')),1 + (sum(Ylesion(:))/1000 > 10),[0 1]); + clear Ylesion; + else + cat_io_cprintf('note',sprintf('SLC: Found masked region of %0.2f cm%s. \n', sum(Ylesion(:))/1000,native2unicode(179, 'latin1'))); + end + end + + %% APP for spm_maff8 + % optimize intensity range + % we have to rewrite the image, because SPM reads it again + if job.extopts.APP > 0 + % WM threshold + Ysrc = single(obj.image.private.dat(:,:,:)); + Ysrc(isnan(Ysrc) | isinf(Ysrc)) = min(Ysrc(:)); + + if job.extopts.APP == 1070 + % APPinit is just a simple bias correction for affreg and should + % not be used further although it maybe helps in some cases! + Ymc = Ysrc; + else + bth = min( [ mean(single(Ysrc( Ybg(:)))) - 2*std(single(Ysrc( Ybg(:)))) , ... + mean(single(Ysrc(~Ybg(:)))) - 4*std(single(Ysrc(~Ybg(:)))) , ... + min(single(Ysrc(~Ybg(:)))) ]); + % use bias corrected image with original intensities + Ymc = Ym * abs(diff([bth,WMth])) + bth; + clear bth + end + + % set variable and write image + obj.image.dat(:,:,:) = Ymc; + obj.image.pinfo = repmat([255;0],1,size(Ymc,3)); + obj.image.private.dat(:,:,:) = Ymc; % = WRITE FILE + + obj.image.dt = [spm_type('FLOAT32') spm_platform('bigend')]; + obj.image.pinfo = repmat([1;0],1,size(Ymc,3)); + + % mask the eroded background + % RD202006: masking of distant background + % This has strong effects for some images but I found no good + % explanation how to use the mask. However, it seems that it is + % useful to mask unclear and/or bad background voxels but not + % all of them. So we use the eroded background segment mask and + % remove also regions with 0 and no gradient that are often the + % result of defacing, skull-stripping and reslicing. + % RD202006: SVE 32 dataset + % We use a noisy corona here to avoid that SPM try to fit a + % head class into it. + % RD202006: thickness phantom problems + % Masking causes general problems in SPM US with Christian's + % thickness phantom (brain PVE voxels were aligned to class 5) + % that required further correction in cat_main_updateSPM. + isSPMtpm = strcmp(job.extopts.species,'human') && ... + ( strcmp(job.opts.tpm , fullfile(spm('dir'),'tpm','TPM.nii') ) || ... + strcmp(job.opts.tpm , fullfile(spm('dir'),'tpm','TPM.nii,1') ) ); + [ppt,fft] = spm_fileparts(job.opts.tpm{1}); + isLONGtpm = strcmp(fft(1:min(numel(fft),7)),'longTPM'); + if exist('Ybg','var') && job.extopts.setCOM ~= 120 % case 120 no msk at all + if ~isempty(job.useprior) || job.extopts.new_release + if job.extopts.setCOM == 122 + % RD202006 background corona to have save background values + Ymsk = cat_vol_morph(Ybg,'de',10,vx_vol) | ... % define background for cat_main_updateSPM + ( cat_vol_grad( Ysrc , vx_vol)==0 & Ysrc==0 ); % RD202006: set value arbitrary to 10 mm + else + % RD202006 background random msk to have save background values + Ymsk = cat_vol_morph( ~Ybg ,'dd',15,vx_vol) & ... % remove voxels far from head + ~( Ybg & rand(size(Ybg))>0.5) & ... % have a noisy corona + ~( cat_vol_grad( Ysrc , vx_vol)==0 & Ysrc==0 ); % remove voxel that are 0 and have no gradient + end + else + % RD20220103: old cross-sectional setting with small correction for own TPMs + if isSPMtpm || isLONGtpm + Ymsk = ~Ybg; % old default - mask background + else + cat_io_addwarning([mfilename ':noSPMTPM-noBGmasking'],... + 'Different TPM detected - deactivated background masking!',1,[1 2]); + Ymsk = []; % new special case for other TPMs + end + end + if ~isempty( Ymsk ) + obj.msk = VF; + obj.msk.pinfo = repmat([255;0],1,size(Ybg,3)); + obj.msk.dt = [spm_type('uint8') spm_platform('bigend')]; + obj.msk.dat = uint8( Ymsk ); + obj.msk = spm_smoothto8bit(obj.msk,0.1); + end + end + clear Ysrc Ymsk; + else + % defintion of basic variables in case of no APP + obj.image.dat(:,:,:) = single(obj.image.private.dat(:,:,:)); + obj.image.dt = [spm_type('FLOAT32') spm_platform('bigend')]; + obj.image.pinfo = repmat([255;0],1,size(obj.image.dat,3)); + + % no masking ! + end + + + + + %% Fine affine Registration with automatic selection in case of multiple TPMs. + % This may not work for non human data (or very small brains). + % This part should be an external (coop?) function? + if useprior==1 + stime = cat_io_cmd('SPM preprocessing 1 (estimate 1 - use prior):','','',1,stime); + elseif job.extopts.setCOM == 10 % no maffreg + stime = cat_io_cmd('SPM preprocessing 1 (estimate 1 - use no TPM registration):','','',1,stime); + else + stime = cat_io_cmd('SPM preprocessing 1 (estimate 1 - TPM registration):','','',1,stime); + end + if ~isempty(job.opts.affreg) && strcmp('human',job.extopts.species) && ~useprior && job.extopts.setCOM ~= 10 % setcom == 10 - never use + % turn rand warning off + wo = warning('QUERY','MATLAB:RandStream:ActivatingLegacyGenerators'); wo = strfind( wo.state , 'on'); + if wo, warning('OFF','MATLAB:RandStream:ActivatingLegacyGenerators'); end + + if strcmp(job.extopts.species,'human') + %% only one TPM (old approach); + spm_plot_convergence('Init','affine registration to TPM','Mean squared difference','Iteration'); + + % first we start with the given affine registration and affreg parameter (e.g. mni) and a very low resolution + % RD202007: also here different maskings could be tested - however, it looks quite stable now + [Affine2,ppe.spm_maff8.ll(1)] = spm_maff8(obj.image(1),obj.samp,(obj.fwhm+1)*16,obj.tpm,Affine ,job.opts.affreg,80); + scl1 = abs(det(Affine1(1:3,1:3))); + scl2 = abs(det(Affine2(1:3,1:3))); + + %CG202010: disabled, because it's not working yet + if 0 % new approach with multiple tests + ppe.spm_maff8.ll_help = ['ll(1) with affreg result, ll(2) without spm_affreg init, ' ... + 'll(3) without spm_affreg and with opts.affreg=none; only test further cases if ll(i)<0.9']; + if ppe.spm_maff8.ll(1)<0.9 + % if there was no high overlap than we try if maff8 supports better results without affreg initialization + [Affine2o,ppe.spm_maff8.ll(2)] = spm_maff8(obj.image(1),obj.samp,(obj.fwhm+1)*16,obj.tpm,eye(4),job.opts.affreg,80); + Affine2 = Affine2o; + if ppe.spm_maff8.ll(2)<0.9 + % especially for very small heads the mni definition is not good + % we start here with the maff8 that is more robust to varying contrasts + [Affine2n,ppe.spm_maff8.ll(3)] = spm_maff8(obj.image(1),obj.samp,(obj.fwhm+1)*16,obj.tpm,eye(4),'none',80); + if ppe.spm_maff8.ll(3) > ppe.spm_maff8.ll(2) + cat_io_addwarning([mfilename ':spm_maff8n'],'Use affreg=none due to better results.',1,[1 2],ppe.spm_maff8); + job.opts.affreg = 'none'; % in this case we have to update the affreg parameter + Affine2 = Affine2n; + else + if ppe.spm_maff8.ll(1) < ppe.spm_maff8.ll(2) + Affine2 = Affine2o; + end + end + end + end + end + + % if nan than retry with less smoothing + if any(any(isnan(Affine2(1:3,:)))) + [Affine2,ppe.spm_maff8.ll(end+1)] = spm_maff8(obj.image(1),obj.samp,(obj.fwhm+1)*4,obj.tpm,Affine ,job.opts.affreg,80); + if any(any(isnan(Affine2(1:3,:)))) + Affine2 = Affine; + end + else + % check for > 10% larger scaling + if scl1 > 1.1*scl2 && job.extopts.setCOM ~= 11 % setcom == 11 - use always + cat_io_addwarning([mfilename ':spm_maff8i'], ... + ['Inital affine registration to TPM failed, try fine.'], 1,[1 2],ppe.spm_maff8.ll(end)); + Affine2 = Affine1; + scl2 = scl1; + end + + % after this initial step we do some refined registration with less smoothing + [Affine3,ppe.spm_maff8.ll(end+1)] = spm_maff8(obj.image(1),obj.samp,obj.fwhm,obj.tpm,Affine2,job.opts.affreg,80); + + if ~any(any(isnan(Affine3(1:3,:)))) + scl3 = abs(det(Affine3(1:3,1:3))); + % check for > 5% larger scaling + if scl2 > 1.05*scl3 && job.extopts.setCOM ~= 11 % setcom == 11 - use always + cat_io_addwarning([mfilename ':spm_maff8f'], ... + ['Final affine registration to TPM failed.\\n' ... + 'Use affine registration from previous sucessful step.'], 1,[1 2],ppe.spm_maff8.ll(end)); + Affine2 = Affine1; + %scl2 = scl1; + Affine = Affine2; + else + Affine = Affine3; + end + else % Affine3 failed (NaN), use Affine2 + Affine = Affine2; + end + end + + % turn warning on + if wo, warning('ON','MATLAB:RandStream:ActivatingLegacyGenerators'); end + end + end + if 0 + %% visual control for development and debugging + VFa = VF; VFa.mat = Affine * VF.mat; %Fa.mat = res0(2).Affine * VF.mat; + if isfield(VFa,'dat'), VFa = rmfield(VFa,'dat'); end + [Vmsk,Yb] = cat_vol_imcalc([VFa,spm_vol(Pb)],Pbt,'i2',struct('interp',3,'verb',0,'mask',-1)); + %[Vmsk,Yb] = cat_vol_imcalc([VFa;obj.tpm.V(1:3)],Pbt,'i2 + i3 + i4',struct('interp',3,'verb',0)); + %[Vmsk,Yb] = cat_vol_imcalc([VFa;obj.tpm.V(5)],Pbt,'i2',struct('interp',3,'verb',0)); + ds('d2sm','',1,Ym,Ym.*(Yb>0.5),round(size(Yb,3)*0.6)) + end + + + %% test for flipping + %fliptest = 1; % 1 - test x>1, 2 - test for shearing + %[ppe.affreg.flipped, ppe.affreg.flippedval,stime] = cat_vol_testflipping(obj,Affine,fliptest,stime,0); + + if isfield(ppe.affreg,'skullstripped') && ~ppe.affreg.skullstripped + %% affreg with brainmask + if debug + [AffineN,Ybi,Ymi,Ym0] = cat_run_job_APRGs(Ym,Ybg,VF,Pb,Pbt,Affine,vx_vol,obj,job); %#ok + else + [AffineN,Ybi] = cat_run_job_APRGs(Ym,Ybg,VF,Pb,Pbt,Affine,vx_vol,obj,job); + end + if ~useprior, Affine = AffineN; end + clear AffineN; + end + + if ppe.affreg.skullstripped || job.extopts.gcutstr<0 + %% update number of SPM gaussian classes + Ybg = 1 - spm_read_vols(obj.tpm.V(1)) - spm_read_vols(obj.tpm.V(2)) - spm_read_vols(obj.tpm.V(3)); + noCSF = job.extopts.gcutstr == -2; + if 1 + for k=1:3 - noCSF + obj.tpm.dat{k} = spm_read_vols(obj.tpm.V(k)); + obj.tpm.V(k).dt(1) = 64; + obj.tpm.V(k).dat = double(obj.tpm.dat{k}); + obj.tpm.V(k).pinfo = repmat([1;0],1,size(Ybg,3)); + end + end + + obj.tpm.V(4 - noCSF).dat = Ybg; + obj.tpm.dat{4 - noCSF} = Ybg; + obj.tpm.V(4 - noCSF).pinfo = repmat([1;0],1,size(Ybg,3)); + obj.tpm.V(4 - noCSF).dt(1) = 64; + obj.tpm.dat(5 - noCSF:6) = []; + obj.tpm.V(5 - noCSF:6) = []; + obj.tpm.bg1(4 - noCSF) = obj.tpm.bg1(6); + obj.tpm.bg2(4 - noCSF) = obj.tpm.bg1(6); + obj.tpm.bg1(5 - noCSF:6) = []; + obj.tpm.bg2(5 - noCSF:6) = []; + %obj.tpm.V = rmfield(obj.tpm.V,'private'); + + % tryed 3 peaks per class, but BG detection error require manual + % correction (set 0) that is simple with only one class + % RD202306: SPM is not considering things without variation and + % a zeroed background is simply not existing! + % Moreover it is possible just to ignore classes :D + % Hence, we may not need to redefine the TPM at all. + if noCSF + job.opts.ngaus = [([job.tissue(1:2).ngaus])',1]; % gaussian background + else + job.opts.ngaus = ([job.tissue(1:3).ngaus])'; % no gaussian background + end + obj.lkp = []; + for k=1:numel(job.opts.ngaus) + job.tissue(k).ngaus = job.opts.ngaus(k); + obj.lkp = [obj.lkp ones(1,job.tissue(k).ngaus)*k]; + end + end + + % adpation parameter for affine registration? 0.98 and 1.02? + if isfield(job.extopts,'affmod') && any(job.extopts.affmod) + stime = cat_io_cmd(' Modify affine regitration:','','',1,stime); + AffineUnmod = Affine; + if numel(job.extopts.affmod)>6, job.extopts.affmod = job.extopts.affmod(1:6); end % remove too many + if numel(job.extopts.affmod)<3, job.extopts.affmod(end+1:3) = job.extopts.affmod(1); end % isotropic + if numel(job.extopts.affmod)<6, job.extopts.affmod(end+1:6) = 0; end % add translation + fprintf('\n Modify affine regitration (S=[%+3d%+3d%+3d], T=[%+3d%+3d%+3d])',job.extopts.affmod); + sf = (100 - job.extopts.affmod(1:3)) / 100; + imat = spm_imatrix(Affine); + COMc = [eye(4,3), [ 0; -24 / mean(imat(7:9)); -12 / mean(imat(7:9)); 1] ]; + imat = spm_imatrix(Affine * COMc); + imat(1:3) = imat(1:3) - job.extopts.affmod(4:6); + imat(7:9) = imat(7:9) .* sf; + AffineMod = spm_matrix(imat) / COMc; + + res.AffineUnmod = AffineUnmod; + res.AffineMod = AffineMod; + else + AffineMod = Affine; + end + obj.Affine = AffineMod; + cat_err_res.obj = obj; + + + %% SPM preprocessing 1 + % ds('l2','a',0.5,Ym,Ybg,Ym,Ym,140); + % ds('l2','a',0.5,Ysrc/WMth,Yb,Ysrc/WMth,Yb,140); + warning off + try + %% inital estimate + stime = cat_io_cmd('SPM preprocessing 1 (estimate 2):','','',job.extopts.verb-1,stime); + obj.tol = job.opts.tol; % reset within loop + + % RD202012: Missclassification of GM as CSF and BG as tissue: + % We observed problems with high-quality data (e.g. AVGs) and + % interpolated low resolution data (single_subT1=Collins), + % where (low-intensity) GM was missclassified as CSF but also + % miss-classification of background. The problems where caused + % by the US (or better the way we use it here) and higher + % accuracy (increased number of minimum iterations in + % cat_spm_preproc8) was essential. Nevertheless, some + % cases still cause severe errors at 3 mm sample size but + % not for other resolutions (eg. 4, 6, 2 mm). In addition, the + % log-likelihood became NaN in such cases. Hence, I added a + % little loop her to test other resolutions for samp. We keep + % the output here quit simple to avoid confusion. samp is a + % rarely used expert parameter and other resolutions are only + % used as backup and the effects should be not too strong for + % normal data without strong bias. + + % sampling resolution definition + if round(obj.samp) == 3, samp = [obj.samp 4 2]; + elseif round(obj.samp) == 2, samp = [obj.samp 3 4]; + elseif ~strcmp(job.extopts.species,'human') + samp = [obj.samp obj.samp*2 obj.samp/2]; + else, samp = [obj.samp 3 2]; + end + + if job.opts.redspmres + image1 = obj.image; + [obj.image,redspmres] = cat_vol_resize(obj.image,'interpv',1); + end + + % run loop until you get a non NaN + % #### additional threshold is maybe also helpful #### + warning off; % turn off ""Warning: Using 'state' to set RANDN's internal state causes RAND ..."" + for sampi = 1:numel(samp) + obj.samp = samp(sampi); + try + res = cat_spm_preproc8(obj); + if any(~isnan(res.ll)) + break + else + stime = cat_io_cmd(sprintf('SPM preprocessing 1 (estimate %d):',... + 2 + sampi),'caution','',job.extopts.verb-1,stime); + end + catch + % RD202110: Catch real errors of cat_spm_preproc8 and try a + % skull-stripped version just to get some result. + stime = cat_io_cmd(sprintf('SPM preprocessing 1 (estimate %d skull-stripped):',... + 2 + sampi),'caution','',job.extopts.verb-1,stime); + if exist('Ybi','var') % use individual mask + obj.image.dat = obj.image.dat .* (cat_vbdist(single(Ybi>0.5))<10); + else % use template mask + VFa = VF; VFa.mat = Affine * VF.mat; %Fa.mat = res0(2).Affine * VF.mat; + if isfield(VFa,'dat'), VFa = rmfield(VFa,'dat'); end + [Vmsk,Yb] = cat_vol_imcalc([VFa,spm_vol(Pb)],Pbt,'i2',struct('interp',3,'verb',0,'mask',-1)); + ds('d2sm','',1,Ym,Ym.*(Yb>0.5),round(size(Yb,3)*0.6)) + obj.image.dat = obj.image.dat .* (cat_vbdist(single(Yb>0.5))<10); + end + res = cat_spm_preproc8(obj); + if any(~isnan(res.ll)) + break + else + stime = cat_io_cmd(sprintf('SPM preprocessing 1 (estimate %d):',... + 2 + sampi),'caution','',job.extopts.verb-1,stime); + end + end + end + if ~exist('res','var') + cat_io_printf('SPM preprocessing with default settings failed. Run backup settings. \n'); + end + warning on; + + if job.opts.redspmres + res.image1 = image1; + clear reduce; + end + + catch + %% + cat_io_addwarning([mfilename ':ignoreErrors'],'Run backup function (IN DEVELOPMENT).',1,[1 1]); + + if isfield(obj.image,'dat') + tmp = obj.image.dat; + else + tmp = spm_read_vols(obj.image); + dt2 = obj.image.dt(1); + dts = cat_io_strrep(spm_type(dt2),{'float32','float64'},{'single','double'}); + obj.image.dat = eval(sprintf('%s(tmp);',dts)); + obj.image.pinfo = repmat([1;0],1,size(tmp,3)); + end + if exist('Ybi','var') + obj.image.dat = obj.image.dat .* (cat_vbdist(single(Ybi>0.5))<10); + else + VFa = VF; VFa.mat = Affine * VF.mat; %Fa.mat = res0(2).Affine * VF.mat; + if isfield(VFa,'dat'), VFa = rmfield(VFa,'dat'); end + [Vmsk,Yb] = cat_vol_imcalc([VFa,spm_vol(Pb)],Pbt,'i2',struct('interp',3,'verb',0,'mask',-1)); + ds('d2sm','',1,Ym,Ym.*(Yb>0.5),round(size(Yb,3)*0.6)) + obj.image.dat = obj.image.dat .* (cat_vbdist(single(Yb>0.5))<10); + end + + suc = 0; + % try higher accuracy + while obj.tol>10e-9 && suc == 0 + obj.tol = obj.tol / 10; + try + res = cat_spm_preproc8(obj); + suc = 1; + end + end + if suc == 0 + % try lower accuracy + while obj.tol<1 && suc == 0 + obj.tol = obj.tol * 10; + try + res = cat_spm_preproc8(obj); + suc = 1; + end + end + end + + if any( (vx_vol ~= vx_voli) ) || ~strcmp(job.extopts.species,'human') + [pp,ff,ee] = spm_fileparts(job.channel(1).vols{subj}); + delete(fullfile(pp,[ff,ee])); + end + + if suc==0 + %% + mati = spm_imatrix(V.mat); + + error('cat_run_job:spm_preproc8',sprintf([ + 'Error in spm_preproc8. Check image and orientation. \n'... + ' Volume size (x,y,z): %8.0f %8.0f %8.0f \n' ... + ' Origin (x,y,z): %8.1f %8.1f %8.1f \n' ... + ' Rotation (deg): %8.1f %8.1f %8.1f \n' ... + ' Resolution: %8.1f %8.1f %8.1f \n'],... + V.dim,[mati(1:3),mati(4:6),mati(7:9),])); + end + + %% set internal image + if ~exist('dt2','var') + %tmp = obj.image.dat; + dt2 = obj.image.dt(1); + dts = cat_io_strrep(spm_type(dt2),{'float32','float64'},{'single','double'}); + end + obj.image.dat = eval(sprintf('%s(tmp);',dts)); + obj.image.pinfo = repmat([1;0],1,size(tmp,3)); + obj.image.dt(1) = dt2; + res.image.dat = eval(sprintf('%s(tmp);',dts)); + res.image.pinfo = repmat([1;0],1,size(tmp,3)); + res.image.dt(1) = dt2; + end + if ppe.affreg.skullstripped || job.extopts.gcutstr<0 + % here we have to add manually our no variance background value of 0 + res.mg(end+1) = 1; + res.mn(end+1) = ppe.affreg.skullstrippedBGth; + res.vr(end+1) = max(eps,numel(res.wp) * eps); + res.wp = res.wp - numel(res.wp) * eps; + res.wp(end+1) = numel(res.wp) * eps; + res.lkp(end+1) = 4; + end + warning on + + if job.extopts.expertgui>1 + %% print the tissue peaks + mnstr = sprintf('\n SPM-US: ll=%0.6f, Tissue-peaks: ',res.ll); + for lkpi = 1:numel(res.lkp) + if lkpi==1 || ( res.lkp(lkpi) ~= res.lkp(lkpi-1) ) + mnstr = sprintf('%s (%d) ',mnstr,res.lkp(lkpi)); + end + if lkpi>1 &&( res.lkp(lkpi) == res.lkp(lkpi-1) ), mnstr = sprintf('%s, ',mnstr); end + if sum(res.lkp == res.lkp(lkpi))>1 && res.mg(lkpi)==max( res.mg( res.lkp == res.lkp(lkpi) )), mnstr = sprintf('%s*',mnstr); end + mnstr = sprintf('%s%0.2f',mnstr,res.mn( lkpi )); + end + cat_io_cprintf('blue',sprintf('%s\n',mnstr)); + cat_io_cmd(' ',' '); + end + fprintf('%5.0fs\n',etime(clock,stime)); + + %% check contrast (and convergence) + % RD202006: SPM peak averaging + % To get one single tissue value the following definition is correct + % in principle but outliers can have strong effect on mean estimation: + % clsint = @(x) round( sum(res.mn(res.lkp==x) .* res.mg(res.lkp==x)') * 10^5)/10^5; + % So we have to be careful by using these values. + if ~isempty(res) + clsint = @(x) round( sum(res.mn(res.lkp==x) .* res.mg(res.lkp==x)') * 10^5)/10^5; + Tgw = [cat_stat_nanmean(res.mn(res.lkp==1)) cat_stat_nanmean(res.mn(res.lkp==2))]; + Tth = [ + ... min(res.mn(res.lkp==6 & res.mg'>0.3)) ... % bg; ignore the background, because of MP2RGAGE, R1, and MT weighted images + max( min( clsint(3) , max(Tgw) + 1.5*abs(diff(Tgw))) , min(Tgw) - 1.5*abs(diff(Tgw)) ) ... % csf with limit for T2! + clsint(1) ... gm + clsint(2) ... wm + clsint(4) ... skull + clsint(5) ... head tissue + clsint(6) ... background + ]; + + res.Tth = Tth; + cat_err_res.res = res; + + % RD202006: Throw warning/error? + % Due to inaccuracies of the clsint function it is better to print + % this as intense warning. + if any( Tth(2:3)<0 ) || job.test_warnings + cat_io_addwarning([mfilename ':negVal'],sprintf( ... + ['CAT12 was developed for images with positive values and \\\\n', ... + 'negative values can lead to preprocessing problems. The average \\\\n', ... + 'intensities of CSF/GM/WM are %0.4f/%0.4f/%0.4f. \\\\n', ... + 'If you observe problems, you can use the %s to scale your data.'], Tth(1:3), ... + spm_file('Datatype-batch','link','spm_jobman(''interactive'','''',''spm.tools.cat.tools.spmtype'');')),2,[0 1],Tth); + end + end + + end + + %% updated tpm information for skull-stripped data should be available for cat_main + if isfield(obj.tpm,'bg1') && exist('ppe','var') && ( ppe.affreg.skullstripped || job.extopts.gcutstr<0 ) + fname = res.tpm(1).fname; + res.tpm = obj.tpm; + res.tpm(1).fname = fname; + end + spm_progress_bar('Clear'); + cat_progress_bar('Clear'); + + % call main processing + res.tpm = obj.tpm.V; + res.stime = stime0; + res.catlog = catlog; + res.Affine0 = res.Affine; + res.image0 = spm_vol(job.channel(1).vols0{subj}); + if exist('ppe','var'), res.ppe = ppe; end + + if isfield(job.extopts,'affmod') && any(job.extopts.affmod) + res.AffineUnmod = AffineUnmod; + res.AffineMod = AffineMod; + end + if exist('Ybge','var') + % If the background was estimated we want to save it to improve the + % SPM segmentation in regions outside the TPM volume. + res.bge = Ybge; + end + + if exist('Ylesion','var'), res.Ylesion = Ylesion; else, res.Ylesion = false(size(res.image.dim)); end; clear Ylesion; + if exist('redspmres','var'); res.redspmres = redspmres; res.image1 = image1; end + job.subj = subj; + cat_main(res,obj.tpm,job); + + % delete denoised/interpolated image + [pp,ff,ee] = spm_fileparts(job.channel(1).vols{subj}); + if exist(fullfile(pp,[ff,ee]),'file') + delete(fullfile(pp,[ff,ee])); + end + %% + + if usediary + diary off; + end +return + +%======================================================================= +function [Ym,Yt,Ybg,WMth] = APPmini(obj,VF,histth) +%% very simple affine preprocessing (APP) +% ------------------------------------------------------------------------ +% Creates an intensity normalized image Ym by the average higher tissue +% intensity WMth estimated in the mask Yt. Moreover, it estimates the +% background region Ybg. +% +% [Ym,Yt,Ybg,WMth] = APPmini(obj,VF) +% ------------------------------------------------------------------------ +% Robert Dahnke 2019/01 + + Ysrc = single(obj.image.private.dat(:,:,:)); + + % remove outlier and use SPM for intensity normalization to uint8 + % empirical division by 200 to get WM values around 1.0 + Ysrc = cat_stat_histth(Ysrc,histth,struct('scale',[0 1])); + VF0 = cat_spm_smoothto8bit(VF,0.1); + Ym = single(VF0.dat)/200; clear VG0 + + % find the larges object and estimate the averag intensity + % keep in mind that this will may inlcude the head (and in MP2RAGE/MT/R1 + % images also the background), i.e. highest intensity is may head, + % blood vessels or WM or CSF in T1/PD + Yt = cat_vol_morph(Ym>cat_stat_nanmean(Ym(Ym(:)>0.1)),'l',[100 1000])>0.5; + WMth = cat_stat_kmeans( Ysrc(Yt(:)) , 1); + + % rescale Ym and roughly estimate the background (not in MP2Rage/MT/R1) + Ym = Ysrc ./ WMth; + Ybg = cat_vol_morph(Ym<0.2,'l',[20 0.05])>0; + +return + +function APP_RMSE = checkAPP(Ym,Ysrc,histth) +%% check Ym +% ------------------------------------------------------------------------ +% Function to compare the normalized gradient maps of two input images +% that should be nearly identical. +% +% APP_RMSE = checkAPP(Ym,Ysrc) +% ------------------------------------------------------------------------ +% Robert Dahnke 2019/01 + + % remove strongest outlier + Ym = cat_stat_histth(Ym ,histth); + Ysrc = cat_stat_histth(Ysrc,histth); + + % avoid division by zeros + Ym = Ym + min(Ym(:)); + Ysrc = Ysrc + min(Ysrc(:)); + + % normalized gradient maps + Ygm = cat_vol_grad(Ym) ./ (Ym + eps); + Ygs = cat_vol_grad(Ysrc) ./ (Ysrc + eps); + + % use only the central region and values in the expected tissue range + sYm = round(size(Ym) / 5); + Ymsk = false(size(Ym) ); Ymsk(sYm(1):end-sYm(1),sYm(2):end-sYm(2),sYm(3):end-sYm(3)) = true; + Ymsk = Ymsk & cat_vol_morph(Ygm<2 & Ygs<2 & Ym>0.5 & Ysrc>0.5,'e'); + + % general error between both images within the mask + APP_RMSE = cat_stat_nanmean( ( Ygm(Ymsk(:)) - Ygs(Ymsk(:)) ).^2 )^0.5; + +return","MATLAB" +"Neurology","ChristianGaser/cat12","cat_vol_sample.m",".m","2215","52","function YA = cat_vol_sample(PT,PA,Yy,hold) +% Return voxel values from an image volume by using a non-linear +% deformation +% +% FORMAT YA = spm_sample_vol(VT,VA,Yy,hold) +% +% VT .. template space of the registration +% VA .. template space with different BB +% hold .. interpolation method for the resampling: +% 0 : Zero-order hold (nearest neighbour) +% 1 : First-order hold (trilinear interpolation) +% 2->127 : Higher order Lagrange (polynomial) interpolation +% using different holds (second-order upwards) +% -127 - -1 : Different orders of sinc interpolation +% +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +% RD202401: The definition could be improved to resample images with +% stronger variing properties correctly, e.g. the T1 template +% before the surface reconstruction in the cat_main[1639] +% pipelines. + + if ~exist('hold','var'), hold = 1; end + + if isstruct(PT), VT = PT; elseif ~isempty(PT), VT = spm_vol(PT); else, VT = []; end + if isstruct(PA), VA = PA; elseif ~isempty(PA), VA = spm_vol(PA); else, VA = []; end + + if ~isempty(VT) && ~isempty(VA) && any(VT.mat(:) ~= VA.mat(:)) + vx_volT = sqrt(sum(VT.mat(1:3,1:3).^2)); + vx_volA = sqrt(sum(VA.mat(1:3,1:3).^2)); + + % resample data in atlas resolution for the first time or if the atlas resolution changes + % adapt y for the atlas resolution (for loop) and for the new position (matit) + mati = VT.mat(13:15) - VA.mat(13:15); + vdim = spm_imatrix( VA.mat ); + matit = mati(1:3) ./ vdim(7:9); + + for i=1:3, Yy(:,:,:,i) = Yy(:,:,:,i) .* vx_volT(i) ./ vx_volA(i); end + Yy = cat(4,Yy(:,:,:,1) + matit(1), Yy(:,:,:,2) + matit(2), Yy(:,:,:,3) + matit(3) ); + end + + YA = single(spm_sample_vol(VA,double(Yy(:,:,:,1)),double(Yy(:,:,:,2)),double(Yy(:,:,:,3)),hold)); + YA = reshape(YA,size(Yy(:,:,:,1))); + +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_vol_partvol1639.m",".m","50288","984","function [Ya1,Ycls,YMF,Ycortex] = cat_vol_partvol1639(Ym,Ycls,Yb,Yy,vx_vol,extopts,Vtpm,noise,job,Ylesionmsk,Ydt,Ydti) +% ______________________________________________________________________ +% Use a segment map Ycls, the global intensity normalized T1 map Ym and +% the atlas label map YA to create a individual label map Ya1. +% The atlas contain main regions like cerebrum, brainstem, midbrain, +% cerebellum, ventricle, and regions with blood vessels. +% +% This function try to solve the following problems: +% 1) Finding of the cerebrum, the cerebellum, the head, blood vessels, +% brain skin and other mayor structures based on atlas (YA) and +% tissue class information (Yp0). +% To do this it is important to use data from the T1-map (Ym) that +% use the same intensity scaling as the segment map Yp0, but have +% more information about partial volume regions. +% 2) Set Partions: +% 2.1) Find biggest WM part of each region. +% 2.2) Align the nearest region class for other voxel +% 2.3) Finding and Filling of the ventricle and the Basalganglia +% 2.4) Find blood vessels +% 2.5) Brain extraction +% 2.6) Side alignment +% ______________________________________________________________________ +% +% Structure: +% +% [vol,Ya1,Yb,YMF] = cat_vol_partvol(YA,Yp0,Ym,Yl0,opt) +% +% INPUT: YA = 3D-volume with brain regions (altas map) +% Yp0 = 3D-volume with tissue propability map (CSF=1,GM=2;WM=3) +% Ym = intensity normalized T1 image (BG=0,CSF=1/3,GM=2/3,WM=1) +% Yl0 = spm-classes 4-6 (intracranial=1,skull=2,background=3) +% opt +% .res = resolution for mapping +% .vx_vol = voxelsize +% .LAB = label of Ya1 map (see LAB definition below) +% +% +% OUTPUT: vol = structure with volumes +% Ya1 = individual label map +% Yb = brain mask +% YMF = filling mask for ventricle and subcortical structures +% +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +% ______________________________________________________________________ +% +% Development comments: +% ToDo: +% - WMHs werden bei geringer Aufl?sung ?berschaetzt +% - mehr Kommentare bei WMHC und SLC +% +% Was ist neu im Vergleich zu anderen? +% - Zuweisung durch Dartel mit hoher Genauigkeit moeglich +% - Erweiterung von SPM/VBM durch MainROIs (Seiten, Lappen, ...) +% - Verbesserung der SPM/VBM durch bessere Enfernung von unerwuenschtem +% Gewebe (ON, Blutgefaesse ...) +% - Blutgefaesse koennnen als erweitere Masken fuer fMRI genutzt werden +% um Seiteneffekte besser ausblenden zu koennen. +% [- Beliebige Atlanten koennen genutzt werden.] +% +% Todo: +% - Besserer Atlas +% - BV vs. HD - glaetten in dilated HD region +% - Fuellen von CSF Luecken bei LAB~=BV und Ym<1.2 und LAB==NV? +% +% ______________________________________________________________________ + + + +% ---------------------------------------------------------------------- +% fast partitioning for B3C[, and LAS] +% ---------------------------------------------------------------------- +% VBM atlas atlas map to find important structures for the LAS and the +% skull-stripping, which are the subcortical GM regions and the cerebellum. +% Maybe also WM hyperintensity have to be labeled here as a region without +% local correction - actual clear WMHs are handeled as GM. +% ---------------------------------------------------------------------- + + % definition of ROIs + +% LAB.CT = 1; % cortex +% LAB.MB = 13; % MidBrain +% LAB.BS = 13; % BrainStem +% LAB.CB = 3; % Cerebellum +% LAB.ON = 11; % Optical Nerv +% LAB.BG = 5; % BasalGanglia +% LAB.TH = 9; % Hypothalamus +% LAB.HC = 19; % Hippocampus +% LAB.VT = 15; % Ventricle +% LAB.NV = 17; % no Ventricle +% LAB.BV = 7; % Blood Vessels +% LAB.NB = 0; % no brain +% LAB.HD = 21; % head +% LAB.HI = 23; % WM hyperintensities +% LAB.PH = 25; % Gyrus parahippocampalis + + % if there is a breakpoint in this file set debug=1 and do not clear temporary variables + dbs = dbstatus; debug = 0; for dbsi=1:numel(dbs), if strcmp(dbs(dbsi).name,mfilename); debug = 1; break; end; end + + def.uhrlim = 0.7; + extopts = cat_io_checkinopt(extopts,def); + + LAB = extopts.LAB; + BVCstr = mod(extopts.BVCstr,1) + (extopts.BVCstr==1 || extopts.BVCstr==2); + verb = extopts.verb-1; + PA = extopts.cat12atlas; + vx_res = max( extopts.uhrlim , max( [ max(vx_vol) min(vx_vol) ] )); + noise = double(noise); + + Yp0toC = @(Yp0,c) 1-min(1,abs(Yp0-c)); + + %% map atlas to RAW space + if verb, fprintf('\n'); end + stime = cat_io_cmd(' Atlas -> subject space','g5','',verb); + % CAT atlas + YA = cat_vol_ctype( cat_vol_sample(Vtpm(1),PA{1},Yy,0) ); + + + % template map + Yp0A = single( cat_vol_sample(Vtpm(1),Vtpm(1),Yy,1) )*2 + ... + single( cat_vol_sample(Vtpm(1),Vtpm(2),Yy,1) )*3 + ... + single( cat_vol_sample(Vtpm(1),Vtpm(3),Yy,1) )*1; + + + % WMH atlas + watlas = 3; + switch watlas + case 1, PwmhA = strrep(PA{1},'cat.nii','cat_wmh_soft.nii'); + case 2, PwmhA = strrep(PA{1},'cat.nii','cat_wmh.nii'); + case 3 + if isfield(job.extopts,'SLtpm') + PwmhA = job.extopts.WMHtpm{1}; + else + PwmhA = strrep(PA{1},'cat.nii','cat_wmh_miccai2017.nii'); + end + end + if ~isempty(PwmhA) && exist(PwmhA,'file') && ~strcmp(PwmhA,PA{1}) + YwmhA = cat_vol_ctype( cat_vol_sample(Vtpm(1),PwmhA,Yy,0) ); + else + YwmhA = max(0,min(1,Yp0A-2)); + end + switch watlas + case 2, YwmhA = min(1,max(0,YwmhA - 0.1) * 0.8); + case 3, YwmhA = min(1,max(0,cat_vol_smooth3X(YwmhA,1) - 0.01) * 10); + end + + + % Stroke lesion atlas + if isfield(job.extopts,'SLtpm') + PslA = job.extopts.SLtpm{1}; + else + PslA = strrep(PA{1},'cat.nii','cat_strokelesions_ATLAS303.nii'); + end + if ~isempty(PslA) && exist(PslA,'file') && ~strcmp(PslA,PA{1}) + YslA = cat_vol_ctype( cat_vol_sample(Vtpm(1),PslA,Yy,0) ); + YslA = YslA./max(YslA(:)); + else + YslA = max(0,min(1,Yp0A-2)); + end + + + % Blood vessel probability map (added 202305): + % Uses a blood vessel map created using MRA scans of the IXI and ICBM + % databases in combination with CSF and WM probability maps as far as + % larger blood vessels are typically located along the brainstem, corpus + % callosum and within the insula. + if isfield(job.extopts,'BVtpm') + Pbv = job.extopts.BVtpm{1}; + else + Pbv = strrep(PA{1},'cat.nii','cat_bloodvessels.nii'); + end + YwmA = single(cat_vol_sample(Vtpm(1),Vtpm(2),Yy,1)); + YcsfA = single(cat_vol_sample(Vtpm(1),Vtpm(3),Yy,1)); + if ~isempty(Pbv) && exist(Pbv,'file') + Vbv = spm_vol(Pbv); + YbvA = single(cat_vol_sample(Vbv,Vbv,Yy,1)); + YbvA = 1 - YwmA + max(YcsfA * 0.1 , YbvA); + else + YbvA = 1 - YwmA + YcsfA * 0.1; + end + clear YwmA YcsfA; + clear Yy; + + + % use addition FLAIR images + if exist('job','var') && isfield(job,'data_wmh') && ~isempty(job.data_wmh) && isfield(job,'subj') && numel(job.data_wmh)>=job.subj + %% + [pp,ff,ee] = spm_fileparts(job.data_wmh{job.subj}); + Pflair = fullfile(pp,[ff ee]); + if ~isempty(Pflair) && exist(Pflair,'file') + stime = cat_io_cmd(' FLAIR corregistration','g5','',verb,stime); + + % coreg + Vflair = spm_vol(job.data_wmh{job.subj}); + Vm = spm_vol(job.data{job.subj}); + evalc('R = spm_coreg(Vm,Vflair,struct(''graphics'',0));'); + R = spm_matrix(R); %#ok + + % load + Vflair.dat = cat_vol_sanlm(struct('verb',0),Vflair,1,spm_read_vols(Vflair)); + Vflair.pinfo = repmat([1;0],1,size(Vflair.dat,3)); + Vflair.dt(1) = 16; + Yflair = zeros(Vm.dim,'single'); + for i=1:Vm.dim(3) + Yflair(:,:,i) = single( spm_slice_vol(Vflair, R \ Vflair.mat \ Vm.mat * spm_matrix([0 0 i]) ,Vm.dim(1:2),[1,NaN])); + end + end + end + + + %% resize data + if ~debug; clear Yy; end + + + Yp0 = (single(Ycls{1})*2/255 + single(Ycls{2})*3/255 + single(Ycls{3})/255) .* Yb; + if isfield(job.extopts,'inv_weighting') && job.extopts.inv_weighting + Ym = Yp0/3; + end + + % work on average resolution + Ym0 = Ym; + % remove background + [Ym,BB] = cat_vol_resize(Ym ,'reduceBrain',vx_vol,2,Yb); + YA = cat_vol_resize(YA ,'reduceBrain',vx_vol,2,Yb); + Yp0 = cat_vol_resize(Yp0 ,'reduceBrain',vx_vol,2,Yb); + if exist('Ydt','var') + Ydt = cat_vol_resize(Ydt ,'reduceBrain',vx_vol,2,Yb); + end + if exist('Ydti','var') + Ydti = cat_vol_resize(Ydti ,'reduceBrain',vx_vol,2,Yb); + end + Yp0A = cat_vol_resize(Yp0A ,'reduceBrain',vx_vol,2,Yb); + YslA = cat_vol_resize(YslA ,'reduceBrain',vx_vol,2,Yb); + YbvA = cat_vol_resize(YbvA ,'reduceBrain',vx_vol,2,Yb); + YwmhA = cat_vol_resize(YwmhA ,'reduceBrain',vx_vol,2,Yb); + if exist('Yflair','var') + Yflair = cat_vol_resize(Yflair ,'reduceBrain',vx_vol,2,Yb); + end + if exist('Ylesionmsk','var') + Ylesionmsk = cat_vol_resize(Ylesionmsk ,'reduceBrain',vx_vol,2,Yb); + end + Yb = cat_vol_resize(Yb ,'reduceBrain',vx_vol,2,Yb); + % use lower resolution + [Ym,resTr] = cat_vol_resize(Ym ,'reduceV',vx_vol,vx_res,64); + YA = cat_vol_resize(YA ,'reduceV',vx_vol,vx_res,64,'nearest'); + Yp0 = cat_vol_resize(Yp0 ,'reduceV',vx_vol,vx_res,64); + if exist('Ydt','var') + Ydt = cat_vol_resize(Ydt ,'reduceV',vx_vol,vx_res,64); + end + if exist('Ydti','var') + Ydti = cat_vol_resize(Ydti ,'reduceV',vx_vol,vx_res,64); + end + Yp0A = cat_vol_resize(Yp0A ,'reduceV',vx_vol,vx_res,64); + YslA = single(cat_vol_resize(YslA ,'reduceV',vx_vol,vx_res,64)); + YbvA = cat_vol_resize(YbvA ,'reduceV',vx_vol,vx_res,64); + YwmhA = cat_vol_resize(YwmhA ,'reduceV',vx_vol,vx_res,64); + if exist('Yflair','var') + Yflair = cat_vol_resize(Yflair,'reduceV',vx_vol,vx_res,64); + end + if exist('Ylesionmsk','var') + Ylesionmsk = cat_vol_resize(Ylesionmsk,'reduceV',vx_vol,vx_res,64); + end + Yb = cat_vol_resize(Yb ,'reduceV',vx_vol,vx_res,64); + vx_vol = resTr.vx_volr; + + + % noise reduction + spm_smooth(Ym,Ym,0.6./vx_vol); + + + % prepare maps + YA = cat_vol_ctype(cat_vol_median3c(single(YA),Yp0>0)); % noise filter of atlas map + [~,~,YS] = cat_vbdist(single(mod(YA,2)) + single(YA>0)); YS=~mod(YS,2); % side map + YA(mod(YA,2)==0 & YA>0)=YA(mod(YA,2)==0 & YA>0)-1; % ROI map without side + YS = cat_vol_smooth3X(YS,4) > 0.5; % RD202501: side smoothing + Yg = cat_vol_grad(Ym,vx_vol); % gadient map (edge map) + Ydiv = cat_vol_div(Ym,vx_vol); % divergence map (edge map) + Ym = Ym*3 .* (Yb); + Yb = Yb>0.5; + + + + %% Create individual mapping: + stime = cat_io_cmd(' Major structures','g5','',verb,stime); + + % Mapping of major structure: + % Major structure mapping with downcut to have a better alginment for + % the CB and CT. Simple setting of BG and TH as GM structures. + Ya1 = zeros(size(Ym),'single'); + Ybg = zeros(size(Ym),'single'); + Ybgd = cat_vbdist(single(YA==LAB.BG),Yb,vx_vol); + Yosd = cat_vbdist(single(YA==LAB.TH | YA==LAB.VT | YA==LAB.HC | ... + YA==LAB.BS | (YA==LAB.CT & Ym>2.9)),Yb,vx_vol); + Ybg(smooth3(Yosd>3 & Ybgd<5 & Ym>1.9 & Ym<2.85 & Yg<4*noise & ... + ((Ybgd<1 & Ydiv>-0.01) | (Ydiv>-0.01+Ybgd/100)))>0.7) = 1; + Ybg(smooth3((Ybg==0 & Yp0>2.8 & Ym>2.8 & YA==LAB.CT) | Ym>2.9 | ... + YA==LAB.TH | YA==LAB.HC | Yosd<2 | (Ybg==0 & Yp0<1.25) | ... + (Ybg==0 & Ybgd>8) | (Ybg==0 & Ydiv<-0.01+Ybgd/200))>0.3) = 2; + Ybg(Ybg==0 & Ybgd>0 & Ybgd<10) = 1.5; + Ybg = cat_vol_laplace3R(Ybg,Ybg==1.5,0.005)<1.5 & Ym<2.9 & Ym>1.8 & Ydiv>-0.02; + Ya1(Ybg & Ym>1.5 & Yp0>1.5) = LAB.BG; % basal ganglia + Ya1(YA==LAB.TH & Ym>1.9 & Ym<2.85 & Ydiv>-0.1) = LAB.TH; % thalamus + % RD202501: hippocampus definition was not optimal here as we need a clear parahippocampus for surface reconstruction + Ya1( cat_vol_morph(YA==LAB.HC,'dd',3) & Ym>1.5 & Ym<2.5 & ~(cat_vol_morph(YA==LAB.PH,'dd',2) | ... + YA==LAB.TH | cat_vol_morph(YA==LAB.NV,'dd',5,vx_vol))) = LAB.HC; % hippocampus + Ya1(Yp0>1.9 & Ym>1.7 & YA==LAB.HC) = LAB.HC; % hippocampus + NBVC = BVCstr > 0 && BVCstr <= 1; % RD202306: new BV correction by default + %% + if NBVC + % define some high intensity BVs and the neocortex + % RD202501: extened the BV detection + Ybv = ( (smooth3(Yp0)-Yp0 )>.7 | (Ym-Ydiv)>3.4 | max(0,Ym - Yp0)>Ydiv+.8 & Ym>2 & Ydiv<0) & YA==LAB.CT & smooth3(Ya1>0)<.5; + Ybv = single( cat_vol_morph( Ybv , 'l', [inf 1])>0 ); % remove single voxels + Ybv( Ybv==0 & Yp0<=2 & YA==LAB.CT) = nan; Ybv(YA~=LAB.CT ) = nan; + Ybv( cat_vol_morph( cat_vol_morph( Yp0>2.1 & Ym<3.2 & (YA==LAB.CT | Ybgd<7),'o'),'lc') ) = 2; % add neocortex region + Ybv( cat_vol_morph( YA==LAB.HC | YA==LAB.VT | YA==LAB.PH | YA==LAB.TH,'dd', 4) ) = 2; % add ""neocortex"" region + Ybv = cat_vol_downcut(Ybv,Ym - Ydiv,noise); + Ybv(Yp0>2.1 & Ym>2.3 & Ybv<2 & YA==LAB.CT) = 1; + Ybv = single( cat_vol_morph( Ybv==1 , 'l', [inf 2])>0 ); % remove single voxels + Ya1( cat_vol_morph( Ybv==1,'dc') ) = LAB.BV; clear Ybv + Ya1( cat_vol_morph( ((Yp0>2.5 & Ym>2.5 & Ym<3 -(YbvA.^4*BVCstr - 1) & (YA==LAB.CT | YA==LAB.BG)) | ... + (Yp0>1.5 & Ym<3.01 & Yp0A>2.5 & Ybgd>1 & Ybgd<8 & (Ybgd>4 | ... + Ydiv<-0.02+Ybgd/200))) & Ya1==0 , 'l',[.1 10 ])) = LAB.CT; % cerebrum + Yhbv = max(0,8*-Ydiv).^4 .* (2*Yg).^4 .* Ym .* 2.*smooth3(Yp0<2.9) .* (YbvA - 1).^2 .* (YA~=LAB.CB); % .* cat_vol_morph(Ya1==0,'e'); + Ya1(Ya1==0 & Yhbv>.2*(1-BVCstr)) = LAB.BV; + else + % older version + Ya1(((Yp0>2.5 & Ym>2.5 & (YA==LAB.CT | YA==LAB.BG )) | ... + (Yp0>1.5 & Ym<3.5 & Ybgd>1 & Ybgd<8 & (Ybgd>4 | ... + Ydiv<-0.02+Ybgd/200))) & Ya1==0)=LAB.CT; % cerebrum + end + % use region-growing in case of the cerebellum to compensate for fine structure + Ycb = single(YA==LAB.CB) + 2*single(cat_vol_morph( YA==LAB.CT,'de',6)); + Ycb(Yp0<1 & Ym<2) = nan; Ycb(cat_vol_morph( YA~=LAB.CB ,'de',12)) = nan; + [Ycb,Yd] = cat_vol_downcut(Ycb,Ym,noise); + Ycb = single(YA==LAB.CB) | cat_vol_smooth3X(Ycb==1 & Yd<50,2)>.7; + % cortext growing without BVs + Yct = single( (Ya1==LAB.CT | (Ybgd>2 & Ybgd<7)) & (Ym - Ydiv)<3.1 ) + 2*single(cat_vol_morph( YA==LAB.CB,'de',6)); + Yct(Yp0<1 & Ym<1.7) = nan; Yct(cat_vol_morph( YA~=LAB.CT,'de',12)) = nan; + [Yct,Yd] = cat_vol_downcut(Yct,Ym - Ydiv,noise/4); + Yct = (Yct==1 & smooth3(Yd)<20); + + + % set other regions + Ya1(Yp0>1.9 & Ym>1.7 & Ym<3.1 & Ycb)=LAB.CB; % cerebellum + Ya1(Yp0>1.9 & Ym>1.7 & YA==LAB.BS)=LAB.BS; % brainstem + Ya1(Yp0>1.9 & Ym>1.7 & YA==LAB.ON)=LAB.ON; % optical nerv + Ya1(Yp0>1.9 & Ym>1.7 & Yp0<3 & YA==LAB.TH)=LAB.TH; % thalamus + Ya1(Yp0>1.9 & Ym>1.7 & cat_vol_smooth3X(YA==LAB.MB,2)>.1)=LAB.MB; % midbrain + Ya1(Yp0>1.9 & Ym>1.7 & YA==LAB.PH & Ya1==0)=LAB.CT; % added PH as cortex + Ya1(Yp0>1.9 & Ym>1.7 & Ym<3.0 & Yct & Ya1==0)=LAB.CT; % added CT + Ya1(Yp0>1.9 & Ym>1.7 & cat_vol_morph(YA==LAB.VT | YA==LAB.HC | YA==LAB.PH ,'dd',2) & Ya1==0)=LAB.CT; % added CT + % denoising for regions but not BV + Ya1 = cat_vol_median3c(Ya1,Ya1>0 & ~YA==LAB.BV); + %Ya1(Ybv>1 & ~cat_vol_morph(Ya1>1,'l',[inf 2]))=0; + %% + if NBVC + % create a cerebellar mask to avoid corrections there + Ycb3 = cat_vol_morph(YA==LAB.CB,'d',1) | (cat_vol_morph(YA==LAB.CB,'d',3) & YbvA<0.5 & Ym<2.5); + Ysc5 = cat_vol_morph(YA==LAB.HC | YA==LAB.BG | YA==LAB.TH,'dd',3); + Yhc3 = smooth3(cat_vol_morph(YA==LAB.HC | YA==LAB.PH | YA==LAB.VT | Ysc5,'d'))>.5; + Ya1(Ysc5 & Ym>2.6 & Ym<2.95 & Ya1==0) = LAB.CT; + + % extend the neocortical area + Ya1(Ya1<1 & Ym<1.8) = nan; + [Ya1,Yd] = cat_vol_downcut(Ya1,Ym,noise); Ya1(isinf(Ya1) | Yd>15 ) = 0; + + % get blood vessels as intensity-based eikonal-distance map with + % different grow rates, where the first one is more limited by the + % local intensities and the second one allows to remove the general + % distance aspect + Ya0 = single(Ya1>0 & Ya1~=LAB.BV); Ya0(Ym<1.7) = nan; + [~,Yd] = cat_vol_downcut(Ya0,Ym,noise ); clear Ya0 + Ya0 = single(Ya1>0 & Ya1~=LAB.BV); Ya0(Ym<1.7) = nan; + [~,Yd2] = cat_vol_downcut(Ya0,Ym,noise * 16); clear Ya0 + Ya1( ((Yd - Yd2)>10./YbvA) & Ym>2.4 & YA==LAB.CT & ~Ycb3 & ~Yhc3 & YbvA>.7) = LAB.BV; % add highly distant voxels + Ya1(Ya1==0 & Ym>2.4 & Yd>70 & Yd2>50 & ~cat_vol_morph(YA>1 & YA~=LAB.HD,'d') & ~Ycb3 & ~Yhc3) = LAB.BV; % mask further BV + Ya1(Ya1==0 & Ym>2.2 & Yd<20 & ~cat_vol_morph(YA>1 & YA~=LAB.HD,'d') & ~Ycb3) = LAB.CT; % add also save brain voxels + Ya1(Ya1==LAB.BV & cat_vol_morph(Ya1==LAB.BV,'l',[inf 16])==0) = 0; + clear Ycb3 Yhc3 + + %% modified old lines + Ya1((Ya1==0 & Yp0<1.5 & Ym<1.5 & Yp0>1.3 & Ym>1.3) & YA==LAB.BV) = LAB.BV; % low-int BV (updated due to cerebellar errors RD20190929) + Ya1((cat_vol_morph(Ya1==0 & YA~=LAB.CB,'e') & (Ym>2.5 | Ym<1.7) & YA==LAB.CT & ... + Ym>2 - (YbvA-1).^4*BVCstr) & (YA==LAB.BV | YbvA>1))=LAB.BV; % high-int BV (updated due to cerebellar errors RD20190929) + + %% some light region growing + Ya1(Ya1<1 & Ym<2.2) = nan; + [Ya1,Yd] = cat_vol_downcut(Ya1,Ym,2*noise); Ya1(isinf(Ya1) | (Yd>15 & Ya1==LAB.BV) ) = 0; + Ya1(Ya1<1 & Ym<1.9) = nan; + [Ya1,Yd] = cat_vol_downcut(Ya1,Ym,2); Ya1(isinf(Ya1) | (Yd>15 & Ya1==LAB.BV) ) = 0; + Ya1(Ya1<1 & Ym<1.7) = nan; + [Ya1,Yd] = cat_vol_downcut(Ya1,Ym,2); Ya1(isinf(Ya1) | (Yd>15 & Ya1==LAB.BV ) ) = 0; + + %% cleanup? + Ymsk = single(smooth3(Ym)>2.2 | Ya1==LAB.BV) .* ((Ya1==LAB.CT) + 2*(Ya1==LAB.BV)); + Ymsk = cat_vol_localstat(Ymsk,Ymsk>0,1,1,8); + %Ya1a = Ya1; Ya1a(Ymsk>0 & Ymsk<1.5) = LAB.CT; Ya1a(Ymsk>=1.5) = LAB.BV; + Ya1(Ymsk>0 & Ymsk<1.5) = LAB.CT; Ya1(Ymsk>=1.5) = LAB.BV; clear Ymsk + + else + Ya1((Ya1==0 & Yp0<1.5 & Ym<1.5 & Yp0>1.3 & Ym>1.3) & YA==LAB.BV)=LAB.BV; % low-int VB (updated due to cerebellar erros RD20190929) + Ya1((Ya1==0 & Yp0>3.0 & Ym>3.2) & YA==LAB.BV)=LAB.BV; % high-int VB (updated due to cerebellar erros RD20190929) + Ya1(Ya1==0 & Ym<1.9)=nan; + Ya1 = cat_vol_downcut(Ya1,Ym,4*noise); Ya1(isinf(Ya1))=0; + end + Ya1(YA==LAB.TH & Ym>1.75 & Ym<2.85 & Ydiv>-0.1 & Yg<.2 & ~cat_vol_morph(Ya1==LAB.MB | Ya1==LAB.VT | Ya1==LAB.HC | Ya1==LAB.PH,'dd',4,vx_vol))=LAB.TH; % thalamus + Ya1 = cat_vol_median3c(Ya1,Ya1>0 & ~YA==LAB.BV); % smoothing + clear Ybg Ybgd; + Ya1((Yp0>1.75 & Ym>1.75 & Yp0<2.5 & Ym<2.5) & Ya1==LAB.MB) = 0; % midbrain correction + Ya1(Ya1==LAB.CT & ~cat_vol_morph(Ya1==LAB.CT,'do',1.4)) = 0; + if 0 + %% display for development + [YD,YI] = cat_vbdist(single(Ya1)); Yax = Ya1(YI); + figure, isosurface(smooth3(Ya1 & Ym>2.1),.5,Yax), axis equal off; colormap cool, clim([1,8]) + %% + figure, isosurface(smooth3((Yd<50 | Ym<2.1) .* (Ym>2.1)),.5,Yax), axis equal off; colormap cool, clim([1,8]) + + end + + % correction of structures that should be compact + Ya1(Ya1==LAB.BS & ~cat_vol_morph(cat_vol_morph(Ya1==LAB.BS,'o'),'c')) = 0; + Ya1(Ya1==LAB.MB & ~cat_vol_morph(cat_vol_morph(Ya1==LAB.MB,'o'),'c')) = 0; + Ya1(Ya1==LAB.PH) = 0; + Ya1 = cat_vol_median3c(Ya1,Ya1>0 & ~YA==LAB.BV); + + + %% Mapping of ventricles: + % Ventricle estimation with a previous definition of non ventricle CSF + % to have a second ROI in the region-growin. Using only the ventricle + % ROI can lead to overgrowing. Using of non ventrilce ROI doesn't work + % because dartle failed for large ventricle. + % It is important to use labopen for each side! + stime = cat_io_cmd(' Ventricle detection','g5','',verb,stime); + %% RD202501: added parahypocampus here to avoid overgrowing ventricles and filling issues and defects + Yph = Ym>2 & cat_vol_smooth3X(YA==LAB.PH | YA==LAB.HC,2)>.1; + Ynv = cat_vol_morph(~Yb,'d',4,vx_vol) | cat_vol_morph(YA==LAB.CB,'dd',10,vx_vol) | ...% RD202501: extend CB + cat_vol_morph(YA==LAB.BS,'dd',2,vx_vol) | ... + (cat_vol_morph(smooth3(YA==LAB.NV | YA==LAB.TH)>.8,'dd',2,vx_vol) & Ym<1.8) | ... + cat_vol_morph(YA==LAB.TH & Ym<2.5,'e',1,vx_vol); + Ynv = Ynv | Yph | (~cat_vol_morph((Yp0>0 & Yp0<1.5 & (YA==LAB.VT)),'dd',20,vx_vol) & Yp0<1.5); + Ynv = single(Ynv & Ym<2 & ~cat_vol_morph(Yp0<2 & (YA==LAB.VT) & Yg<0.2,'d',4,vx_vol) & ~Yph); + Ynv = single(Ynv | (cat_vol_morph(smooth3(YA==LAB.NV | YA==LAB.TH)>.8,'dd',1,vx_vol) & Ym<1.8)); + Ynv = Ynv & (~cat_vol_morph(Ya1==LAB.HC | Ya1==LAB.PH,'d',8) | Ya1==LAB.NV); + Ynv = smooth3(round(Ynv))>0.5; + % between thamlamus + Ynv = Ynv | (cat_vol_morph(Ya1==LAB.TH,'c',10) & Yp0<2) | YA==LAB.CB | YA==LAB.BS; + Ynv = smooth3(Ynv)>0.8; + Yvt = single(smooth3(Yp0<1.5 & (YA==LAB.VT) & Yg<0.25 & ~Ynv)>0.7); + Yvt(cat_vol_morph( (YA==LAB.HC | YA==LAB.PH) & ~(Ya1==LAB.HC | Ya1==LAB.PH) & Yg-.1 & Ym<1.2 & Yp0<1.2,'do',3)) = 1; + Yvt(Yvt==0 & ~(smooth3(Ya1==LAB.HC)>.1 & Ym>1.1) & cat_vol_morph( smooth3(Ya1==LAB.HC)>.7 | Yvt,'dc',7,vx_vol) & Ym<1.25 & Yg<0.3)=1; + Yvt(cat_vol_morph(Yvt,'l',[inf,10])==0 & Yvt>0) = 0; + Yvt(Yvt==0 & Ynv)=2; Yvt(Yvt==0 & Ym>1.8)=nan; Yvt(Yvt==0)=1.5; + Yvt(Yvt==0 & Ydiv<-0.1) = nan; Yvt(~Yb) = nan; + + %% subcortical stroke lesions + if exist('Ylesionmsk','var'), Yvt(Ylesionmsk>0.5) = nan; end + Yvt( cat_vol_morph(YslA>0.6 & Ym<2 & Ydiv./(Ym+eps)>0 & Yp0A>2.5 , 'do', 1 ) ) = 2; % WM + Yvt( cat_vol_morph(YslA>0.2 & Ym<2 & Ydiv./(Ym+eps)>0 & YA==LAB.BG , 'do', 1 ) ) = 2; % BG lesions + if exist('Ydt','var') && exist('Ydti','var') + % by deformation + Ystsl = (( cat_vol_smooth3X( 1-single(cat_vol_morph(YA==LAB.VT,'dd',10,vx_vol)) ,4 ) .* ... + cat_vol_smooth3X( single((Ydt - Ydti)>0.7),4) )>0.1 & Ym>0.5 & Ym<2.5 ); +%% + Ystsl = Ystsl | ... + ((cat_vol_smooth3X(1-single(cat_vol_morph(YA==LAB.VT,'dd',5,vx_vol)),4) .* ... + cat_vol_smooth3X(single((Ydt - Ydti)>0.7),4))>0.05 & Ym>1.5 & Ym<2.8 & ... + ~cat_vol_morph(YA==LAB.BG | YA==LAB.TH,'d',2)); + Ystsl = Ystsl | ... + (cat_vol_smooth3X(single((1/(Ydt+eps) - 1/(Ydti+eps))>0.7),4)>0.4 & Ym>1.5); + Ystsl =cat_vol_morph(Ystsl,'dc',4,vx_vol); + Yvt( cat_vol_morph(Ystsl,'e',2)) = 2; + else + Ystsl = false(size(Ynv)); + end + + %% bottleneck + Yvt2 = cat_vol_laplace3R(Yvt,Yvt==1.5,0.01); % first growing for large regions + Yvt(cat_vol_morph(Yvt2<1.4,'o',2) & ~isnan(Yvt) & Yp0<1.5) = 1; + Yvt(cat_vol_morph(Yvt2>1.6,'o',2) & ~isnan(Yvt) & Yp0<1.5) = 2; + Ygx = Ym/3 ./ cat_vol_localstat(Ym/3,Ym>1.125,1,3,1); Yvt(Yvt==1.5 & Ygx<.5)=nan; + Ygx = Ym/3 ./ cat_vol_localstat(Ym/3,Ym>1.25,1,3,1); Yvt(Yvt==1.5 & Ygx<.8)=nan; + Yvt2 = cat_vol_laplace3R(Yvt,Yvt==1.5,0.001); + % remove small objects + warning('off','MATLAB:cat_vol_morph:NoObject'); + Yvt = cat_vol_morph(Yvt2<1.5, 'l', [10 0.1]); + Yvt = cat_vol_morph(Yvt , 'l', [10 50]); + warning('on','MATLAB:cat_vol_morph:NoObject'); + Yvt = smooth3((Yvt | (YA==LAB.VT & Ym<1.7)) & Yp0<1.5 & Ym<1.5)>0.5; + %% + Ya1(Yvt) = LAB.VT; Yvtp = cat_vol_morph( Yvt ,'dd', 2) ; + Ya1( Ya1 == 0 & YA==LAB.HC & Yvtp & Yp0>1.9 & Ym<3.1 & Ym>1.9 ) = LAB.HC; + Ya1( Ya1 == 0 & YA==LAB.PH & Yvtp & Yp0>1.9 & Ym<3.1 & Ym>1.9 ) = LAB.PH; + Ya1( Ya1 == 0 & YA==LAB.CT & Yvtp & Yp0>1.9 & Ym<3.1 & Ym>1.9 ) = LAB.CT; + if ~debug, clear Yvts1; end + + + + %% Mapping of blood vessels + % For this we may require the best resolution! + % first a hard regions growing have to find the real WM-WM/GM region + if BVCstr + stime = cat_io_cmd(' Blood vessel detection','g5','',verb,stime); + Ywm = Yp0>2.25 & Ym>2.25 & Yp0<3.1 & Ym<4; % init WM + Ywm = Ywm | (cat_vol_morph(Ywm,'dd') & Ym<3.5); + %% + Ywm = single(cat_vol_morph(Ywm,'lc',2,vx_vol)); % closing WM + Ywm(smooth3(single(Ywm))<0.5)=0; % remove small dots + Ywm(~Ywm & (Yp0<0.5 | Ym<1.2 | Ym>4))=nan; % set regions growing are + [Ywm1,YDr] = cat_vol_downcut(Ywm,Ym,2*noise*(1-BVCstr/2)); % region growing + Ywm(Ywm==-inf | YDr>20)=0; Ywm(Ywm1>0)=1; clear Ywm1 % set regions growing + % smoothing + Ywms = smooth3(single(Ywm)); Yms=smooth3(Ym); + Ywm(Ywms<0.5)=0; Ywm(Ywms>0.5 & Yb & (Ym-Yms)<0.5)=1; + Ywm(Ywms<0.5 & Yb & (Ym-Yms)>0.5)=0; clear Ywms + %% set blood vessels + Ybv=cat_vol_morph( (Ym>3.75-(0.5*BVCstr) & Yp0<2+(0.5*BVCstr)) | ... % high intensity, but not classified as WM (SPM) + (Yms>2.5 & (Ym-Yms)>0.6) | ... % regions that strongly change by smoothing + (Ym>2.5-(0.5*BVCstr) & Ywm==0) | ... % high intensity, but not classified as WM (SPM) + 0 ...(Ym>2.5-(0.5*BVCstr) & Yp0<2+(0.5*BVCstr) & Ya1==0 & YA==LAB.CT),'c',1,vx_vol) & ... RD 201901 ADNI 128S0216 error + ,'c',1,vx_vol) & ... + cat_vol_morph(Ya1==LAB.CT,'d',2,vx_vol) & ~cat_vol_morph(Ya1==LAB.HC,'d',2,vx_vol) & ... + cat_vol_morph((Ya1==0 | Ya1==LAB.CB | Ya1==LAB.CT | Ya1==LAB.BV | Ym>1.5) & Ya1~=LAB.VT & Yp0<2.5,'e',1,vx_vol) & ... avoid subcortical regions + ~Ywm; if ~debug, clear Ywm; end + Ybb = cat_vol_morph(Yp0>0.5,'lc',1,vx_vol); + + %% RD 201901 ADNI 128S0216 error + % Ycenter = cat_vol_smooth3X(YS==0,2)<0.95 & cat_vol_smooth3X(YS==1,2)<0.95 & Yp0>0; + Yb2 = Ybv; %smooth3( Ydiv<0.1 & Ym>1.5 & (Ym-Yp0)>0.5 & (Ycenter | cat_vol_morph(~Yb,'dd',3)) & Ya1==0 )>0.5; + + %% + Ybv = ((Ybv | Yb2) & Ybb) | smooth3(Yp0<0.5 & Ybb)>0.4; clear Ybb; + %% smoothing + Ybvs = smooth3(Ybv); + Ybv(Ybvs>0.3 & Ym>2.5 & Yp0<2.5)=1; Ybv(Ybvs>0.3 & Ym>3.5 & Yp0<2.9)=1; + Ybv(Ybvs<0.2 & Ym<4-2*BVCstr)=0; clear Yvbs; + Ya1(Ybv)=LAB.BV; clear Ybv + end + + + + %% WMH (White Matter Hyperintensities): + % WMHs can be found as GM next to the ventricle (A) that do not belong + % to a subcortical structure (A) or there must be a big difference + % between the tissue SPM expect and the real intensity 'Yp0 - Ym' (C). + % Furthermore no other Sulic (=near other CSF) should be labeld (D). + % #################################################################### + % There can also be deep GM Hyperintensities! + % #################################################################### + % ds('l2','',vx_vol,Ym,Ywmh,Ym/3,Ym/3,90) + % #################################################################### + % ToDo: Separate detection of ventricular lesion and subventriculars + % #################################################################### + if extopts.WMHC>=0 && extopts.WMHCstr>=0 && ~extopts.inv_weighting + % T1 bias correction + Yi = Ym .* (Yp0>2.5 & Ym>2.5 & cat_vol_morph(Ya1~=LAB.BG | Ya1~=LAB.VT | Ya1~=LAB.TH,'d',2)); + Yi = cat_vol_median3(Yi,Yi>0,Yi>0); Yi = cat_vol_localstat(Yi,Yi>0,1,3); + for i=1:2, Yi = cat_vol_localstat(Yi,Yi>0,1,1); end + Yi = cat_vol_approx(Yi,'nh',vx_vol,3); + Ymi = Ym ./ Yi * 3; + + + % estimate relative CSF volume + Yp0e = Yp0.*cat_vol_morph(Yb,'e',2); + vols = mean([sum(round(Yp0e(:))==1) sum(round(Yp0e(:))==1 & Yvt(:))] / ... + sum(round(Yp0e(:))>0.5)); clear Yp0e; + noisew = cat_vol_localstat(smooth3(Ymi)*2,cat_vol_morph(Yp0>2.5,'e') & Ya1==LAB.CT & ~(YwmhA>0.5 & Ymi<2.7),3,4); + noisew = cat_stat_nanmean(noisew(noisew(:)>0)); + noisec = cat_vol_localstat(smooth3(Ymi)*2,cat_vol_morph((cat_vol_morph(Yp0>0.5,'e') & .... + cat_vol_morph(Yp0<2.5,'e')) | cat_vol_morph(Ya1==LAB.VT,'e'),'o'),3,4); + noisec = cat_stat_nanmean(noisec(noisec(:)>0)); + if sum(noisec(:)>0)>100, noisew = min(noisew,cat_stat_nanmean(noisec(noisec(:)>0))); end + + % control variables + % only if there is a lot of CSF and not too much noise + extopts.WMHCstr = min( 1, max( 0, extopts.WMHCstr ./ max(1,mean(vx_vol)) )); % adaptiv for resolution + csfvol = max(eps,min(1.0, (vols - 0.05) * 10 )); % relative CSF volume weighting + WMHCstr = max(eps,min(1.0, extopts.WMHCstr .* csfvol )); % normalized WMHCstr + wmhvols = 40 - 30 * (1 - extopts.WMHCstr); % absolute WMH volume threshold + mth = [ min( 1.2 , 1.1 + noisew * (2 - extopts.WMHCstr) ) , ... % lower tissue threshold + max( 2.5 , 2.9 - noisew * (2 - extopts.WMHCstr) ) ]; % upper tissue threshold + %ath = 2.85 - 0.1 * WMHCstr; % tissue probability threshold + + stime = cat_io_cmd(sprintf(' WMH detection (WMHCstr=%0.02f > WMHCstr''=%0.02f)',... + extopts.WMHCstr,WMHCstr),'g5','',verb,stime); + + + %% creation of helping masks with *YwmhL* and *Ycortex* as most important mask! + % Ybgth: subcortical GM regions with WMHs with intensities + % between CSF and GM + % Ycenter: area between the hemispheres that we ignore to avoid + % clossing of the small sulci (eg. close to the CC) + % Ycortex1: initial map to classify cortical GM + % Ycortex2: laplace filtered map to classify cortical GM + % Ycortex: final cortex map that also include CSF and parts of the + % normal subcortical structures + % YwmhL: extrem large WMs (important to use age-based threshold!) + % Yinsula: insula and claustrum + Ybgth = cat_vol_morph( YA==LAB.BG | Ya1==LAB.BS | Ya1==LAB.TH | YA==LAB.PH | YA==LAB.CB ,... + 'dd',1.5 + max(0,2-WMHCstr*4),vx_vol); + Ybgth = cat_vol_morph( Ybgth | Ya1==LAB.VT ,'dc',10,vx_vol); + Ycenter = cat_vol_smooth3X(YS==0,8)<0.95 & cat_vol_smooth3X(YS==1,8)<0.95 & Yp0>0; + + Ycortex1 = single(1.5 + 0.5*(Yvt2>1.5 & Yvt2<3 & Yp0<=2 & Ym<2.1) - 0.5*Yvt); Ycortex1(Ym>2.1) = nan; + %% + YwmhL = cat_vol_morph( smooth3((Yp0A + YwmhA)>1.9 & Ym>1.7 & Ym<2.2 & ~Ybgth & ~Ycenter & ... + cat_vol_morph( YwmhA>0 ,'dd',8) & YA==LAB.CT & ... % use Ywmh atlas + ~cat_vol_morph(Yvt2>1.6 & Yvt2<3 & Ym<1.8 ,'dd',3,vx_vol))>0.5,'do',4-3*WMHCstr,vx_vol); % age adaptation + %% + Ycortex1(cat_vol_morph(YwmhL,'dd',3) & Ycortex1==2) = 0; Ycortex1(YwmhL) = 1; + Ycortex2 = cat_vol_laplace3R(Ycortex1,Ycortex1==1.5,0.005); + Ycortex1( smooth3(Ycortex1==1.5 & Ycortex2>1.5 & Yp0<=2 & Ym<2.1)>0.6) = 2; + Ycortex1(isnan(Ycortex1) & Ym>2.8) = 1; + Ycortex2 = cat_vol_laplace3R(Ycortex1,Ycortex1==1.5,0.002); + Ycortex = cat_vol_morph( (Ycortex2>1.5 & Ycortex2<3) | Ya1==LAB.HC,'dd',2) & Yp0<2.8; + if ~debug, clear Ycortex1 Ycortex2; end + Yinsula = cat_vol_morph( Ycortex,'dd',2,vx_vol) & Yp0<2.8 & ... + cat_vol_morph( Ya1==LAB.BG | Ya1==LAB.BG,'dd',12,vx_vol); + Ycortex = Ycortex | Yinsula; + if ~debug, clear Yinsula; end + + + %% create initial WMH map + % (A1) classical WMHs + (A2) subcortical (GM) WMHs + (A3) large WMHs + % (B1) cortical GM + (B2) deep ventriclal CSF (to avoid the mapping + % of CSF-WM-PVE close to the ventricle) + % (C1 & C2) WM regions as boundary for the bottleneck region growing + Ywmh = single( smooth3( ... + cat_vol_morph(~cat_vol_morph(Ycortex,'dd',2 - WMHCstr) & ~Ycenter & (Yp0A+YwmhA)>2.1 & ... + Ym<2.8 & Ym>1.2 & ~Ybgth & ~cat_vol_morph(Yvt,'d'),'l',[inf,15 - 10*WMHCstr]) > 0 ) > 0.4 ); % (A1) + Ywmh( smooth3(Ym<1.9 & Ybgth & Yp0A>2)>0.5 & ~cat_vol_morph(Yvt,'o',3) & ... + ~Ycenter & ~Yvt & ~Ya1==LAB.TH & ... + ~cat_vol_morph( Ya1==LAB.HC | YA==LAB.PH ,'dc',10,vx_vol)) = 1; % (A2) + Ywmh( cat_vol_morph(Ywmh | Yvt,'dc',4,vx_vol) & Ym>1 & Ym<2.8 & Yp0<2.8 & ~Ycenter & ~Yvt ) = 1; + Ywmh( YwmhL ) = 1; if ~debug, clear YwmhL; end % (A3) + Ywmh( smooth3( Ycortex)>0.8 & ~Yvt ) = 2; % (B1) + Ywmh( cat_vol_morph( Yvt, 'de', 2) ) = 2; % (B2) + Ywmh( Ywmh==0 & Ymi>2.8 ) = nan; % (C1) + Ywmh( Ywmh==0 & Ym>1.9 & cat_vol_morph( Ya1==LAB.BG | Ya1==LAB.TH | ... + Ya1==LAB.HC | YA==LAB.PH ,'dc',10,vx_vol) ) = nan; % (C2) + + + %% remove small dots + Ywmh(Ywmh==2 & smooth3(Ywmh==2)<0.1 + WMHCstr/2 + noisew) = 0; + Ywmh(Ywmh==1 & smooth3(Ywmh==1)<0.1 + WMHCstr/2 + noisew) = 0; + + + % Ywmhp: tiny WMHs that were found by closing the WM + if noisew<0.07 + % tiny WMHs as regions with low T1 intensity that can be described + % by closing of WM-like regions + Ywmhp = (Ymi2.2 & Yp0>2.2,'de')) | ... + (cat_vol_morph(Ymi>mth(2) | cat_vol_morph(Ya1==LAB.VT,'dd',1,vx_vol),'lc',1) & Ymi2.3 | cat_vol_morph(Ya1==LAB.VT,'dd',1,vx_vol),'lc',1) & ... + Ymi2.9,'dd',1.4) & ~Ycortex); + Ywmhp = Ywmhp & (YwmhA>0 | Yp0A>2.6) & ~Ybgth & Ymi>mth(1) & Ymi2.9,'e') & Ym<2.9 & ~Ycortex & ~Ybgth & Ya1~=LAB.BS & Ya1~=LAB.CB) = 1; + % no WMHs + Ywmhp(cat_vol_morph(Ya1==LAB.VT,'dd',1,vx_vol)) = 0; % not close to the ventricle (PVE range) + Ywmhp(smooth3(Ywmhp)<0.2 + noisew) = 0; % avoid WMHs caused by noise + Ywmhp = cat_vol_morph(Ywmhp,'l',[inf 4 * max(1,min(4,noisew*20))])>0; % remove small WMHs + Ywmh(smooth3(Ywmhp)>0.5 & Ymi0.5 )), ... + cat_stat_nanmean( Yflair( Yp0toC(Yp0,2)>0.5 )), ... + cat_stat_nanmean( Yflair( Yp0toC(Yp0,3)>0.5 ))]; + Tstd = cat_stat_nanstd( Yflair(Yflair(:)>T3thf(1) & Yflair(:) cat_stat_nanmean(T3thf(3)) - Tstd*2 & ... + Yflair < cat_stat_nanmean(T3thf(3)) + Tstd*2 & ... + (Yflair/T3thf(3)./(Ymi/3))<2 & Yp0>2.5; + Yi = Yi | (Yp0>2.8 & Ymi>2.8); + Yg = Yflair > cat_stat_nanmean(T3thf(2)) - Tstd*3 & Yp0>1.5 & Yp0<2.5 & ~Yi; + Yi = cat_vol_localstat(Yflair .* Yi,Yi>0,1,2) + ... + cat_vol_localstat(Yflair .* Yg,Yg>0,2,3)*T3thf(3)/T3thf(2); + Yi = cat_vol_median3(Yi,Yi>0,Yi>0); + for i=1:2, Yi = cat_vol_localstat(Yi,Yi>0,1,1); end + Yi = cat_vol_approx(Yi,'nn',vx_vol,8); + + %% + Yflairn = Yflair./(Yi+eps); + T3thf = [cat_stat_nanmean( Yflairn( Yp0toC(Yp0,1)>0.8 )), ... + cat_stat_nanmean( Yflairn( Yp0toC(Yp0,2)>0.9 & Yflairn>1.1 )), ... + cat_stat_nanmean( Yflairn( Yp0toC(Yp0,3)>0.9 & Yflairn<1.1 & Ym>2.8 ))]; + [T3thfs,T3this] = sort([0, T3thf, max(T3thf) + 1*abs(diff(T3thf(2:3)))]); T3this = [0 1/3 2/3 2/3 2]; + Yflairn2 = zeros(size(Yflairn),'single'); + for i=numel(T3thfs):-1:2 + M = Yflairn>T3thfs(i-1) & Yflairn<=T3thfs(i); + Yflairn2(M(:)) = T3this(i-1) + (Yflairn(M(:)) - T3thfs(i-1))/diff(T3thfs(i-1:i))*diff(T3this(i-1:i)); + end + M = Yflairn>=T3thfs(end); + Yflairn2(M(:)) = max(T3this) + (Yflairn(M(:)) - T3thfs(end))/diff(T3thfs(end-1:end))*diff(T3this(i-1:i)); + Yflairn2 = cat_vol_median3(Yflairn2,Yp0>0,Yp0>0,0.1); + + %% create FLAIR mask + Yflairl = Yflairn2>0.8 & ~Ycenter & ... % flair intensiy + cat_vol_morph(cat_vol_morph(Yp0>1 | Yvt,'dc',1.5),'do',1.5); % brain tissue or ventricular area! + % & ... Yflair./Yi > (T3thf(2)/T3thf(3) + Tstd/T3thf(3)*1.5 - (Tstd/T3thf(3)*extopts.WMHCstr)) & ... % flair intensiy + %Yp0>1.1 & Ymi<2.9 & Yp0A>1.1 & ~Ycenter & ... & YwmhA>eps % T1 intensities & altas limits + % (Yflair./Yi + Ymi/3)>max(2.1,3*(1-YwmhA)); % & ... % another flair intensity limit + %cat_vol_morph(Ya1~=LAB.TH & Ya1~=LAB.BG & Ya1~=LAB.HC,'d',1); % avoid some regions +%% + %Yflairl = Yflairl | (Yflair./Yi + Ymi/3)>max(2.3,3*(1-YwmhA)) & Ymi<2.9; % add some regions + Yflairl = cat_vol_morph(Yflairl,'l',[inf (4 - extopts.WMHCstr)^3])>0; + Yflairr = smooth3(Yflairl) .* min( 1, 2 * max(0, Yflair./(Yi+eps) - ... + ( (T3thf(2)/T3thf(3) + Tstd/T3thf(3)*1.5 - (Tstd/T3thf(3)*extopts.WMHCstr)) ) )); + if ~debug, clear Yi Yflair; end + + %% add FLAIR mask + Ywmh(Yflairl & (Ywmh<2 | isnan(Ywmh))) = 1; + else + Yflairl = false(size(Ymi)); + end + if ~debug, clear Ycenter; end + + % lesions as a regions : + % - that did not fit to the expected tissue? - not stong enough + % - with low self/mirror similarity? > Shooting+ + % cat_vol_morph( Ycortex & Yp01.1 & Yp0A>1.8 & ~cat_vol_morph(Yp0<1.2,'do',4) ,'do',1.8); % lesions without FLAIR + % cat_vol_morph( (Yflairn - (Ym-1)) .* (Ycortex & Yp01.1),'do',0.9); % lesion with FLAIR + + %% bottleneck region growing [Manjon:1995] + Ywmh(Ywmh==0) = 1.5; Ywmh(Ym>2.2 & Ywmh==1.5) = nan; % harder mask with low T1 threshold + Ywmh2 = cat_vol_laplace3R(Ywmh, Ywmh==1.5, 0.001); % bottleneck + Ywmh(Ywmh==1.5 & Ywmh2>1.7 & Ywmh<3) = 2; % add cortex + Ywmh(Ywmh==1.5 & (Ywmh2<1.2 | Ywmh2==1.5)) = 1; % add WMHs + Ywmh(isnan(Ywmh) & Ym<2.5 & Ym>1.5) = 1.5; % soft mask with higher T1 threshold + Ywmh2 = cat_vol_laplace3R(Ywmh, Ywmh==1.5, 0.001); % bottleneck + + % final mask and remove small WMHs + Ywmh = ~Yvt & Ymi>mth(1) & Ymi1.8); + if ~debug, clear Ywmh2; end + Ywmh = cat_vol_morph(Ywmh , 'l', [inf wmhvols/2])>0; + + % final mask and add tiny WMHs and FLAIR WMHs + Ywmh = ( ( Ywmh | Ywmhp | Yflairl ) & Ymi>mth(1) & Ym1.125 & Ym<2) ) ) )); + if exist('Yflairr','var'), Ywmhr = max( Yflairr .* Ywmh, Ywmhr ); clear Yflairr; end + if ~debug, clear Ywmhp Ybgth Yflairl Yt; end + + + %% apply to atlas + Ya1(Ywmh) = LAB.HI; + else + Ywmhr = false(size(Ym)); + Ycortex = false(size(Ym)); + end + if ~debug, clear Ywmh Ynwmh Yvt2; end + + + + %% stroke lesion detection + + % 1. Detection of manually masked regions (zeros within brainmask) + if exist('Ylesionmsk','var') + stime = cat_io_cmd(' Manual stroke lesion detection','g5','',verb,stime); + Ylesion = Ylesionmsk>0.5; % add manual lesions + end + + % 2. Automatic stroke lesion detection + % * use prior maps to identify reginos that should be tissue but + % are in stroke areas and have CSF intensity + % * use distance properies to differentiate between normal brain + % atrophy and stroke lesions as local CSF areas that differ stongly + % from the average values + if extopts.SLC + stime = cat_io_cmd(' Stroke lesion detection','g5','',verb,stime); + + %% large CSF regions without lesion prior + Ysd = cat_vbdist(single(cat_vol_morph(~Yb | Yp0>2 | cat_vol_morph(Ya1>0,'ldc',1),'do',3,vx_vol))); + mdYsd = max(3.0,median(Ysd(Ysd(:)>0))); + sdYsd = max(1.5,std(Ysd(Ysd(:)>0))); + Yclesion = smooth3(Ysd>(mdYsd + 3*sdYsd) & Yp0<1.5 & Yp0A>1.25 & Ydiv>-0.1 & (YslA>0 | Yp0A>1.25))>0.5; + % large CSF regions with lesion prior + Ysd2 = Ysd .* YslA .* Yp0A/3; + mdYsd2 = max(3.0,median(Ysd2(Ysd2(:)>0))); + sdYsd2 = max(1.5,std(Ysd2(Ysd2(:)>0))); + Yclesion( smooth3(Ysd>(mdYsd + 3*sdYsd) & Yp0<1.5 & Yp0A>1.25 & Ydiv>-0.1 & (YslA>0 | Yp0A>1.25))>0.5 ) = 1; + if ~debug, clear Ysd; end + Yclesion = cat_vol_morph(cat_vol_morph(Yclesion | ~(Yb & Yp0A>0),'dc',4,vx_vol) & Ym<2 & Yp0>0.5,'do',2); + Yclesion = cat_vol_morph(Yclesion,'l',[inf 400],vx_vol)>0; + + % further lesions + Ywlesion = smooth3(abs(Yp0-Ym)/3 .* (1-max(0,abs(3-Yp0A))) .* YslA * 10 )>0.3 & Ym<2.2 & Yp0>1 & Ya1~=LAB.HI; % WM-GM leson + Ywlesion( smooth3(Yp0A/3 .* YslA .* (3-Ym) .* (Ya1~=LAB.HI))>0.5 ) = 1; % WM lesions + % + Ywlesion( cat_vol_morph(YslA>0.6 & Yp0<2.0 & Ydiv./(Ym+eps)>0 & YslA>0.2 & Yp0A>2.5 , 'do', 1 ) ) = 1; % WM + Ywlesion( cat_vol_morph(YslA>0.2 & Yp0<1.6 & Ydiv./(Ym+eps)>0 & YslA>0.2 & (YA==LAB.BG | YA==LAB.TH) , 'do', 1 ) ) = 1; % BG lesions + % closing and opening + Ywlesion = cat_vol_morph(cat_vol_morph(Ywlesion | ~(Yb & Yp0A>0),'dc',4,vx_vol) & Ym<2 & Yp0>0.5,'do',1); + Ywlesion = cat_vol_morph(Ywlesion,'l',[inf 200],vx_vol)>0; + + %% + Ystsl = Ystsl & Ym<2.8 & Ya1~=LAB.VT; + Yilesion = single(Yclesion | Ywlesion | Ystsl); Yilesion(Yilesion==0 & ( Yp0<0.5 | Yp0>2.1 | Ydiv<-0.1 | Ya1==LAB.VT ) ) = -inf; + [Yilesion,Ydd] = cat_vol_downcut(Yilesion,3-Ym,-0.0001); Yilesion(Ydd>200) = 0; + Yilesion = cat_vol_morph(Yilesion,'dc',1,vx_vol); + Yilesion = cat_vol_morph(Yilesion,'do',4,vx_vol)>0 | Ywlesion| Yclesion; + Yilesion = cat_vol_morph(Yilesion,'l',[inf 200],vx_vol)>0; + Ynlesion = smooth3(~Yilesion & Ysd2<(mdYsd2 + 2*sdYsd2) & Ym<2.0 & Yp0A<1.9 & Ydiv>0)>0.5; + if ~debug, clear Ysd2; end + + % region-growing + Ysl = single(Yilesion) + 2*single(Ynlesion | Yp0<0.5 | Yvt | ~Yb); if ~debug, clear Yilesion Ynlesion; end + Ysl(Yp0>2.8)=nan; Ysl(Ysl==0) = 1.5; % harder mask with low T1 threshold + Ysl2 = cat_vol_laplace3R(Ysl, Ysl==1.5, 0.05); % bottleneck + Ysl(Ysl2<1.45 & ~isnan(Ysl))=1; Ysl(Ysl2>1.55 & ~isnan(Ysl))=2; + Ysl2 = cat_vol_laplace3R(Ysl, Ysl==1.5, 0.01); if ~debug, clear Ysl; end % bottleneck + Ylesion = cat_vol_morph(Ysl2<1.45 & Ysl2>0 & Ym<2.8 & Ya1~=LAB.HI,'do',1,vx_vol); if ~debug, clear Ysl2; end + %% + + %% + %Ylesion = single( Yp0A./(Ym+2)>1.3 & Yp0>0.5 & Yp0<2 & Ya1~=LAB.VT & Ya1~=LAB.HI & Ym<1.5 ); % , 'do', 3); + %Ylesion = single(cat_vol_morph(Ylesion,'l',[inf 50])>0); + %{ + Ylesion( cat_vol_morph(YslA>0.6 & Ym<2 & Ydiv./Ym>0 & Yp0A>2.5 , 'do', 1 ) ) = 2; % WM + Ylesion( cat_vol_morph(YslA>0.2 & Ym<2 & Ydiv./Ym>0 & YA==LAB.BG , 'do', 1 ) ) = 2; % BG lesions + Ylesion(smooth3(Yp0A>2.9 & Ym<2)>0.7) = 1; + + Ylesion(Ym>2 | (Ya1==LAB.VT & Yp0A<2.9) | Ya1==LAB.HI | Yp0==0) = nan; + [Ylesion,Ydx] = cat_vol_simgrow(Ylesion,max(1,Ym),1); Ylesion(Ydx>0.1)=0; + % different volume boundaries depending on the position of the lesion + Ylesion = cat_vol_morph(cat_vol_morph(Ylesion,'do',2) & Yp0A<2.5,'l',[inf 200])>0 | ... % maybe just atrophy + cat_vol_morph(cat_vol_morph(Ylesion,'do',1) & Yp0A>2.5,'l',[inf 100])>0 | ... + cat_vol_morph(Ylesion & Yp0A>2.9,'l',[inf 10])>0; + %} + % add manual leisons + if exist('Ylesionmsk','var'), Ylesion(Ylesionmsk>0.5) = 1; end + end + Ya1(Ylesion>0) = LAB.LE; + + + %% Closing of gaps between diffent structures: + stime = cat_io_cmd(' Closing of deep structures','g5','',verb,stime); + Yvtd2 = cat_vol_morph(Ya1==LAB.VT,'dd',2,vx_vol) & Ya1~=LAB.VT; + % CT and VT + Ycenter = cat_vol_morph(Ya1==LAB.VT,'dd',2,vx_vol) & ... + cat_vol_morph(Ya1==LAB.CT,'d',2,vx_vol) & Ya1==0 ; + Ya1(Ycenter & Yp0<=1.5 & ~Ynv)=LAB.VT; Ya1(Ycenter & Yp0>1.5)=LAB.CT; + % WMH and VT + Ycenter = cat_vol_morph(Ya1==LAB.HI,'dd',2,vx_vol) & Yvtd2 & ~Ynv & Ya1==0; + Ya1(Ycenter & Ym<=1.25)=LAB.VT; Ya1(Ycenter & Ym>1.25 & Ym<2.5)=LAB.HI; + % TH and VT + if 0 % RD202501 + Ycenter = cat_vol_morph(Ya1==LAB.TH,'dd',2,vx_vol) & Yvtd2; + Ya1(Ycenter & Ym<=1.5)=LAB.VT; Ya1(Ycenter & Ym>1.5 & Ym<2.85)=LAB.TH; + end + % BG and VT + Ycenter = cat_vol_morph(Ya1==LAB.BG,'dd',2,vx_vol) & Yvtd2; + Ya1(Ycenter & Ym<=1.5)=LAB.VT; Ya1(Ycenter & Ym>1.5 & Ym<2.85)=LAB.BG; + % no bloodvessels next to the ventricle, because for strong atrophy + % brains the WM structures can be very thin and may still include + % strong bias + Ya1(Ya1==LAB.BV & cat_vol_morph(Ya1==LAB.VT,'dd',3,vx_vol))=0; + if ~debug, clear Yt Yh Yvtd2 Yw; end + + + + %% complete map + Ya1(Ya1==0 & Yp0<1.75) = nan; + Ya1 = cat_vol_downcut(Ya1,Ym,noise); Ya1(isinf(Ya1)) = 0; + Ybv = Ya1==LAB.BV; Ya1(Ya1==LAB.BV) = 0; + [~,~,Ya1x] = cat_vbdist(Ya1,Yb); + Ya1(Ya1x==LAB.CB | Ya1x==LAB.BS | Ya1x==LAB.MB | Ya1x==LAB.CT) = Ya1x(Ya1x==LAB.CB | Ya1x==LAB.BS | Ya1x==LAB.MB | Ya1x==LAB.CT); + Ya1(Ya1x>0 & Ya1==0) = 1; + Ya1(Ybv) = LAB.BV; clear Ybv; + + % consider gyrus parahippocampalis | cat_vol_morph(Ya1==LAB.HC,'e') + % RD202501: add defintion of parahippocampal gyrus (with some extensive + % processing to really have a whole free thing but we will try to first keep it simple) + Yph = cat_vol_morph((YA==LAB.PH ),'dd',1.9) & cat_vol_morph(Ya1==LAB.VT | Ya1==LAB.HC,'dd',4,vx_vol) & Ym>2.125 & Ydiv<0.05; + Ya1(Yph>0) = LAB.PH; clear Yph; % parahippocampus + + %% side aligment using laplace to correct for missalignments due to the normalization + stime = cat_io_cmd(' Side alignment','g5','',verb,stime); + YBG = Ya1==LAB.BG | Ya1==LAB.TH; + YMF = Ya1==LAB.VT | Ya1==LAB.BG | Ya1==LAB.HI | Ya1==LAB.PH | (Ya1==LAB.TH & cat_vol_smooth3X(Ym>1.9)); % add the thalamus (RD20190913) + YMF(smooth3(YMF)<.5) = 0; + YMF = cat_vol_morph(cat_vol_morph(YMF,'dc',2),'do'); + YMF2 = cat_vol_morph(YMF,'dd',2,vx_vol) | Ya1==LAB.CB | Ya1==LAB.BS | Ya1==LAB.MB; + Ymf = max(Ym,smooth3(single(YMF2*3))); + Ycenter = cat_vol_smooth3X(YS==0,6)<0.9 & cat_vol_smooth3X(YS==1,6)<0.9 & ~YMF2 & Yp0>0 & Ym<3.1 & (Yp0<2.5 | Ya1==LAB.BV); + Ys = (2-single(YS)) .* single(smooth3(Ycenter)<0.4); + Ys(Ys==0 & (Ym<1 | Ym>3.1))=nan; Ys = cat_vol_downcut(Ys,Ymf,0.1,vx_vol); + [~,~,Ys] = cat_vbdist(Ys,Ys==0); + if ~debug, clear YMF2 Yt YS; end + + % YMF for FreeSurfer fsaverage + Ysm = cat_vol_morph(Ys==2,'d',1.5,vx_vol) & cat_vol_morph(Ys==1,'d',1.5,vx_vol); + Ynn = 0 * cat_vol_morph(Ysm & Ya1==LAB.MB,'dd',10); + YMF = Ya1==LAB.VT | (cat_vol_morph(Ya1==LAB.PH | Ya1==LAB.BG | Ya1==LAB.HI | (Ya1==LAB.TH & cat_vol_smooth3X(Ym)>1.9),'dc',2,vx_vol) & ~Ysm); % changed thalamus (RD20190913) + YMF = Ya1~=LAB.CB & ~Ynn & Ym<=2.75 & cat_vol_morph(YMF | Ym>2.3,'c',1) & cat_vol_morph(YMF,'dd',2,vx_vol); + YMF = smooth3(YMF)>0.5; + Ycenter = cat_vol_morph(Ya1==LAB.TH | Ya1==LAB.VT,'dc',4,vx_vol) & ~(Ya1==LAB.TH | Ya1==LAB.VT | cat_vol_morph(Ya1==LAB.HC | Ya1==LAB.PH,'dd',2,vx_vol)); + YMF(Ycenter)=1; + clear Ysm; + + + %% back to original size + stime = cat_io_cmd(' Final corrections','g5','',verb,stime); + Ya1 = cat_vol_resize(Ya1,'dereduceV',resTr,'nearest'); Ya1 = cat_vol_median3c(Ya1,Ya1>0 & Ya1~=LAB.BV); + Ys = cat_vol_resize(Ys ,'dereduceV',resTr,'nearest'); Ys = 1 + single(smooth3(Ys)>1.5); + YMF = cat_vol_resize(single(YMF),'dereduceV',resTr)>0.5; + YBG = cat_vol_resize(single(YBG),'dereduceV',resTr)>0.5; + Ywmhr = cat_vol_resize(Ywmhr,'dereduceV',resTr); + Ycortex = cat_vol_resize(single(Ycortex),'dereduceV',resTr)>0.5; + + Ya1 = cat_vol_resize(Ya1,'dereduceBrain',BB); Ya1 = cat_vol_ctype(Ya1); + Ys = cat_vol_resize(Ys ,'dereduceBrain',BB); [~,~,Ys] = cat_vbdist(Ys,Ya1>0); + YMF = cat_vol_resize(YMF,'dereduceBrain',BB); + YBG = cat_vol_resize(YBG,'dereduceBrain',BB); + Ywmhr = cat_vol_resize(Ywmhr,'dereduceBrain',BB); + Ycortex = cat_vol_resize(Ycortex,'dereduceBrain',BB); + Ym = Ym0; clear Ym0; + + % final side alignment + Ya1(Ya1>0)=Ya1(Ya1>0)+(Ys(Ya1>0)-1); + + + %% correction of tissue classes + + % add WMH class + Ywmhrd = cat_vol_morph(Ywmhr,'dd'); + Yclssum = (single(Ycls{1}) + single(Ycls{3})) .* (Ywmhrd); + Ycls{7} = cat_vol_ctype(Yclssum); + Ycls{1} = cat_vol_ctype(single(Ycls{1}) .* (~Ywmhrd)); + Ycls{3} = cat_vol_ctype(single(Ycls{3}) .* (~Ywmhrd)); + clear Ywmhrd + + % set possible blood vessels to class 4 + NS = @(Ys,s) Ys==s | Ys==s+1; + if ~NBVC + % this should be done later with consideration of the BV intensity and WM distance! + Ybv = NS(Ya1,LAB.BV); + Yclssum = (single(Ycls{1}) + single(Ycls{2})) .* (Ybv); + Ycls{5} = cat_vol_ctype(single(Ycls{5}) + Yclssum); + Ycls{1} = cat_vol_ctype(single(Ycls{1}) .* (~Ybv)); + Ycls{2} = cat_vol_ctype(single(Ycls{2}) .* (~Ybv)); + clear Ybv; + end + + + % YBG is smoothed a little bit and (B) reset all values that are related with GM/WM intensity (Ym<2.9/3) (A) + Yclssum = single(Ycls{1}) + single(Ycls{2}) + single(Ycls{3}); + YBGs = min( max(0,min(255, 255 - cat_vol_smooth3X(Ya1==1 & Ycls{2}>round(2.9/3),0.8) .* single(Ycls{2}) )), ... (A) + max(0,min(255, 255 * cat_vol_smooth3X(YBG .* (Ym<=2.9/3 & Ym>2/3) ,0.5) )) ); % (B) + Ycls{1} = cat_vol_ctype(single(Ycls{1}) + YBGs .* (single(Ycls{2})./max(eps,Yclssum))); + Ycls{2} = cat_vol_ctype(single(Ycls{2}) - YBGs .* (single(Ycls{2})./max(eps,Yclssum))); + clear YBGs Yclssum; + + % assure that the sum of all tissues is 255 + Yclss = zeros(size(Ym),'single'); + for ci=1:numel(Ycls), Yclss = Yclss + single(Ycls{ci}); end + for ci=1:numel(Ycls), Ycls{ci} = cat_vol_ctype(single(Ycls{ci}) ./ max(eps,Yclss) * 255); end + + + cat_io_cmd(' ','','',verb,stime); + +end","MATLAB" +"Neurology","ChristianGaser/cat12","genus0.c",".c","47149","1589","/* ______________________________________________________________________ + * + * Christian Gaser, Robert Dahnke + * Structural Brain Mapping Group (https://neuro-jena.github.io) + * Departments of Neurology and Psychiatry + * Jena University Hospital + * ______________________________________________________________________ + * $Id$ + */ + +#include ""genus0.h"" +#include +#include +#include + +static int verbose,invconnectivity, connectivity, autocrop[3][2]; +static int img_horiz,img_vert,img_depth,paddeddims[3]; +static int nbrs[6],offs[27],nbrs18[18],nbrs26[26],pass[27]; +static int elist18[27][19],elist[27][7],elist26[27][27]; +static int *status,*cm,cm_size,que_size,*que,que_len,que_pos; +static int maxlevels,comp_count=10,cut_loops; +static int calloced=0,max_calloced=32; +static int *persist=NULL; + +static void **calloc_list=NULL; +static unsigned char *zpic; +static float voxelsize[3],*fzpic,fzpicmax; + +static mwSize *g_axis_len, *g_stride; +static mwSize paddeddims0[3]; +static float *g_deltax, *g_tmp, *g_tmp_row, **g_j, *g_x, **g_recip, **g_square; + +static void print_msg(char * msg) + { + printf(""%s"",msg); + } + +static void *basic_calloc(mwSize nelem, mwSize elsize) + { + return(calloc(nelem,elsize)); + } + +static void basic_free(void *ptr) + { + if (ptr!=NULL) free(ptr); + } + + +static void Gfree(void *ptr) + { + int i,j; + /* free something in the calloc_list */ + for(i=0;i=0 && i1<=2 && j1>=0 && j1<=2 && k1>=0 && k1<=2) + { /* if in 3x3x3 cube */ + vv=i1+j1*3+k1*9; + if (vv!=13) elist[h][++count]=vv; + } + } + elist[h][0]=count; + h++; + } + + h=0; + for (k=0;k<3;k++) /* for each spot in 3x3x3 cube */ + for(j=0;j<3;j++) + for(i=0;i<3;i++) + if (!((i==0 || i==2)&&(j==0 || j==2)&&(k==0 || k==2))) + if ((i!=1)||(j!=1)||(k!=1)) + { + cases1826[h][0]=i-1; + cases1826[h][1]=j-1; + cases1826[h][2]=k-1; + h++; + } + h=0; + for (k=0;k<3;k++) /* for each spot in 3x3x3 cube */ + for(j=0;j<3;j++) + for(i=0;i<3;i++) + { + count=0; /* count of nbrs */ + for (thecase=0;thecase<18;thecase++) + { + i1=i+cases1826[thecase][0]; + j1=j+cases1826[thecase][1]; + k1=k+cases1826[thecase][2]; + if (i1>=0 && i1<=2 && j1>=0 && j1<=2 && k1>=0 && k1<=2) + { /* if in 3x3x3 cube */ + vv=i1+j1*3+k1*9; + if (vv!=13) elist18[h][++count]=vv; + } + } + elist18[h][0]=count; + h++; + } + + h=0; + for (k=0;k<3;k++) /* for each spot in 3x3x3 cube */ + for(j=0;j<3;j++) + for(i=0;i<3;i++) + if ((i!=1)||(j!=1)||(k!=1)) + { + cases1826[h][0]=i-1; + cases1826[h][1]=j-1; + cases1826[h][2]=k-1; + h++; + } + h=0; + for (k=0;k<3;k++) /* for each spot in 3x3x3 cube */ + for(j=0;j<3;j++) + for(i=0;i<3;i++) + { + count=0; /* count of nbrs */ + for (thecase=0;thecase<26;thecase++) + { + i1=i+cases1826[thecase][0]; + j1=j+cases1826[thecase][1]; + k1=k+cases1826[thecase][2]; + if (i1>=0 && i1<=2 && j1>=0 && j1<=2 && k1>=0 && k1<=2) + { /* if in 3x3x3 cube */ + vv=i1+j1*3+k1*9; + if (vv!=13) elist26[h][++count]=vv; + } + } + elist26[h][0]=count; + h++; + } + + } + + + +static void process_row(int axis,float *start) + { + register mwSize len; + register float *p, *p2, *p3, *p_end, pv, p2v, **jp, **j2p, **j_end, *x2p; + register float x, x0, x2, *recip, *square, dx; + + dx = g_deltax[axis]; + if (dx < 0.f) dx = -dx; + j_end = g_j; + p = start; + p_end = start + g_axis_len[axis]; + do { + if (*p != FLT_MAX) *j_end++ = p; + } while (++p != p_end); + if (j_end == g_j) return; + jp = j2p = g_j; + x2p = g_x; + *g_x = -FLT_MAX; + if (++jp != j_end) { + pv = *(p = *jp); + p2v = *(p2 = *j2p); + x2 = -FLT_MAX; + x0 = dx*(p - start); + square = g_square[axis]; + recip = g_recip[axis]; + while (1) { + len = p - p2; + x = x0 + (pv - p2v - square[len])*recip[len]; + if (x > x2) { + *++j2p = p; + *++x2p = x; + if (++jp == j_end) break; + p2 = p; + p2v = pv; + x2 = x; + pv = *(p = *jp); + x0 = dx*(p - start); + } else { + p2v = *(p2 = *--j2p); + x2 = *--x2p; + } + } + } + + len = g_axis_len[axis]; + p = p_end = g_tmp_row + len; + p3 = start + len; + while (len--) { + x = dx*len; + while (*x2p > x) { + j2p--; + x2p--; + } + p2 = *j2p; + x = dx*(--p3 - p2); + *--p = *p2 + x*x; + } + p2 = start; + while (p != p_end) *p2++ = *p++; + return; + } + +static void recursive_add_dist_squared(int axis,float *start) + { + mwSize len; + float *p, *p_end, *p2, *p2_end, *p3; + + if (axis == 0) { + process_row(0, start); + return; + } + + len = g_stride[axis]; + p = start; + p_end = p + len; + p2_end = g_tmp + g_axis_len[axis]; + while (p != p_end) { + p2 = g_tmp; + p3 = p; + while (p2 != p2_end) { + *p2++ = *p3; + p3 += len; + } + process_row(axis, g_tmp); + p2 = g_tmp; + p3 = p++; + while (p2 != p2_end) { + *p3 = *p2++; + p3 += len; + } + } + + p = start; + len = g_axis_len[axis]; + while (len--) { + recursive_add_dist_squared(axis-1, p); + p += g_stride[axis]; + } + return; + } + + + +static int dist_squared( + int rank, + mwSize *axis_len, + float *deltax, + register char *inimage, + register char inobject, + float *outdist_squared) + { + mwSize max_axis_len, data_len; + register mwSize len; + register float *p, *p2, ftmp, ftmp2; + int i; + + if(!(rank >= 0)) + {error_msg(""Error during distance transform.\n"",__LINE__);return(1);} + if (rank == 0) { + *outdist_squared = (*inimage == inobject)? 0.f : FLT_MAX; + return 0; + } + + g_stride = (mwSize *)Gcalloc(rank,sizeof(mwSize),0); + if (g_stride==NULL) {error_msg(""Memory error.\n"",__LINE__);return(1);} + + max_axis_len = 2; + data_len = 1; + for (i=0; i 1)) return(1); + if (!(deltax[i] != 0.f)) return(1); + if (max_axis_len < axis_len[i]) max_axis_len = axis_len[i]; + g_stride[i] = data_len; + data_len *= axis_len[i]; + } + + g_tmp = (float *)Gcalloc(max_axis_len,sizeof(float),0); + if (g_tmp==NULL) {error_msg(""Memory error.\n"",__LINE__);return(1);} + + g_tmp_row = (float *)Gcalloc(max_axis_len,sizeof(float),0); + if (g_tmp_row==NULL) {error_msg(""Memory error.\n"",__LINE__);return(1);} + + g_j = (float **)Gcalloc(max_axis_len,sizeof(float *),0); + if (g_j==NULL) {error_msg(""Memory error.\n"",__LINE__);return(1);} + + g_x = (float *)Gcalloc(max_axis_len,sizeof(float),0); + if (g_x==NULL) {error_msg(""Memory error.\n"",__LINE__);return(1);} + + p = outdist_squared; + len = g_stride[rank - 1]; + while (len--) { + *p++ = (*inimage++ == inobject)? 0.f : FLT_MAX; + } + p2 = outdist_squared; + ftmp = deltax[rank - 1]; + if (ftmp < 0.f) ftmp = -ftmp; + len = data_len - g_stride[rank - 1]; + while (len--) { + if (*inimage++ == inobject) *p = 0.f; + else if ((*p = *p2) != FLT_MAX) *p += ftmp; + p++; + p2++; + } + if (rank > 1) { + g_axis_len = axis_len; + g_deltax = deltax; + + g_recip = (float **)Gcalloc(rank - 1,sizeof(float *),0); + if (g_recip==NULL) {error_msg(""Memory error.\n"",__LINE__);return(1);} + g_square = (float **)Gcalloc(rank - 1,sizeof(float *),0); + if (g_square==NULL) {error_msg(""Memory error.\n"",__LINE__);return(1);} + + for (i=0; i ftmp2) *p2 = ftmp2; + } + } + recursive_add_dist_squared(rank-2, p); + } + len = g_stride[rank - 1]; + while (len--) { + if (*--p != FLT_MAX) *p *= *p; + } + recursive_add_dist_squared(rank-2, p); + for (i=0; i ftmp2) *p2 = ftmp2; + } + } + if (*--p != FLT_MAX) *p *= *p; + } + Gfree(g_stride); + Gfree(g_tmp); + Gfree(g_tmp_row); + Gfree(g_j); + Gfree(g_x); + return 0; + } + + +static int sub2ind(int horiz, int vert, int depth, int img_horiz, int img_vert) + { /* convert subscripts to linear index */ + return(horiz+(vert+depth*img_vert)*img_horiz); /* factoring to save a mult... why not? */ + } + + +static int get_cc(unsigned char * zpic, int *que, int * status, int *dims, int *ac, int connectivity) + { + int i,*offs,nbrs6[6],nbrs18[18],*g_counts; + int j,k,h,vox,c,w,groups,que_pos,que_len; + int autocrop[3][2],woffsh,w0; + + vox=dims[0]*dims[1]*dims[2]; + + nbrs6[0]=-1; nbrs6[1]=1; + nbrs6[2]=-dims[0]; nbrs6[3]=dims[0]; + nbrs6[4]=-dims[0]*dims[1]; nbrs6[5]=-nbrs6[4]; + + for (k=h=0;k<3;k++) + for(j=0;j<3;j++) + for(i=0;i<3;i++) + if (!((i==0 || i==2)&&(j==0 || j==2)&&(k==0 || k==2))) + if ((i!=1)||(j!=1)||(k!=1)) /* calculate offsets for all 18 neighboring voxels */ + nbrs18[h++]=sub2ind(i,j,k,dims[0],dims[1])-sub2ind(1,1,1,dims[0],dims[1]); + + if (connectivity==18) {c=18; offs=nbrs18;} + else {c=6; offs=nbrs6;} + + for(i=0;i0);} + + w=groups=0; + for(k=0;kw) {w=g_counts[i]; h=i;} + for(i=0;ii) autocrop[0][0]=i; if (autocrop[0][1]j) autocrop[1][0]=j; if (autocrop[1][1]k) autocrop[2][0]=k; if (autocrop[2][1]verbose!=0); + if (verbose) print_msg(""Setting up...\n""); + + if((input=g0->input)==NULL) + {error_msg(""No input volume.\n"",__LINE__);return(1);} + + if ((g0->dims[0]<=0)||(g0->dims[1]<=0)||(g0->dims[2]<=0)) + {error_msg(""Bad input volume dimensions.\n"",__LINE__);return(1);} + + calloc_list=(void**)basic_calloc(max_calloced,sizeof(void*)); + if (calloc_list==NULL) + {error_msg(""Memory error.\n"",__LINE__);return(1);} + + persist=(int*)basic_calloc(max_calloced,sizeof(int)); + if (persist==NULL) + {error_msg(""Memory error.\n"",__LINE__);return(1);} + + if ((g0->connectivity!=6)&&(g0->connectivity!=18)) g0->connectivity=6; + connectivity=g0->connectivity; + invconnectivity=(g0->connectivity==6)?18:6; + + pad=g0->pad; + for(i=0;i<3;i++) if (pad[i]<2) pad[i]=2; + + g0->biggest_component=(g0->biggest_component!=0); + cut_loops=g0->cut_loops=(g0->cut_loops!=0); + g0->return_surface=(g0->return_surface!=0); + g0->return_adjusted_label_map=(g0->return_adjusted_label_map!=0); + + value=g0->value; + + /* get cropping limits */ + for(k=0;k<3;k++) {autocrop[k][0]=(g0->dims)[k]; autocrop[k][1]=0;} + for(k=h=0;k<(g0->dims[2]);k++) + for(j=0;j<(g0->dims[1]);j++) + for(i=0;i<(g0->dims[0]);i++) + { + if (input[h]>=value) + { + if (autocrop[0][0]>i) autocrop[0][0]=i; if (autocrop[0][1]j) autocrop[1][0]=j; if (autocrop[1][1]k) autocrop[2][0]=k; if (autocrop[2][1]autocrop[0][1]) || (autocrop[1][0]>autocrop[1][1]) || + (autocrop[2][0]>autocrop[2][1])) + {error_msg(""No data in volume matches specified value.\n"",__LINE__);return(1);} + + /* calculate cropped dimensions, and total length */ + img_horiz= autocrop[0][1]-autocrop[0][0]+1+pad[0]*2; + img_vert = autocrop[1][1]-autocrop[1][0]+1+pad[1]*2; + img_depth= autocrop[2][1]-autocrop[2][0]+1+pad[2]*2; + totlen=img_horiz*img_vert*img_depth; + paddeddims[0]=img_horiz; paddeddims[1]=img_vert; paddeddims[2]=img_depth; + + if ((zpic=(unsigned char *)Gcalloc(totlen,sizeof(unsigned char),0))==NULL) + {error_msg(""Memory error.\n"",__LINE__);return(1);} + + for(k=0;k<(img_depth-pad[2]*2);k++) + for(j=0;j<(img_vert-pad[1]*2);j++) + for(i=0;i<(img_horiz-pad[0]*2);i++) + { + h=sub2ind(pad[0]+i,pad[1]+j,pad[2]+k,img_horiz,img_vert); + hz=sub2ind(autocrop[0][0]+i,autocrop[1][0]+j,autocrop[2][0]+k,g0->dims[0],g0->dims[1]); + zpic[h]=(int)(input[hz]>=value); + } + + que=NULL; + status=NULL; + + if (g0->connected_component) + { + que_size=totlen; + if ((que=(int *)Gcalloc(que_size,sizeof(int),0))==NULL) + {error_msg(""Memory error.\n"",__LINE__);return(1);} + + /* initialize voxel status */ + if ((status=(int *)Gcalloc(totlen,sizeof(int),0))==NULL) + {error_msg(""Memory error.\n"",__LINE__);return(1);} + + /* zpic is binary. return connected component */ + if(get_cc(zpic,que,status,paddeddims,ac,g0->connectivity)) + {error_msg(""Connected component error.\n"",__LINE__);return(1);} + + /* now we can crop zpic even more */ + autocrop[0][0]+=ac[0]-pad[0]; + autocrop[0][1]=autocrop[0][0]+(ac[1]-ac[0]); + + autocrop[1][0]+=ac[2]-pad[1]; + autocrop[1][1]=autocrop[1][0]+(ac[3]-ac[2]); + + autocrop[2][0]+=ac[4]-pad[2]; + autocrop[2][1]=autocrop[2][0]+(ac[5]-ac[4]); + + img_horiz= autocrop[0][1]-autocrop[0][0]+1+pad[0]*2; + img_vert = autocrop[1][1]-autocrop[1][0]+1+pad[1]*2; + img_depth= autocrop[2][1]-autocrop[2][0]+1+pad[2]*2; + totlen=img_horiz*img_vert*img_depth; + + h=0; + for(k=0;kijk2ras)==NULL) + voxelsize[0]=voxelsize[1]=voxelsize[2]=1.0; + else + for(i=0;i<3;i++) + voxelsize[i]=sqrt(m[0+i]*m[0+i]+m[4+i]*m[4+i]+m[8+i]*m[8+i]); + for(i=0;i<3;i++) if ((g0->extraijkscale)[i]<=0.0) (g0->extraijkscale)[i]=1.0; + for(i=0;i<3;i++) voxelsize[i]*=(g0->extraijkscale)[i]; + minvoxelsize=voxelsize[0]; + if (minvoxelsize>voxelsize[1]) minvoxelsize=voxelsize[1]; + if (minvoxelsize>voxelsize[2]) minvoxelsize=voxelsize[2]; + if (minvoxelsize<=0.0) minvoxelsize=1.0; + + /* calculate a bunch of offsets to face-sharing voxel neighbors */ + nbrs[0]=-1; nbrs[1]=-nbrs[0]; + nbrs[2]=-img_horiz; nbrs[3]=-nbrs[2]; + nbrs[4]=-(img_horiz*img_vert); nbrs[5]=-nbrs[4]; + + for (k=h=0;k<3;k++) + for(j=0;j<3;j++) + for(i=0;i<3;i++) /* calculate offsets for all 27 voxels in neighborhood */ + offs[h++]=sub2ind(i,j,k,img_horiz,img_vert)-sub2ind(1,1,1,img_horiz,img_vert); + + for (k=h=0;k<3;k++) + for(j=0;j<3;j++) + for(i=0;i<3;i++) + if (!((i==0 || i==2)&&(j==0 || j==2)&&(k==0 || k==2))) + if ((i!=1)||(j!=1)||(k!=1)) /* calculate offsets for all 18 neighboring voxels */ + nbrs18[h++]=sub2ind(i,j,k,img_horiz,img_vert)-sub2ind(1,1,1,img_horiz,img_vert); + + for (k=h=0;k<3;k++) + for(j=0;j<3;j++) + for(i=0;i<3;i++) + if ((i!=1)||(j!=1)||(k!=1)) /* calculate offsets for 26 neighboring voxels */ + nbrs26[h++]=sub2ind(i,j,k,img_horiz,img_vert)-sub2ind(1,1,1,img_horiz,img_vert); + + + /* even more offsets */ + calc_elist(); + for(i=0;i<27;i++) pass[i]=1; + + if (!(g0->any_genus)) + { + que_size=totlen; + if (que==NULL) /* might have already calloced it above ... */ + if ((que=(int *)Gcalloc(que_size,sizeof(int),0))==NULL) + {error_msg(""Memory error.\n"",__LINE__);return(1);} + + if ((fzpic=(float *)Gcalloc(totlen,sizeof(float),0))==NULL) + {error_msg(""Memory error.\n"",__LINE__);return(1);} + + paddeddims[0] =img_horiz; paddeddims[1] =img_vert; paddeddims[2] =img_depth; + paddeddims0[0]=img_horiz; paddeddims0[1]=img_vert; paddeddims0[2]=img_depth; + + /* calculate distance transform */ + /* sets fzpic to dist from {zpic=(1-cut_loops)} */ + if (dist_squared(3,paddeddims0,voxelsize,(char*)zpic,(char)(1-g0->cut_loops),fzpic)) + {error_msg(""Memory error.\n"",__LINE__);return(1);} + + fzpicmax=0.0; + for(i=0;ifzpicmax) fzpicmax=fzpic[i]; + } + + maxlevels=(int)(fzpicmax/minvoxelsize+2.5); + + /* Formula for cm_size. certain to be <= totlen + 12 */ + cm_size=totlen+12; + if ((cm=(int *)Gcalloc(cm_size,sizeof(int),0))==NULL) + {error_msg(""Memory error.\n"",__LINE__);return(1);} + + /* initialize voxel status */ + if (status==NULL) /* might have already calloced it above ... */ + if ((status=(int *)Gcalloc(totlen,sizeof(int),0))==NULL) + {error_msg(""Memory error.\n"",__LINE__);return(1);} + + for (i=0;icut_loops)?0:3; /* 3 if not wanted component */ + + /* set status of double boundary to 4 */ + for(i=0;iany_genus)) */ + else + { + if (que!=NULL) Gfree(que); /* don't need the que if not doing topology correction */ + } + return(0); /* no error */ + } + + +static int truecm(int st) /* return true component, set cm[st] to true comp */ + { + int s0,s1; + if (cm[st]!=st) + { + s0=st; + while (cm[st]!=st) st=cm[st]; + while (cm[s0]!=st) {s1=cm[s0]; cm[s0]=st; s0=s1;} + } + return(st); + } + + +static int truecmvx(int vx) /* return true component of voxel */ + { + return(status[vx]=truecm(status[vx])); + } + + +static int test18(int qqp, int *nc) + { + int elQqpj,stqqpn,i,j,ec_count=0,ec[27],found_another=1; + int st[19],Que_len,Que_pos,Que[27],Qqp; + static int idx[18]={1,3,4,5,7,9,10,11,12,14,15,16,17,19,21,22,23,25}; + + for(i=0;i<27;i++) ec[i]=0; + + for(i=0;i<18;i++) /* for each 18 neighbor */ + if (status[qqp+nbrs18[i]]>10) /* if nbr is in an Mcubes component */ + if (!ec[idx[i]]) /* if not assigned an edge component */ + { + /* create new edge component */ + stqqpn=truecmvx(qqp+nbrs18[i]); + st[++ec_count]=stqqpn; /* remember the status associated with the new component */ + + /* find all in the edge component */ + + Que_pos=0; Que_len=1; Que[0]=idx[i]; /* add it to Que */ + ec[idx[i]]=ec_count; + while (Que_pos10) && (!ec[elQqpj])) + ec[Que[Que_len++]=elQqpj]=ec_count; /* add nbr to que */ + } + Que_pos++; + } + + /* compare with previous components */ + for(j=1;j0)?(st[1]):0; + return(found_another); + } + + +static int test6(int qqp, int *nc) + { + int elQqpj,stqqpn,i,j,ec_count=0,ec[27],found_another=1; + int st[7],Que_len,Que_pos,Que[27],Qqp; + static int idx[6]={12,14,10,16,4,22}; + + for(i=0;i<27;i++) ec[i]=0; + + pass[1]=pass[3]=pass[5]=pass[7]=pass[9]=pass[11]=pass[15]=pass[17]= + pass[19]=pass[21]=pass[23]=pass[25]=0; + if(status[qqp+offs[ 4]]>10) pass[ 1]=pass[ 3]=pass[ 5]=pass[ 7]=1; + if(status[qqp+offs[10]]>10) pass[ 1]=pass[ 9]=pass[11]=pass[19]=1; + if(status[qqp+offs[12]]>10) pass[ 3]=pass[ 9]=pass[15]=pass[21]=1; + if(status[qqp+offs[14]]>10) pass[ 5]=pass[11]=pass[17]=pass[23]=1; + if(status[qqp+offs[16]]>10) pass[ 7]=pass[15]=pass[17]=pass[25]=1; + if(status[qqp+offs[22]]>10) pass[19]=pass[21]=pass[23]=pass[25]=1; + + for(i=0;i<6;i++) /* for each neighbor */ + if (status[qqp+nbrs[i]]>10) /* if nbr is in an Mcubes component */ + if (!ec[idx[i]]) /* if not assigned an edge component */ + { + /* create new edge component */ + + stqqpn=truecmvx(qqp+nbrs[i]); + st[++ec_count]=stqqpn; /* remember the status associated with the new component */ + + /* find all in the edge component */ + + Que_pos=0; Que_len=1; Que[0]=idx[i]; /* add it to Que */ + ec[idx[i]]=ec_count; + while (Que_pos10) && (!ec[elQqpj]) && pass[elQqpj]) + ec[Que[Que_len++]=elQqpj]=ec_count; /* add nbr to que */ + } + Que_pos++; + } + + /* compare with previous components */ + for(j=1;j0)?(st[1]):0; + return(found_another); + } + + +static int cmtostat(void) + { + int j,i,*cmremap=NULL,*ccount=NULL,totlen; + char msg[200]; + + if ((cmremap=(int *)Gcalloc(comp_count+1,sizeof(int),0))==NULL) + {error_msg(""Memory error.\n"",__LINE__);return(1);} + if ((ccount=(int *)Gcalloc(comp_count+1,sizeof(int),0))==NULL) + {error_msg(""Memory error.\n"",__LINE__);return(1);} + + for(i=11;i<=comp_count;i++) ccount[truecm(i)]++; + + j=10; + for(i=11;i<=comp_count;i++) + if (ccount[i]) + { + j++; + cmremap[i]=j; + } + totlen=img_horiz*img_vert*img_depth; + for (i=0;i10) status[i]=cmremap[cm[status[i]]]; + + if (verbose&&0) + { + sprintf(msg,""Components reduced from %u to %u.\n"",comp_count-10,j-10); + print_msg(msg); + } + comp_count=j; + for(i=11;i<=comp_count;i++) cm[i]=i; + Gfree(cmremap); + Gfree(ccount); + return(0); + } + + +static void find_component(int level) + { + int i,qqp,qqpni,vox,nc; + int found_another,*nbrs0,totlen; + int (*test)(int, int *); + float flevel; + int theconnectivity; + + if (cut_loops) theconnectivity=connectivity; + else theconnectivity=invconnectivity; + + totlen=img_horiz*img_vert*img_depth; + nbrs0=nbrs; test=test6; + if (theconnectivity==18) {nbrs0=nbrs18; test=test18;} + + flevel=(level-1.0)/(maxlevels-1.0)*fzpicmax; + + for(vox=0;vox=flevel) && (status[vox]==0)) + { + que_len=que_pos=0; + que[que_len]=vox; /* add it to que */ + que_len++; if (que_len==que_size) que_len=0; + status[vox]=2; /* mark as on que */ + while (que_pos!=que_len) + { + qqp=que[que_pos]; + /* check if can add */ + nc=0; + found_another=test(qqp,&nc); + /* if you can, add it, and combine components if needed */ + if (found_another) + { + if(nc==0) /* if no neighboring component */ + { + comp_count++; + cm[comp_count]=comp_count; + status[qqp]=comp_count; + } + else + { + status[qqp]=nc; /* there was this true component nc */ + for(i=0;i10) /* if part of a component */ + { + if (truecmvx(qqpni)!=nc) /* if not the same component as qqp */ + { + cm[status[qqpni]]=nc; + status[qqpni]=nc; + } + } + } + } + /* add nbrs to que, if level ok, etc. */ + for(i=0;i=flevel) && (status[qqpni]==0)) + { + que[que_len]=qqpni; /* add it to que */ + que_len++; if (que_len==que_size) que_len=0; + status[qqpni]=2; /* mark as on que */ + } + } /* for i */ + } /* if found another */ + else + { + status[qqp]=0; + } + /* move to next point in que */ + que_pos++; if (que_pos==que_size) que_pos=0; + } /* while que not empty */ + } /* end if >=level and status==0 */ + } /* end for vox */ + } /* end find_component */ + + +static int GetSurf(unsigned char * J, unsigned char val, int * dims, int connectivity, + int ** Tris, float ** Verts, int * Tri_count, int * Vert_count, genus0parameters *g0) + { + unsigned char *status,*cidx,*pidx; + int img_vert,iv1,img_horiz,img_depth,cellplane,cellplanem[3]; + int i,j,k,u,v,w,*v_idx,tri_count,vert_count,ic,cells,tc[256],vc[256]; + int ih1,id1,stat,pc,vert_count1,tri_count1,tcm[3],tsvw; + int offs[8],coffs[12],ctype[12],*ts,hep[3],planeidx[12],planeoff[2]; + int hep2[3]={5,6,11},*tris,vert_count_times2; + unsigned char pows[8]={64, 128, 16, 32, 4, 8, 1, 2}; /* 2^(6 7 4 5 2 3 0 1) */ + float half[3][3]={{0.5,1.0,1.0},{1.0,0.5,1.0},{1.0,1.0,0.5}},*verts; + + #include ""tricases.h"" + + *Tris=NULL; + *Verts=NULL; + *Tri_count=*Vert_count=0; + + for(i=0;i<256;i++) + for(j=15;j<19;j++) + tricases[i][j]=-1; + + if (connectivity>6) /* flip table up and down */ + for(i=0;i<128;i++) + for(j=0;j<19;j++) + { + k=tricases[i][j]; tricases[i][j]=tricases[255-i][j]; tricases[255-i][j]=k; + } + if (connectivity==26) /* modify table for 26 nbr connectivity */ + for(i=0;i<19;i++) + { + tricases[65 /*190*/][i]=altcases[0][i]; + tricases[130 /*125*/][i]=altcases[1][i]; + tricases[40 /*215*/][i]=altcases[2][i]; + tricases[20 /*235*/][i]=altcases[3][i]; + } + if (connectivity>6) /* switch triangle orientation if we've flipped */ + for(i=0;i<256;i++) + for(j=0;j<18;j+=3) + { + k=tricases[i][j]; tricases[i][j]=tricases[i][j+1]; tricases[i][j+1]=k; + } + + img_horiz=dims[0]; /* cols, fastest in memory */ + img_vert=dims[1]; /* rows */ + img_depth=dims[2]; /* planes, slowest in mem*/ + + ih1=img_horiz-1; + iv1=img_vert-1; + id1=img_depth-1; + + cellplane=ih1*iv1; + cells=id1*cellplane; + cellplanem[0]=0; cellplanem[1]=cellplane; cellplanem[2]=(cellplane<<1); + + v_idx=(int*)Gcalloc(cellplane*3*2,sizeof(int),0); + if (v_idx==NULL) {error_msg(""Memory error.\n"",__LINE__);return(1);} + + status=(unsigned char*)Gcalloc(cells,sizeof(unsigned char),0); + if (status==NULL) {error_msg(""Memory error.\n"",__LINE__);return(1);} + + for(i=0;i<256;i++) /* calculate number of tris, new verts for each case */ + { + hep[0]=hep[1]=hep[2]=0; + k=0; + for(j=0;j<19;j++) + { + if (tricases[i][j]>=0) k++; + for(w=0;w<3;w++) if (tricases[i][j]==hep2[w]) hep[w]=1; + } + tc[i]=k/3; + vc[i]=hep[0]+hep[1]+hep[2]; + } + + /* calculate offsets to adjacent cells */ + offs[0]=0; offs[1]=1; offs[2]=img_horiz; offs[3]=ih1; + for(i=4;i<8;i++) offs[i]=offs[i-4]+cellplane; + + /* calculate offsets to point into v_idx */ + /* v_idx holds vertex number data for two cell planes */ + /* cell edge midpoints 4..11 are in the current plane */ + /* 0..3 are in the previous plane */ + for(i=0;i<4;i++) planeidx[i]=0; + for(i=4;i<12;i++) planeidx[i]=1; + coffs[0]=-ih1; ctype[0]=1; /* cell edge midpoint type '6' */ + coffs[1]=0; ctype[1]=0; /* cell edge midpoint type '5' */ + coffs[2]=0; ctype[2]=1; + coffs[3]=-1; ctype[3]=0; + for(i=4;i<8;i++) {coffs[i]=coffs[i-4]; ctype[i]=ctype[i-4];} + coffs[8]=-ih1-1; ctype[8]=2; /* cell edge midpoint type '11' */ + coffs[9]=-ih1; ctype[9]=2; + coffs[10]=-1; ctype[10]=2; + coffs[11]=0; ctype[11]=2; + /* end of setup */ + + /* calculate status of each cell */ + pidx=J+1+img_horiz+(img_horiz*img_vert); /* begin at point (1,1,1) */ + cidx=status; /* begin at cell (0,0,0) */ + /* for each interior point */ + for (k=img_depth-2;k>=1;k--,pidx+=(img_horiz<<1),cidx+=ih1) + for (j=img_vert-2;j>=1;j--,pidx+=2,cidx++) + for (i=img_horiz-2;i>=1;i--,pidx++,cidx++) + if (*pidx==val) + for (w=0;w<8;w++) /* update cells which have pidx as a corner */ + *(cidx+offs[w])+=pows[w]; + + /* quick count of the number of tris, number of verts needed */ + for (tri_count=vert_count=i=0;ireturn_surface); + if (tris==NULL) {error_msg(""Memory error.\n"",__LINE__);return(1);} + + verts=(float*)Gcalloc(vert_count*3,sizeof(float),g0->return_surface); + if (verts==NULL) {error_msg(""Memory error.\n"",__LINE__);return(1);} + + *Tris=tris; + *Verts=verts; + *Vert_count=vert_count; + *Tri_count=tri_count; + + /* extract the surface... */ + ic=0; /* number of cell within cell volume */ + vert_count1=tri_count1=0; + for (k=0;k1) + { + if ((c_count=(int *)Gcalloc(1+comp_count,sizeof(int),0))==NULL) + {error_msg(""Memory error.\n"",__LINE__);return(1);} + + for(i=0;ipad; + totlen=img_horiz*img_vert*img_depth; + + if (!(g0->any_genus)) /* if we made topological corrections */ + { + j=0; + for(i=0;icut_loops)?(1-sti):sti; /* switch to complement */ + if ((zp==g0->cut_loops) && (status[i]<=10) &&(status[i]!=4)) + { + status[i]=1; /* we wanted this one */ + j++; + } + else status[i]=0; + } + if (verbose) {sprintf(msg,""Made %d adjustments.\n"",j);print_msg(msg);} + Gfree(que); + Gfree(cm); + Gfree(fzpic); + } + + /* Get the surface ! */ + dims[0]=img_horiz; dims[1]=img_vert; dims[2]=img_depth; + if(GetSurf(zpic,1,dims,g0->connectivity, + &(g0->triangles), &(g0->vertices), + &(g0->tri_count),&(g0->vert_count),g0)) return(1); + if (g0->biggest_component) + if ((g0->tri_count>0)&&(g0->vert_count>0)) + if(big_component(g0->triangles,g0->vertices,&(g0->vert_count),&(g0->tri_count))) + {error_msg(""Error getting surface components.\n"",__LINE__);return(1);} + + output=g0->output; + if (g0->return_adjusted_label_map) /* they want a new label map back */ + { + origlen=(g0->dims[0])*(g0->dims[1])*(g0->dims[2]); + if (output==NULL) /* they didn't allocate. So we need to */ + { + if ((output=(unsigned short *)Gcalloc(origlen,sizeof(unsigned short),1))==NULL) + {error_msg(""Memory error.\n"",__LINE__);return(1);} + g0->calloced_output=1; + } + g0->output=output; + for(i=0;iinput)[i]; /* just copy original input */ + if (!(g0->any_genus)) + { + for(k=0;k<(img_depth-pad[2]*2);k++) + for(j=0;j<(img_vert-pad[1]*2);j++) + for(i=0;i<(img_horiz-pad[0]*2);i++) + { + h1=sub2ind(pad[0]+i,pad[1]+j,pad[2]+k,img_horiz,img_vert); + h=sub2ind(autocrop[0][0]+i,autocrop[1][0]+j,autocrop[2][0]+k,g0->dims[0],g0->dims[1]); + if (status[h1]) output[h]=g0->alt_value; + } + } + } + vo[0]=0; vo[1]=g0->vert_count; vo[2]=(g0->vert_count)*2; + verts=g0->vertices; + + if (g0->return_adjusted_label_map) /* they want a new label map back */ + { + if (g0->contour_value==65535) g0->contour_value=g0->alt_value; + if (g0->alt_contour_value==65535) g0->alt_contour_value=g0->alt_value; + for(h=0;hvert_count;h++) + { + j=0; /* j will be direction in which 0.5 position occurs */ + for (i=0;i<3;i++) + { + pos[i]=(int)verts[h+vo[i]]; + if ((verts[h+vo[i]]-pos[i])==0.5) j=i; /* must happen exactly once */ + } + i=sub2ind(pos[0],pos[1],pos[2],dims[0],dims[1]); /* index into zpic */ + if (zpic[i]==0) pos[j]++; /* subscript into boundary voxel of zpic */ + for (i=0;i<3;i++) pos[i]+=autocrop[i][0]-pad[i]; /* subscript into boundary voxel of input */ + i=sub2ind(pos[0],pos[1],pos[2],g0->dims[0],g0->dims[1]); /* index into input */ + output[i]=((g0->input)[i]==g0->value)?(g0->contour_value):(g0->alt_contour_value); + } + } + + /* need to translate verts back into input space. zpic has been cropped */ + for(h=0;hvert_count;h++) for (i=0;i<3;i++) verts[h+vo[i]]+=autocrop[i][0]-pad[i]; + + /* multiply verts by ijk2ras matrix */ + if (g0->ijk2ras!=NULL) + { + m=g0->ijk2ras; + for(h=0;hvert_count;h++) + { + hv[0]=(g0->vertices)[h]; + hv[1]=(g0->vertices)[h+(g0->vert_count)]; + hv[2]=(g0->vertices)[h+((g0->vert_count)<<1)]; + (g0->vertices)[h] =m[0]*hv[0]+m[1]*hv[1]+m[ 2]*hv[2]+m[3]; + (g0->vertices)[h+g0->vert_count] =m[4]*hv[0]+m[5]*hv[1]+m[ 6]*hv[2]+m[7]; + (g0->vertices)[h+((g0->vert_count)<<1)]=m[8]*hv[0]+m[9]*hv[1]+m[10]*hv[2]+m[11]; + } + } + + Gfree(zpic); + if (!(g0->any_genus)) Gfree(status); + if (!(g0->return_surface)) /* don't return surface if they didn't want it */ + { + Gfree(g0->vertices); g0->vertices=NULL; + Gfree(g0->triangles); g0->triangles=NULL; + } + + if (verbose) + { + sprintf(msg,""Vertices: %d Triangles: %d\n"",g0->vert_count,g0->tri_count); + print_msg(msg); + } + return(0); + } + +extern void genus0init(genus0parameters * g0) + { + g0->input=NULL; + g0->return_adjusted_label_map=1; + g0->return_surface=1; + (g0->dims)[0]=(g0->dims)[1]=(g0->dims)[2]=0; + g0->alt_value=g0->value=0; + g0->contour_value=65535; + g0->alt_contour_value=65535; + g0->cut_loops=0; + g0->pad[0]=g0->pad[1]=g0->pad[2]=2; + g0->connectivity=6; + g0->any_genus=0; + g0->biggest_component=1; + g0->connected_component=1; + g0->ijk2ras=NULL; + (g0->extraijkscale)[0]=(g0->extraijkscale)[1]=(g0->extraijkscale)[2]=1.0; + g0->verbose=0; + + g0->output=NULL; + g0->vert_count=0; + g0->vertices=NULL; + g0->tri_count=0; + g0->triangles=NULL; + g0->calloced_output=0; /* private */ + } + + + +extern int genus0(genus0parameters * g0) + { + int thistenth,lasttenth,level; + + if (set_up(g0)) {Gfree_all(0);return(1);} + if (!(g0->any_genus)) + { + if (verbose) printf(""Starting main process...\n""); + lasttenth=0; + for(level=maxlevels;level>=1;level--) /* [maxlevels...1] */ + { + find_component(level); + thistenth=(int)(((float)(maxlevels-level))/(maxlevels-1.0)*10.0+0.5); + if (thistenth!=lasttenth) + { + lasttenth=thistenth; + if (verbose) printf(""Done with %d percent.\n"",thistenth*10); + if (thistenth<10) + if (cmtostat()) {Gfree_all(0);return(1);} + } + } + if(cmtostat()) {Gfree_all(0);return(1);} + } + if (save_image(g0)) {Gfree_all(0);return(1);} + Gfree_all(1); /* isn't really be needed, if we've freed our calloc's */ + return(0); /* normal, error free return */ + } + +extern void genus0destruct(genus0parameters * g0) + { + if (g0->vertices!=NULL) + { + basic_free(g0->vertices); + g0->vertices=NULL; + } + if (g0->triangles!=NULL) + { + basic_free(g0->triangles); + g0->triangles=NULL; + } + if (g0->calloced_output) + if (g0->output!=NULL) + { + basic_free(g0->output); + g0->output=NULL; + g0->calloced_output=0; + } + } +","C" +"Neurology","ChristianGaser/cat12","cat_surf_surf2roi.m",".m","11452","267","function varargout = cat_surf_surf2roi(job) +% ______________________________________________________________________ +% Function to read surface data for atlas maps and create ROI files. +% The function create CSV, as well as XML files. +% Each atlas requires its own CSV file and existing files will actual +% be overwriten. +% In the XML file a structure is used to save the ROIs that allow +% updating of the data. +% +% cat_surf_surf2roi(job) +% +% job.cdata .. cell of cells with the left surface cdata files +% (same number and order of subjects required) +% job.rdata .. cell of left atlas maps +% job.verb .. verbose level (default = 1) +% job.avg .. parameter what averaging is use for each ROI +% struct('mean',1,'std',1,'min',0,'max',0,'median',1); +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + +% ______________________________________________________________________ +% ToDo: +% * read of resampled +% * area estimation +% * create output (average) maps??? +% > not for calcuation, because of redundant data and this is maybe +% a separate function (or use excel) > cat_roi_calc? +% > not for surface displaying, because this a separate function +% cat_roi_display? +% ______________________________________________________________________ + + + %#ok<*AGROW,*NASGU,*PREALL>> + + % parameter + def.verb = 1; + def.debug = cat_get_defaults('extopts.verb')>2; + def.avg = struct('mean',1,'std',0,'min',0,'max',0,'median',0); % mean, min, max, median, std + def.plot = 0; % not ready + def.nproc = 0; % not ready + def.area = 0; + def.vernum = 0; + def.resamp = 1; % resample native data to atlas space (without smoothing) + job = cat_io_checkinopt(job,def); + + % split job and data into separate processes to save computation time + if isfield(job,'nproc') && job.nproc>0 && (~isfield(job,'process_index')) + cat_parallelize(job,mfilename,'cdata'); %,'cat_surf_surf2roi'); + return + elseif isfield(job,'printPID') && job.printPID + cat_display_matlab_PID + end + + % display something + spm_clf('Interactive'); + + % if rdata is not defined use default atlases + if ~isfield(job,'rdata') + job.rdata = cat_vol_findfiles(fullfile(fileparts(mfilename('fullpath')),'atlases_surfaces'),{'lh.aparc_*'}); + end + + %% ROI evaluation + FN = fieldnames(job.avg); + + xmlname = cell(numel(job.cdata{1}),1); + + [tmp, pth_templates] = fileparts(cat_get_defaults('extopts.pth_templates')); + % processing + [CATrel, CATver] = cat_version; + for ri=1:numel(job.rdata) + %% load atlas map + % load the cdata that describe the ROIs of each hemisphere and + % read the ROIs IDs and names from the csv or annot files + rinfo = cat_surf_info(job.rdata{ri},0); + + switch rinfo.ee + case '.annot' + % FreeSurfer annotation files + [vertices, lrdata, colortable, lrcsv] = cat_io_FreeSurfer('read_annotation',job.rdata{ri}); + [vertices, rrdata, colortable, rrcsv] = cat_io_FreeSurfer('read_annotation',char(cat_surf_rename(job.rdata{ri},'side','rh'))); + clear vertices colortable; + case 'gii' + % gifti and csv-files + lrdata = gifti(job.rdata{ri}); + rrdata = gifti(char(cat_surf_rename(rinfo,'side','rh'))); + + rdatacsv = cat_vol_findfiles(strrep(rinfo.pp,'atlases_surfaces',pth_templates),[rinfo.dataname '*.csv']); + if ~isempty(rdatacsv{1}) + rcsv=cat_io_csv(rdatacsv{1}); + end + otherwise + % FreeSurfer and csv-files + lrdata = cat_io_FreeSurfer('read_surf_data',job.rdata{ri}); + rrdata = cat_io_FreeSurfer('read_surf_data',char(cat_surf_rename(rinfo,'side','rh'))); + + rdatacsv = cat_vol_findfiles(strrep(rinfo.pp,'atlases_surfaces',pth_templates),[rinfo.dataname '*.csv']); + if ~isempty(rdatacsv{1}) + rcsv=cat_io_csv(rdatacsv{1}); + end + end + + + %% process the cdata files of each subject + for si=1:numel(job.cdata{1}) % for each subject + [mrifolder, reportfolder, surffolder, labelfolder] = cat_io_subfolders(job.cdata{1}{si}); + for ti=1:numel(job.cdata) % for each texture + + % check for kind of surface + sinfo = cat_surf_info(job.cdata{ti}{si},0); + + if all(~cell2mat(strfind({'central','hull','sphere','sphere.reg','resampledBySurf2roi'},sinfo.dataname))) + + % RD202108: resampled data but without given filename information + if size(lrdata,1) == 163842 + type = '164k'; + elseif size(lrdata,1) == 32492 + type = '32k'; + end + + % RD202108: data without structured filename + if isempty(sinfo.name) + sinfo.name = sinfo.ff; + end + + % load surface cdata + if job.resamp && (sinfo.resampled==0 && sinfo.resampled_32k==0) % do temporary resampling + lCS = get_resampled_values(job.cdata{ti}{si},job.debug,type); + rCS = get_resampled_values(cat_surf_rename(sinfo,'side','rh'),job.debug,type); + elseif strcmp(sinfo.side,'mesh') + switch sinfo.ee + case '.gii' + CS = gifti(job.cdata{ti}{si}); + CS = export(CS,'patch'); + CS = CS.facevertexcdata; + otherwise + CS = cat_io_FreeSurfer('read_surf_data',job.cdata{ti}{si}); + end + lCS.cdata = CS(1:32492); + rCS.cdata = CS(32492:end); + else + switch sinfo.ee + case '.gii' + lCS = gifti(job.cdata{ti}{si}); + rCS = gifti(char(cat_surf_rename(sinfo,'side','rh'))); + otherwise + lCS = cat_io_FreeSurfer('read_surf_data',job.cdata{ti}{si}); + rCS = cat_io_FreeSurfer('read_surf_data',char(cat_surf_rename(sinfo,'side','rh'))); + end + end + + % basic entries + clear ccsv; + switch rinfo.ee + case '.annot' + catROI{si}.(rinfo.dataname).ids(1:2:size(lrcsv,1)*2-2,1) = cell2mat(lrcsv(2:end,1)); + catROI{si}.(rinfo.dataname).ids(2:2:size(rrcsv,1)*2-2,1) = cell2mat(rrcsv(2:end,1)); + catROI{si}.(rinfo.dataname).names(1:2:size(lrcsv,1)*2-2,1) = lrcsv(2:end,2); + catROI{si}.(rinfo.dataname).names(2:2:size(rrcsv,1)*2-2,1) = rrcsv(2:end,2); + for roii=1:2:numel(catROI{si}.(rinfo.dataname).ids)-1 + catROI{si}.(rinfo.dataname).names{roii,1} = ['l' catROI{si}.(rinfo.dataname).names{roii}]; + catROI{si}.(rinfo.dataname).names{roii+1,1} = ['r' catROI{si}.(rinfo.dataname).names{roii+1}]; + end + otherwise + catROI{si}.(rinfo.dataname).ids = rcsv(1:end,1); + catROI{si}.(rinfo.dataname).names = rcsv(1:end,2); + end + catROI{si}.(rinfo.dataname).comments = {'cat_surf_surf2roi'}; + catROI{si}.(rinfo.dataname).version = CATver; + + for ai=1:numel(FN) + if job.avg.(FN{ai}) + if sum(cell2mat(struct2cell(job.avg)))==1 && strcmp(FN{1},'mean') + fieldname = sinfo.dataname; + else + fieldname = sprintf('%s_%s',FN{ai},sinfo.dataname); + end + if strcmpi(spm_check_version,'octave'), maxchar = 127; else, maxchar = 1023; end + fieldname = cat_io_strrep(fieldname,num2cell(char([33:47,124:maxchar])),'_'); + fieldname = cat_io_strrep(fieldname,'__','_'); + switch FN{ai} + case {'min','max'}, nanfunc = ''; + case {'mean','median','std'}, nanfunc = 'cat_stat_nan'; + end + + for roii=1:numel(catROI{si}.(rinfo.dataname).ids) + switch catROI{si}.(rinfo.dataname).names{roii}(1) + case 'l', catROI{si}.(rinfo.dataname).data.(fieldname)(roii,1) = ... + eval(sprintf('%s%s(lCS.cdata(lrdata==catROI{si}.(rinfo.dataname).ids(roii)))',nanfunc,FN{ai})); + case 'r', catROI{si}.(rinfo.dataname).data.(fieldname)(roii,1) = ... + eval(sprintf('%s%s(rCS.cdata(rrdata==catROI{si}.(rinfo.dataname).ids(roii)))',nanfunc,FN{ai})); + case 'b', catROI{si}.(rinfo.dataname).data.(fieldname)(roii,1) = ... + eval(sprintf(['%s%s(lCS.cdata(lrdata==catROI{si}.(rinfo.dataname).ids(roii))) + ' ... + '%s%s(rCS.cdata(rrdata==catROI{si}.(rinfo.dataname).ids(roii)))'],nanfunc,FN{ai},nanfunc,FN{ai})); + otherwise, catROI{si}.(rinfo.dataname).data.(fieldname)(roii,1) = nan; + end + end + + % write xml data + xmlname{si} = fullfile(strrep(sinfo.pp,surffolder,labelfolder),['catROIs_' sinfo.name '.xml']); + cat_io_xml(xmlname{si},catROI{si},'write+'); + + % delete temporarily resampled files + if exist(char(cat_surf_rename(sinfo,'dataname',[sinfo.dataname '.resampledBySurf2roi'],'ee','')),'file') + delete(char(cat_surf_rename(sinfo,'dataname',[sinfo.dataname '.resampledBySurf2roi'],'ee',''))); + end + if exist(char(cat_surf_rename(sinfo,'dataname',[sinfo.dataname '.resampledBySurf2roi'],'ee','','side','rh')),'file'); + delete(char(cat_surf_rename(sinfo,'dataname',[sinfo.dataname '.resampledBySurf2roi'],'ee','','side','rh'))); + end + end + end + end + end + end + end + + if nargout==1, varargout{1}.xmlname = xmlname; end + +end + +function resamp = get_resampled_values(P,debug,type) + if ~exist('type','var'), type = '164k'; end + switch type + case '164k', fsavgDir = fullfile(fileparts(mfilename('fullpath')),'templates_surfaces'); + case '32k', fsavgDir = fullfile(fileparts(mfilename('fullpath')),'templates_surfaces_32k'); + end + P = deblank(char(P)); + + [pp,ff,ex] = spm_fileparts(P); + + name = [ff ex]; + name = strrep(name,'.gii',''); % remove .gii extension + hemi = ff(1:2); + + k = strfind(name,'.'); + pname = ff(k(1)+1:k(2)-1); + Pcentral = [strrep(name,pname,'central') '.gii']; + Pspherereg = fullfile(pp,strrep(Pcentral,'central','sphere.reg')); + Presamp = fullfile(pp,strrep(Pcentral,'central',[pname '.resampledBySurf2roi.resampled'])); + Pvalue = fullfile(pp,strrep(Pcentral,'central',[pname '.resampledBySurf2roi'])); + Pvalue = strrep(Pvalue,'.gii',''); % remove .gii extension + Pcentral = fullfile(pp,Pcentral); + Pfsavg = fullfile(fsavgDir,[hemi '.sphere.freesurfer.gii']); + Pmask = fullfile(fsavgDir,[hemi '.mask']); + + + % check whether temporary resampled file already exists + if ~exist(Pvalue,'file') + + % resample values using warped sphere + cmd = sprintf('CAT_ResampleSurf ""%s"" ""%s"" ""%s"" ""%s"" ""%s"" ""%s""',Pcentral,Pspherereg,Pfsavg,Presamp,P,Pvalue); + err = cat_system(cmd,debug,0); + delete(Presamp); + + end + + % get surface values + %resamp.cdata = gifti(Pvalue); + resamp.cdata = cat_io_FreeSurfer('read_surf_data',Pvalue); + +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_main_gcut_DEV.m",".m","8581","178","function [Yb,Yl1] = cat_main_gcut_DEV(Ysrc,Yb,Ycls,Yl1,YMF,vx_vol,opt) +% This is an exclusive subfunction of cat_main. +% ______________________________________________________________________ +% +% gcut+: skull-stripping using graph-cut +% ---------------------------------------------------------------------- +% This routine use morphological, region-growing and graph-cut methods. +% It starts from the WM segment and grow for lower tissue intensities. +% Atlas knowledge is used to for separate handling of the cerebellum. +% Because its high frequency structures in combination with strong +% noise or other artifacts often lead to strong underestimations. +% +% There are 4 major parameters: +% gcutstr - strengh of skull-stripping with str=0 - more tissue, str=1 less tissue +% vx_res - resolution limit for skull-stripping (default 1.5) +% gcutCSF +% Especialy the second parameter controls many subparameters for +% different tissue thresholds, region-growing, closing and smoothing +% parameters. +% This routine have a strong relation to the previous estimated main +% partition map l1, and the blood vessel correction. Therefore, it is +% maybe useful to move it... +% +% [Yb,Yl1] = cat_main_gcut(Ysrc,Yb,Ycls,Yl1,YMF,vx_vol,opt) +% +% Yb .. updated brain mask +% Yl1 .. updated label map +% +% Ysrc .. anatomical image +% Yb .. initial brain mask +% Ycls .. SPM tissue classification +% Yl1 .. CAT atlas map +% YMF .. subcortical/ventricular regions (for filling in surf. recon.) +% vx_vol .. image resolutino +% opt .. further options +% +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + LAB = opt.LAB; + NS = @(Ys,s) Ys==s | Ys==s+1; + voli = @(v) (v ./ (pi * 4./3)).^(1/3); % volume > radius + brad = double(voli(sum(Yb(:)>0).*prod(vx_vol))); % distance and volume based brain radius (brad) + %noise = cat_stat_nanstd(Ym(cat_vol_morph(cat_vol_morph(Ym>0.95 & Ym<1.05,'lc',1),'e'))); + Yp0 = single(Ycls{3})/255/3 + single(Ycls{1})/255*2/3 + single(Ycls{2})/255; + rvol = [sum(round(Yp0(:)*3)==1), sum(round(Yp0(:)*3)==2), sum(round(Yp0(:)*3)==3)]/sum(round(Yp0(:)*3)>0); + vxd = max(1,1/mean(vx_vol)); + + %% set different paremeters to modifiy the stength of the skull-stripping + %gc.n = max(0.05,min(0.1,noise)); + % intensity parameter + gc.h = max(3.1,3.4 - 0.2*opt.gcutstr - 0.4*(opt.LASstr-0.5)); % 3.25, upper tissue intensity (WM vs. blood vessels) - higher > more ""tissue"" (blood vessels) + gc.l = 1.4 + 0.20*opt.gcutstr; % 1.50, lower tissue intensity (WM vs. blood vessels) - higher > more ""tissue"" (blood vessels) + gc.t = 1.3 - 0.20*opt.gcutstr; % 1.10, lower tissue intensity (WM vs. blood vessels) - higher > more ""tissue"" (blood vessels) + gc.o = 0.1 + 0.80*opt.gcutstr; % 0.50, BG tissue intensity (for high contrast CSF=BG=0!) - lower value > more ""tissue"" + % distance parameter + gc.d = brad*(8 - 6*opt.gcutstr)/mean(vx_vol); % 3; distance parameter for downcut - higher > more tissue + gc.c = (0.020 - 0.04*opt.gcutstr)*mean(vx_vol); % -0.015; growing parameter for downcut - higher > more tissue + gc.f = (brad/20 * opt.gcutstr * rvol(1)/0.10)/mean(vx_vol); % closing parameter - higher > more tissue ... 8 + % smoothing parameter + gc.s = 0.3 + 0.40*opt.gcutstr; % smoothing parameter - higher > less tissue + gc.ss = 1.0 + 2.00*opt.gcutstr; + gc.lc = round(vxd*(1.9 - opt.gcutstr)); + gc.lo = round(vxd*(0.9 + opt.gcutstr)); + + + if opt.verb, fprintf('\n'); end + stime = cat_io_cmd(' WM initialisation','g5','',opt.verb); dispc=1; + %% init: go to reduces resolution + [Ym,Yl1,YMF,BB] = cat_vol_resize({Ysrc,Yl1,YMF},'reduceBrain',vx_vol,round(4/mean(vx_vol)),Yb); + [Ywm,Ygm,Ycsf,Ymg,Yb] = cat_vol_resize({single(Ycls{2})/255,single(Ycls{1})/255,... + single(Ycls{3})/255,single(Ycls{5})/255,Yb},'reduceBrain',vx_vol,round(4/mean(vx_vol)),Yb); + Ymg = Ymg>0.05 & Ym<0.45; + + clear Ycls + Ybo=Yb; + + %% initial WM+ region + Yb=Ybo; + YHDr = cat_vol_morph(Yl1>20 | Yl1<=0,'e',vxd*2); + [Ybr,resT2] = cat_vol_resize(single(Yb),'reduceV',vx_vol,mean(vx_vol)*4,32); + Ybr = single(cat_vol_morph(Ybr>0,'e',brad/25)); + Ybr = cat_vol_resize(Ybr,'dereduceV',resT2)>0.5; + Yb = Yb>0.25 & Ym>2.5/3 & Ym2.5/3 & Ym1.9/3 & Ym<1.1)); % init further WM + spm_smooth(Yb,Yb,gc.ss./vx_vol); Yb = Yb>(gc.s-0.2); % remove small dots + Yb = single(cat_vol_morph(Yb>0,'lc')); + + + + %% region growing GM/WM (here we have to get all WM gyris!) + Ybs = Yb; + stime = cat_io_cmd(' GM region growing','g5','',opt.verb,stime); dispc=dispc+1; + Yb(~Yb & (YHDr | Ym<(min(2.1,gc.l+0.5))/3 | Ym>gc.h/3 | (Ywm + Ygm)<0.5))=nan; %clear Ywm Ygm; + [Yb1,YD] = cat_vol_downcut(Yb,Ym,max(0,0.01+gc.c)); % this have to be not to small... + Yb(isnan(Yb) | YD>gc.d*vxd*2)=0; Yb(Yb1>0 & YDgc.h/3) | Ymg)=nan; + [Yb1,YD] = cat_vol_downcut(Yb,Ym,-0.02+gc.c*0.5); + Yb(isnan(Yb) | YD>gc.d/2)=0; Yb(Yb1>0 & YD0.5; return + + %% region growing - add CSF + Yb(~Yb & (YHDr | Ym<1/3 | Ym>gc.h/3) | Ymg)=nan; + [Yb1,YD] = cat_vol_downcut(Yb,Ym,-0.04+gc.c*0.2); + Yb(isnan(Yb) | YD>gc.d/2)=0; Yb(Yb1>0 & YDgc.o/3)); + Yb = cat_vol_morph(Yb ,'labopen',gc.lo); + + + + %% region growing - add CSF regions + stime = cat_io_cmd(' CSF region growing','g5','',opt.verb,stime); dispc=dispc+1; + Ygr = cat_vol_grad(Ym,vx_vol); + Yb(~Yb & smooth3(cat_vol_morph(smooth3(Ym<0.75/3 | (Ym>1.25/3 & ~Yb) | ... + (Ygr>0.05 & ~Yb))>0.5,'lc',vxd*2) | Ymg )>0.5)=nan; + [Yb1,YD] = cat_vol_downcut(Yb,Ym,-0.02+gc.c); + Yb(isnan(Yb) | YD>gc.d/2)=0; Yb(Yb1>0 & YD0)=1; + for i=1:2, spm_smooth(Yb,Ybs,gc.ss./vx_vol); Yb(Ybs<(gc.s - 0.25))=0; end + Yb = single(Yb | YMF); + + % smooth / low dilated boundary + Ybs = single(Yb)+0; spm_smooth(Ybs,Ybs,2*gc.s./vx_vol); Yb = Yb>0.5 | (Ybs>(gc.s-0.1) & Ym + Yb = Yb | (cat_vol_morph(Yb ,'labclose',vxd*gc.f) & ... + Ym>=gc.o/3 & Ym<1.25/3 & ~Ymg & Ycsf>0.75); + Yb = single(cat_vol_morph(Yb,'o',max(1,min(3,4 - 0.2*gc.f* (rvol(1)/0.4) )))); + Yb = Yb | (cat_vol_morph(Yb ,'labclose',vxd) & Ym<1.1); + %% + Ybs = single(Yb)+0; spm_smooth(Ybs,Ybs,3./vx_vol); Yb = Yb>0.5 | (max(Yb,Ybs)>(gc.s-0.1) & Ym<0.4); % how wide + Ybs = single(Yb)+0; spm_smooth(Ybs,Ybs,2./vx_vol); Yb = max(Yb,Ybs)>0.4; % final smoothing + + %% + Yb = cat_vol_resize(Yb ,'dereduceBrain',BB)>0.5; + Yl1 = cat_vol_resize(Yl1 ,'dereduceBrain',BB); + + %% update Yl1 with Yb + Yl1(~Yb) = 0; + [tmp0,tmp1,Yl1] = cat_vbdist(single(Yl1),Yl1==0 & Yb); clear tmp0 tmp1; + + if opt.debug + cat_io_cmd(' ','','',opt.verb,stime); + else + cat_io_cmd(' ','','',opt.verb,stime); +% cat_io_cmd('cleanup',dispc,'',opt.verb); + end + +end","MATLAB" +"Neurology","ChristianGaser/cat12","ds.m",".m","39588","892","function varargout=ds(type,viewtype,DAR,varargin) +% type: viewtype type +% viewtype: [m|a|c] = [medial|axial|coronal] +% DAS: DataAspectRation (voxelsize) +% nf: ? +% ... +% +% ds('l1','',0,SEG,SLAB,55) +% ds('l2','',0,SEG,SLAB,5:10:160) +% ds('l2','',[1,1,1],TSEG,TSEG,SLAB,TSEG,TSEGM,55) +% ds('l3','',vx_vol,TSEGF,TSEG,TSEGF,ALAB,SLAB,SLABB,60) +%#ok<*TRYNC> + + if nargin==0, return; end; + if ndims(varargin{end})<=2, slice=varargin{end}; vols=nargin-4; + else slice=80; vols=nargin-3; + end + for va=1:numel(varargin), try varargin{va}=single(varargin{va}); end; end + + % rotate data... + if isempty(DAR), DAR=1; end + if numel(DAR)<2, DAR=repmat(DAR,1,3); end + if ~isempty(viewtype) + if viewtype==1 || ~isempty(strfind(viewtype,'m')) || ~isempty(strfind(viewtype,'medial')) + for vi=1:vols, varargin{vi}=shiftdim(varargin{vi},1); end; DAR=DAR([2 3 1]); + elseif viewtype==2 || ~isempty(strfind(viewtype,'a')) || ~isempty(strfind(viewtype,'axial')) + for vi=1:vols, varargin{vi}=shiftdim(varargin{vi},2); end; DAR=DAR([3 1 2]); + end + if ~isempty(strfind(viewtype,'+')), myzoom = 1+numel(strfind(viewtype,'+')); else myzoom = 1; end + else + myzoom = 1; + end + + if isstruct(varargin{1}) && isfield(varargin{1},'vertices') && isfield(varargin{1},'faces') + figure + + SX.vertices = varargin{1}.vertices; + SX.faces = varargin{1}.faces; + if numel(varargin)>1 && numel(varargin{2})==size(varargin{1}.vertices,1) + SX.facevertexcdata = varargin{2}; + elseif isfield(varargin{1},'cdata') + SX.facevertexcdata = varargin{1}.cdata; + elseif isfield(varargin{1},'facevertexcdata') + SX.facevertexcdata = varargin{1}.facevertexcdata; + end + + pSX = patch(SX); + axis equal off + set(pSX,'edgecolor','none') + if isfield(SX,'facevertexcdata') + set(pSX,'facecolor','interp'); + else + + end + camlight; + view(3); + colormap jet; + colorbar; + + return + end + + % figure properties + fhn = 'DisplaySlice';% if nf, fh=figure; else fh=gcf; end + fh = findobj('type','figure','tag',fhn); %,'name',fhn); + if ~isempty(strfind(type,'+')) + for fhi=1:numel(fh), set(fh(fhi),'tag',[get(fh(fhi),'tag') '0']); end + type = strrep(type,'+',''); + fh = []; + end + if ~isempty(fh) + figure(fh); + clf(fh); + else + mp = get(0,'MonitorPositions'); + if strfind(type,'sm') + fpos = min(mp(end,3:4),[800 900]); + else + fpos = min(mp(end,3:4),[1600 900]); + end + fpos = [(mp(end,3:4) - fpos)/2 fpos]; + figure('tag',fhn,'name',fhn,'Position',fpos,'color',[0.5 0.5 0.5],'PaperPositionMode','auto'); + try + clf(fhn); + end + end + + if numel(slice)>1, hold on; end + set(fh,'Color',[1 1 1]); + + + %varargin{1}(varargin{1}>3)=3; + %if nargin>2, varargin{2}=reduce_color(varargin{2}); end + + LAB = size(labelmap16,1); + [X,Y] = meshgrid(0.125/4:0.125/4:LAB,1:3); + + for s=slice(end:-1:1) + switch type + case {'ex'} + set(fh,'WindowStyle','normal','Visible','on'); + pos=get(fh,'Position'); + set(fh,'Position',[pos(1:2) size(varargin{1},2)*4 size(varargin{1},1)*4]); + imagesc(varargin{1}(:,:,s)); + cm=BCGWH; ss=2/(size(cm,1)+2); [X,Y] = meshgrid(1:ss:size(cm,1)+1,1:3); cm=interp2(1:size(cm,1),1:3,cm',X,Y)'; colormap(cm);caxis([0 2]); + axis equal off; set(gca,'Position',[0 0 1 1]); daspect(DAR); + case {'ex2'} + set(fh,'WindowStyle','normal','Visible','on'); + pos=get(fh,'Position'); + set(fh,'Position',[pos(1:2) size(varargin{1},2)*4 size(varargin{1},1)*4]); + image(ind2rgb( uint16(7+8*(min(1,varargin{1}(:,:,s))*3 + 4*varargin{2}(:,:,s)) ) , interp2(1:LAB,1:3,labelmap16',X,Y)')); axis equal off; daspect(DAR); + axis equal off; set(gca,'Position',[0 0 1 1]); daspect(DAR); + + case {'l1','label1'} + %set(fh,'WindowStyle','docked','Visible','on'); + image(ind2rgb( uint16(7+8*(min(1,varargin{1}(:,:,s))*3 + 4*varargin{2}(:,:,s)) ) , interp2(1:LAB,1:3,labelmap16',X,Y)')); axis equal off; daspect(DAR); + axis equal off; set(gca,'Position',[0 0 1 1]); daspect(DAR); + + case {'cat_pre_iscale'} + clf; set(fh,'WindowStyle','docked','Visible','on','color',[0 0 0]); + subplot('Position',[0.0 0.5 0.5 0.5]); image(ind2rgb( uint16(7+8*(min(1,varargin{1}(:,:,s))*3 + 4*varargin{2}(:,:,s)) ) , interp2(1:LAB,1:3,labelmap16',X,Y)')); axis equal off; daspect(DAR); + subplot('Position',[0.5 0.5 0.5 0.5]); image(ind2rgb( uint16(7+8*(min(1,varargin{3}(:,:,s))*3 + 4*varargin{4}(:,:,s)) ) , interp2(1:LAB,1:3,labelmap16',X,Y)')); axis equal off; daspect(DAR); + subplot('Position',[0.0 0.0 0.5 0.5]); imagesc(varargin{1}(:,:,s)); colormap(jet); caxis([0 4/3]); axis equal off; daspect(DAR); + subplot('Position',[0.5 0.0 0.5 0.5]); imagesc(varargin{3}(:,:,s)); colormap(jet); caxis([0 4/3]); axis equal off; daspect(DAR); + cm=myjet; ss=(1/3)/(size(cm,1)+2); [X,Y] = meshgrid(1:ss:size(cm,1),1:3); cm=interp2(1:size(cm,1),1:3,cm',X,Y)'; colormap(cm); + cb= colorbar; set(cb,'position',[0.48,0.1,0.02,0.3],'YTick',0:1/3:4/3,'YTickLabel', ... + {' BG',' ~CSF',' ~GM',' WM',' ~HM'},'FontWeight','bold','Fontsize',14,'FontName','Arial'); + labeltext = {'T with headmask:','T with brainmask:','T scalled by headmask:','T scalled by brainmask:'}; + labelpos = {[0.1 0.5 0.3 0.03],[0.6 0.5 0.3 0.03],[0.1 0.0 0.3 0.05],[0.6 0.0 0.3 0.05]}; + for tli=1:4 + annotation('textbox',labelpos{tli},'string',labeltext{tli},'color','white','FontWeight','bold',... + 'Fontsize',16,'FontName','Arial','HorizontalAlignment','center','EdgeColor','none'); + end + case {'x2'} + set(fh,'WindowStyle','docked','Visible','on'); + subplot('Position',[0 0.5 0.5 0.5]); imagesc(varargin{1}(:,:,s)); axis equal off; daspect(DAR); caxis 'auto'; + subplot('Position',[0.5 0.5 0.5 0.5]); imagesc(varargin{3}(:,:,s)); axis equal off; daspect(DAR); caxis 'auto'; + subplot('Position',[0 0 0.5 0.5]); imagesc(varargin{2}(:,:,s)); axis equal off; daspect(DAR); caxis 'auto'; + subplot('Position',[0.5 0.0 0.5 0.5]); imagesc(varargin{4}(:,:,s)); axis equal off; daspect(DAR); caxis 'auto'; + case {'d2sm'} + %set(fh,'WindowStyle','docked','Visible','on'); + subplot('Position',[0 0.5 1 0.5]); imagesc(varargin{1}(:,:,s)); colormap(jet); axis equal off; daspect(DAR); caxis([0 2]); zoom(myzoom); + subplot('Position',[0 0.0 1 0.5]); imagesc(varargin{2}(:,:,s)); colormap(jet); axis equal off; daspect(DAR); caxis([0 2]); zoom(myzoom); + cm=BCGWH; ss=2/(size(cm,1)+2); [X,Y] = meshgrid(1:ss:size(cm,1)+1,1:3); cm=interp2(1:size(cm,1),1:3,cm',X,Y)'; colormap(cm); + case {'d2smns'} % no scaling + %set(fh,'WindowStyle','docked','Visible','on'); + data = cat(3,varargin{1}(:,:,s),varargin{2}(:,:,s)); data = data(:); data(isnan(data) | isinf(data) | data>10e37 | data<-10e37) = []; + scale = [ median(data) - 2*std(data) - eps , median(data) + 2*std(data) + eps ]; + subplot('Position',[0 0.5 1 0.5]); imagesc(varargin{1}(:,:,s)); axis equal off; daspect(DAR); caxis(scale); zoom(myzoom); + subplot('Position',[0 0.0 1 0.5]); imagesc(varargin{2}(:,:,s)); axis equal off; daspect(DAR); caxis(scale); zoom(myzoom); + %cm=BCGWH; ss=2/(size(cm,1)+2); [X,Y] = meshgrid(1:ss:size(cm,1)+1,1:3); cm=interp2(1:size(cm,1),1:3,cm',X,Y)'; colormap(cm); + case {'d2','default2'} + %set(fh,'WindowStyle','docked','Visible','on'); + subplot('Position',[0 0.5 0.5 0.5]); imagesc(varargin{1}(:,:,s)); colormap(jet); caxis([0 3]); axis equal off; daspect(DAR); caxis([0 2]); zoom(myzoom); + subplot('Position',[0.5 0.5 0.5 0.5]); imagesc(varargin{3}(:,:,s)); colormap(jet); caxis([0 3]); axis equal off; daspect(DAR); caxis([0 2]); zoom(myzoom); + subplot('Position',[0 0 0.5 0.5]); imagesc(varargin{2}(:,:,s)); colormap(jet); caxis([0 3]); axis equal off; daspect(DAR); caxis([0 2]); zoom(myzoom); + subplot('Position',[0.5 0.0 0.5 0.5]); imagesc(varargin{4}(:,:,s)); colormap(jet); caxis([0 3]); axis equal off; daspect(DAR); caxis([0 2]); zoom(myzoom); + cm=BCGWH; ss=2/(size(cm,1)+2); [X,Y] = meshgrid(1:ss:size(cm,1)+1,1:3); cm=interp2(1:size(cm,1),1:3,cm',X,Y)'; colormap(cm); + case {'l2sm'} + [X,Y] = meshgrid(0.125:0.125:LAB,1:3); + %set(fh,'WindowStyle','docked','Visible','on'); + subplot('Position',[0 0.5 1 0.5]); image(ind2rgb( uint16(7+8*(min(1,varargin{1}(:,:,s))*3 + 4*varargin{2}(:,:,s)) ) , interp2(1:LAB,1:3,labelmap16',X,Y)')); axis equal off; daspect(DAR); zoom(myzoom); + subplot('Position',[0 0.0 1 0.5]); image(ind2rgb( uint16(7+8*(min(1,varargin{1}(:,:,s))*3 + 4*varargin{3}(:,:,s)) ) , interp2(1:LAB,1:3,labelmap16',X,Y)')); axis equal off; daspect(DAR); zoom(myzoom); + cm=BCGWH; ss=2/(size(cm,1)+2); [X,Y] = meshgrid(1:ss:size(cm,1)+1,1:3); cm=interp2(1:size(cm,1),1:3,cm',X,Y)'; colormap(cm); + case {'l2','label2'} + [X,Y] = meshgrid(0.125:0.125:LAB,1:3); + %set(fh,'WindowStyle','docked','Visible','on'); + subplot('Position',[0 0.5 0.5 0.5]); image(ind2rgb( uint16(7+8*(min(1,varargin{1}(:,:,s))*3 + 4*varargin{2}(:,:,s)) ) , interp2(1:LAB,1:3,labelmap16',X,Y)')); axis equal off; daspect(DAR); zoom(myzoom); + subplot('Position',[0.5 0.5 0.5 0.5]); imagesc(varargin{3}(:,:,s)); caxis([0 2]); axis equal off; daspect(DAR); zoom(myzoom); + subplot('Position',[0 0 0.5 0.5]); image(ind2rgb( uint16(7+8*(2.5 + 4*varargin{2}(:,:,s)) ) , interp2(1:LAB,1:3,labelmap16',X,Y)' )); axis equal off; daspect(DAR); zoom(myzoom); + subplot('Position',[0.5 0.0 0.5 0.5]); imagesc(varargin{4}(:,:,s)); caxis([0 2]); axis equal off; daspect(DAR); zoom(myzoom); + cm=BCGWH; ss=2/(size(cm,1)+2); [X,Y] = meshgrid(1:ss:size(cm,1)+1,1:3); cm=interp2(1:size(cm,1),1:3,cm',X,Y)'; colormap(cm); + case {'l2x','label2x'} + [X,Y] = meshgrid(0.125:0.125:LAB,1:3); + set(fh,'WindowStyle','docked','Visible','on'); + subplot('Position',[0 0.5 0.5 0.5]); image(ind2rgb( uint16(7+8*(min(1,varargin{1}(:,:,s))*3 + 4*varargin{2}(:,:,s)) ) , interp2(1:LAB,1:3,labelmap16',X,Y)')); axis equal off; daspect(DAR); + subplot('Position',[0.5 0.5 0.5 0.5]); imagesc(varargin{4}(:,:,s)); caxis([0 2]); axis equal off; daspect(DAR); + subplot('Position',[0 0 0.5 0.5]); imagesc(varargin{3}(:,:,s)); caxis([0 2]); axis equal off; daspect(DAR); + subplot('Position',[0.5 0.0 0.5 0.5]); imagesc(varargin{5}(:,:,s)); caxis([0 2]); axis equal off; daspect(DAR); + cm=BCGWH; ss=2/(size(cm,1)+2); [X,Y] = meshgrid(1:ss:size(cm,1)+1,1:3); cm=interp2(1:size(cm,1),1:3,cm',X,Y)'; colormap(cm); + case {'l3','label3'} + %[X,Y] = meshgrid(0.125:0.125:64,1:3); + set(fh,'WindowStyle','docked','Visible','on'); + % top row + subplot('Position',[0/3 2/3 1/3 1/3]); imagesc(varargin{1}(:,:,s)); colormap(jet); caxis([0 3]); axis equal off; daspect(DAR); + subplot('Position',[1/3 2/3 1/3 1/3]); imagesc(varargin{2}(:,:,s)); colormap(jet); caxis([0 3]); axis equal off; daspect(DAR); + subplot('Position',[2/3 2/3 1/3 1/3]); imagesc(varargin{3}(:,:,s)); colormap(jet); caxis([0 3]); axis equal off; daspect(DAR); + + % middle row + subplot('Position',[0/3 1/3 1/3 1/3]); image(ind2rgb( uint16(7+8*(varargin{1}(:,:,s) + 4*varargin{4}(:,:,s)) ) , interp2(1:LAB,1:3,labelmap16',X,Y)')); axis equal off; daspect(DAR); + subplot('Position',[1/3 1/3 1/3 1/3]); image(ind2rgb( uint16(7+8*(varargin{2}(:,:,s) + 4*varargin{5}(:,:,s)) ) , interp2(1:LAB,1:3,labelmap16',X,Y)')); axis equal off; daspect(DAR); + subplot('Position',[2/3 1/3 1/3 1/3]); image(ind2rgb( uint16(7+8*(varargin{3}(:,:,s) + 4*varargin{6}(:,:,s)) ) , interp2(1:LAB,1:3,labelmap16',X,Y)')); axis equal off; daspect(DAR); + + % bottom row + subplot('Position',[0/3 0/3 1/3 1/3]); image(ind2rgb( uint16(7+8*(2.5 + 4*varargin{4}(:,:,s)) ) , interp2(1:LAB,1:3,labelmap16',X,Y)' )); axis equal off; daspect(DAR); + subplot('Position',[1/3 0/3 1/3 1/3]); image(ind2rgb( uint16(7+8*(2.5 + 4*varargin{5}(:,:,s)) ) , interp2(1:LAB,1:3,labelmap16',X,Y)' )); axis equal off; daspect(DAR); + subplot('Position',[2/3 0/3 1/3 1/3]); image(ind2rgb( uint16(7+8*(2.5 + 4*varargin{6}(:,:,s)) ) , interp2(1:LAB,1:3,labelmap16',X,Y)' )); axis equal off; daspect(DAR); + case {'d3','default3'} + fh = figure(912); + set(fh,'WindowStyle','docked','Visible','on'); + + if nargin<=13 + % top row + subplot('Position',[0/3 2/3 1/3 1/3]); imagesc(varargin{1}(:,:,s)); caxis([0 1]); axis equal off; daspect(DAR); + subplot('Position',[1/3 2/3 1/3 1/3]); imagesc(varargin{2}(:,:,s)); caxis([0 3]); axis equal off; daspect(DAR); + subplot('Position',[2/3 2/3 1/3 1/3]); imagesc(varargin{3}(:,:,s)); caxis([0 3]); axis equal off; daspect(DAR); + + % middle row + subplot('Position',[0/3 1/3 1/3 1/3]); imagesc(varargin{4}(:,:,s)); caxis([0 3]); axis equal off; daspect(DAR); + subplot('Position',[1/3 1/3 1/3 1/3]); imagesc(varargin{5}(:,:,s)); caxis([0 3]); axis equal off; daspect(DAR); + subplot('Position',[2/3 1/3 1/3 1/3]); imagesc(varargin{6}(:,:,s)); caxis([0 3]); axis equal off; daspect(DAR); + + % bottom row + subplot('Position',[0/3 0/3 1/3 1/3]); imagesc(varargin{7}(:,:,s)); caxis([0 3]); axis equal off; daspect(DAR); + subplot('Position',[1/3 0/3 1/3 1/3]); imagesc(varargin{8}(:,:,s)); caxis([0 3]); axis equal off; daspect(DAR); + subplot('Position',[2/3 0/3 1/3 1/3]); imagesc(varargin{9}(:,:,s)); caxis([0 3]); axis equal off; daspect(DAR); + else + % top row + subplot('Position',[0/4 2/3 1/4 1/3]); imagesc(varargin{1}(:,:,s)); caxis([0 1]); axis equal off; daspect(DAR); + subplot('Position',[1/4 2/3 1/4 1/3]); imagesc(varargin{4}(:,:,s)); caxis([0 3]); axis equal off; daspect(DAR); + subplot('Position',[2/4 2/3 1/4 1/3]); imagesc(varargin{7}(:,:,s)); caxis([0 3]); axis equal off; daspect(DAR); + subplot('Position',[3/4 2/3 1/4 1/3]); imagesc(varargin{10}(:,:,s)); caxis([0 3]); axis equal off; daspect(DAR); + + % middle row + subplot('Position',[0/4 1/3 1/4 1/3]); imagesc(varargin{2}(:,:,s)); caxis([0 3]); axis equal off; daspect(DAR); + subplot('Position',[1/4 1/3 1/4 1/3]); imagesc(varargin{5}(:,:,s)); caxis([0 3]); axis equal off; daspect(DAR); + subplot('Position',[2/4 1/3 1/4 1/3]); imagesc(varargin{8}(:,:,s)); caxis([0 3]); axis equal off; daspect(DAR); + subplot('Position',[3/4 1/3 1/4 1/3]); imagesc(varargin{11}(:,:,s)); caxis([0 3]); axis equal off; daspect(DAR); + + % bottom row + subplot('Position',[0/4 0/3 1/4 1/3]); imagesc(varargin{3}(:,:,s)); caxis([0 3]); axis equal off; daspect(DAR); + subplot('Position',[1/4 0/3 1/4 1/3]); imagesc(varargin{6}(:,:,s)); caxis([0 3]); axis equal off; daspect(DAR); + subplot('Position',[2/4 0/3 1/4 1/3]); imagesc(varargin{9}(:,:,s)); caxis([0 3]); axis equal off; daspect(DAR); + subplot('Position',[3/4 0/3 1/4 1/3]); imagesc(varargin{12}(:,:,s)); caxis([0 3]); axis equal off; daspect(DAR); + + end + + cm = colormap(jet); + colormap(cm); + set(fh,'Color',cm(1,:)); + case {'BBC','bbc'} + fh=figure(10); clf; colormap(myjet); caxis([0,1.28]); %docked=get(fh,'WindowStyle'); + resfactor = 1; + imgsize = [2560 1440]*resfactor; + set(fh,'Color',ones(1,3),'Visible','off','InvertHardcopy','off', ... + 'PaperUnits','centimeters','PaperPositionMode','auto', ... + 'WindowStyle','normal','Position',[1 1 imgsize]); + + nvols=0; for ni=1:numel(varargin), if ndims(varargin{ni})==3 && all(size(varargin{ni})>32), nvols=nvols+1; end; end + colw = 900*resfactor; + cols = [colw colw imgsize(1)-(2*colw)]/imgsize(1); + rowh = 1/nvols; % divide by number of rows + + % colume 1 (images): + cm=BCGWH; ss=2/(size(cm,1)+2); [X,Y] = meshgrid(1:ss:size(cm,1)+1,1:3); cm=interp2(1:size(cm,1),1:3,cm',X,Y)'; colormap(cm); + for ni=1:nvols + if ndims(varargin{ni})==3 && all(size(varargin{ni})>32) + subplotvol([cols(1)*0/3 (nvols-ni)*rowh cols(1)/3 rowh],varargin{ni},[],1,DAR); + subplotvol([cols(1)*1/3 (nvols-ni)*rowh cols(1)/3 rowh],varargin{ni},[],2,DAR); + subplotvol([cols(1)*2/3 (nvols-ni)*rowh cols(1)/3 rowh],varargin{ni},[],3,DAR); + end + end + + % colume 2 (suraces): + %WM surface + ni=ni+1; + subplotsurf([cols(1)+cols(2)*0/3 2/4 cols(2)/3 1/4],varargin{ni},[0 2],[ 1 0 0],DAR); + subplotsurf([cols(1)+cols(2)*1/3 2/4 cols(2)/3 1/4],varargin{ni},[0 2],[ 0 1 0],DAR); + subplotsurf([cols(1)+cols(2)*2/3 2/4 cols(2)/3 1/4],varargin{ni},[0 2],[ 0 0 1],DAR); + subplotsurf([cols(1)+cols(2)*0/3 3/4 cols(2)/3 1/4],varargin{ni},[0 2],[-1 0 0],DAR); + subplotsurf([cols(1)+cols(2)*1/3 3/4 cols(2)/3 1/4],varargin{ni},[0 2],[ 0 -1 0],DAR); + subplotsurf([cols(1)+cols(2)*2/3 3/4 cols(2)/3 1/4],varargin{ni},[0 2],[ 0 0 -1],DAR); + + % block 1: WM surface + ni=ni+1; + subplotsurf([cols(1)+cols(2)*0/3 0/4 cols(2)/3 1/4],varargin{ni},[0 2],[ 1 0 0],DAR); + subplotsurf([cols(1)+cols(2)*1/3 0/4 cols(2)/3 1/4],varargin{ni},[0 2],[ 0 1 0],DAR); + subplotsurf([cols(1)+cols(2)*2/3 0/4 cols(2)/3 1/4],varargin{ni},[0 2],[ 0 0 1],DAR); + subplotsurf([cols(1)+cols(2)*0/3 1/4 cols(2)/3 1/4],varargin{ni},[0 2],[-1 0 0],DAR); + subplotsurf([cols(1)+cols(2)*1/3 1/4 cols(2)/3 1/4],varargin{ni},[0 2],[ 0 -1 0],DAR); + subplotsurf([cols(1)+cols(2)*2/3 1/4 cols(2)/3 1/4],varargin{ni},[0 2],[ 0 0 -1],DAR); + + % block 4: values + + opt = varargin{end}; spaces=20; + + [p,f,e]=fileparts(opt.hdr.fname); [h2,h]=fileparts(p); h=strrep([h filesep f e],'_','\_'); clear e h2 f; + txt = {['\fontsize{' num2str(18*resfactor,'%d') '}\color{black}{\fontname{Helvetica}\bfBBC Results:}'] ... + sprintf(sprintf('%% %ds %%s',spaces),'Subject:',h)... + sprintf(sprintf('%% %ds%% 4.2fx%%4.2fx%%4.2f mm^3 (V=%%4.2f|Isotropy=%%4.2f)',spaces),... + 'Resolution',DAR,opt.vol.abs.isotropy, opt.vol.vxvol) ... + '' ... + sprintf(sprintf('%% %ds %% 6s %% 6s %% 6s %% 6s %% 6s',spaces), 'NOISE (local SD):','BG','CSF','GM','WM','all') ... + sprintf(sprintf('%% %ds %% 6.3f %% 6.3f %% 6.3f %% 6.3f %% 6.3f',spaces),'original:',opt.noise.original) ... + sprintf(sprintf('%% %ds %% 6.3f %% 6.3f %% 6.3f %% 6.3f %% 6.3f',spaces),'corrected:',opt.noise.corrected) ... + '' ... + '' ... + sprintf(sprintf('%% %ds %% 6s %% 6s %% 6s %% 6s',spaces),'INTENSITY:','BG','CSF','GM','WM') ... + sprintf(sprintf('%% %ds %% 6.3f %% 6.3f %% 6.3f %% 6.3f',spaces),'mean:',opt.intensity) ... + '' ... + '' ... + sprintf(sprintf('%% %ds %% 6s %% 6s %% 6s %% 6s %% 6s',spaces),'BIAS (SD):','BG','CSF','GM','WM','all') ... + sprintf(sprintf('%% %ds %% 6.3f %% 6.3f %% 6.3f %% 6.3f %% 6.3f',spaces),'original:',opt.bias.std_T) ... + sprintf(sprintf('%% %ds %% 6.3f %% 6.3f %% 6.3f %% 6.3f %% 6.3f',spaces),'corrected:',opt.bias.std_TBC) ... + sprintf(sprintf('%% %ds %% 6s %% 6s %% 6s %% 6s %% 6s',spaces),'BIAS (UNIFORMEITY):','BG','CSF','GM','WM','all') ... + sprintf(sprintf('%% %ds %% 6.3f %% 6.3f %% 6.3f %% 6.3f %% 6.3f',spaces),'original:',opt.bias.uniformeity_T)... + sprintf(sprintf('%% %ds %% 6.3f %% 6.3f %% 6.3f %% 6.3f %% 6.3f',spaces),'corrected:',opt.bias.uniformeity_TBC)... + sprintf(sprintf('%% %ds %% 6s %% 6s %% 6s %% 6s %% 6s',spaces),'BIAS (ENTROPIE):','BG','CSF','GM','WM','all') ... + sprintf(sprintf('%% %ds %% 6.3f %% 6.3f %% 6.3f %% 6.3f %% 6.3f',spaces),'original:',opt.bias.entropy_T)... + sprintf(sprintf('%% %ds %% 6.3f %% 6.3f %% 6.3f %% 6.3f %% 6.3f',spaces),'corrected:',opt.bias.entropy_TBC)... + '' ... + '' ... + sprintf(sprintf('%% %ds %% 6s %% 6s %% 6s %% 6s %% 6s',spaces),'VOLUME (cm^3):','BG','CSF','GM','WM','WM+') ... + sprintf(sprintf('%% %ds %% 6.0f %% 6.0f %% 6.0f %% 6.0f %% 6.0f',spaces),'absolute Volume:',opt.vol.abs.tissue(1:5))... + sprintf(sprintf('%% %ds %% 6.2f%%%% %% 6.2f%%%% %% 6.2f%%%% %% 6.2f%%%% %% 6.2f%%%% ',spaces),... + 'relative Volume:',opt.vol.rel.tissue(1:5)*100)... + '' ... + sprintf(sprintf('%% %ds %% 6s %% 6s %% 6s',spaces), 'VOLUME (cm^3):','PVE CG','PVE GW','PVE') ... + sprintf(sprintf('%% %ds %% 6.0f %% 6.0f %% 6.0f',spaces),'absolute Volume:',opt.vol.abs.PVE)... + sprintf(sprintf('%% %ds %% 6.2f%%%% %% 6.2f%%%% %% 6.2f%%%%',spaces),'relative Volume:',opt.vol.rel.PVE*100)... + '' ... + sprintf(sprintf('%% %ds %% 6s %% 6s %% 6s',spaces), 'VOLUME (cm^3):','CGM','GWM','CGWM') ... + sprintf(sprintf('%% %ds %% 6.0f %% 6.0f %% 6.0f',spaces), 'absolute Volume:',opt.vol.abs.subtissue)... + sprintf(sprintf('%% %ds %% 6.2f%%%% %% 6.2f%%%% %% 6.2f%%%%',spaces),'relative Volume:',opt.vol.rel.subtissue*100) ... + '' ... + sprintf(sprintf('%% %ds%% 10s %% 10s %% 10s %% 10s',spaces), 'SPECIAL:','Blurring','Sampling','Gradient','Contrast') ... + sprintf(sprintf('%% %ds%% 10.3f %% 10.3f %% 10.3f %% 10.3f',spaces),'',... + opt.vol.abs.blurring, opt.vol.abs.sampling, opt.vol.abs.gradient,opt.vol.abs.contrast) ... + '' ... + }; + + annotation('textbox',[sum(cols(1:2)) 0 cols(3) 1],'string',txt,'FontName','Courier','EdgeColor','none',... + 'Margin',20,'BackgroundColor',ones(1,3)); + + + [p,f]=fileparts(opt.hdr.fname); + print(fh,'-zbuffer','-r100','-dpng',sprintf('%s%s%s%s',p,filesep,f,'.png')); + set(fh,'WindowStyle','docked','Visible','on'); + close(fh); + otherwise + colorbar; + end + + + end + + if numel(slice)>1, hold off; end + + if nargout==1, varargout{1}=fh; end +end +function D=reduce_color(C) + CT = {[0,11,12,21,22,17,18],0; + 19 ,9; + 20 ,10; + 15 ,11; + 16 ,12}; + D=-ones(size(C),'single'); + for i=1:size(CT,1) + M=zeros(size(C),'single'); + for j=1:numel(CT{i,1}), M(C==CT{i,1}(j))=1; end + D(M==1)=CT{i,2}; + end + D(D==-1)=C(D==-1); +end +function subplotsurf(position,surf,caxisval,sideview,DAR) + subplot('Position',position); + p=patch(surf); set(p,'FaceColor','interp','EdgeColor','none','FaceLighting','phong'); + axis equal off; daspect(DAR); caxis(caxisval); + view(sideview); camlight +end +function subplotvol(position,vol,lab,sideview,DAR) + subplot('Position',position); + if sideview==1 + s=floor(size(vol,3)*5/9); + vol=vol(:,:,s); + if ~isempty(lab), lab=lab(:,:,s); end + elseif sideview==2 + s=floor(size(vol,1)*5/9); + vol=shiftdim(vol,1); vol=vol(:,:,s); vol=rot90(vol,1); + if ~isempty(lab), lab=shiftdim(lab,1); lab=lab(:,:,s); lab=rot90(lab,1); end + DAR=[DAR(3),DAR(2) 1]; + elseif sideview==3 + s=floor(size(vol,2)*5/9); + vol=shiftdim(vol,2); vol=vol(:,:,s); vol=rot90(vol,2); + if ~isempty(lab), lab=shiftdim(lab,2); lab=lab(:,:,s); lab=rot90(lab,2); end + DAR=[DAR(3),DAR(1),1]; + end +% [X,Y] = meshgrid(0.125:0.125:64,1:3); + if ~isempty(lab), + image(ind2rgb( uint16(7+8*(vol + 4*lab) ) , interp2(1:LAB,1:3,labelmap16',X,Y)')); + else + imagesc(vol); caxis([0,2]); + end + axis equal off; daspect(DAR); +end +function LM=WBGRWM +LM = [ + 1.0000 1.0000 1.0000 % 0 + 1.0000 1.0000 1.0000 % 0 + 0.6275 0.8196 0.9255 % + 0.2510 0.6392 0.8549 % C + 0 0 1.0000 + 0 1.0000 0 % G + 1.0000 0 0 + 1.0000 1.0000 1.0000 % W + 0.4784 0.0627 0.8941 + 1.0000 0 0 % + 1.0000 0 0 + 1.0000 0 0 % + 1.0000 0 0 + 1.0000 0 0 % + ]; +end +function LM=BCGWH +LM = [ + 1.0000 1.0000 1.0000 % B + 0.9196 0.9804 1.0000 + 0.6784 0.9216 1.0000 + 0.2510 0.6392 0.8549 % C + 0.0667 0.3843 0.4863 + 0 0.4980 0.1843 + 0 1.0000 0 % G + 1.0000 1.0000 0 + 1.0000 0.6000 0 + 0.7569 0 0 % W + 0.8784 0.4000 0.5000 + 1.0000 0.6500 0.7843 + 1.0000 0.8800 0.9200 % H + 1.0000 1.0000 1.0000 + 0.9273 0.9273 0.9273 + 0.8545 0.8545 0.8545 + 0.8545 0.8545 0.8545 + 0.8545 0.8545 0.8545 + ]; +end + +function LM=labelmap16 +LM = [... % R G B + 0 0 0;%0 BG + 0.1 0.1 0.1; + 0.2 0.2 0.2; + 0.3 0.3 0.3; + 0 0 0;%1 CT LEFT (leicht blau) + 0.1 0.1 0.2; + 0.3 0.5 0.6; + 0.9 0.9 1.0; + 0 0 0;%2 CT RIGHT (leicht rot) + 0.2 0.1 0.1; + 0.7 0.5 0.6; + 1.0 0.9 0.9; + 0 0 0;%3 CB LEFT + 0.7490 0 0.7490; + 0.8055 0.2600 0.7843; + 0.8620 0.5200 0.8196; + 0 0 0;%4 CB RIGHT + 0.80 0.0627 0.8941; + 0.90 0.3824 0.9471; + 1.00 0.7020 1.0000; + 0 0 0;%5 BG LEGT + 0.8706 0.4902 0; + 0.9353 0.7196 0.4333; + 1.0000 0.9490 0.8667; + 0 0 0;%6 BG RIGHT + 1.0000 0.5000 0.3000; + 1.0000 0.7500 0.6000; + 1.0000 0.9686 0.9216; + 0.2000 0 0;%7 BV LEFT (red) + 0.6000 0 0; + 0.8000 0 0; + 1.0000 0 0; + 0 0 0;%8 BV RIGHT (red) + 0.6000 0 0; + 0.8000 0 0; + 1.0000 0 0; + 0 0 0;%9 Hypocampus LEFT + 0.6000 0.6000 0; + 0.8000 0.8000 0; + 1.0000 1.0000 0; + 0 0 0;%10 Hypocampus RIGHT + 0.3150 0.3229 0; + 0.6301 0.6458 0; + 0.9451 0.9686 0; + 0 0.1 0.2222;%11 Ventricle LEFT + 0 0.2 0.4444; + 0 0.3 0.6666; + 0 0.4 0.8888; + 0.1 0 0.2222;%12 Ventricle RIGHT + 0.2 0 0.4444; + 0.3 0 0.6666; + 0.4 0 0.8888; + 0 0 0;%13 Midbrain & Brainstem RIGHT + 0.3333 0.2 0.2; + 0.6667 0.4 0.4; + 1.0000 0.6 0.6; + 0 0 0;%14 Midbrain & Brainstem LEFT + 0.2 0.3333 0.2; + 0.4 0.6667 0.4; + 0.6 1.0000 0.6; + 0 0.1 0.2222;%15 Ventricle LEFT + 0 0.2 0.4444; + 0 0.3 0.6666; + 0 0.4 0.8888; + 0.0 0 0.1111;%12 Ventricle RIGHT + 0.15 0.15 0.4444; + 0.30 0.30 0.6666; + 0.45 0.45 0.9999; + 0 0.1 0.2222;%15 Ventricle LEFT + 0 0.2 0.4444; + 0 0.3 0.6666; + 0 0.4 0.8888; + 0.1 0 0.2222;%18 no Ventricle RIGHT + 0.2 0 0.4444; + 0.3 0 0.6666; + 0.4 0 0.8888; + 0 0 0;%19 Hypocampus LEFT + 0.7490 0.7490 0; + 0.8745 0.8745 0; + 1.0000 1.0000 0; + 0 0 0;%20 Hypocampus RIGHT + 0.3150 0.3229 0; + 0.6301 0.6458 0; + 0.9451 0.9686 0; + 0 0 0;%21 + 0.2850 0.2340 0.3333; + 0.5699 0.4680 0.6667; + 0.8549 0.7020 1.0000; + 0 0 0;%22 + 0.2850 0.2340 0.3333; + 0.5699 0.4680 0.6667; + 0.8549 0.7020 1.0000; + 0 0 0;%1 CT LEFT (leicht blau) + 0.3 0.7 0.5; + 0.4 0.8 0.8; + 0.5 0.9 0.9; + 0 0 0;%2 CT RIGHT (leicht rot) + 0.6 0.4 0.5; + 0.7 0.5 0.6; + 0.8 0.6 0.7;]; + LM(LM<0)=0; LM(LM>1)=1; +end +function LM=myjet + LM = [ + 0 0 0 + 0 0.0667 1.0000 + 0 1.0000 1.0000 + 0 1.0000 0 + 1.0000 1.0000 0 + 1.0000 0 0 + 0.8471 0.1608 0 + 0.9973 0.0028 0.9825 + ]; +end +function LM=myjet2 + LM=[ + 0.8627 0.8627 0.8627; + 0.7669 0.7743 0.8780; + 0.6710 0.6858 0.8932; + 0.5752 0.5974 0.9085; + 0.4793 0.5089 0.9237; + 0.3834 0.4205 0.9390; + 0.2876 0.3320 0.9542; + 0.1917 0.2436 0.9695; + 0.0959 0.1551 0.9847; + 0 0.0667 1.0000; + 0 0.1600 1.0000; + 0 0.2533 1.0000; + 0 0.3467 1.0000; + 0 0.4400 1.0000; + 0 0.5333 1.0000; + 0 0.6267 1.0000; + 0 0.7200 1.0000; + 0 0.8133 1.0000; + 0 0.9067 1.0000; + 0 1.0000 1.0000; + 0 1.0000 0.9000; + 0 1.0000 0.8000; + 0 1.0000 0.7000; + 0 1.0000 0.6000; + 0 1.0000 0.5000; + 0 1.0000 0.4000; + 0 1.0000 0.3000; + 0 1.0000 0.2000; + 0 1.0000 0.1000; + 0 1.0000 0; + 0.1000 1.0000 0; + 0.2000 1.0000 0; + 0.3000 1.0000 0; + 0.4000 1.0000 0; + 0.5000 1.0000 0; + 0.6000 1.0000 0; + 0.7000 1.0000 0; + 0.8000 1.0000 0; + 0.9000 1.0000 0; + 1.0000 1.0000 0; + 1.0000 0.9000 0; + 1.0000 0.8000 0; + 1.0000 0.7000 0; + 1.0000 0.6000 0; + 1.0000 0.5000 0; + 1.0000 0.4000 0; + 1.0000 0.3000 0; + 1.0000 0.2000 0; + 1.0000 0.1000 0; + 1.0000 0 0; + 0.9847 0.0161 0; + 0.9694 0.0322 0; + 0.9541 0.0482 0; + 0.9388 0.0643 0; + 0.9235 0.0804 0; + 0.9082 0.0965 0; + 0.8929 0.1125 0; + 0.8776 0.1286 0; + 0.8624 0.1447 0; + 0.8471 0.1608 0; + 0.8853 0.1206 0.2500; + 0.9235 0.0804 0.5000; + 0.9618 0.0402 0.7500; + 1.0000 0 1.0000; + ]; +end +function LM=myjet4 +LM = [ + 1.0000 1.0000 1.0000 + 0.9799 0.9951 1.0000 + 0.9598 0.9902 1.0000 + 0.9397 0.9853 1.0000 + 0.9196 0.9804 1.0000 + 0.8593 0.9657 1.0000 + 0.7990 0.9510 1.0000 + 0.7387 0.9363 1.0000 + 0.6784 0.9216 1.0000 + 0.5716 0.8510 0.9637 + 0.4647 0.7804 0.9275 + 0.3578 0.7098 0.8912 + 0.2510 0.6392 0.8549 + 0.2049 0.5755 0.7627 + 0.1588 0.5118 0.6706 + 0.1127 0.4480 0.5784 + 0.0667 0.3843 0.4863 + 0.0500 0.4127 0.4108 + 0.0333 0.4412 0.3353 + 0.0167 0.4696 0.2598 + 0 0.4980 0.1843 + 0 0.6235 0.1382 + 0 0.7490 0.0922 + 0 0.8745 0.0461 + 0 1.0000 0 + 0.2500 1.0000 0 + 0.5000 1.0000 0 + 0.7500 1.0000 0 + 1.0000 1.0000 0 + 1.0000 0.9000 0 + 1.0000 0.8000 0 + 1.0000 0.7000 0 + 1.0000 0.6000 0 + 0.9500 0.4500 0 + 0.9000 0.3000 0 + 0.8500 0.1500 0 + 0.8000 0 0 + 0.8500 0.1500 0.1961 + 0.9000 0.3000 0.3922 + 0.9500 0.4500 0.5882 + 1.0000 0.6000 0.7843 + 0.8696 0.4657 0.8118 + 0.7392 0.3314 0.8392 + 0.6088 0.1971 0.8667 + 0.4784 0.0627 0.8941 + 0.4461 0.0971 0.7529 + 0.4137 0.1314 0.6118 + 0.3814 0.1657 0.4706 + 0.3490 0.2000 0.3294 + 0.3258 0.1867 0.3075 + 0.3025 0.1733 0.2855 + 0.2792 0.1600 0.2635 + 0.2559 0.1467 0.2416 + 0.2327 0.1333 0.2196 + 0.2094 0.1200 0.1976 + 0.1861 0.1067 0.1757 + 0.1629 0.0933 0.1537 + 0.1396 0.0800 0.1318 + 0.1163 0.0667 0.1098 + 0.0931 0.0533 0.0878 + 0.0698 0.0400 0.0659 + 0.0465 0.0267 0.0439 + 0.0233 0.0133 0.0220 + 0 0 0 + ]; +end +function LM=myjet3 +LM = [ + 1.0000 1.0000 1.0000 + 0.9799 0.9951 1.0000 + 0.9598 0.9902 1.0000 + 0.9397 0.9853 1.0000 + 0.9196 0.9804 1.0000 + 0.8593 0.9657 1.0000 + 0.7990 0.9510 1.0000 + 0.7387 0.9363 1.0000 + 0.6784 0.9216 1.0000 + 0.5716 0.8510 0.9637 + 0.4647 0.7804 0.9275 + 0.3578 0.7098 0.8912 + 0.2510 0.6392 0.8549 + 0.2049 0.5755 0.7627 + 0.1588 0.5118 0.6706 + 0.1127 0.4480 0.5784 + 0.0667 0.3843 0.4863 + 0.0500 0.4127 0.4108 + 0.0333 0.4412 0.3353 + 0.0167 0.4696 0.2598 + 0 0.4980 0.1843 + 0 0.6235 0.1382 + 0 0.7490 0.0922 + 0 0.8745 0.0461 + 0 1.0000 0 + 0.2500 1.0000 0 + 0.5000 1.0000 0 + 0.7500 1.0000 0 + 1.0000 1.0000 0 + 1.0000 0.9000 0 + 1.0000 0.8000 0 + 1.0000 0.7000 0 + 1.0000 0.6000 0 + 0.9618 0.4902 0 + 0.9235 0.3804 0 + 0.8853 0.2706 0 + 0.8471 0.1608 0 + 0.8225 0.1206 0.1873 + 0.7980 0.0804 0.3745 + 0.7735 0.0402 0.5618 + 0.7490 0 0.7490 + 0.8118 0 0.8118 + 0.8745 0 0.8745 + 0.9373 0 0.9373 + 1.0000 0 1.0000 + 1.0000 0.1500 0.9461 + 1.0000 0.3000 0.8922 + 1.0000 0.4500 0.8382 + 1.0000 0.6000 0.7843 + 1.0000 0.6733 0.8239 + 1.0000 0.7467 0.8634 + 1.0000 0.8200 0.9029 + 1.0000 0.8933 0.9425 + 1.0000 0.9200 0.9569 + 1.0000 0.9467 0.9712 + 1.0000 0.9733 0.9856 + 1.0000 1.0000 1.0000 + 0.9714 0.9714 0.9714 + 0.9429 0.9429 0.9429 + 0.9143 0.9143 0.9143 + 0.8857 0.8857 0.8857 + 0.8571 0.8571 0.8571 + 0.8286 0.8286 0.8286 + 0.8000 0.8000 0.8000 + ]; +end +function LM=wmcon +LM = [ ... + 1.0000 1.0000 1.0000; + 0.9541 0.9888 1.0000; + 0.9081 0.9776 1.0000; + 0.8622 0.9664 1.0000; + 0.8162 0.9552 1.0000; + 0.7703 0.9440 1.0000; + 0.7244 0.9328 1.0000; + 0.6784 0.9216 1.0000; + 0.6319 0.8559 0.9475; + 0.5853 0.7902 0.8951; + 0.5387 0.7245 0.8426; + 0.4922 0.6588 0.7902; + 0.4456 0.5931 0.7377; + 0.3990 0.5275 0.6853; + 0.3525 0.4618 0.6328; + 0.3059 0.3961 0.5804; + 0.2676 0.3539 0.5284; + 0.2294 0.3118 0.4765; + 0.1912 0.2696 0.4245; + 0.1529 0.2275 0.3725; + 0.1147 0.1706 0.2794; + 0.0765 0.1137 0.1863; + 0.0382 0.0569 0.0931; + 0 0 0; + 0.0176 0.0529 0.0353; + 0.0353 0.1059 0.0706; + 0.0529 0.1588 0.1059; + 0.0706 0.2118 0.1412; + 0.1510 0.2951 0.2039; + 0.2314 0.3784 0.2667; + 0.3118 0.4618 0.3294; + 0.3922 0.5451 0.3922; + 0.4833 0.6255 0.4882; + 0.5745 0.7059 0.5843; + 0.6657 0.7863 0.6804; + 0.7569 0.8667 0.7765; + 0.8078 0.8941 0.8304; + 0.8588 0.9216 0.8843; + 0.9098 0.9490 0.9382; + 0.9608 0.9765 0.9922; + 0.9706 0.9059 0.8422; + 0.9804 0.8353 0.6922; + 0.9902 0.7647 0.5422; + 1.0000 0.6941 0.3922; + 0.9618 0.5608 0.2941; + 0.9235 0.4275 0.1961; + 0.8853 0.2941 0.0980; + 0.8471 0.1608 0; + 0.8191 0.1507 0; + 0.7912 0.1407 0; + 0.7632 0.1306 0; + 0.7353 0.1206 0; + 0.7074 0.1105 0; + 0.6794 0.1005 0; + 0.6515 0.0904 0; + 0.6235 0.0804 0; + 0.5956 0.0703 0; + 0.5676 0.0603 0; + 0.5397 0.0502 0; + 0.5118 0.0402 0; + 0.4838 0.0301 0; + 0.4559 0.0201 0; + 0.4279 0.0100 0; + 0.4000 0 0; + ]; +end +function LM=wmcon2 + LM = [ + 1.0000 1.0000 1.0000 + 1.0000 1.0000 1.0000 + 1.0000 1.0000 1.0000 + 1.0000 1.0000 1.0000 + 1.0000 1.0000 1.0000 + 0.9196 0.9804 1.0000 + 0.8392 0.9608 1.0000 + 0.7588 0.9412 1.0000 + 0.6784 0.9216 1.0000 + 0.5980 0.8343 0.9392 + 0.5176 0.7471 0.8784 + 0.4373 0.6598 0.8176 + 0.3569 0.5725 0.7569 + 0.3137 0.5029 0.6961 + 0.2706 0.4333 0.6353 + 0.2275 0.3637 0.5745 + 0.1843 0.2941 0.5137 + 0.1794 0.2588 0.4784 + 0.1745 0.2235 0.4431 + 0.1696 0.1882 0.4078 + 0.1647 0.1529 0.3725 + 0.1971 0.1647 0.3667 + 0.2294 0.1765 0.3608 + 0.2618 0.1882 0.3549 + 0.2941 0.2000 0.3490 + 0.3471 0.2451 0.3902 + 0.4000 0.2902 0.4314 + 0.4529 0.3353 0.4725 + 0.5059 0.3804 0.5137 + 0.6049 0.4804 0.5951 + 0.7039 0.5804 0.6765 + 0.8029 0.6804 0.7578 + 0.9020 0.7804 0.8392 + 0.9265 0.8353 0.8794 + 0.9510 0.8902 0.9196 + 0.9755 0.9451 0.9598 + 1.0000 1.0000 1.0000 + 1.0000 0.8755 0.8755 + 1.0000 0.7510 0.7510 + 1.0000 0.6265 0.6265 + 1.0000 0.5020 0.5020 + 1.0000 0.3765 0.3765 + 1.0000 0.2510 0.2510 + 1.0000 0.1255 0.1255 + 1.0000 0 0 + 0.9000 0 0 + 0.8000 0 0 + 0.7000 0 0 + 0.6000 0 0 + 0.5933 0 0 + 0.5867 0 0 + 0.5800 0 0 + 0.5733 0 0 + 0.5667 0 0 + 0.5600 0 0 + 0.5533 0 0 + 0.5467 0 0 + 0.5400 0 0 + 0.5333 0 0 + 0.5267 0 0 + 0.5200 0 0 + 0.5133 0 0 + 0.5067 0 0 + 0.5000 0 0 + ]; +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_main_amap.m",".m","17623","374","function [prob,indx,indy,indz,th,Yrep] = cat_main_amap(Ymi,Yb,Yb0,Ycls,job,res) +% ______________________________________________________________________ +% +% AMAP segmentation: +% Most corrections were done before and the AMAP routine is used with +% a low level of iterations and no further bias correction, because +% some images get tile artifacts. +% +% [prob,indx,indy,indz,th] = cat_main_amap(Ymi,Yb,Yb0,Ycls,job,res) +% +% prob .. new AMAP segmentation (4D) +% ind* .. index elements to asign a subvolume +% Ymi .. local intensity normalized source image +% Yb .. brain mask +% Ycls .. SPM segmentation +% job .. SPM/CAT parameter structure +% res .. SPM segmentation structure +% th .. AMAP treshholds +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + global cat_err_res + + % this function adds noise to the data to stabilize processing and we + % have to define a specific random pattern to get the same results each time + if exist('rng','file') == 2, rng('default'); rng(0); else, rand('state',0); randn('state',0); end + + + % if there is a breakpoint in this file set debug=1 and do not clear temporary variables + dbs = dbstatus; debug = 0; for dbsi=1:numel(dbs), if strcmp(dbs(dbsi).name,mfilename); debug = 1; break; end; end + + try + if job.extopts.ignoreErrors > 3 + error('cat_main_amap:useSPM','Use SPM segmentation.'); + end + + + % correct for harder brain mask to avoid meninges in the segmentation + % RD20200619: unclear severe MATLAB crashes calling cat_amap in the ignoreErrors pipeline + Ymib = real(Ymi); Ymib(~Yb) = 0; + Ymib(isnan(Ymib) | isinf(Ymib)) = 0; + Ymib = max(0,min(Ymib,2)); + rf = 10^4; Ymib = round(Ymib*rf)/rf; + d = size(Ymi); + vx_vol = sqrt(sum(res.image(1).mat(1:3,1:3).^2)); + + framing.tissue = 4; + framing.pve = 1; + + % prepare data for segmentation + if 1 + %% classic approach, consider the WMH! + Kb2 = numel(Ycls); + cls2 = zeros([d(1:2) Kb2]); + Yp0 = zeros(d,'uint8'); + for i=1:d(3) + for k1 = 1:Kb2, cls2(:,:,k1) = Ycls{k1}(:,:,i); end + % find maximum for reordered segmentations + [maxi,maxind] = max(cls2(:,:,[3,1,2,4:Kb2]),[],3); + k1ind = [1 2 3 1 0 0 2 1]; % WMHs will be WM, lesions CSF + for k1 = 1:Kb2 + Yp0(:,:,i) = Yp0(:,:,i) + cat_vol_ctype((maxind == k1) .* (maxi~=0) * k1ind(k1) .* min(1,Yb(:,:,i))); + end + end + Yp0 = min(3,Yp0); + + + %% correct missing parts by using the intensity normalized map or the old Yp0 label map + % RD202306 this is maybe now already corrected by the WMHs setting of k1ind above +% ########## NEW ########### +% RD202008: this may not working correctly +defineMissingParts = 0; +if defineMissingParts + if job.extopts.ignoreErrors < 3 + Yp0o = min(3,max(1,uint8(max(Yb,min(3,round(Ymi*3)))))); + else + Yp0o = min(3,max(1,single(Ycls{3})/255*3 + single(Ycls{1})/255*2 + single(Ycls{2})/255)); + end + Yp0(Yb & Yp0==0) = cat_vol_ctype( round( Yp0o(Yb & Yp0==0) ) ); +end +% ########## NEW ########### + + if ~debug, clear maxi maxind Kb k1 cls2 Yp0o; end + + else + % more direct method ... a little bit more WM, less CSF + Yp0 = uint8(max(Yb,min(3,round(Ymi*3)))); Yp0(~Yb) = 0; + end +% ########## NEW ########### +% RD202008: class 0 is required and ignored by the AMAP +if defineMissingParts + Yp0o = min(3,max(0,uint8(max(Yb,min(3,round(Ymi*3)))))); % class 0 is required! + Yp0(Yb & (Yp0<=0 | Yp0>3)) = min(3,max(1,cat_vol_ctype( round( Yp0o(Yb & (Yp0<=0 | Yp0>3)) ) ))); clear Yp0o + if sum( Yp0(Yb(:)>0.5)==0 ) ~= 0 + error('cat_main_amap:badYp0def', ... + 'Undefined tissues within the brain area may cause severe MATLAB errors while calling cat_amap.c.'); + end +end +% ########## NEW ########### + + + % use index to speed up and save memory + sz = size(Yb); + [indx, indy, indz] = ind2sub(sz,find(Yb>0)); + if job.extopts.AMAPframing + bx = (framing.tissue + framing.pve) * 3 * job.extopts.AMAPframing + 2; + indx = [min(indx) max(indx)] + [-bx bx]; indy = [min(indy) max(indy)] + [-bx bx]; indz = [min(indz) max(indz)] + [-bx bx]; + end + indx = max((min(indx) - 1),1):min((max(indx) + 1),sz(1)); + indy = max((min(indy) - 1),1):min((max(indy) + 1),sz(2)); + indz = max((min(indz) - 1),1):min((max(indz) + 1),sz(3)); + + % Yb source image because Amap needs a skull stripped image + % set Yp0b and source inside outside Yb to 0 + Yp0b = Yp0(indx,indy,indz); + Ymib = Ymib(indx,indy,indz); + + + % remove non-brain tissue with a smooth mask and set values inside the + % brain at least to CSF to avoid wholes for images with CSF==BG. + if job.extopts.LASstr>0 && job.extopts.ignoreErrors < 3 && ... + ~isfield(job.extopts,'inv_weighting') && ~job.extopts.inv_weighting + Ywmstd = cat_vol_localstat(single(Ymib),Yp0b==3,1,4); + CSFnoise(1) = cat_stat_nanmean(Ywmstd(Ywmstd(:)>0))/mean(vx_vol); + Ywmstd = cat_vol_localstat(cat_vol_resize(single(Ymib),'reduceV',vx_vol,vx_vol*2,16,'meanm'),... + cat_vol_resize(Yp0==3,'reduceV',vx_vol,vx_vol*2,16,'meanm')>0.5,1,4); + CSFnoise(2) = cat_stat_nanmean(Ywmstd(Ywmstd(:)>0))/mean(vx_vol); + Ycsf = double(0.33 * Yb(indx,indy,indz)); spm_smooth(Ycsf,Ycsf,0.6*vx_vol); + Ycsf = Ycsf + cat_vol_smooth3X(randn(size(Ycsf)),0.5) * max(0.005,min(0.2,CSFnoise(1)/4)); % high-frequency noise + Ycsf = Ycsf + cat_vol_smooth3X(randn(size(Ycsf)),1.0) * max(0.005,min(0.2,CSFnoise(2)*1)); % high-frequency noise + Ymib = max(Ycsf*0.8 .* cat_vol_smooth3X(Ycsf>0,2),Ymib); + clear Ycsf; + end + + + % adaptive mrf noise + if (job.extopts.mrf>=1 || job.extopts.mrf<0) %&& job.extopts.ignoreErrors < 3 + % estimate noise + [Yw,Yg] = cat_vol_resize({Ymi.*(Ycls{1}>240),Ymi.*(Ycls{2}>240)},'reduceV',vx_vol,3,32,'meanm'); + Yn = max(cat(4,cat_vol_localstat(Yw,Yw>0,2,4),cat_vol_localstat(Yg,Yg>0,2,4)),[],4); + job.extopts.mrf = double(min(0.15,3*cat_stat_nanmean(Yn(Yn(:)>0)))) * 0.5; + clear Yn Yg + end + + % display something + stime = cat_io_cmd(sprintf('Amap using initial SPM segmentations (MRF filter strength %0.2f)',job.extopts.mrf)); + + %% intensity values + Ymib = abs(double(Ymib)); + + if job.extopts.AMAPframing + Ymib = double(Ymi(indx,indy,indz)) .* double(Yb(indx,indy,indz)); + Yp0b = uint8(Yp0(indx,indy,indz)) .* uint8(Yb(indx,indy,indz)); + %% + if ~job.extopts.inv_weighting + tvals = [0 1 2 3]; + else + % [x,xy] = max( res.mg(:) .* (res.lkp(:) == 3) ); + % [x,xi] = sort([ mean(res.mn(res.lkp(:) == 1)) mean(res.mn(res.lkp(:) == 2)) mean(res.mn( xy )) ]); + tvals = [0 cat_stat_kmeans(Ymib(Yp0b==1)) cat_stat_kmeans(Ymib(Yp0b==2)) cat_stat_kmeans(Ymib(Yp0b==3)) ]; + end + %% + Ybb = Yb0(indx,indy,indz)>0; + Ybb = cat_vol_morph(Ybb,'d',3); + pn = max(double(Yp0b(:))) * 0.015; + pnx = max(double(Yp0b(:))) * 0.015; + Yn = randn(size(Yp0b)); + ex = framing.tissue; + ep = framing.pve; + BBe = ~Ybb; BBe (2 :end-1 , 2 :end-1 , 3 :end-2 ) = false; + BBww = ~Ybb; BBww(ex*1 :end+1-ex*1 , ex*1 :end+1-ex*1 , ex*1 :end+1-ex*1 ) = false; + BBgw = ~Ybb; BBgw(ex*1+0 :end+1-ex*1-0 , ex*1+ep:end+1-ex*1-ep , ex*1+ep:end+1-ex*1-ep) = false; BBgw(BBww) = false; + BBgg = ~Ybb; BBgg(ex*2 :end+1-ex*2 , ex*2 :end+1-ex*2 , ex*2 :end+1-ex*2 ) = false; BBgg(BBww | BBgw) = false; + BBgc = ~Ybb; BBgc(ex*2+0 :end+1-ex*2-0 , ex*2+ep:end+1-ex*2-ep , ex*2+ep:end+1-ex*2-ep) = false; BBgc(BBww | BBgw | BBgg) = false; + BBcc = ~Ybb; BBcc(ex*3 :end+1-ex*3 , ex*3 :end+1-ex*3 , ex*3 :end+1-ex*3 ) = false; BBcc(BBww | BBgw | BBgg | BBgc) = false; + BBcb = ~Ybb; BBcb(ex*3+0 :end+1-ex*3-0 , ex*3+ep:end+1-ex*3-ep , ex*3+ep:end+1-ex*3-ep) = false; BBcb(BBww | BBgw | BBgg | BBgc | BBcc) = false; + % extra values + extra noise + % all peaks have an offset of 0.05 that produces better results + if ~job.extopts.inv_weighting + Ymib(BBcb) = 0.55/3 + pnx * Yn(BBcb); Yp0b(BBcb) = 0; + Ymib(BBcc) = 1.05/3 + pnx * Yn(BBcc); Yp0b(BBcc) = 1; + Ymib(BBgc) = 1.55/3 + pnx * Yn(BBgc); Yp0b(BBgc) = 2; + Ymib(BBgg) = 2.05/3 + pnx * Yn(BBgg); Yp0b(BBgg) = 2; + Ymib(BBgw) = 2.75/3 + pnx * Yn(BBgw); Yp0b(BBgw) = 3; + Ymib(BBww) = 3.05/3 + pnx * Yn(BBww); Yp0b(BBww) = 3; + Ymib(BBe ) = 3.55/3 + pnx * Yn(BBe ); Yp0b(BBe ) = 0; + else + Ymib(BBcb) = tvals(1)/2 + pnx * Yn(BBcb); Yp0b(BBcb) = 0; + Ymib(BBcc) = tvals(2) + 0.05/3 + pnx * Yn(BBcc); Yp0b(BBcc) = 1; + Ymib(BBgc) = mean(tvals(2:3)) + pnx * Yn(BBgc); Yp0b(BBgc) = 2; + Ymib(BBgg) = tvals(3) + 0.05/3 + pnx * Yn(BBgg); Yp0b(BBgg) = 2; + Ymib(BBgw) = mean(tvals(3:4)) + pnx * Yn(BBgw); Yp0b(BBgw) = 3; + Ymib(BBww) = tvals(4) + 0.05/3 + pnx * Yn(BBww); Yp0b(BBww) = 3; + %Ymib(BBe ) = tvals(1) + 0.55/3 + pnx * Yn(BBe ); Yp0b(BBe ) = 0; + end + clear BBww BBgw BBgg BBgc BBcc BBcb BBe; + + %% add noise + addnoise = 0; + if addnoise == 2 + % we add noise only in save regions + WMe = cat_vol_morph( Yp0b==3 , 'e' , 1 )>0; + CMe = cat_vol_morph( Yp0b==1 , 'e' , 1 )>0; + Ymib( WMe ) = Ymib( WMe ) + pn * Yn( WMe ); + Ymib( CMe ) = Ymib( CMe ) + pn * Yn( CMe ); + elseif addnoise == 1 + % add noise + Ymib = Ymib + pn * Yn; + end + Ymib = abs(Ymib); + end + + % Amap parameters - default sub=16 caused errors with highres data! + % don't use bias_fwhm, because the Amap bias correction is not that efficient and also changes + % intensity values + % RD202006 the bias_fwhm paraemter (and/or other) cause also MATLAB crashes in the ignoreError pipeline + % RD202104 sub has to be large because the AMAP bias corrections seams to be in-optimal and caused bad threshold + % RD202104 Ymib should only include positive values + n_iters = 10; sub = round(64/mean(vx_vol)); + n_classes = 3; pve = 5; bias_fwhm = 0; init_kmeans = 0; + if job.extopts.mrf~=0, iters_icm = 50; else, iters_icm = 0; end + if 0 %job.extopts.ignoreErrors > 2 || job.extopts.inv_weighting + % init_kmeans = 0; % k-means was not stable working (e.g. HR075T2) + % % and it is better to use also here the previous intensity scaling + % + % clsint = @(x) round( sum(res.mn(res.lkp==x) .* res.mg(res.lkp==x)') * 10^5)/10^5; % SPM peak definition + % pve = 6 - (clsint(1)1 + if strcmpi(spm_check_version,'octave'), pm = '+/-'; else, pm = char(177); end + if (th{1}(1) < th{2}(1)) && (th{2}(1) < th{3}(1)) % T1 + fprintf(' AMAP peaks: [CSF,GM,WM] = [%0.2f%s%0.2f,%0.2f%s%0.2f,%0.2f%s%0.2f]\n',... + th{1}(1),pm,th{1}(2),th{2}(1),pm,th{2}(2),th{3}(1),pm,th{3}(2)); + else + fprintf(' AMAP peaks: [%0.2f%s%0.2f,%0.2f%s%0.2f,%0.2f%s%0.2f]\n',... + th{1}(1),pm,th{1}(2),th{2}(1),pm,th{2}(2),th{3}(1),pm,th{3}(2)); + end + end + % if one of the peaks is NaN than create an error + if any( isnan( cell2mat(th) ) ) + error('cat_main_amap:nan',['AMAP estimated NaN tissue peaks that point to an error in the \\\\n' ... + 'preprocessing before the AMAP segmentation or inadequate input. ']); + end + % fine evaluation of tissue peaks + if (th{1}(1) < th{2}(1)) && (th{2}(1) < th{3}(1)) % T1 + % in the T1 contrast we have a clear expectation for each tissue class + if th{1}(1)<0 || th{1}(1)>0.6 || th{2}(1)<0.5 || th{2}(1)>0.9 || th{3}(1)<0.95-th{3}(2) || th{3}(1)>1.1 + error('cat_main_amap:peaks',['AMAP estimated untypical tissue peaks that point to an \\\\n' ... + 'error in the preprocessing before the AMAP segmentation. ']); + end + else + % if there is a very low contrast between two peaks then create an error + % because the intensity normalization unsed before was probably incorrect + con = [ abs(diff([th{1}(1) th{2}(1)])) , abs(diff([th{1}(1) th{3}(1)])) , abs(diff([th{2}(1) th{3}(1)]))]; + if any( con < 0.15 ) + %% We only create an servere warning here but go one with processing + cat_io_addwarning([mfilename ':lowTissueContrast'],sprintf( ... + ['AMAP estimated quite low tissue contrast that point to problems \\\\n' ... + 'in the preprocessing before the AMAP segmentation or inadequate input \\\\n' ... + ' [con(c1,c2),con(c1,c3),con(c2,c3)] = [%0.2f,%0.2f,%0.2f] '],con),1 + (min(con) < 0.1),[0 1]); + end + end + + if isfield(job.extopts,'inv_weighting') && job.extopts.inv_weighting % job.extopts.ignoreErrors > 1 && + % RD202006: catching of problems in low quality data - in development + probs = prob; + ap = [3 1 2]; if numel(Ycls)==7, ap(4)=7; end + for i=1:numel(ap), probs(:,:,:,i) = Ycls{ap(i)}(indx,indy,indz); end + % WMHC + probs(:,:,:,2) = sum( probs(:,:,:,2:2:end) ,4); + + Yp0s = (single(probs(:,:,:,1)) + single(probs(:,:,:,2))*2 + single( probs(:,:,:,3))*3)/255/3; % SPM segmentation + Yp0 = (single(prob(:,:,:,1)) + single(prob(:,:,:,2))*2 + single(prob(:,:,:,3))*3)/255/3; % AMAP segmentation + if ( sum(abs(Yp0s(:) - Yp0(:))>0.4) / sum(Yp0(:)>0.5) ) > 0.02 + Yrep = min(1, abs(Yp0s - Yp0) * 3); % * 1 = low correction (less SPM) uint8( abs(Yp0s - Yp0) > 0.3 & Yp0s>0.1); + prob2 = prob; + for i=1:3, prob2(:,:,:,i) = cat_vol_ctype( single(prob(:,:,:,i)) .* (1-Yrep) + Yrep .* single(probs(:,:,:,i)) ); end + + %rep = mean(Yrep(Yp0(:)))*100; + %cat_io_addwarning('cat_main_amap:mixSPMAMAP',sprintf( 'Mix SPM and AMAP segmentation. Use SPM in case of strong differences (%0.2f%%).',rep),1,[0 1]) + + %Yp0c = (single(prob2(:,:,:,1)) + single(prob2(:,:,:,2))*2 + single(prob2(:,:,:,3))*3)/255/3; + else + Yrep = false(size(Ymib)); + end + %% separation just for tests/debugging + if ( sum(abs(Yp0s(:) - Yp0(:))>0.4) / sum(Yp0(:)>0.5) ) > 0.02 + prob = prob2; + end + clear Yp0 Yp0s Yp0c probs prob2 + else + Yrep = false(size(Ymib)); + end + + % reorder probability maps according to spm order + clear Yp0b Ymib; + prob = prob(:,:,:,[2 3 1]); + clear vol Ymib + + % finally use brainmask before cleanup that was derived from SPM segmentations and additionally include + % areas where GM from Amap > GM from SPM. This will result in a brainmask where GM areas + % hopefully are all included and not cut + if job.extopts.gcutstr>0 && ~isfield(job.extopts,'inv_weighting') && ~job.extopts.inv_weighting + Yb0(indx,indy,indz) = Yb0(indx,indy,indz) | ((prob(:,:,:,1) > 0) & Yb(indx,indy,indz)); % & ~Ycls{1}(indx,indy,indz)); + for i=1:3 + prob(:,:,:,i) = prob(:,:,:,i).*uint8(Yb0(indx,indy,indz)); + end + end + + + catch e + if job.extopts.ignoreErrors < 2 + % update segmentation for error report + if exist('prob','var') + Yp0 = single(prob(:,:,:,3))/255/3 + single(prob(:,:,:,1))/255*2/3 + single(prob(:,:,:,2))/255; + else + Yp0 = single(Ycls{3})/255/3 + single(Ycls{1})/255*2/3 + single(Ycls{2})/255; + end + vx_vol = sqrt(sum(res.image(1).mat(1:3,1:3).^2)); + [cat_err_res.init.Yp0,cat_err_res.init.BB] = cat_vol_resize(Yp0,'reduceBrain',vx_vol,2,Yp0>0.5); + cat_err_res.init.Yp0 = cat_vol_ctype(cat_err_res.init.Yp0/3*255); + + rethrow(e) + end + + % use SPM + if job.extopts.ignoreErrors < 3 + cat_io_addwarning(e.identifier,e.message,2,[0 1]); + end + + prob = zeros([size(Ymi),3],'uint8'); + for i = 1:3, prob(:,:,:,i) = Ycls{i}; end + sz = size(Yb); + [indx, indy, indz] = ind2sub(sz,find(Yb>0)); + indx = max((min(indx) - 1),1):min((max(indx) + 1),sz(1)); + indy = max((min(indy) - 1),1):min((max(indy) + 1),sz(2)); + indz = max((min(indz) - 1),1):min((max(indz) + 1),sz(3)); + prob = prob(indx,indy,indz,:); + + Yrep = false(size(Ymib)); + end +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_stat_homogeneity.m",".m","85403","2599","function varargout = cat_stat_homogeneity(job) +%cat_stat_homogeneity. To check Z-score across sample. +% +% Images have to be in the same orientation with same voxel size +% and dimension (e.g. spatially registered images) +% +% Surfaces have to be same size (number of vertices). +% +% varargout = cat_stat_homogeneity(job) +% +% job .. SPM job structure +% .data .. volume and surface files +% .globals .. optionally correct TIV using global scaling (for VBM only) +% .gSF .. global scaling values +% .c .. confounds +% .data_xml .. optional xml QC data +% .verb .. print figures +% .new_fig .. use new window instead of SPM Fgraph +% .xM .. optional mask information from SPM.xM +% +% varargout .. output structure +% .zscore .. quartic mean Z-score +% .table .. Z-score table +% .sorttable .. sorted Z-score table +% .threshold_zsc .. lower threshold for Z-score (mean - 4*std) +% +% Example: +% cat_stat_homogeneity(struct('data',{{ files }} ,'c',[],'data_xml',{{}})); +% +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +clearvars -GLOBAL H; % clear old +global H + +if nargin == 0 + error('No argument given.'); +end + +H.sample = []; +H.mouse.x = 1; +H.mouse.xold = 1; +H.del = []; +H.ui.alphaval = 0.5; +H.names_changed = false; +H.cmap = [jet(64); gray(64)]; % create two colormaps +G = []; +n_subjects = 0; + +% use new figure by default +if ~isfield(job,'new_fig') + job.new_fig = true; +end + +if ~isfield(job,'verb') + job.verb = true; +end + +H.job = job; + +if isfield(job,'show_violin') + H.ui.show_violin = job.show_violin; +else + H.ui.show_violin = false; +end + +if isfield(job,'show_name') + H.ui.show_name = job.show_name; +else + H.ui.show_name = false; +end + +% consider new options, but keep compatibility +if isfield(job,'sel_xml') + if isfield(job.sel_xml,'data_xml') + job.data_xml = job.sel_xml.data_xml; + else + job.data_xml = ''; + end +end + +% this function is also used for the longitudinal, thus we also have to +% test the thickness field +if ~spm_mesh_detect(char(job.data{1}(1,:))) && isempty(strfind(char(job.data{1}(1,:)),'thickness')) + H.mesh_detected = false; +else + H.mesh_detected = true; +end + +% check for repeated anova design with long. data +if isfield(job,'factorial_design') && isfield(job.factorial_design,'des') && isfield(job.factorial_design.des,'fblock') + H.repeated_anova = true; +elseif isfield(job,'factorial_design') && isfield(job.factorial_design,'spmmat') + load(job.factorial_design.spmmat{1}) + H.repeated_anova = ~isempty(SPM.xX.iB); +else + H.repeated_anova = false; +end + +% read filenames for each sample and indicate sample parameter +if H.mesh_detected + n_samples = numel(job.data); + sinfo = cat_surf_info(char(job.data{1}(1,:))); + H.Pmesh = gifti(sinfo.Pmesh); + for i=1:n_samples + [pp,ff,ee] = spm_fileparts(char(deblank(job.data{i}(1,:)))); + if any( ~isempty( strfind({'lh.thickness' },[ff ee]) ) ) && ~strcmp(ee,'.gii') + %% native longitudinal surface + sdata = gifti(fullfile(pp,[strrep(ff,'lh.thickness','lh.central') ee '.gii'])); + cdata = single(cat_io_FreeSurfer('read_surf_data',job.data{i})); + gdata = gifti(struct('vertices',sdata.vertices,'faces',sdata.faces,'cdata',cdata)); + V0 = struct('fname',job.data{i},'dim',size(cdata),'dt',[16 0], ... + 'pinfo',[1 0 0],'mat',eye(4),'n',[1 1],'descript','GMT'); + V0.private = gdata; + else + V0 = spm_data_hdr_read(char(job.data{i})); + end + n_subjects = n_subjects + length(V0); + + if i==1, H.files.V = V0; + else, H.files.V = [H.files.V; V0]; end + H.sample = [H.sample, i*ones(1,size(job.data{i},1))]; + end + H.files.fname = cellstr({H.files.V.fname}'); + H.info = cat_surf_info(H.files.fname{1}); +else + n_samples = numel(job.data); + for i=1:n_samples + + if size(job.data{i},1) == 1 % 4D data + [pth,nam,ext] = spm_fileparts(char(job.data{i})); + % remove "",1"" at the end + job.data{i} = fullfile(pth,[nam ext]); + end + + V0 = nifti(char(job.data{i})); + n_subjects = n_subjects + length(V0); + + if i==1, H.files.V = V0; + else, H.files.V = [H.files.V V0]; end + + H.sample = [H.sample, i*ones(1,length(V0))]; + end + + % we need that field to be comparable to V of mesh-structure + H.files.fname = cellstr({H.files.V.dat.fname}'); +end + +H.ind = true(1,n_subjects); + +% use global scaling from design matrix +if isfield(job,'gSF') && numel(job.gSF) == n_subjects + fprintf('Use global scaling from design matrix (i.e. with TIV).\n'); + gSF = job.gSF; +end + +% check for global scaling with TIV +if isfield(job,'globals') && job.globals + if H.mesh_detected + is_gSF = false; + fprintf('Disabled global scaling with TIV, because this is not meaningful for surface data.\n'); + else + is_gSF = true; + gSF = ones(n_subjects,1); + end +else + is_gSF = false; +end + +% prepare design matrix for adjusting nuisance parameters +if isfield(job,'c') && ~isempty(job.c) + for i=1:numel(job.c) + G = [G job.c{i}]; + end + if size(G,1) ~= n_subjects + G = G'; + end + % mean correction + G = G - mean(G); + iG = pinv(G); +end + +if isempty(char(job.data_xml)) + H.isxml = false; + xml_defined = false; + H.xml.QM_names = ''; + xml_files = []; +else + xml_files = char(job.data_xml); + if size(xml_files,1) ~= n_subjects + fprintf('Only %d of %d report files were defined. Try to find xml-files for quality measures.\n',size(xml_files,1),n_subjects); + H.isxml = false; + xml_defined = false; + else + H.isxml = true; + xml_defined = true; + end +end + +% select school marks (range best-low = 0.5 - 10.5) or percentage system (range low-best: 0-100%) +if isfield(job,'userps'), H.userps = job.userps; else, H.userps = -1; end + +H.xml.QM = ones(n_subjects,3); +H.xml.QM_names = char('Noise','Bias','Structural image quality rating (SIQR)'); +H.xml.QM_names_multi = char('Noise & Quartic Mean Z-score','Bias & Quartic Mean Z-score','SIQR & Quartic Mean Z-score'); +H.xml.QM_order = H.userps .* ones(1,3); + +% add some more entries for surfaces +if H.mesh_detected + H.xml.QM = ones(n_subjects,5); + H.xml.QM_names = char(H.xml.QM_names,'Euler number','Size of topology defects'); + H.xml.QM_names_multi = char(H.xml.QM_names_multi,'Euler number & Quartic Mean Z-score','Size of topology defects & Quartic Mean Z-score'); + H.xml.QM_order = -ones(1,5); +end + + +% To find other related files of each subject, we first have to figure out +% what the general prefix of the data itself is (asuming that it is only +% useful to anlyse on data class (defined by the prefix) at once. +% To find the prefix, we will try to find the XML file of the first subject +% that thould be in the report directory (if exist) or otherwise in the +% same directory in case of BIDS. +% The test for BIDS has to be done later as far BIDS and non BIDS can be +% mixed. + +% try to detect report folder and check if this fits for all +pth = spm_fileparts( H.files.fname{1} ); +if isfield(job,'sel_xml') && isfield(job.sel_xml,'select_dir') + report_folder = char(job.sel_xml.select_dir); +else + % if there is a report directory than use it + ppth = spm_fileparts(pth); + if exist( fullfile( ppth, 'report' ), 'dir' ) + report_folder = fullfile( ppth, 'report' ); + else + report_folder = pth; + end +end + +% search xml report files if not defined +prep_str = ''; +if ~xml_defined + fprintf('Search xml-files '); + + % we now try to find all XML files in the report folder + xml_files = spm_select('List',report_folder,'^cat_.*\.xml$'); + if ~isempty(xml_files) + + % find part of xml-filename in data files to get the prepending string + % (e.g. mwp1) + i = 1; j = 1; + while i <= n_subjects + while j <= size(xml_files,1) + % remove ""cat_"" and "".xml"" from name + fname = deblank(xml_files(j,:)); + fname = fname(5:end-4); + + % and find that string in data filename + Vfname = H.files.fname{i}; + ind = strfind(Vfname,fname); + if ~isempty(ind) + [pth, prep_str] = spm_fileparts(Vfname(1:ind-1)); + i = n_subjects; + j = size(xml_files,1); + break + else + j = j + 1; + end + end + i = i + 1; + end + end + fprintf('\n'); +end + +n_xml_files = 0; +if job.verb, cat_progress_bar('Init',n_subjects,'Load xml-files'); end +res_RMS = nan(n_subjects,1); +for i=1:n_subjects + % get basename for data files + [pth, data_name, ee] = fileparts(H.files.fname{i}); + if ~strcmp(ee,'.nii') && ~strcmp(ee,'.gii'), data_name = [data_name ee]; end + + % remove ending for rigid or affine transformed files + data_name = strrep(data_name,'_affine',''); + data_name = strrep(data_name,'_rigid',''); + + % detect if BIDS file structure is used + % (hope this is unique enough - would be possible to add CAT12 as subdirectory) + BIDSdir = [filesep 'derivatives' filesep]; + isBIDS = cat_io_contains( pth , BIDSdir ); + + if isBIDS + % in case of BIDS CAT wrote all files into this directory + report_folder = pth; + [ppm,pps] = spm_fileparts(report_folder); + % just in case that there are subdirs + if cat_io_contains(pps,{'mri','surf','label'}) + pps = 'report'; + report_folder = fullfile(ppm,pps); + end + elseif ( isfield(job,'sel_xml') && isfield(job.sel_xml,'select_dir') ) + % in case of BIDS CAT wrote all files into this directory + report_folder = job.sel_xml.select_dir{1}; + else % use relative folder for autom. search + report_folder = fullfile(pth,'..','report'); + if ~exist(report_folder,'dir'), report_folder = pth; end + end + + % use xml-file if found by name + if ~xml_defined + + % remove prep_str from name and use report folder and xml extension + subjname = strrep(data_name,prep_str,''); + % for meshes we also have to remove the additional ""."" from name + if H.mesh_detected + subjname = subjname(2:end); + end + xml_file = fullfile(report_folder,['cat_' subjname '.xml']); + else % use defined xml-files + + [pth, subjname] = fileparts(deblank(xml_files(i,:))); + % remove leading 'cat_' + subjname = subjname(5:end); + + % check for filenames + if i > size(xml_files,1) + cat_io_cprintf('warn','\nSkip use of xml-files for quality measures because of not enough XML files were found.\n'); + H.isxml = false; + break + elseif isempty(strfind(data_name,subjname)) + cat_io_cprintf('warn','\nSkip use of xml-files for quality measures because of deviating subject names:\n%s vs. %s\n',H.files.fname{i},xml_files(i,:)); + H.isxml = false; + break + end + xml_file = deblank(xml_files(i,:)); + end + + %% get mri folder + [pth, data_name, ee] = fileparts(H.files.fname{i}); + if strcmp(ee,'.gii') && ~isBIDS, mri_folder = fullfile(fileparts(pth),'mri'); + else, mri_folder = pth; end + + % find raw/p0 files + H.files.raw{i} = fullfile(fileparts(pth),[subjname ee]); + H.files.p0{i} = fullfile(mri_folder,['p0' subjname '.nii']); + + if isBIDS + % get BIDS raw diretory of this subject by looking for the derivatives + % directory. The parent path give us the BIDS main directory where the + % original files should be located in sub path given behind the derivative + % directory + BIDSfst = strfind( pth , BIDSdir ) - 1; + BIDSlst = strfind( pth , BIDSdir ) + numel(BIDSdir); + BIDSlst = BIDSlst + find(pth(BIDSlst:end)==filesep,1,'first'); + BIDSrawdir = pth(1:BIDSfst); + BIDSsubdirs = pth(BIDSlst:end); + + H.files.raw{i} = fullfile(BIDSrawdir,BIDSsubdirs,[subjname ee]); + end + + H.files.rawgz{i} = [H.files.raw{i} '.gz']; + if ~exist(H.files.raw{i},'file'), H.files.raw{i} = ''; end + if isempty(H.files.raw{i}) && exist(H.files.rawgz{i},'file') && ~exist('foundrawgz','var') + cat_io_cprintf('warn','Gzipped (original) files are not supported in SPM display yet.\n'); + foundrawgz = true; %#ok + end + if ~exist(H.files.p0{i}, 'file'), H.files.p0{i} = ''; end + + if exist(xml_file,'file') + H.job.data_xml{i} = xml_file; + xml = cat_io_xml(xml_file); + n_xml_files = n_xml_files + 1; + H.isxml = true; + + % find jpg/pdf/log files + H.files.jpg{i} = fullfile(report_folder,['catreportj_' subjname '.jpg']); + if H.repeated_anova + H.files.jpg_long{i} = fullfile(report_folder,['catlongreportj_' data_name '.jpg']); + if ~exist(H.files.jpg_long{i},'file'), H.files.jpg_long{i} = ''; end + end + H.files.pdf{i} = fullfile(report_folder,['catreport_' subjname '.pdf']); + H.files.log{i} = fullfile(report_folder,['catlog_' subjname '.txt']); + if ~exist(H.files.jpg{i},'file'), H.files.jpg{i} = ''; end + if ~exist(H.files.pdf{i},'file'), H.files.pdf{i} = ''; end + if ~exist(H.files.log{i},'file'), H.files.log{i} = ''; end + + % get TIV + if is_gSF && isfield(xml,'subjectmeasures') && isfield(xml.subjectmeasures,'vol_TIV') + gSF(i) = xml.subjectmeasures.vol_TIV; + else + is_gSF = false; + end + + else + if is_gSF + cat_io_cprintf('warn','\nFile ""%s"" not found. \nSkip use of xml-files for quality measures and TIV. ',xml_file); + else + cat_io_cprintf('warn','\nFile ""%s"" not found. \nSkip use of xml-files for quality measures. ',xml_file); + end + cat_io_cprintf('warn','Please check if only one data type (e.g., mwp1) is used or select xml-files manually.\n\n'); + H.isxml = false; + is_gSF = false; + break + end + + if i > size(xml_files,1) + cat_io_cprintf('warn','\nSkip use of xml-files for quality measures because of not enough XML files were found.\n'); + H.isxml = false; + break + elseif ~isfield(xml,'qualityratings') && ~isfield(xml,'QAM') + cat_io_cprintf('warn',['\nQuality rating is not saved for %s. Report file %s is incomplete. ' ... + '\nPlease repeat preprocessing and check for potential errors in the ""err"" folder.\n'],H.files.fname{i},xml_files(i,:)); + H.isxml = false; + break + end + + if H.mesh_detected + if isfield(xml.qualityratings,'NCR') + % check for newer available surface measures + if isfield(xml.subjectmeasures,'EC_abs') && isfinite(xml.subjectmeasures.EC_abs) && isfinite(xml.subjectmeasures.defect_size) + H.xml.QM(i,:) = [xml.qualityratings.NCR xml.qualityratings.ICR xml.qualityratings.SIQR xml.subjectmeasures.EC_abs xml.subjectmeasures.defect_size]; + else + H.xml.QM(i,:) = [xml.qualityratings.NCR xml.qualityratings.ICR xml.qualityratings.SIQR NaN NaN]; + end + else % also try to use old version + H.xml.QM(i,:) = [xml.QAM.QM.NCR xml.QAM.QM.ICR xml.QAM.QM.rms]; + end + else + if isfield(xml.qualityratings,'NCR') + H.xml.QM(i,:) = [xml.qualityratings.NCR xml.qualityratings.ICR xml.qualityratings.SIQR]; + else % also try to use old version + H.xml.QM(i,:) = [xml.QAM.QM.NCR xml.QAM.QM.ICR xml.QAM.QM.rms]; + end + end + + res_RMS(i,:) = xml.qualityratings.res_RMS; + if job.verb, cat_progress_bar('Set',i); end +end +if H.userps > 0 + mark2rps = @(mark) min(100,max(0,105 - mark*10)); + H.xml.QM = mark2rps( H.xml.QM ); +end +if job.verb, cat_progress_bar('Clear'); end + +if H.isxml + if n_xml_files ~= n_subjects + cat_io_cprintf('warn','Only %d of %d report files found. Skip use of xml-files for quality measures.\n',n_xml_files,n_subjects); + H.isxml = false; + else + fprintf('%d report files with quality measures were found.\n',n_xml_files); + end +end + +% delete QM entries +if ~H.isxml + H.xml.QM = []; + H.xml.QM_order = []; + H.xml.QM_names = ''; + H.xml.QM_names_multi = ''; +end + +% remove last two columns if EC_abs and defect_size are not defined +if H.isxml && H.mesh_detected && all(~isfinite(H.xml.QM(:,4))) && all(~isfinite(H.xml.QM(:,5))) + H.xml.QM = H.xml.QM(:,1:3); + H.xml.QM_order = H.xml.QM_order(1:3); + H.xml.QM_names = H.xml.QM_names(1:3,:); + H.xml.QM_names_multi = H.xml.QM_names_multi(1:3,:); +end + +% add covariates to list if it's not from a statistical analysis where the +% covariates include all columns of the design matrix +if isfield(job,'c') && ~isempty(job.c) && ~isfield(job,'factorial_design') + for i=1:numel(job.c) + if ~isempty(H.xml.QM) + H.xml.QM = [H.xml.QM job.c{i}]; + H.xml.QM_order = [H.xml.QM_order 0]; + H.xml.QM_names = char(H.xml.QM_names, sprintf('Covariate %d',i)); + H.xml.QM_names_multi = char(H.xml.QM_names_multi, sprintf('Covariate %d & Quartic Mean Z-score',i)); + else + H.xml.QM = job.c{i}; + H.xml.QM_order = 0; + H.xml.QM_names = sprintf('Covariate %d',i); + H.xml.QM_names_multi = sprintf('Covariate %d & Quartic Mean Z-score',i); + end + end +end + +H.data.Ymean = 0.0; +Yss = 0.0; % sum of squares + +% preload surface data for later render view +if H.mesh_detected + % load surface texture data + H.texture = single(spm_data_read(H.files.V)); +end + +if job.verb, cat_progress_bar('Init',n_subjects,'Load data'); end + +% prepare Beta +if ~isempty(G) + if H.mesh_detected + dim = (H.files.V(1).dim); + else + dim = H.files.V(1).dat.dim; + end + Beta = zeros(prod(dim),size(G,2),'single'); +end + +% make initial mask +if H.mesh_detected + dim = (H.files.V(1).dim); +else + dim = H.files.V(1).dat.dim; +end +mask = true(dim); +M = H.files.V(1).mat; + +%-Get explicit mask(s) +%========================================================================== +if isfield(job,'xM') + for i = 1:numel(job.xM.VM) + if ~H.mesh_detected + C = spm_bsplinc(job.xM.VM(i), [0 0 0 0 0 0]'); + v = true(dim); + [x1,x2] = ndgrid(1:dim(1),1:dim(2)); + for x3 = 1:dim(3) + M2 = inv(M\job.xM.VM(i).mat); + y1 = M2(1,1)*x1+M2(1,2)*x2+(M2(1,3)*x3+M2(1,4)); + y2 = M2(2,1)*x1+M2(2,2)*x2+(M2(2,3)*x3+M2(2,4)); + y3 = M2(3,1)*x1+M2(3,2)*x2+(M2(3,3)*x3+M2(3,4)); + v(:,:,x3) = spm_bsplins(C, y1,y2,y3, [0 0 0 0 0 0]') > 0; + end + mask = mask & v; + clear C v x1 x2 x3 M2 y1 y2 y3 + else + v = full(job.xM.VM(i).private.cdata) > 0; + mask = mask & v(:); + clear v + end + end +end + +for i = 1:n_subjects + if H.mesh_detected + Ytmp = spm_data_read(H.files.V(i)); + else + Ytmp(:,:,:) = H.files.V(i).dat(:,:,:); + end + + % get mask + if isfield(job,'xM') + mask(mask) = Ytmp(mask) > job.xM.TH(i); %-Threshold (& NaN) mask + end + + Ytmp(~isfinite(Ytmp)) = 0; + + % either global scaling was externally defined using job or values were + % used from xml-file + if is_gSF || isfield(job,'gSF') + Ytmp = Ytmp*gSF(i)/mean(gSF); + end + + if i>1 && numel(H.data.Ymean) ~= numel(Ytmp) + cat_io_cprintf('err','\n\nERROR: File %s has different data size: %d vs. %d\n\n',job.data{i},numel(H.data.Ymean),numel(Ytmp)); + return + end + + % estimate Beta + if ~isempty(G) + for j = 1:size(Beta,2) + Beta(:,j) = Beta(:,j) + single(iG(j,i)*Ytmp(:)); + end + end + + H.data.Ymean = H.data.Ymean + Ytmp(:); + Yss = Yss + Ytmp(:).^2; + if job.verb, cat_progress_bar('Set',i); end +end +if job.verb, cat_progress_bar('Clear'); end + +% get mean and SD +H.data.Ymean = H.data.Ymean/n_subjects; + +% get range 10..98% +H.data.range98 = cat_vol_iscaling(H.data.Ymean(H.data.Ymean~=0),[0.10 0.98]); +H.data.global = mean(H.data.Ymean(H.data.Ymean~=0))/8; H.data.global = mean(H.data.Ymean(H.data.Ymean>H.data.global)); + +H.data.global = 0.25*H.data.global; + +% we have sometimes issues with number precision +Yvar = 1.0/(n_subjects-1)*(Yss - n_subjects*H.data.Ymean.*H.data.Ymean); +Yvar(Yvar<0) = 0; +H.data.Ystd = sqrt(Yvar); + +% only consider non-zero areas for Ystd and threshold Ymean +ind = H.data.Ystd ~= 0 & H.data.Ymean > H.data.global & mask(:); + +if job.verb, cat_progress_bar('Init',n_subjects,'Calculate Z-score'); end + +H.data.avg_abs_zscore = zeros(n_subjects,1); +for i = 1:n_subjects + + if H.mesh_detected + Ytmp = spm_data_read(H.files.V(i)); + else + Ytmp(:,:,:) = H.files.V(i).dat(:,:,:); + end + Ytmp(~isfinite(Ytmp)) = 0; + + if is_gSF + Ytmp = Ytmp*gSF(i)/mean(gSF); + end + + % correct for nuisance + if ~isempty(G) + for j = 1:size(Beta,2) + Ytmp(:) = Ytmp(:) - double(G(i,j)*Beta(:,j)); + end + end + + % calculate Z-score + zscore = (Ytmp(ind) - H.data.Ymean(ind))./H.data.Ystd(ind); + + % use mean of Z-score as overall measure, but emphasize outliers by + % using power operation + power_scale = 4; + H.data.avg_abs_zscore(i) = mean((abs(zscore).^power_scale))^(1/power_scale); + if job.verb, cat_progress_bar('Set',i); end +end + +if job.verb, cat_progress_bar('Clear'); end + +if isfield(job,'sites') && ~isempty(job.sites) + if numel(job.sites{1}) == numel(H.files.fname) + sites = job.sites{1}'; + else + cat_io_cprintf('err', ... + sprintf(' Warning number of site enties does not fit to the number of scans (%d/=%d).\n', ... + numel(job.sites{1}), numel(H.files.fname) ) ); + sites = []; + end +else + sites = []; +end + +if H.isxml +% RD20250913: added normalized SIQR measure +% ------------------------------------------------------------------------- + if isfield(xml.qualityratings,'NCR'), SIQR = H.xml.QM(:,3); else, SIQR = H.xml.QM(:,1); end % use SIQR or NCR + if isempty(sites) + % use site or resolution measures as approximation + [nsites,~,sites] = unique(round(res_RMS,3)); + % in case of too many sites focus on one + if numel(sites) / numel(nsites) < 5, sites = ones(size(res_RMS)); end + end + + % estimate rating (use the ""better"" quantil for linear normalization for each site) + NSIQR = cat_tst_qa_normer( SIQR , struct( 'sites' , sites , 'figure' , 0, 'model' , 0, 'cmodel' , 1)); + + % extend + H.xml.QM(:,end+1) = NSIQR; + H.xml.QM_names = char( [ cellstr(H.xml.QM_names); {'Normalized SIQR (nSIQR)'} ] ); + H.xml.QM_names_multi = char( [ cellstr(H.xml.QM_names_multi); {'nSIQR & Quartic Mean Z-score'} ]); + H.xml.QM_order(end+1) = H.userps; +else + if isempty(sites) + sites = ones(size(H.files.fname)); + end +end +H.sites = sites; + + +% save the rating +Pcsv = fullfile(pwd, sprintf('CheckSampleHomogeneity_%0.0fsubjects_%0.0fsites_%s.csv', ... + numel(H.files.fname), numel(unique(sites)), char(datetime('now','format','yyyyMMdd-HHmm')) )); +if H.isxml + tab = [ + {'fname', 'site', 'res_RMS', 'SIQR','nSIQR','zscore'}; + H.files.fname, num2cell(sites), num2cell(res_RMS), num2cell(SIQR), num2cell(NSIQR), num2cell(H.data.avg_abs_zscore); + ]; +else + tab = [ + {'fname', 'site', 'zscore'}; + H.files.fname, num2cell(sites), num2cell(H.data.avg_abs_zscore); + ]; +end +cat_io_csv(Pcsv,tab); +fprintf('Write csv-table:\n'); +cat_io_cprintf('blue',sprintf(' %s\n',Pcsv)); + + + + +% get data for each subject in longitudinal designs +if H.repeated_anova + if isfield(job.factorial_design,'des') + fsubject = job.factorial_design.des.fblock.fsuball.fsubject; + n_subjects_long = numel(fsubject); + H.ind_subjects_long = cell(numel(fsubject),1); + n = 0; + for i = 1:n_subjects_long + n_scans = numel(fsubject(i).scans); + % find time points in all subjects + H.ind_subjects_long{i} = ismember(1:n_subjects,n + (1:n_scans)); + n = n + n_scans; + end + else + [rw,cl] = find(SPM.xX.I == length(SPM.xX.iB)); % find column which codes subject factor (length(SPM.xX.iB) -> n_subj) + subj_col = cl(1); + n_subjects_long = max(SPM.xX.I(:,subj_col)); + + H.ind_subjects_long = cell(n_subjects_long,1); + n = 0; + for i = 1:n_subjects_long + ind_subj = find(SPM.xX.I(:,subj_col)==i); + n_scans = numel(ind_subj); + % find time points in all subjects + H.ind_subjects_long{i} = ismember(1:n_subjects,n + (1:n_scans)); + n = n + n_scans; + end + + end +end + +% voxelsize and origin of volume data +if ~H.mesh_detected + H.data.vx = sqrt(sum(H.files.V(1).mat(1:3,1:3).^2)); + H.data.Orig = H.files.V(1).mat\[0 0 0 1]'; +end + +% positions & font size +ws = spm('Winsize','Graphics'); +H.FS = cat_get_defaults('extopts.fontsize'); + +popb = [0.038 0.035]; % size of the small buttons +popm = 0.780; % x-position of the control elements + +H.pos = struct(... + 'fig', [10 10 1.3*ws(3) 1.1*ws(3)],...% figure + 'cbar', [0.045 0.035 0.700 0.020],... % colorbar for figure + 'plot', [0.050 0.050 0.700 0.825],... % scatter plot + ... + 'close', [0.775 0.935 0.100 0.040],... % close button + 'show', [0.875 0.935 0.100 0.040],... % button to show worst cases + 'scat', [0.775 0.880 0.100 0.050],... % button to enable ordered matrix + 'boxp', [0.875 0.880 0.100 0.050],... % button to display boxplot + ... + ... == navigation unit == + 'scSelect', [popm+popb(1)*0 0.820 popb],... % select (default) + 'scZoomReset', [popm+popb(1)*1 0.820 popb],... % standard zoom + 'scZoomIn', [popm+popb(1)*2 0.820 popb],... % zoom in + 'scZoomOut', [popm+popb(1)*3 0.820 popb],... % zoom out + 'scPan', [popm+popb(1)*4 0.820 popb],... % pan (moving hand) + ... + ... == remove unit == + 'rmDel', [popm+popb(1)*0 0.750 popb],... % delete + 'rmUndo', [popm+popb(1)*1 0.750 popb],... % undo deletion + 'rmNew', [popm+popb(1)*2 0.750 popb],... % calculate new + 'rmListNew', [popm+popb(1)*3 0.750 popb],... % list remaining data + 'rmListDel', [popm+popb(1)*4 0.750 popb],... % list removed data + ... + ... == display unit == + 'dpReport', [popm+popb(1)*0 0.680 popb],... % report + 'dpReportLong',[popm+popb(1)*1 0.680 popb],... % report + 'dpRaw', [popm+popb(1)*2 0.680 popb],... % raw data + 'dpRawP0', [popm+popb(1)*3 0.680 popb],... % raw data + p0 + 'dpLog', [popm+popb(1)*4 0.680 popb],... % log + ... + ... == check boxes == + 'fnambox',[0.775 0.600 0.200 0.050],... % show filenames? + 'plotbox',[0.875 0.600 0.200 0.050],... % switch between boxplot and violin plot + ... + ... == slice display == + 'text', [0.775 0.450 0.200 0.150],... % textbox with info + 'aslider',[0.775 0.405 0.200 0.040],... % slider for alpha overlay + 'slice', [0.775 0.030 0.200 0.400],... % slice images according to position of mouse pointer + 'zslider',[0.775 0.020 0.200 0.040]); % slider for z-slice + +% use this window for Fgraph +if isfield(job,'new_fig') && job.new_fig + H.Fgraph = spm_figure('GetWin','Homogeneity'); +else + H.Fgraph = spm_figure('GetWin','Graphics'); +end + +% correct position so to prevent overlapping windows +pos = get(H.Fgraph,'Position'); +set(H.Fgraph,'Position',[H.pos.fig(1)+H.pos.fig(3)+10 pos(2:4)]); + +if ~H.mesh_detected + % correct filenames for 4D data + if strcmp(H.files.fname{1}, H.files.fname{2}) + H.names_changed = true; + H.files.Vchanged = H.files.V; + for i=1:n_subjects + [pth,nam,ext] = spm_fileparts(H.files.fname{i}); + H.files.fname{i} = fullfile(pth, [nam sprintf('%04d',i) ext]); + end + end +end + +if job.verb, fprintf('\n'); end +fname_m = []; +fname_tmp = cell(n_samples,1); +fname_s = cell(n_samples,1); +fname_e = cell(n_samples,1); +for i=1:n_samples + + % get common filename (for repeated Anova use all data otherwise data for + % that sample) + if H.repeated_anova + [tmp, fname_tmp{i}] = spm_str_manip(char(H.files.fname),'C'); + else + [tmp, fname_tmp{i}] = spm_str_manip(char(H.files.fname{H.sample == i}),'C'); + end + if ~isempty(fname_tmp{i}) + fname_m = [fname_m; fname_tmp{i}.m]; + fname_s{i} = fname_tmp{i}.s; + fname_e{i} = fname_tmp{i}.e; + else + fname_s{i} = ''; + fname_e{i} = ''; + end + if job.verb + try + %% try some colorful output to make it easier to read + % suppress too long outputs + breaks(1) = find(tmp=='{',1,'first'); + breaks(2) = find(tmp=='}',1,'last'); + + fprintf('Compressed filenames sample %d: ',i); + + cat_io_cprintf([0.0 0.2 .8], '%s', tmp(1:breaks(1)-1)); + % to long cmd line output can cause java errors + if numel(tmp(breaks(1):breaks(2))) < 1000 + cmdlinelim = 120; % 1.5 times as usual ? + tmptmp = [' ...\n ' tmp(breaks(1):breaks(2))]; + for tmpi = flip(cmdlinelim+8:cmdlinelim:numel(tmptmp)) + closekomma = find(tmptmp(1:tmpi)==',',1,'last'); + tmptmp = [tmptmp(1:closekomma) ' ...\n ' tmptmp(closekomma+1:end)]; + end + cat_io_cprintf([0.5 0.0 .5], sprintf('%s', tmptmp)); + else + cat_io_cprintf([0.5 0.0 0], '%s', '{...TOO_LONG_SUPPRESSED...}'); + end + cat_io_cprintf([0.0 0.2 .8], '%s', tmp(breaks(2)+1:end)); + fprintf('\n'); + catch + fprintf('Compressed filenames sample %d: %s \n',i,tmp); + end + end +end + +H.filename = struct('s',{fname_s},'e',{fname_e},'m',{fname_m}); + +% sort data +[H.data.avg_abs_zscore_sorted, H.ind_sorted] = sort(H.data.avg_abs_zscore,'ascend'); + +threshold_zsc = mean(H.data.avg_abs_zscore) + 2*std(H.data.avg_abs_zscore); +n_thresholded = find(H.data.avg_abs_zscore_sorted > threshold_zsc, 1 ); + +if ~isempty(n_thresholded) && job.verb + fprintf('\nThese data have a quartic mean Z-score above 2 standard deviations.\n'); + fprintf('This does not necessarily mean that you have to exclude these data. However, these data have to be carefully checked:\n'); + + fprintf('SIQR / nSIQR / Quartic mean Z-score / filename\n'); + for i = n_thresholded:n_subjects % just switch this improve readability in case of different fname length + if isfield(H.xml,'QM') && ~isempty(H.xml.QM) + cat_io_cprintf([0.5 0 0.5],' %3.3f:', H.xml.QM(i,end-1:end) ); + end + cat_io_cprintf([0.5 0 0.5],' %3.3f: %s \n', H.data.avg_abs_zscore_sorted(i) ,H.files.fname{H.ind_sorted(i)}); + end + fprintf('\n'); +end + +if nargout>0 + varargout{1} = struct('table',{[H.files.fname,num2cell(H.data.avg_abs_zscore)]},... + 'sorttable',{[H.files.fname(H.ind_sorted),num2cell(H.data.avg_abs_zscore_sorted)]},... + 'zscore',H.data.avg_abs_zscore,... + 'threshold_zsc',threshold_zsc); +end + + +if job.verb + + create_menu; + show_boxplot(H.data.avg_abs_zscore,'Quartic Mean Z-score ',-1); + + if isfield(job,'save') && job.save + %% filenames + if ~isempty(job.fname) + dpi = cat_get_defaults('print.dpi'); + if isempty(dpi), dpi = 150; end + + fignames = {'matrix','boxplot'}; + figuresids = {figure(2),H.Fgraph}; + if isempty(job.outdir{1}), job.outdir{1} = pwd; end + + % save + warning('OFF','MATLAB:print:UIControlsScaled'); + for i=1:2 + fname = fullfile(job.outdir{1},[job.fname fignames{i} '.png']); + print(figuresids{i}, '-dpng', '-opengl', sprintf('-r%d',dpi), fname); + end + warning('ON','MATLAB:print:UIControlsScaled'); + end + + %% close + if job.save>1 + spm_figure('Clear','Graphics'); + for i=2:26, try, close(i); end; end + end + end + + % we have to update slice array first if not defined + if ~isfield(H.data,'vol') && ~H.mesh_detected + preload_slice_data; + end +end + +%----------------------------------------------------------------------- +function create_menu +%----------------------------------------------------------------------- +global H + +% create figure +H.mainfig = figure(22); +clf(H.mainfig); + +set(H.mainfig,... + 'MenuBar','none',... + 'Position',H.pos.fig,... +... 'DefaultTextFontSize',H.FS,... +... 'DefaultUicontrolFontSize',H.FS,... + 'NumberTitle','off'); + +if H.mesh_detected + set(H.mainfig,'Name','Click in image to display surfaces'); +else + set(H.mainfig,'Name','Click in image to display slices'); +end + +cm = datacursormode(H.mainfig); +set(cm,'UpdateFcn',@myupdatefcn,'SnapToDataVertex','on','Enable','on'); +try + set(cm,'Interpreter','none','NewDataCursorOnClick',false); +end + +% add colorbar +H.ui.cbar = axes('Position',H.pos.cbar,'Parent',H.mainfig); +try, image(H.ui.cbar);end +set(get(H.ui.cbar,'children'),'HitTest','off','Interruptible','off'); +set(H.ui.cbar,'Ytick',[],'YTickLabel',''); + +%colormap(H.cmap) +colormap(jet) + +% add button for closing all windows +H.ui.close = uicontrol(H.mainfig,... + 'String','Close','Units','normalized',... + 'Position',H.pos.close,... + 'Style','Pushbutton','HorizontalAlignment','center',... + 'Callback','for i=2:26, try close(i); end; end;',... + 'ToolTipString','Close windows',...d + 'Interruptible','on','Enable','on'); + +% check button +H.ui.show = uicontrol(H.mainfig,... + 'String','Check worst','Units','normalized',... + 'Position',H.pos.show,... + 'Style','Pushbutton','HorizontalAlignment','center',... + 'Callback',@check_worst_data,... + 'ToolTipString','Display most deviating files',... + 'Interruptible','on','Enable','on'); + +%% create popoup menu for boxplot + +% check whether we have to add entries from quality measures or covariates +if isempty(H.xml.QM) + str = { 'Boxplot','Quartic Mean Z-score'}; + % average quartic Z-score vs. file order + H.X = [H.data.avg_abs_zscore (1:numel(H.data.avg_abs_zscore))']; + show_QMzscore(H.X,0, H.userps); % show file order on x-axis +else + % average quartic Z-score vs. QM measures + H.X = [H.data.avg_abs_zscore H.xml.QM]; + + str = { 'Boxplot','Quartic Mean Z-score'}; + for i = 1:size(H.xml.QM,2) + str{i+2} = deblank(H.xml.QM_names(i,:)); + end + + if H.isxml + % estimate product between structural quality rating (SIQR) and quartic mean Z-score + H.xml.QMzscore = H.X(:,1).*H.X(:,2); + str{i+3} = 'SIQR (grad) x Quartic Mean Z-score'; + show_QMzscore(H.X,4, H.userps); % show SIQR on x-axis + else + show_QMzscore(H.X,0, H.userps); % show file order on x-axis + end +end + +tmp = { {@show_boxplot, H.data.avg_abs_zscore, 'Quartic Mean Z-score', -1}}; +for i = 1:size(H.xml.QM,2) + tmp{i+1} = {@show_boxplot, H.xml.QM(:,i), deblank(H.xml.QM_names(i,:)), H.xml.QM_order(i)}; +end + +if H.isxml + tmp{i+2} = {@show_boxplot, H.xml.QMzscore, 'SIQR x Quartic Mean Z-score ', -1}; +end + +H.ui.boxp = uicontrol(H.mainfig,... + 'String',str,'Units','normalized',... + 'Position',H.pos.boxp,'UserData',tmp,... + 'Style','PopUp','HorizontalAlignment','center',... + 'Callback','spm(''PopUpCB'',gcbo)',... + 'ToolTipString','Display boxplot',... + 'Interruptible','on','Visible','on'); + +%% create popoup menu for scatterplot + +% if QM values are available allow SIQR and surface parameters, but skip +% noise and bias as first 2 entries +str = { 'Scatterplot','Quartic Mean Z-score'}; +if isempty(H.xml.QM) + tmp = {{@show_QMzscore, H.X, 0, H.userps}}; % just quartic mean Z-score with file order +else + tmp = {{@show_QMzscore, H.X, 0, H.userps}}; % file order + if H.isxml + for i = 1:size(H.xml.QM,2)-2 + str{i+2} = deblank(H.xml.QM_names_multi(i+2,:)); + tmp{i+1} = {@show_QMzscore, H.X, i+3, H.xml.QM_order(i+2)}; + end + else + for i = 1:size(H.xml.QM,2) + str{i+2} = deblank(H.xml.QM_names_multi(i,:)); + tmp{i+1} = {@show_QMzscore, H.X, i+1, H.xml.QM_order(i)}; + end + end +end + +H.ui.scat = uicontrol(H.mainfig,... + 'String',str,'Units','normalized',... + 'Position',H.pos.scat,'UserData',tmp,... + 'Style','PopUp','HorizontalAlignment','center',... + 'Callback','spm(''PopUpCB'',gcbo)',... + 'ToolTipString','Sort matrix',... + 'Interruptible','on','Visible','on'); + +H.ui.text = uicontrol(H.mainfig,... + 'Units','normalized','position',H.pos.text,... + 'String',{'','Click in image to display slices'},... + 'Style','text','HorizontalAlignment','center',... + 'ToolTipString','Select slice for display',... + 'FontSize',H.FS-2,'Visible','off','BackgroundColor',[0.8 0.8 0.8]); + +%% == zoom unit == +H.naviui.text = uicontrol(H.mainfig,... + 'Units','normalized','Style','text',... + 'Position',[H.pos.scSelect(1) H.pos.scSelect(2)+0.042 0.2 0.02],... + 'String','Zoom options','FontSize',H.FS,'BackgroundColor',[0.8 0.8 0.8]); + +H.naviui.select = uicontrol(H.mainfig,... + 'Units','normalized','position',H.pos.scSelect,'callback',... + ['datacursormode(''on''); global H;' ... + 'set(H.naviui.select,''BackGroundColor'',[0.95 0.95 0.95]);'],... + 'Style','Pushbutton','enable','on','ToolTipString','Data selection','CData',load_icon('tool_pointer.png'),'BackGroundColor',[0.95 0.95 0.95]); + +H.naviui.zoomReset = uicontrol(H.mainfig,... + 'Units','normalized','position',H.pos.scZoomReset,'callback',... + ['zoom out; zoom reset; datacursormode(''on''); global H;' ... + 'set(H.naviui.select,''BackGroundColor'',[0.94 0.94 0.94]);'],... + 'Style','Pushbutton','enable','on','ToolTipString','Reset view','CData',load_icon('tool_fit.png')); + +H.naviui.zoomIn = uicontrol(H.mainfig,... + 'Units','normalized','position',H.pos.scZoomIn,'callback',... + ['global H; ' ... + 'hz = zoom(H.ax); set(hz,''enable'',''on'',''direction'',''in'');' ... + 'set(H.naviui.select,''BackGroundColor'',[0.94 0.94 0.94]);'], ... + 'Style','Pushbutton','enable','on','ToolTipString','Zoom in','CData',load_icon('tool_zoom_in.png')); + +H.naviui.zoomOut = uicontrol(H.mainfig,... + 'Units','normalized','position',H.pos.scZoomOut,'callback',... + ['global H; ' ... + 'hz = zoom(H.ax); set(hz,''enable'',''on'',''direction'',''out''); ' ... + 'set(H.naviui.select,''BackGroundColor'',[0.94 0.94 0.94]);'], ... + 'Style','Pushbutton','enable','on','ToolTipString','Zoom out','CData',load_icon('tool_zoom_out.png')); + +H.naviui.pan = uicontrol(H.mainfig,... + 'Units','normalized','position',H.pos.scPan,'Enable','off','callback',... + 'pan on; set(H.naviui.select,''BackGroundColor'',[0.94 0.94 0.94]);',... + 'Style','Pushbutton','enable','on','ToolTipString','Hand','CData',load_icon('tool_hand.png')); + +%% == remove unit == +H.delui.text = uicontrol(H.mainfig,... + 'Units','normalized','Style','text',... + 'Position',[H.pos.rmDel(1) H.pos.rmDel(2)+0.042 0.2 0.02],... + 'String','Data remove options','FontSize',H.FS,'BackgroundColor',[0.8 0.8 0.8]); + +H.delui.remove = uicontrol(H.mainfig,... + 'Units','normalized','position',H.pos.rmDel,'callback',{@remove_point},... + 'Style','Pushbutton','enable','off','ToolTipString','Remove this data point','CData',load_icon('file_delete.png')); + +H.delui.undo = uicontrol(H.mainfig,... + 'Units','normalized','position',H.pos.rmUndo,'callback',{@do_rerun,1},... + 'Style','Pushbutton','enable','off','ToolTipString','Undo all deletions','CData',load_icon('file_delete_restore.png')); + +H.delui.new = uicontrol(H.mainfig,... + 'Units','normalized','position',H.pos.rmNew,'callback',{@get_new_list,1},... + 'Style','Pushbutton','enable','off','ToolTipString','Refresh without removed data','CData',load_icon('refresh.png')); + +H.delui.list_del = uicontrol(H.mainfig,... + 'Units','normalized','position',H.pos.rmListDel,'callback',{@get_new_list,-1},... + 'Style','Pushbutton','enable','off','ToolTipString','List removed data','CData',load_icon('list_del.png')); + +if isfield(H.job,'factorial_design') + icon = load_icon('greenarrowicon.png'); + str = 'Create new analysis without removed data'; +else + icon = load_icon('list_new.png'); + str = ' List remaining data'; +end + +H.delui.analysis_new = uicontrol(H.mainfig,... + 'Units','normalized','position',H.pos.rmListNew,'callback',{@get_new_list,0},... + 'Style','Pushbutton','enable','off','ToolTipString',str,'CData',icon); + +%% == display unit == +H.dpui.text = uicontrol(H.mainfig,... + 'Units','normalized','Style','text',... + 'Position',[H.pos.dpReport(1) H.pos.dpReport(2)+0.042 0.2 0.02],... + 'String','Data display options','FontSize',H.FS,'BackgroundColor',[0.8 0.8 0.8]); + +% enable some buttons only if respective files are available +if H.isxml, H.status.xml = true; +else H.status.xml = false; end + +if isfield(H.files,'raw') && ~isempty(H.files.raw{1}), H.status.raw = true; +else H.status.raw = false; end + +if isfield(H.files,'p0') && ~isempty(H.files.p0{1}), H.status.p0 = true; +else H.status.p0 = false; end % && ~isempty(H.files.raw{numel(H.sample)}) + +H.status.rawp0 = H.status.raw && H.status.p0; + +if isfield(H.files,'log') && ~isempty(H.files.log{1}), H.status.log = true; +else H.status.log = false; end + +if H.repeated_anova && isfield(H.files,'jpg_long') && ~isempty(H.files.jpg_long{1}), H.status.reportlong = true; +else H.status.reportlong = false; end + +if isfield(H.files,'jpg') && ~isempty(H.files.jpg{1}), H.status.report = true; +else H.status.report = false; end + +H.dpui.report = uicontrol(H.mainfig,... + 'Units','normalized','position',H.pos.dpReport,'callback',{@show_report,false},... + 'Style','Pushbutton','enable','off','ToolTipString','Show report file','CData',load_icon('file_cat_report.png')); + +H.dpui.reportlong = uicontrol(H.mainfig,... + 'Units','normalized','position',H.pos.dpReportLong,'callback',{@show_report,true},... + 'Style','Pushbutton','enable','off','ToolTipString','Show longitudinal report file','CData',load_icon('file_cat_reportlong.png')); + +H.dpui.raw = uicontrol(H.mainfig,... + 'Units','normalized','position',H.pos.dpRaw,'callback',{@show_raw,false},... + 'Style','Pushbutton','enable','off','ToolTipString','Show raw data','CData',load_icon('file_spm_view.png')); + +H.dpui.rawp0 = uicontrol(H.mainfig,... + 'Units','normalized','position',H.pos.dpRawP0,'callback',{@show_raw,true},... + 'Style','Pushbutton','enable','off','ToolTipString','Show overlayed label','CData',load_icon('file_spm_view_p0.png')); + +H.dpui.log = uicontrol(H.mainfig,... + 'Units','normalized','position',H.pos.dpLog,'callback',{@show_log},... + 'Style','Pushbutton','enable','off','ToolTipString','Show log file','CData',load_icon('file_cat_log.png')); + +% add slider and opacity control only for volume data +if ~H.mesh_detected + H.ui.alpha = uicontrol(H.mainfig,... + 'Units','normalized','position',H.pos.aslider,... + 'Min',0,'Max',1,... + 'Style','slider','HorizontalAlignment','center',... + 'callback',@update_alpha,'Value',0.5,... + 'ToolTipString','Change Opacity of pos. (blue colors) and neg. (red colors) Z-scores',... + 'SliderStep',[0.01 0.1],'Visible','off'); + + H.ui.alpha_txt = uicontrol(H.mainfig,... + 'Units','normalized','HorizontalAlignment','center',... + 'Style','text','BackgroundColor',[0.8 0.8 0.8],... + 'Position',[H.pos.aslider(1) H.pos.aslider(2)-0.005 0.2 0.02],... + 'String','Overlay Opacity of Z-score',... + 'FontSize',H.FS-2,'Visible','off'); + + H.ui.mm = uicontrol(H.mainfig,... + 'Units','normalized','position',H.pos.zslider,... + 'Min',(1 - H.data.Orig(3))*H.data.vx(3),'Max',(H.files.V(1).dat.dim(3) - H.data.Orig(3))*H.data.vx(3),... + 'Style','slider','HorizontalAlignment','center',... + 'callback',@update_slices_array,... + 'ToolTipString','Select slice for display',... + 'SliderStep',[0.005 0.05],'Visible','off'); + + H.ui.mm_txt = uicontrol(H.mainfig,... + 'Units','normalized','HorizontalAlignment','center',... + 'Style','text','BackgroundColor',[0.8 0.8 0.8],... + 'Position',[H.pos.zslider(1) H.pos.zslider(2)-0.005 0.2 0.02],... + 'String','Slice [mm]','Visible','off','FontSize',H.FS-2); + +end + +return + +%----------------------------------------------------------------------- +function icon = load_icon(name) +%----------------------------------------------------------------------- + +icon = imread(fullfile(fileparts(mfilename('fullpath')),'doc','icons',name)); +icon = double(icon)./double(max(icon(:))); icon(icon==0) = 0.94; + +return + +%----------------------------------------------------------------------- +function check_worst_data(obj, event_obj) +%----------------------------------------------------------------------- +% Old check worst function. The spm_input could be replaced by an popup +% window. A specification of the data range would rather than the x worst +% images would be useful. +%----------------------------------------------------------------------- +global H + +if isempty(spm_figure('FindWin','Interactive')), spm('createintwin'); end + +if isfield(H,'delui') && isfield(H.delui,'remove') set(H.delui.remove,'Enable','off'); end +if isfield(H,'status') + if H.status.report, set(H.dpui.report, 'enable','off','BackgroundColor',[0.94 0.94 0.94]); end + if H.status.raw, set(H.dpui.raw, 'enable','off','BackgroundColor',[0.94 0.94 0.94]); end + if H.status.rawp0, set(H.dpui.rawp0, 'enable','off','BackgroundColor',[0.94 0.94 0.94]); end + if H.status.log, set(H.dpui.log, 'enable','off','BackgroundColor',[0.94 0.94 0.94]); end + if H.status.reportlong, set(H.dpui.reportlong,'enable','off','BackgroundColor',[0.94 0.94 0.94]); end +end + +n = length(H.files.V); +number = min([n 24]); +number = spm_input('How many files ?',1,'e',number); +number = min([number 24]); +number = min([number length(H.files.V)]); + +ind_sorted_decreased = flipud(H.ind_sorted_display); + +list = char(H.files.fname{ind_sorted_decreased}); +sample = H.sample(ind_sorted_decreased); +list2 = list(1:number,:); + +if H.mesh_detected + % display single meshes and correct colorscale of colorbar + for i=1:number + h = cat_surf_render2(struct('vertices',H.Pmesh.vertices,'faces',H.Pmesh.faces,'cdata',H.texture(:,ind_sorted_decreased(i)))); + + % shift each figure slightly + if i==1 + pos = get(h.figure,'Position'); + else + pos = pos - [20 20 0 0]; + end + + % remove menubar and toolbar, use filename as title + set(h.figure,'MenuBar','none','Toolbar','none','Name',sprintf('Sample %d: %s',sample(i),list2(i,:)),... + 'NumberTitle','off','Position',pos); + cat_surf_render2('ColourMap',h,jet); + cat_surf_render2('ColourBar',h,'on'); + cat_surf_render2('CLim',h,H.data.range98); + end +else + spm_check_registration(list2); + spm_orthviews('Resolution',0.2); + set(H.ui.boxp,'Visible','on'); + + % add short name to caption + for i=1:number + txt = {{spm_str_manip(list2(i,:),'k30'),sprintf('Mean abs Z-score: %g',H.data.avg_abs_zscore(ind_sorted_decreased(i)))}}; + if H.isxml + txt{1}{3} = sprintf('SIQR: %g',H.X(ind_sorted_decreased(i),4)); + end + spm_orthviews('Caption',i,txt); + end +end +return + +%----------------------------------------------------------------------- +function checkbox_names(obj, event_obj) +%----------------------------------------------------------------------- +global H + + H.ui.show_name = get(H.ui.fnambox,'Value'); + show_boxplot; + +return + +%----------------------------------------------------------------------- +function checkbox_plot(obj, event_obj) +%----------------------------------------------------------------------- + global H + + H.ui.show_violin = get(H.ui.plotbox,'Value'); + show_boxplot; + +return + +%----------------------------------------------------------------------- +function show_QMzscore(X, sel, quality_order) +%----------------------------------------------------------------------- +global H + +if nargin < 3 + quality_order = -1; +end + +% delete old data tip +delete(findall(H.mainfig,'Type','hggroup')) + +if ~H.mesh_detected && isfield(H.ui,'alpha') + set(H.ui.alpha, 'Visible','off'); + set(H.ui.alpha_txt,'Visible','off'); + set(H.ui.mm, 'Visible','off'); + set(H.ui.mm_txt, 'Visible','off'); +end + +if isfield(H.ui,'alpha'), set(H.ui.text,'Visible','off'); end +if isfield(H,'delui') && isfield(H.delui,'remove') + set(H.delui.remove,'Enable','off'); +end + +if isfield(H,'status') + if H.status.report, set(H.dpui.report, 'enable','off'); end + if H.status.raw, set(H.dpui.raw, 'enable','off'); end + if H.status.rawp0, set(H.dpui.rawp0, 'enable','off'); end + if H.status.log, set(H.dpui.log, 'enable','off'); end + if H.status.reportlong, set(H.dpui.reportlong,'enable','off'); end +end + +H.sel = sel; + +% clear larger area and set background color to update labels and title +H.ax = axes('Position',[-.1 -.1 1.1 1.1],'Parent',H.mainfig); +cla(H.ax); +set(H.ax,'Color',[0.8 0.8 0.8]); + +H.ax = axes('Position',H.pos.plot,'Parent',H.mainfig,'Color',[.6 .6 .6]); +axes(H.ax); +grid on + +% estimate product between QM-value and quartic mean Z-score +if sel + if H.userps > 0 + % in case of the percentage scoring, we first have to go back to marks + % in case of the normalized percentage scoring, no tranthe order changes the default is zero + if sel == 5 + rps2mark = @(rps) quality_order * (0 - rps/10); + else + rps2mark = @(rps) quality_order * (10.5 - rps/10); + end + else + rps2mark = @(rps) -quality_order * rps; + end + H.xml.QMzscore = X(:,1) .* max(0,rps2mark( X(:,sel) )); +else + H.xml.QMzscore = X(:,1); +end + +% get min/max in 0.25 steps +min_QMzscore = min(H.xml.QMzscore(H.ind)); min_QMzscore = floor(4*min_QMzscore)/4; +max_QMzscore = max(H.xml.QMzscore(H.ind)); max_QMzscore = ceil(4*max_QMzscore)/4; +if min_QMzscore == max_QMzscore + max_QMzscore = max_QMzscore + 0.5; +end +if sel==5 + % RD202509: in principle the QMs are scaled with .5 for light and 1.0 for clear motion artifacts + max_QMzscore = max_QMzscore + max(0,min_QMzscore + 1 - max_QMzscore); % grad system +end + +% because we use a splitted colormap we have to set the color +% values explicitely +QMzscore_scaled = 63*(H.xml.QMzscore-min_QMzscore) / (max_QMzscore - min_QMzscore); % scale min..max + +H.C = zeros(length(H.xml.QMzscore),3); +for i=1:length(H.xml.QMzscore) + indc = min(128,round(QMzscore_scaled(i))+1); + H.C(i,:) = H.cmap(indc,:); +end + +% create marker for different samples +marker = char('o','s','d','^','v','<','>','.','+','*'); +while max(H.sample) > numel(marker), marker = [marker; marker]; end + +if sel % show QM measure on x-axis + xx = X(:,sel); + yy = X(:,1); + if H.userps > 0, set(gca, 'XDir','reverse'); end + if quality_order > 0 % reverse xdir ! + xstr = sprintf('<----- Best --- %s --- Worst ------> ',deblank(H.xml.QM_names(sel-1,:))); + elseif quality_order < 0 % reverse xdir ! + xstr = sprintf('<----- Worst --- %s --- Best ------> ',deblank(H.xml.QM_names(sel-1,:))); + else + xstr = sprintf('%s',deblank(H.xml.QM_names(sel-1,:))); + end + +else % show file order on x-axis + xx = 1:numel(X(:,1)); + yy = X(:,1); + xstr = sprintf('<----- First --- File --- Last ------> '); +end + +% scatterplot +hold on +for i = 1:max(H.sample) + ind = H.sample.*H.ind == i; + H.ui.scatter = scatter(H.ax,xx(ind),yy(ind),30,H.C(ind,:),marker(i),'Linewidth',1); + MarkerEdgeColor = get(H.ui.scatter,'MarkerEdgeColor'); + set(H.ui.scatter,'MarkerFaceColor',MarkerEdgeColor,'MarkerFaceAlpha',0.4,'MarkerEdgeAlpha',0.5); +end + +% connect points of each subject for long. designs +if H.repeated_anova + + % use SIQR*zscore if available + if sel == 4 + measure = H.X(:,sel).*H.data.avg_abs_zscore; + else + measure = H.data.avg_abs_zscore; + end + + cm = jet(64); + ind = cell(numel(H.ind_subjects_long),1); + diff_measure = zeros(numel(H.ind_subjects_long),1); + + % get difference between extreme values for each subject + for i = 1:numel(H.ind_subjects_long) + ind{i} = H.ind.*H.ind_subjects_long{i} > 0; + if any(ind{i}) + diff_measure(i) = max(measure(ind{i}))-min(measure(ind{i})); + end + end + + % scale difference measure to a range 1..64 and use jet-colors for lines + diff_measure = 1 + round(63*(diff_measure - min(diff_measure))/(max(diff_measure)-min(diff_measure))); + for i = 1:numel(H.ind_subjects_long) + hp = plot(xx(ind{i}),yy(ind{i})); + set(hp, 'Color',cm(diff_measure(i),:),'LineWidth',diff_measure(i)/20); + end + title('The lines show the time points of each subject with color and thickness in relation to the magnitude of the differences'); +end +hold off + +if ~sel + xlim([0 numel(H.sample)+1]); +end + +xlabel(xstr,'FontSize',H.FS-1,'FontWeight','Bold'); +ylabel('<----- Best --- Quartic Mean Z-score --- Worst ------> ','FontSize',H.FS-1,'FontWeight','Bold'); + +% add colorbar +H.ui.cbar = axes('Position',H.pos.cbar+[0 0.9 0 0],'Parent',H.mainfig); +image((1:64)); + +if sel + if ~quality_order + xstr = sprintf('%s x quartic mean Z-score',deblank(H.xml.QM_names(sel-1,:))); + else + xstr = sprintf('<----- Best --- %s (grad) x quartic mean Z-score --- Worst ------> ',deblank(H.xml.QM_names(sel-1,:))); + end +else + xstr = sprintf('<----- Best --- quartic mean Z-score --- Worst ------> '); +end +title(xstr,'FontSize',H.FS+1,'FontWeight','Bold'); + +colormap(H.cmap) + +% display YTick with 5 values (limit accuracy for floating numbers) +set(H.ui.cbar,'YTickLabel','','YTick','', 'XTick',linspace(1,64,5),'XTickLabel',... + round(100*linspace(min_QMzscore,max_QMzscore,5))/100,'TickLength',[0 0]); + +% update index of worst files +[tmp, H.ind_sorted_display] = sort(H.xml.QMzscore(H.ind),'ascend'); + +return + +%----------------------------------------------------------------------- +function show_boxplot(data_boxp, name_boxp, quality_order) +%----------------------------------------------------------------------- +global H + +if nargin == 0 + data_boxp = H.ui.bp.data; + name_boxp = H.ui.bp.name; + quality_order = H.ui.bp.order; +end + +H.show_sel = 1; +set(H.dpui.report, 'BackGroundColor',[0.94 0.94 0.94]); +set(H.dpui.reportlong,'BackGroundColor',[0.94 0.94 0.94]); +set(H.dpui.log, 'BackGroundColor',[0.94 0.94 0.94]); +set(H.dpui.raw, 'BackGroundColor',[0.94 0.94 0.94]); + +% only use SPM window if not defined +if ~isfield(H,'Fgraph') + H.Fgraph = spm_figure('GetWin','Graphics'); +end + +set(H.Fgraph,'Renderer','OpenGL'); +figure(H.Fgraph); +spm_figure('Select',H.Fgraph); +clf + +n_samples = max(H.sample); + +xpos = cell(1,n_samples); +data = cell(1,n_samples); + +hold on +allow_violin = true; +for i=1:n_samples + ind = find(H.sample(H.ind) == i); + if length(ind)<10 + allow_violin = false; + H.ui.show_violin = false; + end + data{i} = data_boxp(ind); + + if n_samples == 1 + xpos{i} = (i-1)+2*(0:length(ind)-1)/(length(ind)-1); + else + xpos{i} = 0.5/length(ind) + 0.5+(i-1)+1*(0:length(ind)-1)/(length(ind)); + end +end + +H.ui.fnambox = uicontrol(H.mainfig,... + 'String','Show filenames','Units','normalized',... + 'Position',H.pos.fnambox,'callback',@checkbox_names,... + 'Style','CheckBox','HorizontalAlignment','center',... + 'ToolTipString','Show filenames in boxplot','value',H.ui.show_name,... + 'BackgroundColor',[0.8 0.8 0.8],... + 'Interruptible','on','Visible','on','FontSize',H.FS-2); + +% allow violin plot onl if samples are all large enough +if allow_violin + H.ui.plotbox = uicontrol(H.mainfig,... + 'String','Violinplot','Units','normalized',... + 'Position',H.pos.plotbox,'callback',@checkbox_plot,... + 'Style','CheckBox','HorizontalAlignment','center',... + 'ToolTipString','Switch to Violinplot','value',H.ui.show_violin,... + 'BackgroundColor',[0.8 0.8 0.8],... + 'Interruptible','on','Visible','on','FontSize',H.FS-2); +end + +% colormap for samples +if exist('lines') + cm = lines(n_samples); +else + cm = jet(n_samples); +end +opt = struct('groupnum',0,'ygrid',0,'violin',2*H.ui.show_violin,'median',2,'groupcolor',cm); +ylim_add = 0.075; + +cat_plot_boxplot(data,opt); +set(gcf,'Color',[0.94 0.94 0.94]) + +hold on +for i=1:n_samples + ind = find(H.sample(H.ind) == i); + + for j=1:length(ind) + if H.ui.show_name + text(xpos{i}(j),data{i}(j),H.filename.m{ind(j)},'FontSize',H.FS-2,'HorizontalAlignment','center') + else + p = plot(xpos{i}(j),data{i}(j),'.'); + set(p,'Color',0.8*cm(i,:)); + end + end +end + +set(gca,'XTick',[],'XLim',[-.25 n_samples+1.25]); + +yamp = max(data_boxp) - min(data_boxp) + 0.001; +ylim_min = min(data_boxp) - ylim_add*yamp; +ylim_max = max(data_boxp) + ylim_add*yamp; +set(gca,'YLim',[ylim_min ylim_max]); + +% add colored labels and title +if n_samples > 1 + [tmp, tmp2] = spm_str_manip(char(H.filename.s),'C'); + while ~isempty(strfind(tmp,',,')), tmp = strrep(tmp,',,',','); end + title_str = sprintf('Boxplot: %s \n%s ',name_boxp, strrep(tmp,tmp2.s,'')); + fprintf('\nCommon filename: %s\n',tmp); +else + title_str = sprintf('Boxplot: %s \nCommon filename: %s*',name_boxp,spm_file(char(H.filename.s),'short25')); +end +title(title_str,'FontSize',H.FS-1,'FontWeight','Bold'); +xlabel('<----- First --- File Order --- Last ------> ','FontSize',H.FS+1,... + 'FontWeight','Bold'); + +xpos = -0.40 - n_samples*0.1; + +if (length(data_boxp) > 2) + if quality_order > 0 + text(xpos, ylim_min,'<----- Low rating ','Color','red','Rotation',... + 90,'HorizontalAlignment','left','FontSize',H.FS,'FontWeight','Bold') + text(xpos, ylim_max,'High rating ------> ','Color','blue','Rotation',... + 90,'HorizontalAlignment','right','FontSize',H.FS,'FontWeight','Bold') + elseif quality_order < 0 + text(xpos, ylim_max,'Low rating ------> ','Color','red','Rotation',... + 90,'HorizontalAlignment','right','FontSize',H.FS,'FontWeight','Bold') + text(xpos, ylim_min,'<----- High rating ','Color','blue','Rotation',... + 90,'HorizontalAlignment','left','FontSize',H.FS,'FontWeight','Bold') + end + text(xpos, (ylim_max+ylim_min)/2,sprintf('%s',name_boxp),'Color','black','Rotation',... + 90,'HorizontalAlignment','center','FontSize',H.FS,'FontWeight','Bold') +end + +hold off + +% estimate sorted index new for displaying worst files +if quality_order > 0 + [tmp, H.ind_sorted_display] = sort(data_boxp,'descend'); +else + [tmp, H.ind_sorted_display] = sort(data_boxp,'ascend'); +end + +H.ui.bp = struct('data',data_boxp,'name',name_boxp,'order',quality_order); +set(H.delui.remove,'Enable','off'); + +figure(H.mainfig) + +return + +%----------------------------------------------------------------------- +function show_glassbrain +%----------------------------------------------------------------------- +global H + +vol = H.files.V(H.mouse.x).dat(:,:,:); + +% get Z-score +Ymean = reshape(H.data.Ymean,H.files.V(1).dat.dim); +Ystd = reshape(H.data.Ystd,H.files.V(1).dat.dim); +zscore = (vol - Ymean)./Ystd; +ind = Ystd > 0 & (Ymean > H.data.global | vol > H.data.global); +zscore(~ind) = 0; + +% glassbrain +d1 = squeeze(sum(zscore,1)); +d2 = squeeze(sum(zscore,2)); +d3 = squeeze(sum(zscore,3)); + +sz = spm('WinSize','0',1) - H.pos.fig; sz = sz*0.75; sz(3) = sz(4)*1.4; + +if ~isfield(H,'mipfig') + H.mipfig = figure(23); +end + +figure(H.mipfig); + +cm = hot(64); +set(H.mipfig,'Menubar','none','NumberTitle','off','Name',sprintf('Sample %d: Z-score %s',... + H.sample(H.mouse.x),H.filename.m{H.mouse.x}),'Position',[10 H.pos.fig(4)+sz(4) sz(3:4)]); +colormap([1-(cm); cm]); + +mx2 = 2*max(H.files.V(H.mouse.x).dat.dim); + +subplot(2,2,1) +imagesc(rot90(-d1),[-mx2 mx2]) +axis off image + +subplot(2,2,2) +imagesc(rot90(-d2),[-mx2 mx2]) +axis off image + +subplot(2,2,3) +imagesc(-d3,[-mx2 mx2]) +axis off image + +subplot(2,2,4) +colorbar +set(gca,'CLim',[-3 3]); +axis off image + +return + +%----------------------------------------------------------------------- +function show_mesh +%----------------------------------------------------------------------- +global H + +if isfield(H,'hx') && isgraphics(H.hx.figure) + H.hx = cat_surf_render2('Overlay',H.hx,H.texture(:,H.mouse.x(1))); +else + H.hx = cat_surf_render2(struct('vertices',H.Pmesh.vertices,'faces',H.Pmesh.faces,'cdata',H.texture(:,H.mouse.x(1)))); + H.hx = cat_surf_render2('Colourbar',H.hx); +end +H.hx = cat_surf_render2('clim',H.hx,H.data.range98); + +sz = spm('WinSize','0',1) - H.pos.fig; sz = sz*0.75; sz(3) = sz(4)*1.4; +pos_hx = [10 H.pos.fig(4)+sz(4) sz(3:4)]; + +set(H.hx.figure,'Menubar','none','Toolbar','none','NumberTitle','off','Position',pos_hx,... + 'Name',sprintf('Sample %d: %s %s',H.sample(H.mouse.x),H.info.texture,H.filename.m{H.mouse.x(1)})) + +figure(H.hx.figure) + +% get Z-score +zscore = (H.texture(:,H.mouse.x(1)) - H.data.Ymean)./H.data.Ystd; +zscore(H.data.Ystd == 0) = 0; + +if isfield(H,'hy') && isgraphics(H.hy.figure) + H.hy = cat_surf_render2('Overlay',H.hy,zscore); +else + pos_hy = pos_hx; + pos_hy = pos_hy + [pos_hx(3)+5 0 0 0]; + H.hy = cat_surf_render2(struct('vertices',H.Pmesh.vertices,'faces',H.Pmesh.faces,'cdata',zscore)); + H.hy = cat_surf_render2('Colourbar',H.hy); + H.hy = cat_surf_render2('ColourMap',H.hy,cat_io_colormaps('BWR',64)); + set(H.hy.figure,'Position',pos_hy); +end + +H.hy = cat_surf_render2('clim',H.hy,[-3 3]); +set(H.hy.figure,'Menubar','none','Toolbar','none','NumberTitle','off','Name',sprintf('Sample %d: Z-score %s',H.sample(H.mouse.x(1)),H.filename.m{H.mouse.x(1)})); + +figure(H.hy.figure) + +return + +%----------------------------------------------------------------------- +function show_image_slice +%----------------------------------------------------------------------- +global H + +% add sliders for volume data +set(H.ui.mm,'Visible','on'); +set(H.ui.mm_txt,'Visible','on'); + +% we have to update slice array first if not defined +if ~isfield(H.data,'vol') + preload_slice_data; +end + +H.img = H.data.vol(:,:,H.mouse.x(1))'; + +% alpha overlay +H.img_alpha = H.data.zscore(:,:,H.mouse.x(1))'; + +% correct orientation +H.img = rot90(H.img,2); +H.img_alpha = rot90(H.img_alpha,2); + +if ~isfield(H,'ax_slice') + H.ax_slice = axes('Position',H.pos.slice); +else + axes(H.ax_slice); +end + +% display image with 2nd colorbar (gray) +image(65 + H.img); +if ~H.mesh_detected, axis image; end +set(H.ax_slice,'XTickLabel','','YTickLabel','','TickLength',[0 0]); +title('Z-score') + +% prepare alpha overlays for red and green colors +if H.ui.alphaval > 0 + + hold on + alpha_b = cat(3, zeros(size(H.img_alpha)), zeros(size(H.img_alpha)), H.ui.alphaval*ones(size(H.img_alpha))); + alpha_r = cat(3, H.ui.alphaval*ones(size(H.img_alpha)), zeros(size(H.img_alpha)), zeros(size(H.img_alpha))); + hg = image(alpha_b); set(hg, 'AlphaData', 0.25*H.img_alpha.*(H.img_alpha>=0),'AlphaDataMapping','none') + if ~H.mesh_detected, axis image; end + hr = image(alpha_r); set(hr, 'AlphaData',-0.25*H.img_alpha.*(H.img_alpha<0),'AlphaDataMapping','none') + if ~H.mesh_detected, axis image; end + hold off +end + +figure(H.mainfig); +colormap(H.cmap) + +return + +%----------------------------------------------------------------------- +function show_report(obj, event_obj, long_report) +%----------------------------------------------------------------------- +global H + +% change button status and checkboxes if button was pressed +if nargin + if isfield(H.ui,'plotbox') + set(H.ui.plotbox, 'Visible', 'off'); + end + set(H.ui.fnambox, 'Visible', 'off'); + if long_report + set(H.dpui.reportlong,'BackGroundColor',[0.95 0.95 0.95]); + set(H.dpui.report, 'BackGroundColor',[0.94 0.94 0.94]); + H.show_sel = 3; + else + set(H.dpui.report, 'BackGroundColor',[0.95 0.95 0.95]); + set(H.dpui.reportlong,'BackGroundColor',[0.94 0.94 0.94]); + H.show_sel = 2; + end + set(H.dpui.log, 'BackGroundColor',[0.94 0.94 0.94]); + set(H.dpui.raw, 'BackGroundColor',[0.94 0.94 0.94]); + set(H.dpui.rawp0,'BackGroundColor',[0.94 0.94 0.94]); +end + +% select first time point for longitudinal report and selected data for +% normal report +if long_report + jpg_file = H.files.jpg_long{min(H.mouse.x)}; +else + jpg_file = H.files.jpg{H.mouse.x(1)}; +end + +if ~isempty(jpg_file) + + figure(H.Fgraph); + clf + + ppos = [0 0 1 1]; + jpg = imread(jpg_file); + set(gca,'Position',ppos(1,:)); + gpos = H.Fgraph.Position; + [Xq,Yq] = meshgrid(1:size(jpg,2)/gpos(3)/2:size(jpg,2),... + 1:size(jpg,1)/gpos(4)/2:size(jpg,1)); + jpgi = zeros([size(Xq,1) size(Xq,2) 3],'uint8'); + for i=1:3, jpgi(:,:,i) = uint8(interp2(single(jpg(:,:,i)),Xq,Yq,'linear')); end + image(H.Fgraph.CurrentAxes,jpgi); + set(gca,'Visible','off'); + +end + +figure(H.mainfig) + +return + +%----------------------------------------------------------------------- +function show_raw(obj, event_obj, overlay) +%----------------------------------------------------------------------- +global H + +% change button status and checkboxes if button was pressed +if nargin + if isfield(H.ui,'plotbox') + set(H.ui.plotbox, 'Visible', 'off'); + end + set(H.ui.fnambox, 'Visible', 'off'); + set(H.dpui.report, 'BackGroundColor',[0.94 0.94 0.94]); + set(H.dpui.reportlong,'BackGroundColor',[0.94 0.94 0.94]); + set(H.dpui.log, 'BackGroundColor',[0.94 0.94 0.94]); + if overlay + set(H.dpui.rawp0, 'BackGroundColor',[0.95 0.95 0.95]); + set(H.dpui.raw, 'BackGroundColor',[0.94 0.94 0.94]); + H.show_sel = 5; + else + set(H.dpui.rawp0, 'BackGroundColor',[0.94 0.94 0.94]); + set(H.dpui.raw, 'BackGroundColor',[0.95 0.95 0.95]); + H.show_sel = 4; + end +end + +x_sort = sort(H.mouse.x); +raw_file = H.files.raw(x_sort); +p0_file = H.files.p0(sort(H.mouse.x)); +if (~isempty(raw_file) && ~isempty(raw_file{1})) || ... + (~isempty(p0_file) && ~isempty(p0_file{1})) + + job.colormapc = flipud(cat_io_colormaps('BCGWHcheckcov')); + job.prop = 0.2; + + if isempty(char(raw_file)) && ~isempty(char(p0_file)) + spm_check_registration(char(p0_file)); + else + spm_check_registration(char(raw_file)); + end + + % overlay p0image if available + if ~isempty(char(raw_file)) && overlay + for i = 1:numel(p0_file) + if exist(p0_file{i},'file') + spm_orthviews('addtruecolourimage',i,p0_file{i},... + job.colormapc,job.prop,0,5); + end + end + end + + % add short name to caption + for i=1:numel(raw_file) + txt = {{spm_str_manip(raw_file{i},'k30'),sprintf('Mean abs Z-score: %g',H.data.avg_abs_zscore(x_sort(i)))}}; + if H.isxml + txt{1}{3} = sprintf('SIQR: %g',H.X(x_sort(i),4)); + end + spm_orthviews('Caption',i,txt); + end + + spm_orthviews('Reposition',[0 0 0]); + if isempty(char(raw_file)) && ~isempty(char(p0_file)) + spm_orthviews('Zoom',0); + end + spm_orthviews('redraw'); + + % make annoying colorbars smaller + if ~isempty(char(raw_file)) && overlay + % find last axes that are the colorbars + ax = findall(gcf,'type','Axes'); + for i = 1:numel(p0_file) + pos = get(ax(i),'Position'); + set(ax(i),'Position',[pos(1:2) 0.5*pos(3:4)]) + end + end + +end + +figure(H.mainfig) + +return + +%----------------------------------------------------------------------- +function show_log(obj, event_obj) +%----------------------------------------------------------------------- +global H + +% change button status and checkboxes if button was pressed +if nargin + H.show_sel = 6; + if isfield(H.ui,'plotbox') + set(H.ui.plotbox, 'Visible', 'off'); + end + set(H.ui.fnambox, 'Visible', 'off'); + set(H.dpui.report, 'BackGroundColor',[0.94 0.94 0.94]); + set(H.dpui.reportlong,'BackGroundColor',[0.94 0.94 0.94]); + set(H.dpui.log, 'BackGroundColor',[0.95 0.95 0.95]); + set(H.dpui.raw, 'BackGroundColor',[0.94 0.94 0.94]); + set(H.dpui.rawp0, 'BackGroundColor',[0.94 0.94 0.94]); +end + +log_file = H.files.log{H.mouse.x}; +if ~isempty(log_file) + + figure(H.Fgraph); + clf + axis off + + textbox = [0 0 1 1]; + + fid = fopen(log_file); + ph = uipanel(H.Fgraph,'Units','normalized','position',textbox, ... + 'BorderWidth',0,'title',spm_str_manip(log_file,'k100'),'ForegroundColor',[0 0 0.8]); + lbh = uicontrol(ph,'style','listbox','Units','normalized',... + 'fontname','Fixedwidth','position',[ 0 0 1 1 ],'FontSize',9); + indic = 1; + while 1 + tline = fgetl(fid); + if ~ischar(tline), + break + end + strings{indic}=tline; + indic = indic + 1; + end + fclose(fid); + set(lbh,'string',strings); + set(lbh,'Value',1); + set(lbh,'Selected','on'); + +end + +figure(H.mainfig) + +return + +%----------------------------------------------------------------------- +function update_alpha(obj, event_obj) +%----------------------------------------------------------------------- +global H + +if isfield(H.ui,'alpha') + H.ui.alphaval = get(H.ui.alpha,'Value'); +else + H.ui.alphaval = 0.5; +end + +if ~isfield(H,'ax_slice') H.ax_slice = axes('Position',H.pos.slice); end +axes(H.ax_slice); + +% display image with 2nd colorbar (gray) +image(65 + H.img); +if ~H.mesh_detected, axis image; end +set(gca,'XTickLabel','','YTickLabel','','TickLength',[0 0]); + +% prepare alpha overlays for red and green colors +if H.ui.alphaval > 0 + + hold on + alpha_b = cat(3, zeros(size(H.img_alpha)), zeros(size(H.img_alpha)), H.ui.alphaval*ones(size(H.img_alpha))); + alpha_r = cat(3, H.ui.alphaval*ones(size(H.img_alpha)), zeros(size(H.img_alpha)), zeros(size(H.img_alpha))); + hg = image(alpha_b); set(hg, 'AlphaData', 0.25*H.img_alpha.*(H.img_alpha>=0),'AlphaDataMapping','none') + if ~H.mesh_detected, axis image; end + hr = image(alpha_r); set(hr, 'AlphaData',-0.25*H.img_alpha.*(H.img_alpha<0),'AlphaDataMapping','none') + if ~H.mesh_detected, axis image; end + hold off +end + +return + +%----------------------------------------------------------------------- +function preload_slice_data +%----------------------------------------------------------------------- +global H + +if isfield(H.ui,'mm') + slice_mm = get(H.ui.mm,'Value'); +else + slice_mm = 0; +end + +if H.names_changed + P = H.files.Vchanged; +else + P = H.files.V; +end + +H.data.vx = sqrt(sum(P(1).mat(1:3,1:3).^2)); +H.data.Orig = P(1).mat\[0 0 0 1]'; +sl = round(slice_mm/H.data.vx(3)+H.data.Orig(3)); + +% if slice is outside of image use middle slice +if (sl>P(1).dat.dim(3)) || (sl<1) + sl = round(P(1).dat.dim(3)/2); +end + +M = spm_matrix([0 0 sl]); +H.data.zscore = zeros([P(1).dat.dim(1:2) length(H.files.V)]); +Ymean = reshape(H.data.Ymean,P(1).dat.dim(1:3)); +Ystd = reshape(H.data.Ystd,P(1).dat.dim(1:3)); +Ymean = Ymean(:,:,sl); +Ystd = Ystd(:,:,sl); + +scl = max(Ymean(:)); + +% load slices and show progress bar only for large samples +if length(H.files.V) > 500, cat_progress_bar('Init',length(H.files.V),'Load slices'); end +for i = 1:length(H.files.V) + img(:,:) = single(P(i).dat(:,:,sl)); + img(~isfinite(img)) = 0; + + H.data.vol(:,:,i) = img; + if length(H.files.V) > 500, cat_progress_bar('Set',i); end +end +if length(H.files.V) > 500, cat_progress_bar('Clear'); end + +% calculate individual Z-score map +for i=1:size(H.data.zscore,3) + img = H.data.vol(:,:,i); + ind = Ystd > 0 & (Ymean > H.data.global | img > H.data.global); + img(ind) = (img(ind) - Ymean(ind))./Ystd(ind); + img(~ind) = 0; + H.data.zscore(:,:,i) = img; +end + +% enhance contrast and scale image to 0..64 +H.data.vol = 64*((H.data.vol - H.data.range98(1))/(H.data.range98(2)-H.data.range98(1))); +H.data.vol(H.data.vol > 64) = 64; +H.data.vol(H.data.vol < 0) = 0; + +return + +%----------------------------------------------------------------------- +function update_slices_array(obj, event_obj) +%----------------------------------------------------------------------- +global H + +if isfield(H.ui,'mm') + slice_mm = get(H.ui.mm,'Value'); +else + slice_mm = 0; +end + +if H.names_changed + P = H.files.Vchanged; +else + P = H.files.V; +end + +H.data.vx = sqrt(sum(P(1).mat(1:3,1:3).^2)); +H.data.Orig = P(1).mat\[0 0 0 1]'; +sl = round(slice_mm/H.data.vx(3)+H.data.Orig(3)); + +% if slice is outside of image use middle slice +if (sl>P(1).dat.dim(3)) || (sl<1) + sl = round(P(1).dat.dim(3)/2); +end + +M = spm_matrix([0 0 sl]); +H.data.zscore = zeros([P(1).dat.dim(1:2) length(H.files.V)]); +Ymean = reshape(H.data.Ymean,P(1).dat.dim(1:3)); +Ystd = reshape(H.data.Ystd,P(1).dat.dim(1:3)); +Ymean = Ymean(:,:,sl); +Ystd = Ystd(:,:,sl); + +scl = max(Ymean(:)); + +% load slices and show progress bar only for large samples +if length(H.files.V) > 500, cat_progress_bar('Init',length(H.files.V),'Load slices'); end +for i = 1:length(H.files.V) + img(:,:) = single(P(i).dat(:,:,sl)); + img(~isfinite(img)) = 0; + + H.data.vol(:,:,i) = img; + if length(H.files.V) > 500, cat_progress_bar('Set',i); end +end +if length(H.files.V) > 500, cat_progress_bar('Clear'); end + +% calculate individual Z-score map +for i=1:size(H.data.zscore,3) + img = H.data.vol(:,:,i); + ind = Ystd > 0 & (Ymean > H.data.global | img > H.data.global); + img(ind) = (img(ind) - Ymean(ind))./Ystd(ind); + img(~ind) = 0; + H.data.zscore(:,:,i) = img; +end + +% enhance contrast and scale image to 0..64 +H.data.vol = 64*((H.data.vol - H.data.range98(1))/(H.data.range98(2)-H.data.range98(1))); +H.data.vol(H.data.vol > 64) = 64; +H.data.vol(H.data.vol < 0) = 0; + +if isfield(H,'mouse') && isfield(H.mouse,'x') + x = H.mouse.x(1); + + % check whether mouse position is defined + H.img = H.data.vol(:,:,x)'; + H.img_alpha = H.data.zscore(:,:,x)'; + + % correct orientation + H.img = rot90(H.img,2); + H.img_alpha = rot90(H.img_alpha,2); + + if ~isfield(H,'ax_slice') + H.ax_slice = axes('Position',H.pos.slice); + else + axes(H.ax_slice); + end + + % use gray scale colormap for values > 64 + image(65 + H.img); + axis image + set(gca,'XTickLabel','','YTickLabel',''); + title('Z-score') + + % prepare alpha overlays for red and green colors + if H.ui.alphaval > 0 + + hold on + alpha_b = cat(3, zeros(size(H.img_alpha)), zeros(size(H.img_alpha)), H.ui.alphaval*ones(size(H.img_alpha))); + alpha_r = cat(3, H.ui.alphaval*ones(size(H.img_alpha)), zeros(size(H.img_alpha)), zeros(size(H.img_alpha))); + hg = image(alpha_b); set(hg, 'AlphaData', 0.25*H.img_alpha.*(H.img_alpha>=0),'AlphaDataMapping','none') + axis image + hr = image(alpha_r); set(hr, 'AlphaData',-0.25*H.img_alpha.*(H.img_alpha<0),'AlphaDataMapping','none') + axis image + hold off + end + + txt = {sprintf('%s',spm_file(H.filename.m{x},'short25')),[],['Displayed slice: ',num2str(round(get(H.ui.mm,'Value'))),' mm']}; + + set(H.ui.text,'String',txt,'FontSize',H.FS); + set(H.ui.mm_txt,'String',[num2str(round(get(H.ui.mm,'Value'))),' mm'],... + 'FontSize',H.FS-2); +end + +return + +%----------------------------------------------------------------------- +function get_new_list(obj,event_obj, option) +%----------------------------------------------------------------------- +global H + +if ~nargin + option = false; +end + +if isfield(H,'del') + if isempty(H.del) + fprintf('No data removed.\n'); + return + end +else + fprintf('No data removed.\n'); + return +end + +Hdel = H.del; +job = H.job; + +% create new list of xml-files if necessary +if H.isxml && ((iscell(job.data_xml) && ~isempty(job.data_xml{1})) || (~iscell(job.data_xml) && ~isempty(job.data_xml))) + n = 0; + for i=1:numel(job.data_xml) + if any(Hdel == i), continue; end + n = n + 1; + data_xml{n,1} = job.data_xml{i}; + end + job.data_xml = data_xml; +end + +% create new list without removed data in each sample +data = job.data; +for i=1:numel(job.data) + data_sel = data{i}; + if ~iscell(data_sel), data_sel = cellstr(data_sel); end + ind = find(H.sample==i); + n_subjects = numel(ind); + del_list = ismember(ind,Hdel); + Hdel(Hdel < n_subjects) = []; + + if exist('data_del','var') + data_del = [data_del;data_sel( del_list)]; + data_new = [data_new;data_sel(~del_list)]; + else + data_del = data_sel( del_list); + data_new = data_sel(~del_list); + end + data_sel(del_list) = []; + job.data{i} = data_sel; +end + +switch option + case -1, + fprintf('Data that are removed from list:\n'); + for i=1:numel(data_del) + fprintf('%s\n',data_del{i}); + end + case 0, + fprintf('Data that remain in list:\n'); + for i=1:numel(data_new) + fprintf('%s\n',data_new{i}); + end + + if isfield(H.job,'factorial_design') + modify_factorial_design(job.data); + end + + case 1, + do_rerun(obj,event_obj,false); + set(H.naviui.select,'BackGroundColor',[0.95 0.95 0.95]); + set(H.delui.new,'enable','off'); + datacursormode('on'); +end + +return + +%----------------------------------------------------------------------- +function modify_factorial_design(data) +%----------------------------------------------------------------------- +global H + +job = H.job.factorial_design; + +% modify dir +[pth,name,ext] = fileparts(char(job.dir)); +job.dir{1} = fullfile(pth,['wo_removed_data_' name ext]); +fprintf('\n------------------------------------------------------------------------------------------\n'); +fprintf('Create new analysis without removed data in %s\n',job.dir{1}); +fprintf('------------------------------------------------------------------------------------------\n'); + +% modify globals +if isfield(job,'globals') && isfield(job.globals,'g_user') + job.globals.g_user.global_uval = job.globals.g_user.global_uval(H.ind); +end +if isfield(job,'globalc') && isfield(job.globalc,'g_user') + job.globalc.g_user.global_uval = job.globalc.g_user.global_uval(H.ind); +end +if isfield(job,'globals') && isfield(job.globals,'g_ancova') + job.globals.g_ancova.global_uval = job.globals.g_ancova.global_uval(H.ind); +end +if isfield(job,'globalc') && isfield(job.globalc,'g_ancova') + job.globalc.g_ancova.global_uval = job.globalc.g_ancova.global_uval(H.ind); +end + +% modify covariates +if isfield(job,'cov') + for i=1:numel(job.cov) + job.cov(i).c = job.cov(i).c(H.ind); + end +end + +% modify files and factors for different designs +if isfield(job.des,'t2') % two-sample t-test + job.des.t2.scans1 = data{1}; + job.des.t2.scans2 = data{2}; +elseif isfield(job.des,'mreg') % multiple regression + job.des.mreg.scans = data{1}; +elseif isfield(job.des,'fd') % full factorial + for i=1:numel(job.des.fd.icell) + job.des.fd.icell(i).scans = data{i}; + end +elseif isfield(job.des,'fblock') % flexible factorial + fsubject = job.des.fblock.fsuball.fsubject; + + % index of whole subjects is removed from list + ind_remove_subject = []; + + % go through all subjects + for i = 1:numel(H.ind_subjects_long) + + % index where time points are defined for this subject + ind_subject = find(H.ind_subjects_long{i}); + + % array where data are kept for this subject + ind = H.ind.*H.ind_subjects_long{i} > 0; + + % we can keep that subject if we have at least 2 time points + if sum(ind) > 1 % remove single time points and update scans and conditions + job.des.fblock.fsuball.fsubject(i).scans = fsubject(i).scans(ind(ind_subject)); + if size(fsubject(i).conds,1) > 1 + job.des.fblock.fsuball.fsubject(i).conds = fsubject(i).conds(ind(ind_subject),:); + else + job.des.fblock.fsuball.fsubject(i).conds = fsubject(i).conds(ind(ind_subject)); + end + elseif sum(ind) == 1 % indicate to remove whole subject because only one time point remains + ind_remove_subject = [ind_remove_subject i]; + fprintf('Remove all time points of subject %d because only one time point remains.\n',i); + elseif sum(ind) == 0 % indicate to remove whole subject + ind_remove_subject = [ind_remove_subject i]; + fprintf('Remove all time points of subject %d\n',i); + end + end + fprintf('\n'); + + % remove whole subject from list + if ~isempty(ind_remove_subject) + job.des.fblock.fsuball.fsubject(ind_remove_subject) = []; + end +else + fprintf('Other designs are not yet prepared.\n'); + return +end + +% Sometimes window for DesRep is not accessable +try + out = spm_run_factorial_design(job); +catch + out = spm_run_factorial_design(job); +end +spm('alert!', sprintf('Create new analysis without removed data in %s\n',job.dir{1}), 0); + +return + +%----------------------------------------------------------------------- +function do_rerun(obj, event_obj, undo) +%----------------------------------------------------------------------- +global H + +if H.status.report, set(H.dpui.report, 'enable','on','BackGroundColor',[0.94 0.94 0.94]); end +if H.status.raw, set(H.dpui.raw, 'enable','on','BackGroundColor',[0.94 0.94 0.94]); end +if H.status.rawp0, set(H.dpui.rawp0, 'enable','on','BackGroundColor',[0.94 0.94 0.94]); end +if H.status.log, set(H.dpui.log, 'enable','on','BackGroundColor',[0.94 0.94 0.94]); end +if H.status.reportlong, set(H.dpui.reportlong,'enable','on','BackGroundColor',[0.94 0.94 0.94]); end + +set(H.naviui.select, 'BackGroundColor',[0.95 0.95 0.95]); + +datacursormode('on'); + +if undo + H.ind = true(size(H.sample)); + set(H.delui.undo, 'enable','off'); + set(H.delui.new, 'enable','off'); + set(H.delui.list_del,'enable','off'); + set(H.delui.analysis_new,'enable','off'); + H.del = []; +else + + % remove subjects where only one time point remains + if H.repeated_anova + for i = 1:numel(H.ind_subjects_long) + + % array where data are kept for this subject + ind = H.ind.*H.ind_subjects_long{i} > 0; + + if sum(ind) == 1 % indicate to remove whole subject because only one time point remains + H.del = unique([H.del find(H.ind_subjects_long{i})]); + fprintf('Remove all time points of subject %d because only one time point remains.\n',i); + end + end + end + + H.ind = ~ismember((1:numel(H.sample)),H.del); +end + +show_boxplot(H.data.avg_abs_zscore(H.ind),'Quartic Mean Z-score ',-1); +if H.isxml + show_QMzscore(H.X,4); +else + show_QMzscore(H.X,0); +end + +% delete old data tip +delete(findall(H.mainfig,'Type','hggroup')) +set(H.delui.remove,'enable','off'); + +return + +%----------------------------------------------------------------------- +function remove_point(obj, event_obj) +%----------------------------------------------------------------------- +global H + +if H.sel + sel = H.sel; +else + sel = 0; % file order by default +end + +x = H.mouse.x(1); + +% check whether we also have to exlude other time points for long. data +% if there are not enough timepoints anymore available +if H.repeated_anova + for i = 1:numel(H.ind_subjects_long) + ind = find(H.ind_subjects_long{i}); + if any(ismember(ind, x)) + if numel(ind) - 1 == sum(ismember(ind,unique([H.del x]))) + x = H.mouse.x; + end + end + end +end + +if sel % QM measure on x-axis + xx = H.X(x,sel); + yy = H.X(x,1); +else % file order on x-axis + xx = x; + yy = H.X(x,1); +end + +axes(H.ax) +hold on + +% reconsider this data point (and only this one) if already in the list +if ~isempty(H.del) && any(ismember(H.del,x(1))) + plot(xx(1),yy(1),'wx','MarkerSize',15,'Linewidth',2); + plot(xx(1),yy(1),'wo','MarkerSize',15,'Linewidth',2,'MarkerFaceColor','w'); + plot(xx(1),yy(1),'ko','MarkerSize',5,'Linewidth',2); + H.del(ismember(H.del,x(1))) = []; + return +else + plot(xx,yy,'rx','MarkerSize',15,'Linewidth',2); +end +hold off + +% add point to the list +H.del = unique([H.del x]); + +% also update index of considered data and enable icons +H.ind = ~ismember((1:numel(H.sample)),H.del); +set(H.delui.undo, 'enable','on'); +set(H.delui.new, 'enable','on'); +set(H.delui.list_del, 'enable','on'); +set(H.delui.analysis_new,'enable','on'); + +return + +%----------------------------------------------------------------------- +function txt = myupdatefcn(obj, event_obj) +%----------------------------------------------------------------------- +global H + +if H.sel + sel = H.sel; +else + sel = 0; % file order by default +end + +% if it's the same point use old data tip and return +pos_mouse = get(event_obj, 'Position'); +if H.mouse.xold == pos_mouse + txt = get(findall(H.mainfig,'Type','hggroup'),'String'); + if isempty(txt), return; end +end + +H.mouse.xold = pos_mouse; + +x = find(H.X(:,1) == pos_mouse(2)); +if isempty(x) || numel(x) > 1 + x = find(H.X(:,sel) == pos_mouse(1)); +end + +% empty data tip and return if no point was found +if isempty(x) + txt = ''; + return +end + +% text info for data cursor window +txt = {sprintf('%s',H.filename.m{x})}; + +% prevent that that function is called again if position has not changed or +% subject for long. data has not changed for showing raw data +if H.repeated_anova && (isfield(H,'show_sel') && (H.show_sel == 4 || H.show_sel == 5)) + if any(x == H.mouse.x) + return + else + H.mouse.x = x; + end +elseif x == H.mouse.x(1) % && (H.repeated_anova && (H.show_sel == 4 || H.show_sel == 5)) + return +else + H.mouse.x = x; +end + +if H.mesh_detected + % show two render views for meshes: texture and Z-score + show_mesh; +else + % show image slice + show_image_slice; +end + +if ~H.mesh_detected + set(H.ui.alpha,'Visible','on'); + set(H.ui.alpha_txt,'Visible','on'); +end + +% text info for textbox +txt2 = {[],sprintf('%s',spm_file(H.filename.m{H.mouse.x(1)},'short25'))}; +if max(H.sample) > 1, txt2{end+1} = sprintf('Sample %d',H.sample(H.mouse.x(1))); end +if max(H.sites)>1, txt2{end} = sprintf('%s / Site %d', txt2{end}, H.sites(H.mouse.x(1))); end % just add the site variable if useful +txt2{end+1} = sprintf('Mean abs Z-score: %g',H.data.avg_abs_zscore(H.mouse.x(1))); + +if H.isxml + txt2{end+1} = sprintf('SIQR / nSIQR: %g / %g', H.X(H.mouse.x(1),4), H.X(H.mouse.x(1),5) ); +end + +if ~H.mesh_detected + str = {[],'Individual Z-score','red: value < mean','blue: value > mean'}; + for i=1:numel(str) + txt2{end+1} = str{i}; + end +end + +set(H.ui.text,'String',txt2,'FontSize',H.FS); + +% get list of time points for long. data +if H.repeated_anova + for i = 1:numel(H.ind_subjects_long) + if H.ind_subjects_long{i}(x) + H.mouse.x = find(H.ind_subjects_long{i}); + + % set actual position to 1st entry + H.mouse.x(H.mouse.x == x) = []; + H.mouse.x = [x H.mouse.x]; + break + end + end +end + +% only enable select +% does not work and I am not sure whether this is necessary at all +%datacursormode('on'); + +% enable buttons +if strcmp(get(H.delui.remove,'enable'),'off') + set(H.delui.remove,'enable','on'); + + if H.status.report, set(H.dpui.report, 'enable','on'); end + if H.status.raw, set(H.dpui.raw, 'enable','on'); end + if H.status.rawp0, set(H.dpui.rawp0, 'enable','on'); end + if H.status.log, set(H.dpui.log, 'enable','on'); end + if H.status.reportlong, set(H.dpui.reportlong,'enable','on'); end + + if ~H.mesh_detected + set(H.ui.alpha, 'Visible','on'); + set(H.ui.alpha_txt,'Visible','on'); + set(H.ui.mm, 'Visible','on'); + set(H.ui.mm_txt, 'Visible','on'); + end + set(H.ui.text, 'Visible','on'); + +end + + +if isfield(H,'show_sel') + switch(H.show_sel) + case 2, show_report(obj, event_obj, false); % report + case 3, show_report(obj, event_obj, true); % report long + case 4, show_raw(obj, event_obj, false); % raw + case 5, show_raw(obj, event_obj, true); % raw + p0 + case 6, show_log; % log file + end +end + +return +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_io_writenii.m",".m","15889","432","function varargout = cat_io_writenii(V,Y,folder,pre,desc,spmtype,range,writes,transform,YM,YMth) +% ______________________________________________________________________ +% Write an image Y with the properties described by V with the datatype +% spmtype for a specific range. Add the prefix pre and the description +% desc to V. +% +% VO = cat_io_write_nii(Y,V [folder,pre,desc,spmtype,range,write,addpre,transform,YM,YMth]) +% +% Y = input volume +% V = input volume structure +% VO = ouput volume structure +% folder = subfolder for writing data (default='') +% pre = prefix for filename (default='') +% desc = description that is added to the origin description +% (default='CAT#R#') +% spmtype = spm image type (default given by the class of Y) +% write = [native warped modulated dartel] +% native 0/1 (none/yes) +% warped 0/1 (none/yes) +% modulated 0/1/2/3 (none/affine+nonlinear/nonlinear only/both) +% dartel 0/1/2/3 (none/rigid/affine/both) +% transform = transformation data to write the image to warped, +% modulated, or dartel space (see cat_main) +% .push = use push rather than pull +% YM = mask for the final image (i.e. save thickness and ROIs) +% YMth = threshold for YM +% +% Examples: +% +% +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ +% +%#ok<*WNOFF,*WNON,*ASGLU> + + % file name + [cv,cr] = cat_version; + if ~exist('pre','var'), pre = ''; end + if ~exist('desc','var'), desc = sprintf('%sR%s ',cv,cr); end + if exist('transform','var') && isfield(transform,'warped') + if isfield(transform.warped,'push'), push = transform.warped.push; else, push = 0; end + if ~isfield(transform.warped,'w') && ~isfield(transform.warped,'yi'), push = 1; end + else + push = 1; + end + + % image type and convertations + if ~exist('spmtype','var') + switch class(Y) + case 'logical', spmtype = 'uint8'; + case 'int8', spmtype = 'int8'; + case 'int16', spmtype = 'int16'; + case 'int32', spmtype = 'int32'; + case {'uint8','char'}, spmtype = 'uint8'; + case 'uint16', spmtype = 'uint16'; + case 'uint32', spmtype = 'uint32'; + case {'single','double'}, spmtype = 'float32'; + otherwise + end + else + switch spmtype + case 'logical', spmtype = 'uint8'; + case 'char', spmtype = 'uint8'; + case {'single','double'}, spmtype = 'float32'; + otherwise + end + end + + if ~exist('range','var'), range = [0 1]; end + write = [1 0 0 0]; + if isstruct(writes) + if isfield(writes,'native'), write(1) = writes.native; end + if isfield(writes,'warped'), write(2) = writes.warped; end + if isfield(writes,'mod' ), write(3) = writes.mod; end + if isfield(writes,'affine'), write(4) = writes.affine; end + if isfield(writes,'dartel'), write(4) = writes.dartel; end + elseif isnumeric(writes) + if numel(writes)==3, write = [writes(1:2) 0 writes(3)]; else, write = writes; end + end + if ~exist('YMth','var'), YMth = 0.5; end + if exist('YM','var') + if all(size(Y)==size(YM)) + YM=single(YM); + else + error('MATLAB:cat_io_writenii:YM','Y and YM have different size'); + end + end + + pp = fileparts(V.fname); + if ~exist('folder','var'), folder = ''; end + if ~exist(spm_file(fullfile(pp,folder,'tmp'),'fpath'),'dir'), mkdir(spm_file(fullfile(pp,folder,'tmp'),'fpath')); end + + + % deal with label maps + switch class(Y) + case {'single','double'} + labelmap = 0; + case {'uint8','uint16'} + if all(range == [0 1]) + labelmap = 1; + Y = single(Y); + else + labelmap = 0; + end + otherwise + labelmap = 0; + end + + % RD20200619: Just to be safe, there was an error in the BWP MS1. + Y = real(Y); + + % write native file + % ____________________________________________________________________ + if write(1)==1 + filename = io_handle_pre(V.fname,pre,'',folder); + if exist('transform','var') && isfield(transform,'native') + if any(size(Y(:,:,:,1,1))~=transform.native.Vo.dim) + nV = transform.native.Vi; + else + nV = transform.native.Vo; + end + else + nV = V; + end + if exist(filename,'file'), delete(filename); end + + N = nifti; + N.dat = file_array(filename,nV.dim(1:3),[spm_type(spmtype) ... + spm_platform('bigend')],range(1),range(2),0); + N.mat = nV.mat; + N.mat0 = nV.mat; % do not change mat0 - 20150612 - not changing, creating 20150916 + if isempty(V.descrip), N.descrip = desc; else, N.descrip = [desc ' < ' V.descrip]; end + create(N); + + % final masking after transformation + if exist('YM','var') + switch spmtype + case 'float32', N.dat(:,:,:) = double(Y) .* (smooth3(YM)>YMth); + otherwise, N.dat(:,:,:) = max(range(1),min(range(1) + range(2)*double(intmax(spmtype)),double(Y) .* (smooth3(YM)>YMth))); + end + else + switch spmtype + case 'float32', N.dat(:,:,:) = double(Y); + otherwise, N.dat(:,:,:) = max(range(1),min(range(1) + range(2)*double(intmax(spmtype)),double(Y))); + end + end + + Vn = spm_vol(filename); + % reduce to original native space if it was interpolated + if exist('transform','var') && isfield(transform,'native') && any(size(Y(:,:,:,1,1))~=transform.native.Vo.dim) + [pp,ff] = spm_fileparts(filename); + Vo = transform.native.Vo; + Vo.fname = filename; + Vo.dt = Vn.dt; + Vo.pinfo = Vn.pinfo; + if strcmp(ff(1:2),'p0') + [Vn,Yn] = cat_vol_imcalc(Vn,Vo,'i1',struct('interp',5,'verb',0)); + % For Yp0 linear should be better, to avoid interpolation artifacts, but + % some single test showed that rounding produce better results. + rf = 100; + Ynr = round(Yn*rf)/rf; + YMR = false(size(Yn)); + for i=1:4, YMR = YMR | (Yn>(i-1/rf) & Yn<(i+1/rf)); end + Yn(YMR) = Ynr(YMR); clear YMR Ynr; + delete(Vn.fname); % remove it, otherwise it will have the wrong filesize (correct readable, but still too big) + Vn = spm_write_vol(Vn,double(Yn)); + elseif labelmap + [Vn,Yn] = cat_vol_imcalc(Vn,Vo,'i1',struct('interp',0,'verb',0)); + delete(Vn.fname); % remove it, otherwise it will have the wrong filesize (correct readable, but still too big) + Vn = spm_write_vol(Vn,double(Yn)); + else + [Vn,Yn] = cat_vol_imcalc(Vn,Vo,'i1',struct('interp',6,'verb',0)); + delete(Vn.fname); % remove it, otherwise it will have the wrong filesize (correct readable, but still too big) + Vn = spm_write_vol(Vn,double(Yn)); + end + end + + if nargout>0, varargout{1}(1) = Vn; end + if nargout>1, varargout{2}{1} = []; end + clear N; + end + + + % for masked images like thickness we need to fill undefined regions, + % to avoid the PVE of boundary voxel. + if any(write(2:end)) && exist('YM','var') + [D,I] = cat_vbdist(single(Y)); Y(:)=Y(I(:)); clear D I; + end + + + %% warped + % ____________________________________________________________________ + % If we have a label map we have to correct the result, because spm_diffeo + % and spm_field don't allow nearest neigbor deformation. Because the + % interpolated values of the boundaries cannot be simply rounded (it + % maybe generates another label), we need to replace this voxel by + % its nearest neighbor value. + + % interpolation to reduce artifacts if the resolution of the original + % image is similar or worse to that of the template resolution + if write(2) + pre2 = ['w' pre]; desc2 = [desc '(warped)']; + + filename = io_handle_pre(V.fname,pre2,'',folder); + if exist(filename,'file'), delete(filename); end + if labelmap==0 + if push + [wT,w] = spm_diffeo('push', Y, transform.warped.y, transform.warped.odim(1:3) ); + wT = wT ./ max(eps,w); + else + try + wT = spm_diffeo('pull', Y, transform.warped.yi ); + catch + wT = spm_diffeo('samp', Y, transform.warped.yi ); + end + spm_smooth(wT,wT,transform.warped.fs); + end + elseif labelmap==1 + % we can use modulated data throughout the following steps because the final maximum probability function + % will be the same for modulated and unmodulated data + wT = zeros([transform.warped.odim(1:3),max(Y(:))],'uint8'); + % interpolate each label separately + for yi=1:max(Y(:)) + if push + wTi = spm_diffeo('push', single(Y==yi), transform.warped.y, transform.warped.odim(1:3) ); + else + try + wTi = spm_diffeo('pull', single(Y==yi), transform.warped.yi ); + catch + wTi = spm_diffeo('samp', single(Y==yi), transform.warped.yi ); + end + spm_smooth(wTi,wTi,transform.warped.fs); + end + wT(:,:,:,yi) = uint8(wTi * 100); + end + % use maximum probability function to get label again + [wTmax,wT] = max(wT,[],4); + end + clear w; + + % final masking after transformation + if exist('YM','var') + if push + [wTM,w] = spm_diffeo('push', YM, transform.warped.y, transform.warped.odim(1:3) ); + wT = wT ./ max(eps,w); + else + try + wTM = spm_diffeo('pull', YM, transform.warped.yi ); + catch + wTM = spm_diffeo('samp', YM, transform.warped.yi ); + end + spm_smooth(wTM,wTM,transform.warped.fs); + end + wT = wT .* (wTM>YMth); + clear w wTM; + end + + N = nifti; + N.dat = file_array(filename,transform.warped.odim, ... + [spm_type(spmtype) spm_platform('bigend')], ... + range(1),range(2),0); + N.mat = transform.warped.M1; + N.mat0 = transform.warped.M1; % do not change mat0 - 20150612 - not changing, creating 20150916 + if isempty(V.descrip), N.descrip = desc; else N.descrip = [desc2 ' < ' V.descrip]; end + create(N); + N.dat(:,:,:) = double(wT); + clear N; + + if nargout>0, varargout{1}(2) = spm_vol(filename); end + if nargout>1, varargout{2}{2} = wT; end + end + + + + %% modulated + % ___________________________________________________________________ + if write(3) + for wi=1:2 + %% + if (write(3)==1 || write(3)==3) && wi==1 + pre3 = ['mw' pre]; desc3 = [desc '(Jac. sc. warped)']; + elseif (write(3)==2 || write(3)==3) && wi==2 + pre3 = ['m0w' pre]; desc3 = [desc '(Jac. sc. warped non-lin only)']; + else + continue + end + + filename = io_handle_pre(V.fname,pre3,'',folder); + if exist(filename,'file'), delete(filename); end + + if push + wT = spm_diffeo('push', Y, transform.warped.y, transform.warped.odim(1:3) ); + else + try + wT = spm_diffeo('pull', Y, transform.warped.yi ); + catch + wT = spm_diffeo('samp', Y, transform.warped.yi ); + end + wT = wT .* transform.warped.w; + spm_smooth(wT,wT,transform.warped.fs); + end + + if exist('YM','var') % final masking after transformation + if push + [wTM,w] = spm_diffeo('push', YM, transform.warped.y, transform.warped.odim(1:3)); + wT = wT ./ max(eps,w); + else + try + wTM = spm_diffeo('pull', YM, transform.warped.yi ); + catch + wTM = spm_diffeo('samp', YM, transform.warped.yi ); + end + spm_smooth(wTM,wWT,transform.warped.fs); + end + wT = wT .* (wTM>YMth); + clear YM; + end + + % scale the jacobian determinant + if (write(3)==1 || write(3)==3) && wi==1 + wT = wT * abs(det(transform.warped.M0(1:3,1:3)) / ... + det(transform.warped.M1(1:3,1:3))); + else + wT = wT * abs(det(transform.warped.M2(1:3,1:3))); + end + + % check if the total original volume is equal to the total modulated volume + if isfield(transform.warped,'verb') && transform.warped.verb && ... + ( (write(3)==1 || write(3)==3) && wi==1) + fprintf('\n %s: %0.2f > %0.2f',pre3, ... + cat_stat_nansum(Y(:)) .* prod( sqrt( sum( transform.native.Vi.mat(1:3,1:3).^2 ) )) / 1000, ... % = indvidiudal vx_vol + cat_stat_nansum(wT(:)) .* prod( sqrt( sum( transform.warped.M1(1:3,1:3).^2 ) )) / 1000 ); % = template vx_vol + end + + N = nifti; + N.dat = file_array(filename,transform.warped.odim, ... + [spm_type(spmtype) spm_platform('bigend')], ... + range(1),range(2),0); + N.mat = transform.warped.M1; + N.mat0 = transform.warped.M1; % do not change mat0 - 20150612 - not changing, creating 20150916 + if isempty(V.descrip), N.descrip = desc3; else, N.descrip = [desc3 ' < ' V.descrip]; end + create(N); + + N.dat(:,:,:) = double(wT) ; + clear N; + + if nargout>0, varargout{1}(3) = spm_vol(filename); end + if nargout>1, varargout{2}{3} = wT; end + clear wT + end + end + + + + %% write dartel files + % ____________________________________________________________________ + if write(4) + for wi=1:2 + if (write(4)==1 || write(4)==3) && wi==1 && isfield(transform,'rigid') + transf=transform.rigid; + pre4=['r' pre]; post='_rigid'; desc4 = [desc ' (rigid)']; + elseif (write(4)==2 || write(4)==3) && wi==2 && isfield(transform,'affine') + transf=transform.affine; + pre4=['r' pre]; post='_affine'; desc4 = [desc ' (affine)']; + else + continue + end + + + filename = io_handle_pre(V.fname,pre4,post,folder); + if exist(filename,'file'), delete(filename); end + VraT = struct('fname',filename,'dim',transf.odim,... + 'dt', [spm_type(spmtype) spm_platform('bigend')],... + 'pinfo',[range(2) range(1)]','mat',transf.mat);%[1.0 0]' + VraT = spm_create_vol(VraT); + + N = nifti(VraT.fname); + + % do not change mat0 - 20150612 + % the mat0 contain the rigid transformation for the deformation tools! + % get rid of the QFORM0 rounding warning + warning off + N.mat = transf.mat; + N.mat0 = transf.mat0; + warning on + + %N.mat_intent = 'Aligned'; + %N.mat0_intent = 'Aligned'; + if isempty(V.descrip), N.descrip = desc; else N.descrip = [desc4 ' < ' V.descrip]; end + create(N); + + for i=1:transf.odim(3), + if labelmap + tmp = spm_slice_vol(double(Y) ,transf.M*spm_matrix([0 0 i]),transf.odim(1:2),0); + else + tmp = spm_slice_vol(double(Y) ,transf.M*spm_matrix([0 0 i]),transf.odim(1:2),[1,NaN]); + end + if exist('YM','var') % final masking after transformation + if labelmap + tmpM = spm_slice_vol(double(YM),transf.M*spm_matrix([0 0 i]),transf.odim(1:2),0); + else + tmpM = spm_slice_vol(double(YM),transf.M*spm_matrix([0 0 i]),transf.odim(1:2),[1,NaN]); + end + tmpM = smooth3(repmat(tmpM,1,1,3))>YMth; + tmp = tmp .* tmpM(:,:,2); clear tmpM; + end + VraT = spm_write_plane(VraT,tmp,i); + end + + if nargout>0, varargout{1}(4) = spm_vol(filename); end + if nargout>1, varargout{2}{4} = []; end + + + end + end + + +end + +function FO = io_handle_pre(F,pre,post,folder) +% Remove all known cat prefix types from a filename (and check if this file exist). + [pp,ff] = spm_fileparts(F); + + % always use .nii as extension + FO = fullfile(pp,folder,[pre ff post '.nii']); +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_run_newcatch.m",".m","11195","263","function cat_run_newcatch(job,tpm,subj) +% ______________________________________________________________________ +% This function contains the new matlab try-catch block. +% The new try-catch block has to be in a separate file to avoid an error. +% +% See also cat_run_newcatch. +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Revision$ $Date$ + + global cat_err_res; + + [pth,nam,ext] = spm_fileparts(job.channel(1).vols{subj}); + + % don't use try-catch call for octave + if strcmpi(spm_check_version,'octave') + if job.extopts.ignoreErrors>1 + % new pipeline that also include a warning because it still under test + cat_run_job(job,tpm,subj); % the cat_run_job1070 is only called by older functions + else + % RD202008: current version 1678+ is not stable and the 1639 seems to + % have the best result + cat_run_job1639(job,tpm,subj); + end + return + end + + try + if job.extopts.ignoreErrors>1 + % new pipeline that also include a warning because it still under test + cat_run_job(job,tpm,subj); + else + % RD202008: current versions are not that stable and the 1639 seems to + % have the best result + cat_run_job1639(job,tpm,subj); + end + catch caterr + + %% add further information for special errors + if isempty(caterr.identifier) + switch caterr.message + case 'insufficient image overlap' + adderr = MException('SPM:AlignmentError','There is not enough overlap in the images to obtain a solution.'); + otherwise + adderr = MException('SPM:CAT:cat_main',strrep(caterr.message,'\','\\')); + end + caterr = addCause(caterr,adderr); + end + + [mrifolder, reportfolder, surffolder, labelfolder, errfolder] = cat_io_subfolders(job.channel(1).vols{subj},job); + + cat_io_cprintf('err',sprintf('\n%s\nCAT Preprocessing error for %s:\n%s\n%s\n%s\n', ... + repmat('-',1,72),nam,repmat('-',1,72),caterr.message,repmat('-',1,72))); + + + %% check for filenames that are usually indicated by '""' + testmessage = 0; % just for tests + if testmessage + caterr.identifier = 'CAT:error0815:BadFileInput'; + caterr.message = ['Bad values variable ""xyz"" in ""C:\private\patient\name"" ' ... + 'and \n also in the second line ""/private2/patient/name"".\n ' ... + 'But also without /private3/pat3/nam3 and C:\blub\bla. ' ... + 'Don''t forget special character for area (33 mm' char(178) ... + ') or volume (3 mm' char(179) ') or 33' char(177) '0.33%.\n' ... + 'Ignore/Replace unclear chars :' char(200:210)]; + end + + % anonymize by removing filename within '""' characters were found + ind_str = strfind(caterr.message,'""'); + ind_str2 = [strfind(caterr.message,'/') strfind(caterr.message,'\') ... + strfind(caterr.message,'.nii') strfind(caterr.message,'.gii')]; + + caterr_id = caterr.identifier; + caterr_message_str = caterr.message; + if mod(length(ind_str),2) == 0 + for i = length(ind_str):-2:1 + if any( ind_str2>ind_str(i-1) & ind_str2|()&!?%?`''?^[]']; + caterr_idi = false( size( caterr_id ) ); + caterr_message_stri = false( size( caterr_message_str) ); + for wi=1:numel(whitelist) + caterr_idi( caterr_id == whitelist(wi) ) = true; + caterr_message_stri( caterr_message_str == whitelist(wi) ) = true; + end + if 0 % remove + caterr_id = caterr_id(caterr_idi); + caterr_message_str = caterr_message_str(caterr_message_stri); + else % replace ... maybe better do avoid empty messages + caterr_id(~caterr_idi) = 'X'; + caterr_message_str(~caterr_message_stri) = 'X'; + end + + % Or a private/general part that is useful for users but not for us. + + + % We may can use a general limitation for the error message? + maxlength = 256; + if numel(caterr_message_str)>maxlength + caterr_message_str = [spm_str_manip(caterr_message_str,sprintf('f%d',maxlength)) ' ...']; + end + + if testmessage + disp(caterr_message_str) + end + + %% remove uninteresting messages + ignore_message = 0; + keywords = { + ... possible orientation and resolution errors issues + 'insufficient image overlap' + 'Image does not have 3 dimensions.' + 'Voxel resolution has to be better than 5 mm' + 'Out of memory.' + 'cat_run_job:restype' + ... file reading/writing messages + '** failed to open' + 'Access is denied.' + 'Cannot open file' + 'Cannot create file mapping. ' + 'Cannot create output file ' + 'cp: cannot create regular file' + 'File too small' + 'Invalid file identifier.' + 'Permission denied' + 'The process cannot access the file ' + 'There was a problem while generating ' + 'Unable to write file' + }; + for ki = 1:numel(keywords) + if strfind( caterr_message_str , keywords{ki} ) + ignore_message = 1; + end + end + + %% send error information, CAT12 version and computer system + if cat_get_defaults('extopts.send_info') && ~ignore_message && job.extopts.expertgui<2 && job.extopts.ignoreErrors<2 + [CATrel,CATver] = cat_version; expertguistr = ' ed'; + str_err = sprintf('%s%s|',['r' CATver],deblank(expertguistr(job.extopts.expertgui + 1))); % revision and guilevel + for si=1:numel(caterr.stack) + str_err = [str_err '|' caterr.stack(si).name ':' num2str(caterr.stack(si).line)]; + end + urlinfo = sprintf('%s/%s/%s/%s/%s/%s/%s/%s',CATrel,computer,'errors',['r' CATver],caterr_id,version('-release'),caterr_message_str,str_err); + cat_io_send_to_server(urlinfo); + end + + % write error report + caterrtxt = cell(numel(caterr.stack)+2,1); + caterrtxt{1} = sprintf('%s\n',caterr.identifier); + caterrtxt{2} = sprintf('%s\n',caterr.message); + for si=1:numel(caterr.stack) + cat_io_cprintf('err',sprintf('% 5d - %s\n',caterr.stack(si).line,caterr.stack(si).name)); + caterrtxt{si+2} = sprintf('% 5d - %s\n',caterr.stack(si).line,caterr.stack(si).name); + end + cat_io_cprintf('err',sprintf('%s\n',repmat('-',1,72))); + + % save cat xml file + caterrstruct = struct(); + for si=1:numel(caterr.stack) + caterrstruct(si).line = caterr.stack(si).line; + caterrstruct(si).name = caterr.stack(si).name; + caterrstruct(si).file = caterr.stack(si).file; + end + + % better to have the res that the opt field + if exist('cat_err_res','var') + if isfield(cat_err_res,'res') + job.SPM.res = cat_err_res.res; + elseif isfield(cat_err_res,'obj') + job.SPM.opt = cat_err_res.obj; + end + end + + qa = cat_vol_qa('cat12err',struct('write_csv',0,'write_xml',1,'caterrtxt',{caterrtxt},'caterr',caterrstruct,'job',job,'subj',subj)); + cat_io_report(job,qa,subj) + + % delete noise corrected image + if exist(fullfile(pth,mrifolder,['n' nam ext]),'file') + try %#ok + delete(fullfile(pth,mrifolder,['n' nam ext])); + end + end + + % create mail report for serial processing + if ~isfield(job,'process_index') && feature('ShowFigureWindows') + promptMessage = sprintf('Do you want to send error message?'); + button = questdlg(promptMessage, 'Error message', 'Yes', 'No', 'Yes'); + if strcmpi(button, 'Yes') + catfile = fullfile(pth,reportfolder,['cat_' nam '.xml']); + logfile = fullfile(pth,reportfolder,['catlog_' nam '.txt']); + cat_io_senderrormail(catfile,logfile); + end + end + + % create an error directory with errortype subdirectory for all failed datasets + % copy the cat*.xml and catreport_*pdf + % create a symbolic link of the original file + + if job.extopts.subfolders + try + %% + [ppe,ffe] = spm_fileparts(caterr.stack(1).file); + suberrfolder = sprintf('%s.line%d.%s',ffe,caterr.stack(1).line,caterr.identifier); + suberrfolder = char(regexp(strrep(suberrfolder,':','.'),'[A-Za-z0-9_.\- ]','match'))'; % remove bad chars + suberrfolder = strrep(suberrfolder,' ','_'); + if ~exist(fullfile(pth,errfolder,suberrfolder),'dir'), mkdir(fullfile(pth,errfolder,suberrfolder)); end + catfile = fullfile(pth,reportfolder,['cat_' nam '.xml']); + logfile = fullfile(pth,reportfolder,['catlog_' nam '.txt']); + repfile = fullfile(pth,reportfolder,['catreport_' nam '.pdf']); + rejfile = fullfile(pth,reportfolder,['catreport_' nam '.jpg']); + if exist(catfile,'file'), copyfile(catfile,fullfile(pth,errfolder,suberrfolder),'f'); end + if exist(logfile,'file'), copyfile(logfile,fullfile(pth,errfolder,suberrfolder),'f'); end + if exist(repfile,'file'), copyfile(repfile,fullfile(pth,errfolder,suberrfolder),'f'); end + if exist(rejfile,'file'), copyfile(rejfile,fullfile(pth,errfolder,suberrfolder),'f'); end + if ismac || isunix + [ST, RS] = system(sprintf('ln -s -F ""%s"" ""%s""',... + fullfile(pth,[nam ext]),fullfile(pth,errfolder,suberrfolder,[nam ext]))); + cat_check_system_output(ST,RS,job.extopts.verb>2); + end + catch + cat_io_printf('warn','Warning: Cleanup error\.'); + end + end + + %% rethrow error + if ~job.extopts.ignoreErrors + rethrow(caterr); + end + end +end +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_io_cprintf.m",".m","32251","700","function count = cat_io_cprintf(style,format,varargin) %#ok<*JAPIMATHWORKS> +% CPRINTF displays styled formatted text in the Command Window +% +% Syntax: +% count = cprintf(style,format,...) +% +% Description: +% CPRINTF processes the specified text using the exact same FORMAT +% arguments accepted by the built-in SPRINTF and FPRINTF functions. +% +% CPRINTF then displays the text in the Command Window using the +% specified STYLE argument. The accepted styles are those used for +% Matlab's syntax highlighting (see: File / Preferences / Colors / +% M-file Syntax Highlighting Colors), and also user-defined colors. +% +% The possible pre-defined STYLE names are: +% +% 'Text' - default: black +% 'Keywords' - default: blue +% 'Comments' - default: green +% 'Strings' - default: purple +% 'UnterminatedStrings' - default: dark red +% 'SystemCommands' - default: orange +% 'Errors' - default: light red +% 'Hyperlinks' - default: underlined blue +% +% 'Black','Cyan','Magenta','Blue','Green','Red','Yellow','White' +% +% STYLE beginning with '-' or '_' will be underlined. For example: +% '-Blue' is underlined blue, like 'Hyperlinks'; +% '_Comments' is underlined green etc. +% +% STYLE beginning with '*' will be bold (R2011b+ only). For example: +% '*Blue' is bold blue; +% '*Comments' is bold green etc. +% Note: Matlab does not currently support both bold and underline, +% only one of them can be used in a single cprintf command. But of +% course bold and underline can be mixed by using separate commands. +% +% STYLE colors can be specified in 3 variants: +% [0.1, 0.7, 0.3] - standard Matlab RGB color format in the range 0.0-1.0 +% [26, 178, 76] - numeric RGB values in the range 0-255 +% '#1ab34d' - Hexadecimal format in the range '00'-'FF' (case insensitive) +% 3-digit HTML RGB format also accepted: 'a5f'='aa55ff' +% +% STYLE can be underlined by prefixing - : -[0,1,1] or '-#0FF' is underlined cyan +% STYLE can be made bold by prefixing * : '*[1,0,0]' or '*#F00' is bold red +% +% STYLE is case-insensitive and accepts unique partial strings just +% like handle property names. +% +% CPRINTF by itself, without any input parameters, displays a demo +% +% Example: +% cprintf; % displays the demo +% cprintf('text', 'regular black text'); +% cprintf('hyper', 'followed %s','by'); +% cprintf('key', '%d colored', 4); +% cprintf('-comment','& underlined'); +% cprintf('err', 'elements\n'); +% cprintf('cyan', 'cyan'); +% cprintf('_green', 'underlined green'); +% cprintf(-[1,0,1], 'underlined magenta'); +% cprintf([1,0.5,0],'and multi-\nline orange\n'); +% cprintf('*blue', 'and *bold* (R2011b+ only)\n'); +% cprintf('string'); % same as fprintf('string') and cprintf('text','string') +% +% Extended sytles in CAT12: +% {'t','txt','text','k'}, style=[0.0 0.0 0.0]; +% {'e','err','error'}, style=[0.8 0.0 0.0]; +% {'w','warn','warning'}, style=[1.0 0.3 0.0]; +% {'com','comment'}, style=[0.0 0.0 0.8]; +% {'note'}, style=[0.0 0.0 1.0]; +% {'caution'}, style=[0.5 0.0 1.0]; +% {'g','green'}, style=[0.0 1.0 0.0]; +% {'b','blue'}, style=[0.0 0.0 1.0]; +% {'r','red'}, style=[1.0 0.0 0.0]; +% {'c','cyan'}, style=[0.0 1.0 1.0]; +% {'m','magenta'}, style=[1.0 0.0 1.0]; +% {'y','yellow'}, style=[1.0 1.0 0.0]; +% {'o','orange'}, style=[1.0 0.5 0.0]; +% {'g9','gray9'}, style=[0.1 0.1 0.1]; +% {'g8','gray8'}, style=[0.2 0.2 0.2]; +% {'g7','gray7'}, style=[0.3 0.3 0.3]; +% {'g6','gray6'}, style=[0.3 0.4 0.4]; +% {'g5','gray5'}, style=[0.5 0.5 0.5]; +% +% Bugs and suggestions: +% Please send to Yair Altman (altmany at gmail dot com) +% +% Warning: +% This code heavily relies on undocumented and unsupported Matlab +% functionality. It works on Matlab 7+, but use at your own risk! +% +% A technical description of the implementation can be found at: +% http://UndocumentedMatlab.com/articles/cprintf +% +% Limitations: +% 1. In R2011a and earlier, a single space char is inserted at the +% beginning of each CPRINTF text segment (this is ok in R2011b+). +% +% 2. In R2011a and earlier, consecutive differently-colored multi-line +% CPRINTFs sometimes display incorrectly on the bottom line. +% As far as I could tell this is due to a Matlab bug. Examples: +% >> cprintf('-str','under\nline'); cprintf('err','red\n'); % hidden 'red', unhidden '_' +% >> cprintf('str','regu\nlar'); cprintf('err','red\n'); % underline red (not purple) 'lar' +% +% 3. Sometimes, non newline ('\n')-terminated segments display unstyled +% (black) when the command prompt chevron ('>>') regains focus on the +% continuation of that line (I can't pinpoint when this happens). +% To fix this, simply newline-terminate all command-prompt messages. +% +% 4. In R2011b and later, the above errors appear to be fixed. However, +% the last character of an underlined segment is not underlined for +% some unknown reason (add an extra space character to make it look better) +% +% 5. In old Matlab versions (e.g., Matlab 7.1 R14), multi-line styles +% only affect the first line. Single-line styles work as expected. +% R14 also appends a single space after underlined segments. +% +% 6. Bold style is only supported on R2011b+, and cannot also be underlined. +% +% Change log: +% 2009-05-13: First version posted on MathWorks File Exchange +% 2009-05-28: corrected nargout behavior suggested by Andreas Gäb +% 2009-09-28: Fixed edge-case problem reported by Swagat K +% 2010-06-27: Fix for R2010a/b; fixed edge case reported by Sharron; CPRINTF with no args runs the demo +% 2011-03-04: Performance improvement +% 2011-08-29: Fix by Danilo (FEX comment) for non-default text colors +% 2011-11-27: Fixes for R2011b +% 2012-08-06: Fixes for R2012b; added bold style; accept RGB string (non-numeric) style +% 2012-08-09: Graceful degradation support for deployed (compiled) and non-desktop applications; minor bug fixes +% 2015-03-20: Fix: if command window isn't defined yet (startup) use standard fprintf as suggested by John Marozas +% 2015-06-24: Fixed a few discoloration issues (some other issues still remain) +% 2020-01-20: Fix by T. Hosman for embedded hyperlinks +% 2021-04-07: Enabled specifying color as #RGB (hexa codes), [.1,.7,.3], [26,178,76] +% 2022-01-04: Fixed cases of invalid colors (especially bad on R2021b onward) +% 2022-03-26: Fixed cases of using string (not char) inputs +% +% See also: +% sprintf, fprintf +% License to use and modify this code is granted freely to all interested, as long as the original author is +% referenced and attributed as such. The original author maintains the right to be solely associated with this work. +% Programmed and Copyright by Yair M. Altman: altmany(at)gmail.com +% Revision: 1.14 $ Date: 2022/03/26 20:48:51 +% ______________________________________________________________________ +% Copyright (c) 2009, Yair Altman +% All rights reserved. +% +% Redistribution and use in source and binary forms, with or without +% modification, are permitted provided that the following conditions are +% met: +% +% * Redistributions of source code must retain the above copyright +% notice, this list of conditions and the following disclaimer. +% * Redistributions in binary form must reproduce the above copyright +% notice, this list of conditions and the following disclaimer in +% the documentation and/or other materials provided with the distribution +% +% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS"" +% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +% POSSIBILITY OF SUCH DAMAGE. +% ______________________________________________________________________ + +% $Revision$ $Date$ +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +persistent majorVersion minorVersion + +% #### begin extended styles #### +global cprintferror; %#ok +if isempty(cprintferror), cprintferror=0; end +if nargin==0, help cat_io_cprintf; return; end +if strcmp(style,'reset') || strcmp(style,'silentreset') + cprintferror = 0; + if strcmp(style,'reset') + style = [0.0 0.5 0.0]; + cat_io_cprintf(style,'Color output active!\n'); + end + return +end + +if cprintferror + warning off + count1 = fprintf(format,varargin{:}); + if nargout + count = count1; + end +else +% #### end extended styles ... well there is an end at the end of the function #### + + if isempty(majorVersion) + %v = version; if str2double(v(1:3)) <= 7.1 + %majorVersion = str2double(regexprep(version,'^(\d+).*','$1')); + %minorVersion = str2double(regexprep(version,'^\d+\.(\d+).*','$1')); + %[a,b,c,d,versionIdStrs]=regexp(version,'^(\d+)\.(\d+).*'); %#ok unused + v = sscanf(version, '%d.', 2); + majorVersion = v(1); %str2double(versionIdStrs{1}{1}); + minorVersion = v(2); %str2double(versionIdStrs{1}{2}); + end + % The following is for debug use only: + %global docElement el debugData + if ~strcmpi(spm_check_version,'octave') && (~exist('el','var') || isempty(el)), el=handle([]); end %#ok mlint short-circuit error (""used before defined"") + if nargin<1, showDemo(majorVersion,minorVersion); return; end + if isempty(style), return; end + % #### begin extended styles #### + if ischar(style) + switch lower(style) + case {'t','txt','text','k'}, style=[0.0 0.0 0.0]; + case {'e','err','error'}, style=[0.8 0.0 0.0]; + case {'w','warn','warning'}, style=[1.0 0.3 0.0]; + case {'com','comment'}, style=[0.0 0.0 0.8]; + case {'note'}, style=[0.0 0.0 1.0]; + case {'caution'}, style=[0.5 0.0 1.0]; + case {'g','green'}, style=[0.0 1.0 0.0]; + case {'b','blue'}, style=[0.0 0.0 1.0]; + case {'r','red'}, style=[1.0 0.0 0.0]; + case {'c','cyan'}, style=[0.0 1.0 1.0]; + case {'m','magenta'}, style=[1.0 0.0 1.0]; + case {'y','yellow'}, style=[1.0 1.0 0.0]; + case {'o','orange'}, style=[1.0 0.5 0.0]; + case {'g9','gray9'}, style=[0.1 0.1 0.1]; + case {'g8','gray8'}, style=[0.2 0.2 0.2]; + case {'g7','gray7'}, style=[0.3 0.3 0.3]; + case {'g6','gray6'}, style=[0.3 0.4 0.4]; + case {'g5','gray5'}, style=[0.5 0.5 0.5]; + otherwise, style=[0 0 0]; + end + elseif isnumeric(style) + if length(style)>3, style=double(style(1:3)); end + end + % #### end extended styles #### + if isa(style,'string'), style = char(style); end + if all(ishandle(style)) && length(style)~=3 + dumpElement(style); + return; + end + % Process the text string + if nargin<2, format = style; style='text'; end + if isa(format,'string'), format = char(format); end + %error(nargchk(2, inf, nargin, 'struct')); + %str = sprintf(format,varargin{:}); + % In compiled mode + try useDesktop = usejava('desktop'); catch, useDesktop = false; end + if isdeployed | ~useDesktop %#ok - for Matlab 6 compatibility + % do not display any formatting - use simple fprintf() + % See: http://undocumentedmatlab.com/blog/bold-color-text-in-the-command-window/#comment-103035 + % Also see: https://mail.google.com/mail/u/0/?ui=2&shva=1#all/1390a26e7ef4aa4d + % Also see: https://mail.google.com/mail/u/0/?ui=2&shva=1#all/13a6ed3223333b21 + count1 = fprintf(format,varargin{:}); + else + % Else (Matlab desktop mode) + % Get the normalized style name and underlining flag + [underlineFlag, boldFlag, style, debugFlag] = processStyleInfo(style); + % Set hyperlinking, if so requested + if underlineFlag + prefix = ''; + %format = [prefix format '']; % this displayed incorrectly for embedded hyperlinks + % Handle case of embedded hyperlinks with underline format 5/1/2020 + str = sprintf(format, varargin{:}); + str = regexprep(str,{'','_@@@_'},{'_@@@_' prefix],''},'ignorecase'); + str = [prefix str '']; + format = '%s'; varargin = {str}; + % Matlab 7.1 R14 (possibly a few newer versions as well?) + % have a bug in rendering consecutive hyperlinks + % This is fixed by appending a single non-linked space + if majorVersion < 7 || (majorVersion==7 && minorVersion <= 1) + format(end+1) = ' '; + end + end + % Set bold, if requested and supported (R2011b+) + if boldFlag + if (majorVersion > 7 || minorVersion >= 13) + format = ['' format '']; + else + boldFlag = 0; + end + end + % Get the current CW position + cmdWinDoc = com.mathworks.mde.cmdwin.CmdWinDocument.getInstance; + lastPos = cmdWinDoc.getLength; + % If not beginning of line + bolFlag = 0; %#ok + %if docElement.getEndOffset - docElement.getStartOffset > 1 + % Display a hyperlink element in order to force element separation + % (otherwise adjacent elements on the same line will be merged) + if majorVersion<7 || (majorVersion==7 && minorVersion<13) + if ~underlineFlag + fprintf(' '); %fprintf(' \b'); + elseif format(end)~=10 % if no newline at end + fprintf(' '); %fprintf(' \b'); + end + end + %drawnow; + bolFlag = 1; + %end + % Get a handle to the Command Window component + mde = com.mathworks.mde.desk.MLDesktop.getInstance; + cw = mde.getClient('Command Window'); + % Fix: if command window isn't defined yet (startup), use standard fprintf() + if (isempty(cw)) + count1 = fprintf(format,varargin{:}); + if nargout + count = count1; + end + return; + end + + xCmdWndView = cw.getComponent(0).getViewport.getComponent(0); + % Store the CW background color as a special color pref + % This way, if the CW bg color changes (via File/Preferences), + % it will also affect existing rendered strs + com.mathworks.services.Prefs.setColorPref('CW_BG_Color',xCmdWndView.getBackground); + % Display the text in the Command Window + % Note: fprintf(2,...) is required in order to add formatting tokens, which + % ^^^^ can then be updated below (no such tokens when outputting to stdout) + %format(end+1) = ' '; % Jacob D's FEX comment 14/6/2016 (sometimes makes things worse!) https://mail.google.com/mail/u/0/#inbox/15551268609f9fef + cmdWinLen = cmdWinDoc.getLength; + cmdWinLenPrev = cmdWinLen; + count1 = fprintf(2,format,varargin{:}); + % Repaint the command window (wait a bit for the async update to complete) + iter = 0; + while count1 > 0 && cmdWinLen <= cmdWinLenPrev && iter < 100 + %awtinvoke(cmdWinDoc,'remove',lastPos,1); % TODO: find out how to remove the extra '_' + drawnow; % this is necessary for the following to work properly (refer to Evgeny Pr in FEX comment 16/1/2011) + pause(0.01); + xCmdWndView.repaint; + %hListeners = cmdWinDoc.getDocumentListeners; for idx=1:numel(hListeners), try hListeners(idx).repaint; catch, end, end + cmdWinLen = cmdWinDoc.getLength; + iter = iter + 1; + end + docElement = cmdWinDoc.getParagraphElement(lastPos+1); + if majorVersion<7 || (majorVersion==7 && minorVersion<13) + if bolFlag && ~underlineFlag + % Set the leading hyperlink space character ('_') to the bg color, effectively hiding it + % Note: old Matlab versions have a bug in hyperlinks that need to be accounted for... + %disp(' '); dumpElement(docElement) + setElementStyle(docElement,'CW_BG_Color',1+underlineFlag,majorVersion,minorVersion); %+getUrlsFix(docElement)); + %disp(' '); dumpElement(docElement) + el(end+1) = handle(docElement); % #ok used in debug only + end + % Fix a problem with some hidden hyperlinks becoming unhidden... + fixHyperlink(docElement); + %dumpElement(docElement); + end + % Get the Document Element(s) corresponding to the latest fprintf operation + %debugData = [iter, count1, lastPos, docElement.getStartOffset, cmdWinLen]; + while docElement.getStartOffset <= cmdWinLen + % Set the element style according to the current style + if debugFlag, dumpElement(docElement); end + specialFlag = underlineFlag | boldFlag; + setElementStyle(docElement,style,specialFlag,majorVersion,minorVersion); + if debugFlag, dumpElement(docElement); end + docElement2 = cmdWinDoc.getParagraphElement(docElement.getEndOffset+1); + if isequal(docElement,docElement2), break; end + docElement = docElement2; + end + if debugFlag, dumpElement(docElement); end + % Force a Command-Window repaint + % Note: this is important in case the rendered str was not '\n'-terminated + xCmdWndView.repaint; + %fprintf('\b'); % Jacob D's FEX comment 14/6/2016 (sometimes makes things worse!) https://mail.google.com/mail/u/0/#inbox/15551268609f9fef + % The following is for debug use only: + el(end+1) = handle(docElement); %#ok used in debug only + %elementStart = docElement.getStartOffset; + %elementLength = docElement.getEndOffset - elementStart; + %txt = cmdWinDoc.getText(elementStart,elementLength); + end + if nargout + count = count1; + end +end +return; % debug breakpoint +% Process the requested style information +function [underlineFlag,boldFlag,style,debugFlag] = processStyleInfo(style) + underlineFlag = 0; + boldFlag = 0; + debugFlag = 0; + % First, strip out the underline/bold markers + if ischar(style) + % Styles containing '-' or '_' should be underlined (using a no-target hyperlink hack) + %if style(1)=='-' + underlineIdx = (style=='-') | (style=='_'); + if any(underlineIdx) + underlineFlag = 1; + %style = style(2:end); + style = style(~underlineIdx); + end + % Check for bold style (only if not underlined) + boldIdx = (style=='*'); + if any(boldIdx) + boldFlag = 1; + style = style(~boldIdx); + end + if underlineFlag && boldFlag + warning('YMA:cprintf:BoldUnderline','Matlab does not support both bold & underline') + end + % Check for debug mode (style contains '!') + debugIdx = (style=='!'); + if any(debugIdx) + debugFlag = 1; + style = style(~debugIdx); + end + % Check if the remaining style sting is a numeric vector + %styleNum = str2num(style); %#ok % not good because style='text' is evaled! + %if ~isempty(styleNum) + if any(style==' ' | style==',' | style==';') + style = str2num(style); %#ok + end + end + % Style = valid matlab RGB vector: [0.1,0.2,0.3] or [25,50,75] + if isnumeric(style) && length(style)==3 && all(style<=255) && all(abs(style)>=0) + if any(style<0) + underlineFlag = 1; + style = abs(style); + end + style = getColorStyle(style); + elseif ~ischar(style) + error('YMA:cprintf:InvalidStyle','Invalid style - see help section for a list of valid style values') + % #RGB in hex mode (suggested by Andres Tönnesmann 26/3/21 https://mail.google.com/mail/u/0/#inbox/FMfcgxwLtGlbzftbfKJwWLNZKpSqzHhR) + elseif style(1) == '#' + hexCode = style(2:min(end,7)); + if length(hexCode)==3, hexCode = reshape([hexCode;hexCode],1,[]); end % #a5f -> #aa55ff + hexCode = sprintf('%06s',hexCode); % pad with leading 00s + hexCode = reshape(hexCode,2,3)'; % '1a2b3c' -> ['1a'; '2b'; '3c'] + rgb = hex2dec(hexCode); % convert to [r,g,b] tripplet (0-255 values) + style = getColorStyle(rgb); + % Style name + else + % Try case-insensitive partial/full match with the accepted style names + matlabStyles = {'Text','Keywords','Comments','Strings','UnterminatedStrings','SystemCommands','Errors'}; + validStyles = [matlabStyles, ... + 'Black','Cyan','Magenta','Blue','Green','Red','Yellow','White', ... + 'Hyperlinks']; + matches = find(strncmpi(style,validStyles,length(style))); + % No match - error + if isempty(matches) + error('YMA:cprintf:InvalidStyle','Invalid style - see help section for a list of valid style values') + % Too many matches (ambiguous) - error + elseif length(matches) > 1 + error('YMA:cprintf:AmbigStyle','Ambiguous style name - supply extra characters for uniqueness') + % Regular text + elseif matches == 1 + style = 'ColorsText'; % fixed by Danilo, 29/8/2011 + % Highlight preference style name + elseif matches <= length(matlabStyles) + style = ['Colors_M_' validStyles{matches}]; + % Color name + elseif matches < length(validStyles) + colors = [0,0,0; 0,1,1; 1,0,1; 0,0,1; 0,1,0; 1,0,0; 1,1,0; 1,1,1]; + requestedColor = colors(matches-length(matlabStyles),:); + style = getColorStyle(requestedColor); + % Hyperlink + else + style = 'Colors_HTML_HTMLLinks'; % CWLink + underlineFlag = 1; + end + end +% Convert a Matlab RGB vector into a known style name (e.g., '[255,37,0]') +function styleName = getColorStyle(rgb) + if all(rgb<=1), rgb = rgb*255; end % 0.5 -> 127 + intColor = int32(rgb); + javaColor = java.awt.Color(intColor(1), intColor(2), intColor(3)); + styleName = sprintf('[%d,%d,%d]',intColor); + com.mathworks.services.Prefs.setColorPref(styleName,javaColor); +% Fix a bug in some Matlab versions, where the number of URL segments +% is larger than the number of style segments in a doc element +function delta = getUrlsFix(docElement) %currently unused + tokens = docElement.getAttribute('SyntaxTokens'); + links = docElement.getAttribute('LinkStartTokens'); + if length(links) > length(tokens(1)) + delta = length(links) > length(tokens(1)); + else + delta = 0; + end +% fprintf(2,str) causes all previous '_'s in the line to become red - fix this +function fixHyperlink(docElement) + try + tokens = docElement.getAttribute('SyntaxTokens'); + urls = docElement.getAttribute('HtmlLink'); + urls = urls(2); + links = docElement.getAttribute('LinkStartTokens'); + offsets = tokens(1); + styles = tokens(2); + doc = docElement.getDocument; + % Loop over all segments in this docElement + for idx = 1 : length(offsets)-1 + % If this is a hyperlink with no URL target and starts with ' ' and is collored as an error (red)... + if strcmp(styles(idx).char,'Colors_M_Errors') + character = char(doc.getText(offsets(idx)+docElement.getStartOffset,1)); + if strcmp(character,' ') + if isempty(urls(idx)) && links(idx)==0 + % Revert the style color to the CW background color (i.e., hide it!) + styles(idx) = java.lang.String('CW_BG_Color'); + end + end + end + end + catch + % never mind... + end +% Set an element to a particular style (color) +function setElementStyle(docElement,style,specialFlag, majorVersion,minorVersion) + %global tokens links urls urlTargets % for debug only + global oldStyles %#ok + if nargin<3, specialFlag=0; end + % Set the last Element token to the requested style: + % Colors: + tokens = docElement.getAttribute('SyntaxTokens'); + try + styles = tokens(2); + oldStyles{end+1} = cell(styles); + % Correct edge case problem + extraInd = double(majorVersion>7 || (majorVersion==7 && minorVersion>=13)); % =0 for R2011a-, =1 for R2011b+ + %{ + if ~strcmp('CWLink',char(styles(end-hyperlinkFlag))) && ... + strcmp('CWLink',char(styles(end-hyperlinkFlag-1))) + extraInd = 0;%1; + end + hyperlinkFlag = ~isempty(strmatch('CWLink',tokens(2))); + hyperlinkFlag = 0 + any(cellfun(@(c)(~isempty(c)&&strcmp(c,'CWLink')),cell(tokens(2)))); + %} + jStyle = java.lang.String(style); + if numel(styles)==4 && isempty(char(styles(2))) + % Attempt to fix discoloration issues - NOT SURE THAT THIS IS OK! - 24/6/2015 + styles(1) = jStyle; + end + styles(end-extraInd) = java.lang.String(''); + styles(end-extraInd-specialFlag) = jStyle; % #ok apparently unused but in reality used by Java + if extraInd + styles(end-specialFlag) = jStyle; + end + oldStyles{end} = [oldStyles{end} cell(styles)]; + catch + % never mind for now + end + + % Underlines (hyperlinks): + %{ + links = docElement.getAttribute('LinkStartTokens'); + if isempty(links) + %docElement.addAttribute('LinkStartTokens',repmat(int32(-1),length(tokens(2)),1)); + else + %TODO: remove hyperlink by setting the value to -1 + end + %} + % Correct empty URLs to be un-hyperlinkable (only underlined) + urls = docElement.getAttribute('HtmlLink'); + if ~isempty(urls) + urlTargets = urls(2); + for urlIdx = 1 : length(urlTargets) + try + if urlTargets(urlIdx).length < 1 + urlTargets(urlIdx) = []; % '' => [] + else % fix for hyperlinks by T. Hosman 25/11/2019 (via email) + if urlIdx > 1 + styles(urlIdx-1) = jStyle; + end + styles(urlIdx) = jStyle; %=java.lang.String('CWLink'); + end + catch + % never mind... + a=1; %#ok used for debug breakpoint... + end + end + end + + % Bold: (currently unused because we cannot modify this immutable int32 numeric array) + %{ + try + %hasBold = docElement.isDefined('BoldStartTokens'); + bolds = docElement.getAttribute('BoldStartTokens'); + if ~isempty(bolds) + %docElement.addAttribute('BoldStartTokens',repmat(int32(1),length(bolds),1)); + end + catch + % never mind - ignore... + a=1; %#ok used for debug breakpoint... + end + %} + + return; % debug breakpoint +% Display information about element(s) +function dumpElement(docElements) + %return; + disp(' '); + numElements = length(docElements); + cmdWinDoc = docElements(1).getDocument; + for elementIdx = 1 : numElements + if numElements > 1, fprintf('Element #%d:\n',elementIdx); end + docElement = docElements(elementIdx); + if ~isjava(docElement), docElement = docElement.java; end + %docElement.dump(java.lang.System.out,1) + disp(strtrim(char(docElement))) + txt = {}; + try + tokens = docElement.getAttribute('SyntaxTokens'); + %if isempty(tokens), continue; end + links = docElement.getAttribute('LinkStartTokens'); + urls = docElement.getAttribute('HtmlLink'); + try bolds = docElement.getAttribute('BoldStartTokens'); catch, bolds = []; end + tokenLengths = tokens(1); + for tokenIdx = 1 : length(tokenLengths)-1 + tokenLength = diff(tokenLengths(tokenIdx+[0,1])); + if (tokenLength < 0) + tokenLength = docElement.getEndOffset - docElement.getStartOffset - tokenLengths(tokenIdx); + end + txt{tokenIdx} = cmdWinDoc.getText(docElement.getStartOffset+tokenLengths(tokenIdx),tokenLength).char; %#ok + end + catch + tokenLengths = 0; + end + lastTokenStartOffset = docElement.getStartOffset + tokenLengths(end); + try + txt{end+1} = cmdWinDoc.getText(lastTokenStartOffset, docElement.getEndOffset-lastTokenStartOffset).char; %#ok + catch + txt{end+1} = ''; %#ok + end + %cmdWinDoc.uiinspect + %docElement.uiinspect + txt = strrep(txt',sprintf('\n'),'\n'); %#ok + try + data = [cell(tokens(2)) m2c(tokens(1)) m2c(links) m2c(urls(1)) cell(urls(2)) m2c(bolds) txt]; + if elementIdx==1 + disp(' SyntaxTokens(2,1) - LinkStartTokens - HtmlLink(1,2) - BoldStartTokens - txt'); + disp(' =============================================================================='); + end + catch + try + data = [cell(tokens(2)) m2c(tokens(1)) m2c(links) txt]; + catch + try + disp([cell(tokens(2)) m2c(tokens(1)) txt]); + data = [m2c(links) m2c(urls(1)) cell(urls(2))]; + catch + % Matlab 7.1 only has urls(1)... + try + data = [m2c(links) cell(urls)]; + catch % no tokens + data = txt; + end + end + end + end + disp(data) + end +% Utility function to convert matrix => cell +function cells = m2c(data) + %datasize = size(data); cells = mat2cell(data,ones(1,datasize(1)),ones(1,datasize(2))); + cells = num2cell(data); +% Display the help and demo +function showDemo(majorVersion,minorVersion) + fprintf('cprintf displays formatted text in the Command Window.\n\n'); + fprintf('Syntax: count = cprintf(style,format,...); click here for details.\n\n'); + url = 'http://UndocumentedMatlab.com/articles/cprintf'; + fprintf(['Technical description: ' url '\n\n']); + fprintf('Demo:\n\n'); + boldFlag = majorVersion>7 || (majorVersion==7 && minorVersion>=13); + s = ['cprintf(''text'', ''regular black text'');' 10 ... + 'cprintf(''hyper'', ''followed %s'',''by'');' 10 ... + 'cprintf(''key'', ''%d colored'',' num2str(4+boldFlag) ');' 10 ... + 'cprintf(''-comment'',''& underlined'');' 10 ... + 'cprintf(''err'', ''elements:\n'');' 10 ... + 'cprintf(''cyan'', ''cyan'');' 10 ... + 'cprintf(''_green'', ''underlined green'');' 10 ... + 'cprintf(-[1,0,1], ''underlined magenta'');' 10 ... + 'cprintf([1,0.5,0], ''and multi-\nline orange\n'');' 10]; + if boldFlag + % In R2011b+ the internal bug that causes the need for an extra space + % is apparently fixed, so we must insert the sparator spaces manually... + % On the other hand, 2011b enables *bold* format + s = [s 'cprintf(''*blue'', ''and *bold* (R2011b+ only)\n'');' 10]; + s = strrep(s, ''')',' '')'); + s = strrep(s, ''',5)',' '',5)'); + s = strrep(s, '\n ','\n'); + end + disp(s); + eval(s); + +%%%%%%%%%%%%%%%%%%%%%%%%%% TODO %%%%%%%%%%%%%%%%%%%%%%%%% +% - Fix: Remove leading space char (hidden underline '_') +% - Fix: Find workaround for multi-line quirks/limitations +% - Fix: Non-\n-terminated segments are displayed as black +% - Fix: Check whether the hyperlink fix for 7.1 is also needed on 7.2 etc. +% - Enh: Add font support","MATLAB" +"Neurology","ChristianGaser/cat12","cat_vol_grad.m",".m","2222","65","function Yg = cat_vol_grad(Ym,vx_vol,method,repNaN) +% ---------------------------------------------------------------------- +% Simple gradient map for edge description. Default method is the absolute +% sum of all vectors but this should be replaced in future by the length +% of the gradient (RD202111). The function (temporary) replaces NaN to +% reduce boundary effects. +% +% Yg = cat_vol_grad(Ym,vx_vol,method) +% +% Ym .. input image +% Yg .. gradient map +% vx_vol .. voxel size (default=[1 1 1]); +% method .. averaging method (0-abs sum, 1-sum, 2-grad legth, default=0) +% repNaN .. replace NaN (0-no, 1-permanent, 2-temporary, default=1) +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + if ~exist('vx_vol','var'), vx_vol = ones(1,3); end + if ~exist('method','var'), method = 1; end + if ~exist('repNaN','var'), repNaN = 1; end + if isscalar(vx_vol) + vx_vol(2:3) = vx_vol(1); + elseif numel(vx_vol) ~= 3 + error('cat_vol_grad:vx_vol','The size of the second input (vx_vol) has to be 1 or 3.\n'); + end + + Ym = single(Ym); + + % temporary replace NaNs by nearest values + if repNaN + Ynan = isnan(Ym); + [D,I] = cat_vbdist(single(~Ynan),cat_vol_morph(~Ynan,'d',1)); Ym(D<2) = Ym(I(D<2)); % replace nan + clear D I; + else + Ynan = false(size(Ym)); + end + + % remove empty space/nan + [Ym,BB] = cat_vol_resize(Ym,'reduceBrain', 1, 4, Ym~=0 & ~Ynan); + + [gx,gy,gz] = cat_vol_gradient3(Ym); + + % averaging + switch method + case 0, Yg = gx./vx_vol(1) + gy./vx_vol(2) + gz./vx_vol(3); % simple sum + case 1, Yg = abs(gx./vx_vol(1)) + abs(gy./vx_vol(2)) + abs(gz./vx_vol(3)); % absolute sum + case 2, Yg = ((gx/vx_vol(1)).^2 + (gy/vx_vol(2)).^2 + (gz/vx_vol(3)).^2).^(0.5); % gradient length + end + + Yg = cat_vol_resize(Yg, 'dereduceBrain', BB); + + % restore nan + if repNaN==1 + Yg(Ynan) = 0; + elseif repNaN==2 + Yg(Ynan) = nan; + end +return +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_stat_spm2x.m",".m","20105","663","function out = cat_stat_spm2x(job) +%cat_stat_spm2x transformation of +% t-maps to P, -log(P), r or d-maps +% F-maps to P, -log(P), R2 maps +% +% --------------------------------------------- +% The following equations are used for t-maps: +% --------------------------------------------- +% +% --------------------------------------------- +% correlation coefficient: +% +% t +% r = ------------------ +% sqrt(t^2 + df) +% +% --------------------------------------------- +% (uncorrected) effect size d without Bessel +% correction for unequal sample sizes +% +% d = 2*t/sqrt(df(2)); +% +% --------------------------------------------- +% Standard normal (Z-value) +% +% Z = spm_t2z(t,df(2)); +% +% --------------------------------------------- +% p-value: +% +% p = 1-spm_Tcdf +% +% --------------------------------------------- +% log p-value: +% +% -log10(1-P) = -log(1-spm_Tcdf) +% +% --------------------------------------------- +% The following equations are used for F-maps: +% --------------------------------------------- +% +% --------------------------------------------- +% coefficient of determination R2: +% +% 1 +% R2 = 1 - ------------------ +% 1 + F*(p-1)/n-p) +% +% --------------------------------------------- +% p-value: +% +% p = 1-spm_Fcdf +% +% --------------------------------------------- +% log p-value: +% +% -log10(1-P) = -log(1-spm_Fcdf) +% +% For the last case of log transformation this means that a p-value of p=0.99 (0.01) +% is transformed to a value of 2 +% +% Examples: +% p-value -log10(1-P) +% 0.1 1 +% 0.05 1.30103 (-log10(0.05)) +% 0.01 2 +% 0.001 3 +% 0.0001 4 +% +% All maps can be thresholded using height and extent thresholds and you can +% also apply corrections for multiple comparisons based on family-wise error +% (FWE) or false discovery rate (FDR). You can easily threshold and/or +% transform a large number of spmT/F-maps using the same thresholds. +% +% Naming convention of the transformed files: +% Type_Contrast_Pheight_Pextent_K_Neg +% +% Type: P - p-value +% logP - log p-value +% R - correlation coefficient +% D - effect size +% T - t-value +% R2 - coefficient of determination +% F - F-value +% +% Contrast: name used in the contrast manager while replacing none valid strings +% +% Pheight: p - uncorrected p-value in % (p<0.05 will coded with ""p5"") +% pFWE - p-value with FWE correction in % +% pFDR - p-value with FDR correction in % +% +% Pextent: pk - uncorr. extent p-value in % (p<0.05 coded with ""p5"") +% pkFWE - extent p-value with FWE correction in % +% +% K: extent threshold in voxels +% +% Neg: image also shows thresholded inverse effects (e.g. neg. values) +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +if nargin > 0 + if isfield(job,'data_T2x') + T2x = 1; + stat = 'T'; + P = char(job.data_T2x); + else + T2x = 0; + stat = 'F'; + P = char(job.data_F2x); + end + + sel = job.conversion.sel; + + if isfield(job.conversion.threshdesc,'fwe') + adjustment = 1; + u0 = job.conversion.threshdesc.fwe.thresh05; + elseif isfield(job.conversion.threshdesc,'fdr') + adjustment = 2; + u0 = job.conversion.threshdesc.fdr.thresh05; + elseif isfield(job.conversion.threshdesc,'uncorr') + adjustment = 0; + u0 = job.conversion.threshdesc.uncorr.thresh001; + elseif isfield(job.conversion.threshdesc,'none') + adjustment = -1; + u0 = -Inf; + end + + if isfield(job.conversion.cluster,'fwe2') + extent_FWE = 1; + pk = job.conversion.cluster.fwe2.thresh05; + noniso = job.conversion.cluster.fwe2.noniso; + elseif isfield(job.conversion.cluster,'kuncorr') + extent_FWE = 0; + pk = job.conversion.cluster.kuncorr.thresh05; + noniso = job.conversion.cluster.kuncorr.noniso; + elseif isfield(job.conversion.cluster,'k') + extent_FWE = 0; + pk = job.conversion.cluster.k.kthresh; + noniso = job.conversion.cluster.k.noniso; + elseif isfield(job.conversion.cluster,'En') + extent_FWE = 0; + pk = -1; + noniso = job.conversion.cluster.En.noniso; + else + extent_FWE = 0; + pk = 0; + noniso = 0; + end + + if T2x + neg_results = job.conversion.inverse; + end + +else + + %-Get type of statistic + %------------------------------------------------------------------- + T2x = spm_input('Type of statistic',1,'b','T|F',[1 0],1); + + if T2x + stat = 'T'; + P = spm_select(Inf,'^(spmT|nullT).*(img|nii|gii)','Select T-images'); + sel = spm_input('Convert t value to?',1,'m',... + '1-p|-log(1-p)|correlation coefficient cc (only for regression)|effect size d (only for 2-sample t-test)|apply thresholds without conversion|Z-score',1:6, 2); + else + stat = 'F'; + P = spm_select(Inf,'^spmF.*(img|nii|gii)','Select F-images'); + sel = spm_input('Convert F value to?',1,'m',... + '1-p|-log(1-p)|coefficient of determination R^2 (only for regression)|apply thresholds without conversion',1:4, 2); + end + + %-Get height threshold + %------------------------------------------------------------------- + str = 'FWE|FDR|uncorr|none'; + adjustment = spm_input('p value adjustment to control','+1','b',str,[1 2 0 -1],1); + + switch adjustment + case 1 % family-wise false positive rate + %--------------------------------------------------------------- + u0 = spm_input('p value (family-wise error)','+0','r',0.05,1,[0,1]); + case 2 % False discovery rate + %--------------------------------------------------------------- + u0 = spm_input('p value (false discovery rate)','+0','r',0.05,1,[0,1]); + case 0 %-NB: no adjustment + % p for conjunctions is p of the conjunction SPM + %--------------------------------------------------------------- + u0 = spm_input(sprintf('threshold {%s or p value}',stat),'+0','r',0.001,1); + otherwise %-NB: no threshold + % p for conjunctions is p of the conjunction SPM + %--------------------------------------------------------------- + u0 = -Inf; + end + + if adjustment > -1 + pk = spm_input('extent threshold {k or p-value}','+1','r',0,1); + else + pk = 0; + end + if (pk < 1) && (pk > 0) + extent_FWE = spm_input('p value (extent)','+1','b','uncorrected|FWE corrected',[0 1],1); + end + + if T2x + if adjustment < 0 + neg_results = 1; + else + neg_results = spm_input('Show also inverse effects (e.g. neg. values)','+1','b','yes|no',[1 0],2); + end + end + + if pk ~= 0 + noniso = spm_input('Correct for non-isotropic smoothness?','+1','b','no|yes',[0 1],2); + else + noniso = 0; + end +end + +switch adjustment +case 1 % family-wise false positive rate + p_height_str = '_pFWE'; +case 2 % False discovery rate + p_height_str = '_pFDR'; +case 0 %-NB: no adjustment + p_height_str = '_p'; +otherwise %-NB: no threshold + p_height_str = ''; +end + +Pname = cell(size(P,1),1); + +for i=1:size(P,1) + [pth,nm] = spm_fileparts(deblank(P(i,:))); + + SPM_name = fullfile(pth, 'SPM.mat'); + + % SPM.mat exist? + if ~exist(SPM_name,'file') + error('SPM.mat not found') + end + + if strcmp(nm(1:6),sprintf('spm%s_0',stat)) || strcmp(nm(1:7),sprintf('nullT_0')) + Ic = str2double(nm(length(nm)-2:length(nm))); + else + % conversion needs spmT/F images + if sel < 5 + error('Only spm%s_0* files can be used',stat); + else + Ic = str2double(nm(length(nm)-2:length(nm))); + end + end + + load(SPM_name); + xCon = SPM.xCon; + df = [xCon(Ic).eidf SPM.xX.erdf]; + STAT = xCon(Ic).STAT; + R = SPM.xVol.R; %-search Volume {resels} + R = R(1:find(R~=0,1,'last')); % eliminate null resel counts + S = SPM.xVol.S; %-search Volume {voxels} + XYZ = SPM.xVol.XYZ; %-XYZ coordinates + FWHM = SPM.xVol.FWHM; + v2r = 1/prod(FWHM(~isinf(FWHM))); %-voxels to resels + + % correct path for surface if analysis was made with different SPM installation + if isfield(SPM.xVol,'G') + if ischar(SPM.xVol.G) && ~exist(SPM.xVol.G,'file') + % check for 32k meshes + if SPM.xY.VY(1).dim(1) == 32492 || SPM.xY.VY(1).dim(1) == 64984 + fsavgDir = fullfile(fileparts(mfilename('fullpath')),'templates_surfaces_32k'); + else + fsavgDir = fullfile(fileparts(mfilename('fullpath')),'templates_surfaces'); + end + [SPMpth,SPMname,SPMext] = spm_fileparts(SPM.xVol.G); + SPM.xVol.G = fullfile(fsavgDir,[SPMname SPMext]); + end + end + + Vspm = spm_data_hdr_read(deblank(P(i,:))); + + if ~isfield(SPM.xVol,'VRpv') + noniso = 0; + end + + if noniso + SPM.xVol.VRpv.fname = fullfile(pth,SPM.xVol.VRpv.fname); + end + + switch adjustment + case 1 % family-wise false positive rate + %--------------------------------------------------------------- + u = spm_uc(u0,df,STAT,R,1,S); + + case 2 % False discovery rate + %--------------------------------------------------------------- + u = spm_uc_FDR(u0,df,STAT,1,Vspm,0); + + otherwise %-NB: no adjustment + % p for conjunctions is p of the conjunction SPM + %--------------------------------------------------------------- + if (u0 <= 1) && (u0 > 0) + u = spm_u(u0,df,STAT); + else + u = u0; + end + end + + Z = spm_data_read(Vspm.fname,'xyz',XYZ); + + %-Calculate height threshold filtering + %------------------------------------------------------------------- + if T2x && neg_results + Qh = find((Z > u) | (Z < -u)); + else + Qh = find(Z > u); + end + + %-Apply height threshold + %------------------------------------------------------------------- + Z = Z(:,Qh); + XYZ = XYZ(:,Qh); + if isempty(Qh) + fprintf('No voxels survived height threshold u=%0.2g\n',u); + Qe = []; + end + + %-Extent threshold + %----------------------------------------------------------------------- + if ~isempty(XYZ) + + if (pk < 1) && (pk > 0) + if extent_FWE + Pk = 1; + k = 0; + while (Pk >= pk && k= pk && k 0) && isfield(job,'atlas') && ~strcmp(job.atlas,'None') + labk = cell(max(A)+2,1); + Pl = cell(max(A)+2,1); + Zj = cell(max(A)+2,1); + maxZ = zeros(max(A)+2,1); + XYZmmj = cell(max(A)+2,1); + + XYZmm = Vspm.mat(1:3,:)*[XYZ; ones(1,size(XYZ,2))]; %-voxel coordinates {mm} + atlas_name = job.atlas; + xA = spm_atlas('load',atlas_name); + end + + Qe = []; + if noniso + fprintf('Use local RPV values to correct for non-stationary of smoothness.\n'); + + warning('off','MATLAB:subscripting:noSubscriptsSpecified'); + if isfield(SPM.xVol,'G') % mesh detected? + [N2,Z2,XYZ2,A2,L2] = cat_surf_max(abs(Z),XYZ,gifti(SPM.xVol.G)); + else + [N2,Z2,XYZ2,A2,L2] = spm_max(abs(Z),XYZ); + end + + % sometimes max of A and A2 differ, thus we have to use the smaller value + for i2 = 1:min([max(A) max(A2)]) + + %-Get LKC for voxels in i-th region + %---------------------------------------------------------- + LKC = spm_data_read(SPM.xVol.VRpv.fname,'xyz',L2{i2}); + + %-Compute average of valid LKC measures for i-th region + %---------------------------------------------------------- + valid = ~isnan(LKC); + if any(valid) + LKC = sum(LKC(valid)) / sum(valid); + else + LKC = v2r; % fall back to whole-brain resel density + end + + %-Intrinsic volume (with surface correction) + %---------------------------------------------------------- + IV = spm_resels([1 1 1],L2{i2},'V'); + IV = IV*[1/2 2/3 2/3 1]'; + k_noniso = IV*LKC/v2r; + + % find corresponding cluster in spm_clusters if cluster exceeds threshold + if k_noniso > k + ind2 = find(A2==i2); + for l = 1:min([max(A) max(A2)]) + j = find(A == l); + if length(j)==N2(ind2) + if any(ismember(XYZ2(:,ind2)',XYZ(:,j)','rows')) + Qe = [Qe j]; + + % save atlas measures for 3D data + if (nargin > 0) && isfield(job,'atlas') && ~strcmp(job.atlas,'None') + [labk{i2}, Pl{i2}] = spm_atlas('query',xA,XYZmm(:,j)); + Zj{i2} = Z(:,j); + XYZmmj{i2} = XYZmm(:,j); + maxZ(i2) = sign(Zj{i2}(1))*max(abs(Zj{i2})); + end + break + end + end + end + end + end + else + for i2 = 1:min(max(A)) + j = find(A == i2); + if length(j) > k + Qe = [Qe j]; + + % save atlas measures for 3D data + if (nargin > 0) && isfield(job,'atlas') && ~strcmp(job.atlas,'None') + [labk{i2}, Pl{i2}] = spm_atlas('query',xA,XYZmm(:,j)); + Zj{i2} = Z(:,j); + XYZmmj{i2} = XYZmm(:,j); + maxZ(i2) = sign(Zj{i2}(1))*max(abs(Zj{i2})); + end + end + end + end + + % ...eliminate voxels + %------------------------------------------------------------------- + Z = Z(:,Qe); + XYZ = XYZ(:,Qe); + if isempty(Qe) + fprintf('No voxels survived extent threshold k=%3.1f\n',k); + end + + else + k = 0; + Qe = []; + p_extent_str = 'NoVox'; + end % (if ~isempty(XYZ)) + + if T2x + switch sel + case 1, t2x_name = 'P_'; + case 2, t2x_name = 'logP_'; + case 3, t2x_name = 'R_'; + case 4, t2x_name = 'D_'; + case 5, t2x_name = 'T_'; + case 6, t2x_name = 'Z_'; + end + else + switch sel + case 1, t2x_name = 'P_'; + case 2, t2x_name = 'logP_'; + case 3, t2x_name = 'R2_'; + case 4, t2x_name = 'F_'; + end + end + + if strcmp(nm(1:7),sprintf('nullT_0')) + t2x_name = ['null' t2x_name]; + end + + if isempty(Qe) || isempty(Qh) + t2x = Inf; + else + if T2x % T-Test + switch sel + case 1 + t2x = 1-spm_Tcdf(Z,df(2)); + case 2 + t2x = -log10(max(eps,1-spm_Tcdf(Z,df(2)))); + % find neg. T-values + ind_neg = find(Z<0); + if ~isempty(ind_neg) + t2x(ind_neg) = log10(max(eps,spm_Tcdf(Z(ind_neg),df(2)))); + end + case 3 + t2x = Z./sqrt(Z.*Z + df(2)); + case 4 + t2x = 2*Z/sqrt(df(2)); + case 5 + t2x = Z; + case 6 + t2x = spm_t2z(Z,df(2)); + end + else % F-test + switch sel + case 1 + t2x = 1-spm_Fcdf(Z,df); + case 2 + t2x = -log10(max(eps,1-spm_Fcdf(Z,df))); + case 3 + % n = df(2) + % p = df(1) + t2x = 1 - 1./(1+(Z*(df(1)-1)/(df(2)-df(1)))); + case 4 + t2x = Z; + end + end + end % (isempty(Qh)) + str_num = deblank(xCon(Ic).name); + + % replace spaces with ""_"" and characters like ""<"" or "">"" with ""gt"" or ""lt"" + str_num(strfind(str_num,' ')) = '_'; + strpos = strfind(str_num,' > '); + if ~isempty(strpos), str_num = [str_num(1:strpos-1) '_gt_' str_num(strpos+1:end)]; end + strpos = strfind(str_num,' < '); + if ~isempty(strpos), str_num = [str_num(1:strpos-1) '_lt_' str_num(strpos+1:end)]; end + strpos = strfind(str_num,'>'); + if ~isempty(strpos), str_num = [str_num(1:strpos-1) 'gt' str_num(strpos+1:end)]; end + strpos = strfind(str_num,'<'); + if ~isempty(strpos), str_num = [str_num(1:strpos-1) 'lt' str_num(strpos+1:end)]; end + str_num = spm_str_manip(str_num,'v'); + + if T2x && neg_results + neg_str = '_bi'; + else + neg_str = ''; + end + + if isfield(SPM.xVol,'G') + ext = '.gii'; + else + ext = '.nii'; + end + + if ~isempty(Qe) || u0 > -Inf + name = [t2x_name str_num p_height_str num2str(u0*100) p_extent_str '_k' num2str(k) neg_str ext]; + else + name = [t2x_name str_num ext]; + end + + Pname{i} = deblank(fullfile(pth,name)); + + % only write and display files if some voxels survived thresholds + if ~isempty(Qh) && ~isempty(Qe) + fprintf(' Display %s\n',spm_file(Pname{i},'link','cat_surf_display(''%s'')')); + end + + % print table for 3D data + if (nargin > 0) && isfield(job,'atlas') && ~strcmp(job.atlas,'None') && ~isempty(XYZ) + % sort T/F values and print from max to min values + [tmp, maxsort] = sort(maxZ,'descend'); + + % use ascending order for neg. values + indneg = find(tmp<0); + maxsort(indneg) = flipud(maxsort(indneg)); + + if ~isempty(maxsort) + found_neg = 0; + found_pos = 0; + print_header_neg = 0; + print_header_pos = 0; + for l=1:length(maxsort) + j = maxsort(l); + [tmp, indZ] = max(abs(Zj{j})); + + if ~isempty(indZ) + if maxZ(j) < 0, found_neg = 1; end + if maxZ(j) > 0, found_pos = 1; end + + if sel == 2, valname = 'p-value'; else valname = [STAT '-value']; end + + % print header if the first pos./neg. result was found + if found_pos && ~print_header_pos + + fprintf('\n______________________________________________________'); + fprintf('\n%s: Positive effects\n%s',name,atlas_name); + fprintf('\n______________________________________________________\n\n'); + fprintf('%7s\t%12s\t%15s\t%s\n\n',valname,'Cluster-Size',' xyz [mm] ','Overlap of atlas region'); + print_header_pos = 1; + end + if found_neg && ~print_header_neg + fprintf('\n______________________________________________________'); + fprintf('\n%s: Negative effects\n%s',name,atlas_name); + fprintf('\n______________________________________________________\n\n'); + fprintf('%7s\t%12s\t%15s\t%s\n\n',valname,'Cluster-Size',' xyz [mm] ','Overlap of atlas region'); + print_header_neg = 1; + end + if ~found_pos && ~found_neg + fprintf('\n______________________________________________________'); + fprintf('\n%s: No effects\n%s',name,atlas_name); + fprintf('\n______________________________________________________\n\n'); + else + + if sel == 2, val = 10^(-maxZ(j)); else val = maxZ(j); end + fprintf('%7.2g\t%12d\t%4.0f %4.0f %4.0f',val,length(Zj{j}),XYZmmj{j}(:,indZ)); + for m=1:numel(labk{j}) + if Pl{j}(m) >= 1 + if m==1, fprintf('\t%3.0f%%\t%s\n',Pl{j}(m),labk{j}{m}); + else fprintf('%7s\t%12s\t%15s\t%3.0f%%\t%s\n',' ',' ',' ',... + Pl{j}(m),labk{j}{m}); + end + end + end + end + end + end + end + fprintf('\n'); + end + + %-Reconstruct (filtered) image from XYZ & T/Z pointlist + %----------------------------------------------------------------------- + Y = zeros(Vspm.dim); + OFF = XYZ(1,:) + Vspm.dim(1)*(XYZ(2,:)-1 + Vspm.dim(2)*(XYZ(3,:)-1)); + Y(OFF) = t2x; + + VO = Vspm; + VO.fname = Pname{i}; + VO.dt = [spm_type('float32') spm_platform('bigend')]; + + % only write and display files if some voxels survived thresholds + if ~isempty(Qh) && ~isempty(Qe) + VO = spm_data_hdr_write(VO); + spm_data_write(VO,Y); + end + +end % (for i=1:size(P,1)) + +if nargout + out.Pname = Pname; +end + +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_batch_spm.m",".m","1658","65","function cat_batch_spm(batchname,varargin) +% wrapper for using spm8 batch mode (see cat_batch_cat12.sh) +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +if nargin < 1 + fprintf('Syntax: cat_batch_spm(batchname)\n'); + exit +end +if nargin > 1 +% initialize variables given by the shell script to adapt batches + + if mod(numel(varargin),2) ~= 0 + fprintf('Syntax: cat_batch_spm(batchname,''var1name'',var1,...)\n'); + exit + end + for vi = 1:2:numel(varargin)-1 + try + eval(sprintf('%s = varargin{vi+1};', varargin{vi} )); + catch + fprintf('Cannot evaluate variable %0.0f ""%s = varargin{%0.0f+1}; "" \n', (vi+1)/2, varargin{vi}, (vi+1)/2 ); + fprintf('Syntax: cat_batch_spm(batchname,''var1name'',var1,...)\n'); + exit + end + end + clear vi; + + % show result +end + + +% set up SPM enviroment (the batch may need SPM variables/functions) +spm_get_defaults; +global defaults +spm_jobman('initcfg'); + +if ~exist(batchname,'file') + fprintf('Batchfile %s not found\n',batchname); + exit +end + +eval(batchname) + +if ~exist('matlabbatch','var') + fprintf('Batchfile %s did not returned variable matlabbatch.\n', batchname); + exit +end + +warning off +try + spm_jobman('run',matlabbatch); +catch + fprintf('Batchfile %s was not running successfully.\n', batchname); + + exit +end +warning off +exit +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_vol_glassbrain.m",".m","9266","366","function fig = cat_vol_glassbrain(X,pos,varargin) +% Glass brain plot +% FORMAT fig = cat_glass(X,pos,S) +% X - (REQUIRED) values to be painted +% pos - (REQUIRED) coordinates in MNI head (not voxel) space +% S - (optional) config structure +% Fields of S: +% S.cmap - colormap of plot - Default: 'gray' +% S.dark - dark mode - Default: false +% S.detail - glass brain detail level: +% 0=LOW, 1=NORMAL, 2=HIGH - Default: 1 +% S.grid - overlay grid - Default: false +% S.colourbar - show colorbar - Default: false +% 0 - no, 1 - with string min/max, 2 - with min/max value +% S.sym_range - symmetric range if neg. values are present +% - Default: false +% Output: +% fig - Handle for generated figure +%__________________________________________________________________________ + +% modified version of spm_glass +% George O'Neill & Guillaume Flandin +% Copyright (C) 2020-2022 Wellcome Centre for Human Neuroimaging +%--------------------------------------------------------------------- +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +switch nargin + case 1 + error('need at least two arguments, values, and positions!') + case 2 + S = []; + case 3 + S = varargin{1}; +end + +assert(length(X) == length(pos), ['number of values do not match '... + 'number of positions!']); + +if ~isfield(S,'dark'), S.dark = false; end +if ~isfield(S,'cmap'), S.cmap = 'gray'; end +if ~isfield(S,'detail'), S.detail = 1; end +if ~isfield(S,'grid'), S.grid = false; end +if ~isfield(S,'colourbar'), S.colourbar = 0; end +if ~isfield(S,'sym_range'), S.sym_range = false; end +if ~isfield(S,'roi'), S.roi = []; end + +M = [-2 0 0 92;0 2 0 -128;0 0 2 -74;0 0 0 1]; +dim = [91 109 91]; +pos = ceil(M \ [pos';ones(1,size(pos,1))])'; + +% exclude positions that exceed image dimensions +ind = find(pos(:,1) < 1 | pos(:,1) > dim(1) | pos(:,2) < 1 | pos(:,2) > dim(2) | pos(:,3) < 1 | pos(:,3) > dim(3)); +if ~isempty(ind) + pos(ind,:) = []; + X(ind) = []; +end + +tbin = zeros(size(X)); +if ~isempty(S.roi) + tbin(S.roi>0) = 1; + X(isnan(X)) = 0; +% X(S.roi>0) = 1; +end + +% use symmetric range if defined and negative values exist +if any(X<0) && any(X>0) && S.sym_range + rmin = -max(abs(X)); + rmax = max(abs(X)); +else + rmin = min(X); + rmax = max(X); +end + +[~,id] = sort(abs(X),'ascend'); +[~,bin] = histc(X,linspace(rmin,rmax,65)); + +% saggital plane +%---------------------------------------------------------------------- +p_sag = NaN(dim(2),dim(3)); +t_sag = zeros(dim(2),dim(3)); + +for ii = 1:length(id) + + p1 = pos(id(ii),2); + p2 = pos(id(ii),3); + + if p1 > 0 && p1 <= dim(2) && p2 > 0 && p2 <= dim(3) + p_sag(p1,p2) = bin(id(ii)); + if ~isempty(S.roi) + t_sag(p1,p2) = tbin(id(ii)); + end + end + +end + +% coronal plane +%---------------------------------------------------------------------- +p_cor = NaN(dim(1),dim(3)); +t_cor = zeros(dim(1),dim(3)); + +for ii = 1:length(id) + + p1 = pos(id(ii),1); + p2 = pos(id(ii),3); + + if p1 > 0 && p1 <= dim(1) && p2 > 0 && p2 <= dim(3) + p_cor(p1,p2) = bin(id(ii)); + if ~isempty(S.roi) + t_cor(p1,p2) = tbin(id(ii)); + end + end +end + + +% axial plane +%---------------------------------------------------------------------- +p_axi = NaN(dim(2),dim(1)); +t_axi = zeros(dim(2),dim(1)); + +for ii = 1:length(id) + + p1 = pos(id(ii),2); + p2 = pos(id(ii),1); + + if p1 > 0 && p1 <= dim(2) && p2 > 0 && p2 <= dim(1) + p_axi(p1,p2) = bin(id(ii)); + if ~isempty(S.roi) + t_axi(p1,p2) = tbin(id(ii)); + end + end +end + + + +if ~isempty(S.roi) + X(S.roi>0) = 1; + + [~,id] = sort(abs(X),'ascend'); + [~,bin] = histc(X,linspace(rmin,rmax,65)); + + % saggital plane + %---------------------------------------------------------------------- + t_sag = zeros(dim(2),dim(3)); + + for ii = 1:length(id) + + p1 = pos(id(ii),2); + p2 = pos(id(ii),3); + + if p1 > 0 && p1 <= dim(2) && p2 > 0 && p2 <= dim(3) + t_sag(p1,p2) = tbin(id(ii)); + end + + end + + % coronal plane + %---------------------------------------------------------------------- + t_cor = zeros(dim(1),dim(3)); + + for ii = 1:length(id) + + p1 = pos(id(ii),1); + p2 = pos(id(ii),3); + + if p1 > 0 && p1 <= dim(1) && p2 > 0 && p2 <= dim(3) + t_cor(p1,p2) = tbin(id(ii)); + end + end + + + % axial plane + %---------------------------------------------------------------------- + t_axi = zeros(dim(2),dim(1)); + + for ii = 1:length(id) + + p1 = pos(id(ii),2); + p2 = pos(id(ii),1); + + if p1 > 0 && p1 <= dim(2) && p2 > 0 && p2 <= dim(1) + t_axi(p1,p2) = tbin(id(ii)); + end + end +end + +% optional colorbar +%--------------------------------------------------------------------- +p_col = NaN(dim(1),dim(3)); +if S.colourbar + for ii = 42:52 + p_col(ii,14:78) = linspace(2,65,numel(14:78)); + end +end + +% combine and plot +%--------------------------------------------------------------------- +p_all = [rot90(p_sag,1) fliplr(rot90(p_cor,1));rot90(p_axi,1) rot90(p_col,1)]; +p_all(isnan(p_all)) = 0; +if ~isempty(S.roi) + t_all = [rot90(t_sag,1) fliplr(rot90(t_cor,1));rot90(t_axi,1) rot90(zeros(size(p_col)),1)]; +end + +imagesc(p_all) +if ~isempty(S.roi) + hold on + contour(t_all,1,'Color',[0.5 0.5 0.5],'LineWidth',3) + hold off +end +set(gca,'XTickLabel',{},'YTickLabel',{}); +axis image + +caxis([0 64]) +load(fullfile(fileparts(mfilename('fullpath')),'glass_brain.mat')); +overlay_glass_brain(glass,'side',S.dark,S.detail); +overlay_glass_brain(glass,'back',S.dark,S.detail); +overlay_glass_brain(glass,'top', S.dark,S.detail); + +if ischar(S.cmap) + c = feval(S.cmap,64); +else + c = S.cmap; +end + +if S.dark + c(1,:) = [0 0 0]; +else + c(1,:) = [1 1 1]; +end +colormap(c); + +if S.dark + set(gcf,'color','k'); +else + set(gcf,'color','w'); +end + +if S.colourbar > 1 + text(175,170,sprintf('%0.2f',rmin),'color',~c(1,:),'fontsize',12,'horizontalalignment','center'); + text(175,105,sprintf('%0.2f',rmax),'color',~c(1,:),'fontsize',12,'horizontalalignment','center'); +elseif S.colourbar == 1 + if rmin < 0 + text(175,170,'-max','color',~c(1,:),'fontsize',12,'horizontalalignment','center'); + else + text(175,170,'min','color',~c(1,:),'fontsize',12,'horizontalalignment','center'); + end + + text(175,105,'max','color',~c(1,:),'fontsize',12,'horizontalalignment','center'); +end + +if S.grid + grid on +else + axis off +end + +fig = gcf; + +end + +% supporting functions +%--------------------------------------------------------------------- + +function overlay_glass_brain(glass,orient,dark,detail) + +dat = glass.(orient); + +switch orient + case 'top' + xform = [0 -1 0; 1 0 0; 0 0 1]*[0.185 0 0; 0 0.185 0; 10.5 173 1]; + case 'back' +% xform = [0.185 0 0; 0 -0.185 0; 120 89 1]; + % xform was distorted for coronal slice + xform = [1.05 0 0; 0 1.05 0; 0 0 1]*[0.185 0 0; 0 -0.185 0; 118 92 1]; + case 'side' + xform = [0.185 0 0; 0 -0.185 0; 10.5 89 1]; +end + +for ii = 1:length(dat.paths) + pth = dat.paths(ii); + % see if we need to draw based on the complexity option + switch detail + case 0 + draw = pth.linewidth > 1 & sum(hex2rgb(pth.edgecolor))==0; + case 1 + draw = sum(hex2rgb(pth.edgecolor))==0; + otherwise + draw = 1; + end + + if draw + for jj = 1:length(pth.items) + pts = pth.items(jj).pts; + v = [generate_bezier(pts) ones(10,1)]; + v2 = v*xform; + if dark + c = 1 - hex2rgb(pth.edgecolor); + else + c = hex2rgb(pth.edgecolor); + end + line(v2(:,1),v2(:,2),'LineWidth',pth.linewidth,'Color',c); + end + end +end + +end + +function [points, t] = generate_bezier(controlPts, varargin) + +% bezier generation from control points based on code by +% Adrian V. Dalca, https://www.mit.edu/~adalca/ +% https://github.com/adalca/bezier + +% estimate nDrawPoints +if nargin == 1 + nCurvePoints = 10; +else + nCurvePoints = varargin{1}; +end + +% curve parametrization variable +t = linspace(0, 1, nCurvePoints)'; + +% detect the type of curve (linear, quadratic, cubic) based on the +% number of points given in controlPts. +switch size(controlPts, 1) + case 1 + error('Number of Control Points should be at least 2'); + + case 2 + % linear formula + points = (1 - t) * controlPts(1, :) + ... + t * controlPts(2, :); + + case 3 + % quadratic formula + points = ((1 - t) .^ 2) * controlPts(1, :) + ... + (2 * (1 - t) .* t) * controlPts(2, :) + ... + (t .^ 2) * controlPts(3, :); + + case 4 + % cubic formula + points = ((1 - t) .^ 3) * controlPts(1, :) + ... + (3 * (1 - t) .^ 2 .* t) * controlPts(2, :) + ... + (3 * (1 - t) .* t .^ 2) * controlPts(3, :) + ... + (t .^ 3) * controlPts(4, :); +end + +% verify dimensions +assert(size(points, 2) == size(controlPts, 2)); +end + +function rgb = hex2rgb(hex) +% converts hex string to matlab rgb triplet +if strcmpi(hex(1,1),'#') + hex(:,1) = []; +end +rgb = reshape(sscanf(hex.','%2x'),3,[]).'/255; +end +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_stat_coord_diff.m",".m","2350","69","function cat_stat_coord_diff(P) +% compute coordinate differences and eucldiean distance between two +% or more surface meshes. The difference and the euclidean distance is always +% estimated to the first surface: surfX - surf1 +% +% output name will be diff_{name_surfX} +% and euclidean_{name_surfX} +% +% FORMAT cat_stat_coord_diff(P) +% P - filenames for image 1..X +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ + +if nargin == 0 + % select images for each subject + don = 0; + for i = 1:1000, + Ps = spm_select([0 Inf],'^lh.(central|pial|white)',['Select all surfaces for time point ' num2str(i)]); + if size(Ps,2) < 1, don = 1; ; break; end; + P{i} = Ps; + end +end + +coord = {'x','y','z'}; +hemi = {'lh.','rh.'}; + +avg_vertices = cell(1,numel(P)); + +% go through all time points +for side = hemi + for i = 1:numel(P) + sname = char(strrep(cellstr(P{i}),'lh.',side)); + + G = gifti(sname); + avg_vertices{i} = zeros(size(G(1).vertices)); + + % go through all subjects for that time point and average coordinates + for j = 1:numel(G) + avg_vertices{i} = avg_vertices{i} + G(j).vertices; + end + avg_vertices{i} = avg_vertices{i}/numel(G); + + % calc difference to baseline surface + sinfo = cat_surf_info(sname(1,:)); + if i > 1 + fprintf('Calculate s%d-s1\n',i); + diff_coord = cell(1,3); + for k=1:3 + diff_coord{k} = avg_vertices{i}(:,k) - avg_vertices{1}(:,k); + outname = cat_surf_rename(sname(1,:),'ee','','dataname',['diff' coord{k} '_' sinfo.dataname]) + cat_io_FreeSurfer('write_surf_data',outname{1},diff_coord{k}); + end + outname = cat_surf_rename(sname(1,:),'ee','','dataname',['euclidean_' sinfo.dataname]); + e = sqrt(diff_coord{1}.^2+diff_coord{2}.^2+diff_coord{3}.^2); + cat_io_FreeSurfer('write_surf_data',outname{1},e); + else + % write zeros for the 1st image + outname = cat_surf_rename(sname(1,:),'ee','','dataname',['euclidean_' sinfo.dataname]); + e = zeros(size(avg_vertices{1}(:,1))); + cat_io_FreeSurfer('write_surf_data',outname{1},e); + end + end +end +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_main_amap1639.m",".m","10156","226","function [prob,indx,indy,indz,th] = cat_main_amap1639(Ymi,Yb,Yb0,Ycls,job,res) +% ______________________________________________________________________ +% +% AMAP segmentation: +% Most corrections were done before and the AMAP routine is used with +% a low level of iterations and no further bias correction, because +% some images get tile artifacts. +% +% [prob,indx,indy,indz] = cat_main_amap1639(Ymi,Yb,Yb0,Ycls,job,res) +% +% prob .. new AMAP segmentation (4D) +% ind* .. index elements to asign a subvolume +% Ymi .. local intensity normalized source image +% Yb .. brain mask (SPM) +% Yb0 .. original brain mask +% Ycls .. SPM segmentation +% job .. SPM/CAT parameter structure +% res .. SPM segmentation structure +% th .. AMAP treshholds +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + + % this function adds noise to the data to stabilize processing and we + % have to define a specific random pattern to get the same results each time + if exist('rng','file') == 2, rng('default'); rng(0); else, rand('state',0); randn('state',0); end + if ~isfield(job.extopts,'AMAPframing'), job.extopts.AMAPframing = 0; end + + % if there is a breakpoint in this file set debug=1 and do not clear temporary variables + dbs = dbstatus; debug = 0; for dbsi=1:numel(dbs), if strcmp(dbs(dbsi).name,mfilename); debug = 1; break; end; end + + % correct for harder brain mask to avoid meninges in the segmentation + Ymib = Ymi; Ymib(~Yb) = 0; + rf = 10^4; Ymib = round(Ymib*rf)/rf; + d = size(Ymi); + vx_vol = sqrt(sum(res.image(1).mat(1:3,1:3).^2)); + + % use framing + %{ + sz = size(Yb); + [indx, indy, indz] = ind2sub(sz,find(Yb>0)); + tx = [min(indx) szx - max(indx)]; + ty = [min(indx) szy - max(indx)]; + tz = [min(indx) szz - max(indx)]; + tb = min( [ tx ty tz ]; + %} + framing.tissue = 4; + framing.pve = 1; + + % prepare data for segmentation + if 1 + %% classic approach, consider the WMH! + Kb2 = numel(Ycls); + cls2 = zeros([d(1:2) Kb2]); + Yp0 = zeros(d,'uint8'); + for i=1:d(3) + for k1 = 1:Kb2, cls2(:,:,k1) = Ycls{k1}(:,:,i); end + % find maximum for reordered segmentations + [maxi,maxind] = max(cls2(:,:,[3,1,2,4:Kb2]),[],3); + k1ind = [1 2 3 1 0 0 2 1]; % WMHs will be WM, lesions CSF + for k1 = 1:Kb2 + Yp0(:,:,i) = Yp0(:,:,i) + cat_vol_ctype((maxind == k1) .* (maxi~=0) * k1ind(k1) .* min(1,Yb(:,:,i))); + end + end + Yp0 = min(3,Yp0); + if ~debug, clear maxi maxind Kb k1 cls2; end + else + % more direct method ... a little bit more WM, less CSF + Yp0 = uint8(max(Yb,min(3,round(Ymi*3)))); Yp0(~Yb) = 0; + end + + + % use index to speed up and save memory + sz = size(Yb); + [indx, indy, indz] = ind2sub(sz,find(Yb>0)); + if job.extopts.AMAPframing + bx = (framing.tissue + framing.pve) * 3 * job.extopts.AMAPframing + 2; + indx = [min(indx) max(indx)] + [-bx bx]; indy = [min(indy) max(indy)] + [-bx bx]; indz = [min(indz) max(indz)] + [-bx bx]; + end + indx = max((min(indx) - 1),1):min((max(indx) + 1),sz(1)); + indy = max((min(indy) - 1),1):min((max(indy) + 1),sz(2)); + indz = max((min(indz) - 1),1):min((max(indz) + 1),sz(3)); + + % Yb source image because Amap needs a skull stripped image + % set Yp0b and source inside outside Yb to 0 + Yp0b = Yp0(indx,indy,indz); + Ymib = Ymib(indx,indy,indz); + + % remove non-brain tissue with a smooth mask and set values inside the + % brain at least to CSF to avoid wholes for images with CSF==BG. + if job.extopts.LASstr>0 + Ywmstd = cat_vol_localstat(single(Ymib),Yp0b==3,1,4); + CSFnoise(1) = cat_stat_nanmean(Ywmstd(Ywmstd(:)>0))/mean(vx_vol); + Ywmstd = cat_vol_localstat(cat_vol_resize(single(Ymib),'reduceV',vx_vol,vx_vol*2,16,'meanm'),... + cat_vol_resize(Yp0==3,'reduceV',vx_vol,vx_vol*2,16,'meanm')>0.5,1,4); + CSFnoise(2) = cat_stat_nanmean(Ywmstd(Ywmstd(:)>0))/mean(vx_vol); + Ycsf = double(0.33 * Yb(indx,indy,indz)); spm_smooth(Ycsf,Ycsf,0.6*vx_vol); + Ycsf = Ycsf + cat_vol_smooth3X(randn(size(Ycsf)),0.5) * max(0.005,min(0.2,CSFnoise(1)/4)); % high-frequency noise + Ycsf = Ycsf + cat_vol_smooth3X(randn(size(Ycsf)),1.0) * max(0.005,min(0.2,CSFnoise(2)*1)); % high-frequency noise + Ymib = max(Ycsf*0.8 .* cat_vol_smooth3X(Ycsf>0,2),Ymib); + clear Ycsf; + % Yb is needed for surface reconstruction + % if ~job.output.surface, clear Yb; end + end + + % adaptive mrf noise + if job.extopts.mrf>=1 || job.extopts.mrf<0 + % estimate noise + [Yw,Yg] = cat_vol_resize({Ymi.*(Ycls{1}>240),Ymi.*(Ycls{2}>240)},'reduceV',vx_vol,3,32,'meanm'); + Yn = max(cat(4,cat_vol_localstat(Yw,Yw>0,2,4),cat_vol_localstat(Yg,Yg>0,2,4)),[],4); + job.extopts.mrf = double(min(0.15,3*cat_stat_nanmean(Yn(Yn(:)>0)))) * 0.5; + clear Yn Yg + end + + % display something + stime = cat_io_cmd(sprintf('Amap using initial SPM segmentations (MRF filter strength %0.2f)',job.extopts.mrf)); + + + % intensity values + Ymib = abs(double(Ymib)); + + if job.extopts.AMAPframing + Ybb = Yb0(indx,indy,indz)>0; + Ybb = cat_vol_morph(Ybb,'d',3); + pn = max(double(Yp0b(:))) * 0.015; + pnx = max(double(Yp0b(:))) * 0.015; + Yn = randn(size(Yp0b)); + ex = framing.tissue; + ep = framing.pve; + BBe = ~Ybb; BBe (2 :end-1 , 2 :end-1 , 3 :end-2 ) = false; + BBww = ~Ybb; BBww(ex*1 :end+1-ex*1 , ex*1 :end+1-ex*1 , ex*1:end+1-ex*1 ) = false; + BBgw = ~Ybb; BBgw(ex*1+0 :end+1-ex*1-0 , ex*1+ep:end+1-ex*1-ep , ex*1:end+1-ex*1-ep) = false; BBgw(BBww) = false; + BBgg = ~Ybb; BBgg(ex*2 :end+1-ex*2 , ex*2 :end+1-ex*2 , ex*2:end+1-ex*2 ) = false; BBgg(BBww | BBgw) = false; + BBgc = ~Ybb; BBgc(ex*2+0 :end+1-ex*2-0 , ex*2+ep:end+1-ex*2-ep , ex*2:end+1-ex*2-ep) = false; BBgc(BBww | BBgw | BBgg) = false; + BBcc = ~Ybb; BBcc(ex*3 :end+1-ex*3 , ex*3 :end+1-ex*3 , ex*3:end+1-ex*3 ) = false; BBcc(BBww | BBgw | BBgg | BBgc) = false; + BBcb = ~Ybb; BBcb(ex*3+0 :end+1-ex*3-0 , ex*3+ep:end+1-ex*3-ep , ex*3:end+1-ex*3-ep) = false; BBcb(BBww | BBgw | BBgg | BBgc | BBcc) = false; + % extra values + extra noise + % all peaks have an offset of 0.05 that produces better results + Ymib(BBcb) = 0.55/3 + pnx * Yn(BBcb); Yp0b(BBcb) = 0; + Ymib(BBcc) = 1.05/3 + pnx * Yn(BBcc); Yp0b(BBcc) = 1; + Ymib(BBgc) = 1.55/3 + pnx * Yn(BBgc); Yp0b(BBgc) = 1; + Ymib(BBgg) = 2.05/3 + pnx * Yn(BBgg); Yp0b(BBgg) = 2; + Ymib(BBgw) = 2.75/3 + pnx * Yn(BBgw); Yp0b(BBgw) = 2; + Ymib(BBww) = 3.05/3 + pnx * Yn(BBww); Yp0b(BBww) = 3; + Ymib(BBe ) = 3.55/3 + pnx * Yn(BBe ); Yp0b(BBe ) = 0; + clear BBww BBgw BBgg BBgc BBcc BBcb BBe; + + % add noise + addnoise = 0; + if addnoise == 2 + % we add noise only in save regions + WMe = cat_vol_morph( Yp0b==3 , 'e' , 1 )>0; + CMe = cat_vol_morph( Yp0b==1 , 'e' , 1 )>0; + Ymib( WMe ) = Ymib( WMe ) + pn * Yn( WMe ); + Ymib( CMe ) = Ymib( CMe ) + pn * Yn( CMe ); + elseif addnoise == 1 + % add noise + Ymib = Ymib + pn * Yn; + end + Ymib = abs(Ymib); + end + + % Amap parameters + % - sub .. size of sub-elementes is linked to the anatomy and needs adaptation for voxel size + % in additition, test showed that 32 is quite optimal, whereas higher values >64 are worse + % - n_iters .. for highly optimized data is about 10 iterations + % - bias_fwhm .. the bias correction should be inactive + n_iters = 10; sub = round(64/mean(vx_vol)); + n_classes = 3; pve = 5; bias_fwhm = 0; init_kmeans = 0; + if job.extopts.mrf~=0, iters_icm = 50; else, iters_icm = 0; end + + % remove noisy background for kmeans + if init_kmeans, Ymib(Ymib<0.1) = 0; end %#ok + + % do segmentation + [prob,amap_means,amap_stds] = cat_amap(Ymib, Yp0b, n_classes, n_iters, sub, pve, init_kmeans, ... + job.extopts.mrf, vx_vol, iters_icm, bias_fwhm, 0); + fprintf('%5.0fs\n',etime(clock,stime)); + if sum(prob(:)) == 0, error('cat_main:amap','AMAP output empty. '); end + + % analyse segmentation ... the input Ym is normalized an the tissue peaks should be around [1/3 2/3 3/3] + th = {[amap_means(1) amap_stds(1)],[amap_means(2) amap_stds(2)],[amap_means(3) amap_stds(3)]}; + + if job.extopts.AMAPframing + for i=1:3, prob(:,:,:,i) = prob(:,:,:,i) .* uint8(Ybb); end + end + clear Ybb; + + if job.extopts.verb>1 + if strcmpi(spm_check_version,'octave'), pm = '+/-'; else, pm = char(177); end + fprintf(' AMAP peaks: [CSF,GM,WM] = [%0.2f%s%0.2f,%0.2f%s%0.2f,%0.2f%s%0.2f]\n',... + th{1}(1),pm,th{1}(2),th{2}(1),pm,th{2}(2),th{3}(1),pm,th{3}(2)); + end + if th{1}(1)<0 || th{1}(1)>0.6 || th{2}(1)<0.5 || th{2}(1)>0.9 || th{3}(1)<0.95-th{3}(2) || th{3}(1)>1.1 + error('cat_main:amap',['AMAP estimated untypical tissue peaks that point to an \n' ... + 'error in the preprocessing before the AMAP segmentation. ']); + end + % reorder probability maps according to spm order + clear Yp0b Ymib; + prob = prob(:,:,:,[2 3 1]); + clear vol Ymib + + % finally use brainmask before cleanup that was derived from SPM segmentations and additionally include + % areas where GM from Amap > GM from SPM. This will result in a brainmask where GM areas + % hopefully are all included and not cut + if job.extopts.gcutstr>0 && ~job.inv_weighting + Yb0(indx,indy,indz) = Yb0(indx,indy,indz) | ((prob(:,:,:,1) > 0) & Yb(indx,indy,indz)); % & ~Ycls{1}(indx,indy,indz)); + for i=1:3 + prob(:,:,:,i) = prob(:,:,:,i) .* uint8(Yb0(indx,indy,indz)); + end + end + + global cat_err_res + + % update segmentation for error report + Yp0 = single(prob(:,:,:,3))/255/3 + single(prob(:,:,:,1))/255*2/3 + single(prob(:,:,:,2))/255; + [cat_err_res.init.Yp0,cat_err_res.init.BB] = cat_vol_resize(Yp0,'reduceBrain',vx_vol,2,Yp0>0.5); + cat_err_res.init.Yp0 = cat_vol_ctype(cat_err_res.init.Yp0/3*255); + +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat12.sh",".sh","624","20","#! /bin/bash +# ______________________________________________________________________ +# +# Christian Gaser, Robert Dahnke +# Structural Brain Mapping Group (https://neuro-jena.github.io) +# Departments of Neurology and Psychiatry +# Jena University Hospital +# ______________________________________________________________________ +# $Id$ + +echo ""##############################################################"" +echo "" cat12.sh is deprecated. Please now use cat_batch_cat.sh. "" +echo ""##############################################################"" + +cat12_dir=$(dirname ""$0"") +args=(""$@"") + +${cat12_dir}/cat_batch_cat.sh ${args} + +","Shell" +"Neurology","ChristianGaser/cat12","cp_binaries.sh",".sh","419","21","#!/bin/sh + +rm ~/work/c/CAT/build-*/Progs/*.o + +# check for new arm64 +if [ `uname -m` == ""arm64"" ]; then + cd CAT.maca64 +else + cd CAT.glnx86 + for i in CAT*; do cp ~/work/c/CAT/build-x86_64-pc-linux/Progs/${i} .; done + + cd ../CAT.w32 + for i in CAT*; do cp ~/work/c/CAT/build-i586-mingw32/Progs/${i} .; done + chmod a+x *.exe + + cd ../CAT.maci64 +fi + +for i in CAT*; do cp ~/Dropbox/c/CAT/build-native/Progs/${i} .; done +cd .. +","Shell" +"Neurology","ChristianGaser/cat12","update_revision.sh",".sh","655","16","#! /bin/bash +# Tool for adding revision and date to m-files that were prepared in cat12. +# ______________________________________________________________________ +# +# Christian Gaser, Robert Dahnke +# Structural Brain Mapping Group (https://neuro-jena.github.io) +# Departments of Neurology and Psychiatry +# Jena University Hospital +# ______________________________________________________________________ + + +REVISION=`git rev-list --count HEAD` +DATE=`git log --date short |grep ""Date:""|head -1|cut -f2 -d':'|sed -e s'/ //g'` + +perl -p -i -e 's/\$Id\$/\$Id: '$REVISION' '$DATE' \$/g' cat12/*.m +perl -p -i -e 's/\$Id\$/\$Id: '$REVISION' '$DATE' \$/g' cat12/*.sh","Shell" +"Neurology","ChristianGaser/cat12","cat_long_main.m",".m","64562","1150","%----------------------------------------------------------------------- +% Job for longitudinal batch processing in CAT12. +% +% The batch consist of different longitudinal models (job.longmodel): +% (0) A longitudinal cross-sectional pipeline ""LC"" for a maximal independ +% processing (with a subject specific TPM, based on the segmentation +% of the non-linear average to reduce time point specific differences) +% but no time point optimized/independ registration. +% (1) A longitudinal plasticity pipeline ""LP"" for small changes that uses +% an optimized rigit registration scheme (and an indiviual TPM based +% on the average image). As far as only small changes are expected, +% the affine registration is fixed and the skull-stripping uses the +% average as start point. +% (2) A longitudinal aging pipeline ""LA"" that works similar to the LP +% pipeline but uses another deformation step to reduce typical changes +% in aging such as enlargement of ventricles and small movements of +% cortical structures (sinking of gyri due to tissue atropy). +% (3) The LP and LA pipeline can be processes at the same time. +% (4) A longitudial development mdoel ""LD"" that works similar as the LA +% but allows affine rather than rigid adaptions. +% +% Besides abreviations also the code of the longmodel is used, e.g., L0=LC. +% +% Depending on longitudinal model the following optimizations steps/batches +% were arranged: +% * denoising of data in native space +% * trimming of data +% * longitudinal realignment and averaging (not LC) +% * preprocessing of the average to create subject specific TPM and priors +% to make preprocessing of time points more accurate and stable +% * subject-specific TPM creation +% * inter-time point bias correction (developer only, not LC) +% * time point specific preprocessing (with longTPM and priors) +% this is finaly the core preprocessing +% * averaging of time point specific deformations (not LC) +% * time point specific deformations to the average (not LC/LP) +% * cleanup of temporary files +% +% +% Christian Gaser +% $Id$ +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + +% ======================================================================= +% TODO: +% ======================================================================= +% * RD202203: LC surfaces +% Could the LC model benefit from averaging results of the spherical registration? +% +% * RD202203: LC output maps: +% The LC model does not provide registrated maps r*.nii becuase of the +% stong differences in individual brain develpment. However, it would be +% possible to provide the TP specific deformations avg_y_*.nii and also an +% average spatial (and intensity) normalized T1 average image wavg*.nii. +% +% * RD202203: The LD pipeline needs a lot of work ... +% +% * RD202203: WMHs should be better handled, e.g., as own class in the TPM +% but I am no sure it the general pipeline is ready for this. +% Problems are more obvious for 2 mm processing that also point +% to inoptimal values in the CS-Pipeline! +% +% * RD202203: LBC / LongLAS +% A general function for severe intensity (protocol) corrections would be +% important (see ADNI 1.5 & 3.0T test cases or other test-retrest cases). +% John's pipeline has to be use to create a common space where the +% corrections should take place follow by a backprojection to the spaces +% of the single time points. Some of the results can maybe reused and the +% integration in cat_long_main is maybe messy. This corrections could/ +% should also include corrections for geometrical distortions, controlled +% by the main parameter. This problably also need a fast segmentation. +% The whole thing is much more complicated than it looks and it is +% unclear if my hopes can be fullfilled. Test can be done on rescan data +% or on manipulated real datasets or the BWP. Such a function can maybe +% be build on or replace the current LBC function after CAT12 average +% processing what would allow to use the average segmentation but here +% could be problems due to the used longitudinal pipeline and the time +% point specific spaces. +% Buchert data could be use for geometric distortion test data ... +% +% * RD202203: LC pipeline by superior deformations +% Would it be possible to improve the final deformation, by adapting them +% to the average? Would it be useful to use the average not only to create +% a TPM but also a Shooting template and to combine the average>IXI def. +% with the time-point specific deformation? +% This would improve the VBM but not the SBM pipeline. +% Lot of work but probably small effects and many evaluation issues. +% +% ======================================================================= +% Evaluation/Validation/Phantoms: +% ======================================================================= +% +% RD202203: +% - To test the LD pipeline, real longitudinal scans could be used +% and scaled - btw. how are we normalizing for TIV in such cases? +% A simplyfied version can use one cross-section scan and add rotation +% and noise, where global-equally changes are expected. This can also +% be used to test the null-hypotheses in the LP and PA pipelines if no +% scaling is introduced and to show that with scaling the LC pipeline +% has to be used. +% - Test values are given by the long report (cov,RMSE,..) +% - Affine-scaling (1D) has to be adapted to 3D nature (lin>vol). +% Subpoints are possible in linear or log facion. +% +% * John's pipeline can be use to create generalized smoothed deformation +% maps that can be applied (factorized) to create individual time +% points for aging, plasticity or development. +% How many subjects would be sufficient to create general test pattern? +% - Maybe 5 because the result will be smoothed and we only want to +% test the principle idea. +% - Deformation for plasticity/aging could be further limited to +% specific regions to allow more artificial test +% +% ======================================================================= + + + +% global variables don't work properly in deployed mode, thus we have to use +% setappdat/getappdata +try + job = getappdata(0,'job'); + opts = job.opts; + extopts = job.extopts; + output = job.output; + modulate = job.modulate; + dartel = job.dartel; + ROImenu = job.ROImenu; + longmodel = job.longmodel; + useprior = job.enablepriors; + surfaces = job.output.surface; + longTPM = job.longTPM; + bstr = job.bstr; + if isfield(job,'avgLASWMHC') + avgLASWMHC = job.avgLASWMHC; + else + avgLASWMHC = 0; + end + if isfield(job,'prepavg') + prepavg = job.prepavg; + else + prepavg = 2; + end + if isfield(job,'printlong') + printlong = job.printlong; + else + printlong = cat_get_defaults('extopts.print'); + end + if isfield(job,'delete_temp') + delete_temp = job.delete_temp; + else + delete_temp = 1; + end +catch + cat_io_cprintf('err','Setting parameters failed! Use defaults! \n'); + longmodel = 1; % use plasticity model as default (0-development, 1-plasticity, 2-aging, 3-both 1 and 2) + dartel = 0; + modulate = 1; % save modulated data + delete_temp = 1; % delete temporary files after preprocessing + useprior = 1; % use prior from avg-data + surfaces = cat_get_defaults('output.surface'); + longTPM = 1; % create longitudinal TPM form avg-data + bstr = 0.75; % additional longitudinal bias correction based on the avg pp + prepavg = 2; % preparation of the images in native space before SPM longitudinal realignment/averaging + % 0-none, 1-SANLM, 2-SANLM+trimming, 3-SANLM+trimming+rescaleIntensities + avgLASWMHC = 0; % 0-classical approach with LAS (0.5) and WMHC=2 (too WM) in both the avg as well as each timepoint + % (>> overcorrection) + % 1-new approach with + printlong = cat_get_defaults('extopts.print'); % create longitudinal subject report +end + +if ~useprior && longTPM && ~( ~longmodel && longTPM ) + cat_io_cprintf('blue','Deactivate longTPM!\n'); + longTPM = 0; +end + +if longmodel == 4 || ( ~longmodel && longTPM ) % ######################### only for my test ############### + cat_io_cprintf('blue','Have to use prepavg!\n'); + prepavg = 2; +end + +mbi = 0; +write_CSF = double(cat_get_defaults('output.CSF.mod') > 0); + +warning('off','MATLAB:DELETE:FileNotFound'); + + + + +% ======================================================================= +% CHAPTER 1: Preparing data for the preprocessing +% ======================================================================= +% Preparation of the data with additional denoising, data trimming, +% realignment, bias-correction and processing of the optimal average +% case to create an individual TPM and surfaces to stabilize the +% time point specific processing of the following chapter. +% ======================================================================= + + +% Denoising in native space (RD 202201) +% ----------------------------------------------------------------------- +% The SANLM is most effective in native space (non-interpolated) images. +% The prefix is required to avoid overwriting of the original data and we +% have to rename the registered output. +% The trimming and intensity have maybe light negative effects on the SPM +% noise estimation but should reduce processing time significantly! +% ----------------------------------------------------------------------- +if prepavg + mbi = mbi + 1; mb_sanlm = mbi; + matlabbatch{mbi}.spm.tools.cat.tools.sanlm.data = ''; + matlabbatch{mbi}.spm.tools.cat.tools.sanlm.spm_type = 16; + % we need a copy here (so we need a prefix) and have to rename it later + if longmodel + matlabbatch{mbi}.spm.tools.cat.tools.sanlm.prefix = 'sanlm_'; + else + matlabbatch{mbi}.spm.tools.cat.tools.sanlm.prefix = 'r'; + end + matlabbatch{mbi}.spm.tools.cat.tools.sanlm.suffix = ''; + matlabbatch{mbi}.spm.tools.cat.tools.sanlm.intlim = 100; + matlabbatch{mbi}.spm.tools.cat.tools.sanlm.rician = 0; + matlabbatch{mbi}.spm.tools.cat.tools.sanlm.replaceNANandINF = 1; + matlabbatch{1}.spm.tools.cat.tools.sanlm.nlmfilter.optimized.NCstr = 12; % lightavg + + if prepavg>1 + % The trimming may increase the speed of the longitudinal realignment and + % may helps also to remove side effects by huge low intensity backgrounds. + mbi = mbi + 1; mb_trim = mbi; + matlabbatch{mbi}.spm.tools.cat.tools.datatrimming.image_selector.manysubjects.simages(1) = ... + cfg_dep('Spatially adaptive non-local means (SANLM) denoising filter: SANLM Images', ... + substruct('.','val', '{}',{mb_sanlm}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), ... + substruct('.','files', '()',{':'})); + matlabbatch{mbi}.spm.tools.cat.tools.datatrimming.image_selector.manysubjects.oimages = {}; + matlabbatch{mbi}.spm.tools.cat.tools.datatrimming.prefix = ''; + matlabbatch{mbi}.spm.tools.cat.tools.datatrimming.mask = 1; + matlabbatch{mbi}.spm.tools.cat.tools.datatrimming.suffix = ''; + matlabbatch{mbi}.spm.tools.cat.tools.datatrimming.intlim1 = 90; + matlabbatch{mbi}.spm.tools.cat.tools.datatrimming.pth = 0.4; + matlabbatch{mbi}.spm.tools.cat.tools.datatrimming.open = 2; + matlabbatch{mbi}.spm.tools.cat.tools.datatrimming.addvox = 10; % defautl = 2, but we want to keep some more space around it for SPM noise estimation + matlabbatch{mbi}.spm.tools.cat.tools.datatrimming.ctype = 0; + matlabbatch{mbi}.spm.tools.cat.tools.datatrimming.intlim = 99.9999; % light intensity limitiation to avoid odd outliers + matlabbatch{mbi}.spm.tools.cat.tools.datatrimming.lazy = 0; + + if prepavg>2 + % Normalize data range to stabilize SPM longitudinal processing? + % Seems to be unnecessary because SPM scale the data itself. + mbi = mbi + 1; mb_type = mbi; + matlabbatch{mbi}.spm.tools.cat.tools.spmtype.data(1) = cfg_dep('Image data trimming: source images', ... + substruct('.','val', '{}',{mb_trim}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), ... + substruct('.','image_selector', '.','manysubjects', '.','simages')); + matlabbatch{mbi}.spm.tools.cat.tools.spmtype.ctype = 16; + matlabbatch{mbi}.spm.tools.cat.tools.spmtype.prefix = ''; + matlabbatch{mbi}.spm.tools.cat.tools.spmtype.suffix = ''; + matlabbatch{mbi}.spm.tools.cat.tools.spmtype.range = 99.9999; % finally we also want to remove the worst outlier + matlabbatch{mbi}.spm.tools.cat.tools.spmtype.intscale = 2; % 0-255 ? + matlabbatch{mbi}.spm.tools.cat.tools.spmtype.lazy = 0; + end + end +elseif ~longmodel && ~prepavg + % Just create a copy of the files to use the output dependency multiple times + mbi = mbi + 1; mb_sanlm = mbi; + matlabbatch{mbi}.spm.tools.cat.tools.file_move.files = ''; + matlabbatch{mbi}.spm.tools.cat.tools.file_move.action.copyren.copyto = {''}; + matlabbatch{mbi}.spm.tools.cat.tools.file_move.action.copyren.patrep.pattern = '^'; + matlabbatch{mbi}.spm.tools.cat.tools.file_move.action.copyren.patrep.repl = 'r'; + matlabbatch{mbi}.spm.tools.cat.tools.file_move.action.copyren.unique = false; +end + + + + +if 0 %longmodel == 4 && multiscan +% In case of scanner changes it is maybe possible to use John's Pipeline +% to estimate the deformations to remove geometric distortions. +% The deformations are only processed on a relative low level of about +% 2 mm and smoothed strongly to avoid adaption of brain anatomy changes. +% However, strong developemental changes cannot be modelled + + +% - affine scaling? - adapt voxelsize temporary? +% - nonlin averaging +% - bias field and intensity parameter estimation +% - tranformation of bias-field to time-point specific native spaces +% - tranformation of smoothed non-linear registration to native spaces +% - apply bias- and intensity corrections +% - apply non-linear deformation to compensate geometric distortions ... +% development issues + +end + + + + +% 1) longitudinal rigid registration with final masking (SAVG space) +% ----------------------------------------------------------------------- +% Here we bring all time points to the same rigid orientation, reslice the +% images, correct roughly for inhomogeneities between time points and create +% an average image. +% ######## +% RD202005: In case of strong developmental differences due to head size +% an affine registration or John's longitudinal average is maybe +% required at least to create the average. +% RD202201: To do so, it would be necessary to save the deformation field +% or the affine factor to include volumetric changes. +% RD202201: Can non-linear deformations improve average quality? +% In ADNI011S0003 I saw no improvement by using the original +% SPM pipeline, but in development (young children) it is highly +% imporant! +% RD202202: Added new development models to process children. +% ----------------------------------------------------------------------- +if longmodel == 4 || ( longmodel == 0 && longTPM ) +% ===== realign data with strong changes in development ===== + + % Create non-linear average to avoid ghosts. + mbi = mbi + 1; mb_nonlin = mbi; + matlabbatch{mbi}.spm.tools.cat.tools.series.reg.nonlin.times = 10; % inf means linear registration ... + matlabbatch{mbi}.spm.tools.cat.tools.series.reg.nonlin.wparam = [0 0 100 25 100]; + matlabbatch{mbi}.spm.tools.cat.tools.series.bparam = 1e6; + matlabbatch{mbi}.spm.tools.cat.tools.series.use_brainmask = 0; + matlabbatch{mbi}.spm.tools.cat.tools.series.reduce = 0; + matlabbatch{mbi}.spm.tools.cat.tools.series.setCOM = ... + exist('extopts','var') && ((isfield(extopts,'setCOM') && extopts.setCOM) || ... + (isfield(extopts,'segmentation') && isfield(extopts.segmentation,'setCOM') && extopts.segmentation.setCOM)); + if prepavg + matlabbatch{mbi}.spm.tools.cat.tools.series.data(1) = cfg_dep('Spatially adaptive non-local means (SANLM) denoising filter: SANLM Images', ... + substruct('.','val', '{}',{mb_sanlm}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), ... + substruct('.','files', '()',{':'})); + else + %matlabbatch{mbi}.spm.tools.cat.tools.series.data = ''; + matlabbatch{mbi}.spm.tools.cat.tools.series.data(1) = cfg_dep('Move/Delete Files: Moved/Copied Files', ... + substruct('.','val', '{}',{mb_sanlm}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), ... + substruct('.','files')); + end + + if longmodel || prepavg + % CLEANUP: Rename average output + mbi = mbi + 1; mb_rigid_ravg = mbi; + matlabbatch{mbi}.spm.tools.cat.tools.file_move.files(1) = cfg_dep('Longitudinal Registration: Midpoint Average',... + substruct('.','val', '{}',{mb_nonlin}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}),... + substruct('.','avg', '()',{':'})); + if longmodel + matlabbatch{mbi}.spm.tools.cat.tools.file_move.action.ren.patrep.pattern = 'avg_sanlm_'; + else % resliced filename pattern to make the nameing not more complicated + matlabbatch{mbi}.spm.tools.cat.tools.file_move.action.ren.patrep.pattern = 'avg_r'; + end + matlabbatch{mbi}.spm.tools.cat.tools.file_move.action.ren.patrep.repl = 'avg_'; + matlabbatch{mbi}.spm.tools.cat.tools.file_move.action.ren.unique = false; + end + + % CLEANUP: Delete other files + if delete_temp + mbi = mbi + 1; + matlabbatch{mbi}.cfg_basicio.file_dir.file_ops.file_move.files(1) = ... + cfg_dep('Serial Longitudinal Registration: Divergence', ... + substruct('.','val', '{}',{mb_nonlin}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), ... + substruct('.','jac', '()',{':'})); + matlabbatch{mbi}.cfg_basicio.file_dir.file_ops.file_move.files(2) = ... + cfg_dep('Longitudinal Rigid Registration: Realigned images', ... + substruct('.','val', '{}',{mb_nonlin}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), ... + substruct('.','rimg', '()',{':'})); + matlabbatch{mbi}.cfg_basicio.file_dir.file_ops.file_move.action.delete = false; + end + + + + if longmodel == 4 + % Create timepoints without deformation to keep the time-point specific + % native space. + mbi = mbi + 1; mb_rigid = mbi; + matlabbatch{mbi}.spm.tools.cat.tools.series.bparam = 1e6; + matlabbatch{mbi}.spm.tools.cat.tools.series.use_brainmask = 1; + matlabbatch{mbi}.spm.tools.cat.tools.series.reduce = 1; + matlabbatch{mbi}.spm.tools.cat.tools.series.setCOM = ... + exist('extopts','var') && ((isfield(extopts,'setCOM') && extopts.setCOM) || ... + (isfield(extopts,'segmentation') && isfield(extopts.segmentation,'setCOM') && extopts.segmentation.setCOM)); + matlabbatch{mbi}.spm.tools.cat.tools.series.data(1) = cfg_dep('Spatially adaptive non-local means (SANLM) denoising filter: SANLM Images', ... + substruct('.','val', '{}',{mb_sanlm}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), ... + substruct('.','files', '()',{':'})); + + % Rename all registrated images + mbi = mbi + 1; mb_rigid_rtp = mbi; + matlabbatch{mbi}.spm.tools.cat.tools.file_move.files(1) = cfg_dep('Longitudinal Rigid Registration: Realigned images',... + substruct('.','val', '{}',{mb_rigid}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}),... + substruct('.','rimg', '()',{':'})); + matlabbatch{mbi}.spm.tools.cat.tools.file_move.action.ren.patrep.pattern = 'rsanlm_'; + matlabbatch{mbi}.spm.tools.cat.tools.file_move.action.ren.patrep.repl = 'r'; + matlabbatch{mbi}.spm.tools.cat.tools.file_move.action.ren.unique = false; + + % delete average because we use the non-linear one + if delete_temp + mbi = mbi + 1; + matlabbatch{mbi}.cfg_basicio.file_dir.file_ops.file_move.files(1) = ... + cfg_dep('Longitudinal Registration: Midpoint Average',... + substruct('.','val', '{}',{mb_rigid}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}),... + substruct('.','avg', '()',{':'})); + matlabbatch{mbi}.cfg_basicio.file_dir.file_ops.file_move.action.delete = false; + end + end +elseif longmodel +% ===== classical model for plasticity/aging ===== + + mbi = mbi + 1; mb_rigid = mbi; + matlabbatch{mbi}.spm.tools.cat.tools.series.bparam = 1e6; + matlabbatch{mbi}.spm.tools.cat.tools.series.use_brainmask = 1; + matlabbatch{mbi}.spm.tools.cat.tools.series.reduce = 1; + if exist('extopts','var') && ((isfield(extopts,'setCOM') && extopts.setCOM) || ... + (isfield(extopts,'segmentation') && isfield(extopts.segmentation,'setCOM') && extopts.segmentation.setCOM)) + matlabbatch{mbi}.spm.tools.cat.tools.series.setCOM = 1; + else + matlabbatch{mbi}.spm.tools.cat.tools.series.setCOM = 0; + end + if prepavg + % last part of series batch + matlabbatch{mbi}.spm.tools.cat.tools.series.data(1) = cfg_dep('Spatially adaptive non-local means (SANLM) denoising filter: SANLM Images', ... + substruct('.','val', '{}',{mb_sanlm}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), ... + substruct('.','files', '()',{':'})); + + + % in case of denoising we may need another renaming step for the avg ... + mbi = mbi + 1; mb_rigid_ravg = mbi; + matlabbatch{mbi}.spm.tools.cat.tools.file_move.files(1) = cfg_dep('Longitudinal Registration: Midpoint Average',... + substruct('.','val', '{}',{mb_rigid}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}),... + substruct('.','avg', '()',{':'})); + matlabbatch{mbi}.spm.tools.cat.tools.file_move.action.ren.patrep.pattern = 'avg_sanlm_'; + matlabbatch{mbi}.spm.tools.cat.tools.file_move.action.ren.patrep.repl = 'avg_'; + matlabbatch{mbi}.spm.tools.cat.tools.file_move.action.ren.unique = false; + + + % ... and all registrated images + mbi = mbi + 1; mb_rigid_rtp = mbi; + matlabbatch{mbi}.spm.tools.cat.tools.file_move.files(1) = cfg_dep('Longitudinal Rigid Registration: Realigned images',... + substruct('.','val', '{}',{mb_rigid}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}),... + substruct('.','rimg', '()',{':'})); + matlabbatch{mbi}.spm.tools.cat.tools.file_move.action.ren.patrep.pattern = 'rsanlm_'; + matlabbatch{mbi}.spm.tools.cat.tools.file_move.action.ren.patrep.repl = 'r'; + matlabbatch{mbi}.spm.tools.cat.tools.file_move.action.ren.unique = false; + else + % without preparation, we start here with the raw input data + matlabbatch{mbi}.spm.tools.cat.tools.series.data = ''; + end + +end + + + + + + + +% 2) cat12 segmentation of average image +% ----------------------------------------------------------------------- +% The average image is used for a general segmentation and registration +% to the MNI template. The rigid segmentation is used to create an +% individual TPM in step 3. +% ----------------------------------------------------------------------- +if longmodel || longTPM + mbi = mbi + 1; mb_catavg = mbi; + if ~longmodel && ~prepavg + matlabbatch{mbi}.spm.tools.cat.estwrite.data(1) = cfg_dep('Move/Delete Files: Moved/Copied Files', ... + substruct('.','val', '{}',{mb_sanlm}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), ... + substruct('.','files')); + elseif ~longmodel && ~prepavg && longTPM + matlabbatch{mbi}.spm.tools.cat.estwrite.data(1) = cfg_dep('Longitudinal Registration: Midpoint Average',... + substruct('.','val', '{}',{mb_nonlin}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}),... + substruct('.','avg', '()',{':'})); + elseif prepavg + matlabbatch{mbi}.spm.tools.cat.estwrite.data(1) = cfg_dep('Move/Delete Files: Moved/Copied Files', ... + substruct('.','val', '{}',{mb_rigid_ravg}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), ... + substruct('.','files')); + else + matlabbatch{mbi}.spm.tools.cat.estwrite.data(1) = cfg_dep('Longitudinal Registration: Midpoint Average',... + substruct('.','val', '{}',{mb_rigid}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}),... + substruct('.','avg', '()',{':'})); + end + + matlabbatch{mbi}.spm.tools.cat.estwrite.nproc = 0; + if exist('opts','var') && ~isempty(opts) + matlabbatch{mbi}.spm.tools.cat.estwrite.opts = opts; + end + if exist('extopts','var') && ~isempty(extopts) + matlabbatch{mbi}.spm.tools.cat.estwrite.extopts = extopts; + + % WMHC: This is more complicated ... + % Using the CAT default (WMHC==2 + % LAS: Only the small correction here, because it will be done in the TPs + % and we do not want to do it twice (the longTPM would introduce a bias). + % The lowes setting (eps) was a bit to weak. + + % RD202201: Shooting with lower frequency setting? + % Although, we don't use the deformations this effects the WMHC. + % But as far as this is also not used now it is not necessary/ + % useful to change something now. + %if isfield(extopts,'registration') && isfield(extopts.registration,'regmethod') && isfield(extopts.registration.regmethod,'regstr') + % matlabbatch{mbi}.spm.tools.cat.estwrite.extopts.registration.regmethod.shooting.regstr = 14; % low frequency 2.5 mm + %end + if longmodel + switch avgLASWMHC + case 0 % old setting + WMHC = []; % use default + LASstr = []; % use default + case 1 % new corrected setting + % RD20220126: WMHC==1: + % Only temporary because we don't want to bias the WM segmentation of the TPs! + % This works better for the peaks and the GM is less biased compared to the average + % but there are now more problems with incorrected WMHs. + WMHC = 2; % Correct WMH as WM to have a similar handling like in normal TPMs. + % This maybe reduce the chance to find WMHs within the timepoints. + LASstr = 0.25; + case 2 % ... use extra class for WMHC to avoid bias ... + WMHC = 3; + LASstr = 0.25; + case 3 + WMHC = 3; % use own class + LASstr = []; % use GUI value here and lower LASstr in time points + end + if cat_get_defaults('extopts.expertgui')>0 + if ~isempty(WMHC), matlabbatch{mbi}.spm.tools.cat.estwrite.extopts.segmentation.WMHC = WMHC; end + if ~isempty(LASstr), matlabbatch{mbi}.spm.tools.cat.estwrite.extopts.segmentation.LASstr = LASstr; end + else + if ~isempty(WMHC), matlabbatch{mbi}.spm.tools.cat.estwrite.extopts.WMHC = WMHC; end + if ~isempty(LASstr), matlabbatch{mbi}.spm.tools.cat.estwrite.extopts.LASstr = LASstr; end + end + end + end + + % RD202102: differentiation between user levels not tested yet ! + if exist('extopts','var') && isfield(extopts,'bb') + matlabbatch{mbi}.spm.tools.cat.estwrite.extopts.bb = 1; % use TPM output BB + elseif exist('extopts','var') && isfield(extopts,'registration') && isfield(extopts.registration,'bb') + matlabbatch{mbi}.spm.tools.cat.estwrite.extopts.registration.bb = 1; % use TPM output BB + end + % RD202403: run average for 1.5 mm to combine it with the TPM + if exist('extopts','var') && isfield(extopts,'vox') + matlabbatch{mbi}.spm.tools.cat.estwrite.extopts.vox = 1.5; + elseif exist('extopts','var') && isfield(extopts,'registration') && isfield(extopts.registration,'vox') + matlabbatch{mbi}.spm.tools.cat.estwrite.extopts.registration.vox = 1.5; + end + + + if exist('output','var') && ~isempty(output) + matlabbatch{mbi}.spm.tools.cat.estwrite.output = output; + end + + % surface estimation + matlabbatch{mbi}.spm.tools.cat.estwrite.output.surface = surfaces .* (longmodel>0); + matlabbatch{mbi}.spm.tools.cat.estwrite.output.ROImenu.noROI= struct([]); + matlabbatch{mbi}.spm.tools.cat.estwrite.output.GM.native = 0; + matlabbatch{mbi}.spm.tools.cat.estwrite.output.GM.dartel = 2; + matlabbatch{mbi}.spm.tools.cat.estwrite.output.GM.mod = 0; + matlabbatch{mbi}.spm.tools.cat.estwrite.output.WM.native = 0; + matlabbatch{mbi}.spm.tools.cat.estwrite.output.WM.dartel = 2; + matlabbatch{mbi}.spm.tools.cat.estwrite.output.WM.mod = 0; + matlabbatch{mbi}.spm.tools.cat.estwrite.output.CSF.dartel = 2; + matlabbatch{mbi}.spm.tools.cat.estwrite.output.TPMC.dartel = 2 .* double(longTPM); + matlabbatch{mbi}.spm.tools.cat.estwrite.output.label.native = double(longmodel>0); + matlabbatch{mbi}.spm.tools.cat.estwrite.output.bias.warped = 0; + matlabbatch{mbi}.spm.tools.cat.estwrite.output.warps = [0 0]; +end + +% LONGTPM: Creating longitudinal TPM +% ----------------------------------------------------------------------- +% Using a subject-specific TPM allows to stabilize the preprocessing of the +% individual time points, mostly of the initial affine registration and +% the Unified segmentation that also compensates for slight structural +% changes between the time points. However the effects on the final AMAP +% segmentations are relatively small. +if longTPM + mbi = mbi + 1; mb_tpm = mbi; + matlabbatch{mbi}.spm.tools.cat.tools.createTPMlong.files(1) = cfg_dep('CAT12: Segmentation (current release): rp1 affine Image',... + substruct('.','val', '{}',{mb_catavg}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}),... + substruct('.','tiss', '()',{1}, '.','rpa', '()',{':'})); + matlabbatch{mbi}.spm.tools.cat.tools.createTPMlong.fstrength = 2; % smoothness of the individual TPM (0 very hard for plasticity, .., 4 very smooth for long-time aging) + matlabbatch{mbi}.spm.tools.cat.tools.createTPMlong.writeBM = 0; + matlabbatch{mbi}.spm.tools.cat.tools.createTPMlong.verb = 1; +end + + + + + +% 3a) longitudinal bias correction (in development) +% ----------------------------------------------------------------------- +if longmodel && bstr > 0 + mbi = mbi + 1; mb_tpbc = mbi; + if prepavg + matlabbatch{mbi}.spm.tools.cat.tools.longBiasCorr.images(1) = cfg_dep('Move/Delete Files: Moved/Copied Files', ... + substruct('.','val', '{}',{mb_rigid_rtp}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), ... + substruct('.','files')); + else + matlabbatch{mbi}.spm.tools.cat.tools.longBiasCorr.images(1) = cfg_dep('Longitudinal Rigid Registration: Realigned images',... + substruct('.','val', '{}',{mb_rigid}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}),... + substruct('.','rimg', '()',{':'})); + end + matlabbatch{mbi}.spm.tools.cat.tools.longBiasCorr.segment(1) = cfg_dep('CAT12: Segmentation (current release): Native Label Image',... + substruct('.','val', '{}',{mb_catavg}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}),... + substruct('.','label', '()',{':'})); + matlabbatch{mbi}.spm.tools.cat.tools.longBiasCorr.str = job.bstr; + matlabbatch{mbi}.spm.tools.cat.tools.longBiasCorr.prefix = 'm'; +end + + + + + + +% ======================================================================= +% CHAPTER 2: Preprocessing of time points +% ======================================================================= +% Timepoint specific preprocessing with special registration techniques +% depending on the longitudinal model (longmodel). +% ======================================================================= + + +% ----------------------------------------------------------------------- +% Cat12 segmentation of prepared longitudinal images +% ----------------------------------------------------------------------- +% In this step each time point is estimated separately but uses the prior +% (affreg/brain-mask/surface) and the LONGTPM from the AVG for preocessing +% depending on the selected longmodel and other preparation steps. +% ----------------------------------------------------------------------- +mbi = mbi + 1; mb_cat = mbi; +% use average image as prior for affine transformation and surface extraction +%if 0%~longmodel && ~longTPM && +% matlabbatch{mbi}.spm.tools.cat.estwrite.data = ''; +%else +if ~longmodel %&& longTPM + matlabbatch{mbi}.spm.tools.cat.estwrite.data(1) = cfg_dep('Spatially adaptive non-local means (SANLM) denoising filter: SANLM Images', ... + substruct('.','val', '{}',{mb_sanlm}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), ... + substruct('.','files', '()',{':'})); +elseif bstr > 0 + matlabbatch{mbi}.spm.tools.cat.estwrite.data(1) = cfg_dep('Segment: Longitudinal Bias Corrected',... + substruct('.','val', '{}',{mb_tpbc}, '.','val', '{}',{1}, '.','val', '{}',{1}),... + substruct('.','bc', '()',{':'})); +elseif longmodel && prepavg + matlabbatch{mbi}.spm.tools.cat.estwrite.data(1) = cfg_dep('Move/Delete Files: Moved/Copied Files', ... + substruct('.','val', '{}',{mb_rigid_rtp}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), ... + substruct('.','files')); +else + matlabbatch{mbi}.spm.tools.cat.estwrite.data(1) = cfg_dep('Longitudinal Rigid Registration: Realigned images',... + substruct('.','val', '{}',{mb_rigid}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}),... + substruct('.','rimg', '()',{':'})); +end +matlabbatch{mbi}.spm.tools.cat.estwrite.nproc = 0; + +if exist('opts','var') && ~isempty(opts) + matlabbatch{mbi}.spm.tools.cat.estwrite.opts = opts; +end + +if exist('extopts','var') && ~isempty(extopts) + matlabbatch{mbi}.spm.tools.cat.estwrite.extopts = extopts; + + if longmodel && avgLASWMHC==3 + LASstr = 0.25; + if cat_get_defaults('extopts.expertgui')>0 + matlabbatch{mbi}.spm.tools.cat.estwrite.extopts.segmentation.LASstr = LASstr; + else + matlabbatch{mbi}.spm.tools.cat.estwrite.extopts.LASstr = LASstr; + end + end +end + +if exist('output','var') && ~isempty(output) + matlabbatch{mbi}.spm.tools.cat.estwrite.output = output; +end + +% surface estimation +matlabbatch{mbi}.spm.tools.cat.estwrite.output.surface = surfaces; + +if exist('ROImenu','var') && ~isempty(ROImenu) + matlabbatch{mbi}.spm.tools.cat.estwrite.output.ROImenu = ROImenu; +end + +matlabbatch{mbi}.spm.tools.cat.estwrite.output.GM.native = double(longmodel>0); +matlabbatch{mbi}.spm.tools.cat.estwrite.output.GM.dartel = dartel; +matlabbatch{mbi}.spm.tools.cat.estwrite.output.GM.mod = double(longmodel==0); +matlabbatch{mbi}.spm.tools.cat.estwrite.output.WM.native = double(longmodel>0); +matlabbatch{mbi}.spm.tools.cat.estwrite.output.WM.dartel = dartel; +matlabbatch{mbi}.spm.tools.cat.estwrite.output.WM.mod = double(longmodel==0); + +if write_CSF + matlabbatch{mbi}.spm.tools.cat.estwrite.output.CSF.native = double(longmodel>0); % also write CSF? + matlabbatch{mbi}.spm.tools.cat.estwrite.output.CSF.dartel = dartel; + matlabbatch{mbi}.spm.tools.cat.estwrite.output.CSF.mod = double(longmodel==0); +end + +matlabbatch{mbi}.spm.tools.cat.estwrite.output.bias.warped = 0; +matlabbatch{mbi}.spm.tools.cat.estwrite.output.warps = [double(longmodel>0) 0]; + +if longmodel && useprior + if prepavg + matlabbatch{mbi}.spm.tools.cat.estwrite.useprior(1) = cfg_dep('Move/Delete Files: Moved/Copied Files', ... + substruct('.','val', '{}',{mb_rigid_ravg}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), ... + substruct('.','files')); + else + matlabbatch{mbi}.spm.tools.cat.estwrite.useprior(1) = cfg_dep('Longitudinal Registration: Midpoint Average',... + substruct('.','val', '{}',{mb_rigid}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}),... + substruct('.','avg', '()',{':'})); + end + if longmodel<4 % plasticity and aging + matlabbatch{mbi}.spm.tools.cat.estwrite.opts.affreg = 'prior'; + else % development model + matlabbatch{mbi}.spm.tools.cat.estwrite.opts.affreg = 'subj'; + end +elseif longTPM + matlabbatch{mbi}.spm.tools.cat.estwrite.opts.affreg = 'subj'; +end + +if longTPM + matlabbatch{mbi}.spm.tools.cat.estwrite.opts.tpm = cfg_dep('Longitudinal TPM creation: Longitudinal TPMs',... + substruct('.','val', '{}',{mb_tpm}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}),... + substruct('.','tpm', '()',{':'})); +end + + +if longmodel +% 5) averaging deformations +% ----------------------------------------------------------------------- +% To map the data to the MNI space, the time point specific deformations +% were averaged. +% ####### +% RD202005: In case of developemental data, we may need to use the +% deformation from the SAVG to deal with larger affine changes +% due to different head size. +% ####### + mbi = mbi + 1; mb_avgdef = mbi; + matlabbatch{mbi}.spm.tools.cat.tools.avg_img.data(1) = cfg_dep('CAT12: Segmentation (current release): Deformation Field',... + substruct('.','val', '{}',{mb_cat}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}),... + substruct('()',{1}, '.','fordef', '()',{':'})); + matlabbatch{mbi}.spm.tools.cat.tools.avg_img.output = ''; + matlabbatch{mbi}.spm.tools.cat.tools.avg_img.outdir = {''}; +end + + + +if longmodel > 1 +% 6) creating time point specific deformation +% ----------------------------------------------------------------------- +% To reduce longitudinal changes of moving structures between time points +% a longitudinal Shooting template is estimated. +% ####### +% RD202005: In case of developmental data, we may need to use different +% Shooting parameters (e.g., more iterations, more low-freq. +% changes to adapt for head size changes. +% ####### + + lowres = 2; % define resolution in mm + if lowres + % reduce resolution + % It would be also possible to use the rigid output from the time points + % but those depend on user definition of extopts.vox and we are more + % flexible and probably faster and more robust this way. + mb_lr = zeros(1,2); + for ci = 1:2 % only GM and WM are required for Shooting + mbi = mbi + 1; mb_lr(ci) = mbi; % have to do this for all shooting tissues to get the dependencies + matlabbatch{mbi}.spm.tools.cat.tools.resize.data(1) = cfg_dep(sprintf('CAT12: Segmentation (current release): p%d Image',ci),... + substruct('.','val', '{}',{mb_cat}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}),... + substruct('.','tiss', '()',{ci}, '.','p', '()',{':'})); + matlabbatch{mbi}.spm.tools.cat.tools.resize.restype.res = lowres; + matlabbatch{mbi}.spm.tools.cat.tools.resize.interp = 5; + matlabbatch{mbi}.spm.tools.cat.tools.resize.prefix = 'l'; % need to be another file + end + % Shooting low res + mbi = mbi + 1; mb_GS = mbi; + matlabbatch{mbi}.spm.tools.cat.tools.warp.images{1}(1) = cfg_dep('Resize images: Resized',... + substruct('.','val', '{}',{mb_lr(1)}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}),... + substruct('.','res', '()',{':'})); + matlabbatch{mbi}.spm.tools.cat.tools.warp.images{2}(1) = cfg_dep('Resize images: Resized',... + substruct('.','val', '{}',{mb_lr(2)}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}),... + substruct('.','res', '()',{':'})); + matlabbatch{mbi}.spm.tools.cat.tools.warp.dfile = {fullfile(fileparts(mfilename('fullpath')),'cat_long_shoot_defaults.m')}; + + % reinterpolate original resolution + mbi = mbi + 1; mb_GSI = mbi; % have to do this for all shooting tissues to get the dependencies + matlabbatch{mbi}.spm.tools.cat.tools.resize.data(1) = cfg_dep('Run Shooting (create Templates): Deformation Fields',... + substruct('.','val', '{}',{mb_GS}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}),... + substruct('.','def', '()',{':'})); + if prepavg + matlabbatch{mbi}.spm.tools.cat.tools.resize.restype.Pref = cfg_dep('Move/Delete Files: Moved/Copied Files', ... + substruct('.','val', '{}',{mb_rigid_ravg}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), ... + substruct('.','files')); + else + matlabbatch{mbi}.spm.tools.cat.tools.resize.restype.Pref = cfg_dep('Longitudinal Registration: Midpoint Average',... + substruct('.','val', '{}',{mb_rigid}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}),... + substruct('.','avg', '()',{':'})); + end + matlabbatch{mbi}.spm.tools.cat.tools.resize.interp = 5; + matlabbatch{mbi}.spm.tools.cat.tools.resize.prefix = ''; % has to be another name? + else + % Shooting full res + mbi = mbi + 1; mb_GS = mbi; + matlabbatch{mbi}.spm.tools.cat.tools.warp.images{1}(1) = cfg_dep('CAT12: Segmentation (current release): p1 Image',... + substruct('.','val', '{}',{mb_cat}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}),... + substruct('.','tiss', '()',{1}, '.','p', '()',{':'})); + matlabbatch{mbi}.spm.tools.cat.tools.warp.images{2}(1) = cfg_dep('CAT12: Segmentation (current release): p2 Image',... + substruct('.','val', '{}',{mb_cat}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}),... + substruct('.','tiss', '()',{2}, '.','p', '()',{':'})); + matlabbatch{mbi}.spm.tools.cat.tools.warp.dfile = {fullfile(fileparts(mfilename('fullpath')),'cat_long_shoot_defaults.m')}; + end + + + + + % 7) applying time point deformations to rigid native segmentations + % ----------------------------------------------------------------------- + % this is the first simple approach with full resolution + mb_aGS = zeros(1,2 + write_CSF); + for ci = 1:2 + write_CSF + mbi = mbi + 1; mb_aGS(ci) = mbi; + if lowres + matlabbatch{mbi}.spm.tools.cat.tools.defs2.field(1) = cfg_dep('Resize images: Resized',... + substruct('.','val', '{}',{mb_GSI}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}),... + substruct('.','res', '()',{':'})); + else + matlabbatch{mbi}.spm.tools.cat.tools.defs2.field(1) = cfg_dep('Run Shooting (create Templates): Deformation Fields',... + substruct('.','val', '{}',{mb_GS}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}),... + substruct('.','def', '()',{':'})); + end + matlabbatch{mbi}.spm.tools.cat.tools.defs2.images{1}(1) = cfg_dep(sprintf('CAT12: Segmentation (current release): p%d Image',ci),... + substruct('.','val', '{}',{mb_cat}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}),... + substruct('.','tiss', '()',{ci}, '.','p', '()',{':'})); + matlabbatch{mbi}.spm.tools.cat.tools.defs2.interp = 1; + matlabbatch{mbi}.spm.tools.cat.tools.defs2.bb = [NaN NaN NaN + NaN NaN NaN]; + matlabbatch{mbi}.spm.tools.cat.tools.defs2.vox = [NaN NaN NaN]; + if modulate, matlabbatch{mbi}.spm.tools.cat.tools.defs2.modulate = modulate; end % modulation option for applying deformations + end +end + + +if longmodel + % 8) applying deformations to time point optimized native segmentations + % ----------------------------------------------------------------------- + % Applying deformations to tissues by using separate batches to keep the + % dependencies for the different tissue maps of each longitudinal model to + % create the longitudinal reports. + mbfdef = zeros(2,2 + write_CSF); + for ci = 1:(2 + write_CSF)*(1 + (longmodel==3)) % fill image sets + mbi = mbi + 1; + mbfdef(1 + (ci>(2+write_CSF)) , 1 + mod(ci - 1,2+write_CSF)) = mbi; + matlabbatch{mbi}.spm.tools.cat.tools.defs.field1(1) = cfg_dep('Image Average: Average Image: ',... + substruct('.','val', '{}',{mb_avgdef}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}),... + substruct('.','files')); + if ci <= 2 + write_CSF + if longmodel==1 + % was step {11} before ... optimize later ... this make no sense at all + % matlabbatch{mbi}.spm.tools.cat.tools.defs.images(1) = cfg_dep('Apply deformations (many subjects): All Output Files', ... + % substruct('.','val', '{}',{11}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), ... + % substruct('.','vfiles')); + matlabbatch{mbi}.spm.tools.cat.tools.defs.images(1) = cfg_dep(sprintf('CAT12: Segmentation (current release): p%d Image',ci),... + substruct('.','val', '{}',{mb_cat}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}),... + substruct('.','tiss', '()',{ci}, '.','p', '()',{':'})); + else + matlabbatch{mbi}.spm.tools.cat.tools.defs.images(1) = cfg_dep('Apply deformations (many subjects): All Output Files',... + substruct('.','val', '{}',{mb_aGS(ci)}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}),... + substruct('.','vfiles')); + end + else + if longmodel==3 + matlabbatch{mbi}.spm.tools.cat.tools.defs.images(1) = cfg_dep(sprintf('CAT12: Segmentation (current release): p%d Image',ci - (2 + write_CSF)),... + substruct('.','val', '{}',{mb_cat}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}),... + substruct('.','tiss', '()',{ci - (2 + write_CSF)}, '.','p', '()',{':'})); + end + end + matlabbatch{mbi}.spm.tools.cat.tools.defs.interp = 1; + matlabbatch{mbi}.spm.tools.cat.tools.defs.bb = [NaN NaN NaN + NaN NaN NaN]; + matlabbatch{mbi}.spm.tools.cat.tools.defs.vox = [NaN NaN NaN]; + if modulate, matlabbatch{mbi}.spm.tools.cat.tools.defs.modulate = modulate; end % modulation option for applying deformations + end + + + + % 9) applying deformations to average T1 image + % ----------------------------------------------------------------------- + mbi = mbi + 1; + matlabbatch{mbi}.spm.tools.cat.tools.defs.field1(1) = cfg_dep('Image Average: Average Image: ',... + substruct('.','val', '{}',{mb_avgdef}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}),... + substruct('.','files')); + if prepavg + matlabbatch{mbi}.spm.tools.cat.tools.defs.images(1) = cfg_dep('Move/Delete Files: Moved/Copied Files', ... + substruct('.','val', '{}',{mb_rigid_ravg}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), ... + substruct('.','files')); + else + matlabbatch{mbi}.spm.tools.cat.tools.defs.images(1) = cfg_dep('Longitudinal Registration: Midpoint Average',... + substruct('.','val', '{}',{mb_rigid}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}),... + substruct('.','avg', '()',{':'})); + end + matlabbatch{mbi}.spm.tools.cat.tools.defs.interp = 1; + matlabbatch{mbi}.spm.tools.cat.tools.defs.modulate = 0; + matlabbatch{mbi}.spm.tools.cat.tools.defs.bb = [NaN NaN NaN + NaN NaN NaN]; + matlabbatch{mbi}.spm.tools.cat.tools.defs.vox = [NaN NaN NaN]; +end + +% 10) final report +if printlong % write at least long XML ... printlong %&& spm_get_defaults('job.extopts.expertgui')>1 + % cross-case + if ~longmodel + % resample & smooth surface by side ... delete later + + end + + for modi = 1:2 + if ~longmodel || mbfdef(modi,1)>0 + if ( modi == 1 ) || ( modi == 2 && (longmodel==2 || longmodel==3) ) % allways print in modi 1 ! ... && (longmodel==1 || longmodel==3) ) + mbi = mbi + 1; + if longmodel + matlabbatch{mbi}.spm.tools.cat.tools.long_report.data_vol(1) = cfg_dep('Apply deformations (many subjects): All Output Files',... + substruct('.','val', '{}',{mbfdef(modi,1)}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}),... + substruct('.','vfiles', '()',{':'})); + else + matlabbatch{mbi}.spm.tools.cat.tools.long_report.data_vol(1) = cfg_dep('CAT12: Segmentation (current release): mwp1 Image',... + substruct('.','val', '{}',{mb_cat}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}),... + substruct('.','tiss', '()',{1}, '.','mwp', '()',{':'})); + end + if surfaces % && useprior && longmodel % otherwise the indivudal surfaces will not have the same mesh! + matlabbatch{mbi}.spm.tools.cat.tools.long_report.data_surf(1) = cfg_dep('CAT12: Segmentation (current release): Left Thickness',... + substruct('.','val', '{}',{mb_cat}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}),... + substruct('()',{1}, '.','lhthickness', '()',{':'})); + else + matlabbatch{mbi}.spm.tools.cat.tools.long_report.data_surf = {''}; + end + if cat_get_defaults('extopts.expertgui')>0 + matlabbatch{mbi}.spm.tools.cat.tools.long_report.data_xml(1) = cfg_dep('CAT12: Segmentation (current release): ROI XML File',... + substruct('.','val', '{}',{mb_cat}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}),... + substruct('.','catroi')); + %matlabbatch{mbi}.spm.tools.cat.tools.long_report.timepoints = []; % not implemented yet + %matlabbatch{mbi}.spm.tools.cat.tools.long_report.opts.midpoint = 0; % not implemented yet + matlabbatch{mbi}.spm.tools.cat.tools.long_report.opts.smoothvol = 3; + matlabbatch{mbi}.spm.tools.cat.tools.long_report.opts.smoothsurf = 12; + matlabbatch{mbi}.spm.tools.cat.tools.long_report.opts.plotGMWM = 1; + matlabbatch{mbi}.spm.tools.cat.tools.long_report.output.vols = ~delete_temp; + matlabbatch{mbi}.spm.tools.cat.tools.long_report.output.surfs = ~delete_temp; + matlabbatch{mbi}.spm.tools.cat.tools.long_report.output.xml = ~delete_temp; + end + matlabbatch{mbi}.spm.tools.cat.tools.long_report.printlong = printlong; + end + end + end +end + + + +if any(longreport) % && spm_get_defaults('job.extopts.expertgui') > 1 + for ci = 1:2 % + write_CSF + for modi = 1:2 + if longreport(ci) && mbfdef(modi,ci)>0 + if ( modi == 1 ) || ( modi == 2 && (longmodel==2 || longmodel==3) ) % allways print in modi 1 ! ... && (longmodel==1 || longmodel==3) ) + mbi = mbi + 1; + matlabbatch{mbi}.spm.tools.cat.tools.long_report.data_vol(1) = cfg_dep('Apply deformations (many subjects): All Output Files',... + substruct('.','val', '{}',{mbfdef(modi,ci)}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}),... + substruct('.','vfiles', '()',{':'})); + if surfaces + matlabbatch{mbi}.spm.tools.cat.tools.long_report.data_surf(1) = cfg_dep('CAT12: Segmentation (current release): Left Thickness',... + substruct('.','val', '{}',{mb_cat}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}),... + substruct('()',{1}, '.','lhthickness', '()',{':'})); + else + matlabbatch{mbi}.spm.tools.cat.tools.long_report.data_surf = {''}; + end + if cat_get_defaults('extopts.expertgui')>0 + matlabbatch{mbi}.spm.tools.cat.tools.long_report.data_xml(1) = cfg_dep('CAT12: Segmentation (current release): ROI XML File',... + substruct('.','val', '{}',{mb_cat}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}),... + substruct('.','catroi')); + %matlabbatch{mbi}.spm.tools.cat.tools.long_report.timepoints = []; % not implemented yet + %matlabbatch{mbi}.spm.tools.cat.tools.long_report.opts.midpoint = 0; % not implemented yet + matlabbatch{mbi}.spm.tools.cat.tools.long_report.opts.smoothvol = 3; + matlabbatch{mbi}.spm.tools.cat.tools.long_report.opts.smoothsurf = 12; + end + end + end + end + end +end + + + +% 11) delete temporary files +% ----------------------------------------------------------------------- +if delete_temp + mbi = mbi + 1; + c = 1; + + if longmodel + % remove time point specific preprocessing data + for ci = 1:2 + write_CSF + matlabbatch{mbi}.cfg_basicio.file_dir.file_ops.file_move.files(c) = cfg_dep(sprintf('CAT12: Segmentation (current release): p%d Image',ci),... + substruct('.','val', '{}',{mb_cat}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}),... + substruct('.','tiss', '()',{ci}, '.','p', '()',{':'})); c = c+1; + end + % deformation field + matlabbatch{mbi}.cfg_basicio.file_dir.file_ops.file_move.files(c) = cfg_dep('CAT12: Segmentation (current release): Deformation Field',... + substruct('.','val', '{}',{mb_cat}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}),... + substruct('()',{1}, '.','fordef', '()',{':'})); c = c+1; + end + + if longmodel || longTPM + if prepavg + matlabbatch{mbi}.cfg_basicio.file_dir.file_ops.file_move.files(c) = cfg_dep('Move/Delete Files: Moved/Copied Files', ... + substruct('.','val', '{}',{mb_rigid_ravg}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), ... + substruct('.','files')); c = c+1; + end + matlabbatch{mbi}.cfg_basicio.file_dir.file_ops.file_move.files(c) = cfg_dep('CAT12: Segmentation: Native Label Image', ... + substruct('.','val', '{}',{mb_catavg}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), ... + substruct('()',{1}, '.','label', '()',{':'})); c = c+1; + % remove average preprocessing data + matlabbatch{mbi}.cfg_basicio.file_dir.file_ops.file_move.files(c) = cfg_dep('CAT12: Segmentation (current release): CAT Report PDF',... + substruct('.','val', '{}',{mb_catavg}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}),... + substruct('.','catreportpdf', '()',{':'})); c = c+1; + matlabbatch{mbi}.cfg_basicio.file_dir.file_ops.file_move.files(c) = cfg_dep('CAT12: Segmentation (current release): CAT Report JPG',... + substruct('.','val', '{}',{mb_catavg}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}),... + substruct('.','catreportjpg', '()',{':'})); c = c+1; + matlabbatch{mbi}.cfg_basicio.file_dir.file_ops.file_move.files(c) = cfg_dep('CAT12: Segmentation (current release): CAT Report',... + substruct('.','val', '{}',{mb_catavg}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}),... + substruct('.','catxml', '()',{':'})); c = c+1; + matlabbatch{mbi}.cfg_basicio.file_dir.file_ops.file_move.files(c) = cfg_dep('CAT12: Segmentation (current release): CAT log-file',... + substruct('.','val', '{}',{mb_catavg}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}),... + substruct('.','catlog', '()',{':'})); c = c+1; + + + % remove affine registered GM/WM segmentations of average data if not needed + if ~dartel + for ci = 1:2 + matlabbatch{mbi}.cfg_basicio.file_dir.file_ops.file_move.files(c) = cfg_dep(sprintf('CAT12: Segmentation (current release): rp%d affine Image',ci),... + substruct('.','val', '{}',{mb_catavg}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}),... + substruct('.','tiss', '()',{ci}, '.','rpa', '()',{':'})); c = c+1; + end + end + + % remove affine registered CSF segmentation of average data if not needed + if ~write_CSF || ~dartel + matlabbatch{mbi}.cfg_basicio.file_dir.file_ops.file_move.files(c) = cfg_dep('CAT12: Segmentation (current release): rp3 affine Image',... + substruct('.','val', '{}',{mb_catavg}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}),... + substruct('.','tiss', '()',{3}, '.','rpa', '()',{':'})); c = c+1; + end + + + % remove remaining affine registered segmentations of average data (class 4-6) + if longTPM + for ci = 4:6 + matlabbatch{mbi}.cfg_basicio.file_dir.file_ops.file_move.files(c) = cfg_dep(sprintf('CAT12: Segmentation (current release): rp%d affine Image',ci),... + substruct('.','val', '{}',{mb_catavg}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}),... + substruct('.','tiss', '()',{ci}, '.','rpa', '()',{':'})); c = c+1; + end + end + + % remove ROI label files of average data + if exist('ROImenu','var') && ~isempty(ROImenu) + matlabbatch{mbi}.cfg_basicio.file_dir.file_ops.file_move.files(c) = cfg_dep('CAT12: Segmentation (current release): ROI XML File',... + substruct('.','val', '{}',{mb_catavg}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}),... + substruct('.','catroi', '()',{':'})); c = c+1; + end + end + + if longmodel && bstr > 0 && ~isempty( matlabbatch{mb_tpbc}.spm.tools.cat.tools.longBiasCorr.prefix ) + matlabbatch{mbi}.cfg_basicio.file_dir.file_ops.file_move.files(c) = cfg_dep('Segment: Longitudinal Bias Corrected',... + substruct('.','val', '{}',{mb_tpbc}, '.','val', '{}',{1}, '.','val', '{}',{1}),... + substruct('.','bc', '()',{':'})); c = c+1; + end + + % remove surfaces of average data + if longmodel && surfaces + matlabbatch{mbi}.cfg_basicio.file_dir.file_ops.file_move.files(c) = cfg_dep('CAT12: Segmentation (current release): Left Central Surface',... + substruct('.','val', '{}',{mb_catavg}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}),... + substruct('()',{1}, '.','lhcentral', '()',{':'})); c = c+1; + matlabbatch{mbi}.cfg_basicio.file_dir.file_ops.file_move.files(c) = cfg_dep('CAT12: Segmentation (current release): Left Sphere Surface',... + substruct('.','val', '{}',{mb_catavg}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}),... + substruct('()',{1}, '.','lhsphere', '()',{':'})); c = c+1; + matlabbatch{mbi}.cfg_basicio.file_dir.file_ops.file_move.files(c) = cfg_dep('CAT12: Segmentation (current release): Left Spherereg Surface',... + substruct('.','val', '{}',{mb_catavg}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}),... + substruct('()',{1}, '.','lhspherereg', '()',{':'})); c = c+1; + matlabbatch{mbi}.cfg_basicio.file_dir.file_ops.file_move.files(c) = cfg_dep('CAT12: Segmentation (current release): Left Thickness',... + substruct('.','val', '{}',{mb_catavg}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}),... + substruct('()',{1}, '.','lhthickness', '()',{':'})); c = c+1; + matlabbatch{mbi}.cfg_basicio.file_dir.file_ops.file_move.files(c) = cfg_dep('CAT12: Segmentation (current release): Left Pbt',... + substruct('.','val', '{}',{mb_catavg}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}),... + substruct('()',{1}, '.','lhpbt', '()',{':'})); c = c+1; + matlabbatch{mbi}.cfg_basicio.file_dir.file_ops.file_move.files(c) = cfg_dep('CAT12: Segmentation (current release): Right Central Surface',... + substruct('.','val', '{}',{mb_catavg}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}),... + substruct('()',{1}, '.','rhcentral', '()',{':'})); c = c+1; + matlabbatch{mbi}.cfg_basicio.file_dir.file_ops.file_move.files(c) = cfg_dep('CAT12: Segmentation (current release): Right Sphere Surface',... + substruct('.','val', '{}',{mb_catavg}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}),... + substruct('()',{1}, '.','rhsphere', '()',{':'})); c = c+1; + matlabbatch{mbi}.cfg_basicio.file_dir.file_ops.file_move.files(c) = cfg_dep('CAT12: Segmentation (current release): Right Spherereg Surface',... + substruct('.','val', '{}',{mb_catavg}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}),... + substruct('()',{1}, '.','rhspherereg', '()',{':'})); c = c+1; + matlabbatch{mbi}.cfg_basicio.file_dir.file_ops.file_move.files(c) = cfg_dep('CAT12: Segmentation (current release): Right Thickness',... + substruct('.','val', '{}',{mb_catavg}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}),... + substruct('()',{1}, '.','rhthickness', '()',{':'})); c = c+1; + matlabbatch{mbi}.cfg_basicio.file_dir.file_ops.file_move.files(c) = cfg_dep('CAT12: Segmentation (current release): Right Pbt',... + substruct('.','val', '{}',{mb_catavg}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}),... + substruct('()',{1}, '.','rhpbt', '()',{':'})); c = c+1; + end + + if prepavg + matlabbatch{mbi}.cfg_basicio.file_dir.file_ops.file_move.files(c) = cfg_dep('Spatially adaptive non-local means (SANLM) denoising filter: SANLM Images', ... + substruct('.','val', '{}',{mb_sanlm}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), ... + substruct('.','files', '()',{':'})); c = c+1; + end + + % remove timepoint deformations + if longTPM + matlabbatch{mbi}.cfg_basicio.file_dir.file_ops.file_move.files(c) = cfg_dep('Longitudinal TPM creation: Longitudinal TPMs',... + substruct('.','val', '{}',{mb_tpm}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}),... + substruct('.','tpm', '()',{':'})); c = c+1; + end + + % remove temporary shooting files + if longmodel>1 + matlabbatch{mbi}.cfg_basicio.file_dir.file_ops.file_move.files(c) = cfg_dep('Run Shooting (create Templates): Template (0)',... + substruct('.','val', '{}',{mb_GS}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}),... + substruct('.','template', '()',{':'})); c = c+1; + matlabbatch{mbi}.cfg_basicio.file_dir.file_ops.file_move.files(c) = cfg_dep('Run Shooting (create Templates): Velocity Fields',... + substruct('.','val', '{}',{mb_GS}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}),... + substruct('.','vel', '()',{':'})); c = c+1; + matlabbatch{mbi}.cfg_basicio.file_dir.file_ops.file_move.files(c) = cfg_dep('Run Shooting (create Templates): Deformation Fields',... + substruct('.','val', '{}',{mb_GS}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}),... + substruct('.','def', '()',{':'})); c = c+1; + matlabbatch{mbi}.cfg_basicio.file_dir.file_ops.file_move.files(c) = cfg_dep('Run Shooting (create Templates): Jacobian Fields',... + substruct('.','val', '{}',{mb_GS}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}),... + substruct('.','jac', '()',{':'})); c = c+1; + + for ci = 1:2 % for shooting we only have GM/WM + matlabbatch{mbi}.cfg_basicio.file_dir.file_ops.file_move.files(c) = cfg_dep('Resize images: Resized', ... + substruct('.','val', '{}',{mb_lr(ci)}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), ... + substruct('.','res', '()',{':'})); c = c+1; + end + + if longmodel==2 % temporary warped segmentations + for ci = 1:2 + write_CSF + matlabbatch{mbi}.cfg_basicio.file_dir.file_ops.file_move.files(c) = cfg_dep('Apply deformations (many subjects): All Output Files',... + substruct('.','val', '{}',{mb_aGS(ci)}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}),... + substruct('.','vfiles')); c = c+1; + end + end + end + % final command of this batch + if c > 1 % if there is something to delete + matlabbatch{mbi}.cfg_basicio.file_dir.file_ops.file_move.action.delete = false; + end + + +end +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_main_updateSPM.m",".m","47900","957","function [Ysrc,Ycls,Yb,Yb0,Yy,job,res,trans,T3th,stime2] = cat_main_updateSPM(Ysrc,P,Yy,tpm,job,res,stime,stime2) +% ______________________________________________________________________ +% Update SPM preprocessing. +% Subfunction of cat_main. +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + global cat_err_res; + + res.AffineSPM = res.Affine; + + clsint = @(x) round( sum(res.mn(res.lkp==x) .* res.mg(res.lkp==x)') * 10^5)/10^5; + + [pth,nam] = spm_fileparts(res.image0(1).fname); %#ok % original + + % RD202211: Added SPM based detection of high intensity backgronds of MP2Rage scans + %res.isMP2RAGE = min( res.mn(res.lkp==3 & res.mg'>0.2) ) < min( res.mn(res.lkp==max(res.lkp) & res.mg'>0.2) ); + % CG20230227 disabled detection because it was not working properly + res.isMP2RAGE = false; + + % voxel size parameter + vx_vol = sqrt(sum(res.image(1).mat(1:3,1:3).^2)); % voxel size of the processed image + vx_vol0 = sqrt(sum(res.image0(1).mat(1:3,1:3).^2)); + vx_volp = prod(vx_vol)/1000; + + %d = res.image(1).dim(1:3); + + % some reports + for i=1:size(P,4), res.ppe.SPMvols0(i) = cat_stat_nansum(single(P(:,:,:,i)),0)/255 .* prod(vx_vol) / 1000; end + + + try + if job.extopts.ignoreErrors > 2 % && ~( ( clsint(3) < clsint(1) ) && ( clsint(1) < clsint(2) ) ) % ~T1 + error('cat_main_updateSPM:runbackup','Test backup function.'); + end + + stime2 = cat_io_cmd(' Update segmentation','g5','',job.extopts.verb-1,stime2); + + % Create brain mask based on the the TPM classes + % cleanup with brain mask - required for ngaus [1 1 2 4 3 2] and R1/MP2Rage like data + % YbA = zeros(d,'single'); + Vb = tpm.V(1); Vb.pinfo(3) = 0; Vb.dt=16; + Vb.dat = single(exp(tpm.dat{1}) + exp(tpm.dat{2}) + exp(tpm.dat{3})); + YbA = cat_vol_sample(res.tpm(1),Vb,Yy,1); + %for z=1:d(3) + % YbA(:,:,z) = spm_sample_vol(Vb,double(Yy(:,:,z,1)),double(Yy(:,:,z,2)),double(Yy(:,:,z,3)),1); + % end + if (isfield(job,'useprior') && ~isempty(job.useprior) ), bth = 0.5; else, bth = 0.1; end + if round(max(YbA(:))/Vb.pinfo(1)), YbA=YbA>bth*Vb.pinfo(1); else, YbA=YbA>bth; end + % add some distance around brainmask (important for bias!) + YbA = YbA | cat_vol_morph(YbA & sum(P(:,:,:,1:2),4)>4 ,'dd',2.4,vx_vol); + + + if size(P,4)==3 + %% Skull-stripping of post mortem data (RD202108). + % Here we only have 3 classes. GM, WM and a combined CSF/background + % class and we use the GM/WM block to create a rough brain mask that + % is used to artificially seperate between ""CSF"" and background to + % obtain some useful CSF volume values and avoid preprocessing + % problems by other structures. + Yb = smooth3( sum(P(:,:,:,1:2),4) ) > 64; % initial mask + Yb = cat_vol_morph( Yb , 'ldo' , 2 , vx_vol ); % (light) opening to remove menignes and (large) unconnected components + Yb = cat_vol_morph( Yb , 'dc' , 10 , vx_vol ); % major closing to include internal CSF + Yb = cat_vol_morph( Yb , 'ldo' , 5 , vx_vol ); % final opening to remove further menignes + Yb = cat_vol_morph( Yb , 'dd' , 2 , vx_vol ); % add one mm to avoid to hard skull-strippings that could trouble thickness estimation + Yb = cat_vol_ctype(Yb); % convert to uint8 like P + for i=1:3, P(:,:,:,i) = P(:,:,:,i) .* Yb; end % apply masking for major tissues ... + P(:,:,:,4) = cat_vol_ctype((1 - Yb) * 255); % ... and create a new background class + Yb = Yb>0.5; % convert to logical + postmortem = 1; + else + Yb = smooth3( sum(P(:,:,:,1:3),4) ) > 128; + postmortem = 0; + end + + %% correction of CSF-GM-WM PVE voxels that were miss aligned to skull + % RD202006: This is a special cases observed for the thickness phantom. + % With a coronal head-masking, SPM had problems with brain PVE values + % classes that were to close to some head peaks and therefore miss + % classified in P(:,:,:,5). + % GM-WM + if size(P,4)>4 + pth = 128; + lth = min( clsint(1) , clsint(2) ); hth = max( clsint(1) , clsint(2) ); + Ycls5b = YbA & cat_vol_morph(P(:,:,:,1)>pth | P(:,:,:,2)>pth,'c') & Ysrc>lth & Ysrcpth | P(:,:,:,3)>pth,'c') & Ysrc>lth & Ysrcpth | P(:,:,:,3)>pth,'c') & Ysrc>lth & Ysrc128 , 'd'); + Ycc = P(:,:,:,3)>0 & smooth3(single(P(:,:,:,3)/255) < 0.5) & Ywd; + P(:,:,:,1) = P(:,:,:,1) + P(:,:,:,3) .* uint8( Ycc & abs(Ysrc-clsint(1))<=abs(Ysrc-clsint(2)) & ... + abs(Ysrc-clsint(1))<=abs(Ysrc-clsint(3)) & abs(Ysrc-clsint(2))<=abs(Ysrc-clsint(3)) ); + P(:,:,:,2) = P(:,:,:,2) + P(:,:,:,3) .* uint8( Ycc & abs(Ysrc-clsint(1))> abs(Ysrc-clsint(2)) & ... + abs(Ysrc-clsint(1))<=abs(Ysrc-clsint(3)) & abs(Ysrc-clsint(2))<=abs(Ysrc-clsint(3)) ); + P(:,:,:,3) = P(:,:,:,3) - P(:,:,:,3) .* uint8( Ycc ); + clear Ywd Ycc; + % RD20215: Cleanup for CSF artefacts between GM and WM (PD/T2 BWP data) + % there should be no head tissue inside the brain that can be explained by brain values + tth = [clsint(1) clsint(2) clsint(3)]; + Ycc = cat_vol_morph(YbA,'e',3) & sum( P(:,:,:,4:6) , 4 ) & ... + Ysrc>(min(tth) - mean( abs(diff(tth))) ) & Ysrc<(max(tth) + mean( abs(diff(tth)) )); + [~,Yct] = min( cat( 4 , abs(Ysrc - tth(1)) , abs(Ysrc - tth(2)) , abs(Ysrc - tth(3)) ) , [], 4); clear Ytmp + P(:,:,:,1) = P(:,:,:,1) + P(:,:,:,5) .* uint8( Ycc & Yct==1 ); + P(:,:,:,2) = P(:,:,:,2) + P(:,:,:,5) .* uint8( Ycc & Yct==2 ); + P(:,:,:,3) = P(:,:,:,3) + P(:,:,:,5) .* uint8( Ycc & Yct==3 ); + P(:,:,:,5) = P(:,:,:,5) - P(:,:,:,5) .* uint8( Ycc ); + clear Ycc tth Yct; + end + end + + + if isfield(job.extopts,'inv_weighting') && job.extopts.inv_weighting && cat_stat_nanmedian(Ysrc(P(:,:,:,2)>128)) > cat_stat_nanmedian(Ysrc(P(:,:,:,3)>128)) + %% RD202501: added extra cleanup to avoid blood-vessel-like structures in PD/FLAIR + stime2 = cat_io_cmd(' Update PD input','g5','',job.extopts.verb-1,stime2); + + + %% correction of GM-CSF partial volume effects that are similar to blood vessels + Yw = single(P(:,:,:,2))/255; Ywo=Yw; + Yww = cat_vol_approx(cat_vol_localstat(Yw .* (Yw>.3),Yw>.3,1,3),'rec'); Yw = Yw ./ Yww; % correct TPM bias + Yw(smooth3(Yw)<.15) = 0; + Yw = min(Yw,cat_vol_median3(Yw ,Yb | Yw>0,true(size(Ysrc)),0.7)); + Yww = cat_vol_approx(cat_vol_localstat(Yw .* (Yw>.3),Yw>.3,1,3),'rec'); Yw = Yw ./ Yww; % correct TPM bias + Yw(smooth3(Yw)<.15) = 0; + Yw = min(Yw,cat_vol_median3(Yw ,Yb | Yw>0,true(size(Ysrc)),0.5)); + for i=.9:-.2:.2, Yw(cat_vol_morph(Yw>i,'l',[1000,2])==0 & Yw>i)=0; end % remove smaller objects + Ymsk = smooth3(Yw)>.3; + Yw(Ymsk) = max(Ywo(Ymsk),Yw(Ymsk)); + Yw = Yw*0.3 + 0.7*Ywo; + Ydw = Yw - Ywo; + + P(:,:,:,1) = cat_vol_ctype(single(P(:,:,:,1)) + min(0,-Ydw)*255); + P(:,:,:,2) = cat_vol_ctype(single(P(:,:,:,2)) + Ydw*255); + P(:,:,:,3) = cat_vol_ctype(single(P(:,:,:,3)) - min(0,Ydw)*255); + clear Yw Yw2 Ydw Ywo; + + + % additiuonal bias correction + Yp0 = (single(P(:,:,:,1))*3/255 + single(P(:,:,:,2))*2/255 + single(P(:,:,:,3))/255) .* Yb; + Yi = (Ysrc ./ max(eps,Yp0)); + Yi(isnan(Yi) | isinf(Yi) | ( Yi>2*cat_stat_nanmedian(Yi(Yb))) | ( Yi<0.25*cat_stat_nanmedian(Yi(Yb))) ) = 0; + Yi = cat_vol_median3(Yi,Yi>0,Yi>0); + Yw = cat_vol_approx(Yi,'rec'); + Yw = cat_vol_smooth3X(Yw,2); + Yw = Yw ./ mean(Yw(Yb)); + Ysrc = Ysrc ./ Yw; + clear Yi Yw Yp0; + end + + + % clear WM segment + Ywm = P(:,:,:,2) > 128; + Ybe = YbA & ~cat_vol_morph(YbA,'de',8/mean(vx_vol)); + Ywm = cat_vol_morph(Ywm,'l',[100 0.1 ]); + P(:,:,:,min(size(P,4),5)) = P(:,:,:,min(size(P,4),5)) + P(:,:,:,2) .* uint8( Ybe & ~Ywm ) / 2; + P(:,:,:,2) = P(:,:,:,2) - P(:,:,:,2) .* uint8( Ybe & ~Ywm ) / 2; + clear Ywm be; + + %% transfer tissue outside the brain mask to head ... + % RD 201807: I am not sure if this is a good idea. Please test this with children! + for i=1:3 + P(:,:,:,4) = cat_vol_ctype(single(P(:,:,:,4)) + single(P(:,:,:,i)) .* single(~YbA)); + P(:,:,:,i) = cat_vol_ctype(single(P(:,:,:,i)) .* single(YbA)); + end + + + % RD202006: Correct background (from cat_run_job) + % RD202007: The noisy zeros background in resliced data (e.g. long avg) + % can possibly cause problems? - no + if isfield(res,'bge') + P(:,:,:,end) = max( cat_vol_ctype( res.bge * 255 ) , P(:,:,:,end) ); + for i=1:size(P,4)-1, P(:,:,:,i) = P(:,:,:,i) .* cat_vol_ctype(1 - res.bge); end + end + + %% + % Cleanup for high resolution data + % Although the old cleanup is very slow for high resolution data, the + % reduction of image resolution removes spatial segmentation information. + % RD202008: This operation has to be done in high-resolution and it is + % maybe better to avoid the older gcw cleaning step the is + % very very slow. + if job.opts.redspmres==0 % already done in case of redspmres + if max(vx_vol)<1.5 && mean(vx_vol)<1.3 + for i=1:size(P,4), [Pc1(:,:,:,i),BB] = cat_vol_resize(P(:,:,:,i),'reduceBrain',vx_vol,4,YbA); end %#ok + Pc1 = cat_main_clean_gwc(Pc1,max(1,min(2,job.extopts.cleanupstr*2)) / mean(vx_vol)); + Ybb = ones(size(YbA),'uint8'); Ybb(BB.BB(1):BB.BB(2),BB.BB(3):BB.BB(4),BB.BB(5):BB.BB(6)) = uint8(1); + for i=1:size(P,4), P(:,:,:,i) = Ybb.*P(:,:,:,i) + cat_vol_resize(Pc1(:,:,:,i),'dereduceBrain',BB); end + clear Pc1 Ybb; + end + end + + + + %% guarantee probability + sP = (sum(single(P),4)+eps)/255; + for k1=1:size(P,4), P(:,:,:,k1) = cat_vol_ctype(single(P(:,:,:,k1))./sP); end + clear sP; + + + % Use median for WM threshold estimation to avoid problems in case of WMHs! + WMth = double(max( clsint(2) , cat_stat_nanmedian(Ysrc(P(:,:,:,2)>192)) )); + if clsint(3)>clsint(2) % invers + CMth = clsint(3); + else + CMth = min( [ clsint(1) - diff([clsint(1),WMth]) , clsint(3) ]); + end + T3th = double( [ CMth , clsint(1) , WMth]); + + + %% Some error handling + % ds('l2','',vx_vol,Ysrc./WMth,Yp0>0.3,Ysrc./WMth,Yp0,80) + Yp0 = single(P(:,:,:,3))/255/3 + single(P(:,:,:,1))/255*2/3 + single(P(:,:,:,2))/255; + if size(P,4)==4 || size(P,4)==3 || res.ppe.affreg.skullstripped + %% skull-stripped + Ybg = cat_vol_smooth3X(sum(P(:,:,:,1:2)>0,4)==0,4)>.95; + Ybg = Ysrc>=(median(Ysrc(Ybg(:))) - 2*std(Ysrc(Ybg(:)))) & ... + Ysrc<=(median(Ysrc(Ybg(:))) + 2*std(Ysrc(Ybg(:)))); + Ybx = ~cat_vol_morph(~cat_vol_morph(~Ybg,'lc'),'lc'); %clear Ybg + Yp0 = Yp0 .* Ybx; + Ysrc = Ysrc .* Ybx; + for ci = 1:(size(P,4)-1), P(:,:,:,ci) = P(:,:,:,ci) .* uint8(Ybx); end + P(:,:,:,end) = uint8(1-Ybx)*255; + end + if isfield(res,'Ylesion') && sum(res.Ylesion(:)>0) + res.Ylesion = cat_vol_ctype( single(res.Ylesion) .* (Yp0>0.2) ); + for k=1:size(P,4), Yl = P(:,:,:,k); Yl(res.Ylesion>0.5) = 0; P(:,:,:,k) = Yl; end + Yl = P(:,:,:,3); Yl(res.Ylesion>0.5) = 255; P(:,:,:,3) = Yl; clear Yl; + Yp0 = single(P(:,:,:,3))/255/3 + single(P(:,:,:,1))/255*2/3 + single(P(:,:,:,2))/255; + end + if sum(Yp0(:)>0.3)<100 + % this error often depends on a failed affine registration, where SPM + % have to find the brain in the head or background + BGth = min(cat_stat_nanmean(Ysrc( P(:,:,:,end)>128 )),clsint(6)); + HDHth = clsint(5); + HDLth = clsint(4); + clsvol = nan(1,size(P,4)); for ci=1:size(P,4), Yct = P(:,:,:,ci)>128; clsvol(ci) = sum(Yct(:))*vx_volp; end; clear Yct; + if size(P,4)==6 + error('CAT:cat_main:SPMpreprocessing:emptySegmentation', ... + sprintf(['Empty Segmentation: \n ' ... + 'Possibly the affine registration failed. %s.\n' ... + ' Tissue class: %10s%10s%10s%10s%10s%10s\n' ... + ' Rel. to image volume: %10.2f%10.2f%10.2f%10.2f%10.2f%10.2f\n' ... + ' Rel. to brain volume: %10.2f%10.2f%10.2f%10.2f%10.2f%10.2f\n' ... + ' Tissue intensity: %10.2f%10.2f%10.2f%10.2f%10.2f%10.2f'],... + spm_file('Please check image orientation and quality','link',['spm_image(''Display'', ''' res.image0.fname ''')']), ... + 'BG','CSF','GM','WM','HDH','HDL', ... + [ clsvol([6 3 1 2 4 5])/cat_stat_nansum(clsvol)*100, clsvol([6 3 1 2 4 5])/cat_stat_nansum(clsvol(1:3))*100, BGth,T3th,HDHth,HDLth])); %#ok + elseif size(P,4)==4 % skull-stripped + error('CAT:cat_main:SPMpreprocessing:emptySegmentation', ... + sprintf(['Empty Segmentation: \n ' ... + 'Possibly the affine registration failed. %s.\n' ... + ' Tissue class: %10s%10s%10s%10s\n' ... + ' Rel. to image volume: %10.2f%10.2f%10.2f%10.2f\n' ... + ' Rel. to brain volume: %10.2f%10.2f%10.2f%10.2f\n' ... + ' Tissue intensity: %10.2f%10.2f%10.2f%10.2f'],... + spm_file('Please check image orientation and quality','link',['spm_image(''Display'', ''' res.image0.fname ''')']), ... + 'BG','CSF','GM','WM', ... + [ clsvol([4 3 1 2])/cat_stat_nansum(clsvol)*100, clsvol([4 3 1 2])/cat_stat_nansum(clsvol(1:3))*100, BGth,T3th])); %#ok + else + error('CAT:cat_main:SPMpreprocessing:emptySegmentation', ['Empty Segmentation: ' ... + 'Possibly the affine registration failed. Please check image orientation.\n']); + end + end + + + + %% + Yp0(smooth3(cat_vol_morph(Yp0>0.3,'lo'))<0.5)=0; % not 1/6 because some ADNI scans have large ""CSF"" areas in the background + Yp0 = Yp0 .* cat_vol_morph(Yp0 & (Ysrc>WMth*0.05),'lc',2); + Yp0toC = @(Yp0,c) 1-min(1,abs(Yp0-c)); + + + % values are only used if errors occur + cat_err_res.init.T3th = T3th; + cat_err_res.init.subjectmeasures.vol_abs_CGW = [prod(vx_vol)/1000 .* sum(Yp0toC(Yp0(:),1)), ... CSF + prod(vx_vol)/1000 .* sum(Yp0toC(Yp0(:),2)), ... GM + prod(vx_vol)/1000 .* sum(Yp0toC(Yp0(:),3)), ... WM + prod(vx_vol)/1000 .* sum(Yp0toC(Yp0(:),4))]; % WMH + cat_err_res.init.subjectmeasures.vol_TIV = sum(cat_err_res.init.subjectmeasures.vol_abs_CGW); + cat_err_res.init.subjectmeasures.vol_rel_CGW = cat_err_res.init.subjectmeasures.vol_abs_CGW ./ ... + cat_err_res.init.subjectmeasures.vol_TIV; + [cat_err_res.init.Yp0,cat_err_res.init.BB] = cat_vol_resize(Yp0,'reduceBrain',vx_vol,2,Yp0>0.5); + cat_err_res.init.Yp0 = cat_vol_ctype(cat_err_res.init.Yp0/3*255); + clear Yp0; + + % ### This can not be reached because the mask field is removed by SPM! ### + if isfield(res,'msk') + Ybg = ~res.msk.dat; + P4 = cat_vol_ctype( single(P(:,:,:,6)) .* (Ysrc=T3th(2)) .* (Ybg<0.5) + single(P(:,:,:,5)) .* (Ybg<0.5) ); % remove air in head + P6 = cat_vol_ctype( single(sum(P(:,:,:,4:5),4)) .* (Ybg>0.5) + single(P(:,:,:,6)) .* (Ybg>0.5) ); % add objects/artifacts to background + P(:,:,:,4) = P4; + P(:,:,:,5) = P5; + P(:,:,:,6) = P6; + clear P4 P5 P6 Ybg; + end + + + + + %% Skull-Stripping + % ---------------------------------------------------------------------- + % Update Skull-Stripping 1 + % ---------------------------------------------------------------------- + stime2 = cat_io_cmd(' Update skull-stripping','g5','',job.extopts.verb-1,stime2); + if (isfield(job,'useprior') && ~isempty(job.useprior) && strcmp(job.opts.affreg,'prior') ) && ... + (isfield(res,'ppe') && ~res.ppe.affreg.highBG) + % RD202010: use longitudinal skull-stripping + [pp,ff,ee] = spm_fileparts(char(job.useprior)); + if isfield(job.output.BIDS,'BIDSyes') % I am not sure if separation is needed or if we simply try with/without mri-dir + Pavgp0 = fullfile(pp,[strrep(ff,'avg_','p0avg_'),ee]); + if ~exist(Pavgp0,'file') + Pavgp0 = fullfile(pp,'mri',[strrep(ff,'avg_','p0avg_'),ee]); + end + else + Pavgp0 = fullfile(pp,'mri',[strrep(ff,'avg_','p0avg_'),ee]); + if ~exist(Pavgp0,'file') + Pavgp0 = fullfile(pp,[strrep(ff,'avg_','p0avg_'),ee]); + end + end + + % RD20220213: + % For the development model with longitudinal TPM you may have to add the affine registration. + % However it seems that the adaption of the brainmask works quite well ... + % but maybe it is better to full deactive the skull-stripping in the + % plasticity/aging case + + % get gradient and divergence map (Yg and Ydiv) + [Ytmp,Ytmp,Yg,Ydiv] = cat_main_updateSPM_gcut0(Ysrc,P,vx_vol,T3th); clear Ytmp; %#ok + if exist(Pavgp0,'file') + % the p0avg should fit optimal + if any(vx_vol0 ~= vx_vol) % if the data was internaly resampled we have to load it via imcalc + [Vb,Yb] = cat_vol_imcalc(spm_vol(Pavgp0),spm_vol(res.image.fname),'i1',struct('interp',3,'verb',0,'mask',-1)); clear Vb; %#ok + else + Yb = spm_read_vols(spm_vol(Pavgp0)); + end + Yb = Yb > 0.5; + else + % otherwise it would be possible to use the individual TPM + % however, the TPM is more smoothed and is therefore only second choice + cat_io_addwarning('cat_main_updateSPM:miss_p0avg',sprintf('Cannot find p0avg use TPM for brainmask: \n %s\n',Pavgp0),2,[1 2]); + Yb = YbA > 0.5; + clear YbA + end + Ybb = cat_vol_ctype(cat_vol_smooth3X(Yb,0.5)*256); + + %% correct tissues + % RD20221224: Only the brainmask wasn't enough and we need to cleanup + % the segmentation also here (only for long pipeline) + % move brain tissue to head tissues or vice versa + for ti = 1:3 + if ti == 1 % GM with soft bounary to reduce meninges + Ynbm = cat_vol_ctype( single(P(:,:,:,ti)) .* (1 - max(0,2 * smooth3(Yb) - 1) ) ); + Ybm = cat_vol_ctype( single(P(:,:,:,5)) .* ( max(0,2 * smooth3(Yb) - 1) ) ); + elseif ti == 2 % WM with very soft boundary because we exptect no WM close to the skull + Ynbm = cat_vol_ctype( single(P(:,:,:,ti)) .* (1 - max(0,2 * single(Ybb)/255 - 1) ) ); + Ybm = cat_vol_ctype( single(P(:,:,:,5)) .* ( max(0,2 * single(Ybb)/255 - 1) ) ); + else % CSF with hard boundary + Ynbm = cat_vol_ctype( single(P(:,:,:,ti)) .* (1 - Yb) ); + Ybm = cat_vol_ctype( single(P(:,:,:,5)) .* ( Yb) ); + end + P(:,:,:,ti) = P(:,:,:,ti) - Ynbm + Ybm; + P(:,:,:,5) = P(:,:,:,5) + Ynbm - Ybm; + clear Ynbm Ybm; + end + % some extra GM cleanup for meninges + Yngm = P(:,:,:,1) .* uint8( Ybb<255 & (P(:,:,:,1)>64) & (smooth3( single(P(:,:,:,1)>64) )<0.5) ); + P(:,:,:,1) = P(:,:,:,1) - Yngm; P(:,:,:,5) = P(:,:,:,5) + Yngm; %if ~debug, clear Yngm; end + % some further hard GM cleanup ? + %{ + Yp0avg = spm_read_vols(spm_vol(Pavgp0)); + Yngm = P(:,:,:,1) .* uint8( cat_vol_morph( Yp0avg < 1.75 , 'de' , 3, vx_vol) & Yp0yvg>0 ); + P(:,:,:,1) = P(:,:,:,1) - Yngm; P(:,:,:,5) = P(:,:,:,5) + Yngm; %if ~debug, clear Yngm; end + %} + elseif postmortem + % already done + elseif size(P,4)==4 || size(P,4)==3 % skull-stripped + [~,~,Yg,Ydiv,P] = cat_main_updateSPM_skullstriped(Ysrc,P,res,vx_vol,T3th); + Yb = Ybx; Ybb = Ybx; + elseif isfield(job.extopts,'inv_weighting') && job.extopts.inv_weighting + %% estimate gradient (edge) and divergence maps + if ~exist('Ym0','var') + Ym0 = single(P(:,:,:,3))/255 + single(P(:,:,:,1))/255 + single(P(:,:,:,2))/255; + end + Ym0 = cat_vol_smooth3X(Ym0,4/mean(vx_vol)); + Yb = Ym0 > min(0.5,max(0.25, job.extopts.gcutstr)); clear Ym0 + Yb = cat_vol_morph(cat_vol_morph(Yb,'lo'),'c'); + + %% create brain level set map (from cat_main_APRG) + Yc = single(P(:,:,:,3))/255; + + % Ym .. combination of brain tissue and CSF that is further corrected + % for noise (median) and smoothness (Laplace) and finally + % threshholded + Ym = min(1,Yc + single(P(:,:,:,1))/255 + single(P(:,:,:,2))/255 + Yb); + Ym = cat_vol_median3(Ym,Ym>0 & Ym<1); % remove noise + % region-growing + Ym2 = Ym; Ym2(Ym2==0)=nan; + [Ym2,YD] = cat_vol_downcut(single(Ym2>0.99),Ym2,0.01); clear Ym2; %#ok + Ym(YD>400/mean(vx_vol))=0; clear YD; + Ym(cat_vol_morph(Ym>0.95,'ldc',1)) = 1; + Ym(cat_vol_morph(Yb,'e') & Ym<0.9 & Yc<0.25) = 0; + Ym = Ym .* cat_vol_morph(Ym>0.5,'ldo',2); % remove extensions (BV, eye) + Ym = cat_vol_laplace3R(Ym,Ym>0.1 & Ym<0.9,0.2); % smooth mask + Ym = cat_vol_laplace3R(Ym,Ym<0.25,0.2); + Ym(cat_vol_morph(Yb,'e') & Ym<0.9 & Yc<0.25) = 0; + + cutstr = min(0.5,max(0.25, job.extopts.gcutstr)); + Ybb = cat_vol_ctype( max(0,min(1,(Ym - cutstr)/(1-cutstr))) * 256); + + %% + [Ysrcb,BB] = cat_vol_resize({Ysrc},'reduceBrain',vx_vol,round(6/mean(vx_vol)),Yb); + Yg = cat_vol_grad(Ysrcb/T3th(3),vx_vol); + Ydiv = cat_vol_div(Ysrcb/T3th(3),vx_vol); + Yg = cat_vol_resize(Yg ,'dereduceBrain',BB); + Ydiv = cat_vol_resize(Ydiv ,'dereduceBrain',BB); + elseif job.extopts.gcutstr==0 + [Yb,Ybb,Yg,Ydiv] = cat_main_updateSPM_gcut0(Ysrc,P,vx_vol,T3th); + elseif job.extopts.gcutstr==2 + [Yb,Ybb,Yg,Ydiv] = cat_main_APRG(Ysrc,P,res,T3th,0); + elseif job.extopts.gcutstr>2 && job.extopts.gcutstr<3 + [Yb,Ybb,Yg,Ydiv] = cat_main_APRG(Ysrc,P,res,T3th,job.extopts.gcutstr); + else + [Yb,Ybb,Yg,Ydiv] = cat_main_updateSPM_gcutold(Ysrc,P,res,vx_vol,T3th); + end + + + + + + %% save brain mask using SPM12 segmentations for later use + if ~exist('Ym0','var') + Ym0 = single(P(:,:,:,3))/255 + single(P(:,:,:,1))/255 + single(P(:,:,:,2))/255; + end + Ym0 = cat_vol_smooth3X(Ym0,4/mean(vx_vol)); + Yb0 = (Ym0 > min(0.5,max(0.25, job.extopts.gcutstr))); clear Ym0 + Yb0 = cat_vol_morph(cat_vol_morph(Yb0,'ldo',1),'c',3); + + + + + %% RD202110: Background correction in longitidunal mode + % We observed some problems in the SPM background segmentation for + % longidutidnal processing that detected the volume of the boundary box + % whereas the real background was miss-aligned to class 5 that caused + % further problems in the LAS function that were solved too. Although + % it would be possible to adapt the SPM segmentation, eg. by adapting + % the number of gaussians per class, we decided that it is simpler and + % maybe saver to add further test in the longitudinal case, where the + % TPM should be close to the segmentation outcome. + if (isfield(job,'useprior') && ~isempty(job.useprior) ) && ... + (isfield(job,'ppe') && ~job.ppe.affreg.highBG) + % sum of all TPM classes without background + Vall = tpm.V(end); Vall.pinfo(3) = 0; Vall.dt=16; + Vall.dat = zeros(size(tpm.dat{1})); for k1 = 1:numel(tpm.dat)-1, Vall.dat = Vall.dat + single(exp(tpm.dat{k1})); end + Yall = cat_vol_sample(res.tpm(1),Vall,Yy,1); + + % backgound class + Ybg = 1 - Yall; clear Yall Vall; + + % estimate error and do correction + rmse = @(x,y) mean( (x(:) - y(:)).^2 ).^0.5; + % the TPM BG may be smaller due to the limited overlap and we need a + % higher threshold to avoid unnecessary background corrections + TPisSmaller = ( sum(sum(sum(single(P(:,:,:,end))/255))) - sum(Ybg(:))) < 0; + if rmse(Ybg,single(P(:,:,:,end))/255) > 0.3 + 0.2*TPisSmaller % just some threshold (RD20220103: adjusted by TPisSmaller) + % setup new background + Ynbg = Ybg>0.5 | P(:,:,:,end)>128; + Ynbg = cat_vol_morph(Ynbg,'dc',5,vx_vol); + Ynbg = uint8( 255 .* smooth3(Ynbg) ); + + % correct classes + for k1 = 1:size(P,4)-1, P(:,:,:,k1) = P(:,:,:,k1) - min(P(:,:,:,k1),Ynbg); end + P(:,:,:,end) = max( Ynbg , P(:,:,:,end) ); + clear Ynbg; + + % normalize all classes + sP = (sum(single(P),4)+eps)/255; + for k1=1:size(P,4), P(:,:,:,k1) = cat_vol_ctype(single(P(:,:,:,k1))./sP); end + clear sP; + + cat_io_addwarning('cat_main_updateSPM:ReplacedLongBackground','Detected and corrected inadequate background \\nsegmentation in longitudinal mode.',0,[1 2]); + end + clear Ybg; + end + + + %% + stime2 = cat_io_cmd(' Update probability maps','g5','',job.extopts.verb-1,stime2); + if ~(any(sign(diff(T3th))==-1)) && ... + ~( (isfield(job,'useprior') && ~isempty(job.useprior) ) && ... % no single longitudinal timepoint + (isfield(res,'ppe') && ~res.ppe.affreg.highBG) ) + %% Update probability maps + % background vs. head - important for noisy backgrounds such as in MT weighting + if size(P,4)==4 || size(P,4)==3 % skull-stripped + Ybg = ~Yb; + else + if sum(sum(sum(P(:,:,:,6)>240 & Ysrc10000 + Ybg = P(:,:,:,6); + [Ybgr,Ysrcr,resT2] = cat_vol_resize({Ybg,Ysrc},'reduceV',vx_vol,2,32); + Ybgrth = max(cat_stat_nanmean(Ysrcr(Ybgr(:)>128)) + 2*std(Ysrcr(Ybgr(:)>128)),T3th(1)); + Ybgr = cat_vol_morph(cat_vol_morph(cat_vol_morph(Ybgr>128,'d') & Ysrcr8 & Ysrc10000 + % RD202010 bad SPM background + Ybg = cat_vol_smooth3X( single(P(:,:,:,6)) * 240 ,2); + [Ybgr,Ysrcr,resT2] = cat_vol_resize({Ybg,Ysrc},'reduceV',vx_vol,2,32); + Ybgrth = max(cat_stat_nanmean(Ysrcr(Ybgr(:)>128)) + 2*std(Ysrcr(Ybgr(:)>128)),T3th(1)); + Ybgr = cat_vol_morph(cat_vol_morph(cat_vol_morph(Ybgr>128,'d') & Ysrcr=T3th(2)) .* (Ybg<0.5) + single(P(:,:,:,5)) .* (Ybg<0.5) ); % remove air in head + P6 = cat_vol_ctype( single(sum(P(:,:,:,4:5),4)) .* (Ybg>0.5) + single(P(:,:,:,6)) .* (Ybg>0.5) ); % add objects/artifacts to background + P(:,:,:,4) = P4; + P(:,:,:,5) = P5; + P(:,:,:,6) = P6; + clear P4 P5 P6; + end + + % correct probability maps to 100% + sumP = cat_vol_ctype(255 - sum(P(:,:,:,1:6),4)); + P(:,:,:,1) = P(:,:,:,1) + sumP .* uint8( Ybg<0.5 & Yb & Ysrc>cat_stat_nanmean(T3th(1:2)) & Ysrc=cat_stat_nanmean(T3th(2:3))); + P(:,:,:,3) = P(:,:,:,3) + sumP .* uint8( Ybg<0.5 & Yb & Ysrc<=cat_stat_nanmean(T3th(1:2))); + P(:,:,:,4) = P(:,:,:,4) + sumP .* uint8( Ybg<0.5 & ~Yb & Ysrc=T3th(2)); + P(:,:,:,6) = P(:,:,:,6) + sumP .* uint8( Ybg>=0.5 & ~Yb ); + clear Ybg sumP; + + + %% head to WM + % Under-correction of strong inhomogeneities in high field scans + % (>1.5T) can cause miss-alignments of the template and therefore + % miss classifications of the tissues that finally avoid further + % corrections in by LAS. + % Typically the alignment failed in this cases because the high + % intensities next to the head that were counted as head and not + % corrected by SPM. + % e.g. HR075, Magdeburg7T, SRS_SRS_Jena_DaRo81_T1_20150320-191509_MPR-08mm-G2-bw330-nbc.nii, ... + Ywm = single(P(:,:,:,2)>128 & Yg<0.3 & Ydiv<0.03); Ywm(Ybb<128 | (P(:,:,:,1)>128 & abs(Ysrc/T3th(3)-2/3)<1/3) | Ydiv>0.03) = nan; + [Ywm1,YD] = cat_vol_downcut(Ywm,1-Ysrc/T3th(3),0.02); Yb(isnan(Yb))=0; Ywm(YD<300)=1; Ywm(isnan(Ywm))=0; clear Ywm1 YD; %#ok + Ywmc = uint8(smooth3(Ywm)>0.7); + Ygmc = uint8(cat_vol_morph(Ywmc,'d',2) & ~Ywmc & Ydiv>0 & Yb & cat_vol_smooth3X(Yb,8)<0.9); + P(:,:,:,[1,3:6]) = P(:,:,:,[1,3:6]) .* repmat(1-Ywmc,[1,1,1,5]); + P(:,:,:,2:6) = P(:,:,:,2:6) .* repmat(1-Ygmc,[1,1,1,5]); + P(:,:,:,1) = max(P(:,:,:,1),255*Ygmc); + P(:,:,:,2) = max(P(:,:,:,2),255*Ywmc); + Yp0 = single(P(:,:,:,3))/255/3 + single(P(:,:,:,1))/255*2/3 + single(P(:,:,:,2))/255; + clear Ygmc Ywmc; + + + %% head to GM ... important for children + [Ywmr,Ybr,resT2] = cat_vol_resize({Ywm,Yb},'reduceV',vx_vol,2,32); + Ygm = cat_vol_morph(Ywmr>0.5,'d',3) & (cat_vol_morph(~Ybr,'d',3) | cat_vol_morph(Ybr,'d',1)); clear Ybr Ywmr; % close to the head + Ygm = cat_vol_resize(single(Ygm),'dereduceV',resT2)>0.5; + Ygm = Ygm & Yp0<2/3 & Yb & Yg64)) & Ydiv64)); % add GM with low SPM prob ... + Ygm = Ygm & (Ysrc>cat_stat_nansum(T3th(1:2).*[0.5 0.5])) & (Ysrc T3th(1) - min( abs( [ diff(T3th(1:2)) diff(T3th(1:2:3)) ] ))/2 ) & ... + (Ysrc > T3th(1) + min( abs( [ diff(T3th(1:2)) diff(T3th(1:2:3)) ] ))/2 ) & ... + Yb & sum(P(:,:,:,4:2:end),4)>0 & sum(P(:,:,:,1:3),4)<250 & ... + Yg64)*1.5); % & Ydiv64)); + Ycsf(smooth3(Ycsf)<0.5)=0; + for pi=4:2:size(P,4), P(:,:,:,pi) = P(:,:,:,pi) .* cat_vol_ctype(1-Ycsf); end + P(:,:,:,3) = cat_vol_ctype(single(P(:,:,:,3)) + 255*single(Ycsf)); + clear Yg; + + %% remove brain tissues outside the brain mask ... + % tissues > skull (within the brain mask) + if ~(size(P,4)==4 || size(P,4)==3 || res.ppe.affreg.skullstripped) + Yhdc = uint8(smooth3( Ysrc/T3th(3).*(Ybb>cat_vol_ctype(0.2*255)) - Yp0 )>0.5); + sumP = sum(P(:,:,:,1:3),4); + P(:,:,:,4) = cat_vol_ctype( single(P(:,:,:,4)) + sumP .* ((Ybb<=cat_vol_ctype(0.05*255)) | Yhdc ) .* (Ysrc=T3th(2))); + P(:,:,:,1:3) = P(:,:,:,1:3) .* repmat(uint8(~(Ybb<=cat_vol_ctype(0.05*255)) | Yhdc ),[1,1,1,3]); + end + clear sumP Yp0 Yhdc; + end + clear Ybb; + + sP = (sum(single(P),4)+eps)/255; + for k1=1:size(P,4), P(:,:,:,k1) = cat_vol_ctype(single(P(:,:,:,k1))./sP); end + + + + + %% MRF + % Used spm_mrf help and tested the probability TPM map for Q without good results. + nmrf_its = 0; % 10 iterations better to get full probability in thin GM areas + spm_progress_bar('init',nmrf_its,['MRF: Working on ' nam],'Iterations completed'); + if isfield(res,'mg'), Kb = max(res.lkp); else, Kb = size(res.intensity(1).lik,2); end + G = ones([Kb,1],'single'); + vx2 = single(sum(res.image(1).mat(1:3,1:3).^2)); + % P = zeros([d(1:3),Kb],'uint8'); + % P = spm_mrf(P,Q,G,vx2); % init: transfer data from Q to P + if 0 + %% use TPM as Q + Q = zeros(size(P),'uint8'); + for di=1:6 + vol = cat_vol_ctype(spm_sample_vol(tpm.V(di),... + double(Yy(:,:,:,1)),double(Yy(:,:,:,2)),double(Yy(:,:,:,3)),0)*255,'uint8'); + Q(:,:,:,di) = reshape(vol,d); + end + end + for iter=1:nmrf_its + P = spm_mrf(P,single(P),G,vx2); % spm_mrf(P,Q,G,vx2); + spm_progress_bar('set',iter); + end + + % update segmentation for error report + Yp0 = single(P(:,:,:,3))/255/3 + single(P(:,:,:,1))/255*2/3 + single(P(:,:,:,2))/255; + [cat_err_res.init.Yp0,cat_err_res.init.BB] = cat_vol_resize(Yp0,'reduceBrain',vx_vol,2,Yp0>0.5); + cat_err_res.init.Yp0 = cat_vol_ctype(cat_err_res.init.Yp0/3*255); + + spm_progress_bar('clear'); + Ycls = cell(1,size(P,4)); + for k1=1:size(P,4) + Ycls{k1} = P(:,:,:,k1); + end + clear Q P q q1 Coef b cr N lkp n wp M k1 + + + if job.extopts.verb>2 + % save information for debugging and OS test + % input variables + bias corrected, bias field, class image + % strong differences in bias fields can be the result of different + % registration > check 'res.image.mat' and 'res.Affine' + [~, reportfolder] = cat_io_subfolders(res.image(1).fname,job); + [pth,nam] = spm_fileparts(res.image0(1).fname); + tpmci = 1; + tmpmat = fullfile(pth,reportfolder,sprintf('%s_%s%02d%s.mat',nam,'write',tpmci,'postbias')); + save(tmpmat,'res','tpm','job','Ysrc','Ycls'); + end + + catch e + % just try to translate the input to the output + % [Ysrc,Ycls,Yb,Yb0,job,res,T3th,stime2] = cat_main_updateSPM(Ysrc,P,Yy,tpm,job,res,stime,stime2) + + if job.extopts.ignoreErrors < 2 + rethrow(e) + else + % print that that backup function is used + % print the error message as warning in the developer mode + cat_io_addwarning('cat_main_updateSPM:runbackup','IgnoreErrors: Run backup function',1) + if ~strcmp(e.identifier, 'cat_main_updateSPM:runbackup') + fprintf('\n'); + warning(e.message); + stime2 = cat_io_cmd(' ','g5','',job.extopts.verb-1); + end + end + + % voxel size + vx_vol = sqrt(sum(res.image(1).mat(1:3,1:3).^2)); + + + % correct background + if isfield(res,'bge') + P(:,:,:,end) = max( cat_vol_ctype( res.bge * 255 ) , P(:,:,:,end) ); + for i=1:size(P,4)-1, P(:,:,:,i) = P(:,:,:,i) .* cat_vol_ctype(1 - res.bge); end + end + + + % initial definition for threshold function + Ycls = cell(1,size(P,4)); + Yb0 = cat_vol_smooth3X( sum(P(:,:,:,1:3),4), 4/mean(vx_vol)) > 128; + Yb0 = cat_vol_morph( cat_vol_morph( Yb0 , 'do' ,3,vx_vol) , 'lc' , 2,vx_vol); + for k1 = 1:size(P,4) + if k1<4 + Ycls{k1} = P(:,:,:,k1) .* uint8(Yb0); + else + Ycls{k1} = P(:,:,:,k1) .* uint8(~Yb0); + end + end + clear Yb0; + + + % T3th - brain tissue thresholds + % Use median for WM threshold estimation to avoid problems in case of WMHs! + if ~exist('T3th','var') || any( isnan(T3th) ) + clsint = @(x) cat_stat_nanmedian(Ysrc(Ycls{x}>128)); + clsints = @(x) round( sum(res.mn(res.lkp==x) .* res.mg(res.lkp==x)') * 10^5)/10^5; + T3th = [clsint(3) clsint(1) clsint(2)]; + for i=1:3, if isnan(T3th(i)), T3th(i) = clsints(i); end; end + end + + + % Yb - skull-stripping + if ~exist('Yb','var') + if (isfield(job,'useprior') && ~isempty(job.useprior) ) && ... + (isfield(res,'ppe') && ~res.ppe.affreg.highBG) + % use longitudinal TPM + [Ytmp,Ytmp,Yg,Ydiv] = cat_main_updateSPM_gcut0(Ysrc,P,vx_vol,T3th); clear Ytmp; %#ok + Yb = YbA > 0.5; + clear YbA + elseif size(P,4)==4 || size(P,4)==3 + cat_io_cprintf('warn','\n Skull-stripped input - refine original mask ') + [Yb,Ybb,Yg,Ydiv,P] = cat_main_updateSPM_skullstriped(Ysrc,P,res,vx_vol,T3th); %#ok + clear Ybb Yg Ydiv + elseif isfield(job.extopts,'inv_weighting') && job.extopts.inv_weighting + Ym0 = single(P(:,:,:,3))/255 + single(P(:,:,:,1))/255 + single(P(:,:,:,2))/255; + Ym0 = cat_vol_smooth3X(Ym0,4/mean(vx_vol)); + Yb = Ym0 > min(0.5,max(0.25, job.extopts.gcutstr)); clear Ym0 + Yb = cat_vol_morph(cat_vol_morph(Yb,'lo'),'c'); + else + try + Yb = cat_main_APRG(Ysrc,P,res,double(T3th)); + catch + try + cat_io_addwarning('cat_main_updateSPM:runbackup:APRGerr','IgnoreErrors: cat_main_updateSPM APRG failed - run GCUT function.\n',1); + Yb = cat_main_updateSPM_gcut0(Ysrc,P,vx_vol,T3th); + catch + cat_io_addwarning('cat_main_updateSPM:runbackup:GCUTerr','IgnoreErrors: cat_main_updateSPM GCUT failed - use SPM brain mask.\n',1); + Yb = cat_vol_morph( sum(P(:,:,:,1:3) > 128,4) , 'lc' , 2); + end + end + end + end + + % Yb0 - save brain mask using SPM12 segmentations for later use + if ~exist('Yb0','var') + Ym0 = single(P(:,:,:,3))/255 + single(P(:,:,:,1))/255 + single(P(:,:,:,2))/255; + Yb0 = (Ym0 > min(0.5,max(0.25, job.extopts.gcutstr))); + Yb0 = cat_vol_morph(cat_vol_morph(Yb0,'lo'),'c'); + clear Ym0 + end + + % final definition with corrected probability maps + Ycls = cell(1,size(P,4)); + Ysb = zeros(size(Ysrc),'single'); + Ysnb = zeros(size(Ysrc),'single'); + for k1 = 1:size(P,4) + if k1<4 + Ycls{k1} = P(:,:,:,k1) .* uint8(Yb); + Ysb = Ysb + single(Ycls{k1}); + else + Ycls{k1} = P(:,:,:,k1) .* uint8(~Yb); + Ysnb = Ysnb + single(Ycls{k1}); + end + end + for k1 = 1:size(P,4) + if k1<4 + Ycls{k1}(Yb>=0.5) = cat_vol_ctype(single( (Ycls{k1}(Yb>=0.5))) ./ Ysb(Yb>=0.5) * 255 ); + else + Ycls{k1}(Yb< 0.5) = cat_vol_ctype(single( (Ycls{k1}(Yb< 0.5))) ./ Ysnb(Yb< 0.5) * 255 ); + end + end + clear Ysb Ysnb; + + end + + + %% prepared for improved partitioning - RD20170320, RD20180416 + % Update the initial SPM normalization by a fast version of Shooting + % to improve the skull-stripping, the partitioning and LAS. + % We need stong deformations in the ventricle for the partitioning + % but low deformations for the skull-stripping. Moreover, it has to + % be really fast > low resolution (3 mm) and less iterations. + % The mapping has to be done for the TPM resolution, but we have to + % use the Shooting template for mapping rather then the TPM because + % of the cat12 atlas map. + % + % #### move fast shooting to the cat_main_updateSPM function #### + % + stime2 = cat_io_cmd(sprintf(' Update registration'),'g5','',job.extopts.verb,stime2); + + res2 = res; + job2 = job; + job2.extopts.bb = 0; % registration to TPM space + job2.extopts.verb = 0; % do not display process (people would may get confused) + job2.extopts.vox = abs(res.tpm(1).mat(1)); % TPM resolution to replace old Yy + job2.extopts.reg.affreg = 2; % new final affine registration (1-GWM,2-BM,3-GM,4-WM) + if job.extopts.regstr>0 + job2.extopts.regstr = 13; % low resolution + job2.extopts.reg.nits = 8; % less iterations + %job2.extopts.shootingtpms(3:end) = []; % remove high templates, we only need low frequency corrections + % NO! This would cause problems with the interpolation + res2 = res; + res2.do_dartel = 2; % use shooting + else + fprintf('\n'); + job2.extopts.reg.iterlim = 1; % only 1-2 inner iterations + res2.do_dartel = 1; % use dartel + end + if isfield(res,'Ylesion') && sum(res.Ylesion(:)>0) + [trans,res.ppe.reginitp,res.Affine] = cat_main_registration(job2,res2,Ycls(1:3),Yy,res.Ylesion); + else + [trans,res.ppe.reginitp,res.Affine] = cat_main_registration(job2,res2,Ycls(1:3),Yy); + end + Yy2 = trans.warped.y; + + % Shooting did not include areas outside of the boundary box + % + % ### add to cat_main_registration? + % + try + Ybd = true(size(Ysrc)); Ybd(3:end-2,3:end-2,3:end-2) = 0; Ybd(~isnan(Yy2(:,:,:,1))) = 0; Yy2(isnan(Yy2))=0; + for k1=1:3 + Yy2(:,:,:,k1) = Yy(:,:,:,k1) .* Ybd + Yy2(:,:,:,k1) .* (1-Ybd); + Yy2(:,:,:,k1) = cat_vol_approx(Yy2(:,:,:,k1),'nn',vx_vol,3); + end + Yy = Yy2; + clear Yy2; + end + stime2 = cat_io_cmd(' ','g5','',job.extopts.verb-1,stime2); + fprintf('%5.0fs\n',etime(clock,stime)); + + + % some reports + for i=1:numel(Ycls), res.ppe.SPMvols1(i) = cat_stat_nansum(single(Ycls{i}(:)))/255 .* prod(vx_vol) / 1000; end + + % display some values for developers + if job.extopts.expertgui > 1 + cat_io_cprintf('blue',sprintf(' SPM volumes pre (CGW = TIV in mm%s): %7.2f +%7.2f +%7.2f = %4.0f\n',... + native2unicode(179, 'latin1'),res.ppe.SPMvols0([3 1 2]),sum(res.ppe.SPMvols0(1:3)))); + cat_io_cprintf('blue',sprintf(' SPM volumes post (CGW = TIV in mm%s): %7.2f +%7.2f +%7.2f = %4.0f\n',... + native2unicode(179, 'latin1'),res.ppe.SPMvols1([3 1 2]),sum(res.ppe.SPMvols1(1:3)))); + end + + +end +function [Yb,Ybb,Yg,Ydiv,P] = cat_main_updateSPM_skullstriped(Ysrc,P,res,vx_vol,T3th) + Yp0 = single(P(:,:,:,3))/255/3 + single(P(:,:,:,1))/255*2/3 + single(P(:,:,:,2))/255; + Yb = Yp0>=0.5/3; + Ybb = cat_vol_ctype(Yb)*255; + + P(:,:,:,6) = P(:,:,:,4); + P(:,:,:,4) = zeros(size(Ysrc),'uint8'); + P(:,:,:,5) = zeros(size(Ysrc),'uint8'); + res.lkp = [res.lkp 5 6]; + res.mn = [res.mn(1:end-1),0,0,0]; + res.mg = [res.mg(1:end-1);1;1;1]; + res.vr(1,1,numel(res.lkp)-1:numel(res.lkp)) = 0; + + [Ysrcb,BB] = cat_vol_resize(Ysrc,'reduceBrain',vx_vol,round(6/mean(vx_vol)),Yp0>1/3); clear Yp0; + Yg = cat_vol_grad(Ysrcb/T3th(3),vx_vol); + Ydiv = cat_vol_div(Ysrcb/T3th(3),vx_vol); + Yg = cat_vol_resize(Yg ,'dereduceBrain',BB); + Ydiv = cat_vol_resize(Ydiv ,'dereduceBrain',BB); +end +function [Yb,Ybb,Yg,Ydiv] = cat_main_updateSPM_gcut0(Ysrc,P,vx_vol,T3th) + % brain mask + Ym = single(P(:,:,:,3))/255 + single(P(:,:,:,1))/255 + single(P(:,:,:,2))/255; + Yb = (Ym > 0.5); + Yb = cat_vol_morph(cat_vol_morph(Yb,'lo'),'c'); + Ybb = cat_vol_ctype(cat_vol_smooth3X(Yb,2)*256); + + [Ysrcb,BB] = cat_vol_resize({Ysrc},'reduceBrain',vx_vol,round(6/mean(vx_vol)),Yb); + Yg = cat_vol_grad(Ysrcb/T3th(3),vx_vol); + Ydiv = cat_vol_div(Ysrcb/T3th(3),vx_vol); + Yg = cat_vol_resize(Yg ,'dereduceBrain',BB); + Ydiv = cat_vol_resize(Ydiv ,'dereduceBrain',BB); +end +function [Yb,Ybb,Yg,Ydiv] = cat_main_updateSPM_gcutold(Ysrc,P,res,vx_vol,T3th) +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% T1 only > remove in future if gcut is removed too! +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + clsint = @(x) round( sum(res.mn(res.lkp==x) .* res.mg(res.lkp==x)') * 10^5)/10^5; + voli = @(v) (v ./ (pi * 4./3)).^(1/3); % volume > radius + Yp0toC = @(Yp0,c) 1-min(1,abs(Yp0-c)); + + % old skull-stripping + Yp0 = single(P(:,:,:,3))/255/3 + single(P(:,:,:,1))/255*2/3 + single(P(:,:,:,2))/255; + brad = voli(sum(Yp0(:)>0.5).*prod(vx_vol)/1000); + [Ysrcb,Yp0,BB] = cat_vol_resize({Ysrc,Yp0},'reduceBrain',vx_vol,round(6/mean(vx_vol)),Yp0>1/3); + %Ysrcb = max(0,min(Ysrcb,max(T3th)*2)); + BGth = min(cat_stat_nanmean(Ysrc( P(:,:,:,6)>128 )),clsint(6)); + Yg = cat_vol_grad((Ysrcb-BGth)/diff([BGth,T3th(3)]),vx_vol); + Ydiv = cat_vol_div((Ysrcb-BGth)/diff([BGth,T3th(3)]),vx_vol); + Ybo = cat_vol_morph(cat_vol_morph(Yp0>0.3,'lc',2),'d',brad/2/mean(vx_vol)); + BVth = diff(T3th(1:2:3))/abs(T3th(3))*1.5; + RGth = double(diff(T3th(2:3))/abs(T3th(3))*0.1); + Yb = single(cat_vol_morph((Yp0>1.9/3) | (Ybo & Ysrcb>mean(T3th(2)) & ... + Ysrcbcat_stat_nanmean(T3th(3)*1.2) | Yg>BVth))=nan; + [Yb1,YD] = cat_vol_downcut(Yb,Ysrcb/T3th(3),RGth); clear Yb1; Yb(isnan(Yb))=0; Yb(YD<400/mean(vx_vol))=1; clear YD; %#ok + Yb(smooth3(Yb)<0.5)=0; Yb = single(Yb | (Ysrcb>T3th(1) & Ysrcb<1.2*T3th(3) & cat_vol_morph(Yb,'lc',4))); + + %% region-growing GM 2 + Yb(~Yb & (~Ybo | Ysrcbcat_stat_nanmean(T3th(3)*1.2) | Yg>BVth))=nan; + [Yb1,YD] = cat_vol_downcut(Yb,Ysrcb/T3th(3),RGth/2); clear Yb1; Yb(isnan(Yb))=0; Yb(YD<400/mean(vx_vol))=1; clear YD; %#ok + Yb(smooth3(Yb)<0.5)=0; Yb = single(Yb | (Ysrcb>T3th(1) & Ysrcb<1.2*T3th(3) & cat_vol_morph(Yb,'lc',4))); + + %% region-growing GM 3 + Yb(~Yb & (~Ybo | Ysrcbcat_stat_nanmean(T3th(3)*1.2) | Yg>BVth))=nan; clear Ybo; + [Yb1,YD] = cat_vol_downcut(Yb,Ysrcb/T3th(3),RGth/10); clear Yb1; Yb(isnan(Yb))=0; Yb(YD<400/mean(vx_vol))=1; clear YD; %#ok + Yb(smooth3(Yb)<0.5)=0; Yb(Yp0toC(Yp0*3,1)>0.9 & Yg<0.3 & Ysrcb>BGth & Ysrcb0,Ysrcb/T3th(3)},'reduceV',vx_vol,2,32); clear Ysrcb + Ybr = Ybr | (Ymr<0.8 & cat_vol_morph(Ybr,'lc',6)); clear Ymr; % large ventricle closing + Ybr = cat_vol_morph(Ybr,'lc',2); % standard closing + Yb = Yb | cat_vol_resize(cat_vol_smooth3X(Ybr,2),'dereduceV',resT2)>0.7; clear Ybr + Yb = smooth3(Yb)>0.5; + Ybb = cat_vol_ctype(cat_vol_smooth3X(Yb,2)*255); + Yb = cat_vol_resize(Yb , 'dereduceBrain' , BB); + Ybb = cat_vol_resize(Ybb , 'dereduceBrain' , BB); + Yg = cat_vol_resize(Yg , 'dereduceBrain' , BB); + Ydiv = cat_vol_resize(Ydiv , 'dereduceBrain' , BB); + clear Ysrcb Ybo; +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_stat_histth.m",".m","6545","188","function varargout = cat_stat_histth(src,percent,opt) +% ______________________________________________________________________ +% Remove outliers based on the histogram and replace them by the new +% limits. E.g. some MRI images have some extremely high or low values +% that can trouble other functions that try to work on the full given +% input range of the data. Removing only 0.2% of the data often often +% helps to avoid problems without removing important information. +% +% The function can also print a histogram, box- or violin plot of +% the given data (using cat_plot_boxplot) and give some basic values. +% +% [res,ths] = cat_stat_histth(src,percent,verb) +% +% src .. input data +% res .. limited input data +% ths .. estimated thresholds +% percent .. included values (default) = 0.998; +% can be defined with upper and lower limit, e.g., to be more +% aggressive in the background that has more values in general +% verb .. 0 - none +% 1 - histogram +% 2 - histogram without boundary values +% 3 - box-plot +% 4 - violin-plot +% 5 - violin- and box-plot +% +% Expert options: +% +% [res,ths] = cat_stat_histth(src,percent, opt ) +% +% opt .. structur with further fields +% .verb .. see above +% .fs .. font size +% .hbins .. bins for histogram estimation +% .vacc .. limit number of elements used in the violin plot +% e.g. vacc=100 means src(1:100:end) +% .scale .. [low high], default [] - no scaling +% update ths to opt.scale ! +% +% Examples: +% s=10; b = randn(s,s,s); cat_stat_histth(b,0.9,4); +% s=10; b = rand(s,s,s); cat_stat_histth(b,0.9,5); +% s=10; b = rand(s,s,s); cat_stat_histth(b,[0.8,0.999],5); +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + + %% check input + if nargin==0, help cat_stat_histth; return; end + if ~exist('src','var') || isempty(src) + varargout{1} = src; + varargout{2} = nan(1,2); + return; + end + + if ~exist('opt','var'), opt = struct(); end + if ~isstruct(opt) + verb = opt; clear opt; opt.verb = verb; + end + def.verb = 0; + def.fs = 16; + def.hbins = 10000; + def.vacc = max(1,min(100000,round(numel(src)/1000))); % reduce elements in violin plot + def.scale = []; + opt = cat_io_checkinopt(opt,def); + + tol = [ 0.002 0.002 ]; + if nargin==0, help cat_stat_histth; return; end + if ~exist('percent','var') || isempty(percent) + tol = [ 0.002 0.002 ]; + elseif percent(1) == 0 + tol = [ 0 0 ]; + else + if numel(percent)==1, percent(2) = percent(1); end + for pi = 1:2 + if percent(pi)<=1 + tol(pi) = 1 - percent(pi); + elseif percent(pi)<=100 + tol(pi) = 1 - percent(pi)/100; + else + error('cat_stat_histth:percent','Percent has to be in the range of 1 to 100'); + end + end + end + + if ~isreal(src) + % RD202004: This should not happen but it does in surprise some chimp + % images with strong negative intensities. At some point in + % cat_vol_sanlm or here the image becomes complex and create + % an error in the histogram fucntion - so I convert it back. + src = real(src); + end + + % histogram + % use adaptive number of bins to + hsrc = zeros(1,opt.hbins); hbins = opt.hbins; + while (hbins == opt.hbins) || (sum(hsrc>0)/numel(hsrc)<0.3 && hbins2^4) + [hsrc,hval] = hist(src(~isinf(src(:)) & ~isnan(src(:)) & src(:)<3.4027e+38 & src(:)>-3.4027e+38),hbins); + hbins = hbins*2; + end + hp = cumsum(hsrc)./sum(hsrc); + + + % lower limit + if opt.verb, srco=src; end + % Use the last value below tol rather than the first value above tol to + % avoid problems + if tol(1) + ind = max( [1,find(hp(1-tol(2)),1,'first') ] ); + ths(2) = mean( hval( max(1,ind-1):ind ) ); + else + ths(2) = max(src(:)); + end + % apply limits + src(srcths(2)) = ths(2); + + if ~isempty(opt.scale) && opt.scale(1)~=opt.scale(2) && diff(ths)~=0 + src = ( src - ths(1) ) ./ diff(ths); + src = src * diff(opt.scale) + opt.scale(1); + ths = opt.scale; + end + + %% display + if opt.verb + % get figure + fh = findobj('name','cat_stat_histth'); + if isempty(fh), figure('name','cat_stat_histth'); else, figure(fh); clf; end + + % create main plot + subplot('Position',[0.10 0.06 0.64 0.86]); + if opt.verb == 1 + hist(src(:),100); + elseif opt.verb == 2 + hist(src(src(:)>ths(1) & src(:)ths(1) & src(:)0.005,1,'first')),hval(find(hp<0.995,1,'last'))], ... + [hval(find(hp>0.025,1,'first')),hval(find(hp<0.975,1,'last'))]), ... + 'FitBoxToText','On','fontsize',opt.fs*0.85,'linestyle','none','fontname','fixedwidth'); + end + + if nargout>=1, varargout{1} = src; end + if nargout>=2, varargout{2} = ths; end +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_vol_qa202110.m",".m","44227","1013","function varargout = cat_vol_qa202110(action,varargin) +% CAT Preprocessing T1 Quality Control +% ______________________________________________________________________ +% +% Estimation of image quality measures like noise, inhomogeneity, +% contrast, resolution, etc. and scaling for school marks. +% +% [QAS,QAM] = cat_vol_qa202110(action,varargin) +% +% +% 1) Use GUI interface to choose segmentation and automatic setting of +% original and modified image (if available) +% [QAS,QAM] = cat_vol_qa202110() = cat_vol_qa202110('p0') +% +% [QAS,QAM] = cat_vol_qa202110('p0'[,opt]) - p0 class image +% [QAS,QAM] = cat_vol_qa202110('p#'[,opt]) - p1,p2,p3 class images +% [QAS,QAM] = cat_vol_qa202110('c#'[,opt]) - c1,c2,c3 class images +% [QAS,QAM] = cat_vol_qa202110('*#'[,opt]) - csf,gm,wm class images +% [QAS,QAM] = cat_vol_qa202110('p0',Pp0[,opt]) - no GUI call +% [QAS,QAM] = cat_vol_qa202110('p#',Pp1,Pp2,Pp3,[,opt]) - no GUI call +% [QAS,QAM] = cat_vol_qa202110('c#',Pc1,Pc2,Pc3,[,opt]) - no GUI call +% [QAS,QAM] = cat_vol_qa202110('c#',Pcsf,Pgm,Pwm,[,opt]) - no GUI call +% +% +% 2) Use GUI interface to choose all images like for other segmentations +% and modalities with a similar focus of CSF, GM, and WM tissue +% contrast such as PD, T2, or FLASH. +% [QAS,QAM] = cat_vol_qa202110('p0+'[,opt]) - p0 class image +% [QAS,QAM] = cat_vol_qa202110('p#+'[,opt]) - p1,p2,p3 class images +% [QAS,QAM] = cat_vol_qa202110('c#+'[,opt]) - c1,c2,c3 class images +% [QAS,QAM] = cat_vol_qa202110('*#+'[,opt]) - csf,gm,wm class images +% [QAS,QAM] = cat_vol_qa202110('p0+',Pp0,Po[,Pm,opt]) - no GUI call +% [QAS,QAM] = cat_vol_qa202110('p#+',Pp1,Pp2,Pp3,Po[,Pm,opt]) - no GUI call +% [QAS,QAM] = cat_vol_qa202110('c#+',Pc1,Pc2,Pc3,Po[,Pm,opt]) - no GUI call +% +% +% 3) Use GUI interface to choose all images. I.e. for other segmentations +% and modalities without focus of GM-WM contrast such as DTI MTI. +% [ not implemented yet ] +% +% +% 4) CAT12 internal preprocessing interface +% (this is the processing case that is also called in all other cases) +% [QAS,QAM] = cat_vol_qa202110('cat12',Yp0,Po,Ym,res[,opt]) +% +% +% Pp0 - segmentation files (p0*.nii) +% Po - original files (*.nii) +% Pm - modified files (m*.nii) +% Yp0 - segmentation image matrix +% Ym - modified image matrix +% +% opt = parameter structure +% opt.verb = verbose level [ 0=nothing | 1=points | 2*=times ] +% opt.redres = resolution in mm for intensity scaling [ 4* ]; +% opt.write_csv = final cms-file +% opt.write_xml = images base xml-file +% opt.sortQATm = sort QATm output +% opt.orgval = original QAM results (no marks) +% opt.recalc = +% opt.avgfactor = +% opt.prefix = prefix of xml output file (default cat_*.xml) +% +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (http://www.neuro.uni-jena.de) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% +% $Id$ +% ______________________________________________________________________ + +%#ok<*ASGLU> + + % get current release number and version + [ver_cat, rev_cat] = cat_version; + ver_cat = ver_cat(4:end); % remove leading CAT + + % init output + QAS = struct(); + QAR = struct(); + if nargout>0, varargout = cell(1,nargout); end + + try + if strcmp(action,'cat12err') + [mrifolder, reportfolder] = cat_io_subfolders(varargin{1}.job.data,varargin{1}.job); + elseif strcmp(action,'cat12') + [mrifolder, reportfolder] = cat_io_subfolders(varargin{2},varargin{6}.job); + else + [mrifolder, reportfolder] = cat_io_subfolders(varargin{4}.catlog,varargin{6}.job); + end + catch + mrifolder = 'mri'; + reportfolder = 'report'; + end + + % no input and setting of default options + if nargin==0, action='p0'; end + if isstruct(action) + Pp0 = action.data; + action = 'p0'; + end + if nargin==3 && isstruct(varargin{2}) && isstruct(varargin{2}) + opt = cat_check('checkinopt',varargin{2},defaults); + nopt = 1; + elseif nargin==8 && isstruct(varargin{6}) && isstruct(varargin{6}) + opt = cat_check('checkinopt',varargin{6},defaults); + nopt = 1; + else + opt = defaults; + nopt = 0; + end + + % check input by action + switch action + case {'p0','p0+'} + % segment image cases + if nargin<=3 + if (nargin-nopt)<2 + Pp0 = cellstr(spm_select(inf,'image',... + 'select p0-segment image',{},pwd,'^p0.*')); + if isempty(Pp0{1}), return; end + else + Pp0 = varargin{1}; + end + if numel(action)==2 + Po = Pp0; Pm = Pp0; + for fi=1:numel(Pp0) + [pp,ff,ee] = spm_fileparts(Pp0{fi}); + [ppa,ppb] = spm_fileparts(pp); + if strcmp(ppb,'mri'), ppo = ppa; else, ppo = pp; end + + Po{fi} = fullfile(ppo,[ff(3:end) ee]); + Pm{fi} = fullfile(pp,[opt.mprefix ff(3:end) ee]); + %Pmv{fi} = fullfile(pp,['m' ff(3:end) ee]); %#ok + %if ~exist(Pm{fi},'file') && strcmp(opt.mprefix,'nm') && exist(Pmv{fi},'file') + % fprintf('Preparing %s.\n',Pmv{fi}); + % cat_vol_sanlm(Pmv{fi},'n'); + %end + + if ~exist(Po{fi},'file'), Po{fi}=''; end + if ~exist(Pm{fi},'file'), Pm{fi}=''; end + end + else + Po = cellstr(spm_select(repmat(numel(Pp0),1,2),... + 'image','select original image(s)',{},pwd,'.*')); + Pm = cellstr(spm_select(repmat(numel(Pp0),1,2),... + 'image','select modified image(s)',{},pwd,'.*')); + end + elseif nargin<=5 + Pp0 = varargin{1}; + Po = varargin{2}; + Pm = varargin{3}; + else + error('MATLAB:cat_vol_qa202110:inputerror',... + 'Wrong number/structure of input elements!'); + end + case {'p#','c#','*#','p#+','c#+','*#+'} + % tissue class image cases + if nargin-1<=2 % GUI + if (nargin-nopt)<2 + if action(1)=='p' || action(1)=='c' + % cat/spm case + Pcsf = cellstr(spm_select(inf,'image',... + 'select p1-segment image',{},pwd,['^' action(1) '1.*'])); + if isempty(Pcsf{1}), return; end + Pgm=Pcsf; Pwm=Pcsf; + for fi=1:numel(Pcsf) + [pp,ff,ee] = spm_fileparts(Pcsf{fi}); + + Pgm{fi} = fullfile(pp,[action(1) '2' ff(3:end) ee]); + Pwm{fi} = fullfile(pp,[action(1) '3' ff(3:end) ee]); + end + else + Pcsf = cellstr(spm_select(inf,'image',... + 'select CSF segment image(s)',{},pwd,'.*')); + if isempty(Pcsf{1}), return; end + %Pgm = cellstr(spm_select(repmat(numel(Pcsf),1,2),... + % 'image','select GM segment image(s)',{},pwd,'.*')); + %Pwm = cellstr(spm_select(repmat(numel(Pcsf),1,2),... + % 'image','select WM segment image(s)',{},pwd,'.*')); + end + if numel(action)==2 + Pp0=Pcsf; Po=Pcsf; Pm=Pcsf; + for fi=1:numel(Pcsf) + [pp,ff,ee] = spm_fileparts(Pcsf{fi}); + Po{fi} = fullfile(pp,[ff(3:end) ee]); + Pm{fi} = fullfile(pp,['m' ff(3:end) ee]); + Pp0{fi} = fullfile(pp,['p0' ff(3:end) ee]); + end + else + Po = cellstr(spm_select(repmat(numel(Pcsf),1,2),... + 'image','select original image(s)',{},pwd,'.*')); + Pm = cellstr(spm_select(repmat(numel(Pcsf),1,2),... + 'image','select modified image(s)',{},pwd,'.*')); + Pp0=Pcsf; + for fi=1:numel(Pcsf) + [pp,ff,ee] = spm_fileparts(Pcsf{fi}); + Pp0{fi} = fullfile(pp,['p0' ff(3:end) ee]); + end + end + + % wie komm ich zum p0??? + else + Pp0 = varargin{1}; + end + elseif nargin==5 || nargin==6 + else + error('MATLAB:cat_vol_qa202110:inputerror',... + 'Wrong number/structure of input elements!'); + end + + Yp0 = 1; + case 'cat12err' + opt = cat_check('checkinopt',varargin{end},defaults); + case 'cat12' + % CAT12 internal input + if nargin>3 + Yp0 = varargin{1}; + Vo = spm_vol(varargin{2}); + Yo = single(spm_read_vols(Vo)); + Ym = varargin{3}; + res = varargin{4}; + V = res.image; + species = varargin{5}; + if isfield(varargin{6},'qa') + if isfield(varargin{6}.qa,'software') && isfield(varargin{6}.qa.software,'version_segment'), QAS.software.version_segment = varargin{6}.qa.software.version_segment; end + if isfield(varargin{6}.qa,'qualitymeasures'), QAS.qualitymeasures = cat_io_updateStruct(QAS,varargin{6}.qa.qualitymeasures); end + if isfield(varargin{6}.qa,'subjectmeasures'), QAS.subjectmeasures = cat_io_updateStruct(QAS,varargin{6}.qa.subjectmeasures); end + end + if nargin>7, Pp0 = varargin{7}; end % nargin count also parameter + % opt = varargin{end} in line 96) + opt.verb = 0; + + % reduce to original native space if it was interpolated + if any(size(Yp0)~=Vo.dim) + if isfield(Vo,'private'), Vo = rmfield(Vo,'private'); end + if isfield(Vo,'mat0'), Vo = rmfield(Vo,'mat0'); end + Vo.dat = zeros(Vo.dim,'single'); Vo.dt(1) = 16; Vo.pinfo = [1;0;0]; + + Vp0t = res.image; + if isfield(Vp0t,'private'), Vp0t = rmfield(Vp0t,'private'); end + if isfield(Vp0t,'mat0'), Vp0t = rmfield(Vp0t,'mat0'); end + Vp0t.dt(1) = 16; + Vp0t.pinfo = [1;0;0]; + Vp0t.dat = Yp0; + + % resampling and corrections of the Yp0 + % Vp0t = spm_write_vol(Vp0t,double(Yp0)); + [Vtpm,Yp0] = cat_vol_imcalc(Vp0t,Vo,'i1',struct('interp',2,'verb',0)); + rf = 50; + Yp0 = single(Yp0); + Yp0r = round(Yp0*rf)/rf; + YMR = false(size(Yp0)); + for i=1:4, YMR = YMR | (Yp0>(i-1/rf) & Yp0<(i+1/rf)); end + Yp0(YMR) = Yp0r(YMR); clear YMR Ynr; + + % resampling of the corrected image + Vp0t.dat = Ym; + [Vtpm,Ym] = cat_vol_imcalc(Vp0t,Vo,'i1',struct('interp',6,'verb',0)); + Ym = single(Ym); + end + + else + error('MATLAB:cat_vol_qa202110:inputerror',... + 'Wrong number/structure of input elements!'); + end + otherwise + error('MATLAB:cat_vol_qa202110:inputerror',... + 'Wrong number/structure of input elements!'); + end + if ~exist('species','var'), species='human'; end + + + % + % -------------------------------------------------------------------- + [QA,QMAfn] = cat_stat_marks('init'); + stime = clock; + + + + % Print options + % -------------------------------------------------------------------- + Cheader = {'scan'}; + Theader = sprintf(sprintf('%%%ds:',opt.snspace(1)-1),'scan'); + Tline = sprintf('%%5d) %%%ds:',opt.snspace(1)-8); + Tline2 = sprintf('%%5d) %%6s%%%ds:',opt.snspace(1)-14); + Tavg = sprintf('%%%ds:',opt.snspace(1)-1); + TlineE = sprintf('%%5d) %%%ds: %%s',opt.snspace(1)-7); + for fi=1:numel(QMAfn) + Cheader = [Cheader QMAfn{fi}]; %#ok + Theader = sprintf(sprintf('%%s%%%ds',opt.snspace(2)),Theader,... + QMAfn{fi}(1:min(opt.snspace(2)-1,numel(QMAfn{fi})))); + Tline = sprintf('%s%%%d.%df',Tline,opt.snspace(2),opt.snspace(3)); + Tline2 = sprintf('%s%%%d.%df',Tline2,opt.snspace(2),opt.snspace(3)); + Tavg = sprintf('%s%%%d.%df',Tavg,opt.snspace(2),opt.snspace(3)); + end + Cheader = [Cheader 'IQR']; + Theader = sprintf(sprintf('%%s%%%ds',opt.snspace(2)),Theader,'IQR'); + Tline = sprintf('%s%%%d.%df%%s\n',Tline,opt.snspace(2),opt.snspace(3)); + Tline2 = sprintf('%s%%%d.%df\n',Tline2,opt.snspace(2),opt.snspace(3)); + Tavg = sprintf('%s%%%d.%df\n',Tavg,opt.snspace(2),opt.snspace(3)); + + + + + + + % estimation part + switch action + case {'p0','p#','c#','*#','p0+','p#+','c#+','*#+'} + % loop for multiple files + % return for empty input + if isempty(Pp0) || (isempty(Pp0{1}) && numel(Pp0)<=1) + cat_io_cprintf('com','No images for QA!\n'); + return + end + + if opt.verb>1 + fprintf('\n%s\n\n%s\n%s\n', ... + sprintf('CAT Preprocessing T1 Quality Control (%s %s):',mfilename,... + sprintf('Rev: %s',rev_cat)), Theader,repmat('-',size(Theader))); + end + + qamat = nan(numel(Po),numel(QMAfn)); + qamatm = nan(numel(Po),numel(QMAfn)); + mqamatm = 10.5*ones(numel(Po),1); + + + QAS = struct(); QAR = struct(); + QAR.mark2rps = @(mark) min(100,max(0,105 - mark*10)) + isnan(mark).*mark; + + for fi=1:numel(Pp0) + try + stime1 = clock; + if exist(Po{fi},'file') + Vo = spm_vol(Po{fi}); + else + error('cat_vol_qa202110:noYo','No original image.'); + end + + Yp0 = single(spm_read_vols(spm_vol(Pp0{fi}))); + Yp0(isnan(Yp0) | isinf(Yp0)) = 0; + if ~isempty(Pm{fi}) && exist(Pm{fi},'file') + Ym = single(spm_read_vols(spm_vol(Pm{fi}))); + Ym(isnan(Yp0) | isinf(Yp0)) = 0; + elseif 1 + Ym = single(spm_read_vols(spm_vol(Po{fi}))); + Ym(isnan(Yp0) | isinf(Yp0)) = 0; + Yw = Yp0>2.95 | cat_vol_morph( Yp0>2 , 'e'); + Yb = cat_vol_approx( Ym .* Yw + Yw .* min(Ym(:)) ) - min(Ym(:)); + %Yb = Yb / mean(Ym(Yw(:))); + Ym = Ym ./ max(eps,Yb); + + else + error('cat_vol_qa202110:noYm','No corrected image.'); + end + + res.image = spm_vol(Pp0{fi}); + [QASfi,QAMfi] = cat_vol_qa202110('cat12',Yp0,Vo,Ym,res,species,opt,Pp0{fi}); + + if isnan(QASfi.qualitymeasures.NCR) + fprintf(''); + end + + + QAS = cat_io_updateStruct(QAS,QASfi,0,fi); + QAR = cat_io_updateStruct(QAR,QAMfi,0,fi); + + + % color for the differen mark cases (opt.process) + for fni=1:numel(QMAfn) + qamat(fi,fni) = QAS(fi).qualitymeasures.(QMAfn{fni}); + qamatm(fi,fni) = QAR(fi).qualityratings.(QMAfn{fni}); + end + mqamatm(fi) = QAR(fi).qualityratings.IQR; + mqamatm(fi) = max(0,min(10.5, mqamatm(fi))); + + + % print the results for each scan + if opt.verb>1 + if opt.rerun || cat_io_rerun(Vo.fname, fullfile(pp,reportfolder,[opt.prefix ff '.xml']) , 0 ) + rerun = sprintf(' updated %2.0fs',etime(clock,stime1)); + elseif exist( fullfile(pp,reportfolder,[opt.prefix ff '.xml']) , 'file') + rerun = ' loaded'; + else + rerun = ' '; % new + end + + if opt.orgval + cat_io_cprintf(opt.MarkColor(max(1,floor( mqamatm(fi,1)/9.5 * ... + size(opt.MarkColor,1))),:),sprintf(Tline,fi,... + spm_str_manip(QAS(fi).filedata.fname,['a' num2str(opt.snspace(1) - 14)]),... + qamat(fi,:),max(1,min(9.5,mqamatm(fi,:))),rerun)); + else + cat_io_cprintf(opt.MarkColor(max(1,floor( mqamatm(fi,1)/9.5 * ... + size(opt.MarkColor,1))),:),sprintf(Tline,fi,... + spm_str_manip(QAS(fi).filedata.fname,['a' num2str(opt.snspace(1) - 14)]),... + qamatm(fi,:),max(1,min(9.5,mqamatm(fi,:))),rerun)); + end + end + catch e + switch e.identifier + case {'cat_vol_qa202110:noYo','cat_vol_qa202110:noYm','cat_vol_qa202110:badSegmentation'} + em = e.identifier; + otherwise + em = ['ERROR:\n' repmat(' ',1,10) e.message '\n']; + for ei=1:numel(e.stack) + em = sprintf('%s%s%5d: %s\n',em,repmat(' ',1,10),... + e.stack(ei).line(end),e.stack(ei).name); + end + end + + [pp,ff] = spm_fileparts(Po{fi}); + QAS(fi).filedata.fnames = [spm_str_manip(pp,sprintf('k%d',floor( (opt.snspace(1)-19) /3) - 1)),'/',... + spm_str_manip(ff,sprintf('k%d',(opt.snspace(1)-19) - floor((opt.snspace(1)-14)/3)))]; + cat_io_cprintf(opt.MarkColor(end,:),sprintf(TlineE,fi,... + QAS(fi).filedata.fnames,[em '\n'])); + end + end + + + + % sort by mean mark + % ---------------------------------------------------------------- + if opt.sortQATm && numel(Po)>1 + % sort matrix + [smqamatm,smqamatmi] = sort(mqamatm,'ascend'); + sqamatm = qamatm(smqamatmi,:); + sqamat = qamat(smqamatmi,:); + + % print matrix + if opt.verb>0 + fprintf('%s\n',repmat('-',size(Theader))); + for fi=1:numel(QAS) + if opt.orgval + cat_io_cprintf(opt.MarkColor(max(1,min(size(opt.MarkColor,1),... + round( mqamatm(smqamatmi(fi),2)/9.5 * ... + size(opt.MarkColor,1)))),:),sprintf(... + Tline2,fi,sprintf('(%d)',smqamatmi(fi)),... + spm_str_manip(Pp0{fi},'l80'), ...QAS(smqamatmi(fi)).filedata.fnames, ... + ...spm_str_manip(QAS(smqamatmi(fi)).filedata.file,['f' num2str(opt.snspace(1) - 14)]),... + sqamat(fi,:),max(1,min(10.5,mqamatm(smqamatmi(fi),:))))); + else + cat_io_cprintf(opt.MarkColor(max(1,min(size(opt.MarkColor,1),... + round( mqamatm(smqamatmi(fi),2)/9.5 * ... + size(opt.MarkColor,1)))),:),sprintf(... + Tline2,fi,sprintf('(%d)',smqamatmi(fi)),... + spm_str_manip(Pp0{fi},'l80'), ... QAS(smqamatmi(fi)).filedata.fnames, ... + ...spm_str_manip(QAS(smqamatmi(fi)).filedata.file,['f' num2str(opt.snspace(1) - 14)]),... + sqamatm(fi,:),mqamatm(smqamatmi(fi),:))); + end + end + end + else + %[smqamatm,smqamatmi] = sort(mqamatm,'ascend'); + %sqamatm = qamatm(smqamatmi,:); + end + % print the results for each scan + if opt.verb>1 && numel(Pp0)>1 + fprintf('%s\n',repmat('-',size(Theader))); + if opt.orgval + fprintf(Tavg,'mean',cat_stat_nanmean(qamat,1),cat_stat_nanmean(mqamatm,1)); %#ok + fprintf(Tavg,'std' , cat_stat_nanstd(qamat,1), cat_stat_nanstd(mqamatm,1)); %#ok + else + fprintf(Tavg,'mean',cat_stat_nanmean(qamatm,1),cat_stat_nanmean(mqamatm,1)); %#ok + fprintf(Tavg,'std' , cat_stat_nanstd(qamatm,1), cat_stat_nanstd(mqamatm,1)); %#ok + end + %fprintf('%s\n',repmat('-',size(Theader))); + %fprintf(Tavg,'mean',mean(qamat,1)); + %fprintf(Tavg,'std', std(qamat,1)); + end + if opt.verb>0, fprintf('\n'); end + + + + % result tables (cell structures) + % ---------------------------------------------------------------- + if nargout>2 && opt.write_csv + QAT = [Cheader(1:end-1); ... there is no mean for the original measures + Po , num2cell(qamat); ... + 'mean' , num2cell(cat_stat_nanmean(qamat,1)); ... + 'std' , num2cell( cat_stat_nanstd(qamat,1,1))]; + QATm = [Cheader; ... + Po , num2cell(qamatm) , ... + num2cell(cat_stat_nanmean(qamatm,2)); ... + 'mean' , num2cell(cat_stat_nanmean(qamatm,1)) , ... + num2cell(cat_stat_nanmean(mqamatm,1)); ... + 'std' , num2cell( cat_stat_nanstd(qamatm,1,1)), ... + num2cell( cat_stat_nanstd(mqamatm,1))]; + + + % write csv results + % -------------------------------------------------------------- + if opt.write_csv + pp = spm_fileparts(Pp0{1}); + cat_io_csv(fullfile(pp,reportfolder,[opt.prefix num2str(numel(Vo),'%04d') ... + 'cat_vol_qa202110_values.csv']),QAT); + cat_io_csv(fullfile(pp,reportfolder,[opt.prefix num2str(numel(Vo),'%04d') ... + 'cat_vol_qa202110_marks.csv']),QATm); + end + end + + if opt.verb>0 + fprintf('Quality Control for %d subject was done in %0.0fs\n', ... + numel(Pp0),etime(clock,stime)); fprintf('\n'); + end + + + case 'cat12err' + + % file information + % ---------------------------------------------------------------- + [pp,ff,ee] = spm_fileparts(Vo.fname); + if strcmp(ee,'.gz'), [~,ff] = spm_fileparts(ff); ee = '.nii.gz'; end + [pp0,ff0,ee0] = spm_fileparts(Pp0); + [QAS.filedata.path,QAS.filedata.file] = spm_fileparts(Vo.fname); + QAS.filedata.fname = Vo.fname; + QAS.filedata.F = Vo.fname; + QAS.filedata.Fm = fullfile(pp0,['m' ff ee0]); + QAS.filedata.Fp0 = fullfile(pp0,['p0' ff ee0]); + QAS.filedata.fnames = [spm_str_manip(pp,sprintf('k%d',... + floor( max(opt.snspace(1)-19-ff,opt.snspace(1)-19)/3) - 1)),'/',... + spm_str_manip(ff,sprintf('k%d',... + (opt.snspace(1)-19) - floor((opt.snspace(1)-14)/3)))]; + + + % software, parameter and job information + % ---------------------------------------------------------------- + [nam,rev_spm] = spm('Ver'); + QAS.software.version_spm = rev_spm; + A = ver; + for i=1:length(A) + if strcmp(A(i).Name,'MATLAB') + QAS.software.version_matlab = A(i).Version; + end + end + clear A + % 1 line: Matlab, SPM12, CAT12 version number and GUI and experimental mode + if ispc, OSname = 'WIN'; + elseif ismac, OSname = 'MAC'; + else OSname = 'LINUX'; + end + + QAS.software.system = OSname; + QAS.software.version_cat = ver_cat; + if ~isfield(QAS.software,'version_segment') + QAS.software.version_segment = rev_cat; + end + QAS.software.revision_cat = rev_cat; + try + QAS.hardware.numcores = max(cat_get_defaults('extopts.nproc'),1); + catch + QAS.hardware.numcores = 1; + end + + + % save important preprocessing parameter + % remove LAS + QAS.parameter.opts = opt.job.opts; + QAS.parameter.extopts = rmfield(opt.job.extopts,... + {'LAB','atlas','satlas','darteltpms','shootingtpms','fontsize'}); + %QAS.parameter.output = opt.job.output; + QAS.parameter.caterr = opt.caterr; + QAS.error = opt.caterrtxt; + + % export + if opt.write_xml + cat_io_xml(fullfile(pp0,[opt.prefix ff '.xml']),QAS,'write'); + end + + case 'cat12' + % estimation of the measures for the single case + + % file information + % ---------------------------------------------------------------- + [pp,ff,ee] = spm_fileparts(Vo.fname); + if strcmp(ee,'.gz'), [~,ff] = spm_fileparts(ff); ee = '.nii.gz'; end + [pp0,ff0,ee0] = spm_fileparts(Pp0); + [QAS.filedata.path,QAS.filedata.file] = spm_fileparts(Vo.fname); + QAS.filedata.fname = Vo.fname; + QAS.filedata.F = Vo.fname; + QAS.filedata.Fm = fullfile(pp0,['m' ff ee0]); + QAS.filedata.Fp0 = fullfile(pp0,['p0' ff ee0]); + QAS.filedata.fnames = [spm_str_manip(pp,sprintf('k%d',... + floor( max(opt.snspace(1)-19-ff,opt.snspace(1)-19)/3) - 1)),'/',... + spm_str_manip(ff,sprintf('k%d',... + (opt.snspace(1)-19) - floor((opt.snspace(1)-14)/3)))]; + + + % software, parameter and job information + % ---------------------------------------------------------------- + [nam,rev_spm] = spm('Ver'); + if ispc, OSname = 'WIN'; + elseif ismac, OSname = 'MAC'; + else OSname = 'LINUX'; + end + + QAS.software.system = OSname; + QAS.software.version_spm = rev_spm; + A = ver; + for i=1:length(A) + if strcmp(A(i).Name,'MATLAB') + QAS.software.version_matlab = A(i).Version; + end + end + clear A + QAS.software.version_cat = ver_cat; + if ~isfield(QAS.software,'version_segment') + QAS.software.version_segment = rev_cat; + end + QAS.software.revision_cat = rev_cat; + QAS.software.function = which('cat_vol_qa202110'); + QAS.software.markdefs = which('cat_stat_marks'); + QAS.software.qamethod = action; + QAS.software.date = datestr(clock,'yyyymmdd-HHMMSS'); + % RD202007: not requried + %{ + warning off + QAS.software.opengl = opengl('INFO'); + QAS.software.opengldata = opengl('DATA'); + warning on + %} + QAS.software.cat_warnings = cat_io_addwarning; + % replace matlab newlines by HTML code + for wi = 1:numel( QAS.software.cat_warnings ) + QAS.software.cat_warnings(wi).message = cat_io_strrep( QAS.software.cat_warnings(wi).message , {'\\n', '\n'} , {'
','
'} ); + end + + %QAS.parameter = opt.job; + if isfield(opt,'job') && isfield(opt.job,'opts'), QAS.parameter.opts = opt.job.opts; end + if isfield(opt,'job') && isfield(opt.job,'extopts'), QAS.parameter.opts = opt.job.extopts; end + if exist('res','var') + rf = {'Affine','Affine0','lkp','mn','vr','ll'}; % important SPM preprocessing variables + for rfi=1:numel(rf) + if isfield(res,rf{rfi}), QAS.SPMpreprocessing.(rf{rfi}) = res.(rf{rfi}); end + end + end + + + %% resolution, boundary box + % --------------------------------------------------------------- + vx_vol = sqrt(sum(Vo.mat(1:3,1:3).^2)); + vx_voli = sqrt(sum(V.mat(1:3,1:3).^2)); + Yp0toC = @(Yp0,c) 1-min(1,abs(Yp0-c)); + + % resolution + QAS.qualitymeasures.res_vx_vol = vx_vol; + if 1 % CAT internal resolution + QAS.qualitymeasures.res_vx_voli = vx_voli; + end + QAS.qualitymeasures.res_RMS = cat_stat_nanmean(vx_vol.^2).^0.5; + % further unused measure (just for test/comparison) + %QAS.qualitymeasures.res_isotropy = max(vx_vol)./min(vx_vol); + %QAS.qualitymeasures.res_vol = prod(abs(vx_vol)); + %QAS.qualitymeasures.res_MVR = mean(vx_vol); + + % boundary box - brain tissue next to image boundary + bbth = round(2/cat_stat_nanmean(vx_vol)); M = true(size(Yp0)); + M(bbth:end-bbth,bbth:end-bbth,bbth:end-bbth) = 0; + QAS.qualitymeasures.res_BB = sum(Yp0(:)>1.25 & M(:))*prod(abs(vx_vol)); + + % check segmentation + spec = species; for ai=num2str(0:9); spec = strrep(spec,ai,''); end + bvol = species; for ai=char(65:122); bvol = strrep(bvol,ai,''); end; bvol = str2double(bvol); + + subvol = [sum(Yp0(:)>2.5 & Yp0(:)<3.1)*prod(vx_vol)/1000,... + sum(Yp0(:)>1.5 & Yp0(:)<2.5)*prod(vx_vol)/1000,... + sum(Yp0(:)>0.5 & Yp0(:)<1.5)*prod(vx_vol)/1000]; + + if isempty(bvol) + switch spec + case 'human' + bvol = 1400; + otherwise + warning('cat_vol_qa202110:species',... + sprintf('Unknown species %s (C=%0.0f,G=%0.0f,W=%0.0f).',species,subvol)); %#ok + end + end + if sum(subvol)bvol*3 + warning('cat_vol_qa202110:badSegmentation',... + sprintf('Bad %s segmentation (C=%0.0f,G=%0.0f,W=%0.0f).',species,subvol)) %#ok + end + if ~isfield(QAS,'subjectmeasures') + %% in case of external/batch calls + QAS.subjectmeasures.vol_TIV = sum(Yp0(:)>0) .* prod(vx_vol) / 1000; + for i = 1:3 + QAS.subjectmeasures.vol_abs_CGW(i) = sum( Yp0toC(Yp0(:),i)) .* prod(vx_vol) / 1000; + QAS.subjectmeasures.vol_rel_CGW(i) = QAS.subjectmeasures.vol_abs_CGW(i) ./ ... + QAS.subjectmeasures.vol_TIV; + end + end + + %% estimate QA + % --------------------------------------------------------------- + % remove space arount the brain for speed-up + [Yo,Ym,Yp0] = cat_vol_resize({Yo,Ym,Yp0},'reduceBrain',vx_vol,4,Yp0>1.5); + + % rought contast and noise estimation to get a stable T1 map for threshold estimation + T1th = [cat_stat_nanmedian(Ym(Yp0toC(Yp0(:),1)>0.9)) ... + cat_stat_nanmedian(Ym(Yp0toC(Yp0(:),2)>0.9)) ... + cat_stat_nanmedian(Ym(Yp0toC(Yp0(:),3)>0.9))]; + noise = max(0,min(1,cat_stat_nanstd(Ym(Yp0(:)>2.9)) / min(abs(diff(T1th))))); + + Yms = Ym+0; spm_smooth(Yms,Yms,repmat(double(noise)*4,1,3)); % smoothing to reduce high frequency noise + + % basic tissue classes - erosion to avoid PVE, std to avoid other tissues (like WMHs) + if T1th(1) < T1th(2) && T1th(2) < T1th(3) + voli = @(v) (v ./ (pi * 4./3)).^(1/3); + rad = voli( QAS.subjectmeasures.vol_TIV) ./ cat_stat_nanmean(vx_vol); + Ysc = 1-cat_vol_smooth3X(Yp0<1 | Ym==0,min(24,max(16,rad*2))); % fast 'distance' map + Ycm = cat_vol_morph(Yp0>0.5 & Yp0<1.5 & Yms0.75 & Yp0<1.25;% avoid PVE & ventricle focus + if sum(Ycm(:)>0)<10; Ycm=cat_vol_morph(Yp0>0.5 & Yp0<1.5 & Yms0)<10; Ycm=Yp0>0.5 & Yms0.7 & Yms1.1,'e') & cat_vol_morph(Yp0<2.9,'e'); % avoid PVE 2 + Ygm = (Ygm1 | Ygm2) & Ysc<0.9; % avoid PVE & no subcortex + Ywm = cat_vol_morph(Yp0>2.1,'e') & Yp0>2.9 & ... % avoid PVE & subcortex + Yms>min(cat_stat_nanmean(T1th(2:3)),(T1th(2) + 2*noise*abs(diff(T1th(2:3))))); % avoid WMHs2 + else + Ycm = cat_vol_morph(Yp0>0 & Yp0<2,'e'); + Ygm = cat_vol_morph(Yp0>1 & Yp0<3,'e'); + Ywm = cat_vol_morph(Yp0>2 & Yp0<4,'e'); + end + clear Ygm1 Ygm2; % Ysc; + + %% further refinements of the tissue maps + if T1th(1) < T1th(2) && T1th(2) < T1th(3) + T2th = [median(Yms(Ycm)) median(Yms(Ygm)) median(Yms(Ywm))]; + Ycm = Ycm & Yms>(T2th(1)-16*noise*diff(T2th(1:2))) & Ysc &... + Yms<(T2th(1)+0.1*noise*diff(T2th(1:2))); + if sum(Ycm(:)>0)<10; Ycm=cat_vol_morph(Yp0>0.5 & Yp0<1.5 & Yms0)<10; Ycm=Yp0>0.5 & Yms(T2th(2)-2*noise*abs(diff(T1th(2:3)))) & Yms<(T2th(2)+2*noise*abs(diff(T1th(2:3)))); + Ygm(smooth3(Ygm)<0.2) = 0; + end + Ycm = cat_vol_morph(Ycm,'lc'); % to avoid holes + Ywm = cat_vol_morph(Ywm,'lc'); % to avoid holes + Ywe = cat_vol_morph(Ywm,'e'); + + + % Yo was not normalized + if abs(T1th(2) - 2/3) < 0.02 + Ymm = Ym; + else + Ymm = cat_main_gintnorm(Ym,struct('T3th',[0 T1th T1th(end)*2],'T3thx',[0 1 2 3 6])); + end + res_ECR0 = estimateECR0( Ymm , Yp0, 1/3:1/3:1, vx_vol.^.5 ); + QAS.qualitymeasures.res_ECR = abs( 2.5 - res_ECR0 * 10 ); + + + + %% low resolution tissue intensity maps (smoothing) + % High frequency noise is mostly uncritical as far as simple smoothing can reduce it. + % Although the very low frequency interferences (inhomogeneity) is unproblematic in most cases, + % but will influence the noise pattern. + % But most important is the noise with the medium high frequencies, that we try do detect by + % reducing the very high and low noise pattern by filtering and pixel smoothing by reduction. + res = 2; vx_volx = 1; + Yos = cat_vol_localstat(Yo,Ywm,1,1); Yo(Yos>0)=Yos(Yos>0); % reduce high frequency noise in WM + Yos = cat_vol_localstat(Yo,Ycm,1,1); Yo(Yos>0)=Yos(Yos>0); % reduce high frequency noise in CSF + + Yc = cat_vol_resize(Yo .* Ycm,'reduceV',vx_volx,res,32,'meanm'); % CSF thr. (minimum to avoid PVE) + Yg = cat_vol_resize(Yo .* Ygm,'reduceV',vx_volx,res,32,'meanm'); % GM thr. + Yw = cat_vol_resize(Yo .* Ywe,'reduceV',vx_volx,res,32,'meanm'); % WM thr. and bias correction (Ywme) + Ywc = cat_vol_resize(Ym .* Ywe,'reduceV',vx_volx,res,32,'meanm'); % for bias correction + Ywb = cat_vol_resize( (Yo + min(Yo(:))) .* Ywe,'reduceV',vx_volx,res,32,'meanm') - min(Yo(:)); % for WM inhomogeneity estimation (avoid PVE) + Ywn = cat_vol_resize(Yo .* Ywm,'reduceV',vx_volx,res,32,'meanm'); % for WM noise + Ycn = cat_vol_resize(Yo .* Ycm,'reduceV',vx_volx,res,32,'meanm'); % for CSF noise + Ycm = cat_vol_resize(Ycm ,'reduceV',vx_volx,res,32,'meanm'); % CSF thr. (minimum to avoid PVE) + Ygm = cat_vol_resize(Ygm ,'reduceV',vx_volx,res,32,'meanm'); % GM thr. + Ywm = cat_vol_resize(Ywm ,'reduceV',vx_volx,res,32,'meanm'); % WM thr. and bias correction (Ywme) + Ywe = cat_vol_resize(Ywe ,'reduceV',vx_volx,res,32,'meanm'); % WM thr. and bias correction (Ywme) + + % only voxel that were the product of + Yc = Yc .* (Ycm>=0.5); Yg = Yg .* (Ygm>=0.5); Yw = Yw .* (Ywe>=0.5); + Ywc = Ywc .* (Ywe>=0.5); Ywb = Ywb .* (Ywm>=0.5); Ywn = Ywn .* (Ywm>=0.5); + Ycn = Ycn .* (Ycm>=0.5); + + + %clear Ycm Ygm Ywm Ywme; + [Yo,Ym,Yp0,resr] = cat_vol_resize({Yo,Ym,Yp0},'reduceV',vx_volx,res,32,'meanm'); + resr.vx_volo = vx_vol; vx_vol=resr.vx_red .* resr.vx_volo; + + %% intensity scaling for normalized Ym maps like in CAT12 + if cat_stat_nanmean(Yo(Yp0(:)>2))<0 + Ywc = Ywc .* (cat_stat_nanmean(Yo(Yp0(:)>2))/cat_stat_nanmean(2 - Ym(Yp0(:)>2))); % RD202004: negative values in chimp data showed incorrect scalling + else + Ywc = Ywc .* (cat_stat_nanmean(Yo(Yp0(:)>2))/cat_stat_nanmean(Ym(Yp0(:)>2))); + end + %% bias correction for original map, based on the + WI = zeros(size(Yw),'single'); WI(Ywc(:)~=0) = Yw(Ywc(:)~=0)./Ywc(Ywc(:)~=0); WI(isnan(Ywe) | isinf(WI) | Ywe==0) = 0; + WI = cat_vol_approx(WI,'rec',2); + WI = cat_vol_smooth3X(WI,1); + + Ywn = Ywn./max(eps,WI); Ywn = round(Ywn*1000)/1000; + Ymi = Yo ./max(eps,WI); Ymi = round(Ymi*1000)/1000; + Yc = Yc ./max(eps,WI); Yc = round(Yc *1000)/1000; + Yg = Yg ./max(eps,WI); Yg = round(Yg *1000)/1000; + Yw = Yw ./max(eps,WI); Yw = round(Yw *1000)/1000; + + clear WIs ; + + + % tissue segments for contrast estimation etc. + CSFth = cat_stat_nanmean(Yc(~isnan(Yc(:)) & Yc(:)~=0)); + GMth = cat_stat_nanmean(Yg(~isnan(Yg(:)) & Yg(:)~=0)); + WMth = cat_stat_nanmean(Yw(~isnan(Yw(:)) & Yw(:)~=0)); + T3th = [CSFth GMth WMth]; + + % estimate background + [Ymir,resYbg] = cat_vol_resize(Ymi,'reduceV',1,6,32,'meanm'); + try + warning 'off' 'MATLAB:cat_vol_morph:NoObject' + BGCth = min(T3th)/2; + Ybgr = cat_vol_morph(cat_vol_morph(Ymir0.5; clear Yosr Ybgr; + if sum(Ybg(:))<32, Ybg = cat_vol_morph(Yo0.5; clear Yosr Ybgr; + if sum(Ybg(:))<32, Ybg = cat_vol_morph(YoGMth + QAS.qualitymeasures.tissue_weighting = 'T1'; + elseif WMth0.5 & ~isinf(Yp0(:)))); + end + QAS.qualitymeasures.tissue_stdr = QAS.qualitymeasures.tissue_std ./ (WMth-BGth); + + % (relative) (mininum) tissue contrast ( CSF-GM-WM ) + % - the CSF threshold varies strongly due to bad segmentations, + % and anatomica variance, so its better to use GM-WM contrast + % and take care of overoptimisation with values strongly >1/3 + % of the relative contrast + contrast = min(abs(diff(QAS.qualitymeasures.tissue_mn(3:4)))) ./ abs(diff([min([CSFth,BGth]),max([WMth,GMth])])); % default contrast + contrast = contrast + min(0,13/36 - contrast) * 1.2; % avoid overoptimsization + QAS.qualitymeasures.contrast = contrast * (max([WMth,GMth])); + QAS.qualitymeasures.contrastr = contrast; + + + + %% noise estimation (original (bias corrected) image) + % WM variance only in one direction to avoid WMHs! + rms=1; nb=1; + if 1 + NCww = sum(Ywn(:)>0) * prod(vx_vol); + NCwc = sum(Ycn(:)>0) * prod(vx_vol); + [Yos2,YM2,R] = cat_vol_resize({Ywn,Ywn>0},'reduceV',vx_vol,3,16,'meanm'); + signal_intensity = abs( diff( [min(BGth,CSFth) , max(GMth,WMth)] )); + NCRw = estimateNoiseLevel(Yos2,YM2>0.5,nb,rms) / signal_intensity / contrast ; + else + % RD202005: not correct working? + Ywmn = cat_vol_morph(Ywm,'o'); + NCww = sum(Ywmn(:)) * prod(vx_vol); + NCwc = sum(Ycm(:)) * prod(vx_vol); + signal_intensity = abs( diff( [min(BGth,CSFth) , max(GMth,WMth)] )); + [Yos2,YM2,R] = cat_vol_resize({Ywn,Ywmn},'reduceV',vx_vol,max(3 * min(vx_vol) ,3),16,'meanm'); + YM2 = cat_vol_morph(YM2,'o'); % we have to be sure that there are neigbors otherwise the variance is underestimated + NCRw = estimateNoiseLevel(Yos2,YM2>0.5,nb,rms) / signal_intensity / contrast ; + if isnan(NCRw) + NCRw = estimateNoiseLevel(Ywn,Ywmn,nb,rms) / signal_intensity / contrast ; + end + end + NCRw = NCRw * (1 + log(28 - prod(R.vx_red)))/(1 + log(28 - 1)); % compensate voxel averageing + if BGth<-0.1 && WMth<3, NCRw=NCRw/3; end% MT weighting + clear Yos0 Yos1 Yos2 YM0 YM1 YM2; + + %% CSF variance of large ventricle + % for typical T2 images we have too much signal in the CSF and can't use it for noise estimation! + wcth = 200; + if CSFthwcth + if 1 + [Yos2,YM2] = cat_vol_resize({Ycn,Ycn>0},'reduceV',vx_vol,3,16,'meanm'); + NCRc = estimateNoiseLevel(Yos2,YM2>0.5,nb,rms) / signal_intensity / contrast ; + else + % RD202005: not correct working? + [Yos2,YM2] = cat_vol_resize({Ycn,Ycm},'reduceV',vx_vol,max(3 * min(vx_vol) ,3),16,'meanm'); + NCRc = estimateNoiseLevel(Yos2,YM2>0.5,nb,rms) / signal_intensity / contrast ; + if isnan(NCRc) + NCRc = estimateNoiseLevel(Ycn,Ycm,nb,rms) / signal_intensity / contrast ; + end + end + clear Yos0 Yos1 Yos2 YM0 YM1 YM2; + else + NCRc = 0; + NCwc = 0; + end + % 1/sqrt(volume) to compensate for noise differency due to different volumen size. + % Overall there are better chances to correct high resolution noise. + % Nitz W R. Praxiskurs MRT. Page 28. + NCwc = min(wcth,max(0,NCwc-wcth)); NCww = min(wcth,NCww) - NCwc; % use CSF if possible + if NCwc<3*wcth && NCww<10*wcth, NCRc = min(NCRc,NCRw); end + QAS.qualitymeasures.NCR = (NCRw*NCww + NCRc*NCwc)/(NCww+NCwc); + QAS.qualitymeasures.NCR = QAS.qualitymeasures.NCR * abs(prod(resr.vx_volo*res))^0.4 * 5/4; %* 7.5; %15; + %QAS.qualitymeasures.CNR = 1 / QAS.qualitymeasures.NCR; +%fprintf('NCRw: %8.3f, NCRc: %8.3f, NCRf: %8.3f\n',NCRw,NCRc,(NCRw*NCww + NCRc*NCwc)/(NCww+NCwc)); + + + %% Bias/Inhomogeneity (original image with smoothed WM segment) + Yosm = cat_vol_resize(Ywb,'reduceV',vx_vol,3,32,'meanm'); Yosmm = Yosm~=0; % resolution and noise reduction + for si=1:max(1,min(3,round(QAS.qualitymeasures.NCR*4))), mth = min(Yosm(:)) + 1; Yosm = cat_vol_localstat(Yosm + mth,Yosmm,1,1) - mth; end + QAS.qualitymeasures.ICR = cat_stat_nanstd(Yosm(Yosm(:)>0)) / signal_intensity / contrast; + %QAS.qualitymeasures.CIR = 1 / QAS.qualitymeasures.ICR; + + + %% marks + QAR = cat_stat_marks('eval',1,QAS); + + % export + if opt.write_xml + QAS.qualityratings = QAR.qualityratings; + QAS.subjectratings = QAR.subjectratings; + QAS.ratings_help = QAR.help; + + cat_io_xml(fullfile(pp0,[opt.prefix ff '.xml']),QAS,'write'); + end + + clear Yi Ym Yo Yos Ybc + clear Ywm Ygm Ycsf Ybg + + end + + if nargout>1, varargout{2} = QAR; end + if nargout>0, varargout{1} = QAS; end + +end +%======================================================================= +function def=defaults + % default parameter + def.verb = 2; % verbose level [ 0=nothing | 1=points | 2*=results ] + def.write_csv = 2; % final cms-file [ 0=dont write |1=write | 2=overwrite ] + def.write_xml = 1; % images base xml-file + def.sortQATm = 1; % sort QATm output + def.orgval = 0; % original QAM results (no marks) + def.avgfactor = 2; % + def.prefix = 'cat_'; % intensity scaled image + def.mprefix = 'm'; % prefix of the preprocessed image + def.process = 3; % used image [ 0=T1 | 1=mT1 | 2=avg | 3=both ] + def.calc_MPC = 0; + def.calc_STC = 0; + def.calc_MJD = 0; + def.method = 'spm'; + def.snspace = [100,7,3]; + def.nogui = exist('XT','var'); + def.MarkColor = cat_io_colormaps('marks+',40); +end + +function noise = estimateNoiseLevel(Ym,YM,r,rms,vx_vol) +% ---------------------------------------------------------------------- +% noise estimation within Ym and YM. +% ---------------------------------------------------------------------- + if ~exist('vx_vol','var') + vx_vol=[1 1 1]; + end + if ~exist('r','var') + r = 1; + else + r = min(10,max(max(vx_vol),r)); + end + if ~exist('rms','var') + rms = 1; + end + + Ysd = cat_vol_localstat(single(Ym),YM,r ,4); + Ysd2 = cat_vol_localstat(single(Ym),YM,r+1,4); % RD20210617: more stable for sub-voxel resolutions ? + Ysd = Ysd * mod(r,1) + (1-mod(r,1)) * Ysd2; % RD20210617: more stable for sub-voxel resolutions ? + %noise = cat_stat_nanstat1d(Ysd(YM).^rms,'median').^(1/rms); % RD20210617: + noise = cat_stat_kmeans(Ysd(YM),1); % RD20210617: more robust ? +end +%======================================================================= +function res_ECR = estimateECR0(Ym,Yp0,Tth,vx_vol) +%% estimateECR. Quanfify anatomical details by the normalized edge strength. +% +% old pure version for high quality segmentation input that works only well +% for the CAT12 AMAP segmenation + +% extend step by step by some details (eg. masking of problematic regions + + Ygrad = cat_vol_grad(max(Tth(2),min(1,Ym) .* (Yp0>0)) , vx_vol ); + res_ECR = cat_stat_nanmedian(Ygrad(Yp0(:)>2.05 & Yp0(:)<2.95),1); + +end +%======================================================================= + +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_stat_showslice_all.m",".m","3788","144","function cat_stat_showslice_all(vargin) +%cat_stat_showslice_all show 1 slice of all images +% +% FORMAT cat_stat_showslice_all +% +% slice has to be choosen in mm +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +rev = '$Rev$'; + +if nargin == 1 + P = char(vargin.data_vol); + scaling = vargin.scale; + slice_mm = vargin.slice; + orient = vargin.orient; +end + +if nargin < 1 + P = spm_select(Inf,'image','Select images'); + scaling = spm_input('Prop. scaling (e.g. for T1- or modulated images)?',1,'yes|no',[1 0],2); + slice_mm = spm_input('Slice [mm]?','+1','e',0,1); + orient = spm_input('Orientation',1,'axial|coronal|sagittal',[3 2 1],1); +end + +V = spm_vol(deblank(P)); +n = size(P,1); + +hold = 1; + +% voxelsize and origin +vx = sqrt(sum(V(1).mat(1:3,1:3).^2)); +if det(V(1).mat(1:3,1:3))<0, vx(1) = -vx(1); end +Orig = V(1).mat\[0 0 0 1]'; + +% range +range = ([1 V(1).dim(orient)] - Orig(orient))*vx(orient); + +% calculate slice from mm to voxel +sl = slice_mm/vx(orient)+Orig(orient); +while (sl < 1) || (sl > V(1).dim(orient)) + slice_mm = spm_input(['Slice (in mm) [' num2str(range(1)) '...' num2str(range(2)) ']'],1,'e',0); + sl = slice_mm/vx(orient)+Orig(orient); +end + +M = spm_matrix([0 0 0 0 0 0 1 1 1]); +switch orient + case 1, dim_array = [V(1).dim(2), V(1).dim(3)]; M(:,1:3) = M(:,[2 3 1]); + case 2, dim_array = [V(1).dim(3), V(1).dim(1)]; M(:,1:3) = M(:,[3 1 2]); + case 3, dim_array = [V(1).dim(1), V(1).dim(2)]; M(:,1:3) = M(:,[1 2 3]); +end + +M(orient,4) = sl; + +% global scaling +if scaling + gm=zeros(size(V,1),1); + disp('Calculating globals...'); + for i=1:size(V,1), gm(i) = spm_global(V(i)); end + gm_all = mean(gm); + for i=1:n + V(i).pinfo(1:2,:) = gm_all*V(i).pinfo(1:2,:)/gm(i); + end +end + +Y = zeros([dim_array,n]); + +%-Start progress plot +%----------------------------------------------------------------------- +cat_progress_bar('Init',n,'volumes completed'); +for i=1:n + d = spm_slice_vol(V(i),M,dim_array,[hold,NaN]); + if orient == 2 + d = flipud(rot90(d)); + end + Y(:,:,i) = d; + cat_progress_bar('Set',i); +end + +cat_progress_bar('Clear') + +Fgraph = spm_figure('GetWin','Graphics'); +FS = spm('FontSizes'); +figure(Fgraph); +spm_figure('Clear',Fgraph); +WIN = get(gcf,'Position'); +WIN = WIN(3)/WIN(4); +WIN = WIN/(dim_array(1)/dim_array(2)); +sizex = round(sqrt(n*WIN)); +sizey = round(n/sizex); + +while sizex * sizey < n, sizex = sizex + 1; end +if sizex * (sizey-1) >= n, sizey = sizey - 1; end + +img = zeros(sizex*dim_array(1),sizey*dim_array(2)); + +for i = 1:sizex + for j = 1:sizey + k = (sizex-i) + sizex*(j-1); + if k < n + img((i-1)*dim_array(1)+1:(i)*dim_array(1),(j-1)*dim_array(2)+1:(j)*dim_array(2)) = fliplr(Y(:,:,(k+1))); + end + end +end + +axes('Position',[0 0 1 0.96]) + +img = (rot90(img,3)); + +imagesc(img); + +% print filenames + +fs = FS(12); +if n>20, fs = FS(8); end +if n>60, fs = FS(6); end + +[tmp, names] = spm_str_manip(char(V.fname),'C'); +% case of one images or identical names just use the filename +if isempty(names), names = struct('s',spm_str_manip(tmp,'h'),'m',{{spm_str_manip(tmp,'t')}},'e',''); end + +fprintf('Compressed filenames: %s\n',tmp); + +for i = 1:sizex + for j = 1:sizey + k = (sizex-i) + sizex*(j-1); + if k < n && k >= 0 + text(round(sizex*dim_array(1)-((i-1)*dim_array(1)+(i)*dim_array(1))/2),(j-1)*dim_array(2)+fs+2,names.m{k+1},... + 'FontSize',fs,'Color','r','HorizontalAlignment','center'); + end + end +end + +axis off; +title(sprintf('Slice %dmm: %s*%s',slice_mm,names.s, names.e),'FontSize',FS(10),'FontWeight','Bold'); + +return +","MATLAB" +"Neurology","ChristianGaser/cat12","KmeansMex.m",".m","265","17","function [label, mu] = KmeansMex(src, n_classes) +% +% Christian Gaser +% $Id$ + +disp('Compiling KmeansMex.c') + +pth = fileparts(which(mfilename)); +p_path = pwd; +cd(pth); +mex -O KmeansMex.c Kmeans.c vollib.c +cd(p_path); + +[label, mu] = KmeansMex(src, n_classes); + +return +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_io_img2nii.m",".m","1628","45","function varargout=cat_io_img2nii(img,c,verb) +% ______________________________________________________________________ +% Convert img/hdr images to nii. +% +% varargout=cat_io_img2nii(img,c,verb) +% +% img .. list of *.img images +% c .. delete original data (default=1) +% verb .. display something (default=1) +% +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Revision$ $Date$ + if ~exist('img','var') || isempty(img) + img = spm_select(Inf ,'img','Select img files'); + end + if isa(img,'char'), img=cellstr(img); end + if ~exist('c','var'), c=1; end + if ~exist('verb','var'), verb=1; end + + n=numel(img); + if verb, cat_progress_bar('Init',n,'Filtering','Volumes Complete'); end + for i=1:n + [pp,ff]=spm_fileparts(img{i}); niifile = fullfile(pp,sprintf('%s.nii',ff)); + if ~exist(niifile,'file') + if verb, fprintf('%60s: ',img{i}); end; tic; + h = spm_vol(img{i}); + I = spm_read_vols(h); + h.fname(end-2:end)='nii'; + spm_write_vol(h,I); + if c==1, delete([img{i}(1:end-3) 'hdr']); delete([img{i}(1:end-3) 'img']); end + if nargout==1, varargout{1}{i}=h.fname; end + else + if verb, fprintf('%60s: still exist! ',img{i}); end + if nargout==1, varargout{1}{i}=niifile; end + end + if verb, cat_progress_bar('Set',i); fprintf('%5.2fs\n',toc); end + end + if verb, cat_progress_bar('Clear'); end +end","MATLAB" +"Neurology","ChristianGaser/cat12","spm_diffeo_old.c",".c","44754","1254","/* $Id$ */ +/* (c) John Ashburner (2011) */ + +#include ""mex.h"" +#include +#include ""shoot_optim3d.h"" +#include ""shoot_diffeo3d.h"" +#include ""shoot_multiscale.h"" +#include ""shoot_regularisers.h"" +#include ""shoot_dartel.h"" +#include ""shoot_bsplines.h"" +#include ""shoot_boundary.h"" + +static void boundary_mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) +{ + if ((nlhs<=1) && (nrhs==0)) + { + mwSize nout[] = {1,1,1}; + plhs[0] = mxCreateNumericArray(2,nout, mxDOUBLE_CLASS, mxREAL); + mxGetPr(plhs[0])[0] = get_bound(); + } + else if ((nrhs==1) && (nlhs==0)) + { + if (!mxIsNumeric(prhs[0]) || mxIsComplex(prhs[0]) || mxIsSparse(prhs[0]) || !mxIsDouble(prhs[0])) + mexErrMsgTxt(""Data must be numeric, real, full and double""); + set_bound(mxGetPr(prhs[0])[0]); + } +} + +static void cgs3_mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) +{ + const mwSize *dm; + int nit=1; + double tol=1e-10; + float *A, *b, *x, *scratch1, *scratch2, *scratch3; + static double param[] = {1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0}; + + if (nrhs!=3 || nlhs>1) + mexErrMsgTxt(""Incorrect usage""); + if (!mxIsNumeric(prhs[0]) || mxIsComplex(prhs[0]) || mxIsSparse(prhs[0]) || !mxIsSingle(prhs[0])) + mexErrMsgTxt(""Data must be numeric, real, full and single""); + if (mxGetNumberOfDimensions(prhs[0])!=4) mexErrMsgTxt(""Wrong number of dimensions.""); + if (mxGetDimensions(prhs[0])[3]!=6) + mexErrMsgTxt(""4th dimension of 1st arg must be 6.""); + + if (!mxIsNumeric(prhs[1]) || mxIsComplex(prhs[1]) || mxIsSparse(prhs[1]) || !mxIsSingle(prhs[1])) + mexErrMsgTxt(""Data must be numeric, real, full and single""); + if (mxGetNumberOfDimensions(prhs[1])!=4) mexErrMsgTxt(""Wrong number of dimensions.""); + dm = mxGetDimensions(prhs[1]); + if (dm[3]!=3) + mexErrMsgTxt(""4th dimension of second arg must be 3.""); + + if (mxGetDimensions(prhs[0])[0] != dm[0]) + mexErrMsgTxt(""Incompatible 1st dimension.""); + if (mxGetDimensions(prhs[0])[1] != dm[1]) + mexErrMsgTxt(""Incompatible 2nd dimension.""); + if (mxGetDimensions(prhs[0])[2] != dm[2]) + mexErrMsgTxt(""Incompatible 3rd dimension.""); + + if (!mxIsNumeric(prhs[2]) || mxIsComplex(prhs[2]) || mxIsSparse(prhs[2]) || !mxIsDouble(prhs[2])) + mexErrMsgTxt(""Data must be numeric, real, full and double""); + if (mxGetNumberOfElements(prhs[2]) != 10) + mexErrMsgTxt(""Third argument should contain vox1, vox2, vox3, param1, param2, param3, param4, param5, tol and nit.""); + + param[0] = 1/mxGetPr(prhs[2])[0]; + param[1] = 1/mxGetPr(prhs[2])[1]; + param[2] = 1/mxGetPr(prhs[2])[2]; + param[3] = mxGetPr(prhs[2])[3]; + param[4] = mxGetPr(prhs[2])[4]; + param[5] = mxGetPr(prhs[2])[5]; + param[6] = mxGetPr(prhs[2])[6]; + param[7] = mxGetPr(prhs[2])[7]; + + tol = mxGetPr(prhs[2])[8]; + nit = (int)(mxGetPr(prhs[2])[9]); + + plhs[0] = mxCreateNumericArray(4,dm, mxSINGLE_CLASS, mxREAL); + + A = (float *)mxGetPr(prhs[0]); + b = (float *)mxGetPr(prhs[1]); + x = (float *)mxGetPr(plhs[0]); + + scratch1 = (float *)mxCalloc(dm[0]*dm[1]*dm[2]*3,sizeof(float)); + scratch2 = (float *)mxCalloc(dm[0]*dm[1]*dm[2]*3,sizeof(float)); + scratch3 = (float *)mxCalloc(dm[0]*dm[1]*dm[2]*3,sizeof(float)); + + cgs3((mwSize *)dm, A, b, param, tol, nit, x,scratch1,scratch2,scratch3); + + mxFree((void *)scratch3); + mxFree((void *)scratch2); + mxFree((void *)scratch1); +} + +static void fmg3_mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) +{ + const mwSize *dm; + int cyc=1, nit=1; + float *A, *b, *x, *scratch; + static double param[] = {1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0}; + + if ((nrhs!=3 && nrhs!=4) || nlhs>1) + mexErrMsgTxt(""Incorrect usage""); + if (!mxIsNumeric(prhs[0]) || mxIsComplex(prhs[0]) || mxIsSparse(prhs[0]) || !mxIsSingle(prhs[0])) + mexErrMsgTxt(""Data must be numeric, real, full and single""); + if (mxGetNumberOfDimensions(prhs[0])!=4) mexErrMsgTxt(""Wrong number of dimensions.""); + if (mxGetDimensions(prhs[0])[3]!=6) + mexErrMsgTxt(""4th dimension of 1st arg must be 6.""); + + if (!mxIsNumeric(prhs[1]) || mxIsComplex(prhs[1]) || mxIsSparse(prhs[1]) || !mxIsSingle(prhs[1])) + mexErrMsgTxt(""Data must be numeric, real, full and single""); + if (mxGetNumberOfDimensions(prhs[1])!=4) mexErrMsgTxt(""Wrong number of dimensions.""); + dm = mxGetDimensions(prhs[1]); + if (dm[3]!=3) + mexErrMsgTxt(""4th dimension of second arg must be 3.""); + + if (mxGetDimensions(prhs[0])[0] != dm[0]) + mexErrMsgTxt(""Incompatible 1st dimension.""); + if (mxGetDimensions(prhs[0])[1] != dm[1]) + mexErrMsgTxt(""Incompatible 2nd dimension.""); + if (mxGetDimensions(prhs[0])[2] != dm[2]) + mexErrMsgTxt(""Incompatible 3rd dimension.""); + + if (!mxIsNumeric(prhs[2]) || mxIsComplex(prhs[2]) || mxIsSparse(prhs[2]) || !mxIsDouble(prhs[2])) + mexErrMsgTxt(""Data must be numeric, real, full and double""); + + if (mxGetNumberOfElements(prhs[2]) != 10) + mexErrMsgTxt(""Third argument should contain vox1, vox2, vox3, param1, param2, param3, param4, param5, ncycles and relax-its.""); + param[0] = 1/mxGetPr(prhs[2])[0]; + param[1] = 1/mxGetPr(prhs[2])[1]; + param[2] = 1/mxGetPr(prhs[2])[2]; + param[3] = mxGetPr(prhs[2])[3]; + param[4] = mxGetPr(prhs[2])[4]; + param[5] = mxGetPr(prhs[2])[5]; + param[6] = mxGetPr(prhs[2])[6]; + param[7] = mxGetPr(prhs[2])[7]; + cyc = mxGetPr(prhs[2])[8]; + nit = (int)(mxGetPr(prhs[2])[9]); + + { + /* Penalise absolute displacements slightly in case supplied Hessian is too small. + Extra penalty based on sum of values in centre of difference operator, scaled + by some arbitrary multiple of eps('single'). + */ + double v0 = param[0]*param[0], + v1 = param[1]*param[1], + v2 = param[2]*param[2], + lam1 = param[4], lam2 = param[5], + mu = param[6], lam = param[7], + w000, wx000, wy000, wz000; + w000 = lam2*(6*(v0*v0+v1*v1+v2*v2) +8*(v0*v1+v0*v2+v1*v2)) +lam1*2*(v0+v1+v2); + wx000 = 2*mu*(2*v0+v1+v2)/v0+2*lam + w000/v0; + wy000 = 2*mu*(v0+2*v1+v2)/v1+2*lam + w000/v1; + wz000 = 2*mu*(v0+v1+2*v2)/v2+2*lam + w000/v2; + param[3] += (wx000 + wy000 + wz000)*1.1921e-7; + } + + if (nrhs>=4) + { + int i; + float *x_orig; + if (!mxIsNumeric(prhs[3]) || mxIsComplex(prhs[3]) || mxIsSparse(prhs[3]) || !mxIsSingle(prhs[3])) + mexErrMsgTxt(""Data must be numeric, real, full and single""); + if (mxGetNumberOfDimensions(prhs[3])!=4) mexErrMsgTxt(""Wrong number of dimensions.""); + if (mxGetDimensions(prhs[3])[3]!=3) + mexErrMsgTxt(""4th dimension of fourth arg must be 3.""); + if (mxGetDimensions(prhs[3])[0] != dm[0]) + mexErrMsgTxt(""Incompatible 1st dimension.""); + if (mxGetDimensions(prhs[3])[1] != dm[1]) + mexErrMsgTxt(""Incompatible 2nd dimension.""); + if (mxGetDimensions(prhs[3])[2] != dm[2]) + mexErrMsgTxt(""Incompatible 3rd dimension.""); + + plhs[0] = mxCreateNumericArray(4,dm, mxSINGLE_CLASS, mxREAL); + x_orig = (float *)mxGetPr(prhs[3]); + x = (float *)mxGetPr(plhs[0]); + for(i=0; i1) + mexErrMsgTxt(""Incorrect usage""); + + if (!mxIsNumeric(prhs[0]) || mxIsComplex(prhs[0]) || mxIsSparse(prhs[0]) || !mxIsSingle(prhs[0])) + mexErrMsgTxt(""Data must be numeric, real, full and single""); + if (mxGetNumberOfDimensions(prhs[0])!=4) mexErrMsgTxt(""Wrong number of dimensions.""); + dm = mxGetDimensions(prhs[0]); + if (dm[3]!=3) + mexErrMsgTxt(""4th dimension of 1st arg must be 3.""); + + if (!mxIsNumeric(prhs[1]) || mxIsComplex(prhs[1]) || mxIsSparse(prhs[1]) || !mxIsDouble(prhs[1])) + mexErrMsgTxt(""Data must be numeric, real, full and double""); + + if (mxGetNumberOfElements(prhs[1]) != 10) + mexErrMsgTxt(""Second argument should contain vox1, vox2, vox3, param1, param2, param3, param4, param5, ncycles and relax-its.""); + param[0] = 1/mxGetPr(prhs[1])[0]; + param[1] = 1/mxGetPr(prhs[1])[1]; + param[2] = 1/mxGetPr(prhs[1])[2]; + param[3] = mxGetPr(prhs[1])[3]; + param[4] = mxGetPr(prhs[1])[4]; + param[5] = mxGetPr(prhs[1])[5]; + param[6] = mxGetPr(prhs[1])[6]; + param[7] = mxGetPr(prhs[1])[7]; + cyc = (int)(mxGetPr(prhs[1])[8]); + nit = (int)(mxGetPr(prhs[1])[9]); + + if (nrhs>=3) + { + int i; + float *x_orig; + if (!mxIsNumeric(prhs[2]) || mxIsComplex(prhs[2]) || mxIsSparse(prhs[2]) || !mxIsSingle(prhs[2])) + mexErrMsgTxt(""Data must be numeric, real, full and single""); + if (mxGetNumberOfDimensions(prhs[2])!=4) mexErrMsgTxt(""Wrong number of dimensions.""); + if (mxGetDimensions(prhs[2])[3]!=3) + mexErrMsgTxt(""4th dimension of third arg must be 3.""); + if (mxGetDimensions(prhs[2])[0] != dm[0]) + mexErrMsgTxt(""Incompatible 1st dimension.""); + if (mxGetDimensions(prhs[2])[1] != dm[1]) + mexErrMsgTxt(""Incompatible 2nd dimension.""); + if (mxGetDimensions(prhs[2])[2] != dm[2]) + mexErrMsgTxt(""Incompatible 3rd dimension.""); + + plhs[0] = mxCreateNumericArray(4,dm, mxSINGLE_CLASS, mxREAL); + x_orig = (float *)mxGetPr(prhs[2]); + x = (float *)mxGetPr(plhs[0]); + for(i=0; i1) + mexErrMsgTxt(""Incorrect usage""); + if (!mxIsNumeric(prhs[0]) || mxIsComplex(prhs[0]) || mxIsSparse(prhs[0]) || !mxIsSingle(prhs[0])) + mexErrMsgTxt(""Data must be numeric, real, full and single""); + if (mxGetNumberOfDimensions(prhs[0])!=4) mexErrMsgTxt(""Wrong number of dimensions.""); + if (mxGetDimensions(prhs[0])[3]!=6) + mexErrMsgTxt(""4th dimension of 1st arg must be 6.""); + dm = mxGetDimensions(prhs[0]); + A = (float *)mxGetPr(prhs[0]); + + if (!mxIsNumeric(prhs[1]) || mxIsComplex(prhs[1]) || mxIsSparse(prhs[1]) || !mxIsDouble(prhs[1])) + mexErrMsgTxt(""Second argument must be numeric, real, full and double""); + + if (mxGetNumberOfElements(prhs[1]) != 8) + mexErrMsgTxt(""Second argument should contain vox1, vox2, vox3, param1, param2, param3, param4, param5.""); + param[0] = 1/mxGetPr(prhs[1])[0]; + param[1] = 1/mxGetPr(prhs[1])[1]; + param[2] = 1/mxGetPr(prhs[1])[2]; + param[3] = mxGetPr(prhs[1])[3]; + param[4] = mxGetPr(prhs[1])[4]; + param[5] = mxGetPr(prhs[1])[5]; + param[6] = mxGetPr(prhs[1])[6]; + param[7] = mxGetPr(prhs[1])[7]; + + plhs[0] = mxCreateDoubleMatrix((mwSize)1, (mwSize)2, mxREAL); + t = (double *)mxGetPr(plhs[0]); + + t[0] = trapprox((mwSize *)dm, A, param); + t[1] = dm[0]*dm[1]*dm[2]*3 - t[0]; +} + +static void kernel_mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) +{ + mwSize dm[5]; + static double param[] = {1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0}; + + if (nrhs!=2 || nlhs>1) + mexErrMsgTxt(""Incorrect usage""); + + if (!mxIsNumeric(prhs[0]) || mxIsComplex(prhs[0]) || mxIsSparse(prhs[0]) || !mxIsDouble(prhs[0])) + mexErrMsgTxt(""Data must be numeric, real, full and double""); + if (!mxIsNumeric(prhs[1]) || mxIsComplex(prhs[1]) || mxIsSparse(prhs[1]) || !mxIsDouble(prhs[1])) + mexErrMsgTxt(""Data must be numeric, real, full and double""); + + if (mxGetNumberOfElements(prhs[0]) != 3) + mexErrMsgTxt(""Wrong number of dimensions.""); + dm[0] = (mwSize)(mxGetPr(prhs[0])[0]); + dm[1] = (mwSize)(mxGetPr(prhs[0])[1]); + dm[2] = (mwSize)(mxGetPr(prhs[0])[2]); + + if (mxGetNumberOfElements(prhs[1]) != 8) + mexErrMsgTxt(""Second argument should contain vox1, vox2, vox3, param1, param2, param3, param4, param5.""); + param[0] = 1/mxGetPr(prhs[1])[0]; + param[1] = 1/mxGetPr(prhs[1])[1]; + param[2] = 1/mxGetPr(prhs[1])[2]; + param[3] = mxGetPr(prhs[1])[3]; + param[4] = mxGetPr(prhs[1])[4]; + param[5] = mxGetPr(prhs[1])[5]; + param[6] = mxGetPr(prhs[1])[6]; + param[7] = mxGetPr(prhs[1])[7]; + + if (param[6]==0 && param[7]==0) + { + plhs[0] = mxCreateNumericArray(3,dm, mxSINGLE_CLASS, mxREAL); + } + else + { + dm[3] = 3; + dm[4] = 3; + plhs[0] = mxCreateNumericArray(5,dm, mxSINGLE_CLASS, mxREAL); + } + kernel(dm, param, (float *)mxGetPr(plhs[0])); +} + +static void rsz_mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) +{ + mwSize na[32], nc[32]; + int i, nd; + float *a, *b, *c; + if ((nrhs!=2) || (nlhs>1)) + mexErrMsgTxt(""Incorrect usage.""); + if (!mxIsNumeric(prhs[0]) || mxIsComplex(prhs[0]) || mxIsSparse(prhs[0]) || !mxIsSingle(prhs[0])) + mexErrMsgTxt(""Data must be numeric, real, full and single""); + if (!mxIsNumeric(prhs[1]) || mxIsComplex(prhs[1]) || mxIsSparse(prhs[1]) || !mxIsDouble(prhs[1])) + mexErrMsgTxt(""Data must be numeric, real, full and double""); + + if (mxGetNumberOfDimensions(prhs[0])>32) mexErrMsgTxt(""Too many dimensions.""); + na[0] = na[1] = na[2] = 1; + for(i=0; i1)) + mexErrMsgTxt(""Incorrect usage.""); + if (!mxIsNumeric(prhs[0]) || mxIsComplex(prhs[0]) || mxIsSparse(prhs[0]) || !mxIsSingle(prhs[0])) + mexErrMsgTxt(""Data must be numeric, real, full and single""); + + if (mxGetNumberOfDimensions(prhs[0])>3) mexErrMsgTxt(""Wrong number of dimensions.""); + na[0] = na[1] = na[2] = 1; + for(i=0; i1) + mexErrMsgTxt(""Incorrect usage""); + if (!mxIsNumeric(prhs[0]) || mxIsComplex(prhs[0]) || mxIsSparse(prhs[0]) || !mxIsSingle(prhs[0])) + mexErrMsgTxt(""Data must be numeric, real, full and single""); + if (!mxIsNumeric(prhs[1]) || mxIsComplex(prhs[1]) || mxIsSparse(prhs[1]) || !mxIsDouble(prhs[1])) + mexErrMsgTxt(""Data must be numeric, real, full and double""); + + nd = mxGetNumberOfDimensions(prhs[0]); + if (nd!=4) mexErrMsgTxt(""Wrong number of dimensions.""); + dm = mxGetDimensions(prhs[0]); + if (dm[3]!=3) + mexErrMsgTxt(""4th dimension must be 3.""); + + if (mxGetNumberOfElements(prhs[1]) != 8) + mexErrMsgTxt(""Parameters should contain vox1, vox2, vox3, param1, param2, param3, param4 and param5.""); + param[0] = 1/mxGetPr(prhs[1])[0]; + param[1] = 1/mxGetPr(prhs[1])[1]; + param[2] = 1/mxGetPr(prhs[1])[2]; + param[3] = mxGetPr(prhs[1])[3]; + param[4] = mxGetPr(prhs[1])[4]; + param[5] = mxGetPr(prhs[1])[5]; + param[6] = mxGetPr(prhs[1])[6]; + param[7] = mxGetPr(prhs[1])[7]; + + plhs[0] = mxCreateNumericArray(nd,dm, mxSINGLE_CLASS, mxREAL); + + vel2mom((mwSize *)dm, (float *)mxGetPr(prhs[0]), param, (float *)mxGetPr(plhs[0])); +} + +static void comp_mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) +{ + float *A, *B, *C; + mwSize nd, i; + const mwSize *dmp; + mwSize dm[3], mm; + + if (nrhs == 0) mexErrMsgTxt(""Incorrect usage""); + if (nrhs == 2) + { + if (nlhs > 1) mexErrMsgTxt(""Only 1 output argument required""); + } + else if (nrhs == 4) + { + if (nlhs > 2) mexErrMsgTxt(""Only 2 output argument required""); + } + else + mexErrMsgTxt(""Either 2 or 4 input arguments required""); + + for(i=0; i 1) mexErrMsgTxt(""Only 1 output argument required""); + } + else + mexErrMsgTxt(""Two input arguments required""); + + for(i=0; i4) mexErrMsgTxt(""Wrong number of dimensions.""); + dmf[0] = dmf[1] = dmf[2] = dmf[3] = 1; + for(i=0; i 2) mexErrMsgTxt(""Up to two output arguments required""); + + for(i=0; i<2; i++) + if (!mxIsNumeric(prhs[i]) || mxIsComplex(prhs[i]) || + mxIsSparse( prhs[i]) || !mxIsSingle(prhs[i])) + mexErrMsgTxt(""Data must be numeric, real, full and single""); + + nd = mxGetNumberOfDimensions(prhs[0]); + if (nd>4) mexErrMsgTxt(""Wrong number of dimensions.""); + dmf[0] = dmf[1] = dmf[2] = dmf[3] = 1; + for(i=0; i=3) + { + if (!mxIsNumeric(prhs[2]) || mxIsComplex(prhs[2]) || + mxIsSparse( prhs[2]) || !mxIsDouble(prhs[2])) + mexErrMsgTxt(""Data must be numeric, real, full and double""); + if (mxGetNumberOfElements(prhs[2])!= 3) + mexErrMsgTxt(""Output dimensions must have three elements""); + dmo[0] = (int)floor(mxGetPr(prhs[2])[0]); + dmo[1] = (int)floor(mxGetPr(prhs[2])[1]); + dmo[2] = (int)floor(mxGetPr(prhs[2])[2]); + } + else + { + dmo[0] = dmf[0]; + dmo[1] = dmf[1]; + dmo[2] = dmf[2]; + } + dmo[3] = dmf[3]; + + plhs[0] = mxCreateNumericArray(4,dmo, mxSINGLE_CLASS, mxREAL); + f = (float *)mxGetPr(prhs[0]); + Y = (float *)mxGetPr(prhs[1]); + po = (float *)mxGetPr(plhs[0]); + if (nlhs>=2) + { + plhs[1] = mxCreateNumericArray(3,dmo, mxSINGLE_CLASS, mxREAL); + so = (float *)mxGetPr(plhs[1]); + } + else + so = (float *)0; + + m = dmf[0]*dmf[1]*dmf[2]; + n = dmf[3]; + + push(dmo, m, n, Y, f, po, so); +} + +static void pushc_mexFunction(int nlhs, mxArray *plhs[], + int nrhs, const mxArray *prhs[]) +{ + float *f, *Y, *so, *po; + int nd, i, m, n; + mwSize dmf[4]; + mwSize dmo[4]; + const mwSize *dmy; + + if ((nrhs != 2) && (nrhs != 3)) + mexErrMsgTxt(""Two or three input arguments required""); + if (nlhs > 2) mexErrMsgTxt(""Up to two output arguments required""); + + for(i=0; i<2; i++) + if (!mxIsNumeric(prhs[i]) || mxIsComplex(prhs[i]) || + mxIsSparse( prhs[i]) || !mxIsSingle(prhs[i])) + mexErrMsgTxt(""Data must be numeric, real, full and single""); + + nd = mxGetNumberOfDimensions(prhs[0]); + if (nd>4) mexErrMsgTxt(""Wrong number of dimensions.""); + dmf[0] = dmf[1] = dmf[2] = dmf[3] = 1; + for(i=0; i=3) + { + if (!mxIsNumeric(prhs[2]) || mxIsComplex(prhs[2]) || + mxIsSparse( prhs[2]) || !mxIsDouble(prhs[2])) + mexErrMsgTxt(""Data must be numeric, real, full and double""); + if (mxGetNumberOfElements(prhs[2])!= 3) + mexErrMsgTxt(""Output dimensions must have three elements""); + dmo[0] = (int)floor(mxGetPr(prhs[2])[0]); + dmo[1] = (int)floor(mxGetPr(prhs[2])[1]); + dmo[2] = (int)floor(mxGetPr(prhs[2])[2]); + } + else + { + dmo[0] = dmf[0]; + dmo[1] = dmf[1]; + dmo[2] = dmf[2]; + } + dmo[3] = dmf[3]; + + plhs[0] = mxCreateNumericArray(4,dmo, mxSINGLE_CLASS, mxREAL); + f = (float *)mxGetPr(prhs[0]); + Y = (float *)mxGetPr(prhs[1]); + po = (float *)mxGetPr(plhs[0]); + if (nlhs>=2) + { + plhs[1] = mxCreateNumericArray(3,dmo, mxSINGLE_CLASS, mxREAL); + so = (float *)mxGetPr(plhs[1]); + } + else + so = (float *)0; + + m = dmf[0]*dmf[1]*dmf[2]; + n = dmf[3]; + + pushc(dmo, m, n, Y, f, po, so); +} + +static void pushc_grads_mexFunction(int nlhs, mxArray *plhs[], + int nrhs, const mxArray *prhs[]) +{ + float *f, *Y, *J, *po; + int nd, i; + mwSize dmf[4]; + mwSize dmo[4]; + const mwSize *dmy; + const mxArray *jacp = 0, *dimp = 0; + + if ((nrhs<2) || (nrhs>4)) + mexErrMsgTxt(""Two, three or four input arguments required""); + if (nlhs > 1) mexErrMsgTxt(""Up to one output argument required""); + + for(i=0; i<2; i++) + if (!mxIsNumeric(prhs[i]) || mxIsComplex(prhs[i]) || + mxIsSparse( prhs[i]) || !mxIsSingle(prhs[i])) + mexErrMsgTxt(""Data must be numeric, real, full and single""); + + nd = mxGetNumberOfDimensions(prhs[0]); + if (nd>4) mexErrMsgTxt(""Wrong number of dimensions.""); + dmf[0] = dmf[1] = dmf[2] = dmf[3] = 1; + for(i=0; i=3) + { + if (nrhs>=4) + { + jacp = prhs[2]; + dimp = prhs[3]; + } + else + { + if (mxIsDouble(prhs[2])) + dimp = prhs[2]; + else + jacp = prhs[2]; + } + } + + if (jacp) + { + nd = mxGetNumberOfDimensions(jacp); + if (nd!=5) mexErrMsgTxt(""Wrong number of dimensions.""); + dmy = mxGetDimensions(jacp); + if (dmy[0]!=dmf[0] || dmy[1]!=dmf[1] || dmy[2]!=dmf[2] || dmy[3]!=3 || dmy[4]!=3) + mexErrMsgTxt(""Incompatible dimensions.""); + J = (float *)mxGetPr(jacp); + } + else + J = (float *)0; + + if (dimp) + { + if (!mxIsNumeric(dimp) || mxIsComplex(dimp) || + mxIsSparse(dimp) || !mxIsDouble(dimp)) + mexErrMsgTxt(""Data must be numeric, real, full and double""); + if (mxGetNumberOfElements(prhs[3])!= 3) + mexErrMsgTxt(""Output dimensions must have three elements""); + dmo[0] = (int)floor(mxGetPr(dimp)[0]); + dmo[1] = (int)floor(mxGetPr(dimp)[1]); + dmo[2] = (int)floor(mxGetPr(dimp)[2]); + } + else + { + dmo[0] = dmf[0]; + dmo[1] = dmf[1]; + dmo[2] = dmf[2]; + } + dmo[3] = dmf[3]; + + plhs[0] = mxCreateNumericArray(4,dmo, mxSINGLE_CLASS, mxREAL); + po = (float *)mxGetPr(plhs[0]); + + pushc_grads(dmo, dmf, Y, J, f, po); +} + + +static void smalldef_mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) +{ + int nd; + const mwSize *dm; + float *v, *t; + double sc = 1.0; + + if (((nrhs != 1) && (nrhs != 2)) || (nlhs>2)) mexErrMsgTxt(""Incorrect usage.""); + if (!mxIsNumeric(prhs[0]) || mxIsComplex(prhs[0]) || mxIsSparse(prhs[0]) || !mxIsSingle(prhs[0])) + mexErrMsgTxt(""Data must be numeric, real, full and single""); + nd = mxGetNumberOfDimensions(prhs[0]); + if (nd!=4) mexErrMsgTxt(""Wrong number of dimensions.""); + dm = mxGetDimensions(prhs[0]); + if (dm[3]!=3) + mexErrMsgTxt(""4th dimension must be 3.""); + + if (nrhs>1) + { + if (!mxIsNumeric(prhs[1]) || mxIsComplex(prhs[1]) || mxIsSparse(prhs[1]) || !mxIsDouble(prhs[1])) + mexErrMsgTxt(""Data must be numeric, real, full and double""); + if (mxGetNumberOfElements(prhs[1]) > 1) + mexErrMsgTxt(""Params must contain one element""); + if (mxGetNumberOfElements(prhs[1]) >= 1) sc = (float)(mxGetPr(prhs[1])[0]); + } + + v = (float *)mxGetPr(prhs[0]); + + plhs[0] = mxCreateNumericArray(nd,dm, mxSINGLE_CLASS, mxREAL); + t = (float *)mxGetPr(plhs[0]); + + if (nlhs < 2) + { + smalldef((mwSize *)dm, sc, v, t); + } + else + { + float *J; + mwSize dmj[5]; + dmj[0] = dm[0]; + dmj[1] = dm[1]; + dmj[2] = dm[2]; + dmj[3] = 3; + dmj[4] = 3; + plhs[1] = mxCreateNumericArray(5,dmj, mxSINGLE_CLASS, mxREAL); + J = (float *)mxGetPr(plhs[1]); + smalldef_jac1((mwSize *)dm, sc, v, t, J); + } +} + +static void det_mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) +{ + int nd; + const mwSize *dm; + + if (((nrhs != 1)) || (nlhs>1)) mexErrMsgTxt(""Incorrect usage.""); + if (!mxIsNumeric(prhs[0]) || mxIsComplex(prhs[0]) || mxIsSparse(prhs[0]) || !mxIsSingle(prhs[0])) + mexErrMsgTxt(""Data must be numeric, real, full and single""); + nd = mxGetNumberOfDimensions(prhs[0]); + if (nd!=5) mexErrMsgTxt(""Wrong number of dimensions.""); + dm = mxGetDimensions(prhs[0]); + if (dm[3]!=3) mexErrMsgTxt(""4th dimension must be 3.""); + if (dm[4]!=3) mexErrMsgTxt(""5th dimension must be 3.""); + + plhs[0] = mxCreateNumericArray(3,dm, mxSINGLE_CLASS, mxREAL); + determinant((mwSize *)dm,(float *)mxGetPr(prhs[0]),(float *)mxGetPr(plhs[0])); +} + +static void minmax_div_mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) +{ + mwSize nd; + const mwSize *dm; + static mwSize nout[] = {1, 2, 1}; + + if ((nrhs != 1) || (nlhs>1)) mexErrMsgTxt(""Incorrect usage.""); + if (!mxIsNumeric(prhs[0]) || mxIsComplex(prhs[0]) || mxIsSparse(prhs[0]) || !mxIsSingle(prhs[0])) + mexErrMsgTxt(""Data must be numeric, real, full and single""); + nd = mxGetNumberOfDimensions(prhs[0]); + if (nd!=4) mexErrMsgTxt(""Wrong number of dimensions.""); + dm = mxGetDimensions(prhs[0]); + if (dm[3]!=3) mexErrMsgTxt(""4th dimension must be 3.""); + + plhs[0] = mxCreateNumericArray(2,nout, mxDOUBLE_CLASS, mxREAL); + minmax_div((mwSize *)dm,(float *)mxGetPr(prhs[0]),(double *)mxGetPr(plhs[0])); +} + +static void divergence_mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) +{ + mwSize nd; + const mwSize *dm; + + if ((nrhs != 1) || (nlhs>1)) mexErrMsgTxt(""Incorrect usage.""); + if (!mxIsNumeric(prhs[0]) || mxIsComplex(prhs[0]) || mxIsSparse(prhs[0]) || !mxIsSingle(prhs[0])) + mexErrMsgTxt(""Data must be numeric, real, full and single""); + nd = mxGetNumberOfDimensions(prhs[0]); + if (nd!=4) mexErrMsgTxt(""Wrong number of dimensions.""); + dm = mxGetDimensions(prhs[0]); + if (dm[3]!=3) mexErrMsgTxt(""4th dimension must be 3.""); + + plhs[0] = mxCreateNumericArray(3,dm, mxSINGLE_CLASS, mxREAL); + divergence((mwSize *)dm,(float *)mxGetPr(prhs[0]),(float *)mxGetPr(plhs[0])); +} + +static void def2det_mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) +{ + mwSize nd; + const mwSize *dm; + mwSize dm1[3]; + int pl = -1; + + if ((nrhs < 1) || (nrhs>2) || (nlhs>1)) mexErrMsgTxt(""Incorrect usage.""); + if (!mxIsNumeric(prhs[0]) || mxIsComplex(prhs[0]) || mxIsSparse(prhs[0]) || !mxIsSingle(prhs[0])) + mexErrMsgTxt(""Data must be numeric, real, full and single""); + nd = mxGetNumberOfDimensions(prhs[0]); + if (nd!=4) mexErrMsgTxt(""Wrong number of dimensions.""); + dm = mxGetDimensions(prhs[0]); + if (dm[3]!=3) mexErrMsgTxt(""4th dimension must be 3.""); + + dm1[0] = dm[0]; + dm1[1] = dm[1]; + dm1[2] = dm[2]; + + if (nrhs==2) + { + if (!mxIsNumeric(prhs[1]) || mxIsComplex(prhs[1]) || mxIsSparse(prhs[1]) || !mxIsDouble(prhs[1]) || (mxGetNumberOfElements(prhs[1])!=1)) + mexErrMsgTxt(""Slice number must be a numeric, real, full and double scalar""); + pl = (int)mxGetPr(prhs[1])[0]; + if (pl<1 || pl>=dm[2]) + mexErrMsgTxt(""Slice number is out of range""); + dm1[2] = 1; + } + + plhs[0] = mxCreateNumericArray(3,dm1, mxSINGLE_CLASS, mxREAL); + def2det((mwSize *)dm,(float *)mxGetPr(prhs[0]),(float *)mxGetPr(plhs[0]), pl); +} + +static void def2jac_mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) +{ + mwSize nd; + const mwSize *dm; + mwSize dm1[5]; + int pl = -1; + + if ((nrhs < 1) || (nrhs>2) || (nlhs>1)) mexErrMsgTxt(""Incorrect usage.""); + if (!mxIsNumeric(prhs[0]) || mxIsComplex(prhs[0]) || mxIsSparse(prhs[0]) || !mxIsSingle(prhs[0])) + mexErrMsgTxt(""Data must be numeric, real, full and single""); + nd = mxGetNumberOfDimensions(prhs[0]); + if (nd!=4) mexErrMsgTxt(""Wrong number of dimensions.""); + dm = mxGetDimensions(prhs[0]); + if (dm[3]!=3) mexErrMsgTxt(""4th dimension must be 3.""); + + dm1[0] = dm[0]; + dm1[1] = dm[1]; + dm1[2] = dm[2]; + dm1[3] = 3; + dm1[4] = 3; + if (nrhs==2) + { + if (!mxIsNumeric(prhs[1]) || mxIsComplex(prhs[1]) || mxIsSparse(prhs[1]) || !mxIsDouble(prhs[1]) || (mxGetNumberOfElements(prhs[1])!=1)) + mexErrMsgTxt(""Slice number must be a numeric, real, full and double scalar""); + pl = (int)mxGetPr(prhs[1])[0]; + if (pl<1 || pl>=dm[2]) + mexErrMsgTxt(""Slice number is out of range""); + dm1[2] = 1; + } + + plhs[0] = mxCreateNumericArray(5,dm1, mxSINGLE_CLASS, mxREAL); + def2jac((mwSize *)dm,(float *)mxGetPr(prhs[0]),(float *)mxGetPr(plhs[0]), pl); +} + +static void brc_mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) +{ + float *A, *B, *C; + int nd, i; + const mwSize *dm, *dm1; + + if (nrhs == 0) mexErrMsgTxt(""Incorrect usage""); + if (nrhs != 2) mexErrMsgTxt(""Incorrect number of input arguments""); + if (nlhs > 1) mexErrMsgTxt(""Only 1 output argument required""); + + for(i=0; i4 || nlhs > 1) mexErrMsgTxt(""Incorrect usage.""); + + if (!mxIsNumeric(prhs[0]) || mxIsComplex(prhs[0]) || mxIsSparse(prhs[0]) || !mxIsSingle(prhs[0])) + mexErrMsgTxt(""Data must be numeric, real, full and single""); + if (mxGetNumberOfDimensions(prhs[0])!=4) mexErrMsgTxt(""Wrong number of dimensions.""); + for(i=0; i<4; i++) + { + dim_y[i] = dim_iy[i] = mxGetDimensions(prhs[0])[i]; + } + if (dim_y[3]!=3) mexErrMsgTxt(""4th dimension of 1st arg must be 3.""); + + Y = (float *)mxGetData(prhs[0]); + + if (nrhs>1) + { + if (!mxIsNumeric(prhs[1]) || mxIsComplex(prhs[1]) || + mxIsComplex(prhs[1]) || !mxIsDouble(prhs[1]) || mxGetM(prhs[1]) * mxGetN(prhs[1]) != 3) + mexErrMsgTxt(""Output dimensions must be numeric, real, full, double and contain three elements.""); + + dim_iy[0] = (mwSize)mxGetPr(prhs[1])[0]; + dim_iy[1] = (mwSize)mxGetPr(prhs[1])[1]; + dim_iy[2] = (mwSize)mxGetPr(prhs[1])[2]; + + if (nrhs>2) get_mat(prhs[2],M1); else id_mat(M1); + if (nrhs>3) get_mat(prhs[3],M2); else id_mat(M2); + + } + + plhs[0] = mxCreateNumericArray(4, dim_iy,mxSINGLE_CLASS,mxREAL); + iY = (float *)mxGetData(plhs[0]); + + invdef(dim_y, Y, dim_iy, iY, M1, M2); +} + +#include + +void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) +{ + set_bound(get_bound()); + + if ((nrhs>=1) && mxIsChar(prhs[0])) + { + int buflen; + char *fnc_str; + buflen = mxGetNumberOfElements(prhs[0]); + fnc_str = (char *)mxCalloc(buflen+1,sizeof(mxChar)); + mxGetString(prhs[0],fnc_str,buflen+1); + + if (!strcmp(fnc_str,""comp"")) + { + mxFree(fnc_str); + comp_mexFunction(nlhs, plhs, nrhs-1, &prhs[1]); + } + else if (!strcmp(fnc_str,""vel2mom"")) + { + mxFree(fnc_str); + vel2mom_mexFunction(nlhs, plhs, nrhs-1, &prhs[1]); + } + else if (!strcmp(fnc_str,""smalldef"")) + { + mxFree(fnc_str); + smalldef_mexFunction(nlhs, plhs, nrhs-1, &prhs[1]); + } + else if (!strcmp(fnc_str,""samp"")) + { + mxFree(fnc_str); + samp_mexFunction(nlhs, plhs, nrhs-1, &prhs[1]); + } + else if (!strcmp(fnc_str,""push"")) + { + mxFree(fnc_str); + push_mexFunction(nlhs, plhs, nrhs-1, &prhs[1]); + } + else if (!strcmp(fnc_str,""pushc"")) + { + mxFree(fnc_str); + pushc_mexFunction(nlhs, plhs, nrhs-1, &prhs[1]); + } + else if (!strcmp(fnc_str,""pushg"") || !strcmp(fnc_str,""Ad*"")) + { + mxFree(fnc_str); + pushc_grads_mexFunction(nlhs, plhs, nrhs-1, &prhs[1]); + } + else if (!strcmp(fnc_str,""det"")) + { + mxFree(fnc_str); + det_mexFunction(nlhs, plhs, nrhs-1, &prhs[1]); + } + else if (!strcmp(fnc_str,""divrange"")) + { + mxFree(fnc_str); + minmax_div_mexFunction(nlhs, plhs, nrhs-1, &prhs[1]); + } + else if (!strcmp(fnc_str,""fmg"") || !strcmp(fnc_str,""FMG"")) + { + mxFree(fnc_str); + fmg3_mexFunction(nlhs, plhs, nrhs-1, &prhs[1]); + } + else if (!strcmp(fnc_str,""mom2vel"")) + { + mxFree(fnc_str); + fmg3_noa_mexFunction(nlhs, plhs, nrhs-1, &prhs[1]); + } + else if (!strcmp(fnc_str,""cgs"") || !strcmp(fnc_str,""CGS"")) + { + mxFree(fnc_str); + cgs3_mexFunction(nlhs, plhs, nrhs-1, &prhs[1]); + } + else if (!strcmp(fnc_str,""kernel"") || !strcmp(fnc_str,""kern"")) + { + mxFree(fnc_str); + kernel_mexFunction(nlhs, plhs, nrhs-1, &prhs[1]); + } + + else if (!strcmp(fnc_str,""restrict"")) + { + mxFree(fnc_str); + restrict_mexFunction(nlhs, plhs, nrhs-1, &prhs[1]); + } + else if (!strcmp(fnc_str,""rsz"") || !strcmp(fnc_str,""resize"")) + { + mxFree(fnc_str); + rsz_mexFunction(nlhs, plhs, nrhs-1, &prhs[1]); + } + else if (!strcmp(fnc_str,""brc"") || !strcmp(fnc_str,""bracket"")) + { + mxFree(fnc_str); + brc_mexFunction(nlhs, plhs, nrhs-1, &prhs[1]); + } + else if (!strcmp(fnc_str,""dartel"") || !strcmp(fnc_str,""DARTEL"") || !strcmp(fnc_str,""Dartel"")) + { + mxFree(fnc_str); + dartel_mexFunction(nlhs, plhs, nrhs-1, &prhs[1]); + } + else if (!strcmp(fnc_str,""Exp"") || !strcmp(fnc_str,""exp"")) + { + mxFree(fnc_str); + exp_mexFunction(nlhs, plhs, nrhs-1, &prhs[1]); + } + else if (!strcmp(fnc_str,""boundary"") || !strcmp(fnc_str,""bound"")) + { + mxFree(fnc_str); + boundary_mexFunction(nlhs, plhs, nrhs-1, &prhs[1]); + } + else if (!strcmp(fnc_str,""bsplinc"")) + { + mxFree(fnc_str); + bsplinc_mexFunction(nlhs, plhs, nrhs-1, &prhs[1]); + } + else if (!strcmp(fnc_str,""bsplins"")) + { + mxFree(fnc_str); + bsplins_mexFunction(nlhs, plhs, nrhs-1, &prhs[1]); + } + else if (!strcmp(fnc_str,""div"") || !strcmp(fnc_str,""divergence"")) + { + mxFree(fnc_str); + divergence_mexFunction(nlhs, plhs, nrhs-1, &prhs[1]); + } + else if (!strcmp(fnc_str,""def2det"") || !strcmp(fnc_str,""jacdet"")) + { + mxFree(fnc_str); + def2det_mexFunction(nlhs, plhs, nrhs-1, &prhs[1]); + } + else if (!strcmp(fnc_str,""def2jac"") || !strcmp(fnc_str,""jacobian"")) + { + mxFree(fnc_str); + def2jac_mexFunction(nlhs, plhs, nrhs-1, &prhs[1]); + } + else if (!strcmp(fnc_str,""invdef"") || !strcmp(fnc_str,""inv"")) + { + mxFree(fnc_str); + invdef_mexFunction(nlhs, plhs, nrhs-1, &prhs[1]); + } + else if (!strcmp(fnc_str,""trapprox"") || !strcmp(fnc_str,""traceapprox"")) + { + mxFree(fnc_str); + trapprox_mexFunction(nlhs, plhs, nrhs-1, &prhs[1]); + } + else + { + mxFree(fnc_str); + mexErrMsgTxt(""Option not recognised.""); + } + } + else + { + fmg3_mexFunction(nlhs, plhs, nrhs, prhs); + } +} + +","C" +"Neurology","ChristianGaser/cat12","cat_vol_inpaint.m",".m","8425","331","function out = cat_vol_inpaint(vol,niter,smooth,reduce,init,verb) +% ---------------------------------------------------------------------- +% This function uses the inpaintn function from Damien Garcia to replaces +% missing values (indicated by NaN or Inf) with interpolated/extrapolated +% values using discrete cosine transformation. +% It uses an iterative process baased on DCT and IDCT with 10 iterations +% as default. Optionally the output can be smoothed with a Gaussian kernel. +% Missing areas are initialized using Laplace method. +% +% out = cat_vol_inpaint(vol,niter,smooth,reduce,init,verb) +% +% vol .. input image +% niter .. number of iterations for inpainting +% smooth .. size for Gaussian smoothing +% reduce .. increase speed by using a reduced image for inpainting +% init .. use either euclidean distance (init=1) or Laplace method +% (init = 2, default) for initialization of missing values +% verb .. show progress bar (default=0) +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +if nargin < 2 + niter = 10; +end + +if nargin < 3 + smooth = 2; +end + +if nargin < 4 + reduce = 4; +end + +% use Laplace method for initialization +if nargin < 5 + init = 2; +end + +if nargin < 6 + verb = 0; +end + + +% check whether NaN or Inf exist +if 0 && sum(~isfinite(vol)) == 0 + error('Your image does not contain any areas for inpainting.') +end + +if reduce + [volr,resTr] = cat_vol_resize(vol,'reduceV',[1 1 1],reduce,32,'max'); + % set zero areas to NaN + volr(volr == 0) = NaN; + out = inpaintn(volr,niter,init,[],verb); + out = cat_vol_resize(out,'dereduceV',resTr); +else + % set zero areas to NaN + vol(vol == 0) = NaN; + out = inpaintn(vol,niter,init,[],verb); +end + +% optional smoothing +if smooth + out = cat_vol_smooth3X(out,smooth); +end + +end + +function y = inpaintn(x,n,init,m,verb) + +% INPAINTN Inpaint over missing data in N-D array +% Y = INPAINTN(X) replaces the missing data in X by extra/interpolating +% the non-missing elements. The non finite values (NaN or Inf) in X are +% considered as missing data. X can be any N-D array. +% +% INPAINTN (no input/output argument) runs the following 3-D example. +% +% Important note: +% -------------- +% INPAINTN uses an iterative process baased on DCT and IDCT. +% Y = INPAINTN(X,N) uses N iterations. By default, N = 100. If you +% estimate that INPAINTN did not totally converge, increase N: +% Y = INPAINTN(X,1000) +% +% Y = INPAINTN(X,N,INIT) allows to define the method to initialize +% missing values: +% 1 - euclidean distance +% 2 - Laplace method +% +% References (please refer to the two following references) +% ---------- +% 1) Garcia D, Robust smoothing of gridded data in one and higher +% dimensions with missing values. Computational Statistics & Data +% Analysis, 2010;54:1167-1178. +% download PDF +% 2) Wang G, Garcia D et al. A three-dimensional gap filling method for +% large geophysical datasets: Application to global satellite soil +% moisture observations. Environ Modell Softw, 2012;30:139-142. +% download PDF +% +% See also SMOOTHN, GRIDDATAN +% +% -- Damien Garcia -- 2010/06, last update 2017/08 +% website: www.BiomeCardio.com +% +% Copyright (c) 2014, Damien Garcia +% All rights reserved. + + +class0 = class(x); +x = double(x); + +if nargin==1 || isempty(n), n = 100; end + +sizx = size(x); +d = ndims(x); +Lambda = zeros(sizx); +for i = 1:d + siz0 = ones(1,d); + siz0(i) = sizx(i); + Lambda = bsxfun(@plus,Lambda,... + cos(pi*(reshape(1:sizx(i),siz0)-1)/sizx(i))); +end +Lambda = 2*(d-Lambda); + +% Initial condition +if nargin<3 || isempty(init), init = 2; end +W = isfinite(x); +if any(~W(:)) + [y,s0] = InitialGuess(x,isfinite(x),init); +else + y = x; + return +end +x(~W) = 0; + +% Smoothness parameters: from high to negligible values +s = logspace(s0,-6,n); + +RF = 2; % relaxation factor + +if nargin<4 || isempty(m), m = 2; end +Lambda = Lambda.^m; + +if verb, h = waitbar(0,'Inpainting...'); end +for i = 1:n + Gamma = 1./(1+s(i)*Lambda); + y = RF*idctn(Gamma.*dctn(W.*(x-y)+y)) + (1-RF)*y; + if verb, waitbar(i/n,h); end +end +if verb, close(h); end + +y(W) = x(W); +y = cast(y,class0); + +end + +%% Initial Guess +function [z,s0] = InitialGuess(y,I,init) + +% Euclidean distance +if init == 1 + [D,L] = cat_vbdist(single(I)); + z = y; + z(~I) = y(L(~I)); + s0 = 3; % note: s = 10^s0 +else % Laplace method + y(~I) = 0; + z = cat_vol_laplace3R(single(y),I,0.00001); + s0 = 6; % note: s = 10^s0 + +end + +end + +%% DCTN +function y = dctn(y) + +%DCTN N-D discrete cosine transform. +% Y = DCTN(X) returns the discrete cosine transform of X. The array Y is +% the same size as X and contains the discrete cosine transform +% coefficients. This transform can be inverted using IDCTN. +% +% Reference +% --------- +% Narasimha M. et al, On the computation of the discrete cosine +% transform, IEEE Trans Comm, 26, 6, 1978, pp 934-936. +% +% Example +% ------- +% RGB = imread('autumn.tif'); +% I = rgb2gray(RGB); +% J = dctn(I); +% imshow(log(abs(J)),[]), colormap(jet), colorbar +% +% The commands below set values less than magnitude 10 in the DCT matrix +% to zero, then reconstruct the image using the inverse DCT. +% +% J(abs(J)<10) = 0; +% K = idctn(J); +% figure, imshow(I) +% figure, imshow(K,[0 255]) +% +% -- Damien Garcia -- 2008/06, revised 2011/11 +% -- www.BiomeCardio.com -- + +y = double(y); +sizy = size(y); +y = squeeze(y); +dimy = ndims(y); + +% Some modifications are required if Y is a vector +if isvector(y) + dimy = 1; + if size(y,1)==1, y = y.'; end +end + +% Weighting vectors +w = cell(1,dimy); +for dim = 1:dimy + n = (dimy==1)*numel(y) + (dimy>1)*sizy(dim); + w{dim} = exp(1i*(0:n-1)'*pi/2/n); +end + +% --- DCT algorithm --- +if ~isreal(y) + y = complex(dctn(real(y)),dctn(imag(y))); +else + for dim = 1:dimy + siz = size(y); + n = siz(1); + y = y([1:2:n 2*floor(n/2):-2:2],:); + y = reshape(y,n,[]); + y = y*sqrt(2*n); + y = ifft(y,[],1); + y = bsxfun(@times,y,w{dim}); + y = real(y); + y(1,:) = y(1,:)/sqrt(2); + y = reshape(y,siz); + y = shiftdim(y,1); + end +end + +y = reshape(y,sizy); + +end + +%% IDCTN +function y = idctn(y) + +%IDCTN N-D inverse discrete cosine transform. +% X = IDCTN(Y) inverts the N-D DCT transform, returning the original +% array if Y was obtained using Y = DCTN(X). +% +% Reference +% --------- +% Narasimha M. et al, On the computation of the discrete cosine +% transform, IEEE Trans Comm, 26, 6, 1978, pp 934-936. +% +% Example +% ------- +% RGB = imread('autumn.tif'); +% I = rgb2gray(RGB); +% J = dctn(I); +% imshow(log(abs(J)),[]), colormap(jet), colorbar +% +% The commands below set values less than magnitude 10 in the DCT matrix +% to zero, then reconstruct the image using the inverse DCT. +% +% J(abs(J)<10) = 0; +% K = idctn(J); +% figure, imshow(I) +% figure, imshow(K,[0 255]) +% +% See also DCTN, IDSTN, IDCT, IDCT2, IDCT3. +% +% -- Damien Garcia -- 2009/04, revised 2011/11 +% -- www.BiomeCardio.com -- + +y = double(y); +sizy = size(y); +y = squeeze(y); +dimy = ndims(y); + +% Some modifications are required if Y is a vector +if isvector(y) + dimy = 1; + if size(y,1)==1 + y = y.'; + end +end + +% Weighing vectors +w = cell(1,dimy); +for dim = 1:dimy + n = (dimy==1)*numel(y) + (dimy>1)*sizy(dim); + w{dim} = exp(1i*(0:n-1)'*pi/2/n); +end + +% --- IDCT algorithm --- +if ~isreal(y) + y = complex(idctn(real(y)),idctn(imag(y))); +else + for dim = 1:dimy + siz = size(y); + n = siz(1); + y = reshape(y,n,[]); + y = bsxfun(@times,y,w{dim}); + y(1,:) = y(1,:)/sqrt(2); + y = ifft(y,[],1); + y = real(y*sqrt(2*n)); + I = (1:n)*0.5+0.5; + I(2:2:end) = n-I(1:2:end-1)+1; + y = y(I,:); + y = reshape(y,siz); + y = shiftdim(y,1); + end +end + +y = reshape(y,sizy); + +end +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_vol_pbtp.cpp",".cpp","8800","244","/* quasi-euclidean distance calculation + * _____________________________________________________________________________ + * [GMT,RPM,WMD,CSFD,II] = cat_vol_pbtp(SEG,WMD,CSFD[,opt]) + * + * SEG = (single) segment image with low and high boundary bd + * GMT = (single) thickness image + * RPM = (single) radial position map + * WMD = (single) CSF distance map + * CSFD = (single) CSF distance map + * II = (uint32) index of the inner (WM) boundary voxel + * + * opt.bd = (single) [low,high] boundary values (default 1.5 and 2.5) + * opt.CSFD = calculate CSFD + * opt.PVE = use PVE information (0=none,1=fast,2=exact) + * + * TODO: + * - eikonal distance for subsegmentation (region growing) + * - own labeling ( + * ______________________________________________________________________ + * + * Christian Gaser, Robert Dahnke + * Structural Brain Mapping Group (https://neuro-jena.github.io) + * Departments of Neurology and Psychiatry + * Jena University Hospital + * ______________________________________________________________________ + * $Id$ + */ + +#include ""mex.h"" +#include ""math.h"" +#include + +struct opt_type { + int CSFD; /* use CSFD */ + int PVE; /* 0, 1=fast, 2=exact */ + float LB, HB, LLB, HLB, LHB, HHB; /* boundary */ + int sL[3]; + // ... + } opt; + +float min(float a, float b) { + if (ab) return a; else return b; +} + +// get all values of the voxels which are in WMD-range (children of this voxel) +void pmax(const float GMT[], const float RPM[], const float SEG[], const float ND[], const float WMD, const float SEGI, const int sA, float & maximum) { + float T[27]; for (int i=0;i<27;i++) T[i]=-1; float n=0.0; maximum=WMD; + + /* the pure maximum */ + /* (GMT[i]<1e15) && (maximum < GMT[i]) && ((RPM[i]-ND[i]*1.25)<=WMD) && ((RPM[i]-ND[i]*0.5)>WMD) && (SEGI)>=SEG[i] && SEG[i]>1 && SEGI>1.66) */ + for (int i=0;i<=sA;i++) { + if ( ( GMT[i] < 1e15 ) && ( maximum < GMT[i] ) && /* thickness/WMD of neighbors should be larger */ + ( SEG[i] >= 0.0 ) && ( SEGI>1.2 && SEGI<=2.75 ) && /* projection range */ + ( ( ( RPM[i] - ND[i] * 1.2 ) <= WMD ) ) && /* upper boundary - maximum distance */ + ( ( ( RPM[i] - ND[i] * 0.5 ) > WMD ) || ( SEG[i]<1.5 ) ) && /* lower boundary - minimum distance - corrected values outside */ + ( ( ( (SEGI * max(1.0,min(1.2,SEGI-1)) ) >= SEG[i] ) ) || ( SEG[i]<1.5 ) ) ) /* for high values will project data over sulcal gaps */ + { maximum = GMT[i]; } + } + + /* the mean of the highest values*/ + float maximum2=maximum; float m2n=0; + for (int i=0;i<=sA;i++) { + if ( ( GMT[i] < 1e15 ) && ( (maximum - 1) < GMT[i] ) && + ( SEG[i] >= 0.0 ) && ( SEGI>1.2 && SEGI<=2.75 ) && + ( ( (RPM[i] - ND[i] * 1.2 ) <= WMD ) ) && + ( ( (RPM[i] - ND[i] * 0.5 ) > WMD ) || ( SEG[i]<1.5 ) ) && + ( ( ( (SEGI * max(1.0,min(1.2,SEGI-1)) ) >= SEG[i] ) ) || ( SEG[i]<1.5 ) ) ) + { maximum2 = maximum2 + GMT[i]; m2n++; } + } + if ( m2n > 0 ) maximum = (maximum2 - maximum)/m2n; + +} + + + + +// estimate x,y,z position of index i in an array size sx,sxy=sx*sy... +void ind2sub(int i, int *x, int *y, int *z, int snL, int sxy, int sy) { + /* not here ... + * if (i<0) i=0; + * if (i>=snL) i=snL-1; + */ + + *z = (int)floor( (double)i / (double)sxy ) ; + i = i % (sxy); + *y = (int)floor( (double)i / (double)sy ) ; + *x = i % sy ; +} + + + +// main function +void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { + if (nrhs<3) mexErrMsgTxt(""ERROR: not enought input elements\n""); + if (nrhs>4) mexErrMsgTxt(""ERROR: to many input elements.\n""); + if (nlhs>2) mexErrMsgTxt(""ERROR: to many output elements.\n""); + if (mxIsSingle(prhs[0])==0) mexErrMsgTxt(""ERROR: first input must be an 3d single matrix\n""); + + + // main information about input data (size, dimensions, ...) + const mwSize *sL = mxGetDimensions(prhs[0]); + mwSize sSEG[] = {sL[0],sL[1],sL[2]}; + const int dL = mxGetNumberOfDimensions(prhs[0]); + const int nL = mxGetNumberOfElements(prhs[0]); + const int x = sL[0]; + const int y = sL[1]; + const int xy = x*y; + const float s2 = sqrt(2.0); + const float s3 = sqrt(3.0); + const int nr = nrhs; + + // indices of the neighbor Ni (index distance) and euclidean distance NW + const int NI[] = { 0, -1,-x+1, -x,-x-1, -xy+1,-xy,-xy-1, -xy+x+1,-xy+x,-xy+x-1, -xy-x+1,-xy-x,-xy-x-1}; + const float ND[] = {0.0,1.0, s2,1.0, s2, s2,1.0, s2, s3, s2, s3, s3, s2, s3}; + const int sN = sizeof(NI)/4; + float DN[sN],DI[sN],GMTN[sN],WMDN[sN],SEGN[sN],DNm; + + float du, dv, dw, dnu, dnv, dnw, d, dcf, WMu, WMv, WMw, GMu, GMv, GMw, SEGl, SEGu, tmpfloat; + int ni,u,v,w,nu,nv,nw, tmpint, WMC=0, CSFC=0; + + // main volumes - actual without memory optimization ... + plhs[0] = mxCreateNumericArray(dL,sL,mxSINGLE_CLASS,mxREAL); + plhs[1] = mxCreateNumericArray(dL,sL,mxSINGLE_CLASS,mxREAL); + +/* not yet defined + plhs[2] = mxCreateNumericArray(dL,sL,mxSINGLE_CLASS,mxREAL); + plhs[3] = mxCreateNumericArray(dL,sL,mxSINGLE_CLASS,mxREAL); + plhs[4] = mxCreateNumericArray(dL,sL,mxUINT32_CLASS,mxREAL); +*/ + + // input variables + float*SEG = (float *)mxGetPr(prhs[0]); + float*WMD = (float *)mxGetPr(prhs[1]); + float*CSFD = (float *)mxGetPr(prhs[2]); + + /*if ( nrhs>1) { + tmpint = (int)mxGetScalar(mxGetField(prhs[1],1,""CSFD"")); printf(""X=%d"", tmpint); if ( tmpint!=NULL && (tmpint>=0 && tmpint<=1) ) opt.CSFD = tmpint; else opt.CSFD = 1; + tmpint = (int)mxGetScalar(mxGetField(prhs[1],1,""PVE"")); printf(""X=%d"", tmpint); if ( tmpint!=NULL && (tmpint>=0 && tmpint<=2) ) opt.PVE = tmpint; else opt.PVE = 2; + tmpfloat = (float)mxGetScalar(mxGetField(prhs[1],1,""LB"")); printf(""X=%d"", tmpfloat); if ( tmpfloat!=NULL ) opt.LB = tmpfloat; else opt.LB = 1.5; + tmpfloat = (float)mxGetScalar(mxGetField(prhs[1],1,""HB"")); printf(""X=%d"", tmpfloat); if ( tmpfloat!=NULL ) opt.HB = tmpfloat; else opt.HB = 2.5; + } + else */{ opt.CSFD = 1;opt.PVE = 2;opt.LB = 1.5;opt.HB = 2.5; } + opt.LLB=floor(opt.LB), opt.HLB=ceil(opt.LB), opt.LHB=floor(opt.HB), opt.HHB=ceil(opt.HB); + + // output variables + float *GMT = (float *)mxGetPr(plhs[0]); + float *RPM = (float *)mxGetPr(plhs[1]); + + // intitialisiation + for (int i=0;i=opt.HB ) WMC++; + if ( SEG[i]<=opt.LB ) CSFC++; + } + if (WMC==0) mexErrMsgTxt(""ERROR: no WM voxel\n""); + if (CSFC==0) opt.CSFD = 0; + + + +// thickness calcuation +// ============================================================================= + for (int i=0;iopt.LLB && SEG[i]=nL) || (abs(nu-u)>1) || (abs(nv-v)>1) || (abs(nw-w)>1)) ni=i; + GMTN[n] = GMT[ni]; WMDN[n] = RPM[ni]; SEGN[n] = SEG[ni]; + } + + // find minimum distance within the neighborhood + pmax(GMTN,WMDN,SEGN,ND,WMD[i],SEG[i],sN,DNm); + GMT[i] = DNm; + } + } + + for (int i=nL-1;i>=0;i--) { + if (SEG[i]>opt.LLB && SEG[i]=nL) || (abs(nu-u)>1) || (abs(nv-v)>1) || (abs(nw-w)>1)) ni=i; + GMTN[n] = GMT[ni]; WMDN[n] = RPM[ni]; SEGN[n] = SEG[ni]; + } + + // find minimum distance within the neighborhood + pmax(GMTN,WMDN,SEGN,ND,WMD[i],SEG[i],sN,DNm); + if ( GMT[i] < DNm && DNm>0 ) GMT[i] = DNm; + } + } + + for (int i=0;iopt.HB) GMT[i]=0; //WMD[i] + + + + + +// final setings... +// ============================================================================= + float CSFDc = 0, GMTi, CSFDi; // 0.125 + for (int i=0;i=opt.LB & SEG[i]<=opt.LB) { + GMTi = CSFD[i] + WMD[i]; + CSFDi = GMT[i] - WMD[i]; + + if ( CSFD[i]>CSFDi ) CSFD[i] = CSFDi; + else GMT[i] = GMTi; + } + } + + +// estimate RPM +// ============================================================================= + for (int i=0;i=opt.HB ) + RPM[i]=1.0; + else { + if ( SEG[i]<=opt.LB || GMT[i]==0.0 ) + RPM[i]=0.0; + else { + RPM[i] = (GMT[i] - WMD[i]) / GMT[i]; + if (RPM[i]>1.0) RPM[i]=1.0; + if (RPM[i]<0.0) RPM[i]=0.0; + } + } + } + +} + + +","C++" +"Neurology","ChristianGaser/cat12","cat_main1639.m",".m","70253","1480","function Ycls = cat_main1639(res,tpm,job) +% ______________________________________________________________________ +% Write out CAT preprocessed data +% +% FORMAT Ycls = cat_main(res,tpm,job) +% +% based on John Ashburners version of +% spm_preproc_write8.m 2531 2008-12-05 18:59:26Z john $ +% +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +%#ok<*ASGLU> + +update_intnorm = 0; %job.extopts.new_release; % RD202101: temporary parameter to control the additional intensity normalization + + +% if there is a breakpoint in this file set debug=1 and do not clear temporary variables +dbs = dbstatus; debug = 0; for dbsi=1:numel(dbs), if strcmp(dbs(dbsi).name,mfilename); debug = 1; break; end; end + +% error report structure +global cat_err_res + + +%% Update SPM/CAT parameter and add some basic variables +[res,job,VT,VT0,pth,nam,vx_vol,d] = cat_main_updatepara(res,tpm,job); + + + +%% Write SPM preprocessing results +% ------------------------------------------------------------------- +stime = cat_io_cmd('SPM preprocessing 2 (write)'); if job.extopts.verb>1, fprintf('\n'); end +stime2 = cat_io_cmd(' Write Segmentation','g5','',job.extopts.verb-1); +if ~isfield(res,'segsn') + [Ysrc,Ycls,Yy] = cat_spm_preproc_write8(res,zeros(max(res.lkp),4),zeros(1,2),[0 0],0,0); +else + % old SPM segment + [Ysrc,Ycls,Yy] = cat_spm_preproc_write(res.segsn,... + struct('biascor',[1 0 0],'cleanup',[1 0 0],'GM',[1 0 0],'WM',[1 0 0],'CSF',[1 0 0]) ); + YHD = cat_vol_morph( Ysrc > 0.5*min(res.mn(:)),'ldc',5 ) & (Ycls{1} + Ycls{2} + Ycls{3})<.5; + Ycls{4} = uint8(255 .* ( YHD & (Ysrc < 1*min(res.mn(:))))); + Ycls{5} = uint8(255 .* ( YHD & ~(Ysrc < 1*min(res.mn(:))))); + Ycls{6} = uint8(255) - (Ycls{1} + Ycls{2} + Ycls{3} + Ycls{4} + Ycls{5}); +end + +%% CAT vs. SPMpp Pipeline +if ~isfield(res,'spmpp') + %% + if isfield(res,'isiscaled') && res.isiscaled + % reset data + Ysrc = Ysrc * diff(res.intths) + res.intths(1); + res.image.dat = res.image.dat * diff(res.intths) + res.intths(1); + res.mn = res.mn * diff(res.intths) + res.intths(1); + res.Tth = res.Tth * diff(res.intths) + res.intths(1); + end + + + %% Update SPM results in case of reduced SPM preprocessing resolution + % ------------------------------------------------------------------- + if isfield(res,'redspmres') + [Ysrc,Ycls,Yy,res] = cat_main_resspmres(Ysrc,Ycls,Yy,res); + end + P = zeros([size(Ycls{1}) numel(Ycls)],'uint8'); + for i=1:numel(Ycls), P(:,:,:,i) = Ycls{i}; end + clear Ycls; + + + + %% Update SPM preprocessing + % ------------------------------------------------------------------- + % Fix class errors, brainmask etc. + % This is a large and important subfuction that represent the + % starting point of the refined CAT preprocessing. + % ------------------------------------------------------------------- + [Ysrc,Ycls,Yb,Yb0,job,res,T3th,stime2] = cat_main_updateSPM1639(Ysrc,P,Yy,tpm,job,res,stime,stime2); + + + %% Check the previous preprocessing in debug mode ### + % ------------------------------------------------------------------- + % If you want to see intermediate steps of the processing use the ""ds"" + % function: + % ds('l2','',vx_vol,Ym,Yb,Ym,Yp0,80) + % that display 4 images (unterlay, overlay, image1, image2) for one + % slice. The images were scaled in a range of 0 to 1. The overlay + % allows up to 20 colors + % ------------------------------------------------------------------- + if debug;; + Ym = (Ysrc - T3th(1)) / abs( diff(T3th(1:2:3)))*2/3 + 1/3; %#ok % only WM scaling + Yp0 = (single(Ycls{1})/255*2 + single(Ycls{2})/255*3 + single(Ycls{3})/255)/3; % label map + end + + + + %% Global (and local) intensity normalization and partioning + % --------------------------------------------------------------------- + % Global and local intensity corrections are the basis of most of the + % following functions. The global normalization based on the SPM tissue + % thresholds (res.mn) and were used anyway. For strong differences + % (mostly by the CSF) the median will used, because it is e.g. more + % stable. This will cause a warning by the cat_main_gintnorm. + % + % The local adaptive segmentation include a further bias correction + % and a global and local intensity correction. The local intensity + % correction refines the tissue maps to aproximate the local tissue + % peaks of WM (maximum-based), GM, and CSF. + % --------------------------------------------------------------------- + stime = cat_io_cmd('Global intensity correction'); + if all(vx_vol < 0.4 ) && strcmp(job.extopts.species,'human') %&& job.extopts.ignoreErros<2 % 1639 + % guaranty average (lower) resolution with >0.7 mm + % RD202006: This solution is not working when cat_main_gintnorm + % optimize the image (e.g. bias correction). Just calling + % Ym = cat_main_gintnorm(Ysrc,Tth); + % would not include the bias correction but also may use + % inacurate peaks that were estimated on slighly different + % image. So it is more save to turn it off because running + % the default case also in highres data only increase time + % and memory demands. + % Possible test subject: ADHD200/ADHD200_HC_BEJ_1050345_T1_SD000000-RS00.nii + [Ysrcr,resGI] = cat_vol_resize(Ysrc , 'reduceV', vx_vol, 0.6, 32, 'meanm'); + Ybr = cat_vol_resize(single(Yb), 'reduceV', vx_vol, 0.6, 32, 'meanm')>0.5; + Yclsr = cell(size(Ycls)); for i=1:6, Yclsr{i} = cat_vol_resize(Ycls{i},'reduceV',vx_vol,0.6,32,'meanm'); end + %Yyr = zeros([size(Ybr),3],'single'); for i=1:3, Yyr(:,:,:,i) = cat_vol_resize(Yy(:,:,:,i),'reduceV',vx_vol,0.6,32,'meanm'); end + [Ymr,Ybr,T3th,Tth,job.inv_weighting,noise] = cat_main_gintnorm1639(Ysrcr,Yclsr,Ybr,resGI.vx_volr,res,job.extopts); + clear Ymr Ybr Ysrcr Yclsr; + Ym = cat_main_gintnorm1639(Ysrc,Tth); + else + [Ym,Yb,T3th,Tth,job.inv_weighting,noise] = cat_main_gintnorm1639(Ysrc,Ycls,Yb,vx_vol,res,Yy,job.extopts); + end + job.extopts.inv_weighting = job.inv_weighting; + res.ppe.tths.gintnorm.T3th = T3th; + res.ppe.tths.gintnorm.Tth = Tth; + + % RD202101: additional intensity correction + if 0 && update_intnorm + [Ym,tmp,Tthm] = cat_main_update_intnorm(Ym,Ym,Yb,Ycls,job); + res.ppe.tths.uintnorm0postgintnorm.Tthm = Tthm; + clear tmp Tthm; + end + + + + % update in inverse case ... required for LAS + % + % ### include this in cat_main_gintnorm? + % + if job.inv_weighting +% Ysrc = Ym * Tth.T3th(5); Tth.T3th = Tth.T3thx * Tth.T3th(5); + if T3th(1)>T3th(3) && T3th(2)T3th(2) + Yp0toC = @(Yp0,c) 1-min(1,abs(Yp0-c)); + + Yp0 = single(Ycls{3})/255/3 + single(Ycls{1})/255*2/3 + single(Ycls{2})/255; + Yb2 = cat_vol_morph(Yp0>0.5,'lc',2); + prob = cat(4,cat_vol_ctype(Yb2.*Yp0toC(Ym*3,2)*255),... + cat_vol_ctype(Yb2.*Yp0toC(Ym*3,3)*255),... + cat_vol_ctype(Yb2.*Yp0toC(min(3,Ym*3),1)*255)); + + prob = cat_main_clean_gwc1639(prob,1,1); + + for ci=1:3, Ycls{ci} = prob(:,:,:,ci); end + clear prob; + end + Ysrc = Ym; Tth.T3thx(3:5) = 1/3:1/3:1; Tth.T3th = Tth.T3thx; T3th = 1/3:1/3:1; + end + if job.extopts.verb>2 + tpmci = 2; %tpmci + 1; + tmpmat = fullfile(pth,res.reportfolder,sprintf('%s_%s%02d%s.mat',nam,'write',tpmci,'postgintnorm')); + save(tmpmat,'Ysrc','Ycls','Ym','Yb','T3th','vx_vol'); + end + fprintf('%5.0fs\n',etime(clock,stime)); + + + + + %% Enhanced denoising with intensity (contrast) normalized data + % --------------------------------------------------------------------- + % After the intensity scaling and with correct information about the + % variance of the tissue, a further harder noise correction is meaningful. + % Finally, a stronger NLM-filter is better than a strong MRF filter! + % --------------------------------------------------------------------- + if job.extopts.NCstr~=0 + NCstr.labels = {'none','full','light','medium','strong','heavy'}; + NCstr.values = {0 1 2 -inf 4 5}; + stime = cat_io_cmd(sprintf('SANLM denoising after intensity normalization (%s)',... + NCstr.labels{find(cell2mat(NCstr.values)==job.extopts.NCstr,1,'first')})); + + % filter only within the brain mask for speed up + [Yms,Ybr,BB] = cat_vol_resize({Ym,Yb},'reduceBrain',vx_vol,round(2/cat_stat_nanmean(vx_vol)),Yb); Ybr = Ybr>0.5; + Yms = cat_vol_sanlm(struct('data',res.image0.fname,'verb',0,'NCstr',job.extopts.NCstr),res.image,1,Yms); + Ym(BB.BB(1):BB.BB(2),BB.BB(3):BB.BB(4),BB.BB(5):BB.BB(6)) = Yms .* Ybr + ... + Ym(BB.BB(1):BB.BB(2),BB.BB(3):BB.BB(4),BB.BB(5):BB.BB(6)) .* (1-Ybr); + clear Yms Ybr BB; + + if job.inv_weighting + Ysrc = Ym; + else + Ysrc = cat_main_gintnormi(Ym,Tth); + end + + fprintf('%5.0fs\n',etime(clock,stime)); + end + + + + + %% prepared for improved partitioning - RD20170320, RD20180416 + % Update the initial SPM normalization by a fast version of Shooting + % to improve the skull-stripping, the partitioning and LAS. + % We need stong deformations in the ventricle for the partitioning + % but low deformations for the skull-stripping. Moreover, it has to + % be really fast > low resolution (3 mm) and less iterations. + % The mapping has to be done for the TPM resolution, but we have to + % use the Shooting template for mapping rather then the TPM because + % of the cat12 atlas map. + % + % #### move fast shooting to the cat_main_updateSPM function #### + % + % RD20210307: Update of the Yy to the TMP but with the BB of the TPM. + finaffreg = 2; % final affine registration (1-GWM,2-BM,3-GM,4-WM) + if job.extopts.WMHC || job.extopts.SLC + %% + if ~debug, stime = cat_io_cmd(sprintf('Fast Optimized Shooting registration'),'','',job.extopts.verb); end + res2 = res; + job2 = job; + job2.extopts.bb = 0; % registration to TPM space + job2.extopts.verb = debug; % do not display process (people would may get confused) + job2.extopts.vox = abs(res.tpm(1).mat(1)); % TPM resolution to replace old Yy + job2.extopts.reg.affreg = finaffreg; % RD202306: do an addition registration based on the skull (i.e. sum(Ycls{1:3})) + % code is working but better result? + if job.extopts.regstr>0 + job2.extopts.regstr = 12; % lower resolution (2mm) + job2.extopts.reg.nits = 8; % less iterations + %job2.extopts.shootingtpms(3:end) = []; % remove high templates, we only need low frequency corrections .. NO! This would cause problems with the interpolation + res2.do_dartel = 2; % use shooting + else + fprintf('\n'); + job2.extopts.reg.iterlim = 1; % only 1-2 inner iterations + res2.do_dartel = 1; % use dartel + end + if isfield(res,'Ylesion') + [trans1,res.ppe.reginitp,res.ppe.Affine_SPMfinal] = cat_main_registration(job2,res2,Ycls(1:3),Yy,res.Ylesion); + else + [trans1,res.ppe.reginitp,res.ppe.Affine_SPMfinal] = cat_main_registration(job2,res2,Ycls(1:3),Yy); + end + Yy2 = trans1.warped.y; + if ~debug, clear job2 res2; end +%% + if 0 + %% quick CAT atlas test + YA0 = cat_vol_ctype( cat_vol_sample(res.tpm(1),job.extopts.cat12atlas{1},Yy ,0) ); + YA1 = cat_vol_ctype( cat_vol_sample(res.tpm(1),job.extopts.cat12atlas{1},Yy2,0) ); + ds('d2sm','',vx_vol,Ym/3+(single(YA0)/20),Ym/3+(single(YA1)/20),125) + end + + + % Shooting did not include areas outside of the boundary box + % + % ### add to cat_main_registration? + % + Ybd = true(size(Ym)); Ybd(3:end-2,3:end-2,3:end-2) = 0; Ybd(~isnan(Yy2(:,:,:,1))) = 0; Yy2(isnan(Yy2))=0; + for k1=1:3 + Yy2(:,:,:,k1) = Yy(:,:,:,k1) .* Ybd + Yy2(:,:,:,k1) .* (1-Ybd); + Yy2(:,:,:,k1) = cat_vol_approx(Yy2(:,:,:,k1),'nn',vx_vol,3); + end + Yy = Yy2; + clear Yy2 trans1; + if ~debug, fprintf('%5.0fs\n',etime(clock,stime)); end + end + + + Ymo = Ym; if debug, Yclso = Ycls; Ysrco = Ysrc; end + %% Local Intensity Correction + % RD202102: Extension of LAS to correct protocoll depending differences + % of cortical GM intensities due to myelination before and + % after the general call of the LAS function. + % > add this later to the LAS function inclusive the denoising + % > this may also work for T2/PD maps + if debug, Ym = Ymo; Ycls = Yclso; Ysrc = Ysrco; end + if job.extopts.LASstr>0 + if job.extopts.LASstr>1 + stime = cat_io_cmd(sprintf('Simplified Local adaptive segmentation (LASstr=%0.2f)',job.extopts.LASstr-1)); + else + stime = cat_io_cmd(sprintf('Local adaptive segmentation (LASstr=%0.2f)',job.extopts.LASstr)); + end + + % RD202102: Extension of LAS to correct protocoll depending differences + % of cortical GM intensities due to myelination. + if isfield(job.extopts,'LASmyostr') + LASmyostr = job.extopts.LASmyostr; + else + LASmyostr = 0; % job.extopts.LASstr; + end + + if LASmyostr + stime2 = cat_io_cmd(sprintf('\n LAS myelination correction (LASmyostr=%0.2f)',LASmyostr),'g5','',job.extopts.verb); + % It is better to avoid updating of the Ym and Ysrc here because some + % of the problems depend on inhomogenities that can be corrected by + % LAS and a final correct at the end. + % LASstr meaning: + % 0 - none, eps - only Ycls, 0.25 - Ycls + bias correction, .50/.75/1.0 - Ycls + BC + light/medium/strong post correction, ... + [Ym,Ysrc,Ycls,Ycor] = cat_main_correctmyelination(Ym,Ysrc,Ycls,Yb,vx_vol,res.image(1),T3th,LASmyostr,Yy,job.extopts.cat12atlas,res.tpm, res.image.fname); + fprintf('%6.0fs',etime(clock,stime2)); clear Ymx Ysrcx; + end + + % main call of LAS + if job.extopts.LASstr>1 + Ymi = cat_main_LASsimple(Ysrc,Ycls,T3th,job.extopts.LASstr); + else + try + [Ymi,Ym,Ycls] = cat_main_LAS(Ysrc,Ycls,Ym,Yb,Yy,T3th,res,vx_vol,job.extopts,Tth); + catch + cat_io_addwarning([mfilename ':cat_main_LAS'],'Error in cat_main_LAS use cat_main_LASsimple.',3,[1 1]); + Ymi = cat_main_LASsimple(Ysrc,Ycls,T3th,job.extopts.LASstr); + end + end + stime2 = clock; % not really correct but better than before + + % RD202102: update Ymi since the LAS correction is currently not local enough in case of artefacts + % RD202502: the correction is currently not working/tested for T2/PD/FLAIR + if LASmyostr >= .5 && ~job.extopts.inv_weighting + Ymi = max( min( Ymi , min( 2.25 , Ymi )*0.25 + 0.75*( 2.25 - 0.5 * LASmyostr) / 3 ) , Ymi - Ycor / 3 ); + clear Yp0; + end + + % ### include this in cat_main_LAS? ### + % + if job.extopts.NCstr~=0 + % noise correction of the local normalized image Ymi, whereas only small changes are expected in Ym by the WM bias correction + stimen = cat_io_cmd(sprintf(' SANLM denoising after LAS (%s)',... + NCstr.labels{find(cell2mat(NCstr.values)==job.extopts.NCstr,1,'first')}),'g5','',1,stime2); + + [Ymis,Ymior,BB] = cat_vol_resize({Ymi,Ymo},'reduceBrain',vx_vol,round(2/mean(vx_vol)),Yb); + Ymis = cat_vol_sanlm(struct('data',res.image0.fname,'verb',0,'NCstr',job.extopts.NCstr),res.image,1,Ymis); + + Yc = abs(Ymis - Ymior); Yc = Yc * 6 * min(2,max(0,abs(job.extopts.NCstr))); + spm_smooth(Yc,Yc,2./vx_vol); Yc = max(0,min(1,Yc)); clear Ymior; + % mix original and noise corrected image and go back to original resolution + Ybr = Yb(BB.BB(1):BB.BB(2),BB.BB(3):BB.BB(4),BB.BB(5):BB.BB(6)); + Ymi(BB.BB(1):BB.BB(2),BB.BB(3):BB.BB(4),BB.BB(5):BB.BB(6)) = ... + Ymi(BB.BB(1):BB.BB(2),BB.BB(3):BB.BB(4),BB.BB(5):BB.BB(6)) .* (1-Ybr) + ... + (1-Yc) .* Ymi(BB.BB(1):BB.BB(2),BB.BB(3):BB.BB(4),BB.BB(5):BB.BB(6)) .* Ybr + ... + Yc .* Ymis .* Ybr; + + % extreme background denoising to remove holes? + Ymis = cat_vol_median3(Ymi,Ymi>0 & Ymi<0.4,Ymi<0.4); Ymi = Ymi.*max(0.1,Ymi>0.4) + Ymis.*min(0.9,Ymi<=0.4); + Ymis = cat_vol_median3(Ym,Ym>0 & Ym<0.4,Ym<0.4); Ym = Ym.*max(0.1,Ym>0.4) + Ymis.*min(0.9,Ym<=0.4); + + clear Ymis; + else + stimen = stime; + end + + cat_io_cmd(' ','','',job.extopts.verb,stimen); clear stimenc + fprintf('%5.0fs\n',etime(clock,stime)); + else + Ymi = Ym; + end + if ~debug; clear Ysrc ; end + + if job.extopts.verb>2 + tpmci=tpmci+1; tmpmat = fullfile(pth,res.reportfolder,sprintf('%s_%s%02d%s.mat',nam,'write',tpmci,'postLAS')); + save(tmpmat,'Ysrc','Ycls','Ymi','Yb','T3th','vx_vol'); + end + + + % RD202101: additional intensity correction + if update_intnorm + try + [Ym,Ymi,Tthm,Tthmi] = cat_main_update_intnorm(Ym,Ymi,Yb,Ycls,job); + res.ppe.tths.uintnorm1postlas.Tthm = Tthm; + res.ppe.tths.uintnorm1postlas.Tthmi = Tthmi; + clear Tthm Tthmi; + catch + cat_io_cprintf('warn','Update of intensities failed!\n'); + res.ppe.tths.uintnorm1postlas.Tthm = nan; + res.ppe.tths.uintnorm1postlas.Tthmi = nan; + end + end + + + + + + %% Partitioning: + % --------------------------------------------------------------------- + % For most of the following adaptations further knowledge of special + % regions is helpfull. Also Ymi is maybe still a little bit inhomogen + % the alignment should work. Only strong inhomogenities can cause + % problems, especially for the blood vessel detection. + % But for bias correction the ROIs are important too, to avoid over + % corrections in special regions like the cerbellum and subcortex. + % --------------------------------------------------------------------- + stime = cat_io_cmd('ROI segmentation (partitioning)'); + if job.extopts.SLC + if isfield(res,'Ylesion') && sum(res.Ylesion(:)>0) + [Yl1,Ycls,YMF] = cat_vol_partvol(Ymi,Ycls,Yb,Yy,vx_vol,job.extopts,tpm.V,noise,job,res.Ylesion); %,Ydt,Ydti); + fprintf('%5.0fs\n',etime(clock,stime)); + else + [Yl1,Ycls,YMF] = cat_vol_partvol(Ymi,Ycls,Yb,Yy,vx_vol,job.extopts,tpm.V,noise,job,false(size(Ym))); + fprintf('%5.0fs\n',etime(clock,stime)); + if isfield(res,'Ylesion') && sum(res.Ylesion(:)==0) + cat_io_addwarning([mfilename ':SLC_noExpDef'],'SLC is set for manual lesion correction but no lesions were found!',1,[1 1]); + end + end + else + [Yl1,Ycls,YMF] = cat_vol_partvol(Ymi,Ycls,Yb,Yy,vx_vol,job.extopts,tpm.V,noise,job,false(size(Ym))); + fprintf('%5.0fs\n',etime(clock,stime)); + if job.extopts.expertgui && isfield(res,'Ylesion') && sum(res.Ylesion(:))>1000 && job.extopts.ignoreErrors < 2 && ... + ~(res.ppe.affreg.highBG || res.ppe.affreg.skullstripped) && strcmp('human',job.extopts.species) + cat_io_addwarning([mfilename ':SLC_noExpDef'],sprintf(['SLC is deactivated but there are %0.2f cm' ... + native2unicode(179, 'latin1') ' of voxels with zero value inside the brain!'],prod(vx_vol) .* sum(res.Ylesion(:)) / 1000 ),1,[1 1]); + end + end + if ~debug; clear YBG Ycr Ydt; end + + + + %% Blood Vessel Correction + % --------------------------------------------------------------------- + % Blood vessel correction has to be done before the segmentation to + % remove high frequency strutures and avoid missclassifications. + % Problems can occure for strong biased images, because the partioning + % has to be done before bias correction. + % Of course we only want to do this for highres T1 data! + % --------------------------------------------------------------------- + res.applyBVC = 0; + NS = @(Ys,s) Ys==s | Ys==s+1; + if job.extopts.BVCstr && ~job.inv_weighting && all(vx_vol<2); + % RD202306: test if the BVC is required + if job.extopts.BVCstr>0 && job.extopts.BVCstr<1 + res.applyBVC = ... + sum(NS(Yl1(:),job.extopts.LAB.BV)) > 1000 && ... + median(Ymi(NS(Yl1(:),job.extopts.LAB.BV))) > 0.75; + elseif job.extopts.BVCstr >= 1 % allways or old + res.applyBVC = 1; + end + + if job.extopts.expertgui > 1 % + BVCs = sprintf(' (BVCstr=%0.2f)',job.extopts.BVCstr); + else + BVCs = ''; + end + + if res.applyBVC + stime = cat_io_cmd(sprintf('Apply enhanced blood vessel correction%s',BVCs)); + Ybv = cat_vol_smooth3X(cat_vol_smooth3X( ... + NS(Yl1,7) .* (Ymi*3 - (1.5-(mod(job.extopts.BVCstr,1) + (job.extopts.BVCstr>0)))),0.3).^4,0.1)/3; + else + % here we are only correcting the super high intensity strucutres + stime = cat_io_cmd(sprintf('No enhanced blood vessel correction is required %s',BVCs)); + Ybv = (Ymi>1.1) .* cat_vol_smooth3X(cat_vol_smooth3X( ... + NS(Yl1,7) .* (Ymi*3 - (1.5-(mod(job.extopts.BVCstr,1) + (job.extopts.BVCstr>0)))),0.3).^4,0.1)/3; + end + + + %% correct src images + % - good result but no nice form ... + %Ymi = Ym; + Ymio = Ymi; + Ymi = max( min( max(1/3, 1 - Ybv/4), Ymi ), Ymi - Ybv*2/3 ); + for mi = 1:2, Ymi = cat_vol_median3(Ymi,Ybv > max(0,1 - mi/2) & Ymi~=Ymio ); end + Ymi = cat_vol_median3(Ymi,Ybv > 0); clear Ymio; + + %Ymi = max( min(1/3 + 1/3*cat_vol_morph(Ym>2.5/3 & NS(Yl1,job.extopts.LAB.BV),'dd',1.5,vx_vol) , Ymi) ,Ymi - Ybv*2/3); + % Ymis = cat_vol_smooth3X(Ymi); Ymi(Ybv>0.5) = Ymis(Ybv>0.5); clear Ymis; + + %% update classes + Ycls{1} = min(Ycls{1},cat_vol_ctype(255 - Ybv*127)); + Ycls{2} = min(Ycls{2},cat_vol_ctype(255 - Ybv*127)); + Ycls{3} = max(Ycls{3},cat_vol_ctype(127*Ybv)); + + fprintf('%5.0fs\n',etime(clock,stime)); + clear Ybv p0; + end + + + + %% gcut+: additional skull-stripping using graph-cut + % ------------------------------------------------------------------- + % For skull-stripping gcut is used in general, but a simple and very + % old function is still available as backup solution. + % Furthermore, both parts prepare the initial segmentation map for the + % AMAP function. + % ------------------------------------------------------------------- + if job.extopts.gcutstr>0 && job.extopts.gcutstr<=1 + try + stime = cat_io_cmd(sprintf('Skull-stripping using graph-cut (gcutstr=%0.2f)',job.extopts.gcutstr)); + [Yb,Yl1] = cat_main_gcut(Ymo,Yb,Ycls,Yl1,YMF,vx_vol,job.extopts); + + % extend gcut brainmask by brainmask derived from SPM12 segmentations if necessary + if ~job.inv_weighting, Yb = Yb | Yb0; end + + fprintf('%5.0fs\n',etime(clock,stime)); + catch %#ok + cat_io_addwarning([mfilename ':gcuterror'],'Unknown error in cat_main_gcut. Use old brainmask.',1,[1 1]); + job.extopts.gcutstr = 99; + end + end + + + + %% AMAP segmentation + % ------------------------------------------------------------------- + % Most corrections were done before and the AMAP routine is used with + % a low level of iterations and no further bias correction, because + % some images get tile artifacts. + % + % prob .. new AMAP segmentation (4D) + % ind* .. index elements to asign a subvolume + % + % ds('d2sm','',1,Ym,single(prob(:,:,:,1))/255/3 + single(prob(:,:,:,2))/255*2/3 + single(prob(:,:,:,3))/255,50); + % ------------------------------------------------------------------- + job.extopts.AMAPframing = 1; + if 0 && T3th(2) < T3th(3) % ## AMAPsharpening in T1 ## + %% RD202509: EXPERIMENTAL: sharpening for AMAP to improve gyral structures in surface reconstruction + % - improves some case but is worse for others + % maybe helpful in regions that too thick and if the quality is ok + % difficult in thin regions + % - correct only thick(er) regions + % - correct only cortical regions + Yp0 = (single(Ycls{1})/255*2 + single(Ycls{2})/255*3 + single(Ycls{3})/255); % label map + Yct = NS(Yl1,1) | NS(Yl1,3); + + Ywd0 = cat_vbdist(single(Yp0>2.25),Yp0>1.25)/2 + cat_vbdist(single(Yp0>2.75),Yp0>1.25)/2; + Ycd0 = cat_vbdist(single(Yp0<1.25),Yp0<2.75)/2 + cat_vbdist(single(Yp0<1.75),Yp0<2.75)/2; + + % raw thickness maps + Ygmtw0 = cat_vol_pbtp( round(Yp0) , Ywd0, Ycd0); Ygmtw0(Ygmtw0>1000) = 0; + Ygmtc0 = cat_vol_pbtp( 4-round(Yp0) , Ycd0, Ywd0); Ygmtc0(Ygmtc0>1000) = 0; + + Ygmtmin = min(Ygmtw0,Ygmtc0); Ygmtmin = cat_vol_approx(Ygmtmin); + Ygmtmax = max(Ygmtw0,Ygmtc0); Ygmtmax = cat_vol_approx(Ygmtmax); + + Ywd0 = Ywd0 .* mean(vx_vol); Ygmtmin = Ygmtmin .* mean(vx_vol); + Ycd0 = Ycd0 .* mean(vx_vol); Ygmtmax = Ygmtmax .* mean(vx_vol); + + %% refine WM + Ysc = max(2/3,Ymi) - smooth3(max(2/3,Ymi)); % WM focus + Ymi = Ymi.*(1-Yb) + min(Yb,Ymi + max(0,Ysc) .* (smooth3(Ymi)<2.75) .* max(0,min(4,Ygmtmax - Ygmtmin)*4) .* max(0,Ycd0-Ygmtmin/2) .* Yct); % only enhance gyri and only correct in regions that would become GM, ie. thicker) + + %Ysc = min(2/3,Ymi) - smooth3(min(2/3,Ymi)); % CSF focus + %Ymi = Ymi + min(0,Ysc) .* (smooth3(Ymi)<2.1 & smooth3(Ymi)>1.5) .* max(0,Ygmtmax - Ygmtmin) .* max(0,Ywd0-1.5) .* Yct; % only enhance gyri and only correct in regions that would become GM, ie. thicker) + end + [prob,indx,indy,indz] = cat_main_amap1639(Ymi,Yb,Yb0,Ycls,job,res); + + + % RD202101: Update image intensity normalization based on the the AMAP + % segmentation but not the AMAP thresholds + if update_intnorm + [Ym,Ymi,Tthm,Tthmi] = cat_main_update_intnorm(Ym,Ymi,Yb,prob,job,0,indx,indy,indz); + res.ppe.tths.uintnorm2postamap.Tthm = Tthm; + res.ppe.tths.uintnorm2postamap.Tthmi = Tthmi; + clear Tthm Tthmi; + end + + + + %% Final Cleanup + % -------------- ----------------------------------------------------- + % There is one major parameter to control the strength of the cleanup. + % As far as the cleanup has a strong relation to the skull-stripping, + % cleanupstr is controlled by the gcutstr. + % + % Yp0ox = single(prob(:,:,:,1))/255*2 + single(prob(:,:,:,2))/255*3 + single(prob(:,:,:,3))/255; + % Yp0o = zeros(d,'single'); Yp0o(indx,indy,indz) = Yp0ox; + % Yp0 = zeros(d,'uint8'); Yp0(indx,indy,indz) = Yp0b; + % ------------------------------------------------------------------- + if job.extopts.expertgui>1 && job.extopts.verb + for i=1:size(prob,4), pr = prob(:,:,:,i); ppe.AMAPvols(i) = cat_stat_nansum(single(pr(:)))/255 .* prod(vx_vol) / 1000; end; clear pr + cat_io_cprintf('blue',sprintf(' AMAP volumes (CGW=TIV; in mm%s): %6.2f + %6.2f + %6.2f = %4.0f\n',... + native2unicode(179, 'latin1'),ppe.AMAPvols([3 1 2]),sum(ppe.AMAPvols(1:3)))); + end + if job.extopts.cleanupstr>0 + % display voluminas + if job.extopts.cleanupstr < 2 % use cleanupstr==2 to use only the old cleanup + prob = cat_main_clean_gwc1639(prob,min(1,job.extopts.cleanupstr*2/mean(vx_vol))); % default cleanup + else + prob = cat_main_clean_gwc1639(prob,min(1,job.extopts.cleanupstr*2/mean(vx_vol)),0); % old cleanup + end + if job.extopts.cleanupstr < 2 % use cleanupstr==2 to use only the old cleanup + [Ycls,Yp0b] = cat_main_cleanup(Ycls,prob,Yl1(indx,indy,indz),... + Ymo(indx,indy,indz),job.extopts,job.inv_weighting,vx_vol,indx,indy,indz,res.ppe.affreg.skullstripped); % new cleanup + else + for i=1:3, Ycls{i}(:) = 0; Ycls{i}(indx,indy,indz) = prob(:,:,:,i); end + Yp0b = Yb(indx,indy,indz); + end + if job.extopts.expertgui>1 && job.extopts.verb + for i=1:numel(Ycls), ppe.Finalvols(i) = cat_stat_nansum(single(Ycls{i}(:)))/255 .* prod(vx_vol) / 1000; end; + cat_io_cprintf('blue',sprintf(' Final volumes (CGW=TIV; in mm%s): %6.2f + %6.2f + %6.2f = %4.0f\n',... + native2unicode(179, 'latin1'),ppe.Finalvols([3 1 2]),sum(ppe.Finalvols(1:3)))); + end + else + for i=1:3, Ycls{i}(:) = 0; Ycls{i}(indx,indy,indz) = prob(:,:,:,i); end + Yp0b = Yb(indx,indy,indz); + end + if ~debug; clear Ymo; end + clear prob + + + + %% ------------------------------------------------------------------- + % Correction of WM hyperintensities + % ------------------------------------------------------------------- + % The correction of WMH should be important for a correct normalization. + % It is only important to close the mayor WMH structures, and further + % closing can lead to problems with small gyri. So keep it simple here + % and maybe add further refinements in the partitioning function. + % ------------------------------------------------------------------- + LAB = job.extopts.LAB; + Yp0 = zeros(d,'uint8'); Yp0(indx,indy,indz) = Yp0b; + qa.software.version_segment = strrep(mfilename,'cat_main',''); % if cat_main# save the # revision number + if isfield(res,'spmpp') && res.spmpp, qa.software.version_segment = 'SPM'; end % if SPM segmentation is used as input + [cat_err_res.init.Yp0,cat_err_res.init.BB] = cat_vol_resize(Yp0,'reduceBrain',vx_vol,2,Yp0>0.5); + clear Ywmhrel Yp0 + + + + % correction for normalization [and final segmentation] + if ( (job.extopts.WMHC && job.extopts.WMHCstr>0) || job.extopts.SLC) && ~job.inv_weighting + % display something + %{ + if job.extopts.WMHC==1 + cat_io_cmd(sprintf('Internal WMH correction for spatial normalization')); % (WMHCstr=%0.2f)',job.extopts.WMHCstr)); + elseif job.extopts.WMHC>1 + cat_io_cmd(sprintf('Permanent WMH correction')); % (WMHCstr=%0.2f)',job.extopts.WMHCstr)); + end + fprintf('\n'); + if job.extopts.SLC==1 + cat_io_cmd('Internal stroke lesion correction for spatial normalization'); + elseif job.extopts.SLC>1 + cat_io_cmd('Permanent stroke lesion correction'); + end + fprintf('\n'); + %} + + % prepare correction map + Ynwmh = NS(Yl1,LAB.TH) | NS(Yl1,LAB.BG) | NS(Yl1,LAB.HC) | NS(Yl1,LAB.CB) | NS(Yl1,LAB.BS); + Ynwmh = cat_vol_morph(cat_vol_morph( Ynwmh, 'dd', 8 , vx_vol),'dc',12 , vx_vol) & ... + ~cat_vol_morph( NS(Yl1,LAB.VT), 'dd', 4 , vx_vol); + Ywmh = cat_vol_morph( Ycls{7}>0, 'dd', 1.5); + Ywmh = Ycls{7}>0 | (~Ynwmh & (Ycls{2}==255 | ... + cat_vol_morph( cat_vol_morph(Ycls{2}>128 | Ywmh,'ldc',1) ,'de' , 1.5))); + Ywmh = Ywmh .* cat_vol_smooth3X(Ywmh,0.5); % smooth inside + + + %% transfer tissue from GM and CSF to WMH + if job.extopts.SLC>0 + % WMHs and lesions + if job.extopts.SLC==1 + Yls = res.Ylesion; + Ycls{8} = cat_vol_ctype( Yls*255 ); + elseif job.extopts.SLC==2 + Yls = NS(Yl1,LAB.LE)>0.5 | res.Ylesion; + Ycls{8} = cat_vol_ctype( Yls .* single(Ycls{1}) + Yls .* single(Ycls{3}) + 255*single(res.Ylesion) ); + end + Ycls{7} = cat_vol_ctype( Ywmh .* single(Ycls{1}) + Ywmh .* single(Ycls{3})); + Ycls{1} = cat_vol_ctype( single(Ycls{1}) .* (1 - Ywmh - single(Yls)) ); + Ycls{3} = cat_vol_ctype( single(Ycls{3}) .* (1 - Ywmh - single(Yls)) ); + else + % only WMHS + Ycls{7} = cat_vol_ctype( Ywmh .* single(Ycls{1}) + Ywmh .* single(Ycls{3})); + Ycls{1} = cat_vol_ctype( single(Ycls{1}) .* (1 - Ywmh) ); + Ycls{3} = cat_vol_ctype( single(Ycls{3}) .* (1 - Ywmh) ); + end + if ~debug, clear Ynwmh Ywmh Yls; end + + + % different types of WMH correction as GM, WM or extra class + % different types of lesion correction as CSF or extra class + if numel(Ycls)>7 && job.extopts.SLC==1 + if job.extopts.WMHC<2 + Yp0b = cat_vol_ctype(single(Ycls{1})*2/5 + single(Ycls{2})*3/5 + single(Ycls{3})*1/5 + single(Ycls{7})*2/5 + single(Ycls{8})*1/5,'uint8'); + elseif job.extopts.WMHC==2 + Yp0b = cat_vol_ctype(single(Ycls{1})*2/5 + single(Ycls{2})*3/5 + single(Ycls{3})*1/5 + single(Ycls{7})*3/5 + single(Ycls{8})*1/5,'uint8'); + elseif job.extopts.WMHC==3 + Yp0b = cat_vol_ctype(single(Ycls{1})*2/5 + single(Ycls{2})*3/5 + single(Ycls{3})*1/5 + single(Ycls{7})*4/5 + single(Ycls{8})*1/5,'uint8'); + end + elseif numel(Ycls)>7 && job.extopts.SLC==2 + if job.extopts.WMHC<2 + Yp0b = cat_vol_ctype(single(Ycls{1})*2/5 + single(Ycls{2})*3/5 + single(Ycls{3})*1/5 + single(Ycls{7})*2/5 + single(Ycls{8})*1.5/5,'uint8'); + elseif job.extopts.WMHC==2 + Yp0b = cat_vol_ctype(single(Ycls{1})*2/5 + single(Ycls{2})*3/5 + single(Ycls{3})*1/5 + single(Ycls{7})*3/5 + single(Ycls{8})*1.5/5,'uint8'); + elseif job.extopts.WMHC==3 + Yp0b = cat_vol_ctype(single(Ycls{1})*2/5 + single(Ycls{2})*3/5 + single(Ycls{3})*1/5 + single(Ycls{7})*4/5 + single(Ycls{8})*1.5/5,'uint8'); + end + else % no stroke lesion handling + if job.extopts.WMHC<2 + Yp0b = cat_vol_ctype(single(Ycls{1})*2/5 + single(Ycls{2})*3/5 + single(Ycls{3})*1/5 + single(Ycls{7})*2/5,'uint8'); + elseif job.extopts.WMHC==2 + Yp0b = cat_vol_ctype(single(Ycls{1})*2/5 + single(Ycls{2})*3/5 + single(Ycls{3})*1/5 + single(Ycls{7})*3/5,'uint8'); + elseif job.extopts.WMHC==3 + Yp0b = cat_vol_ctype(single(Ycls{1})*2/5 + single(Ycls{2})*3/5 + single(Ycls{3})*1/5 + single(Ycls{7})*4/5,'uint8'); + end + end + + else + Yp0b = cat_vol_ctype(single(Ycls{1})*2/5 + single(Ycls{2})*3/5 + single(Ycls{3})*1/5,'uint8'); + end + + % update error report structure + [cat_err_res.init.Yp0,cat_err_res.init.BB] = cat_vol_resize(Yp0b,'reduceBrain',vx_vol,2,Yp0b>0.5); + + % store smaller version + Yp0b = Yp0b(indx,indy,indz); + clear Yclsb; + + if job.extopts.verb>2 + tpmci=tpmci+1; tmpmat = fullfile(pth,res.reportfolder,sprintf('%s_%s%02d%s.mat',nam,'write',tpmci,'preDartel')); + save(tmpmat,'Yp0','Ycls','Ymi','T3th','vx_vol','Yl1'); + clear Yp0; + end + +else +%% SPM segmentation input +% ------------------------------------------------------------------------ +% Prepare data for registration and surface processing. +% We simply use the SPM segmentation as it is without further modelling of +% a PVE or other refinements. +% ------------------------------------------------------------------------ + [Ycls,Ym,Ymi,Yp0b,Yb0,Yl1,Yy,YMF,indx,indy,indz,qa,job] = ... + cat_main_SPMpp(Ysrc,Ycls,Yy,job,res,stime); + fprintf('%5.0fs\n',etime(clock,stime)); + finaffreg = 0; % final affine registration (1-GWM,2-BM,3-GM,4-WM) +end + + + +%% --------------------------------------------------------------------- +% Spatial Registration with Dartel or Shooting +% --------------------------------------------------------------------- + if res.do_dartel + Yclsd = Ycls(1:3); % use only GM and WM for deformation + if job.extopts.WMHC>0 && numel(Ycls)>6 + Yclsd{2} = cat_vol_ctype(min(255,single(Ycls{2}) + single(Ycls{7}))); % set WMHs as WM in some cases + end + + if job.extopts.SLC && isfield(res,'Ylesion') && sum(res.Ylesion(:)>0) + % lesion detection in the original space with the original data + LSstr = 0.5; + Yvt = cat_vol_morph( NS(Yl1,job.extopts.LAB.VT),'do',4,vx_vol); % open to get lesions close to the ventricle + Yvt = cat_vol_morph( Yvt ,'dd',4,vx_vol); % add some voxels for smoothness + res.Ylesion = cat_vol_ctype( single(res.Ylesion) .* (1 - (Yvt & Ym>0.9 & Ym<1.1) )); + if ~debug, clear Yvt Ybgvt Ybgn; end + % add lesion of automatic lesion estimation? - in development + if job.extopts.WMHC>3 + res.Ylesion = cat_vol_ctype( single(res.Ylesion) + ... + 255* smooth3( Ym<1.5/3 & cat_vol_morph(NS(Yl1,job.extopts.LAB.LE),'dd',4*(1-LSstr))) ); + end + Ylesions = cat_vol_smooth3X(single(res.Ylesion)/255,4); % final smoothing to have soft boundaries + else + Ylesions = []; + end + + % call Dartel/Shooting registration + job2 = job; + job2.extopts.verb = debug; % do not display process (people would may get confused) + if isfield(job2,'spmpp') + job2.extopts.reg.affreg = 0; % RD202404: no additional affine registration in case of spm preprocessed data + if isfield(res,'bb') + job2.extopts.bb = res.bb; % RD202404: use bb parameters from SPM processing ??? + end + else + job2.extopts.reg.affreg = 4; % RD202306: do an addition registration based on the skull (i.e. sum(Ycls{1:3})) + % code is working but better result? {'brain','skull','GM','WM'}; + end + + if numel( job.extopts.vox ) > 1 + Yp0 = zeros(d,'single'); Yp0(indx,indy,indz) = single(Yp0b)/255*5; %job2.export = 1; + [trans,res.ppe.reg,res.ppe.affreg.Affine_catfinal] = cat_main_registration(job2,res,Ycls,Yy,Ylesions,Yp0,Ym,Ymi,Yl1); clear Yp0; + else + [trans,res.ppe.reg,res.ppe.affreg.Affine_catfinal] = cat_main_registration(job2,res,Yclsd,Yy,Ylesions); + end + clear Yclsd Ylesions; + else + %% call Dartel/Shooting registration + % Also it is not required we need to get the trans structure for the + % affine/rigid output + if job.extopts.regstr == 0 + fprintf('Dartel registration is not required.\n'); + else + fprintf('Shooting registration is not required.\n'); + end + + job2 = job; + job2.extopts.verb = debug; % do not display process (people would may get confused) + job2.extopts.reg.affreg = finaffreg; % final affine registration to {'brain','skull','GM','WM'} + [trans,res.ppe.reg,res.ppe.affreg.Affine_catfinal] = cat_main_registration(job2,res,Ycls,Yy); + end + + + +%% update WMHs +% --------------------------------------------------------------------- +Ycls = cat_main_updateWMHs(Ym,Ycls,Yy,tpm,job,res,trans); + + + +%% write results +% --------------------------------------------------------------------- +Yp0 = zeros(d,'single'); Yp0(indx,indy,indz) = single(Yp0b)/255*5; +cat_main_write(Ym,Ymi,Ycls,Yp0,Yl1,job,res,trans); +if debug, clear Yp0; end + + +%% surface creation and thickness estimation +% --------------------------------------------------------------------- +if all( [job.output.surface>0 job.output.surface<9 ] ) || ... + all( [job.output.surface>10 job.output.surface<19 ] ) || (job.output.surface==9 && ... + any( [job.output.ct.native job.output.ct.warped job.output.ct.dartel job.output.ROI] )) + + % prepare some parameters + if ~isfield(job,'useprior'), job.useprior = ''; end + Yp0 = zeros(d,'single'); Yp0(indx,indy,indz) = single(Yp0b)*5/255; + Ym0 = zeros(d,'single'); Ym0(indx,indy,indz) = single(Yp0b)/255; + [Ymix,job,surf,stime] = cat_main_surf_preppara(Ym0,Yp0,job); + + %% default surface reconstruction + if debug, tic; end + if job.extopts.SRP >= 20 + try + surf = unique(surf,'stable'); + catch + surf = unique(surf); + end + %% RD202107: Load Shooting template to correct severe defects in the + % parahippocampla gyrus. Previously also used to stabilize + % the cerebellum but it introduce some Shooting problems. + % RD202401: There is a bug and the T1-template is not in the same space + % (eg. HR075). Maybe because the Yy is defined for the + % TPM but not the T1-template properties. + if 0 % job.extopts.close_parahipp %any( ~cellfun('isempty', strfind(surf,'cb') )) % ... I want to avoid this if possible - it also seem to be worse to use it + VT1 = spm_vol(cat_get_defaults('extopts.shootingT1')); VT1 = VT1{1}; + fac = abs(tpm.V(1).mat(1)) / abs(VT1.mat(1)); + YT = single(spm_sample_vol(VT1,double(smooth3(Yy(:,:,:,1))*fac),double(smooth3(Yy(:,:,:,2))*fac),double(smooth3(Yy(:,:,:,3))*fac),2)); + YT = reshape(YT,size(Yy(:,:,:,1))); clear Yyi; + else + YT = []; + end + % further GUI fields ... + if ~isfield(job.extopts,'vdist'), job.extopts.vdist = 0; end + if ~isfield(job.extopts,'scale_cortex'), job.extopts.scale_cortex = cat_get_defaults('extopts.scale_cortex'); end + if ~isfield(job.extopts,'add_parahipp'), job.extopts.add_parahipp = cat_get_defaults('extopts.add_parahipp'); end + if ~isfield(job.extopts,'close_parahipp'), job.extopts.close_parahipp = cat_get_defaults('extopts.close_parahipp'); end + if ~isfield(job.extopts,'pbtmethod'), job.extopts.pbtmethod = cat_get_defaults('extopts.pbtmethod'); end + if ~isfield(job.extopts,'reduce_mesh'), job.extopts.reduce_mesh = 1; end % cat_get_defaults('extopts.reduce_mesh'); end + if ~isfield(job.output,'surf_measures'), job.output.surf_measures = 1; end % developer + %% + if job.extopts.SRP >= 40 + %% Yb0 was modified in cat_main_amap* for some conditions and we can use it as better mask in + % cat_surf_createCS4 except for inv_weighting or if gcut was not used + if ~(job.extopts.gcutstr>0 && ~job.inv_weighting), Yb0(:) = 1; end + + [Yth1, S, Psurf, qa.createCS] = ... + cat_surf_createCS4(VT,VT0,Ymi,Ymix,Yl1,YMF,Yb0,struct('trans',trans,'reduce_mesh',job.extopts.reduce_mesh,... required for Ypp output + 'interpV',job.extopts.pbtres,'pbtmethod',job.extopts.pbtmethod,'SRP', mod(job.extopts.SRP,10), 'vdist', job.extopts.vdist, ... + 'Affine',res.Affine,'surf',{surf},'verb',job.extopts.verb,'useprior',job.useprior),job); + qa.subjectmeasures.EC_abs = NaN; + qa.subjectmeasures.defect_size = NaN; + elseif job.extopts.SRP >= 30 + %% Yb0 was modified in cat_main_amap* for some conditions and we can use it as better mask in + % cat_surf_createCS3 except for inv_weighting or if gcut was not used + if ~(job.extopts.gcutstr>0 && ~job.inv_weighting), Yb0(:) = 1; end + + [Yth1, S, Psurf, qa.createCS] = ... + cat_surf_createCS3(VT,VT0,Ymix,Yl1,YMF,YT,Yb0,struct('trans',trans,'reduce_mesh',job.extopts.reduce_mesh,... required for Ypp output + 'outputpp',job.output.pp,'surf_measures',job.output.surf_measures, ... 'skip_registration', 1, ... + 'interpV',job.extopts.pbtres,'pbtmethod',job.extopts.pbtmethod,'SRP', mod(job.extopts.SRP,10), ... + 'scale_cortex', job.extopts.scale_cortex, 'add_parahipp', job.extopts.add_parahipp, 'close_parahipp', job.extopts.close_parahipp, .... + 'Affine',res.Affine,'surf',{surf},'pbtlas',job.extopts.pbtlas, ... % pbtlas is the new parameter to reduce myelination effects + 'inv_weighting',job.inv_weighting,'verb',job.extopts.verb,'useprior',job.useprior),job); + qa.subjectmeasures.EC_abs = NaN; + qa.subjectmeasures.defect_size = NaN; + else + %% + [Yth1, S, Psurf, qa.subjectmeasures.EC_abs, qa.subjectmeasures.defect_size, qa.createCS] = ... + cat_surf_createCS2(VT,VT0,Ymix,Yl1,YMF,YT,struct('trans',trans,'reduce_mesh',job.extopts.reduce_mesh,... required for Ypp output + 'vdist',job.extopts.vdist,'outputpp',job.output.pp,'surf_measures',job.output.surf_measures, ... + 'interpV',job.extopts.pbtres,'pbtmethod',job.extopts.pbtmethod,'SRP',mod(job.extopts.SRP,10),... + 'scale_cortex', job.extopts.scale_cortex, 'add_parahipp', job.extopts.add_parahipp, 'close_parahipp', job.extopts.close_parahipp, .... + 'Affine',res.Affine,'surf',{surf},'pbtlas',job.extopts.pbtlas, ... % pbtlas is the new parameter to reduce myelination effects + 'inv_weighting',job.inv_weighting,'verb',job.extopts.verb,'useprior',job.useprior),job); + end + else + %% createCS1 pipeline + [Yth1,S,Psurf,qa.subjectmeasures.EC_abs,qa.subjectmeasures.defect_size, qa.createCS] = ... + cat_surf_createCS(VT,VT0,Ymix,Yl1,YMF,struct('pbtmethod','pbtsimple',... + 'interpV',job.extopts.pbtres,'SRP',mod(job.extopts.SRP,10), ... + 'Affine',res.Affine,'surf',{surf},'pbtlas',job.extopts.pbtlas, ... % pbtlas is the new parameter to reduce myelination effects + 'inv_weighting',job.inv_weighting,'verb',job.extopts.verb,'useprior',job.useprior),job); + end + if debug, toc; end + + + + %% thickness map + if numel(fieldnames(S))==0 && isempty(Psurf), clear S Psurf; end + if isfield(job.output,'ct') + cat_io_writenii(VT0,Yth1,res.mrifolder,'ct','cortical thickness map','uint16',... + [0,0.0001],job.output.ct,trans,single(Ycls{1})/255,0.1); + end + + if job.output.sROI + stime2 = cat_io_cmd(' Surface ROI estimation'); + + %% estimate surface ROI estimates for thickness + [pp,ff] = spm_fileparts(VT.fname); + [stat, val] = fileattrib(pp); + if stat, pp = val.Name; end + + [mrifolder, reportfolder, surffolder] = cat_io_subfolders(VT.fname,job); + + if cat_get_defaults('extopts.subfolders') && strcmp(mrifolder,'mri') + pp = spm_str_manip(pp,'h'); % remove 'mri' in pathname that already exists + end + surffolder = fullfile(pp,surffolder); + + % get original filename without 'n' + [pp0,ff] = spm_fileparts(VT0.fname); + + Psatlas_lh = job.extopts.satlas( [job.extopts.satlas{:,4}]>0 , 2); + Pthick_lh = cell(1,1); + Pthick_lh{1} = fullfile(surffolder,sprintf('lh.thickness.%s',ff)); + + cat_surf_surf2roi(struct('cdata',{{Pthick_lh}},'rdata',{Psatlas_lh},'job',job)); + fprintf('%5.0fs\n',etime(clock,stime2)); + end + + cat_io_cmd('Surface and thickness estimation takes'); + fprintf('%5.0fs\n',etime(clock,stime)); + if ~debug; clear YMF Yp0; end + if ~debug && ~job.output.ROI && job.output.surface, clear Yth1; end + + +else + %if ~debug; clear Ymi; end +end + + + +%% ROI data extraction +% --------------------------------------------------------------------- +% This part estimates individual measurements for different ROIs. +% The ROIs are described in the CAT normalized space and there are two +% ways to estimate them - (1) in subject space, and (2) in normalized +% space. Estimation in normalized space is more direct and avoids further +% transformations. The way over the subject space has the advantage +% that individual anatomical refinements are possible, but this has +% to be done and evaluated for each atlas. +% --------------------------------------------------------------------- +if job.output.ROI + %% + try + Yp0 = zeros(d,'single'); Yp0(indx,indy,indz) = single(Yp0b)/255*5; + cat_main_roi(job,trans,Ycls,Yp0); + catch + cat_io_addwarning([mfilename ':cat_main_roi'],'Error in cat_main_roi.',1,[1 1]); + end +end +if ~debug, clear wYp0 wYcls wYv Yp0; end + + + +%% XML-report and Quality Control +% --------------------------------------------------------------------- + +% estimate brain tissue volumes and TIV +qa.subjectmeasures.vol_abs_CGW = [ + prod(vx_vol)/1000/255 .* sum(Ycls{3}(:)), ... CSF + prod(vx_vol)/1000/255 .* sum(Ycls{1}(:)), ... GM + prod(vx_vol)/1000/255 .* sum(Ycls{2}(:)) 0 0]; % WM WMHs SL +qa.subjectmeasures.vol_abs_WMH = 0; % RD202011: just for internal use (cat_report) but ok if people see it +qa.subjectmeasures.vol_rel_WMH = 0; +% stroke lesions +if numel(Ycls)>7, qa.subjectmeasures.vol_abs_CGW(5) = prod(vx_vol)/1000/255 .* sum(Ycls{8}(:)); end +% set WMHs +if numel(Ycls)>6 && numel(Ycls{6})>0 + qa.subjectmeasures.vol_abs_WMH = prod(vx_vol)/1000/255 .* sum(Ycls{7}(:)); + if job.extopts.WMHC > 2 % extra class + qa.subjectmeasures.vol_abs_CGW(4) = prod(vx_vol)/1000/255 .* sum(Ycls{7}(:)); + elseif job.extopts.WMHC == 2 % count as WM + qa.subjectmeasures.vol_abs_CGW(2) = qa.subjectmeasures.vol_abs_CGW(2) + prod(vx_vol)/1000/255 .* sum(Ycls{7}(:)); + else % count as GM + qa.subjectmeasures.vol_abs_CGW(1) = qa.subjectmeasures.vol_abs_CGW(1) + prod(vx_vol)/1000/255 .* sum(Ycls{7}(:)); + end + qa.subjectmeasures.vol_rel_WMH = qa.subjectmeasures.vol_abs_WMH ./ sum(qa.subjectmeasures.vol_abs_CGW); +end +if job.output.surface && isfield(S,'lh') && isfield(S,'rh') + qa.subjectmeasures.surf_TSA = sum( cat_surf_fun('area',S.lh) )/100 + sum( cat_surf_fun('area',S.lh) )/100; +end +qa.subjectmeasures.vol_TIV = sum(qa.subjectmeasures.vol_abs_CGW); +qa.subjectmeasures.vol_rel_CGW = qa.subjectmeasures.vol_abs_CGW ./ qa.subjectmeasures.vol_TIV; +if ~debug, clear Ycls; end +if job.output.surface + qa.qualitymeasures.SurfaceEulerNumber = qa.subjectmeasures.EC_abs; + qa.qualitymeasures.SurfaceDefectArea = qa.subjectmeasures.defect_size; + try % RD202306: these varialbes are not always created + qa.qualitymeasures.SurfaceDefectNumber = qa.createCS.defects; + qa.qualitymeasures.SurfaceIntensityRMSE = qa.createCS.RMSE_Ym; + qa.qualitymeasures.SurfacePositionRMSE = qa.createCS.RMSE_Ypp; + catch + qa.qualitymeasures.SurfaceDefectNumber = qa.createCS; + qa.qualitymeasures.SurfaceIntensityRMSE = nan; + qa.qualitymeasures.SurfacePositionRMSE = nan; + end + if isfield(qa,'createCS') && isfield(qa.createCS,'self_intersections') + qa.qualitymeasures.SurfaceSelfIntersections = qa.createCS.self_intersections; + else + qa.qualitymeasures.SurfaceSelfIntersections = []; + end +end +stime = cat_io_cmd('Quality check'); job.stime = stime; +Yp0 = zeros(d,'single'); Yp0(indx,indy,indz) = single(Yp0b)/255*5; Yp0(Yp0>3.1) = nan; % no analysis in WMH regions +% in case of SPM input segmentation we have to add the name here to have a clearly different naming of the CAT output +if isfield(res,'spmpp') && res.spmpp, namspm = 'c1'; else, namspm = ''; end +qa = cat_vol_qa('cat12',Yp0,VT0.fname,Ym,res,job.extopts.species, ... + struct('write_csv',0,'write_xml',1,'method','cat12','job',job,'qa',qa,'prefix',['cat_' namspm]),... + fullfile(spm_file(VT.fname,'fpath'),['p0' nam '.nii'])); +clear Yp0; + +% surface data update +if job.output.surface + if exist('S','var') + if isfield(S,'lh') && isfield(S.lh,'th1'), th=S.lh.th1; else, th=[]; end + if isfield(S,'rh') && isfield(S.rh,'th1'), th=[th; S.rh.th1]; end + qa.subjectmeasures.dist_thickness{1} = [cat_stat_nanmean(th(:)) cat_stat_nanstd(th(:))]; + + if job.extopts.expertgui>1 + if isfield(S,'lh') && isfield(S.lh,'th2'), th2=S.lh.th2; else, th2=[]; end + if isfield(S,'rh') && isfield(S.lh,'th2'), th2=[th2; S.rh.th2]; end + qa.subjectmeasures.dist_gyruswidth{1} = [cat_stat_nanmean(th2(:)) cat_stat_nanstd(th2(:))]; + if isfield(S,'lh') && isfield(S.lh,'th3'), th2=S.lh.th3; else, th2=[]; end + if isfield(S,'rh') && isfield(S.lh,'th3'), th2=[th2; S.rh.th3]; end + qa.subjectmeasures.dist_sulcuswidth{1} = [cat_stat_nanmean(th2(:)) cat_stat_nanstd(th2(:))]; + end + elseif exist('Yth1','var') + qa.subjectmeasures.dist_thickness{1} = [cat_stat_nanmean(Yth1(Yth1(:)>mean(vx_vol)/2)) cat_stat_nanstd(Yth1(Yth1(:)>mean(vx_vol)/2))]; + th = Yth1(Yth1(:)>1); + % gyrus- and sulcus-width? + end + %% Thickness peaks + % Estimation of kmean peaks to describe the thickess in a better way than + % by using only mean and std that are both biased strongly by outliers. + [thm ,ths, thh ] = cat_stat_kmeans( th , 1 ); % one anatomical average peak + [thma,thsa,thha] = cat_stat_kmeans( th( abs( th - thm ) < ths * 2 ) , 3 ); % 3 anatomical peaks + [thme,thse,thhe] = cat_stat_kmeans( th( (th < thma(1) - 2*thsa(1) ) | (th > thma(end) + 2*thsa(end) )) , 2 ); % 3 anatomical peaks + qa.subjectmeasures.dist_thickness_kmeans = [thm' ths' thh' ]; + qa.subjectmeasures.dist_thickness_kmeans_inner3 = [thma' thsa' thha']; + qa.subjectmeasures.dist_thickness_kmeans_outer2 = [thme' thse' thhe']; + if ~debug, clear th; end +end +%% qam = cat_stat_marks('eval',job.cati,qa,'cat12'); % ... not ready +cat_io_xml(fullfile(pth,res.reportfolder,['cat_' namspm nam '.xml']),struct(... + ... 'subjectratings',qam.subjectmeasures, ... not ready + 'subjectmeasures',qa.subjectmeasures,'ppe',res.ppe),'write+'); % here we have to use the write+! +fprintf('%5.0fs\n',etime(clock,stime)); +clear Yth1; + +% WMHC warning +if qa.subjectmeasures.vol_rel_WMH>0.01 && job.extopts.WMHC<2 + cat_io_addwarning([mfilename ':uncorrectedWMHs'],... + sprintf('Uncorrected WM lesions greater (%2.2f%%%%%%%% of the TIV, %2.2f%%%%%%%% of the WM)!',... + qa.subjectmeasures.vol_rel_WMH * 100, ... + qa.subjectmeasures.vol_abs_WMH / qa.subjectmeasures.vol_abs_CGW(3) * 100),1); +end + + + + +%% CAT reports +% --------------------------------------------------------------------- +% Final report of preprocessing parameter and results in the SPM +% graphics window that is exported as PDF/JPG. The parameter were +% combined in cat_main_reportstr to three text strings that were +% printed in combination with volume (spm_orthviews) and surface +% data (cat_surf_display). The processing is finished by some +% lines in the command line window. +% --------------------------------------------------------------------- +if job.extopts.print + str = cat_main_reportstr(job,res,qa); + Yp0 = zeros(d,'single'); Yp0(indx,indy,indz) = single(Yp0b)/255*5; + if ~exist('Psurf','var'), Psurf = ''; end + cat_main_reportfig(Ymi,Yp0,Yl1,Psurf,job,qa,res,str); +end + +% final command line report +cat_main_reportcmd(job,res,qa); + +return +function [Ysrc,Ycls,Yy,res] = cat_main_resspmres(Ysrc,Ycls,Yy,res) +%% cat_main_resspmres +% --------------------------------------------------------------------- +% Interpolate to internal resolution if lower resultion was used for +% SPM preprocessing +% +% [Ysrc,Ycls,Yy,res] = cat_main_resspmres(Ysrc,Ycls,Yy,res) +% +% --------------------------------------------------------------------- + + % Update Ycls: cleanup on original data + Yb = Ycls{1} + Ycls{2} + Ycls{3}; + for i=1:numel(Ycls) + [Pc(:,:,:,i),BB] = cat_vol_resize(Ycls{i},'reduceBrain',repmat(job.opts.redspmres,1,3),2,Yb); %#ok + end + Pc = cat_main_clean_gwc1639(Pc,1); + for i=1:numel(Ycls), Ycls{i} = cat_vol_resize(Pc(:,:,:,i),'dereduceBrain',BB); end; clear Pc Yb; + for ci=1:numel(Ycls) + Ycls{ci} = cat_vol_ctype(cat_vol_resize(Ycls{ci},'deinterp',res.redspmres,'linear')); + end + + % Update Yy: + Yy2 = zeros([res.redspmres.sizeO 3],'single'); + for ci=1:size(Yy,4) + Yy2(:,:,:,ci) = cat_vol_ctype(cat_vol_resize(Yy(:,:,:,ci),'deinterp',res.redspmres,'linear')); + end + Yy = Yy2; clear Yy2; + + % Update Ysrc: + Ysrc = cat_vol_resize(Ysrc,'deinterp',res.redspmres,'cubic'); + Ybf = res.image1.dat ./ Ysrc; + Ybf = cat_vol_approx(Ybf .* (Ysrc~=0 & Ybf>0.25 & Ybf<1.5),'nn',1,8); + Ysrc = res.image1.dat ./ Ybf; clear Ybf; + res.image = res.image1; + res = rmfield(res,'image1'); +return + +function [res,job,VT,VT0,pth,nam,vx_vol,d] = cat_main_updatepara(res,tpm,job) +%% Update parameter +% --------------------------------------------------------------------- +% Update CAT/SPM parameter variable job and the SPM preprocessing +% variable res +% +% [res,job] = cat_main_updatepara(res,job) +% +% --------------------------------------------------------------------- + + % this limits ultra high resolution data, i.e. images below ~0.4 mm are reduced to ~0.7mm! + % used in cat_main_partvol, cat_main_gcut, cat_main_LAS + def.extopts.uhrlim = 0.7 * 2; % default 0.7*2 that reduce images below 0.7 mm + def.cati = 0; + def.color.error = [0.8 0.0 0.0]; + def.color.warning = [0.0 0.0 1.0]; + def.color.warning = [0.8 0.9 0.3]; + def.color.highlight = [0.2 0.2 0.8]; + job = cat_io_checkinopt(job,def); + + clear def; + + % complete job structure + defr.ppe = struct(); + res = cat_io_checkinopt(res,defr); + + + % definition of subfolders - add to res variable? + [res.mrifolder, res.reportfolder, res.surffolder, res.labelfolder] = cat_io_subfolders(res.image0(1).fname,job); + + + % Sort out bounding box etc + res.bb = spm_get_bbox(tpm.V(1)); + + if numel(res.image) > 1 + warning('CAT12:noMultiChannel',... + 'CAT12 does not support multiple channels. Only the first channel will be used.'); + end + + % use dartel (do_dartel=1) or shooting (do_dartel=2) normalization + if isempty(job.extopts.darteltpm) || isempty(job.extopts.shootingtpm) + res.do_dartel = 0; + else + res.do_dartel = 1 + (job.extopts.regstr(1)~=0); + if res.do_dartel + tc = [cat(1,job.tissue(:).native) cat(1,job.tissue(:).warped)]; + need_dartel = any(job.output.warps) || ... + job.output.bias.warped || ... + job.output.label.warped || ... + any(any(tc(:,[4 5 6]))) || job.output.jacobian.warped || ... + job.output.ROI || ... + any([job.output.atlas.warped]) || ... + numel(job.extopts.regstr)>1 || ... + numel(job.extopts.vox)>1; + if ~need_dartel + res.do_dartel = 0; + end + end + end + + % Update templates for LAS + if res.do_dartel<2 && job.extopts.regstr(1) == 0 + job.extopts.templates = job.extopts.darteltpms; + else + job.extopts.templates = job.extopts.shootingtpms; + end + + % remove noise/interpolation prefix + VT = res.image(1); % denoised/interpolated n*.nii + VT0 = res.image0(1); % original + [pth,nam] = spm_fileparts(VT0.fname); + + % voxel size parameter + vx_vol = sqrt(sum(VT.mat(1:3,1:3).^2)); % voxel size of the processed image + res.vx_vol = vx_vol; + + % delete old xml file + oldxml = fullfile(pth,res.reportfolder,['cat_' nam '.xml']); + if exist(oldxml,'file'), delete(oldxml); end + clear oldxml + + d = VT.dim(1:3); + +return + +function [Ycls,Ym,Ymi,Yp0b,Yb,Yl1,Yy,YMF,indx,indy,indz,qa,job] = cat_main_SPMpp(Ysrc,Ycls,Yy,job,res,stime) +%% SPM segmentation input +% ------------------------------------------------------------------------ +% Here, DARTEL and PBT processing is prepared. +% We simply use the SPM segmentation as it is, without further modelling +% of the partial volume effect or other refinements. +% ------------------------------------------------------------------------ + + NS = @(Ys,s) Ys==s | Ys==s+1; % for side independent atlas labels + + % QA WMH values required by cat_vol_qa later + qa.subjectmeasures.WMH_abs = nan; % absolute WMH volume without PVE + qa.subjectmeasures.WMH_rel = nan; % relative WMH volume to TIV without PVE + qa.subjectmeasures.WMH_WM_rel = nan; % relative WMH volume to WM without PVE + qa.subjectmeasures.WMH_abs = nan; % absolute WMH volume without PVE in cm^3 + + vx_vol = sqrt(sum(res.image(1).mat(1:3,1:3).^2)); + + %% Update Ycls: cleanup on original data + Yb = Ycls{1} + Ycls{2} + Ycls{3}; + for i=1:numel(Ycls) + [Pc(:,:,:,i),BB] = cat_vol_resize(Ycls{i},'reduceBrain',repmat(job.opts.redspmres,1,3),2,Yb); %#ok + end + Pc = cat_main_clean_gwc(Pc,round(1./mean(vx_vol)),2); + for i=1:3, Ycls{i} = cat_vol_resize(Pc(:,:,:,i),'dereduceBrain',BB); end; clear Pc Yb; + + %% Update Ycls: cleanup on original data + if numel(Ycls)==3 + % in post-mortem data there is no CSF and CSF==BG + Yb = Ycls{1} + Ycls{2}; + [Yb,R] = cat_vol_resize(single(Yb),'reduceV',vx_vol,1,32,'meanm'); % use lower resolution to save time + Yb = cat_vol_morph(Yb>128,'ldo',3,R.vx_volr); % do some cleanup + Yb = cat_vol_morph(Yb,'ldc',8,R.vx_volr); % close mask (even large ventricles) + Yb = cat_vol_morph(Yb,'dd',1,R.vx_volr); % add 1 mm to have some CSF around the brain and simpliefy PVEs + Yb = cat_vol_resize(smooth3(Yb),'dereduceV',R)>0.5; % reinterpolate image and add some space around it + clear R; + + Ycls{3} = cat_vol_ctype(single(Ycls{3}) .* Yb); + Ycls{4} = cat_vol_ctype(255 * (1-Yb)); + else + Yb = Ycls{1} + Ycls{2} + Ycls{3}; + end + for i=1:numel(Ycls) + [Pc(:,:,:,i),BB] = cat_vol_resize(Ycls{i},'reduceBrain',repmat(job.opts.redspmres,1,3),2,Yb); + end + Pc = cat_main_clean_gwc(Pc,round(1./mean(vx_vol)),2); + for i=1:3, Ycls{i} = cat_vol_resize(Pc(:,:,:,i),'dereduceBrain',BB); end; clear Pc Yb; + + %% create (resized) label map and brainmask + Yp0 = single(Ycls{3})/5 + single(Ycls{1})/5*2 + single(Ycls{2})/5*3; + Yb = single(Ycls{3} + Ycls{1} + Ycls{2}) > 128; + + % load original images and get tissue thresholds + clsint = @(x) round( sum(res.mn(res.lkp==x) .* res.mg(res.lkp==x)') * 10^5)/10^5; + + if isfield(job.extopts,'spmAMAP') && job.extopts.spmAMAP + fprintf('%5.0fs\n',etime(clock,stime)); + T3thx = [ clsint(3) clsint(1) clsint(2) ]; + T3thx = [ cat_stat_nanmedian(Ysrc(Ycls{3}(:)>128)) ... + cat_stat_nanmedian(Ysrc(Ycls{1}(:)>128)) ... + cat_stat_nanmedian(Ysrc(Ycls{2}(:)>128)) ]; + + if any( diff( (T3thx-min(T3thx)) / (max(T3thx)-min(T3thx)) ) > .2 ) + % Usefull constrast between ALL tissues? + % Not allways working and especially in such cases AMAP is needed. + % This is expert processing and AMAP is not default! + % It inlcudes also some basic corrections (skull-stripping, bias + % correction, + + %% brain masking + if 0 + Yb = (single(Ycls{3} + Ycls{1} + Ycls{2}) > 64) | ... + cat_vol_morph( single(Ycls{3} + Ycls{1} + Ycls{2}) > 192,'dd',1.5); + Yb = cat_vol_morph( Yb ,'ldc',1.5,vx_vol); + Ycls{3} = max(Ycls{3},cat_vol_ctype(255*Yb) - Ycls{2} - Ycls{1}); + else + P = cat(4,Ycls{1},Ycls{2},Ycls{3},0*Ycls{4},0*Ycls{4},Ycls{4}); + res.isMP2RAGE = 0; + Yb = cat_main_APRG(Ysrc,P,res,double(T3thx)); + Yb = cat_vol_morph( Yb ,'ldc',6,vx_vol); + Yb = cat_vol_smooth3X(Yb,4)>.4; + clear P + end + + %% bias correction + Yg = cat_vol_grad(Ysrc) ./ Ysrc; + if T3thx(2) < T3thx(3) % T1 + Yi = Ysrc .* ( Ycls{2}>128 & Ysrc > cat_stat_nanmedian(T3thx(2:3)) & Ysrc < T3thx(3)*1.2 & Yg < cat_stat_nanmedian(Yg(Yb(:))) ) + ... + Ysrc .* ( Ycls{1}>128 & Ysrc > T3thx(2)*.9 & Ysrc < mean(T3thx(2:3)) & Yg < cat_stat_nanmedian(Yg(Yb(:))) ) * T3thx(3) / T3thx(2); + else % T2/PD + Yi = Ysrc .* ( Ycls{2}>128 & Ysrc < cat_stat_nanmedian(T3thx(2:3)) & Yg < cat_stat_nanmedian(Yg(Yb(:))) ); + Yi = Yi + ... + Ysrc .* ( Ycls{1}>128 & Ysrc > T3thx(1)*.9 & Ysrc > T3thx(1)*1.1 & Yg < cat_stat_nanmedian(Yg(Yb(:)) ) & Yi==0 ) * T3thx(3) / T3thx(2); + Ymsl = ( (Ycls{5}>128 | Ycls{4}>128) & Ysrc > min(T3thx)/4 & Ysrc < min(T3thx)*.8 & smooth3(Yg) < cat_stat_nanmedian(Yg(Yb(:))) & Yi==0 ); + Yi = Yi + ... + Ysrc .* Ymsl * T3thx(3) / cat_stat_nanmedian(Ysrc(Ymsl(:))); + end + Yi = cat_vol_approx(Yi,'rec'); + Ysrc = Ysrc ./ Yi * T3thx(3); + clear Yi; + + %% intensity normalization + if T3thx(2) < T3thx(3) % T1 + T3thx2 = [ cat_stat_nanmedian(Ysrc(Ycls{3}(:)>128 & Yg(:)<.3)) ... + cat_stat_nanmedian(Ysrc(Ycls{1}(:)>128 & Yg(:)<.3)) ... + cat_stat_nanmedian(Ysrc(Ycls{2}(:)>128 & Yg(:)<.3)) ]; + Tth.T3th = [0 .05 1:5]; + Tth.T3thx = sort( [ min(Ysrc(:)) cat_stat_nanmedian([min(Ysrc(:)),T3thx2(1)]) T3thx2 T3thx2(3)+diff(T3thx2(2:3)) max(Ysrc(:)) ] ); + else + T3thx2 = [ cat_stat_nanmedian(Ysrc(Ycls{3}(:)>128 & Yg(:)<.3)) ... ... + cat_stat_nanmedian(Ysrc(Ycls{1}(:)>128 & Yg(:)<.3)) ... + cat_stat_nanmedian(Ysrc(Ycls{2}(:)>128 & Yg(:)<.3)) ]; + Tth.T3th = [0 .05 1:5]; + Tth.T3thx = sort( [ min(Ysrc(:)) cat_stat_nanmedian([min(Ysrc(:)),min(T3thx2)]) T3thx2 max(T3thx2)-diff([max(T3thx2),max([setdiff(T3thx2,max(T3thx2))])]) max(Ysrc(:)) ] ); + end + Ym = cat_main_gintnormi(Ysrc/3,Tth) / 3; + Ym = cat_vol_sanlm(struct('data',res.image.fname,'verb',0,'NCstr',job.extopts.NCstr),res.image,1,Ym); + Yclso=Ycls; + + %% LAS + if 1 + stime = cat_io_cmd(sprintf('Local adaptive segmentation (LASstr=%0.2f)',job.extopts.LASstr)); + %Ymi = cat_main_LAS(Ysrc,Ycls,Ym,Yb,Yy,Tth.T3thx(3:5) ,res,vx_vol,job.extopts,struct('T3thx',Tth.T3th,'T3th',Tth.T3thx)); + Ymi = cat_main_LASsimple(Ysrc,Ycls); %,,job.extopts.LASstr); + Ymi = cat_vol_sanlm(struct('data',res.image0.fname,'verb',0,'NCstr',job.extopts.NCstr),res.image,1,Ymi); + Ym = Ymi; + stime = cat_io_cmd(' ','','',job.extopts.verb,clock); fprintf('%5.0fs\n',etime(clock,stime)); clear Ymx Ysrcx; + else + Ymi = Ym; + end + + %% add missing field and run AMAP + job.inv_weighting = T3thx(2) > T3thx(3); + job.extopts.AMAPframing = 0; + job.extopts.inv_weighting = T3thx(2) > T3thx(3); + [prob,indx,indy,indz] = cat_main_amap(min(10,Ymi+0), Yb & Ymi>1/6, Yb & Ymi>1/6, Ycls, job,res); + stime = cat_io_cmd(' '); + + %% cleanup (just the default value) + if job.extopts.cleanupstr > 0 && T3thx(2) < T3thx(3) + prob = cat_main_clean_gwc1639(prob,min(1,job.extopts.cleanupstr*2/mean(vx_vol))); % default cleanup + for i=1:3, Ycls{i}(:) = 0; Ycls{i}(indx,indy,indz) = prob(:,:,:,i); end + elseif T3thx(2) > T3thx(3) +% close WM in PDw + Yb0 = sum(prob,4) > 0; + Yw = single(prob(:,:,:,2)); + Yw = Yw .* cat_vol_morph(Yw > 0,'l',[.1 10]); + Yw = Yw .* (cat_vol_morph(Yb0,'de',2,vx_vol) | cat_vol_morph(Yw > 0,'ldo',1.9,vx_vol)); + Yw = Yw .* cat_vol_morph(Yw > 0,'l',[.1 10]); + Yw = Yw .* (cat_vol_morph(Yb0,'de',5,vx_vol) | cat_vol_morph(Yw > 0,'ldo',1.2,vx_vol)); + prob(:,:,:,1) = prob(:,:,:,1) + prob(:,:,:,2) .* uint8(Yw==0 & Ym(indx,indy,indz)>1/6 & Ym(indx,indy,indz)<5/6); % GM + prob(:,:,:,3) = prob(:,:,:,3) + prob(:,:,:,2) .* uint8(Yw==0 & Ym(indx,indy,indz)>5/6 & Ym(indx,indy,indz)<6/6); % CSF + prob(:,:,:,2) = prob(:,:,:,2) .* uint8(Yw>0); + clear Yb0 Yw; + + prob = cat_main_clean_gwc1639(prob,min(1,job.extopts.cleanupstr*4/mean(vx_vol))); % default cleanup + for i=1:3, Ycls{i}(:) = 0; Ycls{i}(indx,indy,indz) = prob(:,:,:,i); end + Ycls{3} = max(Ycls{3},cat_vol_ctype(255*Yb) - Ycls{2} - Ycls{1}); + end + else + % error message + cat_io_addwarning([mfilename ':cat_main_SPMpp:AMAP'],'AMAP selected but insufficient tissue contrast. Keep SPM segmentation!',4,[1 1]); + end + end + + % define label map + Yp0 = single(Ycls{3})/255 + single(Ycls{1})/255*2 + single(Ycls{2})/255*3; + Yp0b = single(Ycls{3})/5 + single(Ycls{1})/5*2 + single(Ycls{2})/5*3; + + + %% apply intensity normalization with denoising (used for export and surface evaluation) + % bias correction + Ym = Ysrc ./ cat_vol_approx( (Ycls{2}>240).*Ysrc ); + % threshold estimation + Yg = cat_vol_grad(Ym) ./ cat_stat_nanmedian(Ym(Ycls{2}(:)>128)); + if cat_stat_nanmedian(Ym(Ycls{3}(:)>128 & Yg(:)<.6)) < cat_stat_nanmedian(Ym(Ycls{2}(:)>128 & Yg(:)<.3)) + T3thx2 = [ min([ cat_stat_nanmedian(Ym(Ycls{3}(:)>240 & Yg(:)<.05)) cat_stat_nanmedian(Ym(Ycls{3}(:)>192 & Yg(:)<.1)) ]) ... + cat_stat_nanmedian(Ym(Ycls{1}(:)>128 & Yg(:)<.3)) ... + cat_stat_nanmedian(Ym(Ycls{2}(:)>128 & Yg(:)<.3)) ]; + Tth.T3th = [0 .05 1:5]; + Tth.T3thx = sort( [ min(Ym(:)) cat_stat_nanmedian([min(Ym(:)),T3thx2(1)/10]) T3thx2 T3thx2(3)+diff(T3thx2(2:3)) max(Ym(:)) ] ); + else + T3thx2 = [ cat_stat_nanmedian(Ym(Ycls{3}(:)>128 & Yg(:)<.3)) ... + cat_stat_nanmedian(Ym(Ycls{1}(:)>128 & Yg(:)<.3)) ... + cat_stat_nanmedian(Ym(Ycls{2}(:)>128 & Yg(:)<.3)) ]; + Tth.T3th = [0 .05 1:5]; + Tth.T3thx = sort( [ min(Ym(:)) cat_stat_nanmedian([min(Ym(:)),min(T3thx2)]) T3thx2 max(T3thx2)-diff([max(T3thx2),max([setdiff(T3thx2,max(T3thx2))])]) max(Ym(:)) ] ); + end + % global normalization + Ym = cat_main_gintnormi(Ym/3,Tth)/3; + % denoising + cat_sanlm(Ym,1,3); + % local normalization ( higher values are more stable?! ) + Ymi = cat_main_LASsimple(Ym*1000,Ycls); + + + %% load original images and get tissue thresholds + WMth = double(max(clsint(2),... + cat_stat_nanmedian(cat_stat_nanmedian(cat_stat_nanmedian(Ysrc(Ycls{2}>192)))))); + T3th = [ min([ clsint(1) - diff([clsint(1),WMth]) ,clsint(3)]) , clsint(2) , WMth]; + clear Ysrc + + job.extopts.WMHC = 0; + job.extopts.SLC = 0; + job.extopts.LASmyostr = 0; + job.extopts.inv_weighting = T3th(3)0)); + indx = max((min(indx) - 1),1):min((max(indx) + 1),sz(1)); + indy = max((min(indy) - 1),1):min((max(indy) + 1),sz(2)); + indz = max((min(indz) - 1),1):min((max(indz) + 1),sz(3)); + Yp0b = Yp0b(indx,indy,indz); + + + %% load atlas map and prepare filling mask YMF + % compared to CAT default processing, we have here the DARTEL mapping, but no individual refinement + Vl1 = spm_vol(job.extopts.cat12atlas{1}); + Yl1 = cat_vol_ctype( cat_vol_sample(res.tpm(1),Vl1,Yy,0)); % spm_sample_vol(Vl1,double(Yy(:,:,:,1)),double(Yy(:,:,:,2)),double(Yy(:,:,:,3)),0)); + Yl1 = reshape(Yl1,size(Ym)); [D,I] = cat_vbdist(single(Yl1>0), Yp0>0); Yl1 = cat_vol_ctype( Yl1(I) ); + YMF = NS(Yl1,job.extopts.LAB.VT) | NS(Yl1,job.extopts.LAB.BG); + % refine closing area on low resolution + [Yp0r,YMFr,BB] = cat_vol_resize({Yp0 ,YMF },'reduceBrain',vx_vol,4,Yb); + [Yp0r,YMFr,resTr] = cat_vol_resize({Yp0r,YMFr},'reduceV',vx_vol,2,64); + YMFr = single( min(1,(YMFr>.5) + 0.5*(Yp0r>2.5))); + YMFr = cat_vol_laplace3R(YMFr,Yp0r<2.5 & ~YMFr,0.01); + YMF = cat_vol_resize(YMFr,'dereduceV',resTr); + YMF = cat_vol_resize(YMF,'dereduceBrain',BB)>.75; + % combine with WM + YMF = smooth3( cat_vol_morph( ~(Ycls{2}>128 & NS(Yl1,1)) & cat_vol_morph(YMF | (Ycls{2}>128 & NS(Yl1,1)),'ldc',2),'l',[1 .3]) ); +return + +function [Ymix,job,surf,stime] = cat_main_surf_preppara(Ymi,Yp0,job) +% ------------------------------------------------------------------------ +% Prepare some variables for the surface processing. +% ------------------------------------------------------------------------ + + stime = cat_io_cmd('Surface and thickness estimation'); + + % specify surface + switch job.output.surface + case {1,11}, surf = {'lh','rh'}; + case {2,12}, surf = {'lh','rh','cb'}; + case {9,19}, surf = {'lhv','rhv'}; % estimate only volumebased thickness + otherwise, surf = {}; + end + if ~job.output.surface && any( [job.output.ct.native job.output.ct.warped job.output.ct.dartel] ) + surf = {'lhv','rhv'}; + end + + % surface creation and thickness estimation input map + Yp0toC = @(c) 1-min(1,abs(Yp0-c)); + Yp0th = @(c) cat_stat_nanmedian( Ymi(Yp0toC(c) > 0.5) ); + if job.output.surface < 10 && ... + ( Yp0th(1) < Yp0th(2) ) && ( Yp0th(2) < Yp0th(3) ) && ( Yp0th(3) > 0.9 ) + Ymix = Ymi .* (Yp0>0.5); % using the locally intensity normalized T1 map Ymi + else + Ymix = Yp0 / 3; % use the AMAP segmentation + end +return +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_vol_qa201901x.m",".m","62781","1498","function varargout = cat_vol_qa201901x(action,varargin) +% CAT Preprocessing T1 Quality Control +% ______________________________________________________________________ +% +% From cat_vol_qa201901x. +% +% Estimation of image quality measures like noise, inhomogeneity, +% contrast, resolution, etc. and scaling for school marks. +% +% [QAS,QAM] = cat_vol_qa201901x(action,varargin) +% +% +% 1) Use GUI interface to choose segmentation and automatic setting of +% original and modified image (if available) +% [QAS,QAM] = cat_vol_qa201901x() = cat_vol_qa201901x('p0') +% +% [QAS,QAM] = cat_vol_qa201901x('p0'[,opt]) - p0 class image +% [QAS,QAM] = cat_vol_qa201901x('p#'[,opt]) - p1,p2,p3 class images +% [QAS,QAM] = cat_vol_qa201901x('c#'[,opt]) - c1,c2,c3 class images +% [QAS,QAM] = cat_vol_qa201901x('*#'[,opt]) - csf,gm,wm class images +% [QAS,QAM] = cat_vol_qa201901x('p0',Pp0[,opt]) - no GUI call +% [QAS,QAM] = cat_vol_qa201901x('p#',Pp1,Pp2,Pp3,[,opt]) - no GUI call +% [QAS,QAM] = cat_vol_qa201901x('c#',Pc1,Pc2,Pc3,[,opt]) - no GUI call +% [QAS,QAM] = cat_vol_qa201901x('c#',Pcsf,Pgm,Pwm,[,opt]) - no GUI call +% +% +% 2) Use GUI interface to choose all images like for other segmentations +% and modalities with a similar focus of CSF, GM, and WM tissue +% contrast such as PD, T2, or FLASH. +% [QAS,QAM] = cat_vol_qa201901x('p0+'[,opt]) - p0 class image +% [QAS,QAM] = cat_vol_qa201901x('p#+'[,opt]) - p1,p2,p3 class images +% [QAS,QAM] = cat_vol_qa201901x('c#+'[,opt]) - c1,c2,c3 class images +% [QAS,QAM] = cat_vol_qa201901x('*#+'[,opt]) - csf,gm,wm class images +% [QAS,QAM] = cat_vol_qa201901x('p0+',Pp0,Po[,Pm,opt]) - no GUI call +% [QAS,QAM] = cat_vol_qa201901x('p#+',Pp1,Pp2,Pp3,Po[,Pm,opt]) - no GUI call +% [QAS,QAM] = cat_vol_qa201901x('c#+',Pc1,Pc2,Pc3,Po[,Pm,opt]) - no GUI call +% +% +% 3) Use GUI interface to choose all images. I.e. for other segmentations +% and modalities without focus of GM-WM contrast such as DTI MTI. +% [ not implemented yet ] +% +% +% 4) CAT12 internal preprocessing interface +% (this is the processing case that is also called in all other cases) +% [QAS,QAM] = cat_vol_qa201901x('cat12',Yp0,Po,Ym,res[,opt]) +% +% +% Pp0 - segmentation files (p0*.nii) +% Po - original files (*.nii) +% Pm - modified files (m*.nii) +% Yp0 - segmentation image matrix +% Ym - modified image matrix +% +% opt = parameter structure +% opt.verb = verbose level [ 0=nothing | 1=points | 2*=times ] +% opt.redres = resolution in mm for intensity scaling [ 4* ]; +% opt.write_csv = final cms-file +% opt.write_xml = images base xml-file +% opt.sortQATm = sort QATm output +% opt.orgval = original QAM results (no marks) +% opt.recalc = +% opt.avgfactor = +% opt.prefix = prefix of xml output file (default cat_*.xml) +% +% ______________________________________________________________________ +% Robert Dahnke +% Structural Brain Mapping Group +% University Jena +% +% $Id$ +% ______________________________________________________________________ + +%#ok<*ASGLU> + + % get current release number and version + [ver_cat, rev_cat] = cat_version; + ver_cat = ver_cat(4:end); % remove leading CAT + + % init output + QAS = struct(); + QAR = struct(); + %if nargout>0, varargout = cell(1,nargout); end + + try + if strcmp(action,'cat12err') + [mrifolder, reportfolder] = cat_io_subfolders(varargin{1}.job.data,varargin{1}.job); + elseif strcmp(action,'cat12') + [mrifolder, reportfolder] = cat_io_subfolders(varargin{2},varargin{6}.job); + else + [mrifolder, reportfolder] = cat_io_subfolders(varargin{4}.catlog,varargin{6}.job); + end + catch + mrifolder = 'mri'; + reportfolder = 'report'; + end + + % no input and setting of default options + action2 = action; + if nargin==0, action='p0'; end + if isstruct(action) + if isfield(action,'model') + if isfield(action.model,'catp0') + Po = action.images; + Pp0 = action.model.catp0; + if numel(Po)~=numel(Pp0) && numel(Pp0)==1 + Pp0 = repmat(Pp0,numel(Po),1); + end + Pm = action.images; + action.data = Pp0; + end + end + if isfield(action,'data') + Pp0 = action.data; + end + action = 'p0'; + end + if nargin==3 && isstruct(varargin{2}) && isstruct(varargin{2}) + opt = cat_check('checkinopt',varargin{2},defaults); + nopt = 1; + elseif nargin==8 && isstruct(varargin{6}) && isstruct(varargin{6}) + opt = cat_check('checkinopt',varargin{6},defaults); + nopt = 1; + else + if isstruct(action2) + opt = cat_check('checkinopt',action2.opts,defaults); + else + opt = defaults; + end + nopt = 0; + end + + % for development and in the batch mode we want to call some other versions + if isfield(opt,'version') + if ~exist(opt.version,'file') + error('Selected QC version is not available! '); + elseif ~strcmp(opt.version,mfilename) + eval(sprintf('%s(action2,varargin{:})',opt.version)); + end + end + + % check input by action + switch action + case {'p0','p0+'} + % segment image cases + if nargin<=3 && ( ~exist('Pp0','var') || isempty(Pp0) ) + if (nargin-nopt)<2 + Pp0 = cellstr(spm_select(inf,'image',... + 'select p0-segment image',{},pwd,'^p0.*')); + if isempty(Pp0{1}), return; end + else + Pp0 = varargin{1}; + end + if numel(action)==2 + Po = Pp0; Pm = Pp0; + for fi=1:numel(Pp0) + [pp,ff,ee] = spm_fileparts(Pp0{fi}); + [ppa,ppb] = spm_fileparts(pp); + if strcmp(ppb,'mri'), ppo = ppa; else, ppo = pp; end + + Po{fi} = fullfile(ppo,[ff(3:end) ee]); + Pm{fi} = fullfile(pp,[opt.mprefix ff(3:end) ee]); + %Pmv{fi} = fullfile(pp,['m' ff(3:end) ee]); %#ok + %if ~exist(Pm{fi},'file') && strcmp(opt.mprefix,'nm') && exist(Pmv{fi},'file') + % fprintf('Preparing %s.\n',Pmv{fi}); + % cat_vol_sanlm(Pmv{fi},'n'); + %end + + %if ~exist(Po{fi},'file'), Po{fi}=''; end + if ~exist(Pm{fi},'file'), Pm{fi}=''; end + end + else + Po = cellstr(spm_select(repmat(numel(Pp0),1,2),... + 'image','select original image(s)',{},pwd,'.*')); + Pm = cellstr(spm_select(repmat(numel(Pp0),1,2),... + 'image','select modified image(s)',{},pwd,'.*')); + end + elseif nargin<=5 && ( ~exist('Pp0','var') || isempty(Pp0) ) + Pp0 = varargin{1}; + Po = varargin{2}; + Pm = varargin{3}; + elseif ( ~exist('Pp0','var') || isempty(Pp0) ) + error('MATLAB:cat_vol_qa201901x:inputerror',... + 'Wrong number/structure of input elements!'); + end + case {'p#','c#','*#','p#+','c#+','*#+'} + % tissue class image cases + if nargin-1<=2 % GUI + if (nargin-nopt)<2 + if action(1)=='p' || action(1)=='c' + % cat/spm case + Pcsf = cellstr(spm_select(inf,'image',... + 'select p1-segment image',{},pwd,['^' action(1) '1.*'])); + if isempty(Pcsf{1}), return; end + Pgm=Pcsf; Pwm=Pcsf; + for fi=1:numel(Pcsf) + [pp,ff,ee] = spm_fileparts(Pcsf{fi}); + + Pgm{fi} = fullfile(pp,[action(1) '2' ff(3:end) ee]); + Pwm{fi} = fullfile(pp,[action(1) '3' ff(3:end) ee]); + end + else + Pcsf = cellstr(spm_select(inf,'image',... + 'select CSF segment image(s)',{},pwd,'.*')); + if isempty(Pcsf{1}), return; end + %Pgm = cellstr(spm_select(repmat(numel(Pcsf),1,2),... + % 'image','select GM segment image(s)',{},pwd,'.*')); + %Pwm = cellstr(spm_select(repmat(numel(Pcsf),1,2),... + % 'image','select WM segment image(s)',{},pwd,'.*')); + end + if numel(action)==2 + Pp0=Pcsf; Po=Pcsf; Pm=Pcsf; + for fi=1:numel(Pcsf) + [pp,ff,ee] = spm_fileparts(Pcsf{fi}); + Po{fi} = fullfile(pp,[ff(3:end) ee]); + Pm{fi} = fullfile(pp,['m' ff(3:end) ee]); + Pp0{fi} = fullfile(pp,['p0' ff(3:end) ee]); + end + else + Po = cellstr(spm_select(repmat(numel(Pcsf),1,2),... + 'image','select original image(s)',{},pwd,'.*')); + Pm = cellstr(spm_select(repmat(numel(Pcsf),1,2),... + 'image','select modified image(s)',{},pwd,'.*')); + Pp0=Pcsf; + for fi=1:numel(Pcsf) + [pp,ff,ee] = spm_fileparts(Pcsf{fi}); + Pp0{fi} = fullfile(pp,['p0' ff(3:end) ee]); + end + end + + % wie komm ich zum p0??? + else + Pp0 = varargin{1}; + end + elseif nargin==5 || nargin==6 + else + error('MATLAB:cat_vol_qa201901x:inputerror',... + 'Wrong number/structure of input elements!'); + end + + Yp0 = 1; + case 'cat12err' + opt = cat_check('checkinopt',varargin{end},defaults); + case 'cat12' + % CAT12 internal input + if nargin>3 + Yp0 = varargin{1}; +% Octave is starting with many warning messages here ... +% if strcmpi(spm_check_version,'octave'), warning off; end + Vo = spm_vol(varargin{2}); +% if strcmpi(spm_check_version,'octave'), warning on; end + evalc('Yo = single(spm_read_vols(Vo))'); + if 0 + % this can cause problems by the intensity normalisation + % it would also be different to processing via the QC batch + Ym = varargin{3}; + else + if any( size(Yo) ~= size(Yp0) ) + %% back to orginal resolution + Vp0i = varargin{4}.image; Vp0i.fname = 'tmp'; + Vp0i.dat = varargin{1}; + Vp0 = Vo; Vp0.fname = ''; Vp0.dat = zeros(Vp0.dim); + [~,Yp0] = cat_vol_imcalc(Vp0i,Vp0,'i1',struct('interp',2,'verb',0)); + end + Ym = Yo; + Ym(isnan(Yp0) | isinf(Yp0)) = 0; + Yw = Yp0>2.95 | cat_vol_morph( Yp0>2.25 , 'e'); + Yb = cat_vol_approx( Ym .* Yw + Yw .* min(Ym(:)) ) - min(Ym(:)); + Yb = Yb / median(Ym(Yw(:))); + Ym = Ym ./ max(eps,Yb); + end + res = varargin{4}; + V = res.image; + species = varargin{5}; + if isfield(varargin{6},'qa') + if isfield(varargin{6}.qa,'software') && isfield(varargin{6}.qa.software,'version_segment'), QAS.software.version_segment = varargin{6}.qa.software.version_segment; end + if isfield(varargin{6}.qa,'qualitymeasures'), QAS.qualitymeasures = cat_io_updateStruct(QAS,varargin{6}.qa.qualitymeasures); end + if isfield(varargin{6}.qa,'subjectmeasures'), QAS.subjectmeasures = cat_io_updateStruct(QAS,varargin{6}.qa.subjectmeasures); end + end + if nargin>7, Pp0 = varargin{7}; end % nargin count also parameter + % opt = varargin{end} in line 96) + %opt.verb = 0; + + % reduce to original native space if it was interpolated + sz = size(Yp0); + if any(sz(1:3)~=Vo.dim(1:3)) + if isfield(Vo,'private'), Vo = rmfield(Vo,'private'); end + if isfield(Vo,'mat0'), Vo = rmfield(Vo,'mat0'); end + Vo.dat = zeros(Vo.dim,'single'); Vo.dt(1) = 16; Vo.pinfo = [1;0;0]; + + Vp0t = res.image; + if isfield(Vp0t,'private'), Vp0t = rmfield(Vp0t,'private'); end + if isfield(Vp0t,'mat0'), Vp0t = rmfield(Vp0t,'mat0'); end + Vp0t.dt(1) = 16; + Vp0t.pinfo = [1;0;0]; + Vp0t.dat = Yp0; + + % resampling and corrections of the Yp0 + % Vp0t = spm_write_vol(Vp0t,double(Yp0)); + [Vtpm,Yp0] = cat_vol_imcalc(Vp0t,Vo,'i1',struct('interp',2,'verb',0)); + rf = 50; + Yp0 = single(Yp0); + Yp0r = round(Yp0*rf)/rf; + YMR = false(size(Yp0)); + for i=1:4, YMR = YMR | (Yp0>(i-1/rf) & Yp0<(i+1/rf)); end + Yp0(YMR) = Yp0r(YMR); clear YMR Ynr; + + % resampling of the corrected image + Vp0t.dat = Ym; + [Vtpm,Ym] = cat_vol_imcalc(Vp0t,Vo,'i1',struct('interp',6,'verb',0)); + Ym = single(Ym); + end + + else + error('MATLAB:cat_vol_qa201901x:inputerror',... + 'Wrong number/structure of input elements!'); + end + otherwise + error('MATLAB:cat_vol_qa201901x:inputerror',... + 'Wrong number/structure of input elements!'); + end + if ~exist('species','var'), species='human'; end + + + % + % -------------------------------------------------------------------- + [QA,QMAfn] = cat_stat_marks('init'); + stime = clock; + stime2 = clock; + + + + % Print options + % -------------------------------------------------------------------- + Cheader = {'scan'}; + Theader = sprintf(sprintf('%%%ds:',opt.snspace(1)-1),'scan'); + Tline = sprintf('%%5d) %%%ds:',opt.snspace(1)-8); + Tline2 = sprintf('%%5d) %%6s%%%ds:',opt.snspace(1)-14); + Tavg = sprintf('%%%ds:',opt.snspace(1)-1); + TlineE = sprintf('%%5d) %%%ds: %%s',opt.snspace(1)-7); + for fi=1:numel(QMAfn) + Cheader = [Cheader QMAfn{fi}]; %#ok + Theader = sprintf(sprintf('%%s%%%ds',opt.snspace(2)),Theader,... + QMAfn{fi}(1:min(opt.snspace(2)-1,numel(QMAfn{fi})))); + Tline = sprintf('%s%%%d.%df',Tline,opt.snspace(2),opt.snspace(3)); + Tline2 = sprintf('%s%%%d.%df',Tline2,opt.snspace(2),opt.snspace(3)); + Tavg = sprintf('%s%%%d.%df',Tavg,opt.snspace(2),opt.snspace(3)); + end + Cheader = [Cheader 'IQR']; + Theader = sprintf(sprintf('%%s%%%ds',opt.snspace(2)),Theader,'SIQR'); + Tline = sprintf('%s%%%d.%df%%s\n',Tline,opt.snspace(2),opt.snspace(3)); + Tline2 = sprintf('%s%%%d.%df\n',Tline2,opt.snspace(2),opt.snspace(3)); + Tavg = sprintf('%s%%%d.%df\n',Tavg,opt.snspace(2),opt.snspace(3)); + + + + + + + % estimation part + switch action + case {'p0','p#','c#','*#','p0+','p#+','c#+','*#+'} + % loop for multiple files + stimem = clock; + + % return for empty input + if isempty(Pp0) || (isempty(Pp0{1}) && numel(Pp0)<=1) + cat_io_cprintf('com','No images for QA!\n'); + return + end + + if opt.verb>1 + fprintf('\n%s\n\n%s\n%s\n', ... + sprintf('CAT Preprocessing T1 Quality Control (%s %s):',mfilename,... + sprintf('Rev: %s',rev_cat)), Theader,repmat('-',size(Theader))); + end + + qamat = nan(numel(Po),numel(QMAfn)); + qamatm = nan(numel(Po),numel(QMAfn)); + mqamatm = 10.5*ones(numel(Po),1); + + + QAS = struct(); QAR = struct(); + QAR.mark2rps = @(mark) min(100,max(0,105 - mark*10)) + isnan(mark).*mark; + + for fi=1:numel(Pp0) + try + stime = cat_io_cmd(' Any segmentation Input:','g5','',opt.verb>2); stime1 = stime; + + [pp,ff,ee] = spm_fileparts(Po{fi}); + if exist(fullfile(pp,[ff ee]),'file') + Vo = spm_vol(Po{fi}); + elseif exist(fullfile(pp,[ff ee '.gz']),'file') + gunzip(fullfile(pp,[ff ee '.gz'])); + Vo = spm_vol(Po{fi}); + delete(fullfile(pp,[ff ee '.gz'])); + else + error('cat_vol_qa201901x:noYo','No original image.'); + end + + + Vm = spm_vol(Pm{fi}); + Vp0 = spm_vol(Pp0{fi}); + if any(Vp0.dim ~= Vm.dim) + [Vx,Yp0] = cat_vol_imcalc(Vp0,Vm,'i1',struct('interp',2,'verb',0)); + else + evalc('Yp0 = single(spm_read_vols(Vp0))'); + end + Yp0(isnan(Yp0) | isinf(Yp0)) = 0; + + % bias corrected image + evalc('Ym = single(spm_read_vols(spm_vol(Po{fi})))'); + Ym(isnan(Yp0) | isinf(Yp0)) = 0; + Yw = Yp0>2.95 | cat_vol_morph( Yp0>2.25 , 'e'); + Yb = cat_vol_approx( Ym .* Yw + Yw .* min(Ym(:)) ) - min(Ym(:)); + Ym = Ym ./ max(eps,Yb); + rmse = (mean(Ym(Yp0(:)>0) - Yp0(Yp0(:)>0)/3).^2)^0.5; + if rmse>0.2 + cat_io_cprintf('warn',['Segmentation is maybe not fitting to the ' ... + 'image (RMSE(Ym,Yp0)=%0.2f)?:\n %s\n %s'],rmse,Pm{fi},Pp0{fi}); + end + + evalc('res.image = spm_vol(Pp0{fi});'); + [QASfi,QAMfi] = cat_vol_qa201901x('cat12',Yp0,Vo,Ym,res,species,opt,Pp0{fi}); + + if isnan(QASfi.qualitymeasures.NCR) + fprintf(''); + end + + + try + QAS = cat_io_updateStruct(QAS,QASfi,0,fi); + QAR = cat_io_updateStruct(QAR,QAMfi,0,fi); + catch + fprintf('ERROR-Struct'); + end + + + % color for the differen mark cases (opt.process) + for fni=1:numel(QMAfn) + try + qamat(fi,fni) = QAS(fi).qualitymeasures.(QMAfn{fni}); + qamatm(fi,fni) = QAR(fi).qualityratings.(QMAfn{fni}); + catch + qamat(fi,fni) = QASfi.qualitymeasures.(QMAfn{fni}); + qamatm(fi,fni) = QAMfi.qualityratings.(QMAfn{fni}); + end + + end + try + mqamatm(fi,1) = QAR(fi).qualityratings.IQR; + catch + mqamatm(fi,1) = QASfi.qualityratings.IQR; + end + mqamatm(fi,1) = max(0,min(10.5, mqamatm(fi,1))); + + + if opt.verb>1 + if opt.rerun || cat_io_rerun(Vo.fname, fullfile(pp,reportfolder,[opt.prefix ff '.xml']) , 0 ) + rerun = sprintf(' updated %2.0fs',etime(clock,stime1)); + elseif exist( fullfile(pp,reportfolder,[opt.prefix ff '.xml']) , 'file') + rerun = ' loaded'; + else + rerun = ' '; % new + end + + %% + if opt.orgval + cat_io_cprintf(opt.MarkColor(max(1,floor( mqamatm(fi,1)/9.5 * ... + size(opt.MarkColor,1))),:),sprintf(Tline,fi,... + spm_str_manip(QAS(fi).filedata.fname,['a' num2str(opt.snspace(1) - 14)]),... + qamat(fi,:), max(1,min(9.5,mqamatm(fi,:))), rerun)); + else + cat_io_cprintf(opt.MarkColor(max(1,floor( mqamatm(fi,1)/9.5 * ... + size(opt.MarkColor,1))),:),sprintf(Tline,fi,... + spm_str_manip(QAS(fi).filedata.fname,['a' num2str(opt.snspace(1) - 14)]),... + qamatm(fi,:), max(1,min(9.5,mqamatm(fi,:))), rerun)); + end + end + catch e + switch e.identifier + case {'cat_vol_qa201901x:noYo','cat_vol_qa201901x:noYm','cat_vol_qa201901x:badSegmentation'} + em = e.identifier; + otherwise + em = ['ERROR:\n' repmat(' ',1,10) e.message '\n']; + for ei=1:numel(e.stack) + em = sprintf('%s%s%5d: %s\n',em,repmat(' ',1,10),... + e.stack(ei).line(end),e.stack(ei).name); + end + end + + [pp,ff] = spm_fileparts(Po{fi}); + QAS(fi).filedata.fnames = [spm_str_manip(pp,sprintf('k%d',floor( (opt.snspace(1)-19) /3) - 1)),'/',... + spm_str_manip(ff,sprintf('k%d',(opt.snspace(1)-19) - floor((opt.snspace(1)-14)/3)))]; + cat_io_cprintf(opt.MarkColor(end,:),sprintf(TlineE,fi,Pp0{fi},[em '\n'])); + end + end + + + + % sort by mean mark + % ---------------------------------------------------------------- + if opt.sortQATm && numel(Po)>1 + % sort matrix + [smqamatm,smqamatmi] = sort(mqamatm(:,1),'ascend'); + sqamatm = qamatm(smqamatmi,:); + sqamat = qamat(smqamatmi,:); + + % print matrix + if opt.verb>0 + fprintf('%s\n',repmat('-',size(Theader))); + for fi=1:numel(QAS) + if opt.orgval + cat_io_cprintf(opt.MarkColor(max(1,min(size(opt.MarkColor,1),... + round( mqamatm(smqamatmi(fi),2)/9.5 * ... + size(opt.MarkColor,1)))),:),sprintf(... + Tline2,fi,sprintf('(%d)',smqamatmi(fi)),... + spm_str_manip(Pp0{fi},'l80'), ...QAS(smqamatmi(fi)).filedata.fnames, ... + ...spm_str_manip(QAS(smqamatmi(fi)).filedata.file,['f' num2str(opt.snspace(1) - 14)]),... + sqamat(fi,:),max(1,min(10.5,mqamatm(smqamatmi(fi),:))))); + else + cat_io_cprintf(opt.MarkColor(max(1,min(size(opt.MarkColor,1),... + round( mqamatm(smqamatmi(fi),2)/9.5 * ... + size(opt.MarkColor,1)))),:),sprintf(... + Tline2,fi,sprintf('(%d)',smqamatmi(fi)),... + spm_str_manip(Pp0{fi},'l80'), ... QAS(smqamatmi(fi)).filedata.fnames, ... + ...spm_str_manip(QAS(smqamatmi(fi)).filedata.file,['f' num2str(opt.snspace(1) - 14)]),... + sqamatm(fi,:),mqamatm(smqamatmi(fi),:))); + end + end + end + else + %[smqamatm,smqamatmi] = sort(mqamatm,'ascend'); + %sqamatm = qamatm(smqamatmi,:); + end + % print the results for each scan + if opt.verb>1 && numel(Pp0)>1 + fprintf('%s\n',repmat('-',size(Theader))); + if opt.orgval + fprintf(Tavg,'mean',cat_stat_nanmean(qamat,1), cat_stat_nanmean(mqamatm,1)); %#ok + fprintf(Tavg,'std' , cat_stat_nanstd(qamat,1), cat_stat_nanstd(mqamatm,1)); %#ok + else + fprintf(Tavg,'mean',cat_stat_nanmean(qamatm,1), cat_stat_nanmean(mqamatm,1)); %#ok + fprintf(Tavg,'std' , cat_stat_nanstd(qamatm,1), cat_stat_nanstd(mqamatm,1)); %#ok + end + %fprintf('%s\n',repmat('-',size(Theader))); + %fprintf(Tavg,'mean',mean(qamat,1)); + %fprintf(Tavg,'std', std(qamat,1)); + end + if opt.verb>0, fprintf('\n'); end + + + + % result tables (cell structures) + % ---------------------------------------------------------------- + if nargout>2 && opt.write_csv + QAT = [Cheader(1:end-1); ... there is no mean for the original measures + Po , num2cell(qamat); ... + 'mean' , num2cell(cat_stat_nanmean(qamat,1)); ... + 'std' , num2cell( cat_stat_nanstd(qamat,1,1))]; + QATm = [Cheader; ... + Po , num2cell(qamatm) , ... + num2cell(cat_stat_nanmean(qamatm,2)); ... + 'mean' , num2cell(cat_stat_nanmean(qamatm,1)) , ... + num2cell(cat_stat_nanmean(mqamatm,1)); ... + 'std' , num2cell( cat_stat_nanstd(qamatm,1,1)), ... + num2cell( cat_stat_nanstd(mqamatm,1))]; + + + % write csv results + % -------------------------------------------------------------- + if opt.write_csv + pp = spm_fileparts(Pp0{1}); + cat_io_csv(fullfile(pp,reportfolder,[opt.prefix num2str(numel(Vo),'%04d') ... + 'cat_vol_qa_values.csv']),QAT); + cat_io_csv(fullfile(pp,reportfolder,[opt.prefix num2str(numel(Vo),'%04d') ... + 'cat_vol_qa_marks.csv']),QATm); + end + end + + if opt.verb>0 + fprintf('Quality Control for %d subject was done in %0.0fs\n', ... + numel(Pp0),etime(clock,stimem)); fprintf('\n'); + end + + + case 'cat12err' + + % file information + % ---------------------------------------------------------------- + [pp,ff,ee] = spm_fileparts(Vo.fname); + if strcmp(ee,'.gz'), [~,ff] = spm_fileparts(ff); ee = '.nii.gz'; end + [pp0,ff0,ee0] = spm_fileparts(Pp0); + [QAS.filedata.path,QAS.filedata.file] = spm_fileparts(Vo.fname); + QAS.filedata.fname = Vo.fname; + QAS.filedata.F = Vo.fname; + QAS.filedata.Fm = fullfile(pp0,['m' ff ee0]); + QAS.filedata.Fp0 = fullfile(pp0,['p0' ff ee0]); + QAS.filedata.fnames = [spm_str_manip(pp,sprintf('k%d',... + floor( max(opt.snspace(1)-19-ff,opt.snspace(1)-19)/3) - 1)),'/',... + spm_str_manip(ff,sprintf('k%d',... + (opt.snspace(1)-19) - floor((opt.snspace(1)-14)/3)))]; + + + % software, parameter and job information + % ---------------------------------------------------------------- + [nam,rev_spm] = spm('Ver'); + QAS.software.version_spm = rev_spm; + if strcmpi(spm_check_version,'octave') + QAS.software.version_octave = version; + else + A = ver; + for i=1:length(A) + if strcmp(A(i).Name,'MATLAB') + QAS.software.version_matlab = A(i).Version; + end + end + clear A + end + % 1 line: Matlab, SPM12, CAT12 version number and GUI and experimental mode + if ispc, OSname = 'WIN'; + elseif ismac, OSname = 'MAC'; + else, OSname = 'LINUX'; + end + + QAS.software.system = OSname; + QAS.software.version_cat = ver_cat; + if ~isfield(QAS.software,'version_segment') + QAS.software.version_segment = rev_cat; + end + QAS.software.revision_cat = rev_cat; + try + QAS.hardware.numcores = max(cat_get_defaults('extopts.nproc'),1); + catch + QAS.hardware.numcores = 1; + end + + + % save important preprocessing parameter + % remove LAS + QAS.parameter.opts = opt.job.opts; + QAS.parameter.extopts = rmfield(opt.job.extopts,... + {'LAB','atlas','satlas','darteltpms','shootingtpms','fontsize'}); + %QAS.parameter.output = opt.job.output; + QAS.parameter.caterr = opt.caterr; + QAS.error = opt.caterrtxt; + + % export + if opt.write_xml + cat_io_xml(fullfile(pp0,[opt.prefix ff '.xml']),QAS,'write'); + end + + case 'cat12' + % estimation of the measures for the single case + + + % file information + % ---------------------------------------------------------------- + [pp,ff,ee] = spm_fileparts(Vo.fname); + if strcmp(ee,'.gz'), [~,ff] = spm_fileparts(ff); ee = '.nii.gz'; end + [pp0,ff0,ee0] = spm_fileparts(Pp0); + [QAS.filedata.path,QAS.filedata.file] = spm_fileparts(Vo.fname); + QAS.filedata.fname = Vo.fname; + QAS.filedata.F = Vo.fname; + QAS.filedata.Fm = fullfile(pp0,['m' ff ee0]); + QAS.filedata.Fp0 = fullfile(pp0,['p0' ff ee0]); + QAS.filedata.fnames = [spm_str_manip(pp,sprintf('k%d',... + floor( max(opt.snspace(1)-19-ff,opt.snspace(1)-19)/3) - 1)),'/',... + spm_str_manip(ff,sprintf('k%d',... + (opt.snspace(1)-19) - floor((opt.snspace(1)-14)/3)))]; + + + % software, parameter and job information + % ---------------------------------------------------------------- + [nam,rev_spm] = spm('Ver'); + OSname = {'LINUX','WIN','MAC'}; + QAS.software.system = OSname{1 + ispc + ismac}; + QAS.software.version_spm = rev_spm; + A = ver; + for i=1:length(A) + if strcmp(A(i).Name,'MATLAB') + QAS.software.version_matlab = A(i).Version; + end + end + clear A + QAS.software.version_cat = ver_cat; + if ~isfield(QAS.software,'version_segment') + QAS.software.version_segment = rev_cat; + end + QAS.software.revision_cat = rev_cat; + QAS.software.function = which('cat_vol_qa201901x'); + QAS.software.markdefs = which('cat_stat_marks'); + QAS.software.qamethod = action; + QAS.software.date = datestr(clock,'yyyymmdd-HHMMSS'); + warning off + QAS.software.opengl = opengl('INFO'); + QAS.software.opengldata = opengl('DATA'); + warning on +% ### need for long? + %QAS.parameter = opt.job; + + QAS.parameter.vbm = rmfield(cat_get_defaults,'output'); + if isfield(opt,'job') && isfield(opt.job,'opts'), QAS.parameter.opts = opt.job.opts; end + if isfield(opt,'job') && isfield(opt.job,'extopts'), QAS.parameter.opts = opt.job.extopts; end + if exist('res','var') + % add important SPM preprocessing variables + rf = {'Affine','Affine0','lkp','mn','vr','ll'}; + for rfi=1:numel(rf) + if isfield(res,rf{rfi}), QAS.SPMpreprocessing.(rf{rfi}) = res.(rf{rfi}); end + end + end + + %% resolution, boundary box + % --------------------------------------------------------------- + QAS.software.cat_qa_warnings = struct('identifier',{},'message',{}); + vx_vol = sqrt(sum(Vo.mat(1:3,1:3).^2)); + vx_voli = sqrt(sum(V.mat(1:3,1:3).^2)); + Yp0toC = @(Yp0,c) 1-min(1,abs(Yp0-c)); + + % resolution + QAS.qualitymeasures.res_vx_vol = vx_vol; + QAS.qualitymeasures.res_vx_voli = vx_voli; + QAS.qualitymeasures.res_RMS = cat_stat_nanmean(vx_vol.^2).^0.5; + % further unused measure (just for test/comparison) + %QAS.qualitymeasures.res_isotropy = max(vx_vol)./min(vx_vol); + %QAS.qualitymeasures.res_vol = prod(abs(vx_vol)); + %QAS.qualitymeasures.res_MVR = mean(vx_vol); + + % boundary box - brain tissue next to image boundary + bbth = round(2/cat_stat_nanmean(vx_vol)); M = true(size(Yp0)); + M(bbth:end-bbth,bbth:end-bbth,bbth:end-bbth) = 0; + QAS.qualitymeasures.res_BB = sum(Yp0(:)>1.25 & M(:))*prod(abs(vx_vol)); + + % check segmentation + spec = species; for ai=num2str(0:9); spec = strrep(spec,ai,''); end + bvol = species; for ai=char(65:122); bvol = strrep(bvol,ai,''); end; bvol = str2double(bvol); + + subvol = [sum(Yp0(:)>2.5 & Yp0(:)<3.1)*prod(vx_vol)/1000,... + sum(Yp0(:)>1.5 & Yp0(:)<2.5)*prod(vx_vol)/1000,... + sum(Yp0(:)>0.5 & Yp0(:)<1.5)*prod(vx_vol)/1000]; + + if isempty(bvol) + switch spec + case 'human' + bvol = 1400; + otherwise + warning('cat_vol_qa201901x:species',... + sprintf('Unknown species %s (C=%0.0f,G=%0.0f,W=%0.0f).',species,subvol)); %#ok + end + end + if sum(subvol)bvol*3 + warning('cat_vol_qa201901x:badSegmentation',... + sprintf('Bad %s segmentation (C=%0.0f,G=%0.0f,W=%0.0f).',species,subvol)) %#ok + end + if ~isfield(QAS,'subjectmeasures') + %% in case of external/batch calls + QAS.subjectmeasures.vol_TIV = sum(Yp0(:)>0) .* prod(vx_vol) / 1000; + for i = 1:3 + QAS.subjectmeasures.vol_abs_CGW(i) = sum( Yp0toC(Yp0(:),i)) .* prod(vx_vol) / 1000; + QAS.subjectmeasures.vol_rel_CGW(i) = QAS.subjectmeasures.vol_abs_CGW(i) ./ ... + QAS.subjectmeasures.vol_TIV; + end + end + + + + %% basic level (RD202411) + % To avoid to long processing times but also to standardize the data + % we first fix the resolution to 1 mm. This was also done as there + % is currently not enough data with higher resolution and varying + % properties. + if any( vx_vol < .8 ) + mres = 1; ss = real(max(0.2,min(2,(mres - vx_vol).^2))); + + spm_smooth(Yp0, Yp0, ss); + spm_smooth(Ym , Ym , ss); + spm_smooth(Yo , Yo , ss); + + Ym = single(cat_vol_resize(Ym ,'interphdr',V,mres,1)); + Yo = single(cat_vol_resize(Yo ,'interphdr',V,mres,1)); + [Yp0,V] = cat_vol_resize(Yp0,'interphdr',V,mres,1); Yp0 = single(Yp0); + + vx_vol = repmat(mres,1,3); %#ok<*RPMT1> + end + + + %% estimate QA + % --------------------------------------------------------------- + % remove space arount the brain for speed-up + [Yo,Ym,Yp0] = cat_vol_resize({Yo,Ym,Yp0},'reduceBrain',vx_vol,4,Yp0>1.5); + + % RD20241030: avoid lesions and masking + Y0 = cat_vol_morph(Yo==0,'o',1) | Yp0==0; + Yo(Y0)=nan; Ym(Y0)=0; Yp0(Y0)=0; + + % Refined segmentation to fix skull-stripping issues in case of bad + % segmentation. Tested on the BWP with simulated segmenation issues + % for skull-stripping as well as WM/CSF over/underestimation. + [Yp0r,resYp0] = cat_vol_resize(Yp0,'reduceV',vx_vol,2,32,'meanm'); + Yp0r = cat_vol_morph(cat_vol_morph(cat_vol_morph(Yp0r>0.9,'e',1),'l',[0.5 0.2]),'d',1); + Yp0 = Yp0 .* (cat_vol_resize(Yp0r,'dereduceV',resYp0)>.5); + + % rought contast and noise estimation to get a stable T1 map for threshold estimation + T1th = [cat_stat_nanmedian(Ym(Yp0toC(Yp0(:),1)>0.9)) ... + cat_stat_nanmedian(Ym(Yp0toC(Yp0(:),2)>0.9)) ... + cat_stat_nanmedian(Ym(Yp0toC(Yp0(:),3)>0.9))]; + + newNC = 0; + if newNC + %% new approach + %noise0 = max(0,min( min(abs(diff(T1th))) ,cat_stat_nanstd(Ym(Yp0(:)>2.9)) )); + % we need a bit background noise for the filter around the brain! + Yms = Ym + ( noise0 .* (cat_vol_smooth3X(Yp0,4)>0 & Yp0==0) .* rand(size(Ym)) ); cat_sanlm(Yms,1,3); + noise = max(0,min(1,cat_stat_nanstd(Ym(Yp0(:)>.5) - Yms(Yp0(:)>.5)) / min(abs(diff(T1th))))); + Ym(Y0) = nan; + else + %% classic a bit faster approach + Ym(Y0) = nan; + noise = max(0,min(1,cat_stat_nanstd(Ym(Yp0(:)>2.9)) / min(abs(diff(T1th))))) / 3; + Yms = Ym+0; spm_smooth(Yms,Yms,repmat(double(noise)*4,1,3)); % smoothing to reduce high frequency noise + end + + + % Avoid lesions defined as regions (local blobs) with high difference + % between the segmentation and intensity scaled image. Remove these + % areas from the Yp0 map that is not used for volumetric evaluation. + % Use the ATLAS stroke leson dataset for evalution, where the masked + % and unmasked image should result in the same quality ratings. + if 0 % better without + Ymm = cat_main_gintnorm(Yms,struct('T3th',[0 T1th T1th(end)*2],'T3thx',[0 1 2 3 6])); + Ymd = cat_vol_smooth3X( (Yp0>0) .* abs(Ymm - Yp0/3) , 2); + mdth = cat_stat_nanmedian(Ymd(Ymd(:) > 1.5 * cat_stat_nanmedian(Ymd(Ymd(:)>0)))); + Ymsk = Ymd > mdth & (Ymm>.5); + % tissue contrasts (corrected for noise-bias estimated on the BWP) + T1th = [cat_stat_nanmedian(Yms(Yp0toC(Yp0(:),1)>0.9 & ~Ymsk(:) & Ymm(:)<1.25/3)) ... + cat_stat_nanmedian(Yms(Yp0toC(Yp0(:),2)>0.9 & ~Ymsk(:) )) ... + cat_stat_nanmedian(Yms(Yp0toC(Yp0(:),3)>0.9 & ~Ymsk(:) ))]; + if newNC + noise = max(0,min(1,cat_stat_nanstd(Ym(Yp0(:)>.5) - Yms(Yp0(:)>0.5)) / min(abs(diff(T1th))))); + else + noise = max(0,min(1,cat_stat_nanstd(Ym(Yp0(:)>2.9)) / min(abs(diff(T1th))))) / 3; + end + Yp0(Ymsk) = 0; + clear Ymd Ymm mdth Ymsk + end + + % basic tissue classes - erosion to avoid PVE, std to avoid other tissues (like WMHs) + voli = @(v) (v ./ (pi * 4./3)).^(1/3); + rad = voli( QAS.subjectmeasures.vol_TIV) ./ cat_stat_nanmean(vx_vol); + Ysc = 1-cat_vol_smooth3X(Yp0<1 | Yo==0,min(24,max(16,rad*2))); % fast 'distance' map to focus on deep CSF + % definiton of basic tissue segments without PVE + Ycm = Yp0>0.75 & Yp0<1.25 & cat_vol_morph(Yp0>0.25 & Yp0<1.75,'de',1,vx_vol) & Ysc>0.75; + Ygm = Yp0>1.75 & Yp0<2.25 & cat_vol_morph(Yp0>1.25 & Yp0<2.75,'de',1,vx_vol); + Ywm = Yp0>2.75 & Yp0<3.25 & cat_vol_morph(Yp0>2.25 & Yp0<3.75,'de',1,vx_vol); + % RD202411: Median filter to avoid side effects by PVE/SVD/PVS + Ymed = cat_vol_median3(Yms,Ywm,Ywm); + Ywm(Ymed - (Yms.*Ywm) > noise*T1th(3)*2) = 0; + clear Ymed; + + + %% RD202212: Edge Contrast Ratio + % Estimation of the real structural resolution independent of the voxel size. + % We uses here a linear intensity normalized image Ymm + Ymm = cat_main_gintnorm(Yms,struct('T3th',[0 T1th T1th(end)*2],'T3thx',[0 1 2 3 6])); + % remove blood vessels (eg. ABIDE, ADHD200) + if all(vx_vol < 1.5) + Ybv = ( (Ymm>1.15 & Yp0<2) & ~Ywm) ; + [~,Yi] = cat_vbdist(single(~Ybv),Yp0>1); Ymm = min(Ymm,Ymm(Yi)); clear Ybv; + end + res_ECR0 = estimateECR0old( Ymm , Yp0, vx_vol ); + QAS.qualitymeasures.res_ECR = max(0, 1/4 - (res_ECR0 + .25*noise) ); + + + % Fast Euler Characteristic (FEC) .. Ym was more stable for BWP + Ymm = cat_main_gintnorm(Ym,struct('T3th',[0 T1th T1th(end)*2],'T3thx',[0 1 2 3 6])); + if all(vx_vol < 1.5), Ymm = min(Ymm,Ymm(Yi)); end; clear Yi; + QAS.qualitymeasures.FEC = estimateFEC(Yp0, vx_vol, Ymm, V); + + + % bias correction of the original input image + Yi = Yo ./ Ym; + Yi(isnan(Yi) | Yi > 10 | Yi < 0) = 0; % no neg. values to avoid problems in MP2Rage + Yic = cat_vol_localstat(Yi,Yi>0,1,4); Yi(Yic>.2) = 0; clear Yic; + Ywb = cat_vol_approx(Yi,'rec'); clear Yi + + + %% low resolution tissue intensity maps (smoothing) + % High frequency noise is mostly uncritical as far as simple smoothing can reduce it. + % Although the very low frequency interferences (inhomogeneity) is unproblematic in most cases, + % but will influence the noise pattern. + % But most important is the noise with the medium high frequencies, that we try to detect by + % reducing the very high and low noise pattern by filtering and pixel smoothing by reduction. + if 1 + % This block is a bit weired but is imporant to balance the hard noise + % of the BWP and real data aspects. It uses a Gaussian smoothing to + % reduce this hard noise. + Ymx = Ym; + Yos = Ymx.*Ywm + (1-Ywm).*T1th(3); spm_smooth(Yos,Yos,.8 + .5./vx_vol); Ymx(Ywm>0)=Yos(Ywm>0); + Yos = Ymx.*Ygm + (1-Ygm).*T1th(2); spm_smooth(Yos,Yos,.8 + .5./vx_vol); Ymx(Ygm>0)=Yos(Ygm>0); + Yos = Ymx.*Ycm + (1-Ycm).*T1th(1); spm_smooth(Yos,Yos,.8 + .5./vx_vol); Ymx(Ycm>0)=Yos(Ycm>0); + end + + % reduction to 2 mm to average (smooth) and save some time + res = 2.3; vx_volx = vx_vol; + Ywb = cat_vol_resize(Ywb ,'reduceV',vx_volx,res,32,'meanm'); % CSF thr. (minimum to avoid PVE) + Yg = cat_vol_resize(Ymx .* Ygm,'reduceV',vx_volx,res,32,'meanm'); % GM thr. + Yw = cat_vol_resize(Ymx .* Ywm,'reduceV',vx_volx,res,32,'meanm'); % WM thr. and bias correction (Ywme) + Yc = cat_vol_resize(Ymx .* Ycm,'reduceV',vx_volx,res,32,'meanm'); % CSF thr. (minimum to avoid PVE) + Ywn = cat_vol_resize(Ymx .* Ywm,'reduceV',vx_volx,res,32,'meanm'); % for WM noise + Ycn = cat_vol_resize(Ymx .* Ycm,'reduceV',vx_volx,res,32,'meanm'); % for CSF noise + Ygm = cat_vol_resize(Ygm ,'reduceV',vx_volx,res,32,'meanm'); % GM thr. + Ywm = cat_vol_resize(Ywm ,'reduceV',vx_volx,res,32,'meanm'); % WM thr. and bias correction (Ywme) + Ycm = cat_vol_resize(Ycm ,'reduceV',vx_volx,res,32,'meanm'); % WM thr. and bias correction (Ywme) + [Yo,Ym,Yp0,resr] = cat_vol_resize({Ymx,Ym,Yp0},'reduceV',vx_volx,res,32,'meanm'); + resr.vx_volo = vx_vol; vx_vol=resr.vx_red .* resr.vx_volo; + + % only voxel that have multiple inputs + Yc = Yc .* (Ycm>=0.5); Yg = Yg .* (Ygm>=0.5); Yw = Yw .* (Ywm>=0.5); + Ywn = Ywn .* (Ywm>=0.5); Ycn = Ycn .* (Ycm>=0.5); + clear Ycm Ygm Ywm; + + + %% tissue contrasts (corrected for noise-bias estimated on the BWP) + WMth = cat_stat_nanmedian(Yw(~isnan(Yw(:)) & Yw(:)~=0)); + GMth = cat_stat_nanmedian(Yg(~isnan(Yg(:)) & Yg(:)~=0)); + CSFth = cat_stat_nanmedian(Yc(~isnan(Yc(:)) & Yc(:)~=0)); + BGth = 0; + + + %% Signal and contrast: + % ------------------------------------------------------------------- + % * minimum contrast between tissues without background + % * CSF-BG contrast is often poor and a problem for skull-stripping. + % However, to have ""useful"" ratings we have to ignore that. + signal = abs(diff([min([CSFth,BGth]),max([WMth,GMth])])); + contrastr = min(abs(diff([CSFth GMth WMth]))) / signal; + % avoid overoptimization by high contrasts, eg. in ADHD200 or ABIDE scans + contrastr = (contrastr + min(0,1/3 - contrastr)*1.1); + QAS.qualitymeasures.contrast = contrastr * signal; + QAS.qualitymeasures.contrastr = contrastr; + + % (relative) average tissue intensity of each class + QAS.qualitymeasures.tissue_mn = ([BGth CSFth GMth WMth]); + QAS.qualitymeasures.tissue_mnr = QAS.qualitymeasures.tissue_mn ./ signal; + if WMth > GMth + QAS.qualitymeasures.tissue_weighting = 'T1'; + elseif WMth0.5 & ~isinf(Yp0(:)))); + end + QAS.qualitymeasures.tissue_stdr = QAS.qualitymeasures.tissue_std ./ signal; + + + + % Noise: + % ------------------------------------------------------------------- + % volume weighing for WM and CSF + NCRww = nnz(Ywn(:)>0) * prod(vx_vol); + NCRwc = nnz(Ycn(:)>0) * prod(vx_vol); + % WM variance NCRw + [Yos2,YM2] = cat_vol_resize({Ywn,Ywn>0},'reduceV',vx_vol,2,16,'meanm'); + NCRw = estimateNoiseLevel(Yos2,YM2>0.5) / (contrastr*signal); + clear Yos0 Yos1 Yos2 YM0 YM1 YM2; + + % CSF variance NCRc (if enough volume is available, i.e., large ventricle) + wcth = 200; + if CSFthwcth + [Yos2,YM2] = cat_vol_resize({Ycn,Ycn>0},'reduceV',vx_vol,2,16,'meanm'); + NCRc = estimateNoiseLevel(Yos2,YM2>0.5) / (contrastr*signal); + clear Yos0 Yos1 Yos2 YM0 YM1 YM2; + else + NCRc = 0; + NCRwc = 0; + end + + % mixing + NCRwc = min(wcth,max(0,NCRwc-wcth)); + NCRww = min(wcth,NCRww) - NCRwc; % use CSF if possible + if NCRwc<3*wcth && NCRww<10*wcth, NCRc = min(NCRc,NCRw); end + QAS.qualitymeasures.NCR = (NCRw*NCRww + NCRc*NCRwc)/(NCRww+NCRwc); + clear NCRww NCRwc + + + % Bias/Inhomogeneity: + % ------------------------------------------------------------------- + % * Estimate the (i) ""global"" or (ii) ""regional"" standard deviation within + % (a) the WM of the original image, or (b) the bias correction field + % * The hope was that the ""regional field allows better adaption to local + % outliers (segmentation problems) and that it is less biased by sex in + % MRART but this was not the case and it is only more noisy for other + % BWP parameter. + % The regional measurement underestimates so we have to compensate by a factor: + % ICRw = estimateNoiseLevel(Ywb,Yp0>0,5) / contrast * 3; + ICRw = cat_stat_nanstd(Ywb(Yp0(:)>0)) / contrastr; % need the relative contrast here + QAS.qualitymeasures.ICR = ICRw; + + + %% marks + QAR = cat_stat_marks('eval',1,QAS); + + % export + if opt.write_xml + QAS.qualityratings = QAR.qualityratings; + QAS.subjectratings = QAR.subjectratings; + QAS.ratings_help = QAR.help; + + cat_io_xml(fullfile(pp0,[opt.prefix ff '.xml']),QAS,'write'); + end + + clear Yi Ym Yo Yos Ybc + clear Ywm Ygm Ycsf Ybg + + end + + if nargout>2, varargout{3} = cat_qa_warnings; end + if nargout>1, varargout{2} = QAR; end + if nargout>0, varargout{1} = QAS; end + +end +%======================================================================= +function def=defaults + % default parameter + def.verb = 2; % verbose level [ 0=nothing | 1=points | 2*=results ] + def.write_csv = 2; % final cms-file [ 0=dont write |1=write | 2=overwrite ] + def.write_xml = 1; % images base xml-file + def.sortQATm = 1; % sort QATm output + def.orgval = 0; % original QAM results (no marks) + def.avgfactor = 2; % + def.prefix = 'cat_'; % intensity scaled image + def.mprefix = 'm'; % prefix of the preprocessed image + def.process = 3; % used image [ 0=T1 | 1=mT1 | 2=avg | 3=both ] + def.calc_MPC = 0; + def.calc_STC = 0; + def.calc_MJD = 0; + def.method = 'spm'; + def.snspace = [100,7,3]; + def.nogui = exist('XT','var'); + def.MarkColor = cat_io_colormaps('marks+',40); +end + +function noise = estimateNoiseLevel(Ym,YM,r) +% ---------------------------------------------------------------------- +% Noise estimation within Ym and YM with possible reduction factor r. +% ---------------------------------------------------------------------- + if exist('r','var') && r > 1 + [Ym,YM,red] = cat_vol_resize({Ym,YM},'reduceV',1,r,8,'meanm'); + YM = YM > .5; + end + Ysd = cat_vol_localstat(single(Ym),YM,1,4); + noise = cat_stat_nanstat1d(Ysd(YM),'median'); +end +%======================================================================= +function [res_ECR,segCase,Yp0c,Ygrad] = estimateECR(Ym,Yp0,vx_vol) +%% estimateECR. Quanfify anatomical details by the normalized edge strength. +% +% old pure version for high quality segmentation input that works only well +% for the CAT12 AMAP segmenation. +% +% Extension 202309: Tested at eroded and dilated boundaries positions + + + Ybad = abs(Yp0/3 - Ym) > .5 | isnan(Ym) | isnan(Yp0) | (Yp0==0); + Yp0s = max(2,Yp0+0); spm_smooth(Yp0s,Yp0s,.5 ./ vx_vol); %max(0.4,1.4 - 0.4.*vx_vol)); + Ywmb = Yp0s>2.05 & Yp0s<2.95; + + if 1 + % This sanlm is not working as intended. It is not denoising fully and when I use the + Yms = Ym .* Ywmb; cat_sanlm(Yms,3,1); Ym(Ywmb) = Yms(Ywmb); + else + Yms = Ym .* cat_vol_morph(Ywmb,'d',1); Yms = cat_vol_median3(Yms,Yms>0,Yms>0); Ym(Ywmb) = Yms(Ywmb); + end + Ym(isnan(Ym)) = 0; Ym = max(2/3,min(1,Ym)); %spm_smooth(Ym,Ym,.4); + + Ygrad = cat_vol_grad( Ym , vx_vol .^.5 ); % RD20241106: original ... the sqrt helps to bring + Ygrad(cat_vol_morph(Ybad,'d',1)) = nan; % correct bad areas + res_ECRo = cat_stat_nanmedian(Ygrad(Ywmb(:))); + clear Ywmb + Yp0(Ybad) = nan; + + %% == EXTENSION 202309 == + % * test for segmentation errors by using gray-scale erosion + % * if the WM was overestimated than use the new boundary and export + Yp0e = cat_vol_morph(max(1,Yp0),'gerode'); + Ywmeb = Yp0e>2.05 & Yp0e<2.95 & ~Ybad; + Ywmebm = Yp0 >2.475 & Yp0e<2.525 & ~Ybad; + res_ECRe = cat_stat_nanmedian(Ygrad(Ywmeb(:))); clear Ywmeb + res_ECRem = cat_stat_nanmedian(Ygrad(Ywmebm(:))); clear Ywmebm + [res_ECR,segCase] = max([ res_ECRo , res_ECRem, res_ECRe]); + + test2 = 0; + Yp0c = Yp0; + if segCase == 1 && ( max(res_ECRe,res_ECRem) * 1.05 < res_ECR ) + %% in case of no WM overestimation test for underestimation + Yp0d = cat_vol_morph(Yp0,'gdilate'); + Ywmdb = Yp0d>2.05 & Yp0d<2.95 & Yp0>=1.75 & ~Ybad; + Ywmdbm = Yp0d>2.475 & Yp0 <2.525 & Yp0>=1.75 & ~Ybad; + res_ECRd = cat_stat_nanmedian(Ygrad(Ywmdb(:))); clear Ywmdb + res_ECRdm = cat_stat_nanmedian(Ygrad(Ywmdbm(:))); clear Ywmdbm + + [res_ECR,segCase] = max([ res_ECRo , res_ECRe, res_ECRe, res_ECRe, res_ECRe, res_ECRdm, res_ECRd]); + + % corrected segmentation + if test2 && segCase >= 6 + Yp0d2 = cat_vol_morph(Yp0d,'gdilate'); + Ywmdb = Yp0d2>2.05 & Yp0d2<2.95 & Yp0>=1.75 & ~Ybad; + Ywmdbm = Yp0d2>2.475 & Yp0d <2.525 & Yp0>=1.75 & ~Ybad; + res_ECRd2 = cat_stat_nanmedian(Ygrad(Ywmdb(:))); clear Ywmdb + res_ECRd2m = cat_stat_nanmedian(Ygrad(Ywmdbm(:))); clear Ywmdbm + [res_ECR,segCase] = max([ res_ECRo , res_ECRe, res_ECRe, res_ECRe, ... + res_ECRe, res_ECRdm, res_ECRd, res_ECRd2m, res_ECRd2]); + end + if segCase >=6 && segCase <= 7 + Yp0c(Yp0>=2) = Yp0d(Yp0>=2); + elseif test2 && segCase >7 + Yp0c(Yp0>=2) = Yp0d2(Yp0>=2); + end + else + if test2 + Yp0e2 = cat_vol_morph(Yp0e,'gerode'); + Ywmeb = Yp0e2>2.05 & Yp0e2<2.95 & ~Ybad; + Ywmebm = Yp0e >2.475 & Yp0e2<2.525 & ~Ybad; + res_ECRe2 = cat_stat_nanmedian(Ygrad(Ywmeb(:))); % & Yb(:)) + res_ECRe2m = cat_stat_nanmedian(Ygrad(Ywmebm(:))); % & Yb(:)) + + [res_ECR,segCase] = max([ res_ECRo , res_ECRem, res_ECRe, res_ECRe2m, res_ECRe2]); + end + + % corrected segmentation + if segCase >=2 && segCase <= 3 + Yp0c(Yp0>2) = Yp0e(Yp0>2); + elseif test2 && segCase > 3 + Yp0c(Yp0>2) = Yp0e2(Yp0>2); + end + end + +end +%======================================================================= +function [FEC,WMarea] = estimateFEC(Yp0,vx_vol,Ymm,V,machingcubes) +%estimateFEC. Fast Euler Characteristic (FEC) + + if ~exist('machingcubes','var'), machingcubes = 1; end + Ymsr = (Ymm*3); + %spm_smooth(Ymsr,Ymsr,max(0.3,1.7 - 0.7*vx_vol)); + %spm_smooth(Ymsr,Ymsr,max(0.2,1.4 - 0.6*vx_vol)); + spm_smooth(Ymsr,Ymsr,max(0.2,(1.4 - 0.6*vx_vol))); + + app = 1; + if app == 1 + sth = 0.25:0.125/2:0.5; % two levels for 5 class AMAP + if all(vx_vol<1.5) + Ymsr = max(0,max(Ymsr,cat_vol_localstat(Ymsr,Yp0>2,1,3)) - 2); % ######## + else + Ymsr = max(0,Ymsr - 2); + end + % Ymsr = max(0,cat_vol_localstat(Ymsr,Yp0>0.5,1,3) - 2); + elseif app == 2 + sth = .5; + Ymsr = cat_vol_median3(Yp0,Yp0>=2,Yp0>1); + [Ygmt,Ymsr] = cat_vol_pbtsimple(Ymsr,vx_vol,... + struct('levels',1,'extendedrange',0,'gyrusrecon',0,'keepdetails',0,'sharpening',0)); + else + % FEC by creating of the WM like brain tissue of the full brain. + if isempty(Ymm) % use the segmentation works very well + sth = 0.25:0.5:0.75; % two levels for 5 class AMAP + Ymsr = Ymsr - 2; + else % using raw data not realy + sth = 0.25:0.25:0.75; + Ymsr = max(-2,(Ymm .* (smooth3(Ymsr)>1) * 3) - 2); + end + end + + % light denoising of maximum filter + %spm_smooth(Ymsr,Ymsr,.4./vx_vol); + Ymsr(Yp0==0) = nan; + + % use 2 mm is more robust (accurate in a sample) + smeth = 1; + if smeth==1 + [Ymsr0,resYp0] = cat_vol_resize(Ymsr,'reduceV',vx_vol,2,32,'max'); + Ymsr = Ymsr0 + cat_vol_resize(Ymsr,'reduceV',vx_vol,2,32,'meanm'); + elseif smeth==2 + spm_smooth(Ymsr , Ymsr , 2 - vx_vol); V.dim = size(Ymsr); + Ymsr = single(cat_vol_resize(Ymsr,'interphdr',V,2,1)); + resYp0.vx_volr = [2 2 2]; + else + % this is + spm_smooth(Ymsr,Ymsr,2 ./ vx_vol); % not required + resYp0.vx_volr = vx_vol; + end + + + EC = zeros(size(sth)); area = EC; + for sthi = 1:numel(sth) + % remove other objects and holes + if app == 2 + Ymsr(Ymsr> sth(sthi) & ~cat_vol_morph(Ymsr> sth(sthi),'lo',1,vx_vol)) = sth(sthi) - 0.01; % avoid BVs (eg. in ABIDE2) + else + Ymsr(Ymsr> sth(sthi) & ~cat_vol_morph(Ymsr> sth(sthi),'l')) = sth(sthi) - 0.01; % avoid BVs (eg. in ABIDE2) + end + Ymsr(Ymsr<=sth(sthi) & ~cat_vol_morph(Ymsr<=sth(sthi),'l')) = sth(sthi) + 0.01; + + if machingcubes + % faster binary approach on the default resolution, quite similar result + txt = evalc('[~,faces,vertices] = cat_vol_genus0(Ymsr,sth(sthi),1);'); + CS = struct('faces',faces,'vertices',vertices); + else + % slower but finer matlab isosurface + CS = isosurface(Ymsr,sth(sthi)); + end + if numel(CS.vertices)>0 + CS.vertices = CS.vertices .* repmat(resYp0.vx_volr,size(CS.vertices,1),1); + EC(sthi) = ( size(CS.vertices,1) + size(CS.faces,1) - size(spm_mesh_edges(CS),1) - 2) + 2; + area(sthi) = spm_mesh_area(CS) / 100; % cm2 + EC(sthi) = EC(sthi); + else + area(sthi) = nan; + EC(sthi) = nan; + end + end + + FEC = cat_stat_nanmean(abs(EC - 2) + 2) / log(area(1)/2500 + 1); % defined on the seg-error phantom + FEC = (FEC.^.5)*10; + WMarea = area(1); +end +%======================================================================= + +%======================================================================= +function [res_ECR,segCase,Yp0c,Ygrad] = estimateECR1(Ym,Yp0,vx_vol) +%% estimateECR. Quanfify anatomical details by the normalized edge strength. +% +% old pure version for high quality segmentation input that works only well +% for the CAT12 AMAP segmenation. +% +% Extension 202309: Tested at eroded and dilated boundaries positions + +% extend step by step by some details (eg. masking of problematic regions +%& Ygrad(:)<1/3 +% Yb = cat_vol_morph(cat_vol_morph(Yp0>2,'l',[10 0.1]),'d',2); + + Yb = Yp0>0; + Yp0c = Yp0; + Ygrad = cat_vol_grad(max(2/3,min(1,Ym) .* Yb ) , vx_vol ); + Ywmb = Yp0>2.05 & Yp0<2.95; + res_ECRo = cat_stat_nanmedian(Ygrad(Ywmb(:))); + clear Ywmb + + + %% == EXTENSION 202309 == + % * test for segmentation errors by using gray-scale erosion + % * if the WM was overestimated than use the new boundary and export + Yp0e = cat_vol_morph(max(1,Yp0),'gerode'); + Ywmeb = Yp0e>2.05 & Yp0e<2.95; + Ywmebm = Yp0 >2.475 & Yp0e<2.525; + res_ECRe = cat_stat_nanmedian(Ygrad(Ywmeb(:))); clear Ywmeb + res_ECRem = cat_stat_nanmedian(Ygrad(Ywmebm(:))); clear Ywmebm + [res_ECR,segCase] = max([ res_ECRo , res_ECRem, res_ECRe]); + + test2 = 0; + if segCase == 1 && ( max(res_ECRe,res_ECRem) * 1.05 < res_ECR ) + %% in case of no WM overestimation test for underestimation + Yp0d = cat_vol_morph(Yp0,'gdilate'); + Ywmdb = Yp0d>2.05 & Yp0d<2.95 & Yp0>=1.75; + Ywmdbm = Yp0d>2.475 & Yp0 <2.525 & Yp0>=1.75; + res_ECRd = cat_stat_nanmedian(Ygrad(Ywmdb(:))); clear Ywmdb + res_ECRdm = cat_stat_nanmedian(Ygrad(Ywmdbm(:))); clear Ywmdbm + + [res_ECR,segCase] = max([ res_ECRo , res_ECRe, res_ECRe, res_ECRe, res_ECRe, res_ECRdm, res_ECRd]); + + % corrected segmentation + if test2 && segCase >= 6 + Yp0d2 = cat_vol_morph(Yp0d,'gdilate'); + Ywmdb = Yp0d2>2.05 & Yp0d2<2.95 & Yp0>=1.75; + Ywmdbm = Yp0d2>2.475 & Yp0d <2.525 & Yp0>=1.75; + res_ECRd2 = cat_stat_nanmedian(Ygrad(Ywmdb(:))); clear Ywmdb + res_ECRd2m = cat_stat_nanmedian(Ygrad(Ywmdbm(:))); clear Ywmdbm + [res_ECR,segCase] = max([ res_ECRo , res_ECRe, res_ECRe, res_ECRe, ... + res_ECRe, res_ECRdm, res_ECRd, res_ECRd2m, res_ECRd2]); + end + if segCase >=6 && segCase <= 7 + Yp0c(Yp0>=2) = Yp0d(Yp0>=2); + elseif test2 && segCase >7 + Yp0c(Yp0>=2) = Yp0d2(Yp0>=2); + end + else + if test2 + Yp0e2 = cat_vol_morph(Yp0e,'gerode'); + Ywmeb = Yp0e2>2.05 & Yp0e2<2.95; + Ywmebm = Yp0e >2.475 & Yp0e2<2.525; + res_ECRe2 = cat_stat_nanmedian(Ygrad(Ywmeb(:))); % & Yb(:)) + res_ECRe2m = cat_stat_nanmedian(Ygrad(Ywmebm(:))); % & Yb(:)) + + [res_ECR,segCase] = max([ res_ECRo , res_ECRem, res_ECRe, res_ECRe2m, res_ECRe2]); + end + + % corrected segmentation + if segCase >=2 && segCase <= 3 + Yp0c(Yp0>2) = Yp0e(Yp0>2); + elseif test2 && segCase > 3 + Yp0c(Yp0>2) = Yp0e2(Yp0>2); + end + end + + + + + +%% == EXTENSION 202309 CSF == +if 1 + Ygradc = cat_vol_grad(min(1,max(2/3,Ym) .* Yb ) , vx_vol ); + + + % * test for segmentation errors by using gray-scale erosion + % * if the WM was overestimated than use the new boundary and export + %Yp0e = cat_vol_morph(Yp0,'gerode'); + Ycmeb = Yp0e>1.05 & Yp0e<1.95 & Yp0>=1; + Ycmebm = Yp0 >1.475 & Yp0e<1.525 & Yp0>=1; + res_ECRe = cat_stat_nanmedian(Ygradc(Ycmeb(:))); clear Ywmeb + res_ECRem = cat_stat_nanmedian(Ygradc(Ycmebm(:))); clear Ywmebm + [res_ECRC,segCaseC] = max([ res_ECRo , res_ECRem, res_ECRe]); + + test2 = 0; + if segCaseC == 1 && ( max(res_ECRe,res_ECRem) * 1.05 < res_ECRC ) + %% in case of no CSF underestimation test for overestimation + if ~exist('Yp0d','var') + Yp0d = cat_vol_morph(Yp0,'gdilate'); + end + Ycmdb = Yp0d>1.05 & Yp0d<1.95 & Yp0<2.25 & Yp0>=1; + Ycmdbm = Yp0d>1.475 & Yp0 <1.525 & Yp0<2.25 & Yp0>=1; + res_ECRd = cat_stat_nanmedian(Ygradc(Ycmdb(:))); clear Ywmdb + res_ECRdm = cat_stat_nanmedian(Ygradc(Ycmdbm(:))); clear Ywmdbm + + [res_ECRC,segCaseC] = max([ res_ECRo , res_ECRe, res_ECRe, res_ECRe, res_ECRe, res_ECRdm, res_ECRd]); + + % corrected segmentation + if test2 && segCase >= 6 + if ~exist('Yp0d2','var') + Yp0d2 = cat_vol_morph(Yp0d,'gdilate'); + end + Ywmdb = Yp0d2>2.05 & Yp0d2<2.95 & Yp0>=1.75; + Ywmdbm = Yp0d2>2.475 & Yp0d <2.525 & Yp0>=1.75; + res_ECRd2 = cat_stat_nanmedian(Ygradc(Ywmdb(:))); clear Ywmdb + res_ECRd2m = cat_stat_nanmedian(Ygradc(Ywmdbm(:))); clear Ywmdbm + [res_ECR,segCase] = max([ res_ECRo , res_ECRe, res_ECRe, res_ECRe, ... + res_ECRe, res_ECRdm, res_ECRd, res_ECRd2m, res_ECRd2]); + end + if segCase >=6 && segCase <= 7 + Yp0c(Yp0>=1 & Yp0<2) = Yp0d(Yp0>=1 & Yp0<2); + elseif test2 && segCase >7 + Yp0c(Yp0>=1 & Yp0<2) = Yp0d2(Yp0>=1 & Yp0<2); + end + else + if test2 + if ~exist('Yp0e2','var') + Yp0e2 = cat_vol_morph(Yp0e,'gerode'); + end + Ywmeb = Yp0e2>2.05 & Yp0e2<2.95; + Ywmebm = Yp0e >2.475 & Yp0e2<2.525; + res_ECRe2 = cat_stat_nanmedian(Ygradc(Ywmeb(:))); % & Yb(:)) + res_ECRe2m = cat_stat_nanmedian(Ygradc(Ywmebm(:))); % & Yb(:)) + + [res_ECR,segCase] = max([ res_ECRo , res_ECRem, res_ECRe, res_ECRe2m, res_ECRe2]); + end + + % corrected segmentation + if segCaseC >=2 && segCaseC <= 3 + Yp0c(Yp0>1 & Yp0<2) = Yp0e(Yp0>1 & Yp0<2); + elseif test2 && segCaseC > 3 + Yp0c(Yp0>1 & Yp0<2) = Yp0e2(Yp0>1 & Yp0<2); + end + end +end + + +end +function res_ECR = estimateECR0(Ym,Yp0,vx_vol) +%% estimateECR. Quanfify anatomical details by the normalized edge strength. +% +% old pure version for high quality segmentation input that works only well +% for the CAT12 AMAP segmenation + +% extend step by step by some details (eg. masking of problematic regions +%& Ygrad(:)<1/3 +% Yb = cat_vol_morph(cat_vol_morph(Yp0>2,'l',[10 0.1]),'d',2); + Yb = Yp0>0; + Ygrad = cat_vol_grad(max(2/3,min(1,Ym) .* Yb ) , vx_vol ); + res_ECR = cat_stat_nanmedian(Ygrad(Yp0(:)>2.05 & Yp0(:)<2.95)); % & Yb(:)) + +end +function res_ECR = estimateECR0old(Ym,Yp0,vx_vol,rec) +%% estimateECR. Quanfify anatomical details by the normalized edge strength. +% +% old pure version for high quality segmentation input that works only well +% for the CAT12 AMAP segmenation + if 0 + Yp0( cat_vol_morph(Yp0>2.9,'ldc',1) & Yp0>1.5) = 3; % RD20250907: avoid WMHs + % spm_smooth(Ym,Ym,max(0.2,0.4 ./ (vx_vol*2))); % voxel smoothing to avoid missinterpretations of noise as boundary! needs to be small but not too small + Yp0s = round(Yp0); spm_smooth(Yp0s,Yp0s,3 ./ (vx_vol*2)); % voxel smoothing to avoid missinterpretations of noise as boundary! needs to be small but not too small + Ybad = cat_vol_morph( abs(Yp0s/3 - Ym) > .5 | isnan(Ym) | isnan(Yp0) | (Yp0==0) , 'd',1,vx_vol); + Ygrad = cat_vol_grad(max(2/3,min(1,Ym) ) , vx_vol ); %.^.5 ); %.^ .75 ); + res_ECRo = cat_stat_nanmedian(Ygrad(Yp0s(:)>2.1 & Yp0s(:)<2.9 & ~Ybad(:))); + else + Yp0 = cat_vol_smooth3X(Yp0,0.2); % sync AMAP and SPM + Ywm = Yp0>2.5; %cat_vol_morph(Yp0>2.75,'ldc',1) & Yp0>1.5; + noise = double(std(Ym(Ywm(:)))) * 1; + Yp0( Ywm ) = 3; % avoid WMHs + Yms = max(2/3,Ym); spm_smooth(Yms,Yms,max(0,noise ./ (vx_vol.^2))); + Yp0s = round(Yp0); %spm_smooth(Yp0s,Yp0s,3 ./ (vx_vol*2)); % for AMAP + % GM/WM edge area based on the segmentation + Ymsk = cat_vol_morph(Yp0s>2.5,'d') & ~cat_vol_morph(Yp0s>2.5,'e'); + % avoid critical areas,e.g. blood vessels + Ybad = cat_vol_morph( abs(Yp0/3 - Yms) > .5 | isnan(Ym) | isnan(Yp0) | (Yp0==0) , 'd',1,vx_vol); + % GM/WM edge + Ygrad = cat_vol_grad(max(2/3,min(1,Yms) ) , vx_vol .^.5 ); + Ygrad = cat_vol_localstat(Ygrad,Ymsk,1,3); + Ygrad = cat_vol_approx(Ygrad); + % ""edges"" (noise) in WM for normalization + Ygradw = cat_vol_grad(max(1,Yms ) , vx_vol .^.75 ); % *2 as we only look above the WM peak intensity + Ygradw = cat_vol_localstat(Ygradw,Ywm,1,3); + Ygradw = cat_vol_approx(Ygradw); + % final value + res_ECR = cat_stat_nanmedian(Ygrad(Ymsk(:) & ~Ybad(:))) - ... + cat_stat_nanmedian(Ygradw(Ymsk(:) & ~Ybad(:))); + + % test for segmentation problems + if ~exist('rec','var') + Yp0e = min(2,Yp0s) + cat_vol_morph(Yp0s>2.5,'e'); + Yp0d = min(2,Yp0s) + cat_vol_morph(Yp0s>2.5,'d'); + res_ECRe = estimateECR0old(Ym,Yp0e,vx_vol,1); + res_ECRd = estimateECR0old(Ym,Yp0d,vx_vol,1); + res_ECR = max([res_ECR,res_ECRe,res_ECRd]); + end + + return + end + + + %% == EXTENSION 202309 == + % * test for segmentation errors by using gray-scale erosion + % * if the WM was overestimated than use the new boundary and export + Yp0e = cat_vol_morph(max(1,Yp0),'gerode'); + Ywmeb = Yp0e>2.05 & Yp0e<2.95 & ~Ybad; + Ywmebm = Yp0 >2.475 & Yp0e<2.525 & ~Ybad; + res_ECRe = cat_stat_nanmedian(Ygrad(Ywmeb(:))); clear Ywmeb + res_ECRem = cat_stat_nanmedian(Ygrad(Ywmebm(:))); clear Ywmebm + [res_ECR,segCase] = max([ res_ECRo , res_ECRem, res_ECRe]); + + test2 = 1; + Yp0c = Yp0; + if segCase == 1 && ( max(res_ECRe,res_ECRem) * 1.05 < res_ECR ) + %% in case of no WM overestimation test for underestimation + Yp0d = cat_vol_morph(Yp0,'gdilate'); + Ywmdb = Yp0d>2.05 & Yp0d<2.95 & Yp0>=1.75 & ~Ybad; + Ywmdbm = Yp0d>2.475 & Yp0 <2.525 & Yp0>=1.75 & ~Ybad; + res_ECRd = cat_stat_nanmedian(Ygrad(Ywmdb(:))); clear Ywmdb + res_ECRdm = cat_stat_nanmedian(Ygrad(Ywmdbm(:))); clear Ywmdbm + + [res_ECR,segCase] = max([ res_ECRo , res_ECRe, res_ECRe, res_ECRe, res_ECRe, res_ECRdm, res_ECRd]); + + % corrected segmentation + if test2 && segCase >= 6 + Yp0d2 = cat_vol_morph(Yp0d,'gdilate'); + Ywmdb = Yp0d2>2.05 & Yp0d2<2.95 & Yp0>=1.75 & ~Ybad; + Ywmdbm = Yp0d2>2.475 & Yp0d <2.525 & Yp0>=1.75 & ~Ybad; + res_ECRd2 = cat_stat_nanmedian(Ygrad(Ywmdb(:))); clear Ywmdb + res_ECRd2m = cat_stat_nanmedian(Ygrad(Ywmdbm(:))); clear Ywmdbm + [res_ECR,segCase] = max([ res_ECRo , res_ECRe, res_ECRe, res_ECRe, ... + res_ECRe, res_ECRdm, res_ECRd, res_ECRd2m, res_ECRd2]); + end + if segCase >=6 && segCase <= 7 + Yp0c(Yp0>=2) = Yp0d(Yp0>=2); + elseif test2 && segCase >7 + Yp0c(Yp0>=2) = Yp0d2(Yp0>=2); + end + else + if test2 + Yp0e2 = cat_vol_morph(Yp0e,'gerode'); + Ywmeb = Yp0e2>2.05 & Yp0e2<2.95 & ~Ybad; + Ywmebm = Yp0e >2.475 & Yp0e2<2.525 & ~Ybad; + res_ECRe2 = cat_stat_nanmedian(Ygrad(Ywmeb(:))); + res_ECRe2m = cat_stat_nanmedian(Ygrad(Ywmebm(:))); + + [res_ECR,segCase] = max([ res_ECRo , res_ECRem, res_ECRe, res_ECRe2m, res_ECRe2]); + end + + % corrected segmentation + if segCase >=2 && segCase <= 3 + Yp0c(Yp0>2) = Yp0e(Yp0>2); + elseif test2 && segCase > 3 + Yp0c(Yp0>2) = Yp0e2(Yp0>2); + end + end + +end +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_vol_downcut.c",".c","8083","188","/* intensity limited region growing + * _____________________________________________________________________________ + * Region growing of integer objects in O depending on a distance map that is + * created on the path distance to the object and the intensity in L. The + * region growing for the intensity map is limited by the lim where a neighbor + * value have fit for the following equation: + * L(neigbor(x)) + limit <= L(x) + * But not only the intensity of L is important, also the object distance can be + * used. You can set up the relation of both with the dd value, where dd(1) is + * used for the distance component and dd(2) for the intensity component. + * This regions growing was orignialy used for skull-stripping and to alL used + * + * + * [D,I] = cat_vol_downcut(O,L,lim,vx,dd) + * + * O (3d single) initial object (integer values for different objects) + * L (3d single) intensity image + * lim (1x1 double) limit for the neighbor intensity in the regions growing + * L(neigbor(x)) + limit <= L(x) + * vx (1x3 double) voxel size + * dd (1x2 double) distance weighting for the path length of the regions + * growing (dd(1)) and the intensity (dd(2)) + * (default [0.1 10]) + * + * + * Examples: + * + * ______________________________________________________________________ + * + * Christian Gaser, Robert Dahnke + * Structural Brain Mapping Group (https://neuro-jena.github.io) + * Departments of Neurology and Psychiatry + * Jena University Hospital + * ______________________________________________________________________ + * $Id$ + */ + +#include ""mex.h"" +#include ""math.h"" +#include ""float.h"" +/* #include ""matrix.h"" */ + +/* +#ifndef isnan +#define isnan(a) ((a)!=(a)) +#endif +*/ + +/* HELPFUNCTIONS */ + +/* estimate x,y,z position of index i in an array size sx,sxy=sx*sy... */ +void ind2sub(int i,int *x,int *y, int *z, int sxy, int sy) { + *z = (int)floor( (double)i / (double)sxy ) +1; + i = i % (sxy); + *y = (int)floor( (double)i / (double)sy ) +1; + *x = i % sy + 1; +} + +int sub2ind(int x,int y, int z, const int s[]) { + int i=(z-1)*s[0]*s[1] + (y-1)*s[0] + (x-1); + if (i<0 || i>s[0]*s[1]*s[2]) i=1; + return i; +} + +float abs2(float n) { if (n<0.0) return -n; else return n; } +float sign(float n) { if (n<0.0) return 1.0; else return 0.0; } +float max2(float a, float b) { if (a>b) return a; else return b; } +float min2(float a, float b) { if (a5) mexErrMsgTxt(""ERROR:cat_vol_downcut: too many input elements.\n""); + if (nlhs>2) mexErrMsgTxt(""ERROR:cat_vol_downcut: too many output elements.\n""); + if (mxIsSingle(prhs[0])==0) mexErrMsgTxt(""ERROR:cat_vol_downcut: first input must be an 3d single matrix\n""); + if (mxIsSingle(prhs[1])==0) mexErrMsgTxt(""ERROR:cat_vol_downcut: second input must be an 3d single matrix\n""); + if (mxIsDouble(prhs[2])==0 || mxGetNumberOfElements(prhs[2])!=1) mexErrMsgTxt(""ERROR:cat_vol_downcut: third input must one double value\n""); + if (nrhs==4 && mxIsDouble(prhs[3])==0) mexErrMsgTxt(""ERROR:cat_vol_downcut: fourth input must be an double matrix\n""); + if (nrhs==4 && mxGetNumberOfElements(prhs[3])!=3) mexErrMsgTxt(""ERROR:cat_vol_downcut: fourth input must have 3 Elements""); + if (nrhs==5 && mxIsDouble(prhs[4])==0) mexErrMsgTxt(""ERROR:cat_vol_downcut: fifth input must be an double matrix\n""); + if (nrhs==5 && mxGetNumberOfElements(prhs[4])!=2) mexErrMsgTxt(""ERROR:cat_vol_downcut: fifth input must have 2 Elements""); + + /* main information about input data (size, dimensions, ...) */ + const mwSize *sL = mxGetDimensions(prhs[0]); + const int dL = mxGetNumberOfDimensions(prhs[0]); + const int nL = mxGetNumberOfElements(prhs[0]); + const int x = (int)sL[0]; + const int y = (int)sL[1]; + const int xy = x*y; + + const mwSize sSS[2] = {1,3}, sdsv[2] = {1,2}; + mxArray *SS = mxCreateNumericArray(2,sSS, mxDOUBLE_CLASS,mxREAL); double*S = mxGetPr(SS); + mxArray *dsv = mxCreateNumericArray(2,sdsv,mxDOUBLE_CLASS,mxREAL); double*dd = mxGetPr(dsv); + float dI=0.0; double*SEGd; if (nrhs>=3) {SEGd=mxGetPr(prhs[2]); dI=(float) SEGd[0];}; + if (nrhs<4) {S[0]=1.0; S[1]=1.0; S[2]=1.0;} else {S=mxGetPr(prhs[3]);} + if (nrhs<5) {dd[0]=0.1; dd[1]=10;} else {dd=mxGetPr(prhs[4]);} /* THIS SEAMS TO BE INOPTIMAL IN THE SIMPLE EXAMPLES - DO FURTHER TESTS */ + /* if (nrhs<5) {dd[0]=10; dd[1]=0.1;} else {dd=mxGetPr(prhs[4]);} */ + + float s1 = abs2((float)S[0]),s2 = abs2((float)S[1]),s3 = abs2((float)S[2]); + const float s12 = sqrt( s1*s1 + s2*s2); /* xy - voxel size */ + const float s13 = sqrt( s1*s1 + s3*s3); /* xz - voxel size */ + const float s23 = sqrt( s2*s2 + s3*s3); /* yz - voxel size */ + const float s123 = sqrt(s12*s12 + s3*s3); /* xyz - voxel size */ + + /* indices of the neighbor Ni (index distance) and euclidean distance NW */ + const int NI[26] = { 1, -1, x, -x, xy,-xy, -x-1,-x+1,x-1,x+1, -xy-1,-xy+1,xy-1,xy+1, -xy-x,-xy+x,xy-x,xy+x, -xy-x-1,-xy-x+1,-xy+x-1,-xy+x+1, xy-x-1,xy-x+1,xy+x-1,xy+x+1}; + const float ND[26] = { s1, s1, s2, s2, s3, s3, s12, s12,s12,s12, s13, s13, s13, s13, s23, s23, s23, s23, s123, s123, s123, s123, s123, s123, s123, s123}; + + int ni,u,v,w,nu,nv,nw; + + /* main volumes - actual without memory optimization ... */ + plhs[0] = mxCreateNumericArray(dL,sL,mxSINGLE_CLASS,mxREAL); /* label map */ + plhs[1] = mxCreateNumericArray(dL,sL,mxSINGLE_CLASS,mxREAL); /* tissue map (speed) */ + + /* input variables */ + float*ALAB = (float *)mxGetPr(prhs[0]); /* label map */ + float*SEG = (float *)mxGetPr(prhs[1]); /* tissue map */ + + /* output variables */ + float*SLAB = (float *)mxGetPr(plhs[0]); /* label map */ + float*DIST = (float *)mxGetPr(plhs[1]); /* distance map */ + + int nCV = 0; /* # voxel of interest (negative voxel that have to processed) */ + int kll; + int kllv = 2000; + float DISTN; + + /* initialisation of parameter volumes */ + for (int i=0;i0 && kll0 ) { + kll++; nC=0; + + for (int i=0;i=nL) || (abs(nu-u)>1) || (abs(nv-v)>1) || (abs(nw-w)>1) )==0 && (SEG[i]+dI)>=(SEG[ni]) && ALAB[ni]==0.0 ) { + if (nrhs==5) DISTN = DIST[i] + ((float) dd[0])*ND[n] + ((float) dd[1]) * max2(0.0,min2(1.0,SEG[ni])); + else DISTN = DIST[i] + ((float) dd[0])*ND[n] + ((float) dd[1]) * max2(0.0,4.0 - max2(0.0,SEG[ni])); + + /*if ( DISTN>0 && (abs2(DIST[ni])>abs2(DISTN)) && (( (ni<0) || (ni>=nL) || (abs(nu-u)>1) || (abs(nv-v)>1) || (abs(nw-w)>1) )==0) ) { */ + if ( (DIST[ni]!=-FLT_MAX) && (abs2(DIST[ni])>abs2(DISTN)) ) { + if (DIST[ni]>0) nCV++; nC++; + DIST[ni] = -DISTN; + SLAB[ni] = SLAB[i]; + } + } + } + if (DIST[i]==0.0) DIST[i]=-FLT_MAX; /* demark start points */ + + } + } + + } + /*printf(""(%d,%d)"",nCV,kll); */ + + /* clear internal variables + mxDestroyArray(plhs[1]); + mxDestroyArray(plhs[2]); + */ + +} +","C" +"Neurology","ChristianGaser/cat12","cat_tst_calc_kappa.m",".m","19099","478","function varargout=cat_tst_calc_kappa(P,Pref,opt) +% ______________________________________________________________________ +% Estimates Kappa for a set of input images P to one or an equal number of +% reference image(s) Pref. Use realignment if image properties does not +% match. +% +% [txt,val] = cat_tst_calc_kappa(P,Pref,opt) +% +% P .. list of images +% Pref .. ground truth segmentation +% opt +% .methodname .. just to display (default = datasubpath) +% .verb .. verbose level (default = 1) +% .realign .. force realignment (default = 0) +% .realignres .. resolution of realignment (default = 1.5) +% .diffimg .. write difference image (default = 0) +% .testcase .. evaluation of specific label maps (default = 'auto') +% .finishsound .. bong (default = 0) +% ... +% .spaces .. length of filename field (default = 50) +% ______________________________________________________________________ +% based on cg_calc_kappa by Christian Gaser +% +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ +% ______________________________________________________________________ +%#ok<*AGROW> +%#ok<*ASGLU> + +% ______________________________________________________________________ +% ToDo: +% - opt.fname .. csv-result file % not yet +% - single segment comparison with input of the first image c1 or p1 +% - csv file export +% - xml file update / export +% - update for 4 class p0 case of CAT12 +% - interpolate to gt resolution +% +% - slicewise and tissue class based evaluation +% ______________________________________________________________________ + + +% set defaults, get files: +% spm('Defaults','FMRI'); + + +% initialize output + txt = ''; + val = struct('fname','','path','','name','', ... + 'BE',struct('kappa',[],'accuracy',[],'FP','','FN','', ... + 'sensit_all',[],'sensit',[],'specif',[],'dice',[],'jaccard',[]),... + 'SEG',struct('kappa',[],'rms',[],'kappaGW',[],'rmsGW',[])); + if nargout>0, varargout{1}=''; end + if nargout>1, varargout{2}={''}; end + if nargout>2, varargout{3}=val; end + + +% first input - test data + if ~exist('P','var') || isempty(P) || isempty(P{1}) + P = spm_select(Inf,'image','Select images to compare'); + else + if isa(P,'cell'), if size(P,1)0)-1); + case 'binary' + ncls = 1; + case 'IBSR' + ncls = 3; + case 'p03' + ncls = 3; + case 'p04', + ncls = 4; + otherwise + ncls = max(round(vol(:))); + if ncls==255, ncls=1; + elseif ncls==254, ncls=3; % IBSR + elseif ncls==4, ncls=3; % default 3-class label images with CSF,GM and WM (and + end + end + clear vol; + +% rating system and color output + MarkColor = cat_io_colormaps('marks+',40); + setnan = [0 nan]; + evallinearb = @(x,best,worst,marks) min(marks,max( 1,(abs(best-x) ./ ... + abs(diff([worst,best]))*(marks-1)+1))) + setnan(isnan(x)+1); + estr = sprintf('%s\n%s\n\n',spm_str_manip(P(1,:),'h'),Vref(1).fname); + + Yp0toC = @(Yp0,c) 1-min(1,abs(Yp0-c)); +% loop + for nc=1:(ncls>1 && nargout>2)+1 + + + % create header of output table + if opt.verb>1 + fprintf('cat_tst_calc_kappa with %d classes.\n',ncls); + end + switch ncls + case 0, txt{1}='Error ground truth empty!'; continue + case 1, tab = {['File ' sprintf(sprintf('%%%ds',opt.spaces-4),opt.methodname)],... + 'kappa','jaacard','dice','sens.','spec.','FP(F)','FN(N)','N/(P+N)','RMS'}; + txt{1} = sprintf(sprintf('\\n%%%ds%%6s%%8s%%8s%%8s%%8s%%8s%%8s%%8s%%8s%%8s\\n',opt.spaces),... + estr,tab{1},tab{2},tab{3},tab{4},tab{5},tab{6},tab{7},tab{8},tab{9},tab{10}); + k = zeros(n,9); + case 3, tab = {['File ' sprintf(sprintf('%%%ds',opt.spaces-4),opt.methodname)],... + 'K(C)','K(G)','K(W)','K(CGW)','K(B)','RMS(C)','RMS(G)','RMS(W)','RMS(CGW)','RMS(B)'}; + txt{1} = sprintf(sprintf('\\n%%%ds%%s%%8s%%8s%%8s%%8s%%8s |%%8s%%8s%%8s%%8s%%8s\\n',opt.spaces),... + estr,tab{1},tab{2},tab{3},tab{4},tab{5},tab{6},tab{7},tab{8},tab{9},tab{10},tab{11}); + k = zeros(n,10); + end + txt{2} = ''; + if opt.verb && ~isempty(txt{1}) && opt.verb>1, fprintf(txt{1}); end + + + % data evaluation + for i=1:n + %% for all test cases + [pth, name] = fileparts(V(i).fname); + val(i).fname = V(i).fname; + val(i).path = pth; + val(i).name = name; + fnamestr = [spm_str_manip(pth,sprintf('k%d',max(0,min(floor(opt.spaces/3),opt.spaces-numel(name)-1)-1))),'/',... + spm_str_manip(name,sprintf('k%d',opt.spaces - floor(opt.spaces/3)))]; + + % if only one ground-truth image is give use this, otherwise their + % should be a gound-truth for each image + if numel(Vref)==numel(V), Vrefi=i; else Vrefi=1; end + if numel(Vref)==numel(V) || i==1 + vol1 = single(spm_read_vols(Vref(Vrefi))); + end + vx_vol = sqrt(sum(Vref(Vrefi).mat(1:3,1:3).^2)); + + % realginment + if any(V(i).dim ~= Vref(Vrefi).dim) %|| any(V(i).mat(:) ~= Vref(Vrefi).mat(:)) + [pp,ff,ee] = spm_fileparts(V(i).fname); + if opt.realign + Vir = [tempname ee]; + try + copyfile(V(i).fname,Vir); + spm_realign(char([{Vref(Vrefi).fname};{Vir}]),... + struct('sep',opt.realignres,'rtm',0,'interp',4,'graphics',0,'fwhm',opt.realignres)); + fprintf(repmat('\b',1,73*3+1)) + catch + delete(Vir); + end + else + Vir = V(i).fname; + end + [V(i),vol2] = cat_vol_imcalc(Vir,Vref(Vrefi),'i1',struct('interp',6,'verb',0)); + else + vol2 = single(spm_read_vols(V(i))); + end + + + %% ds('l2','',1,vol2/ncls,vol1/ncls,vol2/ncls,vol1/ncls,126) + switch opt.testcase + case 'slices' + %% + vol1 = round(vol1); + %vol2 = round(vol2); + + xsum = shiftdim(sum(sum(vol1,2),3),1); xslices = find(xsum>max(xsum)*.1); + ysum = sum(sum(vol1,1),3); yslices = find(ysum>max(ysum)*.1); + zsum = shiftdim(sum(sum(vol1,1),2),1); zslices = find(zsum>max(zsum)*.1); + mask = false(size(vol1)); + for xi=1:numel(xslices), mask(xslices(xi),:,:) = true; end + for yi=1:numel(yslices), mask(:,yslices(yi),:) = true; end + for zi=1:numel(zslices), mask(:,:,zslices(zi)) = true; end + %% + switch ncls + case 1 + [kappa_all, kappa, accuracy_all, accuracy, sensit_all, sensit, specif, confusion, dice, jaccard] = ... + cg_confusion_matrix( uint8(vol1(mask(:))>0) + 1, uint8( round(vol2(mask(:))) == max(vol1(:))-1) + 1, 2); + + % rms for GM class + rms = sqrt( cat_stat_nanmean( ( (vol1(mask(:))>0) - Yp0toC(vol2(mask(:)),2) ).^2 ) ); + + FP = confusion(1,2); FN = confusion(2,1); + k(i,:) = [kappa_all,jaccard(1),dice(1),sensit(1),sensit(2),FP,FN,FN/(FN+FP),rms]; + txti = sprintf(sprintf('%%%ds:%%8.4f%%8.4f%%8.4f%%8.4f%%8.4f%%8.0f%%8.0f%%8.4f%%8.4f\\n',opt.spaces),... + fnamestr,k(i,:)); + + val(i).BE = struct('kappa',kappa_all,'accuracy',accuracy_all, ... + 'FP',FP,'FN',FN, ... + 'sensit_all',sensit_all,'sensit',sensit(1),'specif',specif(1),'dice',dice(1),'jaccard',jaccard(1),'rms',rms); + colori = mean(kappa_all); + case 3 + vol1o = vol1; vol1 = (vol1o==1) + (vol1o==3)*2 + (vol1o==6)*3 + (vol1o==5)*4; +%% + if opt.allkappa + [kappa_all,kappa] = cg_confusion_matrix( uint8(round(vol1(mask(:))+1)) ,uint8(round(vol2(mask(:))+1)), 4); + kappa_all = [kappa(2:4)' kappa_all kappa(1)]; + else + for c=1:2, kappa_all(1,c) = cg_confusion_matrix(uint8((round(vol1(mask(:)))==c)+1),uint8((round(vol2(mask(:)))==c)+1), 2); end + c=3; kappa_all(1,c) = cg_confusion_matrix(uint8((round(vol1(mask(:)))==c)+1),uint8((round(vol2(mask(:)))>=c)+1), 2); + bth=0.5; kappa_all(1,5) = cg_confusion_matrix(uint8((vol1(mask(:))>=bth)+1 ),uint8((vol2(mask(:))>=bth)+1 ), 2); + kappa_all(1,4) = mean(kappa_all(1,1:3)); + end + % rms + rms = calcRMS(vol1(mask(:)),vol2(mask(:))); rms = [rms(1:3) mean(rms(1:3)) rms(4)]; + k(i,:) = [kappa_all,rms]; + txti = sprintf(sprintf('%%%ds:%%8.4f%%8.4f%%8.4f%%8.4f%%8.4f |%%8.4f%%8.4f%%8.4f%%8.4f%%8.4f\\n', ... + opt.spaces),fnamestr,k(i,:)); + + val(i).SEG = struct('kappa',kappa_all(1:3),'rms',rms(1:3),'kappaGW',kappa_all(4),'rmsGW',rms(4)); + + %val(i).BE = struct('kappa',kappa_all,'accuracy',accuracy_all, ... + % 'FP',FP,'FN',FN, ... + % 'sensit_all',sensit_all,'sensit',sensit(1),'specif',specif(1),'dice',dice(1),'jaccard',jaccard(1),'rms',rms); + + colori = mean(kappa_all(1,2:3)); % colori = kappa_all(4); + end + otherwise + %% + + + + if opt.diffimg + [pp,ff,ee] = spm_fileparts(V(i).fname); + [pr,fr] = spm_fileparts(Vref(Vrefi).fname); + + Vd = Vref(Vrefi); + %Vd.fname = fullfile(pp,['diffimg.' strrep(ff,'-','') '-' strrep(fr,'-','') '.' genvarname(strrep(opt.methodname,'/','-')) ee]); + Vd.fname = fullfile(pr,['diffimg.' ff '.' fr '.' ... + strrep(genvarname(strrep(['XNT',opt.methodname],'/','-')),'XNT','') ee]); + spm_write_vol(Vd,vol2-vol1); + end + + + + + %% class-based evaluation + switch ncls + case 1 + %if length(Vref)==n, vol1 = spm_read_vols(Vref(i))/255+1; + %else vol1 = spm_read_vols(Vref(i)); + %end + + maxv=max((vol1(:))); if maxv==255, vol1=vol1/maxv; else vol1=vol1/maxv; end + + [kappa_all, kappa, accuracy_all, accuracy, sensit_all, sensit, specif, confusion, dice, jaccard] = ... + cg_confusion_matrix(uint8((round(vol1(:))>opt.th1)+1), uint8((round(vol2(:))>opt.th2)+1), 2); + + rms = sqrt( cat_stat_nanmean( ( ( vol1(:) - vol2(:) ).^2 ) )); + + FP = confusion(1,2); FN = confusion(2,1); + k(i,:) = [kappa_all,jaccard(1),dice(1),sensit(1),sensit(2),FP,FN,FN/(FN+FP),rms]; + txti = sprintf(sprintf('%%%ds:%%8.4f%%8.4f%%8.4f%%8.4f%%8.4f%%8.0f%%8.0f%%8.4f%%8.4f\\n',opt.spaces),... + fnamestr,k(i,:)); + + val(i).BE = struct('kappa',kappa_all,'accuracy',accuracy_all, ... + 'FP',FP,'FN',FN, ... + 'sensit_all',sensit_all,'sensit',sensit(1),'specif',specif(1),'dice',dice(1),'jaccard',jaccard(1)); + colori = mean(kappa_all); + case 3 + maxv=max((vol1(:))); + switch opt.testcase + case 'IBSR' + vol1=round(vol1); + if maxv>3 + vol1=round(((vol1-64)/(maxv-64)) * 3); + end + otherwise + if maxv>4, vol1=round(vol1); vol1=vol1/maxv*3; end + end + + if 0 + % temporare + % bei dem BWP test bei fsl gibts einen ungekl??rten versatz + if ~isempty(strfind(upper(V(i).fname),'FSL')) && ~isempty(strfind(upper(V(i).fname),'BWP')) + vol2(2:end,:,:)=vol2(1:end-1,:,:); + end + end + + if opt.allkappa + [kappa_all,kappa] = cg_confusion_matrix( uint8(round(vol1(:)+1)) ,uint8(round(vol2(:)+1)), 4); + kappa_all = [kappa(2:4)' kappa_all kappa(1)]; + else + for c=1:2, kappa_all(1,c) = cg_confusion_matrix(uint8((round(vol1(:))==c)+1),uint8((round(vol2(:))==c)+1), 2); end + c=3; kappa_all(1,c) = cg_confusion_matrix(uint8((round(vol1(:))==c)+1),uint8((round(vol2(:))>=c)+1), 2); + bth=0.5; kappa_all(1,5) = cg_confusion_matrix(uint8((vol1(:)>=bth)+1 ),uint8((vol2(:)>=bth)+1 ), 2); + kappa_all(1,4) = mean(kappa_all(1,1:3)); + end + + rms = calcRMS(vol1,vol2); rms = [rms(1:3) mean(rms(1:3)) rms(4)]; + k(i,:) = [kappa_all,rms]; + txti = sprintf(sprintf('%%%ds:%%8.4f%%8.4f%%8.4f%%8.4f%%8.4f |%%8.4f%%8.4f%%8.4f%%8.4f%%8.4f\\n', ... + opt.spaces),fnamestr,k(i,:)); + + val(i).SEG = struct('kappa',kappa_all(1:3),'rms',rms(1:3),'kappaGW',kappa_all(4),'rmsGW',rms(4)); + switch opt.testcase + case 'IBSR' + colori = mean(kappa_all(2:3)); + otherwise + colori = kappa_all(4); + end + otherwise + if numel(Vref)==numel(V), Vrefi=i; else Vrefi=1; end + vol1 = single(spm_read_vols(Vref(Vrefi))); + vol2 = single(spm_read_vols(V(i))); + + for c=1:ncls, kappa_all(i,c) = cg_confusion_matrix(uint8((round(vol1(:))==c)+1),uint8((round(vol2(:))==c)+1), 2); end + colori = mean(kappa_all); + end + if exist('Vo','var') && exist(Vo.fname,'file') + txti = [txti(1:end-1) 'i' txti(end)]; + delete(Vo.fname); + clear Vo; + end + end + + %% + if opt.verb + if ncls==1 && ~strcmp(opt.testcase,'slices') + cat_io_cprintf(MarkColor(round(min(40,max(1,evallinearb(colori,1.00,0.80,6)/10*40))),:),txti); + else + cat_io_cprintf(MarkColor(round(min(40,max(1,evallinearb(colori,0.95,0.65,6)/10*40))),:),txti); + end + end; + txt{2}=[txt{2} txti]; tab=[tab;[{name},num2cell(k(i,:))]]; + end + + + %% conclustion + if numel(n) + switch ncls + case 1, txt{3} = sprintf(sprintf( ... + ['\\n%%%ds:%%8.4f%%8.4f%%8.4f%%8.4f%%8.4f%%8.0f%%8.0f%%8.4f%%8.4f\\n', ... + '%%%ds:%%8.4f%%8.4f%%8.4f%%8.4f%%8.4f%%8.0f%%8.0f%%8.4f%%8.4f\\n\\n'], ... + opt.spaces,opt.spaces),'mean',mean(k,1),'std',std(k,1,1)); + case 3, txt{3} = sprintf(sprintf( ... + ['\\n%%%ds:%%8.4f%%8.4f%%8.4f%%8.4f%%8.4f |%%8.4f%%8.4f%%8.4f%%8.4f%%8.4f\\n' ... + '%%%ds:%%8.4f%%8.4f%%8.4f%%8.4f%%8.4f |%%8.4f%%8.4f%%8.4f%%8.4f%%8.4f\\n\\n'], ... + opt.spaces,opt.spaces),'mean',mean(k,1),'std',std(k,1,1)); + end + if opt.verb>1 && n>1, fprintf(txt{3}); end; + tab = [tab;[{'mean'},num2cell(mean(k,1));'std',num2cell(std(k,1,1))]]; + end + + % export + if nc==1 + if nargout>0, varargout{1}=txt'; end + if nargout>1, varargout{2}=tab; end + if nargout>2, varargout{3}=val; end + else + if nargout>0, varargout{1}=[varargout{1};txt']; end + if nargout>1, varargout{2}{nc}=tab; end + if nargout>2, varargout{3}{nc}=val; end + end + ncls=1; + end + + if opt.finishsound + load gong.mat; + soundsc(y(5000:25000),Fs) + end +end +function rms=calcRMS(v1,v2) +% boundary box???? + v1(v1>3)=3; + v2(v2>3)=3; + + for ci=1:3 + c1 = (v1-(ci-1)).* (v1>(ci-1) & v1=ci & v1<(ci+1)); + c2 = (v2-(ci-1)).* (v2>(ci-1) & v2=ci & v2<(ci+1)); + rms(1,ci) = sqrt(cat_stat_nanmean((c1(:)-c2(:)).^2)); + end + + rms(1,4) = sqrt(cat_stat_nanmean((v2(:)-v1(:)).^2)); +end +function varargout = cg_confusion_matrix(reference, classified, n_class) +% compute statistic from confusion matrix +% [kappa_all, kappa, accuracy_all, accuracy, sensit_all, sensit, specif, confusion] = cg_confusion_matrix(reference, classified, n_class) + + % get sure that image is integer + + if nargin < 3 + n_class = max(classified); + end + + % build confusion matrix + confusion = zeros(n_class,n_class); + for i = 1:n_class + for j = 1:n_class + confusion(i,j) = length(find(round(reference)==i & round(classified)==j)); + end + end + + N = sum(confusion(:)); + kappa = zeros(size(confusion,1),1,'single'); + sensit = zeros(size(confusion,1),1,'single'); + specif = zeros(size(confusion,1),1,'single'); + accuracy = zeros(size(confusion,1),1,'single'); + + sum_col = sum(confusion,1); + sum_row = sum(confusion,2); + + Pc = 0; + for i = 1:n_class + sum_row_x_col = sum_row(i)*sum_col(i); + + % calculate a..d of confusion matrix + a = confusion(i,i); + b = sum_col(i) - a; + c = sum_row(i) - a; + d = N - (a + b + c); + + specif(i) = d/(b+d); + sensit(i) = a/(a+c); + accuracy(i) = 1-(b+c)/N; + dice(i) = d/(0.5*(d+d+b+c)); % Shattuck 2008, Online resource for validation of brain segmentation methods + jaccard(i) = d/(d+b+c); % Shattuck 2008, Online resource for validation of brain segmentation methods + + kappa(i) = (N*confusion(i,i) - sum_row_x_col)/(N*sum_row(i) - sum_row_x_col + eps); + Pc = Pc + sum_row_x_col/N^2; + end + + P0 = sum(diag(confusion))/N; + + kappa_all = (P0-Pc)/(1-Pc); + sensit_all = P0; + accuracy_all = P0; + + varargout{1} = kappa_all; + varargout{2} = kappa; + varargout{3} = accuracy_all; + varargout{4} = accuracy; + varargout{5} = sensit_all; + varargout{6} = sensit; + varargout{7} = specif; + varargout{8} = confusion; + varargout{9} = dice; + varargout{10} = jaccard; +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_vol_localstat.c",".c","17474","432","/* Local Mean, Minimum, Maximum, SD, and Peak estimation + * ________________________________________________________________________ + * Estimates specific functions in a volume V within a mask region M. + * For each voxel v of M, the values of the neigbors of v that belong to M + * and are within a distance smaller than nb where used (i.e. masked voxels + * within a sphere of radius nb). + * + * If V contains NaNs, -INFs or INFs these values are ignored and added to + * the mask M. Masked voxels in the output volume were defined depending + * on the mskval variable, i.e. as zeros (0, default), input (1), NANs (2), + * -INF (3), or INF(4). + * + * The function was designed to extract the inhomogeneity in noisy data in + * a well-known area, such a tissue class in structural images. In general + * the mean estimated in a local neighborhood nb or after some interations + * iter. However, tissues are often affected by partial volume effects near + * the tissue boundaries and minimum/maximum can be quite helpful to reduce + * such effects. For noise estimation the local variance/standard deviation + * is also quite useful. + * Besides the mean value the local peak of the histogram can also work + * + * S = cat_vol_localstat(V,M[,nb,stat,iter,filter0,verb]) + * + * V (single) input volume + * M (logical) mask volume + * nb (double) neigbhour distance (1 .. 10) + * stat (double) 1-mean, 2-min, 3-max, 4-std + * 5-peak1, 6-peak2, 7-peak3 (experimental) + * 8-median + * 9-hist (experimental) + * iter number of iterations (default=1) + * filter0 (double) originally values <=0 were ignored (default=0) + * mskval (double) setting of masked voxels + * (0-zeros,1-input,2-NAN,3--INF,4-INF) + * verb (double) verbose output for debugging + * + * + * Examples: + * Here are some simple samples to outline the subfunctions. The mask area + * is defined by NaN. The simulated data of A is between -1 and 1 and B is + * a locial mask. + * + * == input variables == + * A = rand(20,20,3,'single') - 1; + * for i=1:size(A,2), A(:,i,:) = A(:,i,:) + (( i/size(A,2) ) - 0.5); end + * B = smooth3(smooth3(rand(size(A))))>0.5; + * + * + * == function calls == + * (1) MEAN: values around 0 + * C = cat_vol_localstat(A,B,2,1,2,2); ds('d2smns','',1,A,C,2); + * + * (2) MINIMUM: values trending torwards -1 + * C = cat_vol_localstat(A,B,2,2,2,2); ds('d2smns','',1,A,C,2); + * + * (3) MAXIMUM: values trending torwards 1 + * C = cat_vol_localstat(A,B,2,3,2,2); ds('d2smns','',1,A,C,2); + * + * (4) STANDARD DEVIATION: values about 0.5 + * C = cat_vol_localstat(A,B,2,4,1,2); ds('d2smns','',1,A,C,2); + * + * (8) MEDIAN: values around 0 + * C = cat_vol_localstat(AL,B,2,8,1,2); ds('d2smns','',1,A,C,2); + * ______________________________________________________________________ + * + * Christian Gaser, Robert Dahnke + * Structural Brain Mapping Group (https://neuro-jena.github.io) + * Departments of Neurology and Psychiatry + * Jena University Hospital + * ______________________________________________________________________ + * $Id$ + */ + +#include ""mex.h"" +#include ""math.h"" +#include ""float.h"" +#include +#include + +#ifndef ROUND +#define ROUND( x ) ((long) ((x) + ( ((x) >= 0) ? 0.5 : (-0.5) ) )) +#endif + +#ifdef _MSC_VER + #define FINFINITY (FLT_MAX+FLT_MAX); + static const unsigned long __nan[2] = {0xffffffff, 0x7fffffff}; + #define FNAN (*(const float *) __nan) +#else + #define FINFINITY 1.0f/0.0f; + #define FNAN 0.0f/0.0f +#endif + +#ifndef min +#define min(a,b) (((a)<(b))?(a):(b)) +#endif +#ifndef max +#define max(a,b) (((a)>(b))?(a):(b)) +#endif + +#define index(A,B,C,DIM) ((C)*DIM[0]*DIM[1] + (B)*DIM[0] + (A)) + + +/* qicksort for median */ +void swap_float(float *a, float *b) +{ + float t=*a; *a=*b; *b=t; +} + +void sort_float(float arr[], int beg, int end) +{ + if (end > beg + 1) + { + float piv = arr[beg]; + int l = beg + 1, r = end; + while (l < r) + { + if (arr[l] <= piv) + l++; + else + swap_float(&arr[l], &arr[--r]); + } + swap_float(&arr[--l], &arr[beg]); + sort_float(arr, beg, l); + sort_float(arr, r, end); + } +} + + +/* floating point versions */ +float abs2(float n) { if (n<0) return -n; else return n; } +float pow2(float n) { return n*n; } + + +/* main function */ +void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { + /* check size of in-/output */ + if (nrhs<2) mexErrMsgTxt(""ERROR:cat_vol_localstat: Not enough input elements\n""); + if (nrhs>8) mexErrMsgTxt(""ERROR:cat_vol_localstat: Too many input elements\n""); + if (nlhs<1) mexErrMsgTxt(""ERROR:cat_vol_localstat: Not enough output elements\n""); + if (nlhs>1) mexErrMsgTxt(""ERROR:cat_vol_localstat: Too many output elements\n""); + + + /* main information about input data (size, dimensions, ...) */ + const mwSize *sL = mxGetDimensions(prhs[0]); + const int dL = mxGetNumberOfDimensions(prhs[0]); + const int nL = mxGetNumberOfElements(prhs[0]); + const int dB = mxGetNumberOfDimensions(prhs[0]); + const int nB = mxGetNumberOfElements(prhs[0]); + + + /* test properties of input */ + if ( dL != 3 || mxIsSingle(prhs[0])==0) mexErrMsgTxt(""ERROR:cat_vol_localstat: First input must be a single 3d matrix\n""); + if ( dB != 3 || mxIsLogical(prhs[1])==0 || nL != nB ) mexErrMsgTxt(""ERROR:cat_vol_localstat: Second input must be a logical 3d matrix with equal size than input 1\n""); + + + /* set control parameter and defaults */ + int nh, st, iter, mskval, filter0, verb; + if (nrhs<3) nh = 1; else {double *dnh = (double *) mxGetPr(prhs[2]); nh = (int) round( dnh[0] );} + if (nrhs<4) st = 1; else {double *dst = (double *) mxGetPr(prhs[3]); st = (int) round( dst[0] );} + if (nrhs<5) iter = 1; else {double *diter = (double *) mxGetPr(prhs[4]); iter = (int) round( diter[0] );} + if (nrhs<6) mskval = 0; else {double *dmskval = (double *) mxGetPr(prhs[5]); mskval = (int) round( dmskval[0] );} + if (nrhs<7) filter0 = 0; else {double *dfilter0 = (double *) mxGetPr(prhs[6]); filter0 = (int) ( dfilter0[0]>0 );} + if (nrhs<8) verb = 0; else {double *dverb = (double *) mxGetPr(prhs[7]); verb = (int) ( dverb[0]>0 );} + /* check control parameter */ + if ( nh > 10 ) mexErrMsgTxt(""ERROR:cat_vol_localstat: Number of neighbors is limited to 10. (Use reduce resolution instead.) \n""); + if ( st<1 || st>9 ) mexErrMsgTxt(""ERROR:cat_vol_localstat: Fourth input has to be 1=mean, 2=min, 3=max, 4=std, 5=peak1, 6=peak2, 7=peak3, 8=median, 9=hist. \n""); + if ( (st>4 && st<8) || st>8 ) mexErrMsgTxt(""ERROR:cat_vol_localstat: Experimental function! \n""); + if ( iter<1 ) printf(""WARNING:cat_vol_localstat: Number of iteration is 0 and nothing is done except masking! \n""); + if ( mskval<0 || mskval>4 ) mexErrMsgTxt(""ERROR:cat_vol_localstat: mskval has to be 0=zeros,1=input,2=NAN,3=-INF,4=INF. \n""); + + + /* input varialbes */ + const float *D = (float *) mxGetPr(prhs[0]); + const bool *B = (bool *) mxGetPr(prhs[1]); + + + /* create and initialise output variables and internal variables */ + mxArray *hlps[4], *msks[1]; + plhs[0] = mxCreateNumericArray(dL,sL,mxSINGLE_CLASS,mxREAL); float *M = (float *) mxGetPr(plhs[0]); /* only real output */ + hlps[0] = mxCreateNumericArray(dL,sL,mxSINGLE_CLASS,mxREAL); float *M2 = (float *) mxGetPr(hlps[0]); /* helping variable */ + hlps[1] = mxCreateNumericArray(dL,sL,mxSINGLE_CLASS,mxREAL); float *M3 = (float *) mxGetPr(hlps[1]); /* helping variable */ + hlps[2] = mxCreateNumericArray(dL,sL,mxSINGLE_CLASS,mxREAL); float *MD = (float *) mxGetPr(hlps[2]); /* helping variable */ + msks[0] = mxCreateLogicalArray(dL,sL); bool *MB = (bool *) mxGetPr(msks[0]); /* helping variable */ + /* initialise */ + for (int i=0;i1000) HISTmax=1000; */ + int HISTmin=0; + + + /* + * Display initial parameter + */ + if ( verb ) { + printf(""\ncat_vol_localstat.c debuging mode:\n Initialize Parameter: \n""); + printf("" size(B) = %d %d %d\n"",(int)sL[0],(int)sL[1],(int)sL[2]); + printf("" nb = %d\n"",nh); + printf("" stat = %d\n"",st); + printf("" iter = %d\n"",iter); + printf("" mskval = %d\n"",mskval); + printf("" fitler0 = %d\n"",filter0); + printf("" verb = %d\n"",verb); + } + + + /* prepare special variables for histogram based subfunctions */ + if (st==7) { + for (i=0;iD[i]) HISTmin=(int)D[i]; }; HISTmin--; + for (i=0;i=0) && ((x+i)=0) && ((y+j)=0) && ((z+k)M3[ind]) M3[ind]=NV[nn]; + } + M[ind]/=nx; + } + + /* minimum */ + if (st==2) { M[ind]=MD[ind]; for (nn=0;nnM[ind]) M[ind]=NV[nn];};}; + + /* standard deviation */ + if (st==4) { + M[ind] = 0.0; for (nn=0;nnM[ind]) M[ind]=(float) HIST[nn]; } + M[ind]=M[ind]/(float) HISTmax; + }; + + /* max in histogram 2 */ + if (st==6) { + NVmn = MD[ni]; /*= 0.0; for (nn=0;nnM[ind]) M[ind]=(float) nn;} + /*M[ind]=0; for (nn=0;nn<200;nn++) { if (HIST[nn]>M[ind]) M[ind]=(float) nn;} */ + M[ind]=M[ind]/(float) HISTmax; + M2[ind]=0.0; for (nn=0;nn<(int) ROUND( NVmn * (float) HISTmax);nn++) { if (HIST[nn]>M2[ind]) M2[ind]=(float) nn;} + M2[ind]=M2[ind]/(float) HISTmax; + }; + + /* max in histogram 3 */ + if (st==7) { + for (nn=0;nnNVmn) {NVmn=HIST[nn]; M[ind]=(float) nn;}} + M[ind]=M[ind] + HISTmin; + }; + + + + + /* median */ + if (st==8) { + if (n>nh*nh*nh) { + sort_float(NV,0,n); + md=(int)ROUND(n*0.5); + NVmd = NV[md]; + M[ind] = NV[md]; + } + } + + + + /* =============================================================== + * experimental noise/signal functions + * =============================================================== + */ + if (st==9) { + /* estimation of noise and strukture a subregions (normally the WM) */ + + /* mean (or better median) intensity in the area */ + /* M[ind] = 0.0; for (nn=0;nn1) { if (n==2) { + NVmd = (NV[0] + NV[1]) / 2.0f; + } + else { + sort_float(NV,0,n); + NVmd = NV[(int)(n/2.0)]; + } + } + M[ind] = 0.0; for (nn=0;nn=0 && (x+i)NVmd) { + stdp[di] += (MD[ni]-NVmn)*(MD[ni]-NVmn); stdpc[di]++; + } + else { + stdn[di] += (MD[ni]-NVmn)*(MD[ni]-NVmn); stdnc[di]++; + } + } + } + } + + if ( stddc[di]>1 ) {stdd[di]=sqrtf((float)(stdd[di]/(stddc[di]-1)));} else {stdd[di] = 0.0;} + if ( stdpc[di]>1 ) {stdp[di]=sqrtf((float)(stdp[di]/(stdpc[di]-1)));} else {stdp[di] = 0.0;} + if ( stdnc[di]>1 ) {stdn[di]=sqrtf((float)(stdn[di]/(stdnc[di]-1)));} else {stdn[di] = 0.0;} + } + /* sort_float(stdd,0,2); */ + + M[ind]=stdd[0]; + M2[ind]=stdd[1]; + /* M[ind] = (stdd[0] + stdd[1] + stdd[2])/3 * 2; */ + /* M[ind] = (stdp[0] + stdp[1] + stdp[2])/3 * 2; */ + /* M2[ind] = (stdn[0] + stdn[1] + stdn[2])/3 * 2 - M[ind]; */ + + /* if ((M[ind]==-FLT_MAX) || (MD[ind]==FLT_MAX) || (mxIsNaN(MD[ind])) ) M[ind]=0.0; */ + } + } + } + + /* update for next iteration */ + for (i=0;i= i +% CVA.df - d.f. +% CVA.p - p-values +% +% also saved in CVA_*.mat in the SPM working directory +% +% FORMAT [CVA] = cat_stat_cva_ui('results',CVA) +% Display the results of a CVA analysis +%__________________________________________________________________________ +% +% This routine allows one to make inferences about effects that are +% distributed in a multivariate fashion or pattern over voxels. It uses +% conventional canonical variates (CVA) analysis (also know as canonical +% correlation analysis, ManCova and linear discriminant analysis). CVA is +% a complement to MVB, in that the predictor variables remain the design +% matrix and the response variable is the imaging data in the usual way. +% However, the multivariate aspect of this model allows one to test for +% designed effects that are distributed over voxels and thereby increase +% the sensitivity of the analysis. +% +% Because there is only one test, there is no multiple comparison problem. +% The results are shown in term of the maximum intensity projection of the +% (positive) canonical image or vector and the canonical variates based on +% (maximally) correlated mixtures of the explanatory variables and data. +% +% CVA uses the generalised eigenvalue solution to the treatment and +% residual sum of squares and products of a general linear model. The +% eigenvalues (i.e., canonical values), after transformation, have a +% chi-squared distribution and allow one to test the null hypothesis that +% the mapping is D or more dimensional. This inference is shown as a bar +% plot of p-values. The first p-value is formally identical to that +% obtained using Wilks' Lambda and tests for the significance of any +% mapping. +% +% This routine uses the current contrast to define the subspace of interest +% and treats the remaining design as uninteresting. Conventional results +% for the canonical values are used after the data (and design matrix) have +% been whitened; using the appropriate ReML estimate of non-sphericity. +% +% CVA can be used for decoding because the model employed by CVA does not +% care about the direction of the mapping (hence canonical correlation +% analysis). However, one cannot test for mappings between nonlinear +% mixtures of regional activity and some experimental variable (this is +% what the MVB was introduced for). +% +% References: +% +% Characterizing dynamic brain responses with fMRI: a multivariate +% approach. Friston KJ, Frith CD, Frackowiak RS, Turner R. NeuroImage. 1995 +% Jun;2(2):166-72. +% +% A multivariate analysis of evoked responses in EEG and MEG data. Friston +% KJ, Stephan KM, Heather JD, Frith CD, Ioannides AA, Liu LC, Rugg MD, +% Vieth J, Keber H, Hunter K, Frackowiak RS. NeuroImage. 1996 Jun; +% 3(3):167-174. +%__________________________________________________________________________ +% Copyright (C) 2008-2014 Wellcome Trust Centre for Neuroimaging +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ +% +% modified version of +% Karl Friston +% spm_cva_ui.m 6242 2014-10-14 11:16:02Z guillaume + + +%-Get figure handles +%-------------------------------------------------------------------------- +Finter = spm_figure('FindWin','Interactive'); +try, spm_results_ui('Clear'); end +spm_input('!DeleteInputObj'); + +%-Review old analysis or proceed with a new one +%-------------------------------------------------------------------------- +if ~nargin || isempty(action) + action = spm_input('Canonical Variates Analysis',1,'b', ... + {'New Analysis','Results'}, char({'specify','results'}), 1); + if strcmpi(action,'results'), varargin = {}; end +end + +switch lower(action) + + case 'specify' + %================================================================== + % C V A : S P E C I F Y + %================================================================== + + if nargin < 2 + spmmatfile = spm_select(1,'^SPM\.mat$','Select SPM.mat'); + swd = spm_file(spmmatfile,'fpath'); + load(fullfile(swd,'SPM.mat')); + SPM.swd = swd; + cd(SPM.swd); + + % correct path for surface if analysis was made with different SPM installation + if isfield(SPM.xVol,'G') & ~exist(SPM.xVol.G,'file') + % check for 32k meshes + if SPM.xY.VY(1).dim(1) == 32492 || SPM.xY.VY(1).dim(1) == 64984 + fsavgDir = fullfile(fileparts(mfilename('fullpath')),'templates_surfaces_32k'); + else + fsavgDir = fullfile(fileparts(mfilename('fullpath')),'templates_surfaces'); + end + [SPMpth,SPMname,SPMext] = spm_fileparts(SPM.xVol.G); + SPM.xVol.G = fullfile(fsavgDir,[SPMname SPMext]); + end + + %-Check the model has been estimated + %-------------------------------------------------------------------------- + try + XYZ = SPM.xVol.XYZ; + catch + + %-Check the model has been estimated + %---------------------------------------------------------------------- + str = { 'This model has not been estimated.';... + 'Would you like to estimate it now?'}; + if spm_input(str,1,'bd','yes|no',[1,0],1) + SPM = spm_spm(SPM); + else + SPM = []; xSPM = []; + return + end + end + + [xSPM.Ic,xCon] = spm_conman(SPM,'T&F',Inf,... + ' Select contrasts...',' ',1); + + else + if nargin > 1, xSPM = varargin{1}; end + if nargin > 2, SPM = varargin{2}; end + if nargin > 3, CVA = varargin{3}; end + end + + header = get(Finter,'Name'); + set(Finter,'Name','Canonical Variates analysis') + + %-Contrast specification + %------------------------------------------------------------------ + con = SPM.xCon(xSPM.Ic).name; + c = SPM.xCon(xSPM.Ic).c; + c = full(c); + + %-VOI specification + %------------------------------------------------------------------ + name = con; + name_img = ['CVA_' strrep(name,' ','_')]; + name = ['CVA_' strrep(name,' ','_') '.mat']; + + xyzmm = [0 0 0]; + + %-Specify search volume + %------------------------------------------------------------------ + try + xY = CVA.xY; + CVA = rmfield(CVA,'xY'); + catch + xY = []; + end + xY.xyz = xyzmm; + + Q = ones(1,size(SPM.xVol.XYZ, 2)); + + XYZmm = SPM.xVol.M(1:3,:)*[SPM.xVol.XYZ; Q]; + XYZ = XYZmm; + j = 1:size(XYZmm,2); + + %-Extract required data from results files + %================================================================== + + spm('Pointer','Watch') + + %-Get explanatory variables (data) + %------------------------------------------------------------------ + Y = spm_data_read(SPM.xY.VY,'xyz',SPM.xVol.XYZ(:,j)); + + if isempty(Y) + spm('alert*',{'No voxels in this VOI';'Please use a larger volume'},... + 'Canonical Variates analysis'); + return + end + + %-Remove serial correlations and get design (note X := W*X) + %------------------------------------------------------------------ + Y = SPM.xX.W*Y; + X = SPM.xX.xKXs.X; + + %-Null-space + %------------------------------------------------------------------ + X0 = []; + try, X0 = [X0 blkdiag(SPM.xX.K.X0)]; end %-drift terms + try, X0 = [X0 spm_detrend(SPM.xGX.gSF)]; end %-global estimate + + + %-Canonical Variate Analysis + %================================================================== +% U = spm_mvb_U(Y,'compact',spm_svd([X0, X-X*c*pinv(c)]),XYZmm); +% CVA = spm_cva(Y, X, X0, c, U); + CVA = spm_cva(Y, X, X0, c); + + % check for inverted effects + if any(sign(CVA.C)-sign(c)) + CVA.C = -CVA.C; + CVA.V = -CVA.V; + end + + % scale canonical variates to SD of 1 + for j=1:size(CVA.V,2) + v = CVA.V(:,j); + CVA.V(:,j) = v./(eps + std(v(v ~= 0 & ~isnan(v))));; + end + + %-Save results + %================================================================== + M = SPM.xVol.M(1:3,1:3); %-voxels to mm matrix + VOX = sqrt(diag(M'*M))'; %-voxel dimensions + + %-Assemble results + %------------------------------------------------------------------ + CVA.contrast = con; %-contrast name + CVA.name = name; %-CVA name + + CVA.XYZ = XYZmm; %-locations of voxels (mm) + CVA.xyz = xyzmm; %-seed voxel location (mm) + CVA.VOX = VOX; %-dimension of voxels (mm) + if spm_mesh_detect(SPM.xY.VY) + CVA.xVol = SPM.xVol; + end + + %-Save + %------------------------------------------------------------------ + save(fullfile(SPM.swd,name),'CVA', spm_get_defaults('mat.format')); + + for j=1:size(CVA.V,2) + if CVA.p(j) < 0.05 + if spm_mesh_detect(SPM.xY.VY) + F = spm_file(sprintf('%s_%02d',name_img,j),'ext','.gii'); + F = spm_file(F,'CPath'); + fprintf('Canonical image %s will be saved (significance: P<%g)\n',F,CVA.p(j)); + M = gifti(SPM.xVol.G); + if ~isfield(SPM.xVol.G,'vertices') + SPM.xVol.G = M; + end + C = zeros(1,size(SPM.xVol.G.vertices,1)); + C(SPM.xVol.XYZ(1,:)) = CVA.V(:,j); % or use NODE_INDEX + M.cdata = C; + save(M,F); + cmd = 'spm_mesh_render(''Disp'',''%s'')'; + else + + Y = zeros(SPM.xVol.DIM(1:3)'); + OFF = SPM.xVol.XYZ(1,:) + SPM.xVol.DIM(1)*(SPM.xVol.XYZ(2,:)-1 + SPM.xVol.DIM(2)*(SPM.xVol.XYZ(3,:)-1)); + Y(OFF) = CVA.V(:,j); + + VO = SPM.xY.VY(1); + VO.fname = spm_file(sprintf('%s_%02d',name_img,j),'ext','.nii'); + fprintf('Canonical image %s will be saved (significance: P<%g)\n',VO.fname,CVA.p(j)); + VO.dt = [spm_type('float32') spm_platform('bigend')]; + spm_write_vol(VO,Y); + + cmd = 'spm_image(''display'',''%s'')'; + end + end + end + + assignin('base','CVA',CVA); + + %-Display results + %------------------------------------------------------------------ + cat_stat_cva_ui('results',CVA); + + %-Reset title + %------------------------------------------------------------------ + set(Finter,'Name',header) + spm('Pointer','Arrow') + + + case 'results' + %================================================================== + % C V A : R E S U L T S + %================================================================== + + %-Get CVA if necessary + %------------------------------------------------------------------ + if isempty(varargin) + [CVA,sts] = spm_select(1,'mat',... + 'Select CVA to display',[],[],'^CVA.*\.mat$'); + if ~sts, return; end + else + CVA = varargin{1}; + end + if ischar(CVA) + CVA = load(CVA); + CVA = CVA.CVA; + end + + %-Show results + %------------------------------------------------------------------ + Fgraph = spm_figure('GetWin','Graphics'); + + %-Unpack + %------------------------------------------------------------------ + VOX = CVA.VOX; + XYZ = CVA.XYZ; + + %-Maximum intensity projection (first canonical image) + %------------------------------------------------------------------ + if isfield(CVA,'xVol'); + hMIPax = axes('Parent',Fgraph,'Position',[0.05 0.60 0.45 0.26],'Visible','off'); + hMax = cat_surf_render('Disp',CVA.xVol.G,'Parent',hMIPax); + tmp = zeros(1,prod(CVA.xVol.DIM)); + tmp(CVA.xVol.XYZ(1,:)) = CVA.V(:,1); + mx = max(abs(min(CVA.V(:,1))),abs(max(CVA.V(:,1)))); + hMax = cat_surf_render('Overlay',hMax,tmp); + hMax = cat_surf_render('Colourbar',hMax,'on'); + hMax = cat_surf_render('Colourmap',hMax,jet(64)); + hMax = cat_surf_render('Clip',hMax,[-2 2]); + hMax = cat_surf_render('Clim',hMax,[-mx mx]); + else + subplot(2,2,1) + spm_mip(CVA.V(:,1).*(CVA.V(:,1) > 0),XYZ(1:3,:),diag(VOX)); + axis image + end + title({'(Principal) canonical image',[CVA.name ':' CVA.contrast]}) + + %-Inference and canonical variates + %------------------------------------------------------------------ + Xstr{1} = 'Dimensionality'; + Xstr{2} = ['Chi-squared: ' sprintf('%6.1f ', CVA.chi)]; + Xstr{3} = [' df: ' sprintf('%6.0f ',CVA.df) ]; + + subplot(2,2,2) + bar(log(CVA.p)); hold on + plot([0 (length(CVA.p) + 1)],log(0.05)*[1 1],'r:','LineWidth',4), hold off + xlabel(Xstr) + ylabel('log p-value') + axis square + title({'Test of dimensionality';sprintf('minimum p = %.2e',min(CVA.p))}) + + subplot(2,2,3) + plot(CVA.w,CVA.v,'.') + xlabel('prediction') + ylabel('response') + axis square + title('Canonical variates') + + %-Canonical contrast + %------------------------------------------------------------------ + i = find(CVA.p < 0.05); + str = 'Significant canonical contrasts'; + if isempty(i) + i = 1; + str = 'first canonical contrast'; + end + subplot(2,2,4) + bar(CVA.C(:,i)) + xlabel('Parameter') + axis square + title(str) + + otherwise + error('Unknown action.'); + +end +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_spm_shoot_template.m",".m","13043","419","function out = cat_spm_shoot_template(job) +%cat_spm_shoot_template. Like spm_shoot_template but definable def-file +% +% Iteratively compute a template with mean shape and intensities +% format spm_shoot_template(job) +% Fields of job: +% job.images{1} first set of images (eg rc1*.nii) +% job.images{2} second set of images (eg rc2*.nii) +% etc +% +% Other settings are defined in spm_shoot_defaults.m +% +% The outputs are flow fields (v*.nii), deformation fields (y*.nii) +% and a series of Template images. +%_______________________________________________________________________ +% Copyright (C) Wellcome Trust Centre for Neuroimaging (2009) +% John Ashburner +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +%_______________________________________________________________________ + +d = spm_shoot_defaults; +% ######### CAT12.begin +if isfield(job,'dfile') + % use own default file, print error if it cannot be seen by MATLAB + d = struct(); + [pp,ff,ee] = spm_fileparts(job.dfile{1}); + if ~exist(ff,'file'), error('The given file ""%s"" does not exist (in the MATLAB patch).\n',job.dfile{1}); end + eval(sprintf('d = %s;',ff)); + clear pp ff ee; + + % for the longitudinal processing we need unique filenames + [pp,ff] = spm_str_manip(job.images{1},'trC'); + d.tname = strrep(d.tname,'FNAME',[ff.s(3:end) 'XXX' ff.e]); + clear pp ff; + + % adapt schedule for resolution + V = spm_vol(job.images{1}{1}); + vx_vol = sqrt(sum(V.mat(1:3,1:3).^2)); + d.sched = d.sched ./ prod(vx_vol); +end +% ######### CAT12.end + +tname = d.tname; % Base file name for templates +issym = d.issym; % Use a symmetric template + +cyc_its = d.cyc_its; % No. multigrid cycles and inerations +smits = d.smits; % No. smoothing iterations +sched = d.sched; % Schedule for coarse to fine +nits = numel(sched)-1; +rparam = d.rparam; % Regularisation parameters for deformation +sparam = d.sparam; % Regularisation parameters for blurring +eul_its = d.eul_its; % Start with fewer steps +scale = d.scale; % Fraction of Gauss-Newton update step to use + +bs_args = d.bs_args; % B-spline settings for interpolation +%_______________________________________________________________________ + +spm_diffeo('boundary',0); + +% Sort out handles to images +n1 = numel(job.images); +n2 = numel(job.images{1}); +NF = struct('NI',[],'vn',[1 1]); +NF(n1,n2) = struct('NI',[],'vn',[1 1]); + +% Pick out individual volumes within NIfTI files +for i=1:n1 + if numel(job.images{i}) ~= n2 + error('Incompatible number of images'); + end + for j=1:n2 + [pth,nam,ext,num] = spm_fileparts(job.images{i}{j}); + NF(i,j).NI = nifti(fullfile(pth,[nam ext])); + num = [str2num(num) 1 1]; + NF(i,j).vn = num(1:2); + end +end + +spm_progress_bar('Init',n2,'Initial mean','Subjects done'); +dm = [size(NF(1,1).NI.dat) 1]; +dm = dm(1:3); +M = NF(1,1).NI.mat; + +NU = nifti; +NU(n2) = nifti; +NY = nifti; +NY(n2) = nifti; +NJ = nifti; +NJ(n2) = nifti; + +t = zeros([dm n1+1],'single'); + +for i=1:n2 + % Generate files for flow fields, deformations and Jacobian determinants. + [pth,nam,ext] = fileparts(NF(1,i).NI.dat.fname); + + NU(i) = nifti; + NY(i) = nifti; + NJ(i) = nifti; + + if ~isempty(tname) + NU(i).dat = file_array(fullfile(pth,['v_' nam '_' tname '.nii']),... + [dm 1 3], 'float32-le', 352, 1, 0); + NY(i).dat = file_array(fullfile(pth,['y_' nam '_' tname '.nii']),... + [dm 1 3], 'float32-le', 352, 1, 0); + NJ(i).dat = file_array(fullfile(pth,['j_' nam '_' tname '.nii']),... + [dm 1 1], 'float32-le', 352, 1, 0); + else + NU(i).dat = file_array(fullfile(pth,['v_' nam '.nii']),... + [dm 1 3], 'float32-le', 352, 1, 0); + NY(i).dat = file_array(fullfile(pth,['y_' nam '.nii']),... + [dm 1 3], 'float32-le', 352, 1, 0); + NJ(i).dat = file_array(fullfile(pth,['j_' nam '.nii']),... + [dm 1 1], 'float32-le', 352, 1, 0); + end + + NU(i).descrip = sprintf('Velocity (%.4g %.4g %.4g %.4g %.4g)', rparam(1), rparam(2), rparam(3), rparam(4), rparam(5)); + NU(i).mat = M; + NU(i).mat0 = NF(1,i).NI.mat0; + + NY(i).descrip = 'Deformation (templ. to. ind.)'; + NY(i).mat = M; + NY(i).mat0 = M; + + NJ(i).descrip = 'Jacobian det (templ. to. ind.)'; + NJ(i).mat = M; + NJ(i).mat0 = M; + + create(NU(i)); NU(i).dat(:,:,:,:,:) = 0; + create(NY(i)); NY(i).dat(:,:,:,:,:) = reshape(affind(spm_diffeo('Exp',zeros([dm,3],'single'),[0 1]),NU(i).mat0),[dm,1,3]); + create(NJ(i)); NJ(i).dat(:,:,:) = 1; +end + +for i=1:n2, % Loop over subjects. Can replace FOR with PARFOR. + + % Add to sufficient statistics for generating initial template + tmp = zeros([dm n1+1],'single'); + for j=1:n1 + vn = NF(j,i).vn; + dat = NF(j,i).NI.dat(:,:,:,vn(1),vn(2)); + msk = isfinite(dat); + dat(~msk) = 0; + tmp(:,:,:,j) = dat; + if j==1, tmp(:,:,:,end) = msk; end + end + t = t + tmp; + spm_progress_bar('Set',i); +end +spm_progress_bar('Clear'); + +% Make symmetric (if necessary) +if issym, t = t + t(end:-1:1,:,:,:); end + +% Generate template from sufficient statistics +tmp = t(:,:,:,end); +msk = tmp<=0; +for j=1:n1 + tmp = tmp - t(:,:,:,j); +end +tmp(msk) = 0.01; % Most NaNs are likely to be background +t(:,:,:,end) = tmp; +clear tmp msk +M = NF(1,1).NI.mat; +t = max(t,0); +g = cell(n1+1,1); + +% Write template +NG = NF(1,1).NI; +NG.descrip = sprintf('Avg of %d', n2); +[tdir,nam,ext] = fileparts(job.images{1}{1}); +NG.dat.fname = fullfile(tdir,[tname, '_0.nii']); +NG.dat.dim = [dm n1+1]; +NG.dat.dtype = 'float32-le'; +NG.dat.scl_slope = 1; +NG.dat.scl_inter = 0; +NG.mat0 = NG.mat; +vx = sqrt(sum(NG.mat(1:3,1:3).^2)); + +if ~isempty(sparam) && smits~=0 + g0 = spm_shoot_blur(t,[vx, prod(vx)*[sparam(1:2) sched(1)*sparam(3)]],smits); % FIX THIS + for j=1:n1+1 + g{j} = max(g0(:,:,:,j),1e-4); + end + clear g0 +else + sumt = max(sum(t,4),0)+eps; + for j=1:n1+1 + g{j} = (t(:,:,:,j)+0.01)./(sumt+0.01*(n1+1)); + end + clear sumt +end + +if ~isempty(tname) + create(NG); + for j=1:n1+1 + NG.dat(:,:,:,j) = g{j}; + end +end +for j=1:n1+1, g{j} = spm_bsplinc(log(g{j}), bs_args); end + +ok = true(n2,1); + +% The actual work +for it=1:nits + + % More regularisation in the early iterations, as well as a + % a less accurate approximation in the integration. + prm = [vx, rparam*sched(it+1)*prod(vx)]; % FIX THIS + int_args = [eul_its(it), cyc_its]; + drawnow + + t = zeros([dm n1+1],'single'); + su = zeros([dm 3]); + + % Update velocities + spm_progress_bar('Init',n2,sprintf('Update velocities (%d)',it),'Subjects done'); + for i=1:n2 % Loop over subjects. Can replace FOR with PARFOR. + + if ok(i) + fprintf('%3d %5d | ',it,i); + + % Load image data for this subject + f = loadimage(NF(:,i)); + + % Load this subject's flow field and deformation + u = squeeze(single(NU(i).dat(:,:,:,:,:))); + y = affind(squeeze(single(NY(i).dat(:,:,:,:,:))),inv(NU(i).mat0)); + dt = squeeze(single(NJ(i).dat(:,:,:))); + drawnow + + % Gauss-Newton iteration to re-estimate deformations for this subject + u = spm_shoot_update(g,f,u,y,dt,prm,bs_args,scale); + %clear f y + + drawnow + NU(i).dat(:,:,:,:,:) = reshape(u,[dm 1 3]); + su = su + u; + %clear u + spm_progress_bar('Set',i); + end + + end + spm_progress_bar('Clear'); + + if issym + su(:,:,:,1) = (su(:,:,:,1) - su(end:-1:1,:,:,1) )/(sum(ok)*2); + su(:,:,:,2:3) = (su(:,:,:,2:3) + su(end:-1:1,:,:,2:3))/(sum(ok)*2); + else + su = su/sum(ok); + end + + % Generate FT of Green's function + K = spm_shoot_greens('kernel',dm,prm); + + % Update template sufficient statistics + spm_progress_bar('Init',n2,sprintf('Update deformations and template (%d)',it),'Subjects done'); + for i=1:n2 % Loop over subjects. Can replace FOR with PARFOR. + + if ok(i) + % Load velocity, mean adjust and re-save + u = squeeze(single(NU(i).dat(:,:,:,:,:))); + if isempty(sparam) || smits==0 + u = u - su; % Subtract mean (unless template is smoothed) + end + NU(i).dat(:,:,:,:,:) = reshape(u,[dm 1 3]); + + [y,dt] = defdet(u,prm,int_args, K); + + if any(~isfinite(dt(:)) | dt(:)>100 | dt(:)<1/100) + ok(i) = false; + fprintf('Problem with %s (dets: %g .. %g)\n', NU(i).dat.fname, min(dt(:)), max(dt(:))); + %clear dt + end + + NY(i).dat(:,:,:,:,:) = reshape(affind(y,NU(i).mat0),[dm 1 3]); + NJ(i).dat(:,:,:) = dt; + drawnow; + + % Load image data for this subject + f = loadimage(NF(:,i)); + + tmp = zeros([dm n1+1],'single'); + for j=1:n1+1 + try + tmp(:,:,:,j) = spm_diffeo('pullc',f{j},y).*dt; + catch + tmp(:,:,:,j) = spm_diffeo('samp',f{j},y).*dt; + end + end + %clear f y dt + + % Increment sufficient statistic for template + t = t + tmp; + %clear tmp + + fprintf('.'); + spm_progress_bar('Set',i); + end + + end + clear su + fprintf('\n'); + spm_progress_bar('Clear'); + + % Make left-right symmetric (if necessary) + if issym, t = t + t(end:-1:1,:,:,:); end + + % Re-generate template data from sufficient statistics + if ~isempty(sparam) && smits~=0 + g0 = reconv(g,bs_args); + g0 = spm_shoot_blur(t,[vx, prod(vx)*[sparam(1:2) sched(it+1)*sparam(3)]],smits,g0); % FIX THIS + g = cell(n1+1,1); + for j=1:n1+1 + g{j} = max(g0(:,:,:,j),1e-4); + end + clear g0 + else + sumt = max(sum(t,4),0)+eps; + for j=1:n1+1 + g{j} = (t(:,:,:,j)+0.01)./(sumt+0.01*(n1+1)); + end + clear sumt + end + clear t + + % Write template + if ~isempty(tname) + NG.dat.fname = fullfile(tdir,[tname '_' num2str(ceil(it/6)) '.nii']); + create(NG); + for j=1:n1+1 + NG.dat(:,:,:,j) = g{j}; + end + end + + % Compute template's B-spline coefficients + for j=1:n1+1, g{j} = spm_bsplinc(log(g{j}), bs_args); end + drawnow +end + +if any(~ok) + fprintf('Problems with:\n'); + for i=find(~ok)' + fprintf('\t%s\n', NU(i).dat.fname); + end +end + +% Finish off +out.template = cell(1+ceil(nits/6),1); +if ~isempty(tname) + for it=0:ceil(nits/6) + fname = fullfile(tdir,[tname '_' num2str(it) '.nii']); + out.template{it+1} = fname; + end +end +out.vel = cell(n2,1); +out.def = cell(n2,1); +out.jac = cell(n2,1); +for i=1:n2 + out.vel{i} = NU(i).dat.fname; + out.def{i} = NY(i).dat.fname; + out.jac{i} = NJ(i).dat.fname; +end +%======================================================================= + +%======================================================================= +function y1 = affind(y0,M) +% Affine transform of deformation +y1 = zeros(size(y0),'single'); +for d=1:3 + y1(:,:,:,d) = y0(:,:,:,1)*M(d,1) + y0(:,:,:,2)*M(d,2) + y0(:,:,:,3)*M(d,3) + M(d,4); +end +%======================================================================= + +%======================================================================= +function g0 = reconv(g,bs_args) +d = [size(g{1}), 1]; +[i1,i2,i3]=ndgrid(1:d(1),1:d(2),1:d(3)); +g0 = zeros([d,numel(g)],'single'); +for k=1:numel(g) + g0(:,:,:,k) = max(exp(spm_bsplins(g{k},i1,i2,i3,bs_args)),1e-4); +end +%======================================================================= + +%======================================================================= +function f = loadimage(NF) +n1 = size(NF,1); +f = cell(n1+1,1); +dm = [NF(1).NI.dat.dim 1 1 1]; +dm = dm(1:3); +f{n1+1} = ones(dm,'single'); +for j=1:n1 + vn = NF(j,1).vn; + f{j} = single(NF(j,1).NI.dat(:,:,:,vn(1),vn(2))); + msk = ~isfinite(f{j}); + f{j}(msk) = 0; + f{n1+1} = f{n1+1} - f{j}; + drawnow +end +f{n1+1}(msk) = 0.00001; +%======================================================================= + +%======================================================================= +function [y,dt] = defdet(u,prm,int_args, K) +% Generate deformation +[y,J] = spm_shoot3d(u,prm,int_args, K); +dt = spm_diffeo('det',J); +%======================================================================= + +%======================================================================= + +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_vol_laplace3.m",".m","963","27","%cat_vol_laplace3 Volumetric Laplace filter with Dirichlet boundary. +% Filter SEG within the intensity range of low and high until the changes +% are below TH. +% +% L = cat_vol_laplace3(SEG,low,high,TH) +% +% SEG .. 3D single input matrix +% low .. low boundary threshold +% high .. high boundary threshold +% TH .. threshold to control the number of iterations +% maximum change of an element after iteration +% +% Example: +% A = zeros(50,50,3,'single'); A(10:end-9,10:end-9,2)=0.5; +% A(20:end-19,20:end-19,2)=1; +% C = cat_vol_laplace3(A,0,1,0.001); ds('d2smns','',1,A,C,2); +% +% See also cat_vol_laplace3R, compile. +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_io_report.m",".m","36590","769","function cat_io_report(job,qa,subj,createerr) +% ______________________________________________________________________ +% CAT error report to write the main processing parameter, the error +% message, some image parameter and add a picture of the original +% image centered by its AC. +% +% This function is called in cat_run_newcatch. +% +% cat_io_report(job,qa,subj[,createerr]) +% +% job .. SPM job structure +% qa .. CAT quality assurance structure +% subj .. subject index +% +% +% createerr .. variable that create errors for debugging! +% different try-catch blocks to localize the error +% without using an error variable that is not allowed +% in old Matlab Versions. +% 1 .. early error in data preparation +% 2 .. preprocessing option error +% 3 .. preprocessing parameter error +% 4 .. general figure creation error +% 5 .. ? +% 6 .. printing error +% 7 .. ? +% 8 .. general figure creation error +% 9 .. error changing to SPM gray colorbar +% 10-11 .. display error of original image / histogram +% 20-21 .. display error of modified image / histogram +% 30-31 .. display error of segmented image / histogram +% 40-41 .. display error of cortical surfaces / colorbar +% +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Revision$ $Date$ + +%#ok<*AGROW> + + % close diagy + diary off; + + dbs = dbstatus; debug = 0; + for dbsi=1:numel(dbs), + if any(strcmp(dbs(dbsi).name,{'cat_io_report','cat_run_newcatch'})); + debug = 1; break; + end; + end + + if ~exist('createerr','var'); createerr = 0; end + createerrtxt = {}; + lasthours = 10; if debug, lasthours = inf; end % only display data + str = []; + hhist = zeros(3,1); + haxis = zeros(3,1); + + warning off; %#ok % there is a div by 0 warning in spm_orthviews in linux + global cat_err_res; + + + % preparation of specific varialbes that are include in cat_run_job and cat_main + % -------------------------------------------------------------------- + try + % preprocessing subdirectories + [mrifolder, reportfolder, surffolder] = cat_io_subfolders(job.data{subj},job); + + % setting template files + [pp,ff] = spm_fileparts(job.data{subj}); + + Pn = fullfile(pp,mrifolder,['n' ff '.nii']); + Pm = fullfile(pp,mrifolder,['m' ff '.nii']); + Pp0 = fullfile(pp,mrifolder,['p0' ff '.nii']); + + VT0 = spm_vol(job.data{subj}); % original + if exist(Pn,'file'), VT1 = spm_vol(Pn); end %else VT0.mat = nan(4,4); end % intern + [pth,nam] = spm_fileparts(VT0.fname); + + tc = [cat(1,job.tissue(:).native) cat(1,job.tissue(:).warped)]; + + % do dartel + do_dartel = 1; % always use dartel/shooting normalization + if do_dartel + need_dartel = any(job.output.warps) || ... + job.output.bias.warped || job.output.bias.dartel || ... + job.output.label.warped || job.output.label.dartel || ... + any(any(tc(:,[4 5 6]))) || job.output.jacobian.warped || ... + job.output.surface || job.output.ROI || ... + any([job.output.te.warped,job.output.pc.warped,job.output.atlas.warped]); + if ~need_dartel + do_dartel = 0; + end + end + + if createerr==1, error(sprintf('error:cat_io_report:createerr_%d',createerr),'Test'); end + + % Find all templates and distinguish between Dartel and Shooting + % written to match for Template_1 or Template_0 as first template. + template = strrep(job.extopts.darteltpm{1},',1',''); + [templatep,templatef,templatee] = spm_fileparts(template); + numpos = min([strfind(templatef,'Template_1'),strfind(templatef,'Template_0')]) + 8; + if isempty(numpos) + error('CAT:cat_main:TemplateNameError', ... + ['Could not find the string ""Template_1"" (Dartel) or ""Template_0"" (Shooting) \n'... + 'that indicates the first file of the Dartel/Shooting template. \n' ... + 'The given filename is ""%s"" \n' ... + ],templatef); + end + + job.extopts.templates = cat_vol_findfiles(templatep,[templatef(1:numpos) '*' templatef(numpos+2:end) templatee],struct('depth',1)); + %% + % 201812 -error in chimps job.extopts.templates(cellfun('length',job.extopts.templates)~=numel(template)) = []; % furhter condition maybe necessary + [template1p,template1f] = spm_fileparts(job.extopts.templates{1}); %#ok + if do_dartel + if (numel(job.extopts.templates)==6 || numel(job.extopts.templates)==7) + % Dartel template + if ~isempty(strfind(template1f,'Template_0')), job.extopts.templates(1) = []; end + do_dartel=1; + elseif numel(job.extopts.templates)==5 + % Shooting template + do_dartel=2; + else + templates = ''; + for ti=1:numel(job.extopts.templates) + templates = sprintf('%s %s\n',templates,job.extopts.templates{ti}); + end + error('CAT:cat_main:TemplateFileError', ... + ['Could not find the expected number of template. Dartel requires 6 Files (Template 1 to 6),\n' ... + 'whereas Shooting needs 5 files (Template 0 to 4). %d templates found: \n%s'],... + numel(job.extopts.templates),templates); + end + end + catch + createerrtxt = [createerrtxt; {'Error:cat_io_report:CATpre','Error in cat_io_report data preparation.'}]; + cat_io_cprintf('err','%30s: %s\n',createerrtxt{end,1},createerrtxt{end,2}); + end + + + + + + +%% display and print result if possible +% --------------------------------------------------------------------- + + + % CAT GUI parameter: + % -------------------------------------------------------------------- + + if ~isfield(cat_err_res,'res') || ~isfield(cat_err_res.res,'do_dartel') + if exist('do_dartel','var'), cat_err_res.res.do_dartel = do_dartel; else cat_err_res.res.do_dartel = 1; end + end + if ~isfield(cat_err_res.res,'stime'), cat_err_res.res.stime = clock; end + if ~isfield(cat_err_res.res,'tpm'), cat_err_res.res.tpm(1).fname = job.opts.tpm{1}; end + if ~isfield(cat_err_res.res,'Affine'), cat_err_res.res.Affine = eye(4); end + if ~isfield(cat_err_res.res,'lkp'), cat_err_res.res.lkp = 1:6; end + if ~isfield(cat_err_res.res,'mg'), cat_err_res.res.mg = nan(6,1); end + if ~isfield(cat_err_res.res,'mn'), cat_err_res.res.mn = nan(1,6); end + if ~isfield(cat_err_res.res,'Affine'), cat_err_res.res.Affine = eye(4); end + if ~isfield(cat_err_res,'obj') || ~isfield(cat_err_res.obj,'Affine'), cat_err_res.obj.Affine = eye(4); end + + [ver_cat, rev_cat] = cat_version; + ver_cat = ver_cat(4:end); % remove leading CAT + [namspmv,rev_spm] = spm('Ver'); + QAS.software.version_spm = rev_spm; + A = ver; + for i=1:length(A) + if strcmp(A(i).Name,'MATLAB') + QAS.software.version_matlab = A(i).Version; + end + end + clear A + + if ispc, OSname = 'WIN'; + elseif ismac, OSname = 'MAC'; + else OSname = 'LINUX'; + end + + qa.software.system = OSname; + qa.software.version_cat = ver_cat; + if ~isfield(qa.software,'version_segment') + qa.software.version_segment = rev_cat; + end + qa.software.revision_cat = rev_cat; + try + qa.qualitymeasures.res_vx_vol = sqrt(sum(VT0.mat(1:3,1:3).^2)); + catch + qa.qualitymeasures.res_vx_vol = nan(1,3); + end + try + qa.qualitymeasures.res_vx_voli = sqrt(sum(VT1.mat(1:3,1:3).^2)); + catch + qa.qualitymeasures.res_vx_voli = nan(1,3); + end + qa.qualityratings.res_RMS = mean(qa.qualitymeasures.res_vx_vol.^2).^0.5; + qa.qualityratings.res_ECR = nan; + qa.qualityratings.NCR = nan; + qa.qualityratings.FEC = nan; + qa.qualityratings.ICR = nan; + qa.qualityratings.IQR = nan; + qa.qualityratings.SIQR = nan; + qa.subjectmeasures.EC_abs = nan; + qa.subjectmeasures.vol_abs_CGW = nan(1,4); + qa.subjectmeasures.vol_rel_CGW = nan(1,4); + qa.subjectmeasures.vol_TIV = nan; + str = cat_main_reportstr(job,cat_err_res.res,qa); + str = str{1}; + + + %% image parameter + % -------------------------------------------------------------------- + try + %% + Ysrc = spm_read_vols(VT0); + imat = spm_imatrix(VT0.mat); + deg = char(176); + str2 = []; + str2 = [str2 struct('name','\bfImagedata','value','')]; + str2 = [str2 struct('name',' Datatype','value',spm_type(VT0.dt(1)))]; + str2 = [str2 struct('name',' AC (mm)','value',sprintf('% 10.1f % 10.1f % 10.1f ',imat(1:3)))]; + str2 = [str2 struct('name',' Rotation (rad)','value',sprintf('% 10.2f%s % 10.2f%s % 10.2f%s ',... + imat(4) ./ (pi/180), deg, imat(5) ./ (pi/180), deg, imat(6) ./ (pi/180), deg ))]; + str2 = [str2 struct('name',' Voxel size (mm)','value',sprintf('% 10.2f % 10.2f % 10.2f ',imat(7:9)))]; + + if createerr==3, error(sprintf('error:cat_io_report:createerr_%d',createerr),'Test'); end + + %% + if isfield(cat_err_res,'res') + %str2 = [str2 struct('name',' HDl | HDh | BG )','value',sprintf('% 10.2f % 10.2f % 10.2f', ... + % mean(cat_err_res.res.mn(cat_err_res.res.lkp==4 & cat_err_res.res.mg'>0.3)), ... + % mean(cat_err_res.res.mn(cat_err_res.res.lkp==5 & cat_err_res.res.mg'>0.3)), ... + % mean(cat_err_res.res.mn(cat_err_res.res.lkp==6 & cat_err_res.res.mg'>0.4))) )]; + iaffine = spm_imatrix(cat_err_res.res.Affine); + str2 = [str2 struct('name','\bfAffine','value','')]; + str2 = [str2 struct('name',' Translation (mm)','value',sprintf('% 10.1f % 10.1f % 10.1f ',iaffine(1:3)))]; + str2 = [str2 struct('name',' Rotation','value',sprintf('% 10.2f%s % 10.2f%s % 10.2f%s ',... + iaffine(4) ./ (pi/180), deg, iaffine(5) ./ (pi/180), deg, iaffine(6) ./ (pi/180), deg))]; + str2 = [str2 struct('name',' Scaling','value',sprintf('% 10.2f % 10.2f % 10.2f ',iaffine(7:9)))]; + str2 = [str2 struct('name',' Shear','value',sprintf('% 10.2f % 10.2f % 10.2f' ,iaffine(10:12)))]; + if all(~isnan(cat_err_res.res.mn)) + str2 = [str2 struct('name','\bfSPM tissues peaks','value','')]; + str2 = [str2 struct('name',' CSF | GM | WM ','value',sprintf('% 10.2f % 10.2f % 10.2f', ... + cat_stat_nanmean(cat_err_res.res.mn(cat_err_res.res.lkp==3 & cat_err_res.res.mg'>0.3)), ... + cat_stat_nanmean(cat_err_res.res.mn(cat_err_res.res.lkp==1 & cat_err_res.res.mg'>0.3)), ... + cat_stat_nanmean(cat_err_res.res.mn(cat_err_res.res.lkp==2 & cat_err_res.res.mg'>0.3))) )]; + str2 = [str2 struct('name',' HDl | HDh | BG ','value',sprintf('% 10.2f % 10.2f % 10.2f', ... + cat_stat_nanmean(cat_err_res.res.mn(cat_err_res.res.lkp==4 & cat_err_res.res.mg'>0.3)), ... + cat_stat_nanmean(cat_err_res.res.mn(cat_err_res.res.lkp==5 & cat_err_res.res.mg'>0.3)), ... + cat_stat_nanmean(cat_err_res.res.mn(cat_err_res.res.lkp==6 & cat_err_res.res.mg'>0.4))) )]; + end + elseif isfield(cat_err_res,'obj') + iaffine = spm_imatrix(cat_err_res.obj.Affine); + str2 = [str2 struct('name','\bfAffine','value','')]; + str2 = [str2 struct('name',' Translation','value',sprintf('% 10.1f % 10.1f % 10.1f ',iaffine(1:3)))]; + str2 = [str2 struct('name',' Rotation','value',sprintf('% 10.2f%s % 10.2f%s % 10.2f%s ', ... + iaffine(4) ./ (pi/180), deg, iaffine(5) ./ (pi/180), deg, iaffine(6) ./ (pi/180), deg))]; + str2 = [str2 struct('name',' Scaling','value',sprintf('% 10.2f % 10.2f % 10.2f ',iaffine(7:9)))]; + str2 = [str2 struct('name',' Shear','value',sprintf('% 10.2f % 10.2f % 10.2f ',iaffine(10:12)))]; + str2 = [str2 struct('name','\bfIntensities','value','')]; + str2 = [str2 struct('name',' min | max','value',sprintf('% 10.2f % 10.2f ',min(Ysrc(:)),max(Ysrc(:))))]; + str2 = [str2 struct('name',' mean | std','value',sprintf('% 10.2f % 10.2f ',cat_stat_nanmean(Ysrc(:)),cat_stat_nanstd(Ysrc(:))))]; + else + str2 = [str2 struct('name','\bfIntensities','value','')]; + str2 = [str2 struct('name',' min | max','value',sprintf('% 10.2f % 10.2f ',min(Ysrc(:)),max(Ysrc(:))))]; + str2 = [str2 struct('name',' mean | std','value',sprintf('% 10.2f % 10.2f ',cat_stat_nanmean(Ysrc(:)),cat_stat_nanstd(Ysrc(:))))]; + str2 = [str2 struct('name',' isinf | isnan','value',sprintf('% 10.0f % 10.0f ',sum(isinf(Ysrc(:))),sum(isnan(Ysrc(:)))))]; + end + + + % adding one space for correct printing of bold fonts + for si=1:numel(str) + str(si).name = [str(si).name ' ']; str(si).value = [str(si).value ' ']; + end + for si=1:numel(str2) + str2(si).name = [str2(si).name ' ']; str2(si).value = [str2(si).value ' ']; + end + catch + createerrtxt = [createerrtxt; {'Error:cat_io_report:CATgui','Error in cat_io_report GUI parameter report creation > incomple image parameters.'}]; + cat_io_cprintf('err','%30s: %s\n',createerrtxt{end,1},createerrtxt{end,2}); + end + + + + + +%% Figure +% --------------------------------------------------------------------- + try + VT0 = spm_vol(job.data{subj}); % original + + nprog = ( isfield(job,'printPID') && job.printPID ) || ... PID field + ( isempty(findobj('type','Figure','Tag','CAT') ) && ... no menus + isempty(findobj('type','Figure','Tag','Menu') ) ); + fg = spm_figure('FindWin','Graphics'); + set(0,'CurrentFigure',fg) + if isempty(fg) + if nprog + fg = spm_figure('Create','Graphics','visible','off'); + else + fg = spm_figure('Create','Graphics','visible','on'); + end; + else + if nprog, set(fg,'visible','off'); end + end + + set(fg,'windowstyle','normal'); + spm_figure('Clear','Graphics'); + switch computer + case {'PCWIN','PCWIN64'}, fontsize = 8; + case {'GLNXA','GLNXA64'}, fontsize = 8; + case {'MACI','MACI64'}, fontsize = 9; + otherwise, fontsize = 9; + end + ax=axes('Position',[0.01 0.75 0.99 0.24],'Visible','off','Parent',fg); + + text(0,0.99, ['Segmentation: ' spm_str_manip(VT0.fname,'k60d') ' '],... + 'FontSize',fontsize+1,'FontWeight','Bold','Interpreter','none','Parent',ax); + + + % check colormap name + cm = job.extopts.colormap; + + % SPM_orthviews seems to allow only 60 values + % It further requires a modified colormaps with lower values that the + % colorscale and small adaptation for the values. + hlevel = 240; + volcolors = 60; % spm standard + surfcolors = 128; + switch lower(cm) + case {'bcgwhw','bcgwhn'} % cat colormaps with larger range + cmap = [ + cat_io_colormaps([cm 'ov'],volcolors); + flipud(cat_io_colormaps([cm 'ov'],volcolors)) + jet(surfcolors)]; + mlt = 2; + case {'jet','hsv','hot','cool','spring','summer','autumn','winter','gray','bone','copper','pink'} + cmap = [ + eval(sprintf('%s(%d)',cm,volcolors)); + flipud(eval(sprintf('%s(%d)',cm,volcolors))); + jet(surfcolors)]; + mlt = 1; + otherwise + cmap = [ + eval(sprintf('%s(%d)',cm,volcolors)); + flipud(eval(sprintf('%s(%d)',cm,volcolors))); + jet(surfcolors)]; + mlt = 1; + end + colormap(cmap); + spm_orthviews('Redraw'); + + htext = zeros(5,2,2); + for i=1:size(str,2) % main parameter + htext(1,i,1) = text(0.01,0.98-(0.045*i), str(i).name ,'FontSize',fontsize, 'Interpreter','tex','Parent',ax); + htext(1,i,2) = text(0.51,0.98-(0.045*i), str(i).value ,'FontSize',fontsize, 'Interpreter','tex','Parent',ax); + end + htext(2,i,1) = text(0.01,0.52-(0.045*1), '\bfCAT preprocessing error: ','FontSize',fontsize, 'Interpreter','tex','Parent',ax); + for i=1:size(qa.error,1) % error message + errtxt = strrep([qa.error{i} ' '],'_','\_'); + htext(2,i,1) = text(0.01,0.52-(0.045*(i+2)), errtxt ,'FontSize',fontsize, 'Interpreter','tex','Parent',ax,'Color',[0.8 0 0]); + end + for i=1:size(str2,2) % image-parameter + htext(2,i,1) = text(0.51,0.52-(0.045*i), str2(i).name ,'FontSize',fontsize, 'Interpreter','tex','Parent',ax); + htext(2,i,2) = text(0.75,0.52-(0.045*i), str2(i).value ,'FontSize',fontsize, 'Interpreter','tex','Parent',ax); + end + pos = [0.01 0.34 0.48 0.32; 0.51 0.34 0.48 0.32; ... + 0.01 0.01 0.48 0.32; 0.51 0.01 0.48 0.32]; + spm_orthviews('Reset'); + + if createerr==4, error(sprintf('error:cat_io_report:createerr_%d',createerr),'Test'); end + + + + %% Yo - original image in original space + % ----------------------------------------------------------------- + % using of SPM peak values didn't work in some cases (5-10%), + % so we have to load the image and estimate the WM intensity + try + %% + % there appear too many annoying warning under windows for some reasons which I don't know + warning off; hho = spm_orthviews('Image',VT0,pos(1,:)); warning on + spm_orthviews('Caption',hho,{'*.nii (Original)'},'FontSize',fontsize,'FontWeight','Bold'); + Ysrcs = single(Ysrc+0); spm_smooth(Ysrcs,Ysrcs,repmat(0.2,1,3)); + haxis(1) = axes('Position',[pos(1,1:2) + [pos(1,3)*0.58 0],pos(1,3)*0.38,pos(1,4)*0.35] ); + [y,x] = hist(Ysrcs(:),hlevel); y = y ./ max(y)*100; %clear Ysrcs; + if exist(Pp0,'file'), Pp0data = dir(Pp0); Pp0data = etime(clock,datevec(Pp0data.datenum))/3600 < lasthours; else, Pp0data = 0; end +%% + if createerr==10, error(sprintf('error:cat_io_report:createerr_%d',createerr),'Test'); end + ch = cumsum(y)/sum(y); + if Pp0data, Vp0 = spm_vol(Pp0); end + if Pp0data && all(Vp0.dim == size(Ysrcs)) + Yp0 = spm_read_vols(Vp0); + mth = find(x>=cat_stat_nanmean(Ysrcs(Yp0(:)>2.7 & Yp0(:)<3.3)), 1 ,'first'); + else + mth = find(ch>0.95,1,'first'); + end + %spm_orthviews('window',hho,[x(find(ch>0.02,1,'first')) x(mth) + (mlt-1)*diff(x([find(ch>0.02,1,'first'),mth]))]); hold on; + spm_orthviews('Zoom'); + spm_orthviews('Reposition',[0 0 0]); + spm_orthviews('Redraw'); + % colorbar + try + %% + bd = [find(ch>0.01,1,'first'),mth]; + ylims{1} = [min(y(round(numel(y)*0.1):end)),max(y(round(numel(y)*0.1):end)) * 4/3]; + xlims{1} = x(bd) + [0,(4/3-1)*diff(x([find(ch>0.02,1,'first'),mth]))]; M = x>=xlims{1}(1) & x<=xlims{1}(2); + hdata{1} = [x(M) fliplr(x(M)); max(eps,min(ylims{1}(2),y(M))) zeros(1,sum(M)); [x(M) fliplr(x(M))]]; + hhist(1) = fill(hdata{1}(1,:),hdata{1}(2,:),hdata{1}(3,:),'EdgeColor',[0.0 0.0 1.0],'LineWidth',1); + if createerr==11, error(sprintf('error:cat_io_report:createerr_%d',createerr),'Test'); end + %caxis(xlims{1} .* [1,1.5*(2*volcolors+surfcolors)/volcolors]) + caxis(xlims{1} + [0,((2*2*volcolors+surfcolors)/volcolors)*diff(x([find(ch>0.02,1,'first'),mth]))]); %; .* [1,1.5*(2*volcolors+surfcolors)/volcolors]) + ylim(ylims{1}); xlim(xlims{1}); box on; grid on; + catch + createerrtxt = [createerrtxt; {'Error:cat_io_report:dispYoHist','Error in displaying the color histogram of the original image.'}]; + cat_io_cprintf('err','%30s: %s\n',createerrtxt{end,1},createerrtxt{end,2}); + if hhist(1)>0, delete(hhist(1)); hhist(1)=0; end + xlim([0,1]),ylim([0,1]); grid off; + text(pos(1,1) + pos(1,3)*0.35,pos(1,2) + pos(1,4)*0.55,'HIST ERROR','FontSize',20,'color',[0.8 0 0]); + end + catch + createerrtxt = [createerrtxt; {'Error:cat_io_report:dispYo','Error in displaying the original image.'}]; + cat_io_cprintf('err','%30s: %s\n',createerrtxt{end,1},createerrtxt{end,2}); + end + + + + + %% Ym - normalized image in original space + mtxt = 'm*.nii (part. processed.)'; + if exist(Pn,'file'), Pndata = dir(Pn); Pndata = etime(clock,datevec(Pndata.datenum))/3600 < lasthours; else Pndata = 0; end + if exist(Pm,'file'), Pmdata = dir(Pm); Pmdata = etime(clock,datevec(Pmdata.datenum))/3600 < lasthours; else Pmdata = 0; end + if ~Pmdata && Pndata, Pm = Pn; Pmdata = Pndata; mtxt = 'n*.nii (part. processed.)'; end + if Pmdata + try + hhm = spm_orthviews('Image',spm_vol(Pm),pos(2,:)); + spm_orthviews('Caption',hhm,{mtxt},'FontSize',fontsize,'FontWeight','Bold'); + haxis(2) = axes('Position',[pos(2,1:2) + [pos(2,3)*0.58 0],pos(1,3)*0.38,pos(1,4)*0.35] ); + Yms = spm_read_vols(spm_vol(Pm)); spm_smooth(Yms,Yms,repmat(0.2,1,3)); + [y,x] = hist(Yms(:),hlevel); y = y ./ max(y)*100; + ch = cumsum(y)/sum(y); + if createerr==20, error(sprintf('error:cat_io_report:createerr_%d',createerr),'Test'); end + if Pp0data, Vp0 = spm_vol(Pp0); end + if Pp0data && all(Vp0.dim == size(Yms)) + Yp0 = spm_read_vols(spm_vol(Pp0)); + mth = find(x>=cat_stat_nanmean(Yms(Yp0(:)>2.9 & Yp0(:)<3.1)), 1 ,'first'); + else + mth = find(ch>0.95,1,'first'); + end + spm_orthviews('window',hhm,[x(find(ch>0.02,1,'first')) x(mth) + (mlt-1)*diff(x([find(ch>0.02,1,'first'),mth]))]); hold on; + spm_orthviews('Zoom'); % redraw Yo + clear Yms; + try + % colorbar + if createerr==21, error(sprintf('error:cat_io_report:createerr_%d',createerr),'Test'); end + bd = [find(ch>0.01,1,'first'),mth]; + ylims{2} = [min(y(round(numel(y)*0.1):end)),max(y(round(numel(y)*0.1):end)) * 4/3]; + xlims{2} = x(bd) + [0,(4/3-1)*diff(x([find(ch>0.02,1,'first'),mth]))]; M = x>=xlims{2}(1) & x<=xlims{2}(2); + hdata{2} = [x(M) fliplr(x(M)); max(eps,min(ylims{2}(2),y(M))) zeros(1,sum(M)); [x(M) fliplr(x(M))]]; + hhist(2) = fill(hdata{2}(1,:),hdata{2}(2,:),hdata{2}(3,:),'EdgeColor',[0.0 0.0 1.0],'LineWidth',1); + %caxis(xlims{2} .* [1,1.5*(2*volcolors+surfcolors)/volcolors]) + caxis(xlims{2} + [0,((2*2*volcolors+surfcolors)/volcolors)*diff(x([find(ch>0.02,1,'first'),mth]))]); %; .* [1,1.5*(2*volcolors+surfcolors)/volcolors]) + ylim(ylims{2}); xlim(xlims{2}); box on; grid on; + if round(x(mth))==1 + xlim([0 4/3]); + set(gca,'XTick',0:1/3:4/3,'XTickLabel',{'BG','CSF','GM','WM','BV/HD'}); + end + catch + createerrtxt = [createerrtxt; {'Error:cat_io_report:dispYmHist','Error in displaying the color histogram of the processed image.'}]; + cat_io_cprintf('err','%30s: %s\n',createerrtxt{end,1},createerrtxt{end,2}); + if hhist(2)>0, delete(hhist(2)); hhist(2)=0; end + xlim([0,1]),ylim([0,1]); grid off; + if haxis(2)>0, + else text(pos(2,1) + pos(2,3)*0.35,pos(2,2) + pos(2,4)*0.55,'HIST ERROR','FontSize',20,'color',[0.8 0 0]); + end + end + catch + createerrtxt = [createerrtxt; {'Error:cat_io_report:dispYo','Error in displaying the processed image.'}]; + cat_io_cprintf('err','%30s: %s\n',createerrtxt{end,1},createerrtxt{end,2}); + end + end + + + + %% Yp0 - segmentation in original space + if exist(Pp0,'file'), Pp0data = dir(Pp0); Pp0data = etime(datevec(Pp0data.datenum),cat_err_res.stime)/3600 > 0; else Pp0data = 0; end + if Pp0data || (isfield(cat_err_res,'init') && isfield(cat_err_res.init,'Yp0')) + try + %% + if isfield(cat_err_res.init,'Yp0') && exist(Pn,'file') + Vp0 = spm_vol(Pn); + Yp0 = single(cat_vol_resize(cat_err_res.init.Yp0,'dereduceBrain',cat_err_res.init.BB)); + if isa(cat_err_res.init.Yp0,'uint8') + if max( Yp0(:)) == round(255/5*3) + Yp0 = Yp0 / 255 * 5; + elseif max( Yp0(:)) > 100 + Yp0 = Yp0 / 255 * 5; + end + end + else + % here we load the Yp0 that is only code with WM == 3 + Vp0 = spm_vol(Pp0); + Yp0 = spm_read_vols(spm_vol(Pp0)); + end + + + % create V structure that include the image + Vp0 = rmfield(Vp0,'private'); + Vp0.dt = [2 0]; + Vp0.dat = cat_vol_ctype(Yp0 / 5 * 255); + Vp0.dim = size(Yp0); + Vp0.pinfo = repmat([5/255;0],1,size(Yp0,3)); + hhp0 = spm_orthviews('Image',Vp0,pos(3,:)); + + if createerr==30, error(sprintf('error:cat_io_report:createerr_%d',createerr),'Test'); end + spm_orthviews('Caption',hhp0,'p0*.nii (Segmentation)','FontSize',fontsize,'FontWeight','Bold'); + spm_orthviews('window',hhp0,[0,6]); + spm_orthviews('Zoom'); + + + % smooth version for histogram + Yp0s = Yp0; + spm_smooth(Yp0s,Yp0s,repmat(0.5,1,3)); + [y,x] = hist(Yp0s(:),0:1/30:6); clear Yms; y = y ./ max(y)*100; clear Yp0s; + y = min(y,max(y(2:end))); % ignore background + + try + %% colorbar + if createerr==31, error(sprintf('error:cat_io_report:createerr_%d',createerr),'Test'); end + haxis(3) = axes('Position',[pos(3,1:2) + [pos(3,3)*0.58 0.01],pos(1,3)*0.38,pos(1,4)*0.35] ); + xlims{3} = [0 4]; + ylims{3} = [min(y) max(y)] .* [0 4/3]; M = x <= xlims{3}(2); + hdata{3} = [x(M) fliplr(x(M)); max(eps,min(ylims{3}(2),y(M))) zeros(1,sum(M)); [x(M) fliplr(x(M))]]; + hhist(3) = fill( hdata{3}(1,:) , hdata{3}(2,:) , hdata{3}(3,:), 'EdgeColor',[0.0 0.0 1.0], 'LineWidth',1); + caxis(xlims{3} .* [1,1.5*(2*volcolors+surfcolors)/volcolors]) + ylim(ylims{3}); xlim(xlims{3}); box on; grid on; + set(gca,'XTick',0:1:4,'XTickLabel',{'BG','CSF','GM','WM','(WMH)'}); + catch + createerrtxt = [createerrtxt; {'Error:cat_io_report:dispYp0Hist','Error in displaying the color histogram of the segmented image.'}]; + cat_io_cprintf('err','%30s: %s\n',createerrtxt{end,1},createerrtxt{end,2}); + if hhist(3)>0, delete(hhist(3)); hhist(3)=0; end + xlim([0,1]),ylim([0,1]); grid off; + if haxis(3)>0, text(0.5,0.5,'HIST ERROR','FontSize',20,'color',[0.8 0 0]); + else text(pos(3,1) + pos(3,3)*0.35,pos(3,2) + pos(3,4)*0.55,'HIST ERROR','FontSize',20,'color',[0.8 0 0]); + end + end + catch + createerrtxt = [createerrtxt; {'Error:cat_io_report:dispYp0','Error in displaying the segmented image.'}]; + cat_io_cprintf('err','%30s: %s\n',createerrtxt{end,1},createerrtxt{end,2}); + end + end + if createerr==8, error(sprintf('error:cat_io_report:createerr_%d',createerr),'Test'); end + try, spm_orthviews('redraw'); end + + + %% surface or histogram + if isfield(cat_err_res,'obj') && isfield(cat_err_res.obj,'Affine') + Affine = cat_err_res.obj.Affine; + elseif isfield(cat_err_res,'res') && isfield(cat_err_res.res,'Affine') + Affine = cat_err_res.res.Affine; + else + Affine = eye(4); + end + imat = spm_imatrix(Affine); Rigid = spm_matrix([imat(1:6) 1 1 1 0 0 0]); clear imat; + + Pthick = fullfile(pp,surffolder,sprintf('lh.thickness.%s',ff)); + if exist(Pthick,'file'), Pthickdata = dir(Pthick); Pthickdata = etime(datevec(Pthickdata.datenum),cat_err_res.stime)/3600 > 0; else Pthickdata = 0; end + if Pthickdata + hCS = subplot('Position',[0.5 0.05 0.55 0.25],'visible','off'); + try + hSD = cat_surf_display(struct('data',{Pthick},'readsurf',0,'expert',2,... + 'multisurf',1,'view','s','parent',hCS,'verb',0,'caxis',[0 6],'imgprint',struct('do',0))); + + for ppi = 1:numel(hSD{1}.patch) + V = (Rigid * ([hSD{1}.patch(ppi).Vertices, ones(size(hSD{1}.patch(ppi).Vertices,1),1)])' )'; + V(:,4) = []; hSD{1}.patch(ppi).Vertices = V; + end + + if createerr==40, error(sprintf('error:cat_io_report:createerr_%d',createerr),'Test'); end + colormap(cmap); set(hSD{1}.colourbar,'visible','off'); + cc{3} = axes('Position',[0.62 0.02 0.3 0.01],'Parent',fg); image((volcolors*2+1:1:volcolors*2+surfcolors)); + set(cc{3},'XTick',1:(surfcolors-1)/6:surfcolors,'XTickLabel',{'0','1','2','3','4','5',' 6 mm'},... + 'YTickLabel','','YTick',[],'TickLength',[0 0],'FontSize',fontsize,'FontWeight','Bold'); + catch + createerrtxt = [createerrtxt; {'Error:cat_io_report:dispSurf','Error in displaying the cortical surface(s).'}]; + cat_io_cprintf('err','%30s: %s\n',createerrtxt{end,1},createerrtxt{end,2}); + end + end + catch + createerrtxt = [createerrtxt; {'Error:cat_io_report:Fig','Error in CAT report figure creation!'}]; + cat_io_cprintf('err','%30s: %s\n',createerrtxt{end,1},createerrtxt{end,2}); + end + spm_orthviews('Zoom'); + %spm_orthviews('BB'); % update BB to avoid problems with different resolution + + + %% TPM overlay with brain/head and head/background surfaces + global st; + warning('off','MATLAB:subscripting:noSubscriptsSpecified') + showTPMsurf = 1; % ... also in default mode + if job.extopts.expertgui>0 - showTPMsurf + try + Phull = {cat_surf_create_TPM_hull_surface(job.opts.tpm)}; + for id=1 + spm_orthviews('AddContext',id); % need the context menu for mesh handling + + try + spm_ov_mesh('display',id,Phull); + catch + fprintf('Please update to a newer version of spm12 for using this contour overlay\n'); + try + spm_update + catch + fprintf('Update to the newest SPM12 version failed. Please update manually.\n'); + end + end + + % apply affine scaling for gifti objects + for ix=1:numel(Phull) + % load mesh + try spm_ov_mesh('display',id,Phull(ix)); end + + %% apply affine scaling for gifti objects (inv(cat_err_res.res.Affine) + V = (inv(Affine) * ([st.vols{id}.mesh.meshes(ix).vertices,... + ones(size(st.vols{id}.mesh.meshes(ix).vertices,1),1)])' )'; + V(:,4) = []; + M0 = st.vols{id}.mesh.meshes(1:ix-1); + M1 = st.vols{id}.mesh.meshes(ix); + M1 = subsasgn(M1,struct('subs','vertices','type','.'),single(V)); + st.vols{id}.mesh.meshes = [M0,M1]; + end + + %% change line style + hM = findobj(st.vols{id}.ax{1}.cm,'Label','Mesh'); + UD = get(hM,'UserData'); + UD.width = 0.75; + UD.style = repmat({'b--'},1,numel(Phull)); + set(hM,'UserData',UD); + try spm_ov_mesh('redraw',id); end + spm_orthviews('redraw',id); + + %% TPM legend + %ccl{1} = axes('Position',[pos(1,1:2) 0 0] + [0.33 -0.005 0.02 0.02],'Parent',fg); + %cclp = plot(ccl{1},([0 0.4;0.6 1])',[0 0; 0 0],'b-'); text(ccl{1},1.2,0,'TPM fit'); + %set( cclp,'LineWidth',0.75); axis(ccl{1},'off') + end + end + end + + + %% report error + try + if exist('ax','var') && size(createerrtxt,1)>0 + %% + text(0.01,0.52 - (0.045*(size(qa.error,1)+2)), '\bfcat\_io\_report error: ' ,'FontSize',fontsize, 'Interpreter','tex','Parent',ax); + for i=1:size(createerrtxt,1) + createerrtxt2{i,2} = strrep([createerrtxt{i,2} ' '],'_','\_'); + text(0.01,0.52 - (0.045*(size(qa.error,1)+2)) - (0.045*i), createerrtxt2{i,2} ,'FontSize',fontsize, 'Interpreter','tex','Parent',ax,'Color',[0.8 0 0]); + end + end + catch + createerrtxt = [createerrtxt; {'Error:cat_io_report:dispErr','Error in displaying the errors of cat_io_report'}]; + cat_io_cprintf('err','%30s: %s\n',createerrtxt{end,1},createerrtxt{end,2}); + end + + + + %% print group report file + try + fg = spm_figure('FindWin','Graphics'); + set(0,'CurrentFigure',fg) + fprintf(1,'\n'); + + % print subject report file as standard PDF/PNG/... file + job.imgprint.type = 'pdf'; + job.imgprint.dpi = 100; + job.imgprint.fdpi = @(x) ['-r' num2str(x)]; + job.imgprint.ftype = @(x) ['-d' num2str(x)]; + job.imgprint.fname = fullfile(pth,reportfolder,['catreport_' nam '.' job.imgprint.type]); + job.imgprint.fnamej = fullfile(pth,reportfolder,['catreportj_' nam '.jpg']); + + fgold.PaperPositionMode = get(fg,'PaperPositionMode'); + fgold.PaperPosition = get(fg,'PaperPosition'); + fgold.resize = get(fg,'resize'); + + % it is necessary to change some figure properties especialy the fontsizes + if createerr==6, error(sprintf('error:cat_io_report:createerr_%d',createerr),'Test'); end + set(fg,'PaperPositionMode','auto','resize','on','PaperPosition',[0 0 1 1]); + for hti = 1:numel(htext), if htext(hti)>0, set(htext(hti),'Fontsize',fontsize*0.8); end; end + + % pdf is not working yet with Octave + if strcmpi(spm_check_version,'octave') + print(fg, job.imgprint.ftype('jpeg'), job.imgprint.fnamej); + else + print(fg, job.imgprint.ftype(job.imgprint.type), job.imgprint.fdpi(job.imgprint.dpi), job.imgprint.fname); + print(fg, job.imgprint.ftype('jpeg') , job.imgprint.fdpi(job.imgprint.dpi), job.imgprint.fnamej); + for hti = 1:numel(htext), if htext(hti)>0, set(htext(hti),'Fontsize',fontsize); end; end + set(fg,'PaperPositionMode',fgold.PaperPositionMode,'resize',fgold.resize,'PaperPosition',fgold.PaperPosition); + end + fprintf('Print ''Graphics'' figure to: \n %s\n',job.imgprint.fname); + + catch + createerrtxt = [createerrtxt; {'Error:cat_io_report:print','Error printing CAT error report.'}]; + cat_io_cprintf('err','%30s: %s\n',createerrtxt{end,1},createerrtxt{end,2}); + end + + + %% reset colormap to the simple SPM like gray60 colormap + if exist('hSD','var') + % if there is a surface than we have to use the gray colormap also here + % because the colorbar change! + try + cat_surf_render2('ColourMap',hSD{1}.axis,gray(128)); + cat_surf_render2('Clim',hSD{1}.axis,[0 6]); + if createerr==41, error(sprintf('error:cat_io_report:createerr_%d',createerr),'Test'); end + axes(cc{3}); image(0:60); + set(cc{3},'XTick',max(1,0:10:60),'XTickLabel',{'0','1','2','3','4','5',' 6 mm'},... + 'YTickLabel','','YTick',[],'TickLength',[0 0],'FontSize',fontsize,'FontWeight','Bold'); + catch + createerrtxt = [createerrtxt; {'Error:cat_io_report:surfcolmap','Error in displaying surface colormap.'}]; + cat_io_cprintf('err','%30s: %s\n',createerrtxt{end,1},createerrtxt{end,2}); + end + end + + try + %% %cmap = gray(60); colormap(cmap); + % RD202101: This part would has to be replaced completelly with a + % dynamic peak estimation and setting for the original image + cmap(1:volcolors,:) = gray(volcolors); + cmap(volcolors+1:2*volcolors,:) = flipud(pink(volcolors)); + cmap(volcolors*2+1:volcolors*2+surfcolors,:) = jet(surfcolors); + colormap(fg,cmap); %caxis([0,numel(cmap)]); + + %if exist('hho' ,'var'), spm_orthviews('window',hho ,[0,6]); end % not fixed ! ... + %if exist('hhm' ,'var'), spm_orthviews('window',hhm ,[0,3/4]); end + if exist('hhp0','var'), spm_orthviews('window',hhp0,[0,4]); end + + % update histograms - switch from color to gray + if exist('hhist','var') + %% + if hhist(1)>0 && haxis(1)>0, set(hhist(1),'cdata',(hdata{1}(3,:)' - min(hdata{1}(3,:))) / diff([min(hdata{1}(3,:)),max(hdata{1}(3,:))]) ); caxis(haxis(1),[0 4]); end + if createerr==9, error(sprintf('error:cat_io_report:createerr_%d',createerr),'Test'); end + if hhist(2)>0 && haxis(2)>0, set(hhist(2),'cdata',(hdata{2}(3,:)' - min(hdata{2}(3,:))) / diff([min(hdata{2}(3,:)),max(hdata{2}(3,:))])); caxis(haxis(2),[0 4]); end + if hhist(3)>0 && haxis(3)>0, set(hhist(3),'cdata',(hdata{3}(3,:)' - min(hdata{3}(3,:))) / diff([min(hdata{3}(3,:)),max(hdata{3}(3,:))])); caxis(haxis(3),[0 4]); end + end + catch + createerrtxt = [createerrtxt; {'Error:cat_io_report','Error in changing colormap.'}]; + cat_io_cprintf('err','%30s: %s\n',createerrtxt{end,1},createerrtxt{end,2}); + end + %warning on; %#ok + + if job.extopts.expertgui>0 - showTPMsurf && exist('hM','var') && ... + isfield(st,'vol') && iscell(st.vols) && numel(st.vols)>=id && ... + isfield(st.vols{id},'ax') && iscell(st.vols{id}.ax) && isfield(st.vols{id}.ax{1},'cm') + id = 1; + hM = findobj(st.vols{id}.ax{1}.cm,'Label','Mesh'); + UD = get(hM,'UserData'); + UD.width = 0.75; + UD.style = repmat({'r--'},1,numel(Phull)); + set(hM,'UserData',UD); + try spm_ov_mesh('redraw',id); end + end + + warning('ON','MATLAB:subscripting:noSubscriptsSpecified') + +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_tst_staple_multilabels.m",".m","8500","256","function cat_tst_staple_multilabels(P,Pm,Q,verb) +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + if nargin == 0 + P = spm_select(Inf,'image','Select images from different experts'); + Pm = spm_select(1,'image','Select mask image if needed'); + [pp,ff,ee] = spm_fileparts(P(1,:)); + Q = fullfile(pp,[ff '_gt' ee]); + end + if ~exist('verb','var'), verb=0; end + + n = size(P,1); + + V = spm_vol(deblank(P)); + Vm = spm_vol(Pm); + Vo = V(1); + Vo.fname = Q; + + vol = zeros([V(1).dim(1:3) n],'single'); + for i=1:n + vol(:,:,:,i) = single(spm_read_vols(V(i))); + end + n=n+1; vol(:,:,:,n) = cat_stat_nanmean(vol,4); + %vol(isinf(vol(:)) | isnan(vol(:))) = 0; + vol_size = size(vol); + + % check dimensions for data+mask + if ~isempty(Vm); V(n+1) = Vm; end + if any(any(diff(cat(1,V.dim),1,1),1)) + error('Dimensions differ'); + end + + % mask images and remove background + if ~isempty(Vm) + mask = spm_read_vols(Vm); + else + mask = zeros(V(1).dim(1:3),'single'); + for i=1:n + volt = single(vol(:,:,:,i)>0.5); + if sum(volt(:))>10000 % to avaid using of missclassified images for masking + mask = mask + volt; + end + end + mask = smooth3(single(mask))>=(max(mask(:))/2); + end + mask_ind = find(mask > 0); + masked_vol = zeros(length(mask_ind),n,'single'); + for i=1:n + tmp = vol(:,:,:,i); + tmp(isnan(tmp(:)) | isinf(tmp(:)) | tmp(:)<0)=0; + masked_vol(:,i) = round(tmp(mask_ind)); + end + meanvol=mean(vol,4); + clear tmp vol; + + numLabel = max(masked_vol(:)) + 1; + minLabel = min(masked_vol(:)); + if minLabel ~= 0 + error('Minimum value in data is not zero'); + end + + [W, Theta] = STAPLE_multiLabels_nD(masked_vol, numLabel,verb); + + slabel = zeros(size(mask),'single'); + slabel(mask_ind) = W - 1; + slabel(slabel>meanvol*2)=0; + Vo.dt(1) = 2; + spm_write_vol(Vo,slabel); +end + +% Program: function [W,Theta,stop]=STAPLE_multiLabels(expertSegmentations,numLabels) +% Date: 2005/01/25 +% Language: Matlab +% +% AUTHORS: Meritxell Bach Cuadra (http://ltswww.epfl.ch/~bach) +% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% REFERENCE FOR THE IMPLEMENTATION: +% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% ""Simultaneous Truth and Performance Level Estimation (STAPLE): An +% algorithm for the Validation of Image Segmentation"", Warfield et al, +% IEEE Transactions on Medical Imaging, Volume: 23 , Issue: 7 , July 2004 +% +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% TERMS OF USE: +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% You can use/modify this program for any use you wish, provided you cite +% the above references in any publication about it. +% +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% DISCLAIMER: +% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% In no event shall the authors or distributors be liable to any party for +% direct, indirect, special, incidental, or consequential damages arising out +% of the use of this software, its documentation, or any derivatives thereof, +% even if the authors have been advised of the possibility of such damage. +% +% The authors and distributors specifically disclaim any warranties, including, +% but not limited to, the implied warranties of merchantability, fitness for a +% particular purpose, and non-infringement. this software is provided on an +% ""as is"" basis, and the authors and distributors have no obligation to provide +% maintenance, support, updates, enhancements, or modifications. +% +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% Description: +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% Function to calculate the new label map +% using a EM-HMRF assuming Gaussian distribution. +% +% It will first use the normal EM algorithm to find an estimation +% of the means and sigmas of the tissue type: +% +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% Usage: +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% Dij=expertSegmentations: numLine x numCol x numExperts matrix (for the moment only 2D segmentations) of +% integer values (typically 0,1,2,...,L, where L is the number of different labels) +% +% numLabels = number of present labels including the background +% +% W is the estimated True Segmentation probability, it is a matrix of N x +% numLabels elements (where N is the total number of voxels in the image) +% +% Theta is a numLabels x numLabels x numExperts matrix. For each expert, a +% confusion table corresponding to the probability of an expert to classify +% the voxel as s when is actually s_prime (float values) +% +% stop is a vector having the convergence criteria history (here the normalized +% trace of the expert parameters is considered) + +function [W,Theta,stop]=STAPLE_multiLabels_nD(expertSegmentations,numLabels,verb) + + % expertSegmentations will be converted to a 2D matrix: N x numExperts + origsize = size(expertSegmentations); + ndim = length(origsize) - 1; + expertSegmentations = 1 + reshape(expertSegmentations,prod(origsize(1:ndim)),origsize(ndim+1)); + + s=size(expertSegmentations); + + N=s(1); + numExperts=s(2); + + % Prior probability (f(Ti=s)) of belonging to one class (sample mean of the relative proportion of the label in the segmentations) + % Gamma_s=f(Ti=s) + Gamma_s=zeros(numLabels,1,'single'); + for k=1:numLabels, + temp=zeros(s); + temp(find(expertSegmentations==(k-1)))=1; + Gamma_s(k)=sum(sum(sum(temp)))./(N*numExperts); + end + if verb + fprintf('Prior probability (f(Ti=s)) of belonging to one class (Gamma):\n'); + fprintf('%5.5f ',Gamma_s); + fprintf('\n\n'); + end + + clear temp + + %Expert parameters: confusion table Theta + Theta=zeros(numLabels,numLabels,numExperts,'single'); + % Initialization as proposed by Warfield: high value equal for all experts + for j=1:numExperts, + for s=1:numLabels, + for k=1:numLabels, + if(s==k), + Theta(s,k,j)=0.99; + else + Theta(s,k,j)=(1-0.99)./(numLabels-1); + end + end + end + end + + %Convergence + epsilon=10^(-7); % As proposed in the paper + maxIter=25; + stop=zeros(maxIter,1); + %Loop until convergence or maximum number of iterations + k=1; + while(k<=maxIter), + if verb, fprintf('Iteration %d\n',k); end + %Estimation of W + W=zeros(N,numLabels,'single'); + %Eq.20 TMI + sumW=zeros(N,1,'single'); + for s=1:numLabels, + %numeratorW=zeros(N,1); + numeratorW=Gamma_s(s); + for j=1:numExperts, + numeratorW=numeratorW.*Theta(expertSegmentations(:,j),s,j); + end + sumW=sumW+numeratorW; + W(:,s)=numeratorW; + end + %Normalization among all labels + for s=1:numLabels, + W(:,s)=W(:,s)./sumW(:); + %W(find(sumW==0),s)=0; + end + + %Estimation of Theta (expert parameters) + for j=1:numExperts, + for s=1:numLabels, + for s_prime=1:numLabels, + index=find(expertSegmentations(:,j)==s_prime); + temp=zeros(N,1); + temp(index)=W(index,s); + if(sum(W(:,s))~=0) + Theta(s_prime,s,j)=sum(temp)./sum(W(:,s)); + end + end + end + end + clear temp + + %Compute stopping criteria + for j=1:numExperts, + stop(k)=(stop(k)+trace(Theta(:,:,j))); + end + stop(k)=stop(k)./numLabels/numExperts; + if(k>1), + if((stop(k-1)-stop(k)) 1 + W = reshape(Wnew,origsize(1:ndim)); + else + W = Wnew; + end + + % Showing convergence history + if verb + figure; + index=find(stop); + plot(stop(index)) + title('STAPLE convergence evolution') + xlabel('Iteration') + ylabel('Normalized trace of expert parameters') + end +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_surf_smooth.m",".m","5736","151","function varargout = cat_surf_smooth(varargin) +% ______________________________________________________________________ +% Function to smooth the data of a surface mesh. +% +% [Psdata] = cat_surf_smooth(job) +% +% job.data .. cellstr of files +% job.fwhm .. filter size in mm +% job.verb .. display command line progress +% job.nproc .. parallel jobs +% job.assuregifti .. creaty only gifti data (mesh and texture); def==0 +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +% further private job options +% job.lazy .. does not do anything, if the result already exist + +%#ok<*ASGLU> + + if nargin == 1 + Pdata = varargin{1}.data; + fwhm = varargin{1}.fwhm; + job = varargin{1}; + else + job = struct(); + spm_clf('Interactive'); + Pdata = cellstr(spm_select([1 inf],'any','Select surface data','','','[rl]h.(?!cent|sphe|defe).*')); + if isempty(Pdata), return; end + fwhm = spm_input('Smoothing filter size in fwhm',1,'r',15); + end + + def.trerr = 0; % cat_check_system_output error handling + def.debug = cat_get_defaults('extopts.verb')>2; % cat_check_system_output error handling + def.nproc = 0; % parallel processing + def.assuregifti = 0; % guarantee gifti output + def.verb = cat_get_defaults('extopts.verb'); + def.lazy = 0; % do not reprocess exist results + def.fsavgDir = fullfile(fileparts(mfilename('fullpath')),'templates_surfaces'); + def.catblur = 1; % use CAT rather than SPM smoothing + def.spmfactor = 50; % this is guessed factor!!! + job = cat_io_checkinopt(job,def); + + % split job and data into separate processes to save computation time + if isfield(job,'nproc') && job.nproc>0 && (~isfield(job,'process_index')) + if nargout==1 + varargout{1} = cat_parallelize(job,mfilename); + else + cat_parallelize(job,mfilename); + end + return + end + + + % normal processing + % ____________________________________________________________________ + + % new banner + if isfield(job,'process_index'), spm('FnBanner',mfilename); end + + % display something + spm_clf('Interactive'); + cat_progress_bar('Init',numel(Pdata),'Smoothed Surfaces','Surfaces Completed'); + + Psdata = Pdata; + sinfo = cat_surf_info(Pdata); + for i=1:numel(Pdata) + %% new file name + Psdata(i) = cat_surf_rename(sinfo(i),'dataname',sprintf('s%d%s',round(fwhm),sinfo(i).dataname)); + + if exist(Psdata{i},'file') && job.lazy + fprintf('Display already smoothed %s\n',Psdata{i},'link','cat_surf_display(''%s'')'); + else + stime = clock; + + % assure gifty output + if job.assuregifti && ~strcmp(sinfo(i).ee,'.gii') + cdata = cat_io_FreeSurfer('read_surf_data',Pdata{i}); + Psdata(i) = cat_surf_rename(Psdata(i),'ee','.gii'); + save(gifti(struct('cdata',cdata)),Psdata{i}); + end + + % smooth values + [pp,ff,ee] = fileparts(Pdata{i}); + if strcmp(ee,'.gii') + % smoothing of gifti data + if job.catblur + [PS,PC] = cat_io_FreeSurfer('gii2fs',Pdata{i}); + cmd = sprintf('CAT_BlurSurfHK ""%s"" ""%s"" ""%g"" ""%s""',sinfo(i).Pmesh,Psdata{i},fwhm,PC{1}); % load mesh separate anyway + cat_system(cmd,job.debug); + else % spm mesh data smoothing + T = gifti(Pdata{i}); + if sinfo(i).resampled % resampled (with mesh data) + M = T; + T = spm_mesh_smooth(struct('vertices',double(T.vertices),'faces',double(T.faces)), double(T.cdata(:)) , fwhm * job.spmfactor); + else % not resampled (load separate mesh data) + M = gifti(sinfo(i).Pmesh); + T = spm_mesh_smooth(struct('vertices',double(M.vertices),'faces',double(M.faces)), double(T.cdata(:)) , fwhm * job.spmfactor); + end + %save(gifti(struct('cdata',T)),Psdata{i}); % cat_blur write mesh and we here too + save(gifti(struct('vertices',double(M.vertices),'faces',double(M.faces),'cdata',T)),Psdata{i}); + end + else + % smoothing of FreeSurfer data + if job.catblur + cmd = sprintf('CAT_BlurSurfHK ""%s"" ""%s"" ""%g"" ""%s""',sinfo(i).Pmesh,Psdata{i},fwhm,Pdata{i}); + cat_system(cmd,job.debug); + else % spm mesh data smoothing + M = gifti(sinfo(i).Pmesh); + T = gifti(cat_io_FreeSurfer('read_surf_data',Pdata{i})); + T = spm_mesh_smooth(struct('vertices',double(M.vertices),'faces',double(M.faces)), double(T.cdata(:)) , fwhm * job.spmfactor ); + cat_io_FreeSurfer('write_surf_data',Psdata{i},T.cdata); + end + end + + % if gifti output, check if there is surface data in the original gifti and add it + if job.catblur + if sinfo(i).statready || strcmp(sinfo(i).ee,'.gii') + cmd = sprintf('CAT_AddValuesToSurf ""%s"" ""%s"" ""%s""',Pdata{i},Psdata{i},Psdata{i}); + cat_system(cmd,job.debug,def.trerr); + end + + % remove temporary FreeSurfer data + if exist('PS','var'), for pi=1:numel(PS), delete(PS{pi}); end; clear PS; end + if exist('PC','var'), for pi=1:numel(PC), delete(PC{pi}); end; clear PC; end + end + + if job.verb + fprintf('%4.0fs. Display resampled %s\n',etime(clock,stime),spm_file(Psdata{i},'link','cat_surf_display(''%s'')')); + end + end + + cat_progress_bar('Set',i); + + end + + if isfield(job,'process_index') + fprintf('Done\n'); + end + + if nargout==1 + varargout{1} = Psdata; + end + + cat_progress_bar('Clear'); +end","MATLAB" +"Neurology","ChristianGaser/cat12","tbx_cfg_cat.m",".m","26474","573","function cat = tbx_cfg_cat +% Configuration file for segment jobs +%_______________________________________________________________________ +% +% Christian Gaser +% $Id$ +% +%#ok<*AGROW> + +addpath(fileparts(which(mfilename))); + +%% ------------------------------------------------------------------------ +try + expert = cat_get_defaults('extopts.expertgui'); +catch %#ok + expert = 0; +end +if isempty(expert) + expert = 0; +end + +% always use expert mode for standalone installations +if isdeployed, expert = 1; end + +% try to estimate number of processor cores +try + numcores = cat_get_defaults('extopts.nproc'); + % because of poor memory management use only half of the cores for windows + if ispc + numcores = round(numcores/2); + end + numcores = max(numcores,1); +catch + numcores = 0; +end + +% force running in the foreground if only one processor was found or for compiled version +% or for Octave +if numcores == 1 || isdeployed || strcmpi(spm_check_version,'octave'), numcores = 0; end + +%_______________________________________________________________________ +nproc = cfg_entry; +nproc.tag = 'nproc'; +nproc.name = 'Split job into separate processes'; +nproc.strtype = 'w'; +nproc.val = {numcores}; +nproc.num = [1 1]; +nproc.hidden = numcores <= 1 || isdeployed; +nproc.help = { + 'In order to use multi-threading the CAT12 segmentation job with multiple subjects can be split into separate processes that run in the background. If you do not want to run processes in the background then set this value to 0.' + '' + 'Keep in mind that each process needs about 1.5..2GB of RAM, which should be considered to choose the appropriate number of processes.' + '' + 'Please further note that additional modules in the batch can now be used because the processes are checked every minute.' + }; + +%_______________________________________________________________________ + +data = cfg_files; +data.tag = 'data'; +data.name = 'Volumes'; +data.filter = {'image','.*\.(nii.gz)$'}; +data.ufilter = '.*'; +data.num = [1 Inf]; +data.help = { + 'Select highres raw data (e.g. T1 images) for segmentation. 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 implemented for this method. Nifti files and compressed nifti files are supported.'}; +%data.preview = @(f) spm_check_registration(char(f)); + +data_wmh = cfg_files; +data_wmh.tag = 'data_wmh'; +data_wmh.name = 'Additional FLAIR Volumes'; +data_wmh.filter = 'image'; +data_wmh.ufilter = '.*'; +data_wmh.num = [0 Inf]; +data_wmh.hidden = expert < 2; +data_wmh.help = { + 'Select highres FLAIR data for segmentation. This assumes that there is one scan for each T1 scan.' + 'WARNING: WMH segmentation (with/without FLAIR) is in development!'}; +data_wmh.preview = @(f) spm_check_registration(char(f)); +data_wmh.val = {{''}}; + +data_spm = cfg_files; +data_spm.tag = 'data'; +data_spm.name = 'Segmentations in native space'; +data_spm.filter = 'image'; +data_spm.ufilter = '^c1.*'; +data_spm.num = [0 Inf]; +data_spm.help = { + 'Select SPM segmentations for class 1 for all subjects. Names for all other remaining classes 2 and 3 are automatically estimated.'}; +data_spm.preview = @(f) spm_check_registration(char(f)); + +useprior = cfg_files; +useprior.tag = 'useprior'; +useprior.name = 'Use prior for longitudinal data'; +useprior.filter = 'image'; +useprior.ufilter = '.*'; +useprior.num = [0 1]; +useprior.val = {''}; +useprior.hidden = true; % allways hidden +useprior.help = { + 'Please note that this option is only intended for longitudinal data and is internally automatically set to the average image of all time points. Thus, please do not edit this option!' + '' + 'The average image is used as a first estimate for affine transformation, segmentation and surface extraction. The idea is that by initializing with the average image we can reduce random variations and improve the robustness and sensitivity of the entire longitudinal pipeline. Furthermore, it significantly increases the speed of the surface extraction.' + '' +}; + +%% ------------------------------------------------------------------------ +tools = cat_conf_tools(expert); % volume tools +stools = cat_conf_stools(expert); % surface tools +stoolsexp = cat_conf_stoolsexp; % surface expert tools +stoolsexp.hidden = expert<2; +extopts = cat_conf_extopts(expert); +opts = cat_conf_opts(expert); +[output,output_spm] = cat_conf_output(expert); +long = cat_conf_long; +factorial_design = cat_conf_factorial(expert); + +%% ------------------------------------------------------------------------ +estwrite = cfg_exbranch; +estwrite.tag = 'estwrite'; +estwrite.name = 'CAT12: Segmentation'; +estwrite.val = {data data_wmh nproc useprior opts extopts output}; +estwrite.prog = @cat_run; +estwrite.vout = @vout; +estwrite.help = { +'This toolbox is an extension to the default segmentation in SPM12 or SPM25, but uses a completely different segmentation approach.' +'' +'The segmentation approach is based on an Adaptive Maximum A Posterior (MAP) technique without the need for a priori information about tissue probabilities. That is, the Tissue Probability Maps (TPM) are not used constantly in the sense of the classical Unified Segmentation approach (Ashburner et. al. 2005), but just for spatial normalization. The following AMAP estimation is adaptive in the sense that local variations of the parameters (i.e., means and variance) are modeled as slowly varying spatial functions (Rajapakse et al. 1997). This not only accounts for intensity inhomogeneities but also for other local variations of intensity.' +'' +'Additionally, the segmentation approach uses a Partial Volume Estimation (PVE) with a simplified mixed model of at most two tissue types (Tohka et al. 2004). We start with an initial segmentation into three pure classes: gray matter (GM), white matter (WM), and cerebrospinal fluid (CSF) based on the above described AMAP estimation. The initial segmentation is followed by a PVE of two additional mixed classes: GM-WM and GM-CSF. This results in an estimation of the amount (or fraction) of each pure tissue type present in every voxel (as single voxels - given by their size - probably contain more than one tissue type) and thus provides a more accurate segmentation.' +'' +'Another important extension to the SPM segmentation is the integration of the Dartel or Geodesic Shooting registration into the toolbox by an already existing Dartel/Shooting template in MNI space. This template was derived from 555 healthy control subjects of the IXI-database (http://www.brain-development.org) and provides the several Dartel or Shooting iterations. Thus, for the majority of studies the creation of sample-specific templates is not necessary anymore and is mainly recommended for children data.'}; + +%------------------------------------------------------------------------ +% CAT surface processing with existing SPM segmentation + +extopts_spm = cat_conf_extopts(expert,1); +estwrite_spm = cfg_exbranch; +estwrite_spm.tag = 'estwrite_spm'; +estwrite_spm.name = 'SPM segmentation with surface and thickness estimation'; +estwrite_spm.val = {data_spm nproc extopts_spm output_spm}; +estwrite_spm.prog = @cat_run; +estwrite_spm.vout = @vout; +%estwrite_spm.hidden = expert<1; +estwrite_spm.help = { +'Thickness estimation and surface creation for SPM segmentation, which is using the input of CSF, GM, and WM of the SPM segmentation (instead of CAT12 segmentation) and also integrates Dartel or Geodesic Shoothing registration to an already existing Dartel template in MNI space. The default template was derived from 555 healthy control subjects of the IXI-database (http://www.brain-development.org).'}; + +%------------------------------------------------------------------------ +cat = cfg_choice; +cat.name = 'CAT12'; +cat.tag = 'cat'; + +if exist('cat_conf_catsimple','file') + [catsimple,catsimple_long] = cat_conf_catsimple(expert); + catsimple_long.hidden = expert<2; + cat.values = {estwrite long catsimple catsimple_long estwrite_spm factorial_design tools stools stoolsexp}; +else + cat.values = {estwrite long estwrite_spm factorial_design tools stools stoolsexp}; +end +%------------------------------------------------------------------------ + +%------------------------------------------------------------------------ +function dep = vout(job) + +opts = job.output; + +if isfield(opts.GM,'warped') && isfield(opts.GM,'native') + tissue(1).warped = [opts.GM.warped (opts.GM.mod==1) (opts.GM.mod==2) ]; + tissue(1).native = [opts.GM.native (opts.GM.dartel==1) (opts.GM.dartel==2) ]; + tissue(2).warped = [opts.WM.warped (opts.WM.mod==1) (opts.WM.mod==2) ]; + tissue(2).native = [opts.WM.native (opts.WM.dartel==1) (opts.WM.dartel==2) ]; +elseif ~isfield(opts.GM,'native') + if isfield(opts.GM,'warped') + tissue(1).warped = [opts.GM.warped (opts.GM.mod==1) (opts.GM.mod==2) ]; + tissue(2).warped = [opts.WM.warped (opts.WM.mod==1) (opts.WM.mod==2) ]; + else + tissue(1).warped = [0 (opts.GM.mod==1) (opts.GM.mod==2) ]; + tissue(2).warped = [0 (opts.WM.mod==1) (opts.WM.mod==2) ]; + end +else + tissue(1).warped = [0 (opts.GM.mod==1) (opts.GM.mod==2) ]; + tissue(1).native = [opts.GM.native (opts.GM.dartel==1) (opts.GM.dartel==2) ]; + tissue(2).warped = [0 (opts.WM.mod==1) (opts.WM.mod==2) ]; + tissue(2).native = [opts.WM.native (opts.WM.dartel==1) (opts.WM.dartel==2) ]; +end + +if isfield(opts,'CSF') + tissue(3).warped = [opts.CSF.warped (opts.CSF.mod==1) (opts.CSF.mod==2) ]; + if isfield(opts.CSF,'native') + tissue(3).native = [opts.CSF.native (opts.CSF.dartel==1) (opts.CSF.dartel==2) ]; + end +end + +if isfield(opts,'TPMC') + for i=4:6 + tissue(i).warped = [opts.TPMC.warped (opts.TPMC.mod==1) (opts.TPMC.mod==2) ]; + if isfield(opts.TPMC,'native') + tissue(i).native = [opts.CSF.native (opts.CSF.dartel==1) (opts.TPMC.dartel==2) ]; + end + end +end +% This depends on job contents, which may not be present when virtual +% outputs are calculated. + +% CAT report PDF file +cdep = cfg_dep; +cdep(end).sname = 'CAT Report PDF'; +cdep(end).src_output = substruct('.','catreportpdf','()',{':'}); +cdep(end).tgt_spec = cfg_findspec({{'filter','pdf','strtype','e'}}); + +% CAT report JPG file +cdep(end+1) = cfg_dep; +cdep(end).sname = 'CAT Report JPG'; +cdep(end).src_output = substruct('.','catreportjpg','()',{':'}); +cdep(end).tgt_spec = cfg_findspec({{'filter','jpg','strtype','e'}}); + +% CAT report XML file +cdep(end+1) = cfg_dep; +cdep(end).sname = 'CAT Report'; +cdep(end).src_output = substruct('.','catxml','()',{':'}); +cdep(end).tgt_spec = cfg_findspec({{'filter','catreport','strtype','e'}}); + +% CAT log file +cdep(end+1) = cfg_dep; +cdep(end).sname = 'CAT log-file'; +cdep(end).src_output = substruct('.','catlog','()',{':'}); +cdep(end).tgt_spec = cfg_findspec({{'filter','txt','strtype','e'}}); + + +% lh/rh/cb central/white/pial/layer4 surface and thickness (see also cat_run!) +% ---------------------------------------------------------------------- +% In case of the fast surface processing without registration no spherical +% registration surface are available. Moreover, the central and thickness +% cannot be used because the topology is also uncorrected. +if isfield(opts,'surface') && opts.surface + surfaceoutput = { % surface texture + {'central','sphere','sphere.reg'} % no measures - just surfaces + {} % default + {} % expert + {'pial','white'} % developer + }; + if any( job.output.surface == [ 5 6 ] ) %&& cat_get_defaults('extopts.expertgui')<2 % no sphere's without registration + for i = 1:3 + surfaceoutput{i} = setdiff(surfaceoutput{i},{'central','sphere','sphere.reg'}); + end + end + measureoutput = { + {'thickness','pbt'} % default + {} % no measures + {} % expert + {'depthWM','depthCSF'} % developer + }; + if any( job.output.surface == [ 5 6 ] ) %&& cat_get_defaults('extopts.expertgui')<2 + measureoutput{1} = setdiff(measureoutput{1},{'thickness','pbt'}); + end + % no output of intlayer4 or defects in cat_surf_createCS but in cat_surf_createCS2 (but not with fast) + if isfield(job,'extopts') && isfield(job.extopts,'surface') && ... + isfield(job.extopts.surface,'collcorr') && job.extopts.surface.collcorr>19 + + surfaceoutput{1} = [surfaceoutput{1},{'pial','white'}]; + surfaceoutput{4} = {}; + if any( job.output.surface ~= [ 5 6 ] ) % fast pipeline + surfaceoutput{3} = {'layer4'}; + measureoutput{3} = {'intlayer4','defects'}; + end + end + + sides = {'lh','rh'}; + sidenames = {'Left','Right'}; + if any( job.output.surface == [ 2 6 8 ] ) + sides = [sides {'cb'}]; + sidenames = [sidenames {'Cerebellar'}]; + end + + def.output.surf_measures = 1; + def.extopts.expertgui = 0; + job = cat_io_checkinopt(job,def); + % create fields + for si = 1:numel(sides) + for soi = 1:numel(surfaceoutput) + if soi < job.extopts.expertgui + 2 + for soii = 1:numel(surfaceoutput{soi}) + if ~isempty( surfaceoutput{soi} ) + % remove dots in name (e.g. for sphere.reg) + surfaceoutput_str = strrep(surfaceoutput{soi}{soii},'.',''); + cdep(end+1) = cfg_dep; + cdep(end).sname = sprintf('%s %s%s Surface', sidenames{si}, ... + upper(surfaceoutput_str(1)), surfaceoutput_str(2:end)); + cdep(end).src_output = substruct('()',{1}, '.', ... + sprintf('%s%s', sides{si} , surfaceoutput_str ),'()',{':'}); + cdep(end).tgt_spec = cfg_findspec({{'filter','gifti','strtype','e'}}); + end + end + end + end + for soi = 1:numel(surfaceoutput) + if soi < job.extopts.expertgui + 2 + for soii = 1:numel(measureoutput{soi}) + if ~isempty( measureoutput{soi} ) + cdep(end+1) = cfg_dep; + cdep(end).sname = sprintf('%s %s%s', sidenames{si}, ... + upper(measureoutput{soi}{soii}(1)), measureoutput{soi}{soii}(2:end)); + cdep(end).src_output = substruct('()',{1}, '.', ... + sprintf('%s%s', sides{si} , measureoutput{soi}{soii} ),'()',{':'}); + cdep(end).tgt_spec = cfg_findspec({{'filter','any','strtype','e'}}); + end + end + end + end + end +end + +% XML label +if isfield(opts,'ROImenu') && isfield(opts.ROImenu,'atlases') + if isfield(job.output.ROImenu.atlases,'ownatlas'), atlases = rmfield(job.output.ROImenu.atlases,'ownatlas'); end + is_ROI = any(cell2mat(struct2cell(atlases))) || ... + (~isempty( job.output.ROImenu.atlases.ownatlas ) & ~isempty( job.output.ROImenu.atlases.ownatlas{1} )); + + if is_ROI + cdep(end+1) = cfg_dep; + cdep(end).sname = 'ROI XML File'; + cdep(end).src_output = substruct('()',{1}, '.','catroi','()',{'1'}); + cdep(end).tgt_spec = cfg_findspec({{'filter','xml','strtype','e'}}); + end +end + +% bias corrected +if isfield(opts,'bias') + if isfield(opts.bias,'native') + if opts.bias.native + cdep(end+1) = cfg_dep; + cdep(end).sname = 'Native Bias Corr. Image'; + cdep(end).src_output = substruct('()',{1}, '.','biascorr','()',{':'}); + cdep(end).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); + end + end + if opts.bias.warped + cdep(end+1) = cfg_dep; + cdep(end).sname = 'Warped Bias Corr. Image'; + cdep(end).src_output = substruct('()',{1}, '.','wbiascorr','()',{':'}); + cdep(end).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); + end +elseif isfield(opts,'biasnative') + if opts.bias.native + cdep(end+1) = cfg_dep; + cdep(end).sname = 'Native Bias Corr. Image'; + cdep(end).src_output = substruct('()',{1}, '.','biascorr','()',{':'}); + cdep(end).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); + end +end + +% LAS bias corrected +if isfield(opts,'las') + if opts.las.native + cdep(end+1) = cfg_dep; + cdep(end).sname = 'Native LAS Bias Corr. Image'; + cdep(end).src_output = substruct('()',{1}, '.','ibiascorr','()',{':'}); + cdep(end).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); + end + if opts.las.warped + cdep(end+1) = cfg_dep; + cdep(end).sname = 'Warped LAS Bias Corr. Image'; + cdep(end).src_output = substruct('()',{1}, '.','wibiascorr','()',{':'}); + cdep(end).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); + end + if opts.las.dartel==1 + cdep(end+1) = cfg_dep; + cdep(end).sname = 'Rigidly Registered LAS Bias Corr. Image'; + cdep(end).src_output = substruct('()',{1}, '.','ribiascorr','()',{':'}); + cdep(end).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); + end + if opts.las.dartel==2 + cdep(end+1) = cfg_dep; + cdep(end).sname = 'Affine Registered LAS Bias Corr. Image'; + cdep(end).src_output = substruct('()',{1}, '.','aibiascorr','()',{':'}); + cdep(end).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); + end +end + +% label +if isfield(opts,'label') + if opts.label.native + cdep(end+1) = cfg_dep; + cdep(end).sname = 'Native Label Image'; + cdep(end).src_output = substruct('()',{1}, '.','label','()',{':'}); + cdep(end).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); + end + if opts.label.warped + cdep(end+1) = cfg_dep; + cdep(end).sname = 'Warped Label Image'; + cdep(end).src_output = substruct('()',{1}, '.','wlabel','()',{':'}); + cdep(end).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); + end + if opts.label.dartel==1 + cdep(end+1) = cfg_dep; + cdep(end).sname = 'Rigidly Registered Label Image'; + cdep(end).src_output = substruct('()',{1}, '.','rlabel','()',{':'}); + cdep(end).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); + end + if opts.label.dartel==2 + cdep(end+1) = cfg_dep; + cdep(end).sname = 'Affine Registered Label Image'; + cdep(end).src_output = substruct('()',{1}, '.','alabel','()',{':'}); + cdep(end).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); + end +elseif isfield(opts,'labelnative') + cdep(end+1) = cfg_dep; + cdep(end).sname = 'Native Label Image'; + cdep(end).src_output = substruct('()',{1}, '.','label','()',{':'}); + cdep(end).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); +end + +maps = { + 'wmh' 'WM Hyperintensity Image'; + 'sl' 'Stroke Lesion Image'; + 'gmt' 'GM Thickess Image'; + }; +for mi=1:size(maps,1) + if isfield(opts,maps{mi,1}) + if isfield(opts.atlas,'native') && opts.atlas.native + cdep(end+1) = cfg_dep; + cdep(end).sname = ['Native' maps{mi,2}]; + cdep(end).src_output = substruct('()',{1}, '.',maps{mi,1},'()',{':'}); + cdep(end).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); + end + if isfield(opts.atlas,'warped') && opts.atlas.warped + cdep(end+1) = cfg_dep; + cdep(end).sname = ['Warped' maps{mi,2}]; + cdep(end).src_output = substruct('()',{1}, '.',['w' maps{mi,1}],'()',{':'}); + cdep(end).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); + end + if isfield(opts.atlas,'mod') && (opts.atlas.mod==1 || opts.atlas.mod==3) + cdep(end+1) = cfg_dep; + cdep(end).sname = ['Affine + Nonlinear Modulated ' maps{mi,2}]; + cdep(end).src_output = substruct('()',{1}, '.',['wm' maps{mi,1}],'()',{':'}); + cdep(end).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); + end + if isfield(opts.atlas,'mod') && (opts.atlas.mod==2 || opts.atlas.mod==3) + cdep(end+1) = cfg_dep; + cdep(end).sname = ['Nonlinear Modulated Only' maps{mi,2}]; + cdep(end).src_output = substruct('()',{1}, '.',['wm0' maps{mi,1}],'()',{':'}); + cdep(end).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); + end + if isfield(opts.atlas,'dartel') && (opts.atlas.dartel==1 || opts.atlas.dartel==3) + cdep(end+1) = cfg_dep; + cdep(end).sname = ['Rigidly Registered' maps{mi,2}]; + cdep(end).src_output = substruct('()',{1}, '.',['r' maps{mi,1}],'()',{':'}); + cdep(end).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); + end + if isfield(opts.atlas,'dartel') && (opts.atlas.dartel==2 || opts.atlas.dartel==3) + cdep(end+1) = cfg_dep; + cdep(end).sname = ['Affine Registered' maps{mi,2}]; + cdep(end).src_output = substruct('()',{1}, '.',['a' maps{mi,1}],'()',{':'}); + cdep(end).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); + end + end +end + +% atlas +if isfield(opts,'atlas') + if isfield(opts.atlas,'native') && opts.atlas.native + cdep(end+1) = cfg_dep; + cdep(end).sname = 'Native Atlas Image'; + cdep(end).src_output = substruct('()',{1}, '.','atlas','()',{':'}); + cdep(end).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); + end + if isfield(opts.atlas,'warped') && opts.atlas.warped + cdep(end+1) = cfg_dep; + cdep(end).sname = 'Warped Atlas Image'; + cdep(end).src_output = substruct('()',{1}, '.','watlas','()',{':'}); + cdep(end).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); + end + if isfield(opts.atlas,'dartel') && opts.atlas.dartel==1 + cdep(end+1) = cfg_dep; + cdep(end).sname = 'Rigidly Registered Atlas Image'; + cdep(end).src_output = substruct('()',{1}, '.','ratlas','()',{':'}); + cdep(end).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); + end + if isfield(opts.atlas,'dartel') && opts.atlas.dartel==2 + cdep(end+1) = cfg_dep; + cdep(end).sname = 'Affine Registered Atlas Image'; + cdep(end).src_output = substruct('()',{1}, '.','aatlas','()',{':'}); + cdep(end).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); + end +end + +% jacobian +if ( isfield(opts,'jacobian') && opts.jacobian.warped ) || ... + ( isfield(opts,'jacobianwarped') && opts.jacobianwarped ) + cdep(end+1) = cfg_dep; + cdep(end).sname = 'Jacobian Determinant Image'; + cdep(end).src_output = substruct('()',{1}, '.','jacobian','()',{':'}); + cdep(end).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); +end + +% warps +if opts.warps(1) + cdep(end+1) = cfg_dep; + cdep(end).sname = 'Deformation Field'; + cdep(end).src_output = substruct('()',{1}, '.','fordef','()',{':'}); + cdep(end).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); +end +if opts.warps(2) + cdep(end+1) = cfg_dep; + cdep(end).sname = 'Inverse Deformation Field'; + cdep(end).src_output = substruct('()',{1}, '.','invdef','()',{':'}); + cdep(end).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); +end + +% tissues +for i=1:numel(tissue) + if isfield(tissue(i),'native') && tissue(i).native(1) + cdep(end+1) = cfg_dep; + cdep(end).sname = sprintf('p%d Image',i); + cdep(end).src_output = substruct('.','tiss','()',{i},'.','p','()',{':'}); + cdep(end).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); + end + if isfield(tissue(i),'native') && tissue(i).native(2) + cdep(end+1) = cfg_dep; + cdep(end).sname = sprintf('rp%d rigid Image',i); + cdep(end).src_output = substruct('.','tiss','()',{i},'.','rp','()',{':'}); + cdep(end).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); + end + if isfield(tissue(i),'native') && tissue(i).native(3) + cdep(end+1) = cfg_dep; + cdep(end).sname = sprintf('rp%d affine Image',i); + cdep(end).src_output = substruct('.','tiss','()',{i},'.','rpa','()',{':'}); + cdep(end).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); + end + if tissue(i).warped(1) + cdep(end+1) = cfg_dep; + cdep(end).sname = sprintf('wp%d Image',i); + cdep(end).src_output = substruct('.','tiss','()',{i},'.','wp','()',{':'}); + cdep(end).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); + end + if tissue(i).warped(2) + cdep(end+1) = cfg_dep; + cdep(end).sname = sprintf('mwp%d Image',i); + cdep(end).src_output = substruct('.','tiss','()',{i},'.','mwp','()',{':'}); + cdep(end).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); + end + if tissue(i).warped(3) + cdep(end+1) = cfg_dep; + cdep(end).sname = sprintf('m0wp%d Image',i); + cdep(end).src_output = substruct('.','tiss','()',{i},'.','m0wp','()',{':'}); + cdep(end).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); + end +end + +if isfield(job.output,'rmat') && job.output.rmat + cdep(end+1) = cfg_dep; + cdep(end).sname = sprintf('Affine forward transformation',i); + cdep(end).src_output = substruct('.','tiss','()',{i},'.','ta','()',{':'}); + cdep(end).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); + + cdep(end+1) = cfg_dep; + cdep(end).sname = sprintf('Affine backward transformation',i); + cdep(end).src_output = substruct('.','tiss','()',{i},'.','ita','()',{':'}); + cdep(end).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); + + cdep(end+1) = cfg_dep; + cdep(end).sname = sprintf('Rigid forward transformation',i); + cdep(end).src_output = substruct('.','tiss','()',{i},'.','tr','()',{':'}); + cdep(end).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); + + cdep(end+1) = cfg_dep; + cdep(end).sname = sprintf('Rigid backward transformation',i); + cdep(end).src_output = substruct('.','tiss','()',{i},'.','itr','()',{':'}); + cdep(end).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); +end + +dep = cdep; +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_ornlm.c",".c","1543","65","/* ______________________________________________________________________ + * + * Christian Gaser, Robert Dahnke + * Structural Brain Mapping Group (https://neuro-jena.github.io) + * Departments of Neurology and Psychiatry + * Jena University Hospital + * ______________________________________________________________________ + * $Id$ + * + */ + +#include ""math.h"" +#include ""mex.h"" +#include + +extern void ornlm(float* ima, float* fima, int v, int f, float h, const int* dims); + +void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) +{ + +/* Declarations */ +float *ima, *fima; +float h; +int i, v, f, ndim, dims2[3]; +const mwSize *dims; + +/* check inputs */ +if (nrhs!=4) + mexErrMsgTxt(""4 inputs required.""); +else if (nlhs>2) + mexErrMsgTxt(""Too many output arguments.""); + +if (!mxIsSingle(prhs[0])) + mexErrMsgTxt(""First argument must be single.""); + +/* get input image */ +ima = (float*)mxGetPr(prhs[0]); + +ndim = mxGetNumberOfDimensions(prhs[0]); +if (ndim!=3) + mexErrMsgTxt(""Images does not have 3 dimensions.""); + +dims = mxGetDimensions(prhs[0]); + +/* get parameters */ +v = (int)(mxGetScalar(prhs[1])); +f = (int)(mxGetScalar(prhs[2])); +h = (float)(mxGetScalar(prhs[3])); + +/*Allocate memory and assign output pointer*/ +plhs[0] = mxCreateNumericArray(ndim, dims, mxSINGLE_CLASS, mxREAL); + +/*Get a pointer to the data space in our newly allocated memory*/ +fima = (float*)mxGetPr(plhs[0]); + +/* we need to convert dims to int */ +for(i = 0; i < 3; i++) dims2[i] = (int)dims[i]; + +ornlm(ima, fima, v, f, h, dims2); + +return; + +} + +","C" +"Neurology","ChristianGaser/cat12","cat_vol_pbtsimpleCS4.m",".m","40594","845","function [Ygmt,Ypp,Yp0] = cat_vol_pbtsimpleCS4(Yp0,vx_vol,opt) +%cat_vol_pbtsimple. Simple cortical thickness/position estimation. +% Estimation of voxel-based distances and projection-based thickness (PBT) +% and surface position based on a label map. Required isotropic input. +% +% After further optimisation the function becomes more complex again. +% However, the supersimple parameter can be used to switch off extra steps. +% Although, the values look quite similar difference in the surface are +% good detectable for small structures, in particular occipital sulci. +% +% [Ygmt, Ypp, Yp0] = cat_vol_pbtsimple( Yp0 , vx_vol, opt ) +% +% Ygmt .. GM thickness map +% Ypp .. percentage position map +% Yp0 .. tissue label map (1-CSF, 2-GM, 3-WM) +% vx_vol .. voxel-size (in mm, default=1) +% opt .. parameter structure +% +% .supersimple (0-no, 1-yes; default=1) +% WARNING: Activation will run only the basic routines +% without enhanced refinements! +% Although surface intensity and position values are not bad +% the number of self-intersections indicate further problems. +% In particular, small sulci are often affected by blurring. +% +% .levels (integer; default=8) +% Number of dual distance estimations to reduce sampling effects. +% With logarithmic improvement and good results between 2 and 16. +% +% .extendedrange (0-no, 1-yes; default=1) +% Uses also the PVE range to estimate the distance there. +% Important to avoid thickness underestimations. +% +% .correctoffeset (0-none, 1-fixed, 2-adaptive; default=2) +% Correction for the offset of boundaries beyond the paired concept. +% Only minor effects. +% +% .range (real value <=0.5, good between 0.2 and 0.4; default=0.3) +% Limitation of the offset of multiple thickness levels to avoid +% running into partial volume effects with thickness overestimation. +% +% .keepdetails (0-off, 1-sulci, 2-sulci+gyri; default=1) +% Enhance thin sulci (and gyri) to avoid blurring. +% Small global differences but important in occipial regions. +% Gyri enhancement is not optimal yet. +% +% .sharpening (0-no, 1-yes; default=1) +% Further optimization of the maps that can help to save small sulci. +% Sharpening the Ypp map to support more better resampling to lower +% resolution for the 0.5 layer adopted for slight changes that improves +% especially the position RMSE value by ~0.01 (ie, unclear if this is +% really better). +% +% .NBV (0-no, 1-yes; default=1) +% Additional, new blood vessel correction based on a WM region growing. +% +% .myelinCorrection (0-no, 0.25-light, 0.33-default, 0.5-strong, 1.0-maximum) +% Correction of myelinated GM areas that often result in severe GM +% unterestimations. The code is experimental code from the (pre) LAS +% correction that estimated the GM and WM thickness to extend thin GM +% areas if there is a lot of GM-WM PVE behind. +% This correction is not fully correct but the introduced error is +% expected to be smaller than before. +% +% See also cat_vol_pbt, cat_vol_createCS[23]. +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +%#ok<*UNRCH,*HIST> + + if ~exist('opt','var'), opt = struct(); end + + + % Default parameter settings with short impression for some Collins + % processing to roughly quantify the global effect. + % + % Values: + % thickness (mn±sd), surface intensity / position RMSE, SI=self-intersections + % + % Final tests with the following subjects are important : + % Collins, HR075, 4397, OASIS031 (WMHs), BUSS02 (Child), + % BWPT (Phantom), NISALS_UTR (PVEs), ADHD200NYC (LowQuality/Motion) + % + % Overall, it is important to eep an eye on + % * thickness values >> BWPT + % * unterestimation of very thick young cortices >> BUSS02 + % * local breaks/defects with thickness underestimation in older subjects with WMHs >> OASIS31, NISALS_UTR + % * or in case of motion artefact >> ADHD200NYC + % + def.supersimple = 0; % Refined WM distance based on CSF distance (myelination correction) + % This internal options is to turn of all feature functions. + % + def.levels = 4; % Number of dual distance estimates. + % Larger values are more accurate but need more time (log-change). + % Good values are between 1 and 4. + % + def.correctoffeset = 0; % correct for layer intensity + % (0-no, 1-yes-simple, 2-yes-complex; tiny improvement) + % + def.extendedrange = 1; % Estimate the distance from boundary A to boundary B + % also for voxels beyond B with a correction of the + % extra distance, to stabilize the values and avoid + % underestimations (0-no, 1-yes) + % + def.range = 0.3; % Default value for range extension (should be between 0.2-0.4) + % + def.keepdetails = 1; % enhance thin (occipital) sulci (and gyri) to avoid blurring + % (0-no, 1-yes (sulci); 2-yes(sulci+gyri) + % worse values but pretty important! + % + def.sharpening = 1; % sharpening the Ypp map to avoid blurring while + % resampling to lower resolution + % (0-no, 1-yes; reduce collisions) + % + def.NBVC = 1; % new blood vessel correction (RD202503) + % + def.eidist = 0; % distance metric (0-vbdist,1-eidist) + % vbdist is faster but do not support to consider other thissue boundaries + % eidist is much slower but support other tissue boudaries + % + def.myelinCorrection = .3; % correction for large cortical myelination artefacts that + % cause strong local underestimation that is similar to the + % extended LAS correction (cat_main_correctmyelination) (RD202503) + % + def.gyrusrecon = 1; % use PBT also to reconstruct gyri + %def.PVErefinement = 1; % NOT USE YET - uses cat_vol_PVEdist for thickness estimation + def.verb = 0; % be verbose + + opt = cat_io_checkinopt(opt,def); + + % just a fast option to switch of the extra functions + if opt.supersimple % avoid extras + opt.levels = 0; % number of dual distance measurements + opt.correctoffset = 0; % correct of dual displacements (in principle not required) + opt.extendedrange = 1; % use further PVE area + opt.keepdetails = 0; % important for small (occipital) sulci + opt.sharpening = 0; % reduce blurring of the Ypp map + opt.NBVC = 0; % new additional blood vessel correction (RD202503) + opt.myelinCorrection = 0; % myelination correction + end + + + if opt.extendedrange + % extend hard cuts, by a low value just to have a broader estimate + % - could be improved by a basic WMD and GMT estimate to assure a + % local minimum thickness related to the GMT distance + Yp0 = max(Yp0,(Yp0==1 & cat_vol_morph(Yp0==2,'d')) * 1.2); + end + + % close holes (important for SPM with unsufficient WM correction) +if 0 + Yp0 = max(Yp0, 3.0 * smooth3(cat_vol_morph(Yp0>2.75,'ldc',1.5)) ); + Yp0 = max(Yp0, 2.5 * smooth3(cat_vol_morph(Yp0>2.25,'ldc',1.5)) ); +end + + %% RD202503: new blood vessel correction + if opt.NBVC, Yp0 = NBVC(Yp0,vx_vol); end + if opt.myelinCorrection, Yp0 = myelincorrection(Yp0,vx_vol,opt); end + + c = clock; %#ok<*CLOCK> + + % estimation of distance measures ... + % - the fancy estimation does not show useful advantage + % - the eikonal distance (more correct) is much slower (one level eidist ~60s vs. 4 level vbdist ~15s) + % but support assymetrical mapping and not really worth it + %[Ycd0,Ywd0] = cat_vol_PVEdist(Yp0, opt.PVErefinement ); % this function was designed to optimize the GM-WM PVE but is not fully working yet + [Ycd0, Ywd0] = cat_vol_cwdist(Yp0,opt,vx_vol); + + + % raw thickness maps + Ygmtw0 = cat_vol_pbtp( round(Yp0) , Ywd0, Ycd0); Ygmtw0(Ygmtw0>1000) = 0; + Ygmtc0 = cat_vol_pbtp( 4-round(Yp0) , Ycd0, Ywd0); Ygmtc0(Ygmtc0>1000) = 0; + + + % correct reconstrution overestimation + % - important to keep small sulci open, eg. rh.BWPT central and CC sulcus + % - correct thinner areas stronger to improve reconstruction + if 1 % RD20250903: can maybe avoided ... intensity/position (Colins): 0.08/0.02 better with correction & 0.04 thicker + pbtsulccor = @(Ygmtx, Ycdx, Ywdx) max(0,Ygmtx - 0.125 .* (Ygmtx < (Ycdx + Ywdx))); + Ygmtw0 = pbtsulccor(Ygmtw0, Ycd0, Ywd0); + Ygmtc0 = pbtsulccor(Ygmtc0, Ycd0, Ywd0); + end + + + % minimum tickness map and cleanup (removal of extrem outliers and approximation) + % - not useful for Ygmtw0/Ygmtc0! + Ygmt0 = min(Ygmtw0,Ygmtc0); + Ygmt0 = cleanupPBT(Ygmt0, 1, 0); % filter limits has only minor effects + + + % update distance information + Ycd0 = min(Ygmt0,Ycd0); Ywd0 = min(Ygmt0,Ywd0); + + % this functions emphasize fine structurs, ie., to avoid blurring of small sulci + if opt.keepdetails + [Ywd0, Ycd0, Ygmt0] = keepdetails(Yp0, Ywd0, Ycd0, Ygmt0, vx_vol, ... + opt.range * opt.extendedrange, opt.keepdetails); + end + + if opt.verb, fprintf('\n Thickness estimation: %0.3fs\n', etime(clock,c)); c = clock; end %#ok<*DETIM> + + + %% CSF/WM blurring/reconstruction maps + % - define the blurred sulcal/CSF areas as the area of WM closing and + % 'overestimated' thickness (i.e., where the PBT thickness is sign. + % smaller as the simple sum of the WM and CSF distance) + % - blurred gyri/WM is defined vite versa + % - undefined values GM values are defined by neighbours + % - neutral regions are defined by CSF + % - next both areas are extend by intensity emphasized values + if opt.gyrusrecon + if opt.gyrusrecon == 1 + % complex version ... + + % define sulci/gyri as areas closed WM/CSF regions + Ygsr = cat_vol_morph( cat_vol_morph( Yp0<2.5 & cat_vol_morph(Yp0>2.5,'dc',10,vx_vol) & (Ygmtw0 < Ygmtc0) & (Ygmt0*1.05 <= Ycd0+Ywd0) , 'do',1.5), 'dd',1); % large sculci + Ygsr = max(Ygsr,cat_vol_morph( cat_vol_morph( Yp0<2.75 & cat_vol_morph(Yp0>2.75,'dc',3,vx_vol) & (Ygmtw0 < Ygmtc0) & (Ygmt0*1.05 <= Ycd0+Ywd0) , 'do',1), 'dd',2)); % small sulci + Ygsr = Ygsr*.5 + max(Yp0>2.5,cat_vol_morph(Yp0>=2.25 & ~Ygsr & cat_vol_morph(Yp0<2.25,'dc',10,vx_vol) & (Ygmtc0 < Ygmt0*1.1) & (Ygmt0*1.05 <= Ycd0+Ywd0),'do',1.5)); + % basic extension by distance function + [~,I] = cat_vbdist( single(Ygsr>.25),Yp0>1.1); Ygsr = single(Ygsr(I)); clear I; + + + % general (global) relation between sulci and gyri + % to avoid gyrus reconstruction in case of many sulci that comes with high risk of bridge defects + gsr = max(.7,min(1.3,nnz(Ygsr(:)==.5) ./ nnz(Ygsr(:)==1 & Yp0(:)<2.5))); + % in case of very thick cortices as in children (about 3 mm, e.g., BUSS## dataset) + % it is better to avoid the reconstruction whereas in case of low thickness + % (about 2 mm) the need is even higher! + % Besides thickness also high variance of thickness (> 0.75 mm) the risk + % of sulcul blurring increases stongly + mdGMT = median(Ygmt0(round(Yp0(:))==2)) * mean(vx_vol); + iqrGMT = iqr(Ygmt0(round(Yp0(:))==2)) * mean(vx_vol); + gsr = max(0.3, min(1.7, gsr .* max(0.5,min(2,1 + (mdGMT - 2.5))) .* max(.5,min(2,(iqrGMT-.5))))); + + % local refinement + Ygsr(Yp0<1.5) = max(0.55,min(0.80, 0.75 / gsr)); % extend blurred sulci + Ygsr(Yp0<1.5 & ~cat_vol_morph(Yp0<1.5,'do',2,vx_vol)) = max(0.50,min(0.75, 0.625 / gsr.^.5)); % pro sulci + Ygsr(cat_vol_morph(Yp0<1.5,'do',2,vx_vol)) = max(0.75,min(0.95, 0.875 / gsr.^.5)); % pro gyri + %Ygsr = 1 - max(1-Ygsr, max(0,min(1,2-Yp0)).^.75); % limited emphasization, as thin gyri often have lower GM probability ... + Ygsr = max(Ygsr, max(0,min(1,Yp0-2)).^.75); % emphasize WM + Ygsr = Yppsmooth(Ygsr,Ygmt0,vx_vol,[0,-1]); % outlier correction + Ygsr = max(0,min(1,cat_vol_smooth3X(Ygsr,2) * 2 - 1)); % final smoothing .^ (1.5 - Ygsr); ... too small cause edges and bridges (eg. Collins) + else + % simpler version based on the minimum thickness selector + + % local gyrus-sulcus definition + [~,Ygmt0I] = min(cat(4,Ygmtw0,Ygmtc0),[],4); + Ymsk1 = 1; % max(0,min(1,(Ycd0>1/vx_vol) .* Ycd0./max(eps,Ygmtw0) .* (5 ./ (Ygmt0*mean(vx_vol))) + (Yp0>2.5))); % use the uncorrected maps to outline the sulcus .. not working + Ymsk2 = max(0,cat_vol_smooth3X(Yp0-1,2)); % up-weight WM and down-weight CSF regions + Ygsr = max(0,min(1,cat_vol_smooth3X(Ygmt0I .* Ymsk1 .* Ymsk2 , 2 ) - 1)) .^ 1.25; % .^ x with x>1 to prefere sulci + + % general (global) relation between sulci and gyri + mdGMT = median(Ygmt0(round(Yp0(:))==2)) * mean(vx_vol); + iqrGMT = iqr(Ygmt0(round(Yp0(:))==2)) * mean(vx_vol); + gsr = max(0.5, min(1.7, max(0.5,min(2,1 + (mdGMT - 2.5))) .* max(.5,min(2,(iqrGMT-.5))))); + end + + % percentage blurred sulcal/gyral volume (regions that need reconstrution as evaluation parameter) + srecon = sum(Ygsr(:)<.25 & round(Yp0(:))==2 & (Ygmtw0(:) < Ygmt0(:)*1.1) & (Ygmt0(:)*1.05 <= Ycd0(:)+Ywd0(:)) ) / sum( round(Yp0(:))==2 ); + grecon = sum(Ygsr(:)>.75 & round(Yp0(:))==2 & (Ygmtc0(:) < Ygmt0(:)*1.1) & (Ygmt0(:)*1.05 <= Ycd0(:)+Ywd0(:)) ) / sum( round(Yp0(:))==2 ); + + % position maps + % Yppg - gyrus map with further weighting to avoid bridges + % Ypps - suclus map with two defintions based on the minimum thickness Ygmt0 and the WM driven thicknes Ygmtw0. + % The Ygmtw0 is better in gyrus reconstruction but also more noisy and prone to bridges + Yppg = min(1, max( Ygmt0 .* (Yp0>2.5) , max( Ycd0 .* Ygsr.^.1, (Yp0>1.5) .* (Ygmt0-Ywd0) .* Ygsr.^2)) ./ Ygmt0); + Ypps = 0.5 .* min(1, max( 0 , max(Yp0>2.5, (Yp0>1.5) .* max(eps,Ygmtw0-Ywd0) ./ max(eps,Ygmtw0) .* Ygsr ))) + ... + 0.5 .* min(1, max( 0 , max(Yp0>2.5, (Yp0>1.5) .* min(Ycd0,Ygmt0-Ywd0) ./ max(eps,Ygmt0)))); + % add the global weighting to avoid bridges + Yppg = Yppg .* Ypps.^max(0.05, min(.5, .1 * (gsr.^4))); + % final combination + Ypp = Yppg.*Ygsr + (1-Ygsr).*Ypps; + else + gsr = 0; srecon = 1; grecon = 0; + Ypp = 0.5 .* min(1, max( 0 , max(Yp0>2.5, (Yp0>1.5) .* max(eps,Ygmtw0-Ywd0) ./ max(eps,Ygmtw0)))) + ... + 0.5 .* min(1, max( 0 , max(Yp0>2.5, (Yp0>1.5) .* min(Ycd0,Ygmt0-Ywd0) ./ max(eps,Ygmt0)))); + end + + % cleanup of position map + % - a topology correction is not really useful as we might use different thresholds later (cost ~15 seconds) ! + Ypp(cat_vol_morph(Yp0>2.75,'l')) = 1; Ypp(Yp0<1.5) = 0; + Ypp = oneObject(Ypp,vx_vol); + Ypp = Yppsmooth(Ypp,Ygmt0,vx_vol,[0.5,-1]); % correction of strong outliers (eg. from mixing) + Ypp = max( -.1 , min( 1.1, Ypp + (Ypp>.95) .* max(0,Yp0 - 2.5) + (Ypp<.05) .* min(0,Yp0 - 1.5) )); % PVE for interpolation and deformation + + % final scaling + Ygmt = Ygmt0 * mean(vx_vol); + + % (*) EXTRA: magic sharpending function - enhancement of fine structures + % ##### possible to avoid this ? + if opt.sharpening, [Ypp, Ygmt] = sharpening(Ypp, Ygmt, vx_vol); end + + % evaluation + if opt.verb + fprintf(' PP preparation (gsr=%0.3f): %0.3fs\n', gsr, etime(clock,c)); c = clock; + fprintf(' Sulcus / gyrus reconstruction: %5.2f%% / %4.2f%%\n', srecon*100, grecon*100); + fprintf(' Median thickness + IQR: %5.2f ± %4.2f mm\n', ... + median( Ygmt( Ypp(:)>.4 & Ypp(:)<.6 )) , iqr( Ygmt( Ypp(:)>.3 & Ypp(:)<.7 ))); + x = 0:0.01:10; + % smooth gives an error here @Robert + %h = smooth( hist( Ygmt( Ypp(:)>.45 & Ypp(:)<.55 ) , x),2); h = h/sum(h); + try + hi = find(h==max(h),1); hil = find(h==max(h(100:hi-30)),1); hih = find(h==max(h(hi+30:end)),1); + fprintf(' Peak (x:y): %5.2f:%4.4f | %5.2f:%4.4f | %5.2f:%4.4f\n', x(hil), h(hil), x(hi), h(hi), x(hih), h(hih)); + end + end + + Yp0o = Yp0; + %% Update Yp0 + % Yp0=Yp0o; Yp0 = max(Yp0,(Ypp>.5) .* 2 + (max(0,min(1,0-Ywd0)))); Yp0 = min(Yp0,2*(Ypp>.5) + 1 + max(0,min(1,max(0,((Ygmt0 - Ywd0 + .75))).^4))); + Yp0=Yp0o; Yp0 = max(Yp0,(Ypp>.5) .* 2 + (max(0,cat_vol_smooth3X(Ypp,.5)*2-1)).^4); Yp0 = min(Yp0,2*(Ypp>.5) + 2 - max(0,1 - cat_vol_smooth3X(Ypp,.5)*.5).^64); + %ds('d2sm','',1,abs(Yp0fs-Ymfs),abs(Yp0e - Ymfs),150) + %ds('d2sm','',1,Yp0o/3,Yp0/3,140) + + +end +% ====================================================================== +function Ypp = Yppsmooth(Ypp,Ygmt,vx_vol,th) + if ~exist('th','var'), th = 0.1; end + if isscalar(th), th = repmat(th,1,2); end + + % filter in large areas + Yflt = .5; %abs(smooth3(Ypp)*2 - 1) .* max(0,min(1,Ygmt - median(Ygmt(Ypp(:)>0 & Ypp(:)<1))/2 )); + if th(1) >= 0 + Ypp = cat_vol_median3(Ypp, cat_vol_morph(Ypp>0 & Ypp<1,'d') , true(size(Ypp)), th(1)); + Ypp = cat_vol_smooth3X(Ypp,0.5); + Ypp = max(0,min(1, Ypp + .5 * (1-th(1))*(Ypp - smooth3(Ypp)) )); + end + %Ypp = Ypp.*(1-Yflt) + Yflt.*Yppm; + if th(2) >= 0 + [Yppr,resYp0] = cat_vol_resize(Ypp,'reduceV',vx_vol,1,32,'median'); + Yppr = cat_vol_median3(Yppr, cat_vol_morph(Yppr>0 & Yppr<1,'d') , true(size(Yppr)), th(2)); + Yppr = cat_vol_resize(Yppr,'dereduceV',resYp0); + Yppr = max(0,min(1, Yppr + .5 * (1-th(2))*(Yppr - smooth3(Yppr)) )); + Yppr = max(0,min(1,tan(Yppr - .5) + .5)); + Ypp = Ypp.*(1-Yflt) + Yflt.*Yppr; + Ypp = max(0,min(1, Ypp + .5 * (1-th(1))*(Ypp - smooth3(Ypp)) )); + end +end +% ====================================================================== +function Ygmtc = cleanupPBT(Ygmt,lim,lim2) +%cleanupPBT. Upper limit for thickness outliers. +% Remove higher outliers (eg. blood vessels & meninges). No filtering of +% low values as these also represent small sulci. +% +% Ygmtc = cleanupPBT(Ygmt,lim,lim2) +% +% lim1 .. main threshhold +% lim2 .. additional prefiltering +% + +% possible extention: need resolution to handle filter size better ! + + if ~exist('lim','var'), lim = .05; end + if ~exist('lim2','var'), lim2 = 1; end + + % basic approximation & filtering + Ygmta = cat_vol_approx(Ygmt,'rec'); + + % prelimitation to avoid more noisy data with stronger outliers + if lim2 > 0 + Ygmtc = cat_vol_approx(Ygmt .* ((Ygmt - Ygmta .* (Ygmt>0))<=lim & (Ygmt - Ygmta .* (Ygmt>0))<=lim*4 & Ygmt>0), 'rec'); + Ygmt = Ygmt .* (Ygmt>0 & abs( Ygmt - Ygmtc ) < 1); + Ygmta = cat_vol_smooth3X( Ygmta .* (Ygmt==0) + Ygmt , .5); + end + + % main limitation + if lim > 0 + % #### the masking looks more complicated then necessary >> test simplification + Ygmtc = cat_vol_approx(Ygmt .* ((Ygmt - Ygmta .* (Ygmt>0))<=lim & (Ygmt - Ygmta .* (Ygmt>0))<=lim*4 & Ygmt>0), 'rec'); + % #### maybe the filtering is here still a bit too strong >> .25 ? + Ygmtc = cat_vol_smooth3X( min(Ygmta,Ygmtc),.5); % better + else + Ygmtc = Ygmta; + end +end +% ====================================================================== +function Yp0 = oneObject(Yp0, vx_vol, n) +% oneObject. Remove addition objects for multiple threshold levels. + + if ~exist('n','var'), n = 10; end + + for i = 1:n + if max(Yp0(:))>1.5 % Yp0 with values from 1 to 3 + th = 1 + ((n - i) / n) * 2; + else % Ypp with values from 0 to 1 + th = 0 + ((n - i) / n) * 1; + end + + if th > 0.5 + 1.5*(max(Yp0(:))>1.5) + Yl = single(cat_vol_morph( Yp0 > th ,'l')); + else % additional opening + Yl = single(cat_vol_morph( Yp0 > th ,'ldo',(3 - th)/2,vx_vol)); + end + Yp0 = min(Yp0,th) + Yl .* max(0,Yp0-th); + end +end +% ====================================================================== +function Yp0 = NBVC(Yp0,vx_vol) +%% RD202503: new blood vessel correction +% In principle this is not really new and should be done by other functions before. +% However, it is so essential for PBT and not to difficult to include it here (too). +% First the save WM area is estimated and then extended by a region growing method +% that focus on lower intensities in the Yp0 label mapf for GM and CSF. + F = max(0.0,Yp0-1); F(Yp0<=1.1) = inf; + Ywm = cat_vol_morph(Yp0>2.5,'ldo',2,vx_vol) | cat_vol_morph(Yp0>2.75,'ldo',1); + [~,Yd] = cat_vol_downcut(single(Ywm), F,-0.001); Yd(isnan(Yd))=inf; clear Ywm; + Ymsk = Yd > 1000000 & Yp0>2; + + % Ymsk as regions that we want to correct + %[~,I] = cat_vbdist(single(~Ymsk),Yp0>1.5); Yp0(Ymsk) = Yp0(I(Ymsk)); + Yp0(Ymsk) = 2; + Ymsk = cat_vol_morph(Ymsk,'dd',1,vx_vol) & Yp0>1.5; + Yp0s = cat_vol_median3(Yp0,Ymsk); + Yp0(Ymsk) = Yp0s(Ymsk); + + % CSF enhancement (by WM distnace) for better estimation of asymmetry and suppression of artefact ? + %Yd(Ymsk) = 0; + %Yp0 = max( min(1.5,Yp0) , Yp0 - max(0,Yd/10000 .* (Ymsk)) ); +end +% ====================================================================== +function [Ypp, Ygmt] = sharpening(Ypp, Ygmt, vx_vol) +% Sharpening. Enhance edge that would be lost in smoothing/reduction. +% In case of downsample enhancement of values was helping to reduce loss +% of details in the downsampling process. +% +% [Ypp, Ygmt] = sharpening(Ypp, Ygmt, vx_vol) +% + + Ypp0 = Ypp; + + smoothfactor = .02; % basic weighing + smoothoffset = 1; % correction for light understimation in the smoothing process + modthickness = 2; % adaptation of the thickness map (region that are blurring should be thinner) + + % create a sharpend version of the Ypps that enphalize regions that were smoothed + Ypps = Ypp + smoothfactor*1*(Ypp - cat_vol_smooth3X(Ypp,1/mean(vx_vol)) + smoothoffset * 0.000) + ... + smoothfactor*2*(Ypp - cat_vol_smooth3X(Ypp,2/mean(vx_vol)) + smoothoffset * 0.002) + ... + smoothfactor*4*(Ypp - cat_vol_smooth3X(Ypp,4/mean(vx_vol)) + smoothoffset * 0.004); + + % final smoothing to prepare surface reconstruction that also correct for WM topology issues + spm_smooth(Ypps,Ypps,.5/mean(vx_vol)); + + % New version that only change mid-position values relevant for surface + % creation. Although this avoid the old binary-like better thickness + % cannot be expected + Ypp = min(Ypp,max(0.49,Ypps)); + Ypp = max(Ypp,min(0.51,Ypps)); + + % adopt thickness + Ymt = smooth3(Ypp - Ypp0) * modthickness; + Ygmt = Ygmt + Ymt; +end +% ====================================================================== +function [Ycd,Ywd] = cat_vol_PVEdist(Yp0,PVErefinement) +% function to estimate the raw distance maps + + if PVErefinement == 0 + % simple distance estimation with two levels to be robust also in case + % of the 5-cls AMAP segmentation with a subclass at 1.5 and 2.5 (although + % this is blurred in general by the interpolation) + Ycd = cat_vbdist( single(Yp0 < 1.5), Yp0 < 3 )/2 + ... + cat_vbdist( single(Yp0 <= 1.5), Yp0 < 3 )/2 - 0.5; + Ywd = cat_vbdist( single(Yp0 > 2.5), Yp0 > 1 )/2 + ... + cat_vbdist( single(Yp0 >= 2.5), Yp0 > 1 )/2 - 0.5; + elseif PVErefinement == 1 + % Ycci/Ywwi is correction for voxel behind the boundary to avoid + % overestimation by PBT mapping (using the maximum values) + Ycci = max(0,cat_vbdist( single(Yp0 < 2.5), Yp0 < 3 )/2 + ... + cat_vbdist( single(Yp0 <= 2.5), Yp0 < 3 )/2 - .5); + Ywwi = max(0,cat_vbdist( single(Yp0 > 1.5), Yp0 > 1 )/2 + ... + cat_vbdist( single(Yp0 >= 1.5), Yp0 > 1 )/2 - .5); + Ycd = (cat_vbdist( single(Yp0 < 1.5), Yp0 < 3 ) - Ycci)/2 + ... + (cat_vbdist( single(Yp0 <= 1.5), Yp0 < 3 ) - Ycci)/2 - .5; + Ywd = (cat_vbdist( single(Yp0 > 2.5), Yp0 > 1 ) - Ywwi)/2 + ... + (cat_vbdist( single(Yp0 >= 2.5), Yp0 > 1 ) - Ywwi)/2 - .5; + elseif PVErefinement == 3 + Ycci = max(0,cat_vbdist( single(Yp0 < 2.325), Yp0 < 3 )/2 + ... + cat_vbdist( single(Yp0 < 2.675), Yp0 < 3 )/2 - 1); + Ywwi = max(0,cat_vbdist( single(Yp0 > 1.325), Yp0 > 1 )/2 + ... + cat_vbdist( single(Yp0 > 1.675), Yp0 > 1 )/2 - 1); + Ycd = (cat_vbdist( single(Yp0 < 1.325), Yp0 < 3 ) - Ycci)/2 + ... + (cat_vbdist( single(Yp0 < 1.675), Yp0 < 3 ) - Ycci)/2 - 1; + Ywd = (cat_vbdist( single(Yp0 > 2.325), Yp0 > 1 ) - Ywwi)/2 + ... + (cat_vbdist( single(Yp0 > 2.675), Yp0 > 1 ) - Ywwi)/2 - 1; + + elseif PVErefinement == 2 + Ycd = cat_vbdist( single(Yp0 < 1.5), Yp0 < 2.5 ); + Ywd = cat_vbdist( single(Yp0 > 2.5), Yp0 > 1.5 ); + + else + % complex distance estimation with multiple levels (but not to close to + % the standard classes that are more prone to interpolation errors) + + %level = [0.25 0.75]; + level = [0.125 0.25 0.375 0.5 + [0.125 0.25 0.375]]; % in SPM no real improvent in Colins + + % distance maps for all levels + Ywda = zeros([size(Yp0),numel(level)],'single'); + Ycda = zeros([size(Yp0),numel(level)],'single'); + for li = 1:numel(level) + % raw distance measure + Ycda(:,:,:,li) = cat_vbdist( single(Yp0 < 1 + level(li)), Yp0 < 2.5); + Ywda(:,:,:,li) = cat_vbdist( single(Yp0 > 2 + level(li)), Yp0 > 1.5); + + % simple offset correction + % **** this could be maybe improved later as the level intensity + % offset is only a rough approximation of the real distance + % offest + % **** use/correct for negative values? + Ycda(:,:,:,li) = Ycda(:,:,:,li) + (0.5 - level(li)) .* (Yp0>1 & Yp0<3); + Ywda(:,:,:,li) = Ywda(:,:,:,li) + (0.5 - level(li)) .* (Yp0>1 & Yp0<3); + end + % simple average thickness + Ycd0 = single(cat_stat_nanmean(Ycda,4)); + Ywd0 = single(cat_stat_nanmean(Ywda,4)); + + % raw thickness maps that we use to select the best single distance maps + Ygmtw0 = cat_vol_pbtp( round(Yp0) , Ywd0, Ycd0); Ygmtw0(Ygmtw0>1000) = 0; + Ygmtc0 = cat_vol_pbtp( 4-round(Yp0) , Ycd0, Ywd0); Ygmtc0(Ygmtc0>1000) = 0; +% ***** add cleanupPBT of Ygmtw0 and Ygmtc0 ? + Ygmt0 = min(Ygmtw0,Ygmtc0); + Ygmt0 = cleanupPBT(Ygmt0); + Ycd0c = (Ygmt0 - Ywd0) .* (Yp0>1 & Yp0<3); + Ywd0c = (Ygmt0 - Ycd0) .* (Yp0>1 & Yp0<3); + + %% we assume a continuous thickness pattern without extrem values + mdgmt = median(Ygmt0(round(Yp0(:))==2)); + liqrgmt = prctile(Ygmt0(round(Yp0(:))==2),20) - mdgmt; % thinner values are expected (sulci) and ok + hiqrgmt = prctile(Ygmt0(round(Yp0(:))==2),60) - mdgmt; % larger values are more often outliers +% **** maybe the recon maps could be handy here? + + %% estimation of the deviation of the diance from the local expected value + Ywde = Ywd0 * 0; + for li = 1:numel(level) + % estimate thickness - avg. exp. thickness + % - pos. value means too thin, i.e., good in gyri bad in sulci + % - neg. value means too thick, i.e., + Ywdel = (Ycd0c + Ywda(:,:,:,li)) - Ygmt0; + Ywdel(Ywdel > 0 & Ywdel < liqrgmt) = max(0,Ywdel(Ywdel > 0 & Ywdel < liqrgmt) + liqrgmt); + Ywdel(Ywdel < 0 & Ywdel > hiqrgmt) = min(0,Ywdel(Ywdel < 0 & Ywdel > hiqrgmt) + hiqrgmt); + Ywde(:,:,:,li) = Ywdel; + end + + % estimate and correct for minimum error + Ywdem = min(Ywde,[],4); + for li = 1:numel(level) + Ywde(:,:,:,li) = cat_vol_smooth3X( Ywde(:,:,:,li) - Ywdem , 2 ); + end + clear Ywdem + + % include only good distance estimates + Ywd = Ywd0*0; Ywdn = Ywd; + for li = 1:numel(level) + Ywdn = Ywdn + Ywde(:,:,:,li); + Ywd = Ywd + Ywde(:,:,:,li) .* Ywda(:,:,:,li); + end + Ywd = Ywd ./ max(eps,Ywdn); + clear Ywde; + + + %% estimation of the deviation of the diance from the local expected value + Ycde = Ycd0 * 0; + for li = 1:numel(level) + Ycde(:,:,:,li) = abs( Ygmt0 - (Ywd0c + Ycda(:,:,:,li)) ); + Ycdel = (Ywd0c + Ycda(:,:,:,li)) - Ygmt0; + Ycdel(Ycdel > 0 & Ycdel < liqrgmt) = max(0,Ycdel(Ycdel > 0 & Ycdel < liqrgmt) + liqrgmt); + Ycdel(Ycdel < 0 & Ycdel > hiqrgmt) = min(0,Ycdel(Ycdel < 0 & Ycdel > hiqrgmt) + hiqrgmt); + Ycde(:,:,:,li) = Ycdel; + end + + % estimate the minimum error include only good distance estimates + Ycdem = min(Ycde,[],4); + for li = 1:numel(level) + Ycde(:,:,:,li) = cat_vol_smooth3X( Ycde(:,:,:,li) - Ycdem , 2 ); + end + clear Ycdem; + + Ycd = Ycd0*0; Ycdn = Ycd; + for li = 1:numel(level) + Ycdn = Ycdn + Ycde(:,:,:,li); + Ycd = Ycd + Ycde(:,:,:,li) .* Ycda(:,:,:,li); + end + clear Ycde; + Ycd = Ycd ./ max(eps,Ycdn); + + end + + % final correction for the voxel distance error (simplified half grid distance) + % .. thicky ... should be .5 but this results in worse results + % Ycd = max(0,Ycd - 1); + % Ywd = max(0,Ywd - 1); +end +% ====================================================================== +function [Ycd, Ywd] = cat_vol_cwdist(Yp0,opt,vx_vol) +%cat_vol_cwdist. Estimation of CSF and WM distance in a label map Yp0. +% +% [Ycd, Ywd] = cat_vol_cwdist(Yp0,opt) +% +% Ycd, Ywd .. CSF and WM distance maps +% opt .. parameter structure +% .levels .. number of dual distance measurements +% .extendedrange .. estimate values also beyond the boundary to improve +% thickness mapping +% .correctoffeset .. use generalized correction for the additional distance +% estimations, eg., for a more WM like value of 2.75 all +% distance values are assumed to be over +% (0 - none, 1 - default difference, 2 - estimated difference) +% .range .. limitation to avoid bias by interpolation overshoot +% + + % CSF and WM distance + Ycd = zeros(size(Yp0),'single'); + Ywd = zeros(size(Yp0),'single'); + + opt.extendedrange = opt.extendedrange * opt.range; + + % additional correction map for values behind tissue boundary, e.g., + % for the WMD we estimate the distance from the GM/CSF boundary to + % limit WMD values to the maximal thickness value + % same idea as below + YMM = cat_vol_morph(Yp0 > 2.5 + opt.extendedrange,'e',1) | isnan(Yp0); + YMC = cat_vol_morph(Yp0 < 1.5 - opt.extendedrange,'e',1) | isnan(Yp0); + + % estimation of the extend range to correct values beyond the other tissue boundary + if opt.extendedrange > 0 + Ycdlc = Ycd; Ycdhc = Ycd; + Ywdlc = Ywd; Ywdhc = Ywd; + hss = opt.levels; % number of opt.levels (as pairs) + for si = 1:hss + offset = max(0,min(opt.range, opt.range * si/(hss+1))); + + % CSF distance correction beyond WM boudary + if opt.eidist == 3 + % Eikonal-based Euclidean distance + F = double( max(0,min(1, 3 - Yp0)) ); + [~,Ycdlct] = cat_vol_eidist3(Yp0 < 2.5 - offset, F); Ycdlc = Ycdlc + 1/hss * max(0,Ycdlct - .5); + [~,Ycdhct] = cat_vol_eidist3(Yp0 < 2.5 + offset, F); Ycdhc = Ycdhc + 1/hss * max(0,Ycdhct - .5); + elseif opt.eidist == 2 + % Eikonal-based Euclidean distance + F = max(eps,min(1, 3 - Yp0 )); + YM = max(0,min(1,(3 - Yp0 - offset))); YM(YMM) = nan; Ycdlc = Ycdlc + 1/hss * max(0, cat_vol_eidist(YM,F,[1 1 1],1,1,0,0) - .5); + YM = max(0,min(1,(3 - Yp0 + offset))); YM(YMM) = nan; Ycdhc = Ycdhc + 1/hss * max(0, cat_vol_eidist(YM,F,[1 1 1],1,1,0,0) - .5); + else + % simple Euclidean distance + Ycdlc = Ycdlc + 1/hss * max(0,cat_vbdist(single(Yp0 < ( 2.5 - offset)), ~YMM ) - .5); + Ycdhc = Ycdhc + 1/hss * max(0,cat_vbdist(single(Yp0 < ( 2.5 + offset)), ~YMM ) - .5); + + end + + + % WM distance correction beyond CSF boudary + if opt.eidist == 3 + %% + F = double( max(0,min(1, Yp0 - 1)) ); + [~,Ywdlct] = cat_vol_eidist3(Yp0 > 1.5 - offset,F); Ycdlc = Ycdlc + 1/hss * max(0,Ywdlct - .5); + [~,Ywdhct] = cat_vol_eidist3(Yp0 > 1.5 + offset,F); Ywdhc = Ywdhc + 1/hss * max(0,Ywdhct - .5); + elseif opt.eidist == 2 + %% + F = max(eps,min(1, Yp0 - 1 )); + YM = max(0,min(1,(Yp0 - 1 - offset))); YM(YMC) = nan; Ywdlc = Ywdlc + 1/hss * max(0,cat_vol_eidist(YM,F,[1 1 1],1,1,0,0) - .5); + YM = max(0,min(1,(Yp0 - 1 + offset))); YM(YMC) = nan; Ywdhc = Ywdhc + 1/hss * max(0,cat_vol_eidist(YM,F,[1 1 1],1,1,0,0) - .5); + else + Ywdlc = Ywdlc + 1/hss * max(0,cat_vbdist(single(Yp0 > ( 1.5 - offset)), ~YMC) - .5); + Ywdhc = Ywdhc + 1/hss * max(0,cat_vbdist(single(Yp0 > ( 1.5 + offset)), ~YMC) - .5); + end + end + + Ywdlc(Ywdlc > 1000) = 0; Ywdhc(Ywdhc > 1000) = 0; + Ycdlc(Ycdlc > 1000) = 0; Ycdhc(Ycdhc > 1000) = 0; + + end + + + % multi-level distance estimation + hss = opt.levels; % number of opt.levels (as pairs) + for si = 1:hss + offset = max(0,min(opt.range, opt.range * si/(hss+1))); + + % CSF dist + if opt.eidist == 3 + F = max(0,min(1,((3 - Yp0)))); + [~,Ycdl] = cat_vol_eidist3(Yp0<1.5 - offset,double(F)); Ycdl = max(0, Ycdl - .5); + [~,Ycdh] = cat_vol_eidist3(Yp0<1.5 + offset,double(F)); Ycdh = max(0, Ycdh - .5); + elseif opt.eidist > 0 + F = max(eps,min(1,((3 - Yp0)))); + YM = max(0,min(1,(2 - Yp0 - offset))); YM(YMM) = nan; Ycdl = max(0, cat_vol_eidist(YM,F,[1 1 1],1,1,0,0) - .5); + YM = max(0,min(1,(2 - Yp0 + offset))); YM(YMM) = nan; Ycdh = max(0, cat_vol_eidist(YM,F,[1 1 1],1,1,0,0) - .5); + else + Ycdl = max(0,cat_vbdist(single(Yp0 < ( 1.5 - offset)), ~YMM ) -.5); Ycdl(Ycdl > 1000) = 0; + Ycdh = max(0,cat_vbdist(single(Yp0 < ( 1.5 + offset)), ~YMM ) -.5); Ycdh(Ycdh > 1000) = 0; + end + + if opt.extendedrange + Ycdl = Ycdl - Ycdlc; + Ycdh = Ycdh - Ycdhc; + end + + if opt.extendedrange + if opt.correctoffeset==2 + offsetc = offset/mean(vx_vol) + (cat_stat_nanmedian(Ycdl(Ycdl>0 & Ycdh>0) - Ycdh(Ycdl>0 & Ycdh>0)))/2; + else + offsetc = offset/mean(vx_vol); + end + Ycdl(Ycdl>0) = max(eps, Ycdl(Ycdl>0) - (.5 + offsetc) ); + Ycdh(Ycdh>0) = max(eps, Ycdh(Ycdh>0) + (.5 + offsetc) ); + end + + % mixing + Ycd = Ycd + .5/hss .* Ycdl + .5/hss .* Ycdh; + % idea was to could the boundaries different depending on the CSF distance + clear Ycdl Ycdh; + + + % WM distances + if opt.eidist == 3 + F = max(0,min(1,((Yp0-1 )))); + [~,Ywdl] = cat_vol_eidist3(Yp0>2.5 - offset,double(F)); + [~,Ywdh] = cat_vol_eidist3(Yp0>2.5 + offset,double(F)); + elseif opt.eidist > 0 + F = max(0,min(1,((Yp0-1 )))); + YM = max(0,min(1,(Yp0 - 2 - offset))); YM(YMM) = nan; Ywdl = max(0, cat_vol_eidist(YM,F,[1 1 1],1,1,0,0) -.5); + YM = max(0,min(1,(Yp0 - 2 + offset))); YM(YMM) = nan; Ywdh = max(0, cat_vol_eidist(YM,F,[1 1 1],1,1,0,0) -.5); + else + Ywdl = max(0,cat_vbdist(single(Yp0 > ( 2.5 - offset)), Yp0 > 1.5 - opt.extendedrange ) -.5); Ywdl(Ywdl > 1000) = 0; + Ywdh = max(0,cat_vbdist(single(Yp0 > ( 2.5 + offset)), Yp0 > 1.5 - opt.extendedrange ) -.5); Ywdh(Ywdh > 1000) = 0; + end + + if opt.extendedrange + Ywdl = Ywdl - Ywdlc; + Ywdh = Ywdh - Ywdhc; + end + if opt.correctoffeset + if opt.correctoffeset==2 + offsetc = offset + (cat_stat_nanmedian(Ywdl(Ywdl>0 & Ywdh>0) - Ywdh(Ywdl>0 & Ywdh>0)))/2; + else + offsetc = offset; + end + Ywdl(Ywdl>0) = max(eps, Ywdl(Ywdl>0) + (.5 + offsetc) ); + Ywdh(Ywdh>0) = max(eps, Ywdh(Ywdh>0) - (.5 + offsetc) ); + end + + % mixing + Ywd = Ywd + .5/hss .* Ywdl + .5/hss .* Ywdh; + end + + +end +% ====================================================================== +function [Ywd, Ycd, Ygmt] = keepdetails(Yp0, Ywd, Ycd, Ygmt, vx_vol, extendedrange,level) +% Although distances and thickness are quite good, PBT slightly tend to +% over-estimate the thickness in sulcal regions without CSF as the middle +% voxel is counted for both sides (simplified). Moreover, initial surface +% are partially created just on the original internal resolution (~1 mm), +% what result in blurring of small sucli. To keep these structures, we +% optimize regions where blurring/closing is happening by making them a +% bit thinner and correcting the CSF distance (keepdetails>0). The dual +% operation (of avoiding of blurring small gyri) can also be applied but +% is expected to have less effects as these structures are already quite +% save by the WM (keepdetails>1). +% +% 1 -1.0*ppth ... 0 2.5235 ± 0.5959 mm 0.0686 / 0.0605 0.74% (9.16 mm²) 6.0 / 1.0 / 0.42% **** +% 3 -0.8*ppth ... 0 2.5403 ± 0.5872 mm 0.0682 / 0.0608 0.81% (10.01 mm²) 6.0 / 1.0 / 0.42% **** +% 2 -0.5*ppth ... 0 2.5671 ± 0.5727 mm 0.0677 / 0.0621 0.85% (10.49 mm²) 10.0 / 2.0 / 0.46% +% 2 -0.5*ppth ... .1 2.5515 ± 0.5863 mm 0.0690 / 0.0620 0.80% (9.87 mm²) 6.0 / 1.0 / 0.42% + + Ygmto = Ygmt; + + % estimate current percentage map (same as bellow) to identify + % and correct problematic areas + YM = Yp0 > 1.5 - extendedrange & ... + Yp0 < 2.5 + extendedrange & ... + Ygmt > eps; + Ycdc = Ycd; Ycdc(YM) = min(Ycd(YM), Ygmt(YM) - Ywd(YM)); + Ypp = zeros(size(Yp0),'single'); Ypp(Yp0 >= 2.5 + extendedrange) = 1; + Ypp(YM) = Ycdc(YM) ./ (Ygmt(YM) + eps); + + % reduce thickness and CSF distance if this results in smoothing + % do this only in thin regions + for ppth = 1:-.1:0.1 + Yblurredsulci = Ypp=ppth,'c',1) & Ygmt < median(Ygmt(:))/2; + Yblurredsulci = cat_vol_smooth3X(Yblurredsulci, 2); + Ygmt = max( ... + max(0,Ygmto - 1/mean(vx_vol)), ... + Ygmt .* max(0.5,1 - 0.8 .* ppth*Yblurredsulci) ); + Ycd(Yblurredsulci>0) = max(0,min(Ycd(Yblurredsulci>0), Ygmt(Yblurredsulci>0) - Ywd(Yblurredsulci>0))); + end + + % reduce thickness and WM distance if this results in smoothing + % ... slow, worse values, + % - helpful to remove blue outliers? + if level == 2 + for ppth = 0.9:-0.1:0.1 + Yblurredgyri = Ypp>=ppth & cat_vol_morph(Ypp median(Ygmt(:))/2; + Yblurredgyri = cat_vol_smooth3X(Yblurredgyri, 2); + Ygmt = max( ... + min(0,Ygmto + 1/mean(vx_vol)), ... + Ygmt .* min(1.5,1 + .1 .* ppth*Yblurredgyri)); + Ywd(Yblurredgyri>0) = max(0,min(Ywd(Yblurredgyri>0), Ygmt(Yblurredgyri>0) + Ycd(Yblurredgyri>0))); + end + end +end +% ====================================================================== +function Yp0 = myelincorrection(Yp0,vx_vol,opt) + if opt.myelinCorrection > 0 + % quick estimation of the cortical thickness + opt.verb = 0; + opt.levels = 1; + opt.eidist = 0; + + [Ycd, Ywd] = cat_vol_cwdist(Yp0, opt, vx_vol); + + % projection-based thickness mapping + Ygmt0 = cat_vol_pbtp( round(Yp0) , Ywd, Ycd); + Ygmt0 = cat_vol_approx(Ygmt0); + + % reestimation of the CSF distance + Ypp = min(1,min(Ygmt0,Ycd) ./ max(eps,Ygmt0)); Ypp(Yp0>2.5 & Ypp==0) = 1; + Ycdc2 = cat_vbdist( single( max(Yp0<=1, 1 - Ycd - Ypp) ), true(size(Ycd)) ); + Ycdc2(Ycdc2 > 6 / mean(vx_vol)) = 0; + + % estimate the full tissue thickness (we needed the GM thickness and WM to reconstruct the sulcus) + Ybmt = cat_vol_pbtp( min(3,4 - min(2,Yp0)), Ycdc2, Ycdc2*inf); + Ybmt = cat_vol_approx(Ybmt); + + % estimate correction area + medgmt = median(Ygmt0(:)); + try iqrgmt = iqr(Ygmt0(:)); catch, iqrgmt = std(Ygmt0(:)); end + YenoughWM = Ycdc2 < Ybmt - 1.5; + YthinnerGM = max(0,medgmt - 1.5*iqrgmt - Ygmt0); + Yclose2CSF = Ycdc2>0 & Ycdc2<(medgmt - 1.5*iqrgmt); + Ygmwmpve = cat_vol_morph(Yp0>2 & Yp0<2.9,'do',1); % | smooth3(Yp0>2 & Yp0<2.9)>.7); + Ycor = YenoughWM & YthinnerGM & Yclose2CSF & Ygmwmpve; + clear YenoughWM YthinnerGM Yclose2CSF Ygmwmpve; + + Yp0 = max(min(Yp0,2),max(Yp0>=2.95,Yp0 - smooth3( Ycor ) * opt.myelinCorrection)); + clear Ycdc2 Ybmt Ycor; + end +end","MATLAB" +"Neurology","ChristianGaser/cat12","vollib.c",".c","24914","902","/* ______________________________________________________________________ + * + * Christian Gaser, Robert Dahnke + * Structural Brain Mapping Group (https://neuro-jena.github.io) + * Departments of Neurology and Psychiatry + * Jena University Hospital + * ______________________________________________________________________ + * $Id$ + * + * This code is a substantially modified version of spm_conv_vol.c + * from J. Ashburner + */ + +#include +#include +#include +#include +#include + +#define RINT(A) floor((A)+0.5) +#ifndef isfinite +#define isfinite(x) ((x) * (x) >= 0.) /* check for NaNs */ +#endif + +static void +convxy(double out[], int xdim, int ydim, double filtx[], double filty[], int fxdim, int fydim, int xoff, int yoff, double buff[]) +{ + int x,y,k; + for(y=0; y= xdim) ? x-xdim-xoff+1 : 0); + fend = ((x-(xoff+fxdim) < 0) ? x-xoff+1 : fxdim); + + for(k=fstart; k= ydim) ? y-ydim-yoff+1 : 0); + fend = ((y-(yoff+fydim) < 0) ? y-yoff+1 : fydim); + + for(k=fstart; k= xdim) ? x-xdim-xoff+1 : 0); + fend = ((x-(xoff+fxdim) < 0) ? x-xoff+1 : fxdim); + + for(k=fstart; k= ydim) ? y-ydim-yoff+1 : 0); + fend = ((y-(yoff+fydim) < 0) ? y-yoff+1 : fydim); + + for(k=fstart; kxdim) ? ydim : xdim)); + sortedv = (double **)malloc(sizeof(double *)*fzdim); + + if((tmp == NULL) || (buff == NULL) || (sortedv == NULL)) { + printf(""Memory allocation error\n""); + exit(EXIT_FAILURE); + } + + startz = ((fzdim+zoff-1<0) ? fzdim+zoff-1 : 0); + endz = zdim+fzdim+zoff-1; + + for (z=startz; z= 0 && z=0 && z-fzdim-zoff+1= zdim) ? z-zdim+1 : 0); + fend = ((z-fzdim < 0) ? z+1 : fzdim); + + for(k=0; kxdim) ? ydim : xdim)); + sortedv = (float **)malloc(sizeof(float *)*fzdim); + + if((tmp == NULL) || (buff == NULL) || (sortedv == NULL)) { + printf(""Memory allocation error\n""); + exit(EXIT_FAILURE); + } + + startz = ((fzdim+zoff-1<0) ? fzdim+zoff-1 : 0); + endz = zdim+fzdim+zoff-1; + + for (z=startz; z= 0 && z=0 && z-fzdim-zoff+1= zdim) ? z-zdim+1 : 0); + fend = ((z-fzdim < 0) ? z+1 : fzdim); + + for(k=0; kxdim) ? ydim : xdim)); + sortedv = (double **)malloc(sizeof(double *)*fzdim); + + if((tmp == NULL) || (buff == NULL) || (sortedv == NULL)) { + printf(""Memory allocation error\n""); + exit(EXIT_FAILURE); + } + + startz = ((fzdim+zoff-1<0) ? fzdim+zoff-1 : 0); + endz = zdim+fzdim+zoff-1; + + for (z=startz; z= 0 && z=0 && z-fzdim-zoff+1= zdim) ? z-zdim+1 : 0); + fend = ((z-fzdim < 0) ? z+1 : fzdim); + + for(k=0; k255.0) tmp2 = 255.0; + obuf[xy] = (unsigned char)RINT(tmp2); + } + } + else + for(xy=0; xyxdim) ? ydim : xdim)); + sortedv = (double **)malloc(sizeof(double *)*fzdim); + + if((tmp == NULL) || (buff == NULL) || (sortedv == NULL)) { + printf(""Memory allocation error\n""); + exit(EXIT_FAILURE); + } + + startz = ((fzdim+zoff-1<0) ? fzdim+zoff-1 : 0); + endz = zdim+fzdim+zoff-1; + + for (z=startz; z= 0 && z=0 && z-fzdim-zoff+1= zdim) ? z-zdim+1 : 0); + fend = ((z-fzdim < 0) ? z+1 : fzdim); + + for(k=0; k32767.0) tmp2 = 32767.0; + obuf[xy] = (signed short)RINT(tmp2); + } + } + else + for(xy=0; xyxdim) ? ydim : xdim)); + sortedv = (double **)malloc(sizeof(double *)*fzdim); + + if((tmp == NULL) || (buff == NULL) || (sortedv == NULL)) { + printf(""Memory allocation error\n""); + exit(EXIT_FAILURE); + } + + startz = ((fzdim+zoff-1<0) ? fzdim+zoff-1 : 0); + endz = zdim+fzdim+zoff-1; + + for (z=startz; z= 0 && z=0 && z-fzdim-zoff+1= zdim) ? z-zdim+1 : 0); + fend = ((z-fzdim < 0) ? z+1 : fzdim); + + for(k=0; k2147483647.0) tmp2 = 2147483647.0; + obuf[xy] = (signed int)RINT(tmp2); + } + } + else + for(xy=0; xyth); + + for (i=0;i=9); + } +} + + +void +morph_dilate_uint8(unsigned char *vol, int dims[3], int niter, int th) +{ + double filt[3]={1,1,1}; + int i,x,y,z,j,band,dims2[3]; + unsigned char *buffer; + + /* add band with zeros to image to avoid clipping */ + band = niter; + band = 0; + for (i=0;i<3;i++) dims2[i] = dims[i] + 2*band; + + buffer = (unsigned char *)malloc(sizeof(unsigned char)*dims2[0]*dims2[1]*dims2[2]); + + if(buffer == NULL) { + printf(""Memory allocation error\n""); + exit(EXIT_FAILURE); + } + + memset(buffer,0,sizeof(unsigned char)*dims2[0]*dims2[1]*dims2[2]); + + /* threshold input */ + for (z=0;zth); + + for (i=0;i0); + } + + /* return image */ + for (z=0;z th); + + morph_dilate_uint8(buffer, dims, niter, 0); + morph_erode_uint8(buffer, dims, niter, 0); + + for (i=0;i th); + + morph_erode_uint8(buffer, dims, niter, 0); + morph_dilate_uint8(buffer, dims, niter, 0); + + for (i=0;i dim_in[i]) samp[i] = ceil((double)dim_out[i]/(double)dim_in[i]); + else samp[i] = 1.0/(ceil((double)dim_in[i]/(double)dim_out[i])); + } + + for (z=0; z=0 && zi=0 && yi=0 && xi dim_in[i]) samp[i] = ceil((float)dim_out[i]/(float)dim_in[i]); + else samp[i] = 1.0/(ceil((float)dim_in[i]/(float)dim_out[i])); + } + + for (z=0; z=0 && zi=0 && yi=0 && xi 0 */ + if(sum_mask>0) { + convxyz_double(mask,x,y,z,((2*xyz[0])+1),((2*xyz[1])+1),((2*xyz[2])+1),-xyz[0],-xyz[1],-xyz[2],mask,dims); + for(i=0; i0) vol[i] /= (double)mask[i]; + else vol[i] = 0.0; + } + } + free(mask); + free(mask2); + } + + free(x); + free(y); + free(z); + +} + +void +smooth_float(float *vol, int dims[3], float separations[3], float s0[3], int use_mask) +{ + int i; + float xsum, ysum, zsum; + float *x, *y, *z, s[3]; + int xyz[3], nvol, sum_mask; + float *mask; + unsigned char *mask2; + + nvol = dims[0]*dims[1]*dims[2]; + + for(i=0; i<3; i++) { + s[i] = s0[i]/separations[i]; + if(s[i] < 1.0) s[i] = 1.0; + s[i] /= sqrt(8.0*log(2.0)); + xyz[i] = (int) RINT(6.0*s[i]); + } + + x = (float *) malloc(sizeof(float)*((2*xyz[0])+1)); + y = (float *) malloc(sizeof(float)*((2*xyz[1])+1)); + z = (float *) malloc(sizeof(float)*((2*xyz[2])+1)); + + /* build mask for masked smoothing */ + if(use_mask) { + mask = (float *) malloc(sizeof(float)*nvol); + mask2 = (unsigned char *) malloc(sizeof(unsigned char)*nvol); + sum_mask = 0; + for(i=0; i 0 */ + if(sum_mask>0) { + convxyz_float(mask,x,y,z,((2*xyz[0])+1),((2*xyz[1])+1),((2*xyz[2])+1),-xyz[0],-xyz[1],-xyz[2],mask,dims); + for(i=0; i0) vol[i] /= (float)mask[i]; + else vol[i] = 0.0; + } + } + free(mask); + free(mask2); + } + + free(x); + free(y); + free(z); + +} + +void +smooth_subsample_double(double *vol, int dims[3], double separations[3], double s[3], int use_mask, int samp) +{ + int i, nvol_samp, nvol; + int dims_samp[3]; + double *vol_samp, separations_samp[3]; + + /* define grid dimensions */ + for(i=0; i<3; i++) dims_samp[i] = (int) ceil((dims[i]-1)/((double) samp))+1; + for(i=0; i<3; i++) separations_samp[i] = separations[i]*((double)dims[i]/(double)dims_samp[i]); + + nvol = dims[0]*dims[1]*dims[2]; + nvol_samp = dims_samp[0]*dims_samp[1]*dims_samp[2]; + vol_samp = (double *)malloc(sizeof(double)*nvol_samp); + + subsample_double(vol, vol_samp, dims, dims_samp); + smooth_double(vol_samp, dims_samp, separations_samp, s, use_mask); + subsample_double(vol_samp, vol, dims_samp, dims); + + free(vol_samp); +} + +void +smooth_subsample_float(float *vol, int dims[3], float separations[3], float s[3], int use_mask, int samp) +{ + int i, nvol_samp, nvol; + int dims_samp[3]; + float *vol_samp; + float separations_samp[3]; + + /* define grid dimensions */ + for(i=0; i<3; i++) dims_samp[i] = (int) ceil((dims[i]-1)/((float) samp))+1; + for(i=0; i<3; i++) separations_samp[i] = separations[i]*((float)dims[i]/(float)dims_samp[i]); + + nvol = dims[0]*dims[1]*dims[2]; + nvol_samp = dims_samp[0]*dims_samp[1]*dims_samp[2]; + vol_samp = (float *)malloc(sizeof(float)*nvol_samp); + + subsample_float(vol, vol_samp, dims, dims_samp); + smooth_float(vol_samp, dims_samp, separations_samp, s, use_mask); + subsample_float(vol_samp, vol, dims_samp, dims); + + free(vol_samp); +} +","C" +"Neurology","ChristianGaser/cat12","cat_vol_laplace3.c",".c","5597","160","/* laplace calculation + * ________________________________________________________________________ + * Filter SEG within the intensity range of low and high until the changes + * are below TH. + * + * L = cat_vol_laplace3(SEG,low,high,TH) + * + * SEG = 3d sinlge input matrix + * low = low boundary threshold + * high = high boundary threshold + * TH = threshold to control the number of iterations + * maximum change of an element after iteration + * + * Example: + * A = zeros(50,50,3,'single'); A(10:end-9,10:end-9,2)=0.5; + * A(20:end-19,20:end-19,2)=1; + * C = cat_vol_laplace3(A,0,1,0.001); ds('d2smns','',1,A,C,2); + * ______________________________________________________________________ + * + * Christian Gaser, Robert Dahnke + * Structural Brain Mapping Group (https://neuro-jena.github.io) + * Departments of Neurology and Psychiatry + * Jena University Hospital + * ______________________________________________________________________ + * $Id$ + */ + +#include ""mex.h"" +#include ""math.h"" +/* #include ""matrix.h"" */ + +#ifdef _MSC_VER + #define FINFINITY (FLT_MAX+FLT_MAX); + static const unsigned long __nan[2] = {0xffffffff, 0x7fffffff}; + #define FNAN (*(const float *) __nan) +#else + #define FINFINITY 1.0f/0.0f; + #define FNAN 0.0f/0.0f +#endif + +/* estimate x,y,z position of index i in an array size sx,sxy=sx*sy... */ +void ind2sub(int i,int *x,int *y, int *z, int sxy, int sy) { + *z = (int)floor( (double)i / (double)sxy ) +1; + i = i % (sxy); + *y = (int)floor( (double)i / (double)sy ) +1; + *x = i % sy + 1; +} + +float abs2(float n) { if (n<0) return -n; else return n; } + +/* main function */ +void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) +{ + if (nrhs<4) mexErrMsgTxt(""ERROR:laplace3: not enough input elements\n""); + if (nrhs>5) mexErrMsgTxt(""ERROR:laplace3: too many input elements\n""); + if (nlhs<1) mexErrMsgTxt(""ERROR:laplace3: not enough output elements\n""); + if (nlhs>1) mexErrMsgTxt(""ERROR:laplace3: too many output elements\n""); + if (mxIsSingle(prhs[0])==0) mexErrMsgTxt(""ERROR:laplace3: first input must be an 3d single matrix\n""); + if (nrhs==5 && mxIsDouble(prhs[4])==0) mexErrMsgTxt(""ERROR:laplace3: 5th input (voxelsize) must be a double matrix\n""); + if (nrhs==5 && mxGetNumberOfElements(prhs[4])!=3) mexErrMsgTxt(""ERROR:laplace3: 5th input (voxelsize) must have 3 Elements""); + + /* main information about input data (size, dimensions, ...) */ + const mwSize *sL = mxGetDimensions(prhs[0]); + const int dL = mxGetNumberOfDimensions(prhs[0]); + const int nL = mxGetNumberOfElements(prhs[0]); + const int x = (int)sL[0]; + const int y = (int)sL[1]; + const int xy = x*y; + + /* input data */ + float*SEG = (float *)mxGetPr(prhs[0]); + float LB = (float) mxGetScalar(prhs[1]); + float HB = (float) mxGetScalar(prhs[2]); + float TH = (float) mxGetScalar(prhs[3]); if ( TH>=0.5 || TH<0.0001 ) mexErrMsgTxt(""ERROR:laplace3: threshhold must be >0.0001 and smaller than 0.5\n""); + const mwSize sS[2] = {1,3}; + mxArray *SS = mxCreateNumericArray(2,sS,mxDOUBLE_CLASS,mxREAL); + double*S = mxGetPr(SS); + if (nrhs<3) {S[0]=1.0; S[1]=1.0; S[2]=1.0;} else {S = mxGetPr(prhs[2]);} + + + /* indices of the neighbor Ni (index distance) and euclidean distance NW */ + const int sN = 6; + const int NI[6] = { -1, 1, -x, x, -xy, xy}; + + /* output data */ + mxArray *hlps[2]; + plhs[0] = mxCreateNumericArray(dL,sL,mxSINGLE_CLASS,mxREAL); + hlps[0] = mxCreateNumericArray(dL,sL,mxSINGLE_CLASS,mxREAL); + hlps[1] = mxCreateLogicalArray(dL,sL); + + float *L1 = (float *)mxGetPr(plhs[0]); + float *L2 = (float *)mxGetPr(hlps[0]); + bool *LN = (bool *)mxGetPr(hlps[1]); + + + /* intitialisiation */ + for (int i=0;iHB ) L1[i]=1.0; else L1[i] = SEG[i]; } /*(SEG[i]-LB) / BD;} */ + L2[i] = L1[i]; + if ( (SEG[i]>LB) && (SEG[i] TH ) + { + maxdiffi=0; + for (int i=0;iLB && L1[i]=nL) || (abs(nu-u)>1) || (abs(nv-v)>1) || (abs(nw-w)>1) )==false && SEG[ni]>=LB && SEG[ni]<=HB) + {L2[i] = L2[i] + L1[ni]; Nn++;} + } + L2[i] /= Nn; + diff = abs2( L1[i] - L2[i] ); /*printf(""%f %f %f\n"",L1[i],L2[i],diff); */ + if ( diff>(TH/10.0) ) { + for (int n=0;n=nL) || (abs(nu-u)>1) || (abs(nv-v)>1) || (abs(nw-w)>1) )==false && SEG[ni]>LB && SEG[ni]13, job.data(13:end) = []; end + + + % read volume + V = spm_vol(char(job.data)); + + + % get caxis + if ~isfield(job,'caxis') + mni=nan(1,numel(V)); mxi=mni; + for i=2:numel(V) + [mni(i),mxi(i)] = mn_mx_val(V(i)); + end + mn = cat_stat_nanstat1d(mni,'nanmin'); + mx = cat_stat_nanstat1d(mxi,'nanmax'); + if mn < 0 + mn = min([-mn mx]); + mx = mn; + mn = -mn; + end + job.caxis = [mn;mx]; % spm_input('Minimum/Maximum','+1','e',[mn mx],2); + end + + job.colormap = 'lines'; + if ~isfield(job,'colormap') + job.colormapc = spm_input('Colormap',1,'e','jet'); + else + if ischar(job.colormap) + job.colormapc = eval(sprintf('%s(%d)',job.colormap,diff(job.caxis(:)))); + end + end + % add background in colormap (end of colormap!) + if any(job.colormapc(end,1:3)~=0) + job.colormapc = [job.colormapc; 0 0 0]; + end + job.colormapc = max(0,min(1,job.colormapc + 0.2*(rand(size(job.colormapc))-0.5))); + mask = std(job.colormapc,1,2)<0.2; + job.colormapc(mask,:) = max(0,min(1,job.colormapc(mask,:) + 0.5*(rand(sum(mask==1),3)-0.5))); + + + % get transparency + if ~isfield(job,'prop') + job.prop = 0.2; % spm_input('Overlay transparecy (0..1)','+1','e',0.2,1); + end + + + %% + spm_atlas('list','installed','-refresh'); + if size(job.data,1)<=2 + spm_image('init',V(1).fname); + spm_orthviews('AddContext',1); + else + spm_check_registration(repmat(V(1).fname,numel(V)-1,1)); + end + + fprintf(sprintf('%s',repmat('\b',1,73*2))); + % remove SPM image/orthviews cmd-line link + for i=2:numel(V) + fprintf(sprintf('%s',repmat('\b',1,numel(sprintf('Display %s,1x',V(1).fname))))); % only the first anatomical image + end + + % new banner + spm('FnBanner',mfilename); + % all files + if numel(V)>2 + files = sprintf('''%s''',job.data{1}); + for i=2:numel(V); files = sprintf('%s;''%s''',files,job.data{i}); end + dispall = [' (' spm_file('all','link',... + sprintf('cat_vol_display_label(struct(''data'',{{%s}},''colormap'',''%s''))', ... + files,job.colormap)) ') ']; + end + + global st; + % add colormaps + for i=2:numel(V) + % print new label based cmd-line link + if i==2, fprintf('Display '); + elseif i==3, fprintf('%s',dispall); + else fprintf(' '); + end + + fprintf('%s\n',spm_file(V(i).fname,'link',... + sprintf('cat_vol_display_label(struct(''data'',{{''%s'';''%s''}},''colormap'',''%s''))', ... + job.data{1},job.data{i},job.colormap))); + + if exist('mni','var') + spm_orthviews('addtruecolourimage',i-1,V(i).fname,... + job.colormapc,job.prop,mni(i),mxi(i)); + else + spm_orthviews('addtruecolourimage',i-1,V(i).fname,... + job.colormapc,job.prop,job.caxis(2),job.caxis(1)); + end + vx = sqrt(sum(V(i).mat(1:3,1:3).^2)); + spm_orthviews('resolution',min(vx(1:2))); + spm_orthviews('redraw'); + + end + + % only one label for all maps :/ + if size(job.data,1)<=2 + [pp,dsp] = fileparts(V(i).fname); + if ~exist(fullfile(spm('dir'),'atlas',['cat12_' dsp '.nii'])) + try + cat_install_atlases + spm_atlas('Load',['cat12_' dsp]); + catch + error('Error while installing atlases into %s.\nPlease check writing permissions.',fullfile(spm('dir'),'atlas')); + end + else + dsp = spm_atlas('Load',['cat12_' dsp]); + end + for ii=1:numel(st.vols) + if ~isempty(st.vols{ii}) + st.vols{ii}.display = {dsp}; + end + end + spm_ov_display('redraw'); + else + for i=2:numel(V) + [pp,dsp] = fileparts(V(i).fname); + spm_orthviews('Caption',i-1,{dsp},'FontSize',12,'FontWeight','Bold'); + end + + end +end + +%_______________________________________________________________________ +function [mn,mx] = mn_mx_val(vol) + mn = Inf; + mx = -Inf; + for i=1:vol.dim(3), + tmp = spm_slice_vol(vol,spm_matrix([0 0 i]),vol.dim(1:2),0); + imx = max(tmp(find(isfinite(tmp)))); + if ~isempty(imx),mx = max(mx,imx);end + imn = min(tmp(find(isfinite(tmp)))); + if ~isempty(imn),mn = min(mn,imn);end + end; +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_check.m",".m","6392","181","function varargout = cat_check(action,varargin) +% Check input files +% ______________________________________________________________________ +% Blabla +% +% [INtype,F,V,T] = cat_check('checkinfiles',IN); +% OUT = cat_check('checkinfiles',INtype,F,V,T); +% res = cat_check('checkinopt',opt,def,cond); +% +% INtype = [1=F(file) | 2=V(hdr) | 3=V(hdr)+T(volume) | 4=T(volume)] +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + if nargin==0 + error('MATLAB:cat_check','Need some intput!\n'); + end + + warnstat = warning('query'); + warning('off','all'); + % 'QFORM0 representation has been rounded.'); + switch action + case 'checkinfiles', + switch num2str(nargout) + case '1', varargout{1} = cat_checkinfiles(varargin); + case '2', [varargout{1},varargout{2}] = cat_checkinfiles(varargin); + case '3', [varargout{1},varargout{2},varargout{3}] = cat_checkinfiles(varargin); + case '4', [varargout{1},varargout{2},varargout{3},varargout{4}] = cat_checkinfiles(varargin); + end + case 'checkoutfiles', varargout{1} = cat_checkoutfiles(varargin); + case 'checkinopt', varargout{1} = cat_io_checkinopt(varargin); + otherwise, error('MATLAB:cat_check','Unknown action ''%s''',action); + end + if strcmpi(spm_check_version,'octave') + warning('on','all'); + else + warning(warnstat(1).state,'all'); + end +end + +function varargout = cat_checkinfiles(varargin) + if numel(varargin{1})>0, IN = varargin{1}{1}; end + if numel(varargin{1})>1, readvols = varargin{1}{2}; else readvols = 0; end; + + + % 1=F (file), 2=V (hdr), 3=V (hdr) + T (volume), 4= T (volume) + if ischar(IN) || iscell(IN) && all(cellfun('isclass',IN,'char')) + INtype = 1; + elseif isstruct(IN) && isfield(IN,'fname') && ~isfield(IN,'dat') + INtype = 2; + elseif isstruct(IN) && isfield(IN,'fname') && isfield(IN,'dat') + INtype = 3; + elseif isnumeric(IN) + INtype = 4; + else + error('MATLAB:cat_check','Unknown input.\n'); + end + + % create output + varargout{1} = INtype; + varargout{2} = {''}; + varargout{3} = struct(); + varargout{4} = []; + + switch num2str(INtype) + case '1' + % have to check for no image files + IN=cellstr(IN); + for i=numel(IN):-1:1 + if ~isempty(IN{i}) + [pp,ff,ee]=spm_fileparts(IN{i}); + if ~exist(fullfile(pp,[ff ee]),'file') + fprintf('Cannot find ''%s''!\n',IN{i}); + IN(i)=[]; %:end-1)=IN(i+1:end); % remove file + else + [pp,ff,ee]=spm_fileparts(IN{i}); dd=dir(fullfile(pp,[ff,ee])); + if ~any(strcmp(ee,{'.nii','.img'})) || dd.bytes<2^16 + IN(i)=[]; %IN(i:end-1)=IN(i+1:end); % remove file + end + end + end + end + % ########## Error management if file not exist + if nargout>1, varargout{2} = IN; end + if nargout>2, varargout{3} = spm_vol(char(IN)); end + if nargout>3 && readvols, varargout{4} = spm_read_vols(varargout{3}); end + case '2', + if nargout>1, varargout{2} = cellstr([IN.fname]); end + if nargout>2, varargout{3} = IN; end + if nargout>3 && readvols, varargout{4} = spm_read_vols(varargout{3}); end + case '3', + if nargout>3 && readvols + if numel(IN)==1, varargout{4} = IN.dat; + else varargout{4} = {IN.dat}; + end + end + if nargout>2, varargout{3} = IN; end + if nargout>1, varargout{2} = cellstr([IN.fname]); end + case '4', + if nargout>1, varargout{2} = {''}; end + if nargout>2, varargout{3} = struct(); end + if nargout>3, varargout{4} = IN; end + end +end +function varargout = cat_checkoutfiles(varargin) + if numel(varargin{1})>0, INtype = varargin{1}{1}; end + if numel(varargin{1})>1, F = [varargin{1}{2}(:).fname]; end + if numel(varargin{1})>1, V = varargin{1}{2}; end + %if numel(varargin{2})>3, T = varargin{1}{4}; end; ... later to save memory + + varargout{1} = 'ERROR'; + switch num2str(INtype) + case '1', + if nargout>0 && exist('F','var') + varargout{1} = F; + else + error('MATLAB:cat_check','Need second input for filename output!\n'); + end + case '2', + if nargout>0 && exist('V','var') + varargout{1} = V; + else + error('MATLAB:cat_check','Need third input for header output!\n'); + end + case '3', + if nargout>0 && exist('T','var') + varargout{1} = V; + varargout{1}.dat = varargin{1}{4}; + else + error('MATLAB:cat_check','Need fourth input for volume output!!\n'); + end + case '4', + if nargout>0, + varargout{1} = varargin{1}{4}; + else + error('MATLAB:cat_check','Need fourth input for volume output!!\n'); + end + otherwise, error('MATLAB:cat_check','Unkown INtype ''%d''!\n',INtype); + end +end + +function varargout = cat_io_checkinopt(varargin) + if numel(varargin{1})>0, opt = varargin{1}{1}; + else error('MATLAB:cat_check:checkinopt','Need at least one intput!\n'); + end + if numel(varargin{1})>1, def = varargin{1}{2}; else def=[]; end + if numel(varargin{1})>2, cond = varargin{1}{3}; else cond=[]; end + + res = def; + %res.opt = opt; res.def = def; res.cond = cond; + if ~isfield(res,'do'), res.do = 1; end + if ~isfield(res,'verb'), res.verb = 0; end + + % only elments of def will be in res... do not check for subfields! + %fields = intersect(fieldnames(opt),fieldnames(def)); + fields = fieldnames(opt); + for fn = 1:numel(fields), res.(fields{fn}) = opt.(fields{fn}); end + + for r=1:numel(cond) + str=cond{r}; str=strrep(str,'opt.','res.');str=strrep(str,'def.','res.'); + if ~eval(str), + error('Condition ''%s'' do not fit: %s',str,evalc('res')); + end + end + + % set output filenames if possible + if isfield(res,'pre') && isfield(res,'fname') + fields = fieldnames(res.pre); + for fn = 1:numel(fields) + opt.fnames = cat_io_handle_pre(res,'fname',res.pre.(fields{fn})); + end + end + + % set output variable + varargout{1}=res; +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_surf_renderv.m",".m","10451","299","function varargout = cat_surf_renderv(S,facevertexcdata,opt) +% cat_surf_renderv. Simple push rendering for brain surfaces. +% Surface rendering with openGL is currently not working on surfaces. +% This function was designe as simple replacement of the matlab surface +% render in the CAT report functions. It renders only the points and do not +% fill faces. It is just a simple solution and still in development. +% +% h = cat_surf_renderv(S[,facevertexcdata,opt]) +% img = cat_surf_renderv(S[,facevertexcdata,opt]) +% +% S .. file or surface mesh with vertices, faces, and +% facevertexdata/cdata field +% facevertexcdata .. file or surface texture (vertexdata only) +% opt .. render parameter +% .mat .. orientation matrix (e.g. for rigid registration) +% .view .. render view = ['l'|'r'|'t'|'d'|'f'|b'] (default 'l') +% .interp .. resolution parameter (default 1.4) +% (higer = more pixel but slower) +% .bd .. image boundary (default 0.5) +% .h .. figure/axis handle +% +% See cat_main_reportfig for example use. +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + + dbs = dbstatus; debug = 0; for dbsi=1:numel(dbs), if strcmp(dbs(dbsi).name,mfilename); debug = 1; break; end; end + + if ~exist('opt','var'), opt = struct(); end + + % default parameter + def.mat = eye(4); + def.view = 'l'; + def.clim = [0 6]; + def.interp = 1.4; + def.h = []; + def.bd = 0.5; + def.CATrefMesh = 0; % not working at all - texture resmaple problem + def.optimize = 0; % not really working - in development + + opt = cat_io_checkinopt(opt,def); + + opt.bd = opt.bd * 2^def.interp; + + + % load/set data + if ischar(S) || iscell(S) + Ps = S; + S = gifti(char(Ps)); + end + if ~exist('facevertexcdata','var') + if isfield(S,'facevertexcdata') + facevertexcdata = S.facevertexcdata; + elseif isfield(S,'cdata') + facevertexcdata = S.cdata; + end + end + %if ischar(facevertexcdata) || iscell(facevertexcdata) + %[pp,ff,ee] = cat_ + %facevertexcdata = gifti + %end + + if ~isempty(facevertexcdata) + S.facevertexcdata = facevertexcdata; + elseif isfield(S,'facevertexcdata') + S.facevertexcdata = S.facevertexcdata; + facevertexcdata = S.facevertexcdata; + elseif isfield(S,'cdata') + S.facevertexcdata = S.cdata; + facevertexcdata = S.cdata; + end + + + % rotation settings + if ischar( opt.view ) + switch opt.view + case 't', view = [ 0 0 90]; + case 'd', view = [ 0 0 -90]; + case 'r', view = [ 0 90 0]; + case 'l', view = [180 -90 0]; + case 'f', view = [ 0 0 0]; + case 'b', view = [ 0 0 0]; + end + else + view = opt.view; + end + + + % main + if debug, tic; end + Sx = S; + + % rotation + Sx.vertices = [Sx.vertices, ones(size(Sx.vertices,1),1)] * ... + (spm_matrix([0 0 0 deg2rad( view ) 1 1 1 0 0 0]) ); + Sx.vertices = Sx.vertices(:,1:3); + + + if opt.CATrefMesh + % surface refinement with CAT_RefineMesh .. not yet working + Sxo = Sx; + Pcentral = sprintf('%s.gii',tempname); + save(gifti(struct('faces',Sx.faces,'vertices',Sx.vertices)),Pcentral); + cmd = sprintf('CAT_RefineMesh ""%s"" ""%s"" %0.2f 0',Pcentral,Pcentral,1); + cat_system(cmd,0); + Sx = gifti(Pcentral); + delete(Pcentral); + Sx.facevertexcdata = cat_surf_fun('surf2surf',Sxo,Sx,Sxo.facevertexcdata); % ... not working + end + + + % Optimize: + % The general idea is to remove faces that are not vissible and those + % will not need further refinement but the problem is that they can + % effect the normals ... + % in the best case this could half runtime + if 1 %opt.optimize + cat_mesh_smooth = @(M,C,s) single( spm_mesh_smooth(M,double(C),s) ); + + for ii = 1:round(opt.interp) + + if 0 + % remove backface faces .. the test is slower than the improvement + M = spm_mesh_smooth(Sx); + Nv = spm_mesh_normals(struct('vertices',Sx.vertices,'faces',Sx.faces)); + NvA = abs( cat_surf_fun('angle',Nv,repmat([0 0 1],size(Nv,1),1))); clear Nv; + NvA = cat_mesh_smooth(M,NvA,10); clear M; + back = sum( NvA(Sx.faces) < 45 , 2); % the angle depend on surface orientatation definition + Sx.faces(back > 2,:) = []; + clear NvA; + end + + + if 0 + % the idea was to remove small faces does not need further refinement + % but is also not working + [x,A] = cat_surf_fun('area',Sx); clear x; + Sx.faces(A < 0.25 / 2^opt.interp,:) = []; + end + + if 1 + % removel faces those points are not visible + M = spm_mesh_smooth(Sx); + Vb = round(Sx.vertices * 2^(opt.interp)); %max(2,min(8,8 / 2^ii))); + Vb(:,3) = -Vb(:,3); + Vb = Vb - repmat( min( Vb ) , size(Vb,1) , 1 ) + opt.bd*2; + imgz = inf( round(max( Vb(:,1:2) ) + opt.bd*4),'single'); + for vi = 1:size(Vb,1) + i = round(Vb(vi,1)); + j = round(Vb(vi,2)); + if Vb(vi,3) < imgz(i,j) + imgz(i,j) = Vb(vi,3); + end + end + hidden = zeros(size(Sx.facevertexcdata),'single'); + for vi = 1:size(Vb,1) + i = round(Vb(vi,1)); + j = round(Vb(vi,2)); + if Vb(vi,3) > imgz(i,j) + 1 + hidden(vi) = 1; + end + end + hidden = cat_mesh_smooth(M,hidden,10); + Sx.faces( sum( hidden(Sx.faces),2) > 0.999,:) = []; + end + + % mesh interpolation + Sx = cat_surf_fun('meshinterp',Sx,1); + end + else + Sx = cat_surf_fun('meshinterp',Sx,opt.interp); + end + + + % estimate normals + % we here use a direct camlight + N = abs( spm_mesh_normals(struct('vertices',Sx.vertices,'faces',Sx.faces))); + NA = cat_surf_fun('angle',N,repmat([0 0 1],size(N,1),1)); + NA = abs( NA - 90 ); + + + % increase sampling by adding displaced points to avoid holes + % ... limit this to voxel that are orientated to the cam + Sx.vertices(:,3) = -Sx.vertices(:,3); + Sx.vertices = Sx.vertices - repmat( min( Sx.vertices ) , size(Sx.vertices,1) , 1 ) + opt.bd; + Sx.vertices = Sx.vertices * 2^opt.interp; + method = 21; + if method == 1 + Sx.vertices = [Sx.vertices; Sx.vertices - 0.25.*N; Sx.vertices - 0.5.*N; Sx.vertices - 1.0.*N]; + cdatax = repmat(Sx.facevertexcdata,4,1); + NA = repmat(NA,4,1); + elseif method == 2 + Sx.vertices = [floor(Sx.vertices(:,1)*1)/1 , floor(Sx.vertices(:,2)*1)/1 , Sx.vertices(:,3) ; + floor(Sx.vertices(:,1)*1)/1 , ceil(Sx.vertices(:,2)*1)/1 , Sx.vertices(:,3) ; + ceil(Sx.vertices(:,1)*1)/1 , floor(Sx.vertices(:,2)*1)/1 , Sx.vertices(:,3) ; + ceil(Sx.vertices(:,1)*1)/1 , ceil(Sx.vertices(:,2)*1)/1 , Sx.vertices(:,3) ; + Sx.vertices - 0.25.*N; Sx.vertices - 0.5.*N; Sx.vertices - 1.0.*N + ]; + cdatax = repmat(Sx.facevertexcdata,7,1); + NA = repmat(NA,7,1); + elseif method == 21 + Sx.vertices = [floor(Sx.vertices(:,1)*1)/1 , floor(Sx.vertices(:,2)*1)/1 , Sx.vertices(:,3) ; + floor(Sx.vertices(:,1)*1)/1 , ceil(Sx.vertices(:,2)*1)/1 , Sx.vertices(:,3) ; + ceil(Sx.vertices(:,1)*1)/1 , floor(Sx.vertices(:,2)*1)/1 , Sx.vertices(:,3) ; + ceil(Sx.vertices(:,1)*1)/1 , ceil(Sx.vertices(:,2)*1)/1 , Sx.vertices(:,3) ; + ]; + cdatax = repmat(Sx.facevertexcdata,4,1); + NA = repmat(NA,4,1); + elseif method == 3 + Sx.vertices = [Sx.vertices; Sx.vertices - 0.5.*N]; + cdatax = repmat(Sx.facevertexcdata,2,1); + NA = repmat(NA,2,1); + end + + + % render image + imgc = zeros( round(max( Sx.vertices(:,1:2) ) + opt.bd*2 ),'single'); % texture map + imgz = inf( round(max( Sx.vertices(:,1:2) ) + opt.bd*2 ),'single'); % z-depth map (visibility) + imgn = zeros( round(max( Sx.vertices(:,1:2) ) + opt.bd*2 ),'single'); % normal map (lightning) + for vi = 1:size(Sx.vertices,1) + i = round( Sx.vertices(vi,1) ); + j = round( Sx.vertices(vi,2) ); + if Sx.vertices(vi,3) < imgz(i,j) + imgc(i,j) = cdatax(vi); + imgn(i,j) = NA(vi); + imgz(i,j) = Sx.vertices(vi,3); + end + end + + bgm = repmat( isinf( imgz ) , 1,1,3); + bgm = cat_vol_morph( bgm ,'o'); + + % normalize range to 255 for RGB convertation + imgtn = min(255,max(0,round( ( imgc - opt.clim(1) ) / opt.clim(2) * 255 ))); clear imgc; + imgzn = min(255,max(0,round( ( imgz - min(imgz(:)) ) / max( imgz(imgz(:) 1 + bgc = get(opt.h,'color'); + bg = cat(3,bgc(1) * ones( size(imgz)), bgc(2) * ones( size(imgz)), bgc(3) * ones( size(imgz)) ); + img = img.*(1-bgm) + bg.*bgm; + end + + if debug + toc + end + + % set output + if ~isempty( opt.h ) && opt.h > 1 + image( opt.h , img ); + axis(opt.h,'equal','off'); + + varargout{1}.h = opt.h; + varargout{1}.cdata = facevertexcdata; + else + image( img ); + axis('equal','off'); + varargout{1} = img; + end +end +function imgc = median2d(imgc,th) + imgs = repmat(single(imgc),1,1,3); + imgs = cat_vol_median3(imgs); %,true(size(imgs)),true(size(imgs)),th); + imgc = imgs(:,:,2); +end +function img = smooth2d(img,th) + imgs = smooth3(repmat(img,1,1,3)); + img = img*(1-th) + th*imgs(:,:,2); + img = cat_vol_ctype(img); +end +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_surf_create_TPM_hull_surface.m",".m","6970","213","function Phull = cat_surf_create_TPM_hull_surface(tpm,human,skull,onlytmp) +% _________________________________________________________________________ +% Creates a surface of the brain and headmask and save the data in one file +% named as ""bh.headbrain.$TPM-filename$.gii"" in the cat surface directory. +% If the file allready exist only the filename is returned otherwise a new +% brain/head surface file is created. +% +% Phull = cat_surf_create_TPM_hull_surface(tpm[,human,skull]) +% Shull = cat_surf_create_TPM_hull_surface(tpm[,human,skull]) +% +% tpm .. TPM-filename, TPM-header, SPM-TPM-structure +% human .. flag to write animal templates into another directory +% skull .. create outline without skull +% Phull .. filename of the surface file +% Shull .. export surface in case of reading/writing errors +% onlytmp .. only temporary output +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + + % check input + if ~exist('tpm','var') + Ptpm = fullfile(spm('dir'),'tpm','TPM.nii'); + else + if ischar(tpm) + Ptpm = tpm; + clear tpm; + elseif iscell(tpm) + Ptpm = char(tpm); + clear tpm; + else + if numel(tpm)==6 + Ptpm = tpm(1).fname; + clear tpm; + else + % SPM-TPM structure + try + Ptpm = tpm.V(1).fname; + catch + Ptpm = tpm(1).fname; + end + end + end + end + if ~exist('human','var') + species = ''; + human = 1; + else + if isnumeric(human) || islogical(human) + species = ''; + human = human > 0; + else % it is a string + species = ['.' human]; + human = strcmp(human,'human'); + end + end + if ~exist('skull','var') + skull = 1; + end + if ~exist('onlytmp','var') + onlytmp = 1; + end + + % define filename + [pp,Pname,ee] = spm_fileparts(Ptpm); Pname = strrep([Pname ee],'.nii',''); + if human + if strcmp(pp,fullfile(spm('dir'),'tpm')) && strcmp(Pname,'TPM') % default + if skull > 0 + Phull = fullfile(fileparts(mfilename('fullpath')),'templates_surfaces',sprintf('bh.headbrain%s.%s.gii',species,Pname)); + else + Phull = fullfile(fileparts(mfilename('fullpath')),'templates_surfaces',sprintf('bh.brain%s.%s.gii',species,Pname)); + end + % no species in fname - default + if ~exist('Phull','file') + if skull > 0 + Phull = fullfile(fileparts(mfilename('fullpath')),'templates_surfaces',sprintf('bh.headbrain.%s.gii',Pname)); + else + Phull = fullfile(fileparts(mfilename('fullpath')),'templates_surfaces',sprintf('bh.brain.%s.gii',Pname)); + end + end + else + if skull > 0 + Phull = fullfile(pp,sprintf('bh.headbrain%s.%s.gii',species,Pname)); + else + Phull = fullfile(pp,sprintf('bh.brain%s.%s.gii',species,Pname)); + end + end + else + if skull > 0 + Phull = fullfile(fileparts(mfilename('fullpath')),'templates_animals_surfaces',sprintf('bh.headbrain%s.%s.gii',species,Pname)); + else + Phull = fullfile(fileparts(mfilename('fullpath')),'templates_animals_surfaces',sprintf('bh.brain%s.%s.gii',species,Pname)); + end + end + + % nothing to do - just return filename + if ~cat_io_rerun(Ptpm,Phull,0,0), return; end + + + % if the file is not existing we have to (temporary) create it + if onlytmp + [~,Pname,ee] = spm_fileparts(Ptpm); Pname = strrep([Pname ee],'.nii',''); + Phull = fullfile(tempdir,sprintf('bh.headbrain%s.%s.gii',species,Pname)); + + % if we have already done it in this matlab session then just return filename + if ~cat_io_rerun(Ptpm,Phull,0,0), return; end + end + + + % load SPM-TPM-structure + if ~exist('tpm','var') || ~isfield(tpm(1),'dat') + % here we load the full TPM structure + istpm = 1; + tpm = spm_load_priors8(Ptpm); + + % create brainmask surface + if skull==-2 + Yb = exp(tpm.dat{1}) + exp(tpm.dat{2}); + else + Yb = exp(tpm.dat{1}) + exp(tpm.dat{2}) + exp(tpm.dat{3}); + % remove SPM CSF eye + Yb = Yb .* smooth3( cat_vol_morph( cat_vol_morph( Yb , 'lo' , 2), 'd') ); + end + elseif isstruct(tpm) + % if we got the TPM as file header structure + istpm = 2; + try + Yb = spm_read_vol( V(1) ) + spm_read_vol( V(2) ); + catch + if numel(tpm) > 1 + % create brainmask surface + if skull==-2 + Yb = tpm(1).dat + tpm(2).dat; + else + Yb = tpm(1).dat + tpm(2).dat + tpm(3).dat; + % remove SPM CSF eye + Yb = Yb .* smooth3( cat_vol_morph( cat_vol_morph( Yb , 'lo' , 2), 'd') ); + end + else + if skull==-2 + Yb = exp(tpm.dat{1}) + exp(tpm.dat{2}); + else + Yb = exp(tpm.dat{1}) + exp(tpm.dat{2}) + exp(tpm.dat{3}); + % remove SPM CSF eye + Yb = Yb .* smooth3( cat_vol_morph( cat_vol_morph( Yb , 'lo' , 2), 'd') ); + end + end + end + else + % otherwise avoid errors + Yb = zeros(5,5,5); + end + Sh = isosurface(Yb,0.5); + + + % create head surface based on 5 classes with average probability threshold + if skull && istpm + % use all classes but nat the background + if istpm == 1 + Yhd = exp(tpm.dat{1}); + for i = 2:numel(tpm.dat)-1 + Yhd = Yhd + exp(tpm.dat{i}); + end + elseif istpm == 2 + Yhd = spm_read_vols( tpm(1) ); + for i = 2:numel(tpm)-1 + Yhd = Yhd + spm_read_vols( tpm(i) ); + end + end + Yhd = cat_vol_morph(Yhd>0.5,'l',[1 0.5]); + Yhd = ~cat_vol_morph(~Yhd,'l',[1 0.5]); + if strcmpi(spm_check_version,'octave') + Shd = spm_mesh_isosurface(smooth3(Yhd),0.5 - ( 0.4 * (skull<0)),0.5); + else + Shd = isosurface(Yhd,0.5 - ( 0.4 * (skull<0)) ); + end + Sh.faces = [Sh.faces; Shd.faces + size(Sh.vertices,1)]; + Sh.vertices = [Sh.vertices; Shd.vertices]; + end + if strcmpi(spm_check_version,'octave') + Sh = spm_mesh_reduce(Sh,0.2); + else + Sh = reducepatch(Sh,0.2); + end + + % save surface + if istpm == 1 + vmat = tpm.V(1).mat(1:3,:)*[0 1 0 0; 1 0 0 0; 0 0 1 0; 0 0 0 1]; + mati = spm_imatrix(tpm.V(1).mat); + elseif istpm == 2 + vmat = tpm(1).mat(1:3,:)*[0 1 0 0; 1 0 0 0; 0 0 1 0; 0 0 0 1]; + mati = spm_imatrix(tpm(1).mat); + end + if istpm + Sh.vertices = (vmat*[Sh.vertices' ; ones(1,size(Sh.vertices,1))])'; + if mati(7)<0, Sh.faces = [Sh.faces(:,1) Sh.faces(:,3) Sh.faces(:,2)]; end + try + save(gifti(struct('faces',Sh.faces,'vertices',Sh.vertices)),Phull,'Base64Binary'); + catch + if exist(Phull,'file') + fprintf('Warning: Could not update %s with newer version. Please change write permissions.\n',Phull); + else + error('Could not save %s. Please change write permissions.\n',Phull); + end + end + end +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_io_contains.m",".m","2853","95","function TF = cat_io_contains(str,pat,~,icTF) +%Support contains function for older matlabs. +% +% TF = cat_io_contains(str,pat[,'ignoreCase',TRUE|FALSE]) +% +% See also contains or use cat_io_contains(1) to run the unit test. +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + + switch nargin + case 0 + help cat_io_contains; + case 1 + unittest; + case {2,4} + if ischar(str), str = cellstr(str); end + if ischar(pat), pat = cellstr(pat); end + + if ~iscellstr(str) + error('error:cat_io_contains','First argument must be text.') + end + if ~iscellstr(pat) + error('error:cat_io_contains','Search term must be a text or pattern array.') + end + + if nargin == 4 && icTF + str = lower(str); + pat = lower(pat); + end + + TF = ~cellfun('isempty', strfind( str , pat(1))); %#ok + if numel(pat) > 1 + for str2i = 2:numel(pat) + TF = TF | ~cellfun('isempty', strfind( str , pat{str2i})); + end + end + + otherwise + error('error:cat_io_contains:badInput','Wrong number of input elements!'); + end +end +% ====================================================================== +function unittest +%unittest with cases from the MATLAB contains help. + + strpats = { + { {'Mary Ann Jones','Paul Jay Burns','John Paul Smith'} {'Paul'} }; + { {'Mary Ann Jones','Christopher Matthew Burns','John Paul Smith'} {'Ann','Paul'} }; + { {'Mary Ann Jones','Christopher Matthew Burns','John Paul Smith'} 'Ann' }; + { {'Mary Ann Jones','Christopher Matthew Burns','John Paul Smith'} 'ann' }; + { 'peppers, onions, and mushrooms' 'onion'}; + { 'peppers, onions, and mushrooms' 'nothing'}; + { 1:2 'test'}; + { 'test' 1}; + }; + + for spi = 1:numel(strpats) + cat_io_cprintf('blue','\nTestcase %d:\n',spi) + + fprintf('Input1: '); disp(strpats{spi}{1}) + fprintf('Input2: '); disp(strpats{spi}{2}) + + for cs = 0:1 + + fprintf('contains: '); + try + if cs + disp(contains(strpats{spi}{1},strpats{spi}{2},'IgnoreCase',1)) + else + disp(contains(strpats{spi}{1},strpats{spi}{2})) + end + catch e + cat_io_cprintf('err',[e.message '\n']); + end + + fprintf('cat_io_contains: '); + try + if cs + disp(cat_io_contains(strpats{spi}{1},strpats{spi}{2},'IgnoreCase',1)) + else + disp(cat_io_contains(strpats{spi}{1},strpats{spi}{2})) + end + catch e + cat_io_cprintf('err',[e.message '\n']); + end + end + end +end","MATLAB" +"Neurology","ChristianGaser/cat12","distribute_to_server.sh",".sh","8875","271","#! /bin/bash +# Distribute jobs to server +# ______________________________________________________________________ +# +# Christian Gaser, Robert Dahnke +# Structural Brain Mapping Group (https://neuro-jena.github.io) +# Departments of Neurology and Psychiatry +# Jena University Hospital +# ______________________________________________________________________ +# $Id$ + +######################################################## +# global parameters +######################################################## + +SERVER=localhost +USER=`whoami` + +######################################################## +# run main +######################################################## + +main () +{ + parse_args ${1+""$@""} + + check_files + distribute + + exit 0 +} + +######################################################## +# check arguments and files +######################################################## + +parse_args () +{ + local optname optarg files_to_calculate all_files + count=0 + files_to_calculate=0 + all_files=0 + while [ $# -gt 0 ] + do + optname=""`echo $1 | sed 's,=.*,,'`"" + optarg=""`echo $2 | sed 's,^[^=]*=,,'`"" + case ""$1"" in + --command* | -c*) + exit_if_empty ""$optname"" ""$optarg"" + COMMAND=$optarg + shift + ;; + --server* | -s*) + exit_if_empty ""$optname"" ""$optarg"" + SERVER=$optarg + shift + ;; + --pattern* | -p*) + exit_if_empty ""$optname"" ""$optarg"" + PATTERN=$optarg + shift + ;; + --user* | -u*) + exit_if_empty ""$optname"" ""$optarg"" + USER=$optarg + shift + ;; + --dir* | -d*) + exit_if_empty ""$optname"" ""$optarg"" + DIR=$optarg + shift + + if [ ! -n ""$PATTERN"" ]; then + echo Pattern have to be defined first to use that function. + exit 0 + fi + + # exclude that patterns from search + list=`find $DIR -name ""*.[in][mi][gi]"" \! -name ""*wrp[0-3]*.nii"" \! -name ""*wp[0-3]*.nii"" \! -name ""wm*.nii"" \! -name ""wrm*.nii"" \! -name ""bf*.nii"" \! -name ""p[0-3]*.nii"" \! -name ""iy_*.nii"" \! -name ""y_*.nii"" \! -name ""rp[0-3]*.nii""` + + for i in ${list} ; do + ext=""${i##*.}"" + name=""${i%.*}"" + # remove leading ""./"" + name=`echo $name|sed -e 's/\.\///g'` + bname=""${name##*/}"" + dname=""${name%/*}"" + + for j in ${dname}/${PATTERN}${bname}*.nii ; do + if [ ! -f ""$j"" ]; then + ARRAY[$count]=$i + ((count++)) + fi + done + done + ;; + -h | --help | -v | --version | -V) + help + exit 1 + ;; + -*) + echo ""`basename $0`: ERROR: Unrecognized option \""$1\"""" >&2 + ;; + *) + ARRAY[$count]=$1 + ((count++)) + ;; + esac + shift + done + + if [ ""$count"" == ""0"" ] && [ ! -n ""PATTERN"" ] ; then + echo All files are already processed. + exit 0 + fi + +} + +######################################################## +# check arguments +######################################################## + +exit_if_empty () +{ + local desc val + + desc=""$1"" + shift + val=""$*"" + + if [ ! -n ""$val"" ] + then + echo ERROR: ""No argument given with \""$desc\"" command line argument!"" >&2 + exit 1 + fi +} + +######################################################## +# check files +######################################################## + +check_files () +{ + if [ ! -n ""$COMMAND"" ]; + then + echo ""$FUNCNAME ERROR - no command defined."" + help + exit 1 + fi + + SIZE_OF_ARRAY=""${#ARRAY[@]}"" + if [ ""$SIZE_OF_ARRAY"" -eq 0 ] + then + echo 'ERROR: No files given!' >&2 + help + exit 1 + fi + + i=0 + while [ ""$i"" -lt ""$SIZE_OF_ARRAY"" ] + do + if [ ! -f ""${ARRAY[$i]}"" -a ! -L ""${ARRAY[$i]}"" ] && [ ! -d ""${ARRAY[$i]}"" ]; then + echo ERROR: File or directory ${ARRAY[$i]} not found + help + exit 1 + fi + ((i++)) + done + +} + +######################################################## +# run distribute +######################################################## + +distribute () +{ + + NUMBER_OF_SERVERS=0 + for k in ${SERVER}; do + ((NUMBER_OF_SERVERS++)) + done + + SIZE_OF_ARRAY=""${#ARRAY[@]}"" + BLOCK=$((10000* $SIZE_OF_ARRAY / $NUMBER_OF_SERVERS )) + + i=0 + while [ ""$i"" -lt ""$SIZE_OF_ARRAY"" ] + do + count=$((10000* $i / $BLOCK )) + if [ ! -n ""${ARG_LIST[$count]}"" ]; then + ARG_LIST[$count]=""${ARRAY[$i]}"" + else + ARG_LIST[$count]=""${ARG_LIST[$count]} ${ARRAY[$i]}"" + fi + ((i++)) + done + + i=0 + for x in ${SERVER}; + do + if [ ! ""${ARG_LIST[$i]}"" == """" ]; then + j=$(($i+1)) + echo job ${j}/""$NUMBER_OF_SERVERS"": + echo $COMMAND ${ARG_LIST[$i]} + if [ ""$x"" == ""localhost"" ]; then + $COMMAND ${ARG_LIST[$i]} + else + bash -c ""ssh ${USER}@${x} $COMMAND ${ARG_LIST[$i]}"" + fi + fi + ((i++)) + done + +} + +######################################################## +# help +######################################################## + +help () +{ +cat <<__EOM__ + +USAGE: + distribute_to_server.sh [-s server] [-p pattern] -c command_to_distribute_to_server.sh filename|filepattern|-d directory + + -c --command command that should be distributed + -s --server server list (if empty the command runs on the local machine) + -p --pattern pattern to search of already processed files that is prepended. + -u --user user + -d --dir directory for searching file patterns + + Only one filename or pattern or directory using the -d flag is allowed. This can be either a single file or a pattern + with wildcards to process multiple files or even a directory. For the latter case you also have to define a pattern that + is used for the search for already processed files. + +PURPOSE: + distribute_to_server.sh a job or command + +OUTPUT: + +EXAMPLE + distribute_to_server.sh -c ""niismooth -v -fwhm 8"" sTRIO*.nii + smoothing with fwhm of 8mm for all files sTRIO*.nii. Use verbose mode to see diagnostic output. + + distribute_to_server.sh -s ""141.35.68.68 141.35.68.72 141.35.68.73 141.35.68.74 141.35.68.75"" -c ""/Volumes/UltraMax/spm12/toolbox/cat12/cat_batch_cat.sh -p 8 -d /Volumes/UltraMax/cat_defaults_p0123.m -m /Volumes/UltraMax/MATLAB_R2010b.app/bin/matlab"" /Volumes/UltraMax/SVE.LPBA40.testdata/S*.nii + CAT12 batch for all files in /Volumes/UltraMax/SVE.LPBA40.testdata/S*.nii with 8 parallel jobs and optional default file + + distribute_to_server.sh -s ""141.35.68.68 141.35.68.73 141.35.68.74 141.35.68.75"" -c ""/Volumes/UltraMax/spm12/toolbox/cat12/cat_batch_cat.sh -p 8 -d /Volumes/UltraMax/cat_defaults_m0wrp12.m -m /Volumes/UltraMax/MATLAB_R2010b.app/bin/matlab"" -p m0wrp1 -d /Volumes/UltraMax/SVE.LPBA40.testdata + CAT12 batch with 8 parallel jobs and optional default file. Only those files in /Volumes/UltraMax/SVE.LPBA40.testdata/ are processed where no prepended m0wrp1 pattern can be found. All other files are skipped. + + Using of MATLAB, SPM and VBM commands like the NLM filter function ""cat_vol_sanlm({'file1','file2'})"". CFILES contain the files for each job. + distribute_to_server.sh -s ""141.35.68.96"" -c ""/Volumes/vbmDB/MRData/batches/cat_batch_cat.sh -m /Volumes/Ultramax/MATLAB_R2010b.app/bin/matlab -v /Volumes/Ultramax/spm12/toolbox/cat12/ -c \""cat_vol_sanlm\(CFILES\)\"""" -p 8 -u local /Volumes/vbmDB/MRData/release20140211/pre/vbm8/INDI/HC/NYa/sub44*/INDI_*.nii + + Quality assurance for files processed by VBM8 preprocessing. Requires external noise correction by sanlm-call with 'n' prefix + sh distribute_to_server.sh -s ""141.35.68.96 141.35.68.95 141.35.68.75 141.35.68.74"" -c ""/Volumes/vbmDB/MRData/batches/spm12/toolbox/cat12/cat_batch_cat.sh -m /Volumes/Ultramax/MATLAB_R2010b.app/bin/matlab -v /Volumes/vbmDB/MRData/batches/spm12/toolbox/cat12 -p 4 -c \""cat_vol_sanlm\(struct\('data',CFILES,'prefix',\'n'\)\)\"""" -u local /Volumes/vbmDB/MRData/release20140211/pre/vbm8/IXI/HC/*/*/p0*.nii + sh distribute_to_server.sh -s ""141.35.68.96 141.35.68.95 141.35.68.75 141.35.68.74"" -c ""/Volumes/vbmDB/MRData/batches/spm12/toolbox/cat12/cat_batch_cat.sh -m /Volumes/Ultramax/MATLAB_R2010b.app/bin/matlab -v /Volumes/vbmDB/MRData/batches/spm12/toolbox/cat12 -l /Volumes/vbmDB/MRData/log -p 4 -c \""cat_tst_qa2\(\'p0\',CFILES,struct\(\'prefix\',\'vbm8_\',\'write_csv\',0\)\)\"""" -u local /Volumes/vbmDB/MRData/release20140211/pre/vbm8/IXI/HC/*/*/p0*.nii + +This script was written by Christian Gaser (christian.gaser@uni-jena.de). + +__EOM__ +} + +######################################################## +# call main program +######################################################## + +main ${1+""$@""} + +","Shell" +"Neurology","ChristianGaser/cat12","cat_vol_qa202310.m",".m","40351","975","function varargout = cat_vol_qa202310(action,varargin) +% CAT Preprocessing T1 Quality Control +% ______________________________________________________________________ +% +% Estimation of image quality measures like noise, inhomogeneity, +% contrast, resolution, etc. and scaling for school marks. +% +% [QAS,QAM] = cat_vol_qa202310(action,varargin) +% +% 4) CAT12 internal preprocessing interface +% (this is the processing case that is also called in all other cases) +% [QAS,QAM] = cat_vol_qa202310('cat12',Yp0,Po,Ym,res[,opt]) +% +% +% Pp0 - segmentation files (p0*.nii) +% Po - original files (*.nii) +% Pm - modified files (m*.nii) +% Yp0 - segmentation image matrix +% Ym - modified image matrix +% +% opt = parameter structure +% opt.verb = verbose level [ 0=nothing | 1=points | 2*=times ] +% opt.redres = resolution in mm for intensity scaling [ 4* ]; +% opt.write_csv = final cms-file +% opt.write_xml = images base xml-file +% opt.sortQATm = sort QATm output +% opt.orgval = original QAM results (no marks) +% opt.recalc = +% opt.avgfactor = +% opt.prefix = prefix of xml output file (default cat_*.xml) +% +% ______________________________________________________________________ +% Robert Dahnke +% Structural Brain Mapping Group +% University Jena +% +% $Id$ +% ______________________________________________________________________ + +%#ok<*ASGLU> + + % default parameter + if isstruct(varargin{6}) + opt = cat_check('checkinopt',varargin{6},defaults); + end + + % check input by action + switch action + case 'cat12' + % CAT12 internal input + if nargin>3 + Yp0 = varargin{1}; +% Octave is starting with many warning messages here ... +% if strcmpi(spm_check_version,'octave'), warning off; end + Vo = spm_vol(varargin{2}); +% if strcmpi(spm_check_version,'octave'), warning on; end + Yo = single(spm_read_vols(Vo)); + Ym = varargin{3}; + res = varargin{4}; + V = res.image; + species = varargin{5}; + if isfield(varargin{6},'qa') + if isfield(varargin{6}.qa,'software') && isfield(varargin{6}.qa.software,'version_segment'), QAS.software.version_segment = varargin{6}.qa.software.version_segment; end + if exist('QAS','var') + if isfield(varargin{6}.qa,'qualitymeasures'), QAS.qualitymeasures = cat_io_updateStruct(QAS,varargin{6}.qa.qualitymeasures); end + if isfield(varargin{6}.qa,'subjectmeasures'), QAS.subjectmeasures = cat_io_updateStruct(QAS,varargin{6}.qa.subjectmeasures); end + else + if isfield(varargin{6}.qa,'qualitymeasures'), QAS.qualitymeasures = varargin{6}.qa.qualitymeasures; end + if isfield(varargin{6}.qa,'subjectmeasures'), QAS.subjectmeasures = varargin{6}.qa.subjectmeasures; end + end + end + if nargin>7, Pp0 = varargin{7}; end % nargin count also parameter + + % reduce to original native space if it was interpolated + sz = size(Yp0); + if any(sz(1:3)~=Vo.dim(1:3)) + if isfield(Vo,'private'), Vo = rmfield(Vo,'private'); end + if isfield(Vo,'mat0'), Vo = rmfield(Vo,'mat0'); end + Vo.dat = zeros(Vo.dim,'single'); Vo.dt(1) = 16; Vo.pinfo = [1;0;0]; + + Vp0t = res.image; + if isfield(Vp0t,'private'), Vp0t = rmfield(Vp0t,'private'); end + if isfield(Vp0t,'mat0'), Vp0t = rmfield(Vp0t,'mat0'); end + Vp0t.dt(1) = 16; + Vp0t.pinfo = [1;0;0]; + Vp0t.dat = Yp0; + + % resampling and corrections of the Yp0 + [Vtpm,Yp0] = cat_vol_imcalc(Vp0t,Vo,'i1',struct('interp',2,'verb',0)); + rf = 50; + Yp0 = single(Yp0); + Yp0r = round(Yp0*rf)/rf; + YMR = false(size(Yp0)); + for i=1:4, YMR = YMR | (Yp0>(i-1/rf) & Yp0<(i+1/rf)); end + Yp0(YMR) = Yp0r(YMR); clear YMR Ynr; + + % resampling of the corrected image + Vp0t.dat = Ym; + [Vtpm,Ym] = cat_vol_imcalc(Vp0t,Vo,'i1',struct('interp',6,'verb',0)); + Ym = single(Ym); + end + + else + error('MATLAB:cat_vol_qa202310:inputerror',... + 'Wrong number/structure of input elements!'); + end + otherwise + error('MATLAB:cat_vol_qa202310:inputerror',... + 'Wrong number/structure of input elements!'); + end + if ~exist('species','var'), species='human'; end + + + % file information + % ---------------------------------------------------------------- + if isfield(opt,'job') + [mrifolder, reportfolder] = cat_io_subfolders(Vo.fname,opt.job); + if isfield( opt.job, 'filedata') + QAS.filedata = opt.job.filedata; + end + else + [mrifolder, reportfolder] = cat_io_subfolders(Vo.fname,cat_get_defaults); + end + [pp,ff,ee] = spm_fileparts(Vo.fname); + if strcmp(ee,'.gz'), [~,ff] = spm_fileparts(ff); ee = '.nii.gz'; end + [pp0,ff0,ee0] = spm_fileparts(Pp0); + [QAS.filedata.path,QAS.filedata.file] = spm_fileparts(Vo.fname); + QAS.filedata.fname = Vo.fname; + QAS.filedata.F = Vo.fname; + QAS.filedata.Fm = fullfile(pp0,['m' ff ee0]); + QAS.filedata.Fp0 = fullfile(pp0,['p0' ff ee0]); + QAS.filedata.fnames = [spm_str_manip(pp,sprintf('k%d',... + floor( max(opt.snspace(1)-19-ff,opt.snspace(1)-19)/3) - 1)),'/',... + spm_str_manip(ff,sprintf('k%d',... + (opt.snspace(1)-19) - floor((opt.snspace(1)-14)/3)))]; + + + % software, parameter and job information + % ---------------------------------------------------------------- + % get current release number and version + [ver_cat, rev_cat] = cat_version; + ver_cat = ver_cat(4:end); % remove leading CAT + [nam,rev_spm] = spm('Ver'); + if ispc, OSname = 'WIN'; + elseif ismac, OSname = 'MAC'; + else, OSname = 'LINUX'; + end + + % 1 line: Matlab, SPM12, CAT12 version number and GUI and experimental mode + QAS.software.system = char(OSname); + QAS.software.version_spm = rev_spm; + if strcmpi(spm_check_version,'octave') + QAS.software.version_matlab = ['Octave ' version]; + else + A = ver; + for i=1:length(A) + if strcmp(A(i).Name,'MATLAB') + QAS.software.version_matlab = A(i).Version; + end + end + clear A + end + QAS.software.version_cat = ver_cat; + if ~isfield(QAS.software,'version_segment') + QAS.software.version_segment = rev_cat; + end + QAS.software.revision_cat = rev_cat; + QAS.software.function = which('cat_vol_qa202310'); + QAS.software.markdefs = which('cat_stat_marks'); + QAS.software.qamethod = action; + QAS.software.date = datestr(clock,'yyyymmdd-HHMMSS'); + QAS.software.cat_warnings = cat_io_addwarning; + % replace matlab newlines by HTML code + for wi = 1:numel( QAS.software.cat_warnings ) + QAS.software.cat_warnings(wi).message = cat_io_strrep( QAS.software.cat_warnings(wi).message , {'\\n', '\n'} , {'
','
'} ); + end + + %QAS.parameter = opt.job; + if isfield(opt,'job') && isfield(opt.job,'opts'), QAS.parameter.opts = opt.job.opts; end + if isfield(opt,'job') && isfield(opt.job,'extopts'), QAS.parameter.opts = opt.job.extopts; end + if exist('res','var') + rf = {'Affine','Affine0','lkp','mn','vr','ll'}; % important SPM preprocessing variables + for rfi=1:numel(rf) + if isfield(res,rf{rfi}), QAS.SPMpreprocessing.(rf{rfi}) = res.(rf{rfi}); end + end + end + + + %% resolution, boundary box + % --------------------------------------------------------------- + QAS.software.cat_qa_warnings = struct('identifier',{},'message',{}); + vx_vol = sqrt(sum(Vo.mat(1:3,1:3).^2)); + vx_voli = sqrt(sum(V.mat(1:3,1:3).^2)); + Yp0toC = @(Yp0,c) 1-min(1,abs(Yp0-c)); + + % resolution + QAS.qualitymeasures.res_vx_vol = vx_vol; + QAS.qualitymeasures.res_vx_voli = vx_voli; + QAS.qualitymeasures.res_RMS = cat_stat_nanmean(vx_vol.^2).^0.5; + % further unused measure (just for test/comparison) + %QAS.qualitymeasures.res_isotropy = max(vx_vol)./min(vx_vol); + %QAS.qualitymeasures.res_vol = prod(abs(vx_vol)); + %QAS.qualitymeasures.res_MVR = mean(vx_vol); + + % boundary box - brain tissue next to image boundary + % - this parameter is not further tested/evaluated + % - there is another version in cat_vol_qa202205 + bbth = round(2/cat_stat_nanmean(vx_vol)); M = true(size(Yp0)); + M(bbth:end-bbth,bbth:end-bbth,bbth:end-bbth) = 0; + QAS.qualitymeasures.res_BB = sum(Yp0(:)>1.25 & M(:))*prod(abs(vx_vol)); + + % check segmentation + spec = species; for ai=num2str(0:9); spec = strrep(spec,ai,''); end + bvol = species; for ai=char(65:122); bvol = strrep(bvol,ai,''); end; bvol = str2double(bvol); + + subvol = [sum(Yp0(:)>2.5 & Yp0(:)<3.1)*prod(vx_vol)/1000,... + sum(Yp0(:)>1.5 & Yp0(:)<2.5)*prod(vx_vol)/1000,... + sum(Yp0(:)>0.5 & Yp0(:)<1.5)*prod(vx_vol)/1000]; + + if isempty(bvol) + switch spec + case 'human' + bvol = 1400; + otherwise + warning('cat_vol_qa202310:species',... + sprintf('Unknown species %s (C=%0.0f,G=%0.0f,W=%0.0f).',species,subvol)); %#ok + end + end + if sum(subvol)bvol*3 + warning('cat_vol_qa202310:badSegmentation',... + sprintf('Bad %s segmentation (C=%0.0f,G=%0.0f,W=%0.0f).',species,subvol)) %#ok + end + if ~isfield(QAS,'subjectmeasures') + %% in case of external/batch calls + QAS.subjectmeasures.vol_TIV = sum(Yp0(:)>0) .* prod(vx_vol) / 1000; + for i = 1:3 + QAS.subjectmeasures.vol_abs_CGW(i) = sum( Yp0toC(Yp0(:),i)) .* prod(vx_vol) / 1000; + QAS.subjectmeasures.vol_rel_CGW(i) = QAS.subjectmeasures.vol_abs_CGW(i) ./ ... + QAS.subjectmeasures.vol_TIV; + end + end + + if cat_stat_nansum(Yp0(:)>2.5) < 10 + warning('cat_vol_qa202310:badSegmentation',... + sprintf('Bad %s segmentation (C=%0.0f,G=%0.0f,W=%0.0f).',species,subvol)) %#ok + + QAS.qualitymeasures.NCR = nan; + QAS.qualitymeasures.ICR = nan; + QAS.qualitymeasures.ECR = nan; + QAS.qualitymeasures.FEC = nan; + QAS.qualitymeasures.contrast = nan; + QAS.qualitymeasures.contrastr = nan; + QAR = cat_stat_marks('eval',1,QAS); + + if nargout>2, varargout{3} = cat_qa_warnings; end + if nargout>1, varargout{2} = QAR; end + if nargout>0, varargout{1} = QAS; end + + return + end + + + % basic level + if any( vx_vol < .8 ) + mres = 1; ss = min(2,(mres - vx_vol).^2); + + spm_smooth(Yp0, Yp0, ss); + spm_smooth(Ym , Ym , ss); + spm_smooth(Yo , Yo , ss); + + Yp0 = single(cat_vol_resize(Yp0,'interphdr',V,mres,1)); + Ym = single(cat_vol_resize(Ym ,'interphdr',V,mres,1)); + Yo = single(cat_vol_resize(Yo ,'interphdr',V,mres,1)); + + vx_vol = repmat(mres,1,3); %#ok<*RPMT1> + end + + %% estimate QA + % --------------------------------------------------------------- + % remove space arount the brain for speed-up + [Yo,Ym,Yp0] = cat_vol_resize({Yo,Ym,Yp0},'reduceBrain',vx_vol,8,Yp0>1.5); + + % RD20241030: avoid lesions and masking + Y0 = cat_vol_morph(Yo==0,'o',1) | Yp0==0; + Yo(Y0)=nan; Ym(Y0)=nan; Yp0(Y0)=0; + + % Refined segmentation to fix skull-stripping issues in case of bad + % segmentation. Tested on the BWP with simulated segmenation issues + % for skull-stripping as well as WM/CSF over/underestimation. + [Yp0r,resYp0] = cat_vol_resize(Yp0,'reduceV',vx_vol,2,32,'meanm'); + Yp0r = cat_vol_morph(cat_vol_morph(cat_vol_morph(Yp0r>0.9,'de',1.5),'l',[0.5 0.2]),'dd',1.5); + Yp0 = Yp0 .* (cat_vol_resize(Yp0r,'dereduceV',resYp0)>.5); + + % filter blood vessels + Yp0 = cat_vol_median3(Yp0,(Yp0>2 & smooth3(Yp0<=3)) | Ym>1.1,Yp0>1); + + % Fast Euler Characteristic (FEC) + QAS.qualitymeasures.FEC = estimateFEC(Yp0,vx_vol,Ym); + +if 1 + %% rought contast and noise estimation to get a stable T1 map for threshold estimation + T1th = [cat_stat_nanmedian(Ym(Yp0toC(Yp0(:),1)>0.9)) ... + cat_stat_nanmedian(Ym(Yp0toC(Yp0(:),2)>0.9)) ... + cat_stat_nanmedian(Ym(Yp0toC(Yp0(:),3)>0.9))]; + + % Avoid lesions defined as regions (local blobs) with high difference + % between the segmentation and intensity scaled image. Remove these + % areas from the Yp0 map that is not used for volumetric evaluation. + % Use the ATLAS stroke leson dataset for evalution, where the masked + % and unmasked image should result in the same quality ratings. + Ymm = cat_main_gintnorm(Ym,struct('T3th',[0 T1th T1th(end)*2],'T3thx',[0 1 2 3 6])); + Ymd = cat_vol_smooth3X( (Yp0>0) .* abs(Ymm - Yp0/3) , 2); + mdth = cat_stat_nanmedian(Ymd(Ymd(:) > 1.5 * cat_stat_nanmedian(Ymd(Ymd(:)>0)))); + Ymsk = Ymd > mdth; + T1th = [cat_stat_nanmedian(Ym(Yp0toC(Yp0(:),1)>0.9 & ~Ymsk(:) & Ymm(:)<0.35)) ... + cat_stat_nanmedian(Ym(Yp0toC(Yp0(:),2)>0.9 & ~Ymsk(:) )) ... + cat_stat_nanmedian(Ym(Yp0toC(Yp0(:),3)>0.9 & ~Ymsk(:) ))]; + Ymm = cat_main_gintnorm(Ym,struct('T3th',[0 T1th T1th(end)*2],'T3thx',[0 1 2 3 6])); + Ymd = cat_vol_smooth3X( (Yp0>0) .* abs(Ymm - Yp0/3) , 2); + mdth = cat_stat_nanmedian(Ymd(Ymd(:) > 1.5 * cat_stat_nanmedian(Ymd(Ymd(:)>0)))); + Ymsk = Ymd > mdth; + %% + Yp0(Ymsk) = nan; +end + + + + % strongly avoid PVE or non-cortical (thicker GM structures) for tissue peak estimation + Yw2 = cat_vol_morph( Yp0toC(Yp0,3)>0.5 ,'de',2.5, vx_vol ); + Yc2 = cat_vol_morph( Yp0toC(Yp0,1)>0.5 ,'de',2.5, vx_vol ); + Yg2 = Yp0toC(Yp0,2)>0.5 & ~cat_vol_morph( Yp0toC(Yp0,2)>0.5 ,'do',2,vx_vol ); + + % create a inner mask to avoid critical outer or inner regions + voli = @(v) (v ./ (pi * 4./3)).^(1/3); + rad = voli( QAS.subjectmeasures.vol_TIV) ./ cat_stat_nanmean(vx_vol); + Ysc = 1 - cat_vol_smooth3X(Yp0<1.5 | Yo==0,min(24,max(16,rad*2))); % fast 'distance' map to avoid inner or outer areas (eg. to focus on cortex) + Ysc = (Ysc - min(Ysc(Yp0(:)>=1))) / ( max(Ysc(Yp0(:)>=1)) - min(Ysc(Yp0(:)>=1))); % normalization + Ym = Ym ./ cat_stat_nanmedian(Ym(Yw2(:) & Ysc(:)>0.75)) * cat_stat_nanmedian(Yo(Yw2(:) & Ysc(:)>0.75)); % generalize Ym intensity + + % intensity normalized map + Ynwm = cat_vol_morph( Ym < mean( [median(Ym(Yw2(:))), median(Ym(Yg2(:)))] ) , 'o'); % avoid WMHs as values + T0th = [cat_stat_nanmedian(Ym(Yc2(:) & Ysc(:)>0.75)) ... + cat_stat_nanmedian(Ym(Yg2(:) & Ysc(:)<0.75)) ... + cat_stat_nanmedian(Ym(Yw2(:) & ~Ynwm(:) )) ]; + Ymm = cat_main_gintnorm(Ym,struct('T3th',[0 T0th T0th(end)*2],'T3thx',[0 1 2 3 6])); + + % final noise evaluation tissue classes + Yp0w = Yp0toC(Yp0,3)>0.9 & cat_vol_morph( Yp0toC(Yp0,3)>0.5 ,'de',2, vx_vol ); Yp0w(smooth3(Yp0w)<.5) = 0; + Yp0c = Yp0toC(Yp0,1)>0.9 & cat_vol_morph( Yp0toC(Yp0,1)>0.5 ,'de',2, vx_vol ); Yp0c(smooth3(Yp0c)<.5) = 0; + + % denoising + Ymms = Ymm+0; spm_smooth(Ymms,Ymms,repmat(0.8,1,3)); % smoothing to reduce high frequency noise (4 - 16) + noise0 = max(0,min(1.5, 2 * 4 * min( cat_stat_nanstd(Ymm( Yp0w(:) & Ysc(:)>.75 & Ymms(:)>2.5 )) , ... + cat_stat_nanstd(Ymm( Yp0c(:) & Ysc(:)>.75 & Ymms(:)<1.5)) ))); + Ymms = Ymm+0; spm_smooth(Ymms,Ymms,repmat(double(noise0)*4,1,3)); % smoothing to reduce high frequency noise (4 - 16) + + % filter to avoid side effects by PVE/SVD/PVS + Ywm = Yp0w & (Ymms*3 - Yp0) > -max(.15 ,noise0*2); + Ycm = Yp0c & (Ymms*3 - Yp0) < max(.125,noise0.^2) & Ysc>0.75; + Yweb = cat_vol_morph( Yp0toC(Yp0,3)>0.5 ,'de',1.5, vx_vol ) & ... + (Ymms*3 - Yp0) > -max(.5 ,noise0*2) & Yp0toC(Yp0,3)>0.9 & ~Ynwm; % interpolated + + %res_ECR0 = estimateECR0old( Ymm , Yp0 , 1/3:1/3:1, vx_vol.^.5 ); % - noise1/100; + res_ECR0 = estimateECR0( Ymm , Yp0 , 1/3:1/3:1, vx_vol.^.5 ); % - noise1/100; + QAS.qualitymeasures.res_ECR = abs( 2.5 - res_ECR0 * 10 ); + + mix = 1; + Yos = cat_vol_localstat(Ymm,Ywm,1,1); Ymm(Yos>0) = Ymm(Yos>0).*(1-mix) + mix.*Yos(Yos>0); % reduce high frequency noise in WM + Yos = cat_vol_localstat(Ymm,Ycm,1,1); Ymm(Yos>0) = Ymm(Yos>0).*(1-mix) + mix.*Yos(Yos>0); % reduce high frequency noise in CSF + + % adaptation for low-resolution BWP case + mix = max(0,min(1,1 - 0.8*mean(vx_vol-1))); + Yos = cat_vol_localstat(Ymm,Ywm,1,1); Ymm(Yos>0) = Ymm(Yos>0).*(1-mix) + mix.*Yos(Yos>0); % reduce high frequency noise in WM + Yos = cat_vol_localstat(Ymm,Ycm,1,1); Ymm(Yos>0) = Ymm(Yos>0).*(1-mix) + mix.*Yos(Yos>0); % reduce high frequency noise in CSF + + vx_volx = vx_vol; res = 2; + Ywb = cat_vol_resize( ((Yo + min(Yo(:))) .* Yweb) ,'reduceV',vx_volx,res,32,'meanm') - min(Yo(:)); % for WM inhomogeneity estimation (avoid PVE) + Ywn = cat_vol_resize(Ymm .* Ywm,'reduceV',vx_volx,res,32,'meanm'); % for WM noise ################## Ywm better in real data? ########## + Ycn = cat_vol_resize(Ymm .* Ycm,'reduceV',vx_volx,res,32,'meanm'); % for CSF noise + Ycm = cat_vol_resize(Ycm ,'reduceV',vx_volx,res,32,'meanm'); % CSF thr. (minimum to avoid PVE) + Ywm = cat_vol_resize(Ywm ,'reduceV',vx_volx,res,32,'meanm'); % WM thr. and bias correction (Ywme) + Ywe = cat_vol_resize(Yweb ,'reduceV',vx_volx,res,32,'meanm'); % WM thr. and bias correction (Ywme) + + % only voxel that were the product of + Ywn = Ywn .* (Ywm>=0.5); Ycn = Ycn .* (Ycm>=0.5); Ywb = Ywb .* (Ywe>=0.5); + + clear Ycm Ygm Ywm Ywme; + [Yo,Ym,Ymi,Yp0,resr] = cat_vol_resize({Yo,Ym,Ymm, Yp0},'reduceV',vx_volx,res,32,'meanm'); + resr.vx_volo = vx_vol; vx_vol=resr.vx_red .* resr.vx_volo; + + clear WIs ; + + + % estimate background + [Ymir,resYbg] = cat_vol_resize(Ymi,'reduceV',1,6,32,'meanm'); + try + warning 'off' 'MATLAB:cat_vol_morph:NoObject' + BGCth = min(T0th)/2; + Ybgr = cat_vol_morph(cat_vol_morph(Ymir0.5; clear Yosr Ybgr; + if sum(Ybg(:))<32, Ybg = cat_vol_morph(Yo0.5; clear Yosr Ybgr; + if sum(Ybg(:))<32, Ybg = cat_vol_morph(YoT0th(2) + QAS.qualitymeasures.tissue_weighting = 'T1'; + elseif T0th(3)0.5 & ~isinf(Yp0(:)))); + end + QAS.qualitymeasures.tissue_stdr = QAS.qualitymeasures.tissue_std ./ (T0th(3)-BGth); + + % (relative) (mininum) tissue contrast ( CSF-GM-WM ) + % - the CSF threshold varies strongly due to bad segmentations, + % and anatomica variance, so its better to use GM-WM contrast + % and take care of overoptimisation with values strongly >1/3 + % of the relative contrast + contrast = min(abs(diff(QAS.qualitymeasures.tissue_mn(1:4)))) ./ ... + abs(diff([min([T0th(1),BGth]),max([T0th(3),T0th(2)])])); % default contrast + contrast = contrast + min(0,13/36 - contrast)*1.2; % avoid overoptimsization + QAS.qualitymeasures.contrast = contrast * (max([T0th(3),T0th(2)])); + QAS.qualitymeasures.contrastr = contrast; + + + + %% noise estimation (original (bias corrected) image) + % WM variance only in one direction to avoid WMHs! + rms=1; nb=1; exnoise = 1; + NCww = sum(Ywn(:)>0) * prod(vx_vol); + NCwc = sum(Ycn(:)>0) * prod(vx_vol); + [Yos2,YM2,redn] = cat_vol_resize({Ywn,Ywn>0},'reduceV',vx_vol,2,16,'meanm');% RD20241107: was 4 + %spm_smooth(Yos,Yos,.5./redn.vx_volr); Yos = Yos * log(8); + NCRw = estimateNoiseLevel(Yos2,YM2>0.5,nb,rms); + if exnoise && sum(vx_volx<2)>0 % only if enough averaging was done before + Yos2 = cat_vol_localstat(Yos2,YM2>0.5,1,1); + NCRw = mean([NCRw,0.8 * log(27) * estimateNoiseLevel(Yos2,YM2>0.5,nb,rms)]) ; + Yos2 = cat_vol_localstat(Yos2,YM2>0.5,1,1); + NCRw = mean([NCRw,0.8 * log(5^3) * estimateNoiseLevel(Yos2,YM2>0.5,nb,rms)]) ; + end + if BGth<-0.1 && T0th(3)<3, NCRw=NCRw/3; end% MT weighting + clear Yos0 Yos1 Yos2 YM0 YM1 YM2; + + % CSF variance of large ventricle + % for typical T2 images we have too much signal in the CSF and can't use it for noise estimation! + wcth = 200; + if T0th(1)wcth + [Yos2,YM2] = cat_vol_resize({Ycn,Ycn>0},'reduceV',vx_vol,2,16,'meanm'); % RD20241107: was 4 + %spm_smooth(Yos2,Yos2,.5./redn.vx_volr); Yos2 = Yos2 * log(8); + NCRc = estimateNoiseLevel(Yos2,YM2>0.5,nb,rms); + if exnoise && sum(vx_volx<2)>0 % only if enough averaging was done before + Yos2 = cat_vol_localstat(Yos2,YM2>0.5,1,1); + NCRc = mean([NCRc,0.8 * log(27) * estimateNoiseLevel(Yos2,YM2>0.5,nb,rms)]) ; + end + clear Yos0 Yos1 Yos2 YM0 YM1 YM2; + else + NCRc = 0; + NCwc = 0; + end + % 1/sqrt(volume) to compensate for noise differency due to different volumen size. + % Overall there are better chances to correct high resolution noise. + % Nitz W R. Praxiskurs MRT. Page 28. + NCwc = min(wcth,max(0,NCwc - wcth)); NCww = min(wcth,NCww) - NCwc; % use CSF if possible + if NCwc<3*wcth && NCww<10*wcth, NCRc = min(NCRc,NCRw); end + QAS.qualitymeasures.NCR = (NCRw*NCww + NCRc*NCwc) / (NCww+NCwc) * 9; + +% ???? + %res_ECR0 = res_ECR0 - ( (res_ECR0 - 0.15) * 10)*QAS.qualitymeasures.NCR / 9; + %QAS.qualitymeasures.res_ECR = abs( 2.5 - res_ECR0 * 10 ); + + %% Bias/Inhomogeneity (original image with smoothed WM segment) + [Yosm,Yosm2] = cat_vol_resize({Ywb,Ywb>0},'reduceV',vx_vol,4,8,'meanm'); Yosm(Yosm2<0.5) = 0; Yosmm = Yosm~=0; % resolution and noise reduction + for si=1:1, mth = min(Yosm(:)) + 1; Yosm = cat_vol_localstat(Yosm + mth,Yosmm,1,1) - mth; end + QAS.qualitymeasures.ICR = cat_stat_nanstd(Yosm(Yosm(:)>0)) / max(T0th(2),T0th(3)) / contrast; + + %% marks + QAR = cat_stat_marks('eval',1,QAS); + + % export + if opt.write_xml + QAS.qualityratings = QAR.qualityratings; + QAS.subjectratings = QAR.subjectratings; + QAS.ratings_help = QAR.help; + + cat_io_xml(fullfile(pp0,[opt.prefix ff '.xml']),QAS,'write'); + end + + clear Yi Ym Yo Yos Ybc + clear Ywm Ygm Ycsf Ybg + + if nargout>2, varargout{3} = cat_qa_warnings; end + if nargout>1, varargout{2} = QAR; end + if nargout>0, varargout{1} = QAS; end + +end +%======================================================================= +function def=defaults + % default parameter + def.verb = 2; % verbose level [ 0=nothing | 1=points | 2*=results ] + def.write_csv = 2; % final cms-file [ 0=dont write |1=write | 2=overwrite ] + def.write_xml = 1; % images base xml-file + def.sortQATm = 1; % sort QATm output + def.orgval = 0; % original QAM results (no marks) + def.avgfactor = 2; % + def.prefix = 'cat_'; % intensity scaled image + def.mprefix = 'm'; % prefix of the preprocessed image + def.process = 3; % used image [ 0=T1 | 1=mT1 | 2=avg | 3=both ] + def.calc_MPC = 0; + def.calc_STC = 0; + def.calc_MJD = 0; + def.method = 'spm'; + def.snspace = [100,7,3]; + def.nogui = exist('XT','var'); + def.MarkColor = cat_io_colormaps('marks+',40); +end + +function noise = estimateNoiseLevel(Ym,YM,r,rms,vx_vol) +% ---------------------------------------------------------------------- +% noise estimation within Ym and YM. +% ---------------------------------------------------------------------- + if ~exist('vx_vol','var') + vx_vol=[1 1 1]; + end + if ~exist('r','var') + r = 1; + else + r = min(10,max(max(vx_vol),r)); + end + if ~exist('rms','var') + rms = 1; + end + + Ysd = cat_vol_localstat(single(Ym),YM,r,4); + noise = cat_stat_nanstat1d(Ysd(YM).^rms,'median').^(1/rms); +end +%======================================================================= +function res_ECR = estimateECR0old(Ym,Yp0,Tth,vx_vol) +%% estimateECR. Quanfify anatomical details by the normalized edge strength. +% +% old pure version for high quality segmentation input that works only well +% for the CAT12 AMAP segmenation + +% extend step by step by some details (eg. masking of problematic regions + Ygrad = cat_vol_grad(max(Tth(2),min(1,Ym) .* (Yp0>0) ) , vx_vol ); + res_ECR = cat_stat_nanmedian(Ygrad(Yp0(:)>2.05 & Yp0(:)<2.95)); + +end +%======================================================================= +%======================================================================= +%======================================================================= +function [res_ECR,segCase,Yp0c,Ygrad] = estimateECR0(Ym,Yp0,Tth,vx_vol) +%% estimateECR. Quanfify anatomical details by the normalized edge strength. +% +% old pure version for high quality segmentation input that works only well +% for the CAT12 AMAP segmenation. +% +% Extension 202309: Tested at eroded and dilated boundaries positions + + + Yb = Yp0>0; + Yp0c = Yp0; + Ybad = abs(Yp0/3 - Ym) > .5 | isnan(Ym) | isnan(Yp0); % | (cat_vol_morph(Yp0<1.25,'d') & cat_vol_morph(Yp0>2.75,'d')); +if 0 + Ym = max(Ym ,cat_vol_localstat(Ym ,Yp0>1 & ~Ybad,1,3)); + Yp0 = max(Yp0,cat_vol_localstat(Yp0,Yp0>1 & ~Ybad,1,3)); +end + %spm_smooth(Ym,Ym,.5); + Yp0s = Yp0+0; spm_smooth(Yp0s,Yp0s,1./vx_vol); + Ywmb = Yp0s>2.05 & Yp0s<2.95; + + Yms = Ym .* Ywmb; + cat_sanlm(Yms,3,1); + Ym(Ywmb) = Yms(Ywmb); + + %Ygrad = cat_vol_grad(max(Tth(2),min(1,Yp0/3) .* Yb ) , vx_vol ); + %Ygrad = cat_vol_grad(max(Tth(2),min(1,Ym/2 + Yp0/6) .* Yb ) , vx_vol ); + Ygrad = cat_vol_grad(max(Tth(2),min(1,Ym) .* Yb ) , vx_vol ); % RD20241106: original + Ygrad(cat_vol_morph(Ybad,'d',1)) = nan; % correct bad areas + + %Ygrad = cat_vol_localstat(Ygrad,Ywmb>0,1,1); + + res_ECRo = cat_stat_nanmedian(Ygrad(Ywmb(:))); % & Yb(:)) + clear Ywmb + Yp0(Ybad) = nan; + + %% == EXTENSION 202309 == + % * test for segmentation errors by using gray-scale erosion + % * if the WM was overestimated than use the new boundary and export + Yp0e = cat_vol_morph(max(1,Yp0),'gerode'); + Ywmeb = Yp0e>2.05 & Yp0e<2.95 & ~Ybad; + Ywmebm = Yp0 >2.475 & Yp0e<2.525 & ~Ybad; + res_ECRe = cat_stat_nanmedian(Ygrad(Ywmeb(:))); clear Ywmeb + res_ECRem = cat_stat_nanmedian(Ygrad(Ywmebm(:))); clear Ywmebm + [res_ECR,segCase] = max([ res_ECRo , res_ECRem, res_ECRe]); + + test2 = 0; + if segCase == 1 && ( max(res_ECRe,res_ECRem) * 1.05 < res_ECR ) + %% in case of no WM overestimation test for underestimation + Yp0d = cat_vol_morph(Yp0,'gdilate'); + Ywmdb = Yp0d>2.05 & Yp0d<2.95 & Yp0>=1.75 & ~Ybad; + Ywmdbm = Yp0d>2.475 & Yp0 <2.525 & Yp0>=1.75 & ~Ybad; + res_ECRd = cat_stat_nanmedian(Ygrad(Ywmdb(:))); clear Ywmdb + res_ECRdm = cat_stat_nanmedian(Ygrad(Ywmdbm(:))); clear Ywmdbm + + [res_ECR,segCase] = max([ res_ECRo , res_ECRe, res_ECRe, res_ECRe, res_ECRe, res_ECRdm, res_ECRd]); + + % corrected segmentation + if test2 && segCase >= 6 + Yp0d2 = cat_vol_morph(Yp0d,'gdilate'); + Ywmdb = Yp0d2>2.05 & Yp0d2<2.95 & Yp0>=1.75 & ~Ybad; + Ywmdbm = Yp0d2>2.475 & Yp0d <2.525 & Yp0>=1.75 & ~Ybad; + res_ECRd2 = cat_stat_nanmedian(Ygrad(Ywmdb(:))); clear Ywmdb + res_ECRd2m = cat_stat_nanmedian(Ygrad(Ywmdbm(:))); clear Ywmdbm + [res_ECR,segCase] = max([ res_ECRo , res_ECRe, res_ECRe, res_ECRe, ... + res_ECRe, res_ECRdm, res_ECRd, res_ECRd2m, res_ECRd2]); + end + if segCase >=6 && segCase <= 7 + Yp0c(Yp0>=2) = Yp0d(Yp0>=2); + elseif test2 && segCase >7 + Yp0c(Yp0>=2) = Yp0d2(Yp0>=2); + end + else + if test2 + Yp0e2 = cat_vol_morph(Yp0e,'gerode'); + Ywmeb = Yp0e2>2.05 & Yp0e2<2.95 & ~Ybad; + Ywmebm = Yp0e >2.475 & Yp0e2<2.525 & ~Ybad; + res_ECRe2 = cat_stat_nanmedian(Ygrad(Ywmeb(:))); % & Yb(:)) + res_ECRe2m = cat_stat_nanmedian(Ygrad(Ywmebm(:))); % & Yb(:)) + + [res_ECR,segCase] = max([ res_ECRo , res_ECRem, res_ECRe, res_ECRe2m, res_ECRe2]); + end + + % corrected segmentation + if segCase >=2 && segCase <= 3 + Yp0c(Yp0>2) = Yp0e(Yp0>2); + elseif test2 && segCase > 3 + Yp0c(Yp0>2) = Yp0e2(Yp0>2); + end + end + + + + + +%% == EXTENSION 202309 CSF == +if 0 + Ygradc = cat_vol_grad(min(Tth(2),max(Tth(1),Ym) .* Yb ) , vx_vol ); + + + % * test for segmentation errors by using gray-scale erosion + % * if the WM was overestimated than use the new boundary and export + %Yp0e = cat_vol_morph(Yp0,'gerode'); + Ycmeb = Yp0e>1.05 & Yp0e<1.95 & Yp0>=1 & ~Ybad; + Ycmebm = Yp0 >1.475 & Yp0e<1.525 & Yp0>=1 & ~Ybad; + res_ECRe = cat_stat_nanmedian(Ygradc(Ycmeb(:))); clear Ywmeb + res_ECRem = cat_stat_nanmedian(Ygradc(Ycmebm(:))); clear Ywmebm + [res_ECRC,segCaseC] = max([ res_ECRo , res_ECRem, res_ECRe]); + + test2 = 0; + if segCaseC == 1 && ( max(res_ECRe,res_ECRem) * 1.05 < res_ECRC ) + %% in case of no CSF underestimation test for overestimation + if ~exist('Yp0d','var') + Yp0d = cat_vol_morph(Yp0,'gdilate'); + end + Ycmdb = Yp0d>1.05 & Yp0d<1.95 & Yp0<2.25 & Yp0>=1 & ~Ybad; + Ycmdbm = Yp0d>1.475 & Yp0 <1.525 & Yp0<2.25 & Yp0>=1 & ~Ybad; + res_ECRd = cat_stat_nanmedian(Ygradc(Ycmdb(:))); clear Ywmdb + res_ECRdm = cat_stat_nanmedian(Ygradc(Ycmdbm(:))); clear Ywmdbm + + [res_ECRC,segCaseC] = max([ res_ECRo , res_ECRe, res_ECRe, res_ECRe, res_ECRe, res_ECRdm, res_ECRd]); + + % corrected segmentation + if test2 && segCase >= 6 + if ~exist('Yp0d2','var') + Yp0d2 = cat_vol_morph(Yp0d,'gdilate'); + end + Ywmdb = Yp0d2>2.05 & Yp0d2<2.95 & Yp0>=1.75 & ~Ybad; + Ywmdbm = Yp0d2>2.475 & Yp0d <2.525 & Yp0>=1.75 & ~Ybad; + res_ECRd2 = cat_stat_nanmedian(Ygradc(Ywmdb(:))); clear Ywmdb + res_ECRd2m = cat_stat_nanmedian(Ygradc(Ywmdbm(:))); clear Ywmdbm + [res_ECR,segCase] = max([ res_ECRo , res_ECRe, res_ECRe, res_ECRe, ... + res_ECRe, res_ECRdm, res_ECRd, res_ECRd2m, res_ECRd2]); + end + if segCase >=6 && segCase <= 7 + Yp0c(Yp0>=1 & Yp0<2) = Yp0d(Yp0>=1 & Yp0<2); + elseif test2 && segCase >7 + Yp0c(Yp0>=1 & Yp0<2) = Yp0d2(Yp0>=1 & Yp0<2); + end + else + if test2 + if ~exist('Yp0e2','var') + Yp0e2 = cat_vol_morph(Yp0e,'gerode'); + end + Ywmeb = Yp0e2>2.05 & Yp0e2<2.95 & ~Ybad; + Ywmebm = Yp0e >2.475 & Yp0e2<2.525 & ~Ybad; + res_ECRe2 = cat_stat_nanmedian(Ygradc(Ywmeb(:))); % & Yb(:)) + res_ECRe2m = cat_stat_nanmedian(Ygradc(Ywmebm(:))); % & Yb(:)) + + [res_ECR,segCase] = max([ res_ECRo , res_ECRem, res_ECRe, res_ECRe2m, res_ECRe2]); + end + + % corrected segmentation + if segCaseC >=2 && segCaseC <= 3 + Yp0c(Yp0>1 & Yp0<2) = Yp0e(Yp0>1 & Yp0<2); + elseif test2 && segCaseC > 3 + Yp0c(Yp0>1 & Yp0<2) = Yp0e2(Yp0>1 & Yp0<2); + end + end +end + + +end +%======================================================================= +function [FEC,WMarea] = estimateFEC(Yp0,vx_vol,Ymm,V,machingcubes) +%estimateFEC. Fast Euler Characteristic (FEC) + + if ~exist('machingcubes','var'), machingcubes = 1; end +%{ + Yp0s = Yp0+0; spm_smooth(Yp0s,Yp0s,1./vx_vol); + Ywmb = Yp0s>2.05 & Yp0s<2.95; + + Yms = Ymm .* Ywmb; + cat_sanlm(Yms,3,1); + Ymm(Ywmb) = Yms(Ywmb); +%} + %% + Ymsr = (Ymm*3); + spm_smooth(Ymsr,Ymsr,.4./vx_vol); % correct voxel noise + + + %Ymsr = Yp0; + app = 1; + if app == 1 + sth = 0.125:0.125:0.5; % two levels for 5 class AMAP + Ymsr = max(0,cat_vol_localstat(Ymsr,Yp0>.5,1,3) - 2); + elseif app == 2 + sth = .5; + Ymsr = cat_vol_median3(Yp0,Yp0>2,Yp0>1); + [Ygmt,Ymsr] = cat_vol_pbtsimple(Ymsr,vx_vol,... + struct('levels',1,'extendedrange',0,'gyrusrecon',0,'keepdetails',0,'sharpening',0)); + else + % FEC by creating of the WM like brain tissue of the full brain. + if isempty(Ymm) % use the segmentation works very well + sth = 0.25:0.5:0.75; % two levels for 5 class AMAP + Ymsr = Ymsr - 2; + else % using raw data not realy + sth = 0.25:0.25:0.75; + Ymsr = max(-2,(Ymm .* (smooth3(Ymsr)>1) * 3) - 2); + end + end + + % denoising of maximum filter + spm_smooth(Ymsr,Ymsr,.4./vx_vol); + + % use 2 mm is more robust (accurate in a sample) + smeth = 1; + if smeth==1 + [Ymsr,resYp0] = cat_vol_resize(Ymsr,'reduceV',vx_vol,2,32,'meanm'); + elseif smeth==2 + spm_smooth(Ymsr , Ymsr , 2 - vx_vol); V.dim = size(Ymsr); + Ymsr = single(cat_vol_resize(Ymsr,'interphdr',V,2,1)); + resYp0.vx_volr = [2 2 2]; + else + % this is + spm_smooth(Ymsr,Ymsr,2 ./ vx_vol); % not required + resYp0.vx_volr = vx_vol; + end + + EC = zeros(size(sth)); area = EC; + for sthi = 1:numel(sth) + % remove other objects and holes + if app == 2 + Ymsr(Ymsr> sth(sthi) & ~cat_vol_morph(Ymsr> sth(sthi),'lo',1,vx_vol)) = sth(sthi) - 0.01; % avoid BVs (eg. in ABIDE2) + else + Ymsr(Ymsr> sth(sthi) & ~cat_vol_morph(Ymsr> sth(sthi),'l')) = sth(sthi) - 0.01; % avoid BVs (eg. in ABIDE2) + end + Ymsr(Ymsr<=sth(sthi) & ~cat_vol_morph(Ymsr<=sth(sthi),'l')) = sth(sthi) + 0.01; + + if machingcubes + % faster binary approach on the default resolution, quite similar result + txt = evalc('[~,faces,vertices] = cat_vol_genus0(Ymsr,sth(sthi),1);'); + CS = struct('faces',faces,'vertices',vertices); + else + % slower but finer matlab isosurface + CS = isosurface(Ymsr,sth(sthi)); + end + if numel(CS.vertices)>0 + CS.vertices = CS.vertices .* repmat(resYp0.vx_volr,size(CS.vertices,1),1); + EC(sthi) = ( size(CS.vertices,1) + size(CS.faces,1) - size(spm_mesh_edges(CS),1) - 2) + 2; + area(sthi) = spm_mesh_area(CS) / 100; % cm2 + EC(sthi) = EC(sthi); + else + area(sthi) = nan; + EC(sthi) = nan; + end + end + + FEC = cat_stat_nanmean(abs(EC - 2) + 2) / log(area(1)/2500 + 1); % defined on the seg-error phantom + FEC = FEC / 2 ; + WMarea = area(1); +end +%======================================================================= + +%======================================================================= +function [res_ECR,segCase,Yp0c,Ygrad] = estimateECR0_old(Ym,Yp0,Tth,vx_vol) +%% estimateECR. Quanfify anatomical details by the normalized edge strength. +% +% old pure version for high quality segmentation input that works only well +% for the CAT12 AMAP segmenation. +% +% Extension 202309: Tested at eroded and dilated boundaries positions + +% extend step by step by some details (eg. masking of problematic regions +%& Ygrad(:)<1/3 +% Yb = cat_vol_morph(cat_vol_morph(Yp0>2,'l',[10 0.1]),'d',2); + + Yb = Yp0>0; + Yp0c = Yp0; + Ygrad = cat_vol_grad(max(Tth(2),min(1,Ym) .* Yb ) , vx_vol ); + Ywmb = Yp0>2.05 & Yp0<2.95; + res_ECRo = cat_stat_nanmedian(Ygrad(Ywmb(:))); % & Yb(:)) + clear Ywmb + + + %% == EXTENSION 202309 == + % * test for segmentation errors by using gray-scale erosion + % * if the WM was overestimated than use the new boundary and export + Yp0e = cat_vol_morph(max(1,Yp0),'gerode'); + Ywmeb = Yp0e>2.05 & Yp0e<2.95; + Ywmebm = Yp0 >2.475 & Yp0e<2.525; + res_ECRe = cat_stat_nanmedian(Ygrad(Ywmeb(:))); clear Ywmeb + res_ECRem = cat_stat_nanmedian(Ygrad(Ywmebm(:))); clear Ywmebm + [res_ECR,segCase] = max([ res_ECRo , res_ECRem, res_ECRe]); + + test2 = 1; + if segCase == 1 && ( max(res_ECRe,res_ECRem) * 1.05 < res_ECR ) + %% in case of no WM overestimation test for underestimation + Yp0d = cat_vol_morph(Yp0,'gdilate'); + Ywmdb = Yp0d>2.05 & Yp0d<2.95 & Yp0>=1.75; + Ywmdbm = Yp0d>2.475 & Yp0 <2.525 & Yp0>=1.75; + res_ECRd = cat_stat_nanmedian(Ygrad(Ywmdb(:))); clear Ywmdb + res_ECRdm = cat_stat_nanmedian(Ygrad(Ywmdbm(:))); clear Ywmdbm + + [res_ECR,segCase] = max([ res_ECRo , res_ECRe, res_ECRe, res_ECRe, res_ECRe, res_ECRdm, res_ECRd]); + + % corrected segmentation + if test2 && segCase >= 6 + Yp0d2 = cat_vol_morph(Yp0d,'gdilate'); + Ywmdb = Yp0d2>2.05 & Yp0d2<2.95 & Yp0>=1.75; + Ywmdbm = Yp0d2>2.475 & Yp0d <2.525 & Yp0>=1.75; + res_ECRd2 = cat_stat_nanmedian(Ygrad(Ywmdb(:))); clear Ywmdb + res_ECRd2m = cat_stat_nanmedian(Ygrad(Ywmdbm(:))); clear Ywmdbm + [res_ECR,segCase] = max([ res_ECRo , res_ECRe, res_ECRe, res_ECRe, ... + res_ECRe, res_ECRdm, res_ECRd, res_ECRd2m, res_ECRd2]); + end + if segCase >=6 && segCase <= 7 + Yp0c(Yp0>=2) = Yp0d(Yp0>=2); + elseif test2 && segCase >7 + Yp0c(Yp0>=2) = Yp0d2(Yp0>=2); + end + else + if test2 + Yp0e2 = cat_vol_morph(Yp0e,'gerode'); + Ywmeb = Yp0e2>2.05 & Yp0e2<2.95; + Ywmebm = Yp0e >2.475 & Yp0e2<2.525; + res_ECRe2 = cat_stat_nanmedian(Ygrad(Ywmeb(:))); % & Yb(:)) + res_ECRe2m = cat_stat_nanmedian(Ygrad(Ywmebm(:))); % & Yb(:)) + + [res_ECR,segCase] = max([ res_ECRo , res_ECRem, res_ECRe, res_ECRe2m, res_ECRe2]); + end + + % corrected segmentation + if segCase >=2 && segCase <= 3 + Yp0c(Yp0>2) = Yp0e(Yp0>2); + elseif test2 && segCase > 3 + Yp0c(Yp0>2) = Yp0e2(Yp0>2); + end + end + + + + + +%% == EXTENSION 202309 CSF == +if 1 + Ygradc = cat_vol_grad(min(Tth(2),max(Tth(1),Ym) .* Yb ) , vx_vol ); + + + % * test for segmentation errors by using gray-scale erosion + % * if the WM was overestimated than use the new boundary and export + %Yp0e = cat_vol_morph(Yp0,'gerode'); + Ycmeb = Yp0e>1.05 & Yp0e<1.95 & Yp0>=1; + Ycmebm = Yp0 >1.475 & Yp0e<1.525 & Yp0>=1; + res_ECRe = cat_stat_nanmedian(Ygradc(Ycmeb(:))); clear Ywmeb + res_ECRem = cat_stat_nanmedian(Ygradc(Ycmebm(:))); clear Ywmebm + [res_ECRC,segCaseC] = max([ res_ECRo , res_ECRem, res_ECRe]); + + test2 = 0; + if segCaseC == 1 && ( max(res_ECRe,res_ECRem) * 1.05 < res_ECRC ) + %% in case of no CSF underestimation test for overestimation + if ~exist('Yp0d','var') + Yp0d = cat_vol_morph(Yp0,'gdilate'); + end + Ycmdb = Yp0d>1.05 & Yp0d<1.95 & Yp0<2.25 & Yp0>=1; + Ycmdbm = Yp0d>1.475 & Yp0 <1.525 & Yp0<2.25 & Yp0>=1; + res_ECRd = cat_stat_nanmedian(Ygradc(Ycmdb(:))); clear Ywmdb + res_ECRdm = cat_stat_nanmedian(Ygradc(Ycmdbm(:))); clear Ywmdbm + + [res_ECRC,segCaseC] = max([ res_ECRo , res_ECRe, res_ECRe, res_ECRe, res_ECRe, res_ECRdm, res_ECRd]); + + % corrected segmentation + if test2 && segCase >= 6 + if ~exist('Yp0d2','var') + Yp0d2 = cat_vol_morph(Yp0d,'gdilate'); + end + Ywmdb = Yp0d2>2.05 & Yp0d2<2.95 & Yp0>=1.75; + Ywmdbm = Yp0d2>2.475 & Yp0d <2.525 & Yp0>=1.75; + res_ECRd2 = cat_stat_nanmedian(Ygradc(Ywmdb(:))); clear Ywmdb + res_ECRd2m = cat_stat_nanmedian(Ygradc(Ywmdbm(:))); clear Ywmdbm + [res_ECR,segCase] = max([ res_ECRo , res_ECRe, res_ECRe, res_ECRe, ... + res_ECRe, res_ECRdm, res_ECRd, res_ECRd2m, res_ECRd2]); + end + if segCase >=6 && segCase <= 7 + Yp0c(Yp0>=1 & Yp0<2) = Yp0d(Yp0>=1 & Yp0<2); + elseif test2 && segCase >7 + Yp0c(Yp0>=1 & Yp0<2) = Yp0d2(Yp0>=1 & Yp0<2); + end + else + if test2 + if ~exist('Yp0e2','var') + Yp0e2 = cat_vol_morph(Yp0e,'gerode'); + end + Ywmeb = Yp0e2>2.05 & Yp0e2<2.95; + Ywmebm = Yp0e >2.475 & Yp0e2<2.525; + res_ECRe2 = cat_stat_nanmedian(Ygradc(Ywmeb(:))); % & Yb(:)) + res_ECRe2m = cat_stat_nanmedian(Ygradc(Ywmebm(:))); % & Yb(:)) + + [res_ECR,segCase] = max([ res_ECRo , res_ECRem, res_ECRe, res_ECRe2m, res_ECRe2]); + end + + % corrected segmentation + if segCaseC >=2 && segCaseC <= 3 + Yp0c(Yp0>1 & Yp0<2) = Yp0e(Yp0>1 & Yp0<2); + elseif test2 && segCaseC > 3 + Yp0c(Yp0>1 & Yp0<2) = Yp0e2(Yp0>1 & Yp0<2); + end + end +end + + +end +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_parallelize.m",".m","32216","723","function varargout = cat_parallelize(job,func,datafield) +% ______________________________________________________________________ +% Function to parallelize other functions with job structure, by the +% following call: +% +% +% ... further initialization code +% +% % split job and data into separate processes to save computation time +% if isfield(job,'nproc') && job.nproc>0 && (~isfield(job,'process_index')) +% if nargout==1 +% varargout{1} = cat_parallelize(job,mfilename,'data_surf'); +% else +% cat_parallelize(job,mfilename,'data_surf'); +% end +% return +% elseif isfield(job,'printPID') && job.printPID +% cat_display_matlab_PID +% end +% +% % new banner +% if isfield(job,'process_index'), spm('FnBanner',mfilename); end +% +% % add system dependent extension to CAT folder +% if ispc +% job.CATDir = [job.CATDir '.w32']; +% elseif ismac +% job.CATDir = [job.CATDir '.maci64']; +% elseif isunix +% job.CATDir = [job.CATDir '.glnx86']; +% end +% +% ... main code +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +%#ok<*STRIFCND,*STREMP,*STRCL1> % MATLAB contains function +%#ok<*ASGLU> + + def.verb = cat_get_defaults('extopts.verb'); + def.lazy = 0; % reprocess exist results + def.debug = cat_get_defaults('extopts.verb')>2; + def.getPID = 2; + job.CATDir = fullfile(fileparts(mfilename('fullpath')),'CAT'); + job.fsavgDir = fullfile(fileparts(mfilename('fullpath')),'templates_surfaces'); + + job = cat_io_checkinopt(job,def); + + if ~exist('datafield','var'), datafield = 'data'; end + + % rescue original subjects + job_data = job.(datafield); + if isstruct(job.(datafield)) + n_subjects = numel(job.(datafield)); + data = job.(datafield); + elseif iscell(job.(datafield){1}) + n_subjects = numel(job.(datafield){1}); + data = job.(datafield){1}; + else + n_subjects = numel(job.(datafield)); + data = job.(datafield); + end + if job.nproc > n_subjects + job.nproc = n_subjects; + end + job.process_index = cell(job.nproc,1); + job.verb = 1; + + + % initial splitting of data + for i=1:job.nproc + job.process_index{i} = (1:job.nproc:(n_subjects-job.nproc+1))+(i-1); + end + + + % check if all data are covered + for i=1:rem(n_subjects,job.nproc) + job.process_index{i} = [job.process_index{i} n_subjects-i+1]; + end + + + % If one of the input directories is a BIDS directory than use create a + % subfolder derivatives/CAT12.#/log to save the log-files there and not + % somewhere. A try catch block is used in case of untested input (e.g., + % structures). See also for a similar block in cat_run. + try + % Get the first input file path + BIDSdir_candidates = spm_str_manip(data,'h'); + BIDSdir = []; + + % Try to find dataset root by looking for subject folders (sub- or sub_) + for bdi = 1:numel(BIDSdir_candidates) + if isempty(BIDSdir_candidates{bdi}), continue; end + + ppath = BIDSdir_candidates{bdi}; + % Split path and find last folder starting with 'sub-' or 'sub_' + parts = strsplit(ppath, filesep); + for pi = length(parts):-1:1 + if ~isempty(parts{pi}) && (strncmp(parts{pi}, 'sub-', 4) || strncmp(parts{pi}, 'sub_', 4)) + % Found subject folder - reconstruct dataset root (parent of sub-* folder) + ind = strfind(ppath, [filesep parts{pi}]); + if ~isempty(ind) + ind = ind(end); + dataset_root = ppath(1:ind-1); + % Build derivatives path using CAT12 version + [cat_ver, cat_rel] = cat_version; + BIDSdir = fullfile(dataset_root, 'derivatives', [cat_ver '_' cat_rel]); + break; + end + end + end + if ~isempty(BIDSdir), break; end + end + catch + BIDSdir = []; + end + if ~isempty(BIDSdir) + logdir = fullfile(BIDSdir,'log'); + if ~exist(logdir,'dir'), mkdir(logdir); end + else + logdir = []; + end + % Another thing that we want to avoid is to fill some of the SPM + % directories and just write in a ../spm12/toolbox/cat12/log subdirectory. + % Do not forget that this is only about the additional log files and + % not real data output. If there are no writing permissions in the directory + % the same is probably true for other SPM dirs and the user has to change + % the working directory anyway. + if isempty(logdir) + try + SPMdir = spm_str_manip(data,'h'); + SPMdiri = find(~cellfun('isempty',SPMdir),1); + if ~isempty(SPMdiri) +% logdir = fullfile(fileparts(mfilename('fullpath')),'logs'); % log already exist as file + logdir = 'logs'; % log already exist as file + if ~exist(logdir,'dir') + try + mkdir(logdir); + catch + error('cat_parallelize:CATlogs',['Cannot create directory for logs. \n' ... + 'Please choose another working directory with writing permissions to save the log-files. ']); + end + end + else + logdir = []; + end + catch + logdir = []; + end + end + if ~isempty(logdir) && job.verb + if ~isempty(BIDSdir) + cat_io_cprintf('n', ['\nFound a CAT12 BIDS directory in the given ' ... + 'pathnames and save the log file there:\n']); + cat_io_cprintf('blue','%s\n\n', logdir); + else + cat_io_cprintf('n', ['\nYou working directory is in the SPM12/CAT12 ' ... + 'path, where log files saved here:\n']); + cat_io_cprintf('blue','%s\n\n', logdir); + end + end + + + + tmp_array = cell(job.nproc,1); + logdate = datestr(now,'YYYYmmdd_HHMMSS'); + PID = zeros(1,job.nproc); + %catSID = zeros(1,job.nproc); + SID = cell(1,job.nproc); + for i=1:job.nproc + jobo = job; + + fprintf('Running job %d (with datafield 1):\n',i); + if isstruct(job.(datafield)) + job.(datafield) = job_data(job.process_index{i}); + elseif iscell(job.(datafield){1}) + for fi=1:numel(job_data{1}(job.process_index{i})) + fprintf(' %s\n',spm_str_manip(char(job_data{1}(job.process_index{i}(fi))),'a78')); + end + for ix=1:numel(job_data) + job.(datafield){ix} = job_data{ix}(job.process_index{i}); + end + else + for fi=1:numel(job_data(job.process_index{i})) + fprintf(' %s\n',spm_str_manip(char(job_data(job.process_index{i}(fi))),'a78')); + end + job.(datafield) = job_data(job.process_index{i}); + end + + + job.verb = 1; + job.printPID = 1; + % temporary name for saving job information + tmp_name = [tempname '.mat']; + tmp_array{i} = tmp_name; + global defaults cat; %#ok + spm12def = defaults; + cat12def = cat; + save(tmp_name,'job','spm12def','cat12def'); + clear spm12def cat12; + + % matlab command, cprintferror=1 for simple printing + if nargout + %% + matlab_cmd = sprintf(['"" ' ... + 'warning off;global cprintferror; cprintferror=1; addpath %s %s %s; load %s; ' ... + 'global defaults; defaults=spm12def; clear defaults; '... + 'global cat; cat=cat12def; clear cat; cat_display_matlab_PID; ' ... + 'output = %s(job); try, save(''%s'',''output''); end; warning off;exit""'],... + spm('dir'),fullfile(fileparts(mfilename('fullpath'))),fileparts(which(func)),tmp_name,func,tmp_name); + else + matlab_cmd = sprintf(['"" ' ... + 'warning off;global cprintferror; cprintferror=1; addpath %s %s %s; load %s; ' ... + 'global defaults; defaults=spm12def; clear defaults; '... + 'global cat; cat=cat12def; clear cat; cat_display_matlab_PID; ' ... + '%s(job); warning off; exit""'],... + spm('dir'),fullfile(fileparts(mfilename('fullpath'))),fileparts(which(func)),tmp_name,func); + end + + + % log-file for output + if isempty(logdir) + log_name{i} = ['log_' func '_' logdate '_' sprintf('%02d',i) '.txt']; %#ok + else + log_name{i} = fullfile(logdir,['log_' func '_' logdate '_' sprintf('%02d',i) '.txt']); %#ok + end + + + % call matlab with command in the background + if ispc + % check for spaces in filenames that will not work with windows systems and background jobs + if strfind(spm('dir'),' ') + cat_io_cprintf('warn',... + ['\nWARNING: No background processes possible because your SPM installation is located in \n' ... + ' a folder that contains spaces. Please set the number of processes in the GUI \n'... + ' to ''0''. In order to split your job into different processes,\n' ... + ' please do not use any spaces in folder names!\n\n']); + job.nproc = 0; + %job = update_job(job); + %varargout{1} = run_job(job); + return; + end + % prepare system specific path for matlab + export_cmd = ['set PATH=' fullfile(matlabroot,'bin')]; + [status,result] = system(export_cmd); + system_cmd = ['start matlab -nodesktop -nosplash -r ' matlab_cmd ' -logfile ' log_name{i}]; + else + % -nodisplay .. nodisplay is without figure output > problem with CAT report ... was there a server problem with -nodesktop? + system_cmd = [fullfile(matlabroot,'bin') '/matlab -nodesktop -nosplash -r ' matlab_cmd ' -logfile ' log_name{i} ' 2>&1 & ']; + end + [status,result] = system(system_cmd); + + + %% look for existing files and extract their PID for later control + % -------------------------------------------------------------------- + test = 0; lim = 100; ptime = 0.5; % exist file? + testpid = 0; limpid = 200; ptimepid = 2.0; % get PID + if ~isempty(strfind(func,'cat_long_multi_run')) + ptimesid = 30; % update every 30s for long. segmentation + else + ptimesid = 2; % update every 2s for all remaining functions + lim = 10; + limpid = 20; + end + + while test=lim + cat_io_cprintf('warn',sprintf('""%s"" not exist after %d seconds! Proceed! \n',log_name{i},lim)); + end + else + % get PIDs for supervising + % search for the log entry ""CAT parallel processing with MATLAB PID: #####"" + if job.getPID + try + while testpid=limpid && ~isinf(testpid) + cat_io_cprintf('warn',sprintf('""%s"" no PID information available after %d seconds! Proceed! \n',log_name{i},limpid)); + end + end + catch + cat_io_cprintf('warn',sprintf('No PID information available! Proceed! \n')); + end + end + + % open file in editor + test = inf; + if ~strcmpi(spm_check_version,'octave') && usejava('jvm') && feature('ShowFigureWindows') && usejava('awt') + edit(log_name{i}); + end + end + end + + if ~strcmpi(spm_check_version,'octave') && usejava('jvm') && feature('ShowFigureWindows') && usejava('awt') + edit(log_name{i}); + end + if PID(i)>0 + fprintf('\nCheck %s for logging information (PID: ',spm_file(log_name{i},'link','edit(''%s'')')); + cat_io_cprintf([1 0 0.5],sprintf('%d',PID(i))); + else + fprintf('\nCheck %s for logging information (',spm_file(log_name{i},'link','edit(''%s'')')); + cat_io_cprintf([1 0 0.5],'unknown PID'); + end + cat_io_cprintf([0 0 0],').\n_______________________________________________________________\n'); + + % starting many large jobs can cause servere MATLAB errors + pause(1 + rand(1) + job.nproc + numel(job.(datafield))/100); + jobs(i).(datafield) = job.(datafield); %#ok + + job = jobo; + end + + + %job = update_job(job); + varargout{1} = job; + %vout_job(job); + + if job.getPID + if any(PID==0) + cat_io_cprintf('warn',... + ['\nWARNING: CAT was not able to detect the PIDs of the parallel CAT processes. \n' ... + ' Please note that no additional modules in the batch can be run \n' ... + ' except CAT12 segmentation. Any dependencies will be broken for \n' ... + ' subsequent modules if you split the job into separate processes.\n\n']); + else + %% conclusion without filelist + spm_clf('Interactive'); + cat_progress_bar('Init', sum( numel(job_data) ) ,'Processing','Jobs Started/Processed'); + + fprintf('\nStarted %d jobs with the following PIDs:\n',job.nproc); + for i=1:job.nproc + fprintf('%3d) %d subjects (PID: ',i,numel(jobs(i).(datafield))); + cat_io_cprintf([1 0 0.5],sprintf('%6d',PID(i))); + cat_io_cprintf([0 0 0],sprintf('): ')); + cat_io_cprintf([0 0 1],sprintf('%s\n',spm_file(log_name{i},'link','edit(''%s'')'))); + end + + + + %% supervised pipeline processing + % ------------------------------------------------------------------ + % This is a ""simple"" while loop that check if the processes still + % exist and extract information from the log-files, which subject + % was (successfully) processed. + % Finally, a report could be generated and exportet in future that + % e.g. count errors give some suggestions + % ------------------------------------------------------------------ + if job.getPID>1 + cat_io_cprintf('warn',sprintf('\nKilling of this process will not kill the parallel processes!\n')); + fprintf('_______________________________________________________________\n'); + fprintf('Process datasets (see catlog files for details!):\n'); + + % jobIDs .. variable to handle different processing parameters + % [ subID , asignedproc , procID , started , finished , error , printed_started , printed_finished ] + % subID, asignedproc, procID .. identification of the subject in job and jobs(i) + % started .. count all appearance of the subject name) + % finished .. set job as finished (e.g. if the next subject name appears) + % error .. not used yet + % printed .. printed on cmd line (do not want to print every loop) + % + % A matrix gives a better overview of the status although the fieldnames of a structure are also nice + % jobIDs = struct('subID',0,'jobID',0,'jobsubID',0,'started',0,'finished',0,'error',0,'pstarted',0,'pfinished',0); + % + jobIDs = zeros(sum( numel(job_data) ),9); + for pi = 1:job.nproc + for spi = 1:numel(job.process_index{pi}) + si = job.process_index{pi}(spi); + jobIDs(si,1) = si; + jobIDs(si,2) = pi; + jobIDs(si,3) = spi; + end + end + + % some older variables + %err = struct('err',0); + catSID = zeros(1,job.nproc); + catSIDlast = zeros(size(catSID)); + + + % loop as long as data is processed by active tasks + PIDactive = ones(size(catSID)); % active jobs + activePIDs = 1; % loop variable to have an extra loop + cid = 0; + while ( cid <= sum( numel(job_data) ) + 1 ) && activePIDs % plus 1 because only staring jobs are shown! + pause(ptimesid); + if all( PIDactive==0 ), activePIDs = 0; end % if all jobs are finish, we can also stop looping + %fprintf('--\n'); + + % get status of each process + for i=1:job.nproc + % get FID and read the processing output + FID = fopen(log_name{i},'r'); + if FID < 0 + fprintf('Warning: Log file %s could not be opened. Please check file permissions or do not call any other batches until this process is finished!\n',log_name{i}) + continue + end + txt = textscan(FID,'%s','Delimiter','\n'); + txt = txt{1}; + fclose(FID); + + + % find out if the current task is still active + if ispc + [status,result] = system(sprintf('tasklist /v /fi ""PID %d""',PID(i))); + else + [status,result] = system(sprintf('ps %d',PID(i))); + end + if isempty( strfind( result , sprintf('%d',PID(i)) ) ) + PIDactive(i) = 0; + end + + + %% search for the start/end entries of a subject, e.g. ""CAT12.# r####: 1/14: ./MRData/*.nii"" + % This is the dirty part that is expected to need adaptation for + % each new routine that utilize cat_parallelize and has a new + % unique job and log structure. + % If this process failed, we have no progress information but + % we the batch can still work by asking if the taskIDs exist. + % + % jobs(i) .. the i-th parallel job (01 + jobSIDp = jobIDs(jobIDs(:,2)==i & jobIDs(:,3)==(si-1),1); + jobIDs( jobSIDp , 5) = 1; % if work on a new subject that mark the previous one as finished + end + + if strcmp(FN{fni},'mov') % long + % this does not work + FIN = find( ~cellfun('isempty', strfind( txt, 'Finished CAT12 longitudinal processing of '))); + if ~isempty( FIN ) && numel(txt)>FIN(end) + SIDFIN = find( cellfun('isempty', strfind( txt( FIN(end)+1 ) , ff ))==0 ); + if ~isempty( SIDFIN ) + jobIDs( jobSID , 5) = 1; + jobIDs( jobSID , 6) = 0; + else + jobIDs( jobSID , 5) = 1; + jobIDs( jobSID , 6) = 1; + end + end + % CAT long errors with broken batch pipeline + FIN = find( ~cellfun('isempty', strfind( txt, 'Error using MATLABbatch system'))); + if ~isempty( FIN ) && numel(txt)>FIN(end) + SIDFIN = find( cellfun('isempty', strfind( txt( FIN(end)+1 ) , ff ))==0 ); + if ~isempty( SIDFIN ) + jobIDs( jobSID , 5) = 1; + jobIDs( jobSID , 6) = 0; + else + jobIDs( jobSID , 5) = 1; + jobIDs( jobSID , 6) = 1; + end + end + end + + % if you found something and did not print it before than print that you have started this subject + if jobIDs(jobSID,4)>0 && jobIDs(jobSID,7)==0 && jobIDs(jobSID,8)==0 + jobIDs(jobSID,7) = 1; + cat_io_cprintf([0 0 0.5],sprintf(' started %d/%d (pjob %d: %d/%d): %s\n',... + jobSID,sum( numel(job_data) ), i, jobIDs(jobSID,3) , numel(jobs(i).(datafield)), ... + spm_str_manip( jobs(i).(datafield)(si).(FN{1}){1}, 'k40') )); + end + + % if you started the next subject or the job is finished then print that you finished the job + if ( jobIDs(jobSID,5)>0 || PIDactive(i)==0 ) && jobIDs(jobSID,8)==0 + jobIDs(jobSID,8) = 1; + if jobIDs( jobSID , 6) == 0 + cat_io_cprintf( [0 0.5 0] ,sprintf(' finished %d/%d (pjob %d: %d/%d): %s\n',... + jobSID,sum( numel(job_data) ), i, jobIDs(jobSID,3) , numel(jobs(i).(datafield)), ... + spm_str_manip( jobs(i).(datafield)(si).(FN{1}){1}, 'k40') )); + else + cat_io_cprintf( [1 0 0] ,sprintf(' failed %d/%d (pjob %d: %d/%d): %s\n',... + jobSID,sum( numel(job_data) ), i, jobIDs(jobSID,3) , numel(jobs(i).(datafield)), ... + spm_str_manip( jobs(i).(datafield)(si).(FN{1}){1}, 'k40') )); + end + cid = cid + 1; + end + + % if you found something and did not print it before than print that you have started this subject + if jobIDs(jobSID,4)>0 && jobIDs(jobSID,7)==0 + jobIDs(jobSID,7) = 1; + cat_io_cprintf([0 0 0.5],sprintf(' started %d/%d (pjob %d: %d/%d): %s\n',... + jobSID,sum( numel(job_data) ), i, jobIDs(jobSID,3) , numel(jobs(i).(datafield)), ... + spm_str_manip( jobs(i).(datafield)(si).(FN{1}){1}, 'k40') )); + end + + end + end + end + end + end + elseif strcmp( datafield , 'data_surf' ) + % --------------------------------------------------------- + % surfaces ... here the filenames of the processed data + % change strongly due to side coding ... + % --------------------------------------------------------- + for si=1:numel( jobs(i).(datafield) ) + if iscell( jobs(i).(datafield){si} ) + for sii=1:numel( jobs(i).(datafield){si} ) + [pp,ff,ee] = spm_fileparts(jobs(i).(datafield){si}{sii}); + + SID{si} = ... + find(cellfun('isempty', strfind( txt , pp ))==0,1,'first') & ... + find(cellfun('isempty', strfind( txt , ff ))==0,1,'first') & ... + find(cellfun('isempty', strfind( txt , ee ))==0,1,'first'); + end + else + [pp,ff,ee] = spm_fileparts(jobs(i).(datafield){si}); + + SID{si} = ... + find(cellfun('isempty', strfind( txt , pp ))==0,1,'first') & ... + find(cellfun('isempty', strfind( txt , ff ))==0,1,'first') & ... + find(cellfun('isempty', strfind( txt , ee ))==0,1,'first'); + end + end + else % volumes + for si=1:numel( jobs(i).(datafield) ) + SID{si} = find(cellfun('isempty', strfind( txt , jobs(i).(datafield){si} ))==0,1,'first'); + end + end + + %{ + catch + if ~exist('noSID','var') || noSID==0 + noSID = 1; + cat_io_cprintf('warn',' Progress bar did not work but still monitoring the tasks.\n'); + end + end + %} + + + + %% update status (old version!) + % if this task was not printed before ( catSIDlast(i) < catSID(i) ) and + % if one subject was successfully or with error processed ( any(cattime>0) || ~isempty(caterr) ) + if ~isstruct( jobs(i).(datafield) ) + %% + findSIDi = find(cellfun('isempty',SID)==0,1,'last'); + if ~isempty(findSIDi), catSID(i) = findSIDi; end + + if numel(catSID)>1 && ( catSIDlast(i) < catSID(i) ) + try + catSIDlast(i) = catSID(i); + cat_io_cprintf([ 0 0 0 ],sprintf(' %d/%d (pjob %d: %d/%d): %s\n',... + sum(catSID) ,sum( numel(job_data) ), i, catSID(i), numel(jobs(i).(datafield)), ... + spm_str_manip( jobs(i).(datafield){catSID(i)} , 'k40') )); + cid = max( cid + 1 , sum(catSID) ); + end + end + end + end + + % further error handling of different functions + % 'Error using MATLABbatch system' + + + % + cat_progress_bar('Set', cid ); + + + end + + end + %fprintf('done\n'); + end + + + %% Merge output of the subprocesses to support SPM dependencies. + % -------------------------------------------------------------------- + % The results of a function are saved as variable named ""output"" in + % the temporary matlab files that were also used for data input. + % However, currently only the first output can be used and a structure + % array is expected that have maximal two sublevels, e.g. + % output.data = {file1, ...} + % output.subject.data = {file1, ...} + % -------------------------------------------------------------------- + if nargout>0 + %% load the results of the first job + load(tmp_array{1}); + + % add further output results of the other jobs + for oi=1:numel(tmp_array) + clear output + load(tmp_array{oi}); + + if exist('output','var') + if ~exist('varargout','var') + % here we can simply set the output + varargout{1} = output; + else + % here we have to add the data to each field + % (cat_struct does therefore not work) + FN = fieldnames(output); + for fni=1:numel(FN) + if ~isfield( varargout{1} , FN{fni} ) + % no subfield ( = new subfield ) > just add it + varargout{1}.(FN{fni}) = output.(FN{fni}); + else + % existing subfield > merge it + if ~isstruct( output.(FN{fni}) ) + if isfield(varargout{1},FN{fni}) && ~isstruct( varargout{1}.(FN{fni}) ) + if size(varargout{1}.(FN{fni}),1) > size(varargout{1}.(FN{fni}),2) || ... + size(output.(FN{fni}),1) > size(output.(FN{fni}),2) + varargout{1}.(FN{fni}) = [varargout{1}.(FN{fni}); output.(FN{fni})]; + else + varargout{1}.(FN{fni}) = [varargout{1}.(FN{fni}), output.(FN{fni})]; + end + + % cleanup (remove empty entries of failed processings) + if iscell(varargout{1}.(FN{fni})) + for ffni=numel( varargout{1}.(FN{fni}) ):-1:1 + if isempty( varargout{1}.(FN{fni}){ffni} ) + varargout{1}.(FN{fni})(ffni) = []; + end + end + end + else + varargout{1}.(FN{fni}) = output.(FN{fni}); + end + else + % this is similar to the first level ... + FN2 = fieldnames(output.(FN{fni})); + for fni2 = 1:numel(FN2) + for fnj=1:numel( output.(FN{fni}) ) + if ~isstruct( output.(FN{fni})(fnj).(FN2{fni2}) ) + if isfield(varargout{1}.(FN{fni})(fnj),FN2{fni2}) && ~isstruct( varargout{1}.(FN{fni})(fnj).(FN2{fni2}) ) + if size(varargout{1}.(FN{fni})(fnj).(FN2{fni2}),1) > size(varargout{1}.(FN{fni})(fnj).(FN2{fni2}),2) || ... + size(output.(FN{fni})(fnj).(FN2{fni2}),1) > size(output.(FN{fni})(fnj).(FN2{fni2}),2) + varargout{1}.(FN{fni})(fnj).(FN2{fni2}) = [varargout{1}.(FN{fni})(fnj).(FN2{fni2}); output.(FN{fni})(fnj).(FN2{fni2})]; + else + varargout{1}.(FN{fni})(fnj).(FN2{fni2}) = [varargout{1}.(FN{fni})(fnj).(FN2{fni2}), output.(FN{fni})(fnj).(FN2{fni2})]; + end + + % cleanup (remove empty entries of failed processings) + if iscell(varargout{1}.(FN{fni})(fnj).(FN2{fni2})) + for ffni=numel( varargout{1}.(FN{fni})(fnj).(FN2{fni2}) ):-1:1 + if isempty( varargout{1}.(FN{fni})(fnj).(FN2{fni2}){ffni} ) + varargout{1}.(FN{fni})(fnj).(FN2{fni2})(ffni) = []; + end + end + end + else + varargout{1}.(FN{fni})(fnj).(FN2{fni}) = output.(FN{fni})(fnj).(FN2{fni}); + end + else + error('Only 2 level in output structure supported.') + end + end + end + end + end + end + end + else + % create an error message? + oistr = cat_io_strrep( sprintf('%dth',oi) , {'1th'; '2th'; '3th'} , {'1st','2nd','3rd'} ); + cat_io_cprintf('error',sprintf(... + 'The %s processes does not contain the output variable for depending jobs. Check log-file for errors: \n ', oistr)); + %fprintf([spm_file(log_name{oi},'link',sprintf('edit(%s)',log_name{oi})) '\n\n']); + cat_io_cprintf([0 0 1],sprintf('%s\n\n',spm_file(log_name{i},'link','edit(''%s'')'))); + end + end + end + + % no final report yet ... + fprintf('_______________________________________________________________\n'); + + else + cat_io_cprintf('warn',... + ['\nWARNING: Please note that no additional modules in the batch can be run \n' ... + ' except CAT12 segmentation. Any dependencies will be broken for \n' ... + ' subsequent modules if you split the job into separate processes.\n\n']); + end + + cat_progress_bar('Clear'); + return +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_vol_ctype.m",".m","4779","145","function Y = cat_vol_ctype(Y,type) +% ______________________________________________________________________ +% Y = cat_vol_ctype(Y[,type]) +% +% Convert datatype with checking of min/max, nan, and rounding for +% [u]int[8|16], single, double, and char. Default round type is 'uint8'. +% Y has to be a matrix or cell. +% +% This function is only written for our private use, mostly to convert +% single to uint8. We did not check for special behavior, for extremly +% high values or special rounding issues, or converting to larger +% classes etc.! +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ +% ______________________________________________________________________ + + if nargin==0, help cat_vol_ctype; return; end + if nargin==1 && ischar(Y) && strcmp(Y,'test'), testctype; return; end + + types = {'int8','int16','int32','int64','single','float32','float64'... + 'uint8','uint16','uint32','uint64','double'}; + + if ~exist('type','var') + type = 'uint8'; + else + type = lower(type); + % check for additional information such as -le and cut name + ind = strfind(type,'-'); + if ~isempty(ind) + type = type(1:ind-1); + end + if ~any(cat_io_contains(types,type)) + error('MATLAB:SPM:CAT:cat_vol_ctype:UnknownType', ... + ['ERROR: cat_vol_ctype: unknown data type ''%s'' ' ... + '(only [u]int[8|16], single, and double).'],type); + end + end + % use single for logical arrays to be compatible + type = cat_io_strrep(type, ... + {'float32', 'float64'}, ... + {'single', 'double'}); + + + if iscell(Y) + % recall function + for yi = 1:numel(Y) + Y{yi} = cat_vol_ctype(Y{yi}, type); + end + else + type = types{cat_io_contains(types, type)}; + + % prepare conversion + if cat_io_contains('int', type) + switch class(Y) + case {'single','double'} + % replace nan + Y = single(Y); + Y(isnan(Y)) = 0; + Y = round( min( single(intmax(type)), max(single(intmin(type)), Y ))); + case {'uint8','uint16'} + Y = min( uint16(intmax(type)), max(uint16(intmin(type)), uint16(Y) )); + case {'uint32','uint64'} + Y = min( uint32(intmax(type)), max(uint32(intmin(type)), uint32(Y) )); + case {'int8','int16'} + Y = min( int16(intmax(type)), max( int16(intmin(type)), uint16(Y) )); + case {'int32','int64'} + Y = min( int64(intmax(type)), max( int64(intmin(type)), uint64(Y) )); + otherwise + % this is not working for very old matlab versions + eval(sprintf('Y = min( double(intmax(''%s'')), max( double(intmin(''%s'')), double(Y) ))',type,type)); + end + elseif cat_io_contains(type,'single') + Y = min( single(realmax(type)), max(-single(realmax(type)), single(Y) )); + elseif cat_io_contains(type,'double') + Y = min( double(realmax(type)), max(-double(realmax(type)), double(Y) )); + end + + % convert + eval(sprintf('Y = %s(Y);', type)); + end + +end +function testctype +%% unit test with two major cases: +% cell B: double to single/double/(u)int(8,16,32,64) +% cell c: uint16 to single/double/(u)int(8,16,32,64) + + ncases = {'(uint8)', 'single', 'double', ... + 'uint8', 'uint16', 'uint32', 'uint64', ... + 'int8' , 'int16', 'int32', 'int64'}; + tval = 512; + A = randn(10,10,10) * tval; + C = cell(1,numel(ncases)); B = C; + + % default uint8 + C{1} = cat_vol_ctype( A ); + B{1} = cat_vol_ctype( int16( round(A) ) ); + % other cases + for ci = 2:numel(ncases) + C{ci} = cat_vol_ctype( A , ncases{ci}); + B{ci} = cat_vol_ctype( int16( round(A) ) , ncases{ci}); + end + + + %% plot results + fh = figure(38478); clf + fh.Name = 'cat_vol_ctype unit test'; + fh.Color = [1 1 1]; + + % plot C + for ci = 1:numel(ncases) + subplot(4,6,ci); + imagesc( C{ci}(:,:,round(size(A,3)/2)) ); + title(ncases{ci}); caxis([-tval,tval]); + axis equal off; + end + + % plot B + for ci = 1:numel(ncases) + subplot(4,6,ci + 1 +numel(ncases)); + imagesc( B{ci}(:,:,round(size(A,3)/2)) ); + title(ncases{ci}); caxis([-tval,tval]) + axis equal off; + end + + fprintf('Test cases single: uint8, char, single, double, uint[8,16,32,64], uint[8,16,32,64]:\n'); + disp(C) + + fprintf('Test cases int16: uint8, char, single, double, uint[8,16,32,64], uint[8,16,32,64]:\n'); + disp(B) + + fprintf('Convert Cell:\n') + cat_vol_ctype( { A, int16( round(A) ) } ) + + fprintf('Test error:\n') + cat_vol_ctype( A ,'char'); + + +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_plot_circular.m",".m","13601","411","function h = cat_plot_circular(data, opt) +% cat_plot_circular Plots correlation/connection matrix as a circular plot +% +% usage: vargout = cat_plot_circular(data,opt); +% +% cat_plot_circular(data) data is a square numeric matrix with values in [0,1]. +% +% NOTE: only the off-diagonal lower triangular section of data is +% considered, i.e. tril(data,-1). +% +% opt.label Plot a cat_plot_circular with custom labels at each node. +% LABEL is either a cellstring of length M, where +% M = size(r,1), or a M by N char array, where each +% row is a label. +% +% opt.ccolor Supply an RGB triplet or a colormap that specifies the color of +% the curves. CURVECOLOR can also be a 2 by 3 matrix +% with the color in the first row for negative +% correlations and the color in the second row for +% positive correlations. +% +% opt.tcolor Change text color. +% +% opt.bcolor Change background color. +% +% opt.ncolor Change node colors of the doughnut plot. +% +% opt.maxlinewidth Maximal line width for connections. +% +% opt.doughnut Value of doughnut chart. +% +% opt.gap Gap between doughnut chart. +% +% opt.mwidth Multiply width of doughnut chart. +% +% opt.fontsize Font size +% +% opt.saveas Save figure as image (e.g. png or pdf). +% +% opt.fig Figure handle. +% +% H = cat_plot_circular(...) Returns a structure with handles to the graphic objects +% +% h.l handles to the curves (line objects), one per color shade. +% If no curves fall into a color shade that handle will be NaN. +% h.s handle to the nodes (scattergroup object) +% h.t handles to the node text labels (text objects) +% +% +% Examples +% +% % Base demo +% cat_plot_circular +% +% % Supply your own correlation matrix (only lower off-diagonal triangular part is considered) +% x = rand(10).^3; +% x(:,3) = 1.3*mean(x,2); +% cat_plot_circular(x) +% +% % Supply custom labels as ['aa'; 'bb'; 'cc'; ...] or {'Hi','how','are',...} +% cat_plot_circular(x, struct('label',repmat(('a':'j')',1,2))) +% +% % Customize curve colors +% cat_plot_circular(x,struct('ccolor',[1,0,1;1 1 0])) +% +% % Customize node color +% cat_plot_circular(x,struct('ncolor',[0,1,0])) +% +% % Customize manually other aspects +% h = cat_plot_circular; +% set(h.l(~isnan(h.l)), 'LineWidth',1.2) +% set(h.s, 'MarkerEdgeColor','red','LineWidth',2,'SizeData',100) +% +% modified version of schemaball.m +% Author: Oleg Komarov (oleg.komarov@hotmail.it) +% Tested on R2013a Win7 64 and Vista 32 +% 15 jun 2013 - Created +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +% Number of color shades/buckets (large N simply creates many perceptually indifferent color shades) +N = 20; + +% Points in [0, 1] for bezier curves: leave space at the extremes to detach a bit the nodes. +% Smaller step will use more points to plot the curves. +t = (0.01: 0.005 :0.99)'; + +% Nodes edge color +ecolor = [.25 .103922 .012745]; + +% Some defaults +if nargin < 1 || isempty(data) + data = (rand(50)*2-1).^29; +end + +sz = size(data); + +% default parameter +if ~exist('opt','var'), opt = struct(''); end +def.ncolor(:,:,:) = [hot(sz(1)); jet(sz(1))]; % node colors (doughnut) +def.maxlinewidth = 5; % maximal line width for connections +def.label = cellstr(reshape(sprintf('%-4d',1:sz(1)),4,sz(1))'); % label +def.doughnut = []; % value of doughnut chart +def.gap = []; % gap between doughnut chart +def.mwidth = []; % multiply width of doughnut chart +def.saveas = ''; % save image +def.figure = []; % figure handle +def.fontsize = 8; % Fontsize +def.tcolor = [0.0 0.0 0.0]; % text color +def.bcolor = [1.0 1.0 1.0]; % background color +def.ccolor = hsv2rgb([[linspace(.8333, .95, N); ones(1, N); linspace(1,0,N)],... + [linspace(.03, .1666, N); ones(1, N); linspace(0,1,N)]]'); + +opt = cat_io_checkinopt(opt,def); + +% data +if ~isnumeric(data) || any(abs(data(:)) > 1) || sz(1) ~= sz(2) || numel(sz) > 2 || sz(1) == 1 + error('cat_plot_circular:validR','data should be a square numeric matrix with values in [-1, 1].') +end + +% label +if (~ischar(opt.label) || size(opt.label,1) ~= sz(1)) && (~iscellstr(opt.label) || ~isvector(opt.label) || length(opt.label) ~= sz(1)) + error('cat_plot_circular:validLbls','LBLS should either be an M by N char array or a cellstring of length M, where M is size(R,1).') +end +if ischar(opt.label) + opt.label = cellstr(opt.label); +end + +% ccolor +if isempty(opt.ccolor); + opt.ccolor = hsv2rgb([[linspace(.8333, .95, N); ones(1, N); linspace(1,0,N)],... + [linspace(.03, .1666, N); ones(1, N); linspace(0,1,N)]]'); +else + szC = size(opt.ccolor); + if ~isnumeric(opt.ccolor) || szC(2) ~= 3 + error('cat_plot_circular:validCcolor','CCOLOR should be a 1 by 3, 2 by 3 or N by 3 numeric matrix with RGB colors.') + elseif szC(1) == 1 + opt.ccolor = [opt.ccolor; opt.ccolor]; + end + if szC(1) < 3 + opt.ccolor = rgb2hsv(opt.ccolor); + opt.ccolor = hsv2rgb([repmat(opt.ccolor(1,1:2),N,1), linspace(opt.ccolor(1,end),0,N)'; + repmat(opt.ccolor(2,1:2),N,1), linspace(0,opt.ccolor(2,end),N)']); + end +end + +% ncolor +szN = size(opt.ncolor); +if ~isnumeric(opt.ncolor) || szN(2) ~= 3 + error('cat_plot_circular:validCcolor','NCOLOR should be a 1 by 3, 2 by 3 or N by 3 numeric matrix with RGB colors.') +end +if szN(1) < 3 + opt.ncolor = rgb2hsv(opt.ncolor); + opt.ncolor = hsv2rgb([repmat(opt.ncolor(1,1:2),sz(1),1), linspace(opt.ncolor(1,end),0,sz(1))']); +end + +%% Engine + +% Create figure +if isempty opt.fig + figure('renderer','opengl','visible','off') +else + figure(opt.fig,'renderer','opengl','visible','off') +end +axes('NextPlot','add') + +% Index only low triangular matrix without main diag +tf = tril(true(sz),-1); + +% Index correlations into bucketed colormap to determine plotting order (darkest to brightest) +N2 = 2*N; +data(data == 0) = NaN; +[n, isrt] = histc(data(tf), linspace(-1,1 + eps(100),N2 + 1)); +plotorder = reshape([N:-1:1; N+1:N2],N2,1); + +% create varying linewidth +linewidth = [linspace(opt.maxlinewidth,1,N) linspace(1,opt.maxlinewidth,N)]; + +% Retrieve pairings of nodes +[row,col] = find(tf); + +% Use tau http://tauday.com/tau-manifesto +tau = 2*pi; + +% Positions of nodes on the circle starting from (0,-1), useful later for label orientation +step = tau/sz(1); +theta = -.25*tau : step : .75*tau - step; + +% Get cartesian x-y coordinates of the nodes +x = cos(theta); +y = sin(theta); + +if ~isempty(opt.doughnut) + % transpose if necessary + if length(data) ~= size(opt.doughnut,1) + opt.doughnut = opt.doughnut'; + end + if length(data) ~= size(opt.doughnut,1) + error('cat_plot_circular:validDoughnut','Size of data and doughnut differs.'); + end + step2 = tau/size(opt.doughnut,1); + theta2 = -.25*tau : step2 : .75*tau - step2; +end + +% PLOT BEZIER CURVES +% Calculate Bx and By positions of quadratic Bezier curves with P1 at (0,0) +% B(t) = (1-t)^2*P0 + t^2*P2 where t is a vector of points in [0, 1] and determines, i.e. +% how many points are used for each curve, and P0-P2 is the node pair with (x,y) coordinates. +t2 = [1-t, t].^2; +s.l = NaN(N2,1); + +% LOOP per color bucket +for c = 1:N2 + pos = plotorder(c); + idx = isrt == pos; + if nnz(idx) + Bx = [t2*[x(col(idx)); x(row(idx))]; NaN(1,n(pos))]; + By = [t2*[y(col(idx)); y(row(idx))]; NaN(1,n(pos))]; + s.l(c) = plot(Bx(:),By(:),'Color',opt.ccolor(pos,:),'LineWidth',linewidth(pos)); + end +end + +% PLOT NODES +% Do not rely that r is symmetric and base the mean on lower triangular part only +[row,col] = find(tf(end:-1:1,end:-1:1) | tf); +subs = col; +iswap = row < col; +tmp = row(iswap); +row(iswap) = col(iswap); +col(iswap) = tmp; + +% Plot in brighter color those nodes which on average are more absolutely correlated +[Z,isrt] = sort(accumarray(subs,abs(data( row + (col-1)*sz(1) )),[],@mean)); +Z = (Z-min(Z)+0.01)/(max(Z)-min(Z)+0.01); + +text_offset = 1.06; +if ~isempty(opt.doughnut) + + % estimate text offset according to length of data + text_offset = 1.0 + 0.06*size(opt.doughnut,2); + + % consider gap between charts + if isfield(opt,'gap') + text_offset = text_offset + 0.02*sum(opt.gap); + end + + % consider larger width + if isfield(opt,'mwidth') + text_offset = text_offset + 0.06*sum(opt.mwidth-1); + end + + s.s = doughnut(opt.doughnut,opt); +else + ncolor = rgb2hsv([0 0 1]); + ncolor = hsv2rgb([repmat(ncolor(1:2), sz(1),1) Z*ncolor(3)]); + s.s = scatter(x(isrt),y(isrt),[], ncolor,'fill','MarkerEdgeColor',ecolor,'LineWidth',1); +end + +% PLACE TEXT LABELS such that you always read 'left to right' +ipos = x > 0; +s.t = zeros(sz(1),1); +s.t( ipos) = text(x( ipos)*text_offset, y( ipos)*text_offset, opt.label( ipos),'Color',opt.tcolor,'FontSize',opt.fontsize); +set(s.t( ipos),{'Rotation'}, num2cell(theta(ipos)'/tau*360)) +s.t(~ipos) = text(x(~ipos)*text_offset, y(~ipos)*text_offset, opt.label(~ipos),'Color',opt.tcolor,'FontSize',opt.fontsize); +set(s.t(~ipos),{'Rotation'}, num2cell(theta(~ipos)'/tau*360 - 180),'Horiz','right') + +% ADJUST FIGURE height width to fit text labels +xtn = cell2mat(get(s.t,'extent')); +post = cell2mat(get(s.t,'pos')); +sg = sign(post(:,2)); +posfa = cell2mat(get([gcf gca],'pos')); + +% Calculate xlim and ylim in data units as x (y) position + extension along x (y) +ylims = post(:,2) + xtn(:,4).*sg; +ylims = [min(ylims), max(ylims)]; +xlims = post(:,1) + xtn(:,3).*sg; +xlims = [min(xlims), max(xlims)]; + +% Stretch figure +posfa(1,3) = (( diff(xlims)/2 - 1)*posfa(2,3) + 1) * posfa(1,3); +posfa(1,4) = (( diff(ylims)/2 - 1)*posfa(2,4) + 1) * posfa(1,4); + +% Position it a bit lower (movegui slow) +posfa(1,2) = 100; + +% Axis settings +set(gca, 'Xlim',xlims,'Ylim',ylims, 'color', opt.bcolor, 'layer','bottom', 'Xtick',[],'Ytick',[]) +set(gcf, 'pos' ,posfa(1,:),'Visible','on') +axis equal + +if nargout == 1 + h = s; +end + +% save image if defined +if ~isempty(opt.saveas) + [pth,nam,ext] = fileparts(opt.saveas); + print(gcf,sprintf('-d%s',ext(2:end)), '-r600', opt.saveas) +end + +function hh = doughnut(data,opt) +%DOUGHNUT doughnut chart. +% DOUGHNUT(X) draws a pie plot of the data in the vector X. The values in X +% are normalized via X/SUM(X) to determine the area of each slice of pie. +% If SUM(X) <= 1.0, the values in X directly specify the area of the pie +% slices. Only a partial pie will be drawn if SUM(X) < 1. +% +% DOUGHNUT(...,LABELS) is used to label each pie slice with cell array LABELS. +% LABELS must be the same size as X and can only contain strings. +% +% DOUGHNUT(AX,...) plots into AX instead of GCA. +% +% H = DOUGHNUT(...) returns a vector containing patch and text handles. +% +% Example +% doughnut([2 4 3 5],{'North','South','East','West'}) +% +% based on pie.m +% Clay M. Thompson 3-3-94 +% Copyright 1984-2005 The MathWorks, Inc. +% $Revision$ $Date$ + + +% go trough all data +for k=1:size(data,2) + + opt.order = k; + + x = data(:,k); + sz = size(x); + + def.ncolor(:,:,:) = [hot(sz(1)); jet(sz(1))]; % node color + def.border = zeros(sz(1),1); + def.gap = zeros(size(data,2),1); + def.mwidth = ones(sz(1),1); + + opt = cat_io_checkinopt(opt,def); + + nonpositive = (x <= 0); + if all(nonpositive) + error('MATLAB:doughnut:NoPositiveData',... + 'Must have positive data in the doughnut chart.'); + end + if any(nonpositive) + warning('MATLAB:doughnut:NonPositiveData',... + 'Ignoring non-positive data in doughnut chart.'); + x(nonpositive) = []; + end + xsum = sum(x); + + % check whether x consists of integers only + if any(double(int16(x)) - double(x)) + error('MATLAB:doughnut:NoIntegerData',... + 'Must have positive integer data in the doughnut chart.'); + else + % maximum value should not exceed length of x + if max(x) > length(x) + error('MATLAB:doughnut:NoIntegerData',... + 'Must have positive integer data with maximum value <= length of data.'); + end + end + + cax = newplot; + next = lower(get(cax,'NextPlot')); + hold_state = ishold(cax); + + maxpts = 400; + theta0 = -pi/2 - pi/(length(x)); + + h = []; + x0 = 1/length(x); + + for i=1:length(x) + n = max(1,ceil(maxpts*x0)); + + if opt.border(i), start = 1; + else start = 0; end + + width = opt.mwidth(k)*0.05; + + gap = (0.05 + 0.02*opt.gap(k))*(opt.order - 1); + + r = [(0.985+width)*ones(n + (1-start),1);0.985*ones(n + (1 - start),1)] + gap; + theta = theta0 + [x0*(start:n)'/n;flipud(x0*(start:n)'/n)]*2*pi; + [xx,yy] = pol2cart(theta,r); + theta0 = max(theta); + + if size(opt.ncolor,3) > 1 + cc = opt.ncolor(x(i),:,k); + else + cc = opt.ncolor(x(i),:); + end + h = [h,patch('XData',xx,'YData',yy,'Facecolor',cc, ... + 'parent',cax,'EdgeColor','black')]; + end + + if ~hold_state, + view(cax,2); set(cax,'NextPlot',next); + axis(cax,'equal','off',[-1.2 1.2 -1.2 1.2]) + end + + hh = h; + +end +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_io_strrep.m",".m","1818","52","function MODIFIEDSTR = cat_io_strrep(ORIGSTR,OLDSUBSTR,NEWSUBSTR) +% _______________________________________________________________________ +% cat_io_strrep replace strings by other strings. It based on the strrep +% and allows to use cellstrings that were replace by another string or a +% similar number of cellstrings depending on their input order. +% +% claim{1} = 'This is a good example'; +% claim{2} = 'This is a bad example'; +% new_claimA = cat_io_strrep(claim,{' good',' bad'},'n') +% new_claimB = cat_io_strrep(claim,{'good','bad'},{'great','acceptable'}) +% +% See also strrep, strfind, regexprep. +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + if nargin==0, help cat_io_strrep; return; end + + if iscell(ORIGSTR) + MODIFIEDSTR = ORIGSTR; + for i=1:numel(ORIGSTR) + MODIFIEDSTR{i} = cat_io_strrep(ORIGSTR{i},OLDSUBSTR,NEWSUBSTR); + end + else + if iscell(OLDSUBSTR) + if iscell(NEWSUBSTR) + if numel(OLDSUBSTR)==numel(NEWSUBSTR) + MODIFIEDSTR = ORIGSTR; + for i=1:numel(OLDSUBSTR) + MODIFIEDSTR = strrep(MODIFIEDSTR,OLDSUBSTR{i},NEWSUBSTR{i}); + end + else + error('cat_io_strrep:input',... + 'If multiple new strings were used, their number must be equal to the number of old strings.\n'); + end + else + MODIFIEDSTR = ORIGSTR; + for i=1:numel(OLDSUBSTR) + MODIFIEDSTR = strrep(MODIFIEDSTR,OLDSUBSTR{i},NEWSUBSTR); + end + end + else + MODIFIEDSTR = strrep(ORIGSTR,OLDSUBSTR,NEWSUBSTR); + end + end +end +","MATLAB" +"Neurology","ChristianGaser/cat12","WarpPriors.c",".c","10641","265","/* ______________________________________________________________________ + * + * Christian Gaser, Robert Dahnke + * Structural Brain Mapping Group (https://neuro-jena.github.io) + * Departments of Neurology and Psychiatry + * Jena University Hospital + * ______________________________________________________________________ + * $Id$ + * + */ + +#include +#include +#include +#include ""optimizer3d.h"" +#include ""diffeo3d.h"" +#include ""Amap.h"" + +struct dartel_prm { + int rform; /* regularization form: 0 - linear elastic energy; 1 - membrane energy; 2 - bending energy */ + double rparam[6]; /* regularization parameters */ + double lmreg; /* LM regularization */ + int cycles; /* number of cycles for full multi grid (FMG) */ + int its; /* Number of relaxation iterations in each multigrid cycle */ + int k; /* time steps for solving the PDE */ + int code; /* objective function: 0 - sum of squares; 1 - symmetric sum of squares; 2 - multinomial */ +}; + + +/* First order hold resampling - trilinear interpolation */ +void subsample_uint8(unsigned char *in, float *out, int dim_in[3], int dim_out[3], int offset_in, int offset_out) +{ + int i, x, y, z; + double k111,k112,k121,k122,k211,k212,k221,k222; + double dx1, dx2, dy1, dy2, dz1, dz2, xi, yi, zi, samp[3]; + int off1, off2, xcoord, ycoord, zcoord; + + for (i=0; i<3; i++) { + if(dim_out[i] > dim_in[i]) samp[i] = ceil((double)dim_out[i]/(double)dim_in[i]); + else samp[i] = 1.0/(ceil((double)dim_in[i]/(double)dim_out[i])); + } + + for (z=0; z=0 && zi=0 && yi=0 && xi dim_in[i]) samp[i] = ceil((double)dim_out[i]/(double)dim_in[i]); + else samp[i] = 1.0/(ceil((double)dim_in[i]/(double)dim_out[i])); + } + + for (z=0; z=0 && zi=0 && yi=0 && xi> should be done by CAT + def.quicktest = 0; % low quality setting for quick test of general running of settings + + job = cat_io_checkinopt(job,def); + + + [job.resdir,job.prefix] = spm_fileparts(job.prefix); + + + + + % this is a super parameter for default users to control logscale and + % intnorm in a simple manner (do / not do correction) + if job.intscale == 0 + job.logscale = 0; job.intnorm = 0; + elseif job.intscale == 1 % use defaults + job.logscale = def.logscale; job.intnorm = def.intnorm; + end + if isinf(job.logscale), lg = 'A'; else, lg = sprintf('%d',job.logscale); end + if isinf(job.intnorm), in = 'A'; else, in = sprintf('%d',job.intnorm); end + + if 0 %job.biascorrection == 0 + % RD20241010: no sure if this is useful + cat_io_addwarning('Warning:NoBiasCorrection','No bias correction > no intensity scaling!') + job.logscale = 0; + job.intnorm = 0; + end + + if job.quicktest + % Quicktest setting for faster SPM processing to test the principle running for various parameter + job.spm_preprocessing = 2; + job.spm_cleanupfiles = 0; + job.verb = 2; + end + + % update prefix + if cat_io_contains(job.prefix,'PARA') + job.prefix = strrep(job.prefix,'PARA',sprintf('MP2R_bc%d_lg%s_in%s_rn%d_ss%d',... + job.biascorrection, lg, in, job.restoreLCSFnoise, job.skullstripping)); + end + parastr = sprintf('(bc%d;lg%s;in%s;rn%d;ss%d)',... + job.biascorrection, lg, in, job.restoreLCSFnoise, job.skullstripping); + + % prepare output + out.files = job.files; + + + % TODO: + % * Bugs: + % - CJV values in T2/PD MP2R + % - PD/T2 MP2R with to strong background remval + % - intensity setting need further tests + % + % * Challanging data with extrem bias field: + % - 7T-TRT inv2-T1w data >> strong GM and even stronger thickness + % understimation in CAT + % * Improve bone correction in case of MP2R use BG intensity as minimum + % and fat intensity as maximum + % * Add QC measures (as we have the SPM segmentation) + % * Bias correction warning if brain tissues show high variation or + % corrections of the segmentation (closing) where done? + % * Report (make changes transparent) + % > colors to support faster review + % > add histogram !!! + % > colormap for images? + % > intensity peaks org / cor + % > resolution + % - variable/memory cleanup + % + % x What to do in case of worse results? + % - Just use the original? + % - No, problems should be visible to be fixed + % x blood vessel correction ? + % - No, should be done by PP, but may aboid precorrection. + % - Maybe indirectly as part of the skull-stripping (reinclude as brain or not) + + %#ok<*CLOCK,*DETIM> + + %% main processing + spm_progress_bar('Init',numel(job.files),'MP2Rage Optimization','Volumes Complete'); + for si = 1:numel(job.files) + clear Yseg Ym Yo; + + % be verbose + stime = clock; + if job.verb + [pp,ff,ee] = spm_fileparts(job.files{si}); + fprintf('%4d) %80s: ',si,spm_str_manip( fullfile(pp,[ff,ee]), 'a80')); + end + + + %% estimate if MP2R to set up the SPM processing + % MP2R is here defined as an image with high intensity background, ie. + % there is no low intensity background + % In low-int background data a threshold bit below the median will + % separate the object (head/brain) from the background, whereas in + % an MP2R this is not the case and the thresholded regions covers + % the whole image. + Vm = spm_vol( job.files{si} ); + Ym = spm_read_vols( Vm ); + [Ymr,res] = cat_vol_resize(Ym,'reduceV',1,4,16,'meanm'); + Ymo = cat_vol_morph(smooth3(Ymr) > 0.9*median(Ymr(:)),'lc',4) & Ymr~=0; + res.isMP2R = sum(Ymo(:) | Ymr(:)==0) > 0.98*numel(Ymo); + clear Ymo Ymr Ym Vm; + + + %% check if processed data is available + SPMdata = [ + spm_file(job.files(si),'suffix','_seg8','ext','.mat') + spm_file(job.files(si),'prefix','m' ,'ext','.nii') + spm_file(job.files(si),'prefix','c1','ext','.nii') + spm_file(job.files(si),'prefix','c2','ext','.nii') + spm_file(job.files(si),'prefix','c3','ext','.nii') + spm_file(job.files(si),'prefix','c4','ext','.nii') + spm_file(job.files(si),'prefix','c5','ext','.nii') + ]; + SPMdatae = zeros(numel(SPMdata),1); + for fi = 1:numel(SPMdata) + SPMdatae(fi) = exist( SPMdata{fi} , 'file'); + end + + if job.spm_preprocessing==2 || ... allways run SPM segmentation + (job.spm_preprocessing==1 && any(~SPMdatae)) ... only if the segments are missing + + %% SPM segmentation + if job.verb>1, fprintf('\n'); end + stime2 = cat_io_cmd(' SPM segmentation','g5','',job.verb-1); + + spmiter = max(1,2 - 1*res.isMP2R); + % if no bias-correction is used also the additional iterations are not useful + if job.biascorrection <= 1, spmiter = 1; end + % for quick tests we not need full quality ? + if job.quicktest > 1, spmiter = 1; end + for i = 1:spmiter + % *** biasreg 1e-6 caussed problems in the head tissue *** + % *** even 2 mm are not always better *** + if job.verb>1 && i>1, fprintf('.'); end + if job.biascorrection && i~=1 + matlabbatch{1}.spm.spatial.preproc.channel.vols = spm_file(job.files(si),'prefix','m'); + else + matlabbatch{1}.spm.spatial.preproc.channel.vols = job.files(si); + end + if i==1 + % the first iteration should be smooth + if res.isMP2R % only one iteration + matlabbatch{1}.spm.spatial.preproc.channel.biasfwhm = 60; + matlabbatch{1}.spm.spatial.preproc.warp.samp = 3; + else + matlabbatch{1}.spm.spatial.preproc.channel.biasfwhm = 120; + matlabbatch{1}.spm.spatial.preproc.warp.samp = 6; + end + elseif i==spmiter + % final iterations could do further corrections + matlabbatch{1}.spm.spatial.preproc.channel.biasfwhm = 30; + matlabbatch{1}.spm.spatial.preproc.warp.samp = 3; % 3 - (spmiter>2 && spmiter==i); % 2 mm only for 3 iters + else % intermediate + matlabbatch{1}.spm.spatial.preproc.channel.biasfwhm = 60; + matlabbatch{1}.spm.spatial.preproc.warp.samp = 4; % 3 - (spmiter>2 && spmiter==i); % 2 mm only for 3 iters + end + matlabbatch{1}.spm.spatial.preproc.channel.biasreg = 1e-4; % biasreg 1e-6 caussed problems on the bottom of the TPM + matlabbatch{1}.spm.spatial.preproc.channel.write = [0 job.biascorrection>0]; % write bias corrected image + ngaus = [1 1 2-res.isMP2R 3 4 2+res.isMP2R]; % use 3 to have more stable MP2R backgrounds + for ti = 1:6 + matlabbatch{1}.spm.spatial.preproc.tissue(ti).tpm = ... + {fullfile(spm('dir'),'tpm',sprintf('TPM.nii,%d',ti))}; + matlabbatch{1}.spm.spatial.preproc.tissue(ti).ngaus = ngaus(ti); + matlabbatch{1}.spm.spatial.preproc.tissue(ti).native = ... + [((ti<6 & spmiter==i) | ti==2 | ti==5) 0]; + matlabbatch{1}.spm.spatial.preproc.tissue(ti).warped = [0 0]; + end + matlabbatch{1}.spm.spatial.preproc.warp.mrf = 1; + matlabbatch{1}.spm.spatial.preproc.warp.cleanup = 1; + matlabbatch{1}.spm.spatial.preproc.warp.reg = [0 0.001 0.5 0.05 0.2]; + matlabbatch{1}.spm.spatial.preproc.warp.affreg = 'mni'; + matlabbatch{1}.spm.spatial.preproc.warp.fwhm = 2 * (i==1); + matlabbatch{1}.spm.spatial.preproc.warp.write = [0 0]; + matlabbatch{1}.spm.spatial.preproc.warp.vox = NaN; + matlabbatch{1}.spm.spatial.preproc.warp.bb = [NaN NaN NaN; NaN NaN NaN]; + + if job.quicktest + matlabbatch{1}.spm.spatial.preproc.channel.biasfwhm = 60; + matlabbatch{1}.spm.spatial.preproc.channel.biasreg = 1e-4; + matlabbatch{1}.spm.spatial.preproc.warp.samp = 5; + end + + % run SPM + sii = 0; spmfailed = 0; + while sii<3 + sii = sii + 1; + try + evalc('spm_jobman(''run'',matlabbatch)'); + catch + spmfailed = 1; + continue + end + + % use bias corrected in next iteration + [pp,ff,ee] = spm_fileparts(job.files{si}); mfile = fullfile(pp,[ff,ee]); + if job.biascorrection && i > 1 + movefile( spm_file(mfile,'prefix','mm'), spm_file(mfile,'prefix','m') ); + + [pp,ff,ee] = spm_fileparts(job.files{si}); mfile = fullfile(pp,[ff,ee]); + for ti = 1:6 + if exist( spm_file(mfile,'prefix',sprintf('c%dm',ti)) , 'file' ) + movefile( spm_file(mfile,'prefix',sprintf('c%dm',ti)), ... + spm_file(mfile,'prefix',sprintf('c%d',ti)) ); + end + end + end + + % basic test +% test spm8 values + if exist( spm_file(mfile,'prefix','c5') ,'file') + Vseg(5) = spm_vol(spm_file(mfile,'prefix','c5')); + Yseg{5} = single( spm_read_vols(Vseg(5)) ); + if std(Yseg{5}(Yseg{5}(:)>0)) > 0 + matlabbatch{1}.spm.spatial.preproc.channel.biasfwhm = ... + max(60,round(matlabbatch{1}.spm.spatial.preproc.channel.biasfwhm / 1.5,-1)); + matlabbatch{1}.spm.spatial.preproc.warp.samp = ... + max(3, round(matlabbatch{1}.spm.spatial.preproc.warp.samp * .8,1)); + continue + else + break + end + end +% optimize cls parameters +% .. in later iterations test for fatsup value + end + if spmfailed + cat_io_cprintf('err','SPM failed - check origin'); + continue; + end + + %% basic informations + spm8 = load(spm_file(job.files{si},'suffix','_seg8','ext','.mat')); + res.isT1 = (spm8.mn(spm8.lkp==2)*spm8.mg(spm8.lkp==2)) > ... + (spm8.mn(spm8.lkp==1)*spm8.mg(spm8.lkp==1)); + res.isMP2R = (spm8.mn(spm8.lkp==6)*spm8.mg(spm8.lkp==6)) > ... + min( 0.5 * (spm8.mn(spm8.lkp==2)*spm8.mg(spm8.lkp==2)) , ... + 2.0 * (spm8.mn(spm8.lkp==3)*spm8.mg(spm8.lkp==3)) ); + res.fatsup = ((spm8.mn(spm8.lkp==5 & spm8.mg'>.2)*spm8.mg(spm8.lkp==5 & spm8.mg'>.2)) / ... + (spm8.mn(spm8.lkp<3)*spm8.mg(spm8.lkp<3)) ) < .3; + res.fatsup = (mean(spm8.mn(spm8.lkp==5 & spm8.mg'>.25)) / mean(spm8.mn(spm8.lkp<3))) < .9; + vx_vol = sqrt(sum(spm8.image.mat(1:3,1:3).^2)); + + + + %% + if job.biascorrection>1 && ~res.isMP2R && i~=spmiter %&& i>1 + % Using only SPM for bias correction was not successful in super + % extrem cases as the SPM model was stable even the bias was still + % included. Hence, we use the most important segments the WM and + % head to do a very quick/simple/smooth additional correction. + % Skip the first iteration as it was worse with the SPM8 estimates. + + % load SPM bias correct image and the WM and head segment + Pm = spm_file(job.files{si},'prefix','m'); + Vm = spm_vol(Pm); + Ym = single( spm_read_vols(Vm) ); + + Yseg = cell(1,6); + Pseg = cell(1,6); Tth = zeros(1,6); + for ci = [1,2,5] + Pseg{ci} = spm_file(job.files{si},'prefix',sprintf('c%d',ci),'ext','.nii'); + if exist(Pseg{ci},'file') + Vseg(ci) = spm_vol(Pseg{ci}); %#ok + Yseg{ci} = single( spm_read_vols(Vseg(ci)) ) & Ym~=0; + end + Tth(ci) = spm8.mn(spm8.lkp==ci) * spm8.mg(spm8.lkp==ci); + end + if res.isT1 && std(Yseg{5}(Yseg{5}(:)>0))==0 % correct SPM bug + Yseg{5}(Ym<.1*Tth(2)) = 0; + end + Yd = cat_vol_div(Ym./Tth(2),vx_vol,2); + + %% fatsup + [Ymr,Yhd,Ywm,resV] = cat_vol_resize( {Ym,Yseg{5} & smooth3(Ym)>.2*Tth(2),Yseg{2}},'reduceV',vx_vol,1.2,4,'meanm'); %clear Ypx# + Ywm = cat_vbdist( single( smooth3(Ywm) ) , Ymr>0.15*Tth(2), resV.vx_volr ); + Yhd = cat_vol_morph(Yhd & Ywm>5 & Ywm<30,'ldo',2,vx_vol); + Yhd = cat_vbdist( single( smooth3(1-Yhd) ) , Yhd>0, resV.vx_volr ); + Ygt = cat_vol_pbtp( single(3-(smooth3(Yhd>0))) , Yhd , 0*Yhd ); + Yhdppr = Yhd./max(eps,Ygt); Yhdppr(Yhdppr==1 & smooth3(Yhdppr)<.5 | Yhdppr>1) = 0; + isfatsup0 = [ mean( Ymr( Yhdppr(:)>0.5) ) mean( Ymr( Yhdppr(:)>0 & Yhdppr(:)<0.5) ) ]; % inner + isfatsup = isfatsup0(1) / isfatsup0(2) < 1.2; + Yhdpp = cat_vol_resize(Yhdppr,'dereduceV',resV); + if isfatsup, cat_io_cprintf([0 .5 0],'_'); else, cat_io_cprintf('warn','^'); end + res.fatsup = isfatsup; + + %% use the WM and head segment to estimate another smooth bias corrected imags + mth = max(min(Tth(1:2)), min( Tth(5) , mean(Tth(1:2)))); + Yg = cat_vol_grad(Ym)./Ym; + Ypx = (Yseg{2}>.125)*Tth(2) + ... + cat_vol_morph( smooth3((Yseg{5})>.2 & (Ym)>0.05*Tth(2))>.7,'lo',3)*mth; + Ypx( smooth3(Ypx>0)<.1 | Ym==0 | (Yg>.5 & Yseg{2}<.1)) = 0; + Ypx(Ypx==0 & Yhdpp>0.1 & Yhdpp<.5 & Ym>min(Tth(1:2))) = mth; + Ympx = (Ypx~=0) .* cat_vol_localstat(Ym,Ypx>0,1,2+res.isT1); + if isfatsup==0 + [Ymr,Ypxr,resV] = cat_vol_resize( {max(Ym,Ympx),Ypx},'reduceV',vx_vol,1.5,4,'meanm'); %clear Ypx + Ywi0 = cat_vol_approx(Ymr ./ Ypxr); + Ywi0 = cat_vol_smooth3X(Ywi0,16); + Ywi0 = cat_vol_resize(Ywi0,'dereduceV',resV); + Ywi0 = Ywi0 ./ cat_stat_nanmedian(Ywi0(Yseg{2}>.5)); + %Ypx( Ypx>0 & (Ym ./ Ywi0) > Tth(2)*0.9 & (Ym ./ Ywi0) < Tth(2)*0.9 & Yseg{5}>.1) = 0; + Ypx( Ypx>0 & (Ym ./ Ywi0) > Tth(2)*0.9 & Yseg{5}>.1) = max(spm8.mn(spm8.lkp==5)); + Ypx(Ypx==0 & Yhdpp>.5 & Ym>.5*Tth(2)) = max(spm8.mn(spm8.lkp==5)); + end + %% + [Ymr,Ypxr,resV] = cat_vol_resize( {max(Ym,Ympx),Ypx},'reduceV',vx_vol,1.5,4,'meanm'); %clear Ypx + Ywr = cat_vol_localstat(Ymr ./ Ypxr,Ypxr>0,2,2+res.isT1); + Ywir = cat_vol_approx(Ywr); clear Ywr Ymr; + % Ymxr = cat_vol_smooth3X(Ypxr~=0,8); clear Ypxr; + % Ywir = cat_vol_smooth3X(Ywir,2).*Ymxr + (1-Ymxr).*cat_vol_smooth3X(Ywir,2); + Ywir = cat_vol_smooth3X(Ywir,2 + 2*(i==1)); + Ywi = cat_vol_resize(Ywir,'dereduceV',resV); clear Ywir; + Ywi = Ywi ./ cat_stat_nanmedian(Ywi(Yseg{2}>.5)); + + % quantify bias field to interupt unnecessary loops? + BF(i) = std(Ywi(:)) / min(abs(diff(Tth(1:2)/max(Tth(1:2)) ))); + + %% write the result + spm_write_vol(Vm,Ym ./ Ywi); + clear Ym Yseg Ywi + +% document values for XML report + end + end + + else + stime2 = clock; + % if SPM data is incomplete but we are not allow to do it + if any(~SPMdatae) + cat_io_addwarning('Warning:BadSPMdata',['Cannot find all required preprocessed SPM files \\n' ... + '(*seg8.mat, m*.nii, c#*.nii). Continue with next subject!']); + continue + end + end + + + + + %% load SPM mat (with tissue thresholds) + if etime(clock,stime2) < 10 + if job.verb>1, fprintf('\n'); end % no + stime2 = cat_io_cmd(' Load segmentation','g5','',job.verb-1); + else + stime2 = cat_io_cmd(' Load segmentation','g5','',job.verb-1,stime2); + end + spm8 = load(spm_file(job.files{si},'suffix','_seg8','ext','.mat')); + + % load original for skull-stripping + if isfield(job,'ofiles') + Po = job.ofiles{si}; + Vo = spm_vol(Po); + Yo = single( spm_read_vols(Vo)); + else + Po = job.files{si}; + Vo = spm_vol(Po); + Yo = single( spm_read_vols(Vo)); + end + + % load bias corrected +% ############# use the original if no bias corrected was written? ########## + if job.biascorrection + Pm = spm_file(job.files{si},'prefix','m'); + else + Pm = job.files{si}; + end + Vm = spm_vol(Pm); + Ym = single( spm_read_vols(Vm)); + vx_vol = sqrt(sum(Vm.mat(1:3,1:3).^2)); + + % load segmentation (for brain masking) + Yseg = zeros(Vm.dim,'single'); + Pseg = cell(1,6); Tth = zeros(1,6); Sth = Tth; + for ci = 1:5 + Pseg{ci} = spm_file(job.files{si},'prefix',sprintf('c%d',ci)); + Vseg(ci) = spm_vol(Pseg{ci}); + Yseg(:,:,:,ci) = single( spm_read_vols(Vseg(ci)) ); + Ymsk = cat_vol_morph( Yseg(:,:,:,ci)>.9 ,'e') & Ym~=0; + Tth(ci) = cat_stat_nanmedian(Ym(Ymsk(:))); + if isnan(Tth(ci)) + Ymsk = cat_vol_morph( Yseg(:,:,:,ci)>.5 ,'e') & Ym~=0; + Tth(ci) = cat_stat_nanmedian(Ym(Ymsk(:))); + end + if isnan(Tth(ci)) + Ymsk = Yseg(:,:,:,ci)>.5 & Ym~=0; + Tth(ci) = cat_stat_nanmedian(Ym(Ymsk(:))); + end + Sth(ci) = cat_stat_nanstd(Ym(Ymsk(:))); + end + clear Ymsk Vseg; + Yseg(:,:,:,6) = 1 - cat_stat_nansum( Yseg, 4); + Tth(6) = cat_stat_nanmedian(Ym(Yseg(:,:,:,6) & Ym~=0)); + res.isMP2R = Tth(6) > min(Tth(2)/2,Tth(3)*2); % MP2Rage + res.isT1 = Tth(3) < Tth(1) & Tth(1) < Tth(2); % T1 defintion + if 0 % ~res.isT1 + cat_io_cprintf('err','No T1w contrast or bad segmentation!\n') + %continue + end + if any( isnan(Tth) ) + cat_io_cprintf('err','Bad contrast or segmentation!\n') + end + + + +%% %########################## +% detect critical segmentations / skull-strippings +% >> stop case processing and continue with next subject +% >> don't repair! but maybe suggest to check and to what aparameter could +% be changed +% Case 1 - Buchert 125849) failed GM/WM segmentation but BET is ok +% Case 2 - Buchert 150601) extrem low contrast (remove/ignore/bullshit in=bullshit out) +% Case 3 - Buchert 155553) low contrast (high-res, low-freq-noise) but good segmentation +% Case 4 - Buchert 155802) failed bias correction ... +% Yp0 = Yseg(:,:,:,1)*2 + Yseg(:,:,:,2)*3 + Yseg(:,:,:,3); + iCon = @(x) (exp(x) - 1) / (exp(1)-1); + +% ######################## WMHs ?! ############# +% ### errors with BVs and MAs ... test for local high variance in tissues +% ############# + + + if res.isMP2R + norm2 = @(Yx, Ycmm,Ywmm) (Yx - median(Yx(Ycmm(:)))) ./ ... + ( median(Yx(Ywmm(:))) - median(Yx(Ycmm(:)))) * 2/3 + 1/3; + norm2i = @(Yx,Yy,Ycmm,Ywmm) (Yx - 1/3) .* ... + ( median(Yy(Ywmm(:))) - median(Yy(Ycmm(:))) )*2/3 + median(Yy(Ycmm(:))); + else + norm2 = @(Yx, Ycmm,Ywmm) (Yx - median(Yx(Ycmm(:))) + std(Yx(Ycmm(:))) ) ./ ... + ( median(Yx(Ywmm(:))) - median(Yx(Ycmm(:))) + std(Yx(Ycmm(:))) ); + norm2i = @(Yx,Yy,Ycmm,Ywmm) (Yx - 1/3) .* ... + ( median(Yy(Ywmm(:))) - median(Yy(Ycmm(:))) + std(Yx(Ycmm(:))) ) + median(Yy(Ycmm(:))) - std(Yx(Ycmm(:))) ; + end + if res.isT1 + exp1 = exp(1) - 1; + Ywmm = cat_vol_morph( Yseg(:,:,:,2)>.9 ,'e'); + Ycmm = smooth3( (Yseg(:,:,:,3)>.95 | ( (Yseg(:,:,:,6)>.95) .* (Tth(6) < Tth(3))) ) & Ym/spm8.mn(2)<.5)>.5; + Tthm = norm2( Tth , 3, 2); + Ymm = norm2( Ym, Ycmm, Ywmm); log1str = 'Y'; + for i = 1:3 + TX = real(... + [ norm2( exp( norm2(Tthm, 3, 2)*2/3+1/3 - 1) / exp1 , 3, 2); + norm2( norm2(Tthm, 3, 2)*2/3+1/3 , 3, 2); + norm2( log2( norm2(Tthm, 3, 2)*2/3+1/3 + 1) , 3, 2); + norm2( log( (norm2(Tthm, 3, 2)*2/3+1/3) * exp1 + 1), 3, 2); + norm2( log10((norm2(Tthm, 3, 2)*2/3+1/3) * 9 + 1), 3, 2) ]); + [mx,cci] = min( abs(TX(1:5) - 0.7)); + Tthm = TX(cci,:); + + if cci == 1 + Ymm2 = exp ( norm2(Ymm, Ycmm, Ywmm)*2/3+1/3 - 1) / exp1; lstr = 'exp'; %% without / exp1 ??? + elseif cci == 2 + Ymm2 = norm2(Ymm, Ycmm, Ywmm)*2/3+1/3; lstr = 'non'; + elseif cci == 3 + Ymm2 = log2 ( norm2(Ymm, Ycmm, Ywmm)*2/3+1/3 + 1); lstr = 'log2'; + elseif cci == 4 + Ymm2 = log ( (norm2(Ymm, Ycmm, Ywmm)*2/3+1/3) * exp1 + 1); lstr = 'log'; + elseif cci == 5 + Ymm2 = log10( (norm2(Ymm, Ycmm, Ywmm)*2/3+1/3) * 9 + 1); lstr = 'log10'; + end + if cci == 2 || mx < 0.02; break; end + log1str = sprintf('%s(%s)',lstr,log1str); + + if res.isMP2R + Ymm = norm2( real(Ymm2) , Ycmm , Ywmm); + else + Ymm = norm2( real(Ymm2) , Yseg(:,:,:,6)>.9 & Ym.5); + Ym2 = Ym; + Tthm = Tth; + Ym2(Yo==0)=0; + clear Ymm + end + + + + %% get (MP2R) background + [Ybgr,resV] = cat_vol_resize( Yseg(:,:,:,6)>.1 & Ym<1.5*Tth(2),'reduceV',vx_vol,2,4,'meanm'); + Ybgr = cat_vol_morph(cat_vol_morph(Ybgr,'ldo',2),'l',[10 0.2]); + Ybgr = cat_vol_smooth3X(Ybgr,2); + Ybg = cat_vol_resize(Ybgr,'dereduceV',resV); + Ybg = Ybg>.5 & smooth3(Yo)~=0; + + + + % estimate if fat supression is used + % get tissue surrounding the upper skull to estimate if fat supression + [Ymr,resV] = cat_vol_resize( Ym/Tth(2),'reduceV',vx_vol,2,4,'meanm'); + Ysegr = nan([resV.sizeTr,size(Yseg,4)],'single'); + for ti = 1:size(Yseg,4) + Ysegr(:,:,:,ti) = cat_vol_resize( Yseg(:,:,:,ti),'reduceV',vx_vol,2,4,'meanm'); + end + + % estimate distance maps to identify the upper skull + Ybgdistr = cat_vbdist( Ybgr , sum(Ysegr(:,:,:,1:3) ,4) <.5, resV.vx_volr); + Ybdistr = cat_vbdist( sum(Ysegr(:,:,:,1:3) ,4) , Ybgr<.5 , resV.vx_volr); + Ysdistr = cat_vbdist( sum(Ysegr(:,:,:,1:4) ,4) , Ybgr<.5 , resV.vx_volr); + Yuskinr = Ysegr(:,:,:,5)>.5 & Ybdistr<20 & Ybgdistr<20 & Ybdistr>Ysdistr & ... + cat_vol_morph(1 - Ysegr(:,:,:,5)>.2,'dc',10,resV.vx_volr); + Yhdppr = min(Ysdistr,Ybgdistr) ./ (Ybgdistr/2 + Ysdistr/2) .* Yuskinr; + % clear Ysegr Ybdistr + + % final evaluation + %{ + fatsup = [ median( Ymr(Yhdppr(:)<1/2 & Yhdppr(:)>0) ) > median( Ymr(Yhdppr(:)>1/2) ) , ... low-int central area + abs(median( Ymr(Yhdppr(:)<1/2 & Yhdppr(:)>0 & Ybgdistr(:)0 & Ybgdistr(:)>=Ysdistr(:)) )) < .1 , ... + ( spm8.mn(spm8.lkp==5) * spm8.mg(spm8.lkp==5) / Tth(2) ) > 1 ]; + % clear Ymr Ybgdistr Ysdistr + res.fatsup = sum(fatsup)>=1; + %} + Yhdpp = cat_vol_resize(Yhdppr,'dereduceV',resV); + + + + %% extended bias correction + if job.biascorrection > 1 + stime2 = cat_io_cmd(' Bias correction','g5','',job.verb-1,stime2); + + % Use also the GM area to get the closes WM value by a maximum operation (i.e. T1 only). + % We are not using the CSF as we are not knowing much about it and and cannot trust the segmentation too much. + Yg = cat_vol_grad(Ym2)./Ym2; Ygs = smooth3(Yg); + if 0 + %% old version + + % define bias correction field for each tissue + Ywi = cat_vol_localstat(Ym2,cat_vol_morph(Yseg(:,:,:,2)>.5,'lc') ,1,2+res.isT1); + Ywi = cat_vol_median3(Ywi,Ywi>0,Ywi>0); + Ywi(Ybg | Yo==0) = Tth(2); % avoid overcorrections outside the brain + % remove outlier voxels res.fatsup = sum(fatsup)>=2; + Ywiv = cat_vol_localstat(Ywi,Ywi~=0,1,4); + wivth = cat_stat_nanmedian(Ywiv(Ywiv(:)~=0)); + Ywi(Ywiv>(wivth*2)) = 0; Ywi(smooth3(Ywi~=0)<.5) = 0; + clear Ywiv wivth; + + % mean here to handle noise .. .* (Ym2>0 | Ym2.5 & Ygs<.5 ), ...& ~Ysc + single(smooth3(cat_stat_nansum(Yseg(:,:,:,1:2),4))>.5 & Ygs<.5 )},'reduceV',vx_vol,1.5,4,'meanm'); + Ygi1 = cat_vol_localstat(Ym2r,Ym2r~=0 & Ygi1>.5,4,2 + res.isT1); % closer to WM + Ygi2 = cat_vol_localstat(Ym2r,Ym2r~=0 & Ygi2>.5,2,2 + res.isT1); % more distant to WM + Ygi1(Ygi2>0 & Ygi1==0) = Ygi2(Ygi2>0 & Ygi1==0); + Ygi = cat_vol_approx( Ygi1 ); + % clear Ym2r Ygi1 Ygi2 + Ygi = cat_vol_resize(Ygi,'dereduceV',resV); % .* (Yseg(:,:,:,1)>.2); + % adaption for high noise bias in low intensity regions + Ygi = Ygi*.5 + 0.5*(iCon(Ygi / spm8.mn(2))*spm8.mn(2)); + Ywi(Ygi>0 & Ywi==0) = Ygi(Ygi>0 & Ywi==0); + Ywi = cat_vol_approx( Ywi ); + else + %% new version + + % create values for brain and muscles + Ypx = Yseg(:,:,:,1)*Tthm(1) + Yseg(:,:,:,2)*Tthm(2) + Yseg(:,:,:,3)*Tthm(3)*.9; + + if res.isMP2R + % in MP2R only add background and ignore other things + Ypx(Ybg & Yo~=0) = cat_stat_nanmean( Ym2(Ybg(:) & Yo(:)~=0)); + Yw = Ym2./Ypx .* (Ypx>0 & (Ygs<.4 | Yseg(:,:,:,5)>0)); Yw(Yw>2)=0;% clear Ypx + else + % in MPR we need to use the skull to handle extreme cases + % depending on the fat suppression ... + Ypx = Yseg(:,:,:,1)*Tthm(1) + Yseg(:,:,:,2)*Tthm(2) + Yseg(:,:,:,3)*Tthm(3)*.9; + + Ypx = Ypx + (Yseg(:,:,:,5)>.125) * mean(Tthm(1)) .* (cat_vol_morph(Ygs<0.5,'o') & ~Ybg & Yo~=0); + %Ypx = (Yseg{2}>.125)*Tth(2) + ... + % cat_vol_morph( smooth3((Yseg{5})>.2 & (Ym)>0.05*Tth(2))>.7,'lo',3)*mth; + Ypx( smooth3(Ypx>0)<.1 | Ym==0 | (Yg>.5 & Yseg(:,:,:,2)<.1)) = 0; + Ypx(Ypx==0 & Yhdpp>0.1 & Yhdpp<.5 & Ym>min(Tth(1:2))) = mean(Tthm(1)); + %% + if res.fatsup + Ylb = (smooth3(Ypx>0)<0.1 & smooth3(Yseg(:,:,:,5))>0.5 ); + Ypx = max(Ypx, (Ylb & Ym>Tth(3)) .* mean(Tthm(1:2)) ); + Ypx = max(Ypx, (Ylb & smooth3(Yhdpp)>Ym/3 & Ym>Tth(3)) .* min(1,1 - Yhdpp) * mean(Tthm(1:2))); % two skin layer + else + %% + Ypx = Ypx + (Ypx==0 & Yhdpp>.1 & Ym>Tth(3) & Yg>0.1) .* (Yhdpp .* max(spm8.mn(spm8.lkp==5))); + + Ympx = (Ypx~=0) .* cat_vol_localstat(Ym,Ypx>0,2,2+res.isT1); + %{ + Ywi0 = cat_vol_approx(Ympx ./ Ypx); + Ywi0 = cat_vol_smooth3X(Ywi0,32); + Ywi0 = Ywi0 ./ cat_stat_nanmedian(Ywi0(Yseg(:,:,:,2)>.5)); + Ypx( cat_vol_morph( Ypx>0 & (Ym ./ Ywi0) > Tth(2)*.9 & (Ym ./ Ywi0) < Tth(2)*1.2 & Yseg(:,:,:,5)>.1 ,'d' )) = 0; + Ypx( cat_vol_morph( Ypx>0 & (Ym ./ Ywi0) > Tth(2)*1.2 & Yseg(:,:,:,5)>.1 ,'d' )) = ... + max(spm8.mn(spm8.lkp==5)); + %} + [Ymr,Ypxr,resV] = cat_vol_resize( {max(Ym,Ympx),Ypx},'reduceV',vx_vol,1.5,4,'meanm'); %clear Ypx + Ywi0 = cat_vol_approx(Ymr ./ Ypxr); + Ywi0 = cat_vol_smooth3X(Ywi0,16); + Ywi0 = cat_vol_resize(Ywi0,'dereduceV',resV); + Ywi0 = Ywi0 ./ cat_stat_nanmedian(Ywi0(Yseg(:,:,:,2)>.5)); + Ypx( (Ym ./ Ywi0) > Tth(2)*0.9 & Yseg(:,:,:,5)>.1) = max(spm8.mn(spm8.lkp==5)); + Ypx( Yhdpp>.4 & Ym>.5*Tth(2)) = max(spm8.mn(spm8.lkp==5)); + + end + Yw = Ym2./Ypx .* (Ypx>0 & (Ygs<.4 | Yseg(:,:,:,5)>0) & ~Ybg); Yw(Yw>2)=0;% clear Ypx + end + + %Ypx = Ypx .* cat_vol_morph(Ypx>0 & ~Ybg,'l',[10 .1]); + Yw = cat_vol_localstat(Yw,Yw~=0,2,2 + res.isT1); + % + [Ywi,Ywm,resV] = cat_vol_resize({Yw,single(Yw>0)},'reduceV',vx_vol,2,4,'meanm'); + Ywi(Ywm<.25) = 0; clear Ywm; + Ywi = cat_vol_approx(Ywi,'rec'); + Ywi = cat_vol_smooth3X(Ywi,2); + Ywi = cat_vol_resize(Ywi,'dereduceV',resV); + % extended smoothing + Ybs = cat_vol_smooth3X(sum(Yseg(:,:,:,1:3),4),8); + Ywis = cat_vol_smooth3X(Ywi,4); + Ywi = Ywi .* Ybs + (1-Ybs) .* Ywis; clear Ybs Ywis; + % scaling + Ywi = Ywi ./ median(Ywi(Yseg(:,:,:,2)>.9)); + end + Ym3 = Ym2./Ywi; + Ywi = Ywi .* median(Ym3(Yseg(:,:,:,2)>.5)); + clear Ygi Ym3 + + + %% mix tissues and approximate bias field + if res.isMP2R + Ygw = sum(Yseg(:,:,:,2),4)>.5; + Yw = Ywi / mean(Ywi(Ygw(:))) * mean(Ym2(Ygw(:))); + else + %% for the inpaint method the use of GM information was less optimal + % - first estimation for background + Yi = Ywi; %max(Ywi,Ybi .* ( cat_vol_morph(Yseg(:,:,:,5)>.5,'l') & (Ym./spm8.mn(3))>.5) * spm8.mn(2) ); + Yw = cat_vol_inpaint(Yi,10,40,2,1); Yw = Yw*0.9 + 0.1 * iCon(Yw./spm8.mn(2)).*spm8.mn(2); + Yw = Yw ./ cat_stat_nanmedian(Yw(Yseg(:,:,:,2)>.95)) .* cat_stat_nanmedian(Ym2(Yseg(:,:,:,2)>.95)); + % - second estimation for + Yi = max(Ywi,Yw .* ( cat_stat_nansum(Yseg(:,:,:,6),4)>.5 )); + Yw = cat_vol_inpaint(Yi,10,6 / job.biascorrection,2,1); + Yw = Yw*0.9 + 0.1 * iCon(Yw./spm8.mn(2)).*spm8.mn(2); + %Yw = Yw ./ cat_stat_nanmedian(Yw(Yseg(:,:,:,2)>.95)); % .* cat_stat_nanmedian(Ym2(Yseg(:,:,:,2)>.95)); + + end + + % apply bias correction + Ymm = Ym2 ./ Yw; + else + % no bias correction + Ymm = Ym2; + end + Ymbc = Ymm; + + + + + + %% general exp/log scaling + if res.isMP2R && res.isT1 + norm2 = @(Yx, Ycmm,Ywmm) (Yx - median(Yx(Ycmm(:)))) ./ ... + ( median(Yx(Ywmm(:))) - median(Yx(Ycmm(:)))) * 2/3 + 1/3; + norm2i = @(Yx,Yy,Ycmm,Ywmm) (Yx - 1/3) .* ... + ( median(Yy(Ywmm(:))) - median(Yy(Ycmm(:))) ) * 2/3 + median(Yy(Ycmm(:))); + else + norm2 = @(Yx, Ycmm,Ywmm) (Yx - median(Yx(Ycmm(:))) + std(Yx(Ycmm(:))) ) ./ ... + ( median(Yx(Ywmm(:))) - median(Yx(Ycmm(:))) + std(Yx(Ycmm(:))) ); + norm2i = @(Yx,Yy,Ycmm,Ywmm) (Yx - 1/3) .* ... + ( median(Yy(Ywmm(:))) - median(Yy(Ycmm(:))) + std(Yx(Ycmm(:))) ) + median(Yy(Ycmm(:))) - std(Yx(Ycmm(:))) ; + end + if res.isT1 + if job.logscale>0 || job.intnorm>0 + stime2 = cat_io_cmd(' Scale intensities','g5','',job.verb-1,stime2); + end + %Ymm = Ym ./ Yw; % only for debugging + exp1 = exp(1) - 1; + if job.logscale == 1 + Ymm = log( Ymm/spm8.mn(2) * exp1 + 1) * spm8.mn(2); + elseif job.logscale == 2 + Ymm = log2( (Ymm/spm8.mn(2)) + 1) * spm8.mn(2); + elseif job.logscale == 10 + Ymm = log10( (Ymm/spm8.mn(2)) * 9 + 1) * spm8.mn(2); + elseif job.logscale == -1 + Ymm = (exp( Ymm/spm8.mn(2) ) - 1) * spm8.mn(2) / exp1; + elseif isinf(job.logscale) % auto + % we typically expect the GM value at about 60% of the WM peak + opt = 0.7; % BG + + % some images/classes that we need later + Ygm = Yseg(:,:,:,1)>.1 & ~cat_vol_morph( Yseg(:,:,:,1)>.5 ,'o',4); + Ywm = cat_vol_morph( Yseg(:,:,:,2)>.9 ,'e'); + + Ywmm = Ywm; %Yseg(:,:,:,2)>.95; + Ycmm = smooth3( (Yseg(:,:,:,3)>.95 | ( (Yseg(:,:,:,6)>.95) .* (Tth(6) < Tth(3))) ) & Ym/spm8.mn(2)<.5)>.5; + + %% + %Ymm = norm2(Ymm,Ycmm,Ywmm); + res.logscaleres = ''; + res.log2str = 'Y'; + for opti = 1:3 + % ################ local adaption or mixture of values? + for ii = 1:2 + if ii == 1, cli = 1:5; else, ccm = abs(cc - opt); [ccmin,cci] = min( ccm ); cli = cci; end + for cci = cli + if cci == 1, Ymm2 = exp ( norm2(Ymm, Ycmm, Ywmm)*2/3+1/3 - 1) / exp1; lstr = 'exp'; + elseif cci == 2, Ymm2 = norm2(Ymm, Ycmm, Ywmm)*2/3+1/3; lstr = 'non'; + elseif cci == 3, Ymm2 = log2 ( norm2(Ymm, Ycmm, Ywmm)*2/3+1/3 + 1); lstr = 'log2'; + elseif cci == 4, Ymm2 = log ( (norm2(Ymm, Ycmm, Ywmm)*2/3+1/3) * exp1 + 1); lstr = 'log'; + elseif cci == 5, Ymm2 = log10( (norm2(Ymm, Ycmm, Ywmm)*2/3+1/3) * 9 + 1); lstr = 'log10'; + end + if ii == 1 + Ymm2 = norm2i(Ymm2,Ymm2,Ycmm,Ywmm); + Ymmt = norm2(Ymm2,Ycmm,Ywmm); + cc(cci) = median( Ymmt(Ygm(:)) ); clear Ymmt + end + end + end + %Ymm = norm2i(Ymm2,Ymm,Ycmm,Ywmm); + Ymm = norm2(real(Ymm2),Ycmm,Ywmm); + + % ######## ccm = max(0,ccm + [0.04 0 0.01 0.02 0.04] - 0.04); + + ccistr = {'exponential','orgiginal','log2','log','log10'}; + scstr = sprintf('%12s-scaling (exp|org|log2|log|log10 = %s\b)',ccistr{cci},sprintf('%0.2f|',ccm)); + if job.verb > 1 && opti==1, fprintf('\n'); end + if job.verb > 1, cat_io_cprintf('g5',' %s\n',scstr); end + if cci == 2 || ccmin < 0.02; break; end + res.logscaleres = [res.logscaleres '; ' scstr]; + end + res.log2str = sprintf('%s(%s)',lstr,res.log2str); + if job.verb > 1, cat_io_cmd(' ','g5','',job.verb-1); end + %res.logscale = {ccistr;ccm}; + res.logscaleres = scstr; + else + Ygm = Yseg(:,:,:,1)>.1 & ~cat_vol_morph( Yseg(:,:,:,1)>.5 ,'o',4); + Ywm = cat_vol_morph( Yseg(:,:,:,2)>.9 ,'e'); + end + if 0% job.logscale>0 || job.intnorm>0 + stime2 = cat_io_cmd(sprintf(' Scale intensities (%s)',ccistr{cci}),'g5','',job.verb-1,stime2); %#ok + end + + + + %% scale intensities + % This is the critical part. + % log .. optimize the tissue peaks + % fx .. scaling function to reduce the + % Ygs .. add some left-sided noise of CSF values + + %fx = @(x,y,z) min(20,max(0,tan(((x-.5) * z + 0.5) * pi - pi/2)/pi/y/z + .2 + 0.5/y)); + fx2 = @(x,con,sqr) min(inf,max(-inf, ( abs(tan( max(-pi/2, min(pi/2, x * pi * con)))).^sqr .* sign(x)) )); + + if job.intnorm ~= 0 && res.isMP2R + if isinf(job.intnorm) || job.intnorm < 0 + if isinf(job.intnorm), intnorm = 0.5; else, intnorm = abs(job.intnorm); end + %Ym2 = fx( log( Ym/spm8.mn(2)* 1.71 + 1),1.4,.3); % this was worse + %Ym2 = fx2( (Ymm - median(Ymm(Ygm(:))) ) / spm8.mn(2) ,1.8,0.6); %works ok + %Ym2 = fx2( (Ymm - median(Ymm(Ygm(:))) ) / spm8.mn(2) ,.6,1.4); % stronger + Ym2 = fx2( (Ymm - median(Ymm(Ygm(:))) ) / spm8.mn(2) ,0.1,1 + intnorm/2 .* .3 * std(Ymm(Ygm(:))) / std(Ymm(Ywm(:))) ); % stronger + else + Ym2 = fx2( (Ymm - median(Ymm(Ygm(:))) ) / spm8.mn(2) ,0.1,job.intnorm); % manual + end + Ywmm = Yseg(:,:,:,2)>.95; Ycmm = smooth3(Yseg(:,:,:,3)>.95 & Ym/spm8.mn(2)<.5)>.5; + Ym2 = (Ym2 - median(Ym2(Ycmm(:)))) ./ (median(Ym2(Ywmm(:))) - median(Ym2(Ycmm(:)))); + Ym2 = Ym2 * 2/3 + 1/3 .* (Ymm>0); + clear Ywmm Ycmm; + else + %Ym2 = (Ymm / spm8.mn(2)) * 2/3 + 1/3 .* (Ym>0); + if res.isMP2R + Ym2 = norm2(Ymm,Ycmm & (Yseg(:,:,:,3)>.5),Ywmm); + else + Ym2 = norm2(Ymm, Ybg & Ymm.5 ,'e'); + % Ymstd = cat_vol_localstat(single(Ym / Tth(2)),Ybg,1,4); + % noise = cat_stat_nanmean(Ymstd(Ybg(:))); + + % Ym2 = (norm2(Ymm,Ycmm & (Yseg(:,:,:,3)>.5),Ywmm) - 1/3 + 4*noise ) * 1 / (2/3 + 8*noise); + clear Ymstd; + % Ym2 = (norm2(Ymm,Ycmm & (Yseg(:,:,:,6)>.5),Ywmm) - 1/3) * 3/2; + end + end + else + Ym2 = norm2(Ym2,Yo==0 | Yo.5); + end + + + + %% restore left-side CSF noise (value below zero that were just cutted) + if job.restoreLCSFnoise && res.isT1 + if res.isMP2R + stime2 = cat_io_cmd(' Restore CSF noise','g5','',job.verb-1,stime2); + + % define noise + pnoise = 0.03; % percentage of noise + Ymsk = Ym~=0 & Yseg(:,:,:,3)>0.8; % Ym ! + Ygs = Ymsk .* cat_vol_smooth3X( Yseg(:,:,:,3) .^2 ,2) .* ... + pnoise .* randn(size(Ym2)) .* min(1,1 + (Ym2 - 1/3)*3).^2; + % add noise + Ym2(Ymsk) = Ym2(Ymsk) + Ygs(Ymsk); + clear Ygs Ymsk; + %else % inactive because it is only an developer option + % stime2 = cat_io_cmd(' No MP2Rage - no CSF noise restoration.','g8','',job.verb-1,stime2); + end + end + + + + + %% additional skull-stripping + if job.skullstripping == 2 || ( job.skullstripping == 3 && res.isMP2R) + stime2 = cat_io_cmd(' Optimized skull-stripping','g5','',job.verb-1,stime2); + + %% denoising based correction + % In MP2Rage, background/bone/head tissues are quite noisy and strongly + % corrected by the SANLM. Hence, denoised regions are often background + % and should be not part of the GM class + + % get noisy regions + Yngw = cat_vol_morph( smooth3( cat_stat_nansum(Yseg(:,:,:,1:2),4) ) > .99 ,'do',3,vx_vol); + Yngw = smooth3( Yngw ) < .5; + + % gradient to get the local noise before/after correction (Yog/Ymg) + if exist('Yo','var') + Ymm = Ym; + Yog = cat_vol_grad(Yo); + Ymg = cat_vol_grad(Ym); + else + Ymm = single(Ym) + 0; cat_sanlm(Ymm,1,3); + Yog = cat_vol_grad(Ym); + Ymg = cat_vol_grad(Ymm); + end + Ymm = max(-1,min(10,Ymm)); + Ybgx = cat_vol_morph( abs(Ym)<10*eps, 'd',1); + Yog(Ybgx) = mean(Yog(:)); Ymg(Ybgx) = mean(Yog(:)); + + % get correction area + Ynog = max( Ybgx , Yngw .* (Ymm/spm8.mn(2)) .* ((Yog ./ Ymg) .* abs(Yog-Ymg) ./ spm8.mn(2)) ); %clear Yog Ymg Ymm; + Ynog = Yseg(:,:,:,1) .* smooth3(Ynog); + % do correction + Yseg(:,:,:,4) = Yseg(:,:,:,4) + Ynog; + Yseg(:,:,:,1) = Yseg(:,:,:,1) - Ynog; + clear Yngw %Ynog + + + % cleanup + Ygw = smooth3( cat_stat_nansum(Yseg(:,:,:,1:2),4) ) > .9; + Ygw = single(cat_vol_morph(Ygw,'do',3,vx_vol)); + Ygw(cat_stat_nansum(Yseg(:,:,:,1:3),4)<.2) = nan; + [~,Yd] = cat_vol_downcut(Ygw,Ym/spm8.mn(3) .* (1-sum( Yseg(:,:,:,5:6), 4)),0.01); + Ygw2 = Ym/spm8.mn(2)<1.2 & smooth3(Yd<.5)>.5; + + + % edge detection to improve skull-stripping + %Yg = cat_vol_grad(Ym/spm8.mn(2)); + %Yd = cat_vol_div(Ym/spm8.mn(2)); + % optimize skull-stripping + Yb = smooth3( cat_stat_nansum( Yseg(:,:,:,1:3),4) ); + Yb = max(Yb,cat_vol_morph(Yb > .5 ,'ldo',1,vx_vol)); + Yb = max(Yb,cat_vol_morph(Yb > .5 ,'ldc',2,vx_vol)); + Yb = max(Yb,Ygw2); + Yb = smooth3( Yb )>.8; + + elseif job.skullstripping + % simple SPM skull-stripping as CSF+GM+WM + stime2 = cat_io_cmd(' SPM skull-stripping','g5','',job.skullstripping && job.verb>1,stime2); + Yb = smooth3( sum( Yseg(:,:,:,1:3),4) )>.5; + + else + Yb = true(size(Ym)); + + end + + if job.skullstripping == 1 || job.skullstripping == 2 + % full classical skull-stripping + Ym2 = Ym2 .* Yb; + elseif job.skullstripping == 3 && res.isMP2R + % background-stripping and skull modification + % we keep here some minimum amount of noise and also some skull values + Ym2 = max(eps,Ym2 .* smooth3( max( (.4*cat_vol_smooth3X(Yseg(:,:,:,4),2).^4), ... + max(0.06, smooth3( 1 - Ybg - Yseg(:,:,:,4)) ))) - Yseg(:,:,:,4)*.05 + ... + (Ybg*0.02 + 0.04 .* Ybg .* randn(size(Ybg),'single'))); + end + % restore defacing values + Ym2(Yo==0) = 0; + + + %% evaluation + % evaluate also this ... + % * compare the difference between Yp0 and Ym2 => RMSE + % * compare the histogram of the tissues => RMSE + % * run iterative optimization ... + if res.isT1 + Yp0 = Yseg(:,:,:,1)*2 + Yseg(:,:,:,2)*3 + Yseg(:,:,:,3); + else + Yp0 = Yseg(:,:,:,1)*2 + Yseg(:,:,:,2)*1 + Yseg(:,:,:,3)*3; + end + % intensity-based measures + % - the correction should optimize the coefficient of joint variation (CJV) + fcjvx = @(x,y) ( cat_stat_nanstd(x(round(y(:))==1)) + cat_stat_nanstd(x(round(y(:))==2)) + cat_stat_nanstd(x(round(y(:))==3)) ) ./ ... + (cat_stat_nanmean(x(round(y(:))==1)) + cat_stat_nanmean(x(round(y(:))==2)) + cat_stat_nanmean(x(round(y(:))==3))); + fcjv = @(x,y) ( cat_stat_nanstd(x(round(y(:))==2)) + cat_stat_nanstd(x(round(y(:))==3)) ) ./ ... + (cat_stat_nanmean(x(round(y(:))==2)) + cat_stat_nanmean(x(round(y(:))==3))); + res.CJVorg = fcjv(Yo,Yp0); + res.CJVcor = fcjv(Ym2,Yp0); + res.CJVCGWorg = fcjvx(Yo,Yp0); + res.CJVCGWcor = fcjvx(Ym2,Yp0); + % Peak width similarity + res.sdCGWorg = [ cat_stat_nanstd( Yo(round(Yp0(:)*3)==3)) cat_stat_nanstd( Yo(round(Yp0(:))==2)) cat_stat_nanstd( Yo(round(Yp0(:))==3))] / spm8.mn(2); + res.sdCGWcor = [ cat_stat_nanstd( Ym2(round(Yp0(:)*3)==3)) cat_stat_nanstd( Ym2(round(Yp0(:))==2)) cat_stat_nanstd( Ym2(round(Yp0(:))==3))]; + res.sdCGorg = std(res.sdCGWorg(2:3)); + res.sdCGcor = std(res.sdCGWcor(2:3)); + % gradient test + Ygo = cat_vol_grad(Yo) ./ max(eps,Yo); + Ygm = cat_vol_grad(Ymbc) ./ max(eps,Ymbc); + Ygw = max(0,1 - Ygo - Ygm); + res.gradbias_tot = cat_stat_nanmean( (Ygm(:) - Ygo(:)) .* Ygw(:)); + res.gradbias_imp = cat_stat_nanmean( max(0,Ygm(:) - Ygo(:) ) .* Ygw(:) ); + res.gradbias_wor = cat_stat_nanmean( max(0,Ygo(:) - Ygm(:) ) .* Ygw(:) ); + clear Ygo ym Ygw; + + % volumetric measures + % - the resuling map should fit better to the existing segmentation + res.vol_TIV = cat_stat_nansum( Yp0(:)>.5) .* prod(vx_vol) / 1000; + res.vol_abs_CGW = [ cat_stat_nansum(round(Yp0(:))==1) cat_stat_nansum(round(Yp0(:))==2) cat_stat_nansum(round(Yp0(:))==3) ] .* prod(vx_vol) / 1000; + res.vol_rel_CGW = res.vol_abs_CGW ./ res.vol_TIV; + res.vol_abs_CGWorg = [ + cat_stat_nansum(Yb(:) & Yo(:)spm8.mn(1) & Yo(:)spm8.mn(2) ) ] .* prod(vx_vol) / 1000; + res.vol_rel_CGWorg = res.vol_abs_CGWorg ./ res.vol_TIV; + res.vol_abs_CGWcor = [ cat_stat_nansum(round(Yb(:).*Ym2(:)*3)==1) cat_stat_nansum(round(Yb(:).*Ym2(:)*3)==2) cat_stat_nansum(round(Yb(:).*Ym2(:)*3)==3) ] .* prod(vx_vol) / 1000; + res.vol_rel_CGWcor = res.vol_abs_CGWcor ./ res.vol_TIV; + res.vol_fitorg = mean( abs(res.vol_rel_CGWorg - res.vol_rel_CGW ) ); + res.vol_fitcor = mean( abs(res.vol_rel_CGWcor - res.vol_rel_CGW ) ); + res.totalorg = mean([ res.CJVorg res.sdCGorg res.vol_fitorg ]); + res.totalcor = mean([ res.CJVcor res.sdCGcor res.vol_fitcor ]); + clear Yp0; + + + %% write output + stime2 = cat_io_cmd(' Write output','g5','',job.verb-1,stime2); + resdir = fullfile(spm_fileparts(job.files{si}),job.resdir); + if ~exist(resdir,'dir'), mkdir(resdir); end + Pcm = spm_file(job.files{si},'path',resdir,'prefix',job.prefix,'ext','.nii'); + Vm2 = Vm; Vm2.fname = Pcm; + Vm2.descrip = sprintf('%s >> CAT-MP2Rage %s', Vm.descrip,parastr); %#################### + if ~res.isMP2R && res.isT1 + spm_write_vol(Vm2,max(-.5,min(2,Ym2))); + else + spm_write_vol(Vm2,Ym2); + end + +% write bias-field / correction map? + % + + %% run SPM postbiascorrection + if 0 %~res.isMP2R && job.biascorrection > 1 && ~job.quicktest + stime2 = cat_io_cmd(' Post correction','g5','',job.verb-1,stime2); + matlabbatch{1}.spm.spatial.preproc.channel.vols = {Pcm}; + for ti = 1:6 + matlabbatch{1}.spm.spatial.preproc.tissue(ti).native = [0 0]; + end + evalc('spm_jobman(''run'',matlabbatch)'); + movefile( spm_file(Pcm,'prefix','m'), spm_file(Pcm,'prefix','') ); + end + + % save XML/mat + if job.report + jobxml = job; jobxml.files = jobxml.files(si); + jobxml.result = {Pcm}; + jobxml.res = res; + if exist('scstr','var') + jobxml.scstr = scstr; + end + cat_io_xml(spm_file(Pcm,'prefix','catmp2r_','ext','.xml'),jobxml); + end + + out.files{si} = Pcm; + if nargout>1 + outs(si) = res; %#ok + end + + + + % report ? >> subfunction + % - input parameter + % - estimated parameters + % - original image + segmentation + new image + change image ??? + % - histogram tissues? + if job.report + res.time = etime(clock,stime); + report_figure(Vo,Vm2, Yo,Ym2,Yseg, job,spm8,res); + end + + if res.totalorg > res.totalcor, ccol = [0 0.5 0]; else, ccol = [0.5 0 0]; end + imgstr = {'MP1R','MP2R'}; + imgseq = {'PDw','T1w','T2w'}; + imgfat = {'fs0','fs1','fsu'}; + if job.verb > 1 + fprintf('%5.0fs\n Average change rating: ',etime(clock,stime2)); + cat_io_cprintf( ccol , sprintf('%5.2g - %0.2f > %0.2f\n', res.gradbias_tot*100, res.totalorg, res.totalcor) ); + cat_io_cmd(' ','g5','',job.verb-1); + fprintf('%5.0fs\n',etime(clock,stime)); + elseif job.verb == 1 + fprintf('%s-%s-%s: ',imgstr{res.isMP2R+1},imgseq{res.isT1+1},imgfat{res.fatsup+1}); + cat_io_cprintf( ccol , sprintf('%5.2g - %0.2f > %0.2f', res.gradbias_tot*100, res.totalorg, res.totalcor) ); + fprintf('%5.0fs\n',etime(clock,stime)); + end + + if job.spm_cleanupfiles + [pp,ff,ee] = spm_fileparts(job.files{si}); mfile = fullfile(pp,[ff,ee]); + for ci = 1:5 + delete( spm_file(mfile, 'prefix', sprintf('c%d',ci)) ); + end + if job.biascorrection + delete( spm_file(mfile, 'prefix', 'm' ) ); + end + delete( spm_file(mfile, 'suffix', '_seg8' , 'ext', '.mat' ) ); + end + + spm_progress_bar('Set',si); + end +end +function report_figure(V,V2, Ym,Ym2,Yc, opt,spm8,res) + + + % in case of updates + spm_orthviews('Reset') + %clear -global st; global st %#ok + + % fontsettings + fontsize = 10; fontcolor = [0 0 0]; fontname = 'monospace'; + + % setup SPM figure + fg = spm_figure('FindWin','Graphics'); + set(0,'CurrentFigure',fg) + spm_figure('Clear',fg); + if isempty(fg) + fg = spm_figure('Create','Graphics','visible','on'); + end + colormap gray; + + + % main text report box with header (filename) + ax = axes('Position',[0.01 0.75 0.98 0.245],'Visible','off','Parent',fg); + text(0,0.99, ['CAT MP2Rage Precessing: ' ... + strrep( strrep( spm_str_manip(V.fname,'k80d'),'\','\\'), '_','\_') ' '],... + 'FontSize',fontsize+1,'FontWeight','Bold','Interpreter','tex','Parent',ax); + + + % write parameters + str{1} = []; + imgseq = {'T2w','T1w','PDw'}; + imgstr = {'MPR','MP2R'}; + imgfat = {'','fatsup','unkown'}; + % fatshift + biasstr = {'no','yes-basic','yes-extend'}; + ssstr = {'no','SPM','optimized','background-removal'}; % 0-3 + % logstr = {'no','exp','log2','log','log10','auto'}; + csfnoise = {'no','yes'}; + % parameters + str{1}(end+1).name = 'Image type:'; + str{1}(end).value = sprintf('%s %s ', ... + imgseq{res.isT1+1}, imgstr{res.isMP2R+1}, imgfat{res.fatsup+1}); + if cat_get_defaults('extopts.expertgui') + str{1}(end+1).name = 'Bias-correction / skull-stripping:'; + str{1}(end).value = sprintf('%s / %s ', ... + biasstr{opt.biascorrection+1}, ssstr{opt.skullstripping+1}); + else + str{1}(end+1).name = 'Bias-correction / int-harmonization /skull-stripping:'; + str{1}(end).value = sprintf('%s / %s / %s ', ... + biasstr{opt.biascorrection+1}, csfnoise{opt.intscale+1}, ssstr{opt.skullstripping+1}); + end + if cat_get_defaults('extopts.expertgui') + str{1}(end+1).name = 'log-norm / contrast-norm / CSF noise:'; + str{1}(end).value = sprintf('%d / %0.2f / %s ', ... + opt.logscale, opt.intnorm, csfnoise{opt.restoreLCSFnoise+1}); + end + % SPM intensity thresholds ? + % SPM volumes + str{1}(end+1).name = 'Absolute brain volumes (CSF + GM + WM = TIV, in mm): '; + str{1}(end).value = sprintf('%0.0f + %0.0f + %0.0f = %0.0f', res.vol_abs_CGW,res.vol_TIV); + str{1}(end+1).name = 'Relative brain volumes (CSF + GM + WM, in %): '; + str{1}(end).value = sprintf('%0.3f + %0.3f + %0.3f', res.vol_rel_CGW); + % paras + str{1}(end+1).name = 'Intensity-volume fit / average-fit: '; + if res.vol_fitorg > res.vol_fitcor, ccor = '\color[rgb]{0 0.5 0}'; else, ccor = '\color[rgb]{0.5 0 0}'; end + str{1}(end).value = sprintf('%s%0.3f > %0.3f /', ccor, res.vol_fitorg,res.vol_fitcor ); + if res.totalorg > res.totalcor, ccor = '\color[rgb]{0 0.5 0}'; else, ccor = '\color[rgb]{0.5 0 0}'; end + str{1}(end).value = [str{1}(end).value sprintf('%s%0.3f > %0.3f ', ccor, res.totalorg,res.totalcor )]; + % + str{1}(end+1).name = 'Grad-change / CJV(org) > CJV(cor) / CJVCGW(org) > CJVCGW(cor): '; + if res.gradbias_tot < 0, ccor0 = '\color[rgb]{0 0.5 0}'; else, ccor0 = '\color[rgb]{0.5 0 0}'; end + if res.CJVorg > res.CJVcor, ccor1 = '\color[rgb]{0 0.5 0}'; else, ccor1 = '\color[rgb]{0.5 0 0}'; end + if res.CJVCGWorg > res.CJVCGWcor, ccor2 = '\color[rgb]{0 0.5 0}'; else, ccor2 = '\color[rgb]{0.5 0 0}'; end + str{1}(end).value = sprintf('%s%8g / %s%0.3f > %0.3f / %s%0.3f > %0.3f', ... + ccor0, res.gradbias_tot, ccor1, res.CJVorg,res.CJVcor, ccor2, res.CJVCGWorg,res.CJVCGWcor); + str{1}(end+1).name = 'Procesing time: '; + str{1}(end).value = sprintf('%0.0fs',res.time); +% +++ add simple/complex color rating (simple=just better, compex=marks) + + + htext = zeros(5,2,2); + for i=1:size(str{1},2) % main parameter + htext(1,i,1) = text(0.01,0.98-(0.055*i), str{1}(i).name ,'FontName',fontname,'FontSize',fontsize,'color',fontcolor,'Interpreter','none','Parent',ax); + htext(1,i,2) = text(0.51,0.98-(0.055*i), str{1}(i).value ,'FontName',fontname,'FontSize',fontsize,'color',fontcolor,'Interpreter','tex','Parent',ax); + end + + + + %% == images == + spm_orthviews('Reset') + pos = {[0.008 0.375 0.486 0.35]; [0.506 0.375 0.486 0.35]; [0.008 0.01 0.486 0.35];}; + % T1 + SPM segmentation + %colormap( [[0 0.02 0.07]; repmat([0.05 0.15 .35],round(59/(crange+2)),1); repmat([ 0 .3 .6],round(59/(crange+2)),1); jet(59 - 2*round(59/(crange+2)))]); + if res.isT1 + V0 = V; V0.dat(:,:,:) = single(Ym/spm8.mn(2)); V0.dt(1) = 16; + else + V0 = V; V0.dat(:,:,:) = single(Ym/max(spm8.mn(1:3))); V0.dt(1) = 16; + end + V0.pinfo = repmat([1;0],1,size(Ym,3)); + V0.mat = spm8.Affine * V0.mat; % Vo.mat; \seg8t.tpm(1).mat + hh0 = spm_orthviews('Image',spm_vol(fullfile(spm('dir'),'tpm','TPM.nii,1')),pos{1}); % avoid problems with high resolutions + spm_orthviews('window',hh0,[0 10000]); % just make it black + spm_orthviews('BB', [-85 -120 -90; 85 95 105]); % this has to be set in the low-resolution image + hh0 = spm_orthviews('Image',V0,pos{1}); % add correct image after the other settings! + spm_orthviews('Caption',hh0,sprintf('%s','original')); + spm_orthviews('window',hh0,[0 1.2]); +% #### overlay skull-stripping + + % print bone marrow + if res.isT1 + V1 = V; V1.dat(:,:,:) = Ym2; + else + V1 = V; V1.dat(:,:,:) = single(Ym2/max(max(max(Ym2(sum(Yc(:,:,:,1:3),4)>.5))))); V1.dt(1) = 16; + end + V1.pinfo = repmat([1;0],1,size(Ym2,3)); + V1.mat = spm8.Affine * V1.mat; + V1.dt(1) = 16; + hh1 = spm_orthviews('Image',V1,pos{2}); + spm_orthviews('Interp',1); + spm_orthviews('window',hh1,[0 1.1]); + spm_orthviews('Caption',hh1,'Optimized'); + + % print bone marrow + V1 = V; V1.dat(:,:,:) = Yc(:,:,:,1)*2 + Yc(:,:,:,2)*3 + Yc(:,:,:,3) + Yc(:,:,:,4)*0.5 + Yc(:,:,:,5)*3.3; + V1.pinfo = repmat([1;0],1,size(Ym2,3)); + V1.mat = spm8.Affine * V1.mat; + V1.dt(1) = 16; + hh1 = spm_orthviews('Image',V1,pos{3}); + spm_orthviews('window',hh1,[0 3.3]); + spm_orthviews('Caption',hh1,'SPM Label Map'); + spm_orthviews('Reposition',[-25 0 0]); + spm_orthviews('redraw'); + +% ### thresholded optimized ? + + + % save image + try % does not work in headless mode without java + figfs10 = [ findobj(fg,'FontSize',fontsize+1); findobj(fg,'FontSize',fontsize); findobj(fg,'FontSize',fontsize-1); ... + findobj(fg,'FontSize',fontsize*0.85); findobj(fg,'FontSize',fontsize*.6); findobj(fg,'FontSize',fontsize*.4); ]; + for fsi = 1:numel(figfs10), try figfs10(fsi).FontSize = figfs10(fsi).FontSize * .75; end; end %#ok + saveas(fg,spm_file(V2.fname,'prefix','report','ext','.png')); + for fsi = 1:numel(figfs10), try figfs10(fsi).FontSize = figfs10(fsi).FontSize / .75; end; end %#ok + catch + cat_io_cprintf('err','Error while saving report figure using ""saveas"".\n'); + end + +end +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_main_gintnorm1639.m",".m","33962","683","function [Ym,Yb,T3th3,Tth,inv_weighting,noise] = cat_main_gintnorm1639(Ysrc,Ycls,Yb,vx_vol,res,Yy,extopts) +% This is an exclusive subfunction of cat_main. +% ______________________________________________________________________ +% Global intensity normalization based on tissue thresholds estimated as +% median intensity in the SPM tissue maps refined by edge (gradient) +% information. Class propability should be higher than 50% (=128) to +% avoid problems by the PVE or bias regions like basal ganglia or the CSF. +% Especialy correct CSF estimation can be problematic, because it is +% strongly influenced by the PVE and other tissues like blood vessels +% and meninges. This structures with GM like intensity will cause a to +% high global CSF value. +% For CSF, and WM we can use low gradient thesholds to avoid the PVE, but +% for GM this can lead to strong problems because to low thresholds will +% only give large GM areas like the basal ganlia, that have often a to high +% intensity. +% +% [Ym,Yb,T3th3,Tth,inv_weighting,noise] = +% cat_main_gintnorm(Ysrc,Ycls,Yb,vx_vol,res) +% +% Ym .. intensity normalized image +% Yb .. brain mask +% T3th3 .. [CSF,GM,WM] peak intensity +% Tth .. structure for inverse function cat_main_gintnormi +% inv_weighting .. true in T2/PD images +% noise .. first guess of the noise level +% cat_waring .. structure with warings +% +% Ysrc .. the original (noise/bias corrected) image +% Ycls .. SPM classification [GM,WM,CSF,HD1,HD2,BG] +% (6 cells with uint8 classes images) +% Yb .. brain mask +% vx_vol .. voxel resolution of the images +% res .. SPM segmentation structure +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + dbs = dbstatus; debug = 0; for dbsi=1:numel(dbs), if strcmp(dbs(dbsi).name,mfilename); debug = 1; break; end; end + + nwarnings = cat_io_addwarning; + + if isstruct(Ycls) + + %% final peaks and intensity scaling + % ----------------------------------------------------------------- + T3th = Ycls.T3th; + T3thx = Ycls.T3thx; + + % intensity scaling + Ym = Ysrc; + + if all(T3th==T3thx), return; end + + isc = 1; + %T3th = interp1(T3th,1:1/isc:numel(T3th)*isc,'spline'); %pchip'); + %T3thx = interp1(T3thx,1:1/isc:numel(T3th)*isc,'spline'); %pchip'); + + for i=2:numel(T3th) + M = Ysrc>T3th(i-1) & Ysrc<=T3th(i); + Ym(M(:)) = T3thx(i-1) + (Ysrc(M(:)) - T3th(i-1))/diff(T3th(i-1:i))*diff(T3thx(i-1:i)); + end + M = Ysrc>=T3th(end); + Ym(M(:)) = numel(T3th)/isc/6 + (Ysrc(M(:)) - T3th(i))/diff(T3th(end-1:end))*diff(T3thx(i-1:i)); + Ym = Ym / 3; + + return + end + + clsint = @(x) round( sum(res.mn(res.lkp==x) .* res.mg(res.lkp==x)') * 10^5)/10^5; + clsints = @(x,y) [round( res.mn(res.lkp==x) * 10^5)/10^5; res.mg(res.lkp==x-((y==0)*8))']; + + inv_weighting = 0; + + vxv = 1/cat_stat_nanmean(vx_vol); + res.mn = round(res.mn*10^5)/10^5; + + + %% initial thresholds and intensity scaling + T3th3 = [clsint(3) clsint(1) clsint(2)]; + BGth = min(mean(Ysrc(Ycls{end}(:)>192)),clsint(end)); + + %% ------------------------------------------------------------------- + % intensity checks and noise contrast ratio (contrast part 1) + % ------------------------------------------------------------------- + % relation between the GM/WM and CSF/GM and CSF/WM contrast has to be + % greater that 3 times of the maximum contrast (max-min). + clear Yn + checkcontrast = @(T3th,minContrast) ... + abs(diff(T3th([1,3]))) < (max(T3th(:))-min(T3th(:)))*minContrast || ... + abs(diff(T3th(1:2))) < (max(T3th(:))-min(T3th(:)))*minContrast || ... + abs(diff(T3th(2:3))) < (max(T3th(:))-min(T3th(:)))*minContrast; + + if checkcontrast(T3th3,1/9) && exist('cat_warnings','var') % contrast relation + cat_io_addwarning([mfilename ':LowContrast'],... + sprintf(['The contrast between different tissues is relative low! \\n' ... + ' (BG=%0.2f, CSF=%0.2f, GM=%0.2f, WM=%0.2f)'],BGth,T3th3),2,[1 0]); + end + + if T3th3(1)>T3th3(3) && T3th3(2)>T3th3(3) && T3th3(1)>T3th3(2) % invers (T2 / PD) + cat_io_addwarning([mfilename ':InverseContrast'],... + sprintf(['Inverse tissue contrast! \\n' ... + '(BG=%0.2f, CSF=%0.2f, GM=%0.2f, WM=%0.2f)'],BGth,T3th3(1:3)),2,[1 0]); + T3th3(1) = max( max(clsints(3,0)) , mean(Ysrc(Ycls{3}(:)>240))); + + % first initial scaling for gradients and divergence + if abs(diff( abs(diff( T3th3/diff(T3th3([3,1])) )) ))>0.4 % %T2 + T3th = [min(Ysrc(~isnan(Ysrc(:)) & ~isinf(Ysrc(:)))) ... + min( T3th3(3)*0.8+0.2*min(Ysrc(~isnan(Ysrc(:)) & ~isinf(Ysrc(:)))) , BGth ) ... + T3th3 ... + ([T3th3(3)*0.5+0.5*min(Ysrc(~isnan(Ysrc(:)) & ~isinf(Ysrc(:)))) ... WM + cat_stat_nanmean([T3th3(3), BGth ]) ... WM + T3th3(2)*0.5 + 0.5*T3th3(1)... % CSF/GM + max(T3th3) + abs(diff(T3th3([1,3])/2)) ... % CSF / BG + ]) ]; + T3thx = [0,0.05, 1,2,3.2, 1.1, 1.0, 1.75, 0.8]; + + [T3th,si] = sort(T3th); + T3thx = T3thx(si); + else + T3th = [min(Ysrc(~isnan(Ysrc(:)) & ~isinf(Ysrc(:)))) ... + min( T3th3(3)*0.2+0.8*min(Ysrc(~isnan(Ysrc(:)) & ~isinf(Ysrc(:)))) , BGth ) ... + T3th3 ... + ([T3th3(3)*0.5+0.5*min(Ysrc(~isnan(Ysrc(:)) & ~isinf(Ysrc(:)))) ... WM + cat_stat_nanmean([T3th3(3), BGth ]) ... WM + T3th3(2)*0.5 + 0.5*T3th3(1)... % CSF/GM + max(T3th3) + abs(diff(T3th3([1,3])/2)) ... % CSF / BG + max(T3th3(end) + abs(diff(T3th3([1,numel(T3th3)])/2)) , ... + max(Ysrc(~isnan(Ysrc(:)) & ~isinf(Ysrc(:)))) ) ]) ]; + T3thx = [0,0.05, 1,2,3, 2.0, 1.0, 1.75, 0.8, 0.2]; + + [T3th,si] = sort(T3th); + T3thx = T3thx(si); + end + + Ym = Ysrc+0; + for i=2:numel(T3th) + M = Ysrc>T3th(i-1) & Ysrc<=T3th(i); + Ym(M(:)) = T3thx(i-1) + (Ysrc(M(:)) - T3th(i-1))/diff(T3th(i-1:i))*diff(T3thx(i-1:i)); + end + M = Ysrc>=T3th(end); + Ym(M(:)) = numel(T3th)/6 + (Ysrc(M(:)) - T3th(i))/diff(T3th(end-1:end))*diff(T3thx(i-1:i)); + Ym = Ym / 3; + %% + Yg = cat_vol_grad(Ym,vx_vol); + Ydiv = cat_vol_div(Ym,vx_vol); + + %% tissues for bias correction + Ycm = (Ym + Yg - Ydiv + single(Ycls{2})/255)<2/3 | ... + (Ycls{3} + Ycls{6} + Ycls{4} + Ycls{5})>128; + Ycd = cat_vbdist(single(Ycm)); + Ybd = cat_vbdist(cat_vol_morph(single((Ycls{6} + Ycls{4} + Ycls{5})>128),'lo',1)); + + Ywm = (single(Ycls{2})/255 - Yg - Ydiv - max(0,3-Ycd-Ybd/40)/2)>0.7 | ... + (Ym-Yg-Ydiv-max(0,3-Ycd-Ybd/40)/2)>0.8 & Ycls{1}+Ycls{2}>240; + Ywm(smooth3(Ywm)<0.3)=0; + Ygm = (single(Ycls{1})/255 - abs(Ydiv)*8)>0.5 | ... + (single(Ycls{2}+Ycls{1})>240 & max(0,2-Ycd - max(0,Ybd/2-10))>0 & abs(Ydiv)<0.1); + + %% bias correction + [Yi,resT2] = cat_vol_resize(Ysrc.*Ywm,'reduceV',vx_vol,1,16,'min'); + Yig = cat_vol_resize(Ysrc.*Ygm./median(Ysrc(Ygm(:)))*median(Ysrc(Ywm(:))),'reduceV',vx_vol,1,16,'meanm'); + Yi = max(Yi,Yig); Yi(Yig>0) = min(Yig(Yig>0),Yi(Yig>0)); + Yi = cat_vol_localstat(Yi,Yi>0,1,2); + for xi=1:2, Yi = cat_vol_localstat(Yi,Yi>0,2,1); end + Yi = cat_vol_approx(Yi,'nh',resT2.vx_volr,2); Yi = cat_vol_smooth3X(Yi,2); + Yi = cat_vol_resize(Yi,'dereduceV',resT2)./median(Yi(Ycls{2}>192)); + Ysrcr = round(Ysrc ./ Yi * 10^5)/10^5; % * T3th3(3) * 1.05 + if debug==0, clear Yg Ydiv Yn Yi; end + + %% final thresholds + if 0 % old + T3th = [min(Ysrc(~isnan(Ysrc(:)) & ~isinf(Ysrc(:)))) ... + min( T3th3(3)*0.2+0.8*min(Ysrc(~isnan(Ysrc(:)) & ~isinf(Ysrc(:)))) , BGth ) ... + T3th3 ... + ([T3th3(3)*0.3+0.7*min(Ysrc(~isnan(Ysrc(:)) & ~isinf(Ysrc(:)))) ... + cat_stat_nanmean([T3th3(3),BGth]) ... + clsint(2)*0.8 ... + max(T3th3) + abs(diff(T3th3([1,numel(T3th3)])/2)) ... + max(T3th3(end) + abs(diff(T3th3([1,numel(T3th3)])/2)) , ... + max(Ysrc(~isnan(Ysrc(:)) & ~isinf(Ysrc(:)))))]) ]; + T3thx = [0,0.05, 1,2,3, 2.9, 2.5, 2.0, 1.0, 0.7]; + end + if abs(diff( abs(diff( T3th3/diff(T3th3([3,1])) )) ))>0.4 % %T2 + T3th = [min(Ysrc(~isnan(Ysrc(:)) & ~isinf(Ysrc(:)))) ... + min( T3th3(3)*0.8+0.2*min(Ysrc(~isnan(Ysrc(:)) & ~isinf(Ysrc(:)))) , BGth ) ... + T3th3 ... + ([T3th3(3)*0.5+0.5*min(Ysrc(~isnan(Ysrc(:)) & ~isinf(Ysrc(:)))) ... WM + cat_stat_nanmean([T3th3(3), BGth ]) ... WM + T3th3(2)*0.5 + 0.5*T3th3(1)... % CSF/GM + max(T3th3) + abs(diff(T3th3([1,3])/2)) ... % CSF / BG + ]) ]; + T3thx = [0,0.05, 1,2,3.2, 1.1, 1.0, 1.75, 0.8]; + else + T3th = [min(Ysrc(~isnan(Ysrc(:)) & ~isinf(Ysrc(:)))) ... + min( T3th3(3)*0.2+0.8*min(Ysrc(~isnan(Ysrc(:)) & ~isinf(Ysrc(:)))) , BGth ) ... + T3th3 ... + ([T3th3(3)*0.5+0.5*min(Ysrc(~isnan(Ysrc(:)) & ~isinf(Ysrc(:)))) ... WM + cat_stat_nanmean([T3th3(3), BGth ]) ... WM + T3th3(2)*0.5 + 0.5*T3th3(1)... % CSF/GM + max(T3th3) + abs(diff(T3th3([1,3])/2)) ... % CSF / BG + max(T3th3(end) + abs(diff(T3th3([1,numel(T3th3)])/2)) , ... + max(Ysrc(~isnan(Ysrc(:)) & ~isinf(Ysrc(:)))) ) ]) ]; + T3thx = [0,0.05, 1,2,3, 2.0, 1.0, 1.75, 0.8, 0.2]; + end + + + [T3th,si] = sort(T3th); + T3thx = T3thx(si); + + + inv_weighting = 1; + + elseif T3th3(1)240) ) , median(Ysrc(Ycls{3}(:)>16)) ] ); % RD202211: added median value of nearly whole CSF + else + T3th3(1) = min( [ min(clsints(3,0)) , mean(Ysrc(Ycls{3}(:)>240) ) ] ); + end + BGcon = max([BGmin*1.1,T3th3(1) - cat_stat_nanmean(diff(T3th3)),median(Ysrc(Ycls{end}(:)>128))]); + %T3th3 = [max( min(res.mn(res.lkp==3 & res.mg'>0.3/sum(res.lkp==3)))*.05 + .95*max(res.mn(res.lkp==2 & res.mg'>0.3/sum(res.lkp==2))) , ... + % min(res.mn(res.lkp==3 & res.mg'>0.3/sum(res.lkp==3)))) ... + % max(res.mn(res.lkp==1 & res.mg'>0.1)) ... + % max(res.mn(res.lkp==2 & res.mg'>0.1))]; + T3th = [BGmin ... minimum + min(BGcon,BGmin*0.1+0.9*T3th3(1)) ... cat_stat_nanmean background (MT contrast with strong background noise) + T3th3 ... csf gm wm + max(T3th3) + abs(diff(T3th3([1,numel(T3th3)])/2)) ... higher + max(T3th3(end) + abs(diff(T3th3([1,numel(T3th3)])/2)) , ... maximum + max(Ysrc(~isnan(Ysrc(:)) & ~isinf(Ysrc(:))))) ]; + T3thx = [0,0.05,1:5]; + Ysrcr = round(Ysrc*10^5)/10^5; + + + + elseif T3th3(1)>T3th3(3) && T3th3(2)T3th3(2) + % This is a very special case of T2 weighting (of neonates) with + % BG < GM < WM < CSF that need special correction for the sulcal + % CSF that mostly have WM like intensity due to the PVE. Hence, + % there are a lot of miss-labeled voxel that need further correction + % that follow in the second part of this file. + % + % Because, I observed a lot of problems by the SPM bias correction, I + % increased the biasfwhm and the biasreg. Although, this did not work, + % the indroduce bias was smoother and could be corrected here very well. + + cat_io_addwarning([mfilename ':InverseContrast'],... + sprintf(['Inverse tissue contrast that requires strong modifications! \\\\n' ... + 'In case of ""BG0)); + Ysrco = Ysrc+0; + + T3th2 = [clsint(3) ... + min( [clsint(1) , ... + cat_stat_nanmean(Ysrco( Ysrco(:)>(BGth*0.8+0.2*Sth) & Ysrco(:)1.9/3 & Yp0(:)<2.2/3 & Ydiv(:)<0.05 & Yg(:)>0.05 & Yg(:)<0.15)) ]) ... + max( [clsint(2) median( Ysrco(Ycls{2}(:)>192) ) ]) ... + ]; + + + %% + if ~exist('Yy','var') && isfield(res,'Twarp'), Yy = res.Twarp; end + LAB = extopts.LAB; + if ~exist('Yy','var') + PA = extopts.cat12atlas; + VA = spm_vol(PA{1}); + YA = cat_vol_ctype(spm_sample_vol(VA,double(Yy(:,:,:,1)),double(Yy(:,:,:,2)),double(Yy(:,:,:,3)),0)); + YA = reshape(YA,size(Ym)); + YA(mod(YA,2)==0 & YA>0)=YA(mod(YA,2)==0 & YA>0)-1; + else + YA = ones(size(Yg)); + end + if ~debug, clear Yy; end + + + %% bias correction + Ym = (Ysrco - BGth) / ( Sth - BGth); + Ycbg = Yg<0.1 & (Ym<1 | Ycls{1}>Ycls{2} & Ydiv>=0) & YA==LAB.CB; + Ycbw = Yg<0.1 & Ycls{2}>Ycls{1} & Ydiv<0 & YA==LAB.CB & ~Ycbg; + Ybg = cat_vol_morph(cat_vol_morph(cat_vol_smooth3X(Ym<1.02 & Yp0>2/3 & Yp0<1 & Yg0.8 & ... + Yhd>0.5,'o',1),'d',4) & Yp0>1.5/3 & Ym<1.02 & Yg1.9/3 | (Yp0>0 & Ym>0.7 & Ym<1.4)) & cat_vol_morph(cat_vol_morph(smooth3(Ycls{1}>240 & Yg<0.1 & abs(Ydiv)<0.01)<0.3,'c',1),'e',3) & ... + Ym<(clsint(3)/clsint(2)*0.8 + 0.2) & Ym>(clsint(1)/clsint(2)*0.6) & Yg<0.4 & ~Ybg & ~Ycbg; + Ygw = cat_vol_morph(Ygw,'l',[inf 0.05])>0; + Ygw = Ygw | (Yg<0.1 & Ycls{2}>Ycls{1} & Ycls{2}>Ycls{3} & (Yp0>1.5/3 | Ym>0.95 & Ym<1.5) & ~Ybg & ~Ycbg) | YA==LAB.BS | Ycbw; + Ygw = cat_vol_morph(Ygw,'l',[inf 0.1])>0; + Ygw = Ym .* Ygw; + Ygw = cat_vol_median3(Ygw,Yp0>0); + Ygm = Ym .* (cat_vol_morph(smooth3(~Ygw & Yg<0.10 & abs(Ydiv)<0.05 & Ycls{1}>Ycls{2} & Ycls{1}>Ycls{3} & Yhd<0.4)>0.5,'o',2) | Ycbg )/ ... + (T3th2(2) / T3th2(3)); + %Ycm = Ym .* cat_vol_morph(smooth3(~Ygw & ~Ygm & Yg<0.1 & (Ycls{3}>Ycls{2} & Ycls{3}>Ycls{1})>0.5) | (Ym>1.2 & Yb)); + %Ycm = cat_vol_localstat(Ycm,Ycm>0,1,3); + %Ycm = Ycm / mean(Ycm(Ycm(:)>0)); % * (T3th2(1) / T3th2(3)); + Ygw = Ygw + (Ygm .* (Ygw==0)) + ((Ym .* Ybg .* (Ygw==0)) / (cat_stat_nanmean(T3th2(2)) / T3th2(3)) ); % + (Ycm .* (Ygm==0)); + Ygw2 = Ym .* (Yg2.9/3 | Ym>0.9) & Ym<1.5 & Ygw>0) | Ycbw | ... + (abs(Ydiv)<0.1 & Ycls{2}/2>Ycls{1} & Ycls{2}/2>Ycls{3}) ) & ~Ybg & ~Ycbg); + %% field approximation + [Ywi,Ywi2,resT2] = cat_vol_resize({Ygw,Ygw2},'reduceV',vx_vol,max(vx_vol)*2,16,'max'); + for i=1:1, Ywi2 = cat_vol_localstat(Ywi2,Ywi2>0,1,3); end + for i=1:1, Ywi = cat_vol_localstat(Ywi,Ywi>0,2,3); end % only one iteration! + for i=1:1, Ywi = cat_vol_localstat(Ywi,Ywi>0,1,1); end + Ywi = cat_vol_approx(Ywi,'nn',resT2.vx_volr,2); + Ywi = cat_vol_smooth3X(Ywi,1); Ywi(Ywi2>0)=Ywi2(Ywi2>0); + Ywi = cat_vol_smooth3X(Ywi,1); % highres data have may stronger inhomogeneities + Ywi = cat_vol_resize(Ywi,'dereduceV',resT2); + Ywi = Ywi / cat_stat_nanmean(Ywi(Ygw2>0)); + Ysrc = Ysrco ./ Ywi * ( cat_stat_nanmean(Ysrco(Ygw2>0)/T3th2(3)) / cat_stat_nanmean(Ywi(Ygw2>0)) ); + + + + %% first initial scaling for gradients and divergence + %T3th3 = [cat_stat_nanmean( res.mn(res.lkp==3 & res.mg'>0.1)) ... + % min( [res.mn(res.lkp==1 & res.mg'>0.1) , ... + % cat_stat_nanmean(Ysrc( Ysrc(:)>(BGth*0.8+0.2*Sth) & Ysrc(:)1.9/3 & Yp0(:)<2.2/3 & Ydiv(:)<0.05 & Yg(:)>0.05 & Yg(:)<0.15)) ]) ... + % max( [sum(res.mn(res.lkp==2) .* res.mg(res.lkp==2)') median( Ysrc(Ycls{2}(:)>192) ) ]) ... + % ]; + clear T3th T3thx; + T3th = [ min(Ysrc(~isnan(Ysrc(:)) & ~isinf(Ysrc(:)))) ... + min( T3th3(2)*0.5+0.5*min(Ysrc(~isnan(Ysrc(:)) & ~isinf(Ysrc(:)))) , BGth ) ... + ... + min(Ysrc( Ysrc(:)>(BGth*0.8+0.2*Sth) & Ysrc(:)1.9/3 & Yp0(:)<2.2/3 & Ydiv(:)<0.05 & Yg(:)>0.05 & Yg(:)<0.15)) ... head + T3th3 ... + ... + (T3th3(3)*0.8 + 0.2*max(res.mn(res.lkp==3 & res.mn>max(res.mn(res.lkp==2)))) ) ... + (T3th3(3)*0.5 + 0.5*max(res.mn(res.lkp==3 & res.mn>max(res.mn(res.lkp==2)))) ) ... + (T3th3(3)*0.2 + 0.8*max(res.mn(res.lkp==3 & res.mn>max(res.mn(res.lkp==2)))) ) ... + ... + max(Ysrc(~isnan(Ysrc(:)) & ~isinf(Ysrc(:))))]; ... + + T3thx = [0,0.05,1.75, 1,2,3, 3.1,2.0,1.1, 1.0]; + + [T3th,si] = sort(T3th); + T3thx = T3thx(si); + + Ysrcr = round(Ysrc*10^5)/10^5; + + inv_weighting = 1; + + if debug + Ym = Ysrcr+0; + for i=2:numel(T3th) + M = Ysrc>T3th(i-1) & Ysrc<=T3th(i); + Ym(M(:)) = T3thx(i-1) + (Ysrc(M(:)) - T3th(i-1))/diff(T3th(i-1:i))*diff(T3thx(i-1:i)); + end + M = Ysrc>=T3th(end); + Ym(M(:)) = numel(T3th)/6 + (Ysrc(M(:)) - T3th(i))/diff(T3th(end-1:end))*diff(T3thx(i-1:i)); + Ym = Ym / 3; + ds('l2','',vx_vol,Ysrc/T3th3(3), round(Ym*3),Ysrc/T3th3(3),Ym,60) + end + + + else + error('cat_main:badTissueContrast',... + sprintf([... + 'Bad tissue contrast (BG=%0.2f, CSF=%0.2f, GM=%0.2f, WM=%0.2f): \\n' ... + ' This can be the result of (i) an improper SPM segmentation caused by \\n' ... + ' failed affine registration, (ii) improper image properties with low \\n' ... + ' contrast-to-noise ratio, or (iii) by preprocessing error. \\n' ... + ' Please check image orientation and quality. '], ... + BGth,T3th3(1),T3th3(2),T3th3(3))); %#ok + end + + + + + %% intensity scaling for gradient estimation + Tth.T3th = T3th; + Tth.T3thx = T3thx; + + Ym = Ysrcr+0; + for i=2:numel(T3th) + M = Ysrcr>T3th(i-1) & Ysrcr<=T3th(i); + Ym(M(:)) = T3thx(i-1) + (Ysrcr(M(:)) - T3th(i-1))/diff(T3th(i-1:i))*diff(T3thx(i-1:i)); + end + M = Ysrcr>=T3th(end); + Ym(M(:)) = numel(T3th)/6 + (Ysrcr(M(:)) - T3th(i))/diff(T3th(end-1:end))*diff(T3thx(i-1:i)); + Ym = Ym / 3; + + + + %% new initial segment threshold + if ~exist('Yg','var'), Yg = cat_vol_grad(Ym,vx_vol)./max(eps,Ym); end + T3th = [median(Ysrcr(Ycls{3}(:)>192 & Yg(:)<0.20 & Ym(:)<0.45)) ... + median(Ysrcr(Ycls{1}(:)>192 & Yg(:)<0.20)) ... + median(Ysrcr(Ycls{2}(:)>192 & Yg(:)<0.10))]; + Ynw = cat_vol_localstat(Ysrc,Ycls{3}>192,2,4); + Ync = cat_vol_localstat(Ysrc,Ycls{2}>192,2,4); + noise = round(min(cat_stat_nanmean(Ynw(Ynw(:)>0)),cat_stat_nanmean(Ync(Ync(:)>0))) / min(abs(diff(T3th(1:3)))) * 10^6)/10^6; + clear Ynw Ync; + + if debug==2 + [mrifolder, reportfolder] = cat_io_subfolders(res.image0(1).fname,struct('extopts',extopts)); + [pth,nam] = spm_fileparts(res.image0(1).fname); + tmpmat = fullfile(pth,reportfolder,sprintf('%s_%s%02d%s.mat',nam,'write',1,'gintnorm00')); + save(tmpmat,'Ysrc','Ycls','Yb','vx_vol','res','T3th','T3thx','Yg','Ym','noise'); + end + + + + + + + %% ------------------------------------------------------------------- + % check modality (contrast part 2) + % ------------------------------------------------------------------- + % It is possible to invert T2 and PD images based on the SPM class + % information, but actual there is no time to develope and proof this + % function in detail, due to the most other functions ... + % ------------------------------------------------------------------- + if T3th(1)128); + Ymp0diff = sqrt(cat_stat_nanmean(Ym(Ygw(:)) - Ymx(Ygw(:)))^2); + if Ymp0diff>0.10 && debug + cat_io_addwarning([mfilename ':badSPMsegment'],sprintf(... + ['SPM segmentation does not fit to the image (RMS(Ym,Yp0)=%0.2f).\\\\n'... + 'This can be an alignment problem (check origin), \\\\n' ... + 'untypical subjects (neonates, non-human),\\\\n'... + 'bad image contrast (C=%0.2f,G=%0.2f,W=%0.2f), \\\\n'... + 'low image quality (NCR~%0.2f), or something else ...'],Ymp0diff,T3th,noise),2,[1 0]); + end + clear Ymx; + end + + + %% skull-stripping warning + if numel(Ycls)>4 + skulltest = (median(Ysrc(Ycls{5}(:)>192 & Ysrc(:)>T3th(2))) < ... + median(Ysrc(Ycls{3}(:)>192 & Ysrc(:)>0))); + if exist('cat_warnings','var') && (isnan(skulltest) || skulltest) + + % Skull-Stripped images can of course lead to problems with to strong + % brain masks, but the bigger problem here is that the CSF intensity + % threshold were maybe affected. + + % If a skull-stripping was used, we will use this as initial mask + % that we close and dilate a little bit. + % Now, the original image can be corrected in the stripped area, + % because some images have missing points (slicewise). Becuase of + % the gaussian functions a hard boundary is better. + if Ymp0diff<0.05 && numel(Ysrc>0)/numel(Ysrc)<0.8 + Yb = smooth3(cat_vol_morph(cat_vol_morph(Ysrc>0,'lc',3),'d'))>0.5; + CSFth = min([cat_stat_nanmedian(Ysrc(Ycls{3}(:)>240 & Ysrc(:)>0)), ... + cat_stat_nanmedian(Ysrc(Ycls{3}(:)>192 & Ysrc(:)>0)), ... + cat_stat_nanmedian(Ysrc(Ycls{3}(:)>128 & Ysrc(:)>0)), ... + cat_stat_nanmean(Ysrc(Ysrc>0))*0.5])*0.9; % + Ysrc = cat_vol_laplace3R(max(CSFth,Ysrc),Yb & Ysrc==0,0.2) .* Yb; + cat_io_addwarning([mfilename ':SkullStripped'],... + 'Skull-stripped input image detected! Try boundary cleanup.',1,[1 0]); + else + cat_io_addwarning([mfilename ':SkullStripped'],... + 'Skull-stripped input image?',1,[1 0]); + end + end + end + + + %% segment refinement and median peak estimation + % ----------------------------------------------------------------- + Yg = cat_vol_grad(Ym,vx_vol); + Ydiv = cat_vol_div(Ym,vx_vol); + %noise = estimateNoiseLevel(Ym,Ycls{2}>192); + + Yb2 = cat_vol_morph(Yb & Ym>0.5,'e',2*vxv); + gth = max(0.06,min(0.3,noise*6)); + %Ybm = cat_vol_morph(Ycls{6}>240 & Ysrc128))]); + BMth = max(BGmin,min(BGcon,T3th(1) - diff(T3th(1:2)))); %max(0.01,cat_stat_nanmedian(Ysrc(Ybm(:)))); + Ywm = (Ycls{2}>128 & Yg(1-0.05*cat_stat_nanmean(vx_vol)) & Yb2); % intensity | structure (neonate contast problem) + if res.isMP2RAGE % BGth > cat_stat_nanmedian(Ysrc(Ycls{3}(:)>128)) % RD202211: MP2RAGE + Ycm = smooth3((Ycls{3}>16 | Ym<0.4) & YgBMth & Ym<0.7)>0.5 & Yg<.2 & Ycls{1}<8 ; % important to avoid PVE! ... but no CSF is also not good + else + Ycm = smooth3((Ycls{3}>240 | Ym<0.4) & YgBMth & Ym<0.7)>0.5; % important to avoid PVE! + end + + % If SPM get totaly wrong maps due to bad image orientations our + % segment were incorrect too (or empty) and peak estimation fail. + % I try to use the kmeans, but in WM it is affected by WMHs, in + % CSF by blood vessels and meninges and in GM noise and subcortical + % structures were problematic. In ADHD/..NYC..14 the basal structes + % get the average peak and the cortex was detected as CSF. There + % were much more images with smaller problems ... + Ysrcr = round( Ysrc.*10^5 ) / 10^5; + WMth = cat_stat_nanmedian(Ysrcr(Ywm(:))); % cat_stat_kmeans(Ysrc(Ycls{2}(:)>192 & Yg(:)64 & Yg(:)>gth & Yb(:)),2); % CSF CSF/GM + % 0.05 <<<<< BMth + 4*cat_stat_nanstd(Ysrc(Ybm(:))) + Ybg = cat_vol_morph(Yg<0.10 & Yb & YsrcCSFth*1.5 & Ycls{3}<64,'o',2); + Ygm = ~Ybg & Yg<0.4 & Ysrc32 & ~Ywm & Ycls{2}<64 & ... + Ysrc>(CSFth+0.1*diff([CSFth,WMth])) & ~Ywm & ~Ycm & Yb & abs(Ydiv)<0.2; + %Ygm = Ygm | (Ycls{1}>64 & Ybg & ~Ywm); + GMth = cat_stat_nanmedian(Ysrcr(Ygm(:))); %cat_stat_kmeans(Ysrc(Ygm(:)),3); % CSF/GM GM GM/WM + T3th_cls = round([CSFth(1) GMth(1) WMth(1)]*10^4)/10^4; + %clear Ybg + % + if any(isnan(T3th_cls)) + fprintf('\n'); + error('cat_main:cat_main_gintnorm:nobrain',... + 'Bad SPM-Segmentation. Please check image orientation!\n'); + end + % median tissue peaks + + + if debug==2 + tmpmat = fullfile(pth,reportfolder,sprintf('%s_%s%02d%s.mat',nam,'write',1,'gintnorm01')); + save(tmpmat,'Ysrc','Ycls','Yb','vx_vol','res','T3th','Yg','Ydiv','Ym',... + 'Yb2','gth','Ybm','BMth','Ywm','Ygm','Ycm','Ybg','T3th_cls','T3th','noise'); + end + + + %% final peaks and intensity scaling + % ----------------------------------------------------------------- + T3th3 = T3th_cls; + if res.isMP2RAGE + T3th = [min(Ysrcr(~isnan(Ysrcr(:)) & ~isinf(Ysrcr(:)))) T3th3 ... + T3th3(end) + diff(T3th3([1,numel(T3th3)])/2) ... WM+ + max(T3th3(end)+diff(T3th3([1,numel(T3th3)])/2) , ... max + max(Ysrcr(~isnan(Ysrcr(:)) & ~isinf(Ysrcr(:))))) ]; + T3thx = [0,1:5]; + else + T3th = [min(Ysrcr(~isnan(Ysrcr(:)) & ~isinf(Ysrcr(:)))) BMth min(BGth,mean([BMth,T3th3(1)])) T3th3 ... + T3th3(end) + diff(T3th3([1,numel(T3th3)])/2) ... WM+ + max(T3th3(end)+diff(T3th3([1,numel(T3th3)])/2) , ... max + max(Ysrcr(~isnan(Ysrcr(:)) & ~isinf(Ysrcr(:))))) ]; + T3thx = [0,0.02,0.05,1:5]; + end + + % intensity scaling + Ym = Ysrc; + isc = 1; + %T3th = interp1(T3th,1:1/isc:numel(T3th)*isc,'spline'); %pchip'); + %T3thx = interp1(T3thx,1:1/isc:numel(T3th)*isc,'spline'); %pchip'); + + for i=2:numel(T3th) + M = Ysrc>T3th(i-1) & Ysrc<=T3th(i); + Ym(M(:)) = T3thx(i-1) + (Ysrc(M(:)) - T3th(i-1))/diff(T3th(i-1:i))*diff(T3thx(i-1:i)); + end + M = Ysrc>=T3th(end); + Ym(M(:)) = numel(T3th)/isc/6 + (Ysrc(M(:)) - T3th(i))/diff(T3th(end-1:end))*diff(T3thx(i-1:i)); + Ym = Ym / 3; + + Tth.T3th = T3th; + Tth.T3thx = T3thx; + elseif T3th3(1)>T3th3(3) && T3th3(2)>T3th3(3) + %% reestimation of brain mask + Yb = Ym>0.8 & Ym<1.2 & (Ycls{5}<64); Yb = single(cat_vol_morph(Yb,'lo',1)); + [Ybr,Ymr,Ycls5,resT2] = cat_vol_resize({single(Yb),Ym,single(Ycls{5})/255},'reduceV',vx_vol,2,32); + Ybr(~Ybr & (Ymr<2.5/3 | Ymr>3.2/3 | Ycls5>0.5))=nan; + [Ybr1,Ydr] = cat_vol_downcut(Ybr,Ymr,0.03); Ybr(Ydr<100)=1; Ybr(isnan(Ybr))=0; + Ybr(~Ybr & (Ymr<1.9/3 | Ymr>3.2/3 | Ycls5>0.5))=nan; + [Ybr1,Ydr] = cat_vol_downcut(Ybr,Ymr,0.01); Ybr(Ydr<100)=1; Ybr(isnan(Ybr))=0; + Ybr(~Ybr & (Ymr<1/3 | Ymr>2.5/3 | Ycls5>0.5))=nan; + [Ybr1,Ydr] = cat_vol_downcut(Ybr,Ymr,-0.01); Ybr(Ydr<100)=1; Ybr(isnan(Ybr))=0; + Ybr = Ybr>0 | (Ymr<0.8 & cat_vol_morph(Ybr,'lc',6) & Ycls5<0.02); % large ventricle closing + Ybr = cat_vol_morph(Ybr,'lc',2); % standard closing + Yb = cat_vol_resize(cat_vol_smooth3X(Ybr,2),'dereduceV',resT2)>0.4; + clear Ybr Ymr; + %% filtering + %YM = YsrcTth.T3th(4))) | Ym>2; + Ym = cat_vol_median3(Ym,YM,Ym<1.5,0.1); + cat_sanlm(Ym,1,3) + elseif T3th3(1)>T3th3(3) && T3th3(2)T3th3(2) + %% filtering + Ybb = cat_vol_morph(cat_vol_morph(Yp0>0.5/3,'c',4),'d',2); + if debug, Ymo = Ym; end + if 1 + %% new approach + Yswm = Ycls{2}>Ycls{3} & Ycls{2}/32>Ycls{1} & Yg<0.2 & abs(Ydiv)<0.1; + % identify CSF areas next to high intensity regions + Ycm = smooth3(Ym<0.5 & Ycls{3}>Ycls{2} & Ycls{3}>Ycls{1} & Ysrc>(T3th3(1)*0.5+0.5*(T3th3(3))))>0.2 & (Ysrc>(T3th3(1)*0.5+0.5*(T3th3(3)))); + Ycm = cat_vol_morph(Ycm | (Yp0<1.2 & (Ym<0.5 | Ym>1.2) & cat_vol_morph(Ybb,'d',1)),'c',1); + Ycm = single(Ycm); Ycm(Ycm==0 & (Ysrc>(BGth*0.2+0.8*T3th3(2)) & Ysrc<(T3th3(2)*0.5+0.5*T3th3(3)) | ~Ybb | Yswm)) = nan; + [Ycm,YD]= cat_vol_downcut(Ycm,Ysrc./T3th3(3),-0.2); Ycm(YD>50)=0; Ycm(smooth3(Ycm)<0.4)=0; + + %% identify the WM + Ywm = ~Ycm & Ym>0.85 & Ym<1.05 & (Ycls{2}*2>Ycls{3} | Ycls{1}*2>Ycls{3} | Yp0>1.2); Ywm(smooth3(Ywm)<0.5)=0; + Ywm = cat_vol_morph(Ywm,'l',[inf 0.001])>0; + Ywm = single(Ywm); Ywm((Ywm==0 & Ym<0.8) | Ycm | ~Ybb | Ysrc>(T3th3(1)*0.5+0.5*(T3th3(3)))) = nan; + [Ywm,YD] = cat_vol_downcut(Ywm,Ysrc./T3th3(3),0.02); Ywm(YD>400)=0; Ywm(smooth3(Ywm)<0.55)=0; clear YD; + Ywm = single(Ywm); Ywm((Ywm==0 & Ym<0.8) | ~Ybb | Ysrc>(T3th3(1)*0.9+0.1*(T3th3(3)))) = nan; + [Ywm,YD] = cat_vol_downcut(Ywm,Ysrc./T3th3(3),0.01); Ywm(YD>800)=0; Ywm(smooth3(Ywm)<0.55)=0; clear YD; + Ywm(Ysrc<(T3th3(2)*0.2+0.8*(T3th3(3))))=0; + Ywm = cat_vol_morph(Ywm,'l',[inf 0.001])>0; + % + Ywm = single(Ywm); Ywm(Ywm==0 & (Ym<0.7 | Ycm | Ysrc<(T3th3(2)*0.2+0.8*(T3th3(3)))) | ~Ybb) = nan; + [Ywm,YD] = cat_vol_downcut(Ywm,Ysrc./T3th3(3),0.01); Ywm(YD>800)=0; clear YD; + Ywm = cat_vol_morph(Ywm,'l',[inf 0.001])>0; + % + Ywm = single(Ywm); Ywm(Ywm==0 & (Ym<0.7 | Ycm | Ysrc<(T3th3(2)*0.5+0.5*(T3th3(3)))) | ~Ybb) = nan; + [Ywm,YD] = cat_vol_downcut(Ywm,Ysrc./T3th3(3),-0.001); Ywm(YD>800)=0; clear YD; + Ywm(Ysrc<(T3th3(2)*0.5+0.5*(T3th3(3))))=0; + Ywm = cat_vol_morph(Ywm,'l',[inf 0.001])>0; + Ywmd = cat_vbdist(single(Ywm),Ybb); + +%% + Ycmx = (Ywmd .* Ym)>1 | ~Ybb | Ycm; + Ycmx = Ycmx & (Yg>0.01 & abs(Ydiv)>0.0001) & cat_vol_smooth3X(Yp0)<0.995 & ~Ywm ; + Ycmx(smooth3(Ycmx)<0.5)=0; + Ycmx = cat_vol_morph(Ycmx,'l',[inf 0.01])>0; + + + %% improve the CSF classification + Ycm = Ycmx | smooth3(Ym<0.5 & Ycls{3}>Ycls{2} & Ycls{3}>Ycls{1} & Ysrc>(T3th3(1)*0.5+0.5*(T3th3(3))))>0.2 & (Ysrc>(T3th3(1)*0.5+0.5*(T3th3(3)))); + Ycm = single(Ycm); Ycm(Ycm==0 & (~Ybb | Ywm | Ysrc<( T3th3(2)*0.8+0.2*(T3th3(3)))) ) = nan; + [Ycm,YD]= cat_vol_downcut(Ycm,Ysrc./T3th3(3),0.01); Ycm(YD>50)=0; Ycm(smooth3(Ycm)<0.4)=0; clear YD; + Ycm = cat_vol_morph(Ycm,'l',[inf 0.1])>0; + %% + %Ycm = single(Ycm); Ycm((Ycm==0 & Ysrc>(T3th3(1)*0.5+0.5*(T3th3(3))) ) | ~Yb | smooth3(Ywm)>0 | Ysrc<(T3th3(2)*0.9+0.1*(T3th3(3)))) = nan; + %[Ycm,YD]= cat_vol_downcut(Ycm,Ysrc./T3th3(3),0.005); Ycm(YD>800)=0; Ycm(smooth3(Ycm)<0.4)=0; clear YD; + %Ycm = Ycm | (Yp0<1.5 & Ym<0.5 & Yb); + + %% simultan region growing of CSF and WM tissue + Ypx = single(Ywm*3 + Ycm); Ypx(~Ybb | (Ym>0.6 & Ym<0.7)) = nan; Ypx = cat_vol_median3c(Ypx,Ybb); + [Ypx,YD] = cat_vol_downcut(single(Ypx),Ysrc/T3th3(3),-0.01); Ypx(YD>50)=0; Ypx = cat_vol_median3c(Ypx,Ybb); Ypx(~Ybb) = nan; + [Ypx,YD] = cat_vol_downcut(single(Ypx),Ysrc/T3th3(3),-0.01); Ypx(YD>50)=0; clear YD; + + %% cortical thickness based modification + Ys = Ypx==3 & Ym>2.5/3; + [Ysr,Ybr,resTx] = cat_vol_resize({single(Ys),Ybb},'reduceV',vx_vol,1,16,'meanm'); + [Ygmt,Ypp] = cat_vol_pbt( single(1 + (Ybb.* (Ym>0.5)) + Ys) , ... + struct('verb',0,'dmethod','eidist','method','pbt2x') ); + + %% final correction + YM = cat_vol_smooth3X(Ypp,0.5)<0.3 & Ygmt>1 & Ym>2/3 & Ypx<2; + YM = YM | (Ypx==1 & Ym>0.7 & Ym<0.9) | (Ycm & Ym>0.7); + YM = YM | (cat_vol_smooth3X(cat_vol_morph(~Ywm & Ygmt>0.1 & Ygmt<1.2 & Ypx<2,'c',1),1)>0.5 & Ywm); + Ym(YM) = 0.5 + max(0,1 - Ym(YM))/2; + %% + %Ym = cat_vol_median3(Ym,Yb & Ypp<0.5,Ypp<0.5,0.05); + %Ym = cat_vol_median3(Ym,Yb & Ypp>0.5,Ypp>0.5,0.05); + %Ym = cat_vol_median3(Ym,Yb & Ym>0.8 & Ym>1.1,Yb,0.1); + cat_sanlm(Ym,1,3) + else + % old approach ... + %YM = YsrcTth.T3th(4))) | Ym>2; + Ym = cat_vol_median3(Ym,YM,Ym<1.5,0.1); + end + end + + + + %% if there was a warning we need a new line + if numel(nwarnings) < numel(cat_io_addwarning) + cat_io_cmd(' ','','',1); + end + +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_vol_testflipping.m",".m","7318","160","function [flipped,flippedval,stime] = cat_vol_testflipping(varargin) +%cat_vol_testflipping. Test input image for LR flipping. +% Side flipping of images can accidently occurring by converting images types +% (eg. mnc2nii in minc-tools) or by realigning images. Most brains of larger +% animals show a slight positive rotation (i.e. against the clock) that can +% be seen quite good on the top view of both hemishpheres. The left hemi- +% sphere is a bit smaller in frontal regions but its occipital lob is a bit +% longer or moves a bit more to the right. Moreover the +% +% isflipped = cat_vol_testflipping(obj,Affine,method,stime,verb) +% +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + if nargin == 1; + %job = varargin; + else + obj = varargin{1}; + Affine = varargin{2}; + method = varargin{3}; + if nargin>=4 + stime = varargin{4}; + else + stime = clock; + end + if nargin>=5 + verb = varargin{5}; + else + verb = 0; + end + end + + + switch method + case 1 + % simple fast test and warning if the x axis is positive that is + % untypical for (structural) MRI. + + mati = spm_imatrix( Affine ); + if sign( mati(7) ) == -1 + flipped = 1; + flippedval = 1; + mid = [mfilename 'cat_run_job:PossiblyFlippedInput']; + msg = sprintf(['Positive x coordinate detected. \\\\n' ... + 'Please check image for _possible_ side flipping. \\\\n'... + 'You can check for the expected surface rotation (against the clock). \\\\n' ... + 'Use spm_image to correct flipping by changing the \\\\n' ... + 'sign of the x axis scaling from 1 to -1. ']); + cat_io_addwarning(mid,msg,2,[0 2]); + else + flipped = 0; + flippedval = 0; + end + + case 2 + %% test for flipping + % RD202009: IN DEVELOPMENT - not working in all cases + % The flipping test focuses on the following aspects + % (i) better alignment to normal side-biased average template, + % (ii) more neutral alignment of flipped data also after additional + % flipping, and + % (iii) less shearing in unflipped data. + % + % Just draw and test the different cases on paper + % _____ _____ _____ + % / \ \ / / \ / | \ + % / | \ / | \ / \ \ + % \___\___/ \___/___/ \___|___/ + % unflipped flipped flipped + % aligned + + + % The test takes about 20 to 120 seconds and we need some command line output. + if nargin >= 4 + stime = cat_io_cmd('Test side flipping:','','',1,stime); + end + + % Apply affine registration to use a rigid transformation. + % Use only rounded parts of the initial affine registration to avoid + % a too strong bias - at least reset the shearing component to 0 but + % try to use the othere information to avoid miss-alignments and long + % processing. Unclear how well this works + affscale = spm_imatrix(Affine); + affscale(1:3) = fix(affscale(1:3) / 3 ) * 3; % remove translation bias + %affscale(4:9) = fix(affscale(4:9) * 100) / 100; % remove rotation bias + affscale(10:12) = 0; % remove shearing bias + affscale = spm_matrix(affscale); + + %obj.fwhm = 0; + obj.imageflipped(1) = obj.image(1); + obj.imageflipped(1).mat = affscale * obj.image.mat; + obj.image.mat = affscale * obj.image.mat; + % flipped image + obj.imageflipped(1).mat = [-1 0 0 0; 0 1 0 0 ; 0 0 1 0; 0 0 0 1] * obj.image(1).mat; + + % add artificial positive rotation that is worse for flipped images + imat = spm_imatrix(obj.image(1).mat); imat(6) = imat(6) - 0.01; obj.image(1).mat = spm_matrix(imat); + imat = spm_imatrix(obj.imageflipped(1).mat); imat(6) = imat(6) - 0.01; obj.imageflipped(1).mat = spm_matrix(imat); + + % Estimate ideal rigid registration for both flipped and unflipped + % It is expected that the unflipped images can achieve a higher + % log-likelyhood (llu vs. llf) + % This test is expecting a allready aligned images from cat_run_job + % and use lower number of interation to increase speed. + [Affineu,llu ] = spm_maff8(obj.image(1) ,obj.samp,obj.fwhm,obj.tpm,eye(4) ,'rigid',10); + [Affinef,llf ] = spm_maff8(obj.imageflipped(1),obj.samp,obj.fwhm,obj.tpm,eye(4) ,'rigid',10); + + % Use only one interation to just estimate the log-likelyhood. + % For the additional flipped image it is expected that the alignment + % is better for a flipped image because its alignment is already a + % compromise, whereas a unflipped images with match better to the + % template before but not after flipping. + [Affinebu,llbu] = spm_maff8(obj.imageflipped(1),obj.samp,obj.fwhm,obj.tpm,Affineu,'rigid',1); %#ok + [Affinebf,llbf] = spm_maff8(obj.image(1) ,obj.samp,obj.fwhm,obj.tpm,Affinef,'rigid',1); %#ok + + % registration compontents + mati = spm_imatrix( Affineu ); + matiflipped = spm_imatrix( Affinef ); + + % main test variables + flippedval(1) = (sum(abs( mati(10:11) )) / sum(abs( matiflipped(10:11) )) - 1); % less shearing + flippedval(2) = ((llf ./ llu ) - 1) * 100; % the correct image fits better to the TPM + flippedval(3) = ((llbu ./ llbf) - 1) * 100; % if we flip the perfect align image the overlap of the correct image is _lower_ + + % main variable with weighing and limitations + flipped = min(0.95,max(-.95, flippedval(1) / 3 + ... + flippedval(2) * 2 + ... + flippedval(3) / 2 )); + + % just print some values + if verb + disp([mati llu llbu 0 0 0;matiflipped llf llbf flippedval]) + end + + %% warning/error message + % Create the final message as note/warning/alert, depending on the + % estimated probability of flipping. + if flipped>0.3 + fprintf('\n'); + mstr = {'mostLikelyUNflippedInput','possiblyFlippedInput','probablyFlippedInput','mostLikelyFlippedInput'}; + fstr = {'most likely NOT','possibly','probably','most likely'}; + mid = [mfilename 'cat_run_job:%s',mstr{ round(flipped * (numel(fstr) - 1) + 1 ) }]; + msg = sprintf(['The image is %s flipped (probability %0.0f%%%%%%%%)! \\\\n'... + 'You can check the surface rotation (against the clock). \\\\n' ... + 'Use spm_image to correct flipping by changing the \\\\n' ... + 'scaling of the x axis scaling from 1 to -1. '], ... + fstr{ round(flipped * (numel(fstr) - 1) + 1 ) }, flipped * 100 ); + + cat_io_addwarning(mid,msg,round(flipped * 3 - 1),[0 2],flippedval); + end + otherwise + error('Unknown method %s.',method) + end +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_vol_simgrow.m",".m","1140","30","%cat_vol_simgrow Volumetric region-growing. +% +% [SLAB,DIST] = cat_vol_simgrow(ALAB,SEG[,d,dims,dd]); +% +% SLAB (3D single) .. output label map +% DIST (3D single) .. distance map from region-growing +% ALAB (3D single) .. input label map +% SEG (3D single) .. input tissue map +% d (1x1 double) .. growing treshhold parameter (max local gradient) +% in SEG +% dims (1x3 double) .. voxel dimensions (default [1,1,1]) +% dd (1x2 double) .. general growing limits in SEG +% +% Examples: +% 1) +% A = zeros(50,50,3,'single'); A(:,1:25,:)=0.25; A(:,25:end,:)=0.75; +% A = A + (rand(size(A),'single')-0.5)*0.05; +% B = zeros(50,50,3,'single'); B(15:35,15:20,:)=1; B(15:35,30:35,:)=2; +% [C,D] = cat_vol_simgrow(B,A,1); ds('d2smns','',1,A,C,2); +% +% See also cat_vol_downcut. +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_main_update_intnorm.m",".m","6932","164","function [Ym2,Ymi2,Tthm,Tthmi] = cat_main_update_intnorm(Ym,Ymi,Yb,Ycls,job,verb,indx,indy,indz) +%cat_main_update_intnorm. Fine intensity normalization in optimal images. +% This is a temporary function to test the some concepts of improving the +% intensity scaling in prepared images. This function expect optimal pre- +% processed data that is corrected for noise and inhomogeneities! +% +% - after cat_main_LAS: +% [Ym2,Ymi2] = cat_main_update_intnorm(Ym,Ymi,Yb,Ycls,verb) +% +% - after AMAP with own peak estimation +% [Ym2,Ymi2] = cat_main_update_intnorm(Ym,Ymi,Yb,prob,verb,indx,indy,indz) +% +% - after AMAP with AMAP thresholds +% [Ym2,Ymi2] = cat_main_update_intnorm(Ym,Ymi,AMAPths) +% +% Ym[i][2] .. global/local intensity normalized input/output images +% Yb .. brain mask +% Ycls .. tissue classes as cell +% prob .. tissue classes as 4D matrix +% ind[xyz] .. subregions defined by prob +% verb .. display some details (only for tests/development) +% AMAPths .. do not estimate peaks and just use the given +% (1x3 cell with 1x2 matrix with mean and std given by AMAP) +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +% +% ToDo: Test with PD/T2/FLAIR/MP2 +% + + % be verbose for tests + fprintf(' --- Update Ym and Ymi --- \n'); + + def.extopts.ignoreErrors = 0; + job = cat_io_checkinopt(job,def); + if ~exist('verb','var'), verb = 0; end + pve = 0; % estimate peaks also for the PVE boudary region (IN DEVELOPMENT) + + if numel(Yb) == 3 + % Final intensity scaling for local intensity normalized map Ymi that + % uses the AMAP threshholds. + Tthamap = struct('T3th',{0:1/3:2},'T3thx',{3*[0 Yb{1}(1) Yb{2}(1) Yb{3}(1) 4/3:1/3:2] }); + Ymi2 = cat_main_gintnormi(Ymi,Tthamap); + Ym2 = cat_main_gintnormi(Ym ,Tthamap); + return + end + + % thresholds variables and smaller brainmask (to avoid PVE to background) + mith = zeros(1,3); mth = mith; + Ybe = cat_vol_morph(Yb,'e',2); + + % The AMAP gives us a 4D-matrix, whereas SPM/cat_main uses a cell + % structure with each tissue class. + if ndims(Ycls)==4 || ndims(Ycls)==3 + prob = Ycls; clear Ycls; + for i = 1:3 + Ycls{i} = zeros(size(Ym),'uint8'); + Ycls{i}(indx,indy,indz) = prob(:,:,:,i); + end + clear prob; + end + + % Different handling in case of other contrasts. + % **** This needs more tests **** + invers = cat_stat_nanmean(Ym(Ycls{2}(:)>0)) < cat_stat_nanmean(Ym(Ycls{3}(:)>0)); + if invers, thsel = [0 1 2]; else, thsel = [0 2 1]; end + + + + + %% final intensity scaling for global intensity normalized map Ym + % The main aim is to estimate the best value that represents a tissue class. + % This is in general the most typical value that occures most times and + % that is the peak of the histogram. To avoid side effects by the PVE + % it is usefull to use a mask for tissue with large/thick/compact volume + % such as the CSF and WM but not for the GM! In addition we expect a much + % smaller side peak, especially in the unmasked WM, where 5 peaks are + % useful becuase there are also real local intensity differences in the + % subcortical structures but also by the differently myelinated cortex. + % For our highly corrected input the curve of the WM and CSF are not + % symetric and only include PVE torwards the CSF. + % + % Moreover, it is more save to use allways the peak with the larger GM + % distance, i.e., in T1 images the smalles/highest peak in the CSF/WM. + % .. However, right now we are just using the highest one that is easier + % in case of different contrast + for i = 1:3 + % masking + if i==1 + Yclse = Ycls{i}>16; % just a little bit in the GM + else + if job.extopts.ignoreErrors < 3 + Yclse = cat_vol_morph(Ycls{i}>240,'e'); % much more in the GM/CSF + else + Yclse = cat_vol_morph(Ycls{i}>16,'e'); % much more in the GM/CSF + end + end + % assure that there are enough values (e.g. in children/olderly the + % CSF/WM can be quite small + if sum(Yclse(:))<100, Yclse = cat_vol_morph(Ycls{i}>128); end + if sum(Yclse(:))<50, Yclse = cat_vol_morph(Ycls{i}>0); end + + % estimate the peaks + if job.extopts.ignoreErrors < 3 + [tth,sd,h] = cat_stat_kmeans(Ymi( Yclse & Ybe ),2 + 3*(i==1)); % 2 peaks for CSF/WM and 5 for GM + if i==1, mith(i) = tth(h==max(h)); else, mith(i) = tth( thsel(i) ); end + [tth,sd,h] = cat_stat_kmeans(Ym ( Yclse & Ybe ),2 + 3*(i==1)); + if i==1, mth(i) = tth(h==max(h)); else, mth(i) = tth( thsel(i) ); end + else + % inoptimal preprocessing with some noise, bias, and more PVE + % more classes but still inbalanced for CSF/WM (4 rather than the 5 GM classes) + [tth,sd,h] = cat_stat_kmeans(Ymi( Yclse & Ybe ),4 + 1*(i==1)); % 2 peaks for CSF/WM and 5 for GM + if i==1, mith(i) = tth(h==max(h)); else, mith(i) = tth( thsel(i) ); end + [tth,sd,h] = cat_stat_kmeans(Ym ( Yclse & Ybe ),4 + 1*(i==1)); + if i==1, mth(i) = tth(h==max(h)); else, mth(i) = tth( thsel(i) ); end + end + end + + + if pve + %% PVE peaks (IN DEVELOPMENT) + % Peaks of PVE regions are difficult but the edge map of the image and + % segmentation may allow the definition of this area ... + % the matlab isosurface may also helps to extract a sublayer ... + if ~exist('S2','var') + S1 = isosurface( Ycls{1} + Ycls{2} , 128); + S2 = isosurface( Ycls{2} , 128); + end + mipveth(1) = cat_stat_kmeans( cat_surf_fun('isocolors',S1,Ymi ),1); + mipveth(2) = cat_stat_kmeans( cat_surf_fun('isocolors',S2,Ymi ),1); + mpveth(1) = cat_stat_kmeans( cat_surf_fun('isocolors',S1,Ym ),1); + mpveth(2) = cat_stat_kmeans( cat_surf_fun('isocolors',S2,Ym ),1); + end + + + % final scaling + if pve + Tthmi = struct('CGW',mith,'PVEth',mipveth,'T3th',{[0 1/3:1/6:5/6 1:1/3:2]},'T3thx',{3*[0 sort( [mith mipveth]) 4/3:1/3:2] }); + Tthm = struct('CGW',mth ,'PVEth',mpveth ,'T3th',{[0 1/3:1/6:5/6 1:1/3:2]},'T3thx',{3*[0 sort( [mth mpveth]) 4/3:1/3:2] }); + else + Tthmi = struct('CGW',mith,'T3th',{0:1/3:2},'T3thx',{3*[0 sort( mith ) 4/3:1/3:2] }); + Tthm = struct('CGW',mth ,'T3th',{0:1/3:2},'T3thx',{3*[0 sort( mth ) 4/3:1/3:2] }); + end + + + % the final scaling + Ymi2 = cat_main_gintnormi(Ymi,Tthmi); + Ym2 = cat_main_gintnormi(Ym ,Tthm); + + + % display a result histogram figure + if verb + cat_plot_histogram(Ym2(Yb(:))); set(gcf,'Menubar','figure'); + hold on; for i=1:0.5:3, plot([i/3 i/3;],get(gca,'ylim'),'r'); end + cat_plot_histogram(Ymi2(Yb(:))); set(gcf,'Menubar','figure'); + hold on; for i=1:0.5:3, plot([i/3 i/3;],get(gca,'ylim'),'r'); end + end +return","MATLAB" +"Neurology","ChristianGaser/cat12","cat_conf_extopts.m",".m","66850","1314","function extopts = cat_conf_extopts(expert,spmseg) +% Configuration file for extended CAT options +% +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ +%#ok<*AGROW> + +if ~exist('expert','var') + expert = 0; % switch to de/activate further GUI options +end + +if ~exist('spmseg','var') + spmseg = 0; % SPM segmentation input +end + +%_______________________________________________________________________ + +% options for output +%----------------------------------------------------------------------- + +vox = cfg_entry; +vox.tag = 'vox'; +vox.name = 'Voxel size for normalized images'; +vox.strtype = 'r'; +vox.num = [1 1]; +vox.def = @(val)cat_get_defaults('extopts.vox', val{:}); +vox.help = { + 'The (isotropic) voxel sizes of any spatially normalised written images. A non-finite value will be replaced by the average voxel size of the tissue probability maps used by the segmentation.' + '' +}; +if expert > 1 + vox.num = [1 inf]; + vox.help = [vox.help; { + 'Developer option: ' + ' For multiple values the first value is used for the final output, whereas results for the other values are saved in separate sub directories. ' + '' + }]; +end + +%------------------------------------------------------------------------ +% SPM, Dartel, Shooting Template Maps +% e.g. for other species +%------------------------------------------------------------------------ + +darteltpm = cfg_files; +darteltpm.tag = 'darteltpm'; +darteltpm.name = 'Dartel Template'; +darteltpm.def = @(val)cat_get_defaults('extopts.darteltpm', val{:}); +darteltpm.num = [1-spmseg 1]; +darteltpm.filter = 'image'; +darteltpm.ufilter = 'Template_1'; +if spmseg + darteltpm.help = { + 'Select the first of six images (iterations) of a Dartel template. The Dartel template must be in multi-volume (5D) nifti format and should contain GM and WM segmentations. If the field is empty no Dartel registration will be performed.' + '' + 'Please note that the use of an own Dartel template will result in deviations and unreliable results for any ROI-based estimations because the atlases will differ and any ROI processing will be therefore deselected.' + '' + }; +else + darteltpm.help = { + 'Select the first of six images (iterations) of a Dartel template. The Dartel template must be in multi-volume (5D) nifti format and should contain GM and WM segmentations. ' + '' + 'Please note that the use of an own Dartel template will result in deviations and unreliable results for any ROI-based estimations because the atlases will differ and any ROI processing will be therefore deselected.' + '' + }; +end + + +%--------------------------------------------------------------------- + +shootingtpm = cfg_files; +shootingtpm.tag = 'shootingtpm'; +shootingtpm.name = 'Shooting Template'; +shootingtpm.def = @(val)cat_get_defaults('extopts.shootingtpm', val{:}); +shootingtpm.num = [1-spmseg 1]; +shootingtpm.filter = 'image'; +shootingtpm.ufilter = 'Template_0'; +if spmseg + shootingtpm.help = { + 'Select the first of five images (iterations) of a Shooting template. The Shooting template must be in multi-volume (5D) nifti format and should contain GM, WM, and background segmentations and have to be saved with at least 16 bit. If the field is empty no Dartel registration will be performed and the default SPM registration is used instead.' + '' + 'Please note that the use of an own Shooting template will result in deviations and unreliable results for any ROI-based estimations because the atlases will differ and any ROI processing will be therefore deselected.' + '' +}; +else + shootingtpm.help = { + 'Select the first of five images (iterations) of a Shooting template. The Shooting template must be in multi-volume (5D) nifti format and should contain GM, WM, and background segmentations and have to be saved with at least 16 bit. ' + '' + 'Please note that the use of an own Shooting template will result in deviations and unreliable results for any ROI-based estimations because the atlases will differ and any ROI processing will be therefore deselected.' + '' + }; +end + +%------------------------------------------------------------------------ + +cat12atlas = cfg_files; +cat12atlas.tag = 'cat12atlas'; +cat12atlas.name = 'CAT12 ROI atlas'; +cat12atlas.filter = 'image'; +cat12atlas.ufilter = 'cat'; +cat12atlas.def = @(val)cat_get_defaults('extopts.cat12atlas', val{:}); +cat12atlas.num = [1 1]; +cat12atlas.help = { + 'CAT12 atlas file to handle major regions.' +}; + +%------------------------------------------------------------------------ + +brainmask = cfg_files; +brainmask.tag = 'brainmask'; +brainmask.name = 'Brainmask'; +brainmask.filter = 'image'; +brainmask.ufilter = 'brainmask'; +if spmseg % in case of SPM this fields are not required yet + brainmask.val{1} = {''}; +else + brainmask.def = @(val)cat_get_defaults('extopts.brainmask', val{:}); +end +brainmask.hidden = ~spmseg || expert<2; +brainmask.num = [1 1]; +brainmask.help = { + 'Initial brainmask.' +}; + +%------------------------------------------------------------------------ + +T1 = cfg_files; +T1.tag = 'T1'; +T1.name = 'T1'; +T1.filter = 'image'; +T1.ufilter = 'T1'; +if spmseg % in case of SPM this fields are not required yet + T1.val{1}= {''}; +else + T1.def = @(val)cat_get_defaults('extopts.T1', val{:}); +end +T1.hidden = ~spmseg || expert<2; +T1.num = [1-spmseg 1]; +T1.help = { + 'Affine registration template. ' % Implement? >> If no image is give only the TPM is used for registration. +}; + +%------------------------------------------------------------------------ + +WMHtpm = cfg_files; +WMHtpm.tag = 'WMHtpm'; +WMHtpm.name = 'WMH-TPM'; +WMHtpm.filter = 'image'; +WMHtpm.ufilter = ''; +WMHtpm.hidden = ~spmseg || expert<2; +if spmseg % in case of SPM this fields are not required yet + WMHtpm.val{1}= {''}; +elseif isempty(cat_get_defaults('extopts.WMHtpm')) % default files without WMHtpm + WMHtpm.val{1}= spm_file(cat_get_defaults('extopts.T1'),'filename','cat_wmh_miccai2017.nii'); +else + WMHtpm.def = @(val)cat_get_defaults('extopts.WMHtpm', val{:}); +end +WMHtpm.num = [0 1]; +WMHtpm.help = { + 'White matter hyperintensity tissue probability map. ' + 'If no image is give the WMH detection focus on atypical GM close to ventricular regions or within the WM that does not belong to subcortical structures without further prior weighting. ' +}; + +%------------------------------------------------------------------------ + +BVtpm = cfg_files; +BVtpm.tag = 'BVtpm'; +BVtpm.name = 'BV-TPM'; +BVtpm.filter = 'image'; +BVtpm.ufilter = ''; +BVtpm.hidden = ~spmseg || expert<2; +if spmseg % in case of SPM this fields are not required yet + BVtpm.val{1}= {''}; +elseif isempty(cat_get_defaults('extopts.BVtpm')) % default files without BVtpm + BVtpm.val{1}= spm_file(cat_get_defaults('extopts.T1'),'filename','cat_bloodvessels.nii'); +else + BVtpm.def = @(val)cat_get_defaults('extopts.BVtpm', val{:}); +end +BVtpm.num = [0 1]; +BVtpm.help = { + 'Blood vessel tissue probability map. ' + 'If no map is give the blood vessel detection focus on high intensity 1D structures without further prior weighting. ' +}; + +%------------------------------------------------------------------------ + +SLtpm = cfg_files; +SLtpm.tag = 'SLtpm'; +SLtpm.name = 'SL-TPM'; +SLtpm.filter = 'image'; +SLtpm.ufilter = ''; +SLtpm.hidden = ~spmseg || expert<2; +if spmseg + SLtpm.val{1} = {''}; % +elseif isempty(cat_get_defaults('extopts.SLtpm')) % default files without SLtpm + SLtpm.val{1}= spm_file(cat_get_defaults('extopts.T1'),'filename','cat_strokelesions_ATLAS303.nii'); +else + SLtpm.def = @(val)cat_get_defaults('extopts.SLtpm', val{:}); +end +SLtpm.num = [0 1]; +SLtpm.help = { + 'Stroke lesion tissue probability map.' +}; + +%--------------------------------------------------------------------- + +% boundary box +bb = cfg_entry; +bb.strtype = 'r'; +bb.num = [inf inf]; +bb.tag = 'bb'; +bb.name = 'Bounding box'; +bb.def = @(val)cat_get_defaults('extopts.bb', val{:}); +bb.hidden = expert < 1 && ~spmseg; +bb.help = { + 'The bounding box describes the dimensions of the volume to be written starting from the anterior commissure in mm. It should include the entire brain (or head in the case of the Boundary Box of the SPM TPM) and additional space for smoothing the image. The MNI 9-mm boundary box is optimized for CATs MNI152NLin2009cAsym template and supports filter cores up to 10 mm. Although this box support 12 mm filter sizes theoretically, slight interference could occur at the edges and larger boxes are recommended for safety. ' + 'Additionally, it is possible to use the boundary box of the TPM or the template for special (animal) templates with strongly different boundary boxes. ' + '' + 'The boundary box or its id (BBid see table below) has to be entered. ' + '' + ' NAME BBID BOUNDARY BOX SIZE ? FILESIZE $ ' + ' TMP BB 0 boundary box of the template (maybe too small for smoothing!) ' + ' TPM BB 1 boundary box of the TPM ' + ' MNI SPM 16 [ -90 -126 -72; 90 90 108 ] [121x145x121] 4.2 MB (100%)' + ' MNI CAT 12 [ -84 -120 -72; 84 84 96 ] [113x139x113] 3.8 MB ( 84%)' + ' ? - for 1.5 mm; $ - for 1.5 mm uint8' + '' +}; + + +%--------------------------------------------------------------------- + +if expert==0 + regstr = cfg_menu; + regstr.labels = { + 'Optimized Shooting' + 'Default Shooting' + }; + regstr.values = {0.5 4}; % special case 0 = 0.5 due to Dartel default seting + regstr.help = [regstr.help; { ... + 'For spatial registration CAT offers the use of the Dartel (Ashburner, 2008) and Shooting (Ashburner, 2011) registrations to an existing template. Furthermore, an optimized shooting approach is available that uses an adaptive threshold and lower initial resolutions to obtain a good tradeoff between accuracy and calculation time. The CAT default templates were obtained by standard Dartel/Shooting registration of 555 IXI subjects between 20 and 80 years. ' + 'The registration time is typically about 3, 10, and 5 minutes for Dartel, Shooting, and optimized Shooting for the default registration resolution. ' + '' + }]; +elseif expert==1 + regstr = cfg_menu; + regstr.labels = { + 'Default Shooting (4)' + 'Optimized Shooting - vox (5)' + 'Optimized Shooting - fast (eps)' + 'Optimized Shooting - standard (0.5)' + 'Optimized Shooting - fine (1.0)' + 'Optimized Shooting - strong (11)' + 'Optimized Shooting - medium (12)' + 'Optimized Shooting - soft (13)' + }; + regstr.values = {4 5 eps 0.5 1.0 11 12 13}; % special case 0 = 0.5 due to Dartel default seting + regstr.help = [regstr.help; { ... + 'The strength of the optimized Shooting registration depends on the stopping criteria (controlled by the ""extopts.regstr"" parameter) and by the final registration resolution that can be given by the template (fast,standard,fine), as fixed value (hard,medium,soft), or (iii) by the output resolution (vox). In general the template resolution is the best choice to allow an adaptive normalization depending on the individual anatomy with some control of the calculation time. Fixed resolution allows to roughly define the degree of normalization for all images with 2.0 mm for smoother and 1.0 mm for stronger deformations. For special cases the registration resolution can also be set by the output resolution controlled by the ""extopts.vox"" parameter. ' + '' + ' 0 .. ""Dartel""' + ' 4 .. ""Default Shooting""' + ' 5 .. ""Optimized Shooting - vox"" .. vox/2:vox/4:vox' + '' + ' eps .. ""Optimized Shooting - fast"" .. TR/2:TR/4:TR (avg. change rate)' + ' 0.5 .. ""Optimized Shooting - standard"" .. TR/2:TR/4:TR (avg. change rate)' + ' 1.0 .. ""Optimized Shooting - fine"" .. TR/2:TR/4:TR (small change rate)' + '' + ' 11 .. ""Optimized Shooting - strong"" .. max( 1.0 , [3.0:0.5:1.0] )' + ' 22 .. ""Optimized Shooting - medium"" .. max( 1.5 , [3.0:0.5:1.0] )' + ' 23 .. ""Optimized Shooting - soft"" .. max( 2.0 , [3.0:0.5:1.0] )' + }]; +else + % allow different registrations settings by using a matrix + regstr = cfg_entry; + regstr.strtype = 'r'; + regstr.num = [1 inf]; + regstr.help = [regstr.help; { ... + '""Default Shooting"" runs the original Shooting approach for existing templates and takes about 10 minutes per subject for 1.5 mm templates and about 1 hour for 1.0 mm. ' + 'The ""Optimized Shooting"" approach uses lower spatial resolutions in the first iterations and an adaptive stopping criteria that allows faster processing of about 6 minutes for 1.5 mm and 15 minutes for 1.0 mm. ' + '' + 'In the development modus the deformation levels are set by the following values (TR=template resolution) ...' + ' 0 .. ""Use Dartel"" ' + ' eps - 1 .. ""Optimized Shooting"" with lower (eps; fast) to higher quality (1; slow; default 0.5)' + ' 2 .. ""Optimized Shooting"" .. 3:(3-TR)/4:TR' + ' 3 .. ""Optimized Shooting"" .. TR/2:TR/4:TR' + ' 4 .. ""Default Shooting"" .. only TR' + ' 5 .. ""Optimized vox Shooting "" .. vox/2:vox/4:vox' + ' 6 .. ""Optimized Shooting - hydrocephalus (6)""' + ' Use many iterations! Very slow! Use k-means AMAP as initial Segmentation!' + '' + ' 10 .. ""Stronger Shooting"" .. max( 0.5 , [2.5:0.5:0.5] )' + ' 11 .. ""Strong Shooting"" .. max( 1.0 , [3.0:0.5:1.0] )' + ' 12 .. ""Medium Shooting"" .. max( 1.5 , [3.0:0.5:1.0] )' + ' 13 .. ""Soft Shooting"" .. max( 2.0 , [3.0:0.5:1.0] )' + ' 14 .. ""Softer Shooting"" .. max( 2.5 , [3.0:0.5:1.0] )' + ' 15 .. ""Supersoft Shooting"" .. max( 3.0 , [3.0:0.5:1.0] )' + '' + ' 10 .. ""Stronger Shooting TR"" .. max( max( 0.5 , TR ) , [2.5:0.5:0.5] )' + ' 21 .. ""Strong Shooting TR"" .. max( max( 1.0 , TR ) , [3.0:0.5:1.0] )' + ' 22 .. ""Medium Shooting TR"" .. max( max( 1.5 , TR ) , [3.0:0.5:1.0] )' + ' 23 .. ""Soft Shooting TR"" .. max( max( 2.0 , TR ) , [3.0:0.5:1.0] )' + ' 24 .. ""Softer Shooting TR"" .. max( max( 2.5 , TR ) , [3.0:0.5:1.0] )' + ' 25 .. ""Softer Shooting TR"" .. max( max( 3.0 , TR ) , [3.0:0.5:1.0] )' + '' + 'Double digit variants runs only for a limited resolutions and produce softer maps. The cases with TR are further limited by the template resolution and to avoid additional interpolation. ' + '' + 'For each given value a separate deformation process is started in inverse order and saved in subdirectories. The first given value that runs last will be used in the following CAT processing. ' + '' + }]; +end +regstr.tag = 'regstr'; +if cat_get_defaults('extopts.regstr')>0 + regstr.def = @(val)cat_get_defaults('extopts.regstr',val{:}); +else + regstr.val = {0.5}; +end +regstr.name = 'Method'; + +%--------------------------------------------------------------------- + +dartel = cfg_branch; +dartel.tag = 'dartel'; +dartel.name = 'Dartel Registration'; +dartel.val = {darteltpm}; +dartel.help = { + 'Classical Dartel (Ashburner, 2008) registrations to a existing template. The CAT default templates were obtained by standard Dartel registration of 555 IXI subjects between 20 and 80 years. ' + '' +}; + +shooting = cfg_branch; +shooting.tag = 'shooting'; +shooting.name = 'Shooting Registration'; +shooting.val = {shootingtpm regstr}; +shooting.help = { + 'Shooting (Ashburner, 2011) registrations to a existing template. Furthermore, an optimized shooting approach is available that use adaptive threshold and lower initial resolution to improve accuracy and calculation time at once. The CAT default templates were obtained by standard Shooting registration of 555 IXI subjects between 20 and 80 years. ' + '' +}; + +% only allow Shooting in default mode +if expert==0 + registration = cfg_choice; + registration.tag = 'registration'; + registration.name = 'Spatial Registration'; + registration.values = {shooting}; + registration.val = {shooting}; +else + if expert==1 + method = cfg_choice; + method.tag = 'regmethod'; + method.name = 'Spatial Registration Method'; + method.values = {dartel shooting}; + if cat_get_defaults('extopts.regstr')==0 + method.val = {dartel}; + else + method.val = {shooting}; + end + end + + registration = cfg_branch; + registration.tag = 'registration'; + registration.name = 'Spatial Registration Options'; + if expert==2 || spmseg + registration.val = {T1 brainmask cat12atlas darteltpm shootingtpm regstr bb vox}; + else + registration.val = {method vox bb}; + end +end +registration.help = { + 'For spatial registration CAT offers to use the classical Dartel (Ashburner, 2008) and Shooting (Ashburner, 2011) registrations to a existing template. Furthermore, an optimized shooting approach is available that use adaptive threshold and lower initial resolution to improve accuracy and calculation time at once. The CAT default templates were obtained by standard Dartel/Shooting registration of 555 IXI subjects between 20 and 80 years. ' + 'The registration time is typically about 3, 10, and 5 minutes for Dartel, Shooting, and optimized Shooting for the default registration resolution. ' + '' +}; + +%--------------------------------------------------------------------- + +% This version is not ready right now and I packed all working improvments +% (such as the Laplace-based blood-vessel-correction) into cat_surf_createCS2. +pbtver = cfg_menu; +pbtver.tag = 'pbtmethod'; +pbtver.name = 'Projection-based thickness'; +pbtver.labels = {'PBT','PBTx','PBT simple'}; +pbtver.values = {'pbt2','pbt2x','pbtsimple'}; +pbtver.def = @(val) 'pbtsimple'; +pbtver.hidden = expert<2; +pbtver.help = { + ['Version of the projection-based thickness (PBT) thickness and surface reconstruction approach (Dahnke et al., 2013). ' ... + 'Version 2 first estimates a temporary central surface by utilizing higher CSF and lower WM boundaries to utilize the partial volume effect. ' ... + 'This surface divides the GM into a lower and upper GM area where PBT is used with sulcal reconstruction in the lower and gyrus reconstruction in the upper part. ' ... + 'The estimated thickness values of each part were projected over the whole GM and summed up to obtain the full thickness. ' ... + 'Similar to PBT, the project-based thickness and the direct thickness (of the distance maps without sulcus/gyrus reconstruction) are combined by using the minimum. '] + '' + 'PBT simple function do not refine the given map and just estimate the Euclidean distance function on the given map.' + '' + 'Experimental development parameter - do not change! ' + '' +}; + +spmamap = cfg_menu; +spmamap.tag = 'spmAMAP'; +spmamap.name = 'Replace SPM by AMAP segmentation (experimental)'; +spmamap.labels = {'Yes','No'}; +spmamap.values = {1,0}; +spmamap.val = {0}; +spmamap.hidden = expert<1; +spmamap.help = { + 'Replace SPM segmentation by AMAP segmentation for acceptable tissue contrast between CSF, GM, and WM (e.g. T1). ' + 'The AMAP segmentation support partial volume effects that are helpful for thickness estimation and surface reconstruction. ' + 'Where the SPM segmentation often lacks in correct representation of fine structure such as gyral crones in normal high-resolution data. ' +}; + +pbtres = cfg_entry; +pbtres.tag = 'pbtres'; +pbtres.name = 'Voxel size for thickness estimation'; +pbtres.strtype = 'r'; +pbtres.num = [1 1]; +pbtres.def = @(val)cat_get_defaults('extopts.pbtres', val{:}); +pbtres.help = { + 'Internal isotropic resolution for thickness estimation in mm.' + '' +}; + +% replaced by general myelination function +%{ +pbtlas = cfg_menu; +pbtlas.tag = 'pbtlas'; +pbtlas.name = 'Use correction for cortical myelination'; +pbtlas.labels = {'No','Yes'}; +pbtlas.values = {0 1}; +pbtlas.def = @(val)cat_get_defaults('extopts.pbtlas', val{:}); +pbtlas.help = { + 'Apply correction for cortical myelination by local intensity adaptation to improve the description of the GM/WM boundary (added in CAT12.7).' + 'Experimental parameter, not yet working properly!' + '' +}; +%} + +% currently only for developer and experts ... check hidden field +% ############################################################### +SRP = cfg_menu; +SRP.tag = 'SRP'; +SRP.name = 'Surface reconstruction pipeline'; +if ~expert + SRP.labels = {... + 'CS1 (legacy)',... + 'CS2 (classic)',... + 'CS4 (sulcus & gyrus reconstruction; IN DEVELOPMENT)',... + }; + SRP.values = {11 22 42}; +elseif expert >= 1 + SRP.labels = {... + 'CS1 (11; legacy)',... + 'CS2 (22; classic)',... + 'CS2 with CS41+ gyrus reconstruction (24)',... + 'CS4 c-function full resolution (40; IN DEVELOPMENT)',... + 'CS4 sulcus+gyrus reconstuction A (41; IN DEVELOPMENT)',... + 'CS4 sulcus+gyrus reconstuction B (42; IN DEVELOPMENT)',... + }; + SRP.values = {11 22 24 40 41 42}; +elseif expert > 1 + SRP.labels = {... + 'CS1 without SIC (10)',... + 'CS1 with SIC without optimization (11)',... + 'CS1 with SIC with optimization (12)',... + ... + 'CS2 without SIC (20)',... + 'CS2 with SIC without optimization (21)',... + 'CS2 with SIC with optimization (22)',... + 'CS2 with SIC with optimization with CS41+ gyrus recon. (24; IN DEVELOPMENT)',... + ... + 'CS4 c-function full resolution (40; IN DEVELOPMENT)',... + 'CS4 sulcus+gyrus reconstuction A (41; IN DEVELOPMENT)',... + 'CS4 sulcus+gyrus reconstuction B (42; IN DEVELOPMENT)',... + 'CS4 sulcus+gyrus reconstuction B no opt. (43; IN DEVELOPMENT)',... + }; + SRP.values = {10 11 12 20 21 22 24 40 41 42 43}; +end +SRP.help = { + 'CAT uses the projection-based thickness approach (PBT; Dahnke et al., 2012) to reconstruct the central surface. ' + '' + 'With CAT12.8, we extensively revised the surface reconstruction pipeline (SRP), resulting in a new reconstruction scheme (CS2) that supports better control of the mesh resolution and runtime. ' + '' + ['With CAT12.10, we added a new pipeline (CS4) with a gyrus reconstruction scheme in atrophic cases and a new topology correction. ' ... + 'The gyrus reconstruction works similar as the sulcus reconstruction and helps in cases where the CSF describe the cortex better than the WM does. '] + '' + ['All pipelines provide high-precision reconstruction of the central surface and estimation of cortical thickness, which allows estimation of the cortical layer by transforming the surface points along the surface normals. ' ... + 'In particular, this allows the estimation of white and pial surfaces by addition/subtraction of half thickness. ' ... + 'Because the surface normals are modelled quite simply, the interface suffers locally from self-intersections, especially in highly convoluted regions with high GM but low CSF/WM fractions (i.e. in young subjects). ' ... + 'Although these overlaps are usually not a problem in structural analyses, self-intersections are still suboptimal and may cause issues for mapping 3D information onto the surface. ' ... + 'We have therefore developed a fast self-intersection correction (SIC) to provide accurate inner and outer surfaces. ' ... + 'The SIC reduces SIs below 1% of the total area, which are also almost invisible and can be neglected. '] + '' +}; +SRP.def = @(val)cat_get_defaults('extopts.SRP', val{:}); +SRP.hidden = expert < 1; + + +% Control surface mesh resolution by different pipelines. +% Major problem is that MATLAB sometimes fatally crashes in the SPM/MATLAB +% mesh reduction function. Hence, volumetric resolution is used to control +% the resolution of the created isosurfaces. However, topology correction +% used a normalized mesh with oversampling the insula. +reduce_mesh = cfg_menu; +reduce_mesh.tag = 'reduce_mesh'; +reduce_mesh.name = 'Reduce Mesh'; +if expert == 1 + reduce_mesh.labels = { ... + 'No reduction, PBT resolution (0)',... + 'No reduction, optimal resolution (1)',... + 'No reduction, internal resolution (2)',... + 'SPM approach (5)',... + 'MATLAB approach (6)' + }; + reduce_mesh.values = {0 1 2 3 5 4 6}; +elseif expert > 1 + reduce_mesh.labels = { ... + 'No reduction, PBT resolution (0)',... + 'No reduction, optimal resolution (1)',... + 'No reduction, internal resolution (2)',... + 'SPM approach init (3)',... + 'SPM approach full (5)',... + 'MATLAB approach init (4)',... + 'MATLAB approach full (6)' + }; + reduce_mesh.values = {0 1 2 3 5 4 6}; +end +reduce_mesh.def = @(val)cat_get_defaults('extopts.reduce_mesh', val{:}); +reduce_mesh.hidden = expert<2; +reduce_mesh.help = { + ['Limitation of the surface resolution is essential for fast processing, accurate and equally distributed meshes. ' ... + 'Mesh resolution depends in general on the voxel resolution used for surface creation and can be modified afterwards by refinement and reduction. ' ... + 'However, surface mesh reduction is not trivial and we observed fatal MATLAB errors (full uncatchable crash) and freezing of the following spherical registration on some computers. ' ... + 'This variable therefor controls multiple ways to handle mesh resolution in the surface creation process. '] + '' + ['The first setting (0) uses no reduction at all, creating the initial surface at the PBT resolution and also use no mesh reduction and is very slow. ' ... + 'In general, PBT is processed at 0.5 mm and surface creation result in about 1.200k faces with a quadratic increase of processing time. ' ... + 'However, this resolution is not necessary for nearly all analysis that often takes place at meshes with 164k (FreeSurfer) or 32k (HCP). '] + ... + ['Option (1) and (2) use volume reduction to created initial meshes on an optimal (1, depending on the final mesh resolution) or ' ... + 'the internal voxel-resolution (2, depending on your image resolution). ' ... + 'In both cases the maps are refined and further adapted to the PBT position map with a final mesh resolution of about 300k. ']; + '' + ['Surface-based reduction by SPM (3,5) or MATLAB (4,6) are used to optimize the initial surface, supporting a fast but still accurate topology correction. ' ... + 'Although this option support best quality, both the SPM and the MATLAB function can cause unreproducible MATLAB crash and are therefore not used yet! ' ... + 'After topology correction the resolution of the mesh is increased again and adapted for PBT position map. ' ... + 'In option 3 and 4, a supersampling with following reduction is used to obtain an optimal equally distributed sampling. ' ... + 'However, some systems showed problems in the spherical registration (freezing) that seamed to depend on these severe modifications of the mesh. ' ... + 'Hence, option (1) and (2) only use a normal refinement without supersampling.'] + '' + 'These settings are still in development!' + '' +}; + + + +% Expert parameter to control the number of mesh elements and processing +% time. 200k surfaces support good quality in relation to processing time, +% because surface reconstruction times are dominated by the registration +% that depends on the mesh resolution of the individual and template brain. +% A fast version with 100k was tested but showed different problems and is +% relatively slow (70% of the default) and at the end too risky for the low benefit. +% The parameter is the square of the refinement distance but for surface +% creation by the volume-resolution, a general limit of 1.5 mm exist, where +% lower resolution (e.g. 2 mm) can cause problems in thin structures. +vdist = cfg_menu; +vdist.tag = 'vdist'; +vdist.name = 'Mesh resolution'; +vdist.labels = {'optimal (2)','fine (1)','extra fine (0.5)'}; +vdist.values = {2 1 0.5}; +vdist.def = @(val)cat_get_defaults('extopts.vdist', val{:}); +vdist.hidden = expert<1 | (spmseg & expert<2); +vdist.help = { + ['Higher mesh resolution may support independent measurements but also increase the chance of self-intersections. ' ... + 'For each level, the mesh resolution (number of elements) is doubled and accuracy is increased slightly (by the square root). ' ... + 'The depends in addition on the ""reduce mesh"" parameter. '] + ['The mesh resolution is defined by an absolute resolution (e.g. 1 point per 1 mm) and smaller surfaces have therefore a smaller number of total mesh elements. ' ... + ''] + '' + ' Setting distance limit between vertices reconres (CS4) number faces ' + ' ------------------------------------------------------------------------------' + ' optimal: 1.41 mm 1.0 mm ~200k' + ' fine: 1.00 mm 0.7 mm ~400k' + ' extra fine: 0.71 mm 0.5 mm ~800k' + '' + 'Experimental parameter that only works for ""SRP>=20"" (CAT12.8, 202003)!' + '' +}; + +%------------------------------------------------------------------------ +% special expert and developer options +%------------------------------------------------------------------------ + +lazy = cfg_menu; +lazy.tag = 'lazy'; +lazy.name = 'Lazy processing'; +lazy.labels = {'Yes - check only output','Yes - check parameter and output','No'}; +lazy.values = {2,1,0}; +lazy.val = {0}; +lazy.help = { + 'Do not process data if the result already exists (and were created with the same parameters). ' +}; + +experimental = cfg_menu; +experimental.tag = 'experimental'; +experimental.name = 'Use experimental code'; +experimental.labels = {'No','Yes'}; +experimental.values = {0 1}; +experimental.def = @(val)cat_get_defaults('extopts.experimental', val{:}); +experimental.hidden = expert<2; +experimental.help = { + 'Use experimental code and functions.' + '' + 'WARNING: This parameter is only for developer and will call functions that are not safe and may change in future versions!' + '' +}; + +ignoreErrors = cfg_menu; +ignoreErrors.tag = 'ignoreErrors'; +ignoreErrors.name = 'Error handling'; +ignoreErrors.help = { + ['Try to catch preprocessing errors and continue with the next data set or ignore all warnings (e.g., bad intensities) ' ... + 'and use an experimental pipeline which is still in development. ' ... + 'In case of errors, CAT continues with the next subject if this option is enabled. ' ... + 'If the experimental option with backup functions is selected and warnings occur, CAT will try to use backup routines ' ... + 'and skip some processing steps which require good T1 contrasts (e.g., LAS). ' ... + 'If you want to avoid processing of critical data and ensure that only the main pipeline is used ' ... + 'then select the option ""Ignore errors (continue with the next subject)"". ' ... + 'It is strongly recommended to check for preprocessing problems, especially with non-T1 contrasts. '] +}; +if expert + % The case 2 is trying to run all function and then catch errors but it + % is maybe not really clear at what point it crash and what state the + % variables have. To test the backup pipeline directly use value 3. In + % low contrast cases it is maybe better to avoid the AMAP completely (4). + % Although, there is a routine to identify problematic AMAP cases this is + % quite new and may not working. + ignoreErrors.labels = {'Interrupt on errors (0)','Ignore errors (continue with the next subject, 1)','Ignore errors (use backup functions - IN DEVELOPMENT, 2)',... + 'Ignore errors (always use backup functions, 3)','Ignore errors (always use backup functions without AMAP, 4)'}; + ignoreErrors.values = {0 1 2 3 4}; + ignoreErrors.help = [ignoreErrors.help {'The last two options were designed to test the backup function with/without AMAP (experimental!)'}]; +else + ignoreErrors.labels = {'Interrupt on errors','Ignore errors (continue with the next subject)','Ignore errors (use backup functions - IN DEVELOPMENT)'}; + ignoreErrors.values = {0 1 2}; +end +ignoreErrors.def = @(val)cat_get_defaults('extopts.ignoreErrors', val{:}); + + +verb = cfg_menu; +verb.tag = 'verb'; +verb.name = 'Verbose processing level'; +verb.labels = {'none','default','details','debug'}; +verb.values = {0 1 2 3}; +verb.def = @(val)cat_get_defaults('extopts.verb', val{:}); +verb.help = { + 'Verbose processing.' +}; + + +print = cfg_menu; +print.tag = 'print'; +print.name = 'Create CAT report'; +print.labels = {'No','Yes (volume only)','Yes (volume and surfaces)'}; +print.values = {0 1 2}; +print.def = @(val)cat_get_defaults('extopts.print', val{:}); +print.help = { + 'Create final CAT report that requires Java.' +}; + + +%--------------------------------------------------------------------- +% Resolution +%--------------------------------------------------------------------- + +resnative = cfg_branch; +resnative.tag = 'native'; +resnative.name = 'Native resolution '; +resnative.help = { + 'Preprocessing with native resolution.' + '' + 'Examples:' + ' native resolution internal resolution ' + ' 0.95 0.95 1.05 > 0.95 0.95 1.05' + ' 0.45 0.45 1.70 > 0.45 0.45 1.70' + ' 2.00 2.00 2.00 > 2.00 2.00 2.00' + '' + }; + +resbest = cfg_entry; +resbest.tag = 'best'; +resbest.name = 'Best native resolution'; +resbest.def = @(val)cat_get_defaults('extopts.resval', val{:}); +resbest.num = [1 2]; +resbest.help = { + 'Preprocessing with the best (minimal) voxel dimension of the native image. The first parameters defines the lowest spatial resolution for every dimension, while the second defines a tolerance range to avoid tiny interpolations for almost correct resolutions. ' + '' + 'Examples:' + ' Parameters native resolution internal resolution' + ' [1.00 0.10] 0.95 1.05 1.25 > 0.95 1.05 1.00' + ' [1.00 0.10] 0.95 1.05 1.05 > 0.95 1.05 1.05' + ' [1.00 0.20] 0.45 0.45 1.50 > 0.45 0.45 1.00' + ' [0.75 0.20] 0.45 0.45 1.50 > 0.45 0.45 0.75' + ' [0.75 0.00] 0.45 0.45 0.80 > 0.45 0.45 0.80' + '' + }; + +resfixed = cfg_entry; +resfixed.tag = 'fixed'; +resfixed.name = 'Fixed resolution'; +resfixed.val = {[1.0 0.1]}; +resfixed.num = [1 2]; +resfixed.help = { + 'This option sets an isotropic voxel size that is controlled by the first parameter, whereas the second parameter defines a tolerance range to avoid tiny interpolations for almost correct resolutions. The fixed resolution option can also be used to improve preprocessing stability and speed of high resolution data, for instance protocols with high in-plane resolution and large slice thickness (e.g. 0.5x0.5x1.5 mm) and atypical spatial noise pattern. ' + '' + 'Examples: ' + ' Parameters native resolution internal resolution' + ' [1.00 0.10] 0.45 0.45 1.70 > 1.00 1.00 1.00' + ' [1.00 0.10] 0.95 1.05 1.25 > 0.95 1.05 1.00' + ' [1.00 0.02] 0.95 1.05 1.25 > 1.00 1.00 1.00' + ' [0.75 0.10] 0.75 0.95 1.25 > 0.75 0.75 0.75' + '' + }; + +resopt = cfg_entry; +resopt.tag = 'optimal'; +resopt.name = 'Optimal resolution'; +resopt.def = @(val)cat_get_defaults('extopts.resval', val{:}); +resopt.num = [1 2]; +resopt.help = { + 'Preprocessing with an ""optimal"" voxel dimension that utilize the median and the volume of the voxel size for special handling of anisotropic images. In many cases, atypically high slice-resolution (e.g. 0.5 mm for 1.5 Tesla) comes along with higher slice-thickness and increased image interferences. Our tests showed that a simple interpolation to the best voxel resolution not only resulted in much longer calculation times but also in a poor segmentation (and surface reconstruction) compared to the fixed option with e.g. 1 mm. Hence, this option tries to incorporate the voxel volume and its anisotropy to balance the internal resolution. E.g., an image with 0.5x0.5x1.5 mm will resampled at a resolution of 0.9x0.9x0.9 mm. ' + 'The first parameters defines the lowest spatial resolution, while the second defines a tolerance range to avoid tiny interpolations for almost correct resolutions. ' + '' + 'Examples:' + ' Parameters native resolution internal resolution' + ' [1.00 0.10] 0.95 1.05 1.25 > 0.95 1.05 1.00' + ' [1.00 0.30] 0.95 1.05 1.25 > 0.95 1.05 1.25' + ' [1.00 0.10] 0.80 0.80 1.00 > 0.80 0.80 1.00' + ' [1.00 0.10] 0.50 0.50 2.00 > 1.00 1.00 1.00' + ' [1.00 0.10] 0.50 0.50 1.50 > 0.90 0.90 0.90' + ' [1.00 0.10] 0.80 1.00 1.00 > 1.00 1.00 1.00' + ' [1.00 0.30] 0.80 1.00 1.00 > 0.80 1.00 1.00' + '' + }; + +restype = cfg_choice; +restype.tag = 'restypes'; +restype.name = 'Internal resampling for preprocessing'; +switch cat_get_defaults('extopts.restype') + case 'native', restype.val = {resnative}; + case 'best', restype.val = {resbest}; + case 'fixed', restype.val = {resfixed}; + case 'optimal', restype.val = {resopt}; +end + +if ~expert + restype = cfg_menu; + restype.tag = 'restypes'; + restype.name = 'Internal resampling for preprocessing'; + restype.labels = { + 'Optimal' + 'Fixed 1.0 mm' + 'Fixed 0.8 mm' + 'Native' + }; + restype.values = {struct('optimal', cat_get_defaults('extopts.resval')) ... + struct('fixed', [1.0 0.1]) ... + struct('fixed', [0.8 0.1]) ... + struct('native', [])}; + restype.val = {struct(cat_get_defaults('extopts.restype'), cat_get_defaults('extopts.resval'))}; + + % add default value to selection if not yet included + found = 0; + for i=1:numel(restype.values) + if isfield(restype.values{i},cat_get_defaults('extopts.restype')) + if restype.values{i}.(cat_get_defaults('extopts.restype')) == cat_get_defaults('extopts.resval') + found = 1; + end + end + end + if ~found, restype.values{end+1} = restype.val{1}; end + + restype.help = { + 'The default ""optimal"" image resolution offers a good trade-off between optimal quality and preprocessing time and memory demands. This interpolation prefers an isotropic voxel size controlled by the median voxel size and a volume term that penalizes highly anisotropic voxels. Standard structural data with a voxel resolution around 1 mm or even data with high in-plane resolution and large slice thickness (e.g. 0.5x0.5x1.5 mm) will benefit from this setting. If you have higher native resolutions the highres option ""Fixed 0.8 mm"" will sometimes offer slightly better preprocessing quality with an increase of preprocessing time and memory demands. In case of even higher resolutions and high signal-to-noise ratio (e.g. for 7 T data) the ""native"" option will process the data on the original native resolution. ' + '' + }; +else + restype.values = {resopt resnative resbest resfixed}; + restype.help = { + 'The default ""optimal"" image resolution offers a good trade-off between optimal quality and preprocessing time and memory demands. This interpolation prefers an isotropic voxel size controlled by the median voxel size and a volume term that penalizes highly anisotropic voxels. Standard structural data with a voxel resolution around 1 mm or even data with high in-plane resolution and large slice thickness (e.g. 0.5x0.5x1.5 mm) will benefit from this setting. If you have higher native resolutions the highres option ""Fixed 0.8 mm"" will sometimes offer slightly better preprocessing quality with an increase of preprocessing time and memory demands. In case of even higher resolutions and high signal-to-noise ratio (e.g. for 7 T data) the ""native"" option will process the data on the original native resolution. ' + '' + }; +end + + + +%------------------------------------------------------------------------ +% AMAP MRF Filter (expert) +%------------------------------------------------------------------------ +mrf = cfg_menu; % +mrf.tag = 'mrf'; +mrf.name = 'Strength of MRF noise correction'; +mrf.labels = {'none','light','medium','strong','auto'}; +mrf.values = {0 0.1 0.2 0.3 1}; +mrf.def = @(val)cat_get_defaults('extopts.mrf', val{:}); +mrf.hidden = expert<2; +mrf.help = { + 'Strength of the MRF noise correction of the AMAP segmentation. ' + '' +}; + + +%------------------------------------------------------------------------ +% Cleanup +%------------------------------------------------------------------------ +cleanupstr = cfg_menu; +cleanupstr.tag = 'cleanupstr'; +cleanupstr.name = 'Strength of Final Clean Up'; +cleanupstr.def = @(val)cat_get_defaults('extopts.cleanupstr', val{:}); +if ~expert + cleanupstr.labels = {'none','light','medium','strong'}; + cleanupstr.values = {0 0.25 0.50 0.75}; + cleanupstr.help = { + 'Strength of tissue cleanup after AMAP segmentation. The cleanup removes remaining meninges and corrects for partial volume effects in some regions. If parts of brain tissue were missing then decrease the strength. If too many meninges are visible then increase the strength. ' + '' + }; +else + cleanupstr.labels = {'none (0)','light (0.25)','medium (0.50)','strong (0.75)','heavy (1.00)'}; + cleanupstr.values = {0 0.25 0.50 0.75 1.00}; + cleanupstr.help = { + 'Strength of tissue cleanup after AMAP segmentation. The cleanup removes remaining meninges and corrects for partial volume effects in some regions. If parts of brain tissue were missing then decrease the strength. If too many meninges are visible then increase the strength. ' + '' + 'The strength changes multiple internal parameters: ' + ' 1) Size of the correction area' + ' 2) Smoothing parameters to control the opening processes to remove thin structures ' + '' + }; +end +if expert==2 + cleanupstr.labels = [cleanupstr.labels 'SPM (2.00)']; + cleanupstr.values = [cleanupstr.values 2.00]; +end + + +%------------------------------------------------------------------------ +% Skull-stripping +%------------------------------------------------------------------------ +gcutstr = cfg_menu; +gcutstr.tag = 'gcutstr'; +gcutstr.name = 'Skull-Stripping'; +gcutstr.def = @(val)cat_get_defaults('extopts.gcutstr', val{:}); +gcutstr.help = { + 'Method of initial skull-stripping before AMAP segmentation. The SPM approach works quite stable for the majority of data. However, in some rare cases parts of GM (i.e. in frontal lobe) might be cut. If this happens the GCUT approach is a good alternative. GCUT is a graph-cut/region-growing approach starting from the WM area. ' + 'APRG (adaptive probability region-growing) is a new method that refines the probability maps of the SPM approach by region-growing techniques of the gcut approach with a final surface-based optimization strategy. This is currently the method with the most accurate and reliable results. ' + 'If you use already skull-stripped data you can turn off skull-stripping although this is automatically detected in most cases. ' + 'Please note that the choice of the skull-stripping method will also influence the estimation of TIV, because the methods mainly differ in the handling of the outer CSF around the cortical surface. ' + '' +}; +if ~expert + gcutstr.labels = {'none (already skull-stripped)' 'SPM approach' 'GCUT approach' 'APRG approach' 'APRG approach (force skull-stripping)' }; + gcutstr.values = {-1 0 0.50 2 20}; +else + gcutstr.labels = {'none (post-mortem CSF~BG) (-2)','none (already skull-stripped) (-1)', ... + 'SPM approach (0)','GCUT medium (0.50)','APRG approach (2)',... + 'APRG approach V2 (2.5)','APRG approach V2 wider (2.1)','APRG approach V2 tighter (2.9)', ... + 'SPM approach (force skull-stripping, 0)', 'GCUT approach (force skull-stripping, 10.5)', 'APRG approach (force skull-stripping, 12)'}; + gcutstr.values = {-2 -1 , 0 0.50 2 , 2.5 2.1 2.9 , 10 10.5 12}; +end +gcutstr.hidden = expert<1; + + +%------------------------------------------------------------------------ +% Noise correction (expert) +%------------------------------------------------------------------------ + +% expert only +NCstr = cfg_menu; +NCstr.tag = 'NCstr'; +NCstr.name = 'Strength of Noise Corrections'; +if expert + NCstr.help = { + 'Strength of the spatial adaptive (sub-resolution) non local means (SANLM) noise correction. Please note that the filter strength is automatically estimated. Change this parameter only for specific conditions. Typical values are: none (0), classic (1), light (2), medium (3|-inf), and strong (4). The ""classic"" option use the ordinal SANLM filter without further adaptations. The ""light"" option applies half of the filter strength of the adaptive ""medium"" cases, whereas the ""strong"" option uses the full filter strength, force sub-resolution filtering and applies an additional iteration. Sub-resolution filtering is only used in case of high image resolution below 0.8 mm or in case of the ""strong"" option. ' + '' + }; + NCstr.labels = {'none (0)','classic (1)','light (2)','medium (3|-inf)','strong (4)'}; + NCstr.values = {0 1 2 -inf 4}; +else + NCstr.labels = {'none','light','medium','strong'}; + NCstr.values = {0 2 -inf 4}; + NCstr.help = { + 'Strength of the (sub-resolution) spatial adaptive non local means (SANLM) noise correction. Please note that the filter strength is automatically estimated. Change this parameter only for specific conditions. The ""light"" option applies only half of the filter strength of the adaptive ""medium"" cases and no sub-resolution filtering. The ""medium"" case use the full adaptive filter strength and sub-resolution filtering in case of high image resolution below 0.8 mm. The ""strong"" option uses the full filter strength without adaptation, forces the sub-resolution filtering and applies an additional iteration. All cases used an anatomical depending filter strength adaptation, i.e. full (adaptive) filter strength for 1 mm data and no filtering for 2.5 mm data. ' + '' + }; +end +NCstr.def = @(val)cat_get_defaults('extopts.NCstr', val{:}); + + +%------------------------------------------------------------------------ +% Blood Vessel Correction (expert) +%------------------------------------------------------------------------ + +BVCstr = cfg_menu; +BVCstr.tag = 'BVCstr'; +BVCstr.name = 'Strength of Blood Vessel Corrections'; +BVCstr.labels = {'never (0)','auto (0.50)','allways (1.00)','classic (1.50)'}; +BVCstr.values = {0 0.50 1.00 1.50}; +BVCstr.def = @(val)cat_get_defaults('extopts.BVCstr', val{:}); +BVCstr.hidden = expert<1; +BVCstr.help = { + 'Strength of the Blood Vessel Correction (BVC) that was extended 2023 to reduce problems with WM-like blood vessels. ' + '' +}; + + +%------------------------------------------------------------------------ +% Local Adaptive Segmentation +%------------------------------------------------------------------------ +LASstr = cfg_menu; +LASstr.tag = 'LASstr'; +LASstr.name = 'Strength of Local Adaptive Segmentation'; +if ~expert + LASstr.labels = {'none','light','medium','strong'}; + LASstr.values = {0 0.25 0.50 0.75}; +elseif expert == 2 + LASstr.labels = {'none (0)','ultralight (eps)','light (0.25)','medium (0.50)','strong (0.75)','heavy (1.00)', ... + 'simple-ultraligh (1.01)', 'simple-light (1.5)','simple-heavy (2.0)'}; + LASstr.values = {0 eps 0.25 0.50 0.75 1.00 1.01 1.50 2.0}; +else + LASstr.labels = {'none (0)','ultralight (eps)','light (0.25)','medium (0.50)','strong (0.75)','heavy (1.00)'}; + LASstr.values = {0 eps 0.25 0.50 0.75 1.00}; +end +LASstr.def = @(val)cat_get_defaults('extopts.LASstr', val{:}); +LASstr.help = { + 'Additionally to WM-inhomogeneities, GM intensity can vary across different regions such as the motor cortex, the basal ganglia, or the occipital lobe. These changes have an anatomical background (e.g. iron content, myelinization), but are dependent on the MR-protocol and often lead to underestimation of GM at higher intensities and overestimation of CSF at lower intensities. Therefore, a local intensity transformation of all tissue classes is used to reduce these effects in the image. This local adaptive segmentation (LAS) is applied before the final AMAP segmentation.' + '' +}; +if expert == 2 + LASstr.help = [LASstr.help(1:end-1); { + 'The developer mode also allows selection of the simplified LAS version with less additional corrections of the classification that is also used as backup function of the default LAS function. ' + '' + }]; +end +LASstr.hidden = expert<1; + + +LASmyostr = cfg_menu; +LASmyostr.tag = 'LASmyostr'; +LASmyostr.name = 'Strength of LAS myelin correction (expert)'; +if ~expert + LASmyostr.labels = {'no','yes'}; + LASmyostr.values = {0 0.50}; + LASmyostr.help = { + 'IN DEVELOPMENT' + 'Add more local myelination correction of LAS based on the assumption of an equally thick cortex. ' + 'Please, note that because myelination increases with age this will interact with aging and atrophy in degenerative diseases. ' + '' + }; +else + LASmyostr.labels = {'none (0)','ultralight (eps)','light (0.25)','medium (0.50)','strong (0.75)','heavy (1.00)'}; + LASmyostr.values = {0 eps 0.25 0.50 0.75 1.00}; + LASmyostr.help = { + 'IN DEVELOPMENT' + 'Add more local myelination correction of LAS based on the assumption of an equally thick cortex. ' + 'Please, note that because myelination increases with age this will interact with aging and atrophy in degenerative diseases. ' + '' + ' eps - ultralight: only correct SPM segmentation (no effect) ' + ' .25 - light: correct SPM segmentation + bias correction (no effect)' + ' .50 - medium: correct SPM segmentation + bias correction + light image correction' + ' .75 - strong: correct SPM segmentation + bias correction + medium image correction' + ' 1.0 - heavy: correct SPM segmentation + bias correction + strong image correction' + '' + }; +end +LASmyostr.val = {0}; +% RD202104: +% Ideally, the myelination should be used to classify the L4 (VanEssen) but +% for a sample resolution of about 1 mm the thickness estimation becomes +% more unstable (depending on the metric). +% RD202501: +% Works now better but it overcorrect atrophic cases, whereas others +% (Buchert) could still be improved further. +LASmyostr.hidden = expert<1; + + +%------------------------------------------------------------------------ +% WM Hyperintensities (expert) +%------------------------------------------------------------------------ +wmhc = cfg_menu; +wmhc.tag = 'WMHC'; +wmhc.name = 'WM Hyperintensity Correction (WMHCs)'; +wmhc.def = @(val)cat_get_defaults('extopts.WMHC', val{:}); +wmhc.help = { + 'WARNING: Please note that the detection of WM hyperintensies is still under development and does not have the same accuracy as approaches that additionally consider FLAIR images (e.g. Lesion Segmentation Toolbox)! ' + 'In aging or (neurodegenerative) diseases WM intensity can be reduced locally in T1 or increased in T2/PD images. These so-called WM hyperintensies (WMHs) can lead to preprocessing errors. Large GM areas next to the ventricle can cause normalization problems. Therefore, a temporary correction for normalization is useful if WMHs are expected. CAT allows different ways to handle WMHs: ' + '' + ' 0) No Correction (handled as GM). ' + ' 1) Temporary (internal) correction as WM for spatial normalization and estimation of cortical thickness. ' + ' 2) Permanent correction to WM. ' +}; +if expert + wmhc.help = [wmhc.help; { + ' 3) Handling as separate class. ' + '' + }]; + wmhc.values = {0 1 2 3}; + wmhc.labels = { ... + 'no correction (0)' ... + 'set WMH temporary as WM (1)' ... + 'set WMH as WM (2)' ... + 'set WMH as own class (3)' ... + }; +else + %wmhc.help = [wmhc.help; { + % ' 3) Handling as separate class. ' + % '' + %}]; + wmhc.values = {0 1 2}; ... 3 + wmhc.labels = { ... + 'no WMH correction' ... + 'set WMH temporary as WM' ... + 'set WMH as WM' ... + ... 'set WMH as own class' ... + }; +end +wmhc.hidden = expert<1; + +% deactivated 20180714 because the WMHC in cat_vol_partvol did not support +% user modification yet +%{ +WMHCstr = cfg_menu; +WMHCstr.tag = 'WMHCstr'; +WMHCstr.name = 'Strength of WMH Correction'; +WMHCstr.labels = {'none (0)','light (eps)','medium (0.50)','strong (1.00)'}; +WMHCstr.values = {0 eps 0.50 1.00}; +WMHCstr.def = @(val)cat_get_defaults('extopts.WMHCstr', val{:}); +WMHCstr.help = { + 'Strength of the modification of the WM Hyperintensity Correction (WMHC).' + '' +}; +%} + +%------------------------------------------------------------------------ +% stroke lesion handling (expert) +%------------------------------------------------------------------------ +slc = cfg_menu; +slc.tag = 'SLC'; +slc.name = 'Stroke Lesion Correction (SLC) - in development'; +slc.def = @(val)cat_get_defaults('extopts.SLC', val{:}); +slc.help = { + 'WARNING: Please note that the handling of stroke lesion is still under development. ' + 'Without further correction, stroke lesions will be handled by their most probable tissue class, i.e. typically as CSF or GM. Because the spatial registration tries to normalize these regions, the normalization of large regions will lead to strong improper deformations. ' + 'To avoid poor deformations, we created a work-around by manually defined lesion maps. The ""Manual image (lesion) masking"" tool can be used to set the image intensity to zeros to avoid normalization of stroke lesions. ' + '' + ' 0) No Correction. ' + ' 1) Correction of manually defined regions that were set to zeros. ' +}; +if expert>1 + slc.values = {0 1 2}; + slc.labels = { ... + 'no SL handling (0)' ... + 'manual SL handling (1)' ... + 'manual & automatic handling (2)' ... + }; + slc.help = [slc.help;{ + ' 2) Correction automatic detected regions. ' + ''}]; +else + slc.values = {0 1}; + slc.labels = { ... + 'no SL handling' ... + 'manual SL handling' ... + }; + slc.help = [slc.help;{ + ''}]; +end + +%------------------------------------------------------------------------ +% Currently there are to much different strategies and this parameter needs +% revision. There a three basic APP functions that each include an initial +% rough and a following fine method. The first is the SPM approach that +% is a simple iterative call of the Unified segmentation with following +% maximum-based bias correction. It is relatively stable but slow and can be +% combined with the other APP routines. The second one is the classical +% APP approach with default and fine processing (1070), followed by further +% developed version that should be more correct with monitor variables and +% T2/PD compatibility but finally worse results. +% +% So we need more test to find out which strategies will survive to support +% an alternative if the standard failed with a fast standard and slow but +% more powerful other routines. Hence APP1070 (init) or it successor +% should be the standard. The SPM routines are a good alternative due to +% their different concept. +%------------------------------------------------------------------------ + + +app = cfg_menu; +app.tag = 'APP'; +app.name = 'Affine Preprocessing (APP)'; +% short help text +app.help = { ... + 'Affine registration and SPM preprocessing can fail or be biased in some subjects with deviating anatomy (e.g. other species/neonates) or in images with strong signal inhomogeneities (e.g. uncorrected inhomogeneities as locally underestimated thickness visible as ""blue spots"" in the CAT report), or untypical intensities (e.g. synthetic images). An initial bias correction can help to reduce such problems (similar to ADNI N3 bias correction). Recommended are the ""default"" and ""SPM"" option.' + '' + ' none - no additional bias correction (0)' + ' default - default APP bias correction (1070)' + ' SPM - iterative SPM bias correction (effective but slow, 1)' + '' + }; +app.def = @(val)cat_get_defaults('extopts.APP', val{:}); +app.labels = {'none','default','SPM'}; +app.values = {0 1070 1}; +app.hidden = expert<1; + +%------------------------------------------------------------------------ + +setCOM = cfg_menu; +setCOM.tag = 'setCOM'; +setCOM.name = 'Use center-of-mass to set origin'; +setCOM.help = { ... + '' + 'Use center-of-mass to roughly correct for differences in the position between image and template. This will internally correct the origin. ' + '' + 'If affine registration fails you can try to disable this option and/or set the origin manually. ' + }; +setCOM.def = @(val) cat_get_defaults('extopts.setCOM', val{:}); +if expert + % RD202101: I am not sure how useful these options are and miss currently some good test cases. + % In most cases the results are quite similar but forcing TPM registration seems to have the largest effect. + % I would rename the GUI entry to 'Affine Registration Strategy' but this would be more confusion now. + setCOM.labels = { + 'No (0)', ... + 'Yes (1)', ... + 'Yes (no TPM registration, 10)', ... 10 - automatic works quite well + 'Yes (force TPM registration, 11)', ... 11 - head-bias in children + 'Yes (TPM registration without head masking, 120)', ... 120 - probably only slower + ... 'Yes (test TPM, use dilated head mask)', ... only for new pipeline + }; + setCOM.values = {0 1 10 11 120}; % the value codes the operation but it has to be a string to support a leading 0 ... we do not need that yet + setCOM.help = [setCOM.help; { + '' + ['CAT first applies a classical (stepwise) affine registration of the optimized T1 image to a single T1 image via ""spm_affreg"", followed by another (step-wise) TPM-based registration via ""spm_maff8"" (labeled as ""SPM preprocessing 1 (estimate 1)""). ' ... + 'Although the TPM-based registration is more advanced and pretty good in most cases, we observed severe problems in younger/older subjects, where the correct initial affine registration was replaced by an inaccurate solution that was often biased by the head. ' ... + 'Thus, we have implemented different tests to detect and ignore possible incorrect results that can controlled here directly (no/force TPM registration). ' ] + '' + 'In addition, we observed that a head mask often improves and mostly fasten SPM preprocessing that is used by default but can be switch off here (TPM registration without head masking). ' + ''}]; +else + setCOM.labels = {'No','Yes'}; + setCOM.values = {0 1}; +end + +%------------------------------------------------------------------------ + + +% RD202101: This works quite well and support good control by users in single cases or groups. +% A menu is maybe to rough +if expert + affmod = cfg_entry; + affmod.strtype = 'r'; + affmod.val = {}; + affmod.num = [1,inf]; +else + affmod = cfg_menu; + affmod.labels = {'Decrease by 10%','Decrease by 5%','No Adaption','Increase by 5%','Increase by 10%'}; + affmod.values = { -10 , -5 , 0 , 5 , 10 }; +end +affmod.val = { 0 }; +affmod.tag = 'affmod'; +affmod.name = 'Modify Affine Scaling'; +affmod.help = { + ['If the affine registration is inaccurate the intial tissue classification of the ""Unified Segmentation will be not optimal. ' ... + 'Although multiple routines such as scull-stripping, cleanup, and non-linear registration catch a lot of problems some cases may still suffer (mostly visible as bad skull-stripping). ' ... + 'In problematic cases (eg. outlier in the covariance analysis) you can check the brain outline of the original image in the CAT report. ' ... + 'If it appears to be too small/large, you can adapt the scaling here. ' ... + 'If the outline is to small and runs within the brain (e.g. in children) and parts of are missing (blue regions in the label image in the CAT report) than increase this parameter. ' ... + 'If the outline is to large and runs some where beyond the brain (e.g. in elderly) and unremoved meninges are visible as GM than decrease this parameter. '] + '' + }; + % 'The correction can also help to adjust for too soft (descrease template size) or too hard skull-stripping (increase template size). '] +if expert + affmod.help = [affmod.help; { + ['Use one value for isotropic scaling, otherwise specify x y and z scaling: [Sx Sy Sz]. ' ... + 'Moreover, you can specify a final translation: [Tx Ty Tz], i.e. you have to enter a 1x6 matrix with 3 percentual values for the scaling and 3 mm values, e.g., [ 0 0 -10, 0 0 -1] to correct only the z-axis scaling and position. '] + '' + 'Use negative/positive values to indicate percentual reductions/increasements of the TPM, e.g., an 10% decrease/increase of the TPM size is defined by the value -10/10 that result in a scaling factor of (0.92/1.10). ' + '' + ''}]; +end +affmod.hidden = expert < 1; + +%------------------------------------------------------------------------ + +new_release = cfg_menu; +new_release.tag = 'new_release'; +new_release.name = 'New release functions'; +new_release.help = { ... + 'Use new rather then standard functions. ' + }; +new_release.val = {0}; +new_release.labels = {'No','Yes'}; +new_release.values = {0 1}; +new_release.hidden = expert<2; + +%------------------------------------------------------------------------ + +scale_cortex = cfg_entry; +scale_cortex.tag = 'scale_cortex'; +scale_cortex.name = 'Modify cortical surface creation'; +scale_cortex.strtype = 'r'; +scale_cortex.num = [1 1]; +if spmseg + scale_cortex.hidden = true; + scale_cortex.val{1} = 0.5; +else + scale_cortex.def = @(val)cat_get_defaults('extopts.scale_cortex', val{:}); +end +scale_cortex.help = { + 'Scale intensity values for cortex to start with initial surface that is closer to GM/WM border to prevent that gyri/sulci are glued if you still have glued gyri/sulci (mainly in the occ. lobe). You can try to decrease this value (start with 0.6). Please note that decreasing this parameter also increases the risk of an interrupted parahippocampal gyrus.' + '' +}; + +add_parahipp = cfg_entry; +add_parahipp.tag = 'add_parahipp'; +add_parahipp.name = 'Modify parahippocampal surface creation'; +add_parahipp.strtype = 'r'; +scale_cortex.num = [1 1]; +if spmseg + add_parahipp.hidden = true; + add_parahipp.val{1} = 0; +else + add_parahipp.def = @(val)cat_get_defaults('extopts.add_parahipp', val{:}); +end +add_parahipp.help = { + 'Increase values in the parahippocampal area to prevent large cuts in the parahippocampal gyrus (initial surface in this area will be closer to GM/CSF border if the parahippocampal gyrus is still cut. You can try to increase this value (start with 0.15).' + '' +}; + +close_parahipp = cfg_menu; +close_parahipp.tag = 'close_parahipp'; +close_parahipp.name = 'Initial morphological closing of parahippocampus'; +close_parahipp.labels = {'No','Yes'}; +close_parahipp.values = {0 1}; +if spmseg + close_parahipp.hidden = true; + close_parahipp.val{1} =0; +else + close_parahipp.def = @(val)cat_get_defaults('extopts.close_parahipp', val{:}); +end +close_parahipp.help = { + 'Apply initial morphological closing inside mask for parahippocampal gyrus to minimize the risk of large cuts of parahippocampal gyrus after topology correction. However, this may also lead to poorer quality of topology correction for other data and should be only used if large cuts in the parahippocampal areas occur.' + '' +}; + +%------------------------------------------------------------------------ +% special subbranches for experts and developers to cleanup the GUI +%------------------------------------------------------------------------ + +segmentation = cfg_branch; +segmentation.tag = 'segmentation'; +segmentation.name = 'Segmentation Options'; +segmentation.val = {restype,setCOM,app,affmod,NCstr,LASstr,LASmyostr,gcutstr,cleanupstr,BVCstr,wmhc,slc,mrf,WMHtpm,BVtpm,SLtpm}; % WMHCstr, +segmentation.hidden = expert<1; +segmentation.help = {'CAT12 parameter to control the tissue classification.';''}; + +spmsegmentation = cfg_branch; +spmsegmentation.tag = 'segmentation'; +spmsegmentation.name = 'Segmentation Options'; +spmsegmentation.val = {spmamap,WMHtpm,BVtpm,SLtpm}; % WMHCstr, +spmsegmentation.hidden = expert<1; +spmsegmentation.help = {'CAT12 parameter to control the tissue classification.';''}; + +admin = cfg_branch; +admin.tag = 'admin'; +admin.name = 'Administration Options'; +admin.val = {experimental new_release lazy ignoreErrors verb print}; +admin.hidden = expert<1; +admin.help = {'CAT12 parameter to control the behaviour of the preprocessing pipeline.';''}; + +%------------------------------------------------------------------------ + +surface = cfg_branch; +surface.tag = 'surface'; +surface.name = 'Surface Options'; +surface.val = {pbtres pbtver SRP vdist scale_cortex add_parahipp close_parahipp}; +surface.hidden = expert<1; +surface.help = {'CAT12 parameter to control the surface processing.';''}; + + +%------------------------------------------------------------------------ +% main extopts branch .. in order of their call in cat_main +%------------------------------------------------------------------------ + +extopts = cfg_branch; +extopts.tag = 'extopts'; +extopts.name = 'Extended options for CAT12 preprocessing'; +if ~spmseg + if expert % expert/developer options + extopts.val = {segmentation,registration,surface,admin}; + else + extopts.val = {restype,setCOM,app,affmod,LASstr,LASmyostr,gcutstr,wmhc,registration,vox,bb,SRP,ignoreErrors}; + end +else + % SPM based surface processing and thickness estimation + if expert + extopts.val = {spmsegmentation,registration,surface,admin}; + else + extopts.val = {vox,bb,registration,surface,admin}; % bb is hidden + end +end +extopts.help = {'Using the extended options you can adjust special parameters or the strength of different corrections (""0"" means no correction and ""0.5"" is the default value that works best for a large variety of data).'}; +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_vol_nanmean3.m",".m","935","23","function I=cat_vol_nanmean3(I,s,iterations) +% _________________________________________________________________________ +% smooth image with nans +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + if ~isa('I','single'), I = single(I); end; + if ~exist('s','var'), s=1; end + if ~exist('iterations','var'), iterations=1; end + for iteration=1:iterations + I2 = I; I3 = I; + for i=1+s:size(I,1)-s, I2(i,:,:) = cat_stat_nanmean(I3(i-s:i+s,:,:),1); end + for i=1+s:size(I,2)-s, I3(:,i,:) = cat_stat_nanmean(I2(:,i-s:i+s,:),2); end + for i=1+s:size(I,3)-s, I2(:,:,i) = cat_stat_nanmean(I3(:,:,i-s:i+s),3); end + I(isnan(I)) = I2(isnan(I)); + end +end ","MATLAB" +"Neurology","ChristianGaser/cat12","cat_surf_createCS4.m",".m","48895","957","function [Yth,S,P,res] = cat_surf_createCS4(V,V0,Ym,Yp0,Ya,YMF,Yb0,opt,job) +% ______________________________________________________________________ +% Surface creation and thickness estimation. +% +% [Yth,S,P] = cat_surf_createCS4(V,V0,Ym,Ya,YMF,Ypb0,opt,job) +% +% Yth .. thickness map +% S .. structure with surfaces, like the left hemisphere, that contains +% vertices, faces, GM thickness (th1) +% P .. name of surface files +% res .. intermediate and final surface creation information +% V .. spm_vol-structure of internally interpolated image +% V0 .. spm_vol-structure of original image +% Ym .. the (local) intensity, noise, and bias corrected T1 image +% Ya .. the atlas map with the ROIs for left and right hemispheres +% (this is generated with cat_vol_partvol) +% YMF .. a logical map with the area that has to be filled +% (this is generated with cat_vol_partvol) +% Ytemplate .. Shooting template to improve cerebellar surface +% reconstruction +% Yb .. modified mask from gcut +% +% opt.surf = {'lh','rh'[,'lc','rc']} - side +% +% Options set by cat_defaults.m +% .interpV = 0.5 - mm-resolution for thickness estimation +% +% Here we use the intensity normalized image Ym, rather than the Yp0 +% image, because it has more information about sulci that we need +% especially for asymmetrical sulci. +% Furthermore, all non-cortical regions and blood vessels are removed +% (for left and right surface). Blood vessels (with high contrast) can +% lead to strong errors in the topology correction. Higher resolution +% also helps to reduce artifacts. +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + %#ok<*AGROW,*STREMP,*ASGLU,*SFLD,*STFLD> + + % get both sides in the atlas map + NS = @(Ys,s) Ys==s | Ys==s+1; + if ~exist('opt','var'), opt = struct(); end % create variable if not exist + + % Turn off gifti data warning in gifti/subsref (line 45) + % Warning: A value of class ""int32"" was indexed with no subscripts specified. + % Currently the result of this operation is the indexed value itself, + % but in a future release, it will be an error. + warning('off','MATLAB:subscripting:noSubscriptsSpecified'); + cstime = clock; %#ok<*CLOCK> + + % test-variables that should be (partially) removed later + use_cat_vol_pbtsimple = 1; + skip_registration = isfield(opt,'surf') && isscalar(opt.surf); % skip spherical registration for quick tests + create_white_pial = 1; % uses only the quick WM and Pial surface estimation + + myelinCorrection = .5; % .25 - sight correction, 1 - maximum correction + setcut2zero = 0; % works but result in worse values as could be expected + + % surface output and evaluation parameter + res = struct('lh',struct(),'rh',struct()); + Yth = zeros(size(Yp0),'single'); % initialize WM/CSF thickness/width/depth maps + S = struct(); + + + % set defaults + % set debugging variable + dbs = dbstatus; debug = 1; for dbsi=1:numel(dbs), if strcmp(dbs(dbsi).name,mfilename); debug = 1; break; end; end + vx_vol = sqrt(sum(V.mat(1:3,1:3).^2)); % further interpolation based on internal resolution + def.verb = cat_get_defaults('extopts.expertgui'); % 0-none, 1-minimal, 2-default, 3-details, 4-debug + def.surf = {'lh','rh'}; % surface reconstruction setting with {'lh','rh','cb'} + % There is a new SPM approach spm_mesh_reduce that is maybe more robust. + % Higher resolution is at least required for animal preprocessing that is given by cat_main. + def.LAB = cat_get_defaults('extopts.LAB'); % brain regions + % RD20250306: Tfs has large issues currently with some corrected defects + def.useprior = ''; + def.thick_limit = 6; % 6mm upper limit for thickness (similar limit as used in Freesurfer) + def.foldingcorrection = 1; % tickness correction that is influence by folding + def.thick_measure = 0; % 0-PBT; 1-Tfs (Freesurfer method using mean(TnearIS,TnearOS)) ########## + def.fsavgDir = fullfile(fileparts(mfilename('fullpath')),'templates_surfaces'); + def.outputpp.native = 0; % output of Ypp map for cortical orientation in EEG/MEG + def.outputpp.warped = 0; + def.outputpp.dartel = 0; + def.vdist = 2; + + % options that rely on other options + opt = cat_io_updateStruct(def,opt); clear def; + opt.vol = any(~cellfun('isempty',strfind(opt.surf,'v'))); % only volume-based thickness estimation + opt.surf = cat_io_strrep(opt.surf,'v',''); % after definition of the 'vol' varialbe we simplify 'surf' + opt.interpV = max(0.1,min([opt.interpV,1.5])); % general limitation of the PBT resolution + switch opt.SRP + case 0 % pbtsimpleC, full resolution + use_cat_vol_pbtsimple = 0; + myelinCorrection = 0; + opt.reconres = .5; + case 1 % myelincorrection + use_cat_vol_pbtsimple = 1; + myelinCorrection = 0.3; + opt.reconres = .6; + case 2 % default + use_cat_vol_pbtsimple = 1; + myelinCorrection = 0; + opt.reconres = .6; + end + + + % apply the modified mask from gcut + % for non-gcut approaches or inverse weighting Yb0 only contains ones + Yp0 = Yp0 .* (Yb0>0.5); + Ym = Ym .* (Yb0>0.5); + + + % enlarge atlas definition + [~,I] = cat_vbdist(single(Ya>0)); Ya=Ya(I); clear I; + + + % improve PVE (important for SPM25) + % - correct MRF classification problems, i.e., realign GM voxels with + % very high/low raw intensities to WM/CSF (thin WM in BUSS01) + % - this might include blood vessels but these we have to handle anyway + % - this might be better after denoising but before segmentation + % is this done in case of AMAP? + % - in case of SPM 0.75 mm seems to help for MRF? or + % to run SPM without MRF + if opt.SRP > 0 + if 1 + % sharpening of raw image + Ym = Ym + (Ym - smooth3(Ym)) / 2; + %Ym(Yp0>2 & Yp0<3) = Ymx(Yp0>2 & Yp0<3); + %Ym(Yp0>1 & Yp0<2) = Ymx(Yp0>1 & Yp0<2); + end + + if cat_stat_nanmedian(Ym(round(Yp0(:))==1)) < cat_stat_nanmedian(Ym(round(Yp0(:))==3)) % T1w + Yp0 = max(Yp0, 3*(Yp0>1.9 & Ym*3>2.5 & Ym*3<3.5) + 2.5*(Yp0>1.9 & Ym*3>2.25 & Ym*3<3.5)); + elseif cat_stat_nanmedian(Ym(round(Yp0(:))==1)) > cat_stat_nanmedian(Ym(round(Yp0(:))==3)) % T2w + Yp0 = max(Yp0, 3*(Yp0>1.9 & Ym*3>2.5 & Ym*3<3.5) + 2.5*(Yp0>1.9 & Ym*3>2.25 & Ym*3<3.5)); + end + end + + + % simple filling + [Yp0f,Ymf] = fillVentricle(Yp0,Ym,Ya,YMF,vx_vol); clear Ym YMF; + + + % position balancing map + % - this map will be used later to optimise the position map to have + % equal object/non-objects parts to stabilise the reconstruction + % (ie. thickening thin and thinning thick structures) + Ypb = cat_vol_morph( Yp0f > 1.5 , 'ldc', 8 ) & cat_vol_morph( Yp0f < 2.5 , 'ldc', 8 ); + + + % prepare file and directory names + [P,pp0,mrifolder,surffolder,surfdir,ff] = setFileNames(V0,job,opt); + + + % main loop for each surface structure + for si = 1:numel(opt.surf) + + % prepare longitudinal case if required + useprior = setupprior(opt,surfdir,P,si); + + + %% reduce for object area + Ynocerebrum = ~(NS(Ya,opt.LAB.CB) | NS(Ya,opt.LAB.BV) | NS(Ya,opt.LAB.ON) | NS(Ya,opt.LAB.MB) | NS(Ya,opt.LAB.BS)); + switch opt.surf{si} + case {'lh'} + Ymfs = Ymf .* (Ya>0) .* Ynocerebrum .* (mod(Ya,2)==1); + Yp0fs = Yp0f .* (Ya>0) .* Ynocerebrum .* (mod(Ya,2)==1); + Yside = single(mod(Ya,2)==1); + case {'rh'} + Ymfs = Ymf .* (Ya>0) .* Ynocerebrum .* (mod(Ya,2)==0); + Yp0fs = Yp0f .* (Ya>0) .* Ynocerebrum .* (mod(Ya,2)==0); + Yside = single(mod(Ya,2)==0); + case {'cb'} + Ymfs = Ymf .* (Ya>0) .* NS(Ya,opt.LAB.CB); + Yp0fs = Yp0f .* (Ya>0) .* NS(Ya,opt.LAB.CB); + Yside = zeros(size(Yp0fs),'single'); % new full cerebellum reconstruction + end + % print something + if si==1, fprintf('\n'); end; fprintf('%s:\n',opt.surf{si}); + clear Ynocerebrum + + + % RD2025: mark cutting regions to avoid cortical modelling (i.e. to avoid/reduce thickness estimates) + Ycutregion = min(1,max(0,Yp0f - 2 + NS(Ya,opt.LAB.VT)) * 1 .* ... + smooth3( NS(Ya,opt.LAB.ON) | NS(Ya,opt.LAB.MB) | NS(Ya,opt.LAB.VT) | NS(Ya,opt.LAB.TH) | ~Yside )); + + + % removing background (smoothing to remove artifacts) + [Yp0fs,Ymfs,Ycutregion,Ypbs,BB] = cat_vol_resize({Yp0fs,Ymfs,Ycutregion,Ypb}, 'reduceBrain', vx_vol, 4, smooth3(Yp0fs)>1.5); + + % interpolation + imethod = 'cubic'; % cubic is be better in general but we have to consider interpolation artifacts + [Yp0fs,resI] = cat_vol_resize(max(1,Yp0fs),'interp',V,opt.interpV,imethod); % interpolate volume + Ymfs = cat_vol_resize(max(1,Ymfs),'interp',V,opt.interpV,imethod); % interpolate volume + Ypbs = cat_vol_resize(Ypbs,'interp',V,opt.interpV,imethod) > 0.5; + Ycutregion = cat_vol_resize(Ycutregion,'interp',V,opt.interpV,imethod); + Ycutregiond = cat_vol_smooth3X( cat_vol_morph(Ycutregion,'dd',1.5,opt.interpV), 4); % a smooth version to mix maps + + + % surface coordinate transformation matrix + [Vmfs,Smat] = createOutputFileStructures(V,V0,resI,BB,opt,pp0,mrifolder,ff,si); + + + %% thickness and position map estimation + stime = cat_io_cmd(sprintf(' Thickness estimation (%0.2f mm%s)',opt.interpV,native2unicode(179, 'latin1')),'g5'); stimet = stime; % fprintf('\n'); + if use_cat_vol_pbtsimple + if all(opt.interpV ~= vx_vol) + %% reduction of interpolation artifacts + % - remove (i) slight over/underestimation close to boundaries and + % (ii) larger voxel steps by utilizing the median filter but + % try to prevent blurring of thin sulci/gyri + % - allow slighly smoother surfaces (better position with similar intensity) + Yfr = cat_vol_morph( round(Yp0fs)==2 ,'d',2); + Yp0fs = max( 1 , min( 3, ... % general limits + min( Yp0fs .* (3 - 2*(Yp0fs<1.5)) , ... % protect CSF + max( Yp0fs .* (Yp0fs>2.5) , ... % protect WM + cat_vol_median3(Yp0fs,Yfr) )))); % cleanup otherwise + % sharpening + Yp0fs = max( 1 , min( 3, Yp0fs + .5 * (round(Yp0fs)~=2) .* (Yp0fs - smooth3(Yp0fs)) )); + end + + % WM geometry and topology correction + % - this might lower thickness estimates and it might close small sulci + % - takes about 1 minute so I would try to avoid it + % - in case of amap it can be run for 2.25 and 2.75 + % ... we will try to avoid it as is can also create new problems and take 30s + if 1 + Yp0fs = (cat_vol_morph(Yp0fs*2 - 5,'wmtc',1,1,0) + 5)/2; % correct at 2.75 + %Yp0fs = (cat_vol_morph(Yp0fs*2 - 4,'wmtc',1,1,0) + 4)/2; % correct at 2.25 ... can close gyri better avoid + end + + % thickness and position estimation + [Yth1i,Yppi,Ymfsc] = cat_vol_pbtsimpleCS4(Yp0fs, opt.interpV,struct('myelinCorrection',myelinCorrection,'verb',1,'gyrusrecon',1)); + + else + %% Write PP + Vmfs.dt = [16 1]; + spm_write_vol(Vmfs, Yp0fs); + cmd = sprintf('CAT_VolThicknessPbt -median-filter 2 -sharpen 0.02 -fwhm 3 -downsample 0 ""%s"" ""%s"" ""%s""', Vmfs.fname, P(si).Pgmt, P(si).Pppm); + cat_system(cmd,opt.verb-3); + Vgmt = spm_vol(P(si).Pgmt); Yth1i = spm_read_vols(Vgmt); + Vppi = spm_vol(P(si).Pppm); Yppi = spm_read_vols(Vppi); + Ymfsc = Yp0fs; + end + + + %% prepare thickness output + Yth1t = cat_vol_resize(Yth1i,'deinterp',resI); % back to original resolution + Yth1t = cat_vol_resize(Yth1t+1,'dereduceBrain',BB)-1; % adding background + Yth = max(Yth,Yth1t .* Yside); % save on main image + + % prepare Ypp + Ymfsc = Yp0fs .* Ycutregion + (1-Ycutregion) .* Ymfsc; % ################## + Vppm = Vmfs; Vppm.fname = P(si).Pppm; Vppm.dt(1) = 16; Vppm.pinfo(1) = 1; Vpp = spm_write_vol(Vppm, Yppi); + Yppi = max(0,min(1,(cat_vol_smooth3X(Yppi,4)-.5)*4 + .5)) .* Ycutregiond + (1-Ycutregiond) .* Yppi; + + %% + if opt.vol + S = struct(); P = ''; + if opt.verb<2, fprintf('%5.0fs',etime(clock,stime)); end %#ok<*DETIM> + continue; % ############# deactive only for tests ################ + end + + %% RD20250330: The aim is to smoothing cutting regions to avoid defects there. + if 0;; % just for manual tests + opt.reconres = .6; % although 1.5-2.0 mm can work in general, defects correction can result in very severe and unpredictable problems + opt.vdist = 2; % controls surface reduction (linear value >> sqare for area, (8~2 mm), 4~1.2 mm, 2~1 mm, 1~0.7, .5~0.5) + end + + + % surface creation + % -------------------------------------------------------------------- + % In case of the central surface frequency patter between sulci and + % gyri is more harmonized and even lower surface reconstruction + % resolution (eg. 1.5 and 2.0) are possible. + % The resolution of 1.2 mm result in a similar number of vertices/faces + % as the CS2 pipeline. High resolution surfaces are quite large (disk space) + % and + % -------------------------------------------------------------------- + if useprior + fprintf('\n'); + stime = cat_io_cmd(' Load and refine subject average surface','g5','',opt.verb); %if opt.verb>2, fprintf('\n'); end + CS = loadSurf(P(si).Pcentral); + else + reconattempts = round((1.2 - .7)*10); % for reduction of .1 mm per step with 1.2 mm in the worst case + for li = 1:reconattempts + if li > 1, opt.reconres = opt.reconres + 0.1; end + + % optimized downsampling of the the Ypp map and + if isscalar(opt.surf), time_sr = clock; end % temporary for tests + [Vppmi,rel] = exportPPmap( Yp0 .* Ypb, Ymfsc, Yppi, Vmfs, Ypbs, vx_vol, si, opt, surffolder, ff); + + % Main initial surface creation with topology correction. + stime = cat_io_cmd(sprintf(' Create initial surface (%0.2f mm)',opt.reconres),'g5','',opt.verb,stime); %if opt.verb>2, fprintf('\n'); end + if exist(P(si).Pcentral,'file'), delete(P(si).Pcentral); end % have to delete it to get useful error messages in case of reprocessing/testing + cmd = sprintf('CAT_VolMarchingCubes ""%s"" ""%s"" -thresh ""%0.4f"" ', Vppmi.fname, P(si).Pcentral, .55); %5-0.05*opt.reconres); + Vpp = spm_write_vol(Vppm, Yppi); + cat_system(cmd ,opt.verb-3); + + + % load and check surface + % use 80000 as lower limit what is similar to vdist=4 + CS = loadSurf(P(si).Pcentral); + A = sum( cat_surf_fun( 'area', CS )); % in mm2 + nCS = min( size(CS.faces,1) , max( 80000, min( 360000, round(A * 2 * 4 / opt.vdist^2) ))); + if opt.SRP >= 2, nCS = min(300000,nCS); end + EC0 = size(CS.vertices,1) + size(CS.faces,1) - size(spm_mesh_edges(CS),1); + if EC0 ~= 2 + if li < reconattempts + % try again with another resolution + continue + else + cat_io_addwarning('cat_surf_createCS4:TopologyWarning', ... + sprintf('Extracted surface might have small topology issues (Euler count = %d).',EC0),0,[0 1]); + end + end + + % surface reduction + % - low surface resolution are highly important for fast processing and smaller disk usage + % - less critical for thickness but surface quality (intensity/position values) get worse + % - it is important to keep the topology + % - a more aggressive + stimesr = clock; + nCS0 = size(CS.faces,1); + saveSurf(CS,P(si).Pcentral); + cmd = sprintf('CAT_SurfReduce -aggr ""5"" -ratio ""%0.2f"" ""%s"" ""%s""', nCS/nCS0 , P(si).Pcentral, P(si).Pcentral); %5-0.05*opt.reconres); + cat_system(cmd ,opt.verb-3); + CS = loadSurf(P(si).Pcentral); + nCS1 = size(CS.faces,1); + saveSurf(CS,P(si).Pcentral); + + if li == reconattempts || nCS1 < nCS * 1.5 + % all done + cat_io_cmd(sprintf(' Reduce surface (nF: %0.0fk > ~%0.0fk)', nCS0/1000, nCS1/1000),'g5','',opt.verb,stime); + break + elseif li < reconattempts + % if the surface canot be reduced then try again with lower resoution + continue + elseif li == reconattempts && nCS1 > nCS * 1.5 + cat_io_addwarning('cat_surf_createCS4:ReductionFailed', ... + sprintf('Surface reduction incomplete due to topology constrains (%d).',(nCS1/1000-nCS/1000) ./ (nCS0/1000-nCS/1000)),0,[0 1]); + end + stime = stimesr; + end + end + + + % remove artifacts + % - this can maybe partially avoided by the more aggressive surface reduction + % - although the filter reduces some artefacts in problematic cases the surface values are worse and the issue are still not fully solved + % - tried to use it after correction of self-intersections but this made it even worse + % >> better not use now + if 0 + stime = cat_io_cmd(' Filter topology artifacts','g5','',opt.verb,stime); + CS = smoothArt(Yth1i,P,CS,Smat,Vppm,1,si,opt,1,1); % last options - method & refine + end + + % get PBT thickness and update cutregion + if setcut2zero + facevertexcdatanocut = 1 - cat_surf_fun('isocolors',Ycutregion,CS.vertices,Smat.matlabIBB_mm); + facevertexcdatanocut = max(0.5,min(1,(cat_surf_fun('smoothcdata',CS,facevertexcdatanocut,4) - .5) * 2)); + else + facevertexcdatanocut = 1; + end + facevertexcdata = cat_surf_fun('isocolors',Yth1i,CS.vertices,Smat.matlabIBB_mm) .* facevertexcdatanocut; + cat_io_FreeSurfer('write_surf_data',P(si).Ppbt,facevertexcdata); + cat_io_FreeSurfer('write_surf_data',P(si).Pthick,facevertexcdata); + + + % surface deformation + stime = cat_io_cmd(sprintf(' Optimize surface (nF: %0.0fk)', size(CS.faces,1)/1000),'g5','',opt.verb,stime); + for li = 1:2 % ... interation 1 with additional correction, iteration 2 without ... only small improvements for multiple iterations + cmd = sprintf('CAT_SurfDeform -iter 100 ""%s"" ""%s"" ""%s""', Vppm.fname, P(si).Pcentral, P(si).Pcentral); + cat_system(cmd,opt.verb-3); + CS = loadSurf(P(si).Pcentral); + + if opt.SRP > 0 && li == 1 + for xi = 1:2 % interation 1 with optimization, 2 without .. + % quick correction with local optimization + [CS,facevertexcdatac,SIs] = cat_surf_fun('collisionCorrectionPBT',CS,facevertexcdata .* facevertexcdatanocut,Ymfsc,Yppi, ... + struct('optimize',xi==1,'verb',isscalar(opt.surf)*2,'mat',Smat.matlabIBB_mm,'vx_vol',vx_vol,'CS4',0)); % CS4 is not working + if isscalar(opt.surf), fprintf('\b\b'); end + % accurate but slow function (especially for multiple jobs) + if xi == 1 %&& ~isscalar(opt.surf) + [CS,facevertexcdatac,SIs] = cat_surf_fun('collisionCorrectionRY' ,CS,facevertexcdatac .* facevertexcdatanocut,Yppi,... + struct('Pcs',P(si).Pcentral,'verb',isscalar(opt.surf)*2,'mat',Smat.matlabIBB_mm,'accuracy',1/2^2)); + if isscalar(opt.surf), fprintf('\b\b'); end + end + end + facevertexcdata = max(facevertexcdata,facevertexcdatac) .* facevertexcdatanocut; + cat_io_FreeSurfer('write_surf_data',P(si).Ppbt,facevertexcdata); + saveSurf(CS,P(si).Pcentral); + end + end + + + % evaluate and save results + if isempty(stime), stime = clock; end + fprintf('%5.0fs',etime(clock,stime)); stime = []; if 1, fprintf('\n'); end %debug + + + % create white and central surfaces + if create_white_pial + stime = cat_io_cmd(' Create pial and white surface','g5','',opt.verb,stime); + cmd = sprintf('CAT_Central2Pial ""%s"" ""%s"" ""%s"" 0.5',P(si).Pcentral,P(si).Ppbt,P(si).Ppial); + cat_system(cmd,opt.verb-3); + cmd = sprintf('CAT_Central2Pial ""%s"" ""%s"" ""%s"" -0.5',P(si).Pcentral,P(si).Ppbt,P(si).Pwhite); + cat_system(cmd,opt.verb-3); + end + + + if isscalar(opt.surf) + %% ========= only for test visualization ========= + if 1 % opt.thick_measure == 1 % allways here + cmd = sprintf('CAT_SurfDistance -mean -thickness ""%s"" ""%s"" ""%s""',P(si).Ppbt,P(si).Pcentral,P(si).Pthick); + cat_system(cmd,opt.verb-3); + % apply upper thickness limit + facevertexcdata = cat_io_FreeSurfer('read_surf_data',P(si).Pthick) .* facevertexcdatanocut; + facevertexcdata(facevertexcdata > opt.thick_limit) = opt.thick_limit; + cat_io_FreeSurfer('write_surf_data',P(si).Pthick,facevertexcdata); + end + + fprintf('\n'); + res.(opt.surf{si}).createCS_final = cat_surf_fun('evalCS', ... + loadSurf(P(si).Pcentral), cat_io_FreeSurfer('read_surf_data',P(si).Ppbt), facevertexcdata, ... + Ymfs,Yppi,P(si).Pcentral,Smat.matlabIBB_mm,2,0); + CS2 = CS; CS2.cdata = facevertexcdata; H = cat_surf_render2(CS2); + cat_surf_render2('clim',H,[0 6]); + cat_surf_render2('view',H,cat_io_strrep(opt.surf{si},{'lh','rh','ch'},{'right','left','back'})); + cat_surf_render2('ColourBar',H,'on'); + title(sprintf('CS4%d, R=%0.2f, nF=%0.0fk, EC=%d, \n TH=%0.3f±%0.3f, IE=%0.3f, PE=%0.3f, ptime=%0.0fs, time=%s', ... + opt.SRP, opt.reconres, size(CS.faces,1)/1000, EC0, ... + mean( facevertexcdata ), std(facevertexcdata), ... + mean( [ res.(opt.surf{si}).createCS_final.RMSE_Ym_white, res.(opt.surf{si}).createCS_final.RMSE_Ym_layer4, res.(opt.surf{si}).createCS_final.RMSE_Ym_pial ] ) , ... + mean( [ res.(opt.surf{si}).createCS_final.RMSE_Ypp_white, res.(opt.surf{si}).createCS_final.RMSE_Ypp_central, res.(opt.surf{si}).createCS_final.RMSE_Ypp_pial ] ) , ... + etime(clock,time_sr), datetime)) + subtitle( strrep( spm_str_manip(P(si).Pcentral,'a90') ,'_','\_')) + fprintf(' Runtime: %0.0fs\n',etime(clock,time_sr)); + + + % preparation for SPM orthviews links + Po = P(si).Pm; if ~exist(Po,'file'); Po = V0.fname; end + if ~exist(Po,'file') && exist([V0.fname '.gz'],'file'), Po = [V0.fname '.gz']; end + Porthfiles = ['{', sprintf('''%s'',''%s''',P(si).Ppial, P(si).Pwhite ) '}']; + Porthcolor = '{''-g'',''-r''}'; + Porthnames = '{''white'',''pial''}'; + fprintf(' Show surfaces in orthview: %s | %s | %s | (%s) | %s \n', ... + spm_file([opt.surf{si} '.pbt'],'link', sprintf('H=cat_surf_display(''%s'');',P(si).Ppbt)), ... + spm_file([opt.surf{si} '.thick'],'link', sprintf('H=cat_surf_display(''%s'');',P(si).Pthick)), ... + spm_file('segmentation' ,'link', sprintf('cat_surf_fun(''show_orthview'',%s,''%s'',%s,%s)',Porthfiles,P(si).Pp0, Porthcolor,Porthnames)), ... + spm_file('ppmap' ,'link', sprintf('cat_surf_fun(''show_orthview'',%s,''%s'',%s,%s)',Porthfiles,Vpp.fname, Porthcolor,Porthnames)), ... + spm_file('original' ,'link', sprintf('cat_surf_fun(''show_orthview'',%s,''%s'',%s,%s)',Porthfiles,Po, Porthcolor,Porthnames))); + + subtitle( strrep( spm_str_manip( P(si).Pcentral,'a90') ,'_','\_')) + fprintf(' Runtime: %0.0fs\n',etime(clock,time_sr)); + + return + end + + + +%% == TEST STOP == + + + % skip that part if a prior image is defined + if ~useprior && ~skip_registration + % spherical surface mapping of the final corrected surface with minimal areal smoothing + stime = cat_io_cmd(' Spherical mapping with areal smoothing','g5','',opt.verb,stime); + cmd = sprintf('CAT_Surf2Sphere ""%s"" ""%s"" %d',P(si).Pcentral,P(si).Psphere,6); + cat_system(cmd,opt.verb-3); + + % spherical registration to fsaverage template + stime = cat_io_cmd(' Spherical registration','g5','',opt.verb,stime); %#ok + cmd = sprintf('CAT_SurfWarp -steps 2 -avg -i ""%s"" -is ""%s"" -t ""%s"" -ts ""%s"" -ws ""%s""', ... + P(si).Pcentral,P(si).Psphere,P(si).Pfsavg,P(si).Pfsavgsph,P(si).Pspherereg); + cat_system(cmd,opt.verb-3); + end + + + if debug || cat_get_defaults('extopts.expertgui')>1, fprintf('\n'); end + if opt.thick_measure == 1 + % estimate Freesurfer thickness measure Tfs using mean(Tnear1,Tnear2) + if 0 + % estimate Freesurfer thickness based on WM and Pial surface ... not ready yet + cmd = sprintf('CAT_SurfDistance -mean ""%s"" ""%s"" ""%s""',P(si).Pwhite,P(si).Ppial,P(si).Pthick); + cat_system(cmd,opt.verb-3); + else + % use central surface and thickness to estimate Freesurfer thickness + cmd = sprintf('CAT_SurfDistance -mean -thickness ""%s"" ""%s"" ""%s""',P(si).Ppbt,P(si).Pcentral,P(si).Pthick); + cat_system(cmd,opt.verb-3); + end + + % apply upper thickness limit + % here the 5 mm thickness limit of FreeSurfer might be better rather then our 6 mm + facevertexcdata = cat_io_FreeSurfer('read_surf_data',P(si).Pthick) .* facevertexcdatanocut; + cat_io_FreeSurfer('write_surf_data', P(si).Pthick, min(opt.thick_limit,facevertexcdata) ); + else + % otherwise simply use the original values of the PBT map + % WARNING: + % The values of the ?h.pbt.* files are used to estimate further + % surfaces and therefore corrected for self-intersections! + % We use here the orignal PBT values as they are less depending on + % local highly individual features. + facevertexcdata = cat_surf_fun('isocolors',Yth1i,CS.vertices,Smat.matlabIBB_mm) .* facevertexcdatanocut; + cat_io_FreeSurfer('write_surf_data', P(si).Ppbt, facevertexcdata); + cat_io_FreeSurfer('write_surf_data', P(si).Pthick, min(opt.thick_limit,facevertexcdata) ); + end + fprintf('\n'); + + + % correct thickness based on folding pattern + if opt.foldingcorrection + cmd = sprintf('CAT_SurfCorrectThicknessFolding -max ""%f"" ""%s"" ""%s"" ""%s""', opt.thick_limit, P(si).Pcentral, P(si).Pthick, P(si).Pthick); + cat_system(cmd,opt.verb-3); + end + + + % final surface evaluation + res.(opt.surf{si}).createCS_final = cat_surf_fun('evalCS', ... + loadSurf(P(si).Pcentral), cat_io_FreeSurfer('read_surf_data',P(si).Ppbt), cat_io_FreeSurfer('read_surf_data',P(si).Pthick), ... + Ymfs, Yppi, P(si).Pcentral, Smat.matlabIBB_mm, debug + (cat_get_defaults('extopts.expertgui')>1), cat_get_defaults('extopts.expertgui')>1); + + + % average final values + FNres = fieldnames( res.(opt.surf{si}).createCS_final ); + for fnr = 1:numel(FNres) + if ~isfield(res,'final') || ~isfield(res.final,FNres{fnr}) + res.final.(FNres{fnr}) = res.(opt.surf{si}).createCS_final.(FNres{fnr}) / numel(opt.surf); + else + res.final.(FNres{fnr}) = res.final.(FNres{fnr}) + res.(opt.surf{si}).createCS_final.(FNres{fnr}) / numel(opt.surf); + end + end + + % create output structure + S.(opt.surf{si}) = struct('faces',CS.faces,'vertices',CS.vertices,'th1',facevertexcdata); + clear facevertexcdata Yth1i CS; + + if exist(Vppm.fname ,'file'), delete(Vppm.fname); end + if debug && exist(Vpp.fname ,'file') && ~opt.outputpp.native, delete(Vpp.fname); end + + % processing time per side for manual tests + if si == numel(opt.surf) && si == 1 + cat_io_cmd(' ','g5','',opt.verb); + fprintf('%5ds\n',round(etime(clock,cstime))); + end + end + + + % calculate surface quality parameters for all surfaces + res = addSurfaceQualityMeasures(res,opt); + + + % print final stats + evalProcessing(res,opt,P,V0,si) + +end + +%======================================================================= +function saveSurf(CS,P) + save(gifti(struct('faces',CS.faces,'vertices',CS.vertices)),P,'Base64Binary'); +end +%======================================================================= +function CS1 =loadSurf(P) + % add 1s because sometimes surface is not yet ready to read... + if ~exist(P,'file') + pause(3) + if ~exist(P,'file') + pause(1) + error('Surface file %s could not be found due to previous processing errors.',P); + end + end + + try + CS = gifti(P); + catch + error('Surface file %s could not be read due to previous processing errors.',P); + end + + CS1.vertices = CS.vertices; CS1.faces = CS.faces; + if isfield(CS,'cdata'), CS1.cdata = CS.cdata; end +end +%========================================================================== +function [Vmfs,Smat] = createOutputFileStructures(V,V0,resI,BB,opt,pp0,mrifolder,ff,si) + matI = spm_imatrix(V.mat); + matI(7:9) = sign( matI(7:9)) .* repmat( opt.interpV , 1 , 3); + matiBB = spm_imatrix(V.mat * [eye(4,3) [ (BB.BB([1,3,5])' - 1) ; 1]]); + matIBB = matiBB; + matIBB(7:9) = sign( matiBB(7:9)) .* repmat( opt.interpV , 1 , 3); + Smat.matlabi_mm = V.mat * [0 1 0 0; 1 0 0 0; 0 0 1 0; 0 0 0 1]; % CAT internal space + Smat.matlabI_mm = spm_matrix(matI) * [0 1 0 0; 1 0 0 0; 0 0 1 0; 0 0 0 1]; % PBT interpolated space + Smat.matlabIBB_mm = spm_matrix(matIBB) * [0 1 0 0; 1 0 0 0; 0 0 1 0; 0 0 0 1]; % PBT interpolated + Smat.matlabiBB_mm = spm_matrix(matiBB) * [0 1 0 0; 1 0 0 0; 0 0 1 0; 0 0 0 1]; % PBT interpolated + + Vmfs = resI.hdrN; + Vmfs.pinfo = V0.pinfo; + Vmfs.fname = fullfile(pp0,mrifolder, sprintf('%s_seg-%s.nii',ff,opt.surf{si})); + if isfield(Vmfs,'dat'), Vmfs = rmfield(Vmfs,'dat'); end + if isfield(Vmfs,'private'), Vmfs = rmfield(Vmfs,'private'); end + matiBB = spm_imatrix(V.mat * [eye(4,3) [ (BB.BB([1,3,5])' - 1) ; 1]]); + Vmfs.mat(1:3,4) = matiBB(1:3); +end +%========================================================================== +function [Vpp,Vppr] = prepareDownsampling(Vmfs,Ypps,pp0_surffolder,ff,opt,si) +%prepareDownsampling. Create nifti structure for low resolution. + Vpp = Vmfs; + Vpp.pinfo = repmat([1;0], 1,size(Ypps,3)); + Vpp.dat(:,:,:) = smooth3(single(Ypps)); + Vpp.dt(1) = 16; + Vppr = Vpp; + imat = spm_imatrix(Vpp.mat); + Vppr.dim = round(Vpp.dim .* opt.interpV./opt.reconres); + imat(7:9) = opt.reconres .* sign(imat(7:9)); + Vppr.mat = spm_matrix(imat); clear imat; + Vppr.fname = fullfile(pp0_surffolder, sprintf('%s.pp.%s.nii',opt.surf{si},ff)); +end +%========================================================================== +function res = addSurfaceQualityMeasures(res,opt) +%addSurfaceQualityMeasures. Measures to describe surface properties. + res.mnth = []; res.sdth = []; + res.mnRMSE_Ypp = []; res.mnRMSE_Ym = []; + res.SIw = []; res.SIp = []; res.SIwa = []; res.SIpa = []; + for si=1:numel(opt.surf) + if any(strcmp(opt.surf{si},{'lh','rh'})) + if isfield(res.(opt.surf{si}).createCS_final,'fsthickness_mn_sd_md_mx') && ... + ~isnan( res.(opt.surf{si}).createCS_final.fsthickness_mn_sd_md_mx(1) ) + res.mnth = [ res.mnth res.(opt.surf{si}).createCS_final.fsthickness_mn_sd_md_mx(1) ]; + res.sdth = [ res.sdth res.(opt.surf{si}).createCS_final.fsthickness_mn_sd_md_mx(2) ]; + else + res.mnth = [ res.mnth res.(opt.surf{si}).createCS_final.thickness_mn_sd_md_mx(1) ]; + res.sdth = [ res.sdth res.(opt.surf{si}).createCS_final.thickness_mn_sd_md_mx(2) ]; + end + res.mnRMSE_Ym = [ res.mnRMSE_Ym mean([... + res.(opt.surf{si}).createCS_final.RMSE_Ym_layer4 ... + res.(opt.surf{si}).createCS_final.RMSE_Ym_white ... + res.(opt.surf{si}).createCS_final.RMSE_Ym_pial ]) ]; + res.mnRMSE_Ypp = [ res.mnRMSE_Ypp mean([... + res.(opt.surf{si}).createCS_final.RMSE_Ypp_central ... + res.(opt.surf{si}).createCS_final.RMSE_Ypp_white ... + res.(opt.surf{si}).createCS_final.RMSE_Ypp_pial ]) ]; + if isfield(res.(opt.surf{si}).createCS_final,'white_self_interections') + res.SIw = [ res.SIw res.(opt.surf{si}).createCS_final.white_self_interections ]; + res.SIp = [ res.SIp res.(opt.surf{si}).createCS_final.pial_self_interections ]; + res.SIwa = [ res.SIwa res.(opt.surf{si}).createCS_final.white_self_interection_area ]; + res.SIpa = [ res.SIpa res.(opt.surf{si}).createCS_final.pial_self_interection_area ]; + end + end + end + + % final res structure + res.EC = NaN; + res.defect_size = NaN; + res.defect_area = NaN; + res.defects = NaN; + res.mnth = mean(res.mnth); + res.sdth = mean(res.sdth); + res.RMSE_Ym = mean(res.mnRMSE_Ym); + res.RMSE_Ypp = mean(res.mnRMSE_Ypp); +end +%========================================================================== +function evalProcessing(res,opt,P,V0,si) + if opt.verb && ~opt.vol + % display some evaluation + % - For normal use we limited the surface measures. + % - Surface intensity would be interesting as cortical measure similar to thickness (also age dependent). + % Especially the outer surface will describe the sulcal blurring in children. + % But the mixing of surface quality and anatomical features is problematic. + % - The position value describes how good the transformation of the PBT map into a surface worked. + % Also the position values depend on age. Children have worse pial values due to sulcal blurring but + % the white surface is may effected by aging, e.g., by WMHs. + % - However, for both intensity and position some (average) maps would be also interesting. + % Especially, some Kappa similar measure that describes the differences to the Ym or Ypp would be nice. + % - What does the Euler characteristic say? Wouldn't the defect number more useful for users? + + if any(~cellfun('isempty',strfind(opt.surf,'cb'))), cbtxt = 'cerebral '; else, cbtxt = ''; end + fprintf('Final %ssurface processing results: \n', cbtxt); + + % function to estimate the number of interactions of the surface deformation: d=distance in mm and a=accuracy + QMC = cat_io_colormaps('marks+',17); + color = @(m) QMC(max(1,min(size(QMC,1),round(((m-1)*3)+1))),:); + rate = @(x,best,worst) min(6,max(1, max(0,x-best) ./ (worst-best) * 5 + 1)); + + if cat_get_defaults('extopts.expertgui') + % color output currently only for expert ... + if isfield(res.(opt.surf{si}).createCS_final,'fsthickness_mn_sd_md_mx') + fprintf(' Average thickness (FS): '); + else + fprintf(' Average thickness (PBT): '); + end + cat_io_cprintf( color( rate( abs( res.mnth - 2.5 ) , 0 , 2.0 )) , sprintf('%0.4f' , res.mnth ) ); fprintf(' %s ',native2unicode(177, 'latin1')); + cat_io_cprintf( color( rate( abs( res.sdth - 0.5 ) , 0 , 1.0 )) , sprintf('%0.4f mm\n', res.sdth ) ); + + fprintf(' Surface intensity / position RMSE: '); + cat_io_cprintf( color( rate( mean(res.mnRMSE_Ym) , 0.05 , 0.3 ) ) , sprintf('%0.4f / ', mean(res.mnRMSE_Ym) ) ); + cat_io_cprintf( color( rate( mean(res.mnRMSE_Ypp) , 0.05 , 0.3 ) ) , sprintf('%0.4f\n', mean(res.mnRMSE_Ypp) ) ); + + if isfield(res.(opt.surf{si}).createCS_final,'white_self_interections') + fprintf(' Pial/white self-intersections: '); + cat_io_cprintf( color( rate( mean([res.SIw,res.SIp]) , 0 , 20 ) ) , sprintf('%0.2f%%%% (%0.2f mm%s)\n' , mean([res.SIw,res.SIp]) , mean([res.SIwa,res.SIpa]) , char(178) ) ); + end + else + fprintf(' Average thickness: %0.4f %s %0.4f mm\n' , res.mnth, native2unicode(177, 'latin1'), res.sdth); + end + + for si=1:numel(P) + fprintf(' Display thickness: %s\n',spm_file(P(si).Pthick,'link','cat_surf_display(''%s'')')); + end + + %% surfaces in spm_orthview + if exist(P(si).Pm,'file'), Po = P(si).Pm; else, Po = V0.fname; end + if ~exist(Po,'file') && exist([V0.fname '.gz'],'file'), Po = [V0.fname '.gz']; end + + Porthfiles = '{'; Porthcolor = '{'; Porthnames = '{'; + for si=1:numel(P) + Porthfiles = [ Porthfiles , sprintf('''%s'',''%s'',',P(si).Ppial, P(si).Pwhite )]; + Porthcolor = [ Porthcolor , '''-g'',''-r'',' ]; + Porthnames = [ Porthnames , '''pial'',''white'',' ]; + end + Porthfiles = [ Porthfiles(1:end-1) '}']; + Porthcolor = [ Porthcolor(1:end-1) '}']; + Porthnames = [ Porthnames(1:end-1) '}']; + + if 1 %debug + fprintf(' Show surfaces in orthview: %s\n',spm_file(Po ,'link',... + sprintf('cat_surf_fun(''show_orthview'',%s,''%s'',%s,%s)',Porthfiles,Po,Porthcolor,Porthnames))) ; + end + + end +end +%========================================================================== +function [Yp0f,Ymf] = fillVentricle(Yp0,Ym,Ya,YMF,vx_vol) +%fillVentricle. Simple filling of ventricles by a closing around a mask. + + NS = @(Ys,s) Ys==s | Ys==s+1; + LAB = cat_get_defaults('extopts.LAB'); + + % simple filling by the YMF mask + Yp0f = max(Yp0 ,min(1,YMF & ~NS(Ya,LAB.HC) & ~( cat_vol_morph( NS(Ya,LAB.HC),'dd',2,vx_vol)))); + Ymf = max(Ym ,min(1,YMF & ~NS(Ya,LAB.HC) & ~( cat_vol_morph( NS(Ya,LAB.HC),'dd',2,vx_vol)))); + + % close gaps in Yp0f + Yp0fs = cat_vol_smooth3X(Yp0f,1); + Ytmp = cat_vol_morph(YMF,'dd',3,vx_vol) & Yp0fs>2.1/3; + Yp0f(Ytmp) = max(min(Yp0(Ytmp),0),Yp0fs(Ytmp)); clear Ytmp Yp0fs; + Yp0f = Yp0f * 3; + + % close gaps in Ymfs + Ymfs = cat_vol_smooth3X(Ymf,1); + Ytmp = cat_vol_morph(YMF,'dd',3,vx_vol) & Ymfs>2.1/3; + Ymf(Ytmp) = max(min(Ym(Ytmp),0),Ymfs(Ytmp)); clear Ytmp Ymfs; + Ymf = Ymf * 3; +end +%========================================================================== +function [P,pp0,mrifolder,pp0_surffolder,surffolder,ff] = setFileNames(V0,job,opt) + + [mrifolder, ~, surffolder] = cat_io_subfolders(V0.fname,job); + + % get original filename without 'n' + [pp0,ff] = spm_fileparts(V0.fname); + + % correct '../' parts in directory for BIDS structure + [stat, val] = fileattrib(fullfile(pp0,surffolder)); + if stat, pp0_surffolder = val.Name; else, pp0_surffolder = fullfile(pp0,surffolder); end + if ~exist(fullfile(pp0_surffolder),'dir'), mkdir(fullfile(pp0_surffolder)); end + + % surface filenames + for si = 1:numel(opt.surf) + P(si).Pm = fullfile(pp0,mrifolder, sprintf('m%s.nii',ff)); % raw + P(si).Pp0 = fullfile(pp0,mrifolder, sprintf('p0%s.nii',ff)); % labelmap + P(si).Pdefects = fullfile(pp0,mrifolder, sprintf('defects_%s.nii',ff)); % defect + P(si).Pcentral = fullfile(pp0_surffolder,sprintf('%s.central.%s.gii',opt.surf{si},ff)); % central + P(si).Pcentralh = fullfile(pp0_surffolder,sprintf('%s.centralh.%s.gii',opt.surf{si},ff)); % central + P(si).Pcentralr = fullfile(pp0_surffolder,sprintf('%s.central.resampled.%s.gii',opt.surf{si},ff));% central .. used in inactive path + P(si).Ppial = fullfile(pp0_surffolder,sprintf('%s.pial.%s.gii',opt.surf{si},ff)); % pial (GM/CSF) + P(si).Pwhite = fullfile(pp0_surffolder,sprintf('%s.white.%s.gii',opt.surf{si},ff)); % white (WM/GM) + P(si).Pthick = fullfile(pp0_surffolder,sprintf('%s.thickness.%s',opt.surf{si},ff)); % FS thickness / GM depth + P(si).Pmsk = fullfile(pp0_surffolder,sprintf('%s.msk.%s',opt.surf{si},ff)); % msk + P(si).Ppbt = fullfile(pp0_surffolder,sprintf('%s.pbt.%s',opt.surf{si},ff)); % PBT thickness / GM depth + P(si).Psphere = fullfile(pp0_surffolder,sprintf('%s.sphere.%s.gii',opt.surf{si},ff)); % sphere + P(si).Pspherereg = fullfile(pp0_surffolder,sprintf('%s.sphere.reg.%s.gii',opt.surf{si},ff)); % sphere.reg + P(si).Pgmt = fullfile(pp0,mrifolder, sprintf('%s_thickness-%s.nii',ff,opt.surf{si})); % temp thickness + P(si).Pppm = fullfile(pp0,mrifolder, sprintf('%s_ppm-%s.nii',ff,opt.surf{si})); % temp position map + P(si).Pfsavg = fullfile(opt.fsavgDir, sprintf('%s.central.freesurfer.gii',opt.surf{si})); % fsaverage central + P(si).Pfsavgsph = fullfile(opt.fsavgDir, sprintf('%s.sphere.freesurfer.gii',opt.surf{si})); % fsaverage sphere + end +end +%========================================================================== +function useprior = setupprior(opt,surffolder,P,si) +%setupprior. prepare longitidunal files + + % use surface of given (average) data as prior for longitudinal mode + if isfield(opt,'useprior') && ~isempty(opt.useprior) + % RD20200729: delete later ... && exist(char(opt.useprior),'file') + % if it not exist than filecopy has to print the error + [pp1,ff1] = spm_fileparts(opt.useprior); + % correct '../' parts in directory for BIDS structure + [stat, val] = fileattrib(fullfile(pp1,surffolder)); + if stat, pp1_surffolder = val.Name; else, pp1_surffolder = fullfile(pp1,surffolder); end + + % try to copy surface files from prior to individual surface data + useprior = 1; + useprior = useprior & copyfile(fullfile(pp1_surffolder,sprintf('%s.central.%s.gii',opt.surf{si},ff1)),P(si).Pcentral,'f'); + useprior = useprior & copyfile(fullfile(pp1_surffolder,sprintf('%s.sphere.%s.gii',opt.surf{si},ff1)),P(si).Psphere,'f'); + useprior = useprior & copyfile(fullfile(pp1_surffolder,sprintf('%s.sphere.reg.%s.gii',opt.surf{si},ff1)),P(si).Pspherereg,'f'); + + if ~useprior + warn_str = sprintf('Surface files for %s not found. Move on with individual surface extraction.\n',pp1_surffolder); + fprintf('\nWARNING: %s',warn_str); + cat_io_addwarning('cat_surf_createCS4:noPiorSurface', warn_str); + else + fprintf('\nUse existing surface as prior and thus skip many processing steps:\n%s\n',pp1_surffolder); + end + else + useprior = 0; + end +end +function CS = smoothArt(Yth1i,P,CS,Smat,Vppm,facevertexcdatanocut,si,opt,method,refine) +%% Topology artifact correction (after first deformation): +% Although the topology is fine after correction the geometry often +% suffers by small snake-like objects that were deformed close to the +% central layer, resulting in underestimation of the FS thickness. + pbtthick = cat_surf_fun('isocolors',Yth1i,CS.vertices,Smat.matlabIBB_mm) .* facevertexcdatanocut; + cat_io_FreeSurfer('write_surf_data',P(si).Ppbt,pbtthick); + cmd = sprintf('CAT_SurfDistance -mean -thickness ""%s"" ""%s"" ""%s""', P(si).Ppbt, P(si).Pcentral, P(si).Pthick); + cat_system(cmd,opt.verb-3); + fsthick = cat_io_FreeSurfer('read_surf_data',P(si).Pthick); + + % define outlier maps + tart = (pbtthick - fsthick)>.5 | (pbtthick - fsthick)>.5; % artifacts from topology correction + [~,dI] = unique(CS.vertices,'rows'); SM = true(size(CS.vertices,1),1); SM(dI) = false; % vertices with same coordinates + iarea = 1./cat_surf_fun('area',CS); % face area to identify tiny faces (=artifacs) + + if method % old function + CS = cat_surf_smoothr(CS,tart | SM | iarea>10000, size(CS.vertices,1)/10, 10); % local + CS = cat_surf_smoothr(CS,tart>=0, 1, 1); % all + saveSurf(CS,P(si).Pcentral); + else + % this is not really working + cat_io_FreeSurfer('write_surf_data',P(si).Pmsk,tart | SM | iarea>1000); % create a mask for filtering + cmd = sprintf('CAT_BlurSurfHK ""%s"" ""%s"" ""%g"" ""%s""', P(si).Pcentral, P(si).Pmsk, round(size(CS.vertices,1)/100), P(si).Pmsk); % local + cat_system(cmd,opt.verb-3); delete(P(si).Pmsk); + cmd = sprintf('CAT_BlurSurfHK ""%s"" ""%s"" ""%g""', P(si).Pcentral, P(si).Pmsk, 10); % all + cat_system(cmd,opt.verb-3); delete(P(si).Pmsk); + end + + if refine + %saveSurf(CS,P(si).Pcentral); + cmd = sprintf('CAT_Central2Pial -equivolume -weight 0.55 ""%s"" ""%s"" ""%s"" 0',P(si).Pcentral,P(si).Ppbt,P(si).Pcentral); + cat_system(cmd,opt.verb-3); + if 0 + CS2 = loadSurf(P(si).Pcentral); + tart = repmat( tart | SM | iarea>1000 , 1,3); + CS.vertices = CS.vertices.*(tart) + (~tart).*CS2.vertices; + saveSurf(CS,P(si).Pcentral); + end + end + + cmd = sprintf('CAT_SurfDeform -iter 100 ""%s"" ""%s"" ""%s""', Vppm.fname, P(si).Pcentral, P(si).Pcentral); + cat_system(cmd,opt.verb-3); + + CS = loadSurf(P(si).Pcentral); +end +%========================================================================== +function [Vppm,rel] = exportPPmap( Yp0, Yp0fs, Yppi, Vmfs, Ypbs, vx_vol, si, opt, surffolder, ff) +%exportPPmap. Prepare image for resolution reduction. +% +% Local optimization helps to keep thin structures. +% +% [Vppm,Ypps] = exportPPmap( Yp0, Yp0fs, Yppi, Yth1i, Vmfs, vx_vol, si, opt, surffolder, ff) +% +% I tried here multiple things but most are not working or even contraproductive. +% +% * Enhancement by sharpening as inverse smoothing: +% Was not robust and did not support good control. +% +% * Enhandement by local optimization to balance the sulcal-gyral span: +% Partially working but only very small weightings are possible. +% However, the values (distance+thickness) can help to control other +% modifications, such as the min-max-based enlargements of gyri/sulci. +% +% * Divergence-based skeleton: +% Caused bridge defects but the information is useful to limit other things. +% +% * Intensity-based morphometry (gray-dilate) as minimum/maximum filter: +% This works if the + + + + % Yp0fs = cat_vol_median3(Yp0fs,Yppi>0 & Yppi<1); + + %% == optimized downsampling == + % extrem values: .1^.3 = .5012, .6^1.3 = 0.5148 + rel = max(.3,min(1.3, (nnz(Yp0(:)>2.5/3) / nnz(Yp0(:)>.5/3 & Yp0(:)<1.5/3)) )); + optimize = (opt.SRP>0) .* 3; + switch optimize + case 1 % local ... not working! + %% balance suclus/gyrus thickness - make thin fat and fat thin - needs full resolution ! + Yid = cat_vbdist( single(Yppi < 0.45), Ypbs)/2 + cat_vbdist( single(Yppi < 0.55), Ypbs)/2; Yid = Yid .* Ypbs; + Yod = cat_vbdist( single(Yppi > 0.45), Ypbs)/2 + cat_vbdist( single(Yppi > 0.55), Ypbs)/2; Yod = Yod .* Ypbs; + % remove outliers + Yit = cat_vol_pbtp( single(3 - (Yppi>.5)), Yid, 0*Yid); Yit(Yit > 10) = 0; + Yot = cat_vol_pbtp( single(2 + (Yppi>.5)), Yod, 0*Yod); Yot(Yot > 10) = 0; + % approximation + Yit = cat_vol_approx(Yit); + Yot = cat_vol_approx(Yot); + % ""simple"" correction: + % - this has to be use very carefully and ""Yppi.^max(.95,min(1.05, Yit ./ Yot ))"" + % presents already the stronges correction !!! + Ypps = min(0,max( (Yp0fs)-2, Yppi)).^max(.3,min(1.3, cat_vol_smooth3X( Yit ./ Yot ,2 ) ) ); + case 2 % global ... is less good could be further improved + Ypps = min(1,max(Yp0fs-2, Yppi.^max(.3,min(1.3,rel)) )); + case 3 % ########### need futher evaluation / test ! ######### + [Yppsr,Ypbsr,resYpp] = cat_vol_resize({Yppi * 2,single(Ypbs)},'reduceV',opt.interpV,4,32,'meanm'); + Ypppr = cat_vol_localstat(Yppsr,Ypbsr>.1,1,1,8); + Ypppr(Ypbsr>.5) = 1; + Ypppr = cat_vol_approx(Ypppr); + Yppp = cat_vol_resize(Ypppr,'dereduceV',resYpp); + Yppp = cat_vol_smooth3X(Yppp,4); + Ypps = Yppi.^max(.5,min(1.0,Yppp)); % max( max(0,Yp0fs-2), Yppi).^max(.3,min(1.3,Yppp)); + %fprintf('(Yppp=%0.2f)',mean(Yppp(Yppi(:)>0 & Yppi(:)<1))); + otherwise + Ypps = Yppi; + end + + %% Final downsampling: + % - We combine here the average position with the GM/WM interface. + %Ypps = cat_vol_median3(Ypps,Ypps>0 & Ypps<1); + fs = 0; %.35; + if opt.interpV == opt.reconres + Ytx = Ypps; % smooth3( Ypps ); % max(Ypps,max(0,min(1,Yp0fs-2)) .^ .25); % smooth3? + Vppm = Vmfs; + else + [Vpp,Vppr] = prepareDownsampling(Vmfs,Ypps,surffolder,ff,opt,si); + Vpp.dat(:,:,:) = cat_vol_smooth3X( Ypps , fs ); + [Vppm,Yt] = cat_vol_imcalc(Vpp,Vppr,'i1',struct('interp',5,'verb',0,'mask',-1)); + Vpp.dat(:,:,:) = cat_vol_smooth3X( max(0,min(1,Yp0fs-2)) .^ rel, fs ); + [~,Yw] = cat_vol_imcalc(Vpp,Vppr,'i1',struct('interp',5,'verb',0,'mask',-1)); + Vpp.dat(:,:,:) = cat_vol_smooth3X( max(0,min(1,2-Yp0fs)) .^ rel, fs ); + [~,Yc] = cat_vol_imcalc(Vpp,Vppr,'i1',struct('interp',5,'verb',0,'mask',-1)); + Vppm.pinfo = Vmfs.pinfo; + Ytx = Yt; %min(max(0,1-Yc), max(Yt,Yw)); + end + + if isfield(Vppm,'dat'), Vppm = rmfield(Vppm,{'dat'}); end + Vppm = spm_write_vol(Vppm, Ytx ); + + if 0 + Vppm.fname = fullfile(surffolder,sprintf('%s.pp.%s.r%0.2f.surfrecon.nii',opt.surf{si},ff,opt.reconres)); + spm_write_vol(Vppm, Ytx ); + end +end +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_batch_spm.sh",".sh","8937","332","#! /bin/bash +# Call SPM12 batch jobs from shell +# ______________________________________________________________________ +# +# Christian Gaser, Robert Dahnke +# Structural Brain Mapping Group (https://neuro-jena.github.io) +# Departments of Neurology and Psychiatry +# Jena University Hospital +# ______________________________________________________________________ +# $Id$ + +######################################################## +# global parameters +######################################################## + +cwd=$(dirname ""$0"") +matlab=matlab # you can use other matlab versions by changing the matlab parameter +display=0 # use nodisplay option for matlab or not +LOGDIR=$PWD +spm12=$(dirname ""$cwd"") +spm12=$(dirname ""$spm12"") +mpath=""'""$(dirname ""$1 "")""'"" +ivar= +fg=0 +nojvm="""" + +######################################################## +# run main +######################################################## + +main () +{ + parse_args ${1+""$@""} + check_matlab + run_batch + + exit 0 +} + + +######################################################## +# check arguments and files +######################################################## + +parse_args () +{ + local optname optarg + + if [ $# -lt 1 ]; then + help + exit 1 + fi + + + while [ $# -gt 0 ]; do + optname=""`echo $1 | sed 's,=.*,,'`"" + optarg=""`echo $2 | sed 's,^[^=]*=,,'`"" + optarg2=""`echo $3 | sed 's,^[^=]*=,,'`"" + case ""$1"" in + --matlab* | -m*) + exit_if_empty ""$optname"" ""$optarg"" + matlab=$optarg + shift + ;; + --display* | -d*) + display=1 + ;; + --nojvm | -nj*) + exit_if_empty ""$optname"" ""$optarg"" + nojvm="" -nojvm "" + ;; + --fg* | -fg*) + exit_if_empty ""$optname"" ""$optarg"" + fg=1 + ;; + --logdir* | -l*) + exit_if_empty ""$optname"" ""$optarg"" + LOGDIR=$optarg + if [ ! -d $LOGDIR ] + then + mkdir -p $LOGDIR + fi + shift + ;; + -h | --help | -v | --version | -V) + help + exit 1 + ;; + -p | --path) + exit_if_empty ""$optname"" ""$optarg"" + mpath=""$mpath,'$optarg'"" + shift + ;; + -f | --files) + # read all files until nothing remains or the next command is coming and + # pack everything into a matlab cellstr + exit_if_empty2 ""$optname"" ""$optarg"" ""$optarg2"" + ivar=""$ivar,'$optarg',{'$optarg2'"" + runon=1 + shift + shift + while [ $# -gt 0 ] && [ $runon -gt 0 ]; do + case ""$2"" in + -*) + runon=0 + ;; + *) + ivar=""$ivar;'$2'"" + shift + ;; + esac + done + ivar=$ivar""}"" + ;; + -i | --var | --ivar) + exit_if_empty2 ""$optname"" ""$optarg"" ""$optarg2"" + ivar=""$ivar,'$optarg',$3"" + shift + shift + ;; + -*) + echo ""`basename $0`: ERROR: Unrecognized option \""$1\"""" >&2 + ;; + *) + file=""$1"" + ;; + esac + shift + done +} + +######################################################## +# check arguments +######################################################## +exit_if_empty () +{ + local desc val + + desc=""$1"" + shift + val=""$*"" + + if [ ! -n ""$val"" ]; then + echo 'ERROR: No argument given with \""$desc\"" command line argument!' >&2 + exit 1 + fi +} +exit_if_empty2 () +{ + local desc var val + + desc=""$1"" + shift + var=""$2"" + shift + val=""$*"" + + if [ ! -n ""$val"" ]; then + echo 'ERROR: No argument given with \""$desc\"" command line argument!' >&2 + exit 1 + fi +} + + +######################################################## +# run batch +######################################################## + +run_batch () +{ + pwd=$PWD + + # we have to go into toolbox folder to find matlab files + cd $cwd + + if [ ! -n ""${LOGDIR}"" ]; then + LOGDIR=$(dirname ""${ARRAY[0]}"") + fi + + # add current folder to matlabfile if file was not found + if [ ! -f $file ]; then + file=${pwd}/$file + fi + + if [ ! -f $file ]; then + echo File $file does not exist. + exit 0 + fi + + dname=$(dirname ""$file"") + file=$(basename ""$file"") + + if [ ! `echo ""$file"" | cut -f2 -d'.'` == ""m"" ]; then + echo File ""$file"" is not a matlab script. + exit 0 + fi + + # we have to add current path if cat_batch_cat.sh was called from relative path + if [ -d ${pwd}/${spm12} ]; then + spm12=${pwd}/${spm12} + fi + + export MATLABPATH=$spm12:$dname + + time=`date ""+%Y%b%d_%H%M""` + spmlog=${LOGDIR}/spm_${HOSTNAME}_${time}.log + echo Check $spmlog for logging information + echo + + file=`echo $file| sed -e 's/\.m//g'` + + # prepare matlab code with additional path + X=""addpath($mpath); cat_batch_spm('${file}'${ivar})"" + + echo SPM command: + echo "" ""$X; + echo + + echo Running $file + echo > $spmlog + echo ---------------------------------- >> $spmlog + date >> $spmlog + echo ---------------------------------- >> $spmlog + echo >> $spmlog + echo $0 $file >> $spmlog + echo >> $spmlog + + if [ $display == 0 ]; then + str_display="" -nodisplay "" + else + str_display="""" + fi + + if [ ""$fg"" -eq 0 ]; then + nohup ${matlab} ""$str_display"" ""$nojvm"" -nosplash -r ""$X"" >> $spmlog 2>&1 & + else + nohup ${matlab} ""$str_display"" ""$nojvm"" -nosplash -r ""$X"" >> $spmlog 2>&1 + fi + exit 0 +} + +######################################################## +# check if matlab exist +######################################################## + +check_matlab () +{ + found=`which ${matlab} 2>/dev/null` + if [ ! -n ""$found"" ];then + echo $matlab not found. + exit 1 + fi +} + +######################################################## +# help +######################################################## + +help () +{ +cat <<__EOM__ + +USAGE: + cat_batch_spm.sh batchfile.m [-d] [-m matlabcommand] + + -m | --matlab matlab command (matlab version) (default $matlab) + -d | --display use display option in matlab in case that + batch file needs graphical output + -l | --logdir directory for log-file (default $LOGDIR) + -nj | --nojvm supress call of jvm using the -nojvm flag + -fg | --fg do not run matlab process in background + -p | --mpath add directory to matlab path (the path of + the called file is added automaticly) + -f | -files + Create a cellstr by a set of files,e.g., + -f data path1/file1.ext path2/file2.ext + will create a matlab variable + data = {'path1/file1.ext';'path1/file1.ext'}; + -i """" | --ivar """" + Create a variable ""varname"" to be used in + the matlabbatch to set up variables, e.g., + to specify directories, files, or options. + Examples: + (1) To create a simple matrix: + -i mat ""[0 8 1 5]"" + (2) To create a structure with subfields: + -i opt ""struct('flag1',1,'verb',0,'files',{'file.ext})"" + (3) To create a cell array with filenames: + -i files ""{'path1/fname1.ext','path2/fname2.ext'}"" + + Only one batch filename is allowed. Optionally you can set the matlab command + with the ""-m"" option. As default no display is used (via the -nodisplay option + in matlab). However sometimes the batch file needs a graphical output and the + display should be enabled with the option ""-d"". + +PURPOSE: + Command line call of SPM12 batch files + +EXAMPLE + cat_batch_spm.sh test_batch.m -m /usr/local/bin/matlab7 + This command will process the batch file test_batch.m. As matlab command + /usr/local/bin/matlab7 will be used. + + cat_batch_spm.sh /Users/cat/matlabbatches/batch_prepana_smoothandmore.m + -m /Applications/MATLAB_R2020a.app/bin/matlab + -f pdirs /Volumes/drive/MRData/ADNI/derivatives/CAT12.8.1/sub-ADNI002S0955 + /Volumes/drive/MRData/ADNI/derivatives/CAT12.8.1/sub-ADNI002S0954 + -i vdata ""{'mwp1'}"" -i smoothing ""[4 8]"" + +INPUT: + batch file saved as matlab-script or mat-file + +OUTPUT: + ${LOGDIR}/spm_${HOSTNAME}_${time}.log for log information + +USED FUNCTIONS: + SPM12 + +SETTINGS + matlab command: $matlab + +This script was written by Christian Gaser (christian.gaser@uni-jena.de). + +__EOM__ +} + +######################################################## +# call main program +######################################################## + +main ${1+""$@""} +","Shell" +"Neurology","ChristianGaser/cat12","cat_stat_kmeans.m",".m","2851","128","function [mu,su,nu] = cat_stat_kmeans(y,k,s) +% K-means clustering +%_______________________________________________________________________ +% FORMAT [mu,su,nu] = cat_stat_kmeans(y,k[,s]) +% +% y .. data +% k .. Number of components +% s .. select peak (s>0 & s<=k) to have some side peaks just for +% stabilization, s==0 select maximum peak +% +% +% mu .. vector of class means +% su .. vector of class std +% nu .. vector of class percentage of values +% +% examples: +% d1 = randn(1,10000); +% d2 = [randn(1,1000) - 3 , randn(1,10000) + 3]; +% d3 = [randn(1,1000) - 1 , randn(1,10000) + 1]; +% d4 = [randn(1,100)/2 + 0.5 , randn(1,1000)/2 + 2.2, randn(1,700)/2 + 3.8]; +% +% [mn,sd] = cat_stat_kmeans(d1,1) +% [mn,sd] = cat_stat_kmeans(d2,2) +% [mn,sd] = cat_stat_kmeans(d3,2) +% [mn,sd] = cat_stat_kmeans(d4,3) +% +% modified version of +% spm_kmeans1.m 1143 2008-02-07 19:33:33Z spm $ +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +if nargin<1, help cat_stat_kmeans; return; end +if nargin<2, k=1; end + +k = max(1,k); + +dt = class(y); +y = double(y); +y = y(:)'; +y(isnan(y))=[]; % remove NaNs +if numel(y)<=0 + mu = nan(1,k); + su = mu; + nu = mu; + return; +end + +N = length(y); + +% Spread seeds evenly according to CDF +x = sort(y); +seeds=[1,2*ones(1,k-1)]*N/(2*k); +seeds=ceil(cumsum(seeds)); + +last_i = N; %(ones(1,N); +mu = x(seeds); +su = zeros(size(mu)); +nu = ones(size(mu)); + +d = zeros(k,length(y)); +for loops = 1:1000 + + for j=1:k + d(j,:) = (y-mu(j)).^2; + end + [tmp,i] = min(d); clear tmp %#ok + if sum(i - last_i)==0 || isempty(y(i==j)) + % If assignment is unchanged + break; + else + % Recompute centres + for j=1:k + mu(j) = mean(y(i==j)); + end + last_i=i; + end +end + +% Compute variances and mixing proportions +if k==1 + su(1) = std(y(1,:)); +else + for j=1:k + if isempty(y(i==j)) + su(j) = std(d(j,:)); + else + su(j) = std(y(i==j)); + end + end +end + +bd = nan(k,2); +for j=1:k + % lower boundary + if j==1, bd(j,1) = -inf; end + if j>1, bd(j,1) = mean( [ mu(j-1) + su(j-1) , mu(j) - su(j) ] ); end + % upper boudnary + if jbd(j,1) & y<=bd(j,2) )/numel(y); +end + +if exist('s','var') + if s>k + error('s has to be >=0 and <=k.'); + end + if s==0 + [tmp,s] = max(nu); %#ok % select maximum + end + mu = mu(s); + su = su(s); + nu = nu(s); +end + +if strcmp(dt,'double') %#ok + feval(dt,mu); + feval(dt,su); + feval(dt,nu); +end + + ","MATLAB" +"Neurology","ChristianGaser/cat12","Contents.m",".m","6735","181","% Computational Anatomy Toolbox +% Version 2946 (CAT12.9) 2025-11-13 +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ +% ========================================================================== +% Description +% ========================================================================== +% This toolbox is a collection of extensions to the segmentation algorithm +% of SPM12 (Wellcome Department of Cognitive Neurology) to provide computational +% morphometry. It is developed by Christian Gaser and Robert Dahnke (Jena +% University Hospital, Departments of Psychiatry and Neurology) and is available +% to the scientific community under the terms of the GNU General Public License as +% published by the Free Software Foundation; either version 2 of the License, +% or (at your option) any later version. +% +% If you use any CAT12 code for commercial application, please email +% christian.gaser@uni-jena.de. +% +% General files +% INSTALL.txt - installation instructions +% CHANGES.txt - changes in revisions +% Contents.m - this file +% +% Core functions +% cat12.m +% cat_amap.m - compilation wrapper for cat_amap.c +% cat_main.m +% cat_run.m - runtime funtion for CAT12 +% cat_run_job.m +% cat_run_newcatch.m +% cat_run_oldcatch.m +% cat_defaults.m - sets the defaults for CAT12 +% cat_get_defaults.m - defaults for CAT12 +% spm_cat12.m - toolbox wrapper to call CAT12 +% +% Utilities +% cat_sanlm.m - Spatial Adaptive Non Local Means Denoising Filter +% cat_update.m - check for new updates +% cat_debug.m - print debug information for SPM12 and CAT12 +% cat_ornlm.m +% cat_plot_boxplot.m +% slice_overlay.m - overlay tool +% sliderPanel.m +% +% Input & Output +% cat_io_3Dto4D.m +% cat_io_FreeSurfer.m +% cat_io_cgw2seg.m +% cat_io_checkinopt.m +% cat_io_cmd.m +% cat_io_colormaps.m +% cat_io_cprintf.m +% cat_io_csv.m +% cat_io_handle_pre.m +% cat_io_img2nii.m +% cat_io_matlabversion.m +% cat_io_remat.m +% cat_io_seg2cgw.m +% cat_io_struct2table.m +% cat_io_updateStruct.m +% cat_io_writenii.m +% cat_io_xml.m +% cat_io_xml2csv.m +% +% Longitudinal batch +% cat_long_main.m - longitudinal batch mode +% cat_long_multi_run.m - call cat_long_main for multiple subjects +% +% Statistics +% cat_stat_calc_stc.m +% cat_stat_homogeneity.m - check sample homogeneity across sample +% cat_stat_marks.m +% cat_stat_nanmean.m +% cat_stat_nanmedian.m +% cat_stat_nanstat1d.m +% cat_stat_nanstd.m +% cat_stat_nansum.m +% cat_stat_showslice_all.m - show 1 slice of all images +% cat_stat_spm.m +% cat_stat_spmF2x.m - transformation of F-maps to P, -log(P), R2 maps +% cat_stat_spmT2x.m - transformation of t-maps to P, -log(P), r or d-maps +% cat_stat_TIV.m - read total intracranial volume (TIV) from xml-files +% +% Surface functions +% cat_surf_avg.m +% cat_surf_calc.m +% cat_surf_createCS.m +% cat_surf_display.m +% cat_surf_info.m +% cat_surf_parameters.m +% cat_surf_rename.m +% cat_surf_render.m +% cat_surf_resamp.m +% cat_surf_resamp_freesurfer.m +% cat_surf_resample.m +% cat_surf_smooth.m +% cat_surf_vol2surf.m +% +% Test and experimental functions +% cat_tst_BWPsliceartifact.m +% cat_tst_CJV.m +% cat_tst_calc_kappa.m +% cat_tst_qa.m +% cat_tst_staple_multilabels.m +% +% Volume functions +% cat_vol_approx.m +% cat_vol_atlas.m +% cat_vol_average.m +% cat_vol_calc_roi.m +% cat_vol_correct_slice_scaling.m +% cat_vol_ctype.m +% cat_vol_defs.m - apply deformations to images +% cat_vol_findfiles.m +% cat_vol_groupwise_ls.m +% cat_vol_imcalc.m +% cat_vol_iscale.m +% cat_vol_morph.m - morphological operations to 3D data +% cat_vol_nanmean3.m +% cat_vol_partvol.m +% cat_vol_pbt.m +% cat_vol_resize.m +% cat_vol_sanlm.m - GUI for cat_sanlm +% cat_vol_series_align.m +% cat_vol_set_com.m +% cat_vol_slice_overlay.m - wrapper for overlay tool slice_overlay +% cat_vol_slice_overlay_ui.m - example for user interface for overlay wrapper cat_slice_overlay.m +% cat_vol_smooth3X.m +% +% Batch mode +% cat_batch_long.m - batch mode wrapper for spm_jobman for longitudinal pipeline +% cat_batch_spm.m - batch mode wrapper for spm_jobman for SPM12 +% cat_batch_vbm.m - batch mode wrapper for spm_jobman for CAT12 +% +% Check input and files +% cat_check.m +% cat_check_system_output.m +% +% Configuration +% cat_conf_extopts.m +% cat_conf_long.m +% cat_conf_opts.m +% cat_conf_stools.m +% cat_conf_stoolsexp.m +% cat_conf_tools.m - wrapper for calling CAT12 utilities +% tbx_cfg_cat.m +% +% Templates/Atlases volumes +% Template_?_GS.nii - Geodesic Shooting template of 555 subjects from IXI database +% in MNI152NLin2009cAsym space provided for 6 different iteration steps +% Template_T1.nii - average of 555 T1 images of IXI database in MNI152 space after +% Geodesic Shooting +% aal3.* - AAL3 atlas +% anatomy3.* - Anatomy3 atlas +% cobra.* - CoBra atlas +% hammers.* - Hammers atlas +% ibsr.* - IBSR atlas +% julichbrain3.* _ JulichBrain3 atlas +% mori.* - Mori atlas +% thalamus.* - Thalamic Nuclei atlas +% neuromorphometrics.* - Neuromorphometrics atlas +% lpba40.nii - LPBA40 atlas +% brainmask.nii - brainmask +% cat12.nii - partitions for hemispheres, subcortical structures and vessels +% +% Templates/Atlases surfaces +% ?h.central.Template_T1.gii +% - central surface of Dartel average brain for result mapping +% ?h.central.freesurfer.gii - central surface of freesurfer fsaverage +% ?h.inflated.freesurfer.gii - inflated surface of freesurfer fsaverage +% ?h.sphere.freesurfer.gii - spherical surface of freesurfer fsvaverage + + + +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_surf_gyrification.m",".m","23342","605","function PSgi = cat_surf_gyrification(PS,opt) +% Collection of gyrification measures +% ______________________________________________________________________ +% This function includes surface relation measures to describe the +% cortical folding by the folded original central surface and a second +% unfolded version of it. +% +% In the ideal case, the smoothing has to be done for each area and not +% the final measure, to be compatible to global or regional definitions. +% This is not standard yet! Therefore it is maybe better to combine this +% estimation with the resampling function and create only resampled +% output data. +% +% WARNING: All measures required further test, validation and evaluation. +% +% cat_surf_gyrification(PS,opt) +% +% PS .. individual central surface file +% opt .. structure with different option +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + +% Internal documentation: +% ______________________________________________________________________ +% +% Most of the here described measure are only an early conceptual state +% to find out how they look like. However, as far as I miss the time for +% even some basic evaluation I descided to focus only on the Laplacian- +% based gyrification indices that are covered by my DFG project and have +% the best chance for final application. Nevertheless, I do not want to +% remove all the other function now (2018/04/15) although I removed the +% calling main functions in ""cat_surf_parameters"" and ""cat_conf_stools"". +% +% cat_surf_gyrification(type,PS,opt) +% +% PS .. individual central surface file (subject space) +% opt .. structure with different option (see code) +% type .. +% 'sphere': central vs. sphere +% > thin is anatomical usefull measure +% 'inflate': central vs. inflate +% > this works, but depend on the kind and strength +% of the smooting +% 'hullmapping': central vs. hull +% > only normalized output yet +% 'average': central vs. fsavg +% > only normalized output yet +% +% --------------------------------------------------------------------- +% +% Sphere: +% GI as the area-relation between the central surface and the sphere. +% This shows were regions have to be compressed in the registration +% process, but give no information about the anatomical relation. +% +% +% Inflate: +% GI as the area-relation between the central surface and a smooth +% (area-normalized) version of it. High GI regions are the occipital +% and temporal lobe because these structures are overall much thinner +% then other parts of the brain. Subcortical structures on the other +% side show folding below 1. +% Different degree of inflating are possible (opt.inflate = 0..10). +% Furthermore a normalization by the global hull area is maybe useful +% to get a typical GI. +% +% +% Hullmapping: +% GI as the area-relation between the central surface and hull. The +% hull is generated as separate surface and has to be mapped to the +% individual surface mesh. +% There are many options do to the spherical mapping. +% This is just for comparison to the Laplacian GI. +% +% +% Average: +% GI as the area-relation between the central surface and an average +% surface. This will code the individual local volume increasements. +% Different average surface are possible ... +% This is my personal favorite because it describe the individual +% area decreasing/increasing compared to the group or healthy control. +% +% Laplacian: +% The function uses the Laplacian mapping between two boundaries to +% deform the central surface to the position of the hull. +% Although, the laplacian GI is the best local representation of the +% classical GI [Zilles:1989], it has a lot of limitations: +% * It required strong smoothing +% * Due to the hull focus it is a ""sulcation"" measures, that is inverse +% to the development of gyri. +% +% ______________________________________________________________________ +% Robert Dahnke +% Structural Brain Mapping Group +% University Jena +% ______________________________________________________________________ +% $Id$ + + sinfo = cat_surf_info(PS); + + % set default options + if ~exist('opt','var'), opt = struct(); end + def.fsavgDir = fullfile(fileparts(mfilename('fullpath')),'templates_surfaces'); + opt = cat_io_checkinopt(opt,def); clear def; + + def.verb = 1; % be verbose + def.debug = 0; % debuging information + def.trerr = 0; % through error + def.cleanup = 1; % delete temporary surfaces + + + %def.smooth = 0; % smoothing of original data (only for tests) + %def.presmooth = 5; % inflate only: smooth area before GI estimation + %def.inflate = 5; % inflate only: only cat_surf_SGI_inflate with value from 1 to 10 + %def.normalize = 2; % inflate only: normalization: 0 - none, 1 - by smooth, 2 - by smoothed and hull + %def.avgsurf = fullfile(opt.fsavgDir,sprintf('%s.central.freesurfer.gii',sinfo.side)); % fsaverage central + %def.Pfsavg = fullfile(opt.fsavgDir,sprintf('%s.central.freesurfer.gii',sinfo.side)); % fsaverage central + %def.Pfsavgsph = fullfile(opt.fsavgDir,sprintf('%s.sphere.freesurfer.gii',sinfo.side)); % fsaverage sphere + + def.laplaceerr = 0.0001; % laplace volume filter + def.GIpresmooth = 30; % laplacian only: shoold to be greater than 20 .. vary by brain size? - no, because of surf resamp + def.GIstreamopt(1) = 0.01; % stepsize of streamlines in mm... fast=0.05 - 0.01 + def.GIstreamopt(2) = 30 ./ def.GIstreamopt(1); % in mm + def.GIwritehull = 1; % write laplace laplacian hull surface + def.GInorm = 3; % normalization function + def.GIhullmodel = 0; % hull model (0 - hemisphere, 1 - ICV) + def.GIcoremodel = 1; % core model ( ... ) + def.GIcoreth = 0.15; % 0.1 + def.GIsuffix = ''; % GI measure suffix + def.GIprefix = ''; % GI measure prefix + def.cleanup = 0; % remove temporary GI files + + opt = cat_io_checkinopt(opt,def); + + if strcmp( opt.GIsuffix , 'PARA') + opt.GIsuffix = sprintf('_Lerr%d_Sacc',... + opt.laplaceerr,opt.GIstreamopt,GIhullmodel,GIcoremodel,GIcoreth,GIpresmooth); + end + + % call different subroutines + PSgi = cat_surf_SGI_laplacian(sinfo,opt); + %{ + switch lower(type) + case 'sphere', PSgi = cat_surf_SGI_sphere(sinfo,opt); + case 'inflate', PSgi = cat_surf_SGI_inflate(sinfo,opt); + case 'hullmapping', PSgi = cat_surf_SGI_hullmapping(sinfo,opt); + case 'average', PSgi = cat_surf_GI_average(sinfo,opt); + case 'laplacian', PSgi = cat_surf_SGI_laplacian(sinfo,opt); + otherwise + error('cat_surf_gyrification:unknown_type','Unknown type ""%s"".\n',type); + end + %} +end + +function Psgi = cat_surf_SGI_laplacian(sinfo,opt) +%% central vs. hull +% --------------------------------------------------------------------- +% The function use the Laplacian mapping between two boundaries to +% deform the central surface to the position of the hull. +% Although, the laplacian GI is the best local representation of the +% classical GI [Zilles:1989], it has a lot of limitations: +% * It required strong smoothing +% * Due to the hull focus it is a ""sulcation"" measures, that is inverse +% to the development of gyri. +% --------------------------------------------------------------------- + + Phull = char(cat_surf_rename(sinfo,'dataname',[opt.GIprefix 'hull' opt.GIsuffix],'ee','')); + Pcore = char(cat_surf_rename(sinfo,'dataname',[opt.GIprefix 'core' opt.GIsuffix],'ee','')); + Psigi = char(cat_surf_rename(sinfo,'dataname',[opt.GIprefix 'inwardGI' opt.GIsuffix],'ee','')); + Psogi = char(cat_surf_rename(sinfo,'dataname',[opt.GIprefix 'outwardGI' opt.GIsuffix],'ee','')); + Psggi = char(cat_surf_rename(sinfo,'dataname',[opt.GIprefix 'generalizedGI' opt.GIsuffix],'ee','')); + + % load surface and create hull + Scs = gifti(sinfo.Pmesh); + + % translation for fast and simple processing of both sides + Scs.vertices = Scs.vertices - repmat( min(Scs.vertices) , size( Scs.vertices , 1) , 1) + 5; + + %% inward folding GI + % map the central surface to the hull position + if opt.GIL==1 || opt.GIL==3 || opt.GIL==4 || opt.GIcoremodel == 2 + if opt.verb, txt = ' Estimate iGI: '; fprintf(txt); end %cat_io_cmd + + % create hull volume + [Sh,Yh] = cat_surf_fun('hull',Scs); clear Sc; %#ok + [Yo,Yt,mat1] = cat_surf_fun('surf2vol',Scs); clear Yt %#ok + + % estimate mapping + opt.streamopt = opt.GIstreamopt; + S.vertices = Scs.vertices + repmat(mat1,size(Scs.vertices,1),1); + S.faces = Scs.faces; + [S,SH] = cat_surf_GI3D(S,1+Yh+(Yo>0.95),Yh-(Yo>0.95),opt); + + % write surface + if opt.GIwritehull + cat_io_FreeSurfer('write_surf',Phull,SH); + end + + if opt.verb, fprintf(repmat('\b',1,length(txt))); end + end + + + %% outward folding GI + % map the central surface to the core surface + if opt.GIL==2 || opt.GIL==3 || opt.GIL==4 + if opt.verb, fprintf('\n\b'); txt = ' Estimate oGI: '; fprintf(txt); end + switch opt.GIcoremodel + case 1 + % nothing to do + case 2 + %% create iGI-based core volume? + % - looks similar to sulcal depth + % - may use it as relative measure? + GIpresmooth = 1; + Af = cat_surf_smootharea(S,S,GIpresmooth); + Ah = cat_surf_smootharea(S,SH,GIpresmooth,cat_surf_smootharea(S,S,3)*2); + core.iGI = log2 ( Af ./ max(eps,Ah) ) ; + + % normalisation + switch opt.GInorm + case 'log' + eval(sprintf('iGI = %s(max(0,iGI + exp(1)));',opt.GInorm)); + eval(sprintf('oGI = %s(max(0,oGI + exp(1)));',opt.GInorm)); + eval(sprintf('gGI = %s(max(0,gGI + exp(1)));',opt.GInorm)); + case 'log2' + eval(sprintf('iGI = %s(max(0,iGI + 2));',opt.GInorm)); + eval(sprintf('oGI = %s(max(0,oGI + 2));',opt.GInorm)); + eval(sprintf('gGI = %s(max(0,gGI + 2));',opt.GInorm)); + case 'log10' + eval(sprintf('iGI = %s(max(0,iGI + 10));',opt.GInorm)); + eval(sprintf('oGI = %s(max(0,oGI + 10));',opt.GInorm)); + eval(sprintf('gGI = %s(max(0,gGI + 10));',opt.GInorm)); + case {'',1} + % nothing to do + case num2cell(2:10) + core.iGI = nthroot(core.iGI,opt.GInorm); + otherwise + error('Unknown normalization function %s!\n',opt.GInorm); + end + case 3 + %% use sulcal-depth-based core volume? + % - this would support to use PBT for local normalization + % (unfolded brain-hull skeleton) + otherwise + end + + % core estimation + core.type = opt.GIcoremodel; + core.th = opt.GIcoreth; + [Sc,Yc] = cat_surf_fun('core',Scs,core); clear Sc; %#ok + + % estimate mapping + opt.streamopt = opt.GIstreamopt; + S.vertices = Scs.vertices + repmat(mat1,size(Scs.vertices,1),1); + S.faces = Scs.faces; + [S,SC] = cat_surf_GI3D(S,3-(Yc+(Yo>0.05)),(Yo>0.05)-Yc,opt); + + % write surface + if opt.GIwritehull + cat_io_FreeSurfer('write_surf',Pcore,SC); + end + + if opt.verb, fprintf(repmat('\b',1,length(txt))); end + end + + + %% ROI-based evlatuation with non-smoothed data + if 0 % opt.ROI + % 1) (V1) project atlas to individual space + % (V2) resample data to average space + % (use smooth&resample with area/sum-preserving option) + % 2) write data (see cat_main* / cat_surf_*) + % + % Think about common functions + end + + + %% area smoothing and GI estimation + Af = cat_surf_smootharea(S,S,opt.GIpresmooth); + if opt.GIL==1 || opt.GIL==3 || opt.GIL==4 + Ah = cat_surf_smootharea(S,SH,opt.GIpresmooth,cat_surf_smootharea(S,S,3)*2); + iGI = Af ./ max(eps,Ah); + end + if opt.GIL==2 || opt.GIL==3 || opt.GIL==4 + Ac = cat_surf_smootharea(S,SC,opt.GIpresmooth,cat_surf_smootharea(S,S,3)*2); + oGI = Af ./ max(eps,Ac); + end + if opt.GIL==3 || opt.GIL==4 + Sa = SH; Sa.vertices = (Sa.vertices + SC.vertices)/2; + Aa = cat_surf_smootharea(S,Sa,opt.GIpresmooth,cat_surf_smootharea(S,S,3)*2); + gGI = Af ./ max(eps,Aa); + end + + %% normalization function + switch opt.GInorm + case 'log' + if exist('iGI','var'), eval(sprintf('iGI = %s(max(0,iGI + exp(1)));',opt.GInorm)); end + if exist('oGI','var'), eval(sprintf('oGI = %s(max(0,oGI + exp(1)));',opt.GInorm)); end + if exist('gGI','var'), eval(sprintf('gGI = %s(max(0,gGI + exp(1)));',opt.GInorm)); end + case 'log2' + if exist('iGI','var'), eval(sprintf('iGI = %s(max(0,iGI + 2));',opt.GInorm)); end + if exist('oGI','var'), eval(sprintf('oGI = %s(max(0,oGI + 2));',opt.GInorm)); end + if exist('gGI','var'), eval(sprintf('gGI = %s(max(0,gGI + 2));',opt.GInorm)); end + case 'log10' + if exist('iGI','var'), eval(sprintf('iGI = %s(max(0,iGI + 10));',opt.GInorm)); end + if exist('oGI','var'), eval(sprintf('oGI = %s(max(0,oGI + 10));',opt.GInorm)); end + if exist('gGI','var'), eval(sprintf('gGI = %s(max(0,gGI + 10));',opt.GInorm)); end + case {'',1} + % nothing to do + case num2cell(2:10) + if exist('iGI','var'), iGI = nthroot(iGI,opt.GInorm); end + if exist('oGI','var'), oGI = nthroot(oGI,opt.GInorm); end + if exist('gGI','var'), gGI = nthroot(gGI,opt.GInorm); end + otherwise + error('Unknown normalization function %s!\n',opt.GInorm); + end + + + % export textures + if exist('iGI','var'), cat_io_FreeSurfer('write_surf_data',Psigi,iGI); end + if exist('oGI','var'), cat_io_FreeSurfer('write_surf_data',Psogi,oGI); end + if exist('gGI','var'), cat_io_FreeSurfer('write_surf_data',Psggi,gGI); end + + + if 0 + %% internal display + if opt.GIL==1 || opt.GIL==4, cat_surf_display(Psigi); end + if opt.GIL==2 || opt.GIL==4, cat_surf_display(Psogi); end + if opt.GIL==3 || opt.GIL==4, cat_surf_display(Psggi); end + end + + + % in case of exclusive gGI estimation + if opt.GIL==3 && opt.cleanup + delete(Psigi); + delete(Psogi); + end + + + % final output settings + if ~exist(Psigi,'file'), Psigi = ''; end + if ~exist(Psogi,'file'), Psogi = ''; end + if ~exist(Psggi,'file'), Psggi = ''; end + + Psgi = {Psigi;Psogi;Psggi}; +end % central vs. hull (work) + + +function A = cat_surf_smootharea(S,SA,smooth,Amax) +% create smooth area texture files +% --------------------------------------------------------------------- + debug = 0; + + % temporary file names + Pname = tempname; + Pmesh = [Pname 'mesh']; + Parea = [Pname 'area']; + + % estimate areas + SAX.vertices = SA.vertices; SAX.faces = SA.faces; + A = cat_surf_fun('area',SAX); + if exist('Amax','var'); A = min(A,Amax); end + + % write surface and textures + cat_io_FreeSurfer('write_surf',Pmesh,S); + cat_io_FreeSurfer('write_surf_data',Parea,A); + + % smooth textures + cmd = sprintf('CAT_BlurSurfHK ""%s"" ""%s"" ""%g"" ""%s""',Pmesh,Parea,smooth,Parea); + cat_system(cmd,debug); + + % load smoothed textures + A = cat_io_FreeSurfer('read_surf_data',Parea); + + % delete temporary file + delete(Parea); +end + + +%% old subfunction I do not want to remove right now +%{ +function Psgi = cat_surf_SGI_sphere(sinfo,opt) +%% central vs. sphere +% --------------------------------------------------------------------- +% GI as the area-relation between the central surface and the sphere. +% This shows were regions have to be compressed in the registration +% process, but gives no information about the anatomical relation. +% --------------------------------------------------------------------- + Psgi = char(cat_surf_rename(sinfo,'resampled',1,'dataname','SGI','ee','')); + + Scs = gifti(sinfo.Pmesh); + Ssp = gifti(sinfo.Psphere); + + % estiamte and smooth areas + if opt.presmooth>0 + [ASsc,ASsp] = cat_surf_smoothGIarea(sinfo,Scs,Ssp,opt.presmooth); + end + + % estimate GI + GI = cat_surf_estimateGI(Scs,ASsc,ASsp,opt.normalize); + + % write data + cat_io_FreeSurfer('write_surf_data',Psgi,GI); + +end % central vs. sphere (work, but useless) + +function Psgi = cat_surf_SGI_inflate(sinfo,opt) +%% central vs. inflate +% --------------------------------------------------------------------- +% GI as the area-relation between the central surface and a smooth +% version of it. High GI regions are the occipital and temporal lobe +% because these structures are overall much thinner than other parts +% of the brain. Subcortical structures on the other side show folding +% below 1. +% --------------------------------------------------------------------- + + %Psgi = char(cat_surf_rename(sinfo,'dataname',sprintf('IGI%d',opt.inflate),'ee','')); + Psgi = char(cat_surf_rename(sinfo,'dataname','inflateGI','ee','')); + Pinflate = char(cat_surf_rename(sinfo,'dataname','inflate')); + + % spherical mapping of the hull + cmd = sprintf('CAT_Surf2Sphere ""%s"" ""%s"" %d',sinfo.Pmesh,Pinflate,opt.inflate); + cat_system(cmd,opt.debug); + + % load surfaces + Scs = gifti(sinfo.Pmesh); + Ssp = gifti(Pinflate); + + % area smoothing and GI estimation + ASsc = cat_surf_smootharea(Scs,Scs,opt.presmooth); + ASsp = cat_surf_smootharea(Scs,Ssp,opt.presmooth); + + % estimate GI - normalization by area is not required (done by Surf2Sphere) + GI = cat_surf_estimateGI(Scs,ASsc,ASsp,opt.normalize); + + % write data + cat_io_FreeSurfer('write_surf_data',Psgi,GI); + + % smoothing + if opt.smooth>0 + cmd = sprintf('CAT_BlurSurfHK ""%s"" ""%s"" ""%g"" ""%s""',sinfo.Pmesh,Psgi,opt.smooth,Psgi); + cat_system(cmd,opt.debug); + cat_surf_display(Psgi); + end + + % delete temporary files + if opt.cleanup + delete(Pinflate); + end +end % central vs. inflate (work) + +function Psgigii = cat_surf_GI_average(sinfo,opt) +%% central vs. fs average +% --------------------------------------------------------------------- +% GI as the area-relation between the central surface and an average +% surface. This will code the individual local volume increasements. +% --------------------------------------------------------------------- +% does not work yet ... only template space + + Psgi = char(cat_surf_rename(sinfo,'resampled',0,'dataname','averageGI','ee','')); + Ptmp = char(cat_surf_rename(sinfo,'resampled',0,'dataname','tmp','ee','')); + Psgigii = char(cat_surf_rename(sinfo,'resampled',1,'dataname','averageGI')); + Pcentral = char(cat_surf_rename(sinfo,'resampled',1)); + + % resample hull surface in subject space + cmd = sprintf('CAT_ResampleSurf ""%s"" ""%s"" ""%s"" ""%s""',sinfo.Pmesh,sinfo.Psphere,opt.Pfsavgsph,Pcentral); + cat_system(cmd,opt.debug,opt.trerr); + + % load surfaces + Scs = gifti(Pcentral); + Ssp = gifti(opt.avgsurf); + + % area smoothing and GI estimation + ASsc = cat_surf_smootharea(Scs,Scs,opt.presmooth); + ASsp = cat_surf_smootharea(Scs,Ssp,opt.presmooth); + + % estimate GI + GI = cat_surf_estimateGI(Scs,ASsc,ASsp,opt.normalize); + + %% write data + SR = gifti(Pcentral); + SR.cdata = GI; + + save(gifti(SR),Psgigii); + %cat_io_FreeSurfer('write_surf_data',Psgi,GI); + + %% resample hull surface in subject space ... + %cmd = sprintf('CAT_ResampleSurf ""%s"" ""%s"" ""%s"" ""%s"" ""%s"" ""%s""',opt.Pfsavg,opt.Pfsavgsph,sinfo.Pmesh,sinfo.Psphere,Psgi,Psgi); + %cat_system(cmd,opt.debug,opt.trerr); + + %% smoothing + if opt.smooth>0 + %cmd = sprintf('CAT_BlurSurfHK ""%s"" ""%s"" ""%g"" ""%s""',Pcentral,Ptmp,opt.smooth,Psgi); + %cat_system(cmd,opt.debug); + %cat_surf_display(Psgi) + + %% + cmd = sprintf('CAT_BlurSurfHK ""%s"" ""%s"" ""%g"" ""%s""',Pcentral,Ptmp,opt.smooth,Psgi); + cat_system(cmd,opt.debug); + cmd = sprintf('CAT_AddValuesToSurf ""%s"" ""%s"" ""%s""',Pcentral,Ptmp,[Ptmp '.gii']); + cat_system(cmd,opt.debug); + cat_surf_display([Ptmp '.gii']) + end + + + +end % central vs. fs average (work, but only resampled output) + +function Psgi = cat_surf_SGI_hullmapping(sinfo,opt) +%% central vs. hull +% --------------------------------------------------------------------- +% GI as the area-relation between the central surface and hull. +% The hull is generated as separate surface and has to be mapped to the +% individual surface mesh. +% --------------------------------------------------------------------- + + Phull = char(cat_surf_rename(sinfo,'dataname','hull')); + Phullsphere = char(cat_surf_rename(sinfo,'dataname','hullsphere')); + Phullspherereg = char(cat_surf_rename(sinfo,'dataname','hullspherereg')); + PhullR = char(cat_surf_rename(sinfo,'dataname','centralhull')); + Psgi = char(cat_surf_rename(sinfo,'dataname','sphericalGI','ee','')); + + % load surface and create hull + Scs = gifti(sinfo.Pmesh); + + % create hull + Sh = cat_surf_fun('hull',Scs); + + % correct and optimize hull surface + save(gifti(Sh),Phull); + + % remove some unconnected meshes + cmd = sprintf('CAT_SeparatePolygon ""%s"" ""%s"" -1',Phull,Phull); + cat_system(cmd,opt.debug); + + % surface refinement by simple smoothing + cmd = sprintf('CAT_BlurSurfHK ""%s"" ""%s"" %0.2f',Phull,Phull,5); + cat_system(cmd,opt.debug); + + % spherical mapping of the hull + cmd = sprintf('CAT_Surf2Sphere ""%s"" ""%s"" 5',Phull,Phullsphere); + cat_system(cmd,opt.debug); + Phullsphere = Phull; + + % spherical registration to central surface ... -type 0 + cmd = sprintf('CAT_WarpSurf -norot -i ""%s"" -is ""%s"" -t ""%s"" -ts ""%s"" -ws ""%s""',... + Phull,Phullsphere,sinfo.Pmesh,sinfo.Psphere,Phullspherereg); + cat_system(cmd,opt.debug); + + % resample hull surface in subject space + cmd = sprintf('CAT_ResampleSurf ""%s"" ""%s"" ""%s"" ""%s""',Phull,Phullspherereg,sinfo.Psphere,PhullR); + cat_system(cmd,opt.debug,opt.trerr); + + %% load surfaces + Scs = gifti(sinfo.Pmesh); + Ssp = gifti(PhullR); + + % area smoothing and GI estimation + ASsc = cat_surf_smootharea(Scs,Scs,opt.presmooth); + ASsp = cat_surf_smootharea(Scs,Ssp,opt.presmooth); + + % estimate GI + GI = ASsc ./ ASsp; + + % write data + cat_io_FreeSurfer('write_surf_data',Psgi,GI); + + % smoothing + if opt.smooth>0 + cmd = sprintf('CAT_BlurSurfHK ""%s"" ""%s"" ""%g"" ""%s""',sinfo.Pmesh,Psgi,opt.smooth,Psgi); + cat_system(cmd,opt.debug); + cat_surf_display(Psgi) + end + + delete(Phullspherereg); + if opt.cleanup + delete(Phull); + %delete(Phullsphere); + delete(PhullR); + end +end % central vs. hull (work, but only resampled output) + +function GI = cat_surf_estimateGI(Scs,ASsc,ASsp,normalize) + % estimate GI - normalization by area is not required (done by Surf2Sphere) + if normalize==0 % no normalization + GI = ASsc ./ ASsp; + elseif normalize==1 % normalization to 1 + GI = (ASsc/sum(ASsc)) ./ (ASsp/sum(ASsp)); + %GI = (ASsc ./ ASsp) ./ (sum(ASsc)/sum(ASsp)); + elseif normalize==2 % normalization to hullarea + Sh = cat_surf_fun('hull',Scs); + ASh = cat_surf_fun('area',Sh); + GI = ASsc ./ ASsp .* ((sum(ASsp) ./ sum(ASsc)) .* (sum(ASsc) ./ sum(ASh))); + end +end + +%} +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_run_job1639.m",".m","71223","1526","function cat_run_job1639(job,tpm,subj) +% run CAT +% ______________________________________________________________________ +% +% Initialization functions for the CAT preprocessing +% * creation of the subfolder structure (if active) +% * check of image resolution (avoid scans with very low resolution) +% * interpolation +% * affine preprocessing (APP) +% >> cat_run_job_APP_init +% >> cat_run_job_APP_final +% * affine registration +% * initial SPM preprocessing +% +% cat_run_job(job,tpm,subj) +% +% job .. SPM job structure with main parameter +% tpm .. tissue probability map (hdr structure) +% subj .. file name +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +%#ok<*WNOFF,*WNON> + + job.test_warnings = 0; % just for tests + + % if there is a breakpoint in this file set debug=1 and do not clear temporary variables + dbs = dbstatus; debug = 0; for dbsi=1:numel(dbs), if strcmp(dbs(dbsi).name,mfilename); debug = 1; break; end; end + + clearvars -global cat_err_res; + global cat_err_res; % for CAT error report + cat_err_res.stime = clock; + cat_err_res.cat_warnings = cat_io_addwarning('reset'); % reset warnings + stime = clock; + stime0 = stime; % overall processing time + + % create subfolders if not exist + pth = spm_fileparts(job.channel(1).vols{subj}); + [mrifolder, reportfolder, surffolder, labelfolder] = cat_io_subfolders(job.channel(1).vols{subj},job); + + if job.extopts.subfolders + + folders = {mrifolder,reportfolder}; + warning('off', 'MATLAB:MKDIR:DirectoryExists'); + for i=1:numel(folders) + [stat, msg] = mkdir(fullfile(pth,folders{i})); + if ~stat + fprintf('%s: Error while creating directory %s\n\n\n',msg,fullfile(pth,folders{i})); + return + end + end + + if ~exist(fullfile(pth,surffolder),'dir') && job.output.surface + [stat, msg] = mkdir(fullfile(pth,surffolder)); + if ~stat + fprintf('%s: Error while creating directory %s\n\n\n',msg,fullfile(pth,surffolder)); + return + end + end + + if ~exist(fullfile(pth,labelfolder),'dir') && job.output.ROI + [stat, msg] = mkdir(fullfile(pth,labelfolder)); + if ~stat + fprintf('%s: Error while creating directory %s\n\n\n',msg,fullfile(pth,labelfolder)); + return + end + end + + end + + % create subject-wise diary file with the command-line output + [pp,ff,ee,ex] = spm_fileparts(job.data{subj}); %#ok + % sometimes we have to remove .nii from filename if files were zipped + catlog = fullfile(pth,reportfolder,['catlog_' strrep(ff,'.nii','') '.txt']); + if exist(catlog,'file'), delete(catlog); end % write every time a new file, turn this off to have an additional log file + + % check if not another diary is already written that is not the default- or catlog-file. + if ~strcmpi(spm_check_version,'octave') + olddiary = spm_str_manip( get(0,'DiaryFile') , 't'); + usediary = ~isempty(strfind( olddiary , 'diary' )) || ~isempty(strfind( olddiary , 'catlog_' )); + if usediary + diary(catlog); + diary on; + else + cat_io_cprintf('warn',sprintf('External diary log is written to ""%s"".\n',get(0,'DiaryFile'))); + end + else + % always use diary and don't check for old one for Octave + usediary = 1; + diary(catlog); + diary on; + end + + % print current CAT release number and subject file + [n,r] = cat_version; + str = sprintf('%s r%s: %d/%d',n,r,subj,numel(job.channel(1).vols)); + str2 = spm_str_manip(job.channel(1).vols{subj}(1:end-2),['a' num2str(70 - length(str))]); + cat_io_cprintf([0.2 0.2 0.8],'\n%s\n%s: %s%s\n%s\n',... + repmat('-',1,72),str,... + repmat(' ',1,70 - length(str) - length(str2)),str2,... + repmat('-',1,72)); + clear r str str2 + + + % ----------------------------------------------------------------- + % separation of full CAT preprocessing and SPM segmentation + % preprocessing (running DARTEL and PBT with SPM segmentation) + % ----------------------------------------------------------------- + [pp,ff,ee,ex] = spm_fileparts(job.data{subj}); + if exist(fullfile(pp,['c1' ff(3:end) ee]),'file') && ... + exist(fullfile(pp,['c2' ff(3:end) ee]),'file') && ... + ... exist(fullfile(pp,['c3' ff(3:end) ee]),'file') && ... + exist(fullfile(pp,[ff(3:end) '_seg_sn.mat']),'file') && ... + strcmp(ff(1:2),'c1') + + cat_io_cprintf('blue','Load SPM old-segment segmentation (*seg_sn.mat)\n ') + + % create field also for dependency setup + if ~isfield(job.extopts,'spmAMAP'), job.extopts.spmAMAP = 0; end + + job.data{subj} = fullfile(pp,[ff ee]); + job.channel.vols{subj} = fullfile(pp,[ff ee]); + + % prepare SPM preprocessing structure + images = job.channel(1).vols{subj}; + for n = 2:numel(job.channel) + images = char(images,job.channel(n).vols{subj}); + end + Pseg8 = fullfile(pp,[ff(3:end) '_seg_sn.mat']); + reso = load(Pseg8); + res = reso.flags; + res.segsn = reso; + + % prepare spm classes (the GUI limits this to 3 images + automatic background class) + for ti = 1:numel(res.ngaus) + job.tissue(ti).ngaus = res.ngaus(ti); + job.tissue(ti).tpm = reso.VG(min(ti,numel(reso.VG))).fname; + end + job.tissue(numel(res.ngaus)+1:end) = []; + + % create class parameter variable + res.lkp = []; + if all(isfinite(cat(1,res.ngaus))) + for k=1:numel(res.ngaus) + res.lkp = [res.lkp ones(1,job.tissue(k).ngaus)*k]; + end + end + + % update template data and load template + res.tpm = reso.VG; + if numel(res.lkp) == numel(res.mg) + for lkpi = 1:max(res.lkp) + res.mg(res.lkp==lkpi) = res.mg(res.lkp==lkpi) / sum(res.mg(res.lkp==lkpi)); + end + end + res.mn = res.mn'; + tpm = spm_load_priors8(res.tpm); + + obj.image = spm_vol(images); + obj.fwhm = job.opts.fwhm; + obj.affreg = res.regtype; + obj.biasreg = res.biasreg; + obj.biasfwhm = res.biasfwhm; + obj.tol = NaN; + obj.reg = res.warpreg; + obj.samp = res.samp; + obj.lkp = res.lkp; + obj.tpm = tpm; + + % prepare the internal T1 map + cfname = fullfile(pp,[ff ee]); + ofname = fullfile(pp,[ff(3:end) ee]); + nfname = fullfile(pp,mrifolder,['n' ff '.nii']); + copyfile(ofname,nfname,'f'); + + % update option fields + job.opts.tpm = {reso.VG(1).fname}; + job.opts.biasreg = res.biasreg; + job.opts.biasfwhm = res.biasfwhm; + job.opts.samp = res.samp; + job.opts.tpm = res.tpm(1).fname; + job.opts.biasreg = res.biasreg; + % [abs.-displacement, membran-engery, bending-engery, linear-elasticity 2x ] + job.opts.warpreg = nan(1,5); % this does not fit to the old parameter + job.extopts.shootingT1 = job.extopts.T1; + job.channel(1).vols{subj} = [nfname ex]; + job.channel(1).vols0{subj} = [ofname ex]; + res.image = spm_vol([nfname ex]); + res.image0 = spm_vol([ofname ex]); + res.imagec = spm_vol([cfname ex]); + res.spmpp = 1; + job.spmpp = 1; + + % load volumes + Ysrc0 = single(spm_read_vols(obj.image)); + Ylesion = single(isnan(Ysrc0) | isinf(Ysrc0) | Ysrc0==0); clear Ysrc0; + + % prepare error sturture + cat_err_res.obj = obj; + + elseif exist(fullfile(pp,['c1' ff(3:end) ee]),'file') && ... + exist(fullfile(pp,['c2' ff(3:end) ee]),'file') && ... + exist(fullfile(pp,['c3' ff(3:end) ee]),'file') && ... + exist(fullfile(pp,[ff(3:end) '_seg8.mat']),'file') && strcmp(ff(1:2),'c1') + + cat_io_cprintf('blue','Load SPM segment segmentation (*seg8.mat)\n ') + + % create field also for dependency setup + if ~isfield(job.extopts,'spmAMAP'), job.extopts.spmAMAP = 0; end + + job.data{subj} = fullfile(pp,[ff ee]); + job.channel.vols{subj} = fullfile(pp,[ff ee]); + + % prepare SPM preprocessing structure + images = job.channel(1).vols{subj}; + for n=2:numel(job.channel) + images = char(images,job.channel(n).vols{subj}); + end + + obj.image = spm_vol(images); + obj.fwhm = job.opts.fwhm; + obj.biasreg = cat(1,job.opts.biasreg); + obj.biasfwhm = cat(1,job.opts.biasfwhm); + obj.tol = job.opts.tol; + obj.lkp = []; + obj.reg = job.opts.warpreg; + obj.samp = job.opts.samp; + spm_check_orientations(obj.image); + + if all(isfinite(cat(1,job.tissue.ngaus))) + for k=1:numel(job.tissue) + obj.lkp = [obj.lkp ones(1,job.tissue(k).ngaus)*k]; + end + end + + Pseg8 = fullfile(pp,[ff(3:end) '_seg8.mat']); + if ~exist(Pseg8,'file') + error('cat_run_job1639:SPMpp_MissSeg8mat','Can''t find ""%s"" file!',Pseg8); + end + res = load(Pseg8); + + % load tpm priors + tpm = spm_load_priors8(res.tpm); + obj.lkp = res.lkp; + obj.tpm = tpm; + + % Special cases with different class numbers in case of SPM input + if max(obj.lkp)==6 + % default cases + elseif max(obj.lkp)==3 + cat_io_addwarning('SPMpp_PostMortem','Detected only 3 classes that are interpretated as GM, WM, and CSF/background.',0,[0 1]) + elseif max(obj.lkp)==4 + cat_io_addwarning('SPMpp_SkullStripped','Detected only 4 classes that are interpretated as GM, WM, CSF, and background',0,[0 1]) + else + cat_io_addwarning('SPMpp_AtypicalClsNumber',sprintf('Atypical number of input classes (max(lkp)=%d).',max(obj.lkp)),2,[0 1]) + end + + + cfname = fullfile(pp,[ff ee]); + ofname = fullfile(pp,[ff(3:end) ee]); + nfname = fullfile(pp,mrifolder,['n' ff '.nii']); + copyfile(ofname,nfname,'f'); + + Ysrc0 = single(spm_read_vols(obj.image)); + Ylesion = single(isnan(Ysrc0) | isinf(Ysrc0) | Ysrc0==0); clear Ysrc0; + + + job.channel(1).vols{subj} = [nfname ex]; + job.channel(1).vols0{subj} = [ofname ex]; + res.image = spm_vol([nfname ex]); + res.image0 = spm_vol([ofname ex]); + res.imagec = spm_vol([cfname ex]); + res.spmpp = 1; + job.spmpp = 1; + + % prepare error sturture + cat_err_res.obj = obj; + else + + % ----------------------------------------------------------------- + % check resolution properties + % ----------------------------------------------------------------- + % There were some images that should not be processed. So we have + % to check for large slice thickness and low spatial resolution. + % RD201909: I tried 4x4x4 and 1x1x8 mm data with default and NLM + % interpolation. Also NLM shows less edges and more + % correct surfaces, the thickness results are worse and + % the limits are ok. + % RD202007: Low resolution data is now allowed if ignoreErrer > 1. + % Tested again NLM and Boeseflug interpolation and there + % are many artefacts and simple spline interpolation is + % more save. + % RD202107: Print warning for reslimit/2 and alert for reslimit. + % ----------------------------------------------------------------- + for n=1:numel(job.channel) + V = spm_vol(job.channel(n).vols{subj}); + vx_vol = sqrt(sum(V.mat(1:3,1:3).^2)); + + % maximum [ slice-thickness , volume^3 , anisotropy ] + reslimits = [5 4 8]; + + % too thin slices + if any( vx_vol > reslimits(1) ) || job.test_warnings + mid = [mfilename 'cat_run_job:TooLowResolution']; + msg = sprintf(['Voxel resolution should be better than %d mm in any dimension for \\\\n' ... + 'reliable preprocessing! This image has a resolution of %0.2fx%0.2fx%0.2f mm%s. '], ... + reslimits(1),vx_vol,native2unicode(179, 'latin1')); + cat_io_addwarning(mid,msg,1 + any( vx_vol > reslimits(1) ) ,[0 1],vx_vol); + end + + % too small voxel volume (smaller than 3x3x3 mm3) + if prod(vx_vol) > (reslimits(2))^3 || job.test_warnings + mid = [mfilename 'cat_run_job:TooLargeVoxelVolume']; + msg = sprintf(['Voxel volume should be smaller than %d mm%s (around %dx%dx%d mm%s) for \\\\n' ... + 'reliable preprocessing! This image has a voxel volume of %0.2f mm%s. '], ... + reslimits(2)^3,native2unicode(179, 'latin1'),reslimits(2),reslimits(2),reslimits(2),... + native2unicode(179, 'latin1'),prod(vx_vol),native2unicode(179, 'latin1')); + cat_io_addwarning(mid,msg,1 + (prod(vx_vol) > reslimits(2)^3),[0 1],vx_vol); + end + + % anisotropy + if max(vx_vol) / min(vx_vol) > reslimits(3) || job.test_warnings + mid = [mfilename 'cat_run_job:TooStrongAnisotropy']; + msg = sprintf(['Voxel anisotropy (max(vx_size)/min(vx_size)) should be smaller than %d for \\\\n' ... + 'reliable preprocessing! This image has a resolution %0.2fx%0.2fx%0.2f mm%s \\\\nand a anisotropy of %0.2f. '], ... + reslimits(3),vx_vol,native2unicode(179, 'latin1'),max(vx_vol)/min(vx_vol)); + cat_io_addwarning(mid,msg,1 + (max(vx_vol) / min(vx_vol) > reslimits(3)/3),[0 1],vx_vol); + end + end + + % save original file name + for n=1:numel(job.channel) + job.channel(n).vols0{subj} = job.channel(n).vols{subj}; + end + + + % always create the n*.nii image because of the real masking of the + % T1 data for spm_preproc8 that includes rewriting the image! + for n=1:numel(job.channel) + [pp,ff,ee] = spm_fileparts(job.channel(n).vols{subj}); + ofname = fullfile(pp,[ff ee]); + nfname = fullfile(pp,mrifolder,['n' ff '.nii']); + if strcmp(ee,'.nii') + if ~copyfile(ofname,nfname,'f') + spm('alert!',sprintf('ERROR: Check file permissions for folder %s.\n',fullfile(pp,mrifolder)),'',spm('CmdLine'),1); + end + elseif strcmp(ee,'.img') + V = spm_vol(job.channel(n).vols{subj}); + Y = spm_read_vols(V); + V.fname = nfname; + spm_write_vol(V,Y); + clear Y; + end + job.channel(n).vols{subj} = nfname; + + %% denoising + if job.extopts.NCstr~=0 + NCstr.labels = {'none','full','light','medium','strong','heavy'}; + NCstr.values = {0 1 2 -inf 4 5}; + stime = cat_io_cmd(sprintf('SANLM denoising (%s)',... + NCstr.labels{find(cell2mat(NCstr.values)==job.extopts.NCstr,1,'first')})); + cat_vol_sanlm(struct('data',nfname,'verb',0,'prefix','','NCstr',job.extopts.NCstr)); + fprintf('%5.0fs\n',etime(clock,stime)); + end + + %% skull-stripping detection + % ------------------------------------------------------------ + % Detect skull-stripping or defaceing because it strongly + % affects SPM segmentation that expects gaussian distribution! + % If a brain mask was used than we expect + % - many zeros (50% for small background - 80-90% for large backgrounds) + % - a smaller volume because of missing skull (below 2500 cm3) + % - only one object (the masked regions) + % - only one background (not in every case?) + % - less variance of tissue intensity (only 3 brain classes) + % ------------------------------------------------------------ + VFn = spm_vol(nfname); + YF = spm_read_vols(VFn); + Oth = cat_stat_nanmean(YF(YF(:)~=0 & YF(:)>cat_stat_nanmean(YF(:)))); + BGth = median(YF(YF(:) < Oth/2)); + YBG = ~cat_vol_morph(~cat_vol_morph(YF<=BGth,'lc',1),'lc',1); + Oth = cat_stat_nanmean(YF(~YBG(:) & YF(:)>cat_stat_nanmean(YF(:)))); + F0vol = cat_stat_nansum(~YBG(:)) * prod(vx_vol) / 1000; + F0std = cat_stat_nanstd(YF(YF(:)>0.5*Oth & ~YBG(:))/Oth); +% ######## RD202306: not adapted for MP2RAGE - check cat_run_job later + %% + [YL,numo] = spm_bwlabel(double(~YBG),26); clear YL; %#ok % number of objects + [YL,numi] = spm_bwlabel(double( YBG),26); clear YL; %#ok % number of background regions + ppe.affreg.skullstrippedBGth = BGth; + ppe.affreg.skullstrippedpara = [sum(YBG(:))/numel(YBG(:)) numo numi F0vol F0std]; + ppe.affreg.skullstripped = ... + ppe.affreg.skullstrippedpara(1)>0.5 && ... % many zeros + ppe.affreg.skullstrippedpara(2)<15 && ... % only a few objects + ppe.affreg.skullstrippedpara(3)<10 && ... % only a few background regions + F0vol<2500 && F0std<0.5; % many zeros and not too big +% RD20220301: Need further test on trimmed data. + ppe.affreg.skullstripped = ppe.affreg.skullstripped || ... + sum([ppe.affreg.skullstrippedpara(1)>0.8 F0vol<1500 F0std<0.4])>1; % or 2 extreme values + if ~debug, clear YFC F0vol F0std numo numi; end + % not automatic detection in animals + ppe.affreg.skullstripped = ppe.affreg.skullstripped && strcmp(job.extopts.species,'human') && job.extopts.gcutstr<10; + + + %% high intensity background (MP2Rage) + % RD202008: improved object detection with gradient + [YF,R]= cat_vol_resize(YF,'reduceV',vx_vol,2,32,'meanm'); + YFm = cat_stat_histth(YF,[0.95 0.95],struct('scale',[0 1])); + Yg = cat_vol_grad(YFm,R.vx_volr); + gth = max(0.05,min(0.2,median(Yg(Yg(:)>median(Yg(Yg(:)>0.1)))))); % object edge threshold + YOB = abs(YFm)>0.1 & Yg>gth; % high intensity object edges + YOB = cat_vol_morph(YOB,'ldc',8/mean(R.vx_volr)); % full object + % image pricture frame to test for high intensity background in case of defaced data + hd = max(3,round(0.03 * size(YF))); + YCO = true(size(YF)); YCO(hd(1):end-hd(1)+1,hd(2):end-hd(2)+1,hd(3):end-hd(3)+1) = false; + % background + if sum(YOB(:)>0)0)>numel(YOB)*0.1 % if there is a meanful background + YBG = ~cat_vol_morph(YOB,'lc',2/mean(R.vx_volr)); % close noisy background + elseif ppe.affreg.skullstripped % RD20220316: added skull-stripping case to avoid warning + YBG = YF==0; + else + YBG = ~cat_vol_morph(YOB,'lc',2/mean(R.vx_volr)); + msg = [mfilename ': Detection of background failed.']; + cat_io_addwarning('cat_run_job:failedBGD',msg,1,[0 1]); + end + ppe.affreg.highBGpara = [ ... + cat_stat_nanmedian( YFm( YBG(:) > 1/3 )) ... normal background + cat_stat_nanmedian( YFm( YCO(:) > 1/3 )) ... pricture frame background + cat_stat_nanstd( YFm(YBG(:)) > 1/3)]; % I am not sure if we should use the std, because inverted images are maybe quite similar + ppe.affreg.highBG = ... + ppe.affreg.highBGpara(1) > 1/5 || ... + ppe.affreg.highBGpara(2) > 1/5; + + + %% Interpolation + % ----------------------------------------------------------------- + % The interpolation can help reducing problems for morphological + % operations for low resolutions and strong isotropic images. + % Especially for Dartel registration a native resolution larger than the Dartel + % resolution helps to reduce normalization artifacts of the + % deformations. Furthermore, even if artifacts can be reduced by the final smoothing + % it is much better to avoid them. + + % prepare header of resampled volume + Vi = spm_vol(job.channel(n).vols{subj}); + vx_vol = sqrt(sum(Vi.mat(1:3,1:3).^2)); +% vx_vol = round(vx_vol*10^2)/10^2; % avoid small differences + + % we have to look for the name of the field due to the GUI job struct generation! + restype = char(fieldnames(job.extopts.restypes)); + switch restype + case 'native' + vx_voli = vx_vol; + case 'fixed' + vx_voli = min(vx_vol ,job.extopts.restypes.(restype)(1) ./ ... + ((vx_vol > (job.extopts.restypes.(restype)(1)+job.extopts.restypes.(restype)(2)))+eps)); + vx_voli = max(vx_voli,job.extopts.restypes.(restype)(1) .* ... + ( vx_vol < (job.extopts.restypes.(restype)(1)-job.extopts.restypes.(restype)(2)))); + case 'best' + best_vx = max( min(vx_vol) ,job.extopts.restypes.(restype)(1)); + vx_voli = min(vx_vol ,best_vx ./ ((vx_vol > (best_vx + job.extopts.restypes.(restype)(2)))+eps)); + case 'optimal' + %% + aniso = @(vx_vol) (max(vx_vol) / min(vx_vol)^(1/3))^(1/3); % penetration factor + volres = @(vx_vol) repmat( round( aniso(vx_vol) * prod(vx_vol)^(1/3) * 10)/10 , 1 , 3); % volume resolution + optresi = @(vx_vol) min( job.extopts.restypes.(restype)(1) , max( median(vx_vol) , volres(vx_vol) ) ); % optimal resolution + optdiff = @(vx_vol) abs( vx_vol - optresi(vx_vol) ) < job.extopts.restypes.(restype)(2); % tolerance limites + optimal = @(vx_vol) vx_vol .* optdiff(vx_vol) + optresi(vx_vol) .* (1 - optdiff(vx_vol) ); % final optimal resolution + vx_voli = optimal(vx_vol); + otherwise + error('cat_run_job:restype','Unknown resolution type ''%s''. Choose between ''fixed'',''native'',''optimal'', and ''best''.',restype) + end + + % interpolation + if any( (vx_vol ~= vx_voli) ) + stime = cat_io_cmd(sprintf('Internal resampling (%4.2fx%4.2fx%4.2fmm > %4.2fx%4.2fx%4.2fmm)',vx_vol,vx_voli)); + + if 1 + imat = spm_imatrix(Vi.mat); + Vi.dim = round(Vi.dim .* vx_vol./vx_voli); + imat(7:9) = vx_voli .* sign(imat(7:9)); + Vi.mat = spm_matrix(imat); clear imat; + Vn = spm_vol(job.channel(n).vols{subj}); + cat_vol_imcalc(Vn,Vi,'i1',struct('interp',2,'verb',0,'mask',-1)); + else + %% Small improvement for CAT12.9 that uses the cat_vol_resize function rather than the simple interpolation. + % However, postive effects only in case of strong reductions >2, ie. it is nearly useless. + jobr = struct(); + jobr.data = {Vi.fname}; + jobr.interp = -3005; % spline with smoothing in case of downsampling; default without smoothing -5; + jobr.verb = debug; + jobr.lazy = 0; + jobr.prefix = ''; + jobr.restype.res = vx_voli; % use other resolution for test + Pr = cat_vol_resize(jobr); + + if 0 + % test reinterpolation and estimate the RMSE + jobr.data = Pr.res; + jobr = rmfield(jobr,'restype'); + jobr.restype.Pref = {V.fname}; + jobr.prefix = 'I'; + Pre = cat_vol_resize(jobr); + disp('.'); + + Yo = spm_read_vols(V); + Yr = spm_read_vols(spm_vol(Pre.res{1})); + fprintf('%16.8f\n',sqrt( mean((Yo(:) - Yr(:)).^2))); + end + end + vx_vol = vx_voli; + + fprintf('%5.0fs\n',etime(clock,stime)); + else + vx_vol = sqrt(sum(Vi.mat(1:3,1:3).^2)); + end + + clear Vi Vn; + + + %% Affine Preprocessing (APP) with SPM + % ------------------------------------------------------------ + % Bias correction is essential for stable affine registration + % but also the following preprocessing. This approach uses the + % SPM Unified segmentation for intial bias correction of the + % input data with different FWHMs (low to high frequency) and + % resolutions (low to high). + % ------------------------------------------------------------ + if job.extopts.APP == 1 + job.subj = subj; + [Ym,Ybg,WMth] = cat_run_job_APP_SPMinit(job,tpm,ppe,n,... + ofname,nfname,mrifolder,ppe.affreg.skullstripped); + end + end + job.extopts.gcutstr = mod(job.extopts.gcutstr,10); + + + + % MP2RAGE skull-stripping & bias-correction + if ppe.affreg.highBG + stime = cat_io_cmd('Additional MP2RAGE preprocessing'); + + % mp2rage preprocessing options + mp2job.ofiles = {ofname}; + mp2job.files = {nfname}; % list of MP2Rage images + mp2job.headtrimming = 0; % trimming to brain or head (*0-none*,1-brain,2-head) + mp2job.biascorrection = 1; % biascorrection (0-no,1-light(SPM60mm),2-average(SPM60mm+X,3-strong(SPM30+X)) ####### + mp2job.skullstripping = 3; % skull-stripping (0-no, 1-SPM, 2-optimized, 3-*background-removal*) + mp2job.logscale = inf; % use log/exp scaling for more equally distributed + % tissues (0-none, 1-log, -1-exp, inf-*auto*); + mp2job.intnorm = -.25; % contrast normalization using the tan of GM normed + % values with values between 1.0 - 2.0 for light to + % strong adaptiong (0-none, 1..2-manuel, -0..-2-*auto*) + mp2job.restoreLCSFnoise = 1; % restore values below zero (lower CSF noise) + mp2job.prefix = ''; % filename prefix (strong with PARA for parameter + % depending naming, e.g. ... ) + mp2job.spm_preprocessing = 2; % do SPM preprocessing (0-no, 1-yes (if required), 2-always) + mp2job.spm_cleanupfiles = 1; % remove temporary files + mp2job.report = 0; % create a report + mp2job.verb = 0; % be verbose (0-no,1-yes,2-details) + + % adapt tissue class number + job.opts.ngaus(3) = 1; % at least for CSF we should avoid further peaks + if mp2job.skullstripping>0 % no skull-stripping triggered non-T1 case + % with skull-stripping we keep things simple + job.opts.ngaus(4) = 1; + job.opts.ngaus(5) = 1; + job.opts.ngaus(6) = 1; + end + + % call mp2rage preprocessing + cat_vol_mp2rage(mp2job); + ppe.affreg.skullstripped = mp2job.skullstripping==1 | mp2job.skullstripping==2; + + fprintf('%5.0fs\n',etime(clock,stime)); + end + + + + %% prepare SPM preprocessing structure + images = job.channel(1).vols{subj}; + for n=2:numel(job.channel) + images = char(images,job.channel(n).vols{subj}); + end + obj.image = spm_vol(images); + obj.fwhm = job.opts.fwhm; + obj.biasreg = job.opts.biasreg; + obj.biasfwhm = job.opts.biasfwhm; + obj.tpm = tpm; + obj.reg = job.opts.warpreg; + obj.samp = job.opts.samp; % resolution of SPM preprocessing (def. 3, 1.5 as last highest TPM optimal level) + obj.tol = job.opts.tol; % stopping criteria for SPM iteration of outer/inner loops + obj.newtol = 1 + ( isfield(job,'useprior') && ~isempty(job.useprior) ); + % stopping criteria for outer (=tol) and inner loop: + % -1-old SPM (>9 iters, inner=tol), + % 0-old CAT more outer iterations (>19 iter, inner=tol), + % 1-new optimal/faster with additional AUC criteria to have SPM minimum iterations (>9 iters, inner=1e-2) + % 2-new accurate with additioal AUC criteria but CAT minimum iterations (>19 iter, outer=tol, inner=1e-4) - like 0 + obj.lkp = []; + if ~strcmp('human',job.extopts.species) + % RD202105: There are multiple problems in primates and increased + % accuracy is maybe better (eg. 0.5 - 0.66) + scannorm = 0.7; %prod(obj.image.dims .* vx_vol).^(1/3) / 20; % variance from typical field fo view to normalized parameter + obj.samp = obj.samp * scannorm; % normalize by voxel size + obj.fwhm = obj.fwhm * scannorm; + end + if all(isfinite(cat(1,job.tissue.ngaus))) + for k=1:numel(job.tissue) + obj.lkp = [obj.lkp ones(1,job.tissue(k).ngaus)*k]; + end + end + spm_check_orientations(obj.image); + cat_err_res.obj = obj; + + %% Initial affine registration. + % ----------------------------------------------------------------- + [pp,ff] = spm_fileparts(job.channel(1).vols{subj}); + Pbt = fullfile(pp,mrifolder,['brainmask_' ff '.nii']); + Pb = char(job.extopts.brainmask); + Pt1 = char(job.extopts.T1); + + if ~isempty(job.opts.affreg) + % first affine registration (with APP) + + % load template and remove the skull if the image is skull-stripped + try + VG = spm_vol(Pt1); + catch + pause(rand(1)) + VG = spm_vol(Pt1); + end + VF = spm_vol(obj.image(1)); + + % skull-stripping of the template + if ppe.affreg.skullstripped || job.extopts.gcutstr<0 + % print a warning for all users that did not turn off skull-stripping + % because processing of skull-stripped data is not standard! + if (job.extopts.gcutstr>=0 || job.test_warnings) && ~ppe.affreg.highBG + msg = [... + 'Detected skull-stripped or strongly masked image. Skip APP. \\n' ... + 'Use skull-stripped initial affine registration template and \\n' ... + 'TPM without head tissues (class 4 and 5)!']; + if job.extopts.verb>1 && job.extopts.expertgui + msg = [msg sprintf(['\\\\n BG: %0.2f%%%%%%%% zeros; %d object(s); %d background region(s) \\\\n' ... + ' %4.0f cm%s; normalized SD of all tissues %0.2f'],... + ppe.affreg.skullstrippedpara(1:4),native2unicode(179, 'latin1'),ppe.affreg.skullstrippedpara(5))]; + end + cat_io_addwarning([mfilename 'skullStrippedInputWithSkullStripping'],msg,1,[0 1],ppe.affreg.skullstrippedpara); + + elseif job.extopts.gcutstr<0 && ~ppe.affreg.skullstripped || job.test_warnings + cat_io_addwarning([mfilename 'noSkullStrippingButSkull'],[... + 'Skull-Stripping is deactivated but skull was detected. \\n' ... + 'Go on without skull-stripping what possibly will fail.'],0,[0 1],ppe.affreg.skullstrippedpara); + end + + % skull-stripping of the template + VB = spm_vol(Pb); + [VB2,YB] = cat_vol_imcalc([VG,VB],Pbt,'i1 .* i2',struct('interp',3,'verb',0,'mask',-1)); + VB2.dat(:,:,:) = eval(sprintf('%s(YB/max(YB(:))*255);',spm_type(VB2.dt))); + VB2.pinfo = repmat([1;0],1,size(YB,3)); + VG = cat_spm_smoothto8bit(VB2,0.5); + clear VB2 YB; + end + + % Rescale images so that globals are better conditioned + VF.pinfo(1:2,:) = VF.pinfo(1:2,:)/spm_global(VF); + VG.pinfo(1:2,:) = VG.pinfo(1:2,:)/spm_global(VG); + + % APP step 1 rough bias correction and preparation of the affine + % registration + % -------------------------------------------------------------- + % Already for the rough initial affine registration a simple + % bias corrected and intensity scaled image is required, because + % large head intensities can disturb the whole process. + % -------------------------------------------------------------- + % ds('l2','',vx_vol,Ym, Yt + 2*Ybg,obj.image.private.dat(:,:,:)/WMth,Ym,60) + if job.extopts.APP == 1070 && ... %%%%%%%%~ppe.affreg.highBG && ... + ( ~isfield(job,'useprior') || isempty(job.useprior) ) + stime = cat_io_cmd('Affine preprocessing (APP)'); + Ysrc = single(obj.image.private.dat(:,:,:)); + try + [Ym,Yt,Ybg,WMth] = cat_run_job_APP_init1070(Ysrc,vx_vol,job.extopts.verb); %#ok + catch apperr + %% very simple affine preprocessing ... only simple warning + cat_io_addwarning([mfilename ':APPerror'],'APP failed. Use simple scaling.',1,[0 0],apperr); + [Ym,Yt,Ybg,WMth] = APPmini(obj,VF); %#ok + if cat_get_defaults('extopts.send_info') + urlinfo = sprintf('%s%s%s%s%s%s%s%s%s%s',cat_version,'%2F',computer,'%2F','errors',... + '%2F','cat_run_job:failedAPP','%2F','WARNING: APP failed. Use simple scaling.','cat_run_job'); + cat_io_send_to_server(urlinfo); + end + end + APPRMS = checkAPP(Ym,Ysrc); + if APPRMS>1 || job.test_warnings + if job.extopts.ignoreErrors < 1 + fprintf('\n'); + error('cat_run_job:APPerror','Detect problems in APP preprocessing (APPRMS: %0.4f). Do not use APP results. ',APPRMS); + else + cat_io_addwarning([mfilename ':APPerror'],... + sprintf('Detect problems in APP preprocessing (APPRMS: %0.4f). \\\\nDo not use APP results. ',APPRMS),1,[0 1],APPRMS); + end + end + + if ~debug, clear Yt; end + + if ~( job.extopts.setCOM && ~( isfield(job,'useprior') && ~isempty(job.useprior) ) ) %%%%%%%% && ~ppe.affreg.highBG ) + stime = cat_io_cmd('Affine registration','','',1,stime); + end + + % write data to VF + VF.dt = [spm_type('UINT8') spm_platform('bigend')]; + VF.dat(:,:,:) = cat_vol_ctype(Ym * 200,'uint8'); + VF.pinfo = repmat([1;0],1,size(Ym,3)); + clear WI; + + % smoothing + resa = obj.samp*2; % definine smoothing by sample size + VF1 = spm_smoothto8bit(VF,resa); + VG1 = spm_smoothto8bit(VG,resa); + + elseif job.extopts.APP == 1 + % APP by SPM + VF.dt = [spm_type('UINT8') spm_platform('bigend')]; + VF.dat(:,:,:) = cat_vol_ctype(Ym * 200,'uint8'); + VF.pinfo = repmat([1;0],1,size(Ym,3)); + + % smoothing + resa = obj.samp*2; % definine smoothing by sample size + VF1 = spm_smoothto8bit(VF,resa); + VG1 = spm_smoothto8bit(VG,resa); + + elseif job.extopts.setCOM && ~( isfield(job,'useprior') && ~isempty(job.useprior) ) %%%%%%%%%&& ~ppe.affreg.highBG + % standard approach (no APP) with static resa value and no VG smoothing + stime = cat_io_cmd('Coarse affine registration'); + resa = 8; + VF1 = spm_smoothto8bit(VF,resa); + VG1 = VG; + [Ym,Yt,Ybg,WMth] = APPmini(obj,VF); %#ok + else + % no APP and just prepare the data + if ~( isfield(job,'useprior') && ~isempty(job.useprior) ) + stime = cat_io_cmd('Skip initial affine registration due to high-intensity background','','',1); + end + VF = spm_vol(obj.image(1)); + [Ym,Yt,Ybg,WMth] = APPmini(obj,VF); %#ok + end + + %% prepare affine parameter + aflags = struct('sep',obj.samp,'regtype','subj','WG',[],'WF',[],'globnorm',1); + aflags.sep = max(aflags.sep,max(sqrt(sum(VG(1).mat(1:3,1:3).^2)))); + aflags.sep = max(aflags.sep,max(sqrt(sum(VF(1).mat(1:3,1:3).^2)))); + +% if isfield(job,'useprior') && ( isempty(job.useprior) && ~strcmp(job.opts.affreg,'prior') ) + % stime = cat_io_cmd('Affine registration (longitudinal-development model)','','',1,stime); + + % use affine transformation of given (average) data for longitudinal mode + if isfield(job,'useprior') && ~isempty(job.useprior) + % even in the development pipeline the prior is a good start ! + priorname = job.useprior{1}; + [pp,ff,ee,ex] = spm_fileparts(priorname); %#ok + catxml = fullfile(pp,reportfolder,['cat_' ff '.xml']); + catmat = fullfile(pp,reportfolder,['cat_' ff '.mat']); + + % check that file exists and get affine transformation + if exist(catxml,'file') || exist(catmat,'file') + if strcmp(job.opts.affreg,'prior') + fprintf('\nUse affine transformation from:\n%s\n',priorname); + else + fprintf('\nInitialize with affine transformation from:\n%s\n',priorname); + end + stime = cat_io_cmd(' ',' ','',job.extopts.verb); + xml = cat_io_xml(catxml); + % sometimes xml file does not contain affine transformation + if ~isfield(xml,'SPMpreprocessing') + cat_io_cprintf('warn',sprintf('WARNING: File ""%s"" does not contain successful affine transformation. Use individual affine transformation\n',catxml)); + Affine = eye(4); + useprior = 0; + else + Affine = xml.SPMpreprocessing.Affine; + affscale = 1; + useprior = 1 + ~strcmp(job.opts.affreg,'prior'); + end + else + cat_io_cprintf('warn',sprintf('WARNING: File ""%s"" not found. Use individual affine transformation\n',catxml)); + Affine = eye(4); + useprior = 0; + end + else + %% + Affine = eye(4); + useprior = 0; + + % correct origin using COM and invert translation and use it as starting value + if job.extopts.setCOM %%%%%%%%&& ~ppe.affreg.highBG + fprintf('%5.0fs\n',etime(clock,stime)); stime = clock; + Affine_com = cat_vol_set_com(VF1); + Affine_com(1:3,4) = -Affine_com(1:3,4); + else + Affine_com = eye(4); + end + + %%%%% if ~ppe.affreg.highBG ... strcmp('human',job.extopts.species) && + % affine registration + try + spm_plot_convergence('Init','Coarse affine registration','Mean squared difference','Iteration'); + catch + spm_chi2_plot('Init','Coarse affine registration','Mean squared difference','Iteration'); + end + + warning off + try + [Affine0, affscale] = spm_affreg(VG1, VF1, aflags, Affine_com); Affine = Affine0; + catch + affscale = 0; + end + if affscale>3 || affscale<0.5 + cat_io_cmd('Coarse affine registration failed. Try fine affine registration.','','',1,stime); + Affine = Affine_com; + end + warning on + %%%%% end + end + + %% APP step 2 - brainmasking and second tissue separated bias correction + % --------------------------------------------------------- + % The second part of APP maps a brainmask to native space and + % refines it by morphologic operations and region-growing to + % adapt for worse initial affine alignments. It is important + % that the mask covers the whole brain, whereas additional + % masked head is here less problematic. + % --------------------------------------------------------- + % ds('l2','',vx_vol,Ym,Yb,Ym,Yp0,90) + + + % fine affine registration + if ~useprior %%%%%%%%%&& ~ppe.affreg.highBG % strcmp('human',job.extopts.species) && + aflags.sep = obj.samp/2; + aflags.sep = max(aflags.sep,max(sqrt(sum(VG(1).mat(1:3,1:3).^2)))); + aflags.sep = max(aflags.sep,max(sqrt(sum(VF(1).mat(1:3,1:3).^2)))); + + stime = cat_io_cmd('Affine registration','','',1,stime); + if job.extopts.APP > 0 + VF.dt = [spm_type('UINT8') spm_platform('bigend')]; + VF.pinfo = repmat([1;0],1,size(Ym,3)); + VF.dat(:,:,:) = cat_vol_ctype(Ym*200); + end + VF1 = spm_smoothto8bit(VF,aflags.sep); + VG1 = spm_smoothto8bit(VG,aflags.sep); + + try + spm_plot_convergence('Init','Affine registration','Mean squared difference','Iteration'); + catch + spm_chi2_plot('Init','Affine registration','Mean squared difference','Iteration'); + end + warning off + if ~exist('affscale','var'), affscale = 1.0; end + [Affine1,affscale1] = spm_affreg(VG1, VF1, aflags, Affine, affscale); + warning on + if ~any(any(isnan(Affine1(1:3,:)))) && affscale1>0.5 && affscale1<3, Affine = Affine1; end + else + Affine1 = Affine; + end + clear VG1 VF1 + + else + % no affine registration and preprocessing at all and just prepare the data + VF = spm_vol(obj.image(1)); + [Ym,Yt,Ybg,WMth] = APPmini(obj,VF); %#ok + if ~debug, clear Yt; end + useprior = 0; + Affine = eye(4); + Affine1 = Affine; + end + + + + %% Lesion masking as zero values of the orignal image (2018-06): + % We do not use NaN and -INF because (i) most images are only (u)int16 + % and do not allow such values, (ii) NaN can be part of the background + % of resliced images, and (iii) multiple options are not required here. + % Zero values can also occure by poor data scaling or processing in the + % background but also by other (large) CSF regions and we have to remove + % these regions later. + % We further discussed to use a separate mask images but finally decided + % to keep this as simple as possible using no additional options! + % Moreover, we have to test here anyway to create warnings in case + % of inoptimal settings (e.g. no SLC but possible large lesions). + obj.image0 = spm_vol(job.channel(1).vols0{subj}); + Ysrc0 = spm_read_vols(obj.image0); + Ylesion = single(Ysrc0==0 | isnan(Ysrc0) | isinf(Ysrc0)); + Ylesion(smooth3(Ylesion)<0.5)=0; % general denoising + if any( obj.image0.dim ~= obj.image.dim ) + mat = obj.image0.mat \ obj.image.mat; + Ylesion = smooth3(Ylesion); + Ylesionr = zeros(obj.image.dim,'single'); + for i=1:obj.image.dim(3) + Ylesionr(:,:,i) = single(spm_slice_vol(Ylesion,mat*spm_matrix([0 0 i]),obj.image.dim(1:2),[1,NaN])); + end + Ylesion = Ylesionr>0.5; clear Ylesionr; + end + if exist('Ybg','var'), Ylesion(Ybg)=0; end % denoising in background + % use brainmask + VFa = VF; VFa.mat = Affine * VF.mat; %Fa.mat = res0(2).Affine * VF.mat; + if isfield(VFa,'dat'), VFa = rmfield(VFa,'dat'); end + if ~ppe.affreg.skullstripped + [Vmsk,Yb] = cat_vol_imcalc([VFa,spm_vol(Pb)],Pbt,'i2',struct('interp',3,'verb',0,'mask',-1)); clear Vmsk; %#ok + else + Yb = smooth3(Ysrc0~=ppe.affreg.skullstrippedBGth); + if any( obj.image0.dim ~= obj.image.dim ) + mat = obj.image0.mat \ obj.image.mat; + Yb = smooth3(Yb); + Ybr = zeros(obj.image.dim,'single'); + for i=1:obj.image.dim(3) + Ybr(:,:,i) = single(spm_slice_vol(Yb,mat*spm_matrix([0 0 i]),obj.image.dim(1:2),[1,NaN])); + end + Yb = Ybr>0.5; clear Ybr; + end + end + Ylesion = Ylesion & ~cat_vol_morph(Yb<0.9,'dd',5); clear Yb Ysrc0; + % check settings + % RD202105: in primates the data, template and affreg is often inoptimal so we skip this test + if sum(Ylesion(:))/prod(vx_vol)/1000 > 1 && ~(ppe.affreg.highBG || ppe.affreg.skullstripped) && strcmp('human',job.extopts.species) + fprintf('%5.0fs\n',etime(clock,stime)); stime = []; + if ~job.extopts.SLC + % this could be critical and we use a warning for >1 cm3 and an alert in case of >10 cm3 + cat_io_addwarning([mfilename ':StrokeLesionButNoCorrection'],sprintf( ... + ['There are %0.2f cm%s of zeros within the brain but Stroke Lesion \\\\n', ... + 'Correction (SLC) inactive (available in the expert mode). '], ... + sum(Ylesion(:))/1000,native2unicode(179, 'latin1')),1 + (sum(Ylesion(:))/1000 > 10),[0 1]); + clear Ylesion; + else + cat_io_cprintf('note',sprintf('SLC: Found masked region of %0.2f cm%s. \n', sum(Ylesion(:))/1000,native2unicode(179, 'latin1'))); + end + end + + %% APP for spm_maff8 + % optimize intensity range + % we have to rewrite the image, because SPM reads it again + if job.extopts.APP > 0 + % WM threshold + Ysrc = single(obj.image.private.dat(:,:,:)); + Ysrc(isnan(Ysrc) | isinf(Ysrc)) = min(Ysrc(:)); + + if job.extopts.APP == 1070 + % APPinit is just a simple bias correction for affreg and should + % not be used further although it maybe helps in some cases! + Ymc = Ysrc; + else + bth = min( [ mean(single(Ysrc( Ybg(:)))) - 2*std(single(Ysrc( Ybg(:)))) , ... + mean(single(Ysrc(~Ybg(:)))) - 4*std(single(Ysrc(~Ybg(:)))) , ... + min(single(Ysrc(~Ybg(:)))) ]); + % use bias corrected image with original intensities + Ymc = Ym * abs(diff([bth,WMth])) + bth; + clear bth + end + + % set variable and write image + obj.image.dat(:,:,:) = Ymc; + obj.image.pinfo = repmat([255;0],1,size(Ymc,3)); + obj.image.private.dat(:,:,:) = Ymc; + + obj.image.dt = [spm_type('FLOAT32') spm_platform('bigend')]; + obj.image.pinfo = repmat([1;0],1,size(Ymc,3)); + + % mask the background + % RD20211229: Masking of unwanted regions in differnt cases. + % In standard cross-secitonal processing the background of the + % SPM TPM is quite smooth and a hard masking works (pre R1900). + % However, in longitudinal TPMs with its hard background setting + % the SPM US have enough values. Hence, we have to include some + % (random) values close (10-15 mm) to the brain (""corona""). + % It would be also possible to test the smoothness of the TPM + % backgroud class to avoid problems with ""own"" hard TPMs. + isSPMtpm = strcmp(job.extopts.species,'human') && ... + ( strcmp(job.opts.tpm , fullfile(spm('dir'),'tpm','TPM.nii') ) || ... + strcmp(job.opts.tpm , fullfile(spm('dir'),'tpm','TPM.nii,1') ) ); + [ppt,fft] = spm_fileparts(job.opts.tpm{1}); + isLONGtpm = strcmp(fft(1:min(numel(fft),7)),'longTPM'); + if exist('Ybg','var') && job.extopts.setCOM ~= 120 % setCOM == 120 - useCOM,useMaffreg,noMask + if (length(ff)>4 && strcmp(ff(1:5),'navg_')) || ... + (isfield(job,'useprior') && ~isempty(job.useprior)) || ... + (isfield(job.extopts,'new_release') && job.extopts.new_release) + % new minimal masking approach in longitudinal processing to avoid backgound peak erros and for future releases + fprintf('\n'); cat_io_cprintf('g8',' Use new longitudinal background setting. '); + Ymsk = cat_vol_morph( ~Ybg ,'dd',10,vx_vol) & ... % remove voxels far from head + ~( Ybg & rand(size(Ybg))>0.5) & ... % have a noisy corona + ~( cat_vol_grad( Ysrc , vx_vol)==0 & Ysrc==0 ); % remove voxel that are 0 and have no gradient + else + % RD20220103: old cross-sectional setting with small correction for own TPMs + if isSPMtpm || isLONGtpm + Ymsk = ~Ybg; % old default - mask background + else + cat_io_addwarning([mfilename ':noSPMTPM-noBGmasking'],... + 'Different TPM detected - deactivated background masking!',1,[1 2]); + Ymsk = []; % new special case for other TPMs + end + end + if ~isempty( Ymsk ) + obj.msk = VF; + obj.msk.pinfo = repmat([255;0],1,size(Ybg,3)); + obj.msk.dt = [spm_type('uint8') spm_platform('bigend')]; + obj.msk.dat = uint8( Ymsk ); + obj.msk = spm_smoothto8bit(obj.msk,0.1); + end + end + clear Ysrc Ymsk; + end + + + + + %% Fine affine Registration with automatic selection in case of multiple TPMs. + % This may not work for non human data (or very small brains). + % This part should be an external (coop?) function? + if useprior==1 + stime = cat_io_cmd('SPM preprocessing 1 (estimate 1 - use prior):','','',1,stime); + elseif job.extopts.setCOM == 10 % no maffreg + stime = cat_io_cmd('SPM preprocessing 1 (estimate 1 - use no TPM registration):','','',1,stime); + else + stime = cat_io_cmd('SPM preprocessing 1 (estimate 1 - TPM registration):','','',1,stime); + end + if ~isempty(job.opts.affreg) && useprior~=1 && job.extopts.setCOM ~= 10 % setcom == 10 - never use ... && strcmp('human',job.extopts.species) + spm_plot_convergence('Init','Fine affine registration','Mean squared difference','Iteration'); + warning off + + try + Affine2 = spm_maff8(obj.image(1),obj.samp,(obj.fwhm+1)*16,obj.tpm,Affine ,job.opts.affreg,80); + catch + Affine2 = spm_maff8(obj.image(1),obj.samp,(obj.fwhm+1)*16,obj.tpm,Affine ,job.opts.affreg); + end + scl1 = abs(det(Affine1(1:3,1:3))); + scl2 = abs(det(Affine2(1:3,1:3))); + + if any(any(isnan(Affine2(1:3,:)))) + try + Affine2 = spm_maff8(obj.image(1),obj.samp,(obj.fwhm+1)*4,obj.tpm,Affine ,job.opts.affreg,80); + catch + Affine2 = spm_maff8(obj.image(1),obj.samp,(obj.fwhm+1)*4,obj.tpm,Affine ,job.opts.affreg); + end + if any(any(isnan(Affine2(1:3,:)))) + Affine2 = Affine; + end + else + % check for > 10% larger scaling + if ~strcmp(job.opts.affreg,'prior') && scl1 > 1.1*scl2 && job.extopts.setCOM ~= 11 % setcom == 11 - use always + stime = cat_io_cmd(' Use initial fine affine registration.','warn','',1,stime); + %fprintf('\n First fine affine registration failed.\n Use affine registration from previous step. '); + Affine2 = Affine1; + scl2 = scl1; + end + end + try + Affine3 = spm_maff8(obj.image(1),obj.samp,obj.fwhm,obj.tpm,Affine2,job.opts.affreg,80); + catch + Affine3 = spm_maff8(obj.image(1),obj.samp,obj.fwhm,obj.tpm,Affine2,job.opts.affreg); + end + + if ~any(any(isnan(Affine3(1:3,:)))) + scl3 = abs(det(Affine3(1:3,1:3))); + % check for > 5% larger scaling + if ~strcmp(job.opts.affreg,'prior') && scl2 > 1.05*scl3 && job.extopts.setCOM ~= 11 % setcom == 11 - use always + stime = cat_io_cmd(' Use previous fine affine registration.','warn','',1,stime); + %fprintf('\n Final fine affine registration failed.\n Use fine affine registration from previous step. '); + Affine = Affine2; + else + Affine = Affine3; + end + else % Affine3 failed, use Affine2 + Affine = Affine2; + end + warning on + else + Affine2 = Affine1; + Affine3 = Affine1; + end + + %% test for flipping + %fliptest = 2; + %[ppe.affreg.flipped, ppe.affreg.flippedval,stime] = cat_vol_testflipping(obj,Affine,fliptest,stime); + + if 0 + %% visual control for development and debugging + VFa = VF; VFa.mat = AffineMod * VF.mat; %Fa.mat = res0(2).Affine * VF.mat; + if isfield(VFa,'dat'), VFa = rmfield(VFa,'dat'); end + [Vmsk,Yb] = cat_vol_imcalc([VFa,spm_vol(Pb)],Pbt,'i2',struct('interp',3,'verb',0,'mask',-1)); + %[Vmsk,Yb] = cat_vol_imcalc([VFa;obj.tpm.V(1:3)],Pbt,'i2 + i3 + i4',struct('interp',3,'verb',0)); + %[Vmsk,Yb] = cat_vol_imcalc([VFa;obj.tpm.V(5)],Pbt,'i2',struct('interp',3,'verb',0)); + ds('d2sm','',1,Ym,Ym*0.5 + 0.5*Ym.*(Yb>0.5),round(size(Yb,3)*0.6)) + end + + + if isfield(ppe.affreg,'skullstripped') && ~ppe.affreg.skullstripped + %% affreg with brainmask + if debug + [Affine,Ybi,Ymi,Ym0] = cat_run_job_APRGs(Ym,Ybg,VF,Pb,Pbt,Affine,vx_vol,obj,job); %#ok + else + [Affine,Ybi] = cat_run_job_APRGs(Ym,Ybg,VF,Pb,Pbt,Affine,vx_vol,obj,job); + end + end + + if ppe.affreg.skullstripped || job.extopts.gcutstr<0 + %% update number of SPM gaussian classes + Ybg = 1 - spm_read_vols(obj.tpm.V(1)) - spm_read_vols(obj.tpm.V(2)) - spm_read_vols(obj.tpm.V(3)); + noCSF = job.extopts.gcutstr == -2; + if 1 + for k=1:3 - noCSF + obj.tpm.dat{k} = spm_read_vols(obj.tpm.V(k)); + obj.tpm.V(k).dt(1) = 64; + obj.tpm.V(k).dat = double(obj.tpm.dat{k}); + obj.tpm.V(k).pinfo = repmat([1;0],1,size(Ybg,3)); + end + end + + obj.tpm.V(4 - noCSF).dat = Ybg; + obj.tpm.dat{4 - noCSF} = Ybg; + obj.tpm.V(4 - noCSF).pinfo = repmat([1;0],1,size(Ybg,3)); + obj.tpm.V(4 - noCSF).dt(1) = 64; + obj.tpm.dat(5 - noCSF:6) = []; + obj.tpm.V(5 - noCSF:6) = []; + obj.tpm.bg1(4 - noCSF) = obj.tpm.bg1(6); + obj.tpm.bg2(4 - noCSF) = obj.tpm.bg1(6); + obj.tpm.bg1(5 - noCSF:6) = []; + obj.tpm.bg2(5 - noCSF:6) = []; + %obj.tpm.V = rmfield(obj.tpm.V,'private'); + + % tryed 3 peaks per class, but BG detection error require manual + % correction (set 0) that is simple with only one class + % RD202306: SPM is not considering things without variation and + % a zeroed background is simply not existing! + % Moreover it is possible just to ignore classes :D + % Hence, we may not need to redefine the TPM at all. + if noCSF + job.opts.ngaus = [([job.tissue(1:2).ngaus])',1]; % gaussian background + else + job.opts.ngaus = ([job.tissue(1:3).ngaus])'; % no gaussian background + end + obj.lkp = []; + for k=1:numel(job.opts.ngaus) + job.tissue(k).ngaus = job.opts.ngaus(k); + obj.lkp = [obj.lkp ones(1,job.tissue(k).ngaus)*k]; + end + end + + % adpation parameter for affine registration? 0.98 and 1.02? + if isfield(job.extopts,'affmod') && any(job.extopts.affmod) + AffineUnmod = Affine; + if numel(job.extopts.affmod)>6, job.extopts.affmod = job.extopts.affmod(1:6); end % remove too many + if numel(job.extopts.affmod)<3, job.extopts.affmod(end+1:3) = job.extopts.affmod(1); end % isotropic + if numel(job.extopts.affmod)<6, job.extopts.affmod(end+1:6) = 0; end % add translation + fprintf('\n Modify affine regitration (S=[%+3d%+3d%+3d], T=[%+3d%+3d%+3d])',job.extopts.affmod); + sf = (100 - job.extopts.affmod(1:3)) / 100; + imat = spm_imatrix(Affine); + COMc = [eye(4,3), [ 0; -24 / mean(imat(7:9)); -12 / mean(imat(7:9)); 1] ]; + imat = spm_imatrix(Affine * COMc); + imat(1:3) = imat(1:3) - job.extopts.affmod(4:6); + imat(7:9) = imat(7:9) .* sf; + AffineMod = spm_matrix(imat) / COMc; + + res.AffineUnmod = AffineUnmod; + res.AffineMod = AffineMod; + else + AffineMod = Affine; + end + obj.Affine = AffineMod; + cat_err_res.obj = obj; + + + %% SPM preprocessing 1 + % ds('l2','a',0.5,Ym,Ybg,Ym,Ym,140); + % ds('l2','a',0.5,Ysrc/WMth,Yb,Ysrc/WMth,Yb,140); + warning off + try + %% inital estimate + stime = cat_io_cmd('SPM preprocessing 1 (estimate 2):','','',job.extopts.verb-1,stime); + obj.tol = job.opts.tol; % reset within loop + + % RD202012: Missclassification of GM as CSF and BG as tissue: + % We observed problems with high-quality data (e.g. AVGs) and + % interpolated low resolution data (single_subT1=Collins), + % where (low-intensity) GM was missclassified as CSF but also + % miss-classification of background. The problems where caused + % by the US (or better the way we use it here) and higher + % accuracy (increased number of minimum iterations in + % cat_spm_preproc8) was essential. Nevertheless, some + % cases still cause severe errors at 3 mm sample size but + % not for other resolutions (eg. 4, 6, 2 mm). In addition, the + % log-likelihood became NaN in such cases. Hence, I added a + % little loop her to test other resolutions for samp. We keep + % the output here quit simple to avoid confusion. samp is a + % rarely used expert parameter and other resolutions are only + % used as backup and the effects should be not too strong for + % normal data without strong bias. + + % sampling resolution definition + if round(obj.samp) == 3, samp = [obj.samp 4 2]; + elseif round(obj.samp) == 2, samp = [obj.samp 3 4]; + elseif ~strcmp(job.extopts.species,'human') + samp = [obj.samp obj.samp*2 obj.samp/2]; + else, samp = [obj.samp 3 2]; + end + + if job.opts.redspmres + image1 = obj.image; + [obj.image,redspmres] = cat_vol_resize(obj.image,'interpv',1); + end + + % run loop until you get a non NaN + % #### additional threshold is maybe also helpful #### + warning off; % turn off ""Warning: Using 'state' to set RANDN's internal state causes RAND ..."" + for sampi = 1:numel(samp) + obj.samp = samp(sampi); + try + res = cat_spm_preproc8(obj); + if any(~isnan(res.ll)) + break + else + stime = cat_io_cmd(sprintf('SPM preprocessing 1 (estimate %d):',... + 2 + sampi),'caution','',job.extopts.verb-1,stime); + end + catch + % RD202110: Catch real errors of cat_spm_preproc8 and try a + % skull-stripped version just to get some result. + stime = cat_io_cmd(sprintf('SPM preprocessing 1 (estimate %d skull-stripped):',... + 2 + sampi),'caution','',job.extopts.verb-1,stime); + if exist('Ybi','var') % use individual mask + obj.image.dat = obj.image.dat .* (cat_vbdist(single(Ybi>0.5))<10); + else % use template mask + VFa = VF; VFa.mat = Affine * VF.mat; %Fa.mat = res0(2).Affine * VF.mat; + if isfield(VFa,'dat'), VFa = rmfield(VFa,'dat'); end + [Vmsk,Yb] = cat_vol_imcalc([VFa,spm_vol(Pb)],Pbt,'i2',struct('interp',3,'verb',0,'mask',-1)); + ds('d2sm','',1,Ym,Ym.*(Yb>0.5),round(size(Yb,3)*0.6)) + obj.image.dat = obj.image.dat .* (cat_vbdist(single(Yb>0.5))<10); + end + res = cat_spm_preproc8(obj); + if any(~isnan(res.ll)) + break + else + stime = cat_io_cmd(sprintf('SPM preprocessing 1 (estimate %d):',... + 2 + sampi),'caution','',job.extopts.verb-1,stime); + end + end + end + if ~exist('res','var') + cat_io_printf('SPM preprocessing with default settings failed. Run backup settings. \n'); + end + warning on; + + if job.opts.redspmres + res.image1 = image1; + clear reduce; + end + + % unknown BG detection problems in INDI_NHa > manual setting + if ppe.affreg.skullstripped, res.mn(end) = 0; end + + catch + %% + cat_io_addwarning([mfilename ':ignoreErrors'],'Run backup function (IN DEVELOPMENT).',1,[1 1]); + + if isfield(obj.image,'dat') + tmp = obj.image.dat; + else + tmp = spm_read_vols(obj.image); + dt2 = obj.image.dt(1); + dts = cat_io_strrep(spm_type(dt2),{'float32','float64'},{'single','double'}); + obj.image.dat = eval(sprintf('%s(tmp);',dts)); + obj.image.pinfo = repmat([1;0],1,size(tmp,3)); + end + if exist('Ybi','var') + obj.image.dat = obj.image.dat .* (cat_vbdist(single(Ybi>0.5))<10); + else + VFa = VF; VFa.mat = Affine * VF.mat; %Fa.mat = res0(2).Affine * VF.mat; + if isfield(VFa,'dat'), VFa = rmfield(VFa,'dat'); end + [Vmsk,Yb] = cat_vol_imcalc([VFa,spm_vol(Pb)],Pbt,'i2',struct('interp',3,'verb',0,'mask',-1)); + ds('d2sm','',1,Ym,Ym.*(Yb>0.5),round(size(Yb,3)*0.6)) + obj.image.dat = obj.image.dat .* (cat_vbdist(single(Yb>0.5))<10); + end + + suc = 0; + % try higher accuracy + while obj.tol>10e-9 && suc == 0 + obj.tol = obj.tol / 10; + try + res = cat_spm_preproc8(obj); + suc = 1; + end + end + if suc == 0 + % try lower accuracy + while obj.tol<1 && suc == 0 + obj.tol = obj.tol * 10; + try + res = cat_spm_preproc8(obj); + suc = 1; + end + end + end + + if any( (vx_vol ~= vx_voli) ) || ~strcmp(job.extopts.species,'human') + [pp,ff,ee] = spm_fileparts(job.channel(1).vols{subj}); + delete(fullfile(pp,[ff,ee])); + end + + if suc==0 + %% + mati = spm_imatrix(V.mat); + + error('cat_run_job:spm_preproc8',sprintf([ + 'Error in spm_preproc8. Check image and orientation. \n'... + ' Volume size (x,y,z): %8.0f %8.0f %8.0f \n' ... + ' Origin (x,y,z): %8.1f %8.1f %8.1f \n' ... + ' Rotation (deg): %8.1f %8.1f %8.1f \n' ... + ' Resolution: %8.1f %8.1f %8.1f \n'],... + V.dim,[mati(1:3),mati(4:6),mati(7:9),])); + end + + %% set internal image + if ~exist('dt2','var') + %tmp = obj.image.dat; + dt2 = obj.image.dt(1); + dts = cat_io_strrep(spm_type(dt2),{'float32','float64'},{'single','double'}); + end + obj.image.dat = eval(sprintf('%s(tmp);',dts)); + obj.image.pinfo = repmat([1;0],1,size(tmp,3)); + obj.image.dt(1) = dt2; + res.image.dat = eval(sprintf('%s(tmp);',dts)); + res.image.pinfo = repmat([1;0],1,size(tmp,3)); + res.image.dt(1) = dt2; + end + if ppe.affreg.skullstripped || job.extopts.gcutstr<0 + % here we have to add manually our no variance background value of 0 + res.mg(end+1) = 1; + res.mn(end+1) = ppe.affreg.skullstrippedBGth; + res.vr(end+1) = max(eps,numel(res.wp) * eps); + res.wp = res.wp - numel(res.wp) * eps; + res.wp(end+1) = numel(res.wp) * eps; + res.lkp(end+1) = 4; + end + warning on + + if job.extopts.expertgui>1 + %% print the tissue peaks + mnstr = sprintf('\n SPM-US: ll=%0.6f, Tissue-peaks: ',res.ll); + for lkpi = 1:numel(res.lkp) + if lkpi==1 || ( res.lkp(lkpi) ~= res.lkp(lkpi-1) ) + mnstr = sprintf('%s (%d) ',mnstr,res.lkp(lkpi)); + end + if lkpi>1 &&( res.lkp(lkpi) == res.lkp(lkpi-1) ), mnstr = sprintf('%s, ',mnstr); end + if sum(res.lkp == res.lkp(lkpi))>1 && res.mg(lkpi)==max( res.mg( res.lkp == res.lkp(lkpi) )), mnstr = sprintf('%s*',mnstr); end + mnstr = sprintf('%s%0.2f',mnstr,res.mn( lkpi )); + end + cat_io_cprintf('blue',sprintf('%s\n',mnstr)); + cat_io_cmd(' ',' '); + end + fprintf('%5.0fs\n',etime(clock,stime)); + + %% check contrast (and convergence) + %min(1,max(0,1 - sum( shiftdim(res.vr) ./ res.mn' .* res.mg ./ mean(res.mn(res.lkp(2))) ) )); + + clsint = @(x) round( sum(res.mn(res.lkp==x) .* res.mg(res.lkp==x)') * 10^5)/10^5; + Tgw = [cat_stat_nanmean(res.mn(res.lkp==1)) cat_stat_nanmean(res.mn(res.lkp==2))]; + Tth = [ + ... min(res.mn(res.lkp==6 & res.mg'>0.3)) ... % bg; ignore the background, because of MP2RGAGE, R1, and MT weighted images + max( min( clsint(3) , max(Tgw)+1.5*abs(diff(Tgw))) , min(Tgw)-1.5*abs(diff(Tgw)) ) ... % csf with limit for T2! + clsint(1) ... gm + clsint(2) ... wm + clsint(4) ... skull + clsint(5) ... head tissue + clsint(6) ... background + ]; + + res.Tth = Tth; + cat_err_res.res = res; + + % inactive preprocessing of inverse images (PD/T2) ... just try + if 0 % any(diff(Tth(1:3))<=0) + error('cat_run_job:BadImageProperties', ... + ['CAT12 is designed to work only on highres T1 images. \n' ... + 'T2/PD preprocessing can be forced on your own risk by setting \n' ... + '''cat12.extopts.INV=1'' in the cat_default file. If this was a highres \n' ... + 'T1 image then the initial segmentation might be failed, probably \n' ... + 'because of alignment problems (please check image orientation).']); + end + + % RD202006: Throw warning/error? + % Due to inaccuracies of the clsint function it is better to print + % this as intense warning. + if any( Tth(2:3)<0 ) || job.test_warnings + cat_io_addwarning([mfilename ':negVal'],sprintf( ... + ['CAT12 was developed for images with positive values and \\\\n', ... + 'negative values can lead to preprocessing problems. The average \\\\n', ... + 'intensities of CSF/GM/WM are %0.4f/%0.4f/%0.4f. \\\\n', ... + 'If you observe problems, you can use the %s to scale your data.'], Tth(1:3), ... + spm_file('Datatype-batch','link','spm_jobman(''interactive'','''',''spm.tools.cat.tools.spmtype'');')),2,[0 1],Tth); + end + end + + %% updated tpm information for skull-stripped data should be available for cat_main + if isfield(obj.tpm,'bg1') && exist('ppe','var') && ( ppe.affreg.skullstripped || job.extopts.gcutstr<0 ) + fname = res.tpm(1).fname; + res.tpm = obj.tpm; + res.tpm(1).fname = fname; + end + spm_progress_bar('Clear'); + cat_progress_bar('Clear'); + + % call main processing + res.tpm = obj.tpm.V; + res.stime = stime0; + res.catlog = catlog; + res.Affine0 = res.Affine; + res.image0 = spm_vol(job.channel(1).vols0{subj}); + if exist('ppe','var'), res.ppe = ppe; end + + if isfield(job.extopts,'affmod') && any(job.extopts.affmod) + res.AffineUnmod = AffineUnmod; + res.AffineMod = AffineMod; + end + + if exist('Ylesion','var'), res.Ylesion = Ylesion; else, res.Ylesion = false(size(res.image.dim)); end; clear Ylesion; + if exist('redspmres','var'); res.redspmres = redspmres; res.image1 = image1; end + job.subj = subj; + + % call new pipeline in case of inverse images (PD/T2/FLAIR) + if exist('Tth','var') && ( any(diff(Tth(1:3))<=0) || job.test_warnings ) + % update SPM processing ? + % use stronger bias correction ? + + % warning/error because we use the new pipeline + job.extopts.inv_weighting = 1; + cat_io_addwarning([mfilename ':nonT1contrast'],sprintf( ... + ['A non-T1 contrast was detected and the NEW EXPERIMENTAL \\\\n' ... + 'PIPELINE is used! If it is was a high-resolution T1 image, \\\\n' ... + 'the initial segmentation might have failed, probably due \\\\n' ... + 'to alignment problems (please check the image orientation). \\\\n' ... + 'In case of registration issues, try to change the following \\\\n' ... + 'parameter indepently: \\\\n' ... + ' * ""Affine Regularisation"" = ""No regularisation""; \\\\n' ... + ' * ""Use center-of-mass to set origin"" = ""No""; \\\\n ' ... + ' * ""Affine Preprocessing (APP)"" = ""none"". ']),1,[0 1],Tth); + cat_main(res,obj.tpm,job); + else + cat_main1639(res,obj.tpm,job); + end + + % delete denoised/interpolated image + [pp,ff,ee] = spm_fileparts(job.channel(1).vols{subj}); + if exist(fullfile(pp,[ff,ee]),'file') + delete(fullfile(pp,[ff,ee])); + end + %% + + if usediary + diary off; + end +return + +%======================================================================= +function [Ym,Yt,Ybg,WMth] = APPmini(obj,VF) +%% very simple affine preprocessing (APP) +% ------------------------------------------------------------------------ +% Creates an intensity normalized image Ym by the average higher tissue +% intensity WMth estimated in the mask Yt. Moreover, it estimates the +% background region Ybg. +% +% [Ym,Yt,Ybg,WMth] = APPmini(obj,VF) +% ------------------------------------------------------------------------ +% Robert Dahnke 2019/01 + + Ysrc = single(obj.image.private.dat(:,:,:)); + + % remove outlier and use SPM for intensity normalization to uint8 + % empirical division by 200 to get WM values around 1.0 + Ysrc = cat_stat_histth(Ysrc,99.9); + VF0 = cat_spm_smoothto8bit(VF,0.1); + Ym = single(VF0.dat)/200; clear VG0 + + % find the larges object and estimate the averag intensity + % keep in mind that this will may inlcude the head (and in MP2RAGE/MT/R1 + % images also the background), i.e. highest intensity is may head, + % blood vessels or WM or CSF in T1/PD + Yt = cat_vol_morph(Ym>cat_stat_nanmean(Ym(Ym(:)>0.1)),'l',[100 1000])>0.5; + WMth = cat_stat_kmeans( Ysrc(Yt(:)) , 1); + + % rescale Ym and roughly estimate the background (not in MP2Rage/MT/R1) + Ym = Ysrc ./ WMth; + Ybg = cat_vol_morph(Ym<0.2,'l',[100 1000])>0; + +return + +function APP_RMSE = checkAPP(Ym,Ysrc) +%% check Ym +% ------------------------------------------------------------------------ +% Function to compare the normalized gradient maps of two input images +% that should be nearly identical. +% +% APP_RMSE = checkAPP(Ym,Ysrc) +% ------------------------------------------------------------------------ +% Robert Dahnke 2019/01 + + % remove strongest outlier + Ym = cat_stat_histth(Ym,99.9); + Ysrc = cat_stat_histth(Ysrc,99.9); + + % avoid division by zeros + Ym = Ym + min(Ym(:)); + Ysrc = Ysrc + min(Ysrc(:)); + + % normalized gradient maps + Ygm = cat_vol_grad(Ym) ./ (Ym + eps); + Ygs = cat_vol_grad(Ysrc) ./ (Ysrc + eps); + + % use only the central region and values in the expected tissue range + sYm = round(size(Ym) / 5); + Ymsk = false(size(Ym) ); Ymsk(sYm(1):end-sYm(1),sYm(2):end-sYm(2),sYm(3):end-sYm(3)) = true; + Ymsk = Ymsk & cat_vol_morph(Ygm<2 & Ygs<2 & Ym>0.5 & Ysrc>0.5,'e'); + + % general error between both images within the mask + APP_RMSE = cat_stat_nanmean( ( Ygm(Ymsk(:)) - Ygs(Ymsk(:)) ).^2 )^0.5; + +return","MATLAB" +"Neurology","ChristianGaser/cat12","cat_io_colormaps.m",".m","28888","1057"," +function [C,XML] = cat_io_colormaps(Cname,ncolors) +% _________________________________________________________________________ +% Create CAT Colormaps. +% +% [C,XML] = cat_io_colormaps(Cname,ncolors) +% +% Cname - colormap +% colormaps internally used in CAT12 +% 'marks' +% 'marks+' +% 'turbo' +% 'BCGWHw' +% 'BGWHn' +% 'magentadk' +% 'magenta' +% 'orange' +% 'blue' +% 'BCGWHw' +% 'BCGWHwov' +% 'BCGWHn' +% 'BCGWHn2' +% 'BCGWHgov' +% 'BCGWHnov' +% 'BCGWHcheckcov' +% 'curvature' +% 'hotinv' +% 'cold' +% 'coldinv' +% 'BWR' +% categorical colormaps from RColorBrewer +% https://rdrr.io/cran/RColorBrewer/man/ColorBrewer.html +% 'accent' +% 'dark2' +% 'paired' +% 'set1' +% 'set2' +% 'set3' +% categorical colormaps from ggsci +% https://nanx.me/ggsci/articles/ggsci.html +% 'nejm' +% 'jco' +% 'jama' +% 'd3' +% +% ncolors - number of colors +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + % number of colors: + if ~exist('Cname','var') + Cname = 'marks+'; + end + if ~exist('ncolors','var') + ncolors = []; + else + if ncolors<1 + error('MATLAB:cat_io_colormaps','Need at least one Color'); + elseif ncolors>2^12 + error('MATLAB:cat_io_colormaps', ... + 'Wow, why do you want to create a rainbow???. Please use less colors or change me.\n'); + end + end + + % expect continuous colormaps by default + cmap_categorical = false; + + % load basic colormap + switch Cname + case 'marks+', + C = [ + 0.0000 0.4000 0.0000 % 0 - excellent (dark green) + 0.0000 0.8000 0.0000 % 1 - excellent (light green) + 0.4000 0.6000 0.1000 % 2 - good (yellow-green) + 1.0000 0.6000 0.4000 % 3 - ok (yellow-orange) + 1.0000 0.3000 0.0000 % 4 - bad (red-orange) + 0.8000 0.2000 0.0000 % 5 - very bad (red) + 0.7000 0.0000 0.0000 % 6 - unusable (dark red) + 0.6000 0.0000 0.0000 % 7 - unusable (dark red) + 0.5000 0.0000 0.0000 % 8 - unusable (dark red) + 0.4000 0.0000 0.0000 % 9 - unusable (dark red) + ]; + case 'marks' + C = [ %JET + 0.0000 0.0000 0.5625 % 4 - -3 (dark blue) + 0.0000 0.0000 1.0000 % 3 - -2 (blue) + 0.0000 1.0000 1.0000 % 2 - -1 (cyan) + 0.0000 1.0000 0.0000 % 1 - 0 normal case (green) + 1.0000 1.0000 0.0000 % 2 - +1 (yellow) + 1.0000 0.0000 0.0000 % 3 - +2 (red) + 0.5104 0.0000 0.0000 % 4 - +3 (dark red) + ]; + % vbm-output + % GMT output + % ... + case 'trafficlight' + C = [ + 0.000 0.500 0.000 % dk green + 0.100 0.800 0.000 % green + 0.900 0.700 0.000 % yellow + 1.000 0.000 0.000 % red + 0.500 0.000 0.000 % dk red + ]; + case 'trafficlight2' + C = [ + 0.000 0.000 0.900 % blue + 0.000 0.900 0.000 % green + 0.900 0.900 0.000 % orange + 1.000 0.000 0.000 % red + 0.700 0.000 0.700 % pink + ]; + case 'accent' + C = accent; + cmap_categorical = true; + case 'dark2' + C = dark2; + cmap_categorical = true; + case 'paired' + C = paired; + cmap_categorical = true; + case 'set1' + C = set1; + cmap_categorical = true; + case 'set2' + C = set2; + cmap_categorical = true; + case 'set3' + C = set3; + cmap_categorical = true; + case 'nejm' + C = nejm; + cmap_categorical = true; + case 'jco' + C = jco; + cmap_categorical = true; + case 'jama' + C = jama; + cmap_categorical = true; + case 'd3' + C = d3; + cmap_categorical = true; + case 'turbo' + C = turbo; + case 'magentadk' + C = [0.95 0.95 0.95; 0.7 0.2 0.7]; + case 'magenta' + C = [0.95 0.95 0.95; 1.0 0.4 1.0]; + case 'orange' + C = [0.95 0.95 0.95; 0.8 0.4 0.6]; + case 'blue' + C = blue; + case 'BCGWHw' + C = BCGWHw; + case 'BCGWHwov' + C = BCGWHwov; + case 'BCGWHn' + C = BCGWHn; + case 'BCGWHn2'; + C = BCGWHnov; + case 'BCGWHgov' + C = BCGWHgov; + case 'BCGWHnov' + C = BCGWHnov; + case 'BCGWHcheckcov' + C = BCGWHcheckcov; + case 'curvature'; + C = [ + 0.9900 0.9900 0.9900 + 0.9500 0.9000 0.8000 + 0.9700 0.8500 0.6000 + 1.0000 0.8000 0.3000 + 1.0000 0.6000 0.0000 + 1.0000 0.3000 0.0000 + 1.0000 0.0000 0.0000 + 0.5000 0.0000 0.0000 + 0.0000 0.0000 0.0000 + ]; + case 'hotinv'; + C = hotinv; + case 'hot'; + C = hotinv; C = C(end:-1:1,:); + case 'cold'; + C = hotinv; C = C(end:-1:1,:); C = [C(:,3),C(:,2),C(:,1)]; + case 'coldinv'; + C = hotinv; C = [C(:,3),C(:,2),C(:,1)]; + case 'BWR'; + CR = hotinv; + CB = [CR(:,3),CR(:,2),CR(:,1)]; CB = CB(end:-1:1,:); + C = [CB;CR(2:end,:,:,:)]; + otherwise, error('MATLAB:cat_io_colormaps','Unknown Colormap ''%s''\n',Cname); + end + if isempty(ncolors), ncolors = size(C,1); end + + % interpolate colormap, if colormap is categorical only use interpolation for larger number of colors + if (size(C,1)ncolors && ~cmap_categorical) + ss = (size(C,1)+1) / (ncolors); + [X,Y] = meshgrid(1:ss:size(C,1)+1,1:3); X = min(size(C,1),X); + C = interp2(1:size(C,1),1:3,C',X,Y)'; + XML = cellstr([ dec2hex(round(min(255,max(0,C(:,1)*255)))), ... + dec2hex(round(min(255,max(0,C(:,2)*255)))), ... + dec2hex(round(min(255,max(0,C(:,3)*255)))) ]); + % limit categorical colormaps + elseif size(C,1)>ncolors && cmap_categorical + C = C(1:ncolors,:); + end + + +end + + +% from RColorBrewer +% https://rdrr.io/cran/RColorBrewer/man/ColorBrewer.html +function C=accent + C = [ + 127 201 127 + 190 174 212 + 253 192 134 + 255 255 153 + 56 108 176 + 240 2 127 + 191 91 23 + 102 102 102 + ]/255; +end + +% from RColorBrewer +% https://rdrr.io/cran/RColorBrewer/man/ColorBrewer.html +function C=dark2 + C = [ + 27 158 119 + 217 95 2 + 117 112 179 + 231 41 138 + 102 155 30 + 230 171 2 + 166 118 29 + 102 102 102 + ]/255; +end + +% from RColorBrewer +% https://rdrr.io/cran/RColorBrewer/man/ColorBrewer.html +function C=paired + C = [ + 166 206 227 + 31 120 180 + 178 223 138 + 51 160 44 + 251 154 153 + 227 26 28 + 253 191 111 + 255 127 0 + 202 178 214 + 106 61 154 + 255 255 153 + 177 89 40 + ]/255; +end + +% from RColorBrewer +% https://rdrr.io/cran/RColorBrewer/man/ColorBrewer.html +function C=set1 + C = [ + 228 26 28 + 55 126 184 + 77 175 74 + 152 78 163 + 255 127 0 + 255 255 51 + 166 86 40 + 247 129 191 + 153 153 153 + ]/255; +end + +% from RColorBrewer +% https://rdrr.io/cran/RColorBrewer/man/ColorBrewer.html +function C=set2 + C = [ + 102 194 165 + 252 141 98 + 141 160 203 + 231 138 195 + 166 216 84 + 255 217 47 + 229 196 148 + 179 179 179 + ]/255; +end + +% from RColorBrewer +% https://rdrr.io/cran/RColorBrewer/man/ColorBrewer.html +function C=set3 + C = [ + 141 211 199 + 255 255 179 + 190 186 218 + 251 128 114 + 128 177 211 + 253 180 98 + 179 222 105 + 252 205 229 + 217 217 217 + 188 128 189 + 204 235 197 + 255 237 111 + ]/255; +end + +% from ggsci +% https://nanx.me/ggsci/articles/ggsci.html +% extended by additional colors +function C=nejm + C = [ + '#BC3C29' + '#0072B5' + '#E18727' + '#20854E' + '#7876B1' + '#6F99AD' + '#FFDC91' + '#EE4C97' + '#8C564B' + '#BCBD22' + '#00A1D5' + '#374E55' + '#003C67' + '#8F7700' + '#7F7F7F' + '#353535' + ]; + C = hex2rgb(C); +end + +% from ggsci +% https://nanx.me/ggsci/articles/ggsci.html +function C=jama + C = [ + '#374E55' + '#DF8F44' + '#00A1D5' + '#B24745' + '#79AF97' + '#6A6599' + '#80796B' + ]; + C = hex2rgb(C); +end + +% from ggsci +% https://nanx.me/ggsci/articles/ggsci.html +function C=jco + C = [ + '#0073C2' + '#EFC000' + '#868686' + '#CD534C' + '#7AA6DC' + '#003C67' + '#8F7700' + '#3B3B3B' + '#A73030' + '#4A6990' + ]; + C = hex2rgb(C); +end + +% from ggsci +% https://nanx.me/ggsci/articles/ggsci.html +function C=d3 + C = [ + '#1F77B4' + '#FF7F0E' + '#2CA02C' + '#D62728' + '#9467BD' + '#8C564B' + '#E377C2' + '#7F7F7F' + '#BCBD22' + '#17BECF' + ]; + C = hex2rgb(C); +end + +function C=hotinv + C = [ + 0.9900 0.9900 0.9900 + 0.9500 0.9000 0.6000 + 1.0000 0.8000 0.3000 + 1.0000 0.6000 0.0000 + 1.0000 0.3000 0.0000 + 1.0000 0.0000 0.0000 + 0.5000 0.0000 0.0000 + 0.0000 0.0000 0.0000 + ]; +end + +function C=BCGWHcheckcov + C = [ + 0 0 0 + 0.0131 0.0281 0.0915 + 0.0261 0.0562 0.1830 + 0.0392 0.0843 0.2745 + 0.0523 0.1124 0.3660 + 0.0654 0.1405 0.4575 + 0.0784 0.1686 0.5490 + 0.1221 0.2437 0.6134 + 0.1658 0.3188 0.6779 + 0.2095 0.3938 0.7423 + 0.2532 0.4689 0.8067 + 0.2969 0.5440 0.8711 + 0.3406 0.6190 0.9356 + 0.3843 0.6941 1.0000 + 0.3494 0.7219 0.9091 + 0.3144 0.7497 0.8182 + 0.2795 0.7775 0.7273 + 0.2446 0.8053 0.6364 + 0.2096 0.8332 0.5455 + 0.1747 0.8610 0.4545 + 0.1398 0.8888 0.3636 + 0.1048 0.9166 0.2727 + 0.0699 0.9444 0.1818 + 0.0349 0.9722 0.0909 + 0 1.0000 0 + 0.1667 1.0000 0 + 0.3333 1.0000 0 + 0.5000 1.0000 0 + 0.6667 1.0000 0 + 0.8333 1.0000 0 + 1.0000 1.0000 0 + 1.0000 0.8333 0 + 1.0000 0.6667 0 + 1.0000 0.5000 0 + 1.0000 0.3333 0 + 1.0000 0.1667 0 + 1.0000 0 0 + 1.0000 0.0621 0.0719 + 1.0000 0.1242 0.1438 + 1.0000 0.1863 0.2157 + 1.0000 0.2484 0.2876 + 1.0000 0.3105 0.3595 + 1.0000 0.3725 0.4314 + 1.0000 0.4346 0.5033 + 1.0000 0.4967 0.5752 + 1.0000 0.5588 0.6471 + 1.0000 0.6209 0.7190 + 1.0000 0.6830 0.7908 + 1.0000 0.7451 0.8627 + 0.9663 0.7077 0.8424 + 0.9325 0.6703 0.8220 + 0.8988 0.6329 0.8016 + 0.8651 0.5956 0.7812 + 0.8314 0.5582 0.7608 + 0.7976 0.5208 0.7404 + 0.7639 0.4834 0.7200 + 0.7302 0.4460 0.6996 + 0.6965 0.4086 0.6792 + 0.6627 0.3712 0.6588 + 0.6290 0.3339 0.6384 + 0.5953 0.2965 0.6180 + 0.5616 0.2591 0.5976 + 0.5278 0.2217 0.5773 + 0.4941 0.1843 0.5569 + ]; +end + +function C=BCGWHgov +C = [ + 0.95 0.95 0.95 + 0.5 0.5 0.95 + 0 0.5 1 + 0 1 0.5 + 0.5 1.0000 0 + 0.4000 0.4000 0 + 0.8000 0 0 + 0.9000 0.4314 0.4627 + 1.0000 0.8627 0.9255 + 1.0000 0.4314 0.9627 + 1.0000 0 1.0000 + ...0.7882 0 1.0000 + 1 1 1.0000 + 0.7882 0 1.0000 + ]; +end + +function C=BCGWHnov +C = [ + 0 0 0 + ...0.0174 0.4980 0.7403 + ...0.8084 0.9216 1.0000 + ...0.6784 0.9216 1.0000 + 0.0 0.05 .5 + 0.0 0.4 1 % CSF + 0.0 0.7 0.1 % + 0 0.9500 0 % GM + 1.0000 1.0000 0 % + 0.8000 0 0 % WM + 0.9000 0.4314 0.4627 + 1.0000 0.8627 0.9255 + 1.0000 0.4314 0.9627 + 1.0000 1 1.0000 + 0.7882 1 1.0000 + 1 1 1.0000 + ]; +end + +function C=BCGWHn + C = [ + 0.0392 0.1412 0.4157 + 0.0349 0.2366 0.4806 + 0.0305 0.3320 0.5455 + 0.0261 0.4275 0.6105 + 0.0218 0.5229 0.6754 + 0.0174 0.6183 0.7403 + 0.0131 0.7137 0.8052 + 0.0087 0.8092 0.8702 + 0.0044 0.9046 0.9351 + 0 1.0000 1.0000 + 0 0.9163 0.8333 + 0 0.8327 0.6667 + 0 0.7490 0.5000 + 0 0.6653 0.3333 + 0 0.5817 0.1667 + 0 0.4980 0 + 0 0.5984 0 + 0 0.6988 0 + 0 0.7992 0 + 0 0.8996 0 + 0 1.0000 0 + 0.3333 1.0000 0 + 0.6667 1.0000 0 + 1.0000 1.0000 0 + 1.0000 0.8902 0 + 1.0000 0.7804 0 + 1.0000 0.6706 0 + 1.0000 0.5608 0 + 1.0000 0.4510 0 + 0.9333 0.3007 0 + 0.8667 0.1503 0 + 0.8000 0 0 + 0.8154 0.0462 0.0603 + 0.8308 0.0923 0.1207 + 0.8462 0.1385 0.1810 + 0.8615 0.1846 0.2413 + 0.8769 0.2308 0.3017 + 0.8923 0.2769 0.3620 + 0.9077 0.3231 0.4223 + 0.9231 0.3692 0.4827 + 0.9385 0.4154 0.5430 + 0.9538 0.4615 0.6033 + 0.9692 0.5077 0.6637 + 0.9846 0.5538 0.7240 + 1.0000 0.6000 0.7843 + 0.9974 0.6214 0.7935 + 0.9948 0.6429 0.8026 + 0.9922 0.6643 0.8118 + 0.9895 0.6858 0.8209 + 0.9869 0.7072 0.8301 + 0.9843 0.7286 0.8392 + 0.9817 0.7501 0.8484 + 0.9791 0.7715 0.8575 + 0.9765 0.7929 0.8667 + 0.9739 0.8144 0.8758 + 0.9712 0.8358 0.8850 + 0.9686 0.8573 0.8941 + 0.9660 0.8787 0.9033 + 0.9634 0.9001 0.9124 + 0.9608 0.9216 0.9216 + ]; +end + +function C=BCGWHnov_old + C = [ + 0.0392 0.1412 0.4157 + 0.0349 0.2366 0.4806 + 0.0305 0.3320 0.5455 + 0.0261 0.4275 0.6105 + 0.0218 0.4980 0.6754 + 0.0174 0.4980 0.7403 + 0.0131 0.4980 0.8052 + 0.0087 0.4980 0.8702 + 0.0044 0.4980 0.9351 + 0 0.4980 1.0000 + 0 0.4980 0.8333 + 0 0.4980 0.6667 + 0 0.4980 0.5000 + 0 0.4980 0.3333 + 0 0.4980 0.1667 + 0 0.4980 0 + 0 0.6117 0 + 0 0.7255 0 + 0 0.8392 0 + 0 0.9529 0 + 0 1.0000 0 + 0.2405 0.9608 0.0013 + 0.4810 0.9216 0.0026 + 0.7216 0.8824 0.0039 + 0.8608 0.9412 0.0020 + 1.0000 1.0000 0 + 1.0000 0.8588 0 + 1.0000 0.6549 0 + 1.0000 0.4510 0 + 0.9000 0.2255 0 + 0.8000 0 0 + 0.8200 0.0600 0.0784 + 0.8400 0.1200 0.1569 + 0.8600 0.1800 0.2353 + 0.8800 0.2400 0.3137 + 0.9000 0.3000 0.3922 + 0.9200 0.3600 0.4706 + 0.9400 0.4200 0.5490 + 0.9600 0.4800 0.6274 + 0.9800 0.5400 0.7059 + 1.0000 0.6000 0.7843 + 0.9749 0.5400 0.7808 + 0.9498 0.4800 0.7772 + 0.9247 0.4200 0.7737 + 0.8996 0.3600 0.7702 + 0.8745 0.3000 0.7667 + 0.8494 0.2400 0.7631 + 0.8243 0.1800 0.7596 + 0.7992 0.1200 0.7561 + 0.7741 0.0600 0.7525 + 0.7490 0 0.7490 + 0.7102 0 0.7102 + 0.6714 0 0.6714 + 0.6327 0 0.6327 + 0.5939 0 0.5939 + 0.5551 0 0.5551 + 0.5163 0 0.5163 + 0.4776 0 0.4776 + 0.4388 0 0.4388 + 0.4000 0 0.4000 + 0 0 0 + ]; +end + +function C=BCGWHw + C = [ + 1.0000 1.0000 1.0000 + 0.9741 0.9843 0.9961 + 0.9482 0.9686 0.9922 + 0.9224 0.9530 0.9882 + 0.8965 0.9373 0.9843 + 0.8706 0.9216 0.9804 + 0.8322 0.9216 0.9843 + 0.7937 0.9216 0.9882 + 0.7553 0.9216 0.9922 + 0.7168 0.9216 0.9961 + 0.6784 0.9216 1.0000 + 0.5686 0.8470 0.8882 + 0.4588 0.7725 0.7765 + 0.3059 0.6810 0.5177 + 0.1529 0.5895 0.2588 + 0 0.4980 0 + 0 0.5984 0 + 0 0.6988 0 + 0 0.7992 0 + 0 0.8996 0 + 0 1.0000 0 + 0.2500 1.0000 0 + 0.5000 1.0000 0 + 0.7500 1.0000 0 + 1.0000 1.0000 0 + 1.0000 0.8627 0 + 1.0000 0.7255 0 + 1.0000 0.5882 0 + 1.0000 0.4510 0 + 0.9333 0.3007 0 + 0.8667 0.1503 0 + 0.8000 0 0 + 0.8500 0.1000 0.2000 + 0.9000 0.2000 0.4000 + 0.9500 0.3000 0.6000 + 1.0000 0.4000 0.8000 + 1.0000 0.4672 0.8286 + 1.0000 0.5345 0.8571 + 1.0000 0.6017 0.8857 + 1.0000 0.6689 0.9143 + 1.0000 0.7361 0.9429 + 1.0000 0.8034 0.9714 + 1.0000 0.8706 1.0000 + 0.9500 0.7868 1.0000 + 0.9000 0.7029 1.0000 + 0.8500 0.6191 1.0000 + 0.8000 0.5353 1.0000 + 0.7500 0.4515 1.0000 + 0.7000 0.3676 1.0000 + 0.6500 0.2838 1.0000 + 0.6000 0.2000 1.0000 + 0.5250 0.1750 1.0000 + 0.4500 0.1500 1.0000 + 0.3750 0.1250 1.0000 + 0.3000 0.1000 1.0000 + 0.2250 0.0750 1.0000 + 0.1500 0.0500 1.0000 + 0.0750 0.0250 1.0000 + 0 0 1.0000 + 0 0 0 + ]; +end + +function C=BCGWHwov + C = [ + 1.0000 1.0000 1.0000 + 0.9741 0.9843 0.9961 + 0.9482 0.9686 0.9922 + 0.9224 0.9530 0.9882 + 0.8965 0.9373 0.9843 + 0.8706 0.9216 0.9804 + 0.8225 0.9216 0.9853 + 0.7745 0.9216 0.9902 + 0.7264 0.9216 0.9951 + 0.6784 0.9216 1.0000 + 0.6052 0.8719 0.9255 + 0.5320 0.8222 0.8510 + 0.4588 0.7725 0.7765 + 0.2294 0.6352 0.3882 + 0 0.4980 0 + 0 0.6117 0 + 0 0.7255 0 + 0 0.8392 0 + 0 0.9529 0 + 0 1.0000 0 + 0.2405 0.9608 0.0013 + 0.4810 0.9216 0.0026 + 0.7216 0.8824 0.0039 + 0.8608 0.9412 0.0020 + 1.0000 1.0000 0 + 1.0000 0.8588 0 + 1.0000 0.6549 0 + 1.0000 0.4510 0 + 0.9000 0.2255 0 + 0.8000 0 0 + 0.8200 0.0600 0.0784 + 0.8400 0.1200 0.1569 + 0.8600 0.1800 0.2353 + 0.8800 0.2400 0.3137 + 0.9000 0.3000 0.3922 + 0.9200 0.3600 0.4706 + 0.9400 0.4200 0.5490 + 0.9600 0.4800 0.6274 + 0.9800 0.5400 0.7059 + 1.0000 0.6000 0.7843 + 0.9749 0.5400 0.7808 + 0.9498 0.4800 0.7772 + 0.9247 0.4200 0.7737 + 0.8996 0.3600 0.7702 + 0.8745 0.3000 0.7667 + 0.8494 0.2400 0.7631 + 0.8243 0.1800 0.7596 + 0.7992 0.1200 0.7561 + 0.7741 0.0600 0.7525 + 0.7490 0 0.7490 + 0.7102 0 0.7102 + 0.6714 0 0.6714 + 0.6327 0 0.6327 + 0.5939 0 0.5939 + 0.5551 0 0.5551 + 0.5163 0 0.5163 + 0.4776 0 0.4776 + 0.4388 0 0.4388 + 0.4000 0 0.4000 + 0 0 0 + ]; +end + +function C = blue + C = [ + 0.02 0.25 0.50 + 0.20 0.45 0.75 + 0.40 0.80 0.95 + 0.80 0.95 0.98 + 0.94 0.96 0.99 + ]; +end + +function C = turbo +%TURBO Turbo colormap. +% TURBO(M) returns an M-by-3 matrix containing the turbo colormap, a +% variant of the jet colormap that is more perceptually uniform. +C = [ + 0.18995, 0.07176, 0.23217; + 0.19483, 0.08339, 0.26149; + 0.19956, 0.09498, 0.29024; + 0.20415, 0.10652, 0.31844; + 0.20860, 0.11802, 0.34607; + 0.21291, 0.12947, 0.37314; + 0.21708, 0.14087, 0.39964; + 0.22111, 0.15223, 0.42558; + 0.22500, 0.16354, 0.45096; + 0.22875, 0.17481, 0.47578; + 0.23236, 0.18603, 0.50004; + 0.23582, 0.19720, 0.52373; + 0.23915, 0.20833, 0.54686; + 0.24234, 0.21941, 0.56942; + 0.24539, 0.23044, 0.59142; + 0.24830, 0.24143, 0.61286; + 0.25107, 0.25237, 0.63374; + 0.25369, 0.26327, 0.65406; + 0.25618, 0.27412, 0.67381; + 0.25853, 0.28492, 0.69300; + 0.26074, 0.29568, 0.71162; + 0.26280, 0.30639, 0.72968; + 0.26473, 0.31706, 0.74718; + 0.26652, 0.32768, 0.76412; + 0.26816, 0.33825, 0.78050; + 0.26967, 0.34878, 0.79631; + 0.27103, 0.35926, 0.81156; + 0.27226, 0.36970, 0.82624; + 0.27334, 0.38008, 0.84037; + 0.27429, 0.39043, 0.85393; + 0.27509, 0.40072, 0.86692; + 0.27576, 0.41097, 0.87936; + 0.27628, 0.42118, 0.89123; + 0.27667, 0.43134, 0.90254; + 0.27691, 0.44145, 0.91328; + 0.27701, 0.45152, 0.92347; + 0.27698, 0.46153, 0.93309; + 0.27680, 0.47151, 0.94214; + 0.27648, 0.48144, 0.95064; + 0.27603, 0.49132, 0.95857; + 0.27543, 0.50115, 0.96594; + 0.27469, 0.51094, 0.97275; + 0.27381, 0.52069, 0.97899; + 0.27273, 0.53040, 0.98461; + 0.27106, 0.54015, 0.98930; + 0.26878, 0.54995, 0.99303; + 0.26592, 0.55979, 0.99583; + 0.26252, 0.56967, 0.99773; + 0.25862, 0.57958, 0.99876; + 0.25425, 0.58950, 0.99896; + 0.24946, 0.59943, 0.99835; + 0.24427, 0.60937, 0.99697; + 0.23874, 0.61931, 0.99485; + 0.23288, 0.62923, 0.99202; + 0.22676, 0.63913, 0.98851; + 0.22039, 0.64901, 0.98436; + 0.21382, 0.65886, 0.97959; + 0.20708, 0.66866, 0.97423; + 0.20021, 0.67842, 0.96833; + 0.19326, 0.68812, 0.96190; + 0.18625, 0.69775, 0.95498; + 0.17923, 0.70732, 0.94761; + 0.17223, 0.71680, 0.93981; + 0.16529, 0.72620, 0.93161; + 0.15844, 0.73551, 0.92305; + 0.15173, 0.74472, 0.91416; + 0.14519, 0.75381, 0.90496; + 0.13886, 0.76279, 0.89550; + 0.13278, 0.77165, 0.88580; + 0.12698, 0.78037, 0.87590; + 0.12151, 0.78896, 0.86581; + 0.11639, 0.79740, 0.85559; + 0.11167, 0.80569, 0.84525; + 0.10738, 0.81381, 0.83484; + 0.10357, 0.82177, 0.82437; + 0.10026, 0.82955, 0.81389; + 0.09750, 0.83714, 0.80342; + 0.09532, 0.84455, 0.79299; + 0.09377, 0.85175, 0.78264; + 0.09287, 0.85875, 0.77240; + 0.09267, 0.86554, 0.76230; + 0.09320, 0.87211, 0.75237; + 0.09451, 0.87844, 0.74265; + 0.09662, 0.88454, 0.73316; + 0.09958, 0.89040, 0.72393; + 0.10342, 0.89600, 0.71500; + 0.10815, 0.90142, 0.70599; + 0.11374, 0.90673, 0.69651; + 0.12014, 0.91193, 0.68660; + 0.12733, 0.91701, 0.67627; + 0.13526, 0.92197, 0.66556; + 0.14391, 0.92680, 0.65448; + 0.15323, 0.93151, 0.64308; + 0.16319, 0.93609, 0.63137; + 0.17377, 0.94053, 0.61938; + 0.18491, 0.94484, 0.60713; + 0.19659, 0.94901, 0.59466; + 0.20877, 0.95304, 0.58199; + 0.22142, 0.95692, 0.56914; + 0.23449, 0.96065, 0.55614; + 0.24797, 0.96423, 0.54303; + 0.26180, 0.96765, 0.52981; + 0.27597, 0.97092, 0.51653; + 0.29042, 0.97403, 0.50321; + 0.30513, 0.97697, 0.48987; + 0.32006, 0.97974, 0.47654; + 0.33517, 0.98234, 0.46325; + 0.35043, 0.98477, 0.45002; + 0.36581, 0.98702, 0.43688; + 0.38127, 0.98909, 0.42386; + 0.39678, 0.99098, 0.41098; + 0.41229, 0.99268, 0.39826; + 0.42778, 0.99419, 0.38575; + 0.44321, 0.99551, 0.37345; + 0.45854, 0.99663, 0.36140; + 0.47375, 0.99755, 0.34963; + 0.48879, 0.99828, 0.33816; + 0.50362, 0.99879, 0.32701; + 0.51822, 0.99910, 0.31622; + 0.53255, 0.99919, 0.30581; + 0.54658, 0.99907, 0.29581; + 0.56026, 0.99873, 0.28623; + 0.57357, 0.99817, 0.27712; + 0.58646, 0.99739, 0.26849; + 0.59891, 0.99638, 0.26038; + 0.61088, 0.99514, 0.25280; + 0.62233, 0.99366, 0.24579; + 0.63323, 0.99195, 0.23937; + 0.64362, 0.98999, 0.23356; + 0.65394, 0.98775, 0.22835; + 0.66428, 0.98524, 0.22370; + 0.67462, 0.98246, 0.21960; + 0.68494, 0.97941, 0.21602; + 0.69525, 0.97610, 0.21294; + 0.70553, 0.97255, 0.21032; + 0.71577, 0.96875, 0.20815; + 0.72596, 0.96470, 0.20640; + 0.73610, 0.96043, 0.20504; + 0.74617, 0.95593, 0.20406; + 0.75617, 0.95121, 0.20343; + 0.76608, 0.94627, 0.20311; + 0.77591, 0.94113, 0.20310; + 0.78563, 0.93579, 0.20336; + 0.79524, 0.93025, 0.20386; + 0.80473, 0.92452, 0.20459; + 0.81410, 0.91861, 0.20552; + 0.82333, 0.91253, 0.20663; + 0.83241, 0.90627, 0.20788; + 0.84133, 0.89986, 0.20926; + 0.85010, 0.89328, 0.21074; + 0.85868, 0.88655, 0.21230; + 0.86709, 0.87968, 0.21391; + 0.87530, 0.87267, 0.21555; + 0.88331, 0.86553, 0.21719; + 0.89112, 0.85826, 0.21880; + 0.89870, 0.85087, 0.22038; + 0.90605, 0.84337, 0.22188; + 0.91317, 0.83576, 0.22328; + 0.92004, 0.82806, 0.22456; + 0.92666, 0.82025, 0.22570; + 0.93301, 0.81236, 0.22667; + 0.93909, 0.80439, 0.22744; + 0.94489, 0.79634, 0.22800; + 0.95039, 0.78823, 0.22831; + 0.95560, 0.78005, 0.22836; + 0.96049, 0.77181, 0.22811; + 0.96507, 0.76352, 0.22754; + 0.96931, 0.75519, 0.22663; + 0.97323, 0.74682, 0.22536; + 0.97679, 0.73842, 0.22369; + 0.98000, 0.73000, 0.22161; + 0.98289, 0.72140, 0.21918; + 0.98549, 0.71250, 0.21650; + 0.98781, 0.70330, 0.21358; + 0.98986, 0.69382, 0.21043; + 0.99163, 0.68408, 0.20706; + 0.99314, 0.67408, 0.20348; + 0.99438, 0.66386, 0.19971; + 0.99535, 0.65341, 0.19577; + 0.99607, 0.64277, 0.19165; + 0.99654, 0.63193, 0.18738; + 0.99675, 0.62093, 0.18297; + 0.99672, 0.60977, 0.17842; + 0.99644, 0.59846, 0.17376; + 0.99593, 0.58703, 0.16899; + 0.99517, 0.57549, 0.16412; + 0.99419, 0.56386, 0.15918; + 0.99297, 0.55214, 0.15417; + 0.99153, 0.54036, 0.14910; + 0.98987, 0.52854, 0.14398; + 0.98799, 0.51667, 0.13883; + 0.98590, 0.50479, 0.13367; + 0.98360, 0.49291, 0.12849; + 0.98108, 0.48104, 0.12332; + 0.97837, 0.46920, 0.11817; + 0.97545, 0.45740, 0.11305; + 0.97234, 0.44565, 0.10797; + 0.96904, 0.43399, 0.10294; + 0.96555, 0.42241, 0.09798; + 0.96187, 0.41093, 0.09310; + 0.95801, 0.39958, 0.08831; + 0.95398, 0.38836, 0.08362; + 0.94977, 0.37729, 0.07905; + 0.94538, 0.36638, 0.07461; + 0.94084, 0.35566, 0.07031; + 0.93612, 0.34513, 0.06616; + 0.93125, 0.33482, 0.06218; + 0.92623, 0.32473, 0.05837; + 0.92105, 0.31489, 0.05475; + 0.91572, 0.30530, 0.05134; + 0.91024, 0.29599, 0.04814; + 0.90463, 0.28696, 0.04516; + 0.89888, 0.27824, 0.04243; + 0.89298, 0.26981, 0.03993; + 0.88691, 0.26152, 0.03753; + 0.88066, 0.25334, 0.03521; + 0.87422, 0.24526, 0.03297; + 0.86760, 0.23730, 0.03082; + 0.86079, 0.22945, 0.02875; + 0.85380, 0.22170, 0.02677; + 0.84662, 0.21407, 0.02487; + 0.83926, 0.20654, 0.02305; + 0.83172, 0.19912, 0.02131; + 0.82399, 0.19182, 0.01966; + 0.81608, 0.18462, 0.01809; + 0.80799, 0.17753, 0.01660; + 0.79971, 0.17055, 0.01520; + 0.79125, 0.16368, 0.01387; + 0.78260, 0.15693, 0.01264; + 0.77377, 0.15028, 0.01148; + 0.76476, 0.14374, 0.01041; + 0.75556, 0.13731, 0.00942; + 0.74617, 0.13098, 0.00851; + 0.73661, 0.12477, 0.00769; + 0.72686, 0.11867, 0.00695; + 0.71692, 0.11268, 0.00629; + 0.70680, 0.10680, 0.00571; + 0.69650, 0.10102, 0.00522; + 0.68602, 0.09536, 0.00481; + 0.67535, 0.08980, 0.00449; + 0.66449, 0.08436, 0.00424; + 0.65345, 0.07902, 0.00408; + 0.64223, 0.07380, 0.00401; + 0.63082, 0.06868, 0.00401; + 0.61923, 0.06367, 0.00410; + 0.60746, 0.05878, 0.00427; + 0.59550, 0.05399, 0.00453; + 0.58336, 0.04931, 0.00486; + 0.57103, 0.04474, 0.00529; + 0.55852, 0.04028, 0.00579; + 0.54583, 0.03593, 0.00638; + 0.53295, 0.03169, 0.00705; + 0.51989, 0.02756, 0.00780; + 0.50664, 0.02354, 0.00863; + 0.49321, 0.01963, 0.00955; + 0.47960, 0.01583, 0.01055]; +end + +function rgb = hex2rgb(hex) + rgb = reshape(sscanf(hex(:,2:end)','%2x'),3,[]).'/255; +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_surf_laterality_index.m",".m","1802","53","function cat_surf_laterality_index(P) +% ______________________________________________________________________ +% Calculation of laterality index for 32k-meshes +% LI = (L-R)/(R+L) +% +% The result is indicated with a prepended 'LI_' in the dataname +% of the file. +% Please note that only the data of the left hemipshere is stored, since +% the values in the opposite hemisphere would be simply inverted and other- +% wise identical except for the sign. +% +% This function only works with symmetrical 32k-meshes! +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +if ~nargin + P = spm_select(Inf,'mesh','Select 32k-meshes for LI estimation',{},pwd,'mesh.*.resampled_32k'); +end + +n = size(P,1); +for i=1:n + mesh_name = deblank(P(i,:)); + M = gifti(mesh_name); + + % check that values are in the mesh and the data size is that of a 32k mesh + if isfield(M,'cdata') && numel(M.cdata) ~= 64984 + fprintf('ERROR: %s does not contain resampled 32k-mesh values.\n',mesh_name); + break + end + + % flip values + left_cdata = M.cdata(1:32492); + right_cdata = M.cdata(32493:64984); + cdata = M.cdata; + flipped_cdata = [right_cdata;left_cdata]; + + LI = (cdata-flipped_cdata)./(cdata+flipped_cdata+eps); + LI = (left_cdata-right_cdata)./(left_cdata+right_cdata+eps); + M.cdata = [LI; zeros(size(LI))]; + + % rename dataname + sinfo = cat_surf_info(mesh_name); + flipped_name = char(cat_surf_rename(mesh_name,'dataname',['LI_' sinfo.dataname])); + + save(M, flipped_name, 'Base64Binary'); + fprintf('Save LI in %s\n',flipped_name); +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_surf_resamp.m",".m","18722","478","function vout = cat_surf_resamp(varargin) +% ______________________________________________________________________ +% Function to resample parameters to template space and smooth it. +% +% [Psdata] = cat_surf_resamp(job) +% +% job.data_surf .. cellstr of files +% job.fwhm_surf .. filter size in mm +% job.verb .. display command line progress +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +%#ok<*AGROW,*STREMP> + +% Todo: +% - resampling of white matter, pial, hull and core surfaces is not +% supported that are only available in the developer mode (RD20180408) +% > catched by error message + + + % Transform input + % Due to dependencies the input has to be a cell-array of cellstr in general. + % However, the expert GUI allows additional cases to handle or ignore dependencies. + % This results in a more complex input with another cell level, internal + % representation and final output as cell of cellstr. + if nargin == 1 + % complex developer input of different structures to handle dependencies differently + % here we have to build the classical input structure + if isfield(varargin{1},'sample') + if ~isfield(varargin{1},'data_surf') + varargin{1}.data_surf = {}; + end + for si=1:numel(varargin{1}.sample) + if isfield(varargin{1}.sample{si},'data_surf') + for sai=1:numel(varargin{1}.sample) + varargin{1}.data_surf = [varargin{1}.data_surf varargin{1}.sample{sai}.data_surf]; + end + elseif isfield(varargin{1}.sample{si},'data_surf_mixed') + varargin{1}.data_surf = [varargin{1}.data_surf varargin{1}.sample{:}.data_surf_mixed]; + end + end + varargin{1} = rmfield(varargin{1},'sample'); + varargin{1}.data_surf = unique(varargin{1}.data_surf); + end + + % classical simple input structure + if iscell(varargin{1}.data_surf) + %% + P = ''; + for i = 1:numel(varargin{1}.data_surf) + if iscell(varargin{1}.data_surf) + P = char( [cellstr(P); varargin{1}.data_surf{i} ] ); %[P; char(varargin{1}.data_surf{i})]; + else + P = char( [cellstr(P); varargin{1}.data_surf(i) ] ); %[P; char(varargin{1}.data_surf{i})]; + end + end + P = P(2:end,:); + else + P = char(varargin{1}.data_surf); + end + job = varargin{1}; + elseif nargin > 1 + spm_clf('Interactive'); + P = cellstr(spm_select([1 inf],'any','Select surface data')); + job = struct(); + else + error('No argument given.') + end + + if ~isfield(job,'fwhm_surf') + spm('alert!', ['Surface smoothing method has changed with release r1248 and the '... + 'recommended FWHM is now slightly smaller. For cortical thickness a good starting value '... + 'is 15mm, while other surface parameters based on cortex folding (e.g. gyrification, '... + 'cortical complexity) need a larger filter size of about 20-25mm. Please update your scripts '... + 'and replace the old field ""fwhm"" by ""fwhm_surf"" and adapt the values.'], 1); + end + + def.trerr = 0; + def.fwhm_surf = 0; + def.nproc = 0; + def.mesh32k = 1; + def.merge_hemi = 1; + def.lazy = 0; + def.verb = cat_get_defaults('extopts.verb'); + def.debug = cat_get_defaults('extopts.verb')>2; + def.fsavgDir = fullfile(fileparts(mfilename('fullpath')),'templates_surfaces'); + + listpp = struct('new',0,'exist',0,'note',0,'error',0); + + job = cat_io_checkinopt(job,def); + + if job.mesh32k + job.fsavgDir = fullfile(fileparts(mfilename('fullpath')),'templates_surfaces_32k'); + str_resamp = '.resampled_32k'; + else + job.fsavgDir = fullfile(fileparts(mfilename('fullpath')),'templates_surfaces'); + str_resamp = '.resampled'; + end + + % use external dat-file if defined to increase processing speed and keep SPM.mat file small + % because the cdata field is not saved with full data in SPM.mat + if cat_get_defaults('extopts.gifti_dat') + gformat = 'ExternalFileBinary'; + else + gformat = 'Base64Binary'; + end + + % split job and data into separate processes to save computation time + if isfield(job,'nproc') && job.nproc>0 && (~isfield(job,'process_index')) && (size(P,1)>1) + %if nargout==1 + vout.Psdata = cat_parallelize(job,mfilename,'data_surf'); + return + end + + % normal processing + % ____________________________________________________________________ + + % new banner + if isfield(job,'process_index'), spm('FnBanner',mfilename); end + + % display something + spm_clf('Interactive'); + cat_progress_bar('Init',size(P,1),'Smoothed Resampled','Surfaces Completed'); + + Psdata = cell(size(P,1),1); + lPsdata = cell(size(P,1),1); + rPsdata = cell(size(P,1),1); + + for i=1:size(P,1) + pstr = sprintf(sprintf('%% %ds',max(10,round(log10(size(P,1))+3) * 2)),sprintf('%d/%d) ',i,size(P,1))); + nstr = repmat(' ',1,numel(pstr)); + + if ~exist(deblank(P(i,:)),'file') + cat_io_cprintf('warn',sprintf('%sERROR - The file ""%s"" does not exist!\n',pstr,deblank(P(i,:)))); + listpp.error = listpp.error + 1; + continue + end + + stime = clock; + [pp,ff,ex] = spm_fileparts(deblank(P(i,:))); ffex = [ff ex]; + if any([strfind(ffex,'.sphere.'),strfind(ffex,'.central.'),strfind(ffex,'.resampled_tmp'),... + strfind(ffex,'.resampled'),strfind(ff,'.area.tmp.'),strfind(ffex(end-3:end),'.mat'),... + strfind(ffex(end-3:end),'.mat'),strfind(ffex(end-1:end),'.m')]) + if job.verb + cat_io_cprintf('note',sprintf('%s NOTE - Cannot process ""%s""!\n',pstr,deblank(P(i,:)))); + listpp.note = listpp.note + 1; + end + continue; + end + + name0 = [ff(3:end) ex]; % remove leading hemisphere information + name0 = strrep(name0,'.gii',''); % remove .gii extension + hemistr = {'lh','rh','cb'}; + exist_hemi = []; + + if ~isempty(strfind(name0,'white')) || ~isempty(strfind(name0,'inner')) || ... + ~isempty(strfind(name0,'pial')) || ~isempty(strfind(name0,'outer')) || ... + ~isempty(strfind(name0,'core')) || ~isempty(strfind(name0,'hull')) + cat_io_cprintf('note',sprintf('%s NOTE - White matter, pial, hull, or core surfaces can not be resampled so far!\n',pstr)); + listpp.error = listpp.error + 1; + continue + end + + % define output name for lazy option + surfacefield = 'central'; + %% + if job.lazy + for j=1:length(hemistr) + hemi = hemistr{j}; + name = [hemi name0]; + k = strfind(name,'.'); + pname = ff(k(1)+1:k(2)-1); + Pcentral = [name(1:k(1)) strrep(name(k(1)+1:k(2)-1),pname,surfacefield) name(k(2):end) '.gii']; + if job.fwhm_surf > 0 + Pfwhm = [sprintf('s%g.',job.fwhm_surf) strrep(Pcentral(1:k(2)-1),surfacefield,[pname str_resamp]) Pcentral(k(2):end)]; + else + Pfwhm = [strrep(Pcentral(1:k(2)-1),surfacefield,[pname str_resamp]) Pcentral(k(2):end)]; + end + + if job.merge_hemi + k = strfind(Pfwhm,'.'); + Pfwhm = [strrep(Pfwhm(1:k(2)),'.lh.','.mesh.') Pfwhm(k(2)+1:end)]; + %Pcentral = [strrep(Pcentral(1:3),'lh.','mesh.') Pcentral(4:end)]; + end + Pfwhm = strrep(Pfwhm,surfacefield,[pname str_resamp]); + + if j==1 + Psdata{i} = fullfile(pp,Pfwhm); + end + if job.merge_hemi + Psname = [Pfwhm '.gii']; + if j==1, lPsdata{i} = Psname; end + if j==2, rPsdata{i} = Psname; end + end + end + end + %% + if ~job.lazy || (job.merge_hemi && cat_io_rerun(Psdata{i},P(i,:)) ) || ... + (~job.merge_hemi && cat_io_rerun(lPsdata{i},P(i,:)) && cat_io_rerun(rPsdata{i},P(i,:)) ) + + % go through left and right and potentially cerebellar hemispheres + for j=1:length(hemistr) + + % add hemisphere name + hemi = hemistr{j}; + name = [hemi name0]; + + Pvalue0 = fullfile(pp,name); + + % check that file exists + if ~exist(Pvalue0,'file') %&& hemistr{j}(1)=='c' + continue + end + + exist_hemi = [exist_hemi j]; + + k = strfind(name,'.'); + pname = ff(k(1)+1:k(2)-1); + Pcentralf = [name(1:k(1)) strrep(name(k(1)+1:k(2)-1),pname,surfacefield) name(k(2):end) '.gii']; + Pspherereg = fullfile(pp,strrep(Pcentralf,surfacefield,'sphere.reg')); + Pvalue = fullfile(pp,strrep(Pcentralf,surfacefield,[pname str_resamp])); + Pvalue = strrep(Pvalue,'.gii',''); % remove .gii extension + + if job.fwhm_surf > 0 + Pfwhm = fullfile(pp,[sprintf('s%g.',job.fwhm_surf) strrep(Pcentralf,surfacefield,[pname str_resamp])]); + Presamp = fullfile(pp,[sprintf('s%g.',job.fwhm_surf) strrep(Pcentralf,surfacefield,[pname '.tmp.resampled'])]); + else + Pfwhm = fullfile(pp,strrep(Pcentralf,surfacefield,[pname str_resamp])); + Presamp = fullfile(pp,strrep(Pcentralf,surfacefield,[pname 'tmp.resampled'])); + end + + Pfwhm = strrep(Pfwhm,'.gii',''); % remove .gii extension + Pcentral = fullfile(pp,Pcentralf); + Pfsavg = fullfile(job.fsavgDir,[hemi '.sphere.freesurfer.gii']); + Pmask = fullfile(job.fsavgDir,[hemi '.mask']); + + % we have to rename the final files for each hemisphere if we want to merge the hemispheres + % to not interfere with existing files + if job.merge_hemi + Pfwhm_gii = [Pfwhm '_tmp.gii']; + else + Pfwhm_gii = [Pfwhm '.gii']; + end + + % save fwhm name to merge meshes + Pfwhm_all{j} = Pfwhm_gii; + + % resample values + if ~isempty(strfind(pname,'area')) || ~isempty(strfind(pname,'gmv')) + % resample values using delaunay-based age map + + % create mapping between + if job.mesh32k + Pedgemap = cat_io_strrep(Pcentral,{'.central.';'.gii'},{'.edgemap32k.';'.mat'}); + else + Pedgemap = cat_io_strrep(Pcentral,{'.central.';'.gii'},{'.edgemap164k.';'.mat'}); + end + evalc('Ssreg = gifti(Pspherereg);'); + if exist(Pedgemap,'file') + load(Pedgemap,'edgemap'); + end + if ~exist('edgemap','var') || ~isfield(edgemap,'nvertices') || edgemap.nvertices(1) ~= size(Ssreg.vertices,1) + %% + stime2 = clock; + if job.mesh32k + fprintf('\t\tEstimate mapping for 32k surface %s',Pspherereg); + else + fprintf('\t\tEstimate mapping for 164k surface %s',Pspherereg); + end + evalc('Ssreg = gifti(Pspherereg);'); + Sfsavg = gifti(Pfsavg); + edgemap = cat_surf_fun('createEdgemap',Ssreg,Sfsavg); + save(Pedgemap,'edgemap'); + % clear Ssreg Sfsavg; + fprintf(' takes %ds\n',round(etime(clock,stime2))); + end + + %% resample values using warped sphere + + % load individual surface and area file, apply edgemap and save resampled file + cdata = cat_io_FreeSurfer('read_surf_data',Pvalue0); + ncdata = cat_surf_fun('useEdgemap',cdata,edgemap); + cat_io_FreeSurfer('write_surf_data',Pvalue,ncdata); + cmd = sprintf('CAT_ResampleSurf ""%s"" ""%s"" ""%s"" ""%s"" ""%s"" ""%s""',Pcentral,Pspherereg,Pfsavg,Presamp,Pvalue0,Pvalue); + err = cat_system(cmd,job.debug,def.trerr); if err, continue; end + cat_io_FreeSurfer('write_surf_data',Pvalue,ncdata); + clear Si clear Si edgemap; + + else + %% resample values using warped sphere + cmd = sprintf('CAT_ResampleSurf ""%s"" ""%s"" ""%s"" ""%s"" ""%s"" ""%s""',Pcentral,Pspherereg,Pfsavg,Presamp,Pvalue0,Pvalue); + evalc('err = cat_system(cmd,job.debug,def.trerr);'); + %% + if err, continue; end + end + + if job.fwhm_surf > 0 + + %% smooth resampled values + % don't use mask for cerebellum + if strcmp(hemi,'lc') || strcmp(hemi,'rc') + cmd = sprintf('CAT_BlurSurfHK ""%s"" ""%s"" ""%g"" ""%s""',Presamp,Pfwhm,job.fwhm_surf,Pvalue); + else + cmd = sprintf('CAT_BlurSurfHK ""%s"" ""%s"" ""%g"" ""%s"" ""%s""',Presamp,Pfwhm,job.fwhm_surf,Pvalue,Pmask); + end + err = cat_system(cmd,job.debug,def.trerr); + %% + if err + cat_io_cprintf('err',sprintf('%sERROR - Smoothing & resampling of ""%s"" failed!\n',Presamp)); + listpp.error = listpp.error + 1; + continue; + end + end + + %% add values to resampled surf and save as gifti + cmd = sprintf('CAT_AddValuesToSurf ""%s"" ""%s"" ""%s""',Presamp,Pfwhm,Pfwhm_gii); + err = cat_system(cmd,job.debug,def.trerr);% if err, continue; end + + if exist(Pfwhm_gii,'file') + Psname = Pfwhm_gii; + else + cat_io_cprintf('err','The file\n %s \ncould not be found which points to issue while writing files. Please check permission and repeat processing of that subject.\n',Pfwhm_gii); + continue + end + + %% remove path from metadata to allow that files can be moved (pathname is fixed in metadata) + [pp2,ff2,ex2] = spm_fileparts(Psname); %#ok + + g = gifti(Psname); + g.private.metadata = struct('name','SurfaceID','value',[ff2 ex2]); + + if job.merge_hemi + save(g, Psname, 'Base64Binary'); + else + save(g, Psname, gformat); + end + + delete(Presamp); + delete(Pfwhm); + if job.fwhm_surf > 0, delete(Pvalue); end + + if 0 %job.verb + fprintf('Resampling %s\n',Psname); + end + + if j==1, lPsdata{i} = Psname; end + if j==2, rPsdata{i} = Psname; end + end + %if sideErr, continue; end + + % merge hemispheres + if job.merge_hemi + % name for combined hemispheres + k = strfind(name,'.'); + k0 = strfind(name0,'.'); + try + pname = ff(k(1)+1:k(2)-1); + catch + continue + end + Pcentral = [strrep(['mesh' name0(1:k0(2)-1)],pname,surfacefield) name0(k0(2):end) '.gii']; + + if job.fwhm_surf > 0 + Pfwhm = [sprintf('s%g.',job.fwhm_surf) strrep(Pcentral,surfacefield,[pname str_resamp])]; + else + Pfwhm = strrep(Pcentral,surfacefield,[pname str_resamp]); + end + + % combine left and right and optionally cerebellar meshes + switch numel(exist_hemi) + case {2,4} + if exist(Pfwhm_all{1},'file') && exist(Pfwhm_all{2},'file') + evalc('M0 = gifti({Pfwhm_all{1}, Pfwhm_all{2}})'); + evalc('M = gifti(spm_mesh_join([M0(1) M0(2)]))'); + else + warning('off','MATLAB:subscripting:noSubscriptsSpecified'); + if exist(Pfwhm_all{1},'file'), delete(Pfwhm_all{1}); end + if exist(Pfwhm_all{2},'file'), delete(Pfwhm_all{2}); end + cat_io_cprintf('err',sprintf('%sERROR - Error in merging sides of %s!\n',pstr,fullfile(pp,Pfwhm))); + listpp.error = listpp.error + 1; + continue + end + warning('off','MATLAB:subscripting:noSubscriptsSpecified'); + if exist(Pfwhm_all{1},'file'), delete(Pfwhm_all{1}); end + if exist(Pfwhm_all{2},'file'), delete(Pfwhm_all{2}); end + case 1 + cat_io_cprintf('err',sprintf('%sERROR - No data for opposite hemisphere found for %s!\n',pstr,fullfile(pp,Pfwhm))); + listpp.error = listpp.error + 1; + continue + case 3 + cat_io_cprintf('err',sprintf('%sERROR - No data for opposite cerebellar hemisphere found for %s!\n',pstr,fullfile(pp,Pfwhm))); + listpp.error = listpp.error + 1; + continue + case 0 + cat_io_cprintf('err',sprintf('%sERROR - No data was found for %s!\n',pstr,fullfile(pp,Pfwhm))); + listpp.error = listpp.error + 1; + continue + end + + if numel(exist_hemi) > 1 && ~isempty(M) + M.private.metadata(1) = struct('name','SurfaceID','value',Pfwhm); + save(M, fullfile(pp,Pfwhm), gformat); + Psdata{i} = fullfile(pp,Pfwhm); + + if job.verb && ~isempty(Psdata{i}) + fprintf('%s%4.0fs - Display resampled %s\n',pstr,etime(clock,stime),spm_file(Psdata{i},'link','cat_surf_display(''%s'')')); + listpp.new = listpp.new + 1; + end + else + cat_io_cprintf('err',sprintf('%sERROR - No data was written for %s!\n',pstr,fullfile(pp,Pfwhm))); + listpp.error = listpp.error + 1; + continue + end + + else + if job.verb && ~isempty(lPsdata{i}) + fprintf('%s%4.0fs - Display resampled %s\n',pstr,etime(clock,stime),spm_file(lPsdata{i},'link','cat_surf_display(''%s'')')); + listpp.new = listpp.new + 1; + end + if job.verb && ~isempty(rPsdata{i}) + fprintf('%s%4.0fs - Display resampled %s\n',pstr,etime(clock,stime),spm_file(rPsdata{i},'link','cat_surf_display(''%s'')')); + end + end + else + if job.verb && ~isempty(Psdata{i}) + fprintf('%sexist - Display resampled %s\n',pstr,spm_file(Psdata{i},'link','cat_surf_display(''%s'')')); + listpp.exist = listpp.exist + 1; + end + end + + cat_progress_bar('Set',i); + end + + if isfield(job,'process_index') && job.verb + if job.lazy + fprintf(' Conclusion: %d mm smoothing of %d datasets: %d new, %d existing, %d notes, %d errors. ', job.fwhm_surf, size(P,1), listpp.new, listpp.exist, listpp.note, listpp.error); + else + fprintf(' Conclusion: %d mm smoothing of %d datasets: %d normal, %d notes, %d errors. ', job.fwhm_surf, size(P,1), listpp.new, listpp.note, listpp.error); + end + end + + + if isfield(job,'process_index') + fprintf('Done\n'); + end + + if job.merge_hemi + if iscell(varargin{1}.data_surf) && iscell(varargin{1}.data_surf{1}) + n = cumsum(cellfun(@numel,varargin{1}.data_surf)); + a = [1 n+1]; a(end) = []; + for i=1:numel(varargin{1}.data_surf) + vout.sample(i).Psdata = Psdata( a(i) : n(i)); + end + else + vout.sample(1).Psdata = Psdata; + end + else + if iscell(varargin{1}.data_surf) && iscell(varargin{1}.data_surf{1}) + n = cumsum(cellfun(@numel,varargin{1}.data_surf)); + a = [1 n+1]; a(end) = []; + for i=1:numel(varargin{1}.data_surf) + vout.sample(1).lPsdata = lPsdata( a(i) : n(i)); + end + else + vout.sample(1).lPsdata = lPsdata; + end + end + + cat_progress_bar('Clear'); +end + +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_vol_localstat.m",".m","3099","71","%cat_vol_localstat Local mean, minimum, maximum, SD, and peak estimation. +% Estimates specific functions in a volume V within a mask region M. +% For each voxel v of M, the values of the neigbors of v that belong to M +% and are within a distance smaller than nb where used (i.e. masked voxels +% within a sphere of radius nb). +% +% If V contains NaNs, -INFs or INFs these values are ignored and added to +% the mask M. Masked voxels in the output volume were defined depending +% on the mskval variable, i.e. as zeros (0, default), input (1), NANs (2), +% -INF (3), or INF(4). +% +% The function was designed to extract the inhomogeneity in noisy data in +% a well-known area, such a tissue class in structural images. In general +% the mean estimated in a local neighborhood nb or after some interations +% iter. However, tissues are often affected by partial volume effects near +% the tissue boundaries and minimum/maximum can be quite helpful to reduce +% such effects. For noise estimation the local variance/standard deviation +% is also quite useful. +% Besides the mean value the local peak of the histogram can also work +% +% S = cat_vol_localstat(V,M[,nb,stat,iter,filter0,verb]) +% +% V (single) input volume +% M (logical) mask volume +% nb (double) neigbhour distance (1 .. 10) +% stat (double) 1-mean, 2-min, 3-max, 4-std +% 5-peak1, 6-peak2, 7-peak3 (experimental) +% 8-median +% 9-hist (experimental) +% iter number of iterations (default=1) +% filter0 (double) originally values <=0 were ignored (default=0) +% mskval (double) setting of masked voxels +% (0-zeros,1-input,2-NAN,3--INF,4-INF) +% verb (double) verbose output for debugging +% +% +% Examples: +% Here are some simple samples to outline the subfunctions. The mask area +% is defined by NaN. The simulated data of A is between -1 and 1 and B is +% a locial mask. +% +% == input variables == +% A = rand(20,20,3,'single') - 1; +% for i=1:size(A,2), A(:,i,:) = A(:,i,:) + (( i/size(A,2) ) - 0.5); end +% B = smooth3(smooth3(rand(size(A))))>0.5; +% +% +% == function calls == +% (1) MEAN: values around 0 +% C = cat_vol_localstat(A,B,2,1,2,2); ds('d2smns','',1,A,C,2); +% +% (2) MINIMUM: values trending torwards -1 +% C = cat_vol_localstat(A,B,2,2,2,2); ds('d2smns','',1,A,C,2); +% +% (3) MAXIMUM: values trending torwards 1 +% C = cat_vol_localstat(A,B,2,3,2,2); ds('d2smns','',1,A,C,2); +% +% (4) STANDARD DEVIATION: values about 0.5 +% C = cat_vol_localstat(A,B,2,4,1,2); ds('d2smns','',1,A,C,2); +% +% (8) MEDIAN: values around 0 +% C = cat_vol_localstat(AL,B,2,8,1,2); ds('d2smns','',1,A,C,2); +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_main_gintnormi.m",".m","2427","70","function Ysrc = cat_main_gintnormi(Ym,Tth) +% cat_main_gintnormi +% ______________________________________________________________________ +% +% Inverse function of cat_main_gintnorm that restore the original +% intensity levels of an intensity normalized image Ym. +% +% Ysrc = cat_main_gintnormi(Ym,Tth) +% +% Ysrc .. image with original intensity levels +% Ym .. intensity normalized image +% Tth .. data structure with the intensiy transformation +% +% Example: +% % old values in the original image Ysrc +% Tth.T3thx = [BGth CSFth GMth WMth WMth+diff([GMth,WMth]) ]; +% % new values of the output images of the tresholds Tth.T3thx +% Tth.T3th = 0:1/3:4/3; +% % div by 3 due to old definitions +% Ym = cat_main_gintnormi(Ysrc/3,Tth); +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + + % RD202102: There should be no inversion but in the test-retest of + % Buchert sanon-102748-00003-00001-1 it happend. + Tth.T3th = sort(Tth.T3th); + + if 1 + % RD2020: old version without interpolation is a bit inoptimal for the histogram + T3th = Tth.T3thx; + T3thx = Tth.T3th; + else + % use interpolation to avoid steps in the histogram + % makima is better but not available in oder MATLABs :/ + %try + % T3th = interp1(Tth.T3thx,1:0.1:numel(Tth.T3thx),'makima'); + % T3thx = interp1(Tth.T3th ,1:0.1:numel(Tth.T3th) ,'makima'); + %catch + if 1 % lowcontrast + T3th = interp1(Tth.T3thx,1:0.1:numel(Tth.T3thx),'linear'); + T3thx = interp1(Tth.T3th ,1:0.1:numel(Tth.T3th) ,'linear'); + else + T3th = interp1(Tth.T3thx,1:0.1:numel(Tth.T3thx),'spline'); + T3thx = interp1(Tth.T3th ,1:0.1:numel(Tth.T3th) ,'spline'); + end + end + + if all(T3th==T3thx), Ysrc = Ym; return; end + + [T3th,si] = sort(T3th); + T3thx = T3thx(si); + + %% + isc=1; + Ym = Ym*3; + Ysrc = Ym; + for i=2:numel(T3th) + M = Ym>T3th(i-1) & Ym<=T3th(i); + Ysrc(M(:)) = T3thx(i-1) + (Ym(M(:)) - T3th(i-1))/diff(T3th(i-1:i))*diff(T3thx(i-1:i)); + end + M = Ym>=T3th(end); + Ysrc(M(:)) = numel(T3th)/isc/6 + (Ym(M(:)) - T3th(i))/diff(T3th(end-1:end))*diff(T3thx(i-1:i)); +return","MATLAB" +"Neurology","ChristianGaser/cat12","cat_vol_approx.m",".m","20260","523","function [Ya,times] = cat_vol_approx(Y,method,varargin) +% Approximation of missing values +% ______________________________________________________________________ +% Approximation of missing values (nan's / zeros) by different methods. +% +% Method one (rec) is iterativelely downsampling the image as long as it +% is larger than n voxels. On the low resolution undefined voxels were +% labeled by the value of the closest neighbor and Laplace filtered with +% Dirichlet boundary condition (i.e. the original values are fixed). The +% result is resampled to the original double resolution and replaces un- +% defined voxels. +% +% Ya = cat_vol_approx(Y, 'rec' [, s ] ) +% +% Y .. input image with missing elemnts (NaN's / zeros) +% Ya .. filled output image (single) +% s .. final smoothness (default=1) +% +% Method two (nn or nh) first reduces the image to a lower resolution +% and approximate all values by aligning the value of the nearest neighbor. +% Values outside the convex hull are strongly Gaussian filtered, followed +% by Laplace filtering to avoid edges. +% +% Ya = cat_vol_approx(Y, 'nn' [, vx_vol, res ] ) +% +% Y .. input image with missing elemnts (NaN's / zeros) +% Ya .. filled output image (single) +% vx_vol .. voxel resolution of Y (default: 1) +% res .. resolution for approximation (default = 4) +% +% +% Test function: +% As most of our images have no values in the outer regions, the mask +% S is used to define the standard test case, wheras a second mask B is +% used to remove some random pattern in general. +% +% You can run a specific test case tc by calling +% +% cat_vol_approx(tc, 'test') +% cat_vol_approx(tc, 'test'[, masking, bias]) +% +% tc .. test case (1-high freq., 2-mid freq., 3-low freq.) +% masking .. use center object mask (0-no, 1-yes, default=1) +% bias .. add bias (0-no, 1..10-pos, -1..-10-neg, default=1) +% +% +% Examples: +% 1) high frequency pattern of positive values with smaller missing parts +% A = randn(100,100,100); spm_smooth(A,A,8); A = A / std(A(:)*5) + .5; +% S = A+0; spm_smooth(S,S,60); S = S + A/10 ; S = S > 0.7*max(S(:)); +% B = A .* S .* (cat_vol_smooth3X(rand(size(A)),4)>.5); +% +% 2) low frequency pattern of pos./neg. values with larger missing parts +% A = randn(100,100,100); spm_smooth(A,A,32); A = A / std(A(:)*5) * 100; +% S = A+0; spm_smooth(S,S,60); S = S + A/10 ; S = S > 0.7*max(S(:)); +% B = A .* S .* (cat_vol_smooth3X(rand(size(A)),4)>.5); +% +% Display: +% C1 = cat_vol_approx(B,'rec'); +% C2 = cat_vol_approx(B,'nn'); +% +% figure(393); +% subplot(2,2,1); imagesc(A(:,:,round(size(A,3)/2))); title('full') +% subplot(2,2,2); imagesc(B(:,:,round(size(A,3)/2))); title('masked') +% subplot(2,2,3); imagesc(C1(:,:,round(size(A,3)/2))); title('rec') +% subplot(2,2,4); imagesc(C2(:,:,round(size(A,3)/2))); title('nn') +% +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + if nargin==0, help cat_vol_approx; return; end + if ~exist('method','var'); method = 'oldnn'; end + + stime = clock; %#ok + if ~cat_io_contains(method,'test') && 1 + % ################### + % temporary manual overwrite to test replacement + % RD20231211: Although the new rec version performs better in the unit + % test. The updated nn version is closer on the old results and looked + % better on HR075. The recursive rec method shows some strange offset + % in real data that I a not understand so far. + % However, there are also some calls of the old nh version that seems + % to be worse than the old nn version and should replaced anyway. + % ################### + methodold = method; + if 1 + method = 'oldnn'; + else + method = 'rec'; + if nargin<3; vx_vol = ones(1,3); else, vx_vol = varargin{1}; end + if nargin<4; res = 4; else, res = varargin{2}; end + varargin{1} = 0; %res / mean(vx_vol); + end + + %fprintf(' cat_vol_approx: Use ""%s"" instead of (old) ""%s""!\n',method,methodold) + + end + method = strrep(method,'-test',''); + + switch method + case {'recursive','rec','r','simple','s'} + % call new approximation method + if nargin<3; s = 1; else, s = varargin{1}; end + Ya = rec_approx(Y, s); + + case {'nn','nh','linear'} % link old calls to the newer version + % updated classic approach + Ya = cat_vol_approx_classic(Y,varargin{:}); + + case 'oldnn' + % classic approach + Ya = cat_vol_approx2479(Y,'nn',varargin{:}); + + case 'oldnh' + % classic approach + Ya = cat_vol_approx2479(Y,'nh',varargin{:}); + + case 'test' + % call unit test function + if Y == 0 + xi = 0; + for ii = 1:3 % freq + for mi = 0:1 % skull + for bi = [-1 0 3] % bias + xi = xi + 1; + [rmses(xi,:),times(xi,:)] = cat_vol_approx(ii,'test',mi,bi); %#ok + end + end + end + + fprintf('RMSEs\n') + fprintf('%10s%8s%8s%8s%8s%8s%8s\n','method:','res2','res','nn4','nn1','nno4','nno1') + fprintf('%10s%8.4f%8.4f%8.4f%8.4f%8.4f%8.4f\n','mean:',mean(rmses,1)) + fprintf('%10s%8.4f%8.4f%8.4f%8.4f%8.4f%8.4f\n','std:' ,std(rmses,1)) + fprintf('%10s%8.4f%8.4f%8.4f%8.4f%8.4f%8.4f\n','time:',mean(times,1)) + + else + [Ya,times] = cat_tst_approx(Y,varargin{:}); + end + end + if ~exist('times','var'), times = etime(clock,stime); end %#ok +end + +% ====================================================================== +function Ya = cat_vol_approx_classic(Y,varargin) +% call classic approximation method + + if nargin<2; vx_vol = ones(1,3); else, vx_vol = varargin{1}; end + if nargin<3; res = 4; else, res = varargin{2}; end + + % The function approximates only values larger than zeros due to step-wise development. + % The most easy update was to shift the value and use a mask to redefine the filter volume. + Y(isnan(Y) | isinf(Y)) = 0; + if min(Y(:)) < 0 + mask = Y==0; + cf = min(Y(Y(:)~=0)) - 1; + Y = Y - cf; + Y(mask) = 0; + end + % prepare image + maxT = max([ eps; abs(Y(Y(:)~=0)) ]); + Y = single(Y / maxT); + Y = cat_vol_median3(Y,Y~=0,Y~=0,.1); + + % remove tiny things + Y(smooth3(Y~=0)<.5) = 0; + Ym = cat_vol_morph(Y~=0,'l',[100 100]); Y(Ym==0) = 0; + + % use lower resolution for processing + [Yr,resTr] = cat_vol_resize(Y, 'reduceV', vx_vol, res, 16, 'meanm'); + + % create hull on lower resolution + [Yrr,resTrr] = cat_vol_resize(Yr>0, 'reduceV', resTr.vx_volr, 16, 16, 'max'); + Ybrr = cat_vol_morph(Yrr>0, 'distclose', 20) > 0; + YBr = cat_vol_resize(single(Ybrr), 'dereduceV', resTrr)>.5; + + % align value of closest voxel + [~,Yi] = cat_vbdist(single(Yr > 0), Yr==0 | isnan(Yr), double(resTr.vx_volr)); + Yar = Yr(Yi); + + % filtering + Yars = cat_vol_smooth3X(Yar, 8 / mean(resTr.vx_volr)); + YGr = cat_vol_smooth3X(YBr, 8 / mean(resTr.vx_volr)); + Yar = Yars .* (1-YGr) + Yar .* YGr; clear Yars; + Yar = cat_vol_laplace3R(Yar, Yr==0 & YBr, 0.02 / prod(resTr.vx_volr) ); + Yar = cat_vol_laplace3R(Yar, Yr>-inf, 0.2 ); + + % back to original resolution + Ya = cat_vol_resize(Yar,'dereduceV',resTr,'cubic'); + + Ya = Ya * maxT; + if exist('cf','var') + Ya = Ya + cf; + end +end + +% ====================================================================== +function Ya = rec_approx(Y,s,rec,dep) +%simple_approx. Simple recursive approximation of missing values. +% In a given image all ""abnormal"" values, i.e. nans, infs and zeros, are +% replace by ""normal"" values. Zeros are defined as abnormal to a allow +% simple use of masks. +% For each abnormal value the closest normal value is used. The result is +% strongly filtered (controlled by the s parameter with default = 30). For +% performance the opperation is carried out interatively on half resolutions +% controled by the rec parameter (default = 3). +% +% Ya = simple_approx(Y[,s,rec,dep]) +% Y .. input image those zeros will be approximated by closes values +% Ya .. output image with appoximated values +% s .. smoothing filter size (default = 30) +% rec .. number of recursive calls with half resolution (default = 3) +% i.e an image with 256 voxel will be reduced to 128, 64, and +% finally 32 voxels (minimum matrix size is 8 voxels) (private) +% dep .. number of calls (private) + + if ~exist('s', 'var'), s = 0; else, s = double(s); end + if ~exist('rec','var'), rec = 4; else, rec = round(rec); end + if ~exist('dep','var'), dep = 0; end + + + % initial setup + % intensity normalization of the input and set special values + if dep == 0 % better to set it only once + Yc = single(Y ./ cat_stat_nanmedian( abs(Y(Y(:)~=0)) ) * 2); + Yc(isnan(Yc) | isinf(Yc)) = 0; + + % remove tiny things + Y(smooth3(Y~=0)<.5) = 0; + Ym = cat_vol_morph(Yc~=0,'l',[100 100]); Yc(Ym==0) = 0; + + Yc = cat_vol_median3(Yc,Yc~=0,Yc~=0,.1); + else + Yc = Y; + end + + + % iteratively lower/half resolution + if (rec > 0 || all(size(Yc)>128) ) && all(size(Yc)>16) + % use lower resolution for faster processing + [Yr,res] = cat_vol_resize( Yc, 'reduceV', 1, 2, 8, 'meanm'); + + % solve approximation on half resolution + Ya = rec_approx(Yr, s / mean(res.vx_red), rec - 1, dep + 1); + + % back to original resolution + Ya = cat_vol_resize( Ya , 'dereduceV', res,'cubic'); + + % integrate high resolution information if required + if dep > 0 + Ya(Yc~=0) = Yc(Yc~=0); + Ya = cat_vol_laplace3R(Ya, Yc==0, .4 / rec); + end + else + % approximation routine on the lowest resolution + level + + % estimate and align closest object point + [~,I] = cat_vbdist(single(Yc~=0)); Ya = Yc(I); + Ya = cat_vol_smooth3X(Ya,2); + Ya(Yc~=0) = Yc(Yc~=0); + + % main filter + Ya = cat_vol_laplace3R(Ya, Yc==0, .0001); % keep original + end + + % final smoothing on full resolution + if dep == 0 + Ya = cat_vol_smooth3X(Ya, s.^(1/3) ); + end + + % intensity scaling + Ya = Ya / cat_stat_nanmedian(abs(Ya(Y(:)~=0))) * cat_stat_nanmedian(abs(Y(Y(:)~=0))); +end + +% ====================================================================== +function [rmses,times] = cat_tst_approx(testcase, varargin) +%cat_tst_approx. Unit test function. +% cat_tst_approx(testcase, masking, bias) + + if exist('rng','file') == 2, rng('default'); rng(0); else, rand('state',0); randn('state',0); end %#ok + + if numel(varargin)<1, masking = 1; else, masking = varargin{1}; end + if numel(varargin)<2, bias = 4; else, bias = varargin{2}; end + + %fprintf('Run test %d (masking=%d, bias=%d)', testcase, masking, bias); + + if ~exist('testcase','var'), testcase = 1; end + switch testcase + case 1 + % high frequency pattern of positive values with smaller missing parts + A = randn(100,100,100); + spm_smooth(A,A,8); + A = A / std(A(:)*5) + .5; + case 2 + % mid frequency pattern of pos./neg. values with larger missing parts + A = randn(100,100,100); + spm_smooth(A,A,16); + A = A / std(A(:)*5) * 20; + case 3 + % low frequency pattern of pos./neg. values with larger missing parts + A = randn(100,100,100); + spm_smooth(A,A,32); + A = A / std(A(:)*5) * 100; + otherwise + error( sprintf('%s:unknownTestcase',mfilename), 'Unkown testcase %d', testcase); + end + A(50,50,50) = nan; + A(51,51,50) = inf; + A(50,51,50) = -inf; + + % structure for bias and masking + if bias~=0 || masking + S = ones(size(A)); + spm_smooth(S,S,60); + S = S / mean( abs(S(:)) ); % * 2 + 0.01 * A / mean( abs(A(:)) ) ; + else + S = ones(size(A)); + end + + % create brain mask + if masking > 0 + SS = S > masking; + else + SS = ones(size(A)); + end + + % create (biased) (masked) image + if bias>0 + A = A .* S.^(abs(bias)); + else + A = A ./ S.^(abs(bias)); + end + % add noise and mask + B = (A + 0.3 * cat_stat_nanmedian(A(A(:)>0)) .* randn(size(A))) .* ... + SS .* (cat_vol_smooth3X(rand(size(A)),4)>.5); + + + rmse = @(x) cat_stat_nanmean(x(~isinf(x(:))).^2)^.5; + + % Processing + tic, C11 = cat_vol_approx(B,'rec-test',2); C11time = toc; C11rms = rmse(A - C11); + tic, C12 = cat_vol_approx(B,'rec-test',0); C12time = toc; C12rms = rmse(A - C12); + + tic, C21 = cat_vol_approx(B,'nn-test'); C21time = toc; C21rms = rmse(A - C21); + tic, C22 = cat_vol_approx(B,'nn-test',1,1); C22time = toc; C22rms = rmse(A - C22); + + tic, C31 = cat_vol_approx(B,'oldnn-test'); C31time = toc; C31rms = rmse(A - C31); + tic, C32 = cat_vol_approx(B,'oldnn-test',1,1); C32time = toc; C32rms = rmse(A - C32); + + rmses = [C11rms ,C12rms , C21rms ,C22rms , C31rms ,C32rms ]; + times = [C11time,C12time, C21time,C22time, C31time,C32time]; + + % Display + fh = figure(393); di = 3; dj = 3; + fh.Position(3) = 600; + fh.Position(4) = 600; + + % original objects + Alim = 2 * [min(0,-median(abs(B(B(:)<0)))) max(0,median(abs(B(B(:)>0))))]; + subplot(di,dj,1); imagesc(A(:,:,round(size(A,3)/2))); + axis off; caxis(Alim); title('full') %#ok<*CAXIS> + subplot(di,dj,2); imagesc(B(:,:,round(size(A,3)/2))); + axis off; caxis(Alim); title('masked') + + % + fontweighting = {'normal','bold'}; + Cmin1 = ([C11rms,C21rms,C31rms] == min( [C11rms,C21rms,C31rms] ) ) + 1; + Cmin2 = ([C12rms,C22rms,C32rms] == min( [C12rms,C22rms,C32rms] ) ) + 1; + + % print data + subplot(di,dj,3+1); imagesc(C11(:,:,round(size(A,3)/2))); axis off; caxis(Alim); + title(sprintf('{\\color[rgb]{0 0.5 0}rec s2} (RMSE=%0.3f, %0.2fs)',C11rms,C11time),'fontweight',fontweighting{Cmin1(1)}) + subplot(di,dj,5+2); imagesc(C12(:,:,round(size(A,3)/2))); axis off; caxis(Alim); + title(sprintf('{\\color[rgb]{0 0.5 0}rec} (RMSE=%0.3f, %0.2fs)',C12rms,C12time),'fontweight',fontweighting{Cmin2(1)}) + + subplot(di,dj,4+1); imagesc(C21(:,:,round(size(A,3)/2))); axis off; caxis(Alim); + title(sprintf('{\\color[rgb]{0 0 0.7}nn(..,1,4)} (RMSE=%0.3f, %0.2fs)',C21rms,C21time),'fontweight',fontweighting{Cmin1(2)}) + subplot(di,dj,6+2); imagesc(C22(:,:,round(size(A,3)/2))); axis off; caxis(Alim); + title(sprintf('{\\color[rgb]{0 0 0.7}nn(..,1,1)} (RMSE=%0.3f, %0.2fs)',C22rms,C22time),'fontweight',fontweighting{Cmin2(2)}) + + subplot(di,dj,5+1); imagesc(C31(:,:,round(size(A,3)/2))); axis off; caxis(Alim); + title(sprintf('{\\color[rgb]{0.7 0 0}old nn(..,1,4)} (RMSE=%0.3f, %0.2fs)',C31rms,C31time),'fontweight',fontweighting{Cmin1(3)}) + subplot(di,dj,7+2); imagesc(C32(:,:,round(size(A,3)/2))); axis off; caxis(Alim); + title(sprintf('{\\color[rgb]{0.7 0 0}old nn(..,1,1)} (RMSE=%0.3f, %0.2fs)',C32rms,C32time),'fontweight',fontweighting{Cmin2(3)}) + + %fprintf(' done.\n') +end + +% ====================================================================== +function TA = cat_vol_approx2479(T,method,vx_vol,res,opt) +% Approximation of missing values +% ______________________________________________________________________ +% Approximation of missing values (nan's). First, a nearest neigbhor +% approximation is used. After that all values within the convex hull +% were corrected with a laplace filter. Depending on the 'method' +% variable the outside hull area is further improved for +% method=='nn'|'linear', but not for 'nh'. +% Use a resolution 'res' similar to the voxel size for finer results +% (i.e. 2 mm) or smaller 'res' for smoother images (default 4 mm). +% +% TA = cat_vol_approx(T,method,vx_vol,res[,opt]) +% +% T input image +% TA output image (single) +% method ['nh' | 'nn' | 'linear' | 'spm'] +% nh: fast default method +% nn: fast improved method (additional update of the outside +% hull area) +% linear slower improved method +% vx_vol voxel resolution of T (default: 1 mm) +% res voxel resolution for approximation (default: 4 mm) +% opt further options for development and test +% .lfI laplace filter stop criteria for the input image +% .lfI laplace filter stop criteria for the output image +% .hull use hull approximation (default: 1) +% +% Examples: +% There is a cell mode test part in the file...% +% +% TODO: +% - RD202005: This function needs a full update with full description +% and a full test design. +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + if nargin==0, help cat_vol_approx; return; end + if ~exist('res','var'); res=4; end + if ~exist('vx_vol','var'); vx_vol=ones(1,3); end + if ~exist('method','var'); method='nn'; end + + if ~exist('opt','var'), opt=struct(); end + % The function approximates only values larger than zeros due to step-wise development. + % The most easy update was to shift the value and use a mask to redefine the filter volume. + if min(T(:))<0 + mask = T==0; + cf = min(T(T(:)~=0)) - 1; + T = T - cf; + T(mask) = 0; + end + + def.lfI = 0.40; + def.lfO = 0.40; + def.hull = 1; + opt = cat_io_checkinopt(opt,def); + opt.lfO = min(10,max(0.0001,opt.lfO)); + + T(isnan(T) | isinf(T))=0; + maxT = max([ eps; T(T(:)~=0 & T(:)0,'reduceV',resTr.vx_volr,16,16,'max'); + BMrr = cat_vol_morph(Brr>0,'distclose',20)>0; + BMr = cat_vol_resize(BMrr,'dereduceV',resTrr); + + % inside hull approximation ... + [~,MIr] = cat_vbdist(single(Tr>0),Tr==0 | isnan(Tr),double(resTr.vx_volr)); + TAr=Tr(MIr); TAr(Tr>0) = Tr(Tr>0); + if opt.lfO >= 0.5 + meanTAr = cat_stat_nanmedian(TAr(Tr(:)>0)); + TAr = TAr / meanTAr; + Ygr = cat_vol_grad(TAr); + opt.lfO = min( 0.49 , max( 0.0001 , min( mean(resTr.vx_volr)/10 , median(Ygr(Tr(:)>0)) /opt.lfO ))); + TAr = cat_vol_laplace3R(TAr,true(size(TAr)),double(opt.lfO)) * meanTAr; + else + TASr=cat_vol_smooth3X(TAr,2); TAr(~BMr)=TASr(~BMr); clear TASr; + opt.lfO = min(0.49,max(0.0001,opt.lfO)); + TAr = cat_vol_laplace3R(TAr,BMr & ~Tr,opt.lfO); TAr = cat_vol_median3(TAr); %,Tr>0,Tr>0,0.05); + %TAr = cat_vol_laplace3R(TAr,Tr>0,opt.lfI); + TAr = cat_vol_laplace3R(TAr,BMr & ~Tr,opt.lfO); + end + else + TAr = Tr; + BMr = Tr>0; + end + + %ds('l2','',vx_vol,Tr,BMr,Tr/mean(Tr(Tr>0)),TAr/mean(Tr(Tr>0)),80) + switch method + case 'nh' + case 'nn' + TAr = TAr .* (BMr | Tr); + [~,MIr] = cat_vbdist(single(TAr>0),TAr==0,double(resTr.vx_volr)); + TAr=TAr(MIr); TASr=cat_vol_smooth3X(TAr,4); TAr(~BMr)=TASr(~BMr); clear TASr; + TAr = cat_vol_laplace3R(TAr,~BMr,double(opt.lfO)); TAr = cat_vol_median3(TAr,~BMr); + TAr = cat_vol_laplace3R(TAr,~Tr,double(opt.lfO)); + case 'linear' + TNr = TAr; + Tr = TAr .* BMr; + % outside hull linear approximation ... + vx_voln = resTr.vx_vol./mean(resTr.vx_vol); + [MDFr,EIFr] = cat_vbdist(single(cat_vol_morph(BMr>0,'disterode',max(3,8/res))),true(size(Tr)),vx_voln); + [MDNr,EINr] = cat_vbdist(single(cat_vol_morph(BMr>0,'disterode',max(1,6/res))),true(size(Tr)),vx_voln); + TAr = Tr; TAr(~Tr) = Tr(EINr(~Tr)) + ( (Tr(EINr(~Tr))-Tr(EIFr(~Tr))) ./ max(eps,( (MDFr(~Tr)-MDNr(~Tr))./MDFr(~Tr)) )); TAr(1)=TAr(2); + % correction and smoothing + TAr = min(max(TAr,TNr/2),TNr*2); % /2 + TAr = cat_vol_median3(TAr,~BMr); TAr=TAr(MIr); TASr=cat_vol_smooth3X(TAr,1); + TAr(~BMr)=TASr(~BMr); clear TASr; + TAr = cat_vol_laplace3R(TAr,~BMr,opt.lfO); TAr = cat_vol_median3(TAr,~BMr); + TAr = cat_vol_laplace3R(TAr,~BMr,opt.lfO); + end + + TA = cat_vol_resize(TAr,'dereduceV',resTr); + TA = TA*maxT; + + if exist('cf','var') + TA = TA + cf; + end +end +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_vol_img2mip.m",".m","9691","381","function cat_vol_img2mip(OV) +% Visualise up to 3 images as RGB colored MIP (glass brain) +% ______________________________________________________________________ +% +% OV - either char array of 1..3 nifti filenames or structure with +% the following fields: +% name - char array of 1..3 nifti filenames +% cmap - colormap for single MIP wth just one result (default +% jet(64)) +% func - function to apply to image before scaling to cmap +% (and therefore before min/max thresholding. E.g. a func of +% 'i1(i1==0)=NaN' would convert zeros to NaNs +% (default 'i1(i1==0)=NaN') +% range - 2x1 vector of values for image to distribute colormap across +% the first row of the colormap applies to the first +% value in 'range', and the last value to the second +% value in 'range' (default [-Inf Inf]) +% gamma_scl - gamma value to provide non-linear intensity +% scaling (default 0.7) +% save_image - save mip as png image (default '') +% RGB_order - array of RGB order (default [1 2 3]) +% bkg_col - color of background ([0 0 0] as default) +% cbar - if empty skip showing colorbar +% fig_mip - figure number (default 12) +% +% style - MIP style: +% 0 - use old glassbrain +% 1 - use cat_vol_glassbrain +% options 1 is only available for a single filename +% +% If < 3 arguments are given, you can save the png-file by using the +% context menu (right mouse click in the image) +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +if nargin < 1 + OV = spm_select([1 3],'image','Select images'); +end + +def = struct('name',OV,'func','i1(i1==0)=NaN;','cmap',jet(64),'range',... + [-Inf Inf],'gamma_scl',0.7,'save_image','','RGB_order',1:3,'Pos',... + [10 10],'bkg_col',[0 0 0],'fig_mip',12,'cbar',2,'roi',[]); + +style = 1; + +if ischar(OV) + OV = def; +else + OV = cat_io_checkinopt(OV,def); +end + +if ischar(OV.name) + V = spm_vol(OV.name); + dim = V(1).dim; + fname = V(1).fname; +elseif isa(OV.name,'nifti') + V = OV.name; + dim = V(1).dat.dim; + fname = V(1).dat.fname; +else + error('You have to either define a nifti structure or a filename as input.'); +end + +n = numel(V); +if ~isempty(OV.roi) + if ~isa(OV.name,'nifti') + error('The ROI option cannot only be used in conjunction with nifti structure as OV.'); + end + if n > 1 + error('The ROI option cannot be used for multiple images.'); + end + if any(size(OV.roi) ~= dim) + error('Dimension of ROI and image data differs.'); + end +end + +% new glassbrain does not yet support RGB MIP +if n > 1 + style = 0; +end + +if n > 3 + error('At maximum 3 images are allowed.'); +end + +% we use different affine corrections to better fit MN2009cAsym into the +% existing MIPs +if style + Affine = spm_matrix([0.5 0 -1.5 0 0 0 1 1 0.98 0 0 0]); +else + Affine = spm_matrix([0.5 2.5 3.5 0 0 0 0.95 0.95 0.95 0.1 0.1 0.1]); +end +for i=1:n + % we have to correct origin for laterality images + if (V(i).mat(1,4) == -1.5) && (all(dim == [56 137 113])) + V(i).mat(1,4) = 85.5; + end + V(i).mat = Affine * V(i).mat; +end + +M = V(1).mat; + +col = {'R','G','B'}; +for i=1:n + if n > 1 + fprintf('%s color: %s\n',col{OV.RGB_order(i)},V(i).fname); + end + XYZ{i} = []; + Y{i} = []; + if ~isempty(OV.roi) + ROI{i} = logical([]); + end +end + +Origin = V(1).mat\[0 0 0 1]'; +vox = sqrt(sum(V(1).mat(1:3,1:3).^2)); + +mnI = 1e15; mxI = -1e15; +cat_progress_bar('Init',dim(3),'Mip',' '); +for j = 1:dim(3) + B = spm_matrix([0 0 -j 0 0 0 1 1 1]); + M1 = inv(B); + + for i=1:n + % read slice and flip for MIP + if isa(V(i),'nifti') + i1 = V(i).dat(:,:,j); + else + i1 = spm_slice_vol(V(i),M1,V(i).dim(1:2),1); + end + i1 = flipud(i1); + + % apply defined function + eval(OV.func) + + if isfinite(OV.range(1)) + i1(i1OV.range(2)) = OV.range(2); + end + + % find indices + if ~isempty(OV.roi) + roi = flipud(OV.roi(:,:,j)); + [Qc Qr] = find((isfinite(i1) & i1 ~=0) | roi ~= 0); + else + [Qc Qr] = find(isfinite(i1) & i1 ~=0); + end + + Q = sub2ind(size(i1),Qc,Qr); + + if ~isempty(Q) + Qc = (Qc - Origin(1))*vox(1); + Qr = (Qr - Origin(2))*vox(2); + XYZ{i} = [XYZ{i}; [Qc Qr ones(size(Qc,1),1)*(j - Origin(3))*vox(3)]]; + + mnI = min(mnI, min(i1(Q))); + mxI = max(mxI, max(i1(Q))); + + Y{i} = [Y{i}; i1(Q)]; + if ~isempty(OV.roi) + ROI{i} = [ROI{i}; roi(Q)]; + end + end + end + + cat_progress_bar('Set',j); +end +cat_progress_bar('Clear'); + + +[pt,nm,xt] = fileparts(fname); + +if style + + % show new glassbrain + if ishandle(OV.fig_mip) + fig = figure(OV.fig_mip); + set(fig, 'Name',nm); + else + fig = figure(OV.fig_mip); + png_name = ['mip' num2str(n) '_' nm '.png']; + set(fig, 'MenuBar', 'none','Position',[10 10 2*182 2*200],'Name',nm,'NumberTitle','off'); + end + + if isempty(OV.cbar), OV.cbar = 0; end + S = struct('dark',all(OV.bkg_col==0),'cmap',OV.cmap,'grid',false,'colourbar',OV.cbar,... + 'order',style); + if ~isempty(OV.roi) + S.roi = ROI{1}; + end + + if all(isinf(OV.range)) || ~diff(abs(OV.range)) + S.sym_range = 1; + end + + if ~isempty(XYZ{1}) + cat_vol_glassbrain(Y{1},XYZ{1},S); + else + fprintf('No results found (i.e. below threshold)\n'); + end + + set(gca,'units','pixels'); x = get(gca,'position'); + set(gcf,'units','pixels'); y = get(gcf,'position'); + set(gcf,'position',[y(1) y(2) x(3) x(4)])% set the position of the figure to the length and width of the axes + set(gca,'units','normalized','position',[0 0 1 1]) % set the axes units to pixels + + if isempty(OV.save_image) + cmenu = uicontextmenu(fig); + m2 = uimenu(cmenu, 'Label','Save png image','Callback',@(src,event)save_png(OV.save_image)); + try, p.ContextMenu = cmenu; end + else + save_png(OV.save_image); + end + + return +else + load MIP + mip96 = double(mip96); + mip = repmat(full(rot90(mip96/max(mip96(:)))),[1 1 3]); + c0 = [0 0 0 ; 0 0 1 ; 0 1 0 ; 0 1 1 + 1 0 0 ; 1 0 1 ; 1 1 0 ; 1 1 1] -0.5; + c = (M(1:3,1:3)*c0')'; + dim = [(max(c)-min(c)) size(mip96)]; + + % compute colored spheres for colorbar + if n > 1 + s = 35; + coord = [270 310]; + [x,y,z] = sphere(4*s); + yy = y'*y; + yy = yy(1:2*s,1:2*s); + yy = yy/max(yy(:)); + zx = coord(1)-s:coord(1)+s-1; + zy = coord(2)-s:coord(2)+s-1; + + col = {'R','G','B'}; + col = col(OV.RGB_order); + end +end + +for i=1:n + % apply range + if isfinite(OV.range(1)) + Y{i}(Y{i}OV.range(2)) = OV.range(2); + end + + % for some range min combinations we have to subtract the minimum + if isfinite(OV.range(1)) && ( (mnI < 0 && OV.range(1) <= 0) || mnI > 0) + Y{i} = Y{i} - OV.range(1); +% Y{i} = Y{i} - mnI; + end + +end + +sz = size(mip); +for i=1:3 + rgb{i} = zeros(sz(1:2)); +end + +mx = 0; +for i=1:n + XYZ{i} = XYZ{i}'; + if ~isempty(Y{i}) + Y{i} = Y{i}'; + rgb{i} = rot90(spm_project(Y{i},round(XYZ{i}),dim)); + end + if OV.gamma_scl ~= 1 + rgb{i} = rgb{i}.^(1/OV.gamma_scl); + end + mx = max([mx; rgb{i}(:)]); +end + +for i=1:n + rgb{i} = rgb{i}/mx; +end + +% just draw colorbar for a single image +if n == 1 && ~isempty(OV.cbar) + rgb{1}(230:329,305:315) = repmat((100:-1:1)'/100,1,11); +end + +% use RGB color-spheres +if n > 1 && ~isempty(OV.cbar) + rgb{1}(zx,zy-20) = rgb{1}(zx,zy-20) + yy; + rgb{2}(zx,zy) = rgb{2}(zx,zy) + yy; +end +if n > 2 && ~isempty(OV.cbar) + rgb{3}(zx-14,zy-10) = rgb{3}(zx-14,zy-10) + yy; +end + +col = reshape([rgb{OV.RGB_order(1)},rgb{OV.RGB_order(2)},rgb{OV.RGB_order(3)}],size(mip)); +old_mip = mip; +mip = max(cat(3,col),mip); + +sz = size(mip(:,:,1)); + +% show mip image +if ishandle(OV.fig_mip) + fig = figure(OV.fig_mip); +else + fig = figure(OV.fig_mip); + set(fig, 'MenuBar', 'none','Name',nm,'Position',[10 10 sz([2 1])],'NumberTitle','off'); +end + +% single MIP of one result supports colored MIP +if n == 1 + % only use 1st channel + mip = mip(:,:,1); + + % add MIP grid with white color + mip(old_mip(:,:,1)>0) = 1.1; + + p = imagesc(mip); + + % force defined background and inverted MIP grid + OV.cmap(1,:) = OV.bkg_col; + OV.cmap(end+1,:) = 1 - OV.bkg_col; + + if mxI < 0 + colormap(OV.cmap(1:round(size(OV.cmap,1)/2)-1,:)); + else + colormap(OV.cmap); + end + + if ~isempty(OV.cbar) + + if mxI < 0 + t1 = text(320,230,'0'); + t2 = text(320,329,'-max'); + elseif mnI > 0 + t1 = text(320,230,'max'); + t2 = text(320,329,'0'); + else + t1 = text(320,230,'max'); + t2 = text(320,329,'-max'); + end + + set(t1,'Color',1 - OV.bkg_col); + set(t2,'Color',1 - OV.bkg_col); + end + +else + p = image(mip); +end + +axis image; axis off; + +% remove border +set(gca,'units','pixels'); x = get(gca,'position'); +set(gcf,'units','pixels'); y = get(gcf,'position'); +set(gcf,'position',[y(1) y(2) x(3) x(4)])% set the position of the figure to the length and width of the axes +set(gca,'units','normalized','position',[0 0 1 1]) % set the axes units to pixels + +if isempty(OV.save_image) + cmenu = uicontextmenu(fig); + m2 = uimenu(cmenu, 'Label','Save png image','Callback',@(src,event)save_png(OV.save_image)); + try, p.ContextMenu = cmenu; end +else + save_png(OV.save_image); +end + +function save_png(png_name) + +hh = getframe(gcf); +img = frame2im(hh); +imwrite(img,png_name,'png','BitDepth',8); + +fprintf('Image %s saved.\n',png_name); +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_io_load.m",".m","874","30","function x = cat_io_load(file) +% ______________________________________________________________________ +% Read values from txt-files and replace empty lines/entries by NaNs +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +if ~nargin + [file,sts] = spm_select(1,'^.*\.txt$'); + if ~sts, x = []; return; end +end + +if ~exist(file,'file') + error('Unable to find file ''%s''',file); +end + +try + str = fileread(file); + str = regexprep(str, '(?<=\r?\n)[ ]*(?=\r?\n)', 'NaN', 'emptymatch' ); + x = str2num(str); +catch + fprintf('Error: Only txt-files without characters are allowed.\n'); + x = []; +end +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_vol_findfiles.m",".m","36192","1132","function [filesfound,numberfound] = cat_vol_findfiles(varargin) +% cat_vol_findfiles - Linux/UNIX-like find command/function +% ______________________________________________________________________ +% +% FORMAT: [files, number] = cat_vol_findfiles(startfolder, patterns [, opts]) +% +% Input fields: +% +% startfolder 1xN char, folder where to start search +% may alternatively contain the pattern at the end +% patterns 1xP cell of string or 1xN char file pattern(s) +% opts struct, optional parameters in the form of +% .cellstr 1x1 double, if set and ~= 0 return as cellstr (default) +% .chararr 1x1 double, if set and ~= 0 return as char array +% .depth 1x1 double, sets both minimum and maximum depth +% .dirs 1x1 double, if set and ~= 0 find dirs instead of files +% .filesize 1x1 double, if set and > 0, only matching files +% .maxdepth 1x1 double, maximum depth to find files in +% .mindepth 1x1 double, minimum depth to find files in +% .maxage 1x1 double, seconds file must have changed in +% .minage 1x1 double, seconds file must not have changed in +% .oneperdir 1x1 double, if set and ~= 0 only first match (per dir) +% .relative 1xN char, prepend this instead of startfolder +% +% Output fields: +% +% files Fx1 cell array (or FxL char array, if requested) +% number 1x1 number of files found +% +% when used as a command, multiple opts can be given as multiple arguments, +% separated by spaces (' '): +% +% cat_vol_findfiles /search/folder *mypattern*.txt depth=3 oneperdir=1 relative=./ +% +% when used in functional context, a second return value, the number +% of matching files, can be obtained: +% +% [files, number] = cat_vol_findfiles('/where','*.txt'); +% +% NOTE: the minage/maxage feature only fully works when the system +% returns English-style month in calls to dir. i.e. under Linux, set the +% LANG environmental setting to 'en_US' before starting up MatLab +% +% Version: v0.9d +% Build: 14071015 +% Date: Jul-10 2014, 3:28 PM EST +% Author: Jochen Weber, SCAN Unit, Columbia University, NYC, NY, USA +% URL/Info: http://neuroelf.net/ +% +% ______________________________________________________________________ +% +% Copyright (c) 2010 - 2014, Jochen Weber +% All rights reserved. +% +% Redistribution and use in source and binary forms, with or without +% modification, are permitted provided that the following conditions are met: +% * Redistributions of source code must retain the above copyright +% notice, this list of conditions and the following disclaimer. +% * Redistributions in binary form must reproduce the above copyright +% notice, this list of conditions and the following disclaimer in the +% documentation and/or other materials provided with the distribution. +% * Neither the name of Columbia University nor the +% names of its contributors may be used to endorse or promote products +% derived from this software without specific prior written permission. +% +% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS"" AND +% ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +% WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +% DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY +% DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +% (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +% LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +% ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +% (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +% SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +% +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +%#ok<*EFIND> +%#ok<*AGROW> + +% enough arguments ? +if nargin < 1 || ... + ((~ischar(varargin{1}) || ... + isempty(varargin{1})) && ... + (~iscell(varargin{1}) || ... + isempty(varargin{1}) || ... + ~ischar(varargin{1}{1}) || ... + isempty(varargin{1}{1}))) + help cat_vol_findfiles; return + %{ + error( ... + 'neuroelf:TooFewArguments',... + 'Too few arguments. Try ''help %s''.',... + mfilename ... + ); + %} +end + +% for single argument +if nargin == 1 + + % check for full path + [p, f, x] = fileparts(varargin{1}(:)'); + + % local file + if isempty(p) || ... + strcmp(p, '.') + + % look in current directory + varargin{1} = pwd; + + % full path + else + + % use the path given + varargin{1} = p; + end + + % extend varargin + varargin{2} = [f, x]; + +% allow local path with options +elseif ischar(varargin{1}) && ... + any(varargin{1} == '*') && ... + ischar(varargin{2}) && ... + any(varargin{2} == '=') + + % pass on + filesfound = cat_vol_findfiles(pwd, varargin{:}); + + % and return + if iscell(filesfound) + filesfound = filesfound(:); + numberfound = numel(filesfound); + else + numberfound = size(filesfound, 1); + end + return; +end + +% shortcut variable +fsep = filesep; + +% sanity checks: startfolder +startfolder = varargin{1}; +if ischar(startfolder) && ... + ~isempty(startfolder) + + % does startfolder contain an asterisk? + if any(startfolder == '?' | startfolder == '*') + + % then put startfolder into a cell array to treat this case + [filesfound, numberfound] = cat_vol_findfiles({startfolder}, varargin{2:end}); + if iscell(filesfound) + filesfound = filesfound(:); + end + return; + end + +% startfolder is a list of folders +elseif iscell(startfolder) && ... + ~isempty(startfolder) + + % generate expanded list + nstartfolder = cell(0); + + % iterate over items + for nelem = 1:numel(startfolder) + + % must be non-empty char + if ~ischar(startfolder{nelem}) || ... + isempty(startfolder{nelem}) + error( ... + 'neuroelf:BadArgument',... + 'Bad startfolder argument.' ... + ); + end + + % expand pattern? + if ~any(startfolder{nelem} == '?' | startfolder{nelem} == '*') + + % put into final list + nstartfolder{end+1} = startfolder{nelem}; + + % or look up matching folders + else + + % split along possible path separators + [pparts, cparts] = splittocell(startfolder{nelem}, '/\', 1, 1); + if any('/\:' == startfolder{nelem}(1)) + pparts = [{''}, pparts]; + cparts = cparts + 1; + end + + % look for first pattern + for cpart = 1:cparts + if any(pparts{cpart} == '?' | pparts{cpart} == '*') + break; + end + end + + % if the pattern occurs in first part, look in current dir + if cpart==1 + [pfolders, npfolders] = cat_vol_findfiles('.', ... + pparts{1}, ... + struct('dirs', 1, 'depth', 1)); + + % otherwise glue first parts together and look up matches + else + spart = gluetostring({pparts{1:(cpart-1)}}, fsep); + if exist(spart, 'dir') > 0 + [pfolders, npfolders] = cat_vol_findfiles(spart, ... + pparts{cpart}, ... + struct('dirs', 1, 'depth', 1)); + else + pfolders = cell(0, 1); + npfolders = 0; + end + end + + % the pattern was not in last part + if cpart < cparts + + % put remaining parts back on + for ppart = 1:npfolders + pfolders{ppart} = [pfolders{ppart} fsep ... + gluetostring({pparts{(cpart+1):end}},fsep)]; + end + end + + % put results at end of list + nstartfolder = [nstartfolder, pfolders]; + end + end + + % we start with no files found + filesfound = cell(0); + + % for each folder in list + for nelem = 1:numel(nstartfolder) + + % if there (iteratively) remains a pattern char, redo this + if any(nstartfolder{nelem} == '?' | nstartfolder{nelem} == '*') + filesfound = [filesfound(1:end); ... + cat_vol_findfiles({nstartfolder{nelem}}, varargin{2:end})]; + + % otherwise get files in this folder and put at end of array + elseif exist(nstartfolder{nelem}, 'dir') == 7 + filesfound = [filesfound(1:end); ... + cat_vol_findfiles(nstartfolder{nelem}, varargin{2:end})]; + end + end + + % report the total number found + if iscell(filesfound) + filesfound = filesfound(:); + numberfound = numel(filesfound); + else + numberfound = size(filesfound, 1); + end + return; + +% illegal first argument +else + error( ... + 'neuroelf:BadArgument',... + 'Bad startfolder argument.'... + ); +end + +% we're now going for the single folder case and startfolder is OK + +% append missing fsep if needed +if startfolder(end) ~= fsep + startfolder = [startfolder fsep]; +end + +% startfolder exists? +if exist(startfolder,'dir') ~= 7 + error( ... + 'neuroelf:FolderNotFound',... + 'Startfolder (%s) not found or no folder.',... + strrep(startfolder,'\','\\') ... + ); +end + +% - sanity checks patterns +patterns = varargin{2}; + +% default is cell, otherwise +if ~iscell(patterns) + + % if is character, put into cell + if ischar(patterns) + patterns = { patterns }; + + % otherwise bail out + else + error( ... + 'neuroelf:BadArgument', ... + 'Patterns must either be a single string or a cell array!' ... + ); + end +end + +% check each pattern +for count = 1:numel(patterns) + + % only accept chars + if ~ischar(patterns{count}) || ... + isempty(patterns{count}) + patterns{count} = '*'; + end +end +patterns = unique(patterns(:)); + +% option argument parsing, default options +if nargin < 3 + opt.dirs = 0; + opt.filesize = 0; + opt.maxdepth = 0; + opt.mindepth = 0; + opt.maxage = -1; + opt.minage = -1; + opt.oneperdir = 0; + opt.relative = 0; + opt.return = 'cellarr'; + opt.rfolder = startfolder; + +% parse options +else + opt = varargin{3}; + + % non-struct options + if ~isstruct(opt) + + % yet start with default struct + clear opt; + opt.dirs = 0; + opt.filesize = 0; + opt.maxdepth = 0; + opt.mindepth = 0; + opt.maxage = -1; + opt.minage = -1; + opt.oneperdir = 0; + opt.relative = 0; + opt.return = 'cellarr'; + opt.rfolder = startfolder; + + % parse all arguments + for acount=3:nargin + + % char option + if ischar(varargin{acount}) + + % special case: -a#A#d#Dors# + % (minage, maxage, depth, dirs, oneperdir, relative=, size) + if ~isempty(varargin{acount}) && ... + varargin{acount}(1) == '-' + optarg = varargin{acount}(2:end); + while ~isempty(optarg) + switch (optarg(1)) + case {'a'} + if numel(optarg) > 1 && ... + optarg(2) >= '0' && ... + optarg(2) <= '9' + optpos = findfirst(optarg(2:end) < '0' | optarg(2:end) > '9'); + if isempty(optpos) + oval = optarg(2:end); + optarg = ''; + else + oval = optarg(2:optpos); + optarg(1:optpos) = []; + end + opt.minage = str2double(oval); + else + warning( ... + 'neuroelf:BadOption', ... + 'Option -a (minage) requires numeric input.' ... + ); + optarg(1) = []; + end + case {'A'} + if numel(optarg) > 1 && ... + optarg(2) >= '0' && ... + optarg(2) <= '9' + optpos = findfirst(optarg(2:end) < '0' | optarg(2:end) > '9'); + if isempty(optpos) + oval = optarg(2:end); + optarg = ''; + else + oval = optarg(2:optpos); + optarg(1:optpos) = []; + end + opt.maxage = str2double(oval); + else + warning( ... + 'neuroelf:BadOption', ... + 'Option -A (maxage) requires numeric input.' ... + ); + optarg(1) = []; + end + case {'d'} + if numel(optarg) > 1 && ... + optarg(2) >= '0' && ... + optarg(2) <= '9' + optpos = findfirst(optarg(2:end) < '0' | optarg(2:end) > '9'); + if isempty(optpos) + oval = optarg(2:end); + optarg = ''; + else + oval = optarg(2:optpos); + optarg(1:optpos) = []; + end + opt.maxdepth = str2double(oval); + opt.mindepth = opt.maxdepth; + else + warning( ... + 'neuroelf:BadOption', ... + 'Option -d (depth) requires numeric input.' ... + ); + optarg(1) = []; + end + case {'D'} + opt.dirs = 1; + optarg(1) = []; + case {'o'} + opt.oneperdir = 1; + optarg(1) = []; + case {'r'} + opt.relative = 1; + opt.rfolder = ''; + optarg(1) = []; + case {'s'} + if numel(optarg) > 1 && ... + optarg(2) >= '0' && ... + optarg(2) <= '9' + optpos = findfirst(optarg(2:end) < '0' | optarg(2:end) > '9'); + if isempty(optpos) + oval = optarg(2:end); + optarg = ''; + else + oval = optarg(2:optpos); + optarg(1:optpos) = []; + end + opt.filesize = str2double(oval); + else + warning( ... + 'neuroelf:BadOption', ... + 'Option -s (filesize) requires numeric input.' ... + ); + optarg(1) = []; + end + otherwise + warning( ... + 'neuroelf:BadOption', ... + 'Unknown cat_vol_findfiles option: %s.', ... + optarg(1) ... + ); + optarg(1) =[]; + end + end + continue; + end + + % get argument name + argnv = splittocell(varargin{acount}, '=', 1); + oname = argnv{1}; + + % and possible option value + if numel(argnv) > 1 + oval = argnv{2}; + else + oval = ''; + end + + % only accept known arguments + switch lower(oname) + + % option: cellstr, set return type + case {'cellstr'} + oval = str2double(oval); + if oval ~= 0 + opt.return = 'cellstr'; + end + + % option: chararr, set return type + case {'chararr'} + oval = str2double(oval); + if oval ~= 0 + opt.return = 'chararr'; + end + + % option: depth (min and max) + case {'depth'} + if str2double(oval) >= 0 + opt.maxdepth = str2double(oval); + opt.mindepth = str2double(oval); + else + opt.maxdepth = 0; + opt.mindepth = 0; + end + + % option: dirs, set lookup type + case {'dirs'} + oval = str2double(oval); + if oval == 0 + opt.dirs = 0; + else + opt.dirs = 1; + end + + % option: filesize + case {'filesize'} + if str2double(oval) >= 0 + opt.filesize = fix(str2double(oval)); + else + opt.filesize = 0; + end + + % option: maxdepth + case {'maxdepth'} + if str2double(oval) >= 0 + opt.maxdepth = fix(str2double(oval)); + else + opt.maxdepth = 0; + end + + % option: mindepth + case {'mindepth'} + if str2double(oval) >= 0 + opt.mindepth = fix(str2double(oval)); + else + opt.mindepth = 0; + end + + % option: maxage + case {'maxage'} + if str2double(oval) >= 0 + opt.maxage = fix(str2double(oval)); + else + opt.maxage = -1; + end + + % option: minage + case {'minage'} + if str2double(oval) >= 0 + opt.minage = fix(str2double(oval)); + else + opt.minage = -1; + end + + % option: oneperdir + case {'oneperdir'} + oval = str2double(oval); + if oval == 0 + opt.oneperdir = 0; + else + opt.oneperdir = 1; + end + + % option: relative + case 'relative' + noval = str2double(oval); + if ~isnan(noval) + opt.relative = noval; + if noval < 1 + opt.rfolder = startfolder; + else + opt.rfolder = ['.' fsep]; + end + else + opt.relative = 1; + opt.rfolder = oval; + end; + end + end + end + + % struct option argument + else + + % make sure options are present + if ~isfield(opt, 'dirs') + opt.dirs = 0; + end + if ~isfield(opt, 'filesize') + opt.filesize = 0; + end + if ~isfield(opt, 'maxdepth') + if isfield(opt, 'depth') + opt.maxdepth = opt.depth; + else + opt.maxdepth = 0; + end + end + if ~isfield(opt, 'mindepth') + if isfield(opt, 'depth') + opt.mindepth = opt.depth; + else + opt.mindepth = 0; + end + end + if ~isfield(opt, 'maxage') + opt.maxage = -1; + end + if ~isfield(opt, 'minage') + opt.minage = -1; + end + if ~isfield(opt, 'oneperdir') + opt.oneperdir = 0; + end + if isfield(opt, 'rfolder') + opt = rmfield(opt, 'rfolder'); + end + if ~isfield(opt, 'relative') + opt.relative = 0; + opt.rfolder = startfolder; + else + if ischar(opt.relative) + opt.rfolder=opt.relative; + opt.relative=1; + else + if double(opt.relative) >= 1 + opt.rfolder = ['.' fsep]; + opt.relative = 1; + else + opt.rfolder = startfolder; + opt.relative = 0; + end + end + end + if ~isfield(opt, 'return') + opt.return = 'cellarr'; + end + end +end + +% more interdependent checks now +if isfield(opt,'cellstr') && ... + opt.cellstr > 0 + opt.return = 'cellstr'; +end +if isfield(opt,'chararr') && ... + opt.chararr > 0 + opt.return = 'chararr'; +end +if opt.dirs ~= 0 + opt.dirs = 1; +end + +% check option types +if ~isa(opt.filesize, 'double') + opt.filesize = 0; +end +if ~isa(opt.maxdepth, 'double') + opt.maxdepth = 0; +end +if ~isa(opt.mindepth, 'double') + opt.mindepth = 0; +end +if ~isa(opt.maxage, 'double') + opt.maxage = -1; +end +if ~isa(opt.minage, 'double') + opt.minage = -1; +end +if opt.oneperdir ~= 0 + opt.oneperdir = 1; +end +if opt.relative ~= 0 + opt.relative = 1; +else opt.rfolder = startfolder; +end + +% calculate age here +opt.maxage=opt.maxage / 86400; +if opt.maxage < 0 + opt.maxage = -1; +end +opt.minage = opt.minage / 86400; +if opt.minage < 0 + opt.minage = -1; +end + +% make call for files +if opt.dirs == 0 + filesfound = findsubfiles( ... + startfolder, patterns, 1, ... + opt.filesize, opt.mindepth, opt.maxdepth, ... + opt.minage, opt.maxage, ... + opt.oneperdir, opt.rfolder); + +% make call for dirs +else + filesfound = findsubdirs( ... + startfolder, patterns, 1, ... + opt.mindepth, opt.maxdepth, ... + opt.minage, opt.maxage, ... + opt.oneperdir, opt.rfolder); +end + +% return the correct number of values +if nargout > 1 + numberfound = size(filesfound, 1); +end + +% return correct type +if strcmpi(opt.return(:)', 'chararr') + filesfound = char(filesfound); +end +end +% - end of cat_vol_findfiles(...) + + +% %%%%internal functions%%%% + + +% findsubfiles +function found = findsubfiles(path, patterns, adepth, fsize, sdepth, mdepth, mnage, mxage, operdir, relative) + +% start with zero files found +nfound = 0; +found = cell(0, 1); +mfilesep = filesep; + +% first, recursively handle all subfolders, if depth is still valid +if mdepth == 0 || ... + adepth < mdepth + + % get list of files and folders, and size of list + ilist = dir(path); + slist = numel(ilist); + + % get isdir flag into array and find indices of dirs + [ilistd(1:slist)] = [ilist(:).isdir]; + ilistd = find(ilistd > 0); + + % check items + for count = ilistd + + % don't heed . and .. + if strcmp(ilist(count).name, '.') || ... + strcmp(ilist(count).name, '..') + continue; + end; + + % find files in subdirs + filestoadd = findsubfiles([path ilist(count).name mfilesep], ... + patterns, adepth + 1, fsize, sdepth, mdepth, ... + mnage, mxage, operdir, [relative ilist(count).name mfilesep]); + sfound = numel(filestoadd); + + % if files found + if sfound > 0 + nfoundfrm = nfound + 1; + nfoundnew = nfound + sfound; + found(nfoundfrm:nfoundnew, 1) = filestoadd(:); + nfound = nfoundnew; + end + end +end + +% then, if depth is valid, add files to the output +if sdepth == 0 || ... + sdepth <= adepth + + % only get time if needed + if any([mnage, mxage] >= 0) + rnow = now; + end; + + % number of patterns + spatt = numel(patterns); + for pcount = 1:spatt + + % no ""*"" pattern + if ~any(patterns{pcount} == '*') && ... + ~any(patterns{pcount} == '?') + ilist = dir([path patterns{pcount} '*']); + if isempty(ilist) + continue; + end + ilistn = {ilist(:).name}; + if any(strcmp(ilistn, patterns{pcount})) + nfound = nfound + 1; + found{nfound, 1} = [relative patterns{pcount}]; + end + continue; + + % find matching entries with ? + elseif any(patterns{pcount} == '?') + ilist = dir([path strrep(strrep(patterns{pcount}, '?', '*'), '**', '*')]); + ilistn = {ilist(:).name}; + ilist(cellfun('isempty', regexp(ilistn, ... + [strrep(strrep(strrep(patterns{pcount}, '.', '\.'), ... + '?', '.'), '*', '.*') '$']))) = []; + + % and without ? + else + % prevent doubled wildcards that are not allowed + try, patterns{pcount} = regexprep(patterns{pcount}, '**', '*'); end + ilist = dir(fullfile(path,patterns{pcount})); + end + slist = numel(ilist); + + % get isdir flag into array and remove dirs from list + ilistd = []; + [ilistd(1:slist)] = [ilist(:).isdir]; + ilist(ilistd > 0) = []; + slist = numel(ilist); + + % if only one per dir + if operdir == 1 + count = 1; + + % reject all non-matching + while count <= slist && ... + ((mnage >= 0 && (rnow - datenum(ilist(count).date)) < mnage) || ... + (mxage >= 0 && (rnow - datenum(ilist(count).date)) > mxage) || ... + (fsize ~= 0 && ilist(count).bytes ~= fsize)) + count = count + 1; + end + + % choose first if still valid + if count <= slist + nfound = nfound + 1; + found{nfound, 1} = [relative ilist(count).name]; + end + + % otherwise check all + else + + % iterate over all + for count = 1:slist + + % reject non-matching + if ((mnage >= 0 && (rnow - datenum(ilist(count).date)) < mnage) || ... + (mxage >= 0 && (rnow - datenum(ilist(count).date)) > mxage) || ... + (fsize ~= 0 && ilist(count).bytes ~= fsize)) + continue; + end + + % accept rest + nfound = nfound + 1; + found{nfound, 1} = [relative ilist(count).name]; + end + end + end + + % linearize found + found = found(:); +end +% end of function findsubfiles +end +% findsubdirs +function found = findsubdirs(path, patterns, adepth, sdepth, mdepth, mnage, mxage, operdir, relative) + + % start with zero dirs found + nfound = 0; + found = cell(0, 1); + mfilesep = filesep; + + % first, recursively handle all subfolders, if depth is still valid + if mdepth == 0 || ... + adepth < mdepth + + % get list of files and folders, and size of list + ilist = dir(path); + slist = numel(ilist); + + % get isdir flag into array + [ilistd(1:slist)] = [ilist(:).isdir]; + + % find indices of dirs + ilistd = find(ilistd > 0); + + % check items + for count = ilistd + + % don't heed . and .. + if strcmp(ilist(count).name, '.') || ... + strcmp(ilist(count).name, '..') + continue; + end + + % iterate over subdirs + filestoadd = findsubdirs([path ilist(count).name mfilesep], ... + patterns, adepth + 1, sdepth, mdepth, ... + mnage, mxage, operdir, [relative ilist(count).name mfilesep]); + sfound = numel(filestoadd); + + % if dirs founds + if sfound > 0 + nfoundfrm = nfound + 1; + nfoundnew = nfound + sfound; + found(nfoundfrm:nfoundnew, 1) = filestoadd(:); + nfound = nfoundnew; + end + end + end + + % then, if depth is valid, add folders to the output + if sdepth == 0 || ... + sdepth <= adepth + + % only get time if needed + if any([mnage, mxage]>=0) + rnow = now; + end; + + % number of patterns + spatt = numel(patterns); + for pcount = 1:spatt + + % no ""*"" or ""?"" pattern + if ~any(patterns{pcount} == '*') && ... + ~any(patterns{pcount} == '?') + if exist([path patterns{pcount}], 'dir') == 7 + nfound = nfound + 1; + found{nfound} = [relative patterns{pcount}]; + end + continue; + + % ""?"" pattern/s + elseif any(patterns{pcount} == '?') + ilist = dir([path strrep(strrep(patterns{pcount}, '?', '*'), '**', '*')]); + ilistn = {ilist(:).name}; + ilist(cellfun('isempty', regexp(ilistn, ... + [strrep(strrep(strrep(patterns{pcount}, '.', '\.'), ... + '?', '.'), '*', '.*') '$']))) = []; + + % ""*"" pattern/s + else + ilist = dir([path patterns{pcount}]); + end + + % get matching entries + slist = numel(ilist); + + % get isdir flag into array and remove files from list + ilistd = []; + [ilistd(1:slist)] = [ilist(:).isdir]; + ilist(~ilistd) = []; + slist = numel(ilist); + + % if only one per dir + if operdir == 1 + count = 1; + + % reject all non-matching entries + while count <= slist && ... + ((mnage >= 0 && (rnow - datenum(ilist(count).date)) < mnage) || ... + (mxage >= 0 && (rnow - datenum(ilist(count).date)) > mxage)) + count = count + 1; + end + + % find next entry + while count <= slist + + % still reject . and .. + if strcmp(ilist(count).name, '.') || ... + strcmp(ilist(count).name, '..') + count = count + 1; + continue; + end + + % get next entry + nfound = nfound + 1; + found{nfound, 1} = [relative ilist(count).name]; + break; + end + + % otherwise check all + else + + % iterate over all + for count = 1:slist + + % reject non-matching + if ((mnage >= 0 && (rnow - datenum(ilist(count).date)) < mnage) || ... + (mxage >= 0 && (rnow - datenum(ilist(count).date)) > mxage)) + continue; + end + + % reject . and .. + if strcmp(ilist(count).name, '.') || ... + strcmp(ilist(count).name, '..') + continue; + end + + % accept others + nfound = nfound + 1; + found{nfound, 1} = [relative ilist(count).name]; + end + end + end + + % linearize found + found = found(:); + end + % end of function findsubdirs +end +function [linetocell,cellcount] = splittocell(varargin) +% splittocell - split a delimited string into a cell array +% +% usage is straight forward: +% +% FORMAT: [outcell,count] = splittocell(string[,delimiters,multi]) +% +% Input fields: +% string string to split +% delimiters char array containing one or more delimiters +% if left empty -> char(9) == +% multi must be '1' (numeric) to be effective, if set +% multiple delimiters will be treated as one +% +% Output fields: +% outcell cell array containing the tokens after split +% count number of tokens in result + + % no arguments -> help me! + if nargin == 0, help(mfilename); return; end + + % initialize return values and varargin{3} + linetocell=cell(0); + cellcount =0; + multidelim=0; + + + + % do we have useful input ? + if ~ischar(varargin{1}) | length(varargin{1})==0, return; end + line=varargin{1}; + if size(line,2) ~= prod(size(line)) + dispdebug('splittocell: input must be a 1xN shaped char array!',4); + return; + end + + % are any other arguments specified + if nargin < 2 | ~ischar(varargin{2}) + delimiter = char(9); + else + delimiter = reshape(varargin{2},1,prod(size(varargin{2}))); + if nargin > 2 & isnumeric(varargin{3}) & varargin{3} ~= 0, multidelim = 1; end + end + + % multi-delimitting requested ? + if multidelim == 0 + + % set initial parameters + ldelim=size(delimiter,2); + lline =size(line,2); + + % find occurences of delimiter + if ldelim==1 + cpos=[(1-ldelim),find(line==delimiter)]; + else + cpos=[(1-ldelim),strfind(line,delimiter)]; + end + lcpos =size(cpos,2); + + % any delimiter found at all ? + if lcpos==1, cellcount=1; linetocell={line}; return; end + + % large array? + if lcpos < 4096 + + % line doesn't end with delimiter ? + if cpos(lcpos) <= (lline-ldelim) + % then make it look like it was... + cpos =[cpos lline+1]; + lcpos=lcpos+1; + end + + % extract substrings + for dpos=1:(lcpos-1) + linetocell{end+1} = line(cpos(dpos)+ldelim:cpos(dpos+1)-1); + end + + else + + % get good rate + crate = min(384,floor(lcpos^0.666)); + + % iterate over parts + linetocell={}; + for cmpos = 1:crate:(lcpos-crate) + linetocell = [linetocell,splittocell(line(cpos(cmpos)+ldelim:cpos(cmpos+crate)-1),delimiter,multidelim)]; + end + linetocell = [linetocell,splittocell(line(cpos(cmpos+crate)+ldelim:cpos(end)-1),delimiter,multidelim)]; + + end + + else + + % set initial parameters + ldelim=size(delimiter,2); + lline =size(line,2); + + % find occurences of delimiter + pdelim = [0]; + for cdelim=1:ldelim + pdelim = union(pdelim,find(line==delimiter(cdelim))); + end + if pdelim(end) ~= lline, pdelim(end+1)=lline+1; end + lpdel = size(pdelim,2); + + % extract substrings + if pdelim(2)==1, linetocell{end+1} = ''; end + for ppdel=1:(lpdel-1) + if (pdelim(ppdel+1)-1) ~= pdelim(ppdel) + linetocell{end+1} = line(pdelim(ppdel)+1:pdelim(ppdel+1)-1); + end + end + + end + + cellcount=length(linetocell); +end + + + +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_main_LASsimple.m",".m","3711","88","function Yml = cat_main_LASsimple(Ysrc,Ycls,Tth,LASstr) +%cat_main_LASsimple. Local Intensity Normalization. +% ______________________________________________________________________ +% +% Highly simplified version of the Local Adapative Segmenation (LAS) +% functions cat_main_LAS that only did minimal filtering of the +% classification to avoid strong outliers such as blood vessels. +% +% It is important to avoid high intensity blood vessels in the process, +% because they will push down local WM and GM intensity. +% +% Based on this values a intensity transformation is used. Compared to +% the global correciton this has to be done for each voxel. To save time +% only a rough linear transformation is used. +% ______________________________________________________________________ +% +% Yml = cat_main_LASsimple(Ysrc,Ycls[,T3th,LASstr]) +% +% Yml .. local intensity correct image (T1w: 0-1 = BG-WM) +% Ysrc .. (bias corrected) T1 image +% Ycls .. SPM tissue class map +% Tth .. structure with tissue thresholds of CSF, GM, and WM in Ysrc +% LASstr .. parameter to control the strenght of the correction. +% (0 - slight, 1 - strong, default = 0.5) +% +% This is an exclusive subfunction of cat_main. See also cat_main_LAS +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + % in case of given threshold resort them for Ycls order (GM,WM,CSF) + if ~exist('Tth','var'), T3th = nan(1,3); else, T3th = Tth([2,3,1]); end + if ~exist('LASstr','var'), LASstr = .5; end + + %% Estimation of local tissue intensity for GM, WM, and CSF. + % In constrast to cat_main_LAS(s), the classification is only minimal + % refined to avoid outliers from blood vessels. + Ylab = cell(1,3); + minYsrc = min(Ysrc(:))+1; + Ysrc = Ysrc + minYsrc; + for ci = [1,2,3] % classes + % tissue values + Yi = Ysrc .* (Ycls{ci}>128); + + % estimate global threshold if not given + if isnan(T3th(ci)) + T3th(ci) = cat_stat_nanmedian(Ysrc(Ycls{ci}>128)); + end + + % remove outliers + Yi(Yi>T3th(ci) + 4*cat_stat_nanstd(Yi(Yi(:)>0))) = 0; + Yi(Yi>T3th(ci) + 4*cat_stat_nanstd(Yi(Yi(:)>0))) = 0; + + % first approximation for local outlier removal + Yw = cat_vol_approx(Yi); + Yi(Yi>Yw*1.2 | Yi128)) * T3th(ci); + end + Ysrc = Ysrc - minYsrc; + + %% order in case of T2; + [~,si] = sort(T3th); + Ylab = Ylab(si([2,3,1])); % reorder + + %% scaling and final correction of Yml similar to global map + Yml = zeros(size(Ysrc)); + Yml = Yml + ( (Ysrc>=Ylab{2} ) .* (3 + (Ysrc - Ylab{2}) ./ max(eps,Ylab{2} - Ylab{3})) ); % scale highest tissue (WM in T1w) + Yml = Yml + ( (Ysrc>=Ylab{1} & Ysrc=Ylab{3} & Ysrc2) = 2; +end ","MATLAB" +"Neurology","ChristianGaser/cat12","cat_io_cgw2seg.m",".m","10797","254","function varargout=cat_io_cgw2seg(c,g,w,opt) +% ______________________________________________________________________ +% convert SPM or FSL probability maps to PVE label files +% +% varargout=cat_io_cgw2seg(c,g,w,mode,d) +% +% mode .. {'SPM','FLS'} +% d .. delete old files [0|1], default = 0; +% +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Revision$ $Date$ + + if ~exist('opt','var'); opt = struct(); end + + def.verb = 1; + def.mode = 'SPM'; + def.delete = 0; + def.lazy = 1; + def.fsd = '/Volumes/vbmDB/MRData/vbm12tst/results/deffiles/fs6'; + def.fsh = '/Applications/freesurfer'; + def.fss = '/Applications/freesurfer/subjects'; + opt = cat_io_checkinopt(opt,def); + opt.fsc = ['export FREESURFER_HOME=' def.fsh '; source $FREESURFER_HOME/SetUpFreeSurfer.sh; ']; + + if opt.verb, spm('fnbanner','cat_io_cgw2seg'); end + % if there is no input, select files + if ~exist('c','var') || ~exist('g','var') || ~exist('w','var') || isempty(c) || isempty(g) || isempty(w) + if ~isfield(opt,'mode') || isempty(opt.mode) + c = spm_select(Inf ,'image','Select CSF files'); n = size(c,1); [wd,ff]=spm_fileparts(c(1,:)); + if strcmp(ff(1:2),'c1') || strcmp(ff(1:2),'c2') || strcmp(ff(1:2),'c3') + g=c; w=c; + for i=1:n + g(i,numel(wd) + 3)='1'; + w(i,numel(wd) + 3)='2'; + c(i,numel(wd) + 3)='3'; + end + else + g = spm_select([n n],'image','Select GM files',{},wd); + w = spm_select([n n],'image','Select WM files',{},wd); + end + else + switch opt.mode + case 'FS' + % select subject directories + fsdirs = cellstr(spm_select(Inf,'dir','Select subject dirs',{},opt.fss)); + % get result directory + if ~exist(opt.fsd,'dir') + ndir = cellstr(spm_select(1 ,'dir','Select output directory')); + else + ndir = opt.fsd; + end + % find segmentation files + pamgz = {}; p = {}; + for i=1:numel(fsdirs) + [tmp,name] = spm_fileparts(fsdirs{i}); + file = fullfile(fsdirs{i},'mri','aseg.auto_noCCseg.mgz'); + if exist(file,'file') + % set output filename + [h,f] = fileparts(file); + [pp,ff] = spm_fileparts(spm_fileparts(h)); + f = cat_vol_findfiles(opt.fsd,[ff '.nii']); + if ~isempty(f) + cat_io_cprintf([0 0.5 0],'Found segmentation of ""%s"". \n',name) + pamgz{end+1} = file; + p{end+1} = fullfile(fileparts(f{1}),['p0' ff '.nii']); + else + cat_io_cprintf([0.5 0.5 0],'Found segmentation of ""%s"", but not the original input nifti. \n',name) + pamgz{end+1} = file; + p{end+1} = fullfile(opt.fsd,['p0' ff '.nii']); + end + else + cat_io_cprintf([0.5 0 0],'Found no segmentation of ""%s"". \n',name) + end + end + + %% convert mgz to nifti + for i=1:numel(pamgz) + pa{i} = [pamgz{i}(1:end-3) 'nii']; c{i} = pa{i}; g{i} = pa{i}; w{i} = pa{i}; + psmgz{i} = strrep(pamgz{i},'aseg.auto_noCCseg.mgz','brainmask.auto.mgz'); + ps{i} = [psmgz{i}(1:end-3) 'nii']; + pomgz{i} = strrep(pamgz{i},'aseg.auto_noCCseg.mgz',fullfile('orig','001.mgz')); + po{i} = [pomgz{i}(1:end-3) 'nii']; + if ~opt.lazy || ~exist(pa{i},'file') || ~exist(ps{i},'file') + [tmp,name] = spm_fileparts(p{i}); fprintf('Convert mgz to nii of ""%s"". \n',name) + [SR,SR] = system(sprintf('%smri_convert -i %s -o %s -ot nii',opt.fsc,pamgz{i},pa{i})); + [SR,SR] = system(sprintf('%smri_convert -i %s -o %s -ot nii',opt.fsc,psmgz{i},ps{i})); + if strcmp(spm_fileparts(p{i}),opt.fsd) + [SR,SR] = system(sprintf('%smri_convert -i %s -o %s -ot nii',opt.fsc,pomgz{i},po{i})); + end + end + end + + + + case 'FSLs' + c2 = cellstr(spm_select(Inf ,'any','Select CSF files',{},'','T1_fast_pve_0.nii.*')); + if isempty(c2) || isempty(c2{1}), return; end + for i=1:numel(c2), if strcmp(c2{i}(end-2:end),'nii'), c2{i} = [c2{i} '.gz']; end; end + g2=c2; w2=c2; for i=1:numel(c2), g2{i}(end-7)='1'; w2{i}(end-7)='2'; end + c=c2; g=g2; w=w2; for i=1:numel(c), c{i}(end-2:end)=[]; g{i}(end-2:end)=[]; w{i}(end-2:end)=[]; end + gzfiles = [c2;g2;w2]; + for i=1:numel(gzfiles), + if exist(gzfiles{i},'file'), system(sprintf('gunzip %s',gzfiles{i})); end + end + case 'FSL', + c = cellstr(spm_select(Inf ,'image','Select CSF files',{},'','*seg_0.*')); + if isempty(c) || isempty(c{1}), return; end + g=c; w=c; for i=1:numel(c), g{i}(end-6)='1'; w{i}(end-6)='2'; end + case 'SPM', + g = cellstr(spm_select(Inf ,'image','Select GM files',{},'','^c1.*')); + if isempty(g) || isempty(g{1}), return; end + c=g; w=g; p=g; + for i=1:numel(g), + [h,f,e,nn]=spm_fileparts(g{i}); e=e(1:4); + g{i}=fullfile(h,[f,e,nn]); f(2)='3'; + c{i}=fullfile(h,[f,e,nn]); f(2)='2'; + w{i}=fullfile(h,[f,e,nn]); f(1:2)='p0'; + p{i}=fullfile(h,[f,e]); + end + otherwise + c = spm_select(Inf ,'image','Select CSF files'); n = size(c,1); wd=spm_fileparts(c(1,:)); + g = spm_select([n n],'image','Select GM files',{},wd); + w = spm_select([n n],'image','Select WM files',{},wd); + end + end + end + + % if the input is given by char, convert it to cellstr + if isa(c,'char'), c=cellstr(c); g=cellstr(g); w=cellstr(w); end + + % if the input is give by a c,g,w matrix that only one loop + if isa(c,'cell'), n=numel(c); else n=1; end + + % remove , from filenames (spm-image number) + if exist('c','var') + for ci=1:numel(c), + [pp,ff,ee] = spm_fileparts(c{ci}); c{ci}=fullfile(pp,[ff ee]); + [pp,ff,ee] = spm_fileparts(g{ci}); g{ci}=fullfile(pp,[ff ee]); + [pp,ff,ee] = spm_fileparts(w{ci}); w{ci}=fullfile(pp,[ff ee]); + end + end + + + cat_progress_bar('Init',n,'Filtering','Volumes Complete'); + for i=1:n + if opt.verb, fprintf('%s: ',c{i}); end + tic + if isa(c,'cell') + if opt.lazy && exist('p','var') && exist(p{i},'file') + fprintf(' already exist (lazy mode). \n'); + continue + else + if exist('pa','var') + ha = spm_vol(pa{i}); A=uint8(spm_read_vols(ha)); hc=ha; + hs = spm_vol(ps{i}); S=single(spm_read_vols(hs)); + %% + C = single(A== 4 | A== 5 | A==14 | A==15 | A==72 | A==24 | ... + A==43 | A==44 | A==64 | A==63 | A==31); + G = single(A== 3 | A== 8 | A== 9 | A==10 | A==11 | A==12 | A==13 | A==17 | A==18 | A==30 | A==26 | ... + A==42 | A==47 | A==48 | A==49 | A==50 | A==51 | A==52 | A==53 | A==54 | A==57 | A==58 ); + W = single(A==1 | A== 2 | A== 7 | A==16 | A==28 | ... + A==40 | A==41 | A==46 | A==55 | A==60 ); + H = single(A==77 | A==78 | A==79); + W = W+H; + C = C | (A==0 & S~=0); + + %SEG = C + 2*G + 3*W; ds('l2','a',1,S/median(S(S(:)>0)),single(A)/50,SEG/3,single(A)/50,120) + + elseif exist(c{i},'file') && exist(g{i},'file') && exist(w{i},'file') + try + hc=spm_vol(c{i}); C=spm_read_vols(hc); + hg=spm_vol(g{i}); G=spm_read_vols(hg); + hw=spm_vol(w{i}); W=spm_read_vols(hw); + catch + fprintf(1,'ERROR:cat_io_cgw2seg - incorrect file(s) [CSF=%d;GM=%d;WM=%d]\n',... + ~exist(c{i},'file'),~exist(g{i},'file'),~exist(w{i},'file')); + continue + end + %[h,f] = fileparts(hc.fname); + %if strfind({'c1','c2','c3'},f), mode='SPM'; + %elseif strfind({'_seg0','_seg1','_seg2'},f), mode='FSL'; + %else mode=''; + %end + else + fprintf(1,'ERROR:cat_io_cgw2seg - miss file(s) [CSF=%d;GM=%d;WM=%d]\n',... + ~exist(c{i},'file'),~exist(g{i},'file'),~exist(w{i},'file')); + continue + end + end + end + + SEG = C + 2*G + 3*W; + if max(C(:))>1 || max(G(:))>1 || max(W(:))>1, SEG = SEG/max(W(:)); end + + if exist('hc','var') + %% + [h,f] = fileparts(hc.fname); + if opt.delete==1 && ~(strcmp(opt.mode,'FS') && ~isempty(ndir)) + switch hc.fname(end-2:end) + case 'nii' + delete(hc.fname); delete(hg.fname); delete(hw.fname); + case 'img' + delete([hc.fname(1:end-3) 'hdr']); delete([hc.fname(1:end-3) 'img']); + delete([hg.fname(1:end-3) 'hdr']); delete([hg.fname(1:end-3) 'img']); + delete([hw.fname(1:end-3) 'hdr']); delete([hw.fname(1:end-3) 'img']); + end + end + switch opt.mode + case 'FS', hc.fname = fullfile(h,['p0' f(1:end) '.nii']); + case 'SPM', hc.fname = fullfile(h,['p0' f(3:end) '.nii']); + case 'FSL', hc.fname = fullfile(h,['p0' f(1:end-6) '.nii']); + case 'FSLs', + [h2,f2] = spm_fileparts(h); + hc.fname = fullfile(h2,['p0' f2 '.nii']); + otherwise, hc.fname = fullfile(h,['p0' f '.nii']); + end + %hc.dt(1) = 16; + hc.dt(1) = spm_type('uint8'); + hc.pinfo = [3/255;0;1]; + hc.descript = 'label map'; + if exist(hc.fname,'file'),delete(hc.fname); end + spm_write_vol(hc,SEG); + + %% + if strcmp(opt.mode,'FS') && ~isempty(ndir) && ~(opt.lazy && exist('p','var') && exist(p{i},'file')) + %% find native file + [pp,ff] = spm_fileparts(spm_fileparts(h)); + ofile = cat_vol_findfiles(ndir,[ff '.nii']); + if isempty(ofile), cat_io_cprintf([0.5 0 0], 'No original file!\n'); continue; end + + clear Vi Vo; + + Vi = spm_vol(char([ofile;{hc.fname}])); + Vo = Vi(1); Vo.fname = p{i}; Vo.pinfo = [3/255;0;1]; Vo.dt = hc.dt; Vo.descrip = 'label map'; + + % map to origal space + cat_vol_imcalc(Vi,Vo,'single(i2)',struct('interp',1)); + cat_io_cprintf([0 0.5 0],'done'); + end + + if nargout>0, varargout{1}{n} = hc.fname; end + end + cat_progress_bar('Set',i); if opt.verb, fprintf('%4.0f\n',toc); end + end + cat_progress_bar('Clear'); + if opt.verb, fprintf('%-40s: %30s\n','Completed',spm('time')); end +end +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_vol_headtrimming.m",".m","12856","316","function varargout = cat_vol_headtrimming(job) +% ______________________________________________________________________ +% Remove air around the head and convert the image data type to save disk- +% space but also to reduce memory-space and load/save times. Uses 99.99% of +% the main intensity histogram to avoid problems due to outliers. Although +% the internal scaling supports a relative high accuracy for the limited +% number of bits, special values such as NAN and INF will be lost! +% +% varargout = cat_vol_headtrimming(job) +% +% job +% .simages .. filenames as cell of cellstr +% .resdir .. result directory (char, default same as input files) +% .pefix .. filename prefix (char, default = 'trimmed_') +% .addvox .. additional voxels around the box (default = 2); +% .pth .. percentual threshold to estimate the box (0.1); +% .verb .. be verbose (default = 1) +% .ctype .. 'uint16'; +% .range .. 99.99; +% +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + +% ______________________________________________________________________ +% Todo: +% * 4D extension & test +% ______________________________________________________________________ + + + if nargin == 0 + help cat_vol_headtrimming; + return; + end + + %def.image_selector.subjectimages = {{}}; % GUI input data structure 1 + %def.image_selector.manysubjects.simages = {}; % GUI input data structure 2 + %def.image_selector.manysubjects.oimages = {{}}; % GUI input data structure 2 + def.images = {{}}; % internal data structure + %def.resdir = ''; % other result directory + def.prefix = 'trimmed_'; % add prefix to filename (SPM standard) + def.mask = 0; % final masking with source image + def.suffix = ''; % add suffix to filename + def.addvox = 2; % add some voxels around the mask + def.pth = 0.4; % default threshold for masking with bg=0 and object~1 + def.verb = 1; % some output information + def.open = 2; % open operation for masking + def.ctype = 0; % default data type (0=native) + def.intlim = 1; % data range for output + def.range1 = 90; % internal scaling for masking + def.returnOnlyFilename = 0; % + def.process_index = 1; % + def.lazy = 0; + job = cat_io_checkinopt(job,def); + + + if isfield(job.image_selector,'manysubjects') + % source image + if ischar(job.image_selector.manysubjects.simages) + varargout{1}.image_selector.manysubjects.simages = spm_file(... + job.image_selector.manysubjects.simages,'prefix',job.prefix,'suffix',job.suffix); + else + for fi=1:numel(job.image_selector.manysubjects.simages) + varargout{1}.image_selector.manysubjects.simages{fi,1} = spm_file(... + job.image_selector.manysubjects.simages{fi},'prefix',job.prefix,'suffix',job.suffix); + end + end + % other images + for fi=1:numel(job.image_selector.manysubjects.oimages) + for di=1:numel(job.image_selector.manysubjects.oimages{fi}) + if ischar(job.image_selector.manysubjects.oimages{fi}) + varargout{1}.image_selector.manysubjects.oimages{fi,1} = spm_file(... + job.image_selector.manysubjects.oimages{fi},'prefix',job.prefix,'suffix',job.suffix); + else + varargout{1}.image_selector.manysubjects.oimages{fi}{di,1} = spm_file(... + job.image_selector.manysubjects.oimages{fi}{di},'prefix',job.prefix,'suffix',job.suffix); + end + end + end + elseif isfield(job.image_selector,'subjectimages') + varargout{1}.image_selector.firstimages = {}; + varargout{1}.image_selector.otherimages = {}; % collect other images + for si=1:numel(job.image_selector.subjectimages) + % standard single image output + varargout{1}.image_selector.subjectimages{si} = spm_file(... + job.image_selector.subjectimages{si},'prefix',job.prefix,'suffix',job.suffix); + varargout{1}.image_selector.firstimages = [ + varargout{1}.image_selector.firstimages; + varargout{1}.image_selector.subjectimages{si}(1)]; + % collect other images + if numel(varargout{1}.image_selector.subjectimages{si})>1 + varargout{1}.image_selector.otherimages = [ + varargout{1}.image_selector.otherimages; + varargout{1}.image_selector.subjectimages{si}(2:end)]; + end + end + elseif isfield(job,'images') + varargout{1}.images = spm_file(... + job.images,'prefix',job.prefix,'suffix',job.suffix'); + end + if job.returnOnlyFilename, return; end + + + + % transfer data from GUI stucture to internal standard + if isfield(job,'image_selector') + if isfield(job.image_selector,'subjectimages') && ... + ~isempty(job.image_selector.subjectimages) && ... + ~isempty(job.image_selector.subjectimages{1}) + % case many images with subjectwise cells with different number of files: + % {{S1T1,S1T2,...,S1Tn} {S2T1,S2T2,...,S2Tm} ...?} + + job.images = job.image_selector.subjectimages; + + elseif isfield(job.image_selector,'manysubjects') && ... + ~isempty(job.image_selector.manysubjects) + % case many subjects with typewise sets of many subjects with equal number: + % {{S1T1,S2T1,...,SnT1} {S1T2,S2T2,...,SnT2} ...?} + % check number of images + + if numel(job.image_selector.manysubjects.simages)>1 && ... + ~isempty(job.image_selector.manysubjects.oimages) && ... + ~isempty(job.image_selector.manysubjects.oimages{1}) + nimgs = cellfun('length',[{job.image_selector.manysubjects.simages};job.image_selector.manysubjects.oimages']); + if any(nimgs~=mean(nimgs)) + warning('cat_vol_headtrimming:imgages',... + ['The number of images of each set has to be equal where the i-th entry ' ... + 'of each set describes data of the same subject.']); + end + end + + for si=1:numel(job.image_selector.manysubjects.simages) + if ischar(job.image_selector.manysubjects.simages) + job.images{si}{1} = job.image_selector.manysubjects.simages; + else + job.images{si}{1} = job.image_selector.manysubjects.simages{si}; + end + for fi=1:numel(job.image_selector.manysubjects.oimages) + if ~isempty(job.image_selector.manysubjects.oimages{fi}) + if ischar(job.image_selector.manysubjects.oimages{fi}) + job.images{si}{fi+1} = job.image_selector.manysubjects.oimages{fi}; + else + job.images{si}{fi+1} = job.image_selector.manysubjects.oimages{fi}{si}; + end + end + end + end + + end + end + if isempty(job.images) || isempty(job.images{1}), return; end + + + % choose prefix + for si=1:numel(job.images) + for di=1:numel(job.images{si}) + [pp,ff,ee] = spm_fileparts(job.images{si}{di}); + job.images1{si}{di} = fullfile(pp,[ff ee]); + job.images2{si}{di} = fullfile(pp,[job.prefix ff job.suffix ee]); % resdir + + end + end + if job.returnOnlyFilename, return; end + + + % be verbose + if isfield(job,'process_index') && job.process_index && job.verb + spm('FnBanner',mfilename); + end + spm_clf('Interactive'); + spm_progress_bar('Init',numel(job.images{1}),'Head-Trimming','Volumes Complete'); + + + %% major processing + for si = 1:numel(job.images) + if job.verb, fprintf('%58s: ',spm_str_manip(job.images{si}{1},'ra57')); end + + if ~job.lazy || any( cat_io_rerun( job.images{si}, job.images2{si} ) ) + %% estimate trimming parameter + V = spm_vol(char(job.images{si})); % there could be more than one image per subject! + Y = single(spm_read_vols(V(1))); % here we use only the first image + + % create mask for skull-stripped images + if job.mask, Ymask = Y ~= 0; end + + % categorical data have data type uint8 or int16 + % and typically < 1000 different values + categorical = 0; + if V(1).pinfo(1) == 1 && all( round(Y(:)) == Y(:) ) % V(1).dt(1) == 2 || V(1).dt(1) == 4 && + h = hist(Y(:),min(Y(:)):max(Y(:))); + n_values = numel(unique(h)); + if n_values < 1000 + categorical = 1; + end + end + + % skip most of steps that are only needed for non-categorical data + vx_vol = sqrt(sum(V(1).mat(1:3,1:3).^2)); + if categorical + fprintf('Categorical Image (Label map) ') + Yb = cat_vol_morph(Y,'o',1); % remove noise ? + %Yb = cat_vol_morph(Yb,'ldc',5) > 0; % why? + else + % intensity normalization + Yr = cat_vol_resize(Y,'reduceV',vx_vol,2,64,'meanm'); + [Yr,hth] = cat_stat_histth(smooth3(Yr),job.range1,0); + Y = (Y - hth(1)) ./ abs(diff(hth)); + + % masking + Yb = zeros(size(Y),'single'); + Yb(2:end-1,2:end-1,2:end-1) = Y(2:end-1,2:end-1,2:end-1); + Yb = smooth3(Yb)>job.pth; + Yb = cat_vol_morph(Yb,'do',job.open,vx_vol); + Yb = cat_vol_morph(Yb,'l',[10 0.1]); + end + + addvox = job.addvox .* mean(max(1,vx_vol*2)); + + [Yt,redB] = cat_vol_resize(Y,'reduceBrain',vx_vol,addvox,Yb); %#ok + + % prefer odd or even x-size such as found in original data to prevent shifting issues + % at midline + if ~mod(redB.sizeTr(1),2) ~= ~mod(redB.sizeT(1),2) + % and add x-shifted image to increase bounding box by 1 voxel + if ~mod(redB.BB(1),2) + Yb(1:end-1,:,:) = Yb(1:end-1,:,:) + Yb(2:end,:,:); + else + Yb(2:end,:,:) = Yb(2:end,:,:) + Yb(1:end-1,:,:); + end + [Yt,redB] = cat_vol_resize(Y,'reduceBrain',vx_vol,addvox,Yb); %#ok + end + + % estimate if we need negative values + if job.ctype ~= 0 + if job.intscale == 3 % force positive values between 0 and 1 + intscale = 1; + else % scaled values between 0 and |1| + if sum( Y(:)./max(abs(Y(:))) < 0.05 ) > numel(Y(:)) * 0.01 + intscale = -1; + else + intscale = 1; + end + end + % udpate for full range (use slope rather than fixed range) + if job.intscale == 0, intscale = intscale * inf; end + else % full range + if any( V(1).dt(1) == [2 512 768] ) % uint + intscale = inf; + else % int + intscale = -inf; + end + end + + clear Yt Y; + % prepare update of AC orientation + mati = spm_imatrix(V(1).mat); mati(1:3) = mati(1:3) + mati(7:9).*(redB.BB(1:2:end) - 1); + + + % trimming + Vo = V; + for di = 1:numel(V) + if numel(V)>1 && di>1 && job.verb, fprintf('\n %57s: ',spm_str_manip(job.images{si}{di},'ra55')); end + + % optimize tissue intensity range if 00 && job.range<100) || ... + (~isempty(job.ctype) && ( ... + ( isnumeric(job.ctype) && job.ctype>0) || ... + ( ischar(job.ctype) && ~strcmp(job.ctype,'native') ))) + + job2 = struct('data',job.images{si}{di},'ctype',job.ctype,'intscale',intscale,... + 'verb',job.verb*0.5,'range',job.intlim,'prefix',job.prefix,'suffix',job.suffix); + files = cat_io_volctype(job2); + Pdi = files.files; + else + if ~strcmp(job.images1{si}{di},job.images2{si}{di}) + copyfile(job.images1{si}{di},job.images2{si}{di}); + end + Pdi = job.images2{si}(di); + end + spm_progress_bar('Set',si + di/numel(V)); + + %% create ouput + Vo(di) = spm_vol(Pdi{1}); + Yo = single(spm_read_vols(Vo(di))); + + % apply mask + if job.mask, Yo = Yo .* Ymask; end + + [Yo,redB] = cat_vol_resize(Yo,'reduceBrain',vx_vol,addvox,Yb); + Vo(di).mat = spm_matrix(mati); + Vo(di).dim = redB.sizeTr; + if exist(Vo(di).fname,'file'), delete(Vo(di).fname); end % delete required in case of smaller file size! + spm_write_vol(Vo(di),Yo); + + % if there are multiple subjects with multiple images + if numel(job.images)>1 && numel(V)>1 && di>numel(V) && job.verb + fprintf(' ------------------------------------------------------------------------\n'); + end + end + + + %% be verbose + if job.verb, fprintf('saved %5.2f%%\n',100 - 100*((prod(redB.sizeTr) ./ prod(redB.sizeT)))); end + else + if job.verb, fprintf('exist\n'); end + end + spm_progress_bar('Set',si); + end + spm_progress_bar('Clear'); +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_vol_createMPM.m",".m","8589","266","function cat_vol_createMPM(Label, Deform, vox, thresholds, mask, exclude_labels) +% Create Maximum Probability Map (Label) of labels in native space and deformation +% fields +% +% FORMAT cat_vol_create_MPM(Label,Deform) +% Label - char array of filenames of labels +% Deform - char array of filenames of deformation fields (leave empty if labels +% are already normalized and no deformations are needed) +% vox - voxel size (use NaNs to use voxel size of deformation fields) +% mask - optional mask image for final masking +% exclude_labels - optionally exclude labels from atlas (e.g. +% neuromorphometrics) +% +% some of the subfunctions are modified versions from spm_deformations.m +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +refine = 1; % always use refinement with slight smoothing and median filtering + +if nargin < 1 + Label = spm_select(Inf,'image','Select native label maps'); +end + +Vlabel = spm_vol(Label); +n_subjects = numel(Vlabel); + +if nargin < 2 + Deform = spm_select([0 n_subjects],'image','Select deformation fields (or press done if no deformations are needed)',{},pwd,'^y_'); +end + +% voxel size +if nargin < 3 && ~isempty(Deform) + vox = spm_input('Voxel size',1,'r',[NaN NaN NaN],[1,3]); +end + +% thresholds for average probability to exclude non-brain areas +if nargin < 4 + thresholds = spm_input('Threshold(s)','+1','r',0.5); +end + +% optional masking +if nargin < 5 + mask = spm_select([0 1],'image','Select optional mask image',{fullfile(cat_get_defaults('extopts.pth_templates'),'brainmask_T1.nii')}); +end +Vmask = spm_vol(mask); + +% give warning if brainmask is used in cobination with several thresholds +if ~isempty(mask) && numel(thresholds) > 1 + fprintf('Please keep in mind, that use of brainmask will result in very similar results using different thresholds. If you intend to try different thresholds disable use of an additional brainmask\n'); +end + +% thresholds for average probability to exclude non-brain areas +if nargin < 6 + exclude_labels = str2num(spm_input('Exclude labels (e.g. neuromorphometrics)','+1','s')); +end + +% check whether only one value was defined +if size(vox,1) ==1 && size(vox,2) == 1 + vox = [vox vox vox]; +end + +% transpose if necessary +if size(vox,1) > size(vox,2) + vox = vox'; +end + +% find all unique values in structures +structures = round(spm_read_vols(Vlabel(end))); +datarange = sort(unique(structures(structures>0))); +for i=1:numel(exclude_labels) + datarange(datarange == exclude_labels(i)) = []; +end +n_structures = numel(datarange); + +if ~isempty(Deform) + Vdeform = spm_vol(Deform); + V = Vdeform; + [Def,mat] = get_comp(Vdeform(1).fname,vox); + sz = size(Def); + V(1).dim(1:3) = sz(1:3); + V(1).mat = mat; +else + V = Vlabel; +end + +% set data type w.r.t. maximum value +max_val = max(datarange); +if max_val < 2^8 + data_type = 'uint8'; + fprintf('Set data type to uint8\n.') +elseif max_val < 2^16 + data_type = 'uint16'; + fprintf('Set data type to uint16\n.') +else + data_type = 'float32'; + fprintf('Set data type to float32\n.') +end + +[tmp, name] = spm_str_manip(spm_str_manip(Label,'t'),'C'); + +watlas = zeros([V(1).dim(1:3) n_structures],'single'); + +for i=1:n_subjects + fprintf('.'); + if ~isempty(Deform) + Def = get_comp(Vdeform(i).fname,vox); + end + vol = spm_read_vols(Vlabel(i)); + for j=1:n_structures + if ~isempty(Deform) + dat = apply_def(Def,double(round(vol)==datarange(j)),3,Vlabel(i).mat); + else + dat = double(round(vol)==datarange(j)); + end + dat(isnan(dat) | dat < 0) = 0.0; + dat(dat > 1) = 1.0; + watlas(:,:,:,j) = watlas(:,:,:,j) + single(dat); + end +end +fprintf('\n'); + +% apply median filtering to each label and slight smoothing +if refine + for j=1:n_structures + tmp = cat_vol_median3(single(watlas(:,:,:,j))); + spm_smooth(tmp,tmp,2); + watlas(:,:,:,j) = tmp; + end +end + +watlas = watlas/n_subjects; +avg_atlas = sum(watlas,4); +[max_atlas, index_atlas_orig] = max(watlas,[],4); + +% write 4D atlas of all probability maps +PM4d_name = ['PM_' name.s strrep(name.e,',1','')]; +N4d = nifti; +N4d.dat = file_array( PM4d_name ,size(watlas),... + [spm_type('uint8') spm_platform('bigend')],0,1/255,0); +N4d.mat = V(1).mat; +N4d.mat0 = V(1).mat; +N4d.descrip = [strrep(name.e,',1','') 'n=' num2str(n_subjects)]; +create(N4d); +N4d.dat(:,:,:,:,:) = watlas; +fprintf('%s saved.\n',PM4d_name); + +for i=1:numel(thresholds) + threshold = thresholds(i); + + index_atlas = index_atlas_orig; + index_atlas(max_atlas<0.01 | isnan(max_atlas) | avg_atlas 0; + holes = (cat_vol_morph(holes,'c') - holes) > 0; + tmp = cat_vol_median3c(single(index_atlas)); + index_atlas(holes) = double(tmp(holes)); + + Vo = struct('fname',['MPM_th' sprintf('%0.2f',threshold) '_' name.s strrep(name.e,',1','')],... + 'dim',size(index_atlas),... + 'dt',[spm_type(data_type) spm_platform('bigend')],... + 'pinfo',[1 0 352]',... + 'mat',V(1).mat,... + 'n',V(1).n,... + 'descrip',['n=' num2str(n_subjects)]); + Vo = spm_create_vol(Vo); + spm_write_vol(Vo, index_atlas); + fprintf('%s saved.\n',Vo.fname); + + if ~isempty(mask) + Vom = Vo; + Vom.fname = ['MPM_th' sprintf('%0.2f',threshold) '_masked_' name.s strrep(name.e,',1','')]; + cat_vol_imcalc([Vo; Vmask],Vom,'i1.*(i2>0.5)',struct('verb',0,'type',spm_type(data_type))); + fprintf('%s saved.\n',Vom.fname); + end + +end + +%_______________________________________________________________________ +function [Def,mat,vx,bb] = get_def(field) +% Load a deformation field saved as an image +Nii = nifti(field); +Def = single(Nii.dat(:,:,:,1,:)); +d = size(Def); +if d(4)~=1 || d(5)~=3, error('Deformation field is wrong!'); end +Def = reshape(Def,[d(1:3) d(5)]); +mat = Nii.mat; + +vx = sqrt(sum(Nii.mat(1:3,1:3).^2)); +if det(Nii.mat(1:3,1:3))<0, vx(1) = -vx(1); end + +o = Nii.mat\[0 0 0 1]'; +o = o(1:3)'; +dm = size(Nii.dat); +bb = [-vx.*(o-1) ; vx.*(dm(1:3)-o)]; + +%_______________________________________________________________________ +function Def = identity(d,M) +[y1,y2] = ndgrid(single(1:d(1)),single(1:d(2))); +Def = zeros([d 3],'single'); +for y3=1:d(3) + Def(:,:,y3,1) = y1*M(1,1) + y2*M(1,2) + (y3*M(1,3) + M(1,4)); + Def(:,:,y3,2) = y1*M(2,1) + y2*M(2,2) + (y3*M(2,3) + M(2,4)); + Def(:,:,y3,3) = y1*M(3,1) + y2*M(3,2) + (y3*M(3,3) + M(3,4)); +end + +%_______________________________________________________________________ +function [Def,mat] = get_comp(field,vox) +% Return the composition of two deformation fields. + +[Def,mat,vx,bb] = get_def(field); + +% only estimate composite if job field is given +if nargin > 1 + % only move on if any vox or bb field is not NaN + if any(isfinite(vox)) + Def1 = Def; + mat1 = mat; + vox(~isfinite(vox)) = vx(~isfinite(vox)); + + [mat, dim] = spm_get_matdim('', vox, bb); + Def = identity(dim, mat); + M = inv(mat1); + tmp = zeros(size(Def),'single'); + tmp(:,:,:,1) = M(1,1)*Def(:,:,:,1)+M(1,2)*Def(:,:,:,2)+M(1,3)*Def(:,:,:,3)+M(1,4); + tmp(:,:,:,2) = M(2,1)*Def(:,:,:,1)+M(2,2)*Def(:,:,:,2)+M(2,3)*Def(:,:,:,3)+M(2,4); + tmp(:,:,:,3) = M(3,1)*Def(:,:,:,1)+M(3,2)*Def(:,:,:,2)+M(3,3)*Def(:,:,:,3)+M(3,4); + Def(:,:,:,1) = single(spm_diffeo('bsplins',Def1(:,:,:,1),tmp,[1,1,1,0,0,0])); + Def(:,:,:,2) = single(spm_diffeo('bsplins',Def1(:,:,:,2),tmp,[1,1,1,0,0,0])); + Def(:,:,:,3) = single(spm_diffeo('bsplins',Def1(:,:,:,3),tmp,[1,1,1,0,0,0])); + clear tmp + end +end + +%_______________________________________________________________________ +function out = apply_def(Def,vol,intrp,mat) +% Warp an image or series of images according to a deformation field +intrp = [intrp*[1 1 1], 0 0 0]; +M = inv(mat); + +C = spm_bsplinc(vol,intrp); +dat = []; +for j=1:size(Def,3) + d0 = {double(Def(:,:,j,1)), double(Def(:,:,j,2)), double(Def(:,:,j,3))}; + d{1} = M(1,1)*d0{1}+M(1,2)*d0{2}+M(1,3)*d0{3}+M(1,4); + d{2} = M(2,1)*d0{1}+M(2,2)*d0{2}+M(2,3)*d0{3}+M(2,4); + d{3} = M(3,1)*d0{1}+M(3,2)*d0{2}+M(3,3)*d0{3}+M(3,4); + dat = [dat spm_bsplins(C,d{:},intrp)]; +end + +sz = size(Def); +out = reshape(dat,sz(1:3)); +","MATLAB" +"Neurology","ChristianGaser/cat12","Amap.h",".h","2004","84","/* + * Christian Gaser + * $Id$ + * + */ + +#ifdef MATLAB_MEX +#include ""mex.h"" +#endif + +#define SQRT2PI 2.506628 +#define G 6 + +#define MAX_NC 6 +#define TH_COLOR 1 +#define TH_CHANGE 0.0001 +#ifndef TINY +#define TINY 1e-15 +#endif +#ifndef HUGE +#define HUGE 1e15 +#endif +#ifndef NULL +#define NULL ((void *) 0) +#endif + +#define NOPVE 0 +#define KMEANS 1 + +#define BKGCSFLABEL 0 +#define CSFLABEL 1 +#define GMCSFLABEL 2 +#define GMLABEL 3 +#define WMGMLABEL 4 +#define WMLABEL 5 + +#ifndef SQR +#define SQR(x) ((x)*(x)) +#endif + +#ifndef MAX +#define MAX(A,B) ((A) > (B) ? (A) : (B)) +#endif + +#ifndef MIN +#define MIN(A,B) ((A) < (B) ? (A) : (B)) +#endif + +#ifndef ROUND +#define ROUND( x ) ((long) ((x) + ( ((x) >= 0) ? 0.5 : (-0.5) ) )) +#endif + +#ifndef MIN3 +#define MIN3(a,b,c) (MIN(a,MIN(b,c))) +#endif + +extern double Kmeans(double *src, unsigned char *label, unsigned char *mask, + int NI, int n_clusters, double *voxelsize, int *dims, int thresh_mask, + int thresh_kmeans, int iters_nu, int pve, double bias_fwhm); +extern void Amap(double *src, unsigned char *label, unsigned char *prob, + double *mean, int nc, int niters, int sub, int *dims, int pve, + double weight_MRF, double *voxelsize, int niters_ICM, double offset, + double bias_fwhm, int verb, double *fmeans, double *fstds); +extern void Pve5(double *src, unsigned char *prob, unsigned char *label, double *mean, int *dims); +extern void Pve6(double *src, unsigned char *prob, unsigned char *label, double *mean, int *dims); +extern void MrfPrior(unsigned char *label, int nc, double *alpha, double *beta, int init, int *dims, int verb); +#ifdef SPLINESMOOTH + extern int splineSmooth( double *src, double lambda, double distance, + int subsample, double *separations, int *dims); +#endif +void smooth_subsample_double(double *vol, int dims[3], double separations[3], + double s[3], int use_mask, int samp); + +struct point { + double mean; + double var; +}; + +struct ipoint { + int n; + double s; + double ss; +}; +","Unknown" +"Neurology","ChristianGaser/cat12","cat_stat_IQR.m",".m","1119","43","function cat_stat_IQR(p) +%cat_stat_IQR to read weighted overall image quality (IQR) from xml-files +% +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +fid = fopen(p.iqr_name,'w'); + +if fid < 0 + error('No write access: check file permissions or disk space.'); +end + +cat_progress_bar('Init',length(p.data_xml),'Load xml-files','subjects completed') +for i=1:length(p.data_xml) + xml = cat_io_xml(deblank(p.data_xml{i})); + try + iqr = xml.qualityratings.IQR; + catch % also try to use old versions + try + iqr = xml.QAM.QM.rms; + catch % give up + iqr = nan; + end + end + + [pth,nam] = spm_fileparts(p.data_xml{i}); + fprintf(fid,'%s\n',iqr); + fprintf('%s\n',iqr); + cat_progress_bar('Set',i); +end +cat_progress_bar('Clear'); + + +if fclose(fid)==0 + fprintf('\nValues saved in %s.\n',p.iqr_name); +end +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_batch_long.sh",".sh","10565","399","#! /bin/bash +# Call CAT12 longitudinal pipeline from shell +# ______________________________________________________________________ +# +# Christian Gaser, Robert Dahnke +# Structural Brain Mapping Group (https://neuro-jena.github.io) +# Departments of Neurology and Psychiatry +# Jena University Hospital +# ______________________________________________________________________ +# $Id$ + +######################################################## +# global parameters +######################################################## + +matlab=matlab # you can use other matlab versions by changing the matlab parameter +cwd=$(dirname ""$0"") + +# if a relative path was given add current folder to name +if [ ""$cwd"" == ""."" ]; then + cwd=$(pwd); +fi + +cat12_dir=$cwd +spm12=$(dirname ""$cwd"") +spm12=$(dirname ""$spm12"") +spm12dir=spm12 +LOGDIR=$PWD +export_dartel=0 +output_surface=1 +long_model=3 +printlong=2 +time=`date ""+%Y%b%d_%H%M""` +defaults_tmp=/tmp/defaults$$.m +fg=0 +bids=0 +bids_folder= + +######################################################## +# run main +######################################################## + +main () +{ + parse_args ${1+""$@""} + check_matlab + check_files + modifiy_defaults + run_cat12 + + exit 0 +} + + +######################################################## +# check arguments and files +######################################################## + +parse_args () +{ + local optname optarg + count=0 + + if [ $# -lt 1 ]; then + help + exit 1 + fi + + while [ $# -gt 0 ]; do + optname=""`echo $1 | sed 's,=.*,,'`"" + optarg=""`echo $2 | sed 's,^[^=]*=,,'`"" + paras=""$paras $optname $optarg"" + case ""$1"" in + --defaults* | -d*) + exit_if_empty ""$optname"" ""$optarg"" + defaults=$optarg + shift + ;; + --model* | -model*) + exit_if_empty ""$optname"" ""$optarg"" + long_model=$optarg + shift + ;; + --print* | longlong*) + exit_if_empty ""$optname"" ""$optarg"" + printlong=$optarg + shift + ;; + --matlab* | -m*) + exit_if_empty ""$optname"" ""$optarg"" + matlab=$optarg + shift + ;; + --export-dartel* | -e*) + export_dartel=1 + ;; + --no-surf* | -ns*) + output_surface=0 + ;; + --nojvm | -nj*) + nojvm="" -nojvm "" + ;; + --fg* | -fg*) + fg=1 + ;; + --bids_folder* | --bids-folder* | -bf*) + exit_if_empty ""$optname"" ""$optarg"" + bids_folder=$optarg + shift + ;; + --b* | -b*) + exit_if_empty ""$optname"" ""$optarg"" + bids=1 + ;; + --logdir* | -log*) + exit_if_empty ""$optname"" ""$optarg"" + LOGDIR=$optarg + if [ ! -d $LOGDIR ]; then + mkdir -p $LOGDIR + fi + shift + ;; + --small* | -l*) + long_model=1 + ;; + --large* | -l*) + long_model=2 + ;; + -h | --help | -v | --version | -V) + help + exit 1 + ;; + -*) + echo ""`basename $0`: ERROR: Unrecognized option \""$1\"""" >&2 + ;; + *) + ARRAY[$count]=$1 + ((count++)) + ;; + esac + shift + done + +} + +######################################################## +# check arguments +######################################################## + +exit_if_empty () +{ + local desc val + + desc=""$1"" + shift + val=""$*"" + + if [ ! -n ""$val"" ]; then + echo 'ERROR: No argument given with \""$desc\"" command line argument!' >&2 + exit 1 + fi +} + +######################################################## +# check files +######################################################## + +check_files () +{ + + SIZE_OF_ARRAY=""${#ARRAY[@]}"" + if [ ""$SIZE_OF_ARRAY"" -eq 0 ]; then + echo 'ERROR: No files given!' >&2 + help + exit 1 + fi + + if [ ""$SIZE_OF_ARRAY"" -lt 2 ]; then + echo 'ERROR: You have to define at least two files for longitudinal processing!' >&2 + help + exit 1 + fi + + i=0 + while [ ""$i"" -lt ""$SIZE_OF_ARRAY"" ]; do + if [ ! -f ""${ARRAY[$i]}"" ]; then + if [ ! -L ""${ARRAY[$i]}"" ]; then + echo ERROR: File ${ARRAY[$i]} not found + help + exit 1 + fi + fi + ((i++)) + done + +} + +######################################################## +# modify defaults +######################################################## + +modifiy_defaults () +{ + pwd=$PWD + + # argument empty? + if [ -n ""${defaults}"" ]; then + # check whether absolute or relative names were given + if [ -f ""${pwd}/${defaults}"" ]; then + defaults=""${pwd}/${defaults}"" + fi + + # check whether defaults file exist + if [ ! -f ""${defaults}"" ]; then + echo Default file ""$defaults"" not found. + exit + fi + else + defaults=${cat12_dir}/cat_defaults.m + fi + + # modifiy defaults if needed + cp ${defaults} ${defaults_tmp} + + if [ -n ""$bids_folder"" ]; then + echo ""cat.extopts.bids_folder = '${bids_folder}';"" >> ${defaults_tmp} + echo ""cat.extopts.bids_yes = 1;"" >> ${defaults_tmp} + fi + + if [ ""$bids"" -eq 1 ]; then + echo ""cat.extopts.bids_yes = 1;"" >> ${defaults_tmp} + fi + +} + +######################################################## +# run cat12 long pipeline +######################################################## + +run_cat12 () +{ + pwd=$PWD + + # we have to go into toolbox folder to find matlab files + cd $cwd + + if [ ! -n ""${LOGDIR}"" ]; then + LOGDIR=$(dirname ""${ARRAY[0]}"") + fi + + # we have to add current path if cat_batch_cat.sh was called from relative path + if [ -d ${pwd}/${spm12} ]; then + spm12=${pwd}/${spm12} + fi + + export MATLABPATH=$spm12 + + SIZE_OF_ARRAY=""${#ARRAY[@]}"" + + TMP=/tmp/cat_$$ + i=0 + while [ ""$i"" -lt ""$SIZE_OF_ARRAY"" ]; do + + # check whether absolute or relative names were given + if [ ! -f ${ARRAY[$i]} ]; then + if [ -f ""${pwd}/${ARRAY[$i]}"" ]; then + FILE=""${pwd}/${ARRAY[$i]}"" + fi + else + FILE=${ARRAY[$i]} + fi + + # replace white spaces + FILE=$(echo ""$FILE"" | sed -e 's/ /\\ /g') + + if [ ! -n ""${ARG_LIST}"" ]; then + ARG_LIST=""$FILE"" + else + ARG_LIST=""${ARG_LIST} $FILE"" + fi + ((i++)) + done + + echo ${ARG_LIST} >> ${TMP} + + time=`date ""+%Y%b%d_%H%M""` + vbmlog=${LOGDIR}/cat_${HOSTNAME}_${time}.log + + # if relative foldername were given we have to add the data folder because we change into cat12 folder + if [ ! -d ${LOGDIR} ]; then + vbmlog=${pwd}/${vbmlog} + fi + + echo Check $vbmlog for logging information + echo + + COMMAND=""addpath('${spm12}'); cat_batch_long('${TMP}','${output_surface}','${long_model}','${defaults_tmp}','${export_dartel}','{printlong}')"" + echo Running ${ARG_LIST} + echo > $vbmlog + echo ---------------------------------- >> $vbmlog + date >> $vbmlog + echo ---------------------------------- >> $vbmlog + echo >> $vbmlog + echo $0 $ARG_LIST >> $vbmlog + echo >> $vbmlog + + if [ ""$fg"" -eq 0 ]; then + nohup ${matlab} ""$nojvm"" -nodisplay -nosplash -r ""$COMMAND"" >> $vbmlog 2>&1 & + else + nohup ${matlab} ""$nojvm"" -nodisplay -nosplash -r ""$COMMAND"" >> $vbmlog 2>&1 + fi + + exit 0 +} + +######################################################## +# check if matlab exist +######################################################## + +check_matlab () +{ + found=`which ${matlab} 2>/dev/null` + if [ ! -n ""$found"" ]; then + echo $matlab not found. + exit 1 + fi +} + +######################################################## +# help +######################################################## + +help () +{ +cat <<__EOM__ + +USAGE: + cat_batch_long.sh filenames|filepattern [-d default_file] [-m matlabcommand] + [-log logdir] [-ns] [-large] [-model longmodel] [-printlong printlong] [-e] [-nj] + + -m | --matlab matlab command (default $matlab) + -d | --defaults optional default file (default ${cat12_dir}/cat_defaults.m) + -log | --logdir directory for log-file (default $LOGDIR) + -fg | --fg do not run matlab process in background + -ns | --no-surf disable surface and thickness estimation + -e | --export-dartel export affine registered segmentations for Dartel + -large | --large use longitudinal model for detecting large changes (i.e. ageing) + This option is only thought for compatibility with older scripts. Do not use that option together with the model flag. + -small | --small use longitudinal model for detecting smaller changes (i.e. plasticity) + This option is only thought for compatibility with older scripts. Do not use that option together with the model flag. + -nj | --nojvm supress call of jvm using the -nojvm flag + -model | --model longitudinal model: + 0 - detect large changes with brain/head growth (i.e. developmental effects) + 1 - detect small changes (i.e. due to plasticity) + 2 - detect large changes (i.e. ageing) + 3 - save results for both models 1 and 2 (default) + -printlong | --printlong print longitudinal report + 0 - no printing + 1 - print report but only volume results + 2 - print full report (default) + -b | --bids use default BIDS path (i.e. '../derivatives/CAT12.x_rxxxx') + -bf | --bids_folder define BIDS path + + Processing is only supported for one subject. + Optionally you can set the matlab command with the ""-m"" option. As default no display + is used (via the -nodisplay option in matlab). However sometimes the batch file needs + a graphical output and the display should be enabled with the option ""-d"". + +PURPOSE: + Command line call of longitudinal segmentation pipeline + +EXAMPLE + cat_batch_long.sh all_files*.nii -m /Volumes/UltraMax/MATLAB_R2010b.app/bin/matlab + This command will process all given files in the longitudinal pipeline. As matlab command + /Volumes/UltraMax/MATLAB_R2010b.app/bin/matlab will be used. + +INPUT: + filenames + +OUTPUT: + ${LOGDIR}/spm_${HOSTNAME}_${time}.log for log information + +USED FUNCTIONS: + SPM12 + +SETTINGS + matlab command: $matlab + +This script was written by Christian Gaser (christian.gaser@uni-jena.de). + +__EOM__ +} + +######################################################## +# call main program +######################################################## + +main ${1+""$@""} +","Shell" +"Neurology","ChristianGaser/cat12","cat_plot_cov.m",".m","2879","126","function cat_plot_cov(data,opt) +% Plot rotated covariance matrix +% FORMAT cat_plot_cov(data,opt) +% data - covariance/correlation matrix +% opt +% .ax - currect axes +% .name - tick labels +% .group - group coding (1..k) for different samples (indicated with +% different colors) +% .color - background color +% .pos_cbar - position of colorbar +% .ctick - number of tick labels for colorbar +% +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +% sample size +[m,n] = size(data); + +% data should be quadratic matrix +if m ~= n + error('Data should be a covariance or correlation matrix'); +end + +% get axes +if isfield(opt,'ax') + ax = opt.ax; +else + ax = gca; +end + +% get group for coloring names for different samples +if isfield(opt,'group') + group = opt.group; +else + group = ones(n,1); +end + +% get position of axes +pos0 = get(ax,'Position'); + +% tick labels +if isfield(opt,'name') + name = opt.name; +else + name = num2str(1:n); +end + +% background color +if isfield(opt,'color') + col = opt.color; +else + col = [0.8 0.8 0.8]; +end + +% position of colorbar +if isfield(opt,'pos_cbar') + pos = opt.pos_cbar; +else + pos = [pos0(1) 0.950 pos0(3) 0.025*pos0(4)]; +end + +% number of tick labels for colorbar +if isfield(opt,'ctick') + ctick = opt.ctick; +else + ctick = 5; +end + +shift = min(max(0.08,1/(13 - 45/n)),0.4); +shift = pos0(3)/(0.0692*n+8.871); + +% scale data to min..max +mn = min(data(:)); +mx = max(data(data~=1)); + +% show only lower left triangle +data_scaled = tril((data - mn)/(mx - mn)); + +image(64*data_scaled); +set(gca,'XTickLabel',[],'YTickLabel',[],'Color',col); +view([-45 90]) +set(get(ax,'children'),'AlphaData',tril(isfinite(data))); + +axis image +axis off + +% colorbar +H.cbar = axes('Position',pos,'Parent',gcf); +image(1:64); + +set(H.cbar,'YTickLabel','','XTickLabel','','XTick',linspace(1,64,ctick), 'XTickLabel',... + round(100*linspace(min(data(:)),max(data(data~=1)),ctick))/100,'TickLength',[0 0]); + +% axes of rotated tick labels +pos = [pos0(1)+shift pos0(2)+pos0(4)/1.8 pos0(3)-2*shift pos0(4)/2]; +ax = axes('Position',pos,'Parent',gcf,'Color',col); + +% position of tick labels +pos_text = linspace(0,1,n); + +% limit ticks to maximum of 50 +gap = round(n/min(n,50)); + +% colormap for groups +if exist('lines') + cm = lines(max(group)); +else + cm = jet(max(group)); +end + +for i=1:gap:n + t = text(pos_text(i),0.15,name(i,:),'parent',ax,'interpreter','none','Color',0.8*cm(group(i),:)); + set(t,'Units','normalized','VerticalAlignment','middle','HorizontalAlignment','left','Rotation',90); + if isfield(opt,'fontsize') + set(t,'FontSize',opt.fontsize); + end +end +axis off +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_vol_sanlm2.m",".m","33978","719","function out = cat_vol_sanlm2(varargin) +% Spatial Adaptive Non Local Means (SANLM) Denoising Filter +%_______________________________________________________________________ +% Filter a set of images and add the prefix 'sanlm_'. +% Missing input (data) will call GUI or/and use defaults. +% +% Examples: +% cat_vol_sanlm(struct('data','','prefix','n','rician',0)); +% cat_vol_sanlm(struct('data','','NCstr',[-1:0.5:1,inf,-inf)); +% +% Input: +% job - harvested job data structure (see matlabbatch help) +% +% Output: +% out - computation results, usually a struct variable. +% +% cat_vol_sanlm(job) +% +% job +% .data .. set of images +% .prefix .. prefix for filtered images (default = 'sanlm_') +% .suffix .. suffix for filtered images (default = '') +% 'NCstr' will add the used parameter +% .verb .. verbose processing (default = 1) +% .spm_type .. file datatype (default single = 16); +% .replaceNANandINF .. replace NAN by 0, -INF by minimum and INF by maximum +% .rician .. noise distribution +% .intlim .. intensity limitation (default = 0.9999) +% .addnoise .. add noise to noiseless regions +% Add minimal amount of noise in regions without any noise to avoid +% problems of image segmentation routines. The value defines the +% strength of the noise by the percentage of the mean signal intensity. +% .NCstr .. strength of noise correction (default = -inf) +% A value of 1 used the full correction by the SANLM filter. Values +% between 0 and 1 mix the original and the filtered images, whereas +% INF estimated a global value depending on the changes of the SANLM +% filter that reduce to strong filtering in high quality data. +% Negative values work on a local rather than a global level. +% A value of -INF is recommend, but you define a set of values (see +% example) for further changes depending on your data. +% +% 0 .. no denoising +% 1 .. full denoising (original sanlm) +% 2 .. ""light"": NCstr=-0.5, red=0, fred=0; iterm=0 +% 3 | -inf .. ""medium"": NCstr=-1.0, red=1, fred=0; iterm=0 +% 4 .. ""strong"": NCstr= 1.0, red=1, fred=1; iterm=1 +% 0 < job.NCstr < 1 .. automatic global correction with user weighting +% -9 < job.NCstr < 0 .. automatic local correction with user weighting +% inf .. global automatic correction +% -inf .. local automatic correction +% +% .returnOnlyFilename .. just to get the resulting filenames for SPM +% batch mode (default = 0) +% .resolutionDependency .. resolution depending filter strength +% Use the .resolutionDependencyRange Parameter (default = 1) +% .resolutionDependencyRange .. [full-correction no-correction] +% Limit the filter size depending on the general brain size, where +% filtering of images with 2.5 mm voxel size and higher will remove +% important anatomical information (default = [1 2.5]). +% .red .. low resolution filtering (if high-res data) +% .fred .. force resolution reduction +% .iter .. additional iterations on the reduced resolution +% (default = 0) +% .iterm .. additional main iterations of the full filter +% (default = 0) +% +% Some MR images were interpolated or use a limited frequency spectrum to +% support higher spatial resolution with acceptable scan-times +% (eg. 0.5x0.5x1.5 mm on a 1.5 Tesla scanner). However, this can result in +% ""low-frequency"" noise that can not be handled by the standard NLM filter. +% Hence, an additional filtering step is used on a reduces resolution that +% uses an internal call of this routine with direct image in- an output. +% +% src = cat_vol_sanlm(job,V,i,src) +% +% As far as filtering of low resolution data will also remove anatomical +% information the filter uses by default maximal one reduction with a +% resolution limit of 1.6 mm. I.e. a 0.5x0.5x1.5 mm image is reduced +% to 1.0x1.0x1.5 mm, whereas a 0.8x0.8x0.4 mm images is reduced to +% 0.8x0.8x0.8 mm and a 1x1x1 mm dataset is not reduced at all. +% +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + % this function adds noise to the data to stabilize processing and we + % have to define a specific random pattern to get the same results each time + if exist('rng','file') == 2, rng('default'); rng(0); else, rand('state',0); randn('state',0); end + + if nargin == 0 + varargin{1}.data = cellstr(spm_select([1 Inf],'image','select images to filter')); + if isempty(char(varargin{1}.data)); return; end + end + + % default optoins + def.verb = 2; % be verbose + def.prefix = 'sanlm_'; % prefix + def.suffix = ''; % suffix + def.replaceNANandINF = 1; % replace NAN and INF + def.spm_type = 16; % file datatype (default single) + def.NCstr = -Inf; % 0 - no denoising, eps - light denoising, + % 1 - maximum denoising, inf = auto; + def.rician = 0; % use inf for GUI + def.intlim = [0.9999 0.9999]; % general intensity limitation to remove strong outlier + def.resolutionDependency = 1; % resolution depending filter strength + def.resolutionDependencyRange = [1 2.5]; % [full-correction no-correction] + def.relativeIntensityAdaption = 1; % use intensity to limit relative corrections (0 - none, 1 - full) + def.relativeIntensityAdaptionTH = 1; % larger values for continuous filter strength + def.relativeFilterStengthLimit = 1; % limit the noise correction by the relative changes + % to avoid over-filtering in low intensity regions + def.outlier = 0; % threshold to define outlier voxel to filter them with full strength + def.addnoise = 0; % option to add a minimal amount of noise in regions without noise + def.returnOnlyFilename = 0; % just to get the resulting filenames for SPM batch mode + def.red = 0; % number of reductions (be careful using values greater 1!) + def.fred = 0; % force reduce + def.iter = 0; % additional inner iterations on the reduced resolution + def.iterm = 0; % additional main iterations of the full filter + def.lazy = 0; % avoid reprocessing if file exist + def.sharpening = 0; + job = varargin; + if isfield(job{1},'nlmfilter') + subfield = fieldnames(job{1}.nlmfilter); + FN = fieldnames(job{1}.nlmfilter.(subfield{1})); + for fni = 1:numel(FN) + job{1}.(FN{fni}) = job{1}.nlmfilter.(subfield{1}).(FN{fni}); + end + end + job{1} = cat_io_checkinopt(job{1},def); + + % special cases of the CAT GUI + if isfield(job{1},'nlmfilter') + if isfield(job{1}.nlmfilter,'optimized') + job{1} = cat_io_checkinopt(job{1}.nlmfilter.optimized,job{1}); + elseif isfield(job{1}.nlmfilter,'expert') + job{1} = cat_io_checkinopt(job{1}.nlmfilter.expert,job{1}); + elseif isfield(job{1}.nlmfilter,'classic') + job{1}.resolutionDependency = 0; + job{1}.relativeIntensityAdaption = 0; + job{1}.relativeFilterStengthLimit = 0; + end + end + + % general settings + if nargin > 0 && isstruct(job{1}) && isfield(job{1},'nlmfilter') && isfield(job{1}.nlmfilter,'optimized') && isfield(job{1}.nlmfilter,'NCstr') + job{1}.NCstr = job{1}.nlmfilter.optimized.NCstr; + end + if nargin > 0 && isstruct(job{1}) && isfield(job{1},'NCstr') && ... + ( isfield(job{1},'nlmfilter') && ~isfield(job{1}.nlmfilter,'classic') ) + switch job{1}.NCstr + case 2, job{1}.NCstr = -0.5; job{1}.red = 0; job{1}.fred = 0; job{1}.iterm = 0; job{1}.iter = 0; name = 'light'; + case {3,-inf,-1}, job{1}.NCstr = -1.0; job{1}.red = 1; job{1}.fred = 0; job{1}.iterm = 0; job{1}.iter = 0; name = 'medium'; + case 4, job{1}.NCstr = 1.0; job{1}.red = 1; job{1}.fred = 1; job{1}.iterm = 0; job{1}.iter = 0; name = 'strong'; + case 5, job{1}.NCstr = 1.0; job{1}.red = 1; job{1}.fred = 1; job{1}.iterm = 1; job{1}.iter = 1; name = 'heavy'; + case 12, job{1}.NCstr = -0.5; job{1}.red = 0; job{1}.fred = 0; job{1}.iterm = 0; job{1}.iter = 0; name = 'lightavg'; + job{1}.addnoise = 0; job{1}.outlier = 0; + case 14, job{1}.NCstr = -1.0; job{1}.red = 1; job{1}.fred = 1; job{1}.iterm = 0; job{1}.iter = 0; name = 'strongavg'; + job{1}.addnoise = 0; job{1}.outlier = 0; + otherwise, name = ''; + end + job{1}.nlmfilter.optimized.NCstr = job{1}.NCstr; + if ~isempty( name ) + if ~isempty(strfind(job{1}.prefix,'PARA')) + job{1}.prefix = strrep(job{1}.prefix,'PARA',['optimized-' name '_']); + end + if ~isempty(strfind(job{1}.suffix,'PARA')) + job{1}.suffix = strrep(job{1}.suffix,'PARA',['_optimized-' name]); + end + job{1}.filtername = ['optimized-' name]; + else + job{1}.filtername = sprintf('NC%+0.1f',job{1}.NCstr); + end + elseif isfield(job{1},'nlmfilter') && isfield(job{1}.nlmfilter,'classic') + if ~isempty(strfind(job{1}.prefix,'PARA')) + job{1}.prefix = strrep(job{1}.prefix,'PARA','classic_'); + end + if ~isempty(strfind(job{1}.suffix,'PARA')) + job{1}.suffix = strrep(job{1}.suffix,'PARA','_classic'); + end + job{1}.filtername = 'classic'; + elseif nargin > 0 && isstruct(job{1}) + job{1}.filtername = 'manual'; + else + job{1}.filtername = ''; + end + + if nargin <= 1 && isstruct(varargin{1}) % job structure input + out.files = cat_vol_sanlm_file(job{1}); + else % image input + out = cat_vol_sanlm_filter(job{:}); + end + +end + +%_______________________________________________________________________ +function varargout = cat_vol_sanlm_file(job) + + if ~isfield(job,'data') || isempty(job.data) + job.data = cellstr(spm_select([1 Inf],'image','select images to filter')); + else + job.data = cellstr(job.data); + end + if isempty(char(job.data)); if nargout>0, varargout{1} = {{''}}; end; return; end + + + % map GUI data + if isfield(job,'nlmfilter') + if isfield(job.nlmfilter,'classic') + job.NCstr = 1; + elseif isfield(job.nlmfilter,'optimized') + FN = fieldnames(job.nlmfilter.optimized); + for fni=1:numel(FN) + if isfield(job.nlmfilter.optimized,FN{fni}) + job.(FN{fni}) = job.nlmfilter.optimized.(FN{fni}); + end + end + end + end + + % parameter limitations + if ~isinf(job.NCstr), job.NCstr = max(-9.99,min(1,job.NCstr)); end % guarantee values from -9.99 to 1 or inf + job.resolutionDependency = max(0,min(9.99,job.resolutionDependency)); + job.relativeIntensityAdaption = max(0,min(9.99,job.relativeIntensityAdaption)); + job.relativeIntensityAdaptionTH = max(0,min(9.99,job.relativeIntensityAdaptionTH)); + job.relativeFilterStengthLimit = max(0,min(9.99,job.relativeFilterStengthLimit)); + job.outlier = max(0,min(9.99,job.outlier)); + job.addnoise = max(0,min(9.99,job.addnoise)); + + % create automatic filenames by the parameter + if ~isempty(strfind(job.prefix,'PARA')) + nprefix = strrep(job.prefix,'PARA',''); + if numel(nprefix)>0 && ~(strcmp(nprefix(end),'_') || strcmp(nprefix(end),'-')), nprefix = [nprefix '_']; end + if job.NCstr>=0 + job.prefix = sprintf('%sNC%0.2f_',nprefix,job.NCstr); + elseif isinf(job.NCstr) && sign(job.NCstr)==-1 + job.prefix = sprintf('%sNC%0.2f_',nprefix,3); + else + job.prefix = sprintf('%sNC%-0.2f_RN%d_RD%d_RIA%0.2f_RR%d_FR%d_RNI%d_OL%0.2f_PN%0.1f_iterm%d_iter%d',... + nprefix, job.NCstr , job.rician , job.resolutionDependency , job.red , job.fred , job.relativeIntensityAdaption , ... + job.replaceNANandINF , job.outlier , job.addnoise , job.iterm , job.iter); + end + elseif ~isempty(strfind(job.suffix,'PARA')) + if numel(job.NCstr)==1 && job.NCstr>=0 + job.suffix = sprintf('_NC%0.2f',job.NCstr); + elseif isinf(job.NCstr) && sign(job.NCstr)==-1 + job.prefix = sprintf('_NC%0.2f',3); + else + job.suffix = sprintf('_NC%-0.2f_RN%d_RD%d_RIA%0.2f_RR%d_FR%d_RNI%d_OL%0.2f_PN%0.1f_iterm%d_iter%d',... + job.NCstr , job.rician , job.resolutionDependency , job.red , job.fred , job.relativeIntensityAdaption , ... + job.replaceNANandINF , job.outlier , job.addnoise , job.iterm , job.iter); + end + end + % just to get the resulting filenames for SPM batch mode + for i = 1:numel(job.data) + [pth,nm,xt,vr] = spm_fileparts(deblank(job.data{i})); + varargout{1}{i} = fullfile(pth,[job.prefix nm job.suffix xt vr]); + end + if job.returnOnlyFilename + return + end + + V = spm_vol(char(job.data)); + + % new banner + if isfield(job,'process_index') && job.verb, spm('FnBanner',mfilename); end + spm_clf('Interactive'); + spm_progress_bar('Init',numel(job.data),'SANLM-Filtering','Volumes Complete'); + + for i = 1:numel(job.data) + if ~job.lazy || cat_io_rerun( job.data{1} , varargout{1}{i} ) + cat_vol_sanlm_filter(job,V,i); + end + end + + if isfield(job,'process_index') && job.verb, fprintf('Done\n'); end + spm_progress_bar('Clear'); +end + +%_______________________________________________________________________ +function [src2,NCstr,NCrate] = cat_vol_sanlm_filter(job,V,i,src) + Vo = V; + + QMC = cat_io_colormaps('marks+',17); + color = @(m) QMC(max(1,min(size(QMC,1),round(((m-1)*3)+1))),:); + + % if there is a breakpoint in this file set debug=1 and do not clear temporary variables + dbs = dbstatus; debug = 0; for dbsi=1:numel(dbs), if strcmp(dbs(dbsi).name,mfilename); debug = 1; break; end; end + + + [pth,nm,xt,vr] = spm_fileparts(deblank(V(i).fname)); %#ok + + stime = clock; stimef = clock; + vx_vol = sqrt(sum(V(i).mat(1:3,1:3).^2)); + + if nargin<4 + src = single(spm_read_vols(V(i))); + else + src = single(src); + end + + % get zero areas before filtering to consider skull-stripped data + ind_zero = src == 0; + + for im=1:1+job.iterm + % prevent NaN and INF + if job.replaceNANandINF + src(isnan(src)) = 0; + src(isinf(src) & src<0) = min(src(:)); + src(isinf(src) & src>0) = max(src(:)); + else + if sum(isnan(src(:))>0), nanmsk = isnan(src); end + if sum(isinf(src(:))>0), infmsk = int8( isinf(src) .* sign(src) ); end + end + + % histogram limit + [src,srcth] = cat_stat_histth(src,job.intlim); + + % use intensity normalisation because cat_sanlm did not filter values below ~0.01 + th = max( cat_stat_nanmean( src(src(:)>cat_stat_nanmean(src(src(:)>0))) ) , ... + abs(cat_stat_nanmean( src(src(:)0 && (any(vx_vol<0.8) || job.fred ) + clear NCrater; + [srcr,resr] = cat_vol_resize( src ,'reduceV',vx_vol,min(2.2*(job.fred+1),min(vx_vol)*2.3),32,'mean'); + + jobr = job; + jobr.red = job.red - 1; + jobr.iterm = 0; + jobr.addnoise = 0; % no additional noise on lower resolution + jobr.resolutionDependency = 1; % resolution depending filter strength + jobr.resolutionDependencyRange = [1 1.6]; % [full-correction no-correction] + jobr.outlier = 0; + if 0 % RD20220302: deactivated ... this was even not used before and rewritten by the next if-block + jobr.NCstr = -prod(3-resr.vx_red)*2 .* ... + min(1,1 - (mean(resr.vx_volr) - jobr.resolutionDependencyRange(1) )) / ... + diff(jobr.resolutionDependencyRange); + end + if 0 % RD20220302: deactivated + % larger var => more information + Ygr = cat_vol_grad(srcr/th,resr.vx_volr,0); + grsd = std(Ygr(Ygr(:)>0)); + grrel = numel(Ygr(Ygr(:)>grsd))/numel(Ygr(Ygr(:)>0)); + jobr.NCstr = jobr.NCstr .* jobr.NCstr * grrel*10; + end + srcor = src; + if any(resr.vx_red>1) && any( resr.vx_volr < jobr.resolutionDependencyRange(2)*(job.fred+1) ) && jobr.NCstr~=0 + % first block + Vr = V(i); Vmat = spm_imatrix(Vr.mat); Vmat(7:9) = Vmat(7:9).*resr.vx_red; Vr.mat = spm_matrix(Vmat); + srcR = cat_vol_resize(srcr,'dereduceV',resr,'cubic'); + for iter=1:1+job.iter + [srcr,NCstrr1(iter),NCrater1(iter)] = cat_vol_sanlm_filter(jobr,Vr,1,srcr); + end + srcRS = cat_vol_resize(srcr,'dereduceV',resr,'cubic'); + src = (src - srcR) + srcRS; + clear srcRS srcr srcR; + + % second block + if 1 % the second displaced filtering helps to deduce low frequency noise a little bit more + [srcr,resr] = cat_vol_resize( src(2:end,2:end,2:end) ,'reduceV',... + vx_vol,min(2.2*(job.fred+1),min(vx_vol)*2.3),32,'median'); + srcRr = cat_vol_resize(srcr,'dereduceV',resr,'cubic'); + srcR = src; srcR(2:end,2:end,2:end) = srcRr; + for iter=1:1+job.iter + [srcr,NCstrr2(iter),NCrater2(iter)] = cat_vol_sanlm_filter(jobr,Vr,1,srcr); + end + srcRr = cat_vol_resize(srcr,'dereduceV',resr,'cubic'); + srcRS = src; srcRS(2:end,2:end,2:end) = srcRr; + src = src + (src - srcR) + srcRS; + clear srcRS srcr srcR; + src = src / 2; + end + end +% srcoo = srco; + + NCrater = mean([NCrater1 NCrater2]); + NCstrr = mean([NCstrr1 NCstrr2]); % or sum() / 2 ; + %NCstrr = 15 * abs(cat_stat_nanmean(abs(src(:)/th - srco(:)/th))); + else + NCrater = 0; + NCstrr = 0; + end + if job.verb>1 && (nargin>3 || NCstrr>0) + cat_io_cprintf('g5',sprintf('R%1d) %0.2fx%0.2fx%0.2f mm: ',job.red,vx_vol)); stime = clock; + end + + + % the real noise filter + if 0 + if im==1, srco = src; end + src = (src / th) * 100; + src = (src - srcth(1)); % avoid negative values! + cat_sanlm(src,3,1,job.rician); + src = src + srcth(1); % restore original intensity range + src = (src / 100) * th; + end + if job.verb>1 && (nargin>3 || NCstrr>0) && im<1+job.iterm + if job.verb>1 && (nargin>3 || NCstrr>0), cat_io_cprintf('g5',sprintf(' %5.0fs\n',etime(clock,stime))); end + end + end + + % measures normalized changes (th ~ signal intensity) as RMS rate + NCrate = cat_stat_nanmean( abs( src(src(:)~=0)/th - srco(src(:)~=0)/th ).^2 )^0.5; + + lowResMixing = 2; + if lowResMixing>0 && NCrater > 0 && NCrate > NCrater + % Skip low resolution filtering if the default resolution contains more + % noise to prevent overfiltering. Low resolution filtering is only + % useful in case of interpolated/smoothed data were the sanlm is not + % effective at full resolution. + if lowResMixing == 1 + if job.verb > 1 && NCrater > 0 + cat_io_cprintf('blue',sprintf(... + 'Skip low-res filter result because there is more high-frequency noise (NCrater=%8.6f < NCrate=%8.6f).\n ', ... + NCrater, NCrate)); + end + NCrater = 0; + src = src + (srcor - srco); + else + NCmix = min(1,max(0,(NCrater / NCrate )^2)); + NCrater = NCrater * NCmix; + src = src + NCmix * (srcor - srco); + end + end + if ~debug, clear srcor; end + + % set actual filter rate - limit later! + % the factor 15 was estimated on the BWP + NCstr = job.NCstr; + NCstr(isinf(NCstr) & NCstr<0) = -1; % default value + NCstr(NCstr<0) = NCstr(NCstr<0) .* 15 * NCrate; % local dynamic weighting + + for NCstri = 1:numel(NCstr) + if job.verb>1 && (nargin>3 || NCstrr>0) + if exist('NCrater','var') && NCrater > 0 + cat_io_cprintf('g5',sprintf(' (NCrater=%9.6f; NCrate=%8.6f; NCstr=%5.2f) ',NCrater,NCrate,NCstr(NCstri))); + else + cat_io_cprintf('g5',sprintf(' (NCrate=%9.6f; NCstr=%5.2f) ',NCrate,NCstr(NCstri))); + end + elseif exist('NCrater','var') && NCrater > 0 + if job.verb>1 && ~(nargin>3 || NCstrr>0) + % if multiple resolution were used (and printed) than also show when working on full resolution + cat_io_cprintf('g5',sprintf('R0) %0.2fx%0.2fx%0.2f mm: ',vx_vol)); + end + cat_io_cprintf('g5',sprintf(' (NCrater=%8.6f; NCrate=%8.6f) \n ',NCrater,NCrate)); + end + + + if NCstr(NCstri)<0 + % adaptive local denoising + + %% prepare local map + % use less filtering for low-res data to avoid anatomical blurring ??? + NCs = max(eps,abs(src - srco)/th); + + % preserve anatomical details by describing the average changes + % and not the strongest - this reduce the ability of artifact + % correction! + stdNC = std(NCs(NCs(:)~=0)); + NCsm = cat_vol_median3(NCs,NCs>stdNC,true(size(NCs))); % replace outlier + [NCsr,resT2] = cat_vol_resize(NCsm,'reduceV',vx_vol,2,32,'meanm'); clear NCsm; + NCsr = cat_vol_localstat(NCsr,true(size(NCs)),1,1); + NCsr = cat_vol_smooth3X(NCsr,1/mean(resT2.vx_volr)); + NCsr = cat_vol_resize(NCsr,'dereduceV',resT2); + NCso = NCs; + + % no correction of local abnormal high values (anatomy) + NCs = NCsr + (NCso>stdNC & NCso<=stdNC*4 & NCso>NCsr*2 & NCso0 + [NCi,range] = cat_stat_histth(src,job.intlim); % lower values > more similar filtering + NCi = max(eps,log10( 1 + (NCi + range(1)) / diff(range) * 7 + 3 )); % bias corr + intensity normalization + NCi = cat_vol_smooth3X( NCi , job.relativeIntensityAdaption / mean(vx_vol)); % smoothing + if job.relativeIntensityAdaption>0 && ... + job.relativeFilterStengthLimit && ~isinf(job.relativeFilterStengthLimit) + NCsi = NCs ./ max(eps,NCi); + mNCs = cat_stat_nanmean( NCsi(src(:)>th/2 & NCsi(:)>0 )) * ... + job.relativeFilterStengthLimit * ... + max(1,min(4,4 - job.relativeIntensityAdaption*2)); % lower boundary for strong adaptation + NCsi = min( NCsi , mNCs ) .* NCi; + + % Finally, both images were mixed + NCs = NCs * (1 - job.relativeIntensityAdaption) + ... % linear average model to contoll filter strength + NCsi * job.relativeIntensityAdaption; + if ~debug, clear NCsi; end + end + + + + % heavy outlier / artifacts + NCi = min(1,max(0,NCi .* (NCso - ( (stdNC*2) / job.outlier ) ) ./ ((stdNC*2) / job.outlier ))); + NCs = max(NCs, NCi); + if ~debug, clear NCi; end + end + + + %% preserve anatomy + % the idea was to avoid locally clustered corrections but its + % not really working + % >> changed this to a general limitation that only corrects + % stong differences what is maybe useful in case of multiple + % iterations but also this looks better the interesting + % parts of the hippocampus are gone :/ + % + + if 1 % sharpending + src = src .* 2.^(smooth3(NCso)); + end + + %% + if debug, src2 = srco.*(1-NCs) + src.*NCs; end + % ds('d2','',vx_vol,src/th,srco/th,srco2/th, NCs,160) + + + if ~debug, clear NCso; end + + % mix original and noise corrected image + src2 = srco.*(1-NCs) + src.*NCs; + NCstr(NCstri) = -cat_stat_nanmean(NCs(:)); + if ~debug, clear NCs; end + + elseif NCstr(NCstri)==1 + % no adaptation (original filter) + src2 = src; + + elseif NCstr(NCstri)>0 + % simple global denoising + + NCstr(NCstri) = min(1,max(0,NCstr(NCstri))); + + % mix original and noise corrected image + src2 = srco*(1-NCstr(NCstri)) + src*NCstr(NCstri); + + else + % no denoising ... nothing to do + src2 = src; + + end + + + %% add noise + if job.addnoise && NCstrr==0 % only add noise on original resolution + % Small adaptation for inhomogeneity to avoid too much noise in + % regions with low signal intensity. + sth = cat_vol_smooth3X(log10(2 + 8*src/th),4/mean(vx_vol)) * th; + + % Correction only of regions with less noise and with (src~=0) to + % avoid adding of noise in skull-stripped data. This may lead to + % problems with the skull-stripping detection in cat_run_job! + % Also important in case of ADNI. + src2 = src2 + max( 0 , min(1 , cat_vol_smooth3X( ... + ( job.addnoise.*sth/100 ) - abs(srco - src) , 4/mean(vx_vol) ) ./ ( job.addnoise.*sth/100 ) )) .* ... + ( src~=0 ) .* ... save skull-stripping / defacing regions + (randn(size(src)) * job.addnoise.*sth/100); + if ~debug, clear sth; end + end + if numel(NCstr)==1 && ~debug, clear src srco; end + + % rescue zero-values (i.e. for skull-stripped data) + src2(ind_zero) = 0; + + + %% restore NAN and INF + if exist('nanmsk','var'), src2(nanmsk) = nan; end + if exist('infmsk','var'), src2(infmsk==-1) = -inf; src2(infmsk==1) = inf; end + if job.verb>1 && (nargin>3 || NCstrr>0), cat_io_cprintf('g5',sprintf(' %5.0fs\n',etime(clock,stime))); end + + if nargin==4 + return; + end + + % use only float precision + Vo(i).fname = fullfile(pth,[job.prefix nm job.suffix '.nii' vr]); + Vo(i).descrip = sprintf('%s SANLM filtered (NCrate=%-4.2f; NCstr=%-4.2f > %0.2f)',... + V(i).descrip,NCrate,job.NCstr(NCstri),abs(NCstr(NCstri)) + NCstrr); + Vo(i).dt(1) = 16; % default - changes later if required + if exist(Vo(i).fname,'file'); delete(Vo(i).fname); end + spm_write_vol(Vo(i), src2); + spm_progress_bar('Set',i); + + + + %% if single should be not used, the image has to be converted ... + if job.spm_type~=16 + ctype.data = Vo(i).fname; + + if job.spm_type + ctype.ctype = job.spm_type; + else + ctype.ctype = V(i).dt(1); + end + ctype.range = 99.99; + ctype.prefix = ''; + cat_io_volctype(ctype); + end + + + + %% display result and link images for comparison + if job.verb + % I am not sure if this is intuitive. Maybe someone will think + % that red means failed filtering ... + % green > low filtering + % red > strong filtering + if cat_get_defaults('extopts.expertgui') % NCstr(NCstri)<0 || isinf(NCstr(NCstri)) + fprintf(' NCstr = '); + cat_io_cprintf( color( ( ( abs(NCstr(NCstri)) ) * 6 )) , ... + sprintf('%- 5.2f > %4.2f', job.NCstr(NCstri) , abs(NCstr(NCstri)) )); + if NCstrr + cat_io_cprintf( color( ( ( abs(NCstrr) ) * 6 )) , ... + sprintf(' (R0: %4.2f)', abs(NCstrr) )); + end + cat_io_cprintf( [0 0 0] , ', '); % restore default color! + end + + % create some further parameter output for experts + FNs = {'filtername'}; + FNf = {'NCstr'}; + if cat_get_defaults('extopts.expertgui') + FNi = {'rician','intlim','outlier','addnoise','red','fred','iter','iterm'}; + else + FNi = {}; + end + parastr = ['''name = ' job.prefix '*' job.suffix ''';' ]; + for fni = 1:numel(FNs) + parastr = [parastr sprintf('''%s = %s''; ', FNs{fni}, job.(FNs{fni}))]; %#ok + end + for fni = 1:numel(FNf) + parastr = [parastr sprintf('''%s = %0.2f''; ', FNf{fni}, job.(FNf{fni}))]; %#ok + end + for fni = 1:numel(FNi) + parastr = [parastr sprintf('''%s = %d''; ', FNi{fni}, job.(FNi{fni}))]; %#ok + end + + %% spm_orthview preview + % This is a long string but it loads the original and the filtered + % image for comparison (with parameter settings) + fprintf('%5.0fs, Output %s\n',etime(clock,stimef),... + spm_file(Vo(i).fname,'link',sprintf(... + ['spm_figure(''Clear'',spm_figure(''GetWin'',''Graphics'')); ' ... + 'spm_orthviews(''Reset''); ' ... remove old settings + 'ax = axes; set(ax,''Position'',[0 0 1 1]); axis off; hd = text(ax,0.01,0.99,''File: ' job.data{i} '''); ' ... + 'ho = spm_orthviews(''Image'',''%s'' ,[0 0.51 1 0.49]); ',... top image + 'hf = spm_orthviews(''Image'',''%%s'',[0 0.01 1 0.49]);', ... bottom image + 'spm_orthviews(''Caption'', ho, ''original''); ', ... caption top image + 'spm_orthviews(''Caption'', hf, {{''filtered'';'' '';' , ... caption bottom image + parastr '}}); ', ... % the parameters + 'spm_orthviews(''AddContext'',ho); spm_orthviews(''AddContext'',hf); ', ... % add menu + 'spm_orthviews(''Zoom'',40);', ... % zoom in + ],V(i).fname))); + end + + + end +end + +function cat_vol_sanlm_selftest(BWPdir) + % define files + + % create some further test cases + % - resampling (e.g. from 1 to 0.5 mm) to simulated interpolation and low + % resolution filtering and final resampling to the original resolution + % should include 1/2 and 3/4 resolution + % - rotation + + % process major types + + % prepare some output +end + +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_surf_avg.m",".m","5342","154","function varargout = cat_surf_avg(varargin) +% ______________________________________________________________________ +% Surface mesh average function. Only batch mode available. +% +% [Pavg] = cat_surf_avg(job) +% +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + +% TODO: +% - sidehandling + + % add system dependent extension to CAT folder + opt.debug = 0; + opt.delete = 0; + opt.fsavgDir = fullfile(fileparts(mfilename('fullpath')),'templates_surfaces'); + + if nargin == 0, job = struct(); else job = varargin{1}; end + + if isempty(job.outdir{1}) + outdir = spm_fileparts(job.data{1}); + else + outdir = job.outdir{1}; + end + + %% + side = {'lh','rh'}; + filename = cell(numel(side),numel(job.meshsmooth)); FSavgfname = cell(1,2); FSavgsphere = cell(1,2); + for si = 1:numel(side) + FSavgfname{si} = fullfile(opt.fsavgDir,sprintf('%s.central.freesurfer.gii',side{si})); + FSavgsphere{si} = fullfile(opt.fsavgDir,sprintf('%s.sphere.freesurfer.gii',side{si})); + FSavg.(side{si}) = gifti(FSavgfname{si}); + Savg.(side{si}) = struct(... + 'vertices',zeros(size(FSavg.(side{si}).vertices),'single'),... + 'faces',zeros(size(FSavg.(side{si}).faces),'single')); + + for smi=1:numel(job.meshsmooth) + if job.meshsmooth(smi)>0 + filename{si,smi} = fullfile(outdir,sprintf('%s.%s_%dmm.gii',side{si},job.surfname,job.meshsmooth(smi))); + else + filename{si,smi} = fullfile(outdir,sprintf('%s.%s.gii',side{si},job.surfname)); + end + end + end + + + %% side variables - separate data into left and right surfaces + job.rh = {}; job.lh = {}; rhi=1; lhi=1; + for pi=1:numel(job.data) + [pp,ff,ee] = spm_fileparts(job.data{pi}); + switch ff(1:3) + case 'rh.' + job.rh{rhi} = fullfile(pp,[ff ee]); rhi = rhi + 1; + case 'lh.' + job.lh{lhi} = fullfile(pp,[ff ee]); lhi = lhi + 1; + otherwise + end + end + if job.surfside==2 + side = {'lh'}; + job.lh = [job.lh,job.rh]; + n = numel(job.lh) + numel(job.meshsmooth); + else + n = numel(job.rh) + numel(job.lh) + numel(job.meshsmooth); + end + + %% display something + spm_clf('Interactive'); nfi = 0; + cat_progress_bar('Init',n,'Surface Averaging and Smoothing','Surfaces (and Smoothing Steps) Complete'); + for si=1:numel(side) + if numel(job.(side{si}))>0 + %% + Savg.(side{si}).vertices = zeros(size(FSavg.(side{si}).vertices),'single'); + + sinfo = cat_surf_info(job.(side{si})); NS=numel(job.(side{si})); + for di=1:NS + %% + try + [pp1,ff1,ee1] = fileparts(job.(side{si}){di}); + Pcentral = job.(side{si}){di}; + Presamp = fullfile(pp1,[strrep(ff1,'central','resampled') ee1]); + Pspherereg = fullfile(pp1,[strrep(ff1,'central','sphere.reg') ee1]); + + % resample values using warped sphere + if ~exist(Presamp,'file') + %try + cmd = sprintf('CAT_ResampleSurf ""%s"" ""%s"" ""%s"" ""%s""',Pcentral,Pspherereg,FSavgsphere{si},Presamp); + cat_system(cmd,opt.debug); + %catch + % cmd = sprintf('CAT_ResampleSurf ""%s"" ""%s"" ""%s"" ""%s""',Pcentral,Pspherereg,FSavgfname{si},Presamp); + % cat_system(cmd,opt.debug); + %end + end + + % read surfaces + S = gifti(Presamp); + + if job.surfside==2 && strcmp(sinfo(di).side,'lh'); + S.vertices(:,1) = -1 * S.vertices(:,1); + end + + + if opt.delete, delete(Presamp); end + + % add + Savg.(side{si}).vertices = Savg.(side{si}).vertices + S.vertices; + nfi = nfi + 1; cat_progress_bar('Set',nfi); + catch + %NS=NS-1; + S =gifti(Pcentral); + if di==1, Savg.(side{si}).vertices = zeros(size(S.vertices),'single'); end + end + end + + Savg.(side{si}).vertices = Savg.(side{si}).vertices / max(1,NS); + + % surface smoothing + for smi=1:numel(job.meshsmooth); + if job.surfside==1 + save(gifti(struct('faces',S.faces,'vertices',... + Savg.(side{si}).vertices)),filename{si,smi}); + cmd = sprintf('CAT_BlurSurfHK ""%s"" ""%s"" %d',filename{si,smi},filename{si,smi},job.meshsmooth(smi)); + cat_system(cmd,0); + else + save(gifti(struct('faces',FSavg.(side{si}).faces,'vertices',... + [-Savg.(side{si}).vertices(:,1),FSavg.(side{si}).vertices(:,2:3)])),filename{si,smi}); + cmd = sprintf('CAT_BlurSurfHK ""%s"" ""%s"" %d',filename{si,smi},filename{si,smi},job.meshsmooth(smi)); + cat_system(cmd,0); + + save(gifti(struct('vertices',Savg.(side{si}).vertices,'faces',... + [FSavg.(side{si}).faces(:,2),FSavg.(side{si}).faces(:,1),FSavg.(side{si}).faces(:,3)])),filename{si+1,smi}); + cmd = sprintf('CAT_BlurSurfHK ""%s"" ""%s"" %d',filename{si+1,smi},filename{si+1,smi},job.meshsmooth(smi)); + cat_system(cmd,0); + end + nfi = nfi + 1; cat_progress_bar('Set',nfi); + end + end + end + + if nargout>0 + varargout{1} = filename{si,smi}; + end + + cat_progress_bar('Clear'); +end + +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_vol_interp3f.cpp",".cpp","31106","726","// Fast nearest, bi-linear and bi-cubic interpolation for 3d image data on a regular grid. +// +// Usage: +// ------ +// R = ba_interp3(F, X, Y, Z, [method]) +// R = ba_interp3(Fx, Fy, Fz, F, X, Y, Z, [method]) +// +// where method is one off nearest, linear, or cubic. +// +// Fx, Fy, Fz +// are the coordinate system in which F is given. Only the first and +// last entry in Fx, Fy, Fz are used, and it is assumed that the +// inbetween values are linearly interpolated. +// F is a WxHxDxC Image with an arbitray number of channels C. +// X, Y, Z are I_1 x ... x I_n matrices with the x and y coordinates to +// interpolate. +// R is a I_1 x ... x I_n x C matrix, which contains the interpolated image channels. +// +// Notes: +// ------ +// This method handles the border by repeating the closest values to the point accessed. +// This is different from matlabs border handling. +// +// Example +// ------ +// +// %% Interpolation of 3D volumes (e.g. distance transforms) +// clear +// sz=5; +// +// % Dist +// dist1.D = randn(sz,sz,sz); +// [dist1.x dist1.y dist.z] = meshgrid(linspace(-1,1,sz), linspace(-1,1,sz), linspace(-1,1,sz)); +// +// R = [cos(pi/4) sin(pi/4); -sin(pi/4) cos(pi/4)]; +// RD = R * [Dx(:)'; Dy(:)'] + 250; +// RDx = reshape(RD(1,:), size(Dx)); +// RDy = reshape(RD(2,:), size(Dy)); +// +// methods = {'nearest', 'linear', 'cubic'}; +// la=nan(1,3); +// for i=1:3 +// la(i) = subplot(2,2,i); +// tic; +// IMG_R = ba_interp2(IMG, RDx, RDy, methods{i}); +// elapsed=toc; +// imshow(IMG_R); +// title(sprintf('Rotation and zoom using %s interpolation took %gs', methods{i}, elapsed)); +// end +// linkaxes(la); +// +// Licence: +// -------- +// GPL +// (c) 2008 Brian Amberg +// http://www.brian-amberg.de/ + +#include +#include +#include +#include +#include + +#ifndef ROUND +#define ROUND( x ) ((long) ((x) + ( ((x) >= 0) ? 0.5 : (-0.5) ) )) +#endif + +inline +static +int access(int M, int N, int O, int x, int y, int z) { + if (x<0) x=0; else if (x>=N) x=N-1; + if (y<0) y=0; else if (y>=M) y=M-1; + if (z<0) z=0; else if (z>=O) z=O-1; + return y + M*(x + N*z); +} + +inline +static +int access_unchecked(int M, int N, int O, int x, int y, int z) { + return y + M*(x + N*z); +} + +inline +static +void indices_linear( + int &f000_i, + int &f100_i, + int &f010_i, + int &f110_i, + int &f001_i, + int &f101_i, + int &f011_i, + int &f111_i, + const int x, const int y, const int z, + const mwSize &M, const mwSize &N, const mwSize &O) { + if (x<=1 || y<=1 || z<=1 || x>=N-2 || y>=M-2 || z>=O-2) { + f000_i = access(M,N,O, x, y , z); + f100_i = access(M,N,O, x+1, y , z); + + f010_i = access(M,N,O, x, y+1, z); + f110_i = access(M,N,O, x+1, y+1, z); + + f001_i = access(M,N,O, x, y , z+1); + f101_i = access(M,N,O, x+1, y , z+1); + + f011_i = access(M,N,O, x, y+1, z+1); + f111_i = access(M,N,O, x+1, y+1, z+1); + } else { + f000_i = access_unchecked(M,N,O, x, y , z); + f100_i = access_unchecked(M,N,O, x+1, y , z); + + f010_i = access_unchecked(M,N,O, x, y+1, z); + f110_i = access_unchecked(M,N,O, x+1, y+1, z); + + f001_i = access_unchecked(M,N,O, x, y , z+1); + f101_i = access_unchecked(M,N,O, x+1, y , z+1); + + f011_i = access_unchecked(M,N,O, x, y+1, z+1); + f111_i = access_unchecked(M,N,O, x+1, y+1, z+1); + } +} + +inline +static +void indices_cubic( + int f_i[64], + const int x, const int y, const int z, + const mwSize &M, const mwSize &N, const mwSize &O) { + if (x<=2 || y<=2 || z<=2 || x>=N-3 || y>=M-3 || z>=O-3) { + for (int i=0; i<4; ++i) + for (int j=0; j<4; ++j) + for (int k=0; k<4; ++k) + f_i[i+4*(j+4*k)] = access(M,N,O, x+i-1, y+j-1, z+k-1); + } else { + for (int i=0; i<4; ++i) + for (int j=0; j<4; ++j) + for (int k=0; k<4; ++k) + f_i[i+4*(j+4*k)] = access_unchecked(M,N,O, x+i-1, y+j-1, z+k-1); + } +} + + +static +void interpolate_nearest(float *pO, const float *pF, + const float *pX, const float *pY, const float *pZ, + const mwSize ND, const mwSize M, const mwSize N, const mwSize O, const mwSize P, + const float s_x, const float o_x, + const float s_y, const float o_y, + const float s_z, const float o_z) { + const mwSize LO = M*N*O; + for (mwSize i=0; i +static +void interpolate_nearest_unrolled(float *pO, const float *pF, + const float *pX, const float *pY, const float *pZ, + const mwSize ND, const mwSize M, const mwSize N, const mwSize O, + const float s_x, const float o_x, + const float s_y, const float o_y, + const float s_z, const float o_z) { + const mwSize LO = M*N*O; + for (mwSize i=0; i +static +void interpolate_linear_unrolled(float *pO, const float *pF, + const float *pX, const float *pY, const float *pZ, + const mwSize ND, const mwSize M, const mwSize N, const mwSize O, + const float s_x, const float o_x, + const float s_y, const float o_y, + const float s_z, const float o_z) { + const mwSize LO = M*N*O; + for (mwSize i=0; i +static +void interpolate_bicubic_unrolled(float *pO, const float *pF, + const float *pX, const float *pY, const float *pZ, + const mwSize ND, const mwSize M, const mwSize N, const mwSize O, + const float s_x, const float o_x, + const float s_y, const float o_y, + const float s_z, const float o_z) { + const mwSize LO = M*N*O; + for (mwSize i=0; i1) + mexErrMsgTxt(""Wrong number of output arguments for Z = ba_interp3(Fx, Fy, Fz, F, X, Y, Z, method)""); + + const mxArray *Fx = NULL; + const mxArray *Fy = NULL; + const mxArray *Fz = NULL; + const mxArray *F = NULL; + const mxArray *X = NULL; + const mxArray *Y = NULL; + const mxArray *Z = NULL; + const mxArray *method = NULL; + + if (nrhs==4) { + // ba_interp(F, X, Y, Z); + F = prhs[0]; + X = prhs[1]; + Y = prhs[2]; + Z = prhs[3]; + } else if (nrhs==5) { + // ba_interp(F, X, Y, Z, 'method'); + F = prhs[0]; + X = prhs[1]; + Y = prhs[2]; + Z = prhs[3]; + method = prhs[4]; + } else if (nrhs==7) { + // ba_interp(Fx, Fy, Fz, F, X, Y, Z); + Fx= prhs[0]; + Fy= prhs[1]; + Fz= prhs[2]; + F = prhs[3]; + X = prhs[4]; + Y = prhs[5]; + Z = prhs[6]; + method = prhs[4]; + } else if (nrhs==8) { + // ba_interp(Fx, Fy, Fz, F, X, Y, Z, 'method'); + Fx= prhs[0]; + Fy= prhs[1]; + Fz= prhs[2]; + F = prhs[3]; + X = prhs[4]; + Y = prhs[5]; + Z = prhs[6]; + method = prhs[7]; + } else { + mexErrMsgTxt(""Wrong number of input arguments for Z = ba_interp3(Fx, Fy, Fz, F, X, Y, Z, method)""); + } + if ((Fx && !mxIsSingle(Fx)) ||(Fy && !mxIsSingle(Fy)) ||(Fz && !mxIsSingle(Fz)) || + (F && !mxIsSingle(F)) || + (X && !mxIsSingle(X)) || (Y && !mxIsSingle(Y)) || (Z && !mxIsSingle(Z))) + mexErrMsgTxt(""ba_interp3 takes only float arguments for Fx,Fy,Fz,F,X,Y,Z""); + + const mwSize *F_dims = mxGetDimensions(F); + const mwSize *X_dims = mxGetDimensions(X); + const mwSize *Y_dims = mxGetDimensions(Y); + const mwSize *Z_dims = mxGetDimensions(Z); + + const mwSize M=F_dims[0]; + const mwSize N=F_dims[1]; + const mwSize O=F_dims[2]; + + if (Fx && mxGetNumberOfElements(Fx)<2) mexErrMsgTxt(""Fx needs at least two elements.""); + if (Fy && mxGetNumberOfElements(Fy)<2) mexErrMsgTxt(""Fy needs at least two elements.""); + if (Fz && mxGetNumberOfElements(Fz)<2) mexErrMsgTxt(""Fz needs at least two elements.""); + + if ((mxGetNumberOfDimensions(X) != mxGetNumberOfDimensions(Y)) || + (mxGetNumberOfDimensions(X) != mxGetNumberOfDimensions(Z)) || + (mxGetNumberOfElements(X) != mxGetNumberOfElements(Y)) || + (mxGetNumberOfElements(X) != mxGetNumberOfElements(Z))) + mexErrMsgTxt(""X, Y, Z should have the same size""); + + mwSize P=1; + + mwSize outDims[50]; + if (mxGetNumberOfDimensions(X) + mxGetNumberOfDimensions(F) - 3 > 50) + mexErrMsgTxt(""Can't have that many dimensions in interpolated data.""); + + for (mwSize i=0; i(pO, pF, pX, pY, pZ, ND, M, N, O, s_x, o_x, s_y, o_y, s_z, o_z); break; + case 2: interpolate_nearest_unrolled<2>(pO, pF, pX, pY, pZ, ND, M, N, O, s_x, o_x, s_y, o_y, s_z, o_z); break; + case 3: interpolate_nearest_unrolled<3>(pO, pF, pX, pY, pZ, ND, M, N, O, s_x, o_x, s_y, o_y, s_z, o_z); break; + case 4: interpolate_nearest_unrolled<4>(pO, pF, pX, pY, pZ, ND, M, N, O, s_x, o_x, s_y, o_y, s_z, o_z); break; + case 5: interpolate_nearest_unrolled<5>(pO, pF, pX, pY, pZ, ND, M, N, O, s_x, o_x, s_y, o_y, s_z, o_z); break; + case 6: interpolate_nearest_unrolled<6>(pO, pF, pX, pY, pZ, ND, M, N, O, s_x, o_x, s_y, o_y, s_z, o_z); break; + case 7: interpolate_nearest_unrolled<7>(pO, pF, pX, pY, pZ, ND, M, N, O, s_x, o_x, s_y, o_y, s_z, o_z); break; + case 8: interpolate_nearest_unrolled<8>(pO, pF, pX, pY, pZ, ND, M, N, O, s_x, o_x, s_y, o_y, s_z, o_z); break; + case 9: interpolate_nearest_unrolled<9>(pO, pF, pX, pY, pZ, ND, M, N, O, s_x, o_x, s_y, o_y, s_z, o_z); break; + default: + interpolate_nearest(pO, pF, pX, pY, pZ, ND, M, N, O, P, s_x, o_x, s_y, o_y, s_z, o_z); + } + break; + case Linear: + switch (P) { + case 1: interpolate_linear_unrolled<1>(pO, pF, pX, pY, pZ, ND, M, N, O, s_x, o_x, s_y, o_y, s_z, o_z); break; + case 2: interpolate_linear_unrolled<2>(pO, pF, pX, pY, pZ, ND, M, N, O, s_x, o_x, s_y, o_y, s_z, o_z); break; + case 3: interpolate_linear_unrolled<3>(pO, pF, pX, pY, pZ, ND, M, N, O, s_x, o_x, s_y, o_y, s_z, o_z); break; + case 4: interpolate_linear_unrolled<4>(pO, pF, pX, pY, pZ, ND, M, N, O, s_x, o_x, s_y, o_y, s_z, o_z); break; + case 5: interpolate_linear_unrolled<5>(pO, pF, pX, pY, pZ, ND, M, N, O, s_x, o_x, s_y, o_y, s_z, o_z); break; + case 6: interpolate_linear_unrolled<6>(pO, pF, pX, pY, pZ, ND, M, N, O, s_x, o_x, s_y, o_y, s_z, o_z); break; + case 7: interpolate_linear_unrolled<7>(pO, pF, pX, pY, pZ, ND, M, N, O, s_x, o_x, s_y, o_y, s_z, o_z); break; + case 8: interpolate_linear_unrolled<8>(pO, pF, pX, pY, pZ, ND, M, N, O, s_x, o_x, s_y, o_y, s_z, o_z); break; + case 9: interpolate_linear_unrolled<9>(pO, pF, pX, pY, pZ, ND, M, N, O, s_x, o_x, s_y, o_y, s_z, o_z); break; + default: + interpolate_linear(pO, pF, pX, pY, pZ, ND, M, N, O, P, s_x, o_x, s_y, o_y, s_z, o_z); + } + break; + case Cubic: + switch (P) { + case 1: interpolate_bicubic_unrolled<1>(pO, pF, pX, pY, pZ, ND, M, N, O, s_x, o_x, s_y, o_y, s_z, o_z); break; + case 2: interpolate_bicubic_unrolled<2>(pO, pF, pX, pY, pZ, ND, M, N, O, s_x, o_x, s_y, o_y, s_z, o_z); break; + case 3: interpolate_bicubic_unrolled<3>(pO, pF, pX, pY, pZ, ND, M, N, O, s_x, o_x, s_y, o_y, s_z, o_z); break; + case 4: interpolate_bicubic_unrolled<4>(pO, pF, pX, pY, pZ, ND, M, N, O, s_x, o_x, s_y, o_y, s_z, o_z); break; + case 5: interpolate_bicubic_unrolled<5>(pO, pF, pX, pY, pZ, ND, M, N, O, s_x, o_x, s_y, o_y, s_z, o_z); break; + case 6: interpolate_bicubic_unrolled<6>(pO, pF, pX, pY, pZ, ND, M, N, O, s_x, o_x, s_y, o_y, s_z, o_z); break; + case 7: interpolate_bicubic_unrolled<7>(pO, pF, pX, pY, pZ, ND, M, N, O, s_x, o_x, s_y, o_y, s_z, o_z); break; + case 8: interpolate_bicubic_unrolled<8>(pO, pF, pX, pY, pZ, ND, M, N, O, s_x, o_x, s_y, o_y, s_z, o_z); break; + case 9: interpolate_bicubic_unrolled<9>(pO, pF, pX, pY, pZ, ND, M, N, O, s_x, o_x, s_y, o_y, s_z, o_z); break; + default: + interpolate_bicubic(pO, pF, pX, pY, pZ, ND, M, N, O, P, s_x, o_x, s_y, o_y, s_z, o_z); + } + break; + default: + mexErrMsgTxt(""Unimplemented interpolation method.""); + } + } else { + switch(parseInterpolationMethod(method)) { + case Nearest: + switch (P) { + case 1: interpolate_nearest_unrolled<1>(pO, pF, pX, pY, pZ, ND, M, N, O, float(1), float(0), float(1), float(0), float(1), float(0)); break; + case 2: interpolate_nearest_unrolled<2>(pO, pF, pX, pY, pZ, ND, M, N, O, float(1), float(0), float(1), float(0), float(1), float(0)); break; + case 3: interpolate_nearest_unrolled<3>(pO, pF, pX, pY, pZ, ND, M, N, O, float(1), float(0), float(1), float(0), float(1), float(0)); break; + case 4: interpolate_nearest_unrolled<4>(pO, pF, pX, pY, pZ, ND, M, N, O, float(1), float(0), float(1), float(0), float(1), float(0)); break; + case 5: interpolate_nearest_unrolled<5>(pO, pF, pX, pY, pZ, ND, M, N, O, float(1), float(0), float(1), float(0), float(1), float(0)); break; + case 6: interpolate_nearest_unrolled<6>(pO, pF, pX, pY, pZ, ND, M, N, O, float(1), float(0), float(1), float(0), float(1), float(0)); break; + case 7: interpolate_nearest_unrolled<7>(pO, pF, pX, pY, pZ, ND, M, N, O, float(1), float(0), float(1), float(0), float(1), float(0)); break; + case 8: interpolate_nearest_unrolled<8>(pO, pF, pX, pY, pZ, ND, M, N, O, float(1), float(0), float(1), float(0), float(1), float(0)); break; + case 9: interpolate_nearest_unrolled<9>(pO, pF, pX, pY, pZ, ND, M, N, O, float(1), float(0), float(1), float(0), float(1), float(0)); break; + default: + interpolate_nearest(pO, pF, pX, pY, pZ, ND, M, N, O, P, float(1), float(0), float(1), float(0), float(1), float(0)); + } + break; + case Linear: + switch (P) { + case 1: interpolate_linear_unrolled<1>(pO, pF, pX, pY, pZ, ND, M, N, O, float(1), float(0), float(1), float(0), float(1), float(0)); break; + case 2: interpolate_linear_unrolled<2>(pO, pF, pX, pY, pZ, ND, M, N, O, float(1), float(0), float(1), float(0), float(1), float(0)); break; + case 3: interpolate_linear_unrolled<3>(pO, pF, pX, pY, pZ, ND, M, N, O, float(1), float(0), float(1), float(0), float(1), float(0)); break; + case 4: interpolate_linear_unrolled<4>(pO, pF, pX, pY, pZ, ND, M, N, O, float(1), float(0), float(1), float(0), float(1), float(0)); break; + case 5: interpolate_linear_unrolled<5>(pO, pF, pX, pY, pZ, ND, M, N, O, float(1), float(0), float(1), float(0), float(1), float(0)); break; + case 6: interpolate_linear_unrolled<6>(pO, pF, pX, pY, pZ, ND, M, N, O, float(1), float(0), float(1), float(0), float(1), float(0)); break; + case 7: interpolate_linear_unrolled<7>(pO, pF, pX, pY, pZ, ND, M, N, O, float(1), float(0), float(1), float(0), float(1), float(0)); break; + case 8: interpolate_linear_unrolled<8>(pO, pF, pX, pY, pZ, ND, M, N, O, float(1), float(0), float(1), float(0), float(1), float(0)); break; + case 9: interpolate_linear_unrolled<9>(pO, pF, pX, pY, pZ, ND, M, N, O, float(1), float(0), float(1), float(0), float(1), float(0)); break; + default: + interpolate_linear(pO, pF, pX, pY, pZ, ND, M, N, O, P, float(1), float(0), float(1), float(0), float(1), float(0)); + } + break; + case Cubic: + switch (P) { + case 1: interpolate_bicubic_unrolled<1>(pO, pF, pX, pY, pZ, ND, M, N, O, float(1), float(0), float(1), float(0), float(1), float(0)); break; + case 2: interpolate_bicubic_unrolled<2>(pO, pF, pX, pY, pZ, ND, M, N, O, float(1), float(0), float(1), float(0), float(1), float(0)); break; + case 3: interpolate_bicubic_unrolled<3>(pO, pF, pX, pY, pZ, ND, M, N, O, float(1), float(0), float(1), float(0), float(1), float(0)); break; + case 4: interpolate_bicubic_unrolled<4>(pO, pF, pX, pY, pZ, ND, M, N, O, float(1), float(0), float(1), float(0), float(1), float(0)); break; + case 5: interpolate_bicubic_unrolled<5>(pO, pF, pX, pY, pZ, ND, M, N, O, float(1), float(0), float(1), float(0), float(1), float(0)); break; + case 6: interpolate_bicubic_unrolled<6>(pO, pF, pX, pY, pZ, ND, M, N, O, float(1), float(0), float(1), float(0), float(1), float(0)); break; + case 7: interpolate_bicubic_unrolled<7>(pO, pF, pX, pY, pZ, ND, M, N, O, float(1), float(0), float(1), float(0), float(1), float(0)); break; + case 8: interpolate_bicubic_unrolled<8>(pO, pF, pX, pY, pZ, ND, M, N, O, float(1), float(0), float(1), float(0), float(1), float(0)); break; + case 9: interpolate_bicubic_unrolled<9>(pO, pF, pX, pY, pZ, ND, M, N, O, float(1), float(0), float(1), float(0), float(1), float(0)); break; + default: + interpolate_bicubic(pO, pF, pX, pY, pZ, ND, M, N, O, P, float(1), float(0), float(1), float(0), float(1), float(0)); + } + break; + default: + mexErrMsgTxt(""Unimplemented interpolation method.""); + } + } +} +","C++" +"Neurology","ChristianGaser/cat12","cat_batch_cat.sh",".sh","19549","635","#! /bin/bash +# Call CAT12 standard pipeline from shell +# ______________________________________________________________________ +# +# Christian Gaser, Robert Dahnke +# Structural Brain Mapping Group (https://neuro-jena.github.io) +# Departments of Neurology and Psychiatry +# Jena University Hospital +# ______________________________________________________________________ +# $Id$ + +######################################################## +# global parameters +######################################################## + +matlab=matlab # you can use other matlab versions by changing the matlab parameter +cwd=$(dirname ""$0"") +cat12_dir=$cwd +spm12=$(dirname ""$cwd"") +spm12=$(dirname ""$spm12"") +LOGDIR=$PWD +CPUINFO=/proc/cpuinfo +ARCH=`uname` +time=`date ""+%Y%b%d_%H%M""` +nicelevel=0 +defaults_tmp=/tmp/defaults$$.m +no_mwp=0 +no_surf=0 +rp=0 +TEST=0 +fg=0 +bids=0 +bids_folder= +nojvm="""" +NUMBER_OF_JOBS=-1 + +######################################################## +# run main +######################################################## + +main () +{ + parse_args ${1+""$@""} + check_matlab + check_files + get_no_of_cpus + modifiy_defaults + run_cat12 + + exit 0 +} + + +######################################################## +# check arguments and files +######################################################## + +parse_args () +{ + local optname optarg + count=0 + + if [ $# -lt 1 ]; then + help + exit 1 + fi + + while [ $# -gt 0 ]; do + optname=""`echo $1 | sed 's,=.*,,'`"" + optarg=""`echo $2`"" + paras=""$paras $optname $optarg"" + case ""$1"" in + --matlab* | -m*) + exit_if_empty ""$optname"" ""$optarg"" + matlab=$optarg + shift + ;; + --defaults* | -d*) + exit_if_empty ""$optname"" ""$optarg"" + defaults=$optarg + shift + ;; + --nprocesses* | -np*) + exit_if_empty ""$optname"" ""$optarg"" + NUMBER_OF_JOBS=""-$optarg"" + shift + ;; + --processes* | -p*) + exit_if_empty ""$optname"" ""$optarg"" + NUMBER_OF_JOBS=$optarg + shift + ;; + --logdir* | -l*) + exit_if_empty ""$optname"" ""$optarg"" + LOGDIR=$optarg + if [ ! -d $LOGDIR ]; then + mkdir -p $LOGDIR + fi + shift + ;; + --no-mwp* | -nm*) + exit_if_empty ""$optname"" ""$optarg"" + no_mwp=1 + ;; + --no-surf* | -ns*) + exit_if_empty ""$optname"" ""$optarg"" + no_surf=1 + ;; + --rp* | -r*) + exit_if_empty ""$optname"" ""$optarg"" + rp=1 + ;; + --nojvm | -nj) + exit_if_empty ""$optname"" ""$optarg"" + nojvm="" -nojvm "" + ;; + --no-overwrite* | -no*) + exit_if_empty ""$optname"" ""$optarg"" + no_overwrite=$optarg + shift + ;; + --n* | -n* | --nice* | -nice*) + exit_if_empty ""$optname"" ""$optarg"" + nicelevel=$optarg + shift + ;; + --add* | -a*) + exit_if_empty ""$optname"" ""$optarg"" + add_to_defaults=""$optarg"" + shift + ;; + --fg* | -fg*) + exit_if_empty ""$optname"" ""$optarg"" + fg=1 + ;; + --files* | -f*) + exit_if_empty ""$optname"" ""$optarg"" + listfile=$optarg + shift + list=$(< $listfile); + for F in $list; do + ARRAY[$count]=$F + ((count++)) + done + ;; + --bids_folder* | --bids-folder* | -bf*) + exit_if_empty ""$optname"" ""$optarg"" + bids_folder=$optarg + shift + ;; + --b* | -b*) + exit_if_empty ""$optname"" ""$optarg"" + bids=1 + ;; + --s* | -s* | --shell* | -shell*) + exit_if_empty ""$optname"" ""$optarg"" + shellcommand=$optarg + shift + ;; + --tpm* | -tpm*) + exit_if_empty ""$optname"" ""$optarg"" + tpm=$optarg + shift + ;; + --test* | -t*) + TEST=1 + ;; + --c* | -c* | --command* | -command*) + exit_if_empty ""$optname"" ""$optarg"" + matlabcommand=$optarg + shift + ;; + -h | --help | -v | --version | -V) + help + exit 1 + ;; + -*) + echo ""`basename $0`: ERROR: Unrecognized option \""$1\"""" >&2 + ;; + *) + ARRAY[$count]=$1 + ((count++)) + ;; + esac + shift + done +} + +######################################################## +# check arguments +######################################################## + +exit_if_empty () +{ + local desc val + + desc=""$1"" + shift + val=""$*"" + + if [ ! -n ""$val"" ]; then + echo 'ERROR: No argument given with \""$desc\"" command line argument!' >&2 + exit 1 + fi +} + +######################################################## +# check files +######################################################## + +check_files () +{ + + if [ ""$no_surf"" -eq 1 ] && [ ""$no_mwp"" -eq 1 ] && [ ""$rp"" -eq 0 ]; then + echo 'WARNING: You have deselected all outputs! Only the p0-image is saved.' >&2 + fi + + SIZE_OF_ARRAY=""${#ARRAY[@]}"" + if [ ""$SIZE_OF_ARRAY"" -eq 0 ]; then + echo 'ERROR: No files given!' >&2 + help + exit 1 + fi + + i=0 + while [ ""$i"" -lt ""$SIZE_OF_ARRAY"" ]; do + if [ ! -f ""${ARRAY[$i]}"" ]; then + if [ ! -L ""${ARRAY[$i]}"" ]; then + echo ERROR: File ${ARRAY[$i]} not found + help + exit 1 + fi + fi + ((i++)) + done + +} + +######################################################## +# get # of cpus +######################################################## +# modified code from +# PPSS, the Parallel Processing Shell Script +# +# Copyright (c) 2009, Louwrentius +# All rights reserved. + +get_no_of_cpus () { + + if [ ! -n ""$NUMBER_OF_JOBS"" ] | [ $NUMBER_OF_JOBS -le -1 ]; then + if [ ""$ARCH"" == ""Linux"" ]; then + NUMBER_OF_PROC=`grep ^processor $CPUINFO | wc -l` + elif [ ""$ARCH"" == ""Darwin"" ]; then + NUMBER_OF_PROC=`sysctl -a hw | grep -w hw.logicalcpu | awk '{ print $2 }'` + elif [ ""$ARCH"" == ""FreeBSD"" ]; then + NUMBER_OF_PROC=`sysctl hw.ncpu | awk '{ print $2 }'` + else + NUMBER_OF_PROC=`grep ^processor $CPUINFO | wc -l` + fi + + if [ ! -n ""$NUMBER_OF_PROC"" ]; then + echo ""$FUNCNAME ERROR - number of CPUs not obtained. Use -p to define number of processes."" + exit 1 + fi + + # use all processors if not defined otherwise + if [ ! -n ""$NUMBER_OF_JOBS"" ]; then + NUMBER_OF_JOBS=$NUMBER_OF_PROC + fi + + if [ $NUMBER_OF_JOBS -le -1 ]; then + NUMBER_OF_JOBS=$(echo ""$NUMBER_OF_PROC + $NUMBER_OF_JOBS"" | bc) + if [ ""$NUMBER_OF_JOBS"" -lt 1 ]; then + NUMBER_OF_JOBS=1 + fi + fi + if [ ""$NUMBER_OF_JOBS"" -gt ""$NUMBER_OF_PROC"" ]; then + NUMBER_OF_JOBS=$NUMBER_OF_PROC + fi + echo ""Found $NUMBER_OF_PROC processors. Use $NUMBER_OF_JOBS."" + echo + fi +} + +######################################################## +# modify defaults +######################################################## + +modifiy_defaults () +{ + + pwd=$PWD + + # argument empty? + if [ -n ""${defaults}"" ]; then + # check whether absolute or relative names were given + if [ -f ""${pwd}/${defaults}"" ]; then + defaults=""${pwd}/${defaults}"" + fi + + # check whether defaults file exist + if [ ! -f ""${defaults}"" ]; then + echo Default file ""$defaults"" not found. + exit + fi + else + defaults=${cat12_dir}/cat_defaults.m + fi + + cp ${defaults} ${defaults_tmp} + + if [ ""$no_surf"" -eq 1 ]; then + echo ""cat.output.surface = 0;"" >> ${defaults_tmp} + else + echo ""cat.output.surface = 1;"" >> ${defaults_tmp} + fi + + if [ ""$no_mwp"" -eq 1 ]; then + echo ""cat.output.GM.mod = 0;"" >> ${defaults_tmp} + echo ""cat.output.WM.mod = 0;"" >> ${defaults_tmp} + echo ""cat.output.ROI = 0;"" >> ${defaults_tmp} + echo ""cat.output.bias.warped = 0;"" >> ${defaults_tmp} + echo ""cat.output.warps = [0 0];"" >> ${defaults_tmp} + else + echo ""cat.output.GM.mod = 1;"" >> ${defaults_tmp} + echo ""cat.output.WM.mod = 1;"" >> ${defaults_tmp} + echo ""cat.output.ROI = 1;"" >> ${defaults_tmp} + fi + + if [ ""$rp"" -eq 1 ]; then + echo ""cat.output.GM.dartel = 2;"" >> ${defaults_tmp} + echo ""cat.output.WM.dartel = 2;"" >> ${defaults_tmp} + fi + + if [ -n ""$bids_folder"" ]; then + echo ""cat.extopts.bids_folder = '${bids_folder}';"" >> ${defaults_tmp} + echo ""cat.extopts.bids_yes = 1;"" >> ${defaults_tmp} + fi + + if [ ""$bids"" -eq 1 ]; then + echo ""cat.extopts.bids_yes = 1;"" >> ${defaults_tmp} + fi + + if [ -n ""$tpm"" ]; then + # check whether absolute or relative tpm was given + if [ -f ""${pwd}/${tpm}"" ]; then + tpm=""${pwd}/${tpm}"" + fi + echo ""cat.opts.tpm = {'${tpm}'};"" >> ${defaults_tmp} + fi + + if [ -n ""$add_to_defaults"" ]; then + echo ""${add_to_defaults}"" >> ${defaults_tmp} + fi + +} + +######################################################## +# run cat12 +######################################################## + +run_cat12 () +{ + pwd=$PWD + + # we have to go into the toolbox folder to find matlab files + cd $cwd + + if [ ! -n ""${LOGDIR}"" ]; then + LOGDIR=$(dirname ""${ARRAY[0]}"") + fi + + # we have to add current path if cat_batch_cat.sh was called from relative path + if [ -d ${pwd}/${spm12} ]; then + spm12=${pwd}/${spm12} + fi + + export MATLABPATH=${spm12} + + SIZE_OF_ARRAY=""${#ARRAY[@]}"" + + i=0 + j=0 + while [ ""$i"" -lt ""$SIZE_OF_ARRAY"" ]; do + + # check whether absolute or relative names were given + if [ ! -f ""${ARRAY[$i]}"" ]; then + if [ -f ""${pwd}/${ARRAY[$i]}"" ]; then + FILE=""${pwd}/${ARRAY[$i]}"" + fi + else + FILE=${ARRAY[$i]} + fi + + # replace white spaces + FILE=$(echo ""$FILE"" | sed -e 's/ /\\ /g') + + # check whether processed files exist if no-overwrite flag is used + if [ -n ""${no_overwrite}"" ]; then + dn=$(dirname ""$FILE"") + bn=$(basename ""$FILE"" |cut -f1 -d'.') + processed=`eval ls ""${dn}/${no_overwrite}${bn}*"" 2>/dev/null` + fi + + if [ ! -n ""${processed}"" ]; then + if [ ! -n ""${ARG_LIST[$i]}"" ]; then + ARRAY2[$j]=""$FILE"" + else + ARRAY2[$j]=""${ARRAY2[$i]} $FILE"" + fi + ((j++)) + else + echo Skip processing of ${FILE} + fi + ((i++)) + done + + SIZE_OF_ARRAY=""${#ARRAY2[@]}"" + BLOCK=$((10000* $SIZE_OF_ARRAY / $NUMBER_OF_JOBS )) + ARG_LIST="""" + + # split files and prepare tmp-file with filenames + TMP=/tmp/cat_$$ + i=0 + while [ ""$i"" -lt ""$SIZE_OF_ARRAY"" ]; do + count=$((10000* $i / $BLOCK )) + + FILE=""${ARRAY2[$i]}"" + + ARG_LIST[$count]=""${ARG_LIST[$count]} '$FILE'"" + + # filenames have to be quoted in case of any whitespaces + if [ ""$TEST"" -eq 0 ]; then + echo '""'${FILE}'""' >> ${TMP}${count} + else + echo ${FILE} + fi + ((i++)) + done + vbmlog=""${LOGDIR}/cat_${HOSTNAME}_${time}"" + + # if relative foldername were given we have to add the data folder because we change into cat12 folder + if [ ! -d ${LOGDIR} ]; then + vbmlog=${pwd}/${vbmlog} + fi + + i=0 + while [ ""$i"" -lt ""$NUMBER_OF_JOBS"" ]; do + if [ -n ""${ARG_LIST[$i]}"" ] && [ ""$TEST"" -eq 0 ]; then + j=$(($i+1)) + if [ ! -n ""$matlabcommand"" ]; then + COMMAND=""cat_batch_cat('${TMP}${i}','${defaults_tmp}')"" + else + for F in ${ARG_LIST[$i]} ; do + CFILES=$CFILES"",""\'$F\'; + done + CFILES=$(echo $CFILES | cut -c 2-); + matlabcommand2=$matlabcommand + matlabcommand2=$(echo $matlabcommand2 |sed 's/CFILES/$CFILES/g'); + eval ""COMMAND=\""$matlabcommand2\"";"" + COMMAND=""try, spm; spm_get_defaults; cat_get_defaults; global defaults cat matlabbatch; $COMMAND; catch caterr, sprintf('\n%s\nVBM Preprocessing error: %s:\n%s\n', repmat('-',1,72),caterr.identifier,caterr.message,repmat('-',1,72)); for si=1:numel(caterr.stack), cat_io_cprintf('err',sprintf('%5d - %s\n',caterr.stack(si).line,caterr.stack(si).name)); end; cat_io_cprintf('err',sprintf('%s\\n',repmat('-',1,72))); exit; end; fprintf('VBM batch processing done.'); exit;""; + fi + SHCOMMAND=""$shellcommand ${ARG_LIST[$i]}"" + + echo Calculate + for F in ${ARG_LIST[$i]}; do echo $F; done + # File Output + echo > ""${vbmlog}_${j}.log"" + echo ---------------------------------- >> ""${vbmlog}_${j}.log"" + date >> ""${vbmlog}_${j}.log"" + echo ---------------------------------- >> ""${vbmlog}_${j}.log"" + echo >> ""${vbmlog}_${j}.log"" + echo Calling string of this batch: >> ""${vbmlog}_${j}.log"" + echo "" $0 $paras"" >> ""${vbmlog}_${j}.log"" + echo >> ""${vbmlog}_${j}.log"" + echo MATLAB command of this batch: >> ""${vbmlog}_${j}.log"" + echo "" $COMMAND"" >> ""${vbmlog}_${j}.log"" + echo >> ""${vbmlog}_${j}.log"" + if [ -n ""$shellcommand"" ]; then + echo Shell command of this batch: >> ""${vbmlog}_${j}.log"" + echo "" $SHCOMMAND"" >> ""${vbmlog}_${j}.log"" + echo >> ""${vbmlog}_${j}.log"" + fi + + if [ ! -n ""$shellcommand"" ]; then + # do nohup in background or not + if [ ""$fg"" -eq 0 ]; then + nohup nice -n $nicelevel ${matlab} -nodisplay ""$nojvm"" -nosplash -r ""$COMMAND"" >> ""${vbmlog}_${j}.log"" 2>&1 & + else + nohup nice -n $nicelevel ${matlab} -nodisplay ""$nojvm"" -nosplash -r ""$COMMAND"" >> ""${vbmlog}_${j}.log"" 2>&1 + fi + else + # do nohup in background or not + if [ ""$fg"" -eq 0 ]; then + nohup nice -n $nicelevel $SHCOMMAND >> ""${vbmlog}_${j}.log"" 2>&1 & + else + nohup nice -n $nicelevel $SHCOMMAND >> ""${vbmlog}_${j}.log"" 2>&1 + fi + fi + echo Check ""${vbmlog}_${j}.log"" for logging information + echo + fi + ((i++)) + done + + exit 0 +} + +######################################################## +# check if matlab exist +######################################################## + +check_matlab () +{ + found=`which ""${matlab}"" 2>/dev/null` + if [ ! -n ""$found"" ]; then + echo $matlab not found. + exit 1 + fi +} + +######################################################## +# help +######################################################## + +help () +{ + +get_no_of_cpus +cat <<__EOM__ + +USAGE: + cat_batch_cat.sh [-m matlab_command] [-d default_file] [-l log_folder] + [-p number_of_processes] [-tpm TPM-file] [-ns] [-nm] [-rp] [-no output_pattern] + [-n nicelevel] [-s shell_command -f files_for_shell] [-c matlab_command] + [-a add_to_defaults] [-t] [-fg] [-noj] filenames|filepattern + + -m | --matlab matlab command (matlab version) (default $matlab) + -d | --defaults optional default file (default ${cat12_dir}/cat_defaults.m) + -l | --logdir directory for log-file (default $LOGDIR) + -p | --processes number of parallel jobs (=number of processors) + (default $NUMBER_OF_JOBS) + -np | --nprocesses set number of jobs by number_of_processors - number_of_processes + (=number of free processors) + -tpm | --tpm define own TPM + -a | --add add option to default file + -ns | --no-surf skip surface and thickness estimation + -nm | --no-mwp skip estimating modulated and warped segmentations and ROI measures + -rp | --rp additionally estimate affine registered segmentations + -no | --no-overwrite do not overwrite existing results + -n | --nice nice level (default 0) + -s | --shell shell command to call other shell scripts + -f | --files files to process with shell command + -c | --command alternative matlab function that can be called such as the SANLM-filter + -t | --test do not call command, but print files to be processed + -fg | --fg do not run matlab process in background + -b | --bids use default BIDS path (i.e. 'derivatives/CAT12.x_rxxxx' at dataset root) + -bf | --bids_folder define BIDS path + -nj | --nojvm supress call of jvm using the -nojvm flag + + Only one filename or pattern is allowed. This can be either a single file or a pattern + with wildcards to process multiple files. + +PURPOSE: + Command line call of CAT12 segmentation + +EXAMPLE + cat_batch_cat.sh ${spm12}/canonical/single_subj_T1.nii + This command will process only the single file single_subj_T1.nii. + + cat_batch_cat.sh -d your_cat_defaults_file.m ${spm12}/canonical/single_subj_T1.nii + This command will process only the single file single_subj_T1.nii. The defaults defined + in your_cat_defaults_file.m is used instead of cat_defaults.m. + + cat_batch_cat.sh ${spm12}/canonical/*152*.nii + Using wildcards all files containing the term ""152"" are processed. In this case these + are the files avg152PD.nii, avg152T1.nii, and avg152T2.nii and $NUMBER_OF_JOBS parallel + jobs are used. + + cat_batch_cat.sh -no ""mri/mwp1"" ${spm12}/canonical/*152*.nii + Using wildcards all files containing the term ""152"" are processed. In this case these + are the files avg152PD.nii, avg152T1.nii, and avg152T2.nii and $NUMBER_OF_JOBS parallel + jobs are used. If processed files ""mwp1*"" in the subfolder ""mri"" are + found the processing will be skipped. + + cat_batch_cat.sh -p 2 -m /usr/local/bin/matlab7 ${spm12}/canonical/*152*.nii + Using wildcards all files containing the term ""152"" are processed. In this case these + are the files avg152PD.nii, avg152T1.nii, and avg152T2.nii and 2 parallel jobs + jobs are used. As matlab-command /usr/local/bin/matlab7 is used. + + cat_batch_cat.sh -ns -nm -rp -a ""cat.extopts.WMHC = 3;"" ${spm12}/canonical/single_subj_T1.nii + This command will process only the single file single_subj_T1.nii with the defaults in cat_defaults.m and + the additional option for handling WMHs as separate class. No surfaces and modulated and warped segmentations + are estimated. Only the affine registered segmentations are saved. + + cat_batch_cat.sh -bids_folder derivatives/CAT12.8 sub*/anat/sub*T1w.nii.gz + This command will process all *.nii.gz files in the BIDS subfolders sub* with the defaults in cat_defaults.m and + will save the results as BIDS structure in 'derivatives/CAT12.8' at the dataset root (one level above the subject folders). If the option for bids_folder is not given the + default BIDS path is 'derivatives/CAT12.x_rxxxx' where the CAT12 version is used in the path. + + cat_batch_cat.sh -tpm ${cat12_dir}/templates_MNI152NLin2009cAsym/TPM_Age11.5.nii ${spm12}/canonical/single_subj_T1.nii + This command will process only the single file single_subj_T1.nii with the defaults in cat_defaults.m + and the children template that is provided with cat12. + + cat_batch_cat.sh -p 2 -c ""cat_vol_sanlm(struct('data',char(CFILES),'prefix','sanlm_'))"" /Volumes/4TBWD/raw-cg/r[12][0-9][0-9][0-9]*.nii + This command will call the SANLM-filter using the given files, that have to be indicated with CFILES + as first argument. As prefix 'sanlm_' is used. + + +INPUT: + analyze or nifti files + +OUTPUT: + segmented images according to settings in cat_defaults.m + ${LOGDIR}/cat_${HOSTNAME}_${time}.log for log information + +USED FUNCTIONS: + cat_batch_cat.m + CAT12 toolbox + SPM12 + +SETTINGS + matlab command: $matlab + +This script was written by Christian Gaser (christian.gaser@uni-jena.de). + +__EOM__ +} + +######################################################## +# call main program +######################################################## + +main ${1+""$@""} +","Shell" +"Neurology","ChristianGaser/cat12","cat_sanlm.m",".m","1609","43","function cat_sanlm(in, v, f, rician) +% FORMAT cat_sanlm(in, v, f, rician) +% +% Spatial Adaptive Non Local Means Denoising Filter +% +% v - size of search volume (M in paper) +% f - size of neighborhood (d in paper) +% rician - use rician noise distribution +% +% * Details on SANLM filter +% *************************************************************************** +% * The SANLM filter is described in: * +% * * +% * Jose V. Manj—n, Pierrick Coupe, Luis Mart’-bonmat’, Montserrat Robles * +% * and D. Louis Collins. * +% * Adaptive Non-Local Means Denoising of MR Images with Spatially Varying * +% * Noise Levels. Journal of Magnetic Resonance Imaging, 31,192-203, 2010. * +% * * +% ***************************************************************************/ +% +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +rev = '$Rev$'; + +disp('Compiling cat_sanlm.c') + +pth = fileparts(which(mfilename)); +p_path = pwd; +cd(pth); +mex -O cat_sanlm.c sanlm_float.c +cd(p_path); + +cat_sanlm(in, v, f, rician); + +return +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_surf_epivolsurf.m",".m","16978","384","function varargout = cat_surf_epivolsurf(D,CSFS,opt,S) +% _________________________________________________________________________ +% +% varargout = cat_surf_epivolsurf(D,opt,S) +% IN: +% D ... image with Range 0 to 1 +% opt ... +% .side .. [streams0|streams1|streams01 +% .layer .. number of sublayers (default==6) +% +% OUT: +% S.IP ... inner surface points +% S.CP ... central surface points +% S.OP ... outer surface points +% S.SL ... length of the streamline +% S.L(1..nbstream-1) ??? for streamline ??? +% _________________________________________________________________________ +% +% ATTENTION matlab-stream function only works with double! +% _________________________________________________________________________ +% TODO: - optimization of memory and data structure +% * adaptation for GI-algorithm +% - layer calculation (7) +% - surface- vs. voxel-based +% - comments +% - parts-Estimation (memory problem at 100%) +% * isocolors for intensity estimation +% - zero-streams +% - correction of the point removement (half stream-stepsize) +% - parfor +% * size options for D +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + + +% check input +% _________________________________________________________________________ + tic + ndim = ndims(D); + + if ~isa(D,'single'), D = single(D); end + + def.side = 'streams01'; + def.verb = 0; % display calculation times + def.layer = 6; % number of sublayers + def.laplaceerr = 0.001; % Laplace filter stopping condition + def.streamsout = 0; % output streams variable + def.streamcorr = 1; % intensity correction of the streams + def.interpol = 0; % ??? + def.debug = 0; + def.LB = 1.5; + def.HB = 2.5; + def.GI = 0; + def.res = 1; + def.fast = 0; + opt = cat_io_checkinopt(opt,def); + + + % check options + switch opt.side % proof that opt.side is correct + case {'streams0','streams1','streams10'}; + otherwise, error('unknown streamside %s',opt.side); + end + if opt.layer<=2, error('You need at least 3 points'); end % proof useful number of layer + + % if there are too many and not enough streampoints you have to divide the streamline ... + if ~isfield(opt,'streamopt') || numel(opt.streamopt)~=2 + opt.streamopt(1) = 0.1; % point distance 0.05 + opt.streamopt(2) = 1/opt.streamopt(1)*10000; % max number of points in a stream + end + opt.streamopt(1) = opt.streamopt(1) / opt.res; % need adaptation for voxelresolution + %opt.streamopt(2) = round(opt.streamopt(2) / opt.res); % do not need an adaptation for max number of point! + + pinterpol = 2^opt.interpol; + nadd = (pinterpol-1)*(opt.interpol>0); + + + % check surface S + if exist('S','var'), opt.calctype = 'surfacebased'; + else opt.calctype = 'voxelbased'; opt.side='streams10'; + end + +% Output + switch opt.calctype + case 'voxelbased' + % for all GM points + S.SPi=find(D>opt.LB & D0 + slice=find(S.SP(:,3)~=opt.debug); + S.SPi(slice)=[]; + S.SP(slice,:)=[]; + end + S.CP = zeros(size(S.SP),'single'); % central surface points + S.SL = zeros(size(S.SP,1),1,'single'); % streamlength + S.L = zeros(size(S.SP,1),size(S.SP,2),opt.layer+1,'single'); % opt.layer Layerpoints + S.RPM = zeros(size(S.SP,1),1,'single'); % RPM value + case 'surfacebased' + if ~isfield(S,'vertices') || ~isfield(S,'faces'), error('ERROR epivolsurf: uncorrect surface S'); end + S.faces = single(S.faces); + %S.SP = single([S.vertices(:,2),S.vertices(:,1),S.vertices(:,3)]); % Startpoints + S.SP = single([S.vertices(:,1),S.vertices(:,2),S.vertices(:,3)]); % Startpoints + S=rmfield(S,'vertices'); + S.CP = zeros(size(S.SP),'single'); % central surface points + S.L = zeros(size(S.SP,1),size(S.SP,2),opt.layer+1,'single'); % opt.layer Layerpoints + end + S.SL = zeros(size(S.SP,1),1,'single'); % Streamlength + S.streams = []; % streamline from IP to OP with opt.layer points + + + +% set other variables + npoints = size(S.SP,1); + if opt.fast + maxpartsize = 1000000000/opt.streamopt(2); + else + maxpartsize = 100000000/opt.streamopt(2); % 1000000 + end + maxpartsize = maxpartsize / (1/opt.interpV)^3; + opt.parts = max(1,ceil(npoints / maxpartsize)); % fprintf(1,'(%d)',opt.parts); + partsize = floor(npoints/(opt.parts)); + %poi = 32*ceil(1/opt.streamopt(1)); + poi = opt.streamopt(2); + + + +% create potential-picture and gradients +% _________________________________________________________________________ + if opt.verb, fprintf(1,'L: '); end; tic + L = cat_vol_laplace3R(D,D==2,opt.laplaceerr); + Ls = smooth3(L); L(D~=2) = Ls(D~=2); clear Ls; % additional smoothing to avoid problems in the projection + D = smooth3(D); + if opt.GI + D(D<0)=0; + else + D = D-1; D(D<0)=0; D=D/2; + opt.LB = 0.25; opt.HB = 0.75; + end + + %if opt.uD2, D=(1-opt.uD2)*D + opt.uD2*(D2-1.5); clear D2; end + % depend on voxel-resolution and not on the mm resolution of D, because + % the skeleton should be as thin as possible + %D=smooth3(D,'gaussian',3,0.3); + %clear D2; + + % gradients + L=1-L; + [gj,gi,gk] = cat_vol_gradient3(L); + gi=double(gi);gj=double(gj);gk=double(gk); + + % gradients only in range of F + %if opt.streamcorr==0, + gi(D<=opt.LB | D>=opt.HB)=0; + gj(D<=opt.LB | D>=opt.HB)=0; + gk(D<=opt.LB | D>=opt.HB)=0; % Cleared for GI calculation used for layer and thickness!!!! +%end + + if opt.verb, fprintf(1,'%3.0f | SL: ',toc); end; tic + clear minD maxD L; + + if opt.GI, D=CSFS; end + + % streamline calculation in parts for speedup + % all coordingates are xyz=uvw=jik + % _______________________________________________________________________ + for p = 1:opt.parts + [l,h] = getrange(p,partsize,opt.parts,npoints); + + + % create streams + % _____________________________________________________________________ + + + % stream to lower side + if strcmp(opt.side,'streams0') || strcmp(opt.side,'streams10') + streams0 = stream3(gi,gj,gk,double(S.SP(l:h,2)),double(S.SP(l:h,1)),double(S.SP(l:h,3)),opt.streamopt)'; + streams0 = cellfun(@(s) single(pinterpol*[s(:,2),s(:,1),s(:,3)])-nadd,streams0,'UniformOutput',false); + if opt.streamcorr, streams0 = stream_correction(D,streams0,S.SP(l:h,:),ndim,poi,opt.LB,1,1); end % bf =0??? + end + + % stream to upper side + if strcmp(opt.side,'streams1') || strcmp(opt.side,'streams10') + streams1 = stream3(-gi,-gj,-gk,double(S.SP(l:h,2)),double(S.SP(l:h,1)),double(S.SP(l:h,3)),opt.streamopt)'; + streams1 = cellfun(@(s) single(pinterpol*[s(:,2),s(:,1),s(:,3)])-nadd,streams1,'UniformOutput',false); + if strcmp(opt.side,'streams10') + streams1 = cellfun(@(s) s(2:end,:),streams1,'UniformOutput',false);% remove double start point + if opt.streamcorr, streams1 = stream_correction(1-D,streams1,S.SP(l:h,:),ndim,poi,opt.LB,0,0); % remove other bad points => all if nessesary + else streams1 = cellfun(@flipud,streams1,'UniformOutput', false); % flip + end + else + if opt.streamcorr, streams1 = stream_correction(1,streams1,S.SP(l:h,:),ndim,poi,opt.LB,1,0); % one point have to stay (only this stream)! + else streams1 = cellfun(@flipud,streams1,'UniformOutput', false); % flip + end + end + end + switch opt.side + case 'streams0', streams = streams0; + case 'streams1', streams = streams1; + case 'streams10', streams = cellfun(@(s1,s0) [s1;s0],streams1,streams0,'UniformOutput',false); + end + + + + + % calculate the length of a stream. + % and correction for broken end elements + % _____________________________________________________________________ + streampointdist = cellfun(@(s) sum(diff([s(1,:);s]).^2,2).^0.5,streams,'UniformOutput',false); + streamlength = cellfun(@(s) sum(s,1),streampointdist); + + if opt.fast==0 + stream0err = 2*isocolors(CSFS,cell2mat(cellfun(@(s) s(end,[2,1,3]),streams,'UniformOutput',false))); + stream1err = zeros(size(streamlength)); + %stream0err = zeros(size(streamlength)); stream1err=zeros(size(streamlength)); + %streamdisterr = opt.res * isocolors(CSFS,cell2mat(cellfun(@(s) s(end,[2,1,3]),streams,'UniformOutput',false))); + %stream0err = max(stream0err,streamdisterr); clear streamdisterr; + else + stream0err = zeros(size(streamlength)); + stream1err = zeros(size(streamlength)); + end + + streamlength(streamlength>0) = streamlength(streamlength>0) + stream0err(streamlength>0); % + stream1err(streamlength>0); + streamlength(streamlength==0) = eps('single'); + + if strcmpi(opt.calctype,'voxelbased') + % ??berarbeiten !!!!! + streampointdist1 = cellfun(@(s) sum(diff(s).^2,2).^0.5,streams1,'UniformOutput',false); + streamlength1 = cell2mat(cellfun(@(s) single(sum(s,1)),streampointdist1,'UniformOutput',false)); + streamlength1(cellfun('size',streams1,1)==1) = eps('single'); + S.RPM(l:h) = max(0,streamlength - streamlength1) ./ streamlength; + % correction for voxelbased RPM measured by sperical phantom... + % by the way... GMT is perfect... don't know why the RPM need this... + % same for gbdist! + clear streamlength1 streampointdist1; + end + + + if strcmpi(opt.calctype,'surfacebased') % if 1... + % layer calculation + % _____________________________________________________________________ + streamlayer = cellfun(@(s,s1e,sl) (sl-s1e-cumsum(s,1))/(sl-s1e),streampointdist,num2cell(stream1err),... + num2cell(streamlength),'UniformOutput',false); + S.CP(l:h,:) = cell2mat(cellfun(@(s,sl) s(max([1,find(sl<=0.5,1,'first')]),:),streams,streamlayer,'UniformOutput',false)); + % funkt net, weil die l??nge null ist, der steamlayer damit auch null und damit eine leere matrix zugewiesen werden soll... + + S.L(l:h,:,opt.layer+1) = single(cell2mat(cellfun(@(s,sl) s(sl,:),streams,num2cell(double(cellfun('size',streams,1))),... + 'UniformOutput',false))); % OS, GM/CSF boundary + S.L(l:h,:,1) = cell2mat(cellfun(@(s) s(1,:),streams,'UniformOutput',false)); % IS, GM/WM boundary + for lay=1:opt.layer-1 + S.L(l:h,:,lay+1) = single(cell2mat(cellfun(@(s,sl) s(max([1,find(sl<=lay/opt.layer,1,'first')]),:),... + streams,streamlayer,'UniformOutput',false))); + end + end + S.SL(l:h) = streamlength * opt.res; + + clear streamlayer streams streamlength streamlengthUC nostream nostream0 SPi streams0 streams1 stream1err stream0err; + + + % times + % _____________________________________________________________________ + if opt.verb + if p==1, dispstrold=' '; else ... + dispstrold=sprintf('%4.0f/%4.0f - %2.1f%%%% - %4.0f of %4.0f seconds - ready in %4.0f seconds',p-1,opt.parts,100*(p-1)/opt.parts,toc,toc/(p-1)*opt.parts,round(toc/(p-1)*opt.parts-toc)); end + dispstrnew=sprintf('%4.0f/%4.0f - %2.1f%%%% - %4.0f of %4.0f seconds - ready in %4.0f seconds',p ,opt.parts,100* p /opt.parts,toc,toc/ p *opt.parts,round(toc/ p *opt.parts-toc)); + fprintf(1,sprintf('%s%s',repmat('\b',1,numel(dispstrold)-1),dispstrnew)); + end + end +% for p=1:size(S.SP), S.streams{p} = shiftdim(S.L(p,:,:))'; end + + + % backflipping of x and y + % _______________________________________________________________________ +% if isfield(S,'SP'), S.SP=[S.SP(:,2),S.SP(:,1),S.SP(:,3)]; end + if isfield(S,'CP'), S.CP=[S.CP(:,2),S.CP(:,1),S.CP(:,3)]; end +% if isfield(S,'L'), S.L =[S.L(:,2,:),S.L(:,1,:),S.L(:,3,:)]; end +% if isfield(S,'streams'), S.streams=[S.streams(:,2,:),S.streams(:,1,:),S.streams(:,3,:)]; end + + + switch opt.calctype + case 'voxelbased' + varargout{1}=single(D>=HB); % RPM + varargout{2}=zeros(size(D),'single'); % GMT + for p=1:size(S.SP,1) + varargout{1}(S.SPi(p))=S.RPM(p); + varargout{2}(S.SPi(p))=S.SL(p); + end + case 'surfacebased' + varargout{1}=S; + end + + %if opt.verb, fprintf(1,sprintf('%s%4.0fs',repmat('\b',1,numel(dispstrold)+13),toc)); end + if opt.verb, fprintf(1,sprintf('%s',repmat('\b',1,numel(dispstrold)+13))); end +end + +% Subfunctions: +% _________________________________________________________________________ +function streams = stream_correction(D,streams,P,ndim,np,th,sop,bf) +% stream correction - cut too long streams +% remove the last 'np' points of the streams 'streams' were D(np)>=th +% _________________________________________________________________________ +% D ... Image +% ndim ... number of dimensions +% np ... number of points to prove +% th ... theshold for D (default: 0.5) +% sop ... set one if one point have to stay (default: 1) +% bf ... flip to old streamdirection (default: 1) +% _________________________________________________________________________ + + if ~exist('th' ,'var'); th = 0.5; end + if ~exist('sop','var'), sop = 1; end + if ~exist('bf' ,'var'), bf = 1; end + + % Streamline Correction parameter + % _______________________________________________________________________ + % default-neighbor-matrix + % calculate a weight value for every stream-end-points based on his 4 or 8 + % grid neighbor values based on volume (use round operations and + % volume of the diagonal corner) + % calculate a intensity-value for all stream-end-points + % _______________________________________________________________________ + + sR = size(D); + nb = repmat(shiftdim([0 0 0;0 0 1;0 1 0;0 1 1;1 0 0;1 0 1;1 1 0;1 1 1]',-1),np,1); + enb = repmat(shiftdim((ones(8,1)*size(D))',-1),np,1); + + % 1) fipping to get the last points (depend on the stepsize) => np + streams = cellfun(@flipud,streams,'UniformOutput', false); + + % estimate the interesting points for every stream + nstreams = cellfun('size',streams,1); % number of points in a streams + nullstreams = find(nstreams==0); + if ~isempty(nullstreams) + for ns = nullstreams' + streams{ns} = P(ns,:); + nstreams(ns) = 1; + end; + end + + pstreams = nstreams; + pstreams(nstreams>np) = np; % if more than np-points are in a stream + if sop, pstreams(nstreams==pstreams) = pstreams(nstreams==pstreams)-1; end % one point have to stay + pstreams(pstreams<0) = 0; + + % convert into cells + pstreams = num2cell(pstreams); + nstreams = num2cell(nstreams); + + % calculate the weight of a neigbor (volume of the other corner) and + w8b = cellfun(@(s,n) reshape(repmat(s(1:n,:,:),1,2^ndim),[n,ndim,2^ndim]),streams,pstreams,'UniformOutput',false); + + % if the streamline ist near the boundary of the image you could be out of range if you add 1 + n8b = cellfun(@(s,n) max(1,min(floor(s(1:n,:,:)) + nb(1:n,:,:) , enb(1:n,:,:) )),w8b,pstreams,'UniformOutput',false); + w8b = cellfun(@(s,w) flip(prod(abs(s - w),2),3),n8b,w8b,'UniformOutput',false); + + % multiply this with the intensity-value of D => intensity-value of a streampoint + try + istreams = cellfun(@(n,s,w) 1 + n - sum(sum(D( sub2ind(sR,s(:,1,:),s(:,2,:),s(:,3,:)) ) .* w,3)>=th,1),pstreams,n8b,w8b,'UniformOutput',false); + streams = cellfun(@(s,f,e) s(f:e,:),streams,istreams,nstreams,'UniformOutput',false); % reset streams + catch %#ok + fprintf(1,'E'); + end + clear w8b n8b pstreams istreams nstreams; + + if bf, streams = cellfun(@flipud,streams,'UniformOutput', false); end +end + +function [l,h] = getrange(p,partsize,parts,max) +% _________________________________________________________________________ + if max<=partsize + l=1; h=max; + else + if p==1, l=1; h=partsize; + elseif p==parts, l=(p-1)*partsize + 1; h=max; + else l=(p-1)*partsize + 1; h=partsize*p; + end + end +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_vol_eidist.c",".c","22007","603","/* + * This function estimates the Euclidean distance D to the closest boundary + * voxel I, given by the 0.5 isolevel in B with values between 0 and 1, + * defining subvoxel position by partial volume effects. Larger object + * voxel overrule smaller voxels. + * + * To align the closest voxel a modified Eikonal distances T is estimated + * on the field L, ie. L is a speed map and T is the travel time. + * For a correct side alignment a harder option ""csf"" is used that avoids + * the diffusion to voxels with greater values of L (L[i]>L[ni] for + * diffusion). + * + * Voxels with NaN and -INF are ignored and produce NaN in D, whereas + * in I the default index is used, because I has to be a integer matrix + * where NaN is not available. With setnan=0, the result of NAN voxel in + * D is changed to INF. + * + * [D,I,T] = cat_vol_eidist(B,L,[vx_vol,euclid,csf,setnan,verb]) + * + * D Euclidean distance map to the nearest Boundary point in the + * Eikonal field (3d-single-matrix) + * (air distance) + * T Eikonal distance map in the Eikonal field (3d-single-matrix) + * (way length or time) + * I index map (3d-uint32-matrix) + * B boundary map (3d-single-matrix) + * L speed map (3d-single-matrix) + * vx_vol voxel size (1x3-double-matrix): default=[1 1 1] + * ... not tested yet + * csf option (1x1-double-value): 0-no; 1-yes; default=1 + * euclid option (1x1-double-value): 0-no; 1-yes; default=1 + * output euclidean or speed map as first value + * setnan option (1x1-double-value): 0-no; 1-yes; default=1 + * verb option (1x1-double-value): 0-no, 1-yes; default=0 + * + * + * Small test examples: + * 1) ""Face"" with distance from the eyes and an odd nose + * A=zeros(50,50,3,'single'); A(20:30,5:15,2)=10; A=smooth3(A); + * A(20:30,35:45,2)=1; A(1:5,1:25,:)=nan; A(1:5,26:50,:)=-inf; + * F=ones(size(A),'single'); F(10:40,20,:)=0.5; F(40,10:40,:)=0; + * [D,I,T]=cat_vol_eidist(A,F,[1 1 1],1,1); + * ds('d2smns','',1,A - F,D/10,2); title('Euclidean distance') + * ds('d2smns','',1,A - F,T/10,2); title('Eikonal distance') + * + * 2) 1D-examples to count distance + * A=zeros(10,20,10,'single'); A(:,1:5,:)=1; A(:,15:end,:)=nan; F=ones(size(A),'single'); + * A=zeros(10,20,10,'single'); A(:,1:5,:)=1; A(:,6,:)=0.2; A(:,15:end,:)=nan; F=ones(size(A),'single'); + * A=zeros(10,20,10,'single'); A(:,1:5,:)=1; A(:,15:end,:)=nan; F=ones(size(A),'single'); + * + * [D,I]=cat_vol_eidist(A,F,[1 1 1],1,1,0,1); ds('x2','',1,A,D,D,I,5) + * + * See also compile.m + * ______________________________________________________________________ + * + * Christian Gaser, Robert Dahnke + * Structural Brain Mapping Group (https://neuro-jena.github.io) + * Departments of Neurology and Psychiatry + * Jena University Hospital + * ______________________________________________________________________ + * $Id$ + */ + + +/* + * ToDo: + * - check anisotropic distance estimation + */ + + +#include ""mex.h"" +#include ""math.h"" +#include ""float.h"" +#include ""limits.h"" +#include +#include + +#ifdef _MSC_VER + #define FINFINITY (FLT_MAX+FLT_MAX); + static const unsigned long __nan[2] = {0xffffffff, 0x7fffffff}; + #define FNAN (*(const float *) __nan) +#else + #define FINFINITY 1.0f/0.0f; + #define FNAN 0.0f/0.0f +#endif + + +/* + * Estimate x,y,z position of index i in an array size sx,sxy. + * The index is given in c-notation for a matrix with n elements i is + * element of 0,1,...,n-1. Also the x,y,z axis are described in the + * c-notation and a matrix A with 20x30x40 elements will have coordinates + * with x=0,1,...,19; y=0,1,...,30; and z=0,1,...40. The index i=0 is + * identical with x=0,y=0,z=0; whereas the last index in the matrix A + * is i=n-1=(20*30*40)-1 and has the coordinates x=19,y=29, and z=39. + * + */ + + +// estimation of the xyz values based on the index value +void ind2sub(int i, int *x, int *y, int *z, int snL, int sxy, int sy) { + // handling of boundaries + if (i<0) i=0; + if (i>=snL) i=snL-1; + + *z = (int)floor( (double)i / (double)sxy ); + i = i % (sxy); + *y = (int)floor( (double)i / (double)sy ); + *x = i % sy ; +} + + +/* + * Estimate index i of a voxel x,y,z in an array size s. + * See also for ind2sub. + */ +int sub2ind(int x, int y, int z, int s[]) { + // handling on boundaries + if (x<0) x=0; if (x>s[0]-1) x=s[0]-1; + if (y<0) y=0; if (y>s[1]-1) y=s[1]-1; + if (z<0) z=0; if (z>s[2]-1) z=s[2]-1; + + // z * (number of voxels within a slice) + // + y * (number of voxels in a column) + // + x ( what is the position within the column ) + return (z)*s[0]*s[1] + (y)*s[0] + (x); +} + + +float pow_float(float x, float y) { + return (float) pow((double) x,(double) y); +} + +float sqr_float(float x) { + return x*x; +} + +float sqrt_float(float x) { + return (float) sqrt((double) x); +} + +float floor_float(float x) { + return (float) floor((double) x); +} + +/* + * Read out the linear interpolated value of a volume SEG with the size + * s on the position x,y,z (c-notation). See also ind2sub for details of + * the c-notation. + */ +float isoval(float SEG[], float x, float y, float z, int s[]){ + + int i; + float seg=0.0, n=0.0; + float fx = floor_float(x), fy = floor_float(y), fz = floor_float(z); + float cx = floor_float(x+1), cy = floor_float(y+1), cz = floor_float(z+1); + + float wfx = cx-x, wfy = cy-y, wfz = cz-z; + float wcx = x-fx, wcy = y-fy, wcz = z-fz; + + /* value of the 8 neighbors and there distance weight */ + float N[8], W[8]; + N[0]=SEG[sub2ind((int)fx,(int)fy,(int)fz,s)]; W[0]=wfx * wfy * wfz; + N[1]=SEG[sub2ind((int)cx,(int)fy,(int)fz,s)]; W[1]=wcx * wfy * wfz; + N[2]=SEG[sub2ind((int)fx,(int)cy,(int)fz,s)]; W[2]=wfx * wcy * wfz; + N[3]=SEG[sub2ind((int)cx,(int)cy,(int)fz,s)]; W[3]=wcx * wcy * wfz; + N[4]=SEG[sub2ind((int)fx,(int)fy,(int)cz,s)]; W[4]=wfx * wfy * wcz; + N[5]=SEG[sub2ind((int)cx,(int)fy,(int)cz,s)]; W[5]=wcx * wfy * wcz; + N[6]=SEG[sub2ind((int)fx,(int)cy,(int)cz,s)]; W[6]=wfx * wcy * wcz; + N[7]=SEG[sub2ind((int)cx,(int)cy,(int)cz,s)]; W[7]=wcx * wcy * wcz; + + for (int i=0; i<8; i++) { + if ( mxIsNaN(N[i])==false || mxIsInf(N[i])==false ) + seg = seg + N[i] * W[i]; n+= W[i]; + } + if ( n>0.0 ) + return seg/n; + else + return FNAN; +} + + +/* + * MAINFUNCTION [D,I] = cat_vol_eidist(B,L,vx_vol,euclid,csf,setnan,verb]) + */ +void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { + + /* + * Check input + */ + if (nrhs<2) mexErrMsgTxt(""ERROR:cat_vol_eidist: not enough input elements\n""); + if (nrhs>7) mexErrMsgTxt(""ERROR:cat_vol_eidist: too many input elements.\n""); + if (nlhs>3) mexErrMsgTxt(""ERROR:cat_vol_eidist: too many output elements.\n""); + if (mxIsSingle(prhs[0])==false) + mexErrMsgTxt(""ERROR:cat_vol_eidist: first input must be an 3d single matrix\n""); + if (mxIsSingle(prhs[1])==false) + mexErrMsgTxt(""ERROR:cat_vol_eidist: second input must be an 3d single matrix\n""); + if (nrhs==3 && mxIsDouble(prhs[2])==false) + mexErrMsgTxt(""ERROR:cat_vol_eidist: third input must be an double matrix\n""); + if (nrhs==3 && mxGetNumberOfElements(prhs[2])!=3) + printf(""ERROR:cat_vol_eidist: third input must have 3 Elements""); + if (nrhs==4 && mxIsDouble(prhs[3])==false && mxGetNumberOfElements(prhs[3])!=1) + printf(""ERROR:cat_vol_eidist: fourth input must be one double value""); + if (nrhs==5 && mxIsDouble(prhs[4])==false && mxGetNumberOfElements(prhs[4])!=1) + printf(""ERROR:cat_vol_eidist: fifth input must be one double value""); + if (nrhs==6 && mxIsDouble(prhs[5])==false && mxGetNumberOfElements(prhs[5])!=1) + printf(""ERROR:cat_vol_eidist: sixth input must be one double value""); + if (nrhs==7 && mxIsDouble(prhs[6])==false && mxGetNumberOfElements(prhs[6])!=1) + printf(""ERROR:cat_vol_eidist: seventh input must be one double value""); + + /* + * set default variables + */ + int csf, euclid, setnan, verb; + float nanres; + + if (nrhs>=4) csf = (int)*mxGetPr(prhs[3]); else csf = 1; + if (nrhs>=5) euclid = (int)*mxGetPr(prhs[4]); else euclid = 1; + if (nrhs>=6) setnan = (int)*mxGetPr(prhs[5]); else setnan = 1; + if (nrhs>=7) verb = (int)*mxGetPr(prhs[6]); else verb = 0; + + if (setnan>=1) nanres = FNAN; else nanres = FINFINITY; + + /* + * main input variables B (boundary map) and L (speed map) + */ + float*B = (float *)mxGetPr(prhs[0]); + float*L = (float *)mxGetPr(prhs[1]); + + /* + * main information about input data (size, dimensions, ...) + */ + const mwSize *sL = mxGetDimensions(prhs[0]); + const int dL = mxGetNumberOfDimensions(prhs[0]); + const int nL = mxGetNumberOfElements(prhs[0]); + const int nD = mxGetNumberOfElements(prhs[1]); + const int x = (int)sL[0]; + const int y = (int)sL[1]; + const int xy = x*y; + int sizeL[3] = {(int)sL[0],(int)sL[1],(int)sL[2]}; + + if (nL!=nD) mexErrMsgTxt(""ERROR:cat_vol_eidist: images must have the same number of elements.\n""); + + /* + * Voxel dimension and standard distance in the N26 neighborhood. + * Indices of the neighbor NI (index distance) and euclidean distance ND. + * Set default voxel size=[1 1 1] or use input. + */ + const mwSize sS[2] = {1,3}; + mxArray *SS = mxCreateNumericArray(2,sS,mxDOUBLE_CLASS,mxREAL); + double *S = mxGetPr(SS); + if (nrhs<3) {S[0]=1; S[1]=1; S[2]=1;} else S=mxGetPr(prhs[2]); + + float s1 = (float)fabs(S[0]); + float s2 = (float)fabs(S[1]); + float s3 = (float)fabs(S[2]); /* x,y,z - voxel size */ + const float s12 = sqrt( s1*s1 + s2*s2); /* xy - voxel size */ + const float s13 = sqrt( s1*s1 + s3*s3); /* xz - voxel size */ + const float s23 = sqrt( s2*s2 + s3*s3); /* yz - voxel size */ + const float s123 = sqrt(s12*s12 + s3*s3); /* nL - voxel size */ + + const int NI[26] = { 1, -1, x, -x, xy, -xy, -x-1, -x+1, x-1, x+1, + -xy-1, -xy+1, xy-1, xy+1, -xy-x, -xy+x, xy-x, xy+x, + -xy-x-1, -xy-x+1, -xy+x-1, -xy+x+1, xy-x-1, xy-x+1, + xy+x-1,xy+x+1}; + const float ND[26] = { s1, s1, s2, s2, s3, s3, s12, s12,s12,s12, + s13, s13, s13, s13, s23, s23, s23, s23, + s123, s123, s123, s123, s123, s123, s123, s123}; + const int kllv = (sL[0]+sL[1]+sL[2]); + + + /* + * other variables + */ + float dinu, dinv, dinw, dcf, WMu, WMv, WMw, WM, DIN, DINE; /* distance and intensity variables */ + int ni,u,v,w,nu,nv,nw,iu,iv,iw; /* nL and index-values of a voxel, one neighbor and the nearest boundary voxel */ + int nC=sL[0]*sL[1]*sL[2], nCo=INT_MAX; /* runtime variables */ + int kll=0; /* runtime variables */ + int fast=1; /* stop if number of unvisited points stay constant */ + + + /* + * Create main output volumes and variables D (distance map) and I (index map) + */ + mxArray *hlps[2]; /* helping matrixes */ + plhs[0] = mxCreateNumericArray(dL,sL,mxSINGLE_CLASS,mxREAL); + hlps[0] = mxCreateNumericArray(dL,sL,mxUINT32_CLASS,mxREAL); + hlps[1] = mxCreateNumericArray(dL,sL,mxSINGLE_CLASS,mxREAL); + float *D = (float *)mxGetPr(plhs[0]); + unsigned int *I = (unsigned int *)mxGetPr(hlps[0]); /* index map */ + float *T = (float *)mxGetPr(hlps[1]); + + /* + * Display Initial Parameter + */ + if ( verb ) { + printf(""\ncat_vol_eidist.c debuging mode:\n Initialize Parameter: \n""); + printf("" size(B) = %d %d %d\n"",(int)sL[0],(int)sL[1],(int)sL[2]); + printf("" vx_vol = %0.0f %0.0f %0.0f\n"",s1,s2,s3); + printf("" euclid = %d\n"",(int) euclid); + printf("" setnan = %d\n"",(int) setnan); + } + + + /* + * Check input values. + */ + int vx=0; + for (int i=0;i=0.5 ) vx++; /* count object voxel */ + + if ( (L[i]<=0.0 || mxIsNaN(L[i])) && B[i]<0.5) B[i] = FNAN; /* ignore voxel that cannot be visited */ + + if ( mxIsInf(B[i]) && B[i]<0.0 ) B[i] = FNAN; /* voxel to ignore */ + if ( B[i]>1.0 ) B[i] = 1.0; /* normalize object definition limitation */ + if ( B[i]<0.0 ) B[i] = 0.0; /* normalize object definition limitation */ + I[i] = (unsigned int) i; /* initialize index map */ + if ( nlhs>2 ) T[i] = 0.0; + + if ( L[i]<=0.0 || mxIsNaN(B[i]) || mxIsNaN(L[i]) ) + D[i] = FNAN; + else + D[i] = FINFINITY; + } + + + /* + * Check if there is an object and return FINFINITY and i=i+1 (for matlab) + * for all points if there is no object. + */ + if ( vx==0 ) { + for (int i=0;i0.0 && mxIsNaN(D[i])==false) { + + if ( B[i]>=0.5 ) { + D[i] = 0.0; + ind2sub(i,&u,&v,&w,nL,xy,x); + + for (int n=0;n<26;n++) { + ni = i + NI[n]; + ind2sub(ni,&nu,&nv,&nw,nL,xy,x); + + if ( ( (ni<0) || (ni>=nL) || + (abs(nu-u)>1) || (abs(nv-v)>1) || (abs(nw-w)>1) || + (ni==i) )==false && B[ni]<0.5) { + /* PVE idea not robust for interpolation and GM variance */ + DIN = ND[n]; /* * (B[ni] - 0.5) / ( B[ni] - B[i] ); */ /* RD202310: simplification */ + + if ( fabs(D[ni])>DIN ) { + D[ni] = -DIN; + I[ni] = I[i]; + if ( nlhs>2 ) T[ni] = DIN; + } + + } + } + } + } + } + + + /* + * iterative Eikonal distance estimation + */ + if ( verb ) printf("" Eikonal distance estimation and index alignment \n""); + while ( nC>0 && kll=nL) || (abs(nu-u)>1) || (abs(nv-v)>1) || + (abs(nw-w)>1) || (ni==i) || mxIsNaN(D[ni]) || B[ni]>=0.5 )==false && + ( csf==0 || L[ni]<=fabs(L[i]+0.5) ) ) { + + /* new distance for the neighbor */ + DIN = fabs(D[i]) + ND[n] / (FLT_MIN + L[ni]); + + /* use DIN, if the new value is smaller than the actual value of the neighbor */ + if ( fabs(D[ni]) > DIN ) { + if (D[ni]>0.0) nC++; /* count changes */ + D[ni] = -DIN; /* set new thickness - negative value so that the neigbor will also push */ + I[ni] = I[i]; /* index value of the current voxel (closest boundary index) */ + if ( nlhs>2 ) T[ni] = fabs(D[i]) + ND[n]; /* DIN; */ /* second output map with simple voxel distance */ + } + } + } + } + } + + + /* + * Backward direction: + * Same as forward, with the small difference of demarking the start + * voxel at the end. + */ + for (int i=nL-1;i>=0;i--) { + if ( D[i]<=0.0 && mxIsNaN(D[i])==false) { + if ( D[i]<0.0 && mxIsInf(D[i])==false ) D[i]*=-1.0; /* mark voxel as visited */ + + ind2sub(i,&u,&v,&w,nL,xy,x); + + for (int n=0;n<26;n++) { + ni = i + NI[n]; + ind2sub(ni,&nu,&nv,&nw,nL,xy,x); + + /* Only process this part for real neighbor indices and + * only if L is lower (to avoid region-growing over sulci)! + */ + if ( ( (ni<0) || (ni>=nL) || (abs(nu-u)>1) || (abs(nv-v)>1) || + (abs(nw-w)>1) || (ni==i) || mxIsNaN(D[ni]) || B[ni]>=0.5 )==false && + ( csf==0 || L[ni]<=fabs(L[i]+0.5) ) ) { + + /* new distance */ + DIN = fabs(D[i]) + ND[n] / (FLT_MIN + L[ni]); + + /* use DIN, if the actual value is larger */ + if ( fabs(D[ni])>DIN ) { + if (D[ni]>0.0) nC++; + D[ni] = -DIN; + I[ni] = I[i]; + if ( nlhs>2 ) T[ni] = fabs(D[i]) + ND[n]; /* DIN; */ + } + } + } + + /* + * Demarking the start voxels + */ + if (D[i]==0.0) D[i]=-FINFINITY; + + } + } + + if ( verb && kll<30 ) + printf("" nC=%10d, kll=%4d, kllv=%4d\n"",nC,kll,kllv); + if ( nC==nCo ) { csf=0; nCo++; } /* further growing??? */ + } + + + + /* + * Correction of non-visited points due to miss-estimations of the + * exact boundary. + */ + if ( verb ) printf("" Correction of unvisited points \n""); + for (int i=0;i0.0 && I[i]!=(unsigned int)i ) { + + ni = (int) I[i]; + + ind2sub(ni,&nu,&nv,&nw,nL,xy,x); + ind2sub(i ,&iu,&iv,&iw,nL,xy,x); + + /* standard euclidean distance between i and closest object point I[i] */ + dinu = (float)iu - (float)nu; dinu *= s1; + dinv = (float)iv - (float)nv; dinv *= s2; + dinw = (float)iw - (float)nw; dinw *= s3; + DIN = sqrt_float(sqr_float(dinu) + sqr_float(dinv) + sqr_float(dinw) - (3*0.5) ); /* 0.5 is the boundary vs. grid-distance */ + + /* For voxels that are not too close to the object the exact + * Euclidean distance should be estimated. For closer points + * the previous distance value is good enough. + */ + if ( 1 ) { + /* Estimation of the exact PVE boundary by estimation of a point + * next to the boundary voxel. + */ + dinu /= DIN; dinv /= DIN; dinw /= DIN; /* normal vector in normal space */ + dinu /= s1; dinv /= s2; dinw /= s3; /* normal vector for anisotropic space */ + WM = isoval(B,(float)nu + dinu,(float)nv + dinv,(float)nw + dinw,sizeL); + + if ( B[ni]!=WM ) { + /* estimate new point before border to get the gradient based on this the exact HB */ + dcf = (B[ni] - 0.5) / ( B[ni] - WM ); + WMu = (float)nu + dinu*dcf; + WMv = (float)nv + dinv*dcf; + WMw = (float)nw + dinw*dcf; + // WM = isoval(B,WMu,WMv,WMw,sizeL); + + /* new exact distance to interpolated boundary */ + dinu = (float)iu - WMu; dinu *= s1; + dinv = (float)iv - WMv; dinv *= s2; + dinw = (float)iw - WMw; dinw *= s3; + DINE = sqrt_float(sqr_float(dinu) + sqr_float(dinv) + sqr_float(dinw)); + + if ( false ) { // WM<0.45 || WM>0.55 ) { // 0.4 0.6 + WMu = (float)nu + 0.5*dinu*dcf; + WMv = (float)nv + 0.5*dinv*dcf; + WMw = (float)nw + 0.5*dinw*dcf; + WM = isoval(B,WMu,WMv,WMw,sizeL); + } + + /* use the new estimated distance only if it is a meanful */ + if ( DINE>0.0 && mxIsNaN(DINE)==false && mxIsInf(DINE)==false ) { + D[i] = fmin( DIN , DINE ); + } + else { + /* use the voxelboundary corrected euclidean distance DIN + * in case of larger values, or otherwise use the initial + * value used before ... for higher values the speed map + * lead to non euclidean distances! + */ + D[i] = DIN; + } + } + } + else { + /* simple euclidean distance without PVE for tests */ + D[i] = DIN; + } + } + } + } + + + + /* + * Final corrections + */ + if ( verb ) printf("" Final corrections \n""); + for (int i=0;i0 ) I[i]++; else I[i]=1; + + /* correction of non-visited or other incorrect voxels */ + if ( D[i]<0.0 || mxIsNaN(D[i]) || mxIsInf(D[i]) ) D[i]=0; // nanres; + + } + + + /* final alignments to dynamic output variables */ + if (nlhs>1) { + plhs[1] = mxCreateNumericArray(dL,sL,mxUINT32_CLASS,mxREAL); + unsigned int *IO = (unsigned int *) mxGetPr(plhs[1]); + for (int i=0;i2) { + plhs[2] = mxCreateNumericArray(dL,sL,mxSINGLE_CLASS,mxREAL); + float *TO = (float *) mxGetPr(plhs[2]); + for (int i=0;i +#include +#include +#include + +/* + +Program to extract simply connected surfaces (""no holes, handles, loops, or self intersections"") from segmented 3D images. +Steve Haker, Surgical Planning Lab, Brigham and Women's Hospital, Harvard University. +Distance transform by Andre Robatino, Surgical Planning Lab, Brigham and Women's Hospital, Harvard University. + +Please send bug reports to haker@bwh.harvard.edu. + +*/ + +typedef struct _genus0parameters + { + + /* INPUT parameters */ + + unsigned short * input; /* Pointer to data from which to extract surface. */ + + int return_adjusted_label_map ; /* return an adjusted label map? I.e. fill in output[]? Default 1. */ + int return_surface ; /* fill in triangles[] and vertices[]? Default 1. */ + + int dims[3]; /* Dimensions of data set (cols,rows,depth). */ + + unsigned short value; /* Value of label defining surface to extract. */ + + unsigned short alt_value; /* Value to assign to adjusted voxels */ + unsigned short contour_value; /* Value to set contour voxels to, if they are part of original labelmap. Default alt_value */ + unsigned short alt_contour_value; /* Value to set contour voxels to, if they are not part of original labelmap. Default alt_value */ + + int cut_loops; /* cut loops instead of patching holes? Sorry, it's either/or globally... Default 0.*/ + + int pad[3]; /* pad around volume after cropping. Default is {2,2,2}. */ + + int connectivity; /* Connectivity model. 6 or 18. Default is 6. */ + + int any_genus; /* If not zero, just get the surface regardless of its genus. Essentially marching cubes. */ + /* If zero, we want genus zero surfaces. Default is 0 */ + + /* Only used if return_surface not zero... */ + int biggest_component; /* If not zero, extract biggest connected triangulated component. */ + /* Default is 1 */ + + int connected_component; /* extract largest connected component from input[] data _before_ processing. Default 1 */ + + float *ijk2ras; /* 4x4 matrix, ijk2ras[12..15]={0,0,0,1},... you know what I mean. */ + /* Multiply vertices by this, i.e. ijk2ras*vertices. RAS means Right, Anterior, Superior.*/ + /* You can pass NULL to use the identity matrix. */ + /* i=[0..dim[0]], j=[0...dims[1]] (""down the side of each image""), k=[0...dims[2]] */ + /* Default is NULL (identity matrix) */ + + + float extraijkscale[3]; /* Voxel scaling during process. Does not affect the coordinates of vertices created. */ + /* Just seems to help reduce the corrections needed sometimes if you scale in the */ + /* direction of the scan (normally k, i.e. set extraijkscale[2]>1 ). Default is {1,1,1} */ + + int verbose; /* If not zero, show progress of algorithm. Default is 0. */ + + + /* OUTPUT results */ + + /* Only used if return_adjusted_label_map not zero... */ + unsigned short * output; /* Pointer to the place where adjusted label map will be put. */ + /* If NULL when genus0 is called, space will be allocated. */ + /* Else, it's assumed to be allocated already. */ + + /* Only used if return_surface not zero... */ + int vert_count; /* Will hold number of vertices. */ + float * vertices; /* Will hold output vertices. (vert_count cols x 3 rows). Space will be allocated */ + int tri_count; /* Will hold number of triangles. */ + int * triangles; /* Will hold output triangles. (tri_count cols x 3 rows). Space will be allocated */ + + /* PRIVATE */ + int calloced_output; /* A flag to remember if *output was calloced, so it can be freed upon destruction */ + + } genus0parameters; + + +/* public stuff */ +extern void genus0init(genus0parameters * g0); /* Initialize fields in *g0 to their defaults. Must be called before genus0(). */ +extern int genus0(genus0parameters * g0); /* Call the algorithm. Do the work. Returns 0 on success, 1 on failure. */ +extern void genus0destruct(genus0parameters * g0); /* Frees *vertices and *triangles, and frees *output if it was calloced */ +","Unknown" +"Neurology","ChristianGaser/cat12","cat_spm_results_ui.m",".m","90084","2131","function varargout = cat_spm_results_ui(varargin) +% User interface for SPM/PPM results: Display and analysis of regional effects +% FORMAT [hReg,xSPM,SPM] = cat_spm_results_ui('Setup',[xSPM]) +% +% hReg - handle of MIP XYZ registry object +% (see spm_XYZreg.m for details) +% xSPM - structure containing specific SPM, distribution & filtering details +% (see spm_getSPM.m for contents) +% SPM - SPM structure containing generic parameters +% (see spm_spm.m for contents) +% +% NB: Results section GUI CallBacks use these data structures by name, +% which therefore *must* be assigned to the correctly named variables. +%__________________________________________________________________________ +% +% The SPM results section is for the interactive exploration and +% characterisation of the results of a statistical analysis. +% +% The user is prompted to select a SPM{T} or SPM{F}, that is thresholded at +% user specified levels. The specification of the contrasts to use and the +% height and size thresholds are described in spm_getSPM.m. The resulting +% SPM is then displayed in the Graphics window as a maximum intensity +% projection, alongside the design matrix and contrasts employed. +% +% The cursors in the MIP can be moved (dragged) to select a particular +% voxel. The three mouse buttons give different drag and drop behaviour: +% Button 1 - point & drop; Button 2 - ""dynamic"" drag & drop with +% co-ordinate & SPM value updating; Button 3 - ""magnetic"" drag & drop, +% where the cursor jumps to the nearest suprathreshold voxel in the MIP, +% and shows the value there. +% See spm_mip_ui.m, the MIP GUI handling function for further details. +% +% The design matrix and contrast pictures are ""surfable"": Click and drag +% over the images to report associated data. Clicking with different +% buttons produces different results. Double-clicking extracts the +% underlying data into the base workspace. +% See spm_DesRep.m for further details. +% +% The current voxel specifies the voxel, suprathreshold cluster, or +% orthogonal planes (planes passing through that voxel) for subsequent +% localised utilities. +% +% A control panel in the Interactive window enables interactive exploration +% of the results. +% +% p-values buttons: +% (i) volume - Tabulates p-values and statistics for entire volume. +% - see spm_list.m +% (ii) cluster - Tabulates p-values and statistics for nearest cluster. +% - Note that the cursor will jump to the nearest +% suprathreshold voxel, if it is not already at a +% location with suprathreshold statistic. +% - see spm_list.m +% (iii) S.V.C - Small Volume Correction: +% Tabulates p-values corrected for a small specified +% volume of interest. (Tabulation by spm_list.m) +% - see spm_VOI.m +% +% Data extraction buttons: +% Eigenvariate/CVA +% - Extracts the principal eigenvariate for small volumes +% of interest; or CVA of data within a specified volume +% - Data can be adjusted or not for eigenvariate summaries +% - If temporal filtering was specified (fMRI), then it is +% the filtered data that is returned. +% - Choose a VOI of radius 0 to extract the (filtered &) +% adjusted data for a single voxel. Note that this vector +% will be scaled to have a 2-norm of 1. (See spm_regions.m +% for further details.) +% - The plot button also returns fitted and adjusted +% (after any filtering) data for the voxel being plotted.) +% - Note that the cursor will jump to the nearest voxel for +% which raw data was saved. +% - see spm_regions.m +% +% Visualisation buttons: +% (i) plot - Graphs of adjusted and fitted activity against +% various ordinates. +% - Note that the cursor will jump to the nearest +% suprathreshold voxel, if it is not already at a +% location with suprathreshold statistic. +% - Additionally, returns fitted and adjusted data to the +% MATLAB base workspace. +% - see spm_graph.m +% (ii) overlays - Popup menu: Overlays of filtered SPM on a structural image +% - slices - Slices of the thresholded statistic image overlaid +% on a secondary image chosen by the user. Three +% transverse slices are shown, being those at the +% level of the cursor in the z-axis and the two +% adjacent to it. - see spm_transverse.m +% - sections - Orthogonal sections of the thresholded statistic +% image overlaid on a secondary image chosen by the user. +% The sections are through the cursor position. +% - see spm_sections.m +% - render - Render blobs on previously extracted cortical surface +% - see spm_render.m +% (iii) save - Write out thresholded SPM as image +% - see spm_write_filtered.m +% +% The current cursor location can be set by editing the co-ordinate widgets +% at the bottom of the Interactive window. (Note that many of the results +% section facilities are ""linked"" and can update co-ordinates. E.g. +% clicking on the co-ordinates in a p-value listing jumps to that location.) +% +% Graphics appear in the bottom half of the Graphics window, additional +% controls and questions appearing in the Interactive window. +% +% ---------------- +% +% The MIP uses a template outline in MNI space. Consequently for the +% results section to display properly the input images to the statistics +% section should be in MNI space. +% +% Similarly, secondary images should be aligned with the input images used +% for the statistical analysis. +% +% ---------------- +% +% In addition to setting up the results section, cat_spm_results_ui.m sets +% up the results section GUI and services the CallBacks. FORMAT +% specifications for embedded CallBack functions are given in the main +% body of the code. +%__________________________________________________________________________ +% Copyright (C) 1996-2018 Wellcome Trust Centre for Neuroimaging +% Karl Friston & Andrew Holmes +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + +%========================================================================== +% - FORMAT specifications for embedded CallBack functions +%========================================================================== +%( This is a multi function function, the first argument is an action ) +%( string, specifying the particular action function to take. ) +% +% cat_spm_results_ui sets up and handles the SPM results graphical user +% interface, initialising an XYZ registry (see spm_XYZreg.m) to co-ordinate +% locations between various location controls. +% +%__________________________________________________________________________ +% +% FORMAT [hreg,xSPM,SPM] = cat_spm_results_ui('Setup') +% Query SPM and setup GUI. +% +% FORMAT [hreg,xSPM,SPM] = cat_spm_results_ui('Setup',xSPM) +% Query SPM and setup GUI using a xSPM input structure. This allows to run +% results setup without user interaction. See spm_getSPM for details of +% allowed fields. +% +% FORMAT hReg = cat_spm_results_ui('SetupGUI',M,DIM,xSPM,Finter) +% Setup results GUI in Interactive window +% M - 4x4 transformation matrix relating voxel to ""real"" co-ordinates +% DIM - 3 vector of image X, Y & Z dimensions +% xSPM - structure containing xSPM. Required fields are: +% .Z - minimum of n Statistics {filtered on u and k} +% .XYZmm - location of voxels {mm} +% Finter - handle (or 'Tag') of Interactive window (default 'Interactive') +% hReg - handle of XYZ registry object +% +% FORMAT cat_spm_results_ui('DrawButts',hReg,DIM,xSPM,Finter,WS,FS) +% Draw GUI buttons +% hReg - handle of XYZ registry object +% DIM - 3 vector of image X, Y & Z dimensions +% xSPM - structure containing xSPM. Required fields are: +% Finter - handle of Interactive window +% WS - WinScale [Default spm('WinScale') ] +% FS - FontSizes [Default spm('FontSizes')] +% +% FORMAT hFxyz = cat_spm_results_ui('DrawXYZgui',M,DIM,xSPM,xyz,hReg) +% Setup editable XYZ control widgets at foot of Interactive window +% M - 4x4 transformation matrix relating voxel to ""real"" co-ordinates +% DIM - 3 vector of image X, Y & Z dimensions +% xSPM - structure containing SPM; Required fields are: +% .Z - minimum of n Statistics {filtered on u and k} +% .XYZmm - location of voxels {mm} +% xyz - Initial xyz location {mm} +% hReg - handle of XYZ registry object +% hFxyz - handle of XYZ control - the frame containing the edit widgets +% +% FORMAT cat_spm_results_ui('EdWidCB') +% Callback for editable XYZ control widgets +% +% FORMAT cat_spm_results_ui('UpdateSPMval',hFxyz) +% FORMAT cat_spm_results_ui('UpdateSPMval',UD) +% Updates SPM value string in Results GUI (using data from UserData of hFxyz) +% hFxyz - handle of frame enclosing widgets - the Tag object for this control +% UD - XYZ data structure (UserData of hFxyz). +% +% FORMAT xyz = cat_spm_results_ui('GetCoords',hFxyz) +% Get current co-ordinates from editable XYZ control +% hFxyz - handle of frame enclosing widgets - the Tag object for this control +% xyz - current co-ordinates {mm} +% NB: When using the results section, should use XYZregistry to get/set location +% +% FORMAT [xyz,d] = cat_spm_results_ui('SetCoords',xyz,hFxyz,hC) +% Set co-ordinates to XYZ widget +% xyz - (Input) desired co-ordinates {mm} +% hFxyz - handle of XYZ control - the frame containing the edit widgets +% hC - handle of calling object, if used as a callback. [Default 0] +% xyz - (Output) Desired co-ordinates are rounded to nearest voxel if hC +% is not specified, or is zero. Otherwise, caller is assumed to +% have checked verity of desired xyz co-ordinates. Output xyz returns +% co-ordinates actually set {mm}. +% d - Euclidean distance between desired and set co-ordinates. +% NB: When using the results section, should use XYZregistry to get/set location +% +% FORMAT hFxyz = cat_spm_results_ui('FindXYZframe',h) +% Find/check XYZ edit widgets frame handle, 'Tag'ged 'hFxyz' +% h - handle of frame enclosing widgets, or containing figure [default gcf] +% If ischar(h), then uses spm_figure('FindWin',h) to locate named figures +% hFxyz - handle of confirmed XYZ editable widgets control +% Errors if hFxyz is not an XYZ widget control, or a figure containing +% a unique such control +% +% FORMAT cat_spm_results_ui('PlotUi',hAx) +% GUI for adjusting plot attributes - Sets up controls just above results GUI +% hAx - handle of axes to work with +% +% FORMAT cat_spm_results_ui('PlotUiCB') +% CallBack handler for Plot attribute GUI +% +% FORMAT Fgraph = cat_spm_results_ui('Clear',F,mode) +% Clears results subpane of Graphics window, deleting all but semi-permanent +% results section stuff +% F - handle of Graphics window [Default spm_figure('FindWin','Graphics')] +% mode - 1 [default] - clear results subpane +% - 0 - clear results subpane and hide results stuff +% - 2 - clear, but respect 'NextPlot' 'add' axes +% (which is set by `hold on`) +% Fgraph - handle of Graphics window +% +% FORMAT hMP = cat_spm_results_ui('LaunchMP',M,DIM,hReg,hBmp) +% Prototype callback handler for integrating MultiPlanar toolbox +% +% FORMAT cat_spm_results_ui('Delete',h) +% deletes HandleGraphics objects, but only if they're valid, thus avoiding +% warning statements from MATLAB. +% +% modified version of +% spm_results_ui.m r7388 +%__________________________________________________________________________ + +%-Condition arguments +%-------------------------------------------------------------------------- +if nargin == 0 + Action='Setup'; +elseif nargin == 1 && isstruct(varargin{1}) + cat_spm_run_results(varargin{1}); + varargout = {[],[],[]}; + return +else + Action=varargin{1}; +end +useCAT = 2; % 0-like SPM, 1-surface handling, 2-cat_surf_renderer + +global result_ui_varargout use_tfce mesh_detect + +% prevent that TFCE is called if not yet installed +if ~exist(fullfile(fileparts(fileparts(mfilename('fullpath'))),'TFCE'),'dir') + use_tfce = 0; +end + +%========================================================================== +switch lower(Action), case 'setup' %-Set up results +%========================================================================== + + %-Initialise + %---------------------------------------------------------------------- + spm('FnBanner',mfilename); + try + dcm = datacursormode(spm_figure('FindWin','Graphics')); + set(dcm,'Enable','off','UpdateFcn',[]); + + spm_figure('Clear',spm_figure('FindWin','Graphics')); + end + [Finter,Fgraph,CmdLine] = spm('FnUIsetup','Stats: Results'); + spm_clf('Satellite'); + + %-Get thresholded xSPM data and parameters of design + %====================================================================== + if nargin > 1 + if use_tfce + [SPM,xSPM] = tfce_getSPM(varargin{2}); + else + [SPM,xSPM] = spm_getSPM(varargin{2}); + end + else + if exist(fullfile(fileparts(fileparts(mfilename('fullpath'))),'TFCE'),'dir') + [spmmatfile, sts] = spm_select(1,'^SPM\.mat$','Select SPM.mat'); + swd = spm_file(spmmatfile,'fpath'); + cd(swd) + warning off + load('SPM.mat','SPM','xSPM'); + warning on + + [Ic,xCon] = spm_conman(SPM,'T&F',Inf,' Select contrast(s)...','',1); + if ~isempty(xCon(Ic).Vspm) + [pth,nam,xt] = fileparts(xCon(Ic).Vspm.fname); + xCon(Ic).Vspm = spm_data_hdr_read(fullfile(swd,[nam xt])); + end + SPM.Ic = Ic; SPM.xCon = xCon; + SPM.swd = swd; + + % data or analysis moved or data are on a different computer? + if isfield(SPM.xVol,'G') && ischar(SPM.xVol.G) + if ~exist(SPM.xVol.G,'file') + [pp2,ff2,xx2] = spm_fileparts(SPM.xVol.G); + if ~isempty(strfind(ff2,'.central.freesurfer')) || (exist('cat_get_defaults','file')) && (~isempty(strfind(ff2,['.central.' cat_get_defaults('extopts.shootingsurf')]))) + if strfind(pp2,'templates_surfaces_32k') + SPM.xVol.G = fullfile(fileparts(mfilename('fullpath')),'templates_surfaces_32k',[ff2 xx2]); + else + SPM.xVol.G = fullfile(fileparts(mfilename('fullpath')),'templates_surfaces',[ff2 xx2]); + end + end + % modified SPM.mat hast to be saved + fmt = spm_get_defaults('mat.format'); + s = whos('SPM'); + if s.bytes > 2147483647, fmt = '-v7.3'; end + save(fullfile(swd,'SPM.mat'),'SPM',fmt); + end + end + + % check for existing TFCE results for this contrast + if numel(Ic)==1 && (exist(fullfile(swd,sprintf('%s_log_p_%04d.nii',xCon(Ic).STAT,Ic))) || ... + exist(fullfile(swd,sprintf('%s_log_p_%04d.gii',xCon(Ic).STAT,Ic)))) + stat_str = {'TFCE',xCon(Ic).STAT}; + statType = spm_input('Type of statistic',1,'m',... + sprintf('TFCE (non-parametric)|%s (non-parametric)|%s (SPM parametric)',... + xCon(Ic).STAT,xCon(Ic).STAT),[],1); + if statType < 3 + use_tfce = 1; + SPM.statType = stat_str{statType}; + [SPM,xSPM] = tfce_getSPM(SPM); + xSPM.statType = stat_str{statType}; + else + use_tfce = 0; + [SPM,xSPM] = spm_getSPM(SPM); + xSPM.statType = xCon(Ic).STAT; + end + else + use_tfce = 0; + [SPM,xSPM] = spm_getSPM(SPM); + xSPM.statType = xCon(Ic).STAT; + end + else + if nargin > 1 + [SPM,xSPM] = spm_getSPM(varargin{2}); + else + [SPM,xSPM] = spm_getSPM; + end + end + end + + if isempty(xSPM) + varargout = {[],[],[]}; + return; + end + + if ~use_tfce + xSPM.invResult = 0; + end + + if spm_mesh_detect(xSPM.Vspm) + mesh_detect = 1; + else + mesh_detect = 0; + end + + %-Ensure pwd = swd so that relative filenames are valid + %---------------------------------------------------------------------- + cd(SPM.swd) + + %-Get space information + %====================================================================== + M = SPM.xVol.M; + DIM = SPM.xVol.DIM; + + %-Space units + %---------------------------------------------------------------------- + try + try + units = SPM.xVol.units; + catch + units = xSPM.units; + end + catch + try + Modality = spm('CheckModality'); + catch + Modality = {'PET','FMRI','EEG'}; + selected = spm_input('Modality: ','+1','m',Modality); + Modality = Modality{selected}; + spm('ChMod',Modality); + end + if strcmp(Modality,'EEG') + datatype = {... + 'Volumetric (2D/3D)',... + 'Scalp-Time',... + 'Scalp-Frequency',... + 'Time-Frequency',... + 'Frequency-Frequency'}; + selected = spm_input('Data Type: ','+1','m',datatype); + datatype = datatype{selected}; + else + datatype = 'Volumetric (2D/3D)'; + end + + switch datatype + case 'Volumetric (2D/3D)' + units = {'mm' 'mm' 'mm'}; + case 'Scalp-Time' + units = {'mm' 'mm' 'ms'}; + case 'Scalp-Frequency' + units = {'mm' 'mm' 'Hz'}; + case 'Time-Frequency' + units = {'Hz' 'ms' ''}; + case 'Frequency-Frequency' + units = {'Hz' 'Hz' ''}; + otherwise + error('Unknown data type.'); + end + end + + + % CAT.begin + % ------------------------------------------------------------------------- + % ToDo: + % * add batch call with render settings > cat_conf_stools + % * add atlas data coursor > cat_surf_render + % * add colorbar > cat_surf_render + % * fix contrast box boundaries + % * full atlas integration > spm_atlas, spm_XYZreg, spm_list (lot of work) + % ------------------------------------------------------------------------- + if useCAT + [pp,ff,ee] = spm_fileparts(xSPM.Vspm.fname); + if strcmp(ee,'.gii') + datatype = 'Surface (3D)'; + % units = {'mm' 'mm'}; + end + + % change surface ? + % - first we have to use the Shooting Surface for the statistic to + % obtain more meaningful MNI coordinates + % - here we have to change to the used surface (FSaverage) + if spm_mesh_detect(xSPM.Vspm) && exist('spm_cat12') && exist('cat_get_defaults','file') + FSavg = '.freesurfer.gii'; + GSavg = ['.' cat_get_defaults('extopts.shootingsurf') '.gii']; + if ischar(SPM.xVol.G) + SPM.xVol.G = strrep(SPM.xVol.G,GSavg,FSavg); + end + end + + % change coordinates to spherial ?? + %XYZmmFS = xSPM. + + end + % ------------------------------------------------------------------------- + % CAT.end + + if spm_mesh_detect(xSPM.Vspm) + DIM(3) = Inf; % force 3D coordinates + elseif DIM(3) == 1 + units{3} = ''; + if DIM(2) == 1 + units{2} = ''; + end + end + xSPM.units = units; + SPM.xVol.units = units; + + + %-Setup Results User Interface; Display MIP, design matrix & parameters + %====================================================================== + + %-Setup results GUI + %---------------------------------------------------------------------- + spm_clf(Finter); + spm('FigName',['SPM{',xSPM.STAT,'}: Results'],Finter,CmdLine); + hReg = cat_spm_results_ui('SetupGUI',M,DIM,xSPM,Finter); + + %-Setup design interrogation menu + %---------------------------------------------------------------------- + hDesRepUI = spm_DesRep('DesRepUI',SPM); + + %-Setup contrast menu + %---------------------------------------------------------------------- + hConUI = cat_spm_results_ui('SetupConMenu',xSPM,SPM,Finter); + + %-Atlas menu + %---------------------------------------------------------------------- + if ~spm_mesh_detect(xSPM.Vspm) && exist('cat_get_defaults','file') + hAtlasUI = cat_spm_results_ui('SetupAtlasMenu',Finter); + end + + %-Setup Maximum intensity projection (MIP) & register + %---------------------------------------------------------------------- + FS = spm('FontSizes'); + hMIPax = axes('Parent',Fgraph,'Position',[0.05 0.60 0.55 0.36],'Visible','off'); + if spm_mesh_detect(xSPM.Vspm) + tmp = zeros(1,prod(xSPM.DIM)); + tmp(xSPM.XYZ(1,:)) = xSPM.Z; + % block to call cat_surf_render rather than spm_mesh_render + if useCAT>1 & exist('cat_surf_render') + hMax = cat_surf_render('Disp',SPM.xVol.G,'Parent',hMIPax,'Results',1); + hMax = cat_surf_render('Overlay',hMax,tmp); + hMax = cat_surf_render('ColourMap',hMax,jet); + hMax = cat_surf_render('Register',hMax,hReg); + else + hMax = spm_mesh_render('Disp',SPM.xVol.G,'Parent',hMIPax); + hMax = spm_mesh_render('Overlay',hMax,tmp); + hMax = spm_mesh_render('Register',hMax,hReg); + hMax = spm_mesh_render('ColourMap',hMax,jet); + hMax = spm_mesh_render('View',hMax,'top'); + end + elseif isequal(units(2:3),{'' ''}) + set(hMIPax, 'Position',[0.05 0.65 0.55 0.25]); + [allS,allXYZmm] = spm_read_vols(xSPM.Vspm); + plot(hMIPax,allXYZmm(1,:),allS,'Color',[0.6 0.6 0.6]); + set(hMIPax,'NextPlot','add'); + MIP = NaN(1,xSPM.DIM(1)); + MIP(xSPM.XYZ(1,:)) = xSPM.Z; + XYZmm = xSPM.M(1,:)*[1:xSPM.DIM(1);zeros(2,xSPM.DIM(1));ones(1,xSPM.DIM(1))]; + plot(hMIPax,XYZmm,MIP,'b-+','LineWidth',2); + plot(hMIPax,[XYZmm(1) XYZmm(end)],[xSPM.u xSPM.u],'r'); + clim = get(hMIPax,'YLim'); + axis(hMIPax,[sort([XYZmm(1) XYZmm(end)]) 0 clim(2)]); + %set(hMIPax,'XTick',[],'YTick',[]); + else + hMIPax = spm_mip_ui(xSPM.Z,xSPM.XYZmm,M,DIM,hMIPax,units); + spm_XYZreg('XReg',hReg,hMIPax,'spm_mip_ui'); + end + + if xSPM.STAT == 'P' + str = xSPM.STATstr; + else + str = ['SPM\{',xSPM.STATstr,'\}']; + end + text(240,260,str,... + 'Interpreter','TeX',... + 'FontSize',FS(14),'Fontweight','Bold',... + 'Parent',hMIPax) + + + %-Print comparison title + %---------------------------------------------------------------------- + hTitAx = axes('Parent',Fgraph,... + 'Position',[0.02 0.96 0.96 0.04],... + 'Visible','off'); + + text(0.5,0.5,xSPM.title,'Parent',hTitAx,... + 'HorizontalAlignment','center',... + 'VerticalAlignment','top',... + 'FontWeight','Bold','FontSize',FS(14)) + + + %-Print SPMresults: Results directory & thresholding info + %---------------------------------------------------------------------- + hResAx = axes('Parent',Fgraph,... + 'Position',[0.05 0.55 0.45 0.05],... + 'DefaultTextVerticalAlignment','baseline',... + 'DefaultTextFontSize',FS(9),... + 'DefaultTextColor',[1,1,1]*.7,... + 'Units','Pixel',... + 'Visible','off'); + AxPos = get(hResAx,'Position'); set(hResAx,'YLim',[0,AxPos(4)]) + h = text(0,24,'SPMresults:','Parent',hResAx,... + 'FontWeight','Bold','FontSize',FS(14)); + text(get(h,'Extent')*[0;0;1;0],24,spm_file(SPM.swd,'short30'),'Parent',hResAx) + + try + thresDesc = xSPM.thresDesc; + if use_tfce + text(0,12,sprintf('Height threshold %s',thresDesc),'Parent',hResAx) + else + if strcmp(xSPM.STAT,'P') + text(0,12,sprintf('Height threshold %s',thresDesc),'Parent',hResAx) + else + text(0,12,sprintf('Height threshold %c = %0.6f {%s}',xSPM.STAT,xSPM.u,thresDesc),'Parent',hResAx) + end + end + catch + text(0,12,sprintf('Height threshold %c = %0.6f',xSPM.STAT,xSPM.u),'Parent',hResAx) + end + if spm_mesh_detect(xSPM.Vspm), str = 'vertices'; else str = 'voxels'; end + text(0,00,sprintf('Extent threshold k = %0.0f %s',xSPM.k,str), 'Parent',hResAx) + + + %-Plot design matrix + %---------------------------------------------------------------------- + hDesMtx = axes('Parent',Fgraph,'Position',[0.65 0.55 0.25 0.25]); + hDesMtxIm = image((SPM.xX.nKX + 1)*32,'Parent',hDesMtx); + xlabel(hDesMtx,'Design matrix','FontSize',FS(10)) + set(hDesMtxIm,'ButtonDownFcn','spm_DesRep(''SurfDesMtx_CB'')',... + 'UserData',struct(... + 'X', SPM.xX.xKXs.X,... + 'fnames', {reshape({SPM.xY.VY.fname},size(SPM.xY.VY))},... + 'Xnames', {SPM.xX.name})) + + %-Plot contrasts + %---------------------------------------------------------------------- + nPar = size(SPM.xX.X,2); + xx = [repmat([0:nPar-1],2,1);repmat([1:nPar],2,1)]; + nCon = length(xSPM.Ic); + xCon = SPM.xCon; + if nCon + dy = 0.15/max(nCon,2); + hConAx = axes('Parent',Fgraph, 'Position',[0.65 (0.80 + dy*.1) 0.25 dy*(nCon-.1)],... + 'Tag','ConGrphAx','Visible','off'); + if use_tfce & xSPM.invResult + str = 'inverse contrast'; + else + str = 'contrast'; + end + if nCon > 1, str = [str 's']; end + title(hConAx,str) + htxt = get(hConAx,'title'); + set(htxt,'FontSize',FS(10),'FontWeight','normal','Visible','on','HandleVisibility','on') + end + + for ii = nCon:-1:1 + hCon = axes('Parent',Fgraph, 'Position',[0.65 (0.80 + dy*(nCon - ii +.1)) 0.25 dy*.9]); + if xCon(xSPM.Ic(ii)).STAT == 'T' && size(xCon(xSPM.Ic(ii)).c,2) == 1 + + %-Single vector contrast for SPM{t} - bar + %-------------------------------------------------------------- + yy = [zeros(1,nPar);repmat(xCon(xSPM.Ic(ii)).c',2,1);zeros(1,nPar)]; + if use_tfce & xSPM.invResult, yy = -yy; end + h = patch(xx,yy,[1,1,1]*.5,'Parent',hCon); + set(hCon,'Tag','ConGrphAx',... + 'Box','off','TickDir','out',... + 'XTick',spm_DesRep('ScanTick',nPar,10) - 0.5,'XTickLabel','',... + 'XLim', [0,nPar],... + 'YTick',[-1,0,+1],'YTickLabel','',... + 'YLim',[min(xCon(xSPM.Ic(ii)).c),max(xCon(xSPM.Ic(ii)).c)] +... + [-1 +1] * max(abs(xCon(xSPM.Ic(ii)).c))/10 ) + + else + + %-F-contrast - image + %-------------------------------------------------------------- + h = image((xCon(xSPM.Ic(ii)).c'/max(abs(xCon(xSPM.Ic(ii)).c(:)))+1)*32,... + 'Parent',hCon); + set(hCon,'Tag','ConGrphAx',... + 'Box','on','TickDir','out',... + 'XTick',spm_DesRep('ScanTick',nPar,10),'XTickLabel','',... + 'XLim', [0,nPar]+0.5,... + 'YTick',[0:size(SPM.xCon(xSPM.Ic(ii)).c,2)]+0.5,... + 'YTickLabel','',... + 'YLim', [0,size(xCon(xSPM.Ic(ii)).c,2)]+0.5 ) + + end + ylabel(hCon,num2str(xSPM.Ic(ii)),'FontSize',FS(10),'FontWeight','normal') + set(h,'ButtonDownFcn','spm_DesRep(''SurfCon_CB'')',... + 'UserData', struct( 'i', xSPM.Ic(ii),... + 'h', htxt,... + 'xCon', xCon(xSPM.Ic(ii)))) + end + + + %-Store handles of results section Graphics window objects + %---------------------------------------------------------------------- + H = get(Fgraph,'Children'); + H = findobj(H,'flat','HandleVisibility','on'); + H = findobj(H); + Hv = get(H,'Visible'); + set(hResAx,'Tag','PermRes','UserData',struct('H',H,'Hv',{Hv})) + + + TabDat = call_list('List',xSPM,hReg); + + %-Finished results setup + %---------------------------------------------------------------------- + varargout = {hReg,xSPM,SPM,TabDat}; + spm('Pointer','Arrow') + + + + +% ------------------------------------------------------------------------- +% This block is required for postprocessing the SPM result figure. +% It include fixes to avoid rotation of non 3D elements and some other tiny +% changes to the contrast & design matrix. + + if isfield(xSPM,'G') + % create SPM result table and fix elements to avoid rotation of tables + if use_tfce + tfce_list('List',xSPM,hReg); + else + spm_list_cleanup; + end + + % corrections for top elements + hRes.Fgraph = spm_figure('GetWin','Graphics'); + hRes.FgraphC = get( hRes.Fgraph ,'children'); + hRes.FgraphAx = findobj( hRes.FgraphC,'Type','Axes'); + hRes.FgraphAxPos = cell2mat(get( hRes.FgraphAx , 'Position')); + hRes.Ftext = findobj(hRes.Fgraph,'Type','Text'); + % fine red lines of the SPM result table + hRes.Fline = findobj(hRes.Fgraph,'Type','Line','Tag','');% ,'UIcontextMenu',[]); + hRes.FlineAx = get(hRes.Fline,'parent'); + + % find the SPM result texts to fix them against rotation + hres.Ftext = findobj(hRes.Fgraph,'Type','Text','Color',[0.7 0.7 0.7]); + hRes.Ftext3dres = get( hres.Ftext ,'parent'); + % for axi=1:numel(hRes.Ftext), set( hRes.Ftext(axi),'Color',[0.2 0.2 0.2]); end + for axi = 1:numel(hRes.Ftext3dres), set( hRes.Ftext3dres{axi},'HitTest','off'); end + for axi = 1:numel(hRes.FlineAx ), set( hRes.FlineAx{axi},'visible','off'); end + + % make nice contrast box that is a bit larger than the original boxes + hRes.Fcons = hRes.FgraphAx( hRes.FgraphAxPos(:,1) == 0.65 & hRes.FgraphAxPos(:,2) > 0.6 ) ; + for axi = 1:numel( hRes.Fcons ), l = get( hRes.Fcons(axi) , 'ylim'); set(hRes.Fcons(axi) , 'box','on','ylim', round(l) + [-0.015 0.015]); end + + % remove non integer values + hRes.Fdesm = hRes.FgraphAx( hRes.FgraphAxPos(:,1) == 0.65 & hRes.FgraphAxPos(:,2) < 0.6 ) ; + xt = get(hRes.Fdesm,'xtick'); xt(round(xt)~=xt) = []; set(hRes.Fdesm,'xtick',xt); + + % + hRes.Fval = hRes.FgraphAx( hRes.FgraphAxPos(:,1) > 10); + hRes.Fsurf = hRes.FgraphAx( hRes.FgraphAxPos(:,1) == 0.05); + hRes.Flabels = [ hRes.FgraphAx( hRes.FgraphAxPos(:,1) == 0.65); hRes.FgraphAx( hRes.FgraphAxPos(:,1) == 0.02)]; + for axi = 1:numel( hRes.Flabels ), set(hRes.Flabels(axi),'HitTest','off'); end + + if nargout==0, + fprintf( ... + ['\n' ... + '========================================================================\n' ... + ' You have to call cat_spm_results_ui with all output parameters: \n' ... + ' [hReg,xSPM,SPM] = cat_spm_results_ui; \n\n' ... + ' Otherwise, the menu and tables will not work properly! Call now: \n %s\n'... + '========================================================================\n\n'], ... + spm_file('[hReg,xSPM,SPM] = cat_spm_results_ui(''Output'');',... + 'link','[hReg,xSPM,SPM] = cat_spm_results_ui(''Output'');')); + + result_ui_varargout = varargout; + clear varargout; + end + end +% ------------------------------------------------------------------------- + + %====================================================================== + case 'output' %-Set up results section GUI + %====================================================================== + fprintf('Updated result_ui output.\n'); + varargout = result_ui_varargout; + + %====================================================================== + case 'setupgui' %-Set up results section GUI + %====================================================================== + % hReg = cat_spm_results_ui('SetupGUI',M,DIM,xSPM,Finter) + if nargin < 5, Finter='Interactive'; else Finter = varargin{5}; end + if nargin < 4, error('Insufficient arguments'), end + M = varargin{2}; + DIM = varargin{3}; + xSPM = varargin{4}; + Finter = spm_figure('GetWin',Finter); + WS = spm('WinScale'); + FS = spm('FontSizes'); + + %-Create frame for Results GUI objects + %------------------------------------------------------------------ + hPan = uipanel('Parent',Finter,'Title','','Units','Pixels',... + 'Position',[001 001 400 190].*WS,... + 'BorderType','Line', 'HighlightColor',[0 0 0],... + 'BackgroundColor',spm('Colour')); + hReg = uipanel('Parent',hPan,'Title','','Units','Pixels',... + 'BorderType','Etchedin', ... + 'Position',[005 005 390 180].*WS,... + 'BackgroundColor',[179 179 179]/255); + + %-Initialise registry in hReg frame object + %------------------------------------------------------------------ + [hReg,xyz] = spm_XYZreg('InitReg',hReg,M,DIM,[0;0;0]); + + %-Setup editable XYZ widgets & cross register with registry + %------------------------------------------------------------------ + hFxyz = cat_spm_results_ui('DrawXYZgui',M,DIM,varargin{4},xyz,hReg); + spm_XYZreg('XReg',hReg,hFxyz,'cat_spm_results_ui'); + + %-Set up buttons for results functions + %------------------------------------------------------------------ + cat_spm_results_ui('DrawButts',hReg,DIM,xSPM,Finter,WS,FS); + + if spm_check_version('matlab','7.11') ~= 0 + drawnow; % required to force ""ratio locking"" + set(findobj(hPan),'Units','Normalized','FontUnits','Normalized'); + end + + varargout = {hReg}; + + %====================================================================== + case 'drawbutts' %-Draw results section buttons in Interactive window + %====================================================================== + % cat_spm_results_ui('DrawButts',hReg,DIM,xSPM,Finter,WS,FS) + % + if nargin < 4, error('Insufficient arguments'), end + hReg = varargin{2}; + DIM = varargin{3}; + xSPM = varargin{4}; + if nargin < 5, Finter = spm_figure('FindWin','Interactive'); + else Finter = varargin{5}; end + if nargin < 6, WS = spm('WinScale'); else WS = varargin{6}; end + if nargin < 7, FS = spm('FontSizes'); else FS = varargin{7}; end + + %-p-values + %------------------------------------------------------------------ + hPan = uipanel('Parent',hReg,'Title','p-values','Units','Pixels',... + 'Position',[005 085 110 092].*WS,... + 'BorderType','Beveledout', ... + 'ShadowColor',[0.5 0.5 0.5],... + 'FontAngle','Italic',... + 'FontSize',FS(10),... + 'ForegroundColor',[1 1 1],... + 'BackgroundColor',[179 179 179]/255); + if use_tfce + callback = 'TabDat = tfce_list(''List'',xSPM,hReg);cat_spm_results_ui(''spm_list_cleanup'',hReg);'; + else + callback = 'TabDat = spm_list(''List'',xSPM,hReg);cat_spm_results_ui(''spm_list_cleanup'',hReg);'; + end + uicontrol('Parent',hPan,'Style','PushButton','String','whole brain',... + 'Units','Pixels',... + 'FontSize',FS(10),... + 'ToolTipString',... + 'Tabulate summary of local maxima, p-values & statistics',... + 'Callback',callback,... + 'Interruptible','on','Enable','on',... + 'Position',[005 055 100 020].*WS); + if use_tfce + callback = 'TabDat = tfce_list(''ListCluster'',xSPM,hReg);cat_spm_results_ui(''spm_list_cleanup'',hReg);'; + else + callback = 'TabDat = spm_list(''ListCluster'',xSPM,hReg);cat_spm_results_ui(''spm_list_cleanup'',hReg);'; + end + uicontrol('Parent',hPan,'Style','PushButton','String','current cluster',... + 'Units','Pixels',... + 'FontSize',FS(10),... + 'ToolTipString',... + 'Tabulate p-values & statistics for local maxima of nearest cluster',... + 'Callback',callback,... + 'Interruptible','off','Enable','on',... + 'Position',[005 030 100 020].*WS); + + + %-SPM area - used for Volume of Interest analyses + %------------------------------------------------------------------ + if spm_mesh_detect(xSPM.Vspm) + Enable = 'off'; + else + Enable = 'on'; + end + + if ~use_tfce + uicontrol('Parent',hPan,'Style','PushButton','String','small volume',... + 'Units','Pixels',... + 'FontSize',FS(10),... + 'ToolTipString',['Small Volume Correction - corrected p-values ',... + 'for a small search region'],... + 'Callback','TabDat = spm_VOI(SPM,xSPM,hReg);',... + 'Interruptible','off','Enable',Enable,... + 'Position',[005 005 100 020].*WS); + end + + hPan = uipanel('Parent',hReg,'Title','Multivariate','Units','Pixels',... + 'Position',[120 085 150 092].*WS,... + 'BorderType','Beveledout', ... + 'ShadowColor',[0.5 0.5 0.5],... + 'FontAngle','Italic',... + 'FontSize',FS(10),... + 'ForegroundColor',[1 1 1],... + 'BackgroundColor',[179 179 179]/255); + uicontrol('Parent',hPan,'Style','PushButton','String','eigenvariate',... + 'Position',[005 055 069 020].*WS,... + 'ToolTipString',... + 'Responses (principal eigenvariate) in volume of interest',... + 'Callback','[Y,xY] = spm_regions(xSPM,SPM,hReg)',... + 'Interruptible','on','Enable',Enable,... + 'FontSize',FS(10)); + uicontrol('Parent',hPan,'Style','PushButton','String','CVA',... + 'Position',[076 055 069 020].*WS,... + 'ToolTipString',... + 'Canonical variates analysis for the current contrast and VOI',... + 'Callback','CVA = spm_cva_ui('''',xSPM,SPM)',... + 'Interruptible','off','Enable',Enable,... + 'FontSize',FS(10)); + + + %-Visualisation + %------------------------------------------------------------------ + hPan = uipanel('Parent',hReg,'Title','Display','Units','Pixels',... + 'Position',[275 085 110 092].*WS,... + 'BorderType','Beveledout',... + 'ShadowColor',[0.5 0.5 0.5],... + 'FontAngle','Italic',... + 'FontSize',FS(10),... + 'ForegroundColor',[1 1 1],... + 'BackgroundColor',[179 179 179]/255); + uicontrol('Parent',hPan,'Style','PushButton','String','plot',... + 'FontSize',FS(10),... + 'ToolTipString','plot data & contrasts at current voxel',... + 'Callback','[Y,y,beta,Bcov] = spm_graph_ui(xSPM,SPM,hReg);',... + 'Interruptible','on','Enable','on',... + 'Position',[005 055 100 020].*WS,... + 'Tag','plotButton'); + + str0 = {'overlays...',... + 'slices', ... + 'sections', ... + 'CAT-T1 (IXI555 GS)', ... + 'montage',... + 'render',... + 'previous sections',... + 'previous render'}; + tstr0 = { 'overlay filtered SPM on another image: ',... + '3 slices / ',... + 'slice overlay /', ... + 'T1 avg slice overlay /', ... + 'ortho sections / ', ... + 'render /', ... + 'previous ortho sections /', ... + 'previous surface rendering'}; + + if exist('cat_get_defaults','file') + str4 = ['spm_sections(xSPM,hReg,char(cat_get_defaults(''extopts.shootingT1'')));',... + 'cat_spm_results_ui(''spm_list_cleanup'');',]; + else + str4 = ''; + end + tmp0 = {'spm_transverse(''set'',xSPM,hReg)',... + 'spm_sections(xSPM,hReg);',... + str4,... + {@myslover},... + ['spm_render( struct( ''XYZ'', xSPM.XYZ,',... + '''t'', xSPM.Z'',',... + '''mat'', xSPM.M,',... + '''dim'', xSPM.DIM))'],... + ['global prevsect;','spm_sections(xSPM,hReg,prevsect);'],... + ['global prevrend;','if ~isstruct(prevrend)',... + 'prevrend = struct(''rendfile'','''',''brt'',[],''col'',[]); end;',... + 'spm_render( struct( ''XYZ'', xSPM.XYZ,',... + '''t'', xSPM.Z'',',... + '''mat'', xSPM.M,',... + '''dim'', xSPM.DIM),prevrend.brt,prevrend.rendfile)']}; + + if spm_mesh_detect(xSPM.Vspm) + ind = [1 3 7]; + else + ind = [1:3 5:numel(str0)]; + end + + % add average image only if cat12 exists + if exist('spm_cat12') + ind = sort([ind 4]); + end + + % select entries + str = str0(ind); + tstr = tstr0(ind); + tmp = tmp0(ind(2:end)-1); + + uicontrol('Parent',hPan,'Style','popupmenu','String',str,... + 'FontSize',FS(10),... + 'ToolTipString',cat(2,tstr{:}),... + 'Callback','spm(''PopUpCB'',gcbo)',... + 'UserData',tmp,... + 'Interruptible','on','Enable','on',... + 'Position',[005 030 100 020].*WS); + + str = {'save...',... + 'thresholded SPM',... + 'all clusters (binary)',... + 'all clusters (n-ary)',... + 'current cluster'}; + tmp = {{@mysavespm, 'thresh' },... + {@mysavespm, 'binary' },... + {@mysavespm, 'n-ary' },... + {@mysavespm, 'current'}}; + + uicontrol('Parent',hPan,'Style','popupmenu','String',str,... + 'FontSize',FS(10),... + 'ToolTipString','Save as image',... + 'Callback','spm(''PopUpCB'',gcbo)',... + 'UserData',tmp,... + 'Interruptible','on','Enable','on',... + 'Position',[005 005 100 020].*WS); + + %-ResultsUI controls + %------------------------------------------------------------------ + uicontrol('Parent',hReg,'Style','PushButton','String','clear',... + 'ToolTipString','Clear results subpane',... + 'FontSize',FS(9),'ForegroundColor','r',... + 'Callback',['cat_spm_results_ui(''Clear''); ',... + 'spm_input(''!DeleteInputObj''),',... + 'spm_clf(''Satellite'')'],... + 'Interruptible','on','Enable','on',... + 'DeleteFcn','spm_clf(''Graphics'')',... + 'Position',[280 050 048 020].*WS); + + uicontrol('Parent',hReg,'Style','PushButton','String','exit',... + 'ToolTipString','Exit the results section',... + 'FontSize',FS(9),'ForegroundColor','r',... + 'Callback','cat_spm_results_ui(''close'')',... + 'Interruptible','on','Enable','on',... + 'Position',[332 050 048 020].*WS); + + + %====================================================================== + case 'setupconmenu' %-Setup Contrast Menu + %====================================================================== + % cat_spm_results_ui('SetupConMenu',xSPM,SPM,Finter) + if nargin < 4, Finter = 'Interactive'; else Finter = varargin{4}; end + if nargin < 3, error('Insufficient arguments'), end + xSPM = varargin{2}; + SPM = varargin{3}; + Finter = spm_figure('GetWin',Finter); + hC = uimenu(Finter,'Label','Contrasts', 'Tag','ContrastsUI'); + + if use_tfce + hC1 = uimenu(hC,'Label','Change Contrast'); + + for i=1:numel(SPM.xCon) + % check whether TFCE results were found + if exist(fullfile(SPM.swd,sprintf('%s_log_p_%04d.nii',xSPM.STAT,i))) || ... + exist(fullfile(SPM.swd,sprintf('%s_log_p_%04d.gii',xSPM.STAT,i))) + xSPM2 = xSPM; + xSPM2.invResult = 0; + hC2 = uimenu(hC1,'Label',[SPM.xCon(i).STAT, ': ', SPM.xCon(i).name], ... + 'UserData',struct('Ic',i),... + 'Callback',{@mychgcon,xSPM2}); + if any(xSPM.Ic == i) & ~xSPM.invResult + set(hC2,'ForegroundColor',[0 0 1],'Checked','on'); + end + % only add inverse contrasts for T-test + if SPM.xCon(i).STAT == 'T' + xSPM2 = xSPM; + xSPM2.invResult = 1; + hC3 = uimenu(hC1,'Label',['(inverse contrast) ',SPM.xCon(i).STAT, ': ', SPM.xCon(i).name], ... + 'UserData',struct('Ic',i),... + 'Callback',{@mychgcon,xSPM2}); + if any(xSPM.Ic == i) & xSPM.invResult + set(hC3,'ForegroundColor',[0 0 1],'Checked','on'); + end + end + end + end + else + hC1 = uimenu(hC,'Label','New Contrast...',... + 'UserData',struct('Ic',0),... + 'Callback',{@mychgcon,xSPM}); + hC1 = uimenu(hC,'Label','Change Contrast'); + for i=1:numel(SPM.xCon) + hC2 = uimenu(hC1,'Label',[SPM.xCon(i).STAT, ': ', SPM.xCon(i).name], ... + 'UserData',struct('Ic',i),... + 'Callback',{@mychgcon,xSPM}); + if any(xSPM.Ic == i) + set(hC2,'ForegroundColor',[0 0 1],'Checked','on'); + end + end + hC1 = uimenu(hC,'Label','Previous Contrast',... + 'Accelerator','P',... + 'UserData',struct('Ic',xSPM.Ic-1),... + 'Callback',{@mychgcon,xSPM}); + if xSPM.Ic-1<1, set(hC1,'Enable','off'); end + hC1 = uimenu(hC,'Label','Next Contrast',... + 'Accelerator','N',... + 'UserData',struct('Ic',xSPM.Ic+1),... + 'Callback',{@mychgcon,xSPM}); + if xSPM.Ic+1>numel(SPM.xCon), set(hC1,'Enable','off'); end + end + + hC1 = uimenu(hC,'Label','Significance level','Separator','on'); + xSPMtmp = xSPM; xSPMtmp.thresDesc = ''; + uimenu(hC1,'Label','Change...','UserData',struct('Ic',xSPM.Ic),... + 'Callback',{@mychgcon,xSPMtmp}); + + if strcmp(xSPM.STAT,'P') + xSPMtmp = xSPM; xSPMtmp.thresDesc = 'LogBF'; + uimenu(hC1,'Label','Set LogBF','UserData',struct('Ic',xSPM.Ic),... + 'Callback',{@mychgcon,xSPMtmp}); + else + xSPMtmp = xSPM; xSPMtmp.thresDesc = 'p<0.05 (FWE)'; + uimenu(hC1,'Label','Set to 0.05 (FWE)','UserData',struct('Ic',xSPM.Ic),... + 'Callback',{@mychgcon,xSPMtmp}); + xSPMtmp = xSPM; xSPMtmp.thresDesc = 'p<0.001 (unc.)'; + uimenu(hC1,'Label','Set to 0.001 (unc.)','UserData',struct('Ic',xSPM.Ic),... + 'Callback',{@mychgcon,xSPMtmp}); + end + + uimenu(hC1,'Label',[xSPM.thresDesc ', k=' num2str(xSPM.k)],... + 'Enable','off','Separator','on'); + + hC1 = uimenu(hC,'Label','Default cluster listings in result table',... + 'Separator','on',... + 'Callback',{@mycluster,xSPM,8,3}); + + hC1 = uimenu(hC,'Label','Detailed cluster listings in result table',... + 'Separator','off',... + 'Callback',{@mycluster,xSPM,4,16}); + + hC1 = uimenu(hC,'Label','Multiple display...',... + 'Separator','on',... + 'Callback',{@mycheckres,xSPM}); + + varargout = {hC}; + + + %====================================================================== + case 'setupatlasmenu' %-Setup Atlas Menu + %====================================================================== + % cat_spm_results_ui('SetupAtlasMenu',Finter) + + Finter = varargin{2}; + + %hC = uicontextmenu; + hC = uimenu(Finter,'Label','Atlas', 'Tag','AtlasUI'); + + hC1 = uimenu(hC,'Label','Label using'); + + list = spm_atlas('List','installed'); + + [csv_files, n_csv] = cat_vol_findfiles(cat_get_defaults('extopts.pth_templates'), '*.csv'); + if numel(list) < n_csv + disp('Install CAT12 atlases'); + try + cat_install_atlases; + catch + disp('Writing error during atlas installation: Please check file permissions.'); + end + list = spm_atlas('List','installed'); + end + + if use_tfce + clist = 'tfce_list'; + else + clist = 'spm_list'; + end + for i=1:numel(list) + uimenu(hC1,'Label',list(i).name,... + 'Callback',sprintf('%s(''label'',''%s''); cat_spm_results_ui(''spm_list_cleanup'');',clist,list(i).name)); + end + if isempty(list), set(hC1,'Enable','off'); end + + varargout = {hC}; + + + + %====================================================================== + case 'spm_list_cleanup' + %====================================================================== + % cat_spm_results_ui('spm_list_cleanup',hReg) + + if ~mesh_detect, return; end + if nargin>1 + spm_list_cleanup(varargin{2}); + else + spm_list_cleanup + end + + + %====================================================================== + case 'setupsurfatlasmenu' %-Setup Atlas Menu + %====================================================================== + % spm_results_ui('SetupSurfAtlasMenu',Finter) + % RD202003 NOT WORKING YET + % requires update of spm_list('label',atlas) and spm_atlas + + Finter = varargin{2}; + Vspm = varargin{3}; + + %hC = uicontextmenu; + hC = uimenu(Finter,'Label','Atlas', 'Tag','AtlasUI'); + + hC1 = uimenu(hC,'Label','Label using'); + + %% + satlases = cat_get_defaults('extopts.satlas'); + expert = cat_get_defaults('extopts.expertgui'); + listi = 1; + for si = 1:size(satlases,1) + [pp,ff,ee] = spm_fileparts(satlases{si,1}); + if expert >= satlases{si,3} + list(listi) = struct('file',satlases{si,2},'name',satlases{si,1}); + list(listi).file = strrep(list(listi).file,'lh.','mesh.'); + if Vspm.dim(1) == 64984 + list(listi).file = strrep(list(listi).file,'atlases_surfaces','atlases_surfaces_32k'); + end + listi = listi + 1; + end + end + for i=1:numel(list) + uimenu(hC1,'Label',list(i).name,... + 'Callback',sprintf('spm_list(''label'',''%s''); cat_spm_results_ui(''spm_list_cleanup''); ',list(i).name)); + end + if isempty(list), set(hC1,'Enable','off'); end + + %hC2 = uimenu(hC,'Label','Download Atlas...',... + % 'Separator','on',... + % 'Callback','spm_atlas(''install'');'); + + varargout = {hC}; + + + %====================================================================== + case 'drawxyzgui' %-Draw XYZ GUI area + %====================================================================== + % hFxyz = cat_spm_results_ui('DrawXYZgui',M,DIM,xSPM,xyz,hReg) + if nargin<6, hReg=spm_XYZreg('FindReg','Interactive'); + else hReg=varargin{6}; end + if nargin < 5, xyz=[0;0;0]; else xyz=varargin{5}; end + if nargin < 4, error('Insufficient arguments'), end + DIM = varargin{3}; + M = varargin{2}; + xyz = spm_XYZreg('RoundCoords',xyz,M,DIM); + + %-Font details + %------------------------------------------------------------------ + WS = spm('WinScale'); + FS = spm('FontSizes'); + PF = spm_platform('fonts'); + + %-Create XYZ control objects + %------------------------------------------------------------------ + hFxyz = uipanel('Parent',hReg,'Title','co-ordinates','Units','Pixels',... + 'Position',[005 005 265 040].*WS,... + 'BorderType','Beveledout',... + 'ShadowColor',[0.5 0.5 0.5],... + 'FontAngle','Italic',... + 'FontSize',FS(10),... + 'ForegroundColor',[1 1 1],... + 'BackgroundColor',[179 179 179]/255); + + uicontrol('Parent',hReg,'Style','Text','String','x =',... + 'Position',[015 010 024 018].*WS,... + 'FontName',PF.times,'FontSize',FS(10),'FontAngle','Italic',... + 'HorizontalAlignment','Center'); + hX = uicontrol('Parent',hReg,'Style','Edit','String',sprintf('%.2f',xyz(1)),... + 'ToolTipString','enter x-coordinate',... + 'Position',[039 010 056 020].*WS,... + 'FontSize',FS(10),'BackGroundColor',[.8,.8,1],... + 'HorizontalAlignment','Right',... + 'Tag','hX',... + 'Callback','cat_spm_results_ui(''EdWidCB'')'); + + uicontrol('Parent',hReg,'Style','Text','String','y =',... + 'Position',[100 010 024 018].*WS,... + 'FontName',PF.times,'FontSize',FS(10),'FontAngle','Italic',... + 'HorizontalAlignment','Center'); + hY = uicontrol('Parent',hReg,'Style','Edit','String',sprintf('%.2f',xyz(2)),... + 'ToolTipString','enter y-coordinate',... + 'Position',[124 010 056 020].*WS,... + 'FontSize',FS(10),'BackGroundColor',[.8,.8,1],... + 'HorizontalAlignment','Right',... + 'Tag','hY',... + 'Callback','cat_spm_results_ui(''EdWidCB'')'); + + if DIM(3) ~= 1 + uicontrol('Parent',hReg,'Style','Text','String','z =',... + 'Position',[185 010 024 018].*WS,... + 'FontName',PF.times,'FontSize',FS(10),'FontAngle','Italic',... + 'HorizontalAlignment','Center'); + hZ = uicontrol('Parent',hReg,'Style','Edit','String',sprintf('%.2f',xyz(3)),... + 'ToolTipString','enter z-coordinate',... + 'Position',[209 010 056 020].*WS,... + 'FontSize',FS(10),'BackGroundColor',[.8,.8,1],... + 'HorizontalAlignment','Right',... + 'Tag','hZ',... + 'Callback','cat_spm_results_ui(''EdWidCB'')'); + else + hZ = []; + end + + %-Statistic value reporting pane + %------------------------------------------------------------------ + hPan = uipanel('Parent',hReg,'Title','statistic','Units','Pixels',... + 'Position',[275 005 110 040].*WS,... + 'BorderType','Beveledout', ... + 'ShadowColor',[0.5 0.5 0.5],... + 'FontAngle','Italic',... + 'FontSize',FS(10),... + 'ForegroundColor',[1 1 1],... + 'BackgroundColor',[179 179 179]/255); + hSPM = uicontrol('Parent',hPan,'Style','Text','String','',... + 'Position',[005 001 100 020].*WS,... + 'FontSize',FS(10),... + 'HorizontalAlignment','Center'); + + + %-Store data + %------------------------------------------------------------------ + set(hFxyz,'Tag','hFxyz','UserData',struct(... + 'hReg', [],... + 'M', M,... + 'DIM', DIM,... + 'XYZ', varargin{4}.XYZmm,... + 'Z', varargin{4}.Z,... + 'hX', hX,... + 'hY', hY,... + 'hZ', hZ,... + 'hSPM', hSPM,... + 'xyz', xyz )); + + set([hX,hY,hZ],'UserData',hFxyz) + varargout = {hFxyz}; + + + %====================================================================== + case 'edwidcb' %-Callback for editable widgets + %====================================================================== + % cat_spm_results_ui('EdWidCB') + + hC = gcbo; + d = find(strcmp(get(hC,'Tag'),{'hX','hY','hZ'})); + hFxyz = get(hC,'UserData'); + UD = get(hFxyz,'UserData'); + xyz = UD.xyz; + nxyz = xyz; + + o = evalin('base',['[',get(hC,'String'),']'],'sprintf(''error'')'); + if ischar(o) || length(o)>1 + warning(sprintf('%s: Error evaluating ordinate:\n\t%s',... + mfilename,lasterr)) + else + nxyz(d) = o; + nxyz = spm_XYZreg('RoundCoords',nxyz,UD.M,UD.DIM); + end + + if abs(xyz(d)-nxyz(d))>0 + UD.xyz = nxyz; set(hFxyz,'UserData',UD) + if ~isempty(UD.hReg), spm_XYZreg('SetCoords',nxyz,UD.hReg,hFxyz); end + set(hC,'String',sprintf('%.3f',nxyz(d))) + cat_spm_results_ui('UpdateSPMval',UD) + end + + + %====================================================================== + case 'updatespmval' %-Update SPM value in GUI + %====================================================================== + % cat_spm_results_ui('UpdateSPMval',hFxyz) + % cat_spm_results_ui('UpdateSPMval',UD) + if nargin<2, error('insufficient arguments'), end + if isstruct(varargin{2}), UD=varargin{2}; else UD = get(varargin{2},'UserData'); end + i = spm_XYZreg('FindXYZ',UD.xyz,UD.XYZ); + if isempty(i), str = ''; else str = sprintf('%6.2f',UD.Z(i)); end + set(UD.hSPM,'String',str); + + + %====================================================================== + case 'getcoords' % Get current co-ordinates from XYZ widget + %====================================================================== + % xyz = cat_spm_results_ui('GetCoords',hFxyz) + if nargin<2, hFxyz='Interactive'; else hFxyz=varargin{2}; end + hFxyz = cat_spm_results_ui('FindXYZframe',hFxyz); + varargout = {getfield(get(hFxyz,'UserData'),'xyz')}; + + + %====================================================================== + case 'setcoords' % Set co-ordinates to XYZ widget + %====================================================================== + % [xyz,d] = cat_spm_results_ui('SetCoords',xyz,hFxyz,hC) + if nargin<4, hC=NaN; else hC=varargin{4}; end + if nargin<3, hFxyz=cat_spm_results_ui('FindXYZframe'); else hFxyz=varargin{3}; end + if nargin<2, error('Set co-ords to what!'); else xyz=varargin{2}; end + + %-If this is an internal call, then don't do anything + if isequal(hFxyz,hC), return, end + + UD = get(hFxyz,'UserData'); + + %-Check validity of coords only when called without a caller handle + %------------------------------------------------------------------ + if ~ishandle(hC) + [xyz,d] = spm_XYZreg('RoundCoords',xyz,UD.M,UD.DIM); + if d>0 && nargout<2, warning(sprintf(... + '%s: Co-ords rounded to nearest voxel centre: Discrepancy %.2f',... + mfilename,d)) + end + else + d = []; + end + + %-Update xyz information & widget strings + %------------------------------------------------------------------ + UD.xyz = xyz; set(hFxyz,'UserData',UD) + set(UD.hX,'String',sprintf('%.2f',xyz(1))) + set(UD.hY,'String',sprintf('%.2f',xyz(2))) + set(UD.hZ,'String',sprintf('%.2f',xyz(3))) + cat_spm_results_ui('UpdateSPMval',UD); + + %-Tell the registry, if we've not been called by the registry... + %------------------------------------------------------------------ + if (~isempty(UD.hReg) && ~isequal(UD.hReg,hC)) + spm_XYZreg('SetCoords',xyz,UD.hReg,hFxyz); + end + + %-Return arguments + %------------------------------------------------------------------ + varargout = {xyz,d}; + + + %====================================================================== + case 'findxyzframe' % Find hFxyz frame + %====================================================================== + % hFxyz = cat_spm_results_ui('FindXYZframe',h) + % Sorts out hFxyz handles + if nargin<2, h='Interactive'; else h=varargin{2}; end + if ischar(h), h=spm_figure('FindWin',h); end + if ~ishandle(h), error('invalid handle'), end + if ~strcmp(get(h,'Tag'),'hFxyz'), h=findobj(h,'Tag','hFxyz'); end + if isempty(h), error('XYZ frame not found'), end + if length(h)>1, error('Multiple XYZ frames found'), end + varargout = {h}; + + + %====================================================================== + case 'plotui' %-GUI for plot manipulation + %====================================================================== + % cat_spm_results_ui('PlotUi',hAx) + if nargin<2, hAx=gca; else hAx=varargin{2}; end + + WS = spm('WinScale'); + FS = spm('FontSizes'); + Finter=spm_figure('FindWin','Interactive'); + figure(Finter) + + %-Check there aren't already controls! + %------------------------------------------------------------------ + hGraphUI = findobj(Finter,'Tag','hGraphUI'); + if ~isempty(hGraphUI) %-Controls exist + hBs = get(hGraphUI,'UserData'); + if hAx==get(hBs(1),'UserData') %-Controls linked to these axes + return + else %-Old controls remain + delete(findobj(Finter,'Tag','hGraphUIbg')) + end + end + + %-Frames & text + %------------------------------------------------------------------ + hGraphUIbg = uipanel('Parent',Finter,'Title','','Tag','hGraphUIbg',... + 'BackgroundColor',spm('Colour'),... + 'BorderType','Line', 'HighlightColor',[0 0 0],... + 'Units','Pixels','Position',[001 195 400 055].*WS); + hGraphUI = uipanel('Parent',hGraphUIbg,'Title','','Tag','hGraphUI',... + 'BorderType','Etchedin', ... + 'BackgroundColor',[179 179 179]/255,... + 'Units','Pixels','Position',[005 005 390 046].*WS); + hGraphUIButtsF = uipanel('Parent',hGraphUI,'Title','plot controls',... + 'Units','Pixels','Position',[005 005 380 039].*WS,... + 'BorderType','Beveledout', ... + 'FontAngle','Italic',... + 'FontSize',FS(10),... + 'ForegroundColor',[1 1 1],... + 'BackgroundColor',[179 179 179]/255); + + %-Controls + %------------------------------------------------------------------ + h1 = uicontrol('Parent',hGraphUIButtsF,'Style','CheckBox','String','hold',... + 'ToolTipString','toggle hold to overlay plots',... + 'FontSize',FS(10),... + 'Value',double(strcmp(get(hAx,'NextPlot'),'add')),... + 'Callback',[... + 'if get(gcbo,''Value''), ',... + 'set(get(gcbo,''UserData''),''NextPlot'',''add''), ',... + 'else, ',... + 'set(get(gcbo,''UserData''),''NextPlot'',''replace''), ',... + 'end'],... + 'Interruptible','on','Enable','on',... + 'Tag','holdButton',... + 'Position',[005 005 070 020].*WS); + h2 = uicontrol('Parent',hGraphUIButtsF,'Style','CheckBox','String','grid',... + 'ToolTipString','toggle axes grid',... + 'FontSize',FS(10),... + 'Value',double(strcmp(get(hAx,'XGrid'),'on')),... + 'Callback',[... + 'if get(gcbo,''Value''), ',... + 'set(get(gcbo,''UserData''),''XGrid'',''on'','... + '''YGrid'',''on'',''ZGrid'',''on''), ',... + 'else, ',... + 'set(get(gcbo,''UserData''),''XGrid'',''off'','... + '''YGrid'',''off'',''ZGrid'',''off''), ',... + 'end'],... + 'Interruptible','on','Enable','on',... + 'Position',[080 005 070 020].*WS); + h3 = uicontrol('Parent',hGraphUIButtsF,'Style','CheckBox','String','Box',... + 'ToolTipString','toggle axes box',... + 'FontSize',FS(10),... + 'Value',double(strcmp(get(hAx,'Box'),'on')),... + 'Callback',[... + 'if get(gcbo,''Value''), ',... + 'set(get(gcbo,''UserData''),''Box'',''on''), ',... + 'else, ',... + 'set(get(gcbo,''UserData''),''Box'',''off''), ',... + 'end'],... + 'Interruptible','on','Enable','on',... + 'Position',[155 005 070 020].*WS); + h4 = uicontrol('Parent',hGraphUIButtsF,'Style','popupmenu',... + 'ToolTipString','edit axis text annotations',... + 'FontSize',FS(10),... + 'String',{'text','Title','Xlabel','Ylabel'},... + 'Callback','cat_spm_results_ui(''PlotUiCB'')',... + 'Interruptible','on','Enable','on',... + 'Position',[230 005 070 020].*WS); + h5 = uicontrol('Parent',hGraphUIButtsF,'Style','popupmenu',... + 'ToolTipString','change various axes attributes',... + 'FontSize',FS(10),... + 'String',{'attrib','LineWidth','XLim','YLim','handle'},... + 'Callback','cat_spm_results_ui(''PlotUiCB'')',... + 'Interruptible','off','Enable','on',... + 'Position',[305 005 070 020].*WS); + + %-Handle storage for linking, and DeleteFcns for linked deletion + %------------------------------------------------------------------ + set(hGraphUI,'UserData',[h1,h2,h3,h4,h5]) + set([h1,h2,h3,h4,h5],'UserData',hAx) + + set(hGraphUIbg,'UserData',... + [hGraphUI,hGraphUIButtsF,h1,h2,h3,h4,h5],... + 'DeleteFcn','cat_spm_results_ui(''Delete'',get(gcbo,''UserData''))') + set(hAx,'UserData',hGraphUIbg,... + 'DeleteFcn','cat_spm_results_ui(''Delete'',get(gcbo,''UserData''))') + + + %====================================================================== + case 'plotuicb' + %====================================================================== + % cat_spm_results_ui('PlotUiCB') + hPM = gcbo; + v = get(hPM,'Value'); + if v==1, return, end + str = cellstr(get(hPM,'String')); + str = str{v}; + + hAx = get(hPM,'UserData'); + switch str + case 'Title' + h = get(hAx,'Title'); + set(h,'String',spm_input('Enter title:',-1,'s+',get(h,'String'))) + case 'Xlabel' + h = get(hAx,'Xlabel'); + set(h,'String',spm_input('Enter X axis label:',-1,'s+',get(h,'String'))) + case 'Ylabel' + h = get(hAx,'Ylabel'); + set(h,'String',spm_input('Enter Y axis label:',-1,'s+',get(h,'String'))) + case 'LineWidth' + lw = spm_input('Enter LineWidth',-1,'e',get(hAx,'LineWidth'),1); + set(hAx,'LineWidth',lw) + case 'XLim' + XLim = spm_input('Enter XLim',-1,'e',get(hAx,'XLim'),[1,2]); + set(hAx,'XLim',XLim) + case 'YLim' + YLim = spm_input('Enter YLim',-1,'e',get(hAx,'YLim'),[1,2]); + set(hAx,'YLim',YLim) + case 'handle' + varargout={hAx}; + otherwise + warning(['Unknown action: ',str]) + end + + set(hPM,'Value',1) + + + %====================================================================== + case 'clear' %-Clear results subpane + %====================================================================== + % Fgraph = cat_spm_results_ui('Clear',F,mode) + % mode 1 [default] usual, mode 0 - clear & hide Res stuff, 2 - RNP + + if nargin<3, mode=1; else mode=varargin{3}; end + if nargin<2, F='Graphics'; else F=varargin{2}; end + F = spm_figure('FindWin',F); + + %-Clear input objects from 'Interactive' window + %------------------------------------------------------------------ + %spm_input('!DeleteInputObj') + + + %-Get handles of objects in Graphics window & note permanent results objects + %------------------------------------------------------------------ + H = get(F,'Children'); %-Get contents of window + H = findobj(H,'flat','HandleVisibility','on'); %-Drop GUI components + h = findobj(H,'flat','Tag','PermRes'); %-Look for 'PermRes' object + + if ~isempty(h) + %-Found 'PermRes' object + % This has handles of permanent results objects in it's UserData + tmp = get(h,'UserData'); + HR = tmp.H; + HRv = tmp.Hv; + else + %-No trace of permanent results objects + HR = []; + HRv = {}; + end + H = setdiff(H,HR); %-Drop permanent results obj + + + %-Delete stuff as appropriate + %------------------------------------------------------------------ + if mode==2 %-Don't delete axes with NextPlot 'add' + H = setdiff(H,findobj(H,'flat','Type','axes','NextPlot','add')); + end + + delete(H) + %set(F,'resize','on');set(F,'resize','off') + + if mode==0 %-Hide the permanent results section stuff + set(HR,'Visible','off') + else + set(HR,{'Visible'},HRv) + end + + + %====================================================================== + case 'close' %-Close Results + %====================================================================== + set(spm_figure('GetWin','Graphics'),'Color',[1 1 1]); + spm_clf('Interactive'); + spm_clf('Graphics'); + close(spm_figure('FindWin','Satellite')); + evalin('base','clear'); + + + %====================================================================== + case 'launchmp' %-Launch multiplanar toolbox + %====================================================================== + % hMP = cat_spm_results_ui('LaunchMP',M,DIM,hReg,hBmp) + if nargin<5, hBmp = gcbo; else hBmp = varargin{5}; end + hReg = varargin{4}; + DIM = varargin{3}; + M = varargin{2}; + + %-Check for existing MultiPlanar toolbox + hMP = get(hBmp,'UserData'); + if ishandle(hMP) + figure(ancestor(hMP,'figure')); + varargout = {hMP}; + return + end + + %-Initialise and cross-register MultiPlanar toolbox + hMP = spm_XYZreg_Ex2('Create',M,DIM); + spm_XYZreg('Xreg',hReg,hMP,'spm_XYZreg_Ex2'); + + %-Setup automatic deletion of MultiPlanar on deletion of results controls + set(hBmp,'Enable','on','UserData',hMP) + set(hBmp,'DeleteFcn','cat_spm_results_ui(''delete'',get(gcbo,''UserData''))') + + varargout = {hMP}; + + + %====================================================================== + case 'delete' %-Delete HandleGraphics objects + %====================================================================== + % cat_spm_results_ui('Delete',h) + h = varargin{2}; + delete(h(ishandle(h))); + + + %====================================================================== + otherwise + %====================================================================== + error('Unknown action string') + +end + +%========================================================================== +function varargout = call_list(varargin) +%========================================================================== +global use_tfce + +if use_tfce + varargout = {tfce_list(varargin{:})}; +else + varargout = {spm_list(varargin{:})}; +end + +%========================================================================== +function mycluster(obj,evt,xSPM,distmin,nbmax) +%========================================================================== + +spm_get_defaults('stats.results.volume.distmin',distmin); +spm_get_defaults('stats.results.volume.nbmax',nbmax); + +hReg = evalin('base','hReg;'); +TabDat = call_list('List',xSPM,hReg); +figure(spm_figure('GetWin','Interactive')); + +%========================================================================== +function mychgcon(obj,evt,xSPM) +%========================================================================== +global use_tfce + +xSPM2.swd = xSPM.swd; +try, xSPM2.units = xSPM.units; end +xSPM2.Ic = getfield(get(obj,'UserData'),'Ic'); +if isempty(xSPM2.Ic) || all(xSPM2.Ic == 0), xSPM2 = rmfield(xSPM2,'Ic'); end +xSPM2.Im = xSPM.Im; +xSPM2.pm = xSPM.pm; +xSPM2.Ex = xSPM.Ex; +xSPM2.title = ''; +if ~isempty(xSPM.thresDesc) + if strcmp(xSPM.STAT,'P') + % These are soon overwritten by spm_getSPM + xSPM2.thresDesc = xSPM.thresDesc; + xSPM2.u = xSPM.u; + xSPM2.k = xSPM.k; + % xSPM.STATstr contains Gamma + else + td = regexp(xSPM.thresDesc,'p\D?(?[\.\d]+) \((?\S+)\)','names'); + if isempty(td) + td = regexp(xSPM.thresDesc,'\w=(?[\.\d]+)','names'); + td.thresDesc = 'none'; + end + if strcmp(td.thresDesc,'unc.'), td.thresDesc = 'none'; end + xSPM2.thresDesc = td.thresDesc; + if use_tfce + xSPM2.invResult = xSPM.invResult; + end + if isfield(xSPM,'statType') + xSPM2.statType = xSPM.statType; + elseif isfield(xSPM,'STAT') + xSPM2.statType = xSPM.STAT; + end + xSPM2.u = str2double(td.u); + xSPM2.k = xSPM.k; + end +end +hReg = spm_XYZreg('FindReg',spm_figure('GetWin','Interactive')); +xyz = spm_XYZreg('GetCoords',hReg); +[hReg,xSPM,SPM, TabDat] = cat_spm_results_ui('setup',xSPM2); +spm_XYZreg('SetCoords',xyz,hReg); +spm_list_cleanup; +assignin('base','hReg',hReg); +assignin('base','xSPM',xSPM); +assignin('base','SPM',SPM); +assignin('base','TabDat',TabDat); +figure(spm_figure('GetWin','Interactive')); + +%========================================================================== +function mycheckres(obj,evt,xSPM) +%========================================================================== +spm_check_results([],xSPM); + +%========================================================================== +function mysavespm(action) +%========================================================================== +xSPM = evalin('base','xSPM;'); +XYZ = xSPM.XYZ; + +switch lower(action) + case 'thresh' + Z = xSPM.Z; + + case 'binary' + Z = ones(size(xSPM.Z)); + + case 'n-ary' + if ~isfield(xSPM,'G') + Z = spm_clusters(XYZ); + num = max(Z); + [n, ni] = sort(histc(Z,1:num), 2, 'descend'); + n = size(ni); + n(ni) = 1:num; + Z = n(Z); + else + C = NaN(1,size(xSPM.G.vertices,1)); + C(xSPM.XYZ(1,:)) = ones(size(xSPM.Z)); + C = spm_mesh_clusters(xSPM.G,C); + Z = C(xSPM.XYZ(1,:)); + end + + case 'current' + [xyzmm,i] = spm_XYZreg('NearestXYZ',... + cat_spm_results_ui('GetCoords'),xSPM.XYZmm); + cat_spm_results_ui('SetCoords',xSPM.XYZmm(:,i)); + + if ~isfield(xSPM,'G') + A = spm_clusters(XYZ); + j = find(A == A(i)); + Z = ones(1,numel(j)); + XYZ = xSPM.XYZ(:,j); + else + C = NaN(1,size(xSPM.G.vertices,1)); + C(xSPM.XYZ(1,:)) = ones(size(xSPM.Z)); + C = spm_mesh_clusters(xSPM.G,C); + C = C==C(xSPM.XYZ(1,i)); + Z = C(xSPM.XYZ(1,:)); + end + + otherwise + error('Unknown action.'); +end + +if isfield(xSPM,'G') + F = spm_input('Output filename',1,'s'); + if isempty(spm_file(F,'ext')) + F = spm_file(F,'ext','.gii'); + end + F = spm_file(F,'CPath'); + M = gifti(xSPM.G); + C = zeros(1,size(xSPM.G.vertices,1)); + C(xSPM.XYZ(1,:)) = Z; % or use NODE_INDEX + M.cdata = C; + save(M,F); + if exist('cat_surf_render','file') + cmd = 'cat_surf_render(''Disp'',''%s'')'; + else + cmd = 'spm_mesh_render(''Disp'',''%s'')'; + end +else + V = spm_write_filtered(Z, XYZ, xSPM.DIM, xSPM.M,... + sprintf('SPM{%c}-filtered: u = %5.3f, k = %d',xSPM.STAT,xSPM.u,xSPM.k)); + cmd = 'spm_image(''display'',''%s'')'; + F = V.fname; +end + +fprintf('Written %s\n',spm_file(F,'link',cmd)); %-# + +%========================================================================== +function myslover +%========================================================================== +spm_input('!DeleteInputObj'); +xSPM = evalin('base','xSPM;'); + +so = slover; +[img,sts] = spm_select(1,'image','Select image for rendering on'); +if ~sts, return; end +so.img.vol = spm_vol(img); +%obj.img.type = 'truecolour'; +%obj.img.cmap = gray; +%[mx,mn] = slover('volmaxmin', obj.img.vol); +%obj.img.range = [mn mx]; +so.img.prop = 1; + +so = add_spm(so,xSPM); + +so.transform = deblank(spm_input('Image orientation', '+1', ... + 'Axial|Coronal|Sagittal', char('axial','coronal','sagittal'), 1)); +so = fill_defaults(so); +slices = so.slices; +so.slices = spm_input('Slices to display (mm)', '+1', 'e', ... + sprintf('%0.0f:%0.0f:%0.0f',slices(1),mean(diff(slices)),slices(end))); + +so.figure = spm_figure('GetWin', 'SliceOverlay'); +so = paint(so); +assignin('base','so',so); + +%========================================================================== +function spm_list_cleanup(hReg) +%========================================================================== +global mesh_detect + +if ~mesh_detect, return; end + +hRes.Fgraph = [spm_figure('FindWin','Graphics'),spm_figure('FindWin','Satellite')]; + +% fine red lines of the SPM result table +hRes.Fline = findobj(hRes.Fgraph,'Type','Line','Tag','');% ,'UIcontextMenu',[]); +hRes.FlineAx = get(hRes.Fline,'parent'); + +set(hRes.Fline,'HitTest','off'); % +for axi = 1:numel( hRes.FlineAx ), rotate3d(hRes.FlineAx{axi},'off'); end +for axi = 1:numel( hRes.FlineAx ), set(hRes.FlineAx{axi},'visible','off'); end + +%% +hRes.Img = get(findobj(hRes.Fgraph,'Type','Image','Tag','Transverse'),'parent'); +for axi = 1:numel( hRes.Img ), rotate3d(hRes.Img{axi},'off'); end + +%% find the SPM string within the surface axis +hRes.Ftext = findobj(hRes.Fgraph,'Type','Text'); +stext = get(hRes.Ftext,'String'); +hRes.Ftext3dspm = findobj(hRes.Fgraph,'Type','Text','String', ... + stext{ find(~cellfun('isempty',strfind(stext,'SPM\{'))) } ); +set(hRes.Ftext3dspm,'visible','off','HitTest','off'); + +%% get backgroundcolor +bgc = get(spm_figure('FindWin','Graphics'),'Color'); +% get low contrast texts +Ftextcol = cell2mat(get(hRes.Ftext,'Color')); +%% invert text +rms = @(x) mean(x.^2,2).^0.5; +bgcdist = rms(Ftextcol - repmat(bgc, numel(hRes.Ftext), 1)); +bgcdist = abs(bgcdist)<0.3; +if ~isempty(bgcdist) + for fi = 1:numel(bgcdist) + if bgcdist(fi)>0 + set( hRes.Ftext( fi ) , 'Color' , min(1,max(0, 1 - Ftextcol( fi ,:))) ); + end + end +end + +%% update spm_XYZreg XYZ update function +if ~exist('hReg','var') + ListXYZ=findobj('ButtonDownFcn','spm_XYZreg(''SetCoords'',get(gcbo,''UserData''),hReg,1);'); + for i=1:numel(ListXYZ) + set(ListXYZ(i),'ButtonDownFcn',[get(ListXYZ(i),'ButtonDownFcn') ' cat_spm_results_ui(''spm_list_cleanup'');']); + end +end +%========================================================================== +function out = cat_spm_run_results(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-2018 Wellcome Trust Centre for Neuroimaging + +% Guillaume Flandin +% $Id$ + + +cspec = job.conspec; +for k = 1:numel(cspec) + job.conspec = cspec(k); + + %-Apply to all contrasts if Inf is entered + %---------------------------------------------------------------------- + if (numel(cspec(k).contrasts) == 1) && isinf(cspec(k).contrasts) + tmp = load(job.spmmat{1}); + cspec1 = repmat(cspec(k),size(tmp.SPM.xCon)); + for l = 1:numel(tmp.SPM.xCon) + cspec1(l).contrasts = l; + end + job1 = job; + %job1.print = spm_get_defaults('ui.print'); + job1.conspec = cspec1; + out = spm_run_results(job1); + continue; + end + + %-Create xSPM variable + %---------------------------------------------------------------------- + xSPM.swd = spm_file(job.spmmat{1},'fpath'); + xSPM.Ic = job.conspec.contrasts; + xSPM.u = job.conspec.thresh; + xSPM.Im = []; + if ~isfield(job.conspec.mask,'none') + if isfield(job.conspec.mask,'contrast') + xSPM.Im = job.conspec.mask.contrast.contrasts; + xSPM.pm = job.conspec.mask.contrast.thresh; + xSPM.Ex = job.conspec.mask.contrast.mtype; + elseif isfield(job.conspec.mask,'image') + xSPM.Im = job.conspec.mask.image.name; + xSPM.pm = []; + xSPM.Ex = job.conspec.mask.image.mtype; + end + end + xSPM.thresDesc = job.conspec.threshdesc; + xSPM.title = job.conspec.titlestr; + xSPM.k = job.conspec.extent; + try + xSPM.n = job.conspec.conjunction; + end + switch job.units + case 1 + xSPM.units = {'mm' 'mm' 'mm'}; + case 2 + xSPM.units = {'mm' 'mm' 'ms'}; + case 3 + xSPM.units = {'mm' 'mm' 'Hz'}; + case 4 + xSPM.units = {'Hz' 'ms' ''}; + case 5 + xSPM.units = {'Hz' 'Hz' ''}; + otherwise + error('Unknown data type.'); + end + + %-Compute a specified and thresholded SPM + %---------------------------------------------------------------------- + if ~spm('CmdLine') + [hReg, xSPM, SPM] = cat_spm_results_ui('Setup',xSPM); + TabDat = spm_list('List',xSPM,hReg); + else + [SPM, xSPM] = spm_getSPM(xSPM); + TabDat = spm_list('Table',xSPM); + hReg = []; + end + + assignin('base', 'TabDat', TabDat); + assignin('base', 'hReg', hReg); + assignin('base', 'xSPM', xSPM); + assignin('base', 'SPM', SPM); + + out.xSPMvar(k) = xSPM; + out.TabDatvar(k) = TabDat; + out.filtered{k} = {}; + + %-Export + %---------------------------------------------------------------------- + for i=1:numel(job.export) + fn = char(fieldnames(job.export{i})); + switch fn + case {'tspm','binary','nary'} + fname = spm_file(xSPM.Vspm(1).fname,... + 'suffix',['_' job.export{i}.(fn).basename]); + descrip = sprintf('SPM{%c}-filtered: u = %5.3f, k = %d',... + xSPM.STAT,xSPM.u,xSPM.k); + switch fn % see spm_results_ui.m + case 'tspm' + Z = xSPM.Z; + case 'binary' + Z = ones(size(xSPM.Z)); + case 'nary' + if ~isfield(xSPM,'G') + Z = spm_clusters(xSPM.XYZ); + num = max(Z); + [n, ni] = sort(histc(Z,1:num), 2, 'descend'); + n = size(ni); + n(ni) = 1:num; + Z = n(Z); + else + C = NaN(1,size(xSPM.G.vertices,1)); + C(xSPM.XYZ(1,:)) = ones(size(xSPM.Z)); + C = spm_mesh_clusters(xSPM.G,C); + Z = C(xSPM.XYZ(1,:)); + end + end + if isfield(xSPM,'G') + M = gifti(xSPM.G); + C = zeros(1,size(xSPM.G.vertices,1)); + C(xSPM.XYZ(1,:)) = Z; % or use NODE_INDEX + M.cdata = C; + F = spm_file(fname,'path',xSPM.swd); + save(M,F); + cmd = 'spm_mesh_render(''Disp'',''%s'')'; + else + V = spm_write_filtered(Z,xSPM.XYZ,xSPM.DIM,xSPM.M,... + descrip,fname); + cmd = 'spm_image(''display'',''%s'')'; + F = V.fname; + end + out.filtered{k} = F; + fprintf('Written %s\n',spm_file(F,'link',cmd)); + + case {'csv','xls'} + ofile = spm_file(fullfile(xSPM.swd,... + ['spm_' datestr(now,'yyyymmmdd') '.' fn]),'unique'); + spm_list([upper(fn) 'List'],TabDat,ofile); + if strcmp(fn,'csv'), cmd = 'open(''%s'')'; + else cmd = 'winopen(''%s'')'; end + fprintf('Saving results to:\n %s\n',spm_file(ofile,'link',cmd)); + + case 'montage' + % see myslover() in spm_results_ui.m + so = slover; + so.img.vol = spm_vol(char(job.export{i}.montage.background)); + so.img.prop = 1; + so = add_spm(so, xSPM); + so.transform = job.export{i}.montage.orientation; + so = fill_defaults(so); + so.slices = job.export{i}.montage.slices; + so.figure = spm_figure('GetWin', 'SliceOverlay'); + so = paint(so); + %spm_print('',so.figure); + + case 'nidm' + opts = struct('mod',job.export{i}.nidm.modality, ... + 'space',job.export{i}.nidm.refspace,... + 'group',struct('N',[job.export{i}.nidm.group.nsubj],... + 'name',{{job.export{i}.nidm.group.label}})); + nidmfile = spm_results_nidm(SPM,xSPM,TabDat,opts); + fprintf('Exporting results in:\n %s\n',nidmfile); + + otherwise + if ~spm('CmdLine') + switch fn + case {'jpg','png'} + %% print subject report file as standard PDF/PNG/... file + + fg = spm_figure('FindWin','Graphics'); + h = get(findobj(fg,'type','patch','tag','CATSurfRender'),'parent'); + if ~isfield(job,'view'), job.view = 'left'; end + viewname = ''; + if ~isempty(h) && isfield(job,'view') && exist('cat_surf_render','file') + switch lower(job.view) + case {'r','right'}, cat_surf_render('view',h,[ 90 0]); viewname = 'r.'; + case {'l','left'}, cat_surf_render('view',h,[ -90 0]); viewname = 'l.'; + case {'t','s','top','superior'}, cat_surf_render('view',h,[ 0 90]); viewname = 's.'; + case {'b','i','bottom','inferior'}, cat_surf_render('view',h,[-180 -90]); viewname = 'i.'; + case {'f','a','front','anterior'}, cat_surf_render('view',h,[-180 0]); viewname = 'a.'; + case {'p','back','posterior'}, cat_surf_render('view',h,[ 0 0]); viewname = 'p.'; + otherwise + if isnumeric(job.view) && size(job.view)==2 + view(job.view); viewname = sprintf('%04dx%04d.',mod(job.view,360)); + else + cat_io_cprintf('err','Unknown view.\n'); + end + end + end + + job.imgprint.type = fn(1:3); + if numel(fn) > 3 + job.imgprint.dpi = round(str2double(fn(4:end))); + else + job.imgprint.dpi = 300; + end + job.imgprint.fdpi = @(x) ['-r' num2str(x)]; + job.imgprint.ftype = @(x) ['-d' strrep( x , 'jpg' , 'jpeg' ) ]; + job.imgprint.fname = fullfile( spm_fileparts(job.spmmat{1}), sprintf('catresults_con%d-%s_%s%0.0e_ex%d_conj%d_msk%d.%s.%s',... + job.conspec.contrasts, job.conspec.titlestr, ... + job.conspec.threshdesc, job.conspec.thresh, ... + job.conspec.extent, job.conspec.conjunction, ... + ~isfield(job.conspec.mask,'none'), viewname, job.imgprint.type)); + + + if 0 %exist('exportgraphics','file') + exportgraphics(fg,job.imgprint.fname,'Resolution',job.imgprint.dpi) + else + % paperposition defines fontsize and we compensate maybe the screen resolution of 0.75 dpi ... + set(fg,'PaperPositionMode','manual','resize','off','PaperPosition',[0 0 1.4 1.4]); + print(fg, job.imgprint.ftype(fn), job.imgprint.fdpi(job.imgprint.dpi), job.imgprint.fname); + end + otherwise + spm_figure('Print','Graphics','',fn); + end + else + spm_list('TxtList',TabDat); + end + end + end + +end + +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_vol_genus0.c",".c","3581","124","/* Genus0 topology correction + * ______________________________________________________________________ + * + * Christian Gaser, Robert Dahnke + * Structural Brain Mapping Group (https://neuro-jena.github.io) + * Departments of Neurology and Psychiatry + * Jena University Hospital + * ______________________________________________________________________ + * $Id$ + */ + +#include ""mex.h"" +#include ""math.h"" +#include ""float.h"" +#include ""genus0.h"" + +/* main function */ +void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) +{ + if (nrhs<2) mexErrMsgTxt(""ERROR:cat_vol_genus0: At least two input elements necessary.\n""); + if (nlhs<1) mexErrMsgTxt(""ERROR:cat_vol_genus0: At least one output element necessary.\n""); + + /* main information about input data (size, dimensions, ...) */ + const mwSize *sL = mxGetDimensions(prhs[0]); + const int dL = mxGetNumberOfDimensions(prhs[0]); + + unsigned short *input; + + if ( dL != 3 || mxIsSingle(prhs[0])==0) mexErrMsgTxt(""ERROR:cat_vol_genus0: first input must be a single 3d matrix\n""); + + /* indices of the neighbor Ni (index distance) and euclidean distance NW */ + int i, j, sz = sL[0]*sL[1]*sL[2]; + + /* in- and output */ + float *vol = (float *) mxGetPr(prhs[0]); + float th = (float) mxGetScalar(prhs[1]); + + plhs[0] = mxCreateNumericArray(dL,sL,mxSINGLE_CLASS,mxREAL); + float *M = (float *) mxGetPr(plhs[0]); + + input = (unsigned short *) mxMalloc(sizeof(unsigned short)*sz); + + /* use orientation from isosurface */ + float ijk2ras[16] = {0.0, 1.0, 0.0, 0.0, + 1.0, 0.0, 0.0, 0.0, + 0.0, 0.0, 1.0, 0.0, + 0.0, 0.0, 0.0, 1.0}; + + for (i=0; i th) + input[i] = 1; + else input[i] = 0; + } + + genus0parameters g0[1]; /* need an instance of genus0parameters */ + + genus0init(g0); /* initialize the instance, set default parameters */ + + /* set some parameters/options */ + for(j= 0; j dims[j] = sL[j]; + + g0->input = input; + g0->cut_loops = 0; + g0->connectivity = 6; + g0->return_adjusted_label_map = 1; + g0->connected_component = 1; + g0->value = 1; + g0->contour_value = 1; + g0->alt_value = 1; + g0->alt_contour_value = 1; + g0->biggest_component = 1; + g0->pad[0] = g0->pad[1] = g0->pad[2] = 2; + g0->ijk2ras = ijk2ras; + g0->verbose = 1; + g0->return_surface = 0; + g0->extraijkscale[0] = g0->extraijkscale[1] = g0->extraijkscale[2] = 1; + + if (nrhs==3) g0->any_genus = (int) mxGetScalar(prhs[2]); + else g0->any_genus = 0; + + if (nlhs==3) g0->return_surface = 1; + + /* in case of error return empty variables */ + if (genus0(g0)) { + mwSize dims[2]; + + dims[0] = 0; dims[1] = 0; + plhs[1] = mxCreateNumericArray(2,dims,mxUINT32_CLASS,mxREAL); + + dims[0] = 0; dims[1] = 0; + plhs[2] = mxCreateNumericArray(2,dims,mxSINGLE_CLASS,mxREAL); + + return; + } + + for (i=0; ioutput[i]; + + if (nlhs==3) { + mwSize dims[2]; + + dims[0] = g0->tri_count; dims[1] = 3; + plhs[1] = mxCreateNumericArray(2,dims,mxUINT32_CLASS,mxREAL); + + dims[0] = g0->vert_count; dims[1] = 3; + plhs[2] = mxCreateNumericArray(2,dims,mxSINGLE_CLASS,mxREAL); + + int *Tris = (int *) mxGetPr(plhs[1]); + float *Verts = (float *) mxGetPr(plhs[2]); + + /* return Tris and Verts and add 1 for matlab use */ + for (i=0; i<3*g0->tri_count; i++) + Tris[i] = g0->triangles[i] + 1; + for (i=0; i<3*g0->vert_count; i++) + Verts[i] = g0->vertices[i] + 1.0; + } + + genus0destruct(g0); + mxFree(input); + +} + + +","C" +"Neurology","ChristianGaser/cat12","cat_check_system_output.m",".m","2238","67","function varargout = cat_check_system_output(status,result,debugON,trerr) +%_______________________________________________________________________ +% cat_check_system_output check of system commands and returned result +% +% cat_check_system_output(status,result,debugON,trerr) +% +% status, result .. system call outputs [status,result] = system('...'); +% debugON .. display result +% trerr .. trough an error message (default), else just display +% error +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + if ~exist('debugON','var'), debugON=0; end + if ~exist('trerr','var'), trerr=1; end + if nargout>0, varargout{1} = false; varargout{2} = result; end + + % replace special characters + result = genstrarray(result); + + if status > 1 || ... + ~isempty(strfind(result,'ERROR')) || ... + ~isempty(strfind(result,'Segmentation fault')) + if nargout>0, varargout{1} = true; varargout{2} = result; end + if trerr + try + error('CAT:system_error',sprintf('CAT System_error: %s',result)); + catch + fprintf('CAT System_error: %s',sprintf(result)); + end + else + cat_io_cprintf('warn','CAT:system_error:%s',sprintf(result)); + end + end + if nargin > 2 + if debugON>0 && ~strcmp(result,'') + fprintf('%s',sprintf(result)); + end + end +end + +function str = genstrarray(stritem) +% generate a string of properly quoted strings + + str = strrep(stritem, '''', ''''''); + if ~any(str == char(0)) && ~any(str == char(9)) && ~any(str == char(10)) && ~strcmp(str,'') + str = sprintf('''%s''', str ); + else + % first, quote sprintf special chars % and \ + % second, replace special characters by sprintf equivalents + replacements = {'%', '%%'; ... + '\', '\\'; ... + char(0), '\0'; ... + char(9), '\t'; ... + char(10), '\n';... + '\S', ''}; + for cr = 1:size(replacements, 1) + str = strrep(str , replacements{cr,:}); + end + end +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_io_rerun.m",".m","6684","155","function run = cat_io_rerun(files,filedates,verb,force) +%cat_io_rerun(f1,fd). Test if a file f1 is newer than another file/date fd. +% This function is used to estimated if a file is newer than another given +% file or date. For instance file is the result of another file that was +% changed in the meantime, it has to be reprocessed. +% +% run = cat_io_rerun(files,filedates,verb,force) +% +% run .. logical vector with the number of given files +% cell if directories or wildcards are used +% files .. filenames (cellstr or char) +% filedat .. filenames (cellstr or char) or datetimes or datenum +% verb .. print details about the files and about the result +% (default = 0.5 only display if reprocessing is NOT reqired) +% force .. use also in non developer mode (default = 0) +% +% Examples: +% 1) Is the working directory younger/newer than the SPM dir? +% cat_io_rerun(pwd,spm('dir'); +% +% 2) Is the working directory younger/newer than one month? +% cat_io_rerun(pwd,clock - [0 1 0 0 0 0]) +% +% 3) Is this function younger than one year? +% cat_io_rerun(which('cat_io_rerun'),clock - [1 0 0 0 0 0]) +% +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + if ~exist('verb','var'), verb = 0.5; end + if ~exist('force','var'), force = 0; end + files = cellstr(files); + + % only use that function in developer mode because it's simply too dangerous + % if files are not processed if already existing and parameter changed + if force>=0 && (cat_get_defaults('extopts.expertgui') < 2 || force~=0) + if verb, cat_io_cprintf([0.5 0.0 0.0],' Reprocessing! \n'); end + run = ones(size(files)); + return + end + + if iscellstr(filedates) || ischar(filedates) + filedates = cellstr(filedates); + if numel(filedates) == 1 + filedates = repmat(filedates,numel(files),1); + else + if ~isempty(filedates) && numel(files) ~= numel(filedates) + error('ERROR:cat_io_rerun:inputsize','Number of files and filedates has to be equal.\n') + end + end + else + if size(filedates,1) + filedates = repmat(filedates,numel(files),1); + end + end + + run = ones(size(files)); + exf = ones(size(files)); + for fi = 1:numel(files) + [pp,ff,ee] = spm_fileparts(files{fi}); files{fi} = fullfile(pp,[ff ee]); % remove additional dimensions "",1"" + if ~exist(files{fi},'file') + if numel(files)>1 + run(fi) = 1; + if verb + fprintf(' Input file 2-%02d does not exist: %70s\n',fi,spm_str_manip( files{fi}, 'a70')); + end + else + run(fi) = 1; + if verb + fprintf(' Input file 2 does not exist: %73s\n',spm_str_manip( files{fi}, 'a73')); + end + end + exf = 0; + else + fdata = dir(files{fi}); + if numel(fdata)>1 + run = num2cell(run); + end + + if exist('filedates','var') && iscellstr(filedates) + [pp,ff,ee] = spm_fileparts(filedates{fi}); filedates{fi} = fullfile(pp,[ff ee]); % remove additional dimensions "",1"" + if exist(filedates{fi},'file') + fdata2 = dir(filedates{fi}); + if numel(fdata)>1 + run(fi) = [fdata(:).datenum] >= fdata2.datenum; + else + run(fi) = fdata.datenum >= fdata2.datenum; + end + + % be verbose only if verb>=1 or if no reprocessing is required + if verb >= 1 || (verb && ~( (iscell(run) && any(cell2mat(run))) || ( ismatrix(run) && any(run) ) )) + if fi==1, fprintf('\n'); end + if numel(files)==1 && numel(filedates)==1 + fprintf(' Input file 1: %80s: %s\n',spm_str_manip( fdata.name , 'a80'),datestr(fdata.datenum) ); + fprintf(' Input file 2: %80s: %s -',spm_str_manip( fdata2.name, 'a80'),datestr(fdata2.datenum)); + elseif numel(files) == numel(filedates) + fprintf(' Input file %02d-1: %80s: %s\n',fi,spm_str_manip( fdata.name ,'a80'),datestr(fdata.datenum) ); + fprintf(' Input file %02d-2: %80s: %s -',fi,spm_str_manip( fdata2.name,'a80'),datestr(fdata2.datenum)); + elseif numel(files) == 1 + if fi == 1 + fprintf(' Input file 1-%02d: %80s: %s\n',fi,spm_str_manip( fdata.name ,'a80'),datestr(fdata.datenum) ); + end + fprintf(' Input file 1-%02d: %80s: %s -',fi,spm_str_manip( fdata2.name,'a80'),datestr(fdata2.datenum)); + else + error('Error:cat_io_rerun:inputerror','Size input1 does not match size of input2 ([n1,n2]: [1,1], [1,n], or [n,n]).') + end + if run(fi), cat_io_cprintf([0.5 0.0 0.0],' reprocess\n'); else, cat_io_cprintf([0.0 0.5 0.0],' do not process\n'); end + end + elseif verb > 1 + if numel(files)==1 && numel(filedates)==1 + cat_io_cprintf([0.5 0.0 0.0],' Input file 2: %80s: %s\n',spm_str_manip( filedates{fi}, 'a80'),'missing'); + elseif numel(files) == numel(filedates) + cat_io_cprintf([0.5 0.0 0.0],' Input file %02d-1: %80s: %s\n',fi,spm_str_manip( files{fi} ,'a80'),datestr(fdata.datenum) ); + cat_io_cprintf([0.5 0.0 0.0],' Input file %02d-2: %80s: %s\n',fi,spm_str_manip( filedates{fi},'a80'),'missing'); + else + cat_io_cprintf([0.5 0.0 0.0],' Input file 2-%02d: %80s: %s\n',fi,spm_str_manip( filedates{fi},'a80'),'missing'); + end + end + elseif ~isempty(filedates) && isdatetime( filedates(fi,:) ) + if numel(fdata)>1 + run{fi} = [fdata(:).datenum] >= datenum( filedates(fi,:) ); + else + run(fi) = fdata.datenum >= datenum( filedates(fi,:) ); + end + else + if numel(fdata)>1 + run{fi} = 1; + else + run(fi) = 1; + end + end + end + end + % be verbose only if verb>=1 or if no reprocessing is required + if verb >= 1 || ~( (iscell(run) && any(cell2mat(run))) || ( ismatrix(run) && any(run) ) ) + if verb >= 1 && ( (iscell(run) && any(cell2mat(run))) || ( ismatrix(run) && any(run) ) ) + if all(exf) + cat_io_cprintf([0.5 0.0 0.0],' Reprocessing is required. \n'); + elseif all(exf==0) && numel(files)>1 + cat_io_cprintf([0.5 0.0 0.0],' (Re)processing is required. \n'); + else + cat_io_cprintf([0.5 0.0 0.0],' Processing is required. \n'); + end + elseif verb + cat_io_cprintf([0.0 0.5 0.0],' Reprocessing is NOT required. \n'); + end + end +end +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_main_APRG.m",".m","15442","353","function [Yb,Ym0,Yg,Ydiv] = cat_main_APRG(Ysrc,P,res,T3th,cutstr) +% ______________________________________________________________________ +% Skull-stripping subfunction APRG (adaptive probability region-growing) +% of cat_main_updateSPM. +% +% [Yb,Ym0,Yg,Ydiv] = cat_main_updateSPM(Ysrc,P,res,T3th,cutstr) +% +% Ysrc .. original input images +% P .. tissue segmentation (4D) +% res .. SPM preprocessing structure +% T3th .. tissue thresholds +% cutstr .. wider (0) or tider (0.99) masks (1 - auto; default: 0.5) +% Yb .. binary brain mask +% Ym0 .. probability brain mask +% Yg .. absolute gradient map (eg. for tissue edges) +% Ydiv .. divergence maps (eg. for blood vessels) +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + dbs = dbstatus; debug = 0; for dbsi=1:numel(dbs), if strcmp(dbs(dbsi).name,mfilename); debug = 1; break; end; end + + % adaptive probability region-growing + if debug, Po=P; end + + % Use gcutstr in version 2 to control the width of the mask. + % Smaller values are wider, larger values are tider, 0 use the old definition. + if ~exist('cutstr','var'), cutstr = 0; else, cutstr = mod(cutstr,1); end + + vx_vol = sqrt(sum(res.image(1).mat(1:3,1:3).^2)); + clsint = @(x) round( sum(res.mn(res.lkp==x) .* res.mg(res.lkp==x)') * 10^5)/10^5; + + %% tissue treshholds depending on MR modality + if T3th(1) < T3th(3) % T1 + cth = min(res.mn(res.lkp==3)); + cth = min(cth,T3th(1)); + cth = min(cth,cat_stat_nanmedian(Ysrc( cat_vol_morph( smooth3(P(:,:,:,3))>200 & ... + Ysrc200 & ... + Ysrc>sum(T3th(1:2).*[0.8 0.2]),'de',2,vx_vol) ) )); + end + % ######### + % RD202008: Although cth should be better the last test showed problems + % in skull-stripping so its more save to use it for the V2 + % that is only for experts. + % However, we should test this later again. + % ######### + if cutstr + T3th(1) = cth; + end + + + if max(res.lkp)==4 + bth = 0; + else + bth = min( res.mn(res.lkp==4) ); + end + if T3th(1) < T3th(3) % T1: CSF T3th(3) % T2/PD: WM128 )),clsint(6)); + Yg = cat_vol_grad((Ysrc - BGth)/diff([BGth,T3th(3)]),vx_vol); + BVth = abs(diff(T3th(1:2:3)) / abs(T3th(3)) * 3); % avoid blood vessels (high gradients) + RGth = abs(diff(T3th(2:3)) / abs(T3th(3)) * 0.1); % region growing threshold + + + + + %% initial brain mask by region-growing +% ########## +% RD2020007: Todo: further adaptation for T2/PD/MP2Rage and skull-stripped +% ########## + % as CSF/GM+GM+WM without blood vessels (Yg<0.5) + Yb = min(1,single(P(:,:,:,1))/255 + single(P(:,:,:,2))/255 + Ycg/2); + Yb = cat_vol_median3(Yb,Yb>0,true(size(Yb))); + if T3th(1) < T3th(3) % T1 + Yb = min(1,Yb + cat_vol_morph(smooth3(sum(P(:,:,:,1:3),4))>253,'ldc',1,vx_vol)); + else % T2/PD ... more tolerant + Yb = min(1,Yb + cat_vol_morph(smooth3(sum(P(:,:,:,1:3),4))>200,'ldc',1,vx_vol)); + end + %% + Yb = cat_vol_morph(Yb>0.8,'ldo',1.9,vx_vol); + Yb = cat_vol_morph(Yb,'ldc',1.9,vx_vol); + + + %% mask for region growing and WM-GM region growing + Yb2 = single(cat_vol_morph(Yb,'de',1.9,vx_vol)); + if T3th(1) < T3th(3) % T1 + Yh = (Yb2<0.5) & (Ysrc(T3th(3)*1.2) | Yg>BVth); + else + Yh = (Yb2<0.5) & (Ysrcsum(T3th(2:3).*[0.75 0.25]) | Yg>BVth); + end + Yh = cat_vol_morph(Yh,'dc',1,vx_vol); + Yh = cat_vol_morph(Yh,'de',1,vx_vol); Yb2(Yh) = nan; if ~debug, clear Yh; end + if T3th(1) < T3th(3) % T1 + [Yb2,YD] = cat_vol_downcut(Yb2,Ysrc/T3th(3),RGth/2); clear Yb2; %#ok + else + [Yb2,YD] = cat_vol_downcut(Yb2,1 - Ysrc/T3th(3),RGth/2); clear Yb2; %#ok + end + Yb(YD<400/mean(vx_vol)) = 1; clear YD; + Yb(smooth3(Yb)<0.5) = 0; + Yb = cat_vol_morph(Yb,'ldo',1.9,vx_vol); + Yb = cat_vol_morph(Yb,'ldc'); + + +%% GM-CSF region +% Yh is the region that we exclude +if cutstr == 0 + %% RD202007: This is the original version without further adaptations/corrections + Yb2 = single(cat_vol_morph(Yb,'de',1.9,vx_vol)); + if T3th(1) < T3th(3) + Yh = (Yb2<0.5) & (Ysrc250 | ... + Ysrc>cat_stat_nanmean(T3th(3)*1.2) | Yg>BVth); + else + Yh = (Yb2<0.5) & (Ysrc>sum(T3th(1:2).*[0.9 0.1]) | sum(P(:,:,:,4:6),4)>250 | ... + Ysrc<(T3th(3) - sum(T3th(2:3).*[0.5 0.5])) | Yg>BVth); + end + Yh = cat_vol_morph(Yh,'dc',1) | cat_vol_morph(~Yb,'de',10,vx_vol); + Yh = cat_vol_morph(Yh,'de',1,vx_vol); Yb2(Yh) = nan; if ~debug, clear Yh; end + if T3th(1) < T3th(3) % T1 + [Yb2,YD] = cat_vol_downcut(Yb2,Ysrc/T3th(3),-RGth); clear Yb2; %#ok + else + [Yb2,YD] = cat_vol_downcut(Yb2,1 - Ysrc/T3th(3),-RGth); clear Yb2; %#ok + end + Yb(YD<400/mean(vx_vol)) = 1; clear YD; + Yb(smooth3(Yb)<0.5) = 0; Yb(smooth3(Yb)>0.5) = 1; + Yb = cat_vol_morph(Yb,'ldo',1.9,vx_vol); + Yb = cat_vol_morph(Yb,'ldc'); +else + %% RD202007: This is the new Version that is quite similar but controlled by gcutstr + Yb2 = single(cat_vol_morph(cat_vol_morph(Yb,'de',1.9,vx_vol),'ldc',3)); + if T3th(1) < T3th(3) + Yh = (Yb2<0.5) & ( Ysrc<(T3th(1) - 1*(1-cutstr) * diff([T3th(1) min(T3th(2:3))])) | ... + cat_vol_morph(sum(P(:,:,:,4:6),4)>250,'e',2,vx_vol) | ... + (Ysrc>cat_stat_nanmean(mean(T3th(1:2))) & ~Yb) | Yg>BVth); + else + Yh = (Yb2<0.5) & ( Ysrc>(T3th(1) + 1*(1-cutstr) * diff([T3th(1) max(T3th(2:3))])/2) | ... + cat_vol_morph(sum(P(:,:,:,4:6),4)>250,'e',2,vx_vol) | ... + (Ysrc>cat_stat_nanmean(mean(T3th(1:2))) & ~Yb) | Yg>BVth); + end + Yh(smooth3(Yh)>0.7) = 1; Yh(smooth3(Yh)<0.3) = 0; + Yh = cat_vol_morph(Yh,'dc',1) | cat_vol_morph(~Yb,'de',10,vx_vol); + Yh = cat_vol_morph(Yh,'de',1,vx_vol); + Yh = cat_vol_morph(Yh,'do',1,vx_vol); + Yb2(Yh) = nan; if ~debug, clear Yh; end + if T3th(1) < T3th(3) % T1 + [Yb2,YD] = cat_vol_downcut(Yb2,Ysrc/T3th(3),max(0.03,min(0.1,-RGth*2))); clear Yb2; %#ok + else + [Yb2,YD] = cat_vol_downcut(Yb2,1 - Ysrc/T3th(3),max(0.03,min(0.1,-RGth))); clear Yb2; %#ok + end + Yb( (YD < 500 / mean(vx_vol) * (1 - cutstr/2)) & ... + Ysrc<(T3th(1) + 0.5*(1-cutstr) * min( abs( [ diff(T3th(1:2)) , diff(T3th(1:2:3)) ] ))) & ... + Ysrc>(T3th(1) - 0.5*(1-cutstr) * min( abs( [ diff(T3th(1:2)) , diff(T3th(1:2:3)) ] ))) ... + ) = 1; clear YD; + Yb(smooth3(Yb)<0.5) = 0; Yb(smooth3(Yb)>0.5) = 1; + Yb = cat_vol_morph(Yb,'ldo',1.9,vx_vol); + Yb = cat_vol_morph(Yb,'ldc'); +end + + + + %% CSF mask 2 with Yb + % Yc .. Combination of the CSF probability map and intensity map to + % avoid meninges (especially in older subjectes) at the outer + % boundary. Due to failed registration we directly use the + % brain mask Yb in the center of the brain, ie. we allow brain + % tissue in the CSF far from the skull. + cth2 = min(cth,cat_stat_nanmedian( Ysrc( smooth3( ... + cat_vol_morph(P(:,:,:,3)>200 & Yb & Yg<0.2,'de',1.5))>0.9 ) )); + if T3th(1) < T3th(3) + Yc = single(P(:,:,:,3) )/255 .* ... + max(Yb & Ygtth(3,1) & Ysrctth(3,1) & Ysrccth2,min(1,1 - ( abs(Ysrc - cth2) / ... + % (2 * abs( mean(res.mn(res.lkp==1)) - cth2) ) ) )); + + + + + %% update GM map (include tissue that was previously labeled as head) + for i=1:3 + % smaller mask in case of WM + if i==2, Ybt = cat_vol_morph(Yb,'de',1.5,vx_vol); else Ybt = Yb; end + % smooth mask in case of GM + if i==1 + Ytmp = single(P(:,:,:,4)) .* smooth3(Ybt & Ysrc>tth(i,1) & Ysrctth(i,1) & Ysrctth(i,1) & Ysrctth(i,1) & Ysrctth(i,1) & Ysrc0.5)); + Ym = cat_vol_median3(Ym,Ym>0 & Ym<1); % remove noise + % region-growing + Ym2 = Ym; Ym2(Ym2==0)=nan; + [Ym2,YD] = cat_vol_downcut(single(Ym2>0.99),Ym2,0.01); clear Ym2; %#ok + Ym(YD>400/mean(vx_vol))=0; clear YD; + Ym(cat_vol_morph(Ym>0.95,'ldc',1)) = 1; + Ym(cat_vol_morph(Yb,'e') & Ym<0.9 & Yc<0.25) = 0; + Ym = Ym .* cat_vol_morph(Ym>0.5,'ldo',2); % remove extensions (BV, eye) + Ym = cat_vol_laplace3R(Ym,Ym>0.1 & Ym<0.9,0.2); % smooth mask + Ym = cat_vol_laplace3R(Ym,Ym<0.25,0.2); + Ym(cat_vol_morph(Yb,'e') & Ym<0.9 & Yc<0.25) = 0; + + + %% cutting parameter + % This is a nice parameter to control the CSF masking. + % The default value of 0.5 which works best for validation data. + % However, by setting the value to 1 we can also use a surface to find the + % optimal value, which is currently not stable enough. + % RD202008: In the original version we final fix this to the average + % because the selection was not robust enough. + if cutstr==0; cutstr = 0.5; end % V2 + cutstrs = linspace(0.05,0.95,4); % 0.05,0.35,0.65,0.95]; + cutstrval = nan(1,4); + if debug, cutstrsa = zeros(0,8); end + Ysrc2 = (Ysrc>T3th(1)) .* (abs(Ysrc - T3th(1))/(T3th(2) - T3th(1))) + ... + (Ysrc + if debug, cutstrsa = [cutstrsa; cutstrs, cutstrval]; end %#ok + cutstrs = linspace(cutstrs(max(1,cutstrid(1)-1)),cutstrs(min(4,cutstrid(1)+1)),4); + cutstrval = [cutstrval(max(1,cutstrid(1)-1)),nan,nan,cutstrval(min(4,cutstrid(1)+1))]; + + end + cutstr = cutstrs(cutstrid(1)); + end + % MP2Rage + if res.isMP2RAGE + Yb = Yb | Ycc>0.5; + end + + + + %% normalize this map depending on the cutstr parameter + Yb = cat_vol_morph(cat_vol_morph(Ym > cutstr,'lo'),'lc',2); + Yb = cat_vol_morph(Yb,'e') | (Ym>0.9) | (Yb & Yc>0.5); + if cutstr>0; Yb(smooth3(Yb)>0.7) = 1; end % RD202008: V2: a bit closing shoud be also fine ... + Yb(smooth3(Yb)<0.5)=0; + Ybb = cat_vol_ctype( max(0,min(1,(Ym - cutstr)/(1-cutstr))) * 256); + Ym0 = Ybb; + + + %% estimate gradient (edge) and divergence maps + [Ysrcb,BB] = cat_vol_resize({Ysrc},'reduceBrain',vx_vol,round(6/mean(vx_vol)),Yb); + Yg = cat_vol_grad(Ysrcb/T3th(3),vx_vol); + Ydiv = cat_vol_div(Ysrcb/T3th(3),vx_vol); + Yg = cat_vol_resize(Yg ,'dereduceBrain',BB); + Ydiv = cat_vol_resize(Ydiv ,'dereduceBrain',BB); +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_surf_fun.m",".m","166858","4290","function varargout = cat_surf_fun(action,S,varargin) +%cat_surf_fun Set of functions to modify and evaluate surfaces. +% Call without parameters (only action) will print the help of this action. +% +% varargout = cat_surf_fun(action,S,varargin) +% +% varargout, varargin .. variable input depending on the called action +% action .. string to call a subfuction +% S .. surface structure with vertices and faces +% +% Actions: +% * Distance estimation: +% cat_surf_dist;"">dist Estimate edge length of faces in S. +% D = cat_surf_fun('dist',S); +% cat_surf_vdist;"">vdist Estimate distance of each voxel to S. +% D = cat_surf_fun('vdist',S); +% cat_surf_thickness;"">tfs Estimate FreeSurfer thickness. +% T = cat_surf_fun('Tfs',S,varargin{1}); +% cat_surf_thickness;"">tmin Estimate minimum thickness. +% T = cat_surf_fun('Tmin',S,varargin{1}); +% cat_surf_thickness;"">tmax Estimate maximum thickness. +% T = cat_surf_fun('Tmax',S,varargin{1}); +% +% * Data mapping: +% cat_surf;"">? Map face data to vertices. +% V = cat_surf_fun('?',S,F); +% cat_surf_cdatamapping;"">cdatamapping Map texture cdata from S2 to S1. +% C = cat_surf_fun('cdatamapping',S1,S2,cdata[,opt]); +% cat_surf_createEdgemap;"">createEdgemap Creates mapping between two surfaces. +% edgemap = cat_surf_fun('createEdgemap',S1,S2); +% cat_surf_createEdgemap;"">useEdgemap Apply mapping between two surfaces. +% cdata2 = cat_surf_fun('useEdgemap',cdata,edgemap); +% +% * Surface (data) rendering: +% cat_surf_surf2vol;"">surf2vol Render surface (data) to a volume. +% V = cat_surf_fun('surf2vol',S,varargin{1}); +% +% * Surface modification: +% cat_surf_hull;"">hull Estimate hull surface. +% HS = cat_surf_fun('hull',S); +% cat_surf_core;"">core Estimate core surface. +% HS = cat_surf_fun('core',S); +% cat_surf_createinneroutersurface;"">inner Estimate inner surface. +% IS = cat_surf_fun('inner',S,T); +% cat_surf_createinneroutersurface;"">outer Estimate outer surface. +% OS = cat_surf_fun('outer',S,T); +% cat_surf_saveICO;"">saveICO Save multiple output surfaces & measures. +% cat_surf_saveICO(S,T,Pcentral,subdir,writeTfs,C) +% +% * Other functions: +% cat_suf_smoothtexture;"">smoothcdata Smooth surface data. +% +% +% +% * Helping functions: +% cat_surf_area;"">area Estimate face surface area. +% A = cat_surf_fun('area',S); +% cat_surf_graph2edge;"">graph2edge Extract edges of a triangulation T. +% E = cat_surf_fun('graph2edge',T); +% +% * Test functions: +% cat_surf_createEdgemap;"">cdatamappingtst +% +% See also spm_mesh_* functions. +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +% See also spm_mesh_area, spm_mesh_borders, +% spm_mesh_calc, spm_mesh_clusters, spm_mesh_contour, spm_mesh_curvature, +% spm_mesh_detect, spm_mesh_distmtx, spm_mesh_edges, spm_mesh_euler, +% spm_mesh_geodesic, spm_mesh_get_lm, spm_mesh_inflate, spm_mesh_join, +% spm_mesh_label, spm_mesh_max, spm_mesh_neighbours, spm_mesh_normals, +% spm_mesh_polyhedron, spm_mesh_project, spm_mesh_reduce, spm_mesh_refine +% spm_mesh_resels, spm_mesh_smooth, spm_mesh_sphere, spm_mesh_split, +% spm_mesh_to_grid, spm_mesh_transform, spm_mesh_utils. +% spm_mesh_adjacency + +%#ok<*ASGLU,*AGROW> + + switch lower(action) + case 'normals' + if nargin<2, help cat_surf_fun>cat_surf_normals; return; end + varargout{1} = cat_surf_normals(S); + + case 'localsurfsmooth' + varargout{1} = cat_surf_localsurfsmooth(S,varargin{:}); + + case 'angle' + varargout{1} = cat_surf_edgeangle(S,varargin{1}); + + case 'dist' + if nargin<2, help cat_surf_fun>cat_surf_dist; return; end + varargout{1} = cat_surf_dist(S); + + case 'surf2surf' + % create mapping between similar surfaces for area projection + % using Delaunay (will be slow for large surface >1'000'000 + if nargin<2, help cat_surf_fun>cat_surf_surf2surf; return; end + varargout{1} = cat_surf_surf2surf(S,varargin{1}); + + case 'area' + % simple area estimation of S + if nargin<2, help cat_surf_fun>cat_surf_area; return; end + switch nargout + case 1 + varargout{1} = cat_surf_area(S); + case 2 + [varargout{1},varargout{2}] = cat_surf_area(S); + end + + case {'smoothcdata','smoothtexture'} + % use CAT smoothing rather than spm_mesh_smooth + % differences? + if nargin<2, help cat_surf_fun>cat_surf_smoothtexture; return; end + switch nargin + case 2 + if isfield(S,'cdata'), varargout{1} = cat_surf_smoothtexture(S,S.cdata,1); end + otherwise, varargout{1} = cat_surf_smoothtexture(S,varargin{:}); + end + + case 'maparea' + % do the final area projection + if nargin<2, help cat_surf_fun>cat_surf_maparea; return; end + if nargout==1, varargout{1} = cat_surf_maparea(S,varargin{:}); end + if nargout==2, [varargout{1},varargout{2}] = cat_surf_maparea(S,varargin{:}); end + + case 'hull' + % create a hull surface + if nargin<2, help cat_surf_fun>cat_surf_hull; return; end + if nargout==1, varargout{1} = cat_surf_hull(S); end + if nargout==2, [varargout{1},varargout{2}] = cat_surf_hull(S); end + + case 'core' + % create a core surface + if nargin<2, help cat_surf_fun>cat_surf_core; return; end + if nargout==1, varargout{1} = cat_surf_core(S,varargin{:}); end + if nargout==2, [varargout{1},varargout{2}] = cat_surf_core(S,varargin{:}); end + + case {'tfs','tmin','tmax'} + % estimate the distance between two (linked) surfaces + if nargin<2, help cat_surf_fun>cat_surf_thickness; return; end + if numel(varargin)==1 + if nargout==1 + varargout{1} = cat_surf_thickness(action,S,varargin{1}); + else + cat_surf_thickness(action,S,varargin{1}); + end + else + if nargout==1 + varargout{1} = cat_surf_thickness(action,S); + else + cat_surf_thickness(action,S); + end + end + + case {'tlink','surfdist'} + % tlink. Estimate the distance/thickness between two linked surfaces. + % See also tfs, tmin, and tmax for unlinked/unrelated surfaced. + if nargin<2, help cat_surf_fun>cat_surf_tlink; return; end + varargout{1} = cat_surf_tlink(S,varargin{1}); + + case 'checknormaldir' + varargout{1} = cat_surf_checkNormalDir(S); + + case 'meshinterp' + %S=cat_surf_meshinterp(S,interp,method,distth) + varargout{1} = cat_surf_meshinterp(S,varargin{:}); + + case {'inner','outer','white','pial','innervar','outervar','whitevar','pialvar'} + % create different cortical surfaces + if nargin<2, help cat_surf_fun>cat_surf_GMboundarySurface; return; end + if numel(varargin)==1 + switch nargout % surface & texture input + case 0, cat_surf_GMboundarySurface(action,S,varargin{:}); + case 1, varargout{1} = cat_surf_GMboundarySurface(action,S,varargin{:}); + case 2, [varargout{1},varargout{2}] = cat_surf_GMboundarySurface(action,S,varargin{:}); + end + else % file input + switch nargout + case 0, cat_surf_GMboundarySurface(action,S); + case 1, varargout{1} = cat_surf_GMboundarySurface(action,S); + case 2, [varargout{1},varargout{2}] = cat_surf_GMboundarySurface(action,S); + end + end + + case 'disterr' + switch nargout + case 0, cat_surf_disterr(S,varargin{:}); + case 1, varargout{1} = cat_surf_disterr(S,varargin{:}); + case 2, [varargout{1},varargout{2}] = cat_surf_disterr(S,varargin{:}); + end + + + case 'evalcs' + % evaluation of the central and inner/outer surfaces + if nargin<2, help cat_surf_fun>cat_surf_evalCS; return; end + varargout{1} = cat_surf_evalCS(S,varargin{:}); + + case 'createinneroutersurface' + % not a good name ... this is for the Laplacian approach + if nargin<2, help cat_surf_fun>cat_surf_createinneroutersurface; return; end + cat_surf_createinneroutersurface(S,varargin{:}); + + case 'show_orthview' + % show cortical surfaces in the orthview window + if nargin<2, help cat_surf_fun>show_orthview; return; end + cat_surf_show_orthview(S,varargin{:}); + + case 'saveico' + % save the inner, central, and outer surfaces + if nargin<2, help cat_surf_fun>show_orthview; return; end + cat_surf_saveICO(S,varargin{:}); + + case 'collisioncorrection' + % Delaunay-based correction of surface self-intersections - not working + if nargin<2, help cat_surf_fun>show_orthview; return; end + [varargout{1},varargout{2}] = cat_surf_collision_correction(S,varargin{:}); + + case 'collisioncorrectionry' + % CAT_SelfIntersect-based correction of surface self-intersections + if nargin<2, help cat_surf_fun>show_orthview; return; end + [varargout{1},varargout{2},varargout{3}] = cat_surf_collision_correction_ry(S,varargin{:}); + + case 'collisioncorrectionpbt' + % correction of self-intersections based on the PBT PP map + if nargin<2, help cat_surf_fun>show_orthview; return; end + [varargout{1},varargout{2},varargout{3}] = cat_surf_collision_correction_pbt(S,varargin{:}); + + case 'vdist' + % ? + if nargin<2, help cat_surf_fun>show_orthview; return; end + [varargout{1},varargout{2}] = cat_surf_vdist(S,varargin); + + case {'vol2surf','isocolor'} + [varargout{1}] = cat_surf_isocolors2(S,varargin{:}); + + + case 'surf2vol' + % Render surface (data) into volume space. See also spm_mesh_to_grid. + if nargin<2, help cat_surf_fun>surf2vol; return; end + if nargout>3 + if nargin>2 + [varargout{1},varargout{2},varargout{3},varargout{4}] = cat_surf_surf2vol(S,varargin{:}); + else + [varargout{1},varargout{2},varargout{3},varargout{4}] = cat_surf_surf2vol(S); + end + elseif nargout>2 + if nargin>2 + [varargout{1},varargout{2},varargout{3}] = cat_surf_surf2vol(S,varargin{:}); + else + [varargout{1},varargout{2},varargout{3}] = cat_surf_surf2vol(S); + end + elseif nargout>1 + if nargin>2 + [varargout{1},varargout{2}] = cat_surf_surf2vol(S,varargin{:}); + else + [varargout{1},varargout{2}] = cat_surf_surf2vol(S); + end + else + if nargin>2 + varargout{1} = cat_surf_surf2vol(S,varargin{:}); + else + varargout{1} = cat_surf_surf2vol(S); + end + end + case 'smat' + % Apply matrix transformation. See also spm_mesh_transform. + if nargin<2, help cat_surf_fun>cat_surf_mat; return; end + varargout{1} = cat_surf_mat(S,varargin{:}); + + case 'graph2edge' + % extract edges from a give graph + if nargin<2, help cat_surf_fun>cat_surf_edges; return; end + switch nargout + case 0, cat_surf_edges(S); + case 1, varargout{1} = cat_surf_edges(S); + case 2, [varargout{1},varargout{2}] = cat_surf_edges(S); + end + + case 'cdatamappingtst' + cat_surf_cdatamappingtst; + + case 'createedgemap' + % ??? + if nargin<2, help cat_surf_fun>cat_surf_surf2surf; return; end + varargout{1} = cat_surf_surf2surf(S,varargin{:}); + + case 'useedgemap' + % ??? + if nargin<2, help cat_surf_fun>cat_surf_maparea; return; end + varargout{1} = cat_surf_maparea(S,varargin{:}); + + case 'gmv' + % ??? + if nargin<2, help cat_surf_fun>cat_surf_gmv; return; end + varargout{1} = cat_surf_gmv(S,varargin{:}); + + case 'cdatamapping' + % ??? + if nargin<2, help cat_surf_fun>cat_surf_cdatamapping; return; end + if nargin<3, varargin{3} = ''; end + if nargin<4, varargin{4} = struct(); end + if nargout>1 + [varargout{1},varargout{2}] = cat_surf_cdatamapping(S,varargin{:}); + else + varargout{1} = cat_surf_cdatamapping(S,varargin{:}); + end + + case 'reduce' + varargout{1} = cat_surf_reduce(S,varargin{:}); + + case 'isocolors' + % Similar to MATLAB isocolor function but faster and support to use mat + % files. See also spm_mesh_project. + if nargin<2, help cat_surf_fun>isocolors2; return; end + varargout{1} = cat_surf_isocolors2(S,varargin{:}); + + case 'approxnans' + varargout{1} = cat_surf_approxnans(S); + + otherwise + error('Unknow action ""%s""! Check ""help cat_surf_fun"".\n',action); + end + +end +function S = cat_surf_tlink(S1,S2) +% tlink. Estimate the distance/thickness between two linked surfaces. +% See also tfs, tmin, and tmax for unlinked/unrelated surfaced. + if numel( S1.vertices ) ~= numel( S2.vertices ) || ... + numel( S1.faces ) ~= numel( S2.faces ) + error(['Surfaces has to have the same number of vertices and faces.' ... + 'Use tfs, tmin, or tmax functions otherwise']); + end + S.facevertexcdata = sum((S1.vertices - S2.vertices).^2,2).^(1/2); + S.vertices = mean(cat(3,S1.vertices,S2.vertices),3); + S.faces = S1.faces; +end +function S2 = cat_surf_approxnans(S,D,ds) + if ~exist('D','var') + if isfield(S,'facevertexcdata') + D = S.facevertexcdata; + elseif isfield(S,'cdata') + D = S.cdata; + end + end + if ~exist('ds','var') + ds = 10; + end + + V = double(S.vertices(~isnan(D),:)); + T = delaunayn(V); + + [VI,VD] = dsearchn(V,T,double(S.vertices(isnan(D),:))); + Dv = D(~isnan(D)); + Df = D; Df(isnan(D)) = Dv(VI); + + M = spm_mesh_smooth(S); + Ds = single(spm_mesh_smooth(M,double(Df),ds * mean(VD))); + D(isnan(D)) = Ds(isnan(D)); + + if isfield(S,'facevertexcdata') + S2=S; S2.facevertexcdata = D; + elseif isfield(S,'cdata') + S2=S; S2.cdata = D; + else + S2 = D; + end +end + +function CS = cat_surf_localsurfsmooth(CS,C,s) +% local surface filter for a surface CS that is filters vertices with the +% amount defined by C (0 no fitlering, 1 full filtering) and s as number +% of iteration. + + if ~exist('s','var'), s = 1; end + + M = spm_mesh_smooth(CS); + if isempty(C) || all(size(C)==1) + if nargin<3 && all(size(C)==1) + CS.vertices = cat_surf_smooth(M,CS.vertices,C); + else + CS.vertices = cat_surf_smooth(M,CS.vertices,s); + end + else + Cst = sort(C); + + for i=1:s + Ci = min(1,max(0,C - (s - i) * Cst(round(numel(C)*0.99)))); + CSV = cat_surf_smooth(M,CS.vertices,1); + CS.vertices = CS.vertices .* repmat(1 - Ci,1,3) + CSV .* repmat(Ci,1,3); + end + end +end + +function S = cat_surf_reduce(S,red) + Ptemp = tempname; + Ptmpo = [Ptemp 'o.gii']; + Ptmpn = [Ptemp 'n.gii']; + + % save surface + save(gifti(struct('faces',S.faces,'vertices',S.vertices)),Ptmpo,'Base64Binary'); + clear Sgii + + % call + for i=1:3 + %fprintf('.'); + if i>1, pause(5); end + if ispc + cmds = sprintf('set PATH=%s; start ',fullfile(matlabroot,'bin')); + else + cmds = sprintf('%s/',fullfile(matlabroot,'bin')); + end + cmd = sprintf(['matlab -nojvm -nosplash -nodisplay -r ' ... + '""try, %s; catch, disp(''Error''); end; exit; ""'],... + sprintf(['addpath(''%s''); S = gifti(''%s''); '... + 'S = reducepatch( struct(''vertices'',S.vertices,''faces'',S.faces) , %g); ' ... + 'save(gifti(S),''%s'',''Base64Binary''); '],fullfile(fileparts(mfilename('fullpath'))),Ptmpo,red,Ptmpn)); + evalc('[ST, RS] = system([cmds,cmd]); cat_check_system_output(ST,RS,1);'); + + if exist(Ptmpn,'file'); break; end + end + delete(Ptmpo) + if ~exist(Ptmpn,'file') + error('cat_surf_fun:reducemesh','Failed %d times to reduce surface resolution.\n%s',i); + end + + Sgii = gifti(Ptmpn); delete(Ptmpn); + S = struct('vertices',Sgii.vertices,'faces',Sgii.faces); +end +%% area mapping concept +% ------------------------------------------------------------------------ +% We need two functions, one that create the mapping between two very +% close surfaces (cat_surf_surf2surf) and another one (cat_surf_maparea) +% that finally performs the mapping. +% ------------------------------------------------------------------------ +% Robert Dahnke 2019/04 +function edgemap = cat_surf_surf2surf(S1,S2,normalize) +% ------------------------------------------------------------------------ +% Create mapping between two surface by nearest neighbor search on a +% Delaunay graph. +% +% edgemap = cat_surf_surf2surf(S1,S2,normalize) +% +% see also cat_surf_maparea"">cat_surf_surf>cat_surf_maparea +% ------------------------------------------------------------------------ +% Robert Dahnke 2019/04 + + if ~exist('normalize','var'), normalize=1; end + + % 0. Normalize input + if normalize + S1.vertices = S1.vertices/max(S1.vertices(:)); + S2.vertices = S2.vertices/max(S2.vertices(:)) * 0.98; % need slight difference for Delaunay! + end + + % 1. Delaunay triangulation for fast search + D1 = delaunayn(double(S1.vertices)); + D2 = delaunayn(double(S2.vertices)); + + % 2. find minimal relation between the vertices of S1 and S2 as nearest neighbor + E1(:,1) = 1:size(S1.vertices,1); + E2(:,2) = 1:size(S2.vertices,1); + E1(:,2) = dsearchn(double(S2.vertices),D2,double(S1.vertices)); + E2(:,1) = dsearchn(double(S1.vertices),D1,double(S2.vertices)); + E = unique([E1;E2],'rows'); + + % 3. estimate edge length as weighting function + EL = sum( ( S1.vertices(E(:,1),:) - S2.vertices(E(:,2),:) ).^2 , 2) .^ 0.5; + + % 4. Estimate the number of all by c-function + % - outgoing edges of S1 (connections from v element of S1) and + % - incoming edges of S2 (connections from v element of S2) + nE1 = zeros(max(E(:,1)),1,'single'); EL1 = zeros(max(E(:,1)),1,'single'); + nE2 = zeros(max(E(:,2)),1,'single'); EL2 = zeros(max(E(:,2)),1,'single'); + for i=1:size(E,1) + nE1( E(i,1) ) = nE1( E(i,1) ) + 1; + EL1( E(i,1) ) = EL1( E(i,1) ) + EL(i); + nE2( E(i,2) ) = nE2( E(i,2) ) + 1; + EL2( E(i,2) ) = EL2( E(i,2) ) + EL(i); + end + + % 5. Create a weighting function to project data from Si2St and St2Si. + edgemap.edges = E; + edgemap.dist = EL; + edgemap.nvertices = [size(S1.vertices,1),size(S2.vertices,1)]; + edgemap.nforward = 1 ./ nE1(E(:,1)); + edgemap.nbackward = 1 ./ nE2(E(:,2)); + edgemap.dforward = EL ./ EL1(E(:,1)); + edgemap.dbackward = EL ./ EL2(E(:,2)); +end + +function varargout = cat_surf_maparea(varargin) +% Apply graph-based mapping +% ------------------------------------------------------------------------ +% use a c-function to process cat_surf_surf2surf mapping function +% +% cdata = cat_surf_maparea(cdatain,edgemap[,weighting]) +% +% cdata .. texture values at the output surface +% edgemap .. mapping structure between two surfaces +% direction .. direction of cdata mapping if both surfaces have cdata +% with direction: 'forward' == '', 'backward' == 'invers' +% weighting .. type of weighting: +% 'num' .. by number of vertices +% 'dist' .. by distance to the vertices (default) +% +% ------------------------------------------------------------------------ +% Robert Dahnke 2019/04 + + cdata = varargin{1}; + edgemap = varargin{2}; + if nargin>2 + dir = varargin{3}; + else + dir = ''; + end + switch dir + case {'','forward'}, idir = 0; + case {'invers','backward'}, idir = 1; + otherwise, error('Unkown mapping direction %s.\n',dir); + end + + varargout{1} = cat_surf_edgemap(edgemap,cdata,idir); + + % filter with 1/mean(edgelegnth? + % check for area? +end + +function cdata2 = cat_surf_edgemap(edgemap,cdata,idir) + if idir==0 + cdata2 = zeros(edgemap.nvertices(2),1,'single'); + for i=1:size(edgemap.edges,1) + cdata2(edgemap.edges(i,2)) = cdata2(edgemap.edges(i,2)) + ... + cdata(edgemap.edges(i,1)) * edgemap.dforward(i); + end + else + cdata2 = zeros(edgemap.nvertices(1),1,'single'); + for i=1:size(edgemap.edges,1) + cdata2(edgemap.edges(i,1)) = cdata2(edgemap.edges(i,1)) + ... + cdata2(edgemap.edges(i,2)) * edgemap.dbackward(i); + end + end +end + +function [IS,OS] = cat_surf_createinneroutersurface(S,T,Yp0) + if ~exist('Yp0','var') + % render surface + Yp0 = 0; + end + + % test flipping + flipped = cat_surf_checkNormalDir(S); + if flipped && isfield( S , 'mati' ) + S.faces = [S.faces(:,1) S.faces(:,3) S.faces(:,2)]; + if isfield( S , 'mati' ), S.mati(7) = - S.mati(7); end + end + + % call laplace + L = cat_surf_laplace(Yp0); + + % create streamlines + IS.vertices = cat_surf_steams(L ,T/2); + OS.vertices = cat_surf_steams(1-L,T/2); +end + +function VV = cat_surf_gmv(IS,OS) +% Estimate the volume between the given inner and outer boundary surface. +% +% VV = cat_surf_gmv(IS,OS) +% +% VV .. volume between IS and OS +% IS .. inner surface +% OS .. outer surface +% +% Robert Dahnke 201904 + + IV = IS.vertices*0.45 + 0.55*OS.vertices; + OV = OS.vertices*0.45 + 0.55*OS.vertices; + + % create Delaunay triangulation + D = delaunayn(double([IV;OV])); clear IV OV; + + % ############# + % classify and remove non GM tetraeder that have only WM points (ok) but + % only GM? points ( this will not work for all gyri/sulci) + % ############# + % - you maybe can use the centerpoint and then ... + % - or you just use two verly lighty displaced surfaces, ie. 0.01 mm + % thickness that would give a Delaunay triangulation without the bad + % gyral effects! + % ############# + DS = D>size(IS.vertices,1); + D( sum(DS,2)==0 | sum(DS,2)==4 ,:) = []; + clear DS; + + % estimate tetraeder volume + DV = tetraedervolume(D,double([IS.vertices;OS.vertices])); + + %% map volume to faces + VV = zeros(size(IS.vertices,1),1,'single'); + DF = D; DF(DF>size(IS.vertices,1)) = DF(DF>size(IS.vertices,1)) - size(IS.vertices,1); % to use the IS indices for mapping + for i=1:size(DV,1) + for j=1:4 + VV(DF(i,j)) = VV(DF(i,j)) + DV( i ) / 4; + end + end + +end + +function DV = tetraedervolume(D,V) +% estimate tetraeder volume by the Cayley-Menger determinant +% Robert Dahnke 201904 + + % edgelength + r = sum( ( V(D(:,1),:) - V(D(:,2),:) ).^2 , 2).^0.5; + p = sum( ( V(D(:,2),:) - V(D(:,3),:) ).^2 , 2).^0.5; + q = sum( ( V(D(:,3),:) - V(D(:,1),:) ).^2 , 2).^0.5; + a = sum( ( V(D(:,1),:) - V(D(:,4),:) ).^2 , 2).^0.5; + b = sum( ( V(D(:,2),:) - V(D(:,4),:) ).^2 , 2).^0.5; + c = sum( ( V(D(:,3),:) - V(D(:,4),:) ).^2 , 2).^0.5; + + % volume + DV = zeros(size(D,1),1); + for i=1:size(D,1) + DM = [ 0 r(i) q(i) a(i) 1;... + r(i) 0 p(i) b(i) 1;... + q(i) p(i) 0 c(i) 1;... + a(i) b(i) c(i) 0 1;... + 1 1 1 1 0]; + DV(i) = sqrt(det( DM .^2 ) / 288); + end +end + +function varargout = cat_surf_GMboundarySurface(type,varargin) +% +% ... = cat_surf_GMboundarySurface(type,Ps,Pth) +% +% type .. projection direction +% ['inner'|'outer'|'white'|'pial'] .. varargout is a filename +% ['innervar'|'outervar'|'whitevar'|'pialvar'] +% .. varargout is a variable +% Ps .. filename of a given surface +% Pth .. thickness of the surface +% + + if strfind(type,'var') + varout=1; type = strrep(type,'var',''); + else + varout=0; + end + switch type + case {'white','inner'}, direction = -0.5; + case {'pial' ,'outer'}, direction = 0.5; + end + + if nargin>=2 + %% use filenames + [pp,ff,ee] = spm_fileparts(varargin{1}); + + if strcmp(ee,'') + Praw = cat_io_FreeSurfer('fs2gii',varargin{1}); + Praw = Praw{1}; + else + Praw = varargin{1}; + end + if nargin==3 + Pthick = varargin{2}; + else + Pthick = cat_io_strrep(Praw,{'central','.gii'},{'pbt',''}); + if ~exist(Pthick,'file') + Pthick = cat_io_strrep(Praw,{'central','.gii'},{'thickness',''}); + end + if ~exist(Pthick,'file') && exist(cat_io_strrep(Praw,'central','pbt'),'file') + Pthick = cat_io_strrep(Praw,{'central','.gii'},{'pbt',''}); + movefile(cat_io_strrep(Praw,{'central'},{'pbt'}),Pthick); + end + end + Ptype = cat_io_strrep(Praw,'central',type); + + cmd = sprintf('CAT_Central2Pial ""%s"" ""%s"" ""%s"" %0.2f',Praw,Pthick,Ptype,direction); + cat_system(cmd,1); + + if strcmp(ee,'') + Ptype = cat_io_FreeSurfer('gii2fs',Ptype); + end + + % filename + if varout + % load surface + varargout{1} = gifti(Ptype); + + % delete temp files + delete(Ptype); + else + varargout{1} = Ptype; + end + else + % write temp files ... + Praw = 'central.'; + Pthick = strrep(Praw,'central','pbt'); + Ptype = strrep(Praw,'central',type); + + cmd = sprintf('CAT_Central2Pial ""%s"" ""%s"" %0.2f',Praw,Pthick,direction); + cat_system(cmd,1); + + % load surface + varargout{1} = gifti(Ptype); + + % delete temp files + delete(Praw,Pthick,Ptype); + end +end + +function cat_surf_cdatamappingtst +% ??? +% need at least some input +% +% + + +%% Testdata + Psubcentral = ['/Volumes/vbmDB/MRData/vbm12tst/results/deffiles/cg_vbm_defaults_template/template_NKI/'... + 'surf/lh.central.NKI_HC_NKI_1013090_T1_SD000000-RS00.gii']; + PsubsphereA = strrep(Psubcentral,'central','sphere.reg'); + %Psubthick = strrep(strrep(Psubcentral,'central','pbt'),'.gii',''); + Psubthickres = strrep(strrep(Psubcentral,'central','thickness.resampled'),'lh.','s15mm.lh.'); + Psubtmp = strrep(Psubcentral,'central','tmp'); + Pavgtmp = strrep(strrep(Psubcentral,'central','tmp.resampled'),'lh.','s15mm.lh.'); + + %Pavgcentral = fullfile(fileparts(mfilename('fullpath')),'templates_surfaces','lh.central.freesurfer.gii')); + PavgsphereA = fullfile(fileparts(mfilename('fullpath')),'templates_surfaces','lh.sphere.freesurfer.gii'); + PavgDKT40 = fullfile(fileparts(mfilename('fullpath')),'atlases_surfaces','lh.aparc_DKT40JT.freesurfer.annot'); + +%% Test 1 - avg2sub - ok + Ssub = gifti(PsubsphereA); + Savg = gifti(PavgsphereA); + [vertices, label, colortable] = cat_io_FreeSurfer('read_annotation',PavgDKT40); + Savg.cdata = label; + + S3 = gifti(Psubcentral); + S3.cdata = cat_surf_fun('cdatamapping',Ssub,Savg,'nearest'); + save(gifti(S3),Psubtmp); + +%% Test2 - sub2avg - ok + Savg = gifti(PavgsphereA); + Ssub = gifti(PsubsphereA); + %Ssub.cdata = cat_io_FreeSurfer('read_surf_data',Psubthick); + Ssub.cdata = cat_surf_fun('area',gifti(Psubcentral)); + + S3 = gifti(Psubthickres); + mapping = {'directed'}; %,'undirected'}; %'nearest', + for mi = 1:numel(mapping) + S3.cdata = cat_surf_fun('cdatamapping',Savg,Ssub,mapping{mi},1); + S3.cdata = spm_mesh_smooth(struct('vertices',S3.vertices,'faces',S3.faces),double(S3.cdata'),5); + fprintf('mapping = %10s: A(sub) = %0.2f vs. A(avg) = %0.2f\n',mapping{mi},sum(Ssub.cdata(:)),sum(S3.cdata(:))); + save(gifti(S3),Pavgtmp); cat_surf_display(Pavgtmp) + end + +end + +function varargout = cat_surf_cdatamapping(S1,S2,cdata,opt) +% nearest connection between to surfaces + if ischar(S1), S1 = gifti(S1); end + if ischar(S2), S2 = gifti(S2); end + if ischar(cdata) + Pcdata = cdata; + [pp,ff,ee] = spm_fileparts(cdata); + switch ee + case '.annot' + [vertices, cdata] = cat_io_FreeSurfer('read_annotation',Pcdata); + clear vertices + case '.gii' + Scdata = gifti(S2); + if isfield(Scdata,'cdata') + cdata = SX.cdata; + else + error('cat_surf_fun:cdatamapping:noTexture','No texture found in ""%s""!\n',Pcdata); + end + otherwise + cdata = cat_io_FreeSurfer('read_surf_data',Pcdata); + end + end + + if ~exist('cdata','var') || isempty(cdata) + if isfield(S2,'cdata'), cdata = S2.cdata; end + end + + if ~exist('opt','var'), opt = struct(); end + def.method = 'nearest'; + def.verb = 0; + def.smooth = 0; + opt = cat_io_checkinopt(opt,def); + + if opt.verb, stime1 = cat_io_cmd(sprintf('Data-mapping (%s)',method)); fprintf('\n'); end + + % prepare vertices + S1.vertices = S1.vertices ./ repmat(max(S1.vertices),size(S1.vertices,1),1)*1.1; % *100 + S2.vertices = S2.vertices ./ repmat(max(S2.vertices),size(S2.vertices,1),1); + verticesS1 = double(S1.vertices - repmat(mean(S1.vertices),size(S1.vertices,1),1)); + verticesS2 = double(S2.vertices - repmat(mean(S2.vertices),size(S2.vertices,1),1)); + + + % estimate mapping + switch opt.method + case {'nearest'} + [varargout{2},varargout{3}] = dsearchn([verticesS2;inf(1,3)],double([S2.faces ones(size(S2.faces,1),1)*(size(S2.vertices,1)+1)]),verticesS1); + varargout{1} = cdata(varargout{2}); + case {'undirected','directed'} + %% use the surface as delauny graph + switch opt.method + case 'directed' + if opt.verb, stime = cat_io_cmd(' Edge-Estimation (Nearest)','g5',''); end + nextS2fromS1 = dsearchn([verticesS2;inf(1,3)],double([S2.faces ones(size(S2.faces,1),1)*(size(S2.vertices,1)+1)]),verticesS1); + nextS1fromS2 = dsearchn([verticesS1;inf(1,3)],double([S1.faces ones(size(S1.faces,1),1)*(size(S1.vertices,1)+1)]),verticesS2); + tmp = nextS1fromS2; nextS1fromS2 = nextS2fromS1; nextS2fromS1 = tmp; + nearestedges = [ (1:numel(nextS2fromS1))', nextS2fromS1; nextS1fromS2 , (1:numel(nextS1fromS2))' ]; + nearestedges = unique(nearestedges,'rows'); + case 'undirected' + if opt.verb, stime = cat_io_cmd(' Edge-Estimation (Delaunay','g5',''); end + % nearest is required too + nextS2fromS1 = dsearchn([verticesS2;inf(1,3)],double([S2.faces ones(size(S2.faces,1),1)*(size(S2.vertices,1)+1)]),verticesS1); + nextS1fromS2 = dsearchn([verticesS1;inf(1,3)],double([S1.faces ones(size(S1.faces,1),1)*(size(S1.vertices,1)+1)]),verticesS2); + tmp = nextS1fromS2; nextS1fromS2 = nextS2fromS1; nextS2fromS1 = tmp; + nearestedges = [ (1:numel(nextS2fromS1))', nextS2fromS1; nextS1fromS2 , (1:numel(nextS1fromS2))' ]; + nearestedges1 = unique(nearestedges,'rows'); + % delauany + triangulation = delaunayn([verticesS2;verticesS1]); % delaunay triangulation + nearestedges = cat_surf_fun('graph2edge',triangulation); % get edges + nearestedges(sum(nearestedges<=size(verticesS2,1),2)~=1,:)=[]; % only edges between S1 and S2 + nearestedges(:,2) = nearestedges(:,2) - size(verticesS2,1); + nearestedges = unique([nearestedges;nearestedges1],'rows'); + end + if opt.verb, stime = cat_io_cmd(' Weighting','g5','',1,stime); end + + if 0 + %% my little testset + nextS1fromS2 = [1; 1; 3; 4; 4; 4; 5; 5]; + nextS2fromS1 = [1; 3; 3; 5; 8; 8]; + cdata = [1 1 1 1 1 1]'; + nearestedges = [ (1:numel(nextS2fromS1))', nextS2fromS1; nextS1fromS2 , (1:numel(nextS1fromS2))' ]; + nearestedges = unique(nearestedges,'rows'); + end + + + %% simplify edges 1 + if 0 + % simpler, but much slower + nearestedges = [nearestedges, ones(size(nearestedges,1),1)]; % default weight + [NeighborsS1,NidS1] = hist(nearestedges(:,1),1:1:max(nearestedges(:,1))); + for ni=NidS1(NeighborsS1>1) + NumNi = nearestedges(:,1)==ni; + nearestedges(NumNi,3) = nearestedges(NumNi,3) ./ sum(NumNi); + end + else + % faster + %nearestedges = [nearestedges, ones(size(nearestedges,1),1)]; % default weight + dist = sum( (S2.vertices(nearestedges(:,1),:) - S1.vertices(nearestedges(:,2),:)).^2 , 2) .^ 0.5; + nearestedges = [nearestedges, dist]; % default weight + list = [1; find(nearestedges(1:end-1,1)~=nearestedges(2:end,1))+1; size(nearestedges,1)]; + for ni=1:numel(list)-1 + %nearestedges(list(ni):list(ni+1)-1,3) = nearestedges(list(ni):list(ni+1)-1,3) ./ (list(ni+1) - list(ni)); + nearestedges(list(ni):list(ni+1)-1,3) = nearestedges(list(ni):list(ni+1)-1,3) ./ sum(nearestedges(list(ni):list(ni+1)-1,3)); + end + end + if opt.verb, stime = cat_io_cmd(' Mapping','g5','',1,stime); end + + %% + if 0 + % correct & simple, but very slow + varargout{1} = zeros(1,max(nearestedges(:,2))); + for ni=1:size(nearestedges,1) + varargout{1}(nearestedges(ni,2)) = varargout{1}(nearestedges(ni,2)) + ... + cdata(nearestedges(ni,1))' .* nearestedges(ni,3)'; + end + else + varargout{1} = zeros(1,max(nearestedges(:,2))); + if 0 + list = [1; find(nearestedges(1:end-1,2)~=nearestedges(2:end,2))+1; size(nearestedges,1)+1]; + for ni=1:numel(list)-1 + varargout{1}(nearestedges(list(ni),2)) = varargout{1}(nearestedges(list(ni),2)) + ... + sum(cdata(nearestedges(list(ni):list(ni+1)-1,1)) .* nearestedges(list(ni):list(ni+1)-1,3)); + end + else + nearestedges2 = sortrows([nearestedges(:,2) nearestedges(:,1) nearestedges(:,3)]); + list = [1; find(nearestedges2(1:end-1,1)~=nearestedges2(2:end,1))+1; size(nearestedges2,1)+1]; + for ni=1:numel(list)-1 + varargout{1}(nearestedges2(list(ni),1)) = varargout{1}(nearestedges2(list(ni),1)) + ... + sum(cdata(nearestedges2(list(ni):list(ni+1)-1,2)) .* nearestedges2(list(ni):list(ni+1)-1,3)); + end + end + end + if numel(varargout{1})<20, disp(varargout{1}); end + if opt.verb, cat_io_cmd(' ','g5','',1,stime); end + end + + % default smoothing??? + if opt.smooth + varargout{1} = spm_mesh_smooth(struct('vertices',S3.vertices,'faces',S3.faces),double(varargout{1}'),opt.smooth); + end + + if isfield(opt,'fname') + save(gifti(struct('vertices',S1.vertices,'faces',S1.faces,'cdata',varargout{1})),opt.fname); + end + + if opt.verb, cat_io_cmd('','','',1,stime1); end +end + +function [E,uE] = cat_surf_edges(T) +% Extract edges of a given surface struture or its faces +% +% [E,uE] = cat_surf_edges(T) +% +% T .. surface structure or faces +% E .. edges +% + + if isstruct(T) && isfield(T,'faces') + T = T.faces; + end + + T = sort(T,2); E = []; + for i=1:size(T,2)-1 + E = [E; T(:,[i i+1])]; + end + [E,uE] = unique(E,'rows'); +end + +function D = cat_surf_dist(S) +% Estimate the distance between the vertices of the faces of S. +% +% D = cat_surf_dist(S) +% +% D = [c,a,b] = [d(AB),d(BC),d(CA)] +% + + D = [sum( (S.vertices(S.faces(:,1),:) - S.vertices(S.faces(:,2),:)).^2 , 2) .^ 0.5, ... + sum( (S.vertices(S.faces(:,2),:) - S.vertices(S.faces(:,3),:)).^2 , 2) .^ 0.5, ... + sum( (S.vertices(S.faces(:,3),:) - S.vertices(S.faces(:,1),:)).^2 , 2) .^ 0.5]; + +end + +function [AV,AF] = cat_surf_area(S) +% Calculate surface area of the faces AF (Horonsche Form) and map it to the +% vertices AV. +% +% [AV,AF] = cat_surf_area(S) +% +% AV .. area per vertex (1/3 of all connected faces) +% AF .. area per face +% S .. surface structure with vertices and faces +% + + % facearea (Horonsche Form) + method = 2; + if method == 1 + %% + D = cat_surf_dist(S); + facesp = sum(D,2) / 2; % s = (a + b + c) / 2; + AF = (facesp .* (facesp - D(:,1)) .* (facesp - D(:,2)) .* (facesp - D(:,3))).^0.5; % area=sqrt(s*(s-a)*(s-b)*(s-c)); + + % numerical (to small point differences) and mapping problems (crossing of streamlines) + % -> correction because this is theoretical not possible (Laplace field theory) + AF(AF==0) = eps; % to small values + AF = abs(AF); % streamline-crossing + + AV = cat_surf_F2V(S,AF); + elseif method == 2 + %% + AF = spm_mesh_area(S,true); + AV = cat_surf_F2V(S,AF); + else + %% edge points + vn = size(S.vertices,1); + V1 = S.vertices(S.faces(:,1),:); + V2 = S.vertices(S.faces(:,2),:); + V3 = S.vertices(S.faces(:,3),:); + V12 = mean( cat( 3 , V1 , V2 ) , 3); + V13 = mean( cat( 3 , V1 , V3 ) , 3); + V23 = mean( cat( 3 , V2 , V3 ) , 3); + %V123 = circumcenter( struct( 'Points' , [ V1 ; V2 ; V3 ] , 'ConnectivityList' , [ (1:vn)' (1:vn)'+vn (1:vn)'+vn*2 ] )); % center of mass + V123 = circlefit3d( V1 , V2 , V3 ); + +%% + SR11.faces = S.faces; SR11.vertices = [V1 V12 V123]; + SR12.faces = S.faces; SR12.vertices = [V1 V13 V123]; + SR21.faces = S.faces; SR21.vertices = [V2 V12 V123]; + SR22.faces = S.faces; SR22.vertices = [V2 V23 V123]; + SR31.faces = S.faces; SR31.vertices = [V3 V13 V123]; + SR32.faces = S.faces; SR32.vertices = [V3 V23 V123]; + + %% outer circle point + AF3 = [ abs(spm_mesh_area(SR11,true))' + abs(spm_mesh_area(SR12,true))' , ... + abs(spm_mesh_area(SR21,true))' + abs(spm_mesh_area(SR22,true))' , ... + abs(spm_mesh_area(SR31,true))' + abs(spm_mesh_area(SR32,true))']; + + AF = sum( AF3( S.faces ) , 2); + AV = cat_surf_F2V(S,AF); + + % the COM is equal to divide by three and the estimation of the + % circumcircle point was not so easy or fast possible as I hoped ... + % https://en.wikipedia.org/wiki/Triangle#Computing_the_area_of_a_triangle + % https://en.wikipedia.org/wiki/Circumscribed_circle + end + %% +% AV = spm_mesh_smooth(S,AV,5); + +end + +function data = cat_surf_F2V(S,odata) +%% mapping of facedata to vertices + + %A = spm_mesh_distmtx(S,0); + %A = full(sum(A,2)); + %FA = A(S.faces); + %FA = (1./FA.^16); + %FA = FA ./ repmat(sum(FA,2),1,3); + + data = zeros(size(S.vertices,1),1); + [v,f] = sort(S.faces(:)); + [f,fj] = ind2sub(size(S.faces),f); + far = odata(f); +% FA = FA(f,:); + for i=1:numel(v) + data(v(i)) = data(v(i)) + far(i) / 3;% .* FA(i); % + end + + % data = data ./ vcount; %size(S.vertices,2); % Schwerpunkt... besser Voronoi, aber wie bei ner Oberflaeche im Raum??? + +end + +function A = cat_surf_smoothtexture(S,A,smooth,Amax) +% create smooth area texture files +% --------------------------------------------------------------------- + debug = 0; + + if ~exist('smooth','var'), smooth=1; end + + % temporary file names + Pname = tempname; + Pmesh = [Pname 'mesh']; + Parea = [Pname 'area']; + + if exist('Amax','var'); A = min(A,Amax); end + + % write surface and textures + cat_io_FreeSurfer('write_surf',Pmesh,S); + cat_io_FreeSurfer('write_surf_data',Parea,A); + + % smooth textures + cmd = sprintf('CAT_BlurSurfHK ""%s"" ""%s"" ""%g"" ""%s""',Pmesh,Parea,smooth,Parea); + cat_system(cmd,debug); + + % load smoothed textures + A = cat_io_FreeSurfer('read_surf_data',Parea); + + % delete temporary file + delete(Parea); +end + +function [SH,V] = cat_surf_hull(S) +% Create the hull surface SH and volume V of a given surface structure S. +% +% [SH,V] = cat_surf_hull(S) +% +% SH .. hull surface (different from S!) +% V .. volume of S +% S .. input surface +% + + % render surface points + Vi = cat_surf_fun('surf2vol',S); + + % fill mesh + V = cat_vol_morph(Vi,'ldc',mean(size(Vi))/6); clear Vi; % closing + V = cat_vol_smooth3X(V,2); % smoothing + SH = isosurface(V,0.4); % create hull + V = V>0.4; + + % final mesh operations + SH.vertices = [SH.vertices(:,2) SH.vertices(:,1) SH.vertices(:,3)]; % matlab flip + SH.vertices = SH.vertices + repmat(min(S.vertices),size(SH.vertices,1),1) - 5; +end + +function PTN = cat_surf_thickness(action,PS,PT) +% Estimation of different cortical thickness metrics. +% + + if ~exist('T','var') + % create inner and outer surfaces + PIS = cat_surf_fun('inner',PS); % estimate inner surface + POS = cat_surf_fun('outer',PS); % estimate outer surface + else + % create inner and outer surfaces + PIS = cat_surf_fun('inner',PS,PT); % estimate inner surface + POS = cat_surf_fun('outer',PS,PT); % estimate outer surface + end + + % load surfaces + IS = gifti(PIS); + OS = gifti(POS); + + % edgemap + % create mapping between + Pedgemap = cat_io_strrep(PS,{'.central.';'.gii'},{'.edgemapnative.';'.mat'}); + if 0%exist(Pedgemap,'file') % ... you have to test if central is older than the edgemap to use this + load(Pedgemap,'edgemap'); + else + %% + stime2 = clock; + fprintf(' Estimate mapping for native surface'); + edgemap = cat_surf_surf2surf(IS,OS,0); + %edgemap.dist = sum ( (IS.vertices(edgemap.edges(:,1),:) - OS.vertices(edgemap.edges(:,2),:)).^2 , 2).^0.5; + %save(Pedgemap,'edgemap'); + fprintf(' takes %ds\n',round(etime(clock,stime2))); + end + + % create thickness metric mapping matrix + switch lower(action) + case {'tfs','tmin'} + Tnear = inf(edgemap.nvertices(1),2,'single'); + for i=1:size(edgemap.edges,1) + Tnear(edgemap.edges(i,1),1) = min( [ Tnear(edgemap.edges(i,1),1) edgemap.dist(i) ] ) ; + Tnear(edgemap.edges(i,2),2) = min( [ Tnear(edgemap.edges(i,2),2) edgemap.dist(i) ] ) ; + end + case 'tmax' + Tfar = zeros(edgemap.nvertices(1),2,'single'); + for i=1:size(edgemap.edges,1) + Tfar(edgemap.edges(i,1),1) = max( [ Tfar(edgemap.edges(i,1),1) edgemap.dist(i) ] ) ; + Tfar(edgemap.edges(i,2),2) = max( [ Tfar(edgemap.edges(i,2),2) edgemap.dist(i) ] ) ; + end + end + + switch lower(action) + case 'tfs' + TN = mean(Tnear,2); + PTN = cat_io_strrep(PS,{'.central.';'.gii'},{'.thicknessfs.';''}); + case 'tmin' + TN = min(Tnear,[],2); + PTN = cat_io_strrep(PS,{'.central.';'.gii'},{'.thicknessmin.';''}); + case 'tmax' + TN = max(Tfar,[],2); + PTN = cat_io_strrep(PS,{'.central.';'.gii'},{'.thicknessmax.';''}); + end + + % save smoothed textures + cat_io_FreeSurfer('write_surf_data',PTN,TN); +end + +function [SH,V] = cat_surf_core(S,opt) +% _________________________________________________________________________ +% Estimation of a core surface of central WM regions without gyri that is +% the inverse of the hull surface in principle. +% +% [SH,V] = cat_surf_core(S,opt) +% +% SH .. core surface +% V .. volume map of the core surface +% S .. input surface +% opt .. parameter structure +% .type .. type of core creation +% .th .. threshold for core creation +% +% This function is in development! +% +% This is much more complicated that the hull definition. So I will need +% different types of core definitions. However, I first have to find one +% (or multiple) anatomical definitions. +% +% For estimation I can use different techniques: +% * morphological operations +% > very inaccurate and error-prone +% > use of distance & smoothing functions +% * smoothing with/without boundaries +% * anatomical information from volume or better surface atlas maps +% * use of other measures such as +% - thickness (no) +% - sulcal depth or outward folding GI (maybe) +% - curvature (not really) +% +% * use of percentage scalings +% * use of multiple threshold levels and averaging to avoid using only +% one threshold (=multiband) +% * definition as fractal dimension measure? +% _________________________________________________________________________ + + def.type = 1; + def.th = 0.15; + opt = cat_io_checkinopt(opt,def); + + + % render surface points + Vi = cat_surf_fun('surf2vol',S); + + %% break gyri + if opt.type == 1 + %% + Vd = cat_vbdist(single(Vi<0.5)); + + %% + Vdn = Vd ./ max(Vd(:)); + Vdn = cat_vol_laplace3R(Vdn,Vdn>0 & Vdn<0.8 ,0.001); + Vdn = min(opt.th + cat_vol_morph(Vdn>opt.th,'l'),Vdn); + V = Vdn > opt.th; + + %% + SH = isosurface(Vdn,opt.th); % create hull + elseif opt.type == 2 + SiGI = S; SiGI.cdata = opt.iGI; + V = cat_surf_fun('surf2vol',SiGI,struct('pve',3)); + V = V ./ max(V(:)); + SH = isosurface(V,opt.th); % create hull + else + Vs = cat_vol_smooth3X(Vi,8); % smoothing + V = ~cat_vol_morph(Vs<0.5,'ldc',min(size(Vi))/(6*1.5)); % opening + V = cat_vol_smooth3X(V,6); % smoothing + SH = isosurface(V .* smooth3(Vi),0.6); % create hull + V = min(V>0.6,Vi==1); + V = cat_vol_smooth3X(V,4); % smoothing + V = min(V,Vi); + V = cat_vol_laplace3R(V,Vi>0 & V<0.9,0.4); + end %clear Vi; + + % final mesh operations + SH.vertices = [SH.vertices(:,2) SH.vertices(:,1) SH.vertices(:,3)]; % matlab flip + SH.vertices = SH.vertices + repmat(min(S.vertices),size(SH.vertices,1),1) - 5; +end + +function res = cat_surf_evalCS(CS,Tpbt,Tfs,Ym,Ypp,Pcentral,mat,verb,estSI) +% _________________________________________________________________________ +% cat_surf_evalCS in cat_surf_fun print out some values to characterize a +% cortical surface. +% +% res = cat_surf_fun('evalCS',CS[,Tpbt,Tfs,Ym,Yppt]) +% res = cat_surf_evalCS(CS[,Tpbt,Tfs,Ym,Yppt]) +% +% CS .. central surface in world space (mm) +% Tpbt .. cortical thickness (PBT) in world space (mm) +% can be empty (if so than Tfs will be used for generation +% of the white/pial surface +% Tfs .. cortical thickness (FreeSurfer) in world space (mm) +% can be empty +% Ym .. intensity normalized file with BG=0, CSF=1/3, GM=2/3, and WM=1 +% Ypp .. percent position map +% Pcentral .. number of classes for further thickness evaluation or a +% given filename to detect specific thickness phantom rules +% verb .. print results (default = 1) +% estSI .. estimate self intersections (SI) .. slow! (default = 0) +% +% res .. structure with data fields of the printed values +% _________________________________________________________________________ +% Robert Dahnke 201909 + +% - maybe also save and link (surface + hist) some files in future +% - the Layer4 handling with the global variables is horrible + + QMC = cat_io_colormaps('marks+',17); + color = @(m) QMC(max(1,min(size(QMC,1),round(((m-1)*3)+1))),:); + rms = @(x) mean( x.^2 ).^0.5; + rate = @(x,best,worst) min(6,max(1, max(0,x-best) ./ (worst-best) * 5 + 1)); + + if ~exist('verb','var'), verb = 1; end + if ~exist('estSI','var'), estSI = 0; end + + if isempty(Tpbt) + isemptyTpbt = 1; + Tpbt = Tfs; + else + isemptyTpbt = 0; + end + + M = spm_mesh_smooth(CS); % smoothing matrix + if exist('Tpbt','var') % thickness in voxel space + try + N = spm_mesh_normals(CS); + + VI = CS.vertices + N .* repmat(Tpbt / 2 ,1,3); % white surface + VO = CS.vertices - N .* repmat(Tpbt / 2 ,1,3); % pial surface + end + end + + if exist('Pcentral','var') && ischar(Pcentral) + Player4 = strrep(Pcentral,'.central.','.layer4.'); + Pcentralx = strrep(Pcentral,'.central.','.centralx.'); + Player4x = strrep(Pcentral,'.central.','.layer4x.'); + Ppbtx = strrep(Pcentral(1:end-4),'.central.','.pbtx.'); + + if ~isempty(mat); + save(gifti(struct('faces',CS.faces,'vertices',CS.vertices)),Pcentralx,'Base64Binary'); + cat_io_FreeSurfer('write_surf_data',Ppbtx,Tpbt); + cmd = sprintf('CAT_Central2Pial -equivolume -weight 1 ""%s"" ""%s"" ""%s"" 0', ... + Pcentralx,Ppbtx,Player4x); + try + cat_system(cmd,0); + L4 = gifti(Player4x); + uL4 = 1; + delete(Player4x); + catch + uL4 = 1; + end + if exist(Pcentralx,'file'), delete(Pcentralx); end + if exist(Ppbtx,'file'), delete(Ppbtx); end + else + uL4 = 0; + end + else + uL4 = 0; + end + + + + + %% Evaluation of local intensities + % Here we have to use the Layer 4 rather than the central surface. + % All values will depend on age! + if exist('Ym','var') && exist('VI','var') && exist('VO','var') + warning off MATLAB:subscripting:noSubscriptsSpecified + II = cat_surf_isocolors2(Ym,VI,mat); + IO = cat_surf_isocolors2(Ym,VO,mat); + % local adaptation for GM intensity changes by myelination + IIs = single(spm_mesh_smooth(M,double(II),round(100 * sqrt(size(CS.faces,1)/180000)))); + IOs = single(spm_mesh_smooth(M,double(II),round(100 * sqrt(size(CS.faces,1)/180000)))); + % normalization + II = II./(IIs/mean(IIs)) - 2.5; clear IIs; + IO = IO./(IOs/mean(IOs)) - 1.5; clear IOs; + % + + if uL4 && exist('L4','var') + ML = spm_mesh_smooth(L4); % smoothing matrix + IC = cat_surf_isocolors2(Ym,L4,mat); + ICs = single(spm_mesh_smooth(ML,double(IC),round(100 * sqrt(size(CS.faces,1)/180000)))); + IC = IC./(ICs/mean(ICs)) - mean(ICs); clear ICs; + end + % divide by 2 because of the CSF-GM (1-2) and the GM-WM area (2-3) + % and to obtain a similar scaling as for the Ypp (also two segments and + % we do not dived) + II = II / 2; IO = IO / 2; if uL4 && exist('L4','var'), IC = IC / 2; end + % output + if verb + fprintf(' Local intensity RMSE (lower=better): ') + if uL4 && exist('L4','var') + cat_io_cprintf( color( rate( mean( [rms(II),rms(IC),rms(IO)] ) , 0.05 , 0.50 )) , sprintf('%0.4f ',mean( [rms(II),rms(IC),rms(IO)] )) ); + else + cat_io_cprintf( color( rate( mean( [rms(II),rms(IO)] ) , 0.05 , 0.50 )) , sprintf('%0.4f ',mean( [rms(II),rms(IO)] )) ); + end + cat_io_cprintf( color( rate( rms(II) , 0.05 , 0.50 )) , sprintf('(IS=%0.4f,',rms(II)) ); + if uL4 && exist('L4','var'), cat_io_cprintf( color( rate( rms(IC) , 0.05 , 0.50 )) , sprintf('L4=%0.4f,',rms(IC)) ); end + cat_io_cprintf( color( rate( rms(IO) , 0.05 , 0.50 )) , sprintf('OS=%0.4f)\n',rms(IO)) ); + end + res.RMSE_Ym_white = rms(II); + if uL4 && exist('L4','var'), res.RMSE_Ym_layer4 = rms(IC); end + res.RMSE_Ym_pial = rms(IO); + clear II IO; + end + + + + + %% Evaluation of surface position values + % Here we can of course use the central surface + % This will be relative age independent. + if exist('Ypp','var') + II = cat_surf_isocolors2(Ypp,VI,mat); + IC = cat_surf_isocolors2(Ypp,CS,mat); + IO = cat_surf_isocolors2(Ypp,VO,mat); + II = II - 1.0; + IC = IC - 0.5; + IO = IO - 0.0; + % output + if verb + fprintf(' Local position RMSE (lower=better): '); + cat_io_cprintf( color( rate( mean( [rms(IC),rms(II),rms(IO)]) , 0.05 , 0.50 )) ,sprintf('%0.4f ',mean( [rms(IC),rms(II),rms(IO)] )) ); + cat_io_cprintf( color( rate( rms(II) , 0.05 , 0.50 )) , sprintf('(IS=%0.4f,' ,rms(II)) ); + cat_io_cprintf( color( rate( rms(IC) , 0.05 , 0.50 )) , sprintf('CS=%0.4f,' ,rms(IC)) ); + cat_io_cprintf( color( rate( rms(IO) , 0.05 , 0.50 )) , sprintf('OS=%0.4f)\n',rms(IO)) ); + end + res.RMSE_Ypp_white = rms(II); + res.RMSE_Ypp_pial = rms(IO); + res.RMSE_Ypp_central = rms(IC); + end + + + + + %% CAT_SelfIntersect + % This is very slow and we may want to keep the result. + if estSI && exist('Pcentral','var') && ischar(Pcentral) + [pp,ff,ee] = spm_fileparts(Pcentral); + + Pwhite = fullfile(pp,strrep([ff ee],'central','whitex')); + Ppial = fullfile(pp,strrep([ff ee],'central','pialx')); + Pselfw = fullfile(pp,strrep(ff,'central','whiteselfintersect')); + Pselfp = fullfile(pp,strrep(ff,'central','pialselfintersect')); + ePwhite = exist(Pwhite,'file'); + ePpial = exist(Ppial, 'file'); + %ePselfw = exist(Pselfw,'file'); + %ePselfp = exist(Pselfp,'file'); + + % save surfaces + save(gifti(struct('faces',CS.faces,'vertices',VI)),Pwhite,'Base64Binary'); + save(gifti(struct('faces',CS.faces,'vertices',VO)),Ppial,'Base64Binary'); + + %cmd = sprintf('CAT_SurfDistance -mean ""%s"" ""%s"" ""%s""',Pwhite,Ppial,Pthick); + %cat_system(cmd); + + % write self intersection maps + cmd = sprintf('CAT_SelfIntersect ""%s"" ""%s""',Pwhite,Pselfw); + cat_system(cmd,0); + cmd = sprintf('CAT_SelfIntersect ""%s"" ""%s""',Ppial,Pselfp); + cat_system(cmd,0); + + selfw = cat_io_FreeSurfer('read_surf_data',Pselfw); + selfp = cat_io_FreeSurfer('read_surf_data',Pselfp); + + area = cat_surf_area(CS); + + res.white_self_interection_area = sum((selfw(:)>0) .* area(:)) / 100; + res.pial_self_interection_area = sum((selfp(:)>0) .* area(:)) / 100; + res.white_self_interections = res.white_self_interection_area / sum(area(:)/100) * 100; + res.pial_self_interections = res.pial_self_interection_area / sum(area(:)/100) * 100; + + if verb + fprintf(' Self intersections (white,pial): '); + cat_io_cprintf( color( rate( res.white_self_interections , 0 , 20 )) , ... + sprintf('%0.2f%%%% (%0.2f cm%s) ',res.white_self_interections,res.white_self_interection_area,char(178))); + cat_io_cprintf( color( rate( res.pial_self_interections , 0 , 20 )) , ... + sprintf('%0.2f%%%% (%0.2f cm%s)\n',res.pial_self_interections,res.pial_self_interection_area,char(178))); + end + + % delete temparary files + if ~ePwhite, delete(Pwhite); end + if ~ePpial, delete(Ppial); end + %if ~ePselfw, delete(Pselfw); end + %if ~ePselfp, delete(Pselfp); end + end + + + + + %% thickness analysis + if exist('Tpbt','var') || exist('Tfs','var') + if 0 %exist('Tclasses','var') && ~isempty(Pcentral) + if ischar(Pcentral) + if strfind(Pcentral,'dilated1.5-2.5mm') + Tpbt = cat_stat_histth(Tpbt,0.95); + Pcentral = 3; + else + Pcentral = 0; + end + end + + if Pcentral>0 + if Pcentral>7 || Pcentral<1 + warning('Tclasses has to be between 2 and 7.'); + Pcentral = min(7,max(3,Pcentral)); + end + [mn,sd] = cat_stat_kmeans(Tpbt,Pcentral); + if verb + fprintf(' Thickness mean (%d class(es)): ',Pcentral) + fprintf('%7.4f',mn); fprintf('\n'); + fprintf(' Thickness std (%d class(es)): ',Pcentral) + fprintf('%7.4f',sd); fprintf('\n'); + end + res.thickness_mean_nclasses = mn; + res.thickness_std_nclasses = sd; + end + end + + % fully named thickness variable + if ~isemptyTpbt + res.pbtthickness_mn_sd_md_mx = [mean(Tpbt),std(Tpbt),median(Tpbt),max(Tpbt)]; + else + res.pbtthickness_mn_sd_md_mx = nan(1,4); + end + if ~isempty(Tfs) + res.fsthickness_mn_sd_md_mx = [mean(Tfs),std(Tfs),median(Tfs),max(Tfs)]; + else + res.fsthickness_mn_sd_md_mx = nan(1,4); + end + % general thickness value + if isempty(Tfs) && ~isemptyTpbt + res.thickness_mn_sd_md_mx = res.pbtthickness_mn_sd_md_mx; + elseif ~isempty(Tfs) && isemptyTpbt + res.thickness_mn_sd_md_mx = res.fsthickness_mn_sd_md_mx; + else + res.thickness_mn_sd_md_mx = nan(1,4); + end + + if verb + fprintf(' Surface PBT thickness values: %0.4f%s%0.4f (md=%0.4f,mx=%0.4f)\n',... + res.pbtthickness_mn_sd_md_mx(1),native2unicode(177, 'latin1'),res.pbtthickness_mn_sd_md_mx(2:end)); + if ~isnan(res.fsthickness_mn_sd_md_mx(1)) + fprintf(' Surface FS thickness values: %0.4f%s%0.4f (md=%0.4f,mx=%0.4f)\n',... + res.fsthickness_mn_sd_md_mx(1),native2unicode(177, 'latin1'),res.fsthickness_mn_sd_md_mx(2:end)); + end + end + end + + + + + % curvature analyis - not realy relevant + if 0 + C = abs(spm_mesh_curvature(CS)); + res.abscurv_mn_sd_md_mx = [mean(C),std(C),median(C),max(C)]; + if verb + fprintf(' Abs mean curvature values: %0.4f%s%0.4f (md=%0.4f,mx=%0.4f)\n',... + res.abscurv_mn_sd_md_mx(1),native2unicode(177, 'latin1'),res.abscurv_mn_sd_md_mx(2:end)); + end + end + + + + + % surface values + warning off MATLAB:subscripting:noSubscriptsSpecified + EC = size(CS.vertices,1) + size(CS.faces,1) - size(spm_mesh_edges(CS),1); + res.euler_characteristic = EC; + if verb + fprintf(' Faces / Euler: '); + cat_io_cprintf( color( rate( 1 - max(0,size(CS.faces,1)/300000) , 0 , 0.9 )) , sprintf('%d / ',size(CS.faces,1))); + cat_io_cprintf( color( rate( abs(EC-2) , 0 , 30 )) , sprintf('%d',EC)); + fprintf('\n'); + end +end + +function cat_surf_saveICO(S,Tpbt,Pcs,subdir,Pm,mat,writeTfs,writeSI,writeL4,writeInt) +% _________________________________________________________________________ +% Save surface data for debugging: +% Creates and saves the white and pial surfaces based on the displacement by +% the half thickness along the surface normals and use the inner and outer +% surfaces to create the layer4 surface. +% Saves also the thickness file (PBT by default). +% +% Writing of FreeSurfer thickness takes about 10s. +% Writing of self-intersection maps takes about 90s. +% Writing of the Layer4 also take about 8s. +% Writing of the Layer4 also take about 6s if Ym is given else 90s. +% +% cat_surf_saveICO(S,Tpbt,Pcs,subdir,Pm,writeTfs,writeSI,writeL4,writeInt) +% +% S .. central surface in voxel space +% T .. cortical thickness (in mm) +% Pcs .. central surface file name (with full path) +% subdir .. addition subdirectory in the standard surface directory +% Pm .. intensity information +% writeTfs .. estimate FreeSurfer thickness metric +% Pm .. intensity file/volume to map data to the surfaces +% writeTfs .. write default thickness metric rather than given PBT +% writeSI .. write self-intersection maps +% writeL4 .. create L4 surface (and project data on it) +% writeInt .. write some intensity maps +% _________________________________________________________________________ +% Robert Dahnke 201908 + + opt.verb = 0; + + [pp,ff,ee] = spm_fileparts(Pcs); + if ~exist('Pm','var'), Pm = ''; end + if ~exist('writeTfs','var'), writeTfs = 0; end + if ~exist('writeInt','var'), writeInt = 0; end + if ~exist('writeSI','var'), writeSI = 0; end + if ~exist('writeL4','var'), writeL4 = 1; end + if ~exist('subdir','var') + subdir = ''; + else + if ~exist(fullfile(pp,subdir),'dir') + mkdir(fullfile(pp,subdir)); + end + end + + %if isfield(S,'vmat') && isfield(S,'mati') + % S.vertices = (S.vmat * [S.vertices' ; ones(1,size(S.vertices,1))])'; + % if S.mati(7)<0, S.faces = [S.faces(:,1) S.faces(:,3) S.faces(:,2)]; end + %end + + flipped = cat_surf_fun('checkNormalDir',S); + if flipped, S.faces = [S.faces(:,1) S.faces(:,3) S.faces(:,2)]; end + + % normalized surface normals + N = spm_mesh_normals(S); + % matx = spm_imatrix( [S.vmat; 0 0 0 1] ); matx([1:3,9:12]) = 0; matx(6:9) = 1; % only rotate + % vmat = spm_matrix( matx ); vmat(4,:) = []; + % N = -(vmat * [N' ; ones(1,size(N,1))])'; + + % inner and outer surface + VI = S.vertices + N .* repmat(Tpbt / 2,1,3); + VO = S.vertices - N .* repmat(Tpbt / 2,1,3); + + % surface filenames + Pcentral = fullfile(pp,subdir,[ff ee]); + Pwhite = fullfile(pp,subdir,strrep([ff ee],'central','white')); + Ppial = fullfile(pp,subdir,strrep([ff ee],'central','pial')); + Pthick = fullfile(pp,subdir,strrep(ff,'central','thickness')); + Ppbt = fullfile(pp,subdir,strrep(ff,'central','pbt')); + PintIS = fullfile(pp,subdir,strrep(ff,'central','intwhite')); + PintOS = fullfile(pp,subdir,strrep(ff,'central','intpial')); + PintL4 = fullfile(pp,subdir,strrep(ff,'central','intlayer4')); + Player4 = fullfile(pp,subdir,strrep([ff ee],'central','layer4')); + Pselfw = fullfile(pp,subdir,strrep(ff,'central','whiteselfintersect')); + Pselfp = fullfile(pp,subdir,strrep(ff,'central','pialselfintersect')); + + % save surfaces + save(gifti(struct('faces',S.faces,'vertices',S.vertices)),Pcentral,'Base64Binary'); + save(gifti(struct('faces',S.faces,'vertices',VI)),Pwhite,'Base64Binary'); + save(gifti(struct('faces',S.faces,'vertices',VO)),Ppial,'Base64Binary'); + + % write self intersection maps + if writeSI + cmd = sprintf('CAT_SelfIntersect ""%s"" ""%s""',Pwhite,Pselfw); + cat_system(cmd,0); + cmd = sprintf('CAT_SelfIntersect ""%s"" ""%s""',Ppial,Pselfp); + cat_system(cmd,0); + end + + % save thickness + cat_io_FreeSurfer('write_surf_data',Ppbt,Tpbt); + if exist('writeTfs','var') && ~isempty(writeTfs) && writeTfs + cmd = sprintf('CAT_SurfDistance -mean ""%s"" ""%s"" ""%s""',Pwhite,Ppial,Pthick); + cat_system(cmd,opt.verb-2); + fprintf('Display thickness: %s\n',spm_file(Pthick ,'link','cat_surf_display(''%s'')')); + end + + % final correction of central surface in highly folded areas with high mean curvature + if writeL4 + cmd = sprintf('CAT_Central2Pial -equivolume -weight 1 ""%s"" ""%s"" ""%s"" 0', ... + Pcentral,Ppbt,Player4); + cat_system(cmd,0); + end + + % save intensities + if isempty(Pm) && writeInt + % volume filenames for spm_orthview + sinfo = cat_surf_info(Pcentral); + + [mrifolder, reportfolder, surffolder, labelfolder] = cat_io_subfolders(sinfo.name); + if cat_get_defaults('extopts.subfolders') + Pm = fullfile(spm_str_manip(pp,'h'),mrifolder,['m' sinfo.name '.nii']); + else + Pm = fullfile(pp,['m' sinfo.name '.nii']); + end + if ~exist(Pm,'file') + Pm = fullfile(spm_str_manip(pp,'hh'),mrifolder,['m' sinfo.name '.nii']); + end + if ~exist(Pm,'file') + Pm = fullfile(spm_str_manip(pp,'h'),[sinfo.name '.nii']); + end + if ~exist(Pm,'file') + Pm = ''; + end + end + + if ~isnumeric( Pm ) && exist(Pm,'file') + % use the file data ... slow???? + cmd = sprintf('CAT_3dVol2Surf -steps 1 -start 0 -end 1 ""%s"" ""%s"" ""%s""',Pwhite , Pm, PintIS); + cat_system(cmd,0); + cmd = sprintf('CAT_3dVol2Surf -steps 1 -start 0 -end 0 ""%s"" ""%s"" ""%s""',Ppial , Pm, PintOS); + cat_system(cmd,0); + if writeL4 + cmd = sprintf('CAT_3dVol2Surf -steps 1 -start 0 -end 0 ""%s"" ""%s"" ""%s""',Player4, Pm, PintL4); + cat_system(cmd,0); + end + elseif ndims(Pm)==3 + int = cat_surf_isocolors2(Pm,VO,mat); cat_io_FreeSurfer('write_surf_data',PintOS,int); + int = cat_surf_isocolors2(Pm,VI,mat); cat_io_FreeSurfer('write_surf_data',PintIS,int); + if writeL4 + % use a given volume + SL = gifti(Player4); + warning off MATLAB:subscripting:noSubscriptsSpecified + int = cat_surf_isocolors2(Pm,SL,mat); cat_io_FreeSurfer('write_surf_data',PintL4,int); + end + + % define filename (same block as above) + + % volume filenames for spm_orthview + sinfo = cat_surf_info(Pcentral); + + [mrifolder, reportfolder, surffolder, labelfolder] = cat_io_subfolders(sinfo.name); + if cat_get_defaults('extopts.subfolders') + Pm = fullfile(spm_str_manip(pp,'h'),mrifolder,['m' sinfo.name '.nii']); + else + Pm = fullfile(pp,['m' sinfo.name '.nii']); + end + if ~exist(Pm,'file') + Pm = fullfile(spm_str_manip(pp,'hh'),mrifolder,['m' sinfo.name '.nii']); + end + if ~exist(Pm,'file') + Pm = fullfile(spm_str_manip(pp,'h'),[sinfo.name '.nii']); + end + if ~exist(Pm,'file') + Pm = ''; + end + + end + + % display something to click + fprintf('\n Display surface: %s\n',spm_file(Ppbt ,'link','cat_surf_display(''%s'')')); + if ~isempty(Pm) + fprintf(' Show in orthview: %s\n',spm_file(Pm ,'link',... + [ sprintf('cat_surf_fun(''show_orthview'',{''%s'';''%s'';''%s''},',Pcentral,Ppial,Pwhite) '''%s'')'])); + end + +end + +function Sg = cat_surf_volgrad(varargin) +% _________________________________________________________________________ +% This function estimates the local gradient in an image along the surface +% normals. +% +% Sg = cat_surf_volgrad(S[,N],Y,mat[,d]) +% +% S .. surface in voxel-space +% N .. surface normals in voxel-space +% Y .. voxel in voxel-space +% mat .. structure with resolution information +% d .. distance along the surface-normal (default = 0.05) +% _________________________________________________________________________ +% Robert Dahnke 201910 + + d = 0.05; + if isstruct(varargin{1}) + S = varargin{1}; + Y = varargin{2}; + mat = varargin{3}; + if nargin==4 + d = varargin{4}; + end + + N = spm_normals(S); + V = S.vertices; + else + V = varargin{1}; + N = varargin{2}; + Y = varargin{3}; + mat = varargin{4}; + + if nargin==5 + d = varargin{5}; + end + end + + V1 = V - N*d; + V2 = V + N*d; + + if exist('mat','var') + Si1 = cat_surf_isocolors2(Y,V1,mat); + Si2 = cat_surf_isocolors2(Y,V2,mat); + vx_vol = sqrt(sum(mat(1:3,1:3).^2)); + else + Si1 = cat_surf_isocolors2(Y,V1); + Si2 = cat_surf_isocolors2(Y,V2); + vx_vol = [1 1 1]; + end + + Sg = (Si1 - Si2) ./ repmat( mean(vx_vol), size(Si1,1), 1 ) * 2; +end + +function [S,Tn,SI] = cat_surf_collision_correction_ry(S,T,Y,opt) +% _________________________________________________________________________ +% Correction of self-intersection (S) by iterative use of the +% CAT_selfintersect function of Rachel Yotter / Christian Gaser. +% For typical 164k surfaces 60 to 90s are required per iteration and at +% least 5 iterations are required for reasonable quality (accuracy 1/2^4 +% with aobut 0.25% SIs). +% +% [S,Tn] = cat_surf_collision_correction_ry(S,T,Y,opt) +% +% S .. central surface in voxel space +% T .. thickness in world space +% Y .. intensity normalized image (to estimate face normal orientation) +% opt .. structure with further options +% .verb .. print progress +% .redterm .. size of the reduction interval (default 2 = half interval) +% .accurarcy .. stop criteria (default 1/2^4 for about 5 iterations) +% .iterfull .. maximum number of iterations that is automatically defined +% by the accuracy +% .interBB .. structure with resolution information +% .BB .. not used here +% .interpV .. voxel-space resolution of S +% _________________________________________________________________________ +% Robert Dahnke 201910 + + if ~exist('opt','var'), opt = struct(); end + + % defaults + def.redterm = 2; % reduction term of the iteration, e.g. 2 = half resolution every iteration + def.verb = 1; % print changes + def.debug = 2; % use debugging + def.mod = 1; % 1 - interval-based correction, 0 - linear correction + def.accuracy = 0.0625; % smallest used stepsize (the value should not be to small because there + % should also be a gab between the structures and a reasonable running time) + %def.interpBB = struct('BB',[],'interpV',1); + def.ta = 0.99; + def.mat = []; + opt = cat_io_checkinopt(opt,def); + opt.iterfull = find( 1 ./ opt.redterm.^(1:100) < opt.accuracy , 1); % + 2 maximum number of iterations + + sf = round( sqrt( size(S.faces,1) / 50000) ) / 2 * 0.25; % smoothing iterations depend on mesh size ### empirical value + M = spm_mesh_smooth(S); % for spm_smoothing matrix + + % filenames + [pp,ff,ee] = spm_fileparts(opt.Pcs); + Pwhite = fullfile(pp,strrep([ff ee],'central','white')); + Ppial = fullfile(pp,strrep([ff ee],'central','pial')); + Pselfw = fullfile(pp,strrep(ff,'central','whiteselfintersect')); + Pselfp = fullfile(pp,strrep(ff,'central','pialselfintersect')); + + % inner and outer thickness seen from the central surface + Tvxw = T / 2; % white matter side thickness + Tvxp = T / 2; % pial side thickness + + % detection and correction for flipped faces to have always the same normal direction + flipped = cat_surf_checkNormalDir(S); %,T,Y,opt.interpBB); + if flipped + S.faces = [S.faces(:,1) S.faces(:,3) S.faces(:,2)]; + if isfield(S,'mati'), S.mati(7) = - S.mati(7); end + end + + % addition flip test + N = spm_mesh_normals(S); + VI = S.vertices + N .* repmat(T/2,1,3); + YI = cat_surf_isocolors2(Y,VI,opt.mat); + flipped2 = mean(YI)<.2; + if flipped2 + S.faces = [S.faces(:,1) S.faces(:,3) S.faces(:,2)]; + end + + % simple surface smoothing + smoothsurf = @(V,s) [ ... + spm_mesh_smooth(M,double(V(:,1)),s) , ... + spm_mesh_smooth(M,double(V(:,2)),s) , ... + spm_mesh_smooth(M,double(V(:,3)),s) ]; + + if opt.ta + %% do not correct in regions with extremly high thickness + A = cat_surf_fun('area',S); + TA = T ./ A; + TAs = spm_mesh_smooth(M,double(TA),80 * sf); + TAs = min(1,max(0, TAs - mean(TAs(:) + 2 * std(TAs(:))) ./ 2 * std(TAs(:)))); + TAs = 1 - TAs*opt.ta; + clear A TA; + end + + Tn = T; + N = spm_mesh_normals(S); + i = 0; final = 0; + + if opt.verb, fprintf('\n'); end; SI = 90; SIO=100; + while i < opt.iterfull || (SI>5 && SI0; + selfp = cat_io_FreeSurfer('read_surf_data',Pselfp)>0; + + + if opt.ta > 0 + selfw = selfw .* TAs; + selfp = selfp .* TAs; + end + + % correction scheme that based on the original thickness + % selfo self direction + % 0 0 0 + % 1 0 -1 % not the last iteration! + % 1 1 1 + % 0 1 1 + + % at the beginning with have no old information, at the end we only want to reduce thickness + % here we use the original thickness value - test if new is better! + if opt.mod~=1 || i==1 || final %corrsize <= opt.accuracy || + Twc = (T/2) .* corrsize .* selfw; + Tpc = (T/2) .* corrsize .* selfp; + else + Twc = (T/2) .* corrsize .* ( (selfw | selfwo) - 2 .* ( selfwo & ~selfw ) ); + Tpc = (T/2) .* corrsize .* ( (selfp | selfpo) - 2 .* ( selfpo & ~selfp ) ); + end + + % correction in specified areas that also include a general + % smoothness constrains of the cortical thickness + Twc = single(spm_mesh_smooth(M,double(Twc) , sf)) * sf; Tvxw = max(eps,Tvxw - Twc); + Tws = single(spm_mesh_smooth(M,double(Tvxw) , sf/2)); Tvxw(Twc~=0) = Tws(Twc~=0); clear Tws; + Tpc = single(spm_mesh_smooth(M,double(Tpc) , sf)) * sf; Tvxp = max(eps,Tvxp - Tpc); + Tps = single(spm_mesh_smooth(M,double(Tvxp) , sf/2)); Tvxp(Tpc~=0) = Tps(Tpc~=0); clear Tps; + + % save for next iteration + selfwo = selfw; + selfpo = selfp; + + % update thickness and surface + VOC = S.vertices - N .* repmat(Tvxp,1,3); + VIC = S.vertices + N .* repmat(Tvxw,1,3); + + if 1 + % extra thickenss smoothing + Sa = cat_surf_fun('area',S); + Tsw = repmat( max(0,min(1,max( (Tn-3)/6 , (Tn ./ (Sa * 4) - 3) / 6) )) ,1,3); clear Sa; + VOCS = smoothsurf(VOC,2); VOC = VOC.*(1-Tsw) + Tsw.*VOCS; + VICS = smoothsurf(VIC,2); VIC = VIC.*(1-Tsw) + Tsw.*VICS; + clear VOCS VICS Tsw; + + % adaptive smoothing + Tpc = Tpc./max(Tpc(:)); Tpc = single(spm_mesh_smooth(M,double(Tpc) , 1)); VOCSf = repmat(0.2 .* Tpc(Tpc>0),1,3); + Twc = Twc./max(Twc(:)); Twc = single(spm_mesh_smooth(M,double(Twc) , 1)); VICSf = repmat(0.5 .* Twc(Twc>0),1,3); + VOCS = smoothsurf(VOC,1); VOC(Tpc>0,:) = VOC(Tpc>0,:).*(1-VOCSf) + VOCSf.*VOCS(Tpc>0,:); + VICS = smoothsurf(VIC,1); VIC(Twc>0,:) = VIC(Twc>0,:).*(1-VICSf) + VICSf.*VICS(Twc>0,:); + clear VOCS VICS Tsw; + end + + % update thickness and central surface position + Tn = double( max(0.01,sum( (VIC - VOC).^2 , 2) .^ 0.5 )); + Tvxw = Tn/2; + Tvxp = Tn/2; + S.vertices = mean(cat(3,VIC,VOC),3); + + % update normals (only for smaller corrections otherwise this will introduce further errors!) + if corrsize<0.25 + N = spm_mesh_normals(S); + end + + % cleanup + delete(Pwhite); + delete(Ppial); + delete(Pselfw); + delete(Pselfp); + + % iteration + if corrsize <= opt.accuracy, final = final + 1; end + SIO = SI; + SI = (sum(selfw>0)/2 + sum(selfp>0)/2) / numel(selfw) * 100; + if opt.verb + cat_io_cprintf('g5',sprintf( ... + ' Step %2d (SS=%02.0f%%%%, SI=%5.2f%%%%, T=%4.2f%s%4.2f)\n',... + i,corrsize*100, (sum(selfw>0)/2 + sum(selfp>0)/2) / numel(selfw) * 100,... + mean(Tn),native2unicode(177, 'latin1'),std(Tn))); + %fprintf('/sprintf('%s',repmat('\b',1,73*2))); + end + if (sum(selfw>0)/2 + sum(selfp>0)/2) / numel(selfw) * 100 < opt.accuracy % if changes are below a specified relative level + if final < 4 && (sum(selfw>0)/2 + sum(selfp>0)/2)>0 % do some additional iterations if required + final = final + 1; + else + break + end + end + end + + if opt.verb, fprintf('\n'); end + % final settings: back to world thickness in mm + if flipped2 + S.faces = [S.faces(:,1) S.faces(:,3) S.faces(:,2)]; + end + if flipped + S.faces = [S.faces(:,1) S.faces(:,3) S.faces(:,2)]; + if isfield(S , 'mati' ), S.mati(7) = - S.mati(7); end + end +end + +function flipped = cat_surf_checkNormalDir(S) +% estimate the orientation of the surface by adding the normals and +% testing which directions makes the surface great again :D + N = spm_mesh_normals(S); + %flipped = abs(mean( S.vertices(:) - 2*N(:) ) ) > abs(mean( S.vertices(:) + 2*N(:) ) ); + %flipped = any(mean(N)) ; (mean( S.vertices(:) - 2*N(:) ) ) > abs(mean( S.vertices(:) + 2*N(:) ) ); + flipped = spm_mesh_area( S.vertices + N ) > spm_mesh_area( S.vertices - N ); % normals are here invers! +end + +function V = cat_surf_smooth(M,V,s,mode) + if ~exist('s','var'), s = 1; end + if ~exist('mode','var'), mode = 0; end + + smoothsurf = @(V,s) [ ... % simple surface smoothing + spm_mesh_smooth(M,V(:,1),s) , ... + spm_mesh_smooth(M,V(:,2),s) , ... + spm_mesh_smooth(M,V(:,3),s) ]; + + if isa(V,'single') + singleV = 1; + V = double(V); + else + singleV = 0; + end + + if mode == 0 + V = smoothsurf(V,s); + else + VS = smoothsurf(V,s); + + VD = sum( (VS - V).^2 , 2).^0.5; + + if mode<0 + V(VDmode) = VS(VD>mode); + end + end + + if singleV + single(V); + end +end + +function [S,Tn,SI] = cat_surf_collision_correction_pbt(S,T,Y,Ypp,opt) +% _________________________________________________________________________ +% This function utilize the percentage position map Ypp map of the +% projection-based thickness to detect and correct self-intersections (SI) +% of a central surface S (in voxel-space) and thickness T (in mm). +% +% [S,Tn] = cat_surf_collision_correction_pbt(S,T,Y,Ypp,Yl4,opt) +% +% S .. central surface in voxel space +% T .. thickness in world space (mm) +% #### +% Y .. intensity normalized image (resolution ????) +% #### +% Ypp .. percentage position map in voxel space +% opt .. structure with further options +% .verb .. print progress +% .redterm .. size of the reduction interval (default 2 = half interval) +% .accurarcy .. stop criteria (default 1/2^4 for about 5 iterations) +% .iterfull .. maximum number of iterations that is automatically defined +% by the accuracy +% .optimize .. use position/intensity values for optimization (def = 1) +% .optmod .. optimization mode (0 - Ypp, 1 - Ym, 2 - Ypp & Ym; def = 0) +% .interBB .. structure with resolution information +% .BB .. not used here +% .interpV .. voxel-space resolution of S +% _________________________________________________________________________ +% Robert Dahnke 201910 + + if ~exist('opt','var'), opt = struct(); end + + % defaults + def.redterm = 2; % reduction term of the iteration, e.g. 2 = half resolution every iteration + def.verb = 1; % display information + def.debug = 2; % save results + def.accuracy = 1/2^5; % smallest used step-size (the value should not be to small + % because there should also be a gab between the structures and a reasonalbe running time) + def.optimize = 1; % use percentage position values for optimization + def.mat = []; + def.ta = 1; + def.CS4 = 0; + + opt = cat_io_checkinopt(opt,def); + opt.iteropt = find( 1 ./ opt.redterm.^(1:100) < opt.accuracy , 1); + opt.iterfull = round( opt.iteropt * (1 + opt.optimize) ); + + sf = round( sqrt( size(S.faces,1) / 50000) ); % ### empirical value optimized on Collins and Thicknessphantom + M = spm_mesh_smooth(S); % for spm_smoothing matrix + + % detection and correction for flipped faces to have always the same normal direction + flipped = cat_surf_checkNormalDir(S); + if flipped + S.faces = [S.faces(:,1) S.faces(:,3) S.faces(:,2)]; + if isfield( S , 'mati' ), S.mati(7) = - S.mati(7); end + end + + % simple surface smoothing ... finaly not required anymore + smoothsurf = @(V,s) [ ... + spm_mesh_smooth(M,double(V(:,1)),s) , ... + spm_mesh_smooth(M,double(V(:,2)),s) , ... + spm_mesh_smooth(M,double(V(:,3)),s) ]; + + % inner and outer thickness seen from the central surface + Tw = T / 2; + Tp = T / 2; + + Tn = T; + N = spm_mesh_normals(S); + if 0 % ### empirical value optimized on Collins and Thicknessphantom ... RD20210403: not required + N = smoothsurf(N,sf); + Ns = sum(N.^2,2).^.5; + N = N ./ repmat(Ns,1,3); + clear Ns; + end + + + % second flip test + VI = S.vertices + N .* repmat(Tw,1,3); + YI = cat_surf_isocolors2(Ypp,VI,opt.mat); + flipped2 = mean(YI)<.2; + if flipped2 + S.faces = [S.faces(:,1) S.faces(:,3) S.faces(:,2)]; + N = -N; + end + + + % curvature + C = spm_mesh_curvature(S); + C = spm_mesh_smooth(M,C,1); + C = C .* (T/2.5); + + % do not correct in regions with extremly high thickness ... + % RD20210403: this is still not fully working + if opt.ta>0 + %% + A = cat_surf_fun('area',S); + TA = T ./ A; + TAs = spm_mesh_smooth(M,double(TA),80 * sf); + TAs = min(1,max(0, TAs - mean(TAs(:) + 2 * std(TAs(:))) ./ 2 * std(TAs(:)))); + TAs = 1 - TAs * opt.ta; + clear A TA; + else + TAs = ones(size(T),'single'); + end + + i = 0; final = 0; SIO = 1; SI = 90; SIO2 = 100; + if opt.verb, fprintf('\n'); end + if opt.CS4, SIO2th = 0.98; else, SIO2th = 0.95; end + while (i < round(opt.iterfull/2)*2 ) || (SI>0.1 && SI opt.alphaYpp ); % | (T>2 & angle( VIg , VOg ) > opt.alphaYpp*2 ); + selfw = ( spm_mesh_smooth( M , double( cat_surf_edgeangle( Vg , VIg )) , 1 ) > opt.alphaYpp ); + + % correction scheme that based on the original thickness + % selfo self direction + % 0 0 0 + % 1 0 -1 % not the last iteration! + % 1 1 1 + % 0 1 1 + % + if i==1 || final % at the beginning with have no old information, at the end we only want to reduce thickness + Twc = T/2 .* corrsize .* selfw; + Tpc = T/2 .* corrsize .* selfp; + else + Twc = T/2 .* corrsize .* ( (selfw | selfwo) - 2 .* ( selfwo & ~selfw ) ); + Tpc = T/2 .* corrsize .* ( (selfp | selfpo) - 2 .* ( selfpo & ~selfp ) ); + end + + selfw = selfw .* TAs; + selfp = selfp .* TAs; + + if opt.optimize && i1, fprintf(' YIC:%5.2f%s%0.2f, YOC:%5.2f%s%0.2f',mean(YI),native2unicode(177, 'latin1'),std(YI),mean(YO),native2unicode(177, 'latin1'),std(YO)); end + + % correction value + YI = max(-1, min(1, ( GWth - YI ) * coristr .* (1-C) )) .* TAs; + YO = max(-1, min(1, ( YO - CGth ) * coristr .* (C+1)/2 )) .* TAs; + + % test new inner surface position .. balance corrections in both + % directions to keep the thickness + if opt.CS4 + VIC = S.vertices + N .* repmat( Tw - (Twc - YI) + (Tpc - YO) ,1,3) / 2; % inner surface + VOC = S.vertices - N .* repmat( Tp - (Tpc - YO) + (Twc - YI) ,1,3) * 2; % outer surface + else + VIC = S.vertices + N .* repmat( Tw - (Twc - YI) + (Tpc - YO) ,1,3); % inner surface + VOC = S.vertices - N .* repmat( Tp - (Tpc - YO) + (Twc - YI) ,1,3); % outer surface + end + + % get values + YIC = cat_surf_isocolors2(Ypp,VIC,opt.mat); YIC = min(1,YIC + cterm); + YppI = cat_surf_isocolors2(Ypp,VI ,opt.mat); YppI = min(1,YppI + cterm); + YppIC = cat_surf_isocolors2(Ypp,VIC,opt.mat); YppIC = min(1,YppIC + cterm); + + % + VIg = cat_surf_volgrad(VIC,N,Ypp,opt.mat); + YI = YI .* ( Twc==0 & ... + abs( GWth - YI ) > abs( GWth - YIC ) & ... + cat_surf_edgeangle( Vg , VIg ) < opt.alphaYpp & ... + ( YppIC > YppI | YppI>GWth) & (YppIC abs( YOC - CGth ) & ... + cat_surf_edgeangle( Vg , VOg ) < opt.alphaYpp & ... + YppOC < YppO & YppOC>CGth & YOC>1.50); % 0.01 & 1.5 + elseif false + YO = YO .* (0.5 + 0.5*YppOC) .* ( Tpc==0 & ... + cat_surf_edgeangle( Vg , VOg ) < opt.alphaYpp & ... + YppOC>CGth ); + end + end + YI = YI .* TAs; + YO = YO .* TAs; + clear YppOC YOC YppO VOg; + + if opt.verb>1, fprintf(' YIC:%5.2f%s%0.2f, YOC:%5.2f%s%0.2f',mean(YI),native2unicode(177, 'latin1'),std(YI),mean(YO),native2unicode(177, 'latin1'),std(YO)); end + + % add to other correction map + Tpc = Tpc - YO; clear YO; + Twc = Twc - YI; clear YI; + end + + % define minimal sulcal/gyral gap + % RD20200403: The idea was good but it is not realy helping for the ISs + % but lead to strong thickness changes (-0.05). + if 0 + sulciGyriWidth = 0.0; + Twc(Twc>0) = Twc(Twc>0) + sulciGyriWidth * 2; + Tpc(Tpc>0) = Tpc(Tpc>0) + sulciGyriWidth; + end + + Tpc = Tpc .* TAs; + Twc = Twc .* TAs; + + % correction in specified areas that also include a general + % smoothness constrains of the cortical thickness + Twc = single(spm_mesh_smooth(M,double(Twc) , sf)) * sf; Tw = max(eps,Tw - Twc); + Tws = single(spm_mesh_smooth(M,double(Tw) , sf/2)); Tw(Twc~=0) = Tws(Twc~=0); clear Tws; + Tpc = single(spm_mesh_smooth(M,double(Tpc) , sf)) * sf; Tp = max(eps,Tp - Tpc); + Tps = single(spm_mesh_smooth(M,double(Tp) , sf/2)); Tp(Tpc~=0) = Tps(Tpc~=0); clear Tps; + + % for the next iteration (used above) + selfwo = selfw; + selfpo = selfp; + + % update thickness and surface + VOC = S.vertices - N .* repmat(Tp,1,3); + VIC = S.vertices + N .* repmat(Tw,1,3); + + % edge flip + if 0 % this has a huge positive effects - RD202506: this might cause some issues ... try without + sm = sf; % smoothness - 1 is not enougth + fa = 60; % error angle (worst case is 180 ) + E = spm_mesh_edges(S); + V = S.vertices; + + VCOA = cat_surf_edgeangle( V(E(:,1),:) - V(E(:,2),:) , VOC(E(:,1),:) - VOC(E(:,2),:) ); + VCOC = VOC(E(VCOA>fa,1),:)/2 + VOC(E(VCOA>fa,2),:)/2; + VOC(E(VCOA>fa,1),:) = VCOC; VOC(E(VCOA>fa,2),:) = VCOC; clear VCOC; + VTPO = T*0; VTPO(E(VCOA>fa,1)) = 1; VTPO(E(VCOA>fa,2)) = 1; clear VCOA; + VTPO = repmat(min(1,max(0,single(spm_mesh_smooth(M,double(VTPO) , 1*sm )) * 1*sm)),1,3); + VOCS = cat_surf_smooth(M,VOC,sm); VOC = VOC.*(1-VTPO) + VTPO.*VOCS; + clear VCOC VTPM; + + + VCIA = cat_surf_edgeangle( V(E(:,1),:) - V(E(:,2),:) , VIC(E(:,1),:) - VIC(E(:,2),:) ); + VCIC = VIC(E(VCIA>fa,1),:)/2 + VIC(E(VCIA>fa,2),:)/2; + VIC(E(VCIA>fa,1),:) = VCIC; VIC(E(VCIA>fa,2),:) = VCIC; clear VCIC; + VTPI = T*0; VTPI(E(VCIA>fa,1)) = 1; VTPI(E(VCIA>fa,2)) = 1; clear VCIA; + VTPI = repmat(min(1,max(0,single(spm_mesh_smooth(M,double(VTPI) , 2*sm))) * 2*sm),1,3); + VICS = cat_surf_smooth(M,VIC,sm); VIC = VIC.*(1-VTPI) + VTPI.*VICS; + clear VCIC VTPM; + clear E V; + else + VTPO = zeros(size(T),'single'); + VTPI = zeros(size(T),'single'); + end + + + + % RD20210403: smoothing block that is not realy necessary anymore + if 0 + % adaptive smoothing + if 1 + Tf = max(1,min(6,Tn)); inorm = ( opt.iteropt*3 - i ) / (opt.iteropt*3); + Tpc = Tpc./max(Tpc(:)); Tpc = single(spm_mesh_smooth(M,double(Tpc) , 1 )) * 1/2 .* Tf .* (1-TAs/2); VOCSf = max(0,min(1,repmat(0.2 .* inorm .* abs(Tpc(Tpc>0 | VTPO(:,1)>0)),1,3))); + Twc = Twc./max(Twc(:)); Twc = single(spm_mesh_smooth(M,double(Twc) , 1 )) * 2/2 .* Tf .* (1-TAs/2); VICSf = max(0,min(1,repmat(0.8 .* inorm .* abs(Twc(Twc>0 | VTPI(:,1)>0)),1,3))); + + VOCS = smoothsurf(VOC,sf/2 * 0.0125); VOC(Tpc>0 | VTPO(:,1)>0,:) = VOC(Tpc>0 | VTPO(:,1)>0,:).*(1-VOCSf) + VOCSf.*VOCS(Tpc>0 | VTPO(:,1)>0,:); + VICS = smoothsurf(VIC,sf/2 * 0.0125); VIC(Twc>0 | VTPI(:,1)>0,:) = VIC(Twc>0 | VTPI(:,1)>0,:).*(1-VICSf) + VICSf.*VICS(Twc>0 | VTPI(:,1)>0,:); + clear VTPI VTPO + end + + % extra smoothing that reduce self-intersections but a bit worse values + % RD202103: I just keep it as the idea of further smoothing + if 0 + Sa = cat_surf_fun('area',S); + Tsw = repmat( max(0,min(1,max( (Tn-3)/6 , (Tn ./ (Sa * 4) - 3) / 6) )) ,1,3) * 0.5; + VOCS = smoothsurf(VOC,sf); VOC = VOC.*(1-Tsw) + Tsw.*VOCS; + VICS = smoothsurf(VIC,sf); VIC = VIC.*(1-Tsw) + Tsw.*VICS; + + % full smooting + VOCSf = repmat(Tf * 0.02 / opt.iterfull,1,3); VOCS = smoothsurf(VOC,sf/2); VOC = VOC.*(1-VOCSf) + VOCSf.*VOCS; clear VOCSf; + VICSf = repmat(Tf * 0.05 / opt.iterfull,1,3); VICS = smoothsurf(VIC,sf/2); VIC = VIC.*(1-VICSf) + VICSf.*VICS; clear VICSf; + end + clear VICS VOCS + + % surface smoothing + if 1 + VOC = cat_surf_smooth(M,VOC,sf,1); + VIC = cat_surf_smooth(M,VIC,sf,1); + end + + % remove outlier ... this has NO effect + % RD202103: I just keep it as the idea of outlier smoothing + if 0 % mod(i,5)==0 || final + VOCc = spm_mesh_curvature( struct('vertices',VOC,'faces',S.faces) ); + VICc = spm_mesh_curvature( struct('vertices',VIC,'faces',S.faces) ); + Tn = max(0.01,sum( (VIC - VOC).^2 , 2) .^ 0.5 ); + Tns = spm_mesh_smooth(M,Tn,sf/2); + Tnss = spm_mesh_smooth(M,Tn,sf/2 * 5); + Tnm = abs( Tns - T )>0.5/(final+1) & (VOCc>60 & VICc>60) & ( Tn > mean(Tn) - min(1,max(2,2*std(Tn))) ) & Tn>1 & Tn>Tnss * 0.75; clear Tns; + Tn( Tnm ) = Tnss( Tnm ); clear Tnss; + VIC( Tnm ,:) = S.vertices( Tnm ,:) + N( Tnm ,:) .* repmat( Tn( Tnm )/2 ,1,3); % inner surface + VOC( Tnm ,:) = S.vertices( Tnm ,:) - N( Tnm ,:) .* repmat( Tn( Tnm )/2 ,1,3); % outer surface + clear Tnm; + end + end + + + + % final new thickness + Tn = max(0.01,sum( (VIC - VOC).^2 , 2) .^ 0.5 ); + Tw = Tn/2; + Tp = Tn/2; + S.vertices = mean(cat(3,VIC,VOC),3); + + % update normals + N = spm_mesh_normals(S); + if 1 % RD20210401: lightly better int/pos but much more intersections + N = smoothsurf(N,1); %sf); + Ns = sum(N.^2,2).^.5; + N = N ./ repmat(Ns,1,3); + end + clear Ns; + + SI = (sum(selfw>0)/2 + sum(selfp>0)/2) / numel(selfw) * 100; + % iteration + if corrsize <= opt.accuracy, final = final + 1; end + if opt.verb + cat_io_cprintf('g5',sprintf( ... + ' Step %2d (SS=%02.0f%%%%, SI=%5.2f%%%%, T=%4.2f%s%4.2f)',... + i,corrsize*100, SI, mean(Tn),native2unicode(177, 'latin1'),std(Tn))); + fprintf('\n') + end + if ((sum(selfw>0)/2 + sum(selfp>0)/2) / numel(selfw) * 100 < opt.accuracy) || (i>opt.iterfull && SI<0.1 && abs(SI - SIO)<0.005) % if changes are below a specified relative level + if final < 4 && (sum(selfw>0)/2 + sum(selfp>0)/2)>0 && i>opt.iterfull && abs(SI - SIO)>0.005 % do some additional iterations if required + final = final + 1; + else + break + end + end + SIO2 = SIO; + SIO = SI; + end + + if opt.verb, fprintf('\n'); end + if 0 % flipped2 + S.faces = [S.faces(:,1) S.faces(:,3) S.faces(:,2)]; + end + if flipped + S.faces = [S.faces(:,1) S.faces(:,3) S.faces(:,2)]; + if isfield(S , 'mati' ), S.mati(7) = - S.mati(7); end + end +end +function [Sve,Svde] = cat_surf_disterr(S,T,mat,Yp0,tol) + + % render volume + % [Yp,Yt,vmat1,vmat1i] = cat_surf_surf2vol(S,Y,T,type,opt) + Yp0S = cat_surf_surf2vol(S,Yp0,T,'seg',struct('mat',mat)); + Ycs = cat_surf_surf2vol(S,Yp0,T,'p0',struct('mat',mat)); + + Ydiff = Yp0S - Yp0; + + % Delaunay triangulation + D = delaunayn(S); + + % select relevant points for projection + PI = find( abs(Ydiff) > tol & Ycs>0 ); + PO = find( abs(Ydiff) > tol & Ycs<0 ); + + % project points + [DI,II] = dnear(D,PI); + [DO,IO] = dnear(D,PI); + + % remove to close points + + + % mapping + for di = 1:numel(DI) + Sve( II(di) ) = Sve( II(di) ) + Ydiff( PI(di) ); % just the volume + Svde( II(di) ) = Svde( II(di) ) + DI(di) * Ydiff( PI(di) ); % weighted by distance + end +end +function [SN,TN,E] = cat_surf_collision_correction(S,T,Y,Ypp,Yl4,opt) +% _________________________________________________________________________ +% Delaunay based collision detection: +% 1) Correction for local curvature +% 2) Creation of a Delaunay graph +% 3) Differentiation of intra (edges between surface points) and inter +% surface edges (e.g., edges between to opposite gyri or sulci) and +% removal of intra-surface edges. +% 4) Use of the inter-surfaces edges to detect collision by normal +% transformations of the half thickness to obtain the inner and outer +% surfaces. +% 5) Further correction of possible flips by normal transformation +% +% This is a prototype that allows correction of the worst things but not +% all collisions. +% +% [SN,TN,E] = cat_surf_collision_correction(S,T,Y[,debug,E,Pcs]) +% +% SN .. new surface +% TN .. new thickness +% S .. original surface +% T .. original thickness +% Y .. segmentation map or intensity normalized images +% for intra/inter surface edge definition +% Yl4 .. layer4 intensity surface map +% opt .. parameter structure +% .debug .. option to write the un- and corrected cortical surfaces in a +% subdirectory +% .verb .. +% .E .. Delaunay edge map (from previous run or empty matrix as input) +% .Pcs .. central surface file name to write debugging files +% ... experimental settings +% .smoothCSinput .. +% .model .. +% .PVEcorr .. +% .slowdown .. +% . +% _________________________________________________________________________ +% Robert Dahnke 201909 + + +% ------------------------------------------------------------------------- +% Todo: +% - full support of parameters & recall +% - support of different correction models +% (e.g. only collision vs. intensity correction) +% - full documentation and detailed comments +% - helping boundary surfaces? +% > partially implemented +% > very slow +20-60s for each just for creation +% - stable subset/list (also as internal/external error measure +% - use of gradients and divergence rather simple intensity information +% - use of Ypp +% - optimization of the layer 4 (layer concept) +% - face-flipping correction that can not be handled by Delaunay because of +% its neighbor limits +% - improved evaluation concept +% - improved validation concept +% - fast mapping c-function for edge to surf that combine multiple values +% given by an index map by different functions (mean,min,max,std) +% - surface filter sub-function to remove outlier +% - triangle height rather than edge distance (or combination) +% ------------------------------------------------------------------------- + + if ~exist('opt','var'), opt = struct(); end + + % default variables + def.Pcs = ''; % filename to write debugging output data + def.debug = 1; % debugging output vs. memory optimization + def.verb = 1; % display debugging information + def.E = []; % inter-surface Delaunay edges (of a previous run) + def.boundarySurfaces = 0; % use inner and outer boundary surface to improve the Delaunay graph + def.smoothCSinput = 0; % smooth the input CS for more stable Delaunay triangulation in case of locally oversampled surfaces + def.PVEcorr = 1; % correction of PVE values for 2 boundaries in on voxel (experimental) + def.slowdown = 1; % slowdown may stabilize the process over the iterations + def.model = 2; % 0 - only collcorr, 1 - only intopt, 2 - both + def.vx_vol = 1; + opt = cat_io_checkinopt(opt,def); clear def; + def.write = opt.debug & ~isempty(opt.Pcs); + opt = cat_io_checkinopt(opt,def); + + + % helping smoothing functions for data and surfaces + M = spm_mesh_smooth(S); % for spm_smoothing matrix + rms = @(x) mean( x.^2 ) .^ 0.5; % for error handling of mad vertices + smoothsurf = @(V,s) [ ... % simple surface smoothing + spm_mesh_smooth(M,double(V(:,1)),s) , ... + spm_mesh_smooth(M,double(V(:,2)),s) , ... + spm_mesh_smooth(M,double(V(:,3)),s) ]; + + + % detection and correction for flipped faces to have always the same normal direction + lim = 1:round(size(S.vertices,1)/1000):size(S.vertices,1); + N = spm_mesh_normals(S); + VOl = S.vertices(lim,:) - N(lim,:) .* repmat(T(lim)/2,1,3); + VIl = S.vertices(lim,:) + N(lim,:) .* repmat(T(lim)/2,1,3); + YOl = cat_surf_isocolors2(Y,VOl); + YIl = cat_surf_isocolors2(Y,VIl); + flipped = mean(YOl) > mean(YIl); + clear N VOl VIl YOl YIl lim; + if flipped, S.faces = [S.faces(:,1) S.faces(:,3) S.faces(:,2)]; S.mati(7) = - S.mati(7); end + + + % larger surface need more smoothing to avoid triangulation problems + sf = round( sqrt( size(S.faces,1) / 50000) ); % ### empirical value + if max(Y(:))<1.5, Y = Y.*2+1; else, Y = max(1,Y); end + if opt.debug, fprintf('\n'); end + if opt.write, cat_surf_saveICO(S,T,mat,Pcs,sprintf('pre_collcorr_%0.0fk',round( size(S.faces,1)/1000 / 10) * 10 ),0); end + stime = cat_io_cmd(sprintf(' Delaunay triangulation of %d vertices (sf=%d):',size(S.vertices,1),sf),'g5','',opt.debug); + + + + + + + %% Creation of the inter surface edges based on a Delaunay graph + % ---------------------------------------------------------------------- + % There is a short cut to apply further iterations without processing + % the graph again. + % ---------------------------------------------------------------------- + if isfield(opt,'E') && isempty(opt.E) + + % Early versions used a smoothed surface to reduce problems due to + % artifacts. However, the improved input meshed (createCS2 pipeline) + % do not need smoothing and surface smoothing can not be combined + % with helping surfaces (inner and outer surface points). + VS = double(S.vertices); + if opt.smoothCSinput + % Surface smoothing as loop to correct for outlier due to incorrect surfaces. + % Using the smoothing directly create some extrem large spikes - don't know why (RD20190912). + % The smoothing is not required in newer version (RD20190922) + for i = 1:opt.smoothCSinput + VSi = smoothsurf(VS,2); + VM = rms(VSi - VS)<2; + VS(VM,:) = VSi(VM,:); + end + VS = smoothsurf(VS,1); + end + if ~opt.debug, clear VSi VM; end + + + % helping boundary surface - (uncorrected) inner or/and outer surface + % this was slow (20-60 seconds) and did not work so simple/fast ... need further work + % maybe just use low resolution surfaces (1 mm) + if opt.boundarySurfaces + if opt.smoothCSinput, error('Initial surface smoothing ""smoothCSinput"" can not be combined with ""boundarySurfaces"".\n'), end + VB = S.vertices; + if opt.boundarySurfaces == 1 || opt.boundarySurfaces == 3 + UOS = isosurface(Y,1.5); + VS = [ VS ; UOS.vertices ]; + VB = [ VB ; UOS.vertices ]; + if ~opt.debug, clear UOS; end + end + if opt.boundarySurfaces == 2 || opt.boundarySurfaces == 3 + UIS = isosurface(Y,1.5); + VS = [ VS ; UIS.vertices ]; + VB = [ VB ; UIS.vertices ]; + if ~opt.debug, clear UIS; end + end + end + + + % Delaunay graph + D = single(delaunayn( VS )); + if ~opt.debug, clear VS; end + + % decompose delaunay graph into its edges + E = uint32(cat_surf_edges(D)); + nE = size(E,1); + if ~opt.debug, clear D; end + if opt.debug, cat_io_cprintf('g5',sprintf('%5.0fs\n',etime(clock,stime))); end + + + % separate helping boundary surfaces + if opt.boundarySurfaces == 2 || opt.boundarySurfaces == 3 + Etmep = sum( E>( size(S.vertices,1) + any(opt.boundarySurfaces==[1,3]).*size(UOS.vertices,1) ) , 2 )>0; + EUIS = E( Etmep , : ); + EUIS( sum( EUIS>numel(S.vertices) , 2 )~=1, :) = []; % remove all edges that are not between the CS and the UIS + EUIS = sort(EUIS,2); + E( Etmep , : ) = []; + end + if opt.boundarySurfaces == 1 || opt.boundarySurfaces == 3 + Etmep = sum( E>( size(S.vertices,1) ) , 2 )>0; + EUOS = E( Etmep , : ); + EUOS( sum( EUOS>numel(S.vertices) , 2 )~=1, :) = []; % remove all edges that are not between the CS and the UOS + EUOS = sort(EUOS,2); + E( Etmep , : ) = []; + end + + + %% Remove intra-surface edges + % -------------------------------------------------------------------- + % If we remove too much then the correction will not work. + % If we do not remove enough then it will add sulci in regions without sulci + + V = S.vertices; + + % remove edge that we know from the surface - super save + stime = clock; + EF = uint32(cat_surf_edges(S.faces)); + E = setdiff(E,EF,'rows'); clear EF; + + % remove edges between neigbors of each point - relative save + % get neighbor matrix + [NE,MED] = spm_mesh_neighbours(M); + nNE = size(NE,1); + + % extra element that link on itself and replace the 0 in NE that does not allow matrix indexing + NIL = nNE + 1; + NE(NIL,:) = NIL * ones(1,size(NE,2)); NE(NE==0) = nNE+1; + + % further levels + % use higher levels only for large surfaces (use sqrt to compensate area grow factor) + nlevel = 2; % max(2,round( 1 + sqrt( ceil( size(S.faces,1) / 300000 ) ))); + for nli = 1:nlevel % nice idear but not working yet + for ni = 1:size(NE,2) + NEN = sum( NE == repmat( NE(NE(:,ni),ni) , 1 , size(NE,2) ),2)>0; + NE = [ NE min( NIL , NE(:,ni) + NIL*NEN) ]; %#ok + MED = [ MED MED(:,ni) ]; %#ok + end + + % sort entries + [NE,NEsi] = sort(NE,2); MED = MED(NEsi); clear NEsi + NILi = min([ size(NE,2) , find( sum(NE == NIL,1) >= size(NE,1)*0.5 , 1, 'first') - 1]); + NE = NE(:,1:NILi); + MED = MED(:,1:NILi); + end + NE(NE==NIL) = 0; + + % remove edges from the neigbor list + for i=2:size(NE,2) + E = setdiff(E,[NE(:,1) NE(:,i)],'rows'); + E = setdiff(E,[NE(:,i) NE(:,1)],'rows'); + end + clear NE + if opt.debug + cat_io_cprintf('g5',sprintf(' remove edges by surface (l%d):%8d > %9d (%0.2f%%%%) %9.0fs',... + nlevel,nE,size(E,1),size(E,1)./nE,etime(clock,stime))); + else + clear nE + end + + if 1 + % remove edge by distance - this is not clear but it helps + stime = clock; + LE = sum( (V(E(:,1),:) - V(E(:,2),:)).^2 , 2) .^ 0.5; % length of edge + DE = min( LE > max(0.5,min(1,max(MED(:)))) , min( LE - T(E(:,1))*0.33 , LE - T(E(:,2))*0.33 )); + NEd = abs(DE); clear LE DE MED; + + % remove by angle .. sum(NEa)./numel(NEa), figure, hist( S1alpha, -180:1:180) + % N(S)alpha .. angle between the (smoothed) normals of each edge + % (~0? = surface edge; ~180? between surface edge) + % S[12]alpha .. angle between the edge and the first normal + % (~0?/~180? = surface edge; ~90? = between surface edge) + % + N = spm_mesh_normals(S); + NS = N; for i=1:80*sf, NSS = smoothsurf(NS,1); NM = rms(NS - NSS)<0.5; NS(NM,:) = NSS(NM,:); end + Nalpha = [cat_surf_edgeangle(NS(E(:,1),:), NS(E(:,2),:)), ... + cat_surf_edgeangle(NS(E(:,2),:), NS(E(:,1),:))]; clear NS + SNalpha = [cat_surf_edgeangle(N(E(:,1),:), V(E(:,1),:) - V(E(:,2),:)), ... + cat_surf_edgeangle(N(E(:,2),:), V(E(:,2),:) - V(E(:,1),:))]; + NEna = mean(Nalpha/180,2); clear Nalpha % figure, hist( NEna , 0:0.01:1); + NEsa = (abs(90 - SNalpha)/90 + abs(90 - SNalpha)/90)/2; % figure, hist( NEsa , 0:0.01:1); + clear SNalpha; + + % remove by intensity given by the centroids of the edges + VC = cat_surf_centroid(V,E); + IC = cat_surf_isocolors2(Y,VC); clear VC; + % outer surface intensity + VO = V - N .* repmat(T/2,1,3); + VOC = cat_surf_centroid(VO,E); + IO = cat_surf_isocolors2(Y,VOC); clear VOC VO; + % inner surface intensity + VI = V + N .* repmat(T/2,1,3) + 0.1; % GM/WM + VIC = cat_surf_centroid(VI,E); + II = cat_surf_isocolors2(Y,VIC); clear VIC VI; + VI = V + N .* repmat(T/2,1,3) + 0.5; % save WM + VIC = cat_surf_centroid(VI,E); + II = max(II,cat_surf_isocolors2(Y,VIC)); clear VIC VI; % use max to get WM value + VI = V + N .* repmat(T/2,1,3) + 1.0; % supersave WM + VIC = cat_surf_centroid(VI,E); + II = max(II,cat_surf_isocolors2(Y,VIC)); clear VIC VI; % use max to get WM value + % combine all intensities + NEi = 1 - min(1,max(abs(diff([II IC IO],1,2)),[],2)); + %ET = mean([II IC IO],2)>2.25; % edge classification + if ~opt.debug, clear II IC IO; end + + % combine all measures by product to remove many things + % I also though about an adaptive threshold but it is not so easy ... + NE = prod( [NEd NEi NEna*2 NEsa*2] ,2); % 1.75 % larger values > remove less + NE = NE < .05; %05; %max(eps,mean(NE) - 1*std(NE)); % smaller values > remove less + E (NE,:) = []; %if exist('ET','var'), ET(NE) = []; end + if opt.debug + cat_io_cprintf('g5',sprintf('\n remove edges by intensity: > %9d (%0.2f%%%%) %9.0fs',... + size(E,1),size(E,1)./nE,etime(clock,stime))); stime = clock; + else + clear NE NEd NEi NEna NEsa + end + else + N = spm_mesh_normals(S); + end + + + %fprintf('\nsf = %0.2f',sf); + else + N = spm_mesh_normals(S); + end + + + if opt.debug + cat_io_cprintf('g5','\n Prepare Optimization:'); stime = clock; + end + + %% updated measures + SNalpha = [cat_surf_edgeangle(N(E(:,1),:), V(E(:,1),:) - V(E(:,2),:)), ... + cat_surf_edgeangle(N(E(:,2),:), V(E(:,2),:) - V(E(:,1),:))]; + + VC = cat_surf_centroid(V,E); + IC = isocolors(Y,VC); clear VC; + + OE = min(1,(IC<2.15)); %(min(SNalpha,[],2)<90) + + IE = min(1,(IC>2.15));%(max(SNalpha,[],2)>90) + + if 0 + %% map outer or inner edges + %VLE = inf(size(T),'single'); + VLE = zeros(size(T),'single'); + for ni=1:size(E,1) + VLE(E(ni,1)) = VLE(E(ni,1)) + IE(ni); + end + end + + + if 0 + % avoid PBT overestimation in gyri (well thickness is correct but + % measures non-linear/non-orthogonal) + TN = single(spm_mesh_smooth(M,double(T), sf * 20 )); + T = min(T,TN); + end + + TN = T; SN = S; TCsum = 0; %#ok + TCsumo = inf; TNold = inf; + maxiter = 5; % main number of iterations + maxiter2 = 5; % limit of adapting the mixing model + + Yl4 = single(spm_mesh_smooth(M,double(Yl4),sf/4 * 100)); + + % I did not manage to use curvate ... + %C = spm_mesh_curvature(S); + %C = spm_mesh_smooth(M,C,1); + + % PVE doubleside correction: + % If a voxel contain 38% GM and 62% CSF and has one boundary, it is approximately at the 38% position of the voxel. + % If the same voxel contain two boundaries, the each boundary is approximately at the 19% position of that voxel. + % Hence, I try to measure the filling effect in regions of two boundaries by the local minimum/maximum to estimate + % double the PVE effect (like a sharpening). + % However, this is relative slow ... + if 0 %opt.PVEcorr + Ypvec = cat_vol_localstat(max(1,cat_vol_localstat(min(2,max(1,Y)),Y>1,2,3)),Y>1,2,2); + Ypvew = cat_vol_localstat(max(2,cat_vol_localstat(min(3,max(2,Y)),Y>1,2,2)),Y>1,2,3); + Y = max(1,min(3,Y - ((max(Ypvec,Y))-Y) + (Y-(min(Ypvew,Y))))); + end + + if opt.debug + stime = cat_io_cmd(' Optimize surface:','g5','',opt.verb,stime); fprintf('\n'); + end + + %% Iterative correction routine + for j=1:maxiter+1 + V = single(SN.vertices); + + % update surface normales + N = spm_mesh_normals(SN); + + % inner and outer surface + VO = V - N .* repmat(TN/2,1,3); + VI = V + N .* repmat(TN/2,1,3); + + + % First correction step that works but also could be improved. + % --------------------------------------------------------------------- + % Complex side specific correction by the inter-surface edges, that + % used the angle between the edges and normals to define edges within + % a suclus (outer) or within a gyrus (inner). + % In general, only inter-surface edges are expected here, those + % distance describes the maximal local thickness. We also add some + % sulcus-width to avoid collisions but the effect will be small due + % to the smoothing. + % There are problems that not all points have a inter-surface edge, + % so it is necessary to smooth to include unconnected neighbors + % LEC, LEOC, and LEIC represent the distance error by collisions + % of each edge. + % --------------------------------------------------------------------- + + + % edgelength of the central, inner, and outer surface + % ### + % The edgelength is just the simples measure - the high of the + % tetraeder would be more excact. + %% ### + LE = sum( (V(E(:,1),:) - V(E(:,2),:)).^2 , 2) .^ 0.5; % distance between the central surface (~ thickness/2 + thickness/2) + LEO = sum( (VO(E(:,1),:) - VO(E(:,2),:)).^2 , 2) .^ 0.5; % distance between the outer surface (~?minimal/maximal distance) + LEI = sum( (VI(E(:,1),:) - VI(E(:,2),:)).^2 , 2) .^ 0.5; % distance between the inner surface (~ minimal/maximal distance) + %% angle correction + if 0 + %% + Nalpha = [angle(V(E(:,1),:), N(E(:,1),:)), angle(V(E(:,2),:), N(E(:,2),:))]; + Nalphas = 1; %(Nalpha>90) * 2 - 1; + Nalpha = min( Nalpha , abs( 180 - Nalpha )) .* Nalphas; + LE = min( repmat( LE ,1,2) .* cosd(Nalpha) , [] , 2); +%% + NalphaO = [angle(VO(E(:,1),:), N(E(:,1),:)), angle(VO(E(:,2),:), N(E(:,2),:))]; + NalphaOs = (NalphaO>90) * 2 - 1; + NalphaO = min( NalphaO , abs( 180 - NalphaO )) .* NalphaOs; + LEO = min( repmat( LEO ,1,2) .* cosd(NalphaO) .* (NalphaO<60),[],2); clear NalphaO; + + NalphaI = [angle(VI(E(:,1),:), N(E(:,1),:)), angle(VI(E(:,2),:), N(E(:,2),:))]; + NalphaIs = (NalphaI>90) * 2 - 1; + NalphaI = min( NalphaI , abs( 180 - NalphaI )) .* NalphaIs; + LEI = min( repmat( LEI ,1,2) .* cosd(NalphaI),[],2); clear NalphaI; + + if 0 + %% + %VLE = inf(size(T),'single'); + VLE = zeros(size(T),'single'); + for ni=1:size(E,1) + %VLE(E(ni,1)) = min( VLE(E(ni,1)) , LE(ni) ./ OE(ni) ); + VLE(E(ni,1)) = VLE(E(ni,1)) + IE(ni); + end + end + end + if opt.boundarySurfaces == 1 || opt.boundarySurfaces == 3 + LEUOS = sum( (VB(EUOS(:,1),:) - VB(EUOS(:,2),:)).^2 , 2) .^ 0.5; % distance b + end + if opt.boundarySurfaces == 2 || opt.boundarySurfaces == 3 + LEUIS = sum( (VB(EUIS(:,1),:) - VB(EUIS(:,2),:)).^2 , 2) .^ 0.5; + end +%TNalpha = sum( [ min( TN(E(:,1))/2, TN(E(:,1))/2 .* cosd(Nalpha(E(:,1))) ) ....* (Nalpha(E(:,1))<60) ) ... +% min( TN(E(:,2))/2, TN(E(:,2))/2 .* cosd(Nalpha(E(:,2))) ) ] ,2); %.* (Nalpha(E(:,2))<60) ) ] , 2); +TNalpha = sum( [ TN(E(:,1))/2, TN(E(:,2))/2 ] , 2 ); %.* (Nalpha(E(:,2))<60) ) ] , 2); + + LE = max(0,LE - 0.02); % minimum sulcus/gyrusweidth + + % estimate error for each Delaunay edge + % (sum local thickness and sulcuswidth vs. the length of the edge) + %sulcuswidth = 0.0; % worse results with additional width + LECP = max(0, LE - TNalpha); %( TN(E(:,1))/2 + TN(E(:,2))/2 + 0.02 ) ) / 2; % - sulcuswidth )); + LEC = max(-inf, TNalpha - LE); %(TN(E(:,1))/2 + TN(E(:,2))/2) - (LE - 0.02) ) / 2; % - sulcuswidth )); + LEOC = LEO .* max(-inf, 0.02 - LEO) / 2; %clear LEO; % minimum distance between points (rare spaecial case) + LEIC = LEI .* max(-inf, 0.02 - LEI) / 2; %clear LEI; % minimum distance between points (rare spaecial case) + TNP = repmat(TN,3,1); %2 + any(opt.boundarySurfaces == [1,3]) + any(opt.boundarySurfaces == [2,3]) ,1); + if opt.boundarySurfaces == 1 || opt.boundarySurfaces == 3 + LEUOC = max(0, LEUOS - ( TNP(EUOS(:,1))/2 ) ); + end + if opt.boundarySurfaces == 2 || opt.boundarySurfaces == 3 + LEUIC = max(0, LEUIS - ( TNP(EUIS(:,1))/2 ) ); + end + + + + %% map the Delaunay edge correction to the vertices (simple maximum) + % ### + % You may (also) use some intensity information here! ... added + % Moreover, a loop is very slow and the estimation of a mapping + % would be better! But how? ... partially implemented + % ### + %{ + EOid = TN*0; EIid = TN*0; + for ni=1:size(E,1) + EOid(E(ni,1)) = EOid(E(ni,1)) .* , LEC(ni) .* OE(ni), LEOC(ni)]); + EOid(E(ni,2)) = max([EOid(E(ni,2)), LEC(ni) .* OE(ni), LEOC(ni)]); + EIid(E(ni,1)) = max([TIC(E(ni,1)), LEC(ni) .* IE(ni), LEIC(ni)]); + EIid(E(ni,2)) = max([TIC(E(ni,2)), LEC(ni) .* IE(ni), LEIC(ni)]); + end + %} + OE = min(1,(min(SNalpha,[],2)<60) + IC<2.15); + IE = min(1,(max(SNalpha,[],2)>60) + IC>2.15); + + DN = TN*0; + TOC = TN*0; TIC = TN*0; TOCP = TN*0; TICP = TN*0; %PVE_LEOC = TN*0; PVE_LEIC = TN*0; + app = 0; + if app == 1 + for ni=1:size(E,1) + % OE = min(1,(min(SNalpha(ni,:))<60) + IC(ni)<2.15); + % IE = min(1,(max(SNalpha(ni,:))>60) + IC(ni)>2.15); + + %{ + PVE_LEOC(E(ni,1)) = max(0,opt.vx_vol - LEOC(ni)); + PVE_LEOC(E(ni,2)) = max(0,opt.vx_vol - LEOC(ni)); + PVE_LEIC(E(ni,1)) = max(0,opt.vx_vol - LEIC(ni)); + PVE_LEIC(E(ni,2)) = max(0,opt.vx_vol - LEIC(ni)); + %} + + % DN(E(ni,1)) = DN(E(ni,1)) + 1; + % DN(E(ni,2)) = DN(E(ni,2)) + 1; + + TOC(E(ni,1)) = max([TOC(E(ni,1)), LEC(ni) .* OE(ni), LEOC(ni)]); + TOC(E(ni,2)) = max([TOC(E(ni,2)), LEC(ni) .* OE(ni), LEOC(ni)]); + TIC(E(ni,1)) = max([TIC(E(ni,1)), LEC(ni) .* IE(ni), LEIC(ni)]); + TIC(E(ni,2)) = max([TIC(E(ni,2)), LEC(ni) .* IE(ni), LEIC(ni)]); + + % with angle weighting ... + TOCP(E(ni,1)) = max([TOCP(E(ni,1)),LECP(ni) .* OE(ni)]); + TOCP(E(ni,2)) = max([TOCP(E(ni,1)),LECP(ni) .* OE(ni)]); + TICP(E(ni,1)) = max([TICP(E(ni,1)),LECP(ni) .* IE(ni)]); + TICP(E(ni,2)) = max([TICP(E(ni,1)),LECP(ni) .* IE(ni)]); + end + else + for ni=1:size(E,1) + TOC(E(ni,1)) = max([TOC(E(ni,1)), LEC(ni) .* OE(ni), LEOC(ni)]); + TOC(E(ni,2)) = max([TOC(E(ni,2)), LEC(ni) .* OE(ni), LEOC(ni)]); + TIC(E(ni,1)) = max([TIC(E(ni,1)), LEC(ni) .* IE(ni), LEIC(ni)]); + TIC(E(ni,2)) = max([TIC(E(ni,2)), LEC(ni) .* IE(ni), LEIC(ni)]); + end + end + if opt.boundarySurfaces == 1 || opt.boundarySurfaces == 3 + for ni=1:size(EUOS,1) + TOC( mod( EUOS(ni,1)-1 , size(SN,1) )+1) = LEUOC(ni); + end + end + if opt.boundarySurfaces == 2 || opt.boundarySurfaces == 3 + for ni=1:size(EUOS,1) + TOC( mod(EUIS(ni,1)-1, size(SN,1) )+1) = LEUIC(ni); + end + end + %% + clear LEC LEOC LIOC; + if opt.slowdown + slowdown = max(1,2/j); + else + slowdown = 1; + end +opt.model=0; + if opt.model == 0 || opt.model == 2 + TOC = single( spm_mesh_smooth(M,double(TOC), sf ))*1.4; TOC = TOC / (slowdown/2); + TIC = single( spm_mesh_smooth(M,double(TIC), sf ))*1.2; TIC = TIC / (slowdown/2); + if opt.verb, fprintf('\n TIC: %0.2f%s%0.2f, TOC: %0.2f%s%0.2f',mean(TIC),native2unicode(177, 'latin1'),std(TIC),mean(TOC),native2unicode(177, 'latin1'),std(TOC)); end + end + %% + if opt.model + % filter limits + TOCP = single( spm_mesh_smooth(M,double(TOCP), 1 ))*0.2;%1.0;% 1.5 + TICP = single( spm_mesh_smooth(M,double(TICP), 1 ))*0.8; + + % correction for intensities ... + YI = cat_surf_isocolors2(Y,VI); + YO = cat_surf_isocolors2(Y,VO); + YppO = cat_surf_isocolors2(Ypp,VO); + + if opt.model == 1 && opt.verb, fprintf('\n'); end + if opt.verb, fprintf(' YIC: %0.2f%s%0.2f, YOC: %0.2f%s%0.2f',mean(YI),native2unicode(177, 'latin1'),std(YI),mean(YO),native2unicode(177, 'latin1'),std(YO)); end + + WMth = 3; YI = max( -TICP , max(-1, min(0.5, YI - ((WMth/2 + Yl4/2) ) )) ) / (slowdown); + CSFth = 1; YO = max( -TOCP , max(-1, min(0.5, ((CSFth/2 + Yl4/2) ) - YO )) ) / (slowdown);% + 2*C + CSFth = 0; Yppc = max( -TOCP , max(-0.05, min(0.05, 0.01 - YppO )) ) / (slowdown);% + 2*C + + if 0 + YC = isocolors2(Y,V ); + YC = max( -0.5, min( 0.5, YC - Yl4 )) / (slowdown); + YI = YI * 0.8 + 0.2 * YC; + YO = (YO * 0.8 - 0.2 * YC) .* min(1,YppO*20); + end + YO = YO * 0.8 - 0.2 * Yppc; + + if opt.verb, fprintf(', YIC: %0.2f%s%0.2f, YOC: %0.2f%s%0.2f',mean(YI),native2unicode(177, 'latin1'),std(YI),mean(YO),native2unicode(177, 'latin1'),std(YO)); end + + VOC = V - N .* repmat( TN/2 - YO ,1,3); % outer surface + VIC = V + N .* repmat( TN/2 - YI ,1,3); % inner surface + + YIC = cat_surf_isocolors2(Y,VIC); + YOC = cat_surf_isocolors2(Y,VOC); + YppOC = cat_surf_isocolors2(Ypp,VOC); + + YI = YI .* ( abs(YI - (WMth/2 + Yl4/2)) > abs(YIC - (WMth/2 + Yl4/2))); + YO = YO .* ( abs((CSFth/2 + Yl4/2) - YO) > abs((CSFth/2 + Yl4/2) - YOC) & YppOC>0); + + % filter correction + YO = single(spm_mesh_smooth(M,double(YO), sf )); + YI = single(spm_mesh_smooth(M,double(YI), sf )); + +% if the point is/was perfect then do not change +% if the new point is perfect / better than the old then simply use it? + + % combine + if opt.model == 1 % only intensity + TIC = YI; + TOC = YO; + elseif opt.model % combine + mixing = max(0,min(0.5,-0.02 + 1.0*min(1,j/maxiter2)));%0.8; + TIC = mean( cat( 4, TIC*(1-mixing) , YI*mixing), 4); + TOC = mean( cat( 4, TOC*(1-mixing) , YO*mixing), 4); + end + end + + + % estimate first corrected inner and outer thickness + % Different levels of smoothing were use to have more effect on neighbors. + TOC = single( spm_mesh_smooth(M,double( TOC ), sf*2 )); % + spm_mesh_smooth(M,double( TOC ), sf*4 )); + TIC = single( spm_mesh_smooth(M,double( TIC ), sf*2 )); % + spm_mesh_smooth(M,double( TIC ), sf*4 )); + TC = TOC + TIC; TCsum = rms(TC(TC>0)); + +%{ + % correction in specified areas that also include a general + % smoothness constrains of the cortical thickness + TNC = TN - TOC/2 - TIC/2; + TNC = single(spm_mesh_smooth(M,double(TNC), sf*max(0.5,2 - 2*(j/maxiter2))) ); + TN(TC>0) = TNC(TC>0); + clear TC TNC flim; +%} + + % estimate new inner and outer surfaces + VOC = V - N .* repmat( TN/2 - TOC ,1,3); % outer surface + VIC = V + N .* repmat( TN/2 - TIC ,1,3); % inner surface + clear TOC TIC; + + % update thickness and surface + TN = sum( (VIC - VOC).^2 , 2) .^ 0.5; + SN.vertices = mean(cat(3,VIC,VOC),3); + + + %% this is just for display and loop settings + % SX.vertices = VOC; SX.faces = S.faces; SX.facevertexcdata = TC; cat_surf_render2(SX); + stopiterth = 0.00005; + if opt.debug && ( j==1 || mod(j,1)==0 || abs(TCsum)<0.01 || abs(TCsumo - TCsum)(mean(TN(:)) - 2*std(TN(:))) & TN<(mean(TN(:)) + 2*std(TN(:))); + if ~opt.verb, fprintf('\n'); end + try + cat_io_cprintf('g5',sprintf(' remaining overlap: %8.4f mm (Tlink: %4.2f%s%4.2f mm) %9.0fs',... + TCsum,mean(TN(TNM)),native2unicode(177, 'latin1'),std(TN(TNM)),etime(clock,stime) )); stime = clock; + end + end + if ( TCsum<0.005 || abs(TCsumo - TCsum) + F = [F1;F2;F3;F4]; clear F1 F2 F3 F4; + + % remove double vertices + if CT==0, [V,F] = reduce_points(V,F); + else [V,F,C] = reduce_points(V,F,C); + end + + case 'dist' + if ~exist('distth','var'), distth=sqrt(2); end + + % addition vertices (middle of the edge) + E1 = diff(cat(3,V(F(:,1),:),V(F(:,2),:)),1,3); + E2 = diff(cat(3,V(F(:,2),:),V(F(:,3),:)),1,3); + E3 = diff(cat(3,V(F(:,3),:),V(F(:,1),:)),1,3); + + V1 = V(F(:,1),:) + repmat((sum(E1.^2,2).^0.5)>=distth,1,3) .* (0.5*E1); + V2 = V(F(:,2),:) + repmat((sum(E2.^2,2).^0.5)>=distth,1,3) .* (0.5*E2); + V3 = V(F(:,3),:) + repmat((sum(E3.^2,2).^0.5)>=distth,1,3) .* (0.5*E3); + + % new faces which replace the old one + F1 = [F(:,1), nV + 2*nF + NF, nV + NF]; + F2 = [F(:,2), nV + NF, nV + nF + NF]; + F3 = [F(:,3), nV + nF + NF, nV + 2*nF + NF]; + F4 = [nV + NF, nV + 2*nF + NF, nV + nF + NF]; + + % colors + if CT==2, C=[C;nanmean(C(F(:,1),:),C(F(:,2),:));nanmean(C(F(:,2),:),C(F(:,3),:));nanmean(C(F(:,3),:),C(F(:,1),:))]; %#ok + elseif CT==1, C=repmat(C,4,1); + end + + V = [V;V1;V2;V3]; clear V1 V2 V3; %#ok + F = [F1;F2;F3;F4]; clear F1 F2 F3 F4; + + + % remove double vertices + if CT==0, [V,F] = reduce_points(V,F); + else [V,F,C] = reduce_points(V,F,C); + end + + % remove degnerated faces + F((F(:,1)==F(:,2)) | (F(:,1)==F(:,3)) | (F(:,2)==F(:,3)),:)=[]; + + otherwise + error('ERROR: Unknown method ""%s""',method); + end + end + S.vertices = V; S.faces = double(F); if exist('C','var'), S.facevertexcdata = C; end +end + +function [V,F,C]=reduce_points(V,F,C) + try + [V,i,j] = unique(V, 'rows'); + catch %#ok + V=single(V); + [V,i,j] = unique(V, 'rows'); + end + if exist('C','var'), C=C(i); end + j(end+1) = nan; + F(isnan(F)) = length(j); + if size(F,1)==1, F = j(F)'; + else F = j(F); + end +end + +function cdata2 = cat_surf_surf2vol2surf(S,S2,cdata,res) + % create volume + % render data + % aprax + % proejcet +end + +function [Yp,Yt,vmat1,vmat1i] = cat_surf_surf2vol(S,Y,T,type,opt) +% cat_surf_surf2vol +% _________________________________________________________________________ +% +% Render a surface mesh and/or its data to a (given) volume. +% The volume Y can be used as mask to reduce processing time. +% +% [Yp,Yv,vmat,vmati] = cat_surf_surf2vol(S,Y,T,type,opt) +% +% S .. surface +% Y .. volume for rendering +% T .. thickness +% type .. ['pve','seg','val'] +% 'pve' .. default that simply render the surface into a (given) volume +% 'pp' .. create percentage position map +% 'seg' .. create a segmentation label map with the thickness map T +% 'val' .. just render the value (fast) +% opt .. additional parameter +% .refine .. refine mesh to improve accuracy (default 1.8) +% .acc .. render more layer to improve accuracy (default 0) +% .verb .. display +% _________________________________________________________________________ +% Robert Dahnke 201911 + + +% TODO: +% - T as [1x2] and [T,T] vector with lower and upper enlargement +% - render of negative values T + minT ... Yt - minT +% - triangle/edge rendering and no refinement + + global mati vmati + + ftime = clock; + + if ~exist('Y','var'), Y = []; end + if ~exist('T','var'), T = []; end + if ~exist('type','var'), type = 'pve'; end + if ~exist('opt','var'), opt = struct(); end + + def.debug = 0; % debugging output vs. memory optimization + def.refine = 1.8; % mesh refinement - more points more stable but slower + def.acc = 1; % larger value - more layer - more exact but slower + def.bdist = 5; % default volume + def.fsize = 10; + def.verb = 0; + def.testseggmt = 0; + def.interpBB = struct('BB',[],'interpV',1,'mati',mati,'vmati',vmati); + def.mat = []; + opt = cat_io_checkinopt(opt,def); + + if ~isempty(T) && size(S.vertices,1) ~= numel(T) + error('The number of surface vertices and datavalues has to be equal.\n'); + end + if strcmpi(type,'pp') && isempty(T) + error('Position map creation requires a thickness map T.\n'); + end + + if ~isempty(opt.mat) + vx_vol = sqrt(sum(opt.mat(1:3,1:3).^2)); + else + vx_vol = [1 1 1]; + end + opt.interpBB.interpV = vx_vol(1); + + %% save a temporary version of S and refine it + if ~strcmpi(type,'val') + if opt.verb, stime = cat_io_cmd(' Refine mesh','g5','',opt.verb); end + Praw = [tempname '.gii']; + save(gifti(struct('vertices',S.vertices,'faces',S.faces)),Praw); + cmd = sprintf('CAT_RefineMesh ""%s"" ""%s"" %0.2f',Praw,Praw,opt.refine .* mean(vx_vol)); + cat_system(cmd,opt.debug); + Sr = gifti(Praw); + delete(Praw); + end + + + %% transformation for create CS + if 0 ~isempty(opt.interpBB.mati) && ~isempty(opt.interpBB.BB) + S.vertices = S.vertices - repmat( opt.interpBB.BB([3,1,5]) - 1,size(S.vertices,1),1); % correction for boundary box + S.vertices = S.vertices ./ repmat(abs(opt.interpBB.interpV ./ opt.interpBB.mati([8,7,9])),size(S.vertices,1),1); % resolution adaptation + + vmat1 = [0 0 0]; + + if ~strcmpi(type,'val') + Sr.vertices = Sr.vertices - repmat( opt.interpBB.BB([3,1,5]) - 1,size(Sr.vertices,1),1); % correction for boundary box + Sr.vertices = Sr.vertices ./ repmat(abs(opt.interpBB.interpV ./ opt.interpBB.mati([8,7,9])),size(Sr.vertices,1),1); % resolution adaptation + end + elseif ~isempty(opt.mat) + S = cat_surf_mat(S,opt.mat,1); + end + %% + if isempty(Y) + Y = ones( round(max(S.vertices,[],1) - min(S.vertices)) + opt.bdist*2 ,'single'); + vmat1 = -[min(S.vertices(:,1)) min(S.vertices(:,2)) min(S.vertices(:,3))] + opt.bdist; + vmat1i = repmat(min(S.vertices),size(S.vertices,1),1) - opt.bdist; + else + if sum(Y(:)) == 0, Y = Y + 1; end + + %{ + vmat1i = [0 0 0]; + vmat1 = -opt.interpBB.vmati(10:12); + + S.vertices = (opt.interpBB.vmati * [S.vertices' ; ones(1,size(S.vertices ,1))])'; + if ~strcmpi(type,'val') + Sr.vertices = (opt.interpBB.vmati * [Sr.vertices' ; ones(1,size(Sr.vertices,1))])'; + end + if opt.interpBB.vmati(7)<0, S.faces = [S.faces(:,1) S.faces(:,3) S.faces(:,2)]; end + %} + vmat1 = [0 0 0];% -opt.interpBB.vmati(10:12); + S.vertices = ([0 1 0; 1 0 0; 0 0 1] * [eye(3) vmat1'] * [S.vertices';ones(1,size(S.vertices,1))] )'; + if ~strcmpi(type,'val') + Sr.vertices = ([0 1 0; 1 0 0; 0 0 1] * [eye(3) vmat1'] * [Sr.vertices';ones(1,size(Sr.vertices,1))] )'; + end + end + + %% transfer thickness information to refined surface by volume rendering + if ~isempty(T) + if opt.verb + if exist('stime','var') + stime = cat_io_cmd(' Render thickness/data','g5','',opt.verb,stime); + else + stime = cat_io_cmd(' Render thickness/data','g5','',opt.verb); + end + end + Yt = nan(size(Y),'single'); + % render points + I = sub2ind(size(Y),... + max(1,min(size(Y,1),round(S.vertices(:,1) + vmat1(1)))),... + max(1,min(size(Y,2),round(S.vertices(:,2) + vmat1(2)))),... + max(1,min(size(Y,3),round(S.vertices(:,3) + vmat1(3))))); + Yt(I) = T; + if 1 % fill volume + if all(T == round(T)) + [D,I] = cat_vbdist( single( ~isnan(Yt) ) , Y>0 ); + Yt = Yt(I); + else + Yt = cat_vol_approx(Yt,1); + end + end + %T = isocolors(Yt,([0 1 0; 1 0 0; 0 0 1] * [eye(3) vmat'] * [So.vertices';ones(1,size(So.vertices,1))] )' ); % self projection + else + Yt = nan(size(Y),'single'); + end + if strcmpi(type,'val') + if (opt.verb) > 0, fprintf('%5.0fs\n',etime(clock,stime)); end + Yt = Yt .* (Y>0); + Yp = Yt; + return; + end + + + + %% smooth the normals to avoid problems with self-intersections + if opt.verb, stime = cat_io_cmd(' Smooth normals','g5','',opt.verb,stime); end + Mr = spm_mesh_smooth(Sr); + smoothsurf = @(Y,s) [ ... + spm_mesh_smooth(Mr,double(Y(:,1)),s) , ... + spm_mesh_smooth(Mr,double(Y(:,2)),s) , ... + spm_mesh_smooth(Mr,double(Y(:,3)),s) ]; + Srn = spm_mesh_normals(Sr); + Srn = smoothsurf(Srn, min(100,max(50,opt.fsize * (numel(Sr.vertices)./numel(S.vertices))^0.5 ) ) ); + Srn = Srn ./ repmat( sum(Srn.^2,2).^0.5 , 1 , 3); + + + %% render surface + if opt.verb, stime = cat_io_cmd(' Render final map','g5','',opt.verb,stime); end + switch lower(type) + case {'pve','seg','pp'} + %% render surface with PVE + ss = max(1,opt.acc + 1) / 12; + offset = -0.25 : ss : 0.75 * round(opt.refine/0.75); + % the transverse offset should include only few elements for runtime + toffset = -1/3 * round(opt.refine/1.5) : (2/3) / max(1,round(opt.refine/1.5)) : 1/3 * round(opt.refine/1.5); + Yp = zeros(size(Y),'single'); + for oi = 1:numel(offset) + % middle point + I = sub2ind(size(Y),... + max(1,min(size(Y,1),round(Sr.vertices(:,1) + Srn(:,1)*offset(oi) + vmat1(1)))),... + max(1,min(size(Y,2),round(Sr.vertices(:,2) + Srn(:,2)*offset(oi) + vmat1(2)))),... + max(1,min(size(Y,3),round(Sr.vertices(:,3) + Srn(:,3)*offset(oi) + vmat1(3))))); + % diagonal elments + if 1 + for ti1 = 1:numel(toffset) + for ti2 = 1:numel(toffset) + for ti3 = 1:numel(toffset) + I = [I; sub2ind(size(Y),... + max(1,min(size(Y,1),round(Sr.vertices(:,1) + Srn(:,1)*offset(oi) + toffset(ti1)*1/sqrt(3) + vmat1(1)))),... + max(1,min(size(Y,2),round(Sr.vertices(:,2) + Srn(:,2)*offset(oi) + toffset(ti2)*1/sqrt(3) + vmat1(2)))),... + max(1,min(size(Y,3),round(Sr.vertices(:,3) + Srn(:,3)*offset(oi) + toffset(ti3)*1/sqrt(3) + vmat1(3)))))]; + end + end + end + end + % direct neigbors + if 1 + for ti1 = 1:numel(toffset) + I = [I; sub2ind(size(Y),... + max(1,min(size(Y,1),round(Sr.vertices(:,1) + Srn(:,1)*offset(oi) + toffset(ti1) + vmat1(1)))),... + max(1,min(size(Y,2),round(Sr.vertices(:,2) + Srn(:,2)*offset(oi) + vmat1(2)))),... + max(1,min(size(Y,3),round(Sr.vertices(:,3) + Srn(:,3)*offset(oi) + vmat1(3)))))]; + end + for ti2 = 1:numel(toffset) + I = [I; sub2ind(size(Y),... + max(1,min(size(Y,1),round(Sr.vertices(:,1) + Srn(:,1)*offset(oi) + vmat1(1)))),... + max(1,min(size(Y,2),round(Sr.vertices(:,2) + Srn(:,2)*offset(oi) + toffset(ti2) + vmat1(2)))),... + max(1,min(size(Y,3),round(Sr.vertices(:,3) + Srn(:,3)*offset(oi) + vmat1(3)))))]; + end + for ti3 = 1:numel(toffset) + I = [I; sub2ind(size(Y),... + max(1,min(size(Y,1),round(Sr.vertices(:,1) + Srn(:,1)*offset(oi) + vmat1(1)))),... + max(1,min(size(Y,2),round(Sr.vertices(:,2) + Srn(:,2)*offset(oi) + vmat1(2)))),... + max(1,min(size(Y,3),round(Sr.vertices(:,3) + Srn(:,3)*offset(oi) + toffset(ti3) + vmat1(3)))))]; + end + end + % final rendering + Yp(I) = min(1, oi ./ sum( offset < 1 ) ); + end + case 'pps' + %% render percentage position map + % read thickness value from map + + Tr = isocolors(Yt,([0 1 0; 1 0 0; 0 0 1] * [eye(3) vmat1'] * [Sr.vertices';ones(1,size(Sr.vertices,1))] )' ); + %Tr = isocolors(Yt,Sr.vertices); + + % create Ypp map + ss = max(1,opt.acc - 1) / round(4 * round(mean(T))); + offset = -0.25 : ss : 0.75 ; + toffset = -1/3 * round(opt.refine/1.5) : (2/3) / max(1,round(opt.refine/1.5)) : 1/3 * round(opt.refine/1.5); + Yp = zeros(size(Y),'single'); + for oi = 1:numel(offset) + % middle point + I = sub2ind(size(Y),... + max(1,min(size(Y,1),round(Sr.vertices(:,1) + Srn(:,1)*offset(oi).* max(offset(oi)>0.5,Tr)./vx_vol(1) + vmat1(1)))),... + max(1,min(size(Y,2),round(Sr.vertices(:,2) + Srn(:,2)*offset(oi).* max(offset(oi)>0.5,Tr)./vx_vol(2) + vmat1(2)))),... + max(1,min(size(Y,3),round(Sr.vertices(:,3) + Srn(:,3)*offset(oi).* max(offset(oi)>0.5,Tr)./vx_vol(3) + vmat1(3))))); + % diagonal elments + if 1 + for ti1 = 1:numel(toffset) + for ti2 = 1:numel(toffset) + for ti3 = 1:numel(toffset) + I = [I; sub2ind(size(Y),... + max(1,min(size(Y,1),round(Sr.vertices(:,1) + Srn(:,1)*offset(oi).* max(offset(oi)>0.5,Tr)./opt.interpBB.interpV + toffset(ti1)*1/sqrt(3) + vmat1(1)))),... + max(1,min(size(Y,2),round(Sr.vertices(:,2) + Srn(:,2)*offset(oi).* max(offset(oi)>0.5,Tr)./opt.interpBB.interpV + toffset(ti2)*1/sqrt(3) + vmat1(2)))),... + max(1,min(size(Y,3),round(Sr.vertices(:,3) + Srn(:,3)*offset(oi).* max(offset(oi)>0.5,Tr)./opt.interpBB.interpV + toffset(ti3)*1/sqrt(3) + vmat1(3)))))]; + end + end + end + end + % direct neigbors + if 1 + for ti1 = 1:numel(toffset) + I = [I; sub2ind(size(Y),... + max(1,min(size(Y,1),round(Sr.vertices(:,1) + Srn(:,1)*offset(oi).* max(offset(oi)>0.5,Tr)./vx_vol(1) + toffset(ti1) + vmat1(1)))),... + max(1,min(size(Y,2),round(Sr.vertices(:,2) + Srn(:,2)*offset(oi).* max(offset(oi)>0.5,Tr)./vx_vol(1) + vmat1(2)))),... + max(1,min(size(Y,3),round(Sr.vertices(:,3) + Srn(:,3)*offset(oi).* max(offset(oi)>0.5,Tr)./opt.interpBB.interpV + vmat1(3)))))]; + end + for ti2 = 1:numel(toffset) + I = [I; sub2ind(size(Y),... + max(1,min(size(Y,1),round(Sr.vertices(:,1) + Srn(:,1)*offset(oi).* max(offset(oi)>0.5,Tr)./opt.interpBB.interpV + vmat1(1)))),... + max(1,min(size(Y,2),round(Sr.vertices(:,2) + Srn(:,2)*offset(oi).* max(offset(oi)>0.5,Tr)./opt.interpBB.interpV + toffset(ti2) + vmat1(2)))),... + max(1,min(size(Y,3),round(Sr.vertices(:,3) + Srn(:,3)*offset(oi).* max(offset(oi)>0.5,Tr)./opt.interpBB.interpV + vmat1(3)))))]; + end + for ti3 = 1:numel(toffset) + I = [I; sub2ind(size(Y),... + max(1,min(size(Y,1),round(Sr.vertices(:,1) + Srn(:,1)*offset(oi).* max(offset(oi)>0.5,Tr)./opt.interpBB.interpV + vmat1(1)))),... + max(1,min(size(Y,2),round(Sr.vertices(:,2) + Srn(:,2)*offset(oi).* max(offset(oi)>0.5,Tr)./opt.interpBB.interpV + vmat1(2)))),... + max(1,min(size(Y,3),round(Sr.vertices(:,3) + Srn(:,3)*offset(oi).* max(offset(oi)>0.5,Tr)./opt.interpBB.interpV + toffset(ti3) + vmat1(3)))))]; + end + end + + Yp(I) = min( 1, oi./ sum( offset <= 0.5 ) ); + + + end + Yp = cat_vol_median3(Yp,smooth3(Yp>0 & Yp<1)>0.2,Yp>0,0.05); + Yps = cat_vol_localstat(Yp,Yp>0 & Yp<1,1,1); Ypsw = min(1,smooth3(cat_vol_morph(Yps>0,'e'))*2); + Yp = Yp .* (1 - Ypsw) + Ypsw .* Yps; clear Yps Ypsw; + end + + % filling + Yp0 = Yp; + for fi=1:2 + if sum( abs( Yp0(:) - Yp(:) ) ) / sum( Yp0(:) ) < 0.1 + Yp(~cat_vol_morph( cat_vol_morph( Yp<(1-0.2*fi) ,'o',fi), 'l',[0.2 2]) & Yp==0 ) = 1; + end + end + clear Yp0; + % final filtering + Yp = cat_vol_median3(Yp,smooth3(Yp>0 & Yp<1)>0.2,Yp>0,0.05); + + + + %% create segment map + switch lower(type) + case 'pp' + %% distance map for PVE + % optimized for real Ypp map + Yd = cat_vbdist( 1 - Yp ) - cat_vbdist( Yp , cat_vol_morph( Y , 'd', 2) ); + Yd(Yd<0) = Yd(Yd<0) + 0.5; % use correction + Yd(Yd>0) = Yd(Yd>0) - 0.5; + Yd = Yd * opt.interpBB.interpV; + + % create final segmentation + Yp = max(0,min(1,(Yd + Yt/2) ./ Yt)); + + Yp = cat_vol_median3(Yp,smooth3(Yp>0 & Yp<1)>0.2,Yp>0,0.05); + Yps = cat_vol_localstat(Yp,Yp>0 & Yp<1,1,1); Ypsw = min(1,smooth3(cat_vol_morph(Yps>0,'e'))*2); + Yp = Yp .* (1 - Ypsw/2) + Ypsw/2 .* Yps; clear Yps Ypsw; + case 'seg' + %% distance map for PVE + % optimized for thickness error + Yd = cat_vbdist( 1 - Yp ) - cat_vbdist( Yp , cat_vol_morph( Y , 'd', 2) ); + Yd(Yd<0) = Yd(Yd<0) + 0.0; % no correction + Yd(Yd>0) = Yd(Yd>0) - 0.0; + Yd = Yd * opt.interpBB.interpV; + + % create CSF background + [Yb,red] = cat_vol_resize(Yp,'reduceV',opt.interpBB.interpV,2,8,'meanm'); + Yb = cat_vol_morph( Yb>0 ,'ldc',16); + Yb = cat_vol_resize(Yb,'dereduceV',red); + Yb = Yb | cat_vol_morph( Yp , 'd' ,2 ); + + % create final segmentation + Yp = Yb + max(0,min(1, (Yd + Yt / 2) / opt.interpBB.interpV ) ) + max(0,min(1,(Yd - Yt / 2) / opt.interpBB.interpV ) ); + + if opt.testseggmt + %% test rendering + stime = cat_io_cmd(' Test segment map','g5','',opt.verb,stime); + Ycd = cat_vbdist( 2 - Yp , Yp<2.5 ); + Ywd = cat_vbdist( Yp - 2 , Yp>1.5 ); + Ygmt = (Ywd + Ycd) * opt.interpBB.interpV; Ygmt(Ygmt>1000) = 0; + Ypbt = min(Ywd + Ycd,cat_vol_pbtp(Yp,Ywd,Ycd)) * opt.interpBB.interpV; Ypbt(Ypbt>1000) = 0; + + % values + rms = @(x) mean( x.^2 ) .^ 0.5; + Tgmt = cat_surf_isocolors2(Ygmt, ([0 1 0; 1 0 0; 0 0 1] * [eye(3) vmat1'] * [S.vertices';ones(1,size(S.vertices,1))] )' ); + Tpbt = cat_surf_isocolors2(Ypbt, ([0 1 0; 1 0 0; 0 0 1] * [eye(3) vmat1'] * [S.vertices';ones(1,size(S.vertices,1))] )' ); + + fprintf('\n T_surf: %0.2f%s%0.2f (md=%0.2f)\n',mean(T),native2unicode(177, 'latin1'),std(T),median(T)); + fprintf(' T_direct: %0.2f%s%0.2f (md=%0.2f, RMSE=%0.2f)\n',... + mean(Ygmt(Ygmt(:)>0)),native2unicode(177, 'latin1'),std(Ygmt(Ygmt(:)>0)),median(Ygmt(Ygmt(:)>0)),rms(T - Tgmt)); + fprintf(' T_pbtfast %0.2f%s%0.2f (md=%0.2f, RMSE=%0.2f)\n',... + mean(Ypbt(Ypbt(:)>0)),native2unicode(177, 'latin1'),std(Ypbt(Ypbt(:)>0)),median(Ypbt(Ypbt(:)>0)),rms(T - Tpbt)); + cat_io_cmd(' ','g5','',opt.verb); + end + end + + if exist('Yt','var') + Yt = Yt .* (Y>0); + end + if opt.verb + fprintf('%5.0fs\n',etime(clock,stime)); + cat_io_cmd(' ','g5','',opt.verb); + fprintf('%5.0fs\n',etime(clock,ftime)); + end +end + +function [V,vmat,vmati] = cat_surf_surf2vol_old(S,opt) +%% render inner surface area +% Render the volume V with V==1 within the surface. +% Use type=1 to render also the surface area with 0.5. +% The transformation imat to create +% SH.vertices = [SH.vertices(:,2) SH.vertices(:,1) SH.vertices(:,3)]; % matlab flip +% SH.vertices = SH.vertices + imat; + + if ~exist('opt','var'), opt = struct(); end + def.debug = 0; % debugging output vs. memory optimization + def.pve = 1; % 0 - no PVE; 1 - PVE; 1 - PP with thickness (opt.T) + % 2 - fill with surface texture values without interpolation and masking (==4) + % 3 - fill with surface texture values with interpolation and masking (==5) + def.refine = 0.6; + def.bdist = 5; + def.mat = []; + def.res = 1; % not yet ... + + opt = cat_io_checkinopt(opt,def); + + % save a temporary version of S and refine it + if 1 + + Praw = [tempname '.gii']; + save(gifti(struct('vertices',S.vertices,'faces',S.faces)),Praw); + + cmd = sprintf('CAT_RefineMesh ""%s"" ""%s"" %0.2f',Praw,Praw,opt.refine .* opt.interpBB.interpV); + cat_system(cmd,opt.debug); + + So = S; S = gifti(Praw); + delete(Praw); + else + So = S; + end + + if ~isempty(opt.mat) + S = cat_surf_mat(S,mat); + end + + + %% render surface points + if ( isfield(opt,'V') || isfield(opt,'sizeV') ) && isfield(opt,'vmati') + if isfield(opt,'V') + V = single(opt.V); + else + V = zeros(opt.sizeV,'single'); + end + + vmati = [0 0 0]; + vmat = -opt.vmati(10:12); + + S.vertices = (opt.vmati * [S.vertices' ; ones(1,size(S.vertices ,1))])'; + So.vertices = (opt.vmati * [So.vertices' ; ones(1,size(So.vertices,1))])'; + if opt.vmati(7)<0, S.faces = [S.faces(:,1) S.faces(:,3) S.faces(:,2)]; end + else + if opt.pve == 0 + V = false( round(max(S.vertices,[],1) - min(S.vertices)) + opt.bdist*2 ); + else + V = zeros( round(max(S.vertices,[],1) - min(S.vertices)) + opt.bdist*2 ,'single'); + end + vmat = -[min(S.vertices(:,1)) min(S.vertices(:,2)) min(S.vertices(:,3))] + opt.bdist; + vmati = repmat(min(S.vertices),size(S.vertices,1),1) - opt.bdist; + end + if opt.pve > 1 && opt.pve < 6 + % get surface data or give error + if isfield(So,'cdata') + cdata = So.cdata; + elseif isfield(So,'facevertexcdata') + cdata = So.facevertexcdata; + else + error('cat_surf_fun:cat_surf_surf2vol:No datafield for filling'); + end + + % render data + I = sub2ind(size(V),... + max(1,min(size(V,1),round(S.vertices(:,1) + vmat(1)))),... + max(1,min(size(V,2),round(S.vertices(:,2) + vmat(2)))),... + max(1,min(size(V,3),round(S.vertices(:,3) + vmat(3))))); + V(I) = 1; + V = cat_vol_morph(V,'lc',1); % closeing + + % data filling + if exist('cdata','var') + Vv = zeros( size(V) ,'single'); % same size so S and not So + I = sub2ind(size(V),... + max(1,min(size(V,1),round(So.vertices(:,1) + vmat(1)))),... + max(1,min(size(V,2),round(So.vertices(:,2) + vmat(2)))),... + max(1,min(size(V,3),round(So.vertices(:,3) + vmat(3))))); + Vv(I) = cdata; + end + if opt.pve == 2 || opt.pve == 4 + [D,I] = vbdist(single(V )); Vv = Vv(I); clear D; + if opt.pve<4 + [D,I] = vbdist(single(~V)); Vv = Vv(I); clear D, + end + else + Vv = cat_vol_approx(Vv); + end + + % final masking + if opt.pve > 3 + V = Vv .* V; + else + V = Vv; + end + clear Vv; + + elseif opt.pve == 0 + %% + I = sub2ind(size(V),... + max(1,min(size(V,1),round(S.vertices(:,1) + vmat(1)))),... + max(1,min(size(V,2),round(S.vertices(:,2) + vmat(2)))),... + max(1,min(size(V,3),round(S.vertices(:,3) + vmat(3))))); + V(I) = 1; + + V = cat_vol_morph(V,'lc',1); % closeing + V(I) = 0; % remove points of the surface + V = cat_vol_morph(V,'lab'); % final closing + elseif opt.pve == 6 + % render a nice volume + S2 = struct('faces',So.faces,'vertices',... + [max(1,min(size(V,1),round(So.vertices(:,1) + vmat(1)))),... + max(1,min(size(V,2),round(So.vertices(:,2) + vmat(2)))),... + max(1,min(size(V,3),round(So.vertices(:,3) + vmat(3))))]); + + [D,I] = cat_surf_vdist(S2,V,V>0); + D = D * opt.interpBB.interpV; + + YT = zeros(size(V),'single'); + YT( I>0 ) = opt.T( I( I>0 )); + YT = cat_vol_localstat(YT,YT>0,2,1); + + %% + % refinement did not work and is also computation stupid and slow + %[D2,I2] = cat_surf_vdist(S2,V>0 & D<2,V>0 & D<2,struct('res',1)); + %I(V>0 & D<2) = I2(V>0 & D<2); D(V>0 & D<2) = D2(V>0 & D<2); + + % % das geht natuer nach dem refinement nicht ... + +% opt.res + if isfield(opt,'T') + V = max(0,min(1, (D + T(I)/2) / T(I) )); + else + V = max(0,min(1, D + 0.5 )); + end + + else %if opt.pve == 1 + %% fast PVE estimation by rendering multiple layer + + + %% part 1 .. render one surface with simple PVE + + % smooth the normals to avoid problems with self-intersections + M = spm_mesh_smooth(S); + smoothsurf = @(V,s) [ ... + spm_mesh_smooth(M,double(V(:,1)),s) , ... + spm_mesh_smooth(M,double(V(:,2)),s) , ... + spm_mesh_smooth(M,double(V(:,3)),s) ]; + Sn = spm_mesh_normals(S); + Sn = smoothsurf(Sn,100); + + % render surface + offset = -0.25:0.1:1; + V=0*V; + for oi = 1:numel(offset) + I = sub2ind(size(V),... + max(1,min(size(V,1),round(S.vertices(:,1) + Sn(:,1)*offset(oi) + vmat(1)))),... + max(1,min(size(V,2),round(S.vertices(:,2) + Sn(:,2)*offset(oi) + vmat(2)))),... + max(1,min(size(V,3),round(S.vertices(:,3) + Sn(:,3)*offset(oi) + vmat(3))))); + V(I) = min(1,max( V(I) , oi./sum(offset<1))); + end + V(~cat_vol_morph( V<1, 'l',[0.2 2]) & V==0 ) = 1; % closing + + + + %% part 2 .. surf2vol2surf + Yt = zeros(size(V),'single'); + I = sub2ind(size(V),... + max(1,min(size(V,1),round(So.vertices(:,1) + vmat(1)))),... + max(1,min(size(V,2),round(So.vertices(:,2) + vmat(2)))),... + max(1,min(size(V,3),round(So.vertices(:,3) + vmat(3))))); + Yt(I) = opt.T; + Yt = cat_vol_approx(Yt,1); + + %T = isocolors(Yt,([0 1 0; 1 0 0; 0 0 1] * [eye(3) vmat'] * [So.vertices';ones(1,size(So.vertices,1))] )' ); % self projection + T = isocolors(Yt,([0 1 0; 1 0 0; 0 0 1] * [eye(3) vmat'] * [S.vertices';ones(1,size(S.vertices,1))] )' ); + + %% create Ypp map + offset = [-0.5:0.05:0.5 0.75:0.25:1]; + Vp=0*V; + for oi = 1:numel(offset) + I = sub2ind(size(V),... + max(1,min(size(V,1),round(S.vertices(:,1) + Sn(:,1).*offset(oi) .* T./opt.interpBB.interpV + vmat(1)))),... + max(1,min(size(V,2),round(S.vertices(:,2) + Sn(:,2).*offset(oi) .* T./opt.interpBB.interpV + vmat(2)))),... + max(1,min(size(V,3),round(S.vertices(:,3) + Sn(:,3).*offset(oi) .* T./opt.interpBB.interpV + vmat(3))))); + Vp(I) = min( 1.5, max( Vp(I) , offset(oi) + 0.5 )); + end + Vp(~cat_vol_morph( Vp<1, 'l',[0.2 2]) & Vp==0 ) = 1; + Vp(cat_vol_morph( Vp>1.2, 'lc',1) & Vp==0 ) = 1; + Vp(cat_vol_morph( Vp>=1, 'lc',0) & Vp>0) = 1; + Vp = min(1,Vp); + end + + %% + %SH = isosurface(V,0.6); % create hull + %SH.vertices = [SH.vertices(:,2) SH.vertices(:,1) SH.vertices(:,3)]; % matlab flip + %SH.vertices = SH.vertices + repmat(min(S.vertices),size(SH.vertices,1),1) - 5; +end + +function alpha = cat_surf_edgeangle(N1,N2) +%cat_surf_fun>cat_surf_edgeangle Estimate angle between two vectors. +% +% alpha = cat_surf_edgeangle(N1,N2) +% ________________________________________________________________________ +% Robert Dahnke 201909 + + if 1 % fast version + alpha = acosd( dot(N1,N2,2) ./ ( sum(N1.^2,2).^.5 .* sum(N2.^2,2).^.5 )); + else + %% + alpha = zeros(size(N1,1),1,'single'); + for i=1:size(N1,1) + a = N1(i,:); b = N2(i,:); + alpha(i) = acosd( dot(a,b) / (norm(a) * norm(b)) ); + end + end +end + +function N = cat_surf_normals(S) +%cat_surf_normals Surface normals. +% Vertex normals of a triangulated mesh, area weighted, left-hand-rule +% N = patchnormals(FV) - struct with fields, faces Nx3 and vertices Mx3 +% N: vertex normals as Mx3 +% +% https://de.mathworks.com/matlabcentral/fileexchange/24330-patch-normals +% by Dirk-Jan Kroon +% +% See also spm_mesh_normals. +% ________________________________________________________________________ +% Dirk-Jan Kroon, Robert Dahnke, 2019 + +% Well, I now use spm_mesh_normals, but maybe we need it some day. + + % face corners index + A = S.faces(:,1); + B = S.faces(:,2); + C = S.faces(:,3); + + % face normals + n = cross(S.vertices(A,:)-S.vertices(B,:),S.vertices(C,:)-S.vertices(A,:)); %area weighted + + % vertice normals + N = zeros(size(S.vertices)); % init vertex normals + for i = 1:size(S.faces,1) % step through faces (a vertex can be reference any number of times) + N(A(i),:) = N(A(i),:) + n(i,:); % sum face normals + N(B(i),:) = N(B(i),:) + n(i,:); + N(C(i),:) = N(C(i),:) + n(i,:); + end + + % normalize + Ns = sum(N.^2,2).^.5; + N = N ./ repmat(Ns,1,3); +end + +function S = cat_surf_mat(S,mat,invers,nin) +%cat_surf_fun>cat_surf_mat +% Apply transformation matrix mat to a surface structure S. +% +% S = cat_surf_fun('smat',S,mat[,inv,nin]) +% S = cat_surf_mat(S,mat[,inv,nin]) +% +% S .. surface structure with vertices and faces +% mat .. tranformation matrix +% if empty only check for vertex inversion +% invers .. apply invers transformation (default = 0) +% nin .. set normal direction pointing to the inside (default = 1) +% +% Used in cat_surf_createCS. +% +% See also spm_mesh_transform. +% ------------------------------------------------------------------------ +% Robert Dahnke 201911 + + if ~exist('invers','var'), invers = 0; end + if ~exist('nin','var'), nin = 1; end + if ~exist('mat','var'), error('cat_surf_fun:cat_surf_mat:incompleteInput','Need transformation matrix as input!'); end + + if ~isempty(mat) + if isnumeric(S) + % only vertices + if invers + S = ( inv( mat ) * [S' ; ones(1,size(S,1))])'; + else + S = ( mat * [S' ; ones(1,size(S,1))])'; + end + S(:,4) = []; + else %if isstruct(S) % surface + if invers + S.vertices = ( inv( mat ) * [S.vertices' ; ones(1,size(S.vertices,1))])'; + else + S.vertices = ( mat * [S.vertices' ; ones(1,size(S.vertices,1))])'; + end + S.vertices(:,4) = []; + end + end + + % estimate the orientation of the surface by adding the normals and + % testing which directions makes the surface great again :D + if isstruct(S) + N = spm_mesh_normals(S); + CSnin = mean( abs(S.vertices(:) - N(:) ) ) > mean( abs(S.vertices(:) + N(:) ) ); + + % flip faces if normals point into the wrong direction + if ( nin && ~CSnin ) || ( ~nin && CSnin ) + S.faces = [S.faces(:,1) S.faces(:,3) S.faces(:,2)]; + end + end +end + +function I = cat_surf_isocolors2(V,Y,mat,interp) +%cat_surf_fun>cat_surf_isocolors2 Map volume data to surface. +% Calculates an interpolated value of a vertex V in Y. +% +% I = cat_surf_isocolors2(V,Y,mat,interp) +% +% I .. facevertexcdata +% V .. vertices or surface struct +% mat .. transformation matrix +% interp .. interpolation type ('nearest','linear) +% +% See also isocolors, spm_mesh_project. +% _____________________________________________________________________ +% Robert Dahnke, 2009-2019 + + if isempty(Y), return; end + if ~isnumeric(V) && isfield(V,'vertices'), SV = V; V = V.vertices; end + if ~isnumeric(Y) && isfield(Y,'vertices'), SY = Y; Y = Y.vertices; end + if ~ismatrix(V) && ndims(Y)~=3, VR = Y; Y = V; V = VR; end; clear VR % flip + if ndims(Y)~=3, error('MATLAB:isocolor2:dimsY','Only 2 or 3 dimensional input of Y.'); end + if ~exist('interp','var'); interp = 'linear'; end + + if isa(V,'double'), V = single(V); end + if isnumeric(Y) + if ~isa(Y,'double') + Y = double(Y); + YD = 0; + else + YD = 1; + end + else + Ygii = Y; clear V + Y = single(Ygii.vertices); + YD = 0; + end + + + % inverse transformation of the given mat + if exist('mat','var') && ~isempty(mat) + V = cat_surf_mat(V,mat,1); + end + + + nV = size(V,1); + ndim = size(V,2); + + + % We have to process everything with double, thus larger images will cause memory issues. + switch interp + case 'nearest' + sY = [size(Y,2) size(Y,1) size(Y,3)]; % flipped limit + V = max(1,min(round(V),repmat(sY,nV,1))); + I = Y( max(1,min(numel(Y), sub2ind(size(Y),V(:,2),V(:,1),V(:,3))))); % flipped vertices + case {'pushWSsum','pushWSmean','pushmax','pushsum','pushw','pushmean'} + %% map all non-NaN voxel to the surface + + % find voxels for mapping + switch interp + case 'pushWSsum' + otherwise + voxi = find(isnan(Y)==0); + [vox(:,2),vox(:,1),vox(:,3)] = ind2sub(size(Y),voxi); + end + + % estimate nearest neighbor mapping (push of each voxel) + V = double(V); + T = delaunayn(V); + %[VI,SD] = dsearchn(double(V),T,vox); +%% + I = nan(size(V,1),1); + switch interp + case {'pushWSsum','pushWSmean'} + % A) Cluster first and map the whole region to one voxel + % (*) add local smoothing + % (*) limit size of the cluster ?! But how? + % >> structural separation by sulcal/gyral skeleton? + % (*) extract local surface of the cluster and + % extract the largest component + % create new mapping of the whole cluster to this component + % (*) cluster mapping only for large structures? + % extract minima and maxima + % + % Problems: + % - Mapping error of missing (broken) structures with huge miss-mapping + % - ""Overmapping"" to peak structures (a skyscraber get all views) + % and that can change the whole picture (= instable) + % >> futher differentitiation or cluster limitation is needed ! + % + % (C) Mapping via simpler surfaces with later refinement or + % Mixed mapping ? + % + % - use tissue segmentation to limit Y + if 1 + Yd = -cat_vol_div(smooth3(Y),1,2); + Yd( cat_vol_morph( smooth3(abs(Yd))<0.01) ) = 0; + else + Yd = Y; Yd(isnan(Yd)) = 0; + end + % watershed segmentation/partitioning + if exist('watershed','var') + Yw = watershed(-Yd); %<-0.001); + % remove unwanted (superlarge) clusters + Yw(isnan(Y) | Yd==0) = 0; + else + %% normalize map to find local peaks + Yw = Y ./ max(0.1,cat_vol_smooth3X(log(abs(Y)+1),2)); + [Yw,th] = cat_stat_histth(Yw,95); Yw = Yw ./ max(abs(th)); + Yd = -cat_vol_div(abs(Yw),1,1,1); + [Yd,th] = cat_stat_histth(Yd,99); Yd = Yd ./ max(abs(th)); + Yw = abs(Yd) .* abs(Yw); + % + Yw(isnan(Y)) = nan; + Yl = spm_bwlabel(double(Yw>0.95)); + Yw = cat_vol_downcut(single(Yl),abs(single(Yw)),-0.4); Yw = cat_vol_median3c(Yw,~isnan(Y)); Yw(isnan(Y)) = nan; + Yw = cat_vol_downcut(single(Yw),abs(single(Yw)),-0.2); Yw = cat_vol_median3c(Yw,~isnan(Y)); Yw(isnan(Y)) = nan; + Yw = cat_vol_downcut(single(Yw),abs(single(Yw)),-0.1); Yw = cat_vol_median3c(Yw,~isnan(Y)); Yw(isnan(Y)) = nan; + end + + + %% remove mini clusters (better to use the direct projection) + if 1 + [whst,wind] = hist(single(Yw(Yw(:)>0)),1:single(max(Yw(:)))); + wind(whst > 3^3) = []; + for wi = 1:numel(wind) + Yw(Yw==wind(wi)) = 0; + end + end + + %% map cluster to surface + Scluster = cat_surf_fun('isocolors',SV,Yw,[],'nearest'); + Sdata = cat_surf_fun('isocolors',SV,Y ,[],'nearest'); + + % for cluster + + SV.facevertexcdata = Scluster; + + %% map 0-values (direct projection via push) + if 1 + voxi = find(isnan(Y)==0 & Yw==0); clear vox; + [vox(:,2),vox(:,1),vox(:,3)] = ind2sub(size(Y),voxi); + + I = nan(size(V,1),1); + [VI,SD] = dsearchn(V,T,vox); + + for vi = 1:numel(VI) + if isnan(I(VI(vi))) + I(VI(vi)) = Y(voxi(vi)) .* 10./SD(vi); + else + I(VI(vi)) = I(VI(vi)) + Y(voxi(vi)) .* 10./SD(vi); + end + end + end + + + %% there should be some general limit vom a center point + for wi = setxor( 1:max(single(Yw(:))) , single(wind) ) + th = 0.1 * max(Y(Yw(:)==wi)); + if ~isempty(th) && sum(Yw(:)==wi & Y(:)>=th)>0 + %% + if 0 + voxi = find(Yw==wi & Y>=th); clear vox; + [vox(:,2),vox(:,1),vox(:,3)] = ind2sub(size(Y),voxi); + [VIwi,SD] = dsearchn(V,T,vox); + + [VThst,VTind] = hist(VIwi,min(VIwi(:)):max(VIwi(:))); + [VThstmax,VThstind] = max(VThst); + VIwimax = VTind(VThstind); + + I(VIwimax) = sum( Y(Yw(:)==wi) ); + else + voxi = find(Yw==wi & Y>=th); clear vox; + [vox(:,2),vox(:,1),vox(:,3)] = ind2sub(size(Y),voxi); + + + + [VIwi,SD] = dsearchn(V,T,vox); + + + end + end + end + + case 'pushsum' % for fMRI + I = zeros(size(V,1),1,'single'); + [VI,SD] = dsearchn(V,T,vox); + + for vi = 1:numel(VI) + if isnan(I(VI(vi))) + I(VI(vi)) = Y(voxi(vi)) .* min(1,1./SD(vi)); + else + I(VI(vi)) = I(VI(vi)) + Y(voxi(vi)) .* min(1,1./SD(vi)); + end + end + case 'pushmax' + for vi = 1:numel(vox) + if ~isnan(I(VI(vi))) + I(VI(vi)) = max(I(VI(vi)),vox(vi)); + else + I(VI(vi)) = vox(vi); + end + end + case 'pushmean' + I = nan(size(V,1),1,'single'); + N = zeros(size(V,1),1,'single'); + [VI,SD] = dsearchn(V,T,vox); SD=SD*6; + + for vi = 1:numel(VI) + if isnan(I(VI(vi))) + I(VI(vi)) = Y(voxi(vi)) .* min(1,1./SD(vi)); + N(VI(vi)) = min(1,1./SD(vi)); + else + I(VI(vi)) = I(VI(vi)) + Y(voxi(vi)) .* min(1,1./SD(vi)); + N(VI(vi)) = N(VI(vi)) + min(1,1./SD(vi)); + end + end + I = I ./ max(1,N); + end + + % question of smoothing & interpolation + % I(isnan(I)) = 0; + + + + case 'linear' + nb = repmat(shiftdim(double([0 0 0;0 0 1;0 1 0;0 1 1;1 0 0;1 0 1;1 1 0;1 1 1]'),-1),nV,1); + enb = repmat(shiftdim((ones(8,1,'double')*[size(Y,2),size(Y,1),size(Y,3)])',-1),nV,1); + + % calculate the weight of a neigbor (volume of the other corner) and + w8b = reshape(repmat(V,1,2^ndim),[nV,ndim,2^ndim]); clear V; + % if the streamline is near the boundary of the image you could be out of range if you add 1 + n8b = min(floor(w8b) + nb,enb); clear enb + n8b = max(n8b,1); + + % sometimes flip is not allowed for single types + w8b = double(w8b); + n8b = double(n8b); + w8b = flip(prod(abs(n8b - w8b),2),3); + + % multiply this with the intensity value of R + I = sum( Y( max(1,min(numel(Y), sub2ind(size(Y),n8b(:,2,:),n8b(:,1,:),n8b(:,3,:))))) .* w8b,3); + end + if ~YD, I = single(I); end +end +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_surf_scaling.m",".m","6068","155","function rn = cat_surf_scaling(job) +%cat_surf_scaling: scaling to normalize surfaces by spherical properties. +% The function was developed to normalize surfaces for surface complexity +% measures that use absolute parameters such as the size of spheres for +% morphological closing (e.g., classical GI like Schaer's GI) or helping +% spheres (e.g., toroGI). +% However, scaling is just a technical element of obtain more comparable +% measurements but it allows no correction of biological aspects and the +% TIV still has to be a confound in analyses! +% There are multiple scaling options (for tests) available but the use of +% the 3d hull (norm=31 that is also the default) should most accurate and +% robust because the hull is closer to the TIV and is less effected by +% individual changes, e.g., the enlarged of ventricles will also effect +% the cortical surfaces. Vertices may depend strongly on the sampling. +% +% +% rn = cat_surf_scaling(job) +% +% rn .. linear scaling factor +% job .. SPM job structure +% .file .. input file +% .norm .. scaling option +% 12 - affine (not tested yet) +% 1 - 1d +% 11 - 1d hull +% 2 - 2d area +% 21 - 2d hull area +% 30 - 3d volume +% 31 - 3d hull volume (default) +% .fname .. outpout file name +% .fname2 .. second output for tests +% +% TODO: +% - RD202005 - inoptimal hull defintion: +% Currently the hull definition based on a approach that renders the +% surface and used closing. This could probably replaced by the real +% mathematical hull (at least as previous scaling). +% - RD202006 - inoptimal hull defintion 2: +% Another problem is that the process strongly depend on the used +% object - typically the left or right hemishpere but what happen +% if we use the cerbellum? +% > So it is maybe better to use left and right but nothing more for +% scaling? +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + + + def.file = {}; + def.norm = 31; + def.fname = {}; + def.fname2 = {}; % just for tests + job = cat_io_checkinopt(job,def); + + [pp,ff] = spm_fileparts(job.file); + + warning('off','MATLAB:subscripting:noSubscriptsSpecified'); + S = export(gifti( job.file ), 'patch'); + + if job.norm == 0 + r = 60; + elseif job.norm == 12 % affine + % RD20200211 - get XML information for affine normalization? + if strcmp(pp(end-3:end),'surf') + reportdir = [pp(1:end-4) strrep(pp(end-3:end),'surf','report')]; + else + reportdir = pp; + end + Pxml = fullfile( reportdir , cat_io_strrep( ['cat_' ff '.xml' ],{'lh.central.','rh.central.','cb.central.'},'') ); + + X = cat_io_xml( Pxml ); + mati = spm_imatrix( X.parameter.spm.Affine ) .* [0 0 0 0 0 0 1 1 1 0 0 0] - [ min( S.vertices )*1.1 0 0 0 0 0 0 0 0 0] ; + mat = spm_matrix(mati); + + vertices = mat * ([ S.vertices , ones( size(S.vertices,1) , 1) ])'; + vertices = vertices(1:3,:)'; + + elseif job.norm == 1 || job.norm == 11 + % normalization as distance of all vertices to the center of mass (COM) + % or to the vertices of the hull + if job.norm == 1 + COM = mean(S.vertices); + else % hull + hf = convhulln(double(S.vertices)); + COM = mean(S.vertices(unique( hf) ,:)); + end + DCOM = sum((S.vertices - repmat( COM , size(S.vertices,1), 1)).^2,2).^0.5; clear COM; + r = mean(DCOM); clear DCOM; + + elseif job.norm == 2 || job.norm == 21 + % normalization by the surface area + if job.norm == 2 + SA = cat_surf_fun('area',S); + else + hf = convhulln(double(S.vertices)); + SH = struct('vertices',S.vertices,'faces',hf); + SA = cat_surf_fun('area',SH); + end + r = sqrt( sum(SA) / (4 * pi) ); clear SA, % A_sphere = 4 * pi * r^2 + + elseif job.norm == 3 + vol = spm_mesh_utils('volume',struct('vertices',S.vertices,'faces',double(S.faces))); + r = ( vol / (4/3 * pi) )^(1/3); clear vol; % V_sphere = 4/3 * pi * r^3 + + elseif job.norm == 31 + % normalization by hull volume + [hf,vol] = convhulln(double(S.vertices)); clear hf; %#ok + r = ( vol / (4/3 * pi) )^(1/3); clear vol; % V_sphere = 4/3 * pi * r^3 + + elseif job.norm == 32 + % normalization by volumebased TIV + % RD20200211 - get XML information for affine normalization? + if strcmp(pp(end-3:end),'surf') + reportdir = [pp(1:end-4) strrep(pp(end-3:end),'surf','report')]; + else + reportdir = pp; + end + Pxml = fullfile( reportdir , cat_io_strrep( ['cat_' ff '.xml' ],{'lh.central.','rh.central.','cb.central.'},'') ); + + X = cat_io_xml( Pxml ); + r = X; + rn = 60/r; + end + + if job.norm == 12 + else + rn = 60/abs(r); + vertices = S.vertices * rn; + end + + % write data + if ~isempty(job.fname) + if exist([job.fname(1:end-3),'dat'],'file'), delete([job.fname(1:end-3),'dat']); end + save( gifti(struct('faces',S.faces,'vertices',vertices)) ,job.fname,'Base64Binary'); + end + if ~isempty(job.fname2) + if exist([job.fname2(1:end-3),'dat'],'file'), delete([job.fname2(1:end-3),'dat']); end + save( gifti(struct('faces',S.faces,'vertices',vertices2)),job.fname2,'Base64Binary'); + end + + % just a block of warnings for extrem normalization factors + if rn<0.25 || rn>4.00 + cat_io_cprintf('err' ,sprintf(['cat_surf_scale:smallSurface:Warning the normalisation factor is quite ' ... + 'low (%0.2f), check for possible sampling artifcats in Toro''s GI.\n'],rn)); + elseif rn<0.50 || rn>2.00 + cat_io_cprintf('warn',sprintf(['cat_surf_scale:largeSurface:Warning the normalisation factor is quite ' ... + 'high (%0.2f), check for possible (ocipital) boundary artifacts in Toro''s GI.\n'],rn)); + end +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_vol_qa201901.m",".m","43792","1021","function varargout = cat_vol_qa201901(action,varargin) +% CAT Preprocessing T1 Quality Control +% ______________________________________________________________________ +% +% Estimation of image quality measures like noise, inhomogeneity, +% contrast, resolution, etc. and scaling for school marks. +% +% [QAS,QAM] = cat_vol_qa201901(action,varargin) +% +% +% 1) Use GUI interface to choose segmentation and automatic setting of +% original and modified image (if available) +% [QAS,QAM] = cat_vol_qa201901() = cat_vol_qa201901('p0') +% +% [QAS,QAM] = cat_vol_qa201901('p0'[,opt]) - p0 class image +% [QAS,QAM] = cat_vol_qa201901('p#'[,opt]) - p1,p2,p3 class images +% [QAS,QAM] = cat_vol_qa201901('c#'[,opt]) - c1,c2,c3 class images +% [QAS,QAM] = cat_vol_qa201901('*#'[,opt]) - csf,gm,wm class images +% [QAS,QAM] = cat_vol_qa201901('p0',Pp0[,opt]) - no GUI call +% [QAS,QAM] = cat_vol_qa201901('p#',Pp1,Pp2,Pp3,[,opt]) - no GUI call +% [QAS,QAM] = cat_vol_qa201901('c#',Pc1,Pc2,Pc3,[,opt]) - no GUI call +% [QAS,QAM] = cat_vol_qa201901('c#',Pcsf,Pgm,Pwm,[,opt]) - no GUI call +% +% +% 2) Use GUI interface to choose all images like for other segmentations +% and modalities with a similar focus of CSF, GM, and WM tissue +% contrast such as PD, T2, or FLASH. +% [QAS,QAM] = cat_vol_qa201901('p0+'[,opt]) - p0 class image +% [QAS,QAM] = cat_vol_qa201901('p#+'[,opt]) - p1,p2,p3 class images +% [QAS,QAM] = cat_vol_qa201901('c#+'[,opt]) - c1,c2,c3 class images +% [QAS,QAM] = cat_vol_qa201901('*#+'[,opt]) - csf,gm,wm class images +% [QAS,QAM] = cat_vol_qa201901('p0+',Pp0,Po[,Pm,opt]) - no GUI call +% [QAS,QAM] = cat_vol_qa201901('p#+',Pp1,Pp2,Pp3,Po[,Pm,opt]) - no GUI call +% [QAS,QAM] = cat_vol_qa201901('c#+',Pc1,Pc2,Pc3,Po[,Pm,opt]) - no GUI call +% +% +% 3) Use GUI interface to choose all images. I.e. for other segmentations +% and modalities without focus of GM-WM contrast such as DTI MTI. +% [ not implemented yet ] +% +% +% 4) CAT12 internal preprocessing interface +% (this is the processing case that is also called in all other cases) +% [QAS,QAM] = cat_vol_qa201901('cat12',Yp0,Po,Ym,res[,opt]) +% +% +% Pp0 - segmentation files (p0*.nii) +% Po - original files (*.nii) +% Pm - modified files (m*.nii) +% Yp0 - segmentation image matrix +% Ym - modified image matrix +% +% opt = parameter structure +% opt.verb = verbose level [ 0=nothing | 1=points | 2*=times ] +% opt.redres = resolution in mm for intensity scaling [ 4* ]; +% opt.write_csv = final cms-file +% opt.write_xml = images base xml-file +% opt.sortQATm = sort QATm output +% opt.orgval = original QAM results (no marks) +% opt.recalc = +% opt.avgfactor = +% opt.prefix = prefix of xml output file (default cat_*.xml) +% +% ______________________________________________________________________ +% Robert Dahnke +% Structural Brain Mapping Group +% University Jena +% +% $Id$ +% ______________________________________________________________________ + +%#ok<*ASGLU> + + % get current release number and version + [ver_cat, rev_cat] = cat_version; + ver_cat = ver_cat(4:end); % remove leading CAT + + % init output + QAS = struct(); + QAR = struct(); + %if nargout>0, varargout = cell(1,nargout); end + + try + if strcmp(action,'cat12err') + [mrifolder, reportfolder] = cat_io_subfolders(varargin{1}.job.data,varargin{1}.job); + elseif strcmp(action,'cat12') + [mrifolder, reportfolder] = cat_io_subfolders(varargin{2},varargin{6}.job); + else + [mrifolder, reportfolder] = cat_io_subfolders(varargin{4}.catlog,varargin{6}.job); + end + catch + mrifolder = 'mri'; + reportfolder = 'report'; + end + + % no input and setting of default options + action2 = action; + if nargin==0, action='p0'; end + if isstruct(action) + if isfield(action,'model') + if isfield(action.model,'catp0') + Po = action.images; + Pp0 = action.model.catp0; + if numel(Po)~=numel(Pp0) && numel(Pp0)==1 + Pp0 = repmat(Pp0,numel(Po),1); + end + Pm = action.images; + action.data = Pp0; + end + end + if isfield(action,'data') + Pp0 = action.data; + end + action = 'p0'; + end + if nargin==3 && isstruct(varargin{2}) && isstruct(varargin{2}) + opt = cat_check('checkinopt',varargin{2},defaults); + nopt = 1; + elseif nargin==8 && isstruct(varargin{6}) && isstruct(varargin{6}) + opt = cat_check('checkinopt',varargin{6},defaults); + nopt = 1; + else + if isstruct(action2) + opt = cat_check('checkinopt',action2.opts,defaults); + else + opt = defaults; + end + nopt = 0; + end + + % for development and in the batch mode we want to call some other versions + if isfield(opt,'version') + if ~exist(opt.version,'file') + error('Selected QC version is not available! '); + elseif ~strcmp(opt.version,mfilename) + eval(sprintf('%s(action2,varargin{:})',opt.version)); + end + end + + % check input by action + switch action + case {'p0','p0+'} + % segment image cases + if nargin<=3 && ( ~exist('Pp0','var') || isempty(Pp0) ) + if (nargin-nopt)<2 + Pp0 = cellstr(spm_select(inf,'image',... + 'select p0-segment image',{},pwd,'^p0.*')); + if isempty(Pp0{1}), return; end + else + Pp0 = varargin{1}; + end + if numel(action)==2 + Po = Pp0; Pm = Pp0; + for fi=1:numel(Pp0) + [pp,ff,ee] = spm_fileparts(Pp0{fi}); + [ppa,ppb] = spm_fileparts(pp); + if strcmp(ppb,'mri'), ppo = ppa; else, ppo = pp; end + + Po{fi} = fullfile(ppo,[ff(3:end) ee]); + Pm{fi} = fullfile(pp,[opt.mprefix ff(3:end) ee]); + %Pmv{fi} = fullfile(pp,['m' ff(3:end) ee]); %#ok + %if ~exist(Pm{fi},'file') && strcmp(opt.mprefix,'nm') && exist(Pmv{fi},'file') + % fprintf('Preparing %s.\n',Pmv{fi}); + % cat_vol_sanlm(Pmv{fi},'n'); + %end + + %if ~exist(Po{fi},'file'), Po{fi}=''; end + if ~exist(Pm{fi},'file'), Pm{fi}=''; end + end + else + Po = cellstr(spm_select(repmat(numel(Pp0),1,2),... + 'image','select original image(s)',{},pwd,'.*')); + Pm = cellstr(spm_select(repmat(numel(Pp0),1,2),... + 'image','select modified image(s)',{},pwd,'.*')); + end + elseif nargin<=5 && ( ~exist('Pp0','var') || isempty(Pp0) ) + Pp0 = varargin{1}; + Po = varargin{2}; + Pm = varargin{3}; + elseif ( ~exist('Pp0','var') || isempty(Pp0) ) + error('MATLAB:cat_vol_qa201901:inputerror',... + 'Wrong number/structure of input elements!'); + end + case {'p#','c#','*#','p#+','c#+','*#+'} + % tissue class image cases + if nargin-1<=2 % GUI + if (nargin-nopt)<2 + if action(1)=='p' || action(1)=='c' + % cat/spm case + Pcsf = cellstr(spm_select(inf,'image',... + 'select p1-segment image',{},pwd,['^' action(1) '1.*'])); + if isempty(Pcsf{1}), return; end + Pgm=Pcsf; Pwm=Pcsf; + for fi=1:numel(Pcsf) + [pp,ff,ee] = spm_fileparts(Pcsf{fi}); + + Pgm{fi} = fullfile(pp,[action(1) '2' ff(3:end) ee]); + Pwm{fi} = fullfile(pp,[action(1) '3' ff(3:end) ee]); + end + else + Pcsf = cellstr(spm_select(inf,'image',... + 'select CSF segment image(s)',{},pwd,'.*')); + if isempty(Pcsf{1}), return; end + %Pgm = cellstr(spm_select(repmat(numel(Pcsf),1,2),... + % 'image','select GM segment image(s)',{},pwd,'.*')); + %Pwm = cellstr(spm_select(repmat(numel(Pcsf),1,2),... + % 'image','select WM segment image(s)',{},pwd,'.*')); + end + if numel(action)==2 + Pp0=Pcsf; Po=Pcsf; Pm=Pcsf; + for fi=1:numel(Pcsf) + [pp,ff,ee] = spm_fileparts(Pcsf{fi}); + Po{fi} = fullfile(pp,[ff(3:end) ee]); + Pm{fi} = fullfile(pp,['m' ff(3:end) ee]); + Pp0{fi} = fullfile(pp,['p0' ff(3:end) ee]); + end + else + Po = cellstr(spm_select(repmat(numel(Pcsf),1,2),... + 'image','select original image(s)',{},pwd,'.*')); + Pm = cellstr(spm_select(repmat(numel(Pcsf),1,2),... + 'image','select modified image(s)',{},pwd,'.*')); + Pp0=Pcsf; + for fi=1:numel(Pcsf) + [pp,ff,ee] = spm_fileparts(Pcsf{fi}); + Pp0{fi} = fullfile(pp,['p0' ff(3:end) ee]); + end + end + + % wie komm ich zum p0??? + else + Pp0 = varargin{1}; + end + elseif nargin==5 || nargin==6 + else + error('MATLAB:cat_vol_qa201901:inputerror',... + 'Wrong number/structure of input elements!'); + end + + Yp0 = 1; + case 'cat12err' + opt = cat_check('checkinopt',varargin{end},defaults); + case 'cat12' + % CAT12 internal input + if nargin>3 + Yp0 = varargin{1}; +% Octave is starting with many warning messages here ... +% if strcmpi(spm_check_version,'octave'), warning off; end + Vo = spm_vol(varargin{2}); +% if strcmpi(spm_check_version,'octave'), warning on; end + Yo = single(spm_read_vols(Vo)); + Ym = varargin{3}; + res = varargin{4}; + V = res.image; + species = varargin{5}; + if isfield(varargin{6},'qa') + if isfield(varargin{6}.qa,'software') && isfield(varargin{6}.qa.software,'version_segment'), QAS.software.version_segment = varargin{6}.qa.software.version_segment; end + if isfield(varargin{6}.qa,'qualitymeasures'), QAS.qualitymeasures = cat_io_updateStruct(QAS,varargin{6}.qa.qualitymeasures); end + if isfield(varargin{6}.qa,'subjectmeasures'), QAS.subjectmeasures = cat_io_updateStruct(QAS,varargin{6}.qa.subjectmeasures); end + end + if nargin>7, Pp0 = varargin{7}; end % nargin count also parameter + % opt = varargin{end} in line 96) + %opt.verb = 0; + + % reduce to original native space if it was interpolated + sz = size(Yp0); + if any(sz(1:3)~=Vo.dim(1:3)) + if isfield(Vo,'private'), Vo = rmfield(Vo,'private'); end + if isfield(Vo,'mat0'), Vo = rmfield(Vo,'mat0'); end + Vo.dat = zeros(Vo.dim,'single'); Vo.dt(1) = 16; Vo.pinfo = [1;0;0]; + + Vp0t = res.image; + if isfield(Vp0t,'private'), Vp0t = rmfield(Vp0t,'private'); end + if isfield(Vp0t,'mat0'), Vp0t = rmfield(Vp0t,'mat0'); end + Vp0t.dt(1) = 16; + Vp0t.pinfo = [1;0;0]; + Vp0t.dat = Yp0; + + % resampling and corrections of the Yp0 + % Vp0t = spm_write_vol(Vp0t,double(Yp0)); + [Vtpm,Yp0] = cat_vol_imcalc(Vp0t,Vo,'i1',struct('interp',2,'verb',0)); + rf = 50; + Yp0 = single(Yp0); + Yp0r = round(Yp0*rf)/rf; + YMR = false(size(Yp0)); + for i=1:4, YMR = YMR | (Yp0>(i-1/rf) & Yp0<(i+1/rf)); end + Yp0(YMR) = Yp0r(YMR); clear YMR Ynr; + + % resampling of the corrected image + Vp0t.dat = Ym; + [Vtpm,Ym] = cat_vol_imcalc(Vp0t,Vo,'i1',struct('interp',6,'verb',0)); + Ym = single(Ym); + end + + else + error('MATLAB:cat_vol_qa201901:inputerror',... + 'Wrong number/structure of input elements!'); + end + otherwise + error('MATLAB:cat_vol_qa201901:inputerror',... + 'Wrong number/structure of input elements!'); + end + if ~exist('species','var'), species='human'; end + + + % + % -------------------------------------------------------------------- + [QA,QMAfn] = cat_stat_marks('init'); + stime = clock; + stime2 = clock; + + + + % Print options + % -------------------------------------------------------------------- + Cheader = {'scan'}; + Theader = sprintf(sprintf('%%%ds:',opt.snspace(1)-1),'scan'); + Tline = sprintf('%%5d) %%%ds:',opt.snspace(1)-8); + Tline2 = sprintf('%%5d) %%6s%%%ds:',opt.snspace(1)-14); + Tavg = sprintf('%%%ds:',opt.snspace(1)-1); + TlineE = sprintf('%%5d) %%%ds: %%s',opt.snspace(1)-7); + for fi=1:numel(QMAfn) + Cheader = [Cheader QMAfn{fi}]; %#ok + Theader = sprintf(sprintf('%%s%%%ds',opt.snspace(2)),Theader,... + QMAfn{fi}(1:min(opt.snspace(2)-1,numel(QMAfn{fi})))); + Tline = sprintf('%s%%%d.%df',Tline,opt.snspace(2),opt.snspace(3)); + Tline2 = sprintf('%s%%%d.%df',Tline2,opt.snspace(2),opt.snspace(3)); + Tavg = sprintf('%s%%%d.%df',Tavg,opt.snspace(2),opt.snspace(3)); + end + Cheader = [Cheader 'IQR']; + Theader = sprintf(sprintf('%%s%%%ds',opt.snspace(2)),Theader,'SIQR'); + Tline = sprintf('%s%%%d.%df%%s\n',Tline,opt.snspace(2),opt.snspace(3)); + Tline2 = sprintf('%s%%%d.%df\n',Tline2,opt.snspace(2),opt.snspace(3)); + Tavg = sprintf('%s%%%d.%df\n',Tavg,opt.snspace(2),opt.snspace(3)); + + + + + + + % estimation part + switch action + case {'p0','p#','c#','*#','p0+','p#+','c#+','*#+'} + % loop for multiple files + stimem = clock; + + % return for empty input + if isempty(Pp0) || (isempty(Pp0{1}) && numel(Pp0)<=1) + cat_io_cprintf('com','No images for QA!\n'); + return + end + + if opt.verb>1 + fprintf('\n%s\n\n%s\n%s\n', ... + sprintf('CAT Preprocessing T1 Quality Control (%s %s):',mfilename,... + sprintf('Rev: %s',rev_cat)), Theader,repmat('-',size(Theader))); + end + + qamat = nan(numel(Po),numel(QMAfn)); + qamatm = nan(numel(Po),numel(QMAfn)); + mqamatm = 10.5*ones(numel(Po),1); + + + QAS = struct(); QAR = struct(); + QAR.mark2rps = @(mark) min(100,max(0,105 - mark*10)) + isnan(mark).*mark; + + for fi=1:numel(Pp0) + try + stime = cat_io_cmd(' Any segmentation Input:','g5','',opt.verb>2); stime1 = stime; + + [pp,ff,ee] = spm_fileparts(Po{fi}); + if exist(fullfile(pp,[ff ee]),'file') + Vo = spm_vol(Po{fi}); + elseif exist(fullfile(pp,[ff ee '.gz']),'file') + gunzip(fullfile(pp,[ff ee '.gz'])); + Vo = spm_vol(Po{fi}); + delete(fullfile(pp,[ff ee '.gz'])); + else + error('cat_vol_qa201901:noYo','No original image.'); + end + + + Vm = spm_vol(Pm{fi}); + Vp0 = spm_vol(Pp0{fi}); + if any(Vp0.dim ~= Vm.dim) + [Vx,Yp0] = cat_vol_imcalc(Vp0,Vm,'i1',struct('interp',2,'verb',0)); + else + Yp0 = single(spm_read_vols(Vp0)); + end + Yp0(isnan(Yp0) | isinf(Yp0)) = 0; + if 0 %~isempty(Pm{fi}) && exist(Pm{fi},'file') + Ym = single(spm_read_vols(spm_vol(Pm{fi}))); + Ym(isnan(Yp0) | isinf(Yp0)) = 0; + elseif 1 %end + %if ~exist(Ym,'var') || round( cat_stat_nanmean(Ym(round(Yp0)==3)) * 100) ~= 100 + Ym = single(spm_read_vols(spm_vol(Po{fi}))); + Ym(isnan(Yp0) | isinf(Yp0)) = 0; + Yw = Yp0>2.95 | cat_vol_morph( Yp0>2.25 , 'e'); + Yb = cat_vol_approx( Ym .* Yw + Yw .* min(Ym(:)) ) - min(Ym(:)); + %Yb = Yb / mean(Ym(Yw(:))); + Ym = Ym ./ max(eps,Yb); + + else + error('cat_vol_qa201901:noYm','No corrected image.'); + end + rmse = (mean(Ym(Yp0(:)>0) - Yp0(Yp0(:)>0)/3).^2).^0.5; + if rmse>0.2 + cat_io_cprintf('warn','Segmentation is maybe not fitting to the image (RMSE(Ym,Yp0)=%0.2f)?:\n %s\n %s',rmse,Pm{fi},Pp0{fi}); + end + + res.image = spm_vol(Pp0{fi}); + [QASfi,QAMfi] = cat_vol_qa201901('cat12',Yp0,Vo,Ym,res,species,opt,Pp0{fi}); + + if isnan(QASfi.qualitymeasures.NCR) + fprintf(''); + end + + + try + QAS = cat_io_updateStruct(QAS,QASfi,0,fi); + QAR = cat_io_updateStruct(QAR,QAMfi,0,fi); + catch + fprintf('ERROR-Struct'); + end + + + % color for the differen mark cases (opt.process) + for fni=1:numel(QMAfn) + try + qamat(fi,fni) = QAS(fi).qualitymeasures.(QMAfn{fni}); + qamatm(fi,fni) = QAR(fi).qualityratings.(QMAfn{fni}); + catch + qamat(fi,fni) = QASfi.qualitymeasures.(QMAfn{fni}); + qamatm(fi,fni) = QAMfi.qualityratings.(QMAfn{fni}); + end + + end + try + mqamatm(fi,1) = QAR(fi).qualityratings.IQR; + catch + mqamatm(fi,1) = QASfi.qualityratings.IQR; + end + mqamatm(fi,1) = max(0,min(10.5, mqamatm(fi,1))); + + + if opt.verb>1 + if opt.rerun || cat_io_rerun(Vo.fname, fullfile(pp,reportfolder,[opt.prefix ff '.xml']) , 0 ) + rerun = sprintf(' updated %2.0fs',etime(clock,stime1)); + elseif exist( fullfile(pp,reportfolder,[opt.prefix ff '.xml']) , 'file') + rerun = ' loaded'; + else + rerun = ' '; % new + end + + %% + if opt.orgval + cat_io_cprintf(opt.MarkColor(max(1,floor( mqamatm(fi,1)/9.5 * ... + size(opt.MarkColor,1))),:),sprintf(Tline,fi,... + spm_str_manip(QAS(fi).filedata.fname,['a' num2str(opt.snspace(1) - 14)]),... + qamat(fi,:), max(1,min(9.5,mqamatm(fi,:))), rerun)); + else + cat_io_cprintf(opt.MarkColor(max(1,floor( mqamatm(fi,1)/9.5 * ... + size(opt.MarkColor,1))),:),sprintf(Tline,fi,... + spm_str_manip(QAS(fi).filedata.fname,['a' num2str(opt.snspace(1) - 14)]),... + qamatm(fi,:), max(1,min(9.5,mqamatm(fi,:))), rerun)); + end + end + catch e + switch e.identifier + case {'cat_vol_qa201901:noYo','cat_vol_qa201901:noYm','cat_vol_qa201901:badSegmentation'} + em = e.identifier; + otherwise + em = ['ERROR:\n' repmat(' ',1,10) e.message '\n']; + for ei=1:numel(e.stack) + em = sprintf('%s%s%5d: %s\n',em,repmat(' ',1,10),... + e.stack(ei).line(end),e.stack(ei).name); + end + end + + [pp,ff] = spm_fileparts(Po{fi}); + QAS(fi).filedata.fnames = [spm_str_manip(pp,sprintf('k%d',floor( (opt.snspace(1)-19) /3) - 1)),'/',... + spm_str_manip(ff,sprintf('k%d',(opt.snspace(1)-19) - floor((opt.snspace(1)-14)/3)))]; + cat_io_cprintf(opt.MarkColor(end,:),sprintf(TlineE,fi,Pp0{fi},[em '\n'])); + end + end + + + + % sort by mean mark + % ---------------------------------------------------------------- + if opt.sortQATm && numel(Po)>1 + % sort matrix + [smqamatm,smqamatmi] = sort(mqamatm(:,1),'ascend'); + sqamatm = qamatm(smqamatmi,:); + sqamat = qamat(smqamatmi,:); + + % print matrix + if opt.verb>0 + fprintf('%s\n',repmat('-',size(Theader))); + for fi=1:numel(QAS) + if opt.orgval + cat_io_cprintf(opt.MarkColor(max(1,min(size(opt.MarkColor,1),... + round( mqamatm(smqamatmi(fi),2)/9.5 * ... + size(opt.MarkColor,1)))),:),sprintf(... + Tline2,fi,sprintf('(%d)',smqamatmi(fi)),... + spm_str_manip(Pp0{fi},'l80'), ...QAS(smqamatmi(fi)).filedata.fnames, ... + ...spm_str_manip(QAS(smqamatmi(fi)).filedata.file,['f' num2str(opt.snspace(1) - 14)]),... + sqamat(fi,:),max(1,min(10.5,mqamatm(smqamatmi(fi),:))))); + else + cat_io_cprintf(opt.MarkColor(max(1,min(size(opt.MarkColor,1),... + round( mqamatm(smqamatmi(fi),2)/9.5 * ... + size(opt.MarkColor,1)))),:),sprintf(... + Tline2,fi,sprintf('(%d)',smqamatmi(fi)),... + spm_str_manip(Pp0{fi},'l80'), ... QAS(smqamatmi(fi)).filedata.fnames, ... + ...spm_str_manip(QAS(smqamatmi(fi)).filedata.file,['f' num2str(opt.snspace(1) - 14)]),... + sqamatm(fi,:),mqamatm(smqamatmi(fi),:))); + end + end + end + else + %[smqamatm,smqamatmi] = sort(mqamatm,'ascend'); + %sqamatm = qamatm(smqamatmi,:); + end + % print the results for each scan + if opt.verb>1 && numel(Pp0)>1 + fprintf('%s\n',repmat('-',size(Theader))); + if opt.orgval + fprintf(Tavg,'mean',cat_stat_nanmean(qamat,1), cat_stat_nanmean(mqamatm,1)); %#ok + fprintf(Tavg,'std' , cat_stat_nanstd(qamat,1), cat_stat_nanstd(mqamatm,1)); %#ok + else + fprintf(Tavg,'mean',cat_stat_nanmean(qamatm,1), cat_stat_nanmean(mqamatm,1)); %#ok + fprintf(Tavg,'std' , cat_stat_nanstd(qamatm,1), cat_stat_nanstd(mqamatm,1)); %#ok + end + %fprintf('%s\n',repmat('-',size(Theader))); + %fprintf(Tavg,'mean',mean(qamat,1)); + %fprintf(Tavg,'std', std(qamat,1)); + end + if opt.verb>0, fprintf('\n'); end + + + + % result tables (cell structures) + % ---------------------------------------------------------------- + if nargout>2 && opt.write_csv + QAT = [Cheader(1:end-1); ... there is no mean for the original measures + Po , num2cell(qamat); ... + 'mean' , num2cell(cat_stat_nanmean(qamat,1)); ... + 'std' , num2cell( cat_stat_nanstd(qamat,1,1))]; + QATm = [Cheader; ... + Po , num2cell(qamatm) , ... + num2cell(cat_stat_nanmean(qamatm,2)); ... + 'mean' , num2cell(cat_stat_nanmean(qamatm,1)) , ... + num2cell(cat_stat_nanmean(mqamatm,1)); ... + 'std' , num2cell( cat_stat_nanstd(qamatm,1,1)), ... + num2cell( cat_stat_nanstd(mqamatm,1))]; + + + % write csv results + % -------------------------------------------------------------- + if opt.write_csv + pp = spm_fileparts(Pp0{1}); + cat_io_csv(fullfile(pp,reportfolder,[opt.prefix num2str(numel(Vo),'%04d') ... + 'cat_vol_qa_values.csv']),QAT); + cat_io_csv(fullfile(pp,reportfolder,[opt.prefix num2str(numel(Vo),'%04d') ... + 'cat_vol_qa_marks.csv']),QATm); + end + end + + if opt.verb>0 + fprintf('Quality Control for %d subject was done in %0.0fs\n', ... + numel(Pp0),etime(clock,stimem)); fprintf('\n'); + end + + + case 'cat12err' + + % file information + % ---------------------------------------------------------------- + [pp,ff,ee] = spm_fileparts(Vo.fname); + if strcmp(ee,'.gz'), [~,ff] = spm_fileparts(ff); ee = '.nii.gz'; end + [pp0,ff0,ee0] = spm_fileparts(Pp0); + [QAS.filedata.path,QAS.filedata.file] = spm_fileparts(Vo.fname); + QAS.filedata.fname = Vo.fname; + QAS.filedata.F = Vo.fname; + QAS.filedata.Fm = fullfile(pp0,['m' ff ee0]); + QAS.filedata.Fp0 = fullfile(pp0,['p0' ff ee0]); + QAS.filedata.fnames = [spm_str_manip(pp,sprintf('k%d',... + floor( max(opt.snspace(1)-19-ff,opt.snspace(1)-19)/3) - 1)),'/',... + spm_str_manip(ff,sprintf('k%d',... + (opt.snspace(1)-19) - floor((opt.snspace(1)-14)/3)))]; + + + % software, parameter and job information + % ---------------------------------------------------------------- + [nam,rev_spm] = spm('Ver'); + QAS.software.version_spm = rev_spm; + if strcmpi(spm_check_version,'octave') + QAS.software.version_octave = version; + else + A = ver; + for i=1:length(A) + if strcmp(A(i).Name,'MATLAB') + QAS.software.version_matlab = A(i).Version; + end + end + clear A + end + % 1 line: Matlab, SPM12, CAT12 version number and GUI and experimental mode + if ispc, OSname = 'WIN'; + elseif ismac, OSname = 'MAC'; + else, OSname = 'LINUX'; + end + + QAS.software.system = OSname; + QAS.software.version_cat = ver_cat; + if ~isfield(QAS.software,'version_segment') + QAS.software.version_segment = rev_cat; + end + QAS.software.revision_cat = rev_cat; + try + QAS.hardware.numcores = max(cat_get_defaults('extopts.nproc'),1); + catch + QAS.hardware.numcores = 1; + end + + + % save important preprocessing parameter + % remove LAS + QAS.parameter.opts = opt.job.opts; + QAS.parameter.extopts = rmfield(opt.job.extopts,... + {'LAB','atlas','satlas','darteltpms','shootingtpms','fontsize'}); + %QAS.parameter.output = opt.job.output; + QAS.parameter.caterr = opt.caterr; + QAS.error = opt.caterrtxt; + + % export + if opt.write_xml + cat_io_xml(fullfile(pp0,[opt.prefix ff '.xml']),QAS,'write'); + end + + case 'cat12' + % estimation of the measures for the single case + + + % file information + % ---------------------------------------------------------------- + [pp,ff,ee] = spm_fileparts(Vo.fname); + if strcmp(ee,'.gz'), [~,ff] = spm_fileparts(ff); ee = '.nii.gz'; end + [pp0,ff0,ee0] = spm_fileparts(Pp0); + [QAS.filedata.path,QAS.filedata.file] = spm_fileparts(Vo.fname); + QAS.filedata.fname = Vo.fname; + QAS.filedata.F = Vo.fname; + QAS.filedata.Fm = fullfile(pp0,['m' ff ee0]); + QAS.filedata.Fp0 = fullfile(pp0,['p0' ff ee0]); + QAS.filedata.fnames = [spm_str_manip(pp,sprintf('k%d',... + floor( max(opt.snspace(1)-19-ff,opt.snspace(1)-19)/3) - 1)),'/',... + spm_str_manip(ff,sprintf('k%d',... + (opt.snspace(1)-19) - floor((opt.snspace(1)-14)/3)))]; + + + % software, parameter and job information + % ---------------------------------------------------------------- + [nam,rev_spm] = spm('Ver'); + OSname = {'LINUX','WIN','MAC'}; + QAS.software.system = OSname{1 + ispc + ismac}; + QAS.software.version_spm = rev_spm; + A = ver; + for i=1:length(A) + if strcmp(A(i).Name,'MATLAB') + QAS.software.version_matlab = A(i).Version; + end + end + clear A + QAS.software.version_cat = ver_cat; + if ~isfield(QAS.software,'version_segment') + QAS.software.version_segment = rev_cat; + end + QAS.software.revision_cat = rev_cat; + QAS.software.function = which('cat_vol_qa201901'); + QAS.software.markdefs = which('cat_stat_marks'); + QAS.software.qamethod = action; + QAS.software.date = datestr(clock,'yyyymmdd-HHMMSS'); + warning off + QAS.software.opengl = opengl('INFO'); + QAS.software.opengldata = opengl('DATA'); + warning on + + %QAS.parameter = opt.job; + QAS.parameter.vbm = rmfield(cat_get_defaults,'output'); + if isfield(opt,'job') && isfield(opt.job,'opts'), QAS.parameter.opts = opt.job.opts; end + if isfield(opt,'job') && isfield(opt.job,'extopts'), QAS.parameter.opts = opt.job.extopts; end + if exist('res','var') + rf = {'Affine','Affine0','lkp','mn','vr','ll'}; % important SPM preprocessing variables + for rfi=1:numel(rf) + if isfield(res,rf{rfi}), QAS.SPMpreprocessing.(rf{rfi}) = res.(rf{rfi}); end + end + end + + %% resolution, boundary box + % --------------------------------------------------------------- + QAS.software.cat_qa_warnings = struct('identifier',{},'message',{}); + vx_vol = sqrt(sum(Vo.mat(1:3,1:3).^2)); + vx_voli = sqrt(sum(V.mat(1:3,1:3).^2)); + Yp0toC = @(Yp0,c) 1-min(1,abs(Yp0-c)); + + % resolution + QAS.qualitymeasures.res_vx_vol = vx_vol; + if 1 % CAT internal resolution + QAS.qualitymeasures.res_vx_voli = vx_voli; + end + QAS.qualitymeasures.res_RMS = cat_stat_nanmean(vx_vol.^2).^0.5; + % further unused measure (just for test/comparison) + %QAS.qualitymeasures.res_isotropy = max(vx_vol)./min(vx_vol); + %QAS.qualitymeasures.res_vol = prod(abs(vx_vol)); + %QAS.qualitymeasures.res_MVR = mean(vx_vol); + + % boundary box - brain tissue next to image boundary + bbth = round(2/cat_stat_nanmean(vx_vol)); M = true(size(Yp0)); + M(bbth:end-bbth,bbth:end-bbth,bbth:end-bbth) = 0; + QAS.qualitymeasures.res_BB = sum(Yp0(:)>1.25 & M(:))*prod(abs(vx_vol)); + + % check segmentation + spec = species; for ai=num2str(0:9); spec = strrep(spec,ai,''); end + bvol = species; for ai=char(65:122); bvol = strrep(bvol,ai,''); end; bvol = str2double(bvol); + + subvol = [sum(Yp0(:)>2.5 & Yp0(:)<3.1)*prod(vx_vol)/1000,... + sum(Yp0(:)>1.5 & Yp0(:)<2.5)*prod(vx_vol)/1000,... + sum(Yp0(:)>0.5 & Yp0(:)<1.5)*prod(vx_vol)/1000]; + + if isempty(bvol) + switch spec + case 'human' + bvol = 1400; + otherwise + warning('cat_vol_qa201901:species',... + sprintf('Unknown species %s (C=%0.0f,G=%0.0f,W=%0.0f).',species,subvol)); %#ok + end + end + if sum(subvol)bvol*3 + warning('cat_vol_qa201901:badSegmentation',... + sprintf('Bad %s segmentation (C=%0.0f,G=%0.0f,W=%0.0f).',species,subvol)) %#ok + end + if ~isfield(QAS,'subjectmeasures') + %% in case of external/batch calls + QAS.subjectmeasures.vol_TIV = sum(Yp0(:)>0) .* prod(vx_vol) / 1000; + for i = 1:3 + QAS.subjectmeasures.vol_abs_CGW(i) = sum( Yp0toC(Yp0(:),i)) .* prod(vx_vol) / 1000; + QAS.subjectmeasures.vol_rel_CGW(i) = QAS.subjectmeasures.vol_abs_CGW(i) ./ ... + QAS.subjectmeasures.vol_TIV; + end + end + + %% estimate QA + % --------------------------------------------------------------- + % remove space arount the brain for speed-up + [Yo,Ym,Yp0] = cat_vol_resize({Yo,Ym,Yp0},'reduceBrain',vx_vol,4,Yp0>1.5); + + % rought contast and noise estimation to get a stable T1 map for threshold estimation + T1th = [cat_stat_nanmedian(Ym(Yp0toC(Yp0(:),1)>0.9)) ... + cat_stat_nanmedian(Ym(Yp0toC(Yp0(:),2)>0.9)) ... + cat_stat_nanmedian(Ym(Yp0toC(Yp0(:),3)>0.9))]; + noise = max(0,min(1,cat_stat_nanstd(Ym(Yp0(:)>2.9)) / min(abs(diff(T1th))))); + Yms = Ym+0; spm_smooth(Yms,Yms,repmat(double(noise)*4,1,3)); % smoothing to reduce high frequency noise + + % basic tissue classes - erosion to avoid PVE, std to avoid other tissues (like WMHs) + voli = @(v) (v ./ (pi * 4./3)).^(1/3); + rad = voli( QAS.subjectmeasures.vol_TIV) ./ cat_stat_nanmean(vx_vol); + Ysc = 1-cat_vol_smooth3X(Yp0<1 | Yo==0,min(24,max(16,rad*2))); % fast 'distance' map + Ycm = cat_vol_morph(Yp0>0.5 & Yp0<1.5 & Yms0.75 & Yp0<1.25;% avoid PVE & ventricle focus + if sum(Ycm(:)>0)<10; Ycm=cat_vol_morph(Yp0>0.5 & Yp0<1.5 & Yms0)<10; Ycm=Yp0>0.5 & Yms0.7 & Yms1.1,'e') & cat_vol_morph(Yp0<2.9,'e'); % avoid PVE 2 + Ygm = (Ygm1 | Ygm2) & Ysc<0.9; % avoid PVE & no subcortex + Ywm = cat_vol_morph(Yp0>2.1,'e') & Yp0>2.9 & ... % avoid PVE & subcortex + Yms>min(cat_stat_nanmean(T1th(2:3)),(T1th(2) + 2*noise*abs(diff(T1th(2:3))))); % avoid WMHs2 + clear Ygm1 Ygm2; % Ysc; + + %% further refinements of the tissue maps + T2th = [median(Yms(Ycm)) median(Yms(Ygm)) median(Yms(Ywm))]; + Ycm = Ycm & Yms>(T2th(1)-16*noise*diff(T2th(1:2))) & Ysc &... + Yms<(T2th(1)+0.1*noise*diff(T2th(1:2))); + if sum(Ycm(:)>0)<10; Ycm=cat_vol_morph(Yp0>0.5 & Yp0<1.5 & Yms0)<10; Ycm=Yp0>0.5 & Yms(T2th(2)-2*noise*abs(diff(T1th(2:3)))) & Yms<(T2th(2)+2*noise*abs(diff(T1th(2:3)))); + Ygm(smooth3(Ygm)<0.2) = 0; + Ycm = cat_vol_morph(Ycm,'lc'); % to avoid holes + Ywm = cat_vol_morph(Ywm,'lc'); % to avoid holes + Ywe = cat_vol_morph(Ywm,'e'); + + + %% RD202212 add resolution measure + res_ECR0 = estimateECR0( Ym , Yp0, T2th, vx_vol ); + + %% low resolution tissue intensity maps (smoothing) + % High frequency noise is mostly uncritical as far as simple smoothing can reduce it. + % Although the very low frequency interferences (inhomogeneity) is unproblematic in most cases, + % but will influence the noise pattern. + % But most important is the noise with the medium high frequencies, that we try do detect by + % reducing the very high and low noise pattern by filtering and pixel smoothing by reduction. + res = 2; vx_volx = 1; + Yos = cat_vol_localstat(Yo,Ywm,1,1); Yo(Yos>0)=Yos(Yos>0); % reduce high frequency noise in WM + Yos = cat_vol_localstat(Yo,Ycm,1,1); Yo(Yos>0)=Yos(Yos>0); % reduce high frequency noise in CSF + + Yc = cat_vol_resize(Yo .* Ycm,'reduceV',vx_volx,res,32,'min'); % CSF thr. (minimum to avoid PVE) + Yg = cat_vol_resize(Yo .* Ygm,'reduceV',vx_volx,res,32,'meanm'); % GM thr. + Yw = cat_vol_resize(Yo .* Ywe,'reduceV',vx_volx,res,32,'meanm'); % WM thr. and bias correction (Ywme) + Ywc = cat_vol_resize(Ym .* Ywe,'reduceV',vx_volx,res,32,'meanm'); % for bias correction + Ywb = cat_vol_resize(Yo .* Ywm,'reduceV',vx_volx,res,32,'max'); % for WM inhomogeneity estimation (avoid PVE) + Ywn = cat_vol_resize(Yo .* Ywe,'reduceV',vx_volx,res,32,'meanm'); % for WM noise + Ycn = cat_vol_resize(Yo .* Ycm,'reduceV',vx_volx,res,32,'meanm'); % for CSF noise + Ycm = cat_vol_resize(Ycm ,'reduceV',vx_volx,res,32,'meanm'); % CSF thr. (minimum to avoid PVE) + Ygm = cat_vol_resize(Ygm ,'reduceV',vx_volx,res,32,'meanm'); % GM thr. + Ywm = cat_vol_resize(Ywm ,'reduceV',vx_volx,res,32,'meanm'); % WM thr. and bias correction (Ywme) + Ywe = cat_vol_resize(Ywe ,'reduceV',vx_volx,res,32,'meanm'); % WM thr. and bias correction (Ywme) + + % only voxel that were the product of + Yc = Yc .* (Ycm>=0.5); Yg = Yg .* (Ygm>=0.5); Yw = Yw .* (Ywe>=0.5); + Ywc = Ywc .* (Ywe>=0.5); Ywb = Ywb .* (Ywm>=0.5); Ywn = Ywn .* (Ywm>=0.5); + Ycn = Ycn .* (Ycm>=0.5); + + clear Ycm Ygm Ywm Ywme; + [Yo,Ym,Yp0,resr] = cat_vol_resize({Yo,Ym,Yp0},'reduceV',vx_volx,res,32,'meanm'); + resr.vx_volo = vx_vol; vx_vol=resr.vx_red .* resr.vx_volo; + + % intensity scaling for normalized Ym maps like in CAT12 + Ywc = Ywc .* (cat_stat_nanmean(Yo(Yp0(:)>2))/cat_stat_nanmean(Ym(Yp0(:)>2))); + + %% bias correction for original map, based on the + WI = Yw./max(eps,Ywc); WI(isnan(WI) | isinf(WI)) = 0; + WI = cat_vol_approx(WI,'rec',2); + WI = cat_vol_smooth3X(WI,1); + Ywn = Ywn./WI; Ywn = round(Ywn*1000)/1000; + Ymi = Yo ./WI; Ymi = round(Ymi*1000)/1000; + Yc = Yc ./WI; Yc = round(Yc *1000)/1000; + Yg = Yg ./WI; Yg = round(Yg *1000)/1000; + Yw = Yw ./WI; Yw = round(Yw *1000)/1000; + clear WIs ; + + Ywb = Ywb ./ cat_stat_nanmean(Ywb(Yp0(:)>2)); % ############### incorrect ################### + + % tissue segments for contrast estimation etc. + CSFth = cat_stat_nanmean(Yc(~isnan(Yc(:)) & Yc(:)~=0)); + GMth = cat_stat_nanmean(Yg(~isnan(Yg(:)) & Yg(:)~=0)); + WMth = cat_stat_nanmean(Yw(~isnan(Yw(:)) & Yw(:)~=0)); + T3th = [CSFth GMth WMth]; + + % estimate background + [Ymir,resYbg] = cat_vol_resize(Ymi,'reduceV',1,6,32,'meanm'); + try + warning 'off' 'MATLAB:cat_vol_morph:NoObject' + BGCth = min(T3th)/2; + Ybgr = cat_vol_morph(cat_vol_morph(Ymir0.5; clear Yosr Ybgr; + if sum(Ybg(:))<32, Ybg = cat_vol_morph(Yo0.5; clear Yosr Ybgr; + if sum(Ybg(:))<32, Ybg = cat_vol_morph(YoGMth + QAS.qualitymeasures.tissue_weighting = 'T1'; + elseif WMth0.5 & ~isinf(Yp0(:)))); + end + QAS.qualitymeasures.tissue_stdr = QAS.qualitymeasures.tissue_std ./ (WMth-BGth); + + % (relative) (mininum) tissue contrast ( CSF-GM-WM ) + % - the CSF threshold varies strongly due to bad segmentations, + % and anatomica variance, so its better to use GM-WM contrast + % and take care of overoptimisation with values strongly >1/3 + % of the relative contrast + contrast = min(abs(diff(QAS.qualitymeasures.tissue_mn(3:4)))) ./ (max([WMth,GMth])); % default contrast + contrast = contrast + min(0,13/36 - contrast)*1.2; % avoid overoptimsization + QAS.qualitymeasures.contrast = contrast * (max([WMth,GMth])); + QAS.qualitymeasures.contrastr = contrast; + + + + %% noise estimation (original (bias corrected) image) + % WM variance only in one direction to avoid WMHs! + rms=1; nb=1; + NCww = sum(Ywn(:)>0) * prod(vx_vol); + NCwc = sum(Ycn(:)>0) * prod(vx_vol); + [Yos2,YM2] = cat_vol_resize({Ywn,Ywn>0},'reduceV',vx_vol,3,16,'meanm'); + NCRw = estimateNoiseLevel(Yos2,YM2>0.5,nb,rms) / max(GMth,WMth) / contrast ; + if BGth<-0.1 && WMth<3, NCRw=NCRw/3; end% MT weighting + clear Yos0 Yos1 Yos2 YM0 YM1 YM2; + + % CSF variance of large ventricle + % for typical T2 images we have too much signal in the CSF and can't use it for noise estimation! + wcth = 200; + if CSFthwcth + [Yos2,YM2] = cat_vol_resize({Ycn,Ycn>0},'reduceV',vx_vol,3,16,'meanm'); + NCRc = estimateNoiseLevel(Yos2,YM2>0.5,nb,rms) / max(GMth,WMth) / contrast ; + clear Yos0 Yos1 Yos2 YM0 YM1 YM2; + else + NCRc = 0; + NCwc = 0; + end + % 1/sqrt(volume) to compensate for noise differency due to different volumen size. + % Overall there are better chances to correct high resolution noise. + % Nitz W R. Praxiskurs MRT. Page 28. + NCwc = min(wcth,max(0,NCwc-wcth)); NCww = min(wcth,NCww) - NCwc; % use CSF if possible + if NCwc<3*wcth && NCww<10*wcth, NCRc = min(NCRc,NCRw); end + QAS.qualitymeasures.NCR = (NCRw*NCww + NCRc*NCwc)/(NCww+NCwc); + QAS.qualitymeasures.NCR = QAS.qualitymeasures.NCR * (prod(resr.vx_volo*res))^0.4 * 5/4; %* 7.5; %15; + %QAS.qualitymeasures.CNR = 1 / QAS.qualitymeasures.NCR; +%fprintf('NCRw: %8.3f, NCRc: %8.3f, NCRf: %8.3f\n',NCRw,NCRc,(NCRw*NCww + NCRc*NCwc)/(NCww+NCwc)); + + + %% Bias/Inhomogeneity (original image with smoothed WM segment) + Yosm = cat_vol_resize(Ywb,'reduceV',vx_vol,3,32,'meanm'); % resolution and noise reduction + for si=1:max(1,min(3,round(QAS.qualitymeasures.NCR*4))), Yosm = cat_vol_localstat(Yosm,Yosm>0,1,1); end + QAS.qualitymeasures.ICR = cat_stat_nanstd(Yosm(Yosm(:)>0)) / contrast; + %QAS.qualitymeasures.CIR = 1 / QAS.qualitymeasures.ICR; + + + %% resolution reating + QAS.qualitymeasures.res_ECR = 1 - abs( res_ECR0 / contrast); + + + %% marks + QAR = cat_stat_marks('eval',1,QAS); + + % export + if opt.write_xml + QAS.qualityratings = QAR.qualityratings; + QAS.subjectratings = QAR.subjectratings; + QAS.ratings_help = QAR.help; + + cat_io_xml(fullfile(pp0,[opt.prefix ff '.xml']),QAS,'write'); + end + + clear Yi Ym Yo Yos Ybc + clear Ywm Ygm Ycsf Ybg + + end + + if nargout>2, varargout{3} = cat_qa_warnings; end + if nargout>1, varargout{2} = QAR; end + if nargout>0, varargout{1} = QAS; end + +end +%======================================================================= +function def=defaults + % default parameter + def.verb = 2; % verbose level [ 0=nothing | 1=points | 2*=results ] + def.write_csv = 2; % final cms-file [ 0=dont write |1=write | 2=overwrite ] + def.write_xml = 1; % images base xml-file + def.sortQATm = 1; % sort QATm output + def.orgval = 0; % original QAM results (no marks) + def.avgfactor = 2; % + def.prefix = 'cat_'; % intensity scaled image + def.mprefix = 'm'; % prefix of the preprocessed image + def.process = 3; % used image [ 0=T1 | 1=mT1 | 2=avg | 3=both ] + def.calc_MPC = 0; + def.calc_STC = 0; + def.calc_MJD = 0; + def.method = 'spm'; + def.snspace = [100,7,3]; + def.nogui = exist('XT','var'); + def.MarkColor = cat_io_colormaps('marks+',40); +end + +function noise = estimateNoiseLevel(Ym,YM,r,rms,vx_vol) +% ---------------------------------------------------------------------- +% noise estimation within Ym and YM. +% ---------------------------------------------------------------------- + if ~exist('vx_vol','var') + vx_vol=[1 1 1]; + end + if ~exist('r','var') + r = 1; + else + r = min(10,max(max(vx_vol),r)); + end + if ~exist('rms','var') + rms = 1; + end + + Ysd = cat_vol_localstat(single(Ym),YM,r,4); + noise = cat_stat_nanstat1d(Ysd(YM).^rms,'median').^(1/rms); +end +%======================================================================= +function res_ECR = estimateECR0(Ym,Yp0,Tth,vx_vol) +%% estimateECR. Quanfify anatomical details by the normalized edge strength. +% +% old pure version for high quality segmentation input + +% extend step by step by some details (eg. masking of problematic regions + + Ygrad = cat_vol_grad(max(Tth(2),min(1,Ym) .* (Yp0>0)) , vx_vol); + res_ECR = cat_stat_nanmedian(Ygrad(Yp0(:)>2.05 & Yp0(:)<2.95),1); + +end +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_stat_nanmean.m",".m","2102","76","function out = cat_stat_nanmean(in, dim) +% ---------------------------------------------------------------------- +% Average, not considering NaN values. Similar usage like mean() or +% MATLAB nanmean of the statistic toolbox. Process input as double +% due to errors in large single arrays and set data class of ""out"" +% to the data class of ""in"" at the end of the processing. +% Use dim==0 to evaluate in(:) in case of dimension selection +% (e.g., in(:,:,:,2) ). +% +% out = cat_stat_nanmean(in,dim) +% +% Example 1: +% a = rand(4,6,3); +% a(rand(size(a))>0.5)=nan; +% av = cat_stat_nanmean(a,3); +% am = nanmean(a,3); % of the statistical toolbox ... +% fprintf('%0.4f %0.4f\n',([av(:),am(:)])'); +% +% Example 2 - special test call of example 1: +% cat_stat_nanstd('test') +% +% See also cat_stat_nansum, cat_stat_nanstd, cat_stat_nanmedian. +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + if nargin < 1 + help cat_stat_nanmean; + return; + end; + + if ischar(in) && strcmp(in,'test') + a = rand(4,6,3); + a(rand(size(a))>0.5)=nan; + av = cat_stat_nanmean(a,3); + am = nanmean(a,3); % of the statistical toolbox ... + fprintf('%0.4f %0.4f\n',([av(:),am(:)])'); + out = nanmean(av(:) - am(:)); + return; + end + + if nargin < 2 + if size(in,1) ~= 1 + dim = 1; + elseif size(in,2) ~= 1 + dim = 2; + else + dim = 3; + end; + end; + + if dim == 0 + in = in(:); + dim = 1; + end + + if isempty(in), out = nan; return; end + + % estimate mean + %tp = class(in); + tmpin = double(in); % single failed in large arrays + tmpin(isnan(in(:))) = 0; + if sum(~isnan(in),dim)==0 + out = nan(size(sum(tmpin, dim))); + else + out = sum(tmpin, dim) ./ max(eps,sum(~isnan(in),dim)); + out(sum(~isnan(in),dim)==0) = nan; + end + + %eval(sprintf('out = %s(out);',tp)); +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_vol_nonlin_coreg_multi_run.m",".m","918","40","function out = cat_vol_nonlin_coreg_multi_run(job) +% Call cat_vol_nonlin_coreg for multiple subjects +% +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +global vox reg bb + +warning off; + +% use some options from GUI or default file +vox = job.vox; +reg = job.reg; +bb = job.bb; + +inputs = cell(3, 1); + +m = numel(job.other); +out.ofiles = cell(m,1); +other = cell(m,1); + +for j=1:m + [pth,nam,ext,num] = spm_fileparts(job.other{j}); + out.ofiles{j} = fullfile(pth,['w', nam, ext, num]); + other{j} = job.other{j}; +end +inputs{1} = job.ref; +inputs{2} = job.source; +inputs{3} = other; + +spm_jobman('run',{'cat_vol_nonlin_coreg.m'},inputs{:}); + +warning on; +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_surf_flipsides.m",".m","7969","215","function Prdata = cat_surf_flipsides(job) +% ______________________________________________________________________ +% Mirror surface side. +% +% There are to major ways (i) using the mapping between the templates, +% and (ii) estimating an individual mapping. The first way only need a +% resampling of the data, whereas the second way requires a spherical +% mapping (~5 minutes per hemisphere). +% +% To keep things easy the first way used the resampled gifti files +% s#mm.[rl]h.TEXTURE.resampled.FILENAME.gii as input and ... +% +% * template | subject +% +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + + + +% Todo: +% +% * Hier muss ein allgemeinenes Konzept vorliegen, mit dem sich sowohl eine +% automatische (z.B. fuer cat_surf_calc), als auch manuelle Nutzung (GUI) +% moeglich ist. +% +% * Ich fuerchte ich mach die dinge komplizierter als sie sind ... +% +% Facts: +% 1. Die Daten muessen IMMER gesampled werden. +% 2. Fuer eine Analyse kommen nur GIFTIs in Frage. +% 3. Fuer eine Analyse spielt die Seite keine Rolle. +% >> Als in/output waere die s#mm.rh.DATA.resampled.SUBJECT.gii wohl sinnvoll +% >> Als Name koennte man entweder eine dritte seite Lh/Rh nutzen (=mesh) oder +% einen weiteren Term 'flip' oder 'flipped' einfuegen +% >> Die 32k Meshes sind flip-ready! +% >> Nutzt man den Subject-case waere die Orignaldaten rh.DATA.SUBJECT +% wohl besser (achtung hier koennten auch resampled reinrutschen) +% >> Analysefertig ausgabe sinnvoll ... andere Faelle machens nur unnoetig komplex +% +% Frage: +% 1. Spielt die Reihefolge des Remeshings eine Rolle? +% >> Wahrscheinlich besser die Originaloberflaeche auf die andere Seite zu mappen im individuellen Fall. +% >> Beim template-Fall spiel das wohl eher keine Rolle +% +% * Namensgebebung: +% rh.thickness.MaMu99.gii > Lh.thickness.MaMu99.gii +% s#mm.rh.thickness.resampled.MaMu99.gii +% +% * Flip man nur texturen oder ganze Oberflaechen? +% - wegen Analyse ganze Oberflaechen +% +% * GUI Anbindung +% - job.cdata (lh > rh, rh > lh) ... am besten nur eine seite waehlbar, so bekommst du ein sichereres reslutat +% - job.type (template | subject) ... +% +% * automatische Ansbindung fuer surf_calc +% - es wird kein bild geschrieben, sondern die daten werden als output +% uebergeben + +% Ablauf... +% * Input sollten die Originaldaten (Texturen) sein. +% Subject (aufwendiger - genauer) +% * Die Daten werden geflipt und ein Mapping zur anderen fsavg bestimmt. +% * Resampling +% Template (einfacher - schneller) +% * Die Daten werden gesampled +% * Das vorbestimmte Mapping zwischen den fsavgs wird angewandt. + + + if ~exist('job','var'), job=struct(); end + + def.verb = 1; + def.cdata = {}; + def.type = 'template'; % template | subject + def.recalctemplate = 0; + def.usetemplate = 1; + def.debug = 0; + job = cat_io_checkinopt(job,def); + + if isempty(job.cdata); job.cdata = cellstr(spm_select(inf,'gifti','Select surface','','','^s.*')); end + job.cdata = cellstr(job.cdata); + if isempty(job.cdata) + fprintf('Nothing to do.\n'); + return; + end + + + %% fsavg sphere and central + Psphere{1} = fullfile(fileparts(mfilename('fullpath')),'templates_surfaces','lh.sphere.freesurfer.gii'); + Psphere{2} = fullfile(fileparts(mfilename('fullpath')),'templates_surfaces','rh.sphere.freesurfer.gii'); + Pcentral{1} = fullfile(fileparts(mfilename('fullpath')),'templates_surfaces','lh.central.freesurfer.gii'); + Pcentral{2} = fullfile(fileparts(mfilename('fullpath')),'templates_surfaces','rh.central.freesurfer.gii'); + % fsavg flipping spherical mapping + Preg{1} = fullfile(fileparts(mfilename('fullpath')),'templates_surfaces','lh.sphere.rhreg.freesurfer.gii'); + Preg{2} = fullfile(fileparts(mfilename('fullpath')),'templates_surfaces','rh.sphere.lhreg.freesurfer.gii'); + % fsavg flipping + Pflipsphere{1} = fullfile(fileparts(mfilename('fullpath')),'templates_surfaces','rh.sphere.lhflip.freesurfer.gii'); + Pflipsphere{2} = fullfile(fileparts(mfilename('fullpath')),'templates_surfaces','lh.sphere.rhflip.freesurfer.gii'); + Pflipcentral{1} = fullfile(fileparts(mfilename('fullpath')),'templates_surfaces','rh.central.lhflip.freesurfer.gii'); + Pflipcentral{2} = fullfile(fileparts(mfilename('fullpath')),'templates_surfaces','lh.central.rhflip.freesurfer.gii'); + + + + %% spherical registration of lh to rh template + if job.recalctemplate + for si=1:2 + %% flipping + flipsurf(Pcentral{si},Pflipcentral{si}); + flipsurf(Psphere{si},Pflipsphere{si}); + + % registration + cmd = sprintf('CAT_WarpSurf -type 0 -i ""%s"" -is ""%s"" -t ""%s"" -ts ""%s"" -ws ""%s""',... + Pflipcentral{si},Pflipsphere{si},Pcentral{~(si-1)+1},Psphere{~(si-1)+1},Preg{~(si-1)+1}); + cat_system(cmd,job.debug); + end + end + + + %% + sides = {'lh','rh'}; + %sidesi = {'flh','frh'}; % further letters ... problem [rl]h.* + %sidesi = {'ih','ih'}; % other letter ... problem [rl]h.* > [rli]h, but ih for both left and right + sidesi = {'rh','lh'}; % simple flipped ... flip information in resampled field + Prdata = cell(numel(job.cdata),1); + Prmesh = cell(numel(job.cdata),1); + if job.usetemplate + % this is the simple case + + sinfo = cat_surf_info(job.cdata); + + for di = 1:numel(job.cdata) + %% + try + switch sinfo(di).side + case 'lh', si = 1; + case 'rh', si = 2; + end + + Prdata(di) = cat_surf_rename(sinfo(di).Pdata,'side',sidesi{si},... + 'dataname',sinfo(di).dataname,'templateresampled',sprintf('%sresampled',sides{si})); + Prmesh(di) = cat_surf_rename(sinfo(di).Pmesh,'side',sidesi{si},... + 'dataname','central','templateresampled',sprintf('%sresampled',sides{si})); + + % flip gifti + gii = gifti(sinfo(di).Pmesh); + [pp,ff] = spm_fileparts(sinfo(di).Pmesh); + gii.vertices(:,1) = -gii.vertices(:,1); + gii.faces = [gii.faces(:,2),gii.faces(:,1),gii.faces(:,3)]; + cat_io_FreeSurfer('write_surf',fullfile(pp,[ff 'tmp']),gii); + + cmd = sprintf('CAT_ResampleSurf ""%s"" ""%s"" ""%s"" ""%s"" ""%s"" ""%s""',... + fullfile(pp,[ff 'tmp']),Preg{~(si-1)+1},Psphere{si},Prmesh{di},job.cdata{di},Prdata{di}); + err = cat_system(cmd,job.debug); + + if err + cat_io_cprintf('err','Case ""%s"" did not work.\n',job.cdata{di}); + continue; + end + + gc = gifti(Prdata{di}); gm = gifti(Prmesh{di}); gm.cdata = gc.cdata; save(gm,Prdata{di}); + + % delete temporary files + if exist(Prmesh{di},'file'), delete(Prmesh{di}); end + if exist(fullfile(pp,[ff 'tmp']),'file'), delete(fullfile(pp,[ff 'tmp'])); end + + if job.verb + fprintf('Display %s\n',spm_file(Prdata{di},'link','cat_surf_display(''%s'')')); + end + catch + cat_io_cprintf('err','Case ""%s"" did not work.\n',job.cdata{di}); + end + end + else + error('not ready now'); + + %{ + for di = 1:numel(job.cdata) + sinfo = cat_surf_info(job.cdata{di}); + + switch sinfo.side + case 'lh', si = 1; + case 'rh', si = 2; + end + + % flipping + flipsurf(Pcentral{si},Pflipcentral{si}); + flipsurf(Psphere{si},Pflipsphere{si}); + + % registration + cmd = sprintf('CAT_WarpSurf -type 0 -i ""%s"" -is ""%s"" -t ""%s"" -ts ""%s"" -ws ""%s""',... + Pflipcentral{si},Pflipsphere{si},Pcentral{~(si-1)+1},Psphere{~(si-1)+1},Preg{~(si-1)+1}); + cat_system(cmd,opt.debug); + + end + %} + + end + +end +function flipsurf(P,Po) + gii = gifti(P); + gii.vertices(:,1) = -gii.vertices(:,1); + gii.faces = [gii.faces(:,2),gii.faces(:,1),gii.faces(:,3)]; + save(gii,Po); +end + + + ","MATLAB" +"Neurology","ChristianGaser/cat12","cat_vol_simgrow.c",".c","6246","162","/* ______________________________________________________________________ + * + * Christian Gaser, Robert Dahnke + * Structural Brain Mapping Group (https://neuro-jena.github.io) + * Departments of Neurology and Psychiatry + * Jena University Hospital + * ______________________________________________________________________ + * $Id$ + */ + +#include ""mex.h"" +#include ""math.h"" +#include ""float.h"" +/* #include ""matrix.h"" */ + +#ifndef isnan +#define isnan(a) ((a)!=(a)) +#endif + +/* HELPFUNCTIONS */ + +/* estimate x,y,z position of index i in an array size sx,sxy=sx*sy... */ +void ind2sub(int i,int *x,int *y, int *z, int sxy, int sy) { + *z = (int)floor( (double)i / (double)sxy ) +1; + i = i % (sxy); + *y = (int)floor( (double)i / (double)sy ) +1; + *x = i % sy + 1; +} + +int sub2ind(int x,int y, int z, const int s[]) { + int i=(z-1)*s[0]*s[1] + (y-1)*s[0] + (x-1); + if (i<0 || i>s[0]*s[1]*s[2]) i=1; + return i; +} + +float abs2(float n) { if (n<0.0) return -n; else return n; } +float sign(float n) { if (n<0.0) return 1; else return 0.0; } +float max2(float a, float b) { if (a>b) return a; else return b; } + +/* MAINFUNCTION */ +/* ROI, F, 1 */ +void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { + if (nrhs<3) mexErrMsgTxt(""ERROR:cat_vol_simgrow: not enough input elements\n""); + if (nrhs>5) mexErrMsgTxt(""ERROR:cat_vol_simgrow: too many input elements.\n""); + if (nlhs>2) mexErrMsgTxt(""ERROR:cat_vol_simgrow: too many output elements.\n""); + if (mxIsSingle(prhs[0])==0) mexErrMsgTxt(""ERROR:cat_vol_simgrow: first input must be an 3d single matrix\n""); + if (mxIsSingle(prhs[1])==0) mexErrMsgTxt(""ERROR:cat_vol_simgrow: second input must be an 3d single matrix\n""); + if (mxIsDouble(prhs[2])==0 || mxGetNumberOfElements(prhs[2])!=1) mexErrMsgTxt(""ERROR:cat_vol_simgrow: third input must one double value\n""); + + if (nrhs==4 && mxIsDouble(prhs[3])==0) mexErrMsgTxt(""ERROR:cat_vol_simgrow: fourth input must be an double matrix\n""); + if (nrhs==4 && mxGetNumberOfElements(prhs[3])!=3) mexErrMsgTxt(""ERROR:cat_vol_simgrow: fourth input must have 3 Elements""); + if (nrhs==5 && mxIsDouble(prhs[4])==0) mexErrMsgTxt(""ERROR:cat_vol_simgrow: fifth input must be an double matrix\n""); + if (nrhs==5 && mxGetNumberOfElements(prhs[4])!=2) mexErrMsgTxt(""ERROR:cat_vol_simgrow: fifth input must have 2 Elements""); + + /* main information about input data (size, dimensions, ...) */ + const mwSize *sL = mxGetDimensions(prhs[0]); + const int dL = mxGetNumberOfDimensions(prhs[0]); + const int nL = mxGetNumberOfElements(prhs[0]); + const int x = sL[0]; + const int y = sL[1]; + const int xy = x*y; + + const mwSize sSS[2] = {1,3}, sdsv[2] = {1,2}; + mxArray *SS = mxCreateNumericArray(2,sSS, mxDOUBLE_CLASS,mxREAL); double*S = mxGetPr(SS); + mxArray *dsv = mxCreateNumericArray(2,sdsv,mxDOUBLE_CLASS,mxREAL); double*dd = mxGetPr(dsv); + float dI=0.0; double*SEGd; if (nrhs>=3) {SEGd=mxGetPr(prhs[2]); dI=(float) SEGd[0];}; + if (nrhs<4) {S[0]=1.0; S[1]=1.0; S[2]=1.0;} else {S=mxGetPr(prhs[3]);} + if (nrhs<5) {dd[0]=0.1; dd[1]=10.0;} else {dd=mxGetPr(prhs[4]);} + + /* indices of the neighbor Ni (index distance) and euclidean distance NW */ + const int NI[26] = { 1, -1, x, -x, xy,-xy, -x-1,-x+1,x-1,x+1, -xy-1,-xy+1,xy-1,xy+1, -xy-x,-xy+x,xy-x,xy+x, + -xy-x-1,-xy-x+1,-xy+x-1,-xy+x+1, xy-x-1,xy-x+1,xy+x-1,xy+x+1}; + + int ni,u,v,w,nu,nv,nw; + + /* input variables */ + float*ALAB = (float *)mxGetPr(prhs[0]); /* label map */ + float*SEG = (float *)mxGetPr(prhs[1]); /* tissue map */ + + /* main volumes - actual without memory optimization ... */ + mxArray *hlps[1]; + hlps[0] = mxCreateNumericArray(dL,sL,mxSINGLE_CLASS,mxREAL); + float*DIST = (float *)mxGetPr(hlps[0]); /* distance map */ + + /* output variables */ + plhs[0] = mxCreateNumericArray(dL,sL,mxSINGLE_CLASS,mxREAL); /* label map */ + if (nlhs>0) plhs[1] = mxCreateNumericArray(dL,sL,mxSINGLE_CLASS,mxREAL); /* tissue map (speed) */ + /* output variables */ + float*DISTO; + float*SLAB = (float *)mxGetPr(plhs[0]); /* label map */ + if (nlhs>0) DISTO = (float *)mxGetPr(plhs[1]); /* distance map for ouput */ + + + int nCV = 0; /* # voxel of interest (negative voxel that have to processed) */ + int kll = 0; + int nC = 1; + int kllv = 2000; + float Dmax = 0.2; + float DISTN = 0.0; + + + /* initialisation of parameter volumes */ + for (int i=0;i0 && kll0 ) { + kll++; nC=0; + + for (int i=0;i=nL) || (abs(nu-u)>1) || (abs(nv-v)>1) || (abs(nw-w)>1) )==false && + (abs2(SEG[i]-SEG[ni])<(dI*SEG[i]*SEG[i])) && ALAB[ni]==0.0 ) { + DISTN = DIST[i] + abs2(SEG[i]-SEG[ni]) + 0.001; + + if ( (ALAB[ni]==0.0) && (DIST[ni]>0) && (DIST[ni]!=-FLT_MAX) && (abs2(DIST[ni])>abs2(DISTN)) && DISTN0.0) nCV++; nC++; + DIST[ni] = -DISTN; + SLAB[ni] = SLAB[i]; + } + } + } + if (DIST[i]==0.0) DIST[i]=-FLT_MAX; /* demark start points */ + } + } + } + + + for (int i=0;i0) for (int i=0;i +% range(1) where (range(1)>range(2)). If missing, +% display min (for Left) and max (for Right) value from colormap. +% Otherwise should be a 2 element cell array, where +% the first element is the colour value for image values +% left of 'range', and the second is for image values +% right of 'range'. Scalar values for +% colour index the colormap, 3x1 vectors are colour +% values. An empty array attracts default settings +% appropriate to the mode - i.e. transparent colour (where +% SO.prop ~= Inf), or split colour. Empty cells +% default to 0. 0 specifies that voxels with this +% colour do not influence the image (split = +% background, true = black) +% hold - resampling order for image (see spm_sample_vol) - +% default 1 +% background - value when resampling outside image - default +% NaN +% +% - transform - either - 4x4 transformation to apply to image slice position, +% relative to mm given by slicedef, before display +% or - text string, one of axial, coronal, sagittal +% These orientations assume the image is currently +% (after its mat file has been applied) axially +% oriented +% - slicedef - 2x3 array specifying dimensions for slice images in mm +% where rows are x,and y of slice image, and cols are neg max dim, +% slice separation and pos max dim +% - slices - vector of slice positions in mm in z (of transformed image) +% - figure - figure handle for slice display figure +% - refreshf - flag - if set or empty, refresh axis info for figure +% else assume this is OK +% - clf - flag, non zero -> clear figure before display. Redundant +% if refreshf == 0 +% - area struct with fields +% position - bottom left, x size y size 1x4 vector of +% area in which to display slices +% units - one of +% inches,centimeters,normalized,points,{pixels} +% halign - one of left,{center},right +% valign - one of top,{middle},bottom +% - xslices - no of slices to display across figure (defaults to an optimum) +% - cbar - if empty, missing, no colourbar. If an array of integers, then +% indexes img array, and makes colourbar for each cmap for +% that img. Cbars specified in order of appearance L->R +% - labels - struct can be absent (-> default numerical labels) +% empty (SO.labels = []) (no labels) or contain fields +% colour - colour for label text +% size - font size in units normalized to slice axes +% format - if = cell array of strings = +% labels for each slice in Z. If is string, specifies +% sprintf format string for labelling in distance of the +% origin (Xmm=0, Ymm=0) of each slice from plane containing +% the AC, in mm, in the space of the transformed image +% - callback - callback string for button down on image panels. E.g. +% setting SO.callback to 'slice_overlay(''getpos'')' prints to +% the matlab window the equivalent position in mm of the +% position of a mouse click on one of the image slices +% - printstr - string for printing slice overlay figure window, e.g. +% 'print -dpsc -painters -noui' (the default) +% - printfile - name of file to print output to; default 'slices.ps' +% +% FORMAT slice_overlay +% Checks, fills SO struct (slice_overlay('checkso')), and +% displays slice overlay (slice_overlay('display')) +% +% FORMAT slice_overlay('checkso') +% Checks SO structure and sets defaults +% +% FORMAT cmap = slice_overlay('getcmap',cmapname) +% Gets colormap named in cmapname string +% +% FORMAT [mx mn] = slice_overlay('volmaxmin', vol) +% Returns maximum and minimum finite values from vol struct 'vol' +% +% FORMAT slice_overlay('addspm',SPM,dispf) +% Adds SPM blobs as new img to SO struct, split effect, 'hot' colormap, +% SPM structure is generated by calls to SPM results +% if not passed, it is fetched from the workspace +% If dispf is not passed, or nonzero, displays resulting SO figure also +% +% FORMAT slice_overlay('addblobs', imgno, XYZ, vals, mat) +% adds SPM blobs to img no 'imgno', as specified in +% XYZ - 3xN voxel coordinates of N blob values +% vals - N blob intensity values +% mat - 4x4 matrix specifying voxels -> mm +% +% FORMAT vol = slice_overlay('blobs2vol', XYZ, vals, mat) +% returns (pseudo) vol struct for 3d blob volume specified +% in matrices as above +% +% FORMAT slice_overlay('addmatrix', imgno, mat3d, mat) +% adds 3d matrix image vol to img imgno. Optionally +% mat - 4x4 matrix specifying voxels -> mm +% +% FORMAT vol = slice_overlay('matrix2vol', mat3d, mat) +% returns (pseudo) vol struct for 3d matrix +% input matrices as above +% +% FORMAT mmpos = slice_overlay('getpos') +% returns equivalent position in mm of last click on current axes (gca) +% if the axes contain an image slice (empty otherwise) +% +% FORMAT vals = slice_overlay('pointvals', XYZmm, holdlist) +% returns IxN matrix with values of each image 1..I, at each +% point 1..N specified in 3xN mm coordinate matrix XYZmm +% If specified, 'holdlist' contains I values giving hold +% values for resampling for each image (see spm_sample_vol) +% +% FORMAT slice_overlay('display') +% Displays slice overlay from SO struct +% +% FORMAT slice_overlay('print', filename, printstr) +% Prints slice overlay figure, usually to file. If filename is not +% passed/empty gets filename from SO.printfile. If printstr is not +% passed/empty gets printstr from SO.printstr +% +% V 0.8 2/8/00 +% More or less beta - take care. Please report problems to +% Matthew Brett matthew@mrc-cbu.cam.ac.uk + +global SO + +if nargin < 1 + checkso; + action = 'display'; +else + action = lower(action); +end + +switch action + case 'checkso' + checkso; + case 'getcmap' + varargout = {getcmap(varargin{1})}; + case 'volmaxmin' + [mx mn] = volmaxmin(varargin{1}); + varargout = {mx, mn}; + case 'addspm' + if nargin < 2 + varargin{1} = []; + end + if nargin < 3 + varargin{2} = 1; + end + if isempty(varargin{1}) + % Fetch from workspace + errstr = sprintf(['Cannot find SPM variables in the workspace\n'... + 'Please run SPM results GUI']); + V = spm('ver') + switch V(4:end) + case '99' + xSPM = evalin('base', 'SPM', ['error(' errstr ')']); + xSPM.M = evalin('base', 'VOL.M', ['error(' errstr ')']); + case '2' + xSPM = evalin('base', 'xSPM', ['error(' errstr ')']); + otherwise + error(['Strange SPM version ' V]); + end + else + xSPM = varargin{1}; + end + newimg = length(SO.img)+1; + SO.img(newimg).vol = blobs2vol(xSPM.XYZ,xSPM.Z, xSPM.M); + SO.img(newimg).prop = Inf; + SO.img(newimg).cmap = hot; + SO.img(newimg).range = [0 max(xSPM.Z)]; + SO.cbar = [SO.cbar newimg]; + if varargin{2} + checkso; + slice_overlay('display'); + end + + case 'addblobs' + addblobs(varargin{1},varargin{2},varargin{3},varargin{4}); + case 'blobs2vol' + varargout = {blobs2vol(varargin{1},varargin{2},varargin{3})}; + case 'addmatrix' + if nargin<3,varargin{2}='';end + if nargin<4,varargin{3}='';end + addmatrix(varargin{1},varargin{2},varargin{3}); + case 'matrix2vol' + if nargin<3,varargin{2}=[];end + varargout = {matrix2vol(varargin{1},varargin{2})}; + case 'getpos' + varargout = {getpos}; + case 'pointvals' + varargout = {pointvals(varargin{1})}; + case 'print' + if nargin<2,varargin{1}='';end + if nargin<3,varargin{2}='';end + printfig(varargin{1}, varargin{2}); + case 'display' + +% get coordinates for plane +X=1;Y=2;Z=3; +dims = SO.slicedef; +xmm = dims(X,1):dims(X,2):dims(X,3); +ymm = dims(Y,1):dims(Y,2):dims(Y,3); +zmm = SO.slices; +[y x] = meshgrid(ymm,xmm'); +vdims = [length(xmm),length(ymm),length(zmm)]; + +% set default for background color +if ~isfield(SO,'bkg_col') + SO.bkg_col = [0 0 0]; +end + +% no of slices, and panels (an extra for colorbars) +nslices = vdims(Z); +minnpanels = nslices; +cbars = 0; +if is_there(SO,'cbar') + cbars = length(SO.cbar); + minnpanels = minnpanels+cbars; +end + +% get figure data +% if written to, the axes may be specified already +figno = figure(SO.figure); + +% (re)initialize axes and stuff + +% check if the figure is set up correctly +if ~SO.refreshf + axisd = flipud(findobj(SO.figure, 'Type','axes','Tag', 'slice overlay panel')); + npanels = length(axisd); + if npanels < vdims(Z)+cbars; + SO.refreshf = 1; + end +end +if SO.refreshf + % clear figure, axis store + if SO.clf, clf; end + axisd = []; + + % prevent print inversion problems + set(figno,'InvertHardCopy','off'); + + % calculate area of display in pixels + parea = SO.area.position; + if ~strcmp(SO.area.units, 'pixels') + ubu = get(SO.figure, 'units'); + set(SO.figure, 'units','pixels'); + tmp = get(SO.figure, 'Position'); + ascf = tmp(3:4); + if ~strcmp(SO.area.units, 'normalized') + set(SO.figure, 'units',SO.area.units); + tmp = get(SO.figure, 'Position'); + ascf = ascf ./ tmp(3:4); + end + set(figno, 'Units', ubu); + parea = parea .* repmat(ascf, 1, 2); + end + asz = parea(3:4); + + % by default, make most parsimonious fit to figure + yxratio = length(ymm)*dims(Y,2)/(length(xmm)*dims(X,2)); + if ~is_there(SO, 'xslices') + % iteration needed to optimize, surprisingly. Thanks to Ian NS + axlen(X,:)=asz(1):-1:1; + axlen(Y,:)=yxratio*axlen(X,:); + panels = floor(asz'*ones(1,size(axlen,2))./axlen); + estnpanels = prod(panels); + tmp = find(estnpanels >= minnpanels); + if isempty(tmp) + error('Whoops, cannot fit panels onto figure'); + end + b = tmp(1); % best fitting scaling + panels = panels(:,b); + axlen = axlen(:, b); + else + % if xslices is specified, assume X is flush with X figure dimensions + panels([X:Y],1) = [SO.xslices; 0]; + axlen([X:Y],1) = [asz(X)/panels(X); 0]; + end + + % Axis dimensions are in pixels. This prevents aspect ratio rescaling + panels(Y) = ceil(minnpanels/panels(X)); + axlen(Y) = axlen(X)*yxratio; + + % centre (etc) panels in display area as required + divs = [Inf 2 1];the_ds = [0;0]; + the_ds(X) = divs(strcmp(SO.area.halign, {'left','center','right'})); + the_ds(Y) = divs(strcmp(SO.area.valign, {'bottom','middle','top'})); + startc = parea(1:2)' + (asz'-(axlen.*panels))./the_ds; + + % make axes for panels + r=0;c=1; + npanels = prod(panels); + lastempty = npanels-cbars; + for i = 1:npanels + % panel userdata + if i<=nslices + u.type = 'slice'; + u.no = zmm(i); + elseif i > lastempty + u.type = 'cbar'; + u.no = i - lastempty; + else + u.type = 'empty'; + u.no = i - nslices; + end + axpos = [r*axlen(X)+startc(X) (panels(Y)-c)*axlen(Y)+startc(Y) axlen']; + axisd(i) = axes(... + 'Parent',figno,... + 'XTick',[],... + 'XTickLabel',[],... + 'YTick',[],... + 'YTickLabel',[],... + 'Box','on',... + 'XLim',[1 vdims(X)],... + 'YLim',[1 vdims(Y)],... + 'Units', 'pixels',... + 'Position',axpos,... + 'Tag','slice overlay panel',... + 'UserData',u); + r = r+1; + if r >= panels(X) + r = 0; + c = c+1; + end + end +end + +% sort out labels +if is_there(SO,'labels') + labels = SO.labels; + if iscell(labels.format) + if length(labels.format)~=vdims(Z) + error(... + sprintf('Oh dear, expecting %d labels, but found %d',... + vdims(Z), length(labels.contents))); + end + else + % format string for mm from AC labelling + fstr = labels.format; + labels.format = cell(vdims(Z),1); + acpt = SO.transform * [0 0 0 1]'; + for i = 1:vdims(Z) + labels.format(i) = {sprintf(fstr,zmm(i)-acpt(Z))}; + end + end +end + +% modify colormaps with any new colours +nimgs = length(SO.img); +lrn = zeros(nimgs,3); +cmaps = cell(nimgs); +for i = 1:nimgs + cmaps(i)={SO.img(i).cmap}; + lrnv = {SO.img(i).outofrange{:}, SO.img(i).nancol}; + for j = 1:length(lrnv) + if prod(size(lrnv{j}))==1 + lrn(i,j) = lrnv{j}; + else + cmaps(i) = {[cmaps{i}; lrnv{j}(1:3)]}; + lrn(i,j) = size(cmaps{i},1); + end + end +end + +% cycle through slices displaying images +nvox = prod(vdims(1:2)); +pandims = [vdims([2 1]) 3]; % NB XY transpose for display + +zimg = zeros(pandims); +for i = 1:nslices + ixyzmm = [x(:)';y(:)';ones(1,nvox)*zmm(i);ones(1,nvox)]; + img = zimg; + for j = 1:nimgs + thisimg = SO.img(j); + % to voxel space of image + vixyz = inv(SO.transform*thisimg.vol(1).mat)*ixyzmm; + % raw data + if is_there(thisimg.vol(1), 'imgdata') + V = thisimg.vol(1).imgdata; + else + V = thisimg.vol(1); + end + i1 = spm_sample_vol(V,vixyz(X,:),vixyz(Y,:),vixyz(Z,:), ... + [thisimg.hold thisimg.background]); + if is_there(thisimg, 'func') + eval(thisimg.func); + end + % transpose to reverse X and Y for figure + i1 = reshape(i1, vdims(1:2))'; + % make white background if defined + if all(SO.bkg_col == [1 1 1]), i1(i1==0) = 1; end + % rescale to colormap + [csdata badvals]= scaletocmap(... + i1,... + thisimg.range(1),... + thisimg.range(2),... + cmaps{j},... + lrn(j,:)); + % take indices from colormap to make true colour image + iimg = reshape(cmaps{j}(csdata(:),:),pandims); + tmp = repmat(logical(~badvals),[1 1 3]); + if thisimg.prop ~= Inf % truecolor overlay + img(tmp) = img(tmp) + iimg(tmp)*thisimg.prop; + else % split colormap effect + img(tmp) = iimg(tmp); + end + end + + % threshold out of range values + img(img>1) = 1; + + image('Parent', axisd(i),... + 'ButtonDownFcn', SO.callback,... + 'CData',img); + if is_there(SO,'labels') + text('Parent',axisd(i),... + 'Color', labels.colour,... + 'FontUnits', 'normalized',... + 'VerticalAlignment','bottom',... + 'HorizontalAlignment','left',... + 'Position', [1 1],... + 'FontSize',labels.size,... + 'ButtonDownFcn', SO.callback,... + 'String', labels.format{i}); + end +end +for i = (nslices+1):npanels + set(axisd(i),'Color',SO.bkg_col); +end +% add colorbar(s) +for i = 1:cbars + axno = axisd(end-cbars+i); + cbari = SO.img(SO.cbar(i)); + cml = size(cbari.cmap,1); + p = get(axno, 'Position'); % position of last axis + cw = p(3)*0.2; + ch = p(4)*0.75; + pc = p(3:4)/2; + [axlims idxs] = sort(cbari.range); + if ~diff(axlims) + break + end + a=axes(... + 'Parent',figno,... + 'XTick',[],... + 'XTickLabel',[],... + 'Units', 'pixels',... + 'YLim', axlims,... + 'FontUnits', 'normalized',... + 'FontSize', 0.075,... + 'YColor',1 - SO.bkg_col,... + 'Tag', 'cbar',... + 'Box', 'off',... + 'Position',[p(1)+pc(1)-cw/2,p(2)+pc(2)-ch/2,cw,ch]... + ); + ih = image('Parent', a,... + 'YData', axlims(idxs),... + 'CData', reshape(cbari.cmap,[cml,1,3])); + +end + + otherwise + error(sprintf('Unrecognized action string %s', action)); + +% end switch action +end + +return + +function checkso +% checks and fills SO structure +global SO + +% figure +if is_there(SO, 'figure') + try + if ~strcmp(get(SO.figure,'Type'),'figure') + error('Figure handle is not a figure') + end + catch + error('Figure handle is not a valid figure') + end +else + % no figure handle. Try spm figure, then gcf + SO.figure = spm_figure('FindWin', 'Graphics'); + if isempty(SO.figure) + SO.figure = gcf; + end +end +% set defaults for SPM figure +if strcmp(get(SO.figure, 'Tag'),'Graphics') + % position figure nicely for SPM + defstruct = struct('position', [0 0 1 0.92], 'units', 'normalized', ... + 'valign', 'top'); + SO = set_def(SO, 'area', defstruct); + SO.area = set_def(SO.area, 'position', defstruct.position); + SO.area = set_def(SO.area, 'units', defstruct.units); + SO.area = set_def(SO.area, 'valign', defstruct.valign); +end +SO = set_def(SO, 'clf', 1); + +% orientation; string or 4x4 matrix +orientn = []; +SO = set_def(SO, 'transform', 'axial'); +if ischar(SO.transform) + orientn = find(strcmpi(SO.transform, {'axial','coronal','sagittal'})); + if isempty(orientn) + error(sprintf('Unexpected orientation %s', SO.transform)); + end + ts = [0 0 0 0 0 0 1 1 1;... + 0 0 0 pi/2 0 0 1 -1 1;... + 0 0 0 pi/2 0 -pi/2 -1 1 1]; + SO.transform = spm_matrix(ts(orientn,:)); +end +% default slice size, slice matrix depends on orientation +if ~is_there(SO,'slicedef' | ~is_there(SO, 'slices')) + % take image sizes from first image + V = SO.img(1).vol; + D = V.dim(1:3); + T = SO.transform * V.mat; + vcorners = [1 1 1; D(1) 1 1; 1 D(2) 1; D(1:2) 1; ... + 1 1 D(3); D(1) 1 D(3); 1 D(2:3) ; D(1:3)]'; + corners = T * [vcorners; ones(1,8)]; + SC = sort(corners'); + vxsz = sqrt(sum(T(1:3,1:3).^2)); + + SO = set_def(SO, 'slicedef',... + [SC(1,1) vxsz(1) SC(8,1);SC(1,2) vxsz(2) SC(8,2)]); + SO = set_def(SO, 'slices',[SC(1,3):vxsz(3):SC(8,3)]); +end + +% no colourbars by default +SO = set_def(SO, 'cbars', []); + +% always refresh figure window, by default +SO = set_def(SO, 'refreshf', 1); + +% labels +defstruct = struct('colour',1-SO.bkg_col,'size',0.075,'format', '%+3.0f'); +if ~isfield(SO, 'labels') % no field, -> default + SO.labels = defstruct; +elseif ~isempty(SO.labels) % empty -> no labels + % colour for slice labels + SO.labels = set_def(SO.labels, 'colour', defstruct.colour); + % font size normalized to image axis + SO.labels = set_def(SO.labels, 'size', defstruct.size); + % format string for slice labels + SO.labels = set_def(SO.labels, 'format', defstruct.format); +end + +% callback +SO = set_def(SO, 'callback', ';'); + +% figure area stuff +defarea = struct('position',[0 0 1 1],'units','normalized'); +SO = set_def(SO, 'area', defarea); +if ~is_there(SO.area, 'position') + SO.area = defarea; +end +if ~is_there(SO.area,'units') + if (all(SO.area.position>=0 & SO.area.position<=1)) + SO.area.units = 'normalized'; + else + SO.area.units = 'pixels'; + end +end +SO.area = set_def(SO.area,'halign', 'center'); +SO.area = set_def(SO.area,'valign', 'middle'); + +% printing +SO = set_def(SO, 'printstr', 'print -dpsc -painters -noui'); +SO = set_def(SO, 'printfile', 'slices.ps'); + +% fill various img arguments +% would be nice to use set_def, but we can't + +% set colour intensities as we go +remcol = 1; +for i = 1:length(SO.img) + if ~is_there(SO.img(i),'hold') + if ~is_there(SO.img(i).vol,'imgdata') + % normal file vol struct + SO.img(i).hold = 1; + else + % 3d matrix vol struct + SO.img(i).hold = 0; + end + end + if ~is_there(SO.img(i),'background') + SO.img(i).background = NaN; + end + if ~is_there(SO.img(i),'prop') + % default is true colour + SO.img(i).prop = remcol/(length(SO.img)-i+1); + remcol = remcol - SO.img(i).prop; + end + if ~is_there(SO.img(i),'range') + [mx mn] = volmaxmin(SO.img(i).vol); + SO.img(i).range = [mn mx]; + end + if ~is_there(SO.img(i),'cmap') + if SO.img(i).prop == Inf; % split map + if SO.range(1) 1 + img(img>=0 & img<=1)=1; +else + img = img*(cml-1)+1; +end +outvals = {img<1, img>cml, isnan(img)}; +img = round(img); +badvals = zeros(size(img)); +for i = 1:length(lrn) + if lrn(i) + img(outvals{i}) = lrn(i); + else + badvals = badvals | outvals{i}; + img(outvals{i}) = 1; + end +end +return + +function st = set_def(st, fld, def) +if ~is_there(st, fld) + st = setfield(st, fld, def); +end +return + +function addblobs(imgno, xyz,vals,mat) +global SO +if isempty(imgno) + imgno = length(SO.img); +end +if ~isempty(xyz) + SO.img(imgno).vol = blobs2vol(xyz,vals,mat); +end + +function vol = blobs2vol(xyz,vals,mat) +vol = []; +if ~isempty(xyz), + rcp = round(xyz); + vol.dim = max(rcp,[],2)'; + off = rcp(1,:) + vol.dim(1)*(rcp(2,:)-1+vol.dim(2)*(rcp(3,:)-1)); + vol.imgdata = zeros(vol.dim)+NaN; + vol.imgdata(off) = vals; + vol.imgdata = reshape(vol.imgdata,vol.dim); + vol.mat = mat; +end +return + +function addmatrix(imgno,mat3d,mat) +global SO +if isempty(imgno) + imgno = length(SO.img); +end +if nargin<3 + mat = []; +end +if ~isempty(mat3d) + SO.img(imgno).vol = matrix2vol(mat3d,mat); +end + +function vol = matrix2vol(mat3d,mat) +if nargin < 2 + mat = spm_matrix([]); +end +if isempty(mat) + mat = spm_matrix([]); +end +vol = []; +if ~isempty(mat3d) + vol.imgdata = mat3d; + vol.mat = mat; + vol.dim = size(mat3d); +end +return + +function [mx,mn] = volmaxmin(vol) +if is_there(vol, 'imgdata') + tmp = vol.imgdata(finite(vol.imgdata)); + mx = max(tmp); + mn = min(tmp); +else + mx = -Inf;mn=Inf; + for i=1:vol.dim(3), + tmp = spm_slice_vol(vol,spm_matrix([0 0 i]),vol.dim(1:2),[0 NaN]); + tmp = tmp(find(finite(tmp(:)))); + if ~isempty(tmp) + mx = max([mx; tmp]); + mn = min([mn; tmp]); + end + end +end +return + +function cmap = getcmap(acmapname) +% get colormap of name acmapname +if ~isempty(acmapname) + cmap = evalin('base',acmapname,'[]'); + if isempty(cmap) % not a matrix, is it... + % a colour name? + tmp = strcmp(acmapname, {'red','green','blue'}); + if any(tmp) + cmap = zeros(64,3); + cmap(:,tmp) = ((0:63)/63)'; + else + % a .mat file? + [p f e] = fileparts(acmapname); + acmat = fullfile(p, [f '.mat']); + if exist(acmat, 'file') + s = struct2cell(load(acmat)); + cmap = s{1}; + end + end + end +end +if size(cmap, 2)~=3 + warning('Colormap was not an N by 3 matrix') + cmap = []; +end +return + +function mmpos = getpos +% returns point location from last click, in mm +global SO +mmpos=[]; +pos = get(gca, 'CurrentPoint'); +u = get(gca, 'UserData'); +if is_there(u, 'type') + if strcmp(u.type, 'slice') % is slice panel + mmpos = (pos(1,1:2)'-1).*SO.slicedef(:,2)+SO.slicedef(:,1); + mmpos = inv(SO.transform) * [mmpos; u.no; 1]; + mmpos = mmpos(1:3,1); + end +end +return + +function vals = pointvals(XYZmm, holdlist) +% returns values from all the images at points given in XYZmm +global SO +if nargin < 2 + holdlist = [SO.img(:).hold]; +end +X=1;Y=2;Z=3; +nimgs = length(SO.img); +nvals = size(XYZmm,2); +vals = zeros(nimgs,nvals)+NaN; +if size(XYZmm,1)~=4 + XYZmm = [XYZmm(X:Z,:); ones(1,nvals)]; +end +for i = 1:nimgs + I = SO.img(i); + XYZ = I.vol.mat\XYZmm; + if ~is_there(I.vol, 'imgdata') + vol = I.vol; + else + vol = I.vol.imgdata; + end + vals(i,:) = spm_sample_vol(vol, XYZ(X,:), XYZ(Y,:),XYZ(Z,:),[holdlist(i) ... + I.background]); +end +return + +function printfig(filename,printstr) +% print slice overlay figure +% based on spm_figure print, and including fix from thence for ps printing +global SO; +if nargin < 1 + filename = []; +end +if isempty(filename) + filename = SO.printfile; +end +if nargin < 2 + printstr = ''; +end +if isempty(printstr) + printstr = SO.printstr; +end + +%-Note current figure, & switch to figure to print +cF = get(0,'CurrentFigure'); +set(0,'CurrentFigure',SO.figure) + +%-Temporarily change all units to normalized prior to printing +% (Fixes bizarre problem with stuff jumping around!) +%----------------------------------------------------------------------- +H = findobj(get(SO.figure,'Children'),'flat','Type','axes'); +un = cellstr(get(H,'Units')); +set(H,'Units','normalized') + +%-Print +%----------------------------------------------------------------------- +err = 0; +try, eval([printstr ' ' filename]), catch, err=1; end +if err + errstr = lasterr; + tmp = [find(abs(errstr)==10),length(errstr)+1]; + str = {errstr(1:tmp(1)-1)}; + for i = 1:length(tmp)-1 + if tmp(i)+1 < tmp(i+1) + str = [str, {errstr(tmp(i)+1:tmp(i+1)-1)}]; + end + end + str = {str{:}, '','- print command is:',[' ',printstr ' ' filename],... + '','- current directory is:',[' ',pwd],... + '',' * nothing has been printed *'}; + for i=1:length(str) + disp(str{i});end +end + +set(H,{'Units'},un) +set(0,'CurrentFigure',cF) + +return","MATLAB" +"Neurology","ChristianGaser/cat12","cat_vol_ROIval.m",".m","903","25","%cat_vol_ROIval Region-wise statistic. +% Estimation of mean, standard deviation, minimum, maximum, sum, number +% of Yv in a ROI described by an label map Ya. +% +% [mn,std,min,max,sum,num] = cat_vol_ROIval(Ya,Yv) +% +% mn (single) .. mean value +% std (single) .. standard deviation +% min (single) .. minimum of Yv each ROI +% max (single) .. maximum of each ROI +% sum (single) .. sum of all values of each ROI +% num (single) .. number of voxel of each ROI +% Ya (3D uint8) .. label volume +% Yv (3D single) .. data volume +% +% See also compile. +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_vol_imcalc.m",".m","10757","271","function varargout = cat_vol_imcalc(Vi,Vo,f,flags,varargin) +%__________________________________________________________________________ +% Similar to SPM function with some small differences for better use as +% internal function. +% Yo can be aligned as second output and then no ""size warning - use first +% input image properties"" is given and no progress bar is display. +%__________________________________________________________________________ +% +% Perform algebraic functions on images +% FORMAT [Vo, Yo] = cat_vol_imcalc(Vi, Vo, f [,flags [,extra_vars...]]) +% Vi - struct array (from spm_vol) of images to work on +% or a char array of input image filenames +% Vo (input) - struct array (from spm_vol) containing information on +% output image +% ( pinfo field is computed for the resultant image data, ) +% ( and can be omitted from Vo on input. See spm_vol ) +% or output image filename +% f - MATLAB expression to be evaluated +% flags - cell array of flags: {dmtx,mask,interp,dtype} +% or structure with these fieldnames +% dmtx - Read images into data matrix? +% [defaults (missing or empty) to 0 - no] +% mask - implicit zero mask? +% [defaults (missing or empty) to 0] +% ( negative value implies NaNs should be zeroed ) +% interp - interpolation hold (see spm_slice_vol) +% [defaults (missing or empty) to 0 - nearest neighbour] +% dtype - data type for output image (see spm_type) +% [defaults (missing or empty) to 4 - 16 bit signed shorts] +% extra_vars... - additional variables which can be used in expression +% +% Vo (output) - spm_vol structure of output image volume after +% modifications for writing +% Yo - output image +%__________________________________________________________________________ +% +% cat_vol_imcalc performs user-specified algebraic manipulations on a set of +% images, with the result being written out as an image. +% The images specified in Vi, are referred to as i1, i2, i3,... in the +% expression to be evaluated, unless the dmtx flag is setm in which +% case the images are read into a data matrix X, with 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))]. +% +% 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, for data types without a +% representation of NaN. +% +% With images of different sizes and orientations, the size and orientation +% of the reference image is used. Reference is the first image, if +% Vo (input) is a filename, otherwise reference is Vo (input). A +% warning is given in this situation. Images are sampled into this +% orientation using the interpolation specified by the interp parameter. +%__________________________________________________________________________ +% +% Example expressions (f): +% +% i) Mean of six images (select six images) +% f = '(i1+i2+i3+i4+i5+i6)/6' +% ii) Make a binary mask image at threshold of 100 +% f = 'i1>100' +% iii) Make a mask from one image and apply to another +% f = '(i1>100).*i2' +% (here the first image is used to make the mask, which is applied +% to the second image - note the '.*' operator) +% iv) Sum of n images +% f = 'i1 + i2 + i3 + i4 + i5 + ...' +% v) Sum of n images (when reading data into data-matrix) +% f = 'sum(X)' +% vi) Mean of n images (when reading data into data-matrix) +% f = 'mean(X)' +%__________________________________________________________________________ +% +% Furthermore, additional variables for use in the computation can be +% passed at the end of the argument list. These should be referred to by +% the names of the arguments passed in the expression to be evaluated. +% E.g. if c is a 1xn vector of weights, then for n images, using the (dmtx) +% data-matrix version, the weighted sum can be computed using: +% Vi = spm_vol(spm_select(inf,'image')); +% Vo = 'output.img' +% Q = cat_vol_imcalc(Vi,Vo,'c*X',{1},c) +% Here we've pre-specified the expression and passed the vector c as an +% additional variable (you'll be prompted to select the n images). +%__________________________________________________________________________ +% Copyright (C) 1998-2011 Wellcome Trust Centre for Neuroimaging + +% John Ashburner & Andrew Holmes +% Id: spm_imcalc.m 6043 2014-06-13 14:31:48Z volkmar +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +%-Parameters & arguments +%========================================================================== +if nargin < 3 + spm_jobman('interactive','','spm.util.imcalc'); + return; +end + +%-Flags +%-------------------------------------------------------------------------- +if nargin < 4, flags = {}; end +if iscell(flags) + if length(flags) < 5, verb = []; else verb = flags{5}; end + if length(flags) < 4, dtype = []; else dtype = flags{4}; end + if length(flags) < 3, interp = []; else interp = flags{3}; end + if length(flags) < 2, mask = []; else mask = flags{2}; end + if length(flags) < 1, dmtx = []; else dmtx = flags{1}; end +else + if isfield(flags,'dmtx'), dmtx = flags.dmtx; else dmtx = []; end + if isfield(flags,'mask'), mask = flags.mask; else mask = []; end + if isfield(flags,'interp'), interp = flags.interp; else interp = []; end + if isfield(flags,'dtype'), dtype = flags.dtype; else dtype = []; end + if isfield(flags,'verb'), verb = flags.verb; else verb = []; end +end +if ischar(dtype), dtype = spm_type(dtype); end +if isempty(interp), interp = 0; end +if isempty(mask), mask = 0; end +if isempty(dmtx), dmtx = 0; end +if isempty(verb), verb = 0; end +if isempty(dtype), dtype = spm_type('int16'); end + +if verb + spm('FnBanner',mfilename); +end + +%-Input images +%-------------------------------------------------------------------------- +if ~isstruct(Vi), Vi = spm_vol(char(Vi)); end + +if isempty(Vi), error('no input images specified'), end + +if isstruct(Vo) + Vchk = [Vo; Vi(:)]; + refstr = 'output'; +else + Vchk = Vi(:); + refstr = '1st'; +end +[sts, str] = spm_check_orientations(Vchk, false); +if verb + if ~sts + for i=1:size(str,1) + fprintf('Warning: %s - using %s image.\n',strtrim(str(i,:)),refstr); + end + end +end + + + +%-Output image +%-------------------------------------------------------------------------- +if ischar(Vo) + [p, n, e] = spm_fileparts(Vo); + Vo = struct('fname', fullfile(p, [n, e]),... + 'dim', Vi(1).dim(1:3),... + 'dt', [dtype spm_platform('bigend')],... + 'pinfo', [Inf Inf Inf]',... + 'mat', Vi(1).mat,... + 'n', 1,... + 'descrip', 'spm - algebra'); +end + +%-Process any additional variables +%-------------------------------------------------------------------------- +if nargin > 4 + reserved = {'Vi','Vo','f','flags','interp','mask','dmtx','varargin',... + 'dtype','reserved','e','n','Y','p','B','X','i','j','M','d'}; + for i=5:nargin + if isstruct(varargin{i-4}) && ... + isempty(setxor(fieldnames(varargin{i-4}),{'name','value'})) + for j=1:numel(varargin{i-4}) + if any(strcmp(varargin{i-4}(j).name,reserved)) + error(['additional parameter (',varargin{i-4}(j).name,... + ') clashes with internal variable.']) + end + eval([varargin{i-4}(j).name,'=varargin{i-4}(j).value;']); + end + else + if any(strcmp(inputname(i),reserved)) + error(['additional parameter (',inputname(i),... + ') clashes with internal variable.']) + end + eval([inputname(i),' = varargin{i-4};']); + end + end +end + + +%-Computation +%========================================================================== +n = numel(Vi); +Y = zeros(Vo.dim(1:3)); + +%-Start progress plot +%-------------------------------------------------------------------------- +if verb + spm_progress_bar('Init',Vo.dim(3),f,'planes completed'); +end + +%-Loop over planes computing result Y +%-------------------------------------------------------------------------- +for p = 1:Vo.dim(3) + B = spm_matrix([0 0 -p 0 0 0 1 1 1]); + + if dmtx, X = zeros(n,prod(Vo.dim(1:2))); end + for i = 1 + isempty(strfind(f,'i1')):n % use i1 only to get the resolution properties + M = inv(B * inv(Vo.mat) * Vi(i).mat); + d = spm_slice_vol(Vi(i), M, Vo.dim(1:2), [interp,NaN]); + if (mask < 0), + if (mask <-1), + [D,I] = cat_vbdist(single(~(isnan(d))),true(size(d))); clear D; %#ok + d = d(I); clear I; + end + d(isnan(d)) = 0; + end + if (mask > 0) && ~spm_type(Vi(i).dt(1),'nanrep'), d(d==0)=NaN; end + if dmtx, X(i,:) = d(:)'; else eval(sprintf('i%d=d;',i)); end + end + + try + eval(['Yp = ' f ';']); + catch + l = lasterror; + error('%s\nCan''t evaluate ""%s"".',l.message,f); + end + if prod(Vo.dim(1:2)) ~= numel(Yp) + error(['""',f,'"" produced incompatible image.']); end + if (mask < 0), Yp(isnan(Yp)) = 0; end + Y(:,:,p) = reshape(Yp,Vo.dim(1:2)); + + if verb + spm_progress_bar('Set',p); + end +end + +%-Write output image +%-------------------------------------------------------------------------- +if nargout <= 1 + if exist(Vo.fname,'file'); delete(Vo.fname); end + varargout{1} = spm_write_vol(Vo,Y); +elseif nargout == 2 + if isfield(Vo,'dat'); + switch Vo.dt(1) + case 2, Vo.dat = cat_vol_ctype(Y,'uint8'); + case 4, Vo.dat = cat_vol_ctype(Y,'int16'); + case 8, Vo.dat = cat_vol_ctype(Y,'int32'); + case 16, Vo.dat = single(Y); + case 64, Vo.dat = double(Y); + case 256, Vo.dat = cat_vol_ctype(Y,'int8'); + case 512, Vo.dat = cat_vol_ctype(Y,'uint16'); + case 768, Vo.dat = cat_vol_ctype(Y,'uint32'); + end + end + varargout{1} = Vo; + varargout{2} = Y; +end +%-End +%-------------------------------------------------------------------------- +if verb + spm_progress_bar('Clear') +end +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_io_xml.m",".m","86211","2149","function varargout = cat_io_xml(file,varargin) +% ______________________________________________________________________ +% Import/export of a matlab structure from/to a xml file. Use functions +% from Jaroslaw Tuszynski on MATLAB Central (xml_io_tools_2010_11_05). +% Because the XML decoding is very slow, the data is further stored and +% loaded (if available) as MATLAB MAT-file. +% +% cat_io_xml(file,S) export structure to a xml-file +% S = cat_io_xml(file) import structure from a xml-file +% +% ______________________________________________________________________ +% Copyright (c) 2007, Jaroslaw Tuszynski +% All rights reserved. +% +% Redistribution and use in source and binary forms, with or without +% modification, are permitted provided that the following conditions are +% met: +% +% * Redistributions of source code must retain the above copyright +% notice, this list of conditions and the following disclaimer. +% * Redistributions in binary form must reproduce the above copyright +% notice, this list of conditions and the following disclaimer in +% the documentation and/or other materials provided with the distribution +% +% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS"" +% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +% POSSIBILITY OF SUCH DAMAGE. +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + +% Further comments: +% ______________________________________________________________________ +% I also tried the ""struct2xml"" and ""xml2struct"" functions of Wouter +% Falkena, but there were some problems for multi-element structures, +% and fields where set as struct too and the only char is supported for +% datastoring. +% ______________________________________________________________________ + + onlyxml = 0; + + + verbose = 0; + if ~exist('file','var') + file = spm_select(Inf,'xml','Select *.xml files',{},pwd,'^cat.*.xml'); + if isempty(file) + if nargout>0, varargout{1}=struct(); end + return; + end + end + if exist('varargin','var') + if numel(varargin)==0 + action='read'; + elseif isscalar(varargin) + if ischar(varargin{1}) + action='read'; % can only be read yet + else + if isstruct(varargin{1}) + S=varargin{1}; + else + error('cat_io_xml:needStructurToSave','The variable to write has to be a structure.\n'); + end + action='write'; + end + elseif numel(varargin)==2 + S=varargin{1}; action=varargin{2}; + if ~isstruct(S) + error('MATLAB:cat_io_xml','ERROR: Second input should be a structure.\n'); + end + elseif numel(varargin)==3 + S=varargin{1}; action=varargin{2}; verbose=varargin{3}; + if ~isstruct(S) + error('MATLAB:cat_io_xml','ERROR: Second input should be a structure.\n'); + end + else + error('MATLAB:cat_io_xml','ERROR: To many inputs.\n'); + end + end + if (iscell(file) && numel(file)>100) || (ischar(file) && size(file,1)>100) + verbose = 1; + end + + % multi-file read + if strcmp(action,'read') + varargout{1} = struct(); + if verbose, fprintf('% 6d/% 6d',0,numel(cellstr(file))); end + if iscell(file) && numel(file)>1 + spm_progress_bar('Init',numel(file),... + sprintf('read XML\n%d',numel(file)),'Files Completed'); + for fi=1:numel(file) + if ~exist(file{fi},'file'), continue; end + try + tmp = cat_io_xml(file{fi}); + catch + cat_io_cprintf('err','cat_io_xml:readfile',sprintf('Error reading file ""%s"".\nCheck XML structure for missing parts.\n', file{fi})); + end + try + fn = fieldnames(tmp); + for fni = 1:numel(fn) + varargout{1}(fi).(fn{fni}) = tmp.(fn{fni}); + end + clear tmp; + end + if verbose, fprintf('\b\b\b\b\b\b\b\b\b\b\b\b\b% 6d/% 6d',fi,numel(file)); end + spm_progress_bar('Set',fi); + end + + spm_progress_bar('Clear'); + if verbose, fprintf('\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b'); end + return + + elseif ischar(file) && size(file,1)>1 + spm_progress_bar('Init',size(file,1),... + sprintf('read XML\n%s',size(file,1)),'Files Completed'); + for fi=1:size(file,1) + try + if exist(file(fi,:),'file') + tmp = cat_io_xml(file(fi,:)); + else + [pp,ff] = spm_fileparts(file(fi,:)); + xmlfile = fullfile(pp,[ff '.xml']); + if exist(xmlfile,'file') + tmp = cat_io_xml( xmlfile ); + else + cat_io_cprintf('err','cat_io_xml:readfile',sprintf('Cannot find ""%s"" xml/mat file.\n', fullfile(pp,ff))); + end + end + catch + cat_io_cprintf('err','cat_io_xml:readfile',sprintf('Error reading file ""%s"".\nCheck XML structure for missing parts.\n', file(fi,:))); + end + try + fn = fieldnames(tmp); + for fni = 1:numel(fn) + varargout{1}(fi).(fn{fni}) = tmp.(fn{fni}); + end + clear tmp; + end + if verbose, fprintf('\b\b\b\b\b\b\b\b\b\b\b\b\b% 6d/% 6d',fi,numel(file)); end + spm_progress_bar('Set',fi); + end + + spm_progress_bar('Clear'); + if verbose, fprintf('\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b'); end + return + end + end + + if iscell(file) && size(file,1)<=1, file = char(file); end + + [~,ff,ee] = fileparts(file); if ~strcmp(ee,'.xml'), file = [file '.xml']; end + if isempty(ff), return; end + + mfile = [file(1:end-4) '.mat']; + switch action + case 'write' + % ------------------------------------------------------------------ + try + S=orderfields(S); + if ~exist(fileparts(mfile),'dir'), try mkdir(fileparts(mfile)); end; end + save(mfile,'S'); + catch %#ok<*NASGU> % can write xml file?? + % This has to be an error because we need at least the mat for the TIV. + error('MATLAB:cat_io_xml:writeErr','Can''t write MAT-file ''%s''!\n',mfile); + end + try + if usejava('jvm') + xml_write(file,S); + elseif strcmpi(spm_check_version,'octave') + warning off all + savexml(file,'S'); + end + if ~exist(file,'file') + fprint('MATLAB:cat_io_xml:writeErr','Can''t write XML-file ''%s''!\n',file); + end + catch %#ok<*NASGU> % can write xml file?? + % This can be a warning as far as we have the mat. + warning('MATLAB:cat_io_xml:writeErr','Can''t write XML-file ''%s''!\n',file); + end + + + case 'write+' + % ------------------------------------------------------------------ + % WARNING: THIS ACTION NEED MUCH MORE WORK!!! + % ------------------------------------------------------------------ + SN = orderfields(S); + + if exist(mfile,'file') + try + load(mfile,'S'); + catch + if exist(file,'file') + try + if usejava('jvm') + S = xml_read(file); + elseif strcmpi(spm_check_version,'octave') + S = loadxml(file); + end + catch + error('MATLAB:cat_io_xml:write+ReadErr','Can''t read XML-file ''%s'' for update!\n',file); + end + end + end + elseif exist(file,'file') + try + if usejava('jvm') + S = xml_read(file); + elseif strcmpi(spm_check_version,'octave') + S = loadxml(file); + end + catch + error('MATLAB:cat_io_xml:write+ReadErr','Can''t read XML-file ''%s'' for update!\n',file); + end + else + S = struct(); + end + + if numel(S)>1 + error('MATLAB:cat_io_xml:write','Not implemented yet!\n'); + end + + S=cat_io_updateStruct(S,SN); + + try + if ~exist(fileparts(mfile),'dir'), try mkdir(fileparts(mfile)); end; end + save(mfile,'S'); + catch + error('MATLAB:cat_io_xml:writeErr','Can''t write MAT-file ''%s''!\n',mfile); + end + try + if usejava('jvm') + xml_write(file,S); + elseif strcmpi(spm_check_version,'octave') + warning off all + savexml(file,'S'); + end + catch + warning('MATLAB:cat_io_xml:writeErr','Can''t write XML-file ''%s''!\n',file); + end + + + case 'read' + % ------------------------------------------------------------------ + % + if exist(mfile,'file') + try + load(mfile,'S'); + catch + error('MATLAB:cat_io_xml:readErr','Can''t read MAT-file ''%s'' for update!\n',mfile); + end + elseif exist(file,'file') % && usejava('jvm') + try + warning off + if usejava('jvm') + S = xml_read(file); + elseif strcmpi(spm_check_version,'octave') + S = loadxml(file); + end + warning on + catch + error('MATLAB:cat_io_xml:readErr','Can''t read XML-file ''%s'' for update!\n',file); + end + if ~exist(mfile,'file') + try + if ~exist(fileparts(mfile),'dir'), try, mkdir(fileparts(mfile)); end; end + save(mfile,'S'); + catch + error('MATLAB:cat_io_xml:writeErr','Can''t write MAT-file ''%s''!\n',mfile); + end + end + elseif exist(file,'file') && ~(usejava('jvm')) + S = struct(); + else + error('MATLAB:cat_io_xml','""%s"" does not exist!\n',file); + end + + if contains(file,'catROIs_') + FNatlas = fieldnames(S); + for fna = 1:numel(FNatlas) + FNdata = fieldnames(S.(FNatlas{fna}).data); + for fni = 1:numel(FNdata) + if ischar( S.(FNatlas{fna}).data.(FNdata{fni}) ) + S.(FNatlas{fna}).data.(FNdata{fni}) = ... + eval( S.(FNatlas{fna}).data.(FNdata{fni}) ); + end + end + end + end + + otherwise + error('MATLAB:cat_io_xml:read','Unknown action ''%s''!\n',action'); + end + + if nargout==1, varargout{1} = S; end + +end + + +function [tree, RootName, DOMnode] = xml_read(xmlfile, Pref) +%XML_READ reads xml files and converts them into Matlab's struct tree. +% +% DESCRIPTION +% tree = xml_read(xmlfile) reads 'xmlfile' into data structure 'tree' +% +% tree = xml_read(xmlfile, Pref) reads 'xmlfile' into data structure 'tree' +% according to your preferences +% +% [tree, RootName, DOMnode] = xml_read(xmlfile) get additional information +% about XML file +% +% INPUT: +% xmlfile URL or filename of xml file to read +% Pref Preferences: +% Pref.ItemName - default 'item' - name of a special tag used to itemize +% cell arrays +% Pref.ReadAttr - default true - allow reading attributes +% Pref.ReadSpec - default true - allow reading special nodes +% Pref.Str2Num - default 'smart' - convert strings that look like numbers +% to numbers. Options: ""always"", ""never"", and ""smart"" +% Pref.KeepNS - default true - keep or strip namespace info +% Pref.NoCells - default true - force output to have no cell arrays +% Pref.Debug - default false - show mode specific error messages +% Pref.NumLevels- default infinity - how many recursive levels are +% allowed. Can be used to speed up the function by prunning the tree. +% Pref.RootOnly - default true - output variable 'tree' corresponds to +% xml file root element, otherwise it correspond to the whole file. +% Pref.CellItem - default 'true' - leave 'item' nodes in cell notation. +% OUTPUT: +% tree tree of structs and/or cell arrays corresponding to xml file +% RootName XML tag name used for root (top level) node. +% Optionally it can be a string cell array storing: Name of +% root node, document ""Processing Instructions"" data and +% document ""comment"" string +% DOMnode output of xmlread +% +% DETAILS: +% Function xml_read first calls MATLAB's xmlread function and than +% converts its output ('Document Object Model' tree of Java objects) +% to tree of MATLAB struct's. The output is in format of nested structs +% and cells. In the output data structure field names are based on +% XML tags, except in cases when tags produce illegal variable names. +% +% Several special xml node types result in special tags for fields of +% 'tree' nodes: +% - node.CONTENT - stores data section of the node if other fields are +% present. Usually data section is stored directly in 'node'. +% - node.ATTRIBUTE.name - stores node's attribute called 'name'. +% - node.COMMENT - stores node's comment section (string). For global +% comments see ""RootName"" output variable. +% - node.CDATA_SECTION - stores node's CDATA section (string). +% - node.PROCESSING_INSTRUCTIONS - stores ""processing instruction"" child +% node. For global ""processing instructions"" see ""RootName"" output variable. +% - other special node types like: document fragment nodes, document type +% nodes, entity nodes, notation nodes and processing instruction nodes +% will be treated like regular nodes +% +% EXAMPLES: +% MyTree=[]; +% MyTree.MyNumber = 13; +% MyTree.MyString = 'Hello World'; +% xml_write('test.xml', MyTree); +% [tree treeName] = xml_read ('test.xml'); +% disp(treeName) +% gen_object_display() +% % See also xml_examples.m +% +% See also: +% xml_write, xmlread, xmlwrite +% +% Written by Jarek Tuszynski, SAIC, jaroslaw.w.tuszynski_at_saic.com +% References: +% - Function inspired by Example 3 found in xmlread function. +% - Output data structures inspired by xml_toolbox structures. + + % default preferences + DPref.TableName = {'tr','td'}; % name of a special tags used to itemize 2D cell arrays + DPref.ItemName = 'item'; % name of a special tag used to itemize 1D cell arrays + DPref.CellItem = false; % leave 'item' nodes in cell notation + DPref.ReadAttr = true; % allow reading attributes + DPref.ReadSpec = true; % allow reading special nodes: comments, CData, etc. + DPref.KeepNS = true; % Keep or strip namespace info + DPref.Str2Num = 'smart';% convert strings that look like numbers to numbers + DPref.NoCells = true; % force output to have no cell arrays + DPref.NumLevels = 1e10; % number of recurence levels + DPref.PreserveSpace = false; % Preserve or delete spaces at the beggining and the end of stings? + RootOnly = true; % return root node with no top level special nodes + Debug = false; % show specific errors (true) or general (false)? + tree = []; + RootName = []; + + % read user preferences + if (nargin>1) + if (isfield(Pref, 'TableName')), DPref.TableName = Pref.TableName; end + if (isfield(Pref, 'ItemName' )), DPref.ItemName = Pref.ItemName; end + if (isfield(Pref, 'CellItem' )), DPref.CellItem = Pref.CellItem; end + if (isfield(Pref, 'Str2Num' )), DPref.Str2Num = Pref.Str2Num ; end + if (isfield(Pref, 'NoCells' )), DPref.NoCells = Pref.NoCells ; end + if (isfield(Pref, 'NumLevels')), DPref.NumLevels = Pref.NumLevels; end + if (isfield(Pref, 'ReadAttr' )), DPref.ReadAttr = Pref.ReadAttr; end + if (isfield(Pref, 'ReadSpec' )), DPref.ReadSpec = Pref.ReadSpec; end + if (isfield(Pref, 'KeepNS' )), DPref.KeepNS = Pref.KeepNS; end + if (isfield(Pref, 'RootOnly' )), RootOnly = Pref.RootOnly; end + if (isfield(Pref, 'Debug' )), Debug = Pref.Debug ; end + if (isfield(Pref, 'PreserveSpace')), DPref.PreserveSpace = Pref.PreserveSpace; end + end + if ischar(DPref.Str2Num), % convert from character description to numbers + DPref.Str2Num = find(strcmpi(DPref.Str2Num, {'never', 'smart', 'always'}))-1; + if isempty(DPref.Str2Num), DPref.Str2Num=1; end % 1-smart by default + end + + % read xml file using Matlab function + if isa(xmlfile, 'org.apache.xerces.dom.DeferredDocumentImpl'); + % if xmlfile is a DOMnode than skip the call to xmlread + try + %try + DOMnode = xmlfile; + %catch ME + % error('Invalid DOM node: \n%s.', getReport(ME)); + %end + catch %#ok catch for mablab versions prior to 7.5 + error('Invalid DOM node. \n'); + end + else % we assume xmlfile is a filename + if (Debug) % in debuging mode crashes are allowed + DOMnode = xmlread(xmlfile); + else % in normal mode crashes are not allowed + try + %try + DOMnode = xmlread(xmlfile); + %catch ME + % error('Failed to read XML file %s: \n%s',xmlfile, getReport(ME)); + %end + catch %#ok catch for mablab versions prior to 7.5 + error('Failed to read XML file %s\n',xmlfile); + end + end + end + Node = DOMnode.getFirstChild; + + % Find the Root node. Also store data from Global Comment and Processing + % Instruction nodes, if any. + GlobalTextNodes = cell(1,3); + GlobalProcInst = []; + GlobalComment = []; + GlobalDocType = []; + while (~isempty(Node)) + if (Node.getNodeType==Node.ELEMENT_NODE) + RootNode=Node; + elseif (Node.getNodeType==Node.PROCESSING_INSTRUCTION_NODE) + data = strtrim(char(Node.getData)); + target = strtrim(char(Node.getTarget)); + GlobalProcInst = [target, ' ', data]; + GlobalTextNodes{2} = GlobalProcInst; + elseif (Node.getNodeType==Node.COMMENT_NODE) + GlobalComment = strtrim(char(Node.getData)); + GlobalTextNodes{3} = GlobalComment; + % elseif (Node.getNodeType==Node.DOCUMENT_TYPE_NODE) + % GlobalTextNodes{4} = GlobalDocType; + end + Node = Node.getNextSibling; + end + + % parse xml file through calls to recursive DOMnode2struct function + if (Debug) % in debuging mode crashes are allowed + [tree RootName] = DOMnode2struct(RootNode, DPref, 1); + else % in normal mode crashes are not allowed + try + %try + [tree RootName] = DOMnode2struct(RootNode, DPref, 1); + %catch ME + % error('Unable to parse XML file %s: \n %s.',xmlfile, getReport(ME)); + %end + catch %#ok catch for mablab versions prior to 7.5 + error('Unable to parse XML file %s.',xmlfile); + end + end + + % If there were any Global Text nodes than return them + if (~RootOnly) + if (~isempty(GlobalProcInst) && DPref.ReadSpec) + t.PROCESSING_INSTRUCTION = GlobalProcInst; + end + if (~isempty(GlobalComment) && DPref.ReadSpec) + t.COMMENT = GlobalComment; + end + if (~isempty(GlobalDocType) && DPref.ReadSpec) + t.DOCUMENT_TYPE = GlobalDocType; + end + t.(RootName) = tree; + tree=t; + end + if (~isempty(GlobalTextNodes)) + GlobalTextNodes{1} = RootName; + RootName = GlobalTextNodes; + end +end + +% -- begin of mathworks code that is equaly slow ... delete this later -- + function theStruct = parseXML(filename) + % PARSEXML Convert XML file to a MATLAB structure. + try + tree = xmlread(filename); + catch + error('Failed to read XML file %s.',filename); + end + + % Recurse over child nodes. This could run into problems + % with very deeply nested trees. + try + theStruct = parseChildNodes(tree); + catch + error('Unable to parse XML file %s.',filename); + end + end + + % ----- Local function PARSECHILDNODES ----- + function children = parseChildNodes(theNode) + % Recurse over node children. + children = []; + if theNode.hasChildNodes + childNodes = theNode.getChildNodes; + numChildNodes = childNodes.getLength; + allocCell = cell(1, numChildNodes); + + children = struct( ... + 'Name', allocCell, 'Attributes', allocCell, ... + 'Data', allocCell, 'Children', allocCell); + + for count = 1:numChildNodes + theChild = childNodes.item(count-1); + children(count) = makeStructFromNode(theChild); + end + end + end + + % ----- Local function MAKESTRUCTFROMNODE ----- + function nodeStruct = makeStructFromNode(theNode) + % Create structure of node info. + + nodeStruct = struct( ... + 'Name', char(theNode.getNodeName), ... + 'Attributes', parseAttributes(theNode), ... + 'Data', '', ... + 'Children', parseChildNodes(theNode)); + + if any(strcmp(methods(theNode), 'getData')) + nodeStruct.Data = char(theNode.getData); + else + nodeStruct.Data = ''; + end + end + + % ----- Local function PARSEATTRIBUTES ----- + function attributes = parseAttributes(theNode) + % Create attributes structure. + + attributes = []; + if theNode.hasAttributes + theAttributes = theNode.getAttributes; + numAttributes = theAttributes.getLength; + allocCell = cell(1, numAttributes); + attributes = struct('Name', allocCell, 'Value', ... + allocCell); + + for count = 1:numAttributes + attrib = theAttributes.item(count-1); + attributes(count).Name = char(attrib.getName); + attributes(count).Value = char(attrib.getValue); + end + end + end + % -- end of mathworks code -- + + + % ======================================================================= + % === DOMnode2struct Function =========================================== + % ======================================================================= + function [s TagName LeafNode] = DOMnode2struct(node, Pref, level) + + % === Step 1: Get node name and check if it is a leaf node ============== + [TagName LeafNode] = NodeName(node, Pref.KeepNS); + s = []; % initialize output structure + + % === Step 2: Process Leaf Nodes (nodes with no children) =============== + if (LeafNode) + if (LeafNode>1 && ~Pref.ReadSpec), LeafNode=-1; end % tags only so ignore special nodes + if (LeafNode>0) % supported leaf node types + try + %try % use try-catch: errors here are often due to VERY large fields (like images) that overflow java memory + s = char(node.getData); + if (isempty(s)), s = ' '; end % make it a string + % for some reason current xmlread 'creates' a lot of empty text + % fields with first chatacter=10 - those will be deleted. + if (~Pref.PreserveSpace || s(1)==10) + if (isspace(s(1)) || isspace(s(end))), s = strtrim(s); end % trim speces is any + end + if (LeafNode==1), s=str2var(s, Pref.Str2Num, 0); end % convert to number(s) if needed + %catch ME % catch for mablab versions 7.5 and higher + % warning('xml_io_tools:read:LeafRead', ... + % 'This leaf node could not be read and was ignored. '); + % getReport(ME) + %end + catch %#ok catch for mablab versions prior to 7.5 + warning('xml_io_tools:read:LeafRead', ... + 'This leaf node could not be read and was ignored. '); + end + end + if (LeafNode==3) % ProcessingInstructions need special treatment + target = strtrim(char(node.getTarget)); + s = [target, ' ', s]; + end + return % We are done the rest of the function deals with nodes with children + end + if (level>Pref.NumLevels+1), return; end % if Pref.NumLevels is reached than we are done + + % === Step 3: Process nodes with children =============================== + if (node.hasChildNodes) % children present + Child = node.getChildNodes; % create array of children nodes + nChild = Child.getLength; % number of children + + % --- pass 1: how many children with each name ----------------------- + f = []; + for iChild = 1:nChild % read in each child + [cname cLeaf] = NodeName(Child.item(iChild-1), Pref.KeepNS); + if (cLeaf<0), continue; end % unsupported leaf node types + if (~isfield(f,cname)), + f.(cname)=0; % initialize first time I see this name + end + f.(cname) = f.(cname)+1; % add to the counter + end % end for iChild + % text_nodes become CONTENT & for some reason current xmlread 'creates' a + % lot of empty text fields so f.CONTENT value should not be trusted + if (isfield(f,'CONTENT') && f.CONTENT>2), f.CONTENT=2; end + + % --- pass 2: store all the children as struct of cell arrays ---------- + for iChild = 1:nChild % read in each child + [c cname cLeaf] = DOMnode2struct(Child.item(iChild-1), Pref, level+1); + if (cLeaf && isempty(c)) % if empty leaf node than skip + continue; % usually empty text node or one of unhandled node types + elseif (nChild==1 && cLeaf==1) + s=c; % shortcut for a common case + else % if normal node + if (level>Pref.NumLevels), continue; end + n = f.(cname); % how many of them in the array so far? + if (~isfield(s,cname)) % encountered this name for the first time + if (n==1) % if there will be only one of them ... + s.(cname) = c; % than save it in format it came in + else % if there will be many of them ... + s.(cname) = cell(1,n); + s.(cname){1} = c; % than save as cell array + end + f.(cname) = 1; % initialize the counter + else % already have seen this name + s.(cname){n+1} = c; % add to the array + f.(cname) = n+1; % add to the array counter + end + end + end % for iChild + end % end if (node.hasChildNodes) + + % === Step 4: Post-process struct's created for nodes with children ===== + if (isstruct(s)) + fields = fieldnames(s); + nField = length(fields); + + % Detect structure that looks like Html table and store it in cell Matrix + if (nField==1 && strcmpi(fields{1},Pref.TableName{1})) + tr = s.(Pref.TableName{1}); + fields2 = fieldnames(tr{1}); + if (length(fields2)==1 && strcmpi(fields2{1},Pref.TableName{2})) + % This seems to be a special structure such that for + % Pref.TableName = {'tr','td'} 's' corresponds to + % M11 M12 + % M12 M22 + % Recognize it as encoding for 2D struct + nr = length(tr); + for r = 1:nr + row = tr{r}.(Pref.TableName{2}); + Table(r,1:length(row)) = row; %#ok + end + s = Table; + end + end + + % --- Post-processing: convert 'struct of cell-arrays' to 'array of structs' + % Example: let say s has 3 fields s.a, s.b & s.c and each field is an + % cell-array with more than one cell-element and all 3 have the same length. + % Then change it to array of structs, each with single cell. + % This way element s.a{1} will be now accessed through s(1).a + vec = zeros(size(fields)); + for i=1:nField, vec(i) = f.(fields{i}); end + if (numel(vec)>1 && vec(1)>1 && var(vec)==0) % convert from struct of + s = cell2struct(struct2cell(s), fields, 1); % arrays to array of struct + end % if anyone knows better way to do above conversion please let me know. + + end + + % === Step 5: Process nodes with attributes ============================= + if (node.hasAttributes && Pref.ReadAttr) + if (~isstruct(s)), % make into struct if is not already + ss.CONTENT=s; + s=ss; + end + Attr = node.getAttributes; % list of all attributes + for iAttr = 1:Attr.getLength % for each attribute + name = char(Attr.item(iAttr-1).getName); % attribute name + name = str2varName(name, Pref.KeepNS); % fix name if needed + value = char(Attr.item(iAttr-1).getValue); % attribute value + value = str2var(value, Pref.Str2Num, 1); % convert to number if possible + s.ATTRIBUTE.(name) = value; % save again + end % end iAttr loop + end % done with attributes + if (~isstruct(s)), return; end %The rest of the code deals with struct's + + % === Post-processing: fields of ""s"" + % convert 'cell-array of structs' to 'arrays of structs' + fields = fieldnames(s); % get field names + nField = length(fields); + for iItem=1:length(s) % for each struct in the array - usually one + for iField=1:length(fields) + field = fields{iField}; % get field name + % if this is an 'item' field and user want to leave those as cells + % than skip this one + if (strcmpi(field, Pref.ItemName) && Pref.CellItem), continue; end + x = s(iItem).(field); + if (iscell(x) && all(cellfun(@isstruct,x(:))) && numel(x)>1) % it's cell-array of structs + % numel(x)>1 check is to keep 1 cell-arrays created when Pref.CellItem=1 + try % this operation fails sometimes + % example: change s(1).a{1}.b='jack'; s(1).a{2}.b='john'; to + % more convinient s(1).a(1).b='jack'; s(1).a(2).b='john'; + s(iItem).(field) = [x{:}]'; %#ok % converted to arrays of structs + catch %#ok + % above operation will fail if s(1).a{1} and s(1).a{2} have + % different fields. If desired, function forceCell2Struct can force + % them to the same field structure by adding empty fields. + if (Pref.NoCells) + s(iItem).(field) = forceCell2Struct(x); %#ok + end + end % end catch + end + end + end + + % === Step 4: Post-process struct's created for nodes with children ===== + + % --- Post-processing: remove special 'item' tags --------------------- + % many xml writes (including xml_write) use a special keyword to mark + % arrays of nodes (see xml_write for examples). The code below converts + % s.item to s.CONTENT + ItemContent = false; + if (isfield(s,Pref.ItemName)) + s.CONTENT = s.(Pref.ItemName); + s = rmfield(s,Pref.ItemName); + ItemContent = Pref.CellItem; % if CellItem than keep s.CONTENT as cells + end + + % --- Post-processing: clean up CONTENT tags --------------------- + % if s.CONTENT is a cell-array with empty elements at the end than trim + % the length of this cell-array. Also if s.CONTENT is the only field than + % remove .CONTENT part and store it as s. + if (isfield(s,'CONTENT')) + if (iscell(s.CONTENT) && isvector(s.CONTENT)) + x = s.CONTENT; + for i=numel(x):-1:1, if ~isempty(x{i}), break; end; end + if (i==1 && ~ItemContent) + s.CONTENT = x{1}; % delete cell structure + else + s.CONTENT = x(1:i); % delete empty cells + end + end + if (nField==1) + if (ItemContent) + ss = s.CONTENT; % only child: remove a level but ensure output is a cell-array + s=[]; s{1}=ss; + else + s = s.CONTENT; % only child: remove a level + end + end + end + end + % ======================================================================= + % === forceCell2Struct Function ========================================= + % ======================================================================= + function s = forceCell2Struct(x) + % Convert cell-array of structs, where not all of structs have the same + % fields, to a single array of structs + + % Convert 1D cell array of structs to 2D cell array, where each row + % represents item in original array and each column corresponds to a unique + % field name. Array ""AllFields"" store fieldnames for each column + AllFields = fieldnames(x{1}); % get field names of the first struct + CellMat = cell(length(x), length(AllFields)); + for iItem=1:length(x) + fields = fieldnames(x{iItem}); % get field names of the next struct + for iField=1:length(fields) % inspect all fieldnames and find those + field = fields{iField}; % get field name + col = find(strcmp(field,AllFields),1); + if isempty(col) % no column for such fieldname yet + AllFields = [AllFields; field]; %#ok + col = length(AllFields); % create a new column for it + end + CellMat{iItem,col} = x{iItem}.(field); % store rearanged data + end + end + % Convert 2D cell array to array of structs + s = cell2struct(CellMat, AllFields, 2); + end + % ======================================================================= + % === str2var Function ================================================== + % ======================================================================= + function val=str2var(str, option, attribute) + % Can this string 'str' be converted to a number? if so than do it. + val = str; + len = numel(str); + if (len==0 || option==0), return; end % Str2Num=""never"" of empty string -> do not do enything + if (len>10000 && option==1), return; end % Str2Num=""smart"" and string is very long -> probably base64 encoded binary + digits = '(Inf)|(NaN)|(pi)|[\t\n\d\+\-\*\.ei EI\[\]\;\,]'; + s = regexprep(str, digits, ''); % remove all the digits and other allowed characters + if (~all(~isempty(s))) % if nothing left than this is probably a number + if (~isempty(strfind(str, ' '))), option=2; end %if str has white-spaces assume by default that it is not a date string + if (~isempty(strfind(str, '['))), option=2; end % same with brackets + str(strfind(str, '\n')) = ';';% parse data tables into 2D arrays, if any + if (option==1) % the 'smart' option + try % try to convert to a date, like 2007-12-05 + datenum(str); % if successful than leave it as string + catch %#ok % if this is not a date than ... + option=2; % ... try converting to a number + end + end + if (option==2) + if (attribute) + num = str2double(str); % try converting to a single number using sscanf function + if isnan(num), return; end % So, it wasn't really a number after all + else + num = str2num(str); %#ok % try converting to a single number or array using eval function + end + if(isnumeric(num) && numel(num)>0), val=num; end % if convertion to a single was succesful than save + end + elseif ((str(1)=='[' && str(end)==']') || (str(1)=='{' && str(end)=='}')) % this looks like a (cell) array encoded as a string + try + val = eval(str); + catch %#ok + val = str; + end + elseif (~attribute) % see if it is a boolean array with no [] brackets + str1 = lower(str); + str1 = strrep(str1, 'false', '0'); + str1 = strrep(str1, 'true' , '1'); + s = regexprep(str1, '[01 \;\,]', ''); % remove all 0/1, spaces, commas and semicolons + if (~all(~isempty(s))) % if nothing left than this is probably a boolean array + num = str2num(str1); %#ok + if(isnumeric(num) && numel(num)>0), val = (num>0); end % if convertion was succesful than save as logical + end + end + end + % ======================================================================= + % === str2varName Function ============================================== + % ======================================================================= + function str = str2varName(str, KeepNS) + % convert a sting to a valid matlab variable name + if(KeepNS) + str = regexprep(str,':','_COLON_', 'once', 'ignorecase'); + else + k = strfind(str,':'); + if (~isempty(k)) + str = str(k+1:end); + end + end + str = regexprep(str,'-','_DASH_' ,'once', 'ignorecase'); + if (~isvarname(str)) && (~iskeyword(str)) + if strcmpi(spm_check_version,'octave') + str = matlab.lang.makeValidName(str); + else + str = genvarname(str); + end + end + end + % ======================================================================= + % === NodeName Function ================================================= + % ======================================================================= + function [Name LeafNode] = NodeName(node, KeepNS) + % get node name and make sure it is a valid variable name in Matlab. + % also get node type: + % LeafNode=0 - normal element node, + % LeafNode=1 - text node + % LeafNode=2 - supported non-text leaf node, + % LeafNode=3 - supported processing instructions leaf node, + % LeafNode=-1 - unsupported non-text leaf node + switch (node.getNodeType) + case node.ELEMENT_NODE + Name = char(node.getNodeName);% capture name of the node + Name = str2varName(Name, KeepNS); % if Name is not a good variable name - fix it + LeafNode = 0; + case node.TEXT_NODE + Name = 'CONTENT'; + LeafNode = 1; + case node.COMMENT_NODE + Name = 'COMMENT'; + LeafNode = 2; + case node.CDATA_SECTION_NODE + Name = 'CDATA_SECTION'; + LeafNode = 2; + case node.DOCUMENT_TYPE_NODE + Name = 'DOCUMENT_TYPE'; + LeafNode = 2; + case node.PROCESSING_INSTRUCTION_NODE + Name = 'PROCESSING_INSTRUCTION'; + LeafNode = 3; + otherwise + NodeType = {'ELEMENT','ATTRIBUTE','TEXT','CDATA_SECTION', ... + 'ENTITY_REFERENCE', 'ENTITY', 'PROCESSING_INSTRUCTION', 'COMMENT',... + 'DOCUMENT', 'DOCUMENT_TYPE', 'DOCUMENT_FRAGMENT', 'NOTATION'}; + Name = char(node.getNodeName);% capture name of the node + warning('xml_io_tools:read:unkNode', ... + 'Unknown node type encountered: %s_NODE (%s)', NodeType{node.getNodeType}, Name); + LeafNode = -1; + end + end + + +function DOMnode = xml_write(filename, tree, RootName, Pref) +%XML_WRITE Writes Matlab data structures to XML file +% +% DESCRIPTION +% xml_write( filename, tree) Converts Matlab data structure 'tree' containing +% cells, structs, numbers and strings to Document Object Model (DOM) node +% tree, then saves it to XML file 'filename' using Matlab's xmlwrite +% function. Optionally one can also use alternative version of xmlwrite +% function which directly calls JAVA functions for XML writing without +% MATLAB middleware. This function is provided as a patch to existing +% bugs in xmlwrite (in R2006b). +% +% xml_write(filename, tree, RootName, Pref) allows you to specify +% additional preferences about file format +% +% DOMnode = xml_write([], tree) same as above except that DOM node is +% not saved to the file but returned. +% +% INPUT +% filename file name +% tree Matlab structure tree to store in xml file. +% RootName String with XML tag name used for root (top level) node +% Optionally it can be a string cell array storing: Name of +% root node, document ""Processing Instructions"" data and +% document ""comment"" string +% Pref Other preferences: +% Pref.ItemName - default 'item' - name of a special tag used to +% itemize cell or struct arrays +% Pref.XmlEngine - let you choose the XML engine. Currently default is +% 'Xerces', which is using directly the apache xerces java file. +% Other option is 'Matlab' which uses MATLAB's xmlwrite and its +% XMLUtils java file. Both options create identical results except in +% case of CDATA sections where xmlwrite fails. +% Pref.CellItem - default 'true' - allow cell arrays to use 'item' +% notation. See below. +% Pref.RootOnly - default true - output variable 'tree' corresponds to +% xml file root element, otherwise it correspond to the whole file. +% Pref.StructItem - default 'true' - allow arrays of structs to use +% 'item' notation. For example ""Pref.StructItem = true"" gives: +% +% +% ... <\item> +% ... <\item> +% <\b> +% <\a> +% while ""Pref.StructItem = false"" gives: +% +% ... <\b> +% ... <\b> +% <\a> +% +% +% Several special xml node types can be created if special tags are used +% for field names of 'tree' nodes: +% - node.CONTENT - stores data section of the node if other fields +% (usually ATTRIBUTE are present. Usually data section is stored +% directly in 'node'. +% - node.ATTRIBUTE.name - stores node's attribute called 'name'. +% - node.COMMENT - create comment child node from the string. For global +% comments see ""RootName"" input variable. +% - node.PROCESSING_INSTRUCTIONS - create ""processing instruction"" child +% node from the string. For global ""processing instructions"" see +% ""RootName"" input variable. +% - node.CDATA_SECTION - stores node's CDATA section (string). Only works +% if Pref.XmlEngine='Xerces'. For more info, see comments of F_xmlwrite. +% - other special node types like: document fragment nodes, document type +% nodes, entity nodes and notation nodes are not being handled by +% 'xml_write' at the moment. +% +% OUTPUT +% DOMnode Document Object Model (DOM) node tree in the format +% required as input to xmlwrite. (optional) +% +% EXAMPLES: +% MyTree=[]; +% MyTree.MyNumber = 13; +% MyTree.MyString = 'Hello World'; +% xml_write('test.xml', MyTree); +% type('test.xml') +% %See also xml_tutorial.m +% +% See also +% xml_read, xmlread, xmlwrite +% +% Written by Jarek Tuszynski, SAIC, jaroslaw.w.tuszynski_at_saic.com + + % default preferences + DPref.TableName = {'tr','td'}; % name of a special tags used to itemize 2D cell arrays + DPref.ItemName = 'item'; % name of a special tag used to itemize 1D cell arrays + DPref.StructItem = true; % allow arrays of structs to use 'item' notation + DPref.CellItem = true; % allow cell arrays to use 'item' notation + DPref.StructTable= 'Html'; + DPref.CellTable = 'Html'; + DPref.XmlEngine = 'Matlab'; % use matlab provided XMLUtils + %DPref.XmlEngine = 'Xerces'; % use Xerces xml generator directly + DPref.PreserveSpace = false; % Preserve or delete spaces at the beggining and the end of stings? + RootOnly = true; % Input is root node only + GlobalProcInst = []; + GlobalComment = []; + GlobalDocType = []; + + % read user preferences + if (nargin>3) + if (isfield(Pref, 'TableName' )), DPref.TableName = Pref.TableName; end + if (isfield(Pref, 'ItemName' )), DPref.ItemName = Pref.ItemName; end + if (isfield(Pref, 'StructItem')), DPref.StructItem = Pref.StructItem; end + if (isfield(Pref, 'CellItem' )), DPref.CellItem = Pref.CellItem; end + if (isfield(Pref, 'CellTable')), DPref.CellTable = Pref.CellTable; end + if (isfield(Pref, 'StructTable')), DPref.StructTable= Pref.StructTable; end + if (isfield(Pref, 'XmlEngine' )), DPref.XmlEngine = Pref.XmlEngine; end + if (isfield(Pref, 'RootOnly' )), RootOnly = Pref.RootOnly; end + if (isfield(Pref, 'PreserveSpace')), DPref.PreserveSpace = Pref.PreserveSpace; end + end + if (nargin<3 || isempty(RootName)), RootName=inputname(2); end + if (isempty(RootName)), RootName='ROOT'; end + if (iscell(RootName)) % RootName also stores global text node data + rName = RootName; + RootName = char(rName{1}); + if (length(rName)>1), GlobalProcInst = char(rName{2}); end + if (length(rName)>2), GlobalComment = char(rName{3}); end + if (length(rName)>3), GlobalDocType = char(rName{4}); end + end + if(~RootOnly && isstruct(tree)) % if struct than deal with each field separatly + fields = fieldnames(tree); + for i=1:length(fields) + field = fields{i}; + x = tree(1).(field); + if (strcmp(field, 'COMMENT')) + GlobalComment = x; + elseif (strcmp(field, 'PROCESSING_INSTRUCTION')) + GlobalProcInst = x; + elseif (strcmp(field, 'DOCUMENT_TYPE')) + GlobalDocType = x; + else + RootName = field; + t = x; + end + end + tree = t; + end + + % Initialize jave object that will store xml data structure + RootName = varName2str(RootName); + if (~isempty(GlobalDocType)) + % n = strfind(GlobalDocType, ' '); + % if (~isempty(n)) + % dtype = com.mathworks.xml.XMLUtils.createDocumentType(GlobalDocType); + % end + % DOMnode = com.mathworks.xml.XMLUtils.createDocument(RootName, dtype); + warning('xml_io_tools:write:docType', ... + 'DOCUMENT_TYPE node was encountered which is not supported yet. Ignoring.'); + end + DOMnode = com.mathworks.xml.XMLUtils.createDocument(RootName); + + + % Use recursive function to convert matlab data structure to XML + root = DOMnode.getDocumentElement; + struct2DOMnode(DOMnode, root, tree, DPref.ItemName, DPref); + + % Remove the only child of the root node + root = DOMnode.getDocumentElement; + Child = root.getChildNodes; % create array of children nodes + nChild = Child.getLength; % number of children + if (nChild==1) + node = root.removeChild(root.getFirstChild); + while(node.hasChildNodes) + root.appendChild(node.removeChild(node.getFirstChild)); + end + while(node.hasAttributes) % copy all attributes + root.setAttributeNode(node.removeAttributeNode(node.getAttributes.item(0))); + end + end + + % Save exotic Global nodes + if (~isempty(GlobalComment)) + DOMnode.insertBefore(DOMnode.createComment(GlobalComment), DOMnode.getFirstChild()); + end + if (~isempty(GlobalProcInst)) + n = strfind(GlobalProcInst, ' '); + if (~isempty(n)) + proc = DOMnode.createProcessingInstruction(GlobalProcInst(1:(n(1)-1)),... + GlobalProcInst((n(1)+1):end)); + DOMnode.insertBefore(proc, DOMnode.getFirstChild()); + end + end + % Not supported yet as the code below does not work + % if (~isempty(GlobalDocType)) + % n = strfind(GlobalDocType, ' '); + % if (~isempty(n)) + % dtype = DOMnode.createDocumentType(GlobalDocType); + % DOMnode.insertBefore(dtype, DOMnode.getFirstChild()); + % end + % end + + % save java DOM tree to XML file + if (~isempty(filename)) + if (strcmpi(DPref.XmlEngine, 'Xerces')) + xmlwrite_xerces(filename, DOMnode); + else + xmlwrite(filename, DOMnode); + end + end +end + + % ======================================================================= + % === struct2DOMnode Function =========================================== + % ======================================================================= + function [] = struct2DOMnode(xml, parent, s, TagName, Pref) + % struct2DOMnode is a recursive function that converts matlab's structs to + % DOM nodes. + % INPUTS: + % xml - jave object that will store xml data structure + % parent - parent DOM Element + % s - Matlab data structure to save + % TagName - name to be used in xml tags describing 's' + % Pref - preferenced + % OUTPUT: + % parent - modified 'parent' + + % perform some conversions + if (ischar(s) && min(size(s))>1) % if 2D array of characters + s=cellstr(s); % than convert to cell array + end + % if (strcmp(TagName, 'CONTENT')) + % while (iscell(s) && length(s)==1), s = s{1}; end % unwrap cell arrays of length 1 + % end + TagName = varName2str(TagName); + + % == node is a 2D cell array == + % convert to some other format prior to further processing + nDim = nnz(size(s)>1); % is it a scalar, vector, 2D array, 3D cube, etc? + if (iscell(s) && nDim==2 && strcmpi(Pref.CellTable, 'Matlab')) + s = var2str(s, Pref.PreserveSpace); + end + if (nDim==2 && (iscell (s) && strcmpi(Pref.CellTable, 'Vector')) || ... + (isstruct(s) && strcmpi(Pref.StructTable, 'Vector'))) + s = s(:); + end + if (nDim>2), s = s(:); end % can not handle this case well + nItem = numel(s); + nDim = nnz(size(s)>1); % is it a scalar, vector, 2D array, 3D cube, etc? + + % == node is a cell == + if (iscell(s)) % if this is a cell or cell array + if ((nDim==2 && strcmpi(Pref.CellTable,'Html')) || (nDim< 2 && Pref.CellItem)) + % if 2D array of cells than can use HTML-like notation or if 1D array + % than can use item notation + if (strcmp(TagName, 'CONTENT')) % CONTENT nodes already have ... + array2DOMnode(xml, parent, s, Pref.ItemName, Pref ); % recursive call + else + node = xml.createElement(TagName); % ... + array2DOMnode(xml, node, s, Pref.ItemName, Pref ); % recursive call + parent.appendChild(node); + end + else % use ...<\TagName> ...<\TagName> notation + array2DOMnode(xml, parent, s, TagName, Pref ); % recursive call + end + % == node is a struct == + elseif (isstruct(s)) % if struct than deal with each field separatly + if ((nDim==2 && strcmpi(Pref.StructTable,'Html')) || (nItem>1 && Pref.StructItem)) + % if 2D array of structs than can use HTML-like notation or + % if 1D array of structs than can use 'items' notation + node = xml.createElement(TagName); + array2DOMnode(xml, node, s, Pref.ItemName, Pref ); % recursive call + parent.appendChild(node); + elseif (nItem>1) % use ...<\TagName> ...<\TagName> notation + array2DOMnode(xml, parent, s, TagName, Pref ); % recursive call + else % otherwise save each struct separately + fields = fieldnames(s); + node = xml.createElement(TagName); + for i=1:length(fields) % add field by field to the node + field = fields{i}; + x = s.(field); + switch field + case {'COMMENT', 'CDATA_SECTION', 'PROCESSING_INSTRUCTION'} + if iscellstr(x) % cell array of strings -> add them one by one + array2DOMnode(xml, node, x(:), field, Pref ); % recursive call will modify 'node' + elseif ischar(x) % single string -> add it + struct2DOMnode(xml, node, x, field, Pref ); % recursive call will modify 'node' + else % not a string - Ignore + warning('xml_io_tools:write:badSpecialNode', ... + ['Struct field named ',field,' encountered which was not a string. Ignoring.']); + end + case 'ATTRIBUTE' % set attributes of the node + if (isempty(x)), continue; end + if (isstruct(x)) + attName = fieldnames(x); % get names of all the attributes + for k=1:length(attName) % attach them to the node + att = xml.createAttribute(varName2str(attName(k))); + att.setValue(var2str(x.(attName{k}),Pref.PreserveSpace)); + node.setAttributeNode(att); + end + else + warning('xml_io_tools:write:badAttribute', ... + 'Struct field named ATTRIBUTE encountered which was not a struct. Ignoring.'); + end + otherwise % set children of the node + if ~isempty(s.(field)) + struct2DOMnode(xml, node, x, field, Pref ); % recursive call will modify 'node' + end + end + end % end for i=1:nFields + parent.appendChild(node); + end + % == node is a leaf node == + else % if not a struct and not a cell than it is a leaf node + switch TagName % different processing depending on desired type of the node + case 'COMMENT' % create comment node + com = xml.createComment(s); + parent.appendChild(com); + case 'CDATA_SECTION' % create CDATA Section + cdt = xml.createCDATASection(s); + parent.appendChild(cdt); + case 'PROCESSING_INSTRUCTION' % set attributes of the node + OK = false; + if (ischar(s)) + n = strfind(s, ' '); + if (~isempty(n)) + proc = xml.createProcessingInstruction(s(1:(n(1)-1)),s((n(1)+1):end)); + parent.insertBefore(proc, parent.getFirstChild()); + OK = true; + end + end + if (~OK) + warning('xml_io_tools:write:badProcInst', ... + ['Struct field named PROCESSING_INSTRUCTION need to be',... + ' a string, for example: xml-stylesheet type=""text/css"" ', ... + 'href=""myStyleSheet.css"". Ignoring.']); + end + case 'CONTENT' % this is text part of already existing node + txt = xml.createTextNode(var2str(s, Pref.PreserveSpace)); % convert to text + parent.appendChild(txt); + otherwise % I guess it is a regular text leaf node + txt = xml.createTextNode(var2str(s, Pref.PreserveSpace)); + node = xml.createElement(TagName); + node.appendChild(txt); + parent.appendChild(node); + end + end % of struct2DOMnode function + end + % ======================================================================= + % === array2DOMnode Function ============================================ + % ======================================================================= + function [] = array2DOMnode(xml, parent, s, TagName, Pref) + % Deal with 1D and 2D arrays of cell or struct. Will modify 'parent'. + nDim = nnz(size(s)>1); % is it a scalar, vector, 2D array, 3D cube, etc? + switch nDim + case 2 % 2D array + for r=1:size(s,1) + subnode = xml.createElement(Pref.TableName{1}); + for c=1:size(s,2) + v = s(r,c); + if iscell(v), v = v{1}; end + struct2DOMnode(xml, subnode, v, Pref.TableName{2}, Pref ); % recursive call + end + parent.appendChild(subnode); + end + case 1 %1D array + for iItem=1:numel(s) + v = s(iItem); + if iscell(v), v = v{1}; end + struct2DOMnode(xml, parent, v, TagName, Pref ); % recursive call + end + case 0 % scalar -> this case should never be called + if ~isempty(s) + if iscell(s), s = s{1}; end + struct2DOMnode(xml, parent, s, TagName, Pref ); + end + end + end + % ======================================================================= + % === var2str Function ================================================== + % ======================================================================= + function str = var2str(object, PreserveSpace) + % convert matlab variables to a string + switch (1) + case isempty(object) + str = ''; + case (isnumeric(object) || islogical(object)) + if ndims(object)>2, object=object(:); end % can't handle arrays with dimention > 2 + str=mat2str(object); % convert matrix to a string + % mark logical scalars with [] (logical arrays already have them) so the xml_read + % recognizes them as MATLAB objects instead of strings. Same with sparse + % matrices + if ((islogical(object) && isscalar(object)) || issparse(object)), + str = ['[' str ']']; + end + if (isinteger(object)), + str = ['[', class(object), '(', str ')]']; + end + case iscell(object) + if ndims(object)>2, object=object(:); end % can't handle cell arrays with dimention > 2 + [nr nc] = size(object); + obj2 = object; + for i=1:length(object(:)) + str = var2str(object{i}, PreserveSpace); + if (ischar(object{i})), object{i} = ['''' object{i} '''']; else object{i}=str; end + obj2{i} = [object{i} ',']; + end + for r = 1:nr, obj2{r,nc} = [object{r,nc} ';']; end + obj2 = obj2.'; + str = ['{' obj2{:} '}']; + case isstruct(object) + str=''; + warning('xml_io_tools:write:var2str', ... + 'Struct was encountered where string was expected. Ignoring.'); + case isa(object, 'function_handle') + str = ['[@' char(object) ']']; + case ischar(object) + str = object; + otherwise + str = char(object); + end + + % string clean-up + str=str(:); str=str.'; % make sure this is a row vector of char's + if (~isempty(str)) + str(str<32|str==127)=' '; % convert no-printable characters to spaces + if (~PreserveSpace) + str = strtrim(str); % remove spaces from begining and the end + str = regexprep(str,'\s+',' '); % remove multiple spaces + end + end + end + % ======================================================================= + % === var2Namestr Function ============================================== + % ======================================================================= + function str = varName2str(str) + % convert matlab variable names to a sting + str = char(str); + p = strfind(str,'0x'); + if (~isempty(p)) + for i=1:length(p) + before = str( p(i)+(0:3) ); % string to replace + after = char(hex2dec(before(3:4))); % string to replace with + str = regexprep(str,before,after, 'once', 'ignorecase'); + p=p-3; % since 4 characters were replaced with one - compensate + end + end + str = regexprep(str,'_COLON_',':', 'once', 'ignorecase'); + str = regexprep(str,'_DASH_' ,'-', 'once', 'ignorecase'); + end + + + +function varargout=xmlwrite_xerces(varargin) +%XMLWRITE_XERCES Serialize an XML Document Object Model node using Xerces parser. +% xmlwrite_xerces(FILENAME,DOMNODE) serializes the DOMNODE to file FILENAME. +% +% The function xmlwrite_xerces is very similar the Matlab function xmlwrite +% but works directly with the XERCES java classes (written by Apache XML +% Project) instead of the XMLUtils class created by Mathworks. Xerces files +% are provided in standard MATLAB instalation and live in root\java\jarext +% directory. +% +% Written by A.Amaro (02-22-2007) and generously donated to xml_io_tools. +% This function is needed as a work-around for a bug in XMLUtils library +% which can not write CDATA SECTION nodes correctly. Also Xerces and +% XMLUtils libraries handle namespaces differently. +% +% Examples: +% % See xmlwrite examples this function have almost identical behavior. +% +% Advanced use: +% FILENAME can also be a URN, java.io.OutputStream or java.io.Writer object +% SOURCE can also be a SAX InputSource, JAXP Source, InputStream, or +% Reader object + + returnString = false; + if length(varargin)==1 + returnString = true; + result = java.io.StringWriter; + source = varargin{1}; + else + result = varargin{1}; + if ischar(result) + % Using the XERCES classes directly, is not needed to modify the + % filename string. So I have commented this next line + % result = F_xmlstringinput(result,false); + end + + source = varargin{2}; + if ischar(source) + source = F_xmlstringinput(source,true); + end + end + + % SERIALIZATION OF THE DOM DOCUMENT USING XERCES CLASSES DIRECTLY + + % 1) create the output format according to the document definitions + % and type + objOutputFormat = org.apache.xml.serialize.OutputFormat(source); + set(objOutputFormat,'Indenting','on'); + + % 2) create the output stream. In this case: an XML file + objFile = java.io.File(result); + objOutputStream = java.io.FileOutputStream(objFile); + + % 3) Create the Xerces Serializer object + objSerializer= org.apache.xml.serialize.XMLSerializer(objOutputStream,objOutputFormat); + + % 4) Serialize to the XML files + javaMethod('serialize',objSerializer,source); + + % 5) IMPORTANT! Delete the objects to liberate the XML file created + objOutputStream.close; + + if returnString + varargout{1}=char(result.toString); + end + + % ======================================================================== + function out = F_xmlstringinput(xString,isFullSearch,varargin) + % The function F_xmlstringinput is a copy of the private function: + % 'xmlstringinput' that the original xmlwrite function uses. + + if isempty(xString) + error('Filename is empty'); + elseif ~isempty(strfind(xString,'://')) + %xString is already a URL, most likely prefaced by file:// or http:// + out = xString; + return; + end + + xPath=fileparts(xString); + if isempty(xPath) + if nargin<2 || isFullSearch + out = which(xString); + if isempty(out) + error('xml:FileNotFound','File %s not found',xString); + end + else + out = fullfile(pwd,xString); + end + else + out = xString; + if (nargin<2 || isFullSearch) && ~exist(xString,'file') + %search to see if xString exists when isFullSearch + error('xml:FileNotFound','File %s not found',xString); + end + end + + %Return as a URN + if strncmp(out,'\\',2) + % SAXON UNC filepaths need to look like file:///\\\server-name\ + out = ['file:///\',out]; + elseif strncmp(out,'/',1) + % SAXON UNIX filepaths need to look like file:///root/dir/dir + out = ['file://',out]; + else + % DOS filepaths need to look like file:///d:/foo/bar + out = ['file:///',strrep(out,'\','/')]; + end + end +end + + +%{ +function y = base64encode(x, alg, isChunked, url_safe) +%BASE64ENCODE Perform base64 encoding on a string. +% INPUT: +% x - block of data to be encoded. Can be a string or a numeric +% vector containing integers in the range 0-255. +% alg - Algorithm to use: can take values 'java' or 'matlab'. Optional +% variable defaulting to 'java' which is a little faster. If +% 'java' is chosen than core of the code is performed by a call to +% a java library. Optionally all operations can be performed using +% matleb code. +% isChunked - encode output into 76 character blocks. The returned +% encoded string is broken into lines of no more than +% 76 characters each, and each line will end with EOL. Notice that +% if resulting string is saved as part of an xml file, those EOL's +% are often stripped by xmlwrite funtrion prior to saving. +% url_safe - use Modified Base64 for URL applications ('base64url' +% encoding) ""Base64 alphabet"" ([A-Za-z0-9-_=]). +% +% +% OUTPUT: +% y - character array using only ""Base64 alphabet"" characters +% +% This function may be used to encode strings into the Base64 encoding +% specified in RFC 2045 - MIME (Multipurpose Internet Mail Extensions). +% The Base64 encoding is designed to represent arbitrary sequences of +% octets in a form that need not be humanly readable. A 65-character +% subset ([A-Za-z0-9+/=]) of US-ASCII is used, enabling 6 bits to be +% represented per printable character. +% +% See also BASE64DECODE. +% +% Written by Jarek Tuszynski, SAIC, jaroslaw.w.tuszynski_at_saic.com +% +% Matlab version based on 2004 code by Peter J. Acklam +% E-mail: pjacklam@online.no +% URL: http://home.online.no/~pjacklam +% http://home.online.no/~pjacklam/matlab/software/util/datautil/base64encode.m + + if nargin<2, alg='java'; end + if nargin<3, isChunked=false; end + if ~islogical(isChunked) + if isnumeric(isChunked) + isChunked=(isChunked>0); + else + isChunked=false; + end + end + if nargin<4, url_safe=false; end + if ~islogical(url_safe) + if isnumeric(url_safe) + url_safe=(url_safe>0); + else + url_safe=false; + end + end + + + % if x happen to be a filename than read the file + if (numel(x)<256) + if (exist(x, 'file')==2) + fid = fopen(x,'rb'); + x = fread(fid, 'uint8'); % read image file as a raw binary + fclose(fid); + end + end + + % Perform conversion + switch (alg) + case 'java' + base64 = org.apache.commons.codec.binary.Base64; + y = base64.encodeBase64(x, isChunked); + if url_safe + y = strrep(y,'=','-'); + y = strrep(y,'/','_'); + end + + case 'matlab' + + % add padding if necessary, to make the length of x a multiple of 3 + x = uint8(x(:)); + ndbytes = length(x); % number of decoded bytes + nchunks = ceil(ndbytes / 3); % number of chunks/groups + if rem(ndbytes, 3)>0 + x(end+1 : 3*nchunks) = 0; % add padding + end + x = reshape(x, [3, nchunks]); % reshape the data + y = repmat(uint8(0), 4, nchunks); % for the encoded data + + % Split up every 3 bytes into 4 pieces + % aaaaaabb bbbbcccc ccdddddd + % to form + % 00aaaaaa 00bbbbbb 00cccccc 00dddddd + y(1,:) = bitshift(x(1,:), -2); % 6 highest bits of x(1,:) + y(2,:) = bitshift(bitand(x(1,:), 3), 4); % 2 lowest bits of x(1,:) + y(2,:) = bitor(y(2,:), bitshift(x(2,:), -4)); % 4 highest bits of x(2,:) + y(3,:) = bitshift(bitand(x(2,:), 15), 2); % 4 lowest bits of x(2,:) + y(3,:) = bitor(y(3,:), bitshift(x(3,:), -6)); % 2 highest bits of x(3,:) + y(4,:) = bitand(x(3,:), 63); % 6 lowest bits of x(3,:) + + % Perform the mapping + % 0 - 25 -> A-Z + % 26 - 51 -> a-z + % 52 - 61 -> 0-9 + % 62 -> + + % 63 -> / + map = ['A':'Z', 'a':'z', '0':'9', '+/']; + if (url_safe), map(63:64)='-_'; end + y = map(y(:)+1); + + % Add padding if necessary. + npbytes = 3 * nchunks - ndbytes; % number of padding bytes + if npbytes>0 + y(end-npbytes+1 : end) = '='; % '=' is used for padding + end + + % break into lines with length LineLength + if (isChunked) + eol = sprintf('\n'); + nebytes = numel(y); + nlines = ceil(nebytes / 76); % number of lines + neolbytes = length(eol); % number of bytes in eol string + + % pad data so it becomes a multiple of 76 elements + y(nebytes + 1 : 76 * nlines) = 0; + y = reshape(y, 76, nlines); + + % insert eol strings + y(end + 1 : end + neolbytes, :) = eol(:, ones(1, nlines)); + + % remove padding, but keep the last eol string + m = nebytes + neolbytes * (nlines - 1); + n = (76+neolbytes)*nlines - neolbytes; + y(m+1 : n) = []; + end + end + + % reshape to a row vector and make it a character array + y = char(reshape(y, 1, numel(y))); +end +function y = base64decode(x, outfname, alg) + %BASE64DECODE Perform base64 decoding on a string. + % + % INPUT: + % x - block of data to be decoded. Can be a string or a numeric + % vector containing integers in the range 0-255. Any character + % not part of the 65-character base64 subset set is silently + % ignored. Characters occuring after a '=' padding character are + % never decoded. If the length of the string to decode (after + % ignoring non-base64 chars) is not a multiple of 4, then a + % warning is generated. + % + % outfname - if provided the binary date from decoded string will be + % saved into a file. Since Base64 coding is often used to embbed + % binary data in xml files, this option can be used to extract and + % save them. + % + % alg - Algorithm to use: can take values 'java' or 'matlab'. Optional + % variable defaulting to 'java' which is a little faster. If + % 'java' is chosen than core of the code is performed by a call to + % a java library. Optionally all operations can be performed using + % matleb code. + % + % OUTPUT: + % y - array of binary data returned as uint8 + % + % This function is used to decode strings from the Base64 encoding specified + % in RFC 2045 - MIME (Multipurpose Internet Mail Extensions). The Base64 + % encoding is designed to represent arbitrary sequences of octets in a form + % that need not be humanly readable. A 65-character subset ([A-Za-z0-9+/=]) + % of US-ASCII is used, enabling 6 bits to be represented per printable + % character. + % + % See also BASE64ENCODE. + % + % Written by Jarek Tuszynski, SAIC, jaroslaw.w.tuszynski_at_saic.com + % + % Matlab version based on 2004 code by Peter J. Acklam + % E-mail: pjacklam@online.no + % URL: http://home.online.no/~pjacklam + % http://home.online.no/~pjacklam/matlab/software/util/datautil/base64encode.m + + if nargin<3, alg='java'; end + if nargin<2, outfname=''; end + + % if x happen to be a filename than read the file + if (numel(x)<256) + if (exist(x, 'file')==2) + fid = fopen(x,'rb'); + x = fread(fid, 'uint8'); + fclose(fid); + end + end + x = uint8(x(:)); % unify format + + % Perform conversion + switch (alg) + case 'java' + base64 = org.apache.commons.codec.binary.Base64; + y = base64.decode(x); + y = mod(int16(y),256); % convert from int8 to uint8 + case 'matlab' + % Perform the mapping + % A-Z -> 0 - 25 + % a-z -> 26 - 51 + % 0-9 -> 52 - 61 + % + - -> 62 '-' is URL_SAFE alternative + % / _ -> 63 '_' is URL_SAFE alternative + map = uint8(zeros(1,256)+65); + map(uint8(['A':'Z', 'a':'z', '0':'9', '+/=']))= 0:64; + map(uint8('-_'))= 62:63; % URL_SAFE alternatives + x = map(x); % mapping + + x(x>64)=[]; % remove non-base64 chars + if rem(numel(x), 4) + warning('Length of base64 data not a multiple of 4; padding input.'); + end + x(x==64)=[]; % remove padding characters + + % add padding and reshape + nebytes = length(x); % number of encoded bytes + nchunks = ceil(nebytes/4); % number of chunks/groups + if rem(nebytes, 4)>0 + x(end+1 : 4*nchunks) = 0; % add padding + end + x = reshape(uint8(x), 4, nchunks); + y = repmat(uint8(0), 3, nchunks); % for the decoded data + + % Rearrange every 4 bytes into 3 bytes + % 00aaaaaa 00bbbbbb 00cccccc 00dddddd + % to form + % aaaaaabb bbbbcccc ccdddddd + y(1,:) = bitshift(x(1,:), 2); % 6 highest bits of y(1,:) + y(1,:) = bitor(y(1,:), bitshift(x(2,:), -4)); % 2 lowest bits of y(1,:) + y(2,:) = bitshift(x(2,:), 4); % 4 highest bits of y(2,:) + y(2,:) = bitor(y(2,:), bitshift(x(3,:), -2)); % 4 lowest bits of y(2,:) + y(3,:) = bitshift(x(3,:), 6); % 2 highest bits of y(3,:) + y(3,:) = bitor(y(3,:), x(4,:)); % 6 lowest bits of y(3,:) + + % remove extra padding + switch rem(nebytes, 4) + case 2 + y = y(1:end-2); + case 3 + y = y(1:end-1); + end + end + + % reshape to a row vector and make it a character array + y = uint8(reshape(y, 1, numel(y))); + + % save to file if needed + if ~isempty(outfname) + fid = fopen(outfname,'wb'); + fwrite(fid, y, 'uint8'); + fclose(fid); + end +end +%} + + + +%{ +This works only for special structures... grummel. + +% struct2xml - function: +% __________________________________________________________________________________________________ + +function varargout = struct2xml( s, varargin ) +%Convert a MATLAB structure into a xml file +% [ ] = struct2xml( s, file ) +% xml = struct2xml( s ) +% +% A structure containing: +% s.XMLname.Attributes.attrib1 = ""Some value""; +% s.XMLname.Element.Text = ""Some text""; +% s.XMLname.DifferentElement{1}.Attributes.attrib2 = ""2""; +% s.XMLname.DifferentElement{1}.Text = ""Some more text""; +% s.XMLname.DifferentElement{2}.Attributes.attrib3 = ""2""; +% s.XMLname.DifferentElement{2}.Attributes.attrib4 = ""1""; +% s.XMLname.DifferentElement{2}.Text = ""Even more text""; +% +% Will produce: +% +% Some text +% Some more text +% Even more text +% +% +% Please note that the following strings are substituted +% '_dash_' by '-', '_colon_' by ':' and '_dot_' by '.' +% +% Written by W. Falkena, ASTI, TUDelft, 27-08-2010 +% On-screen output functionality added by P. Orth, 01-12-2010 +% Multiple space to single space conversion adapted for speed by T. Lohuis, 11-04-2011 +% Val2str subfunction bugfix by H. Gsenger, 19-9-2011 + + if (nargin ~= 2) + if(nargout ~= 1 || nargin ~= 1) + error(['Supported function calls:' sprintf('\n')... + '[ ] = struct2xml( s, file )' sprintf('\n')... + 'xml = struct2xml( s )']); + end + end + + if(nargin == 2) + file = varargin{1}; + + if (isempty(file)) + error('Filename can not be empty'); + end + + if (isempty(strfind(file,'.xml'))) + file = [file '.xml']; + end + end + + if (~isstruct(s)) + error([inputname(1) ' is not a structure']); + end + + if (length(fieldnames(s)) > 1) + error(['Error processing the structure:' sprintf('\n') 'There should be a single field in the main structure.']); + end + xmlname = fieldnames(s); + xmlname = xmlname{1}; + + %substitute special characters + xmlname_sc = xmlname; + xmlname_sc = strrep(xmlname_sc,'_dash_','-'); + xmlname_sc = strrep(xmlname_sc,'_colon_',':'); + xmlname_sc = strrep(xmlname_sc,'_dot_','.'); + + %create xml structure + docNode = com.mathworks.xml.XMLUtils.createDocument(xmlname_sc); + + %process the rootnode + docRootNode = docNode.getDocumentElement; + + %append childs + parseStruct(s.(xmlname),docNode,docRootNode,[inputname(1) '.' xmlname '.']); + + if(nargout == 0) + %save xml file + xmlwrite(file,docNode); + else + varargout{1} = xmlwrite(docNode); + end +end + +% ----- Subfunction parseStruct ----- +function [] = parseStruct(s,docNode,curNode,pName) + + fnames = fieldnames(s); + for i = 1:length(fnames) + curfield = fnames{i}; + + %substitute special characters + curfield_sc = curfield; + curfield_sc = strrep(curfield_sc,'_dash_','-'); + curfield_sc = strrep(curfield_sc,'_colon_',':'); + curfield_sc = strrep(curfield_sc,'_dot_','.'); + + if (strcmp(curfield,'Attributes')) + %Attribute data + if (isstruct(s.(curfield))) + attr_names = fieldnames(s.Attributes); + for a = 1:length(attr_names) + cur_attr = attr_names{a}; + + %substitute special characters + cur_attr_sc = cur_attr; + cur_attr_sc = strrep(cur_attr_sc,'_dash_','-'); + cur_attr_sc = strrep(cur_attr_sc,'_colon_',':'); + cur_attr_sc = strrep(cur_attr_sc,'_dot_','.'); + + [cur_str,succes] = val2str(s.Attributes.(cur_attr)); + if (succes) + curNode.setAttribute(cur_attr_sc,cur_str); + else + disp(['Warning. The text in ' pName curfield '.' cur_attr ' could not be processed.']); + end + end + else + disp(['Warning. The attributes in ' pName curfield ' could not be processed.']); + disp(['The correct syntax is: ' pName curfield '.attribute_name = ''Some text''.']); + end + elseif (strcmp(curfield,'Text')) + %Text data + [txt,succes] = val2str(s.Text); + if (succes) + curNode.appendChild(docNode.createTextNode(txt)); + else + disp(['Warning. The text in ' pName curfield ' could not be processed.']); + end + else + %Sub-element + if (isstruct(s.(curfield))) + %single element + curElement = docNode.createElement(curfield_sc); + curNode.appendChild(curElement); + parseStruct(s.(curfield),docNode,curElement,[pName curfield '.']) + elseif (iscell(s.(curfield))) + %multiple elements + for c = 1:length(s.(curfield)) + curElement = docNode.createElement(curfield_sc); + curNode.appendChild(curElement); + if (isstruct(s.(curfield){c})) + parseStruct(s.(curfield){c},docNode,curElement,[pName curfield '{' num2str(c) '}.']) + else + disp(['Warning. The cell ' pName curfield '{' num2str(c) '} could not be processed, since it contains no structure.']); + end + end + else + %eventhough the fieldname is not text, the field could + %contain text. Create a new element and use this text + curElement = docNode.createElement(curfield_sc); + curNode.appendChild(curElement); + [txt,succes] = val2str(s.(curfield)); + if (succes) + curElement.appendChild(docNode.createTextNode(txt)); + else + disp(['Warning. The text in ' pName curfield ' could not be processed.']); + end + end + end + end +end + +%----- Subfunction val2str ----- +function [str,succes] = val2str(val) + + succes = true; + str = []; + + if (isempty(val)) + return; %bugfix from H. Gsenger + elseif (ischar(val)) + %do nothing + elseif (isnumeric(val)) + val = num2str(val); + else + succes = false; + end + + if (ischar(val)) + %add line breaks to all lines except the last (for multiline strings) + lines = size(val,1); + val = [val char(sprintf('\n')*[ones(lines-1,1);0])]; + + %transpose is required since indexing (i.e., val(nonspace) or val(:)) produces a 1-D vector. + %This should be row based (line based) and not column based. + valt = val'; + + remove_multiple_white_spaces = true; + if (remove_multiple_white_spaces) + %remove multiple white spaces using isspace, suggestion of T. Lohuis + whitespace = isspace(val); + nonspace = (whitespace + [zeros(lines,1) whitespace(:,1:end-1)])~=2; + nonspace(:,end) = [ones(lines-1,1);0]; %make sure line breaks stay intact + str = valt(nonspace'); + else + str = valt(:); + end + end +end + + +% xml2struct - function: +% __________________________________________________________________________________________________ + +function [ s ] = xml2struct( file ) +%Convert xml file into a MATLAB structure +% [ s ] = xml2struct( file ) +% +% A file containing: +% +% Some text +% Some more text +% Even more text +% +% +% Will produce: +% s.XMLname.Attributes.attrib1 = ""Some value""; +% s.XMLname.Element.Text = ""Some text""; +% s.XMLname.DifferentElement{1}.Attributes.attrib2 = ""2""; +% s.XMLname.DifferentElement{1}.Text = ""Some more text""; +% s.XMLname.DifferentElement{2}.Attributes.attrib3 = ""2""; +% s.XMLname.DifferentElement{2}.Attributes.attrib4 = ""1""; +% s.XMLname.DifferentElement{2}.Text = ""Even more text""; +% +% Please note that the following characters are substituted +% '-' by '_dash_', ':' by '_colon_' and '.' by '_dot_' +% +% Written by W. Falkena, ASTI, TUDelft, 21-08-2010 +% Attribute parsing speed increased by 40% by A. Wanner, 14-6-2011 +% Added CDATA support by I. Smirnov, 20-3-2012 +% +% Modified by X. Mo, University of Wisconsin, 12-5-2012 + + if (nargin < 1) + clc; + help xml2struct + return + end + + if isa(file, 'org.apache.xerces.dom.DeferredDocumentImpl') || isa(file, 'org.apache.xerces.dom.DeferredElementImpl') + % input is a java xml object + xDoc = file; + else + %check for existance + if (exist(file,'file') == 0) + %Perhaps the xml extension was omitted from the file name. Add the + %extension and try again. + if (isempty(strfind(file,'.xml'))) + file = [file '.xml']; + end + + if (exist(file,'file') == 0) + error(['The file ' file ' could not be found']); + end + end + %read the xml file + xDoc = xmlread(file); + end + + %parse xDoc into a MATLAB structure + s = parseChildNodes(xDoc); + +end + +% ----- Subfunction parseChildNodes ----- +function [children,ptext,textflag] = parseChildNodes(theNode) + % Recurse over node children. + children = struct; + ptext = struct; textflag = 'Text'; + if hasChildNodes(theNode) + childNodes = getChildNodes(theNode); + numChildNodes = getLength(childNodes); + + for count = 1:numChildNodes + theChild = item(childNodes,count-1); + [text,name,attr,childs,textflag] = getNodeData(theChild); + + if (~strcmp(name,'#text') && ~strcmp(name,'#comment') && ~strcmp(name,'#cdata_dash_section')) + %XML allows the same elements to be defined multiple times, + %put each in a different cell + if (isfield(children,name)) + if (~iscell(children.(name))) + %put existsing element into cell format + children.(name) = {children.(name)}; + end + index = length(children.(name))+1; + %add new element + children.(name){index} = childs; + if(~isempty(fieldnames(text))) + children.(name){index} = text; + end + if(~isempty(attr)) + children.(name){index}.('Attributes') = attr; + end + else + %add previously unknown (new) element to the structure + children.(name) = childs; + if(~isempty(text) && ~isempty(fieldnames(text))) + children.(name) = text; + end + if(~isempty(attr)) + children.(name).('Attributes') = attr; + end + end + else + ptextflag = 'Text'; + if (strcmp(name, '#cdata_dash_section')) + ptextflag = 'CDATA'; + elseif (strcmp(name, '#comment')) + ptextflag = 'Comment'; + end + + %this is the text in an element (i.e., the parentNode) + if (~isempty(regexprep(text.(textflag),'[\s]*',''))) + if (~isfield(ptext,ptextflag) || isempty(ptext.(ptextflag))) + ptext.(ptextflag) = text.(textflag); + else + %what to do when element data is as follows: + %Text More text + + %put the text in different cells: + % if (~iscell(ptext)) ptext = {ptext}; end + % ptext{length(ptext)+1} = text; + + %just append the text + ptext.(ptextflag) = [ptext.(ptextflag) text.(textflag)]; + end + end + end + + end + end +end + +% ----- Subfunction getNodeData ----- +function [text,name,attr,childs,textflag] = getNodeData(theNode) + % Create structure of node info. + + %make sure name is allowed as structure name + name = toCharArray(getNodeName(theNode))'; + name = strrep(name, '-', '_dash_'); + name = strrep(name, ':', '_colon_'); + name = strrep(name, '.', '_dot_'); + + attr = parseAttributes(theNode); + if (isempty(fieldnames(attr))) + attr = []; + end + + %parse child nodes + [childs,text,textflag] = parseChildNodes(theNode); + + if (isempty(fieldnames(childs)) && isempty(fieldnames(text))) + %get the data of any childless nodes + % faster than if any(strcmp(methods(theNode), 'getData')) + % no need to try-catch (?) + % faster than text = char(getData(theNode)); + text.(textflag) = toCharArray(getTextContent(theNode))'; + end + +end + +% ----- Subfunction parseAttributes ----- +function attributes = parseAttributes(theNode) + % Create attributes structure. + + attributes = struct; + if hasAttributes(theNode) + theAttributes = getAttributes(theNode); + numAttributes = getLength(theAttributes); + + for count = 1:numAttributes + %attrib = item(theAttributes,count-1); + %attr_name = regexprep(char(getName(attrib)),'[-:.]','_'); + %attributes.(attr_name) = char(getValue(attrib)); + + %Suggestion of Adrian Wanner + str = toCharArray(toString(item(theAttributes,count-1)))'; + k = strfind(str,'='); + attr_name = str(1:(k(1)-1)); + attr_name = strrep(attr_name, '-', '_dash_'); + attr_name = strrep(attr_name, ':', '_colon_'); + attr_name = strrep(attr_name, '.', '_dot_'); + attributes.(attr_name) = str((k(1)+2):(end-1)); + end + end +end + +%} + + +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_install_atlases.m",".m","3397","111","function cat_install_atlases +% Convert CAT12 atlas files (csv) and add Dartel atlas labels to spm12 +% atlas folder (xml) +% +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +spm_dir = spm('dir'); +atlas_dir = fullfile(spm_dir,'atlas'); +[ST, RS] = mkdir(atlas_dir); + +if ST + [csv_files, n] = cat_vol_findfiles(cat_get_defaults('extopts.pth_templates'), '*.csv'); + for i = 1:n + csv_file = deblank(csv_files{i}); + csv = cat_io_csv(csv_file,'','',struct('delimiter',';')); + [pth,nam] = spm_fileparts(csv_file); + xml_file = fullfile(atlas_dir, ['labels_cat12_' nam '.xml']); + old_xml_file = fullfile(atlas_dir, ['labels_dartel_' nam '.xml']); + create_spm_atlas_xml(xml_file, csv); + atlas_file = fullfile(pth,[nam '.nii']); + new_atlas_name = ['cat12_' nam '.nii']; + try + copyfile(atlas_file,fullfile(atlas_dir,new_atlas_name),'f'); + if exist(old_xml_file,'file'), delete(old_xml_file); end + fprintf('Install %s\n',xml_file); + catch + disp('Writing error: Please check file permissions.'); + end + end +else + error(RS); +end + +% this is maybe not enough, to update the file in SPM functions +% you may need to remove the old files and finish SPM, update and restart SPM +spm_atlas('list','installed','-refresh'); + +fprintf('\nUse atlas function in SPM Results or context menu in orthogonal view (via right mouse button): Display|Labels\n'); + +function create_spm_atlas_xml(fname,csvx,opt) +% create an spm12 compatible xml version of the csv data +if ~exist('opt','var'), opt = struct(); end + +[pp,ff,ee] = spm_fileparts(fname); + +% remove prepending name part +if ~isempty(strfind(ff,'labels_cat12_')) + ff = ff(length('labels_cat12_')+1:end); +end + +def.name = ff; +def.desc = ''; +def.url = ''; +def.ver = cat_version; +def.lic = 'CC BY-NC'; +def.cor = 'MNI152 NLin 2009c Asym'; +def.type = 'Label'; +def.images = ['cat12_' ff '.nii']; + +opt = cat_io_checkinopt(opt,def); + +xml.header = [... + '\n' ... + '\n' ... + ' \n' ... + '
\n' ... + ' ' opt.name '\n' ... + ' ' opt.ver '\n' ... + ' ' opt.desc '\n' ... + ' ' opt. url '\n' ... + ' ' opt.lic '\n' ... + ' ' opt.cor '\n' ... + ' ' opt.type '\n' ... + ' \n' ... + ' ' opt.images '\n' ... + ' \n' ... + '
\n' ... + ' \n' ... + ]; +xml.data = ''; + +% find ROIname in header +ind_name = find(strcmp(csvx(1,:),'ROIname')); + +for di = 2:size(csvx,1) + xml.data = sprintf('%s%s\n',xml.data,sprintf([' '],... + csvx{di,1}, csvx{di,ind_name})); +end + +xml.footer = [ ... + ' \n' ... + '
\n' ... + ]; + +fid = fopen(fname,'w'); +if fid >= 0 + fprintf(fid,[xml.header,xml.data,xml.footer]); + fclose(fid); +else + fprintf('Error while writing %s. Check file permissions.\n',fname); +end + +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_io_remat.m",".m","1626","54","function cat_io_remat(P1,Pn) +% ______________________________________________________________________ +% Set orientation of Pn by orientation of P1. If more than one P1 input +% image is used, Pn must have the same number of files. +% +% cat_io_remat(P1,Pn) +% +% P1 = image(s) with correct resolution (1 iamge or n images) +% Pn = goal images for P1.mat (n images) +% +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Revision$ $Date$ + + if ~exist('P1','var') || isempty(P1) + P1 = spm_select([1 inf],'image','Select correct orientated image'); + else + P1 = char(P1); + end + if numel(P1)==0, return; end + if ~exist('Pn','var') || isempty(Pn) + if size(P1,1)==1 + Pn = spm_select(inf,'image','Select uncorrect orientated images'); + else + Pn = spm_select([size(P1,1) size(P1,1)],'image','Select uncorrect orientated images'); + end + else + Pn = char(Pn); + end + if numel(Pn)==0, return; end + if size(P1,1)>1 && size(P1,1)~=size(P1,1), + error('cat_io_repmat:numberP1Pn',... + sprintf('Number of images P1 and Pn does not fit (n(P1)=%d,n(Pn)=%d).',... + size(P1,1),size(Pn,1))); %#ok + end + + V1 = spm_vol(P1); + Vn = spm_vol(Pn); + + for i=1:numel(Vn) + Y = spm_read_vols(Vn(i)); + if size(P1,1)==1 + Vn(i).mat = V1.mat; + else + Vn(i).mat = V1(i).mat; + end + spm_write_vol(Vn(i),Y); + end +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_conf_nonlin_coreg.m",".m","5210","111","function nonlin_coreg = cat_conf_nonlin_coreg +% Configuration file for non-linear co-registration +% +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +%-------------------------------------------------------------------------- +% Reference Image +%-------------------------------------------------------------------------- +ref = cfg_files; +ref.tag = 'ref'; +ref.name = 'Reference Image'; +ref.help = {'This is the image that is assumed to remain stationary (e.g. T1 image), while the source image is moved to match it.'}; +ref.filter = 'image'; +ref.ufilter = '.*'; +ref.num = [1 1]; +ref.preview = @(f) spm_image('Display',char(f)); + +%-------------------------------------------------------------------------- +% 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 (e.g. mean EPI, B0 image).'}; +source.filter = 'image'; +source.ufilter = '.*'; +source.num = [1 1]; +source.preview = @(f) spm_image('Display',char(f)); + +%-------------------------------------------------------------------------- +% Other Images +%-------------------------------------------------------------------------- +other = cfg_files; +other.name = 'Images to write'; +other.tag = 'other'; +other.filter = 'image'; +other.num = [1 Inf]; +other.help = {'These are any images that need to remain in alignment with the source image.'}; +other.preview = @(f) spm_image('Display',char(f)); + +%-------------------------------------------------------------------------- +% Warping regularisation +%-------------------------------------------------------------------------- +reg = cfg_entry; +reg.tag = 'reg'; +reg.name = 'Warping Regularisation'; +reg.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. Start with 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. '}; +reg.strtype = 'r'; +reg.num = [1 1]; +reg.val = {1}; + +%-------------------------------------------------------------------------- +% Bounding box +%-------------------------------------------------------------------------- +bb = cfg_entry; +bb.tag = 'bb'; +bb.name = 'Bounding box'; +bb.help = {'The bounding box (in mm) of the volume which is to be written (relative to the anterior commissure). NaN is using the bounding box of the reference image.'}; +bb.strtype = 'r'; +bb.num = [2 3]; +bb.val = {[NaN NaN NaN; NaN NaN NaN]}; + +%-------------------------------------------------------------------------- +% Voxel sizes +%-------------------------------------------------------------------------- +vox = cfg_entry; +vox.tag = 'vox'; +vox.name = 'Voxel sizes'; +vox.help = {'The voxel sizes (x, y & z, in mm) of the written normalised images.'}; +vox.strtype = 'r'; +vox.num = [1 3]; +vox.def = @(val)spm_get_defaults('normalise.write.vox', val{:}); + +%------------------------------------------------------------------------ + +nonlin_coreg = cfg_exbranch; +nonlin_coreg.name = 'Non-linear co-registration'; +nonlin_coreg.tag = 'nonlin_coreg'; +nonlin_coreg.val = {ref,source,other,reg,bb,vox}; +nonlin_coreg.prog = @cat_vol_nonlin_coreg_multi_run; +nonlin_coreg.vout = @vout_nonlin_coreg; +nonlin_coreg.help = { + 'Within-subject non-linear co-registration performed via the segmentation routine.' + '' + 'The non-linear co-registration method used here is based on the SPM12 non-linear normalisation method that uses the segmented images to estimate deformations to match the source to the target image.' + '' + 'The resliced images are named the same as the originals except that they are prefixed by ''w''.' +'' +}; + +%------------------------------------------------------------------------ + +return; +%------------------------------------------------------------------------ + +%------------------------------------------------------------------------ +function dep = vout_nonlin_coreg(job) + +dep(1) = cfg_dep; +dep(1).sname = 'Non-linear coregistered data'; +dep(1).src_output = substruct('.','ofiles'); +dep(1).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); +%------------------------------------------------------------------------ +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_long_report.m",".m","26206","677","function out = cat_long_report(job) +%cat_long_report. Create report figure for longitudinal changes. +% Function to estimate and print the changes of longitudinal data as well +% as test-restest data. Images and surface data has to be in the same +% space. +% +% cat_long_report(job) +% +% job +% .data_vol .. p0 volumes +% .data_surf .. surface data_vol +% .data_xml .. xml data_vol +% .opts .. parameters +% .smoothvol .. smoothing rate of volumetric data +% .smoothsurf .. smoothing rate of surfaces data +% .output .. write output files +% .vols .. write +% .surfs .. write surface difference maps used +% .xml .. write XML file with combined values from the time- +% points (default=1) + + +% +% Todo: +% - batch input/data concept (p0, p1, m) +% - batch interface +% - processing vol +% - processing surf +% - evaluation parameter +% - evaluation & print data +% - print vols +% - print data_surf +% +% Notes for longitudinal preprocessing: +% - use of a scanner/protocoll variable to control protocoll depending +% geometric differencs by ultra low deformations via shooting between +% time point before ageing model without! modulation by asuming that +% the average reprents the goldstand, i.e. the TIV should be more +% similar: +% (1) identical imaging, (2) scanner-upgrades, (3) scanner change +% +% - analysis/conclusion of multiple subjects in template space with cross flag? +% to conclute CAT preprocessing + + + if ~exist('job','var'); job.test = 3; else, job.test = 0; end + def.data_vol = {''}; + def.data_vol_avg = {''}; % not implemented yet - should support further error measurements + def.data_surf = {''}; + def.data_surf_avg = {''}; % not implemented yet - should support further error measurements + def.opts.smoothvol = 3; % this is good + def.opts.smoothsurf = 12; % this could be less + def.opts.midpoint = 0; % setup of anatomical variables: 0-first, 1-midpoint + % check estiamtion of other measurements + def.tp = []; % timepoints + def.opts.boxplot = 0; % use boxplot rather than normal plot + def.opts.plotGMWM = 1; + def.printlong = cat_get_defaults('extopts.print'); + % print* to control the diagram output in the report that is maybe a bit crammed + %def.output.printqc = [1 1 1]; % [IQR COV RMSE] + %def.output.printana = [1 1 0 0 0 0 1]; % [GM WM CSF WMHs LS TIV GMT] + % def.output ... to write output files + def.output.vols = 0; + def.output.surfs = 0; + def.output.xml = 1; + def.output.prefix = 'catlongreport'; + def.extopts.expertgui = cat_get_defaults('extopts.expertgui'); + job = cat_io_checkinopt(job,def); + + if isempty(job.data_vol) && isempty(job.data_vol{1}) && ... + isempty(job.data_surf) && isempty(job.data_surf{1}) + error('cat_long_report:Input','Need input scans.'); + else + if numel(job.data_vol)>1 && numel(job.data_surf)>1 && ... + numel(job.data_vol) ~= numel(job.data_surf) + error('cat_long_report:Input','Need equal number of input scans for volumes and surfaces'); + end + end + + % estimate (and write) volumetric differences images and measurements (in vres) + if job.printlong > 0 + [vres,Vmn,Vidiff,Vrdiff] = cat_vol_longdiff(job.data_vol, job.data_vol_avg, job.opts.smoothvol, job.output.vols); + if job.opts.plotGMWM + for fi = 1:numel(job.data_vol) + [pp,ff,ee] = spm_fileparts(job.data_vol{fi}); + job.data_volw{fi} = fullfile(pp,[strrep(ff(1:8),'wp1','wp2') ff(9:end) ee]); + if ~exist( job.data_volw{fi} , 'file' ) + job.data_volw{fi} = ''; + job.opts.plotGMWM = 0; + cat_io_cprintf('err','Cannot find WM files. Use default printing.\n'); + continue + end + end + if ~isempty(job.data_vol_avg) && ~isempty(job.data_vol_avg{1}) + [pp,ff,ee] = spm_fileparts(job.data_vol_avg{1}); + job.data_vol_avgw{1} = fullfile(pp,[strrep(ff(1:8),'wp1','wp2') ff(9:end) ee]); + else + job.data_vol_avgw = job.data_vol_avg; + end + + [vresw,Vmnw,Vidiffw,Vrdiffw] = cat_vol_longdiff(job.data_volw, job.data_vol_avgw, job.opts.smoothvol, job.output.vols); + end + % create (and write) surface maps and measurements (sres) + [sres,Psurf] = cat_surf_longdiff(job.data_surf, job.opts.smoothsurf); + % extract values from XML files and combine (and write) them + % this function creates also the main report str + [repstr,ppjob,ppres,qa] = cat_get_xml(job,Psurf); + end + + %% create final report structure to call cat_main_reportfig + if job.printlong > 0 + ppres.image = Vmn; + ppres.image0 = Vmn; + ppres.Vmn = Vmn; + ppres.Vidiff = Vidiff; + ppres.Vrdiff = Vrdiff; + ppres.long.vres = vres; + ppres.long.sres = sres; + if job.opts.plotGMWM + ppres.long.vresw = vresw; + ppres.Vmnw = Vmnw; + ppres.Vidiffw = Vidiffw; + % RD20220203: A general map that shows GM and WM tissue atropy could be + % also quit interesting and it is also more stable. + % I see a lot of local spots, where GM is detected as WM + % and vice versa, probably by the WMHC and inhomogeneity. + % But of course this happens also in development. + % I also though about a general map that code all changes + % (GM>WM, WM>GM, GM>CSF, WM>CSF, CSF>WM, CSF>GM, WMHs>WM, WM>WMHs) + % but I am not sure if this gets to complex and how do code ... + ppres.Vidiffw.dat = Vidiffw.dat; % + max(0,-ppres.Vidiff.dat); + ppres.Vrdiffw = Vrdiffw; + end + ppjob.extopts.colormap = 'gray'; + if job.printlong == 1 + cat_main_reportfig([],[],[],[],ppjob,qa,ppres,repstr); + else + cat_main_reportfig([],[],[],Psurf,ppjob,qa,ppres,repstr); + end + end + + + %% cleanup of files we do not need further + if ~job.output.surfs + for si = 1:numel(Psurf) + if exist(Psurf(si).Pthick,'file') + delete(Psurf(si).Pthick); + end + end + end + + % output for dependencies + out = struct(); + if job.output.surfs + out.Psurf = Psurf; + end + if exist('sres','var') && isfield(sres,'resampled') && sres.resampled + % remove resampled thickness files + FN = {'Pcentral','Pthick'}; + for si = 1:numel(Psurf) + for fni = 1:numel(FN) + if iscell(Psurf(si).(FN{fni})) + for fi = 1:numel(Psurf(si).(FN{fni})) + if exist(Psurf(si).(FN{fni}){fi},'file'), delete(Psurf(si).(FN{fni}){fi}); end + end + else + for fi = 1:size(Psurf(si).(FN{fni}),1) + if exist(Psurf(si).(FN{fni})(fi,:),'file'), delete(Psurf(si).(FN{fni})(fi,:)); end + end + end + end + end + end + if job.output.vols + out.Pvm = Vmn.fname; + out.Pidiff = Vidiff.fname; + out.Prdiff = Vrdiff.fname; + if exist('Vadiff','var') + out.Padiff = Vadiff.fname; + end + else + if exist(Vmn.fname,'file'), delete(Vmn.fname); end + if exist(Vidiff.fname,'file'); delete(Vidiff.fname); end + if exist(Vrdiff.fname,'file'); delete(Vrdiff.fname); end + if exist('Vadiff','var') && exist(Vadiff,'file'); delete(Vadiff); end + end +end + +function [cres,Vmn,Vidiff,Vrdiff,Vadiff] = cat_vol_longdiff(Pdata_vol,Pavg,s,write) +% Create multiple difference image to characterise real (anatomically) and +% articial (protocol/processing) depending changes over time. +% The mean difference to the average Vadiff seems to describe TPM effects, +% i.e. there regions that are generally (in all time points) different to +% the average, e.g. the subcortical regions (more GM) and close to the +% brain hull or fine structres in the cerebellum. +% Differences between the time points Vidiff and Vrdiff are describing the +% variance between time or sites, e.g. ventricle enlargement, where Vrdiff +% indicate outliers (as kind of RMSE) and Vidiff all changes. +% TPM effects seems to be larger than TP effects + +%Pavg = job.avg; Pdata_vol = job.data_vol; + + if isempty( Pdata_vol ) || isempty( Pdata_vol{1} ) + % create default output in case of no volumetric data + cres = struct('cov',nan,'RMSEidiff',nan); + Vmn = struct(); + Vidiff = struct(); + Vrdiff = struct(); + Vadiff = struct(); + return + end + + if numel(Pdata_vol)<2 + error('Need more than one case.'); + end + + %% estimate covariance + cjob.data = Pdata_vol; + cjob.verb = 0; + cjob.c = {}; + cjob.data_xml = {}; + cjob.new_fig = 0; + cres = cat_stat_homogeneity(cjob); + + % the average is created by a more complex function and not only the + % mean/median so it is not clear what I can do if it is missed + useAvg = 0; % exist(Pavg{1},'file'); + if useAvg + Vavg = spm_vol(Pavg{1}); + Yavg = spm_read_vols(Vavg); + else + Vavg = spm_vol(Pdata_vol{1}); + Yavg = spm_read_vols(Vavg); + end + + Vfi = spm_vol(Pdata_vol{1}); + rmse = @(x,y) mean( (x(:) - y(:)).^2 ).^0.5; + if useAvg, cres.RMSEadiff = zeros(1,numel(Pdata_vol)); end + cres.RMSEidiff = zeros(1,numel(Pdata_vol)); + if ~isempty(Pdata_vol) + if useAvg, Yadiff = zeros(size(Yavg),'single'); end + Ymn = zeros(size(Yavg),'single'); + Yidiff = zeros(size(Yavg),'single'); + Yrdiff = zeros(size(Yavg),'single'); + + % ######### Do we need a wighting depending on the resolution ? + %vx_vol = sqrt(sum(Vfi.mat(1:3,1:3).^2)); + + for fi = 1:numel(Pdata_vol) + % check if data_vol exist + [pp,ff,ee] = spm_fileparts(Pdata_vol{fi}); + vfile = fullfile(pp,[ff ee]); + if ~exist(vfile,'file') + cat_io_cprintf('warn',sprintf(' Missing file ""%s""\n',vfile)); + continue + end + + % create difference image between avg and each timepoint + Vfi = spm_vol(Pdata_vol{fi}); + Yfi = spm_read_vols(Vfi); + Yfi(isnan(Yfi) | isinf(Yfi))=0; + Ymn = Ymn + Yfi / numel(Pdata_vol); + + % create difference image between averge and timepoint + % simple form with average but maybe not so relevant + if useAvg + Yadiff = Yadiff + (Yavg - Yfi) / numel(Pdata_vol); + cres.RMSEadiff(fi) = rmse(Yavg,Yfi); + end + + % create difference image between timepoints + if fi > 1 + Yidiff = Yidiff + (Yfi - Yfo) / numel(Pdata_vol); + Yrdiff = max( Yrdiff , (Yfi - Yfo).^2 ); + cres.RMSEidiff(fi-1) = cres.RMSEidiff(fi-1) + rmse(Yfo,Yfi) * (1 + (fi==2)); + cres.RMSEidiff(fi) = cres.RMSEidiff(fi) + rmse(Yfo,Yfi) * (1 + (fi==numel(Pdata_vol))); + end + + % between points we can quantify all increase and decreases + % serperatelly to have a major change c1 and its error rate c2, + % where the average change is given as c = c1 - c2 + + Yfo = Yfi; + end + Yrdiff = Yrdiff.^0.5; + end + + %% write data + [pp,ff,ee] = spm_fileparts(Vavg.fname); + + if exist('s','var') && s>0 + if useAvg + spm_smooth(Yadiff,Yadiff,repmat(s,1,3)); + end + spm_smooth(Yidiff,Yidiff,repmat(s,1,3)); + spm_smooth(Yrdiff,Yrdiff,repmat(s,1,3)); + end + + if useAvg + Vadiff = Vavg; + Vadiff.fname = fullfile(pp,['avgdiff_' ff ee]); + Vadiff.dt = [spm_type('FLOAT32') spm_platform('bigend')]; + Vadiff.dat(:,:,:) = single(Yadiff); + Vadiff.pinfo = repmat([1;0],1,size(Yadiff,3)); + if job.output.vols, spm_write_vol(Vadiff,Yadiff); end + else + Vadiff = struct(); + end + + Vmn = rmfield(Vfi,'private'); + Vmn.fname = fullfile(pp,['mean_' ff ee]); + Vmn.dt = [spm_type('FLOAT32') spm_platform('bigend')]; + if write, spm_write_vol(Vmn,Ymn); end + Vmn.dat(:,:,:) = single(Ymn); + Vmn.pinfo = repmat([1;0],1,size(Ymn,3)); + + Vidiff = rmfield(Vfi,'private'); + Vidiff.fname = fullfile(pp,['tpidiff_' ff ee]); + Vidiff.dt = [spm_type('FLOAT32') spm_platform('bigend')]; + if write, spm_write_vol(Vidiff,Yidiff); end + Vidiff.dat(:,:,:) = single(Yidiff); + Vidiff.pinfo = repmat([1;0],1,size(Yidiff,3)); + + Vrdiff = rmfield(Vfi,'private'); + Vrdiff.fname = fullfile(pp,['tprdiff_' ff ee]); + Vrdiff.dt = [spm_type('FLOAT32') spm_platform('bigend')]; + if write, spm_write_vol(Vrdiff,Yrdiff); end + Vrdiff.dat(:,:,:) = single(Yrdiff); + Vrdiff.pinfo = repmat([1;0],1,size(Yrdiff,3)); + +end + +function [cres,Psurf] = cat_surf_longdiff(Pdata_surf,s) +% create surface difference maps + + if isempty(Pdata_surf) || isempty(Pdata_surf{1}) + cres = struct(); + Psurf = []; + else + Pdata_surfold = Pdata_surf; + + %% estimate covariance + cjob.data = Pdata_surf; + cjob.verb = 0; + cjob.data_xml = {}; + cjob.gap = 3; + cjob.new_fig = 0; + try + % try to estimate covariance ... if it fails then asume that the + % meshes are not equal and resmaple them + %warning('off',char(sprintf('[GIFTI] Parsing of XML file %s failed.', Pdata_surf{1}))); + cres = cat_stat_homogeneity(cjob); + catch + % resample (& smooth) + srjob.data_surf = Pdata_surf; + srjob.fwhm_surf = 0; + srjob.nproc = 0; + srjob.verb = 0; + srjob.merge_hemi = 0; + srjob.mesh32k = 1; % use option 2 - 192k? + Psdata = cat_surf_resamp(srjob); + Pdata_surf = Psdata.sample.lPsdata; + + cjob.data = Pdata_surf; + cres = cat_stat_homogeneity(cjob); + end + + + + %% load data + sides = {'lh','rh','cb'}; + [pp1,ff1,ee1] = spm_fileparts(Pdata_surf{1} ); + if any( cat_io_contains( ff1 , sides )) + sdata = cell(size(sides)); Psurf = struct(); + for si = 1:numel(sides) + % load surfaces mesh (only first) + [pp1,ff1,ee1] = spm_fileparts(Pdata_surf{1}); + if strcmp(ee1,'.gii') % resampled + Pcentral = fullfile(pp1,[strrep(ff1,'lh.thickness',[sides{si} '.thickness']) ee1]); + if ~exist(Pcentral,'file'), continue; end + if 0 % average surface in cross sectional pipeline + for i = 1:numel(Pdata_surf) + [ppi,ffi,eei] = spm_fileparts(Pdata_surf{i}); + Pcentrali = fullfile(ppi,[strrep(ffi,'lh.thickness',[sides{si} '.thickness']) ee1]); + sdatai = export(gifti(Pcentrali),'patch'); + if i==1, sdata{si} = sdatai; else, sdata{si} = sdata{si} + sdatai; end + end + Pcentral = fullfile(pp1,[strrep(ff1,'lh.thickness',[sides{si} '.thickness']) ee1]); + else + sdata{si} = export(gifti(Pcentral),'patch'); + end + + Pcentral = fullfile(pp1,strrep(ff1,'lh.thickness',[sides{si} '.central'])); + cat_io_FreeSurfer('write_surf',Pcentral,sdata{si}); + else % native thickness data in freesurfer format + Pcentral = fullfile(pp1,[strrep(ff1,'lh.thickness',[sides{si} '.central']) ee1 '.gii']); + if ~exist(Pcentral,'file'), continue; end + sdata{si} = gifti(Pcentral); + end + + + % load surface data + clear cdata; %cdata = zeros(numel(sides),si); + for fi = 1:numel(Pdata_surf) + %if ~exist(Pdata_surf{fi},'file'), continue; end + [pp,ff,ee] = spm_fileparts( Pdata_surf{fi} ); + if ~strcmp(ee,'.gii') + cdata(:,fi) = cat_io_FreeSurfer('read_surf_data',fullfile(pp,[strrep(ff,'lh.thickness',[sides{si} '.thickness']) ee])); + Psurf(si).Pcentral = fullfile(pp1,[strrep(ff1,'lh.thickness',[sides{si} '.central']) ee1 '.gii']); + else %% native FS files + data = gifti(fullfile(pp,[strrep(ff,'lh.thickness',[sides{si} '.thickness' ]) ee])); + data = export(data,'patch'); + cdata(:,fi) = data.facevertexcdata; + Psurf(si).Pcentral = Pcentral; + end + end + + %% simple meshsmooth + M = spm_mesh_smooth(sdata{si}); + cdata = cat_stat_nanmean(diff(cdata,[],2),2); % ./ cat_stat_nanmean(cdata,2); % relative changes + cdata = spm_mesh_smooth(M,cdata, s * (size(cdata,1)/128000).^0.5 ); % some adaptions to be closer to mm + + if ~strcmp(ee1,'.gii') + Psurf(si).Pthick = fullfile(pp1,[strrep(ff1,'lh.thickness',[sides{si} '.longThicknessChanges']) ee1]); + else + Psurf(si).Pthick = fullfile(pp1,strrep(ff1,'lh.thickness',[sides{si} '.longThicknessChanges'])); + end + cat_io_FreeSurfer('write_surf_data',Psurf(si).Pthick,cdata); + + end + end + + + end +end + +function [str,ppjob,ppres,qa] = cat_get_xml(job,Psurf) +% + + mark2rps = @(mark) min(100,max(0,105 - real(mark)*10)) + isnan(real(mark)).*real(mark); + + % detect XML files if not available + if ~isfield(job,'data_xml') || isempty(job.data_xml) || numel(job.data_xml) + if ~isempty( job.data_vol ) && ~isempty( job.data_vol{1} ) + % detect XML files based on the volume data + prefs = {'p0',... + 'mwmwp1','mwwp1','mwp1','mwp1m','mwmwp1m', ... + 'mwmwp2','mwwp2','mwp2','mwp2m','mwmwp2m', ... + 'mwmwp3','mwwp3','mwp3','mwp3m','mwmwp3m', ... + }; + % try to find it + for fi = 1:numel(job.data_vol) + [pp,ff] = spm_fileparts(job.data_vol{fi}); + [pp1,pp2] = spm_fileparts(pp); + Pxml = fullfile(pp1,strrep(pp2,'mri','report'),... + [cat_io_strrep(ff,prefs,repmat({'cat_'},1,numel(prefs))) '.xml']); + if exist(Pxml,'file') + job.data_xml{fi,1} = Pxml; + else + Pxml = fullfile(pp,'report',... + ['cat_' ff '.xml']); + if exist(Pxml,'file') + job.data_xml{fi,1} = Pxml; + else + cat_io_cprintf('red','no xml\n') + end + end + end +%% ######### separation is not realy working +% I need an long-xml/mat file to store all parameters in a useful way + [pp,ff,ee] = spm_fileparts(job.data_vol{1}); + if cat_io_contains(ff,'mwmwp') % ~isempty(strfind(ff,'mwmwp')) + model = 'aging'; + elseif cat_io_contains(ff,'mwp') % ~isempty(strfind(ff,'mwp')) + model = 'plasticity'; + else + model = ''; + end + elseif ~isempty( job.data_surf ) && ~isempty( job.data_surf{1} ) + % detect XML files based on the surface data + + prefs = {'lh.thickness.','lh.central'}; + % try to find it + for fi = 1:numel(job.data_surf) + [pp,ff,ee] = spm_fileparts(job.data_surf{fi}); + if ~strcmp(ee,'.gii'), ff = [ff ee]; end %#ok + Pxml = fullfile(strrep(pp,'surf','report'),... + [cat_io_strrep(ff,prefs,repmat({'cat_'},1,numel(prefs))) '.xml']); + if exist(Pxml,'file') + job.data_xml{fi,1} = Pxml; + else + Pxml = fullfile(pp,'report',... + ['cat_' ff '.xml']); + if exist(Pxml,'file') + job.data_xml{fi,1} = Pxml; + else + cat_io_cprintf('red','no xml\n') + end + end + end + model = ''; + else + cat_io_cprintf('red','no xml\n') + end + end + + + % load XML data + if isfield(job,'data_xml') && ~isempty(job.data_xml) && ~isempty(job.data_xml{1}) + xml = cat_io_xml(job.data_xml); + + for fi = 1:numel(job.data_xml) + xml(fi).subjectmeasures = rmfield(xml(fi).subjectmeasures,'software'); + end + + + % for fi = 1:numel(job.data_vol), SPMpp(fi,:) = xml(fi).SPMpreprocessing.mn ./ xml(fi).SPMpreprocessing.mn(2); end + for fi = 1:numel(job.data_xml), long.vol_rel_CGW(fi,:) = xml(fi).subjectmeasures.vol_rel_CGW; end + for fi = 1:numel(job.data_xml), long.vol_abs_CGW(fi,:) = xml(fi).subjectmeasures.vol_abs_CGW; end + for fi = 1:numel(job.data_xml), long.vol_abs_WMH(fi) = xml(fi).subjectmeasures.vol_abs_WMH; end + for fi = 1:numel(job.data_xml), long.vol_TIV(fi,:) = xml(fi).subjectmeasures.vol_TIV; end + for fi = 1:numel(job.data_xml), long.qar_IQR(fi,:) = xml(fi).qualityratings.IQR; end + for fi = 1:numel(job.data_xml), long.tissue_mn(fi,:) = xml(fi).qualitymeasures.tissue_mn; end + if isfield(xml(fi).subjectmeasures,'dist_thickness') + for fi = 1:numel(job.data_xml), long.dist_thickness(fi,:) = xml(fi).subjectmeasures.dist_thickness{1}; end + end + if isfield(xml(fi).subjectmeasures,'surf_TSA') + for fi = 1:numel(job.data_xml), long.surf_TSA(fi,:) = xml(fi).subjectmeasures.surf_TSA; end + end + + %% + %try + for ti = 1:3; %size(long.vol_rel_CGW,2) + [ pfp , pfS , pfmu ] = polyfit( 1:size(long.vol_rel_CGW,1) , long.vol_rel_CGW(:,ti)' , 1); + long.vol_rel_CGW_fit.p{ti} = pfp; + long.vol_rel_CGW_fit.S{ti} = pfS; + long.vol_rel_CGW_fit.mu{ti} = pfmu; + [ pfp , pfS , pfmu ] = polyfit( 1:size(long.vol_abs_CGW,1) , long.vol_abs_CGW(:,ti)' , 1); + long.vol_abs_CGW_fit.p{ti} = pfp; + long.vol_abs_CGW_fit.S{ti} = pfS; + long.vol_abs_CGW_fit.mu{ti} = pfmu; + end + %end + %% + long.model = model; +% long.change_vol_rel_CGW = (long.vol_rel_CGW - repmat(long.vol_rel_CGW(1,:),size(long.vol_rel_CGW,1),1)); + if job.opts.midpoint + long.change_vol_rel_CGW = long.vol_rel_CGW - repmat(mean(long.vol_rel_CGW,1),size(long.vol_rel_CGW,1),1); + long.change_vol_rel_TIV = (long.vol_TIV - mean(long.vol_TIV)) ./ mean(long.vol_TIV); + else + long.change_vol_rel_CGW = (long.vol_rel_CGW - repmat(mean(long.vol_rel_CGW(1,:),1),size(long.vol_rel_CGW,1),1)); + long.change_vol_rel_TIV = (long.vol_TIV / long.vol_TIV(1) - 1 ); + end + long.change_qar_IQR = (mark2rps(long.qar_IQR) - max(mark2rps(long.qar_IQR)) ); + if isfield(long,'dist_thickness') + if job.opts.midpoint + long.change_dist_thickness = (long.dist_thickness - repmat(mean(long.dist_thickness,1),size(long.dist_thickness,1),1)) ./ ... + repmat(long.dist_thickness(1,:),size(long.dist_thickness,1),1); + else + long.change_dist_thickness = (long.dist_thickness - repmat(long.dist_thickness(1,:),size(long.dist_thickness,1),1)) ./ ... + repmat(long.dist_thickness(1,:),size(long.dist_thickness,1),1); + end + end + + %% combine + QM = struct(); + QFN = {'qualitymeasures','qualityratings','subjectmeasures'}; + for qfni = 1:numel(QFN) + FN = fieldnames(xml(fi).(QFN{qfni})); + for fni = 1:numel(FN) + clear QMF; + try + for fi = 1:numel(job.data_xml) + try + QMF.(FN{fni})(fi,:) = xml(fi).(QFN{qfni}).(FN{fni}); + catch + % struct/cell, missing or empty field + QMF.(FN{fni})(fi,:) = nan; + end + end + if isnumeric(QMF.(FN{fni})) + QM.(QFN{qfni}).(FN{fni}) = cat_stat_nanmean(QMF.(FN{fni})); + end + catch + cat_io_cprintf('err','cat_long_report:XMLerror','Error in extracting XML data.\n'); + end + end + end + + %% create final variables + % use job settings form the first XML file + ppjob = xml(1).parameter; + ppjob.output.surface = ~isempty(Psurf); + + % get preprocessing settings/data from the first variable + ppres = xml(1).SPMpreprocessing; + try + ppres.do_dartel = (ppjob.extopts.regstr > 0) + 1; + catch + ppres.do_dartel = -1; + end + ppres.ppe = struct(); + ppres.tpm = spm_vol(fullfile(spm('dir'),'tpm','TPM.nii')); % replace by default SPM TPM + ppres.stime = clock; + ppres.long.model = model; + + % create qa structure with the combined measures from above + qa = struct('software',xml(1).software,... + 'qualitymeasures',QM.qualitymeasures,... + 'qualityratings' ,QM.qualityratings,... + 'subjectmeasures',QM.subjectmeasures); + + % search xml of the average to extract some parameters that we change + % in the longitudinal processings (at least for bias, acc and tpm) + [pp,ff] = spm_fileparts(job.data_xml{1}); + Pxmlavg = fullfile(pp,[strrep(ff,'cat_r','cat_avg_') '.mat']); + if exist(Pxmlavg,'file') + xmlavg = load(Pxmlavg); + else + xmlavg.S = xml(1); + end + ppjob.opts = xmlavg.S.parameter.opts; + ppjob.extopts = xmlavg.S.parameter.opts; + + % get catlong parameter setting + try + %% + Pxmllong = fullfile(pp,[strrep(ff,'cat_r','catlong_') '.mat']); + if exist(Pxmllong,'file') + xmllong = load(Pxmllong); + else + xmllong.S = xml(1); + end + ppjob.lopts = xmllong.S.parameter; + + % update model + longmodels = {'LC','LP','LA','LD','LPA'}; + %longmodels = {'LongCrossDevelopment','LongPlasticity','LongAging','LongDevelopment','LongPlasticityAging'}; + ppres.long.model = longmodels{ppjob.lopts.longmodel + 1}; + if ppjob.lopts.longmodel == 3 % Plasticity + Aging + if strcmp(model,'plasticity') + ppres.long.model = longmodels{2}; + elseif strcmp(model,'aging') + ppres.long.model = longmodels{3}; + end + end + long.model = ppres.long.model; + model = long.model; + end + + try + str = cat_main_reportstr(ppjob,ppres,qa); + catch + str = cell(1,3); + end + else + % create some empty default output if no XML is available + str = cell(1,3); + long = struct(); + ppres = struct(); + qa = struct(); + ppjob.output.surface = ~isempty(Psurf); + end + + %% add further fields to the output structure + ppres.long = long; + ppres.long.measure = 'thickness'; % ################### generalize! + if ~isempty(job.data_vol) && ~isempty(job.data_vol{1}) + ppres.long.files = job.data_vol; + else + ppres.long.files = job.data_surf; + end + ppres.long.smoothvol = job.opts.smoothvol; + ppres.long.smoothsurf = job.opts.smoothsurf; + +end +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_vol_laplace3R.m",".m","960","27","%cat_vol_laplace3R Volumetric Laplace filter with Dirichlet boundary. +% Filter SEG within the intensity range of low and high until the changes +% are below TH. +% +% L = cat_vol_laplace3R(SEG,R,TH) +% +% SEG .. 3D single input matrix +% R .. 3D boolean volume to describe the filter area +% TH .. threshold to control the number of iterations +% maximum change of an element after iteration +% +% Example: +% A = zeros(50,50,3,'single'); A(10:end-9,10:end-9,2)=0.5; +% A(20:end-19,20:end-19,2)=1; +% B = A==0.5; +% C = cat_vol_laplace3R(A,B,0.001); ds('d2smns','',1,A,C,2); +% +% See also cat_vol_laplace3, compile. +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_tst_CJV.m",".m","1834","63","function CJV = cat_tst_CJV(P,Pp0) +% ______________________________________________________________________ +% Function to estimate the CJV (coefficient of joint variation) in +% images. +% +% CJV = cat_tst_CJV(P,Pp0) +% +% P ... set of n images (cellstr or char) +% Pp0 ... set of 1 (ground truth) or n images (cellstr of char) +% CJV ... matrix of n CJV values of each image +% +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ +% ______________________________________________________________________ + + if iscell(P) && size(P,1) 1 + Yp0 = spm_read_vols(Vp0(i)); + else + Yp0 = spm_read_vols(Vp0); + end + ncls = max(round(Yp0(:))); + if ncls==254 + Yp0 = Yp0/ncls*3; + end + + CJV(i) = ( cat_stat_nanstd(Y(Yp0>2.5))/2 + ... + cat_stat_nanstd(Y(Yp0>1.5 & Yp0<2.5))/2 ) / ... + ( cat_stat_nanmean(Y(Yp0>2.5)) - ... + cat_stat_nanmean(Y(Yp0>1.5 & Yp0<2.5)) ); + catch + cat_io_cprintf('err',sprintf('Error: %s\n',P(i,:))); + CJV(i) = nan; + end + end + else + cat_io_cprintf('err',sprintf('Error: no images\n')); + end +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_system.m",".m","3738","120","function [status,result] = cat_system(cmd,verb,trerr) +% ______________________________________________________________________ +% CAT12 wrapper for system calls +% This is necessary because windows does not allow spaces in system +% calls. Thus, we have to cd into that folder and call the command +% from this folder. +% +% [status,result] = cat_system(cmd,verb,trerr) +% cmd .. system call; +% verb .. verbosity +% trerr .. trough an error message (default), else just display error +% status, result .. system call outputs [status,result] = system('...'); +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +rev = '$Rev$'; + +if nargin == 0 + error('Argument is missing'); +end +if nargin < 3 trerr = 1; end +if nargin < 2 verb = 0; end + +CATDir = fullfile(fileparts(mfilename('fullpath')),'CAT'); + +% replace spaces in directory name +if ~ispc + CATDir = strrep(CATDir,' ','\ '); +end + +if ispc + CATDir = [CATDir '.w32']; +elseif ismac + [stat, output] = system('uname -v'); + % try to recognize new Apple arm64 processor + if ~stat && ~isempty(strfind(output,'ARM64')) + CATDir = [CATDir '.maca64']; + else + CATDir = [CATDir '.maci64']; + end +elseif isunix + CATDir = [CATDir '.glnx86']; +end + +if ispc + olddir = pwd; + cd(CATDir); + [ST, RS] = system(cmd); + cd(olddir); +else + cmdfull = fullfile(CATDir,cmd); + warning off % this is to prevent warnings by calling cat12 from the shell script + [ST, RS] = system(cmdfull); + warning on +end + +% if not successful try it again after changing the file attributes to ""+x"" +if ST > 1 + if ispc + try, fileattrib(fullfile(CATDir,'*'),'+x'); end + olddir = pwd; + cd(CATDir); + [ST, RS] = system(cmd); + cd(olddir); + else + try, fileattrib(fullfile(CATDir,'*'),'+x','a'); end + cmdfull = fullfile(CATDir,cmd); + warning off % this is to prevent warnings by calling cat12 from the shell script + [ST, RS] = system(cmdfull); + warning on + end +end + +if nargout > 0 + [status,result] = cat_check_system_output(ST,RS,verb,trerr); +else + cat_check_system_output(ST,RS,verb,trerr); +end + +% for mac we need to enable execution because of Apple Gatekeeper +%cmdspaces = strfind(cmd,' '); +%[STT,RST] = system(fullfile(CATDir,cmd(1:cmdspaces(1)))); % just try the basic call +if ismac && (ST == 137 || ST == 127) + cmd = ['xattr -r -d com.apple.quarantine ' CATDir]; + system(cmd); fprintf([cmd '\n']); + cmd = ['chmod a+x ' CATDir '/CAT.mac*/CAT*']; + system(cmd); fprintf([cmd '\n']); + return +end + +if ST > 1 && ST~=139 % 139: data setup error + if ispc + [ST, RS] = system('systeminfo.exe'); + else + [ST, RS] = system('uname -a'); + end + str = sprintf('\nWARNING: Surface processing will not work because\n(1) File permissions are not correct (for unix use chmod a+x) or\n(1) CAT binaries are not compatible to your system or\n(3) Antivirus software in Windwos or Gatekeeper in MAC OS is blocking to execute binaries\nSystem: %s\n',RS); + cat_io_cmd(str,'warning'); + helpdlg(str,'Error Using Surface Tools'); + + % check Gatekeeper on MAC OS + if ismac + [ST, RS] = system('spctl --status'); + if ~isempty(strfind(RS,'enabled')) + str = 'Please disable Gatekeeper on MAC OS!'; + fprintf('\n\n%s\n',str); + helpdlg(str,'Gatekeeper error'); + web('https://en.wikibooks.org/wiki/SPM/Installation_on_64bit_Mac_OS_(Intel)#Troubleshooting'); + end + end + fprintf('\n\nFor future support of your system please send this message to christian.gaser@uni-jena.de\n\n'); +end + +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_stat_svd.m",".m","12672","431","function v = cat_stat_svd(P, mask, basename, cov, exclude_scan, scanner) +% cat_stat_svd - Singular Value Decomposition (SVD) for brain imaging data. +% +% This function performs SVD (PCA) on neuroimaging data, accounting for +% masks, covariates, scanner batch effects, and optionally excluding scans. +% The principal components (""eigenvectors"") and their explained variance are +% visualized, saved, and written to disk. Optionally, SPM or CAT12 routines +% are used for visualization. +% +% USAGE: +% v = cat_stat_svd(P, mask, basename, cov, exclude_scan, scanner) +% +% INPUTS: +% P - Cell array or char matrix of image filenames (e.g., NIfTI or mesh files). +% Each file should correspond to a subject/scan. Can also be a single filename. +% mask - (optional) Filename of a mask image (e.g., brain mask) or [] to use all voxels. +% If omitted, user will be prompted to select one. +% basename - (optional) Output base filename for writing results. If omitted, user will be prompted. +% cov - (optional) Covariate vector or matrix (e.g., age, sex, behavioral scores). Size must +% match number of input images after exclusion. +% exclude_scan - (optional) Vector of indices specifying which scans to exclude from analysis. +% scanner - (optional) Scanner batch variable. Should be a vector or matrix encoding scanner/site +% effects (e.g., as integer labels or dummy-encoded). Used to regress out scanner effects. +% +% OUTPUT: +% v - Eigenvectors (principal components) for the subjects in the sample. +% Returns only components with eigenvalues > 1 (Kaiser criterion). +% +% DEPENDENCIES: +% - Requires SPM (Statistical Parametric Mapping) for data I/O and figure handling. +% - Optional: CAT12 toolbox for glassbrain visualization (`cat_vol_img2mip`). +% +% EXAMPLES: +% % Typical usage with a set of NIfTI images and a brain mask: +% v = cat_stat_svd({'sub1.nii', 'sub2.nii', ...}, 'brainmask.nii', 'myoutput', age_vector, [], scanner_ids); +% +% % Minimal usage (GUI for file selection): +% v = cat_stat_svd(); +% +% ______________________________________________________________________ +% +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ + + +if nargin<4, cov = []; end +if nargin<5, exclude_scan = []; end +if nargin<6, scanner = []; end + +if ~exist('cat_vol_img2mip') + fprintf('Please install CAT12 to visualize the effects as glassbrain\n') +end + +% -- Select images for each variate (if no input, open GUI) +if ~nargin + n = Inf; + for i = 1:100 + P = spm_select([0 n],{'mesh','image'},['Select images for Variate ' num2str(i) ' (or press done)']); + try P = strrep(P,'.nii,1','.nii'); end + if isempty(P), break; end + if i==1 + n = size(P,1); + end + if n ~= size(P,1) + error(['Number of images for variate ' num2str(i) ' is different.']); + end + V{i} = spm_data_hdr_read(P); + Ptmp = P; + end +else + V{1} = spm_data_hdr_read(P); + if ~isempty(exclude_scan) + V{1}(exclude_scan) = []; + fprintf('%d scans excluded. New n=%d\n', numel(exclude_scan), numel(V{1})); + if ~isempty(cov) + cov(exclude_scan) = []; + end + end + Ptmp = P; +end + +% -- Check for mesh data or image data +mesh_detected = 0; +if spm_mesh_detect(V{1}(1)) + mesh_detected = 1; +end + +n_variates = length(V); + +% -- Prepare mask image if provided or prompt user +if mesh_detected + mask = []; +elseif nargin < 2 + mask = spm_select([0 1],{'mesh','image'},{'select mask image (or press done)'}); +end + +% -- Prepare output file basename +if nargin < 3 + if ~isempty(mask) + str = '_masked'; + else + str = ''; + end + [tmp, name] = spm_str_manip(spm_str_manip(Ptmp,'t'),'C'); + if isfield(name,'e') + pos = strfind(name.e,',1'); + if ~isempty(pos) + name.e = name.e(1:pos-1); + end + basename = [name.s name.e]; + else + basename = tmp; + end + basename = strrep(basename, '.nii', [str '.nii']); + basename = spm_input('Output filename',1,'s',basename); +end + +% -- Load and apply mask if provided +if ~isempty(mask) + Vm = spm_vol(char(mask)); + volmask = zeros(V{1}(1).dim(1:3)); + + for j=1:V{1}(1).dim(3) + + Mi = spm_matrix([0 0 j]); + + % Load slice j from all images + M1 = V{1}(1).mat\Vm.mat\Mi; + volmask(:,:,j) = spm_slice_vol(Vm,M1,V{1}(1).dim(1:2),[1 0]); + end + sz_vol = size(volmask); + + ind = find(volmask > 0); + volmask = volmask(ind); +end + +% -- Load image data and extract voxel/vertex values +for j=1:n_variates + vol0{j} = spm_data_read(V{j}); +end + +if isempty(mask) + if mesh_detected + vol_tmp = vol0{j}(:,1); + else + vol_tmp = vol0{j}(:,:,:,1); + end + ind = find(isfinite(vol_tmp)); + sz_vol = V{1}(1).dim; +end + +sz_ind = length(ind); +sz = n_variates*sz_ind; + +if mesh_detected + n = size(vol0{1},2); +else + n = size(vol0{1},4); +end + +y = zeros(sz,n,'single'); + +% -- Build subject-by-feature matrix y +for i=1:n + vol = []; + for j=1:n_variates + if mesh_detected + vol_tmp = vol0{j}(:,i); + else + vol_tmp = vol0{j}(:,:,:,i); + end + if ~isempty(mask) + if sum(size(vol_tmp(ind))-size(volmask)) + warning('Mask has different size'); + else + vol_tmp = vol_tmp(ind).*volmask; + end + else + vol_tmp = vol_tmp(ind); + end + vol = [vol; vol_tmp]; + end + y(:,i) = single(vol(:)); +end + +y(~isfinite(y)) = 0; + +% -- Remove scanner effects if scanner variable is provided +if ~isempty(scanner) + % looks like a vector with coding scanner 1..n + if min(size(scanner)) == 1 && min(scanner) == 1 + batch = dummyvar(scanner); + elseif min(size(scanner)) > 1 && min(scanner) == 0 && max(scanner) == 1 + batch = scanner; + else + error('Wrong definition of variable scanner'); + end + batch(exclude_scan,:) = []; + G = [ones(max(size(batch)),1) batch]; + disp('Remove scanner effects') + % remove scanner effects + y = y - y*G*(pinv(G)); + +end + +% -- Center and scale data +y = y/max(y(:)); +ymean = mean(y,2); + +% -- Mask out areas with missing data +mask_SD = all(y==0,2); +y(mask_SD,:) = 0; +ymean(mask_SD) = 0; + +for i=1:n, y(:,i) = y(:,i) - ymean; end +clear vol volmask ymean vol0 + +% -- Run SVD (PCA) on covariance matrix +cov_y = y'*y; +cov_y = double(cov_y)/(n-1); +[~, s, v] = svd(cov_y,0); + +s = diag(s); +s2 = s.^2; +s2 = length(s2)*s2/sum(s2); + +% -- Determine number of components (eigenvalues > 1) +n_e = find(s2 > 1, 1, 'last' ); + +if isempty(n_e) + fprintf('No Eigenvalue > 1 found\n'); + return +end + +s_scaled = s2/sum(s2); +sum_s = zeros(n,1); +sum_s(1) = s_scaled(1); +for i=2:n + sum_s(i) = sum_s(i-1) + s_scaled(i); +end + +% -- Plot explained variance and SVD eigenvectors, and output summary +expl_var = [sum_s(1); diff(sum_s)]; +fprintf('Explained variance:\n') +fprintf('%3.2f\n',100*expl_var(1:n_e)) + +Vout = V{1}(1); +Vout.n = 1; % ignore multivariate data for output + +Fgraph = spm_figure('FindWin','Graphics'); +spm_figure('Clear',Fgraph); +figure(Fgraph) +FS = spm('FontSizes'); +col = char('r','g','b','m','c','k','y'); + +ysize = 0.4; +step = ysize/n_e; + +if ~isempty(cov) && size(cov,1) ~= n + cov = cov'; + if size(cov,1) ~= n + fprintf('Differing length of covariates (n=%d) compared to data size (n=%d)\n',numel(cov),n) + cov = []; + end +end + +if ~isempty(cov) + cov = cov - mean(cov); +end + +% -- Correlate components with covariates (if provided) +for nn=1:n_e + axes('Position',[.07 0.55+step*(n_e - nn) .9 step]); + + % if values at maximum value in image show a neg. correlation to + % eigenvector then invert the eigenvecor + u = y*v(:,nn)/sqrt(n); + cc = corrcoef(y(u==max(u),:),v(:,nn)); + if cc(1,2) < 0 + v(:,nn) = -v(:,nn); + end + + plot(v(:,nn),'Color',col(rem(nn-1,7)+1)) + set(gca,'XTick',1:5:n,'YTick',[],'XGrid','on','XLim',[1 n]); + if ~isempty(cov) + set(gca,'XGrid','off'); + end + ylabel(num2str(nn)) + if ~isempty(cov) + mx = max(abs(v(:,nn))); + cov1 = mx*cov./max(abs(cov)); + [cc, pp] = corrcoef([v(:,nn) cov1]); + + % check for largest correlation + ind_mx = find(abs(cc(2:end,1)) == max(abs(cc(2:end,1)))); + mx_corr = cc(ind_mx+1,1); + + % we invert SVD output to get pos. correlations with covariate + if mx_corr < 0 + v(:,nn) = -v(:,nn); + cc = -cc; + plot(v(:,nn),'Color',col(rem(nn-1,7)+1)) + set(gca,'XTick',1:5:n,'YTick',[],'XGrid','on','XLim',[1 n]); + set(gca,'XGrid','off'); + end + + legend_str = {['component' num2str(nn)]}; + for j = 1:size(cov,2) + legend_str{j+1} = ['covariate' num2str(j)]; + end + + hold on + plot(cov1,':') + hold off + + legend(legend_str) + + fprintf('Correlation of eigenvector %d to covariate:',nn); + for j=2:size(cc,1) + fprintf('%3.3f (P=%3.3f) ',cc(1,j), pp(1,j)); + end + fprintf('\n'); + else + legend(sprintf('%3.1f%s expl. var\n',100*expl_var(nn),'%s')) + end + if nn==1 + title('Significant Eigenvectors','Fontsize',FS(14),'Fontweight','Bold') + end +end +xlabel('scans') + +% skip writing images if basename is not defined +if ~isempty(basename) + csv_name = ['eigen_' basename(:,1:end-4) '.csv']; + csvwrite(csv_name,v(:,1:n_e)); + + axes('Position',[.07 .07 .44 .4],'Visible','off',... + 'DefaultTextFontSize',FS(8)); + + plot(100*sum_s(1:n-1),':o') + set(gca,'Xlim',[0.5 n-0.5],'XTick',1:n-1,'Ylim',[min(100*sum_s(1:n-1)) 100]) + + title('Percent of total variance','Fontsize',FS(14),'Fontweight','Bold') + ylabel('Variance [%]') + xlabel('Eigenvalue') + + axes('Position',[.53 .07 .44 .4],'Visible','off',... + 'DefaultTextFontSize',FS(8)); + + plot(s2(1:n-1),':o') + set(gca,'Xlim',[0.5 n-0.5],'XTick',1:n-1) + + title('Plot of eigenvalues','Fontsize',FS(14),'Fontweight','Bold') + xlabel('Eigenvalue') + + drawnow + + % save SPM figure + saveas(Fgraph, [basename '.png']); + + for k=1:n_e + u = y*v(:,k)/sqrt(n); + Vout.dt = [spm_type('float32') spm_platform('bigend')]; + Vout.pinfo(1) = 1; + tmp = zeros(sz_vol); + % -- Save eigenvectors and images for each component + for i=1:n_variates + tmp(ind) = u((i-1)*sz_ind+1:i*sz_ind); + if n_variates > 1 + Vout.fname = ['eigen' sprintf('%.2d_%d',k,i) '_' basename]; + else + Vout.fname = ['eigen' sprintf('%.2d',k) '_' basename]; + end + fprintf('save %s\n',Vout.fname); + Vout = spm_data_hdr_write(Vout); + spm_data_write(Vout,tmp); + + % -- (Optional) Visualize glassbrain images if CAT12 is available + if ~mesh_detected && exist('cat_vol_img2mip') + [H0, X0] = hist(tmp(tmp>0),100); + TH0p = X0(find(cumsum(H0)/sum(H0) > 0.5, 1 )); + TH1p = X0(find(cumsum(H0)/sum(H0) > 0.9, 1 )); + [H0, X0] = hist(tmp(tmp<0),100); + TH0n = X0(find(cumsum(H0)/sum(H0) > 0.5, 1 )); + TH1n = X0(find(cumsum(H0)/sum(H0) > 0.9, 1 )); + frange = max(abs([TH0p TH0n])); + range = [-max(abs([TH1p TH1n])) max(abs([TH1p TH1n]))]; + func = sprintf('i1(i1<%g & i1>-%g)=NaN;',frange,frange); + + png_name = strrep(Vout.fname,'nii','png'); + OV = struct('name',Vout.fname,'func',func,'cmap',jet(64),'range',... + range,'gamma_scl',0.7,'save_image',png_name,'RGB_order',1:3,'Pos',... + [10 10],'bkg_col',[0 0 0],'fig_mip',10*k+i,'cbar',2,'roi',[]); + cat_vol_img2mip(OV); + + end + end + end +end + +[~, fname_tmp] = spm_str_manip(char(V{1}.fname),'C'); +order_ev = {[1,2],[1,3],[2,3]}; + +% -- Scatter plots of first three components (with covariate coloring if provided) +for k=1:3 + figure(22+k) + x = v(:,order_ev{k}(1)); + y = v(:,order_ev{k}(2)); + if ~isempty(cov) + scatter(x,y,50,cov,'filled') + colormap(cat_io_colormaps('nejm',numel(unique(cov)))) + else + scatter(x,y,20,'filled') + hold on + for i=1:n + text(x(i),y(i),fname_tmp.m{i},'FontSize',12,'HorizontalAlignment','center','interpreter','none') + end + hold off + end + xlabel(['Eigenvalue ' num2str(order_ev{k}(1))]); + ylabel(['Eigenvalue ' num2str(order_ev{k}(2))]); +end + +% -- Return eigenvectors for significant components +v = v(:,1:n_e); + +if ~nargout, clear v; end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_surf_parameters.m",".m","33607","717","function varargout = cat_surf_parameters(job) +% ______________________________________________________________________ +% +% cat_surf_parameters to extract surface parameters such as +% gyrification and cortical complexity. +% +% varargout = cat_surf_parameters(job) +% +% job. +% .data_surf .. input data +% .nproc .. parallel processing (default 0) +% .verb .. verbose output (default cat_get_defaults('extopts.verb')) +% .lazy .. avoid reprocess of exist results (default 0) +% .debug .. (default cat_get_defaults('extopts.verb')>2) +% = measures = +% .GI .. estimate absolute mean curvature (default 0) +% .FD .. estimate fractal dimension (Yotter:2012; default 0) +% .SD .. estimate sulcal depth (default 0) +% .tGI .. estimate Toro's GI (default 0) +% = experimental measures = (only cat_get_defaults('extopts.expertgui')>1) +% .lGI .. estimate Schaer's lGI (default 0) +% .GIL .. estimate Laplacian-based gyrification index +% is a numeric in case of default users (default 0) +% is a structure in case of expert users +% .area .. estimate area (not implemented; default 0) +% .surfaces .. further cortical surfaces +% .IS .. create inner surface (default 0) +% .OS .. create outer surface (default 0) +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + if nargin == 1 + P = char(job.data_surf); + else + error('Not enough parameters.'); + end + + if exist('rng','file') == 2, rng('default'); rng(0); else, rand('state',0); randn('state',0); end + + % default structure + def.fsavgDir = fullfile(fileparts(mfilename('fullpath')),'templates_surfaces'); + def.trerr = 0; % display errors + def.nproc = 0; % parallel processing + def.verb = cat_get_defaults('extopts.verb'); + def.debug = cat_get_defaults('extopts.verb')>2; + def.lazy = 0; % do not reprocess existing results + def.norm = 0; % apply inital surface normalization for job.normmeasure (GI measures) using cat_surf_scaling + % [0-none,1-default,12-affine,1-radius,11-hullradius,2-area,21-hullarea,30-surfacevolume,31-hullvolume]; + def.normprefix = 'n'; + def.FS_HOME = '/Volumes/WD4TBE2/TMP/freesurfer'; % necessary for Schaer's lGI +% output parameter of validated measures + def.GI = 0; % estimate absolute mean curvature + def.FD = 0; % estimate fractal dimension (Yotter:2012) + def.SD = 0; % estimate sulcal depth + def.tGI = 0; % Toro's GI + def.lGI = 0; % Schaer's lGI + % implemented but under test + def.area = 0; % estimate area + def.gmv = 0; % cortical volume + % experimental measures (cat_get_defaults('extopts.expertgui')) + % def.GIL = 0; % defined below due to numeric/structure definion + % further thickness measures by estimating the IS and OS by Tnormal that + % result in Tpbt = Tnormal = Tnear + def.thickness.Tfs = 0; % Freesurfer thickness metric = mean([ Tnear(IS) Tnear(OS) ],2) + def.thickness.Tmin = 0; % mininmal thickness metric = min([ Tnear(IS) Tnear(OS) ],2) + def.thickness.Tmax = 0; % maximal thickness metric = max([ Tnear(IS) Tnear(OS) ],2) that is only + % further surfaces + def.surfaces.IS = 0; % create inner surface + def.surfaces.OS = 0; % create outer surface + + job = cat_io_checkinopt(job,def); + job.FS_HOME = char(job.FS_HOME); + if isfield(job,'tGI') + if any(isinf(job.tGI)), job.tGI(isinf(job.tGI)) = -1; end + job.tGI = unique(job.tGI); + end + if isfield(job,'Tfs'), job.thickness.Tfs = job.Tfs; end + + % estimate Laplacian-based gyrification index (including inward, outward, and generalized GI) + if ~isfield(job,'GIL'), job.GIL = 0; end + + % split job and data into separate processes to save computation time + if isfield(job,'nproc') && job.nproc>0 && (~isfield(job,'process_index')) && numel(job.data_surf)>1 % no parallel processsing for just one file + + varargout{1} = cat_parallelize(job,mfilename,'data_surf'); + return + end + + + % new banner + if isfield(job,'process_index') && job.verb, spm('FnBanner',mfilename); end + + % display something + spm_clf('Interactive'); + cat_progress_bar('Init',size(P,1),'Processed surfaces','Surfaces Completed'); + + % just a counter for the progress bar + if cat_get_defaults('extopts.expertgui')<2 + sides = {'l','r'}; + else + sides = {'l','r','c'}; + end + measuresn = (job.GI>0) + (job.FD>0) + (job.SD>0) + ... + (job.area>0) + (job.gmv>0) + any(job.tGI>0) + (job.lGI>0) + ... + ( ( isnumeric(job.GIL) && job.GIL ) || ( isstruct(job.GIL) && job.GIL.GIL ) ) + ... + (job.surfaces.IS>0) + (job.surfaces.OS>0); + measuresn = measuresn * numel(sides); + + + % main loop + for i=1:size(P,1) + measuresi = 0; + pstr = sprintf(sprintf('%% %ds',max(10,round(log10(size(P,1))+3) * 2)),sprintf('%d/%d) ',i,size(P,1))); + nstr = repmat(' ',1,numel(pstr)); + + % go through left and right hemisphere + %try + for si=1:numel(sides) + %% file names + if si == 1 % lh + Pname = deblank(P(i,:)); + elseif si == 2 % rh + Pname = cat_surf_rename(deblank(P(i,:)),'side','rh'); + Pname = Pname{1}; + else + Pname = cat_surf_rename(deblank(P(i,:)),'side','cb'); + Pname = Pname{1}; + end + if ~exist(Pname,'file') && sides{si}=='c' + continue + end + + [pp,ff,ex] = spm_fileparts(Pname); + name = [ff ex]; + Pname2 = fullfile( pp , strrep([ff ex],'central','central2') ); % temporary surface with noise for failed save sulcal depth estimation + + % dependencies + % - measures without normalization + PGI = {fullfile(pp,strrep(ff,'central','gyrification')); % MNI approach + fullfile(pp,strrep(ff,'central','gyrification2'))}; % new approach (slower and probably not better) - just for developer tests + % also consider pial surfaces for sulcal depth + if ~isempty(strfind(ff,'pial')) + PSD = {fullfile(pp,strrep(ff,'pial','sulc'))}; + PSDsqrt = {fullfile(pp,strrep(ff,'pial','sqrtsulc'))}; + else + PSD = {fullfile(pp,strrep(ff,'central','depth'))}; + PSDsqrt = {fullfile(pp,strrep(ff,'central','sqrtdepth'))}; + end + PFD = fullfile(pp,strrep(ff,'central','fractaldimension')); + Parea = fullfile(pp,strrep(ff,'central','area')); + Pgmv{1} = fullfile(pp,strrep(ff,'central','gmv')); % RD202005: need projection based version for tests + + % - measures with/without normalization + switch job.norm %num2str( job.norm , '%d' ) + case 0, prefix = ''; % no normalization '' + case 1, prefix = job.normprefix; % default case with 'n' + otherwise, prefix = sprintf('%s%d', job.normprefix, job.norm); % special normalization (only for developer tests) + end + Psname = fullfile( pp , strrep([ff ex],'central',[prefix 'central']) ); + % -- toroGI + ntGI = numel( job.tGI ); + PtGI = cell(ntGI ,2); + for ti = 1:ntGI + if job.tGI(ti) == -1, tGIname = sprintf('%storoGIa' ,prefix); % adaptive radius + elseif isinf(job.tGI(ti)), tGIname = sprintf('%storoGIa' ,prefix); job.tGI(ti) = -1; % is not created but required as variable + elseif job.tGI(ti) == 1, tGIname = sprintf('%storoGI20mm' ,prefix); % one is the spacial case of 20 mm + elseif job.tGI(ti) > 1, tGIname = sprintf('%storoGI%02dmm',prefix,job.tGI(ti)); + elseif job.tGI(ti) == 0, tGIname = sprintf('%storoGI' ,prefix); % is not created but required as variable + else, error('cat_surf_parameters:badtGI','Incorrect tGI parameter.'); + end + PtGI{ti,1} = fullfile(pp,strrep(ff,'central',tGIname)); + PtGI{ti,2} = tGIname([1+numel(prefix), 5 + numel(prefix):numel(tGIname)]); + end + % -- Schaer's GI + PlGI = fullfile(pp,strrep(ff,'central',[prefix 'lGI'])); + % -- new experimental GIs + PiGI = fullfile(pp,strrep(ff,'central',[prefix 'inwardGI'])); + PoGI = fullfile(pp,strrep(ff,'central',[prefix 'outwardGI'])); + PgGI = fullfile(pp,strrep(ff,'central',[prefix 'generalizedGI'])); + % -- other surfaces + PIS = fullfile(pp,strrep([ff ex],'central','white')); + POS = fullfile(pp,strrep([ff ex],'central','pial')); + Psphere = fullfile(pp,strrep(name,'central','sphere')); + Ppbt = fullfile(pp,strrep(ff,'central','pbt')); + Pspbt = fullfile(pp,strrep(ff,'central','spbt')); + + % thickness measures + Ptfs = fullfile(pp,strrep(ff,'central','thicknessfs')); + Ptmin = fullfile(pp,strrep(ff,'central','thicknessmin')); + Ptmax = fullfile(pp,strrep(ff,'central','thicknessmax')); + %{ + Pspherereg = fullfile(pp,strrep(name,'central','sphere')); + [pp1,pp2] = spm_fileparts(pp); + Pxml = { + fullfile(pp1,strrep(pp2,'surf','report'),[cat_io_strrep(ff,{'lh.','rh.','cb.','central.'},{'','','','cat_'}) '.xml']); + fullfile(pp1,strrep(pp2,'surf','') ,[cat_io_strrep(ff,{'lh.','rh.','cb.','central.'},{'','','','cat_'}) '.xml']); % for phantoms + }; + %} + if job.verb && si==1, fprintf('\n%sExtract parameters for %s\n',pstr,Pname); end + + + + % normalization by affine information? + % update normalization if input data has changed + if isstruct(job.GIL) + LGIpp = any(job.GIL.GIL == [1 4]) && cat_io_rerun(PiGI ,Pname) && ... + any(job.GIL.GIL == [2 4]) && cat_io_rerun(PoGI ,Pname) && ... + any(job.GIL.GIL == [3 4]) && cat_io_rerun(PgGI ,Pname); + else + LGIpp = any(job.GIL == [1 4]) && cat_io_rerun(PiGI ,Pname) && ... + any(job.GIL == [2 4]) && cat_io_rerun(PoGI ,Pname) && ... + any(job.GIL == [3 4]) && cat_io_rerun(PgGI ,Pname); + end + if job.norm && any( [ ~job.lazy, LGIpp, ... + any( cat_io_rerun(PtGI(:,1) ,Pname) ), ( job.lGI && cat_io_rerun(PlGI ,Pname) ) ] ) + if ~exist(Psname,'file') + rn = cat_surf_scaling(struct('file',Pname,'norm',job.norm,'fname',Psname)); + end + % for old CAT results without pbt file + if job.gmv>1 && ~exist(Pspbt,'file') + T = cat_io_FreeSurfer('read_surf_data',Ppbt); + cat_io_FreeSurfer('write_surf_data',Pspbt,T * rn); + end + Pxname = Psname; + else + Pxname = Pname; + end + + + + + if job.area + %% local surface area by nearest neighbor approach (see Winkler 2012, 2017) + % As far as cat_surf_parameters characterize the original surface + % her only the simple surface area is esimated an mapped to all + % connected vertices (simply divided by 3 that describes the COM + % alingment but the alignments by the voronoi / outer-circle + % point would be more accurate). + % For area estimation scaling of the orinal surface is irelevant. + % RD202005: implement better mapping + stime = clock; + if ~cat_io_rerun(Parea,Pname) && job.lazy + if job.verb, fprintf('%sexist - Display %s\n',nstr,spm_file(Parea,'link','cat_surf_display(''%s'')')); end + else + Si = gifti(Pname); + area = cat_surf_fun('area',Si) * 1000; clear Si % in cm2 + cat_io_FreeSurfer('write_surf_data',Parea,area); clear area; + if job.verb, fprintf('%s%4.0fs - Display %s\n',nstr,etime(clock,stime),spm_file(Parea,'link','cat_surf_display(''%s'')')); end + end + + if nargout==1, varargout{1}.([sides{si} 'Parea' ]){i} = Parea; end + measuresi = measuresi + 1; cat_progress_bar('Set',i - 1 + measuresi/measuresn); + end + + + + + if job.gmv + %% local volume ... still under development ... do not use + stime = clock; + for gmvi = 1 + if gmvi == 1 + % based on the surface of Voronoi regions + if ~cat_io_rerun(Pgmv{gmvi},Pname) && job.lazy + if job.verb, fprintf('%sexist - Display %s\n',nstr,spm_file(Pgmv{gmvi},'link','cat_surf_display(''%s'')')); end + else + Sw = cat_surf_fun('whitevar',Pname,Ppbt); + Sp = cat_surf_fun('pialvar' ,Pname,Ppbt); + gmv = cat_surf_fun('gmv',Sw,Sp); clear Sw Sp; + cat_io_FreeSurfer('write_surf_data',Pgmv{gmvi},gmv); clear gmv; + if job.verb, fprintf('%s%4.0fs - Display %s\n',nstr,etime(clock,stime),spm_file(Pgmv{gmvi},'link','cat_surf_display(''%s'')')); end + end + elseif gmvi == 2 + % RD202005: For a comparision a local mapping of the p1 map sould be implementet here. + end + end + if nargout==1 && gmvi==1, varargout{1}.([sides{si} 'Pgmv' ]){i} = Pgmv{gmvi}; end + measuresi = measuresi + 1; cat_progress_bar('Set',i - 1 + measuresi/measuresn); + if exist(Pspbt,'file'), delete(Pspbt); end + end + + + + + if job.GI + %% gyrification index based on absolute mean curvature + for GIi = setdiff( (1:2) .* (job.GI==[1 2] | isinf(job.GI) ) ,0) % different approaches + if ~cat_io_rerun(PGI{GIi},Pname) && job.lazy + if job.verb, fprintf('%sexist - Display %s\n',nstr,spm_file(PGI{GIi},'link','cat_surf_display(''%s'')')); end + else + stime = clock; + if GIi==2 % Dong + curv = cat_spm_mesh_curvature( export(gifti(Pname),'patch') ,'tri'); + cat_io_FreeSurfer('write_surf_data',PGI{GIi},curv ); clear curv; + else % MNI + cmd = sprintf('CAT_DumpCurv ""%s"" ""%s"" 0 0 1',Pname,PGI{GIi}); + cat_system(cmd,job.debug,job.trerr); + end + if job.verb, fprintf('%s%4.0fs - Display %s\n',nstr,etime(clock,stime),spm_file(PGI{GIi},'link','cat_surf_display(''%s'')')); end + end + if nargout==1 && GIi==1, varargout{1}.([sides{si} 'PGI' ]){i} = PGI{GIi}; end + if nargout==1 && GIi==2, varargout{1}.([sides{si} 'PGIx' ]){i} = PGI{GIi}; end + end + measuresi = measuresi + 1; cat_progress_bar('Set',i - 1 + measuresi/measuresn); + end + + + + + if job.SD + %% sulcus depth + % optionally transform SD with sqrt + if job.SD == 2 + option = ' -sqrt '; + PSD = PSDsqrt; + else + option = ''; + end + SDi = 1; % default sulcal depth ... the LGI or eidist would provide slightly different SD that accounts for WM + if ~cat_io_rerun(PSD{SDi},Pname) && job.lazy + if job.verb, fprintf('%sexist - Display %s\n',nstr,spm_file(PSD{SDi},'link','cat_surf_display(''%s'')')); end + else + stime = clock; + cmd = sprintf('CAT_SulcusDepth %s ""%s"" ""%s"" ""%s""',option,Pname,Psphere,PSD{SDi}); + try + cat_system(cmd,job.debug*0,job.trerr*0); + catch + % catch block that was required for some simulated datasets + % and can probably removed in future (RD 202002) + S = gifti( Pname ); + + S.vertices = S.vertices + 0.1 * (rand(size(S.vertices))-0.5); + MHS = spm_mesh_smooth(S); s=1; + S.vertices = [ ... + spm_mesh_smooth(MHS,double(S.vertices(:,1)),s) , ... + spm_mesh_smooth(MHS,double(S.vertices(:,2)),s) , ... + spm_mesh_smooth(MHS,double(S.vertices(:,3)),s) ]; + clear MHS; + + save( gifti(struct('faces',S.faces,'vertices',S.vertices)),Pname2,'Base64Binary'); clear S; + cmd = sprintf('CAT_SulcusDepth %s ""%s"" ""%s"" ""%s""',option,Pname2,Psphere,PSD{SDi}); + delete(Pname2); + + cat_system(cmd,job.debug,job.trerr); + end + if job.verb, fprintf('%s%4.0fs - Display %s\n',nstr,etime(clock,stime),spm_file(PSD{SDi},'link','cat_surf_display(''%s'')')); end + end + if nargout==1 && SDi==1, varargout{1}.([sides{si} 'PSD' ]){i} = PSD{SDi}; end + measuresi = measuresi + 1; cat_progress_bar('Set',i - 1 + measuresi/measuresn); + end + + + + + if job.FD + %% fractal dimension using spherical harmonics + if ~cat_io_rerun(PFD,Pname) && job.lazy + if job.verb, fprintf('%sexist - Display %s\n',nstr,spm_file(PFD,'link','cat_surf_display(''%s'')')); end + else + stime = clock; + cmd = sprintf('CAT_FractalDimension -sphere ""%s"" -nosmooth ""%s"" ""%s"" ""%s""',Psphere,Pname,Psphere,PFD); + cat_system(cmd,job.debug,job.trerr); + if job.verb, fprintf('%s%4.0fs - Display %s\n',nstr,etime(clock,stime),spm_file(PFD,'link','cat_surf_display(''%s'')')); end + end + if nargout==1, varargout{1}.([sides{si} 'PFD']){i} = PFD; end + measuresi = measuresi + 1; cat_progress_bar('Set',i - 1 + measuresi/measuresn); + end + + + + + + + + if job.tGI + %% Toro's gyrification index + for ti = 1:numel( job.tGI ) + if job.tGI(ti)~=0 + if ~cat_io_rerun(PtGI{ti,1},Pxname) && job.lazy + if job.verb, fprintf('%sexist - Display %s\n',nstr,spm_file(PtGI{ti,1},'link','cat_surf_display(''%s'')')); end + else + stime = clock; + cmd = sprintf('CAT_DumpSurfaceRatio ""%s"" ""%s"" %d -no_normalization %d',Pxname,PtGI{ti,1},job.tGI( ti ),job.tGI( ti )<0); + cat_system(cmd,job.debug,job.trerr); + if job.verb, fprintf('%s%4.0fs - Display %s\n',nstr,etime(clock,stime),spm_file(PtGI{ti,1},'link','cat_surf_display(''%s'')')); end + end + if nargout==1, varargout{1}.([sides{si} 'P' PtGI{ti,2} ]){i} = PtGI{ti,1}; end + end + end + + measuresi = measuresi + 1; cat_progress_bar('Set',i - 1 + measuresi/measuresn); + end + + + + if job.lGI + %% Schaer's GI + % Estimation of Schaer's GI in FreeSurfer using CAT surface. + % You have to update the job.FS_HOME directoy and you have to replace + % line 83 in mris_compute_lgi to use a different surface file + % ""${input}h"" for volume rending. + % line 82: # create a filled-volume from the input surface file... + % line 83: set cmd=(mris_fill -c -r 0.5 ${input}h ${tmpdir}/${input}.filled.mgz) + % The GI is only added for internal comparisons. + if ~exist(job.FS_HOME,'dir') + cat_io_cprintf('err',sprintf('%sERROR - lGI estimation only internally. \n',nstr)); + else + stime = clock; + + if ~cat_io_rerun(PlGI,Pxname) && job.lazy + % check for old unremoved temporar data + Ppialfs = fullfile(pp,strrep(ff,'central','pialfs')); + [lpp,lff,lee] = spm_fileparts(Ppialfs); + tmpdir = fullfile(lpp,['tmp-mris_compute_lgi-' lff lee]); + + if exist(tmpdir,'dir') + % remove temp dir + files = cat_vol_findfiles(tmpdir,'*'); + for fi=1:numel(files), delete(files{fi}); end + rmdir(tmpdir); + end + + if nargout==1, varargout{1}.([sides{si} 'PlGI' ]){i} = PlGI; end + if job.verb, fprintf('%sexist - Display %s\n',nstr,spm_file(PlGI,'link','cat_surf_display(''%s'')')); end + else + Ppial = cat_surf_fun('pial',Pxname,Ppbt); + + S = gifti(Ppial); + %% smooth surface to reduce problems due to self-intersections? + s = 0; + if s>0 + MHS = spm_mesh_smooth(S); + S.vertices = [ ... + spm_mesh_smooth(MHS,double(S.vertices(:,1)),s) , ... + spm_mesh_smooth(MHS,double(S.vertices(:,2)),s) , ... + spm_mesh_smooth(MHS,double(S.vertices(:,3)),s) ]; + end + + % write hull surface for estimation + Ppial = cat_surf_fun('pial',Pxname,Ppbt); + Ppialfs = fullfile(pp,strrep(ff,'central','pialfs')); + cat_io_FreeSurfer('write_surf',Ppialfs,S); + + % Reorient file to support correct volume rendering to create the hull. + % I don't know why but without the extra points only a small box is rendered. + S2.vertices = [-S.vertices(:,1) S.vertices(:,3) -S.vertices(:,2)]; + S2.faces = [ S.faces(:,2) S.faces(:,1) S.faces(:,3)]; + S2.vertices = [S2.vertices; + [-128 -128 -128; + 128 128 128]]; + Ppialfsh = fullfile(pp,[strrep(ff,'central','pialfs') 'h']); + cat_io_FreeSurfer('write_surf',Ppialfsh,S2); clear S2; + + + %% external solution that calls nearly the original script + % Although it is possible to call the main script with """" + % to support blanks the FS scripts do not, so I just print + % an error here, followed by the main FS error message. + [lpp,lff,lee] = spm_fileparts(Ppialfs); + if sum(strfind(Ppialfs,' ')), cat_io_cprintf('err',... + sprintf('Error: Freesurfer do not like blanks in filenames! Found %d blanks in: \n %s\n', ... + sum(strfind(Ppialfs,' ')),Ppialfs)); + end + cmd = [ ... + 'export FREESURFER_HOME=""' job.FS_HOME '""; ' ... % set FreeSurfer home (FSH) directory + 'tcsh ""$FREESURFER_HOME' filesep 'SetUpFreeSurfer.csh""; ' ... % export FSH + 'PATH=$PATH:""' job.FS_HOME filesep 'bin"":""' job.FS_HOME filesep 'fsfast/bin"":""' matlabroot '/bin"";' ... % add FSH bin directories + 'cd ""' lpp '""; tcsh ""$FREESURFER_HOME/bin/mris_compute_lgi"" --i ""' [lff lee] '""; ' ... % call lGI script + ]; + + [status, result] = system(cmd); + if status || ~isempty(strfind(result,'ERROR')) || ~isempty(strfind(result,'Segmentation fault')) %#ok + [status, result] = system(cmd); + end + if status || ~isempty(strfind(result,'ERROR')) || ~isempty(strfind(result,'Segmentation fault')) %#ok + cat_check_system_output(status,result,job.debug,job.trerr); + + fid = fopen([Ppialfs '.log'],'w'); + fprintf(fid, '%s',result); + fclose(fid); + clear fid result status + + % remove temp dir + tmpdir = fullfile(lpp,['tmp-mris_compute_lgi-' lff lee]); + if exist(tmpdir,'dir') + files = cat_vol_findfiles(tmpdir,'*'); + for fi=1:numel(files), delete(files{fi}); end + rmdir(tmpdir); + end + clear tmpdir + end + clear status result + if exist(fullfile(lpp,[lff lee '_lgi']),'file') + movefile(fullfile(lpp,[lff lee '_lgi']), PlGI); + end + + + if exist(Ppial ,'file'), delete(Ppial ); end + if exist(Ppialfs ,'file'), delete(Ppialfs ); end + if exist(Ppialfsh,'file'), delete(Ppialfsh); end + + %% dispaly something + if exist(job.FS_HOME,'dir') + if exist(PlGI,'file') + if nargout==1, varargout{1}.([sides{si} 'PlGI' ]){i} = PlGI; end + if job.verb, fprintf('%s%4.0fs - Display %s\n',nstr,etime(clock,stime),spm_file(PlGI,'link','cat_surf_display(''%s'')')); end + else + cat_io_cprintf('err',sprintf('%sERROR - no output %s\n',nstr,PlGI)); + end + end + end + + measuresi = measuresi + 1; cat_progress_bar('Set',i - 1 + measuresi/measuresn); + end + end + + + + + + + + %% Developer folding measures + % ------------------------------------------------------------------ + % These approaches are still in development. + % See cat_surf_gyrification for further information. + % ------------------------------------------------------------------ + if ( isnumeric(job.GIL) && job.GIL ) || ( isstruct(job.GIL) && job.GIL.GIL ) + %% gyrification index based on laplacian GI + if isnumeric(job.GIL) % default user mode only support default values + GIL = job.GIL; + GILjob = struct('verb',job.verb); + else + GIL = job.GIL.GIL; + GILjob = job.GIL; + GILjob.verb = 0; + GILjob.GIprefix = prefix; + + % new experimental GIs + if isfield(job.GIL,'suffix') && isempty(job.GIL.suffix) + PiGI = fullfile(pp,strrep(ff,'central',[prefix 'inwardGI',job.GIL.suffix])); + PoGI = fullfile(pp,strrep(ff,'central',[prefix 'outwardGI',job.GIL.suffix])); + PgGI = fullfile(pp,strrep(ff,'central',[prefix 'generalizedGI',job.GIL.suffix])); + Phull = fullfile(pp,strrep([ff '.gii'],'central',[prefix,'hull',job.GIL.suffix])); + Pcore = fullfile(pp,strrep([ff '.gii'],'central',[prefix,'core',job.GIL.suffix])); + else + Phull = fullfile(pp,strrep([ff '.gii'],'central',[prefix 'hull'])); + Pcore = fullfile(pp,strrep([ff '.gii'],'central',[prefix 'core'])); + end + end + + % run GI estimation if ~lazy or any output does not exist + if job.lazy==0 || ... + ( any(GIL==[1,4]) && ~exist(PiGI,'file') ) || ... + ( any(GIL==[2,4]) && ~exist(PoGI,'file') ) || ... + ( any(GIL==[3,4]) && ~exist(PgGI,'file') ) + + + % do not display GI processing details while you write into a file! + if isfield(job,'process_index'), GILjob.verb = 0; end + + + % process data + stime = clock; + first = 1; + PGIL = cat_surf_gyrification(Pxname,GILjob); + else + first = 2; + PGIL = {PiGI,PoGI,PgGI}; + if ~exist(PiGI,'file'), PGIL{1} = ''; end + if ~exist(PoGI,'file'), PGIL{2} = ''; end + if ~exist(PgGI,'file'), PGIL{3} = ''; end + end + if nargout && exist('Phull','var') %&& isfield(GILjob,'GIwritehull') && any(GILjob.GIwritehull==[1 3]) + if exist(Phull,'file') + varargout{1}.([sides{si} 'Phull']){i} = Phull; + else + varargout{1}.([sides{si} 'Phull']){i} = ''; + end + end + if nargout && exist('Phull','var') %&& isfield(GILjob,'GIwritehull') && any(GILjob.GIwritehull==[2 3]) + if exist(Pcore,'file') + varargout{1}.([sides{si} 'Pcore']){i} = Pcore; + else + varargout{1}.([sides{si} 'Pcore']){i} = ''; + end + end + + type = 'iog'; + for gi=1:numel(PGIL) + if job.verb && ~isempty(PGIL{1}) + if first==1 + fprintf('%s%4.0fs - Display %s\n',nstr,etime(clock,stime),spm_file(PGIL{gi},'link','cat_surf_display(''%s'')')); + first = 0; + elseif first==2 + fprintf('%sexist - Display %s\n',nstr,spm_file(PGIL{gi},'link','cat_surf_display(''%s'')')); + elseif ~isempty(PGIL{gi}) + fprintf('%s - Display %s\n',nstr,spm_file(PGIL{gi},'link','cat_surf_display(''%s'')')); + end + if nargout==1, varargout{1}.([sides{si} 'P' type(gi) 'GI']){i} = PGIL{gi}; end + end + end + + measuresi = measuresi + 1; cat_progress_bar('Set',i - 1 + measuresi/measuresn); + end + + + + + %% ---------------------------------------------------------------------- + % Further thickness measures. + % ---------------------------------------------------------------------- + %existIOS = [exist(PIS,'file') exist(POS,'file')]; + + if job.thickness.Tfs + if ~cat_io_rerun(Ptfs,Pname) && job.lazy + if job.verb, fprintf('%sexist - Display %s\n',nstr,spm_file(Ptfs,'link','cat_surf_display(''%s'')')); end + else + stime = clock; + cat_surf_fun('Tfs',Pname); + if job.verb, fprintf('%s%4.0fs - Display %s\n',nstr,etime(clock,stime),spm_file(Ptfs,'link','cat_surf_display(''%s'')')); end + end + if nargout==1, varargout{1}.([sides{si} 'Tfs']){i} = Ptfs; end + measuresi = measuresi + 1; cat_progress_bar('Set',i - 1 + measuresi/measuresn); + end + + if job.thickness.Tmin + if ~cat_io_rerun(Ptmin,Pname) && job.lazy + if job.verb, fprintf('%sexist - Display %s\n',nstr,spm_file(Ptmin,'link','cat_surf_display(''%s'')')); end + else + stime = clock; + cat_surf_fun('Tmin',Pname); + if job.verb, fprintf('%s%4.0fs - Display %s\n',nstr,etime(clock,stime),spm_file(Ptmin,'link','cat_surf_display(''%s'')')); end + end + if nargout==1, varargout{1}.([sides{si} 'Tmin']){i} = Ptmin; end + measuresi = measuresi + 1; cat_progress_bar('Set',i - 1 + measuresi/measuresn); + end + + if job.thickness.Tmax + if ~cat_io_rerun(Ptmax,Pname) && job.lazy + if job.verb, fprintf('%sexist - Display %s\n',nstr,spm_file(Ptmax,'link','cat_surf_display(''%s'')')); end + else + stime = clock; + cat_surf_fun('Tmax',Pname); + if job.verb, fprintf('%s%4.0fs - Display %s\n',nstr,etime(clock,stime),spm_file(Ptmax,'link','cat_surf_display(''%s'')')); end + end + if nargout==1, varargout{1}.([sides{si} 'Tmax']){i} = Ptmax; end + measuresi = measuresi + 1; cat_progress_bar('Set',i - 1 + measuresi/measuresn); + end + + % delete temporary surface files + %if existIOS + % remove white or pial surface if there were created in this function ... + %end + + %% ---------------------------------------------------------------------- + % No measures, but I do not want another script. However, this leads + % to problems in batch processing, e.g. to resample and smooth the + % results that are surfaces rather than textures (RD20190408). + % ---------------------------------------------------------------------- + if job.surfaces.IS + if ~cat_io_rerun(PIS,Pname) && job.lazy + if job.verb, fprintf('%sexist - Display %s\n',nstr,spm_file(PIS,'link','cat_surf_display(''%s'')')); end + else + stime = clock; + cat_surf_fun('white',Pname); + if job.verb, fprintf('%s%4.0fs - Display %s\n',nstr,etime(clock,stime),spm_file(PIS,'link','cat_surf_display(''%s'')')); end + end + if nargout==1, varargout{1}.([sides{si} 'PIS']){i} = PIS; end + measuresi = measuresi + 1; cat_progress_bar('Set',i - 1 + measuresi/measuresn); + end + + if job.surfaces.OS + if ~cat_io_rerun(PIS,Pname) && job.lazy + if job.verb, fprintf('%sexist - Display %s\n',nstr,spm_file(POS,'link','cat_surf_display(''%s'')')); end + else + stime = clock; + cat_surf_fun('pial',Pname); + if job.verb, fprintf('%s%4.0fs - Display %s\n',nstr,etime(clock,stime),spm_file(POS,'link','cat_surf_display(''%s'')')); end + end + if nargout==1, varargout{1}.([sides{si} 'POS']){i} = POS; end + measuresi = measuresi + 1; cat_progress_bar('Set',i - 1 + measuresi/measuresn); + end + + % do not delete it otherwise lazy will not work (new file > new processing) + %if exist(Psname ,'file') && ~strcmp(Psname,Pname), delete(Psname); end + end + cat_progress_bar('Set',i); + + + + + if isfield(job,'process_index') && job.verb + fprintf('%sDone\n',nstr); + end + % catch + % if job.verb, cat_io_cprintf('err','%sERROR - Check data of %s\n',nstr,spm_file(P(i,:),'link','cat_surf_display(''%s'')')); end + % end + end + if isfield(job,'process_index') && job.verb + fprintf('\nDone\n'); + end + + cat_progress_bar('Clear'); + + if nargout && ~exist('varargout','var'), varargout{1} = struct(''); end + + % remove files that do not exist + varargout{1} = cat_io_checkdepfiles( varargout{1} ); +end +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_io_lazy.m",".m","4494","116","function run = cat_io_lazy(files,filedates,verb,force) +%cat_io_lazy. Test if a file is newer than another file. +% This function is used to estimated if a file is newer than another given +% file or date. For instance file is the result of anther file that was +% changed in the meantime, it has to be reprocessed. +% +% run = cat_io_lazy(files,filedates,verb) +% +% run .. logical vector with the number of given files +% cell if directories or wildcards are used +% files .. filenames (cellstr or char) +% filedat .. filenames (cellstr or char) or datetimes or datenum +% verb .. print details about the files and about the result +% (default = 0.5 only display if reprocessing is NOT reqired) +% force .. use also in non developer mode (default = 0) +% +% Examples: +% 1) Is the working directory younger than the SPM dir? +% cat_io_lazy(pwd,spm('dir'); +% +% 2) Is the working directory younger than one month? +% cat_io_lazy(pwd,clock - [0 1 0 0 0 0]) +% +% 3) Is this function younger than one year? +% cat_io_lazy(which('cat_io_lazy'),clock - [1 0 0 0 0 0]) +% +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + if ~exist('verb','var'), verb = 0.5; end + if ~exist('force','var'), force = 1; end + + % only use that function in developer mode because it's simply too dangerous + % if files are not processed if already existing and parameter changed + if cat_get_defaults('extopts.expertgui') < 2 && ~force + if verb, cat_io_cprintf([0.5 0.0 0.0],' Reprocessing! \n'); end + run = zeros(size(files)); + return + end + + files = cellstr(files); + if iscellstr(filedates) || ischar(filedates) + filedates = cellstr(filedates); + if numel(filedates) == 1 + filedates = repmat(filedates,numel(files),1); + else + if ~isempty(filedates) && numel(files) ~= numel(filedates) + error('ERROR:cat_io_lazy:inputsize','Number of files and filedates has to be equal.\n') + end + end + else + if size(filedates,1) + filedates = repmat(filedates,numel(files),1); + end + end + + run = ones(size(files)); + for fi = 1:numel(files) + if ~exist(files{fi},'file') + run(fi) = 1; + else + fdata = dir(files{fi}); + if numel(fdata)>1 + run = num2cell(run); + end + if exist('filedates','var') && iscellstr(filedates) && exist(filedates{fi},'file') + fdata2 = dir(filedates{fi}); + if numel(fdata)>1 + run{fi} = [fdata(:).datenum] < fdata2.datenum; + else + run(fi) = fdata.datenum < fdata2.datenum; + end + elseif ~isempty(filedates) + if numel(fdata)>1 + run{fi} = [fdata(:).datenum] < datenum( filedates(fi,:) ); + else + run(fi) = fdata.datenum < datenum( filedates(fi,:) ); + end + end + % be verbose only if verb>=1 or if no reprocessing is required + if verb >= 1 || (verb && ~( (iscell(run) && any(cell2mat(run))) || ( ismatrix(run) && any(run) ) )) + fprintf('\n'); + if numel(files)==1 + fprintf('\n Input file 1: %50s: %s\n',spm_str_manip( fdata.name , 'a50'),datestr(fdata.datenum) ); + fprintf('\n Input file 2: %50s: %s\n',spm_str_manip( fdata2.name, 'a50'),datestr(fdata2.datenum)); + else + if fi == 1 + fprintf('\n Input file 1: %50s: %s\n', spm_str_manip( fdata.name ,'a50'),datestr(fdata.datenum) ); + end + fprintf('\n Input file 2-%02d: %50s: %s\n',fi,spm_str_manip( fdata2.name,'a50'),datestr(fdata2.datenum)); + end + end + end + end + % be verbose only if verb>=1 or if no reprocessing is required + if verb >= 1 || ~( (iscell(run) && any(cell2mat(run))) || ( ismatrix(run) && any(run) ) ) + if verb >= 1 && ( (iscell(run) && any(cell2mat(run))) || ( ismatrix(run) && any(run) ) ) + if all(exf) + cat_io_cprintf([0.5 0.0 0.0],' Reprocessing is required. \n'); + elseif all(exf==0) && numel(files)>1 + cat_io_cprintf([0.5 0.0 0.0],' (Re)processing is required. \n'); + else + cat_io_cprintf([0.5 0.0 0.0],' Processing is required. \n'); + end + elseif verb + cat_io_cprintf([0.0 0.5 0.0],' Reprocessing is NOT required. \n'); + end + end +end +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_vol_defs.m",".m","9634","296","function vol = cat_vol_defs(job) +% Apply deformations to images. In contrast to spm_deformations images are saved +% in the original directory. +% FORMAT vol = cat_vol_defs(job) +% job - a job created via cat_conf_tools.m +% vol - cell of deformed output volumes (deformed images are only returned, but not saved as file) +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ +% +% based on spm_deformations.m + +many_images = 0; + +if isfield(job,'field') + PU = job.field; +else + PU = job.field1; + many_images = 1; +end + +def.verb = cat_get_defaults('extopts.verb'); +job = cat_io_checkinopt(job,def); + +PI = job.images; +interp = job.interp; + +if interp < 0 && job.modulate + warning('Modulation in combination with categorical interpolation is not meaningful and possible. Disable modulation.'); + job.modulate = 0; +end + +if nargout == 1 + vol = cell(numel(PU),numel(PI)); +end + +for i=1:numel(PU) + + % external call with PU as deformation field + if isnumeric(PU{i}) & isfield(job,'mat') + Def = PU{i}; + mat = job.mat; + else + [pth,nam,ext] = spm_fileparts(PU{i}); + PU{i} = fullfile(pth,[nam ext]); + + if isfield(job,'vox') && isfield(job,'bb') + [Def,mat] = get_comp(PU{i},job); + else + [Def,mat] = get_comp(PU{i}); + end + end + + for m=1:numel(PI) + + if many_images % many images + PIi = char(PI{m}); + else % many subjects + PIi = char(PI{m}{i}); + end + + if nargout == 1 + [PIri, vol{i,m}] = apply_def(Def,mat,PIi,interp,job.modulate,job.verb); + else + PIri = apply_def(Def,mat,PIi,interp,job.modulate,job.verb); + end + + if job.verb & ~isempty(PIri) + fprintf('Display resampled %s\n',spm_file(PIri,'link','spm_image(''Display'',''%s'')')); + end + end +end +return + +%_______________________________________________________________________ +function [Def,mat,vx,bb] = get_def(field) +% Load a deformation field saved as an image +Nii = nifti(field); +Def = single(Nii.dat(:,:,:,1,:)); +d = size(Def); +if d(4)~=1 || d(5)~=3, error('Deformation field is wrong!'); end +Def = reshape(Def,[d(1:3) d(5)]); +mat = Nii.mat; + +vx = sqrt(sum(Nii.mat(1:3,1:3).^2)); +if det(Nii.mat(1:3,1:3))<0, vx(1) = -vx(1); end + +o = Nii.mat\[0 0 0 1]'; +o = o(1:3)'; +dm = size(Nii.dat); +bb = [-vx.*(o-1) ; vx.*(dm(1:3)-o)]; + +%_______________________________________________________________________ +function Def = identity(d,M) +[y1,y2] = ndgrid(single(1:d(1)),single(1:d(2))); +Def = zeros([d 3],'single'); +for y3=1:d(3) + Def(:,:,y3,1) = y1*M(1,1) + y2*M(1,2) + (y3*M(1,3) + M(1,4)); + Def(:,:,y3,2) = y1*M(2,1) + y2*M(2,2) + (y3*M(2,3) + M(2,4)); + Def(:,:,y3,3) = y1*M(3,1) + y2*M(3,2) + (y3*M(3,3) + M(3,4)); +end + +%_______________________________________________________________________ +function [Def,mat] = get_comp(field,job) +% Return the composition of two deformation fields. + +[Def,mat,vx,bb] = get_def(field); + +% only estimate composite if job field is given +if nargin > 1 + % only move on if any vox or bb field is not NaN + if any(isfinite(job.vox)) | any(isfinite(job.bb)) + Def1 = Def; + mat1 = mat; + job.vox(~isfinite(job.vox)) = vx(~isfinite(job.vox)); + job.bb(~isfinite(job.bb)) = bb(~isfinite(job.bb)); + + [mat, dim] = spm_get_matdim('', job.vox, job.bb); + Def = identity(dim, mat); + M = inv(mat1); + tmp = zeros(size(Def),'single'); + tmp(:,:,:,1) = M(1,1)*Def(:,:,:,1)+M(1,2)*Def(:,:,:,2)+M(1,3)*Def(:,:,:,3)+M(1,4); + tmp(:,:,:,2) = M(2,1)*Def(:,:,:,1)+M(2,2)*Def(:,:,:,2)+M(2,3)*Def(:,:,:,3)+M(2,4); + tmp(:,:,:,3) = M(3,1)*Def(:,:,:,1)+M(3,2)*Def(:,:,:,2)+M(3,3)*Def(:,:,:,3)+M(3,4); + Def(:,:,:,1) = single(spm_diffeo('bsplins',Def1(:,:,:,1),tmp,[1,1,1,0,0,0])); + Def(:,:,:,2) = single(spm_diffeo('bsplins',Def1(:,:,:,2),tmp,[1,1,1,0,0,0])); + Def(:,:,:,3) = single(spm_diffeo('bsplins',Def1(:,:,:,3),tmp,[1,1,1,0,0,0])); + clear tmp + end +end + +%_______________________________________________________________________ +function [out, wvol] = apply_def(Def,mat,filenames,interp0,modulate,verb) +% Warp an image or series of images according to a deformation field + +interp = [interp0*[1 1 1], 0 0 0]; +dim = size(Def); +dim = dim(1:3); +if nargout == 2 + wvol = cell(size(filenames,1),1); + out = ''; +end + +for i=1:size(filenames,1) + + % Generate headers etc for output images + %---------------------------------------------------------------------- + [pth,nam,ext] = spm_fileparts(deblank(filenames(i,:))); + NI = nifti(fullfile(pth,[nam ext])); + j_range = 1:size(NI.dat,4); + k_range = 1:size(NI.dat,5); + l_range = 1:size(NI.dat,6); + + if nargout < 2 + NO = NI; + ext = '.nii'; + + % use float for modulated images + if modulate + NO.dat.scl_slope = 1.0; + NO.dat.scl_inter = 0.0; + NO.dat.dtype = 'float32-le'; + end + + % set slope to 1 for categorical interpolation + if interp0 < 0 + NO.dat.scl_slope = 1.0; + NO.dat.scl_inter = 0.0; + + % select data type w.r.t. maximum value + f0 = single(NI.dat(:,:,:,:,:,:)); + max_val = max(f0(:)); clear f0 + if max_val < 2^8 + NO.dat.dtype = 'uint8-le'; + if verb, fprintf('Set data type to uint8\n'); end + elseif max_val < 2^16 + NO.dat.dtype = 'uint16-le'; + if verb, fprintf('Set data type to uint16\n'); end + else + NO.dat.dtype = 'float32-le'; + if verb, fprintf('Set data type to float32\n'); end + end + end + + NO.dat.dim = [dim NI.dat.dim(4:end)]; + NO.dat.offset = 0; % For situations where input .nii images have an extension. + NO.mat = mat; + NO.mat0 = mat; + NO.mat_intent = 'Aligned'; + NO.mat0_intent = 'Aligned'; + + switch modulate + case 0 + NO.dat.fname = fullfile(pth,['w',nam,ext]); + NO.descrip = sprintf('Warped'); + case 1 + NO.dat.fname = fullfile(pth,['mw',nam,ext]); + NO.descrip = sprintf('Warped & Jac scaled'); + case 2 + NO.dat.fname = fullfile(pth,['m0w',nam,ext]); + NO.descrip = sprintf('Warped & Jac scaled (nonlinear only)'); + end + out = NO.dat.fname; + + NO.extras = []; + create(NO); + end + + if modulate + dt = spm_diffeo('def2det',Def)/det(mat(1:3,1:3)); + dt(:,:,[1 end]) = NaN; + dt(:,[1 end],:) = NaN; + dt([1 end],:,:) = NaN; + + % for modulation of non-linear parts only we have to remove the affine part + % of the jacobian determinant + if modulate == 2 + [x1,x2,x3] = ndgrid(single(1:size(Def,1)),single(1:size(Def,2)),single(1:size(Def,3))); + X = cat(4,x1,x2,x3); + Ma = spm_get_closest_affine(X,Def); + M3 = Ma\mat; + dt = dt*abs(det(M3)); + end + + end + + if nargout == 2, wvol{i} = zeros([dim NI.dat.dim(4:end)]); end + for j=j_range + + M0 = NI.mat; + if ~isempty(NI.extras) && isstruct(NI.extras) && isfield(NI.extras,'mat') + M1 = NI.extras.mat; + if size(M1,3) >= j && sum(sum(M1(:,:,j).^2)) ~=0 + M0 = M1(:,:,j); + end + end + M = inv(M0); + % Generate new deformation (if needed) + Y = affine(Def,M); + % Write the warped data for this time point + %------------------------------------------------------------------ + for k=k_range + for l=l_range + f0 = single(NI.dat(:,:,:,j,k,l)); + if interp0>=0 + c = spm_diffeo('bsplinc',f0,interp); + f1 = spm_diffeo('bsplins',c,Y,interp); + else + % Warp labels + U = unique(f0(:)); + if numel(U)>500 + fprintf('Categorical interpolation of so many labels will be quite slow...\n'); + end + if numel(U)>1100 + error('Too many label values.'); + end + f1 = zeros(dim(1:3),class(f0)); + p1 = zeros(size(f1),'single'); + for u=U' + g0 = single(f0==u); + tmp = spm_diffeo('bsplins',g0,Y,[abs(interp(1:3)) interp(4:end)]); + msk1 = (tmp>p1); + p1(msk1) = tmp(msk1); + f1(msk1) = u; + end + end + if modulate + f1 = f1.*double(dt); + end + + if nargout < 2 + NO.dat(:,:,:,j,k,l) = f1; + else + wvol{i}(:,:,:,j,k,l) = f1; + end + end + end + end + +end +return; + +%========================================================================== +% function Def = affine(y,M) +%========================================================================== +function Def = affine(y,M) +Def = zeros(size(y),'single'); +Def(:,:,:,1) = y(:,:,:,1)*M(1,1) + y(:,:,:,2)*M(1,2) + y(:,:,:,3)*M(1,3) + M(1,4); +Def(:,:,:,2) = y(:,:,:,1)*M(2,1) + y(:,:,:,2)*M(2,2) + y(:,:,:,3)*M(2,3) + M(2,4); +Def(:,:,:,3) = y(:,:,:,1)*M(3,1) + y(:,:,:,2)*M(3,2) + y(:,:,:,3)*M(3,3) + M(3,4); +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_vol_slice_overlay.m",".m","27224","1029","function OV = cat_vol_slice_overlay(OV) +% Extension/wrapper to slice_overlay +% Call help for slice_overlay for any additional help +% +% Additional fields to slice_overlay: +% OV.name - char array of filenames for overlay that can be interactively +% selected +% OV.slices_str - char array of slice values (e.g. '-32:2:20') +% use empty string for automatically estimating slices with +% local maxima +% OV.xy - define number of columns and rows +% comment this out for interactive selection or set the values +% to [Inf 1] for using one row and automatically estimate number +% of columns or use [1 Inf] for using one column +% OV.atlas - define atlas for labeling (e.g. 'cat12_cobra') +% comment this out for interactive selection +% or use 'none' for no atlas information +% OV.min_extent - minimum cluster extent for atlas labeling +% OV.min_overlap- minimum overlap to atlas regions for atlas labeling +% OV.save - save result as png/jpg/pdf/tif +% comment this out for interactive selection or use '' for not +% saving any file or use just file extension (png/jpg/pdf/tif) to +% automatically estimate filename to save +% OV.FS - normalized font size (default 0.08) +% OV.name_subfolder +% - if result is saved as image use up to 2 subfolders to add their +% names to the filename (default 1) +% OV.overview - use empty brackets to not suppress slice overview (.e.g []); +% OV.pos - define first two numbers of image position +% OV.bkg_col - color of background ([0 0 0] as default) +% OV.fig - figure number (default 22) +% OV.cbar - show colorbar (leave empty for no colorbar) +% OV.labels - show slice label text (leave empty for no label text) +% +% OV.clip - clip (limit) image for thresholding. This can be used to set +% the image to defined values (e.g. NaN) for the given range +% +% see cat_vol_slice_overlay_ui.m for an example +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +clear global SO +global SO + +if ~nargin + + imgs = spm_select(2, 'image', 'Select additional overlay image', cat_get_defaults('extopts.shootingT1')); + if isempty(imgs) + return; + end + OV = pr_basic_ui(imgs, 0); + + % set options + OV.opacity = Inf; + OV.reference_image = deblank(imgs(1, :)); + OV.reference_range = OV.img(1).range; + OV.name = imgs(2:end, :); + OV.cmap = OV.img(2).cmap; + OV.range = OV.img(2).range; + OV.slices_str = ''; +end + +% get fontsize +if isfield(OV,'FS') + FS = OV.FS; +else + FS = 0.08; +end + +if ~isfield(OV,'fig') + OV.fig = 22; +end + +% hot colormap by default +if ~isfield(OV,'cmap') + OV.cmap = hot(256); +end + +% clip colorbar +if isfield(OV,'clip') && all(isfinite(OV.clip)) && OV.clip(2) ~= OV.clip(1) + ncol = length(OV.cmap); + col_step = (OV.range(2) - OV.range(1)) / ncol; + cmin = max([1, ceil((OV.clip(1) - OV.range(1)) / col_step)]); + cmax = min([ncol, floor((OV.clip(2) - OV.range(1)) / col_step)]); + OV.cmap(cmin:cmax, :) = repmat([0.5 0.5 0.5], (cmax - cmin + 1), 1); + OV.func = sprintf('i1(i1>%f & i1<%f)=NaN;',OV.clip(1),OV.clip(2)); +else + OV.clip = [Inf -Inf]; +end + +% black background by default +if ~isfield(OV,'bkg_col') + SO.bkg_col = [0 0 0]; +else + SO.bkg_col = OV.bkg_col; +end + +% check filename whether log. scaling was used +OV.logP = zeros(size(OV.name, 1)); +for i = 1:size(OV.name, 1) + if ~isempty(strfind(OV.name(i, :), 'logP')) || ~isempty(strfind(OV.name(i, :), 'log_')) + OV.logP(i) = 1; + end +end + +% check fields of OV structure +fieldnames = char('reference_image', 'reference_range', ... + 'opacity', 'cmap', 'name', 'range', 'logP', 'slices_str', 'transform'); +for i = 1:size(fieldnames, 1) + str = deblank(fieldnames(i, :)); + if ~isfield(OV, str) + error([str ' not defined']); + end +end + +cmap_bivariate = [1 - (hot); hot]; % colormap if range(1) < 0 + +if isfield(OV, 'labels') + SO.labels = OV.labels; + if ~isempty(SO.labels) + SO.labels.size = FS*0.65; + end +end + +if isfield(OV, 'overview') + SO.overview = OV.overview; +end + +if isfield(OV, 'cbar') + SO.cbar = OV.cbar; +else + SO.cbar = 2; % colorbar +end + +n = size(OV.name, 1); + +str = deblank(OV.name(1, :)); +for i = 2:n, str = [str '|' deblank(OV.name(i, :))]; end + +if n > 1 + sel = spm_input('Select image', 1, 'm', str); +else + sel = 1; +end + +OV.name = deblank(OV.name(sel, :)); + +% if only one argument is given assume that parameters are the same for all files +if size(OV.range, 1) > 1 + range = OV.range(sel, :); +else + range = OV.range; +end + +if size(OV.logP, 1) > 1 + logP = OV.logP(sel); +else + logP = OV.logP; +end + +% for log-scaled p-values we should rather use gt than ge for comparison with threshold +if logP + compare_to_threshold = @(a,b) gt(a,b); +else + compare_to_threshold = @(a,b) ge(a,b); +end + +img = OV.name; + +n_slice = size(OV.slices_str, 1); +if n_slice > 0 + for i = 1:n_slice + try + slices{i} = eval(OV.slices_str(i, :)); + catch + slices{i} = []; + end + end +else + if isfield(OV,'slices') + slices{1} = OV.slices; + else + SO.img(2).vol = spm_vol(OV.name); + if isfield(OV,'func') + [mx, mn, XYZ, img2] = volmaxmin(SO.img(2).vol,OV.func); + else + [mx, mn, XYZ, img2] = volmaxmin(SO.img(2).vol); + end + + % threshold map and restrict coordinates + Q = find(compare_to_threshold(img2,range(1)) & le(img2,range(2))); + XYZ = XYZ(:, Q); + img2 = img2(Q); + + M = SO.img(2).vol.mat; + XYZmm = M(1:3, :) * [XYZ; ones(1, size(XYZ, 2))]; + + XYZ_unique = get_xyz_unique(XYZ, XYZmm, img2); + orientn = strcmpi(OV.transform, {'sagittal', 'coronal', 'axial'}); + slices{1} = XYZ_unique{orientn}; + end +end + +sl_name = []; +for i = 1:size(OV.transform, 1) + if n_slice > 0 + sl_name = strvcat(sl_name, [OV.transform(i, :) ': ' OV.slices_str(i, :)]); + else + sl_name = strvcat(sl_name, OV.transform(i, :)); + end +end + +str_select = deblank(sl_name(1, :)); +for i = 2:n_slice, str_select = [str_select '|' deblank(sl_name(i, :))]; end +if n_slice + ind = spm_input('Select slices', '+1', 'm', str_select); +else + ind = 1; +end +OV.transform = deblank(OV.transform(ind, :)); +slices = slices{ind}; + +SO.img(1).vol = spm_vol(OV.reference_image); +SO.img(1).prop = 1; +SO.img(1).cmap = gray; +SO.img(1).range = OV.reference_range; +SO.img(1).background = 0; + +SO.img(2).vol = spm_vol(img); +SO.img(2).hold = 0; % use NN interpolation +SO.img(2).prop = OV.opacity; % transparent overlay +SO.img(2).cmap = OV.cmap; % colormap + +if ~isfield(OV, 'func') + SO.img(2).func = 'i1(i1==0)=NaN;'; +else + SO.img(2).func = OV.func; +end + +if ~isfield(OV, 'range') + [mx, mn] = volmaxmin(OV.img(2).vol); + SO.img(2).range = spm_input('Intensity range for colormap', '+1', 'e', [mn mx], 2)'; +else + SO.img(2).range = range; +end + +if range(1) >= 0 + SO.img(2).outofrange = {0, size(SO.img(2).cmap, 1)}; +else + SO.img(2).outofrange = {1, 1}; + % use bivariate colormap if OV was not defined + if ~nargin, SO.img(2).cmap = cmap_bivariate; end +end + +SO.transform = OV.transform; +SO.slices = slices; + +if isempty(SO.slices) + if isfield(OV,'func') + [mx, mn, XYZ, vol] = volmaxmin(SO.img(2).vol,OV.func); + else + [mx, mn, XYZ, vol] = volmaxmin(SO.img(2).vol); + end + + % threshold map and restrict coordinates + Q = find(compare_to_threshold(vol,SO.img(2).range(1))); + XYZ = XYZ(:, Q); + vol = vol(Q); + + M = SO.img(2).vol.mat; + XYZmm = M(1:3, :) * [XYZ; ones(1, size(XYZ, 2))]; + orientn = strcmpi(SO.transform, {'sagittal', 'coronal', 'axial'}); + + XYZ_unique = get_xyz_unique(XYZ, XYZmm, vol); + SO.slices = XYZ_unique{orientn}; + + % update OV.slices_str for cat_surf_results to estimate available + % rows/columns + OV.slices_str = num2str(SO.slices); +end + +n_images = length(SO.slices) + length(SO.cbar); +xy = get_xy(n_images); + +n = size(xy, 1); +xy_name = num2str(xy); +str = deblank(xy_name(1, :)); +for i = 2:n, str = [str '|' deblank(xy_name(i, :))]; end + +% either interactively select columns/rows or use the defined values +if ~isfield(OV, 'xy') + indxy = spm_input('Select number of columns/rows', '+1', 'm', str); + xy = xy(indxy, :); +else + if ~isfinite(OV.xy(1)) + ind = find(xy(:,2) == OV.xy(2)); + if isempty(ind) + ind = n; + end + xy = xy(ind,:); + elseif ~isfinite(OV.xy(2)) + ind = find(xy(:,1) == OV.xy(1)); + if isempty(ind) + ind = 1; + end + xy = xy(ind,:); + else + xy = OV.xy; + end +end + +% get position of graphic figure +pos1 = spm('Winsize', 'Graphics'); + +screensize = get(0, 'screensize'); + +if ~isfield(SO,'overview') + % prepare overview of slices + V = SO.img(1).vol; + ref_vol = spm_read_vols(V); + ref_vol = 64 * (ref_vol - SO.img(1).range(1)) / (SO.img(1).range(2) - SO.img(1).range(1)); + vx = sqrt(sum(V.mat(1:3, 1:3).^2)); + Orig = round(V.mat \ [0 0 0 1]'); + + h0 = figure(11); clf + axes('Position', [0 0 1 1]); + + hold on + dim = SO.img(1).vol.dim(1:3); + switch lower(OV.transform) + case 'sagittal' + ref_img = ref_vol(:, :, Orig(3))'; + slices_vx = SO.slices / vx(1) + Orig(1); + image(fliplr(ref_img)) + for i = slices_vx + h = line([i i], [1 dim(2)]); + set(h, 'Color', 'r') + end + case 'coronal' + ref_img = squeeze(ref_vol(Orig(1), :, :))'; + slices_vx = SO.slices / vx(2) + Orig(2); + image(ref_img) + for i = slices_vx + h = line([i i], [1 dim(3)]); + set(h, 'Color', 'r') + end + case 'axial' + ref_img = squeeze(ref_vol(Orig(1), :, :))'; + slices_vx = SO.slices / vx(3) + Orig(3); + image(ref_img) + for i = slices_vx + h = line([1 dim(2)], [i i]); + set(h, 'Color', 'r') + end + end + + set(h0, 'Position', [10 10 2 * size(ref_img, 2), 2 * size(ref_img, 1)], ... + 'MenuBar', 'none', ... + 'Resize', 'off', ... + 'PaperType', 'A4', ... + 'PaperUnits', 'normalized', ... + 'NumberTitle', 'off', ... + 'Name', 'Slices', ... + 'PaperPositionMode', 'auto'); + + hold off + axis off xy image + colormap(gray) + +end + +SO.xslices = xy(:, 1); +switch lower(OV.transform) + case 'sagittal' + dim = xy .* SO.img(1).vol.dim(2:3); + case 'coronal' + dim = xy .* SO.img(1).vol.dim([1 3]); + case 'axial' + dim = xy .* SO.img(1).vol.dim(1:2); +end + +% use double size +dim = 2 * dim; + +scale = screensize(3:4) ./ dim; +% scale image only if its larger than screensize +if min(scale) < 1 + fig_size = min(scale) * dim * 0.975; +else + fig_size = dim; +end + +[pt, nm] = spm_fileparts(img); + +if isfield(OV,'pos') && ishandle(OV.fig) + pos0 = OV.pos(1:2); +else + pos0 = [10 1200]; +end + +if ishandle(OV.fig) + h = figure(OV.fig); + pos = get(h, 'Position'); + set(h, 'Position', [pos(1:2) fig_size]); +else + h = figure(OV.fig); + set(h, 'Position', [pos0 fig_size]); +end + +set(h, ... + 'MenuBar', 'none', ... + 'Resize', 'off', ... + 'PaperType', 'A4', ... + 'PaperUnits', 'normalized', ... + 'PaperPositionMode', 'auto', ... + 'NumberTitle', 'off', ... + 'Name', nm, ... + 'Visible', 'on'); + +SO.figure = h; +SO.area.units = 'pixels'; + +slice_overlay; + +% remove remaining gray colored border +ax = get(SO.figure,'Children'); +for i = 1:numel(ax) + set(ax(i),'YColor',SO.bkg_col,'XColor',SO.bkg_col); +end + +% change labels of colorbar for log-scale +H = gca; + +if ~isempty(SO.cbar) && SO.cbar == 2 && logP + + YTick = get(H, 'YTick'); + + % check whether lower threshold is P=0.05 and change values for YTick at + % threshold + if ~isempty(OV.clip) && abs(OV.clip(2)) >= 1.3 && abs(OV.clip(2)) <= 1.4 && OV.range(2) > OV.range(1) + YTick_step = ceil((OV.range(2) - OV.range(1)) / numel(YTick)); + if OV.clip(1) <= - 1.3 && OV.clip(1) >= - 1.4 && OV.range(1) < 0 + values = [round(OV.range(1)):YTick_step:round(OV.range(2))]; + mid = find(YTick==0); + if ~isempty(mid) + values(mid-1:mid+1) = [log10(0.05) 0 -log10(0.05)]; + else + values(values == -1) = log10(0.05); + values(values == 1) = -log10(0.05); + end + else + values = [0:YTick_step:round(OV.range(2))]; + values(2) = -log10(0.05); + end + + else + mn = floor(min(YTick)); + mx = ceil(max(YTick)); + + % only allow integer values + values = floor(mn:mx); + end + + + pos = get(get(gca, 'YLabel'), 'position'); + pos(1) = 2.5; + + set(H, 'YTick', values); + YTick = get(H, 'YTick'); + + YTickLabel = cell(length(YTick),1); + for i = 1:length(YTick) + if YTick(i) > 0 && YTick(i) >= OV.clip(2) + if YTick(i) > 7 + % use 1E-x notation + YTickLabel{i} = sprintf('%g', 10^(-YTick(i))); + else + % use 0.000x notation + YTickLabel{i} = remove_zeros(sprintf('%3.7f', 10^(-YTick(i)))); + end + elseif YTick(i) < 0 && YTick(i) <= OV.clip(1) + if YTick(i) < -7 + % use 1E-x notation + YTickLabel{i} = sprintf('-%g', 10^(YTick(i))); + else + % use 0.000x notation + YTickLabel{i} = remove_zeros(sprintf('-%3.7f', 10^(YTick(i)))); + end + else + YTickLabel{i} = ''; + end + end + + % update YTickLabel + set(H, 'YTickLabel', YTickLabel,'YAxisLocation','left') + set(get(gca, 'YLabel'), 'string', 'p-value', 'position', pos) + +end + +set(H, 'FontSize', FS, 'YColor', SO.bkg_col) +set(get(H, 'YLabel'), 'FontUnits', 'normalized', 'FontSize', 1.5*FS, 'Color', 1 - SO.bkg_col) + +% we have to get rid off that annoying axis and simply draw a box +% with 1 pixel width +posc = get(H,'Position'); +posc(3) = 1; +a=axes(... + 'Parent',SO.figure,... + 'XTick',[],... + 'XTickLabel',[],... + 'YTick',[],... + 'YTickLabel',[],... + 'Units', 'pixels',... + 'YColor',SO.bkg_col,... + 'Color',SO.bkg_col,... + 'Box', 'off',... + 'Position',posc); + +% select atlas for labeling +if isfield(OV, 'atlas') + atlas_name = OV.atlas; + if strcmpi(atlas_name,'none') || isempty(atlas_name) + xA = []; + else + xA = spm_atlas('load',atlas_name); + end +else + list = spm_atlas('List','installed'); + atlas_labels{1} = 'None'; + j = 1; + for i=1:numel(list) + if ~strcmp(list(i).name,'Neuromorphometrics') + atlas_labels{j+1} = list(i).name; + j = j + 1; + end + end + atlas = spm_input('Select atlas?', '1', 'm', atlas_labels); + atlas_name = atlas_labels{atlas}; + if atlas > 1 + xA = spm_atlas('load',atlas_name); + else + xA = []; + end +end + +[mx, mn, XYZ, vol] = volmaxmin(SO.img(2).vol,SO.img(2).func); + +% threshold map and restrict coordinates +if SO.img(2).range(1) >= 0 + Q = find(compare_to_threshold(vol,SO.img(2).range(1))); + XYZ = XYZ(:, Q); + vol = vol(Q); +end + +if isempty(XYZ) + fprintf(""No results for %s found.\n"", img); + return; +end + +% atlas labeling +if ~isempty(xA) & ~isempty(XYZ) + + % threshold values for printing table + if isfield(OV, 'min_extent') + min_extent = OV.min_extent; + else + min_extent = 1; + end + + if isfield(OV, 'min_overlap') + min_overlap = OV.min_overlap; + else + min_overlap = 1; + end + + M = SO.img(2).vol.mat; + XYZmm = M(1:3, :) * [XYZ; ones(1, size(XYZ, 2))]; + + i1 = vol; + + % remove NaN values + Q = find(isfinite(i1)); + XYZ = XYZ(:, Q); + i1 = i1(Q); + + % find clusters + A = spm_clusters(XYZ); + + labk = cell(max(A)+2,1); + Pl = cell(max(A)+2,1); + Zj = cell(max(A)+2,1); + maxZ = zeros(max(A)+2,1); + XYZmmj = cell(max(A)+2,1); + + for k = 1:min(max(A)) + j = find(A == k); + + [labk{k}, Pl{k}] = spm_atlas('query',xA,XYZmm(:,j)); + Zj{k} = i1(j); + XYZmmj{k} = XYZmm(:,j); + maxZ(k) = sign(Zj{k}(1))*max(abs(Zj{k})); + end + + % sort T/F values and print from max to min values + [tmp, maxsort] = sort(maxZ,'descend'); + + % use ascending order for neg. values + indneg = find(tmp<0); + maxsort(indneg) = flipud(maxsort(indneg)); + + if ~isempty(maxsort) + found_neg = 0; + found_pos = 0; + for l=1:length(maxsort) + j = maxsort(l); + [tmp, indZ] = max(abs(Zj{j})); + + if ~isempty(indZ) + if maxZ(j) < 0, found_neg = found_neg + 1; end + if maxZ(j) >= 0, found_pos = found_pos + 1; end + + if logP, valname = 'p-value'; else valname = 'Value'; end + + % print header if the first pos./neg. result was found + if found_pos == 1 + fprintf('\n______________________________________________________'); + fprintf('\n%s: Positive effects\n%s',SO.img(2).vol.fname,atlas_name); + fprintf('\n______________________________________________________\n\n'); + fprintf('%7s\t%12s\t%15s\t%s\n\n',valname,'Cluster-Size',' xyz [mm] ','Overlap of atlas region'); + end + if found_neg == 1 + fprintf('\n______________________________________________________'); + fprintf('\n%s: Negative effects\n%s',SO.img(2).vol.fname,atlas_name); + fprintf('\n______________________________________________________\n\n'); + fprintf('%7s\t%12s\t%15s\t%s\n\n',valname,'Cluster-Size',' xyz [mm] ','Overlap of atlas region'); + end + + if maxZ(j) < 0 + maxZ(j) = -maxZ(j); + end + + if logP val = 10^(-maxZ(j)); + else val = maxZ(j); end + + if length(Zj{j}) >= min_extent + fprintf('%7.2g\t%12d\t%4.0f %4.0f %4.0f',val,length(Zj{j}),XYZmmj{j}(:,indZ)); + for m=1:numel(labk{j}) + if Pl{j}(m) >= min_overlap + if m==1, fprintf('\t%3.0f%%\t%s\n',Pl{j}(m),labk{j}{m}); + else, fprintf('%7s\t%12s\t%15s\t%3.0f%%\t%s\n',' ',' ',' ',... + Pl{j}(m),labk{j}{m}); + end + end + end + end + end + end + end + fprintf('\n'); +end + +auto_savename = 0; +% save image +if ~isfield(OV, 'save') + image_ext = spm_input('Save image file?', '+1', 'none|png|jpg|pdf|tif', char('none', 'png', 'jpg', 'pdf', 'tiff'), 2); +else + if isempty(OV.save) + image_ext = spm_input('Save image file?', '+1', 'none|png|jpg|pdf|tif', char('none', 'png', 'jpg', 'pdf', 'tiff'), 2); + else + [pp, nn, ee] = spm_fileparts(OV.save); + if ~isempty(ee) + image_ext = ee(2:end); + else + % if only the extension is given then automatically estimate filename for saving + image_ext = OV.save; + auto_savename = 1; + end + end +end + +if ~strcmp(image_ext, 'none') + + [pt, nm] = spm_fileparts(img); + if isempty(pt) + pt1 = ''; + else + [tmp,nm2] = spm_fileparts(pt); + if isempty(nm2) + pt1 = [pt '_']; + else + pt1 = [nm2 '_']; + end + + [tmp,nm3] = spm_fileparts(spm_fileparts(pt)); + if isempty(nm3) + pt2 = [pt1 '_']; + else + pt2 = [nm3 '_']; + end + end + + if ~isfield(OV, 'save') + imaname = spm_input('Filename', '+1', 's', [pt1 nm '_' lower(OV.transform) '.' image_ext]); + else + if auto_savename + + % use up to 2 subfolders for getting filename + if isfield(OV,'name_subfolder') + % subfolder should be 0..2 + subfolder = max(min(OV.name_subfolder,3),0); + else + subfolder = 1; + end + + % use up to 2 subfolders for getting filename + switch subfolder + case 0, pt1 = ''; + case 2, try, pt1 = [pt2 pt1]; end + end + if numel(slices) == 1 + imaname = [pt1 nm '_' lower(OV.transform) num2str(slices) '.' image_ext]; + else + imaname = [pt1 nm '_' lower(OV.transform) '.' image_ext]; + end + else + imaname = OV.save; + end + end + + % jpg needs full name to be accepted + if strcmp(image_ext, 'jpg') + image_ext = 'jpeg'; + end + + % and print + H = findobj(get(SO.figure, 'Children'), 'flat', 'Type', 'axes'); + set(H, 'Units', 'normalized') + + saveas(SO.figure, imaname, image_ext); + + % read image, remove white border and save it again + tmp = imread(imaname); + sz = size(tmp); + wborderx = 1; + wbordery = sz(2); + % we search for a white border inside a width of 4 pixels using + % effect size. A line would be indicated by large mean and very low std + for k=1:4 + if mean(double(tmp(k,:,1)))./(eps+std(double(tmp(k,:,1)))) > 25 + wborderx = wborderx + 1; + end + if mean(double(tmp(:,sz(2)-k+1,1)))./(eps+std(double(tmp(:,sz(2)-k+1,1)))) > 25 + wbordery = wbordery - 1; + end + end + + % save the image without borders + imwrite(tmp(wborderx:sz(1),1:wbordery,:),imaname); + fprintf('Image %s saved.\n', imaname); + + if ~isfield(SO,'overview') + if n_slice > 0 + imaname = [lower(OV.transform) '_' replace_strings(OV.slices_str(ind, :)) '.' image_ext]; + else + imaname = [lower(OV.transform) '.' image_ext]; + end + + saveas(h0, imaname, image_ext); + fprintf('Image %s saved.\n', imaname); + end +end + +% check whether bounding box is from previous version that is not compatible +% with new template +BB = spm_get_bbox(SO.img(2).vol); +if sum(sum(BB-[-90 -126 -72;90 90 108])) == 0 + fprintf('WARNING: Check that %s is really compatible to new template in MNI152NLin2009cAsym template space. If not, you should use the old T1-template from CAT12.7 or older for overlay.\n',SO.img(2).vol.fname); +end + +if ~nargout + clear OV +end + +% -------------------------------------------------------------------------- +function xy = get_xy(n) + +nn = round(n^0.4); +if n > 8, x = nn:round(n / nn); else x = 1:n; end +xy = []; +for i = 1:length(x) + y = round(n / x(i)); + % check whether y is to small + while y * x(i) < n, y = y + 1; end + if i > 2 + if y * x(i - 1) < n, xy = [xy; [x(i) y]]; end + else xy = [xy; [x(i) y]]; end +end + +% change order of x and y +for i = 1:size(xy, 2) + yx = [xy(i, 2) xy(i, 1)]; + xy = [xy; yx]; +end + +% remove duplicates +xy = [[n 1];xy]; +xy = unique(xy, 'rows'); +return + +% -------------------------------------------------------------------------- +function s = replace_strings(s) + +s = deblank(s); +% replace spaces with ""_"" and characters like ""<"" or "">"" +s(strfind(s, ' ')) = '_'; +s(strfind(s, ':')) = '_'; +s = spm_str_manip(s, 'v'); + +return + +% -------------------------------------------------------------------------- +function [mx, mn, XYZ, img] = volmaxmin(vol,func) + +if nargout > 2 + XYZ = []; +end +if nargout > 3 + img = []; +end + +mx = -Inf; mn = Inf; +for i = 1:vol.dim(3) + i1 = spm_slice_vol(vol, spm_matrix([0 0 i]), vol.dim(1:2), [0 NaN]); + if nargin > 1, eval(func); end + tmp1 = i1(isfinite(i1(:)) & (i1(:) ~= 0)); + if ~isempty(tmp1) + if nargout > 2 + [Qc Qr] = find(isfinite(i1) & (i1 ~= 0)); + if size(Qc, 1) + XYZ = [XYZ; [Qc Qr i * ones(size(Qc))]]; + if nargout > 3 + img = [img; tmp1]; + end + end + end + mx = max([mx; tmp1]); + mn = min([mn; tmp1]); + end +end + +if nargout > 2 + XYZ = XYZ'; +end + +return + +% -------------------------------------------------------------------------- +function SO = pr_basic_ui(imgs, dispf) +% GUI to request parameters for slice_overlay routine +% FORMAT SO = pr_basic_ui(imgs, dispf) +% +% GUI requests choices while accepting many defaults +% +% imgs - string or cell array of image names to display +% (defaults to GUI select if no arguments passed) +% dispf - optional flag: if set, displays overlay (default = 1) +% +% $Id$ + +if nargin < 1 + imgs = ''; +end +if isempty(imgs) + imgs = spm_select(Inf, 'image', 'Image(s) to display'); +end +if ischar(imgs) + imgs = cellstr(imgs); +end +if nargin < 2 + dispf = 1; +end + +clear global SO +global SO %#ok this is print as error + +spm_clf('Interactive'); +spm_input('!SetNextPos', 1); + +% load images +nimgs = length(imgs); + +% process names +nchars = 20; +imgns = spm_str_manip(imgs, ['rck' num2str(nchars)]); + +SO.transform = deblank(spm_input('Image orientation', '+1', ['Axial|' ... + ' Coronal|Sagittal'], strvcat('axial', 'coronal', 'sagittal'), 1)); +orientn = find(strcmpi(SO.transform, {'sagittal', 'coronal', 'axial'})); + +% identify image types +SO.cbar = []; +XYZ_unique = cell(3, 1); +for i = 1:nimgs + SO.img(i).vol = spm_vol(imgs{i}); + if i == 1 + SO.img(i).cmap = gray; + %[mx, mn] = volmaxmin(SO.img(i).vol); + [tmp, th] = cat_stat_histth(spm_read_vols(SO.img(i).vol),0.95,0); + + SO.img(i).range = th; + else + [mx, mn, XYZ, img] = volmaxmin(SO.img(i).vol); + if ~isempty(strfind(SO.img(i).vol.fname, 'logP')) || ~isempty(strfind(SO.img(i).vol.fname, 'log_')) + logP = 1; + else + logP = 0; + end + + SO.img(i).func = 'i1(i1==0)=NaN;'; + SO.img(i).prop = Inf; + SO.cbar = [SO.cbar i]; + SO.img(i).cmap = return_cmap('Colormap:', 'jet'); + if logP + % only ask for threshold if images is probably not thresholded + if mn < -log10(0.05) + thresh = spm_input('Threshold P','+1','b','0.05|0.01|0.001',[0.05 0.01 0.001],1); + mn = -log10(thresh); + % use slightly larger maximum value to ensure that YTickLabel fits + if thresh == 0.05 + mx = floor(mx) + 0.3011; + end + end + end + + SO.img(i).range = spm_input('Image range for colormap', '+1', 'e', [mn mx], 2)'; + define_slices = spm_input('Slices', '+1', 'm', 'Estimate slices with local maxima|Define slices', [0 1], 1); + + if ~define_slices + + % for log-scaled p-values we should rather use gt than ge for comparison with threshold + if logP + compare_to_threshold = @(a,b) gt(a,b); + else + compare_to_threshold = @(a,b) ge(a,b); + end + + % threshold map and restrict coordinates + Q = find(compare_to_threshold(img,SO.img(i).range(1)) & le(img,SO.img(i).range(2))); + XYZ = XYZ(:, Q); + img = img(Q); + + M = SO.img(i).vol.mat; + XYZmm = M(1:3, :) * [XYZ; ones(1, size(XYZ, 2))]; + + XYZ_unique = get_xyz_unique(XYZ, XYZmm, img); + end + + end +end + +% slices for display +ts = [0 0 0 pi / 2 0 -pi / 2 -1 1 1; ... + 0 0 0 pi / 2 0 0 1 -1 1; ... + 0 0 0 0 0 0 1 1 1]; + +V = SO.img(2).vol; +D = V.dim(1:3); +T = spm_matrix(ts(orientn, :)) * V.mat; +vcorners = [1 1 1; D(1) 1 1; 1 D(2) 1; D(1:2) 1; ... + 1 1 D(3); D(1) 1 D(3); 1 D(2:3); D(1:3)]'; +corners = T * [vcorners; ones(1, 8)]; + +SO.slices = spm_input('Slices to display (mm)', '+1', 'e', XYZ_unique{orientn}); +SO.figure = figure(22); + +% and do the display +if dispf, slice_overlay; end + +return + +% -------------------------------------------------------------------------- +function cmap = return_cmap(prompt, defmapn) +cmap = []; +while isempty(cmap) + cmap = slice_overlay('getcmap', spm_input(prompt, '+1', 's', defmapn)); +end +return + +% -------------------------------------------------------------------------- +function XYZ_unique = get_xyz_unique(XYZ, XYZmm, img) + +xyz_array = []; + +% cluster map +A = spm_clusters(XYZ); +for j = 1:max(A) + ind = find(A == j); + xyz = XYZmm(:, ind); + xyz_array = [xyz_array xyz(:, img(ind) == max(img(ind)))]; +end + +% only keep unique coordinates +XYZ_unique = cell(3, 1); +for j = 1:3 + XYZ_unique{j} = unique(xyz_array(j, :)); +end + +return + +%========================================================================== +function s = remove_zeros(s) + +s = deblank(s); +pos = length(s); +while pos > 1 + if strcmp(s(pos), '0') + s(pos) = ''; + pos = pos - 1; + else break + end +end + +return","MATLAB" +"Neurology","ChristianGaser/cat12","cat_vol_sanlm2180.m",".m","27621","588","function out = cat_vol_sanlm(varargin) +% Spatial Adaptive Non Local Means (SANLM) Denoising Filter +%_______________________________________________________________________ +% Filter a set of images and add the prefix 'sanlm_'. +% Missing input (data) will call GUI or/and use defaults. +% +% Examples: +% cat_vol_sanlm(struct('data','','prefix','n','rician',0)); +% cat_vol_sanlm(struct('data','','NCstr',[-1:0.5:1,inf,-inf)); +% +% Input: +% job - harvested job data structure (see matlabbatch help) +% +% Output: +% out - computation results, usually a struct variable. +% +% cat_vol_sanlm(job) +% +% job +% .data .. set of images +% .prefix .. prefix for filtered images (default = 'sanlm_') +% .suffix .. suffix for filtered images (default = '') +% 'NCstr' will add the used parameter +% .verb .. verbose processing (default = 1) +% .spm_type .. file datatype (default single = 16); +% .replaceNANandINF .. replace NAN by 0, -INF by minimum and INF by maximum +% .rician .. noise distribution +% .intlim .. intensity limitation (default = 0.9999) +% .addnoise .. add noise to noiseless regions +% Add minimal amount of noise in regions without any noise to avoid +% problems of image segmentation routines. The value defines the +% strength of the noise by the percentage of the mean signal intensity. +% .NCstr .. strength of noise correction (default = -inf) +% A value of 1 used the full correction by the SANLM filter. Values +% between 0 and 1 mix the original and the filtered images, whereas +% INF estimated a global value depending on the changes of the SANLM +% filter that reduce to strong filtering in high quality data. +% Negative values work on a local rather than a global level. +% A value of -INF is recommend, but you define a set of values (see +% example) for further changes depending on your data. +% +% 0 .. no denoising +% 1 .. full denoising (original sanlm) +% 2 .. ""light"": NCstr=-0.5, red=0, fred=0; iterm=0 +% 3 | -inf .. ""medium"": NCstr=-1.0, red=1, fred=0; iterm=0 +% 4 .. ""strong"": NCstr= 1.0, red=1, fred=1; iterm=1 +% 0 < job.NCstr < 1 .. automatic global correction with user weighting +% -9 < job.NCstr < 0 .. automatic local correction with user weighting +% inf .. global automatic correction +% -inf .. local automatic correction +% +% .returnOnlyFilename .. just to get the resulting filenames for SPM +% batch mode (default = 0) +% .resolutionDependency .. resolution depending filter strength +% Use the .resolutionDependencyRange Parameter (default = 1) +% .resolutionDependencyRange .. [full-correction no-correction] +% Limit the filter size depending on the general brain size, where +% filtering of images with 2.5 mm voxel size and higher will remove +% important anatomical information (default = [1 2.5]). +% .red .. low resolution filtering (if high-res data) +% .fred .. force resolution reduction +% .iter .. additional iterations on the reduced resolution +% (default = 0) +% .iterm .. additional main iterations of the full filter +% (default = 0) +% +% Some MR images were interpolated or use a limited frequency spectrum to +% support higher spatial resolution with acceptable scan-times +% (eg. 0.5x0.5x1.5 mm on a 1.5 Tesla scanner). However, this can result in +% ""low-frequency"" noise that can not be handled by the standard NLM filter. +% Hence, an additional filtering step is used on a reduces resolution that +% uses an internal call of this routine with direct image in- an output. +% +% src = cat_vol_sanlm(job,V,i,src) +% +% As far as filtering of low resolution data will also remove anatomical +% information the filter uses by default maximal one reduction with a +% resolution limit of 1.6 mm. I.e. a 0.5x0.5x1.5 mm image is reduced +% to 1.0x1.0x1.5 mm, whereas a 0.8x0.8x0.4 mm images is reduced to +% 0.8x0.8x0.8 mm and a 1x1x1 mm dataset is not reduced at all. +% +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + % this function adds noise to the data to stabilize processing and we + % have to define a specific random pattern to get the same results each time + if exist('rng','file') == 2, rng('default'); rng(0); else, rand('state',0); randn('state',0); end + + if nargin == 0 + varargin{1}.data = cellstr(spm_select([1 Inf],'image','select images to filter')); + if isempty(char(varargin{1}.data)); return; end + end + + % default optoins + def.verb = 2; % be verbose + def.prefix = 'sanlm_'; % prefix + def.suffix = ''; % suffix + def.replaceNANandINF = 1; % replace NAN and INF + def.spm_type = 16; % file datatype (default single) + def.NCstr = -Inf; % 0 - no denoising, eps - light denoising, + % 1 - maximum denoising, inf = auto; + def.rician = 0; % use inf for GUI + def.intlim = [0.9999 0.9999]; % general intensity limitation to remove strong outlier + def.resolutionDependency = 1; % resolution depending filter strength + def.resolutionDependencyRange = [1 2.5]; % [full-correction no-correction] + def.relativeIntensityAdaption = 1; % use intensity to limit relative corrections (0 - none, 1 - full) + def.relativeIntensityAdaptionTH = 1; % larger values for continuous filter strength + def.relativeFilterStengthLimit = 1; % limit the noise correction by the relative changes + % to avoid over-filtering in low intensity regions + def.outlier = 1; % threshold to define outlier voxel to filter them with full strength + def.addnoise = 1; % option to add a minimal amount of noise in regions without noise + def.returnOnlyFilename = 0; % just to get the resulting filenames for SPM batch mode + def.red = 1; % number of reductions (be careful using values greater 1!) + def.fred = 0; % force reduce + def.iter = 0; % additional inner iterations on the reduced resolution + def.iterm = 0; % additional main iterations of the full filter + def.lazy = 1; % avoid reprocessing if file exist + job = varargin; + if isfield(job{1},'nlmfilter') + subfield = fieldnames(job{1}.nlmfilter); + FN = fieldnames(job{1}.nlmfilter.(subfield{1})); + for fni = 1:numel(FN) + job{1}.(FN{fni}) = job{1}.nlmfilter.(subfield{1}).(FN{fni}); + end + end + job{1} = cat_io_checkinopt(job{1},def); + + % special cases of the CAT GUI + if isfield(varargin{1},'nlmfilter') + if isfield(varargin{1}.nlmfilter,'optimized') + varargin{1} = cat_io_checkinopt(varargin{1}.nlmfilter.optimized,varargin{1}); + elseif isfield(varargin{1}.nlmfilter,'expert') + varargin{1} = cat_io_checkinopt(varargin{1}.nlmfilter.expert,varargin{1}); + end + end + if nargin > 0 && isstruct(varargin{1}) && isfield(varargin{1},'NCstr') + switch varargin{1}.NCstr + case 2, varargin{1}.NCstr = -0.5; varargin{1}.red = 0; varargin{1}.fred = 0; varargin{1}.iterm = 0; % light + case {3,-inf}, varargin{1}.NCstr = -1.0; varargin{1}.red = 1; varargin{1}.fred = 0; varargin{1}.iterm = 0; % medium + case 4, varargin{1}.NCstr = 1.0; varargin{1}.red = 1; varargin{1}.fred = 1; varargin{1}.iterm = 1; varargin{1}.iter = 1;% strong + end + end + + if nargin <= 1 && isstruct(varargin{1}) % job structure input + out.files = cat_vol_sanlm_file(job{1}); + else % image input + out = cat_vol_sanlm_filter(job{:}); + end + +end + +%_______________________________________________________________________ +function varargout = cat_vol_sanlm_file(job) + + if ~isfield(job,'data') || isempty(job.data) + job.data = cellstr(spm_select([1 Inf],'image','select images to filter')); + else + job.data = cellstr(job.data); + end + if isempty(char(job.data)); if nargout>0, varargout{1} = {{''}}; end; return; end + + + % map GUI data + if isfield(job,'nlmfilter') + if isfield(job.nlmfilter,'classic') + job.NCstr = 1; + elseif isfield(job.nlmfilter,'optimized') + FN = fieldnames(job.nlmfilter.optimized); + for fni=1:numel(FN) + if isfield(job.nlmfilter.optimized,FN{fni}) + job.(FN{fni}) = job.nlmfilter.optimized.(FN{fni}); + end + end + job.NCstr = -abs(job.nlmfilter.optimized.NCstr); + end + end + + % parameter limitations + if ~isinf(job.NCstr), job.NCstr = max(-9.99,min(1,job.NCstr)); end % guarantee values from -9.99 to 1 or inf + job.resolutionDependency = max(0,min(9.99,job.resolutionDependency)); + job.relativeIntensityAdaption = max(0,min(9.99,job.relativeIntensityAdaption)); + job.relativeIntensityAdaptionTH = max(0,min(9.99,job.relativeIntensityAdaptionTH)); + job.relativeFilterStengthLimit = max(0,min(9.99,job.relativeFilterStengthLimit)); + job.outlier = max(0,min(9.99,job.outlier)); + job.addnoise = max(0,min(9.99,job.addnoise)); + + % create automatic filenames by the parameter + if ~isempty(strfind(job.prefix,'PARA')) + nprefix = strrep(job.prefix,'PARA',''); + if numel(nprefix)>0 && ~(strcmp(nprefix(end),'_') || strcmp(nprefix(end),'-')), nprefix = [nprefix '_']; end + if job.NCstr>=0 + job.prefix = sprintf('%sNC%0.2f_',nprefix,job.NCstr); + elseif isinf(job.NCstr) && sign(job.NCstr)==-1 + job.prefix = sprintf('%sNC%0.2f_',nprefix,3); + else + job.prefix = sprintf('%sNC%-0.2f_RN%d_RD%d_RIA%0.2f_RR%d_FR%d_RNI%d_OL%0.2f_PN%0.1f_iterm%d_iter%d',... + nprefix, job.NCstr , job.rician , job.resolutionDependency , job.red , job.fred , job.relativeIntensityAdaption , ... + job.replaceNANandINF , job.outlier , job.addnoise , job.iterm , job.iter); + end + elseif ~isempty(strfind(job.suffix,'PARA')) + if numel(job.NCstr)==1 && job.NCstr>=0 + job.suffix = sprintf('_NC%0.2f',job.NCstr); + elseif isinf(job.NCstr) && sign(job.NCstr)==-1 + job.prefix = sprintf('_NC%0.2f',3); + else + job.suffix = sprintf('_NC%-0.2f_RN%d_RD%d_RIA%0.2f_RR%d_FR%d_RNI%d_OL%0.2f_PN%0.1f_iterm%d_iter%d',... + job.NCstr , job.rician , job.resolutionDependency , job.red , job.fred , job.relativeIntensityAdaption , ... + job.replaceNANandINF , job.outlier , job.addnoise , job.iterm , job.iter); + end + end + % just to get the resulting filenames for SPM batch mode + for i = 1:numel(job.data) + [pth,nm,xt,vr] = spm_fileparts(deblank(job.data{i})); + varargout{1}{i} = fullfile(pth,[job.prefix nm job.suffix xt vr]); + end + if job.returnOnlyFilename + return + end + + V = spm_vol(char(job.data)); + + % new banner + if isfield(job,'process_index') && job.verb + spm('FnBanner',mfilename); + end + spm_progress_bar('Init',numel(job.data),'SANLM-Filtering','Volumes Complete'); + + for i = 1:numel(job.data) + if ~job.lazy || cat_io_rerun( job.data{1} , varargout{1}{i} ) + cat_vol_sanlm_filter(job,V,i); + end + spm_progress_bar('Set',i); + end + + if isfield(job,'process_index') && job.verb + fprintf('Done\n'); + end + spm_progress_bar('Clear'); +end + +%_______________________________________________________________________ +function src2 = cat_vol_sanlm_filter(job,V,i,src) + Vo = V; + + QMC = cat_io_colormaps('marks+',17); + color = @(m) QMC(max(1,min(size(QMC,1),round(((m-1)*3)+1))),:); + + % if there is a breakpoint in this file set debug=1 and do not clear temporary variables + dbs = dbstatus; debug = 0; for dbsi=1:numel(dbs), if strcmp(dbs(dbsi).name,mfilename); debug = 1; break; end; end + + + [pth,nm,xt,vr] = spm_fileparts(deblank(V(i).fname)); %#ok + + stime = clock; stimef = clock; + vx_vol = sqrt(sum(V(i).mat(1:3,1:3).^2)); + + if nargin<4 + src = single(spm_read_vols(V(i))); + else + src = single(src); + end + + for im=1:1+job.iterm + % prevent NaN and INF + if job.replaceNANandINF + src(isnan(src)) = 0; + src(isinf(src) & src<0) = min(src(:)); + src(isinf(src) & src>0) = max(src(:)); + else + if sum(isnan(src(:))>0), nanmsk = isnan(src); end + if sum(isinf(src(:))>0), infmsk = int8( isinf(src) .* sign(src) ); end + end + + % histogram limit + [src,srcth] = cat_stat_histth(src,job.intlim); + + % use intensity normalisation because cat_sanlm did not filter values below ~0.01 + th = max( cat_stat_nanmean( src(src(:)>cat_stat_nanmean(src(src(:)>0))) ) , ... + abs(cat_stat_nanmean( src(src(:)0 && (any(vx_vol<0.8) || job.fred ) + [srcr,resr] = cat_vol_resize( src ,'reduceV',vx_vol,min(2.2*(job.fred+1),min(vx_vol)*2.3),32,'median'); + + jobr = job; + jobr.red = job.red - 1; + jobr.iterm = 0; + jobr.addnoise = 0; % no additional noise on lower resolution + jobr.resolutionDependency = 1; % resolution depending filter strength + jobr.resolutionDependencyRange = [1 1.6]; % [full-correction no-correction] + jobr.outlier = jobr.outlier*2; + jobr.NCstr = -prod(3-resr.vx_red)*2 .* ... + min(1,1 - (mean(resr.vx_volr) - jobr.resolutionDependencyRange(1) )) / ... + diff(jobr.resolutionDependencyRange); + + if 1 + % larger var => more information + Ygr = cat_vol_grad(srcr/th,resr.vx_volr,0); + grsd = std(Ygr(Ygr(:)>0)); + grrel = numel(Ygr(Ygr(:)>grsd))/numel(Ygr(Ygr(:)>0)); + jobr.NCstr = jobr.NCstr * grrel*10; + end + + srco = src; + if any(resr.vx_red>1) && any( resr.vx_volr < jobr.resolutionDependencyRange(2)*(job.fred+1) ) && jobr.NCstr~=0 + % first block + Vr = V(i); Vmat = spm_imatrix(Vr.mat); Vmat(7:9) = Vmat(7:9).*resr.vx_red; Vr.mat = spm_matrix(Vmat); + srcR = cat_vol_resize(srcr,'dereduceV',resr,'cubic'); + for iter=1:1+job.iter + srcr = cat_vol_sanlm_filter(jobr,Vr,1,srcr); + end + srcRS = cat_vol_resize(srcr,'dereduceV',resr,'cubic'); + src = (src - srcR) + srcRS; + clear srcRS srcr srcR; + + % second block + if 1 % the second displaced filtering helps to deduce low frequency noise a little bit more + [srcr,resr] = cat_vol_resize( smooth3(src(2:end,2:end,2:end)) ,'reduceV',... + vx_vol,min(2.2*(job.fred+1),min(vx_vol)*2.3),32,'median'); + srcRr = cat_vol_resize(srcr,'dereduceV',resr,'cubic'); + srcR = src; srcR(2:end,2:end,2:end) = srcRr; + for iter=1:1+job.iter + srcr = cat_vol_sanlm_filter(jobr,Vr,1,srcr); + end + srcRr = cat_vol_resize(srcr,'dereduceV',resr,'cubic'); + srcRS = src; srcRS(2:end,2:end,2:end) = srcRr; + src = src + (src - srcR) + srcRS; + clear srcRS srcr srcR; + src = src / 2; + end + end + + NCstrr = 15 * abs(cat_stat_nanmean(abs(src(:)/th - srco(:)/th))); + else + NCstrr = 0; + end + if job.verb>1 && (nargin>3 || NCstrr>0) + cat_io_cprintf('g5',sprintf('R%1d) %0.2fx%0.2fx%0.2f mm: ',job.red,vx_vol)); stime = clock; + end + + + % the real noise filter + if im==1, srco = src; end + src = (src / th) * 100; + src = (src - srcth(1)); % avoid negative values! + cat_sanlm(src,3,1,job.rician); + src = src + srcth(1); % reset negative values + src = (src / 100) * th; + if job.verb>1 && (nargin>3 || NCstrr>0) && im<1+job.iterm + if job.verb>1 && (nargin>3 || NCstrr>0), cat_io_cprintf('g5',sprintf(' %5.0fs\n',etime(clock,stime))); end + end + end + + % measures changes + NCrate = cat_stat_nanmean(abs(src(:)/th - srco(:)/th)); + + % set actual filter rate - limit later! + % the factor 15 was estimated on the BWP + NCstr = job.NCstr; + NCstr(isinf(NCstr) & NCstr>0) = 15 * NCrate; + NCstr(isinf(NCstr) & NCstr<0) = -1; + + + for NCstri = 1:numel(NCstr) + + if NCstr(NCstri)<0 + % adaptive local denoising + + %% prepare local map + % use less filtering for low-res data to avoid anatomical blurring ??? + NCs = max(eps,abs(src - srco)/th); + + % preserve anatomical details by describing the average changes + % and not the strongest - this reduce the ability of artifact + % correction! + stdNC = std(NCs(NCs(:)~=0)); + NCsm = cat_vol_median3(NCs,NCs>stdNC,true(size(NCs))); % replace outlier + [NCsr,resT2] = cat_vol_resize(NCsm,'reduceV',vx_vol,2,32,'meanm'); clear NCsm; + NCsr = cat_vol_localstat(NCsr,true(size(NCs)),1,1); + NCsr = cat_vol_smooth3X(NCsr,1/mean(resT2.vx_volr)); + NCsr = cat_vol_resize(NCsr,'dereduceV',resT2); + NCso = NCs; + + % no correction of local abnormal high values (anatomy) + NCs = NCsr + (NCso>stdNC & NCso<=stdNC*4 & NCso>NCsr*2 & NCso more similar filtering + NCi = max(eps,log10( 1 + (NCi + range(1)) / diff(range) * 7 + 3 )); % bias corr + intensity normalization + NCi = cat_vol_smooth3X( NCi , job.relativeIntensityAdaption / mean(vx_vol)); % smoothing + if job.relativeIntensityAdaption>0 && ... + job.relativeFilterStengthLimit && ~isinf(job.relativeFilterStengthLimit) + NCsi = NCs ./ max(eps,NCi); + mNCs = cat_stat_nanmean( NCsi(src(:)>th/2 & NCsi(:)>0 )) * ... + job.relativeFilterStengthLimit * ... + max(1,min(4,4 - job.relativeIntensityAdaption*2)); % lower boundary for strong adaptation + NCsi = min( NCsi , mNCs ) .* NCi; + + % Finally, both images were mixed + NCs = NCs * (1 - job.relativeIntensityAdaption) + ... % linear average model to contoll filter strength + NCsi * job.relativeIntensityAdaption; + if ~debug, clear NCsi; end + end + + + + % heavy outlier / artifacts + if job.outlier>0 + NCi = min(1,max(0,NCi .* (NCso - ( (stdNC*2) / job.outlier ) ) ./ ((stdNC*2) / job.outlier ))); + NCs = max(NCs, NCi); + if ~debug, clear NCi; end + if ~debug, clear NCso; end + end + + + + if debug, src2 = srco.*(1-NCs) + src.*NCs; end + % ds('d2','',vx_vol,src/th,srco/th,srco2/th, NCs,160) + + + + % mix original and noise corrected image + src2 = srco.*(1-NCs) + src.*NCs; + NCstr(NCstri) = -cat_stat_nanmean(NCs(:)); + if ~debug, clear NCs; end + + elseif NCstr(NCstri)==1 + % no adaptation (original filter) + src2 = src; + + elseif NCstr(NCstri)>0 + % simple global denoising + + NCstr(NCstri) = min(1,max(0,NCstr(NCstri))); + + % mix original and noise corrected image + src2 = srco*(1-NCstr(NCstri)) + src*NCstr(NCstri); + + else + % no denoising ... nothing to do + src2 = src; + + end + + + + %% add noise + if job.addnoise + % Small adaptation for inhomogeneity to avoid too much noise in + % regions with low signal intensity. + sth = cat_vol_smooth3X(log10(2 + 8*src/th),4/mean(vx_vol)) * th; + + % Correction only of regions with less noise and with (src~=0) to + % avoid adding of noise in skull-stripped data. This may lead to + % problems with the skull-stripping detection in cat_run_job! + % Also important in case of ADNI. + src2 = src2 + max( 0 , min(1 , cat_vol_smooth3X( ... + ( job.addnoise.*sth/100 ) - abs(srco - src) , 4/mean(vx_vol) ) ./ ( job.addnoise.*sth/100 ) )) .* ... + ( src~=0 ) .* ... save skull-stripping / defacing regions + (randn(size(src)) * job.addnoise.*sth/100); + if ~debug, clear sth; end + end + if numel(NCstr)==1 && ~debug, clear src srco; end + + + + %% restore NAN and INF + if exist('nanmsk','var'), src2(nanmsk) = nan; end + if exist('infmsk','var'), src2(infmsk==-1) = -inf; src2(infmsk==1) = inf; end + if job.verb>1 && (nargin>3 || NCstrr>0), cat_io_cprintf('g5',sprintf(' %5.0fs\n',etime(clock,stime))); end + + if nargin==4 + return; + end + + % use only float precision + Vo(i).fname = fullfile(pth,[job.prefix nm job.suffix '.nii' vr]); + Vo(i).descrip = sprintf('%s SANLM filtered (NCstr=%-4.2f > %0.2f)',... + V(i).descrip,job.NCstr(NCstri),abs(NCstr(NCstri)) + NCstrr); + Vo(i).dt(1) = 16; % default - changes later if required + if exist(Vo(i).fname,'file'); delete(Vo(i).fname); end + spm_write_vol(Vo(i), src2); + + + + %% if single should be not used, the image has to be converted ... + if job.spm_type~=16 + ctype.data = Vo(i).fname; + + if job.spm_type + ctype.ctype = job.spm_type; + else + ctype.ctype = V(i).dt(1); + end + ctype.range = 99.99; + ctype.prefix = ''; + cat_io_volctype(ctype); + end + + + + %% display result and link images for comparison + if job.verb + % I am not sure if this is intuitive. Maybe someone will think + % that red means failed filtering ... + % green > low filtering + % red > strong filtering + % create some further parameter output for experts + FNs = {'filtername'}; + FNf = {'NCstr'}; + if cat_get_defaults('extopts.expertgui') + FNi = {'rician','intlim','outlier','addnoise','red','fred','iter','iterm'}; + else + FNi = {}; + end + parastr = ['''name = ' job.prefix '*' job.suffix ''';' ]; + %for fni = 1:numel(FNs) + % parastr = [parastr sprintf('''%s = %s''; ', FNs{fni}, job.(FNs{fni}))]; %#ok + %end + for fni = 1:numel(FNf) + parastr = [parastr sprintf('''%s = %0.2f''; ', FNf{fni}, job.(FNf{fni}))]; %#ok + end + for fni = 1:numel(FNi) + parastr = [parastr sprintf('''%s = %d''; ', FNi{fni}, job.(FNi{fni}))]; %#ok + end + + %% spm_orthview preview + % This is a long string but it loads the original and the filtered + % image for comparison (with parameter settings) + fprintf('%5.0fs, Output %s\n',etime(clock,stimef),... + spm_file(Vo(i).fname,'link',sprintf(... + ['spm_figure(''Clear'',spm_figure(''GetWin'',''Graphics'')); ' ... + 'spm_orthviews(''Reset''); ' ... remove old settings + 'ax = axes; set(ax,''Position'',[0 0 1 1]); axis off; hd = text(ax,0.01,0.99,''File: ' job.data{i} '''); ' ... + 'ho = spm_orthviews(''Image'',''%s'' ,[0 0.51 1 0.49]); ',... top image + 'hf = spm_orthviews(''Image'',''%%s'',[0 0.01 1 0.49]);', ... bottom image + 'spm_orthviews(''Caption'', ho, ''original''); ', ... caption top image + 'spm_orthviews(''Caption'', hf, {{''filtered'';'' '';' , ... caption bottom image + parastr '}}); ', ... % the parameters + 'spm_orthviews(''AddContext'',ho); spm_orthviews(''AddContext'',hf); ', ... % add menu + 'spm_orthviews(''Zoom'',40);', ... % zoom in + ],V(i).fname))); + end + + + end +end + +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_vol_median3.c",".c","8770","218","/* Median Filter + * _____________________________________________________________________________ + * Median Filter for a 3d single image D. Bi is used to mask voxels for the + * filter process, whereas Bn is used to mask voxels that are used as + * neighbors in the filter process. Both mask can changed by intensity + * threshold (Bi_low,Bi_high,Bn_low,Bn_high) for D. Local NAN and INF + * values can be replaced, if a neighbor has a non NAN/INF value and is + * within the defined maskes and boundaries. + * + * M = cat_vol_median3(D[, Bi, Bn, sf, Bi_low, Bi_high, Bn_low, Bn_high, + * filterNaNandINF]) + * + * D (single) .. 3d matrix for filter process + * Bi (logical) .. 3d matrix that marks voxels that should be filtered + * Bn (logical) .. 3d matrix that marks voxels that are used to filter + * sf (double) .. threshold that is used to filter the result + * sf=0: no filter + * sf<0: only smaller changes + * sf>0: only bigger changes + * Bi_low (double) .. low threshold in D for filtering (add to Bi) + * Bi_high (double) .. high threshold in D for filtering (add to Bi) + * Bn_low (double) .. low threshold in D for neighbors (add to Bn) + * Bn_high (double) .. high threshold in D for neighbors (add to Bn) + * filterNaNandINF (double ) .. replace NaN or Inf by the median of non + * NaN/INF voxels (default=0) + * + * Used slower quicksort for median calculation, because the faster median + * of the median estimation leaded to incorrect results. + * + * Example: + * A is the image that should be filter and that may contain NaN and Inf + * values, whereas B defines the regions that should be filtered and spend + * values. + % + * A = randn(50,50,3,'single'); + * B = false(size(A)); B(5:end-4,5:end-4,:)=true; + * N = rand(size(A),'single'); + * A(N>0.9 & N<1.0) = NaN; A(N<0.1 & N>0) = -inf; A(N<0.05 & N>0) = inf; + * + * 1) simple cases without limits + * C = cat_vol_median3(A,B); ds('d2smns','',1,A+B,C,2); + * + * 2) simple case without limits bud with NaN that are replaced by default + * C = cat_vol_median3(A,B,B,0,-inf,inf,-inf,inf,1); ds('d2smns','',1,A+B,C,2); + * + * 3) Replace only small changes in C1, eg. to filter within tissue classes. + * Replace only large outlier in C2, eg. to remove outlier like salt & + * pepper noise. In both cases NANs/INFs were replaced. + * C1 = cat_vol_median3(A,B,B, -1.0 ,-inf,inf,-inf,inf,1 ); + * C2 = cat_vol_median3(A,B,B, 1.0 ,-inf,inf,-inf,inf,1 ); + * ds('d2smns','',1,C1,C2,2); + * + * See also cat_vol_median3c, compile. + * + * TODO: check all input elements... + * ______________________________________________________________________ + * + * Christian Gaser, Robert Dahnke + * Structural Brain Mapping Group (https://neuro-jena.github.io) + * Departments of Neurology and Psychiatry + * Jena University Hospital + * ______________________________________________________________________ + * $Id$ + */ + +#include ""mex.h"" +#include ""math.h"" +#include ""float.h"" + +#ifdef _MSC_VER + #define FINFINITY (FLT_MAX+FLT_MAX); + static const unsigned long __nan[2] = {0xffffffff, 0x7fffffff}; + #define FNAN (*(const float *) __nan) +#else + #define FINFINITY 1.0f/0.0f; + #define FNAN 0.0f/0.0f +#endif + +#define index(A,B,C,DIM) ((C)*DIM[0]*DIM[1] + (B)*DIM[0] + (A)) + +/* qicksort */ +void swap(float *a, float *b) +{ + float t=*a; *a=*b; *b=t; +} + +void sort(float arr[], int beg, int end) +{ + if (end > beg + 1) + { + float piv = arr[beg]; + int l = beg + 1, r = end; + while (l < r) + { + if (arr[l] <= piv) + l++; + else + swap(&arr[l], &arr[--r]); + } + swap(&arr[--l], &arr[beg]); + sort(arr, beg, l); + sort(arr, r, end); + } +} + +/* main function */ +void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) +{ + if (nrhs<1) mexErrMsgTxt(""ERROR:cat_vol_median3: not enough input elements\n""); + if (nrhs>9) mexErrMsgTxt(""ERROR:cat_vol_median3: too many input elements\n""); + if (nlhs<1) mexErrMsgTxt(""ERROR:cat_vol_median3: not enough output elements\n""); + if (nlhs>1) mexErrMsgTxt(""ERROR:cat_vol_median3: too many output elements\n""); + + /* main information about input data (size, dimensions, ...) */ + const mwSize *sL = mxGetDimensions(prhs[0]); + const int dL = mxGetNumberOfDimensions(prhs[0]); + const int nL = (int) mxGetNumberOfElements(prhs[0]); + + if ( dL != 3 || mxIsSingle(prhs[0])==false) mexErrMsgTxt(""ERROR:cat_vol_median3: first input must be a single 3d matrix\n""); + if ( nrhs>1) { + const int nBi = (int) mxGetNumberOfElements(prhs[1]); + + if ( mxGetNumberOfDimensions(prhs[1]) != 3 ) mexErrMsgTxt(""ERROR:cat_vol_median3: second input must be 3d - to use a later parameter use ''true(size( input1 ))''\n""); + if ( mxIsLogical(prhs[1])==false) mexErrMsgTxt(""ERROR:cat_vol_median3: second input must be a logical 3d matrix\n""); + if ( nL != nBi) mexErrMsgTxt(""ERROR:cat_vol_median3: second input must be a logical 3d matrix with equal size than input 1\n""); + } + if ( nrhs>2) { + const int nBn = (int) mxGetNumberOfElements(prhs[2]); + + if ( mxGetNumberOfDimensions(prhs[2]) != 3 ) mexErrMsgTxt(""ERROR:cat_vol_median3: third input must be 3d - to use a later parameter use ''true(size( input1 ))'\n""); + if ( mxIsLogical(prhs[2])==false) mexErrMsgTxt(""ERROR:cat_vol_median3: third input must be a logical 3d matrix\n""); + if ( nL != nBn) mexErrMsgTxt(""ERROR:cat_vol_median3: third input must be a logical 3d matrix with equal size than input 1\n""); + } + + + /* indices of the neighbor Ni (index distance) and euclidean distance NW */ + float NV[27], sf, bil, bih, bnl, bnh ; + int ind,ni,n; + bool *Bi, *Bn; + bool filterNANandINF; + + /* in- and output */ + float *D = (float *) mxGetPr(prhs[0]); + if (nrhs>1) Bi = (bool *) mxGetPr(prhs[1]); + if (nrhs>2) Bn = (bool *) mxGetPr(prhs[2]); + if (nrhs<4) sf = 0; + else sf = (float) *mxGetPr(prhs[3]); + + if (nrhs<5) bil = -FLT_MAX; + else bil = (float) *mxGetPr(prhs[4]); + if (nrhs<6) bih = FLT_MAX; + else bih = (float) *mxGetPr(prhs[5]); + if (nrhs<7) bnl = -FLT_MAX; + else bnl = (float) *mxGetPr(prhs[6]); + if (nrhs<8) bnh = FLT_MAX; + else bnh = (float) *mxGetPr(prhs[7]); + if (nrhs<9) filterNANandINF = true; + else filterNANandINF = 0 < *mxGetPr(prhs[8]); + + plhs[0] = mxCreateNumericArray(dL,sL,mxSINGLE_CLASS,mxREAL); + float *M = (float *) mxGetPr(plhs[0]); + + /* filter process */ + for (int z=0;z=2 && Bi[ind]) ) && /* filter allwaws or only in the masked regions if a mask is given */ + ( mxIsNaN(D[ind]) || mxIsInf(D[ind]) || ( D[ind]>=bil && D[ind]<=bih ) ) && /* filter only in range or in case of NAN or INF */ + ( filterNANandINF || ( !mxIsNaN(D[ind]) && !mxIsInf(D[ind])) ) ) { /* filter only voxels that are not NAN or INF if filterNANandINF==0*/ + n = 0; + /* go through all elements in a 3x3x3 box */ + for (int i=-1;i<=1;i++) for (int j=-1;j<=1;j++) for (int k=-1;k<=1;k++) { + /* check borders */ + if ( ((x+i)>=0) && ((x+i)=0) && ((y+j)=0) && ((z+k)=3 && Bn[ni]==0) || D[ni]bnh || mxIsNaN(D[ni]) || mxIsInf(D[ni]) ) ni = ind; + + /* Use only non NAN and INF values */ + if ( !mxIsNaN(D[ni]) && !mxIsInf(D[ni]) ) { + NV[n] = D[ni]; + n++; + } + } + } + + /* sort and get the median by finding the element in the middle of the sorting */ + if (n>1) { if (n==2) { + M[ind] = (NV[0] + NV[1]) / 2.0; + } + else { + sort(NV,0,n); + /* M[ind] = NV[(int) round( ((double)n)/2.0)]; */ /* OLD VERSION */ + M[ind] = (NV[(int) floor( ((double)n)/2.0)] + NV[(int) ceil( ((double)n)/2.0)]) / 2.0; + } + } + } + else { + M[ind] = D[ind]; + } + } + + /* selective filter settings - only big changes (only change extremly noisy data) */ + if (sf>0.0) { + for (int i=0;i=2 && Bi[i]) && D[i]>bil && D[i]=2 && Bi[i]) && D[i]>bil && D[i]-sf) ) M[i]=D[i]; + } + } + +} + + +","C" +"Neurology","ChristianGaser/cat12","cat_conf_output.m",".m","25298","493","function [output,output_spm] = cat_conf_output(expert) +%function [output,output_spm] = cat_conf_output(expert) +% writing options for data +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ +% +%#ok<*AGROW> + + if ~exist('expert','var') + try + expert = cat_get_defaults('extopts.expertgui'); + catch %#ok + expert = 0; + end + end + + %------------------------------------------------------------------------ + + % get default BIDS folder + try + bids_folder = cat_get_defaults('extopts.bids_folder'); + catch + bids_folder = fullfile('derivatives',cat_version); + end + + BIDSfolder = cfg_entry; + BIDSfolder.tag = 'BIDSfolder'; + BIDSfolder.name = 'BIDS folder (relative to dataset root)'; + BIDSfolder.strtype = 's'; + BIDSfolder.num = [1 Inf]; + BIDSfolder.val = {bids_folder}; + BIDSfolder.help = {'Path to derivatives relative to the dataset root (the parent directory of the subject folders, i.e., the folder that contains sub-*).', ... + 'Example: ""derivatives/CAT12.x_rxxxx"" will save results to /derivatives/CAT12.x_rxxxx//... regardless of the depth of the input files.', ... + 'Absolute paths are not allowed here.'}; + + BIDSfolder2 = BIDSfolder; + BIDSfolder2.name = 'Relative folder (advanced)'; + + BIDSyes2 = cfg_branch; + BIDSyes2.tag = 'BIDSyes2'; + BIDSyes2.name = 'Yes (relative folder)'; + BIDSyes2.val = {BIDSfolder2}; + BIDSyes2.help = {'Use relative directory structure for storing data although if it is not BIDS conform. This alternative definion based on the depth of the file, controlled here by the repetition of ""../"" is keeping subdirectories to be more robust in case of a regular but non-BIDS structure without default directory naming ""sub-##/ses-##/anat"" and similar filenames, e.g. for ""../../derivatives/CAT##.#_#"" and the following files:'; + ' ../group-01/sub-01/t1w.nii'; + ' ../group-01/sub-02/t1w.nii'; + 'it results in:'; + ' ../derivatives/CAT##.#_#/group-01/sub-01/t1w.nii'; + ' ../derivatives/CAT##.#_#/group-01/sub-02/t1w.nii'; + 'rather than:'; + ' ../derivatives/CAT##.#_#/t1w.nii'; + ' ../derivatives/CAT##.#_#/t1w.nii'; + 'where the relative BIDS folder would also cause conflicts by overwriting results.'; + ''; + }; + + BIDSyes = cfg_branch; + BIDSyes.tag = 'BIDSyes'; + BIDSyes.name = 'Yes'; + BIDSyes.val = {BIDSfolder}; + BIDSyes.help = {'Use BIDS directory structure for storing data'}; + + BIDSno = cfg_const; + BIDSno.tag = 'BIDSno'; + BIDSno.name = 'No'; + BIDSno.val = {1}; + BIDSno.help = {'Use CAT12 default directories for storing data'}; + + BIDS = cfg_choice; + BIDS.tag = 'BIDS'; + BIDS.name = 'Use BIDS directory structure?'; + if expert + BIDS.values = {BIDSyes2 BIDSyes BIDSno}; + else + BIDS.values = {BIDSyes BIDSno}; + end + if cat_get_defaults('extopts.bids_yes') + BIDS.val = {BIDSyes}; + else + BIDS.val = {BIDSno}; + end + BIDS.help = {'Select prefered output structure to save data.'}; + + + %------------------------------------------------------------------------ + + surface = cfg_menu; + surface.tag = 'surface'; + surface.name = 'Surface and thickness estimation'; + surface.labels = {'No','Yes'}; + surface.values = {0 1}; + surface.def = @(val)cat_get_defaults('output.surface', val{:}); + surface.help = { + 'Use projection-based thickness (PBT) (Dahnke et al. 2012) to estimate cortical thickness and to create the central cortical surface for left and right hemisphere. Surface reconstruction includes topology correction (Yotter et al. 2011), spherical inflation (Yotter et al.) and spherical registration. Additionally you can also estimate surface parameters such as gyrification, cortical complexity or sulcal depth that can be subsequently analyzed at each vertex of the surface. ' + '' + 'Please note, that surface reconstruction and spherical registration additionally requires about 20-60 min of computation time.' + '' + }; + + if expert == 2 + surface.labels = {'No', 'lh + rh (T1w-based)', 'lh + rh + cb (T1w-based)',... + 'lh + rh (AMAP-based)', 'lh + rh + cb (AMAP-based)',... + 'Thickness estimation (for ROI analysis only)', 'Full'}; + surface.values = {0 1 2 , 11 12, 9 22}; + surface.help = [surface.help; { + 'Cerebellar reconstruction is still in development and is strongly limited due to the high frequency of folding and image properties! ' + '' + 'You can also estimate thickness for ROI analysis only. This takes much less time, but does not allow to take advantage of surface-based registration and smoothing and the extraction of additional surface parameters. Here, the analysis is limited to cortical thickness only in atlas-defined ROIs.' + }]; + end + + % write specific output surface maps + % 0 none: only surfaces (central,white,pial,sphere,sphere.reg) + % 1 default: + thickness + % 2 expert: + L4myelination, topology defects, + % 3 developer: + WM and CSF thickness, YppRMSEmap? + % 4 debug: + substeps in subdirs + surf_measures = cfg_menu; + surf_measures.tag = 'surf_measures'; + surf_measures.name = 'Surface measures'; + surf_measures.labels = {'Default','Expert'}; + surf_measures.values = {1 2}; + surf_measures.val = {1}; + surf_measures.hidden = expert<2; + surf_measures.help = { + ['Write additional surface measures that are currently under development. ' ... + 'The defaults setting include only cortical thickness, whereas the expert level also ' ... + 'writes a myelination map (normalized T1 intensity extracted at the layer 4 surface) and ' ... + 'a map of topology defects coding the percentage size of the effect. ']; + }; + if expert == 2 + surf_measures.labels = [ surf_measures.labels {'Developer','Debug'}]; + surf_measures.values = [ surf_measures.values {3,4}]; + surf_measures.val = {3}; + surf_measures.help = [ surf_measures.help + {'The developer option further write the gyral and sulcal thickness. '} + ]; + end + + %------------------------------------------------------------------------ + native = cfg_menu; + native.tag = 'native'; + native.name = 'Native space'; + native.labels = {'No','Yes'}; + native.values = {0 1}; + native.help = { + 'The native space option allows you to save a tissue class image (p*) that is in alignment with the original image.' + '' + }; + + warped = cfg_menu; + warped.tag = 'warped'; + warped.name = 'Normalized'; + warped.labels = {'No','Yes'}; + warped.values = {0 1}; + warped.help = {'Write image in normalized space without any modulation.' + '' + }; + + dartel = cfg_menu; + dartel.tag = 'dartel'; + dartel.name = 'DARTEL export'; + if expert + dartel.labels = {'No','Rigid (SPM12 default)','Affine','Both'}; + dartel.values = {0 1 2 3}; + else + dartel.labels = {'No','Rigid (SPM12 default)','Affine'}; + dartel.values = {0 1 2}; + end + dartel.help = { + 'This option is to export data into a form that can be used with DARTEL. The SPM default is to only apply rigid body transformation. However, a more appropriate option is to apply affine transformation, because the additional scaling of the images requires less deformations to non-linearly register brains to the template.' + '' + }; + + native.def = @(val)cat_get_defaults('output.bias.native', val{:}); + warped.def = @(val)cat_get_defaults('output.bias.warped', val{:}); + dartel.def = @(val)cat_get_defaults('output.bias.dartel', val{:}); + bias = cfg_branch; + bias.tag = 'bias'; + bias.name = 'Bias, noise and global intensity corrected T1 image'; + if expert + bias.val = {native warped dartel}; + else + bias.val = {warped}; + end + bias.help = { + 'This is the option to save a bias, noise, and global intensity corrected version of the original T1 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 and can be saved in native space and/or normalised. Noise is corrected by an adaptive non-local mean (NLM) filter (Manjon 2008, Medical Image Analysis 12).' + '' + }; + bias_spm = bias; + bias_spm.val = {warped dartel}; + + native.def = @(val)cat_get_defaults('output.las.native', val{:}); + warped.def = @(val)cat_get_defaults('output.las.warped', val{:}); + dartel.def = @(val)cat_get_defaults('output.las.dartel', val{:}); + las = cfg_branch; + las.tag = 'las'; + las.name = 'Bias, noise and local intensity corrected T1 image'; + las.val = {native warped dartel}; + las.hidden = expert<1; + las.help = { + 'This is the option to save a bias, noise, and local intensity corrected version of the original T1 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 and can be saved in native space and/or normalised. Noise is corrected by an adaptive non-local mean (NLM) filter (Manjon 2008, Medical Image Analysis 12).' + '' + }; + + + %------------------------------------------------------------------------ + + jacobianwarped = warped; + jacobianwarped.tag = 'jacobianwarped'; + jacobianwarped.name = 'Jacobian determinant'; + jacobianwarped.def = @(val)cat_get_defaults('output.jacobian.warped', val{:}); + jacobianwarped.help = { + 'This is the option to save the Jacobian determinant, which expresses local volume changes. This image can be used in a pure deformation based morphometry (DBM) design. Please note that the affine part of the deformation field is ignored. Thus, there is no need for any additional correction for different brain sizes using ICV.' + '' + }; + + %------------------------------------------------------------------------ + + + native.def = @(val)cat_get_defaults('output.label.native', val{:}); + warped.def = @(val)cat_get_defaults('output.label.warped', val{:}); + dartel.def = @(val)cat_get_defaults('output.label.dartel', val{:}); + + label = cfg_branch; + label.tag = 'label'; + label.name = 'PVE label image'; + label.val = {native warped dartel}; + label.hidden = expert<1; + label.help = { + 'This is the option to save a labeled version of your segmentations for fast visual comparision. Labels are saved as Partial Volume Estimation (PVE) values with different mix classes for GM-WM (2.5) and GM-CSF (1.5). BG=0, CSF=1, GM=2, WM=3, WMH=4 (if WMHC=3), SL=1.5 (if SLC)' + '' + }; + + labelnative = native; + labelnative.tag = 'labelnative'; + labelnative.name = 'PVE label image in native space'; + labelnative.def = @(val)cat_get_defaults('output.label.native', val{:}); + labelnative.hidden = expert>0; + labelnative.help = { + 'This is the option to save a labeled version of your segmentations in native space for fast visual comparision and preprocessing quality control. Labels are saved as Partial Volume Estimation (PVE) values with different mix classes for GM-WM (2.5) and GM-CSF (1.5). BG=0, CSF=1, GM=2, WM=3, WMH=4 (if WMHC=3), SL=1.5 (if SLC)' + '' + }; + + + %------------------------------------------------------------------------ + + modulated = cfg_menu; + modulated.tag = 'mod'; + modulated.name = 'Modulated normalized'; + if expert + modulated.labels = {'No','Affine + non-linear (SPM12 default)','Non-linear only'}; + modulated.values = {0 1 2}; + else + modulated.labels = {'No','Yes'}; + modulated.values = {0 1}; + end + modulated.help = { + '""Modulation"" is to compensate for the effect of spatial normalisation. Spatial normalisation causes volume changes due to affine transformation (global scaling) and non-linear warping (local volume change). After modulation the resulting modulated images are preserved for the total amount of grey matter signal in the normalised partitions. Thus, modulated images reflect the tissue volumes before spatial normalisation. However, the user is almost always interested in removing the confound of different brain sizes and there are many ways to apply this correction. In contrast to previous VBM versions I now recommend to use total intracranial volume (TIV) as nuisance parameter in an AnCova model. ' + '' + 'Please note that I do not use the SPM modulation where the original voxels are projected into their new location in the warped images because this method introduces aliasing artifacts. Here, I use the scaling by the Jacobian determinants to generate ""modulated"" data. ' + '' + }; + + native.def = @(val)cat_get_defaults('output.GM.native', val{:}); + warped.def = @(val)cat_get_defaults('output.GM.warped', val{:}); + modulated.def = @(val)cat_get_defaults('output.GM.mod', val{:}); + dartel.def = @(val)cat_get_defaults('output.GM.dartel', val{:}); + grey = cfg_branch; + grey.tag = 'GM'; + grey.name = 'Grey matter'; + grey.help = {'Options to save grey matter images.' + '' + }; + grey_spm = grey; + if expert + grey.val = {native warped modulated dartel}; + grey_spm.val = {warped modulated dartel}; + else + grey.val = {native modulated dartel}; + grey_spm.val = {modulated dartel}; + end + + native.def = @(val)cat_get_defaults('output.WM.native', val{:}); + warped.def = @(val)cat_get_defaults('output.WM.warped', val{:}); + modulated.def = @(val)cat_get_defaults('output.WM.mod', val{:}); + dartel.def = @(val)cat_get_defaults('output.WM.dartel', val{:}); + white = cfg_branch; + white.tag = 'WM'; + white.name = 'White matter'; + white.help = {'Options to save white matter images.' + '' + }; + white_spm = white; + if expert + white.val = {native warped modulated dartel}; + white_spm.val = {warped modulated dartel}; + else + white.val = {native modulated dartel}; + white_spm.val = {modulated dartel}; + end + + + native.def = @(val)cat_get_defaults('output.CSF.native', val{:}); + warped.def = @(val)cat_get_defaults('output.CSF.warped', val{:}); + modulated.def = @(val)cat_get_defaults('output.CSF.mod', val{:}); + dartel.def = @(val)cat_get_defaults('output.CSF.dartel', val{:}); + csf = cfg_branch; + csf.tag = 'CSF'; + csf.name = 'Cerebro-Spinal Fluid (CSF)'; + csf.help = {'Options to save CSF images.' + '' + }; + csf.hidden = expert<1; + csf_spm = csf; + csf.val = {native warped modulated dartel}; + csf_spm.val = {warped modulated dartel}; + + % head/background tissue classes + native.def = @(val)cat_get_defaults('output.TPMC.native', val{:}); + warped.def = @(val)cat_get_defaults('output.TPMC.warped', val{:}); + modulated.def = @(val)cat_get_defaults('output.TPMC.mod', val{:}); + dartel.def = @(val)cat_get_defaults('output.TPMC.dartel', val{:}); + tpmc = cfg_branch; + tpmc.tag = 'TPMC'; + tpmc.name = 'Tissue Probability Map Classes'; + tpmc.hidden = expert<1; + tpmc.help = {'Option to save the SPM tissue class 4 to 6: p#*.img, wp#*.img and m[0]wp#*.img.' + '' + }; + tpmc.val = {native warped modulated dartel}; + tpmc_spm = tpmc; + tpmc_spm.val = {warped modulated dartel}; + + + % WMH + native.def = @(val)cat_get_defaults('output.WMH.native', val{:}); + warped.def = @(val)cat_get_defaults('output.WMH.warped', val{:}); + modulated.def = @(val)cat_get_defaults('output.WMH.mod', val{:}); + dartel.def = @(val)cat_get_defaults('output.WMH.dartel', val{:}); + wmh = cfg_branch; + wmh.tag = 'WMH'; + wmh.name = 'White matter hyperintensities (WMHs)'; + wmh.val = {native warped modulated dartel}; + wmh.hidden = expert<1; + wmh.help = {'WARNING: Please note that the detection of WM hyperintensities (WMHs) is still under development and does not have the same accuracy as approaches that additionally consider FLAIR images (e.g. Lesion Segmentation Toolbox)!' + 'Options to save WMH images, if WMHC==3: p7*.img, wp7*.img and m[0]wp7*.img.' + '' + }; + + % stroke lesions + native.def = @(val)cat_get_defaults('output.SL.native', val{:}); + warped.def = @(val)cat_get_defaults('output.SL.warped', val{:}); + modulated.def = @(val)cat_get_defaults('output.SL.mod', val{:}); + dartel.def = @(val)cat_get_defaults('output.SL.dartel', val{:}); + sl = cfg_branch; + sl.tag = 'SL'; + sl.name = 'Stroke lesions (SLs) - in development'; + sl.val = {native warped modulated dartel}; + sl.hidden = expert<1; + sl.help = {'WARNING: Please note that the handling of stroke lesions (SLs) is still under development! ' + 'To save SL images, SLC has to be active and (SLs has to be labeled): p8*.img, wp8*.img and m[0]wp8*.img.' + '' + }; + + % main structure atlas + native.def = @(val)cat_get_defaults('output.atlas.native', val{:}); + warped.def = @(val)cat_get_defaults('output.atlas.warped', val{:}); + dartel.def = @(val)cat_get_defaults('output.atlas.dartel', val{:}); + atlas = cfg_branch; + atlas.tag = 'atlas'; + atlas.name = 'Atlas label maps'; + if expert < 2 + atlas.val = {native}; + else + atlas.val = {native warped dartel}; + end + atlas.hidden = expert<1; + atlas.help = { + 'This option saves the selected atlas maps from the ""Process Volume ROIs"" dialog in native space. The name of the atlas is prepended to the file name.' + '' + 'In addition the cat atlas map with major structures is saved.' + '' + }; + + % cortical thickness maps + native.def = @(val)cat_get_defaults('output.ct.native', val{:}); + warped.def = @(val)cat_get_defaults('output.ct.warped', val{:}); + dartel.def = @(val)cat_get_defaults('output.ct.dartel', val{:}); + native.val = {0}; + warped.val = {0}; + dartel.val = {0}; + gmt = cfg_branch; + gmt.tag = 'ct'; + gmt.name = 'Cortical Thickness'; + gmt.val = {native warped dartel}; + gmt.hidden = expert<2; + gmt.help = { + 'Options to save cortical thickess maps (experimental).' + '' + }; + + % percentual position maps - uses defaults from thickness + native.def = @(val)cat_get_defaults('output.pp.native', val{:}); + warped.def = @(val)cat_get_defaults('output.pp.warped', val{:}); + dartel.def = @(val)cat_get_defaults('output.pp.dartel', val{:}); + native.val = {0}; + warped.val = {0}; + dartel.val = {0}; + pp = cfg_branch; + pp.tag = 'pp'; + pp.name = 'Percentage Position'; + pp.val = {native warped dartel}; + pp.hidden = expert<1; + pp.help = { + 'Options to save percentage position maps (experimental).' + '' + }; + + warps = cfg_menu; + warps.tag = 'warps'; + warps.name = 'Deformation Fields'; + warps.labels = { + 'No' + 'Image->Template (forward)' + 'Template->Image (inverse)' + 'inverse + forward'}; + warps.values = {[0 0],[1 0],[0 1],[1 1]}; + warps.def = @(val)cat_get_defaults('output.warps', val{:}); + warps.help = { + 'Deformation fields can be saved to disk, and used by the Deformations Utility and/or applied to coregistered data from other modalities (e.g. fMRI). For spatially normalising images to MNI space, you will need the forward deformation, whereas for spatially normalising (eg) GIFTI surface files, you''ll need the inverse. It is also possible to transform data in MNI space on to the individual subject, which also requires the inverse transform. Deformations are saved as .nii files, which contain three volumes to encode the x, y and z coordinates.' + '' + }; + + rmat = cfg_menu; + rmat.tag = 'rmat'; + rmat.name = 'Registration Matrixes'; + rmat.labels = {'No','Yes'}; + rmat.values = {0 1}; + rmat.def = @(val)cat_get_defaults('output.rmat', val{:}); + rmat.hidden = expert<1; + rmat.help = { + 'Deformation matrixes (affine and rigid) can be saved and used by the SPM Reorient Images Utility and/or applied to coregistered data from other modalities (e.g. fMRI). For normalising images to MNI space, you will need the forward transformation, whereas for normalising (eg) GIFTI surface files, you''ll need the inverse. It is also possible to transform data in MNI space on to the individual subject, which also requires the inverse transform. Transformation are saved as .mat files, which contain the tranformation matrix.' + '' + }; + + %% ------------------------------------------------------------------------ + + [ROI,sROI] = cat_conf_ROI(expert); % ROI options + + output = cfg_branch; + output.tag = 'output'; + output.name = 'Writing options'; + %if expert + % output.val = {BIDS surface surf_measures ROI sROI grey white csf gmt pp wmh sl tpmc atlas label labelnative bias las jacobianwarped warps rmat}; + %else + output.val = {BIDS surface surf_measures ROI sROI grey white csf gmt pp wmh sl tpmc atlas label labelnative bias las jacobianwarped warps rmat}; + %end + + output.help = { + 'There are a number of options about what kind of data you like save. The routine can be used for saving images of tissue classes, as well as bias corrected images. The native space option will save a tissue class image (p*) that is in alignment with the original image. You can also save spatially normalised versions - both with (m[0]wp*) and without (wp*) modulation. In the cat toolbox, the voxel size of the spatially normalised versions is 1.5 x 1.5 x 1.5mm as default. The saved images of the tissue classes can directly be used for doing voxel-based morphometry (both un-modulated and modulated). 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""). Please note that many less-common options are only available in expert mode (e.g. CSF, labels, atlas maps).' + '' + '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 labeled 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.' + '' + '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 |% \ /' + '' + '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.'}; + + %% + %------------------------------------------------------------------------ + % R1173 + %------------------------------------------------------------------------ + warped.def = @(val)cat_get_defaults1173('output.jacobian.warped', val{:}); + jacobian = cfg_branch; + jacobian.tag = 'jacobian'; + jacobian.name = 'Jacobian determinant'; + jacobian.val = {warped}; + jacobian.help = { + 'This is the option to save the Jacobian determinant, which expresses local volume changes. This image can be used in a pure deformation based morphometry (DBM) design. Please note that the affine part of the deformation field is ignored. Thus, there is no need for any additional correction for different brain sizes using ICV.' + '' + }; + + output_spm = output; + output_spm.val = {BIDS surface ROI grey_spm white_spm csf_spm tpmc_spm label bias_spm labelnative jacobianwarped warps}; + +return +%------------------------------------------------------------------------","MATLAB" +"Neurology","ChristianGaser/cat12","cat_conf_tools.m",".m","228263","5177","function tools = cat_conf_tools(expert) +% wrapper for calling CAT utilities +% +% tools = cat_conf_tools(expert) +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + if ~exist('expert','var'), expert = 1; end + +% multi use fields +% ----------------------------------------------------------------------- + + % just used once + data_xml = cfg_files; + data_xml.name = 'Quality measures'; + data_xml.tag = 'data_xml'; + data_xml.filter = 'xml'; + data_xml.ufilter = '^cat_.*\.xml$'; + data_xml.val = {{''}}; + data_xml.num = [0 Inf]; + data_xml.help = { + 'Select the quality measures that are saved during segmentation as xml-files in the report folder.' + 'Please note, that the order of the xml-files should be the same as the other data files.' + }; + + outdir = cfg_files; + outdir.tag = 'outdir'; + outdir.name = 'Output directory'; + outdir.filter = 'dir'; + outdir.ufilter = '.*'; + outdir.num = [0 1]; + outdir.help = {'Select a directory where files are written.'}; + outdir.val{1} = {''}; + + subdir = cfg_entry; + subdir.tag = 'subdir'; + subdir.name = 'Additional output directory'; + subdir.strtype = 's'; + subdir.num = [0 Inf]; + subdir.val = {'EVA_volmod'}; + subdir.help = { + 'The directory is created within the choosen output directory. If no name is given no subdirecty is created. ' ''}; + + data = cfg_files; + data.tag = 'data'; + data.name = 'Volumes'; + data.filter = 'image'; + data.ufilter = '.*'; + data.num = [1 Inf]; + data.help = {''}; + + + % Do not process, if result already exists and is younger than the + % original image, i.e., if the original was changed then it will be + % processed again. The function is quite helpful to develop and test + % SPM batches and avoid reprocessing of slow steps. + lazy = cfg_menu; + lazy.tag = 'lazy'; + lazy.name = 'Lazy processing'; + lazy.labels = {'Yes','No'}; + lazy.values = {1,0}; + lazy.val = {0}; + lazy.help = { + 'Do not process data if the result already exists. ' + }; + + +% CHECK USE + data_vol = cfg_files; + data_vol.name = 'Sample data'; + data_vol.tag = 'data_vol'; + data_vol.filter = 'image'; + data_vol.num = [1 Inf]; + data_vol.help = {'These are the (spatially registered) data. They must all have the same image dimensions, orientation, voxel size etc. Furthermore, it is recommended to use unsmoothed files.'}; + + % also this is a separate function that is used for the results + spm_type = cfg_menu; % + spm_type.tag = 'spm_type'; + spm_type.name = 'Data type of the output images'; + spm_type.labels = {'same','uint8','int8','uint16','int16','single'}; + spm_type.values = {0 2 256 512 4 16}; + spm_type.val = {16}; + spm_type.help = { + 'SPM data type of the output image. Single precision is recommended, but uint16 also provides good results. Internal scaling supports a relative high accuracy for the limited number of bits, special values such as NAN and INF (e.g. in the background) will be lost and NAN is converted to 0, -INF to the minimum, and INF to the maximum value. ' + '' + }; + + % also this limit is a separate function that is used for the noise filter + % and therefore included here + intlim = cfg_entry; + intlim.tag = 'intlim'; + intlim.name = 'Global intensity limitation'; + intlim.strtype = 'r'; + intlim.num = [1 inf]; + intlim.val = {100}; + intlim.help = { + 'General intensity limitation to remove strong outliers by using 100% of the original histogram values. ' + 'You can also specify the lower and upper boundary seperatlym, e.g. [80 99], what will keep only 80% of the (many) low (background values) but 99% of the (rew) high intensity (skull) values. ' + '' + }; + + prefix = cfg_entry; + prefix.tag = 'prefix'; + prefix.name = 'Filename prefix'; + prefix.strtype = 's'; + prefix.num = [0 Inf]; + prefix.val = {''}; + prefix.help = {''}; + + suffix = cfg_entry; + suffix.tag = 'suffix'; + suffix.name = 'Filename suffix'; + suffix.strtype = 's'; + suffix.num = [0 Inf]; + suffix.val = {''}; + suffix.help = {''}; + + fname = prefix; + fname.name = 'Filename'; + fname.tag = 'fname'; + fname.val = {'CATcheckdesign_'}; + fname.help = {'Basic filename to save figures.'}; + + save = cfg_menu; + save.name = 'Save & close windows'; + save.tag = 'save'; + save.labels = {'Save & close','Save only','No'}; + save.values = {2,1,0}; + save.val = {0}; + save.help = {'Save and close figures for batch processing.'}; + + verb = cfg_menu; + verb.tag = 'verb'; + verb.name = 'Verbose output'; + verb.labels = {'No' 'Yes' 'Yes (Details)'}; + verb.values = {0 1 2}; + verb.val = {1}; + verb.hidden = expert<1; + verb.help = { + 'Be more or less verbose. ' + '' + }; + + globals = cfg_menu; + globals.tag = 'globals'; + globals.name = 'Global scaling with TIV'; + globals.labels = {'Yes', 'No'}; + globals.values = {1 0}; + globals.val = {0}; + globals.help = { + 'This option is to correct mean Z-scores for TIV by global scaling. It is only meaningful for VBM data.' + '' + }; + +% get subbatches +% ------------------------------------------------------------------------- + [T2x,T2x_surf,F2x,F2x_surf] = conf_T2x; + [check_cov_old, check_cov] = conf_check_cov(data_xml,outdir,fname,save,globals,expert); + quality_measures = conf_quality_measures(globals); + [defs,defs2] = conf_vol_defs; + nonlin_coreg = cat_conf_nonlin_coreg; + createTPM = conf_createTPM(data_vol,expert,suffix,outdir); + createTPMlong = conf_createTPMlong(data_vol,expert); + long_report = conf_long_report(data_vol,data_xml,expert); + headtrimming = conf_vol_headtrimming(intlim,spm_type,prefix,suffix,verb,lazy,expert); + check_SPM = conf_stat_check_SPM(outdir,fname,save,expert); + showslice = conf_stat_showslice_all(data_vol); + maskimg = conf_vol_maskimage(data,prefix); + calcvol = conf_stat_TIV; + spmtype = conf_io_volctype(data,intlim,spm_type,prefix,suffix,verb,expert,lazy); + calcroi = conf_roi_fun(outdir); + [~,~,ROIsum] = cat_conf_ROI(expert); + resize = conf_vol_resize(data,prefix,expert,outdir); + avg_img = conf_vol_average(data,outdir); + savg = conf_vol_savg(prefix,verb,expert); + realign = conf_vol_series_align(data,expert); + shootlong = conf_shoot(expert); + [sanlm,sanlm2] = conf_vol_sanlm(data,intlim,spm_type,prefix,suffix,lazy,expert); + biascorrlong = conf_longBiasCorr(data,expert,prefix); + data2mat = conf_io_data2mat(data,outdir); + boxplot = conf_io_boxplot(outdir,subdir,prefix,expert); + [getCSVXML,getXML,getCSV] = cat_cfg_getCSVXML(outdir,expert); + xml2csv = conf_io_xml2csv(outdir); + file_move = conf_io_file_move; + mp2rage = conf_vol_mp2rage(prefix,verb,expert); + %urqio = conf_vol_urqio; % this cause problems + iqr = conf_stat_IQR(data_xml); + qa = conf_vol_qa(expert,outdir); + catreport = conf_main_report(data_xml,outdir,expert); + multi_subject_imcalc = conf_vol_imcalc(prefix); + +% create main batch +% ------------------------------------------------------------------------- + tools = cfg_choice; + tools.name = 'Tools'; + tools.tag = 'tools'; + tools.values = { ... + showslice, ... cat.stat.pre + check_cov, ... cat.stat.pre + check_cov_old, ... cat.stat.pre + quality_measures, ... cat.stat.pre + qa, ... cat.stat.pre + check_SPM, ... cat.stat.pre + ... + calcvol, ... cat.stat.pre + calcroi, ... cat.stat.pre + ROIsum, ... + iqr, ... cat.stat.pre + ... + T2x, F2x, T2x_surf, F2x_surf, ... cat.stat.models? + ... + ... SPLIT THIS FILE ?! + ... + sanlm, ... cat.pre.vtools. + sanlm2, ... + maskimg, ... cat.pre.vtools. + spmtype, ... cat.pre.vtools. + headtrimming, ... cat.pre.vtools. + resize, ... cat.pre.vtools. + multi_subject_imcalc, ... cat.pre.vtools. + mp2rage, ... + ... + realign, ... cat.pre.long.? % hidden + shootlong,... cat.pre.long.? % hidden + biascorrlong,... cat.pre.long.? % hidden + createTPMlong, ... cat.pre.long.createTPM % hidden + long_report, ... cat.pre.long.report % hidden + ... + createTPM, ... + nonlin_coreg, ... cat.pre.vtools. + defs, ... cat.pre.vtools. + defs2, ... cat.pre.vtools. + avg_img, ... cat.pre.vtoolsexp. + savg, ... cat.pre.vtools. + data2mat, ... cat.pre.vtools. + ... + catreport, ... + boxplot, ... cat.stat.eval ... print of XML data by the boxplot function and saving as images + getCSVXML, ... cat.stat.eval ... read out of XML/CSV data and export as batch dependency + xml2csv, ... + getXML, ... + getCSV, ... + file_move, ... + ... + }; + + %RD202005: the cause problems at Christians installation ... check it + %if expert + % tools.values = [tools.values,{urqio}]; + %end +return +%_______________________________________________________________________ +function savg = conf_vol_savg(prefix,verb,expert) +%conf_vol_savg. GUI setup for subject-session average tool + + + % files per subject + subjectdirs = cfg_files; + subjectdirs.tag = 'subjectdirs'; + subjectdirs.name = 'Directories'; + subjectdirs.help = {'Select directories of subjects or sessions that contain (gzipped) NIFTI files (in subdirectories) for averaging.' ''}; + subjectdirs.filter = 'dir'; + + sessiondirs = cfg_files; + sessiondirs.tag = 'sessiondirs'; + sessiondirs.name = 'Session directories'; + sessiondirs.help = {'Select session directories that contain (gzipped)NIFTI files (in subdirectories) for averaging.' ''}; + sessiondirs.filter = 'dir'; + + session = cfg_files; + session.num = [1 Inf]; + session.tag = 'session'; + session.name = 'Session files'; + session.ufilter = '.*.nii'; + session.filter = 'any'; % also want nii.gz + session.help = {'Select all (gzipped) NIFTI images of this session that should be averaged. '}; + + subject = cfg_repeat; + subject.tag = 'subject'; + subject.name = 'Subject'; + subject.values = {session,sessiondirs}; + subject.val = {session}; + subject.num = [1 Inf]; + subject.help = {'Define sessions of a subject.'}; + + scans = session; + scans.name = 'Subject files'; + scans.help = {'Select all (gzipped) NIFTI images for this subject that should be averaged. '}; + + subjects = cfg_repeat; + subjects.tag = 'subjects'; + subjects.name = 'Subjects/Sessions'; + subjects.values = {subjectdirs,subject,scans}; + subjects.val = {subjectdirs}; + subjects.num = [1 Inf]; + subjects.help = { + ['Specify a set of files for a number of subjects or select a set of directories, each with subject-specific scans (in subdirs). ' ... + 'For example, if you have images in a BIDS structure you can select the subjects by choosing the subject or session directory. '] + '' + }; + + + % data selectors + % ----------------------------------------------------------------------- + + % file limitations (DEVELOPER) + filelim = cfg_entry; + filelim.tag = 'filelim'; + filelim.name = 'File number limit (Expert)'; + filelim.strtype = 'n'; + filelim.num = [1 1]; + filelim.val = {inf}; + filelim.hidden = expert<1; + filelim.help = {'Just to support quick tests. '}; + + % seplist + seplist = cfg_entry; + seplist.tag = 'seplist'; + seplist.name = 'Data separation list'; + seplist.strtype = 's'; + seplist.num = [0 Inf]; + seplist.val = {'T1w T2w PD inv1 inv2'}; + seplist.help = {'Enter keywords to separate files in the averaging process, e.g., to separate protocols (T1w,T2w etc.). ' ''}; + + % blacklist + blacklist = cfg_entry; + blacklist.tag = 'blacklist'; + blacklist.name = 'Blacklist'; + blacklist.strtype = 's'; + blacklist.num = [0 Inf]; + blacklist.val = {''}; + blacklist.help = {'Enter strings to excluded files, e.g., protocols you don''t want to include. ' ''}; + + % reqlist + reqlist = cfg_entry; + reqlist.tag = 'reqlist'; + reqlist.name = 'Path selector (EXPERT)'; + reqlist.strtype = 's'; + reqlist.num = [0 Inf]; + reqlist.hidden = expert<1; + reqlist.val = {[filesep 'anat' filesep]}; + reqlist.help = {'Enter strings that have to be in the path to force on specific directories, eg. with anatomical data. ' ''}; + + % resolution limitation (EXPERT) + reslim = cfg_entry; + reslim.tag = 'reslim'; + reslim.name = 'Resolution limitation (EXPERT)'; + reslim.strtype = 'r'; + reslim.num = [1 3]; + reslim.val = {[2 3 8]}; + reslim.hidden = expert<1; + reslim.help = { + ['The first value specify the standard deviation from the median voxel volume to remove scans with lower values. ' ... + 'It avoids to include low resolution scans if high resolution data is available. '] + ['The second value describes the lower limit of inslice resolution ' ... + '(at least one dimension should have higher resolution) whereas the ' ... + 'second value defines the lower limit of slice thickness (worst resolution limit). '] + ['E.g., for [1 2 8] a resolution of [ 0.6 0.6 4] or [ 2 2 8] is ok but not' ... + '[0.5 0.5 10] (too thick slices) or [ 3 3 3] (to low slice resolution). '] + 'Keep in mind that there is also a general limitation to high resolution data within this subject. ' + }; + + + % main field + limits = cfg_exbranch; + limits.tag = 'limits'; + limits.name = 'Data selectors'; + limits.val = {seplist,blacklist,reqlist,reslim,filelim}; + limits.help = {'Parameters to control the selection of input files. '}; + + + % processing options + % ----------------------------------------------------------------------- + + % intensity normalization bias correction (EXPERT) + bias = cfg_menu; + bias.tag = 'bias'; + bias.name = 'Bias correction'; % intensity normalization is done by the the long pipeline anyway + bias.labels = {'no','yes'}; + bias.values = {0 2}; + bias.val = {2}; + bias.help = {'Use soft bias correction. '}; + + % denoising + sanlm = cfg_menu; + sanlm.tag = 'sanlm'; + sanlm.name = 'Spatial Non Local Means (SANLM) denoising'; + sanlm.labels = {'no','yes'}; + sanlm.values = {0 1}; + sanlm.val = {1}; + sanlm.help = {'Use SANLM denoising filter before reslicing. The amount of denoising is reduce with growing number of scans. ' ''}; + + % sharpen (EXPERT - this is experimental) + sharpen = cfg_menu; + sharpen.tag = 'sharpen'; + sharpen.name = 'Sharpening before resampling (EXPERT)'; + if expert > 1 + sharpen.labels = {'no','light','strong','heavy','insane'}; + sharpen.values = {0 1 2 4 8}; + else + sharpen.labels = {'no','light','strong'}; + sharpen.values = {0 1 2}; + end + sharpen.val = {1}; + sharpen.hidden = expert<1; % we hide as this is connected to the resolution + sharpen.help = {'Apply sharpening filter before averaging to improve appearance of edges. ' ''}; + + % resolution + res = cfg_entry; + res.tag = 'res'; + res.name = 'Spatial resolution'; + res.strtype = 'r'; + res.num = [1 1]; + res.val = {0}; + res.help = { + ['Output resolution of the average file. The default ""0"" uses the minimum resolution per subject/session. ' ... + 'Additional interpolation is only useful in case of many high-quality images. '] + '' + }; + + % Trimming option for CAT (one might need the full head) + reduce = cfg_menu; + reduce.name = 'Reduce Bounding Box'; + reduce.tag = 'reduce'; + reduce.labels = {'Yes','No'}; + reduce.values = {1,0}; + reduce.val = {1}; + reduce.hidden = expert<1; + reduce.help = { + 'Reduce bounding box at final resolution level because usually there is a lot of air around the head after registration of multiple scans. This helps to save memory and time for later use of these registered images.' + '' + 'Please note that this option can only be used for rigid registration and will be disabled for non-linear registration.' + }; + + % Non-linear option for SPM + + % MNI alignment and coregistration of separated scans + + % average method selector 1 - anyavg, 2 - spm/cat long, 3 - SPM-long + avgmethod = cfg_menu; + avgmethod.tag = 'avgmethod'; + avgmethod.name = 'Average method (EXPERT)'; + avgmethod.labels = {'SPMavg','CATavg','savg'}; + avgmethod.values = {3,2,1}; + avgmethod.val = {2}; + avgmethod.hidden = expert<1; + avgmethod.help = { + 'Select averaging method. ' + }; + + % opts field + opts = cfg_exbranch; + opts.tag = 'opts'; + opts.name = 'Options'; + opts.val = {bias,sanlm,sharpen,reduce,res,avgmethod}; + opts.help = {'Processing parameters'}; + + + % Output options: + % ----------------------------------------------------------------------- + + % cleanup temporary files (EXPERT - normal people are not expected to need the resliced files) + cleanup = cfg_menu; + cleanup.tag = 'cleanup'; + cleanup.name = 'Remove temporary files (EXPERT)'; + cleanup.labels = {'no','yes'}; + cleanup.values = {0,1}; + cleanup.val = {1}; + cleanup.hidden = expert<1; + cleanup.help = {'Remove temporary files from processing. ' ''}; + + % udpate of default fields + prefix.val = {''}; + prefix.hidden = expert<2; % automatic defined .. need further implementation and test + + suffix = prefix; + suffix.tag = 'suffix'; + suffix.name = 'Filename suffix'; + + BIDSdir = cfg_entry; + BIDSdir.tag = 'BIDSdir'; + BIDSdir.name = 'Output directory'; + BIDSdir.strtype = 's'; + BIDSdir.num = [0 inf]; + BIDSdir.val = {['derivatives' filesep 'catavg'];}; + BIDSdir.help = { + 'Output directory. ' + '' + }; + + verb.tag = 'verb'; + verb.name = 'Verbose output'; + verb.labels = {'no','yes','yes (details)'}; + verb.values = {0,1,2}; + verb.val = {1}; + verb.hidden = false; + verb.help = {'Remove temporary files from processing. ' ''}; + + % opts field + output = cfg_exbranch; + output.tag = 'output'; + output.name = 'Output'; + output.val = {BIDSdir,prefix,suffix,verb,cleanup}; + output.help = {'Output parameters'}; + + % main field + savg = cfg_exbranch; + savg.tag = 'savg'; + savg.name = 'Rescan average'; + savg.val = {subjects, limits, opts, output}; + savg.prog = @cat_vol_savg; + savg.vout = @vout_vol_savg; + savg.help = { + ['Creation of a subject- and session-wise average image of varying protocols, i.e., averaging of rescans to improve SNR. ' ... + 'The batch considers BIDS and allows the selection of the subject directories (sub-*). ' ... + 'It looks for session-directories (ses-*) and the anatomical data (anat directory). ' ... + 'The weightings are handled by the ""Data separation list"" and unwanted files can be excluded by the ""Blacklist"". '] + '' + ['It is assumed that rescans are within the same ses-*/anat/ directory (e.g. specified by a run-* entry). ' ... + 'Otherwise, it is possible to define subjects with sessions directly.'] + '' + ['The processing includes a quick bias-correction and denoising before the data is averaged per session. ' ... + 'In the case of many high-quality rescans, it is also possible to slightly increase the output resolution. ' ... + 'Moreover, a subject average of the session average is created in an additional ses-avg directory. '] + ''}; +return +%_______________________________________________________________________ +function mp2rage = conf_vol_mp2rage(prefix,verb,expert) +% conf_vol_mp2rage. Batch for cat_vol_mp2rage to optimize MP2Rage images. + + data = cfg_files; + data.tag = 'files'; + data.name = 'Volumes'; + data.filter = {'image'}; + data.ufilter = '.*'; + data.num = [1 Inf]; + data.help = {'Select head images. '}; + + spmseg = cfg_menu; + spmseg.tag = 'spmseg'; + spmseg.name = 'SPM Preprocessing (developer)'; + spmseg.labels = {'Yes (allways, with cleanup)'; 'Yes (only if required, no cleanup)'}; + spmseg.values = {1 2}; + spmseg.help = {'Run SPM Unified Segmentation if required and delete or keep the temporary results (e.g., to rerun this batch with other options but keep the SPM results). ' ''}; + spmseg.val = {1}; + spmseg.hidden = expert<2; + + bias = cfg_menu; + bias.tag = 'biascorrection'; + bias.name = 'Additional bias corretion'; + bias.labels = {'No'; 'Yes - basic';'Yes - extended'}; + bias.values = {0 1 2}; + bias.help = {'Additional bias correction. ' ''}; + bias.help = {'Bias correction by the SPM segmentation (simple) or with additional post-correction (complex). The extend version can help in cases of reminding inhomogeneities that can be seen as local/global underestimated ""blue"" thickness values (< 1.5 mm) on the CAT report. ' ''}; + bias.val = {1}; + %bias.hidden = expert<1; + + intscale = cfg_menu; + intscale.tag = 'intscale'; + intscale.name = 'Apply intensity harmonization'; + intscale.help = {'Use intensity scaling for more equally distributed tissue intensities.' ''}; + intscale.labels = {'No';'Yes'}; + intscale.values = {0,1}; + intscale.val = {1}; + intscale.hidden = expert>1; + + logscale = cfg_menu; + logscale.tag = 'log'; + logscale.name = 'Log/exp-based intensity transformation (expert)'; + logscale.help = {'Use log/exp scaling for more equally distributed tissue intensities. The default (""auto"") select a function that support the most balanced tissue peaks.' ''}; + if expert > 1 + logscale.labels = {'No';'Yes';'Yes - exp';'Yes - log'}; + logscale.values = {0,inf,-1,1,}; + else + logscale.labels = {'No';'Yes'}; + logscale.values = {0,inf}; + end + logscale.val = {inf}; + logscale.hidden = expert<1; + + intnorm = cfg_menu; + intnorm.tag = 'intnorm'; + intnorm.name = 'Contrast transformation (expert)'; + intnorm.help = {'Contrast normalization using the tangens function of GM normed values. This results in a compression of the GM values, whereas the outer CSF and WM values keep there intensities. ' ''}; + if expert > 1 + intnorm.labels = {'No (0)';'Light (-0.25)'; 'Standard (-0.50)'; 'Strong (-1.00)'; 'Severe (-1.50)'; 'Fixed (1.2)';'Fixed (1.4)';'Fixed (1.6)';'Fixed (1.8)';'Fixed (2.0)'}; + intnorm.values = {0, -0.25,-0.50,-1.00,-1.50, 1.2,1.4,1.6,1.8,2.0}; + intnorm.help = [intnorm.help {'Experts have additional manuell settings with light (1.2) to strong (2.0) corrections.'}]; + elseif expert + intnorm.labels = {'No';'Yes' }; + intnorm.values = {0, -0.5}; + end + intnorm.val = {-0.5}; + intnorm.hidden = expert<1; + + bet = cfg_menu; + bet.tag = 'skullstripping'; + bet.name = 'Skull-stripping'; + if expert > 1 + bet.labels = {'No (0)';'SPM (1)';'Optimized (2)';'Remove noisy background (only MP2Rage; 3)'}; + bet.values = {0,1,2,3}; + bet.help = {'Apply skull-stripping to the image. The ""SPM"" version may miss some brain regions (e.g., motorcortex/occiptial). The optimized version try to add some tissue around in without running too much into the skull. Alternatively only the noisy regions of the background and skull can be removed/reduced.' ''}; + else + bet.labels = {'No';'Yes';'Remove noisy background'}; + bet.values = {0,2,3}; + bet.help = {'Remove the skull or reduce noisy background/skull regions.' ''}; + end + bet.val = {3}; + +% bloodvesselscorrection - not implemented yet >> should be handled in CAT anyway +% maybe useful to handle SPM detected structures that were labeled as head +% for experts + + CSFnoise = cfg_menu; + CSFnoise.tag = 'restoreLCSFnoise'; + CSFnoise.name = 'Restore lower CSF noise if MP2Rage (expert)'; + CSFnoise.labels = {'No'; 'Yes'}; + CSFnoise.values = {0 1}; + CSFnoise.val = {1}; + CSFnoise.hidden = expert<1; + CSFnoise.help = {'In MP2Rage the CSF peak is quite inbalanced and the values are limited by zero. this adds some noise as far as some steps in SPM/CAT expect more variation within the CSF.' ''}; + + prefix.val = {'mp2rc_'}; + prefix.help = [prefix.help {'The string can include a subdirectory ""mytestdir/myprefix_"" that is then used to store the results. '}]; + if expert + prefix.help = [prefix.help {'The keyword ""PARA"" will be replaced by a string that include major parameter settings for testing. '}]; + end + + report = cfg_menu; + report.tag = 'report'; + report.name = 'Print report (developer)'; + report.labels = {'No'; 'Yes'}; + report.values = {0 1}; + report.val = {1}; + report.hidden = expert<2; + report.help = {'Create a report file with parameters, results and in-/output images.' ''}; + + verb.hidden = expert<1; + + % == main == + mp2rage = cfg_exbranch; + mp2rage.tag = 'mp2rage'; + mp2rage.name = 'MP2RAGE preprocessing for CAT'; + mp2rage.val = {data bias intscale logscale intnorm bet CSFnoise prefix report verb}; + mp2rage.prog = @cat_vol_mp2rage; + mp2rage.vout = @vout_mp2rage; % define output files d + mp2rage.help = { + 'Batch to optimize MP2Rage (and other) images for CAT preprocessing. It utilize SPM12 to correct inhomogenities, harmonize the GM-WM contrast, and finally apply a skull-stripping or reduce the noisy background/skull values. ' + }; + +return +function report = conf_main_report(data_xml,outdir,expert) +%conf_main_report. Retrospective creation of CAT report. + + data_xml.tag = 'files'; + data_xml.name = 'CAT XML files'; + data_xml.val = {}; + data_xml.num = [1 Inf]; + data_xml.help = { + 'Select CAT XML files from the report directories of the subjects those report has to be (re)generated.' + }; + + Pm = data_xml; + Pm.name = 'Intensity Normalized Images'; + Pm.tag = 'Pm'; + Pm.filter = {'image','^m.*\.(nii.gz)$'}; + Pm.hidden = expert < 1; + Pm.help = { + 'Select bias corrected images to replace the default settings. ' + 'The same subjects has to be used as for the XML files. ' + }; + + Pp0 = data_xml; + Pp0.name = 'Label maps'; + Pp0.tag = 'Pp0'; + Pp0.filter = {'image','^p0.*\.(nii.gz)$'}; + Pp0.hidden = expert < 1; + Pp0.help = { + 'Select segmentation label images to replace the default settings. ' + 'The same subjects has to be used as for the XML files. ' + }; + + print = cfg_menu; + print.tag = 'print'; + print.name = 'Print setting'; + print.labels = {'volume only','volume and surfaces'}; + print.values = {1 2}; + print.def = @(val)cat_get_defaults('extopts.print', val{:}); + print.hidden = expert < 1; + print.help = { + 'Create final CAT report that requires Java. ' + }; + + % remove old image field + report = cfg_exbranch; + report.val = {data_xml Pm Pp0 print outdir}; % xmlfields + report.help = {[... + 'Retrospective creation of the CAT report PDF/JPG by using the CAT preprocessing XML file, e.g., ' ... + 'when report creation was not possible or failed. ']}; + report.tag = 'catreport'; + report.vout = @vout_report; + report.prog = @cat_main_report; + report.name = 'Retrospective CAT Report'; +return +%_______________________________________________________________________ +function imcalc = conf_vol_imcalc(prefix) +%conf_vol_imcalc. Like spm_imcalc but to run the same operation for many subjects. + + % get original SPM imcalc function + imcalc = spm_cfg_imcalc; + + % update prefix and suffix fileds + suffix = prefix; + suffix.tag = 'suffix'; + suffix.name = 'Filename suffix'; + suffix.val = {''}; + suffix.help = {'You can use ""\b"" to remove the a letter at the end of the filename, e.g., ""srMyImage_segX1"" with ""\b\b0"" would replace the last two letters by 0, i.e., ""srMyImage_seg0"".'}; + prefix.help = {'You can use ""\f"" to remove the a letter at the beginning of the filename, e.g., ""srMyImage_seg1"" with ""\f\fx"" would replace the first two letters by x, i.e., ""xMyImage_seg1"".'}; + + % allow also gzipped + data = cfg_files; + data.tag = 'subjects'; + data.name = 'Volumes'; + data.filter = {'image','.*\.(nii.gz)$'}; + data.ufilter = '.*'; + data.num = [1 Inf]; + data.help = {'Select the same number and order of subjects for one image class. '}; + + image = data; + image.tag = 'images'; + image.name = 'Images'; + + images = cfg_repeat; + images.tag = 'imagetype'; + images.name = 'Image type'; + images.values = {image}; + images.num = [1 Inf]; + images.help = {'Specify input images class, e.g., the T1 image of a subject. '}; + + coreg = cfg_menu; + coreg.tag = 'coreg'; + coreg.name = 'Coregistration'; + coreg.labels = {'No'; 'Yes'}; + coreg.values = {0 1}; + coreg.val = {0}; + coreg.help = { + 'Apply coregistration to the first image of each subject.' + 'E.g. to combine T1w (i1) and T2w (i2) of the same subject with the expression: ' + '' + ' min( 5 , (i1./max(eps,i2)) .* log10(i1+i2+1) ) .* ~isnan(i2) ' + '' + 'or' + '' + ' min( 10 , max(0, i1./max(0,i1/2+i2)).^2 .* min(1,max(0,1 - 100*max(0, i1 ./ (i1+i2).^2 ) ))) .* ~isnan(i2)' + '' + 'with a general limit of 5, the eps to avoid division by 0, the log10 term to mask the background, and the isnan to avoid reslicing issues from the T2w.' + '' + }; +%min( 10 , (i1./max(eps,1+i2)) .* log10(1+log10( (i1.*i2) ./ (1+i1+i2).^2 + 1 ) )) .* ~isnan(i2) .* (i1./i2<100) +%min( 10 , (i1./i2) .* (1 - i1./max(i1,i1+i2.^2)) ) .* ~isnan(i2) .* (i1./i2<100) +%min( 10 , max(0, i1./max(0,i1/2+i2)).^2 .* min(1,max(0,1 - 100*max(0, i1 ./ (i1+i2).^2 ) ))) .* ~isnan(i2) + + + BIDsdir = cfg_entry; + BIDsdir.tag = 'BIDSdir'; + BIDsdir.name = 'Output Subdirectory'; + BIDsdir.strtype = 's'; + BIDsdir.num = [0 inf]; + BIDsdir.val = {['derivatives' filesep 'mimcalc'];}; + BIDsdir.help = {[... + 'Files produced by this function will be written into this subdirectory. ' ... + 'If no subdirectory is given, images will be written to the home of the first input image i1 within the output directory. ' ... + 'The name ""derivatives"" is used to keep the BIDS subdirectory list. ' ... + 'A relative path (e.g., ""../output"") can be used. '] + '' + }; + + + % remove old image field + imcalc.val = imcalc.val(); + imcalc.val{1} = images; + imcalc.val{2} = prefix; + imcalc.val(4:end+1) = imcalc.val(3:end); % move all fields + imcalc.val{3} = suffix; % add suffix option + imcalc.val(6:end+1) = imcalc.val(5:end); % move all fields + imcalc.val{5} = BIDsdir; % + imcalc.val{end}.val{end+1} = coreg; + imcalc.tag = 'mimcalc'; + imcalc.vout = @vout_mimcalc; + imcalc.prog = @cat_vol_mimcalc; + imcalc.name = 'Multi-subject Image Calculator'; +return +%_______________________________________________________________________ +function file_move = conf_io_file_move + +% --------------------------------------------------------------------- +% file_move Move/Delete Files +% --------------------------------------------------------------------- + + +% --------------------------------------------------------------------- +% files Files to move/copy/delete +% --------------------------------------------------------------------- +files = cfg_files; +files.tag = 'files'; +files.name = 'Files to move/copy/delete'; +files.help = {'These files will be moved, copied or deleted.'}; +files.filter = {'any'}; +files.ufilter = '.*'; +files.num = [0 Inf]; +% --------------------------------------------------------------------- +% moveto Move to +% --------------------------------------------------------------------- +moveto = cfg_files; +moveto.tag = 'moveto'; +moveto.name = 'Move to'; +moveto.help = {'Files will be moved to the specified directory.'}; +moveto.filter = {'dir'}; +moveto.ufilter = '.*'; +moveto.num = [1 1]; +% --------------------------------------------------------------------- +% copyto Copy to +% --------------------------------------------------------------------- +copyto = cfg_files; +copyto.tag = 'copyto'; +copyto.name = 'Copy to'; +copyto.help = {'Files will be moved to the specified directory.'}; +copyto.filter = {'dir'}; +copyto.ufilter = '.*'; +copyto.num = [1 1]; +% --------------------------------------------------------------------- +% moveto Move to +% --------------------------------------------------------------------- +moveto1 = cfg_files; +moveto1.tag = 'moveto'; +moveto1.name = 'Move to'; +moveto1.help = {'Files will be moved to the specified directory.'}; +moveto1.filter = {'dir'}; +moveto1.ufilter = '.*'; +moveto1.num = [1 1]; +% --------------------------------------------------------------------- +% pattern Pattern +% --------------------------------------------------------------------- +pattern = cfg_entry; +pattern.tag = 'pattern'; +pattern.name = 'Pattern'; +pattern.help = {'The regular expression pattern to look for.'}; +pattern.strtype = 's'; +pattern.num = [1 Inf]; +% --------------------------------------------------------------------- +% repl Replacement +% --------------------------------------------------------------------- +repl = cfg_entry; +repl.tag = 'repl'; +repl.name = 'Replacement'; +repl.help = {'This string (or pattern) will be inserted instead.'}; +repl.strtype = 's'; +repl.num = [1 Inf]; +% --------------------------------------------------------------------- +% patrep Pattern/Replacement Pair +% --------------------------------------------------------------------- +patrep = cfg_branch; +patrep.tag = 'patrep'; +patrep.name = 'Pattern/Replacement Pair'; +patrep.val = {pattern repl }; +% --------------------------------------------------------------------- +% patreplist Pattern/Replacement List +% --------------------------------------------------------------------- +patreplist = cfg_repeat; +patreplist.tag = 'patreplist'; +patreplist.name = 'Pattern/Replacement List'; +patreplist.help = {'Regexprep supports a list of multiple patterns and corresponding replacements. These will be applied to the filename portion (without path, without extension) one after another. E.g., if your filename is ''testimage(.nii)'', and you replace ''test'' with ''xyz'' and ''xyzim'' with ''newtestim'', the final filename will be ''newtestimage.nii''.'}; +patreplist.values = {patrep }; +patreplist.num = [1 Inf]; +% --------------------------------------------------------------------- +% unique Unique Filenames +% --------------------------------------------------------------------- +unique = cfg_menu; +unique.tag = 'unique'; +unique.name = 'Unique Filenames'; +unique.help = { + 'If the regexprep operation results in identical output filenames for two or more input files, these can not be written/renamed to their new location without loosing data. If you are sure that your regexprep patterns produce unique filenames, you do not need to care about this.' + 'If you choose to append a running number, it will be zero-padded to make sure alphabetical sort of filenames returns them in the same order as the input files are.' + }'; +unique.labels = { + 'Don''t Care' + 'Append Index Number' + }'; +unique.values = { + false + true + }'; +% --------------------------------------------------------------------- +% moveren Move and Rename +% --------------------------------------------------------------------- +moveren = cfg_branch; +moveren.tag = 'moveren'; +moveren.name = 'Move and Rename'; +moveren.val = {moveto1 patreplist unique }; +moveren.help = {'The input files will be moved to the specified target folder. In addition, their filenames (not paths, not extensions) will be changed by replacing regular expression patterns using MATLABs regexprep function. Please consult MATLAB help and HTML documentation for how to specify regular expressions.'}; + +ren = cfg_branch; +ren.tag = 'ren'; +ren.name = 'Rename'; +ren.val = {patreplist unique }; +ren.help = {'The input files will be moved to the specified target folder. In addition, their filenames (not paths, not extensions) will be changed by replacing regular expression patterns using MATLABs regexprep function. Please consult MATLAB help and HTML documentation for how to specify regular expressions.'}; + + +% --------------------------------------------------------------------- +% copyto Copy to +% --------------------------------------------------------------------- +copyto1 = cfg_files; +copyto1.tag = 'copyto'; +copyto1.name = 'Copy to'; +copyto1.help = {'Files will be moved to the specified directory.'}; +copyto1.filter = {'dir'}; +copyto1.ufilter = '.*'; +copyto1.num = [1 1]; +% --------------------------------------------------------------------- +% pattern Pattern +% --------------------------------------------------------------------- +pattern = cfg_entry; +pattern.tag = 'pattern'; +pattern.name = 'Pattern'; +pattern.help = {'The regular expression pattern to look for.'}; +pattern.strtype = 's'; +pattern.num = [1 Inf]; +% --------------------------------------------------------------------- +% repl Replacement +% --------------------------------------------------------------------- +repl = cfg_entry; +repl.tag = 'repl'; +repl.name = 'Replacement'; +repl.help = {'This string (or pattern) will be inserted instead.'}; +repl.strtype = 's'; +repl.num = [1 Inf]; +% --------------------------------------------------------------------- +% patrep Pattern/Replacement Pair +% --------------------------------------------------------------------- +patrep = cfg_branch; +patrep.tag = 'patrep'; +patrep.name = 'Pattern/Replacement Pair'; +patrep.val = {pattern repl }; +% --------------------------------------------------------------------- +% patreplist Pattern/Replacement List +% --------------------------------------------------------------------- +patreplist = cfg_repeat; +patreplist.tag = 'patreplist'; +patreplist.name = 'Pattern/Replacement List'; +patreplist.help = {'Regexprep supports a list of multiple patterns and corresponding replacements. These will be applied to the filename portion (without path, without extension) one after another. E.g., if your filename is ''testimage(.nii)'', and you replace ''test'' with ''xyz'' and ''xyzim'' with ''newtestim'', the final filename will be ''newtestimage.nii''.'}; +patreplist.values = {patrep }; +patreplist.num = [1 Inf]; +% --------------------------------------------------------------------- +% unique Unique Filenames +% --------------------------------------------------------------------- +unique = cfg_menu; +unique.tag = 'unique'; +unique.name = 'Unique Filenames'; +unique.help = { + 'If the regexprep operation results in identical output filenames for two or more input files, these can not be written/renamed to their new location without loosing data. If you are sure that your regexprep patterns produce unique filenames, you do not need to care about this.' + 'If you choose to append a running number, it will be zero-padded to make sure alphabetical sort of filenames returns them in the same order as the input files are.' + }'; +unique.labels = { + 'Don''t Care' + 'Append Index Number' + }'; +unique.values = { + false + true + }'; +unique.val = {false}; +% --------------------------------------------------------------------- +% copyren Copy and Rename +% --------------------------------------------------------------------- +copyren = cfg_branch; +copyren.tag = 'copyren'; +copyren.name = 'Copy and Rename'; +copyren.val = {copyto1 patreplist unique }; +copyren.help = {'The input files will be copied to the specified target folder. In addition, their filenames (not paths, not extensions) will be changed by replacing regular expression patterns using MATLABs regexprep function. Please consult MATLAB help and HTML documentation for how to specify regular expressions.'}; +% --------------------------------------------------------------------- +% delete Delete +% --------------------------------------------------------------------- +delete = cfg_const; +delete.tag = 'delete'; +delete.name = 'Delete'; +delete.val = {false}; +delete.help = {'The selected files will be deleted.'}; +% --------------------------------------------------------------------- +% action Action +% --------------------------------------------------------------------- +action = cfg_choice; +action.tag = 'action'; +action.name = 'Action'; +action.values = {moveto copyto moveren copyren ren delete }; + + +file_move = cfg_exbranch; +file_move.tag = 'file_move'; +file_move.name = 'Move/Rename/Delete Files'; +file_move.val = {files action }; +file_move.help = {'Move, rename or delete files.'}; +file_move.prog = @cat_io_file_move; +file_move.vout = @vout_file_move; + +return +%_______________________________________________________________________ +function long_report = conf_long_report(data_vol,data_xml,expert) +% ------------------------------------------------------------------------- +% Batch to create a final report of the processing of a set of files of one +% (or multiple) subject(s). +% +% RD202201: start of development for fast visualisation of longitudinal and +% test-retest data +% ------------------------------------------------------------------------- + data_vol.name = 'Volume Data Files'; + data_vol.num = [0 Inf]; + data_vol.val{1} = {''}; + + data_surf = cfg_files; + data_surf.tag = 'data_surf'; + data_surf.name = '(Left) Surface Data Files'; + data_surf.filter = 'any'; + data_surf.ufilter = 'lh.(?!cent|pial|white|sphe|defe|hull|pbt).*'; + data_surf.num = [0 Inf]; + data_surf.help = {'Surface data files. Both sides will be processed'}; + data_surf.val{1} = {''}; + + avg_vol = data_vol; + avg_vol.tag = 'avg_vol'; + avg_vol.name = 'Volume Average Data File (In Development)'; % ###### not implemented yet ###### + avg_vol.num = [0 1]; + avg_vol.help = {'Segmentation of an average volume T1 to estimate further measures.' ''}; + avg_vol.val{1} = {''}; + avg_vol.hidden = expert<2; + + avg_surf = data_surf; + avg_surf.tag = 'avg_vol'; + avg_surf.name = '(Left) Surface Average Data File (In Development)'; % ###### not implemented yet ###### + avg_surf.num = [0 1]; + avg_surf.help = {'Surface/thickness of an average volume T1 to estimate further measures.' ''}; + avg_surf.val{1} = {''}; + avg_surf.hidden = expert<2; + + % selected automatically ... need further controlling routines for covariance analysis + xmls = data_xml; + xmls.name = 'XML Data Files (In Development)'; % ###### not implemented yet ###### + xmls.hidden = expert<2; + + timepoints = cfg_entry; + timepoints.tag = 'timepoints'; + timepoints.name = 'Timepoints (In Development)'; % ###### not implemented yet ###### + timepoints.help = {'Define difference between timepoints in years. '}; + timepoints.strtype = 'r'; + timepoints.num = [0 inf]; + timepoints.val = {[]}; + timepoints.hidden = expert<2; + + + % == options == + smoothvol = cfg_entry; + smoothvol.tag = 'smoothvol'; + smoothvol.name = 'Volumetric Smoothing'; + smoothvol.help = {'FWHM of volumetric smoothing in mm.'}; + smoothvol.strtype = 'r'; + smoothvol.num = [1 1]; + smoothvol.val = {3}; + + smoothsurf = cfg_entry; + smoothsurf.tag = 'smoothsurf'; + smoothsurf.name = 'Thickness Smoothing'; + smoothsurf.help = {'Amount of surface-based smoothing in mm'}; + smoothsurf.strtype = 'r'; + smoothsurf.num = [1 1]; + smoothsurf.val = {12}; + + midpoint = cfg_menu; + midpoint.tag = 'midpoint'; + midpoint.name = 'Scaling (In Development)'; % ###### not implemented yet ###### + midpoint.labels = { + 'first image' + 'mean' + }; + midpoint.values = {0;1}; + midpoint.val = {0}; + midpoint.help = {'Data scaling by first image or by mean value. ' ''}; + midpoint.hidden = expert<2; + + boxplot = cfg_menu; + boxplot.tag = 'boxplot'; + boxplot.name = 'Boxplot (In Development)'; % ###### not implemented yet ###### + boxplot.labels = { + 'no' + 'yes' + }; + boxplot.values = {0;1}; + boxplot.val = {0}; + boxplot.help = {'Use boxplots.' ''}; + boxplot.hidden = expert < 2; + + plotGMWM = cfg_menu; + plotGMWM.tag = 'plotGMWM'; + plotGMWM.name = 'Plot WM and GM in one figure'; % ###### not implemented yet ###### + plotGMWM.labels = { + 'no' + 'yes' + }; + plotGMWM.values = {0;1}; + plotGMWM.val = {1}; + plotGMWM.help = {'Plot WM and GM in one figure. ' ''}; + plotGMWM.hidden = expert < 2; + + opts = cfg_exbranch; + opts.tag = 'opts'; + opts.name = 'Options'; + opts.val = {smoothvol smoothsurf midpoint plotGMWM}; + opts.help = {'Specify some processing options.' ''}; + opts.hidden = expert<1; + + % == output == + vols = cfg_menu; + vols.tag = 'vols'; + vols.name = 'Difference Maps'; + vols.labels = {'No';'Yes'}; + vols.values = {0,1}; + vols.val = {0}; + vols.help = {'Write difference volume maps.' ''}; + + surfs = cfg_menu; + surfs.tag = 'surfs'; + surfs.name = 'Difference Surfaces Data Files'; + surfs.labels = {'No';'Yes'}; + surfs.values = {0,1}; + surfs.val = {0}; + surfs.help = {'Write difference surface data files.' ''}; + + xml = cfg_menu; + xml.tag = 'xml'; + xml.name = 'XML'; + xml.labels = {'No';'Yes'}; + xml.values = {0,1}; + xml.val = {1}; + xml.help = {'Write combined XML file.' ''}; + + output = cfg_exbranch; + output.tag = 'output'; + output.name = 'Write Output Data'; + output.val = {vols surfs xml}; + output.help = {'Specify output data.' ''}; + output.hidden = expert<1; + + printlong = cfg_menu; + printlong.tag = 'printlong'; + printlong.name = 'Create CAT long report'; + printlong.labels = {'No','Yes (volume only)','Yes (volume and surfaces)'}; + printlong.values = {0 1 2}; + printlong.def = @(val)cat_get_defaults('extopts.print', val{:}); + printlong.help = { + 'Create final longitudinal CAT report that requires Java.' + }; + + + % == main == + long_report = cfg_exbranch; + long_report.tag = 'long_report'; + long_report.name = 'Longitudinal Report'; + if expert + long_report.val = {data_vol avg_vol data_surf avg_surf xmls timepoints opts output printlong}; + else + long_report.val = {data_vol data_surf}; + end + long_report.prog = @cat_long_report; + %long_report.vout = @vout_long_report; + long_report.hidden = expert<1; + long_report.help = { + }; +return +%_______________________________________________________________________ +function xml2csv = conf_io_xml2csv(outdir) +% ------------------------------------------------------------------------- +% Read structures/XML-files and export and transform it to a table/CSV-file +% +% RD202304 +% ------------------------------------------------------------------------- + + % n-files, e.g. XML for direct extraction or nii/gii as selector + files = cfg_files; + files.num = [1 Inf]; + files.tag = 'files'; + files.name = 'XML files'; + files.filter = 'any'; + files.ufilter = '^cat.*\.xml$'; + files.val = {{''}}; + files.help = {'Select XML files of one type (e.g., ""cat_"", ""catROI_"" or ""catROIs""). '}; + + % filename + fname = cfg_entry; + fname.tag = 'fname'; + fname.name = 'Filename'; + fname.strtype = 's'; + fname.num = [1 inf]; + fname.val = {'CATxml.csv'}; + fname.help = {'CSV filename.' }; + + % expert output options + % fieldnames + fieldnames = cfg_entry; + fieldnames.tag = 'fieldnames'; + fieldnames.name = 'Included fieldnames'; + fieldnames.strtype = 's+'; + fieldnames.val = {{' '}}; + fieldnames.num = [0 inf]; + fieldnames.help = { + 'Define keywords or complete fields to limit the extraction (empty = include all), i.e. only fields that inlclude these strings are used. ' + 'In case of catROI-files you can limit the extraction to specific atlas, regions, or tissues. ' + 'In case of cat-files you can limit the extraction to specific parameters (""opts"" or ""extopts"") or QC ratings (""qualityratings""). ' + '' + }; + + % avoidfields + avoidfields = cfg_entry; + avoidfields.tag = 'avoidfields'; + avoidfields.name = 'Excluded fieldnames'; + avoidfields.strtype = 's+'; + avoidfields.val = {{''}}; + avoidfields.num = [0 inf]; + avoidfields.help = { + 'Define keywords or complete fields that should be avoided/excluded (empty = exclude none), i.e. fields that inlclude such strings even they were included before. ' + 'In case of catROI-files you can limit the extraction to specific atlas, regions, or tissues. ' + 'In case of cat-files you can limit the extraction to specific parameters or measures. ' + '' + }; + + + report = cfg_menu; + report.tag = 'report'; + report.name = 'CAT XML export field sets'; + report.labels = {'default','only processing parameters','no processing parameters'}; + report.values = {'default','paraonly' ,'nopara' }; + report.val = {'default'}; + report.help = {'Predefined sets of CAT XML values in case of ""cat_"" processing XML files (no effect in other XMLs). '}; + + + xml2csv = cfg_exbranch; + xml2csv.tag = 'xml2csv'; + xml2csv.name = 'XML2CSV'; + xml2csv.val = {files fname outdir fieldnames avoidfields report}; + xml2csv.prog = @cat_io_xml2csv; + %xml2csv.vout = @vout_long_report; + xml2csv.help = { + 'Export XML files (e.g. the cat preprocessing results or catROI-files) as a CSV table. ' + }; + +return +%_______________________________________________________________________ +function [getCSVXML,getXML,getCSV] = cat_cfg_getCSVXML(outdir,expert) +% ------------------------------------------------------------------------- +% Batch to read out of XML/CSV data and export as batch dependency/file. +% +% RD202104 +% ------------------------------------------------------------------------- + + % n-files, e.g. XML for direct extraction or nii/gii as selector + files = cfg_files; + files.num = [0 Inf]; + files.tag = 'files'; + files.name = 'XML files'; + files.filter = 'any'; + files.ufilter = '^cat_.*\.xml$'; + files.val = {{''}}; + files.help = {'Select XML files of subjects those XML/CSV data should be extracted. '}; + + % 0..1-file ... maybe n later + csvfile = cfg_files; + csvfile.num = [0 1]; + csvfile.tag = 'csvfile'; + csvfile.name = 'CSV file'; + csvfile.filter = 'any'; + csvfile.ufilter = '.*\.(csv|tsv)$'; + csvfile.val = {{''}}; + csvfile.help = { + ['Select one CSV/TSV file that contains further information, e.g. age or sex. The first line has to be the header with the name of the variables. ' ... + 'The first row has to include an unique identifier for the selected subjects files give above, e.g. the subject ID, the filename, or path if the filename is not unique. ' ... + 'For instance, a file IXI_IOP_493 can be identified by the subject ID 493 given in the IXI CSV/TSV table. ' ... + 'However, filenames in BIDS are not suited for identification and you has to specify the ""Path/filename selector"" to select the directory entry that include the ID. '] + '' + }; + + + +% ------------------------------------------------------------------------- +% general definition +% ------------------------------------------------------------------------- + % set of variables names for extraction ... preselection TIV IQR ... + % the variables were extracted and a depency for each created + % The CSV selection is a bit more tricky. + fields = cfg_entry; + fields.tag = 'fields'; + fields.name = 'XML and CSV/TSV fieldnames'; + fields.strtype = 's+'; + fields.num = [0 inf]; + fields.val = {{''}}; +% fields.hidden = expert < 2; + fields.help = { + ['Enter (part of) the fieldnames (XML) or columns names (CSV/TSV) or column numbers (positve to select or negative values as final deselection). ' ... + 'The fieldnames (XML) or headerentries (CSV/TSV) are used to create the dependency objects and will be converted to variables. ' ... + 'The CSV/TSV columns have to have unique names and non-standard characters are replaces. '] + ['To extract one value of a matrix or cell field of an XML fiedl use the matlab specification, e.g., ' ... + 'to extract the GM value from ""subjectmeasures.vol_CGW"" use ""subjectmeasures.vol_CGW(2)"".' ] + '' + 'Enter one field per row (what creates a cellstr), e.g.:' + ' AGE' + ' SEX_ID_(1=m,2=f)' + ' subjectmeasures.vol_TIV' + ' subjectmeasures.vol_abs_CGW(2)' + ' 1' + '' + }; + +% ------------------------------------------------------------------------- +% +% ------------------------------------------------------------------------- + + + xmlsets = cfg_menu; + xmlsets.tag = 'xmlsets'; + xmlsets.name = 'CAT XML export field sets'; + %if expert + xmlsets.labels = {'default','expert','developer','full'}; + xmlsets.values = {'default','expert','developer','full'}; + %else + % xmlsets.labels = {'default','expert','developer'}; + % xmlsets.values = {'default','expert','developer'}; + %end + xmlsets.val = {'default'}; + xmlsets.help = {'Predefined sets of CAT XML parameters. '}; + + + + % ------ + csvdelkom = cfg_menu; + csvdelkom.tag = 'seg'; + csvdelkom.name = 'CSV/TSV delimiter and comma'; + csvdelkom.labels = {',.',';,',';.',' ,',' .','t.','t,'}; % ... space/tab? ' ,',' .' + csvdelkom.values = {',.',';,',';.',' ,',' .','t.','t.'}; + csvdelkom.val = {',.'}; + csvdelkom.hidden = expert < 2; + csvdelkom.help = {'Delimiter and comma in the CSV/TSV file. '}; + + write = cfg_menu; + write.tag = 'write'; + write.name = 'Writing options'; + write.labels = {'tables','text','all','none'}; % ... space/tab? ' ,',' .' + write.values = {{'csv','tsv','mat'}, {'txt'}, {'csv','tsv','mat','txt'}, {''}}; + write.val = {{'csv','tsv','mat'}}; + write.help = {'Writing of different outputs as tables, as csv, tsv, and mat files, and/or as single vector/column as text file. '}; + + fname = cfg_entry; + fname.tag = 'fname'; + fname.name = 'Write outputs file name'; + fname.strtype = 's'; + fname.val = {'_nf_nl'}; + fname.num = [1 inf]; + fname.help = { + 'Name to write output files with , , and as keywords to use the original file name, the number of fields, and number of subjects. ' + '' + }; + + + csvid = cfg_entry; + csvid.tag = 'csvIDfd'; + csvid.name = 'Subpath selector'; + csvid.strtype = 'w'; + csvid.num = [0 inf]; + csvid.val = {[]}; + csvid.help = { + ['Because the filename (=0 or []) does not allways defines the subject ID you can select another directory of the file path. ' ... + 'E.g., for the file "".../myProject/GROUP/SUB01/TP01/T1w/001.nii"" you have to define the 3rd ancestor (=3), ' ... + 'whereas "".../myProject/GROUP/SUB01/TP01/T1w/report/catxml_001.xml"" would require the 4th ancestor (=4). '] + '' + }; + + filesel = cfg_entry; + filesel.tag = 'filesel'; + filesel.name = 'Filepart selector'; + filesel.help = {'Limitation of x-axis. '}; + filesel.strtype = 'w'; + filesel.num = [0 inf]; + filesel.val = {[]}; + filesel.help = {'Specify a part of the filename, e.g. by 1 to select ""IXI002"" from ""IXI002-Guys-0815-T1.nii"". No intput uses the full filename. Two inputs can ' }; + + fileseps = cfg_entry; + fileseps.tag = 'fileseps'; + fileseps.name = 'Filename seperators'; + fileseps.strtype = 's'; + fileseps.val = {'_-.'}; + fileseps.num = [0 inf]; + fileseps.help = { + 'Seperators used within the filename. E.g. to select ""IXI002"" from ""IXI002-Guys-0815-T1.nii"" by defining also the ID filename selector with ""1"". ' + }; + + % path filename varialbes ? + % pathsel + filesel + name + % filenameselector + name = cfg_entry; + name.tag = 'name'; + name.name = 'Field / variable name'; + name.strtype = 's'; + name.val = {}; + name.num = [1 inf]; + name.help = { + 'Select a unique name for the variable / field.'}; + + fnamefield = cfg_exbranch; + fnamefield.tag = 'fnamefields'; + fnamefield.name = 'Filename field'; + fnamefield.val = {csvid filesel fileseps name}; + fnamefield.help = {'' ''}; + + fnamefields = cfg_repeat; + fnamefields.tag = 'fnamefields'; + fnamefields.name = 'Filename fields'; + fnamefields.values = {fnamefield}; + fnamefields.val = {}; + fnamefields.num = [0 Inf]; + fnamefields.hidden = expert < 2; + %fnamefields.forcestruct = 0; + fnamefields.help = {'Selectors to define the subject ID by a given path/filename, e.g., the IXI filename also include a site ID and weighting: ""IXI002-Guys-0815-T1.nii'}; + + % ############ improve help + idselector = cfg_exbranch; + idselector.tag = 'idselector'; + idselector.name = 'ID filename selector'; + idselector.val = {csvid filesel fileseps}; + idselector.help = {'Selectors to define the subject ID by a given path/filename, e.g., the IXI filename also include a site ID and weighting: ""IXI002-Guys-0815-T1.nii'}; + + + %{ + csvid = cfg_entry; + csvid.tag = 'csvIDfd'; + csvid.name = 'Subpath selector'; + csvid.strtype = 'w'; + csvid.num = [0 inf]; + csvid.val = {[]}; + csvid.help = { + ['Because the filename (=0 or []) does not allways defines the subject ID you can select another directory of the file path. ' ... + 'E.g., for the file "".../myProject/GROUP/SUB01/TP01/T1w/001.nii"" you have to define the 3rd ancestor (=3), ' ... + 'whereas "".../myProject/GROUP/SUB01/TP01/T1w/report/catxml_001.xml"" would require the 4th ancestor (=4). '] + '' + }; + %} + csvIDcol = cfg_entry; + csvIDcol.tag = 'csvIDcol'; + csvIDcol.name = 'CSV column ID selector'; + csvIDcol.strtype = 'w'; + csvIDcol.num = [1 1]; + csvIDcol.val = {1}; + csvIDcol.help = {''}; + + csvselcol = cfg_entry; + csvselcol.tag = 'csvselcol'; + csvselcol.name = 'CSV selector column'; + csvselcol.strtype = 'w'; + csvselcol.num = [1 1]; + csvselcol.val = {0}; + csvselcol.help = {'Define the number of a column to select (=1) and unselect/skip (=0 or empty) rows. If the setting is 0 then all rows are used. ' ''}; + + verb = cfg_menu; + verb.tag = 'verb'; + verb.name = 'Verbose output'; + verb.labels = {'No' 'Yes' 'Yes (Details)'}; + verb.values = {0 1 2}; + verb.val = {1}; + %verb.hidden = expert<1; + verb.help = { + 'Be more or less verbose. ' + '' + }; + + + % this is the general batch that is still in development + getCSVXML = cfg_exbranch; + getCSVXML.tag = 'getCSVXML'; + getCSVXML.name = 'XML/CSV readout'; + if expert + getCSVXML.val = {files csvfile xmlsets csvIDcol fields fnamefields idselector fname outdir write verb}; % xmlfields + else + getCSVXML.val = {files csvfile xmlsets fname outdir write verb}; + end + getCSVXML.prog = @cat_stat_getCSVXMLfield; + getCSVXML.vout = @vout_stat_getCSVXML; + getCSVXML.hidden = expert < 2; + getCSVXML.help = { + 'This batch allows to extract XML and CSV/TSV entries and filename-parts for a given list of a subset of (processed) files to use the in statistical models. ' + '' % XML block + ['The XML extraction of the CAT*.xml allows for instance to extract informations from the CAT prepcrocessing, such as global volumes, image quality ratings or preprocessing setting, ' ... + 'You need to select the processed files that define the used subjects, e.g. the ""catxml_*.xml"" or the ""lh.thickness.*.gii"" files or the original images. ' ... + 'Moreover, specific atlas regions can be extracted from CAT atlas XML files. '] % is this useful ? Use a predefined batch for it, eg. by automaticly analyse the CSV atlas files + '' % CSV block + ['Many databases use CSV files to store information such as ""IXI_ID; SEX_ID; HEIGHT; WEIGHT; ...; AGE"" for the IXI dataset. ' ... + 'You also need to select the delimiter type of the CSV/TSV file and specify how to distinguish the part of the filename that contains the subject ID (this must be the first column in the CSV file) and the fieldnames (e.g. ""SEX_ID"" or ""AGE"").'] + '' % FILE selector block ? + 'You can write the results into a text file or you can use the DEPENDENCY function of the SPM batches by choosing the column-wise output vectors. ' + '' + 'Problems can occure if the ID is not fully unique, i.e. if a ID (e.g. 1) is part of another ID (e.g. 101), or if an ID is used multiple times. ' + }; + + % simplified XML batch + getXML = cfg_exbranch; + getXML.tag = 'getXML'; + getXML.name = 'XML readout'; + getXML.val = {files xmlsets fields fname outdir write verb}; + getXML.prog = @cat_stat_getCSVXMLfield; + getXML.vout = @vout_stat_getCSVXML; + getXML.help = { + 'This batch allows to extract XML data fields from a set of files that can be saved as CSV/TSV/TXT files or used as matlabbatch dependencies, e.g., for statistical models. ' + }; + + % simplified CSV batch + % + selector for columns (data)? > hmm this could be given by a number/columnstr (e.g., AA=27) + % but it is only relevant in huge files to avoid long deps list + % + selector for rows (subject)? > no, critical to match it but it could be useful to specify one column as a selctor + getCSV = cfg_exbranch; + getCSV.tag = 'getCSV'; + getCSV.name = 'CSV readout'; + getCSV.val = {csvfile csvselcol fields fname outdir write verb}; + getCSV.prog = @cat_stat_getCSVXMLfield; + getCSV.vout = @vout_stat_getCSVXML; + getCSV.help = { + 'This batch allows to extract columns from one CSV/TSV file that can be saved as CSV/TSV/TXT files or as matlabbatch dependencies, e.g., for statistical models. ' + }; +return + +%_______________________________________________________________________ +function resize = conf_vol_resize(data,prefix,expert,outdir) +% ------------------------------------------------------------------------- +% Simple function to resize and scale images. +% +% RD202005 +% ------------------------------------------------------------------------- + + + % developer with matrix values + res = cfg_entry; + res.tag = 'res'; + res.name = 'Resolution'; + res.strtype = 'r'; + res.num = [1 inf]; + res.val = {1}; + res.help = { + ['Voxel resolution in mm. For isotropocic resolution you can enter 1 value (e.g., 1.2 for 1.2x1.2x1.2 mm' char(179) ... + '), otherwise you have to specify all 3 dimensions. '] + }; + + % this is a special expert case + scale = cfg_entry; + scale.tag = 'scale'; + scale.name = 'Scaling'; + scale.strtype = 'r'; + scale.num = [1 inf]; + scale.val = {1}; + scale.hidden = expert<2; + scale.help = { + 'Scaling to resize the object by changing the voxel size. A value of 0.5 for instance will half the xyz scale of the object. ' + }; + + % trim data (increase or decrease boundary box) + trim = cfg_entry; + trim.tag = 'trim'; + trim.name = 'Trimming'; + trim.strtype = 'r'; + trim.num = [1 6]; + trim.val = {[0 0 0 0 0 0]}; + trim.hidden = expert<2; + trim.help = { + 'Change boundary box by adding (positive values) or removing (negative values) voxel on each side (-x,+x,-y,+y,-z,+z). ' + }; + + + % use header to resample to + Pref = data; + Pref.tag = 'Pref'; + Pref.name = 'Alternative image space'; + Pref.num = [1 1]; + Pref.val = {''}; % this is not working + Pref.help = {[ + 'Alternative output space to resample to another image. ' ... + 'Leave empty to use space of input image. ' ... + 'Set voxel resolution to 0 to use the resolution of this image. ']}; + + % main setting + restype = cfg_choice; + restype.tag = 'restype'; + restype.name = 'Operation'; + restype.values = {res,Pref,scale,trim}; + restype.val = {res}; + restype.help = {'The images can be resize to (i) a specific resolution and (ii) to the space of another images (like in ImCalc). '}; + if ~scale.hidden + restype.help = [ restype.help; {'Moreover, the data of the volume can be rescaled, e.g., to adopt template data for other species. The images are not resliced in this case. '}]; + end + + % imcalc interpolation field + imcalc = spm_cfg_imcalc; + if isa(imcalc.val,'function_handle') + imcalc.val = feval(imcalc.val); + end + method = imcalc.val{6}.val{3}; + if expert>1 + % extended version with additional filtering filtering + % there are different levels available (FWHM size) but I want to keep it simple + method.labels{9} = 'Trilinear (with smooth downsampling)'; + method.values{9} = -2001; + method.labels{10} = '5th Degree Sinc (with light smooth downsampling)'; + method.values{10} = -2005; + method.help = [ method.help'; { ' Trilinear / 5th Degree Sinc (with smooth downsampling)'; ' - If image dimensions are downsampled, prior Gaussian filtering allows denoising and simulation of the partial volume effect. The FWHM can be defined as the ratio of the new to the original voxel size: vx_vol_org ./ vx_vol_org - 1. E.g. an image of 0.2x0.2x0.5 mm downsampled to 0.5x0.5x0.5 mm supports smoothing with FWHM=[3 3 0], which reduces noise along the downsampled axis. '; ''}]; + end + clear imcalc + + prefix.val = {'r'}; + prefix.help = { + 'Use ""auto"" to add resolution automatically, e.g., ""r0.8_*.nii"" for final resolution or ""rx0.5_*.nii"" for the scaling parameter. ' + 'If you want the original resolution use 0 in the resolution setting (autoprefix ""rorg_"") or 1 in the scaling setting. ' + }; + resize = cfg_exbranch; + resize.tag = 'resize'; + resize.name = 'Resize images'; + resize.val = {data,restype,method,prefix,outdir}; + resize.prog = @cat_vol_resize; + resize.vfiles = @vout_resize; + resize.vout = @vout_resize; + resize.help = {'Interpolation of images.' ''}; +return + +%_______________________________________________________________________ +function shootlong = conf_shoot(expert) +% ------------------------------------------------------------------------- +% This is slightly modified version of the original Shooting that allows to +% specify another default file. It is required to remove slight movements of +% between scans in longidudinal data. +% Although this is a general batch it is here defined as a private function +% called only from the CAT longidudinal batch. +% +% RD202005 +% ------------------------------------------------------------------------- + + % get shooting toolbox definition + shoot = tbx_cfg_shoot; + + % find the create template batch + FN = cell(1,numel(shoot.values)); for fni=1:numel( shoot.values ), FN{fni} = shoot.values{fni}.name; end + fi = find(cellfun('isempty',strfind(FN,'Run Shooting (create Templates)'))==0,1); + + % field to select an m-file with similar to shooting defaults. + dfile = cfg_files; + dfile.tag = 'dfile'; + dfile.name = 'Shooting default file'; + dfile.filter = 'm'; + dfile.ufilter = '.*'; + dfile.num = [0 1]; + dfile.val = {{''}}; + dfile.help = {'Select one Shooting default matlab m-file. If empty Shooting ""spm_shoot_defaults"" is used. '}; + + % creat new version + shootlong = shoot.values{fi}; + shootlong.prog = @cat_spm_shoot_template; + shootlong.hidden = expert<2; + shootlong.val = [shootlong.val {dfile}]; + +return + +%_______________________________________________________________________ +function createTPM = conf_createTPM(data,expert,name,outdir) +% ------------------------------------------------------------------------- +% Batch to create own templates based on a Shooting template or a CAT pre- +% processing +% +% RD202005 +% ------------------------------------------------------------------------- + + % Shooting template input files + tfiles = data; + tfiles.tag = 'tfiles'; + tfiles.name = 'First spatial registration template'; + tfiles.help = {'Select all Dartel/Shooting template volumes, i.e., you have to select in general 6 Dartel or 5 Shooting template volumes. ' ''}; + tfiles.ufilter = '^Template.*'; + tfiles.num = [1 Inf]; + + % local intensity normalized T1 input images + mfiles = data; + mfiles.tag = 'mfiles'; + mfiles.name = 'Normalized tissue maps'; + mfiles.help = {[ ... + 'Select the averaged normalized tissue volumes. ' ... + 'Use ""CAT Apply Deformation"" or ""SPM Deformation"" tools to apply the mapping of Dartel/Shooting ' ... + 'to map all tissue maps from the individual to the template space. ' ... + 'Next, use cat_vol_avg to average each tissue class. ' ... + 'Use CAT expert mode to write all tissue classes p1 to p6 to native space (use the TPM output field for p4-6) and correct WMHs to WM (WMHC=3). ' ... + 'If this field is empty the template tissues are use to simulate a T1 image. ' '']}; + mfiles.ufilter = '.*'; + mfiles.val = {''}; + mfiles.num = [0 Inf]; + + % normalized tissue maps + pfiles = data; + pfiles.tag = 'pfiles'; + pfiles.name = 'Normalized intensity maps'; + pfiles.help = {[ + 'Select all normalized tissue volumes. ' ... + 'Use ""CAT Apply Deformation"" or ""SPM Deformation"" tools to apply the mapping of Dartel/Shooting ' ... + 'to map all local intensity normalized T1 maps from the individual to the template space. ' ... + 'Next use cat_vol_avg to average all images. ' ... + 'Use CAT expert mode to write the local intensity normalized maps in native space. ' ... + 'If this field is empty the template tissues are use instead. ' '']}; + pfiles.ufilter = '.*'; + pfiles.val = {''}; + pfiles.num = [0 Inf]; + + % atlas maps + afiles = data; + afiles.tag = 'afiles'; + afiles.name = 'Atlas maps'; + afiles.help = {[ + 'Select all atlas maps in native space usually written in the label directory. ' ... + 'Use ""CAT Apply Deformation"" or ""SPM Deformation"" tools to apply the mapping of Dartel/Shooting ' ... + 'to map all individual atlas maps from the individual to the template space. ' ... + 'Next use cat_vol_avg to average all images with discrete interpolation. ' ... + 'Use CAT expert mode to write out selected volume atlases maps into native space. ' ... + 'If this field is empty no atlas files are generated and no Template is generated. '] + }; + afiles.ufilter = '.*'; + afiles.val = {''}; + afiles.num = [0 Inf]; + + logfile = data; + logfile.tag = 'logfile'; + logfile.name = 'Log/report file'; + logfile.help = {'Select a file where the report is added at the end. '}; + logfile.ufilter = '.*'; + logfile.val = {''}; + logfile.num = [0 1]; + + % input files + files = cfg_branch; + files.tag = 'files'; + files.name = 'Files'; + files.val = {tfiles pfiles mfiles afiles logfile}; + files.help = {'Define input files. All images has to be in the same space having the same resolution. ' ''}; + + + + % options + fstrength = cfg_menu; + fstrength.tag = 'fstrength'; + fstrength.name = 'Filter strength'; + fstrength.labels = {'small' 'medium' 'strong'}; + fstrength.values = {2 3 4}; + fstrength.val = {2}; + fstrength.help = {'Main filter control parameter with 3 levels. ' ''}; + + + % trimming? > main batch (= boundary box optimization) + % resolution? > main batch + + + % name + name.tag = 'name'; + name.name = 'Template name'; + name.val = {'MyTemplate'}; + + % verb + verb = cfg_menu; + verb.tag = 'verb'; + verb.name = 'Verbose output'; + verb.labels = {'No' 'Yes'}; + verb.values = {0 1}; + verb.val = {1}; + verb.help = {'Be verbose.' ''}; + + % input files + opt = cfg_branch; + opt.tag = 'opt'; + opt.name = 'Options'; + opt.val = {fstrength,name,outdir,verb,}; + opt.help = {'Main options.' ''}; + + % verb + verb = cfg_menu; + verb.tag = 'verb'; + verb.name = 'Verbose output'; + verb.labels = {'No' 'Yes'}; + verb.values = {0 1}; + verb.val = {1}; + verb.help = {'Be verbose.' ''}; + + + %{ + def.write.name = 'MyTemplate'; % template name + def.write.outdir = ''; % main output directory + def.write.subdir = ''; % create sub directory + def.write.TPM = 1; % write TPM + def.write.TPMc = 1; % write seperate TPM classes + def.write.TPM4 = 1; % write 4 class TPM + def.write.TPM4c = 1; % write seperate 4 class TPM + def.write.T1 = 1; % write T1 + def.write.T2 = 1; % write T2 + def.write.GS = 1; % write Shooting template + def.write.DT = 1; % create and write Dartel template + job.write.brainmask = 1; % write brainmask + %} + + % input files + write = cfg_branch; + write.tag = 'write'; + write.name = 'Output'; + write.val = {}; + write.help = {'' ''}; + + % main + createTPM = cfg_exbranch; + createTPM.tag = 'createTPMlong'; + createTPM.name = 'TPM creation'; + createTPM.val = {files, opt, write}; + createTPM.prog = @cat_vol_createTPM; + createTPM.vfiles = @vout_createTPM; + createTPM.vout = @vout_createTPM; + createTPM.hidden = expert<2; + createTPM.help = { + 'Create individual TPMs for preprocessing by using Dartel/Shooting templates. ' + ['SPM uses TPMs with 6 tissue classes (GM,WM,CSF,HD1,HD2,BG), whereas the head classes (HD) can be empty. ' ... + 'However, the affine normalized or a soft non-linear normalized space is expected to obtain best result (see options in cat_main_registration). ' ... + 'A resolution of 1.5 mm seems to be quite optimal as far as we have to smooth anyway. ' ... + 'The images will be filtered in different ways to allow soft meanderings of anatomical structures. ' ... + 'WMHs should probably be corrected to WM (WMHC=2) in the average preprocessing.' ] + ''}; +return + +%_______________________________________________________________________ +function createTPMlong = conf_createTPMlong(data,expert) +% ------------------------------------------------------------------------- +% This is a special version of the cat_vol_createTPM batch only for the +% longitudinal preprocessing without further GUI interaction and well +% defined input. +% +% RD202005 +% ------------------------------------------------------------------------- + + % update input + data.tag = 'files'; + data.name = 'GM segments'; + data.help = {'Select GM segments. The other tissue classes (2-6) will be selected automaticelly. '}; + + fstrength = cfg_menu; + fstrength.tag = 'fstrength'; + fstrength.name = 'Filtermodel'; + fstrength.labels = { + 'very small (plasticity)' + 'small (plasticty/aging)' + 'medium (aging/development)' + 'strong (development)'}; + fstrength.values = {1 2 3 4}; + fstrength.val = {1}; + fstrength.help = { + ['Main filter control parameter with 4 settings, (1) very small for variations in plasticity, ' ... + '(2) small for changes in pasticity/short time aging, (3) medium for changes in long-time aging '... + 'and short-time development, and (3) strong for large variations in long-time development. '] + '' + }; + + verb = cfg_menu; + verb.tag = 'verb'; + verb.name = 'Verbose output'; + verb.labels = {'No' 'Yes'}; + verb.values = {0 1}; + verb.val = {1}; + verb.help = { + 'Be verbose.' + '' + }; + + writeBM = cfg_menu; + writeBM.tag = 'writeBM'; + writeBM.name = 'Write brainmask'; + writeBM.labels = {'No' 'Yes'}; + writeBM.values = {0 1}; + writeBM.val = {1}; + writeBM.help = { + 'Save brainmask image.' + '' + }; + + % main + createTPMlong = cfg_exbranch; + createTPMlong.tag = 'createTPMlong'; + createTPMlong.name = 'Longitudinal TPM creation'; + createTPMlong.val = {data,fstrength,writeBM,verb}; + createTPMlong.prog = @cat_long_createTPM; + createTPMlong.vfiles = @vout_createTPMlong; + createTPMlong.vout = @vout_createTPMlong; + createTPMlong.hidden = expert<1; + createTPMlong.help = { + 'Create individual TPMs for longitudinal preprocessing. This is a special version of the cat_vol_createTPM batch only for the longitudinal preprocessing without further GUI interaction and well defined input. ' + ['There has to be 6 tissue classes images (GM,WM,CSF,HD1,HD2,BG) that can be in the native space, the affine or a non-linear normalized space. ' ... + 'However, the affine normalized or a soft non-linear normalized space is expected to give the best result (see options in cat_main_registration). ' ... + 'A resolution of 1.5 mm seems to be quite optimal as far as we have to smooth anyway. ' ... + 'The images will be filtered in different ways to allow soft meanderings of anatomical structures. ' ... + 'WMHs should probably be corrected to WM (WMHC=2) in the average preprocessing.' ] + ''}; +return + +%_______________________________________________________________________ +function iqr = conf_stat_IQR(data_xml) +% ------------------------------------------------------------------------ + iqr_name = cfg_entry; + iqr_name.tag = 'iqr_name'; + iqr_name.name = 'Output file'; + iqr_name.strtype = 's'; + iqr_name.num = [1 Inf]; + iqr_name.val = {'IQR.txt'}; + iqr_name.help = {'The output file is written to current working directory unless a valid full pathname is given'}; + + iqr = cfg_exbranch; + iqr.tag = 'iqr'; + iqr.name = 'Get Weighted Overall Image Quality'; + iqr.val = {data_xml,iqr_name}; + iqr.prog = @cat_stat_IQR; + iqr.help = {'This function reads weighted overall image quality from saved xml-files.' ''}; +return + +%_______________________________________________________________________ +function longBiasCorr = conf_longBiasCorr(data,expert,prefix) +% ------------------------------------------------------------------------- +% Longitudinal bias correction by using the average segmentation. +% See cat_long_biascorr. +% +% RD202010: First tests showed clear improvements of the timepoints but the +% whole pipeline seems to be less affected. +% Hence, corrections are maybe more relevant for plasticity +% studies or in case of artifacts. +% ------------------------------------------------------------------------- + + images = data; + images.tag = 'images'; + images.name = 'Realigned images of one subject'; + images.num = [1 inf]; + + segment = data; + segment.tag = 'segment'; + segment.num = [1 1]; + segment.name = 'Average tissue segmentation of one subject'; + + bstr = cfg_menu; + bstr.tag = 'str'; + bstr.name = 'Strength of correction'; + bstr.labels = {'no correction','small','medium','strong','very strong'}; + bstr.values = {0,0.25,0.5,0.75,1.0}; + bstr.val = {0.5}; + bstr.help = { + 'Strength of bias correction.' + '' + }; + + longBiasCorr = cfg_exbranch; + longBiasCorr.tag = 'longBiasCorr'; + longBiasCorr.name = 'Longitudinal Bias Correction'; + longBiasCorr.val = {images,segment,bstr,prefix}; + longBiasCorr.prog = @cat_long_biascorr; + longBiasCorr.vout = @vout_conf_longBiasCorr; + longBiasCorr.hidden = expert<0; + longBiasCorr.help = {'Bias correction based on the segmentation of the average map.' ''}; +return + +%_______________________________________________________________________ +function qa = conf_vol_qa(expert,outdir) +% Batch for estimation of image quality by a given input segmentation. +% There was the idea of a relative common batch that allows to use a wide +% set of maps to allow personal adaptions, e.g., to measure in background +% regions or to use atlas maps for region-specific results. However, this +% becomes quite complex and would focus on experts that have so specific +% knowledge that they better write there own code. +% So I try to keep it simple here to support our image quality measures +% also for other tissue segmentation, e.g. by SPM, FSL, FreeSurfer. + + % update input + data = cfg_files; + data.tag = 'images'; + data.name = 'Images'; + data.help = {'Select images that should be evaluated.'}; + data.filter = 'any'; + data.ufilter = '.*.nii'; + data.num = [1 Inf]; + + catlab = data; + catlab.ufilter = '^p0.*'; + catlab.tag = 'catp0'; + catlab.name = 'Default with CAT label map'; + catlab.help = {['Select CAT label map with brain tissues (p0*.nii). Also label maps created by other tissue segmentations can be used, ' ... + 'as long the following labeling is used: CSF=1, GM=2, and WM=3 with optinal intermediate PVE values (e.g., 2.32 for 68% GM and 32% WM). ']}; + catlab.num = [0 Inf]; + catlab.filter = 'any'; + catlab.ufilter = '.*.nii'; + + catsegp = data; + catsegp.ufilter = '^p1.*'; + catsegp.tag = 'catp1'; + catsegp.name = 'Default with CAT segment maps'; + catsegp.help = {'Select corresponing CAT GM tissue segments of the selected images above (p1*.nii). The WM and CSF maps were selected automatically. ' ''}; + + spmsegc = data; + spmsegc.ufilter = '^c1.*'; + spmsegc.tag = 'spmc1'; + spmsegc.name = 'Default with SPM segment maps'; + spmsegc.help = {'Select corresponing individual SPM GM tissue segments of the selected images above (c1*.nii). The WM and CSF maps were selected automatically. ' ''}; + + % segmentation in general + gm = data; + gm.tag = 'gm'; + gm.name = 'GM segment'; + gm.help = {'Select images with GM segmentation. ' ''}; + wm = data; + wm.tag = 'wm'; + wm.name = 'WM segment'; + wm.help = {'Select images with WM segmentation. ' ''}; + cm = data; + cm.tag = 'cm'; + cm.name = 'CSF segment'; + cm.help = {'Select images with CSF segmentation. ' ''}; + seg = cfg_exbranch; + seg.tag = 'seg'; + seg.name = 'Brain tissue segmentation'; + seg.help = {'Select tissue segments of other segmentations' ''}; + seg.val = {gm,wm,cm}; + +% other posible cases +% - FSL segment maps +% - FS label map, DL maps + + model = cfg_choice; + model.tag = 'model'; + model.name = 'Segmentation input'; + if expert > 0 + model.values = {catlab,catsegp,spmsegc,seg}; + else + model.values = {catlab,spmsegc}; + end + model.val = {catlab}; + model.help = {[ ... + 'Select input segmentations in the same image space as the original images for estimation of quality measures/ratings. ' ... + 'The default model is developed for typcial structural T1/T2/PD-based images with a given brain tissue classification. ']}; + + + % main options + % ----------------------------------------------------------------------- + prefix = cfg_entry; + prefix.tag = 'prefix'; + prefix.name = 'Filename prefix'; + prefix.strtype = 's'; + prefix.num = [0 Inf]; + if expert + prefix.val = {'VERSION_'}; + prefix.help = {'Specify the string to be prepended to the filenames of the XML file(s), where VERSION is replaced by the selected QA file without underlines (eg. ""catvolqc201901_""). ' ''}; + else + prefix.val = {'qce_'}; + prefix.help = {'Specify the string to be prepended to the filenames of the XML file(s). ' ''}; + end +% ############## automatic replacement ? + + version = cfg_menu; + version.tag = 'version'; + version.name = 'Version'; + version.help = { + ['Select different versions of QC processing. ' ... + 'The first version 201602 was quite stable with small bugfixes until the version 201901. ' ... + 'Light corrections result then in version 202110 and later version 202205. ' ... + 'Extensive tests result in a stronger modified version 202310 that was finally stable for ' ... + '(i) the brain web phantom, (ii) preprocessing error simulation, (iii) IXI (aging), ' ... + '(iv) ATLAS (lesions), (v) MR-ART (motion artificats), (vi) private motion data. '] + '' + }; + if expert > 1 + version.labels = {'202412 (expertimental with own simple segmentation)', ... + '202310', '202110x (reworked 202310)','201901x (reworked 202310, default)', ... + '202205', '202110', '201901','201602'}; + version.values = {'cat_vol_qa202412', ... + 'cat_vol_qa202310', 'cat_vol_qa202110x', 'cat_vol_qa201901x', ... + 'cat_vol_qa202205', 'cat_vol_qa202110', 'cat_vol_qa201901', 'cat_vol_qa201602'}; + version.help = [ version.help , { + ['The developer GUI further supports updated versions (cat_vol_qa#x) of 201901 and 202110 ' ... + 'that included corrections for the differnet test cases and result finally in the cat_vol_qa202310. ' ... + 'All functions uses the cat_vol_qa for basic loading of variables that may inlcude further differences to the fully orginal version. '] + '' + }]; + else + version.labels = {'201901x (reworked, default)', '202310', '202205', '202110', '201901', '201602'}; + version.values = {'cat_vol_qa201901x', 'cat_vol_qa202310', 'cat_vol_qa202205', 'cat_vol_qa202110', 'cat_vol_qa201901', 'cat_vol_qa201602'}; + end + % remove undefined cases + for vi = numel(version.values):-1:1 + if ~exist(version.values{vi},'file') + version.values(vi) = []; + version.labels(vi) = []; + end + end + version.val = {'cat_vol_qa201901x'}; + version.hidden = expert<1; + + rerun = cfg_menu; + rerun.tag = 'rerun'; + rerun.name = 'Force reprocessing in case of existing results'; + rerun.labels = {'Yes','No'}; + rerun.values = {2,0}; + rerun.val = {2}; + rerun.hidden = expert<2; + rerun.help = { + 'Do not process data if the resulting xml/mat files already exists. ' + }; + + verb = cfg_menu; + verb.tag = 'verb'; + verb.name = 'Print results'; + verb.labels = {'no' 'yes'}; + verb.values = {0 2 }; + verb.val = {2}; + verb.help = {'Print progress and results. ';''}; + + writecsv = cfg_menu; + verb.tag = 'verb'; + verb.name = 'Print results'; + verb.labels = {'no' 'yes'}; + verb.values = {0 2 }; + verb.val = {2}; + verb.help = {'Print progress and results. ';''}; + + + outdir.val{1} = {'report'}; + outdir.help = {'Create sub-directory within the main directory.'}; +% could be confusing ... writes into the current report directory (defined by mri from the preprocessing) + + opts = cfg_branch; + opts.tag = 'opts'; + opts.name = 'Options'; + opts.val = {version, prefix, verb , rerun }; % outdir, + opts.help = {'Basic options. ' ''}; + + % main + qa = cfg_exbranch; + qa.tag = 'iqe'; + qa.name = 'Image quality estimation'; + qa.val = {data, model, opts}; + qa.prog = @cat_vol_qa; + qa.vfiles = @vout_qa; % XML files + values + qa.help = {'Image quality estimation based on a set of images and their segmentation maps. '}; +return + +%_______________________________________________________________________ +function [sanlm,sanlm2] = conf_vol_sanlm(data,intlim,spm_type,prefix,suffix,lazy,expert) + + % --- update input variables --- + data.help = {'Select images for filtering.'}; + + prefix.val = {'sanlm_'}; + prefix.help = { + 'Specify the string to be prepended to the filenames of the filtered image file(s). Default prefix is ""samlm_"". Use the keyword ""PARA"" to add the name of the filter, e.g., ""classic"" or ""optimized-medium"".' + '' + }; + if expert>1 + prefix.help = { + 'Specify the string to be prepended to the filenames of the filtered image file(s). Default prefix is ""samlm_"". Use the keyword ""PARA"" to add the strength of filtering, e.g. ""sanlm_PARA"" result in ""sanlm_NC#_*.nii"".' + '' + }; + suffix.val = {''}; + suffix.help = { + 'Specify the string to be appended to the filenames of the filtered image file(s). Default suffix is ''''. Use the keyword ""PARA"" to add the name of the filter, e.g., ""classic"" or ""optimized-medium"".' + '' + }; + end + + + % --- new fields --- + rician = cfg_menu; + rician.tag = 'rician'; + rician.name = 'Rician noise'; + rician.labels = {'Yes' 'No'}; + rician.values = {1 0}; + rician.val = {0}; + rician.help = { + 'MRIs can have Gaussian or Rician distributed noise with uniform or nonuniform variance across the image. If SNR is high enough (>3) noise can be well approximated by Gaussian noise in the foreground. However, for SENSE reconstruction or DTI data a Rician distribution is expected. Please note that the Rician noise estimation is sensitive for large signals in the neighbourhood and can lead to artefacts, e.g. cortex can be affected by very high values in the scalp or in blood vessels.' + '' + }; + + % remove artifacts + outlier = cfg_entry; + outlier.tag = 'outlier'; + outlier.name = 'Strength of outlier correction'; + outlier.strtype = 'r'; + outlier.num = [1 1]; + outlier.val = {1}; + outlier.help = { + 'Remove strong outliers (salt and pepper noise) with more than n times of the average local correction strength. Larger values will result in stronger corrections, whereas lower values result in less corrections. Changes will be more visible in high quality areas/images.' + }; + + % developer with matrix values + NCstr = cfg_entry; + NCstr.tag = 'NCstr'; + NCstr.name = 'Strength of noise corrections'; + NCstr.strtype = 'r'; + NCstr.num = [1 1]; %inf]; % this case did not work with yet + NCstr.def = @(val) cat_get_defaults('extopts.NCstr', val{:}); + NCstr.hidden = expert<1; + NCstr.help = { + ['Strength of the spatial adaptive (sub-resolution) non-local means (SANLM) noise correction. Please note that the filter strength is automatically estimated. Change this parameter only for specific conditions. ' ... + 'Typical values are: none (0), classic (1), light (2), medium (3|-inf), strong (4), heavy (5). The ""classic"" option use the ordinal SANLM filter without further adaptations. The ""light"" option uses the half filter strength of ""medium"" cases. The ""strong"" option use 8-times of the ""medium"" filter strength. Sub-resolution filtering is only used in case of high image resolution below 0.8 mm or in case of the ""heavy"" option. ' ... + 'For the global modified scheme use smaller values (>0) for less denoising, higher values (<=1) for stronger denoising, and ""inf"" for an automatic estimated threshold. Negative values control the local adaptive scheme, with the default ""-inf""|""-1"", that successfully tested on a variety of scans. Use higher values (>-1,<0) for less filtering and lower values ""<-1"" for stronger filtering. The value 0 will turn off any noise correction.'] + '' + }; + + % noise correction level + NCstrm = cfg_menu; + NCstrm.tag = 'NCstr'; + NCstrm.name = 'Strength of Noise Corrections'; + NCstrm.def = @(val) cat_get_defaults('extopts.NCstr', val{:}); + NCstrm.help = { + ['Strength of the (sub-resolution) spatial adaptive non local means (SANLM) noise correction. Please note that the filter strength is automatically estimated. Change this parameter only for specific conditions. ' ... + 'The ""light"" option applies half of the filter strength of the adaptive ""medium"" cases, whereas the ""strong"" option uses the full filter strength, force sub-resolution filtering and applies an additional iteration. Sub-resolution filtering is only used in case of high image resolution below 0.8 mm or in case of the ""strong"" option.'] + ['If you have scans with low amount of noise then use the ""light"" option. If you have data that was resampled or interpolated in some way (i.e., even within scanning/reconstruction) then the noise is often blurred over multiple voxels and has to be handled on lower resolutions available for the try the ""strong"" or ""heavy"" filter setting.' ... + 'If you have multiple scans that should be averaged than you should use the "".. for average"" filter settings.'] + 'The filter will always leave some low amount of noise in the data that is assumed by preprocessing routines such as the tissue classification with its Gaussian fitting.' + '' + }; + if expert + NCstrm.values = {2 -inf 4 5 12 14}; + NCstrm.labels = {'light (adapted half strength; 2)','medium (adapted; default; -1|3|-inf)','strong (low-resolution filtering; 4)','heavy (low-resolution filtering with 2 iterations; 5)','light for averaging (adapted half strength; 12)','strong for averaging (low-resolution filtering; 14)',}; + else + NCstrm.values = {2 -inf 4 5}; + NCstrm.labels = {'light','medium (default)','strong','heavy'}; + end + + addnoise = cfg_entry; + addnoise.tag = 'addnoise'; + addnoise.name = 'Strength of additional noise in noise-free regions'; + addnoise.strtype = 'r'; + addnoise.val = {0.5}; + addnoise.num = [1 1]; + addnoise.help = { + 'Add minimal amount of noise in regions without any noise to avoid image segmentation problems. This parameter defines the strength of additional noise as percentage of the average signal intensity. ' + '' + }; + + replaceNANandINF = cfg_menu; + replaceNANandINF.tag = 'replaceNANandINF'; + replaceNANandINF.name = 'Replace NAN and INF'; + replaceNANandINF.labels = {'Yes' 'No'}; + replaceNANandINF.values = {1 0}; + replaceNANandINF.val = {1}; + replaceNANandINF.help = { + 'Replace NAN by 0, -INF by the minimum and INF by the maximum of the image.' + '' + }; + + % relative value vs. on/off + if expert + relativeFilterStengthLimit = cfg_entry; + relativeFilterStengthLimit.tag = 'relativeFilterStengthLimit'; + relativeFilterStengthLimit.name = 'Factor of relative filter strength limit'; + relativeFilterStengthLimit.strtype = 'r'; + relativeFilterStengthLimit.num = [1 1]; + relativeFilterStengthLimit.val = {1}; + relativeFilterStengthLimit.hidden = expert<2; + relativeFilterStengthLimit.help = { + 'Limit the relative noise correction to avoid over-filtering of low intensity areas. Low values will lead to less filtering in low intensity areas, whereas high values will be closer to the original filter. INF deactivates the filter. ' + '' + }; + else + relativeFilterStengthLimit = cfg_menu; + relativeFilterStengthLimit.tag = 'relativeFilterStengthLimit'; + relativeFilterStengthLimit.name = 'Use relative filter strength'; + relativeFilterStengthLimit.labels = {'Yes' 'No'}; + relativeFilterStengthLimit.values = {1 0}; + relativeFilterStengthLimit.val = {1}; + relativeFilterStengthLimit.hidden = expert<2; + relativeFilterStengthLimit.help = { + 'Limit the relative noise correction to avoid over-filtering of low intensities areas.' + '' + }; + end + + relativeIntensityAdaption = cfg_entry; + relativeIntensityAdaption.tag = 'relativeIntensityAdaption'; + relativeIntensityAdaption.name = 'Strength of relative intensity adaptation'; + relativeIntensityAdaption.strtype = 'r'; + relativeIntensityAdaption.num = [1 1]; + relativeIntensityAdaption.val = {1}; + relativeIntensityAdaption.hidden = expert<2; + relativeIntensityAdaption.help = { + 'Strength of relative intensity adaptation, with 0 for no adaptation and 1 for full adaptation. The SANLM filter is often very successful in the background and removed nearly all noise. However, routines such as the SPM Unified Segmentation expect Gaussian distribution in all regions and is troubled by regions with too low variance. Hence, a relative limitation of SANLM correction is added here that is based on the bias reduced image intensity. ' + '' + }; + + % very special parameter ... + % ----------------------------------------------------------------------- + iter = cfg_entry; + iter.tag = 'iter'; + iter.name = 'Number of additional sub-resolution iterations'; + iter.strtype = 'r'; + iter.num = [1 1]; + iter.val = {0}; + iter.hidden = expert<1; + iter.help = { + 'Choose number of additional iterations that can further reduce sub-resolution noise but also anatomical information, e.g. larger blood vessel or small gyri/sulci.' + '' + }; + + iterm = cfg_entry; + iterm.tag = 'iterm'; + iterm.name = 'Number of additional iterations'; + iterm.strtype = 'r'; + iterm.num = [1 1]; + iterm.val = {0}; + iterm.hidden = expert<1; + iterm.help = { + 'Choose number of additional iterations that can further reduce noise but also anatomical information, e.g. smaller blood-vessels.' + '' + }; + + relativeIntensityAdaptionTH = cfg_entry; + relativeIntensityAdaptionTH.tag = 'relativeIntensityAdaptionTH'; + relativeIntensityAdaptionTH.name = 'Strength of smoothing of the relative filter strength limit'; + relativeIntensityAdaptionTH.strtype = 'r'; + relativeIntensityAdaptionTH.num = [1 1]; + relativeIntensityAdaptionTH.val = {2}; + relativeIntensityAdaptionTH.hidden = expert<2; + relativeIntensityAdaptionTH.help = { + 'Smoothing of the relative filter strength limitation.' + '' + }; + + resolutionDependency = cfg_menu; + resolutionDependency.tag = 'resolutionDependency'; + resolutionDependency.name = 'Resolution depended filtering'; + resolutionDependency.labels = {'Yes' 'No'}; + resolutionDependency.values = {1 0}; + resolutionDependency.val = {0}; + resolutionDependency.hidden = expert<2; + resolutionDependency.help = { + 'Resolution depending filtering with reduced filter strength in data with low spatial resolution defined by the ""Range of resolution dependency"".' + '' + }; + + resolutionDependencyRange = cfg_entry; + resolutionDependencyRange.tag = 'resolutionDependencyRange'; + resolutionDependencyRange.name = 'Range of resolution dependency'; + resolutionDependencyRange.strtype = 'r'; + resolutionDependencyRange.num = [1 2]; + resolutionDependencyRange.val = {[1 2.5]}; + resolutionDependencyRange.hidden = expert<1; + resolutionDependencyRange.help = { + 'Definition of the spatial resolution for ""full filtering"" (first value) and ""no filtering"" (second value), with [1 2.5] for typical structural data of humans. ' + '' + }; + + resolutionReduction = cfg_menu; + resolutionReduction.tag = 'red'; + resolutionReduction.name = 'Low resolution filtering'; + resolutionReduction.labels = {'Yes (allways)' 'Yes (only highres <0.8 mm)' 'No'}; + resolutionReduction.values = {11 1 0}; + resolutionReduction.val = {0}; + %resolutionReduction.hidden = expert<1; + resolutionReduction.help = { + 'Some MR images were interpolated or use a limited frequency spectrum to support higher spatial resolution with acceptable scan-times (e.g., 0.5x0.5x1.5 mm on a 1.5 Tesla scanner). However, this can result in ""low-frequency"" noise that can not be handled by the standard NLM-filter. Hence, an additional filtering step is used on a reduces resolution. As far as filtering of low resolution data will also remove anatomical information the filter use by default maximal one reduction with a resolution limit of 1.6 mm. I.e. a 0.5x0.5x1.5 mm image is reduced to 1.0x1.0x1.5 mm, whereas a 0.8x0.8x0.4 mm images is reduced to 0.8x0.8x0.8 mm and a 1x1x1 mm dataset is not reduced at all. ' + '' + }; + + verb = cfg_menu; + verb.tag = 'verb'; + verb.name = 'Verbose output'; + verb.labels = {'No' 'Yes'}; + verb.values = {0 1}; + verb.val = {1}; + verb.hidden = expert<1; + verb.help = { + 'Be verbose.' + '' + }; + + sharpening = cfg_entry; + sharpening.tag = 'sharpening'; + sharpening.name = 'Sharpening'; + sharpening.strtype = 'r'; + sharpening.num = [1 1]; + sharpening.val = {1}; + sharpening.hidden = expert<2; + sharpening.help = { + 'By smoothing heavily noisy areas, fine structures and local contrasts such as cerebellar sublobuli can disappear. The effect is similar to a real photo of a meadow at night and short exposure time (e.g., with a lot of noise), where the denoising filter merges everything into one large smooth area. The sharpening tries to preserve local contrasts. ' + 'Sharpening is only applied in case of the optimized filters.' + '' + }; + + % ----------------------------------------------------------------------- + + + + + nlm_default = cfg_branch; + nlm_default.tag = 'classic'; + nlm_default.name = 'Classic SANLM filter'; + nlm_default.val = {}; + nlm_default.help = { + 'Classical SANLM filter without further adaptations, i.e. strong filtering on the full resolution.' + }; + + nlm_optimized = cfg_branch; + nlm_optimized.tag = 'optimized'; + nlm_optimized.name = 'Optimized filter'; + nlm_optimized.val = {NCstrm}; + nlm_optimized.help = { + 'Optimized SANLM filter with predefined parameter settings.' + }; + + nlm_expert = cfg_branch; + nlm_expert.tag = 'expert'; + nlm_expert.name = 'Optimized filter (expert options)'; + nlm_expert.hidden = expert<0; + nlm_expert.val = {NCstr iter iterm outlier addnoise relativeIntensityAdaption relativeIntensityAdaptionTH relativeFilterStengthLimit resolutionDependency resolutionDependencyRange resolutionReduction lazy}; + nlm_expert.help = { + 'Optimized SANLM filter with all parameters.' + }; + + nlmfilter = cfg_choice; + nlmfilter.tag = 'nlmfilter'; + nlmfilter.name = 'Filter type'; + if expert + nlmfilter.values = {nlm_default nlm_optimized nlm_expert}; + else + nlmfilter.values = {nlm_default nlm_optimized}; + end + nlmfilter.val = {nlm_optimized}; + if expert + nlmfilter.help = { + 'Selection between the classical SANLM filter and an optimized SANLM filter with predefined settings or detailed parameterization. The classic filter is often too strong in normal data that was not interpolated or resampled and the default CAT12 preprocessing uses the medium optimized version. ' + '' + }; + else + nlmfilter.help = { + 'Selection between the classical SANLM filter and an optimized SANLM filter. The classic filter is often too strong in normal data that was not interpolated or resampled and the default CAT12 preprocessing uses the medium optimized version. ' + '' + }; + end + + % V1 + sanlm = cfg_exbranch; + sanlm.tag = 'sanlm'; + sanlm.name = 'Spatially adaptive non-local means (SANLM) denoising filter'; + + intlim.hidden = expert<2; + + sanlm.val = {data spm_type prefix suffix intlim rician replaceNANandINF nlmfilter}; + sanlm.prog = @cat_vol_sanlm; + sanlm.vout = @vout_sanlm; + sanlm.help = { + 'This function applies an spatial adaptive (sub-resolution) non-local means denoising filter to the data. This filter will remove noise while preserving edges. The filter strength is automatically estimated based on the standard deviation of the noise. ' + '' + 'This filter is internally used in the segmentation procedure anyway. Thus, it is not necessary (and not recommended) to apply the filter before segmentation.' + '' + }; + + % V2 + sanlm2 = sanlm; + sanlm2.tag = 'sanlm2'; + sanlm2.name = 'Spatially adaptive non-local means (SANLM) denoising filter V2'; + sanlm2.val = {data spm_type prefix suffix intlim rician sharpening replaceNANandINF nlmfilter}; + sanlm2.prog = @cat_vol_sanlm2; + sanlm2.hidden = expert<2; + +return + +%_______________________________________________________________________ +function spmtype = conf_io_volctype(data, intlim, spm_type,prefix,suffix,verb,expert,lazy) + % update variables + data.help = {'Select images for data type conversion';''}; + + intlim.tag = 'range'; + intlim.num = [1 inf]; + + prefix.val = {'PARA'}; + prefix.help = { + 'Specify the string to be prepended to the filenames of the converted image file(s). Default prefix is ""PARA"" that is replaced by the chosen datatype.' + '' + }; + + suffix.hidden = expert<2; + suffix.help = { + 'Specify the string to be prepended to the filenames of the converted image file(s). Default prefix is ''''. Use ""PARA"" to add the datatype to the filename.' + '' + }; + + spm_type.labels(1) = []; % remove native case + spm_type.values(1) = []; % remove native case + spm_type.tag = 'ctype'; + + lazy.hidden = expert<1; + verb.hidden = expert<1; + + intscale = cfg_menu; + intscale.name = 'Intensity scaling'; + intscale.tag = 'intscale'; + if expert>1 + intscale.labels = {'No (round in case of integer)','Yes (0:1)','Yes (-1:1)','Yes (0:max)','Yes (min:max)', 'Yes (0:256)'}; + intscale.values = {0,1,-1,inf,-inf,2}; + else + intscale.labels = {'No (round in case of integer)','Yes (0:1)','Yes (-1:1)','Yes (0:max)','Yes (min:max)'}; + intscale.values = {0,1,-1,inf,-inf}; + end + intscale.val = {1}; + intscale.help = {'Normalize image intensities in range between (i) 0 and 1 (0:1) or (ii) between -1 and 1 (-1:1) balanced around zero, i.e., the absoluted values are ranged betweed 0 and 1. '}; + + % new + spmtype = cfg_exbranch; + spmtype.tag = 'spmtype'; + spmtype.name = 'Image data type converter'; + spmtype.val = {data prefix suffix intlim spm_type intscale verb lazy}; + spmtype.prog = @cat_io_volctype; + spmtype.vout = @vout_volctype; + spmtype.help = { + 'Convert the image data type to reduce disk-space.' + 'Uses 99.99% of the main intensity histogram to avoid problems due to outliers. Although the internal scaling supports a relative high accuracy for the limited number of bits, special values such as NAN and INF will be lost!' + '' + }; +return + +%_______________________________________________________________________ +function headtrimming = conf_vol_headtrimming(intlim,spm_type,prefix,suffix,verb,lazy,expert) + + suffix.hidden = expert<1; + intlim.hidden = expert<1; + lazy.hidden = expert<1; + lazy.val = {1}; + intlim.num = [1 inf]; + + % update input variables + intlim1 = intlim; + intlim1.tag = 'intlim1'; + intlim1.name = 'Global intensity limitation for masking'; + intlim1.val = {90}; + intlim1.hidden = expert<1; + intlim1.num = [1 Inf]; + intlim1.help = {'General intensity limitation to remove strong outliers by using 90% of the original histogram values. Too high values will include background noise and do not allow trimming, whereas to low values will cut objects with low values (e.g. by image inhomogeneities). ' ''}; + + prefix.val = {'trimmed_'}; + + intscale = cfg_menu; + intscale.name = 'Intensity scaling'; + intscale.tag = 'intscale'; + intscale.labels = {'No','Yes','Yes (force positive values)'}; + intscale.values = {0,1,3}; + intscale.val = {0}; + intscale.help = {'Normalize image intensities in range between 0 and 1 (unsigned integer or forced scaling option) or -1 to 1 (signed integer / float). '}; + + + % many subjects + simages = cfg_files; + simages.tag = 'simages'; + simages.name = 'Source images'; + simages.help = {'Select images for trimming (e.g. T1 images).' ''}; + simages.filter = 'image'; + simages.ufilter = '.*'; + simages.num = [1 Inf]; + + images1 = cfg_files; + images1.tag = 'oimages'; + images1.name = 'Images'; + images1.help = {'Select other images that should be trimmed similar to the source images (e.g. coregistrated images).' ''}; + images1.filter = 'image'; + images1.ufilter = '.*'; + images1.num = [1 Inf]; + + oimages = cfg_repeat; + oimages.tag = 'oimages'; + oimages.name = 'Other images'; + oimages.help = {'Select other images that should be trimmed similar to the source images. For example, the source images are a set of T1 images, whereas the second set may be a set of coregistered images of the same subjects with the same image dimensions.' ''}; + oimages.values = {images1}; + oimages.val = {}; + oimages.num = [0 Inf]; + + manysubjects = cfg_branch; + manysubjects.tag = 'manysubjects'; + manysubjects.name = 'Many subjects'; + manysubjects.val = {simages oimages}; + manysubjects.help = { + 'Create stacks of images of one class that include the same number of many subjects:' + ' { {S1T1, S2T1,...} {S1T2, S2T2, ...} ... }' + '' + }; + + % manyimages + subjectimages = cfg_files; + subjectimages.tag = 'subjectimages'; + subjectimages.name = 'Subject'; + subjectimages.help = { + 'Select all images of one subject that are in the same space and should be trimmed together.' + }; + if expert + subjectimages.help = [ subjectimages.help; { + 'The first image is used to estimate the trimming. ' + '' + }]; + else + subjectimages.help = [ subjectimages.help; { + 'In general the first image is used to estimate the trimming (see ""Average images"" option). ' + '' + }]; + end + subjectimages.filter = 'image'; + subjectimages.ufilter = '.*'; + subjectimages.num = [1 Inf]; + + manyimages = cfg_repeat; + manyimages.tag = 'manyimages'; + manyimages.name = 'Many images'; + manyimages.help = { + 'Collect images of each subject that should be trimmed together and are in the same space.' + ' { {S1T1, S1T2,...} {S2T1, S2T2, ...} {S2T1, S2T2 } ... }' + ''}; + manyimages.values = {subjectimages}; + manyimages.val = {}; + manyimages.num = [1 Inf]; + + % image selection type + timages = cfg_choice; + timages.tag = 'image_selector'; + timages.name = 'Select type of image selection'; + timages.values = {manyimages manysubjects}; + timages.val = {manyimages}; + timages.help = { + 'Select ""many images"" if you have a small number of subjects with a VARYING number of images.' + 'Select ""many subjects"" if you have a large number of subject with the SAME number of images.' + }; + + + pth = cfg_entry; + pth.tag = 'pth'; + pth.name = 'Percentual trimming threshold'; + pth.strtype = 'r'; + pth.num = [1 1]; + pth.val = {0.4}; + pth.help = {'Percentual treshold for trimming. Lower values will result in a wider mask, ie. more air, whereas higher values will remove more air but maybe also brain regions with very low intensity.' ''}; + + open = cfg_entry; + open.tag = 'open'; + open.name = 'Size of morphological opening of the mask'; + open.strtype = 'w'; + open.num = [1 1]; + open.val = {2}; + open.hidden = expert<1; + open.help = {'The morphological opening of the mask allows to avoid problems due to noise in the background. However, too large opening will also remove the skull or parts of the brain.' ''}; + + addvox = cfg_entry; + addvox.tag = 'addvox'; + addvox.name = 'Add voxels around mask'; + addvox.strtype = 'w'; + addvox.num = [1 1]; + addvox.val = {2}; + addvox.hidden = expert<1; + addvox.help = {'Add # voxels around the original mask to avoid to hard masking.' ''}; + + mask = cfg_menu; + mask.name = 'Final masking with source image'; + mask.tag = 'mask'; + mask.labels = {'Yes','No'}; + mask.values = {1,0}; + mask.val = {1}; + mask.hidden = false; % expert < 1; % the field is important if multiple images are used and the first one is skull-stripped + % but this stripping/masking should not applied to the other images + mask.help = {'Use source image for trimming and final masking (e.g. for skull-stripping in longitudinal pipeline).'}; + + + % don't change data type + spm_type.val = {0}; + spm_type.tag = 'ctype'; + % --- main --- + headtrimming = cfg_exbranch; + headtrimming.tag = 'datatrimming'; + headtrimming.name = 'Image data trimming'; + headtrimming.val = {timages prefix suffix mask intlim1 pth open addvox intlim spm_type intscale verb lazy}; + headtrimming.prog = @cat_vol_headtrimming; + headtrimming.vout = @vout_headtrimming; + headtrimming.help = { + 'Remove air around the head and convert the image data type to save disk-space but also to reduce memory-space and load/save times. Corresponding images have to have the same image dimenions. ' + 'Uses 99.99% of the main intensity histogram to avoid problems due to outliers. Although the internal scaling supports a relative high accuracy for the limited number of bits, special values such as NAN and INF will be lost!' + '' + }; +return + +%_______________________________________________________________________ +function maskimg = conf_vol_maskimage(data,prefix) + + % update input variables + data.name = 'Select images'; + data.help = {'Select images for lesion or brain masking';''}; + + prefix.val = {'msk_'}; + prefix.help = { + 'Specify the string to be prepended to the filenames of the masked image file(s).' + '' + }; + + % lesion mask + mask = data; + mask.tag = 'mask'; + mask.name = 'Select lesion mask images'; + mask.help = {'Select (additional) lesion mask images that describe the regions that should be set to zero.';''}; + mask.num = [0 Inf]; + + % brain mask + bmask = data; + bmask.tag = 'bmask'; + bmask.name = 'Optionally select additional brain mask images'; + bmask.help = {'Select (additional) brain mask images that describe the regions that should remain in the image.';''}; + bmask.num = [0 Inf]; + bmask.val = {{''}}; + + % recalc + recalc = cfg_menu; + recalc.tag = 'recalc'; + recalc.name = 'Reprocess'; + recalc.help = {'If an output image already exist then use this image rather than the original input image for additional masking. This allows you to add lesions from other lesion images.'}; + recalc.labels = {'Yes' 'No'}; + recalc.values = {1 0}; + recalc.val = {1}; + + % main + maskimg = cfg_exbranch; + maskimg.tag = 'maskimg'; + maskimg.name = 'Manual image (lesion) masking'; + maskimg.val = {data mask bmask recalc prefix}; + maskimg.prog = @cat_vol_maskimage; + maskimg.vout = @vout_maskimg; + maskimg.help = { + 'Mask images to avoid segmentation and registration errors in brain lesion. The number of mask images has to be equal to the number of the original images. Voxels inside the lesion mask(s) and outside the brainmask(s) will be set to zero. ' + 'If you have multiple lesion masks than add them with the original images, eg. ""images = {sub01.nii; sub02.nii; sub01.nii}"" and ""mask = {sub01_lesion1.nii; sub02_lesion1.nii; sub01_lesion2.nii}"". Alternatively, you can choose only one original image and a various number of mask files.' + '' + }; + +return + +%_______________________________________________________________________ +function [defs,defs2] = conf_vol_defs() + + field = cfg_files; + field.tag = 'field'; + field.name = 'Deformation Fields'; + field.filter = 'image'; + field.ufilter = '^(i)?y_.*\.nii$'; + field.num = [1 Inf]; + field.help = {[ + 'Select deformation fields for all subjects. ' ... + 'Use the ""y_*.nii"" to project data from subject to template space, and the ""iy_*.nii"" to map data from template to individual space. ' ... + 'Both deformation maps can be created in the CAT preprocessing by setting the ""Deformation Field"" flag to forward or inverse.' ... + ]}; + + field1 = cfg_files; + field1.tag = 'field1'; + field1.name = 'Deformation Field'; + field1.filter = 'image'; + field1.ufilter = '^(i)?y_.*\.nii$'; + field1.num = [1 1]; + field1.help = {[ + 'Select the deformation field of one subject.' ... + 'Use the ""y_*.nii"" to project data from subject to template space, and the ""iy_*.nii"" to map data from template to individual space.' ... + 'Both deformation maps can be created in the CAT preprocessing by setting the ""Deformation Field"" flag to forward or inverse.' ... + ]}; + + images1 = cfg_files; + images1.tag = 'images'; + images1.name = 'Images'; + images1.help = {'Select images to be warped. Note that there should be the same number of images as there are deformation fields, such that each flow field warps one image.'}; + images1.filter = 'image'; + images1.ufilter = '.*'; + images1.num = [1 Inf]; + + images = cfg_repeat; + images.tag = 'images'; + images.name = 'Images'; + images.help = {'The flow field deformations can be applied to multiple images. At this point, you choose how many images each flow field should be applied to.'}; + images.values = {images1}; + images.num = [1 Inf]; + + 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','Categorical'}; + interp.values = {0,1,2,3,4,5,6,7,-1}; + interp.val = {1}; + interp.help = { + '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.' + ' 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). Do not use B-splines when there is any region of NaN or Inf in the images. ' + ' Categorical Interpolation: - Slow (particularly when there are lots of categories). This is intended to warp categorical images such as label maps.' + }'; + + modulate = cfg_menu; + modulate.tag = 'modulate'; + modulate.name = 'Modulate image (preserve volume)'; + modulate.labels = {'No','Affine + non-linear (SPM12 default)','Non-linear only'}; + modulate.values = {0 1 2}; + modulate.val = {0}; + modulate.help = { + '""Modulation"" is to compensate for the effect of spatial normalisation. Spatial normalisation causes volume changes due to affine transformation (global scaling) and non-linear warping (local volume change). The SPM default is to adjust spatially normalised grey matter (or other tissue class) by using both terms and the resulting modulated images are preserved for the total amount of grey matter. Thus, modulated images reflect the grey matter volumes before spatial normalisation. However, the user is often interested in removing the confound of different brain sizes and there are many ways to apply this correction. We can use the total amount of GM, GM+WM, GM+WM+CSF, or manual estimated total intracranial volume (TIV). Theses parameters can be modeled as nuisance parameters (additive effects) in an AnCova model or used to globally scale the data (multiplicative effects): ' + '' + '% Correction Interpretation' + '% ---------- --------------' + '% nothing absolute volume' + '% globals relative volume after correcting for total GM or TIV (multiplicative effects)' + '% AnCova relative volume that can not be explained by total GM or TIV (additive effects)' + '' + 'Modulated images can be optionally saved by correcting for non-linear warping only. Volume changes due to affine normalisation will be not considered and this equals the use of default modulation and globally scaling data according to the inverse scaling factor due to affine normalisation. I recommend this option if your hypothesis is about effects of relative volumes which are corrected for different brain sizes. This is a widely used hypothesis and should fit to most data. The idea behind this option is that scaling of affine normalisation is indeed a multiplicative (gain) effect and we rather apply this correction to our data and not to our statistical model. These modulated images are indicated by ""m0"" instead of ""m"". ' + '' + }; + + bb = cfg_entry; + bb.tag = 'bb'; + bb.name = 'Bounding box'; + bb.help = {'The bounding box (in mm) of the volume which is to be written (relative to the anterior commissure).'}; + bb.strtype = 'r'; + bb.num = [2 3]; + bb.val = {[NaN NaN NaN; NaN NaN NaN]}; + + vox = cfg_entry; + vox.tag = 'vox'; + vox.name = 'Voxel sizes'; + vox.help = {'The voxel sizes (x, y & z, in mm) of the written normalised images.'}; + vox.strtype = 'r'; + vox.num = [1 3]; + vox.val = {[NaN NaN NaN]}; + + images1.help = {'Select images to be warped for this subject.'}; + defs = cfg_exbranch; + defs.tag = 'defs'; + defs.name = 'Apply deformations (many images)'; + defs.val = {field1,images1,bb,vox,interp,modulate}; + defs.prog = @cat_vol_defs; + defs.vfiles = @vout_defs; + defs.help = {'This is an utility for applying a deformation field of one subject to many images.'}; + + defs2 = cfg_exbranch; + defs2.tag = 'defs2'; + defs2.name = 'Apply deformations (many subjects)'; + defs2.val = {field,images,bb,vox,interp,modulate}; + defs2.prog = @cat_vol_defs; + defs2.vfiles = @vout_defs2; + defs2.help = {'This is an utility for applying deformation fields of many subjects to images.'}; +return + +%_______________________________________________________________________ +function realign = conf_vol_series_align(data,expert) + + data.help = { + 'Select all images for this subject'}; + + tim = cfg_entry; + tim.tag = 'times'; + tim.name = 'Times'; + tim.strtype = 'e'; + tim.val = {NaN}; + tim.num = [1 Inf]; + tim.help = {'Specify the times of the scans in years. If you leave the default NaN value the standard warping regularization will be used for all scans.'}; + + bparam = cfg_entry; + bparam.tag = 'bparam'; + bparam.name = 'Bias Regularisation'; + bparam.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 variations in the difference between the images that arise because of the differential bias artifact due to the physics of MR scanning, and those that arise due to shape differences. The objective is to model the latter by deformations, while modelling the former with a bias field. We know a priori that intensity variations due to MR physics tend to be spatially smooth. 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 estimates of the intensity non-uniformity.' + 'Knowing what works best should be a matter of empirical exploration, as it depends on the scans themselves. For example, if your data has very little of the 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.' + }'; + bparam.strtype = 'e'; + bparam.num = [1 1]; + bparam.val = {1e7}; + + setCOM = cfg_menu; + setCOM.tag = 'setCOM'; + setCOM.name = 'Use center-of-mass to set origin'; + setCOM.help = { ... + '' + 'Use center-of-mass to roughly correct for differences in the position between image and template. This will internally correct the origin. ' + '' + 'If affine registration fails you can try to disable this option and/or set the origin manually. ' + }; + setCOM.def = @(val) cat_get_defaults('extopts.setCOM', val{:}); + setCOM.labels = {'No','Yes'}; + setCOM.values = {0 1}; + + + wparam = cfg_entry; + wparam.tag = 'wparam'; + wparam.name = 'Warping Regularisation'; + wparam.help = { + 'Registration involves simultaneously minimising two terms. One of these is a measure of similarity between the images (mean-squared difference in the current situation), whereas the other is a measure of the roughness of the deformations. This measure of roughness involves the sum of the following terms:',... + '* Absolute displacements need to be penalised by a tiny amount. The first element encodes the amount of penalty on these. Ideally, absolute displacements should not be penalised, but it is often necessary for technical reasons.',... + '* The `membrane energy'' of the deformation is penalised (2nd element), usually by a relatively small amount. This penalises the sum of squares of the derivatives of the velocity field (ie the sum of squares of the elements of the Jacobian tensors).',... + '* The `bending energy'' is penalised (3rd element). This penalises the sum of squares of the 2nd derivatives of the velocity.',... + '* Linear elasticity regularisation is also included (4th and 5th elements). The first parameter (mu) is similar to that for linear elasticity, except it penalises the sum of squares of the Jacobian tensors after they have been made symmetric (by averaging with the transpose). This term essentially penalises length changes, without penalising rotations.',... + '* The final term also relates to linear elasticity, and is the weight that denotes how much to penalise changes to the divergence of the velocities (lambda). This divergence is a measure of the rate of volumetric expansion or contraction.',... + 'Note that regularisation is specified based on what is believed to be appropriate for a year of growth. The specified values are divided by the number of years time difference.' + }; + wparam.strtype = 'e'; + wparam.num = [1 5]; + wparam.val = {[0 0 100 25 100]}; + % Change to (eg): wparam.val = {[0 0 100 25 12]}; + + write_rimg = cfg_menu; + write_rimg.tag = 'write_rimg'; + write_rimg.name = 'Save rigidly registered images'; + write_rimg.help = {'Do you want to save the rigidly registered images? The resliced images are named the same as the originals, except that they are prefixed by ''r''.'}; + write_rimg.labels = {'Save','Dont save'}; + write_rimg.values = { 1 0 }; + write_rimg.val = {1}; + + write_avg = cfg_menu; + write_avg.tag = 'write_avg'; + write_avg.name = 'Save Mid-point average'; + write_avg.help = {'Do you want to save the mid-point average template image? This is likely to be useful for groupwise alignment, and is prefixed by ''avg_'' and written out in the same directory of the first time point data. Please note that with rigid registration a weighted median/mean is stored instead of the average image. In areas with low stdev the mean is used and in areas with larger stdev the median is more weighted.'}; + write_avg.labels = {'Save','Dont save'}; + write_avg.values = { 1 0 }; + write_avg.val = {1}; + + write_jac = cfg_menu; + write_jac.tag = 'write_jac'; + write_jac.name = 'Save Jacobians'; + write_jac.help = {'Do you want to save a map of the Jacobian determinants? Some consider these useful for morphometrics (although the divergences of the initial velocities may be preferable). Each map of Jacobians encodes the relative volume (at each spatial location) between the scan and the median time-point average. Values less than one indicate contraction (over time), whereas values greater than one indicate expansion. These files are prefixed by ``j_'''' and written out in the same directory of the first time point data.'}; + write_jac.labels = {'Save','Dont save'}; + write_jac.values = { 1 0 }; + write_jac.val = {1}; + + write_def = cfg_menu; + write_def.tag = 'write_def'; + write_def.name = 'Deformation Fields'; + write_def.help = {'Deformation fields can be saved to disk, and used by the Deformations Utility. Deformations are saved as y_*.nii files, which contain three volumes to encode the x, y and z coordinates. They are written in the same directory as the corresponding image.'}; + write_def.labels = {'Save','Dont save'}; + write_def.values = { 1 0 }; + write_def.val = {0}; + + use_brainmask = cfg_menu; + use_brainmask.name = 'Use Brainmask'; + use_brainmask.tag = 'use_brainmask'; + use_brainmask.labels = {'Yes','No'}; + use_brainmask.values = {1,0}; + use_brainmask.val = {1}; + use_brainmask.help = {'Use brainmask at last level of rigid body registration to obtain better registration by considering brain regions only.'}; + + reduce = cfg_menu; + reduce.name = 'Reduce Bounding Box'; + reduce.tag = 'reduce'; + reduce.labels = {'Yes','No'}; + reduce.values = {1,0}; + reduce.val = {1}; + reduce.help = { + 'Reduce bounding box at final resolution level because usually there is a lot of air around the head after registration of multiple scans. This helps to save memory and time for later use of these registered images.' + '' + 'Please note that this option can only be used for rigid registration and will be disabled for non-linear registration.' + }; + + nonlin = cfg_branch; + nonlin.tag = 'nonlin'; + nonlin.name = 'Non-linear registration'; + nonlin.val = {tim wparam write_jac write_def}; + nonlin.help = {''}; + + rigid = cfg_const; + rigid.tag = 'rigid'; + rigid.name = 'Rigid body registration'; + rigid.val = {1}; + rigid.help = {'Rigid registration only'}; + + reg = cfg_choice; + reg.name = 'Registration Method'; + reg.tag = 'reg'; + reg.values = {rigid nonlin}; + reg.val = {rigid}; + reg.help = {'Choose between rigid body and non-linear registration. The non-linear registration is using the methods of the Longitudinal Toolbox and is thought for data over longer periods, where the deformations can then be used to calculate local volume changes, which are then multiplied (modulated) by the segmented mean image. Rigid body registration can be used to detect more subtle effects over shorter periods of time (e.g. brain plasticity or training effects after a few weeks or even shorter times).'}; + + noise = cfg_entry; + noise.tag = 'noise'; + noise.name = 'Noise Estimate'; + noise.strtype = 'e'; + noise.num = [Inf Inf]; + noise.val = {NaN}; + noise.help = {'Specify the standard deviation of the noise in the images. If a scalar is entered, all images will be assumed to have the same level of noise. For any non-finite values, the algorithm will try to estimate the noise from fitting a mixture of two Rician distributions to the intensity histogram of each of the images, and assuming that the Rician with the smaller overall intensity models the intensity distribution of air in the background. This works reasonably well for simple MRI scans, but less well for derived images (such as averages) and it fails badly for scans that are skull-stripped. The assumption used by the registration is that the residuals, after fitting the model, are i.i.d. Gaussian. The assumed standard deviation of the residuals is derived from the estimated Rician distribution of the air.' + }; + + % parameter for other batches (eg. for averageing) + sharpen = cfg_menu; + sharpen.tag = 'sharpen'; + sharpen.name = 'Sharping (DEVELOPER)'; + sharpen.labels = {'None','Light','Strong'}; + sharpen.values = { 0 1 2 }; + sharpen.val = { 0 }; + sharpen.hidden = expert<2; + sharpen.help = {'Enhancement of local details for averaging.' + }; + + % parameter for other batches (eg. for averageing) + isores = cfg_entry; + isores.tag = 'isores'; + isores.name = 'Isotropic Resolution (EXPERT)'; + isores.help = {'Voxel sizes of the written images. Default 0 will use the minimum of the maximum resolution of all images. '}; + isores.strtype = 'r'; + isores.num = [1 1]; + isores.hidden = expert<1; + isores.val = {0}; + + realign = cfg_exbranch; + realign.tag = 'series'; + realign.name = 'Longitudinal Registration'; + realign.val = {data noise setCOM bparam use_brainmask reduce reg write_rimg write_avg isores sharpen}; + realign.help = { + 'Longitudinal registration of series of anatomical MRI scans for a single subject. It is based on inverse-consistent alignment among each of the subject''s scans, and incorporates a bias field correction. Prior to running the registration, the scans should already be in very rough alignment, although because the model incorporates a rigid-body transform, this need not be extremely precise. Note that there are a bunch of hyper-parameters to be specified. If you are unsure what values to take, then the defaults should be a reasonable guess of what works. Note that changes to these hyper-parameters will impact the results obtained.' + '' + 'The alignment assumes that all scans have similar resolutions and dimensions, and were collected on the same (or very similar) MR scanner using the same pulse sequence. If these assumption are not correct, then the approach will not work as well. There are a number of settings (noise estimate, regularisation etc). Default settings often work well, but it can be very helpful to try some different values, as these can have a large effect on the results.' + '' + 'The resliced images are named the same as the originals, except that they are prefixed by ''r''.' + }; + realign.prog = @cat_vol_series_align; + realign.vout = @vout_realign; + +return + +%_______________________________________________________________________ +function [T2x,T2x_surf,F2x,F2x_surf] = conf_T2x + + data_T2x = cfg_files; + data_T2x.tag = 'data_T2x'; + data_T2x.name = 'Data'; + data_T2x.filter = {'image'}; + data_T2x.ufilter = '^spmT.*'; + data_T2x.num = [1 Inf]; + data_T2x.help = {'Select spmT-data to transform or convert.'}; + + sel = cfg_menu; + sel.name = 'Convert t value to'; + sel.tag = 'sel'; + sel.labels = {'p','-log(p)','correlation coefficient r (only for linear regression)','effect size d (only for 2-sample t-test)','standard normal (Z-value)','apply thresholds without conversion'}; + sel.values = {1,2,3,4,6,5}; + sel.val = {2}; + sel.help = {'Select conversion of t-value'}; + + thresh05 = cfg_entry; + thresh05.tag = 'thresh05'; + thresh05.name = 'Threshold'; + thresh05.help = {''}; + thresh05.strtype = 'r'; + thresh05.num = [1 1]; + thresh05.val = {0.05}; + + thresh001 = cfg_entry; + thresh001.tag = 'thresh001'; + thresh001.name = 'Threshold'; + thresh001.help = {''}; + thresh001.strtype = 'r'; + thresh001.num = [1 1]; + thresh001.val = {0.001}; + + kthresh = cfg_entry; + kthresh.tag = 'kthresh'; + kthresh.name = 'Extent (voxels)'; + kthresh.help = {'Enter the extent threshold in voxels'}; + kthresh.strtype = 'r'; + kthresh.val = {0}; + kthresh.num = [1 1]; + + noniso = cfg_menu; + noniso.name = 'Correct for non-isotropic smoothness'; + noniso.tag = 'noniso'; + noniso.labels = {'Yes','No'}; + noniso.values = {1,0}; + noniso.val = {1}; + noniso.help = {'Correct for non-isotropic smoothness for cluster extent thresholds.'}; + + none = cfg_const; + none.tag = 'none'; + none.name = 'None'; + none.val = {1}; + none.help = {'No threshold'}; + + k = cfg_branch; + k.tag = 'k'; + k.name = 'k-value'; + k.val = {kthresh, noniso }; + k.help = {''}; + + fwe = cfg_branch; + fwe.tag = 'fwe'; + fwe.name = 'FWE'; + fwe.val = {thresh05 }; + fwe.help = {''}; + + fdr = cfg_branch; + fdr.tag = 'fdr'; + fdr.name = 'FDR'; + fdr.val = {thresh05 }; + fdr.help = {''}; + + fwe2 = cfg_branch; + fwe2.tag = 'fwe2'; + fwe2.name = 'FWE'; + fwe2.val = {thresh05, noniso }; + fwe2.help = {''}; + + uncorr = cfg_branch; + uncorr.tag = 'uncorr'; + uncorr.name = 'uncorrected'; + uncorr.val = {thresh001 }; + uncorr.help = {''}; + + kuncorr = cfg_branch; + kuncorr.tag = 'kuncorr'; + kuncorr.name = 'uncorrected'; + kuncorr.val = {thresh05, noniso }; + kuncorr.help = {''}; + + En = cfg_branch; + En.tag = 'En'; + En.name = 'Expected voxels per cluster'; + En.val = {noniso }; + En.help = {''}; + + inverse = cfg_menu; + inverse.name = 'Show also inverse effects (e.g. neg. values)'; + inverse.tag = 'inverse'; + inverse.labels = {'Yes','No'}; + inverse.values = {1,0}; + inverse.val = {0}; + inverse.help = {'Show also inverse effects (e.g. neg. values). This is not valid if you convert to (log) p-values.'}; + + threshdesc = cfg_choice; + threshdesc.name = 'Threshold type peak-level'; + threshdesc.tag = 'threshdesc'; + threshdesc.values = {none uncorr fdr fwe}; + threshdesc.val = {uncorr}; + threshdesc.help = {'Select method for voxel threshold'}; + + cluster = cfg_choice; + cluster.name = 'Cluster extent threshold'; + cluster.tag = 'cluster'; + cluster.values = {none k En kuncorr fwe2}; + cluster.val = {none}; + cluster.help = {'Select method for extent threshold'}; + + conversion = cfg_branch; + conversion.tag = 'conversion'; + conversion.name = 'Conversion'; + conversion.val = {sel threshdesc inverse cluster}; + conversion.help = {''}; + + atlas = cfg_menu; + atlas.name = 'Atlas Labeling'; + atlas.tag = 'atlas'; + atlas.labels{1} = 'None'; + atlas.values{1} = 'None'; + + list = spm_atlas('List','installed'); + j = 1; + for i=1:numel(list) + if ~strcmp(list(i).name,'Neuromorphometrics') + atlas.labels{j+1} = list(i).name; + atlas.values{j+1} = list(i).name; + j = j + 1; + end + end + + atlas.val = {'None'}; + atlas.help = { + 'Select atlas for labeling. The prepending atlas name ''dartel_'' indicates that this atlas was created using Dartel spatial normalization with the Dartel IXI template as default.' + '' + 'Please note, that you can install additional atlases for CAT12 using the command ''cat_install_atlases''. ' + }; + + + + % T2x volumes + % ----------------------------------------------------------------------- + T2x = cfg_exbranch; + T2x.tag = 'T2x'; + T2x.name = 'Threshold and transform spmT images'; + T2x.val = {data_T2x,conversion,atlas}; + T2x.prog = @cat_stat_spm2x; + T2x.vout = @vout_stat_spm2x; + T2x.help = { + 'This function transforms t-maps to P, -log(P), r, d, or Z-maps.' + 'The following formulas are used:' + '--------------------------------' + 'correlation coefficient (only for regression):' + ' t' + ' r = ------------------' + ' sqrt(t^2 + df)' + 'effect size d (only for 2-sample t-test):' + ' d = 2*t/sqrt(df(2))' + 'Standard normal (Z-value):' + ' Z = spm_t2z(t,df(2))' + 'p-value:' + ' p = 1-spm_Tcdf' + 'log p-value:' + ' -log10(1-P) = -log(1-spm_Tcdf)' + 'For the latter case of log transformation this means that a p-value of p=0.99 (0.01) is transformed to a value of 2.' + 'Examples:' + 'p-value -log10(1-P)' + '0.1 1' + '0.05 1.30103 (-log10(0.05))' + '0.01 2' + '0.001 3' + '0.0001 4' + 'All maps can be thresholded using height and extent thresholds and you can also apply corrections for multiple comparisons based on family-wise error (FWE) or false discovery rate (FDR). You can easily threshold and/or transform a large number of spmT-maps using the same thresholds.' + 'Naming convention of the transformed files:' + ' Type_Contrast_Pheight_Pextent_K_Neg' + ' Type: P - p-value' + ' logP - log p-value' + ' D - effect size d' + ' R - correlation coefficient' + ' T - t-value' + ' Z - Z-value' + ' Contrast: name used in the contrast manager with replaced none valid' + ' strings' + ' Pheight: p - uncorrected p-value in % (p<0.05 will coded with ""p5"")' + ' pFWE - p-value with FWE correction in %' + ' pFDR - p-value with FDR correction in %' + ' Pextent: pk - uncorr. extent p-value in % (p<0.05 coded with ""p5"")' + ' pkFWE - extent p-value with FWE correction in %' + ' K: extent threshold in voxels' + ' Neg: image also shows thresholded inverse effects (e.g. neg. ' + ' values) ' + }'; + + + % T2x surfaces + % ----------------------------------------------------------------------- + + % Do not use 3D atlases for surfaces + data_T2x.filter = {'gifti'}; + + % surfaces + T2x_surf = T2x; + T2x_surf.val = {data_T2x,conversion}; + T2x_surf.tag = 'T2x_surf'; + T2x_surf.name = 'Threshold and transform spmT surfaces'; + T2x_surf.vout = @vout_stat_spm2x_surf; + + + % F2x volumes + % ----------------------------------------------------------------------- + + data_F2x = cfg_files; + data_F2x.tag = 'data_F2x'; + data_F2x.name = 'Data'; + data_F2x.filter = {'image'}; + data_F2x.ufilter = '^spmF.*'; + data_F2x.num = [1 Inf]; + data_F2x.help = {'Select spmF-data to select.'}; + + sel = cfg_menu; + sel.name = 'Convert F value to'; + sel.tag = 'sel'; + sel.labels = {'p','-log(p)','coefficient of determination R^2 (only for linear regression)','apply thresholds without conversion'}; + sel.values = {1,2,3,4}; + sel.val = {2}; + sel.help = {'Select conversion of F-value'}; + + none = cfg_const; + none.tag = 'none'; + none.name = 'None'; + none.val = {1}; + none.help = {'No threshold'}; + + cluster = cfg_choice; + cluster.name = 'Cluster extent threshold'; + cluster.tag = 'cluster'; + cluster.values = {none k En kuncorr fwe2}; + cluster.val = {none}; + cluster.help = {'Select method for extent threshold'}; + + conversion = cfg_branch; + conversion.tag = 'conversion'; + conversion.name = 'Conversion'; + conversion.val = {sel threshdesc cluster}; + conversion.help = {''}; + + F2x = cfg_exbranch; + F2x.tag = 'F2x'; + F2x.name = 'Threshold and transform spmF images'; + F2x.val = {data_F2x,conversion,atlas}; + F2x.prog = @cat_stat_spm2x; + F2x.vout = @vout_stat_spm2x; + F2x.help = { + 'This function transforms F-maps to P, -log(P), or R2-maps.' + 'The following formulas are used:' + '--------------------------------' + 'coefficient of determination R2 (only for regression):' + ' 1' + ' R2 = ------------------' + ' 1 + F*(p-1)/n-p)' + 'p-value:' + ' p = 1-spm_Fcdf' + 'log p-value:' + ' -log10(1-P) = -log(1-spm_Fcdf)' + 'For the last case of log transformation this means that a p-value of p=0.99 (0.01) is transformed to a value of 2.' + 'Examples:' + 'p-value -log10(1-P)' + '0.1 1' + '0.05 1.30103 (-log10(0.05))' + '0.01 2' + '0.001 3' + '0.0001 4' + 'All maps can be thresholded using height and extent thresholds and you can also apply corrections for multiple comparisons based on family-wise error (FWE) or false discovery rate (FDR). You can easily threshold and/or transform a large number of spmT-maps using the same thresholds.' + 'Naming convention of the transformed files:' + ' Type_Contrast_Pheight_K' + ' Type: P - p-value' + ' logP - log p-value' + ' R2 - coefficient of determination' + ' Contrast: name used in the contrast manager with replaced none valid' + ' strings' + ' Pheight: p - uncorrected p-value in % (p<0.05 will coded with ""p5"")' + ' pFWE - p-value with FWE correction in %' + ' pFDR - p-value with FDR correction in %' + ' K: extent threshold in voxels' + }'; + + + % F2x surfaces + % ----------------------------------------------------------------------- + + % Do not use 3D atlases for surfaces + data_F2x.filter = {'gifti'}; + + F2x_surf = F2x; + F2x_surf.val = {data_F2x,conversion}; + F2x_surf.tag = 'F2x_surf'; + F2x_surf.name = 'Threshold and transform spmF surfaces'; + F2x_surf.vout = @vout_stat_spm2x_surf; + +return + +%_______________________________________________________________________ +function showslice = conf_stat_showslice_all(data_vol) + data_vol.help = {'Select all images. Images have to be in the same orientation with same voxel size and dimension (e.g. normalized images)'}; + + scale = cfg_menu; + scale.tag = 'scale'; + scale.name = 'Proportional scaling?'; + scale.labels = {'No','Yes'}; + scale.values = {0 1}; + scale.val = {0}; + scale.help = {'This option should be only used if image intensity is not scaled (e.g. T1 images) or if images have to be scaled during statistical analysis (e.g. modulated images).'}; + + orient = cfg_menu; + orient.tag = 'orient'; + orient.name = 'Spatial orientation'; + orient.labels = {'axial','coronal','sagittal'}; + orient.values = {3 2 1}; + orient.val = {3}; + orient.help = {'Spatial orientation of slice.'}; + + slice = cfg_entry; + slice.tag = 'slice'; + slice.name = 'Selected slice (in mm)?'; + slice.strtype = 'r'; + slice.num = [1 1]; + slice.val = {0}; + slice.help = {'Choose slice in mm.'}; + + showslice = cfg_exbranch; + showslice.tag = 'showslice'; + showslice.name = 'Display one slice for all images'; + showslice.val = {data_vol,scale,orient,slice}; + showslice.prog = @cat_stat_showslice_all; + showslice.help = {'This function displays a selected slice for all images and indicates the respective filenames which is useful to check image quality for a large number of files in a circumscribed region (slice).'}; + +%_______________________________________________________________________ +function quality_measures = conf_quality_measures(globals) + + data = cfg_files; + data.name = 'Sample data'; + data.tag = 'data'; + data.filter = {'image','resampled.*\.(gii)$'}; + data.num = [1 Inf]; + data.help = {'These are the (spatially registered or resampled) data. They must all have the same data dimension, orientation, voxel or mesh size etc. Furthermore, it is recommended to use unsmoothed files.'}; + + csv_name = cfg_entry; + csv_name.tag = 'csv_name'; + csv_name.name = 'Output csv file'; + csv_name.strtype = 's'; + csv_name.num = [1 Inf]; + csv_name.val = {'Quality_measures.csv'}; + csv_name.help = { + 'The output file is written to current working directory unless a valid full pathname is given. The following parameters are saved:' + ' Mean Z-score - low values indicate more similarity/homogeneity to sample' + ' Weighted overall image quality (IQR) - low values mean better image quality before preprocessing' + ' Normalized product of IQR and Mean Z-score - low values point to good image quality before preprocessing and large homogeneity to sample after preprocessing' + ' Euler Number (for surfaces only) - lower numbers point to better quality of surface extraction' + ' Size of topology defects (for surfaces only) - smaller size points to better quality of surface extraction' + '' + }; + + quality_measures = cfg_exbranch; + quality_measures.tag = 'quality_measures'; + quality_measures.name = 'Save sample homogeneity for very large samples'; + quality_measures.val = {data,globals,csv_name}; + quality_measures.prog = @cat_stat_quality_measures; + quality_measures.help = { + 'In order to identify data with poor image quality or even artefacts you can use this function. In contrast to the Check Homogeneity tool this function can be also applied to very large samples, but provides no graphical output.' + 'The saved quality parameters in the csv-file can be then used with external analysis tools. The following parameters are saved:' + ' Mean Z-score - low values indicate more similarity/homogeneity to sample' + ' Weighted overall image quality (IQR) - low values mean better image quality before preprocessing' + ' Normalized product of IQR and Mean Z-score - low values point to good image quality before preprocessing and large homogeneity to sample after preprocessing' + ' Euler Number (for surfaces only) - lower numbers point to better quality of surface extraction' + ' Size of topology defects (for surfaces only) - smaller size points to better quality of surface extraction' + '' + }; + +%_______________________________________________________________________ +function [check_homogeneity, check_cov] = conf_check_cov(data_xml,outdir,fname,save,globals,expert) + + % --- update input data --- + data_xml.name = 'Quality measures (leave emtpy for autom. search)'; + data_xml.help = { + 'Select optional the quality measures that are saved during segmentation as xml-files in the report folder. This allows to additionally analyze image quality parameters such as noise, bias, and weighted overall image quality.' + 'Please note, that the order of the xml-files should be the same as the other data files.' + 'Leave empty for automatically search for these xml-files.' + }; + + % --- further data --- + c = cfg_entry; + c.tag = 'c'; + c.name = 'Vector/Matrix'; + c.help = {'Vector or matrix of nuisance values.'}; + c.strtype = 'r'; + c.num = [Inf Inf]; + + nuisance = cfg_repeat; + nuisance.tag = 'nuisance'; + nuisance.name = 'Nuisance variable'; + nuisance.values = {c}; + nuisance.num = [0 Inf]; + nuisance.help = {'This option allows for the specification of nuisance effects to be removed from the data. A potential nuisance parameter can be TIV if you check segmented data with the default modulation. In this case the variance explained by TIV will be removed prior to the calculation of the correlation. Another meaningful nuisance effect is age. This parameter should be defined for all samples as one variable and may also contain several columns.'}; + + s = cfg_entry; + s.tag = 'sites'; + s.name = 'Sites'; + s.help = {'Vector of site/protocol identifier.'}; + s.strtype = 'c'; + s.num = [1 Inf]; + + sites = cfg_repeat; + sites.tag = 'sites'; + sites.name = 'Site variable'; + sites.values = {s}; + sites.num = [0 1]; + sites.help = {'Definition of scan sites to normalize quality ratings per site to identify outliers with motion artefacts. If no site is give the image resolution is used to identify sites.'}; + + gap = cfg_entry; + gap.tag = 'gap'; + gap.name = 'Separation'; + gap.strtype = 'n'; + gap.num = [1 1]; + gap.val = {3}; + gap.hidden = expert<2; + gap.help = {'To speed up calculations you can define that covariance is estimated only every x voxel. Smaller values give slightly more accurate covariance, but will be much slower.'}; + + data_vol = cfg_files; + data_vol.name = 'Sample data'; + data_vol.tag = 'data_vol'; + data_vol.filter = {'image','resampled.*\.gii$'}; + data_vol.num = [1 Inf]; + data_vol.help = {'These are the (spatially registered or resampled) data. Volumes must all have the same image dimensions, orientation, voxel size and surfaces should be resampled with the same parameters. Furthermore, it is recommended to use unsmoothed files (i.e. for volumes).'}; + + sample = cfg_repeat; + sample.tag = 'sample'; + sample.name = 'Data'; + sample.values = {data_vol}; + sample.num = [1 Inf]; + sample.help = {'Specify data for each sample. If you specify different samples the mean correlation is displayed in separate boxplots (or violin plots) for each sample.'}; + + rps = cfg_menu; + rps.tag = 'userps'; + rps.name = 'Rating sytem'; + rps.labels = {'School marks','Percentage score'}; + rps.values = {-1 1}; + rps.val = {-1}; + rps.help = { + 'Rating system selection between school grads (range good-bad: 0.5-10.5) and percentage score (range good-bad: 100-0) for quality metrics: '; + ''; + ' Definition: excellent good satisfactory sufficent critical unacceptable'; + ' Nominal Letter: A B C D E ...'; + ' School grad: 1 2 3 4 5 ...'; + ' Percentage (rps*): 95% 85% 75% 65% 55% ...'; + ''; + 'The normalised SIQR (nSIQR) is lineary corrected for the ""better"" quantil of each site (see site variable): '; + ' Definition: excellent average slight artifacts severe artifacts '; + ' School grad: -0.5 0.0 0.5 1.0 '; + ' Percentage (rps*): 5 0 -5 -10 '; + '' + '* .. rating points'; + ''; + }; + + + check_cov = cfg_exbranch; + check_cov.tag = 'check_cov'; + check_cov.name = 'Check Sample Homogeneity for long. Data (old method)'; + if expert>1 + check_cov.val = {sample,data_xml,gap,nuisance,outdir,fname,save}; + else + check_cov.val = {sample,data_xml,gap,nuisance}; + end + check_cov.prog = @cat_stat_check_cov_old; + check_cov.help = { + 'In order to identify data with poor data quality or even artefacts you can use this function. 3D images have to be in the same orientation with same voxel size and dimension (e.g. normalized images without smoothing) while surfaces have to be resampled and smoothed using the same parameters. The idea of this tool is to check the correlation of all data across the sample.' + '' + 'The correlation is calculated between all data and the mean for each data is plotted using a boxplot and the indicated filenames. The smaller the mean correlation the more deviant is this data from the sample mean. In the plot, outliers from the sample are usually isolated from the majority of data which are clustered around the sample mean. The mean correlation is plotted at the y-axis and the x-axis reflects the data order.' + 'If you have loaded quality measures, you can also display the ratio between weighted overall structural image quality (SIQR) and mean correlation. These two are the most important measures for assessing data quality.' + '' + 'SIQR is further used to estimate a (site-specific if specified) normalizes score nSIQR that allows detection of outliers from the typical quality of the protocol, where a deviating ratings of about 5/10 rps indicate cases with slight/severe (motion) artifacts. ' + }; + + data = data_vol; + data.tag = 'data'; + sample.values = {data}; + + data_xml.name = 'Select quality measures (leave emtpy for autom. search)'; + + xmldir = cfg_files; + xmldir.tag = 'select_dir'; + xmldir.filter = 'dir'; + xmldir.ufilter = '.*'; + xmldir.num = [0 1]; + xmldir.name = 'Select report folder'; + xmldir.val{1} = {''}; + xmldir.help = {'Select the folder where xml-files are located. This is usally the report folder.'}; + + sel_xml = cfg_choice; + sel_xml.name = 'Method to find quality measures'; + sel_xml.tag = 'sel_xml'; + sel_xml.values = {xmldir data_xml}; + sel_xml.val = {data_xml}; + sel_xml.help = { + 'Choose between two methods to find xml-files with quality measures:' + '(1) Selecting the xml-files manually or leave emtpy for automatically search in the standard report folder.' + '(2) Selecting the report folder for automatically search for these xml-files.' + }; + + % --- main --- + check_homogeneity = cfg_exbranch; + check_homogeneity.val = {sample,sel_xml,globals,rps,sites,nuisance}; + check_homogeneity.tag = 'check_homogeneity'; + check_homogeneity.name = 'Check Sample Homogeneity'; + check_homogeneity.prog = @cat_stat_homogeneity; + check_homogeneity.help = { + 'In order to identify data with poor data quality or even artefacts you can use this function. 3D images have to be in the same orientation with same voxel size and dimension (e.g. normalized images without smoothing) while surfaces have to be resampled and smoothed using the same parameters. The idea of this tool is to check the Z-score of all data across the sample.' + '' + 'The Z-score is calculated for all data and the quartic mean (using a power of 4) for each data is plotted using a boxplot and the indicated filenames. The larger the quartic mean Z-score the more deviant is this data from the sample mean. The reason we apply a power of 4 to the z-score (quartic) is to give outliers a greater weight and make them more obvious in the plot. In the plot, outliers from the sample are usually isolated from the majority of data which are clustered around the sample mean. The quartic mean Z-score is plotted at the y-axis and the x-axis reflects the data order.' + 'If you have loaded quality measures, you can also display the product between weighted overall image quality (IQR) and quartic mean Z-score. These two are the most important measures for assessing data quality.' + }; + +%_______________________________________________________________________ +function check_SPM = conf_stat_check_SPM(outdir,fname,save,expert) + + outdir.hidden = expert<2; + fname.hidden = expert<2; + save.hidden = expert<2; + + spmmat = cfg_files; + spmmat.tag = 'spmmat'; + spmmat.name = 'Select SPM.mat'; + spmmat.filter = {'mat'}; + spmmat.ufilter = '^SPM\.mat$'; + spmmat.num = [1 1]; + spmmat.help = {'Select the SPM.mat file that contains the design specification.'}; + + % check_SPM_zscore + use_unsmoothed_data = cfg_menu; + use_unsmoothed_data.name = 'Use unsmoothed data if found'; + use_unsmoothed_data.tag = 'use_unsmoothed_data'; + use_unsmoothed_data.labels = {'Yes','No'}; + use_unsmoothed_data.values = {1,0}; + use_unsmoothed_data.val = {1}; + use_unsmoothed_data.help = {'Check for sample homogeneity results in more reliable values if unsmoothed data are used. Unsmoothed data contain more detailed information about differences and similarities between the data.'}; + + adjust_data = cfg_menu; + adjust_data.name = 'Adjust data using design matrix'; + adjust_data.tag = 'adjust_data'; + adjust_data.labels = {'Yes','No'}; + adjust_data.values = {1,0}; + adjust_data.val = {1}; + adjust_data.help = {'This option allows to use nuisance and group parameters from the design matrix to obtain adjusted data. In this case the variance explained by these parameters will be removed prior to the calculation of the correlation. Furthermore, global scaling (if defined) is also applied to the data.'}; + + do_check_zscore = cfg_branch; + do_check_zscore.tag = 'do_check_zscore'; + do_check_zscore.name = 'Yes'; + do_check_zscore.val = {use_unsmoothed_data adjust_data ,outdir,fname,save}; + do_check_zscore.help = {''}; + + none = cfg_const; + none.tag = 'none'; + none.name = 'No'; + none.val = {1}; + none.help = {''}; + + check_SPM_zscore = cfg_choice; + check_SPM_zscore.name = 'Check for sample homogeneity'; + check_SPM_zscore.tag = 'check_SPM_zscore'; + check_SPM_zscore.values = {none do_check_zscore}; + check_SPM_zscore.val = {do_check_zscore}; + check_SPM_zscore.help = { + 'In order to identify images with poor image quality or even artefacts you can use this function. The idea of this tool is to check the correlation of all files across the sample using the files that are already defined in SPM.mat.' + '' + 'The correlation is calculated between all images and the mean for each image is plotted using a boxplot (or violin plot) and the indicated filenames. The smaller the mean correlation the more deviant is this image from the sample mean. In the plot outliers from the sample are usually isolated from the majority of images which are clustered around the sample mean. The mean correlation is plotted at the y-axis and the x-axis reflects the image order' + }; + + check_SPM_ortho = cfg_menu; + check_SPM_ortho.name = 'Check for design orthogonality'; + check_SPM_ortho.tag = 'check_SPM_ortho'; + check_SPM_ortho.labels = {'Yes','No'}; + check_SPM_ortho.values = {1,0}; + check_SPM_ortho.val = {1}; + check_SPM_ortho.help = {'Review Design Orthogonality.'}; + + check_SPM = cfg_exbranch; + check_SPM.tag = 'check_SPM'; + check_SPM.name = 'Check design orthogonality and homogeneity'; + check_SPM.val = {spmmat,check_SPM_zscore,check_SPM_ortho}; + check_SPM.prog = @cat_stat_check_SPM; + check_SPM.help = {'Use design matrix saved in SPM.mat to check for sample homogeneity of the used data and for orthogonality of parameters.'}; + +%_______________________________________________________________________ +function calcvol = conf_stat_TIV + calcvol_name = cfg_entry; + calcvol_name.tag = 'calcvol_name'; + calcvol_name.name = 'Output file'; + calcvol_name.strtype = 's'; + calcvol_name.num = [1 Inf]; + calcvol_name.val = {'TIV.txt'}; + calcvol_name.help = { + 'The output file is written to current working directory unless a valid full pathname is given.'}; + + calcvol_TIV = cfg_menu; + calcvol_TIV.tag = 'calcvol_TIV'; + calcvol_TIV.name = 'Save values'; + calcvol_TIV.labels = {'TIV only' 'TIV & GM/WM/CSF/WMH'}; + calcvol_TIV.values = {1 0}; + calcvol_TIV.val = {1}; + calcvol_TIV.help = {'You can save either the total intracranial volume (TIV) only or additionally also save the global volumes for GM, WM, CSF, and WM hyperintensities.' + '' + }; + + calcvol_savenames = cfg_menu; + calcvol_savenames.tag = 'calcvol_savenames'; + calcvol_savenames.name = 'Add filenames'; + calcvol_savenames.labels = {'Values only' 'Add file names' 'Add folders and file names'}; + calcvol_savenames.values = {0 1 2}; + calcvol_savenames.val = {0}; + calcvol_savenames.help = {'You can either save only the values (that can be easily read with spm_load) or also add file names (and folders) to 1st column.' + '' + }; + + clear data_xml + data_xml = cfg_files; + data_xml.name = 'XML files'; + data_xml.tag = 'data_xml'; + data_xml.filter = 'xml'; + data_xml.ufilter = '^cat_.*\.xml$'; + data_xml.num = [1 Inf]; + data_xml.help = {... + 'Select xml-files that are saved during segmentation in the report folder.'}; + + calcvol = cfg_exbranch; + calcvol.tag = 'calcvol'; + calcvol.name = 'Estimate TIV and global tissue volumes'; + calcvol.val = {data_xml,calcvol_TIV,calcvol_savenames,calcvol_name}; + calcvol.prog = @cat_stat_TIV; + calcvol.vout = @vout_stat_TIV; + calcvol.help = { + 'This function reads raw volumes for TIV/GM/WM/CSF/WM hyperintensities (WMH) and saves values in a txt-file. These values can be read with the matlab command: vol = spm_load. If you choose to save all values the entries for TIV/GM/WM/CSF/WMH are now saved in vol(:,1) vol(:,2) vol(:,3), vol(:,4), and vol(:,5) respectively.' + '' + 'You can use TIV either as nuisance in an AnCova model or as user-specified globals with the ""global calculation"" option depending on your hypothesis. The use of TIV as nuisance or globals is recommended for modulated data where both the affine transformation and the non-linear warping of the registration are corrected for. ' + '' + }; + +%_______________________________________________________________________ +function calcroi = conf_roi_fun(outdir) + roi_xml = cfg_files; + roi_xml.name = 'XML files'; + roi_xml.tag = 'roi_xml'; + roi_xml.filter = 'xml'; + roi_xml.ufilter = '^catROI.*\.xml$'; + roi_xml.num = [1 Inf]; + roi_xml.help = {'These are the xml-files that are saved in the label folder after CAT12 segmentation.'}; + + % NOT USED + %{ + usefolder = cfg_menu; + usefolder.tag = 'folder'; + usefolder.name = 'Use foldername'; + usefolder.labels = {'Yes' 'No'}; + usefolder.values = {1 0}; + usefolder.val = {0}; + usefolder.help = {'Use foldername to describe the subject.'}; + %} + + point = cfg_menu; + point.tag = 'point'; + point.name = 'Decimal point'; + point.labels = {',','.'}; + point.values = {',','.'}; + point.val = {'.'}; + point.help = {'Decimal point.'}; % that has to be unequal to the column delimiter.'}; + + % tab ""\t"" does not work and so we automatically switch in case of decimal + % point "","" to delimiter "";"". + %{ + delimiter = cfg_menu; + delimiter.tag = 'delimiter'; + delimiter.name = 'column delimiter'; + delimiter.labels = {',',';',' '}; + delimiter.values = {',',';',' '}; + delimiter.val = {','}; + delimiter.help = {'Delimiter between columns.'}; + %} + + calcroi_name = cfg_entry; + calcroi_name.tag = 'calcroi_name'; + calcroi_name.name = 'Output file'; + calcroi_name.strtype = 's'; + calcroi_name.num = [1 Inf]; + calcroi_name.val = {'ROI'}; + calcroi_name.help = {'The mean volume values in mL (e.g. GM volume) or the mean surface values (e.g. thickness) are written to the current working directory unless a valid full pathname is given. The output file will also include the name of the atlas and the measure (e.g. Vgm). The file is using tabstops to separate values in order to easily import the file into Excel or SPSS or any other software for subsequent analysis.'}; + + calcroi = cfg_exbranch; + calcroi.tag = 'calcroi'; + calcroi.name = 'Estimate mean/volume inside ROI'; + calcroi.val = {roi_xml,point,outdir,calcroi_name}; + %calcroi.val = {roi_xml,usefolder,point,outdir,calcroi_name}; % usefolder is never used + calcroi.prog = @(job)cat_roi_fun('exportSample',job); + calcroi.help = { + 'This function reads values inside a ROI from different atlases (that were selected for CAT12 segmentation) and saves either the mean volume values in mL (e.g. GM volume) or the mean surface values (e.g. thickness) for all data in a csv-file. ' + 'Missed values are replaced by NaN.' + }; + +%_______________________________________________________________________ +function urqio = conf_vol_urqio +% ------------------------------------------------------------------------ +% Ultra-High Resolution Quantitative Image Optimization +% ------------------------------------------------------------------------ + + % -- Data --- + r1 = cfg_files; + r1.tag = 'r1'; + r1.name = 'R1-Volumes'; + r1.filter = 'image'; + r1.ufilter = '.*'; + r1.num = [1 Inf]; + r1.help = {'Select R1 weighted images.'}; + + pd = cfg_files; + pd.tag = 'pd'; + pd.name = 'PD-Volumes'; + pd.filter = 'image'; + pd.ufilter = '.*'; + pd.num = [1 Inf]; + pd.help = {'Select PD weighted images.'}; + + r2s = cfg_files; + r2s.tag = 'r2s'; + r2s.name = 'R2s-Volumes'; + r2s.filter = 'image'; + r2s.ufilter = '.*'; + r2s.num = [1 Inf]; + r2s.help = {'Select R2s weighted images.'}; + + data = cfg_branch; + data.tag = 'data'; + data.name = 'Input data'; + data.val = {r1 pd r2s}; + data.help = { + 'Input Images.' + }; + + + % --- Parameter --- + spm = cfg_menu; + spm.tag = 'spm'; + spm.name = 'Use SPM Preprocessing'; + spm.labels = {'No','Yes'}; + spm.values = {0 1}; + spm.val = {1}; + spm.help = { + 'Use SPM preprocessing if the data is not skull-stripped.' + }; + + bc = cfg_menu; + bc.tag = 'bc'; + bc.name = 'Bias Correction'; + bc.labels = {'No','light','medium','strong'}; + bc.values = {0 0.5 1 2}; + bc.val = {1}; + bc.help = { + 'Additional bias correction that is important for detection and correction of blood vessels.' + '' + 'The correction uses a simple tissue classification and local filter approaches to estimate the local signal intensity in the WM and GM segment, e.g. a minimum/maximum filter in the WM for PD/T1 images. Next, unclassified voxels were approximated and smoothed depending on the defined strength. ' + '' + }; + + in = cfg_menu; + in.tag = 'in'; + in.name = 'Intensity Normalization'; + in.labels = {'No','Yes'}; + in.values = {0 1}; + in.val = {1}; + in.help = { + 'Additional global intensity normalization that is also important for detection and correction of blood vessels.' + '' + }; + + bvc = cfg_menu; + bvc.tag = 'bvc'; + bvc.name = 'Blood Vessel Correction'; + bvc.labels = {'No','Yes'}; + bvc.values = {0 1}; + bvc.val = {1}; + bvc.help = { + 'Correction of blood vessels with high intensity in T1/R1/R2s and low intensity in PD images by CSF-like intensities. ' + '' + }; + + ss = cfg_menu; + ss.tag = 'ss'; + ss.name = 'Apply Skull-Stripping'; + ss.labels = {'No','Yes'}; + ss.values = {0 1}; + ss.val = {1}; + ss.help = { + 'Write skull-stripped images. ' + '' + }; + + nc = cfg_menu; + nc.tag = 'nc'; + nc.name = 'Noise Correction'; + nc.labels = {'No','Yes'}; + nc.values = {0 1}; + nc.val = {1}; + nc.help = { + 'Noise corrections of the final images.' + '' + }; + + prefix = cfg_entry; + prefix.tag = 'prefix'; + prefix.name = 'Filename prefix'; + prefix.strtype = 's'; + prefix.num = [0 Inf]; + prefix.val = {'catsyn_'}; + prefix.help = { + 'Prefix of output files.'}; + + + opts = cfg_branch; + opts.tag = 'opts'; + opts.name = 'Parameter'; + opts.val = {spm bc in bvc ss nc prefix}; + opts.help = { + 'Parameter settings for image correction.' + }; + + + % --- Output --- + pdo = cfg_menu; + pdo.tag = 'pd'; + pdo.name = 'PD Output'; + pdo.labels = {'No','Yes'}; + pdo.values = {0 1}; + pdo.val = {1}; + pdo.help = { + 'Write PD output images.' + }; + + t1o = cfg_menu; + t1o.tag = 't1'; + t1o.name = 'T1 Output'; + t1o.labels = {'No','Yes'}; + t1o.values = {0 1}; + t1o.val = {1}; + t1o.help = { + 'Write synthesized T1 output images based on the PD image.' + }; + + r1o = cfg_menu; + r1o.tag = 'r1'; + r1o.name = 'R1 Output'; + r1o.labels = {'No','Yes'}; + r1o.values = {0 1}; + r1o.val = {1}; + r1o.help = { + 'Write R1 output images.' + }; + + r2so = cfg_menu; + r2so.tag = 'r2s'; + r2so.name = 'R2s Output'; + r2so.labels = {'No','Yes'}; + r2so.values = {0 1}; + r2so.val = {1}; + r2so.help = { + 'Write R2s output images.' + }; + + bvco = cfg_menu; + bvco.tag = 'bv'; + bvco.name = 'Blood Vessel Output'; + bvco.labels = {'No','Yes'}; + bvco.values = {0 1}; + bvco.val = {0}; + bvco.help = { + 'Write map of blood vessels.' + }; + + output = cfg_branch; + output.tag = 'output'; + output.name = 'Output'; + output.val = {r1o r2so pdo t1o bvco}; + output.help = { + 'Output images.' + }; + + + % --- main --- + % batch mode - output is undefined! + urqio = cfg_exbranch; + urqio.tag = 'urqio'; + urqio.name = 'Ultra-High Resolution Quantitative Image Optimization'; + urqio.val = {data opts output}; + urqio.prog = @cat_vol_urqio; + %urqio.vout = @vout_urqio; + urqio.help = { + 'Additional correction of high resolution PD, R1, and R2s weighted images that includes another bias correction, intensity normalization, and blood vessel correction step. ' + '' + 'WARNING: This tool is in development and was just tested on a small set of subjects!' + }; +function boxplot = conf_io_boxplot(outdir,subdir,name,expert) + + files = cfg_files; + files.tag = 'files'; + files.name = 'Files'; + files.help = {'files.' ''}; + files.filter = 'any'; + files.ufilter = '.*.xml'; + files.num = [3 Inf]; + + % - groupname ... % opt.names = []; % array of group names + setname = cfg_entry; + setname.tag = 'setname'; + setname.name = 'Name'; + setname.help = {'Name of the dataset that replaces the number of the set. ' ''}; + setname.strtype = 's'; + setname.num = [0 Inf]; + setname.val = {''}; + + % - groupcolor ... % has to be generated later + setcolor = cfg_entry; + setcolor.tag = 'setcolor'; + setcolor.name = 'Color'; + setcolor.strtype = 'r'; + setcolor.num = [0 Inf]; + setcolor.help = { + ['Color of the dataset that replaces the default color definied by the color table below. ' ... + 'The color has to be defined as 3x1 RGB value between 0 and 1, e.g. [0 0.5 0] for dark green. '] ''}; + setcolor.val = {''}; + + % - groupcolor ... % has to be generated later + color = cfg_menu; + color.tag = 'setcolor'; + color.name = 'Color'; + color.labels = { ... + 'colormap' + 'red (light)'; 'red'; 'red (dark)'; + 'orange (light)'; 'orange'; 'orange (dark)'; + 'yellow (light)'; 'yellow'; 'yellow (dark)'; + 'green (light)'; 'green'; 'green (dark)'; + 'cyan (light)'; 'cyan'; 'cyan (dark)'; + 'blue (light)'; 'blue'; 'blue (dark)'; + 'violet (light)'; 'violet'; 'violet (dark)'; + 'gray (light)'; 'gray'; 'gray (dark)'; + }; + color.values = { + ''; + [1 1/3 1/3]; [1 0 0 ]; [2/3 0 0 ]; % red + [1 2/3 1/3]; [1 1/2 0 ]; [2/3 1/3 0 ]; % orange + [1 1 1/3]; [1 1 0 ]; [2/3 2/3 0 ]; % yellow + [1/3 1 1/3]; [0 1 0 ]; [0 2/3 0 ]; % green + [1/3 1 1 ]; [0 1 1 ]; [0 2/3 2/3]; % cyan + [1/3 1/3 1 ]; [0 0 1 ]; [0 0 2/3]; % blue + [1 1/3 1 ]; [1 0 1 ]; [2/3 0 2/3]; % violet + [3/4 3/4 3/4]; [1/2 1/2 1/2]; [1/4 1/4 1/4]; % gray + }; + color.val = {''}; + color.help = { + 'Color of the dataset that replaces the default color definied by the colormap below. ' ''}; + + % subset .. was not working + %{ + subset = cfg_menu; + subset.tag = 'subset'; + subset.name = 'Subset'; + subset.labels = {'W','G'}; + subset.values = {0 1}; + subset.def = @(val) 0; + subset.help = {'Subset G with gray background' ''}; + %} + + % as structure with subfields + datasetxml = cfg_exbranch; + datasetxml.tag = 'data'; + datasetxml.name = 'Dataset'; + datasetxml.val = { files , setname, color}; + datasetxml.help = {'Specify major properties of a dataset with predfined colors.' ''}; + + datasetxml2 = cfg_exbranch; + datasetxml2.tag = 'data'; + datasetxml2.name = 'Dataset (color definition)'; + datasetxml2.val = { files , setname, setcolor}; + datasetxml2.help = {'Specify major properties of a dataset with own color definition.' ''}; + + datasets = cfg_repeat; + datasets.tag = 'data'; + datasets.name = 'Datasets'; + datasets.values = {datasetxml datasetxml2}; + datasets.val = {}; + datasets.num = [1 Inf]; + datasets.help = {'Specify manually grouped XML files their name and color. '}; + + + % or as xmlparagroup where all xml-files are selected and then internally differentiated + % - xmlfiles + % - XML grouping parameter(s) (eg. software.version, parameter.extopts.collcorr ) ... + % ... the idea is nice but what if multiple parameter change? + % ... it is more easy, clearer and saver to force manual grouping or may focus on some elements + % Computer + SPM + CAT revision + + + + % quality measures (expert) + QMfield = cfg_menu; + QMfield.tag = 'xmlfields'; + QMfield.name = 'Image quality'; + QMfield.labels = { + 'Noise Contrast Ratio (NCR)' + 'Inhomogeny Contrast Ratio (ICR)' + 'Resolution RMSE (resRMS)' + 'Minimum tissue contrast' + }; + QMfield.values = { + 'qualitymeasures.NCR' + 'qualitymeasures.ICR' + 'qualitymeasures.res_RMS' + 'qualitymeasures.contrast' + }; + QMfield.val = {'qualitymeasures.NCR'}; + QMfield.help = {'CAT preprocessing image quality measures (not normalized).' ''}; + + + % quality ratings + QRfield = cfg_menu; + QRfield.tag = 'xmlfields'; + QRfield.name = 'Image quality ratings'; + QRfield.labels = { + 'Noise Contrast Ratio (NCR)' + 'Inhomogeny Contrast Ratio (ICR)' + 'Resolution RMSE (resRMS)' + 'Minimum tissue contrast' + }; + QRfield.values = { + 'qualitratings.NCR' + 'qualitratings.ICR' + 'qualitratings.res_RMS' + 'qualitratings.contrast' + }; + QRfield.val = {'qualitratings.NCR'}; + QRfield.help = {'CAT preprocessing image quality ratings (normalized marks).' ''}; + + + % surface measures + SMfield = cfg_menu; + SMfield.tag = 'xmlfields'; + SMfield.name = 'Surface quality'; + SMfield.labels = { + ... 'Surface Euler number' + 'Surface defect area' + 'Surface defect number' + 'Surface intensity RMSE' + 'Surface position RMSE' + 'Surface self-intersections' + }; + SMfield.values = { + ... 'qualitymeasures.SurfaceEulerNumber' + 'qualitymeasures.SurfaceDefectArea' + 'qualitymeasures.SurfaceDefectNumber' + 'qualitymeasures.SurfaceIntensityRMSE' + 'qualitymeasures.SurfacePositionRMSE' + 'qualitymeasures.SurfaceSelfIntersections' + }; + SMfield.val = {'qualitymeasures.SurfaceDefectArea'}; + SMfield.help = {'CAT preprocessing surface quality measures (not normalized). ' ''}; + + + % segmentation measures + USMfield = cfg_menu; + USMfield.tag = 'xmlfields'; + USMfield.name = 'Unified segmentation validation measures'; + USMfield.labels = { + 'SPM log-likelyhood' + 'SPM tissue peak 1 (def. GM)' + 'SPM tissue peak 2 (def. WM)' + 'SPM tissue peak 3 (def. CSF1)' + 'SPM tissue peak 4 (def. CSF2)' + 'SPM tissue volume 1 (GM)' + 'SPM tissue volume 2 (WM)' + 'SPM tissue volume 3 (CSF)' + 'SPM tissue volume 4 (HD1)' + 'SPM tissue volume 5 (HD2)' + 'SPM tissue volume 6 (BG)' + ...'CAT skull-stripping parameter' + ...'CAT high BG parameter' + }; + USMfield.values = { + 'SPMpreprocessing.ll' + 'SPMpreprocessing.mn(1)' + 'SPMpreprocessing.mn(2)' + 'SPMpreprocessing.mn(3)' + 'SPMpreprocessing.mn(4)' + 'ppe.SPMvols0(1)' + 'ppe.SPMvols0(2)' + 'ppe.SPMvols0(3)' + 'ppe.SPMvols0(4)' + 'ppe.SPMvols0(5)' + 'ppe.SPMvols0(6)' + ...'ppe.skullstrippedpara' + ...'ppe.highBGpara' + ...reg.ll + ...reg.dt, rmsdt + }; + USMfield.val = {'SPMpreprocessing.ll'}; + USMfield.help = {'SPM preprocessing measures for evaluation of the preprocessing. The tissue peaks depend on the defined number of SPM peaks within a class (default=[1 1 2 3 4 2]). The volumes depend on the TPM that are by default GM, MW, CSF, HD1 (hard tissue), HD2 (soft tissue), backgroun (BG). ' ''}; + USMfield.hidden = expert<2; + + + % individual measures + IMfield = cfg_menu; + IMfield.tag = 'xmlfields'; + IMfield.name = 'Morphometric measures'; + IMfield.labels = { + 'Total Intracranial Volume (TIV)' + 'Total Surface Area (TSA)' + 'Mean cortical thickness' + 'Cortical thickness standard deviation' + 'Relative CSF volume' + 'Relative GM volume' + 'Relative WM volume' + 'Relative WMH volume' + 'Absolute CSF volume' + 'Absolute GM volume' + 'Absolute WM volume' + 'Absolute WMH volume' + }; + IMfield.values = { + 'subjectmeasures.vol_TIV' + 'subjectmeasures.surf_TSA' + 'subjectmeasures.dist_thickness{1}(1)' + 'subjectmeasures.dist_thickness{1}(2)' + 'subjectmeasures.vol_rel_CGW(1)' + 'subjectmeasures.vol_rel_CGW(2)' + 'subjectmeasures.vol_rel_CGW(3)' + 'subjectmeasures.vol_rel_CGW(4)' + 'subjectmeasures.vol_abs_CGW(1)' + 'subjectmeasures.vol_abs_CGW(2)' + 'subjectmeasures.vol_abs_CGW(3)' + 'subjectmeasures.vol_abs_CGW(4)' + ...'ppe.reg.rmsdt' + ...'ppe.reg.rmsdtc' + }; + IMfield.val = {'subjectmeasures.vol_TIV'}; + IMfield.help = {'Global morphometric measures. ' ''}; + + + % - title + ftitle = setname; + ftitle.name = 'title'; + ftitle.tag = 'Plot title'; + ftitle.help = {'Name of figure' ''}; + ftitle.val = {''}; + % - yname (measure/scala) + fname = setname; + fname.name = 'name'; + fname.tag = 'Measure name'; + fname.help = {'Name of the measure ploted at the y-axis. ' ''}; + % + fspec = setname; + fspec.name = 'name'; + fspec.tag = 'Measure name'; + fspec.help = {'Name of the measure ploted at the y-axis. ' ''}; + % opt.ylim = [-inf inf]; % y-axis scaling + ylim = cfg_entry; + ylim.tag = 'ylim'; + ylim.name = 'y-axis limits'; + ylim.help = {'Limitation of x-axis. '}; + ylim.strtype = 'r'; + ylim.num = [1 2]; + ylim.val = {[-inf inf]}; + % opt.subsets = false(1,numel(data)); + + xmlfield0 = cfg_exbranch; + xmlfield0.tag = 'xmlfields'; + xmlfield0.name = 'Data field (complex)'; + xmlfield0.val = { ftitle , fname , fspec , ylim}; + xmlfield0.help = {'Specify set properties such as name or color' ''}; + + + xmlfield = cfg_entry; + xmlfield.tag = 'xmlfields'; + xmlfield.name = 'Data field (simple)'; + xmlfield.help = { + ['Specify field for data extraction that result in one value per file, e.g., ' ... + 'measures.vol_rel_CGW(1) to extract the first (CSF) volume value. '] ''}; + xmlfield.strtype = 's'; + xmlfield.num = [1 Inf]; + xmlfield.def = @(val) 'subjectmeasures.vol_TIV'; + + xmlfields = cfg_repeat; + xmlfields.tag = 'xmlfields'; + xmlfields.name = 'XML-fields'; + if expert + xmlfields.values = {xmlfield,xmlfield0,USMfield,QMfield,QRfield,SMfield,IMfield}; + else + xmlfields.values = {xmlfield,xmlfield0,QRfield,SMfield,IMfield}; + end + xmlfields.val = {}; + xmlfields.num = [1 Inf]; + xmlfields.forcestruct; + xmlfields.help = {'Specify manually grouped XML files.'}; + + + % ------ + + + % main figure title and xlabel (ylabel is defined by the fieldselector) + title = cfg_entry; + title.tag = 'title'; + title.name = 'Title'; + title.help = {'Title of the plot append to the field specific title definition.' + 'If the first char is a + than the title is added to automatic generated titles. ' + ''}; + title.strtype = 's'; + title.num = [0 inf]; + title.val = {''}; + + xlabel = name; + xlabel.tag = 'xlabel'; + xlabel.name = 'Xlabel'; + xlabel.val = {'groups'}; + xlabel.help = {'General group name, e.g., methods, versions, parameter A. ' ''}; + + + % opt.style = 0; % violin-plot: 0 - box plot; 1 - violin plot; 2 - violin + thin box plot + % opt.violin = 0; % violin-plot: 0 - box plot; 1 - violin plot; 2 - violin + thin box plot + style = cfg_menu; + style.tag = 'style'; + style.name = 'Plotting Style'; + style.labels = {'Box-plot','Violin-lot','Violin-box-lot','Density-plot'}; + style.values = {0 1 2 3}; + style.def = @(val) 0; + style.help = {'Type of data plot.' ''}; + + % colorset - menu? jet, hsv, ... + colorset = cfg_menu; + colorset.tag = 'colorset'; + colorset.name = 'Colorset'; + colorset.labels = {'Parula','Jet','HSV','Hot','Cool','Spring','Summer','Autumn','Winter','Lines','Prism'}; + colorset.values = {'parula','jet','hsv','hot','cool','spring','summer','autumn','winter','lines','prism'}; + colorset.def = @(val) 'jet'; + colorset.help = {'Default colors of the boxes.' ''}; + + + % figformat - + fsize = cfg_entry; + fsize.tag = 'fsize'; + fsize.name = 'Figure size in cm'; + fsize.help = { + 'Define height/size of the figure. Using only one value only defines the heigh. ' + 'Default matlab figure is [9.8778 7.4083] cm. ' + }; + fsize.strtype = 'r'; + fsize.num = [1 2]; + fsize.val = {[4.5 3.6]}; + + % opt.notched = 0; % thinner at median [0 1] with 1=0.5 + notched = cfg_menu; + notched.tag = 'notched'; + notched.name = 'Notched boxes'; + notched.labels = {'No','Yes'}; + notched.values = {0 1}; + notched.def = @(val) 0; + notched.help = {'Notched boxes that are thinner at the median.' ''}; + + % opt.symbol = '+o'; % outlier symbols + symbol = cfg_entry; + symbol.tag = 'symbol'; + symbol.name = 'Outlier symbols'; + symbol.help = {'Notched boxes that are thinner at the median.' ''}; + symbol.strtype = 's'; + symbol.num = [1 2]; + symbol.val = {'+o'}; + + % opt.maxwhisker = 1.5; % + maxwhisker = cfg_entry; + maxwhisker.tag = 'maxwhisker'; + maxwhisker.name = 'Maximum whisker'; + maxwhisker.help = {' '}; + maxwhisker.strtype = 'r'; + maxwhisker.num = [1 1]; + maxwhisker.val = {1.5}; + +% opt.sort = 0; % no sorting +% = 1; % sort groups (ascending) +% = 2; % sort groups (descending)[inactive] +% = [index]; % or by a index matrix + sortdata = cfg_menu; + sortdata.tag = 'sort'; + sortdata.name = 'Sort groups'; + sortdata.labels = {'No','Ascending','Descending'}; + sortdata.values = {0 1 2}; + sortdata.def = @(val) 0; + sortdata.help = {'' ''}; + +% opt.fill = 1; % filling of boxes: 0 - no filling; 0.5 - half-filled boxes; 1 - filled boxes + fill = cfg_menu; + fill.tag = 'fill'; + fill.name = 'Plot box'; + fill.labels = {'No filling','half-filling','full-filling'}; + fill.values = {0 0.5 1}; + fill.def = @(val) 1; + fill.help = {'Filling of boxes: 0 - no filling; 0.5 - half-filled boxes; 1 - filled boxes' ''}; + fill.hidden = expert<1; + + menubar = cfg_menu; + menubar.tag = 'menubar'; + menubar.name = 'Display MATLAB menu bars'; + menubar.labels = {'No','Yes'}; + menubar.values = {0 1}; + menubar.def = @(val) 0; + menubar.help = {'Print number of elements of each group in the groupname' ''}; + + close = cfg_menu; + close.tag = 'close'; + close.name = 'Close figures'; + close.labels = {'No','Yes'}; + close.values = {0 1}; + close.def = @(val) 0; + close.help = {'Close figures after export. ' ''}; + + +% opt.groupnum = 1; % add number of elements + groupnum = cfg_menu; + groupnum.tag = 'fill'; + groupnum.name = 'Number group elements'; + groupnum.labels = {'No','Yes'}; + groupnum.values = {0 1}; + groupnum.def = @(val) 1; + groupnum.help = {'Print number of elements of each group in the groupname' ''}; + groupnum.hidden = expert<1; + +% [opt.groupmin = 5;] % minimum number of non-nan-elements in a group [inactive] + +% opt.ygrid = 1; % activate y-grid-lines + ygrid = cfg_menu; + ygrid.tag = 'ygrid'; + ygrid.name = 'Plot y-grid lines'; + ygrid.labels = {'No','Yes'}; + ygrid.values = {0 1}; + ygrid.def = @(val) 1; + ygrid.help = {'Plot y-grid-lines' ''}; + ygrid.hidden = expert<1; + +% opt.gridline = '-'; % grid line-style + + +% opt.box = 1; % plot box + box = cfg_menu; + box.tag = 'box'; + box.name = 'Plot box'; + box.labels = {'No','Yes'}; + box.values = {0 1}; + box.def = @(val) 1; + box.help = {'' ''}; + +% opt.outliers = 1; % plot outliers + outliers = cfg_menu; + outliers.tag = 'outliers'; + outliers.name = 'Plot outliers'; + outliers.labels = {'No','Yes'}; + outliers.values = {0 1}; + outliers.def = @(val) 1; + outliers.help = {'' ''}; + outliers.hidden = expert<1; + +% opt.boxwidth = 0.8; % width of box + boxwidth = cfg_entry; + boxwidth.tag = 'boxwidth'; + boxwidth.name = 'Boxwidth'; + boxwidth.help = {'Main width of the boxes. ' ''}; + boxwidth.strtype = 'r'; + boxwidth.num = [1 1]; + boxwidth.val = {0.8}; + boxwidth.hidden = expert<1; + +% opt.groupcolor = [R G B]; % matrix with (group)-bar-color(s) +% use jet(numel(data)) +% or other color functions + groupcolormap = cfg_menu; + groupcolormap.tag = 'groupcolormap'; + groupcolormap.name = 'Colormap'; + groupcolormap.labels = {'jet','hsv','warm','cold'}; + groupcolormap.values = {'jet','hsv','warm','cold'}; + groupcolormap.def = @(val) 1; + groupcolormap.help = {'' ''}; + + % colormapdef + colormapdef = cfg_entry; + colormapdef.tag = 'colormapdef'; + colormapdef.name = 'Own colormap'; + colormapdef.help = {'Definition of a own colormap.' ''}; + colormapdef.strtype = 'r'; + colormapdef.num = [inf 3]; + colormapdef.val = {jet(10)}; + +% opt.symbolcolor = 'r'; % color of symbols + symbolcolor = cfg_menu; + symbolcolor.tag = 'symbolcolor'; + symbolcolor.name = 'Outlier color'; + symbolcolor.labels = {'red','green','blue','black','magenta','cyan','yellow'}; + symbolcolor.values = {'r','g','b','n','m','c','y'}; + symbolcolor.val = {'r'}; + symbolcolor.help = {'Color of outlier symbols.' ''}; + + +% opt.showdata = 0; % show data points: 0 - no; 1 - as points; 2 - as short lines (barcode plot) + showdata = cfg_menu; + showdata.tag = 'showdata'; + showdata.name = 'Show datapoints'; + showdata.labels = {'No','Points','Bars'}; + showdata.values = {0 1 2}; + showdata.def = @(val) 0; + showdata.help = {'Show data points as points or as short lines (barcode plot).' ''}; + +% opt.median = 2; % show median: 0 - no; 1 - line; 2 - with different fill colors + median = cfg_menu; + median.tag = 'median'; + median.name = 'Median style'; + median.labels = {'No','Line','Brightend'}; + median.values = {0 1 2}; + median.def = @(val) 2; + median.help = {'Show median as line or with different fill colors. ' ''}; + +% opt.edgecolor = 'none'; % edge color of box + boxedgecolor = cfg_menu; + boxedgecolor.tag = 'edgecolor'; + boxedgecolor.name = 'Use edgecolor for boxes'; + boxedgecolor.labels = {'No','Yes'}; + boxedgecolor.values = {'none','-n'}; + boxedgecolor.val = {'none'}; + boxedgecolor.help = {'Show median as line or with different fill colors. ' ''}; + +% opt.trans = 0.25; % transparency of the boxes + +% opt.sat = 0.50; % saturation of the boxes + + % opt.hflip = 0; + hflip = cfg_menu; + hflip.tag = 'hflip'; + hflip.name = 'Flip data'; + hflip.labels = {'No','Yes'}; + hflip.values = {0 1}; + hflip.def = @(val) 0; + hflip.help = {'Flip data orientation.' ''}; + + % opt.vertical = 1; % boxplot orientation + vertical = cfg_menu; + vertical.tag = 'vertical'; + vertical.name = 'Box orientation'; + vertical.labels = {'Horizontal','Vertical'}; + vertical.values = {0 1}; + vertical.def = @(val) 1; + vertical.help = {'Boxplot orientation. ' ''}; + + % fontsize + fontsize = cfg_entry; + fontsize.tag = 'FS'; + fontsize.name = 'Fontsize'; + fontsize.help = {'Main font size of the figure. ' ''}; + fontsize.strtype = 'r'; + fontsize.num = [1 1]; + fontsize.val = {10}; + + % main parameter structure passed to cat_plot_boxplot + opts = cfg_exbranch; + opts.tag = 'opts'; + opts.name = 'Options'; + opts.val = { title, xlabel , ... + ygrid, style , colorset , hflip , vertical , fsize, fontsize}; + % boxedgecolor + opts.help = {'Specify the thickness of specific ROIs.' ''}; + + extopts = opts; + extopts.tag = 'extopts'; + extopts.name = 'Extended options'; + extopts.val = { + showdata, sortdata, ... + maxwhisker, symbol, symbolcolor, ... + median, notched, boxwidth , boxedgecolor, fill, ... + menubar, ... + }; + +% * figure size +% * plot table +% E + + % ------ + type = cfg_menu; + type.tag = 'type'; + type.name = 'Export data type'; + type.labels = {'none','fig','png','epsc','fig + png','fig + png + epsc'}; + type.values = {'','fig','png','epsc','fig png','fig png epsc'}; + type.def = @(val) 'fig png epsc'; + type.help = {'Type of output files.' ''}; + + name.tag = 'name'; + name.name = 'Prefix'; + name.help = {'Additional prefix'}; + name.val = {''}; + + subdir.val = {'CAT_boxplot'}; + + % dpi + + output = cfg_exbranch; + output.tag = 'output'; + output.name = 'Output'; + output.val = {outdir,subdir,name,type,close}; + output.help = {''}; + + % ----- + boxplot = cfg_exbranch; + boxplot.tag = 'boxplot'; + boxplot.name = 'XML boxplot'; + if expert + boxplot.val = {datasets,xmlfields,opts,extopts,output}; + else + boxplot.val = {datasets,xmlfields,opts,output}; + end + boxplot.prog = @cat_plot_boxplot; + boxplot.hidden = expert<1; + %boxplot.vout = @vout_io_boxplot; + boxplot.help = {''}; + +return + +%_______________________________________________________________________ +function avg_img = conf_vol_average(data,outdir) +% image average +% ------------------------------------------------------------------------- + + % update input functions + data.name = 'Select images'; + data.help = {'Select images for calculating average.'}; + + outdir.help = {'Select a directory where files are written otherwise the path of the first image will be used.'}; + + % 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.' + 'If the field is left empty, i.e. set to '''', then the name of the 1st input image, preprended with ''i'', is used (change this letter in the spm_defaults if necessary).' + }; + output.strtype = 's'; + output.num = [0 Inf]; + output.val = {'avg.nii'}; + + weighting = cfg_entry; + weighting.tag = 'weighting'; + weighting.name = 'Weighting'; + weighting.strtype = 'r'; + weighting.val = {[]}; + weighting.num = [0 Inf]; + weighting.help = {'Weighting vector for input files that has to have the same number of entries as selected images. The weighing is normalized, e.g., a weighting [1 2 3] for 3 images means that the last image three counts 50%, image two 33.33% and image one 16.67%. If you want to use weighting maps see mimcalc batch.'}; + + write_var = cfg_menu; + write_var.tag = 'write_var'; + write_var.name = 'Save variance map'; + write_var.labels = {'No','Yes'}; + write_var.values = {0 1}; + write_var.def = @(val) 0; + write_var.help = {'Save (weighted) variance map with suffix ""_var"".' ''}; + + % main + avg_img = cfg_exbranch; + avg_img.tag = 'avg_img'; + avg_img.name = 'Image Average'; + avg_img.val = {data weighting write_var output outdir}; + avg_img.help = {'This function is for calculating the average of a set of images, which should be of same dimension and voxel size (i.e. after spatial registration).'}; + avg_img.prog = @cat_vol_avg; + avg_img.vout = @vout_avg; + +%_______________________________________________________________________ +function data2mat = conf_io_data2mat(data,outdir) +% ------------------------------------------------------------------------- +% Batch to save Matlab mat files of surface or resampled volume data for use +% with machine learning tools + + resolution = cfg_entry; + resolution.tag = 'resolution'; + resolution.name = 'Spatial resolution for resampling'; + resolution.strtype = 'r'; + resolution.num = [1 1]; + resolution.val = {4}; + resolution.help = { + 'Volume data can be saved with a lower spation resolution which is especially helpful with further use with machine learning tools such as relevance/support vector approaches or Gaussian Process models. Spatial structure of the data is not considered.' + 'Recommended resampling values are 3-8mm. For BrainAGE we obtained best prediction accuracy with values of 4 or 8mm.' + }; + + c = cfg_entry; + c.tag = 'c'; + c.name = 'Vector/Matrix'; + c.help = {'Vector or matrix of nuisance values'}; + c.strtype = 'r'; + c.num = [Inf Inf]; + + nuisance = cfg_repeat; + nuisance.tag = 'nuisance'; + nuisance.name = 'Nuisance variable'; + nuisance.values = {c}; + nuisance.num = [0 Inf]; + nuisance.help = {'This option allows for the specification of nuisance effects to be removed from the data. A potential nuisance parameter can be TIV if you check segmented data with the default modulation. In this case the variance explained by TIV will be removed from the data. Another meaningful nuisance effect is age. This parameter should be defined for all samples as one variable and may also contain several columns.'}; + + mask = data; + mask.tag = 'mask'; + mask.name = 'Select brain mask image'; + mask.def = @(val) cat_get_defaults('extopts.brainmask', val{:}); + mask.help = {'Select additionally mask image to exclude non-brain areas.';''}; + mask.num = [0 1]; + + data.name = 'Sample volume data'; + data.tag = 'data'; + data.filter = 'image'; + data.num = [1 Inf]; + data.help = {'Select spatially registered data. They must all have the same image dimensions, orientation, voxel size etc. Furthermore, it is recommended to use smoothed files with further use with machine learning tools.'}; + + sample = cfg_repeat; + sample.tag = 'sample'; + sample.name = 'Data'; + sample.values = {data}; + sample.num = [1 Inf]; + sample.help = {'Specify data for each sample. If you specify different samples a label variable will be also saved that decodes the samples.'}; + + vol_data = cfg_exbranch; + vol_data.tag = 'vol_data'; + vol_data.name = 'Volume data'; + vol_data.val = {sample,mask,resolution}; + vol_data.help = {''}; + + data.name = 'Sample surface data'; + data.filter = 'mesh'; + data.ufilter = 'resampled'; + data.help = {'Select resampled and smoothed surface data. They must all have the same mesh size (32k or 164k).'}; + + sample.values = {data}; + surf_data = cfg_exbranch; + surf_data.tag = 'surf_data'; + surf_data.name = 'Surface data'; + surf_data.val = {sample}; + surf_data.help = {''}; + + data_type = cfg_choice; + data_type.tag = 'data_type'; + data_type.name = 'Select data type'; + data_type.values = {vol_data surf_data}; + data_type.val = {vol_data}; + data_type.help = {'Choose between volume and surface data.'}; + + fname = cfg_entry; + fname.name = 'Filename'; + fname.tag = 'fname'; + fname.val = {'Data.mat'}; + fname.strtype = 's'; + fname.help = {'Filename to save data matrix.'}; + + data2mat = cfg_exbranch; + data2mat.tag = 'data2mat'; + data2mat.name = 'Save volume or surface data as mat-file'; + data2mat.val = {data_type,nuisance,fname,outdir}; + data2mat.prog = @cat_io_data2mat; + data2mat.vout = @vout_io_data2mat; + data2mat.help = { + 'Save spatially registered volume or resampled surface data as Matlab data matrix for further use with machine learning tools.' + 'Volume data can be optionally masked to remove non-brain areas.' + 'A mat-file will be saved with the following parameters:' + ' Y - data matrix with size number of subjects x number of voxels/vertices' + ' label - label of samples' + ' ind - index for volume or surface data inside mask' + ' dim - dimension of original data' + }; + +%_______________________________________________________________________ +function vf = vout_defs(job) + +PU = job.field1; +PI = job.images; + +vf = cell(numel(PI),1); +for i=1:numel(PU) % ########### RD202201: i is not used + for m=1:numel(PI) + [pth,nam,ext,num] = spm_fileparts(PI{m}); + + switch job.modulate + case 2 + filename = fullfile(pth,['m0w' nam ext num]); + case 1 + filename = fullfile(pth,['mw' nam ext num]); + case 0 + filename = fullfile(pth,['w' nam ext num]); + otherwise + error('incorrect - DEP') + end + vf{m} = filename; + end +end + +return; +%_______________________________________________________________________ +function vf = vout_defs2(job) + + PU = job.field; + PI = job.images; + + vf = cell(numel(PU),numel(PI)); + for i=1:numel(PU) + for m=1:numel(PI) + [pth,nam,ext,num] = spm_fileparts(PI{m}{i}); + + switch job.modulate + case 2 + filename = fullfile(pth,['m0w' nam ext num]); + case 1 + filename = fullfile(pth,['mw' nam ext num]); + case 0 + filename = fullfile(pth,['w' nam ext num]); + otherwise + error('incorrect - DEP') + end + vf{i,m} = filename; + end + end + +return; +%_______________________________________________________________________ +function cdep = vout_urqio(job) + %% + cdep = cfg_dep; + if job.output.r1 + cdep(end+1) = cfg_dep; + cdep(end).sname = 'R1 Images'; + cdep(end).src_output = substruct('.','data','()',{1},'.',[job.opts.prefix 'r1_'],'()',{':'}); + cdep(end).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); + end + if job.output.pd + cdep(end+1) = cfg_dep; + cdep(end).sname = 'PD Images'; + cdep(end).src_output = substruct('.','data','()',{1},'.',[job.opts.prefix 'pd_'],'()',{':'}); + cdep(end).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); + end + if job.output.t1 + cdep(end+1) = cfg_dep; + cdep(end).sname = 'T1 Images'; + cdep(end).src_output = substruct('.','data','()',{1},'.',[job.opts.prefix 't1_'],'()',{':'}); + cdep(end).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); + end + if job.output.r2s==1 || job.output.r2s==3 + cdep(end+1) = cfg_dep; + cdep(end).sname = 'R2s nobc Images'; + cdep(end).src_output = substruct('.','data','()',{1},'.',[job.opts.prefix 'nobc_r2s_'],'()',{':'}); + cdep(end).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); + end + if job.output.r2s==2 || job.output.r2s==3 + cdep(end+1) = cfg_dep; + cdep(end).sname = 'R2s bc Images'; + cdep(end).src_output = substruct('.','data','()',{1},'.',[job.opts.prefix 'bc_r2s_'],'()',{':'}); + cdep(end).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); + end + if job.output.bv + cdep(end+1) = cfg_dep; + cdep(end).sname = 'Blood Vessel Images'; + cdep(end).src_output = substruct('.','data','()',{1},'.',[job.opts.prefix 'bv_'],'()',{':'}); + cdep(end).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); + end + if numel(cdep)>1 + cdep(1)=[]; + end +%% +return; +%_______________________________________________________________________ +function dep = vout_report(varargin) + dep(1) = cfg_dep; + dep(1).sname = 'CAT PDF Report'; + dep(1).src_output = substruct('.','files','()',{':'}); + dep.tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); + dep(2) = cfg_dep; + dep(2).sname = 'CAT JPG Report'; + dep(2).src_output = substruct('.','filesj','()',{':'}); + dep.tgt_spec = cfg_findspec({{'filter','any','strtype','e'}}); +return; +%_______________________________________________________________________ +function dep = vout_sanlm(varargin) + %job.returnOnlyFilename = 1; + %vf = cat_vol_sanlm(job); + + dep(1) = cfg_dep; + dep(1).sname = 'SANLM Images'; + dep(1).src_output = substruct('.','files'); + dep(1).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); +return; +%_______________________________________________________________________ +function dep = vout_maskimg(varargin) + %job.returnOnlyFilename = 1; + %vf = cat_vol_maskimage(job); + + dep = cfg_dep; + dep.sname = 'Masked Images'; + dep.src_output = substruct('.','files'); + dep.tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); +return; +%_______________________________________________________________________ +function cdep = vout_headtrimming(job) + job.returnOnlyFilename = 1; + %vf = cat_vol_headtrimming(job); + vf = job; + cdep = cfg_dep; + + if isfield(vf.image_selector,'manysubjects') + cdep(end).sname = 'source images'; + cdep(end).src_output = substruct('.','image_selector','.','manysubjects','.','simages'); + cdep(end).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); + if isfield(vf.image_selector.manysubjects,'oimages') + for i=1:numel(vf.image_selector.manysubjects.oimages) + cdep(end+1) = cfg_dep;%#ok + cdep(end).sname = sprintf('other images %d',i); + cdep(end).src_output = substruct('.','image_selector','.','manysubjects','.','oimages','{}',{i}); + cdep(end).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); + end + end + elseif isfield(vf.image_selector,'subjectimages') + % image-wise + % - first image + cdep(end).sname = sprintf('first images of all subjects'); + cdep(end).src_output = substruct('.','image_selector','.','firstimages'); + cdep(end).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); + % - other images + cdep(end+1) = cfg_dep; + cdep(end).sname = sprintf('other images of all subjects'); + cdep(end).src_output = substruct('.','image_selector','.','otherimages'); + cdep(end).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); + % subject-wise ... + % the substruct seems to be correct, but it does not work, + % probably because each cdep entry has to be unique + % RD201810 + %{ + for si=1:numel(vf.image_selector.subjectimages) + cdep(end+1) = cfg_dep;%#ok + cdep(end).sname = sprintf('all imgages of subject %d',si); + cdep(end).src_output = substruct('.','image_selector','.','subjectimages','{}',{si}); + cdep(end).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); + end + % single scans + for si=1:numel(vf.image_selector.subjectimages) + for fi=1:numel(vf.image_selector.subjectimages{si}) + cdep(end+1) = cfg_dep;%#ok + cdep(end).sname = sprintf('subject %d image %d',si,fi); + cdep(end).src_output = substruct('.','image_selector','.','subjectimages','{}',{si},'()',{fi}); + cdep(end).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); + end + end + %} + else + for i=1:numel(vf.images) + cdep(i) = cfg_dep; + cdep(i).sname = sprintf('image %d',i); + cdep(i).src_output = substruct('.','images','{}',{i}); + cdep(i).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); + end + end + +return; + +%_______________________________________________________________________ +function dep = vout_volctype(varargin) + % job.returnOnlyFilename = 1; + % vf = cat_io_volctype(job); + + dep = cfg_dep; + dep.sname = 'Converted Images'; + dep.src_output = substruct('.','files','()',{':'}); + dep.tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); +return; + +%_______________________________________________________________________ +function dep = vout_mimcalc(varargin) + dep = cfg_dep; + dep.sname = 'Multi-subject Image Calculator'; + dep.src_output = substruct('.','Pname'); + dep.tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); +return + +%_______________________________________________________________________ +function dep = vout_createTPM(varargin) + dep(1) = cfg_dep; + dep(1).sname = 'TPM'; + dep(1).src_output = substruct('.','tpm','()',{':'}); + dep(1).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); + + dep(end+1) = cfg_dep; + dep(end).sname = 'T1'; + dep(end).src_output = substruct('.','t1','()',{':'}); + dep(end).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); + + dep(end+1) = cfg_dep; + dep(end).sname = 'atlases'; + dep(end).src_output = substruct('.','atlas','()',{':'}); + dep(end).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); + + dep(end+1) = cfg_dep; + dep(end).sname = 'brainmask'; + dep(end).src_output = substruct('.','brainmask','()',{':'}); + dep(end).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); +return; + +%_______________________________________________________________________ +function dep = vout_createTPMlong(varargin) + dep = cfg_dep; + dep.sname = 'Longitudinal TPMs'; + dep.src_output = substruct('.','tpm','()',{':'}); + dep.tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); + + dep = cfg_dep; + dep.sname = 'Longitudinal TPMs Tissues'; + dep.src_output = substruct('.','tpmtiss','()',{':'},'()',{':'}); + dep.tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); +return; + +%_______________________________________________________________________ +function dep = vout_conf_longBiasCorr(varargin) + dep = cfg_dep; + dep.sname = 'Longitudinal Bias Corrected'; + dep.src_output = substruct('.','bc','()',{':'}); + dep.tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); +return + +%_______________________________________________________________________ +function dep = vout_resize(varargin) + dep = cfg_dep; + dep.sname = 'Resized'; + dep.src_output = substruct('.','res','()',{':'}); + dep.tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); +return; +%_______________________________________________________________________ +function dep = vout_qa(job) + if 0 % old + if isfield(job,'data') + s = cellstr(char(job.data)); dep = s; + elseif isfield(job,'images') + s = cellstr(char(job.images)); dep = s; + else + s = {}; + dep = {}; + end + for i=1:numel(s) + [pth,nam,ext,num] = spm_fileparts(s{i}); + if isfield(job,'prefix') % old + dep{i} = fullfile(pth,[job.prefix,nam,ext,num]); + elseif isfield(job,'opts') && isfield(job.opts,'prefix') + dep{i} = fullfile(pth,[job.opts.prefix,nam,ext,num]); + else + dep{i} = fullfile(pth,[nam,ext,num]); + end + end + else + dep = cfg_dep; + dep.sname = 'CATQC'; + dep.src_output = substruct('.','xmls','()',{':'}); + dep.tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); + end +return; + +%------------------------------------------------------------------------ +function dep = vout_avg(job) + dep = cfg_dep; + if ~ischar(job.output) || strcmp(job.output, '') + dep.sname = 'Average Image'; + else + dep.sname = sprintf('Average Image %s', job.output); + end + dep.src_output = substruct('.','files'); + dep.tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); +return + +%------------------------------------------------------------------------ +function dep = vout_stat_TIV(varargin) + dep = cfg_dep; + dep.sname = 'TIV'; + dep.src_output = substruct('.','calcvol','()',{':'}); + dep.tgt_spec = cfg_findspec({{'strtype','e','strtype','r'}}); +return + +%_______________________________________________________________________ +function dep = vout_io_data2mat(varargin) + dep = cfg_dep; + dep.sname = 'Saved mat-file'; + dep.src_output = substruct('.','fname'); + dep.tgt_spec = cfg_findspec({{'filter','mat','strtype','e'}}); +return; + +%------------------------------------------------------------------------ +function cdep = vout_realign(job) + ind = 1; + if job.write_avg + cdep(ind) = cfg_dep; + cdep(ind).sname = 'Midpoint Average'; + cdep(ind).src_output = substruct('.','avg','()',{':'}); + cdep(ind).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); + ind = ind + 1; + end + if job.write_rimg + cdep(ind) = cfg_dep; + cdep(ind).sname = 'Realigned images'; + cdep(ind).src_output = substruct('.','rimg','()',{':'}); + cdep(ind).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); + ind = ind + 1; + end + if isfield(job.reg,'nonlin') && job.reg.nonlin.write_jac + cdep(ind) = cfg_dep; + cdep(ind).sname = 'Jacobian Diff'; + cdep(ind).src_output = substruct('.','jac','()',{':'}); + cdep(ind).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); + ind = ind + 1; + end + if isfield(job.reg,'nonlin') && job.reg.nonlin.write_def + cdep(ind) = cfg_dep; + cdep(ind).sname = 'Deformation (1)'; + cdep(ind).src_output = substruct('.','def1','()',{':'}); + cdep(ind).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); + ind = ind + 1; + + cdep(ind) = cfg_dep; + cdep(ind).sname = 'Deformation (2)'; + cdep(ind).src_output = substruct('.','def2','()',{':'}); + cdep(ind).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); + end + +return + +%------------------------------------------------------------------------ +function dep = vout_stat_spm2x(varargin) + dep = cfg_dep; + dep.sname = 'Transform & Threshold spm volumes'; + dep.src_output = substruct('.','Pname'); + dep.tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); +return + +%------------------------------------------------------------------------ +function dep = vout_stat_spm2x_surf(varargin) + dep = cfg_dep; + dep.sname = 'Transform & Threshold spm surfaces'; + dep.src_output = substruct('.','Pname'); + dep.tgt_spec = cfg_findspec({{'filter','gifti','strtype','e'}}); +return + +%------------------------------------------------------------------------ +function dep = vout_stat_getCSVXML(job) + dep = cfg_dep; + + job.dep = 1; + if ( isfield(job,'xmlfile') && ~isempty( job.files ) && ~isempty(job.files{1}) ) || ... + ( isfield(job,'csvfile') && ~isempty( job.csvfile ) && ~isempty(job.csvfile{1}) ) + out = cat_stat_getCSVXMLfield(job); + + FN = fieldnames(out); + %if isfield(job,'fields') && iscell(job.fields) + for fni = 1:numel(FN) + dep(end + (fni>1)) = cfg_dep; + dep(end).sname = sprintf('%s',FN{fni}); + dep(end).src_output = substruct('.',FN{fni},'()',{':'}); + dep(end).tgt_spec = cfg_findspec({}); %{{'filter',,'strtype','e'}}); + end + %end + end +return +%_______________________________________________________________________ +function dep = vout_mp2rage(varargin) + %job.returnOnlyFilename = 1; + %vf = cat_vol_mp2rage(job); + + dep = cfg_dep; + dep.sname = 'Corrected Images'; + dep.src_output = substruct('.','files'); + dep.tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); +return; +%_______________________________________________________________________ +function dep = vout_file_move(job) + +% Define virtual output for cfg_run_move_file. Output can be passed on to +% either a cfg_files or an evaluated cfg_entry. +% +% 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$ + +rev = '$Rev$'; %#ok + +if ~isfield(job.action,'delete') + dep = cfg_dep; + dep.sname = 'Moved/Rename/Copied Files'; + dep.src_output = substruct('.','files'); + dep.tgt_spec = cfg_findspec({{'class','cfg_files','strtype','e'}}); +else + dep = []; +end +return +function dep = vout_vol_savg(job) +% list of average images +% list of correced images ? + + cdep = cfg_dep; + + cdep(end).sname = 'AnyAvg Average Map'; + cdep(end).src_output = substruct('.','avg','()',{':'}); + cdep(end).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); + + if isfield(job,'writeLabelmap') && job.writeLabelmap + cdep(end).sname = 'AnyAvg Label Map'; + cdep(end).src_output = substruct('.','Yp0','()',{':'}); + cdep(end).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); + end + if isfield(job,'writeLabelmap') && job.writeBrainmask + cdep(end).sname = 'AnyAvg Brain Mask'; + cdep(end).src_output = substruct('.','Yb','()',{':'}); + cdep(end).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); + end + + dep = cdep; +return","MATLAB" +"Neurology","ChristianGaser/cat12","cat_stat_spm.m",".m","4212","120","function varargout = cat_stat_spm(SPM) +% Workaround to use fsaverage surface as SurfaceID (for displaying results) +% spm_spm is used to estimate the model and the mesh of the 1st file in the model +% is replaced by the fsaverage brain because this mesh is used for overlaying +% results. +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +if nargin == 0 + P = spm_select([1 Inf],'^SPM\.mat$','Select SPM.mat file(s)'); +elseif exist('SPM','var') && isfield(SPM,'spmmat') + P = char(SPM.spmmat); spmmat = SPM.spmmat; +elseif ischar(SPM) + P = SPM; +end + +if exist('P','var') + for i=1:size(P,1) + swd = spm_file(P(i,:),'fpath'); + load(fullfile(swd,'SPM.mat')); + SPM.swd = swd; + cat_stat_spm(SPM); + end + if nargout && exist('spmmat','var') + varargout{1}.spmmat = spmmat; + end + return +end + +if ~isfield(SPM,'xY') + error(sprintf('SPM.mat was not correctly saved. Please check that you have set the following flag in spm_defaults if your files are > 2GB:\ndefaults.mat.format = ''-v7.3''')); +end + +fmt = spm_get_defaults('mat.format'); +s = whos('SPM'); +if s.bytes > 2147483647, fmt = '-v7.3'; end + +% older formats don't support large files +spm_get_defaults('mat.format',fmt); + +% check for 32k meshes +if SPM.xY.VY(1).dim(1) == 32492 || SPM.xY.VY(1).dim(1) == 64984 + fsavgDir = fullfile(fileparts(mfilename('fullpath')),'templates_surfaces_32k'); +else + fsavgDir = fullfile(fileparts(mfilename('fullpath')),'templates_surfaces'); +end + +% select underlying surface and prefer shooting template +job.surftype = 1; +surftype = {'freesurfer',cat_get_defaults('extopts.shootingsurf')}; +if ~exist(fullfile(fsavgDir, ['lh.central.' surftype{job.surftype} '.gii'])) + job.surftype = 2; +end + +% check that folder exist and number of vertices fits +if exist(fsavgDir,'dir') == 7 && (SPM.xY.VY(1).dim(1) == 163842 || SPM.xY.VY(1).dim(1) == 327684 || ... + SPM.xY.VY(1).dim(1) == 655368) || SPM.xY.VY(1).dim(1) == 32492 || SPM.xY.VY(1).dim(1) == 64984 + + [pp,ff] = spm_fileparts(SPM.xY.VY(1).fname); + + % find mesh string + hemi_ind = []; + hemi_ind = [hemi_ind strfind(ff,'mesh.')]; + if ~isempty(hemi_ind) + + SPM.xY.VY(1).private.private.metadata = struct('name','SurfaceID','value',fullfile(fsavgDir, ['mesh.central.' surftype{job.surftype} '.gii'])); + M0 = gifti({fullfile(fsavgDir, ['lh.central.' surftype{job.surftype} '.gii']), fullfile(fsavgDir, ['rh.central.' surftype{job.surftype} '.gii'])}); + G.faces = [M0(1).faces; M0(2).faces+size(M0(1).vertices,1)]; + G.vertices = [M0(1).vertices; M0(2).vertices]; + + % cerebellar lobes? + if SPM.xY.VY(1).dim(1) == 655368 + M0 = gifti({fullfile(fsavgDir, 'cb.central.freesurfer.gii')}); %, fullfile(fsavgDir, 'rc.central.freesurfer.gii')}); + G.faces = [G.faces; M0(1).faces+2*size(M0(1).vertices,1)]; % ; M0(2).faces+3*size(M0(1).vertices,1)]; + G.vertices = [G.vertices; M0(1).vertices]; % ; M0(2).vertices]; + end + clear M0; + + SPM.xVol.G = G; + + % remove memory demanding faces and vertices which are not necessary + for i=1:length(SPM.xY.VY) + SPM.xY.VY(i).private.faces = []; + SPM.xY.VY(i).private.vertices = []; + end + + else + + % find lh|rh string + hemi_ind = []; + hemi_ind = [hemi_ind strfind(ff,'lh.')]; + hemi_ind = [hemi_ind strfind(ff,'rh.')]; + hemi = ff(hemi_ind:hemi_ind+1); + if ~isempty(hemi) + SPM.xY.VY(1).private.private.metadata = struct('name','SurfaceID','value',fullfile(fsavgDir,[hemi '.central.' surftype{job.surftype} '.gii'])); + G = fullfile(fsavgDir,[hemi '.central.' surftype{job.surftype} '.gii']); + SPM.xVol.G = gifti(G); + + % remove memory demanding faces and vertices which are not necessary + for i=1:length(SPM.xY.VY) + SPM.xY.VY(i).private.faces = []; + SPM.xY.VY(i).private.vertices = []; + end + + end + end +end + +if nargout>0 + varargout{1} = spm_spm(SPM); +else + spm_spm(SPM); +end +end","MATLAB" +"Neurology","ChristianGaser/cat12","compile.m",".m","21901","568","function varargout = compile(comp,test,verb) +% ______________________________________________________________________ +% Function to compile and test cat12 c-functions. +% Testing include a standard call of the function with simple image and +% small a small test of the eximated values. +% +% [ok_all[,ok_tst,result_tst]] = compile([comp,test,verb]) +% +% comp .. compile functions ([0|1]; default=1) +% test .. test compiled functions ([0|1]; default=1) +% verb .. display progress ([0|1]; default=1) +% +% ok_all .. true if all functions are compiled (and tested if test==1) +% successfully +% ok_tst .. logical matrix with the RMS error of the tests +% (only if test==1) +% result_tst .. vector with the RMS error of the tests +% (only if test==1) +% (the error gives no information about the accuracy of the +% function, as far as comparison function do somethimes +% only similar things and the test cases are very simple) +% ______________________________________________________________________ +% $Id$ + +%#ok<*NASGU,*ASGLU,*LERR,*TRYNC> + + + if strcmpi(spm_check_version,'octave') + mexcmd = 'mkoctfile --mex'; + else + + fprintf('-----------------------------------------------------------------------------------\n'); + fprintf('Please check that for new mex-files functions such as mxCreateNumericArray has the \n'); + fprintf('right data type for the variable dims (const mwSize*). Otherwise compilation with \n'); + fprintf('Matlab >= R2017a will be not successful!\n'); + fprintf('-----------------------------------------------------------------------------------\n\n'); + + if (strcmp(mexext,'mexmaci64') || strcmp(mexext,'mexmaca64')) && verLessThan('matlab','9.2') + warning('WARNING: Matlab version should be at least R2017a for compilation under Mac.'); + end + + mexcmd = 'mex'; + end + + try % failed in older MATLABs + rng('default'); rng(13); % fix random numbers + end + + if ~exist('comp','var'), comp=1; end + if ~exist('test','var'); test=1; end + if ~exist('verb','var'); verb=2; end + + expert = cat_get_defaults('extopts.expertgui'); + olddir = pwd; + catdir = olddir; + + try + rng('default'); % restore default + end + + % reset colorfunction + cat_io_cprintf('silentreset') + + %% compiling c-functions + if comp==1 + + if 0 % strcmp(mexext,'mexmaci64') + mexflag=['-Dchar16_t=UINT16_T CFLAGS=''$CFLAGS -Wall -ansi -pedantic ' ... + '-Wextra'' CPPLAGS=''$CPPFLAGS -Wall -ansi -pedantic -Wextra''']; + elseif strcmpi(spm_check_version,'octave') + mexflag=' -O -DOCTAVE'; + else + mexflag=' -O -largeArrayDims COPTIMFLAGS=''-O3 -fwrapv -DNDEBUG'''; + end + + % main c-functions + nc{1} = { + 'cat_amap.c Kmeans.c Amap.c MrfPrior.c Pve.c vollib.c' + 'cat_vol_median3.c' + 'cat_vol_median3c.c' + 'cat_vol_laplace3.c' + 'cat_vol_downcut.c' + 'cat_vol_laplace3R.c' + 'cat_vol_gradient3.c' + 'cat_vol_simgrow.c' + 'cat_vol_localstat.c' + 'cat_vol_pbtp.c' + 'cat_vol_interp3f.cpp' + 'cat_vol_eidist.c' + 'cat_vol_genus0.c genus0.c' + 'cat_vbdist.c' + 'cat_ornlm.c ornlm_float.c' + 'cat_sanlm.c sanlm_float.c' + }; + % internal c-functions + % does not yet work for octave + if ~strcmpi(spm_check_version,'octave') && exist(fullfile(catdir,'internal'),'dir') + nc{2} = { + 'cat_vol_cMRegularizarNLM3D.c' + }; + end + rc = cell(1,2); % results of c-function comiling + rcc = cell(1,2); % results of c-function comiling + nce = cell(1,2); % number of errors + ncw = cell(1,2); % number of warnings + + %% compile main c-functions + for nci=1:numel(nc) + if verb, fprintf('Compiling c-functions:\n'); end + for ncj = 1:numel(nc{nci}) + try + rcc{nci}(ncj) = 0; + if nci==1 + cd(catdir) + %try + + % clear function if it was maybe used before + if strcmpi(spm_check_version,'octave') + % replace expected endings to clear the function + str = strrep( strrep( nc{nci}{ncj}, '.cpp' , ''), '.c' , ''); + evalc(['clear ' str]); + + % not working yet - see also cat_io_xml + %{ + pkglist = pkg('list'); + if all( strfind( [pkglist{:}.name] , 'io') == 0 ) + pkg install -forge io + end + pkg load io + %} + end + + rc{nci}{ncj} = evalc([mexcmd ' ' mexflag ' ' nc{nci}{ncj}]); + %{ + catch + rcc{nci}(ncj) = 1; + err = lasterror; + rc{nci}{ncj} = err.message; + cd(catdir) + rc{nci}{ncj} = evalc(['mex ' nc{nci}{ncj}]); + end + %} + else + cd(fullfile(catdir,'internal')); + [pp,ff,ee] = spm_fileparts(nc{nci}{ncj}); + if strcmp(nc{nci}{ncj},'cat_vol_cMRegularizarNLM3D.c') + % additional windows version + if any(strcmp({'mexw32','mexw64'},mexext)) + rc{nci}{ncj} = evalc([mexcmd ' ' mexflag ' ' ff 'w' ee]); + movefile([ff 'w' mexext],[ff mexext]); + else + rc{nci}{ncj} = evalc([mexcmd ' ' mexflag ' ' nc{nci}{ncj}]); + end + else + rc{nci}{ncj} = evalc([mexcmd ' ' mexflag ' ' nc{nci}{ncj}]); + end + cd(catdir) + end + catch + rcc{nci}(ncj) = 2; + err = lasterror; + rc{nci}{ncj} = err.message; + cd(catdir) + end + + % check for errors and warnings + ncw{nci}(ncj) = numel(strfind(lower(rc{nci}{ncj}),'warning')); + % space is necessary because otherwise strings such as ""errorDocCallback"" are + % also indicated as error + nce{nci}(ncj) = numel(strfind(rc{nci}{ncj},'error '))+numel(strfind(rc{nci}{ncj},'errors ')); + + % correct for conclusion + nce{nci}(ncj) = nce{nci}(ncj) - 2*(nce{nci}(ncj)>0); + ncw{nci}(ncj) = ncw{nci}(ncj) - 2*(ncw{nci}(ncj)>0); + + % display result + if verb + if rcc{nci}(ncj)==1 + cat_io_cprintf([0.7 0.7 0.0],... + sprintf('%4d) Compiling of %s failed with mexopt! \n',... + ncj,['""' nc{nci}{ncj} '""'])); + elseif rcc{nci}(ncj)==2 + cat_io_cprintf([0.6 0.0 0.0],... + sprintf('%4d) Compiling of %s failed! \n',... + ncj,['""' nc{nci}{ncj} '""'])); + else + if nce{nci}(ncj)==0 + if ncw{nci}(ncj)==0 || expert==0 + cat_io_cprintf([0.0 0.5 0.0],... + sprintf('%4d) Compiling of %s successful!\n',... + ncj,['""' nc{nci}{ncj} '""'])); + else + cat_io_cprintf([0.7 0.7 0.0],... + sprintf('%4d) Compiling of %s successful! (%d warning(s))\n',... + ncj,['""' nc{nci}{ncj} '""'],ncw{nci}(ncj))); + end + else + cat_io_cprintf([0.6 0.0 0.0],... + sprintf('%4d) Compiling of %s failed! (%d error(s))\n',... + ncj,['""' nc{nci}{ncj} '""'],nce{nci}(ncj))); + end + end + end + end + end + + %% + for nci=1:numel(nc) + if (verb>0 && sum(cellfun(@(x) sum(x),nce))>0) || ... + (verb>1 && sum(cellfun(@(x) sum(x),ncw))>0) || verb>2 + fprintf('\n\nCompiling c-functions errors/warnings:\n'); + end + for ncj = 1:numel(nc{nci}) + if (nce{nci}(ncj)>0 && verb) || (ncw{nci}(ncj)>0 && verb>1) || verb>2 + cat_io_cprintf([0.6 0.0 0.0],... + sprintf('%4d) Compiling of %s with errors or warnings! (%d error(s), %d warning(s))\n',... + ncj,['""' nc{nci}{ncj} '""'],nce{nci}(ncj),ncw{nci}(ncj))); + fprintf('%s\n\n',rc{nci}{ncj}); + end + end + if numel(nc{nci})==0 + fprintf('%s\n\n',rc{nci}{ncj}); + end + end + end + + + + + + %% test c-functions + if test==1 + + % testdata + % empty image with a NaN voxel + d0 = rand(10,10,10,'single'); d0(5,5,5) = NaN; + % simple segment image for distance and filter tests + d1 = zeros(10,10,10,'single'); d1(3:8,:,:)=1; d1(9:10,:,:)=2; d1(5,5,5) = NaN; + d2 = zeros(10,10,10,'single'); d2(3,:,:)=0.8; d2(4:7,:,:)=1; + d2(8,:,:)=1.2; d2(9:10,:,:)=2; d2(5,5,5) = NaN; + % more complex segment image for distance and filter tests + d3 = zeros(10,10,10,'single'); d3(3:8,:,:)=1; d3(9:10,:,:)=2; + d3(3,:,:)=0.25; d3(8,:,:)=1.75; d3(5,5,5) = NaN; + d4 = zeros(10,10,10,'single'); d4(3,:,:)=0.2; d4(4:8,:,:)=1; d4(9,:,:)=1.2; + d4(10,:,:)=2; d4(2:7,5,:) = 0; d4(6:9,[1:2,8:10],:) = 2; d4(8,8,:) = 1; + d5 = d4; d5(2:3,6:7,:) = 0.5; + %% + d6 = zeros(13,13,10,'single'); d6(3,:,:)=0.2; d6(4:13,:,:)=1; d6(14,:,:)=1.2; d6(4,6:8,:)=0.5; + d6(15,:,:)=2; d6(2:5,7,:) = 0.1; d6(5:10,7,:) = 0.8; d6(10:end-4,7,:) = 0.3; + d6(6:end-1,[1:4,end-3:end],:) = 2; d6(13,10,:) = 1; d6(6:12,10,:) = 1.8; d6(2:3,8:9,:) = 0.7; + %if (verb>2), ds('d2','',1,d6,Ycsfdi/3*2,Ywmdi/3*2,Ygmti/2,5); colormap jet; end + d6(2:3,6:7,:) = 0.5; + %% ground truth distance map for the d1 map + dc = zeros(10,10,10,'single'); for si=3:8; dc(si,:,:)=si-2.5; end; dc(5,5,5) = NaN; % csf distance + dw = zeros(10,10,10,'single'); for si=3:8; dw(si,:,:)=8.5-si; end; dw(5,5,5) = NaN; % wm distance + dcube10 = zeros(10,10,10,'single'); dcube10(2:end-1,2:end-1,2:end-1) = 1; + dcube = zeros(12,12,12,'single'); dcube(4:end-3,4:end-3,4:end-3) = 1; d1(6,6,6) = NaN; + dcubetr = dcube; + dcubetr(2,5:7,5) = 1; dcubetr(3,[5,7],5) = 1; % handle + dcubetr(end-4,end-4:end-3,5) = 0; dcubetr(end-3,end-4,5) = 0; dcubetr(6,1:end,5) = 0; % hole + + ntests = 16; % number of tests + ni = 0; % counter + n = cell(ntests, 1); % testname + d = cell(ntests, 1); % result of the tested function + r = nan(ntests,1); % assessed result + s = false(ntests, 1); % accepted result + + rms = @(x) cat_stat_nanmean( x(:).^2 )^0.5; % RMS error function + %nstd = @(x) cat_stat_nanstd( x(:) ); % STD function + + + %% Median + % Test the noise reduction by the median filter in the segment image. + % ds('l2','',1,d0,d1/2,d1/2 + (d0-0.5)/10,d{ni}/2,5) + ni = ni + 1; + n{ni} = 'cat_vol_median3'; + d{ni} = cat_vol_median3(d1 + (d0-0.5)/10); + r(ni) = rms(d{ni} - d1); + s(ni) = r(ni)<0.05; + %% Median function for label images + % ds('d2','',1,d0,d1/2,round(d1 + (d0-0.5)*1.2)/2,d{ni}/2,5) + ni = ni + 1; + n{ni} = 'cat_vol_median3c'; % for label maps + d{ni} = cat_vol_median3c(single(round(d1 + (d0-0.5)*1.0))); % + r(ni) = rms(d{ni} - d1); + s(ni) = r(ni)<0.05; + + + %% NLM + % Test reminding noise; + % ds('l2','',1,d0,d1/2,d1/2 + (d0+0.5)/10,d{ni}/2,10) + ni = ni + 1; + n{ni} = 'cat_ornlm'; + d{ni} = cat_ornlm(d1 + (d0-0.5)/10,3,1,0.05); + r(ni) = rms(d1 - d{ni}); + s(ni) = r(ni)<0.05; + % sanlm + ni = ni + 1; + n{ni} = 'cat_sanlm'; + d{ni} = d1 + (d0-0.5)/10; + cat_sanlm(d{ni},3,1); + r(ni) = rms(d1 - d{ni}); + s(ni) = r(ni)<0.05; + + + %% AMAP + % Test peak estimation + % - not only a sulci, we need a brain ... + % - amap do not like nans etc... + % ds('d2','',1,t1,t1c,seg/3,d{ni}/3,10) + ni = ni + 1; + n{ni} = 'cat_amap'; + ip = 0; + res = [6,6,4]; + t1 = (1 + d5)/3 + (d0-0.5)/10; t1(isnan(t1)) = 1/3; t1 = repmat(t1,res); t1 = interp3(t1,ip); + seg = d5+1; seg(isnan(seg)) = 1; seg = repmat(seg,res); seg = interp3(seg,ip); + obj = zeros(size(t1),'single'); obj(4:end-3,4:end-3,4:end-3) = 1; + t1 = t1 .* obj; seg = seg .* obj; + vx_vol = 8*[1 1 1]/(ip+1); n_iters = 16; sub = round(16/min(vx_vol)); + bias_fwhm = 60; init_kmeans = 0; mrf = 0.1; iters_icm = 50; n_classes = 3; pve = 5; + t1c = double(t1+0); segc = cat_vol_ctype(seg+0); + [txt,prob,mean] = evalc('cat_amap(t1c,segc, n_classes, n_iters, sub, pve, init_kmeans, mrf, vx_vol, iters_icm, bias_fwhm)'); + prob = prob(:,:,:,[1 2 3]); + d{ni} = single(prob(:,:,:,1))/255 + single(prob(:,:,:,2))/255*2 + single(prob(:,:,:,3))/255*3; + r(ni) = rms(seg - d{ni}); + s(ni) = r(ni)<0.05; + + + + %% Laplace + % Laplace filtering is similar to distance transformation. + % ds('d2','',1,d0,d1/2,dc/6 + 0.5/6,d{5}(d1==1) - dc(d1==1)/6 + 0.5/6,5) + ni = ni + 1; + n{ni} = 'cat_vol_laplace3'; + d{ni} = cat_vol_laplace3(d1/2,0,1,0.01); + r(ni) = rms(d{ni}(d1==1) - (dc(d1==1)+0.5)/7.5 ); + s(ni) = r(ni)<0.05; + ni = ni + 1; + n{ni} = 'cat_vol_laplace3R'; + d{ni} = cat_vol_laplace3R(d1/2,d1==1,0.01); + r(ni) = rms(d{ni}(d1==1) - (dc(d1==1)+0.5)/7.5 ); + s(ni) = r(ni)<0.05; + + + %% gradient + % compare the result to the matlab function ... + %##### HIER GIBTS UNTERSCHIEDE?! ... beim zuf?lligen bild??? + % ds('l2','',1,dg,(abs(dx)+abs(dy)+abs(dz))*3,dg,d{7},10) + ni = ni + 1; + n{ni} = 'cat_vol_gradient3'; + dg = d1/2+d0/10; + [y,x,z] = gradient(dg); + [dx,dy,dz] = cat_vol_gradient3(dg); + d{ni} = abs(dx-x)+abs(dy-y)+abs(dz-z); + r(ni) = rms(dx-x)/3 + rms(dy-y)/3 + rms(dz-z)/3; + s(ni) = r(ni)<0.1; + + + %% voxelbased distance / thickness + % ds('l2','',1,d1,d1,d1/2,d{8}/10,10) + ni = ni + 1; + n{ni} = 'cat_vbdist'; + d{ni} = cat_vbdist(single(d1==0),d1==1); + r(ni) = max(d{ni}(d1(:)==1)) - 6; % grid distance + s(ni) = r(ni)>=0 & r(ni)<0.5; + ip = 1; + if verb>2 % just for debuging + dx1 = cat_vbdist(single(interp3(d5-1,ip)),round(interp3(d5,ip))==1); + dx2 = cat_vbdist(single(d5-1),round(d5)==1); + ds('d2','',1,interp3(d5,ip)/2,d5/2,dx1/20,dx2/10,10) + end + %% eikonal distance + % ds('l2','',1,d1,d1,d1/2,d{9}/10,10) + ni = ni + 1; + n{ni} = 'cat_vol_eidist'; + d{ni} = cat_vol_eidist(single(d1==0),ones(size(d1),'single')); + r(ni) = max(d{ni}(d1(:)==1)) - 5.5; % distance to boundary + s(ni) = abs(r(ni))<0.5; + % projection-based thickness c-function ... + % The result of this function is generally 0.5 smaller than expected + % because the PVE handling is done in the cat_vol_pbt + % matlab function + % ds('l2','',1,d1,d1,(d1+1)/3,d{10}/10,10) + ni = ni + 1; + n{ni} = 'cat_vol_pbtp'; + [d{ni},dpp] = cat_vol_pbtp(d1+1,dw,dc); + r(ni) = rms(d{ni}(d1==1)) - 5.5; + s(ni) = r(ni)<0.05; + + + %% test interpolation invariance + % - less difference in simple structures + % - the mean rather than median is used because the median not stable + % ds('d2','',1,d5/2,(Ygmti)/5,(Ygmt)/5,Yppi,5) + % ds('d2','',1,d5/2,Ycsfdi/3,Ywmdi/3,Yppi,5) + ni = ni + 1; + n{ni} = 'cat_vol_pbt'; + ip = 1; + distfunct = 1; % eidist is standard, but the simple vbdist a nice comparison and tests + ppth = 0.4; % threshold for Ypp mask generation + % simple case + dx = d2+1; + if distfunct + [Ygmt ,Ypp ,Ywmd ,Ycsfd ] = cat_vol_pbt(dx,struct('verb',0)); + [Ygmti,Yppi,Ywmdi,Ycsfdi] = cat_vol_pbt(interp3(dx,ip),struct('resV',1/2^ip,'verb',0)); + else + [Ygmt ,Ypp ,Ywmd ,Ycsfd ] = cat_vol_pbt(dx,struct('verb',0,'method','pbt2','dmethod','vbdist')); + [Ygmti,Yppi,Ywmdi,Ycsfdi] = cat_vol_pbt(interp3(dx,ip),struct('resV',1/2^ip,'verb',0,'method','pbt2','dmethod','eidist')); + end + Ytr = abs(Ypp-0.5)2 % just for debuging + ds('d2','',1,d5/2,Ycsfdi/3,Ywmdi/3,Ycsfd/3,5) + ds('d2','',1,d5/2,Ygmt/3,Ywmdi/3,Ygmti/3,5) + disp(rt) + disp(rx) + end + + %% interpolation + ni = ni + 1; + n{ni} = 'cat_vol_interp3f'; sD = size(d0); + [Rx,Ry,Rz] = meshgrid(single(1.75:0.5:sD(2)),single(1.75:0.5:sD(1)),single(1.75:0.5:sD(3))); + d0nan = d0+0; d0nan(isnan(d0)) = 0; + dcl = cat_vol_interp3f(d0nan,Rx,Ry,Rz,'linear'); + dcc = cat_vol_interp3f(d0nan,Rx,Ry,Rz,'cubic'); + dml = interp3(d0nan,Rx,Ry,Rz,'linear'); + tol = [10e-7 0.04]; + if strcmpi(spm_check_version,'octave') + try + % not implemented in 202112 + dmc = interp3(d0nan,Rx,Ry,Rz,'cubic'); + catch + dmc = interp3(d0nan,Rx,Ry,Rz,'spline'); + tol = [10e-4 0.11]; + end + else + dmc = interp3(d0nan,Rx,Ry,Rz,'cubic'); + end + d{ni}{1} = dcl - dml; + d{ni}{2} = dcc - dmc; + r(ni) = rms(d{ni}{1}) + rms(d{ni}{2}) ; + s(ni) = rms(d{ni}{1})1,'d')); dsg(d1==0) = nan; + [tmp1,tmp2] = cat_vol_simgrow(dsg,d1 + (d0-0.5)/10,0.05); + d{ni}{1} = tmp1; d{ni}{2} = tmp2; + % no test yet + r(ni) = rms((d1>0.5) - d{ni}{1}); + s(ni) = r(ni)<0.05; + + + %% downcut + % ds('l2','',1,d1 + (d0-0.5)/10,dsg,(d1 + (d0-0.5)/10)/2,d{14}{2}/200,10) + ni = ni + 1; + n{ni} = 'cat_vol_downcut'; + dsg = single(cat_vol_morph(d1>1,'d')); dsg(d1==0) = nan; + [tmp1,tmp2] = cat_vol_downcut(dsg,d1 + (d0-0.5)/10,0.1); + d{ni}{1} = tmp1; d{ni}{2} = tmp2; + r(ni) = rms((d1>0.5) - d{ni}{1}); + s(ni) = 1; + + + %% surface genersation + % Compare a simple cube - vertices should be identical, faces not. + % + ni = ni + 1; + n{ni} = 'cat_vol_genus0'; + MS = isosurface(dcubetr,0.5); + txt = evalc('[dcubec,CS.faces ,CS.vertices ] = cat_vol_genus0(dcubetr,0.5);'); + if verb>2, disp(txt); end + %r(ni) = all(all(sortrows(MS.vertices) == sortrows(CS.vertices) )) & ... + % all(size(MS.faces) == size(CS.faces)); + %s(ni) = r(ni)==1; + %% + if verb>2 + % Smoothed version showed differences, because cat_vol_genus does + % not use isovalues. + MSs = isosurface(cat_vol_smooth3X(dcube,2),0.5); + evalc('[tmp,CSs.faces,CSs.vertices] = cat_vol_genus0(cat_vol_smooth3X(dcube,2),0.5);'); + figure + subplot(2,2,1), patch(CS ,'facecolor',[.8 .7 .6]); axis equal off; lighting phong; view(3); camlight; zoom(1.5) + subplot(2,2,2), patch(MS ,'facecolor',[.8 .7 .6]); axis equal off; lighting phong; view(3); camlight; zoom(1.5) + subplot(2,2,3), patch(CSs,'facecolor',[.8 .7 .6]); axis equal off; lighting phong; view(3); camlight; zoom(1.8) + subplot(2,2,4), patch(MSs,'facecolor',[.8 .7 .6]); axis equal off; lighting phong; view(3); camlight; zoom(1.8) + end + + + %% NLM upsampling + %{ + % c-fuction used iterative based on an interpolated image + try + ni = ni + 1; + n{ni} = 'cat_vol_cMRegularizarNLM3D'; + dnc = cat_vol_cMRegularizarNLM3D(dcc,3,1,std(d0nan(:))/2,[2 2 2]); + d{ni} = dcl - dnc; + r(ni) = rms(d{ni}); + s(ni) = rms(d{ni})<0.05; + end + %} + + % Display results + if verb + fprintf('\n\nTest of compiled c-functions:\nThese are amplified tests with RMS values as rough approximation!\n'); + for si=1:numel(s) + if s(si) + cat_io_cprintf([0.0 0.6 0.0],sprintf('%4d) RMS = % 05.2f; Test of %20s successful!\n',... + si,r(si),['""' n{si} '""'])); + else + cat_io_cprintf([0.6 0.0 0.0],sprintf('%4d) RMS = % 05.2f; Test of %20s failed!\n',... + si,r(si),['""' n{si} '""'])); + end + end + fprintf('\n'); + end + + debugname = ['debug_' mexext '.mat']; + try + save(debugname,'d','CS'); + fprintf('Save %s.\n',debugname); + catch + fprintf('Can''t save ""%s""!\n',debugname); + end + + ok = all(s==1); + else + ok = 1; + r = []; + s = []; + end + + %% + if nargout>0, varargout{1}=ok; end + if nargout>1, varargout{2}=s; end + if nargout>2, varargout{3}=r; end +end +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_long_shoot_defaults.m",".m","4027","79","function d = cat_long_shoot_defaults +%cat_long_shoot_defaults: Defaults settings for intra subject deformations. +% Shoooting settings for tiny deformations between time points in the CAT +% longidtudinal preprocessing. These settings should correct for tiny +% disaplacements in aging. +% +% Defaults file +% FORMAT d = spm_shoot_defaults +% This file contains settings that are intended to be customised +% according to taste. Some of them will influence the speed/accuracy +% tradeoff, whereas others are various regularisation settings +% (registration and template blurring)... +%_______________________________________________________________________ +% Copyright (C) Wellcome Trust Centre for Neuroimaging (2009) +% John Ashburner +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + +%_______________________________________________________________________ +% The following settings are intended to be customised according to +% taste. Some of them will influence the speed/accuracy tradeoff, +% whereas others are various regularisation settings (registration +% and template blurring)... + +% +% shooting defaults for cross-sectional processing (just for comparison) +if 0 + d.tname = 'Template'; % Base file name for templates + d.issym = false; % Use a symmetric template? + + d.cyc_its = [2 2]; % No. multigrid cycles and iterations + + nits = 24; % No. iterations of Gauss-Newton + + % Schedule for coarse to fine + lam = 0.5; % Decay of coarse to fine schedule + inter = 32; % Scaling of parameters at first iteration + d.sched = (inter-1)*exp(-lam*((1:(nits+1))-1))+1; + d.sched = d.sched/d.sched(end); + + maxoil = 8; % Maximum number of time steps for integration + d.eul_its = round((0:(nits-1))*(maxoil-0.5001)/(nits-1)+1); % Start with fewer steps + + d.rparam = [1e-4 0.001 0.2 0.05 0.2]; % Regularisation parameters for deformation + d.sparam = [0.0001 0.08 0.8]; % Regularisation parameters for blurring + d.smits = 16; % No. smoothing iterations + %d.smits = 0; d.sparam = []; + d.scale = 0.8; % Fraction of Gauss-Newton update step to use + + d.bs_args = [2 2 2 1 1 1]; % B-spline settings for interpolation +else + %% RD202005: definition for individual aging deformation + + d.tname = 'Template_FNAME'; % Base file name for templates ... FNAME is replaced by filename + d.issym = false; % Use a symmetric template? + d.cyc_its = [1 1]; % No. multigrid cycles and iterations + nits = 8; % No. iterations of Gauss-Newton (4-8) + % Schedule for coarse to fine + lam = 0.25; % Decay of coarse to fine schedule + inter = 64; % Scaling of parameters at first iteration (32) + d.sched = (inter-1)*exp(-lam*((1:(nits+1))-1))+1; + d.sched = d.sched/d.sched(end) * 32; % 32 as gener offset to have low-frequency deformations + maxoil = 8; % Maximum number of time steps for integration + d.eul_its = round((0:(nits-1))*(maxoil-0.5001)/(nits-1)+1); % Start with fewer steps + d.eul_its = flipud(d.eul_its); + d.rparam = [1e-4 0.001 0.2 0.05 0.2]; % Regularisation parameters for deformation (just the defaults) + d.sparam = [0 0 0.0000001]; % Regularisation parameters for blurring - strongly reduced as far as it create incorrect results in the individual cases + d.smits = 1; % Minimum smoothing iterations (turn it off will produce an error at the end of the Shooting iteration) + d.scale = 0.8; % Fraction of Gauss-Newton update step to use + d.bs_args = [2 2 2 1 1 1]; % B-spline settings for interpolation +end +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_vol_slice_overlay_ui.m",".m","4923","116","function cat_vol_slice_overlay_ui +% Wrapper to cat_vol_slice_overlay +% Call help for slice_overlay for any additional help +% +% Additional fields to slice_overlay: +% OV.name - char array of filenames for overlay that can be interactively +% selected +% OV.slices_str - char array of slice values (e.g. '-32:2:20') +% use empty string for automatically estimating slices with +% local maxima +% OV.xy - define number of columns and rows +% comment this out for interactive selection or set the values +% to [Inf 1] for using one row and automatically estimate number +% of columns or use [1 Inf] for using one column +% OV.atlas - define atlas for labeling +% comment this out for interactive selection +% or use 'none' for no atlas information +% OV.save - save result as png/jpg/pdf/tif +% comment this out for interactive selection or use '' for not +% saving any file or use just file extension (png/jpg/pdf/tif) to +% automatically estimate filename to save +% OV.FS - normalized font size (default 0.08) +% OV.name_subfolder +% - if result is saved as image use up to 2 subfolders to add their +% names to the filename (default 1) +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +% use default T1 from Shooting +%OV.reference_image = fullfile(cat_get_defaults('extopts.pth_templates'),'Template_T1.nii'); +% or its masked version +OV.reference_image = fullfile(cat_get_defaults('extopts.pth_templates'),'Template_T1_masked.nii'); + +OV.reference_range = [0.2 1.0]; % intensity range for reference image +OV.opacity = Inf; % transparency value for overlay (<1) +OV.cmap = jet; % colormap for overlay + +% char array of file names +OV.name = char(fullfile(cat_get_defaults('extopts.pth_templates'),'Template_4_GS.nii,1'),... + fullfile(cat_get_defaults('extopts.pth_templates'),'cobra.nii')); + +% range for each file +% Use range 0..0 if you want to autoscale range. +% If you are using log. scaling, check the highest p-value in the table +% and approximate the range; e.g. for a max. p-value of p=1e-7 and a +% threshold of p<0.001 use a range of [3 7]. Check cat_stat_spmT2x.m for details. +% If you are unsure, simply use the autorange option by using a range of [0 0]. +% The log-scaled values are calculated by -log10(1-p): +% p-value -log10(1-P) +% 0.1 1 +% 0.05 1.30103 (-log10(0.05)) +% 0.01 2 +% 0.001 3 +% 0.0001 4 + +% Number of fields in range should be the same as number of files (see above) +% or define one field, which is valid for all. +% Be careful: intensities below the lower range are not shown! +OV.range =[[0.5 1]; [126 139]]; + +% OV.clip can be used to set the image to defined values (e.g. NaN) for the given range +% This is quite helpful for log-scaled p-maps without any threshold (e.g. after TFCE) and +% allows to define the threshold afterwards +% The example below thresholds the log-scaled p-map with p<0.05 for positive as well as negative effects +%OV.clip = [log10(0.05) -log10(0.05)]; + +% selection of slices and orientations +% if OV.slices_str is an empty string then slices with local maxima are estimated automatically +OV.slices_str = char('','0:2:36','-40:5:-5'); +OV.transform = char('axial','sagittal','coronal'); + +% define output format of slices +OV.labels.format = '%3.1f'; + +% define number of columns and rows +% comment this out for interactive selection +%OV.xy = [3 5]; + +% or use Inf to automatically estimate the number of necessray rows or columns +OV.xy = [Inf 1]; % use one row and automatically estimate number of columns + +% save result as png/jpg/pdf/tif +% comment this out for interactive selection or use 'none' for not +% saving any file or use just file extension (png/jpg/pdf/tif) to automatically +% estimate filename to save +OV.save = 'png'; + +% if result is saved as image use up to 2 subfolders to add their names to the filename (default 1) +OV.name_subfolder = 2; + +% Comment this out if you wish slice overview +OV.overview = []; + +% Comment this out if you wish slice labels +OV.labels = []; + +% Comment this out if you wish colorbar +OV.cbar = []; + +% Normalized font size +OV.FS = 0.08; + +% define atlas for labeling +% comment this out for interactive selection +% or use 'none' for skipping atlas information +OV.atlas = 'cat12_neuromorphometrics'; + +% call slice overlay with that settings +cat_vol_slice_overlay(OV) +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_stat_marks.m",".m","18837","317","function varargout = cat_stat_marks(action,uselevel,varargin) +% ______________________________________________________________________ +% +% Meta data management for a scan. +% Contain evaluation data and function. +% +% varargout = cat_stat_marks(action,varargin) +% QS = cat_stat_marks('init') +% [0|1] = cat_stat_marks('isfield','fieldname') +% QSM = cat_stat_marks('eval',QS) +% QH = cat_stat_marks('help') +% +% action = {'init','isfield','eval','help'} +% 'init' .. create a empty data structure QS +% 'isfield' .. check if varargin{1} is a field in QS +% 'eval' .. evaluates fields of a input structure QS +% 'help' .. output the help information for QS +% +% hier wird noch eine zusammenfassung/vereinfachung der ma??e gebraucht +% QM: res + noise + bias + contrast +% QS: vol +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +%#ok<*NASGU,*STRNU> + + rev = '$Rev$'; + try + dbs = dbstack; + qav = dbs(2).name; + catch + qav = ''; + end + +% used measures and marks: +% ______________________________________________________________________ +% def.tisvolr with the mean relative tissue volume of 10 year groups of +% healty subjects of a set of different projects with IQR<3 and the std +% of all datasets (5122 images). + + def.tissue = [ 1/3 3/12; 2/3 3/12; 1 3/12]; % ideal normalized tissue peak values + def.tisvolr = [0.1754 0.1439; 0.4538 0.1998; 0.3688 0.1325; 0 0.1]; % relative expected tissue volumes + def.thickness = [2.50 1.0; 0.75 0.5]; % absolute expected thickness + def.WMdepth = [2.50 1.0; 1.50 1.0]; % absolute expected thickness + def.CSFdepth = [1.25 1.0; 0.25 0.5]; % absolute expected thickness + def.CHvsCG = [ 0.9 0.6; 0.1 0.4; 9 1]; % relation + def.noise = [0.0466 0.3949]; % noise: NM=[0.0466 0.3949]; %NM = [NM(1) NM(1)+(NM(2)-NM(1))/5*6]; + def.bias = [0.2178 1.1169 * 2 ]; % bias: BM=[0.2178 1.1169*2]; %BM = [BM(1) BM(1)+(BM(2)-BM(1))/3*6]; + %CM=[1/2 1/6]; CM = [CM(1)+diff(CM)/12 CM(2)+diff(CM)/12]; %CM=[1/3 1/12]; CM = [CM(1)-CM(2)/2 CM(2)-CM(2)/2]; + CM=[1/3 0]; %CM = [CM(1)+diff(CM)/12 CM(2)+diff(CM)/12]; %CM=[1/3 1/12]; CM = [CM(1)-CM(2)/2 CM(2)-CM(2)/2]; + def.contrast = CM; % contrast + def.QS = { +% -- structure --------------------------------------------------------- +% 'measure' 'fieldname' 'marktpye' markrange help +% 'measure' 'fieldname' 'linear' [best worst] 'use for most qa measures +% 'measure' 'fieldname' 'normal' [mean std] 'use for most subject measures +% -- software data ----------------------------------------------------- + 'software' 'matlab' '' [] 'MATLAB version' + 'software' 'spm' '' [] 'SPM version' + 'software' 'cat' '' [] 'CAT version' + 'software' 'qamethod' '' [] 'CAT QA method' + 'software' 'date' '' [] 'calculation date' +% -- file data --------------------------------------------------------- + 'filedata' 'fname' '' [] 'path and filename' + 'filedata' 'path' '' [] 'path' + 'filedata' 'file' '' [] 'filename' + 'filedata' 'F' '' [] 'original filename used for QA' + 'filedata' 'Fm' '' [] 'modified filename used for QA' + 'filedata' 'Fp0' '' [] 'label map filename used for QA' +% -- image quality measures on the original image ---------------------- + % - resolution - + 'qualitymeasures' 'res_vx_vol' 'linear' [ 0.50 3.00] 'voxel dimensions' + 'qualitymeasures' 'res_RMS' 'linear' [ 0.50 3.00] 'RMS error of voxel size' + 'qualitymeasures' 'res_ECR' 'linear' [ 0.125 1.00] 'normalized gradient slope of the white matter boundary' % [0.3222 0.5413] + %'qualitymeasures' 'res_MVR' 'linear' [ 0.50 3.00] 'mean voxel resolution' + %'qualitymeasures' 'res_vol' 'linear' [ 0.125 27] 'voxel volume' + %'qualitymeasures' 'res_isotropy' 'linear' [ 1.00 8.00] 'voxel isotropy' + 'qualitymeasures' 'res_BB' 'linear' [ 0 10] 'brain next to the image boundary' + % - tissue mean and varianz - + 'qualitymeasures' 'tissue_mn' 'normal' def.tissue 'mean within the tissue classes' + 'qualitymeasures' 'tissue_std' 'normal' [ 0.10 0.20] 'standard deviation within the tissue classes' + % - contrast - + 'qualitymeasures' 'contrast' 'linear' [ CM(1) CM(2)] 'contrast between tissue classes' % das geht nicht + 'qualitymeasures' 'contrastr' 'linear' [ CM(1) CM(2)] 'contrast between tissue classes' + % - noise & contrast - + 'qualitymeasures' 'NCR' 'linear' def.noise 'noise to contrast ratio' + %'qualitymeasures' 'CNR' 'linear' [1/NM(1) 1/NM(2)] 'contrast to noise ratio' + % - inhomogeneity & contrast - + 'qualitymeasures' 'ICR' 'linear' def.bias 'inhomogeneity to contrast ratio' + % 'qualitymeasures' 'ICRk' 'linear' [ 1.095 1.80] 'inhomogeneity to contrast ratio' + %'qualitymeasures' 'CIR' 'linear' [1/BM(1) 1/BM(2)] 'contrast to inhomogeneity ratio' + % - subject measures / preprocessing measures - + %'qualitymeasures' 'CJV' 'linear' [ 0.12 0.18] 'coefficient of variation - avg. std in GM and WM' + %'qualitymeasures' 'MPC' 'linear' [ 0.11 0.33] 'mean preprocessing change map - difference between optimal T1 and p0' + %'qualitymeasures' 'MJD' 'linear' [ 0.05 0.15] 'mean Jacobian determinant' + %'qualitymeasures' 'STC' 'linear' [ 0.05 0.15] 'difference between template and label' + 'qualitymeasures' 'FEC' 'linear' [ 100 600] 'quick Euler characteristic' + 'qualitymeasures' 'SurfaceEulerNumber' 'linear' [ 2 100] 'average Euler number (characteristic)' + 'qualitymeasures' 'SurfaceDefectArea' 'linear' [ 0 20] 'average area of topological defects' + 'qualitymeasures' 'SurfaceDefectNumber' 'linear' [ 0 100] 'average number of defects' + 'qualitymeasures' 'SurfaceIntensityRMSE' 'linear' [ 0.05 0.3] 'RMSE of the expected boundary intensity Ym of the IS, OS, and CS' + 'qualitymeasures' 'SurfacePositionRMSE' 'linear' [ 0.05 0.3] 'RMSE of the expected boundary position Ypp of the IS, OS, and CS' + 'qualitymeasures' 'SurfaceSelfIntersections' 'linear' [ 0 20] 'Percentual area of self-intersections of the IS and OS.' +% -- subject-related data from the preprocessing ----------------------- + % - volumetric measures - + 'subjectmeasures' 'vol_TIV' 'normal' [ 1400 400] 'total intracranial volume (GM+WM+VT)' + 'subjectmeasures' 'vol_CHvsGW' 'linear' def.CHvsCG 'relation between brain and non brain' + 'subjectmeasures' 'vol_rel_CGW' 'linear' def.tisvolr 'relative tissue volume (CSF,GM,WM)' + 'subjectmeasures' 'vol_rel_BG' 'linear' [ 0.05 0.05] 'relative tissue volume of basal structures' + 'subjectmeasures' 'vol_rel_VT' 'linear' [ 0.05 0.05] 'relative tissue volume of the ventricle' + 'subjectmeasures' 'vol_rel_BV' 'linear' [ 0.00 0.05] 'relative blood vessel volume' + 'subjectmeasures' 'vol_rel_WMH' 'linear' [ 0.00 0.05] 'relative WMH volume' + % - distance / thickness measures - + 'subjectmeasures' 'dist_thickness' 'normal' def.thickness 'absolute GM thickness' + 'subjectmeasures' 'dist_WMdepth' 'normal' def.WMdepth 'absolute WM depth' + 'subjectmeasures' 'dist_CSFdepth' 'normal' def.CSFdepth 'absolute CSF depth' + 'subjectmeasures' 'dist_abs_depth' 'normal' [ 5.00 2.00] 'absolute sulcal depth' + 'subjectmeasures' 'dist_rel_depth' 'normal' [ 0.50 0.20] 'relative sulcal depth' + % - area measures - + 'subjectmeasures' 'surf_TSA' 'normal' [ 1400 400]*2/3 'total surface area' + % - software - + 'software' 'cat_warnings' '' [] 'CAT preprocessing warning structure with subfields for identifier, message, type, and data. See ../cat12/html/cat_methods_warnings.html' + 'SPMpreprocessing' 'Affine0' '' [] 'Initial affine matrix estimated in cat_run_job, used for SPM US.' + 'SPMpreprocessing' 'Affine' '' [] 'Final affine matrix extimated in cat_main_registration.' + 'SPMpreprocessing' 'lkp' '' [] 'Number of SPM tissue classes.' + 'SPMpreprocessing' 'mn' '' [] 'Mean value of SPM tissue class defined by the lkp field.' + 'SPMpreprocessing' 'vr' '' [] 'Variance of SPM tissue class defined by the lkp field.' + 'SPMpreprocessing' 'Affine_translation' '' [] 'Translation parameter of the affine registration [X Y Z]. ' + 'SPMpreprocessing' 'Affine_rotation ' '' [] 'Rotation parameter of the affine registration [X Y Z]. ' + 'SPMpreprocessing' 'Affine_scaling' '' [] 'Scaling parameter of the affine registration [X Y Z]. ' + 'SPMpreprocessing' 'Affine_shearing' '' [] 'Shearing parameter of the affine registration [X Y Z]. ' + 'SPMpreprocessing' 'Affine0_translation' '' [] 'Translation parameter of the initial affine registration [X Y Z]. ' + 'SPMpreprocessing' 'Affine0_rotation ' '' [] 'Rotation parameter of the initial affine registration [X Y Z]. ' + 'SPMpreprocessing' 'Affine0_scaling' '' [] 'Scaling parameter of the initial affine registration [X Y Z]. ' + 'SPMpreprocessing' 'Affine0_shearing' '' [] 'Shearing parameter of the initial affine registration [X Y Z]. ' + }; + if nargin>3 && isstruct(varargin{2}), def = cat_io_checkinopt(varargin{2},def); end + + % create structure + for QSi=1:size(def.QS,1) + if isempty(def.QS{QSi,3}) + eval(sprintf('QS.%s.%s = '''';',def.QS{QSi,1},def.QS{QSi,2})); + else + eval(sprintf('QS.%s.%s = [];',def.QS{QSi,1},def.QS{QSi,2})); + end + end + + % mark limits + def.bstm = 1; % best mark + def.wstm = 6; % worst mark + def.wstmn = 8.624; % worst mark to get a 4 for values with std + def.bstl = 0.5+eps*2; % highest rating ... 0.5 because of rounding values + def.wstl = 10.5-eps*2; % lowest rating ... to have only values with 1 digit .. but % scaling... + + + % mark functions + setnan = [1 nan]; + nv = @(x,m,s) (1./sqrt(2.*pi.*s^2) .* exp( - (x-m)^2 ./ (2.*s^2))) ./ (1./sqrt(2.*pi.*s^2) .* exp( - (0)^2 ./ (2.*s^2))); + evallinearx = @(bst,wst ,bstm,wstm,bstl,wstl,x) setnan(isnan(x)+1) .* ... + (min(wstl,max(bstl,abs(x - bst) ./ abs(diff([wst ,bst])) .* abs(diff([bstm,wstm])) + bstm))); + evalnormalx = @(bst,wstd,bstm,wstm,bstl,wstl,x) setnan(isnan(x)+1) .* ... + (min(wstl,max(bstl,(1 - nv(x,bst,wstd)) .* abs(diff([bstm,wstm])) + bstm))); + evallinear = @(x,bst,wst) setnan(isnan(x)+1) .* ... max(0, + (min(def.wstl,max(-inf,(sign(wst-bst)*x - sign(wst-bst)*bst) ./ abs(diff([wst ,bst])) .* abs(diff([def.bstm,def.wstm])) + def.bstm))); + evalnormal = @(x,bst,wstd) setnan(isnan(x)+1) .* ... + (min(def.wstl,max(def.bstl,(1 - nv(x,bst,wstd)) .* abs(diff([def.bstm,def.wstmn])) + def.bstm))); + + mark2rps = @(mark) min(100,max(0,105 - mark*10)); + grades = {'A+','A','A-','B+','B','B-','C+','C','C-','D+','D','D-','E+','E','E-','F'}; + mark2grad = @(mark) grades{max(1,min(numel(grades),max(max(isnan(mark)*numel(grades),1),round((mark+2/3)*3-3))))}; + + rms = @(a,fact) max(0,cat_stat_nanmean(a.^fact).^(1/fact)); + rmsw = @(a,fact,w) max(0,(cat_stat_nansum((a.*w).^fact)/cat_stat_nansum(w)).^(1/fact)); + + switch action + case 'default' + varargout{1} = def; + + + case 'isfield' % active field? + if nargin<1 || isempty(varargin{1}) + error('MATLAB:cat_stat_marks:input','Need fieldname!\n'); + end + pii = strfind(varargin{1},'.'); + if isempty(pii) + varargout{1} = any(strcmp(def.QS(:,2),varargin{1})); + else + varargout{1} = any(strcmp(def.QS(:,1),varargin{1}(1:pii-1)) & ... + strcmp(def.QS(:,2),varargin{1}(pii+1:end))); + end + + + case 'eval' % evalutate input structure + if nargin<1 || isempty(varargin{1}) + error('MATLAB:cat_stat_marks:input','Need input structure with measurements!\n'); + end + if nargin>3 && ~isstruct(varargin{2}) + def = cat_vol_qa('getdef',varargin{2}); + elseif nargin>3 && isstruct(varargin{2}) + def = varargin{2}; + end + if ~isstruct(varargin{1}) + error('MATLAB:cat_stat_marks:input','Second input has to be a structure!\n'); + end + QA = varargin{1}; + + % evaluation + QAM = struct(); + for QSi=1:size(def.QS,1) + if ~isempty(def.QS{QSi,3}) && isfield(QA,def.QS{QSi,1}) && ... + isfield(QA.(def.QS{QSi,1}),def.QS{QSi,2}) + + QAM.help.(def.QS{QSi,1}).(def.QS{QSi,2}) = def.QS{QSi,5}; + + if ~iscell(QA.(def.QS{QSi,1}).(def.QS{QSi,2})) + + if size(def.QS{QSi,4},1)>1 && ... + size(def.QS{QSi,4},1) == numel(QA.(def.QS{QSi,1}).(def.QS{QSi,2})) + for v=1:size(def.QS{QSi,4},1) + for ij=1:numel(QA.(def.QS{QSi,1}).(def.QS{QSi,2})) + eval(sprintf(['QAM.%s.%s(ij) = cat_stat_nanmean(eval%s(' ... + 'QA.%s.%s(ij),def.QS{QSi,4}(ij,1),def.QS{QSi,4}(ij,2)));'], ... + strrep(def.QS{QSi,1},'measures','ratings'),... + def.QS{QSi,2},def.QS{QSi,3},def.QS{QSi,1},def.QS{QSi,2})); + end + end + else + for ij=1:numel(QA.(def.QS{QSi,1}).(def.QS{QSi,2})) + eval(sprintf(['QAM.%s.%s(ij) = cat_stat_nanmean(eval%s(' ... + 'QA.%s.%s(ij),def.QS{QSi,4}(1),def.QS{QSi,4}(2)));'], ... + strrep(def.QS{QSi,1},'measures','ratings'),... + def.QS{QSi,2},def.QS{QSi,3},def.QS{QSi,1},def.QS{QSi,2})); + end + end + else + for ci=1:numel(QA.(def.QS{QSi,1}).(def.QS{QSi,2})) + if size(def.QS{QSi,4},1)>1 && ... + size(def.QS{QSi,4},1) == numel(QA.(def.QS{QSi,1}).(def.QS{QSi,2}){ci}) + for v=1:size(def.QS{QSi,4},1) + for ij=1:numel(QA.(def.QS{QSi,1}).(def.QS{QSi,2}){ci}) + eval(sprintf(['QAM.%s.%s{ci}(ij) = cat_stat_nanmean(eval%s(' ... + 'QA.%s.%s{ci}(ij),def.QS{QSi,4}(ij,1),def.QS{QSi,4}(ij,2)));'], ... + strrep(def.QS{QSi,1},'measures','ratings'),... + def.QS{QSi,2},def.QS{QSi,3},def.QS{QSi,1},def.QS{QSi,2})); + end + end + else + for ij=1:numel(QA.(def.QS{QSi,1}).(def.QS{QSi,2}){ci}) + eval(sprintf(['QAM.%s.%s{ci}(ij) = cat_stat_nanmean(eval%s(' ... + 'QA.%s.%s{ci}(ij),def.QS{QSi,4}(1),def.QS{QSi,4}(2)));'], ... + strrep(def.QS{QSi,1},'measures','ratings'),... + def.QS{QSi,2},def.QS{QSi,3},def.QS{QSi,1},def.QS{QSi,2})); + end + end + end + end + end + end + +% if numel(varargin)>1, method = varargin{2}; else method = 'cat12'; end +% CJVpos = find(cellfun('isempty',strfind(def.QS(:,2),'CJV'))==0); +% MPCpos = find(cellfun('isempty',strfind(def.QS(:,2),'MPC'))==0); +% +% % average +% BWP.NCRm = evallinear(QA.qualitymeasures.NCR ,0.05,0.35,6); +% BWP.MVRm = evallinear(QA.qualitymeasures.res_RMS,0.50,3.00,6); + + % SIQR is the successor of IQR that also includes a edge-based + % resolution rating (res_ECR) and fast Euler characteristic (FEC) + % The inhomogeneity (bias) contrast rating (ICR) is again not included + % as it is not really connect to processing quality. + % We use here a power of 8 for the old image quality rating (IQR) and + % 4 for the new structural image quality rating (SIQR) to focus + % stronger on outliers. + try + if isfield(QAM.qualityratings,'FEC') + QAM.qualityratings.SIQR = rms([QAM.qualityratings.NCR ... + QAM.qualityratings.res_RMS QAM.qualityratings.res_ECR QAM.qualityratings.FEC],4); + elseif isfield(QAM.qualityratings,'res_ECR') + QAM.qualityratings.SIQR = rms([QAM.qualityratings.NCR ... + QAM.qualityratings.res_RMS QAM.qualityratings.res_ECR],4); + else + % we use here 8 to compensate the mising ECR/FEC ratings and to + % be compatibel to the old ICR rating + QAM.qualityratings.SIQR = rms([QAM.qualityratings.NCR ... + QAM.qualityratings.res_RMS],8); + end + catch + QAM.qualityratings.SIQR = nan; + end + QAM.qualityratings.IQR = rms([QAM.qualityratings.NCR QAM.qualityratings.res_RMS ],8); + QAM.subjectratings.SQR = rms([QAM.subjectratings.vol_rel_CGW],2); + + varargout{1} = QAM; + + + case 'init' % ausgabe einer leeren struktur + varargout{1} = QS; + switch qav + case {'cat_vol_qa202110','cat_vol_qa201901'} % older version + varargout{2} = {'NCR','ICR','res_RMS','contrastr'}; % ,'res_BB' is not working now + otherwise + varargout{2} = {'NCR','ICR','res_RMS','res_ECR','FEC','contrastr'}; % ,'res_BB' is not working now + end + + case 'marks' % ausgabe einer leeren struktur + varargout{1} = def.QS; + end + + +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_surf_calc.m",".m","12058","410","function varargout = cat_surf_calc(job) +% ______________________________________________________________________ +% Surface Calculation Tool - Only batch mode available. +% +% [Psdata] = cat_surf_smooth(job) +% +% job.cdata .. cellstr or cell of cellstr for multi-subject +% processing +% job.dataname .. output name (def = 'ouput') +% job.outdir .. output directory (if empty first subject directory) +% job.expression .. texture calculation expression +% 's1 + s2' for dmtx==0 +% 'mean(S)' for dmtx==1 +% job.dmtx .. use data matrix +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + if strcmp(job,'selftest') + cat_surf_calc_selftest; + end + + if nargin == 1 + def.nproc = 0; % multiple threads + def.verb = 0; % dispaly something + def.lazy = 0; % do not process anything if output exist (expert) + def.datahandling = 1; % 1-subjectwise, 2-datawise + def.usefsaverage = 1; % + def.assuregifti = 0; % write gii output + def.dataname = 'output'; + def.usetexturefield = 0; + job = cat_io_checkinopt(job,def); + else + error('Only batch mode'); + end + + % prepare output filename + if iscellstr(job.cdata) + sinfo = cat_surf_info(job.cdata{1}); + else + sinfo = cat_surf_info(job.cdata{1}{1}); + end + + if strfind(sinfo.side,'mesh') + if sinfo.resampled_32k + job.fsaverage = fullfile(fileparts(mfilename('fullpath')),'templates_surfaces_32k','mesh.central.freesurfer.gii'); + else + job.fsaverage = fullfile(fileparts(mfilename('fullpath')),'templates_surfaces','mesh.central.freesurfer.gii'); + end + else + if sinfo.resampled_32k + job.fsaverage = fullfile(fileparts(mfilename('fullpath')),'templates_surfaces_32k','lh.central.freesurfer.gii'); + else + job.fsaverage = fullfile(fileparts(mfilename('fullpath')),'templates_surfaces','lh.central.freesurfer.gii'); + end + end + + if ~isempty(job.outdir{1}), outdir = job.outdir{1}; else, outdir=''; end + ee = sinfo.ee; if job.assuregifti, ee = '.gii'; end + + job.dataname = strrep(job.dataname,'.gii',''); % remove .gii extension + + % single or multi subject calculation + if iscellstr(job.cdata) + if isempty(outdir), outdir = fileparts(job.cdata{1}); end + + if job.usetexturefield + useinput = strfind('INPUT',job.dataname); + if ~isempty(useinput) + sinfo = cat_surf_info(job.cata{1}); + job.dataname = strrep(job.dataname,'INPUT',sinfo.texture); + end + + job.output = char(cat_surf_rename(job.cdata{1},... + 'preside','','pp',outdir,'name','','dataname',job.dataname,'ee',ee)); + else + job.output = fullfile(outdir,[job.dataname,ee]); + end + + % call surfcalc + if strcmp(strrep(job.expression,' ',''),'s1') % this is just a copy + copyfile(job.cdata{1},job.output,'f'); + else + job.verb = 1; + surfcalc(job); + end + fprintf('Output %s\n',spm_file(job.output,'link','cat_surf_display(''%s'')')); + + elseif job.datahandling==1 + % multisubject + for si = 1:numel(job.cdata{1}) + if ~isempty(outdir) + soutdir = outdir; + else + soutdir = fileparts(job.cdata{1}{si}); + end + + job.output{si} = char(cat_surf_rename(job.cdata{1}{si},... + 'preside','','pp',soutdir,'dataname',job.dataname,'ee',ee)); + end + + % split job and data into separate processes to save computation time + if job.nproc>0 && (~isfield(job,'process_index')) + cat_parallelize(job,mfilename,'cdata'); + return + elseif isfield(job,'printPID') && job.printPID + cat_display_matlab_PID + end + + if job.nproc==0 + cat_progress_bar('Init',numel(job.cdata{1}),... + sprintf('Surface Calculator\n%d',numel(job.cdata{1})),'Subjects Completed'); + end + + for si = 1:numel(job.cdata{1}) % for subjects + sjob = rmfield(job,'cdata'); + sjob.verb = 0; + + % subject data + for ti = 1:numel(job.cdata) % for textures + sjob.cdata{ti} = job.cdata{ti}{si}; + end + + sjob.output = job.output{si}; + try + if strcmp(strrep(job.expression,' ',''),'s1') % this is just a copy + copyfile(sjob.cdata{1},job.output{si},'f'); + else + surfcalc(sjob); + end + fprintf('Output %s\n',spm_file(sjob.output,'link','cat_surf_display(''%s'')')); + catch + fprintf('Output %s failed\n',sjob.output); + end + + if job.nproc==0 + cat_progress_bar('Set',si); + end + end + + if job.nproc==0 + cat_progress_bar('Clear'); + end + else + %% + for di = 1:numel(job.cdata) + if ~isempty(outdir) + soutdir = outdir; + else + soutdir = fileparts(job.cdata{di}{1}); + end + + sinfo = cat_surf_info(job.cdata{di}); + names = 'isequaln('; for si=1:numel(sinfo), names = [names '''' sinfo(si).name ''',']; end; names(end) = ')'; %#ok + if numel(sinfo)>1 && eval(names) + job.output{di,1} = char(cat_surf_rename(job.cdata{di}{1},... + 'preside','','pp',outdir,'name','','dataname',job.dataname,'ee',ee)); + + else + job.output{di,1} = char(cat_surf_rename(job.cdata{di}{1},... + 'preside','','pp',soutdir,'name',job.dataname,'ee',ee)); + end + end + + + % split job and data into separate processes to save computation time + if job.nproc>0 && (~isfield(job,'process_index')) + cat_parallelize(job,mfilename,'cdata'); + return + elseif isfield(job,'printPID') && job.printPID + cat_display_matlab_PID + end + + if job.nproc==0 + cat_progress_bar('Init',numel(job.cdata{1}),... + sprintf('Surface Calculator\n%d',numel(job.cdata{1})),'Subjects Completed'); + end + + for di = 1:numel(job.cdata) % for subjects + sjob = rmfield(job,'cdata'); + sjob.verb = 0; + + % subject data + sjob.cdata = job.cdata{di}; + sjob.output = job.output{di}; + try + surfcalc(sjob); + fprintf('Output %s\n',spm_file(sjob.output,'link','cat_surf_display(''%s'')')); + catch + fprintf('Output %s failed\n',sjob.output); + end + + if job.nproc==0 + cat_progress_bar('Set',di); + end + end + + if job.nproc==0 + cat_progress_bar('Clear'); + end + + end + + + + if nargout + if iscellstr(job.cdata) + varargout{1}.output = {job.output}; + else % is cell of cellstrings + varargout{1}.output = job.output; + end + end +end + +function surfcalc(job) + + def.debug = cat_get_defaults('extopts.verb')>2; + def.fsavgDir = fullfile(fileparts(mfilename('fullpath')),'templates_surfaces'); + def.pbar = 0; + job = cat_io_checkinopt(job,def); + + %% calculation + [sinfo1,S1] = cat_surf_info(job.cdata{1},1); + sinfo = cat_surf_info(job.cdata); + + if ~isfield(sinfo1(1),'ncdata') + G = gifti(sinfo1(1).fname); + sinfo1(1).ncdata = numel(G.cdata); + end + cdata = zeros([1,sinfo1(1).ncdata],'single'); + if sinfo1.datatype==3 + vdata = zeros([1,sinfo1(1).nvertices,3],'single'); + end + + % work on subsets (""slices"") to save memory + subsetsize = round(10e10 / numel(job.cdata)); + + if job.verb + spm_clf('Interactive'); + cat_progress_bar('Init',numel(job.cdata),... + sprintf('Surface Calculator\n%s',job.output),'Input Surfaces Completed'); + end + sdata = struct('dsize',[],'fsize',[],'vsize',[]); + for si = 1:ceil(sinfo1(1).nvertices/subsetsize) + range = [ (si-1) * subsetsize + 1 , si * subsetsize ]; + range = min(range,sinfo1(1).nvertices); + range = range(1):range(2); + + if job.dmtx + S = zeros(numel(job.cdata),numel(range),1,'single'); + end + if sinfo1.datatype==3 + V = zeros(numel(job.cdata),numel(range),3,'single'); + end + + + %% + for i=1:numel(job.cdata) + if sinfo(i).ftype==1 + GS = gifti(job.cdata{i}); + if isfield(GS,'cdata') + try + d = reshape(GS.cdata,1,sinfo1(1).nvertices); + catch + if i>1 && numel(job.cdata{i-1})~=numel(job.cdata{i}) + fprintf('cat_surf_calc:gificdata',... + 'Number of elements must be equal:\n%12d entries in file %s\n%12d entries in file %s\n',... + numel(job.cdata{i-1}), job.cdata{i-1}, numel(job.cdata{i}), job.cdata{i}); + end + end + else + error('cat_surf_calc:gifticdata',... + 'No texture found in ''s''!',job.cdata{i}); + end + sdata(i).dsize = size(GS.cdata); + if sinfo1.datatype==3 + V(i,:,:) = shiftdim(GS.vertices(range,:),-1); + sdata(i).vsize = size(GS.vertices); + sdata(i).fsize = size(GS.faces); + end + else + d = cat_io_FreeSurfer('read_surf_data',job.cdata{i})'; + sdata(i).dsize = size(d); + end + if i>1 + if any(sdata(i).dsize~=sdata(i-1).dsize) + if sinfo(i).resampled==0 + error('cat_surf_calc:texturesize',... + 'Surface ''s%d'' (%s) does not match previous texture (non-resampled input)!%s',i,job.cdata{i}); + else + error('cat_surf_calc:texturesize',... + 'Surface ''s%d'' (%s) does not match previous texture!%s',i,job.cdata{i}); + end + end + if sinfo(i).datatype==3 && ... + any(sdata(i).vsize~=sdata(i-1).vsize) || any(sdata(i).fsize~=sdata(i-1).fsize) + error('cat_surf_calc:meshsize',... + 'Mesh ''s%d'' (%s) does not match to previous mesh!',i,job.cdata{i}); + end + end + d = d(1,range,1); + + + if job.dmtx + S(i,:) = d; + else + eval(['s',num2str(i),'=d;']); + end + + %% evaluate mesh + if sinfo1.datatype==3 + if job.usefsaverage + CS = gifti(strrep(job.fsaverage,'lh.',sinfo1.side)); + vdata(1,range,:) = CS.vertices; + else + vdata(1,range,:) = mean(V,1); + end + end + + if job.verb + cat_progress_bar('Set',(si-1)*numel(job.cdata)/subsetsize + i); + end + end + + %% evaluate texture + try + eval(['cdata(range) = ' job.expression ';']); + catch %#ok + l = lasterror; %#ok<*LERR> + error('%s\nCan''t evaluate ""%s"".',l.message,job.expression); + end + + + + %cat_progress_bar('Set',si); + end + + + + + %% save texture + ppn = fileparts(job.output); if ~exist(ppn,'dir'), mkdir(ppn); end + if sinfo1.datatype==3 || strcmp(job.output(end-3:end),'.gii') + if ~strcmp(job.output(end-3:end),'.gii'), job.output = [job.output '.gii']; end + if sinfo1.datatype==3 + save(gifti(struct('vertices',shiftdim(vdata),'faces',S1{1}.faces,'cdata',cdata')),job.output,'Base64Binary'); + else + save(gifti(struct('cdata',cdata)),job.output,'Base64Binary'); + end + else + cat_io_FreeSurfer('write_surf_data',job.output,cdata'); + end + + if job.verb + cat_progress_bar('Clear'); + end +end + +function cat_surf_calc_selftest + % creation of a test directory with syntect (resampled) simple surface (cubes) + % + % s15mm.[rl]h.thickness.resampled.C01.gii % full gifti resampled + % s15mm.[rl]h.thickness.resampled.C02.gii % full gifti resampled + % [rl]h.thickness.C01 % FS texture > error + % [rl]h.thickness.resampled.C01 % FS resampled texture + % + % [rl]h/beta0815.gii % + % [rl]h/mask0815.gii % + % + % GUI - Parameter structure with(out) side handling + % + % job cases: + % - standard imcalc with a mix of GII and FS surfases + % - different outputs (PATH,FS-FILE,GII-File) + % - only texture, both, use AVG, ... + % - different expressions with and without datamatrix + % + +end + + + + + + + + + + + + + + + + + + + + + + + + + + ","MATLAB" +"Neurology","ChristianGaser/cat12","cat_surf_max.m",".m","3720","123","function [N,Z,M,A,XYZ] = cat_surf_max(X,L,G) +% Sizes, local maxima and locations of excursion sets on a surface mesh +% FORMAT [N,Z,M,A,XYZ] = cat_surf_max(X,L,G) +% X - a [nx1] array of stat values +% L - a [nx1] array of locations {in vertices} +% G - a patch structure +% +% N - a [px1] size of connected components {in vertices} +% Z - stat values of maxima +% M - location of maxima {in vertices} +% A - region number +% XYZ - cell array of vertices locations +%__________________________________________________________________________ +% +% See also: spm_max.m, spm_mesh_clusters.m and spm_mesh_get_lm.m +%__________________________________________________________________________ +% Copyright (C) 2012-2016 Wellcome Trust Centre for Neuroimaging +% +% modified version of spm_mesh_max because for some rare data only one global +% maximum was returned +% Guillaume Flandin +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +%-Get connected components +%-------------------------------------------------------------------------- +LL = NaN(size(G.vertices,1),1); +LL(L(1,:)) = X; +warning('off','MATLAB:subscripting:noSubscriptsSpecified'); +[C, N0] = spm_mesh_clusters(G,LL); + +%-Get local maxima +%-------------------------------------------------------------------------- +M0 = spm_mesh_get_lm(G,LL); + +Z = LL(M0); +A = C(M0); +M = [M0;ones(2,size(M0,2))]; +N = N0(A); + +% In rare cases where local maxima are not correctly found the number of clusters +% differs from cluster indices in A. Then, we have to add non-unique entries +% using function find_connected_component +if numel(unique(N0)) ~= max(A) + A2 = spm_mesh_adjacency(G); + A2 = A2 + speye(size(A2)); + M2 = find_connected_component(A2,LL); + + % find uniqe entries in both methods + M = [M0 M2]; + [tmp, ind] = unique(M); + M0 = M(sort(ind)); + + % and create new variables using corrected M0 + Z = LL(M0); + A = C(M0); + M = [M0;ones(2,size(M0,2))]; + N = N0(A); +end + +if nargout > 4 + XYZ = cell(1,max(A)); + for i=1:numel(XYZ) + XYZ{i} = find(C==i)'; + XYZ{i} = [XYZ{i};ones(2,size(XYZ{i},2))]; + end +end + +%========================================================================== +function C = find_connected_component(A, T); +% find connected components +% FORMAT C = find_connected_component(A,T) +% A - a [nxn[ (reduced) adjacency matrix +% T - a [nx1] data vector (using NaNs or logicals), n = #vertices +% +% C - a [nx1] vector of cluster indices +% +% modified version from spm_mesh_clusters.m 5065 2012-11-16 20:00:21Z guillaume +% + +%-Input parameters +%-------------------------------------------------------------------------- +T0 = T; +if ~islogical(T) + T = ~isnan(T); +end + +A1 = A; +A1(~T,:) = []; +A1(:,~T) = []; + +%-And perform Dulmage-Mendelsohn decomposition to find connected components +%-------------------------------------------------------------------------- +[p,q,r] = dmperm(A1); +N = diff(r); +CC = zeros(size(A1,1),1); +for i = 1:length(r)-1 + CC(p(r(i):r(i+1)-1)) = i; +end +C = NaN(numel(T),1); +C(T) = CC; + +mx_array = zeros(1,max(C)); +ind_array = zeros(1,max(C)); + +for i = 1:max(C) + N = find(C == i); + T1 = zeros(size(T0)); + T1(N) = T0(N); + [mx_array(i), ind_array(i)] = max(T1); +end + +%-Sort connected component labels according to their max T value +%-------------------------------------------------------------------------- +[tmp,ni] = sort(mx_array, 'descend'); +C = ind_array(ni); +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_defaults.m",".m","24517","372","function cat_defaults +% Sets the defaults for CAT +% FORMAT cat_defaults +%_______________________________________________________________________ +% +% This file is intended to be customised for the site. +% +% Care must be taken when modifying this file +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +clear global cat; +global cat + +% CAT12 installation folder +catdir = fileparts(which('cat12')); + +% Options for inital SPM12 segmentation that is used as starting point for CAT12. +%======================================================================= +cat.opts.tpm = {fullfile(spm('dir'),'tpm','TPM.nii')}; +cat.opts.ngaus = [1 1 2 3 4 2]; % Gaussians per class (SPM12 default = [1 1 2 3 4 2]) - alternative: [3 3 2 3 4 2] +cat.opts.affreg = 'mni'; % Affine regularisation (SPM12 default = mni) - '';'mni';'eastern';'subj';'none';'rigid' +cat.opts.warpreg = [0 0.001 0.5 0.05 0.2]; % Warping regularisation (SPM12 default) - no useful modification found +cat.opts.tol = 1e-4; % SPM preprocessing accuracy (CAT only!) - 1e-2 very low accuracy (fast); 1e-4 default; 1e-6 very high accuracy (slow) +cat.opts.accstr = 0.5; % SPM preprocessing accuracy (CAT only!) - 0 very low accuracy (fast) .. 1 very high accuracy (slow); default = 0.5 +cat.opts.biasstr = 0.5; % Strength of the bias correction that controls the biasreg and biasfwhm parameter (CAT only!) + % 0 - use SPM parameter; eps - ultralight, 0.25 - light, 0.5 - medium, 0.75 - strong, and 1 - heavy corrections + % job.opts.biasreg = min( 10 , max( 0 , 10^-(job.opts.biasstr*2 + 2) )); + % job.opts.biasfwhm = min( inf , max( 30 , 30 + 60*job.opts.biasstr )); +cat.opts.biasreg = 0.001; % Bias regularisation (cat.opts.biasstr has to be 0!) - 10,1,0.1,...,0.00001 + % smaller values for stronger bias fields +cat.opts.biasfwhm = 60; % Bias FWHM (cat.opts.biasstr has to be 0!) - 30:10:120,inf + % lower values for strong bias fields, but check for overfitting of the thalamus (values <45 mm) +cat.opts.samp = 3; % Sampling distance - alternative: 1.5 + % Initial SPM segmentation resolution, whereas the AMAP runs on the full or specified resolution + % described by cat.extopts.restype and cat.extopts.resval. Higher resolution did not improve the + % results in most results (but increase calculation time were. +cat.opts.redspmres = 0.0; % limit image resolution for internal SPM preprocessing output in mm (default: 1.0) + + +% Writing options +%======================================================================= + +% options: +% native 0/1 (none/yes) +% warped 0/1 (none/yes) +% mod 0/1/2/3 (none/affine+nonlinear/nonlinear only/both) +% dartel 0/1/2/3 (none/rigid/affine/both) + +% save surface and thickness +cat.output.surface = 1; % surface and thickness creation: 0 - no (default), 1 - lh+rh, 2 - lh+rh+cerebellum, + % 3 - lh, 4 - rh, 5 - lh+rh (fast, no registration, only for quick quality check and not for analysis), + % 6 - lh+rh+cerebellum (fast, no registration, only for quick quality check and not for analysis) + % 9 - thickness only (for ROI analysis, experimental!) + % +10 to estimate WM and CSF width/depth/thickness (experimental!) + +% save ROI values +cat.output.ROI = 1; % write xml-file with ROI data (0 - no, 1 - yes (default)) + +% bias and noise corrected, global intensity normalized +cat.output.bias.native = 0; +cat.output.bias.warped = 1; +cat.output.bias.dartel = 0; + +% bias and noise corrected, (locally - if LAS>0) intensity normalized +cat.output.las.native = 0; +cat.output.las.warped = 0; +cat.output.las.dartel = 0; + +% GM tissue maps +cat.output.GM.native = 0; +cat.output.GM.warped = 0; +cat.output.GM.mod = 1; +cat.output.GM.dartel = 0; + +% WM tissue maps +cat.output.WM.native = 0; +cat.output.WM.warped = 0; +cat.output.WM.mod = 1; +cat.output.WM.dartel = 0; + +% CSF tissue maps +cat.output.CSF.native = 0; +cat.output.CSF.warped = 0; +cat.output.CSF.mod = 0; +cat.output.CSF.dartel = 0; + +% WMH tissue maps (only for opt.extopts.WMHC==3) - in development +cat.output.WMH.native = 0; +cat.output.WMH.warped = 0; +cat.output.WMH.mod = 0; +cat.output.WMH.dartel = 0; + +% stroke lesion tissue maps (only for opt.extopts.SLC>0) - in development +cat.output.SL.native = 0; +cat.output.SL.warped = 0; +cat.output.SL.mod = 0; +cat.output.SL.dartel = 0; + +% label +% background=0, CSF=1, GM=2, WM=3, WMH=4 (if opt.extopts.WMHC==3), SL=1.5 (if opt.extopts.SLC>0) +cat.output.label.native = 1; +cat.output.label.warped = 0; +cat.output.label.dartel = 0; + +% Tissue classes 4-6 to create own TPMs +cat.output.TPMC.native = 0; +cat.output.TPMC.warped = 0; +cat.output.TPMC.mod = 0; +cat.output.TPMC.dartel = 0; + +% cortical thickness (experimental) +cat.output.ct.native = 0; +cat.output.ct.warped = 0; +cat.output.ct.dartel = 0; + +% percentage position (experimental) +cat.output.pp.native = 0; +cat.output.pp.warped = 0; +cat.output.pp.dartel = 0; + +% jacobian determinant 0/1 (none/yes) +cat.output.jacobian.warped = 0; + +% deformations +% order is [forward inverse] +cat.output.warps = [1 0]; + +% transformations +% order is affine rigid (both forward and inverse) +cat.output.rmat = 0; + +% Expert options +%======================================================================= +% general GUI compatible definition of most *str parameter: +% 0 - no correction +% eps - ultralight correction +% 0.25 - light correction +% 0.50 - medium correction +% 0.75 - strong correction +% 1 - heavy correction +% [inf - automatic correction] + +% skull-stripping options +cat.extopts.gcutstr = 2; % Strength of skull-stripping: 0 - SPM approach; eps to 1 - gcut; 2 - new APRG approach; -1 - no skull-stripping (already skull-stripped); default = 2 +cat.extopts.cleanupstr = 0.5; % Strength of the cleanup process: 0 to 1; default 0.5 + +% segmentation options +cat.extopts.NCstr =-Inf; % Strength of the noise correction: 0 to 1; 0 - no filter, -Inf - auto, 1 - full, 2 - ISARNLM (else SANLM), default -Inf +cat.extopts.LASstr = 0.5; % Strength of the local adaptation: 0 to 1; default 0.5 +cat.extopts.BVCstr = 0.5; % Strength of the Blood Vessel Correction: 0 to 1; default 0.5 +cat.extopts.regstr = 0.5; % Strength of Shooting registration: 0 - Dartel, eps (fast), 0.5 (default) to 1 (accurate) optimized Shooting, 4 - default SPM Shooting +cat.extopts.WMHC = 2; % Correction of WM hyperintensities: 0 - no correction, 1 - only for Dartel/Shooting + % 2 - also correct segmentation (to WM), 3 - handle as separate class; default 1 +cat.extopts.WMHCstr = 0.5; % Strength of WM hyperintensity correction: 0 to 1; default 0.5 +cat.extopts.SLC = 0; % Stroke lesion correction (SLC): 0 - no correction, 1 - handling of manual lesion that have to be set to zero! + % 2 - automatic lesion detection (in development) +cat.extopts.mrf = 1; % MRF weighting: 0 to 1; <1 - weighting, 1 - auto; default 1 + +% resolution option +cat.extopts.restype = 'optimal'; % resolution handling: 'native','fixed','best', 'optimal' +cat.extopts.resval = [1.0 0.30]; % resolution value and its tolerance range for the 'fixed' and 'best' restype + +% use BIDS data structure +[cat_ver, cat_rel] = cat_version; +cat.extopts.bids_folder = fullfile('derivatives',[cat_ver '_' cat_rel]); % default BIDS path relative to dataset root (parent of sub-*) +cat.extopts.bids_yes = 0; % use BIDS structure for saving data + +% check for multiple cores is different for octave +if strcmpi(spm_check_version,'octave') + cat.extopts.nproc = nproc; +else + cat.extopts.nproc = feature('numcores'); +end + +%{ +native: + Preprocessing with native resolution. + In order to avoid interpolation artifacts in the Dartel output the lowest spatial resolution is always limited to the voxel size of the normalized images (default 1.5mm). + + Examples: + native resolution internal resolution + 0.95 0.95 1.05 > 0.95 0.95 1.05 + 0.45 0.45 1.70 > 0.45 0.45 1.70 + +best: + Preprocessing with the best (minimal) voxel dimension of the native image or at least 1.0 mm.' + The first parameters defines the lowest spatial resolution for every dimension, while the second is used to avoid tiny interpolations for almost correct resolutions. + In order to avoid interpolation artifacts in the Dartel output the lowest spatial resolution is always limited to the voxel size of the normalized images (default 1.5mm). + + Examples: + Parameters native resolution internal resolution + [1.00 0.10] 0.95 1.05 1.25 > 0.95 1.05 1.00 + [1.00 0.10] 0.45 0.45 1.50 > 0.45 0.45 1.00 + [0.75 0.10] 0.45 0.45 1.50 > 0.45 0.45 0.75 + [0.75 0.10] 0.45 0.45 0.80 > 0.45 0.45 0.80 + [0.50 0.10] 0.45 0.45 0.80 > 0.45 0.45 0.50 + [0.50 0.30] 0.50 0.50 1.50 > 0.50 0.50 0.50 + [0.50 0.30] 1.50 1.50 3.00 > 1.50 1.50 1.50 + [0.00 0.10] 0.45 0.45 1.50 > 0.45 0.45 0.45 + +fixed: + This options prefers an isotropic voxel size that is controlled by the first parameter. + The second parameter is used to avoid tiny interpolations for almost correct resolutions. + In order to avoid interpolation artifacts in the Dartel output the lowest spatial resolution is always limited to the voxel size of the normalized images (default 1.5mm). + There is no upper limit, but we recommend to avoid unnecessary interpolation. + + Examples: + Parameters native resolution internal resolution + [1.00 0.10] 0.45 0.45 1.70 > 1.00 1.00 1.00 + [1.00 0.10] 0.95 1.05 1.25 > 0.95 1.05 1.00 + [1.00 0.02] 0.95 1.05 1.25 > 1.00 1.00 1.00 + [0.75 0.10] 0.75 0.95 1.25 > 0.75 0.75 0.75 + +optimal: + This option prefers an isotropic voxel size that is controlled by the median voxel size and a volume term that deals with highly anisotropic voxels. + The first parameter controls the lower resolution limit, while the second parameter is used to avoid tiny interpolations for almost correct resolutions. + + Examples: + Parameters native resolution internal resolution + [1.00 0.10] 0.50 0.50 0.90 > 0.50 0.50 0.60 + [1.00 0.10] 0.50 0.50 1.00 > 0.70 0.70 0.70 + [1.00 0.30] 0.50 0.50 1.00 > 0.50 0.50 0.70 + [1.00 0.10] 0.80 0.80 1.00 > 0.80 0.80 1.00 + [1.00 0.10] 0.45 0.45 1.70 > 0.90 0.90 0.90 + [1.00 0.10] 0.95 1.05 1.25 > 0.95 1.05 1.00 + [1.00 0.30] 0.95 1.05 1.25 > 0.95 1.05 1.25 +%} + + +% registration and normalization options +% Subject species: - 'human';'ape_greater';'ape_lesser';'monkey_oldworld';'monkey_newwold' (in development) +cat.extopts.species = 'human'; +% Affine PreProcessing (APP) with rough bias correction and brain extraction for special anatomies (nonhuman/neonates) +cat.extopts.APP = 1070; % 0 - none; 1070 - default; [1 - SPM; 5 - animal (no affreg)] +cat.extopts.setCOM = 1; % 0 - none; 1 - use center-of-mass to estimate origin as starting value for affine registration +cat.extopts.vox = 1.5; % voxel size for normalized data (EXPERIMENTAL: inf - use Tempate values) +cat.extopts.bb = 12; % boundary box: 12 - [-84 -120 -72;84 84 96]; 16 - [-90 -126 -72;90 90 108] +cat.extopts.shootingsurf = 'Template_T1'; % Shooting surface name +cat.extopts.pth_templates = fullfile(catdir,'templates_MNI152NLin2009cAsym'); % Templates and atlases folder for volumes +cat.extopts.darteltpm = {fullfile(cat.extopts.pth_templates,'Template_1_Dartel.nii')}; % Indicate first Dartel template (Template_1) +cat.extopts.shootingtpm = {fullfile(cat.extopts.pth_templates,'Template_0_GS.nii')}; % Indicate first Shooting template (Template 0) - not working +cat.extopts.shootingT1 = {fullfile(cat.extopts.pth_templates,'Template_T1_masked.nii')}; % T1 for result overlay, choose Template_T1.nii for non-masked T1 +cat.extopts.brainmask = {fullfile(cat.extopts.pth_templates,'brainmask.nii')}; % Brainmask for affine registration +cat.extopts.T1 = {fullfile(cat.extopts.pth_templates,'T1.nii')}; % T1 for affine registration +cat.extopts.cat12atlas = {fullfile(cat.extopts.pth_templates,'cat.nii')}; % CAT atlas with major regions for VBM, SBM & ROIs + +% surface options +cat.extopts.pbtres = 0.5; % internal resolution for thickness estimation in mm (default 0.5) +cat.extopts.SRP = 24; % surface reconstruction pipeline & self-intersection correction: + % 0/1 - CS1 without/with/with-optimized SIC + % 20/21/22 - CS2 without/with/with-optimized SIC + % 30 - CS3 + % 42 - CS4 +cat.extopts.reduce_mesh = 1; % optimize surface sampling: 0 - PBT res. (slow); 1 - optimal res. (default); 2 - internal res.; 3 - SPM init; 4 - MATLAB init; 5 - SPM full; + % 6 - MATLAB full; 7 - MATLAB full ext.; +cat.extopts.vdist = 2; % mesh resolution (experimental, do not change!) +cat.extopts.pbtlas = 0; % reduce myelination effects (experimental, not yet working properly!) +cat.extopts.thick_measure = 1; % distance method for estimating thickness: 1 - Tfs: Freesurfer method using mean(Tnear1,Tnear2) (default in 12.7+); 0 - Tlink: linked distance (used before 12.7) +cat.extopts.thick_limit = 5; % upper limit for Tfs thickness measure similar to Freesurfer (only valid if cat.extopts.thick_measure is set to ""1"" +cat.extopts.close_parahipp = 1; % optionally apply closing inside mask for parahippocampal gyrus to get rid of deep holes that lead to large + % cuts in gyri after topology correction. However, this may also lead to poorer quality of topology + % correction for other data and should be only used if large cuts in the parahippocampal areas occur +cat.extopts.scale_cortex = 0.7; % scale intensity values for cortex to start with initial surface that is closer to GM/WM border to prevent that gyri/sulci are glued + % if you still have glued gyri/sulci (mainly in the occ. lobe) you can try to decrease this value (start with 0.6) + % please note that decreasing this parameter also increases the risk of an interrupted parahippocampal gyrus +cat.extopts.add_parahipp = 0.1; % increase values in the parahippocampal area to prevent large cuts in the parahippocampal gyrus (initial surface in this area + % will be closer to GM/CSF border) + % if the parahippocampal gyrus is still cut you can try to increase this value (start with 0.15) + +% visualisation, print, developing, and debugging options +cat.extopts.colormap = 'BCGWHw'; % {'BCGWHw','BCGWHn'} and matlab colormaps {'jet','gray','bone',...}; +cat.extopts.report.color = []; % report color setting invert fontcolor if dark: [] - use figure color; 0.95 - light gray; [0.1 0.15 0.2] - dark blue +cat.extopts.verb = 2; % verbose output: 1 - default; 2 - details; 3 - write debugging files +cat.extopts.ignoreErrors = 1; % catch errors: 0 - stop with error (default); 1 - catch preprocessing errors and proceed with next subject (requires MATLAB 2008 or higher); + % 2 - catch preprocessing errors and try backup function if this also fails then proceed with the next subject (requires MATLAB 2008 or higher) +cat.extopts.expertgui = 0; % control of user GUI: 0 - common user modus with simple GUI; 1 - expert modus with extended GUI; 2 - developer modus with full GUI +cat.extopts.subfolders = 1; % use subfolders such as mri, surf, report, and label to organize your data (this option is ignored if BIDS structure is found in your data) +cat.extopts.experimental = 0; % experimental functions: 0 - default, 1 - call experimental unsafe functions +cat.extopts.print = 2; % display and print out pdf-file of results: 0 - off, 1 - volume only (use this to avoid problems on servers that do not support openGL), + % 2 - volume and surface (default) +cat.extopts.fontsize = get(0,'defaultuicontrolFontSize'); % default font size for GUI; +%cat.extopts.fontsize = spm('FontSizes',7); % set default font size for GUI manually; increase value for larger fonts or set it to +cat.extopts.send_info = 1; % send Matlab and CAT12 version to SBM server for internal statistics only. If you don't want to send this + % information set this flag to ""0"". See online help CAT12->CAT12 user statistics for more information +cat.extopts.gifti_dat = 1; % save gifti files after resampling with external dat-file, which increases speed of gifti-processing and keeps SPM.mat file small + % because the cdata field is not saved with full data in SPM.mat. + +% always use expert mode for standalone installations +if isdeployed, cat.extopts.expertgui = 1; end + +% Expert options - ROIs +%======================================================================= +% ROI maps from different sources mapped to Dartel CAT-space of IXI-template +% { filename , GUIlevel , tissue , use } +% filename = '' - path to the ROI-file +% GUIlevel = [ 0 | 1 | 2 ] - avaible in GUI level +% tissue = {['csf','gm','wm','brain','none']} - tissue classes for volume estimation +% use = [ 0 | 1 ] - default setting to use this atlas +cat.extopts.atlas = { ... + fullfile(cat.extopts.pth_templates,'neuromorphometrics.nii') 0 {'csf','gm','wm'} 1; ... % atlas based on 35 subjects + fullfile(cat.extopts.pth_templates,'lpba40.nii') 0 {'gm','wm'} 1; ... % atlas based on 40 subjects + fullfile(cat.extopts.pth_templates,'cobra.nii') 0 {'gm','wm'} 1; ... % hippocampus-amygdala-cerebellum-subcortex, 5 subjects, 0.6 mm voxel size + fullfile(cat.extopts.pth_templates,'hammers.nii') 0 {'csf','gm','wm'} 0; ... % atlas based on 30 subjects with 95 regions + fullfile(cat.extopts.pth_templates,'thalamus.nii') 0 {'gm'} 1; ... % thalamic nuclei based on DTI from 70 subjects with 14 regions + fullfile(cat.extopts.pth_templates,'thalamic_nuclei.nii') 0 {'gm'} 1; ... % thalamic nuclei based on hi-res T2 from 9 subjects with 22 regions + fullfile(cat.extopts.pth_templates,'hypothalamus.nii') 0 {'gm','wm'} 0; ... % thalamic nuclei based on DTI from 70 subjects with 14 regions + fullfile(cat.extopts.pth_templates,'suit.nii') 0 {'gm','wm'} 1; ... % cerebellar lobes from 20 subjects + fullfile(cat.extopts.pth_templates,'ibsr.nii') 0 {'csf','gm','wm'} 0; ... % less regions, 18 subjects, low-res T1 image quality + fullfile(cat.extopts.pth_templates,'aal3.nii') 1 {'gm'} 0; ... % many regions, but only labeled on one subject + fullfile(cat.extopts.pth_templates,'mori.nii') 1 {'gm','wm'} 0; ... % only one subject, but with WM regions + fullfile(cat.extopts.pth_templates,'anatomy3.nii') 1 {'gm','wm'} 0; ... % 93 regions, 10 subjects + fullfile(cat.extopts.pth_templates,'julichbrain3.nii') 0 {'gm','wm'} 0; ... % 207 regions, 25 subjects, V3.1, https://www.julich-brain-atlas.de/ + fullfile(cat.extopts.pth_templates,'Tian_Subcortex_S4_7T.nii') 1 {'gm'} 0; ... % 62 subcortical regions, 183 subjects + fullfile(cat.extopts.pth_templates,'Schaefer2018_100Parcels_17Networks_order.nii') 1 {'gm','wm'} 0; ... % atlas based on rsfMRI data from 1489 subjects + fullfile(cat.extopts.pth_templates,'Schaefer2018_200Parcels_17Networks_order.nii') 1 {'gm','wm'} 0; ... % atlas based on rsfMRI data from 1489 subjects + fullfile(cat.extopts.pth_templates,'Schaefer2018_400Parcels_17Networks_order.nii') 1 {'gm','wm'} 0; ... % atlas based on rsfMRI data from 1489 subjects + fullfile(cat.extopts.pth_templates,'Schaefer2018_600Parcels_17Networks_order.nii') 1 {'gm','wm'} 0; ... % atlas based on rsfMRI data from 1489 subjects +}; + +% { name fileid GUIlevel use } - in development +cat.extopts.satlas = { ... + 'Desikan' fullfile(catdir,'atlases_surfaces','lh.aparc_a2009s.freesurfer.annot') 0 1; + 'Destrieux' fullfile(catdir,'atlases_surfaces','lh.aparc_DK40.freesurfer.annot') 0 1; + 'HCP' fullfile(catdir,'atlases_surfaces','lh.aparc_HCP_MMP1.freesurfer.annot') 0 0; + 'JulichBrain' fullfile(catdir,'atlases_surfaces','lh.JulichBrainAtlas_3.1.freesurfer.annot') 0 0; + ... Schaefer atlases ... + 'Schaefer2018_100P_17N' fullfile(catdir,'atlases_surfaces','lh.Schaefer2018_100Parcels_17Networks_order.annot') 1 0; + 'Schaefer2018_200P_17N' fullfile(catdir,'atlases_surfaces','lh.Schaefer2018_200Parcels_17Networks_order.annot') 0 0; + 'Schaefer2018_400P_17N' fullfile(catdir,'atlases_surfaces','lh.Schaefer2018_400Parcels_17Networks_order.annot') 1 0; + 'Schaefer2018_600P_17N' fullfile(catdir,'atlases_surfaces','lh.Schaefer2018_600Parcels_17Networks_order.annot') 1 0; +}; + + + +%======================================================================= +% PRIVATE PARAMETERS (NOT FOR GENERAL USE) +%======================================================================= + + +% Additional maps +%======================================================================= +% atlas maps (for evaluation) +cat.output.atlas.native = 0; +cat.output.atlas.warped = 0; +cat.output.atlas.dartel = 0; + +% IDs of the ROIs in the cat atlas map (cat.nii). Do not change this! +cat.extopts.LAB.NB = 0; % no brain +cat.extopts.LAB.CT = 1; % cortex +cat.extopts.LAB.CB = 3; % Cerebellum +cat.extopts.LAB.BG = 5; % BasalGanglia +cat.extopts.LAB.BV = 7; % Blood Vessels +cat.extopts.LAB.TH = 9; % Hypothalamus +cat.extopts.LAB.ON = 11; % Optical Nerve +cat.extopts.LAB.MB = 13; % MidBrain +cat.extopts.LAB.BS = 13; % BrainStem +cat.extopts.LAB.VT = 15; % Ventricle +cat.extopts.LAB.NV = 17; % no Ventricle +cat.extopts.LAB.HC = 19; % Hippocampus +cat.extopts.LAB.HD = 21; % Head +cat.extopts.LAB.HI = 23; % WM hyperintensities +cat.extopts.LAB.PH = 25; % Gyrus parahippocampalis +cat.extopts.LAB.LE = 27; % lesions + +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_vol_partvol.m",".m","54072","1029","function [Ya1,Ycls,YMF,Ycortex] = cat_vol_partvol(Ym,Ycls,Yb,Yy,vx_vol,extopts,Vtpm,noise,job,Ylesionmsk,Ydt,Ydti) +% ______________________________________________________________________ +% Use a segment map Ycls, the global intensity normalized T1 map Ym and +% the atlas label map YA to create a individual label map Ya1. +% The atlas contain main regions like cerebrum, brainstem, midbrain, +% cerebellum, ventricle, and regions with blood vessels. +% +% This function try to solve the following problems: +% 1) Finding of the cerebrum, the cerebellum, the head, blood vessels, +% brain skin and other mayor structures based on atlas (YA) and +% tissue class information (Yp0). +% To do this it is important to use data from the T1-map (Ym) that +% use the same intensity scaling as the segment map Yp0, but have +% more information about partial volume regions. +% 2) Set Partions: +% 2.1) Find biggest WM part of each region. +% 2.2) Align the nearest region class for other voxel +% 2.3) Finding and Filling of the ventricle and the Basalganglia +% 2.4) Find blood vessels +% 2.5) Brain extraction +% 2.6) Side alignment +% ______________________________________________________________________ +% +% Structure: +% +% [vol,Ya1,Yb,YMF] = cat_vol_partvol(YA,Yp0,Ym,Yl0,opt) +% +% INPUT: YA = 3D-volume with brain regions (altas map) +% Yp0 = 3D-volume with tissue propability map (CSF=1,GM=2;WM=3) +% Ym = intensity normalized T1 image (BG=0,CSF=1/3,GM=2/3,WM=1) +% Yl0 = spm-classes 4-6 (intracranial=1,skull=2,background=3) +% opt +% .res = resolution for mapping +% .vx_vol = voxelsize +% .LAB = label of Ya1 map (see LAB definition below) +% +% +% OUTPUT: vol = structure with volumes +% Ya1 = individual label map +% Yb = brain mask +% YMF = filling mask for ventricle and subcortical structures +% +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +% ______________________________________________________________________ +% +% Development comments: +% ToDo: +% - WMHs werden bei geringer Aufl?sung ?berschaetzt +% - mehr Kommentare bei WMHC und SLC +% +% Was ist neu im Vergleich zu anderen? +% - Zuweisung durch Dartel mit hoher Genauigkeit moeglich +% - Erweiterung von SPM/VBM durch MainROIs (Seiten, Lappen, ...) +% - Verbesserung der SPM/VBM durch bessere Enfernung von unerwuenschtem +% Gewebe (ON, Blutgefaesse ...) +% - Blutgefaesse koennnen als erweitere Masken fuer fMRI genutzt werden +% um Seiteneffekte besser ausblenden zu koennen. +% [- Beliebige Atlanten koennen genutzt werden.] +% +% Todo: +% - Besserer Atlas +% - BV vs. HD - glaetten in dilated HD region +% - Fuellen von CSF Luecken bei LAB~=BV und Ym<1.2 und LAB==NV? +% +% ______________________________________________________________________ + + + +% ---------------------------------------------------------------------- +% fast partitioning for B3C[, and LAS] +% ---------------------------------------------------------------------- +% VBM atlas atlas map to find important structures for the LAS and the +% skull-stripping, which are the subcortical GM regions and the cerebellum. +% Maybe also WM hyperintensity have to be labeled here as a region without +% local correction - actual clear WMHs are handeled as GM. +% ---------------------------------------------------------------------- + + % definition of ROIs + +% LAB.CT = 1; % cortex +% LAB.MB = 13; % MidBrain +% LAB.BS = 13; % BrainStem +% LAB.CB = 3; % Cerebellum +% LAB.ON = 11; % Optical Nerv +% LAB.BG = 5; % BasalGanglia +% LAB.TH = 9; % Hypothalamus +% LAB.HC = 19; % Hippocampus +% LAB.VT = 15; % Ventricle +% LAB.NV = 17; % no Ventricle +% LAB.BV = 7; % Blood Vessels +% LAB.NB = 0; % no brain +% LAB.HD = 21; % head +% LAB.HI = 23; % WM hyperintensities +% LAB.PH = 25; % Gyrus parahippocampalis + + % if there is a breakpoint in this file set debug=1 and do not clear temporary variables + dbs = dbstatus; debug = 0; for dbsi=1:numel(dbs), if strcmp(dbs(dbsi).name,mfilename); debug = 1; break; end; end + + Yp0toC = @(Yp0,c) 1-min(1,abs(Yp0-c)); + + try + if job.extopts.ignoreErrors > 2 + Yg = cat_vol_grad(Ym,vx_vol) ./ max(eps,Ym); + gth = max(0.05,min( 1/3 , cat_stat_nanmean( Yg( cat_vol_morph( smooth3( Ycls{2}>240 )>0.5 ,'e') )) * 1.5 )); + clsintg = @(x) cat_stat_nanmedian(Ym(Ycls{x}>128 & Yg 2 + %error('runbackup') + end + + def.uhrlim = 0.7; + extopts = cat_io_checkinopt(extopts,def); + + LAB = extopts.LAB; + BVCstr = mod(extopts.BVCstr,1) + (extopts.BVCstr==1 || extopts.BVCstr==2); + verb = extopts.verb-1; + PA = extopts.cat12atlas; + vx_res = max( extopts.uhrlim , max( [ max(vx_vol) min(vx_vol) ] )); + noise = double(noise); + + + %% map atlas to RAW space + if verb, fprintf('\n'); end + stime = cat_io_cmd(' Atlas -> subject space','g5','',verb); dispc=1; + % CAT atlas + YA = cat_vol_ctype( cat_vol_sample(Vtpm(1),PA{1},Yy,0) ); + + % template map + Yp0A = single( cat_vol_sample(Vtpm(1),Vtpm(1),Yy,1) )*2 + ... + single( cat_vol_sample(Vtpm(1),Vtpm(2),Yy,1) )*3 + ... + single( cat_vol_sample(Vtpm(1),Vtpm(3),Yy,1) )*1; + + + % WMH atlas + watlas = 3; + switch watlas + case 1, PwmhA = strrep(PA{1},'cat.nii','cat_wmh_soft.nii'); + case 2, PwmhA = strrep(PA{1},'cat.nii','cat_wmh.nii'); + case 3 + if isfield(job.extopts,'SLtpm') + PwmhA = job.extopts.WMHtpm{1}; + else + PwmhA = strrep(PA{1},'cat.nii','cat_wmh_miccai2017.nii'); + end + end + if ~isempty(PwmhA) && exist(PwmhA,'file') && ~strcmp(PwmhA,PA{1}) + YwmhA = cat_vol_ctype( cat_vol_sample(Vtpm(1),PwmhA,Yy,0) ); + else + YwmhA = max(0,min(1,Yp0A-2)); + end + switch watlas + case 2, YwmhA = min(1,max(0,YwmhA - 0.1) * 0.8); + case 3, YwmhA = min(1,max(0,cat_vol_smooth3X(YwmhA,1) - 0.01) * 10); + end + + + % Stroke lesion atlas + if isfield(job.extopts,'SLtpm') + PslA = job.extopts.SLtpm{1}; + else + PslA = strrep(PA{1},'cat.nii','cat_strokelesions_ATLAS303.nii'); + end + if ~isempty(PslA) && exist(PslA,'file') && ~strcmp(PslA,PA{1}) + YslA = cat_vol_ctype( cat_vol_sample(Vtpm(1),PslA,Yy,0) ); + YslA = YslA./max(YslA(:)); + else + YslA = max(0,min(1,Yp0A-2)); + end + + + % Blood vessel probability map (added 202305): + % Uses a blood vessel map created using MRA scans of the IXI and ICBM + % databases in combination with CSF and WM probability maps as far as + % larger blood vessels are typically located along the brainstem, corpus + % callosum and within the insula. + if isfield(job.extopts,'BVtpm') + Pbv = job.extopts.BVtpm{1}; + else + Pbv = strrep(PA{1},'cat.nii','cat_bloodvessels.nii'); + end + YwmA = single(cat_vol_sample(Vtpm(1),Vtpm(2),Yy,1)); + YcsfA = single(cat_vol_sample(Vtpm(1),Vtpm(3),Yy,1)); + if ~isempty(Pbv) && exist(Pbv,'file') + Vbv = spm_vol(Pbv); + YbvA = single(cat_vol_sample(Vbv,Vbv,Yy,1)); + YbvA = 1 - YwmA + max(YcsfA * 0.1 , YbvA); + else + YbvA = 1 - YwmA + YcsfA * 0.1; + end + clear YwmA YcsfA; + % clear Yy; % is needed in the backup routine + + + % use addition FLAIR images + if exist('job','var') && isfield(job,'data_wmh') && ~isempty(job.data_wmh) && isfield(job,'subj') && numel(job.data_wmh)>=job.subj + if isfield(job,'subj') && numel(job.data_wmh)>=job.subj + %% + [pp,ff,ee] = spm_fileparts(job.data_wmh{job.subj}); + Pflair = fullfile(pp,[ff ee]); + if ~isempty(Pflair) && exist(Pflair,'file') + stime = cat_io_cmd(' FLAIR corregistration','g5','',verb,stime); + + % coreg + Vflair = spm_vol(job.data_wmh{job.subj}); + Vm = spm_vol(job.data{job.subj}); + evalc('R = spm_coreg(Vm,Vflair,struct(''graphics'',0));'); + R = spm_matrix(R); %#ok + + % load + Vflair.dat = cat_vol_sanlm(struct('verb',0),Vflair,1,spm_read_vols(Vflair)); + Vflair.pinfo = repmat([1;0],1,size(Vflair.dat,3)); + Vflair.dt(1) = 16; + Yflair = zeros(Vm.dim,'single'); + for i=1:Vm.dim(3) + Yflair(:,:,i) = single( spm_slice_vol(Vflair, R \ Vflair.mat \ Vm.mat * spm_matrix([0 0 i]) ,Vm.dim(1:2),[1,NaN])); + end + end + else + cat_io_cprintf('err','Miss job.subj field in cat_vol_partvol to process FLAIR data'); + end + end + + + %% resize data + %if ~debug; clear Yy; end % need this in case of errors + if job.extopts.inv_weighting && cat_stat_nanmedian(Ym(Ycls{2}>128)) > cat_stat_nanmedian(Ym(Ycls{3}>128)) + %% RD202501: added extra cleanup to avoid blood-vessel-like structures in PD/FLAIR + Yw = single(Ycls{2})/255; + Yw2 = min(Yw,cat_vol_median3(Yw ,Yb | Yw>0,true(size(Ym)),0.3)); + Yw2 = min(Yw,cat_vol_median3(Yw2,Yb | Yw>0,true(size(Ym)),0.2)); + + end + + Yp0 = (single(Ycls{1})*2/255 + single(Ycls{2})*3/255 + single(Ycls{3})/255) .* Yb; + if isfield(job.extopts,'inv_weighting') && job.extopts.inv_weighting + Ym = Yp0/3; + end + + % work on average resolution + Ym0 = Ym; + % remove background + [Ym,BB] = cat_vol_resize(Ym ,'reduceBrain',vx_vol,2,Yb); + YA = cat_vol_resize(YA ,'reduceBrain',vx_vol,2,Yb); + Yp0 = cat_vol_resize(Yp0 ,'reduceBrain',vx_vol,2,Yb); + if exist('Ydt','var') + Ydt = cat_vol_resize(Ydt ,'reduceBrain',vx_vol,2,Yb); + end + if exist('Ydti','var') + Ydti = cat_vol_resize(Ydti ,'reduceBrain',vx_vol,2,Yb); + end + Yp0A = cat_vol_resize(Yp0A ,'reduceBrain',vx_vol,2,Yb); + YslA = cat_vol_resize(YslA ,'reduceBrain',vx_vol,2,Yb); + YbvA = cat_vol_resize(YbvA ,'reduceBrain',vx_vol,2,Yb); + YwmhA = cat_vol_resize(YwmhA ,'reduceBrain',vx_vol,2,Yb); + if exist('Yflair','var') + Yflair = cat_vol_resize(Yflair ,'reduceBrain',vx_vol,2,Yb); + end + if exist('Ylesionmsk','var') + Ylesionmsk = cat_vol_resize(Ylesionmsk ,'reduceBrain',vx_vol,2,Yb); + end + Yb = cat_vol_resize(Yb ,'reduceBrain',vx_vol,2,Yb); + % use lower resolution + [Ym,resTr] = cat_vol_resize(Ym ,'reduceV',vx_vol,vx_res,64); + YA = cat_vol_resize(YA ,'reduceV',vx_vol,vx_res,64,'nearest'); + Yp0 = cat_vol_resize(Yp0 ,'reduceV',vx_vol,vx_res,64); + if exist('Ydt','var') + Ydt = cat_vol_resize(Ydt ,'reduceV',vx_vol,vx_res,64); + end + if exist('Ydti','var') + Ydti = cat_vol_resize(Ydti ,'reduceV',vx_vol,vx_res,64); + end + Yp0A = cat_vol_resize(Yp0A ,'reduceV',vx_vol,vx_res,64); + YslA = single(cat_vol_resize(YslA ,'reduceV',vx_vol,vx_res,64)); + YbvA = cat_vol_resize(YbvA ,'reduceV',vx_vol,vx_res,64); + YwmhA = cat_vol_resize(YwmhA ,'reduceV',vx_vol,vx_res,64); + if exist('Yflair','var') + Yflair = cat_vol_resize(Yflair,'reduceV',vx_vol,vx_res,64); + end + if exist('Ylesionmsk','var') + Ylesionmsk = cat_vol_resize(Ylesionmsk,'reduceV',vx_vol,vx_res,64); + end + Yb = cat_vol_resize(Yb ,'reduceV',vx_vol,vx_res,64); + vx_vol = resTr.vx_volr; + + + % noise reduction + spm_smooth(Ym,Ym,0.6./vx_vol); + + + % prepare maps + YA = cat_vol_ctype(cat_vol_median3c(single(YA),Yp0>0)); % noise filter of atlas map + [~,~,YS] = cat_vbdist(single(mod(YA,2)) + single(YA>0)); YS=~mod(YS,2); % side map + YA(mod(YA,2)==0 & YA>0)=YA(mod(YA,2)==0 & YA>0)-1; % ROI map without side + YS = cat_vol_smooth3X(YS,4) > 0.5; % RD202501: side smoothing + Yg = cat_vol_grad(Ym,vx_vol); % gadient map (edge map) + Ydiv = cat_vol_div(Ym,vx_vol); % divergence map (edge map) + Ym = Ym*3 .* (Yb); + Yb = Yb>0.5; + + + + %% Create individual mapping: + stime = cat_io_cmd(' Major structures','g5','',verb,stime); + + % Mapping of major structure: + % Major structure mapping with downcut to have a better alginment for + % the CB and CT. Simple setting of BG and TH as GM structures. + Ya1 = zeros(size(Ym),'single'); + Ybg = zeros(size(Ym),'single'); + Ybgd = cat_vbdist(single(YA==LAB.BG),Yb,vx_vol); + Yosd = cat_vbdist(single(YA==LAB.TH | YA==LAB.VT | YA==LAB.HC | ... + YA==LAB.BS | (YA==LAB.CT & Ym>2.9)),Yb,vx_vol); + Ybg(smooth3(Yosd>3 & Ybgd<5 & Ym>1.9 & Ym<2.85 & Yg<4*noise & ... + ((Ybgd<1 & Ydiv>-0.01) | (Ydiv>-0.01+Ybgd/100)))>0.7) = 1; + Ybg(smooth3((Ybg==0 & Yp0>2.8 & Ym>2.8 & YA==LAB.CT) | Ym>2.9 | ... + YA==LAB.TH | YA==LAB.HC | Yosd<2 | (Ybg==0 & Yp0<1.25) | ... + (Ybg==0 & Ybgd>8) | (Ybg==0 & Ydiv<-0.01+Ybgd/200))>0.3) = 2; + Ybg(Ybg==0 & Ybgd>0 & Ybgd<10) = 1.5; + Ybg = cat_vol_laplace3R(Ybg,Ybg==1.5,0.005)<1.5 & Ym<2.9 & Ym>1.8 & Ydiv>-0.02; + Ya1(Ybg & Ym>1.8 & Yp0>1.9)=LAB.BG; % basal ganglia + % RD202501: hippocampus definition was not optimal here as we need a clear parahippocampus for surface reconstruction + Ya1( cat_vol_morph(YA==LAB.HC,'dd',3) & Ym>1.5 & Ym<2.5 & ~(cat_vol_morph(YA==LAB.PH,'dd',2) | ... + YA==LAB.TH | cat_vol_morph(YA==LAB.NV,'dd',5,vx_vol))) = LAB.HC; % hippocampus & ~cat_vol_morph(YA==LAB.PH,'d') + Ya1(Yp0>1.5 & Ym>1.5 & YA==LAB.HC) = LAB.HC; + NBVC = BVCstr > 0 && BVCstr <= 1; % RD202306: new BV correction by default + if NBVC + % define some high intensity BVs and the neocortex + % RD202501: extened the BV detection + Ybv = ( (smooth3(Yp0)-Yp0 )>.7 | (Ym-Ydiv)>3.4 | max(0,Ym - Yp0)>Ydiv+.8 & Ym>2 & Ydiv<0) & YA==LAB.CT & smooth3(Ya1>0)<.5; + Ybv = single( cat_vol_morph( Ybv , 'l', [inf 1])>0 ); % remove single voxels + Ybv( Ybv==0 & Yp0<=2 & YA==LAB.CT) = nan; Ybv(YA~=LAB.CT ) = nan; + Ybv( cat_vol_morph( cat_vol_morph( Yp0>2.1 & Ym<3.2 & (YA==LAB.CT | Ybgd<7),'o'),'lc') ) = 2; % add neocortex region + Ybv( cat_vol_morph( YA==LAB.HC | YA==LAB.VT | YA==LAB.PH | YA==LAB.TH,'dd', 4) ) = 2; % add ""neocortex"" region + Ybv = cat_vol_downcut(Ybv,Ym - Ydiv,noise); + Ybv(Yp0>2.1 & Ym>2.3 & Ybv<2 & YA==LAB.CT) = 1; + Ybv = single( cat_vol_morph( Ybv==1 , 'l', [inf 2])>0 ); % remove single voxels + Ya1( cat_vol_morph( Ybv==1,'dc') ) = LAB.BV; clear Ybv + Ya1( cat_vol_morph( ((Yp0>2.5 & Ym>2.5 & Ym<3 -(YbvA.^4*BVCstr - 1) & (YA==LAB.CT | YA==LAB.BG)) | ... + (Yp0>1.5 & Ym<3.01 & Yp0A>2.5 & Ybgd>1 & Ybgd<8 & (Ybgd>4 | ... + Ydiv<-0.02+Ybgd/200))) & Ya1==0 , 'l',[.1 10 ])) = LAB.CT; % cerebrum + Yhbv = max(0,8*-Ydiv).^4 .* (2*Yg).^4 .* Ym .* 2.*smooth3(Yp0<2.9) .* (YbvA - 1).^2 .* (YA~=LAB.CB); % .* cat_vol_morph(Ya1==0,'e'); + Ya1(Ya1==0 & Yhbv>.2*(1-BVCstr)) = LAB.BV; + else + % older version + Ya1(((Yp0>2.5 & Ym>2.5 & (YA==LAB.CT | YA==LAB.BG )) | ... + (Yp0>1.5 & Ym<3.5 & Ybgd>1 & Ybgd<8 & (Ybgd>4 | ... + Ydiv<-0.02+Ybgd/200))) & Ya1==0)=LAB.CT; % cerebrum + end + % use region-growing in case of the cerebellum to compensate for fine structure + Ycb = single(YA==LAB.CB) + 2*single(cat_vol_morph( YA==LAB.CT,'de',6)); + Ycb(Yp0<1 & Ym<2) = nan; Ycb(cat_vol_morph( YA~=LAB.CB,'de',12)) = nan; + [Ycb,Yd] = cat_vol_downcut(Ycb,Ym,noise); + Ycb = single(YA==LAB.CB) | cat_vol_smooth3X(Ycb==1 & Yd<50,2)>.7; + % cortext growing without BVs + Yct = single( (Ya1==LAB.CT | (Ybgd>2 & Ybgd<7)) & (Ym - Ydiv)<3.1 ) + 2*single(cat_vol_morph( YA==LAB.CB,'de',6)); + Yct(Yp0<1 & Ym<1.7) = nan; Yct(cat_vol_morph( YA~=LAB.CT,'de',12)) = nan; + [Yct,Yd] = cat_vol_downcut(Yct,Ym - Ydiv,noise/4); + Yct = (Yct==1 & smooth3(Yd)<20); + + % set other regions + Ya1(Yp0>1.9 & Ym>1.7 & Ym<3.1 & Ycb)=LAB.CB; % cerebellum + Ya1(Yp0>1.9 & Ym>1.7 & YA==LAB.BS)=LAB.BS; % brainstem + Ya1(Yp0>1.9 & Ym>1.7 & YA==LAB.ON)=LAB.ON; % optical nerv + Ya1(Yp0>1.9 & Ym>1.7 & Yp0<3 & YA==LAB.TH)=LAB.TH; % thalamus + Ya1(Yp0>1.9 & Ym>1.7 & cat_vol_smooth3X(YA==LAB.MB,2)>.1)=LAB.MB; % midbrain + Ya1(Yp0>1.9 & Ym>1.7 & YA==LAB.PH & Ya1==0)=LAB.CT; % added PH as cortex + Ya1(Yp0>1.9 & Ym>1.7 & Ym<3.0 & Yct & Ya1==0)=LAB.CT; % added CT + Ya1(Yp0>1.9 & Ym>1.7 & cat_vol_morph(YA==LAB.VT | YA==LAB.HC | YA==LAB.PH ,'dd',2) & Ya1==0)=LAB.CT; % added CT + % denoising for regions but not BV + Ya1 = cat_vol_median3c(Ya1,Ya1>0 & ~YA==LAB.BV); + if NBVC + % create a cerebellar mask to avoid corrections there + Ycb3 = cat_vol_morph(YA==LAB.CB,'d',1) | (cat_vol_morph(YA==LAB.CB,'d',3) & YbvA<0.5 & Ym<2.5); + Ysc5 = cat_vol_morph(YA==LAB.HC | YA==LAB.BG | YA==LAB.TH,'dd',3); + Yhc3 = smooth3(cat_vol_morph(YA==LAB.HC | YA==LAB.PH | YA==LAB.VT | Ysc5,'d'))>.5; + Ya1(Ysc5 & Ym>2.6 & Ym<2.95 & Ya1==0) = LAB.CT; + + % extend the neocortical area + Ya1(Ya1<1 & Ym<1.8) = nan; + [Ya1,Yd] = cat_vol_downcut(Ya1,Ym,noise); Ya1(isinf(Ya1) | Yd>15 ) = 0; + + % get blood vessels as intensity-based eikonal-distance map with + % different grow rates, where the first one is more limited by the + % local intensities and the second one allows to remove the general + % distance aspect + Ya0 = single(Ya1>0 & Ya1~=LAB.BV); Ya0(Ym<1.7) = nan; + [~,Yd] = cat_vol_downcut(Ya0,Ym,noise ); clear Ya0 + Ya0 = single(Ya1>0 & Ya1~=LAB.BV); Ya0(Ym<1.7) = nan; + [~,Yd2] = cat_vol_downcut(Ya0,Ym,noise * 16); clear Ya0 + Ya1( ((Yd - Yd2)>10./YbvA) & Ym>2.4 & YA==LAB.CT & ~Ycb3 & ~Yhc3 & YbvA>.7) = LAB.BV; % add highly distant voxels + Ya1(Ya1==0 & Ym>2.4 & Yd>70 & Yd2>50 & ~cat_vol_morph(YA>1 & YA~=LAB.HD,'d') & ~Ycb3 & ~Yhc3) = LAB.BV; % mask further BV + Ya1(Ya1==0 & Ym>2.2 & Yd<20 & ~cat_vol_morph(YA>1 & YA~=LAB.HD,'d') & ~Ycb3) = LAB.CT; % add also save brain voxels + Ya1(Ya1==LAB.BV & cat_vol_morph(Ya1==LAB.BV,'l',[inf 16])==0) = 0; + clear Ycb3 Yhc3 + + %% modified old lines + Ya1((Ya1==0 & Yp0<1.5 & Ym<1.5 & Yp0>1.3 & Ym>1.3) & YA==LAB.BV) = LAB.BV; % low-int BV (updated due to cerebellar errors RD20190929) + Ya1((cat_vol_morph(Ya1==0 & YA~=LAB.CB,'e') & (Ym>2.5 | Ym<1.7) & YA==LAB.CT & ... + Ym>2 - (YbvA-1).^4*BVCstr) & (YA==LAB.BV | YbvA>1))=LAB.BV; % high-int BV (updated due to cerebellar errors RD20190929) + + %% some light region growing + Ya1(Ya1<1 & Ym<2.2) = nan; + [Ya1,Yd] = cat_vol_downcut(Ya1,Ym,2*noise); Ya1(isinf(Ya1) | (Yd>15 & Ya1==LAB.BV) ) = 0; + Ya1(Ya1<1 & Ym<1.9) = nan; + [Ya1,Yd] = cat_vol_downcut(Ya1,Ym,2); Ya1(isinf(Ya1) | (Yd>15 & Ya1==LAB.BV) ) = 0; + Ya1(Ya1<1 & Ym<1.7) = nan; + [Ya1,Yd] = cat_vol_downcut(Ya1,Ym,2); Ya1(isinf(Ya1) | (Yd>15 & Ya1==LAB.BV ) ) = 0; + + %% cleanup? + Ymsk = single(smooth3(Ym)>2.2 | Ya1==LAB.BV) .* ((Ya1==LAB.CT) + 2*(Ya1==LAB.BV)); + Ymsk = cat_vol_localstat(Ymsk,Ymsk>0,1,1,8); + %Ya1a = Ya1; Ya1a(Ymsk>0 & Ymsk<1.5) = LAB.CT; Ya1a(Ymsk>=1.5) = LAB.BV; + Ya1(Ymsk>0 & Ymsk<1.5) = LAB.CT; Ya1(Ymsk>=1.5) = LAB.BV; clear Ymsk + + else + Ya1((Ya1==0 & Yp0<1.5 & Ym<1.5 & Yp0>1.3 & Ym>1.3) & YA==LAB.BV)=LAB.BV; % low-int VB (updated due to cerebellar erros RD20190929) + Ya1((Ya1==0 & Yp0>3.0 & Ym>3.2) & YA==LAB.BV)=LAB.BV; % high-int VB (updated due to cerebellar erros RD20190929) + Ya1(Ya1==0 & Ym<1.9)=nan; + Ya1 = cat_vol_downcut(Ya1,Ym,4*noise); Ya1(isinf(Ya1))=0; + Ya1 = cat_vol_median3c(Ya1,Yb); % smoothing + end + Ya1(YA==LAB.TH & Ym>1.75 & Ym<2.85 & Ydiv>-0.1 & Yg<.2 & ~cat_vol_morph(Ya1==LAB.MB | Ya1==LAB.VT | Ya1==LAB.HC | Ya1==LAB.PH,'dd',4,vx_vol))=LAB.TH; % thalamus + Ya1 = cat_vol_median3c(Ya1,Ya1>0 & ~YA==LAB.BV); % smoothing + clear Ybg Ybgd; + Ya1((Yp0>1.75 & Ym>1.75 & Yp0<2.5 & Ym<2.5) & Ya1==LAB.MB)=0; % midbrain correction + Ya1(Ya1==LAB.CT & ~cat_vol_morph(Ya1==LAB.CT,'do',1.4)) = 0; + + % correction of structures that should be compact + Ya1(Ya1==LAB.BS & ~cat_vol_morph(cat_vol_morph(Ya1==LAB.BS,'o'),'c')) = 0; + Ya1(Ya1==LAB.MB & ~cat_vol_morph(cat_vol_morph(Ya1==LAB.MB,'o'),'c')) = 0; + Ya1(Ya1==LAB.PH) = 0; + Ya1 = cat_vol_median3c(Ya1,Ya1>0 & ~YA==LAB.BV); + + + %% Mapping of ventricles: + % Ventricle estimation with a previous definition of non ventricle CSF + % to have a second ROI in the region-growin. Using only the ventricle + % ROI can lead to overgrowing. Using of non ventrilce ROI doesn't work + % because dartle failed for large ventricle. + % It is important to use labopen for each side! + stime = cat_io_cmd(' Ventricle detection','g5','',verb,stime); + %% RD202501: added parahypocampus here to avoid overgrowing ventricles and filling issues and defects + Yph = Ym>2 & cat_vol_smooth3X(YA==LAB.PH | YA==LAB.HC,2)>.1; + Ynv = cat_vol_morph(~Yb,'d',4,vx_vol) | cat_vol_morph(YA==LAB.CB,'dd',10,vx_vol) | ...% RD202501: extend CB + cat_vol_morph(YA==LAB.BS,'dd',2,vx_vol) | ... + (cat_vol_morph(smooth3(YA==LAB.NV | YA==LAB.TH)>.8,'dd',2,vx_vol) & Ym<1.8) | ... + cat_vol_morph(YA==LAB.TH & Ym<2.5,'e',1,vx_vol); + Ynv = Ynv | Yph | (~cat_vol_morph((Yp0>0 & Yp0<1.5 & (YA==LAB.VT)),'dd',20,vx_vol) & Yp0<1.5); + Ynv = single(Ynv & Ym<2 & ~cat_vol_morph(Yp0<2 & (YA==LAB.VT) & Yg<0.2,'d',4,vx_vol) & ~Yph); + Ynv = single(Ynv | (cat_vol_morph(smooth3(YA==LAB.NV | YA==LAB.TH)>.8,'dd',1,vx_vol) & Ym<1.8)); + Ynv = Ynv & (~cat_vol_morph(Ya1==LAB.HC | Ya1==LAB.PH,'d',8) | Ya1==LAB.NV); + Ynv = smooth3(round(Ynv))>0.5; + % between thamlamus + Ynv = Ynv | (cat_vol_morph(Ya1==LAB.TH,'c',10) & Yp0<2) | YA==LAB.CB | YA==LAB.BS; + Ynv = smooth3(Ynv)>0.8; + Yvt = single(smooth3(Yp0<1.5 & (YA==LAB.VT) & Yg<0.25 & ~Ynv)>0.7); + Yvt(cat_vol_morph( (YA==LAB.HC | YA==LAB.PH) & ~(Ya1==LAB.HC | Ya1==LAB.PH) & Yg-.1 & Ym<1.2 & Yp0<1.2,'do',3)) = 1; + Yvt(Yvt==0 & ~(smooth3(Ya1==LAB.HC)>.1 & Ym>1.1) & cat_vol_morph( smooth3(Ya1==LAB.HC)>.7 | Yvt,'dc',7,vx_vol) & Ym<1.25 & Yg<0.3)=1; + Yvt(cat_vol_morph(Yvt,'l',[inf,10])==0 & Yvt>0) = 0; + Yvt(Yvt==0 & Ynv)=2; Yvt(Yvt==0 & Ym>1.8)=nan; Yvt(Yvt==0)=1.5; + Yvt(Yvt==0 & Ydiv<-0.1) = nan; Yvt(~Yb) = nan; + + %% subcortical stroke lesions + if exist('Ylesionmsk','var'), Yvt(Ylesionmsk>0.5) = nan; end + Yvt( cat_vol_morph(YslA>0.6 & Ym<2 & Ydiv./(Ym+eps)>0 & Yp0A>2.5 , 'do', 1 ) ) = 2; % WM + Yvt( cat_vol_morph(YslA>0.2 & Ym<2 & Ydiv./(Ym+eps)>0 & YA==LAB.BG , 'do', 1 ) ) = 2; % BG lesions + if exist('Ydt','var') && exist('Ydti','var') + % by deformation + Ystsl = (( cat_vol_smooth3X( 1-single(cat_vol_morph(YA==LAB.VT,'dd',10,vx_vol)) ,4 ) .* ... + cat_vol_smooth3X( single((Ydt - Ydti)>0.7),4) )>0.1 & Ym>0.5 & Ym<2.5 ); + %% + Ystsl = Ystsl | ... + ((cat_vol_smooth3X(1-single(cat_vol_morph(YA==LAB.VT,'dd',5,vx_vol)),4) .* ... + cat_vol_smooth3X(single((Ydt - Ydti)>0.7),4))>0.05 & Ym>1.5 & Ym<2.8 & ... + ~cat_vol_morph(YA==LAB.BG | YA==LAB.TH,'d',2)); + Ystsl = Ystsl | ... + (cat_vol_smooth3X(single((1/(Ydt+eps) - 1/(Ydti+eps))>0.7),4)>0.4 & Ym>1.5); + Ystsl =cat_vol_morph(Ystsl,'dc',4,vx_vol); + Yvt( cat_vol_morph(Ystsl,'e',2)) = 2; + else + Ystsl = false(size(Ynv)); + end + + %% bottleneck + Yvt2 = cat_vol_laplace3R(Yvt,Yvt==1.5,0.01); % first growing for large regions + Yvt(cat_vol_morph(Yvt2<1.4,'o',2) & ~isnan(Yvt) & Yp0<1.5) = 1; + Yvt(cat_vol_morph(Yvt2>1.6,'o',2) & ~isnan(Yvt) & Yp0<1.5) = 2; + Ygx = Ym/3 ./ cat_vol_localstat(Ym/3,Ym>1.125,1,3,1); Yvt(Yvt==1.5 & Ygx<.5)=nan; + Ygx = Ym/3 ./ cat_vol_localstat(Ym/3,Ym>1.25,1,3,1); Yvt(Yvt==1.5 & Ygx<.8)=nan; + Yvt2 = cat_vol_laplace3R(Yvt,Yvt==1.5,0.001); + % remove small objects + warning('off','MATLAB:cat_vol_morph:NoObject'); + Yvt = cat_vol_morph(Yvt2<1.5, 'l', [10 0.1]); + Yvt = cat_vol_morph(Yvt , 'l', [10 50]); + warning('on','MATLAB:cat_vol_morph:NoObject'); + Yvt = smooth3((Yvt | (YA==LAB.VT & Ym<1.7)) & Yp0<1.5 & Ym<1.5)>0.5; + %% + Ya1(Yvt) = LAB.VT; Yvtp = cat_vol_morph( Yvt ,'dd', 2) ; + Ya1( Ya1 == 0 & YA==LAB.HC & Yvtp & Yp0>1.9 & Ym<3.1 & Ym>1.9 ) = LAB.HC; + Ya1( Ya1 == 0 & YA==LAB.PH & Yvtp & Yp0>1.9 & Ym<3.1 & Ym>1.9 ) = LAB.PH; + Ya1( Ya1 == 0 & YA==LAB.CT & Yvtp & Yp0>1.9 & Ym<3.1 & Ym>1.9 ) = LAB.CT; + if ~debug, clear Yvts1; end + + + + %% Mapping of blood vessels + % For this we may require the best resolution! + % first a hard regions growing have to find the real WM-WM/GM region + if BVCstr + stime = cat_io_cmd(' Blood vessel detection','g5','',verb,stime); + Ywm = Yp0>2.25 & Ym>2.25 & Yp0<3.1 & Ym<4; % init WM + Ywm = Ywm | (cat_vol_morph(Ywm,'dd') & Ym<3.5); + %% + Ywm = single(cat_vol_morph(Ywm,'lc',2,vx_vol)); % closing WM + Ywm(smooth3(single(Ywm))<0.5)=0; % remove small dots + Ywm(~Ywm & (Yp0<0.5 | Ym<1.2 | Ym>4))=nan; % set regions growing are + [Ywm1,YDr] = cat_vol_downcut(Ywm,Ym,2*noise*(1-BVCstr/2)); % region growing + Ywm(Ywm==-inf | YDr>20)=0; Ywm(Ywm1>0)=1; clear Ywm1 % set regions growing + % smoothing + Ywms = smooth3(single(Ywm)); Yms=smooth3(Ym); + Ywm(Ywms<0.5)=0; Ywm(Ywms>0.5 & Yb & (Ym-Yms)<0.5)=1; + Ywm(Ywms<0.5 & Yb & (Ym-Yms)>0.5)=0; clear Ywms + %% set blood vessels + Ybv=cat_vol_morph( (Ym>3.75-(0.5*BVCstr) & Yp0<2+(0.5*BVCstr)) | ... % high intensity, but not classified as WM (SPM) + (Yms>2.5 & (Ym-Yms)>0.6) | ... % regions that strongly change by smoothing + (Ym>2.5-(0.5*BVCstr) & Ywm==0) | ... % high intensity, but not classified as WM (SPM) + 0 ...(Ym>2.5-(0.5*BVCstr) & Yp0<2+(0.5*BVCstr) & Ya1==0 & YA==LAB.CT),'c',1,vx_vol) & ... RD 201901 ADNI 128S0216 error + ,'c',1,vx_vol) & ... + cat_vol_morph(Ya1==LAB.CT,'d',2,vx_vol) & ~cat_vol_morph(Ya1==LAB.HC,'d',2,vx_vol) & ... + cat_vol_morph((Ya1==0 | Ya1==LAB.CB | Ya1==LAB.CT | Ya1==LAB.BV | Ym>1.5) & Ya1~=LAB.VT & Yp0<2.5,'e',1,vx_vol) & ... avoid subcortical regions + ~Ywm; if ~debug, clear Ywm; end + Ybb = cat_vol_morph(Yp0>0.5,'lc',1,vx_vol); + + %% RD 201901 ADNI 128S0216 error + % Ycenter = cat_vol_smooth3X(YS==0,2)<0.95 & cat_vol_smooth3X(YS==1,2)<0.95 & Yp0>0; + Yb2 = Ybv; %smooth3( Ydiv<0.1 & Ym>1.5 & (Ym-Yp0)>0.5 & (Ycenter | cat_vol_morph(~Yb,'dd',3)) & Ya1==0 )>0.5; + + %% + Ybv = ((Ybv | Yb2) & Ybb) | smooth3(Yp0<0.5 & Ybb)>0.4; clear Ybb; + %% smoothing + Ybvs = smooth3(Ybv); + Ybv(Ybvs>0.3 & Ym>2.5 & Yp0<2.5)=1; Ybv(Ybvs>0.3 & Ym>3.5 & Yp0<2.9)=1; + Ybv(Ybvs<0.2 & Ym<4-2*BVCstr)=0; clear Yvbs; + Ya1(Ybv)=LAB.BV; clear Ybv + end + + + + %% WMH (White Matter Hyperintensities): + % WMHs can be found as GM next to the ventricle (A) that do not belong + % to a subcortical structure (A) or there must be a big difference + % between the tissue SPM expect and the real intensity 'Yp0 - Ym' (C). + % Furthermore no other Sulic (=near other CSF) should be labeld (D). + % #################################################################### + % There can also be deep GM Hyperintensities! + % #################################################################### + % ds('l2','',vx_vol,Ym,Ywmh,Ym/3,Ym/3,90) + % #################################################################### + % ToDo: Separate detection of ventricular lesion and subventriculars + % #################################################################### + if extopts.WMHC>=0 && extopts.WMHCstr>=0 && ~extopts.inv_weighting + % T1 bias correction + Yi = Ym .* (Yp0>2.5 & Ym>2.5 & cat_vol_morph(Ya1~=LAB.BG | Ya1~=LAB.VT | Ya1~=LAB.TH,'d',2)); + Yi = cat_vol_median3(Yi,Yi>0,Yi>0); Yi = cat_vol_localstat(Yi,Yi>0,1,3); + for i=1:2, Yi = cat_vol_localstat(Yi,Yi>0,1,1); end + Yi = cat_vol_approx(Yi,'nh',vx_vol,3); + Ymi = Ym ./ Yi * 3; + + + % estimate relative CSF volume + Yp0e = Yp0.*cat_vol_morph(Yb,'e',2); + vols = mean([sum(round(Yp0e(:))==1) sum(round(Yp0e(:))==1 & Yvt(:))] / ... + sum(round(Yp0e(:))>0.5)); clear Yp0e; + noisew = cat_vol_localstat(smooth3(Ymi)*2,cat_vol_morph(Yp0>2.5,'e') & Ya1==LAB.CT & ~(YwmhA>0.5 & Ymi<2.7),3,4); + noisew = cat_stat_nanmean(noisew(noisew(:)>0)); + noisec = cat_vol_localstat(smooth3(Ymi)*2,cat_vol_morph((cat_vol_morph(Yp0>0.5,'e') & .... + cat_vol_morph(Yp0<2.5,'e')) | cat_vol_morph(Ya1==LAB.VT,'e'),'o'),3,4); + noisec = cat_stat_nanmean(noisec(noisec(:)>0)); + if sum(noisec(:)>0)>100, noisew = min(noisew,cat_stat_nanmean(noisec(noisec(:)>0))); end + + % control variables + % only if there is a lot of CSF and not too much noise + extopts.WMHCstr = min( 1, max( 0, extopts.WMHCstr ./ max(1,mean(vx_vol)) )); % adaptiv for resolution + csfvol = max(eps,min(1.0, (vols - 0.05) * 10 )); % relative CSF volume weighting + if extopts.ignoreErrors > 2 || extopts.inv_weighting % only small correction in the backup/inverse pipeline + WMHCstr = eps; + else + WMHCstr = max(eps,min(1.0, extopts.WMHCstr .* csfvol )); % normalized WMHCstr + end + wmhvols = 40 - 30 * (1 - extopts.WMHCstr); % absolute WMH volume threshold + mth = [ min( 1.2 , 1.1 + noisew * (2 - extopts.WMHCstr) ) , ... % lower tissue threshold + max( 2.5 , 2.9 - noisew * (2 - extopts.WMHCstr) ) ]; % upper tissue threshold + %ath = 2.85 - 0.1 * WMHCstr; % tissue probability threshold + + stime = cat_io_cmd(sprintf(' WMH detection (WMHCstr=%0.02f > WMHCstr''=%0.02f)',... + extopts.WMHCstr,WMHCstr),'g5','',verb,stime); + + %% creation of helping masks with *YwmhL* and *Ycortex* as most important mask! + % Ybgth: subcortical GM regions with WMHs with intensities + % between CSF and GM + % Ycenter: area between the hemispheres that we ignore to avoid + % clossing of the small sulci (eg. close to the CC) + % Ycortex1: initial map to classify cortical GM + % Ycortex2: laplace filtered map to classify cortical GM + % Ycortex: final cortex map that also include CSF and parts of the + % normal subcortical structures + % YwmhL: extrem large WMs (important to use age-based threshold!) + % Yinsula: insula and claustrum + Ybgth = cat_vol_morph( YA==LAB.BG | Ya1==LAB.BS | Ya1==LAB.TH | YA==LAB.PH | YA==LAB.CB ,... + 'dd',1.5 + max(0,2-WMHCstr*4),vx_vol); + Ybgth = cat_vol_morph( Ybgth | Ya1==LAB.VT ,'dc',10,vx_vol); + Ycenter = cat_vol_smooth3X(YS==0,8)<0.95 & cat_vol_smooth3X(YS==1,8)<0.95 & Yp0>0; + + Ycortex1 = single(1.5 + 0.5*(Yvt2>1.5 & Yvt2<3 & Yp0<=2 & Ym<2.1) - 0.5*Yvt); Ycortex1(Ym>2.1) = nan; + %% + YwmhL = cat_vol_morph( smooth3((Yp0A + YwmhA)>1.9 & Ym>1.7 & Ym<2.2 & ~Ybgth & ~Ycenter & ... + cat_vol_morph( YwmhA>0 ,'dd',8) & YA==LAB.CT & ... % use Ywmh atlas + ~cat_vol_morph(Yvt2>1.6 & Yvt2<3 & Ym<1.8 ,'dd',3,vx_vol))>0.5,'do',4-3*WMHCstr,vx_vol); % age adaptation + %% + Ycortex1(cat_vol_morph(YwmhL,'dd',3) & Ycortex1==2) = 0; Ycortex1(YwmhL) = 1; + Ycortex2 = cat_vol_laplace3R(Ycortex1,Ycortex1==1.5,0.005); + Ycortex1( smooth3(Ycortex1==1.5 & Ycortex2>1.5 & Yp0<=2 & Ym<2.1)>0.6) = 2; + Ycortex1(isnan(Ycortex1) & Ym>2.8) = 1; + Ycortex2 = cat_vol_laplace3R(Ycortex1,Ycortex1==1.5,0.002); + Ycortex = cat_vol_morph( (Ycortex2>1.5 & Ycortex2<3) | Ya1==LAB.HC,'dd',2) & Yp0<2.8; + if ~debug, clear Ycortex1 Ycortex2; end + Yinsula = cat_vol_morph( Ycortex,'dd',2,vx_vol) & Yp0<2.8 & ... + cat_vol_morph( Ya1==LAB.BG | Ya1==LAB.BG,'dd',12,vx_vol); + Ycortex = Ycortex | Yinsula; + if ~debug, clear Yinsula; end + + + %% create initial WMH map + % (A1) classical WMHs + (A2) subcortical (GM) WMHs + (A3) large WMHs + % (B1) cortical GM + (B2) deep ventriclal CSF (to avoid the mapping + % of CSF-WM-PVE close to the ventricle) + % (C1 & C2) WM regions as boundary for the bottleneck region growing + Ywmh = single( smooth3( ... + cat_vol_morph(~cat_vol_morph(Ycortex,'dd',2 - WMHCstr) & ~Ycenter & (Yp0A+YwmhA)>2.1 & ... + Ym<2.8 & Ym>1.2 & ~Ybgth & ~cat_vol_morph(Yvt,'d'),'l',[inf,15 - 10*WMHCstr]) > 0 ) > 0.4 ); % (A1) + Ywmh( smooth3(Ym<1.9 & Ybgth & Yp0A>2)>0.5 & ~cat_vol_morph(Yvt,'o',3) & ... + ~Ycenter & ~Yvt & ~Ya1==LAB.TH & ... + ~cat_vol_morph( Ya1==LAB.HC | YA==LAB.PH ,'dc',10,vx_vol)) = 1; % (A2) + Ywmh( cat_vol_morph(Ywmh | Yvt,'dc',4,vx_vol) & Ym>1 & Ym<2.8 & Yp0<2.8 & ~Ycenter & ~Yvt ) = 1; + Ywmh( YwmhL ) = 1; if ~debug, clear YwmhL; end % (A3) + Ywmh( smooth3( Ycortex)>0.8 & ~Yvt ) = 2; % (B1) + Ywmh( cat_vol_morph( Yvt, 'de', 2) ) = 2; % (B2) + Ywmh( Ywmh==0 & Ymi>2.8 ) = nan; % (C1) + Ywmh( Ywmh==0 & Ym>1.9 & cat_vol_morph( Ya1==LAB.BG | Ya1==LAB.TH | ... + Ya1==LAB.HC | YA==LAB.PH ,'dc',10,vx_vol) ) = nan; % (C2) + + + %% remove small dots + Ywmh(Ywmh==2 & smooth3(Ywmh==2)<0.1 + WMHCstr/2 + noisew) = 0; + Ywmh(Ywmh==1 & smooth3(Ywmh==1)<0.1 + WMHCstr/2 + noisew) = 0; + + + % Ywmhp: tiny WMHs that were found by closing the WM + if noisew<0.07 + % tiny WMHs as regions with low T1 intensity that can be described + % by closing of WM-like regions + Ywmhp = (Ymi2.2 & Yp0>2.2,'de')) | ... + (cat_vol_morph(Ymi>mth(2) | cat_vol_morph(Ya1==LAB.VT,'dd',1,vx_vol),'lc',1) & Ymi2.3 | cat_vol_morph(Ya1==LAB.VT,'dd',1,vx_vol),'lc',1) & ... + Ymi2.9,'dd',1.4) & ~Ycortex); + Ywmhp = Ywmhp & (YwmhA>0 | Yp0A>2.6) & ~Ybgth & Ymi>mth(1) & Ymi2.9,'e') & Ym<2.9 & ~Ycortex & ~Ybgth & Ya1~=LAB.BS & Ya1~=LAB.CB) = 1; + % no WMHs + Ywmhp(cat_vol_morph(Ya1==LAB.VT,'dd',1,vx_vol)) = 0; % not close to the ventricle (PVE range) + Ywmhp(smooth3(Ywmhp)<0.2 + noisew) = 0; % avoid WMHs caused by noise + Ywmhp = cat_vol_morph(Ywmhp,'l',[inf 4 * max(1,min(4,noisew*20))])>0; % remove small WMHs + Ywmh(smooth3(Ywmhp)>0.5 & Ymi0.5 )), ... + cat_stat_nanmean( Yflair( Yp0toC(Yp0,2)>0.5 )), ... + cat_stat_nanmean( Yflair( Yp0toC(Yp0,3)>0.5 ))]; + Tstd = cat_stat_nanstd( Yflair(Yflair(:)>T3thf(1) & Yflair(:) cat_stat_nanmean(T3thf(3)) - Tstd*2 & ... + Yflair < cat_stat_nanmean(T3thf(3)) + Tstd*2 & ... + (Yflair/T3thf(3)./(Ymi/3))<2 & Yp0>2.5; + Yi = Yi | (Yp0>2.8 & Ymi>2.8); + Yg = Yflair > cat_stat_nanmean(T3thf(2)) - Tstd*3 & Yp0>1.5 & Yp0<2.5 & ~Yi; + Yi = cat_vol_localstat(Yflair .* Yi,Yi>0,1,2) + ... + cat_vol_localstat(Yflair .* Yg,Yg>0,2,3)*T3thf(3)/T3thf(2); + Yi = cat_vol_median3(Yi,Yi>0,Yi>0); + for i=1:2, Yi = cat_vol_localstat(Yi,Yi>0,1,1); end + Yi = cat_vol_approx(Yi,'nn',vx_vol,8); + + %% + Yflairn = Yflair./(Yi+eps); + T3thf = [cat_stat_nanmean( Yflairn( Yp0toC(Yp0,1)>0.8 )), ... + cat_stat_nanmean( Yflairn( Yp0toC(Yp0,2)>0.9 & Yflairn>1.1 )), ... + cat_stat_nanmean( Yflairn( Yp0toC(Yp0,3)>0.9 & Yflairn<1.1 & Ym>2.8 ))]; + [T3thfs,T3this] = sort([0, T3thf, max(T3thf) + 1*abs(diff(T3thf(2:3)))]); T3this = [0 1/3 2/3 2/3 2]; + Yflairn2 = zeros(size(Yflairn),'single'); + for i=numel(T3thfs):-1:2 + M = Yflairn>T3thfs(i-1) & Yflairn<=T3thfs(i); + Yflairn2(M(:)) = T3this(i-1) + (Yflairn(M(:)) - T3thfs(i-1))/diff(T3thfs(i-1:i))*diff(T3this(i-1:i)); + end + M = Yflairn>=T3thfs(end); + Yflairn2(M(:)) = max(T3this) + (Yflairn(M(:)) - T3thfs(end))/diff(T3thfs(end-1:end))*diff(T3this(i-1:i)); + Yflairn2 = cat_vol_median3(Yflairn2,Yp0>0,Yp0>0,0.1); + + %% create FLAIR mask + Yflairl = Yflairn2>0.8 & ~Ycenter & ... % flair intensiy + cat_vol_morph(cat_vol_morph(Yp0>1 | Yvt,'dc',1.5),'do',1.5); % brain tissue or ventricular area! + % & ... Yflair./Yi > (T3thf(2)/T3thf(3) + Tstd/T3thf(3)*1.5 - (Tstd/T3thf(3)*extopts.WMHCstr)) & ... % flair intensiy + %Yp0>1.1 & Ymi<2.9 & Yp0A>1.1 & ~Ycenter & ... & YwmhA>eps % T1 intensities & altas limits + % (Yflair./Yi + Ymi/3)>max(2.1,3*(1-YwmhA)); % & ... % another flair intensity limit + %cat_vol_morph(Ya1~=LAB.TH & Ya1~=LAB.BG & Ya1~=LAB.HC,'d',1); % avoid some regions + %% + %Yflairl = Yflairl | (Yflair./Yi + Ymi/3)>max(2.3,3*(1-YwmhA)) & Ymi<2.9; % add some regions + Yflairl = cat_vol_morph(Yflairl,'l',[inf (4 - extopts.WMHCstr)^3])>0; + Yflairr = smooth3(Yflairl) .* min( 1, 2 * max(0, Yflair./(Yi+eps) - ... + ( (T3thf(2)/T3thf(3) + Tstd/T3thf(3)*1.5 - (Tstd/T3thf(3)*extopts.WMHCstr)) ) )); + if ~debug, clear Yi Yflair; end + + %% add FLAIR mask + Ywmh(Yflairl & (Ywmh<2 | isnan(Ywmh))) = 1; + else + Yflairl = false(size(Ymi)); + end + if ~debug, clear Ycenter; end + + % lesions as a regions : + % - that did not fit to the expected tissue? - not stong enough + % - with low self/mirror similarity? > Shooting+ + % cat_vol_morph( Ycortex & Yp01.1 & Yp0A>1.8 & ~cat_vol_morph(Yp0<1.2,'do',4) ,'do',1.8); % lesions without FLAIR + % cat_vol_morph( (Yflairn - (Ym-1)) .* (Ycortex & Yp01.1),'do',0.9); % lesion with FLAIR + + %% bottleneck region growing [Manjon:1995] + Ywmh(Ywmh==0) = 1.5; Ywmh(Ym>2.2 & Ywmh==1.5) = nan; % harder mask with low T1 threshold + Ywmh2 = cat_vol_laplace3R(Ywmh, Ywmh==1.5, 0.001); % bottleneck + Ywmh(Ywmh==1.5 & Ywmh2>1.7 & Ywmh<3) = 2; % add cortex + Ywmh(Ywmh==1.5 & (Ywmh2<1.2 | Ywmh2==1.5)) = 1; % add WMHs + Ywmh(isnan(Ywmh) & Ym<2.5 & Ym>1.5) = 1.5; % soft mask with higher T1 threshold + Ywmh2 = cat_vol_laplace3R(Ywmh, Ywmh==1.5, 0.001); % bottleneck + + % final mask and remove small WMHs + Ywmh = ~Yvt & Ymi>mth(1) & Ymi1.8); + if ~debug, clear Ywmh2; end + Ywmh = cat_vol_morph(Ywmh , 'l', [inf wmhvols/2])>0; + + % final mask and add tiny WMHs and FLAIR WMHs + Ywmh = ( ( Ywmh | Ywmhp | Yflairl ) & Ymi>mth(1) & Ym1.125 & Ym<2) ) ) )); + if exist('Yflairr','var'), Ywmhr = max( Yflairr .* Ywmh, Ywmhr ); clear Yflairr; end + if ~debug, clear Ywmhp Ybgth Yflairl Yt; end + + + %% apply to atlas + Ya1(Ywmh) = LAB.HI; + else + Ywmhr = false(size(Ym)); + Ycortex = false(size(Ym)); + end + if ~debug, clear Ywmh Ynwmh Yvt2; end + + + + %% stroke lesion detection + + % 1. Detection of manually masked regions (zeros within brainmask) + if exist('Ylesionmsk','var') + stime = cat_io_cmd(' Manual stroke lesion detection','g5','',verb,stime); + Ylesion = Ylesionmsk>0.5; % add manual lesions + end + + % 2. Automatic stroke lesion detection + % * use prior maps to identify reginos that should be tissue but + % are in stroke areas and have CSF intensity + % * use distance properies to differentiate between normal brain + % atrophy and stroke lesions as local CSF areas that differ stongly + % from the average values + if extopts.SLC + stime = cat_io_cmd(' Stroke lesion detection','g5','',verb,stime); + + %% large CSF regions without lesion prior + Ysd = cat_vbdist(single(cat_vol_morph(~Yb | Yp0>2 | cat_vol_morph(Ya1>0,'ldc',1),'do',3,vx_vol))); + mdYsd = max(3.0,median(Ysd(Ysd(:)>0))); + sdYsd = max(1.5,std(Ysd(Ysd(:)>0))); + Yclesion = smooth3(Ysd>(mdYsd + 3*sdYsd) & Yp0<1.5 & Yp0A>1.25 & Ydiv>-0.1 & (YslA>0 | Yp0A>1.25))>0.5; + % large CSF regions with lesion prior + Ysd2 = Ysd .* YslA .* Yp0A/3; + mdYsd2 = max(3.0,median(Ysd2(Ysd2(:)>0))); + sdYsd2 = max(1.5,std(Ysd2(Ysd2(:)>0))); + Yclesion( smooth3(Ysd>(mdYsd + 3*sdYsd) & Yp0<1.5 & Yp0A>1.25 & Ydiv>-0.1 & (YslA>0 | Yp0A>1.25))>0.5 ) = 1; + if ~debug, clear Ysd; end + Yclesion = cat_vol_morph(cat_vol_morph(Yclesion | ~(Yb & Yp0A>0),'dc',4,vx_vol) & Ym<2 & Yp0>0.5,'do',2); + Yclesion = cat_vol_morph(Yclesion,'l',[inf 400],vx_vol)>0; + + % further lesions + Ywlesion = smooth3(abs(Yp0-Ym)/3 .* (1-max(0,abs(3-Yp0A))) .* YslA * 10 )>0.3 & Ym<2.2 & Yp0>1 & Ya1~=LAB.HI; % WM-GM leson + Ywlesion( smooth3(Yp0A/3 .* YslA .* (3-Ym) .* (Ya1~=LAB.HI))>0.5 ) = 1; % WM lesions + % + Ywlesion( cat_vol_morph(YslA>0.6 & Yp0<2.0 & Ydiv./(Ym+eps)>0 & YslA>0.2 & Yp0A>2.5 , 'do', 1 ) ) = 1; % WM + Ywlesion( cat_vol_morph(YslA>0.2 & Yp0<1.6 & Ydiv./(Ym+eps)>0 & YslA>0.2 & (YA==LAB.BG | YA==LAB.TH) , 'do', 1 ) ) = 1; % BG lesions + % closing and opening + Ywlesion = cat_vol_morph(cat_vol_morph(Ywlesion | ~(Yb & Yp0A>0),'dc',4,vx_vol) & Ym<2 & Yp0>0.5,'do',1); + Ywlesion = cat_vol_morph(Ywlesion,'l',[inf 200],vx_vol)>0; + + %% + Ystsl = Ystsl & Ym<2.8 & Ya1~=LAB.VT; + Yilesion = single(Yclesion | Ywlesion | Ystsl); Yilesion(Yilesion==0 & ( Yp0<0.5 | Yp0>2.1 | Ydiv<-0.1 | Ya1==LAB.VT ) ) = -inf; + [Yilesion,Ydd] = cat_vol_downcut(Yilesion,3-Ym,-0.0001); Yilesion(Ydd>200) = 0; + Yilesion = cat_vol_morph(Yilesion,'dc',1,vx_vol); + Yilesion = cat_vol_morph(Yilesion,'do',4,vx_vol)>0 | Ywlesion| Yclesion; + Yilesion = cat_vol_morph(Yilesion,'l',[inf 200],vx_vol)>0; + Ynlesion = smooth3(~Yilesion & Ysd2<(mdYsd2 + 2*sdYsd2) & Ym<2.0 & Yp0A<1.9 & Ydiv>0)>0.5; + if ~debug, clear Ysd2; end + + % region-growing + Ysl = single(Yilesion) + 2*single(Ynlesion | Yp0<0.5 | Yvt | ~Yb); if ~debug, clear Yilesion Ynlesion; end + Ysl(Yp0>2.8)=nan; Ysl(Ysl==0) = 1.5; % harder mask with low T1 threshold + Ysl2 = cat_vol_laplace3R(Ysl, Ysl==1.5, 0.05); % bottleneck + Ysl(Ysl2<1.45 & ~isnan(Ysl))=1; Ysl(Ysl2>1.55 & ~isnan(Ysl))=2; + Ysl2 = cat_vol_laplace3R(Ysl, Ysl==1.5, 0.01); if ~debug, clear Ysl; end % bottleneck + Ylesion = cat_vol_morph(Ysl2<1.45 & Ysl2>0 & Ym<2.8 & Ya1~=LAB.HI,'do',1,vx_vol); if ~debug, clear Ysl2; end + %% + + %% + %Ylesion = single( Yp0A./(Ym+2)>1.3 & Yp0>0.5 & Yp0<2 & Ya1~=LAB.VT & Ya1~=LAB.HI & Ym<1.5 ); % , 'do', 3); + %Ylesion = single(cat_vol_morph(Ylesion,'l',[inf 50])>0); + %{ + Ylesion( cat_vol_morph(YslA>0.6 & Ym<2 & Ydiv./Ym>0 & Yp0A>2.5 , 'do', 1 ) ) = 2; % WM + Ylesion( cat_vol_morph(YslA>0.2 & Ym<2 & Ydiv./Ym>0 & YA==LAB.BG , 'do', 1 ) ) = 2; % BG lesions + Ylesion(smooth3(Yp0A>2.9 & Ym<2)>0.7) = 1; + + Ylesion(Ym>2 | (Ya1==LAB.VT & Yp0A<2.9) | Ya1==LAB.HI | Yp0==0) = nan; + [Ylesion,Ydx] = cat_vol_simgrow(Ylesion,max(1,Ym),1); Ylesion(Ydx>0.1)=0; + % different volume boundaries depending on the position of the lesion + Ylesion = cat_vol_morph(cat_vol_morph(Ylesion,'do',2) & Yp0A<2.5,'l',[inf 200])>0 | ... % maybe just atrophy + cat_vol_morph(cat_vol_morph(Ylesion,'do',1) & Yp0A>2.5,'l',[inf 100])>0 | ... + cat_vol_morph(Ylesion & Yp0A>2.9,'l',[inf 10])>0; + %} + % add manual leisons + if exist('Ylesionmsk','var'), Ylesion(Ylesionmsk>0.5) = 1; end + end + Ya1(Ylesion>0) = LAB.LE; + + + %% Closing of gaps between diffent structures: + stime = cat_io_cmd(' Closing of deep structures','g5','',verb,stime); + Yvtd2 = cat_vol_morph(Ya1==LAB.VT,'dd',2,vx_vol) & Ya1~=LAB.VT; + % CT and VT + Ycenter = cat_vol_morph(Ya1==LAB.VT,'dd',2,vx_vol) & ... + cat_vol_morph(Ya1==LAB.CT,'d',2,vx_vol) & Ya1==0 ; + Ya1(Ycenter & Yp0<=1.5 & ~Ynv)=LAB.VT; Ya1(Ycenter & Yp0>1.5)=LAB.CT; + % WMH and VT + Ycenter = cat_vol_morph(Ya1==LAB.HI,'dd',2,vx_vol) & Yvtd2 & ~Ynv & Ya1==0; + Ya1(Ycenter & Ym<=1.25)=LAB.VT; Ya1(Ycenter & Ym>1.25 & Ym<2.5)=LAB.HI; + % TH and VT + if 0 % RD202501 + Ycenter = cat_vol_morph(Ya1==LAB.TH,'dd',2,vx_vol) & Yvtd2; + Ya1(Ycenter & Ym<=1.5)=LAB.VT; Ya1(Ycenter & Ym>1.5 & Ym<2.85)=LAB.TH; + end + % BG and VT + Ycenter = cat_vol_morph(Ya1==LAB.BG,'dd',2,vx_vol) & Yvtd2; + Ya1(Ycenter & Ym<=1.5)=LAB.VT; Ya1(Ycenter & Ym>1.5 & Ym<2.85)=LAB.BG; + % no bloodvessels next to the ventricle, because for strong atrophy + % brains the WM structures can be very thin and may still include + % strong bias + Ya1(Ya1==LAB.BV & cat_vol_morph(Ya1==LAB.VT,'dd',3,vx_vol))=0; + if ~debug, clear Yt Yh Yvtd2 Yw; end + + + + %% complete map + Ya1(Ya1==0 & Yp0<1.75) = nan; + Ya1 = cat_vol_downcut(Ya1,Ym,noise); Ya1(isinf(Ya1)) = 0; + Ybv = Ya1==LAB.BV; Ya1(Ya1==LAB.BV) = 0; + [~,~,Ya1x] = cat_vbdist(Ya1,Yb); + Ya1(Ya1x==LAB.CB | Ya1x==LAB.BS | Ya1x==LAB.MB | Ya1x==LAB.CT) = Ya1x(Ya1x==LAB.CB | Ya1x==LAB.BS | Ya1x==LAB.MB | Ya1x==LAB.CT); + Ya1(Ya1x>0 & Ya1==0) = 1; + Ya1(Ybv) = LAB.BV; clear Ybv; + + % consider gyrus parahippocampalis | cat_vol_morph(Ya1==LAB.HC,'e') + % RD202501: add defintion of parahippocampal gyrus (with some extensive + % processing to really have a whole free thing but we will try to first keep it simple) + Yph = cat_vol_morph((YA==LAB.PH ),'dd',1.9) & cat_vol_morph(Ya1==LAB.VT | Ya1==LAB.HC,'dd',4,vx_vol) & Ym>2.125 & Ydiv<0.05; + Ya1(Yph>0) = LAB.PH; clear Yph; % parahippocampus + + %% side aligment using laplace to correct for missalignments due to the normalization + stime = cat_io_cmd(' Side alignment','g5','',verb,stime); + YBG = Ya1==LAB.BG | Ya1==LAB.TH; + YMF = Ya1==LAB.VT | Ya1==LAB.BG | Ya1==LAB.HI | Ya1==LAB.PH | (Ya1==LAB.TH & cat_vol_smooth3X(Ym>1.9)); % add the thalamus (RD20190913) + YMF(smooth3(YMF)<.5) = 0; + YMF = cat_vol_morph(cat_vol_morph(YMF,'dc',2),'do'); + YMF2 = cat_vol_morph(YMF,'dd',2,vx_vol) | Ya1==LAB.CB | Ya1==LAB.BS | Ya1==LAB.MB; + Ymf = max(Ym,smooth3(single(YMF2*3))); + Ycenter = cat_vol_smooth3X(YS==0,6)<0.9 & cat_vol_smooth3X(YS==1,6)<0.9 & ~YMF2 & Yp0>0 & Ym<3.1 & (Yp0<2.5 | Ya1==LAB.BV); + Ys = (2-single(YS)) .* single(smooth3(Ycenter)<0.4); + Ys(Ys==0 & (Ym<1 | Ym>3.1))=nan; Ys = cat_vol_downcut(Ys,Ymf,0.1,vx_vol); + [~,~,Ys] = cat_vbdist(Ys,Ys==0); + if ~debug, clear YMF2 Yt YS; end + + % YMF for FreeSurfer fsaverage + Ysm = cat_vol_morph(Ys==2,'d',1.5,vx_vol) & cat_vol_morph(Ys==1,'d',1.5,vx_vol); + Ynn = 0 * cat_vol_morph(Ysm & Ya1==LAB.MB,'dd',10); + YMF = Ya1==LAB.VT | (cat_vol_morph(Ya1==LAB.PH | Ya1==LAB.BG | Ya1==LAB.HI | (Ya1==LAB.TH & cat_vol_smooth3X(Ym)>1.9),'dc',2,vx_vol) & ~Ysm); % changed thalamus (RD20190913) + YMF = Ya1~=LAB.CB & ~Ynn & Ym<=2.75 & cat_vol_morph(YMF | Ym>2.3,'c',1) & cat_vol_morph(YMF,'dd',2,vx_vol); + YMF = smooth3(YMF)>0.5; + Ycenter = cat_vol_morph(Ya1==LAB.TH | Ya1==LAB.VT,'dc',4,vx_vol) & ~(Ya1==LAB.TH | Ya1==LAB.VT | cat_vol_morph(Ya1==LAB.HC | Ya1==LAB.PH,'dd',2,vx_vol)); + YMF(Ycenter)=1; + clear Ysm; + + + %% back to original size + stime = cat_io_cmd(' Final corrections','g5','',verb,stime); + Ya1 = cat_vol_resize(Ya1,'dereduceV',resTr,'nearest'); Ya1 = cat_vol_median3c(Ya1,Ya1>0 & Ya1~=LAB.BV); + Ys = cat_vol_resize(Ys ,'dereduceV',resTr,'nearest'); Ys = 1 + single(smooth3(Ys)>1.5); + YMF = cat_vol_resize(single(YMF),'dereduceV',resTr)>0.5; + YBG = cat_vol_resize(single(YBG),'dereduceV',resTr)>0.5; + Ywmhr = cat_vol_resize(Ywmhr,'dereduceV',resTr); + Ycortex = cat_vol_resize(single(Ycortex),'dereduceV',resTr)>0.5; + + Ya1 = cat_vol_resize(Ya1,'dereduceBrain',BB); Ya1 = cat_vol_ctype(Ya1); + Ys = cat_vol_resize(Ys ,'dereduceBrain',BB); [~,~,Ys] = cat_vbdist(Ys,Ya1>0); + YMF = cat_vol_resize(YMF,'dereduceBrain',BB); + YBG = cat_vol_resize(YBG,'dereduceBrain',BB); + Ywmhr = cat_vol_resize(Ywmhr,'dereduceBrain',BB); + Ycortex = cat_vol_resize(Ycortex,'dereduceBrain',BB); + Ym = Ym0; clear Ym0; + + % final side alignment + Ya1(Ya1>0)=Ya1(Ya1>0)+(Ys(Ya1>0)-1); + + + %% correction of tissue classes + + % add WMH class + Ywmhrd = cat_vol_morph(Ywmhr,'dd'); + Yclssum = (single(Ycls{1}) + single(Ycls{3})) .* (Ywmhrd); + Ycls{7} = cat_vol_ctype(Yclssum); + Ycls{1} = cat_vol_ctype(single(Ycls{1}) .* (~Ywmhrd)); + Ycls{3} = cat_vol_ctype(single(Ycls{3}) .* (~Ywmhrd)); + clear Ywmhrd + + % set possible blood vessels to class 4 + NS = @(Ys,s) Ys==s | Ys==s+1; + if ~NBVC + % this should be done later with consideration of the BV intensity and WM distance! + Ybv = NS(Ya1,LAB.BV); + Yclssum = (single(Ycls{1}) + single(Ycls{2})) .* (Ybv); + Ycls{5} = cat_vol_ctype(single(Ycls{5}) + Yclssum); + Ycls{1} = cat_vol_ctype(single(Ycls{1}) .* (~Ybv)); + Ycls{2} = cat_vol_ctype(single(Ycls{2}) .* (~Ybv)); + clear Ybv; + end + + + % YBG is smoothed a little bit and (B) reset all values that are related with GM/WM intensity (Ym<2.9/3) (A) + Yclssum = single(Ycls{1}) + single(Ycls{2}) + single(Ycls{3}); + YBGs = min( max(0,min(255, 255 - cat_vol_smooth3X(Ya1==1 & Ycls{2}>round(2.9/3),0.8) .* single(Ycls{2}) )), ... (A) + max(0,min(255, 255 * cat_vol_smooth3X(YBG .* (Ym<=2.9/3 & Ym>2/3) ,0.5) )) ); % (B) + Ycls{1} = cat_vol_ctype(single(Ycls{1}) + YBGs .* (single(Ycls{2})./max(eps,Yclssum))); + Ycls{2} = cat_vol_ctype(single(Ycls{2}) - YBGs .* (single(Ycls{2})./max(eps,Yclssum))); + clear YBGs Yclssum; + + % assure that the sum of all tissues is 255 + Yclss = zeros(size(Ym),'single'); + for ci=1:numel(Ycls), Yclss = Yclss + single(Ycls{ci}); end + for ci=1:numel(Ycls), Ycls{ci} = cat_vol_ctype(single(Ycls{ci}) ./ max(eps,Yclss) * 255); end + + cat_io_cmd(' ','','',verb,stime); + + catch e + if extopts.ignoreErrors < 1 + rethrow(e); + else + % [Ya1,Ycls,YMF,Ycortex] = cat_vol_partvol(Ym,Ycls,Yb,Yy,vx_vol,extopts,Vtpm,noise,job,Ylesionmsk,Ydt,Ydti) + if ~exist('Ya1','var') || any( size(Ya1) ~= size(Ym) ) + % atlas map + PA = extopts.cat12atlas; + Ya1 = cat_vol_sample(Vtpm(1),PA{1},Yy,0); + Ya1 = cat_vol_ctype(cat_vol_median3(Ya1,Yb,Yb)); + end + + if ~exist('YMF','var') || any( size(YMF) ~= size(Ym) ) + LAB = extopts.LAB; + NS = @(s) Ya1==s | Ya1==s+1; + YMF = NS(LAB.VT) | NS(LAB.BG) | NS(LAB.TH) | NS(LAB.HI) | NS(LAB.TH); + Yp0 = (single(Ycls{1})*2/255 + single(Ycls{2})*3/255 + single(Ycls{3})/255) .* Yb; + YMF = Yp0<=3 & cat_vol_morph(YMF | Yp0>2.5,'c',1) & cat_vol_morph(YMF,'d',1,vx_vol); + YMF(smooth3(YMF)<0.5) = 0; + end + + if ~exist('Ycortex','var') || any( size(Ycortex) ~= size(Ym) ) + Ycortex = Ya1==LAB.CT; + end + + end + end +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_surf_display.m",".m","13792","389","function varargout = cat_surf_display(varargin) +% ______________________________________________________________________ +% Function to display surfaces. Wrapper to cat_surf_render(2). +% +% [Psdata] = cat_surf_display(job) +% +% job.data .. (lh|rh|mesh).* surfaces +% job.colormap .. colormap +% job.caxis .. range of the colormap +% job.multisurf .. load both sides, if possible (default = 0) +% 1 - load other side of same structure +% 2 - load all structures of the same side +% 3 - load all structures of both sides +% job.usefsaverage .. use average surface (for resampled data only) +% (default = 0) +% job.view .. view +% l=left, r=right +% a=anterior, p=posterior +% s=superior, i=inferior +% job.verb .. SPM command window report (default = 1) +% job.readsurf .. get full surface informtion by loading the image +% (default = 1; see cat_surf_info) +% job.parent .. axis handle to print in other (sub)figures +% +% job.imgprint.do .. print image (default = 0) +% job.imgprint.type .. render image type (default = png) +% job.dpi .. print resolution of the image (default = 600 dpi) +% +% Examples: +% - Open both hemispheres of one subject S01: +% cat_surf_display(struct('data','lh.thickness.S01.gii','multisurf',1)) +% - Use another scaling of the intensities +% cat_surf_display(struct('caxis',[0 10])) +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + if nargout>0, varargout{1}{1} = []; end + + if nargin>0 + if isstruct(varargin{1}) + job = varargin{1}; + if ~isfield(job,'data') || isempty(job.data) + if cat_get_defaults('extopts.expertgui') + job.data = spm_select([1 24],'any','Select surfaces or textures','','','(lh|rh|lc|rc|cb|mesh).*'); + else + job.data = spm_select([1 24],'any','Select surfaces or textures','','','.*gii'); + end + job.imgprint.do = 0; + job.imgprint.close = 0; + end + else + job.data = varargin{1}; + end + else + if cat_get_defaults('extopts.expertgui') + job.data = spm_select([1 24],'any','Select surfaces or textures','','','(lh|rh|lc|rc|cb|mesh).*'); + else + job.data = spm_select([1 24],'any','Select surfaces or textures','','','.*gii'); + end + job.imgprint.do = 0; + job.imgprint.close = 0; + end + if isempty(job.data), return; end + job.data = cellstr(job.data); + + % scaling options for textures + def.colormap = ''; + def.usefsaverage = 0; + def.caxis = []; % default/auto, range + def.expert = cat_get_defaults('extopts.expertgui'); + + % print options ... just a quick output > cat_surf_print as final function + def.imgprint.type = 'png'; + def.imgprint.dpi = 600; + def.imgprint.fdpi = @(x) ['-r' num2str(x)]; + def.imgprint.ftype = @(x) ['-d' num2str(x)]; + def.imgprint.do = 0; + def.imgprint.close = 0; + def.imgprint.dir = ''; + + % multi-surface output for one subject + def.multisurf = 0; % 0 - no; 1 - both hemispheres; + def.verb = 1; + def.readsurf = 0; % readsurf=1 for individual average surface (e.g. apes); readsurf=0 for group average surface + + job = cat_io_checkinopt(job,def); + + %% ... need further development + sinfo = cat_surf_info(job.data,job.readsurf,0,0,job.usefsaverage); + + if job.verb + spm('FnBanner',mfilename); + end + + for i=1:numel(job.data) + + % correct display of annotation files only work in developer mode + if strcmp(sinfo(i).ee,'.annot') + expert = 2; + else + expert = job.expert; + end + + if job.usefsaverage + + if ~isempty(strfind(fileparts(sinfo(i).Pmesh),'_32k')) + templates_surfaces = 'templates_surfaces_32k'; + else + templates_surfaces = 'templates_surfaces'; + end + + job.fsaverage = { + fullfile(fileparts(mfilename('fullpath')),templates_surfaces,'lh.central.freesurfer.gii'); + fullfile(fileparts(mfilename('fullpath')),templates_surfaces,'lh.inflated.freesurfer.gii'); + fullfile(fileparts(mfilename('fullpath')),templates_surfaces,['lh.central.' cat_get_defaults('extopts.shootingsurf') '.gii']); + }; + sinfo(i).Pmesh = cat_surf_rename(job.fsaverage{job.usefsaverage},'side',sinfo(i).side); + end + + % load multiple surfaces + % 3 - load all structures of both sides + % 2 - load all structures of the same side + % 1 - load other side of same structure + if job.multisurf + if strcmp('r',sinfo(i).side(1)), oside = ['l' sinfo(i).side(2)]; else, oside = ['r' sinfo(i).side(2)]; end + if job.multisurf==3 + Pmesh = [ ... + cat_surf_rename(sinfo(i).Pmesh,'side','lh') cat_surf_rename(sinfo(i).Pmesh,'side','rh') ... + cat_surf_rename(sinfo(i).Pmesh,'side','cb') ]; + Pdata = [ ... + cat_surf_rename(sinfo(i).Pdata,'side','lh') cat_surf_rename(sinfo(i).Pdata,'side','rh') ... + cat_surf_rename(sinfo(i).Pdata,'side','cb') ]; + elseif job.multisurf==2 + if strcmp('h',sinfo(i).side(2)), oside = [sinfo(i).side(1) 'c']; else, oside = [sinfo(i).side(1) 'h']; end + Pmesh = [sinfo(i).Pmesh cat_surf_rename(sinfo(i).Pmesh,'side',oside)]; + Pdata = [sinfo(i).Pdata cat_surf_rename(sinfo(i).Pdata,'side',oside)]; + else + Pmesh = [sinfo(i).Pmesh cat_surf_rename(sinfo(i).Pmesh,'side',oside)]; + Pdata = [sinfo(i).Pdata cat_surf_rename(sinfo(i).Pdata,'side',oside)]; + end + for im=numel(Pmesh):-1:1 + if ~exist(Pmesh{im},'file'), Pmesh(im) = []; end + if ~isempty(Pdata) && ~exist(Pdata{im},'file'), Pdata(im) = []; end + end + if numel(Pmesh)==1; Pmesh=char(Pmesh); end + if numel(Pdata)==1; Pdata=char(Pdata); end + else + Pmesh = sinfo(i).Pmesh; + Pdata = sinfo(i).Pdata; + end + + if job.verb + fprintf('Display %s\n',spm_file(job.data{i},'link','cat_surf_display(''%s'')')); + end + + if expert>1 && ~isfield(job,'parent') + fprintf('Developer display mode!\n'); + end + + if ~isempty(Pdata) && ~all(strcmp(Pmesh,Pdata)) + % only gifti surface without texture + if isfield(job,'parent') + if expert<2 + h = cat_surf_render('disp',Pmesh,'Pcdata',Pdata,'parent',job.parent); + else + h = cat_surf_render2('disp',Pmesh,'Pcdata',Pdata,'parent',job.parent); + end + else + if expert<2 + try + h = cat_surf_render('disp',Pmesh,'Pcdata',Pdata); + catch + h = cat_surf_render('disp',Pdata); + end + else + h = cat_surf_render2('disp',Pmesh,'Pcdata',Pdata); + end + end + else + % only gifti surface without texture + if isfield(job,'parent') + if expert<2 + h = cat_surf_render(Pmesh,'parent',job.parent); + else + h = cat_surf_render2(Pmesh,'parent',job.parent); + end + else + if expert<2 + h = cat_surf_render(Pmesh); + else + h = cat_surf_render2(Pmesh); + end + end + end + + set(h.figure,'MenuBar','none','Toolbar','none','Name',spm_file(job.data{i},'short60'),'NumberTitle','off'); + + % shift each figure slightly + if i==1 + pos = get(h.figure,'Position'); + else + pos = pos - [20 20 0 0]; + set(h.figure,'Position',pos); + end + + if sinfo(i).label, continue; end + + % try + %% textur handling + if expert<2 + cat_surf_render('ColourBar',h.axis,'on'); + else + cat_surf_render2('ColourBar',h.axis,'on'); + end + + if ~job.multisurf && strcmp(sinfo(i).side,'rh'), view(h.axis,[90 0]); end + + + % temporary colormap + if any(strcmpi({'neuromorphometrics','lpba40','ibsr','hammers','mori','aal3'},sinfo(i).dataname)) + %% + switch lower(sinfo(i).dataname) + case 'neuromorphometrics', rngid=3; + case 'lpba40', rngid=12; + case 'ibsr', rngid=1; + case 'hammers', rngid=5; + case 'mori', rngid=3; + case 'aal3', rngid=11; + otherwise, rngid=1; + end + + sideids = ceil(max(h.cdata(:))/2)*2; + if exist('rng','builtin') == 5 + rng('default') + rng(rngid) + else + rand('state',rngid); + end + + cmap = colorcube(ceil((sideids/2) * 8/7)); % greater to avoid grays + cmap(ceil(sideids/2):end,:)=[]; % remove grays + cmap(sum(cmap,2)<0.3,:) = min(1,max(0.1,cmap(sum(cmap,2)<0.3,:)+0.2)); % not to dark + cmap = cmap(randperm(size(cmap,1)),:); % random + cmap = reshape(repmat(cmap',2,1),3,size(cmap,1)*2)'; + + if expert<2 + cat_surf_render('ColourMap',h.axis,cmap); + else + cat_surf_render2('ColourMap',h.axis,cmap); + end + %% + continue + else + if isempty(job.colormap) + if expert<2 + h = cat_surf_render('ColourMap',h.axis,jet(256)); + else + h = cat_surf_render2('ColourMap',h.axis,jet(256)); + end + else + if expert<2 + h = cat_surf_render('ColourMap',h.axis,eval(job.colormap)); + else + h = cat_surf_render2('ColourMap',h.axis,eval(job.colormap)); + end + end + end + + % scaling + if isempty(job.caxis) + switch sinfo(i).texture + case {'ROI'} + %% + if strfind(sinfo(i).posside,'-Igm.ROI'), clim = [2/3 2/3] .* [0.9 1.1]; % balanced PVE + elseif strfind(sinfo(i).posside,'-Iwm.ROI'), clim = [0.85 1.05]; % below 1 because of a lot of GM/WM PVE + elseif strfind(sinfo(i).posside,'-Icsf.ROI'), clim = [1.33/3 1.33/3] .* [0.8 1.2]; % higher 1/3 because of a lot of GM/CSF PVE + else, clim = cat_vol_iscaling(h.cdata); + end + if expert<2 + cat_surf_render('clim',h.axis,clim); + else + cat_surf_render2('clim',h.axis,clim); + end + case {'defects','sphere'} + % no texture + case {'central'} + % default curvature + set(h.patch,'AmbientStrength',0.2,'DiffuseStrength',0.8,'SpecularStrength',0.1) + case {'thickness','pbt'} + h = cat_surf_render('ColourMap',h.axis,jet(128)); + cat_surf_render('clim',h.axis,[0.5 5]); + otherwise + % no texture name + if ~isempty(h.cdata) + clim = cat_vol_iscaling(h.cdata); + if clim(1)<0 + clim = [-max(abs(clim)) max(abs(clim))]; + if expert<2 + cat_surf_render('clim',h.axis,clim); + else + cat_surf_render2('ColourMap',h.axis,cat_io_colormaps('BWR',128)); + cat_surf_render2('clim',h.axis,clim); + end + else + if expert<2 + cat_surf_render('clim',h.axis,clim); + else + cat_surf_render2('ColourMap',h.axis,cat_io_colormaps('hotinv',128)); + cat_surf_render2('clim',h.axis,clim); + end + end + + end + end + else + switch sinfo(i).texture + case {'longThicknessChanges'} + if expert<2 + h = cat_surf_render('ColourMap',h.axis,flipud(cat_io_colormaps('BWR',128))); + else + h = cat_surf_render2('ColourMap',h.axis,flipud(cat_io_colormaps('BWR',128))); + end + end + if expert<2 + cat_surf_render('clim',h.axis,job.caxis); + else + cat_surf_render2('clim',h.axis,job.caxis); + end + end + + + + %% view + if ~isfield(job,'view') + if strcmp(sinfo(i).side,'lh') && ~job.multisurf + job.view = 'left'; + elseif strcmp(sinfo(i).side,'rh') && ~job.multisurf + job.view = 'right'; + else + job.view = 'top'; + end + end + + switch lower(job.view) + case {'r','right'}, cat_surf_render('view',h,[ 90 0]); viewname = '.r'; + case {'l','left'}, cat_surf_render('view',h,[ -90 0]); viewname = '.l'; + case {'t','s','top','superior'}, cat_surf_render('view',h,[ 0 90]); viewname = '.s'; + case {'b','i','bottom','inferior'}, cat_surf_render('view',h,[-180 -90]); viewname = '.i'; + case {'f','a','front','anterior'}, cat_surf_render('view',h,[-180 0]); viewname = '.a'; + case {'p','back','posterior'}, cat_surf_render('view',h,[ 0 0]); viewname = '.p'; + otherwise + if isnumeric(job.view) && size(job.view)==2 + view(job.view); viewname = sprintf('.%04dx%04d',mod(job.view,360)); + else + error('Unknown view.\n') + end + end + + + + + %% print + if job.imgprint.do + %% + if isempty(job.imgprint.dir), ppp = sinfo(i).pp; else, ppp=job.imgprint.dir; end + if ~exist(ppp,'dir'), mkdir(ppp); end + pfname = fullfile(ppp,sprintf('%s%s.%s',sinfo(i).ff,viewname,job.imgprint.type)); + print(h.figure , def.imgprint.ftype(job.imgprint.type) , job.imgprint.fdpi(job.imgprint.dpi) , pfname ); + + if job.imgprint.close + close(h.figure); + end + end + + if nargout>0 + varargout{1}{i} = h; + end + end +end + + + +","MATLAB" +"Neurology","ChristianGaser/cat12","SplineSmooth.cc",".cc","5969","195","/*-------------------------------------------------------------------------- +@COPYRIGHT : + Copyright 1996, John G. Sled, + McConnell Brain Imaging Centre, + Montreal Neurological Institute, McGill University. + Permission to use, copy, modify, and distribute this + software and its documentation for any purpose and without + fee is hereby granted, provided that the above copyright + notice appear in all copies. The author and McGill University + make no representations about the suitability of this + software for any purpose. It is provided ""as is"" without + express or implied warranty. +---------------------------------------------------------------------------- +$RCSfile: splineSmooth.cc,v $ +$Revision$ +$Author$ +$Date$ +$State: Exp $ +--------------------------------------------------------------------------*/ +/* ----------------------------- MNI Header ----------------------------------- +@NAME : splineSmooth.c,v +@INPUT : +@OUTPUT : (none) +@RETURNS : +@DESCRIPTION: Tool for smoothing and extrapolating data in minc volumes +@METHOD : +@GLOBALS : +@CALLS : +@CREATED : April 21, 1996 (John G. Sled) +@MODIFIED : Log: splineSmooth.c,v + * Revision 1.2 1996/04/23 13:36:58 jgsled + * Working version. Problems with thin plate splines have been fixed. + * + * Revision 1.1 1996/04/21 23:41:50 jgsled + * Initial version of SplineSmooth tool + * - B spline implementation appears to work + * +@COPYRIGHT : 1996 +---------------------------------------------------------------------------- */ + +#ifndef lint +static char rcsid[] = ""$Header: /software/source/INSECT/N3/src/SplineSmooth/splineSmooth.cc,v 1.2 2005/03/08 15:55:34 bert Exp $""; +#endif + +#include +#include // (bert) +using namespace std; // (bert) +#include +#include // (bert) +#include // (bert) +#undef ROUND +#undef SIGN + +//--------------------------------------------------------------------------------- +// Implementation notes +/* + The spline basis functions are defined in a world coordinate system aligned + with the voxel coordinate system and sharing the same origin. + + */ + +//--------------------------------------------------------------------------------- +// Declarations +DblMat volume_domain(double *separations, int *dims); +int fitSplinesToVolumeLookup(TBSplineVolume *spline, double *src, + const DblMat &domain, + int subsample, double *separations, int *dims); +void smoothVolumeLookup(TBSplineVolume *spline, double *src, int *dims); + +//-------------------------------------------------------------------------------- +// main program +extern ""C"" int splineSmooth( double *src, double lambda, double distance, int subsample, double *separations, int *dims) +{ + int i; + + DblMat domain; // region in world coordinates on which splines are defined + + // domain is whole volume + domain = volume_domain(separations, dims); + + // create spline basis + Spline *theSplines; + + double start[3] = { 0.0, 0.0, 0.0 }; + theSplines = new TBSplineVolume(domain, start, separations, dims, + distance, lambda); + + // do least squares fit to data + if(fitSplinesToVolumeLookup((TBSplineVolume *)theSplines, src, + domain, subsample, separations, dims) == TRUE) { + // write smooth function to volume + smoothVolumeLookup((TBSplineVolume *) theSplines, src, dims); + } else { + cerr << ""Spline fit failed: No fitting is used.\n""; + for (i=0; i < dims[0]*dims[1]*dims[2]; i++) src[i] = 0.0; + } + + return(0); +} + + +//----------------------------------------------------------------------------- +// Supporting functions + + + +// determine domain from size of volume in world coordinates +// Returns an 3 by 2 matrix +DblMat +volume_domain(double *separations, int *dims) +{ + DblMat domain(3,2); + + for(int i = 0; i < 3; i++) + { + if(separations[i] > 0) { + domain(i,0) = -0.5*separations[i]; + domain(i,1) = (dims[i]-0.5)*separations[i]; + } + else { + domain(i,1) = -0.5*separations[i]; + domain(i,0) = (dims[i]-0.5)*separations[i]; + } + } + return domain; +} + + +int +fitSplinesToVolumeLookup(TBSplineVolume *spline, double* src, + const DblMat &domain, int subsample, double* separations, int* dims) +{ + int i,x,y,z,j,k; + long area, vol, z_area, y_dims; + double value; + + // only look at values within domain + int lower[3], upper[3]; + for(i = 0; i < 3; i++) + { + if(separations[i] > 0) { + lower[i] = (int) ceil(domain(i,0)/separations[i]); + upper[i] = (int) floor(domain(i,1)/separations[i]); + } + else { + upper[i] = (int) floor(domain(i,0)/separations[i]); + lower[i] = (int) ceil(domain(i,1)/separations[i]); + } + } + + area = dims[0]*dims[1]; + vol = area*dims[2]; + + for(z = lower[2]; z <= upper[2]; z += subsample) { + z_area = z*area; + for(y = lower[1]; y <= upper[1]; y += subsample) { + y_dims = y*dims[0]; + for(x = lower[0]; x <= upper[0]; x += subsample) + { + value = src[z_area + y_dims + x]; + if(value > 0) + spline->addDataPoint(x,y,z, value); + } + } + } + + if(spline->fit() == FALSE) // fit splines to the data + { + cerr << ""Fatal Error: Spline fit failed.\n""; + return(FALSE); + } else return(TRUE); +} + +void +smoothVolumeLookup(TBSplineVolume *spline, double* src, int* dims) +{ + int x,y,z; + double value; + long area, vol, z_area, y_dims; + + area = dims[0]*dims[1]; + vol = area*dims[2]; + + for (z = 0; z < dims[2]; z++) { + z_area = z*area; + for (y = 0; y < dims[1]; y++) { + y_dims = y*dims[0]; + for (x = 0; x < dims[0]; x++) { + value = (*spline)(x,y,z); + src[z_area + y_dims + x] = value; + } + } + } +} +","Unknown" +"Neurology","ChristianGaser/cat12","cat_roi_roi2surf.m",".m","5097","168","function varargout = cat_roi_roi2surf(job) +% This function maps roi data to the surface, by setting the cdata of +% all vertices of a ROI to the specified field. +% +% cat_surf_roi2surf(job) +% +% job.rdata .. csv - ROI files +% xml - ROI files +% +% job.vars .. set of fieldnames +% +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + if nargin == 1 + def.verb = 1; + def.usefsaverage = 1; + def.assuregifti = 1; + def.fsaverage = fullfile(fileparts(mfilename('fullpath')),'templates_surfaces','lh.central.freesurfer.gii'); + def.inflated = fullfile(fileparts(mfilename('fullpath')),'templates_surfaces','lh.inflated.freesurfer.gii'); + def.dartelaverage = fullfile(fileparts(mfilename('fullpath')),'templates_surfaces',['lh.central.' cat_get_defaults('extopts.shootingsurf') '.gii']); + + job = cat_io_checkinopt(job,def); + else + error('Only batch mode'); + end + + % volume ROIs + % surface ROIs > ROI in Filename??? + + switch job.surf + case 'freesurfer', surf = job.fsaverage; + case 'inflated', surf = job.inflated; + case 'dartel', surf = job.dartelaverage; + case 'subject', surf = ''; + end + + % sides + sides = {'lh.','rh.'}; + S = struct('vertices',[],'faces',[]); + if ~isempty(surf) + [pps,ffs,ees] = spm_fileparts(surf); + + for si=1:2 + SX = gifti(fullfile(pps,[sides{si} ffs(4:end) ees])); + S(si).vertices = SX.vertices; + S(si).faces = SX.faces; + clear SX; + end + end + + cat_progress_bar('Init',numel(job.rdata{1}),... + sprintf('ROI2Surface\n%s',numel(job.rdata{1})),'ROIs Completed'); + + sname = cell(numel(job.rdata),1,1,numel(sides)); + for rfi=1:numel(job.rdata) + [pp,ff,ee] = spm_fileparts(job.rdata{rfi}); + ffname = textscan(ff,'%q','delimiter','_'); + + if job.verb + fprintf('process ""%s"":\n',job.rdata{rfi}); + end + + %% first we need to load the ROI tables in a similar style + clear xml; + switch ee + case '.csv' + % load csv data + roiname = ffname{1}{2}; + subname = ffname{1}{3}; + xml.ROI.(roiname) = cat_io_csv(job.rdata{rfi}); + case '.xml' + % read xml + subname = ffname{1}{2}; + xml = cat_io_xml(job.rdata{rfi}); + otherwise + % error + end + + % extract atlas names + atlas = fieldnames(xml.ROI); + + + %% load individual surfaces + if strcmp(job.surf,'subject') + % have to look for the resampled surface + % if it not exist we may resample the individual surface + % if this does not exist we print an error + [pp2,ppl] = spm_fileparts(pp); + surf = fullfile(pp2,strrep(ppl,'label','surf'),['lh.central.' subname '.gii']); + + [pps,ffs,ees] = spm_fileparts(surf); + + for si=1:2 + SX = gifti(fullfile(pps,[sides{si} ffs(4:end) ees])); + S(si).vertices = SX.vertices; clear SX; + end + end + + %% + for ai = 1:numel(atlas) + + % load ROI data + Proi = cat_vol_findfiles(fullfile(fileparts(mfilename('fullpath')),'atlases_surfaces'),['*' atlas{ai} '*']); + for si=1:2 + [ppr,ffr,eer] = spm_fileparts(Proi{si}); + switch eer + case '.annot' + [vertices, S(si).rdata] = cat_io_FreeSurfer('read_annotation',Proi{si}); + case '.gii' + SX = gifti(Proi{si}); + S(si).rdata = SX.cdata; clear SX; + otherwise + S(si).rdata = cat_io_FreeSurfer('read_surf_data',Proi{si}); + end + S(si).rdata = uint16(S(si).rdata); + end + + fields = xml.ROI.(atlas{ai})(1,3:end); + switch job.fields + case 'all' + % nothing to do + otherwise + fields = setunion(fields,job.fields); + + % warning for unknown ROIs + end + + %% mapping + for si=1:numel(S) + for fi = 1:numel(fields) + %% + fid = find(cellfun('isempty',strfind(xml.ROI.(atlas{ai})(1,:),fields{fi}))==0); + S(si).cdata = mapROI2surf(S(si).rdata,xml.ROI.(atlas{ai}),fid); + + % save data + [pp2,ppl] = spm_fileparts(pp); + sname{rfi,ai,fi,si} = fullfile(pp2,strrep(ppl,'label','surf'),sprintf('%s%s-%s.ROI.%s.gii',sides{si},atlas{ai},fields{fi},subname)); + save(gifti(struct('vertices',S(si).vertices,'faces',S(si).faces,'cdata',S(si).cdata)),sname{rfi,ai,fi,si} ); + + if job.verb + fprintf('Output %s\n',spm_file(sname{rfi,ai,fi,si},'link','cat_surf_display(''%s'')')); + end + end + end + + end + cat_progress_bar('Set',rfi); + + end + cat_progress_bar('Clear'); + + if nargout>0 + varargout{1} = sname; + end +end +function cdata = mapROI2surf(rdata,tab,fid) + cdata = zeros(size(rdata),'single'); + for ri=2:size(tab,1) + cdata(rdata==tab{ri,1}) = tab{ri,fid}; + end +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_io_FreeSurfer.m",".m","31691","1001","function varargout=cat_io_FreeSurfer(action,varargin) +% ______________________________________________________________________ +% +% Read/Write FreeSurfer Data. +% +% Use FreeSurfer in/output functions created by Bruce Fischl, Doug Greve, +% Thomas Yeo, and Mert Sabuncu. +% +% varargout = cat_io_FreeSurfer(action,varargin) +% +% * surface meshs: +% cat_io_FreeSurfer('write_surf',fname,vertices,faces); +% S = cat_io_FreeSurfer('read_surf',fname); +% +% * surface data: +% cat_io_FreeSurfer('write_surf_data',fname,cdata); +% cdata = cat_io_FreeSurfer('read_surf_data',fname); +% +% * surface atlases: +% [vertices, label, colortable] = +% cat_io_FreeSurfer('read_annotation',fname); +% cat_io_FreeSurfer('write_annotation', ... +% fname, vertices, label, colortable); +% +% * GIFTI to FreeSurfer / FreeSurfer to GIFTI: +% [P] = cat_io_FreeSurfer('gii2fs',fname); +% [P] = cat_io_FreeSurfer('gii2fs',... +% struct('data',{fnames},'delete',[0|1])); +% +% [P] = cat_io_FreeSurfer('fs2gii',fname); +% [P] = cat_io_FreeSurfer('fs2gii',... +% struct('data',{fnames},'cdata',{cfnames},'delete',[0|1])); +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + if ~exist('action','var'), help cat_io_FreeSurfer; return; end + if nargin==0, varargin{1} = struct(); end + + switch action + case {'fs2gii','read_surf','read_surf_data'} + [pp,ff,ee] = spm_fileparts(varargin{1}); + if any(strcmp({'.gii','.nii','.mat','.m'},ee)) + error('cat_io_FreeSurfer:WrongInput','FreeSurfer file format only! No filenames GIFTI (*.gii), NIFTI (*.nii), or Matlab (*.mat,*.m) are allowed! '); + end + end + + switch action + %case 'FSatlas2cat' + % varargout{1} = cat_surf_FSannotation2CAT(varargin{1}); + case 'fs2cat' + if isdir(varargin{1}) + covertFS2CAT(varargin) + else + covertFS2CAT + end + case 'gii2fs' + if nargout==1 + varargout{1} = gii2fs(varargin{1}); + elseif nargout==2 + [varargout{1},varargout{2}] = gii2fs(varargin{1}); + else + gii2fs(varargin{1}) + end + case 'fs2gii' + if nargout>0 + varargout{1} = fs2gii(varargin{1}); + else + fs2gii(varargin{1}) + end + case 'read_annotation' + if nargin==2 + [varargout{1}, varargout{2}, varargout{3}] = read_annotation(varargin{1}); + else + [varargout{1}, varargout{2}, varargout{3}] = read_annotation(varargin{1}, varargin(2:end)); + end + varargout{4} = [{'ROIid'},{'ROIname'};num2cell(varargout{3}.table(1:end,5)),varargout{3}.struct_names]; + case 'write_annotation' + + %write_annotation(filename, vertices, label, ct) + write_annotation(varargin{1}, varargin{2}, varargin{3}, varargin{4}) + case 'write_surf' + write_surf(varargin{1}, varargin{2}.vertices, varargin{2}.faces); + case 'read_surf' + [varargout{1}.vertices,varargout{1}.faces] = read_surf(varargin{1}); + % varargout{1}.faces = varargout{1}.faces+1; + case 'write_surf_data' + write_curv(varargin{1},varargin{2}); + case 'read_surf_data' + [varargout{1},varargout{2}] = read_curv(varargin{1}); + otherwise + error(['cat_io_FreeSurfer:unknownAction','Unknown action ''%s''!\n' ... + 'Use ''write_surf'',''read_surf'',''write_surf_data'',''read_surf_data'',''gii2fs'',''fs2gii'',''read_annotation'',''write_annotation''.\n'],action); + end + +end + +function covertFS2CAT(varargin) +%% convert surface data of one subject ... + % start with the CS my add some other maps? + if ~exist('varargin','var') || isempty(varargin{1}) + job.sdirs = spm_select(inf,'dir','Choose FreeSurfer subject directories!'); + else + job.sdirs = varargin{1}.sdirs; + end + job.sdirs = cellstr(job.sdirs); + + % default options + def.sides = {'lh','rh'}; % developer: hemisspheres + def.offset = [-3.25 38.25 -20.5]; % developer: tranlation ... > affine transformation? + def.limit = 300000; % developer: reduce surfaces ... not realy + def.resdir = ''; % ... prepare this somewere else ... + def.mri = {}; % ... convert these files to nifti (nu? & seg & atlas?) + def.surf = {'thickness';'area';'curvature'}; % copy these surface datasets + job = checkinopt(job,def); + + for si=1:numel(sdirs) + %% get subject directory + if strcmp(job.sdirs{si}(end-4:end),'surf') + sdir = spm_fileparts(sdir{si}); + elseif strcmp(job.sdirs{si}(end-7:end),'subjects') + sdir = cat_vol_findfiles(job.sdirs{si},'*',struct('depth',1)); + else + sdir = job.sdirs{si}; + end + + %% get subject name + [FS_sujects,subname1,subname2] = spm_fileparts(sdir); + subname = [subname1,subname2]; + + for hi=1:numel(job.sides) + %% + Pwhite = fullfile(sdir,'surf',sprintf('%s.white',job.sides{hi})); + Ppial = fullfile(sdir,'surf',sprintf('%s.pial',job.sides{hi})); + PCcentral = fullfile(sdir,'surf',sprintf('%s.central.%s',job.sides{hi},subname)); + PCwhite = fullfile(sdir,'surf',sprintf('%s.white.%s',job.sides{hi},subname)); + PCpial = fullfile(sdir,'surf',sprintf('%s.pial.%s',job.sides{hi},subname)); + PCpial = fullfile(sdir,'surf',sprintf('%s.sphere.%s',job.sides{hi},subname)); + PCpial = fullfile(sdir,'surf',sprintf('%s.pial.%s',job.sides{hi},subname)); + + Swhite = cat_io_FreeSurfer('read_surf',Pwhite); + Spial = cat_io_FreeSurfer('read_surf',Ppial); + Scentral.vertices = Swhite.vertices/2 + Spial.vertices/2; + Scentral.faces = Swhite.faces; + if 0 %job.limit + Scentral = reducepatch(patch(Scentral),job.limit); + end + if ~isempty(job.offset) + Scentral.vertices = Scentral.vertices + repmat(job.offset,size(Scentral.vertices,1),1); + Swhite.vertices = Swhite.vertices + repmat(job.offset,size(Swhite.vertices,1),1); + Spial.vertices = Spial.vertices + repmat(job.offset,size(Spial.vertices,1),1); + end + save(gifti(Scentral),[PCcentral '.gii']); + save(gifti(Swhite),[PCwhite '.gii']); + save(gifti(Spial),[PCpial '.gii']); + + %clear Sinner Souter Scentral; + end + end +end + +function job = getjob(job0,sel) +if isstruct(job0) +job = job0; +else +job.data = job0; +end +if ~isfield(job,'data') || isempty(job.data) +job.data = spm_select(inf,'any','Select surface','','',sel); +end +if isempty(job.data), return; end + +job.data = cellstr(job.data); +if isfield(job,'cdata'), job.cdata = cellstr(job.cdata); end +if isfield(job,'cdata') && isfield(job,'data') && ... +numel(job.cdata) ~= numel(job.data) +error('cat_io_FreeSurfer:getjob:data','Number of surface meshes and textures have to be equivalent'); +end + +for si=1:numel(job.data) +if isfield(job,'cdata') +[pp,ff,ee] = spm_fileparts(job.cdata{si}); +else +[pp,ff,ee] = spm_fileparts(job.data{si}); +end +def.fname{si} = strrep(fullfile(pp,[ff ee]),'.gii',''); +end + +def.verb = 0; +def.delete = 0; +def.merge = 0; + +job = cat_io_checkinopt(job,def); +end + +function varargout = gii2fs(varargin) +% convert gifti surfaces to FreeSurfer + job = getjob(varargin,'[lr]h.*.gii'); + + surfname = cell(numel(job.data),1); + curfname = cell(numel(job.data),1); + for si=1:numel(job.data) + [pp,ff] = spm_fileparts(job.data{si}); + sinfo = cat_surf_info(job.data{si}); + + CS = gifti(job.data{si}); + if isfield(CS,'vertices') && isfield(CS,'faces') + switch sinfo.texture + case {'sphere','central','hull','inner','outer'} + surfname{si} = char(cat_surf_rename(sinfo,'ee','')); + otherwise + surfname{si} = char(cat_surf_rename(sinfo,'dataname',[sinfo.texture '_surface'],'ee','')); + end + write_surf(char(surfname{si}), CS.vertices , CS.faces); + else + surfname{si} = ''; + end + if isfield(CS,'cdata') + curfname{si} = fullfile(pp,ff); + + write_curv(curfname{si}, double(CS.cdata)); + else + curfname{si} = ''; + end + if job.delete + delete(job.data{si}); + end + end + + if nargout>0 + varargout{1} = surfname; + end + if nargout>1 + varargout{2} = curfname; + end + +end + +function varargout = fs2gii(varargin) +% convert FreeSurfer surfaces meshes/data files to a gifti + job = getjob(varargin{1},'[lr]h.*'); + + for si=1:numel(job.data) + [pp,ff,ee] = spm_fileparts(job.data{si}); %#ok + switch ee + case '.gii' + S = gifti(job.data{si}); + otherwise + %if isfield(job,'cdata') + try + [vertices,faces] = read_surf(job.data{si}); + S.vertices = vertices; + S.faces = faces; + end + %else + % try %#ok + % S.cdata = read_curv(job.cdata{si}); + % end + %end + end + + if isfield(job,'cdata') + S.cdata = read_curv(job.cdata{si}); + elseif ~exist('S','var') + S.cdata = read_curv(job.data{si}); + end + + job.fname{si} = [job.fname{si} '.gii']; + save(gifti(S),job.fname{si}); + + if job.delete + delete(job.data{si}); + end + clear S; + end + + if nargout>0 + varargout{1} = job.fname; + end +end + +function annots = cat_surf_FSannotation2CAT(job) +% -- in development -- +% Read FreeSurfer average atlas maps and save them as texture with csv +% and xml data. +% > convertation to SPM ROI format ... + + def.trerr = 0; + def.verb = cat_get_defaults('extopts.verb'); + def.debug = cat_get_defaults('extopts.verb')>2; + def.fsavgDir = fullfile(fileparts(mfilename('fullpath')),'templates_surfaces'); + if ismac + def.FSDir = cat_vol_findfiles('/Applications','Freesurfer*',struct('depth',1,'dirs',1)); + def.FSDir = def.FSDir{end}; + end + def.FSsub = cat_vol_findfiles(fullfile(def.FSDir,'subjects'),'fsaverage',struct('depth',1,'dirs',1)); + job = cat_io_checkinopt(job,def); + + for FSsubi=1:numel(job.FSsub) + annots{FSsubi} = cat_vol_findfiles(fullfile(job.FSsub{FSsubi},'label'),'*.annot'); + + for annotsi=1:numel(annots{FSsubi}) + %% + [pp,ff,ee] = fileparts(annots{FSsubi}{annotsi}); side=ff(1:2); + [vertices, label, colortable] = cat_io_FreeSurfer('read_annotation',annots{FSsubi}{annotsi}); + + Pfsavg = fullfile(def.fsavgDir,sprintf('%s.central.freesurfer.gii',side)); % fsaverage central + + CS = gifti(Pfsavg); + + end + + end + +end + +function write_surf(filename, vert, face) +% write_surf - FreeSurfer I/O function to write a surface file +% +% write_surf(filename, vert, face) +% +% writes a surface triangulation into a binary file +% filename - name of file to write +% vert - Nx3 matrix of vertex coordinates +% face - Mx3 matrix of face triangulation indices +% +% The face matrix here must be matlab compatible +% (no zero indices). It is converted to FreeSurfer +% indices that start at zero. +% +% See also freesurfer_read_surf, freesurfer_write_curv, freesurfer_write_wfile + + if(nargin ~= 3) + fprintf('USAGE: freesurfer_write_surf(filename, vert, face)\n'); + return; + end + + if size(vert,2) ~= 3, + error('vert must be Nx3 matrix'); + end + + if size(face,2) ~= 3, + error('face must be Mx3 matrix'); + end + + %fprintf('...subtracting 1 from face indices for FreeSurfer compatibility.\n'); + face = face - 1; + + % open it as a big-endian file + fid = fopen(filename, 'wb', 'b') ; + + TRIANGLE_FILE_MAGIC_NUMBER = 16777214 ; + fwrite3(fid, TRIANGLE_FILE_MAGIC_NUMBER); + + vnum = size(vert,1) ; % number of vertices + fnum = size(face,1) ; % number of faces + + % Ouput a couple of text lines with creation date + fprintf(fid,'created by %s on %s\n\n',getenv('USER'),datestr(now)); % creation date + + fwrite(fid, vnum,'int32'); + fwrite(fid, fnum,'int32'); + + % reshape vert into column array and write + vert = reshape(vert',size(vert,1)*size(vert,2),1); + fwrite(fid, vert,'float32'); + + % reshape face into column array and write + face = reshape(face',size(face,1)*size(face,2),1); + fwrite(fid, face,'int32'); + + fclose(fid) ; + +end + +function [vertex_coords, faces] = read_surf(filename) + % + % [vertex_coords, faces] = read_surf(filename) + % reads a the vertex coordinates and face lists from a surface file + % note that reading the faces from a quad file can take a very long + % time due to the goofy format that they are stored in. If the faces + % output variable is not specified, they will not be read so it + % should execute pretty quickly. + % + + + % + % read_surf.m + % + % Original Author: Bruce Fischl + % CVS Revision Info: + % $Author$ + % $Date$ + % $Revision$ + % + % Copyright ?? 2011 The General Hospital Corporation (Boston, MA) ""MGH"" + % + % Terms and conditions for use, reproduction, distribution and contribution + % are found in the 'FreeSurfer Software License Agreement' contained + % in the file 'LICENSE' found in the FreeSurfer distribution, and here: + % + % https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense + % + % Reporting: freesurfer@nmr.mgh.harvard.edu + % + + + TRIANGLE_FILE_MAGIC_NUMBER = 16777214 ; + QUAD_FILE_MAGIC_NUMBER = 16777215 ; + + if ~exist(filename,'file') + error('MATLAB:cat_io_FreeSurfer:read_surf','mesh file %s does not exist.', filename) ; + end + fid = fopen(filename, 'rb', 'b') ; + if (fid < 0) + error('MATLAB:cat_io_FreeSurfer:read_surf','could not open mesh file %s.', filename) ; + end + magic = fread3(fid) ; + + if(magic == QUAD_FILE_MAGIC_NUMBER) + vnum = fread3(fid) ; + fnum = fread3(fid) ; + vertex_coords = fread(fid, vnum*3, 'int16') ./ 100 ; + faces = zeros(fnum,4,'single'); + if (nargout > 1) + for i=1:fnum + for n=1:4 + faces(i,n) = fread3(fid) ; + end + end + end + elseif (magic == TRIANGLE_FILE_MAGIC_NUMBER) + fgets(fid) ; + fgets(fid) ; + vnum = fread(fid, 1, 'int32') ; + fnum = fread(fid, 1, 'int32') ; + vertex_coords = fread(fid, vnum*3, 'float32') ; + faces = fread(fid, fnum*3, 'int32') ; + faces = reshape(faces, 3, fnum)' ; + else + error('MATLAB:cat_io_FreeSurfer:read_surf','mesh file %s contains no surface.', filename) ; + end + + faces=faces+1; %end + vertex_coords = reshape(vertex_coords, 3, vnum)' ; + fclose(fid) ; +end + +function fwrite3(fid, val) +% +% fwrite3.m +% +% Original Author: Bruce Fischl +% CVS Revision Info: +% $Author$ +% $Date$ +% $Revision$ +% +% Copyright ?? 2011 The General Hospital Corporation (Boston, MA) ""MGH"" +% +% Terms and conditions for use, reproduction, distribution and contribution +% are found in the 'FreeSurfer Software License Agreement' contained +% in the file 'LICENSE' found in the FreeSurfer distribution, and here: +% +% https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense +% +% Reporting: freesurfer@nmr.mgh.harvard.edu +% + + b1 = bitand(bitshift(val, -16), 255) ; + b2 = bitand(bitshift(val, -8), 255) ; + b3 = bitand(val, 255) ; + fwrite(fid, b1, 'uchar') ; + fwrite(fid, b2, 'uchar') ; + fwrite(fid, b3, 'uchar') ; +end + +function [retval] = fread3(fid) + % [retval] = fd3(fid) + % read a 3 byte integer out of a file + + + % + % fread3.m + % + % Original Author: Bruce Fischl + % CVS Revision Info: + % $Author$ + % $Date$ + % $Revision$ + % + % Copyright ?? 2011 The General Hospital Corporation (Boston, MA) ""MGH"" + % + % Terms and conditions for use, reproduction, distribution and contribution + % are found in the 'FreeSurfer Software License Agreement' contained + % in the file 'LICENSE' found in the FreeSurfer distribution, and here: + % + % https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense + % + % Reporting: freesurfer@nmr.mgh.harvard.edu + % + + b1 = fread(fid, 1, 'uchar') ; + b2 = fread(fid, 1, 'uchar') ; + b3 = fread(fid, 1, 'uchar') ; + retval = bitshift(b1, 16) + bitshift(b2,8) + b3 ; + +end + +function err = write_wfile(filename, w, v) +% err = write_wfile(filename, w, ) +% +% writes a vector into a binary 'w' file +% filename - name of file to write to +% w - vector of values to be written +% v - 0-based vertex numbers +% (assumes 0 to N-1 if not present or empty). +% +% See also read_wfile. +% + + +% +% write_wfile.m +% +% Original Author: Doug Greve +% CVS Revision Info: +% $Author$ +% $Date$ +% $Revision$ +% +% Copyright ?? 2011 The General Hospital Corporation (Boston, MA) ""MGH"" +% +% Terms and conditions for use, reproduction, distribution and contribution +% are found in the 'FreeSurfer Software License Agreement' contained +% in the file 'LICENSE' found in the FreeSurfer distribution, and here: +% +% https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense +% +% Reporting: freesurfer@nmr.mgh.harvard.edu +% + + + err = 1; + + if(nargin ~= 2 && nargin ~= 3) + fprintf('USAGE: err = write_wfile(filename, w, ) \n'); + return; + end + + vnum = length(w) ; + + % Handle when v not given or is empty % + if (exist('v','var') ~= 1), v = []; end + if (isempty(v)), v = 0:vnum-1; end + + % open it as a big-endian file + fid = fopen(filename, 'wb', 'b') ; + if(fid == -1) + fprintf('ERROR: could not open %s\n',filename); + return; + end + + fwrite(fid, 0, 'int16') ; + fwrite3(fid, vnum) ; + for i=1:vnum + fwrite3(fid, v(i)) ; % vertex number (0-based) + fwrite(fid, w(i), 'float') ; % vertex value + end + + fclose(fid) ; + + err = 0; +end + +function [curv] = write_curv(filename, curv, fnum) +% [curv] = write_curv(filename, curv, fnum) +% +% writes a curvature vector into a binary file +% filename - name of file to write to +% curv - vector of curvatures +% fnum - # of faces in surface. +% + + +% +% write_curv.m +% +% Original Author: Bruce Fischl +% CVS Revision Info: +% $Author$ +% $Date$ +% $Revision$ +% +% Copyright (C) 2002-2007, +% The General Hospital Corporation (Boston, MA). +% All rights reserved. +% +% Distribution, usage and copying of this software is covered under the +% terms found in the License Agreement file named 'COPYING' found in the +% FreeSurfer source code root directory, and duplicated here: +% https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferOpenSourceLicense +% +% General inquiries: freesurfer@nmr.mgh.harvard.edu +% Bug reports: analysis-bugs@nmr.mgh.harvard.edu +% + + % assume fixed tetrahedral topology + if nargin == 2 + fnum = (length(curv)-2)*2; + end + + % open it as a big-endian file + fid = fopen(filename, 'w', 'b') ; + vnum = length(curv) ; + NEW_VERSION_MAGIC_NUMBER = 16777215; + fwrite3(fid, NEW_VERSION_MAGIC_NUMBER ) ; + fwrite(fid, vnum,'int32') ; + fwrite(fid, fnum,'int32') ; + fwrite(fid, 1, 'int32'); + fwrite(fid, curv, 'float') ; + fclose(fid) ; + +end + +function [curv, fnum] = read_curv(filename) +% +% [curv, fnum] = read_curv(filename) +% reads a binary curvature file into a vector +% +% +% read_curv.m +% +% Original Author: Bruce Fischl +% CVS Revision Info: +% $Author$ +% $Date$ +% $Revision$ +% +% Copyright ?? 2011 The General Hospital Corporation (Boston, MA) ""MGH"" +% +% Terms and conditions for use, reproduction, distribution and contribution +% are found in the 'FreeSurfer Software License Agreement' contained +% in the file 'LICENSE' found in the FreeSurfer distribution, and here: +% +% https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense +% +% Reporting: freesurfer@nmr.mgh.harvard.edu +% + + + % open it as a big-endian file + if ~exist(filename,'file') + error('cat_io_FreeSurfer:read_curv','Curvature file ""%s"" does not exist!\n', filename); + end + fid = fopen(filename, 'r', 'b') ; + if (fid < 0) + error('cat_io_FreeSurfer:read_curv','Could not open curvature file ""%s""!\n', filename); + end + vnum = fread3(fid) ; + NEW_VERSION_MAGIC_NUMBER = 16777215; + if (vnum == NEW_VERSION_MAGIC_NUMBER) + vnum = fread(fid, 1, 'int32') ; + fnum = fread(fid, 1, 'int32') ; + x = fread(fid, 1, 'int32') ; + curv = fread(fid, vnum, 'float') ; + + fclose(fid) ; + else + + fnum = fread3(fid) ; + curv = fread(fid, vnum, 'int32') ./ 100 ; + fclose(fid) ; + end + +end + +function write_annotation(filename, vertices, label, ct) +% Contact ythomas@csail.mit.edu or msabuncu@csail.mit.edu for bugs or questions +% +%========================================================================= +% +% Copyright (c) 2008 Thomas Yeo and Mert Sabuncu +% All rights reserved. +% +%Redistribution and use in source and binary forms, with or without +%modification, are permitted provided that the following conditions are met: +% +% * Redistributions of source code must retain the above copyright notice, +% this list of conditions and the following disclaimer. +% +% * Redistributions in binary form must reproduce the above copyright notice, +% this list of conditions and the following disclaimer in the documentation +% and/or other materials provided with the distribution. +% +% * Neither the names of the copyright holders nor the names of future +% contributors may be used to endorse or promote products derived from this +% software without specific prior written permission. +% +%THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS"" AND +%ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +%WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +%DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +%ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +%(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +%LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +%ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +%(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +%SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +% +%========================================================================= + + % write_annotation(filename, vertices, label, ct) + % + % Only writes version 2... + % + % vertices expected to be simply from 0 to number of vertices - 1; + % label is the vector of annotation + % + % ct is a struct + % ct.numEntries = number of Entries + % ct.orig_tab = name of original ct + % ct.struct_names = list of structure names (e.g. central sulcus and so on) + % ct.table = n x 5 matrix. 1st column is r, 2nd column is g, 3rd column + % is b, 4th column is flag, 5th column is resultant integer values + % calculated from r + g*2^8 + b*2^16 + flag*2^24. flag expected to be all 0 + + fp = fopen(filename, 'w', 'b'); + + % first write vertices and label + + count = fwrite(fp, int32(length(label)), 'int'); + if(count~=1) + error('write_annotation: Writing #vertices/labels not successful!!'); + end + + temp = zeros(length(label)*2,1); + temp(1:2:end) = vertices; + temp(2:2:end) = label; + temp = int32(temp); + + count = fwrite(fp, int32(temp), 'int'); + if(count~=length(temp)) + error('write_annotation: Writing labels/vertices not successful!!'); + end + + %Write that ct exists + count = fwrite(fp, int32(1), 'int'); + if(count~=1) + error('write_annotation: Unable to write flag that ct exists!!'); + end + + %write version number + count = fwrite(fp, int32(-2), 'int'); + if(count~=1) + error('write_annotation: Unable to write version number!!'); + end + + %write number of entries + count = fwrite(fp, int32(ct.numEntries), 'int'); + if(count~=1) + error('write_annotation: Unable to write number of entries in ct!!'); + end + + %write original table + orig_tab = [ct.orig_tab char(0)]; + count = fwrite(fp, int32(length(orig_tab)), 'int'); + if(count~=1) + error('write_annotation: Unable to write length of ct source!!'); + end + + count = fwrite(fp, orig_tab, 'char'); + if(count~=length(orig_tab)) + error('write_annotation: Unable to write orig_tab!!'); + end + + %write number of entries + count = fwrite(fp, int32(ct.numEntries), 'int'); + if(count~=1) + error('write_annotation: Unable to write number of entries in ct!!'); + end + + %write ct + for i = 1:ct.numEntries + count = fwrite(fp, int32(i-1), 'int'); + if(count~=1) + error('write_annotation: Unable to write structure number!!'); + end + + structure_name = [ct.struct_names{i} char(0)]; + count = fwrite(fp, int32(length(structure_name)), 'int'); + if(count~=1) + error('write_annotation: Unable to write length of structure name!!'); + end + count = fwrite(fp, structure_name, 'char'); + if(count~=length(structure_name)) + error('write_annotation: Unable to write structure name!!'); + end + + for j=1:4 + count = fwrite(fp, int32(ct.table(i, j)), 'int'); + if(count~=1) + error('write_annotation: Unable to write red color'); + end + end + + end + + fclose(fp); +end + +function [vertices, label, colortable] = read_annotation(filename, varargin) +% +% NAME +% +% function [vertices, label, colortable] = ... +% read_annotation(filename [, verbosity]) +% +% ARGUMENTS +% INPUT +% filename string name of annotation file to read +% +% OPTIONAL +% verbosity int if true (>0), disp running output +% + if false (==0), be quiet and do not +% + display any running output +% +% OUTPUT +% vertices vector vector with values running from 0 to +% + size(vertices)-1 +% label vector lookup of annotation values for +% + corresponding vertex index. +% colortable struct structure of annotation data +% + see below +% +% DESCRIPTION +% +% This function essentially reads in a FreeSurfer annotation file +% and returns structures and vectors that together +% assign each index in the surface vector to one of several +% structure names. +% +% COLORTABLE STRUCTURE +% +% Consists of the following fields: +% o numEntries: number of entries +% o orig_tab: filename of original colortable file +% o struct_names: cell array of structure names +% o table: n x 5 matrix +% Columns 1,2,3 are RGB values for struct color +% Column 4 is a flag (usually 0) +% Column 5 is the structure ID, calculated from +% R + G*2^8 + B*2^16 + flag*2^24 +% +% LABEL VECTOR +% +% Each component of the
Dahnke et al., 2011)). +% +% [GMT,RPM] = cat_vol_pbtp(SEG,WMD,CSFD[,opt]) +% +% GMT (3D single) .. thickness image +% RPM (3D single) .. radial position map +% SEG (3D single) .. segment image with low and high boundary bd +% (default 1=CSF, 2=GM, 3=WM) +% WMD (3D single) .. CSF distance map +% CSFD (3D single) .. CSF distance map +% +% opt .. MATLAB structure +% .bd (1x2 single) .. [low,high] boundary values (default 1.5 and 2.5) +% .CSFD .. calculate CSFD +% .PVE .. use PVE information (0=none,1=fast,2=exact) +% +% See also cat_vbdist, cat_vol_eidist, compile. +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_roi_values2surf.m",".m","2214","65","function cat_roi_values2surf(atlas_name, values, surfname); +%_______________________________________________________________________ +% map values from surface atlas ROIs to surface +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +if nargin == 0 + atlas_name = spm_select(1,'^lh.*\.annot$','Select left atlas file for value mapping',{},fullfile(fileparts(mfilename('fullpath')),'atlases_surfaces_32k')); +end + +[vertices, lrdata, colortable, lrcsv] = cat_io_FreeSurfer('read_annotation',atlas_name); +[vertices, rrdata, colortable, rrcsv] = cat_io_FreeSurfer('read_annotation',char(cat_surf_rename(atlas_name,'side','rh'))); +lrdata = round(lrdata); +rrdata = round(rrdata); + +n_rois = 2*colortable.numEntries; +info = cat_surf_info(atlas_name); +atlas = info.dataname; + +if nargin == 0 + values = spm_input('Values in the order of the atlas ROI', 1, 'e', [], n_rois); + surfname = spm_input('Name of surface', '+1', 's', ['mesh.val2surf_' atlas '.gii'], n_rois); +end + +fsaverage = fullfile(fileparts(mfilename('fullpath')),'templates_surfaces_32k','mesh.central.freesurfer.gii'); +M = gifti(fsaverage); + +lvalues = values(1:2:n_rois); +rvalues = values(2:2:n_rois); + +ldata = zeros(size(lrdata)); +rdata = zeros(size(rrdata)); + +lids = cell2mat(lrcsv(2:end,1)); +rids = cell2mat(rrcsv(2:end,1)); + +for i=1:n_rois/2 + ldata(lrdata == lids(i)) = lvalues(i); + rdata(rrdata == rids(i)) = rvalues(i); +end + +M.cdata = [ldata; rdata]; +save(gifti(M), surfname, 'Base64Binary'); +cat_surf_results('Disp',surfname); +cat_surf_results('texture', 3); % no texture +border_mode = 0; +if strcmp(atlas,'aparc_DK40') + border_mode = 1; +elseif strcmp(atlas,'aparc_a2009s') + border_mode = 2; +elseif strcmp(atlas,'aparc_HCP_MMP1') + border_mode = 3; +end +cat_surf_results('surface', 2); % inflated surface +if border_mode, cat_surf_results('border', border_mode); end +cat_surf_results('clim',[ min(M.cdata) max(M.cdata)]); +cat_surf_results('colorbar'); +cat_surf_results('colorbar'); +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_surf_createCS.m",".m","62675","1257","function [Yth1,S,Psurf,EC,defect_size,res] = cat_surf_createCS(V,V0,Ym,Ya,YMF,opt,job) +% ______________________________________________________________________ +% Surface creation and thickness estimation. +% +% [Yth1,S,Psurf,EC]=cat_surf_createCS(V,V0,Ym,Ya,YMF,opt) +% +% Yth1 = thickness map +% S = structure with surfaces, like the left hemishere, that contains +% vertices, faces, GM thickness (th1), and the transformation to +% map to nifti space (vmat) and back (vmati). +% Psurf = name of surface files +% EC = Euler characteristic +% defect_size = size of topology defects +% V = spm_vol-structure of internally interpolated image +% V0 = spm_vol-structure of original image +% Ym = the (local) intensity, noise, and bias corrected T1 image +% Ya = the atlas map with the ROIs for left and right hemispheres +% (this is generated with cat_vol_partvol) +% Yp0 = label image for surface deformation +% YMF = a logical map with the area that has to be filled +% (this is generated with cat_vol_partvol) +% +% opt.surf = {'lh','rh'[,'lc','rc']} - side +% .reduceCS = 100000 - number of faces +% +% Options set by cat_defaults.m +% .interpV = 0.5 - mm-resolution for thickness estimation +% +% Here we used the intensity normalized image Ym, rather that the Yp0 +% image, because it has more information about sulci that we need +% especially for asymmetrical sulci. +% Furthermore, all non-cortical regions and blood vessels were removed +% (for left and right surface). Blood vessels (with high contrast) can +% lead to strong error in the topology correction. Higher resolution +% also helps to reduce artifacts. +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +% Turn off gifti data warning in gifti/subsref (line 45) +% Warning: A value of class ""int32"" was indexed with no subscripts specified. +% Currently the result of this operation is the indexed value itself, +% but in a future release, it will be an error. +warning('off','MATLAB:subscripting:noSubscriptsSpecified'); +cstime = clock; + + % variables to tranfer from MATLAB to image coordinates used by loadSurf and saveSurf subfunctions + global vmat vmati mati + + if strcmpi(spm_check_version,'octave') + cat_io_addwarning('cat_surf_createCS:noSRP','Correction of surface collisions is not yet available under Octave.',[1 1]) + opt.SRP = 0; + end + + % surface evaluation parameter + res = struct('euler_characteristic',nan,'defect_size',nan,'lh',struct(),'rh',struct()); + +%#ok<*AGROW> + dbs = dbstatus; debug = 0; for dbsi=1:numel(dbs), if strcmp(dbs(dbsi).name,mfilename); debug = 1; break; end; end + + % set defaults + vx_vol = sqrt(sum(V.mat(1:3,1:3).^2)); % further interpolation based on internal resolution + vx_vol0 = sqrt(sum(V0.mat(1:3,1:3).^2)); % final surface resolution based on original image resolution + if ~exist('opt','var'), opt=struct(); end + def.verb = max(2,2 + cat_get_defaults('extopts.expertgui')); + def.surf = {'lh','rh'}; + + % reducepatch has some issues with self intersections + def.reduceCS = 0; + + def.vdist = max(1,mean(vx_vol0)); % distance between vertices ... at least 1 mm ? + def.LAB = cat_get_defaults('extopts.LAB'); + def.SPM = 0; + def.pbtmethod = 'pbt2x'; + def.WMT = 0; % WM/CSF width/depth/thickness + def.sharpenCB = 0; % in development + def.thick_measure = 1; % Tfs: Freesurfer method using mean(Tnear1,Tnear2) + def.thick_limit = 5; % 5mm upper limit for thickness (same limit as used in Freesurfer) + def.SRP = 3; % Estimate pial and white matter surface (in development and very slow!) + def.new_release = 0; % developer flag to test new functionality for new release (currently not used) + def.pbtlas = 0; + def.interpV = 0.5; + def.add_parahipp = cat_get_defaults('extopts.add_parahipp'); + def.scale_cortex = cat_get_defaults('extopts.scale_cortex'); + def.close_parahipp = cat_get_defaults('extopts.close_parahipp'); + + opt = cat_io_updateStruct(def,opt); + opt.vol = any(~cellfun('isempty',strfind(opt.surf,'v'))); + opt.interpV = max(0.1,min([opt.interpV,1.5])); + opt.interpVold = opt.interpV; + opt.surf = cat_io_strrep(opt.surf,'v',''); + + % check for self-intersections during surface refinement with CAT_SurfDeform + if opt.SRP == 1 + force_no_selfintersections = 1; + else + force_no_selfintersections = 0; + end + + opt.fsavgDir = fullfile(fileparts(mfilename('fullpath')),'templates_surfaces'); + + Psurf = struct(); + + % correction for 'n' prefix for noise corrected and/or interpolated files + [pp0,ff] = spm_fileparts(V0.fname); + + if exist('job','var') + [mrifolder, reportfolder, surffolder, labelfolder] = cat_io_subfolders(V0.fname,job); + else + [mrifolder, reportfolder, surffolder, labelfolder] = cat_io_subfolders(V0.fname); + end + + % change surffolder name if subfolders are forced and surffolder has + % default name ""surf"" (i.e. for non-BIDS structure) + if cat_get_defaults('extopts.subfolders') && strcmp(surffolder,'surf') + if strcmp(opt.pbtmethod,'pbt2x') + opt.pbtmethod = 'pbt2x'; + surffolder = sprintf('%s_%s_%0.2f',surffolder,opt.pbtmethod,opt.interpV); + end + pp0 = spm_str_manip(pp0,'h'); % remove 'mri' in pathname that already exists + if ~exist(fullfile(pp0,surffolder),'dir'), mkdir(fullfile(pp0,surffolder)); end + end + + % get original filename without 'n' + [pp0,ff] = spm_fileparts(V0.fname); + + % function to estimate the number of interactions of the surface deformation: d=distance in mm and a=accuracy + QMC = cat_io_colormaps('marks+',17); + color = @(m) QMC(max(1,min(size(QMC,1),round(((m-1)*3)+1))),:); + rate = @(x,best,worst) min(6,max(1, max(0,x-best) ./ (worst-best) * 5 + 1)); + + + %% get both sides in the atlas map + NS = @(Ys,s) Ys==s | Ys==s+1; + + % noise reduction for higher resolutions (>=1 mm full correction, 1.5 mm as lower limit) + % (added 20160920 ~R1010 due to servere sulcus reconstruction problems with 1.5 Tesla data) + Yms = Ym + 0; cat_sanlm(Yms,3,1); + %noise = std(Yms(Yms(:)>0) - Ym(Yms(:)>0)); % more selective filtering? + %vx_vol = [0.5;0.75;1;1.25;1.5;2]; [vx_vol + %min(1,max(0,3-2*mean(vx_vol,2))) min(1,max(0,1-mean(vx_vol,2))/2) 0.5*min(1,max(0,1.5-mean(vx_vol,2)))] % filter test + mf = min(1,max(0,3-2*mean(vx_vol,2))); + Ym = mf * Yms + (1-mf) * Ym; + clear Yms; + + % filling + Ymf = max(Ym,min(1,YMF)); + Ymfs = cat_vol_smooth3X(Ymf,1); + Ytmp = cat_vol_morph(YMF,'d',3) & Ymfs>2.3/3; + Ymf(Ytmp) = max(min(Ym(Ytmp),0),Ymfs(Ytmp)); clear Ytmp Ymfs; + Ymf = Ymf*3; + + %% reduction of artifact, blood vessel, and meninges next to the cortex + % (are often visible as very thin structures that were added to the WM + % or removed from the brain) + if ~opt.SPM + Ydiv = cat_vol_div(Ymf,vx_vol); + Ycsfd = cat_vbdist(single(Ymf<1.5),Ymf>1,vx_vol); + Yctd = cat_vbdist(single(Ymf<0.5),Ymf>0,vx_vol); + Ysroi = Ymf>2 & Yctd<10 & Ycsfd>0 & Ycsfd<2 & ... + cat_vol_morph(~NS(Ya,opt.LAB.HC) & ~NS(Ya,opt.LAB.HI) & ... + ~NS(Ya,opt.LAB.PH) & ~NS(Ya,opt.LAB.VT),'erode',4); + Ybv = cat_vol_morph(Ymf+Ydiv./max(1,Ymf)>3.5,'d') & Ymf>2; + Ymf(Ybv) = 1.4; + Ymfs = cat_vol_median3(Ymf,Ysroi | Ybv,Ymf>eps & ~Ybv,0.1); % median filter + %% + Ymf = mf * Ymfs + (1-mf) * Ymf; + + %% closing of small WMHs and blood vessels + %vols = [sum(round(Ymf(:))==1 & Ya(:)>0) sum(round(Ymf(:))==2) sum(round(Ymf(:))==3)] / sum(round(Ymf(:))>0); + %volt = min(1,max(0,mean([ (vols(1)-0.20)*5 (1 - max(0,min(0.3,vols(3)-0.2))*10) ]))); + %Ywmh = cat_vol_morph(Ymf>max(2.2,2.5 - 0.3*volt),'lc',volt); + %Ymf = max(Ymf,smooth3(Ywmh)*2.9); + + % gaussian filter? ... only in tissue regions + %Ymfs = cat_vol_smooth3X(max(1,Ymf),0.5*min(1,max(0,1.5-mean(vx_vol)))); + %Ymf(Ymf>1) = Ymfs(Ymf>1); + end + if ~debug, clear Ysroi Ymfs Yctd Ybv Ymfs; end + + + + if 1 + %% CS2: Amygdala Hippocampus smoothing + % We use a median filter to remove the nice details of the hippocampus + % that will cause topology errors and self-intersections. + % Currently, I have no CAT ROI for Amygdala - but it would be more + % robust to filter (simple smoothing) this region strongly because + % the ""random"" details especially in good data introduce more variance. + % (RD 201912) + + Ymsk = ~(NS(Ya,opt.LAB.PH) | NS(Ya,opt.LAB.ON) | NS(Ya,opt.LAB.BS) ); + Ymsk = Ymf>0 & cat_vol_morph( NS(Ya,opt.LAB.HC) , 'dd' , 3 , vx_vol ) & Ymsk; + Ymf = cat_vol_median3( Ymf , Ymsk ); + Ymf = cat_vol_median3( Ymf , Ymsk ); + if ~debug, clear Ymsk; end + + % further cleanup + Ymsk = ~(NS(Ya,opt.LAB.PH) | NS(Ya,opt.LAB.ON) | NS(Ya,opt.LAB.BS) ); + Ymsk = Ymf>0 & NS(Ya,opt.LAB.HC) & Ymsk; + Ymsk = smooth3(Ymsk); + Ymf = min(Ymf,3-Ymsk); + if ~debug, clear Ymsk; end + end + + + + if 0 + %% CS2: Sharpening + % This function works quite good in the cerebellum and it allows to + % stabilize thin structures avoiding thickness overestimations if it + % used moderatly. Abuse can increase problems by local artefacts or + % unwanted details that finally cause strong local unterestimation. + % (RD 201911) + + gmv = sum(round(Ymf(:))==2) / sum(round(Ymf(:))==3); gmvm = max(0,min(1,1 / gmv)); + for i=1:gmv, Ymf = Ymf.*(gmvm) + (1 - gmvm).*max(1,min(3, Ymf - smooth3(cat_vol_median3(Ymf,Ymf>1,Ymf>1) - Ymf) )); end + end + + + + %% sharpening of thin structures (gyri and sulci) + % WARNING: this will change cortical thickness! + if ~opt.SPM && opt.sharpenCB + Ydiv = cat_vol_div(Ymf); %Ydivl = cat_vol_div(Ymf,vx_vol); + Ywmd = cat_vbdist(single(Ymf>2.5),Ymf>1,vx_vol); + if 0 + %% divergence based + % this works in principle but gyral crones and sulcal values are + % overestimated ... need limit + Ymsk = (NS(Ya,opt.LAB.CB) & ((Ymf<2.8 & Ymf>2.0 ) | (Ymf<1.9 & Ymf>1.2 )) ) | ... sulci and gyri in the cerebellum + (NS(Ya,opt.LAB.CT) & ((Ymf<2.8 & Ymf>2.0 & Ycsfd>3) | (Ymf<1.9 & Ymf>1.2 & Ywmd>3)) ) | ... distant gyri and sulci in the cerebrum + (NS(Ya,opt.LAB.PH) & ((Ymf<2.8 & Ymf>2.0 & Ycsfd>3) | (Ymf<1.9 & Ymf>1.2 & Ywmd>3)) ); + Ymf = min(3,max( min(1,Ymf) , Ymf - (abs(Ydivl) .* Ydiv) .* Ymsk)); + end + + if 1 + %% biascorrection based + % WM + Ymsk = ((NS(Ya,opt.LAB.CB) | YMF) & ( Ymf>2.2 | (Ymf>2 & Ydiv<-0.01) ) ) | ... % sulci and gyri in the cerebellum + (NS(Ya,opt.LAB.PH) & ( Ymf>2.2 | (Ymf>2 & Ydiv<-0.01) ) ) | ... % hippocampal gyri + (NS(Ya,opt.LAB.CT) & ( Ymf>2.2 | (Ymf>2 & Ydiv<-0.01 & Ycsfd>cat_stat_nanmean(Ycsfd(Ycsfd(:)>0 & Ycsfd(:)<100)) )*1.0) ); % distant gyri and sulci in the cerebrum + Yi = cat_vol_localstat(Ymf,Ymsk,1,3); + % GM + Ymsk = (NS(Ya,opt.LAB.CB) & ( Ymf>1.9 & Ymf<2.2 & Ycsfd>0 & Ydiv>-0.05) ) | ... % sulci and gyri in the cerebellum + (NS(Ya,opt.LAB.PH) & ( Ymf>1.3 & Ymf<2.2 & Ycsfd>0 ) ) | ... % hippocampal gyri + (NS(Ya,opt.LAB.CT) & ( Ymf>1.3 & Ymf<2.2 & Ycsfd>0 & Ywmd>cat_stat_nanmean(Ywmd(Ywmd(:)>0 & Ywmd(:)<100))*0.2 ) ); % distant gyri and sulci in the cerebrum + Yi = Yi + cat_vol_localstat(Ymf,Yi==0 & Ymsk,1,1)/2*3; + Yi = cat_vol_localstat(Yi,Yi>0,1,3); + Yi = cat_vol_localstat(Yi,Yi>0,1,1); + if ~debug, clear Ywmd; end + %% CSF - instable and not required + %Ymsk = NS(Ya,opt.LAB.VT) & Ymf>=0.5 & Ymf<1.5; % sulci and gyri in the cerebellum + %Yi = Yi + cat_vol_localstat(Ymf,Yi==0 & Ymsk,1,3)*3; + %% + Ywi = cat_vol_approx(Yi,'nn',1,2,struct('lfO',2)); + + %% + Ymf = Ymf./Ywi * 3; + if ~debug, clear Ywi Yi; end + end + if ~debug, clear Ymsk; end + end + if ~debug, clear Ydiv Ycsfd; end + + Yth1 = zeros(size(Ymf),'single'); + if opt.WMT > 1 + Ywd = zeros(size(Ymf),'single'); + Ycd = zeros(size(Ymf),'single'); + end + + [D,I] = cat_vbdist(single(Ya>0)); Ya = Ya(I); % for sides + + % use sum of EC's and defect sizes for all surfaces, thus set values initially to 0 + EC = 0; + defect_size = 0; + defect_area = 0; + defect_number = 0; + + % correct '../' parts in directory for BIDS structure + pp_surffolder = fullfile(pp0,surffolder); + [stat, val] = fileattrib(pp_surffolder); + if stat, pp_surffolder = val.Name; end + + for si=1:numel(opt.surf) + + % surface filenames + Pm = fullfile(pp0,mrifolder, sprintf('m%s',ff)); % raw + Praw = fullfile(pp_surffolder,sprintf('%s.central.nofix.%s.gii',opt.surf{si},ff)); % raw + Psphere0 = fullfile(pp_surffolder,sprintf('%s.sphere.nofix.%s.gii',opt.surf{si},ff)); % sphere.nofix + Pcentral = fullfile(pp_surffolder,sprintf('%s.central.%s.gii',opt.surf{si},ff)); % central + Pcentralr = fullfile(pp_surffolder,sprintf('%s.central.resampled.%s.gii',opt.surf{si},ff));% central + Player4 = fullfile(pp_surffolder,sprintf('%s.layer4.%s.gii',opt.surf{si},ff)); % layer4 + Ppial = fullfile(pp_surffolder,sprintf('%s.pial.%s.gii',opt.surf{si},ff)); % pial (GM/CSF) + Pwhite = fullfile(pp_surffolder,sprintf('%s.white.%s.gii',opt.surf{si},ff)); % white (WM/GM) + Pthick = fullfile(pp_surffolder,sprintf('%s.thickness.%s',opt.surf{si},ff)); % FS thickness / GM depth + Ppbt = fullfile(pp_surffolder,sprintf('%s.pbt.%s',opt.surf{si},ff)); % PBT thickness / GM depth + Pmask = fullfile(pp_surffolder,sprintf('%s.mask.%s',opt.surf{si},ff)); % mask + Ptemp = fullfile(pp_surffolder,sprintf('%s.temp.%s',opt.surf{si},ff)); % temporary file + Pgwo = fullfile(pp_surffolder,sprintf('%s.depthWMo.%s',opt.surf{si},ff)); % gyrus width / GWM depth / gyral span + Pgw = fullfile(pp_surffolder,sprintf('%s.depthGWM.%s',opt.surf{si},ff)); % gyrus width / GWM depth / gyral span + Pgww = fullfile(pp_surffolder,sprintf('%s.depthWM.%s',opt.surf{si},ff)); % gyrus witdh of the WM / WM depth + Pgwwg = fullfile(pp_surffolder,sprintf('%s.depthWMg.%s',opt.surf{si},ff)); % gyrus witdh of the WM / WM depth + Psw = fullfile(pp_surffolder,sprintf('%s.depthCSF.%s',opt.surf{si},ff)); % sulcus width / CSF depth / sulcal span + Pdefects0 = fullfile(pp_surffolder,sprintf('%s.defects.%s',opt.surf{si},ff)); % defects temporary file + Pdefects = fullfile(pp_surffolder,sprintf('%s.defects.%s.gii',opt.surf{si},ff)); % defects + Psphere = fullfile(pp_surffolder,sprintf('%s.sphere.%s.gii',opt.surf{si},ff)); % sphere + Pspherereg = fullfile(pp_surffolder,sprintf('%s.sphere.reg.%s.gii',opt.surf{si},ff)); % sphere.reg + Pfsavg = fullfile(opt.fsavgDir, sprintf('%s.central.freesurfer.gii',opt.surf{si})); % fsaverage central + Pfsavgsph = fullfile(opt.fsavgDir, sprintf('%s.sphere.freesurfer.gii',opt.surf{si})); % fsaverage sphere + Pfsavgmask = fullfile(opt.fsavgDir, sprintf('%s.mask',opt.surf{si})); % fsaverage mask + + + % use surface of given (average) data as prior for longitudinal mode + if isfield(opt,'useprior') && ~isempty(opt.useprior) + % RD20200729: delete later ... && exist(char(opt.useprior),'file') + % if it not exist than filecopy has to print the error + priorname = opt.useprior; + [pp0,ff0] = spm_fileparts(priorname); + + % try to copy surface files from prior to indivudal surface data + useprior = 1; + useprior = useprior & copyfile(fullfile(pp0,surffolder,sprintf('%s.central.%s.gii',opt.surf{si},ff0)),Pcentral,'f'); + useprior = useprior & copyfile(fullfile(pp0,surffolder,sprintf('%s.sphere.%s.gii',opt.surf{si},ff0)),Psphere,'f'); + useprior = useprior & copyfile(fullfile(pp0,surffolder,sprintf('%s.sphere.reg.%s.gii',opt.surf{si},ff0)),Pspherereg,'f'); + + if ~useprior + warn_str = sprintf('Surface files for %s not found. Move on with individual surface extraction.\n',fullfile(pp0,ff0)); + fprintf('\nWARNING: %s',warn_str); + cat_io_addwarning('cat_surf_createCS:noPiorSurface', warn_str); + else + fprintf('\nUse existing surface from %s as prior and thus skip many processing steps.\n',fullfile(pp0,ff0)); + end + else + useprior = 0; + end + + surffile = {'Praw','Psphere0','Pcentral','Pthick','Ppbt','Pgw','Pgww','Psw',... + 'Pdefects0','Pdefects','Psphere','Pspherereg','Pfsavg','Pfsavgsph','Pwhite','Ppial'}; + for sfi=1:numel(surffile) + eval(sprintf('Psurf(si).%s = %s;',surffile{sfi},surffile{sfi})); + end + + % reduce for object area + switch opt.surf{si} + case {'lh'}, Ymfs = Ymf .* (Ya>0) .* ~(NS(Ya,opt.LAB.CB) | NS(Ya,opt.LAB.BV) | NS(Ya,opt.LAB.ON) | NS(Ya,opt.LAB.MB)) .* (mod(Ya,2)==1); Yside = mod(Ya,2)==1; + case {'rh'}, Ymfs = Ymf .* (Ya>0) .* ~(NS(Ya,opt.LAB.CB) | NS(Ya,opt.LAB.BV) | NS(Ya,opt.LAB.ON) | NS(Ya,opt.LAB.MB)) .* (mod(Ya,2)==0); Yside = mod(Ya,2)==0; + case {'lc'}, Ymfs = Ymf .* (Ya>0) .* NS(Ya,opt.LAB.CB).* (mod(Ya,2)==1); Yside = mod(Ya,2)==1; + case {'rc'}, Ymfs = Ymf .* (Ya>0) .* NS(Ya,opt.LAB.CB).* (mod(Ya,2)==0); Yside = mod(Ya,2)==0; + case {'cb'}, Ymfs = Ymf .* (Ya>0) .* NS(Ya,opt.LAB.CB); Yside = mod(Ya,2)==0; + end + + switch opt.surf{si} + case {'lh','rh'}, opt.interpV = opt.interpVold; + case {'lc','rc'}, opt.interpV = opt.interpVold / 2 ; + case {'cb'}, opt.interpV = opt.interpVold; + end + + % check for cerebellar hemis + iscerebellum = strcmp(opt.surf{si},'lc') || strcmp(opt.surf{si},'rc') || strcmp(opt.surf{si},'cb'); + + % scaling factor for reducing patches and refinement for cerebellar hemis 2..4 according to voxel size + % or 1 for cerebrum + scale_cerebellum = 1 + (iscerebellum*max(1,min(3,1/mean(vx_vol,2)))); + + % get dilated mask of gyrus parahippocampalis and hippocampus of both sides + if ~iscerebellum + mask_parahipp = cat_vol_morph(NS(Ya,opt.LAB.PH) | NS(Ya,opt.LAB.HC),'d',6); + end + + %% thickness estimation + if si==1, fprintf('\n'); end + fprintf('%s:\n',opt.surf{si}); + + stime = cat_io_cmd(sprintf(' Thickness estimation (%0.2f mm%s)',opt.interpV,native2unicode(179, 'latin1'))); stimet =stime; + + % removing background (smoothing to remove artifacts) + switch opt.surf{si} + case {'lh','rh'}, [Ymfs,Ysidei,mask_parahipp,BB] = cat_vol_resize({Ymfs,Yside,mask_parahipp},'reduceBrain',vx_vol,4,smooth3(Ymfs)>1.5); + case {'lc','rc'}, [Ymfs,Ysidei,BB] = cat_vol_resize({Ymfs,Yside},'reduceBrain',vx_vol,4,smooth3(Ymfs)>1.5); + case {'cb'}, [Ymfs,Ysidei,BB] = cat_vol_resize({Ymfs,Yside},'reduceBrain',vx_vol,4,smooth3(Ymfs)>1.5); + end + interpBB = BB; interpBB.interpV = opt.interpV; + + imethod = 'cubic'; % cubic should be better in general - however, linear is better for small thickness (version?) + [Ymfs,resI] = cat_vol_resize(max(1,Ymfs),'interp',V,opt.interpV,imethod); % interpolate volume + Ysidei = cat_vol_resize(single(Ysidei>0.5),'interp',V,opt.interpV,imethod)>0.5; % interpolate volume (small dilatation) + + if ~iscerebellum + mask_parahipp = cat_vol_resize(mask_parahipp,'interp',V,opt.interpV)>0.5; % interpolate volume + end + + Ymfs = min(3,max(1,Ymfs)); + + %% pbt calculation + if strcmp(opt.pbtmethod,'pbtsimple') + [Yth1i,Yppi] = cat_vol_pbtsimple(Ymfs,opt.interpV,struct('classic',1)); + else + [Yth1i,Yppi] = cat_vol_pbt(Ymfs,struct('method',opt.pbtmethod,'resV',opt.interpV,'vmat',... + V.mat(1:3,:)*[0 1 0 0; 1 0 0 0; 0 0 1 0; 0 0 0 1],'pbtlas',opt.pbtlas)); % avoid underestimated thickness in gyri + end + + + %% + Yth1i(Yth1i>10)=0; Yppi(isnan(Yppi))=0; + [D,I] = cat_vbdist(Yth1i,Ysidei); Yth1i = Yth1i(I); clear D I Ysidei; % add further values around the cortex + Yth1t = cat_vol_resize(Yth1i,'deinterp',resI); %clear Yth1i; % back to original resolution + Yth1t = cat_vol_resize(Yth1t,'dereduceBrain',BB); % adding background + Yth1 = max(Yth1,Yth1t .* Yside); % save on main image + clear Yth1t; + if 0 %~useprior + fprintf('%5.0fs\n',etime(clock,stime)); + end + + if opt.vol + S = struct(); Psurf = ''; + fprintf('%5.0fs\n',etime(clock,stime)); + continue + end + + %% PBT estimation of the gyrus and sulcus width + if opt.WMT > 1 + %% gyrus width / WM depth + % For the WM depth estimation it is better to use the L4 boundary + % and correct later for thickness, because the WM is very thin in + % gyral regions and will cause bad values. + % On the other side we do not want the whole filled block of the + % Yppi map and so we have to mix both the original WM map and the + % Yppi map. + % As far as there is no thickness in pure WM regions there will + % be no correction. + % + % figure, isosurface(smooth3(Yppi),0.5,Yth1i), axis equal off + stime = cat_io_cmd(' WM depth estimation'); + [Yar,Ymr,BB] = cat_vol_resize({Ya,Ym},'reduceBrain',vx_vol,BB.BB); % removing background + Yar = uint8(cat_vol_resize(Yar,'interp',V,opt.interpV,'nearest')); % interpolate volume + Ymr = cat_vol_resize(Ymr,'interp',V,opt.interpV); % interpolate volume + switch opt.surf{si} + case {'lh'}, + Ymr = Ymr .* (Yar>0) .* ~(NS(Yar,3) | NS(Yar,7) | NS(Yar,11) | NS(Yar,13)) .* (mod(Yar,2)==1); + Ynw = smooth3(cat_vol_morph(NS(Yar,5) | NS(Yar,9) | NS(Yar,15) | NS(Yar,23),'d',2) | ... + (cat_vol_morph(Yppi==1,'e',2) & Ymr>1.7/3 & Ymr<2.5/3) & (mod(Yar,2)==1)); + case {'rh'}, + Ymr = Ymr .* (Yar>0) .* ~(NS(Yar,3) | NS(Yar,7) | NS(Yar,11) | NS(Yar,13)) .* (mod(Yar,2)==0); + Ynw = smooth3(cat_vol_morph(NS(Yar,5) | NS(Yar,9) | NS(Yar,15) | NS(Yar,23),'d',2) | ... + (cat_vol_morph(Yppi==1,'e',2) & Ymr>1.7/3 & Ymr<2.5/3) & (mod(Yar,2)==0)); + case {'lc'}, Ymr = Ymr .* (Yar>0) .* NS(Yar,3) .* (mod(Yar,2)==1); + case {'rc'}, Ymr = Ymr .* (Yar>0) .* NS(Yar,3) .* (mod(Yar,2)==0); + end + % clear Yar; + %% + Yppis = Yppi .* (1-Ynw) + max(0,min(1,Ymr*3-2)) .* Ynw; % adding real WM map + Ywdt = cat_vol_eidist(1-Yppis,ones(size(Yppis),'single')); % estimate distance map to central/WM surface + Ywdt = cat_vol_pbtp(max(2,4-Ymfs),Ywdt,inf(size(Ywdt),'single'))*opt.interpV; + [D,I] = cat_vbdist(single(Ywdt>0.01),Yppis>0); Ywdt = Ywdt(I); clear D I Yppis; % add further values around the cortex + Ywdt = cat_vol_median3(Ywdt,Ywdt>0.01,Ywdt>0.01); + Ywdt = cat_vol_localstat(Ywdt,Ywdt>0.1,1,1); % smoothing + Ywdt = cat_vol_resize(Ywdt,'deinterp',resI); % back to original resolution + Ywdt = cat_vol_resize(Ywdt,'dereduceBrain',BB); % adding background + Ywd = max(Ywd,Ywdt); + clear Ywdt; + + %% sulcus width / CSF depth + % for the CSF depth we cannot use the origal data, because of + % sulcal blurring, but we got the PP map at half distance and + % correct later for half thickness + fprintf('%5.0fs\n',etime(clock,stime)); + stime = cat_io_cmd(' CSF depth estimation'); + YM = single(smooth3(cat_vol_morph(Ymr<0.1,'o',4))<0.5); YM(YM==0)=nan; % smooth CSF/background-skull boundary + Yppis = Yppi .* ((Ymr+0.25)>Yppi) + min(1,Ymr*3-1) .* ((Ymr+0.25)<=Yppi); % we want also CSF within the ventricle (for tests) + Ycdt = cat_vol_eidist(Yppis,YM); % distance to the cental/CSF-GM boundary + Ycdt = cat_vol_pbtp(max(2,Ymfs),Ycdt,inf(size(Ycdt),'single'))*opt.interpV; Ycdt(isnan(Ycdt))=0; + [D,I] = cat_vbdist(single(Ycdt>0),Yppis>0 & Yppis<3); Ycdt = Ycdt(I); clear D I Yppis; % add further values around the cortex + Ycdt = cat_vol_median3(Ycdt,Ycdt>0.01,Ycdt>0.01); % median filtering + Ycdt = cat_vol_localstat(Ycdt,Ycdt>0.1,1,1); % smoothing + Ycdt = cat_vol_resize(Ycdt,'deinterp',resI); % back to original resolution + Ycdt = cat_vol_resize(Ycdt,'dereduceBrain',BB); % adding background + Ycd = max(Ycd,Ycdt); + clear Ycdt; + %fprintf('%5.0fs\n',etime(clock,stime)); + clear Ymr; + end + + if debug, Yppio=Yppi; end + if ~useprior, fprintf('%5.0fs\n',etime(clock,stime)); end + + %% Replace isolated voxels and holes in Ypp by its median value + + % indicate isolated holes and replace by median of the neighbors + Yppi(Yppi<0.35 & ~cat_vol_morph(Yppi<1,'l'))=1; % close major wholes in the WM + Ymsk = Yppi==0 & cat_vol_morph(Yppi>0.9,'d',1); % filter small wholes close to the WM + Yppi = cat_vol_median3(single(Yppi),Ymsk,~Ymsk); + + %% indicate isolated objects and replace by median of the neighbors + Yppi(Yppi>0.65 & cat_vol_morph(Yppi==0,'l'))=0; + Ymsk = Yppi>0.95 & cat_vol_morph(Yppi<0.1,'d',1); + Yppi = cat_vol_median3(single(Yppi),Ymsk,~Ymsk); + if ~debug, clear Ymsk; end + + %% Write Ypp for final deformation + % Write Yppi file with 1 mm resolution for the final deformation, + % because CAT_DeformSurf achieved better results using that resolution + Yppt = cat_vol_resize(Yppi,'deinterp',resI); % back to original resolution + Yppt = cat_vol_resize(Yppt,'dereduceBrain',BB); % adding of background + + % scale Yppt so that backgrounds remains 0 and WM 1, but cortical band is + % now in the range of 0.1..0.9 + Vpp = cat_io_writenii(V,Yppt,'',sprintf('%s.pp',opt.surf{si}),'percentage position map','uint8',[0,1/255],[1 0 0 0]); + Vpp1 = Vpp; + Vpp1.fname = fullfile(pp0,mrifolder,sprintf('%s.pp1%s.nii',opt.surf{si},ff)); + vmat2 = spm_imatrix(Vpp1.mat); + Vpp1.dim(1:3) = round(Vpp1.dim .* abs(vmat2(7:9)*(1 + iscerebellum))); % use double resolution in case of cerebellum + vmat2(7:9) = sign(vmat2(7:9)).*[1 1 1]/(1 + iscerebellum); % use double resolution in case of cerebellum + Vpp1.mat = spm_matrix(vmat2); + + Vpp1 = spm_create_vol(Vpp1); + for x3 = 1:Vpp1.dim(3), + M = inv(spm_matrix([0 0 -x3 0 0 0 1 1 1]) * inv(Vpp1.mat) * Vpp.mat); %#ok + v = spm_slice_vol(Vpp,M,Vpp1.dim(1:2),1); + Vpp1 = spm_write_plane(Vpp1,v,x3); + end; + clear M v x3; + + vmatBBV = spm_imatrix(V.mat); + + % surface coordinate transformations that are used in the ""saveCS"" and ""loadCS"" functions + mati = spm_imatrix(V.mat); + vmat = V.mat(1:3,:)*[0 1 0 0; 1 0 0 0; 0 0 1 0; 0 0 0 1]; + vmati = inv([vmat; 0 0 0 1]); vmati(4,:) = []; + + %% transformation matrix + matIBB = spm_imatrix(V.mat * [eye(4,3) [ (BB.BB([1,3,5])' - 1) ; 1]]); + matIBB(7:9) = sign( mati(7:9)) .* repmat( opt.interpV , 1 , 3); + Smat.matlabi_mm = V.mat * [0 1 0 0; 1 0 0 0; 0 0 1 0; 0 0 0 1]; + Smat.matlabIBB_mm = spm_matrix(matIBB) * [0 1 0 0; 1 0 0 0; 0 0 1 0; 0 0 0 1]; % .* mati(7:9)' + + % skip that part if a prior image is defined + if ~useprior + + %% surface coordinate transformations + if opt.verb>2 + stime = clock; cat_io_cprintf('g5',sprintf(' Create topology opt. surface ')); + else + stime = cat_io_cmd(' Create initial surface','g5','',opt.verb); %if opt.verb>2, fprintf('\n'); end + end + + % smooth mask to have smooth border + if ~iscerebellum + mask_parahipp_smoothed = zeros(size(mask_parahipp)); + spm_smooth(double(mask_parahipp),mask_parahipp_smoothed,[8 8 8]); + end + + % parameter for isosurface of Yppi + th_initial = 0.5; + + ind0 = find(Yppi<=0); + Yppisc = opt.scale_cortex*Yppi; + + if ~iscerebellum + Yppisc = Yppisc + opt.add_parahipp/opt.scale_cortex*mask_parahipp_smoothed; + end + Yppisc(ind0) = 0; + clear ind0; + + % optionally apply closing inside mask for parahippocampal gyrus to get rid of the holes that lead to large cuts in gyri + % after topology correction + if opt.close_parahipp && ~iscerebellum + tmp = cat_vol_morph(Yppisc,'labclose',1); + Yppisc(mask_parahipp) = tmp(mask_parahipp); + end + + if opt.reduceCS>0 + % apply voxel-based topology correction only for smaller defects < 30 voxel + [tmp,CS] = cat_vol_genus0opt(Yppisc,th_initial,15 * (1-iscerebellum),debug); + + % correction for the boundary box used within the surface creation process + CS = cat_surf_fun('smat',CS,Smat.matlabIBB_mm); % translate to mm coordinates + [Yvxdef,defect_number0] = spm_bwlabel( double(abs(tmp - (Yppisc>0.5))>0) ); clear tmp + else + % if no mesh reduction is selected use lower-scaled Yppt with original voxel size + Yppt = cat_vol_resize(Yppisc,'deinterp',resI); % back to original resolution + Yppt = cat_vol_resize(Yppt,'dereduceBrain',BB); % adding of background + + % apply voxel-based topology correction only for smaller defects < 30 voxel + [tmp,CS] = cat_vol_genus0opt(Yppt,th_initial,15 * (1-iscerebellum),debug); + CS = cat_surf_fun('smat',CS,Smat.matlabi_mm); % translate to mm coordinates + [Yvxdef,defect_number0] = spm_bwlabel( double(abs(tmp - (Yppt>0.5))>0) ); clear tmp + end + EC0 = size(CS.vertices,1) + size(CS.faces,1) - size(spm_mesh_edges(CS),1); + vdefects = cat_surf_fun('isocolors',Yvxdef,CS.vertices)>0; clear Yvxdef; + defect_size0 = sum(vdefects > 0) / length(vdefects) * 100; % percent + defect_area0 = sum(vdefects > 0) / length(vdefects) .* ... + sum(cat_surf_fun('area',CS)) / opt.interpV / 100; % cm2 + if opt.verb>2 + cat_io_cprintf('g5',sprintf('( SC/EC/DN/DS = %0.1f/',opt.scale_cortex)); + cat_io_cprintf( color( rate( abs( EC0 - 2 ) , 0 ,100 * (1+4*iscerebellum) )) ,sprintf('%d/',EC0)); + cat_io_cprintf( color( rate( defect_number0 , 0 ,100 * (1+4*iscerebellum) )) ,sprintf('%d/',defect_number0)); + cat_io_cprintf( color( rate( defect_size0 , 1 , 10 * (1+4*iscerebellum) )) ,sprintf('%0.2f%%%%' ,defect_size0)); + cat_io_cprintf('g5',' )'); + fprintf(repmat(' ',1,max(0,14 - numel(sprintf('%d/%d/%0.2f. )',EC0,defect_number0,defect_size0))))); + end + clear Yppisc; + + if opt.verb>2 + fprintf(txt); + fprintf('%s %4.0fs\n',repmat(' ',1,66),etime(clock,stime)); + end + + + % correct the number of vertices depending on the number of major objects + if opt.reduceCS>0 + CS = reducepatch(CS,opt.reduceCS * scale_cerebellum); % adaptation for cerebellum + if opt.verb>2 + stime = cat_io_cmd(sprintf(' Reduce surface to %d faces:',size(CS.faces,1)),'g5','',opt.verb); + elseif opt.verb>0 + stime = cat_io_cmd(sprintf(' Reduce surface to %d faces:',size(CS.faces,1)),'g5','',opt.verb,stime); + end + end + save(gifti(struct('faces',CS.faces,'vertices',CS.vertices)),Praw,'Base64Binary'); + + if opt.reduceCS>0 + % after reducepatch many triangles have very large area which causes isses for resampling + % RefineMesh adds triangles in those areas + cmd = sprintf('CAT_RefineMesh ""%s"" ""%s"" %0.2f 0',Praw,Praw,2 * opt.vdist / scale_cerebellum); % adaptation for cerebellum + cat_system(cmd,opt.verb-2); + + % remove some unconnected meshes + cmd = sprintf('CAT_SeparatePolygon ""%s"" ""%s"" -1',Praw,Praw); % CAT_SeparatePolygon works here + cat_system(cmd,opt.verb-2); + end + + % spherical surface mapping 1 of the uncorrected surface for topology correction + cmd = sprintf('CAT_Surf2Sphere ""%s"" ""%s"" 5',Praw,Psphere0); + cat_system(cmd,opt.verb-2); + + % estimate size of topology defects + cmd = sprintf('CAT_MarkDefects ""%s"" ""%s"" ""%s""',Praw,Psphere0,Pdefects0); + cat_system(cmd,opt.verb-2); + try + sdefects = cat_io_FreeSurfer('read_surf_data',Pdefects0); delete(Pdefects0); + catch + sdefects = NaN; + end + defect_number0 = defect_number0 + ceil( max(sdefects )); + defect_size0 = defect_size0 + sum(sdefects > 0) / length(sdefects) * 100; % percent + defect_area0 = defect_area0 + sum(sdefects > 0) / length(sdefects) .* ... + sum(cat_surf_fun('area',CS)) / opt.interpV / 100; clear defects; % cm2 + % estimate Euler characteristic: EC = #vertices + #faces - #edges + EC0 = (EC0-2) + ( size(CS.vertices,1) + size(CS.faces,1) - size(spm_mesh_edges(CS),1) - 2) + 2; + EC = EC + abs(EC0 - 2) + 2; % -2 is the correction for the sphere + defect_size = defect_size + defect_size0; + defect_area = defect_area + defect_area0; + defect_number = defect_number + defect_number0; + + %% topology correction and surface refinement + stime = cat_io_cmd(' Topology correction and surface refinement:','g5','',opt.verb,stime); + if opt.verb>2, fprintf('\n'); end + cmd = sprintf('CAT_FixTopology -lim 128 -bw 512 -n 81920 -refine_length %g ""%s"" ""%s"" ""%s""',2 * opt.vdist / scale_cerebellum,Praw,Psphere0,Pcentral); + cat_system(cmd,opt.verb-2); + + % read final surface and map thickness data + CS = gifti(Pcentral); + % ignore this warning writing gifti with int32 (eg. cat_surf_createCS:580 > gifti/subsref:45) + warning off MATLAB:subscripting:noSubscriptsSpecified + facevertexcdata = cat_surf_fun('isocolors',Yth1i,CS,Smat.matlabIBB_mm); + cat_io_FreeSurfer('write_surf_data',Ppbt,facevertexcdata); + + % final correction of central surface in highly folded areas with high mean curvature with weight of 0.7 + %stime = cat_io_cmd(' Correction of central surface in highly folded areas','g5','',opt.verb,stime); + cmd = sprintf(['CAT_Central2Pial -equivolume -weight 0.7 ""%s"" ""%s"" ""%s"" 0.2'], ... + Pcentral,Ppbt,Pcentral); + cat_system(cmd,opt.verb-2); + + % we need some refinement because some vertices are too large to be deformed with high accuracy + cmd = sprintf('CAT_RefineMesh ""%s"" ""%s"" %0.2f 1',Pcentral,Pcentral,2 * opt.vdist / scale_cerebellum); % adaptation for cerebellum + cat_system(cmd,opt.verb-2); + end + + % surface refinement by surface deformation based on the PP map + %stime = cat_io_cmd(' Refine central surface','g5','',opt.verb,stime); + th = 0.5; + cmd = sprintf(['CAT_DeformSurf ""%s"" none 0 0 0 ""%s"" ""%s"" none 0 1 -1 .1 ' ... + 'avg -0.1 0.1 .2 .1 5 0 ""%g"" ""%g"" n 0 0 0 150 0.01 0.0 %d'], ... + Vpp.fname,Pcentral,Pcentral,th,th,force_no_selfintersections); + cat_system(cmd,opt.verb-2); + + % skip that part if a prior image is defined + if ~useprior + % need some more refinement because some vertices are distorted after CAT_DeformSurf + cmd = sprintf('CAT_RefineMesh ""%s"" ""%s"" %0.2f 1',Pcentral,Pcentral,1.6 * opt.vdist / scale_cerebellum); % adaptation for cerebellum + cat_system(cmd,opt.verb-2); + end + + cmd = sprintf(['CAT_DeformSurf ""%s"" none 0 0 0 ""%s"" ""%s"" none 0 1 -1 .2 ' ... + 'avg -0.15 0.15 .1 .1 5 0 ""%g"" ""%g"" n 0 0 0 150 0.01 0.0 %d'], ... + Vpp.fname,Pcentral,Pcentral,th,th,force_no_selfintersections); + cat_system(cmd,opt.verb-2); + + % read final surface and map thickness data + CS = gifti(Pcentral); + % ignore this warning writing gifti with int32 (eg. cat_surf_createCS:580 > gifti/subsref:45) + warning off MATLAB:subscripting:noSubscriptsSpecified + facevertexcdata = cat_surf_fun('isocolors',Yth1i,CS,Smat.matlabIBB_mm); + cat_io_FreeSurfer('write_surf_data',Ppbt,facevertexcdata); + + % final correction of central surface in highly folded areas with high mean curvature + cmd = sprintf('CAT_BlurSurfHK ""%s"" ""%s"" 1', Pcentral,Pcentral); + cat_system(cmd,opt.verb-2); + cmd = sprintf('CAT_Central2Pial -equivolume -weight 0.4 ""%s"" ""%s"" ""%s"" 0', ... + Pcentral,Ppbt,Pcentral); + cat_system(cmd,opt.verb-2); + + if opt.SRP + + %% Collision correction by Delaunay triangularization + % -------------------------------------------------------------------- + % New self-intersection correction that uses different detections of + % self-intersections (SIDs; RY vs. PBT) with/without further optimization. + % It does not fully avoid self-intersections because some are already + % in the CS and some other required strong changes that result in worse + % thickness results. + + if opt.SRP == 1 + stime = cat_io_cmd(' Reduction of surface collisions:','g5','',opt.verb,stime); + else + stime = cat_io_cmd(' Reduction of surface collisions with optimization:','g5','',opt.verb,stime); + end + verblc = 0; % verbose level + if debug, if exist('CSO','var'), CS = CSO; facevertexcdata = facevertexcdatao; else, CSO = CS; facevertexcdatao = facevertexcdata; end; stime2 = clock; else, stime2 = []; end + if debug, saveSurf(CS,Pcentral); cat_io_FreeSurfer('write_surf_data',Ppbt,facevertexcdata); tic; end + + % call collision correction + [CS,facevertexcdata] = cat_surf_fun('collisionCorrectionPBT',CS,facevertexcdata,Ymfs,Yppi,struct('optimize',opt.SRP==2,'verb',verblc,'mat',Smat.matlabIBB_mm,'CS4',0)); + if verblc, fprintf('\b\b'); end + if strcmpi(spm_check_version,'octave') + cat_io_addwarning('cat_surf_createCS2:nofullSRP','Fine correction of surface collisions is not yet available under Octave.',2) + else + [CS,facevertexcdata] = cat_surf_fun('collisionCorrectionRY' ,CS,facevertexcdata,Ymfs,struct('Pcs',Pcentral,'verb',verblc,'mat',Smat.matlabIBB_mm,'accuracy',1/2^3)); + end + if debug, toc; end + + % evaluate and save results + if verblc, cat_io_cmd(' ','g5','',opt.verb); end + fprintf('%5.0fs',etime(clock,min([stime2;stime],[],1))); if ~debug, stime = []; end + saveSurf(CS,Pcentral); cat_io_FreeSurfer('write_surf_data',Ppbt,facevertexcdata); + % final result ... test for self-intersections only in developer mode? + if debug % opt.surf_measures > 2 || opt.verb > 2 + cat_surf_fun('saveico',CS,facevertexcdata,Pcentral,sprintf('createCS_3_collcorr_%0.2fmm_vdist%0.2fmm',opt.interpV,opt.vdist),Ymfs,Smat.matlabIBB_mm); + fprintf('\n'); + res.(opt.surf{si}).createCS_3_collcorr = cat_surf_fun('evalCS' ,CS,facevertexcdata,[],Ymfs,Yppi,Pcentral,Smat.matlabIBB_mm,opt.verb-1,cat_get_defaults('extopts.expertgui')>1); + res.(opt.surf{si}).createCS_final = res.(opt.surf{si}).createCS_3_collcorr; + else + fprintf('\n'); + end + + if ~debug, clear CSO; end + end + + %% just a shortcut for manual tests + writedebug = 0; %cat_get_defaults('extopts.expertgui')==2; + % intensity based evaluation + CS = gifti(Pcentral); + % ignore this warning writing gifti with int32 (eg. cat_surf_createCS:580 > gifti/subsref:45) + warning off MATLAB:subscripting:noSubscriptsSpecified + if writedebug + if opt.SRP + facevertexcdata1 = cat_io_FreeSurfer('read_surf_data',Ppbt); + else + facevertexcdata1 = cat_surf_fun('isocolors',Yth1i,CS,Smat.matlabIBB_mm); + end + fprintf('%5.0fs',etime(clock,stime)); + cat_surf_fun('saveico',CS,facevertexcdata1,Pcentral,saveiconame,Ymfs); + res.(opt.surf{si}).createCS_final = cat_surf_fun('evalCS',CS,facevertexcdata1,[],Ymfs,Yppi,Pcentral,Smat.matlabIBB_mm,opt.verb-2,cat_get_defaults('extopts.expertgui')>1); + end + + % skip that part if a prior image is defined + if ~useprior + %% spherical surface mapping 2 of corrected surface + stime = cat_io_cmd(' Spherical mapping with areal smoothing','g5','',opt.verb,stime); + cmd = sprintf('CAT_Surf2Sphere ""%s"" ""%s"" 10',Pcentral,Psphere); + cat_system(cmd,opt.verb-2); + + % spherical registration to fsaverage template + stime = cat_io_cmd(' Spherical registration','g5','',opt.verb,stime); + cmd = sprintf('CAT_WarpSurf -steps 2 -avg -i ""%s"" -is ""%s"" -t ""%s"" -ts ""%s"" -ws ""%s""', ... + Pcentral,Psphere,Pfsavg,Pfsavgsph,Pspherereg); + cat_system(cmd,opt.verb-2); + end + + % set thickness values to zero for masked area (use inverse transformation to map mask) + % does not work properly for all data... + if 0 + stime = cat_io_cmd(' Correct thickness','g5','',opt.verb,stime); + cmd = sprintf('CAT_ResampleSurf ""%s"" ""%s"" ""%s"" ""%s"" ""%s"" ""%s""', ... + Pfsavg,Pfsavgsph,Pspherereg,Ptemp,Pfsavgmask,Pmask); + cat_system(cmd,opt.verb-2); + resampled_mask = cat_io_FreeSurfer('read_surf_data',Pmask); + + % set thickness to 0 for masked area and write thickness data + facevertexcdata(resampled_mask < 0.5) = 0; + cat_io_FreeSurfer('write_surf_data',Ppbt,facevertexcdata); + delete(Pmask) + delete(Ptemp); + end + + % map WM and CSF width data (corrected by thickness) + if opt.WMT > 1 + %% + facevertexcdata2 = cat_surf_fun('isocolors',Ywd,CS,Smat.matlabi_mm); + facevertexcdata2c = max(eps,facevertexcdata2 - facevertexcdata/2); + cat_io_FreeSurfer('write_surf_data',Pgwo,facevertexcdata2c); % gyrus width WM only + facevertexcdata2c = correctWMdepth(CS,facevertexcdata2c,100,0.2); + cat_io_FreeSurfer('write_surf_data',Pgww,facevertexcdata2c); % gyrus width WM only + facevertexcdata3c = facevertexcdata2c + facevertexcdata; % ); + cat_io_FreeSurfer('write_surf_data',Pgw,facevertexcdata3c); % gyrus width (WM and GM) + facevertexcdata4 = estimateWMdepthgradient(CS,facevertexcdata2c); + cat_io_FreeSurfer('write_surf_data',Pgwwg,facevertexcdata4); % gyrus width WM only > gradient + % smooth resampled values + try + cmd = sprintf('CAT_BlurSurfHK ""%s"" ""%s"" ""%g"" ""%s""',Pcentral,Pgwwg,3,Pgwwg); + cat_system(cmd,opt.verb-2); + end + %% + %clear facevertexcdata2 facevertexcdata2c facevertexcdata3c facevertexcdata4; + % just a test ... problem with other species ... + %norm = sum(Ymf(:)>0.5) / prod(vx_vol) / 1000 / 1400; + %norm = mean([2 1 1].*diff([min(CS.vertices);max(CS.vertices)])); + %norm = mean([2 1 1].*std(CS.vertices)); % maybe the hull surface is better... + + facevertexcdata3 = cat_surf_fun('isocolors',Ycd,CS,Smat.matlabi_mm); + facevertexcdata3 = max(eps,facevertexcdata3 - facevertexcdata/2); + cat_io_FreeSurfer('write_surf_data',Psw,facevertexcdata3); + end + if ~useprior, fprintf('%5.0fs\n',etime(clock,stime)); end + + if 0 %opt.verb>1 && ~useprior + cat_io_cprintf( 'g5', sprintf(' Euler number / defect number / defect size: ')); + cat_io_cprintf( color( rate( EC0 - 2 , 0 , 2 * 50 * (1+9*iscerebellum)) ) , sprintf('%0.0f / ' , EC0 ) ); + cat_io_cprintf( color( rate( defect_number0 , 0 , 2 * 50 * (1+9*iscerebellum)) ) , sprintf('%0.0f / ' , defect_number0 ) ); + cat_io_cprintf( color( rate( defect_size0 , 0 , 2 * 5 * (1+9*iscerebellum)) ) , sprintf('%0.2f%%%% ' , defect_size0 ) ); + fprintf('\n'); + end + + if 0 %writedebug + % This part is not highly relevant for the individual surface reconstruction + % but it can help to test and optimize the spatial registration. + + % filenames for resampling + Presamp = fullfile(pp_surffolder,sprintf('%s.tmp.resampled.%s' ,opt.surf{si},ff)); + Ppbtr = fullfile(pp_surffolder,sprintf('%s.pbt.resampled.%s' ,opt.surf{si},ff)); + Ppbtr_gii = [Ppbtr '.gii']; + + % resample values using warped sphere + cmd = sprintf('CAT_ResampleSurf ""%s"" ""%s"" ""%s"" ""%s"" ""%s"" ""%s""',Pcentral,Pspherereg,Pfsavgsph,Presamp,Ppbt,Ppbtr); + cat_system(cmd,opt.verb-2); + + if 0 + % resample surface using warped sphere with better surface quality (using Spherical harmonics) + % ### + % deactivated because the resampling of the surface alone leads to displacements of the textures (RD20190927)! + % ### + cmd = sprintf('CAT_ResampleSphericalSurfSPH -n 327680 ""%s"" ""%s"" ""%s""',Pcentral,Pspherereg,Presamp); + cat_system(cmd,opt.verb-2); + + % resample surface according to freesurfer sphere + cmd = sprintf('CAT_ResampleSurf ""%s"" NULL ""%s"" ""%s""',Presamp,Pfsavgsph,Presamp); + cat_system(cmd,opt.verb-2); + end + + % add values to resampled surf and save as gifti + cmd = sprintf('CAT_AddValuesToSurf ""%s"" ""%s"" ""%s""',Presamp,Ppbtr,Ppbtr_gii); + cat_system(cmd,opt.verb-2); + if exist(Ppbtr,'file'), delete(Ppbtr); end + + % remove path from metadata to allow that files can be moved (pathname is fixed in metadata) + [pp2,ff2,ex2] = spm_fileparts(Ppbtr_gii); + g = gifti(Ppbtr_gii); + g.private.metadata = struct('name','SurfaceID','value',[ff2 ex2]); + save(g, Ppbtr_gii, 'Base64Binary'); + + % intensity based evaluation + CS1 = gifti(Ppbtr_gii); + CSr = struct('vertices',CS1.vertices,'faces',CS1.faces,'cdata',CS1.cdata,'vmat',vmat,'mati',mati); + CSr.vertices = (vmati*[CSr.vertices' ; ones(1,size(CSr.vertices,1))])'; + if mati(7)<0, CSr.faces = [CSr.faces(:,1) CSr.faces(:,3) CSr.faces(:,2)]; end + warning off MATLAB:subscripting:noSubscriptsSpecified + cat_surf_fun('saveico',CSr,CSr.cdata,Pcentralr,[saveiconame '_resampled']); + res.(opt.surf{si}).createCS_resampled = cat_surf_fun('evalCS',CSr,CSr.cdata,[],Ymfs,Yppi,Pcentralr); + clear CSr CS1 + end + %clear Yppi; + + % visualize a side + % csp=patch(CS); view(3), camlight, lighting phong, axis equal off; set(csp,'facecolor','interp','edgecolor','none') + + + % estimate Freesurfer thickness measure Tfs using mean(Tnear1,Tnear2) + if opt.thick_measure == 1 + % not ready yet + if 0 +% if opt.extract_pial_white % use white and pial surfaces + cmd = sprintf('CAT_SurfDistance -mean ""%s"" ""%s"" ""%s""',Pwhite,Ppial,Pthick); + cat_system(cmd,opt.verb-2); + else % use central surface and thickness + cmd = sprintf('CAT_SurfDistance -mean -thickness ""%s"" ""%s"" ""%s""',Ppbt,Pcentral,Pthick); + cat_system(cmd,opt.verb-2); + end + + % apply upper thickness limit + facevertexcdata = cat_io_FreeSurfer('read_surf_data',Pthick); + facevertexcdata(facevertexcdata > opt.thick_limit) = opt.thick_limit; + cat_io_FreeSurfer('write_surf_data',Pthick,facevertexcdata); + + res.(opt.surf{si}).createCS_final = cat_surf_fun('evalCS',CS,cat_io_FreeSurfer('read_surf_data',Ppbt),cat_io_FreeSurfer('read_surf_data',Pthick),Ymfs,Yppi,Pcentral,Smat.matlabIBB_mm,debug,cat_get_defaults('extopts.expertgui')>1); + else % otherwise simply copy ?h.pbt.* to ?h.thickness.* + copyfile(Ppbt,Pthick,'f'); + res.(opt.surf{si}).createCS_final = cat_surf_fun('evalCS',CS,cat_io_FreeSurfer('read_surf_data',Pthick),[],Ymfs,Yppi,Pcentral,Smat.matlabIBB_mm,debug,cat_get_defaults('extopts.expertgui')>1); + end + + fprintf('\n'); + + % create output structure + warning off MATLAB:subscripting:noSubscriptsSpecified + S.(opt.surf{si}) = struct('faces',CS.faces,'vertices',CS.vertices,'th1',facevertexcdata); + if opt.WMT > 1 + S.(opt.surf{si}) = setfield(S.(opt.surf{si}),'th2',facevertexcdata2); + S.(opt.surf{si}) = setfield(S.(opt.surf{si}),'th3',facevertexcdata3); + end + clear Yth1i + + %% average final values + FNres = fieldnames( res.(opt.surf{si}).createCS_final ); + for fnr = 1:numel(FNres) + if ~isfield(res,'final') || ~isfield(res.final,FNres{fnr}) + res.final.(FNres{fnr}) = res.(opt.surf{si}).createCS_final.(FNres{fnr}) / numel(opt.surf); + else + res.final.(FNres{fnr}) = res.final.(FNres{fnr}) + res.(opt.surf{si}).createCS_final.(FNres{fnr}) / numel(opt.surf); + end + end + if isfield(res.(opt.surf{si}),'createCS_resampled') + FNres = fieldnames( res.(opt.surf{si}).createCS_resampled ); + for fnr = 1:numel(FNres) + if ~isfield(res,'createCS_resampled') || ~isfield(res.createCS_resampled,FNres{fnr}) + res.resampled.(FNres{fnr}) = res.(opt.surf{si}).createCS_resampled.(FNres{fnr}) / numel(opt.surf); + else + res.resampled.(FNres{fnr}) = res.resampled.(FNres{fnr}) + res.(opt.surf{si}).createCS_resampled.(FNres{fnr}) / numel(opt.surf); + end + end + end + + + % we have to delete the original faces, because they have a different number of vertices after + % CAT_FixTopology! + if ~useprior + delete(Praw); + if opt.verb > 2 + delete(Pdefects0); + end + delete(Psphere0); + end + if ~debug + delete(Vpp.fname); + delete(Vpp1.fname); + end + clear CS + + % create white and central surfaces + if cat_get_defaults('extopts.expertgui') == 2 + cat_surf_fun('white',Pcentral); + cat_surf_fun('pial',Pcentral); + end + end + + % calculate mean EC and defect size for all surfaces + mnth = []; sdth = []; mnRMSE_Ypp = []; mnRMSE_Ym = []; sdRMSE_Ym = []; sdRMSE_Ypp = []; + SIw = []; SIp = []; SIwa = []; SIpa = []; + for si=1:numel(opt.surf) + if any(strcmp(opt.surf{si},{'lh','rh'})) + if isfield(res.(opt.surf{si}).createCS_final,'fsthickness_mn_sd_md_mx') + mnth = [ mnth res.(opt.surf{si}).createCS_final.fsthickness_mn_sd_md_mx(1) ]; + sdth = [ sdth res.(opt.surf{si}).createCS_final.fsthickness_mn_sd_md_mx(2) ]; + else + mnth = [ mnth res.(opt.surf{si}).createCS_final.thickness_mn_sd_md_mx(1) ]; + sdth = [ sdth res.(opt.surf{si}).createCS_final.thickness_mn_sd_md_mx(2) ]; + end + mnRMSE_Ym = [ mnRMSE_Ym mean([... + res.(opt.surf{si}).createCS_final.RMSE_Ym_layer4 ... + res.(opt.surf{si}).createCS_final.RMSE_Ym_white ... + res.(opt.surf{si}).createCS_final.RMSE_Ym_pial ]) ]; + sdRMSE_Ym = [ sdRMSE_Ym std([... + res.(opt.surf{si}).createCS_final.RMSE_Ym_layer4 ... + res.(opt.surf{si}).createCS_final.RMSE_Ym_white ... + res.(opt.surf{si}).createCS_final.RMSE_Ym_pial ]) ]; + mnRMSE_Ypp = [ mnRMSE_Ypp mean([... + res.(opt.surf{si}).createCS_final.RMSE_Ypp_central ... + res.(opt.surf{si}).createCS_final.RMSE_Ypp_white ... + res.(opt.surf{si}).createCS_final.RMSE_Ypp_pial ]) ]; + sdRMSE_Ypp = [ sdRMSE_Ypp std([... + res.(opt.surf{si}).createCS_final.RMSE_Ypp_central ... + res.(opt.surf{si}).createCS_final.RMSE_Ypp_white ... + res.(opt.surf{si}).createCS_final.RMSE_Ypp_pial ]) ]; + if isfield(res.(opt.surf{si}).createCS_final,'white_self_interections') + SIw = [ SIw res.(opt.surf{si}).createCS_final.white_self_interections ]; + SIp = [ SIp res.(opt.surf{si}).createCS_final.pial_self_interections ]; + SIwa = [ SIwa res.(opt.surf{si}).createCS_final.white_self_interection_area ]; + SIpa = [ SIpa res.(opt.surf{si}).createCS_final.pial_self_interection_area ]; + end + end + end + + % skip that part if a prior image is defined + if ~useprior + EC = EC / numel(opt.surf); + defect_area = defect_area / numel(opt.surf); + defect_size = defect_size / numel(opt.surf); + defect_number = defect_number / numel(opt.surf); + else % obtain surface information from xml report file + [pp0,ff0] = spm_fileparts(priorname); %#ok + catxml = fullfile(pp0,reportfolder,['cat_' ff0 '.xml']); + xml = cat_io_xml(catxml); + EC = xml.qualitymeasures.SurfaceEulerNumber; + defect_size = xml.subjectmeasures.defect_size; + defect_area = xml.qualitymeasures.SurfaceDefectArea; + defects = xml.qualitymeasures.SurfaceDefectNumber; + end + + % final res structure + res.Smat = Smat; + res.EC = EC; + res.defect_size = defect_size; + res.defect_area = defect_area; + res.defects = defect_number; + res.RMSE_Ym = mean(mnRMSE_Ym); + res.RMSE_Ypp = mean(mnRMSE_Ypp); + if isfield(res.(opt.surf{si}).createCS_final,'white_self_interections') + res.self_intersections = mean([SIw,SIp]); + res.self_intersections_area = mean([SIwa,SIpa]); + end + + % create white and central surfaces + if cat_get_defaults('extopts.expertgui') + cat_surf_fun('white',Pcentral); + cat_surf_fun('pial',Pcentral); + end + + if opt.verb && ~opt.vol + % display some evaluation + % - For normal use we limited the surface measures. + % - Surface intensity would be interesting as cortical measure similar to thickness (also age dependent). + % Especially the outer surface will describe the sulcal blurring in childeren. + % But the mixing of surface quality and anatomical features is problematic. + % - The position value describes how good the tranformation of the PBT map into a surface worked. + % Also the position values depend on age. Children have worste pial values due to sulcal blurring but + % the white surface is may effected by aging, e.g. by WMHs. + % - However, for both intensity and position some (average) maps would be also interesting. + % Especially, some Kappa similar measure that describes the differences to the Ym or Ypp would be nice. + % - What does the Euler charateristic say? Wouldn't the defect number more useful for users? + if any(~cellfun('isempty',strfind(opt.surf,'cb'))), cbtxt = 'cerebral '; else cbtxt = ''; end + fprintf('Final %ssurface processing results: \n', cbtxt); + + if cat_get_defaults('extopts.expertgui') + % color output currently only for expert ... + if isfield(res.(opt.surf{si}).createCS_final,'fsthickness_mn_sd_md_mx') + fprintf(' Average thickness (FS): '); + else + fprintf(' Average thickness (PBT): '); + end + cat_io_cprintf( color( rate( abs( mean(mnth) - 2.5 ) , 0 , 2.0 )) , sprintf('%0.4f' , mean(mnth) ) ); fprintf(' %s ',native2unicode(177, 'latin1')); + cat_io_cprintf( color( rate( abs( mean(sdth) - 0.5 ) , 0 , 1.0 )) , sprintf('%0.4f mm\n', mean(sdth) ) ); + + fprintf(' Surface intensity / position RMSE: '); + cat_io_cprintf( color( rate( mean(mnRMSE_Ym) , 0.05 , 0.3 ) ) , sprintf('%0.4f / ', mean(mnRMSE_Ym) ) ); + cat_io_cprintf( color( rate( mean(mnRMSE_Ypp) , 0.05 , 0.3 ) ) , sprintf('%0.4f\n', mean(mnRMSE_Ypp) ) ); + + if isfield(res.(opt.surf{si}).createCS_final,'white_self_interections') + fprintf(' Pial/white self-intersections: '); + cat_io_cprintf( color( rate( mean([SIw,SIp]) , 0 , 20 ) ) , sprintf('%0.2f%%%% (%0.2f mm%s)\n' , mean([SIw,SIp]) , mean([SIwa,SIpa]) , char(178) ) ); + end + + fprintf(' Euler number / defect number / defect size: '); + cat_io_cprintf( color( rate( EC - 2 , 0 , 100 * (1+9*iscerebellum)) ) , sprintf('%0.1f / ' , EC ) ); + cat_io_cprintf( color( rate( defect_number , 0 , 100 * (1+9*iscerebellum)) ) , sprintf('%0.1f / ' , defect_number ) ); + cat_io_cprintf( color( rate( defect_size , 0 , 10 * (1+9*iscerebellum)) ) , sprintf('%0.2f%%%% ' , defect_size ) ); + fprintf('\n'); + else + fprintf(' Average thickness: %0.4f %s %0.4f mm\n' , mean(mnth), native2unicode(177, 'latin1'), mean(sdth)); + fprintf(' Euler characteristic / defect size: %0d / %0.2f%%%% \n' , EC, defect_size); + end + + for si=1:numel(Psurf) + fprintf(' Display thickness: %s\n',spm_file(Psurf(si).Pthick,'link','cat_surf_display(''%s'')')); + end + + % surfaces in spm_orthview + if exist(Pm,'file'), Po = Pm; else, Po = V0.fname; end + + Porthfiles = '{'; Porthcolor = '{'; Porthnames = '{'; + for si=1:numel(Psurf) + Porthfiles = [ Porthfiles , sprintf('''%s'',''%s'',',Psurf(si).Ppial, Psurf(si).Pwhite )]; + Porthcolor = [ Porthcolor , '''-g'',''-r'',' ]; + Porthnames = [ Porthnames , '''white'',''pial'',' ]; + end + Porthfiles = [ Porthfiles(1:end-1) '}']; + Porthcolor = [ Porthcolor(1:end-1) '}']; + Porthnames = [ Porthnames(1:end-1) '}']; + + fprintf(' Show in orthview: %s\n',spm_file(Po ,'link',... + sprintf('cat_surf_fun(''show_orthview'',%s,''%s'',%s,%s)',Porthfiles,Po,Porthcolor,Porthnames))) ; + end +end + +%======================================================================= +function varargout = cat_vol_genus0opt(Yo,th,limit,debug) +% cat_vol_genus0opt: Voxel-based topology optimization and surface creation +% The correction of large defects is often not optimal and this function +% uses only small corrections. +% +% [Yc,S] = cat_vol_genus0vol(Yo[,limit,debug]) +% +% Yc .. corrected volume +% Yo .. original volume +% S .. surface +% th .. threshold for creating surface +% limit .. maximum number of voxels to correct a defect (default = 30) +% debug .. print details. +% + + if nargin < 2, th = 0.5; end + if nargin < 3, limit = 30; end + if nargin < 4, debug = 0; end + + Yc = Yo; nooptimization = limit==0; %#ok + if limit==0 + % use all corrections + if nargout>1 + txt = evalc(sprintf('[Yc,S.faces,S.vertices] = cat_vol_genus0(Yo,th,nooptimization);')); + else + txt = evalc(sprintf('Yc = cat_vol_genus0(Yo,th,nooptimization);')); + end + + if debug, fprintf(txt); end + else + % use only some corrections + txt = evalc(sprintf('Yc = cat_vol_genus0(Yo,th,nooptimization);')); + + % remove larger corrections + Yvxcorr = abs(Yc - (Yo > th))>0; + Yvxdef = spm_bwlabel( double( Yvxcorr ) ); clear Yppiscrc; + Yvxdef = cat_vol_morph(Yvxdef,'l',[inf limit]) > 0; % large corrections that we remove + + if debug + fprintf(txt); + fprintf(' Number of voxels of genus-topocorr: %d\n Finally used corrections: %0.2f%%\n', ... + sum(Yvxcorr(:)) , 100 * sum(Yvxcorr(:) & ~Yvxdef(:)) / sum(Yvxcorr(:)) ); + end + + Yc = Yc & ~Yvxdef; + + % final surface creation without correction + if nargout>1 + evalc(sprintf('[Yt,S.faces,S.vertices] = cat_vol_genus0( single(Yc) ,th,1);')); + end + + end + + varargout{1} = Yc; + if nargout>1, varargout{2} = S; end +end + +%======================================================================= +function [cdata,i] = correctWMdepth(CS,cdata,iter,lengthfactor) +% ______________________________________________________________________ +% Correct deep WM depth values that does not fit to the local thickness +% of the local gyri. +% +% lengthfactor should be between 0.2 and 0.4 +% ______________________________________________________________________ + + if ~exist('lengthfactor','var'), lengthfactor = 1/3; end + if ~exist('iter','var'), iter = 100; end + + %% + SV = CS.vertices; % Surface Vertices + SE = unique([CS.faces(:,1:2);CS.faces(:,2:3);CS.faces(:,3:-2:1)],'rows'); % Surface Edges + SEv = single(diff(cat(3,SV(SE(:,1),:),SV(SE(:,2),:)),1,3)); % Surface Edge Vector + SEL = sum(SEv.^2,2).^0.5; % Surface Edge Length + clear SEv + + + %% + i=0; cdatac = cdata+1; pc = 1; oc = 0; + while i0.05 ); + i=i+1; cdatac = cdata; + + M = (cdatac(SE(:,1)) - SEL(SE(:,1))*lengthfactor ) > cdatac(SE(:,2)); + cdata(SE(M,1)) = cdatac(SE(M,2)) + SEL(SE(M,1))*lengthfactor; + M = (cdata(SE(:,2)) - SEL(SE(:,2))*lengthfactor ) > cdatac(SE(:,1)); + cdata(SE(M,2)) = cdatac(SE(M,1)) + SEL(SE(M,1))*lengthfactor; + oc = sum( abs(cdata - cdatac)>0.05 ); + + %fprintf('%d - %8.2f - %d\n',i,sum( abs(cdata - cdatac)>0.05 ),pc~=oc) + + end + +end + +%======================================================================= +function saveSurf(CS,P) + save(gifti(struct('faces',CS.faces,'vertices',CS.vertices)),P,'Base64Binary'); +end + +%======================================================================= +function CS1 = loadSurf(P) + CS = gifti(P); + CS1.vertices = CS.vertices; CS1.faces = CS.faces; + if isfield(CS,'cdata'), CS1.cdata = CS.cdata; end +end + +%======================================================================= +function cdata = estimateWMdepthgradient(CS,cdata) +% ______________________________________________________________________ +% Estimates the maximum local gradient of a surface. +% Major use is the WM depth that grows with increasing sulcal depth. +% It measures the amount of WM behind the cortex, but more relevant is +% the amount of WM fibers that this region will add to the WM depth. +% The width of the street next to a house gives not the connectivity of +% this house, but the width of the entrance does! +% This measure can be improved by furhter information of sulcal depth. +% ______________________________________________________________________ + + %% + SV = CS.vertices; % Surface Vertices + SE = unique([CS.faces(:,1:2);CS.faces(:,2:3);CS.faces(:,3:-2:1)],'rows'); % Surface Edges + SEv = single(diff(cat(3,SV(SE(:,1),:),SV(SE(:,2),:)),1,3)); % Surface Edge Vector + SEL = sum(SEv.^2,2).^0.5; % Surface Edge Length + clear SEv + + + %% + cdata_l = inf(size(cdata),'single'); + cdata_h = zeros(size(cdata),'single'); + for i=1:size(SE,1) + val = (cdata(SE(i,2)) - cdata(SE(i,1)))*SEL(SE(i,1)); + cdata_l(SE(i,1)) = min([cdata_l(SE(i,1)),val]); + cdata_h(SE(i,1)) = max([cdata_h(SE(i,2)),val]); + end + cdata = cdata_h - cdata_l; +end + +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_main_updateWMHs.m",".m","3514","107","function Ycls = cat_main_updateWMHs(Ym,Ycls,Yy,tpm,job,res,trans) +% ______________________________________________________________________ +% Handle WMHs in the segmentation. +% +% Ycls = cat_main_updateWMHs(Ym,Ycls,Yy,job,trans) +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + % update WMHs? + if numel(Ycls)>6 + if isfield(trans,'warped') + %% load template + VwmA = spm_vol([job.extopts.templates{end},',2']); + + if any( VwmA.dim ~= trans.warped.odim ) + % interpolation + yn = numel(trans.warped.y); + p = ones([4,yn/3],'single'); + p(1,:) = trans.warped.y(1:yn/3); + p(2,:) = trans.warped.y(yn/3+1:yn/3*2); + p(3,:) = trans.warped.y(yn/3*2+1:yn); + amat = VwmA.mat \ trans.warped.M1; + p = amat(1:3,:) * p; + + Yy = zeros([res.image(1).dim(1:3),3],'single'); + Yy(1:yn/3) = p(1,:); + Yy(yn/3+1:yn/3*2) = p(2,:); + Yy(yn/3*2+1:yn) = p(3,:); + + Yy = double(Yy); + else + Yy = double(trans.warped.y); + end + YwmA = single( spm_sample_vol( VwmA ,Yy(:,:,:,1),Yy(:,:,:,2),Yy(:,:,:,3),1)); YwmA = reshape(YwmA,size(Ym)); + elseif isfield(trans,'atlas') + %% load template + VwmA = spm_vol([job.extopts.templates{end},',2']); + + if any( VwmA.dim ~= size(Yy(:,:,:,1)) ) + % interpolation + yn = numel(trans.atlas.Yy); + p = ones([4,yn/3],'single'); + p(1,:) = trans.atlas.Yy(1:yn/3); + p(2,:) = trans.atlas.Yy(yn/3+1:yn/3*2); + p(3,:) = trans.atlas.Yy(yn/3*2+1:yn); + amat = VwmA.mat \ tpm.M; + p = amat(1:3,:) * p; + + Yy = zeros([res.image(1).dim(1:3),3],'single'); + Yy(1:yn/3) = p(1,:); + Yy(yn/3+1:yn/3*2) = p(2,:); + Yy(yn/3*2+1:yn) = p(3,:); + + Yy = double(Yy); + else + Yy = double(trans.warped.y); + end + YwmA = single( spm_sample_vol( VwmA ,Yy(:,:,:,1),Yy(:,:,:,2),Yy(:,:,:,3),1)); YwmA = reshape(YwmA,size(Ym)); + else + %% load template + VwmA = spm_vol([job.extopts.templates{end},',2']); + + if any( VwmA.dim ~= size(Yy(:,:,:,1)) ) + % interpolation + yn = numel(Yy); + p = ones([4,yn/3],'single'); + p(1,:) = Yy(1:yn/3); + p(2,:) = Yy(yn/3+1:yn/3*2); + p(3,:) = Yy(yn/3*2+1:yn); + amat = VwmA.mat \ tpm.M; + p = amat(1:3,:) * p; + + Yy = zeros([res.image(1).dim(1:3),3],'single'); + Yy(1:yn/3) = p(1,:); + Yy(yn/3+1:yn/3*2) = p(2,:); + Yy(yn/3*2+1:yn) = p(3,:); + + Yy = double(Yy); + else + Yy = double(Yy); + end + YwmA = single( spm_sample_vol( VwmA ,Yy(:,:,:,1),Yy(:,:,:,2),Yy(:,:,:,3),1)); YwmA = reshape(YwmA,size(Ym)); + end + + % transfer tissue from GM to WMH class + Yclst = cat_vol_ctype( single(Ycls{7} ) .* YwmA ); + Ycls{2} = Ycls{2} + (Ycls{7} - Yclst); + Ycls{7} = Yclst; + + end + + if numel(Ycls)>6 && ~isempty(Ycls{7}) + if job.extopts.WMHC<2 + Ycls{1} = Ycls{1} + Ycls{7}; % WMH as GM + elseif job.extopts.WMHC==2 + Ycls{2} = Ycls{2} + Ycls{7}; % WMH as WM + elseif job.extopts.WMHC>=3 + Ycls{2} = Ycls{2} + Ycls{7}; % WMH as own class + end + end +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_get_defaults.m",".m","2860","87","function varargout = cat_get_defaults(defstr, varargin) +% Get/set the defaults values associated with an identifier +% FORMAT defval = cat_get_defaults(defstr) +% Return the defaults value associated with identifier ""defstr"". +% Currently, this is a '.' subscript reference into the global +% ""defaults"" variable defined in spm_defaults.m. +% +% FORMAT cat_get_defaults(defstr, defval) +% Sets the cat value associated with identifier ""defstr"". The new +% cat value applies immediately to: +% * new modules in batch jobs +% * modules in batch jobs that have not been saved yet +% This value will not be saved for future sessions of SPM. To make +% persistent changes, edit cat_defaults.m. +% +% FORMAT cat_get_defaults(defstr, 'rmfield') +% Removes last field of defstr eg. defstr = 'opts.sopt.myfield' will remove +% 'myfield'. +% +% FORMAT cat_get_defaults(defstr, 'rmentry') +% Removes last field of defstr eg. defstr = 'opts.sopt.myfield' will remove +% 'sopt' with all all subfield. +%__________________________________________________________________________ +% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging + +% based on Volkmar Glauches version of +% spm_get_defaults +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +global cat; +if isempty(cat) + cat_defaults; +end + +if nargin == 0 + varargout{1} = cat; + return +end + +% construct subscript reference struct from dot delimited tag string +tags = textscan(defstr,'%s', 'delimiter','.'); +subs = struct('type','.','subs',tags{1}'); + +if nargin == 1 + % default output + try + varargout{1} = subsref(cat, subs); + catch + varargout{1} = []; + end + return; +elseif nargin == 2 + if iscell( varargin{1} ) + % add an new entry + cat = subsasgn(cat, subs, varargin{1}); + else + switch varargin{1} + case 'rmfield' + % remove the last field of the given defstr + mainfield = tags{1}{1}; + for ti=2:numel(tags{1})-1 + mainfield = [mainfield '.' tags{1}{ti}]; %#ok + end + subfield = tags{1}{end}; + %fprintf('Remove field ""%s"" in ""cat.%s""!\n',subfield,mainfield); + eval(sprintf('cat.%s = rmfield(cat.%s,subfield);',mainfield,mainfield)); + case 'rmentry' + % removes the complete entry of the given defstr + %fprintf('Remove entry ""%s"" ""cat""!\n',tags{1}{1}); + cat = rmfield(cat,defstr); + otherwise + % add an new entry + cat = subsasgn(cat, subs, varargin{1}); + end + end +end +if nargout == 1 + % output in case changes in cat + varargout{1} = cat; +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_main_LAS.m",".m","39785","906","function [Yml,Ymg,Ycls,Ycls2,T3th] = ... + cat_main_LAS(Ysrc,Ycls,Ym,Yb0,Yy,T3th,res,vx_vol,extopts,Tth) +% This is an exclusive subfunction of cat_main. +% ______________________________________________________________________ +% +% Local Adaptive Segmentation (LAS): +% +% This version of the local adaptive intensity correction includes a +% bias correction that is based on a maximum filter for the WM, a mean +% filter of GM and a mean filter of the head tissue (if available).m +% For each tissue a refined logical map is generated to filter the local +% tissue intensity and approximate the local tissue intensity in the whole +% volume. Based on these values an intensity transformation is used. +% Compared to the global correction this has to be done for each voxel. +% To save time only a rough linear transformation is used. Finally, a +% second NLM-filter is used. +% It is important to avoid high intensity blood vessels in the process +% because they will push down local WM and GM intensity. +% +% ______________________________________________________________________ +% +% [Yml,Ymg,Ycls,Ycls2,T3th] = ... +% cat_main_LAS(Ysrc,Ycls,Ym,Yb0,Yy,T3th,res,vx_vol,extopts,Tth) +% +% Yml .. local intensity normalized image +% Ymg .. global intensity normalized image +% Ycls .. corrected SPM tissue class map +% Ycls2 .. ? +% T3th .. tissue thresholds of CSF, GM, and WM in Ysrc +% +% Ysrc .. (bias corrected) T1 image +% Ycls .. SPM tissue class map +% Ym .. intensity corrected T1 image (BG=0,CSF=1/3,GM=2/3,WM=1) +% Yb0 .. brain mask +% Yy .. deformation map +% T3th .. intensity thresholds from global intensity normalization +% res .. SPM segmentation structure +% vx_vol .. voxel dimensions +% extopts .. +% Tth .. +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + + +% ______________________________________________________________________ +% +% internal maps: +% +% Yg .. gradient map - edges between tissues +% Ydiv .. divergence map - sulci/gyri pattern, and blood vessels +% Yp0 .. label map - tissue classes (BG=0,CSF=1,GM=2,WM=3) +% +% Ysw .. save WM tissue map +% Ybv .. blood vessel map +% Ycp .. CSF / background area for distances estimation +% Ycd .. CSF / background distance map +% Ywd .. WM distance map +% +% Ycm .. CSF +% Ygm .. GM +% Ywm .. WM +% Yvt .. WM next to the ventricle map +% ______________________________________________________________________ +% +% Development / TODO: +% * replace old calls of cat_vol_morph by distance based operations with +% resolution parameter +% ______________________________________________________________________ + + + + % The reduction to 1 mm is not really good for the Ycls map. If this + % is required to support faster and memory saving preprocessing also + % for ultra-high resolution data further test are necessary! + %def.uhrlim = 0.7; + %extopts = cat_io_checkinopt(extopts,def); + extopts.uhrlim = 0.2; % no reduction for >0.4 mm + + + % set this variable to 1 for simpler debugging without reduceBrain + % function (that normally save half of processing time) + verb = extopts.verb - 1; + vxv = 1 / mean(vx_vol); % normalization of voxel size (mostly for old calls of cat_vol_morph) + dsize = size(Ysrc); + NS = @(Ys,s) Ys==s | Ys==s+1; % function to ignore brain hemisphere coding + LASstr = max(eps,min(1,extopts.LASstr)); % LAS strength (for GM/WM threshold) - manual correction based on R1109 (2017/02) + LAB = extopts.LAB; % atlas labels + LABl1 = 1; % use atlas map + cleanupstr = min(1,max(0,extopts.gcutstr)); % required to avoid critical regions (only used in case of atlas maps) + cleanupdist = min(3,max(1,1 + 2*cleanupstr)); + + + % set debug = 1 and do not clear temporary variables if there is a breakpoint in this file + dbs = dbstatus; debug = 0; + for dbsi = 1:numel(dbs), if strcmp(dbs(dbsi).name,'cat_main_LAS'); debug = 1; break; end; end + + + + +%% --------------------------------------------------------------------- +% First, we have to optimize the segments using further information that +% SPM do not use, such as the gradient, divergence and distance maps. +% (1) The gradient map (average of the first derivate of the T1 map) is +% an edge map and independent of the image intensity. It helps to +% avoid PVE regions and meninges. +% (2) The divergence (second derivate of the T1 map) help to identify +% sulcal and gyral pattern and therefore to find WM and CSF regions +% for further corrections and to avoid meninges and blood vessels. +% (3) Distance maps can help to describe the cortex by its expected +% thickness or to separate structures close to the skull or deep +% in the brain. +% +% Furthermore, special assumption can be used. +% The first is that the maximum property of the WM in T1 data that +% allows using of a maxim filter for the GM/WM region. +% The second is the relative stable estimation of CSF/BG that allows to +% estimate a distance map. Because, most regions have a thin layer of +% GM around the WM, we can avoid overestimation of the WM by the other +% maps (especially the divergence). +% --------------------------------------------------------------------- + + fprintf('\n'); + stime = cat_io_cmd(' Prepare maps','g5','',verb); + + + % general resolution limitation + % ------------------------------------------------------------------- + % Using a lot of maps make this function memory intensive that is + % critical for high resolution data. Furthermore, it can be expected + % that the full resolution is not required here. However, reducing + % the tissue class map can lead to other problems. Hence, the uhrlim + % parameter is maybe inactive (see above). + % ------------------------------------------------------------------- + if any( vx_vol < extopts.uhrlim/2 ) + % store old data that is needed in full resolution + Yclso2 = Ycls; + Ysrco2 = Ysrc; + + % reduce all input maps (Ysrc, Ycls, Yy, Ym, Yb0) + [Ysrc,resT0] = cat_vol_resize( Ysrc , 'reduceV' , vx_vol , extopts.uhrlim , 64 ); + for ci = 1:numel(Ycls) + Ycls{ci} = cat_vol_resize( Ycls{ci}, 'reduceV' , vx_vol , extopts.uhrlim , 64 ); + end + Yy2 = ones([size(Ysrc),4],'single'); + for ci = 1:numel(Yy) + Yy2(:,:,:,ci) = cat_vol_resize( Yy(:,:,:,ci) , 'reduceV' , vx_vol , extopts.uhrlim , 64 ); + end + Yy = Yy2; clear Yy2; + Ym = cat_vol_resize( Ym , 'reduceV' , vx_vol , extopts.uhrlim , 64 ); + Yb0 = cat_vol_resize( single(Yb0) , 'reduceV' , vx_vol , extopts.uhrlim , 64 )>0.5; + + vx_vol = resT0.vx_volr; + vxv = 1/ mean(resT0.vx_volr); + dsize = size(Ysrc); + end + + + % brain bounding box to save processing time + Yclso = Ycls; + [Ym,BB] = cat_vol_resize( Ym , 'reduceBrain' , vx_vol , round(10/mean(vx_vol)) , Yb0 ); + Yb = cat_vol_resize( Yb0 , 'reduceBrain' , vx_vol , round(10/mean(vx_vol)) , Yb0 ); clear Yb0; + + try + for i = 1:numel(Ycls), Ycls{i} = cat_vol_resize(Ycls{i} , 'reduceBrain' , vx_vol , BB.BB); end + catch + error('LAS failed probably due to bad tissue contrast.\n'); + end + + % helping maps (Yg = mean gradient = edge) and divergence (CSF or WM skeleton) + Yg = cat_vol_grad( Ym , vx_vol ); + Ydiv = cat_vol_div( max(0.33,Ym) , vx_vol ); + Yp0 = single( Ycls{1} )/255*2 + single( Ycls{2} )/255*3 + single( Ycls{3} )/255; % create label map + Yb = smooth3( Yb | cat_vol_morph(Yb,'d',2*vxv) & Ym<0.8 & Yg<0.3 & Ym>0 )>0.5; % increase brain mask, for missing GM + + + + + %% adding of atlas and template information (for subcortical structures) + % ------------------------------------------------------------------- +%%% 20180801 - Why not use the partitioning before LAS to benefit by the + % better ventricle, WMH and cerebellum maps? + % - Because the partitioning benefit in subcortical regions + % from LAS. >> call it twice? + % ------------------------------------------------------------------- + if LABl1 + stime = cat_io_cmd(' Prepare partitions','g5','',verb,stime); + + % map atlas to RAW space + for i=1:5 + try + Vl1A = spm_vol(extopts.cat12atlas{1}); + break + catch + % avoid read error in parallel processing + pause(rand(1)) + end + end + Yl1 = cat_vol_ctype( cat_vol_sample(res.tpm(1),Vl1A,Yy,0) ); + + + % load WM of the Dartel/Shooting Template for WMHs - use uint8 to save memory + % Ywtpm .. WM template map + Vtemplate = spm_vol(extopts.templates{end}); + Ywtpm = cat_vol_ctype( cat_vol_sample(res.tpm(1),Vtemplate(2),Yy,1) * 255,'uint8'); + if debug==0, clear Yy; end + Ywtpm = single(reshape(Ywtpm,dsize)); + spm_smooth(Ywtpm,Ywtpm,2*vxv); + Ywtpm = cat_vol_ctype(Ywtpm); + + + % apply boundary box for brain mask + Yl1 = cat_vol_resize(Yl1 ,'reduceBrain',vx_vol,round(4/mean(vx_vol)),BB.BB); + Ywtpm = cat_vol_resize(Ywtpm,'reduceBrain',vx_vol,round(4/mean(vx_vol)),BB.BB); + % The correction of image resolution is not required because of the adaptation of the Yy? + + + % do not reduce LASstr + LASmod = min(2,max(1,mean((Ym( NS(Yl1,LAB.BG) & Yg<0.1 & Ydiv>-0.05 & Ycls{1}>4)) - 2/3) * 8)); + else + LASmod = 1; %#ok + end + + + % adaptation of the LASstr depending on average basal values + LASstr = min(1,max(0.01,LASstr * LASmod)); % adaptation by local BG variation + LASfs = 1 / max(0.01,LASstr); % smoothing filter strength + LASi = min(8,round(LASfs)); % smoothing iteration (limited) + + + + + %% helping segments + % ------------------------------------------------------------------- + % We will now try to identify the CSF and WM regions those finally + % describe the GM area. + % * brain mask (Ybb), blood vessel maps (Ybv), + % * distance maps from CSF (Ycd), WM (Ywd), and brain mask (Ybd) + % * tissue maps for CSF (Ycp >> Ycm), GM (Ygm), and WM (Ysw >> Ywm) + % * ventricle map (Yvt) + % ------------------------------------------------------------------- + stime = cat_io_cmd(sprintf(' Prepare segments (LASmod = %0.2f)',LASmod),'g5','',verb,stime); + + % Ybb .. brain mask + % Don't trust SPM too much by using Yp0 because it may miss some GM areas! + % 20180801 - The brain mask should be correct now. + Ybb = cat_vol_morph((Yb & Ym>1.5/3 & Ydiv<0.05) | Yp0>1.5,'lo',vxv); + if debug==0, clear Yb; end + + + % Ysw .. save WM + % Ybv .. possible blood vessels + Ysw1 = cat_vol_morph(Ycls{2}>128 & (min(1,Ym)-Ydiv)<1.5,'lc',vxv*2) & (Ym - Ydiv)>5/6; + Ybv = ((min(1,Ym) - Ydiv + Yg)>2.0 | (Ycls{5}>16 & Ym<0.6 & Ycls{1}<192)) & ... + ~cat_vol_morph(Ysw1,'d',1) & Ym>0.2; + + + % Ycp = mask for CSF/BG distance initialization + Ycp1 = Ycls{3}>240 & Ydiv>0 & Yp0<1.1 & Ym<0.5 ; % typical CSF + Ycp2 = Ycls{5}>8 & Ycls{2}<32 & Ym<0.6 & Ydiv>0; % venes + Ycp3 = (Ym-Ydiv/4<0.4) & Ycls{3}>4 & Ycls{3}>16; % sulcal CSF + Ycp4 = (single(Ycls{6}) + single(Ycls{4}))>192; % non-CSF .. class 5 with error for negative t1 values + Ycp5 = ~cat_vol_morph(Ybb,'lc',5); % add background + Ycp6 = Ym<0.3; % but do not trust the brain mask! + Ycp = Ycp1 | Ycp2 | Ycp3 | Ycp4 | Ycp5 | Ycp6; % combine maps + Ycp(smooth3(Ycp)>0.4) = 1; % remove some meninges + if debug==0; clear Ycp1 Ycp2 Ycp3 Ycp4 Ycp5 Ycp6; end + + + % Ywd .. WM distance map + % Ysk .. divergence skeleton to improve CSF map + % deactivated due to problems in non-cortical structures + Ywd = cat_vbdist(single(Yp0>2.5),Yp0>0.5,vx_vol); % WM distance for skeleton + %Ysk = cat_vol_div(min(5,Ywd),2); % divergence skeleton + %Ysk = (Ym + min(0,Ysk))<0.2; % binary divergence skeleton + %Ycp = Ycp | Ysk; if debug==0, clear Ysk; end % combine skeleton with CSF map + + % Ycd .. CSF/BG distance map + Ycd = cat_vbdist(single(Ycp),~Ycp,vx_vol); % real CSF distance + Ycd((Ym-Ydiv<2/3 | Ydiv>0.1) & Ycls{3}>4 & Ycls{3}>1) = ... % correction for sulci + min(Ycd((Ym-Ydiv<2/3 | Ydiv>0.1) & Ycls{3}>4 & Ycls{3}>1),1.5); % ... maybe another distance estimation? + + + % we need to remove strong edge regions, because here is no GM layer between CSF and WM ??? + % Yb .. brain mask + % Ybd .. skull distance +%%% 20180801 - What is the difference of Yb2 to Ybb and the (previously replaced) Yb? + Yb2 = cat_vol_morph(~Ycp | (Ycls{3}>128),'lc',1); + Ybd = cat_vbdist(single(~Yb2),Yb2,vx_vol); + + + % Yvt .. Ventricle map WITHOUT atlas data as large deep CSF areas + % need the ventricle to avoid PVE GM between WM and CSF. + % There is an update for atlas data. + Yvt = (Yg + abs(Ydiv))>0.4 & smooth3(single(Ycls{1})/255)<0.5 & Ybd>20 & ... + cat_vol_morph(Ycls{3}>8,'d',vxv) & cat_vol_morph(Ycls{2}>8,'d',vxv); + Yvt = smooth3(Yvt)>0.7; + Yvt = smooth3(Yvt)>0.2; + + + + + %% final tissue maps: Ycm = CSF, Ygm = GM, Ywm = WM + % ------------------------------------------------------------------- + + % CSF: + Ycm = Ycp & Yb2 & Ycls{3}>192 & ~Ybv & Ym<0.45 & Yg<0.25 & Ym>0 ; + %Ycm = Ycm | (Yb2 & (Ym - max(0,Ydiv))<0.5); % adding of divergence information was not save + if debug==0, clear Ycp; end + + + %% WM: + % Different definitions of the possible WM (Ysw,Ysw2,Ysw3,Ysw4) + % and a variable (Ygw) to avoid non WM areas. + % Ysw1 .. defined above + % Ysw2 .. addition WM map that further include CSF distance (Ycd) and + % divergence information (Ydiv) and use a flexible intensity + % Ysw3 .. similar to Ysw2 with a skull-near and CSF distance criteria + % to reconstruct WM gyri + % Ysw4 .. was removed long ago + % Ygw .. map to of regions that we want to avoid in all possible WM + % definitions Ysw* + Ysw2 = Yb2 & (Ycd - Ydiv)>2 & Ydiv<0 & Ym>(0.9 + LASstr * 0.05); % general WM + Ysw3 = Yb2 & (Ycd - Ydiv .* Ycd)>4 & Ydiv<-0.01 & Ym>0.5 & Ybd<20 & Ycd>2; % addition WM gyri close to the cortex + %Ysw4 = ( (Ycd - Ydiv*5)>3 & Yb2 & Ym>0.4 & Ybd<20 & Ycd>2.5) & ... % further WM (rmoved long ago) + % (Ydiv<-0.01 & (Yg + max(0,0.05 - Ycd/100))<0.1 ); + + Ygw = ~Ybv & Yb2 & Ybd>1 & (Ycd>1.0 | (Yvt & Yp0>2.9)) & ... + (Yg + Ydiv<(Ybd/50) | (Ydiv - Ym)<-1); + + Ywm = ( Ycls{2}>252 | Ysw1 | Ysw2 | Ysw3 ) & Ygw; + if debug==0, clear Ysw Ysw2 Ysw3 Ygw; end + + + %% GM: + % Different criteria (Ygm1,Ygm2,Ygm3) to define the possible GM area + % whereas Ygm4 describe general GM limitation. + % Ygm1 .. upper intensity limitation + % Ygm2 .. lower intensity limitation + % Ygm3 .. avoid GM next to hard boundaries in the middle of the brain + Ygm1 = ( Ym - Ydiv - max(0,2 - Ycd)/10 )<0.9; % upper limit + Ygm2 = Ycls{1}>4 | ( Ym>0.7 & Ycls{3}>64 ) | Ycd<(Ym + Ydiv)*3; % lower limit + Ygm3 = smooth3(Yg>(Ybd/800) & Ycls{2}<240 )>0.6; % avoid GM-WM PVE + Ygm = Ybb & ~Yvt & ~Ybv & ~Ywm & ~Ycm & Ycd>0.5 & Ygm1 & Ygm2 & Ygm3; + if debug==0, clear Ybv Yvt Ygm1 Ygm2 Ygm3; end + + % Ygm4 .. general GM limitations + Ygm4 = Ybb & ~Ycm & ~Ywm & Ym>1/3 & Ym<2.8/3 & ... + Yg<0.4 & (Ym - Ydiv)>1/3 & (Ym - Ydiv)<1; + Ygm4( smooth3(Ygm4)<0.5 ) = 0; % remove small dots + + % combine possible area with limitation map + Ygm = Ygm | Ygm4; + if debug==0, clear Ygm4; end + Ygm = Ygm | (Ym>1.5/3 & Ym<2.8/3 & ~Ywm & ~Ycm & Ybb); + Ygm(smooth3(Ygm)<0.25) = 0; + if debug==0, clear Ybv Ycp; end + + + + + + %% further maps that require the atlas + if LABl1 + % SPM GM segmentation can be affected by inhomogeneities and some GM + % areas are miss-classified as CSF/GM (Ycls{5}) when the affine + % registration was not optimal. But for some regions we can trust + % these information. + + + + %% regions for cleanup of meninges and blood vessels + % Ycbp .. close to the cerebellum + % Ycbn .. not to deep in the cerebellum + % Ylhp / Yrhp .. GM next to the left/right hemisphere + % Ybv2 .. close to the skull and between the hemispheres or between cerebrum and cerebellum + % Ybvv .. sinus + Ycbp = cat_vbdist(single( NS(Yl1,LAB.CB)),Yb2,vx_vol); % close to cerebellum + Ycbn = cat_vbdist(single(~NS(Yl1,LAB.CB)),Yb2,vx_vol); % close to cerebellum surface + Ylhp = cat_vbdist(single(mod(Yl1,2)==1 & Yb2 & Yl1>0),Yb2,vx_vol); % GM next to the left hemisphere + Yrhp = cat_vbdist(single(mod(Yl1,2)==0 & Yb2 & Yl1>0),Yb2,vx_vol); % GM next to the right hemisphere + Ybv2 = Ycls{5}>2 & Ym<0.7 & Ym>0.3 & Yb2 & (... + ((Ylhp+Ybd/2)0.5; + Ybvv = (Ym - max(0,6 - abs(Ycbp - 6))/50)<0.6 & Ym>0.4 & Yb2 & Ycbp<8 & Ycbp>1; % sinus + if debug==0, clear Ycbp; end + + + + %% refinements of subcortical regions + % Thalamus (TH): + % YTH .. enlarged atlas ROI + % Ytd .. CSF distance in the thalamus YTH + % Yxd .. distance to the basal-ganglia (BGL) in the thalamus YTH + THth = 0.8 - LASstr*0.6; %0.5; % lower more thalamus + YTH = NS(Yl1,LAB.TH) | (cat_vol_morph(NS(Yl1,LAB.TH),'d',3) & Ym>0.5 & Ycls{1}>128); + Ytd = cat_vbdist(single(Ym<0.45),YTH | NS(Yl1,LAB.BG),vx_vol); Ytd(Ytd>2^16)=0; % CSF distance in the TH + Yxd = cat_vbdist(single(NS(Yl1,LAB.BG)),YTH,vx_vol); Yxd(Yxd>2^16)=0; % BGL distance in the TH + if debug==0, clear YTH; end + + + % Yss .. (enlarged) subcortical structures + % Ynw .. no WM ?? + Yss = NS(Yl1,LAB.BG) | NS(Yl1,LAB.TH); + Yss = Yss | (cat_vol_morph(Yss,'d',vxv*2) & Ym>2.25/3 & Ym<2.75/3 & Ydiv>-0.01); % add higher tissue around mask + Yss = Yss | (cat_vol_morph(Yss,'d',vxv*3) & NS(Yl1,LAB.VT) & Yp0>1.5 & Yp0<2.3); % add lower tissue around mask + Yss = Yss & Yp0>1.5 & (Yp0<2.75 | (Ym<(2.5 + LASstr * 0.45)/3 & Ydiv>-0.05)); % limit the enlarged map by intensity + Yss = Yss | ((Yxd./max(eps,Ytd + Yxd))>THth/2 & ... % save TH by distances - for overcorrected images + (Yp0<2.75 | (Ym<(2.75 + LASstr * 0.20)/3 & Ydiv>-0.05))); + Yss = cat_vol_morph(Yss,'o'); + + Ynw = (Yxd./max(eps,Ytd + Yxd))>THth/2 | (NS(Yl1,LAB.BG) & Ydiv>-0.01); + if debug==0, clear Ytd Yxd ; end + + + % increase CSF ROI + % Yvt .. improve ventricle ROI with atlas information +%%%%% 20180801 - Why not use the ventricle maps from the partitioning? + % - Because the partitioning is after LAS + % - Why not use a fast partitioning before LAS? + % Why not use the code from the partitioning? + % Is a good ventricle segmentation here not important? + Yvt = cat_vol_morph( (NS(Yl1,LAB.VT) | cat_vol_morph(Ycm,'o',3) ) ... + & Ycm & ~NS(Yl1,LAB.BG) & ~NS(Yl1,LAB.TH) & Ybd>30,'d',vxv*3) & ~Yss; + + + + %% meningeal corrections + % Ycx .. cerebellar and other CSF + % Ycwm .. cerebellar WM + % Yccm .. cerebellar CSF + % Ybwm .. brain WM + % Ybcm .. brain CSF + Ycx = ( NS(Yl1,LAB.CB) & ( (Ym - Ydiv)<0.55 | Ycls{3}>128 ) ) | ... + ( ( (Ym - Ydiv)<0.45 & Ycls{3}>8 ) | Ycls{3}>240 ); + % in the cerebellum tissue can be differentiated by div etc. + Ycwm = NS(Yl1,LAB.CB) & (Ym - Ydiv*4)>5/6 & Ycd>3 & Yg>0.05; + Yccm = NS(Yl1,LAB.CB) & Ydiv>0.02 & Ym<1/2 & Yg>0.05; + Ybwm = (Ym - Ydiv*4)>0.9 & Ycd>3 & Yg>0.05; + Ybcm = Ydiv>0.04 & Ym<0.55 & Yg>0.05; + + + + %% correction 1 of tissue maps + % Ywmtpm .. refined WM template map (original Ywtpm) + Ywmtpm = ( single( Ywtpm )/255 .* Ym .* (1 - Yg - Ydiv) .* ... + cat_vol_morph( NS(Yl1,1) .* Ybd/5 ,'e',1) )>0.6; % no WM hyperintensities in GM! + if debug==0, clear Ywtpm; end + + + % refine the GM map + Ygm = Ygm | (Yss & ~Yvt & ~Ycx & ~Ybv2 & ~Ycwm & ~(Yccm | Ybcm)); + Ygm = Ygm & ~Ywmtpm & ~Ybvv; % no WMH area + + + % refine the WM map + Ywm = Ywm & ~Yss & ~Ybv2 & ~Ynw; + Ywm = Ywm | Ycwm | Ybwm; + Ywmtpm(smooth3(Ywmtpm & Ym<11/12)<0.5) = 0; % 20180801 - Why here? + Ywm = Ywm & ~Ywmtpm & ~Ybvv & ~Yss; % no WM area + + + Ycm = Ycm | ( (Ycx | Yccm | Ybcm) & Yg<0.2 & Ym>0 & Ydiv>-0.05 & Ym<0.3 & Yb2 ) | Ybvv; + if debug==0, clear Ycwm Yccm Ycd Ybvv Ycx; end + + + % Mapping of the brain stem to the WM (well there were some small GM + % structures, but the should not effect the local segmentation to much. + % Ybs .. brain stem mask + Ybs = Ym<1.2 & Ym>0.9 & Yp0>1.5 & ... + cat_vol_morph(NS(Yl1,LAB.BS) & Ym<1.2 & Ym>0.9 & Yp0>2.5,'c',2*vxv); + Ygm = (Ygm & ~Ybs & ~Ybv2 & ~Ywm) | Yss; + Ywm = Ywm | (Ybs & Ym<1.1 & Ym>0.9 & Yp0>1.5) ; + end + + + + + + + + + %% back to original resolution for full bias field estimation + % ------------------------------------------------------------------- + Ycls = Yclso; clear Yclso; + Ycm = cat_vol_resize(Ycm , 'dereduceBrain' , BB); + Ygm = cat_vol_resize(Ygm , 'dereduceBrain' , BB); + Ywm = cat_vol_resize(Ywm , 'dereduceBrain' , BB); + + Yvt = cat_vol_resize(Yvt , 'dereduceBrain' , BB); + Yb2 = cat_vol_resize(Yb2 , 'dereduceBrain' , BB); + Yss = cat_vol_resize(Yss , 'dereduceBrain' , BB); + Ybb = cat_vol_resize(Ybb , 'dereduceBrain' , BB); + Ybs = cat_vol_resize(Ybs , 'dereduceBrain' , BB); + Ybv2 = cat_vol_resize(Ybv2 , 'dereduceBrain' , BB); + + Ym = cat_vol_resize(Ym , 'dereduceBrain' , BB); + Yp0 = cat_vol_resize(Yp0 , 'dereduceBrain' , BB); + Yl1 = cat_vol_resize(Yl1 , 'dereduceBrain' , BB); + Ybd = cat_vol_resize(Ybd , 'dereduceBrain' , BB); + Yg = cat_vol_resize(Yg , 'dereduceBrain' , BB); + Ydiv = cat_vol_resize(Ydiv , 'dereduceBrain' , BB); + Ywd = cat_vol_resize(Ywd , 'dereduceBrain' , BB); + + + % correction for negative values + [Ysrcx,thx] = cat_stat_histth(Ysrc,99); clear Ysrcx; %#ok + srcmin = thx(1); + Ysrc = Ysrc - srcmin; + T3th = T3th - srcmin; + Tthc = Tth; Tthc.T3th = Tth.T3th - srcmin; + if exist('Ysrco2','var'),Ysrco2 = Ysrco2 - srcmin; end + + + + + + + +%% --------------------------------------------------------------------- +% Now, we can estimate the local peaks +% --------------------------------------------------------------------- +% Estimation of the local WM intensity with help of intensity corrected +% GM, CSF and head tissues to avoid overfitting (eg. BWP cerebellum). +% CSF is problematic in high contrast or skull-stripped images and +% should not be used here or in the GM peak estimation. +% --------------------------------------------------------------------- + mres = 1.1; + stime = cat_io_cmd(' Estimate local tissue thresholds (WM)','g5','',verb,stime); + Ysrcm = cat_vol_median3(Ysrc.*Ywm,Ywm,Ywm); + rf = [10^5 10^4]; + T3th3 = max(1,min(10^6,rf(2) / (round(T3th(3)*rf(1))/rf(1)))); + Ysrcm = round(Ysrcm*T3th3)/T3th3; + + + % Ygwg .. large homogen GM regions (e.g. subcortical structures or in the BWP cerebellum) + % Ygwc .. large homogen CSF regions + Ygwg = Ycls{1}>128 & Ym>(2/3 - 0.04) & Ym<(2/3 + 0.04) & Ygm .*Ydiv>0.01; + Ygwg = Ygwg | (Ycls{1}>128 & Yg<0.05 & abs(Ydiv)<0.05 & ~Ywm & Ym<3/4); + Ygwc = Ycls{3}>128 & Yg<0.05 & ~Ywm & ~Ygm & Ywd<3; + Ygwc(smooth3(Ygwc)<0.5) = 0; + if debug==0, clear Ywd; end + + + % also use normalized GM tissues + % Ygi .. tissue-corrected intensity map (normalized for WM) + Ygi = Ysrc .* Ygwg * T3th(3)/mean(Ysrc(Ygwg(:))); + if cat_stat_nanmean(Ym(Ygwc))>0.1 + % use normalized CSF tissue only in images with clear CSF intensity + % (to avoid errors in skull-stripped data) + Ygi = Ygi + Ysrc .* Ygwc * T3th(3)/mean(Ysrc(Ygwc(:))); + end + + + %% limit image resolution for fast processing + [Yi,resT2] = cat_vol_resize( Ysrcm ,'reduceV',vx_vol,mres,32,'max'); % maximum reduction for the WM area + Ygi = cat_vol_resize( Ygi ,'reduceV',vx_vol,mres,32,'meanm'); % mean for other (intensity normalized) tissues + for xi = 1:2*LASi, Ygi = cat_vol_localstat(Ygi,Ygi>0,2,1); end; % intensity smoothing in the GM area + Ygi(smooth3(Ygi>0)<0.3) = 0; % remove small dots (meninges) + Yi = cat_vol_localstat(Yi,Yi>0,1,3); % maximum filtering to stabilize small WM structures + Yi(Yi==0 & Ygi>0) = Ygi(Yi==0 & Ygi>0); % combine the WM and GM map + for xi = 1:2*LASi, Yi = cat_vol_localstat(Yi,Yi>0,2,1); end % intensity smoothing in both regions no maximum here! + + + % Add head tissue if it is available. + if cat_stat_nanmean(Ym(Ygwc))>0.1 && cat_stat_nanmean(Ysrc(Ycls{6}(:)>128))>T3th(1) + try % no skull-stripped + % definion of head tissue + Ygwh = Ycls{6}>128 & ~Ygwc & ~Ygwg & Yg<0.5 & abs(Ydiv)<0.1 & ... + Ysrc>min( res.mn(res.lkp==6) * 0.5 ) & Ysrc ( cat_stat_nanmedian( Ysrc(Ygwh(:)) ) + 2 * cat_stat_nanstd( Ysrc(Ygwh(:)) ) ); + Ygwh( Ygwhn ) = false; clear Ygwhn + %% go to low resolution + [Ygi,resTB] = cat_vol_resize(Ysrc .* Ygwh * T3th(3)/mean(Ysrc(Ygwh(:))),'reduceV',vx_vol,mres,32,'meanm'); + % additional approximation + Ygi = cat_vol_approx(Ygi,'nh',resTB.vx_volr,2); Ygi = cat_vol_smooth3X(Ygi,2 * LASfs); + Ygi = Ygwh .* max(eps,cat_vol_resize(Ygi,'dereduceV',resTB)); + Yi(Yi==0) = Ygi(Yi==0); + if debug==0; clear Ygwh; end + end + end + if debug==0, clear Ygwg Ygwc; end + + + % final approximation of the WM inhomogeneity + Yi = cat_vol_approx(Yi,'nh',resT2.vx_volr,2); + Yi = cat_vol_smooth3X(Yi,2 * LASfs); + Ylab{2} = max(eps,cat_vol_resize(Yi,'dereduceV',resT2)); +% Ylab{2} = Ylab{2} .* mean( [median(Ysrc(Ysw(:))./Ylab{2}(Ysw(:))),1] ); + if debug==0; clear Ysw Yi; end + + + + + + + %% update GM tissue map after the WM bias correction + % -------------------------------------------------------------------- + Ygm(Ysrc./Ylab{2}>(T3th(2) + 0.90 * diff(T3th(2:3)))/T3th(3)) = 0; + Ygm(Ysrc./Ylab{2}<(T3th(2) + 0.75 * diff(T3th(2:3)))/T3th(3) & ... + Ysrc./Ylab{2}<(T3th(2) - 0.75 * diff(T3th(2:3)))/T3th(3) & ... + Ydiv<0.3 & Ydiv>-0.3 & Ybb & ~Ywm & ~Yvt & ~Ybv2 & Ycls{1}>48) = 1; + Ywd2 = cat_vbdist(single(Ywm),Yb2); % update WM distance + Ygmn = (Ywd2 - Ym + Ydiv)>0.5 & ~Ybv2 & ... + (Ym + 0.5 - Ydiv - Yg - Ywd2/10)>1/3 & ... low intensity tissue + ~(Ym - min(0.2,Yg + Ywd2/10 - Ydiv)<1/4) & ... + Yg0.5 & ~Ywm; + Ygmn(smooth3(Ygmn)<0.5) = 0; + Ygm = Ygm | Ygmn; % correct gm (SPM based) + if debug==0; clear Ygm4; end + + + + + + + %% update maps +%%% ... more details + + % Update CSF maps. + % Ycm .. updated CSF map + % Ycp1 .. typical CSF + % Ycp2 .. venes + % Ycp3 .. sulcal CSF + % Ycp4 .. save non-CSF + % Ycp5 .. but do not trust the brain mask! + % Ycpn .. updated CSF 2 map + % Ycd2 .. updated CSF distance + Ycm = Ycm | (Yb2 & (Ysrc./Ylab{2})<((T3th(1)*0.5 + 0.5*T3th(2))/T3th(3))); + Ycm = ~Ygm & ~Ywm & ~Ybv2 & Yg<0.6 & Ycm; + Ycp1 = Ycls{2}<128 & Ydiv>0 & Yp0<2.1 & Ysrc./Ylab{2}32 & Ycls{2}<32 & Ysrc./Ylab{2}0; % venes + Ycp3 = (Ym - Ydiv<0.4) & Ycls{3}>4 & Ycls{3}>16 & Ysrc./Ylab{2}192; % save non-CSF + Ycp5 = Ysrc./Ylab{2}0.4 ) = 1; % remove some meninges + Ycd2 = cat_vbdist(single(Ycpn),~Ycpn,vx_vol); + + + %% update GM map + Ygm = Ygm & ~Ycm & ~Ywm & Ywd2<5; + if debug==0; clear Ywd2; end + Ygm = Ygm | (NS(Yl1,1) & Ybd<20 & (Ycd2 - Ydiv)<2 & ... + Ycls{1}>0 & ~Ycm & Ybb & Ym>0.6 & Yg1.5 | ... + (Ym>1.2/3 & Ym<3.1/3 & Yb2))>0.6,'lo',min(1,vxv)); + if debug==0, clear Yp0 Yvt; end + Ygm(~Ybb) = 0; + Ygm(smooth3(Ygm)<0.3) = 0; + Ygm(smooth3(Ygm)>0.4 & Ysrc./Ylab{2}>mean(T3th(1)/T3th(2)) & ... + Ysrc./Ylab{2}<(T3th(2)*0.2+0.8*T3th(3))) = 1; + if debug==0; clear Ybb Yl1; end + + + + + + %% GM + % .. more details + + % Yi .. main GM intensity map + stime = cat_io_cmd(' Estimate local tissue thresholds (GM)','g5','',verb,stime); + Yi = Ysrc./Ylab{2} .* Ygm; + Yi = round(Yi * rf(2))/rf(2); + Yi(Ybs) = Ysrc(Ybs)./Ylab{2}(Ybs) .* T3th(2)/T3th(3); + if debug==0; clear Ybs; end + Yi = cat_vol_median3(Yi,Yi>0.5,Yi>0.5); % reduce artifacts + + % add CSF and CSF/GM areas (venes) to avoid overfitting + % Ycmx .. venes / sinus + % Tcmx .. intensity correction + Ycmx = smooth3( Ycm & Ysrc<(T3th(1)*0.8 + T3th(2)*0.2) )>0.9; + Tcmx = mean( Ysrc(Ycmx(:)) ./ Ylab{2}(Ycmx(:)) ) * T3th(3); + Yi(Ycmx) = Ysrc(Ycmx)./Ylab{2}(Ycmx) .* T3th(2)/Tcmx; + if debug==0; clear Ycm Ycmx; end + + %% reduce data to lower resolution + Ybgx = Ycls{6}>128; + Ybgxn = Ysrc < ( cat_stat_nanmedian( Ysrc(Ybgx(:)) ) - 2 * cat_stat_nanstd( Ysrc(Ybgx(:)) ) ) | ... + Ysrc > ( cat_stat_nanmedian( Ysrc(Ybgx(:)) ) + 2 * cat_stat_nanstd( Ysrc(Ybgx(:)) ) ); + Ybgx = Ybgx & ~Ybgxn; clear Ybgxn; + [Yi,resT2] = cat_vol_resize( Yi ,'reduceV',vx_vol,1,32,'meanm'); + Yii = cat_vol_resize( Ylab{2}/T3th(3) ,'reduceV',vx_vol,1,32,'meanm'); + Ybgx = cat_vol_resize( Ybgx ,'reduceV',vx_vol,1,32,'meanm'); + for xi = 1:2*LASi, Yi = cat_vol_localstat(Yi,Yi>0,3,1); end % local smoothing + Yi = cat_vol_approx(Yi,'nh',resT2.vx_volr,2); % approximation of the GM bias + Yi = min(Yi,Yii*(T3th(2) + 0.90*diff(T3th(2:3)))/T3th(3)); % limit upper values to avoid wholes in the WM + Yi(Ybgx) = Yii(Ybgx) * cat_stat_nanmean(Yi(~Ybgx(:))); % use WM bias field in the background + if debug==0; clear Yii Ybgx; end + Yi = cat_vol_smooth3X(Yi,LASfs); % final low res smoothing + Ylab{1} = cat_vol_resize(Yi,'dereduceV',resT2).*Ylab{2}; % back to original resolution + if debug==0; clear Yi; end + + + % update CSF map + Ycm = (single(Ycls{3})/255 - Yg*4 + abs(Ydiv)*2)>0.5 & ... + Ysrc<(Ylab{1}*mean(T3th([1,1:2]))/T3th(2)); + if debug==0; clear Ydiv; end + Ycm(smooth3(Ycm)<0.5)=0; + Ycm(Yb2 & cat_vol_morph(Ysrc128 & Yg<0.15; % & Ysrc0.5) * rf(2))/rf(2); + Yx = round(Ysrc./Ylab{2} .* Ynb * rf(2))/rf(2); + + % The correction should be very smooth (and fast) for CSF and we can use + % much lower resolution. + [Yc,resT2] = cat_vol_resize(Yc,'reduceV',vx_vol,8,16,'min'); % only pure CSF !!! + Yx = cat_vol_resize(Yx,'reduceV',vx_vol,8,16,'meanm'); + + % correct Nans and remove outlier + Yc(isnan(Yc)) = 0; Yc = cat_vol_median3(Yc,Yc~=0,true(size(Yc)),0.1); + Yx(isnan(Yx)) = 0; Yx = cat_vol_median3(Yx,Yx~=0,true(size(Yc)),0.1); + + % CSF intensity show be higher than background intensity + Yx(Yc>0)=0; Yc(Yx>0)=0; + if 0 % no so important ... keep it simple? + if cat_stat_nanmean(Yx(Yx~=0)) < cat_stat_nanmean(Yc(Yc~=0)) + meanYx = min(median(Yc(Yc(:)>0)),median(Yx(Yx(:)>0))); + meanYc = max(median(Yc(Yc(:)>0)),median(Yx(Yx(:)>0))); + else + meanYc = min(median(Yc(Yc(:)>0)),median(Yx(Yx(:)>0))); + meanYx = max(median(Yc(Yc(:)>0)),median(Yx(Yx(:)>0))); + end + else + meanYx = cat_stat_nanmean( [ 0 ; Yx(Yx(:)>0) ]); + meanYc = cat_stat_nanmedian( [ T3th(1) ; Yc(Yc(:)>0) ]); + end + + % correct for high intensity backgrounds (e.g. Gabi's R1) + %Yx = Yx .* (Yx > (meanYc + max(0.1,std(Yc(Yc(:)>0))))); + + %% avoid CSF in background and background in CSF + if ~res.ppe.affreg.highBG + bcd = max( abs( [ diff( [meanYx meanYc] ) min( diff( T3th/max(T3th(:)) ) ) ] )); + Yxc = Yx + (Yx==0 & Yc~=0) .* (Yc * meanYx/meanYc - 0.5 * bcd) + ... % avoid BG in the CSF (white dots in the blue CSF) + ( (Yx~=0) * 0.2 * bcd ); % this term is the lower HG intensity (some nice noise in the BG) + if 0% (meanYx/meanYc) > 0.8 % this looks nice but its no good and change thickness + Ycc = Yc + (Yc==0 & Yx~=0) .* (Yx * meanYc/meanYx + 0.5 * bcd); % here we avoid CSF in the BG (higher boudnary) ... blue CSF dots in the BG + else + Ycc = Yc; + end + %Ycc = Yc + min(max( meanYx + stdYbc , meanYc - stdYbc ), Yx .* meanYc/max(eps,meanYx)); + else + Yxc = Yx; + Ycc = Yc; + end + + %% guaranty small difference between backgound and CSF intensity + Yxa = cat_vol_approx(Yxc ,'nh',resT2.vx_volr,16); + Yca = cat_vol_approx(Ycc ,'nh',resT2.vx_volr,16); + if debug==0, clear Yc Yx; end + Yca = Yca * 0.7 + 0.3 * max( mean(Yca(:)) , T3th(1)/T3th(3) ); + % smoothing + Yxa = cat_vol_smooth3X( Yxa , LASfs * 2 ); + Yca = cat_vol_smooth3X( Yca , LASfs * 2 ); + %% back to original resolution, combination with WM bias, and final smoothing + Yca = cat_vol_resize(Yca,'dereduceV',resT2) .* Ylab{2}; + Yxa = cat_vol_resize(Yxa,'dereduceV',resT2) .* Ylab{2}; + Ylab{3} = cat_vol_smooth3X( Yca , LASfs * 2 ); + Ylab{6} = cat_vol_smooth3X( Yxa , LASfs * 2 ); + if debug==0, clear Yxa Yca; end + + if res.ppe.affreg.highBG + Ylab{6} = min(Ysrc(:)); + end + else + % simple + % RD202403: avoid skull-stripped voxels and neighbors + Ynb = smooth3( Ycls{6})>128 & Yg<0.3 & ... + ~cat_vol_morph(Yg==0,'d'); % avoid arificial regions + %Ynb = cat_vol_morph(Ynb,'e',4*vxv); + + Ylab{3} = ones(size(Ygm),'single') .* min( [ T3th(1) , cat_stat_nanmean(Ysrc(Ycm(:))) ] ); + Ylab{6} = ones(size(Ynb),'single') .* min( [ T3th(1) - min(diff(T3th)) , cat_stat_nanmean(Ysrc(Ycm(:))) ] ); + end + + % final scaling of GM and CSF (not required for WM) + Ylab{1} = Ylab{1} .* T3th(2) / cat_stat_kmeans( Ylab{1}(Ygm(:)>0.5), 1); + Ylab{3} = Ylab{3} .* T3th(1) / cat_stat_kmeans( Ylab{3}(Ycm(:)>0.5), 1); + + %% RD202110: corrected cases with incorrect background region Ynb + % RD202403: there are allways some voxels .. somegthing is wrong here + %if sum(Ynb(:)>0.5)>0 + % Ynb = smooth3( Ycls{6})>128 & Yg<0.3; + %end + if sum(Ynb(:)>0.5)>0 + Ylab{6} = Ylab{6} .* abs(cat_stat_kmeans( Ysrc(Ynb(:)>0.5) , 1)) / max(eps,abs(cat_stat_kmeans( Ylab{6}(Ynb(:)>0.5) , 1))); + else + Ylab{6} = min(Ysrc(:)); + end + + %% restore original resolution + if exist('resT0','var') + Ycls = Yclso2; clear Yclso2; + Ysrc = Ysrco2; clear Ysrco2; + for i=[1 2 3 6], Ylab{i} = cat_vol_resize (Ylab{i} , 'dereduceV' , resT0 ); end + Yb2 = cat_vol_resize( single(Yb2) , 'dereduceV' , resT0 )>0.5; + end + + %% local intensity modification of the original image + % -------------------------------------------------------------------- + cat_io_cmd(' Intensity transformation','g5','',verb,stime); + + Yml = zeros(size(Ysrc)); + Yml = Yml + ( (Ysrc>=Ylab{2} ) .* (3 + (Ysrc - Ylab{2}) ./ max(eps,Ylab{2} - Ylab{3})) ); + Yml = Yml + ( (Ysrc>=Ylab{1} & Ysrc=Ylab{3} & Ysrc10)=10; + + + + %% update of the global intensity normalized map + if Tth.T3th(Tth.T3thx==1) == Tth.T3thx(Tth.T3thx==1) % invers intensities (T2/PD) + Ymg = max(eps,(Ysrc + srcmin)./Ylab{2}); + else + Ymg = Ysrc ./ max(eps,Ylab{2}); + Ymg = Ymg * Tthc.T3th(Tthc.T3thx==3)/(Tthc.T3thx(Tthc.T3thx==3)/3) + srcmin; % RD202004: corrected srcmin-correction + end + if ~debug, clear Ylab Ysrc; end + Ymg = cat_main_gintnorm(Ymg,Tth); + + + + %% fill up CSF in the case of a skull stripped image + if max(res.mn(res.lkp==5 & res.mg'>0.1)) < mean(res.mn(res.lkp==3 & res.mg'>0.3)) + YM = cat_vol_morph(Yb2,'d'); + Ymls = smooth3(max(Yml,YM*0.5)); + Yml(YM & Yml<0.5) = Ymls(YM & Yml<0.5); + clear Ymls YM + end + clear res + + + + %% interpolate maps if an resolution adaptation was applied + if exist('resT0','var') + Ywm = cat_vol_resize( single(Ywm) , 'dereduceV' , resT0 )>0.5; + Ygm = cat_vol_resize( single(Ygm) , 'dereduceV' , resT0 )>0.5; + end + + + + %% class correction and definition of the second logical class map Ycls2 + Ynwm = Ywm & ~Ygm & Yml/3>0.95 & Yml/3<1.3; + Ynwm = Ynwm | (smooth3(Ywm)>0.6 & Yml/3>5/6); Ynwm(smooth3(Ynwm)<0.5)=0; + Yngm = Ygm & ~Ywm & Yml/3<0.95; Yngm(smooth3(Yngm)<0.5)=0; + Yncm = ~Ygm & ~Ywm & ((Yml/3)>1/6 | Ycls{3}>128) & (Yml/3)<0.5 & Yb2; + if debug==0, clear Ywm Ygm; end + + % cleanup outer GM that was mislabeled as WM + Yp0 = single( Ycls{1} )/255*2 + single( Ycls{2} )/255*3 + single( Ycls{3} )/255; % recreate label map + Ycls{2} = cat_vol_ctype(single(Ycls{2}) + (Ynwm & ~Yngm & Yp0>=1.5)*256 - (Yngm & ~Ynwm & Yp0>=2)*256,'uint8'); + Ycls{1} = cat_vol_ctype(single(Ycls{1}) - (Ynwm & ~Yngm & Yp0>=1.5)*256 + (Yngm & ~Ynwm & Yp0>=2)*256,'uint8'); + %Ycls{3} = cat_vol_ctype(single(Ycls{3}) - ((Ynwm | Yngm) & Yp0>=2)*256,'uint8'); + %Ycls{3} = cat_vol_ctype(single(Ycls{3}) + (Yb2 & Yml<1.1 & ~Ynwm & ~Yngm)*256,'uint8'); + Ycls{1} = cat_vol_ctype(single(Ycls{1}) - (Yb2 & Yml<1.1 & ~Ynwm & ~Yngm)*256,'uint8'); + Ycls{2} = cat_vol_ctype(single(Ycls{2}) - (Yb2 & Yml<1.1 & ~Ynwm & ~Yngm)*256,'uint8'); + Ycls2 = {Yngm,Ynwm,Yncm}; + if debug==0, clear Yngm Ynwm Yncm Yb2; end + + + + %% final correction of Yml similar to Ymg + Yml = Yml/3; + +end + +","MATLAB" +"Neurology","ChristianGaser/cat12","MrfPrior.c",".c","3844","133","/* ______________________________________________________________________ + * + * Christian Gaser, Robert Dahnke + * Structural Brain Mapping Group (https://neuro-jena.github.io) + * Departments of Neurology and Psychiatry + * Jena University Hospital + * ______________________________________________________________________ + * $Id$ + * + */ + +/* This code is a substantially modified version of MrfPrior.C + * from Jagath C. Rajapakse + * + * Original author : Jagath C. Rajapakse + * + * See: + * Statistical approach to single-channel MR brain scans + * J. C. Rajapakse, J. N. Giedd, and J. L. Rapoport + * IEEE Transactions on Medical Imaging, Vol 16, No 2, 1997 + * + * Comments to raja@cns.mpg.de, 15.10.96 + */ + +#include +#include +#include ""Amap.h"" + +#ifdef MATLAB_MEX_FILE +#include +#endif + +void MrfPrior(unsigned char *label, int n_classes, double *alpha, double *beta, int init, int *dims, int verb) +{ + int i, j, x, y, z; + int fi, fj; + long color[MAX_NC][7][7][7][7]; + long area; + + int f[MAX_NC-1], plab, zero, iBG; + int n, z_area, y_dims; + double XX, YY, L; + + area = dims[0]*dims[1]; + + /* initialize configuration counts */ + for (i = 0; i < n_classes; i++) + for (f[0] = 0; f[0] < 7; f[0]++) + for (f[1] = 0; f[1] < 7; f[1]++) + for (f[2] = 0; f[2] < 7; f[2]++) + for (f[3] = 0; f[3] < 7; f[3]++) + color[i][f[0]][f[1]][f[2]][f[3]]=0; + + /* calculate configuration counts */ + n = 0; + for (i = 0; i < n_classes; i++) alpha[i] = 0.0; + + for (z = 1; z < dims[2]-1; z++) { + z_area=z*area; + for (y = 1; y < dims[1]-1; y++) { + y_dims = y*dims[0]; + for (x = 1; x < dims[0]-1; x++) { + + plab = (int)label[z_area + y_dims + x]; + + zero = plab; + if (zero < 1) continue; + n++; + alpha[zero - 1] += 1.0; + + for (i = 1; i < n_classes; i++) { + f[i-1] = 0; + iBG = i+1; + if ((int)label[z_area + y_dims + x-1] == iBG) f[i-1]++; + if ((int)label[z_area + y_dims + x+1] == iBG) f[i-1]++; + if ((int)label[z_area + ((y-1)*dims[0]) + x] == iBG) f[i-1]++; + if ((int)label[z_area + ((y+1)*dims[0]) + x] == iBG) f[i-1]++; + if ((int)label[((z-1)*area) + y_dims + x] == iBG) f[i-1]++; + if ((int)label[((z+1)*area) + y_dims + x] == iBG) f[i-1]++; + } + color[zero-1][f[0]][f[1]][f[2]][f[3]]++; + } + } + } + + /* evaluate alphas */ + if ( verb == 1 ) printf(""MRF priors: alpha ""); + for (i = 0; i < n_classes; i++) { + if (init == 0) alpha[i] /= (double) n; else alpha[i] = 1.0; + if ( verb == 1 ) printf(""%3.3f "", alpha[i]); + } + + /* compute beta */ + n = 0; + XX=0.0, YY=0.0; + for (f[0] = 0; f[0] < 7; f[0]++) + for (f[1] = 0; f[1] < 7; f[1]++) + for (f[2] = 0; f[2] < 7; f[2]++) + for (f[3] = 0; f[3] < 7; f[3]++) + for (i = 0; i < n_classes; i++) + for (j = 0; j < i; j++) { + n++; + if (color[i][f[0]][f[1]][f[2]][f[3]] < TH_COLOR || + color[j][f[0]][f[1]][f[2]][f[3]] < TH_COLOR) continue; + + L = log(((double) color[i][f[0]][f[1]][f[2]][f[3]]) / + (double) color[j][f[0]][f[1]][f[2]][f[3]]); + + if (i == 0) + fi = 6 - f[0] - f[1] - f[2] - f[3]; + else fi = f[i-1]; + + if (j == 0) + fj = 6 - f[0] - f[1] - f[2] - f[3]; + else fj = f[j-1]; + + XX += (double) (fi-fj)*(fi-fj); + YY += L * ( (double) (fi-fj)); + } + + /* weighting of beta was empirically estimated using brainweb data with different noise levels + because old beta estimation was not working */ + beta[0] = XX/YY; + if ( verb == 1 ) printf(""\t beta %3.3f\n"", beta[0]); + fflush(stdout); +} + + + + + + +","C" +"Neurology","ChristianGaser/cat12","cat_vol_qa202412.m",".m","67622","1580","function varargout = cat_vol_qa202412(action,varargin) +% CAT Preprocessing T1 Quality Control +% ______________________________________________________________________ +% +% From cat_vol_qa201901x. +% +% Estimation of image quality measures like noise, inhomogeneity, +% contrast, resolution, etc. and scaling for school marks. +% +% [QAS,QAM] = cat_vol_qa201901x(action,varargin) +% +% +% 1) Use GUI interface to choose segmentation and automatic setting of +% original and modified image (if available) +% [QAS,QAM] = cat_vol_qa201901x() = cat_vol_qa201901x('p0') +% +% [QAS,QAM] = cat_vol_qa201901x('p0'[,opt]) - p0 class image +% [QAS,QAM] = cat_vol_qa201901x('p#'[,opt]) - p1,p2,p3 class images +% [QAS,QAM] = cat_vol_qa201901x('c#'[,opt]) - c1,c2,c3 class images +% [QAS,QAM] = cat_vol_qa201901x('*#'[,opt]) - csf,gm,wm class images +% [QAS,QAM] = cat_vol_qa201901x('p0',Pp0[,opt]) - no GUI call +% [QAS,QAM] = cat_vol_qa201901x('p#',Pp1,Pp2,Pp3,[,opt]) - no GUI call +% [QAS,QAM] = cat_vol_qa201901x('c#',Pc1,Pc2,Pc3,[,opt]) - no GUI call +% [QAS,QAM] = cat_vol_qa201901x('c#',Pcsf,Pgm,Pwm,[,opt]) - no GUI call +% +% +% 2) Use GUI interface to choose all images like for other segmentations +% and modalities with a similar focus of CSF, GM, and WM tissue +% contrast such as PD, T2, or FLASH. +% [QAS,QAM] = cat_vol_qa201901x('p0+'[,opt]) - p0 class image +% [QAS,QAM] = cat_vol_qa201901x('p#+'[,opt]) - p1,p2,p3 class images +% [QAS,QAM] = cat_vol_qa201901x('c#+'[,opt]) - c1,c2,c3 class images +% [QAS,QAM] = cat_vol_qa201901x('*#+'[,opt]) - csf,gm,wm class images +% [QAS,QAM] = cat_vol_qa201901x('p0+',Pp0,Po[,Pm,opt]) - no GUI call +% [QAS,QAM] = cat_vol_qa201901x('p#+',Pp1,Pp2,Pp3,Po[,Pm,opt]) - no GUI call +% [QAS,QAM] = cat_vol_qa201901x('c#+',Pc1,Pc2,Pc3,Po[,Pm,opt]) - no GUI call +% +% +% 3) Use GUI interface to choose all images. I.e. for other segmentations +% and modalities without focus of GM-WM contrast such as DTI MTI. +% [ not implemented yet ] +% +% +% 4) CAT12 internal preprocessing interface +% (this is the processing case that is also called in all other cases) +% [QAS,QAM] = cat_vol_qa201901x('cat12',Yp0,Po,Ym,res[,opt]) +% +% +% Pp0 - segmentation files (p0*.nii) +% Po - original files (*.nii) +% Pm - modified files (m*.nii) +% Yp0 - segmentation image matrix +% Ym - modified image matrix +% +% opt = parameter structure +% opt.verb = verbose level [ 0=nothing | 1=points | 2*=times ] +% opt.redres = resolution in mm for intensity scaling [ 4* ]; +% opt.write_csv = final cms-file +% opt.write_xml = images base xml-file +% opt.sortQATm = sort QATm output +% opt.orgval = original QAM results (no marks) +% opt.recalc = +% opt.avgfactor = +% opt.prefix = prefix of xml output file (default cat_*.xml) +% +% ______________________________________________________________________ +% Robert Dahnke +% Structural Brain Mapping Group +% University Jena +% +% $Id$ +% ______________________________________________________________________ + +%#ok<*ASGLU> + + % get current release number and version + [ver_cat, rev_cat] = cat_version; + ver_cat = ver_cat(4:end); % remove leading CAT + + % init output + QAS = struct(); + QAR = struct(); + %if nargout>0, varargout = cell(1,nargout); end + + try + if strcmp(action,'cat12err') + [mrifolder, reportfolder] = cat_io_subfolders(varargin{1}.job.data,varargin{1}.job); + elseif strcmp(action,'cat12') + [mrifolder, reportfolder] = cat_io_subfolders(varargin{2},varargin{6}.job); + else + [mrifolder, reportfolder] = cat_io_subfolders(varargin{4}.catlog,varargin{6}.job); + end + catch + mrifolder = 'mri'; + reportfolder = 'report'; + end + + % no input and setting of default options + action2 = action; + if nargin==0, action='p0'; end + if isstruct(action) + if isfield(action,'model') + if isfield(action.model,'catp0') + Po = action.images; + Pp0 = action.model.catp0; + if numel(Po)~=numel(Pp0) && numel(Pp0)==1 + Pp0 = repmat(Pp0,numel(Po),1); + end + Pm = action.images; + action.data = Pp0; + end + end + if isfield(action,'data') + Pp0 = action.data; + end + action = 'p0'; + end + if nargin==3 && isstruct(varargin{2}) && isstruct(varargin{2}) + opt = cat_check('checkinopt',varargin{2},defaults); + nopt = 1; + elseif nargin==8 && isstruct(varargin{6}) && isstruct(varargin{6}) + opt = cat_check('checkinopt',varargin{6},defaults); + nopt = 1; + else + if isstruct(action2) + opt = cat_check('checkinopt',action2.opts,defaults); + else + opt = defaults; + end + nopt = 0; + end + + % for development and in the batch mode we want to call some other versions + if isfield(opt,'version') + if ~exist(opt.version,'file') + error('Selected QC version is not available! '); + elseif ~strcmp(opt.version,mfilename) + eval(sprintf('%s(action2,varargin{:})',opt.version)); + end + end + + % check input by action + switch action + case {'p0','p0+'} + % segment image cases + if nargin<=3 && ( ~exist('Pp0','var') || isempty(Pp0) ) + if (nargin-nopt)<2 + Pp0 = cellstr(spm_select(inf,'image',... + 'select p0-segment image',{},pwd,'^p0.*')); + if isempty(Pp0{1}), return; end + else + Pp0 = varargin{1}; + end + if numel(action)==2 + Po = Pp0; Pm = Pp0; + for fi=1:numel(Pp0) + [pp,ff,ee] = spm_fileparts(Pp0{fi}); + [ppa,ppb] = spm_fileparts(pp); + if strcmp(ppb,'mri'), ppo = ppa; else, ppo = pp; end + + Po{fi} = fullfile(ppo,[ff(3:end) ee]); + Pm{fi} = fullfile(pp,[opt.mprefix ff(3:end) ee]); + %Pmv{fi} = fullfile(pp,['m' ff(3:end) ee]); %#ok + %if ~exist(Pm{fi},'file') && strcmp(opt.mprefix,'nm') && exist(Pmv{fi},'file') + % fprintf('Preparing %s.\n',Pmv{fi}); + % cat_vol_sanlm(Pmv{fi},'n'); + %end + + %if ~exist(Po{fi},'file'), Po{fi}=''; end + if ~exist(Pm{fi},'file'), Pm{fi}=''; end + end + else + Po = cellstr(spm_select(repmat(numel(Pp0),1,2),... + 'image','select original image(s)',{},pwd,'.*')); + Pm = cellstr(spm_select(repmat(numel(Pp0),1,2),... + 'image','select modified image(s)',{},pwd,'.*')); + end + elseif nargin<=5 && ( ~exist('Pp0','var') || isempty(Pp0) ) + Pp0 = varargin{1}; + Po = varargin{2}; + Pm = varargin{3}; + elseif ( ~exist('Pp0','var') || isempty(Pp0) ) + error('MATLAB:cat_vol_qa201901x:inputerror',... + 'Wrong number/structure of input elements!'); + end + case {'p#','c#','*#','p#+','c#+','*#+'} + % tissue class image cases + if nargin-1<=2 % GUI + if (nargin-nopt)<2 + if action(1)=='p' || action(1)=='c' + % cat/spm case + Pcsf = cellstr(spm_select(inf,'image',... + 'select p1-segment image',{},pwd,['^' action(1) '1.*'])); + if isempty(Pcsf{1}), return; end + Pgm=Pcsf; Pwm=Pcsf; + for fi=1:numel(Pcsf) + [pp,ff,ee] = spm_fileparts(Pcsf{fi}); + + Pgm{fi} = fullfile(pp,[action(1) '2' ff(3:end) ee]); + Pwm{fi} = fullfile(pp,[action(1) '3' ff(3:end) ee]); + end + else + Pcsf = cellstr(spm_select(inf,'image',... + 'select CSF segment image(s)',{},pwd,'.*')); + if isempty(Pcsf{1}), return; end + %Pgm = cellstr(spm_select(repmat(numel(Pcsf),1,2),... + % 'image','select GM segment image(s)',{},pwd,'.*')); + %Pwm = cellstr(spm_select(repmat(numel(Pcsf),1,2),... + % 'image','select WM segment image(s)',{},pwd,'.*')); + end + if numel(action)==2 + Pp0=Pcsf; Po=Pcsf; Pm=Pcsf; + for fi=1:numel(Pcsf) + [pp,ff,ee] = spm_fileparts(Pcsf{fi}); + Po{fi} = fullfile(pp,[ff(3:end) ee]); + Pm{fi} = fullfile(pp,['m' ff(3:end) ee]); + Pp0{fi} = fullfile(pp,['p0' ff(3:end) ee]); + end + else + Po = cellstr(spm_select(repmat(numel(Pcsf),1,2),... + 'image','select original image(s)',{},pwd,'.*')); + Pm = cellstr(spm_select(repmat(numel(Pcsf),1,2),... + 'image','select modified image(s)',{},pwd,'.*')); + Pp0=Pcsf; + for fi=1:numel(Pcsf) + [pp,ff,ee] = spm_fileparts(Pcsf{fi}); + Pp0{fi} = fullfile(pp,['p0' ff(3:end) ee]); + end + end + + % wie komm ich zum p0??? + else + Pp0 = varargin{1}; + end + elseif nargin==5 || nargin==6 + else + error('MATLAB:cat_vol_qa201901x:inputerror',... + 'Wrong number/structure of input elements!'); + end + + Yp0 = 1; + case 'cat12err' + opt = cat_check('checkinopt',varargin{end},defaults); + case 'cat12' + % CAT12 internal input + if nargin>3 + Yp0 = varargin{1}; +% Octave is starting with many warning messages here ... +% if strcmpi(spm_check_version,'octave'), warning off; end + Vo = spm_vol(varargin{2}); +% if strcmpi(spm_check_version,'octave'), warning on; end + Yo = single(spm_read_vols(Vo)); + Ym = varargin{3}; + res = varargin{4}; + V = res.image; + species = varargin{5}; + if isfield(varargin{6},'qa') + if isfield(varargin{6}.qa,'software') && isfield(varargin{6}.qa.software,'version_segment'), QAS.software.version_segment = varargin{6}.qa.software.version_segment; end + if isfield(varargin{6}.qa,'qualitymeasures'), QAS.qualitymeasures = cat_io_updateStruct(QAS,varargin{6}.qa.qualitymeasures); end + if isfield(varargin{6}.qa,'subjectmeasures'), QAS.subjectmeasures = cat_io_updateStruct(QAS,varargin{6}.qa.subjectmeasures); end + end + if nargin>7, Pp0 = varargin{7}; end % nargin count also parameter + % opt = varargin{end} in line 96) + %opt.verb = 0; + + % reduce to original native space if it was interpolated + sz = size(Yo); + if any(sz(1:3)~=Vo.dim(1:3)) + if isfield(Vo,'private'), Vo = rmfield(Vo,'private'); end + if isfield(Vo,'mat0'), Vo = rmfield(Vo,'mat0'); end + Vo.dat = zeros(Vo.dim,'single'); Vo.dt(1) = 16; Vo.pinfo = [1;0;0]; + + Vp0t = res.image; + if isfield(Vp0t,'private'), Vp0t = rmfield(Vp0t,'private'); end + if isfield(Vp0t,'mat0'), Vp0t = rmfield(Vp0t,'mat0'); end + Vp0t.dt(1) = 16; + Vp0t.pinfo = [1;0;0]; + Vp0t.dat = Yp0; + + % resampling and corrections of the Yp0 + % Vp0t = spm_write_vol(Vp0t,double(Yp0)); + [Vtpm,Yp0] = cat_vol_imcalc(Vp0t,Vo,'i1',struct('interp',2,'verb',0)); + rf = 50; + Yp0 = single(Yp0); + Yp0r = round(Yp0*rf)/rf; + YMR = false(size(Yp0)); + for i=1:4, YMR = YMR | (Yp0>(i-1/rf) & Yp0<(i+1/rf)); end + Yp0(YMR) = Yp0r(YMR); clear YMR Ynr; + + % resampling of the corrected image + Vp0t.dat = Ym; + [Vtpm,Ym] = cat_vol_imcalc(Vp0t,Vo,'i1',struct('interp',6,'verb',0)); + Ym = single(Ym); + end + + else + error('MATLAB:cat_vol_qa201901x:inputerror',... + 'Wrong number/structure of input elements!'); + end + otherwise + error('MATLAB:cat_vol_qa201901x:inputerror',... + 'Wrong number/structure of input elements!'); + end + if ~exist('species','var'), species='human'; end + + + % + % -------------------------------------------------------------------- + [QA,QMAfn] = cat_stat_marks('init'); + stime = clock; + stime2 = clock; + + + + % Print options + % -------------------------------------------------------------------- + Cheader = {'scan'}; + Theader = sprintf(sprintf('%%%ds:',opt.snspace(1)-1),'scan'); + Tline = sprintf('%%5d) %%%ds:',opt.snspace(1)-8); + Tline2 = sprintf('%%5d) %%6s%%%ds:',opt.snspace(1)-14); + Tavg = sprintf('%%%ds:',opt.snspace(1)-1); + TlineE = sprintf('%%5d) %%%ds: %%s',opt.snspace(1)-7); + for fi=1:numel(QMAfn) + Cheader = [Cheader QMAfn{fi}]; %#ok + Theader = sprintf(sprintf('%%s%%%ds',opt.snspace(2)),Theader,... + QMAfn{fi}(1:min(opt.snspace(2)-1,numel(QMAfn{fi})))); + Tline = sprintf('%s%%%d.%df',Tline,opt.snspace(2),opt.snspace(3)); + Tline2 = sprintf('%s%%%d.%df',Tline2,opt.snspace(2),opt.snspace(3)); + Tavg = sprintf('%s%%%d.%df',Tavg,opt.snspace(2),opt.snspace(3)); + end + Cheader = [Cheader 'IQR']; + Theader = sprintf(sprintf('%%s%%%ds',opt.snspace(2)),Theader,'SIQR'); + Tline = sprintf('%s%%%d.%df%%s\n',Tline,opt.snspace(2),opt.snspace(3)); + Tline2 = sprintf('%s%%%d.%df\n',Tline2,opt.snspace(2),opt.snspace(3)); + Tavg = sprintf('%s%%%d.%df\n',Tavg,opt.snspace(2),opt.snspace(3)); + + + + + + + % estimation part + switch action + case {'p0','p#','c#','*#','p0+','p#+','c#+','*#+'} + % loop for multiple files + stimem = clock; + + % return for empty input + if isempty(Pp0) || (isempty(Pp0{1}) && numel(Pp0)<=1) + cat_io_cprintf('com','No images for QA!\n'); + return + end + + if opt.verb>1 + fprintf('\n%s\n\n%s\n%s\n', ... + sprintf('CAT Preprocessing T1 Quality Control (%s %s):',mfilename,... + sprintf('Rev: %s',rev_cat)), Theader,repmat('-',size(Theader))); + end + + qamat = nan(numel(Po),numel(QMAfn)); + qamatm = nan(numel(Po),numel(QMAfn)); + mqamatm = 10.5*ones(numel(Po),1); + + + QAS = struct(); QAR = struct(); + QAR.mark2rps = @(mark) min(100,max(0,105 - mark*10)) + isnan(mark).*mark; + + for fi=1:numel(Pp0) + try + stime = cat_io_cmd(' Any segmentation Input:','g5','',opt.verb>2); stime1 = stime; + + [pp,ff,ee] = spm_fileparts(Po{fi}); + if exist(fullfile(pp,[ff ee]),'file') + Vo = spm_vol(Po{fi}); + elseif exist(fullfile(pp,[ff ee '.gz']),'file') + gunzip(fullfile(pp,[ff ee '.gz'])); + Vo = spm_vol(Po{fi}); + delete(fullfile(pp,[ff ee '.gz'])); + else + error('cat_vol_qa201901x:noYo','No original image.'); + end + + + Vm = spm_vol(Pm{fi}); + Vp0 = spm_vol(Pp0{fi}); + if any(Vp0.dim ~= Vm.dim) + [Vx,Yp0] = cat_vol_imcalc(Vp0,Vm,'i1',struct('interp',2,'verb',0)); + else + Yp0 = single(spm_read_vols(Vp0)); + end + Yp0(isnan(Yp0) | isinf(Yp0)) = 0; + if 0 %~isempty(Pm{fi}) && exist(Pm{fi},'file') ################################ + Ym = single(spm_read_vols(spm_vol(Pm{fi}))); + Ym(isnan(Yp0) | isinf(Yp0)) = 0; + elseif 1==1 %end + %if ~exist(Ym,'var') || round( cat_stat_nanmean(Ym(round(Yp0)==3)) * 100) ~= 100 + Ym = single(spm_read_vols(spm_vol(Po{fi}))); + Ym(isnan(Yp0) | isinf(Yp0)) = 0; + Yw = Yp0>2.95 | cat_vol_morph( Yp0>2.25 , 'e'); + Yb = cat_vol_approx( Ym .* Yw + Yw .* min(Ym(:)) ) - min(Ym(:)); + %Yb = Yb / mean(Ym(Yw(:))); + Ym = Ym ./ max(eps,Yb); + + else + error('cat_vol_qa201901x:noYm','No corrected image.'); + end + rmse = (mean(Ym(Yp0(:)>0) - Yp0(Yp0(:)>0)/3).^2).^0.5; + if rmse>0.2 + cat_io_cprintf('warn','Segmentation is maybe not fitting to the image (RMSE(Ym,Yp0)=%0.2f)?:\n %s\n %s',rmse,Pm{fi},Pp0{fi}); + end + + res.image = spm_vol(Pp0{fi}); + [QASfi,QAMfi] = cat_vol_qa201901x('cat12',Yp0,Vo,Ym,res,species,opt,Pp0(fi)); + + if isnan(QASfi.qualitymeasures.NCR) + fprintf(''); + end + + + try + QAS = cat_io_updateStruct(QAS,QASfi,0,fi); + QAR = cat_io_updateStruct(QAR,QAMfi,0,fi); + catch + fprintf('ERROR-Struct'); + end + + + % color for the differen mark cases (opt.process) + for fni=1:numel(QMAfn) + try + qamat(fi,fni) = QAS(fi).qualitymeasures.(QMAfn{fni}); + qamatm(fi,fni) = QAR(fi).qualityratings.(QMAfn{fni}); + catch + qamat(fi,fni) = QASfi.qualitymeasures.(QMAfn{fni}); + qamatm(fi,fni) = QAMfi.qualityratings.(QMAfn{fni}); + end + + end + try + mqamatm(fi,1) = QAR(fi).qualityratings.IQR; + catch + mqamatm(fi,1) = QASfi.qualityratings.IQR; + end + mqamatm(fi,1) = max(0,min(10.5, mqamatm(fi,1))); + + + if opt.verb>1 + if opt.rerun || cat_io_rerun(Vo.fname, fullfile(pp,reportfolder,[opt.prefix ff '.xml']) , 0 ) + rerun = sprintf(' updated %2.0fs',etime(clock,stime1)); + elseif exist( fullfile(pp,reportfolder,[opt.prefix ff '.xml']) , 'file') + rerun = ' loaded'; + else + rerun = ' '; % new + end + + %% + if opt.orgval + cat_io_cprintf(opt.MarkColor(max(1,floor( mqamatm(fi,1)/9.5 * ... + size(opt.MarkColor,1))),:),sprintf(Tline,fi,... + spm_str_manip(QAS(fi).filedata.fname,['a' num2str(opt.snspace(1) - 14)]),... + qamat(fi,:), max(1,min(9.5,mqamatm(fi,:))), rerun)); + else + cat_io_cprintf(opt.MarkColor(max(1,floor( mqamatm(fi,1)/9.5 * ... + size(opt.MarkColor,1))),:),sprintf(Tline,fi,... + spm_str_manip(QAS(fi).filedata.fname,['a' num2str(opt.snspace(1) - 14)]),... + qamatm(fi,:), max(1,min(9.5,mqamatm(fi,:))), rerun)); + end + end + catch e + switch e.identifier + case {'cat_vol_qa201901x:noYo','cat_vol_qa201901x:noYm','cat_vol_qa201901x:badSegmentation'} + em = e.identifier; + otherwise + em = ['ERROR:\n' repmat(' ',1,10) e.message '\n']; + for ei=1:numel(e.stack) + em = sprintf('%s%s%5d: %s\n',em,repmat(' ',1,10),... + e.stack(ei).line(end),e.stack(ei).name); + end + end + + [pp,ff] = spm_fileparts(Po{fi}); + QAS(fi).filedata.fnames = [spm_str_manip(pp,sprintf('k%d',floor( (opt.snspace(1)-19) /3) - 1)),'/',... + spm_str_manip(ff,sprintf('k%d',(opt.snspace(1)-19) - floor((opt.snspace(1)-14)/3)))]; + cat_io_cprintf(opt.MarkColor(end,:),sprintf(TlineE,fi,Pp0{fi},[em '\n'])); + end + end + + + + % sort by mean mark + % ---------------------------------------------------------------- + if opt.sortQATm && numel(Po)>1 + % sort matrix + [smqamatm,smqamatmi] = sort(mqamatm(:,1),'ascend'); + sqamatm = qamatm(smqamatmi,:); + sqamat = qamat(smqamatmi,:); + + % print matrix + if opt.verb>0 + fprintf('%s\n',repmat('-',size(Theader))); + for fi=1:numel(QAS) + if opt.orgval + cat_io_cprintf(opt.MarkColor(max(1,min(size(opt.MarkColor,1),... + round( mqamatm(smqamatmi(fi),2)/9.5 * ... + size(opt.MarkColor,1)))),:),sprintf(... + Tline2,fi,sprintf('(%d)',smqamatmi(fi)),... + spm_str_manip(Pp0{fi},'l80'), ...QAS(smqamatmi(fi)).filedata.fnames, ... + ...spm_str_manip(QAS(smqamatmi(fi)).filedata.file,['f' num2str(opt.snspace(1) - 14)]),... + sqamat(fi,:),max(1,min(10.5,mqamatm(smqamatmi(fi),:))))); + else + cat_io_cprintf(opt.MarkColor(max(1,min(size(opt.MarkColor,1),... + round( mqamatm(smqamatmi(fi),2)/9.5 * ... + size(opt.MarkColor,1)))),:),sprintf(... + Tline2,fi,sprintf('(%d)',smqamatmi(fi)),... + spm_str_manip(Pp0{fi},'l80'), ... QAS(smqamatmi(fi)).filedata.fnames, ... + ...spm_str_manip(QAS(smqamatmi(fi)).filedata.file,['f' num2str(opt.snspace(1) - 14)]),... + sqamatm(fi,:),mqamatm(smqamatmi(fi),:))); + end + end + end + else + %[smqamatm,smqamatmi] = sort(mqamatm,'ascend'); + %sqamatm = qamatm(smqamatmi,:); + end + % print the results for each scan + if opt.verb>1 && numel(Pp0)>1 + fprintf('%s\n',repmat('-',size(Theader))); + if opt.orgval + fprintf(Tavg,'mean',cat_stat_nanmean(qamat,1), cat_stat_nanmean(mqamatm,1)); %#ok + fprintf(Tavg,'std' , cat_stat_nanstd(qamat,1), cat_stat_nanstd(mqamatm,1)); %#ok + else + fprintf(Tavg,'mean',cat_stat_nanmean(qamatm,1), cat_stat_nanmean(mqamatm,1)); %#ok + fprintf(Tavg,'std' , cat_stat_nanstd(qamatm,1), cat_stat_nanstd(mqamatm,1)); %#ok + end + %fprintf('%s\n',repmat('-',size(Theader))); + %fprintf(Tavg,'mean',mean(qamat,1)); + %fprintf(Tavg,'std', std(qamat,1)); + end + if opt.verb>0, fprintf('\n'); end + + + + % result tables (cell structures) + % ---------------------------------------------------------------- + if nargout>2 && opt.write_csv + QAT = [Cheader(1:end-1); ... there is no mean for the original measures + Po , num2cell(qamat); ... + 'mean' , num2cell(cat_stat_nanmean(qamat,1)); ... + 'std' , num2cell( cat_stat_nanstd(qamat,1,1))]; + QATm = [Cheader; ... + Po , num2cell(qamatm) , ... + num2cell(cat_stat_nanmean(qamatm,2)); ... + 'mean' , num2cell(cat_stat_nanmean(qamatm,1)) , ... + num2cell(cat_stat_nanmean(mqamatm,1)); ... + 'std' , num2cell( cat_stat_nanstd(qamatm,1,1)), ... + num2cell( cat_stat_nanstd(mqamatm,1))]; + + + % write csv results + % -------------------------------------------------------------- + if opt.write_csv + pp = spm_fileparts(Pp0{1}); + cat_io_csv(fullfile(pp,reportfolder,[opt.prefix num2str(numel(Vo),'%04d') ... + 'cat_vol_qa_values.csv']),QAT); + cat_io_csv(fullfile(pp,reportfolder,[opt.prefix num2str(numel(Vo),'%04d') ... + 'cat_vol_qa_marks.csv']),QATm); + end + end + + if opt.verb>0 + fprintf('Quality Control for %d subject was done in %0.0fs\n', ... + numel(Pp0),etime(clock,stimem)); fprintf('\n'); + end + + + case 'cat12err' + + % file information + % ---------------------------------------------------------------- + [pp,ff,ee] = spm_fileparts(Vo.fname); + if strcmp(ee,'.gz'), [~,ff] = spm_fileparts(ff); ee = '.nii.gz'; end + [pp0,ff0,ee0] = spm_fileparts(Pp0); + [QAS.filedata.path,QAS.filedata.file] = spm_fileparts(Vo.fname); + QAS.filedata.fname = Vo.fname; + QAS.filedata.F = Vo.fname; + QAS.filedata.Fm = fullfile(pp0,['m' ff ee0]); + QAS.filedata.Fp0 = fullfile(pp0,['p0' ff ee0]); + QAS.filedata.fnames = [spm_str_manip(pp,sprintf('k%d',... + floor( max(opt.snspace(1)-19-ff,opt.snspace(1)-19)/3) - 1)),'/',... + spm_str_manip(ff,sprintf('k%d',... + (opt.snspace(1)-19) - floor((opt.snspace(1)-14)/3)))]; + + + % software, parameter and job information + % ---------------------------------------------------------------- + [nam,rev_spm] = spm('Ver'); + QAS.software.version_spm = rev_spm; + if strcmpi(spm_check_version,'octave') + QAS.software.version_octave = version; + else + A = ver; + for i=1:length(A) + if strcmp(A(i).Name,'MATLAB') + QAS.software.version_matlab = A(i).Version; + end + end + clear A + end + % 1 line: Matlab, SPM12, CAT12 version number and GUI and experimental mode + if ispc, OSname = 'WIN'; + elseif ismac, OSname = 'MAC'; + else, OSname = 'LINUX'; + end + + QAS.software.system = OSname; + QAS.software.version_cat = ver_cat; + if ~isfield(QAS.software,'version_segment') + QAS.software.version_segment = rev_cat; + end + QAS.software.revision_cat = rev_cat; + try + QAS.hardware.numcores = max(cat_get_defaults('extopts.nproc'),1); + catch + QAS.hardware.numcores = 1; + end + + + % save important preprocessing parameter + % remove LAS + QAS.parameter.opts = opt.job.opts; + QAS.parameter.extopts = rmfield(opt.job.extopts,... + {'LAB','atlas','satlas','darteltpms','shootingtpms','fontsize'}); + %QAS.parameter.output = opt.job.output; + QAS.parameter.caterr = opt.caterr; + QAS.error = opt.caterrtxt; + + % export + if opt.write_xml + cat_io_xml(fullfile(pp0,[opt.prefix ff '.xml']),QAS,'write'); + end + + case 'cat12' + % estimation of the measures for the single case + + + % file information + % ---------------------------------------------------------------- + [pp,ff,ee] = spm_fileparts(Vo.fname); + if strcmp(ee,'.gz'), [~,ff] = spm_fileparts(ff); ee = '.nii.gz'; end + [pp0,ff0,ee0] = spm_fileparts(Pp0); + [QAS.filedata.path,QAS.filedata.file] = spm_fileparts(Vo.fname); + QAS.filedata.fname = Vo.fname; + QAS.filedata.F = Vo.fname; + QAS.filedata.Fm = fullfile(pp0,['m' ff ee0]); + QAS.filedata.Fp0 = fullfile(pp0,['p0' ff ee0]); + QAS.filedata.fnames = [spm_str_manip(pp,sprintf('k%d',... + floor( max(opt.snspace(1)-19-ff,opt.snspace(1)-19)/3) - 1)),'/',... + spm_str_manip(ff,sprintf('k%d',... + (opt.snspace(1)-19) - floor((opt.snspace(1)-14)/3)))]; + + + % software, parameter and job information + % ---------------------------------------------------------------- + [nam,rev_spm] = spm('Ver'); + OSname = {'LINUX','WIN','MAC'}; + QAS.software.system = OSname{1 + ispc + ismac}; + QAS.software.version_spm = rev_spm; + A = ver; + for i=1:length(A) + if strcmp(A(i).Name,'MATLAB') + QAS.software.version_matlab = A(i).Version; + end + end + clear A + QAS.software.version_cat = ver_cat; + if ~isfield(QAS.software,'version_segment') + QAS.software.version_segment = rev_cat; + end + QAS.software.revision_cat = rev_cat; + QAS.software.function = which('cat_vol_qa201901x'); + QAS.software.markdefs = which('cat_stat_marks'); + QAS.software.qamethod = action; + QAS.software.date = datestr(clock,'yyyymmdd-HHMMSS'); + warning off + QAS.software.opengl = opengl('INFO'); + QAS.software.opengldata = opengl('DATA'); + warning on + + %QAS.parameter = opt.job; + if isfield(opt,'job') + if isfield(opt.job,'opts') + QAS.parameter.opts = opt.job.opts; + end + if isfield(opt.job,'extopts') + QAS.parameter.extopts = opt.job.extopts; + end + %QAS.parameter.output = opt.job.output; + if exist('res','var') + rf = {'Affine','lkp','mn','vr'}; % important SPM preprocessing variables + for rfi=1:numel(rf) + if isfield(res,rf{rfi}), QAS.parameter.spm.(rf{rfi}) = res.(rf{rfi}); end + end + end + end + + %% resolution, boundary box + % --------------------------------------------------------------- + QAS.software.cat_qa_warnings = struct('identifier',{},'message',{}); + vx_vol = sqrt(sum(Vo.mat(1:3,1:3).^2)); + vx_voli = sqrt(sum(V.mat(1:3,1:3).^2)); + Yp0toC = @(Yp0,c) 1-min(1,abs(Yp0-c)); + + % resolution + QAS.qualitymeasures.res_vx_vol = vx_vol; + QAS.qualitymeasures.res_vx_voli = vx_voli; + QAS.qualitymeasures.res_RMS = cat_stat_nanmean(vx_vol.^2).^0.5; + % further unused measure (just for test/comparison) + %QAS.qualitymeasures.res_isotropy = max(vx_vol)./min(vx_vol); + %QAS.qualitymeasures.res_vol = prod(abs(vx_vol)); + %QAS.qualitymeasures.res_MVR = mean(vx_vol); + + % boundary box - brain tissue next to image boundary + bbth = round(2/cat_stat_nanmean(vx_vol)); M = true(size(Yp0)); + M(bbth:end-bbth,bbth:end-bbth,bbth:end-bbth) = 0; + QAS.qualitymeasures.res_BB = sum(Yp0(:)>1.25 & M(:))*prod(abs(vx_vol)); + + % check segmentation + spec = species; for ai=num2str(0:9); spec = strrep(spec,ai,''); end + bvol = species; for ai=char(65:122); bvol = strrep(bvol,ai,''); end; bvol = str2double(bvol); + + subvol = [sum(Yp0(:)>2.5 & Yp0(:)<3.1)*prod(vx_vol)/1000,... + sum(Yp0(:)>1.5 & Yp0(:)<2.5)*prod(vx_vol)/1000,... + sum(Yp0(:)>0.5 & Yp0(:)<1.5)*prod(vx_vol)/1000]; + + if isempty(bvol) + switch spec + case 'human' + bvol = 1400; + otherwise + warning('cat_vol_qa201901x:species',... + sprintf('Unknown species %s (C=%0.0f,G=%0.0f,W=%0.0f).',species,subvol)); %#ok + end + end + if sum(subvol)bvol*3 + warning('cat_vol_qa201901x:badSegmentation',... + sprintf('Bad %s segmentation (C=%0.0f,G=%0.0f,W=%0.0f).',species,subvol)) %#ok + end + if ~isfield(QAS,'subjectmeasures') + %% in case of external/batch calls + QAS.subjectmeasures.vol_TIV = sum(Yp0(:)>0) ./ prod(vx_vol) / 1000; + for i = 1:3 + QAS.subjectmeasures.vol_abs_CGW(i) = sum( Yp0toC(Yp0(:),i)) ./ prod(vx_vol) / 1000; + QAS.subjectmeasures.vol_rel_CGW(i) = QAS.subjectmeasures.vol_abs_CGW(i) ./ ... + QAS.subjectmeasures.vol_TIV; + end + end + + + + %% basic level (RD202411) + % To avoid to long processing times but also to standardize the data + % we first fix the resolution to 1 mm. This was also done as there + % is currently not enough data with higher resolution and varying + % properties. + % Lower resolution improve time + mres = 1; % analyse resolution + if any( vx_vol < .8*mres ) + ss = min(2,(mres - vx_vol).^2); + spm_smooth(Yo , Yo , ss); Yo = single(Yo); + [Yo,Vr] = cat_vol_resize(Yo ,'interphdr',V,mres,1); + V = Vr.hdrN; vx_vol = repmat(mres,1,3); %#ok<*RPMT1> + elseif 0 + [Yo,resYo] = cat_vol_resize(Yo ,'reduceV',vx_vol,mres,32,'meanm'); + V.dim = size(Yo); V.mat = spm_matrix( spm_imatrix( V.mat) .* [0 0 0 0 0 0 resYo.vx_red 0 0 0]); + vx_vol = repmat(mres,1,3); %#ok<*RPMT1> + end + Yo=single(Yo); + + + %% + denoising = 1; + Ys = Yo+0; Ymsk = cat_vol_morph( cat_vol_smooth3X(Ys,1./mean(vx_vol)) < .3*prctile(Ys(:),90),'lo',3); Ys(Ymsk) = 0; + if denoising == 1 + cat_sanlm(Ys,1,3); + % additional median filter in case of strong noise + noise = sqrt( (cat_stat_nanmean(Yo(:) - Ys(:))/ prctile(Ys(:),90)) .^2 ); + if (noise>0.03 && all(vx_vol < 1.5 )) || noise>0.075 + mix = min(1,noise * 10); + Ys = Ys.*(1-mix) + mix.*cat_vol_median3(Ys,Ys>0,Ys>0,0.2); + end + elseif denoising == 2 + Ys = cat_vol_median3(Ys,Ys>0,Ys>0); + elseif denoising == 3 + spm_smooth(Ys,Ys,0.4); + end + Ys(Ymsk) = Yo(Ymsk); + Ynd = Yo == 0 | isnan(Yo) | isinf(Yo); + + + %% tissue approximation + Yg = cat_vol_grad(Ys,vx_vol); + Ygn = Yg ./ min( prctile(Ys(:),90)*1.2 , max(eps,Ys - 2*noise*prctile(Ys(:),90))); Ygn(Ynd) = inf; + Yt = cat_vol_morph(Ygn>1 & Ys < cat_stat_nanmean(Ys(Ygn<.1 & Ygn~=0))*.4 ,'dd',2,vx_vol)<.3 & ... + Ys > cat_stat_nanmedian(Ys(Ygn<.4 & Ygn~=0))*.6 & ... + Ygn < cat_stat_nanmedian(Ygn(Ygn(:)<.5 & Ygn(:)~=0)) & ... + Yg < cat_stat_nanmedian(Yg(Ygn(:)<.5 & Ygn(:)~=0))*4 ; + Ymn = cat_vol_localstat(Ys,Ygn>0.05 & Yt,round(2./vx_vol),2); + Ymx = cat_vol_localstat(Ys,Ygn>0.05 & Yt,round(2./vx_vol),3); + Yt = Yt & ~Ynd & ~( (Ymx - Ymn) > .1*Ymx); clear mn mx; + Yt = cat_vol_morph( Yt , 'ldo' , 0*max(1,min( 1.5, (sum(Yt(:)) .* prod(vx_vol) / 1000 )/1000)) , vx_vol); + % cleanup PVE voxels + Yte = cat_vol_morph( Yt , 'e' , 2, vx_vol); + Yss = cat_vol_localstat(Ys ,Yt ,1,2 + (cat_stat_nanmean(Ys(Yte>0))>cat_stat_nanmean(Ys(Yt>0 & ~Yte))) ,round(2./mean(vx_vol))) .* Yt; Yss(Yte) = Ys(Yte); + %% iterative bias approximation + Yw = cat_vol_approx(Yss .* Yt,'rec'); + Yw = cat_vol_smooth3X(Yw,8/mean(vx_vol.^4)); + % add/use head tissue ??? - difficult + for bi = 1:2 + Yw = Yw ./ cat_stat_nanmedian(Yw(Yt)) .* cat_stat_nanmedian(Yo(Yt)); + Yw = cat_vol_approx(Yss .* cat_vol_morph(Yt & (Yss./Yw)>.925+0.025*bi & (Yss./Yw)<1.4-0.05*bi,'l'),'rec'); + Yw = cat_vol_smooth3X(Yw,8/bi/mean(vx_vol.^4)); + end + Yt = Yt & (Yss./Yw)>.925+0.025*bi & (Yss./Yw)<1.4-0.05*bi; + Ym = Yo ./ Yw * cat_stat_nanmedian(Yss(Yt)); + Ym(Ynd) = nan; + %% + Ys = Ys ./ Yw * cat_stat_nanmedian(Yss(Yt)); + Ys(Ynd) = nan; + + + + %% simple segment to estimate the tissue values + [Ymr,Ygr,resYp0] = cat_vol_resize({Ys / cat_stat_nanmedian(Ys(Yt)),Ygn},'reduceV',vx_vol,2,32,'meanm'); + % inital segmenation for intensity normalization and skull-stripping + Yp0 = 3*cat_vol_morph(Ymr >.9 & Ymr <1.2 & Ygr<.5,'l'); + Yp0 = max(Yp0,2 * (cat_vol_morph(Yp0==3,'dd',4,resYp0.vx_volr) & Ymr >.5 & Ymr <.9)); + Yp0 = Yp0 .* cat_vol_morph(Yp0>0,'ldo',2,resYp0.vx_volr); + [Yss,res2] = cat_vol_resize(single(Yp0>0),'reduceV',vx_vol,4,32,'meanm'); + Yss = cat_vol_morph(Yss,'ldc',8,resYp0.vx_volr); + Yss = cat_vol_smooth3X(Yss,4); + Yss = cat_vol_resize(Yss,'dereduceV',res2); + Yp0 = max(Yp0,Yss>.4 & Ymr <.5 & Ygr./Ymr<0.3); + T1th = [cat_stat_nanmedian(Ymr(Yp0toC(Yp0(:),1)>.9)) ... + cat_stat_nanmedian(Ymr(Yp0toC(Yp0(:),2)>.9)) ... + cat_stat_nanmedian(Ymr(Yp0toC(Yp0(:),3)>.9))]; + Ymm = cat_main_gintnorm(Ymr,struct('T3th',[0 T1th T1th(end)*2],'T3thx',[0 1 2 3 6])); + Yi = single(Yp0>2 & Yss); Yi(Yss==0 | Ymm<.4) = -inf; + Yss = cat_vol_downcut(Yi,Ymm,0,resYp0.vx_volr); + Yss = cat_vol_morph(cat_vol_morph(Yss,'lo',2),'lc',4); + Yss = cat_vol_smooth3X(Yss,4)>.3; + Yp0 = cat_vol_resize(Yp0,'dereduceV',resYp0); Yp0(Ynd) = 0; + Yss = cat_vol_resize(Yss,'dereduceV',resYp0); Yss(Ynd) = 0; + % AMAP + [Ymr,Yp0,Yss,resYp0] = cat_vol_resize({Ys / cat_stat_nanmedian(Ys(Yt)),Yp0,Yss},'reduceV',vx_vol,1,32,'meanm'); + Ymm = cat_main_gintnorm(Ymr,struct('T3th',[0 T1th T1th(end)*2],'T3thx',[0 1 2 3 6])); %#ok + evalc([ ... + '[prob,indx,indy,indz] = cat_main_amap1639(Ymm,Yss,Yss,' ... + '{Yp0toC(round(Yss.*Ymm*3),2),Yp0toC(round(Yss.*Ymm*3),3),Yp0toC(round(Yss.*Ymm*3),1)},' ... + 'struct(''extopts'',struct(''gcutstr'',0,''verb'',0,''LASstr'',0,''mrf'',0)),struct(''image'',V));']); + Yp0 = zeros(size(Yss),'single'); tti = [2 3 1]; + for ci = 1:3, Yp0(indx,indy,indz) = Yp0(indx,indy,indz) + tti(ci) * single(prob(:,:,:,ci))/255; end %#ok + Yp0 = cat_vol_resize(Yp0,'dereduceV',resYp0); Yp0(Ynd) = 0; + + + if opt.writeQCseg + Vp0 = V; Vp0.fname = fullfile(pp,['p0_qcseg_' ff '.nii']); Vp0.dt(1) = 2; Vp0.pinfo(1) = 3/255; + spm_write_vol(Vp0,Yp0); + end + %% in case of external/batch calls + QAS.subjectmeasures.vol_TIV = cat_stat_nansum(Yp0(:)>0) .* prod(vx_vol) / 1000; + for i = 1:3 + QAS.subjectmeasures.vol_abs_CGW(i) = cat_stat_nansum( Yp0toC(Yp0(:),i)) .* prod(vx_vol) / 1000; + QAS.subjectmeasures.vol_rel_CGW(i) = QAS.subjectmeasures.vol_abs_CGW(i) ./ ... + QAS.subjectmeasures.vol_TIV; + end + + %% + if 0 + %% Shortcut + % tissue intensity and intensity normalization + T1th = [cat_stat_nanmedian(Ym(Yp0toC(Yp0(:),1)>.9)) ... + cat_stat_nanmedian(Ym(Yp0toC(Yp0(:),2)>.9)) ... + cat_stat_nanmedian(Ym(Yp0toC(Yp0(:),3)>.9))]; + + Ymm = cat_main_gintnorm(Ym,struct('T3th',[0 T1th T1th(end)*2],'T3thx',[0 1 2 3 6])); + Ycm = cat_vol_morph(Yp0>1.5 & Yp0<2.5,'e'); + Ywm = cat_vol_morph(Yp0>2.5,'e'); + Yml = cat_vol_localstat(Ym,Ywm | Ycm,1,4); + res_ECR0 = estimateECR0old( Ymm + 0 , Yp0 + 0, vx_vol ); + signal = max(T1th(3)); + contrast = 1 / 3; + + if T1th(3) > T1th(2) + QAS.qualitymeasures.tissue_weighting = 'T1'; + else + QAS.qualitymeasures.tissue_weighting = 'inverse'; + end + + %% Bias/Inhomogeneity (original image with smoothed WM segment) + QAS.qualitymeasures.tissue_mn = ([0 T1th(1:3)]); + QAS.qualitymeasures.tissue_mnr = QAS.qualitymeasures.tissue_mn ./ signal; + %QAS.qualitymeasures.background = BGth; + QAS.qualitymeasures.signal = signal; + QAS.qualitymeasures.contrast = contrast * signal; + QAS.qualitymeasures.contrastr = 1/3 - abs(1/3 - contrast) / 2; + QAS.qualitymeasures.NCR = min( cat_stat_nanmean(Yml(Ywm(:))) , cat_stat_nanmean(Yml(Ycm(:))) ) / signal * contrast * 3; + QAS.qualitymeasures.ICR = cat_stat_nanstd(Yw(Ywm(:))) / signal * contrast; + QAS.qualitymeasures.res_ECR = abs( 2.5 - res_ECR0 * 10 ); + QAS.qualitymeasures.FEC = estimateFEC(Yp0, vx_vol, Ymm, V); + + else + + + + + %% estimate QA + % --------------------------------------------------------------- + % remove space arount the brain for speed-up + [Yo,Ym,Ys,Yp0,Yw] = cat_vol_resize({Yo,Ym,Ys,Yp0,Yw},'reduceBrain',vx_vol,2,Yp0>1.5); + + % RD20241030: avoid lesions and masking + Y0 = cat_vol_morph(Yo==0,'o',1) | Yp0==0; + Yo(Y0)=nan; Ym(Y0)=0; Yp0(Y0)=0; + + % Refined segmentation to fix skull-stripping issues in case of bad + % segmentation. Tested on the BWP with simulated segmenation issues + % for skull-stripping as well as WM/CSF over/underestimation. + [Yp0r,resYp0] = cat_vol_resize(Yp0,'reduceV',vx_vol,2,32,'meanm'); + Yp0r = cat_vol_morph(cat_vol_morph(cat_vol_morph(Yp0r>0.9,'e',1),'l',[0.5 0.2]),'d',1); + Yp0 = Yp0 .* (cat_vol_resize(Yp0r,'dereduceV',resYp0)>.5); + + + % rought contast and noise estimation to get a stable T1 map for threshold estimation + T1th = [cat_stat_nanmedian(Ym(Yp0toC(Yp0(:),1)>0.9)) ... + cat_stat_nanmedian(Ym(Yp0toC(Yp0(:),2)>0.9)) ... + cat_stat_nanmedian(Ym(Yp0toC(Yp0(:),3)>0.9))]; + + newNC = 0; + if newNC + %% new more accurate approach + %noise = max(0,min(1,cat_stat_nanstd(Ym(Yp0(:)>2.9)) / min(abs(diff(T1th))))); + % we need a bit background noise for the filter! + %Yms = Ym + ( (T1th(3)*noise/3) .* (cat_vol_smooth3X(Yp0,2)>0 & Yp0==0) .* rand(size(Ym)) ); cat_sanlm(Yms,1,3); + noise = max(0,min(1,cat_stat_nanstd(Ym(Yp0(:)>.5) - Ys(Yp0(:)>.5)) / min(abs(diff(T1th))))) * 5; + Ym(Y0) = nan; + else + %% classic a bit faster approach + Ym(Y0) = nan; + noise = max(0,min(1,cat_stat_nanstd(Ym(Yp0(:)>2.9)) / min(abs(diff(T1th))))); + Yms = Ym+0; spm_smooth(Yms,Yms,repmat(double(noise)*4,1,3)); % smoothing to reduce high frequency noise + end + + + % Avoid lesions defined as regions (local blobs) with high difference + % between the segmentation and intensity scaled image. Remove these + % areas from the Yp0 map that is not used for volumetric evaluation. + % Use the ATLAS stroke leson dataset for evalution, where the masked + % and unmasked image should result in the same quality ratings. + Ymm = cat_main_gintnorm(Ym,struct('T3th',[0 T1th T1th(end)*2],'T3thx',[0 1 2 3 6])); + Ymd = cat_vol_smooth3X( (Yp0>0) .* abs(Ymm - Yp0/3) , 2); + mdth = cat_stat_nanmedian(Ymd(Ymd(:) > 1.5 * cat_stat_nanmedian(Ymd(Ymd(:)>0)))); + Ymsk = Ymd > mdth & (Ymm>.5); + % tissue contrasts (corrected for noise-bias estimated on the BWP) + T1th = [cat_stat_nanmedian(Ym(Yp0toC(Yp0(:),1)>0.9 & ~Ymsk(:) & Ymm(:)<1.25/3)) + noise/200 ... + cat_stat_nanmedian(Ym(Yp0toC(Yp0(:),2)>0.9 & ~Ymsk(:) )) + noise/150 ... + cat_stat_nanmedian(Ym(Yp0toC(Yp0(:),3)>0.9 & ~Ymsk(:) ))]; + if newNC + noise = max(0,min(1,cat_stat_nanstd(Ym(Yp0(:)>0.5) - Ys(Yp0(:)>0.5)) / min(abs(diff(T1th))))) * 5; + else + noise = max(0,min(1,cat_stat_nanstd(Ym(Yp0(:)>2.9)) / min(abs(diff(T1th))))); + end + Yp0(Ymsk) = 0; + % fprintf('BCGW=%5.3f,%5.3f,%5.3f,%5.3f, WTH=%8.2f | ',noise,T1th/max(T1th),T1th(3)); + + + % basic tissue classes - erosion to avoid PVE, std to avoid other tissues (like WMHs) + voli = @(v) (v ./ (pi * 4./3)).^(1/3); + rad = voli( QAS.subjectmeasures.vol_TIV) ./ cat_stat_nanmean(vx_vol); + Ysc = 1-cat_vol_smooth3X(Yp0<1 | Yo==0,min(24,max(16,rad*2))); % fast 'distance' map to focus on deep CSF + % definiton of basic tissue segments without PVE + Ycm = cat_vol_morph(Yp0>0.75 & Yp0<1.25,'de',1,vx_vol) & cat_vol_morph(Yp0>0.25 & Yp0<1.75,'de',2,vx_vol) & Ysc>0.75; + if sum(Ycm(:)) < 0.3*sum(Yp0(:)>0.75 & Yp0(:)<1.25), Ycm = Yp0>0.75 & Yp0<1.25 & cat_vol_morph(Yp0>0.25 & Yp0<1.75,'de',1) & Ysc>0.75; end + Ygm = Yp0>1.5 & Yp0<2.5 & cat_vol_morph(Yp0>1.25 & Yp0<2.75,'de',1,vx_vol); + Ywm = cat_vol_morph(Yp0>2.75 & Yp0<3.25,'de',1,vx_vol) & cat_vol_morph(Yp0>2.25 & Yp0<3.75,'de',2,vx_vol); + if sum(Ywm(:)) < 0.3*sum(Yp0(:)>2.25 & Yp0(:)<3.75), Ywm = Yp0>2.25 & Yp0<3.75 & cat_vol_morph(Yp0>2.25 & Yp0<3.75,'de',1); end + % RD202411: Median filter to avoid side effects by PVE/SVD/PVS + Ymed = cat_vol_median3(Ys,Ywm,Ywm); + Ywm(Ymed - (Ys.*Ywm) > noise/2*T1th(3)) = 0; + + + %% RD202212: Edge Contrast Ratio + % To estimate the real structural resolution independent of the + % voxel size that is useless + Ymm = cat_main_gintnorm(Ys*.5 + 0.5*Ym,struct('T3th',[0 T1th T1th(end)*2],'T3thx',[0 1 2 3 6])); + res_ECR0 = estimateECR0old( Ymm + 0, Yp0 + 0, vx_vol ); + QAS.qualitymeasures.res_ECR = abs( 2.5 - res_ECR0 * 10 ); + + %% Fast Euler Characteristic (FEC) + QAS.qualitymeasures.FEC = estimateFEC(Yp0, vx_vol, Ymm, V); + + + % bias correction of the original input image + if 1 % slight improvement + Yi = (Ys .* Yw) ./ cat_stat_nanmedian(Yw(Ywm)).^2 .* Ywm; + Yw = cat_vol_approx(Yi,'rec'); + Yw = cat_vol_smooth3X(Yw,8/mean(vx_vol.^4)); + end + Yw = Yw ./ cat_stat_nanmedian(Yw(Ywm)); + Ymx = Yo ./ Yw; + Ymx = Ymx ./ cat_stat_nanmedian(Ymx(Ywm)); + + %% low resolution tissue intensity maps (smoothing) + % High frequency noise is mostly uncritical as far as simple smoothing can reduce it. + % Although the very low frequency interferences (inhomogeneity) is unproblematic in most cases, + % but will influence the noise pattern. + % But most important is the noise with the medium high frequencies, that we try do detect by + % reducing the very high and low noise pattern by filtering and pixel smoothing by reduction. + res = 2.3; vx_volx = vx_vol; %min(2,max(vx_vol)*2); vx_volx = vx_vol; %/max(vx_vol); + + if 1 + %################## + % This block is a bit weired but is imporant to balance the hard noise + % of the BWP and real data aspects. It uses a Gaussian smoothing to + % reduce this hard noise. + T0th = [cat_stat_nanmedian(Ymx(Ycm(:))) cat_stat_nanmedian(Ymx(Ygm(:))) cat_stat_nanmedian(Ymx(Ywm(:)))]; + Yos = Ymx.*Ywm + (1-Ywm).*T0th(3); spm_smooth(Yos,Yos,.5 + 1./vx_vol); Ymx(Ywm>0)=Yos(Ywm>0); + Yos = Ymx.*Ygm + (1-Ygm).*T0th(2); spm_smooth(Yos,Yos,.5 + 1./vx_vol); Ymx(Ygm>0)=Yos(Ygm>0); + Yos = Ymx.*Ycm + (1-Ycm).*T0th(1); spm_smooth(Yos,Yos,.5 + 1./vx_vol); Ymx(Ycm>0)=Yos(Ycm>0); + end + + Ywb = cat_vol_resize(Yw ,'reduceV',vx_volx,res,32,'meanm'); % CSF thr. (minimum to avoid PVE) + Yg = cat_vol_resize(Ymx .* Ygm,'reduceV',vx_volx,res,32,'meanm'); % GM thr. + Yw = cat_vol_resize(Ymx .* Ywm,'reduceV',vx_volx,res,32,'meanm'); % WM thr. and bias correction (Ywme) + Yc = cat_vol_resize(Ymx .* Ycm,'reduceV',vx_volx,res,32,'meanm'); % CSF thr. (minimum to avoid PVE) + Ywn = cat_vol_resize(Ymx .* Ywm,'reduceV',vx_volx,res,32,'meanm'); % for WM noise + Ycn = cat_vol_resize(Ymx .* Ycm,'reduceV',vx_volx,res,32,'meanm'); % for CSF noise + Ygm = cat_vol_resize(Ygm ,'reduceV',vx_volx,res,32,'meanm'); % GM thr. + Ywm = cat_vol_resize(Ywm ,'reduceV',vx_volx,res,32,'meanm'); % WM thr. and bias correction (Ywme) + Ycm = cat_vol_resize(Ycm ,'reduceV',vx_volx,res,32,'meanm'); % WM thr. and bias correction (Ywme) + [Yo,Ym,Yp0,resr] = cat_vol_resize({Ymx,Ym,Yp0},'reduceV',vx_volx,res,32,'meanm'); + resr.vx_volo = vx_vol; vx_vol=resr.vx_red .* resr.vx_volo; + + % only voxel that have multiple inputs + Yc = Yc .* (Ycm>=0.5); Yg = Yg .* (Ygm>=0.5); Yw = Yw .* (Ywm>=0.5); + Ywn = Ywn .* (Ywm>=0.5); Ycn = Ycn .* (Ycm>=0.5); + clear Ycm Ygm Ywm; + + % tissue contrasts (corrected for noise-bias estimated on the BWP) + WMth = cat_stat_nanmedian(Yw(~isnan(Yw(:)) & Yw(:)~=0)); + GMth = cat_stat_nanmedian(Yg(~isnan(Yg(:)) & Yg(:)~=0)) + noise/220 * WMth; + CSFth = cat_stat_nanmedian(Yc(~isnan(Yc(:)) & Yc(:)~=0)) - noise/55 * WMth; + BGth = noise/20 * WMth; + T3th = [CSFth GMth WMth]; + + if 1 % 201901 version + signal = max([WMth,GMth]); + else % maybe more robust 202110 version ? + signal = abs(diff([min([CSFth,BGth]),max([WMth,GMth])])); + end + + % (relative) average tissue intensity of each class + QAS.qualitymeasures.tissue_mn = ([BGth CSFth GMth WMth]); + QAS.qualitymeasures.tissue_mnr = QAS.qualitymeasures.tissue_mn ./ signal; + if WMth > GMth + QAS.qualitymeasures.tissue_weighting = 'T1'; + elseif WMth0.5 & ~isinf(Yp0(:)))); + end + QAS.qualitymeasures.tissue_stdr = QAS.qualitymeasures.tissue_std ./ (WMth-BGth); + + contrast = min(abs(diff(QAS.qualitymeasures.tissue_mn(2:4)))) ./ signal; + QAS.qualitymeasures.background = BGth; + QAS.qualitymeasures.signal = signal; + QAS.qualitymeasures.contrast = contrast * signal; + QAS.qualitymeasures.contrastr = 1/3 - abs(1/3 - contrast) / 2; + + % fprintf('BCGW=%5.3f,%5.3f,%5.3f,%5.3f, WTH=%8.2f CON=%0.3f\n',BGth/max(T3th),T3th/max(T3th),T3th(3),contrast); + + % WM variance only in one direction to avoid WMHs! + rms=1; nb=1; + NCww = nnz(Ywn(:)>0) * prod(vx_vol); + NCwc = nnz(Ycn(:)>0) * prod(vx_vol); + [Yos2,YM2] = cat_vol_resize({Ywn,Ywn>0},'reduceV',vx_vol,2,16,'meanm'); + NCRw = estimateNoiseLevel(Yos2,YM2>0.5,nb,rms) / (signal * contrast); + if BGth<-0.1 && WMth<3, NCRw=NCRw/3; end% MT weighting + clear Yos0 Yos1 Yos2 YM0 YM1 YM2; + + % CSF variance of large ventricle + % for typical T2 images we have too much signal in the CSF and can't use it for noise estimation! + wcth = 200; + if CSFthwcth + [Yos2,YM2] = cat_vol_resize({Ycn,Ycn>0},'reduceV',vx_vol,2,16,'meanm'); + NCRc = estimateNoiseLevel(Yos2,YM2>0.5,nb,rms) / (signal * contrast); + clear Yos0 Yos1 Yos2 YM0 YM1 YM2; + else + NCRc = 0; + NCwc = 0; + end + % 1/sqrt(volume) to compensate for noise differency due to different volumen size. + % Overall there are better chances to correct high resolution noise. + % Nitz W R. Praxiskurs MRT. Page 28. + NCwc = min(wcth,max(0,NCwc-wcth)); NCww = min(wcth,NCww) - NCwc; % use CSF if possible + if NCwc<3*wcth && NCww<10*wcth, NCRc = min(NCRc,NCRw); end + QAS.qualitymeasures.NCR = (NCRw*NCww + NCRc*NCwc)/(NCww+NCwc); + + + % Bias/Inhomogeneity (original image with smoothed WM segment) + QAS.qualitymeasures.ICR = cat_stat_nanstd(Ywb(Yp0(:)>0)) / contrast; + end + + %% marks + QAR = cat_stat_marks('eval',1,QAS); + + % export + if opt.write_xml + QAS.qualityratings = QAR.qualityratings; + QAS.subjectratings = QAR.subjectratings; + QAS.ratings_help = QAR.help; + + cat_io_xml(fullfile(pp0,[opt.prefix ff '.xml']),QAS,'write'); + end + + clear Yi Ym Yo Yos Ybc + clear Ywm Ygm Ycsf Ybg + + end + + if nargout>2, varargout{3} = cat_qa_warnings; end + if nargout>1, varargout{2} = QAR; end + if nargout>0, varargout{1} = QAS; end + +end +%======================================================================= +function def=defaults + % default parameter + def.verb = 2; % verbose level [ 0=nothing | 1=points | 2*=results ] + def.write_csv = 2; % final cms-file [ 0=dont write |1=write | 2=overwrite ] + def.write_xml = 1; % images base xml-file + def.sortQATm = 1; % sort QATm output + def.orgval = 0; % original QAM results (no marks) + def.avgfactor = 2; % + def.prefix = 'cat_'; % intensity scaled image + def.mprefix = 'm'; % prefix of the preprocessed image + def.process = 3; % used image [ 0=T1 | 1=mT1 | 2=avg | 3=both ] + def.calc_MPC = 0; + def.calc_STC = 0; + def.calc_MJD = 0; + def.writeQCseg = 1; + def.method = 'spm'; + def.snspace = [100,7,3]; + def.nogui = exist('XT','var'); + def.MarkColor = cat_io_colormaps('marks+',40); +end + +function noise = estimateNoiseLevel(Ym,YM,r,rms,vx_vol) +% ---------------------------------------------------------------------- +% noise estimation within Ym and YM. +% ---------------------------------------------------------------------- + if ~exist('vx_vol','var') + vx_vol=[1 1 1]; + end + if ~exist('r','var') + r = 1; + else + r = min(10,max(max(vx_vol),r)); + end + if ~exist('rms','var') + rms = 1; + end + + Ysd = cat_vol_localstat(single(Ym),YM,r,4); + noise = cat_stat_nanstat1d(Ysd(YM).^rms,'median').^(1/rms); +end +%======================================================================= +function [res_ECR,segCase,Yp0c,Ygrad] = estimateECR(Ym,Yp0,vx_vol) +%% estimateECR. Quanfify anatomical details by the normalized edge strength. +% +% old pure version for high quality segmentation input that works only well +% for the CAT12 AMAP segmenation. +% +% Extension 202309: Tested at eroded and dilated boundaries positions + + + Ybad = abs(Yp0/3 - Ym) > .5 | isnan(Ym) | isnan(Yp0) | (Yp0==0); + Yp0s = max(2,Yp0+0); spm_smooth(Yp0s,Yp0s,.5 ./ vx_vol); %max(0.4,1.4 - 0.4.*vx_vol)); + Ywmb = Yp0s>2.05 & Yp0s<2.95; + + if 1 + % This sanlm is not working as intended. It is not denoising fully and when I use the + Yms = Ym .* Ywmb; cat_sanlm(Yms,3,1); Ym(Ywmb) = Yms(Ywmb); + else + Yms = Ym .* cat_vol_morph(Ywmb,'d',1); Yms = cat_vol_median3(Yms,Yms>0,Yms>0); Ym(Ywmb) = Yms(Ywmb); + end + Ym(isnan(Ym)) = 0; Ym = max(2/3,min(1,Ym)); %spm_smooth(Ym,Ym,.4); + + Ygrad = cat_vol_grad( Ym , vx_vol .^.5 ); % RD20241106: original ... the sqrt helps to bring + Ygrad(cat_vol_morph(Ybad,'d',1)) = nan; % correct bad areas + res_ECRo = cat_stat_nanmedian(Ygrad(Ywmb(:))); + clear Ywmb + Yp0(Ybad) = nan; + + %% == EXTENSION 202309 == + % * test for segmentation errors by using gray-scale erosion + % * if the WM was overestimated than use the new boundary and export + Yp0e = cat_vol_morph(max(1,Yp0),'gerode'); + Ywmeb = Yp0e>2.05 & Yp0e<2.95 & ~Ybad; + Ywmebm = Yp0 >2.475 & Yp0e<2.525 & ~Ybad; + res_ECRe = cat_stat_nanmedian(Ygrad(Ywmeb(:))); clear Ywmeb + res_ECRem = cat_stat_nanmedian(Ygrad(Ywmebm(:))); clear Ywmebm + [res_ECR,segCase] = max([ res_ECRo , res_ECRem, res_ECRe]); + + test2 = 1; + Yp0c = Yp0; + if segCase == 1 && ( max(res_ECRe,res_ECRem) * 1.05 < res_ECR ) + %% in case of no WM overestimation test for underestimation + Yp0d = cat_vol_morph(Yp0,'gdilate'); + Ywmdb = Yp0d>2.05 & Yp0d<2.95 & Yp0>=1.75 & ~Ybad; + Ywmdbm = Yp0d>2.475 & Yp0 <2.525 & Yp0>=1.75 & ~Ybad; + res_ECRd = cat_stat_nanmedian(Ygrad(Ywmdb(:))); clear Ywmdb + res_ECRdm = cat_stat_nanmedian(Ygrad(Ywmdbm(:))); clear Ywmdbm + + [res_ECR,segCase] = max([ res_ECRo , res_ECRe, res_ECRe, res_ECRe, res_ECRe, res_ECRdm, res_ECRd]); + + % corrected segmentation + if test2 && segCase >= 6 + Yp0d2 = cat_vol_morph(Yp0d,'gdilate'); + Ywmdb = Yp0d2>2.05 & Yp0d2<2.95 & Yp0>=1.75 & ~Ybad; + Ywmdbm = Yp0d2>2.475 & Yp0d <2.525 & Yp0>=1.75 & ~Ybad; + res_ECRd2 = cat_stat_nanmedian(Ygrad(Ywmdb(:))); clear Ywmdb + res_ECRd2m = cat_stat_nanmedian(Ygrad(Ywmdbm(:))); clear Ywmdbm + [res_ECR,segCase] = max([ res_ECRo , res_ECRe, res_ECRe, res_ECRe, ... + res_ECRe, res_ECRdm, res_ECRd, res_ECRd2m, res_ECRd2]); + end + if segCase >=6 && segCase <= 7 + Yp0c(Yp0>=2) = Yp0d(Yp0>=2); + elseif test2 && segCase >7 + Yp0c(Yp0>=2) = Yp0d2(Yp0>=2); + end + else + if test2 + Yp0e2 = cat_vol_morph(Yp0e,'gerode'); + Ywmeb = Yp0e2>2.05 & Yp0e2<2.95 & ~Ybad; + Ywmebm = Yp0e >2.475 & Yp0e2<2.525 & ~Ybad; + res_ECRe2 = cat_stat_nanmedian(Ygrad(Ywmeb(:))); % & Yb(:)) + res_ECRe2m = cat_stat_nanmedian(Ygrad(Ywmebm(:))); % & Yb(:)) + + [res_ECR,segCase] = max([ res_ECRo , res_ECRem, res_ECRe, res_ECRe2m, res_ECRe2]); + end + + % corrected segmentation + if segCase >=2 && segCase <= 3 + Yp0c(Yp0>2) = Yp0e(Yp0>2); + elseif test2 && segCase > 3 + Yp0c(Yp0>2) = Yp0e2(Yp0>2); + end + end + +end +%======================================================================= +function [FEC,WMarea] = estimateFEC(Yp0,vx_vol,Ymm,V,machingcubes) +%estimateFEC. Fast Euler Characteristic (FEC) + + if ~exist('machingcubes','var'), machingcubes = 1; end + Ymsr = (Ymm*3); + %spm_smooth(Ymsr,Ymsr,max(0.3,1.7 - 0.7*vx_vol)); %1.6 - 0.6.*vx_vol ... 1.8 - 0.7.*vx_vol + spm_smooth(Ymsr,Ymsr,max(0.2,1.4 - 0.6*vx_vol)); + + app = 1; + if app == 1 + sth = 0.25:0.125/2:0.5; % two levels for 5 class AMAP + if all(vx_vol<1.5) + Ymsr = max(0,max(Ymsr,cat_vol_localstat(Ymsr,Yp0>2,1,3)) - 2); % ######## + else + Ymsr = max(0,Ymsr - 2); + end + % Ymsr = max(0,cat_vol_localstat(Ymsr,Yp0>0.5,1,3) - 2); + elseif app == 2 + sth = .5; + Ymsr = cat_vol_median3(Yp0,Yp0>=2,Yp0>1); + [Ygmt,Ymsr] = cat_vol_pbtsimple(Ymsr,vx_vol,... + struct('levels',1,'extendedrange',0,'gyrusrecon',0,'keepdetails',0,'sharpening',0)); + else + % FEC by creating of the WM like brain tissue of the full brain. + if isempty(Ymm) % use the segmentation works very well + sth = 0.25:0.5:0.75; % two levels for 5 class AMAP + Ymsr = Ymsr - 2; + else % using raw data not realy + sth = 0.25:0.25:0.75; + Ymsr = max(-2,(Ymm .* (smooth3(Ymsr)>1) * 3) - 2); + end + end + Ymsr(Ymsr>sth(1)/2 & ~cat_vol_morph(Ymsr> sth(1)/2,'l')) = 0; + + % light denoising of maximum filter + %spm_smooth(Ymsr,Ymsr,.4./vx_vol); + Ymsr(Yp0==0) = nan; + + % use 2 mm is more robust (accurate in a sample) + smeth = 1; + if smeth==1 + [Ymsr0,resYp0] = cat_vol_resize(Ymsr,'reduceV',vx_vol,2,32,'max'); + Ymsr = Ymsr0 + cat_vol_resize(Ymsr,'reduceV',vx_vol,2,32,'meanm'); + elseif smeth==2 + spm_smooth(Ymsr , Ymsr , 2 - vx_vol); V.dim = size(Ymsr); + Ymsr = single(cat_vol_resize(Ymsr,'interphdr',V,2,1)); + resYp0.vx_volr = [2 2 2]; + else + % this is + spm_smooth(Ymsr,Ymsr,2 ./ vx_vol); % not required + resYp0.vx_volr = vx_vol; + end + + + EC = zeros(size(sth)); area = EC; + for sthi = 1:numel(sth) + % remove other objects and holes + if app == 2 + Ymsr(Ymsr> sth(sthi) & ~cat_vol_morph(Ymsr> sth(sthi),'lo',1,vx_vol)) = sth(sthi) - 0.01; % avoid BVs (eg. in ABIDE2) + else + Ymsr(Ymsr> sth(sthi) & ~cat_vol_morph(Ymsr> sth(sthi),'l')) = sth(sthi) - 0.01; % avoid BVs (eg. in ABIDE2) + end + Ymsr(Ymsr<=sth(sthi) & ~cat_vol_morph(Ymsr<=sth(sthi),'l')) = sth(sthi) + 0.01; + + if machingcubes + % faster binary approach on the default resolution, quite similar result + txt = evalc('[~,faces,vertices] = cat_vol_genus0(Ymsr,sth(sthi),1);'); + CS = struct('faces',faces,'vertices',vertices); + else + % slower but finer matlab isosurface + CS = isosurface(Ymsr,sth(sthi)); + end + if numel(CS.vertices)>0 + CS.vertices = CS.vertices .* repmat(resYp0.vx_volr,size(CS.vertices,1),1); + EC(sthi) = ( size(CS.vertices,1) + size(CS.faces,1) - size(spm_mesh_edges(CS),1) - 2) + 2; + area(sthi) = spm_mesh_area(CS) / 100; % cm2 + EC(sthi) = EC(sthi); + else + area(sthi) = nan; + EC(sthi) = nan; + end + end + + FEC = cat_stat_nanmean(abs(EC - 2) + 2) / log(area(1)/2500 + 1); % defined on the seg-error phantom + FEC = (FEC.^.5)*10; + WMarea = area(1); +end +%======================================================================= + +%======================================================================= +function [res_ECR,segCase,Yp0c,Ygrad] = estimateECR0(Ym,Yp0,vx_vol) +%% estimateECR. Quanfify anatomical details by the normalized edge strength. +% +% old pure version for high quality segmentation input that works only well +% for the CAT12 AMAP segmenation. +% +% Extension 202309: Tested at eroded and dilated boundaries positions + +% extend step by step by some details (eg. masking of problematic regions +%& Ygrad(:)<1/3 +% Yb = cat_vol_morph(cat_vol_morph(Yp0>2,'l',[10 0.1]),'d',2); + + Yb = Yp0>0; + Yp0c = Yp0; + Ygrad = cat_vol_grad(max(2/3,min(1,Ym) .* Yb ) , vx_vol ); + Ywmb = Yp0>2.05 & Yp0<2.95; + res_ECRo = cat_stat_nanmedian(Ygrad(Ywmb(:))); + clear Ywmb + + + %% == EXTENSION 202309 == + % * test for segmentation errors by using gray-scale erosion + % * if the WM was overestimated than use the new boundary and export + Yp0e = cat_vol_morph(max(1,Yp0),'gerode'); + Ywmeb = Yp0e>2.05 & Yp0e<2.95; + Ywmebm = Yp0 >2.475 & Yp0e<2.525; + res_ECRe = cat_stat_nanmedian(Ygrad(Ywmeb(:))); clear Ywmeb + res_ECRem = cat_stat_nanmedian(Ygrad(Ywmebm(:))); clear Ywmebm + [res_ECR,segCase] = max([ res_ECRo , res_ECRem, res_ECRe]); + + test2 = 1; + if segCase == 1 && ( max(res_ECRe,res_ECRem) * 1.05 < res_ECR ) + %% in case of no WM overestimation test for underestimation + Yp0d = cat_vol_morph(Yp0,'gdilate'); + Ywmdb = Yp0d>2.05 & Yp0d<2.95 & Yp0>=1.75; + Ywmdbm = Yp0d>2.475 & Yp0 <2.525 & Yp0>=1.75; + res_ECRd = cat_stat_nanmedian(Ygrad(Ywmdb(:))); clear Ywmdb + res_ECRdm = cat_stat_nanmedian(Ygrad(Ywmdbm(:))); clear Ywmdbm + + [res_ECR,segCase] = max([ res_ECRo , res_ECRe, res_ECRe, res_ECRe, res_ECRe, res_ECRdm, res_ECRd]); + + % corrected segmentation + if test2 && segCase >= 6 + Yp0d2 = cat_vol_morph(Yp0d,'gdilate'); + Ywmdb = Yp0d2>2.05 & Yp0d2<2.95 & Yp0>=1.75; + Ywmdbm = Yp0d2>2.475 & Yp0d <2.525 & Yp0>=1.75; + res_ECRd2 = cat_stat_nanmedian(Ygrad(Ywmdb(:))); clear Ywmdb + res_ECRd2m = cat_stat_nanmedian(Ygrad(Ywmdbm(:))); clear Ywmdbm + [res_ECR,segCase] = max([ res_ECRo , res_ECRe, res_ECRe, res_ECRe, ... + res_ECRe, res_ECRdm, res_ECRd, res_ECRd2m, res_ECRd2]); + end + if segCase >=6 && segCase <= 7 + Yp0c(Yp0>=2) = Yp0d(Yp0>=2); + elseif test2 && segCase >7 + Yp0c(Yp0>=2) = Yp0d2(Yp0>=2); + end + else + if test2 + Yp0e2 = cat_vol_morph(Yp0e,'gerode'); + Ywmeb = Yp0e2>2.05 & Yp0e2<2.95; + Ywmebm = Yp0e >2.475 & Yp0e2<2.525; + res_ECRe2 = cat_stat_nanmedian(Ygrad(Ywmeb(:))); % & Yb(:)) + res_ECRe2m = cat_stat_nanmedian(Ygrad(Ywmebm(:))); % & Yb(:)) + + [res_ECR,segCase] = max([ res_ECRo , res_ECRem, res_ECRe, res_ECRe2m, res_ECRe2]); + end + + % corrected segmentation + if segCase >=2 && segCase <= 3 + Yp0c(Yp0>2) = Yp0e(Yp0>2); + elseif test2 && segCase > 3 + Yp0c(Yp0>2) = Yp0e2(Yp0>2); + end + end + + + + + +%% == EXTENSION 202309 CSF == +if 1 + Ygradc = cat_vol_grad(min(1,max(2/3,Ym) .* Yb ) , vx_vol ); + + + % * test for segmentation errors by using gray-scale erosion + % * if the WM was overestimated than use the new boundary and export + %Yp0e = cat_vol_morph(Yp0,'gerode'); + Ycmeb = Yp0e>1.05 & Yp0e<1.95 & Yp0>=1; + Ycmebm = Yp0 >1.475 & Yp0e<1.525 & Yp0>=1; + res_ECRe = cat_stat_nanmedian(Ygradc(Ycmeb(:))); clear Ywmeb + res_ECRem = cat_stat_nanmedian(Ygradc(Ycmebm(:))); clear Ywmebm + [res_ECRC,segCaseC] = max([ res_ECRo , res_ECRem, res_ECRe]); + + test2 = 0; + if segCaseC == 1 && ( max(res_ECRe,res_ECRem) * 1.05 < res_ECRC ) + %% in case of no CSF underestimation test for overestimation + if ~exist('Yp0d','var') + Yp0d = cat_vol_morph(Yp0,'gdilate'); + end + Ycmdb = Yp0d>1.05 & Yp0d<1.95 & Yp0<2.25 & Yp0>=1; + Ycmdbm = Yp0d>1.475 & Yp0 <1.525 & Yp0<2.25 & Yp0>=1; + res_ECRd = cat_stat_nanmedian(Ygradc(Ycmdb(:))); clear Ywmdb + res_ECRdm = cat_stat_nanmedian(Ygradc(Ycmdbm(:))); clear Ywmdbm + + [res_ECRC,segCaseC] = max([ res_ECRo , res_ECRe, res_ECRe, res_ECRe, res_ECRe, res_ECRdm, res_ECRd]); + + % corrected segmentation + if test2 && segCase >= 6 + if ~exist('Yp0d2','var') + Yp0d2 = cat_vol_morph(Yp0d,'gdilate'); + end + Ywmdb = Yp0d2>2.05 & Yp0d2<2.95 & Yp0>=1.75; + Ywmdbm = Yp0d2>2.475 & Yp0d <2.525 & Yp0>=1.75; + res_ECRd2 = cat_stat_nanmedian(Ygradc(Ywmdb(:))); clear Ywmdb + res_ECRd2m = cat_stat_nanmedian(Ygradc(Ywmdbm(:))); clear Ywmdbm + [res_ECR,segCase] = max([ res_ECRo , res_ECRe, res_ECRe, res_ECRe, ... + res_ECRe, res_ECRdm, res_ECRd, res_ECRd2m, res_ECRd2]); + end + if segCase >=6 && segCase <= 7 + Yp0c(Yp0>=1 & Yp0<2) = Yp0d(Yp0>=1 & Yp0<2); + elseif test2 && segCase >7 + Yp0c(Yp0>=1 & Yp0<2) = Yp0d2(Yp0>=1 & Yp0<2); + end + else + if test2 + if ~exist('Yp0e2','var') + Yp0e2 = cat_vol_morph(Yp0e,'gerode'); + end + Ywmeb = Yp0e2>2.05 & Yp0e2<2.95; + Ywmebm = Yp0e >2.475 & Yp0e2<2.525; + res_ECRe2 = cat_stat_nanmedian(Ygradc(Ywmeb(:))); % & Yb(:)) + res_ECRe2m = cat_stat_nanmedian(Ygradc(Ywmebm(:))); % & Yb(:)) + + [res_ECR,segCase] = max([ res_ECRo , res_ECRem, res_ECRe, res_ECRe2m, res_ECRe2]); + end + + % corrected segmentation + if segCaseC >=2 && segCaseC <= 3 + Yp0c(Yp0>1 & Yp0<2) = Yp0e(Yp0>1 & Yp0<2); + elseif test2 && segCaseC > 3 + Yp0c(Yp0>1 & Yp0<2) = Yp0e2(Yp0>1 & Yp0<2); + end + end +end + + +end + +function res_ECR = estimateECR0old(Ym,Yp0,vx_vol) +%% estimateECR. Quanfify anatomical details by the normalized edge strength. +% +% old pure version for high quality segmentation input that works only well +% for the CAT12 AMAP segmenation + Ybad = abs(Yp0/3 - Ym) > .5 | isnan(Ym) | isnan(Yp0) | (Yp0<=0.5) | (Ym<0.5/3); + [YD,YI] = cat_vbdist(single(~Ybad),Ybad & cat_vol_morph(~Ybad,'d',1,vx_vol)); Ym = Ym(YI); Yp0 = Yp0(YI); + + % define boundfary Ygw and save WM + Ywe = cat_vol_morph(Yp0>2.5,'e'); + Ygw = cat_vol_morph(Yp0>2.5,'d') & ~Ywe; + + Ygrad = cat_vol_grad(max(2/3,min(1,Ym) ) , vx_vol .^ .5 ); % the power<1 is to balance the rating of low-res and interpolated data + Ygrad(Ybad) = nan; + Ygradgw = cat_vol_localstat(Ygrad,Ygw,1,3); % get maximum edge in the boundary area + Yws = cat_vol_morph(Ywe,'e',sum(Ywe(:))>1000); %,vx_vol); % extend WM in highres data to reduce issues with interpolation/smoothing + Ygradwe = cat_stat_nanstd(Ygrad(Yws(:) & Ym(:)>.95)); + res_ECR = (cat_stat_nanmedian(Ygradgw(Ygw(:))) - .7*Ygradwe / prod(vx_vol .^ 2)) * 0.8; +return + + %% == EXTENSION 202309 == + % * test for segmentation errors by using gray-scale erosion + % * if the WM was overestimated than use the new boundary and export + Yp0e = cat_vol_morph(max(1,Yp0),'gerode'); + Ywmeb = Yp0e>2.05 & Yp0e<2.95 & ~Ybad; + Ywmebm = Yp0 >2.475 & Yp0e<2.525 & ~Ybad; + res_ECRe = cat_stat_nanmedian(Ygrad(Ywmeb(:))); clear Ywmeb + res_ECRem = cat_stat_nanmedian(Ygrad(Ywmebm(:))); clear Ywmebm + [res_ECR,segCase] = max([ res_ECRo , res_ECRem, res_ECRe]); + + test2 = 0; + Yp0c = Yp0; + if segCase == 1 && ( max(res_ECRe,res_ECRem) * 1.05 < res_ECR ) + %% in case of no WM overestimation test for underestimation + Yp0d = cat_vol_morph(Yp0,'gdilate'); + Ywmdb = Yp0d>2.05 & Yp0d<2.95 & Yp0>=1.75 & ~Ybad; + Ywmdbm = Yp0d>2.475 & Yp0 <2.525 & Yp0>=1.75 & ~Ybad; + res_ECRd = cat_stat_nanmedian(Ygrad(Ywmdb(:))); clear Ywmdb + res_ECRdm = cat_stat_nanmedian(Ygrad(Ywmdbm(:))); clear Ywmdbm + + [res_ECR,segCase] = max([ res_ECRo , res_ECRe, res_ECRe, res_ECRe, res_ECRe, res_ECRdm, res_ECRd]); + + % corrected segmentation + if test2 && segCase >= 6 + Yp0d2 = cat_vol_morph(Yp0d,'gdilate'); + Ywmdb = Yp0d2>2.05 & Yp0d2<2.95 & Yp0>=1.75 & ~Ybad; + Ywmdbm = Yp0d2>2.475 & Yp0d <2.525 & Yp0>=1.75 & ~Ybad; + res_ECRd2 = cat_stat_nanmedian(Ygrad(Ywmdb(:))); clear Ywmdb + res_ECRd2m = cat_stat_nanmedian(Ygrad(Ywmdbm(:))); clear Ywmdbm + [res_ECR,segCase] = max([ res_ECRo , res_ECRe, res_ECRe, res_ECRe, ... + res_ECRe, res_ECRdm, res_ECRd, res_ECRd2m, res_ECRd2]); + end + if segCase >=6 && segCase <= 7 + Yp0c(Yp0>=2) = Yp0d(Yp0>=2); + elseif test2 && segCase >7 + Yp0c(Yp0>=2) = Yp0d2(Yp0>=2); + end + else + if test2 + Yp0e2 = cat_vol_morph(Yp0e,'gerode'); + Ywmeb = Yp0e2>2.05 & Yp0e2<2.95 & ~Ybad; + Ywmebm = Yp0e >2.475 & Yp0e2<2.525 & ~Ybad; + res_ECRe2 = cat_stat_nanmedian(Ygrad(Ywmeb(:))); + res_ECRe2m = cat_stat_nanmedian(Ygrad(Ywmebm(:))); + + [res_ECR,segCase] = max([ res_ECRo , res_ECRem, res_ECRe, res_ECRe2m, res_ECRe2]); + end + + % corrected segmentation + if segCase >=2 && segCase <= 3 + Yp0c(Yp0>2) = Yp0e(Yp0>2); + elseif test2 && segCase > 3 + Yp0c(Yp0>2) = Yp0e2(Yp0>2); + end + end + +end ","MATLAB" +"Neurology","ChristianGaser/cat12","cat_surf_smoothr.c",".c","9691","257","/* + * partial_smooth_roi.c — Laplacian smoothing limited to a vertex ROI + * + * Updated July 2025 so that it no longer crashes when the input mesh + * stores vertices as *single* or faces as *int32/uint32* arrays. + * Accepted classes now: + * • vertices : double or single, size [N×3] + * • faces : double | single | int32 | uint32, size [M×3] + * + * If an unsupported class is supplied, the MEX throws an informative + * error instead of seg‑faulting. + * + * Usage + * ----- + * S2 = partial_smooth_roi(S, ROI [, iterations] [, lambda]); + * + * S.vertices – [N×3] double|single + * S.faces – [M×3] double|single|int32|uint32 (1‑based) + * ROI – logical|numeric [N×1] mask of vertices to move + * iterations – integer ≥1 (default 10) + * lambda – relaxation 0<λ≤1 (default 0.5) + * + * Compilation (tested R2024a macOS / Apple‑silicon): + * mex -largeArrayDims partial_smooth_roi.c + * + * Author: ChatGPT‑o3 | MIT licence + */ +#include ""mex.h"" +#include +#include +#include +#include + +#ifndef MAX +# define MAX(a,b) ((a)>(b)?(a):(b)) +#endif + +/* =================== ADJACENCY LIST =================================== */ +typedef struct { + mwSize *idx; /* concatenated neighbour indices */ + mwSize *head; /* head[i] = start offset of vertex‑i list */ + mwSize *deg; /* deg[i] = number of neighbours */ +} adjacency_t; + +static void free_adjacency(adjacency_t *A) +{ + if (A->idx) mxFree(A->idx); + if (A->head) mxFree(A->head); + if (A->deg) mxFree(A->deg); + memset(A,0,sizeof(*A)); +} + +/* Utility: fetch 0‑based index from faces matrix at linear offset k */ +static mwSize get_face_idx(const void *F, mxClassID c, mwSize k) +{ + switch (c) { + case mxDOUBLE_CLASS: return (mwSize)(((double *)F)[k]) - 1U; + case mxSINGLE_CLASS: return (mwSize)(((float *)F)[k]) - 1U; + case mxINT32_CLASS: return (mwSize)(((int32_T *)F)[k]) - 1U; + case mxUINT32_CLASS: return (mwSize)(((uint32_T*)F)[k]) - 1U; + default: return (mwSize)-1; /* should never happen */ + } +} + +static void build_adjacency(const mxArray *facesPr, mwSize nV, adjacency_t *A) +{ + const mwSize nF = mxGetM(facesPr); /* faces are [M×3] */ + const void *F = mxGetData(facesPr); + const mxClassID cls = mxGetClassID(facesPr); + + /* ---------- allocate degree & head arrays ---------- */ + A->deg = (mwSize*)mxCalloc(nV, sizeof(mwSize)); + A->head = (mwSize*)mxCalloc(nV + 1, sizeof(mwSize)); + + /* ---------- first pass: degree count --------------- */ + for (mwSize f = 0; f < nF; ++f) { + mwSize off = f; /* row index */ + mwSize v0 = get_face_idx(F, cls, off); + mwSize v1 = get_face_idx(F, cls, off + nF); + mwSize v2 = get_face_idx(F, cls, off + 2*nF); + if (v0>=nV || v1>=nV || v2>=nV) + mexErrMsgIdAndTxt(""partial_smooth_roi:badFace"", + ""Face index out of bounds (are faces 1‑based?)""); + A->deg[v0]+=2; A->deg[v1]+=2; A->deg[v2]+=2; + } + + /* ---------- prefix sum for heads ------------------- */ + mwSize total = 0; + for (mwSize i=0;ihead[i] = total; + total += A->deg[i]; + } + A->head[nV] = total; + A->idx = (mwSize*)mxCalloc(total, sizeof(mwSize)); + + /* reuse deg[] as write‑cursor */ + memset(A->deg, 0, nV*sizeof(mwSize)); + + /* ---------- second pass: fill neighbour indices ---- */ + for (mwSize f = 0; f < nF; ++f) { + mwSize off = f; + mwSize v0 = get_face_idx(F, cls, off); + mwSize v1 = get_face_idx(F, cls, off + nF); + mwSize v2 = get_face_idx(F, cls, off + 2*nF); + + /* v0 <‑‑> v1 */ + A->idx[A->head[v0] + A->deg[v0]++] = v1; + A->idx[A->head[v1] + A->deg[v1]++] = v0; + /* v1 <‑‑> v2 */ + A->idx[A->head[v1] + A->deg[v1]++] = v2; + A->idx[A->head[v2] + A->deg[v2]++] = v1; + /* v2 <‑‑> v0 */ + A->idx[A->head[v2] + A->deg[v2]++] = v0; + A->idx[A->head[v0] + A->deg[v0]++] = v2; + } +} + +/* =================== GATEWAY =========================================== */ +void mexFunction(int nlhs, mxArray *plhs[], + int nrhs, const mxArray *prhs[]) +{ + if (nrhs < 2) + mexErrMsgIdAndTxt(""partial_smooth_roi:nargin"", + ""Usage: S2 = partial_smooth_roi(S, ROI [,iter] [,lambda])""); + + /* ---- Input structure S ---- */ + if (!mxIsStruct(prhs[0])) + mexErrMsgIdAndTxt(""partial_smooth_roi:invalidS"",""First input must be a struct.""); + const mxArray *vField = mxGetField(prhs[0],0,""vertices""); + const mxArray *fField = mxGetField(prhs[0],0,""faces""); + if (!vField || !fField) + mexErrMsgIdAndTxt(""partial_smooth_roi:missingFields"", + ""Struct S needs fields 'vertices' and 'faces'.""); + + /* ---- validate vertex class ---- */ + const mxClassID vCls = mxGetClassID(vField); + if (vCls!=mxDOUBLE_CLASS && vCls!=mxSINGLE_CLASS) + mexErrMsgIdAndTxt(""partial_smooth_roi:vertClass"", + ""Vertices must be double or single.""); + + /* ---- validate face class ---- */ + const mxClassID fCls = mxGetClassID(fField); + if (fCls!=mxDOUBLE_CLASS && fCls!=mxSINGLE_CLASS && + fCls!=mxINT32_CLASS && fCls!=mxUINT32_CLASS) + mexErrMsgIdAndTxt(""partial_smooth_roi:faceClass"", + ""Faces must be double, single, int32 or uint32.""); + + /* ---- geometry sizes ---- */ + const mwSize nV = mxGetM(vField); + if (mxGetN(vField)!=3) + mexErrMsgIdAndTxt(""partial_smooth_roi:vertDim"",""Vertices must be [N×3].""); + + if (mxGetM(prhs[1])!=nV) + mexErrMsgIdAndTxt(""partial_smooth_roi:roiSize"", + ""ROI must have %llu rows (one per vertex)"", (unsigned long long)nV); + + /* ---- parameters ---- */ + int iterations = (nrhs>=3) ? (int)mxGetScalar(prhs[2]) : 10; + if (iterations < 1) iterations = 1; + double lambda = (nrhs>=4) ? mxGetScalar(prhs[3]) : 0.5; + if (lambda<=0 || lambda>1) lambda = 0.5; + + /* ---- build adjacency once ---- */ + adjacency_t A = {0}; + build_adjacency(fField, nV, &A); + + /* ---- working buffers (double) ---- */ + double *curr = (double*)mxMalloc(nV*3*sizeof(double)); + double *next = (double*)mxMalloc(nV*3*sizeof(double)); + + /* copy vertices into curr (promote to double if necessary) */ + if (vCls==mxDOUBLE_CLASS) { + memcpy(curr, mxGetPr(vField), nV*3*sizeof(double)); + } else { /* single -> double */ + const float *Vs = (float*)mxGetData(vField); + for (mwSize i=0;i10000) + #endif + for (mwSize v=0; v 0 && isempty(data)) + data = spm_select([1 Inf],{'txt','image','gii','(lh|rh).*'},'Select images to work on'); +end + +if isempty(data), error('no input images specified'), end + +if ischar(data) + n = size(data,1); +else + if ~iscell(data) + [n, ind] = min(size(data)); + if n==1 + data0{1} = data(:); + else + if ind == 2 + data = data'; + end + for i=1:n + data0{i} = data(i,:); + end + end + data = data0; clear data0; + end + n = numel(data); +end + +def.color = cat_io_colormaps('nejm',n); +def.norm_frequency = true; +def.winsize = [750 500]; +def.xrange = []; +def.xlim = []; +def.ylim = []; +def.dist = 'kernel'; +def.mean = n > 12; + +opt = cat_io_checkinopt(opt,def); + +if ~isempty(opt.dist) && exist('fitdist') ~= 2 + fprintf('Function fitdist not found: Disable curve fitting.'); + opt.dist = ''; +end + +% ignore NaNs +dropNaNs = @(x) double(x(~isnan(x))); + +mn = zeros(n,1); +mx = zeros(n,1); +cdata = cell(n,1); + +for i = 1:n + + if ~ischar(data) + cdata{i} = single(data{i}(:)); + mn(i) = min(data{i}(:)); + mx(i) = max(data{i}(:)); + else + + fname = deblank(data(i,:)); + [pth,nam,ext] = spm_fileparts(fname); + [pth2,nam2,ext2] = spm_fileparts(nam); + + % 0 - nii.gz; 1 - txt; 2 - volume; 3 - mesh; 4 - Freesurfer + if strcmp(ext,'.gz') && strcmp(ext2,'.nii') + filetype = 0; + elseif strcmp(ext,'.txt') + filetype = 1; + elseif strcmp(ext,'.nii') || strcmp(ext,'.img') + filetype = 2; + elseif strcmp(ext,'.gii') + filetype = 3; + else + filetype = 4; + end + + switch filetype + case 0 + [cdata{i}, mn(i), mx(i)] = loadsingle(spm_vol(fname)); + case 1 + [cdata{i}, mn(i), mx(i)] = loadsingle_txt(fname); + case 2 + [cdata{i}, mn(i), mx(i)] = loadsingle(nifti(fname)); + case 3 + [cdata{i}, mn(i), mx(i)] = loadsingle(gifti(fname)); + case 4 + try + [cdata{i}, mn(i), mx(i)] = loadsingleFS(fname); + catch + error('Unknown data format'); + end + end + end +end + +if n == 2 + if (length(cdata{1}(:)) == length(cdata{2}(:)) && (size(cdata{1},1) == size(cdata{2},1)) && (size(cdata{1},2) == size(cdata{2},2))) + + fig = figure(11); + set(fig,'MenuBar', 'none', 'Position',[100,0,500,500]); + + cat_plot_scatter(cdata{1}(:), cdata{2}(:), 'fig', fig); + + ax = gca; + set(ax,'PlotBoxAspectRatioMode','auto','XDir','normal','YDir','normal'); + + title('Histogram','Parent',ax); + if ischar(data(1,:)) + xlabel(spm_str_manip(data(1,:),'a90'),'Parent',ax,'Interpreter','none'); + ylabel(spm_str_manip(data(2,:),'a90'),'Parent',ax,'Interpreter','none'); + else + xlabel('Data 1','Parent',ax,'Interpreter','none'); + ylabel('Data 2','Parent',ax,'Interpreter','none'); + end + if ischar(data(1,:)) && (filetype == 2) && (size(cdata{1},2) ~= 1) && (size(cdata{2},2) ~= 1) + + d = double(cdata{2}) - double(cdata{1}); + d(isnan(d)) = 0; + + d1 = squeeze(sum(d,1)); + d2 = squeeze(sum(d,2)); + d3 = squeeze(sum(d,3)); + + mx1 = max(abs(d(:))); + + if mx1 > 0.0 + + fprintf('Blue: i1>i2; Red: i2>i1\ni1 = %s\ni2 = %s\n',data(1,:),data(2,:)); + fig = figure(12); + cm = hot(64); + set(fig,'Menubar','none'); + colormap([1-(cm); cm]) + + mx2 = max(abs([d1(:); d2(:); d3(:)])); + if mx2 == 0, mx2 = eps; end + + subplot(2,2,1) + imagesc(rot90(d1),[-mx2 mx2]) + axis off image + + subplot(2,2,2) + imagesc(rot90(d2),[-mx2 mx2]) + axis off image + + subplot(2,2,3) + imagesc(d3,[-mx2 mx2]) + axis off image + + subplot(2,2,4) + colorbar + set(gca,'CLim',[-mx1 mx1]); + axis off image + else + disp('Images are identical!'); + end + % display surface rendering of difference + elseif ischar(data(1,:)) && filetype == 3 + d = double(cdata{2}) - double(cdata{1}); + d(isnan(d)) = 0; + sinfo = cat_surf_info(data(1,:)); + Pmesh = ''; + if ~isempty(strfind(sinfo.Pmesh,'templates_surfaces')) + Pmesh = sinfo.Pmesh; + elseif sinfo.resampled + if sinfo.resampled_32k + templates_surfaces = 'templates_surfaces_32k'; + else + templates_surfaces = 'templates_surfaces'; + end + Pmesh = fullfile(fileparts(mfilename('fullpath')),templates_surfaces,[sinfo.side '.central.freesurfer.gii']); + end + if exist(Pmesh,'file') + % scale in 2..98% range + range = cat_vol_iscaling(d,[0.02 0.98]); + absmx = max(abs(range)); + S = gifti(Pmesh); + cat_surf_render2(struct('vertices',S.vertices,'faces',S.faces,'cdata',d)); + cat_surf_render2('colorbar'); + cat_surf_render2('view','top'); + cat_surf_render2('clim',[-absmx absmx]); + fprintf('Blue: i1>i2; Red: i2>i1\ni1 = %s\ni2 = %s\n',data(1,:),data(2,:)); + end + end + else + disp('No 2D histogram plotted because size differs between data.'); + end +end + +if isempty(opt.xrange) + X0 = linspace(min(mn), max(mx), max(min(round(numel(dropNaNs(cdata{1}))/100),500),10)); +elseif numel(opt.xrange) == 2 + X0 = linspace(opt.xrange(1), opt.xrange(2), 500); +else + error('Parameter xrange does not consist of two entries'); +end + +fig = figure; +set(fig,'MenuBar', 'none', 'Position',[100, 0, opt.winsize]); + +% get shorter filenames +if iscellstr(data) + fname_tmp = struct('s','','e','','m',num2str(1:numel(data))); +else + if isnumeric(data) || (iscell(data) && isnumeric(data{1})) + % call with direct data input + % (eg. from cat_surf_render2 menu > surface information > histogram) + fname_tmp = 'data'; + else + [~, fname_tmp] = spm_str_manip(data,'C'); + end +end + +y_all = []; +for j = 1:n + y = dropNaNs(cdata{j}); + if ~isempty(opt.dist) + n = numel(y); + H0 = hist(y,X0); + pd = fitdist(y,opt.dist); + + [bincounts,binedges] = histcounts(y,X0); + + % Normalize the density to match the total area of the histogram + Hfit(j,:) = n * (binedges(2)-binedges(1)) * pdf(pd,X0); + else + H0 = hist(y,X0); + Hfit(j,:) = H0; + y_all = [y_all; y]; + end + + if opt.norm_frequency + if ~isempty(opt.dist) + Hfit(j,:) = Hfit(j,:)/sum(H0); + end + H0 = H0/sum(H0); + end + H(j,:) = H0; + X(j,:) = X0; + if ischar(data) + try + if ~isempty(fname_tmp) + legend_str{j} = fname_tmp.m{j}; + length_leg = max(cellfun(@length,fname_tmp.m)); + else + legend_str{j} = char(spm_str_manip(data(j,:),'a90')); + length_leg = size(char(spm_str_manip(data,'a90'),2)); + end + catch + legend_str{j} = sprintf('%d',j); + length_leg = 1; + end + + % give some specific output for (normally distributed) T-values or + % effect size (D) + [pth,nam] = spm_fileparts(deblank(data(j,:))); + spmT_found = ~isempty(strfind(nam,'spmT')) || strcmp(nam(1),'D'); + mn = mean(y); + sd = std(y); + ES = mn/sd; + if spmT_found + TH5 = X0(min(find(cumsum(H0)/sum(H0) > 0.95))); + fprintf('%s\tmean=%g\tSD=%g\tES=%g\tTH5=%g\n',legend_str{j},mn,sd,ES,TH5); + legend_str{j} = sprintf('TH5=%.4f %s',TH5,legend_str{j}); + out2(j) = struct('name',legend_str{j},'mean',mn,'std',sd,'ES',ES,'TH5',TH5); + else + if j==1 + fprintf( sprintf('\n%%%ds\t%%10s %%10s %%10s %%10s %%10s\n',length_leg), ... + 'file', 'mean', 'median', 'std', 'ES', 'maxFreq'); + end + fprintf( sprintf('%%%ds\t%%10s %%10s %%10s %%10s %%10s\n',length_leg), ... + legend_str{j}, sprintf('%8g',mn), sprintf('%8g',median(y)), ... + sprintf('%8g',sd), sprintf('%8g',ES), sprintf('%8g',max(H(j,:)))); + out2(j) = struct('name',legend_str{j},'mean',mn,'std',sd,'ES',ES,'maxFreq',max(Hfit(j,:)) ); + end + else + legend_str{j} = num2str(j); + end +end + +if ~isempty(opt.dist) + HP = plot(X(:,2:end-1)', Hfit(:,2:end-1)'); + hold on + HP0 = plot(X(:,2:end-1)', H(:,2:end-1)'); + hold off +else + HP = plot(X(:,2:end-1)', H(:,2:end-1)'); +end + +for i = 1:length(HP) + set(HP(i),'LineWidth',1); + if ~isempty(opt.dist) + set(HP0(i),'LineWidth',1,'Linestyle',':'); + end + if ~isempty(opt.color) + set(HP(i),'Color',opt.color(i,:)); + if ~isempty(opt.dist) + set(HP0(i),'Color',opt.color(i,:)); + end + end +end + +h = legend(legend_str); +set(h,'Interpreter','none'); +grid on +if opt.norm_frequency + ylabel('Normalized Frequency'); +else + ylabel('Frequency'); +end + +if ~isempty(opt.xlim) && numel(opt.xlim) == 2 + xlim(opt.xlim) +end + +if ~isempty(opt.ylim) && numel(opt.ylim) == 2 + ylim(opt.ylim) +end + +grid minor + +if isempty(opt.dist) + figure + hist(y_all, X0) + if ~isempty(opt.xlim) && numel(opt.xlim) == 2 + xlim(opt.xlim) + end +end + +if opt.mean + figure(11) + HP = plot(X(1,2:end-1)', mean(H(:,2:end-1))'); + legend('Average histogram') + if ~isempty(opt.xlim) && numel(opt.xlim) == 2 + xlim(opt.xlim) + end + + if ~isempty(opt.ylim) && numel(opt.ylim) == 2 + ylim(opt.ylim) + end +end + + +grid minor + +if nargout + varargout{1} = HP; + + if nargout > 1 + varargout{2} = out2; + end +end + +%_______________________________________________________________________ +function [udat, mn, mx] = loadsingle(V) +% Load surface or volume data from file indicated by V into an array of floats. + +% use fast method for file reading for nifti files +if isa(V,'nifti') + udat(:,:,:) = V.dat(:,:,:); +elseif isstruct(V) + udat = spm_read_vols(V); +else + udat = V.cdata(:); +end + +% remove zero background +ind0 = find(udat == 0); +if ~isempty(ind0) + if length(ind0) > 0.01*numel(udat) + udat(ind0) = NaN; + end +end + +mx = max(udat(:)); +mn = min(udat(:)); + +udat = single(udat); + +%_______________________________________________________________________ +function [udat, mn, mx] = loadsingle_txt(P) +% Load txt data from file indicated by V into an array of floats. + +udat = spm_load(P); + +% remove zero background +ind0 = find(udat == 0); +if ~isempty(ind0) + if length(ind0) > 0.01*numel(udat) + udat(ind0) = NaN; + end +end + +mx = max(udat(:)); +mn = min(udat(:)); + +udat = single(udat); + +%_______________________________________________________________________ +function [udat, mn, mx] = loadsingleFS(P) +% +% [udat, mn, mx] = loadsingleFS(P) +% reads a binary curvature file into a vector with single data type +% + +udat = cat_io_FreeSurfer('read_surf_data',P); + +mx = max(udat(:)); +mn = min(udat(:)); + +udat = single(udat); + +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_surf_load.m",".m","5253","160","function varargout = cat_surf_load(files,sides,data) +%cat_surf_load. Load gifti surface and combine them to one mesh. +% +% [S,sdata,fdata,rnames] = cat_surf_load(file,sides,loadmesh) +% +% S .. surface patch structure with vertices, faces, and +% facevertexcdata depending on the data variable +% sdata .. facevertexcdata of side +% fdata .. facevertexcdata of object +% rnames .. region names in case of atlas files +% +% file .. surface or texture +% sides .. load specific sides +% 'mesh' (default), 'lh', 'rh' ... 'meshcb', 'cb' +% data .. load surface mesh and/or surface data +% 1-mesh only, 2-texture only, 3-load both (default) +% avg .. use average mesh +% 1-FreeSurfer, 2-Shooting +% type? .. central, pial, white, hull +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +%#ok<*AGROW> + + % defaults + if ~exist('sides','var'), data = 'mesh'; end + if ~exist('data' ,'var'), data = 3; end + if ~exist('avg' ,'var'), avg = 1; end + + + % check all input files + files = cellstr(files); +% for fi=1:numel(files) +% if ~exist(files{fi},'file') +% error('cat_surf_loadfiles:noFile','Input file %d ""%s"" does not exist.',fi,files{fi}); +% end +% end + + + % check side input string + if iscell(sides) + if strfind(sides,'mesh') + sides = unique( [sides, 'lh', 'rh'] ); + elseif strfind(sides,'meshcb') + sides = unique( [sides, 'lh', 'rh', 'cb' ] ); + end + else + if strcmp(sides,'mesh') + sides = {'lh', 'rh'}; + elseif strcmp(sides,'meshcb') + sides = {'lh', 'rh', 'cb'}; + end + end + + + %% check & prepare matlab patch data + if data==1 || data==3 + S.vertices = []; + S.faces = []; + end + if data==2 || data==3 + S.facevertexcdata = []; + end + sdata = uint8([]); + odata = uint8([]); + + + % check mesh type >> 1=individual, 2=resampled32k, 3=resampled164k + %sinfo = cat_surf_info( files ); + %mtype = 1; + + for fi = 1:numel(files) + for si = 1:numel(sides) + %% + fname = char(cat_surf_rename(files{fi},'side',sides{si})); + [pp,ff,ee] = spm_fileparts( fname ); + clear St; + if exist(fname, 'file') + switch ee + case '.gii' + St = gifti(fname); + St = export(St,'patch'); + if (data==1 || data==3) && ~isfield(St,'vertices') + % try to load individual surface + fname2 = char(cat_surf_rename(fname,'dataname','central','ee','.gii',... + 'pp',strrep(pp,'atlases_surfaces','templates_surfaces'))); + % type +% >>> + if exist(fname2,'file') + St = gifti(fname2); + else % if normalized + % load fiting template ... + fname2 = char(cat_surf_rename(fname,'dataname','central','ee','.gii',... + 'pp',strrep(pp,'atlases_surfaces','templates_surfaces'))); + St = gifti(fname2); + end + end + case '.annot' + % allways template data + if data==1 || data==3 + fname2 = char(cat_surf_rename(fname,'dataname','central','ee','.gii',... + 'pp',strrep(pp,'atlases_surfaces','templates_surfaces'))); + St = gifti(fname2); + St = export(St,'patch'); + end + if data==2 || data==3 + [cx,cdata,ctab] = cat_io_FreeSurfer('read_annotation',fname); + St.facevertexcdata = cdata; + end + otherwise +% >>> + %{ + snames = {'.central.','.inflated.','sphere','.hull.','.inner.','.outer.','.white.','.pial.'}; + if any( ~cellfun('isempty',strfind(snames,fname))) + % FreeSurfer surface - no texture + [St.vertices,St.faces] = cat_io_FreeSurfer('read_surf',avg); + + else + % FreeSurfer texture (individual data) + St. + + if data==1 || data==3 + % individual surface + St.vertices = []; + St.faces = []; + end + %} + + end + else + error('cat_surf_loadfiles:noFile2','The ""%s"" side of input file %d ""%s"" does not exist.',sides{si},fi,files{fi}); + end + + if data==1 || data==3 + S.faces = [S.faces; St.faces + size(S.vertices,1)]; + S.vertices = [S.vertices; St.vertices]; + end + if data==2 || data==3 + S.facevertexcdata = [S.facevertexcdata; St.facevertexcdata]; + end + sdata = [sdata repmat( uint8(si) , numel(St.facevertexcdata) , 1) ]; + odata = [sdata repmat( uint8(fi) , numel(St.facevertexcdata) , 1) ]; + end + end + + %% + varargout{1} = S; + if nargout>1, varargout{2} = sdata; end + if nargout>2, varargout{3} = odata; end + if nargout>3 && exist('ctab','var'), varargout{4} = ctab; end +end + + + ","MATLAB" +"Neurology","ChristianGaser/cat12","cat_stat_nanstat1d.m",".m","1102","30","function x=cat_stat_nanstat1d(x,action) +% ---------------------------------------------------------------------- +% replace nan* functions of the stat toolbox for the 1d case +% use double, because mean error for large single arrays. +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + x=double(x(:)); x(isnan(x) | isinf(x))=[]; + if ~exist('action','var'), action='nanmean'; end + + switch lower(action) + case {'mean' 'nanmean'}, x = mean(x); + case {'median' 'nanmedian'}, x = median(x); + case {'std' 'nanstd'}, x = std(x); + case {'min' 'nanmin'}, x = min(x); + case {'max' 'nanmax'}, x = max(x); + case {'var' 'nanvar'}, x = var(x); + case {'sum' 'nansum'}, x = sum(x); + case {'prod' 'nanprod'}, x = prod(x); + case {'cumsum' 'nancumsum'}, x = cumsum(x); + end +end + +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_progress_bar.m",".m","7118","208","function cat_progress_bar(action,varargin) +% Display progress and remaining time with the same syntax as for spm_progress_bar. +% +% FORMAT cat_progress_bar('Init', n_steps [, process_name, type]) +% Initialises progress tool with additional specific name ""process_name"". +% The ""type"" can be used to use a command line counter ('cmd') instead of +% the popup window or to switch off this function ('off'). +% +% FORMAT cat_progress_bar('Set',value) +% Sets iteration. +% +% FORMAT cat_progress_bar('Clear') +% Clears the progress window. +% +% Example 1 - percentage progess bar window: +% cat_progress_bar('Init', 10, 'Bar', 'bar') +% for i=1:10, cat_progress_bar('Set',i), pause(.25); end +% cat_progress_bar('Clear') +% +% Example 2 - command line progress: +% cat_progress_bar('Init', 10, 'CMD', 'cmd') +% for i=1:10, cat_progress_bar('Set',i), pause(.25); end +% cat_progress_bar('Clear') +% +% Example 3 - percentage command line progress: +% cat_progress_bar('Init', 10, '', 'cmd%') +% for i=1:10, cat_progress_bar('Set',i), pause(.25); end +% cat_progress_bar('Clear') +% +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +persistent sum_time time_old n_iterations Fwaitbar progress_step Fwaitbartype Fwaitbarname + +%if ~nargin, action = 'Init'; end % this cannot work as init requires input +if ~nargin, help cat_progress_bar; return; end + +if strcmpi(action,'init') + if nargin > 1 + % catch possible errors of older calls with additional field, eg. + % cat_progress_bar('Init', 10 ,'CAT-Preprocessing','Volumes Complete'); + switch varargin{end} + case {'bar','cmd','cmd%'} + bartype = varargin{end}; + otherwise + bartype = 'bar'; + end + else + bartype = 'bar'; + end +elseif strcmpi(action,'off') || strcmpi(action,'silent') || strcmpi(action,'quite') || strcmpi(action,'') + return +else + if exist('Fwaitbartype','var') + if ischar(Fwaitbartype) + bartype = Fwaitbartype; + else + if strcmpi(action,'clear') + return + else + error('cat_progress_bar:nobar','No progess bar!'); + end + end + else + if strcmpi(action,'clear') + return + else + error('cat_progress_bar:nobar','No progess bar!'); + end + end +end +switch bartype + case {'bar','cmd','cmd%'} + switch lower(action) + % Initialise + %------------------------------------------------------------------- + case 'init' + n_iterations = varargin{1}; + + % from older versions that were not printed + %{ + if nargin > 2 + arg3 = varargin{2}; + else + arg3 = ''; + end + %} + + if nargin > 1 + arg2 = varargin{2}; + if ~strcmp(bartype,'bar') && arg2(end)~=':' + arg2(end+1) = ':'; + end + else + if strcmp(bartype,'bar') + arg2 = 'Computing'; + else + arg2 = ''; + end + end + + Fwaitbarname = arg2; + Fwaitbartype = bartype; + sum_time = 0; + time_old = clock; + progress_step = 1; + + switch Fwaitbartype + case 'bar' + try + Fwaitbar = waitbar(0,arg2,'Name',arg2); + catch + Fwaitbar = waitbar(0,arg2); + end + + % don't know whether this works, but I have used the parameters from spm_progress_bar + set(Fwaitbar,'IntegerHandle','off','InvertHardcopy','on','PaperPositionMode','auto','Tag','Interactive'); + + case 'cmd' + fprintf('% 6d/% 6d',0,n_iterations); + case 'cmd%' + fprintf('%s% 6.2f ',arg2,0); + end + + % Set + %------------------------------------------------------------------- + case 'set' + iter = varargin{1}; + + % save time if we don't have to show every step + if rem(iter, progress_step), return; end + + % estimate time for remaining iterations + diff_time = etime(clock, time_old); + sum_time = sum_time + diff_time; + avg_time = sum_time/iter; + remain_time = avg_time*(n_iterations-iter); + + % if execution time is much shorter than displaying the ui we skip + % most of that displaying to save time + if diff_time < 0.05; progress_step = progress_step*2; end + + % add 0.5s to remaining time to prevent that at the end 0s is + % displayed for a longer time + if iter/n_iterations*100 > 1 + str = sprintf('%.f%% (%s remaining)',iter/n_iterations*100,time2str(0.5+remain_time)); + else + str = sprintf('%.f%%',iter/n_iterations*100); + end + switch Fwaitbartype + case 'bar' + if ishandle(Fwaitbar), waitbar(iter/n_iterations,Fwaitbar,str); end + case 'cmd' + fprintf('\b\b\b\b\b\b\b\b\b\b\b\b\b% 6d/% 6d',min(999999,iter),n_iterations); + case 'cmd%' + fprintf('\b\b\b\b\b\b\b% 6.2f%%',min(999,iter/n_iterations*100)); + end + + % save old values + time_old = clock; + + % Clear + %------------------------------------------------------------------- + case 'clear' + switch Fwaitbartype + case 'bar' + if ishandle(Fwaitbar), delete(Fwaitbar); end + case 'cmd' + fprintf('\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b'); + case 'cmd%' + fprintf(sprintf('%s',repmat('\b',1,numel(Fwaitbarname)))); + fprintf('\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b'); + end + + % Error + %------------------------------------------------------------------- + otherwise + error('Unknown action string'); + end + otherwise + error('error:cat_progress_bar:bartype',sprintf('Unknown bartype ""%s""',bartype)); +end + +return + +function str = time2str(t) +minutes = t/60; +hours = t/3600; +days = hours/24; + +if days > 2 + str = sprintf('%d days %02.1f h', floor(days),24*(days-floor(days))); +elseif days > 1 + str = sprintf('%d day %02.1f h', floor(days),24*(days-floor(days))); +elseif hours > 1 + str = sprintf('%d:%02.0f h', floor(hours),60*(hours-floor(hours))); +elseif minutes > 1 + str = sprintf('%d:%02.0f min',floor(minutes),60*(minutes-floor(minutes))); +else + str = sprintf('%d s',round(t)); +end +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_stat_calc_stc.m",".m","4616","108","function [vbmSTC,Ystc,stctype] = cat_stat_calc_stc(Yp0,VT0,trans,te,res) +% Subject Template (TE) +% ---------------------------------------------------------------------- +% This measure should describe the difference between our expectation +% from the mean group probability map and the subject. Strong variation +% can represent +% (1) strong anatomical variations of this subject, and +% (2) normalisation error (that are often caused by special anatomies +% or be previous preprocessing errors) +% Stronger changes are expected in with growing distance from the core +% of the WM. +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + opt.tpm = 1; + + if opt.tpm + %% CAT-Dartel template + [pth1,nam1,ext1] = spm_fileparts(char(cat_get_defaults('extopts.darteltpm'))); + VclsA = spm_vol(fullfile(pth1,[strrep(nam1,'Template_1','Template_6'),ext1])); + YclsA = cell(1,3); + + if VclsA(1).dim==size(Yp0) %subject space + for i=1:2 + YclsA{i} = single(spm_read_vols(VclsA(i))); + YclsA{i} = reshape(YclsA{i},size(Yp0)); + end + stctype = 'subspace-vbmtemplate'; + else + for i=1:2 + YclsA{i} = single(spm_sample_vol(VclsA(i), ... + double(trans.atlas.Yy(:,:,:,1)), ... + double(trans.atlas.Yy(:,:,:,2)), ... + double(trans.atlas.Yy(:,:,:,3)), 1)); + YclsA{i} = reshape(YclsA{i},size(Yp0)); + end + stctype = 'tempspace-vbmtemplate'; + end + + % now we need to create a CSF probability map (for the next correction) + Yclsb = cat_vol_smooth3X(cat_vol_morph((YclsA{1} + YclsA{2})>0.3,'lc',2),2)>0.5; + for i=1:2, YclsA{i} = YclsA{i} .* smooth3(Yclsb); end + YclsA{3} = (Yclsb & smooth3(YclsA{1} + YclsA{2})<0.6) .* ... + ((Yclsb - single(YclsA{1} + YclsA{2}) ./ ... + median(YclsA{1}(Yclsb) + YclsA{2}(Yclsb)))); + + % final correction for maximum probability of 1 + YclsAsum = (YclsA{1} + YclsA{2} + YclsA{3}) .* Yclsb; + for i=1:3, YclsA{i} = (YclsA{i}./max(eps,YclsAsum)) .* Yclsb; end + Yp0A = YclsA{1}*2 + YclsA{2}*3 + YclsA{3} .* Yclsb; + clear YclsA YclsAsum VclsA Yclsb; + + else + %% SPM-Tissue template + VclsB = spm_vol(res.tpm(1).fname); + YclsB = cell(1,7); + if VclsB(1).dim==size(Yp0) %subject space + for i=1:2 + YclsB{i} = single(spm_read_vols(VclsB(i))); + YclsB{i} = reshape(YclsB{i},size(Yp0)); + end + stctype = 'subspace-spmtemplate'; + else + for i=1:3 + YclsB{i} = single(spm_sample_vol(VclsB(i), ... + double(trans.atlas.Yy(:,:,:,1)), ... + double(trans.atlas.Yy(:,:,:,2)), ... + double(trans.atlas.Yy(:,:,:,3)), 1)); + YclsB{i} = reshape(YclsB{i},d); + end + stctype = 'tempspace-spmtemplate'; + end + + % now we need to create a CSF probability map (for the next correction) + Yclsb = cat_vol_smooth3X(cat_vol_morph((YclsB{1} + YclsB{2})>0.3,'lc',2),2)>0.5; + for i=1:3, YclsB{i} = YclsB{i} .* smooth3(Yclsb); end + % final correction for maximum probability of 1 + YclsBsum = (YclsB{1} + YclsB{2} + YclsB{3}) .* Yclsb; + for i=1:3, YclsB{i} = (YclsB{i}./max(eps,YclsBsum)) .* Yclsb; end + Yp0A = YclsB{1}*2 + YclsB{2}*3 + YclsB{3} .* Yclsb; + clear YclsB YclsBsum Yclsb VclsB; + end + + + % Now we can estimate the difference maps for each intensity/Yp0b map. + % But finally only our segment/Yp0b map is important, because other + % non-intensity scaled images will have higher errors due to the + % intensity scaling. + Ystc = abs(max(1,Yp0A)-max(1,Yp0)); % we are not interessed in skull-stripping differences... maybe later ;-) + spm_smooth(Ystc,Ystc,8); % we are only interessed on larger changes + + if strcmp(stctype(1:4),'temp') + mrifolder = cat_io_subfolders(VT0.fname); + cat_io_writenii(VT0,Ystc,mrifolder,'te', ... + ['group expectation map (matching of template after normalization) - ' stctype], ... + 'uint8',[0,1/255],min([1 0 0 0],cell2mat(struct2cell(te)')),trans); + cat_io_writenii(VT0,Ystc,mrifolder,'te', ... + ['group expectation map (matching of template after normalization) - ' stctype]', ... + 'uint8',[0,1/255],min([0 1 2 2],cell2mat(struct2cell(te)')),trans); + end + vbmSTC = sum(Ystc(:)) ./ sum(Yp0(:)>0); +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_long_biascorr.m",".m","12119","300","function out = cat_long_biascorr(job) +%cat_long_biascorr. Longitudinal bias correction by average segmentation. +% +% job .. SPM job structure +% .images .. cell of realigend images +% .p0 .. cell with the avg p0 label map +% .str .. strength of correction (0=soft, 0.5=default, 1=strong corr.) +% .prefix .. filename prefix (default 'm') +% .fs .. filter size in mm (2=strong, 4=default, 8=soft correction) +% (if it is empty then it is defined by job.str) +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +% ToDo: +% * Integration and Test of WMHs. +% * Strong correction (str = 0.75) caused GM overestimation and adaptation +% of filter thresholds and smoothin is required. +% * Iterative correction with low to high filter size + +% RD202010: First tests showed clear improvements of the timepoints but the +% whole pipeline seems to be less affected. +% Hence, corrections are maybe more relevant for plasticity +% studies or in case of artifacts. +% Strong correction (str = 0.75) caused GM overestimation, +% whereas low correction (str = 0.25) seemed to be much better. + + + def.images = {}; + def.segment = {}; + def.str = 0.5; + def.prefix = 'm'; + def.hardcore = 0; % direct correction based on the T1 maps > not realy working + def.LASstr = 0.5; % use (local) intensity normalization > + job = cat_io_checkinopt(job,def); + job.str = max(0.1,min(1,job.str)); + + if ~isfield(job,'fs') || isempty(job.fs) + job.fs = 2^(4 * (1 - job.str)); + end + %% + if job.LASstr > 0 + fprintf(' Biasstr = %0.2f, filtersize = %0.2f, LASstr = %0.2f\n',job.str,job.fs,job.LASstr); + else + fprintf(' Biasstr = %0.2f, filtersize = %0.2f \n',job.str,job.fs); + end + + if job.hardcore + %% 202201 intensity based correction > remove if not further needed in 202301 + % This is just a temporary test if stronger changes based on the original + % images intens can improve the preprocessing, especially in case of + % different protocols. + % This can be seen as some very strong bias correction that changes + % also contrast differences (that why we cannot smooth stonger), + % whereas zero smooting would simply replace the image by the average. + % Although, there are some visual improvements, the is much to simple + % and an intensity normalization and more smoothing are probably + % necessary to stabilize the effect. + [pp,ff,ee] = spm_fileparts(job.segment{1}); + if strcmp(pp(end-2:end),'mri'), pp = pp(1:end-3); end + Vavg = spm_vol( fullfile(pp,[ff(3:end) ee]) ); + Yavg = spm_read_vols(Vavg); + end + + % load segment and estimate voxel size + Vp0 = spm_vol(job.segment{1}); + Yp0 = spm_read_vols(Vp0); + vx_vol = sqrt(sum(Vp0.mat(1:3,1:3).^2)); + + % apply bias correction for all images + for ii = 1:numel(job.images) + Vo = spm_vol(job.images{ii}); + Yo = single(spm_read_vols(Vo)); + + %% avoid edges (artifacts) in the original image + Yg = cat_vol_grad(Yo) ./ (1+Yo); % normalized gradient map of the original image + Ygp0 = cat_vol_grad(Yp0) ./ (1+Yp0); % normalized gradient map of the average segmentation map + Ydiv = cat_vol_div(Yo) ./ Yo; + + + %% hard intensity correction (this is too simple) + %Ywa = cat_vol_smooth3X(Yavg ./ Yo,0); % correct addtive to adapt avg to tp + if job.hardcore + fprintf('Hard intensity correction based on the average:\n'); + Ybg = cat_vol_smooth3X( Yo ./ cat_stat_kmeans(Yo(round(Yp0)==3)) <0.5 & Yp0==0 , 4) ; + Yi = max(0.7,max(eps,Yo) ./ max(eps,Yavg)).*(1-Ybg) + Ybg; + Yi = cat_vol_median3(Yi); + Yw = cat_vol_smooth3X(Yi, 2 ); + + % quantify difference + Ygow = cat_vol_grad(Yo./Yw) ./ (1+(Yo./Yw)); + fprintf(' Yg overlap after hard corection: %0.4f\n',cat_stat_nanmean(abs(Ygow(Yp0(:)>0) - Yg(Yp0(:)>0)))); + + Yo = Yo ./ Yw; + end + + + %% intensity normalization + T3th = [ min(Yo(:)) min(Yo(Yp0(:)>0.5 & Yg(:)<0.2))+eps ... + cat_stat_kmeans(Yo(round(Yp0)==1 & Yg<0.2)) ... + cat_stat_kmeans(Yo(round(Yp0)==2 & Yg<0.2)) ... + cat_stat_kmeans(Yo(round(Yp0)==3 & Yg<0.2)) ... + max(Yo(Yp0>0 & Yg<0.2))]; + T3thx = [ 0 min(Yo(Yp0(:)>0.5 & Yg(:)<0.2))/cat_stat_kmeans(Yo(round(Yp0)==1 & Yg<0.2))+eps ... + 1 2 3 ... + max(Yo(Yp0(:)>0.5 & Yg(:)<0.2))/cat_stat_kmeans(Yo(round(Yp0)==3 & Yg<0.2))*3 ]; + + % intensity scaling + Ym = Yo; + for i=2:numel(T3th) + M = Yo>T3th(i-1) & Yo<=T3th(i); + Ym(M(:)) = T3thx(i-1) + (Yo(M(:)) - T3th(i-1))/diff(T3th(i-1:i))*diff(T3thx(i-1:i)); + end + M = Yo>=T3th(end); + Ym(M(:)) = numel(T3th)/6 + (Yo(M(:)) - T3th(i))/diff(T3th(end-1:end))*diff(T3thx(i-1:i)); + + + %% avoid regions that strongly changed between the time points + Yd = single(abs(Ym - Yp0) .* (Yp0>0)); + Yd = cat_vol_median3(Yd,Yp0>0,Yp0>0,0.1); + Yd = cat_vol_smooth3X(Yd,0.5); + Yd = Yd .* Yg; + + + %% extract save segment + gstr = 2^( 2 * (job.str - 0.5) ); + Ywm = abs(Ydiv)<0.2*mean(vx_vol) & Yd<0.2*mean(vx_vol) & Yg<0.6*mean(vx_vol) * gstr & Ygp0<0.6*mean(vx_vol) & Yp0>2.5; % & cat_vol_morph(Yp0>2,'e',1,vx_vol); + Ygm = abs(Ydiv)<0.2*mean(vx_vol) & Yd<0.2*mean(vx_vol) & Yg<0.6*mean(vx_vol) * gstr & Ygp0<0.6*mean(vx_vol) & Yp0>1.5 & Yp0<2.5; % & cat_vol_morph(Yp0>1,'e') & cat_vol_morph(Yp0<3,'e'); + Ycm = abs(Ydiv)<0.2*mean(vx_vol) & Yd<0.2*mean(vx_vol) & Yg<0.6*mean(vx_vol) * gstr & Ygp0<1.2*mean(vx_vol) & Yp0>0.5 & Yp0<1.5 & cat_vol_morph(Yp0>0,'e',3,vx_vol) & cat_vol_morph(Yp0<2,'de',3,vx_vol); + Ycm(smooth3(Ycm)<0.3) = 0; + Ybg = Ym<0.5 & single(cat_vol_morph(Yp0==0,'de',40,vx_vol)); + %clear Yg; + + + %% get values from segment + Yi = Ybg + Yo .* Ywm ./ cat_stat_kmeans(Yo(Ywm(:))); + Yi = Yi + Yo .* Ygm ./ cat_stat_kmeans(Yo(Ygm(:))); + Yi = Yi + Yo .* Ycm ./ cat_stat_kmeans(Yo(Ycm(:))); + if 1 + if T3th(4)0.2 * max(0.5,job.str) ) = 0; + % remove background + Yi(Ybg) = 0; + Yi = cat_vol_median3(Yi,Yi~=1 & Yi~=0,Yi~=1 & Yi~=0); + Yi = cat_vol_localstat(Yi,Yi~=0,round(3/mean(vx_vol)),1,round(10 ./ mean(vx_vol))); + % approximate bias field + Yw = cat_vol_approx(Yi,'nh',vx_vol,job.fs); % overcorrection of subcortical structures + Yw = Yw ./ cat_stat_kmeans(Yw(Ywm(:))); + + + + %% local intensity correction based on the average segmentation + % The priciple idea is to do some further corrections in case of + % changed protocols (indicated by the user). The hope is that this + % reduce the bias like local differences related to contrast + % differences. + % For test the ADNI 1.5 and 3.0 Tesla scans with 100 days differences + % and normal longitudinal scans with 1 and 2 years differences are used, + % where the correction should result in a more likely aging pattern in + % the 100-days rescans and not worse (quite similar) changes within the + % normal longitudinal images. + if job.LASstr + + % apply bias correction + Ysrc = Yo ./ Yw; + +if 0 + clsdef = { + ... p0- g d k op + 0.01 0.1 0.1 1; + 1.05 0.1 0.1 1; ... C + ... 1.33 0.1 0.1 1; + ... 1.66 0.1 0.1 1; + 1.95 0.1 0.1 1; + 2.05 0.1 0.1 1; ... G + ... 2.33 0.1 0.1 1; + ... 2.66 0.1 0.1 1; + 2.95 0.1 0.1 1; + 3.15 0.1 0.1 1; ... W + }; + clsdef = { + ... p0- g d k op + 0.50 0.1 0.1 1; %C + 1.25 1.1 1.5 1; % G + 1.75 1.1 1.1 1; % C + 2.25 1.1 1.1 1; % G + 2.75 1.3 1.1 1; % W + 3.10 0.3 0.5 1; % W + }; + for ci = 2:size(clsdef,1) + Ymsk = Yp0>=clsdef{ci-1,1} & Yp0T3th(i-1) & Ym<=T3th(i); + Ysrc(M(:)) = T3thx(i-1) + (Ym(M(:)) - T3th(i-1))/diff(T3th(i-1:i))*diff(T3thx(i-1:i)); + end + M = Ym>=T3th(end); + Ysrc(M(:)) = numel(T3th)/isc/6 + (Ym(M(:)) - T3th(i))/diff(T3th(end-1:end))*diff(T3thx(i-1:i)); + %% + Yww = smooth3(Ysrc)./smooth3(Yavg) .* (Yp0>0) .* (Yg<0.3 | abs(Yd)>0.1); Yww = cat_vol_median3(Yww,Yp0>0); + %Yww = cat_vol_localstat(Yww,Yp0>0,1,1,10); + Yww = cat_vol_approx(Yww,1); + Yww = Yww ./ ( cat_stat_nanmean(Ysrc(:)./Yavg(:)./Yww(:) .* (Yp0(:)>0)) ./ cat_stat_nanmean(Ysrc(:)./Yavg(:) .* (Yp0(:)>0))); + % Ysrc2 = Ysrc / 1000; + + % Yn = (Ysrc ./ Yww - Yavg); + % cat_sanlm(Yn,1,3); + + %% + Ym = cat_main_gintnormi(Ysrc,Tth); +end + + %% + + % estimate threshholds + T3th2 = zeros(1,3); + for ti=1:3, T3th2(ti) = cat_stat_kmeans(Ysrc(round(Yp0)==ti & Yg<0.3)); end + + + + + %% the most important segment is the GM + Ygm2 = Ygp0<0.6*mean(vx_vol) & Yp0>1.5 & Yp0<2.5 & Yg<0.6*mean(vx_vol); + Ygm2(smooth3(Ygm2)<0.3) = 0; % remove small dots + Yi = Ysrc .* Ygm2; + Yi = cat_vol_median3(Yi,Yi~=1 & Yi~=0,Yi~=1 & Yi~=0); + Yi = cat_vol_localstat(Yi,Yi~=0,1,1,round(20 ./ mean(vx_vol))); + % first approximation to remove local outlier + Ylab{1} = cat_vol_approx(Yi,'nh',vx_vol,job.fs * 4 / job.LASstr); + Yi( abs( log( Yi ./ Ylab{1} )) > 0.2 ) = 0; % arbitrary value between 0.10 (remove more) and 0.25 (remove less) + % final approximation + Ylab{1} = cat_vol_approx(Yi,'nh',vx_vol,job.fs * 4 / job.LASstr); + % for all other segments we just use the global values + Ylab{2} = T3th2(3); + Ylab{3} = T3th2(1); + Ylab{6} = min(Yo); % ####### inoptimal# + + % intensity normalization + Yml = zeros(size(Ysrc)); + Yml = Yml + ( (Ysrc>=Ylab{2} ) .* (3 + (Ysrc - Ylab{2}) ./ max(eps,Ylab{2} - Ylab{1})) ); + Yml = Yml + ( (Ysrc>=Ylab{1} & Ysrc=Ylab{3} & Ysrc10)=10; + end + + %% create some final measurements + % CJV ? + % RMSE ? + % COV ? + % hist overlap? > rmse? + + + %% write corrected output + out.bc{ii} = spm_file(Vo.fname,'prefix',job.prefix); + Vw = Vo; Vw.fname = out.bc{ii}; + if job.LASstr + spm_write_vol(Vw,Yml); + else + spm_write_vol(Vw,Yo ./ Yw); + end + end +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_vol_laplace3R.c",".c","5519","144","/* laplace calculation + * _____________________________________________________________________ + * Filter SEG within the intensity range of low and high until the changes + * are below TH. + * + * L = cat_vol_laplace3R(SEG,R,TH) + * + * SEG .. 3D single input matrix + * R .. 3D boolean volume to describe the filter area + * TH .. threshold to control the number of iterations + * maximum change of an element after iteration + * + * Example: + * A = zeros(50,50,3,'single'); A(10:end-9,10:end-9,2)=0.5; + * A(20:end-19,20:end-19,2)=1; + * B = A==0.5; + * C = cat_vol_laplace3R(A,0,1,0.001); ds('d2smns','',1,A,C,2); + * ______________________________________________________________________ + * + * Christian Gaser, Robert Dahnke + * Structural Brain Mapping Group (https://neuro-jena.github.io) + * Departments of Neurology and Psychiatry + * Jena University Hospital + * ______________________________________________________________________ + * $Id$ + */ + +/* + * TODO: change of L1 and L2 by pointer + */ + +#include ""mex.h"" +#include ""math.h"" +#include ""float.h"" +/* #include ""matrix.h"" */ + +/* estimate x,y,z position of index i in an array size sx,sxy=sx*sy... */ +void ind2sub(int i,int *x,int *y, int *z, int sxy, int sy) { + *z = (int)floor( (double)i / (double)sxy ) +1; + i = i % (sxy); + *y = (int)floor( (double)i / (double)sy ) +1; + *x = i % sy + 1; +} + +float abs2(float n) { if (n<0) return -n; else return n; } + +/* main function */ +void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) +{ + if (nrhs<2) mexErrMsgTxt(""ERROR:laplace3R: not enough input elements\n""); + if (nrhs>4) mexErrMsgTxt(""ERROR:laplace3R: too many input elements\n""); + if (nlhs>1) mexErrMsgTxt(""ERROR:laplace3R: too many output elements\n""); + if (nlhs<1) mexErrMsgTxt(""ERROR:laplace3R: not enough output elements\n""); + if (mxIsSingle(prhs[0])==0) mexErrMsgTxt(""ERROR:laplace3R: 1st input must be an 3d single matrix\n""); + if (mxIsLogical(prhs[1])==0) mexErrMsgTxt(""ERROR:laplace3R: 2nd input must be an 3d logical matrix\n""); + if (nrhs==3 && mxIsDouble(prhs[2])==0) mexErrMsgTxt(""ERROR:laplace3R: 3rd input must be an double matrix\n""); + if (nrhs==4 && mxIsDouble(prhs[3])==0) mexErrMsgTxt(""ERROR:laplace3R: 4th input (voxelsize) must be a double matrix\n""); + if (nrhs==4 && mxGetNumberOfElements(prhs[3])!=3) mexErrMsgTxt(""ERROR:laplace3R: 4th input (voxelsize) must have 3 Elements""); + + /* main information about input data (size, dimensions, ...) */ + const mwSize *sL = mxGetDimensions(prhs[0]); + const int dL = mxGetNumberOfDimensions(prhs[0]); + const int nL = mxGetNumberOfElements(prhs[0]); + const int x = (int)sL[0]; + const int y = (int)sL[1]; + const int xy = x*y; + + /* input data */ + float*SEG = (float *)mxGetPr(prhs[0]); + bool *M = (bool *)mxGetPr(prhs[1]); + float TH = (float) mxGetScalar(prhs[2]); if ( TH>=0.5 || TH<0.000001 ) mexErrMsgTxt(""ERROR:laplace3R: threshhold must be >0.000001 and smaller than 0.5\n""); + const mwSize sS[2] = {1,3}; + mxArray *SS = mxCreateNumericArray(2,sS,mxDOUBLE_CLASS,mxREAL); + double*S = mxGetPr(SS); + if (nrhs<3) {S[0]=1.0; S[1]=1.0; S[2]=1.0;} else {S = mxGetPr(prhs[2]);} + + /* indices of the neighbor Ni (index distance) and euclidean distance NW */ + const int sN = 6; + const int NI[6] = { -1, 1, -x, x, -xy, xy}; + + /* output data */ + mxArray *hlps[2]; + plhs[0] = mxCreateNumericArray(dL,sL,mxSINGLE_CLASS,mxREAL); + hlps[0] = mxCreateNumericArray(dL,sL,mxSINGLE_CLASS,mxREAL); + hlps[1] = mxCreateLogicalArray(dL,sL); + + float *L1 = (float *)mxGetPr(plhs[0]); + float *L2 = (float *)mxGetPr(hlps[0]); + bool *LN = (bool *)mxGetPr(hlps[1]); + + /* intitialisiation */ + for (int i=0;i TH && iter < maxiter) { + maxdiffi=0; iter++; + for (int i=0;i=nL) || (abs(nu-u)>1) || (abs(nv-v)>1) || (abs(nw-w)>1) || (L1[ni]==-FLT_MAX) || (L1[ni]==FLT_MAX) )==false) + {L2[i] = L2[i] + L1[ni]; Nn++;} + } + if (Nn>0) {L2[i]/=Nn;} else {L2[i]=L1[i];} + + diff = abs2( L1[i] - L2[i] ); /*printf(""%f %f %f\n"",L1[i],L2[i],diff); */ + if ( diff>(TH/10.0) ) { + for (int n=0;n=nL) || (abs(nu-u)>1) || (abs(nv-v)>1) || (abs(nw-w)>1) || (L1[ni]==-FLT_MAX) || (L1[ni]==FLT_MAX) )==false) + LN[ni] = true; /* if i change his neigbors has to be recalculated */ + } + } + + LN[i]=false; + if ( maxdiffi 0.01*max(abs(in(:))); +scl = median(in(ind)./out(ind)); +out = scl*out; + +if invert + out = mx - out; +end +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_io_csv.m",".m","11320","320","function varargout = cat_io_csv(filename,varargin) +% ______________________________________________________________________ +% Writes and read csv-files (with sheet-like subparts) of a cell-array C +% of chars and numbers. The action 'write' or 'read' is definend by the +% output of this function - no output means write, whereas an output +% will stand for read. +% +% cat_io_csv(filename,C[,sheet,pos,opt]) +% C = cat_io_csv(filename[,sheet,pos,opt]) +% +% filename = string with or without csv +% C = cell with chars and numbers {'Hallo' 'Welt'; 1 2.3} +% sheet = lines of the csv file (to get the header) +% pos = 'A3:B4' - position of the Data +% opt.delimiter = ',' +% .komma = '.' +% .linedelimiter = '\n' +% .format = '%0.4f' +% +% Examples: +% cat_io_csv('test',{'Hallo','Welt';1,2.4}) +% C=cat_io_csv('test.csv','','A1:C1') +% cat_io_csv('test',rand(3,3),'','',struct('delimiter',',','komma','.')) +% +% TODO: +% * adding of sheets to save different cells in one file +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + if nargout>0, action='r'; else, action='w'; end + if ~exist('filename','var') || isempty(filename) + filename = spm_select([0 1],'csv','Select *.csv files',{},pwd,'.*'); + if isempty(filename) + if nargout>0, varargout{1}=cell(); end + return; + end + end + if strcmp(action,'w') + if nargin < 1+(nargout==0), C = {}; else, C = varargin{1}; end + if ~isa(C,'cell'); C = num2cell(C); end + if strcmpi(spm_check_version,'octave') % RD20211212: under test + for ci = 1:numel(C) + C{ci} = char( min( 128 , max( 0 , double( C{ci} )))); + end + end + end + if nargin < 2+(nargout==0), sheet = ''; else, sheet = varargin{2-(nargout>0)}; end + if nargin < 3+(nargout==0), pos = ''; else, pos = varargin{3-(nargout>0)}; end + if nargin < 4+(nargout==0), opt = struct(); else, opt = varargin{4-(nargout>0)}; end + + [~,~,ee] = fileparts(filename); + switch action + case {'read','r'} + if strcmp(ee,'.tsv') + def.delimiter = '\t'; + else + def.delimiter = ''; % auto + end + case {'write','w'} + if strcmp(ee,'.tsv') + def.delimiter = '\t'; + else + def.delimiter = ','; + end + end + def.komma = '.'; + def.linedelimiter = '\n'; + def.format = '%0.4f'; + def.finaldelimiter = 0; + + opt = cat_io_checkinopt(opt,def); + opt.delimiter = cat_io_strrep(opt.delimiter,{'t','n','\\'},{'\t','\n','\'}); + if opt.komma==',' && opt.komma == opt.delimiter, opt.delimiter = ';'; end + + switch action + case {'write','w'} + writecsv(filename,C,sheet,pos,opt); + case {'read','r'} + varargout{1} = readcsv(filename,sheet,pos,opt); + otherwise + error('MATLAB:CAT_IO_CSV:unkown_action','Unknown action ''%s''',action); + end +end + +function C=readcsv(filename,sheet,pos,opt) +% __________________________________________________________________________________________________ +% read data as xls if matlab xlswrite works else will try to use the cvs-files. +% __________________________________________________________________________________________________ + + % set filename and load if it exist + if ~exist(filename,'file'), fprintf('File ""%s"" does not exist.\n',filename); C={}; return; end + + % auto detection + if isempty( opt.delimiter ) + [~,~,ee] = fileparts(filename); + switch ee + case '.tsv' + opt.delimiter = '\t'; + if isempty( opt.komma ) + opt.komma = '.'; + end + case '.csv' + % read the header + fid = fopen(filename); + hdr = textscan(fid,'%q',1,'delimiter',opt.linedelimiter); hdr = hdr{1}; + fclose(fid); + + % we asume that this should be + hdrk = textscan(hdr{1},'%q','delimiter',',')'; hdrk=hdrk{1}'; + hdrs = textscan(hdr{1},'%q','delimiter',';')'; hdrs=hdrs{1}'; + if numel(hdrk) > numel(hdrs) + opt.delimiter = ','; + opt.komma = '.'; + else + opt.delimiter = ';'; + end + + end + end + + % read file and convert from string to cell + fid = fopen(filename); + %mv = version; mvi = strfind(mv,'R'); + % if str2double(mv(mvi+1:mvi+4)) < 2015 % old ... str2double(mv(mvi+1:mvi+4)) > 2013 && + % C1 = textscan(fid,'%q','delimiter',opt.linedelimiter,'BufSize',2^24); C1=C1{1}; + % else % new + if isnumeric(sheet) + C1 = textscan(fid,'%q',sheet,'delimiter',opt.linedelimiter); C1=C1{1}; + else + C1 = textscan(fid,'%q','delimiter',opt.linedelimiter); C1=C1{1}; + end + % end + fclose(fid); + + % The matlab textscan removes the second "" of quoted csv-entries. + % Try to find the next delimiter and to replace the "". + for i=1:size(C1,1) + Quote=strfind(C1{i},'""'); + for qi=numel(Quote):-1:1 + Delim=strfind(C1{i}(Quote(qi):end),opt.delimiter) + Quote(qi) - 1; + if ~isempty(Delim) && strcmp(C1{i}(1:Delim(1)-1),'""') + C1{i}=[C1{i}(1:Delim(1)-1) '""' C1{i}(Delim(1):end)]; + end + end + end + + + + % issue with special characters + if strcmpi(spm_check_version,'octave') + if iscell( C1 ) + for i = 1:numel( C1 ) + C1{i} = char( min(255, max(0, double( C1{i} )))); + end + elseif ischar( C1 ) + C1 = char( min(255, max(0, double( C1 )))); + end + %else + % RD202509: The special characters are not working and were replace in GitHub again + % C1 = strrep(C1,'ä','ä'); + % C1 = strrep(C1,'ü','ü'); + % C1 = strrep(C1,'ö','ö'); + end + + for i=1:size(C1,1) + try + + % if numel(strfind(C1{i},';'))>0 + if isempty(C1{i}) + C2{i} = ''; %#ok + else +% if str2double(mv(mvi+1:mvi+4)) > 2013 && str2double(mv(mvi+1:mvi+4)) < 2015 +% C2{i}=textscan(C1{i},'%q','delimiter',opt.delimiter,'BufSize',2^24)'; C2{i}=C2{i}{1}'; %#ok +% else + C2{i}=textscan(C1{i},'%q','delimiter',opt.delimiter)'; C2{i}=C2{i}{1}'; %#ok +% end + %if size(C2{i},2)~=size(C2{1}), fprintf('Line %4d: %4d - %4d\n',i,size(C2{i},2),size(C2{1},2)); end + end + % fprintf('%4.0f-%4.0f\n',numel(strfind(C1{i},';')),numel(C2{i})); + catch %#ok + fprintf('WARNING:cat_io_csv:readcsv: Can''t read line %d!\n',i); C2{i}=cell(1,numel(C2{1})); %#ok + end + end + C3=cell(size(C2,2),max(cellfun('size',C2,1))); + for i=1:size(C2,2) + for j=1:size(C2{i},2) + C3{i,j}=C2{i}{j}; + end + end + + % set colum and row... + if isempty(pos), C=C3; else, C=readC(C3,pos); end + + % if a field could be interpreted as a number, then convert it to a float + % ??? if there is a comma otherwise to integer??? + for i=1:numel(C), if ~isnan(str2double(C{i})) || strcmpi(C{i},'nan'), id=strfind(C{i},','); C{i}(id)='.'; C{i} = str2double(C{i}); end; end + +end +function writecsv(filename,C,sheet,pos,opt) +% __________________________________________________________________________________________________ +% write data as xls if matlab xlswrite works else it export cvs-files. +% __________________________________________________________________________________________________ + % check if xlswrite could work + + % set colum and row + if isempty(pos), else, C=readC(C,pos); end + + for i=1:numel(C) + if ~isempty(C{i}) + if isnumeric(C{i}) +% if isnan(C{i}) || isinf(C{i}), C{i}=sprintf('%0.0f',C{i}); +% else C{i}=sprintf(sprintf('%%0.0f,%%0%0.0f.0f',opt.digit),fix(C{i}),abs(C{i}*10^opt.digit-fix(C{i})*10^opt.digit)); +% end + end + if ischar(C{i}), id=regexp(C{i},['[' opt.delimiter opt.linedelimiter ']']); C{i}(id)=[]; end + end + end + + % read old file if there is one an merge the cells where C isn't + % specified the old value still exist + if 0 %exist(filename,'file') + fid = fopen(filename); + MO = textscan(fid,'%s','delimiter',opt.linedelimiter); MO = MO{1}; + fclose(fid); + + for i=size(MO,1), tmp=textscan(MO{i},'%s','delimiter',opt.delimiter); CO{i,:} = tmp{1}; end %#ok + + % set size + CC=cell(max(size(C),size(CO))); CC(1:size(C ,1),1:size(C ,2))=C; C =CC; + CC=cell(max(size(C),size(CO))); CC(1:size(CO,1),1:size(CO,2))=CO; CO=CC; + clear CC; + + % merge + for i=find(cellfun('isempty',C)==0); CO(i)=C(i); end + end + + M=cell(size(C,1),1); + if strcmpi(spm_check_version,'octave'), M =cellstr(M); end + + for i=1:size(C,1) + for j=1:size(C,2) + if ~isstruct(C{i,j}) && ~iscell(C{i,j}) + if C{i,j}==round(C{i,j}) + M{i}=[M{i} num2str(strrep(num2str(C{i,j}), '\', '\\'),'%d') opt.delimiter]; + else + switch opt.komma + case '.', M{i}=[M{i} num2str(C{i,j},opt.format) opt.delimiter]; + otherwise, M{i}=[M{i} strrep(num2str(C{i,j},opt.format),'.',opt.komma) opt.delimiter]; + end + end + else + M{i}=[M{i} 'ERR:' class(C) opt.delimiter]; + end + end + if opt.finaldelimiter + M{i}=[M{i} opt.linedelimiter]; + else + M{i}=[M{i}(1:end - numel(opt.delimiter) ) opt.linedelimiter]; + end + end + M=cell2mat(M'); + + hdir = fileparts(filename); + if ~isempty(hdir) && ~exist(hdir,'dir'), mkdir(hdir); end + + f=fopen(filename,'w'); + if f~=-1 + fprintf(f,M); + fclose(f); + else + error('cat_io_csv:writeError','Cannot write ""%s"" - Check writing rights!',filename); + end + +end +function [Cpos,ijpos]=readC(C,pos) + i=strfind(pos,':'); if ~isempty(i), pos(i)=[]; end % remove double points + tmp=textscan(pos,'%[^1234567890]%d'); colum=tmp{1}; row=tmp{2}; % separate colum and row in pos-string + if size(row,1)>2, row(3:end,1)=[]; colum(3:end,1)=[]; end % remove to positions if there are to many + ijpos(:,1)=sort(cell2mat(base27dec(colum))); % convert to ij-position + ijpos(:,2)=sort(double(row)); + CX=cell(max([size(C,1),ijpos(:,2)']),max([size(C,2),ijpos(:,1)'])); CX(1:size(C,1),1:size(C,2))=C; + Cpos=CX(ijpos(1,end):ijpos(end,end),ijpos(1,1):ijpos(end,1)); +end +function d = base27dec(s) +% copied from xlswrite.m +%-------------------------------------------------------------------------- +% BASE27DEC(S) returns the decimal of string S which represents a number in +% base 27, expressed as 'A'..'Z', 'AA','AB'...'AZ', and so on. Note, there is +% no zero so strictly we have hybrid base26, base27 number system. +% +% Examples +% base27dec('A') returns 1 +% base27dec('Z') returns 26 +% base27dec('IV') returns 256 +%-------------------------------------------------------------------------- + d=cell(numel(s)); + if iscell(s) + for i=1:numel(s), d{i} = base27dec(s{i}); end + else + if length(s) == 1 + d = s(1) -'A' + 1; + else + cumulative = 0; + for i = 1:numel(s)-1 + cumulative = cumulative + 26.^i; + end + indexes_fliped = 1 + s - 'A'; + indexes = fliplr(indexes_fliped); + indexes_in_cells = num2cell(indexes); + d = cumulative + sub2ind(repmat(26, 1,numel(s)), indexes_in_cells{:}); + end + end +end +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_io_file_move.m",".m","4396","125","function out = cat_io_file_move(job) +% +% Move files to another directory or delete them, if no directory is +% specified. Special treatment to move .img/.hdr/.mat pairs of files +% together. +% +% This code is part of a batch job configuration system for MATLAB. See +% help matlabbatch +% for a general overview. +% +% RD202201: Added simple rename case to rename files independend of their +% directory (reguqired for the longitudinal pipeline). +%_______________________________________________________________________ +% Copyright (C) 2007 Freiburg Brain Imaging + +% Volkmar Glauche +% $Id$ + +rev = '$Rev$'; %#ok + +action = fieldnames(job.action); +action = action{1}; +if strcmp(action, 'delete') + todelete = {}; + for k = 1:numel(job.files) + [p, n, e] = fileparts(job.files{k}); + if numel(e)>=4 && any(strcmp(e(1:4), {'.nii','.img'})) + try + [p, n, e, v] = spm_fileparts(job.files{k}); + todelete{end+1} = fullfile(p,[n '.hdr']); + todelete{end+1} = fullfile(p,[n '.mat']); + end + end + todelete{end+1} = fullfile(p, [n e]); + end + if ~isempty(todelete) + ws = warning; + warning('off', 'MATLAB:DELETE:FileNotFound'); + delete(todelete{:}); + warning(ws); + end + out = []; +else + % copy or move + if any(strcmp(action, {'copyto','copyren'})) + cmd = @copyfile; + for k = 1:numel(job.files) + if strcmp(action,'copyto') + if isempty(job.action.copyto{min(k,numel(job.action.copyto))}) + tgt{k} = fileparts(job.files{min(k,numel(job.action.(action)))}); + else + tgt{k} = job.action.copyto{max(k,numel(job.action.copyto))}; + end + else + if isempty(job.action.(action).copyto{min(k,numel(job.action.(action)))}) + tgt{k} = fileparts(job.files{min(k,numel(job.action.(action)))}); + else + tgt{k} = job.action.(action).copyto{max(k,numel(job.action.(action)))}; % here was a bug ... replaced numel(job.action.copto) + end + end + end + elseif any(strcmp(action, {'ren'})) + cmd = @movefile; + else + cmd = @movefile; + for k = 1:numel(job.files) + if strcmp(action,'moveto') + if isempty(job.action.moveto{max(k,numel(job.action.copyto))}) + tgt{k} = fileparts(job.files{max(k,numel(job.action.(action)))}); + else + tgt{k} = job.action.moveto{max(k,numel(job.action.copyto))}; + end + else + if isempty(job.action.(action).moveto{max(k,numel(job.action.copyto))}) + tgt{k} = fileparts(job.files{max(k,numel(job.action.(action)))}); + else + tgt{k} = job.action.(action).moveto{max(k,numel(job.action.copyto))}; + end + end + end + end + if any(strcmp(action, {'copyren','moveren','ren'})) + patrep = struct2cell(job.action.(action).patrep(:)); % patrep{1,:} holds patterns, patrep{2,:} replacements + if job.action.(action).unique + nw = floor(log10(numel(job.files))+1); + end + end + out.files = {}; + for k = 1:numel(job.files) + [p, n, e] = fileparts(job.files{k}); + if numel(e)>=4 && any(strcmp(e(1:4), {'.nii','.img'})) + try + [p, n, e, v] = spm_fileparts(job.files{k}); + end + end + if any(strcmp(action, {'copyren','moveren','ren'})) + on = regexprep(n, patrep(1,:), patrep(2,:),'emptymatch'); + if job.action.(action).unique + on = sprintf('%s_%0*d', on, nw, k); + end + else + on = n; + end + nam = {[n e]}; + onam = {[on e]}; + if any(strcmp(e, {'.nii','.img'})) + nam{2} = [n '.hdr']; + onam{2} = [on '.hdr']; + nam{3} = [n '.mat']; + onam{3} = [on '.mat']; + end + for l = 1:numel(nam) + try + if any(strcmp(action, {'ren'})) + feval(cmd, fullfile(p, nam{l}), fullfile(p, onam{l})); + out.files{end+1,1} = fullfile(p, onam{l}); + else + feval(cmd, fullfile(p, nam{l}), fullfile(tgt{k}, onam{l})); + out.files{end+1,1} = fullfile(tgt{k}, onam{l}); + end + end + end + end +end +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_surf_vol2surf.m",".m","18961","487","function out = cat_surf_vol2surf(varargin) +% Project volume data to a surface and create a texture file. +% ______________________________________________________________________ +% P = cat_surf_vol2surf(job) +% +% job.data_mesh_lh .. lh mesh files +% job.data_vol .. volume for mapping +% job.verb .. verbose (default: 1) +% job.gifti .. output gifti (default: 0) +% job.interp .. interpolation type (default 'linear') +% ['cubic'|'nearest_neighbour'|'cubic'] +% job.mapping .. mapping type +% .abs_mapping .. absolute mapping distance +% .startpoint .. start point of the vector in mm +% .steps .. number of grid steps +% .endpoint .. end point of the vector in mm +% .surface .. ['Central'|'WM'|'Pial'] +% .rel_mapping .. relative mapping distance +% .startpoint .. start point of the vector +% .steps .. number of grid steps +% .endpoint .. end point of the vector +% .class .. 'GM' % ['GM'|'WM'|'CSF'] +% .rel_equivol_mapping .. relative mapping distance (equi-volume approach) +% .startpoint .. start point of the vector +% .steps .. number of grid steps +% .endpoint .. end point of the vector +% .class .. 'GM' % ['GM'|'WM'|'CSF'] +% job.datafieldname .. new fieldname +% job.cerebellum .. also map cerebellum (default: 0) +% def.mesh32k .. use 32k meshs (default: 0) +% job.merge_hemi .. merge hemishperes (default: 0) +% job.sample .. sampling function (default: 'maxabs') +% ['avg','weighted_avg','range','sum',... +% 'min','max','maxabs','exp','multi'] +% 'avg': Use average for mapping along normals. +% 'weighted_avg': Use weighted average with gaussian kernel for +% mapping along normals. The kernel is so defined +% that values at the boundary are weighted with 50% +% while the center is weighted with 100%. +% 'range': Count number of values in range for mapping along +% normals. If any value is out of range values will +% be counted only until this point. +% Default value: 3.40282e+38 +% 'maxabs': Use absolute maximum value for mapping along +% normals (Default). Optionally a 2nd volume can be +% defined to output its value at the maximum value +% of the 1st volume. +% 'max': Use maximum value for mapping along normals. +% Optionally a 2nd volume can be defined to output +% its value at the maximum value of the 1st volume. +% 'min': Use minimum value for mapping along normals. +% Optionally a 2nd volume can be defined to output +% its value at the minimum value of the 1st volume. +% 'exp': Use exponential average of values for mapping +% along normals. The argument defines the distance +% in mm where values are decayed to 50% +% (recommended value is 10mm). +% Default value: [ 3.40282e+38 0 2.12263e-314 ... +% 9.88131e-323 4.94066e-324 ] +% 'sum': Use sum of values for mapping along normals. +% 'multi': Map data for each grid step separately and save +% file with indicated grid value. Please note that +% this option is intended for high-resolution +% (f)MRI data only. +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + spm_clf('Interactive'); + + if nargin == 0 + help cat_surf_vol2surf; + cat_system('CAT_3dVol2Surf -help'); + out = {}; + return + elseif nargin == 1 + job = varargin{1}; + else + help cat_surf_vol2surf; return + end + + def.cerebellum = 0; + def.verb = 1; + def.gifti = 0; + def.debug = 0; + def.mesh32k = 0; + def.merge_hemi = 0; + def.interp{1} = 'linear'; + def.sample{1} = 'maxabs'; + def.datafieldname = 'intensity'; + if isfield(job.mapping,'abs_mapping') + def.mapping.abs_mapping = struct('startpoint',0,'steps',1,'endpoint',1,'surface','Central'); + elseif isfield(job,'rel_mapping') + def.mapping.rel_mapping = struct('startpoint',0,'steps',1,'endpoint',1,'surface','GM'); + elseif isfield(job,'rel_equivol_mapping') + def.mapping.rel_equivol_mapping = struct('startpoint',0,'steps',1,'endpoint',1,'surface','GM'); + end + job = cat_io_checkinopt(job,def); + + % if no data_mesh_lh is given for normalized space use default + % Dartel template surface + if ~isfield(job,'data_mesh_lh') + if job.mesh32k + fsavgDir = fullfile(fileparts(mfilename('fullpath')),'templates_surfaces_32k'); + str_resamp = '.resampled_32k'; + else + fsavgDir = fullfile(fileparts(mfilename('fullpath')),'templates_surfaces'); + str_resamp = '.resampled'; + end + job.data_mesh_lh = {fullfile(fsavgDir, ['lh.central.' cat_get_defaults('extopts.shootingsurf') '.gii'])}; + else + fsavgDir = fileparts( job.data_mesh_lh{1} ); + end + + n_vol = numel(job.data_vol); + n_surf = numel(job.data_mesh_lh); + + % 4D volume data have to be split into temp. 3D files + counter = 0; + istemp = []; % delete temp. 3d files after mapping + + for vi = 1:n_vol + N = nifti(job.data_vol{vi}); + + % 4D data? + if numel(N.dat.dim) > 3 + n4d = N.dat.dim(4); + [ppv,ffv,eev] = spm_fileparts(job.data_vol{vi}); + N2 = N; + + for vj = 1:n4d + counter = counter + 1; + name3d = fullfile(ppv,sprintf('%s_%05d%s',ffv,vj,eev)); + + % 3d file already exists? + if exist(name3d, 'file') + istemp(counter) = 0; + else + istemp(counter) = 1; + N2.dat = file_array(name3d, N.dat.dim(1:3),... + N.dat.dtype,0,N.dat.scl_slope,N.dat.scl_inter); + create(N2); + N2.dat(:,:,:) = N.dat(:,:,:,vj); + end + + data_vol{counter} = name3d; + end + else + counter = counter + 1; + data_vol{counter} = job.data_vol{vi}; + istemp(counter) = 0; + end + end + + % new volume number + n_vol = counter; + + % if only 1 surface but multiple volumes are given then fill + % up the missing surface names with the single surface name + if (n_surf == 1) && (n_vol > 1) + for i=2:n_vol + job.data_mesh_lh{i} = job.data_mesh_lh{1}; + end + end + + % if only 1 volume but multiple surfaces are given then fill + % up the missing volume names with the single volume name + if (n_vol == 1) && (n_surf > 1) + for i=2:n_surf + data_vol{i} = data_vol{1}; + istemp(i) = 0; + end + end + + %% + side = {'data_mesh_lh','data_mesh_rh'}; + sside = {'sinfo_lh','sinfo_rh'}; + + job.sinfo_lh = cat_surf_info(job.data_mesh_lh); + template = job.sinfo_lh(1).template; + + if ~isfield(job,'data_mesh_rh') + job.data_mesh_rh = cat_surf_rename(job.data_mesh_lh,'side','rh'); + for i=1:numel(job.data_mesh_rh) + % check whether we have rather merged hemispheres + if ~exist(job.data_mesh_rh{i},'file') + side = {'data_mesh_lh'}; + end + end + end + if job.cerebellum + if job.merge_hemi + error('cat_surf_vol2surf:cbmesh_notprepared','Combination of job.cerebellum & job.merge_hemi is not yet prepared.') + else + side = [side {'data_mesh_lc','data_mesh_rc'}]; + sside = [sside {'sinfo_lc','sinfo_rc'}]; + if ~isfield(job,'data_mesh_lc') + job.data_mesh_lc = cat_surf_rename(job.data_mesh_lh,'side','lc'); + for i=1:numel(job.data_mesh_lc) + % check whether we have rather merged hemispheres + if ~exist(job.data_mesh_lc{i},'file') + side = setdiff(side,'data_mesh_lc'); + end + end + end + if ~isfield(job,'data_mesh_rc') + job.data_mesh_rc = cat_surf_rename(job.data_mesh_lh,'side','rc'); + for i=1:numel(job.data_mesh_rc) + % check whether we have rather merged hemispheres + if ~exist(job.data_mesh_rc{i},'file') + side = setdiff(side,'data_mesh_rc'); + end + end + end + end + end + if isfield(job,'data_mesh_rh'), job.sinfo_rh = cat_surf_info(job.data_mesh_rh); end + if isfield(job,'data_mesh_lc'), job.sinfo_lc = cat_surf_info(job.data_mesh_lc); end + if isfield(job,'data_mesh_rc'), job.sinfo_rc = cat_surf_info(job.data_mesh_rc); end + + %% Mapping command + % -------------------------------------------------------------------- + if isfield(job.mapping,'abs_mapping') + mapping = 'abs_mapping'; + elseif isfield(job.mapping,'rel_mapping') + mapping = 'rel_mapping'; + elseif isfield(job.mapping,'rel_equivol_mapping') + mapping = 'rel_equivol_mapping'; + end + + mapdef.class = 'GM'; + job.mapping.(mapping) = cat_io_checkinopt( job.mapping.(mapping),mapdef); + + % if only one step is defined force use of ""max"" as sampling function + if job.mapping.(mapping).steps == 1 + job.sample{1} = 'max'; + end + + mappingstr = sprintf('-%s -steps ""%d"" -start ""%0.4f"" -end ""%0.4f""',... + job.sample{1}, job.mapping.(mapping).steps, job.mapping.(mapping).startpoint,... + job.mapping.(mapping).endpoint); + + %% display something + spm_clf('Interactive'); + cat_progress_bar('Init',numel(data_vol),'Mapped Volumes','Volumes Complete'); + P.data = cell(numel(data_vol),2); + P.relmap = cell(numel(data_vol),2); + P.thick = cell(numel(data_vol),2); + + % display mapping parameters + fprintf('\n'); + if template, space_str='normalized'; else space_str='native'; end + switch mapping + case 'abs_mapping' + mapping_str = ['to ' job.mapping.(mapping).surface ' surface at absolute']; + case 'rel_mapping' + mapping_str = ['within ' job.mapping.(mapping).class ' at thickness-related']; + case 'rel_equivol_mapping' + mapping_str = ['within ' job.mapping.(mapping).class ' using equi-volume approach at thickness-related']; + end + fprintf('Mapping %s volume(s) %s grid positions: ',space_str, mapping_str); + for i=1:job.mapping.(mapping).steps + if job.mapping.(mapping).steps > 1 + fprintf(' %g', job.mapping.(mapping).startpoint + (i-1)*(job.mapping.(mapping).endpoint-job.mapping.(mapping).startpoint)/(job.mapping.(mapping).steps-1)); + else + fprintf(' %g', job.mapping.(mapping).startpoint); + end + end + fprintf('.\n\n'); + if isempty(job.datafieldname), dsep0 = ''; else dsep0 = '_'; end + + if template + % normalized volume to Template surface + + for vi=1:numel(data_vol) + % check whether bounding box is from previous version that is not compatible + % with new template + BB = spm_get_bbox(spm_vol(data_vol{vi})); + if sum(sum(BB-[-90 -126 -72;90 90 108])) == 0 + fprintf('WARNING: File %s is not compatible to new template because a new MNI152NLin2009cAsym template space is used, which is not compatible!\n',data_vol{vi}); + end + [ppv,ffv,eev] = spm_fileparts(data_vol{vi}); + + % replace '.img' extension by '.hdr' extension to work with CAT + if strcmp(eev,'.img') + eev = '.hdr'; + end + + P.vol{vi} = fullfile(ppv,[ffv eev]); + Pout = cell(2,1); + + % replace dots in volume name with ""_"" + ffv(strfind(ffv,'.')) = '_'; + + if ~strcmp(job.sinfo_lh(vi).dataname, 'central') + dsep = [dsep0 job.sinfo_lh(vi).dataname '_']; + end + + for si=1:numel(side) + + if job.merge_hemi + P.data(vi,si) = cat_surf_rename(job.(sside{si})(vi),'side','mesh',... + 'preside','','pp',ppv,'dataname',[job.datafieldname dsep ffv],'name',job.(sside{si})(vi).name); + + % temporary name for merged hemispheres to prevent that previous single hemi-data are deleted + Pout(si) = cat_surf_rename(job.(sside{si})(vi),... + 'preside','','pp',ppv,'dataname',[job.datafieldname dsep 'tmp' ffv],'name',job.(sside{si})(vi).name); + else + P.data(vi,si) = cat_surf_rename(job.(sside{si})(vi),... + 'preside','','pp',ppv,'dataname',[job.datafieldname dsep ffv],'name',job.(sside{si})(vi).name); + Pout(si) = P.data(vi,si); + end + + P.thickness(vi,si) = cat_surf_rename(job.(sside{si})(vi).Pmesh,... + 'preside','','pp',fsavgDir,'dataname','thickness','ee',''); + + switch mapping + case 'abs_mapping' + switch job.mapping.(mapping).surface + case {1,'Central'}, addstr = ''; + case {2,'WM'}, addstr = sprintf(' -offset_value 0.5 -offset ""%s"" ',P.thickness{vi,si}); % + half thickness + case {3,'Pial'}, addstr = sprintf(' -offset_value -0.5 -offset ""%s"" ',P.thickness{vi,si}); % - half thickness + end + case {'rel_mapping','rel_equivol_mapping'} + switch job.mapping.(mapping).class + case {1,'GM'}, addstr = sprintf(' -thickness ""%s"" ',P.thickness{vi,si}); + case {2,'WM'}, error('Not yet supported'); + case {3,'CSF'}, error('Not yet supported'); + end + end + + cmd = sprintf('CAT_3dVol2Surf %s %s ""%s"" ""%s"" ""%s""',... + mappingstr, addstr,job.(sside{si})(vi).Pmesh, P.vol{vi}, Pout{si}); + cat_system(cmd,job.debug); + + if job.verb && ~job.merge_hemi + fprintf('Display %s\n',spm_file(P.data{vi,si},'link','cat_surf_display(''%s'')')); + end + end + + % merge hemispheres + if job.merge_hemi + + % combine left and right + M0 = gifti(Pout(:)); + for si=1:numel(Pout), delete(Pout{si}); end + M.cdata = []; for si=1:numel(Pout), M.cdata = [M.cdata; M0(si).cdata]; end + + M.private.metadata = struct('name','SurfaceID','value',P.data(vi,1)); + save(gifti(M), char(P.data(vi,1)), 'Base64Binary'); + + if job.verb + fprintf('Display %s\n',spm_file(char(P.data(vi,1)),'link','cat_surf_display(''%s'')')); + end + end + + cat_progress_bar('Set',vi); + end + + else + % native volume to individual surface + + for vi=1:numel(data_vol) + + [ppv,ffv,eev] = spm_fileparts(data_vol{vi}); + + % replace '.img' extension by '.hdr' extension to work with CAT + if strcmp(eev,'.img') + eev = '.hdr'; + end + + P.vol{vi} = fullfile(ppv,[ffv eev]); + + if ~strfind(ffv,job.(sside{1})(vi).name) + cat_io_cprintf('warn',sprintf('Surface and volume matching error.\n')) + continue + end + + % replace dots in volume name with ""_"" + ffv(strfind(ffv,'.')) = '_'; + + if strcmp(job.sinfo_lh(vi).dataname, 'central') + dsep = dsep0; + else + dsep = [dsep0 job.sinfo_lh(vi).dataname '_']; + end + + %% + for si=1:numel(side) + % also add volume name to differentiate between multiple volumes + P.data(vi,si) = cat_surf_rename(job.(sside{si})(vi).Pmesh,... + 'preside','','pp',spm_fileparts(job.(sside{si})(vi).fname),... + 'dataname',[job.datafieldname dsep ffv]); + + P.data(vi,si) = strrep(P.data(vi,si),'.gii',''); % remove .gii extension + + P.thickness(vi,si) = cat_surf_rename(job.(sside{si})(vi).Pmesh,... + 'preside','','pp',spm_fileparts(job.(sside{si})(vi).fname),... + 'dataname','pbt','ee',''); + if ~exist(P.thickness{vi,si},'file') + warning('File %s not found probably because you are using preprocessed data from an older version.',P.thickness{vi,si}); + P.thickness(vi,si) = cat_surf_rename(job.(sside{si})(vi).Pmesh,... + 'preside','','pp',spm_fileparts(job.(sside{si})(vi).fname),... + 'dataname','thickness','ee',''); + end + P.depthWM(vi,si) = cat_surf_rename(job.(sside{si})(vi).Pmesh,... + 'preside','','pp',spm_fileparts(job.(sside{si})(vi).fname),... + 'dataname','depthWM','ee',''); + P.depthCSF(vi,si) = cat_surf_rename(job.(sside{si})(vi).Pmesh,... + 'preside','','pp',spm_fileparts(job.(sside{si})(vi).fname),... + 'dataname','depthCSF','ee',''); + + switch mapping + case 'abs_mapping' + switch job.mapping.(mapping).surface + case {1,'Central'}, addstr = ''; + case {2,'WM'}, addstr = sprintf(' -offset_value 0.5 -offset ""%s"" ',P.thickness{vi,si}); % + half thickness + case {3,'Pial'}, addstr = sprintf(' -offset_value -0.5 -offset ""%s"" ',P.thickness{vi,si}); % - half thickness + end + case 'rel_mapping' % equi-distance approach + switch job.mapping.(mapping).class + case {1,'GM'}, addstr = sprintf(' -thickness ""%s"" ',P.thickness{vi,si}); + case {2,'WM'}, error('Not yet supported'); + case {3,'CSF'}, error('Not yet supported'); + end + case 'rel_equivol_mapping' % equi-volume approach + switch job.mapping.(mapping).class + case {1,'GM'}, addstr = sprintf(' -equivolume -thickness ""%s"" ',P.thickness{vi,si}); + case {2,'WM'}, error('Not yet supported'); + case {3,'CSF'}, error('Not yet supported'); + end + end + + cmd = sprintf('CAT_3dVol2Surf %s %s ""%s"" ""%s"" ""%s""',... + mappingstr, addstr, job.(sside{si})(vi).Pmesh, P.vol{vi}, P.data{vi,si}); + cat_system(cmd,job.debug); + + if job.gifti==1 + P.data{vi,si} = char(cat_io_FreeSurfer('fs2gii',struct('data',job.(sside{si})(vi).Pmesh,'cdata',P.data{vi,si},'delete',0))); + end + + if vi==1 && si==1 + + if job.debug + fprintf('\n%s\n',RS); + fprintf('\nMappingstring: %s\n',mappingstr); + end + end + + % don't print it for multi-value sampling + if job.verb && ~strcmp(job.sample{1},'multi') + fprintf('Display %s\n',spm_file(P.data{vi,si},'link','cat_surf_display(''%s'')')); + end + + end + + cat_progress_bar('Set',vi); + end + end + + for vi=1:numel(data_vol) + if istemp(vi) + delete(data_vol{vi}); + end + end + + % prepare output + if isfield(job,'merge_hemi') && job.merge_hemi + out.mesh = P.data(:,1); + else + out.lh = P.data(:,1); + out.rh = P.data(:,2); + if job.cerebellum + out.lc = P.data(:,3); + out.rc = P.data(:,4); + end + end + + cat_progress_bar('Clear'); + +end +","MATLAB" +"Neurology","ChristianGaser/cat12","spm_cat12.m",".m","13341","349","function spm_cat12(varargin) +% ______________________________________________________________________ +% CAT12 Toolbox wrapper to start CAT with different user modes or +% default files. Changing the user mode requires restarting of CAT and +% SPM. The expert user mode allows to control further parameters and +% semi-evaluated functions, whereas the developer mode contain parameter +% for internal tests and unsafe functions. +% +% cat12(action) +% +% CAT user modes: +% action = ['default','expert','developer'] +% +% CAT default files for other species (in development): +% action = ['oldwoldmonkeys'|'greaterapes'] +% +% CAT start with own default files: +% action = 'select' +% action = 'mypath/cat_defaults_mydefaults' +% +% ______________________________________________________________________ +% Christian Gaser, Robert Dahnke +% $Id$ + + +rev = '$Rev$'; +global deffile; +global cprintferror; % temporary, because of JAVA errors in cat_io_cprintf ... 20160307 +%try clearvars -global deffile; end %#ok + +% start cat with different default file +catdir = fileparts(mfilename('fullpath')); +catdef = fullfile(catdir,'cat_defaults.m'); + +% add path for octave mex-files +if strcmpi(spm_check_version,'octave') + if ismac + uts = uname; + if strcmp(uts.machine,'x86_64') + addpath(fullfile(catdir,'mexmaci')); + else + addpath(fullfile(catdir,'mexmaca')); + end + elseif isunix + addpath(fullfile(catdir,'mexa64')); + elseif ispc + addpath(fullfile(catdir,'mexw64')); + end +end + +% check that CAT12 is installed in the correct folder +pth = fileparts(mfilename('fullpath')); +[pth2, nam] = fileparts(pth); +if ~strcmp(nam,'cat12') + spm('alert!',sprintf('Please check that you do not have multiple CAT12 installations in your path!\nYour current CAT12 version is installed in %s but should be installed in %s',pth,fullfile(catdir)),'WARNING'); +end + +% find all zipped nifti's and unpack if necessary +niigz = cat_vol_findfiles(pth,'*.nii.gz'); +nii = cat_io_strrep(cat_vol_findfiles(pth,'*.nii'),'.nii','.nii.gz'); +niigz = setdiff(niigz,nii); +if ~isempty(niigz), gunzip(niigz); end +for fi = 1:numel(niigz), if cat_io_contains(niigz{fi},'templates_animals'), delete(niigz{fi}); end; end +clear niigz nii + +% check that mex-files on MAC are not blocked +try + feval(@cat_sanlm,single(rand(6,6,6)),1,3); +catch + if strcmpi(spm_check_version,'octave') + oldpath = pwd; + cd(pth) + compile + feval(@cat_sanlm,single(rand(6,6,6)),1,3); + cd(oldpath) + + % check that patches and updates exist + if ~exist('savexml') || ~exist('fcnchk') + error('Please update and patch SPM first') + end + elseif ismac + CATDir = fullfile(catdir); + web('https://en.wikibooks.org/wiki/SPM/Installation_on_64bit_Mac_OS_(Intel)#Troubleshooting'); + cat_io_cmd(sprintf('\nThe following commands might be executed as administrator to allow execution of CAT12 binaries and mex-files.'),'warning'); + cat_io_cmd(sprintf('You can also break that command here and run the commands that are listed on the open website under Troubleshooting manually.\n'),'warning'); + cmd = ['xattr -r -d com.apple.quarantine ' CATDir]; + system(cmd); fprintf([cmd '\n']); + cmd = ['chmod a+x ' CATDir '/CAT.mac*/CAT*']; + system(cmd); fprintf([cmd '\n']); + end +end + + +% get expert level except for standalone installation +expert = cat_get_defaults('extopts.expertgui'); + +if nargin==0 && (isempty(deffile) || strcmp(deffile,catdef)) + deffile = catdef; + if ~strcmp(cat_get_defaults('extopts.species'),'human') || expert>0 + restartspm = 1; + else + restartspm = 0; + end +elseif nargin==1 + deffile = varargin{1}; + restartspm = 1; +elseif nargin==2 + deffile = varargin{1}; + catdef = varargin{2}; + restartspm = 1; +else + deffile = catdef; + restartspm = 1; +end + + +% choose filesspecies +speciesdisp = ''; +switch cat_get_defaults('extopts.species') + case {'select','human','default','expert','developer'} + % nothing to do + otherwise + % load default to remove animal settings + try clearvars -global cat; end %#ok + [deffile_pp,deffile_ff] = fileparts(catdef); + oldwkd = cd; + cd(deffile_pp); + try clearvars -global cat; end %#ok + clear cat; + eval(deffile_ff); + eval('global cat;'); + cd(oldwkd); +end +switch lower(deffile) + case 'select' + deffile = spm_select(1,'batch','Select CAT default file!','',catdir); + if isempty(deffile) + return + end + case {'default','human',lower(catdef)} + mycat = cat_get_defaults; + mycat.extopts.expertgui = 0; + restartspm = 1; + deffile = catdef; + case 'expert' + mycat = cat_get_defaults; + mycat.extopts.expertgui = 1; + restartspm = 1; + deffile = catdef; + case 'developer' + mycat = cat_get_defaults; + mycat.extopts.expertgui = 2; + restartspm = 1; + deffile = catdef; + case {'greaterapes','lesserapes','oldworldmonkeys','newworldmonkeys','mammals','chimpanzees','dogs',... + 'greaterape' ,'lesserape' ,'oldworldmonkey' ,'newworldmonkey', 'mammal', 'chimpanzee' ,'dog', ... + 'baboons', 'macaques', ... + 'baboon' ,'macaca', 'macaque'} + switch lower(deffile) + case {'greaterapes','greaterape'}, species = 'ape_greater'; speciesdisp = ' (greater apes)'; + %case {'lesserapes','lesserape'}, species = 'ape_lesser'; speciesdisp = ' (lesser apes)'; + case {'oldworldmonkeys','oldworldmonkey'}, species = 'monkey_oldworld'; speciesdisp = ' (oldworld monkeys)'; + %case {'newworldmonkeys','newworldmonkey'}, species = 'monkey_newworld'; speciesdisp = ' (newworld monkeys)'; + %case {'mammals','mammal'}, species = 'mammal'; speciesdisp = ' (mammal)'; + case {'chimpanzees','chimpanzee'}, species = 'chimpanzee'; speciesdisp = ' (chimpanzee)'; + case {'macaque','macaques'}, species = 'macaque'; speciesdisp = ' (macaque)'; + case {'baboons','baboon'}, species = 'baboon'; speciesdisp = ' (baboon)'; + case {'dogs','dog'}, species = 'dog'; speciesdisp = ' (dogs)'; + otherwise + error('CAT:unreadySpecies','Templates of species ""%s"" are not ready yet.\n',deffile); + end + + mycat = cat_get_defaults; + % change TPM and user higher resolution and expect stronger bias + mycat.opts.tpm = {fullfile(catdir,'templates_animals',[species '_TPM.nii'])}; + mycat.opts.biasreg = 0.001; % less regularisation + mycat.opts.biasfwhm = 30; % stronger fields + mycat.opts.samp = 1; % smaller resampling + mycat.opts.affreg = 'none'; % no affine regularisation + % use species specific templates, higher resolution, stronger corrections and less affine registration (by SPM) + mycat.extopts.species = species; + %mycat.extopts.brainscale = 200; % non-human brain volume in cm3 (from literature) or scaling in mm (check your data) + mycat.extopts.darteltpm = {fullfile(catdir,'templates_animals',[species '_Template_1.nii'])}; % Indicate first Dartel template + mycat.extopts.shootingtpm = {fullfile(catdir,'templates_animals',[species '_Template_0_GS.nii'])}; % Indicate first Shooting template + mycat.extopts.cat12atlas = {fullfile(catdir,'templates_animals',[species '_cat.nii'])}; % VBM atlas with major regions for VBM, SBM & ROIs + mycat.extopts.brainmask = {fullfile(catdir,'templates_animals',[species '_brainmask.nii'])}; % brainmask for affine registration + mycat.extopts.T1 = {fullfile(catdir,'templates_animals',[species '_T1.nii'])}; % T1 for affine registration + mycat.extopts.sanlm = 3; % ISARNLM for stronger corrections + mycat.extopts.restype = 'best'; + mycat.extopts.resval = [0.50 0.30]; % higher internal resolution + %mycat.extopts.APP = 1070; % less affine registration, but full corrections (by SPM) + mycat.extopts.vox = 0.50; % voxel size for normalized data + mycat.extopts.bb = [[-inf -inf -inf];[inf inf inf]]; % template default + mycat.extopts.WMHC = 0; % not in primates yet + mycat.extopts.expertgui = 2; % set to expert later ... + mycat.extopts.ignoreErrors = 1; + switch species + case 'monkey_oldworld' + mycat.extopts.atlas = { ... + fullfile(catdir,'templates_animals','monkey_oldworld_atlas_inia19NeuroMaps.nii') 1 {'csf','gm','wm'} 1; + }; + case 'chimpanzee' + mycat.extopts.atlas = { ... + fullfile(catdir,'templates_animals','chimpanzee_atlas_davi.nii') 1 {'csf','gm','wm'} 1; + }; + otherwise + mycat.extopts.atlas = {}; + mycat.output.ROI = 0; + end + + restartspm = 1; + deffile = catdef; + otherwise + % lazy input - no extension + [deffile_pp,deffile_ff,deffile_ee] = fileparts(deffile); + if isempty(deffile_ee) + deffile_ee = '.m'; + end + % lazy input - no directory + if isempty(deffile_pp) + if exist(fullfile(pwd,deffile_ff,deffile_ee),'file') + deffile_pp = pwd; + else + deffile_pp = fullfile(catdir); + end + end + deffile = fullfile(deffile_pp,[deffile_ff,deffile_ee]); + + if isempty(deffile) || ~exist(deffile,'file') + help spm_cat12; + error('CAT:unknownDefaultFile','Unknown action or nonexisting default file ""%s"".\n',deffile); + end +end + + +% The cat12 global variable is created and localy destroyed, because we want to call the cat12 function. +if exist('mycat','var') + try clearvars -global cat; end %#ok + eval('global cat; cat = mycat;'); +else + % set other defaultfile + oldwkd = cd; + cd(deffile_pp); + try clearvars -global cat; end %#ok + clear cat; + eval(deffile_ff); + eval('global cat;'); + cd(oldwkd); +end + +% initialize SPM +eval('global defaults;'); +% this is required to initialize the atlas variable for default users +if restartspm + clear defaults; + spm_jobman('initcfg'); +end +clear cat; + +% initialize atlas variable +exatlas = cat_get_defaults('extopts.atlas'); +for ai = 1:size(exatlas,1) + if exatlas{ai,2}<=expert && exist(exatlas{ai,1},'file') + [pp,ff,ee] = spm_fileparts(exatlas{ai,1}); + + % if output.atlases.ff does not exist then set it by the default file value + if isempty(cat_get_defaults(['output.atlases.' ff])) + cat_get_defaults(['output.atlases.' ff], exatlas{ai,4}) + end + end +end + +exsatlas = cat_get_defaults('extopts.satlas'); +for ai = 1:size(exsatlas,1) + if exsatlas{ai,3}<=expert && exist(exsatlas{ai,2},'file') + name = exsatlas{ai,1}; + + % if output.atlases.ff does not exist then set it by the default file value + if isempty(cat_get_defaults(['output.satlases.' name])) + cat_get_defaults(['output.satlases.' name], exsatlas{ai,4}) + end + end +end + + + +% temporary, because of JAVA errors in cat_io_cprintf ... 20160307 +if expert<2 + cprintferror=1; +end + +spm('FnBanner',mfilename,cat_version); +[Finter,Fgraph] = spm('FnUIsetup','CAT12.9'); +url = fullfile(fileparts(mfilename('fullpath')),'doc','cat.html'); + +% open interactive help for newer version because display of html pages does not work anymore +if cat_io_matlabversion > 20212 + % SPM header image + Pposter = fullfile( catdir, 'doc', 'images', 'CAT_Poster.jpg'); + F = spm_figure('GetWin'); + spm_figure('clear',F); + Fpos = get(F,'Position'); + h = image(imread(Pposter)); + set(get(h,'Parent'),'Position',[0 0 1 1],'Visible','off'); + set(F,'Position',Fpos); + + % CAT help + web(url,'-noaddressbox','-new') +else + spm_help('!Disp',url,'',Fgraph,'Computational Anatomy Toolbox for SPM12 or SPM25'); +end + +% check that binaries for surface tools are running +cat_system('CAT_3dVol2Surf'); + +%% add some directories +spm_select('PrevDirs',{fullfile(catdir)}); + +%% command line output +cat_io_cprintf('silentreset'); +switch expert + case 0, expertguitext = ''; + case 1, expertguitext = ['Expert Mode' speciesdisp]; + case 2, expertguitext = ['Developer Mode' speciesdisp]; +end +cat_io_cprintf([0.0 0.0 0.5],sprintf([ ... + '\n' ... + ' _______ ___ _______ \n' ... + ' | ____/ / _ \\\\ \\\\_ _/ ' expertguitext '\n' ... + ' | |___ / /_\\\\ \\\\ | | Computational Anatomy Toolbox\n' ... + ' |____/ /_/ \\\\_\\\\ |_| CAT12.9 - https://neuro-jena.github.io\n\n'])); +cat_io_cprintf([0.0 0.0 0.5],' CAT default file:\n\t%s\n\n',deffile); + +% call GUI +cat12('fig'); + +% animal template dir warning +if exist('species','var') && ~strcmp(species,'human') && ~exist(fullfile(catdir,'templates_animals'),'dir') + cat_io_cprintf('err',sprintf([ ... + '\n Warning: The ""templates_animals"" subdirectory is missing. ' ... + '\n You can download it from: ' ... + '\n https://github.com/robdahn/primetemp \n\n'])); +end + +% force use of PET modality in SPM to avoid problems of very low variance in spm_spm.m +warning off +spm('chmod','PET'); +warning on +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_vol_qa201602.m",".m","38258","884","function varargout = cat_vol_qa201602(action,varargin) +% CAT Preprocessing T1 Quality Assurance +% ______________________________________________________________________ +% +% Estimation of image quality measures like noise, inhomogeneity, +% contrast, resolution, etc. and scaling for school marks. +% +% [QAS,QAM] = cat_vol_qa(action,varargin) +% +% +% 1) Use GUI interface to choose segmentation and automatic setting of +% original and modified image (if available) +% [QAS,QAM] = cat_vol_qa() = cat_vol_qa('p0') +% +% [QAS,QAM] = cat_vol_qa('p0'[,opt]) - p0 class image +% [QAS,QAM] = cat_vol_qa('p#'[,opt]) - p1,p2,p3 class images +% [QAS,QAM] = cat_vol_qa('c#'[,opt]) - c1,c2,c3 class images +% [QAS,QAM] = cat_vol_qa('*#'[,opt]) - csf,gm,wm class images +% [QAS,QAM] = cat_vol_qa('p0',Pp0[,opt]) - no GUI call +% [QAS,QAM] = cat_vol_qa('p#',Pp1,Pp2,Pp3,[,opt]) - no GUI call +% [QAS,QAM] = cat_vol_qa('c#',Pc1,Pc2,Pc3,[,opt]) - no GUI call +% [QAS,QAM] = cat_vol_qa('c#',Pcsf,Pgm,Pwm,[,opt]) - no GUI call +% +% +% 2) Use GUI interface to choose all images like for other segmentations +% and modalities with a similar focus of CSF, GM, and WM tissue +% contrast such as PD, T2, or FLASH. +% [QAS,QAM] = cat_vol_qa('p0+'[,opt]) - p0 class image +% [QAS,QAM] = cat_vol_qa('p#+'[,opt]) - p1,p2,p3 class images +% [QAS,QAM] = cat_vol_qa('c#+'[,opt]) - c1,c2,c3 class images +% [QAS,QAM] = cat_vol_qa('*#+'[,opt]) - csf,gm,wm class images +% [QAS,QAM] = cat_vol_qa('p0+',Pp0,Po[,Pm,opt]) - no GUI call +% [QAS,QAM] = cat_vol_qa('p#+',Pp1,Pp2,Pp3,Po[,Pm,opt]) - no GUI call +% [QAS,QAM] = cat_vol_qa('c#+',Pc1,Pc2,Pc3,Po[,Pm,opt]) - no GUI call +% +% +% 3) Use GUI interface to choose all images. I.e. for other segmentations +% and modalities without focus of GM-WM contrast such as DTI MTI. +% [ not implemented yet ] +% +% +% 4) CAT12 internal preprocessing interface +% (this is the processing case that is also called in all other cases) +% [QAS,QAM] = cat_vol_qa('cat12',Yp0,Po,Ym,res[,opt]) +% +% +% Pp0 - segmentation files (p0*.nii) +% Po - original files (*.nii) +% Pm - modified files (m*.nii) +% Yp0 - segmentation image matrix +% Ym - modified image matrix +% +% opt = parameter structure +% opt.verb = verbose level [ 0=nothing | 1=points | 2*=times ] +% opt.redres = resolution in mm for intensity scaling [ 4* ]; +% opt.write_csv = final cms-file +% opt.write_xml = images base xml-file +% opt.sortQATm = sort QATm output +% opt.orgval = original QAM results (no marks) +% opt.recalc = +% opt.avgfactor = +% opt.prefix = prefix of xml output file (default cat_*.xml) +% +% ______________________________________________________________________ +% Robert Dahnke +% Structural Brain Mapping Group +% University Jena +% +% $Id$ +% ______________________________________________________________________ + +%#ok<*ASGLU> + + % get current release number + [n, rev_cat] = cat_version; + + % init output + QAS = struct(); QAM = struct(); + cat_qa_warnings = struct('identifier',{},'message',{}); + cat_warnings = struct('identifier',{},'message',{}); + if nargout>0, varargout = cell(1,nargout); end + + try + if strcmp(action,'cat12err') + [mrifolder, reportfolder] = cat_io_subfolders(varargin{1}.job.data,varargin{1}.job); + elseif strcmp(action,'cat12') + [mrifolder, reportfolder] = cat_io_subfolders(varargin{2},varargin{6}.job); + else + [mrifolder, reportfolder] = cat_io_subfolders(varargin{4}.catlog,varargin{6}.job); + end + catch + mrifolder = 'mri'; + reportfolder = 'report'; + end + + % no input and setting of default options + if nargin==0, action='p0'; end + if isstruct(action) + Pp0 = action.data; + action = 'p0'; + end + if nargin==3 && isstruct(varargin{2}) && isstruct(varargin{2}) + opt = cat_check('checkinopt',varargin{2},defaults); + nopt = 1; + elseif nargin==8 && isstruct(varargin{6}) && isstruct(varargin{6}) + opt = cat_check('checkinopt',varargin{6},defaults); + nopt = 1; + else + opt = defaults; + nopt = 0; + end + + % check input by action + switch action + case {'p0','p0+'} + % segment image cases + if nargin<=3 + if (nargin-nopt)<2 + Pp0 = cellstr(spm_select(inf,'image',... + 'select p0-segment image',{},pwd,'^p0.*')); + if isempty(Pp0{1}), return; end + else + Pp0 = varargin{1}; + end + if numel(action)==2 + Po = Pp0; Pm = Pp0; + for fi=1:numel(Pp0) + [pp,ff,ee] = spm_fileparts(Pp0{fi}); + + Po{fi} = fullfile(pp,[ff(3:end) ee]); + Pm{fi} = fullfile(pp,[opt.mprefix ff(3:end) ee]); + Pmv{fi} = fullfile(pp,['m' ff(3:end) ee]); %#ok + if ~exist(Pm{fi},'file') && strcmp(opt.mprefix,'nm') && exist(Pmv{fi},'file') + fprintf('Preparing %s.\n',Pmv{fi}); + cat_vol_sanlm(Pmv{fi},'n'); + end + + if ~exist(Po{fi},'file'), Po{fi}=''; end + if ~exist(Pm{fi},'file'), Pm{fi}=''; end + end + else + Po = cellstr(spm_select(repmat(numel(Pp0),1,2),... + 'image','select original image(s)',{},pwd,'.*')); + Pm = cellstr(spm_select(repmat(numel(Pp0),1,2),... + 'image','select modified image(s)',{},pwd,'.*')); + end + elseif nargin<=5 + Pp0 = varargin{1}; + Po = varargin{2}; + Pm = varargin{3}; + else + error('MATLAB:cat_vol_qa:inputerror',... + 'Wrong number/structure of input elements!'); + end + case {'p#','c#','*#','p#+','c#+','*#+'} + % tissue class image cases + if nargin-1<=2 % GUI + if (nargin-nopt)<2 + if action(1)=='p' || action(1)=='c' + % cat/spm case + Pcsf = cellstr(spm_select(inf,'image',... + 'select p1-segment image',{},pwd,['^' action(1) '1.*'])); + if isempty(Pcsf{1}), return; end + Pgm=Pcsf; Pwm=Pcsf; + for fi=1:numel(Pcsf) + [pp,ff,ee] = spm_fileparts(Pcsf{fi}); + + Pgm{fi} = fullfile(pp,[action(1) '2' ff(3:end) ee]); + Pwm{fi} = fullfile(pp,[action(1) '3' ff(3:end) ee]); + end + else + Pcsf = cellstr(spm_select(inf,'image',... + 'select CSF segment image(s)',{},pwd,'.*')); + if isempty(Pcsf{1}), return; end + %Pgm = cellstr(spm_select(repmat(numel(Pcsf),1,2),... + % 'image','select GM segment image(s)',{},pwd,'.*')); + %Pwm = cellstr(spm_select(repmat(numel(Pcsf),1,2),... + % 'image','select WM segment image(s)',{},pwd,'.*')); + end + if numel(action)==2 + Pp0=Pcsf; Po=Pcsf; Pm=Pcsf; + for fi=1:numel(Pcsf) + [pp,ff,ee] = spm_fileparts(Pcsf{fi}); + Po{fi} = fullfile(pp,[ff(3:end) ee]); + Pm{fi} = fullfile(pp,['m' ff(3:end) ee]); + Pp0{fi} = fullfile(pp,['p0' ff(3:end) ee]); + end + else + Po = cellstr(spm_select(repmat(numel(Pcsf),1,2),... + 'image','select original image(s)',{},pwd,'.*')); + Pm = cellstr(spm_select(repmat(numel(Pcsf),1,2),... + 'image','select modified image(s)',{},pwd,'.*')); + Pp0=Pcsf; + for fi=1:numel(Pcsf) + [pp,ff,ee] = spm_fileparts(Pcsf{fi}); + Pp0{fi} = fullfile(pp,['p0' ff(3:end) ee]); + end + end + + % wie komm ich zum p0??? + else + Pp0 = varargin{1}; + end + elseif nargin==5 || nargin==6 + else + error('MATLAB:cat_vol_qa:inputerror',... + 'Wrong number/structure of input elements!'); + end + + Yp0 = 1; + case 'cat12err' + opt = cat_check('checkinopt',varargin{end},defaults); + case 'cat12' + % CAT12 internal input + if nargin>3 + Yp0 = varargin{1}; + Vo = spm_vol(varargin{2}); + Yo = single(spm_read_vols(Vo)); + Ym = varargin{3}; + res = varargin{4}; + V = res.image; + cat_warnings = varargin{5}; + species = varargin{6}; + if nargin>8, Pp0 = varargin{8}; end % nargin count also parameter + % opt = varargin{end} in line 96) + opt.verb = 0; + + % reduce to original native space if it was interpolated + if any(size(Yp0)~=Vo.dim) + if isfield(Vo,'private'), Vo = rmfield(Vo,'private'); end + if isfield(Vo,'mat0'), Vo = rmfield(Vo,'mat0'); end + Vo.dat = zeros(Vo.dim,'single'); Vo.dt(1) = 16; Vo.pinfo(3) = 0; + + Vp0t = res.image; + if isfield(Vp0t,'private'), Vp0t = rmfield(Vp0t,'private'); end + if isfield(Vp0t,'mat0'), Vp0t = rmfield(Vp0t,'mat0'); end + Vp0t.dt(1) = 16; + Vp0t.pinfo(3) = 0; + Vp0t.dat = Yp0; + + % resampling and corrections of the Yp0 + % Vp0t = spm_write_vol(Vp0t,double(Yp0)); + [Vtpm,Yp0] = cat_vol_imcalc(Vp0t,Vo,'i1',struct('interp',6,'verb',0)); + rf = 50; + Yp0 = single(Yp0); + Yp0r = round(Yp0*rf)/rf; + YMR = false(size(Yp0)); + for i=1:4, YMR = YMR | (Yp0>(i-1/rf) & Yp0<(i+1/rf)); end + Yp0(YMR) = Yp0r(YMR); clear YMR Ynr; + + % resampling of the corrected image + Vp0t.dat = Ym; + [Vtpm,Ym] = cat_vol_imcalc(Vp0t,Vo,'i1',struct('interp',6,'verb',0)); + Ym = single(Ym); + end + + else + error('MATLAB:cat_vol_qa:inputerror',... + 'Wrong number/structure of input elements!'); + end + otherwise + error('MATLAB:cat_vol_qa:inputerror',... + 'Wrong number/structure of input elements!'); + end + if ~exist('species','var'), species='human'; end + + + % + % -------------------------------------------------------------------- + [QA,QMAfn] = cat_stat_marks('init'); + stime = clock; + + + + % Print options + % -------------------------------------------------------------------- + opt.snspace = [70,7,3]; + Cheader = {'scan'}; + Theader = sprintf(sprintf('%%%ds:',opt.snspace(1)-1),'scan'); + Tline = sprintf('%%5d) %%%ds:',opt.snspace(1)-8); + Tline2 = sprintf('%%5d) %%6s%%%ds:',opt.snspace(1)-14); + Tavg = sprintf('%%%ds:',opt.snspace(1)-1); + TlineE = sprintf('%%5d) %%%ds: %%s',opt.snspace(1)-7); + for fi=1:numel(QMAfn) + Cheader = [Cheader QMAfn{fi}]; %#ok + Theader = sprintf(sprintf('%%s%%%ds',opt.snspace(2)),Theader,... + QMAfn{fi}(1:min(opt.snspace(2)-1,numel(QMAfn{fi})))); + Tline = sprintf('%s%%%d.%df',Tline,opt.snspace(2),opt.snspace(3)); + Tline2 = sprintf('%s%%%d.%df',Tline2,opt.snspace(2),opt.snspace(3)); + Tavg = sprintf('%s%%%d.%df',Tavg,opt.snspace(2),opt.snspace(3)); + end + Cheader = [Cheader 'IQM']; + Theader = sprintf(sprintf('%%s%%%ds',opt.snspace(2)),Theader,'IQM'); + Tline = sprintf('%s%%%d.%df\n',Tline,opt.snspace(2),opt.snspace(3)); + Tline2 = sprintf('%s%%%d.%df\n',Tline2,opt.snspace(2),opt.snspace(3)); + Tavg = sprintf('%s%%%d.%df\n',Tavg,opt.snspace(2),opt.snspace(3)); + + + + + + + % estimation part + switch action + case {'p0','p#','c#','*#','p0+','p#+','c#+','*#+'} + % loop for multiple files + % return for empty input + if isempty(Pp0) || (isempty(Pp0{1}) && numel(Pp0)<=1) + cat_io_cprintf('com','No images for QA!\n'); + return + end + + if opt.verb>1 + fprintf('\n%s\n\n%s\n%s\n', ... + sprintf('CAT Preprocessing T1 Quality Assurance (%s):',... + sprintf('Rev: %s',rev_cat)), Theader,repmat('-',size(Theader))); + end + + qamat = nan(numel(Po),numel(QMAfn)); + qamatm = nan(numel(Po),numel(QMAfn)); + mqamatm = 9.9*ones(numel(Po),1); + + + QAS = struct(); QAM = struct(); + + for fi=1:numel(Pp0) + try + if exist(Po{fi},'file') + Vo = spm_vol(Po{fi}); + else + error('cat_vol_qa201602:noYo','No original image.'); + end + + Yp0 = single(spm_read_vols(spm_vol(Pp0{fi}))); + if ~isempty(Pm{fi}) && exist(Pm{fi},'file') + Ym = single(spm_read_vols(spm_vol(Pm{fi}))); + else + error('cat_vol_qa201602:noYm','No corrected image.'); + end + + [QASfi,QAMfi,cat_qa_warnings{fi}] = cat_vol_qa201602('cat12',Yp0,Vo,Ym,'',cat_warnings,species,opt); + + + QAS = cat_io_updateStruct(QAS,QASfi,0,fi); + QAM = cat_io_updateStruct(QAM,QAMfi,0,fi); + + + % color for the differen mark cases (opt.process) + for fni=1:numel(QMAfn) + qamat(fi,fni) = QAS(fi).qualitymeasures.(QMAfn{fni}); + qamatm(fi,fni) = QAM(fi).qualitymeasures.(QMAfn{fni}); + end + mqamatm(fi) = QAM(fi).qualitymeasures.rms; + mqamatm(fi) = max(0,min(9.5, mqamatm(fi))); + + + % print the results for each scan + if opt.verb>1 + if opt.orgval + cat_io_cprintf(opt.MarkColor(max(1,round( mqamatm(fi,:)/9.5 * ... + size(opt.MarkColor,1))),:),sprintf(Tline,fi,... + QAS(fi).filedata.fnames, ... spm_str_manip(QAS(fi).filedata.file,['f' num2str(opt.snspace(1) - 14)]),... + qamat(fi,:),max(1,min(6,mqamatm(fi))))); + else + cat_io_cprintf(opt.MarkColor(max(1,round( mqamatm(fi,:)/9.5 * ... + size(opt.MarkColor,1))),:),sprintf(Tline,fi,... + QAS(fi).filedata.fnames, ... spm_str_manip(QAS(fi).filedata.file,['f' num2str(opt.snspace(1) - 14)]),... + qamatm(fi,:),max(1,min(6,mqamatm(fi))))); + end + end + catch %#ok ... normal ""catch err"" does not work for MATLAB 2007a + try %#ok + e = lasterror; %#ok ... normal ""catch err"" does not work for MATLAB 2007a + + switch e.identifier + case {'cat_vol_qa201602:noYo','cat_vol_qa201602:noYm','cat_vol_qa201602:badSegmentation'} + em = e.identifier; + otherwise + em = ['ERROR:\n' repmat(' ',1,10) e.message '\n']; + for ei=1:numel(e.stack) + em = sprintf('%s%s%5d: %s\n',em,repmat(' ',1,10),... + e.stack(ei).line(end),e.stack(ei).name); + end + end + + [pp,ff] = spm_fileparts(Po{fi}); + QAS(fi).filedata.fnames = [spm_str_manip(pp,sprintf('k%d',floor( (opt.snspace(1)-19) /3) - 1)),'/',... + spm_str_manip(ff,sprintf('k%d',(opt.snspace(1)-19) - floor((opt.snspace(1)-14)/3)))]; + cat_io_cprintf(opt.MarkColor(end,:),sprintf(TlineE,fi,... + QAS(fi).filedata.fnames,[em '\n'])); +% spm_str_manip(Po{fi},['f' num2str(opt.snspace(1) - 14)]),em)); + end + end + end + + + + % sort by mean mark + % ---------------------------------------------------------------- + if opt.sortQATm && numel(Po)>1 + % sort matrix + [smqamatm,smqamatmi] = sort(mqamatm,'ascend'); + sqamatm = qamatm(smqamatmi,:); + sqamat = qamat(smqamatmi,:); + + % print matrix + if opt.verb>0 + fprintf('%s\n',repmat('-',size(Theader))); + for fi=1:numel(QAS) + if opt.orgval + cat_io_cprintf(opt.MarkColor(min(size(opt.MarkColor,1),... + round( smqamatm(fi,:)/9.5 * ... + size(opt.MarkColor,1))),:),sprintf(... + Tline2,fi,sprintf('(%d)',smqamatmi(fi)),... + QAS(smqamatmi(fi)).filedata.fnames, ... + ...spm_str_manip(QAS(smqamatmi(fi)).filedata.file,['f' num2str(opt.snspace(1) - 14)]),... + sqamat(fi,:),max(1,min(6,smqamatm(fi))))); + else + cat_io_cprintf(opt.MarkColor(min(size(opt.MarkColor,1),... + round( smqamatm(fi,:)/9.5 * ... + size(opt.MarkColor,1))),:),sprintf(... + Tline2,fi,sprintf('(%d)',smqamatmi(fi)),... + QAS(smqamatmi(fi)).filedata.fnames, ... + ...spm_str_manip(QAS(smqamatmi(fi)).filedata.file,['f' num2str(opt.snspace(1) - 14)]),... + sqamatm(fi,:),smqamatm(fi))); + end + end + end + else + %[smqamatm,smqamatmi] = sort(mqamatm,'ascend'); + %sqamatm = qamatm(smqamatmi,:); + end + % print the results for each scan + if opt.verb>1 && numel(Pp0)>1 + fprintf('%s\n',repmat('-',size(Theader))); + if opt.orgval + fprintf(Tavg,'mean',cat_stat_nanmean(qamat,1),mean(mqamatm,1)); %#ok + fprintf(Tavg,'std' , cat_stat_nanstd(qamat,1), std(mqamatm,1)); %#ok + else + fprintf(Tavg,'mean',cat_stat_nanmean(qamatm,1),mean(mqamatm,1)); %#ok + fprintf(Tavg,'std' , cat_stat_nanstd(qamatm,1), std(mqamatm,1)); %#ok + end + %fprintf('%s\n',repmat('-',size(Theader))); + %fprintf(Tavg,'mean',mean(qamat,1)); + %fprintf(Tavg,'std', std(qamat,1)); + end + if opt.verb>0, fprintf('\n'); end + + + + % result tables (cell structures) + % ---------------------------------------------------------------- + if nargout>2 && opt.write_csv + QAT = [Cheader(1:end-1); ... there is no mean for the original measures + Po , num2cell(qamat); ... + 'mean' , num2cell(cat_stat_nanmean(qamat,1)); ... + 'std' , num2cell( cat_stat_nanstd(qamat,1,1))]; + QATm = [Cheader; ... + Po , num2cell(qamatm) , ... + num2cell(cat_stat_nanmean(qamatm,2)); ... + 'mean' , num2cell(cat_stat_nanmean(qamatm,1)) , ... + num2cell(cat_stat_nanmean(mqamatm,1)); ... + 'std' , num2cell( cat_stat_nanstd(qamatm,1,1)), ... + num2cell( cat_stat_nanstd(mqamatm,1))]; + + + % write csv results + % -------------------------------------------------------------- + if opt.write_csv + pp = spm_fileparts(Pp0{1}); + cat_io_csv(fullfile(pp,reportfolder,[opt.prefix num2str(numel(Vo),'%04d') ... + 'cat_vol_qa_values.csv']),QAT); + cat_io_csv(fullfile(pp,reportfolder,[opt.prefix num2str(numel(Vo),'%04d') ... + 'cat_vol_qa_marks.csv']),QATm); + end + end + + if opt.verb>0 + fprintf('Quality Control for %d subject was done in %0.0fs\n', ... + numel(Pp0),etime(clock,stime)); fprintf('\n'); + end + + + case 'cat12err' + + % file information + % ---------------------------------------------------------------- + [pp,ff,ee] = spm_fileparts(Vo.fname); + if strcmp(ee,'.gz'), [~,ff] = spm_fileparts(ff); ee = '.nii.gz'; end + [pp0,ff0,ee0] = spm_fileparts(Pp0); + [QAS.filedata.path,QAS.filedata.file] = spm_fileparts(Vo.fname); + QAS.filedata.fname = Vo.fname; + QAS.filedata.F = Vo.fname; + QAS.filedata.Fm = fullfile(pp0,['m' ff ee0]); + QAS.filedata.Fp0 = fullfile(pp0,['p0' ff ee0]); + QAS.filedata.fnames = [spm_str_manip(pp,sprintf('k%d',... + floor( max(opt.snspace(1)-19-ff,opt.snspace(1)-19)/3) - 1)),'/',... + spm_str_manip(ff,sprintf('k%d',... + (opt.snspace(1)-19) - floor((opt.snspace(1)-14)/3)))]; + + + % software, parameter and job information + % ---------------------------------------------------------------- + [nam,rev_spm] = spm('Ver'); + AS.software.version_spm = rev_spm; + A = ver; + for i=1:length(A) + if strcmp(A(i).Name,'MATLAB'), + QAS.software.version_matlab = A(i).Version; + end + end + clear A + QAS.software.version_cat = rev_cat; + QAS.software.function = which('cat_vol_qa'); + QAS.software.markdefs = which('cat_stat_marks'); + QAS.software.qamethod = action; + QAS.software.date = datestr(clock,'yyyymmdd-HHMMSS'); + + QAS.hardware.computer = mexext; + try + QAS.hardware.numcores = max(feature('numcores'),1); + catch + QAS.hardware.numcores = 1; + end + + + %opt.job = rmfield(opt.job,{'data','channel','output'}); + %QAS.parameter = opt.job; + QAS.parameter.vbm = rmfield(cat_get_defaults,'output'); + QAS.parameter.caterr = opt.caterr; + QAS.error = opt.caterrtxt; + + % export + if opt.write_xml + cat_io_xml(fullfile(pp,reportfolder,[opt.prefix ff '.xml']),QAS,'write'); + end + + case 'cat12' + % estimation of the measures for the single case + + + % file information + % ---------------------------------------------------------------- + [pp,ff,ee] = spm_fileparts(Vo.fname); + if strcmp(ee,'.gz'), [~,ff] = spm_fileparts(ff); ee = '.nii.gz'; end + [pp0,ff0,ee0] = spm_fileparts(Pp0); + [QAS.filedata.path,QAS.filedata.file] = spm_fileparts(Vo.fname); + QAS.filedata.fname = Vo.fname; + QAS.filedata.F = Vo.fname; + QAS.filedata.Fm = fullfile(pp0,['m' ff ee0]); + QAS.filedata.Fp0 = fullfile(pp0,['p0' ff ee0]); + QAS.filedata.fnames = [spm_str_manip(pp,sprintf('k%d',... + floor( max(opt.snspace(1)-19-ff,opt.snspace(1)-19)/3) - 1)),'/',... + spm_str_manip(ff,sprintf('k%d',... + (opt.snspace(1)-19) - floor((opt.snspace(1)-14)/3)))]; + + + % software, parameter and job information + % ---------------------------------------------------------------- + [nam,rev_spm] = spm('Ver'); + QAS.software.version_spm = rev_spm; + A = ver; + for i=1:length(A) + if strcmp(A(i).Name,'MATLAB'), + QAS.software.version_matlab = A(i).Version; + end + end + clear A + QAS.software.version_cat = rev_cat; + QAS.software.function = which('cat_vol_qa'); + QAS.software.markdefs = which('cat_stat_marks'); + QAS.software.qamethod = action; + QAS.software.date = datestr(clock,'yyyymmdd-HHMMSS'); + QAS.software.cat_warnings = cat_warnings; + + % @Christian: Do we only want the cat parameter or is it important to have further information? + % I think cat defaults would be enought for the beginning. + % Furhter data will only be excess baggage for the cat*.xml file. + %QAS.parameter.spm = spm_get_defaults; + QAS.parameter.vbm = rmfield(cat_get_defaults,'output'); + if isfield(opt,'job') && isfield(opt.job,'opts'), QAS.parameter.opts = opt.job.opts; end + if isfield(opt,'job') && isfield(opt.job,'extopts'), QAS.parameter.opts = opt.job.extopts; end + if exist('res','var') + rf = {'Affine','Affine0','lkp','mn','vr','ll'}; % important SPM preprocessing variables + for rfi=1:numel(rf) + if isfield(res,rf{rfi}), QAS.SPMpreprocessing.(rf{rfi}) = res.(rf{rfi}); end + end + end + + + %% inti, volumina, resolution, boundary box + % --------------------------------------------------------------- + QAS.software.cat_qa_warnings = struct('identifier',{},'message',{}); + vx_vol = sqrt(sum(Vo.mat(1:3,1:3).^2)); + vx_voli = sqrt(sum(V.mat(1:3,1:3).^2)); + Yp0toC = @(Yp0,c) 1-min(1,abs(Yp0-c)); + + % volumina + QAS.subjectmeasures.vol_abs_CGW = [prod(vx_vol)/1000 .* sum(Yp0toC(Yp0(:),1)), ... CSF + prod(vx_vol)/1000 .* sum(Yp0toC(Yp0(:),2)), ... GM + prod(vx_vol)/1000 .* sum(Yp0toC(Yp0(:),3)), ... WM + prod(vx_vol)/1000 .* sum(Yp0toC(Yp0(:),4))]; % WMH + QAS.subjectmeasures.vol_TIV = sum(QAS.subjectmeasures.vol_abs_CGW); + QAS.subjectmeasures.vol_rel_CGW = QAS.subjectmeasures.vol_abs_CGW ./ QAS.subjectmeasures.vol_TIV; + + % resolution + QAS.qualitymeasures.res_vx_vol = vx_vol; + if 1 % CAT internal resolution + QAS.qualitymeasures.res_vx_voli = vx_voli; + end + QAS.qualitymeasures.res_RMS = mean(vx_vol.^2).^0.5; + % futher unused measure (just for test/comparison) + %QAS.qualitymeasures.res_isotropy = max(vx_vol)./min(vx_vol); + %QAS.qualitymeasures.res_vol = prod(abs(vx_vol)); + %QAS.qualitymeasures.res_MVR = mean(vx_vol); + + % boundary box - brain tissue next to image boundary + bbth = round(2/mean(vx_vol)); M = true(size(Yp0)); + M(bbth:end-bbth,bbth:end-bbth,bbth:end-bbth) = 0; + QAS.qualitymeasures.res_BB = sum(Yp0(:)>1.25 & M(:))*prod(abs(vx_vol)); + + % check segmentation + spec = species; for ai=num2str(0:9); spec = strrep(spec,ai,''); end; + bvol = species; for ai=char(65:122); bvol = strrep(bvol,ai,''); end; bvol = str2double(bvol); + + subvol = [sum(Yp0(:)>2.5 & Yp0(:)<3.1)*prod(vx_vol)/1000,... + sum(Yp0(:)>1.5 & Yp0(:)<2.5)*prod(vx_vol)/1000,... + sum(Yp0(:)>0.5 & Yp0(:)<1.5)*prod(vx_vol)/1000]; + + if isempty(bvol) + switch spec + case 'human' + bvol = 1400; + otherwise + warning('cat_vol_qa201602:species',... + sprintf('Unknown species %s (C=%0.0f,G=%0.0f,W=%0.0f).',species,subvol)); %#ok + end + end + if sum(subvol)bvol*3 + warning('cat_vol_qa201602:badSegmentation',... + sprintf('Bad %s segmentation (C=%0.0f,G=%0.0f,W=%0.0f).',species,subvol)) %#ok + end + + + %% estimate QA + % --------------------------------------------------------------- + % remove space arount the brain for speed-up + [Yo,Ym,Yp0] = cat_vol_resize({Yo,Ym,Yp0},'reduceBrain',vx_vol,4,Yp0>1.5); + + % rought contast and noise estimation to get a stable T1 map for threshold estimation + T1th = [median(Ym(Yp0toC(Yp0(:),1)>0.9)) ... + median(Ym(Yp0toC(Yp0(:),2)>0.9)) ... + median(Ym(Yp0toC(Yp0(:),3)>0.9))]; + noise = max(0,min(1,std(Ym(Yp0(:)>2.9)) / min(abs(diff(T1th))))); + Yms = Ym+0; spm_smooth(Yms,Yms,repmat(double(noise)*4,1,3)); % smoothing to reduce high frequency noise + + % basic tissue classes - erosion to avoid PVE, std to avoid other tissues (like WMHs) + voli = @(v) (v ./ (pi * 4./3)).^(1/3); + rad = voli( QAS.subjectmeasures.vol_TIV) ./ mean(vx_vol); + Ysc = 1-cat_vol_smooth3X(Yp0<1 | Yo==0,min(24,max(16,rad*2))); % fast 'distance' map + Ycm = cat_vol_morph(Yp0>0.5 & Yp0<1.5 & Yms0.75 & Yp0<1.25;% avoid PVE & ventricle focus + if sum(Ycm(:)>0)<10; Ycm=cat_vol_morph(Yp0>0.5 & Yp0<1.5 & Yms0)<10; Ycm=Yp0>0.5 & Yms0.7 & Yms1.1,'e') & cat_vol_morph(Yp0<2.9,'e'); % avoid PVE 2 + Ygm = (Ygm1 | Ygm2) & Ysc<0.9; % avoid PVE & no subcortex + Ywm = cat_vol_morph(Yp0>2.1,'e') & Yp0>2.9 & ... % avoid PVE & subcortex + Yms>min(mean(T1th(2:3)),(T1th(2) + 2*noise*diff(T1th(2:3)))); % avoid WMHs2 + clear Ygm1 Ygm2; % Ysc; + + %% further refinements of the tissue maps + T2th = [median(Yms(Ycm)) median(Yms(Ygm)) median(Yms(Ywm))]; + Ycm = Ycm & Yms>(T2th(1)-16*noise*diff(T2th(1:2))) & Ysc &... + Yms<(T2th(1)+0.1*noise*diff(T2th(1:2))); + if sum(Ycm(:)>0)<10; Ycm=cat_vol_morph(Yp0>0.5 & Yp0<1.5 & Yms0)<10; Ycm=Yp0>0.5 & Yms(T2th(2)-2*noise*diff(T1th(2:3))) & Yms<(T2th(2)+2*noise*diff(T1th(2:3))); + Ygm(smooth3(Ygm)<0.2) = 0; + Ycm = cat_vol_morph(Ycm,'lc'); % to avoid wholes + Ywm = cat_vol_morph(Ywm,'lc'); % to avoid wholes + Ywe = cat_vol_morph(Ywm,'e'); + + + %% low resolution tissue intensity maps (smoothing) + % High frequency noise is mostly uncritical as far as simple smoothing can reduce it. + % Although the very low frequency interferences (inhomogeneity) is unproblematic in most cases, + % but will influence the noise pattern. + % But most important is the noise with the medium high frequencies, that we try do detect by + % reducing the very high and low noise pattern by filtering and pixel smoothing by reduction. + res = 2; vx_volx = 1; + Yos = cat_vol_localstat(Yo,Ywm,1,1); Yo(Yos>0)=Yos(Yos>0); % reduce high frequency noise in WM + Yos = cat_vol_localstat(Yo,Ycm,1,1); Yo(Yos>0)=Yos(Yos>0); % reduce high frequency noise in CSF + + Yc = cat_vol_resize(Yo .* Ycm,'reduceV',vx_volx,res,32,'min'); % CSF thr. (minimum to avoid PVE) + Yg = cat_vol_resize(Yo .* Ygm,'reduceV',vx_volx,res,32,'meanm'); % GM thr. + Yw = cat_vol_resize(Yo .* Ywe,'reduceV',vx_volx,res,32,'meanm'); % WM thr. and bias correction (Ywme) + Ywc = cat_vol_resize(Ym .* Ywe,'reduceV',vx_volx,res,32,'meanm'); % for bias correction + Ywb = cat_vol_resize(Yo .* Ywm,'reduceV',vx_volx,res,32,'max'); % for WM inhomogeneity estimation (avoid PVE) + Ywn = cat_vol_resize(Yo .* Ywm,'reduceV',vx_volx,res,32,'meanm'); % for WM noise + Ycn = cat_vol_resize(Yo .* Ycm,'reduceV',vx_volx,res,32,'meanm'); % for CSF noise + Ycm = cat_vol_resize(Ycm ,'reduceV',vx_volx,res,32,'meanm'); % CSF thr. (minimum to avoid PVE) + Ygm = cat_vol_resize(Ygm ,'reduceV',vx_volx,res,32,'meanm'); % GM thr. + Ywm = cat_vol_resize(Ywm ,'reduceV',vx_volx,res,32,'meanm'); % WM thr. and bias correction (Ywme) + Ywe = cat_vol_resize(Ywe ,'reduceV',vx_volx,res,32,'meanm'); % WM thr. and bias correction (Ywme) + + % only voxel that were the product of + Yc = Yc .* (Ycm>=0.5); Yg = Yg .* (Ygm>=0.5); Yw = Yw .* (Ywe>=0.5); + Ywc = Ywc .* (Ywe>=0.5); Ywb = Ywb .* (Ywm>=0.5); Ywn = Ywn .* (Ywm>=0.5); + Ycn = Ycn .* (Ycm>=0.5); + + clear Ycm Ygm Ywm Ywme; + [Yo,Ym,Yp0,resr] = cat_vol_resize({Yo,Ym,Yp0},'reduceV',vx_volx,res,32,'meanm'); + resr.vx_volo = vx_vol; vx_vol=resr.vx_red .* resr.vx_volo; + + % intensity scaling for normalized Ym maps like in CAT12 + Ywc = Ywc .* (mean(Yo(Yp0(:)>2))/mean(Ym(Yp0(:)>2))); + + %% bias correction for original map, based on the + WI = Yw./max(eps,Ywc); WI(isnan(WI) | isinf(WI)) = 0; + WI = cat_vol_approx(WI,'nn',vx_vol,2); + WI = cat_vol_smooth3X(WI,1); + Ywn = Ywn./WI; Ywn = round(Ywn*1000)/1000; + Ymi = Yo ./WI; Ymi = round(Ymi*1000)/1000; + Yc = Yc ./WI; Yc = round(Yc *1000)/1000; + Yg = Yg ./WI; Yg = round(Yg *1000)/1000; + Yw = Yw ./WI; Yw = round(Yw *1000)/1000; + clear WIs ; + + Ywb = Ywb ./ mean(Ywb(Yp0(:)>2)); + + % tissue segments for contrast estimation etc. + CSFth = mean(Yc(~isnan(Yc(:)) & Yc(:)~=0)); + GMth = mean(Yg(~isnan(Yg(:)) & Yg(:)~=0)); + WMth = mean(Yw(~isnan(Yw(:)) & Yw(:)~=0)); + T3th = [CSFth GMth WMth]; + + % estimate background + [Ymir,resYbg] = cat_vol_resize(Ymi,'reduceV',1,6,32,'meanm'); + warning 'off' 'MATLAB:cat_vol_morph:NoObject' + BGCth = min(T3th)/2; + Ybgr = cat_vol_morph(cat_vol_morph(Ymir0.5; clear Yosr Ybgr; + if sum(Ybg(:))<32, Ybg = cat_vol_morph(YoGMth + QAS.qualitymeasures.tissue_weighting = 'T1'; + elseif WMth0.5 & ~isinf(Yp0(:)))); + end + QAS.qualitymeasures.tissue_stdr = QAS.qualitymeasures.tissue_std ./ (WMth-BGth); + + % (relative) (mininum) tissue contrast ( CSF-GM-WM ) + % - the CSF threshold varies strongly due to bad segmentations, + % and anatomica variance, so its better to use GM-WM contrast + % and take care of overoptimisation with values strongly >1/3 + % of the relative contrast + contrast = min(abs(diff(QAS.qualitymeasures.tissue_mn(3:4)))) ./ (max([WMth,GMth])); % default contrast + contrast = contrast + min(0,13/36 - contrast)*1.2; % avoid overoptimsization + %QAS.qualitymeasures.contrast = contrast * (max([WMth,GMth])); + QAS.qualitymeasures.contrastr = contrast; + + + + %% noise estimation (original (bias corrected) image) + % WM variance only in one direction to avoid WMHs! + rms=1; nb=1; + NCww = sum(Ywn(:)>0) * prod(vx_vol); + NCwc = sum(Ycn(:)>0) * prod(vx_vol); + [Yos2,YM2] = cat_vol_resize({Ywn,Ywn>0},'reduceV',vx_vol,3,16,'meanm'); + NCRw = estimateNoiseLevel(Yos2,YM2>0.5,nb,rms) / max(GMth,WMth) / contrast ; + if BGth<-0.1 && WMth<3, NCRw=NCRw/3; end% MT weighting + clear Yos0 Yos1 Yos2 YM0 YM1 YM2; + + % CSF variance of large ventricle + % for typical T2 images we have to much signal in the CSF and can't use it for noise estimation! + wcth = 200; + if CSFthwcth + [Yos2,YM2] = cat_vol_resize({Ycn,Ycn>0},'reduceV',vx_vol,3,16,'meanm'); + NCRc = estimateNoiseLevel(Yos2,YM2>0.5,nb,rms) / max(GMth,WMth) / contrast ; + clear Yos0 Yos1 Yos2 YM0 YM1 YM2; + else + NCRc = 0; + NCwc = 0; + end + % 1/sqrt(volume) to compensate for noise differency due to different volumen size. + % Overall there are better chances to correct high resolution noise. + % Nitz W R. Praxiskurs MRT. Page 28. + NCwc = min(wcth,max(0,NCwc-wcth)); NCww = min(wcth,NCww) - NCwc; % use CSF if possible + if NCwc<3*wcth && NCww<10*wcth, NCRc = min(NCRc,NCRw); end + QAS.qualitymeasures.NCR = (NCRw*NCww + NCRc*NCwc)/(NCww+NCwc); + QAS.qualitymeasures.NCR = QAS.qualitymeasures.NCR * (prod(resr.vx_volo*res))^0.4 * 5/4; %* 7.5; %15; + %QAS.qualitymeasures.CNR = 1 / QAS.qualitymeasures.NCR; +%fprintf('NCRw: %8.3f, NCRc: %8.3f, NCRf: %8.3f\n',NCRw,NCRc,(NCRw*NCww + NCRc*NCwc)/(NCww+NCwc)); + + + %% Bias/Inhomogeneity (original image with smoothed WM segment) + Yosm = cat_vol_resize(Ywb,'reduceV',vx_vol,3,32,'meanm'); % resolution and noise reduction + for si=1:max(1,min(3,round(QAS.qualitymeasures.NCR*4))), Yosm = cat_vol_localstat(Yosm,Yosm>0,1,1); end + QAS.qualitymeasures.ICR = cat_stat_nanstd(Yosm(Yosm(:)>0)) / contrast; + %QAS.qualitymeasures.CIR = 1 / QAS.qualitymeasures.ICR; + + + + %% marks + QAM = cat_stat_marks('eval',1,QAS); + + % export + if opt.write_xml + QAS.qualityratings = QAM.qualityratings; + % QAS.subjectratings = QAM.subjectmeasures; + + cat_io_xml(fullfile(pp0,[opt.prefix ff '.xml']),QAS,'write'); + end + + clear Yi Ym Yo Yos Ybc + clear Ywm Ygm Ycsf Ybg + + end + + if nargout>2, varargout{3} = cat_qa_warnings; end + if nargout>1, varargout{2} = QAM; end + if nargout>0, varargout{1} = QAS; end + +end +%======================================================================= +function def=defaults + % default parameter + def.verb = 2; % verbose level [ 0=nothing | 1=points | 2*=results ] + def.write_csv = 2; % final cms-file [ 0=dont write |1=write | 2=overwrite ] + def.write_xml = 1; % images base xml-file + def.sortQATm = 1; % sort QATm output + def.orgval = 0; % original QAM results (no marks) + def.avgfactor = 2; % + def.prefix = 'cat_'; % intensity scaled image + def.mprefix = 'm'; % prefix of the preprocessed image + def.process = 3; % used image [ 0=T1 | 1=mT1 | 2=avg | 3=both ] + def.calc_MPC = 0; + def.calc_STC = 0; + def.calc_MJD = 0; + def.method = 'spm'; + def.snspace = [70,7,3]; + def.nogui = exist('XT','var'); + def.output.te = struct('native',cat_get_defaults('output.te.native'), ... + 'warped',cat_get_defaults('output.te.warped'), ... + 'dartel',cat_get_defaults('output.te.dartel')); + def.output.pc = struct('native',cat_get_defaults('output.pc.native'), ... + 'warped',cat_get_defaults('output.pc.warped'), ... + 'dartel',cat_get_defaults('output.pc.dartel')); + def.MarkColor = cat_io_colormaps('marks+',40); +end + +function noise = estimateNoiseLevel(Ym,YM,r,rms,vx_vol) +% ---------------------------------------------------------------------- +% noise estimation within Ym and YM. +% ---------------------------------------------------------------------- + if ~exist('vx_vol','var'); + vx_vol=[1 1 1]; + end + if ~exist('r','var'); + r = 1; + else + r = min(10,max(max(vx_vol),r)); + end + if ~exist('rms','var') + rms = 1; + end + + Ysd = cat_vol_localstat(single(Ym),YM,r,4); + noise = cat_stat_nanstat1d(Ysd(YM).^rms,'median').^(1/rms); +end +%=======================================================================","MATLAB" +"Neurology","ChristianGaser/cat12","Pve.c",".c","5870","174","/* ______________________________________________________________________ + * + * Christian Gaser, Robert Dahnke + * Structural Brain Mapping Group (https://neuro-jena.github.io) + * Departments of Neurology and Psychiatry + * Jena University Hospital + * ______________________________________________________________________ + * $Id$ + * + */ + +/* This PVE calculation is a modified version from the PVE software bundle: + * Copyright (C) Jussi Tohka, Institute of Signal Processing, + * Tampere University of Technology, 2002 - 2004. + * P.O. Box 553, FIN-33101, Finland + * E-mail: jussi.tohka@tut.fi + */ + +#include +#include +#include +#include ""Amap.h"" + +void Pve5(double *src, unsigned char *prob, unsigned char *label, double *mean, int *dims) +{ + int z_area, y_dims, ind; + double w; + unsigned char new_val[MAX_NC]; + + int area = dims[0]*dims[1]; + int vol = area*dims[2]; + + for (int z = 1; z < dims[2]-1; z++) { + z_area = z*area; + for (int y = 1; y < dims[1]-1; y++) { + y_dims = y*dims[0]; + for (int x = 1; x < dims[0]-1; x++) { + ind = z_area + y_dims + x; + + switch(label[ind]) { + case 0: /* BG */ + new_val[CSFLABEL-1] = 0; + new_val[GMLABEL-1] = 0; + new_val[WMLABEL-1] = 0; + break; + case CSFLABEL: /* CSF */ + new_val[CSFLABEL-1] = 255; + new_val[GMLABEL-1] = 0; + new_val[WMLABEL-1] = 0; + label[ind] = (unsigned char) ROUND(1.0*255.0/3.0); + break; + case GMLABEL: /* GM */ + new_val[CSFLABEL-1] = 0; + new_val[GMLABEL-1] = 255; + new_val[WMLABEL-1] = 0; + label[ind] = (unsigned char) ROUND(2.0*255.0/3.0); + break; + case WMLABEL: /* WM */ + new_val[CSFLABEL-1] = 0; + new_val[GMLABEL-1] = 0; + new_val[WMLABEL-1] = 255; + label[ind] = 255; + break; + case GMCSFLABEL: /* GMCSF */ + w = (src[ind] - mean[CSFLABEL-1]) / ( mean[GMLABEL-1] - mean[CSFLABEL-1] ); + if(w > 1.0) w = 1.0; if(w < 0.0) w = 0.0; + new_val[CSFLABEL-1] = (unsigned char) ROUND(255.0*(1-w)); + new_val[GMLABEL-1] = (unsigned char) ROUND(255.0*w); + new_val[WMLABEL-1] = 0; + label[ind] = (unsigned char) ROUND(255.0/3.0*(1.0 + w)); + break; + case WMGMLABEL: /* WMGM */ + w = (src[ind] - mean[GMLABEL-1])/(mean[WMLABEL-1]-mean[GMLABEL-1]); + if(w > 1.0) w = 1.0; if(w < 0.0) w = 0.0; + new_val[CSFLABEL-1] = 0; + new_val[GMLABEL-1] = (unsigned char) ROUND(255.0*(1-w)); + new_val[WMLABEL-1] = (unsigned char) ROUND(255.0*w); + label[ind] = (unsigned char) ROUND(255.0/3.0*(2.0 + w)); + break; + } + + prob[ ind] = new_val[CSFLABEL-1]; + prob[vol + ind] = new_val[GMLABEL-1]; + prob[(2*vol) + ind] = new_val[WMLABEL-1]; + + /* set old probabilities for mixed classes to zero */ + prob[(3*vol) + ind] = 0; + prob[(4*vol) + ind] = 0; + + } + } + } +} + +void Pve6(double *src, unsigned char *prob, unsigned char *label, double *mean, int *dims) +{ + int z_area,y_dims,ind; + double w; + unsigned char new_val[MAX_NC]; + + int area = dims[0]*dims[1]; + int vol = area*dims[2]; + + for (int z = 1; z < dims[2]-1; z++) { + z_area = z*area; + for (int y = 1; y < dims[1]-1; y++) { + y_dims = y*dims[0]; + for (int x = 1; x < dims[0]-1; x++) { + ind = z_area + y_dims + x; + + switch(label[ind]) { + case 0: /* BG */ + new_val[CSFLABEL] = 0; + new_val[GMLABEL] = 0; + new_val[WMLABEL] = 0; + break; + case CSFLABEL+1: /* CSF */ + new_val[CSFLABEL] = 255; + new_val[GMLABEL] = 0; + new_val[WMLABEL] = 0; + label[ind] = (unsigned char) ROUND(1.0*255.0/3.0); + break; + case GMLABEL+1: /* GM */ + new_val[CSFLABEL] = 0; + new_val[GMLABEL] = 255; + new_val[WMLABEL] = 0; + label[ind] = (unsigned char) ROUND(2.0*255.0/3.0); + break; + case WMLABEL+1: /* WM */ + new_val[CSFLABEL] = 0; + new_val[GMLABEL] = 0; + new_val[WMLABEL] = 255; + label[ind] = 255; + break; + case BKGCSFLABEL+1: /* BKGCSF */ + w = src[ind]/mean[CSFLABEL]; + if(w > 1.0) w = 1.0; if(w < 0.0) w = 0.0; + new_val[CSFLABEL] = (unsigned char) ROUND(255.0*w); + new_val[GMLABEL] = 0; + new_val[WMLABEL] = 0; + label[ind] = ROUND(255.0/3.0*w); + break; + case GMCSFLABEL+1: /* GMCSF */ + w = (src[ind] - mean[CSFLABEL])/(mean[GMLABEL]-mean[CSFLABEL]); + if(w > 1.0) w = 1.0; if(w < 0.0) w = 0.0; + new_val[CSFLABEL] = (unsigned char) ROUND(255.0*(1-w)); + new_val[GMLABEL] = (unsigned char) ROUND(255.0*w); + new_val[WMLABEL] = 0; + label[ind] = (unsigned char) ROUND(255.0/3.0*(1.0 + w)); + break; + case WMGMLABEL+1: /* WMGM */ + w = (src[ind] - mean[GMLABEL])/(mean[WMLABEL]-mean[GMLABEL]); + if(w > 1.0) w = 1.0; if(w < 0.0) w = 0.0; + new_val[CSFLABEL] = 0; + new_val[GMLABEL] = (unsigned char) ROUND(255.0*(1-w)); + new_val[WMLABEL] = (unsigned char) ROUND(255.0*w); + label[ind] = (unsigned char) ROUND(255.0/3.0*(2.0 + w)); + break; + } + + prob[ ind] = new_val[CSFLABEL]; + prob[vol + ind] = new_val[GMLABEL]; + prob[(2*vol) + ind] = new_val[WMLABEL]; + + /* set old probabilities for mixed classes to zero */ + prob[(3*vol) + ind] = 0; + prob[(4*vol) + ind] = 0; + prob[(5*vol) + ind] = 0; + + } + } + } +} +","C" +"Neurology","ChristianGaser/cat12","cat_conf_ROI.m",".m","19907","449","function [ROI,sROI,ROIsum] = cat_conf_ROI(expert) +%_______________________________________________________________________ +% wrapper for calling CAT ROI options +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + +if nargin == 0 + try + expert = cat_get_defaults('extopts.expertgui'); + catch %#ok + expert = 0; + end +end + +noROI = cfg_branch; +noROI.tag = 'noROI'; +noROI.name = 'No ROI processing'; +noROI.help = {'No ROI processing'}; + +exatlas = cat_get_defaults('extopts.atlas'); +matlas = {}; mai = 1; atlaslist = {}; +for ai = 1:size(exatlas,1) + if exatlas{ai,2}<=expert && exist(exatlas{ai,1},'file') + [pp,ff] = spm_fileparts(exatlas{ai,1}); + + % if output.atlases.ff does not exist then set it by the default file value + if isempty(cat_get_defaults(['output.atlases.' ff])) + cat_get_defaults(['output.atlases.' ff], exatlas{ai,4}) + end + atlaslist{end+1,1} = ff; + + license = {'' ' (no commercial use)' ' (free academic use)'}; + if size(exatlas,2)>4 + lic = exatlas{ai,5}; + else + switch ff + case 'hammers', lic = 2; + case 'lpba40' , lic = 1; + case 'suit', lic = 1; + otherwise, lic = 0; + end + end + + matlas{mai} = cfg_menu; + matlas{mai}.tag = ff; + matlas{mai}.name = [ff license{lic+1}]; + matlas{mai}.labels = {'No','Yes'}; + matlas{mai}.values = {0 1}; + matlas{mai}.def = eval(sprintf('@(val) cat_get_defaults(''output.atlases.%s'', val{:});',ff)); + txtfile = fullfile(pp,[ff '.txt']); + if exist(txtfile,'file') + fid = fopen(txtfile,'r'); + txt = textscan(fid,'%s','delimiter','\n'); + fclose(fid); + matlas{mai}.help = [{ + 'Processing flag of this atlas map.' + '' + } + txt{1}]; + else + matlas{mai}.help = { + 'Processing flag of this atlas map.' + '' + ['No atlas readme text file ""' txtfile '""!'] + }; + end + mai = mai+1; + else + [pp,ff] = spm_fileparts(exatlas{ai,1}); + + if ~isempty(cat_get_defaults(['output.atlases.' ff])) + cat_get_defaults(['output.atlases.' ff],'rmfield'); + end + end +end + +ownatlas = cfg_files; +ownatlas.tag = 'ownatlas'; +ownatlas.name = 'own atlas maps'; +ownatlas.help = { + sprintf([ + 'Select images that should be used as atlas maps. ' ... + 'The maps should only contain positive integers for regions of interest. ' ... + 'You can use a CSV-file with the same name as the atlas to define region ' ... + 'names similar to the CSV-files of other atlas files in ""%s"". ' ... + 'The CSV-file should have an header line containing the number of the ROI ""ROIid"", ' ... + 'the abbreviation of the ROI ""ROIabbr"" (using leading l/r/b to indicate the hemisphere) ' ... + 'and the full name of the ROI ""ROIname"". ' ... + 'The GM, WM, and CSF values will be extracted for all regions. '], ... + cat_get_defaults('extopts.pth_templates') ); + ''}; +ownatlas.filter = 'image'; +ownatlas.ufilter = '.*'; +ownatlas.val{1} = {''}; +ownatlas.dir = cat_get_defaults('extopts.pth_templates'); +ownatlas.num = [0 Inf]; + +atlases = cfg_branch; +atlases.tag = 'atlases'; +atlases.name = 'Atlases'; +atlases.val = [matlas,{ownatlas}]; +atlases.help = {'Writing options of ROI atlas maps.' +'' +}; + + +ROI = cfg_choice; +ROI.tag = 'ROImenu'; +ROI.name = 'Process Volume ROIs'; +if cat_get_defaults('output.ROI')>0 + ROI.val = {atlases}; +else + ROI.val = {noROI}; +end +ROI.values = {noROI atlases}; +if expert > 1 + commentthicknessROI = { + '' + 'Developer: For fast volume-based thickness estimation without surfaces, the projection-based thickness (PBT) [Dahnke:2012] only estimates the thickness values that were than average per ROI. ' + '' }; +else + commentthicknessROI = {''}; +end +ROI.help = [{ + 'Export of ROI data of volume to a xml-files. For further information see atlas specific text files in' + [' ""' cat_get_defaults('extopts.pth_templates') '"" CAT12 subdir. '] } + commentthicknessROI + {'There are different atlas maps available: '} + ]; + +%% +mai = 1; +for ali=1:numel(atlaslist) + if any(~cellfun('isempty',strfind(atlaslist(ali),'hammers'))) + ROI.help = [ROI.help; strrep({ + '(MAI) Hammers (68 CSF/GM/[WM] ROIs of 20 subjects, 2003):' + ' Alexander Hammers brain atlas from the Euripides project (www.brain-development.org).' + ' Hammers et al. Three-dimensional maximum probability atlas of the human brain, with particular reference to the temporal lobe. Hum Brain Mapp 2003, 19: 224-247.' + ''},'MAI',num2str(mai,'%d'))]; mai = mai+1; + end + if any(~cellfun('isempty',strfind(atlaslist(ali),'neuromorphometrics'))) + ROI.help = [ROI.help; strrep({ + '(MAI) Neuromorphometrics (142 GM ROIs of 15 subjects, 2012):' + ' Maximum probability tissue labels derived from the MICCAI 2012 Grand Challenge and Workshop on Multi-Atlas Labeling' + ' https://masi.vuse.vanderbilt.edu/workshop2012/index.php/Challenge_Details' + ''},'MAI',num2str(mai,'%d'))]; mai = mai+1; + end + if any(~cellfun('isempty',strfind(atlaslist(ali),'lpba40'))) + ROI.help = [ROI.help; strrep({ + '(MAI) LPBA40 (56 GM ROIs of 40 subjects, 2008):' + ' The LONI Probabilistic Brain Atlas (LPBA40) is a series of maps of brain anatomical regions. These maps were estimated from a set of whole-head MRI of 40 human volunteers. Each MRI was manually delineated to identify a set of 56 structures in the brain, most of which are within the cortex. These delineations were then transformed into a common atlas space to obtian a set of coregistered anatomical labels. The original MRI data were also transformed into the atlas space. ' + ' Shattuck et al. 2008. Construction of a 3D Probabilistic Atlas of Human Cortical Structures, NeuroImage 39 (3): 1064-1070. DOI: 10.1016/j.neuroimage.2007.09.031' + ''},'MAI',num2str(mai,'%d'))]; mai = mai+1; + end + if any(~cellfun('isempty',strfind(atlaslist(ali),'cobra'))) + ROI.help = [ROI.help; strrep({ + '(MAI) COBRA (1 GM/WM ROI in amgdala, 2 combined GM/WM ROIs in hippocampus and 13 GM/WM ROIs in cerebellum of 5 subjects):' + ' The Cobra atlas is build from 3 atlases that are provided by the Computational Brain Anatomy Laboratory at the Douglas Institute (CoBra Lab). The 3 atlases are based on high-resolution (0.3mm isotropic voxel size) images of the amygdala, hippocampus and the cerebellum. Some of the hippocampus subfields were merged because of their small size (CA1/CA2/CA3/stratum radiatum/subiculum/stratum lacunosum/stratum moleculare). Please note that the original labels were changed in order to allow a combined atlas. ' + ' Entis JJ, Doerga P, Barrett LF, Dickerson BC. A reliable protocol for the manual segmentation of the human amygdala and its subregions using ultra-high resolution MRI. Neuroimage. 2012;60(2):1226-35.' + ' Winterburn JL, Pruessner JC, Chavez S, et al. A novel in vivo atlas of human hippocampal subfields using high-resolution 3 T magnetic resonance imaging. Neuroimage. 2013;74:254-65.' + ' Park, M.T., Pipitone, J., Baer, L., Winterburn, J.L., Shah, Y., Chavez, S., Schira, M.M., Lobaugh, N.J., Lerch, J.P., Voineskos, A.N., Chakravarty, M.M. Derivation of high-resolution MRI atlases of the human cerebellum at 3T and segmentation using multiple automatically generated templates. Neuroimage. 2014; 95: 217-31.' + ''},'MAI',num2str(mai,'%d'))]; mai = mai+1; + end + if any(~cellfun('isempty',strfind(atlaslist(ali),'ibsr'))) + ROI.help = [ROI.help; strrep({ + '(MAI) IBSR (32 CSF/GM ROIs of 18 subjects, 2004):' + ' See IBSR terms ""http://www.nitrc.org/projects/ibsr""' + ''},'MAI',num2str(mai,'%d'))]; mai = mai+1; + end + if any(~cellfun('isempty',strfind(atlaslist(ali),'aal3'))) + ROI.help = [ROI.help; strrep({ + '(MAI) AAL3 (170 GM ROIs of 1 subject, 2020):' + ' Tzourio-Mazoyer et al., Automated anatomical labelling of activations in spm using a macroscopic anatomical parcellation of the MNI MRI single subject brain. Neuroimage 2002, 15: 273-289.' + ' Rolls et al., Automated anatomical labelling atlas 3. Neuroimage 2020; 206:116189.' + ''},'MAI',num2str(mai,'%d'))]; mai = mai+1; + end + if any(~cellfun('isempty',strfind(atlaslist(ali),'mori'))) + ROI.help = [ROI.help; strrep({ + '(MAI) MORI (128 GM/WM ROIs of 1 subject, 2009):' + ' Oishi et al. Atlas-based whole brain white matter analysis using large deformation diffeomorphic metric mapping: application to normal elderly and Alzheimer''s disease participants. 2009' + ''},'MAI',num2str(mai,'%d'))]; mai = mai+1; + end + if any(~cellfun('isempty',strfind(atlaslist(ali),'anatomy3'))) + ROI.help = [ROI.help; strrep({ + '(MAI) Anatomy (93 GM/WM ROIs in 10 post-mortem subjects, 2014):' + ' Eickhoff SB, Stephan KE, Mohlberg H, Grefkes C, Fink GR, Amunts K, Zilles K. A new SPM toolbox for combining probabilistic cytoarchitectonic maps and functional imaging data. NeuroImage 25(4), 1325-1335, 2005' + ''},'MAI',num2str(mai,'%d'))]; mai = mai+1; + end + if any(~cellfun('isempty',strfind(atlaslist(ali),'julichbrain3'))) + ROI.help = [ROI.help; strrep({ + '(MAI) Whole-brain parcellation of the Julich-Brain Cytoarchitectonic Atlas (v3.1):' + ' Amunts K, Mohlberg H, Bludau S, Zilles K (2020). Julich-Brain – A 3D probabilistic atlas of human brains cytoarchitecture. Science 369, 988-99' + ''},'MAI',num2str(mai,'%d'))]; mai = mai+1; + end + if any(~cellfun('isempty',strfind(atlaslist(ali),'thalamus'))) + ROI.help = [ROI.help; strrep({ + '(MAI) Atlas of human thalamic nuclei (based on DTI from 70 subjects with 14 regions):' + ' Najdenovska E, Alemán-Gómez Y, Battistella G, Descoteaux M, Hagmann P, Jacquemont S, Maeder P, Thiran JP, Fornari E, Bach Cuadra M. In-vivo probabilistic atlas of human thalamic nuclei based on diffusion- weighted magnetic resonance imaging. Sci Data. 2018 Nov 27;5:180270.' + ''},'MAI',num2str(mai,'%d'))]; mai = mai+1; + end + if any(~cellfun('isempty',strfind(atlaslist(ali),'thalamic_nuclei'))) + ROI.help = [ROI.help; strrep({ + '(MAI) Atlas of human thalamic nuclei (based on hi-res T2 from 9 subjects with 22 regions):' + ' Saranathan M, Iglehart C, Monti M, Tourdias T, Rutt B. In vivo high-resolution structural MRI-based atlas of human thalamic nuclei. Sci Data. 2021 Oct 28;8(1):275.' + ''},'MAI',num2str(mai,'%d'))]; mai = mai+1; + end + if any(~cellfun('isempty',strfind(atlaslist(ali),'suit'))) + ROI.help = [ROI.help; strrep({ + '(MAI) SUIT Atlas of the human cerebellum:' + ' Diedrichsen J., Balster J.H., Flavell J., Cussans E., Ramnani N. (2009). A probabilistic MR atlas of the human cerebellum. Neuroimage; 46(1), 39-46.' + ''},'MAI',num2str(mai,'%d'))]; mai = mai+1; + end + if any(~cellfun('isempty',strfind(atlaslist(ali),'Schaefer2018_200Parcels_17Networks_order'))) + ROI.help = [ROI.help; strrep({ + '(MAI) Local-Global Intrinsic Functional Connectivity Parcellation by Schaefer et al.:' + 'These atlases are available for different numbers of parcellations (100, 200, 400, 600)' + 'and are based on resting state data from 1489 subjects.' + 'https://github.com/ThomasYeoLab/CBIG/tree/master/stable_projects/brain_parcellation/Schaefer2018_LocalGlobal' + ''},'MAI',num2str(mai,'%d'))]; mai = mai+1; + end +end + + + +%% ------------------------------------------------------------------------ +% Surface Atlases +% RD 20190416 +%------------------------------------------------------------------------ + +nosROI = cfg_branch; +nosROI.tag = 'noROI'; +nosROI.name = 'No surface ROI processing'; +nosROI.help = {'No surface ROI processing'}; + +exatlas = cat_get_defaults('extopts.satlas'); +matlas = {}; mai = 1; atlaslist = {}; +for ai = 1:size(exatlas,1) + if exatlas{ai,3}<=expert && ~isempty(exatlas{ai,2}) + [pp,ff] = spm_fileparts( exatlas{ai,2} ); + name = exatlas{ai,1}; + + % if output.atlases.ff does not exist then set it by the default file value + if isempty(cat_get_defaults(['output.satlases.' name])) + cat_get_defaults(['output.satlases.' name], exatlas{ai,4}) + end + atlaslist{end+1,1} = name; + + if cat_get_defaults('extopts.expertgui') + if strcmp(spm_str_manip(pp,'t'),'atlases_surfaces_32k') + addname = ' (32k)'; + elseif strcmp(spm_str_manip(pp,'t'),'atlases_surfaces') + addname = ' (164k)'; + else + addname = ''; + end + else + addname = ''; + end + + matlas{mai} = cfg_menu; + matlas{mai}.tag = name; + matlas{mai}.name = [name addname]; + matlas{mai}.labels = {'No','Yes'}; + matlas{mai}.values = {0 1}; + matlas{mai}.def = eval(sprintf('@(val) cat_get_defaults(''output.satlases.%s'', val{:});',name)); + + txtfile = fullfile(pp,[name '.txt']); + if exist(txtfile,'file') + fid = fopen(txtfile,'r'); + txt = textscan(fid,'%s','delimiter','\n'); + fclose(fid); + matlas{mai}.help = [{ + 'Processing flag of this atlas map.' + '' + } + txt{1}]; + else + matlas{mai}.help = { + 'Processing flag of this atlas map.' + '' + ['No atlas readme text file ""' txtfile '""!'] + }; + end + mai = mai+1; + else + name = exatlas{ai,1}; + + if ~isempty(cat_get_defaults(['output.satlases.' name])) + cat_get_defaults(['output.satlases.' name],'rmfield'); + end + end +end + +ownsatlas = ownatlas; +ownsatlas.filter = ''; +ownsatlas.ufilter = '.*'; +ownsatlas.help = { + 'Select FreeSurfer surface annotation files (*.annot), FreeSurfer CURV-files, or GIFTI surfaces with positve integer with 32k or 164k faces. '; + ''}; + +satlases = cfg_branch; +satlases.tag = 'satlases'; +satlases.name = 'Surface atlases'; +satlases.val = [matlas,{ownatlas}]; +satlases.help = {'Writing options for surface ROI atlas maps.' +'' +}; + + +sROI = cfg_choice; +sROI.tag = 'sROImenu'; +sROI.name = 'Process Surface ROIs'; +if cat_get_defaults('output.surface')>0 && cat_get_defaults('output.ROI')>0 + sROI.val = {satlases}; +else + sROI.val = {nosROI}; +end +sROI.values = {nosROI satlases}; +sROI.help = { +'Export of ROI data of volume to a xml-files. ' +['For further information see atlas specific text files in ""' cat_get_defaults('extopts.pth_templates') '"" CAT12 subdir. '] +'' +'For thickness estimation the projection-based thickness (PBT) [Dahnke:2012] is used that averages cortical thickness for each GM voxel. ' +'' +'There are different atlas maps available: ' +}; + +%------------------------------------------------------------- +% summarize in ROI +atlases.help = {'ROI atlas maps. In order to obtain more atlases you have to switch to expert mode.'}; + +field = cfg_files; +field.tag = 'field'; +field.name = 'Deformation Fields'; +field.filter = 'image'; +field.ufilter = '^y_.*\.nii$'; +field.num = [1 Inf]; +field.help = { + 'Select deformation fields for all subjects.' + 'Use the ""y_*.nii"" to project data from subject to template space, and the ""iy_*.nii"" to map data from template to individual space.' + 'Both deformation maps can be created in the CAT preprocessing by setting the ""Deformation Field"" flag to forward or inverse.' +}; + +field1 = cfg_files; +field1.tag = 'field1'; +field1.name = 'Deformation Field'; +field1.filter = 'image'; +field1.ufilter = '^y_.*\.nii$'; +field1.num = [1 1]; +field1.help = { + 'Select the deformation field of one subject.' + 'Use the ""y_*.nii"" to project data from subject to template space, and the ""iy_*.nii"" to map data from template to individual space.' + 'Both deformation maps can be created in the CAT preprocessing by setting the ""Deformation Field"" flag to forward or inverse.' +}; + +images1 = cfg_files; +images1.tag = 'images'; +images1.name = 'Images'; +images1.help = { + 'Select co-registered files for ROI estimation. It is important that this image is in the same space and co-registered to the T1-weighted image. Note that there should be the same number of images as there are ' + 'deformation fields, such that each flow field relates to one image. The images can be also given as 4D data (e.g. rsfMRI data).' +}; +images1.filter = 'image'; +images1.ufilter = '.*'; +images1.num = [1 Inf]; + +images = cfg_repeat; +images.tag = 'images'; +images.name = 'Images'; +images.help = {'ROI estimation can be done for multiple images of one subject. At this point, you are choosing how many images for each flow field exist.'}; +images.values = {images1 }; +images.num = [1 Inf]; + +cfun = cfg_entry; +cfun.tag = 'cfun'; +cfun.name = 'Customized function'; +cfun.strtype = 's'; +cfun.num = [0 Inf]; +cfun.val = {'@median'}; +cfun.help = { + 'Here, you can define your own function to summarize data as function handle. This also allows to use external functions.' + 'Examples: ' + 'Calculate median:' + '@median' + '' + 'Calculate absolute amplitude between 10-90% percentile:' + '@(x) abs(diff(spm_percentile(x,[10 90])))' + '' + 'Get mean inbetween 10-90% percentile' + '@(x) mean(x>spm_percentile(x,10) & x0: only bigger changes +% Bi_low (double) .. low threshold in D for filtering (add to Bi) +% Bi_high (double) .. high threshold in D for filtering (add to Bi) +% Bn_low (double) .. low threshold in D for neighbors (add to Bn) +% Bn_high (double) .. high threshold in D for neighbors (add to Bn) +% filterNaNandINF (double ) .. replace NaN or Inf by the median of non +% NaN/INF voxels (default=0) +% +% Used slower quicksort for median calculation, because the faster median +% of the median estimation leaded to incorrect results. +% +% Example: +% A is the image that should be filter and that may contain NaN and Inf +% values, whereas B defines the regions that should be filtered and spend +% values. +% +% A = randn(50,50,3,'single'); +% B = false(size(A)); B(5:end-4,5:end-4,:)=true; +% N = rand(size(A),'single'); +% A(N>0.9 & N<1.0) = NaN; A(N<0.1 & N>0) = -inf; A(N<0.05 & N>0) = inf; +% +% 1) simple cases without limits +% C = cat_vol_median3(A,B); ds('d2smns','',1,A+B,C,2); +% +% 2) simple case without limits bud with NaN that are replaced by default +% C = cat_vol_median3(A,B,B,0,-inf,inf,-inf,inf,1); ds('d2smns','',1,A+B,C,2); +% +% 3) Replace only small changes in C1, eg. to filter within tissue classes. +% Replace only large outlier in C2, eg. to remove outlier like salt & +% pepper noise. In both cases NANs/INFs were replaced. +% C1 = cat_vol_median3(A,B,B, -1.0 ,-inf,inf,-inf,inf,1 ); +% C2 = cat_vol_median3(A,B,B, 1.0 ,-inf,inf,-inf,inf,1 ); +% ds('d2smns','',1,C1,C2,2); +% +% See also cat_vol_median3c, compile. +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ +","MATLAB" +"Neurology","ChristianGaser/cat12","sliderPanel.m",".m","17375","482","function [sliderHandle,panelHandle,editHandle] = sliderPanel(parent,PanelPVs,SliderPVs,EditPVs,LabelPVs,numFormat,varargin) +% [sliderHandle,panelHandle,editHandle] = sliderPanel(parent,PanelPVs,SliderPVs,EditPVs,LabelPVs,numFormat) +% +% Creates a slider in a separate uipanel, with an associated +% interactive EditBox, and left and right labels showing the +% minimum and maximum values of the slider, respectively. +% Moving the slider automatically updates the textbox, and vice +% versa. Both slider movement and text edits will trigger +% (non-recursively) the callback of the slider. +% +% The EditBox automatically disallows the entry of +% non-numeric values, or of values outside of [min,max]. +% Attempts to enter disallowed values will be ignored. +% +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% SYNTAXES: +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% +% 1) The main syntax for sliderPanel allows full control of +% all elements of the uitool. (See INPUT ARGUMENTS below for +% details). +% +% [sliderHandle,panelHandle,editHandle] = +% sliderPanel(parent,PanelPVs,SliderPVs,EditPVs,LabelPVs,numFormat); +% +% 2)The following syntax captures a small subset of the +% sliderPanel functionality; +% +% hFig = gcf; +% sliderPanel(... +% 'Parent' , hFig, ... +% 'Title' , 'Slider Panel', ... +% 'Position', [0.3 0.5 0.4 0.2], ... +% 'Backgroundcolor', 'r',... +% 'Min' , 0, ... +% 'Max' , 100, ... +% 'Value' , 50, ... +% 'FontName', 'Verdana', ... +% 'Callback', @myCallback); +% +% Note: This simplified syntax supports a small subset of +% the available PV pairs that can be controlled via the +% primary syntax. Supported parameters, and the object to +% which they assigned, are shown below: +% +% Parameter Object(s) affected +%____________________________________ +% Parent uipanel +% Title uipanel +% Position uipanel +% Backgroundcolor uipanel +% Bordertype uipanel +% Tag uipanel +% Fontname uipanel, edit box, labels +% Fontweight uipanel, edit box, labels +% Fontsize uipanel, edit box, labels +% Min slider +% Max slider +% Value slider +% Sliderstep slider +% Callback slider (and, by extension, edit box) +% Units uipanel, slider, edit box, labels +% Visible uipanel (as a parent) +% Numberformat edit box +% +% (The code is easily modifiable to add new PV support.) +% +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% INPUT ARGUMENTS (ALL OPTIONAL): +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% PARENT: the handle of the parent object for the +% uipanel. Default is the current figure. +% +% PANELPVS: a cell array of any parameter-value pairs +% valid for the uipanel object, or a structure +% of same. (Defaults are those used by +% UIPANEL.) +% +% SLIDERPVS: a cell array of any parameter-value pairs +% valid for the slider object, or a structure +% of same. (Defaults are those used by +% UICONTROL('STYLE','SLIDER').) +% +% EDITPVS: a cell array of any parameter-value pairs +% valid for the UICONTROL EDIT object, or a +% structure of same. (Defaults are those used +% by UICONTROL('STYLE','EDIT').) +% +% LABELPVS: a cell array of any parameter-value pairs +% valid for the UICONTROL TEXT objects used to +% label the slider, or a structure of same. +% (Defaults are those used by +% UICONTROL('STYLE','TEXT').) +% NOTE: The following are valid syntaxes for LABELPVS: +% 1) Applied to both (l/r) labels: +% {param1, val1, param2, val2,...} +% 2) First array applied to left label, second +% array applied to right label: +% {{P-V array},{P-V array}} +% 3) First array applied to left label, second +% array applied to right label, third array +% applied to both (l/r) labels: +% {{P-V array},{P-V array},{P-V array}} +% +% NUMFORMAT: a format string accepted by SPRINTF, which +% controls the formatting of the EditBox when +% the slider is dragged. (Typing directly in +% the EditBox does not trigger the formatting +% constraint.) +% +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% OUTPUT ARGUMENTS: +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% SLDRHNDL: handles of slider object. +% +% PNLHNDL: handle of uipanel object. +% +% EDITHNDL: handle of edit box. +% +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% EXAMPLES: +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% 1) Create a single-slider sliderPanel using cell-array inputs. +% +% [sldr,pnl,edt] = ... +% sliderPanel(gcf,... +% {'title','Threshold','pos',[0.1 0.2 0.8 0.15],'fontweight','b','units','pixels'},... +% {'max',80,'value',60,'callback','disp(''Slid'')'},... +% {},... +% {{'string','Low','foregroundcolor','b'},... +% {'string','High','foregroundcolor','r'},... +% {'fontweight','b'}},... +% '%0.1f'); +% +% 2) Create a single-slider sliderPanel as a child of a +% uipanel, using struct and cell-array inputs. Moving the +% slider or updating the edit box will immediately refresh +% the value of variable sliderVal in the base workspace. +% +% hFig = figure; +% hPanel = uipanel(hFig,'title','MASTER','pos',[0.3 0.1 0.4 0.6]); +% PnlOpt.title = 'Threshold'; +% PnlOpt.position = [0.05 0.2 0.9 0.4]; +% PnlOpt.fontsize = 10; +% SldrOpt.min = 10; +% SldrOpt.max = 100; +% SldrOpt.value = 50; +% SldrOpt.callback = 'assignin(''base'',''sliderVal'',get(gcbo,''value''));'; +% sliderPanel(hPanel,PnlOpt,SldrOpt,{'fontsize',12},{},'%0.0f') +% +% 3) Create multiple sliderPanels as children of a UIPANEL. +% +% figure; +% h = uipanel(gcf,'title','MAIN','units','normalized','pos',[0.2 0.1 0.6 0.8]); +% PnlOpt.title = 'Parameter Tool'; +% PnlOpt.bordertype = 'none'; +% PnlOpt.titleposition = 'centertop'; +% PnlOpt.fontweight = 'bold'; +% SldrOpt.min = 0; +% SldrOpt.max = 255; +% SldrOpt.value = 50; +% EditOpts = {'fontsize',10}; +% LabelOpts = {'fontsize',9,'fontweight','b'}; +% numFormat = '%0.0f'; +% titleStrings = {'Slider 1','Slider 2', 'Slider 3', 'Slider 4'}; +% startPos = {[0.1 0.05 0.8 0.21]; +% [0.1 0.28 0.8 0.21]; +% [0.1 0.51 0.8 0.21]; +% [0.1 0.74 0.8 0.21]}; +% sldrCallbacks = {'disp(''Slider 1 moved'')'; +% 'disp(''Slider 2 moved'')'; +% 'disp(''Slider 3 moved'')'; +% 'disp(''Slider 4 moved'')'}; +% for ii = 1:4 +% PnlOpt.position = startPos{ii}; +% PnlOpt.title = titleStrings{ii}; +% SldrOpt.callback = sldrCallbacks{ii}; +% sliderPanel(h,PnlOpt,SldrOpt,EditOpts,LabelOpts,numFormat); +% end +% +% 4) Demonstrate the use of sliderPanel in a function that +% interactively thresholds an image. (To try this example, +% paste the following code (both TEST and THRESH) into a new +% mfile, save it, and run it.) +% +% function test +% figure; +% ax1 = axes('units','normalized','pos',[0.1 0.25 0.8 0.7]); +% myimg = im2double(imread('cameraman.tif')); +% imobj = imshow(myimg); +% sliderPanel(gcf,{'pos',[0.1 0.05 0.8 0.15]},{'callback',{@thresh,myimg,imobj}},{},{},'%0.1f') +% +% % SUBFUNCTION: +% function thresh(varargin) +% sldr = varargin{1}; +% newval = get(sldr,'value'); +% myimg = varargin{3}; +% imobj = varargin{4}; +% set(imobj,'cdata',myimg > newval); +% +% 5) SIMPLIFIED SYNTAX +% +% hFig = gcf; +% [a,b]=sliderPanel(... +% 'Title' , 'Slider Panel', ... +% 'Position', [0.3, 0.5, 0.4, 0.2], ... +% 'Min' , 0, ... +% 'Max' , 100, ... +% 'Value' , 50, ... +% 'String' , 'Slider 1', ... +% 'FontName', 'Verdana', ... +% 'units','pixels',... +% 'numformat','%0.0f',... +% 'Callback', 'disp(''slid'')') + +% REVISIONS: +% 06/07/2010 +% Modified simple syntax to specify label colors the same as background +% colors, unless otherwise set. +% +% 10/10/2012 +% Implemented right-click resetting to default (initial) value. Right-click +% anywhere on the slider itself, and the slider and text reset +% automatically. +% +% 1/18/2013 Right-clicking to reset default now (appropriately) triggers +% slider's callback. + +% Written by Brett Shoelson, PhD +% brett.shoelson@mathworks.com +% 01/21/07 +% Copyright 2007 - 2012 MathWorks, Inc. + + +if nargin < 6, numFormat = []; end +if nargin < 5, LabelPVs = {}; end +if nargin < 4, EditPVs = {}; end +if nargin < 3, SliderPVs = {}; end +if nargin < 2, PanelPVs = {}; end +if nargin == 0, parent = gcf; end + +% OPTIONAL CALLING SYNTAX: +% Subset of functionality available for this calling syntax +if nargin > 1 && ~iscell(PanelPVs) && ~isa(PanelPVs,'struct') + allargs = {parent,PanelPVs,SliderPVs,EditPVs,LabelPVs,numFormat,varargin{:}}; + PanelPVs = {};SliderPVs = {};EditPVs = {};LabelPVs = {};numFormat = []; + if ishandle(allargs{1}), + parent = allargs{1}; + end + loc = cellfind(allargs,'parent'); + if ~isempty(loc) + parent = allargs{loc+1}; + end + if ~ishandle(parent) + parent = gcf; + end + loc = cellfind(allargs,'numformat'); + if ~isempty(loc) + numFormat = allargs{loc+1}; + end + loc = cellfind(allargs,'numberformat'); + if ~isempty(loc) + numFormat = allargs{loc+1}; + end + + PanelPVs = validate(allargs,PanelPVs,... + {'title','pos','position','fontname','fontname','fontsize',... + 'fontweight','backgroundcolor','bordertype','tag','units','visible','userdata'}); + SliderPVs = validate(allargs,SliderPVs,... + {'min','max','value','callback','sliderstep','units'}); + EditPVs = validate(allargs,EditPVs,... + {'fontname','fontsize','fontweight'}); + LabelPVs = validate(allargs,LabelPVs,{'fontname','fontsize',... + 'fontweight','units'}); + if isfield(PanelPVs,'backgroundcolor') && ~isfield(LabelPVs,'backgroundcolor') + LabelPVs.backgroundcolor = PanelPVs.backgroundcolor; + end +end + +% CREATE PANEL (DEFAULT) +% Uipanels can be children of figures, uipanels, or +% uibuttongroups; the latter two are of 'type' 'uipanel' + +% CREATE UIPANEL AS PARENT +panelHandle = uipanel('parent',parent); + +% CREATE SLIDER (DEFAULT) +sliderHandle = uicontrol(panelHandle,'style','slider','units','normalized',... + 'pos',[0.05 0.5 0.9 0.40]); +% CREATE EDIT BOX (DEFAULT) +editHandle = uicontrol(panelHandle,'style','edit','units','normalized',... + 'pos',[0.35 0.05 0.3 0.35]); +% CREATE LABELS (DEFAULT) +labelHandle(1) = uicontrol(panelHandle,'style','text','units','normalized',... + 'pos',[0.05 0.05 0.25 0.25],'horizontalalignment','l',... + 'Backgroundcolor',get(panelHandle,'Backgroundcolor')); +labelHandle(2) = uicontrol(panelHandle,'style','text','units','normalized',... + 'pos',[0.7 0.05 0.25 0.25],'horizontalalignment','r',... + 'Backgroundcolor',get(panelHandle,'Backgroundcolor')); + +% CUSTOMIZE PER USER-DEFINED PV PAIRS +applyPVs(panelHandle,PanelPVs); +applyPVs(sliderHandle,SliderPVs); + +% EXTRACT SLIDER PARAMETERS +sldr.minval = get(sliderHandle,'min'); +sldr.maxval = get(sliderHandle,'max'); +sldr.value = get(sliderHandle,'value'); +%Ensure that slider's value is in acceptable range of +%[min,max] +if sldr.value < sldr.minval || sldr.value > sldr.maxval + disp('Out-of-range value ignored for slider object.'); + sldr.value = sldr.minval; + set(sliderHandle,'value',sldr.value); +end +sldr.callback = get(sliderHandle,'callback'); + +set(labelHandle(1),'string',sldr.minval); +set(labelHandle(2),'string',sldr.maxval); +set(editHandle,'string',sldr.value); + +applyPVs(editHandle,EditPVs); +% If LabelPVs is a 1x2 array of cells, then cell 1 is +% applied to label 1, and cell 2 is applied to label 2. +% Otherwise, +if numel(LabelPVs)>1 && iscell(LabelPVs{1}) && iscell(LabelPVs{2}) + applyPVs(labelHandle(1),LabelPVs{1}); + applyPVs(labelHandle(2),LabelPVs{2}); +else + applyPVs(labelHandle,LabelPVs); +end +% If a third array of PVs is provided, use it for both +% labels. +if numel(LabelPVs)>2 && iscell(LabelPVs{3}) + applyPVs(labelHandle,LabelPVs{3}); +end + +%USERDATA IS A CHAR +set(editHandle,'userdata',get(editHandle,'string')); + +%GIVE ADDHNDLEVENT/EVALHNDLEVENT A TRY +addHndlEvent(sliderHandle,'callback',@updateText); +addHndlEvent(editHandle,'callback',@updateSlider); + + function applyPVs(obj,pvarray) + if isstruct(pvarray) + set(obj,pvarray); + else %Cell + if ~isempty(pvarray) + for ii = 1:2:numel(pvarray) + set(obj,pvarray{ii},pvarray{ii+1}); + end + %set(obj,pvarray{:}); + end + end + % NEW: 10/10/2012: implement right-click resetting of default + % initial value + if strcmp(get(obj,'type'),'uicontrol') + if strcmp(get(obj,'style'),'slider') + val = get(obj,'value'); + set(obj,'buttondownfcn',{@resetDefault,gcbo,val}); + end + end + end + + function resetDefault(varargin) + set(varargin{1},'value',varargin{4}); + updateText; + if ~isempty(sldr.callback) + feval(sldr.callback,varargin{1}); + end + end + + function updateText(varargin) + %Triggered by slider move + newVal = get(sliderHandle,'value'); + if ~isempty(numFormat) + newVal = sprintf(numFormat,newVal); + end + set(editHandle,'string',newVal,'userdata',newVal); + drawnow; + end + + function updateSlider(varargin) + %Triggered by text change + newVal = get(editHandle,'string'); + if isnan(str2double(newVal)) || str2double(newVal) < get(sliderHandle,'min') || str2double(newVal) > get(sliderHandle,'max') + set(editHandle,'string',get(editHandle,'userdata')); + return + end + set(sliderHandle,'value',str2double(newVal)); + set(editHandle,'userdata',newVal); + set(editHandle,'value',str2double(newVal));%BUG FIX, 7/1/10 + drawnow; + currFun = sldr.callback; + if isempty(currFun) + %Do nothing + elseif isa(currFun,'function_handle') + %REPLACE OBJECT HANDLE WITH THAT OF SLIDER + varargin{1} = sliderHandle; + currFun(varargin{:}); + %feval(sldr.callback,varargin{:}); + elseif isa(currFun,'char') + %Just in case the callback specifies GCBO (which + %will initially point to the edit box, rather + %than the slider: + currFun = strrep(currFun,'gcbo','sliderHandle'); + eval(currFun); + elseif isa(currFun,'cell'); + %REPLACE OBJECT HANDLE WITH THAT OF SLIDER + varargin{1} = sliderHandle; + currFun{1}(varargin{:},currFun{2:end}); + else + %Shouldn't ever get here...but if you do, I + %would like to know about it. + error('Unrecognized event registered in eventid %d.',ii); + end + end + + function addHndlEvent(hndl,eventtype,newevent) + hndlevent = getappdata(hndl,[eventtype 'hndlevent']); + if isempty(hndlevent) + %Initialize to original event comand + hndlevent.cmdset = get(hndl,eventtype); + end + if isempty(hndlevent.cmdset) + numevents = 0; + else + numevents = numel(hndlevent); + end + hndlevent(numevents+1).cmdset = newevent; + + set(hndl,eventtype,@evalHndlEvent); + setappdata(hndl,[eventtype 'hndlevent'],hndlevent); + + function evalHndlEvent(varargin) + hndlevent = getappdata(hndl,[eventtype 'hndlevent']); + if nargin < 4 + eventList = 1:numel(hndlevent); + end + for ii = eventList + currFun = hndlevent(ii).cmdset; + if isempty(currFun) + continue + elseif ischar(currFun) + eval(currFun); + elseif iscell(currFun) + currFun{1}(varargin{:},currFun{2:end}); + else + currFun(varargin{:}); + end + end + end + end + + function PVarray = validate(allargs, PVarray, parameterStrings) + for ii = 1:numel(parameterStrings) + parameter = parameterStrings{ii}; + loc = cellfind(allargs, parameter); + if ~isempty(loc) + eval(['PVarray.' parameter ' = allargs{loc(1)+1};']); + end + end + end + + function posns = cellfind(cellarray, searchval) + posns = []; + if ischar(searchval) + searchval = lower(searchval); + for ii = 1:numel(cellarray) + tmp = cellarray{ii}; + if ischar(tmp) + tmp = lower(tmp); + end + if isequal(searchval,tmp) + posns = [posns;ii]; + end + end + end + end + +end","MATLAB" +"Neurology","ChristianGaser/cat12","tfceMex_pthread.m",".m","1254","44","tfce = tfceMex_pthread(t, dh, E, H, calc_neg, single_threaded) +% Apply threshold-free cluster enhancement (TFCE) +% FORMAT tfce = tfceMex(t, dh, E, H, calc_neg, single_threaded) +% Estimate TFCE +% t - T map +% dh - step size (e.g. dh = max(abs(t))/100) +% E - TFCE parameter for extent +% H - TFCE parameter for height +% calc_neg - also calc neg. TFCE values (default) +% single_threaded - use single thread only +% +% ______________________________________________________________________ +% +% Christian Gaser +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +rev = '$Rev: 125 $'; + +disp('Compiling tfceMex_pthread.c') + +pth = fileparts(which(mfilename)); +p_path = pwd; +cd(pth); + +if strcmpi(spm_check_version,'octave') + mexcmd = 'mkoctfile --mex'; + mexflag=' -O -DOCTAVE '; +else + mexcmd = 'mex'; + mexflag=' -O -largeArrayDims COPTIMFLAGS=''-O3 -fwrapv -DNDEBUG'' CFLAGS=''$CFLAGS -pthread -Wall -ansi -pedantic -Wextra'' '; +end + +eval([mexcmd ' ' mexflag ' tfceMex_pthread.c']) + +cd(p_path); + +tfce = tfceMex_pthread(t, dh, E, H, calc_neg, single_threaded); + +return +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_vol_downcut.m",".m","1917","41","%cat_vol_downcut Intensity limited region-growing +% Region growing of integer objects in O depending on a distance map that +% is created on the path distance to the object and the intensity in L. +% The region growing for the intensity map is limited by the lim where a +% neighbor value have fit for the following equation: +% L(neigbor(x)) + limit <= L(x) +% But not only the intensity of L is important, also the object distance +% can be used. You can set up the relation of both with the dd value, +% where dd(1) is used for the distance component and dd(2) for the +% intensity component. This regions growing was orignialy used for skull- +% stripping. +% +% [D,I] = cat_vol_downcut(O,L,lim,vx,dd) +% +% O (3d single) .. initial object (integer values for different objects) +% L (3d single) .. intensity image +% lim (1x1 double) .. limit for the neighbor intensity in the regions +% growing L(neigbor(x)) + limit <= L(x) +% vx (1x3 double) .. voxel size +% dd (1x2 double) .. distance weighting for the path length of the regions +% growing (dd(1)) and the intensity (dd(2)) +% (default [0.1 10]) +% +% Example: +% 1) +% A = zeros(50,50,3,'single'); A(:,1:25,:)=0.25; A(:,25:end,:)=0.75; +% A = A + (rand(size(A),'single')-0.5)*0.05; +% B = zeros(50,50,3,'single'); B(15:35,15:20,:)=1; B(15:35,30:35,:)=2; +% [C,D] = cat_vol_downcut(B,A,1); ds('d2smns','',1,A,C,2); +% [C,D] = cat_vol_downcut(B,A,1,[1 1 1],[10 1]); ds('d2smns','',1,A+B,C,2); +% +% See also cat_vol_simgrow, compile. +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_vol_slice_overlay_rgb_ui.m",".m","4693","173","function cat_vol_slice_overlay_rgb_ui +% Wrapper to cat_vol_slice_overlay for overlaying +% 3 different images to a RGB overlay +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ + +clear global SO +global SO + +% --------------------------------------------------------------------------------------- +% image array of max. 3 images +% --------------------------------------------------------------------------------------- +name = char(fullfile(cat_get_defaults('extopts.pth_templates'),'cobra.nii'),... + fullfile(cat_get_defaults('extopts.pth_templates'),'mori.nii'),... + fullfile(cat_get_defaults('extopts.pth_templates'),'cat.nii')); + +range = [0 1]; % this should be adapted to the image range +logP = 0; % option to use log-scaled colorbars if the input is a log-transformed p-map + +% --------------------------------------------------------------------------------------- +% underlying image +% --------------------------------------------------------------------------------------- +SO.img(1).vol = spm_vol(cat_get_defaults('extopts.shootingT1')); +SO.img(1).prop = 1; +SO.img(1).cmap = gray; +SO.img(1).range = [0.2 1]; % image range have to be adapted + +% --------------------------------------------------------------------------------------- +% selection of slices +% --------------------------------------------------------------------------------------- +% this should be adapted +slices = [{-42:3:52}, {-70:3:30}]; +transform = str2mat('axial','coronal'); +sl_name = str2mat('axial: -42:3:59','coronal: -70:3:34'); + +% Comment this out if you don't wish slice labels +SO.labels=[]; + +% --------------------------------------------------------------------------------------- +% --------------------------------------------------------------------------------------- +ind = 1; +nm = deblank(name(ind,:)); +range = range(ind,:); +logP = logP(ind); + +n = size(sl_name,1); +str = deblank(sl_name(1,:)); +for i = 2:n, str = [str '|' deblank(sl_name(i,:))]; end +ind = spm_input('Select slices',1,'m',str); +transform = deblank(transform(ind,:)); +slices = slices{ind}; + + +for i=(1:size(name,1))+1 + SO.img(i).background = 0; + SO.img(i).vol = spm_vol(deblank(name(i-1,:))); + SO.img(i).prop = 1; + + cmap = zeros(64,3); + cmap(:,i-1) = (1:64)'/64; + SO.img(i).cmap = cmap; + + SO.img(i).range = range; + SO.img(i).func = 'i1(i1==0)=NaN;'; + + if range(1) > 0 + SO.img(i).outofrange = {0,size(SO.img(i).cmap,1)}; + else + SO.img(i).outofrange = {1,0}; + end +end + +SO.transform = transform; +SO.slices = slices; +SO.cbar=[(1:size(name,1))+1]; + +n_images = length(slices) + length(SO.cbar); +xy = get_xy(n_images); + +n = size(xy,1); +xy_name = num2str(xy); +str = deblank(xy_name(1,:)); +for i = 2:n, str = [str '|' deblank(xy_name(i,:))]; end +ind = spm_input('Select xy',1,'m',str); +xy = xy(ind,:); + + +SO.xslices = xy(:,1); +switch lower(SO.transform) + case 'sagittal' + dim = xy.*SO.img(1).vol.dim(2:3); + case 'coronal' + dim = xy.*SO.img(1).vol.dim([1 3]); + case 'axial' + dim = xy.*SO.img(1).vol.dim(1:2); +end +screensize = get(0,'screensize'); + +scale = screensize(3:4)./dim; +% scale image only if its larger than screensize +if min(scale) < 1 + fig_size = min(scale)*dim*0.975; +else + fig_size = dim; +end + +h = figure(12); +set(h,... + 'Position',[1 1 fig_size],... + 'MenuBar','none',... + 'Resize','off',... + 'PaperType','A4',... + 'PaperUnits','normalized',... + 'PaperPositionMode','auto',... + 'Visible','off'); + +SO.figure = h; +SO.area.units='pixels'; + +slice_overlay + +% save image +saving = spm_input('Save png images?','+1','yes|no',[1 0],2); +if saving + [pt,nm] = fileparts(nm); + imaname = spm_input('Filename','+1','s',[nm '_' lower(transform) '.png']); + slice_overlay('print',imaname,'print -dpng -painters -noui') + fprintf('Image %s saved.\n',imaname); +end + +return + +function xy = get_xy(n) + +nn = round(n^0.4); +if n>8, x = nn:round(n/nn); else x = 1:n; end +xy=[]; +for i=1:length(x) + y = round(n/x(i)); + % check whether y is to small + while y*x(i)2 + if y*x(i-1)1 + if strcmp(s(pos),'0') + s(pos)=''; + pos = pos-1; + else break + end +end +","MATLAB" +"Neurology","ChristianGaser/cat12","check_pipeline_homogeneity.m",".m","1879","71","function check_pipeline_homogeneity +%check_pipeline_homogeneity to sample homogeneity for different +% cat12 releases using check_pipeline.sh +% +% _________________________________________________________________________ +% $Id$ + +min_release = 1800; +max_release = 3000; + +% list nifti files and exclude longitudinal ADNI-data +data = spm_select('List','.','.nii'); +ind = []; +for i=1:size(data,1) + if ~isempty(strfind(data(i,:),'ADNI')) + ind = [ind i]; + end +end +data(ind,:) = []; +data = char('ADNI-longitudinal',data); +sel = spm_input('Data',1,'m',data); + +job = struct('c',[],'data_xml',[],'gap',3, 'verb',true,'show_name',1,'show_violin',0); + +% longitudinal data +if sel == 1 + dirs = spm_select('List','.','dir','^check_r'); + + % exclude older releases + ind = []; + for i = 1:size(dirs,1) + ind_r = strfind(dirs(i,:),'check_r'); + release = str2num(dirs(i,ind_r+7:ind_r+10)); + if ~isempty(release) && (release < min_release || release > max_release) + ind = [ind i]; + end + end + dirs(ind,:) = []; + + j = 0; + for i = 1:size(dirs,1) + folder = deblank(dirs(i,:)); + if ~isempty(strfind(folder,'check_r')) + files = spm_select('FPListRec',[folder '/long'],'^mwmwp1.*\.nii$'); + if size(files,1) >= 2 + j = j + 1; + job.data_vol{j} = files; + end + end + end +else % selected cross-sectional data + files = spm_select('FPListRec','.',['^mwp1' deblank(data(sel,:))]); + ind = []; + for i=1:size(files,1) + ind_r = strfind(files(i,:),'check_r'); + release = str2num(files(i,ind_r+7:ind_r+10)); + if (release < min_release) || release > max_release || ~isempty(strfind(files(i,:),'not_used')) + ind = [ind i]; + end + end + files(ind,:) = []; + job.data_vol{1} = files; +end + +cat_stat_check_cov_old(job); +[pth filename] = spm_fileparts(deblank(data(sel,:))); + +name = ['check_cov' filename '.png']; + +saveas(1, name); +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_main_clean_gwc1639.m",".m","5592","148","function P = cat_main_clean_gwc1639(P,level,new) +%========================================================================== +% Cleanup function that removes non-brain tissue (e.g. meninges) by means +% of morphological operations to cleanup WM, GM, and CSF tissue. +% Successor of the cg_cleanup_gwc function of VBM8. +% Include a new brain limitation that remove/add empty space around the +% brain for speedup (no functional difference). +% +% Moreover, a new morpholocial cleanup close to the skull was added to +% remove larger unwanted parts of head tissue that is used for the kamap +% preprocessing pipeline (see cat_main_kamap, 201812 - 202311). +% RD202108: Added file input and new cleanup method for PD/T2 data. +% RD202311: Remove kamap but keep new cleanup. +% +% function P = cat_main_clean_gwc1639(P[,level,new]) +% +% P .. 4D uint8 matrix of tissue classes GM, WM, and CSF +% level .. controls strength of corrections (values=[1,2]; default=1) +% new .. use new additional cleanup (default=0) +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +if nargin<2, level = 1; end +if nargin<3, new = 0; end + +% remove empty space for speed up +sP = sum(P,4); +for i=1:size(P,4), [P2(:,:,:,i),BB] = cat_vol_resize(P(:,:,:,i),'reduceBrain',ones(1,3),2,sP); end %#ok +P = P2; clear sP P2; + +% New additional harder cleanup close to the skull to remove meninges. +% Added due to problems with the alternative cat_main_kamap segmentation. +% However, this should also help in other cases and should not create to +% large problems. >> TEST IT! (RD201812, RD202311 also kamap was removed) +%-------------------------------------------------------------------------- +if new + Yp0 = single(P(:,:,:,3))/255 + single(P(:,:,:,1))/255*2 + single(P(:,:,:,2))/255*3; + Ybe = cat_vol_morph(cat_vol_morph( cat_vol_morph(Yp0>0.5,'ldc',1), 'de', 5 ), 'lc'); % area close to the skull + % mask WM + Ymsk = Ybe | cat_vol_morph( cat_vol_morph( Yp0>2.5 , 'do' , 0.5 + level/2 ) , 'l' , [10 0.1]); + P(:,:,:,2) = cat_vol_ctype(single(P(:,:,:,2)) .* cat_vol_smooth3X(cat_vol_morph(Ymsk,'dd',1.5),0.5)); + Yp0 = single(P(:,:,:,3))/255 + single(P(:,:,:,1))/255*2 + single(P(:,:,:,2))/255*3; % update + % mask GM (iter + Ywd = cat_vol_morph( Yp0>2.5 , 'dd' , 5 - level); % area close to the WM + for i=1:2 + Ymsk = cat_vol_morph(Ybe | (Ywd & cat_vol_morph( Yp0>1.5 , 'do' , level/2+1.5 )),'ldc',1); + P(:,:,:,1) = cat_vol_ctype(single(P(:,:,:,1)) .* cat_vol_smooth3X(cat_vol_morph(Ymsk,'dd',1.5),0.5)); + end + Yp0 = single(P(:,:,:,3))/255 + single(P(:,:,:,1))/255*2 + single(P(:,:,:,2))/255*3; % update + % CSF + for i=1:2 + Ymsk = cat_vol_morph(Ybe | (cat_vol_morph( Yp0>0.95 , 'do' , level+2.5 )),'ldc',1); + P(:,:,:,3) = cat_vol_ctype(single(P(:,:,:,3)) .* cat_vol_smooth3X(cat_vol_morph(Ymsk,'dd',1.5),0.5)); + end + clear Yp0 Ybe Ymsk Ywd; +end + +%b = P(:,:,:,2); +b = cat_vol_morph(P(:,:,:,2)>128,'l',[10 0.1])*255; + +% Build a 3x3x3 seperable smoothing kernel +%-------------------------------------------------------------------------- +kx=[0.75 1 0.75]; +ky=[0.75 1 0.75]; +kz=[0.75 1 0.75]; +sm=sum(kron(kron(kz,ky),kx))^(1/3); +kx=kx/sm; ky=ky/sm; kz=kz/sm; + +th1 = 0.15; +if level>1, th1 = 0.2; end +% Erosions and conditional dilations +%-------------------------------------------------------------------------- +niter = 32; +niter2 = 32; +spm_progress_bar('Init',niter+niter2,'Extracting Brain','Iterations completed'); +for j=1:niter + if j>2, th=th1; else th=0.6; end % Dilate after two its of erosion + for i=1:size(b,3) + gp = single(P(:,:,i,1)); + wp = single(P(:,:,i,2)); + bp = single(b(:,:,i))/255; + bp = (bp>th).*(wp+gp); + b(:,:,i) = cat_vol_ctype(round(bp)); + end + spm_conv_vol(b,b,kx,ky,kz,-[1 1 1]); + spm_progress_bar('Set',j); +end + +% Also clean up the CSF. +if niter2 > 0, + c = b; + for j=1:niter2 + for i=1:size(b,3) + gp = single(P(:,:,i,1)); + wp = single(P(:,:,i,2)); + cp = single(P(:,:,i,3)); + bp = single(c(:,:,i))/255; + bp = (bp>th).*(wp+gp+cp); + c(:,:,i) = cat_vol_ctype(round(bp)); + end + spm_conv_vol(c,c,kx,ky,kz,-[1 1 1]); + spm_progress_bar('Set',j+niter); + end +end + +th = 0.05; + +for i=1:size(b,3) + slices = cell(1,size(P,4)); + for k1=1:size(P,4), + slices{k1} = single(P(:,:,i,k1))/255; + end + bp = single(b(:,:,i))/255; + bp = ((bp>th).*(slices{1}+slices{2}))>th; + slices{1} = slices{1}.*bp; + slices{2} = slices{2}.*bp; + + if niter2>0, + cp = single(c(:,:,i))/255; + cp = ((cp>th).*(slices{1}+slices{2}+slices{3}))>th; + slices{3} = slices{3}.*cp; + end + if numel(slices)>=5 + slices{5} = slices{5}+1e-4; % Add something to the soft tissue class + end + tot = zeros(size(bp))+eps; + for k1=1:size(P,4), + tot = tot + slices{k1}; + end + for k1=1:size(P,4), + P(:,:,i,k1) = cat_vol_ctype(round(slices{k1}./tot*255)); + end +end + +% add previously removed empty space +for i=1:size(P,4), P2(:,:,:,i) = cat_vol_resize(P(:,:,:,i),'dereduceBrain',BB); end; +P = P2; clear P2; + +spm_progress_bar('Clear'); +return; +%========================================================================== +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_vol_nonlin_coreg.m",".m","7639","88","%----------------------------------------------------------------------- +% Job for non-linear coregistration batch +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ +%----------------------------------------------------------------------- + +global vox reg bb +warning('off','MATLAB:DELETE:FileNotFound'); + +matlabbatch{1}.spm.spatial.preproc.channel.vols = ''; + +matlabbatch{1}.spm.spatial.preproc.channel.biasreg = 0.001; +matlabbatch{1}.spm.spatial.preproc.channel.biasfwhm = 60; +matlabbatch{1}.spm.spatial.preproc.channel.write = [0 0]; +matlabbatch{1}.spm.spatial.preproc.tissue(1).tpm = {fullfile(spm('dir'),'tpm','TPM.nii,1')}; +matlabbatch{1}.spm.spatial.preproc.tissue(1).ngaus = 1; +matlabbatch{1}.spm.spatial.preproc.tissue(1).native = [1 0]; +matlabbatch{1}.spm.spatial.preproc.tissue(1).warped = [0 0]; +matlabbatch{1}.spm.spatial.preproc.tissue(2).tpm = {fullfile(spm('dir'),'tpm','TPM.nii,2')}; +matlabbatch{1}.spm.spatial.preproc.tissue(2).ngaus = 1; +matlabbatch{1}.spm.spatial.preproc.tissue(2).native = [1 0]; +matlabbatch{1}.spm.spatial.preproc.tissue(2).warped = [0 0]; +matlabbatch{1}.spm.spatial.preproc.tissue(3).tpm = {fullfile(spm('dir'),'tpm','TPM.nii,3')}; +matlabbatch{1}.spm.spatial.preproc.tissue(3).ngaus = 2; +matlabbatch{1}.spm.spatial.preproc.tissue(3).native = [1 0]; +matlabbatch{1}.spm.spatial.preproc.tissue(3).warped = [0 0]; +matlabbatch{1}.spm.spatial.preproc.tissue(4).tpm = {fullfile(spm('dir'),'tpm','TPM.nii,4')}; +matlabbatch{1}.spm.spatial.preproc.tissue(4).ngaus = 3; +matlabbatch{1}.spm.spatial.preproc.tissue(4).native = [1 0]; +matlabbatch{1}.spm.spatial.preproc.tissue(4).warped = [0 0]; +matlabbatch{1}.spm.spatial.preproc.tissue(5).tpm = {fullfile(spm('dir'),'tpm','TPM.nii,5')}; +matlabbatch{1}.spm.spatial.preproc.tissue(5).ngaus = 4; +matlabbatch{1}.spm.spatial.preproc.tissue(5).native = [1 0]; +matlabbatch{1}.spm.spatial.preproc.tissue(5).warped = [0 0]; +matlabbatch{1}.spm.spatial.preproc.tissue(6).tpm = {fullfile(spm('dir'),'tpm','TPM.nii,6')}; +matlabbatch{1}.spm.spatial.preproc.tissue(6).ngaus = 2; +matlabbatch{1}.spm.spatial.preproc.tissue(6).native = [1 0]; +matlabbatch{1}.spm.spatial.preproc.tissue(6).warped = [0 0]; +matlabbatch{1}.spm.spatial.preproc.warp.mrf = 1; +matlabbatch{1}.spm.spatial.preproc.warp.cleanup = 1; +matlabbatch{1}.spm.spatial.preproc.warp.reg = [0 0.001 0.5 0.05 0.2]; +matlabbatch{1}.spm.spatial.preproc.warp.affreg = 'mni'; +matlabbatch{1}.spm.spatial.preproc.warp.fwhm = 0; +matlabbatch{1}.spm.spatial.preproc.warp.samp = 3; +matlabbatch{1}.spm.spatial.preproc.warp.write = [0 0]; +matlabbatch{2}.spm.spatial.smooth.data(1) = cfg_dep('Segment: c1 Images', substruct('.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','tiss', '()',{1}, '.','c', '()',{':'})); +matlabbatch{2}.spm.spatial.smooth.data(2) = cfg_dep('Segment: c2 Images', substruct('.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','tiss', '()',{2}, '.','c', '()',{':'})); +matlabbatch{2}.spm.spatial.smooth.data(3) = cfg_dep('Segment: c3 Images', substruct('.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','tiss', '()',{3}, '.','c', '()',{':'})); +matlabbatch{2}.spm.spatial.smooth.data(4) = cfg_dep('Segment: c4 Images', substruct('.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','tiss', '()',{4}, '.','c', '()',{':'})); +matlabbatch{2}.spm.spatial.smooth.data(5) = cfg_dep('Segment: c5 Images', substruct('.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','tiss', '()',{5}, '.','c', '()',{':'})); +matlabbatch{2}.spm.spatial.smooth.data(6) = cfg_dep('Segment: c6 Images', substruct('.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','tiss', '()',{6}, '.','c', '()',{':'})); +matlabbatch{2}.spm.spatial.smooth.fwhm = [3 3 3]; +matlabbatch{2}.spm.spatial.smooth.dtype = 0; +matlabbatch{2}.spm.spatial.smooth.im = 0; +matlabbatch{2}.spm.spatial.smooth.prefix = 's'; +matlabbatch{3}.spm.util.cat.vols(1) = cfg_dep('Smooth: Smoothed Images', substruct('.','val', '{}',{2}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','files')); +matlabbatch{3}.spm.util.cat.name = 'TPM_tmp.nii'; +matlabbatch{3}.spm.util.cat.dtype = 16; +matlabbatch{4}.spm.spatial.normalise.estwrite.subj.vol = ''; +matlabbatch{4}.spm.spatial.normalise.estwrite.subj.resample = ''; +matlabbatch{4}.spm.spatial.normalise.estwrite.eoptions.biasreg = 0.0001; +matlabbatch{4}.spm.spatial.normalise.estwrite.eoptions.biasfwhm = 60; +matlabbatch{4}.spm.spatial.normalise.estwrite.eoptions.tpm(1) = cfg_dep('3D to 4D File Conversion: Concatenated 4D Volume', substruct('.','val', '{}',{3}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','mergedfile')); +matlabbatch{4}.spm.spatial.normalise.estwrite.eoptions.affreg = 'subj'; +matlabbatch{4}.spm.spatial.normalise.estwrite.eoptions.reg = reg*[0 1e-05 0.005 0.0005 0.002]; +matlabbatch{4}.spm.spatial.normalise.estwrite.eoptions.fwhm = 3; +matlabbatch{4}.spm.spatial.normalise.estwrite.eoptions.samp = 3; +matlabbatch{4}.spm.spatial.normalise.estwrite.woptions.bb = bb; +matlabbatch{4}.spm.spatial.normalise.estwrite.woptions.vox = vox; +matlabbatch{4}.spm.spatial.normalise.estwrite.woptions.interp = 4; +matlabbatch{4}.spm.spatial.normalise.estwrite.woptions.prefix = 'w'; +matlabbatch{5}.cfg_basicio.file_dir.file_ops.file_move.files(1) = cfg_dep('Segment: Seg Params', substruct('.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','param', '()',{':'})); +matlabbatch{5}.cfg_basicio.file_dir.file_ops.file_move.files(2) = cfg_dep('Segment: c1 Images', substruct('.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','tiss', '()',{1}, '.','c', '()',{':'})); +matlabbatch{5}.cfg_basicio.file_dir.file_ops.file_move.files(3) = cfg_dep('Segment: c2 Images', substruct('.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','tiss', '()',{2}, '.','c', '()',{':'})); +matlabbatch{5}.cfg_basicio.file_dir.file_ops.file_move.files(4) = cfg_dep('Segment: c3 Images', substruct('.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','tiss', '()',{3}, '.','c', '()',{':'})); +matlabbatch{5}.cfg_basicio.file_dir.file_ops.file_move.files(5) = cfg_dep('Segment: c4 Images', substruct('.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','tiss', '()',{4}, '.','c', '()',{':'})); +matlabbatch{5}.cfg_basicio.file_dir.file_ops.file_move.files(6) = cfg_dep('Segment: c5 Images', substruct('.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','tiss', '()',{5}, '.','c', '()',{':'})); +matlabbatch{5}.cfg_basicio.file_dir.file_ops.file_move.files(7) = cfg_dep('Segment: c6 Images', substruct('.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','tiss', '()',{6}, '.','c', '()',{':'})); +matlabbatch{5}.cfg_basicio.file_dir.file_ops.file_move.files(8) = cfg_dep('Smooth: Smoothed Images', substruct('.','val', '{}',{2}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','files')); +matlabbatch{5}.cfg_basicio.file_dir.file_ops.file_move.files(9) = cfg_dep('3D to 4D File Conversion: Concatenated 4D Volume', substruct('.','val', '{}',{3}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','mergedfile')); +matlabbatch{5}.cfg_basicio.file_dir.file_ops.file_move.action.delete = false; +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_run.m",".m","80250","1975","function varargout = cat_run(job) +% Segment a bunch of images +% ______________________________________________________________________ +% +% FORMAT cat_run(job) +% +% job.channel(n).vols{m} +% job.channel(n).biasreg +% job.channel(n).biasfwhm +% job.channel(n).write +% job.tissue(k).tpm +% job.tissue(k).ngaus +% job.tissue(k).native +% job.tissue(k).warped +% +% See the user interface for a description of the fields. +% +% based on John Ashburners version of +% spm_preproc8_run.m 2281 2008-10-01 12:52:50Z john $ +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +%#ok<*AGROW,*STRIFCND,*STRCL1,*ASGLU,*STREMP> + +%rev = '$Rev$'; + +% ----------------------------------------------------------------- +% Lazy processing (expert feature) +% ----------------------------------------------------------------- +% If N>10000 files were processed the crash of one of J jobs by +% small errors makes it hard to find the unprocess files. +% The lazy processing will only process files, if one of the output +% is missed and if the same preprocessing options were used before. +% ----------------------------------------------------------------- + +% disable parallel processing for only one subject +n_subjects = numel(job.data); +name1 = spm_file(job.data{1},'fpath'); +BIDSfolder = ''; +if n_subjects == 1, job.nproc = 0; end + +if isfield(job.output,'BIDS') + if isfield(job.output.BIDS,'BIDSyes') || isfield(job.output.BIDS,'BIDSyes2') + if isfield(job.output.BIDS,'BIDSyes') + BIDSfolder = job.output.BIDS.BIDSyes.BIDSfolder; + else + BIDSfolder = job.output.BIDS.BIDSyes2.BIDSfolder; + end + + % get path of first data set and find ""sub-"" BIDS part + name1 = spm_file(job.data{1},'fpath'); + ind = min(strfind(name1,'sub-')); + + if ~isempty(strfind(job.data{1},BIDSfolder)) + BIDSfolder = ''; + ind = []; + end + + if ~isempty(ind) + % remove leading "".."" for real BIDS structure + BIDSfolder = strrep(BIDSfolder,['..' filesep],''); + + length_name = length(name1); + + % Shorten path until ""sub-"" indicator is found and add additional + % relative paths to get BIDSfolder relative to ""sub-"" directories. + % This is necessary because there might be additional session + % folders and more + while length_name > ind + name1 = spm_file(name1,'fpath'); + BIDSfolder = ['..' filesep BIDSfolder]; + length_name = length(name1); + end + end + + % we need this in job.extopts for cat_io_subfolders + if isfield(job.output.BIDS,'BIDSyes') + job.extopts.BIDSfolder = BIDSfolder; + else + job.extopts.BIDSfolder2 = BIDSfolder; + end + end +end + + +% If one of the input directories is a BIDS directory and multipe jobs are +% running than create a subfolder logs to save the log-files there and +% not in the current directory. See also for a similar block in cat_parallelize. +% Use the same logic as cat_io_subfolders to find the dataset root +BIDSdir = []; +if isfield(job.extopts,'BIDSfolder') || isfield(job.extopts,'BIDSfolder2') + try + % Find dataset root by looking for subject folders (sub- or sub_) + ppath = name1; + % Split path and find last folder starting with 'sub-' or 'sub_' + parts = strsplit(ppath, filesep); + for pi = length(parts):-1:1 + if ~isempty(parts{pi}) && (strncmp(parts{pi}, 'sub-', 4) || strncmp(parts{pi}, 'sub_', 4)) + % Found subject folder - reconstruct dataset root (parent of sub-* folder) + ind = strfind(ppath, [filesep parts{pi}]); + if ~isempty(ind) + ind = ind(end); + dataset_root = ppath(1:ind-1); + % Get the relative BIDSfolder config + if isfield(job.extopts,'BIDSfolder') + bids_rel = job.extopts.BIDSfolder; + else + bids_rel = job.extopts.BIDSfolder2; + end + % Remove any leading ../ + while strncmp(bids_rel, ['..' filesep], 3) + bids_rel = bids_rel(4:end); + end + % Build derivatives path at dataset root + BIDSdir = fullfile(dataset_root, bids_rel); + break; + end + end + end + catch + BIDSdir = []; + end +end +if ~isempty(BIDSdir) + logdir = fullfile(BIDSdir,'log'); + if ~exist(logdir,'dir'), try, mkdir(logdir); end; end +else + logdir = []; +end +% Another thing that we want to avoid is to fill some of the SPM +% directories and just write in a ../spm12/toolbox/cat12/log subdirectory. +% Do not forget that this is only about the additional log files and +% not real data output. +% If there are no writing permissions in the directory the same is probably true +% for other SPM dirs and the user has to change the working directory anyway. +% So we create an error so that the user can change this. +if isempty(logdir) + try + SPMdir = spm_str_manip(data,'h'); + SPMdiri = find(~cellfun('isempty',SPMdir),1); + if ~isempty(SPMdiri) +% logdir = fullfile(fileparts(mfilename('fullpath')),'logs'); % log already exist as file + logdir = 'logs'; % log already exist as file + if ~exist(logdir,'dir') + try + mkdir(logdir); + catch + cat_io_cprintf('cat_parallelize:CATlogs',['Cannot create directory for logs. \n' ... + 'Please choose another working directory with writing permissions to save the log-files. ']); + end + end + else + logdir = []; + end + catch + logdir = []; + end +end +if ~isempty(logdir) + if ~isempty(BIDSdir) + cat_io_cprintf('n', ['\nFound a CAT12 BIDS directory in the given ' ... + 'pathnames and save the log file there:\n']); + cat_io_cprintf('blue','%s\n\n', logdir); + else + cat_io_cprintf('n', ['\nYou working directory is in the SPM12/CAT12 ' ... + 'path, where log files saved here:\n']); + cat_io_cprintf('blue','%s\n\n', logdir); + end +end +% RD202403: added path and filesnames - maybe better as separate structure +job.filedata.help = ['Structure directory and file names. \n' ... + ' logdir .. path for log file \n' ... + ' rawdir .. origin directory of the RAW data \n' ... + ' BIDSfolder .. relative path to the main result directory \n' ... + ' BIDSdir .. absolution (full) path to the result directory \n']; +job.filedata.rawdir = name1; +job.filedata.logdir = logdir; +job.filedata.BIDSdir = BIDSdir; +job.filedata.BIDSfolder = BIDSfolder; +%} + +if ( isfield(job.extopts,'lazy') && job.extopts.lazy && ~isfield(job,'process_index') ) || ... + ( isfield(job.extopts,'admin') && isfield(job.extopts.admin,'lazy') && job.extopts.admin.lazy && ~isfield(job,'process_index') ) + jobl = update_job(job,0); + jobl.vout = vout_job(jobl); + job.data = remove_already_processed(jobl); + if numel(job.data)==0 + % If everything is ready (no new subject or subject that requires + % reprocessing) then we need no parallel jobs. + job.nproc = 0; + end +elseif ~isempty(BIDSdir) + % RD202403: If BIDS is used with ""incorrect"" folder structure file names + % are maybe not unique after reorganization. Besides the + % overwriting of results this can cause also processing errors + % if one parallel job is removing files of another one. Hence, + % we should at least create an error. + jobl = update_job(job,0); + jobl.vout = vout_job(jobl); + + cpath = spm_file( jobl.vout.catxml ,'cpath'); + [cpathu,ui] = unique(cpath); + cpathd = cpath( setdiff(1:numel(cpath),ui) ); + fnames = ''; + + if numel( cpathu ) < numel( cpath ) + for i = 1:numel( cpathd ) + sf = find( cat_io_contains( cpath , cpathd{i} ) ); + fnamesi = sprintf('%4d) Results: %s\n', i, cpathd{i}); + for j = 1:numel(sf) + fnamesi = sprintf('%s %8s: %s\n',fnamesi, sprintf('%d. RAW',j), jobl.vout.catxml{sf(j)} ); %jobl.data{sf(j)}(1:end-2) ); + end + fnames = sprintf('%s\n%s', fnames, fnamesi ); + end + error('cat_run:BIDSnotUniqueResults', ... + ['You are using CAT''s BIDS output:\n' ... + ' %s\n' ... + 'but the given input does not support a unique output (e.g. same filenames) in %d of %d cases:\n' ... + '%s\n' ... + 'Try to select ""Relative Folders"" instead of ""Relative BIDS Folders"".\n'], ... + BIDSfolder, numel( cpath ) - numel( cpathu ), numel( cpath ), fnames ); + + end + %% +end + +% split job and data into separate processes to save computation time +if isfield(job,'nproc') && job.nproc>0 && (~isfield(job,'process_index')) + % rescue original subjects + job_data = job.data; + n_subjects = numel(job.data); + if job.nproc > n_subjects + job.nproc = n_subjects; + end + job.process_index = cell(job.nproc,1); + + % initial splitting of data + for i=1:job.nproc + job.process_index{i} = (1:job.nproc:(n_subjects-job.nproc+1))+(i-1); + end + + % check if all data are covered + for i=1:rem(n_subjects,job.nproc) + job.process_index{i} = [job.process_index{i} n_subjects-i+1]; + end + + tmp_array = cell(job.nproc,1); job.printPID = 1; job.getPID = 2; + + logdate = datestr(now,'YYYYmmdd_HHMMSS'); + PID = zeros(1,job.nproc); + catSID = zeros(1,job.nproc); + for i=1:job.nproc + jobo = job; + + fprintf('\nRunning job %d:\n',i); + for fi=1:numel(job_data(job.process_index{i})) + fprintf(' %s\n',spm_str_manip(char(job_data(job.process_index{i}(fi))),'a78')); + end + job.data = job_data(job.process_index{i}); + + % temporary name for saving job information + tmp_name = [tempname '.mat']; + tmp_array{i} = tmp_name; + %def = cat_get_defaults; job = cat_io_checkinopt(job,def); % further job update required here to get the latest cat defaults + spm12def = spm_get_defaults; + cat12def = cat_get_defaults; + save(tmp_name,'job','spm12def','cat12def'); + clear spm12def cat12; + + % matlab command, cprintferror=1 for simple printing + matlab_cmd = sprintf(... + ['""global cprintferror; cprintferror=1; addpath(''%s'', ''%s'', ''%s'', ''%s'');load(''%s''); ' ... + 'global defaults; defaults=spm12def; clear defaults; '... + 'global cat; cat=cat12def; clear cat; cat_run(job); ""'],... + spm('dir'),fullfile(fileparts(mfilename('fullpath'))),... + fullfile(spm('dir'),'toolbox','OldNorm'),fullfile(spm('dir'),'toolbox','DARTEL'), tmp_name); + + % log-file for output + if isempty(logdir) + log_name{i} = ['catlog_main_' logdate '_log' sprintf('%02d',i) '.txt']; + else + log_name{i} = fullfile(logdir,['catlog_main_' logdate '_log' sprintf('%02d',i) '.txt']); + end + + % test writing + try + pp = spm_fileparts(log_name{i}); + if ~isempty(pp) && ~exist(pp,'dir'), mkdir(pp); else, pp = pwd; end + pid = fopen(log_name{i},'w'); + fwrite(pid,''); + fclose(pid); + delete(log_name{i}); + catch + cat_io_cprintf('err',sprintf('Cannot create ""%s"" file under ""%s"". \n',log_name{i}),pp); + end + + % call matlab with command in the background + if ispc + % check for spaces in filenames that will not work with windows systems and background jobs + if strfind(spm('dir'),' ') + cat_io_cprintf('warn',... + ['\nWARNING: No background processes possible because your SPM installation is located in \n' ... + ' a folder that contains spaces. Please set the number of processes in the GUI \n'... + ' to ''0''. In order to split your job into different processes,\n' ... + ' please do not use any spaces in folder names!\n\n']); + job.nproc = 0; + job = update_job(job,0); + + varargout{1} = run_job(job); + return; + end + % prepare system specific path for matlab + export_cmd = ['set PATH=' fullfile(matlabroot,'bin')]; + [status,result] = system(export_cmd); + system_cmd = ['start matlab -nodesktop -nosplash -r ' matlab_cmd ' -logfile ' log_name{i}]; + else + % -nodisplay .. nodisplay is without figure output > problem with CAT report ... was there a server problem with -nodesktop? + system_cmd = [fullfile(matlabroot,'bin') '/matlab -nodesktop -nosplash -r ' matlab_cmd ' -logfile ""' log_name{i} '"" 2>&1 & ']; + end + [status,result] = system(system_cmd); + cat_check_system_output(status,result); + + + + %% look for existing files and extract their PID for later control + % -------------------------------------------------------------------- + % RD202306 tried lim/limpid = 20/40 rather than 200/400 but got problems + test = 0; lim = 60; ptime = 0.5; % exist file? + testpid = 0; limpid = 120; ptimepid = 2.0; % get PID + ptimesid = 1 * 30; % update every minute? + while test=lim + cat_io_cprintf('warn',sprintf('""%s"" not exist after %d seconds! Proceed! \n',log_name{i},lim)); + end + else + % get PIDs for supervising + % search for the log entry ""CAT parallel processing with MATLAB PID: #####"" + if job.getPID + try + while testpid=limpid && ~isinf(testpid) + cat_io_cprintf('warn',sprintf('""%s"" no PID information available after %d seconds! Proceed! \n',log_name{i},limpid)); + end + end + catch + cat_io_cprintf('warn',sprintf('No PID information available! Proceed! \n')); + end + end + + % open file in editor if GUI is available + test = inf; + if ~strcmpi(spm_check_version,'octave') && usejava('jvm') && feature('ShowFigureWindows') && usejava('awt') + edit(log_name{i}); + end + end + end + + % open file in editor if GUI is available + if ~strcmpi(spm_check_version,'octave') && usejava('jvm') && feature('ShowFigureWindows') && usejava('awt') + edit(log_name{i}); + end + if PID(i)>0 + fprintf('\nCheck %s for logging information (PID: ',spm_file(log_name{i},'link','edit(''%s'')')); + cat_io_cprintf([1 0 0.5],sprintf('%d',PID(i))); + else + fprintf('\nCheck %s for logging information (',spm_file(log_name{i},'link','edit(''%s'')')); + cat_io_cprintf([1 0 0.5],'unknown PID'); + end + cat_io_cprintf([0 0 0],sprintf(').\n_______________________________________________________________\n')); + + % starting many large jobs can cause servere MATLAB errors + pause(1 + rand(1) + job.nproc + numel(job.data)/100); + jobs(i).data = job.data; + + job = jobo; + end + + job = update_job(job); + varargout{1} = vout_job(job); + + %njobs = cellfun(@numel,{jobs.data}); % not used + + % command window output + kcol = [0.5 0.5 0.5]; % color for comma + QMC = cat_io_colormaps('marks+',17); + GMC = cat_io_colormaps('turbo',45); + GMC = GMC ./ repmat( max(1,sum(GMC,2)) , 1 , 3); % make bright values darker + color = @(QMC,m) QMC(max(1,min(size(QMC,1),round(((m-1)*3)+1))),:); + colorgmt = @(GMC,m) GMC(max(1,min(size(GMC,1),round(((m-0.5)*10)+1))),:); + colorsurf = @(SI,m) SI(max(1,min(size(SI,1),round(((m-0.06)*4000)+1))),:); + rps2mark = @(rps) min(10.5,max(0.5,10.5 - rps / 10)) + isnan(rps).*rps; + % not used + %mark2rps = @(mark) min(100,max(0,105 - mark*10)) + isnan(mark).*mark; + %grades = {'A+','A','A-','B+','B','B-','C+','C','C-','D+','D','D-','E+','E','E-','F'}; + %mark2grad = @(mark) grades{max(1,min(numel(grades),max(max(isnan(mark)*numel(grades),1),round((mark+2/3)*3-3))))}; + + err = struct('aff',0,'vbm',0,'sbm',0,'else',0,'warn0',0,'warn1',0,'warn2',0); + + allcatalerts = 0; + allcatwarnings = 0; + if job.getPID + if any(PID==0) + cat_io_cprintf('warn',... + ['\nWARNING: CAT was not able to detect the PIDs of the parallel CAT processes. \n' ... + ' Please note that no additional modules in the batch can be run \n' ... + ' except CAT12 segmentation. Any dependencies will be broken for \n' ... + ' subsequent modules if you split the job into separate processes.\n\n']); + else + %% conclusion without filelist + spm_clf('Interactive'); + cat_progress_bar('Init', sum( numel(job_data) ) ,'CAT-Preprocessing'); + + fprintf('\nStarted %d jobs with the following PIDs:\n',job.nproc); + for i=1:job.nproc + fprintf('%3d) %d subjects (PID: ',i,numel(jobs(i).data)); + cat_io_cprintf([1 0 0.5],sprintf('%6d',PID(i))); + cat_io_cprintf([0 0 0],sprintf('): ')); + cat_io_cprintf([0 0 1],sprintf('%s\n',spm_file(log_name{i},'link','edit(''%s'')'))); + end + + + + %% supervised pipeline processing + % ------------------------------------------------------------------ + % This is a ""simple"" while loop that check if the processes still + % exist and extract information from the log-files, which subject + % was (successfully) processed. + % Finally, a report could be generated and exported in future that + % e.g. count errors give some suggestions + % ------------------------------------------------------------------ + if job.getPID>1 + cat_io_cprintf('warn',sprintf('\nKilling of this process will not kill the parallel processes! \n')); + fprintf('_______________________________________________________________\n'); + fprintf('Completed volumes (see catlog files for details!):\n'); + + % some variables + cid = 0; + PIDactive = ones(size(catSID)); + catSIDlast = zeros(size(catSID)); + [catv,catr] = cat_version; + + %% loop as long as data is processed by active tasks + while cid <= sum( numel(job_data) ) && any( PIDactive ) + pause(ptimesid); + + %% get status of each process + for i=1:job.nproc + % get FID + FID = fopen(log_name{i},'r'); + if FID < 0 + fprintf('File %s was probably deleted. Process monitoring inactive.',log_name{i}); + %continue + end + txt = textscan(FID,'%s','Delimiter','\n'); + txt = txt{1}; + fclose(FID); + + % search for the _previous_ start entry ""CAT12.# r####: 1/14: ./MRData/*.nii"" + catis = find(cellfun('isempty',strfind(txt,sprintf('%s r%s: ',catv,catr)))==0,2,'last'); + if isempty(catis) + catis = find(cellfun('isempty',strfind(txt,sprintf('%s r',catv)))==0,2,'last'); + end + catie = find(cellfun('isempty',strfind(txt,'CAT preprocessing takes'))==0,1,'last'); + if ~isempty(catis) && ( numel(catis)>2 || ~isempty(catie) ) + if catis(end)catis(end) + cathd = textscan( txt{catis(1)} ,'%s%s%s','Delimiter',':'); + cathd = textscan( char(cathd{2}) ,'%d','Delimiter','/'); + catSID(i) = cathd{1}(1); + + caterr = textscan( txt{cati+2} ,'%s','Delimiter','\n'); + caterr = char(caterr{1}); + caterrcode = ''; + + if job.extopts.expertgui + % error message with nested functions + try + %% + for ei = (catl(find(catl>cati,1,'first')+2) - cati - 1):-1:4 + try + txt2 = txt{cati+ei}; + catch + txt2 = ''; + end + if ~isempty(txt2) + catfct{ei-2} = textscan( txt2 ,'%d%s%s','Delimiter',' '); + if ~isempty(catfct{ei-2}) && ~isempty(catfct{ei-2}{1}) + if isempty(caterrcode) + caterrcode = sprintf('%s:%d',char(catfct{ei-2}{3}),double(catfct{ei-2}{1})); + else + caterrcode = [caterrcode '>' sprintf('%s:%d',char(catfct{ei-2}{3}),double(catfct{ei-2}{1}))]; + end + end + end + end + catch + cat_io_cprintf('err','Unknown error in job supervision.\n') + end + else + % only last file and error message + ei = (catl(find(catl>cati,1,'first')+2) - cati - 1); + catfct{1} = textscan( txt{cati+ei} ,'%d%s%s','Delimiter',' '); + caterrcode = sprintf('%s:%d',char(catfct{1}{3}),double(catfct{1}{1})); + end + else + caterr = ''; + caterrcode = ''; + end + % RD20200 + % + % We need some simple error codes that helps the user (check origin) + % but also us (because they may only send us this line). Hence, + % the major position of the error (e.g. cat_run/main) is most + % important. + % + % - affreg VBM error > check origin + % - R#:cat_run:#:Possible registration error - Check origin! + % - R#:cat_main:#:VBM processing error. + % - R#:cat_createCS:#:Surface creation error. + % ----- + % * Handling of warnings? + % * yellow light warning vs. orange severe warning + % - low IQR? < 50% = yellow warning? + % - high topodefarea? > 1000 = yellow warning? > 5000 = orange warning? + % - template corvariance < 0.80 = yellow warning? < 0.60 = orange warning? + % this required an update of cat_vol_qa + % ----- + + + % find out if the current task is still active + if ispc + [status,result] = system(sprintf('tasklist /v /fi ""PID %d""',PID(i))); + else + [status,result] = system(sprintf('ps %d',PID(i))); + end + if isempty( strfind( result , sprintf('%d',PID(i)) ) ) + PIDactive(i) = 0; + end + + + %% update status + % if this test was not printed before ( catSIDlast(i) < catSID(i) ) and + % if one subject was successfully or with error processed ( any(cattime>0) || ~isempty(caterr) ) + %fprintf(' %d - %d %d %d %d\n',i,catSIDlast(i), catSID(i), any(cattime>0), ~isempty(caterr) ); + if ( ( catSIDlast(i) < catSID(i) ) && ( any(cattime>0) || ~isempty(caterr) ) ) || ... + ( ( catSIDlast(i) < catSID(i) ) && ( ~isempty(cati) && cati>catis ) ) + cid = cid + 1; + catSIDlast(i) = catSID(i); + + [pp,ff,ee] = spm_fileparts(jobs(i).data{max(1,catSID(i))}); + + [mrifolder, reportfolder] = cat_io_subfolders(jobs(i).data{max(1,catSID(i))},job); + % sometimes we have to remove .nii from filename if files were zipped + catlog = fullfile(pp,reportfolder,['catlog_' strrep(ff,'.nii','') '.txt']); + + + switch caterr + case 'Bad SPM-Segmentation. Check image orientation!' % pink error that support user interaction + err.txt = 'VBM affreg error - Check origin!'; + err.color = [0.9 0 0.9]; + err.aff = err.aff + 1; + case '' % successful processing + % here it would be necessary to differentiate IQR and PQR + if catwarnings>0 % light yellow warning + err.txt = 'Possible error - Check results!'; + err.color = [0.7 0.4 0]; + err.warn1 = err.warn1 + 1; + elseif catalerts==2 % severe orange waring + err.txt = 'Probable error - Check results!'; + err.color = [1 0.3 0]; + err.warn2 = err.warn2 + 1; + else % no warning + err.txt = ''; + err.color = [0 0 0]; + err.warn0 = err.warn0 + 1; + end + otherwise + err.txt = caterr; + err.color = [1 0 0]; + err.vbm = err.vbm + 1; + end + err.txt = sprintf('R%s:%s:%s',catr,caterrcode,err.txt); + + idx = sprintf(' %d/%d (job %d: %d/%d): ',... + cid,sum( numel(job_data) ), i,catSID(i), numel(jobs(i).data) ); + + if exist(catlog,'file') + catlogt = ['' ... + spm_str_manip( [catlog repmat(' ',1,100)] , sprintf('k%d',70 - numel(idx)) ) ': ']; + else + catlogt = spm_str_manip( fullfile(pp,[ff ee]), 'k60'); + end + + %% display + cat_io_cprintf([0 0 0],idx); + cat_io_cprintf([0 0 0],catlogt); + if isempty(caterr) + cat_io_cprintf([0 0 0],sprintf('% 5d.%02d minutes, ',cattime')); + + % add IQR + col = color(QMC,rps2mark( str2double( catiqr{1}(1:end-1) ))); + cat_io_cprintf(col,sprintf('SIQR=%s',strrep(catiqr{1},'%','%%'))); + + % add GMV - colors only for developer + if job.extopts.expertgui >= 1 && ~strcmp(catrgmv{1},'unknown') + col = colorgmt(GMC,str2double(catrgmv{3}) / 1200 * 2.5); + else + col = [0 0 0]; + end + if job.extopts.expertgui >= 0 + try + cat_io_cprintf(kcol,', '); cat_io_cprintf(col,sprintf('TIV=%4.0fcm%s',... + str2double(catrgmv{3}),'3')); + catch + disp('E'); + end + end + + + % add GMV - colors only for developer + if job.extopts.expertgui > 1 && ~strcmp(catgmt{1},'unknown') + col = colorgmt(GMC,str2double( catgmt{1} )); + elseif job.extopts.expertgui > 1 + col = colorgmt(GMC,str2double( catrgmv{1} ) * 5 ); % simple translation to thickness + else + col = [0 0 0]; + end + kcol = [0.5 0.5 0.5]; % color for comma + if job.extopts.expertgui >= 0 && ~strcmp(catrgmv{1},'unknown') + cat_io_cprintf(kcol,', '); cat_io_cprintf(col,sprintf('rGMV=%s',strrep(catrgmv{1},'%','%%'))); + end + if job.extopts.expertgui >= 0 && ~strcmp(catgmt{1},'unknown') + cat_io_cprintf(kcol,', '); cat_io_cprintf(col,sprintf('GMT=%s',strrep(catgmt{1},'%','%%'))); + end + + % surf vals + if job.extopts.expertgui > 0 && ~strcmp(catgmt{1},'unknown') + colorsurf = @(SI,m) SI(max(1,min(size(SI,1),round((max(0.0,m-0.05)*300)+5))),:); + cat_io_cprintf(kcol,', '); + cat_io_cprintf(colorsurf(GMC,str2double( catSRMSE{1} )),sprintf('surf=%s',catSRMSE{1})); + cat_io_cprintf(kcol,', '); + cat_io_cprintf(colorsurf(GMC,str2double( catSRMSE{2} )),sprintf('%s' ,catSRMSE{2})); + end + + + + % warnings + allcatwarnings = allcatwarnings + catwarnings; + if job.extopts.expertgui > 1 && catwarnings + if catwarnings + col = 'warn'; + else + col = [0.6 0.6 0.6]; + end + cat_io_cprintf(kcol,', '); cat_io_cprintf(col,sprintf('%d warnings',catwarnings)); + end + + % alerts + allcatalerts = allcatalerts + catwarnings; + if job.extopts.expertgui > 1 && catalerts + if catalerts + col = [0.8 0 0 ]; + else + col = [0.6 0.6 0.6]; + end + cat_io_cprintf(kcol,', '); cat_io_cprintf(col,sprintf('%d alerts',catalerts)); + end + + else + cat_io_cprintf(err.color,sprintf('%s',err.txt)); + end + cat_io_cprintf(kcol,'. '); % to avoid color bug? + fprintf(' \n'); + end + end + cat_progress_bar('Set', cid ); + end + end + end + err.missed = max(0,sum( numel(job_data) ) - (err.warn0 + err.warn1 + err.warn2 + err.aff + err.vbm + err.sbm)); + + + % RD202401: create CSV report for all processed files + % besides this a nice para report could be useful that include + % all fields and not just the most relevant on listed in the + % report. + % try + if ~exist('BIDSfolder','var'), BIDSfolder = pwd; end + cat_run_createCSVreport(job,BIDSfolder); + % end + + + %% final report + fprintf('_______________________________________________________________\n'); + fprintf('Conclusion of %d cases: \n',numel(job_data)); + if sum( numel(job_data) ) == err.warn0, col = [0 0.5 0]; else, col = ''; end + cat_io_cprintf(col, sprintf(' Processed successfully:% 8d volume(s)\n',err.warn0)); + if err.warn1 + cat_io_cprintf('warn', sprintf(' Processed with warning:% 8d volume(s)\n',err.warn1)); + end + if err.warn2 + cat_io_cprintf('alert', sprintf(' Processed with alert: % 8d volume(s)\n',err.warn2)); + end + if (err.aff + err.vbm + err.sbm) > 0, col = 'error'; else, col = ''; end + if (err.aff + err.vbm + err.sbm )> 0 + cat_io_cprintf(col, sprintf(' Processed with error: % 8d volume(s)\n',err.aff + err.vbm + err.sbm )); + + % create mail report + promptMessage = sprintf('Do you want to send error message?'); + button = questdlg(promptMessage, 'Error message', 'Yes', 'No', 'Yes'); + if strcmpi(button, 'Yes') + xmlfile = fullfile(pp,reportfolder,['cat_' ff '.xml']); + logfile = fullfile(pp,reportfolder,['catlog_' ff '.txt']); + err_txt = sprintf('Processed %d of %d with errors.',numel(job_data),err.aff + err.vbm + err.sbm); + cat_io_senderrormail(xmlfile,logfile,err_txt); + end + end + if err.missed > 0 + col = 'blue'; %else, col = ''; end + cat_io_cprintf(col, sprintf(' Unknown/Unprocessed: % 8d volume(s)\n\n',err.missed )); + end + fprintf('_______________________________________________________________\n'); + + else + cat_io_cprintf('warn',... + ['\nWARNING: Please note that no additional modules in the batch can be run \n' ... + ' except CAT12 segmentation. Any dependencies will be broken for \n' ... + ' subsequent modules if you split the job into separate processes.\n\n']); + end + + cat_progress_bar('Clear'); + return +end + +if isfield(job,'printPID') && job.printPID + cat_display_matlab_PID +end + +job = update_job(job); + +varargout{1} = run_job(job); +if ( isfield(job.extopts,'lazy') && job.extopts.lazy && ~isfield(job,'process_index')) || ... + ( isfield(job.extopts,'admin') && isfield(job.extopts.admin,'lazy') && job.extopts.admin.lazy && ~isfield(job,'process_index')) + % set default output even it was not processed this time + varargout{1} = jobl.vout; +end + + +% clear useprior option to ensure that option is set back to default +% for next processings +cat_get_defaults('useprior',''); + +% remove files that do not exist +varargout{1} = cat_io_checkdepfiles( varargout{1} ); +return +%_______________________________________________________________________ +function cat_run_createCSVreport(job,BIDSfolder) +%% create a final csv with values from the XML reports + + % define input XMLs + matlabbatch{1}.spm.tools.cat.tools.xml2csv.files = job.data; + for fi = 1:numel(job.data) + [~, reportfolderfi] = cat_io_subfolders(job.data{fi}, job); + matlabbatch{1}.spm.tools.cat.tools.xml2csv.files{fi} = spm_file( strrep(job.data{fi},'.gz',''), ... + 'path', spm_file( fullfile( spm_fileparts(job.data{fi}), reportfolderfi,'t' ),'fpath'), ... + 'prefix', 'cat_', 'ext', '.xml'); + end + + % RD20240129: HOW TO HANDLE MISSED FILES ? >> handle in cat_io_xml2csv + + % filename with date + [~,pp1,pp2] = spm_fileparts(BIDSfolder); + date = ['_' char(datetime('now','Format','yyyyMMddHHmm'))]; + if ~isempty(pp1), pp1 = ['_' pp1 strrep(pp2,'_','-')]; end + matlabbatch{1}.spm.tools.cat.tools.xml2csv.fname = ... + sprintf('CATxml%s%s.csv', pp1, date); + matlabbatch{1}.spm.tools.cat.tools.xml2csv.outdir = ... + {spm_file( fullfile( spm_fileparts(job.data{fi}), spm_str_manip(reportfolderfi,'h')),'fpath') }; + matlabbatch{1}.spm.tools.cat.tools.xml2csv.fieldnames = {' '}; + matlabbatch{1}.spm.tools.cat.tools.xml2csv.avoidfields = {''}; + matlabbatch{1}.spm.tools.cat.tools.xml2csv.report = 'default'; + + % run SPM batch + warning off; + try + evalc('spm_jobman(''run'',matlabbatch);'); + catch + warning('Error in writing final CSV file. Use the XML2CSV batch if the file is required.'); + end + warning on; + + csvfile = fullfile( ... + matlabbatch{1}.spm.tools.cat.tools.xml2csv.outdir{1}, ... + matlabbatch{1}.spm.tools.cat.tools.xml2csv.fname ); + if exist(csvfile,'file') + fprintf('\nPrint CSV-file %s\n\n',spm_file(csvfile,'link','edit(''%s'')')); + end +return +%_______________________________________________________________________ +function job = update_job(job,verbatlas) + if ~exist('verbatlas','var'), verbatlas = 1; end + + % set GUI specific parameter if available + FN = {}; GUIfields = {'registration','segmentation','admin','surface'}; + for fnj=1:numel(GUIfields) + if isfield(job.extopts,GUIfields{fnj}) + FN = [FN;{GUIfields{fnj} fieldnames(job.extopts.(GUIfields{fnj}) )'}]; + end + end + for fnj=1:size(FN,1) + if isfield(job.extopts,FN{fnj,1}) + for fni=1:numel(FN{fnj,2}) + if isfield(job.extopts.(FN{fnj,1}),FN{fnj,2}{fni}) + job.extopts.(FN{fnj,2}{fni}) = job.extopts.(FN{fnj,1}).(FN{fnj,2}{fni}); + %$else + % fprintf('err1: %s\n', FN{fnj,2}{fni}); + end + end + job.extopts = rmfield(job.extopts,FN{fnj,1}); % this is just a GUI field! + end + end + + % get defaults + def = cat_get_defaults; + def.useprior = {}; % additional field for longitudinal processing of the single cases + % that use the affine transformation of the AVG (xml-filename) + + if isfield(job.extopts,'restypes') + def.extopts.restype = (char(fieldnames(job.extopts.restypes))); + def.extopts.resval = job.extopts.restypes.(def.extopts.restype); + end + + def.extopts.new_release = 0; + def.extopts.lazy = 0; + def.extopts.affmod = 0; + def.opts.fwhm = 1; % ############################## why is this set to 1 and not 0? + def.nproc = 0; + def.getPID = 2; % 0 - nothing (old), 1 - get PIDs, 2 - supervise PIDs + + % ROI atlas maps + if isfield(job.output,'ROImenu') % expert/developer GUI that allows control each atlas map + if isfield(job.output.ROImenu,'atlases') + %% image output + try atlases = rmfield(job.output.ROImenu.atlases,'ownatlas'); end %#ok + def.output.atlases = atlases; + def.output.ROI = any(cell2mat(struct2cell(atlases))) || ~isempty( job.output.ROImenu.atlases.ownatlas ); + + if ~isempty( job.output.ROImenu.atlases.ownatlas ) && ~isempty( job.output.ROImenu.atlases.ownatlas{1} ) + for i=1:numel( job.output.ROImenu.atlases.ownatlas ) + [pp,ff,ee] = spm_fileparts( job.output.ROImenu.atlases.ownatlas{i} ); + if ~exist(fullfile(pp,[ff,ee]),'file') + error('cat_run:missingAtlasFile','Cannot find ""%s"".',job.output.ROImenu.atlases.ownatlas{i}) + end + if ~isvarname(ff) + error('cat_run:atlasName',['Your atlas ""%s"" has to be named to be a matlab variable, i.e., \n' ... + 'the filename should not include blanks and other special characters. \n' ... + 'You can test the new filename with ""isvarname"".'],ff); + end + if any( strcmp( spm_str_manip( def.extopts.atlas( cell2mat(def.extopts.atlas(:,2)) < cat_get_defaults('extopts.expertgui') + 1 ,1) ,'cs') ,ff)) + error('cat_run:ownatlasname', ... + ['There is a atlas file name conflict. Each atlas name has to be unique. \n' ... + 'Please rename your own atlas map ""%s"". \n'],fullfile(pp,[ff ee]) ); + else + % add new atlas + def.output.atlases.(ff) = 1; + def.extopts.atlas = [ def.extopts.atlas; [ job.output.ROImenu.atlases.ownatlas(i) {def.extopts.expertgui} {{'gm','wm','csf'}} {0} ] ]; + end + end + end + else + def.output.atlases = struct(); + def.output.ROI = 0; + end + job = cat_io_checkinopt(job,def); + end + % ROI atlas maps + if isfield(job.output,'sROImenu') % expert/developer GUI that allows control each atlas map + if isfield(job.output.sROImenu,'satlases') + %% image output + satlases = rmfield(job.output.sROImenu.satlases,'ownatlas'); + def.output.satlases = satlases; + def.output.sROI = any(cell2mat(struct2cell(satlases))) || ~isempty( job.output.ROImenu.satlases.ownatlas ); + + if ~isempty( job.output.sROImenu.satlases.ownatlas ) && ~isempty( job.output.sROImenu.satlases.ownatlas{1} ) + for i=1:numel( job.output.sROImenu.satlases.ownatlas ) + [pp,ff,ee] = spm_fileparts( job.output.sROImenu.satlases.ownatlas{i} ); + if any(~cellfun('isempty',strfind( spm_str_manip( def.extopts.satlas(:,1) ,'cs') ,ff))) + error('cat_run:ownatlasname', ... + ['There is a surface atlas file name conflict. Each atlas name has to be unique. \n' ... + 'Please rename your own surface atlas map ""%s"". \n'],fullfile(pp,[ff ee]) ); + else + % add new atlas + def.output.satlases.(ff) = 1; + def.extopts.satlas = [ def.extopts.satlas; [ {ff} job.output.sROImenu.satlases.ownatlas(i) {def.extopts.expertgui} {0} ] ]; + end + end + end + else + def.output.atlases = struct(); + def.output.sROI = 0; + end + job = cat_io_checkinopt(job,def); + else + def.output.atlases = struct(); + def.output.sROI = 0; + job = cat_io_checkinopt(job,def); + end + + + if ~isfield(job.output,'atlases') + % default GUI that only allow to switch on the settings defined in the default file + if ~isfield(job.extopts,'atlas') + job.extopts.atlas = def.extopts.atlas; + end + + job.output.atlases = struct(); + if job.output.ROI + % if output, than use the parameter of the default file + job.output.atlases = cell2struct(job.extopts.atlas(:,4)',spm_str_manip(job.extopts.atlas(:,1),'tr')',2); + job.output.ROI = any(cell2mat(struct2cell(job.output.atlases))); + end + end + if ~isfield(job.output,'satlases') + % default GUI that only allow to switch on the settings defined in the default file + if ~isfield(job.extopts,'satlas') + job.extopts.satlas = def.extopts.satlas; + end + + job.output.satlases = struct(); + if job.output.sROI + % if output, than use the parameter of the default file + job.output.satlases = cell2struct(job.extopts.satlas(:,4)',spm_str_manip(job.extopts.satlas(:,1),'tr')',2); + job.output.sROI = any(cell2mat(struct2cell(job.output.satlases))); + end + end + + if ~isfield(job.output,'atlases') + if ~isfield(job.extopts,'atlas') && job.output.surface + job.extopts.satlas = def.extopts.satlas; + end + end + + % simplyfied default user GUI input + if isfield(job.output,'labelnative') + job.output.label.native = job.output.labelnative; + job.output = rmfield(job.output,'labelnative'); + end + + % simplyfied default user GUI input + if isfield(job.output,'jacobianwarped') + job.output.jacobian.warped = job.output.jacobianwarped; + job.output = rmfield(job.output,'jacobianwarped'); + end + + %% ROI export + if any( [job.extopts.atlas{ contains(spm_file(job.extopts.atlas(:,1),'path',''),'hammers') , 4 }] ) && verbatlas + cat_io_cprintf('err',... + ['-------------------------------------------- \n' ... + 'Free academic end user license agreement for Hammers atlas! \n' ... + 'For using the Hammers atlas, please fill out license agreement at \n https://www.brain-development.org \n' ... + '-------------------------------------------- \n']); + end + if any( [job.extopts.atlas{ contains(spm_file(job.extopts.atlas(:,1),'path',''),'lpba40') , 4 }] ) && verbatlas + cat_io_cprintf('warn',... + ['-------------------------------------------- \n' ... + 'No commercial use of LPBA40 atlas! \n' ... + 'Permission is granted to use this atlas without charge for non-commercial research purposes only: \n https://www.loni.usc.edu/docs/atlases_methods/Human_Atlas_Methods.pdf \n' ... + '-------------------------------------------- \n']); + end + if any( [job.extopts.atlas{ contains(spm_file(job.extopts.atlas(:,1),'path',''),'suit') , 4 }] ) && verbatlas + cat_io_cprintf('warn',... + ['-------------------------------------------- \n' ... + 'No commercial use of SUIT cerebellar atlas! \n' ... + 'Creative Commons Attribution-NonCommercial 3.0 Unported License does not allow commercial use. \n' ... + '-------------------------------------------- \n']); + end + if any( [job.extopts.atlas{ contains(spm_file(job.extopts.satlas(:,1),'path',''),'julichbrain3') , 4 }] ) && verbatlas + cat_io_cprintf('warn',... + ['-------------------------------------------- \n' ... + 'No commercial use of Julich Brain atlas! \n' ... + 'Creative Commons Attribution Non Commercial Share Alike 4.0 International Licence does not allow commercial use. \n' ... + '-------------------------------------------- \n']); + end + + + job = cat_io_checkinopt(job,def); + if ~isfield(job.extopts,'restypes') + job.extopts.restypes.(def.extopts.restype) = job.extopts.resval; + end + + %% handling of SPM biasoptions for specific GUI entry + if isfield(job.opts,'bias') + if isfield(job.opts.bias,'spm') + job.opts.biasacc = 0; + job.opts.biasstr = 0; + job.opts.biasfwhm = job.opts.bias.spm.biasfwhm; + job.opts.biasreg = job.opts.bias.spm.biasreg; + elseif isfield(job.opts.bias,'biasstr') + job.opts.biasstr = job.opts.bias.biasstr; + end + job.opts = rmfield(job.opts,'bias'); + end + % the extopts.biasstr controls and overwrites (biasstr>0) the SPM biasreg and biasfwhm parameter + % biasstr = [0.01 0.25 0.50 0.75 1.00] ... result in ? + % biasreg = [0.01 0.0032 0.0010 0.0003 0.0001] ? and ? + % biasfwhm = [30 45 60 75 90] for ""30 + 60*biasstr? + % biasfwhm = [30.32 42.65 60 84.39 118.71)] for ""10^(5/6 + biasstr/3)? .. allows lower fields + if isfield(job.opts,'biasacc') && job.opts.biasacc > 0 + job.opts.acc = job.opts.biasacc; + job.opts.biasstr = job.opts.biasacc; + job.opts.biasreg = min( 10 , max( 0 , 10^-(job.opts.biasstr*2 + 2) )); + job.opts.biasfwhm = min( inf , max( 30 , 30 + 60*(1-job.opts.biasstr) )); + elseif job.opts.biasstr > 0 % update biasreg and biasfwhm only if biasreg>0 + % limits only describe the SPM standard range + job.opts.biasacc = 0; + job.opts.biasreg = min( 10 , max( 0 , 10^-(job.opts.biasstr*2 + 2) )); + job.opts.biasfwhm = min( inf , max( 30 , 30 + 60*(1-job.opts.biasstr) )); + end + + + % SPM preprocessing accuracy + if ~isfield(job.opts,'tol') + job.opts.tol = cat_get_defaults('opts.tol'); + end + job.opts.tol = min(1e-4,max(1e-16, job.opts.tol)); + + %% handling of SPM accuracy options for specific GUI entry + % Although lower resolution (>3 mm) is not really faster and maybe much + % worse in sense of quality, it is simpler to have a linear decline + % rather than describing the other case. + % RD20200130: Takes me a day to figure out that the SPM7771 US failed in + % T1_dargonchow but also single_subjT1 by lower sampl res: + % sampval = [3 2.5 2 1.5 1]; + % Keep in mind that this effects volume resolution (^3), eg + % [32 16 8 4 2] .^(1/3) is close to these values. + % RD20200301: However, this setting is really slow and did not solve all + % problems, so we go back to previous settings. + % sampval = [5 4 3 2 1]; % that describes volume of + % [125 64 27 8 1] that is also describes the changes in + % processing time roughly + % RD20200619: The tol parameter is more important than the resolution to + % correct strong local inhomogeneities. So I make this even + % a bit more agressive and the strongest option will take + % hours. This is also more relevant for low contrast data + % with strange contrast. + sampval = [5 4 3 2 1]; + tolval = [1e-1 1e-2 1e-4 1e-8 1e-16]; + if isfield(job.opts,'accstr') && ~isfield(job.opts,'acc') + job.opts.samp = sampval( round(job.opts.accstr*4 + 1) ); + job.opts.tol = tolval( round(job.opts.accstr*4 + 1) ); + elseif isfield(job.opts,'acc') % developer settings + if isfield(job.opts.acc,'accstr') + job.opts.accstr = job.opts.acc.accstr; + job.opts.samp = sampval( round(job.opts.acc.accstr*4 + 1)); + job.opts.tol = tolval( round(job.opts.acc.accstr*4 + 1)); + elseif isfield(job.opts.acc,'spm') + job.opts.accstr = -1; + job.opts.samp = job.opts.acc.spm.samp; + job.opts.tol = job.opts.acc.spm.tol; + end + job.opts = rmfield(job.opts,'acc'); + end + clear sampval tolval; + + + % RD20211224: Strong bias correction in case of long TPMs and long BC. + % In case of individual TPMs we should force strong correction. Although + % it further adapation of by another bias correction parameter would be + % possible, I think that simple fixed values are the better solution. + % >> seems not be realy important and could be tested in the next release + if isfield(job,'useprior') && ~isempty(job.useprior) && job.extopts.new_release + cat_io_cprintf('blue','Addapt bias correction for longitudinal TPM!\n'); + job.opts.biasacc = 1; + job.opts.biasstr = 1; + job.opts.biasreg = 1e-04; + job.opts.biasfwhm = 30; + %{ + % RD20220103: Further optimisation? > Slow and no clear improvement + % in single test cases (ADNI 0559 with 1.5 and 3.0T scans) + job.opts = rmfield(job.opts,'acc'); + job.opts.accstr = -1; + job.opts.samp = 1.5; + job.opts.tol = 1e-8; % 0.75 + %} + end + + + if strcmpi(spm_check_version,'octave') && job.extopts.regstr > 0 + warning('cat_run:noShooting','No Shooting registration possible under Octave yet. Switch to Dartel registration.') + job.extopts.regstr = 0; + if isfield(job.extopts,'regmethod') + job.extopts.regmethod = rmfield(job.extopts.regmethod,'shooting'); + else + job.extopts = rmfield(job.extopts,'shooting'); + end + job.extopts.dartel.darteltpm = cat_get_defaults('extopts.darteltpm'); + end + + + %% set Dartel/Shooting templates + if isfield(job.extopts,'regmethod') + if isfield(job.extopts.regmethod,'dartel') + job.extopts.darteltpm = job.extopts.regmethod.dartel.darteltpm; + job.extopts.regstr = 0; + elseif isfield(job.extopts.regmethod,'shooting') + job.extopts.shootingtpm = job.extopts.regmethod.shooting.shootingtpm; + job.extopts.regstr = job.extopts.regmethod.shooting.regstr; + end + else + if isfield(job.extopts,'dartel') + job.extopts.darteltpm = job.extopts.dartel.darteltpm; + job.extopts.regstr = 0; + elseif isfield(job.extopts,'shooting') + job.extopts.shootingtpm = job.extopts.shooting.shootingtpm; + job.extopts.regstr = job.extopts.shooting.regstr; + end + end + + % find and check the Dartel templates + if isempty( job.extopts.darteltpm{1} ) + % use TPM + [tpp,tff,tee] = spm_fileparts(job.opts.tpm{1}); + job.extopts.darteltpms{1} = fullfile(tpp,[tff,tee]); + job.extopts.darteltpms = repmat( job.extopts.darteltpms(1), 6,1 ); + else + [tpp,tff,tee] = spm_fileparts(job.extopts.darteltpm{1}); + job.extopts.darteltpm{1} = fullfile(tpp,[tff,tee]); + numpos = min(strfind(tff,'Template_1')) + 8; + if isempty(numpos) + error('CAT:cat_main:TemplateNameError', ... + ['Could not find the string ""Template_1"" in Dartel template that \n'... + 'indicates the first file of the Dartel template. \n' ... + 'The given filename is ""%s.%s"" \n'],tff,tee); + end + job.extopts.darteltpms = cat_vol_findfiles(tpp,[tff(1:numpos) '*' tff(numpos+2:end) tee],struct('depth',1)); + + % if we also have found Template_0 we have to remove it from the list + if numel(job.extopts.darteltpms)==7 + if ~isempty(strfind(job.extopts.darteltpms{1},'Template_0')) + for i=1:6, job.extopts.darteltpms{i} = job.extopts.darteltpms{i+1}; end + job.extopts.darteltpms(7) = []; + end + end + end + + job.extopts.darteltpms(cellfun('length',job.extopts.darteltpms)~=length(job.extopts.darteltpm{1}))=[]; % remove to short/long files + if numel(job.extopts.darteltpms)~=6 && any(job.extopts.regstr==0) + %% + files = ''; for di=1:numel(job.extopts.darteltpms), files=sprintf('%s\n %s',files,job.extopts.darteltpms{di}); end + error('CAT:cat_main:TemplateFileError', ... + ['Could not find the expected 6 Dartel template files (Template_1 to Template_6). \n' ... + 'Found %d templates: %s'],numel(job.extopts.darteltpms),files); + end + + % find and check the Shooting templates + if isempty( job.extopts.shootingtpm{1} ) + % use TPM + [tpp,tff,tee] = spm_fileparts(job.opts.tpm{1}); + job.extopts.shootingtpms{1} = fullfile(tpp,[tff,tee]); + job.extopts.shootingtpms = repmat( job.extopts.shootingtpms(1), 5,1 ); + else + [tpp,tff,tee] = spm_fileparts(job.extopts.shootingtpm{1}); + job.extopts.shootingtpm{1} = fullfile(tpp,[tff,tee]); + numpos = min(strfind(tff,'Template_0')) + 8; + if isempty(numpos) + error('CAT:cat_main:TemplateNameError', ... + ['Could not find the string ""Template_0"" in Shooting template that \n'... + 'indicates the first file of the Shooting template. \n' ... + 'The given filename is ""%s.%s"" \n'],tff,tee); + end + job.extopts.shootingtpms = cat_vol_findfiles(tpp,[tff(1:numpos) '*' tff(numpos+2:end) tee],struct('depth',1)); + job.extopts.shootingtpms(cellfun('length',job.extopts.shootingtpms)~=length(job.extopts.shootingtpm{1}))=[]; % remove to short/long files + if numel(job.extopts.shootingtpms)~=5 && any(job.extopts.regstr>0) + %% + files = ''; for di=1:numel(job.extopts.shootingtpms), files=sprintf('%s\n %s',files,job.extopts.shootingtpms{di}); end + error('CAT:cat_main:TemplateFileError', ... + ['Could not find the expected 5 Shooting template files (Template_0 to Template_4).\n' ... + 'Found %d templates: %s'],numel(job.extopts.shootingtpms),files); + end + end + + + % check range of str variables + FN = {'WMHCstr','LASstr','BVCstr','gcutstr','cleanupstr','mrf'}; + for fni=1:numel(FN) + if ~isfield(job.extopts,FN{fni}) + job.extopts.(FN{fni}) = max(0,min(1,job.extopts.(FN{fni}))); + end + end + + if job.extopts.WMHC<3 && any(cell2mat(struct2cell(job.output.WMH))) + error('cat_run:bad_WMHC_parameter','Cannot ouput WMH maps if WMHC<3!') + end + if job.extopts.SLC<1 && any(cell2mat(struct2cell(job.output.SL))) + error('cat_run:bad_SLC_parameter','Cannot ouput stroke lesion maps if SLC is inactive!') + end + + + % deselect ROI output and print warning if ROI output is true and dartel template was changed + [pth,nam] = spm_fileparts(job.extopts.darteltpm{1}); + if isempty(strfind(nam,'_GS')) && isempty(strfind(nam,'_Dartel')) && isempty(strfind(nam,'IXI555')) && ... + strcmp(job.extopts.species,'human') && cat_get_defaults('output.ROI') && ~isfield(job.extopts,'spmAMAP') + warning('DARTEL:template:change',... + ['Dartel template was changed: Please be aware that ROI analysis \n' ... + 'and other template-specific options cannot be used and ROI \n ' ... + 'output has been deselected.']); + job.output.ROI = 0; + end + + + % set boundary box by Template properties + if ~isfield(job.extopts,'bb'), job.extopts.bb = 12; end + + job.extopts.vox( isinf(job.extopts.vox) | isnan(job.extopts.vox) ) = []; + if isempty( job.extopts.vox ), job.extopts.vox = cat_get_defaults('extopts.vox'); end + job.extopts.vox = abs( job.extopts.vox ); + + % prepare tissue priors and number of gaussians for all 6 classes + [pth,nam,ext] = spm_fileparts(job.opts.tpm{1}); + clsn = min(6,numel(spm_vol(fullfile(pth,[nam ext])))); + tissue = struct(); + for i=1:clsn + tissue(i).ngaus = job.opts.ngaus(i); + tissue(i).tpm = [fullfile(pth,[nam ext]) ',' num2str(i)]; + end + + tissue(1).warped = [job.output.GM.warped (job.output.GM.mod==1) (job.output.GM.mod==2) ]; + tissue(1).native = [job.output.GM.native (job.output.GM.dartel==1) (job.output.GM.dartel==2) ]; + tissue(2).warped = [job.output.WM.warped (job.output.WM.mod==1) (job.output.WM.mod==2) ]; + tissue(2).native = [job.output.WM.native (job.output.WM.dartel==1) (job.output.WM.dartel==2) ]; + tissue(3).warped = [job.output.CSF.warped (job.output.CSF.mod==1) (job.output.CSF.mod==2) ]; + tissue(3).native = [job.output.CSF.native (job.output.CSF.dartel==1) (job.output.CSF.dartel==2) ]; + + % never write class 4-6 + if isfield(job.output,'TPMC') + for i=4:6 + tissue(i).warped = [job.output.TPMC.warped (job.output.TPMC.mod==1) (job.output.TPMC.mod==2) ]; + tissue(i).native = [job.output.TPMC.native (job.output.TPMC.dartel==1) (job.output.TPMC.dartel==2) ]; + end + end + + job.channel = struct('vols',{job.data}); + job.tissue = tissue; + +return; + +%_______________________________________________________________________ +function vout = run_job(job) + + % load tpm priors + tpm = char(cat(1,job.tissue(:).tpm)); + tpm = spm_load_priors8(tpm); + + for subj=1:numel(job.channel(1).vols) + % __________________________________________________________________ + % Error management with try-catch blocks + % See also cat_run_newcatch. + % __________________________________________________________________ + [pth,nam,ext] = spm_fileparts(job.channel(1).vols{subj}); + + % uncompress nii.gz files and change file name for job + if strcmp(ext,'.gz') + try + fname = gunzip(job.channel(1).vols{subj}); + catch + % in case of datalad the alias exist without the file itself + cat_io_cprintf('err','Cannot gunzip ""%s"" file. \nMaybe the alias (e.g. for Datalad) exist but not the file it is refering to? \n',job.channel(1).vols{subj}); + continue + end + + job.channel(1).vols{subj} = char(fname); + fprintf('Uncompress %s\n',job.channel(1).vols{subj}); + cat_run_newcatch(job,tpm,subj); + spm_unlink(char(fname)); + else + cat_run_newcatch(job,tpm,subj); + end + + end + + % use an extended colormap that also include + % ###################################################################### + % RD202007: In case of multiple subjects ... + % It should work to use additional colors, but it would also + % be possible to clear the figure and load the CAT help. + % Another solution would be to run checkreg as conclusion or + % to create a final report that may only use some of the + % checkreg results (better). + % It should include (i) the main parameter (cat_main_reportstr), + % (2) a table with the number of successful and failed cases, + % (3) the number of problematic cases (> checkreg) and maybe + % (4) also include a average volume with variance overlay and + % surface with thickness variance. + % Such a report should be saved at the same place as the major + % log files. + % ###################################################################### + surfcolors = 128; + cmap(1:60,:) = gray(60); cmap(61:120,:) = flipud(pink(60)); cmap(121:120+surfcolors,:) = jet(surfcolors); + colormap(cmap) + + if isfield(job,'nproc') && job.nproc>0 + fprintf('\n%s',repmat('_',1,72)); + fprintf('\nCAT12 Segmentation job finished.\n'); + end + + vout = vout_job(job); + +return +%_______________________________________________________________________ + +function vout = vout_job(job) +% ---------------------------------------------------------------------- +% create output structure for SPM batch mode +% ---------------------------------------------------------------------- + +n = numel(job.channel(1).vols); + +parts = cell(n,4); % fileparts + +biascorr = {}; +wbiascorr = {}; +ibiascorr = {}; +wibiascorr = {}; +ribiascorr = {}; +aibiascorr = {}; +label = {}; +wlabel = {}; +rlabel = {}; +alabel = {}; +catreportjpg= {}; +catreportpdf= {}; +catlog = {}; +catxml = {}; +jacobian = {}; + +mrifolder = cell(n,1); +reportfolder = cell(n,1); +surffolder = cell(n,1); +labelfolder = cell(n,1); +for j=1:n + [parts{j,:}] = spm_fileparts(job.channel(1).vols{j}); + [mrifolder{j}, reportfolder{j}, surffolder{j}, labelfolder{j}] = cat_io_subfolders(job.channel(1).vols{j},job); + + % .gz correction + if strcmp(parts{j,3},'.gz') + parts{j,3} = parts{j,2}(end-3:end); % replace .gz by file type + parts{j,2}(end-3:end) = []; % remove file type from filename + end +end + +% test for SPM segmentation input and remove c1 file +sparts = parts; +for j=1:n + if isfield(job.extopts,'spmAMAP') && strcmp( parts{j,2}(1:2) , 'c1') + sparts{j,2}(1:2) = []; + end +end + +% CAT report XML file +% ---------------------------------------------------------------------- +catroi = cell(0,1); +for j=1:n + catxml{j,1} = fullfile(parts{j,1},reportfolder{j},['cat_',parts{j,2},'.xml']); + catlog{j,1} = fullfile(parts{j,1},reportfolder{j},['catlog_',parts{j,2},'.txt']); + catreportpdf{j,1} = fullfile(parts{j,1},reportfolder{j},['catreport_',parts{j,2},'.pdf']); + catreportjpg{j,1} = fullfile(parts{j,1},reportfolder{j},['catreportj_',parts{j,2},'.jpg']); +end + + +% lh/rh/cb central/white/pial/layer4 surface and thickness +% --------------------------------------------------------------------- +surfaceoutput = { % surface texture + {'central','sphere','sphere.reg'} % no measures - just surfaces + {} % default + {} % expert + {'pial','white'} % developer +}; +if any( job.output.surface == [ 5 6 ] ) %&& cat_get_defaults('extopts.expertgui')<2 % no sphere's without registration + for i = 1:3 + surfaceoutput{i} = setdiff(surfaceoutput{i},{'central','sphere','sphere.reg'}); + end +end +measureoutput = { + {'thickness','pbt'} % default + {} % no measures + {} % expert + {'depthWM','depthCSF'} % developer +}; +if any( job.output.surface == [ 5 6 ] ) %&& cat_get_defaults('extopts.expertgui')<2 + measureoutput{1} = setdiff(measureoutput{1},{'thickness','pbt'}); +end +% no output of intlayer4 or defects in cat_surf_createCS but in cat_surf_createCS2 (but not with fast) +if isfield(job,'extopts') && isfield(job.extopts,'surface') && ... + isfield(job.extopts.surface,'collcorr') && job.extopts.surface.collcorr>19 + + surfaceoutput{1} = [surfaceoutput{1},{'pial','white'}]; + surfaceoutput{4} = {}; + if any( job.output.surface ~= [ 5 6 ] ) % fast pipeline + surfaceoutput{3} = {'layer4'}; + measureoutput{3} = {'intlayer4','defects'}; + end +end + +sides = {'lh','rh'}; +if any( job.output.surface == [ 2 6 8 ] ) + sides = [sides {'cb'}]; +end +voutsfields = {}; + +def.output.surf_measures = 1; +def.extopts.expertgui = 0; +job = cat_io_checkinopt(job,def); +% create fields +for si = 1:numel(sides) + % surfaces + for soi = 1:numel(surfaceoutput) + if soi < job.extopts.expertgui + 2 + for soii = 1:numel(surfaceoutput{soi}) + % remove dots in name (e.g. for sphere.reg) + surfaceoutput_str = strrep(surfaceoutput{soi}{soii},'.',''); + eval( sprintf('%s%s = {};' , sides{si} , surfaceoutput_str ) ); + if ~isempty( surfaceoutput{soi} ) && job.output.surface + eval( sprintf('%s%s = cell(n,1);' , sides{si} , surfaceoutput_str ) ); + for j = 1:n + eval( sprintf('%s%s{j} = fullfile( parts{j,1} , surffolder{j} , ''%s.%s.%s.gii'' ); ' , ... + sides{si} , surfaceoutput_str , ... + sides{si} , surfaceoutput{soi}{soii} , sparts{j,2} ) ); + voutsfields{end+1} = sprintf('%s%s', sides{si} , surfaceoutput_str ); + end + end + end + end + end + % measures + for soi = 1:numel(measureoutput) + if soi < job.extopts.expertgui + 2 + for soii = 1:numel(measureoutput{soi}) + eval( sprintf('%s%s = {};' , sides{si} , measureoutput{soi}{soii} ) ); + if ~isempty( measureoutput{soi} ) && job.output.surface + eval( sprintf('%s%s = cell(n,1);' , sides{si} , measureoutput{soi}{soii} ) ); + for j = 1:n + eval( sprintf('%s%s{j} = fullfile( parts{j,1} , surffolder{j} , ''%s.%s.%s'' ); ' , ... + sides{si} , measureoutput{soi}{soii} , ... + sides{si} , measureoutput{soi}{soii} , sparts{j,2} ) ); + voutsfields{end+1} = sprintf('%s%s', sides{si} , measureoutput{soi}{soii} ); + end + end + end + end + end +end + + +% XML label +% ---------------------------------------------------------------------- +if job.output.ROI %&& isfield(job.opts,'ROImenu') && isfield(job.opts.ROImenu,'atlases') + if isfield(job.output.ROImenu.atlases,'ownatlas'), atlases = rmfield(job.output.ROImenu.atlases,'ownatlas'); end + is_ROI = any(cell2mat(struct2cell(atlases))) || ... + (~isempty( job.output.ROImenu.atlases.ownatlas ) & ~isempty( job.output.ROImenu.atlases.ownatlas{1} )); + + catroi = cell(n,1); + if is_ROI + for j=1:n + catroi{j,1} = fullfile(parts{j,1},labelfolder{j},['catROI_',parts{j,2},'.xml']); + end + end +end + +% bias +% ---------------------------------------------------------------------- +if job.output.bias.native + biascorr = cell(n,1); + for j=1:n + biascorr{j} = fullfile(parts{j,1},mrifolder{j},['m',parts{j,2},'.nii']); + end +end + +if job.output.bias.warped + wbiascorr = cell(n,1); + for j=1:n + wbiascorr{j} = fullfile(parts{j,1},mrifolder{j},['wm',parts{j,2},'.nii']); + end +end + +if job.output.bias.dartel==1 + rbiascorr = cell(n,1); + for j=1:n + rbiascorr{j} = fullfile(parts{j,1},mrifolder{j},['rm',parts{j,2},'_rigid.nii']); + end +end + +if job.output.bias.dartel==2 + abiascorr = cell(n,1); + for j=1:n + abiascorr{j} = fullfile(parts{j,1},mrifolder{j},['rm',parts{j,2},'_affine.nii']); + end +end + +% intensity corrected bias +% ---------------------------------------------------------------------- +if job.output.las.native + ibiascorr = cell(n,1); + for j=1:n + ibiascorr{j} = fullfile(parts{j,1},mrifolder{j},['mi',parts{j,2},'.nii']); + end +end + +if job.output.las.warped + wibiascorr = cell(n,1); + for j=1:n + wibiascorr{j} = fullfile(parts{j,1},mrifolder{j},['wmi',parts{j,2},'.nii']); + end +end + +if job.output.las.dartel==1 + ribiascorr = cell(n,1); + for j=1:n + ribiascorr{j} = fullfile(parts{j,1},mrifolder{j},['rmi',parts{j,2},'_rigid.nii']); + end +end + +if job.output.las.dartel==2 + aibiascorr = cell(n,1); + for j=1:n + aibiascorr{j} = fullfile(parts{j,1},mrifolder{j},['rmi',parts{j,2},'_affine.nii']); + end +end + + +% label +% ---------------------------------------------------------------------- +if job.output.label.native + label = cell(n,1); + for j=1:n + label{j} = fullfile(parts{j,1},mrifolder{j},['p0',parts{j,2},'.nii']); + end +end + +if job.output.label.warped + wlabel = cell(n,1); + for j=1:n + wlabel{j} = fullfile(parts{j,1},mrifolder{j},['wp0',parts{j,2},'.nii']); + end +end + +if job.output.label.dartel==1 + rlabel = cell(n,1); + for j=1:n + rlabel{j} = fullfile(parts{j,1},mrifolder{j},['rp0',parts{j,2},'_rigid.nii']); + end +end + +if job.output.label.dartel==2 + alabel = cell(n,1); + for j=1:n + alabel{j} = fullfile(parts{j,1},mrifolder{j},['rp0',parts{j,2},'_affine.nii']); + end +end + + +% tissues +% ---------------------------------------------------------------------- +tiss = struct('p',{},'rp',{},'rpa',{},'wp',{},'mwp',{},'m0wp',{}); +for i=1:numel(job.tissue) + if job.tissue(i).native(1) + tiss(i).p = cell(n,1); + for j=1:n + tiss(i).p{j} = fullfile(parts{j,1},mrifolder{j},['p',num2str(i),parts{j,2},'.nii']); + end + end + if job.tissue(i).native(2) + tiss(i).rp = cell(n,1); + for j=1:n + tiss(i).rp{j} = fullfile(parts{j,1},mrifolder{j},['rp',num2str(i),parts{j,2},'_rigid.nii']); + end + end + if job.tissue(i).native(3) + tiss(i).rpa = cell(n,1); + for j=1:n + tiss(i).rpa{j} = fullfile(parts{j,1},mrifolder{j},['rp',num2str(i),parts{j,2},'_affine.nii']); + end + end + if job.tissue(i).warped(1) + tiss(i).wp = cell(n,1); + for j=1:n + tiss(i).wp{j} = fullfile(parts{j,1},mrifolder{j},['wp',num2str(i),parts{j,2},'.nii']); + end + end + if job.tissue(i).warped(2) + tiss(i).mwp = cell(n,1); + for j=1:n + tiss(i).mwp{j} = fullfile(parts{j,1},mrifolder{j},['mwp',num2str(i),parts{j,2},'.nii']); + end + end + if job.tissue(i).warped(3) + tiss(i).m0wp = cell(n,1); + for j=1:n + tiss(i).m0wp{j} = fullfile(parts{j,1},mrifolder{j},['m0wp',num2str(i),parts{j,2},'.nii']); + end + end +end + + +% deformation fields +% ---------------------------------------------------------------------- +if job.output.warps(1) + fordef = cell(n,1); + for j=1:n + fordef{j} = fullfile(parts{j,1},mrifolder{j},['y_',parts{j,2},'.nii']); + end +else + fordef = {}; +end + +if job.output.warps(2) + invdef = cell(n,1); + for j=1:n + invdef{j} = fullfile(parts{j,1},mrifolder{j},['iy_',parts{j,2},'.nii']); + end +else + invdef = {}; +end + + +% jacobian +% ---------------------------------------------------------------------- +if job.output.jacobian.warped + jacobian = cell(n,1); + for j=1:n + jacobian{j} = fullfile(parts{j,1},mrifolder{j},['wj_',parts{j,2},'.nii']); + end +end + +% affine/ridid tranformation matrices +% ---------------------------------------------------------------------- +if job.output.rmat + ta = {fullfile(parts{j,1},mrifolder{j},['t_' ,parts{j,2},'_affine_reorient.mat'])}; + ita = {fullfile(parts{j,1},mrifolder{j},['it_',parts{j,2},'_affine_reorient.mat'])}; + tr = {fullfile(parts{j,1},mrifolder{j},['t_' ,parts{j,2},'_rigid_reorient.mat'])}; + itr = {fullfile(parts{j,1},mrifolder{j},['it_',parts{j,2},'_rigid_reorient.mat'])}; +else + ta = {}; + ita = {}; + tr = {}; + itr = {}; +end + + +% ---------------------------------------------------------------------- +vout = struct('tiss',tiss,'label',{label},'wlabel',{wlabel},'rlabel',{rlabel},'alabel',{alabel},... + 'biascorr',{biascorr},'wbiascorr',{wbiascorr},'catroi',{catroi},'ibiascorr',{ibiascorr},... + 'wibiascorr',{wibiascorr},'ribiascorr',{ribiascorr},'aibiascorr',{aibiascorr},... + 'invdef',{invdef},'fordef',{fordef},'jacobian',{jacobian},'catxml',{catxml},... + 'catlog',{catlog},'catreportpdf',{catreportpdf},'catreportjpg',{catreportjpg},... + 'ta',{ta},'ita',{ita},'tr',{tr},'itr',{itr}); + +% add surface fields +for fi=1:numel(voutsfields) + eval( sprintf( 'vout.(voutsfields{fi}) = %s;', voutsfields{fi} ) ); +end + +%_______________________________________________________________________ +return + +%======================================================================= +function [data,err] = remove_already_processed(job,verb) + if ~exist('verb','var'), verb=0; end + remove = []; err = zeros(size(job)); + cat_io_cprintf('warn','Lazy processing: \n'); + for subj = 1:numel(job.data) + [lazy,err(subj)] = checklazy(job,subj,verb); + if lazy + remove = [remove subj]; + end + end + cat_io_cprintf('warn',' Skip %d subjects!\n',numel(remove)); + data = job.data(setxor(1:numel(job.data),remove)); + cat_io_cprintf([0 0.4 0.6],'\n\nProcess:\n'); + for subj = 1:numel(data) + cat_io_cprintf([0 0.4 0.6],sprintf(' Code%3d: ""%s""\n',err(subj),data{subj})); + end + cat_io_cprintf('warn',sprintf(' Process %d subjects!\n',numel(data))); +return + +%======================================================================= +function [lazy,FNok] = checklazy(job,subj,verb) %#ok + [mrifolder, reportfolder, surffolder, labelfolder] = cat_io_subfolders(job.data{subj},job); + + lazy = 0; + + [pp,ff] = spm_fileparts(job.data{subj}); + if strcmp(ff(end-3:end),'.nii'), ff(end-3:end) = []; end % .gz case + catxml = fullfile(pp,reportfolder,['cat_' ff '.xml']); + + FNok = 0; + if exist(catxml,'file') + + xml = cat_io_xml(catxml); + + FNopts = fieldnames(job.opts); + FNextopts = fieldnames(job.extopts); + FNok = 1; + FNextopts = setxor(FNextopts,{'LAB','lazy','mrf','NCstr','resval','ignoreErrors'}); + if job.extopts.lazy > 0 % ingnore paths that can change when copied + FNopts = setxor(FNopts,{'tpm'}); + FNextopts = setxor(FNextopts,{'brainmask','T1','cat12atlas','darteltpm','darteltpms','shootingtpm','shootingtpms','atlas','satlas'}); + end + + %% check opts + if job.extopts.lazy < 2 % check parameter only if lazy=1 to avoid parameter checks e.g. due to version changes + if isempty(FNopts) || isempty(FNextopts) || ... + ~isfield(xml.parameter,'opts') || ~isfield(xml.parameter,'extopts') + return + end + for fni=1:numel(FNopts) + if ~isfield(xml.parameter.opts,FNopts{fni}) + FNok = 2; break + end + if ischar(xml.parameter.opts.(FNopts{fni})) + if ischar(job.opts.(FNopts{fni})) + if ~strcmp(xml.parameter.opts.(FNopts{fni}),job.opts.(FNopts{fni})) + FNok = 3; break + end + else + if ~strcmp(xml.parameter.opts.(FNopts{fni}),job.opts.(FNopts{fni}){1}) + FNok = 4; break + end + end + else + if isnumeric(job.opts.(FNopts{fni})) + if strcmp(FNopts{fni},'ngaus') && numel(xml.parameter.opts.(FNopts{fni}))==4 + % nothing to do (skull-stripped case) + else + try + if xml.parameter.opts.(FNopts{fni}) ~= job.opts.(FNopts{fni}) + FNok = 5; break + end + catch + FNok = 5; break + end + end + elseif ischar(job.opts.(FNopts{fni})) + if ~strcmp(xml.parameter.opts.(FNopts{fni}),job.opts.(FNopts{fni})) + FNok = 5; break + end + end + end + end + if FNok~=1 % different opts + return + end + + %% check extopts + for fni=1:numel(FNextopts) + if ~isfield(xml.parameter.extopts,FNextopts{fni}) + FNok = 6; break + end + if ischar(xml.parameter.extopts.(FNextopts{fni})) + if ischar(job.extopts.(FNextopts{fni})) + if ~strcmp(xml.parameter.extopts.(FNextopts{fni}),job.extopts.(FNextopts{fni})) + FNok = 7; break + end + else + if ~strcmp(xml.parameter.extopts.(FNextopts{fni}),job.extopts.(FNextopts{fni}){1}) + FNok = 8; break + end + end + elseif iscell(xml.parameter.extopts.(FNextopts{fni})) + if numel(xml.parameter.extopts.(FNextopts{fni}))~=numel(job.extopts.(FNextopts{fni})) + FNok = 9; break + end + for fnic = 1:numel(xml.parameter.extopts.(FNextopts{fni})) + if iscell(xml.parameter.extopts.(FNextopts{fni}){fnic}) + for fnicc = 1:numel(xml.parameter.extopts.(FNextopts{fni}){fnic}) + if xml.parameter.extopts.(FNextopts{fni}){fnic}{fnicc} ~= job.extopts.(FNextopts{fni}){fnic}{fnicc} + FNok = 10; break + end + end + if FNok==10; break; end + else + try + if any(xml.parameter.extopts.(FNextopts{fni}){fnic} ~= job.extopts.(FNextopts{fni}){fnic}) + FNok = 11; break + end + catch + FNok = 11; + end + if FNok==11; break; end + end + if FNok==11 || FNok==10; break; end + end + elseif isstruct(xml.parameter.extopts.(FNextopts{fni})) + FNX = fieldnames(xml.parameter.extopts.(FNextopts{fni})); + for fnic = 1:numel(FNX) + if any(xml.parameter.extopts.(FNextopts{fni}).(FNX{fnic}) ~= job.extopts.(FNextopts{fni}).(FNX{fnic})) + FNok = 12; break + end + if FNok==12; break; end + end + else + % this did not work anymore due to the GUI subfields :/ + %if any(xml.parameter.extopts.(FNextopts{fni}) ~= job.extopts.(FNextopts{fni})) + % FNok = 13; break + %end + end + end + if FNok~=1 % different extopts + return + end + end + + + % check output + + % surface + if job.output.surface && exist(fullfile(pp,surffolder),'dir') + Pcentral = cat_vol_findfiles(fullfile(pp,surffolder),['*h.central.' ff '.gii']); + if isscalar(Pcentral) + return + end + end + + % rois + if job.output.ROI && isfield(opts,'ROImenu') && isfield(opts.ROImenu,'atlases') + if isfield(job.output.ROImenu.atlases,'ownatlas'), atlases = rmfield(job.output.ROImenu.atlases,'ownatlas'); end + is_ROI = any(cell2mat(struct2cell(atlases))) || ... + (~isempty( job.output.ROImenu.atlases.ownatlas ) & ~isempty( job.output.ROImenu.atlases.ownatlas{1} )); + + if is_ROI && ~exist(fullfile(pp,labelfolder,['catROI_' ff '.xml']),'file') + return + end + end + + %% volumes + FNO = fieldnames(job.vout); + FNO = setdiff(FNO,{'catlog'}); % RD202207: wrong directory in case of BIDS need to fix this later + for fnoi = 1:numel(FNO) + if isempty(job.vout.(FNO{fnoi})) + continue + elseif iscell(job.vout.(FNO{fnoi})) + try + if ~isempty(job.vout.(FNO{fnoi}){subj}) && ~exist(job.vout.(FNO{fnoi}){subj},'file') + FNok = 14; break + end + end + elseif isstruct(job.vout.(FNO{fnoi})) + for si = numel(job.vout.(FNO{fnoi})) + FNOS = fieldnames(job.vout.(FNO{fnoi})); + for fnosi = 1:numel(FNOS) + if isempty([job.vout.(FNO{fnoi})(si).(FNOS{fnosi})]) + continue + elseif ~exist(job.vout.(FNO{fnoi})(si).(FNOS{fnosi}){subj},'file') + FNok = 14; break + end + end + end + end + if FNok==14 % miss volumes + return + end + end + %% + + lazy = FNok==1; + + end + + if lazy + cat_io_cprintf('warn',' ""%s"" \n',job.data{subj}); + end +return","MATLAB" +"Neurology","ChristianGaser/cat12","cat_vol_set_com.m",".m","2026","74","function Affine = cat_vol_set_com(V) +% use center-of-mass (COM) to roughly correct for differences in the +% position between image and template +% ______________________________________________________________________ +% FORMAT: Affine = cat_vol_set_com(varargin) +% +% V - mapped images or filenames +% Affine - affine transformation to roughly correct origin +% +% Only if no input is defined the function is called interactively and the +% estimated transformation is applied to the images. Otherwise, only the +% Affine parameter is returned. +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + +if nargin == 1 + if isstruct(V) + V = V; + else + P = char(V); + V = spm_vol(P); + end +else + P = spm_select(Inf,'image','Select images to filter'); + V = spm_vol(P); +end +n = numel(V); + +% pre-estimated COM of MNI template +com_reference = [0 -20 -15]; + +if nargin == 1 + % call from cat_run_job that will add the time and then the line break + fprintf('Correct center-of-mass '); +else + fprintf('Correct center-of-mass \n'); +end +for i=1:n + Affine = eye(4); + if isfield(V(i),'dat') + vol(:,:,:) = V(i).dat(:,:,:); + else + vol = spm_read_vols(V(i)); + end + + % median should be more robust + avg = cat_stat_nanmedian(vol(:)); + avg = cat_stat_nanmedian(vol(vol(:)>=avg)); % = to support binary/mask data + + % don't use background values + [x,y,z] = ind2sub(size(vol),find(vol>avg)); + com = V(i).mat(1:3,:)*[mean(x) mean(y) mean(z) 1]'; + com = com'; + + M = spm_get_space(V(i).fname); + Affine(1:3,4) = (com - com_reference)'; + + if nargin < 1 + spm_get_space(V(i).fname,Affine\M); + fprintf('\n'); + end + + if ~nargout + clear Affine + end +end +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_main_reportcmd.m",".m","4381","109","function cat_main_reportcmd(job,res,qa) +% ______________________________________________________________________ +% +% Display report of CAT preprocessing in the command window and +% cleanup some figures. +% +% cat_main_reportcom(job,res,qa) +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + VT0 = res.image0(1); + [pth,nam] = spm_fileparts(VT0.fname); + + % command window output + QMC = cat_io_colormaps('marks+',17); + GMC = cat_io_colormaps('turbo',45); + GMC = GMC ./ repmat( max(1,sum(GMC,2)) , 1 , 3); % make bright values darker + color = @(QMC,m) QMC(max(1,min(size(QMC,1),isnan(m) + round(((m-1)*3)+1))),:); + colorgmt = @(GMC,m) GMC(max(1,min(size(GMC,1),isnan(m) + round(((m-0.5)*10)+1))),:); + mark2rps = @(mark) min(100,max(0,105 - mark*10)) + isnan(mark).*mark; + grades = {'A+','A','A-','B+','B','B-','C+','C','C-','D+','D','D-','E+','E','E-','F'}; + mark2grad = @(mark) grades{max(min(numel(grades),max(max(isnan(mark)*numel(grades),1),round((mark+2/3)*3-3))))}; + + % definition of subfolders + [mrifolder, reportfolder, surffolder, labelfolder] = cat_io_subfolders(VT0.fname,job); + + mrifolder = fullfile(pth,mrifolder); + [stat, val] = fileattrib(mrifolder); + if stat, mrifolder = val.Name; end + + reportfolder = fullfile(pth,reportfolder); + [stat, val] = fileattrib(reportfolder); + if stat, reportfolder = val.Name; end + + surffolder = fullfile(pth,surffolder); + [stat, val] = fileattrib(surffolder); + if stat, surffolder = val.Name; end + + labelfolder = fullfile(pth,labelfolder); + [stat, val] = fileattrib(labelfolder); + if stat, labelfolder = val.Name; end + + % output conclusion + fprintf('\n%s',repmat('-',1,72)); + fprintf(1,'\nCAT preprocessing takes %0.0f minute(s) and %0.0f second(s).\n', ... + floor(round(etime(clock,res.stime))/60),mod(round(etime(clock,res.stime)),60)); + + % image quality (just use real to avoid some rare problems with irrational values that should not occur anymore) + cat_io_cprintf(color(QMC,real(qa.qualityratings.SIQR)), sprintf('Structural Image Quality Rating (SIQR): %5.2f%%%% (%s)\n',... + mark2rps(real(qa.qualityratings.SIQR)),mark2grad(real(qa.qualityratings.SIQR)))); + + % processing quality + % coming soon + + % print GMV / GMT values (for developer in colors) + if job.extopts.expertgui > 0 + if job.extopts.expertgui > 1 && isfield(qa.subjectmeasures,'dist_thickness') + col = colorgmt(GMC,qa.subjectmeasures.dist_thickness{1}(1)); + elseif job.extopts.expertgui > 1 + col = colorgmt(GMC, qa.subjectmeasures.vol_rel_CGW(2) * 5 ); % simple translation to thickness + else + col = [0 0 0]; + end + cat_io_cprintf(col, sprintf('Relative gray matter volume (GMV/TIV): %5.2f%%%% (%5.2f / %5.2f ml)\n',... + qa.subjectmeasures.vol_rel_CGW(2)*100 , qa.subjectmeasures.vol_abs_CGW(2) , qa.subjectmeasures.vol_TIV )); + if isfield(qa.subjectmeasures,'dist_thickness') + cat_io_cprintf(col, sprintf('Gray matter thickness (GMT): %5.2f %s %4.2f mm\n',... + qa.subjectmeasures.dist_thickness{1}(1), native2unicode(177, 'latin1'), qa.subjectmeasures.dist_thickness{1}(2) ) ); + end + end + + + + %% print subfolders + if job.extopts.subfolders + fprintf('Segmentations are saved in %s\n',mrifolder); + fprintf('Reports are saved in %s\n',reportfolder); + if job.output.ROI + fprintf('Labels are saved in %s\n',labelfolder); + end + if job.output.surface && exist('Psurf','var') && ~isempty(Psurf) + fprintf('Surface measurements are saved in %s\n',surffolder); + end + end + + fprintf('%s\n\n',repmat('-',1,72)); + + % finish diary entry of ""../report/cmdln_*.txt"" + % read diary and add the command-line output to the *.xml and *.mat file + diary off; + try %#ok + fid =fopen(res.catlog); + txt = fread(fid,200000,'uint8=>char'); + fclose(fid); + txt2 = textscan(txt,'%s','Delimiter',''); + cat_io_xml(fullfile(reportfolder,['cat_' nam '.xml']),struct(... + 'catlog',txt2),'write+'); % here we have to use the write+! + end + + spm_progress_bar('Clear'); + cat_progress_bar('Clear'); + +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_run_job_APP_init1070.m",".m","11868","236","function [Ym,Yt,Ybg,WMth,bias] = cat_run_job_APP_init1070(Ysrco,vx_vol,verb) +% _____________________________________________________________________ +% The rough bias correction is a subfunction of cat_run_rob. +% +% All tissues (low gradient areas) should have a similar intensity. +% A strong smoothing of this approximation is essential to +% avoid anatomical filtering between WM and GM that can first +% be seen in overfitting of the subcortical structures. +% However, this filtering will overcorrect head tissue with +% a typical intensity around GM. +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + +% ds('l2','',0.5,Yo/WMth,Yg<0.2,Yo/WMth,Ym,80) + + rf = 10^9; + bfsmoothness = 3; + if verb, fprintf('\n'); end + + stime = cat_io_cmd(' Initialize','g5','',verb); + msize = 222; %round(222 ./ max(size(Ysrco).*vx_vol) .* min(size(Ysrco).*vx_vol)); + + [Ysrc,resT3] = cat_vol_resize(Ysrco,'reduceV',vx_vol,min(1.2,cat_stat_nanmean(vx_vol)*2),msize,'meanm'); + vx_vol = resT3.vx_volr; + + %% correction for negative backgrounds (MT weighting) + [Ym,BGth] = cat_stat_histth(Ysrc,99.99); BGth(2) = []; clear Ym; %#ok + + Ysrc = Ysrc - BGth; Ysrco = Ysrco - BGth; BGth2 = BGth; + Yg = cat_vol_grad(Ysrc,vx_vol) ./ max(eps,Ysrc); + Ygth = max(0.05,min(0.2,mean(Yg(Yg(:)>0))*0.75)); + + Ybg0 = cat_vol_smooth3X(Yg0.05; + Yw0 = Ygcat_stat_nanmean( Ysrc(Yg(:)0.3; % MT / MP2RAGE + if highBG + % In case of high intensity background we simply need the lowest + % intensity of the histogram without extrem outliers. + Ysrcr = cat_vol_resize(Ysrc,'reduceV',vx_vol,2,24,'meanm'); + [Ysrcr,th] = cat_stat_histth(Ysrcr,99.99); %#ok + BGth = th(1); + clear Ysrcr; + end + Ym = (Ysrc - BGth) ./ (WMth - BGth); + + Ydiv = cat_vol_div(Ym,vx_vol/2) ./ (Ym+eps); % lower resolution is 8 times faster + + + %% background + stime = cat_io_cmd(' Estimate background','g5','',verb,stime); + if highBG + % As far as our background have an intensity similar to the brain, we + % have to find the average intensity of the background create a mask. + Ymr = cat_vol_resize(Ysrc,'reduceV',vx_vol,3,32,'meanm'); + Ymsk = true(size(Ymr)); Ymsk(5:end-4,5:end-4,5:end-4) = false; + [HBGth,HBGsd] = cat_stat_kmeans(Ymr(Ymsk(:)),1); + HBGsd = max(diff([BGth,WMth])*0.1, HBGsd); clear Ymr + Ymsk = true(size(Ym)); Ymsk(5:end-4,5:end-4,5:end-4) = false; + Ybg = (Yg<0.3 & Ysrc>(HBGth - 2*HBGsd) & Ysrc<(HBGth + 2*HBGsd)) | Ymsk; + [Ybg,resT2] = cat_vol_resize(smooth3(Ybg) ,'reduceV',vx_vol,2,32,'meanm'); + Ybg = cat_vol_morph(cat_vol_morph(Ybg>0.5,'l',[100,400])<0.5,'lc',4)<0.5; + Ybgid = cat_vbdist(single(Ybg)); Ybgid = Ybgid./max(Ybgid(Ybgid(:)<1000)); + Ybgi = cat_vol_resize(Ybg,'dereduceV',resT2)<0.5; % inverse background = object + Ybgid = cat_vol_resize(Ybgid,'dereduceV',resT2); % inverse background = object + + %% estimate WM threshold + Yw0 = Yg<0.15 & Ysrc>cat_stat_nanmean( Ysrc(Yg(:)<0.15 & Ybgid(:)>0.5)) & Ybgid>0.8; + Yw0 = cat_vol_morph(smooth3(Yw0)>0.5,'l',[10,100])>0; + Yw0 = cat_vol_morph(smooth3(Yw0)>0.5,'l'); + WMth = cat_stat_kmeans(Ysrc(Yw0(:)),1); + else + Ybgi = ((Yg.*Ym)0.1; % inverse background = object + Ybgi([1,end],:,:)=0; Ybgi(:,[1,end],:)=0; Ybgi(:,:,[1,end])=0; Ybgi(smooth3(Ybgi)<0.5)=0; + end + [Ybg,resT2] = cat_vol_resize(single(Ybgi),'reduceV',resT3.vx_volr,2,32,'meanm'); + Ybg([1,end],:,:)=0; Ybg(:,[1,end],:)=0; Ybg(:,:,[1,end])=0; Ybg = Ybg>0.5; + Ybg = cat_vol_morph(Ybg,'lc',8); + Ybg = cat_vol_smooth3X(Ybg,2); + Ybg = cat_vol_resize(Ybg,'dereduceV',resT2)<0.5; + if ~highBG + BGth = roundx(cat_stat_nanmean(Ysrc(Ybg(:))),rf); + [Ybgr,resT2] = cat_vol_resize(smooth3(Ybg) ,'reduceV',vx_vol,2,32,'meanm'); + Ybgid = cat_vbdist(single(Ybgr)); Ybgid = Ybgid./max(Ybgid(Ybgid(:)<1000)); + Ybgid = cat_vol_resize(Ybgid,'dereduceV',resT2); + end + Ym = (Ysrc - BGth) ./ (WMth - BGth); + + %% first WM inhomogeneity with low tissue boundary (may include CSF > strong filtering for IXI175) + stime = cat_io_cmd(' Initial correction','g5','',verb,stime); + Yms = cat_vol_smooth3X( min(2 .* ~Ybg,Ym .* (Ydiv>-0.2) .* ~Ybg .* (Ym>0.1)),16*mean(vx_vol)); % this map is to avoid CSF in the mask! + Yms = (Yms ./ mean(Yms(~Ybg(:)))) * WMth; + Yms = cat_vol_smooth3X( min(Yms*1.5 .* ~Ybg,Ysrc .* ~Ybg),16*mean(vx_vol)); + Yms = (Yms ./ mean(Yms(~Ybg(:)))) * WMth; + if ~highBG + Yt = Ysrc>max(BGth,Yms*0.3) & Ysrc-0.6 & smooth3(Ysrc./(Yms+eps).*Yg.*Ydiv<-0.2)<0.3 & ~Ybg; Yt(smooth3(Yt)<0.5)=0; + Ywi = (Ysrc .* Yt) ./ max(eps,Yt); + [Ywi,resT2] = cat_vol_resize(Ywi,'reduceV',resT3.vx_volr,cat_stat_nanmean(resT3.vx_volr)*2,32,'max'); + for i=1:1, Ywi = cat_vol_localstat(Ywi,Ywi>0,2,3); end % only one iteration! + for i=1:4, Ywi = cat_vol_localstat(Ywi,Ywi>0,2,1); end + Ywi = cat_vol_approx(Ywi,'nn',resT2.vx_volr,4); + Ywi = cat_vol_smooth3X(Ywi,bfsmoothness.*mean(vx_vol)); % highres data have may stronger inhomogeneities + Ywi = cat_vol_resize(Ywi,'dereduceV',resT2); + Ybc = (Ysrc - BGth) ./ Ywi; + WMt2 = roundx(cat_stat_nanmedian(Ybc(Yg(:)<0.2 & Ym(:)>0.9)),rf); clear Ybc; + Ywi = Ywi * WMt2; + Ym = (Ysrc - BGth) ./ Ywi; + else + Yt = Ysrc>max(BGth,Yms*0.3) & Ysrc0.5 & ... + Ym>0.5 & Ym<1.1 & ... + Ydiv>-0.6 & smooth3(Ysrc./(Yms+eps).*Yg.*Ydiv<-0.2)<0.3 & ~Ybg; Yt(smooth3(Yt)<0.5)=0; + Yt = cat_vol_morph(Yt,'ldo',1.5); + Ywi = ones(size(Ym),'single'); + end + + %% background update + if ~highBG + stime = cat_io_cmd(' Refine background','g5','',verb,stime); + Ybg = ((Yg.*(Ym))0.2; + Ybg([1,end],:,:)=0; Ybg(:,[1,end],:)=0; Ybg(:,:,[1,end])=0; Ybg(smooth3(Ybg)<0.5)=0; + [Ybg,resT2] = cat_vol_resize(single(Ybg),'reduceV',resT3.vx_volr,2,32,'meanm'); + Ybg([1,end],:,:)=0; Ybg(:,[1,end],:)=0; Ybg(:,:,[1,end])=0; Ybg = Ybg>0.5; + Ybg = cat_vol_morph(Ybg,'ldc',8); + Ybg = cat_vol_smooth3X(Ybg,2); + Ybg = cat_vol_resize(Ybg,'dereduceV',resT2)<0.5 & Ymmax(BGth,Yms*0.3) & Ym>0.9 & Ym<1.2 & Ybgid>0.5 & ... + Ym-0.6 & ... + smooth3(Ym.*Yg.*Ydiv<-0.1)<0.1 & ~Ybg; Yt(smooth3(Yt)<0.5)=0; + Yt = Yt | (~Ybg & Ysrc>BGth/2 & Ysrc>Yms*0.5 & Ysrc0.3 & Yg>0.1 & Ydiv<0) | (~Ybg & Ysrc./(Ywi+eps)>0.6)) & Ysrc./(Ywi+eps)<1.2); + Yt(smooth3(Yt)<0.7)=0; + if ~highBG + Ywi = (Ysrc .* Yt) ./ max(eps,Yt); + [Ywi,resT2] = cat_vol_resize(Ywi,'reduceV',resT3.vx_volr,cat_stat_nanmean(resT3.vx_volr)*2,32,'max'); + for i=1:1, Ywi = cat_vol_localstat(Ywi,Ywi>0,2,3); end % only one iteration! + for i=1:4, Ywi = cat_vol_localstat(Ywi,Ywi>0,2,1); end + Ywi = cat_vol_approx(Ywi,'nn',resT2.vx_volr,4); + Ywi = cat_vol_smooth3X(Ywi,bfsmoothness.*mean(vx_vol)); %.*mean(vx_vol)); % highres data have may stronger inhomogeneities + Ywi = cat_vol_resize(Ywi,'dereduceV',resT2); + Ybc = (Ysrc - BGth) ./ Ywi; + WMt2 = roundx(cat_stat_nanmedian(Ybc(Yg(:)<0.2 & Ym(:)>0.9)),rf); + Ywi = Ywi * WMt2; + Ym = (Ysrc - BGth) ./ Ywi; + bias = std(Ywi(:))/mean(Ywi(:)); + else + Ywi = ones(size(Ym),'single') .* WMth; + Yt = cat_vol_morph(Yt,'lo'); + bias = 0; + end + + %% BG inhomogeneity (important for normalization of the background noise) + %[Ybc,Ygr,resT2] = cat_vol_resize({Ysrc./Ywi,Yg},'reduceV',resT3.vx_volr,cat_stat_nanmean(resT3.vx_volr)*4,16,'meanm'); + %Ybc = cat_vol_morph(Ybc0.5; + if 0 + stime = cat_io_cmd(' Background correction','g5','',verb,stime); + [Ybc,resT2] = cat_vol_resize(single(Ysrc .* Ybg),'reduceV',resT3.vx_volr,max(8,min(16,cat_stat_nanmean(resT3.vx_volr)*4)),16,'min'); + Ybc = cat_vol_localstat(Ybc,Ybc>0,2,2); + Ybc = cat_vol_localstat(Ybc,Ybc>0,2,1); + %Ybc = cat_vol_approx(Ybc,'nn',resT2.vx_volr,4); % no aproximation to correct only in the background! + Ybc = cat_vol_smooth3X(Ybc,4); + Ybc = cat_vol_resize(Ybc,'dereduceV',resT2) * WM; + end + + %% prepare intensity normalization by brain tissues + [Ymr,Ytr,resT2] = cat_vol_resize({Ym,Yt},'reduceV',resT3.vx_volr,3,32,'meanm'); + Yb0r = cat_vol_morph(cat_vol_morph(Ytr>0.1,'dd',6,resT2.vx_volr),'ldc',10,resT2.vx_volr) & Ymr<1.2; + T3th = cat_stat_kmeans(Ymr(Yb0r(:)),5); T3th = T3th(1:2:5); + clear Ymr Ytr Yb0r; + + %% back to original size + stime = cat_io_cmd(' Final scaling','g5','',verb,stime); + Ywi = cat_vol_resize(Ywi,'dereduceV',resT3); + %Ybc = cat_vol_resize(Ybc,'dereduceV',resT3); + Yg = cat_vol_resize(Yg,'dereduceV',resT3); + [Yt,Ybg] = cat_vol_resize({single(Yt),single(Ybg)},'dereduceV',resT3); Yt = Yt>0.5; Ybg = Ybg>0.5; + Ysrc = Ysrco; clear Ysrco; + + %% intensity normalization (Ybc is the average background noise) + % in data with strong inhomogeneities (7T) the signal can trop below the noise level + Ym = (Ysrc - BGth) ./ Ywi; %(Ywi - min(BGth,min(Ybc/2,Ywi/20))); + Wth = single(cat_stat_nanmedian(Ym(Yg(:)<0.2 & Yt(:)))); + [WIth,WMv] = hist(Ym(Yg(:)<0.2 & Ym(:)>Wth*0.5 & Ym(:)0.8,1,'first'); WIth = roundx(WMv(WIth),rf); + Ym = Ym ./ WIth; + % update WMth + Ysrc = Ysrc + BGth2; + [WIth,WMv] = hist(Ysrc(Yg(:)<0.2 & Ym(:)>Wth*0.5 & Ym(:)0.7,1,'first'); WMth = roundx(WMv(WMth),rf); + + %% intensity normalization + [Ymr,Ytr,resT2] = cat_vol_resize({Ym,Yt},'reduceV',resT3.vx_volr,2,32,'meanm'); + Yb0r = cat_vol_morph(cat_vol_morph(Ytr>0.1,'dd',6,resT2.vx_volr),'ldc',10,resT2.vx_volr) & Ymr<1.2; + T3th = cat_stat_kmeans(Ymr(Yb0r(:)),5); T3th = T3th(1:2:5); + T3th2 = T3th; + if 1 % highBG + T3thc = cat_stat_kmeans(Ymr(Yb0r & Ymr>0.1 & ... + cat_vol_morph(Ymrcat_stat_nansum(T3th(1:2).*[0.8 0.2]) ),3); + T3th2(2) = T3th2g(2); + T3th2w = cat_stat_kmeans(Ymr(Yb0r & ... + cat_vol_morph(Ymr>cat_stat_nansum(T3th(2:3).*[0.5 0.5]) & Ymr<(T3th(3) + diff(T3th(2:3))),'de',1) ),3); + T3th2(3) = T3th2w(2); + end + T3th = T3th2; + clear Ymr Ytr Yb0r; + + Tth.T3thx = [0 T3th T3th(3)+diff(T3th(2:3))]; + Tth.T3th = 0:1/3:4/3; + Ym = cat_main_gintnormi(Ym/3,Tth); + + cat_io_cmd(' ','','',verb,stime); +end +%======================================================================= +function r = roundx(r,rf) + r(:) = round(r(:) * rf) / rf; +end +%======================================================================= +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_vol_urqio.m",".m","29550","686","function cat_vol_urqio(job) +% Ultrahigh Resolution Quantitative Image Optimization +% ______________________________________________________________________ +% +% Skript to reduce inhomogeneity, noise, and blood vessels in ultra-high +% resolution quantitative MR data. The R1, PD (A), and R2s images are +% required. The function use a simple tissue classification to apply a +% bias correction, a gobal intensity normalization, a blood vessel +% correction, and finally a noise reduction. +% +% WARNING: This function is in an early development stage (alpha) +% +% cat_vol_urqio(job) +% +% job.data .. structure with the filenames of the input images +% .r1 .. R1 images +% .pd .. PD images (A) +% .r2s .. R2s images +% job.ouput .. structure to control writing of output images +% .pd .. write corrected PD images +% .r1 .. write corrected R1 images +% .r2s .. write corrected R2s images +% .t1 .. write synthetic T1 images (invertation of the PD) +% .bv .. write detected blood vessels +% job.opts .. structure of option parameter +% .prefix .. filename prefix (default = 1) +% .verb .. display processing notes +% .bc .. apply bias correction [0|1] +% .in .. apply global intensity normalisation [0|1] +% .bvc .. apply blood vessel correction [0|1] +% .nc .. apply noise correction +% +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% +% $Id$ + + + % this function adds noise to the data to stabilize processing and we + % have to define a specific random pattern to get the same results each time + if exist('rng','file') == 2, rng('default'); rng(0); else, rand('state',0); randn('state',0); end + + + dbs = dbstatus; debug = 0; for dbsi=1:numel(dbs), if strcmp(dbs(dbsi).name,mfilename); debug = 1; break; end; end + + % default options + if ~exist('job','var'), job = struct(); end + % input data + def.data.r1 = {}; + def.data.pd = {}; + def.data.r2s = {}; + % output data + def.output.pd = 1; + def.output.t1 = 1; + def.output.r1 = 1; + def.output.r2s = 1; + def.output.bv = 1; + % parameter + def.opts.prefix = 'catsyn_'; + def.opts.verb = 2; + def.opts.bc = 1; + def.opts.in = 1; + def.opts.bvc = 1; + def.opts.nc = 1; + def.opts.spm = 1; % use SPM preprocessing + def.opts.spmres = 0.8; + def.opts.ss = 0; % apply skull-stripping + def.opts.SSbd = 20; % reduce the size of the image by removing parts with distance greater SSbd + % checkin + job = cat_io_checkinopt(job,def); + + % set empty data fields + if isempty(job.data.r1) || isempty(job.data.r1{1}) + job.data.r1 = cellstr(spm_select(1,'image','Select R1 files')); + end + if isempty(job.data.pd) || isempty(job.data.pd{1}) + job.data.pd = cellstr(spm_select(1,'image','Select PD files')); + end + if isempty(job.data.r2s) || isempty(job.data.r2s{1}) + job.data.r2s = cellstr(spm_select(1,'image','Select R2s files')); + end + job.data.r1 = cellstr(job.data.r1); + job.data.r2s = cellstr(job.data.r2s); + job.data.pd = cellstr(job.data.pd); + + si = 1; %#ok + + + + %% main loop + for si=1:numel(job.data.r1) + stime2 = cat_io_cmd(sprintf('Preprocessing subject %d/%d:',si,numel(job.data.r1)),'','',job.opts.verb); fprintf('\n'); + + % get header + Vd = spm_vol(job.data.r1{si}); + Vr = spm_vol(job.data.r2s{si}); + Vp = spm_vol(job.data.pd{si}); + + % voxel size + vx_vol = sqrt(sum(Vd.mat(1:3,1:3).^2)); + + + % SPM unified segmentation + if job.opts.spm + %% + stime = cat_io_cmd(' SPM preprocessing','g5'); + + % SPM segmentation parameter + ofname = spm_file(job.data.pd{si},'number',''); + nfname = spm_file(ofname,'prefix','n'); + preproc.channel.vols{1,1} = nfname; + preproc.channel.biasreg = 0.001; + preproc.channel.biasfwhm = 60; + preproc.channel.write = [0 1]; + for ti=1:6 + preproc.tissue(ti).tpm = {[char(cat_get_defaults('opts.tpm')) ',' num2str(ti)]}; + preproc.tissue(ti).ngaus = 3; + preproc.tissue(ti).native = [0 0]; % native, dartel + preproc.tissue(ti).warped = [0 0]; % unmod, mod + end + preproc.warp.mrf = 1; % + preproc.warp.cleanup = 1; % this is faster and give better results! + preproc.warp.reg = [0 0.001 0.5 0.05 0.2]; + preproc.warp.affreg = 'none'; + preproc.warp.write = [0 0]; + preproc.warp.samp = 3; + preproc.Yclsout = true(1,6); + + %% lower resolution to improve SPM processing time and use smoothing for denoising + copyfile(ofname,nfname); + Vi = spm_vol(nfname); + Vi = rmfield(Vi,'private'); Vn = Vi; + imat = spm_imatrix(Vi.mat); + Vi.dim = round(Vi.dim .* vx_vol./repmat(job.opts.spmres,1,3)); + imat(7:9) = repmat(job.opts.spmres,1,3) .* sign(imat(7:9)); + Vi.mat = spm_matrix(imat); + + spm_smooth(nfname,nfname,repmat(0.75,1,3)); % denoising + [Vi,Yi] = cat_vol_imcalc(Vn,Vi,'i1',struct('interp',1,'verb',0)); + delete(nfname); spm_write_vol(Vi,Yi); + + vout = cat_spm_preproc_run(preproc,'run'); + %spmmat = open(fullfile(pp,mrifolder,['n' ff '_seg8.mat'])); + %AffineSPM = spmmat.Affine; + + %% update Ycls + if isfield(vout,'Ycls') + for i=1:6 + Vn = spm_vol(nfname); Vn = rmfield(Vn,'private'); + Vo = spm_vol(ofname); Vo = rmfield(Vo,'private'); + Vn.pinfo = repmat([1;0],1,size(vout.Ycls{i},3)); + Vo.pinfo = repmat([1;0],1,Vo.dim(3)); + Vn.dt = [2 0]; + Vo.dt = [2 0]; + Vo.dat = zeros(Vo.dim(1:3),'uint8'); + if ~isempty(vout.Ycls{i}) + Vn.dat = vout.Ycls{i}; + [Vmx,vout.Ycls{i}] = cat_vol_imcalc([Vo,Vn],Vo,'i2',struct('interp',1,'verb',0)); + vout.Ycls{i} = cat_vol_ctype(vout.Ycls{i}); + end + end + end + %% + Yp0 = (2*single(vout.Ycls{1})+3*single(vout.Ycls{2})+single(vout.Ycls{3}))/255; + Ybm = cat_vol_morph(Yp0>0.5,'lc'); + Ybg = cat_vol_morph(~cat_vol_morph(vout.Ycls{6}<64,'lo',1),'lo',1); + + %if ~debug, clear vout; end + + %% load images + Yd = single(spm_read_vols(Vd)); + Yr = single(spm_read_vols(Vr)); + Yp = single(spm_read_vols(Vp)); + + %% correct errors in Yd + YM = Yd>max(Yd(:)*0.99) & Yp64; + YM = cat_vol_morph(YM,'d',2); + Yd(YM) = 0; + + %% display segmentation V2 + %ds('d2','a',vx_vol,Yd/dth,Yd/dth .* ~YM,Yr./rth,Yp/pth,120); colormap gray + + else + stime = cat_io_cmd(' Load images:','g5','',job.opts.verb-1); + % load images + Yd = single(spm_read_vols(Vd)); + Yr = single(spm_read_vols(Vr)); + Yp = single(spm_read_vols(Vp)); + Ybm = ~(Yd==0 & Yr==0 & Yp==0); + Ybg = (Yd==0 & Yr==0 & Yp==0); + end + + if 0 % gcut>0 && job.opts.spm + Yl1 = ones(size(Ybm)); + + YMF = cat_vol_morph(Yp0==1 & cat_vol_smooth3X(Yp0,8)>1,'l',[0.4,2]); % ventricle + cat_main_gcut(Yr,Ybm,vout.Ycls,Yl1,YMF,vx_vol,opt) + end + + + + %% some kind of brain masking + Ypg = cat_vol_grad(Yp)./Yp; + Ydg = cat_vol_grad(Yd)./Yd; + pgth = max( cat_stat_nanmean(Ypg(Ypg(:)>0.01 & Ypg(:)<0.7 & Ybm(:)) ) , ... + abs(cat_stat_nanmean(Ypg(Ypg(:)>0.01 & Ypg(:)<0.7 & Ybm(:)) )) ); + pgth = min(0.5,max(0.25,pgth)); + if job.opts.spm + Ytis = Ybm & Ypg>0 & Ypg0; + Ytis = cat_vol_morph(Ytis,'lc',2/mean(vx_vol)) & Ybm & Ypg>0 & Ypg0; + else + Ytis = Ybm & Ypg>0 & Ypg0; + Ytis = cat_vol_morph(cat_vol_morph(Ytis,'lo',1),'lc',10/mean(vx_vol)) & Ypg>0 & Ypg0; + end + + %% some simple thresholds + dth = max( mean(Yd(Ytis(:))) , abs(mean(Yd(Ytis(:))))); + rth = max( mean(Yr(Ytis(:))) , abs(mean(Yr(Ytis(:))))); + pth = max( mean(Yp(Ytis(:))) , abs(mean(Yp(Ytis(:))))); + if ~debug, clear Ytis; end + + % gradient maps and thresholds + % only use PD contrast that have best SNR here + Ypg = cat_vol_grad(Yp); + Ypd = cat_vol_div(Yp); + pgth = max( mean(Ypg(Ypg(:)>0)) , abs(mean(Ypg(Ypg(:)<0)))); + + + + + %% tissue classification + % -------------------------------------------------------------------- + % Yw = white matter map + % Yg = gray matter map + % Yc = cerebrospinal fluid map + % -------------------------------------------------------------------- + stime = cat_io_cmd(' Tissue classification:','g5','',job.opts.verb-1,stime); + + % WM + Yw = Yppth*0.6 & Yd>dth & Ydrth/2 & Yr-pgth/2 & Ypd2.9 & Yppth*0.6 & Ypg-pgth/4 & Ypd=2 & Yppth*0.6 & Ypg>pgth/8 & Ypd>0.01); + end + Yw = Yw & Yrpth & Ypdth*0.5 & Yr>rth/2 & Ybm & ... + Ypg-pgth/2 & Ypdpth & Yp0>1.9 & Yp0<2.1 & Ypg-pgth/2 & Ypdpth*1.5 & Ypdth*0.01 & Yr-pgth*2 & ~Yw & ~Yg; + if job.opts.spm + Yc = Yc | (Yp>pth*1.5 & Ypdth*0.01 & ... + Yr0.9 & Yp0<1.1 & Ypg-pgth/42 & Ypdpth/8 & Yprth & Yr-pgth & Ypd64; + Yh(smooth3(Yh)<0.5)=0; + Yh = cat_vol_morph(Yh,'l',[0.02 50]); + end + + + + %% super WM (higher intensity in R1 and R2s) and the question if and how + % we need to correction it for normal preprocessing, because actual it + % lead to GM like brainstem that get lost ... + %if debug, Yx = Yp; end + if ~debug, clear Ypd; end + + if 0 + %% display segmentation V1 + ds('l2','',vx_vol,Yp./mean(Yp(Yw(:))),(Yw*3 + Yg*2 + Yc)/3,Yp./mean(Yp(Yw(:))),(Yw*3 + Yg*2 + Yc)/3*2,360); colormap gray + %% display segmentation V2 + ds('d2','a',vx_vol,Yd/dth,Yh,Yr./rth,Yp/pth,120); colormap gray + end + + + + + %% bias correction + % -------------------------------------------------------------------- + % Ybiw = initial signal intensity map (of the white matter) + % Ybig = intitla signal intensity map of the gray matter + % Ybiws = approximated bias field map + % normalization in the next step + % -------------------------------------------------------------------- + if job.opts.bc + useGMandCSF = [1 0]; % use also the GM (and CSF) for bias correction (CSF is problematic) + + % approx .. 2 is fast and smooth, 1 sh + biasstr = { % name var WMfilter CSFfitler approxres approxsmooth + 'PD' ,'Yp', 2, 3, 1.6, 2/job.opts.bc; + 'R1' ,'Yd', 3, 2, 1.6, 2/job.opts.bc; + 'R2s','Yr', 3, 2, 1.6, 1/job.opts.bc; + }; + for bi=1:size(biasstr,1) + stime = cat_io_cmd(sprintf(' Bias correction (%s):',biasstr{bi,1}),'g5','',job.opts.verb-1,stime); + eval(['Ybi = ' biasstr{bi,2} '; bith = ' biasstr{bi,2}(2) 'th;']); + Ybiw = Ybi .* Yw; Ybiw = cat_vol_localstat(Ybiw,Ybiw>0,1,1); + Ybiw = Ybi .* (Yw & Ybiw~=Ybi & abs(Ybiw-Ybi)0,1,biasstr{bi,3}); + for ii=1:round(8/mean(vx_vol)), Ybiw = cat_vol_localstat(Ybiw,Ybiw>0,1,1); end + if useGMandCSF(1) + % use additonal GM + Ybig = Ybi .* Yg; Ybig = cat_vol_localstat(Ybig,Ybig>0,1,1); + Ybig = Ybi .* (Yg & Ybig~=Ybi & abs(Ybig-Ybi)0,1,1); end + Ybiw = Ybiw + (Ybig / median(Ybig(Ybig(:)>0)) * median(Ybiw(Ybiw(:)>0))); + clear Ybig; + end + if useGMandCSF(2) + % use additonal CSF + Ybig = Ybi .* Yc; Ybig = cat_vol_localstat(Ybig,Ybig>0,1,2); + Ybig = Ybi .* (Yc & Ybig~=Ybi & abs(Ybig-Ybi)0,1,biasstr{bi,4}); + for ii=1:round(8/mean(vx_vol)), Ybig = cat_vol_localstat(Ybig,Ybig>0,1,1); end + Ybiw = Ybiw + (Ybig / median(Ybig(Ybig(:)>0)) * median(Ybiw(Ybiw(:)>0))); + clear Ybig; + end + % + if job.opts.spm + % use additonal CSF + Ybig = Ybi .* Yh; Ybig = cat_vol_localstat(Ybig,Ybig>0,1,2); + Ybig = Ybi .* (Yh & Ybig~=Ybi & abs(Ybig-Ybi)0,1,biasstr{bi,4}); + for ii=1:round(4/mean(vx_vol)), Ybig = cat_vol_localstat(Ybig,Ybig>0,5,1); end + %% + Ybiw = Ybiw + (Ybig / mean(Ybiw(Ybiw(:)>0)) * mean(Ybi(Yw(:)>0))); + if ~debug, clear Ybig; end + end + %% + Ybiws = cat_vol_approx(Ybiw,'nn',vx_vol,biasstr{bi,5},struct('lfO',biasstr{bi,6})); %#ok + eval([biasstr{bi,2} 'ws = Ybiws;']); + if debug, eval([biasstr{bi,2} 'w = Ybiw;']); end + if ~debug, clear Ybiw Ybiws; end + end + if 0 + % this is just for manual development & debugging + %% display PD + ds('d2','a',vx_vol,Ybiw./mean(Yp(Yw(:))),Ypws./mean(Yp(Yw(:))),Yp./mean(Yp(Yw(:))),Yp./Ypws,120); colormap gray + %% display R1 + ds('d2','a',vx_vol,Yd./mean(Yd(Yw(:))),Ydws./mean(Yd(Yw(:))),Yd./mean(Yd(Yw(:))),Yd./Ydws,120); colormap gray + %% display R2s + ds('d2','a',vx_vol,Yr./mean(Yr(Yw(:))),Yrws./mean(Yr(Yw(:))),Yr./mean(Yr(Yw(:))),Yr./Yrws,120); colormap gray + end + end + + + + + %% intensity normalization + % -------------------------------------------------------------------- + % Ydm = bias corrected R1 map + % Ypm = bias corrected PD map + % Yrm = bias corrected R2s map + % + % Ydmc = intensity normalized bias corrected R1 map + % Ypmc = intensity normalized bias corrected PD map + % Yrmc = intensity normalized bias corrected R2s map + % -------------------------------------------------------------------- + if job.opts.in + stime = cat_io_cmd(' Intensity Normalization:','g5','',job.opts.verb-1,stime); + + % apply bias correction, create inverted version of the pd image + if job.opts.bc + Ydm = Yd ./ Ydws; + Ypm = Yp ./ Ypws; + Yrm = Yr ./ Yrws; + else + Ydm = Yd ./ mean(Yd(Yw(:))); + Ypm = Yp ./ mean(Yp(Yw(:))); + Yrm = Yr ./ mean(Yr(Yw(:))); + end + if ~debug, clear Yd Yp Yr; end + Ybs = cat_vol_smooth3X(Ybm,1); + + %% create synthetic T1 contrast based on the PD image + %Ytm = 1.5 - Ypm/2; + Ypmi = cat_stat_histth(Ypm,99); + Ytm = Ybs - (Ypmi - min(Ypmi(Ybs(:)>0))) / ( max(Ypmi(Ybs(:)>0)) - min(Ypm(Ybs(:)>0))); + Ytm = min(cat_stat_histth( Ytm .* Ybs,99) *0.8-0.1 + 1.2*smooth3(Ybs), Ytm + (1-Ybs)); + if debug, clear YM; end + + %% the region maps are only used to estimate a the mean intensity of a tissue + Ywm = Yw & Yrm1.2 & Ypm<0.5 & Yrm>1.2; + Ylm = ~Ybs & ~Yw & ~Yg & ~Yc & ~Ybm & Ydm>0 & Ypm>0 & Yrm>0 & Ydmmean(Ypm(Ycm(:)))/1.5 & Yrmmin(Ydm(:)) & Ypm>min(Ypm(:)) & Yrm>min(Yrm(:)) & Ydmmean(Ypm(Ycm(:)))/2 & Yrm0)<1000 && sum(Ylm(:)>0)<1000 + T3th{1,2}([2,6]) = [mean(T3th{1,2}(1:2:3)) mean(T3th{1,2}(5:2:7))]; + T3th{2,2}(5) = mean(T3th{2,2}(4:2:6)); + T3th{3,2}([2,6]) = [mean(T3th{3,2}(1:2:3)) mean(T3th{3,2}(5:2:7))]; + T3th{4,2}(2) = 0.02; + end + Yp0 = Ycm + 2*Ygm + 3*Ywm; + if ~debug, clear Ylm Yhm Ycm Ygm Ywm; end + + %% final thresholds + T3th{1,3} = [ 0 1/12 1/3 2/3 1 T3th{1,2}(5)+diff(T3th{1,2}(5:6)) T3th{1,2}(6)+diff(T3th{1,2}(6:7))]; + T3th{2,3} = [ 0 1 2/3 1/3 T3th{2,2}(5)/(1/T3th{2,2}(2)) T3th{2,2}(6)/(1/T3th{2,2}(2))]; + T3th{3,3} = [ 0 1/12 1/3 2/3 1 T3th{3,2}(5)+diff(T3th{3,2}(5:6)) T3th{3,2}(6)+diff(T3th{3,2}(6:7))]; + T3th{4,3} = [ 0 0.02 1/3 2/3 1 T3th{4,2}(6)/T3th{4,2}(5)]; + + % global intensity normalization + for bi=1:size(T3th,1) + %% + [T3ths,tsi] = sort(T3th{bi,2}); + T3thx = T3th{bi,3}(tsi); + eval(['Ym = ' T3th{bi,1} ' + 0; if ~debug, clear ' T3th{bi,1} '; end; Ysrc = Ym;']); + for i=numel(T3ths):-1:2 + M = Ysrc>T3ths(i-1) & Ysrc<=T3ths(i); + Ym(M(:)) = T3thx(i-1) + (Ysrc(M(:)) - T3ths(i-1))/diff(T3ths(i-1:i))*diff(T3thx(i-1:i)); + end + M = Ysrc>=T3ths(end); + Ym(M(:)) = numel(T3ths)/6 + (Ysrc(M(:)) - T3ths(i))/diff(T3ths(end-1:end))*diff(T3thx(i-1:i)); + eval([T3th{bi,1} 'c = Ym;']); + clear Ym Ysrc M; + end + if 0 + %% just for debuging and display + ds('d2','',vx_vol,Ydmc,Ypmc,Yrmc,Ytmc,220); colormap gray + %% + ds('d2','a',vx_vol,Ydm,Ydmc,Yrm,Yrmc,220); colormap gray + %% + ds('d2','a',vx_vol,Ypm,Ypmc*2,Ytm,Ytmc,140); colormap gray + end + + else + % no intensity normalization + Ydmc = Yd ./ mean(Yd(Yw(:))); + Ypmc = Yp ./ mean(Yp(Yw(:))); + Yrmc = Yr ./ mean(Yr(Yw(:))); + Ytmc = 1.5 - Ypmc/2; Ytmc(Ypmc<0.8 & cat_vol_morph(cat_vol_morph(Ypmc<0.5 | Yrmc>1.5,'l'),'d',1.5))=0; + if ~debug, clear Ybs; end + end + + + + + + + %% find blood vessels + % -------------------------------------------------------------------- + % Yrd, Ydd, Ytd = divergence maps + % -------------------------------------------------------------------- + Yb = cat_vol_morph((Ybm | (Yp0>0.1)) & Ydmc>0 & Ydmc<1.1 & Yrmc>0 & Yrmc<1.1 & Ytmc>0 & Ytmc<1.1,'lc',max(1,min(2,1/mean(vx_vol)))); % brain mask for CSF minimum value + Yb = cat_vol_morph(Yb,'lo',0.5/mean(vx_vol)); + if job.opts.bvc || job.output.bv + stime = cat_io_cmd(' Blood Vessel Detection:','g5','',job.opts.verb-1,stime); + + % divergence update + Yrd = cat_vol_div(Yrmc); + Ydd = cat_vol_div(Ydmc); + Ytd = cat_vol_div(Ytmc); + + + %% first we remove high intensity blood vessels with large area + % in the save WM region only a mean filter should be used to create an + % corrected map, whereas in the other regions a larger and minimum + % based filter is applied + Ywc = cat_vol_morph(Yw,'lc',1) | ~cat_vol_morph(~cat_vol_morph(Yw,'o',1),'lc',max(1,min(2,1/mean(vx_vol)))); % wm mask with close microstructures + Ywc = Ywc | smooth3(Yrmc>0.8 & Yrmc<1.1 & Yb)>0.5 | cat_vol_morph(smooth3(Ydmc>0.7 & Ydmc<1.2 & Yb)>0.6,'o',1); + Ywc = cat_vol_morph(Ywc,'lc',1); + + %% correction maps + Ymin = max(Yb.*3/12,Yb.*min(Ydmc,min(Ytmc,Yrmc))); % minimum intensity in all images (CSF) + Ymax = max(Yb.*3/12,Yb.*max(Ydmc,max(Ytmc,Yrmc))); % maximum intensity in all images (BV) + Ymn1 = cat_vol_localstat(Ymin,Ymin>0,1,1); % low short correction + Ymin1 = cat_vol_localstat(Ymin,Ymin>0,1,2); % storng short correction + Ymax1 = cat_vol_localstat(Ymax,Ymax>0,1,3); % very close to vessel + Ymax2 = cat_vol_localstat(Ymax1,Ymax>0,1,3); % close to vessel + Ymin2 = cat_vol_localstat(Ymin1,Ymin>0,1,2); % strong medium correction + Ymin4 = cat_vol_localstat(Ymin2,Ymin>0,2,2); % strong long correction + + + %% specific masks + % - save regions that need no corrections + % - save blood vessels that requires maxim correction (long distance with min) + % - save blood vessels that requires carfull correction (short distance with mean) + % - small blood vessels that requires less agressive correction + YminA = Ytmc .* ( Ymax<1.1 & Ywc) + ... low values in the WM + Ymn1 .* ( Ymax>=1.1 & Ywc) + ... high values in the WM + Ymin .* ( Ymax< 0.7 & ~Ywc) + ... low good values + Ymn1 .* ( Ymax>=0.7 & Ymax<1.0 & ~Ywc) + ... affected voxel + Ymn1 .* ( Ymax>=1.0 & Ymax<1.1 & ~Ywc) + ... + Ymin .* (Ymin< 0.9 & Ymax2< 1.3 & Ymax>=1.1 & Ymax<1.3 & ~Ywc) + ... + Ymin1 .* (Ymin< 0.9 & Ymax2>=1.3 & Ymax>=1.1 & Ymax<1.3 & ~Ywc) + ... + Ymin .* (Ymin< 0.9 & Ymax2< 1.3 & Ymax>=1.3 & ~Ywc) + ... + Ymin2 .* (Ymin< 0.9 & Ymax2>=1.3 & Ymax>=1.3 & ~Ywc) + ... + Ymn1 .* (Ymin>=0.9 & Ymax>=1.1 & Ymax<1.3 & ~Ywc) + ... + Ymin4 .* (Ymin>=0.9 & Ymax>=1.3 & ~Ywc); + + + %% find blood vessels + Ybv1 = (Yrmc>2 | Ytmc>1.5 | Ydmc>1.5) & ~Ywc & Yb; + Ybv = Yb .* max(0 , max(Yrmc.*Ydmc.*Ytmc,Ymax) - min(Yrmc.*Ydmc.*Ytmc,Ymin) - 2/3 + 2*max(Yrd.*Ydd.*Ytd,max(Yrd,max(Ydd,Ytd))) - Ywc ); + + if debug + %% display BV + ds('d2','a',vx_vol,Ydmc*1.5,Ytmc*1.5,Ybv,Yp0/3*2,180); colormap gray + end + end + %% correct blood vessels + % -------------------------------------------------------------------- + % -------------------------------------------------------------------- + if job.opts.bvc + stime = cat_io_cmd(' Blood Vessel Correction:','g5','',job.opts.verb-1,stime); + + %% first correction + Ybvd = cat_vol_div(Ybv); + Ylow = smooth3(((Ymax1+1)./(Ymin1+1))>(Ymin+1) | Ybv>2 | Ybv1)>0.2; + %% + %Ypc = min(1.1.*(Ypm>0.1),max( (1.25-Ymin2) .* (Ypm>0),Ypmc - (Ylow | Ybv1) .* ~Yw .* (min(0,Ybvd) - max(0,Ybv-0.5) - max(0,(Ydmc./Ypmc) - 1.5) ))); + Ydc = max(Ymin2,Ydmc + (Ylow | Ybv1) .* ~Yw .* (min(0,Ybvd) - max(0,Ybv-0.5) - max(0,(Ydmc./Ypmc) - 1.5) )); + Ytc = max(Ymin2,Ytmc + (Ylow | Ybv1) .* ~Yw .* (min(0,Ybvd) - max(0,Ybv-0.5) - max(0,(Ydmc./Ypmc) - 1.5) )); + Yrc = max(Ymin2,Yrmc + (Ylow | Ybv1) .* ~Yw .* (min(0,Ybvd) - max(0,Ybv-0.5) - max(0,(Ydmc./Ypmc) - 1.5) )); + + %% median fitlering + %Ydcm = cat_vol_median3(Ydc,Ydc>0,true(size(Ydc)),0.05); + Ytcm = cat_vol_median3(Ytc,Ytc>0,true(size(Ydc)),0.05); + Yrcm = cat_vol_median3(Yrc,Yrc>0,true(size(Ydc)),0.05); + + %% second correction + % r1 + YminAm = cat_vol_median3(YminA,YminA>0,true(size(Ydc)),0.1); + YM = YminAm>0.2 & ~Ywc & ((Ydmc - YminAm)>0.2 | Ydmc>1.5 | Ybv>1) & Yb; + Ydc2 = Ydmc; Ydc2(YM) = YminAm(YM); %Ydc2 = min(Ydc2.*Yb,Ydmc); %.* (YminA>0.05) + Ydc2 = cat_stat_histth(Ydc2); + % pd + YM = Ypmc>0.01 & Yb & ~Ywc & smooth3((Ypmc - (1.25-YminAm))>0.1 | Ypmc<0.3 | Ybv>1)>0.1; + YH = 1.1 - 0.05* (randn(size(YM))/4); % RD20200115: replaced rand(size(YM)) + Ypc2 = Ypmc; Ypc2(YM) = min(YH(YM),1.25-YminAm(YM).*Yb(YM)); + Ypc2 = cat_stat_histth(Ypc2); + % t1 = inverse pd + YM = Ytmc>0.2 & ~Ywc & ((Ytmc - Ytcm)>0.1 | Ytmc>1.1 | Ybv>0.5) & Yb; + Ytc2 = Ytmc; Ytc2(YM) = Ytcm(YM); Ytc2 = min(Ytc2,Ytmc); + YM = (Ydc2 - Ytc2)<-0.4 & Ydc2<0.5 & Yb; + Ytc2(YM) = min(Ytc2(YM) ,Ydc2(YM).*Yb(YM) ); + Ytc2 = cat_stat_histth(Ytc2); + % r2s + YM = Yrmc>0.2 & ~Ywc & ((Yrmc - Yrcm)>0.2 | Yrmc>1.1 | Ybv>0.5) & Yb; + Yrc2 = Yrmc; Yrc2(YM) = Yrcm(YM); Yrc2 = min(Yrc2,Yrmc); + YM = smooth3(Ydc2 - Yrc2)<-0.2 & (Ydc2<0.8 | Yrc2>1.3) & (~Ywc | (Yrd<-0.1 & Yrc2>1.3 & Ypg>0.05))>0.5 & Yb; + Yrc2(YM) = min(Yrc2(YM) ,Ydc2(YM).*Yb(YM) ); + Yrc2 = cat_vol_median3(Yrc2,YM | Yrc2>1.3 & Ypg>0.2); % remove small reminding WM vessels and artifacts + Yrc2 = cat_stat_histth(Yrc2); + if ~debug, clear Ypg; end + + %% this is just for manual development & debugging + if 0 + + %% display BV + ds('d2','a',vx_vol,Ybv1,Ybv,Ydcm,abs(Ydc2-Yd),200); colormap gray + %% display PD + ds('d2','a',vx_vol,Ypmc/2.5*1.5,Ypws./mean(Ypmc(Yw(:))),Ypmc*1.5,Ypc2*1.5,120); colormap gray + %% display PDi + ds('d2','a',vx_vol,2 - Ypc2*1.5,Yp/mean(Yp(Yw(:))),Ydmc*1.5,Ytc2*1.5,120); colormap gray + %% display R1 + ds('d2','a',vx_vol,Ydws./mean(Ydws(Yw(:)))*1.5,Ydws./mean(Ydws(Yw(:))),Ydc*1.5,Ydc2*1.5,120); colormap gray + %% display R2s + ds('d2','a',vx_vol,Yr./mean(Yr(Yw(:))),Yrws./mean(Yr(Yw(:))),Yr./mean(Yr(Yw(:))),Yrc2,120); colormap gray + + + %% create test WM surface with correct blood vessel system - Warning very slow! + S = isosurface(cat_vol_smooth3X(Ytc2,0.5),0.8); + Sb = isosurface(cat_vol_smooth3X(Ybv .* Yb,0.5),0.25); + + % reduce surface + SR = reducepatch(S,500000); + SbR = reducepatch(Sb,500000); + + % add some color + SR.facevertexcdata = zeros(size(SR.vertices,1),1); + SbR.facevertexcdata = ones(size(SbR.vertices,1),1); + + % combine surfaces + SRX.vertices = [SR.vertices;SbR.vertices]; + SRX.faces = [SR.faces;SbR.faces+size(SR.vertices,1)]; + SRX.cdata = [SR.facevertexcdata;SbR.facevertexcdata]; + + % dispaly surfaces + cat_surf_render2(SRX); + + end + else + Ypc2 = Ypmc; + Ytc2 = Ytmc; + Ydc2 = Ydmc; + Yrc2 = Yrmc; + end + if ~debug, clear Ypmc Ytmc Ydmc Yrmc; end + + + if job.opts.ss + Ypc2 = Ypc2 .* Yb; + Ytc2 = Ytc2 .* Yb; + Ydc2 = Ydc2 .* Yb; + Yrc2 = Yrc2 .* Yb; + end + + + %% write data + % -------------------------------------------------------------------- + stime = cat_io_cmd(' Write Output:','g5','',job.opts.verb-1,stime); + + % PD + if job.output.pd + [pp,ff,ee,dd] = spm_fileparts(Vp.fname); + Vpc = Vp; Vpc.fname = fullfile(pp,[job.opts.prefix 'pd_' ff ee dd]); Vpc.dt(1) = 16; + spm_write_vol(Vpc,Ypc2); + end + + % inverted PD + if job.output.t1 + [pp,ff,ee,dd] = spm_fileparts(Vp.fname); + Vtc = Vp; Vtc.fname = fullfile(pp,[job.opts.prefix 't1_' ff ee dd]); Vtc.dt(1) = 16; + spm_write_vol(Vtc,Ytc2); + end + + % R1 + if job.output.r1% r1 + [pp,ff,ee,dd] = spm_fileparts(Vd.fname); + Vdc = Vd; Vdc.fname = fullfile(pp,[job.opts.prefix 'r1_' ff ee dd]); Vdc.dt(1) = 16; + spm_write_vol(Vdc,Ydc2); + end + + % R2s + if job.output.r2s + [pp,ff,ee,dd] = spm_fileparts(Vr.fname); + Vrc = Vr; Vrc.fname = fullfile(pp,[job.opts.prefix 'r2s_' ff ee dd]); Vrc.dt(1) = 16; + spm_write_vol(Vrc,Yrc2); + end + + % BV + if job.output.bv + [pp,ff,ee,dd] = spm_fileparts(Vp.fname); + Vbvc = Vp; Vbvc.fname = fullfile(pp,[job.opts.prefix 'bv_' ff ee dd]); Vbvc.dt(1) = 16; + spm_write_vol(Vbvc,Ybv .* Yb); + end + if ~debug, clear Ypc2 Ytc2 Ydc2 Yrc2 Ybv Yb; end + + + + %% noise reduction + if job.opts.nc + stime = cat_io_cmd(' Noise Correction:','g5','',job.opts.verb-1,stime); fprintf('\n') + if job.output.pd, cat_vol_sanlm(struct('data',cellstr(Vpc.fname),'prefix','')); end + if job.output.t1, cat_vol_sanlm(struct('data',cellstr(Vtc.fname),'prefix','')); end + if job.output.r1, cat_vol_sanlm(struct('data',cellstr(Vdc.fname),'prefix','')); end + if job.output.r2s, cat_vol_sanlm(struct('data',cellstr(Vrc.fname),'prefix','')); end + if job.output.bv, cat_vol_sanlm(struct('data',cellstr(Vbvc.fname),'prefix','')); end + end + + cat_io_cmd(' ','g5','',job.opts.verb-1); cat_io_cmd(' ','g5','',job.opts.verb-1,stime); % time of the last step + cat_io_cmd(' ','','',job.opts.verb-1,stime2); fprintf('\n'); % time of the full subject + end +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_stat_diff.m",".m","3330","112","function cat_stat_diff(P,rel,glob) +% compute difference between two images or surfaces +% image2 - image1 +% output name will be diff_{name of image2} +% or diff_rel{name of image2} for relative differences +% +% FORMAT cat_stat_diff(P,rel,glob) +% P - filenames for image 1/2 +% rel - compute relative difference rather than absolute (1 for relative) +% glob - normalize global mean of images +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +% get filenames +%---------------------------------------------------------------------------- +if nargin < 3, glob = 0; end +if nargin < 2, rel = 0; end + +if nargin == 0 + % select images for each subject + don = 0; + for i = 1:1000 + P = spm_select([0 Inf],{'mesh','image'},['Image(s)/Surface(s), subj ' num2str(i)]); + if size(P,1) < 2, don = 1; break; end + try + V{i} = spm_data_hdr_read(P); + catch + error('Error reading file. Ensure that you either have an image file or a surface texture file with values.'); + end + end + rel = 0; + glob = 0; +else + try + V{1} = spm_data_hdr_read(P); + catch + error('Error reading file. Ensure that you either have an image file or a surface texture file with values.'); + end +end + +if isfield(V{1}(1).private,'cdata') + surf = 1; +else surf = 0; end + +for i = 1:length(V) + Vi = V{i}; + + n = length(Vi); + % compute global means to normalize images to same value + if glob && ~surf + gm = zeros(n,1); + disp('Calculating globals...'); + for j=1:n, gm(j) = spm_global(Vi(j)); end + gm_all = mean(gm); + for j=1:n + Vi(j).pinfo(1,:) = gm_all*Vi(j).pinfo(1,:)/gm(j); + end + end + + for j=2:n + + Q = char(Vi(j).fname); + [pth,nm,xt,vr] = spm_fileparts(Q); + + if rel + outname = ['diffrel_' nm xt vr]; + str='relative difference %'; + else + outname = ['diff_' nm xt vr]; + str='difference'; + end + + Q = fullfile(pth,outname); + + Vo = struct( 'fname', Q,... + 'dim', Vi(j).dim,... + 'mat', Vi(j).mat,... + 'descrip', str); + + Vo.dt = [spm_type('float32') spm_platform('bigend')]; + + [pth1,nm1,xt1,vr1] = spm_fileparts(Vi(1).fname); + [pth2,nm2,xt2,vr2] = spm_fileparts(Vi(j).fname); + if surf + fprintf('Calculate s2-s1: %s - %s\n',[nm2 xt2],[nm1 xt1]); + else + fprintf('Calculate i2-i1: %s - %s\n',[nm2 xt2],[nm1 xt1]); + end + + % implement the computing + %--------------------------------------------------------------------------- + if surf + if rel, formula='200*(s2-s1)./(s1+s2+eps)'; + else, formula='s2-s1'; end + iname{1} = Vi(1).fname; + iname{2} = Vi(j).fname; + spm_mesh_calc(iname,Vo.fname,formula); + else + if rel, formula='200*(i2-i1)./(i1+i2+eps)'; + else, formula='i2-i1'; end + spm_imcalc(Vi([1 j]),Vo,formula,{0 0 4 1}); + end + end + +end +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_plot_scatter.m",".m","23936","918","function hAxes = cat_plot_scatter(X,Y, varargin) +% cat_plot_scatter creates a scatter plot coloured by density. +% +% cat_plot_scatter(X,Y) creates a scatterplot of X and Y at the locations +% specified by the vectors X and Y (which must be the same size), colored +% by the density of the points. +% +% cat_plot_scatter(...,'MARKER',M) allows you to set the marker for the +% scatter plot. Default is 's', square. +% +% cat_plot_scatter(...,'MSIZE',MS) allows you to set the marker size for the +% scatter plot. Default is 10. +% +% cat_plot_scatter(...,'FILLED',true) sets the markers in the scatter plot to be +% outline. +% +% cat_plot_scatter(...,'COLOR',COLOR) specifies the marker colors +% Only works for plottype 'scatter' +% +% cat_plot_scatter(...,'FIT_POLY',N) fit polynomial with degree N +% The default is 0. +% +% cat_plot_scatter(...,'CI',false) add plot of confidence interval for +% polynomial fit. The default is true. +% +% cat_plot_scatter(...,'CMAP',cmap) defines colormap +% The default is parula (if available) or jet. +% +% cat_plot_scatter(...,'FIG',FIG) defines figure handle +% +% cat_plot_scatter(...,'GROUP',GROUP) defines different groups for which +% separate plots are displayed. Use 1..n for coding the groups. +% For more than one group the parameter 'plottype' is set to 'scatter'. +% +% cat_plot_scatter(...,'NAMES',NAMES) char-array of names for different groups +% +% cat_plot_scatter(...,'SHOWLEGEND',SHOWLEGEND) show legend with names +% +% cat_plot_scatter(...,'JITTER',TRUE) adds jitter on x-axis for +% categorical x-variables +% +% cat_plot_scatter(...,'PLOTTYPE',TYPE) allows you to create other ways of +% plotting the scatter data. Options are 'dscatter' and 'scatter'. +% 'dscatter' creates plots colored by density of the scatter data, which is +% the default. +% +% cat_plot_scatter(...,'BINS',[NX,NY]) allows you to set the number of bins used +% for the 2D histogram used to estimate the density. The default is to +% use the number of unique values in X and Y up to a maximum of 200. +% +% cat_plot_scatter(...,'SMOOTHING',LAMBDA) allows you to set the smoothing factor +% used by the density estimator. The default value is 20 which roughly +% means that the smoothing is over 20 bins around a given point. +% +% cat_plot_scatter(...,'LOGY',true) uses a log scale for the yaxis. +% +% cat_plot_scatter(...,'IMG',FILENAME) saves plot in desired graphic output format. +% +% cat_plot_scatter(...,'FONTSIZE',FONTSIZE) change font size. +% +% Examples: +% +% data randn(1000,2); +% cat_plot_scatter(data(:,1),10.^(data(:,2)/256),'log',1) +% % Add contours +% hold on +% cat_plot_scatter(data(:,1),10.^(data(:,2)/256),'log',1,'plottype','contour') +% hold off +% +% See also SCATTER. +% +% modified by Christian Gaser (christian.gaser@uni-jena.de) and +% original dscatter version was written by Paul H. C. Eilers +% +% Copyright 2003-2004 The MathWorks, Inc. +% $Revision$ $Date$ +% Reference: +% Paul H. C. Eilers and Jelle J. Goeman +% Enhancing scatterplots with smoothed densities +% Bioinformatics, Mar 2004; 20: 623 - 628. +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +lambda = []; +nbins = []; +plottype = 'dscatter'; +contourFlag = false; +msize = 10; +marker = 's'; +logy = false; +filled = false; +fit_poly = 0; +ci = true; +jitter = false; +img = ''; +fontsize = 20; +color = []; +group = []; +names = []; +showlegend = 0; +if exist('parula') + cmap = 'parula'; +else + cmap = 'jet'; +end + +if nargin < 2 + printf('Arguments missing. Syntax: cat_plot_scatter(X,Y)\n'); + hAxes = []; + return +end + +% define plot of confidence band +plot_variance = @(x,lower,upper,color,alpha) set(fill([x,x(end:-1:1)],[upper,lower(end:-1:1)],color),... + 'EdgeColor',color,'FaceAlpha',alpha); + +if nargin > 2 + if rem(nargin,2) == 1 + error('IncorrectNumberOfArguments',... + 'Incorrect number of arguments to %s.',mfilename); + end + okargs = {'smoothing','bins','plottype','logy','contourFlag','marker','msize',... + 'filled','fit_poly','ci','cmap','fig','jitter','img','fontsize','color',... + 'group','names','showlegend'}; + for j=1:2:nargin-2 + pname = varargin{j}; + pval = varargin{j+1}; + k = strmatch(lower(pname), okargs); %#ok + if isempty(k) + error('UnknownParameterName',... + 'Unknown parameter name: %s.',pname); + elseif length(k)>1 + error('AmbiguousParameterName',... + 'Ambiguous parameter name: %s.',pname); + else + switch(k) + case 1 % smoothing factor + if isnumeric(pval) + lambda = pval; + else + error('InvalidScoringMatrix','Invalid smoothing parameter.'); + end + case 2 + if isscalar(pval) + nbins = [ pval pval]; + else + nbins = pval; + end + case 3 + plottype = pval; + case 4 + logy = pval; + Y = log10(Y); + case 5 + contourFlag = pval; + case 6 + marker = pval; + case 7 + msize = pval; + case 8 + filled = true; + case 9 + fit_poly = pval; + case 10 + ci = pval; + case 11 + cmap = pval; + case 12 + fig = pval; + case 13 + jitter = pval; + case 14 + img = pval; + case 15 + fontsize = pval; + case 16 + color = pval; + case 17 + group = pval; + case 18 + names = pval; + case 19 + showlegend = pval; + end + end + end +end + +% For more than one group the parameter 'plottype' is set to 'scatter'. +if ~isempty(group) && max(group) > 1 + plottype = 'scatter'; + n_groups = max(group); + if isempty(color) + color = nejm; + end + color = color(1:n_groups,:); +else + n_groups = 1; + group = ones(size(X)); +end + +if isempty(names) + names = num2str((1:n_groups)'); +end +lnames = cell(2*n_groups,1); +for i = 1:n_groups + lnames{i} = deblank(names(i,:)); +end +for j = 1:n_groups + lnames{i+j} = ['Fit ' deblank(names(j,:))]; +end + +if size(X,1) == size(Y,2) + Y = Y'; +end + +ind = ~isnan(X) & ~isnan(Y); +X = X(ind); Y = Y(ind); +if ~isempty(color) && size(color,1) == numel(ind) + color = color(ind,:); +end + +minx = min(X(:)); +maxx = max(X(:)); +miny = min(Y(:)); +maxy = max(Y(:)); + +if isempty(nbins) + nbins = [min(numel(unique(X)),200), min(numel(unique(Y)),200)]; +end + +if isempty(lambda) + lambda = 20; +end + +if logy + Y = 10.^Y; +end + +if exist('fig','var') + figure(fig) +else + clf +end + +if size(X,1) == 1 + X = X'; +end + +if size(Y,1) == 1 + Y = Y'; +end + +% check whether X has limited number of entries (and is rather categorical) +n_categories_X = numel(unique(X)); +add_range = min([1,log10(n_categories_X)/10]); + +% polynomial fit and confidence interval +if fit_poly + + % add some more range because of jittered data + if n_categories_X < 30 && jitter + xfit = linspace(minx-2*add_range,maxx+2*add_range,100); + else + if minx < 0, minx = 1.01*minx; else minx = 0.99*minx; end + if maxx > 0, maxx = 1.01*maxx; else maxx = 0.99*maxx; end + xfit = linspace(minx,maxx,100); + end + + for i = 1:n_groups + ind2 = group == i; + ind2 = ind2(ind); + [p,S] = polyfit(X(ind2),Y(ind2),fit_poly); + + yfit{i} = polyval(p,xfit); + + if ci + alpha = 0.05; + + [Y2,DELTA] = cat_stat_polyconf(p,xfit,S); + if isempty(color) && n_groups > 1 + plot_variance(xfit,Y2+DELTA,Y2-DELTA,color(i,:),0.05) + else + plot_variance(xfit,Y2+DELTA,Y2-DELTA,[0.75 0.75 0.75],0.1) + end + + % find standard error + std_err = sqrt(diag(inv(S.R)*inv(S.R')).*S.normr.^2./S.df)'; + + t_crit = tinv(1-alpha/2,S.df); + + ci = t_crit * std_err; + confidence_intervals = [p - ci; p + ci]; + + end + + % estimate R^2 + R2 = 1 - (S.normr/norm(Y(ind2) - mean(Y(ind2))))^2; + [cc,pp] = corrcoef(X(ind2),Y(ind2)); + if n_groups > 1 + fprintf('Group %d: R^2 = %g\tr = %g\tp = %g\n',i,R2,cc(1,2),pp(1,2)) + else + fprintf('R^2 = %g\tr = %g\tp = %g\n',R2,cc(1,2),pp(1,2)) + end + fprintf('Coefficients:\n') + for j = 1:numel(p) + if ci + fprintf('%g (CI %g %g)\n',p(j),confidence_intervals(1,j),confidence_intervals(2,j)) + else + fprintf('%g\n',p(j)) + end + end + if i == 1, hold on; end + end +end + +% check whether X has limited number of entries (and is rather categorical) +% and add jitter if defined +if n_categories_X < 30 && jitter + if exist('rng'), rng(1); end + X = X + add_range*randn(size(X)); +end + +lh = []; +if strmatch(lower(plottype), 'dscatter') + edges1 = linspace(minx, maxx, nbins(1)+1); + edges1 = [-Inf edges1(2:end-1) Inf]; + edges2 = linspace(miny, maxy, nbins(2)+1); + edges2 = [-Inf edges2(2:end-1) Inf]; + [n,p] = size(X); + bin = zeros(n,2); + + % Reverse the columns to put the first column of X along the horizontal + % axis, the second along the vertical. + [dum,bin(:,2)] = histc(X,edges1); + [dum,bin(:,1)] = histc(Y,edges2); + + % remove zero histogram entries that can't be used + ind = find(bin(:,1)==0 | bin(:,2)==0); + bin(ind,:) = []; + X(ind) = []; + Y(ind) = []; + + H = accumarray(bin,1,nbins([2 1])) ./ n; + G = smooth1D(H,nbins(2)/lambda); + F = smooth1D(G',nbins(1)/lambda)'; + + if ~isempty(color), fprintf('Color flag does not work with dscatter plottype.\n'); end + F = F./max(F(:)); + ind = sub2ind(size(F),bin(:,1),bin(:,2)); + col = F(ind); + if filled + h{1} = scatter(X,Y,msize,col,marker,'filled'); + else + h{1} = scatter(X,Y,msize,col,marker); + end + lh = [lh h{i}]; +else + if ~isempty(color) + for i = 1:n_groups + ind2 = group == i; + ind2 = ind2(ind); + + if numel(X(ind2)) == size(color,1) + col = color; + else + col = color(i,:); + end + + if filled + h{i} = scatter(X(ind2),Y(ind2),msize,col,marker,'filled'); + else + h{i} = scatter(X(ind2),Y(ind2),msize,col,marker); + end + lh = [lh h{i}]; + if i==1, hold on; end + end + else + if filled + h{1} = scatter(X,Y,msize,marker,'filled'); + else + h{1} = scatter(X,Y,msize,marker); + end + lh = h{1}; + end +end + +colormap(cmap) +set(gca,'FontSize',fontsize); + +if fit_poly + for i = 1:n_groups + if isempty(color) + pl{i} = plot(xfit,yfit{i},'k'); + else + pl{i} = plot(xfit,yfit{i},'Color',color(i,:)); + end + lh = [lh pl{i}]; + set(pl{i},'LineWidth',1) + if minx > 0 && minx < 1e-4 + xl = xlim; + xlim([0 xl(2)]) + end + % prevent that all values are on y-axis if min=0 + if minx == 0 + xl = xlim; + xlim([-0.05*maxx xl(2)]) + end + if miny > 0 && miny < 1e-4 + yl = ylim; + ylim([0 yl(2)]) + end + end + hold off +end + +if showlegend + if n_groups > 1 + if fit_poly + legend(lh,lnames); + else + legend(lnames(1:2:end)); + end + else + if fit_poly + legend(lh,lnames); + else + legend(lnames(1:2:end)); + end + end +end + +if logy + set(gca,'yscale','log'); +end + +if nargout > 0 + hAxes = get(h,'parent'); +end + +if ~isempty(img) + saveas(h{1},img); +end + +%%%% This method is quicker for symmetric data. +% function Z = filter2D(Y,bw) +% z = -1:(1/bw):1; +% k = .75 * (1 - z.^2); +% k = k ./ sum(k); +% Z = filter2(k'*k,Y); +function Z = smooth1D(Y,lambda) +[m,n] = size(Y); +E = eye(m); +D1 = diff(E,1); +D2 = diff(D1,1); +P = lambda.^2 .* D2'*D2 + 2.*lambda .* D1'*D1; +Z = (E + P) \ Y; + +function [y, delta] = cat_stat_polyconf(p,x,S,varargin) +%POLYCONF Polynomial evaluation and confidence interval estimation. +% Y = POLYCONF(P,X) returns the value of a polynomial P evaluated at X. P +% is a vector of length N+1 whose elements are the coefficients of the +% polynomial in descending powers. +% +% Y = P(1)*X^N + P(2)*X^(N-1) + ... + P(N)*X + P(N+1) +% +% If X is a matrix or vector, the polynomial is evaluated at all points +% in X. See also POLYVALM for evaluation in a matrix sense. +% +% [Y,DELTA] = POLYCONF(P,X,S) uses the optional output, S, created by +% POLYFIT to generate 95% prediction intervals. If the coefficients in P +% are least squares estimates computed by POLYFIT, and the errors in the +% data input to POLYFIT were independent, normal, with constant variance, +% then there is a 95% probability that Y +/- DELTA will contain a future +% observation at X. +% +% [Y,DELTA] = POLYCONF(P,X,S,'NAME1',VALUE1,'NAME2',VALUE2,...) specifies +% optional argument name/value pairs chosen from the following list. +% Argument names are case insensitive and partial matches are allowed. +% +% Name Value +% 'alpha' A value between 0 and 1 specifying a confidence level of +% 100*(1-alpha)%. Default is alpha=0.05 for 95% confidence. +% 'mu' A two-element vector containing centering and scaling +% parameters as computed by polyfit. With this option, +% polyconf uses (X-MU(1))/MU(2) in place of x. +% 'predopt' Either 'observation' (the default) to compute intervals for +% predicting a new observation at X, or 'curve' to compute +% confidence intervals for the polynomial evaluated at X. +% 'simopt' Either 'off' (the default) for non-simultaneous bounds, +% or 'on' for simultaneous bounds. +% +% See also POLYFIT, POLYTOOL, POLYVAL, INVPRED, POLYVALM. + +% For backward compatibility we also accept the following: +% [...] = POLYCONF(p,x,s,ALPHA) +% [...] = POLYCONF(p,x,s,alpha,MU) + +% Copyright 1993-2009 The MathWorks, Inc. +% $Revision$ $Date$ + +error(nargchk(2,Inf,nargin,'struct')); + +alpha = []; +mu = []; +doobs = true; % predict observation rather than curve estimate +dosim = false; % give non-simultaneous intervals +if nargin>3 + if ischar(varargin{1}) + % Syntax with parameter name/value pairs + okargs = {'alpha' 'mu' 'predopt' 'simopt'}; + defaults = {0.05 [] 'obs' 'off'}; + [eid emsg alpha mu predopt simopt] = ... + internal.stats.getargs(okargs,defaults,varargin{:}); + if ~isempty(eid) + error(sprintf('stats:polyconf:%s',eid),emsg); + end + + i = find(strncmpi(predopt,{'curve';'observation'},length(predopt))); + if ~isscalar(i) + error('stats:polyconf:BadPredOpt', ... + 'PREDOPT must be one of the strings ''curve'' or ''observation''.'); + end + doobs = (i==2); + + i = find(strncmpi(simopt,{'on';'off'},length(simopt))); + if ~isscalar(i) + error('stats:polyconf:BadSimOpt', ... + 'SIMOPT must be one of the strings ''on'' or ''off''.'); + end + dosim = (i==1); + else + % Old syntax + alpha = varargin{1}; + if numel(varargin)>=2 + mu = varargin{2}; + end + end +end +if nargout > 1 + if nargin < 3, S = []; end % this is an error; let polyval handle it + if nargin < 4 || isempty(alpha) + alpha = 0.05; + elseif ~isscalar(alpha) || ~isnumeric(alpha) || ~isreal(alpha) ... + || alpha<=0 || alpha>=1 + error('stats:polyconf:BadAlpha',... + 'ALPHA must be a scalar between 0 and 1.'); + end + if isempty(mu) + [y,delta] = polyval(p,x,S); + else + [y,delta] = polyval(p,x,S,mu); + end + if doobs + predvar = delta; % variance for predicting observation + else + s = S.normr / sqrt(S.df); + delta = delta/s; + predvar = s*sqrt(delta.^2 - 1); % get uncertainty in curve estimation + end + if dosim + k = length(p); + crit = sqrt(k * finv(1-alpha,k,S.df)); % Scheffe simultaneous value + else + crit = tinv(1-alpha/2,S.df); % non-simultaneous value + end + delta = crit * predvar; +else + if isempty(mu) + y = polyval(p,x); + else + y = polyval(p,x,[],mu); + end +end + +function x = tinv(p,v) +% TINV Inverse of Student's T cumulative distribution function (cdf). +% X=TINV(P,V) returns the inverse of Student's T cdf with V degrees +% of freedom, at the values in P. +% +% The size of X is the common size of P and V. A scalar input +% functions as a constant matrix of the same size as the other input. +% +% This is an open source function that was assembled by Eric Maris using +% open source subfunctions found on the web. + +if nargin < 2 + error('Requires two input arguments.'); +end + +[errorcode p v] = distchck(2,p,v); + +if errorcode > 0 + error('Requires non-scalar arguments to match in size.'); +end + +% Initialize X to zero. +x=zeros(size(p)); + +k = find(v < 0 | v ~= round(v)); +if any(k) + tmp = NaN; + x(k) = tmp(ones(size(k))); +end + +k = find(v == 1); +if any(k) + x(k) = tan(pi * (p(k) - 0.5)); +end + +% The inverse cdf of 0 is -Inf, and the inverse cdf of 1 is Inf. +k0 = find(p == 0); +if any(k0) + tmp = Inf; + x(k0) = -tmp(ones(size(k0))); +end +k1 = find(p ==1); +if any(k1) + tmp = Inf; + x(k1) = tmp(ones(size(k1))); +end + +k = find(p >= 0.5 & p < 1); +if any(k) + z = betainv(2*(1-p(k)),v(k)/2,0.5); + x(k) = sqrt(v(k) ./ z - v(k)); +end + +k = find(p < 0.5 & p > 0); +if any(k) + z = betainv(2*(p(k)),v(k)/2,0.5); + x(k) = -sqrt(v(k) ./ z - v(k)); +end + +%%%%%%%%%%%%%%%%%%%%%%%%% +% SUBFUNCTION distchck +%%%%%%%%%%%%%%%%%%%%%%%%% + +function [errorcode,varargout] = distchck(nparms,varargin) +%DISTCHCK Checks the argument list for the probability functions. + +errorcode = 0; +varargout = varargin; + +if nparms == 1 + return; +end + +% Get size of each input, check for scalars, copy to output +isscalar = (cellfun('prodofsize',varargin) == 1); + +% Done if all inputs are scalars. Otherwise fetch their common size. +if (all(isscalar)), return; end + +n = nparms; + +for j=1:n + sz{j} = size(varargin{j}); +end +t = sz(~isscalar); +size1 = t{1}; + +% Scalars receive this size. Other arrays must have the proper size. +for j=1:n + sizej = sz{j}; + if (isscalar(j)) + t = zeros(size1); + t(:) = varargin{j}; + varargout{j} = t; + elseif (~isequal(sizej,size1)) + errorcode = 1; + return; + end +end + +%%%%%%%%%%%%%%%%%%%%%%%%%%% +% SUBFUNCTION betainv +%%%%%%%%%%%%%%%%%%%%%%%%%%% + +function x = betainv(p,a,b) +%BETAINV Inverse of the beta cumulative distribution function (cdf). +% X = BETAINV(P,A,B) returns the inverse of the beta cdf with +% parameters A and B at the values in P. +% +% The size of X is the common size of the input arguments. A scalar input +% functions as a constant matrix of the same size as the other inputs. +% +% BETAINV uses Newton's method to converge to the solution. + +% Reference: +% [1] M. Abramowitz and I. A. Stegun, ""Handbook of Mathematical +% Functions"", Government Printing Office, 1964. + +% B.A. Jones 1-12-93 + +if nargin < 3 + error('Requires three input arguments.'); +end + +[errorcode p a b] = distchck(3,p,a,b); + +if errorcode > 0 + error('Requires non-scalar arguments to match in size.'); +end + +% Initialize x to zero. +x = zeros(size(p)); + +% Return NaN if the arguments are outside their respective limits. +k = find(p < 0 | p > 1 | a <= 0 | b <= 0); +if any(k) + tmp = NaN; + x(k) = tmp(ones(size(k))); +end + +% The inverse cdf of 0 is 0, and the inverse cdf of 1 is 1. +k0 = find(p == 0 & a > 0 & b > 0); +if any(k0) + x(k0) = zeros(size(k0)); +end + +k1 = find(p==1); +if any(k1) + x(k1) = ones(size(k1)); +end + +% Newton's Method. +% Permit no more than count_limit interations. +count_limit = 100; +count = 0; + +k = find(p > 0 & p < 1 & a > 0 & b > 0); +pk = p(k); + +% Use the mean as a starting guess. +xk = a(k) ./ (a(k) + b(k)); + + +% Move starting values away from the boundaries. +if xk == 0 + xk = sqrt(eps); +end +if xk == 1 + xk = 1 - sqrt(eps); +end + + +h = ones(size(pk)); +crit = sqrt(eps); + +% Break out of the iteration loop for the following: +% 1) The last update is very small (compared to x). +% 2) The last update is very small (compared to 100*eps). +% 3) There are more than 100 iterations. This should NEVER happen. + +while(any(abs(h) > crit * abs(xk)) && max(abs(h)) > crit ... + & count < count_limit) + + count = count+1; + h = (betacdf(xk,a(k),b(k)) - pk) ./ betapdf(xk,a(k),b(k)); + xnew = xk - h; + +% Make sure that the values stay inside the bounds. +% Initially, Newton's Method may take big steps. + ksmall = find(xnew < 0); + klarge = find(xnew > 1); + if any(ksmall) || any(klarge) + xnew(ksmall) = xk(ksmall) /10; + xnew(klarge) = 1 - (1 - xk(klarge))/10; + end + + xk = xnew; +end + +% Return the converged value(s). +x(k) = xk; + +if count==count_limit + fprintf('\nWarning: BETAINV did not converge.\n'); + str = 'The last step was: '; + outstr = sprintf([str,'%13.8f'],h); + fprintf(outstr); +end + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% SUBFUNCTION betapdf +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +function y = betapdf(x,a,b) +%BETAPDF Beta probability density function. +% Y = BETAPDF(X,A,B) returns the beta probability density +% function with parameters A and B at the values in X. +% +% The size of Y is the common size of the input arguments. A scalar input +% functions as a constant matrix of the same size as the other inputs. + +% References: +% [1] M. Abramowitz and I. A. Stegun, ""Handbook of Mathematical +% Functions"", Government Printing Office, 1964, 26.1.33. + +if nargin < 3 + error('Requires three input arguments.'); +end + +[errorcode x a b] = distchck(3,x,a,b); + +if errorcode > 0 + error('Requires non-scalar arguments to match in size.'); +end + +% Initialize Y to zero. +y = zeros(size(x)); + +% Return NaN for parameter values outside their respective limits. +k1 = find(a <= 0 | b <= 0 | x < 0 | x > 1); +if any(k1) + tmp = NaN; + y(k1) = tmp(ones(size(k1))); +end + +% Return Inf for x = 0 and a < 1 or x = 1 and b < 1. +% Required for non-IEEE machines. +k2 = find((x == 0 & a < 1) | (x == 1 & b < 1)); +if any(k2) + tmp = Inf; + y(k2) = tmp(ones(size(k2))); +end + +% Return the beta density function for valid parameters. +k = find(~(a <= 0 | b <= 0 | x <= 0 | x >= 1)); +if any(k) + y(k) = x(k) .^ (a(k) - 1) .* (1 - x(k)) .^ (b(k) - 1) ./ beta(a(k),b(k)); +end + +%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% SUBFUNCTION betacdf +%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +function p = betacdf(x,a,b) +%BETACDF Beta cumulative distribution function. +% P = BETACDF(X,A,B) returns the beta cumulative distribution +% function with parameters A and B at the values in X. +% +% The size of P is the common size of the input arguments. A scalar input +% functions as a constant matrix of the same size as the other inputs. +% +% BETAINC does the computational work. + +% Reference: +% [1] M. Abramowitz and I. A. Stegun, ""Handbook of Mathematical +% Functions"", Government Printing Office, 1964, 26.5. + +if nargin < 3 + error('Requires three input arguments.'); +end + +[errorcode x a b] = distchck(3,x,a,b); + +if errorcode > 0 + error('Requires non-scalar arguments to match in size.'); +end + +% Initialize P to 0. +p = zeros(size(x)); + +k1 = find(a<=0 | b<=0); +if any(k1) + tmp = NaN; + p(k1) = tmp(ones(size(k1))); +end + +% If is X >= 1 the cdf of X is 1. +k2 = find(x >= 1); +if any(k2) + p(k2) = ones(size(k2)); +end + +k = find(x > 0 & x < 1 & a > 0 & b > 0); +if any(k) + p(k) = betainc(x(k),a(k),b(k)); +end + +% Make sure that round-off errors never make P greater than 1. +k = find(p > 1); +p(k) = ones(size(k)); + + +%%%%%%%%%%%%%%%%%%%%%%%%%%% +% SUBFUNCTION nejm +%%%%%%%%%%%%%%%%%%%%%%%%%%% +function C = nejm + C = [ + '#BC3C29' + '#0072B5' + '#E18727' + '#20854E' + '#7876B1' + '#6F99AD' + '#FFDC91' + '#EE4C97' + '#8C564B' + '#BCBD22' + '#00A1D5' + '#374E55' + '#003C67' + '#8F7700' + '#7F7F7F' + '#353535' + ]; + C = reshape(sscanf(C(:,2:end)','%2x'),3,[]).'/255; + +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_surf_flipvalues.m",".m","1428","43","function cat_surf_flipvalues(P) +% ______________________________________________________________________ +% Mirror values in 32k-meshes to the opposite hemisphere +% +% This function allows to flip the resampled data of symmetrical 32k-meshes. +% The flipped mesh is indicated with a prepended 'flip_' in the dataname +% of the file. +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +if ~nargin + P = spm_select(Inf,'mesh','select 32k-meshes to flip',{},pwd,'mesh.*.resampled_32k'); +end + +n = size(P,1); +for i=1:n + mesh_name = deblank(P(i,:)); + M = gifti(mesh_name); + + % check that values are in the mesh and the data size is that of a 32k mesh + if isfield(M,'cdata') && numel(M.cdata) ~= 64984 + fprintf('ERROR: %s does not contain resampled 32k-mesh values.\n',mesh_name); + break + end + + % flip values + cdata1 = M.cdata(1:32492); + cdata2 = M.cdata(32493:64984); + M.cdata = [cdata2; cdata1]; + + % rename dataname + sinfo = cat_surf_info(mesh_name); + flipped_name = char(cat_surf_rename(mesh_name,'dataname',['flipped_' sinfo.dataname])); + + save(M, flipped_name, 'Base64Binary'); + fprintf('Save flipped file %s\n',flipped_name); +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_io_volctype.m",".m","14126","379","function out = cat_io_volctype(varargin) +% ______________________________________________________________________ +% Convert datatype of images, to have more space on your hard-disk. +% In example most tissue classifications can saved as uint8 or uint16 +% rather than double or single. If the image contains negative values +% int8/16 is rather used than uint8/16. +% +% out = cat_io_volctype(job) +% +% job +% .data .. images +% .verb .. be verbose (default=1) +% .lazy .. do not reprocess files (default=0); +% .prefix .. prefix with the keyword PARA that is replaced by the +% nifti datatype (spm_input if undefined) +% .suffix .. suffix with the keyword PARA that is replaced by the +% nifti datatype (default='') +% .intscale .. scaling type of the data +% (0: no, 1: 0..1, 0..2^8-1, 2: 0..2^16-1) +% .ctype .. nifti data type (see spm_type) +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +%% choose images + + if nargin == 0 + job.data = cellstr(spm_select([1 Inf],'image','Select images')); + else + job = varargin{1}; + end + def.verb = 1; + def.lazy = 0; + def.suffix = ''; + def.intscale = 0; + def.returnOnlyFilename = 0; + def.ctype = 16; + def.cvals = 1; + job = cat_io_checkinopt(job,def); + + + % define images - return in case of no input + if nargin==0 || ~isfield(job,'data') || isempty(job.data) + % interatcive + job.data = cellstr(spm_select([1 Inf],'image','Select images')); + else + job.data = cellstr(job.data); + end + if isempty(job.data) || isempty(job.data{1}), return; end + + + % choose output datatype + if nargin + if ischar(job.ctype) + ctype = spm_type(job.ctype); + else + ctype = job.ctype; + end + else + % interactive + V = spm_vol(strrep(job.data{1},',1','')); + switch V.dt(1) + case {2,512}, dtype = 1; % uint8 + case {4,256}, dtype = 3; % int8 + otherwise, dtype = 2; % uint16 + end + spm_clf('Interactive'); + ctype = spm_input('Datatype',1,'(u)int8|(u)int16|single',[2,512,16],dtype); + end + + + % choose data limiting (range) and define histogram scaling cvals (with 0 for auto) + if ~nargin && any(ctype==[2 4 256 512]) + + if isfield(job,'range') + range = job.range; + else + range = spm_input('Range','+1','100%|99.99%|%',[100,99.99,-1],2); + end + if range == -1 + range = min(100,max(eps,spm_input('Range in %:','+1','r',99.99,1))); + end + else + range = job.range; + end + + + % stepsize (0=auto) + if ~nargin + Y = spm_read_vols(V); + cvals = spm_input(sprintf('Stepsize (0=auto;min:%4.2f;max:%4.2f):',min(Y(:)),max(Y(:))),'+1','r',0,1); + else + cvals = job.cvals; + end + + + % choose prefix + if ~isfield(job,'prefix') + job.prefix = spm_input('Filename prefix (empty=overwrite!)','+1','s',[spm_type(ctype) '_'],1); + end + if strcmp(job.prefix,'PARA') + job.prefix = [spm_type(ctype) '_']; + end + if ~strcmp(job.prefix,'PARA') && strcmp(job.suffix,'PARA') + job.prefix = ['_' spm_type(ctype)]; + end + for si=1:numel(job.data) + [pp,ff,ee,dd] = spm_fileparts(job.data{si}); + out.files{si} = fullfile(pp,[job.prefix ff job.suffix ee dd]); + end + if job.returnOnlyFilename, return; end + +% +% +% 2 'uint8 ' +% 4 'int16 ' +% 8 'int32 ' +% 16 'float32' +% 64 'float64' +% 256 'int8 ' +% 512 'uint16 ' +% 768 'uint32 ' + + + %% convert + if isfield(job,'process_index') && job.process_index && job.verb + spm('FnBanner',mfilename); + end + spm_clf('Interactive'); + spm_progress_bar('Init',numel(job.data),'SANLM-Filtering','Volumes Complete'); + for si=1:numel(job.data) + if job.lazy==0 || cat_io_rerun( out.files{si} , job.data{si} ) + V = spm_vol(strrep(job.data{si},',1','')); + Y = spm_read_vols(V); + + % reduce volumes to be more robust and faster + vx_vol = sqrt(sum(V.mat(1:3,1:3).^2)); + Yr = cat_vol_resize(Y,'reduceV',vx_vol,2,32); + + [pp,ff,ee] = spm_fileparts(V.fname); + + % intensity scaling / limitation + [Yt,clim] = cat_stat_histth(Yr,range); clear Yt; %#ok + + + + % extend datatype uint to int or vice versa + % ------------------------------------------------------------------- + changetype = 0; % 0-ignore, 1-warn, 2-change + if changetype + switch ctype %#ok + case {2,4,8,256,512,768} % integer types + if any(clim<0) % negative value use int + if changetype==2 + cat_io_cprintf('warning',[' cat_io_volctype:useInt: '... + 'Switch from unsigned integer to integer datatype.\n']); + switch ctype %V.dt(1) + case 2, ctype = 256; + case 512, ctype = 4; + case 768, ctype = 8; + end + else + cat_io_cprintf('note',[' cat_io_volctype:useUint: '... + 'Selected datatype does not support the (small) negative values in the image.\n']); + end + else % otherwise use uint + if changetype==2 + cat_io_cprintf('warning',[' cat_io_volctype:useInt: '... + 'Switch from integer to unsigned integer datatype because no negative values exist.\n']); + switch ctype %V.dt(1) + case 256, ctype = 2; + case 4, ctype = 512; + case 8, ctype = 768; + end + else + cat_io_cprintf('note',[' cat_io_volctype:useUint: '... + 'Selected datatype does not support the (small) negative values in the image.\n']); + end + end + end + end + + + + % data type changes ... to simple ... + % ------------------------------------------------------------------- + if ( ctype ~= 0 && ctype ~= V.dt(1) ) + if job.intscale == 1 || job.intscale == -1 + % fixed scaling between 0 and 1 (uint) or -1 and 1 (int) + switch ctype + case 2, V.pinfo(1) = 1 / 2^8; % uint8 + case 512, V.pinfo(1) = 1 / 2^16; % uint16 + case 768, V.pinfo(1) = 1 / 2^32; % uint32 + case 256, V.pinfo(1) = 1 / 2^8 * 2; % int8 + case 4, V.pinfo(1) = 1 / 2^16 * 2; % int16 + case 8, V.pinfo(1) = 1 / 2^32 * 2; % int32 + otherwise, V.pinfo(1) = 1; % float/double + end + elseif isinf( job.intscale ) + % dynamic scaling based on the maximal absolute value + switch ctype + case 2, V.pinfo(1) = max(abs(clim)) / 2^8; % uint8 + case 512, V.pinfo(1) = max(abs(clim)) / 2^16; % uint16 + case 768, V.pinfo(1) = max(abs(clim)) / 2^32; % uint32 + case 256, V.pinfo(1) = max(abs(clim)) / 2^8 * 2; % int8 + case 4, V.pinfo(1) = max(abs(clim)) / 2^16 * 2; % int16 + case 8, V.pinfo(1) = max(abs(clim)) / 2^32 * 2; % int32 + otherwise, V.pinfo(1) = 1; % float/double + end + elseif job.intscale == 2 || job.intscale == 256 + V.pinfo(1) = 1; % just to mention this case clearly + else + V.pinfo(1) = 1; + end + end + + + % add info about change of datatype + if ctype ~= 0 + V.dt(1) = ctype; + descrip = [V.descrip ' > ' spm_type(ctype)]; + else + descrip = V.descrip; + end + + + % replace NAN and INF in case of integer + switch V.dt(1) + case {2,4,256,512} + Y(isnan(Y)) = 0; + Y(isinf(Y) & Y<0) = min(Y(:)); + Y(isinf(Y) & Y>0) = max(Y(:)); + end + + switch V.dt(1) + case 2, ivals = [0 V.pinfo(1)] * 2^8; + case 512, ivals = [0 V.pinfo(1)] * 2^16; + case 768, ivals = [0 V.pinfo(1)] * 2^32; + case 256, ivals = [-V.pinfo(1) V.pinfo(1)] * (2^8 / 2); + case 4, ivals = [-V.pinfo(1) V.pinfo(1)] * (2^16 / 2); + case 8, ivals = [-V.pinfo(1) V.pinfo(1)] * (2^32 / 2); + otherwise, ivals = [-inf inf]; + end + + + if job.intscale ~= 0 % ctype ~= 0 && + switch job.intscale + case 1 % range 0 to 1 + Y = ( Y - min(clim) ) / diff([min(clim),max(clim)]); + Yrd = round(Y / V.pinfo(1)) * V.pinfo(1); + case -1 % range -1 to 1 scaled around 0 + Y = Y / max( abs(clim) ); + Yrd = round(Y / V.pinfo(1)) * V.pinfo(1); + case {2,256} + ivals = [0 256]; + Y = ( Y - min(clim) ) / diff([min(clim),max(clim)]) * 256; + Yrd = round(Y); + otherwise + Yrd = round(Y / V.pinfo(1)) * V.pinfo(1); + end + else + Yrd = round(Y / V.pinfo(1)) * V.pinfo(1); + end + + + % estimate error measures + switch V.dt(1) + case {2,4,8,256,512,768} + intlimlow = sum( Y(:) < (ivals(1) - abs(ivals(1))*0.05) ) / numel(Y) * 100; + intlimhigh = sum( Y(:) > (ivals(2) + abs(ivals(2))*0.05) ) / numel(Y) * 100; + otherwise + intlimlow = 0; + intlimhigh = 0; + end + Yrd = max(ivals(1),min(ivals(2),Yrd)); + Yc = max(ivals(1),min(ivals(2),Y)); + RMSEf = sum(( ( Y(:) - Yrd(:) ) / max(clim) ).^2)^0.5; + RMSEl = sum(( ( Yc(:) - Yrd(:) ) / max(clim) ).^2)^0.5; + + + % print critical cases + if job.verb % || RMSEf>2 || RMSEl>2 || intlimlow > 2 || intlimhigh > 2 + switch V.dt(1) +% linked display image from sanlm + case {2,4,256,512} + QMC = cat_io_colormaps('marks+',17); + color = @(QMC2,m) QMC2(max(1,min(size(QMC,1),round(((m-1)*3)+1))),:); + rating = @(x,best,worst) cat_io_cprintf( color(QMC,min(10.5,max(0.5, ... + ((x-best) / (worst-best)) * 10 + 0.5))) , sprintf('%5.2f',x) ); + + if job.verb >= 1 && ctype>0 % not repeat for headtrimming (=.5) + cat_io_cprintf([0 0 0],sprintf(' %s(%s):',spm_type(ctype),spm_str_manip(job.data{si},'k40'))); + end + if 0 + cat_io_cprintf([0 0 0],sprintf('RSME-fullRange: ')); + rating(RMSEf,0,40); + cat_io_cprintf([0 0 0],sprintf(', RSME-inRange: ')); + rating(RMSEl,0,40); + cat_io_cprintf([0 0 0],sprintf(', interger cut-off(low,high): ')); + else + cat_io_cprintf([0 0 0],sprintf('RSME: ')); + rating(RMSEf,0,40); + cat_io_cprintf([0 0 0],sprintf(', int-cut-off(low,high): ')); + end + rating(intlimlow,0,40); fprintf('%%, '); + rating(intlimhigh,0,40); fprintf('%%.'); + if job.verb >= 1, fprintf('\n'); else, cat_io_cprintf([0 0 0],' '); end + otherwise + if ctype>0 + fprintf(' %s(%s)\n',spm_type(ctype),spm_str_manip(job.data{si},'k40')); + end + end + end + + %% print critical cases + msg = {'note','warning','error'}; + switch V.dt(1) + case {2,4,8,256,512,768} + if intlimlow > 2 || intlimhigh > 2 + fprintf('\n'); + end + if intlimlow > 2 + cat_io_cprintf(msg{round(max(1,min(3,intlimlow / 4)))},sprintf([' cat_io_volctype:intlimitlow: '... + 'Selected datatype/scaling cut off %0.2f%%%% of the low values (RMSE: %0.3f).\n'],intlimlow,RMSEf)); + end + if intlimhigh > 2 + cat_io_cprintf(msg{round(max(1,min(3,intlimhigh / 4)))},sprintf([' cat_io_volctype:intlimithigh: ' ... + 'Selected datatype/scaling cut off %0.2f%%%% of the high values (RMSE: %0.3f).\n'],intlimhigh,RMSEf)); + end + end + if ( intlimlow >= 10 || intlimhigh >= 10 ) && (any(V.dt(1) == [2,512,768])) && (job.intscale < 0) + cat_io_cprintf('error',sprintf([' cat_io_volctype:inoptimalType: ' ... + 'You selected an unsigned integer datatype but your data probalby needs signed integer.\n'],... + intlimhigh,RMSEf)); + elseif ( intlimlow >= 10 || intlimhigh >= 10 ) && any(V.dt(1) == [2,4,8,256,512,768]) + cat_io_cprintf('error',sprintf([' cat_io_volctype:inoptimalType: ' ... + 'The RMSE is unexpected high (%0.3f but should be strongly below 10). \n '... + 'Use a datatype that uses more bits supporting high accuracy (e.g. uint16 rather than uint8).\n'],RMSEf)); + end + + if ctype==0 + ctype = V.dt; + end + + + if ndims(Y)==4 + %% + V.fname = fullfile(pp,[job.prefix ff job.suffix ee]); + if exist(V.fname,'file'), delete(V.fname); end % delete required in case of smaller file size! + N = nifti; + N.dat = file_array(fullfile(pp,[job.prefix ff ee]),... + min([inf inf inf size(Y,4)],size(Y)),[ctype spm_platform('bigend')],0,job.cvals,0); + N.descrip = descrip; + N.mat = V.mat; + N.mat0 = V.private.mat0; + N.descrip = V.descrip; + create(N); + %Y(:,:,:,3) = Y(:,:,:,3) + Y(:,:,:,4); + N.dat(:,:,:,:) = Y(:,:,:,:); + else + %% + Vo = V; + Vo(1).fname = fullfile(pp,[job.prefix ff job.suffix ee]); + Vo(1).descrip = descrip; + Vo(1).dt = [ctype spm_platform('bigend')]; + Vo = rmfield(Vo,'private'); + if exist(Vo(1).fname,'file'), delete(Vo(1).fname); end % delete required in case of smaller file size! + spm_write_vol(Vo,Y); + end + spm_progress_bar('Set',si); + end + spm_progress_bar('Clear'); + end +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_surf_GI3D.m",".m","5402","149","function [S,SH] = cat_surf_GI3D(S,D,R,opt) +% ========================================================================= +% Next version of local gyrification index calculation. The laplace-method +% is used to map the area of the face of a given surface S to the hull +% given by D and R. Because lapace mapping the vertices with equal +% triangulation produce errors (at watershed of laplace field in gyral +% regions where on e vertex move to the other side and the face get +% corrupt.) we only map vertices to their hull position and retriangulate +% the surface with delaunay. Next, voroi area of this vertices is estimated +% to get the outer surface area (OSA) and the inner surface area (ISA) to +% calculate the GI. +% _________________________________________________________________________ +% INPUT: +% S.faces = Surface faces +% S.vertices = Surface points +% D = Tissues image for laplace-filter +% R = filter region +% opt = options... +% . = 0.02 (lapalce error criteria) +% .streamopt = [,] (stepsize and maxiumum length of a streamline) +% +% OUTPUT: +% S.faces = Surface faces +% S.vertices = Surface points +% S.area = Surface area for each vertex +% SH.faces = Hull surface faces +% SH.vertices = Hull surface faces +% SH.area = Hull surface area for each vertex +% +% S.GI = Gyrifcation Index for points (S.area / S.Harea) +% S.SL = streamlength between S.vertices and S.Hvertices +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + % pinterpol = (2^opt.interpol)-(2^opt.interpol-1)*(opt.interpol>0); + % if ~isfield(opt,'gridres'), opt.gridres = [1,1,1]; end + + % ATTENSION matlab-stream function only work with double! so don't + % convert vertices! + S.faces = single(S.faces); + + D = single(D); + R = single(R); + + % for correct smoother border (else WM blows to strong + D = D - 0.5*(single(D==1) & cat_vol_morph(D==0,'d')); + + % streamline calculation + % _______________________________________________________________________ + if ~exist('opt','var') opt = struct(); end + def.side = 'streams0'; + def.interpV = 1; + def.streamopt(1) = 0.01; % 0.05 + def.streamopt(2) = 1000 ./ def.streamopt(1); + opt = cat_io_checkinopt(opt,def); + + SL = cat_surf_epivolsurf(D,R,opt,S); + SL.OP = SL.L(:,:,7); + S.Hvertices = SL.OP; + S.SL = SL.SL; + S.streams = SL.streams; + + + SH.vertices = SL.OP; + SH.faces = S.faces; + SH.facevertexcdata = SL.SL; + + % GI: gyrification index + % _______________________________________________________________________ + % Calculate the face areas of the surface and it's hull (see surfacearea) + % and map them to the vertices (see verticemapping). + % The GI is the ratio between the inner and outer area. + S = surfacearea(S,''); S.farea = S.area; S = verticemapping(S,'area'); + S = surfacearea(S,'H'); S.Hfarea = S.Harea; S = verticemapping(S,'Harea'); + S.GI = S.area ./ S.Harea; + S.GIl = log(S.GI); + %fprintf(1,'|GI:%0.0f',toc); tic + +end + + +function S = surfacearea(S,fname) +% calculate surface area of the faces and also map it to the vertices +% IN: S.*vertices, S.faces +% OUT: S.*verticesarea, S.*facearea + + fa = [fname 'area']; fd = [fname 'dist']; + ndim = size(S.vertices,2); + + % facearea (Horonsche Form) + S = surfacedistance(S,fname); + if ndim==2 + S.(fa) = S.(fd); + elseif ndim==3 + facesp = sum(S.(fd),2) / 2; % s = (a + b + c) / 2; + S.(fa) = (facesp .* (facesp - S.(fd)(:,1)) .* (facesp - S.(fd)(:,2)) .* (facesp - S.(fd)(:,3))).^0.5; % area=sqrt(s*(s-a)*(s-b)*(s-c)); + end + % numberical (to small point diffences) and mapping broblems (crossing of streamlines) + % -> correction because this is theoretical not possible (laplace field theorie) + S.(fa)(S.(fa)==0) = eps; % to small values + S.(fa) = abs(S.(fa)); % streamline-crossing +end +function S = verticemapping(S,fname) +% mapping of facedata to vertices + + data = zeros(size(S.vertices,1),1); + [v,f] = sort(S.faces(:)); + [f,fj] = ind2sub(size(S.faces),f); %#ok + far = S.(fname)(f); + for i=1:numel(v) + data(v(i)) = data(v(i)) + far(i)/3; + end + %data = data / size(S.vertices,2); % Schwerpunkt... besser Voronoi, aber wie bei ner Oberfl??che im Raum??? + S = rmfield(S,fname); + S.(fname) = data; +end + +%{ +function S = verticeneighbor(S) + if ~isfield(S,'nb') + S.nb = [S.vertices(:,1),S.vertices(:,2); + S.vertices(:,2),S.vertices(:,3); + S.vertices(:,3),S.vertices(:,1)]; + end +end +%} + +function S = surfacedistance(S,fname) +% 2D: d(AB) +% 3D: [c,a,b] = d(AB),d(BC),d(CA) + v = [fname 'vertices']; fd = [fname 'dist']; + ndim = size(S.vertices,2); + + % facearea (Horonsche Form) + if ndim==2 + S.(fd) = sum( (S.(v)(S.faces(:,1),:) - S.(v)(S.faces(:,2),:)).^2 , 2) .^ 0.5; + elseif ndim==3 + S.(fd) = [sum( (S.(v)(S.faces(:,1),:) - S.(v)(S.faces(:,2),:)).^2 , 2) .^ 0.5, ... + sum( (S.(v)(S.faces(:,2),:) - S.(v)(S.faces(:,3),:)).^2 , 2) .^ 0.5, ... + sum( (S.(v)(S.faces(:,3),:) - S.(v)(S.faces(:,1),:)).^2 , 2) .^ 0.5]; % [c,a,b] = d(AB),d(BC),d(CA) + end +end +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_vbdist.m",".m","1429","37","%cat_vbdist Voxel-based euclidean distance calculation. +% Calculates the euclidean distance without PVE to an object in P with a +% boundary of 0.5 for all voxels within a given mask M that should define +% a convex hull with direct connection between object and estimation +% voxels. +% +% [D,I,L] = vbdist(P[,M]) +% +% P (single) input image with zero for non elements +% M (logical) mask to limit the distance calculation roughly, e.g., to +% the brain defined by a convex hull +% WARNING: Voxels have to see objects within the mask! +% D (single) distance image +% L (uint8) label map +% I (uint32) index of nearest point +% +% Examples: +% % (1) distance from two points with a simple mask +% A = zeros(50,50,3,'single'); A(15,25,2)=1; A(35,25,2)=1; +% B = false(size(A)); B(5:end-5,5:end-5,:) = true; +% D = cat_vbdist(A,B); +% ds('d2sm','',1,A/3+B/3+1/3,D/20,2); +% +% % (2) not working mask definition +% B = false(size(A)); B(5:end-5,5:end-5,:) = true; +% B(10:end-10,10:end-10,:) = false; +% D = cat_vbdist(A,B); +% ds('d2sm','',1,A/3+B/3+1/3,D/20,2); +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_vol_resize.m",".m","42826","1097","function varargout = cat_vol_resize(Y, action, varargin) +%cat_vol_resize. Temporary cropping, down- and upsampling of volumes. +% The function was created to temporary crop, down- and upsample images to +% support faster or more accurate processing. The function is also used +% for the CAT resampling batch calling cat_vol_resize(job) with job as +% SPM matlabbatch structure to processes larger set of files. +% +% [Yout,res] = cat_vol_resize(Yin, action, varargin) +% +% Yin .. input volumes +% Yout .. output volumes +% res .. structure to restore the original image properties +% action .. operation that influence the following varargin parameters: +% +% Actions with general command - for details use subfunction help: +% (1) reducev;"">reducev & dereducev +% Temporary use of lower (isotropic) resolutions. +% [Yr, res] = cat_vol_resize( Y, 'reduceV', vx_vol, vx_volr [, minsize, method] ); +% [Yr1,..,Yrn, res] = cat_vol_resize( {Y1,..,Yn}, res [, method] ); +% +% (2) reduceBrain;"">crop/reduceBrain & uncrop/dereduceBrain +% Temporar cropping of volumes, e.g. by remove air around brain. +% [Yb,BB] = cat_vol_resize( Y , 'reduceBrain' , vx_vol [, 10, Yb] ); +% Y2b = cat_vol_resize( Y2, 'reduceBrain' , vx_vol , BB ); +% Y3 = cat_vol_resize( Yb, 'dereduceBrain', BB ); +% +% (3) interpi;"">interp & deinterp +% Temporary use of higher/fixed resolutions. +% +% (4) interpihdr;"">interphdr +% General (internal) resampling functions. +% +% (5) cat_vol_resize_test;"">test +% Unit test function with basic calls and simple figure output. +% +% See also: +% spm_imcalc, cat_vol_imcalc, cat_vol_headtrimming +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + if ~license('test', 'Statistics_Toolbox') + error('This function requires the ""Statistics and Machine Learning Toolbox"" of MATLAB.\n') + end + + if nargin == 0, help cat_vol_resize; return; end + if isempty(Y), varargout{1} = Y; return; end + + + if nargin == 1 + % job input structure for SPM batch + if isstruct(Y) + varargout{:} = resize_job(Y); + else + error('ERROR: cat_vol_resolution: not enough input!\n'); + end + + else + % actions + + % handel a cell of multipole volumes + if ndims(Y) > 2, YI = Y; clear Y; Y{1} = YI; end %#ok + + if ~strcmp(action,'test') + % handle and prepare output structure + if nargout < numel(Y) + warning('cat_vol_resize:notAllInputsWhereUsed', ... + 'Only %d images out of %d were used! ', nargout, numel(Y)); + elseif nargout > numel(Y) + 1 + warning('cat_vol_resize:tooManyOutputsElements', ... + 'Only %d images are give but %d needs to be assigned! ', numel(Y),nargout - 1); + end + varargout = cell(1,nargout); + end + + + % main processing + switch lower(action) + % (1) temporary reduce resolution + case 'reducev' + [varargout{:}] = reducev( Y , varargin{:} ); + case 'dereducev' + [varargout{:}] = dereducev( Y , varargin{:} ); + + % (2) temporary cropping + case {'reducebrain', 'crop'} + [varargout{:}] = reduceBrain( Y , varargin{:} ); + case {'dereducebrain', 'uncrop'} + [varargout{:}] = dereduceBrain( Y , varargin{:} ); + + % (3) temporary interpolation/resampling + case 'interp' + [varargout{:}] = interpi( Y , varargin{:} ); + case 'deinterp' + [varargout{:}] = deinterpi( Y , varargin{:} ); + + % (4) internal function for (de)interp + case {'interphdr'} + [varargout{:}] = interhdr( Y , varargin{:} ); + + % (5) unit test + case 'test' + cat_vol_resize_unittest; + + otherwise + error('ERROR: cat_vol_resize: unknown operation ""%s""!\n', action); + + end + + if 0 % ~strcmp(action,'test') + % RD20231220: to use the same type result in errors in existing code + for i = 1:numel(varargout) %#ok + if ~isstruct( varargout{i} ) + varargout{i} = cat_vol_ctype( varargout{i} , class(Y{i}) ); + end + end + end + end +end +% ====================================================================== +function varargout = resize_job(job) +%cat_vol_resize(job). Resize of files for SPM batch input structure. +% +% out = cat_vol_resize(job) +% +% job .. SPM batch input structure +% .interp .. interpolation method (see spm_slice_vol, eg: +% [0 - nearest, 1 - linear, 2..127 - Lagrange, ...] +% and additional special case for internal smoothing to +% include neighborhood information while downsampling +% using the modulus of 1000, eg. 1001 for smoothing + +% linear sampling. +% .prefix .. file name prefix (default = 'r') +% 'auto' - automatic prefix naming by processing parameters +% .outdir .. write result into another directory (default = '') +% .verb .. display progress (default = 1) with spm_orthview link +% for comparisons +% .lazy .. avoid reprocessing (default = 0) +% .restype .. resampling parameter +% .scale .. scaling factor (eg. half/double resolution) +% .res .. finale resolution with one or three values in mm +% out .. output structure +% .res .. resulting files as cell for SPM batch dependencies. +% + + % set defaults + def.interp = 2; % interpolation method + def.prefix = 'r'; % file name prefix + def.outdir = ''; % write result into another directory + def.verb = 1; % display progress + def.lazy = 0; % avoid reprocessing + job = cat_io_checkinopt(job,def); + + + % automatic prefix naming by processing parameters + if strcmp( job.prefix , 'auto' ) + if isfield(job,'restype') && (isfield(job.restype,'Pref') || isfield(job.restype,'res')) + % resampling to a specific resolution e.g. to 1.5 mm for all images + if isfield(job.restype,'Pref') && ~isempty(job.restype.Pref) && ~isempty(job.restype.Pref{1}) + job.prefix = 'rimg_'; + elseif isfield(job.restype,'res') && ~isempty(job.restype.res) + if numel(job.restype.res)==1 + if job.restype.res == 0 + job.prefix = 'rorg_'; + else + job.prefix = sprintf('r%0.2f_',job.restype.res); + end + elseif numel(job.restype.res)==3 + job.prefix = sprintf('r%0.2fx%0.2fx%0.2f_',job.restype.res); + end + end + + elseif isfield(job,'restype') && isfield(job.restype,'scale') + % rescaling of all images by a specific factor, e.g. half resolution + if any( job.restype.scale~=1 ) + if numel(job.restype.scale)==3 + job.prefix = sprintf('rx%0.2fx%0.2fx%0.2f_',job.restype.scale); + elseif numel(job.restype.scale)==1 + if job.restype.scale == 1 + job.prefix = 'rorg_'; + else + job.prefix = sprintf('rx%0.2f_',repmat( job.restype.scale(1) , 1 , 3)); + end + else + job.prefix = sprintf('rx%0.2f_',job.restype.scale(1)); + end + else + job.prefix = 'rorg_'; + end + end + end + + varargout{1}.res = {}; + for fi = 1:numel(job.data) + stimef = clock; + + % filename setup + fnameres = spm_file(job.data{fi},'prefix',job.prefix); + [pp,ff,ee] = spm_fileparts(fnameres); + if ~isempty(job.outdir) && ~isempty(job.outdir{1}) + if ~exist(job.outdir{1},'dir'), mkdir(job.outdir{1}); end + pp = job.outdir{1}; + end + fnameres = fullfile(pp,[ff ee]); + varargout{1}.res{fi,1} = fnameres; + + % in case of lazy processing check if it is exsiting and may needs to be updated + if job.lazy && ~cat_io_rerun(job.data{fi},fnameres) + if job.verb, fprintf(' Exist %s\n',fnameres); end + else + V = spm_vol(job.data{fi}); + + % higher dimension data requires different reading + if isfield(V,'private') + dims = ndims(V.private.dat); + if dims>4 %########## + Nii = nifti(V.fname); + Y = single(Nii.dat(:,:,:,:,:)); + else + Y = spm_read_vols(V); + end + else + Y = spm_read_vols(V); + end + + if isfield(job,'restype') && (isfield(job.restype,'Pref') || isfield(job.restype,'res')) %&& all( (job.restype.scale)==1 ) + % call main function + + if isfield(job.restype,'Pref') && ~isempty(job.restype.Pref) && ~isempty(job.restype.Pref{1}) + % adapt to given image + Vref = spm_vol(char(job.restype.Pref)); + + % use smoothing for denoising in case of + if abs( job.interp ) >= 1000 + fs = max(0,(sqrt(sum(Vref.mat(1:3,1:3).^2)) ./ sqrt(sum(V.mat(1:3,1:3).^2)) ) - 1) / 2^floor(abs(job.interp)/1000 - 1); + spm_smooth(Y, Y, fs ); + end + + [Y,res] = cat_vol_resize(Y,'interphdr',V,sqrt(sum(Vref.mat(1:3,1:3)^2)),rem(job.interp,1000),Vref); + + elseif isfield(job.restype,'res') && ~isempty(job.restype.res) + % use defined resolution + + if abs( job.interp ) >= 1000 + fs = max(0,(job.restype.res ./ sqrt(sum(V.mat(1:3,1:3).^2))) - 1 ) / 2^floor(abs(job.interp)/1000 - 1); + spm_smooth(Y, Y, fs ); + end + + if all(job.restype.res == 0) + vx_vol = sqrt(sum(V.mat(1:3,1:3).^2)); + res = struct('hdrO',V,'hdrN',V,'sizeO',size(Y),'sizeN',size(Y),'resO',vx_vol,'resN',vx_vol); + else + [Y,res] = cat_vol_resize(Y,'interphdr',V,job.restype.res,rem(job.interp,1000)); + end + else + error('Undefined setting.'); + end + Vo = res.hdrN; Vo.fname = fnameres; + + elseif isfield(job,'restype') && isfield(job.restype,'scale') && any( job.restype.scale~=1 ) + % handle scaling + if numel(job.restype.scale)==3 + scale = job.restype.scale; + elseif numel(job.restype.scale)==1 + scale = repmat( job.restype.scale(1) , 1 , 3); + else + cat_io_cprintf('warn','Unclear value job.restype.scale use only first entry.\n'); + scale = job.restype.scale(1); + end + + Vo = V; + imat = spm_imatrix(Vo.mat); + imat(10:12) = imat(10:12) .* scale; + imat(7:9) = imat(7:9) .* scale; + imat(1:3) = imat(1:3) .* scale; + Vo.mat = spm_matrix(imat); + Vo.fname = fnameres; + + else + error('Undefined setting.'); + end + + + if isfield(Vo,'private'), Vo = rmfield(Vo,'private'); end + + + if exist(fnameres,'file'), delete(fnameres); end %strcmp(job.data{fi},fnameres) && + if exist('dims','var') && dims>3 + Ndef = nifti; + Ndef.dat = file_array(fnameres,size(Y),V.dt,0,V.pinfo(1),0); + Ndef.mat = Vo.mat; + Ndef.mat0 = Vo.mat; + Ndef.descrip = V.descrip; + create(Ndef); + if dims>4 + Ndef.dat(:,:,:,:,:) = Y; + else + Ndef.dat(:,:,:,:) = Y; + end + clear dims + else + spm_write_vol(Vo,Y); + end + + clear Y + + + if job.verb + % prepare a link to open the original and processed image with SPM + fprintf('%5.0fs, Output %s\n',etime(clock,stimef),... + spm_file(fnameres,'link',sprintf(... + ['spm_figure(''Clear'',spm_figure(''GetWin'',''Graphics'')); ' ... + 'spm_orthviews(''Reset''); ' ... remove old settings + 'ho = spm_orthviews(''Image'',''%s'' ,[0 0.51 1 0.49]); ',... top image + 'hf = spm_orthviews(''Image'',''%%s'',[0 0.01 1 0.49]);', ... bottom image + 'spm_orthviews(''Caption'', ho, ''original''); ', ... caption top image + 'spm_orthviews(''Caption'', hf, ''resized''); ', ... caption bottom image + 'spm_orthviews(''AddContext'',ho); spm_orthviews(''AddContext'',hf); ', ... % add menu + ...'spm_orthviews(''Zoom'',40);', ... % zoom in + ],job.data{fi}))); + end + end + end +end +% ====================================================================== +function varargout = reducev( Y , varargin ) +% reducev;"">reducev & dereducev +% Resize to lower resolution and restore original resolution. +% +% [Yr, res] = cat_vol_resize(Y, 'reduceV', vx_vol, vx_volr [, minsize, method]); +% [Yr1, .. , Yrn, res] = cat_vol_resize({Y1,...,Yn}, res [, method]); +% +% Y .. input image (as matrix or cell) +% Yr .. output image +% {Y1, ... Yn} .. input images +% Yr1, ... Yrn .. output images +% vx_vol .. voxel size of the input image(s) +% vx_volr .. voxel size of the output image(s) +% minsize .. resolution limit of the downsampled image +% (default: 32x32x32 voxels) +% method .. downsampling methods with voxel binning for +% denoising (min, max meanm, median, stdm) or +% by classical 'nearest', 'linear', or 'cubic' +% resampling (use unit test for examples) +% +% Examples: +% [Yir, Yig, Ygi, res] = cat_vol_resize({Yi, YIG, single(Yg/Yi)}, 'reduceV',vx_vol,2,64); +% Yi2 = cat_vol_resize(Yir, 'dereduceV', resT); +% + + varargout = cell(1,nargout); + + sizeY = size(Y{1}); + + % set up paraemters + if numel(varargin) < 1, vx_vol = 1; else, vx_vol = round(varargin{1} * 100) / 100; end + if numel(varargin) < 2, vx_volr = 2; else, vx_volr = round(varargin{2} * 100) / 100; end + if numel(varargin) < 3, minSize = 32; else, minSize = varargin{3}; end + if numel(varargin) < 4, interp = 'linear'; else, interp = varargin{4}; end + + % update 2nd and 3rd dimention parameters + if numel(vx_vol) == 1, vx_vol = repmat(vx_vol , 1, 3); end + if numel(vx_volr) == 1, vx_volr = repmat(vx_volr, 1, 3); end + if numel(minSize) == 1, minSize = min(sizeY,repmat(minSize,1,3)); end + + % assure the downsampling + vx_volr = max(vx_volr,vx_vol); + + % estimate the stepsize (reduction rate) and lower resolution + ss = floor(vx_volr ./ vx_vol); sizeYr = floor(sizeY ./ ss); + ss = floor(sizeY ./ max(sizeYr, minSize)); + vx_volr = vx_vol .* ss; vx_red = ones(1,3) ./ ss; + + + % the downsampling + minvoxcount = max(2,mean(ss)/2); % define only voxels if they have enough input + for i = 1:numel(Y) + if any(vx_red <= 0.5) + + % enlarge the volume to support downsampling of the last voxel line + if mod(size(Y{i},1),2) == 1 && vx_red(1) <= 0.75, Y{i}(end+1,:,:) = Y{i}(end,:,:); end + if mod(size(Y{i},2),2) == 1 && vx_red(2) <= 0.75, Y{i}(:,end+1,:) = Y{i}(:,end,:); end + if mod(size(Y{i},3),2) == 1 && vx_red(3) <= 0.75, Y{i}(:,:,end+1) = Y{i}(:,:,end); end + + if cat_io_contains(interp,'near') + nsize = floor(size(Y{i}) ./ ss) .* ss; + varargout{i} = Y{i}(round(ss(1)/2):ss(1):nsize(1), ... + round(ss(2)/2):ss(2):nsize(2), ... + round(ss(3)/2):ss(3):nsize(3)); + resT.vx_red = ss; + resT.vx_volr = vx_volr; + continue + end + + % different cases of downsampling + if strcmp(interp,'median') || strcmp(interp,'medianm') + varargout{i} = zeros([floor(size(Y{i})./ss), prod(ss)],'single'); + medi = 1; + elseif strcmp(interp,'min') + varargout{i} = inf(floor(size(Y{i}) ./ ss),'single'); + elseif strcmp(interp,'max') + varargout{i} = -inf(floor(size(Y{i}) ./ ss),'single'); + else + varargout{i} = zeros(floor(size(Y{i}) ./ ss),'single'); + end + counter = zeros(floor(size(Y{i}) ./ ss),'single'); + nsize = floor(size(Y{i}) ./ ss) .* ss; + + % estimate mean in case of std + if strcmp(interp,'stdm') + meanx = cat_vol_resize( Y{i} , 'reduceV', vx_vol, vx_volr, minSize, 'meanm'); + end + + + + for ii = 1:ss(1) + for jj = 1:ss(2) + for kk = 1:ss(3) + Yadd = single( Y{i}(ii:ss(1):nsize(1), jj:ss(2):nsize(2), kk:ss(3):nsize(3)) ); + switch interp + case {'meanm','min','max','stdm','median'} + counter = counter + (abs(Yadd)>0 & ~isinf(Yadd)); + otherwise + counter = counter + single( ~isnan(Y{i}(ii:ss(1):nsize(1),jj:ss(2):nsize(2),kk:ss(3):nsize(3)))); + end + %Yadd(isnan(Yadd(:))) = 0; + % RD20231215: refined NaN handling with counter? + switch interp + case 'max' + Yadd(Yadd==0) = nan; + varargout{i} = max(varargout{i},Yadd); + case 'min' + Yadd(Yadd==0) = nan; + varargout{i} = min(varargout{i},Yadd); + case {'cat_stat_nanmean','meannan','mean'} + varargout{i} = varargout{i} + Yadd; + case 'meanm' + varargout{i} = varargout{i} + Yadd; + case 'stdm' + varargout{i} = varargout{i} + (Yadd - meanx.*(Yadd~=0)).^2; + case {'median','medianm'} + varargout{i}(:,:,:,medi) = Yadd; medi = medi + 1; + otherwise + [Rx,Ry,Rz] = meshgrid(single( round(ss(2)/2):ss(2):size(Y{i},2)),... + single( round(ss(1)/2):ss(1):size(Y{i},1)),... + single( round(ss(3)/2):ss(3):size(Y{i},3))); + varargout{i} = cat_vol_interp3f(single(Y{i}),Rx,Ry,Rz,interp); + end + end + end + end + %% divide for number of used input / estimate median + if cat_io_contains(interp,{'mean'}) + varargout{i}(counter(:)>0) = varargout{i}(counter(:)>0) ./ counter(counter(:)>0); + elseif strcmp(interp,'stdm') + varargout{i}(counter(:)>0) = varargout{i}(counter(:)>0) ./ counter(counter(:)>0); + varargout{i}(counter(:)>0) = sqrt( varargout{i}(counter(:)>0) ); + elseif strcmp(interp,'median') + varargout{i}(varargout{i}==0) = nan; + varargout{i} = cat_stat_nanmedian(varargout{i},4); + end + % irgnore values with too small input + switch interp + case {'meanm','min','max','stdm','median'} + varargout{i}( counter(:) < minvoxcount | isinf( varargout{i}(:) ) | isnan(varargout{i}(:)) ) = 0; + end + + %% set upt resT variable for dereducev case + if islogical(Y{i}), varargout{i} = varargout{i} > 0.5; end + %varargout{i} = cat_vol_ctype( varargout{i} , class(Y{i}) ); % do not use this ! + resT.vx_red = ss; + resT.vx_volr = vx_volr; + else + % no reduction neccessary + % set upt resT variable for dereducev case + varargout{i} = Y{i}; + resT.vx_red = [1 1 1]; + resT.vx_volr = vx_vol; + end + + end + varargout{i+1}.vx_red = resT.vx_red; + varargout{i+1}.vx_vol = vx_vol; + varargout{i+1}.vx_volr = resT.vx_volr; + varargout{i+1}.sizeT = sizeY; + varargout{i+1}.sizeTr = size(varargout{1}); + varargout{i+1}.interp = interp; +end +% ====================================================================== +%{ +case 'deinterpv' + if numel(varargin)>1, interp = varargin{2}; else interp = 'cubic'; end + varargout{1} = varargin{1}.hdrO; + if isfield(T,'dat') + Y = T.dat; clear T; + else + Y = spm_read_vols(T); + end + varargout{1}.dat = cat_vol_resize(Y,'deinterp',varargin{1},interp); +%} +function varargout = dereducev( Y , varargin ) +%dereducev. Restore old resolution. See reducev for help. + + varargout = cell(1,nargout); + + vx_red = varargin{1}.vx_red; + sD = varargin{1}.sizeT ./ vx_red + 0.5; + if numel(varargin) < 2 + if isfield(varargin{1},'interp') + switch varargin{1}.interp + case {'linear','nearest','cubic'} + interp = varargin{1}.interp; + otherwise + interp = 'linear'; + end + else + interp = 'linear'; + end + else + interp = varargin{2}; + end + + [Rx,Ry,Rz] = meshgrid(single(0.5 + 0.5/vx_red(2) : 1/vx_red(2) : sD(2)),... + single(0.5 + 0.5/vx_red(1) : 1/vx_red(1) : sD(1)),... + single(0.5 + 0.5/vx_red(3) : 1/vx_red(3) : sD(3))); + + for i = 1:numel(Y) + Y{i}(isnan(Y{i})) = 0; + if islogical(Y{i}) && any(vx_red>1) + varargout{i} = cat_vol_smooth3X(cat_vol_interp3f(single(Y{i}), Rx, Ry, Rz, interp), mean(vx_red) ) > 0.5; + else + varargout{i} = cat_vol_interp3f(single(Y{i}), Rx, Ry, Rz, interp); + end + end + + % ##### SMOOTH #### +end +% ====================================================================== +function varargout = reduceBrain(Y,varargin) +% reduceBrain;"">Crop/reduceBrain & uncrop/dereduceBrain +% Temporary cropping of volumes. +% +% [Yb,BB] = cat_vol_resize( Y , 'reduceBrain' , vx_vol [, bb, Yb] ); +% Y2b = cat_vol_resize( Y2, 'reduceBrain' , vx_vol , BB ); +% Y3 = cat_vol_resize( Yb, 'dereduceBrain', BB ); +% +% Y .. input image (or cell of images) +% Yb .. cropped image +% Y3 .. restored image +% vx_vol .. voxel size +% bb .. additional distance to brainmask +% Yb .. additional brainmask +% BB .. internal structure to apply cropping to other similar images +% and restoring the original properties +% + + varargout = cell(1,nargout); + + if numel(varargin) < 1, vx_vol = [1,1,1]; else, vx_vol = varargin{1}; end + if numel(varargin) < 2 || isempty(varargin{2}), d = 1; else, d = varargin{2}; end + if numel(vx_vol) == 1, vx_vol = repmat(vx_vol , 1, 3); end + + % setup boundary distance + if numel(d)==1, d=d(1).*(ones(1,6)); + elseif numel(d)~=6, error('ERROR:reduceBrain: d has to have one or six elements.'); + elseif any(d([2,4,6]) > (size(Y{1})/2)), BB = d; d = [1 1 1 1 1 1]; % ???? + else + error('ERROR:reduceBrain: unknown error using d.'); + end + d = max(1,round(d ./ vx_vol([1 1 2 2 3 3]))); + + % prepare BB or M variable + if numel(varargin) > 2 && ndims(varargin{3}) == 3 + M = varargin{3}; + elseif numel(varargin) > 2 && ndims(varargin{3}) == 2 %#ok + if numel(varargin{3}) == 6 + BB = varargin{3}; + else + error('BB has a wrong number of elements'); + end + elseif exist('BB','var') + % nothing to do + else + % find largest object + [~, M] = cat_vol_iscale(Y{1},'findhead',vx_vol,4); M(end) = 0; + end + + % prepare BB variable + if ~exist('BB','var') + if sum(M(:))>0 + SSUM = sum(sum(M,3),2); BB(1) = max(1,find(SSUM>0,1,'first')-d(1)); BB(2) = min(size(M,1),find(SSUM>0,1,'last')+d(2)); + SSUM = sum(sum(M,3),1); BB(3) = max(1,find(SSUM>0,1,'first')-d(3)); BB(4) = min(size(M,2),find(SSUM>0,1,'last')+d(4)); + SSUM = sum(sum(M,2),1); BB(5) = max(1,find(SSUM>0,1,'first')-d(5)); BB(6) = min(size(M,3),find(SSUM>0,1,'last')+d(6)); + else + BB(1) = 1; BB(2) = max(2,size(Y,1)); + BB(3) = 1; BB(4) = max(2,size(Y,2)); + BB(5) = 1; BB(6) = max(2,size(Y,3)); + end + end + + for i = 1:numel(Y) + varargout{i} = Y{i}(BB(1):BB(2), BB(3):BB(4), BB(5):BB(6)); + end + + % prepare BB variable to restore full volume + varargout{i+1}.BB = BB; + varargout{i+1}.sizeT = size(Y{1}); + varargout{i+1}.sizeTr = size(varargout{1}); + +end +% ====================================================================== +function varargout = dereduceBrain(Y,varargin) +%dereduceBrain. Uncrop image matrix. See reduceBrain for help. +% See dereduceBrain for help. + + varargout = cell(1,nargout); + + BB = varargin{1}.BB; + for i = 1:numel(Y) + if ndims(Y{i})==3 + if islogical(Y{i}) + YO = false(varargin{1}.sizeT); + else + YO = zeros(varargin{1}.sizeT,class(Y{i})); + end + varargout{i} = YO; varargout{i}(BB(1):BB(2),BB(3):BB(4),BB(5):BB(6)) = Y{i}(:,:,:); + elseif ndims(Y{i}) == 4 + YO = zeros([varargin{1}.sizeT,size(Y{i},4)],class(Y{i})); + varargout{i} = YO; varargout{i}(BB(1):BB(2),BB(3):BB(4),BB(5):BB(6),:) = Y{i}(:,:,:,:); + end + end +end +% ====================================================================== +function varargout = interpi(Y,varargin) +%interpi;"">interp & deinterp +% Resampling of volumes with smoothing in case of downsampling to improve +% SNR. +% +% varargout = interpi(Y, V [, res, interp, smooth ] ) +% +% V .. volume header +% res .. input resolution parameter (res = .5) +% interp .. interpolation method (default = 'linear') +% smooth .. factor of smoothing (default = .5 voxel) using spm_smooth +% + + + varargout = cell(1,nargout); + + if numel(varargin) > 0, V = varargin{1}; end + if numel(varargin) > 1, res = varargin{2}; else, res = .5; end + if numel(varargin) > 2, interp = varargin{3}; else, interp = 'linear'; end + if numel(varargin) > 3, smooth = varargin{4}; else, smooth = 0.5; end + + if ~exist('V','var') || isempty(V) + V.mat = [1 0 0 1;0 1 0 1; 0 0 1 1; 0 0 0 1]; + V.dim = size(Y); + end + if numel(res) == 1, res(2:3) = res; end + if numel(res) == 2, res = [res(1), res]; end + + Y = single(Y{1}); + resV = sqrt(sum(V.mat(1:3,1:3).^2)); + sizeO = size(Y); + + if all(res > 0) + % final size of the interpolated image + + % ########## + % RD202005: This is not corrected and can cause displacements (a + % little offset ... use AC + % ########## + [Rx,Ry,Rz] = meshgrid(single(res(2) / resV(2) : res(2)/resV(2) : size(Y,2)),... + single(res(1) / resV(1) : res(1)/resV(1) : size(Y,1)),... + single(res(3) / resV(3) : res(3)/resV(3) : size(Y,3))); + + + % use smoothing in case of resolution downsampling as partial volume effect + if exist('smooth','var') && any( ( res ./ resV ) > 1.0 ) + if ndims(Y) > 3 + if ndims(Y) == 4, YI = zeros([size(Rx) size(Y,4) ]); end + for d4i = 1:size(Y,4) + if ndims(Y) > 4 + YI = zeros([size(Rx) size(Y,4) size(Y,5) ]); + for d5i = 1:size(Y,5) + Ys = YI(:,:,:,d4i,d5i); + spm_smooth(Ys,Ys, (res(2)/resV(2)) / 2 * smooth); + YI(:,:,:,d4i,d5i) = Ys; clear Ys; + end + else + Ys = YI(:,:,:,d4i); + spm_smooth(Ys,Ys, (res(2)/resV(2)) / 2 * smooth); + YI(:,:,:,d4i) = Ys; clear Ys; + end + end + else + spm_smooth(Y,Y, (res(2)/resV(2)) / 2 * smooth); + end + end + + + %% T = spm_sample_vol(T,Dx,Dy,Dz,method); + if ndims(Y) > 3 + dims = size(Y); + YI = zeros([size(Rx) dims(4:end)],'single'); + for d4i = 1:size(Y,4) + if ndims(Y)>4 + for d5i = 1:size(Y,5) + YI(:,:,:,d4i,d5i) = cat_vol_interp3f(Y(:,:,:,d4i,d5i),Rx,Ry,Rz,interp); + end + else + YI(:,:,:,d4i) = cat_vol_interp3f(Y(:,:,:,d4i),Rx,Ry,Rz,interp); + end + end + Y = YI; clear YI; + else + Y = cat_vol_interp3f(Y,Rx,Ry,Rz,interp); + end + + + V.dim=size(Y); + if isfield(V,'pinfo'), V.pinfo = repmat([1;0],1,size(Y,3)); end + %hdr.mat([1,2,3,5,6,7,9,10,11]) = hdr.mat([1,2,3,5,6,7,9,10,11]) .* res(1); + Vo = V; + vmat = spm_imatrix(V.mat); + vmat(7:9) = sign(vmat(7:9)).*res(1:3); + Vo.mat = spm_matrix(vmat); + %Vo.fname = Vi.fname; + end + + varargout{1} = Y; + varargout{2}.hdrO = V; + varargout{2}.hdrN = Vo; + varargout{2}.sizeO = sizeO; + varargout{2}.sizeN = size(Y); + varargout{2}.resO = resV; + varargout{2}.resN = res; +end +% ====================================================================== +function varargout = deinterpi(Y,varargin) +%cat_vol_resize. Resample to original resolution. +% See interpi for help. + + res = varargin{1}.resO; + resV = varargin{1}.resN; + if numel(varargin)>1, interp = varargin{2}; else, interp = 'cubic'; end + + + Y = single(Y{1}); + if strcmp(interp,'masked') + % for interpolation of partial defined maps like the cortical + % thickness... finally 'nearest' interpolation is often good + % enough and much faster + if all(res>0) %&& any(round(abs(res)*100)/100>resV) + d = single(res./resV); + [Rx,Ry,Rz]=meshgrid(1:d(2):size(Y,2),1:d(1):size(Y,1),1:d(3):size(Y,3)); + if strcmpi(spm_check_version,'octave') + Rx = single(Rx); Ry = single(Ry); Rz = single(Rz); + end + M = single(Y~=0); MM = cat_vol_morph(M,'d',2)>0; + [~,I] = cat_vbdist(Y,MM); Y=Y(I); clear D I; + %Ts = smooth3(T); MM=cat_vol_morph(M,'e'); T(~MM)=Ts(~MM); clear MM; + M = cat_vol_interp3f(M,Rx,Ry,Rz,'linear')>0.5; + Y = cat_vol_interp3f(Y,Rx,Ry,Rz,'cubic'); + Y = Y .* M; + clear Rx Ry Rz; + end + else + if all(res>0) %&& any(round(abs(res)*100)/100>resV) + d = single(res./resV); + if 0 + [Rx,Ry,Rz] = meshgrid(.5:d(2):size(Y,2), ... + .5:d(1):size(Y,1), ... + .5:d(3):size(Y,3)); + else + [Rx,Ry,Rz] = meshgrid(d(2):d(2):size(Y,2), ... + d(1):d(1):size(Y,1), ... + d(3):d(3):size(Y,3)); + end + if strcmpi(spm_check_version,'octave') + Rx = single(Rx); Ry = single(Ry); Rz = single(Rz); + end + Ys = Y + 0; + Y = cat_vol_interp3f(Ys,Rx,Ry,Rz,interp); + clear Rx Ry Rz; + end + end + + + varargout{1} = zeros(varargin{1}.sizeO,'single'); + varargout{1}(1:min(size(Y,1),varargin{1}.sizeO(1)), ... + 1:min(size(Y,2),varargin{1}.sizeO(2)), ... + 1:min(size(Y,3),varargin{1}.sizeO(3))) = ... + Y(1:min(size(Y,1),varargin{1}.sizeO(1)), ... + 1:min(size(Y,2),varargin{1}.sizeO(2)), ... + 1:min(size(Y,3),varargin{1}.sizeO(3))); + +end +% ====================================================================== +function varargout = interhdr(Y,varargin) +%interpihdr;"">interphdr +% Resize images based on cat_vol_imcalc. +% +% varargout = interhdr(Y, V, res, interp, V2[, nonan]) +% +% Y .. volume +% V .. volume header +% res .. resolution parameter +% interp .. interpolation method +% V2 .. output volume header (for cat_vol_imcalc) +% nonan .. replace NaNs +% + + varargout = cell(1,nargout); + + if nargin > 1, V = varargin{1}; end + if nargin > 2, res = varargin{2}; end + if nargin > 3, interp = varargin{3}; end + if nargin > 4, V2 = varargin{4}; end + if nargin > 5, nonan = varargin{5}; else, nonan = 0; end + + if ~exist('V','var') || isempty(V) + V.mat = [1 0 0 1;0 1 0 1; 0 0 1 1; 0 0 0 1]; + V.dim = size(Y); + end + if numel(res) == 1, res(2:3) = res; end + if numel(res) == 2, res = [res(1),res]; end + if ~exist('interp','var'), interp = 2; end + + Y = single(Y{1}); + + if exist('V2','var') + Vi = V2; + Vi.pinfo = V.pinfo; + Vi.dt = V.dt; + else + Vi = V; + end + resV = sqrt(sum(Vi.mat(1:3,1:3).^2)); + vmat = spm_imatrix(Vi.mat); + sizeO = size(Y); + sizeO3 = sizeO(1:3); + if nargin < 5 && all(res > 0) + %% Updated 20220805 to avoid unbalance and boundary problems in low resolution cases (e.g., 16mm) + vmat(7:9) = sign(vmat(7:9)) .* res; % this is the goal res + Vi.dim = ceil(sizeO3 ./ (res./resV) / 2)*2 + mod(sizeO3,2); % here we _add_ a voxel to keep a even or odd resolution + %Vi.dim = round((Vi.dim ./ vmat(7:9) - 1 ) / 2)*2 + 1; + vmat(1:3) = vmat(1:3) - vmat(7:9)/2 + vmat(7:9) .* (sizeO3 ./ (res./resV) - Vi.dim)/2; % if we add something we have to adjust for it + Vi.mat = spm_matrix(vmat); + end + + + + % main interpolation + Vt = V; + if ndims(Y) > 3 + % high dimensional cases requires the interpolation of the each n-D + % component. Here, we handle only the 4D (e.g. TPM,fMRI?) and 5D + % (Deformations) case. + if isfield(Vi,'private'), Vi = rmfield(Vi,'private'); end + if isfield(Vt,'private'), Vt = rmfield(Vt,'private'); end + if isfield(V,'pinfo') + Vt.pinfo = repmat([1;0],1,size(Y,3)); + Vi.pinfo = repmat([1;0],1,size(Y,3)); + else + Vt.pinfo = repmat([Vt.pinfo(1);0],1,size(Y,3)); + Vi.pinfo = repmat([Vt.pinfo(1);0],1,size(Y,3)); + end + dims = size(Y); + + YI = zeros([Vi.dim dims(4:end)],'single'); + for d4i = 1:size(Y,4) + if numel(Y) + for d5i = 1:size(Y,5) + Vt.dat(:,:,:) = single(Y(:,:,:,d4i,d5i)); Vt.dt(1) = 16; + Vi.dat(:,:,:) = single(Y(:,:,:,d4i,d5i)); Vi.dt(1) = 16; + [Vo,YI(:,:,:,d4i,d5i)] = cat_vol_imcalc(Vt,Vi,'i1',struct('interp',interp,'verb',0)); + if nonan + YI45 = YI(:,:,:,d4i,d5i); + [~,I] = cat_vbdist( single(~isnan(YI45)) ); + YI(:,:,:,d4i,d5i) = YI45(I); clear I YI45; + end + end + else + Vt.dat(:,:,:) = Y(:,:,:,d4i); + Vi.dat(:,:,:) = Y(:,:,:,d4i); + [Vo,YI(:,:,:,d4i)] = cat_vol_imcalc(Vt,Vi,'i1',struct('interp',interp,'verb',0)); + if nonan + YI45 = YI(:,:,:,d4i); + [~,I] = cat_vbdist( single(~isnan(YI45)) ); + YI(:,:,:,d4i) = YI45(I); clear I YI45; + end + end + end + Y = YI; clear YI; + else + % simple 3D case + if isfield(Vt,'private'), Vt = rmfield(Vt,'private'); end + if isfield(Vi,'private'), Vi = rmfield(Vi,'private'); end + if isfield(V,'pinfo') + Vt.pinfo = repmat([1;0],1,size(Y,3)); + Vi.pinfo = repmat([1;0],1,size(Y,3)); + else + Vt.pinfo = repmat([Vt.pinfo(1);0],1,size(Y,3)); + Vi.pinfo = repmat([Vt.pinfo(1);0],1,size(Y,3)); + end + % update datatype + dt = spm_type(Vt.dt(1)); + dt = cat_io_strrep(dt,{'float32','float64'},{'single','double'}); + if cat_io_contains({'single','double'},dt) + eval(sprintf('T = %s(T);', dt )); + else + Vt.dt(1) = spm_type('float32'); + Y = single(Y); + end + % setup images + if isfield(Vt,'dat'), Vt = rmfield(Vt,'dat'); end + if isfield(Vi,'dat'), Vi = rmfield(Vi,'dat'); end + Vt.dat(:,:,:) = Y(:,:,:); Vt.dim = size(Y); + Vi.dat(:,:,:) = zeros(Vi.dim); + + [Vo,Y] = cat_vol_imcalc(Vt,Vi,'i1',struct('interp',interp,'verb',0)); + + Vo.pinfo = V.pinfo; + if isfield(Vo,'dat'), Vo = rmfield(Vo,'dat'); end + + if nonan + [~,I] = cat_vbdist( single(~isnan(Y)) ); Y = Y(I); clear I D; + end + end + + % create output structure for cat_vol_resize > deinterp + varargout{1} = Y; + varargout{2}.hdrO = V; + varargout{2}.hdrN = Vo; + varargout{2}.sizeO = sizeO; + varargout{2}.sizeN = size(Y); + varargout{2}.resO = resV; + varargout{2}.resN = res; + +end +% ====================================================================== +function cat_vol_resize_unittest +%cat_vol_resize_test;"">test +% Unit test of cat_vol_resize functions for a random image with 128^3 voxel +% for different resampling operations. +% +% cat_vol_resize(0,'test'); +% + + fprintf('Run Unit Test for cat_vol_resize: '); + + % prepare random test matrix + ms = 128; % matrix size + A = 10 * cat_vol_smooth3X(randn(ms,ms,ms),4); % structure + A = A + randn(ms,ms,ms)*.03 + 0.5; % noise + A = A .* ( cat_vol_smooth3X(randn(ms,ms,ms),8)>0 ); % bias + B = A + 0; spm_smooth(B,B,32); B = B>0.2; A = A .* B; % brainmask + ca = min([0 inf],repmat(cat_stat_nanmedian(A(A(:)~=0)),1,2) + 2*[-1 1].* repmat(cat_stat_nanstd(A(A(:)~=0)),1,2)); + + + % create figure, estimate and display images + subplots = [4 + exist('cat_vol_resizeo','file'),5]; + fg = figure(1847); + fg.Position(3:4) = subplots*150; clf(fg); + fg.Name = 'cat_vol_resize unit test'; + fg.Color = [1 1 1]; + + % === resize === + % operations + red = 7; + [Ar,res] = cat_vol_resize(A ,'reducev',1,red,4,'meanm'); + Arme = cat_vol_resize(A ,'reducev',1,red,4,'mean'); + AR = cat_vol_resize(Ar,'dereducev',res) .* (A~=0); + + % plots first column + subplot(subplots(2),subplots(1),sub2ind(subplots,1,1)) + imagesc(A(:,:,round(.5 * size(A,3)))); caxis(ca); axis equal off; title('original') + subplot(subplots(2),subplots(1),sub2ind(subplots,1,2)) + imagesc(Arme(:,:,round(.5 * size(Arme,3)))); caxis(ca); axis equal off; title('reducev-mean') + subplot(subplots(2),subplots(1),sub2ind(subplots,1,3)) + imagesc(Ar(:,:,round(.5 * size(Ar,3)))); caxis(ca); axis equal off; title('reducev-meanm') + subplot(subplots(2),subplots(1),sub2ind(subplots,1,4)) + imagesc(AR(:,:,round(.5 * size(A,3)))); caxis(ca); axis equal off; title('res-meanm .* (org~=0)') + subplot(subplots(2),subplots(1),sub2ind(subplots,1,5)); + imagesc(abs( A(:,:,round(.5 * size(A,3))) - AR(:,:,round(.5 * size(A,3))))); + caxis(ca/5); axis equal off; title('diff (org-res-meanm)') + + % plots second column + Arnr = cat_vol_resize(A,'reducev',1,red,4,'nearest'); + Armi = cat_vol_resize(A,'reducev',1,red,4,'min'); + Arma = cat_vol_resize(A,'reducev',1,red,4,'max'); + Arsd = cat_vol_resize(A,'reducev',1,red,4,'stdm'); + Armd = cat_vol_resize(A,'reducev',1,red,4,'median'); + ARnr = cat_vol_resize(Arnr,'dereducev',res) .* (A~=0); + ARme = cat_vol_resize(Arme,'dereducev',res) .* (A~=0); + + subplot(subplots(2),subplots(1),sub2ind(subplots,2,1)) + imagesc(Arnr(:,:,round(.5 * size(Arnr,3)))); caxis(ca); axis equal off; title('reducev-nearest') + subplot(subplots(2),subplots(1),sub2ind(subplots,2,2)) + imagesc(Armi(:,:,round(.5 * size(Armi,3)))); caxis(ca); axis equal off; title('reducev-min') + subplot(subplots(2),subplots(1),sub2ind(subplots,2,3)) + imagesc(Arma(:,:,round(.5 * size(Arma,3)))); caxis(ca); axis equal off; title('reducev-max') + subplot(subplots(2),subplots(1),sub2ind(subplots,2,4)) + imagesc(Armd(:,:,round(.5 * size(Armd,3)))); caxis(ca); axis equal off; title('reducev-median') + subplot(subplots(2),subplots(1),sub2ind(subplots,2,5)) + imagesc(Arsd(:,:,round(.5 * size(Arsd,3)))); caxis(ca/5); axis equal off; title('reducev-stdm') + + % add on + subplot(subplots(2),subplots(1),sub2ind(subplots,3,1)) + imagesc(ARnr(:,:,round(.5 * size(ARnr,3)))); caxis(ca); axis equal off; title('res-near .* (org~=0)') + subplot(subplots(2),subplots(1),sub2ind(subplots,4,1)) + imagesc(abs( A(:,:,round(.5 * size(A,3))) - ARnr(:,:,round(.5 * size(A,3))))); + caxis(ca/2); axis equal off; title('diff (org-res-nearest)') + + xp = 3 + exist('cat_vol_resizeo','file'); + subplot(subplots(2),subplots(1),sub2ind(subplots,xp,1)) + imagesc(ARme(:,:,round(.5 * size(ARme,3)))); caxis(ca); axis equal off; title('res-mean.*(org~=0)') + subplot(subplots(2),subplots(1),sub2ind(subplots,xp+1,1)) + imagesc(abs( A(:,:,round(.5 * size(A,3))) - ARme(:,:,round(.5 * size(A,3))))); + caxis(ca/2); axis equal off; title('diff (org-res-mean)') + + %% plots column 3 and 4 for old functions + if exist('cat_vol_resizeo','file') + Armio = cat_vol_resizeo(A,'reducev',1,red,4,'min'); + Armao = cat_vol_resizeo(A,'reducev',1,red,4,'max'); + Arsdo = cat_vol_resizeo(A,'reducev',1,red,4,'stdm'); + Armeo = cat_vol_resizeo(A,'reducev',1,red,4,'mean'); + %Arnro = cat_vol_resizeo(A,'reducev',1,red,4,'nearest'); + Armmo = cat_vol_resizeo(A,'reducev',1,red,4,'meanm'); + Armdo = cat_vol_resizeo(A,'reducev',1,red,4,'median'); + ARmmo = cat_vol_resizeo(Armmo,'dereducev',res) .* (A~=0); + %ARnro = cat_vol_resizeo(Arnro,'dereducev',res) .* (A~=0); + subplot(subplots(2),subplots(1),sub2ind(subplots,3,2)) + imagesc(Armeo(:,:,round(.5 * size(Armeo,3)))); caxis(ca); axis equal off; title('reducev-mean (old)') + subplot(subplots(2),subplots(1),sub2ind(subplots,3,3)) + imagesc(Armmo(:,:,round(.5 * size(Ar,3)))); caxis(ca); axis equal off; title('reducev-meanm (old)') + subplot(subplots(2),subplots(1),sub2ind(subplots,3,4)) + imagesc(ARmmo(:,:,round(.5 * size(A,3)))); caxis(ca); axis equal off; title('restored meanm .* (org~=0)') + subplot(subplots(2),subplots(1),sub2ind(subplots,3,5)); + imagesc(abs( ARmmo(:,:,round(.5 * size(A,3))) - A(:,:,round(.5 * size(A,3))))); + caxis(ca/2); axis equal off; title('diff (org-restored)') + + subplot(subplots(2),subplots(1),sub2ind(subplots,4,2)) + imagesc(Armio(:,:,round(.5 * size(Armio,3)))); caxis(ca); axis equal off; title('reducev-min (old)') + subplot(subplots(2),subplots(1),sub2ind(subplots,4,3)) + imagesc(Armao(:,:,round(.5 * size(Armao,3)))); caxis(ca); axis equal off; title('reducev-max (old)') + subplot(subplots(2),subplots(1),sub2ind(subplots,4,4)) + imagesc(Armdo(:,:,round(.5 * size(Armdo,3)))); caxis(ca); axis equal off; title('reducev-median (old)') + subplot(subplots(2),subplots(1),sub2ind(subplots,4,5)) + imagesc(Arsdo(:,:,round(.5 * size(Arsdo,3)))); caxis(ca/5); axis equal off; title('reducev-stdm (old)') + end + + + %% === crop === + % operations + [Ab,bb] = cat_vol_resize(A,'reduceBrain',1,5); + AB = cat_vol_resize(Ab,'dereduceBrain',bb); + + % plots + xp = 3 + exist('cat_vol_resizeo','file'); + subplot(subplots(2),subplots(1),sub2ind(subplots,xp,2)) + imagesc(Ab(:,:,round(.5 * size(Ab,3)))); caxis(ca); axis equal off; title('crop(5)') + subplot(subplots(2),subplots(1),sub2ind(subplots,xp,3)) + imagesc(AB(:,:,round(.5 * size(A,3)))); caxis(ca); axis equal off; title('uncrop') + subplot(subplots(2),subplots(1),sub2ind(subplots,xp,4)) + imagesc(abs( A(:,:,round(.5 * size(A,3))) - AB(:,:,round(.5 * size(A,3))))); + caxis(ca/2); axis equal off; title('diff (crop)') + + % === resize === + % operations + [AI,ipv] = cat_vol_resize(A,'interp',[],.3,'cubic'); + Ai = cat_vol_resize(AI,'deinterp',ipv); + Aim = cat_vol_resize(AI,'deinterp',ipv,'masked'); + if exist('cat_vol_resizeo','file') + Aio = cat_vol_resizeo(AI,'deinterp',ipv); %#ok + end + + % plots + subplot(subplots(2),subplots(1),sub2ind(subplots,xp+1,2)) + imagesc(AI(:,:,round(.5 * size(AI,3)))); caxis(ca); axis equal off; title('interp') + subplot(subplots(2),subplots(1),sub2ind(subplots,xp+1,3)) + imagesc(Ai(:,:,round(.5 * size(Ai,3)))); caxis(ca); axis equal off; title('deinterp') + subplot(subplots(2),subplots(1),sub2ind(subplots,xp+1,5)) + imagesc(Aim(:,:,round(.5 * size(Ai,3)))); caxis(ca); axis equal off; title('deinterp-masked') + subplot(subplots(2),subplots(1),sub2ind(subplots,xp+1,4)) + imagesc(abs( A(:,:,round(.5 * size(A,3))) - Ai(:,:,round(.5 * size(A,3))))); + caxis(ca/2); axis equal off; title('diff (interp)') + + fprintf('done. \n'); +end +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_main_gcut.m",".m","11202","228","function [Yb,Yl1] = cat_main_gcut(Ysrc,Yb,Ycls,Yl1,YMF,vx_vol,opt) +% This is an exclusive subfunction of cat_main. +% ______________________________________________________________________ +% +% gcut+: skull-stripping using graph-cut +% ---------------------------------------------------------------------- +% This routine use morphological, region-growing and graph-cut methods. +% It starts from the WM segment and grow for lower tissue intensities. +% Atlas knowledge is used to for separate handling of the cerebellum. +% Because its high frequency structures in combination with strong +% noise or other artifacts often lead to strong underestimations. +% +% There are 4 major parameters: +% gcutstr - strengh of skull-stripping with str=0 - more tissue, str=1 less tissue +% vx_res - resolution limit for skull-stripping (default 1.5) +% gcutCSF +% Especialy the second parameter controls many subparameters for +% different tissue thresholds, region-growing, closing and smoothing +% parameters. +% This routine have a strong relation to the previous estimated main +% partition map l1, and the blood vessel correction. Therefore, it is +% maybe useful to move it... +% +% [Yb,Yl1] = cat_main_gcut(Ysrc,Yb,Ycls,Yl1,YMF,vx_vol,opt) +% +% Yb .. updated brain mask +% Yl1 .. updated label map +% +% Ysrc .. anatomical image +% Yb .. initial brain mask +% Ycls .. SPM tissue classification +% Yl1 .. CAT atlas map +% YMF .. subcortical/ventricular regions (for filling in surf. recon.) +% vx_vol .. image resolutino +% opt .. further options +% +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + + dbs = dbstatus; debug = 0; for dbsi=1:numel(dbs), if strcmp(dbs(dbsi).name,mfilename); debug = 1; break; end; end + + + def.uhrlim = 0.7; + opt = cat_io_checkinopt(opt,def); + opt.gcutstr = min(1,opt.gcutstr); + + % general resolution limitation + if nargout>1, Yl1o = Yl1; end + if any( vx_vol < opt.uhrlim/2 ) + [Ysrc,resT0] = cat_vol_resize( Ysrc , 'reduceV' , vx_vol , opt.uhrlim , 64 ); + for ci=[1,2,3,5] + Ycls{ci} = cat_vol_resize( Ycls{ci}, 'reduceV' , vx_vol , opt.uhrlim , 64 ); + end + YMF = cat_vol_resize( single(YMF) , 'reduceV' , vx_vol , opt.uhrlim , 64 )>0.5; + Yb = cat_vol_resize( single(Yb) , 'reduceV' , vx_vol , opt.uhrlim , 64 )>0.5; + Yl1 = cat_vol_resize( Yl1 , 'reduceV' , vx_vol , opt.uhrlim , 64 , 'median' ); + end + + + NS = @(Ys,s) Ys==s | Ys==s+1; % side alignment function + LAB = opt.LAB; % cat atlas regions + voli = @(v) (v ./ (pi * 4./3)).^(1/3); % volume > radius + brad = double(voli(sum(Yb(:)>0).*prod(vx_vol))); % distance and volume based brain radius (brad) + Yp0 = single(Ycls{3})/255/3 + single(Ycls{1})/255*2/3 + single(Ycls{2})/255; + Ygm = single(Ycls{1})/255; + Ywm = single(Ycls{2})/255; + Ycsf = single(Ycls{3})/255; + Ymg = single(Ycls{5})/255; clear Ycls; + rvol = [sum(round(Yp0(:)*3)==1), sum(round(Yp0(:)*3)==2), sum(round(Yp0(:)*3)==3)]/sum(round(Yp0(:)*3)>0); + %noise = cat_stat_nanstd(Ym(cat_vol_morph(cat_vol_morph(Ym>0.95 & Ym<1.05,'lc',1),'e'))); + + + %% set different paremeters to modifiy the stength of the skull-stripping + %gc.n = max(0.05,min(0.1,noise)); + % intensity parameter + gc.h = 3.5 - 0.2*opt.gcutstr + 0.2*opt.LASstr; % 3.25; upper tissue intensity (WM vs. blood vessels) - higher > more ""tissue"" (blood vessels) + gc.g = 1.9 + 0.1*opt.gcutstr; % 1.50; lower tissue intensity (WM vs. blood vessels) - higher > more ""tissue"" (blood vessels) + gc.l = 1.1 + 0.8*opt.gcutstr; % 1.50; lower tissue intensity (WM vs. blood vessels) - higher > more ""tissue"" (blood vessels) + gc.o = 0.2 + 0.8*opt.gcutstr; % 0.50; BG tissue intensity (for high contrast CSF=BG=0!) - lower value > more ""tissue"" + % distance parameter + gc.d = brad*(5 - 4*opt.gcutstr)/mean(vx_vol); % 3.0; distance parameter for downcut - higher > more tissue + gc.c = max(-0.01,(0.01 - 0.03*opt.gcutstr)*mean(vx_vol)); % -0.005; growing parameter for downcut - higher > more tissue + gc.f = max(1,min(4,(brad/200 / (0.7-0.4*opt.gcutstr) * rvol(1)/0.10)/mean(vx_vol))); % closing parameter - higher > more tissue ... 8 + gc.gd = 1 + 2*opt.gcutstr; + gc.bd = 3 + 2*opt.gcutstr; + % smoothing parameter + gc.s = 0.2 + 0.30*min(0.6,opt.gcutstr); % 0.5; smoothing parameter - higher > less tissue + + + if opt.verb, fprintf('\n'); end + stime = cat_io_cmd(' WM initialisation','g5','',opt.verb); dispc=1; + + + %% init: remove empty space for speedup + [Ym,BB] = cat_vol_resize({Ysrc} , 'reduceBrain' , vx_vol , round(4/mean(vx_vol)) , Yb); + if ~debug, clear Ysrc; end + Yl1 = cat_vol_resize({Yl1} , 'reduceBrain' , vx_vol , round(4/mean(vx_vol)) , Yb); + YMF = cat_vol_resize({YMF} , 'reduceBrain' , vx_vol , round(4/mean(vx_vol)) , Yb); + Yp0 = cat_vol_resize({Yp0} , 'reduceBrain' , vx_vol , round(4/mean(vx_vol)) , Yb); + Ycsf = cat_vol_resize({Ycsf} , 'reduceBrain' , vx_vol , round(4/mean(vx_vol)) , Yb); + Ywm = cat_vol_resize({Ywm} , 'reduceBrain' , vx_vol , round(4/mean(vx_vol)) , Yb); + Ygm = cat_vol_resize({Ygm} , 'reduceBrain' , vx_vol , round(4/mean(vx_vol)) , Yb); + Ymg = cat_vol_resize({Ymg} , 'reduceBrain' , vx_vol , round(4/mean(vx_vol)) , Yb); + Yb = cat_vol_resize({Yb} , 'reduceBrain' , vx_vol , round(4/mean(vx_vol)) , Yb); + vxd = max(1,1/mean(vx_vol)); + Ymg = Ymg>0.05 & Ym<0.45; + if debug, Ybo=Yb; end + + + %% initial WM+ region + if debug, Yb=Ybo; end + YHDr = cat_vol_morph(Yl1>20 | Yl1<=0,'e',vxd*1); + + % YGD .. something like the GWM depth/thickness + % YBD .. brain depth, (simple) sulcal depth + [Yp0r,resT1] = cat_vol_resize(Yp0,'reduceV',vx_vol,1,32); + YGD = cat_vbdist(max(0,1-Yp0r) , true(size(Yp0r)) , resT1.vx_volr); + YBD = cat_vbdist(max(0,1-Yp0r*3) , true(size(Yp0r)) , resT1.vx_volr./mean(resT1.vx_volr)); + YGD = cat_vol_resize(YGD,'dereduceV',resT1); + YBD = cat_vol_resize(YBD,'dereduceV',resT1); + clear resT1; + + Yb = Yb>0.25 & Ym>2.5/3 & Ymgc.gd & YBD>gc.bd; % init WM + Yb = Yb | (Ym>2/3 & Ym10 | (YBD>2 & (NS(Yl1,LAB.CB) | NS(Yl1,LAB.HI))))); + [Ybr,Ymr,resT2] = cat_vol_resize({single(Yb),Ym},'reduceV',1,4./vx_vol,32); + Ybr = Ybr | (Ymr<0.8 & cat_vol_morph(Ybr,'lc',2)); clear Ymr; % large ventricle closing + Ybr = cat_vol_resize(cat_vol_smooth3X(Ybr,2),'dereduceV',resT2)>0.9; + + % if no largest object could be find it is very likeli that initial normalization failed + if sum(Yb(:) & mod(Yl1(:),2)==0)==0 || sum(Yb(:) & mod(Yl1(:),2)==1)==0 + error('cat:cat_main:largestWM',['No largest WM cluster could be found: \n'... + 'Please try to set origin (AC) and run preprocessing again \n' ... + 'because it is very likeli that spatial normalization failed.']); + end + Yb = cat_vol_morph(Yb & mod(Yl1,2)==0,'l') | ... + cat_vol_morph(Yb & mod(Yl1,2)==1,'l') | ... + (Ybr & Yp0>1.9/3 & Ym<3.5 & (NS(Yl1,LAB.CB))) | ... + (Ybr & Yp0<1.5/3 & Ym<1.5); + if ~debug, clear Ybr Yl1 Yp0; end + Yb = smooth3(Yb)>gc.s; + Yb(smooth3(single(Yb))<0.5)=0; % remove small dots + Yb = single(cat_vol_morph(Yb,'labclose',gc.f)); % one WM object to remove vbs + + + %% region growing GM/WM (here we have to get all WM gyris!) + stime = cat_io_cmd(' GM region growing','g5','',opt.verb,stime); dispc=dispc+1; + Yb(~Yb & (YHDr | Ymgc.h/3 | (Ywm + Ygm)<0.5 | YGD<(gc.gd-1) | YBD<(gc.bd-3)))=nan; %clear Ywm Ygm; + [Yb1,YD] = cat_vol_downcut(Yb,Ym,0.03+gc.c); % this have to be not to small... + Yb(isnan(Yb) | YD>gc.d*vxd*2)=0; Yb(Yb1>0 & YDgc.h/3) | Ymg)=nan; % | YBD<1 + [Yb1,YD] = cat_vol_downcut(Yb,Ym,0.01+gc.c); + Yb(isnan(Yb) | YD>gc.d/2)=0; Yb(Yb1>0 & YDgc.h/3) | Ymg)=nan; if ~debug, clear Ymg; end + [Yb1,YD] = cat_vol_downcut(Yb,Ym,-0.00+gc.c); + Yb(isnan(Yb) | YD>gc.d/2)=0; Yb(Yb1>0 & YD0.8 & Ygr(:)<0.1)); + Ybb = smooth3( Ym1.5/3 & ~Yb) | (Ygr>0.15 & ~Yb))>0.5 | smooth3(Ycsf)<0.15; + if ~debug, clear Yp0; end + if std(Ybb(:))>0 % no ROI in low res images + if sum(Ybb(:)>0.5)>0 % Ybb is maybe empty + Ybb = cat_vol_morph( Ybb>0.5 ,'lc',vxd); + Yb(~Yb & smooth3( Ybb )>0.6 ) = nan; + end + Yb(isnan(Yb) & cat_vol_morph(Yb>=0,'lc',2))=0; + end + [Yb1,YD] = cat_vol_downcut(Yb,smooth3(Ym),+0.01+gc.c); + Yb(isnan(Yb) | YD>gc.d/2)=0; Yb(Yb1>0 & YD0)=1; + for i=1:2, Yb(cat_vol_smooth3X(Yb,2)(gc.s-0.2) & Ym<1.25/3); + + %% filling of ventricles and smooth mask + stime = cat_io_cmd(' Ventricle filling','g5','',opt.verb,stime); dispc=dispc+1; %#ok<*NASGU> + [Ybr,resT3] = cat_vol_resize(single(Yb),'reduceV',vx_vol,min(1,cat_stat_nanmean(vx_vol)*2),32,'meanm'); + Ybr = cat_vol_morph(Ybr>0.5,'labclose',gc.f/mean(resT3.vx_volr)); + Ybr = cat_vol_resize(Ybr,'dereduceV',resT3)>0.5; + Yb = Yb | Ybr; clear Ybr; % & Ym>=gc.o/3 & Ym<1.25/3 & ~Ymg & Ycsf>0.75); + Yb = single(cat_vol_morph(Yb,'o',max(1,min(3,4 - 0.2*gc.f* (rvol(1)/0.4) ))./cat_stat_nanmean(vx_vol))); + Yb = Yb | (cat_vol_morph(Yb ,'labclose',vxd*2) & Ym<1.1); + Yb = cat_vol_morph(Yb ,'labclose'); + Ybs = single(Yb)+0; spm_smooth(Ybs,Ybs,3./vx_vol); Yb = Yb>0.5 | (max(Yb,Ybs)>0.3 & Ym<0.4); % how wide + Ybs = single(Yb)+0; spm_smooth(Ybs,Ybs,2./vx_vol); Yb = max(Yb,Ybs)>0.4; % final smoothing + clear Ybs; + + %% go back to original resolution + Yb = cat_vol_resize(Yb , 'dereduceBrain' , BB); + if exist('resT0','var') + Yb = cat_vol_resize( single(Yb) , 'dereduceV' , resT0 )>0.5; + end + + %% update Yl1 with Yb + if nargout>1 + Yl1 = Yl1o; + Yl1(~Yb) = 0; + [tmp0,tmp1,Yl1] = cat_vbdist(single(Yl1),Yl1==0 & Yb); clear tmp0 tmp1; + end + + cat_io_cmd(' ','','',opt.verb,stime); +% cat_io_cmd('cleanup',dispc,'',opt.verb); + +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_spm_preproc_run.m",".m","12621","357","function varargout = cat_spm_preproc_run(job,action) +% Segment a bunch of images +% FORMAT spm_preproc_run(job) +% job.channel(n).vols{m} +% job.channel(n).biasreg +% job.channel(n).biasfwhm +% job.channel(n).write +% job.tissue(k).tpm +% job.tissue(k).ngaus +% job.tissue(k).native +% job.tissue(k).warped +% job.warp.mrf +% job.warp.cleanup +% job.warp.affreg +% job.warp.reg +% job.warp.fwhm +% job.warp.samp +% job.warp.write +% job.warp.bb +% job.warp.vox +% job.iterations +% job.alpha +% +% See the batch interface for a description of the fields. +% +% See also spm_preproc8.m amd spm_preproc_write8.m +%__________________________________________________________________________ +% Copyright (C) 2008-2015 Wellcome Trust Centre for Neuroimaging +% John Ashburner +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + +if nargin == 1, action = 'run'; end +if ~isfield(job,'Yclsout'), if nargout==0, job.Yclsout = [0 0 0 0 0 0]; else job.Yclsout = [1 1 1 1 1 1]; end; end %% ADDED RD +switch lower(action) + case 'run' + varargout{1} = run_job(job); + case 'check' + varargout{1} = check_job(job); + case 'vfiles' + varargout{1} = vfiles_job(job); + case 'vout' + varargout{1} = vout_job(job); + otherwise + error('Unknown argument (""%s"").', action); +end + + +%========================================================================== +% Run +%========================================================================== +function vout = run_job(job) + +vout = vout_job(job); +tpm = strvcat(cat(1,job.tissue(:).tpm)); +tpm = spm_load_priors8(tpm); + +if ~isfield(job,'iterations'), nit = 1; else nit = job.iterations; end +if ~isfield(job,'alpha'), alpha = 12; else alpha = job.alpha; end +if ~isfield(job.warp,'fwhm'), job.warp.fwhm = 1; end +if ~isfield(job.warp,'bb'), job.warp.bb = NaN(2,3); end +if ~isfield(job.warp,'vox'), job.warp.vox = 1.5; end +if ~isfield(job.warp,'cleanup'), job.warp.cleanup = 0; end +if ~isfield(job.warp,'mrf'), job.warp.mrf = 0; end + +if nit > 1 + orig_priors = tpm; +end + +for iter=1:nit + for subj=1:numel(job.channel(1).vols) + %fprintf('Segment %s\n',spm_file(job.channel(1).vols{subj},... + % 'link','spm_image(''display'',''%s'')')); + + images = cell(numel(job.channel),1); + for n=1:numel(job.channel) + images{n} = job.channel(n).vols{subj}; + end + obj.image = spm_vol(char(images)); + spm_check_orientations(obj.image); + + obj.fwhm = job.warp.fwhm; + obj.biasreg = cat(1,job.channel(:).biasreg); + obj.biasfwhm = cat(1,job.channel(:).biasfwhm); + obj.tpm = tpm; + obj.lkp = []; + if all(isfinite(cat(1,job.tissue.ngaus))) + for k=1:numel(job.tissue), + obj.lkp = [obj.lkp ones(1,job.tissue(k).ngaus)*k]; + end; + end + obj.reg = job.warp.reg; + obj.samp = job.warp.samp; + + if iter==1 + % Initial affine registration. + Affine = eye(4); + if ~isempty(job.warp.affreg) + if isfield(job.warp,'Affine') + Affine = job.warp.Affine; + else + % Sometimes the image origins are poorly specified, in which case it might be worth trying + % the centre of the field of view instead. The idea here is to run a coarse registration + % using two sets of starting estimates, and pick the one producing the better objective function. + + % Run using origin at centre of the field of view + im1 = obj.image(1); + M = im1.mat; + c = (im1.dim+1)/2; + im1.mat(1:3,4) = -M(1:3,1:3)*c(:); + warning('off','MATLAB:RandStream:ActivatingLegacyGenerators') + [Affine1,ll1] = spm_maff8(im1,8,(obj.fwhm+1)*16,tpm,[],job.warp.affreg); % Closer to rigid + Affine1 = Affine1*(im1.mat/M); + + % Run using the origin from the header + im1 = obj.image(1); + [Affine2,ll2] = spm_maff8(im1,8,(obj.fwhm+1)*16,tpm,[],job.warp.affreg); % Closer to rigid + + % Pick the result with the best fit and use as starting estimate + if ll1>ll2 + Affine = Affine1; + else + Affine = Affine2; + end + end + warning('off','MATLAB:RandStream:ActivatingLegacyGenerators') + Affine = spm_maff8(obj.image(1),job.warp.samp,(obj.fwhm+1)*16,tpm,Affine,job.warp.affreg); % Closer to rigid + Affine = spm_maff8(obj.image(1),job.warp.samp, obj.fwhm, tpm,Affine,job.warp.affreg); + end + obj.Affine = Affine; + else + % Load results from previous iteration for use with next round of + % iterations, with the new group-specific tissue probability map. + [pth,nam] = fileparts(job.channel(1).vols{subj}); + res = load(fullfile(pth,[nam '_seg8.mat'])); + obj.Affine = res.Affine; + obj.Twarp = res.Twarp; + obj.Tbias = res.Tbias; + if ~isempty(obj.lkp) + obj.mg = res.mg; + obj.mn = res.mn; + obj.vr = res.vr; + end + end + + % in case masking is needed (e.g. CFM for lesions) + if isfield(job,'msk') + obj.msk = job.msk ; + end + + if isfield(job,'tol') + obj.tol = job.tol; + end + res = cat_spm_preproc8(obj); + + if ~isfield(job,'savemat') || job.savemat==1 + try + [pth,nam] = fileparts(job.channel(1).vols{subj}); + save(fullfile(pth,[nam '_seg8.mat']),'-struct','res', spm_get_defaults('mat.format')); + catch + end + end + + if iter==nit + % Final iteration, so write out the required data. + tmp1 = [cat(1,job.tissue(:).native) cat(1,job.tissue(:).warped)]; + tmp2 = cat(1,job.channel(:).write); + tmp3 = job.warp.write; + if any(job.Yclsout) %% ADDED RD + [vout.Ym,vout.Ycls] = cat_spm_preproc_write8(res,tmp1,tmp2,tmp3,job.warp.mrf,job.warp.cleanup,job.warp.bb,job.warp.vox,job.Yclsout); + else + vout.Ym = cat_spm_preproc_write8(res,tmp1,tmp2,tmp3,job.warp.mrf,job.warp.cleanup,job.warp.bb,job.warp.vox); + end + vout.res = res; %% ADDED RD + else + % Not the final iteration, so compute sufficient statistics for + % re-estimating the template data. + N = numel(job.channel); + K = numel(job.tissue); + [cls,M1] = spm_preproc_write8(res,zeros(K,4),zeros(N,2),[0 0],job.warp.mrf,... + job.warp.cleanup,job.warp.bb,job.warp.vox); + + if subj==1 + % Sufficient statistics for possible generation of group-specific + % template data. + SS = zeros([size(cls{1}),numel(cls)],'single'); + end + + for k=1:K + SS(:,:,:,k) = SS(:,:,:,k) + cls{k}; + end + end + + end + if iter1 + % Treat the tissue probability maps as Dirichlet priors, and compute the + % MAP estimate of group tissue probability map using the sufficient + % statistics. + [x1,x2] = ndgrid(1:size(SS,1),1:size(SS,2)); + for i=1:size(SS,3) + M = orig_priors.M\M1; + y1 = M(1,1)*x1 + M(1,2)*x2 + M(1,3)*i + M(1,4); + y2 = M(2,1)*x1 + M(2,2)*x2 + M(2,3)*i + M(2,4); + y3 = M(3,1)*x1 + M(3,2)*x2 + M(3,3)*i + M(3,4); + b = spm_sample_priors8(orig_priors,y1,y2,y3); + msk = (y1<1) | (y1>orig_priors.V(1).dim(1)) | ... + (y2<1) | (y2>orig_priors.V(1).dim(2)) | ... + (y3<1) | (y3>orig_priors.V(1).dim(3)); + for k=1:K + bk = b{k}*alpha; + bk(msk) = bk(msk)*0.01; + SS(:,:,i,k) = SS(:,:,i,k) + bk; + end + end + save SS.mat SS M1 + tpm.M = M1; + s = sum(SS,4); + for k=1:K + tmp = SS(:,:,:,k)./s; + tpm.bg1(k) = mean(mean(tmp(:,:,1))); + tpm.bg2(k) = mean(mean(tmp(:,:,end))); + tpm.dat{k} = spm_bsplinc(log(tmp+tpm.tiny),[ones(1,3)*(tpm.deg-1) 0 0 0]); + end + end +end + + +%========================================================================== +% Check +%========================================================================== +function msg = check_job(job) +msg = {}; +if numel(job.channel) >1 + k = numel(job.channel(1).vols); + for i=2:numel(job.channel) + if numel(job.channel(i).vols)~=k + msg = {['Incompatible number of images in channel ' num2str(i)]}; + break + end + end +elseif numel(job.channel)==0 + msg = {'No data'}; +end + + +%========================================================================== +% Vout +%========================================================================== +function vout = vout_job(job) + +n = numel(job.channel(1).vols); +parts = cell(n,4); + +channel = struct('biasfield',{},'biascorr',{}); +for i=1:numel(job.channel) + for j=1:n, + [parts{j,:}] = spm_fileparts(job.channel(i).vols{j}); + end + if job.channel(i).write(1) + channel(i).biasfield = cell(n,1); + for j=1:n + channel(i).biasfield{j} = fullfile(parts{j,1},['BiasField_',parts{j,2},'.nii']); + end + end + if job.channel(i).write(2) + channel(i).biascorr = cell(n,1); + for j=1:n + channel(i).biascorr{j} = fullfile(parts{j,1},['m',parts{j,2},'.nii']); + end + end +end + +for j=1:n + [parts{j,:}] = spm_fileparts(job.channel(1).vols{j}); +end +param = cell(n,1); +for j=1:n + param{j} = fullfile(parts{j,1},[parts{j,2},'_seg8.mat']); +end + +tiss = struct('c',{},'rc',{},'wc',{},'mwc',{}); +for i=1:numel(job.tissue) + if job.tissue(i).native(1) + tiss(i).c = cell(n,1); + for j=1:n + tiss(i).c{j} = fullfile(parts{j,1},['c',num2str(i),parts{j,2},'.nii']); + end + end + if job.tissue(i).native(2) + tiss(i).rc = cell(n,1); + for j=1:n + tiss(i).rc{j} = fullfile(parts{j,1},['rc',num2str(i),parts{j,2},'.nii']); + end + end + if job.tissue(i).warped(1) + tiss(i).wc = cell(n,1); + for j=1:n + tiss(i).wc{j} = fullfile(parts{j,1},['wc',num2str(i),parts{j,2},'.nii']); + end + end + if job.tissue(i).warped(2) + tiss(i).mwc = cell(n,1); + for j=1:n + tiss(i).mwc{j} = fullfile(parts{j,1},['mwc',num2str(i),parts{j,2},'.nii']); + end + end +end + +if job.warp.write(1) + invdef = cell(n,1); + for j=1:n + invdef{j} = fullfile(parts{j,1},['iy_',parts{j,2},'.nii']); + end +else + invdef = {}; +end + +if job.warp.write(2) + fordef = cell(n,1); + for j=1:n + fordef{j} = fullfile(parts{j,1},['y_',parts{j,2},'.nii']); + end +else + fordef = {}; +end + +vout = struct('channel',channel,'tiss',tiss,'param',{param},'invdef',{invdef},'fordef',{fordef}); + + +%========================================================================== +% Vfiles +%========================================================================== +function vf = vfiles_job(job) +vout = vout_job(job); +vf = vout.param; +if ~isempty(vout.invdef), vf = {vf{:}, vout.invdef{:}}; end +if ~isempty(vout.fordef), vf = {vf{:}, vout.fordef{:}}; end +for i=1:numel(vout.channel) + if ~isempty(vout.channel(i).biasfield), vf = {vf{:}, vout.channel(i).biasfield{:}}; end + if ~isempty(vout.channel(i).biascorr), vf = {vf{:}, vout.channel(i).biascorr{:}}; end +end + +for i=1:numel(vout.tiss) + if ~isempty(vout.tiss(i).c), vf = {vf{:}, vout.tiss(i).c{:}}; end + if ~isempty(vout.tiss(i).rc), vf = {vf{:}, vout.tiss(i).rc{:}}; end + if ~isempty(vout.tiss(i).wc), vf = {vf{:}, vout.tiss(i).wc{:}}; end + if ~isempty(vout.tiss(i).mwc), vf = {vf{:}, vout.tiss(i).mwc{:}}; end +end +vf = reshape(vf,numel(vf),1); +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_stat_orth_nuisance.m",".m","1111","50","function G_orth = cat_stat_orth_nuisance(C,G) +% Orthogonalization of nuisance parameters G w.r.t C +% FORMAT G_orth = cat_stat_orth_nuisance(C,G) +% C - vector of covariate parameter +% G - matrix of nuisance parameter +% +% G_orth - orthogonalized nuisance parameter +% +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +if nargin < 2 + fprintf('Syntax: G = cat_stat_orth_nuisance(C,G)\n'); + G = []; + return +end + +if size(C,2) > size(C,1) + C = C'; + G = G'; + trans = 1; +else + trans = 0; +end + +if size(C,1) ~= size(G,1) + fprintf('Parameters C and G have different length: %d vs %d\n',size(C,1),size(G,1)); + G = []; + return +end + +if size(C,2) ~= 1 + fprintf('Parameters C must have only one column: %d \n',size(C,2)); + G = []; + return +end + +C2 = [ones(size(C)) C]; +G_orth = G - C2*(pinv(C2)*G); + +if trans + G_orth = G_orth'; +end +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_debug.m",".m","1254","41","function cat_debug +%cat_debug print debug information for SPM12 and CAT12 +% +% FORMAT cat_debug +% +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +rev = '$Rev$'; + +% print last error +fprintf('\nLast error message:\n'); +fprintf('-------------------------------------------------------------------------------------\n'); +fprintf('-------------------------------------------------------------------------------------\n'); +try + er = lasterror; + fprintf('%s\n',er.message); + if isfield(er,'stack') + for i=1:length(er.stack) + fprintf('%s at line %g\n',char(er.stack(i).file),er.stack(i).line); + end + end +catch + fprintf('%s\n',lasterr); +end + +fprintf('-------------------------------------------------------------------------------------\n'); +fprintf('-------------------------------------------------------------------------------------\n'); + +fprintf('\nVersion information:\n'); +fprintf('-------------------------------------------------------------------------------------\n'); + +ver + +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_plot_glassbrain.m",".m","2298","78","function [img,range] = cat_plot_glassbrain(P) +%cat_plot_glassbrain. Create glassbrain images +% +% [img,range] = cat_plot_glassbrain(P) +% +% P .. filename or image header +% img .. glassbrain rendering (cell with 3 views + colormap) +% range .. minimum and maximum intensities +% +% Used in cat_long_report. +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + if isstruct(P) + V = P; + if isfield(V,'dat') + Y = P.dat(:,:,:); + else + Y = spm_read_vols(V); + end + else + V = spm_vol(P); + Y = spm_read_vols(V); + end + + if 0 + % load additional atlas maps, eg. to outline the ventricles or the cerebellum + LAB = cat_get_defaults('extopts.LAB'); + VT1 = spm_vol(char(cat_get_defaults('extopts.T1'))); + YT1 = spm_read_vols(VT1); + YT1 = cat_vol_sample(VT1,V,YT1,1); + VA = spm_vol(char(cat_get_defaults('extopts.cat12atlas'))); + YA = spm_read_vols(VA); + + YCT = smooth3(YA==LAB.CT | YA==(LAB.CT+1)) & YT1>0.1; + YV = smooth3(YA==LAB.VT | YA==(LAB.VT+1)); + end + + %% main + img{1} = flip(rot90(cat_stat_nansum(Y,3),1),2); + img{2} = rot90(cat_stat_nansum(shiftdim(Y,2),3),2); + img{3} = rot90(cat_stat_nansum(flip(shiftdim(Y,1),2),3),-1); + + % create a (symmetric) colormap image + imax = max( abs( [img{1}(:); img{2}(:); img{3}(:) ] )); + if all( [img{1}(:); img{2}(:); img{3}(:)] >= 0 ) + img{4} = flip( (0:imax/128:imax)' , 1); + range = [0 imax]; + else + img{4} = flip( (-imax:(2*imax)/128:imax)' , 1); + range = [-imax imax]; + end + + if 0 + %% test area + %d=1; figure; imagesc(log10(max(1,img{d}-2)) + img{d}), colormap pink; axis equal off; + %d=1; figure; imagesc(img{d}), colormap pink; axis equal off; + d=1; + figure(9939); clf(9939); hold on; + image(img{d}); + contour(log(img{d}),[0.2 0.2],'color',[0 0 0]); + if 0 + contour(log(imgct{d}),[0.5 0.5],'color',[0 0 0]); + contour(log(imgv{d}),[0.2 0.2],'color',[0 0 1]); + end + colormap(flip(hot)); + axis equal off; hold off; + end + + +end +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_io_senderrormail.m",".m","2815","85","function cat_io_senderrormail(xml_file,log_file,err_txt) +% ______________________________________________________________________ +% Function that prepares a mail with errors in CAT. +% xml_file - xml-file of errornous data +% log_file - log-file of errornous data +% err_txt - optional error text +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Revision$ $Date$ + +%#ok<*TRYNC> + + % program version + [nam,rev_cat] = cat_version; + [nam,rev_spm] = spm('Ver'); + + % read xml-file + fid = fopen(xml_file,'r'); + if nargin > 2 + err_txt = [err_txt '\n\n']; + else + err_txt = ''; + end + while 1 + tline = fgetl(fid); + if ~ischar(tline), break, end + err_txt = [err_txt tline '\n']; + end + fclose(fid); + + % initial message + emailSubject = sprintf('CAT %s error',rev_cat); + emailSubject = strrep(emailSubject,' ','%20'); + mainBody = sprintf('Hi Christian,\\n\\nan error has occurred in CAT %s with SPM %s with MATLAB %s under %s.\\n%s',... + rev_cat , rev_spm, version('-release') , computer); + + mainBody = sprintf('%s\\nBest regards\\n\\n\\n',mainBody); + mainBody = convert_utf([mainBody err_txt]); + + % final creation of the mail + recipients = 'vbmweb@gmail.com'; + + %% open xml-file if mail does not work + status = web(sprintf('mailto:""%s""?subject=""%s""&body=""%s""',recipients,emailSubject,mainBody),'-browser'); + if status + % try with shorter text + status = web(sprintf('mailto:""%s""?subject=""%s""&body=""%s""',recipients,emailSubject,mainBody(1:8000)),'-browser'); + if status + web(sprintf('mailto:""%s""?subject=""%s""',recipients,emailSubject),'-browser'); + end + end + + % show information anyway because sometimes mail does not open even if status is zero + alert_txt = sprintf('Please send mail to %s and copy content of %s and %s into mail if not already done or attach these files.',recipients,xml_file,log_file); + spm('alert',alert_txt); + edit(xml_file); + edit(log_file); + fprintf('\n\n%s\n',alert_txt) +end + +function txt = convert_utf(txt) + + txt = strrep(txt,':','%20'); + txt = strrep(txt,'""',''''); + txt = strrep(txt,' ','%20'); + txt = strrep(txt,'\n','%0A'); + txt = strrep(txt,'!','%21'); + txt = strrep(txt,'#','%23'); + txt = strrep(txt,'%%','%25'); + txt = strrep(txt,'*','%2A'); + txt = strrep(txt,'/','%2F'); + txt = strrep(txt,'<','%3C'); + txt = strrep(txt,'>','%3E'); + txt = strrep(txt,'?','%3F'); + txt = strrep(txt,'(','%28'); + txt = strrep(txt,')','%29'); + txt = strrep(txt,'\\\\\\\\','\'); + txt = strrep(txt,'\\\\','\'); + txt = strrep(txt,'\\','\'); +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_long_multi_run.m",".m","9883","285","function out = cat_long_multi_run(job) +% Call cat_long_main for multiple subjects +% +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +warning off; + +if isdeployed, job.nproc = 0; end + +% use some options from GUI or default file +opts = job.opts; +extopts = job.extopts; +output = job.output; +modulate = job.modulate; +dartel = job.dartel; +ROImenu = job.ROImenu; +longmodel = job.longmodel; +printlong = job.printlong; +useprior = job.enablepriors; +surfaces = job.output.surface; +longTPM = job.longTPM; + +setappdata(0,'job',job); + +if isfield(job,'delete_temp') + delete_temp = job.delete_temp; +else + delete_temp = 1; +end + +% modify job.subj w.r.t. different selection options +if isfield(job,'datalong') + + if isfield(job.datalong,'subjects') + job.data = {}; + + for si = 1:numel(job.datalong.subjects) + for ti = 1:numel(job.datalong.subjects{si}) + job.subj(si).mov{ti,1} = job.datalong.subjects{si}{ti}; + end + job.data = [job.data; job.datalong.subjects{si}]; + end + else + job.data = {}; + + n_ti = numel(job.datalong.timepoints{1}); + for si = 1:numel(job.datalong.timepoints) + for ti = 1:numel(job.datalong.timepoints{si}) + job.subj(ti).mov(si) = job.datalong.timepoints{si}(ti); + end + % check that number of time points does not differ + if numel(job.datalong.timepoints{si}) ~= n_ti + error('Number of time points differ between the subjects. Please take care to select the same number of time points for all subjects!'); + end + job.data = [job.data job.datalong.timepoints{si}]; + end + end + + % remove datalong field to prevent that modification of job.subjs is called again + job = rmfield(job,'datalong'); + + is_copied = zeros(numel(job.data),1); + + % create BIDS structure and unzip or copy file to BIDS-folder + if isfield(job.output,'BIDS') + if isfield(job.output.BIDS,'BIDSyes') + + c = 1; + is_copied = ones(numel(job.data),1); + for ti = 1:numel(job.subj) + + BIDSfolder = job.output.BIDS.BIDSyes.BIDSfolder; + + % get path of first data set and find ""sub-"" BIDS part + name1 = spm_file(job.data{c},'fpath'); + ind = min(strfind(name1,'sub-')); + + if ~isempty(ind) + % remove leading "".."" for real BIDS structure + BIDSfolder = strrep(BIDSfolder,['..' filesep],''); + + length_name = length(name1); + + % Shorten path until ""sub-"" indicator is found and add additional + % relative paths to get BIDSfolder relative to ""sub-"" directories. + % This is necessary because there might be additional session + % folders and more + while length_name > ind + name1 = spm_file(name1,'fpath'); + length_name = length(name1); + BIDSfolder = ['..' filesep BIDSfolder]; + end + end + + % we need this in job.extopts for cat_io_subfolders + job.extopts.BIDSfolder = BIDSfolder; + + for si = 1:numel(job.subj(ti).mov) + [pth,nam,ext] = spm_fileparts(job.subj(ti).mov{si}); + rootfolder = cat_io_subfolders(job.subj(ti).mov{si},job); + % remove additional mri subfolder because registration first will + % work in the upper folder + ind = strfind(rootfolder,[filesep 'mri']); + if ~isempty(ind), rootfolder(ind:end) = []; end + + name = fullfile(pth,[nam ext]); + newdir = fullfile(pth,rootfolder); + % uncompress nii.gz files and change file name for job + if strcmp(ext,'.gz') + fname = gunzip(name,newdir); + fprintf('Uncompress %s to %s\n',name,newdir); + job.subj(ti).mov{si} = char(fname); + job.data{c} = char(fname); + else + if ~exist(newdir), mkdir(newdir); end + is_copied(c) = 2; + s = copyfile(name,newdir); + if ~s + error('Could not write %s to %s',name,newdir); + else + fprintf('Copy %s to %s\n',name,newdir); + job.subj(ti).mov{si} = fullfile(newdir,[nam ext]); + job.data{c} = fullfile(newdir,[nam ext]); + end + end + c = c + 1; + end + end + + else + job.output = rmfield(job.output,'BIDS'); + if isfield(job.extopts,'BIDSfolder'), job.extopts = rmfield(job.extopts,'BIDSfolder'); end + output = job.output; + extopts = job.extopts; + + end + end + + % also uncompress gz-files for non-BIDS structure + if ~isfield(job.extopts,'BIDSfolder') || isempty(job.extopts.BIDSfolder) + c = 1; + for ti = 1:numel(job.subj) + for si = 1:numel(job.subj(ti).mov) + [pth,nam,ext] = spm_fileparts(job.subj(ti).mov{si}); + % uncompress nii.gz files and change file name for job + if strcmp(ext,'.gz') + is_copied(c) = 1; + fname = gunzip(job.subj(ti).mov{si}); + job.subj(ti).mov{si} = char(fname); + job.data{c} = char(fname); + fprintf('Uncompress %s\n',job.subj(ti).mov{si}); + end + c = c + 1; + end + end + else + % remove BIDS fields because files are now already copied to BIDS-folder + job.output = rmfield(job.output,'BIDS'); + job.extopts = rmfield(job.extopts,'BIDSfolder'); + output = job.output; + extopts = job.extopts; + end + +end + +job_name = fullfile(fileparts(mfilename('fullpath')),'cat_long_main.txt'); + +% we have to copy the original txt-file to a matlab file because for deployed versions +% matlab files will be always pre-compiled, but we need the original matlab file untouched +m_job_name = strrep(job_name,'.txt','.m'); +if isdeployed + txt_fileid = fopen(job_name,'r'); + txt_contents = fread(txt_fileid); + fclose(txt_fileid); + + m_fileid = fopen(m_job_name,'r'); + m_contents = fread(m_fileid); + fclose(m_fileid); + + % check whether length of txt- and m-file differs or content differs and only then the txt-file will be copied + % this allows to pre-install the m-file on systems where this file is read-only + if (length(txt_contents) == length(m_contents) && any(txt_contents ~= m_contents)) || (length(txt_contents) ~= length(m_contents)) + [status, mesg] = copyfile(job_name,m_job_name,'f'); + if ~status + % try to save the file to current folder, but it'snot sure that this always works + [pth,name] = fileparts(m_job_name); + m_job_name = fullfile('.',name); + [status, mesg] = copyfile(job_name,m_job_name,'f'); + end + end + +end + +if ~exist(m_job_name,'file') + fprintf(mesg); + fprintf('\nIf you do not have write permissions, the administrator should copy the %s file to %s after installing the precompiled version. This prevents overwriting the read-only file.\n',job_name,m_job_name); + return +end + +% mirror jobs for all subjects +jobs = repmat({m_job_name}, 1, numel(job.subj)); + +inputs = cell(1, numel(job.subj)); + +out.surf = cell(''); out.thick = cell(''); out.mwp1 = cell(''); +out.catreport = cell(''); out.catroi = cell(''); + +for i=1:numel(job.subj) + [mrifolder, reportfolder, surffolder, labelfolder] = cat_io_subfolders(job.subj(i).mov{1},job); + + out.sess(i).warps = cell(1,1); + [pth,nam,ext,num] = spm_fileparts(job.subj(i).mov{1}); + out.sess(i).warps{1} = fullfile(pth,mrifolder,['avg_y_', nam, ext, num]); + + out.sess(i).files = cell(numel(job.subj(i).mov),1); + m = numel(job.subj(i).mov); + data = cell(m,1); + for j=1:m + [pth,nam,ext,num] = spm_fileparts(job.subj(i).mov{j}); + switch modulate + case 0 + out.sess(i).files{j} = fullfile(pth,mrifolder,['wp1r', nam, ext, num]); + case 1 + out.sess(i).files{j} = fullfile(pth,mrifolder,['mwp1r', nam, ext, num]); + case 2 + out.sess(i).files{j} = fullfile(pth,mrifolder,['m0wp1r', nam, ext, num]); + end + data{j} = job.subj(i).mov{j}; + + out.mwp1 = [out.mwp1 fullfile(pth,mrifolder ,['mwp1r' nam ext num])]; + out.surf = [out.surf fullfile(pth,surffolder ,['lh.central.r' nam '.gii'])]; + out.thick = [out.thick fullfile(pth,surffolder ,['lh.thickness.r' nam])]; + out.catreport = [out.catreport fullfile(pth,reportfolder,['cat_r' nam '.xml'])]; + out.catroi = [out.catroi fullfile(pth,labelfolder ,['catROI_r' nam '.xml'])]; + + end + inputs{1,i} = data; + + % save XML Parameter + if ~(isfield(job,'nproc') && job.nproc>0 && (~isfield(job,'process_index')) && numel(job.subj) > 1 ) + [pp,ff] = spm_fileparts(job.subj(i).mov{1}); + longxml = fullfile( pp , reportfolder , ['catlong_' ff '.xml'] ); + jobsx = rmfield(job,{'data','subj'}); + jobsx.subj = job.subj(i); + jobsx.out = out; + jobsx.dirs = struct('mrifolder',mrifolder, 'reportfolder', reportfolder, ... + 'surffolder', surffolder, 'labelfolder', labelfolder, 'pp1', pp, 'ff1', ff); + cat_io_xml(longxml,struct('parameter',jobsx)); + end + + +end + +% split job and data into separate processes to save computation time +if isfield(job,'nproc') && job.nproc>0 && (~isfield(job,'process_index')) && numel(job.subj) > 1 + if nargout==1 + varargout{1} = cat_parallelize(job,mfilename,'subj'); + else + cat_parallelize(job,mfilename,'subj'); + end + return +else + spm_jobman('run',jobs,inputs{:}); +end + +for i=1:numel(job.data) + [pth,nam,ext] = spm_fileparts(job.data{i}); + if exist('is_copied','var') && is_copied(i) + spm_unlink(fullfile(pth,[nam ext])); + if is_copied(i) == 2 + fprintf('Remove copied file %s\n',fullfile(pth,[nam ext])); + else + fprintf('Remove unzipped file %s\n',fullfile(pth,[nam ext])); + end + end +end + +warning on;","MATLAB" +"Neurology","ChristianGaser/cat12","cat_install_tfce.m",".m","1626","51","function varargout = cat_install_tfce(install) +% +% This function will connect to the SBM server and install +% the TFCE toolbox +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +if nargin == 0 + install = spm_input('Install TFCE toolbox',1,'yes|no',[1 0],1); +end + +if install + try + fprintf(' Download and install TFCE...\n'); + d0 = spm('Dir'); + d = fullfile(spm('Dir'),'toolbox'); + lastwarn(''); + s = unzip('http://www.neuro.uni-jena.de/tfce/tfce_latest.zip', d); + fprintf(' Success: %d files have been downloaded.\n',numel(s)); + addpath(d0); + rehash + rehash toolboxcache; + if exist('toolbox_path_cache','file'), toolbox_path_cache; end + eval(['spm fmri;clear cat_version;spm_cat12']); + catch + le = lasterror; + switch le.identifier + case 'MATLAB:checkfilename:urlwriteError' + fprintf(' Update failed: cannot download file.\n'); + otherwise + fprintf('\n%s\n',le.message); + end + end + + [warnmsg, msgid] = lastwarn; + switch msgid + case '' + case 'MATLAB:extractArchive:unableToCreate' + fprintf(' Update failed: check folder permission.\n'); + case 'MATLAB:extractArchive:unableToOverwrite' + fprintf(' Update failed: check file permissions.\n'); + otherwise + fprintf(' Update failed: %s.\n',warnmsg); + end +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_conf_long.m",".m","26320","536","function varargout = cat_conf_long(varargin) +% Configuration file for longitudinal data +% +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +newapproach = 0; + +if newapproach && nargin>0 + [dep,varargout{1},varargout{2}] = vout_long(varargin{1}); + return +end + +try + expert = cat_get_defaults('extopts.expertgui'); +catch %#ok + expert = 0; +end + +% try to estimate number of processor cores +try + numcores = cat_get_defaults('extopts.nproc'); + % because of poor memory management use only half of the cores for windows + if ispc + numcores = round(numcores/2); + end + numcores = max(numcores,1); +catch + numcores = 0; +end + +% force running in the foreground if only one processor was found or for compiled version +% or for Octave +if numcores == 1 || isdeployed || strcmpi(spm_check_version,'octave'), numcores = 0; end + +%------------------------------------------------------------------------ +nproc = cfg_entry; +nproc.tag = 'nproc'; +nproc.name = 'Split job into separate processes'; +nproc.strtype = 'w'; +nproc.val = {numcores}; +nproc.num = [1 1]; +nproc.hidden = numcores <= 1 || isdeployed; +nproc.help = { + 'In order to use multi-threading the CAT12 segmentation job with multiple subjects can be split into separate processes that run in the background. You can even close Matlab, which will not affect the processes that will run in the background without GUI. If you do not want to run processes in the background then set this value to 0.' + '' + 'Keep in mind that each process needs about 1.5..2GB of RAM, which should be considered to choose the appropriate number of processes.' + '' + 'Please further note that no additional modules in the batch can be run except CAT12 segmentation. Any dependencies will be broken for subsequent modules.' + }; +%------------------------------------------------------------------------ +% files long with two different selection schemes +% - timepoints-subjects +% - subjects-timepoints +data = cfg_files; +data.tag = 'data'; +data.name = 'Volumes'; +data.filter = {'image','.*\.(nii.gz)$'}; +data.ufilter = '.*'; +data.num = [1 Inf]; +data.help = {'Select the same number and order of subjects for each time point. '}; + +timepoint = data; +timepoint.tag = 'timepoints'; +timepoint.name = 'Timepoint'; + +timepoints = cfg_repeat; +timepoints.tag = 'timepoints'; +timepoints.name = 'Timepoints'; +timepoints.values = {timepoint}; +timepoints.num = [2 Inf]; +timepoints.help = {'Specify time points. '}; + +subjlong = data; +subjlong.num = [2 Inf]; +subjlong.tag = 'subjects'; +subjlong.name = 'Subject'; +subjlong.help = {'Select all longitudinal T1 images for this subject. '}; + +subjects = cfg_repeat; +subjects.tag = 'subjects'; +subjects.name = 'Subjects'; +subjects.values = {subjlong}; +subjects.num = [1 Inf]; +subjects.help = {'Specify subjects. '}; + +datalong = cfg_choice; +datalong.tag = 'datalong'; +datalong.name = 'Longitudinal data'; +datalong.values = {timepoints subjects}; +datalong.val = {subjects}; +datalong.help = { + ['Select mode of longitudinal data selection for time points or subjects. ' ... + 'In case of ""timepoints"" you can create multiple time points where each time point has to contain the same number and order of subjects. ' ... + 'If you have a varying number of time points for each subject you have to use the ""subjects"" mode where you have to define the files of each subject separately. '] +}; + +%------------------------------------------------------------------------ +longmodel = cfg_menu; +longmodel.tag = 'longmodel'; +longmodel.name = 'Longitudinal Model'; +longmodel.labels = { + 'Optimized for detecting small changes (i.e. plasticity/learning effects)', ... + 'Optimized for detecting large changes (i.e. aging effects)', ... + 'Optimized for detecting large changes with brain/head growth (i.e. developmental effects)', ... + 'Save both plasticity and aging models'}; +longmodel.values = {1 2 0 3}; +longmodel.val = {3}; +if expert + % Add the internal values and the special plasticity & aging model for + % developer only because it is not fully working now (RD20220317). + longmodel.labels{1} = [longmodel.labels{1}(1:end-1) '; 1)']; + longmodel.labels{2} = [longmodel.labels{2}(1:end-1) '; 2)']; + longmodel.labels{3} = [longmodel.labels{3}(1:end-1) '; 3)']; + longmodel.labels{4} = [longmodel.labels{3}(1:end-1) '; 0)']; + if expert > 1 + longmodel.labels{5} = [longmodel.labels{3}(1:end-1) ' V2; 4)']; + longmodel.values{5} = 4; + end +end +longmodel.help = { +'The longitudinal pre-processing in CAT12 has been developed and optimized to detect subtle effects over shorter periods of time (e.g. brain plasticity or training effects after a few weeks or even shorter periods of time) and is less sensitive to detect larger changes over longer periods of time (e.g. ageing or developmental effects). To detect larger effects, we also offer a model that additionally takes into account deformations between time points. The use of deformations between the time points makes it possible to estimate and detect larger changes, while subtle effects over shorter periods of time in the range of weeks or a few months can be better detected with the model for small changes.' +'' +'Unlike the plasticity and ageing models, the developmental pipeline must include a time point-independent registration to adjust the growth of the brain/head. ' +'' +'Please note that due to the additional warping and modulation steps, the resulting files are saved with ""mwmwp1r"" for gray matter instead of ""mwp1r""' +'' +}; +if expert % add some further detail for the combined model that is only available for experts + longmodel.help{end-3} = [longmodel.help{end-1} ... + ' It therefore also requires independent processing and cannot be processed together with the other two models.']; +end + +% The heavy option is at the limit and the images starts to look artifical. +% However, this could be relevant of strong artifacts and plasticity studies. +bstr = cfg_menu; +bstr.tag = 'bstr'; +bstr.name = 'Strength of final longitudinal bias correction (IN DEVELOPMENT)'; +bstr.labels = {'no correction','light','medium','strong'}; %,'heavy'}; +bstr.values = {0,0.25,0.5,0.75}; %,1.0 +bstr.val = {0}; +bstr.hidden = expert<2; +bstr.help = { + 'Strength of final longitudinal bias correction that utilize the average segmentation for further subtile corrections. Test also higher SPM bias correction that also incooperates the information from the average by using the longTPM. Use weaker corrections if the points in time are far apart or if the imgages are less affected by inhomogeneities. Only use stong corrections in case of severe inhomogeneities or artefacts and check the results! ' + 'This correction was introduced in CAT12.7 (2020/10) and is still under test! So use it carefully! ' + '' +}; + +prepavg = cfg_menu; +prepavg.tag = 'prepavg'; +prepavg.name = 'Optimize orignal data before averaging (IN DEVELOPMENT)'; +prepavg.labels = {'no preparation','denoising','denosing+trimming'}; +prepavg.values = {0,1,2}; +prepavg.val = {2}; +prepavg.hidden = expert<2; +prepavg.help = { + 'Denoising, trimming and intensity scaling of the original timepoint data before creating the average. ' + '' +}; + +avgLASWMHC = cfg_menu; +avgLASWMHC.tag = 'avgLASWMHC'; +avgLASWMHC.name = 'Handling of LAS and WMHC on the average (IN DEVELOPMENT)'; +avgLASWMHC.labels = {'classic (AVG=TP)','reduced LAS','reduce LAS & extra WMH class','reduce LAS in TPs & extra WMH class'}; +avgLASWMHC.values = {0,1,2,3}; +avgLASWMHC.val = {0}; +avgLASWMHC.hidden = expert<2; + +avgLASWMHC.help = { + ['The use of the LAS for the creation of the indiviudal TPM as well as in the time point specific processing can result in a overestimation of subcortical GM. ' ... + 'A lower correction in the average or the time point is therefore maybe better suited. ']; + ['The correction of WMHs to the WM is most similar to the original SPM TPM in principle. ' ... + 'However, the many GM-like values of large WMHs seams to bias the WM peak resulting in WM over- and GM underestimation. ' ... + 'Without or with temporar correction (WMHC=0, WMHC=1) the values of WMHs are maybe corrected to GM what can causes problems in the WMHC of the time points. ' ... + 'Using an extra WMH class (WMHC=3) may reduce this bias. ']; + '' +}; + +enablepriors = cfg_menu; +enablepriors.tag = 'enablepriors'; +enablepriors.name = 'Use priors for longitudinal data'; +enablepriors.labels = {'No','Yes'}; +enablepriors.values = {0 1}; +enablepriors.val = {1}; +enablepriors.hidden = expert<1; +enablepriors.help = { + 'The average image is used as a first estimate for affine transformation, segmentation and surface extraction. The idea is that by initializing with the average image we can reduce random variations and improve the robustness and sensitivity of the entire longitudinal pipeline. Furthermore, it significantly increases the speed of the surface extraction.' + '' +}; + +%------------------------------------------------------------------------ +delete_temp = cfg_menu; +delete_temp.tag = 'delete_temp'; +delete_temp.name = 'Delete temporary files'; +delete_temp.labels = {'No','Yes'}; +delete_temp.values = {0 1}; +delete_temp.val = {1}; +delete_temp.help = { +'Temporary files such as the native segmentations, deformation fields or any processed data from the average image are usually removed after preprocessing. However, if you like to keep these files (for debugging) you can enable this option.' +'' +}; + +longTPM = cfg_menu; +longTPM.tag = 'longTPM'; +longTPM.name = 'Use longitudinal TPM from avg image'; +longTPM.labels = {'No','Yes'}; +longTPM.values = {0 1}; +longTPM.val = {1}; +longTPM.hidden = expert<1; +longTPM.help = { +'Use longitudinal TPM from average image.' +}; + +printlong = cfg_menu; +printlong.tag = 'printlong'; +printlong.name = 'Create CAT long report'; +printlong.labels = {'No','Yes (volume only)','Yes (volume and surfaces)'}; +printlong.values = {0 1 2}; +printlong.hidden = expert < 1; +printlong.def = @(val)cat_get_defaults('extopts.print', val{:}); +printlong.help = { + 'Create final longitudinal CAT report that requires Java.' +}; + + +%------------------------------------------------------------------------ + +% boundary box +bb = cfg_entry; +bb.strtype = 'r'; +bb.num = [inf inf]; +bb.tag = 'bb'; +bb.name = 'Bounding box'; +bb.val = {12}; +bb.hidden = expert < 1; +bb.help = { + 'The bounding box describes the dimensions of the volume to be written starting from the anterior commissure in mm. It should include the entire brain (or head in the case of the Boundary Box of the SPM TPM) and additional space for smoothing the image. The MNI 9-mm boundary box is optimized for CATs MNI152NLin2009cAsym template and supports filter cores up to 10 mm. Although this box support 12 mm filter sizes theoretically, slight interference could occur at the edges and larger boxes are recommended for safety. ' + 'Additionally, it is possible to use the boundary box of the TPM or the template for special (animal) templates with strongly different boundary boxes. ' + '' + 'The boundary box or its id (BBid see table below) has to be entered. ' + '' + ' NAME BBID BOUNDARY BOX SIZE ? FILESIZE $ ' + ' TMP BB 0 boundary box of the template (maybe too small for smoothing!) ' + ' TPM BB 1 boundary box of the TPM ' + ' MNI SPM 16 [ -90 -126 -72; 90 90 108 ] [121x145x121] 4.2 MB (100%)' + ' MNI CAT 12 [ -84 -120 -72; 84 84 96 ] [113x139x113] 3.8 MB ( 84%)' + ' ? - for 1.5 mm; $ - for 1.5 mm uint8' + '' +}; + + +%------------------------------------------------------------------------ +extopts = cat_conf_extopts(expert); +if ~expert + extopts.val = [ extopts.val {bb} ]; +end +opts = cat_conf_opts(expert); +output = cat_conf_output(expert); +%------------------------------------------------------------------------ + +% RD202007: Allow only lh+rh surface processing in long mode although this +% this does not help to update default settings via function handle. +clear FN; for vi = 1:numel(output.val), FN{vi} = output.val{vi}.tag; end +surf = find(cellfun('isempty',strfind(FN,'surface'))==0); +output.val{surf}.labels = {'No','Yes'}; +output.val{surf}.values = {0 1}; + + +long = cfg_exbranch; +long.name = 'CAT12: Segment longitudinal data'; +long.tag = 'long'; +if newapproach % new way - not working + + % remove major output fields + clear FN; for vi = 1:numel(output.val), FN{vi} = output.val{vi}.tag; end + removefields = {'warps','jacobianwarped'}; + for vi = 1:numel(removefields) + output.val(find(cellfun('isempty',strfind(FN,removefields{vi}))==0)) = []; + end + + % remove subfields + removefields = {'native'}; + for vim = 1:numel(output.val) + clear FN; for vi = 1:numel(output.val{vim}.val), FN{vi} = output.val{vim}.val{vi}.tag; end + if numel(output.val{vim}.val) + for vi = 1:numel(removefields) + output.val{vim}.val(find(cellfun('isempty',strfind(FN,removefields{vi}))==0)) = []; + end + end + end + + if expert + output.val = [output.val, delete_temp]; + end + long.val = {datalong,longmodel,prepavg,bstr,avgLASWMHC,nproc,opts,extopts,output}; + long.vout = @vout_long2; +else + % old appraoch + %------------------------------------------------------------------------ + modulate = cfg_menu; + modulate.tag = 'modulate'; + modulate.name = 'Modulated GM/WM segmentations'; + modulate.labels = {'No','Yes'}; + modulate.values = {0 1}; + modulate.val = {1}; + modulate.help = { + '""Modulation"" is to compensate for the effect of spatial normalisation. Spatial normalisation causes volume changes due to affine transformation (global scaling) and non-linear warping (local volume change). After modulation the resulting modulated images are preserved for the total amount of grey matter signal in the normalised partitions. Thus, modulated images reflect the tissue volumes before spatial normalisation. However, the user is almost always interested in removing the confound of different brain sizes and there are many ways to apply this correction. In contrast to previous VBM versions I now recommend to use total intracranial volume (TIV) as nuisance parameter in an AnCova model. ' + '' + 'Please note that I do not use the SPM modulation where the original voxels are projected into their new location in the warped images because this method introduces aliasing artifacts. Here, I use the scaling by the Jacobian determinants to generate ""modulated"" data. ' + '' + 'For longitudinal data the modulation is actually not necessary because normalization estimates for one subject are the same for all time points and thus modulation will be also the same for all time points. However, modulation might be useful if you want to compare the baseline images in a cross-sectional design in order to test whether there are any differences between the groups at the beginning of the longitudinal study. ' + '' + }; + + + %------------------------------------------------------------------------ + dartel = cfg_menu; + dartel.tag = 'dartel'; + dartel.name = 'DARTEL export'; + if expert + dartel.labels = {'No','Rigid (SPM12 default)','Affine','Both'}; + dartel.values = {0 1 2 3}; + else + dartel.labels = {'No','Rigid (SPM12 default)','Affine'}; + dartel.values = {0 1 2}; + end + dartel.val = {0}; + dartel.help = { + 'This option is to export data into a form that can be used with DARTEL. The SPM default is to only apply rigid body transformation. However, a more appropriate option is to apply affine transformation, because the additional scaling of the images requires less deformations to non-linearly register brains to the template.' + '' + 'Please note, that this option is only useful if you intend to create a customized DARTEl template for your longittudinal data. The DARTEL exported segmentations is saved for the average image of all time points for one subject (and also for the data of all time points) and can be used in order to create a customized template with the DARTEL toolbox. The resulting flow fields can be finally applied to the respective native segmentations (e.g. p1/p2 images) to obtain normalized segmentations according to the newly created DARTEL template.' + '' + }; + + % extract only the surface, ROI, sROI, and BIDS menu + FN = cell(1,numel(output.val)); for fni=1:numel(output.val), FN{fni} = output.val{fni}.tag; end + ROI = output.val{ setdiff( find(cellfun('isempty',strfind(FN,'ROImenu'))==0) , ... + find(cellfun('isempty',strfind(FN,'sROImenu'))==0,1) ) }; + BIDS = output.val{find(cellfun('isempty',strfind(FN,'BIDS'))==0)}; + surface = output.val{find(cellfun('isempty',strfind(FN,'surface'))==0)}; + + output.val = {BIDS,surface}; + + delete_temp.hidden = expert<1; + + long.val = {datalong,longmodel,enablepriors,prepavg,bstr,avgLASWMHC,nproc,opts,extopts,output,ROI,longTPM,modulate,dartel,printlong,delete_temp}; + +% does not yet work! +% long.vout = @vout_long; +end +long.prog = @cat_long_multi_run; + +long.help = { +'This option offers customized processing of longitudinal data. Please note that two different longitudinal models are offered. The first longitudinal model is optimized for processing and capturing smaller changes over time in response to short-term plasticity effects (e.g. from learning and training). This model will probably not be as sensitive for larger longitudinal changes where large parts of the brain change over time (e.g. atrophy due to Alzheimers disease or aging). This is due to the effect of estimating the parameters of spatial registration from the deformations of all time points and then applying them to all time points. If a large atrophy occurs between the time points, this can lead to a displacement of tissue boundaries and might result in areas with reduced volumes over time, which are surrounded by areas with increased volume due to these displacement problems. For data with larger volume changes over time, you should choose the longitudinal model, which is optimized to detect larger changes. This model also takes into account the deformations between time points and prevents the problems mentioned above.' +'' +'Please note that surface-based preprocessing and ROI estimates are not affected by the selected longitudinal model, as the realigned images are used independently to create cortical surfaces, thickness, or ROI estimates.' +'' +'Furthermore, we use an idea that was introduced by Reuter et al. for the Freesurfer software. Here the processing of the individual time points is initialized by the processed results from the (unbiased) average image. This reduces random variations in the processing procedure and improves the robustness and sensitivity of the overall longitudinal analysis.' +'' +}; + +%------------------------------------------------------------------------ +varargout{1} = long; +return; +%------------------------------------------------------------------------ + + +%------------------------------------------------------------------------ +function dep = vout_long(job) + +% this is not yet working! +if isfield(job.datalong,'subjects') + job.subj = job.datalong.subjects; +else + job.subj = job.datalong.timepoints; +end + +for k=1:numel(job.subj) + cdep = cfg_dep; + cdep.sname = sprintf('Segmented longitudinal data (Subj %d)',k); + cdep.src_output = substruct('.','sess','()',{k},'.','files'); + cdep.tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); + if k == 1 + dep = cdep; + else + dep = [dep cdep]; + end +end; + +% add all surface/thickness files! of all time points and all subjects +if job.output.surface + for k=1:numel(job.subj) + dep(end+1) = cfg_dep; + dep(end).sname = 'mwp1 Images'; + dep(end).src_output = substruct('.','mwp1','()',{':'}); + dep(end).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); + end + for k=1:numel(job.subj) + dep(end+1) = cfg_dep; + dep(end).sname = 'Left Central Surfaces'; + dep(end).src_output = substruct('.','surf','()',{':'}); + dep(end).tgt_spec = cfg_findspec({{'filter','gifti','strtype','e'}}); + end + for k=1:numel(job.subj) + dep(end+1) = cfg_dep; + dep(end).sname = 'Left Thickness'; + dep(end).src_output = substruct('.','thick','()',{':'}); + dep(end).tgt_spec = cfg_findspec({{'filter','any','strtype','e'}}); + end + for k=1:numel(job.subj) + dep(end+1) = cfg_dep; + dep(end).sname = 'CAT Report'; + dep(end).src_output = substruct('.','catreport','()',{':'}); + dep(end).tgt_spec = cfg_findspec({{'filter','xml','strtype','e'}}); + end + for k=1:numel(job.subj) + dep(end+1) = cfg_dep; + dep(end).sname = 'ROI XML File'; + dep(end).src_output = substruct('.','catroi','()',{':'}); + dep(end).tgt_spec = cfg_findspec({{'filter','xml','strtype','e'}}); + end +end + + +%------------------------------------------------------------------------ + +%------------------------------------------------------------------------ +function [dep,out,inputs] = vout_long2(job) + inputs = cell(1, numel(job.subj)); + + [mrifolder, reportfolder, surffolder] = cat_io_subfolders(job.subj(1).mov,job); + + for i=1:numel(job.subj), + %% + out.subj(i).warps = cell(1,1); + if iscell(job.subj(i).mov) + [pth,nam,ext,num] = spm_fileparts(job.subj(i).mov{1}); + else + [pth,nam,ext,num] = spm_fileparts(job.subj(i).mov); + end + out.subj(i).warps{1} = fullfile(pth,mrifolder,['avg_y_', nam, ext, num]); + + out.subj(i).files = cell(numel(cellstr(job.subj(i).mov)),1); + m = numel(cellstr(job.subj(i).mov)); % number of scans of this subject +%% + data = cell(m,1); + for j=1:m + if iscell(job.subj(i).mov) + [pth,nam,ext,num] = spm_fileparts(job.subj(i).mov{j}); + else + [pth,nam,ext,num] = spm_fileparts(job.subj(i).mov); + end + % for output (DEP) + volumes = { + 'GM' 1; + 'WM' 2; + 'CSF' 3; + 'WMH' 7; + }; + + for txi = 1:size(volumes,1) + %% + tissue = { + volumes{txi,1} 'warped' 1 sprintf('wp%d',volumes{txi,2}) sprintf('wp%dr',volumes{txi,2}) ''; + volumes{txi,1} 'mod' [1 3] sprintf('mwp%d',volumes{txi,2}) sprintf('mwp%dr',volumes{txi,2}) ''; + volumes{txi,1} 'mod' [2 3] sprintf('m0wp%d',volumes{txi,2}) sprintf('m0wp%dr',volumes{txi,2}) ''; + volumes{txi,1} 'dartel' [1 3] sprintf('rp%da',volumes{txi,2}) sprintf('rp%dr',volumes{txi,2}) '_affine'; + volumes{txi,1} 'dartel' [2 3] sprintf('rp%dr',volumes{txi,2}) sprintf('rp%dr',volumes{txi,2}) '_affine'; + }; + for ti = 1:size(tissue,1) + if isfield(job.output,tissue{ti,1}) && isfield(job.output.(tissue{ti,1}),tissue{ti,2}) && ... + any( job.output.(tissue{ti,1}).(tissue{ti,2}) == tissue{ti,3} ) + out.subj(i).(tissue{ti,4}){j,1} = fullfile(pth,mrifolder,[(tissue{ti,5}), nam, (tissue{ti,6}), ext, num]); + end + end + end + %% + if isfield(job.output,'labelnative') && job.output.labelnative + out.subj(i).p0{j,1} = fullfile(pth,mrifolder,['p0r', nam, ext, num]); + end + if isfield(job.output.bias,'warped') && job.output.bias.warped + out.subj(i).wm{j,1} = fullfile(pth,mrifolder,['wmr', nam, ext, num]); + end + if job.output.surface + out.subj(i).surface{j,1} = fullfile(pth,surffolder,['lh.central.' , nam, ext, num]); + out.subj(i).thickness{j,1} = fullfile(pth,surffolder,['lh.thickness.', nam, ext, num]); + end + + % for input + if iscell(job.subj(i).mov) + data{j} = job.subj(i).mov{j}; + else + data{j} = cellstr(job.subj(i).mov); + end + end + + inputs{1,i} = data; + end + + %% + maps = {... + ... 'files','warps', ... internal + 'wp1','wp2','wp3','wp7',... % unmodulated (warped==1) + 'mwp1','mwp2','mwp3','mwp7',... % modulated (mod==1 | mod==3) + 'm0wp1','m0wp2','m0wp3','m0wp7', ... % modulated (mod==2 | mod==3) + 'rp1a','rp2a','rp3a','rp7a',... % dartel affine (dartel==1 |?dartel==3) + 'rp1r','rp2r','rp3r','rp7r', ... % dartel rigid (dartel==2 |?dartel==3) + 'p0','wm', ... % + 'surface','thickness' ... % surface + }; + + for mi=1:numel(maps) + for k=1:numel(job.subj) + if isfield(out.subj(k),maps{mi}) + cdep = cfg_dep; + cdep.sname = sprintf('%s files of Subject %d',maps{mi},k); + cdep.src_output = substruct('.','subj','()',{k},'.',maps{mi}); + cdep.tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); + if ~exist('dep','var'); + dep = cdep; + else + dep = [dep cdep]; + end + end + end + end + %% +return +%------------------------------------------------------------------------ +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_stat_polynomial.m",".m","933","36","function y = cat_stat_polynomial(x,p) +% Polynomial expansion and orthogonalization of function x +% FORMAT y = cat_stat_polynomial(x,p) +% x - data matrix +% p - order of polynomial [default: 1] +% +% y - orthogonalized data matrix +%__________________________________________________________________________ +% +% cat_stat_polynomial orthogonalizes a polynomial function of order p +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +if nargin < 2, p = 1; end + +if size(x,1) < size(x,2) + x = x'; +end + +y = spm_detrend(x(:)); +v = zeros(size(y,1),p + 1); + +for j = 0:p + v(:,(j + 1)) = (y.^j) - v*(pinv(v)*(y.^j)); +end + +for j = 2:p + y = [y v(:,(j + 1))]; +end +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_amap.c",".c","8188","213","/* ______________________________________________________________________ + * + * Christian Gaser, Robert Dahnke + * Structural Brain Mapping Group (https://neuro-jena.github.io) + * Departments of Neurology and Psychiatry + * Jena University Hospital + * ______________________________________________________________________ + * $Id$ + * + */ + +/* + * TODO: + * - use structure with defaults for input parameter + * - use long rather to indexing ultra-high-resolution data + */ + +#include ""mex.h"" +#include ""math.h"" +#include ""stdio.h"" +#include ""Amap.h"" +/* #include ""matrix.h"" */ + +void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) +{ + unsigned char *label0, *label, *prob, *mask; + double *src0, *src, *srco, *mean, *fmeans, *fstds, *voxelsize; + double max_vol = -1e15, weight_MRF, bias_fwhm, offset; + const mwSize *dims; + mwSize dims3[4]; + int dims2[4]; + int n_classes, pve, nvox, iters_icm, verb; + int niters, iters_nu, sub, init, thresh, thresh_kmeans_int; + + if (nrhs<11 | nrhs > 12) + mexErrMsgTxt(""11 inputs required: \n [prob, means, stds, srcb] = cat_amap(src, label, n_classes, n_iters, sub, pve, init, mrf_weight, voxelsize, iters_icm, bias_fwhm, verb)""); + else if (nlhs>4) + mexErrMsgTxt(""Too many output arguments.""); + + if (!mxIsDouble(prhs[0])) /* src */ + mexErrMsgTxt(""First argument must be double.""); + if (!mxIsUint8(prhs[1])) /* label */ + mexErrMsgTxt(""Second argument must be uint8.""); + if (!mxIsDouble(prhs[2])) /* n_classes */ + mexErrMsgTxt(""Third argument must be double.""); + if (!mxIsDouble(prhs[3])) /* n_iters */ + mexErrMsgTxt(""4th argument must be double.""); + if (!mxIsDouble(prhs[4])) /* sub */ + mexErrMsgTxt(""5th argument must be double.""); + if (!mxIsDouble(prhs[5])) /* pve */ + mexErrMsgTxt(""6th argument must be double.""); + if (!mxIsDouble(prhs[6])) /* init */ + mexErrMsgTxt(""7th argument must be double.""); + if (!mxIsDouble(prhs[7])) /* mrf_weight */ + mexErrMsgTxt(""8th argument must be double.""); + if (!mxIsDouble(prhs[8])) /* voxelsize */ + mexErrMsgTxt(""9th argument must be double.""); + if (nrhs>9 && !mxIsDouble(prhs[9])) /* iters_icm */ + mexErrMsgTxt(""10th argument must be double.""); + if (nrhs>10 && !mxIsDouble(prhs[10])) /* bias_fwhm */ + mexErrMsgTxt(""11th argument must be double.""); + if (nrhs>11 && !mxIsDouble(prhs[11])) /* verb */ + mexErrMsgTxt(""12th argument must be double.""); + + src0 = (double*)mxGetPr(prhs[0]); + label0 = (unsigned char*)mxGetPr(prhs[1]); + n_classes = (int)mxGetScalar(prhs[2]); + niters = (int)mxGetScalar(prhs[3]); + sub = (int)mxGetScalar(prhs[4]); + pve = (int)mxGetScalar(prhs[5]); + init = (int)mxGetScalar(prhs[6]); + weight_MRF = (double)mxGetScalar(prhs[7]); + voxelsize = (double*)mxGetPr(prhs[8]); + iters_icm = (int)mxGetScalar(prhs[9]); + if (nrhs>10) bias_fwhm = (double)mxGetScalar(prhs[10]); else bias_fwhm = 60.0; + if (nrhs>11) verb = (int)mxGetScalar(prhs[11]); else verb = 0; + + if ( mxGetM(prhs[8])*mxGetN(prhs[8]) != 3) + mexErrMsgTxt(""Voxelsize should have 3 values.""); + + dims = mxGetDimensions(prhs[0]); + dims2[0] = (int)dims[0]; dims2[1] = (int)dims[1]; dims2[2] = (int)dims[2]; dims2[3] = n_classes; + + /* for PVE we need more classes */ + if(pve == 6) dims2[3] += 3; + if(pve == 5) dims2[3] += 2; + + /* mxCreateNumericArray expects mwSize data type */ + for(int i = 0; i < 4; i++) dims3[i] = (mwSize)dims2[i]; + + /* final segmentation */ + plhs[0] = mxCreateNumericArray(4, dims3, mxUINT8_CLASS, mxREAL); + prob = (unsigned char *)mxGetPr(plhs[0]); + + /* internal mean and std values */ + mxArray *hlps[3]; + hlps[0] = mxCreateNumericMatrix(1, n_classes+3, mxDOUBLE_CLASS, mxREAL); /* old segmentation mean values */ + hlps[1] = mxCreateNumericMatrix(1, n_classes+3, mxDOUBLE_CLASS, mxREAL); /* new corrected mean values (may equal to old) */ + hlps[2] = mxCreateNumericMatrix(1, n_classes+3, mxDOUBLE_CLASS, mxREAL); /* new std values */ + mean = (double *)mxGetPr(hlps[0]); + fmeans = (double *)mxGetPr(hlps[1]); + fstds = (double *)mxGetPr(hlps[2]); + for (int i=0; i1 ) { /* means */ + plhs[1] = mxCreateNumericMatrix(1, n_classes, mxDOUBLE_CLASS, mxREAL); + fmeanso = (double *)mxGetPr(plhs[1]); + for (int i=0; i2 ) { /* stds */ + plhs[2] = mxCreateNumericMatrix(1, n_classes, mxDOUBLE_CLASS, mxREAL); + fstdso = (double *)mxGetPr(plhs[2]); + for (int i=0; i3 ) { /* bias corrected */ + plhs[3] = mxCreateNumericArray(3, dims, mxDOUBLE_CLASS, mxREAL); + srco = (double *)mxGetPr(plhs[3]); + for (int i=0; i 0) src[i] += offset; + } + + /* initial labeling using Kmeans */ + if (init>0) { + mask = (unsigned char *)mxMalloc(sizeof(unsigned char)*nvox); + if(mask == NULL) { + mexErrMsgTxt(""Memory allocation error\n""); + exit(EXIT_FAILURE); + } + for (int i=0; i0) ? 255 : 0; + + thresh = 0; + thresh_kmeans_int = 128; + iters_nu = 0; /* bias correction works better inside Amap */ + + /* + * kmeans.c: + * double Kmeans(double *src, unsigned char *label, unsigned char *mask, int NI, int n_clusters, + * double *voxelsize, int *dims, int thresh_mask, int thresh_kmeans, int iters_nu, int pve, double bias_fwhm) + */ + + /* initial Kmeans estimation with 6 classes */ + max_vol = Kmeans( src, label, mask, 25, n_classes, voxelsize, dims2, thresh, thresh_kmeans_int, iters_nu, KMEANS, bias_fwhm); + /* final Kmeans estimation with 3 classes */ + max_vol = Kmeans( src, label, mask, 25, n_classes, voxelsize, dims2, thresh, thresh_kmeans_int, iters_nu, NOPVE, bias_fwhm); + + mxFree(mask); + } + + + /* + * Amap.c: + * void Amap(double *src, unsigned char *label, unsigned char *prob, double *mean, int n_classes, int niters, + * int sub, int *dims, int pve, double weight_MRF, double *voxelsize, int niters_ICM, double offset, double bias_fwhm, + * double *fmeans, double *fstd) + */ + Amap(src, label, prob, mean, n_classes, niters, sub, dims2, pve, weight_MRF, voxelsize, iters_icm, offset, bias_fwhm, verb, fmeans, fstds); + + + /* Pve.c: + * void Pve5(double *src, unsigned char *prob, unsigned char *label, double *mean, int *dims) + * void Pve6(double *src, unsigned char *prob, unsigned char *label, double *mean, int *dims) + */ + if(pve==6) Pve6(src, prob, label, mean, dims2); + if(pve==5) Pve5(src, prob, label, mean, dims2); + + + /* new dynamic output for segmentation mean and std values */ + if ( nlhs>1 ) { + for (int i=0; i2 ) { + for (int i=0; i3 ) { + for (int i=0; i0 + vf{si,smi} = fullfile(outdir,sprintf('%s.%s_%dmm.gii',side{si},job.surfname,job.meshsmooth(smi))); + else + vf{si,smi} = fullfile(outdir,sprintf('%s.%s.gii',side{si},job.surfname)); + end + end + end + +return; +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_stat_quality_measures.m",".m","9328","344","function cat_stat_quality_measures(job) +% To check Z-score across sample using quartic mean z-score and +% save quality measures in csv file. +% +% Images have to be in the same orientation with same voxel size +% and dimension (e.g. spatially registered images) +% +% Surfaces have to be same size (number of vertices). +% +% varargout = cat_stat_quality_measures(job) +% +% job .. SPM job structure +% .data .. volume files +% .globals .. global scaling +% .csv_name .. csv output name +% +% Example: +% cat_stat_quality_measures(struct('data',{{ files }},'globals',1,'csv_name','test.csv')); +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +n_subjects = 0; +sample = []; + +% read header +n_subjects = numel(job.data); +mesh_detected = spm_mesh_detect(char(job.data{1})); + +% use faster nifti function for reading data +if mesh_detected + V = spm_data_hdr_read(char(job.data)); +else + V = nifti(char(job.data)); +end + +pth = spm_fileparts(job.data{1}); +report_folder = fullfile(spm_fileparts(pth),'report'); +subfolder = 1; +% check whether report subfolder exists +if ~exist(report_folder,'dir') + report_folder = pth; + subfolder = 0; +end + +isxml = 0; +% search xml report files +xml_files = spm_select('List',report_folder,'^cat_.*\.xml$'); +if ~isempty(xml_files) + fprintf('Search xml-files\n'); + % find part of xml-filename in data files to get the prepending string + % (e.g. mwp1) + i = 1; j = 1; + while i <= n_subjects + while j <= size(xml_files,1) + % remove ""cat_"" and "".xml"" from name + fname = deblank(xml_files(j,:)); + fname = fname(5:end-4); + + % and find that string in data filename + ind = strfind(job.data{i},fname); + if ~isempty(ind) + [pth, prep_str] = spm_fileparts(job.data{1}(1:ind-1)); + isxml = 1; + i = n_subjects; + j = size(xml_files,1); + break + else + j = j + 1; + end + end + i = i + 1; + end +end + +% check for global scaling with TIV +if job.globals + if mesh_detected + is_gSF = false; + fprintf('Disabled global scaling with TIV, because this is not meaningful for surface data.\n'); + else + if isxml + is_gSF = true; + gSF = ones(n_subjects,1); + else + is_gSF = false; + fprintf('No xml-files found. Disable global scaling with TIV.\n'); + end + end +else + is_gSF = false; +end + +if isxml + if mesh_detected + QM = ones(n_subjects,5); + QM_names = char('Noise','Bias','Weighted overall image quality (IQR)','Euler number','Size of topology defects'); + else + QM = ones(n_subjects,3); + QM_names = char('Noise','Bias','Weighted overall image quality (IQR)'); + end + + cat_progress_bar('Init',n_subjects,'Load xml-files','subjects completed') + for i=1:n_subjects + + % get basename for data files + [pth, data_name] = fileparts(job.data{i}); + + % remove ending for rigid or affine transformed files + data_name = strrep(data_name,'_affine',''); + data_name = strrep(data_name,'_rigid',''); + + % get report folder + if subfolder + report_folder = fullfile(spm_fileparts(pth),'report'); + else + report_folder = pth; + end + + % remove prep_str from name and use report folder and xml extension + if mesh_detected + % for meshes we also have to remove the additional ""."" from name + tmp_str = strrep(data_name,prep_str,''); + xml_file = fullfile(report_folder,['cat_' tmp_str(2:end) '.xml']); + else + xml_file = fullfile(report_folder,['cat_' strrep(data_name,prep_str,'') '.xml']); + end + + if ~exist(xml_file,'file') + isxml = 0; + fprintf('Cannot use quality ratings, because xml-file %s was not found\n',xml_file); + break + end + + if exist(xml_file,'file') + xml = cat_io_xml(xml_file); + else + fprintf('File %s not found. Skip use of xml-files for quality measures.\n',xml_file); + isxml = 0; + break + end + + % get TIV + if is_gSF && isfield(xml,'subjectmeasures') && isfield(xml.subjectmeasures,'vol_TIV') + gSF(i) = xml.subjectmeasures.vol_TIV; + else + is_gSF = false; + end + + if ~isfield(xml,'qualityratings') && ~isfield(xml,'QAM') + fprintf('Quality rating is not saved for %s. Report file %s is incomplete.\nPlease repeat preprocessing amd check for potential errors in the ''err'' folder.\n',job.data{i},xml_files(i,:)); + return + end + if mesh_detected + if isfield(xml.qualityratings,'NCR') + % check for newer available surface measures + if isfield(xml.subjectmeasures,'EC_abs') && isfinite(xml.subjectmeasures.EC_abs) && isfinite(xml.subjectmeasures.defect_size) + QM(i,:) = [xml.qualityratings.NCR xml.qualityratings.ICR xml.qualityratings.IQR xml.subjectmeasures.EC_abs xml.subjectmeasures.defect_size]; + else + QM(i,:) = [xml.qualityratings.NCR xml.qualityratings.ICR xml.qualityratings.IQR NaN NaN]; + end + else % also try to use old version + QM(i,:) = [xml.QAM.QM.NCR xml.QAM.QM.ICR xml.QAM.QM.rms]; + end + else + if isfield(xml.qualityratings,'NCR') + QM(i,:) = [xml.qualityratings.NCR xml.qualityratings.ICR xml.qualityratings.IQR]; + else % also try to use old version + QM(i,:) = [xml.QAM.QM.NCR xml.QAM.QM.ICR xml.QAM.QM.rms]; + end + end + cat_progress_bar('Set',i); + end + cat_progress_bar('Clear'); + + % remove last two columns if EC_abs and defect_size are not defined + if mesh_detected && all(isnan(QM(:,4))) && all(isnan(QM(:,5))) + QM = QM(:,1:3); + end + +end + +[pth,nam] = spm_fileparts(job.data{1}); + +if ~mesh_detected + % voxelsize and origin + vx = sqrt(sum(V(1).mat(1:3,1:3).^2)); + Orig = V(1).mat\[0 0 0 1]'; + + if length(V)>1 && any(any(diff(cat(1,V.dat.dim),1,1),1)) + error('images don''t all have same dimensions') + end + if max(max(max(abs(diff(cat(3,V.mat),1,3))))) > 1e-8 + error('images don''t all have same orientation & voxel size') + end +end + +if is_gSF + fprintf('Use global scaling with TIV\n'); +end + +Ymean = 0.0; +Yss = 0.0; % sum of squares + +fprintf('Load data '); +for i = 1:n_subjects + fprintf('.'); + if mesh_detected + tmp = spm_data_read(V(i)); + else + tmp(:,:,:) = V(i).dat(:,:,:); + end + tmp(isnan(tmp)) = 0; + if is_gSF + tmp = tmp*gSF(i)/mean(gSF); + end + if i>1 && numel(Ymean) ~= numel(tmp) + fprintf('\n\nERROR: File %s has different data size: %d vs. %d\n\n',job.data{i},numel(Ymean),numel(tmp)); + return + end + Ymean = Ymean + tmp(:); + Yss = Yss + tmp(:).^2; +end + +% get mean and SD +Ymean = Ymean/n_subjects; + +% we have sometimes issues with number precision +Yvar = 1.0/(n_subjects-1)*(Yss - n_subjects*Ymean.*Ymean); +Yvar(Yvar<0) = 0; +Ystd = sqrt(Yvar); + +% only consider non-zero areas +ind = Ystd ~= 0; + +% prepare glassbrain +Ytmp = zeros(size(tmp)); +d1 = squeeze(sum(Ytmp,1)); +d2 = squeeze(sum(Ytmp,2)); +d3 = squeeze(sum(Ytmp,3)); + +mean_zscore = zeros(n_subjects,1); +for i = 1:n_subjects + fprintf('.'); + if mesh_detected + tmp = spm_data_read(V(i)); + else + tmp(:,:,:) = V(i).dat(:,:,:); + end + tmp(isnan(tmp)) = 0; + if is_gSF + tmp = tmp*gSF(i)/mean(gSF); + end + % calculate Z-score + zscore = (tmp(ind) - Ymean(ind))./Ystd(ind); + + % calculate glassbrain with emphasized Z-score + Ytmp(ind) = zscore.^4; + Ytmp = reshape(Ytmp,size(tmp)); + d1 = d1 + squeeze(sum(Ytmp,1)); + d2 = d2 + squeeze(sum(Ytmp,2)); + d3 = d3 + squeeze(sum(Ytmp,3)); + + % use mean of Z-score as overall measure, but emphasize outliers by + % using power operation + power_scale = 4; + mean_zscore(i) = mean((abs(zscore).^power_scale))^(1/power_scale); +end +fprintf('\n'); + +% not yet finished +if 0 + mx = max([d1(:); d2(:); d3(:)]); + + figure(11) + colormap(hot(64)) + subplot(2,2,1) + imagesc(rot90(d1),[0 mx]) + axis off image + + subplot(2,2,2) + imagesc(rot90(d2),[0 mx]) + axis off image + + subplot(2,2,3) + imagesc(d3,[0 mx]) + axis off image + +end + +if isxml + % estimate product between weighted overall quality (IQR) and quartic mean Z-score + IQR = QM(:,3); + IQRratio = (mean_zscore/std(mean_zscore)).*(IQR/std(IQR)); + if mesh_detected + Euler_number = QM(:,4); + Topo_defects = QM(:,5); + end +end + +figure +cat_plot_boxplot(mean_zscore,struct('style',2)); + +fid = fopen(job.csv_name,'w'); + +if fid < 0 + error('No write access for %s: check file permissions or disk space.',job.csv_name); +end + +fprintf(fid,'Path;Name;Mean Z-score'); +if isxml + fprintf(fid,';Weighted overall image quality (IQR);Normalized product of IQR and quartic mean Z-score'); + if mesh_detected + fprintf(fid,';Euler Number;Size of topology defects\n'); + else + fprintf(fid,'\n'); + end +else + fprintf(fid,'\n'); +end +for i = 1:n_subjects + [pth, data_name] = fileparts(job.data{i}); + fprintf(fid,'%s;%s;%g',pth,data_name,mean_zscore(i)); + if isxml + fprintf(fid,';%g;%g',IQR(i),IQRratio(i)); + if mesh_detected + fprintf(fid,';%d;%g\n',Euler_number(i),Topo_defects(i)); + else + fprintf(fid,'\n'); + end + else + fprintf(fid,'\n'); + end +end + +if fclose(fid)==0 + fprintf('\nValues saved in %s.\n',job.csv_name); +end +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_main_reportfig.m",".m","93416","1929","function cat_main_reportfig(Ym,Yp0,Yl1,Psurf,job,qa,res,str) +% ______________________________________________________________________ +% +% Display CAT report in the SPM grafics window and save a PDF and JPG +% file in the report directory. +% +% cat_main_reportfig(Ym,Yp0,Psurf,job,res,str); +% +% Ym .. intensity normalized image +% Yp0 .. segmentation label map +% Psurf .. central surface file +% job .. SPM/CAT parameter structure +% res .. SPM result structure +% str .. Parameter strings (see cat_main_reportstr) +% Yl1 .. Label map for ventricle and WMHs +% qa .. WMH handling +% +% special options via: +% job.extopts.colormap .. colormap +% job.extopts.report +% .useoverlay .. different p0 overlays +% (0 - no, 1 - red mask, 2 - atlas [default] ... ) +% .type .. volume/surface print layout +% (1 - Yo,Ym,Yp0,CS-top, 2 - Yo,Yp0,CS-left-right-top) +% .color .. +% See also cat_main_reportstr and cat_main_reportcmd. +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + %#ok<*TRYNC,*AGROW,*ASGLU> + % warning off; %#ok % there is a div by 0 warning in spm_orthviews in linux + dbs = dbstatus; debug = 0; for dbsi=1:numel(dbs), if strcmp(dbs(dbsi).name,mfilename); debug = 1; break; end; end + + global st; % global variable of spm_orthviews + + catdef = cat_get_defaults; + job = cat_io_checkinopt(job,catdef); + + fg = spm_figure('FindWin','Graphics'); + set(0,'CurrentFigure',fg) + + % remove CAT12 figure background image from start + try + fgc = get(fg,'Children'); + if ~isempty(fgc) + fgcc = get(fgc,'Children'); + if ~isempty(fgcc) + % remove figure elements to prevent further interations + delete(fgcc); + spm_figure('Clear',fg) + + % run the reportfig function the first time to fully clear the + % changes by the cat start figure + cat_main_reportfig(Ym,Yp0,Yl1,[],job,qa,res,str) + end + end + end + + def.extopts.report.useoverlay = 2; % different p0 overlays, described below in the Yp0 print settings + % (0 - no, 1 - red mask, 2 - blue BG, red BVs, WMHs [default] ... ) + def.extopts.report.type = 2; % (1 - Yo,Ym,Yp0,CS-top, 2 - Yo,Yp0,CS-left-right-top) + def.extopts.report.color = cat_get_defaults('extopts.report.color'); + % background gray level that focus on: white, black, gray + % [] - current figure, 0.95 - light gray + def.extopts.expertgui = cat_get_defaults('extopts.expertgui'); + def.extopts.WMHC = cat_get_defaults('extopts.WMHC'); + def.extopts.print = 2; + %def.extopts.report.thickvar = 0; % 0 - thickness, 1 - thickness corrected by global mean + %def.extopts.report.orthviewbox = 0; % 0 - off, 1 - on; % not ready + %if job.extopts.report.orthviewbox && cm(1)=='b', for ai=1:3, st.vols{1}.ax{2}.ax.Visible = 'off'; end; end + job = cat_io_checkinopt(job,def); + + if isempty(job.extopts.report.color) + job.extopts.report.color = get(fg,'color'); + elseif numel(job.extopts.report.color)==1 + job.extopts.report.color = ones(1,3) * job.extopts.report.color; + end + if job.extopts.expertgui && isempty(job.extopts.report.color) + job.extopts.report.color = [0.95 0.95 0.95]; + end + + % ratings for colorful ouput of longitudinal results (see also cat_main_reportstr) + QMC = cat_io_colormaps('marks+',17); + QMCt = [cat_io_colormaps('hotinv',30);cat_io_colormaps('cold',30)]; QMCt = QMCt([11:30,32:end-9],:); + color = @(QMC,m) QMC(max(1,min(size(QMC,1),round(((m-1)*3)+1))),:); + colort = @(QMC,m) QMC(max(1,min(size(QMC,1),round((m)))),:); + marks2str = @(mark,str) sprintf('\\color[rgb]{%0.2f %0.2f %0.2f}%s',color(QMC,real(mark)),str); + marks2strt = @(mark,str) sprintf('\\color[rgb]{%0.2f %0.2f %0.2f}%s',colort(QMCt,real(mark*4 + 21)),str); + mark2rps = @(mark) min(100,max(0,105 - real(mark)*10)) + isnan(real(mark)).*real(mark); + + VT = res.image(1); + VT0 = res.image0(1); + % this block is to handle the surface only output of longitudinal reports + if isempty( VT0 ) || isempty(fieldnames(VT0)) + if ~isempty(Psurf) && isfield(Psurf,'Pthick') + [pth,nam,ee] = spm_fileparts(Psurf(1).Pthick); + if ~strcmp(ee,'.gii'), nam = ee(2:end); else, [tmp,nam] = spm_fileparts(nam); end + VT0.fname = Psurf(1).Pthick; + dispvol = 0; + else + cat_io_cprintf('err','Found no volume or surface. Skip printing.\n'); + return; + end + else + [pth,nam] = spm_fileparts(VT0.fname); + dispvol = 1; + end + + % in case of SPM input segmentation we have to add the name here to have a clearly different naming of the CAT output + if isfield(res,'spmpp'), nam = ['c1' nam]; end % no changes in VT0! + + % definition of subfolders + [mrifolder, reportfolder, surffolder, labelfolder] = cat_io_subfolders(VT0.fname,job); + + nprog = ( isfield(job,'printPID') && job.printPID ) || ... PID field + ( isempty(findobj('type','Figure','Tag','CAT') ) && ... no menus + isempty(findobj('type','Figure','Tag','Menu') ) ); + if isempty(fg) + if nprog + fg = spm_figure('Create','Graphics','visible','off'); + else + fg = spm_figure('Create','Graphics','visible','on'); + end + else + if nprog, set(fg,'visible','off'); end + end + set(fg,'windowstyle','normal'); + try, spm_figure('Clear',fg); end + switch computer + case {'PCWIN','PCWIN64'}, fontsize = 8; + case {'GLNXA','GLNXA64'}, fontsize = 8; + case {'MACI','MACI64'}, fontsize = 9.5; + otherwise, fontsize = 9.5; + end + % the size of the figure is adapted to screen size but we must also update the font size + PaperSize = get(fg,'PaperSize'); + spm_figure_scale = get(fg,'Position'); spm_figure_scale = spm_figure_scale(4)*PaperSize(2)/1000; + fontsize = fontsize * spm_figure_scale; + + % get axis + try + ax = axes('Position',[0.01 0.75 0.98 0.24],'Visible','off','Parent',fg); + catch + error('Do not close the SPM Graphics window during preprocessing'); + end + + % set backgroundcolor + if ~isfield(job.extopts,'colormap'), job.extopts.colormap = 'BCGWHw'; end + if ~isempty(job.extopts.report.color) + set(fg,'color',job.extopts.report.color); + if isempty(job.extopts.colormap) || strcmp(job.extopts.colormap,'BCGWHw') + if any( job.extopts.report.color < 0.4 ) + job.extopts.colormap = 'BCGWHn'; + elseif any( job.extopts.report.color < 0.95 ) + job.extopts.colormap = 'BCGWHg'; + end + else + end + if any( job.extopts.report.color < 0.4 ) + fontcolor = [1 1 1]; + else + fontcolor = [0 0 0]; + end + else + job.extopts.colormap = 'BCGWHw'; + fontcolor = [0 0 0]; + end + % check colormap name + cm = job.extopts.colormap; + switch lower(cm) + case {'jet','hsv','hot','cool','spring','summer','autumn','winter',... + 'gray','bone','copper','pink','bcgwhw','bcgwhn','bcgwhg'} + otherwise + cat_io_cprintf(job.color.warning,'WARNING:Unknown Colormap - use default.\n'); + cm = 'gray'; + end + + % some sans serif fonts we prefere + if exist('ax','var') + fontname = get(ax,'fontname'); + end + if strcmpi(spm_check_version,'octave') + fontname = 'Helvetica'; + else + fonts = listfonts; + pfonts = {'Verdana','Arial','Helvetica','Tebuchet MS','Tahoma','Geneva','Microsoft Sans Serif'}; + for pfi = 1:numel(pfonts) + ffonti = []; + try + ffonti = find(cellfun('isempty',strfind(fonts,pfonts{pfi},'ForceCellOutput',1))==0,1,'first'); + end + if ~isempty( ffonti ) + fontname = fonts{ffonti}; + break + end + end + end + + + + + + + %% colormap labels + % ---------------------------------------------------------------------- + % var in: + % out: ytickm, yticklabelm, yticklabelo, yticklabeli, cmap, cmmax + + % SPM_orthviews work with 60 values. + % For the surface we use a larger colormap. + surfcolors = 128; + % In the longitudinal report we use another colormap without white rather + % than green to make it clear that these are changes and not thickness values. + if isfield(res,'long') + cmap3 = flipud(cat_io_colormaps('BWR',surfcolors)); + else + cmap3 = jet(surfcolors); + end + % ################# + % T1 vs T2/PD labeling + % ################ + switch lower(cm) + case {'bcgwhw','bcgwhn','bcgwhg'} + % CAT colormap with larger range colorrange from 0 (BG) to 1 (WM) to 2 (HD). + ytick = [1,5:5:60]; + if isfield(job.extopts,'inv_weighting') && job.extopts.inv_weighting + Tth = [cat_stat_kmeans(Ym(Yp0(:)>0.5 & Yp0(:)<1.5),2,0),... + cat_stat_kmeans(Ym(Yp0(:)>1.5 & Yp0(:)<2.5),5,0),... + cat_stat_kmeans(Ym(Yp0(:)>2.5 & Yp0(:)<3.5),2,0)]; + [x,od] = sort(Tth); tiss = {' CSF',' GM',' WM'}; + yticklabel = {' BG',' ',tiss{od(1)},' ',tiss{od(2)},' ',tiss{od(3)},' ',' ',' ',' ',' ',' Vessels/Head '}; + else + yticklabel = {' BG',' ',' CSF',' CGM',' GM',' GWM',' WM',' ',' ',' ',' ',' ',' Vessels/Head '}; + end + yticklabelo = {' BG',' ',' ',' ',' ',' ',' ~WM ',' ',' ',' ',' ',' ',' Vessels/Head '}; + yticklabeli = {' BG',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' Vessels/Head '}; + cmap = [cat_io_colormaps([cm 'ov'],60);flipud(cat_io_colormaps([cm 'ov'],60));cmap3]; + cmmax = 2; + case {'gray'} + % CAT colormap with larger range colorrange from 0 (BG) to 1 (WM) to 2 (HD). + ytick = [1,15:15:60]; + if isfield(job.extopts,'inv_weighting') && job.extopts.inv_weighting + Tth = [cat_stat_kmeans(Ym(Yp0(:)>0.5 & Yp0(:)<1.5),2,0),... + cat_stat_kmeans(Ym(Yp0(:)>1.5 & Yp0(:)<2.5),5,0),... + cat_stat_kmeans(Ym(Yp0(:)>2.5 & Yp0(:)<3.5),2,0)]; + [x,od] = sort(Tth); tiss = {' CSF',' GM',' WM'}; + yticklabel = {' BG',tiss{od(1)},tiss{od(2)},tiss{od(3)},' Vessels/Head '}; + else + yticklabel = {' BG',' CSF',' GM',' WM',' Vessels/Head '}; + end + yticklabelo = {' BG',' ',' ',' WM',' Vessels/Head '}; + yticklabeli = {' BG',' ',' ',' ',' Vessels/Head '}; + cmap = [eval(sprintf('%s(60)',cm));flipud(eval(sprintf('%s(60)',cm)));cmap3]; + cmmax = 7/6; + case {'jet','hsv','hot','cool','spring','summer','autumn','winter','bone','copper','pink'} + % default colormaps + ytick = [1 20 40 60]; + yticklabel = {' BG',' CSF',' GM',' WM'}; + yticklabelo = {' BG',' ',' ',' WM'}; + yticklabeli = {' BG',' ',' ',' '}; + cmap = [eval(sprintf('%s(60)',cm));flipud(eval(sprintf('%s(60)',cm)));cmap3]; + cmmax = 1; + otherwise + cat_io_cprintf(job.color.warning,'WARNING:Unknown Colormap - use default.\n'); + end + + % For the segmentation map an overlay color map is used that is + % independent of the first colormap. + ytickp0 = [ 1, 13.5, 17.5, 30, 45, 52, 56, 60]; + if job.extopts.expertgui>1 + yticklabelp0 = {' BG',' HD',' CSF',' GM',' WM',' WMHs',' Ventricle',' Vessels/Dura->CSF'}; + else + yticklabelp0 = {' BG',' HD',' CSF',' GM',' WM',' WMHs',' ',' Vessels/Dura->CSF'}; + end + %if job.extopts.WMHC<1 + % yticklabelp0{end-2} = ' \color[rgb]{1,0,1}no WMHC!'; + if isfield(qa,'subjectmeasures') && isfield(qa.subjectmeasures, 'vol_rel_WMH') + if job.extopts.WMHC<2 + if qa.subjectmeasures.vol_rel_WMH>0.01 || ... + (qa.subjectmeasures.vol_abs_WMH / qa.subjectmeasures.vol_abs_CGW(3) )>0.02 + yticklabelp0{end-2} = ' \color[rgb]{1,0,1}uncorrected WMHs=GM!'; + else + yticklabelp0{end-2} = ' no/small WMHs'; + end + elseif job.extopts.WMHC==2 + if qa.subjectmeasures.vol_rel_WMH>0.01 || ... + qa.subjectmeasures.vol_abs_WMH / qa.subjectmeasures.vol_rel_CGW(3)>0.02 + yticklabelp0{end-2} = ' \color[rgb]{1,0,1}WMHs->WM'; + else + yticklabelp0{end-2} = ' no/small WMHs->WM'; + end + else + if qa.subjectmeasures.vol_rel_WMH>0.01 || ... + qa.subjectmeasures.vol_abs_WMH / qa.subjectmeasures.vol_rel_CGW(3)>0.02 + yticklabelp0{end-2} = ' \color[rgb]{1,0,1}WMHs'; + else + yticklabelp0{end-2} = ' no/small WMHs'; + end + end + end + + if strcmpi(spm_check_version,'octave') + colormap(cmap); + else + colormap(fg,cmap); + end + try spm_orthviews('Redraw'); end + % ---------------------------------------------------------------------- + + + + + %% print header and parameters + % ---------------------------------------------------------------------- + warning('off','MATLAB:tex') + + % print header + npara = '\color[rgb]{0 0 0}'; + cpara = '\color[rgb]{0 0 1}'; + if isfield(res,'spmpp') && res.spmpp, SPMCATstr = [cpara 'SPM-']; else, SPMCATstr = 'CAT-'; end + hd = text(0,0.99, [SPMCATstr 'Segmentation: ' npara strrep( strrep( spm_str_manip(VT0.fname,'k80d'),'\','\\'), '_','\_') ' '],... + 'FontName',fontname,'FontSize',fontsize+1,'color',fontcolor,'FontWeight','Bold','Interpreter','tex','Parent',ax); + + % replace tex color settings + if mean(fontcolor)>0.5 + for stri = 1:numel(str) + for stri2 = 1:numel(str{stri}) + colstrb = strfind(str{stri}(stri2).value,'\color[rgb]{'); + for ci = numel(colstrb):-1:1 + colstre = colstrb(ci) + 10 + find( str{stri}(stri2).value(colstrb(ci) + 12 : end) == '}' ,1,'first'); + colval = cell2mat(textscan( str{stri}(stri2).value(colstrb(ci) + 12 : colstre),'%f %f %f')); + if all( colval <= [0.1 0.5 1] ) && colval(3)>0 % replace blue by brighter and bolder values + str{stri}(stri2).value = sprintf('%s%s%s',str{stri}(stri2).value(1:colstrb(ci)-1),... + sprintf('\\bf\\color[rgb]{%f %f %f}',min(1,[0.1 0.7 1.0] + colval)),str{stri}(stri2).value(colstre+2:end)); + elseif mean( colval ) < 0.1 + str{stri}(stri2).value = sprintf('%s%s%s',str{stri}(stri2).value(1:colstrb(ci)-1),... + '\color[rgb]{1 1 1}',str{stri}(stri2).value(colstre+2:end)); + end + end + end + end + end + + % print parameters + htext = zeros(5,2,2); + for i=1:size(str{1},2) % main parameter + htext(1,i,1) = text(0.01,0.98-(0.055*i), str{1}(i).name ,'FontName',fontname,'FontSize',fontsize,'color',fontcolor,'Interpreter','none','Parent',ax); + htext(1,i,2) = text(0.51,0.98-(0.055*i), str{1}(i).value ,'FontName',fontname,'FontSize',fontsize,'color',fontcolor,'Interpreter','tex','Parent',ax); + end + if isfield(res,'long') + % Adaption for longitudinal reports, where we focus on changes between + % timepoints or scanners in case of test-retest data. + % As far as we have some additional plots here also the creation of the + % text/table is here and not in cat_main_reportstr. + + + %% image and processing quality normalized to the best value + % -------------------------------------------------------------------- + + % measures to display + if isfield(res.long,'change_qar_IQR') + IQR = res.long.change_qar_IQR; + else + IQR = nan; + end + ZSCORE = (res.long.vres.zscore - max(res.long.vres.zscore)); + RMSE = (min(res.long.vres.RMSEidiff) - res.long.vres.RMSEidiff )'; + + % text to display (header + main measures) + if isfield(res.long,'qar_IQR') + IQRE = (max(res.long.qar_IQR) - min(res.long.qar_IQR)) + 0.5; + else + IQRE = nan; + end + htext(2,1,1) = text(0.01,0.48 - (0.055 * 1), '\bfImage and preprocessing quality changes (best to worst):', ... + 'FontName',fontname,'FontSize',fontsize,'color',fontcolor,'Interpreter','tex','Parent',ax); + if isfield(res.long,'qar_IQR') + lstr{1}(1) = struct('name','\bf\color[rgb]{.6 0 0}IQR:' , ... + 'value', marks2str(min(res.long.qar_IQR), sprintf('%0.2f%%' ,mark2rps(min(res.long.qar_IQR) )) ), ... ,mark2grad(min(res.long.qar_IQR) + 'value2', marks2str( (IQRE - 0.5) * 2 + 0.5, sprintf('%+0.2fpp',mark2rps(IQRE) - 100))); + else + lstr{1}(1) = struct('name','','value','','value2',''); + end + + % only plot ZSCORE and RMSE if more than two timepoints are available + if ~isnan(ZSCORE) + if numel(res.long.files) > 2 + val = min(res.long.vres.zscore) - max(res.long.vres.zscore); + val2 = marks2str(min(10.5,max(val * 100 + 0.5)),sprintf('%+0.3f',val)); + cstr = '\bf\color[rgb]{0 0.6 0}ZSCORE:'; + else + val2 = ''; + cstr = 'ZSCORE:'; + end + lstr{1}(2) = struct('name',cstr ,... + 'value', marks2str( min(10.5,max(0.5,(0.98 - min(res.long.vres.zscore))*100+0.5)) , sprintf('%0.3f',min(res.long.vres.zscore)) ), ... + 'value2',val2); + if numel(res.long.files) > 2 + val = max(res.long.vres.RMSEidiff) - min(res.long.vres.RMSEidiff); + val2 = marks2str( min(10.5,max(0.5,max(0,val-0.05)*100+0.5)),sprintf('%+0.3f',val)); + cstr = '\bf\color[rgb]{0 .3 .7}RMSE:'; + else + val2 = ''; + cstr = 'RMSE:'; + end + lstr{1}(3) = struct('name',cstr, ... + 'value' ,marks2str( min(10.5,max(0.5,max(0,max(res.long.vres.RMSEidiff) - 0.05)*50+0.5)) , ... + sprintf('%0.3f',max(res.long.vres.RMSEidiff)) ), ... + 'value2',val2); + end + for i=1:size(lstr{1},2) % qa-measurements + htext(2,i+1,1) = text(0.01,0.47-(0.055*(i+1)), lstr{1}(i).name , ... + 'FontName',fontname,'FontSize',fontsize,'color',fontcolor,'Interpreter','tex','Parent',ax); + htext(2,i+1,2) = text(0.135,0.47-(0.055*(i+1)), lstr{1}(i).value , 'HorizontalAlignment','right', ...... + 'FontName',fontname,'FontSize',fontsize,'color',fontcolor,'Interpreter','tex','Parent',ax); + htext(2,i+1,3) = text(0.14,0.47-(0.055*(i+1)), lstr{1}(i).value2, 'HorizontalAlignment','left', ...... + 'FontName',fontname,'FontSize',fontsize,'color',fontcolor,'Interpreter','tex','Parent',ax); + end + + % create figure + mdiff = min([ ZSCORE; (mark2rps(IQRE) - 100)/100; RMSE]); + mlim = min(-0.05,-ceil(abs(mdiff)*20)/20); + tcmap = [0.6 0 0; 0 .6 0; 0 0.3 0.7; 0.5 0.5 0.5]; + marker = {'^','s','>','o'}; + leg = {}; + axi(1) = axes('Position',[0.24,0.745,0.22,0.095],'Parent',fg); cp(1) = gca; hold on; + set(axi(1),'Color',job.extopts.report.color,'YAxisLocation','right','box','on','XAxisLocation','bottom'); + % plot QC boxes + if 0 %mlim < -0.04 + fb = fill(cp{1},[0 numel(res.long.files) numel(res.long.files) 0]+0.5,-[ 40 40 0 0]/1000,'green'); + set(fb,'Facecolor',[0.8 1.0 0.8],'LineStyle','none','FaceAlpha',0.5); leg = [leg {':)'}]; + if mlim < -0.04 + fb = fill(cp{1},[0 numel(res.long.files) numel(res.long.files) 0]+0.5,-[ 80 80 40 40]/1000,'yellow'); + set(fb,'Facecolor',[1.0 1.0 0.8],'LineStyle','none','FaceAlpha',0.5); leg = [leg {':|'}]; + end + if mlim < -0.08 + fb = fill(cp{1},[0 numel(res.long.files) numel(res.long.files) 0]+0.5,[mlim mlim -0.04 -0.04],'red'); + set(fb,'Facecolor',[1.0 0.8 0.8],'LineStyle','none','FaceAlpha',0.5); leg = [leg {':('}]; + end + end + if ~any(isnan(ZSCORE)) && numel(res.long.files) > 2 + leg = [leg {'dIQR/100','dZSCORE','dRMSE'}]; + else + leg = [leg {'dIQR/100'}]; + end + % plot lines + pt = plot( axi(1), IQR/100 ); set(pt,'Color',tcmap(1,:),'Marker',marker{2}, ... + 'MarkerFaceColor',job.extopts.report.color,'MarkerSize',max(3,6 - numel(res.long.files)/10)); + if ~any(isnan(ZSCORE)) && numel(res.long.files) > 2 + pt = plot( axi(1), ZSCORE ); set(pt,'Color',tcmap(2,:),'Marker',marker{1}, ... + 'MarkerFaceColor',job.extopts.report.color,'MarkerSize',max(3,6 - numel(res.long.files)/10)); + pt = plot( axi(1), RMSE); set(pt,'Color',tcmap(3,:),'Marker',marker{3}, ... + 'MarkerFaceColor',job.extopts.report.color,'MarkerSize',max(3,6 - numel(res.long.files)/10)); + end + % final settings + ylim( [mlim 0]); xlim([0.9 numel(res.long.files)+0.1]); + set(cp(1),'Fontsize',fontsize*0.8,'xtick',max(1,0:round(numel(res.long.files)/100)*10:numel(res.long.files)), ... + 'ytick',mlim:max(0.01,round((abs(mlim)/5)*200)/200):0,... + 'XAxisLocation','origin'); + lh(1) = legend(leg,'Location','southoutside','Orientation','horizontal','box','off','FontSize',fontsize*.8); grid on; + + + + + %% morphmetric parameter normalized to the first value + % -------------------------------------------------------------------- + if isfield(res.long,'vol_rel_CGW') + leg = {'dGMV','dWMV','dCSFV'}; + val2f = @(valr,vala) marks2strt(valr * 100,sprintf('%+0.2f',vala)); + htext(3,1,1) = text(0.51,0.48-(0.055), '\bfGlobal tissue volumes and their maximum change:', ... + 'FontName',fontname,'FontSize',fontsize,'color',fontcolor,'Interpreter','tex','Parent',ax); + + % rGMV + li = 1; + valr = max(diff(res.long.vol_rel_CGW(:,2))); + vala = max(diff(res.long.vol_abs_CGW(:,2))); + lstr{2}(li) = struct('name','\bf\color[rgb]{0 0.6 0}GMV:', ... + 'value' , sprintf('%0.0fml' , res.long.vol_abs_CGW(1,2)), ... + 'value2', [val2f(valr,vala) 'ml'] ); + + % rWMV + li = li + 1; + valr = max(diff(res.long.vol_rel_CGW(:,3))); + vala = max(diff(res.long.vol_abs_CGW(:,3))); + lstr{2}(li) = struct('name','\bf\color[rgb]{0.6 0 0}WMV:', ... + 'value' , sprintf('%0.0fml' , res.long.vol_abs_CGW(1,3)), ... + 'value2', [val2f(valr,vala) 'ml'] ); + + % rCSFV + li = li + 1; + valr = max(diff(res.long.vol_rel_CGW(:,1))); + vala = max(diff(res.long.vol_abs_CGW(:,1))); + lstr{2}(li) = struct('name','\bf\color[rgb]{0 .3 0.7}CSFV:', ... + 'value', sprintf('%0.0fml' , res.long.vol_abs_CGW(1,1)), ... + 'value2', [val2f(valr,vala) 'ml'] ); + + % WMHs + % ########################### + if any( res.long.vol_abs_WMH ) + li = li + 1; + leg = [leg,{'dWMHs'}]; + val = max(diff(res.long.vol_abs_WMH)); + lstr{2}(li) = struct('name','\bf\color[rgb]{0.8 0.4 0.8}WMHs:', ... + 'value', sprintf('%0.0fml' , res.long.vol_abs_WMH(1,1)), ... + 'value2', [val2f(max(diff( res.long.vol_abs_WMH ./ res.long.vol_TIV')),val) 'ml'] ); + end + + % TIV (looks boring in adult but not in children) + li = li + 1; + leg = [leg,{'dTIV'}]; + valr = mean(diff(res.long.vol_TIV) ./ mean(res.long.vol_TIV)); + vala = mean(diff(res.long.vol_TIV)); + lstr{2}(li) = struct('name','\bf\color[rgb]{.5 .5 .5}TIV:' ,... + 'value', sprintf('%0.0fml' , res.long.vol_TIV(1,1)) , ... + 'value2', [val2f(valr,vala) 'ml'] ); + + % TSA + if isfield(res.long,'surf_TSA') + li = li + 1; + leg = [leg,{'TSA/1k'}]; + valr = mean(diff(res.long.surf_TSA) ./ mean(res.long.surf_TSA)); + vala = mean(diff(res.long.surf_TSA)); + lstr{2}(li) = struct('name','\bf\color[rgb]{.7 .2 .7}TSA:', ... + 'value' , sprintf('%0.0fsqmm',res.long.surf_TSA(1,1)), ... + 'value2', [val2f(valr,vala) 'sqmm']); + % marks2str(min(10.5,max(val * 100 + 0.5)),sprintf('%+0.3fmm',val))); + end + + % thickness + if isfield(res.long,'dist_thickness') + li = li + 1; + leg = [leg,{'dGMT*1k'}]; + val = mean(res.long.change_dist_thickness(2:end,1)); + lstr{2}(li) = struct('name','\bf\color[rgb]{.3 .0 .7}GMT:', ... + 'value' , sprintf('%0.2fmm',res.long.dist_thickness(1,1)), ... + 'value2', [val2f(val,val) 'mm']); + % marks2str(min(10.5,max(val * 100 + 0.5)),sprintf('%+0.3fmm',val))); + end + + mod = 0.003 * (isfield(res.long,'surf_TSA') + isfield(res.long,'dist_thickness')); + for i=1:size(lstr{2},2) % morphometric measurements + htext(3,i+1,1) = text(0.52,0.47-((0.055-mod)*(i+1)), lstr{2}(i).name , ... + 'FontName',fontname,'FontSize',fontsize,'color',fontcolor,'Interpreter','tex','Parent',ax); + htext(3,i+1,2) = text(0.64,0.47-((0.055-mod)*(i+1)), lstr{2}(i).value , 'HorizontalAlignment','right', ... + 'FontName',fontname,'FontSize',fontsize,'color',fontcolor,'Interpreter','tex','Parent',ax); + htext(3,i+1,3) = text(0.645,0.47-((0.055-mod)*(i+1)), lstr{2}(i).value2 ,'HorizontalAlignment','left', ... + 'FontName',fontname,'FontSize',fontsize,'color',fontcolor,'Interpreter','tex','Parent',ax); + end + + %% figure + tcmap = [0 0.3 0.7; 0 .6 0; 0.6 0 0; 0.5 0.5 0.5; 0.3 0.0 0.7; 0.7 0.2 0.7; 0.8 0.4 0.8]; + marker = {'<','^','>','o','d','s'}; + axi(2) = axes('Position',[0.75,0.745,0.22,0.095],'Parent',fg); cp(2) = gca; hold on; + set(axi(2),'Color',job.extopts.report.color,'YAxisLocation','right','XAxisLocation','bottom','box','on'); + % plot tissue values + for ti = [2 3 1] + pt = plot( axi(2), ( res.long.vol_abs_CGW(:,ti) - repmat( res.long.vol_abs_CGW(1,ti) , size(res.long.vol_abs_CGW,1) , 1) )'); + set(pt,'Color',tcmap(ti,:),'Marker',marker{ti},... + 'MarkerFaceColor',job.extopts.report.color,'MarkerSize',max(3,6 - numel(res.long.files)/10)); + end + % plot WMH + if any( res.long.vol_abs_WMH ) + pt = plot( axi(2), res.long.vol_abs_WMH - res.long.vol_abs_WMH(1)); + set(pt,'Color',tcmap(6,:),'LineStyle','-','Marker',marker{4}, ... + 'MarkerFaceColor',job.extopts.report.color,'MarkerSize',max(3,6 - numel(res.long.files)/10)); + end + % plot TIV + pt = plot( axi(2), res.long.vol_TIV - res.long.vol_TIV(1)); + set(pt,'Color',tcmap(4,:),'LineStyle','-','Marker',marker{4}, ... + 'MarkerFaceColor',job.extopts.report.color,'MarkerSize',max(3,6 - numel(res.long.files)/10)); + % plot TSA + if isfield(res.long,'surf_TSA') + pt = plot( axi(2), res.long.surf_TSA - res.long.surf_TSA(1)); + set(pt,'Color',tcmap(5,:),'LineStyle','-','Marker',marker{5}, ... + 'MarkerFaceColor',job.extopts.report.color,'MarkerSize',max(3,6 - numel(res.long.files)/10)); + end + % plot thickness + if isfield(res.long,'change_dist_thickness') + pt = plot( axi(2), res.long.change_dist_thickness(:,1) * 1000); + set(pt,'Color',tcmap(6,:),'LineStyle','-','Marker',marker{6}, ... + 'MarkerFaceColor',job.extopts.report.color,'MarkerSize',max(3,6 - numel(res.long.files)/10)); + end + %mlim = max( 20 , ceil( max( max( abs( [ diff( res.long.vol_abs_CGW(:,1:3) ,1 ); diff( res.long.vol_TIV ) ] ) )) / 20 ) * 20); + mlim = max( 20 , ceil( max( max( abs( [ ... + [res.long.vol_abs_CGW(:,1:3) - repmat( res.long.vol_abs_CGW(1,1:3) , size(res.long.vol_abs_CGW,1) , 1)], ... + [res.long.vol_TIV - res.long.vol_TIV(1)] ] ) )) * 1.2 / 20 ) * 20); + if isfield(res.long,'surf_TSA') + mlim = max( mlim , ceil( max( max( abs( res.long.surf_TSA - res.long.surf_TSA(1) ) )) * 1.2 / 20 ) * 20); + end + if isfield(res.long,'change_dist_thickness') + mlim = max( mlim , ceil( max( max( res.long.change_dist_thickness(:,1) * 1000 )) * 1.2 / 20 ) * 20); + end + ylim([-mlim mlim]); xlim([0.9 numel(res.long.files)+0.1]); + set(cp(2),'Fontsize',fontsize*0.8,'xtick',max(1,0:round(numel(res.long.files)/100)*10:numel(res.long.files)), ... + 'ytick',-mlim:round(mlim*2 / 4):mlim,'XAxisLocation','top'); + lh(2) = legend(leg,'Location','southoutside','Orientation','horizontal','box','off','FontSize',fontsize*0.8); grid on; + end + + + + else + for i=1:size(str{2},2) % qa-measurements + htext(2,i,1) = text(0.01,0.45-(0.055*i), str{2}(i).name ,'FontName',fontname,'FontSize',fontsize,'color',fontcolor,'Interpreter','tex','Parent',ax); + htext(2,i,2) = text(0.33,0.45-(0.055*i), str{2}(i).value ,'FontName',fontname,'FontSize',fontsize,'color',fontcolor,'Interpreter','tex','Parent',ax); + end + for i=1:size(str{3},2) % subject-measurements + htext(3,i,1) = text(0.51,0.45-(0.055*i), str{3}(i).name ,'FontName',fontname,'FontSize',fontsize,'color',fontcolor,'Interpreter','tex','Parent',ax); + htext(3,i,2) = text(0.70,0.45-(0.055*i), str{3}(i).value ,'FontName',fontname,'FontSize',fontsize,'color',fontcolor,'Interpreter','tex','Parent',ax); + end + end + + %% position values of the orthview/surface subfigures + pos = {[0.008 0.375 0.486 0.35]; [0.506 0.375 0.486 0.35]; ... + [0.008 0.010 0.486 0.35]; [0.506 0.010 0.486 0.35]}; + try spm_orthviews('Reset'); end + + % BB box is not optimal for all images + disptype = 'affine'; + warning('off','MATLAB:handle_graphics:exceptions:SceneNode') + if isfield(res,'Affine') + switch disptype + case 'affine' + dispmat = res.Affine; + warning('off') + try spm_orthviews('BB', res.bb*0.95 ); end + warning('on') + case 'rigid' + % this does not work so good... AC has a little offset ... + aff = spm_imatrix(res.Affine); scale = aff(7:9); + try spm_orthviews('BB', res.bb ./ mean(scale)); end + dispmat = R; + end + else + dispmat = eye(4); + end + + + + % ---------------------------------------------------------------------- + % Yo - original image in original space + % ---------------------------------------------------------------------- + % Using of SPM peak values didn't work in some cases (5-10%), so we have + % to load the image and estimate the WM intensity. + if dispvol + if isfield(res,'long') + try + %% create SPM volume plots + if isfield(res,'Vmnw') + Ymn = res.Vmnw.dat(:,:,:); + else + Ymn = res.Vmn.dat(:,:,:); + end + WMth = cat_stat_kmeans(Ymn(Ymn(:)>0)) * 3; + if isfield(res,'Vmnw') + hho = spm_orthviews('Image',res.Vmn,pos{1}); + T1txt = sprintf('GM tissue changes (FWHM %d mm)',res.long.smoothvol); + else + hho = spm_orthviews('Image',res.Vmn,pos{1}); + T1txt = 'High variant regions'; + end + spm_orthviews('Caption',hho,T1txt,'FontName',fontname,'FontSize',fontsize-1,'color',fontcolor,'FontWeight','Bold'); + spm_orthviews('window',hho,[0 single(WMth)*cmmax]); + % rang = (0:6)'; hoti = [rang,flip(rang,1)*0,flip(rang,1)]; hoti(1,:) = [0 0 0]; + %rang = (0:10)'; hoti = [rang,flip(rang,1),flip(rang,1)*0] .* repmat(min(max(rang),rang*2)/2,1,3) / max(rang) * 1; hoti(1,:) = [0 0 0]; + if isfield(res,'Vidiffw') + Vidiff = res.Vidiff; Vidiff.dat = Vidiff.dat * 100; + BCGWH = [cat_io_colormaps('hotinv',35);cat_io_colormaps('cold',35)]; BCGWH = BCGWH(6:65,:); + BCGWH = BCGWH.^1.1 * 2; % less transparent for high values + maxdiff = max(1,round(std(Vidiff.dat(:)))) * 10; + spm_orthviews('addtruecolourimage',hho,Vidiff, BCGWH,0.4,maxdiff,-maxdiff); + else + hoti = cat_io_colormaps('hot',10); + spm_orthviews('addtruecolourimage',hho,res.Vrdiff,hoti,0.4,0.5,0.4); + end + spm_orthviews('redraw'); + end + try + % SPM colorbar settings + warning('off','MATLAB:warn_r14_stucture_assignment'); + set(st.vols{1}.blobs{1}.cbar,'Position', [st.vols{1}.ax{3}.ax.Position(1) st.vols{1}.ax{1}.ax.Position(2) 0.01 0.13] ); + set(st.vols{1}.blobs{1}.cbar,'YAxisLocation', 'right','FontSize', fontsize-2,'FontName',fontname,'xcolor',fontcolor,'ycolor',fontcolor); + set(st.vols{1}.blobs{1}.cbar,'NextPlot','add'); % avoid replacing of labels + set(st.vols{1}.blobs{1}.cbar,'HitTest','off'); % avoid replacing of labels + % I create a copy of the colorbar that is not changed by SPM and + % remove the old one that is redrawn by SPM otherwise. + st.vols{1}.blobs1cbar = copyobj(st.vols{1}.blobs{1}.cbar,fg); + st.vols{1}.blobs{1} = rmfield(st.vols{1}.blobs{1},'cbar'); + end + try + %% create glassbrain images + glassbr = cat_plot_glassbrain( res.Vmn ); + glassbrain = cat_plot_glassbrain( res.Vidiff ); + glassbrainmax = max( maxdiff / 5, ceil(mean(abs(glassbrain{1}(:))) + 4*std(glassbrain{1}(:)) )); % ########## need dynamic adaptions in extrem cases + [glassbr,gbrange] = cat_plot_glassbrain( res.Vmn ); + + % position of each glassbrain view and its colormap + gbpos{1} = [ st.vols{1}.ax{3}.ax.Position(3)+0.015, st.vols{1}.ax{1}.ax.Position(2)+0.00 ,0.11, 0.09]; + gbpos{2} = [ st.vols{1}.ax{3}.ax.Position(3)+0.015, st.vols{1}.ax{1}.ax.Position(2)+0.09 ,0.11, 0.07]; + gbpos{3} = [ st.vols{1}.ax{3}.ax.Position(3)+0.115, st.vols{1}.ax{1}.ax.Position(2)+0.09 ,0.12, 0.07]; + gbpos{4} = [ st.vols{1}.ax{3}.ax.Position(3)+0.125, st.vols{1}.ax{1}.ax.Position(2)+0.00 ,0.005,0.09]; + + %% plot glassbrains + for gbi=1:4 + %% + if strcmpi(spm_check_version,'octave') + axes('Position',gbpos{gbi},'Parent',fg); + gbcc{gbi} = gca; + else + gbcc{gbi} = axes('Position',gbpos{gbi},'Parent',fg); + end + + if isfield(res,'Vidiffw') + gbo = image(gbcc{gbi},max( 60 + 60 + 1 , min( 60+60+surfcolors, (glassbrain{gbi} / glassbrainmax ) * ... + surfcolors/2 + 60 + 60 + surfcolors/2))); hold on; + else + gbo = image(gbcc{gbi},max( 60 + 60 + 1, min( 60+60+surfcolors/2-1, - (glassbrain{gbi} / glassbrainmax ) * ... + surfcolors/2 + 60 + 60 + surfcolors/2))); hold on; + end + if gbi<4 + set(gbo,'AlphaDataMapping','scaled','AlphaData',glassbr{gbi}>0.25 & get(gbo,'CData')>(60 + 60) ); + contour(gbcc{gbi},log(max(0,glassbr{gbi})),[0.5 0.5],'color',repmat(0.2,1,3)); + axis equal off; + else + set(gbcc{gbi},'XTickLabel','','XTick',[],'TickLength',[0.01 0],'YAxisLocation','right',... + 'YTick',max(1,0:surfcolors/2:surfcolors),'YTickLabel',{num2str([glassbrainmax; 0; -glassbrainmax] ,'%+0.0f')},... + 'FontSize', fontsize*0.8,'FontName',fontname,'xcolor',fontcolor,'ycolor',fontcolor); + end + + end + end + else + if ~isfield(VT0,'dat') + VT0 = spm_vol(VT0.fname); + end + try Yo = single(VT0.private.dat(:,:,:)); end + if isfield(res,'spmpp') + VT0x = res.image0(1); + else + VT0x = VT0; + end + + if exist('Yo','var') + + if isempty(Yp0) || any(size(Yo)~=size(Yp0)) + try Yo = single(VT.private.dat(:,:,:)); end + if isfield(res,'spmpp') + VT0x = spm_vol(res.image(1).fname); + else + if exist(VT.fname,'file') + VT0x = spm_vol(VT.fname); + else + VT0x = VT0; + VT0x.fname = spm_file(VT0x.fname,'prefix','x'); + end + end + end + + % remove outlier to make it orthviews easier + if isfield(res.ppe,'affreg') && isfield(res.ppe.affreg,'highBG') && res.ppe.affreg.highBG + Yo = cat_stat_histth(Yo,[0.999999 0.9999],struct('scale',[0 255])); + elseif isfield(job.extopts,'histth') + Yo = cat_stat_histth(Yo,job.extopts.histth,struct('scale',[0 255])); + else + Yo = cat_stat_histth(Yo,[0.999 0.999],struct('scale',[0 255])); + end + Yo = cat_vol_ctype(Yo); + VT0x.dt(1) = spm_type('uint8'); + VT0x.pinfo = repmat([1;0],1,size(Yo,3)); + VT0x.dat(:,:,:) = Yo; + + if isfield(job.extopts,'inv_weighting') && job.extopts.inv_weighting + Tth = [cat_stat_kmeans(Yo(Yp0(:)>0.5 & Yp0(:)<1.5),2,0),... + cat_stat_kmeans(Yo(Yp0(:)>1.5 & Yp0(:)<2.5),5,0),... + cat_stat_kmeans(Yo(Yp0(:)>2.5 & Yp0(:)<3.5),2,0)]; + WMth = min(max(Tth),median(Tth)*2); + wstr = 'PD/T2'; + else + WMth = cat_stat_kmeans(Yo(Yp0(:)>2.8 & Yp0(:)<3.2),2,0); clear Yo; + wstr = 'T1'; + end + T1txt = ['*.nii (Original ' wstr ')']; + %if ~debug, clear Yo; end + + VT0x.mat = dispmat * VT0x.mat; + try + hho = spm_orthviews('Image',VT0x,pos{1}); + spm_orthviews('Caption',hho,{T1txt},'FontName',fontname,'FontSize',fontsize-1,'color',fontcolor,'FontWeight','Bold'); + spm_orthviews('window',hho,[0 single(WMth)*cmmax]); + end + %% + + try % sometimes creation of axes fails for unknown reasons + if strcmpi(spm_check_version,'octave') + axes('Position',[st.vols{1}.ax{3}.ax.Position(1) st.vols{1}.ax{1}.ax.Position(2) 0.01 0.13],'Parent',fg); + cc{1} = gca; + else + cc{1} = axes('Position',[st.vols{1}.ax{3}.ax.Position(1) st.vols{1}.ax{1}.ax.Position(2) 0.01 0.13],'Parent',fg); + end + image((60:-1:1)','Parent',cc{1}); + + if isfield(job.extopts,'job.extopts.inv_weighting') && job.extopts.inv_weighting + set(cc{1},'YTick',ytick,'YTickLabel',fliplr(yticklabeli),'XTickLabel','','XTick',[],'TickLength',[0 0],... + 'FontName',fontname,'FontSize',fontsize-2,'FontWeight','normal','YAxisLocation','right','xcolor',fontcolor,'ycolor',fontcolor); + else + set(cc{1},'YTick',ytick,'YTickLabel',fliplr(yticklabelo),'XTickLabel','','XTick',[],'TickLength',[0 0],... + 'FontName',fontname,'FontSize',fontsize-2,'FontWeight','normal','YAxisLocation','right','xcolor',fontcolor,'ycolor',fontcolor); + end + catch + cc = {}; + end + else + cat_io_cprintf('warn','WARNING: Can''t display original file ""%s""!\n',VT.fname); + end + end + + + + + % ---------------------------------------------------------------------- + % Ym - normalized image in original space + % ---------------------------------------------------------------------- + p0id = 3 - ( job.extopts.report.type>1 || isfield(res,'spmpp') ); + if p0id > 2 + %% + Vm = res.image(1); + Vm.fname = ''; + Vm.dt = [spm_type('FLOAT32') spm_platform('bigend')]; + Vm.dat(:,:,:) = single(Ym); % intensity normalized + Vm.pinfo = repmat([1;0],1,size(Ym,3)); + Vm.mat = dispmat * Vm.mat; + try + hhm = spm_orthviews('Image',Vm,pos{2}); % intensity normalized is to long, in particular the image here is affine normalized + spm_orthviews('Caption',hhm,{['m*.nii (Normalized ' wstr ')']},'FontName',fontname,'FontSize',fontsize-1,'color',fontcolor,'FontWeight','Bold'); + spm_orthviews('window',hhm,[0 cmmax]); + + % new histogram + if strcmpi(spm_check_version,'octave') + axes('Position',[st.vols{2}.ax{3}.ax.Position(1) st.vols{2}.ax{1}.ax.Position(2) 0.01 0.13],'Parent',fg); + cc{2} = gca; + else + cc{2} = axes('Position',[st.vols{2}.ax{3}.ax.Position(1) st.vols{2}.ax{1}.ax.Position(2) 0.01 0.13],'Parent',fg); + end + image((60:-1:1)','Parent',cc{2}); + set(cc{2},'YTick',ytick,'YTickLabel',fliplr(yticklabel),'XTickLabel','','XTick',[],'TickLength',[0 0],... + 'FontName',fontname,'FontSize',fontsize-2,'color',fontcolor,'FontWeight','normal','YAxisLocation','right',... + 'xcolor',fontcolor,'ycolor',fontcolor); + end + end + + + + % ---------------------------------------------------------------------- + % Yp0 - segmentation in original space + % ---------------------------------------------------------------------- + % Use different kind of overlays to visualize the segmentation: + % 0 - old default + % (only brain tissue with the standard colormap) + % 1 - default + head + % (bad handling of PVE head values) + % + % 2 - color overlay for head and brain (DEFAULT) + % subversion with different background color (22-pink,222-green) + % (good for skull stripping but worst representation of brain tissues) + % 3 - color overlay for head and brain (inverse head) + % (good for skull stripping but worst representation of brain tissues) + % + % 4 - black background + gray head + cat brain colors + % (miss some details in CSF tissues) + % 5 - white background + gray head + cat brain colors (inverse head) + % (more similar to other backgrounds) + % + % Currently, no overlay and overlay 2 are the best supported options. + % Other options are only for internal test or development and can maybe + % removed in future (RD 20190110). + if isfield(res,'long') + %% + try + hhp0 = spm_orthviews('Image',res.Vmnw,pos{2}); + Vidiff = res.Vidiffw; Vidiff.dat = Vidiff.dat * 100; + BCGWH = [cat_io_colormaps('hotinv',35);cat_io_colormaps('cold',35)]; BCGWH = BCGWH(6:65,:); + BCGWH = BCGWH.^1.1 * 2; % less transparent for high values + maxdiff = max(1,round(std(Vidiff.dat(:)))) * 10; + spm_orthviews('window',hhp0,[0 single(WMth)*cmmax]); + spm_orthviews('addtruecolourimage',hhp0,Vidiff, BCGWH,0.4,maxdiff,-maxdiff); + spm_orthviews('redraw'); + if ~all(all(dispmat==eye(4))) + spm_orthviews('Reposition',[-25 0 0]); + end + if 1 + spm_orthviews('Caption',hhp0,sprintf('WM tissue changes (FWHM %d mm)',res.long.smoothvol),'FontName',fontname,'FontSize',fontsize-1,'color',fontcolor,'FontWeight','Bold'); + end + end + try + set(st.vols{p0id}.blobs{1}.cbar,'Position', [st.vols{p0id}.ax{3}.ax.Position(1) st.vols{p0id}.ax{1}.ax.Position(2) 0.01 0.13] ); + warning('off','MATLAB:warn_r14_stucture_assignment'); + set(st.vols{p0id}.blobs{1}.cbar,'YAxisLocation', 'right','FontSize', fontsize-2,'FontName',fontname,'xcolor',fontcolor,'ycolor',fontcolor); + set(st.vols{p0id}.blobs{1}.cbar,'NextPlot','add'); % avoid replacing of labels + set(st.vols{p0id}.blobs{1}.cbar,'HitTest','off'); % avoid replacing of labels + % I create a copy of the colorbar that is not changed by SPM and remove + % the old one that is redrawn by SPM otherwise. + st.vols{p0id}.blobs1cbar = copyobj(st.vols{p0id}.blobs{1}.cbar,fg); + st.vols{p0id}.blobs{1} = rmfield(st.vols{p0id}.blobs{1},'cbar'); + spm_orthviews('redraw'); + end + ov_mesh = 0; + try, spm_orthviews('AddContext',1); end + %% try + % create glassbrain images + if isfield(res,'Vidiffw') + glassbrain = cat_plot_glassbrain( res.Vidiffw ); + glassbrainmax = max( maxdiff / 5, ceil(mean(abs(glassbrain{1}(:))) + 4*std(glassbrain{1}(:))) ); % maxdiff / 5; % ########## need dynamic adaptions in extrem cases + else + Vrdiff = res.Vrdiff; + Vrdiff.dat(:,:,:) = max(0,abs(Vrdiff2.dat(:,:,:)) - 0.4); + glassbrain = cat_plot_glassbrain( Vrdiff ); + glassbrainmax = 1; + end + + % glassbrain positions + gbpos{1} = [ pos{2}(1) + st.vols{p0id}.ax{3}.ax.Position(3)+0.015, st.vols{p0id}.ax{1}.ax.Position(2)+0.00 ,0.11, 0.09]; + gbpos{2} = [ pos{2}(1) + st.vols{p0id}.ax{3}.ax.Position(3)+0.015, st.vols{p0id}.ax{1}.ax.Position(2)+0.09 ,0.11, 0.07]; + gbpos{3} = [ pos{2}(1) + st.vols{p0id}.ax{3}.ax.Position(3)+0.115, st.vols{p0id}.ax{1}.ax.Position(2)+0.09 ,0.12, 0.07]; + gbpos{4} = [ pos{2}(1) + st.vols{p0id}.ax{3}.ax.Position(3)+0.125, st.vols{p0id}.ax{1}.ax.Position(2)+0.00 ,0.005,0.09]; + + % plot + for gbi=1:4 + if strcmpi(spm_check_version,'octave') + axes('Position',gbpos{gbi},'Parent',fg); + gbcc{4+gbi} = gca; + else + gbcc{4+gbi} = axes('Position',gbpos{gbi},'Parent',fg); + end + gbp0 = image(gbcc{4+gbi},max(1 , min( 60+60+surfcolors, (glassbrain{gbi} / glassbrainmax) * ... + surfcolors/2 + 60 + 60 + surfcolors/2))); hold on; + caxis([-glassbrainmax glassbrainmax]); + if gbi<4 + set(gbp0,'AlphaDataMapping','scaled','AlphaData',glassbr{gbi}>0.25 & get(gbp0,'CData')>(60 + 60) ); + contour(gbcc{4+gbi},log(max(0,glassbr{gbi})),[0.5 0.5],'color',repmat(0.2,1,3)); + axis equal off; + else + set(gbcc{4+gbi},'XTickLabel','','XTick',[],'TickLength',[0.01 0],'YAxisLocation','right',... + 'YTick',1:surfcolors/2:surfcolors,'YTickLabel',{num2str([glassbrainmax; 0; -glassbrainmax] ,'%+0.0f')},... + 'FontSize', fontsize*0.8,'FontName',fontname,'xcolor',fontcolor,'ycolor',fontcolor); + end + end + spm_orthviews('redraw'); + %end + else + + VO = res.image(1); + VO.fname = ''; + VO.dt = [spm_type('FLOAT32') spm_platform('bigend')]; + + % create main brackground image + if isempty(Yl1) + job.extopts.report.useoverlay = 0; + elseif max(Yl1(:)) == 1 + job.extopts.report.useoverlay = 3; + end + switch job.extopts.report.useoverlay + case 0 % old default that shows only brain tissues + VO.dat(:,:,:) = single(Yp0/3); + case 3 % show brain and head tissues ??? + VO.dat(:,:,:) = single(Yp0/3) + ... + max(0,min(2, 2 - Ym )) .* (Yp0<0.5 & Ym<1/2) + ... + max(0,min(2, 2 - Ym )) .* (Yp0<0.5 & Ym>1/2); + otherwise % show brain and head tissues for refined atlas overlay + VO.dat(:,:,:) = single(Yp0/3) + ... + min(0.4, Ym/2 ) .* (Yp0<0.5 & Ym<1/2) + ... + min(2.0, 2 + Ym/2 ) .* (Yp0<0.5 & Ym>1/2); + end + + % affine normalization + VO.pinfo = repmat([1;0],1,size(Yp0,3)); + VO.mat = dispmat * VO.mat; + % remove existing subplot in case of debugging + if exist('hhp0','var') + try, spm_orthviews('Delete', hhp0); end %#ok + clear hhp0; + end + % create new figure + if isempty( VO.fname ) && isfield(VO,'dat') && ~isempty( VO.dat ) + try + hhp0 = spm_orthviews('Image',VO,pos{p0id}); + spm_orthviews('window',hhp0,[0 1.3]); + end + end + + % CAT atlas labeling + LAB = job.extopts.LAB; + NS = @(Ys,s) Ys==s | Ys==s+1; + if job.extopts.report.useoverlay>1 && ~strcmpi(spm_check_version,'octave') + try spm_orthviews('window',hhp0,[0 2]); end + V2 = VO; + switch job.extopts.report.useoverlay + case 1 % classic red mask + V2.dat(:,:,:) = min(59,min(1,Yp0/3) + 60*(smooth3((abs(Yp0 - Ym*3)>0.6).*cat_vol_morph(abs(Yp0 - Ym*3)>0.8,'d',2).*(Yp0>0.5))>0.5)); + try spm_orthviews('addtruecolourimage',hhp0,V2, [0.05 0.4 1; gray(58); 0.8 0.2 0.2],0.5,3,0); end + case {2,22,222} % red mask high contrast (default) + + % basic head/brain tissue colormapping + switch job.extopts.report.useoverlay + case 22 % pink head + BCGWH = pink(15); fx = 4; + case 222 % green head + BCGWH = [0 0.1 0.05; 0.05 0.2 0.1; 0.1 0.3 0.2; 0.15 0.4 0.3; summer(11)]; fx = 3; + otherwise % blue head + BCGWH = [0 0 0; 0.03 0.12 0.25; 0.05 0.18 0.40; cat_io_colormaps('blue',12)];fx = 3; + end + % background correction + Yhd = Yp0==0; + BGth = cat_stat_kmeans( Ym(Yhd(:)) , 5); Ym(Yhd) = (Ym(Yhd) - BGth(1)) / ( 1 - BGth(1) ); clear Ybg; + % create image + V2.dat(:,:,:) = min(0.49,Ym/fx).*(Yp0<0.5) + (Yp0/3+0.5).*(Yp0>0.5); + + % meninges/blood vessels: GM > CSF + if ~job.extopts.inv_weighting + Ychange = 60*(smooth3( ... + ((Ym*3 - Yp0)>0.4) .* (Yp0<1.25) .* ~NS(Yl1,LAB.VT) .* ... + cat_vol_morph(abs(Ym*3 - Yp0)>0.5,'d',2) .* ... + (Yp0>0.5))>0.5); + else + Ychange = 60*(smooth3( ... + ((Yp0 - Ym*3)>0.4) .* (Yp0<1.25) .* ~NS(Yl1,LAB.VT) .* ... + cat_vol_morph(abs(Yp0 - Ym*3)>0.5,'d',2) .* ... + (Yp0>0.5))>0.5); + end + V2.dat(Ychange & Ym<1.33/3) = 58/30; + V2.dat(Ychange & Ym>1.33/3) = 59/30; + V2.dat(Ychange & Ym>1.66/3) = 60/30; + clear Ychange; + + % WMHs + if job.extopts.WMHC > 1 || ( isfield(qa,'subjectmeasures') && ( ... + (qa.subjectmeasures.vol_rel_WMH>0.01 || qa.subjectmeasures.vol_rel_WMH/qa.subjectmeasures.vol_rel_WMH>0.02))) + V2.dat(NS(Yl1,LAB.HI)) = 52/30; + end + + % ventricles + if job.extopts.expertgui > 1 + V2.dat(NS(Yl1,LAB.VT) & Yp0<1.5) = 55/30; + V2.dat(NS(Yl1,LAB.VT) & Yp0>1.5) = 56/30; + V2.dat(NS(Yl1,LAB.VT) & Yp0>2.5) = 57/30; + vent3 = repmat([0.3 0.3 0.5],3,1); + vent3 = max(0,min(1,vent3 .* repmat([1;2;3],1,3))); + else + vent3 = repmat([0.8 0.0 0.0],3,1); + end + + % colormap of WMHs + g29 = gray(39); g29(1:7,:) = []; g29(end-3:end,:) = []; + if job.extopts.WMHC > 0 && job.extopts.WMHC < 2 + if qa.subjectmeasures.vol_rel_WMH>0.01 || ... + qa.subjectmeasures.vol_rel_WMH/qa.subjectmeasures.vol_rel_WMH>0.02 + if job.extopts.WMHC == 2 + wmhc9 = cat_io_colormaps('magenta',9); + else + wmhc9 = cat_io_colormaps('magentadk',9); + end + else + wmhc9 = gray(20); wmhc9(1:10,:) = []; wmhc9(end,:) = []; + wmhc9 = flipud(wmhc9); + end + else + wmhc9 = cat_io_colormaps('orange',9); + end + + % colormap of blood vessels + if ~job.extopts.inv_weighting + bv3 = [0.4 0.2 0.2; 0.6 0.2 0.2; 1 0 0]; + else + bv3 = [0.4 0.4 0.4; 0.5 0.5 0.5; 0.6 0.6 0.6]; + end + + % display also the detected blood vessels + V2.dat(NS(Yl1,LAB.BV)) = 60/30; + + % mapping + try spm_orthviews('addtruecolourimage',hhp0,V2, [BCGWH; g29; wmhc9; vent3; bv3],1,2,0); end + + case 3 % red mask + Ychange = 60*(smooth3((abs(Yp0 - Ym*3)>0.6).*cat_vol_morph(abs(Yp0 - Ym*3)>0.8,'d',2) .* (Yp0>0.5))>0.5); + BCGWH = pink(15); BCGWH = min(1,BCGWH + [zeros(13,3);repmat((1:2)'/2,1,3)]); + V2.dat(:,:,:) = min(0.5,Ym/3).*(Yp0<0.5) + (Yp0/4*1.4+0.5).*(Yp0>0.5) + Ychange; + try spm_orthviews('addtruecolourimage',hhp0,V2, [flipud(BCGWH);gray(44);1 0 0],1,2,0); end + case 4 % gray - color (black background) + BCGWH = cat_io_colormaps('BCGWHwov',60); BCGWH(46:end,:) = []; + V2.dat(:,:,:) = min(0.5,Ym/3).*(Yp0<0.5) + (Yp0/4*1.4+0.5).*(Yp0>0.5); + try spm_orthviews('addtruecolourimage',hhp0,V2, [gray(16);BCGWH],1,2,0); end + case 5 % gray - color (white background) + BCGWH = cat_io_colormaps('BCGWHnov',60); BCGWH(46:end,:) = []; + V2.dat(:,:,:) = min(0.5,Ym/3).*(Yp0<0.5) + (Yp0/4*1.4+0.5).*(Yp0>0.5); + try spm_orthviews('addtruecolourimage',hhp0,V2, [flipud(gray(16));BCGWH],1,2,0); end + end + % the colormap deactivation is a bit slow but I know no way to improve that + if job.extopts.report.useoverlay > 1 && ~isempty(st.vols{p0id}) + set([st.vols{p0id}.blobs{1}.cbar, get(st.vols{p0id}.blobs{1}.cbar,'children')],'Visible','off'); + end + if isfield(res,'long'), set([st.vols{1}.blobs{1}.cbar,get(st.vols{1}.blobs{1}.cbar,'children')],'Visible','off'); end + try spm_orthviews('redraw'); end + else + try spm_orthviews('window',hhp0,[0 cmmax]); end + end + + % Yp0 legend + try + spm_orthviews('window',hhp0,[0 cmmax]); + if all(all(dispmat==eye(4))) + % set new BB based on the segmentation + V2 = VO; + V2.dat(:,:,:) = Yp0; + bb = spm_get_bbox( V2 , .5); + spm_orthviews('BB',bb*1.2); + else + spm_orthviews('Reposition',[-25 0 0]); + end + if ~isfield(res,'long') + spm_orthviews('Caption',hhp0,'p0*.nii (Segmentation)','FontName',fontname,'FontSize',fontsize-1,'color',fontcolor,'FontWeight','Bold'); + end + end + try + if job.extopts.report.useoverlay > 1 + %% make SPM colorbar invisible (cannot delete it because SPM orthviews needs it later) + set(st.vols{p0id}.blobs{1}.cbar,'Position', [st.vols{p0id}.ax{3}.ax.Position(1) st.vols{p0id}.ax{1}.ax.Position(2) 0.01 0.13] ); + warning('off','MATLAB:warn_r14_stucture_assignment'); + set(st.vols{p0id}.blobs{1}.cbar,'YTick', ytickp0/30,'XTick', [],'YTickLabel', yticklabelp0,'XTickLabel', {},'TickLength',[0 0]); + set(st.vols{p0id}.blobs{1}.cbar,'YAxisLocation', 'right','FontSize', fontsize-2,'FontName',fontname,'xcolor',fontcolor,'ycolor',fontcolor); + set(st.vols{p0id}.blobs{1}.cbar,'NextPlot','add'); % avoid replacing of labels + set(st.vols{p0id}.blobs{1}.cbar,'HitTest','off'); % avoid replacing of labels + else + if strcmpi(spm_check_version,'octave') + axes('Position',[st.vols{p0id}.ax{3}.ax.Position(1) st.vols{p0id}.ax{1}.ax.Position(2) 0.01 0.13],'Parent',fg); + cc{p0id} = gca; + else + cc{p0id} = axes('Position',[st.vols{p0id}.ax{3}.ax.Position(1) st.vols{p0id}.ax{1}.ax.Position(2) 0.01 0.13],'Parent',fg); + end + image((60:-1:1)','Parent',cc{p0id}); + set(cc{p0id},'YTick',ytick,'YTickLabel',fliplr(yticklabel),'XTickLabel','','XTick',[],'TickLength',[0 0],... + 'FontName',fontname,'FontSize',fontsize-2,'color',fontcolor,'YAxisLocation','right','xcolor',fontcolor,'ycolor',fontcolor); + end + % if isfield(res,'long') + % set(st.vols{1}.blobs{1}.cbar,'Position', [st.vols{1}.ax{3}.ax.Position(1) st.vols{1}.ax{1}.ax.Position(2) 0.01 0.13] ); + % set(st.vols{1}.blobs{1}.cbar,'YAxisLocation', 'right','FontSize', fontsize-2,'FontName',fontname,'xcolor',fontcolor,'ycolor',fontcolor); + % set(st.vols{1}.blobs{1}.cbar,'NextPlot','add'); % avoid replacing of labels + % set(st.vols{1}.blobs{1}.cbar,'HitTest','off'); % avoid replacing of labels + % end + end + %if ~debug, clear Yp0; end + + + %{ + if job.extopts.expertgui>1 + %% + ppe_seg{2} = {'CSF', 'GM', 'WM', 'TIV'; + sprintf('%0.0f',res.ppe.SPMvols0(1)), sprintf('%0.0f',res.ppe.SPMvols0(2)), sprintf('%0.0f',res.ppe.SPMvols0(3)), sprintf('%0.0f',sum(res.ppe.SPMvols0(1:3)),'%0.0f'); + sprintf('%0.0f',res.ppe.SPMvols1(1)), sprintf('%0.0f',res.ppe.SPMvols1(2)), sprintf('%0.0f',res.ppe.SPMvols1(3)), sprintf('%0.0f',sum(res.ppe.SPMvols1(1:3)),'%0.0f'); + '','','',''; + 'DT','DT''','ll2','ll1'; + res.ppe.reg.dt, res.ppe.reg.rmsgdt, res.ppe.reg.ll(end,2), res.ppe.reg.ll(end,1); + }; + for idi = 2 + ppeax{idi} = axes('Position',[st.vols{p0id}.ax{3}.ax.Position(1)+0.03 st.vols{p0id}.ax{1}.ax.Position(2) 0.2 0.1],'Parent',fg); axis off; + for i = 1:size(ppe_seg{idi},1) + for j = 1:size(ppe_seg{idi}{i},2) + % lg{idi+1} = text( j*0.25, 1 - i*0.1 , ppe_seg{idi}{i,j}, 'Parent', ppeax{idi}); %, ... + % 'FontName', fontname, 'Fontsize', fontsize-2, 'Color', fontcolor); + end + end + end + %,0,stxt,'Parent',ppepos{idi},'FontName',fontname,'Fontsize',fontsize-2,'color',fontcolor,'Interpreter','none','Parent',ax); + end + %} + + + % ---------------------------------------------------------------------- + % TPM overlay with brain/head and head/background surfaces + % ---------------------------------------------------------------------- + % RD20200727: res.Affine shows the final affine mapping but more relevant + % for error handling is the intial affine registration before + % the US that is now saved as res.Affine0. + % However mapping both is to much if they are to similar, so + % you have so quantify and evaluate the difference to add the + % second map when it is relevant ... + % You may also create a warning (in cat_main) and just look + % for the warning (or res.FIELD created there). + + % just remove old things in debugging mode + if 1 %debug + warning('off','MATLAB:subscripting:noSubscriptsSpecified') + for idi = 1:numel(st.vols) + if isfield( st.vols{idi}, 'mesh'), st.vols{idi} = rmfield( st.vols{idi} ,'mesh'); end + end + end + + % test mesh display + idi = 1; + try + Phull = cat_surf_create_TPM_hull_surface(res.tpm, job.extopts.species , ... + min( job.extopts.gcutstr , ~isfield(res,'spmpp') && ~(isfield(res,'spmpp') && res.spmpp) >0 ) ); + catch + Phull = ''; + end + try, spm_orthviews('AddContext',idi); end % need the context menu for mesh handling + try + warning('off','MATLAB:subscripting:noSubscriptsSpecified'); + if ~isempty(Phull) + spm_ov_mesh('display',idi,{Phull}); + ov_mesh = 1; + else + ov_mesh = 0; + end + catch + fprintf('Please update to a newer version of spm12 for using this contour overlay\n'); + ov_mesh = 0; + end + end + + % test mesh display + if ~isfield(res,'long') + idi = 1; + try + try + Phull = cat_surf_create_TPM_hull_surface(res.tpm, job.extopts.species , ... + max(0,min( job.extopts.gcutstr , ~isfield(res,'spmpp') && ~(isfield(res,'spmpp') && res.spmpp) )>0 )); + catch + Phull = ''; + end + end + try, spm_orthviews('AddContext',idi); end % need the context menu for mesh handling + try + warning('off','MATLAB:subscripting:noSubscriptsSpecified'); + if ~isempty(Phull) + spm_ov_mesh('display',idi,{Phull}); + ov_mesh = 1 & ~isfield(res,'long'); + else + ov_mesh = 0; + end + catch + fprintf('Please update to a newer version of spm12 for using this contour overlay\n'); + ov_mesh = 0; + end + end + + % display mesh + if ov_mesh + + % load mesh + warning('off','MATLAB:subscripting:noSubscriptsSpecified'); + try, spm_ov_mesh('display', idi, Phull); end + + % apply registration (AC transformation) for all hull objects + V = (dispmat * inv(res.Affine) * ([st.vols{idi}.mesh.meshes(1).vertices,... + ones(size(st.vols{idi}.mesh.meshes(1).vertices,1),1)])' )'; V(:,4) = [];%#ok + V = subsasgn(st.vols{idi}.mesh.meshes(1), struct('subs','vertices','type','.'),single(V)); + st.vols{idi}.mesh.meshes = V; clear V; + + %% change line style + hM = findobj(st.vols{idi}.ax{1}.cm,'Label','Mesh'); + UD = get(hM,'UserData'); + UD.width = 0.75; + if strcmp(cm,'gray') + UD.style = repmat({'r--'},1,numel(Phull)); + elseif any( job.extopts.report.color < 0.4 ) + UD.style = repmat({'w--'},1,numel(Phull)); + else + UD.style = repmat({'b--'},1,numel(Phull)); + end + set(hM,'UserData',UD); clear hM + warning('off','MATLAB:subscripting:noSubscriptsSpecified'); + spm_ov_mesh('redraw',idi); + try spm_orthviews('redraw',idi); end + + %% TPM overlay legend + try + ccl{1} = axes('Position',[st.vols{1}.ax{3}.ax.Position(1) st.vols{1}.ax{3}.ax.Position(2)-0.04 0.017 0.02],'Parent',fg); + cclp = plot(ccl{1},([0 0.4;0.6 1])',[0 0; 0 0],UD.style{1}(1:2)); + lg{1} = text(1.2,0,'Brain/skull TPM overlay','Parent',ccl{1},'FontName',fontname,'Fontsize',fontsize-2,'color',fontcolor); + set(cclp,'LineWidth',0.75); axis(ccl{1},'off') + end + end + end + + + %% ---------------------------------------------------------------------- + % central / inner-outer surface overlay + % ---------------------------------------------------------------------- + if exist('Psurf','var') && ~isempty(Psurf) && ov_mesh && ~isfield(res,'long') + % ... cleanup this part of code when finished ... + + Psurf2 = Psurf; + + % create temporary boundary surfaces for the report + if ~exist(Psurf2(2).Pwhite,'file') && ~exist(Psurf2(2).Ppial,'file') + tempsurf = 1; + + surfs = {'Pwhite','Ppial'}; sx = [-0.5 0.5]; + for surfi = 1:2 % boundary surfaces + for si = 1:2 % brain sides + cmd = sprintf('CAT_Central2Pial ""%s"" ""%s"" ""%s"" %0.1f', ... + Psurf2(si).Pcentral, Psurf2(si).Pthick,Psurf2(si).(surfs{surfi}),sx(surfi)); + cat_system(cmd,0); + end + end + else + tempsurf = 0; + end + + % phite/pial surface in segmentation view number 2 or 3 + if exist(Psurf2(1).Pwhite,'file') && exist(Psurf2(1).Ppial,'file'), ids = 1:p0id; else, ids = []; end % job.extopts.expertgui==2 && + for ix=1:numel(Psurf2) + Psurf2(end+1).Pcentral = Psurf2(ix).Pwhite; + Psurf2(end+1).Pcentral = Psurf2(ix).Ppial; + end + Psurf2(1:numel(Psurf)) = []; + + for idi = 1:p0id % render in each volume + try spm_orthviews('AddContext',idi); end % need the context menu for mesh handling + + if any(idi==ids), nPsurf = numel(Psurf2); else, nPsurf = numel(Psurf); end + for ix=1:nPsurf + % load mesh + if ov_mesh + warning('off','MATLAB:subscripting:noSubscriptsSpecified'); + if any(idi==ids) + spm_ov_mesh('display',idi,Psurf2(ix).Pcentral); + else + spm_ov_mesh('display',idi,Psurf(ix).Pcentral); + end + else + continue + end + + % apply affine scaling for gifti objects + V = (dispmat * ([st.vols{idi}.mesh.meshes(end).vertices,... + ones(size(st.vols{idi}.mesh.meshes(end).vertices,1),1)])' )'; + V(:,4) = []; + M0 = st.vols{idi}.mesh.meshes(1:end-1); + M1 = st.vols{idi}.mesh.meshes(end); + M1 = subsasgn(M1,struct('subs','vertices','type','.'),single(V)); + st.vols{idi}.mesh.meshes = [M0,M1]; + end + + % change line style + hM = findobj(st.vols{idi}.ax{1}.cm,'Label','Mesh'); + UD = get(hM,'UserData'); + UD.width = [repmat(0.5,1,numel(UD.width) - nPsurf) repmat(0.5,1,nPsurf)]; + UD.style = [repmat({'b--'},1,numel(UD.width) - nPsurf) repmat({'k-'},1,nPsurf)]; + set(hM,'UserData',UD); clear UD hM + warning('off','MATLAB:subscripting:noSubscriptsSpecified'); + if ov_mesh, try, spm_ov_mesh('redraw',idi); end; end + + % layer legend + try + if any(idi==ids), stxt = 'white/pial'; else, stxt = 'central surface'; end + ccl{idi+1} = axes('Position',[st.vols{idi}.ax{3}.ax.Position(1) st.vols{idi}.ax{3}.ax.Position(2)-0.05+0.005*(idi~=1) 0.017 0.02],'Parent',fg); + plot(ccl{idi+1},[0 1],[0 0],'k-'); axis(ccl{idi+1},'off') + lg{idi+1} = text(1.2,0,stxt,'Parent',ccl{idi+1},'FontName',fontname,'Fontsize',fontsize-2,'color',fontcolor); + end + + end + + % cleanup + if tempsurf + for xi=1:numel(Psurf) + delete(Psurf(xi).Ppial); + delete(Psurf(xi).Pwhite); + end + end + + % remove menu + %if ~debug, spm_orthviews('RemoveContext',idi); end + end + + + + %% ---------------------------------------------------------------------- + % 3D surfaces + % ---------------------------------------------------------------------- + if job.extopts.print>1 + if exist('Psurf','var') && ~isempty(Psurf) + if 1 %~strcmpi(spm_check_version,'octave') && opengl('info') + boxwidth = 0.1; + if job.extopts.report.type <= 1 + %% classic top view + % -------------------------------------------------------------- + % + large clear view of one big brain + % - missing information of interesting lower and median regions + sidehist = 1; %job.extopts.expertgui>1; + try + id1 = find( cat_io_contains({Psurf(:).Pcentral},'lh.') ,1, 'first'); + spm_figure('Focus','Graphics'); + % this is strange but a 3:4 box property results in a larger brain scaling + hCS = subplot('Position',[0.52 0.037*(~sidehist) 0.42 0.31+0.02*sidehist],'visible','off'); + if ~strcmpi(spm_check_version,'octave'), renderer = get(fg,'Renderer'); else, renderer = 'volume'; end + + % only add contours if OpenGL is found (to prevent crashing on clusters) + if strcmpi(renderer,'opengl') + hSD = cat_surf_display(struct('data',Psurf(id1).Pthick,'readsurf',0,'expert',2,... + 'multisurf',1,'view','s','menu',0,... + 'parent',hCS,'verb',0,'caxis',[0 6],'imgprint',struct('do',0))); + + + % rigid reorientation + isotropic scaling + imat = spm_imatrix(res.Affine); Rigid = spm_matrix([imat(1:6) ones(1,3)*mean(imat(7:9)) 0 0 0]); clear imat; + for ppi = 1:numel(hSD{1}.patch) + V = (Rigid * ([hSD{1}.patch(ppi).Vertices, ones(size(hSD{1}.patch(ppi).Vertices,1),1)])' )'; + V(:,4) = []; hSD{1}.patch(ppi).Vertices = V; + end + + % remove old colormap and add own + if strcmpi(spm_check_version,'octave'), colormap(cmap); + else, colormap(fg,cmap); end + set(hSD{1}.colourbar,'visible','off'); + else + %% + for i = 1:numel(Psurf) + if i == 1 + id1 = find( cat_io_contains({Psurf(:).Pcentral},'lh.') ,1, 'first'); + CS = gifti( Psurf(id1).Pcentral ); + T = cat_io_FreeSurfer('read_surf_data',Psurf(id1).Pthick ); + CS.cdata = T; + else + id1 = find( cat_io_contains({Psurf(:).Pcentral},'rh.') ,1, 'first'); + S = gifti( Psurf(id1).Pcentral ); + T = cat_io_FreeSurfer('read_surf_data',Psurf(id1).Pthick ); + CS.faces = [ CS.faces; S.faces + size(CS.vertices,1) ]; + CS.vertices = [ CS.vertices; S.vertices ]; + CS.cdata = [ CS.cdata; T ]; + clear S; + end + end + CS = export(CS,'patch'); + hSD{i} = cat_surf_renderv(CS,[],struct('rot','t','interp',1,'h',hCS)); + end + + if ~sidehist + if strcmpi(spm_check_version,'octave') + axes('Position',[0.58 0.022 0.3 0.007],'Parent',fg); image((121:1:120+surfcolors),'Parent',cc{4}); + cc{4} = gca; + else + cc{4} = axes('Position',[0.58 0.022 0.3 0.007],'Parent',fg); image((121:1:120+surfcolors),'Parent',cc{4}); + end + set(cc{4},'XTick',1:(surfcolors-1)/6:surfcolors,'xcolor',fontcolor,'ycolor',fontcolor,'XTickLabel',... + {'0','1','2','3','4','5',' 6 mm'},... + 'YTickLabel','','YTick',[],'TickLength',[0 0],'FontName',fontname,'FontSize',fontsize-2,'FontWeight','normal'); + else + %% histogram + + % colormap + if strcmpi(spm_check_version,'octave') + axes('Position',[0.965 0.03 0.01 0.28],'Parent',fg); image(flip(121:1:120+surfcolors)','Parent',cc{4}); + cc{4} = gca; + else + cc{4} = axes('Position',[0.965 0.03 0.01 0.28],'Parent',fg); image(flipud(121:1:120+surfcolors)','Parent',cc{4}); + end + set(cc{4},'YAxisLocation','right','YTick',1:(surfcolors-1)/6:surfcolors,'YTickLabel',{'6','5','4','3','2','1','0'},... + 'XTickLabel','','XTick',[],'FontName',fontname,'FontSize',fontsize-2,'xcolor',fontcolor,'ycolor',fontcolor,'FontWeight','normal'); + + %% histogram line + if strcmpi(spm_check_version,'octave') + axes('Position',[0.936 0.03 0.03 0.28],'Parent',fg,'Visible', 'off','tag', 'cat_surf_results_hist', ... + 'xcolor',fontcolor,'ycolor',fontcolor); + cc{5} = gca; + else + cc{5} = axes('Position',[0.936 0.03 0.03 0.28],'Parent',fg,'Visible', 'off','tag', 'cat_surf_results_hist', ... + 'xcolor',fontcolor,'ycolor',fontcolor); + end + side = hSD{1}.cdata; + [d,h] = hist( side(~isinf(side(:)) & ~isnan(side(:)) & side(:)<6 & side(:)>0) , hrange); + d = d./numel(side); + d = d./max(d); + + % print histogram + hold(cc{5},'on'); + for bi = 1:numel(d) + b(bi) = barh(cc{5},h(bi),-d(bi),boxwidth); + set(b(bi),'Facecolor',cmap3(bi,:),'Edgecolor',fontcolor); + end + ylim([0,6]); xlim([-1 0]); + end + catch + cat_io_cprintf('warn','WARNING: Can''t display surface!\n',VT.fname); + end + elseif job.extopts.report.type >= 2 + spm_figure('Focus','Graphics'); + id1 = find( cat_io_contains({Psurf(:).Pcentral},'lh.') ,1, 'first'); + id2 = find( cat_io_contains({Psurf(:).Pcentral},'rh.') ,1, 'first'); + % this is strange but a 3:4 box property result in a larger brain scaling + hCS{1} = subplot('Position',[0.34 0.07 0.32 0.27],'Parent',fg,'visible','off'); PCS{1} = Psurf(id1).Pthick; sview{1} = 't'; + hCS{2} = subplot('Position',[0.02 0.18 0.30 0.17],'Parent',fg,'visible','off'); PCS{2} = Psurf(id1).Pthick; sview{2} = 'l'; + hCS{3} = subplot('Position',[0.68 0.18 0.30 0.17],'Parent',fg,'visible','off'); PCS{3} = Psurf(id2).Pthick; sview{3} = 'r'; + hCS{4} = subplot('Position',[0.02 0.01 0.30 0.17],'Parent',fg,'visible','off'); PCS{4} = Psurf(id1).Pthick; sview{4} = 'r'; + hCS{5} = subplot('Position',[0.68 0.01 0.30 0.17],'Parent',fg,'visible','off'); PCS{5} = Psurf(id2).Pthick; sview{5} = 'l'; + if ~strcmpi(spm_check_version,'octave'), renderer = get(fg,'Renderer'); else, renderer = 'volume'; end + + % only add contours if OpenGL is found (to prevent crashing on clusters) + if isfield(res,'long') + [~,~,ee] = spm_fileparts(Psurf(id1).Pthick); + if strcmp(ee,'.gii') + S = gifti(Psurf(id1).Pthick); + cdata = S.cdata; + else + cdata = cat_io_FreeSurfer('read_surf_data',Psurf(id1).Pthick); + end + maxdiff = max(.02, 4 * ceil(std(cdata(:))*8)/8); + srange = [-maxdiff maxdiff]; + boxwidth = diff(srange)/40 / 2; % 0.05; + else + srange = [0 6]; + boxwidth = diff(srange)/30 / 2; % 0.1; + end + %% hrange = srange(1) + boxwidth/2:boxwidth:srange(2); + if job.output.surface > 10, addcb = 1; else, addcb = 0; end + if strcmpi(renderer,'opengl') + try + i=1; hSD{i} = cat_surf_display(struct('data',PCS{i},'readsurf',0,'expert',2,... + 'multisurf',1 + 2*addcb,'view',sview{i},'menu',0,'parent',hCS{i},'verb',0,'caxis',srange,'imgprint',struct('do',0))); + end + + for i = 2:numel(hCS) + try + hSD{i} = cat_surf_display(struct('data',PCS{i},'readsurf',0,'expert',2,... + 'multisurf',0 + 3*addcb,'view',sview{i},'menu',0,'parent',hCS{i},'verb',0,'caxis',srange,'imgprint',struct('do',0))); + end + end + + % rigid reorientation + isotropic scaling + if isfield(res,'Affine') + imat = spm_imatrix(res.Affine); Rigid = spm_matrix([imat(1:6) ones(1,3)*mean(imat(7:9)) 0 0 0]); clear imat; + else + Rigid = eye(4); + end + if exist('hSD','var') + for i = 1:numel(hSD) + for ppi = 1:numel(hSD{i}{1}.patch) + try + V = (Rigid * ([hSD{i}{1}.patch(ppi).Vertices, ones(size(hSD{i}{1}.patch(ppi).Vertices,1),1)])' )'; + V(:,4) = []; hSD{i}{1}.patch(ppi).Vertices = V; + end + end + end + for i = 1:numel(hSD), colormap(fg,cmap); set(hSD{i}{1}.colourbar,'visible','off'); end + end + else + try + if 1 + % just the first draft + for i = 1:numel(Psurf) + if i == 1 + id1 = find( cat_io_contains({Psurf(:).Pcentral},'lh.') ,1, 'first'); + CS = gifti( Psurf(id1).Pcentral ); + T = cat_io_FreeSurfer('read_surf_data',Psurf(id1).Pthick ); + CS.cdata = T; + CSl = CS; + else + id1 = find( cat_io_contains({Psurf(:).Pcentral},'rh.') ,1, 'first'); + S = gifti( Psurf(id1).Pcentral ); + T = cat_io_FreeSurfer('read_surf_data',Psurf(id1).Pthick ); + CS.faces = [ CS.faces; S.faces + size(CS.vertices,1) ]; + CS.vertices = [ CS.vertices; S.vertices ]; + CS.cdata = [ CS.cdata; T ]; + CSr = S; CSr.cdata = T; + clear S; + end + end + CS = export(CS,'patch'); + CSl = export(CSl,'patch'); + CSr = export(CSr,'patch'); + else + % ###### this is not working yet ####### + % the idea is to refine the surface to quaranty a minimum + % resolution but the thickness data mapping is not working + % yet ... + side = {'lh.','rh.'}; + for si = 1:numel(side) + id1 = find( cat_io_contains({Psurf(:).Pcentral},side{si}) ,1, 'first'); + % quaranty 1 mm mesh resolution + Pcentral = sprintf('%s.gii',tempname); + CSo = gifti(Psurf(id1).Pcentral); + cmd = sprintf('CAT_RefineMesh ""%s"" ""%s"" %0.2f 0',Psurf(id1).Pcentral,Pcentral,1); + cat_system(cmd,0); + CSx = gifti(Pcentral); + CSx = export(CSx,'patch'); + delete(Pcentral); + T = cat_io_FreeSurfer('read_surf_data',Psurf(id1).Pthick ); + CSx.cdata = cat_surf_fun('cdatamapping',CSx,CSo,T,struct('scale',1)); + if si==1, CSl = CSx; else, CSr = CSx; end + end + CS.faces = [ CSl.faces; CSr.faces + size(CSl.vertices,1) ]; + CS.vertices = [ CSl.vertices; CSr.vertices ]; + CS.cdata = [ CSl.cdata; CSr.cdata ]; + end + + %% + imat = spm_imatrix(res.Affine); Rigid = spm_matrix([imat(1:6) ones(1,3)*mean(imat(7:9)) 0 0 0]); clear imat; + V = (Rigid * ([CS.vertices, ones(size(CS.vertices ,1),1)])' )'; V(:,4) = []; CS.vertices = V; + V = (Rigid * ([CSl.vertices, ones(size(CSl.vertices,1),1)])' )'; V(:,4) = []; CSl.vertices = V; + V = (Rigid * ([CSr.vertices, ones(size(CSr.vertices,1),1)])' )'; V(:,4) = []; CSr.vertices = V; + + if strcmpi(spm_check_version,'octave'), colormap(cmap); + else, colormap(fg,cmap); end + + % The interpolation value controls quality and speed, the normal report + + % surface-rendering takes about 70s, whereas this renderer takes 60 to 160s. + % round(interp) controls the main mesh interpolation level with equal + % subdivision of one face by 4 faces, but the value also sets the sampling + % size of the rendering images and a value of 1.4 means 1.4 more pixel in + % each dimension. Values of 1.0 - 1.4 are quite fast (but not fine enough + % for standard zoom-in) and 2.4 (120s) suits better. + interp = 2.45; + + hSD{1}{1} = cat_surf_renderv(CS ,[],struct('view',sview{1},'mat',spm_imatrix(res.Affine),'h',hCS{1},'interp',interp)); + cat_surf_renderv(CSl,[],struct('view',sview{2},'mat',spm_imatrix(res.Affine),'h',hCS{2},'interp',interp*0.9)); + cat_surf_renderv(CSr,[],struct('view',sview{3},'mat',spm_imatrix(res.Affine),'h',hCS{3},'interp',interp*0.9)); + cat_surf_renderv(CSl,[],struct('view',sview{4},'mat',spm_imatrix(res.Affine),'h',hCS{4},'interp',interp*0.9)); + cat_surf_renderv(CSr,[],struct('view',sview{5},'mat',spm_imatrix(res.Affine),'h',hCS{5},'interp',interp*0.9)); + + catch + cat_io_cprintf('err','Error in non OpenGL surface rendering.\n'); + end + end + + + %% To do: filter thickness values on the surface ... + + % sometimes hSD is not defined here because of mysterious errors on windows systems + if ~exist('hSD','var'), return; end + + if ~isfield(hSD{1}{1},'cdata'), return; end + + % colormap + side = hSD{1}{1}.cdata; + + % histogram + if strcmpi(spm_check_version,'octave') + axes('Position',[0.36 0.0245 0.28 0.030],'Parent',fg,... + 'visible','off', 'tag','cat_surf_results_hist', ... + 'xcolor',fontcolor,'ycolor',fontcolor); + cc{5} = gca; + else + cc{5} = axes('Position',[0.36 0.0245 0.28 0.030],'Parent',fg,... + 'visible','off', 'tag','cat_surf_results_hist', ... + 'xcolor',fontcolor,'ycolor',fontcolor); + end + % boxes + if isfield(res,'long') + [d,h] = hist( side(~isinf(side(:)) & ~isnan(side(:)) ), ...& side(:)srange(1)) , ... + srange(1)+boxwidth/2:boxwidth:srange(2)-boxwidth/2); + else + [d,h] = hist( side(~isinf(side(:)) & ~isnan(side(:)) & side(:)srange(1)) , ... + srange(1)+boxwidth/2:boxwidth:srange(2)-boxwidth/2); + end + dmax = max(d) * 1.2; % 15% extra for the line plot (use thickness phantom to set this value) + % histogram line + [dl,hl] = hist( side(~isinf(side(:)) & ~isnan(side(:)) & side(:)srange(1)) , ... + srange(1)+boxwidth/2:boxwidth/10:srange(2)-boxwidth/2); %hl = hl + 0.02/2; + try dl = smooth(dl,2); catch, dl = (dl + [0 dl(1:end-1)] + [dl(2:end) 0])/3; end % smooth requires Curve Fitting Toolbox + dl = dl / (dmax/10); % 10 times smaller boxes + % boxplot values + q0 = median(side); q1 = median(side(sideq0)); + d = d / dmax; + if 0%isfield(res,'long') % make outlier vissible in the histogram + hx = srange(1)+boxwidth/2:boxwidth:srange(2)-boxwidth/2; + hlx = srange(1)+boxwidth/10:boxwidth/10:srange(2)-boxwidth/2; + d = min(1, d .* max(0,2.^((abs(hx * 20).^1)))); + dl = min(1, dl .* max(0,2.^((abs(hlx * 20).^1)))); + end + + + %% print histogram + hold(cc{5},'on'); + for bi = 1:numel(d) + outlier0 = h(bi) < q0 - 3*(q0-q1) & d(bi)>0.01 & d(bi)>0.9*d(min(numel(d),bi+1)); + outlier1 = h(bi) > q0 + 3*(q2-q0) & d(bi)>0.01 & d(bi)>0.9*d(max(1,bi-1)); + b(bi) = bar(cc{5},h(bi),d(bi),boxwidth); + if outlier0 || outlier1, ecol = [1 0 0]; else, ecol = fontcolor; end % mark outlier + set(b(bi),'Facecolor',cmap3(min(surfcolors,round(bi * surfcolors/numel(d) )),:),'Edgecolor',ecol) + end + try + line(cc{5},hl,dl,'color',mean([fontcolor;[0.9 0.3 0.3]])); + outlier0 = hl < q0 - 3*(q0-q1) & d(bi)/max(d)>0.01; + outlier1 = hl > q0 + 3*(q2-q0) & d(bi)/max(d)>0.01; + if ~isempty(outlier0), line(cc{5},hl( outlier0 ),dl( outlier0 ),'color',[1 0 0 ]); end + if isfield(res,'long') + if ~isempty(outlier1), line(cc{5},hl( outlier1 ),dl( outlier1 ),'color',[0 0 1 ]); end + else + if ~isempty(outlier1), line(cc{5},hl( outlier1 ),dl( outlier1 ),'color',[1 0 0 ]); end + end + xlim(srange); ylim([0 1]); + end + + + %% print colormap and boxplot on top of the bar/line histogramm to avoid that the line run into it + cc{4} = axes('Position',[0.36 0.018 0.28 0.007],'Parent',fg); xlim([1 surfcolors]); + image((121:1:120+surfcolors),'Parent',cc{4}); hold on; + + try + if isfield(res,'long') + if srange(2)>2.00, cfontcolor = [0.8 0 0]; + elseif srange(2)>1.00, cfontcolor = [0.4 0 0]; + else , cfontcolor = fontcolor; + end + set(cc{4},'XTick',1:(surfcolors-1)/4:surfcolors,'xcolor',cfontcolor,'ycolor',fontcolor,'XTickLabel',... + {sprintf('%.2f',srange(1)),sprintf('%.2f',srange(1)/2),'0',... + sprintf('%+.2f',srange(2)/2),... + sprintf(' %+.2f %s changes (smoothed %d times)',... + srange(2),res.long.measure,round(res.long.smoothsurf))},... + 'YTickLabel','','YTick',[],'TickLength',[0.01 0],'FontName',fontname,'FontSize',fontsize-2,'FontWeight','normal'); + else + set(cc{4},'XTick',1:(surfcolors-1)/6:surfcolors,'xcolor',fontcolor,'ycolor',fontcolor,'XTickLabel',... + {'0','1','2','3','4','5',[repmat(' ',1,10) '6 mm']},... + 'YTickLabel','','YTick',[],'TickLength',[0.01 0],'FontName',fontname,'FontSize',fontsize-2,'FontWeight','normal'); + end + + % boxplot + % sometimes it's crashing on windows systems for no reason... + try + if isfield(res,'long') + %% + line(cc{4},surfcolors/2 + surfcolors/2 * [(q0 - 1.5*(q0-q1)) q1 ], [ 1 1] , 'Color',[0 0 0],'LineWidth',0.75); + line(cc{4},surfcolors/2 + surfcolors/2 * [q2 (q0 + 1.5*(q2-q0)) ], [ 1 1] , 'Color',[0 0 0],'LineWidth',0.75); + fill(cc{4},surfcolors/2 + surfcolors/2 * [q1 q2 q2 q1], [ 0.8 0.8 1.2 1.2],[1 1 1],'LineWidth',0.5,'FaceAlpha',0.7); + line(cc{4},surfcolors/2 + surfcolors/2 * repmat(mean(side),1,2), [ 0.6 1.4 ] , 'Color',[0 0 0],'LineWidth',0.75); + line(cc{4},surfcolors/2 + surfcolors/2 * repmat(q0,1,2), [ 0.6 1.4 ] , 'Color',[1 0 0],'LineWidth',1.5); + else + line(cc{4},(surfcolors-1)/6 * [(q0 - 1.5*(q0-q1)) q1 ], [ 1 1] , 'Color',[0 0 0],'LineWidth',0.75); + line(cc{4},(surfcolors-1)/6 * [q2 (q0 + 1.5*(q2-q0)) ], [ 1 1] , 'Color',[0 0 0],'LineWidth',0.75); + fill(cc{4},(surfcolors-1)/6 * [q1 q2 q2 q1], [ 0.8 0.8 1.2 1.2],[1 1 1],'LineWidth',0.5,'FaceAlpha',0.7); + line(cc{4},(surfcolors-1)/6 * repmat(mean(side),1,2), [ 0.6 1.4 ] , 'Color',[0 0 0],'LineWidth',0.75); + line(cc{4},(surfcolors-1)/6 * repmat(q0,1,2), [ 0.6 1.4 ] , 'Color',[1 0 0],'LineWidth',1.5); + end + end + hold off; + end + else + cat_io_cprintf('warn','WARNING: Surface rending without openGL is deactivated to prevent zoombie processes on servers!\n',VT.fname); +% render warning on figure + end + end + end + + +if 1 + %% ---------------------------------------------------------------------- + % print subject report file as standard PDF/PNG/... file + % ---------------------------------------------------------------------- + % vars in: fg, htext, cc, st + % vars out: - + + job.imgprint.type = 'pdf'; + job.imgprint.dpi = 300; + job.imgprint.fdpi = @(x) ['-r' num2str(x)]; + job.imgprint.ftype = @(x) ['-d' num2str(x)]; + + [pth1,pth2] = spm_fileparts(pth); + if strcmp(pth2,mrifolder), pth = pth1; end % remove mri nameing + + pth_reportfolder = fullfile(pth,reportfolder); + [stat, val] = fileattrib(pth_reportfolder); + if stat, pth_reportfolder = val.Name; end + if ~exist(pth_reportfolder,'dir'), mkdir(pth_reportfolder); end + if isfield(res,'long') + longstr = 'long'; % catLONGreport + nam = strrep(nam,'mean_',''); % remove the mean + else + longstr = ''; + end + if ~isfield(job,'imgprint') || ~isfield(job.imgprint,'fname') + job.imgprint.fname = fullfile(pth_reportfolder,['cat' longstr 'report_' nam '.' job.imgprint.type]); + end + if ~isfield(job,'imgprint') || ~isfield(job.imgprint,'fnamej') + job.imgprint.fnamej = fullfile(pth_reportfolder,['cat' longstr 'reportj_' nam '.jpg']); + end + + % save old settings of the SPM figure + fgold.PaperPositionMode = get(fg,'PaperPositionMode'); + fgold.PaperPosition = get(fg,'PaperPosition'); + fgold.resize = get(fg,'resize'); + + % it is necessary to change some figure properties especially the fontsizes + set(fg,'PaperPositionMode','auto','resize','on','PaperPosition',[0 0 1 1]); + try, set(hd,'FontName',fontname,'Fontsize',get(hd,'Fontsize')/spm_figure_scale*0.8); end + try, spm_orthviews('Caption',hho,{T1txt},'FontName',fontname,'FontSize',(fontsize-1)/spm_figure_scale*0.8,'FontWeight','Bold'); end + try, spm_orthviews('Caption',hhm,{['m*.nii (Normalized ' wstr ')']},... + 'FontName',fontname,'FontSize',(fontsize-1)/spm_figure_scale*0.8,'FontWeight','Bold'); end + if ~isfield(res,'long') + try, spm_orthviews('Caption',hhp0,'p0*.nii (Segmentation)','FontName',fontname,'FontSize',(fontsize-1)/spm_figure_scale*0.8,'FontWeight','Bold'); end + else + try, spm_orthviews('Caption',hhp0,sprintf('WM tissue changes (FWHM %d mm)',res.long.smoothvol),'FontName',fontname,'FontSize',(fontsize-1)/spm_figure_scale*0.8,'FontWeight','Bold'); end + end + if exist('axi','var') + for hti = 1:numel(axi), try, set(axi(hti),'FontName',fontname,'Fontsize',get(axi(hti),'Fontsize')/spm_figure_scale*0.8); end; end + end + if exist('cp','var') + for hti = 1:numel(cp), try, set(cp(hti),'FontName',fontname,'Fontsize',get(cp(hti),'Fontsize')/spm_figure_scale*0.8); end; end + end + if exist('lh','var') + for hti = 1:numel(lh), try, set(lh(hti),'FontName',fontname,'Fontsize',get(lh(hti),'Fontsize')/spm_figure_scale*0.8); end; end + end + if exist('gbcc','var') + for hti = [4,8], try, set(gbcc{hti},'FontName',fontname,'Fontsize',get(gbcc{hti},'Fontsize')/spm_figure_scale*0.8); end; end + end + for hti = 1:numel(htext), try, set(htext(hti),'FontName',fontname,'Fontsize',get(htext(hti),'Fontsize')/spm_figure_scale*0.8); end; end + if exist('cc','var') % sometimes cc does not exist of anything fails before + for hti = 1:numel(cc), try, set(cc{hti} , 'FontName', fontname, 'Fontsize', get(cc{hti} , 'Fontsize')/spm_figure_scale*0.8); end; end + end + if exist('ccl','var') % sometimes lg does not exist of anything fails before + for hti = 1:numel(ccl), try, set(ccl{hti} ,'FontName',fontname,'Fontsize',get(ccl{hti} ,'Fontsize')/spm_figure_scale*0.8); end; end + end + if exist('lg','var') % sometimes lg does not exist of anything fails before + for hti = 1:numel(lg), try, set(lg{hti} ,'FontName',fontname,'Fontsize',get(lg{hti} ,'Fontsize')/spm_figure_scale*0.8); end; end + end + if job.extopts.report.useoverlay > 1 + try + set(st.vols{p0id}.blobs{1}.cbar,'FontName',fontname,'Fontsize',get(st.vols{p0id}.blobs{1}.cbar,'Fontsize')/spm_figure_scale*0.8); + end + end + warning('off','MATLAB:hg:patch:RGBColorDataNotSupported'); + + % the PDF is is an image because openGL is used but -painters would not look good for surfaces ... + try % does not work in headless mode without java + if ~isempty(job.imgprint.fname) + print(fg, job.imgprint.ftype(job.imgprint.type), job.imgprint.fdpi(job.imgprint.dpi), job.imgprint.fname); + end + if ~isempty(job.imgprint.fnamej) + print(fg, job.imgprint.ftype('jpeg'), job.imgprint.fdpi(job.imgprint.dpi), job.imgprint.fnamej); + end + end + + %% reset font settings + try, set(hd,'FontName',fontname,'Fontsize',get(hd,'Fontsize')*spm_figure_scale/0.8); end + try, spm_orthviews('Caption',hho,{T1txt},'FontName',fontname,'FontSize',fontsize-1,'FontWeight','Bold'); end + if ~isfield(res,'long') + try, spm_orthviews('Caption',hhm,{['m*.nii (Normalized ' wstr ')']},'FontName',fontname,'FontSize',fontsize-1,'FontWeight','Bold'); end + try, spm_orthviews('Caption',hhp0,'p0*.nii (Segmentation)','FontName',fontname,'FontSize',fontsize-1,'FontWeight','Bold'); end + else + try, spm_orthviews('Caption',hhp0,sprintf('WM tissue changes (FWHM %d mm)',res.long.smoothvol),'FontName',fontname,'FontSize',fontsize-1,'FontWeight','Bold'); end + end + for hti = 1:numel(htext), try, set(htext(hti),'FontName',fontname,'Fontsize',get(htext(hti),'Fontsize')*spm_figure_scale/0.8); end; end + if exist('axi','var') + for hti = 1:numel(axi ), try, set(axi(hti),'FontName',fontname,'Fontsize',get(axi(hti),'Fontsize')*spm_figure_scale/0.8); end; end + end + if exist('cp','var') + for hti = 1:numel(cp ), try, set(cp(hti),'FontName',fontname,'Fontsize',get(cp(hti),'Fontsize')*spm_figure_scale/0.8); end; end + end + if exist('lh','var') + for hti = 1:numel(lh), try, set(lh(hti),'FontName',fontname,'Fontsize',get(lh(hti),'Fontsize')*spm_figure_scale/0.8); end; end + end + if exist('gbcc','var') + for hti = [4,8], try, set(gbcc{hti},'FontName',fontname,'Fontsize',get(gbcc{hti},'Fontsize')*spm_figure_scale/0.8); end; end + end + try, for hti = 1:numel(cc), try, set(cc{hti} ,'FontName',fontname,'Fontsize',get(cc{hti} ,'Fontsize')*spm_figure_scale/0.8); end; end; end + try, for hti = 1:numel(ccl), set(ccl{hti} ,'FontName',fontname,'Fontsize',get(ccl{hti} ,'Fontsize')*spm_figure_scale/0.8); end; end + if exist('lg','var') % sometimes lg does not exist of anything fails before + for hti = 1:numel(lg), try, set(lg{hti} ,'FontName',fontname,'Fontsize',get(lg{hti} ,'Fontsize')*spm_figure_scale/0.8); end; end + end + if job.extopts.report.useoverlay > 1 && ~isfield(res,'long') + try + set(st.vols{p0id}.blobs{1}.cbar,'FontName',fontname,'Fontsize',get(st.vols{p0id}.blobs{1}.cbar,'Fontsize')*spm_figure_scale/0.8); + % I create a copy of the colorbar that is not changed by SPM and remove + % the old one that is redrawn by SPM otherwise. + st.vols{p0id}.blobs1cbar = copyobj(st.vols{p0id}.blobs{1}.cbar,fg); + st.vols{p0id}.blobs{1} = rmfield(st.vols{p0id}.blobs{1},'cbar'); + end + end + + % restore old SPM figure settings + set(fg,'PaperPositionMode',fgold.PaperPositionMode,'resize',fgold.resize,'PaperPosition',fgold.PaperPosition); + clear fgold + + % be verbose ... but just one row to work in the retrospective batch mode + try + if ~isempty(job.imgprint.fname) + fprintf(' %s\n',job.imgprint.fname); %Print ''Graphics'' figure to: \n + end + if isempty(job.imgprint.fname) && ~isempty(job.imgprint.fnamej) + fprintf(' %s\n',job.imgprint.fname); % Print ''Graphics'' figure to: \n + end + end +end + + + + % ---------------------------------------------------------------------- + % reset colormap to the simple SPM like gray60 colormap + % ---------------------------------------------------------------------- + % vars in: WMth, hho, hhm, hhp0, job, showTPMsurf, Psurf, st + % vars out: - + + % gray colormap + cmap(1:60,:) = gray(60); cmap(61:120,:) = flipud(pink(60)); + cmap(121:120+surfcolors,:) = cmap3; + if strcmpi(spm_check_version,'octave') + colormap(cmap); clear cmap; + else + colormap(fg,cmap); clear cmap; + end + + % update intensity scaling for gray colormap + if ~isfield(res,'long') + WMfactor0 = single(WMth) * 8/6; + WMfactor1 = 8/6; + + % update the colormap in the SPM orthview windows + warning('off','MATLAB:subscripting:noSubscriptsSpecified'); + if exist('hho' ,'var'), try, spm_orthviews('window',hho ,[0 WMfactor0]); set(cc{1},'YTick',ytick * 4/3 - 20); end; end + if exist('hhm' ,'var'), try, spm_orthviews('window',hhm ,[0 WMfactor1]); set(cc{2},'YTick',ytick * 4/3 - 20); end; end + if exist('hhp0','var'), try, spm_orthviews('window',hhp0,[0 WMfactor1]); end; end + clear WMfactor0 WMfactor1; + end + + %% change line style of TPM surf (from b-- to r--) + if ov_mesh && exist('Psurf','var') && ~isempty(Psurf) && exist('st','var') && ... + isfield(st,'vols') && iscell(st.vols) && isfield(st.vols{1},'ax') && ... + iscell(st.vols{1}.ax) && isfield(st.vols{1}.ax{1} ,'cm') + hM = findobj(st.vols{1}.ax{1}.cm,'Label','Mesh'); + UD = get(hM,'UserData'); + UD.style{1} = 'r--'; + set(hM,'UserData',UD); + set(cclp,'Color', [1 0 0]); % overlay legend + try,spm_ov_mesh('redraw',1);end + end +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_conf_stools.m",".m","94670","2346","function stools = cat_conf_stools(expert) +%_______________________________________________________________________ +% wrapper for calling CAT surface utilities +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +%#ok<*NOCOM> + +% try to estimate number of processor cores +try + numcores = cat_get_defaults('extopts.nproc'); + % because of poor memory management use only half of the cores for windows + if ispc + numcores = round(numcores/2); + end + numcores = max(numcores,1); +catch + numcores = 0; +end + +% force running in the foreground if only one processor was found or for compiled version +% or for Octave +if numcores == 1 || isdeployed || strcmpi(spm_check_version,'octave'), numcores = 0; end + +if ~exist('expert','var') + expert = 0; % switch to de/activate further GUI options +end + +% parallelize +% ____________________________________________________________________ +nproc = cfg_entry; +nproc.tag = 'nproc'; +nproc.name = 'Split job into separate processes'; +nproc.strtype = 'w'; +nproc.val = {numcores}; +nproc.num = [1 1]; +nproc.help = { + 'In order to use multi-threading the CAT12 segmentation job with multiple subjects can be split into separate processes that run in the background. You can even close Matlab, which will not affect the processes that will run in the background without GUI. If you do not want to run processes in the background then set this value to 0.' + '' + 'Please note that no additional modules in the batch can be run except CAT12 segmentation. Any dependencies will be broken for subsequent modules.' + }; + + +% do not process, if result already exists +% ____________________________________________________________________ +lazy = cfg_menu; +lazy.tag = 'lazy'; +lazy.name = 'Lazy processing'; +lazy.labels = {'Yes','No'}; +lazy.values = {1,0}; +lazy.val = {0}; +lazy.help = { + 'Do not process data if the result already exists. ' +}; + + +% merge hemispheres +% ____________________________________________________________________ +merge_hemi = cfg_menu; +merge_hemi.tag = 'merge_hemi'; +merge_hemi.name = 'Merge hemispheres'; +merge_hemi.labels = { + 'No - save resampled data for each hemisphere',... + 'Yes - merge hemispheres' +}; +merge_hemi.values = {0,1}; +merge_hemi.val = {1}; +merge_hemi.hidden = expert<1; +merge_hemi.help = { + 'Meshes for left and right hemisphere can be merged to one single mesh. This simplifies the analysis because only one analysis has to be made for both hemispheres and this is the recommended approach.' + 'However, this also means that data size is doubled for one single analysis which might be too memory demanding for studies with several hundreds or even more files. If your model cannot be estimated due to memory issues you should not merge the resampled data.' +}; + + +% default mesh +% ____________________________________________________________________ +mesh32k = cfg_menu; +mesh32k.hidden = expert<1; +mesh32k.tag = 'mesh32k'; +mesh32k.name = 'Resample Size'; +mesh32k.labels = { + '32k mesh (HCP)',... + '164k mesh (Freesurfer)' +}; +mesh32k.values = {1,0}; +mesh32k.val = {1}; +mesh32k.help = { + 'Resampling can be done either to a higher resolution 164k mesh that is compatible to Freesurfer data or to a lower resolution 32k mesh (average vertex spacing of ~2 mm) that is compatible to the Human Connectome Project (HCP).' + 'The HCP mesh has the advantage of being processed and handled much faster and with less memory demands. Another advantage is that left and right hemispheres are aligned to optionally allow a direct comparison between hemispheres.' +}; + + + +%% import GUIs +% ------------------------------------------------------------------------ +[surfresamp,surfresamp_fs] = cat_surf_resamp_GUI(expert,nproc,merge_hemi,mesh32k,lazy); +[vol2surf,vol2tempsurf] = cat_surf_vol2surf_GUI(expert,merge_hemi,mesh32k); +[surfcalc,surfcalcsub] = cat_surf_calc_GUI(expert); +renderresults = cat_surf_results_GUI(expert); +surfextract = cat_surf_parameters_GUI(expert,nproc,lazy); +flipsides = cat_surf_flipsides_GUI(expert); +surf2roi = cat_surf_surf2roi_GUI(expert,nproc); +roi2surf = cat_roi_roi2surf_GUI(expert); +surfstat = cat_surf_stat_GUI; +surfcon = cat_surf_spm_cfg_con; +surfres = cat_surf_spm_cfg_results; +vx2surf = cat_surf_vx2surf_GUI(expert,nproc,lazy); + + +%% Toolset +% --------------------------------------------------------------------- +stools = cfg_choice; +stools.name = 'Surface Tools'; +stools.tag = 'stools'; +stools.values = { ... + surfextract, ... .cat.stools + surfresamp, ... .cat.stools + surfresamp_fs,... .cat.stools + vol2surf, ... .cat.stools + vol2tempsurf, ... .cat.stools + vx2surf, ... .cat.stools (expert) + surfcalc, ... .cat.stools + surfcalcsub, ... .cat.stools + surf2roi, ... .cat.rtools? + roi2surf, ... .cat.rtools? (developer) + flipsides, ... .cat.stools (developer) + surfstat ... + surfcon ... + surfres ... + renderresults, ... .cat.disp/plot/write? +}; + + +%========================================================================== +% subfunctions of batch GUIs +%========================================================================== +function res = cat_surf_spm_cfg_results +% Surface based version of the SPM result function (tiny changes). +res = spm_cfg_results; +res.prog = @cat_spm_results_ui; +res.name = ['Surface ' res.name]; + +function con = cat_surf_spm_cfg_con +% Surface based version of the SPM contrast tools that only change the +% dependency settings updated here in vout_stats. +con = spm_cfg_con; +con.name = ['Surface ' con.name]; +con.vout = @vout_stats; % gifti rather than nifti output + +function dep = vout_stats(varargin) +% Surface based version of the SPM contrast tools that only change the +% dependency settings updated here. +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 = 'All Con Surfaces'; +dep(2).src_output = substruct('.','con'); +dep(2).tgt_spec = cfg_findspec({{'filter','gifti','strtype','e'}}); +dep(3) = cfg_dep; +dep(3).sname = 'All Stats Surfaces'; +dep(3).src_output = substruct('.','spm'); +dep(3).tgt_spec = cfg_findspec({{'filter','gifti','strtype','e'}}); + +function surfstat = cat_surf_stat_GUI +% Surface based version of the SPM result GUI. +% This function include multipe updates to (i) deactivate buttons that +% are not working for surfaces and (ii) new control functions to avoid +% problems with the object rotation function (that also rotate the result +% tables and not only the surfaces), but also (iii) some visual updates +% with predefined settings for result visualization. + +spmmat = cfg_files; +spmmat.tag = 'spmmat'; +spmmat.name = 'Select SPM.mat files'; +spmmat.filter = {'mat'}; +spmmat.ufilter = '^SPM\.mat$'; +spmmat.num = [1 inf]; +spmmat.help = {'Select the SPM.mat file that contains the design specification.'}; + +surfstat = cfg_exbranch; +surfstat.tag = 'SPM'; +surfstat.name = 'Estimate Surface Model'; +surfstat.val = {spmmat}; +surfstat.prog = @cat_stat_spm; +surfstat.vout = @vout_cat_stat_spm; +surfstat.help = { + ''}; + +function vx2surf = cat_surf_vx2surf_GUI(expert,nproc,lazy) +% This is a voxel-based projection of values to the surface. + + + % surf + surf = cfg_files; + surf.tag = 'surf'; + surf.name = 'Left central surfaces'; + surf.filter = 'gifti'; + surf.ufilter = '^lh.central'; + surf.num = [1 Inf]; + surf.help = {'Select central surfaces.'}; + + % name of the measure + name = cfg_entry; + name.tag = 'name'; + name.name = 'Name'; + name.strtype = 's'; + name.num = [1 Inf]; + name.val = {'vxvol'}; + name.help = { + 'Name of the measure that is used in the surface file name, e.g., ""roi_volume"" will result in ""lh.roi_volume.S01"" for a subject S01. ' + 'The surface data has to be smoothed and normalized in the next step. ' + '' + }; + + iname = name; + iname.val = {'vxint'}; + + dname = name; + dname.val = {'vxdist'}; + + % distance weighting function [high low] + dweighting = cfg_entry; + dweighting.tag = 'dweighting'; + dweighting.name = 'Weighting / limitation [Low High High Low]'; + dweighting.strtype = 'r'; + dweighting.num = [1 4]; + dweighting.val = {[0 0 0 10]}; + dweighting.help = { + ['Distance based weighting outside and inside the surface from high to low. ' ... + 'I.e. [2 0 5 10] means full weighting at 0 mm distance and zero weighting at ' ... + '2 mm distance outside of the surface and full weighting from 0 to 5 mm inside ' ... + 'the surface with linear decrease from 1 to 0 between 5 and 10 mm inside of the surface. '] + '' + }; + + norm = cfg_menu; + norm.tag = 'norm'; + norm.name = 'Final normalization'; + norm.val = {''}; + norm.help = { + ['For many measures a log10 normalization is useful to obtain normal distributed data ' ... + 'but also to handle exponential dependencies to brain size. Moreover, it is important ' ... + 'to use TIV as general confound in the analysis. '] + ''}; + if expert>1 + norm.labels = {'none','log10a','log10b','log10c','log10d','log10e'}; + norm.values = {'','log10a','log10b','log10c','log10d','log10e'}; + norm.help = [ norm.help ; { + ' log10a = @(val) log10(val * 9/10 + 1)' + ' log10b = @(val) log10(val * 99/100 + 1)/2' + ' log10c = @(val) log10(val * 999/1000 + 1)/3' + ' log10d = @(val) log10(val * 9999/1000 + 1)/4' + ' log10e = @(val) log10(val * 99999/1000 + 1)/5' + }]; + else + norm.labels = {'none','log10','log10p'}; + norm.values = {'','log10a','log10p'}; + norm.help = [ norm.help ; { + ' log10 = @(val) log10(val * 9/10 + 1)' + ' log10p = @(val) log10(val * 999/1000 + 1)/3' + }]; + end + + + % average + average = cfg_menu; + average.tag = 'vweighting'; + average.name = 'Average function'; + if expert + average.labels = {'mean','median','standard deviation','variance','minimum','maximum'}; + average.values = {'mean','median','std','var','min','max'}; + else + average.labels = {'mean','standard deviation','variance'}; + average.values = {'mean','std','var'}; + end + average.val = {'mean'}; + average.help = {'Average function for the projection of multiple voxels.' ''}; + + % msk + rimage = cfg_files; + rimage.tag = 'rimage'; + rimage.name = 'Region/tissue (partial) volume mask'; + rimage.help = {'Select images that define the tissue/region that should be projected to the surface. ' ''}; + rimage.filter = 'image'; + rimage.ufilter = '.*'; + rimage.num = [1 Inf]; + + rimage2 = rimage; + rimage2.tag = 'rimage2'; + rimage2.name = 'Second region mask for relativation'; + rimage2.help = {'i.e. WMH vs. WMV.'}; + rimage2.val = {''}; + rimage2.num = [0 Inf]; + + % int + iimage = cfg_files; + iimage.tag = 'iimage'; + iimage.name = 'Intensity map'; + iimage.help = {'Select images those values are projected within the masked region. ' ''}; + iimage.filter = 'image'; + iimage.ufilter = '.*'; + iimage.num = [1 Inf]; + + if 0 + % complex version + sdist = average; + sdist.tag = 'sdist'; + sdist.name = 'Surface distance (average function)'; + + odist = cfg_menu; + odist.tag = 'odist'; + odist.name = 'Object distance (type)'; + odist.labels = {'nearest','nearest with erosion'}; + odist.values = {'near','nearerode'}; + odist.val = {'near'}; + odist.help = { + ['The nearest option estimates a distance map from the object structure. ' ... + 'It maps the inverse value (1/d) because the distance objects are expected to have lower effect in general. ' ... + 'The second option estimates multiple distance maps by stepwise erode all structures. '] + }; + + dmetric = cfg_choice; + dmetric.tag = 'dmetric'; + dmetric.name = 'Distance metric'; + dmetric.values = {sdist,odist}; + dmetric.val = {odist}; + dmetric.help = { + ['Average distance from the surface to the object or from the object to the surface. ' ... + 'The surface distance estimate a voxel-based distance map and then average the values. ' ... + 'The object based distance on the other side estimates (multiple) voxel-based distance maps to read out the value at the surface position. ' ... + 'Hence, the closes structure (e.g. small lesions) normaly defines the distance but if erosion is used also larger far distance structures can taken into account. '] + ''}; + else + % simple version + dmetric = cfg_menu; + dmetric.tag = 'odist'; + dmetric.name = 'Distance metric'; + dmetric.labels = {'Mean surface distance (Push)','Minimum object distance (Pull)'}; + dmetric.values = {'sdist','odist'}; + dmetric.val = {'odist'}; + dmetric.help = { + ['Average distance from the surface to the object or from the object to the surface. ' ... + 'The surface distance is measured for each voxel and average for the closest vertex. ' ... + 'The object based distance on the other side estimates (multiple) voxel-based distance maps to read out the value at the surface position. ' ... + 'Hence, the closes structure (e.g. small lesions) normaly defines the distance but if erosion is used also larger far distance structures can taken into account. '] + ''}; + end + + inverse = cfg_menu; + inverse.tag = 'inverse'; + inverse.name = 'Inverse metric'; + inverse.labels = {'Yes','No'}; + inverse.values = {1,0}; + inverse.val = {1}; + inverse.help = { + 'Use inverse distance measures 1/d with 1 if the object is close and 0 if it is far away. Use log10 scaling. ' + ''}; + + outdir = cfg_files; + outdir.tag = 'outdir'; + outdir.name = 'Output Directory'; + outdir.filter = 'dir'; + outdir.ufilter = '.*'; + outdir.num = [0 1]; + 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.' + }; + + % distance weighting function [high low] + smoothing = cfg_entry; + smoothing.tag = 'smooth'; + smoothing.name = 'smoothing'; + smoothing.strtype = 'r'; + smoothing.num = [1 1]; + smoothing.val = {0}; + smoothing.hidden = expert<2; + smoothing.help = { + 'Distance based weighting from high to low, i.e. [0 10] means full weighting at 0 mm distance and zero weighting at 10 mm distance. ' + '' + }; + + + % measures + vmeasure = cfg_branch; + vmeasure.tag = 'vmeasure'; + vmeasure.name = 'Volume measure'; + if expert>1 + vmeasure.val = {rimage,rimage2,name,dweighting,norm,inverse}; + else + vmeasure.val = {rimage,rimage2,name,dweighting,norm}; + end + vmeasure.help = { + 'Extraction of local volume values of a specied tissue or region. Modulated push from voxel- to surface-space. '}; + + imeasure = cfg_branch; + imeasure.tag = 'imeasure'; + imeasure.name = 'Intensity measure'; + if expert>1 + imeasure.val = {rimage,iimage,iname,dweighting,norm,average}; + else + imeasure.val = {rimage,iimage,iname,dweighting,norm}; + end + imeasure.help = { + 'Extraction of local intensity values of one map in the regions defined by another. '}; + + dmeasure = cfg_branch; + dmeasure.tag = 'dmeasure'; + dmeasure.name = 'Distance measure'; + if expert>1 + dmeasure.val = {rimage,dname,dweighting,norm,dmetric}; + else + dmeasure.val = {rimage,dname,dweighting,norm}; + end + dmeasure.help = { + 'Extraction of local intensity values of one map in the regions defined by another. '}; + + + % predefined measures + % --- volume measures ------------------------------------------------- + GMV = cfg_menu; + GMV.tag = 'GMV'; + GMV.name = 'GM volume'; + GMV.labels = {'Yes','No'}; + GMV.values = {1,0}; + GMV.val = {0}; + GMV.hidden = expert<1; + GMV.help = { + ['Map local GM volume within 3 mm distance to the surface. ' ... + 'The results are similar to the GM thickness map and represents the simplyfied form V_GM = A_GM * T_GM. '] + ''}; + + WMV = GMV; + WMV.tag = 'WMV'; + WMV.name = 'WM volume'; + WMV.hidden = expert<1; + WMV.help = { + ['Map local WM volume within 10 mm distance to the surface. ' ... + 'Especially the motorcortex and occipital areas have an enlarged volume compared to other ares. ' ... + 'The enlargement could be related to the amount of myelination and hence depend on the preprocessing. '] + ''}; + + WMHV = GMV; + WMHV.tag = 'WMHV'; + WMHV.name = 'WMH volume'; + WMHV.hidden = expert<1; + WMHV.help = { + 'Map local WMH volume within 10 mm distance to the surface. ' + '' + 'See also WMH vs WM volume measure.' + ''}; + + WMHVvsWMV = GMV; + WMHVvsWMV.tag = 'WMHVvsWMV'; + WMHVvsWMV.name = 'WMH vs. WM volume'; + WMHVvsWMV.hidden= expert<1; + WMHVvsWMV.help = { + 'Estimate the relation between the mapped local WMH and WM volume within 10 mm distance. ' + ''}; + + WMVvsGMV = GMV; + WMVvsGMV.tag = 'WMVvsGMV'; + WMVvsGMV.name = 'WM vs. GM volume'; + WMVvsGMV.hidden = expert<2; + WMVvsGMV.help = { + 'This describes the relation between the local amount of WM to GM and is some kind of folding measure. ' + ''}; + + % intensity + WMmnI = GMV; + WMmnI.tag = 'WMmnI'; + WMmnI.name = 'WM mean intensity'; + WMmnI.hidden = expert<2; + WMmnI.help = { + 'This describes the mean intensity of the WM in a distance of 7 voxels and describes the impact of WMHs in the volume. ' + '' + 'See also WM intensity variance.' + ''}; + + WMsdI = GMV; + WMsdI.tag = 'WMsdI'; + WMsdI.name = 'WM intensity variance'; + WMsdI.hidden = expert<2; + WMsdI.help = { + ['This describes the standard deviation of the intensity within the WM of a 7x7x7 box and describes the impact of WMHs in the volume. ' ... + 'In contrast to the WM mean intensity it is less effected by WMHs and more sensitive to PVSs. '] + '' + 'See also WM mean intensity. ' + ''}; + + GMmnI = GMV; + GMmnI.tag = 'GMmnI'; + GMmnI.name = 'GM mean intensity'; + GMmnI.hidden = expert<2; + GMmnI.help = { + 'This describes the mean intensity of the GM in a 5x5x5 box and describes the myelination of the cortex. ' + ''}; + + % distances + WMD = GMV; + WMD.tag = 'WMD'; + WMD.name = 'WM distance'; + WMD.hidden = expert<1; + WMD.help = { + ['This another way to measures the cortical thickness with GMT = WMD * 2, ' ... + 'because the central surface runs in the middle of the cortex. '] + 'However, this is just an example to test the distance measure in general and it is better to use the thickness itself. ' + ''}; + + WMHD = GMV; + WMHD.tag = 'WMHD'; + WMHD.name = 'WMH distance'; + WMHD.hidden = expert<1; + WMHD.help = { + 'This describes the distance to the closest WMH. The measure is similar to the WMV. ' + ''}; + + % PVSdist + + xmeasure = cfg_branch; + xmeasure.tag = 'xmeasure'; + xmeasure.name = 'Predefined measures'; + xmeasure.val = {GMV,WMV,WMHV,WMHVvsWMV,WMVvsGMV,WMmnI,WMsdI,GMmnI,WMD,WMHD}; + xmeasure.help = { + 'The are some predefined measures to project local tissue properties to the surface.'}; + + % measure {vol, int, dist, idist) + measures = cfg_repeat; + measures.tag = 'measures'; + measures.name = 'Measures'; + measures.num = [1 inf]; + measures.values = {xmeasure, vmeasure, imeasure, dmeasure}; + measures.val = {xmeasure}; + measures.help = { + 'Application of predefined measures or own defintion of volume-, intensity-, distance-based ways to map voxel-based informations to the surface. ' ''}; + + interp = cfg_menu; + interp.tag = 'interp'; + interp.name = 'Interpolation'; + interp.labels = {'yes','no'}; + interp.values = {1,0}; + interp.val = {0}; + interp.hidden = expert<2; + interp.help = { + ['Use interpolated voxel grid to improve mapping quality. ' ... + 'However, it is expected that there are only small improvements that are not ' ... + 'relevant because strong smoothing is also required by anatomical constrains. '] ''}; + + % opts + opts = cfg_exbranch; + opts.tag = 'opts'; + opts.name = 'Options'; + if expert + opts.val = {interp,outdir,nproc}; % lazy,nproc,verb + else + opts.val = {outdir,nproc}; + end + opts.help = {'General processing options of all measures. ' ''}; + + % main + vx2surf = cfg_exbranch; + vx2surf.tag = 'vx2surf'; + vx2surf.name = 'Map voxel-data to the surface (IN DEVELOPMENT)'; + vx2surf.val = {surf,measures,opts}; % + vx2surf.prog = @cat_surf_vx2surf; + vx2surf.vout = @vout_cat_surf_vx2surf; + vx2surf.help = { + ['Voxel-based projection of volume values to the individual surface that is still IN DEVELOPMENT. ' ... + 'The approach aligns all voxels within a specified tissue/ROI to its closest surface vertex. ' ... + 'The volume, intensity, or distance values were averaged in a user specified way and saved as a raw surface measure ' ... + 'that has to be smoothed and resampled. '] + ''}; + vx2surf.hidden = expert<2; + +return +function surf2roi = cat_surf_surf2roi_GUI(expert,nproc) +%% surface to ROI (in template space) +% --------------------------------------------------------------------- +% * CxN cdata files [ thickness , curvature , ... any other file ] in template space [ resampled ] +% * M atlas files [ choose files ] +% * average measures [ mean , std , median , max , min , mean95p ] +% +% - csv export (multiple files) > catROIs_ATLAS_SUBJECT +% - xml export (one file) > catROIs_ATLAS_SUBJECT +% --------------------------------------------------------------------- +% surface ROIs have sidewise index?! +% --------------------------------------------------------------------- + +% set of cdata files +if expert && 0 % this is not ready now + cdata = cfg_files; + cdata.tag = 'cdata'; + cdata.name = '(Left) Surface Data Files'; + cdata.filter = 'any'; + cdata.ufilter = 'lh.(?!cent|pial|white|sphe|defe|hull|pbt).*'; + cdata.num = [1 Inf]; + cdata.help = {'Surface data files. Both sides will be processed'}; +else % only smoothed/resampled + cdata = cfg_files; + cdata.tag = 'cdata'; + cdata.name = '(Left) Surface Data Files'; + cdata.filter = 'any'; + cdata.ufilter = '^lh.(?!cent|pial|white|sphe|defe|hull|pbt).*'; + cdata.num = [1 Inf]; + cdata.help = {'Surface data files. Both sides will be processed'}; +end + +cdata_sample = cfg_repeat; +cdata_sample.tag = 'cdata_sub.'; +cdata_sample.name = 'Surface Data'; +cdata_sample.values = {cdata}; +cdata_sample.num = [1 Inf]; +cdata_sample.help = {[... + 'Specify data for each measure (i.e. thickness, gyrification, ...). ' ... + 'All measures must have the same size and same order. ' ... + '' +]}; + +% ROI files +ROIs = cfg_files; +ROIs.tag = 'rdata'; +ROIs.name = '(Left) ROI atlas files'; +ROIs.filter = 'any'; +ROIs.ufilter = '^lh.*\.annot$'; +ROIs.dir = fullfile(fileparts(mfilename('fullpath')),'atlases_surfaces'); +ROIs.num = [1 Inf]; +%ROIs.hidden = expert<2; +ROIs.help = {'These are the ROI atlas files. Both sides will be processed.'}; + + +% not used +%{ +% ROI area +area = cfg_menu; +area.tag = 'area'; +area.name = 'Estimate ROI Area'; +area.labels = {'No','Yes'}; +area.values = {0,1}; +area.val = {1}; +area.help = {'Estimate area of each ROI.'}; + +% ROI area +vernum = cfg_menu; +vernum.tag = 'vernum'; +vernum.name = 'Count ROI Vertices'; +vernum.labels = {'No','Yes'}; +vernum.values = {0,1}; +vernum.val = {1}; +vernum.help = {'Count vertices of each ROI.'}; +%} + +% average mode within a ROI +% mean +avg.mean = cfg_menu; +avg.mean.tag = 'mean'; +avg.mean.name = 'Mean Estimation'; +avg.mean.labels = {'No','Yes'}; +avg.mean.values = {0,1}; +avg.mean.val = {1}; +avg.mean.help = {'Set mean value estimation per ROI.'}; +% std +avg.std = cfg_menu; +avg.std.tag = 'std'; +avg.std.name = 'STD Estimation'; +avg.std.labels = {'No','Yes'}; +avg.std.values = {0,1}; +avg.std.val = {1}; +avg.std.help = {'Set standard deviation estimation per ROI.'}; +% min +avg.min = cfg_menu; +avg.min.tag = 'min'; +avg.min.name = 'Minimum Estimation'; +avg.min.labels = {'No','Yes'}; +avg.min.values = {0,1}; +avg.min.val = {0}; +avg.min.help = {'Set minimum estimation per ROI.'}; +% max +avg.max = cfg_menu; +avg.max.tag = 'max'; +avg.max.name = 'Maximum Estimation'; +avg.max.labels = {'No','Yes'}; +avg.max.values = {0,1}; +avg.max.val = {0}; +avg.max.help = {'Set maximum estimation per ROI.'}; +% median +avg.median = cfg_menu; +avg.median.tag = 'median'; +avg.median.name = 'Median Estimation'; +avg.median.labels = {'No','Yes'}; +avg.median.values = {0,1}; +avg.median.val = {0}; +avg.median.help = {'Set median estimation per ROI.'}; +% all functions +avg.main = cfg_branch; +avg.main.tag = 'avg'; +avg.main.name = 'ROI Average Functions'; +avg.main.val = { + avg.mean ... + avg.std ... + avg.min ... + avg.max ... + avg.median ... +}; +avg.main.hidden = expert<2; + + +nproc.hidden = expert<2; + +%% main function +surf2roi = cfg_exbranch; +surf2roi.tag = 'surf2roi'; +surf2roi.name = 'Extract ROI-based surface values'; +% CG 20200820: here we still have to use the differentiation between different modes +% because the developer settings are not yet working +switch expert +case 2 + surf2roi.val = { + cdata_sample ... + ROIs ... + nproc ... + avg.main}; +case {0, 1} + surf2roi.val = {cdata_sample,ROIs}; +end +surf2roi.prog = @cat_surf_surf2roi; +surf2roi.vout = @vout_surf_surf2roi; +surf2roi.help = { + 'While ROI-based values for VBM (volume) data are automatically saved in the label folder as XML file it is necessary to additionally extract these values for surface data. This has to be done after preprocessing the data and creating cortical surfaces. ' + '' + 'You can extract ROI-based values for cortical thickness but also for any other surface parameter that was extracted using the ""Extract Additional Surface Parameters"" function.' + '' + 'Please note that these values are extracted from data in native space without any smoothing. As default the mean inside a ROI is calculated and saved as XML file in the label folder.' +}; + +%========================================================================== +function [vol2surf,vol2tempsurf] = cat_surf_vol2surf_GUI(expert,merge_hemi,mesh32k) +%% map volumetric data +%----------------------------------------------------------------------- +datafieldname = cfg_entry; +datafieldname.tag = 'datafieldname'; +datafieldname.name = 'Output Name'; +datafieldname.strtype = 's'; +datafieldname.num = [1 Inf]; +datafieldname.val = {'intensity'}; +datafieldname.help = { + 'Name that is prepended to the filename of the mapped volume.' + '' + }; + +interp = cfg_menu; +interp.tag = 'interp'; +interp.name = 'Interpolation Type'; +interp.labels = {'Nearest neighbour','Linear','Cubic'}; +interp.values = {{'nearest_neighbour'},{'linear'},{'cubic'}}; +interp.val = {{'linear'}}; +interp.hidden = expert<1; +interp.help = { + 'Volume extraction interpolation type. ' + ' -linear: Use linear interpolation (default).' + ' -nearest_neighbour: Use nearest neighbour interpolation.' + ' -cubic: Use cubic interpolation.' + '' +}; + +% sample function +sample = cfg_menu; +sample.tag = 'sample'; +sample.name = 'Sampling Function'; +sample.labels = {'Mean','Median','Weighted mean','Maximum','Minimum','Absolute maximum','Multi-values'}; +sample.values = {{'avg'},{'median'},{'weighted_avg'},{'max'},{'min'},{'maxabs'},{'multi'}}; +sample.val = {{'maxabs'}}; +sample.help = { + 'Sampling function to combine the values of the grid along the surface normals.' + ' Mean: Use average for mapping along normals.' + ' Median: Use median for mapping along normals.' + ' Weighted mean: Use weighted average with gaussian kernel for mapping along normals. The kernel is so defined that values at the boundary are weighted with 50% while center is weighted with 100% (useful for (r)fMRI data.' + ' Maximum: Use maximum value for mapping along normals.' + ' Minimum: Use minimum value for mapping along normals.' + ' Absolute maximum: Use absolute maximum value for mapping along normals (useful for mapping contrast images from 1st-level fMRI analysis).' + ' Multi-values: Map data for each grid step separately and save files with indicated grid value. Please note that this option is intended for high-resolution (f)MRI data only (e.g. 0.5mm voxel size).' + '' +}; + +%% -- sampling points and average function + +% startpoint +abs_startpoint = cfg_entry; +abs_startpoint.tag = 'startpoint'; +abs_startpoint.name = 'Startpoint'; +abs_startpoint.strtype = 'r'; +abs_startpoint.val = {-0.5}; +abs_startpoint.num = [1 1]; +abs_startpoint.help = { + 'Absolute position of the start point of the grid along the surface normals in mm according to the surface. Give negative value for a start point outside of the surface (CSF direction, outwards). ' +}; +rel_startpoint = abs_startpoint; +rel_startpoint.val = {-0.6}; +rel_startpoint.help = { + 'Relative position of the start point of the grid along the surface normals according to a tissue class. A value of ""-0.5"" begins at the GM/CSF border and even lower values define a start point outside of the tissue class (CSF direction, outwards) which is the default to ensure that all values are mapped. A value of ""0"" means that the central surface is used as starting point and ""0.5"" is related to the GM/WM border.' +}; + +% steps +abs_steps = cfg_entry; +abs_steps.tag = 'steps'; +abs_steps.name = 'Steps'; +abs_steps.strtype = 'w'; +abs_steps.val = {7}; +abs_steps.num = [1 1]; +abs_steps.help = { + 'Number of grid steps. ' +}; +rel_steps = abs_steps; + +% endpoint +abs_endpoint = cfg_entry; +abs_endpoint.tag = 'endpoint'; +abs_endpoint.name = 'Endpoint'; +abs_endpoint.strtype = 'r'; +abs_endpoint.val = {0.5}; +abs_endpoint.num = [1 1]; +abs_endpoint.help = { + 'Absolute position of the end point of the grid along the surface normals (pointing inwards) in mm according to the surface. ' +}; +rel_endpoint = abs_endpoint; +rel_endpoint.val = {0.6}; +rel_endpoint.help = { + 'Relative position of the end point of the grid along the surface normals (pointing inwards) according to a tissue class. A value of ""0.5"" ends at the GM/WM border and values > 0.5 define an end point outside of the tissue class (WM direction, inwards) which is the default to ensure that all values are mapped. A value of ""0"" ends at the central surface.' +}; + +% tissue class +rel_class = cfg_menu; +rel_class.tag = 'class'; +rel_class.name = 'Tissue Class'; +rel_class.labels = {'GM'}; +rel_class.values = {'GM'}; +rel_class.val = {'GM'}; +rel_class.help = { + 'Tissue class for which the relative positions are estimated.' +}; + +% tissue class +abs_class = cfg_menu; +abs_class.tag = 'surface'; +abs_class.name = 'Surface'; +abs_class.labels = {'WM Surface','Central Surface','Pial Surface'}; +abs_class.values = {'WM','Central','Pial'}; +abs_class.val = {'Central'}; +abs_class.help = { + 'Surface (or tissue boundary) for which the absolute positions are estimated.' +}; + +% absolute position +abs_mapping = cfg_branch; +abs_mapping.tag = 'abs_mapping'; +abs_mapping.name = 'Absolute Grid Position From a Surface'; +abs_mapping.val = { + abs_class ... + abs_startpoint ... + abs_steps ... + abs_endpoint ... +}; +abs_mapping.help = { + 'Map volumetric data from abolute grid positions from a surface (or tissue boundary).' +}; + +%% relative mapping with equi-distance approach +rel_mapping = cfg_branch; +rel_mapping.tag = 'rel_mapping'; +rel_mapping.name = 'Relative Grid Position Within a Tissue Class (Equi-distance Model)'; +rel_mapping.val = { + rel_class ... + rel_startpoint ... + rel_steps ... + rel_endpoint ... +}; +rel_mapping.help = { + 'Map volumetric data from relative grid positions within a tissue class using equi-distance approach. Here, the grid lines have equal distances between the tissues.' +}; + +%% relative mapping with equi-volume approach +rel_equivol_mapping = cfg_branch; +rel_equivol_mapping.tag = 'rel_equivol_mapping'; +rel_equivol_mapping.name = 'Relative Grid Position Within a Tissue Class (Equi-volume Model)'; +rel_equivol_mapping.val = { + rel_class ... + rel_startpoint ... + rel_steps ... + rel_endpoint ... +}; +rel_equivol_mapping.help = { + 'Map volumetric data from relative positions within a tissue class using equi-volume approach. ' + 'This option is using the approach by Bok (Z. Gesamte Neurol. Psychiatr. 12, 682-750, 1929). ' + 'Here, the volume between the grids is constant. The correction is based on Waehnert et al. (NeuroImage, 93: 210-220, 2014).' + '' +}; + +%% -- Mapping function + +mapping = cfg_choice; +mapping.tag = 'mapping'; +mapping.name = 'Mapping Function'; +mapping.values = { + abs_mapping ... + rel_equivol_mapping ... +}; +mapping.val = {rel_equivol_mapping}; +mapping.help = { + 'Volume extraction type. ' + ' Absolute Grid Position From a Surface (or Tissue Boundary):' + ' Extract values around a surface or tissue boundary with a specified absolute sample ' + ' distance and either combine these values or save values separately.' + ' Relative Grid Position Within a Tissue Class (Equi-volume approach):' + ' Extract values within a tissue class with a specified relative sample distance' + ' that is corrected for constant volume between the grids and either combine these values or save values separetely.' + '' +}; + +if expert > 1 + mapping.values{3} = rel_mapping; + mapping.help = [ mapping.help; { + ' Relative Grid Position Within a Tissue Class (Equi-distance approach):' + ' Extract values within a tissue class with a specified relative sample distance' + ' with equally distributed distances and either combine these values or save values separately.' + '' + }]; +end + +mapping_native = mapping; + + +% extract volumetric data in individual space +%----------------------------------------------------------------------- + +data_surf_sub_lh = cfg_files; +data_surf_sub_lh.tag = 'data_mesh_lh'; +data_surf_sub_lh.name = '(Left) Individual Surfaces'; +data_surf_sub_lh.filter = 'gifti'; +data_surf_sub_lh.ufilter = '^lh.central.(?!nofix).*'; +data_surf_sub_lh.num = [1 Inf]; +data_surf_sub_lh.help = { + 'Select left subject surface files.' + 'Right side will be automatically processed.' + }; + +data_sub = cfg_files; +data_sub.tag = 'data_vol'; +data_sub.name = '(Co-registered) Volumes in Native Space'; +data_sub.filter = 'image'; +data_sub.ufilter = '^(?!wm|wp|m0wp|mwp|wc).*'; % no normalized images +data_sub.num = [1 Inf]; +data_sub.help = { + 'Select volumes in native (subject) space.' + 'Please note that these images have to be in the same space as the T1-image that was used to extract the cortical surface. An optional co-registration might be necessary if you have functional or structural data that are not yet aligned to the T1-image.' +}; + +vol2surf = cfg_exbranch; +vol2surf.tag = 'vol2surf'; +vol2surf.name = 'Map Volume (Native Space) to Individual Surface'; +vol2surf.val = { + data_sub ... + data_surf_sub_lh ... + sample ... + interp ... + datafieldname ... + mapping_native ... + }; + +vol2surf.prog = @cat_surf_vol2surf; +vol2surf.vout = @vout_vol2surf; +vol2surf.help = { + 'Map volume (native space) to individual surface. These mapped volumes have to be finally resampled and smoothed before any statistical analysis.' + '' + 'The output will be named:' + ' [rh|lh].OutputName_VolumeName' + '' +}; + +data_surf_avg_lh = cfg_files; +data_surf_avg_lh.tag = 'data_mesh_lh'; +data_surf_avg_lh.name = '(Left) Template Hemisphere'; +data_surf_avg_lh.filter = 'gifti'; +data_surf_avg_lh.ufilter = '^lh.*'; +data_surf_avg_lh.num = [1 1]; +data_surf_avg_lh.val{1} = {fullfile(fileparts(mfilename('fullpath')),'templates_surfaces',['lh.central.' cat_get_defaults('extopts.shootingsurf') '.gii'])}; +data_surf_avg_lh.dir = fullfile(fileparts(mfilename('fullpath'))); +data_surf_avg_lh.help = { + 'Select left template surface file. ' + 'Right hemisphere will be automatically processed.' + }; + +data_norm = cfg_files; +data_norm.tag = 'data_vol'; +data_norm.name = 'Spatially Normalized Volumes'; +data_norm.filter = 'image'; +data_norm.ufilter = '.*'; +data_norm.num = [1 Inf]; +data_norm.help = { + 'Select spatially normalized volumes (in template space).' + '' +}; + +vol2tempsurf = cfg_exbranch; +vol2tempsurf.tag = 'vol2surftemp'; +vol2tempsurf.name = 'Map Normalized Volume to Template Surface'; +vol2tempsurf.val = { + data_norm ... + merge_hemi ... + mesh32k ... + sample ... + interp ... + datafieldname ... + mapping ... +}; +vol2tempsurf.prog = @cat_surf_vol2surf; +vol2tempsurf.vout = @vout_vol2surf; +vol2tempsurf.help = { + 'Map spatially normalized data (in template space) to template surface.' + 'The template surface was generated by CAT12 surface processing of the average of 555 Dartel-normalized images of the IXI database that were also used to create the IXI Dartel template. ' + '' + 'The ouput will be named:' + ' [rh|lh|mesh].OutputName_VolumeName.Template_T1.gii' + '' + ' WARNING: This function is primarily thought in order to project statistical results ' + ' to the template surface. Do not use the output of this function' + ' for any statistical analysis. Statistical analysis should only use' + ' resampled data of individual volume data (in native space) that were mapped' + ' to individual surfaces.' + '' +}; + +%========================================================================== +function [surfcalc,surfcalcsub] = cat_surf_calc_GUI(expert) +%% surface calculations +% --------------------------------------------------------------------- +% estimation per subject (individual and group sampling): +% g groups with i datafiles and i result datafile + +cdata = cfg_files; +cdata.tag = 'cdata'; +cdata.name = 'Surface Data Files'; +cdata.filter = 'any'; % use any to support Freesurfer surfaces and dependencies +cdata.ufilter = '(lh|rh|mesh).*.gii'; +cdata.num = [1 Inf]; +cdata.help = {'These are the surface data files that are used by the calculator. They are referred to as s1, s2, s3, etc in the order they are specified.'}; + +cdata_sub = cfg_files; +cdata_sub.tag = 'cdata'; +cdata_sub.name = 'Surface Data Files'; +cdata_sub.filter = 'any'; % use any to support Freesurfer surfaces and dependencies +cdata_sub.ufilter = '(lh|rh|mesh).(?!cent|pial|white|sphe|defe|hull).*gii'; +cdata_sub.num = [1 Inf]; +cdata_sub.help = {'These are the surface data files that are used by the calculator. They are referred to as s1, s2, s3, etc in the order they are specified.'}; + +cdata_sample = cfg_repeat; +cdata_sample.tag = 'cdata_sub.'; +cdata_sample.name = 'Surface Data Sample'; +cdata_sample.values = {cdata_sub}; +cdata_sample.num = [1 Inf]; +cdata_sample.help = {... + 'Specify data for each sample. All samples must have the same size and same order.'}; + +outdir = cfg_files; +outdir.tag = 'outdir'; +outdir.name = 'Output Directory'; +outdir.filter = 'dir'; +outdir.ufilter = '.*'; +outdir.num = [0 1]; +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.' +}; + +dataname = cfg_entry; +dataname.tag = 'dataname'; +dataname.name = 'Output Filename'; +dataname.strtype = 's'; +dataname.num = [1 Inf]; +dataname.val = {'mesh.output'}; +dataname.help = {'The output surface data file 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.'}; + +datahandling = cfg_menu; +datahandling.name = 'Sample data handling'; +datahandling.tag = 'datahandling'; +datahandling.labels = {'subjectwise','datawise'}; +datahandling.values = {1,2}; +datahandling.val = {1}; +datahandling.hidden = expert<2; +datahandling.help = {... + 'There are two ways to hand surface calculation for many subjects: (i) subjectwise or (ii) datawise.' + '' + ['Subject-wise means that you have multiple surface measures that should ' ... + 'be processed for multiple subjects in the same way within the native subject space. ' ... + 'E.g., To multiply thickness with area as simple approximation of cortical ' ... + 'volume, resulting in a new surface measure or texture for each subject. ' ... + 'So you have to create one sample for each surface measure and select for each of them all subject. ' ... + 'In our example, we have two samples: (i) one with thickness that include the thickness data of all subjects and ' ... + '(ii) another one that includes the surface area data of the same subjects. ' ... + 'It is therefore important that you select exactly the same subjects in the same order! ' ... + 'Hence, the name entry specify a the name of the the new surface measure (MEASUREENAME) in the resulting file: '] + ' [rh|lh].TEXTURNAME[.resampled].subjectname[.gii]' + '' + ['Data-wise means can be used to process each sample by the imcalc operation. ' ... + 'Hence, it require that each surface measure has the same data size - being from one subject or being resampled.' ... + 'This can be useful if you want to average the data of multiple subjects (e.g., mean(S) or std(S)) or ' ... + 'if you want to process multiple new measure of the same subject but with varying number of inputs (e.g., for multiple time points. ' ... + 'If each sample contain different subject than the SUBJECTNAME is replaced otherwise the TEXTURENAME: '] + ' [rh|lh].TEXTURNAME[.resampled].SUBJECTNAME[.gii]' + '' + }; + +expression = cfg_entry; +expression.tag = 'expression'; +expression.name = 'Expression'; +expression.strtype = 's'; +expression.num = [1 Inf]; +expression.val = {'s1'}; +expression.help = { + 'Example expressions (f):' + ' * Mean of six surface textures (select six texture files)' + ' f = ''(s1+s2+s3+s4+s5+s6)/6''' + ' * Make a binary mask texture at threshold of 100' + ' f = ''(s1>100)''' + ' * Make a mask from one texture and apply to another' + ' f = ''s2.*(s1>100)''' + ' - here the first texture is used to make the mask, which is applied to the second texture' + ' * Sum of n textures' + ' f = ''s1 + s2 + s3 + s4 + s5 + ...''' + ' * Sum of n textures (when reading data into a data-matrix - use dmtx arg)' + ' f = mean(S)' + '' +}; + +dmtx = cfg_menu; +dmtx.tag = 'dmtx'; +dmtx.name = 'Data Matrix'; +dmtx.labels = { + 'No - don''t read images into data matrix',... + 'Yes - read images into data matrix' +}; +dmtx.values = {0,1}; +dmtx.val = {0}; +dmtx.help = { + 'If the dmtx flag is set, then textures are read into a data matrix S (rather than into separate variables s1, s2, s3,...). The data matrix should be referred to as S, and contains textures in rows. Computation is vertex by vertex, S is a NxK matrix, where N is the number of input textures, and K is the number of vertices per plane.' +}; + + +% main functions +% ---------------------------------------------------------------------- + +% any image with similar properties +surfcalc = cfg_exbranch; +surfcalc.tag = 'surfcalc'; +surfcalc.name = 'Surface Calculator'; +surfcalc.val = { + cdata ... + dataname ... + outdir ... + expression ... + dmtx ... +}; +surfcalc.prog = @cat_surf_calc; +surfcalc.help = { + 'Mathematical operations for surface data (textures).' + 'It works similar to ""spm_imcalc"". The input surface data must have the same number of entries (e.g. data of the same hemisphere of a subject or resampled data).' +}; +surfcalc.vout = @(job) vout_cat_surf_calc(job); + + +% subject- / group-w +surfcalcsub = cfg_exbranch; +surfcalcsub.tag = 'surfcalcsub'; +surfcalcsub.name = 'Surface Calculator (subject-wise)'; +surfcalcsub.val = { + cdata_sample ... + datahandling ... developer + dataname ... + outdir ... + expression ... + dmtx ... +}; +surfcalcsub.help = { + 'Mathematical operations for surface data sets (textures).' + 'In contrast to the ""Surface Calculator"" it allows to apply the same expression to multiple subjects. Please note that a fixed name structure is expected: [rh|lh].TEXTURENAME[.resampled].subjectname[.gii]. Here TEXTURENAME will be replaced by the output name.' +}; +surfcalcsub.prog = @cat_surf_calc; +surfcalcsub.vout = @(job) vout_cat_surf_calcsub(job); + +%========================================================================== +function flipsides = cat_surf_flipsides_GUI(expert) +% Flipsides +%----------------------------------------------------------------------- +cdata = cfg_files; +cdata.tag = 'cdata'; +cdata.name = 'Surface Data Files'; +cdata.filter = 'gifti'; +cdata.ufilter = '^s.*mm\.lh.*'; +cdata.num = [1 Inf]; +cdata.help = {'Texture maps that should be flipped/mirrored from right to left.' ''}; + +cdata_sample = cfg_repeat; +cdata_sample.tag = 'cdata_sub.'; +cdata_sample.name = 'Surface Data Sample'; +cdata_sample.values = {cdata}; +cdata_sample.num = [1 Inf]; +cdata_sample.help = {'Specify data for each sample.'}; + +flipsides = cfg_exbranch; +flipsides.tag = 'flipsides'; +flipsides.name = 'Flip right to left hemisphere'; +flipsides.val = {cdata}; % replace later by cdata_sample ... update vout ... +flipsides.prog = @cat_surf_flipsides; +flipsides.hidden = expert<2; +flipsides.help = {'This function flip the right hemisphere to the left side, to allow side' ''}; +flipsides.vout = @(job) vout_cat_surf_flipsides(job); + +%========================================================================== +function [surfresamp,surfresamp_fs] = cat_surf_resamp_GUI(expert,nproc,merge_hemi,mesh32k,lazy) +%% Resample and smooth surfaces +% ------------------------------------------------------------------------ + +lazy.hidden = expert<1; + +data_surf = cfg_files; +data_surf.tag = 'data_surf'; +data_surf.name = '(Left) Surfaces Data'; +data_surf.filter = 'any'; +if expert > 1 + data_surf.ufilter = '^lh.'; +else + data_surf.ufilter = '^lh.(?!cent|pial|white|sphe|defe|hull|pbt).*'; +end +data_surf.num = [1 Inf]; +data_surf.help = {'Select surfaces data files for left hemisphere for resampling to template space.Right side will be automatically processed.'}; + +data_surf_mixed = data_surf; +data_surf_mixed.tag = 'data_surf_mixed'; +data_surf_mixed.name = '(Left) Mixed Surfaces Data'; +data_surf_mixed.help = [data_surf.help {'This version allows input of multiple dependencies!'}]; + +sample_surf = cfg_repeat; +sample_surf.tag = 'sample'; +sample_surf.name = 'Data'; +sample_surf.values = {data_surf,data_surf_mixed}; +sample_surf.num = [1 Inf]; +sample_surf.help = {... +'Specify data for each sample. If you specify different samples the mean correlation is displayed in separate boxplots for each sample.'}; + + +fwhm_surf = cfg_entry; +fwhm_surf.tag = 'fwhm_surf'; +fwhm_surf.name = 'Smoothing Filter Size in FWHM'; +fwhm_surf.strtype = 'r'; +fwhm_surf.num = [1 1]; +fwhm_surf.val = {12}; +fwhm_surf.help = { + 'Select filter size for smoothing. For cortical thickness a good starting value is 12mm, while other surface parameters based on cortex folding (e.g. gyrification, cortical complexity) need a larger filter size of about 20-25mm. For no filtering use a value of 0.'}; + +surfresamp = cfg_exbranch; +surfresamp.tag = 'surfresamp'; +surfresamp.name = 'Resample and Smooth Surface Data'; +if expert + surfresamp.val = {sample_surf, merge_hemi,mesh32k,fwhm_surf,lazy,nproc}; +else + surfresamp.val = {data_surf, merge_hemi,mesh32k,fwhm_surf,lazy,nproc}; +end +surfresamp.prog = @cat_surf_resamp; +surfresamp.vout = @(job) vout_surf_resamp(job); +surfresamp.help = { +'In order to analyze surface parameters all data have to be resampled into template space and the resampled data have to be finally smoothed. Resampling is done using the warped coordinates of the resp. sphere.'}; + + + + +%% Resample and smooth FreeSurfer surfaces +% ------------------------------------------------------------------------ + +data_fs = cfg_files; +data_fs.tag = 'data_fs'; +data_fs.name = 'Freesurfer Subject Directories'; +data_fs.filter = 'dir'; +data_fs.ufilter = '.*'; +data_fs.num = [1 Inf]; +data_fs.help = {'Select subject folders of Freesurfer data to resample data (e.g. thickness).'}; + +measure_fs = cfg_entry; +measure_fs.tag = 'measure_fs'; +measure_fs.name = 'Freesurfer Measure'; +measure_fs.strtype = 's'; +measure_fs.num = [1 Inf]; +measure_fs.val = {'thickness'}; +measure_fs.help = { + 'Name of surface measure that should be resampled and smoothed.' + '' + }; + +outdir = cfg_files; +outdir.tag = 'outdir'; +outdir.name = 'Output Directory'; +outdir.filter = 'dir'; +outdir.ufilter = '.*'; +outdir.num = [0 1]; +outdir.help = {'Select a directory where files are written.'}; + +surfresamp_fs = cfg_exbranch; +surfresamp_fs.tag = 'surfresamp_fs'; +surfresamp_fs.name = 'Resample and Smooth Existing FreeSurfer Surface Data'; +surfresamp_fs.val = {data_fs,measure_fs,merge_hemi,mesh32k,fwhm_surf,outdir}; +surfresamp_fs.prog = @cat_surf_resamp_freesurfer; +surfresamp_fs.help = { +'If you have existing Freesurfer data (e.g. thickness) this function can be used to resample these data, smooth the resampled data, and convert Freesurfer data to gifti format.'}; + +%========================================================================== +function roi2surf = cat_roi_roi2surf_GUI(expert) +%% roi to surface +% ------------------------------------------------------------------------ + +% ROI files +r2s.ROIs = cfg_files; +r2s.ROIs.tag = 'rdata'; +r2s.ROIs.name = 'ROI atlas files'; +r2s.ROIs.filter = 'xml'; +r2s.ROIs.ufilter = '.*\.xml$'; +r2s.ROIs.dir = cat_get_defaults('extopts.pth_templates'); +r2s.ROIs.num = [1 Inf]; +r2s.ROIs.help = {'These are the indiviudal ROI atlas files from the label directory. Choose XML files.'}; + +% atlas used for extraction .. if xml +r2s.atlas = cfg_entry; +r2s.atlas.tag = 'atlas'; +r2s.atlas.name = 'Atlas maps'; +r2s.atlas.help = {'Enter the name of the atlas maps, e.g. ""LPBA40"", or ""all"".'}; +r2s.atlas.strtype = 's'; +r2s.atlas.val = {'all'}; +r2s.atlas.num = [1 Inf]; + +% datafield in the CSV or XML file eg the GM thickness +r2s.data = cfg_entry; +r2s.data.tag = 'fields'; +r2s.data.name = 'Datafields'; +r2s.data.help = {'Enter the name of the data fields, e.g. ""Vgm"", ""Igm"", ""Tgm"", ""mySurfData"" or ""all""'}; +r2s.data.strtype = 's'; +r2s.data.val = {'all'}; +r2s.data.num = [1 Inf]; + +% surface +r2s.surf = cfg_menu; +r2s.surf.name = 'Surface type for mapping'; +r2s.surf.tag = 'surf'; +r2s.surf.labels = {'FS average','Dartel average','subject'}; +r2s.surf.values = {'freesurfer','dartel','subject'}; +r2s.surf.val = {'freesurfer'}; +r2s.surf.help = {'Surface type for value projection. '}; + +% average function? - not required + +% main function +roi2surf = cfg_exbranch; +roi2surf.tag = 'roi2surf'; +roi2surf.name = 'Map ROI data to the surface'; +roi2surf.val = { + r2s.ROIs ... + r2s.atlas ... + r2s.data ... + r2s.surf ... + }; +roi2surf.prog = @cat_roi_roi2surf; +roi2surf.hidden = expert<2; +roi2surf.help = { + '' +}; + +%========================================================================== +function surfextract = cat_surf_parameters_GUI(expert,nproc,lazy) +%% surface measures +% ------------------------------------------------------------------------ + +data_surf_extract = cfg_files; +data_surf_extract.tag = 'data_surf'; +data_surf_extract.name = 'Central Surfaces'; +data_surf_extract.filter = 'gifti'; +data_surf_extract.ufilter = '^lh.central'; +data_surf_extract.num = [1 Inf]; +data_surf_extract.help = {'Select left surfaces to extract values.'}; + +% absolute mean curvature +GI = cfg_menu; +if expert>1 + GI.name = 'Gyrification (absolute mean curvature)'; + GI.labels = {'No','Yes (MNI approach)','Yes (Dong approach)'}; + GI.values = {0,1,2}; +else + GI.name = 'Gyrification'; + GI.labels = {'No','Yes'}; + GI.values = {0,1}; +end +GI.tag = 'GI'; +GI.val = {1}; +GI.help = { + 'Extract gyrification based on absolute mean curvature. The method is described in Luders et al. NeuroImage, 29: 1224-1230, 2006.' +}; +if expert>1 + GI.help = [ GI.help; + {['Because curvature depends on object size a normalization / scaling of the full surface by the radius of sphere with the volume of the hull surface is used. ' ... + 'The default curvature estimation uses a fast approach that is less robust for the sampling of the surface and a more accurate but slower version is available. ' ... + 'based on Dong et al. (2005) Curvature estimation on triangular mesh, JZUS.']}]; +end + + + + +% --------------------------------------------------------------------- +% DFG project measures +% --------------------------------------------------------------------- +GIL = cfg_menu; +GIL.name = 'Laplacian gyrification indices'; +GIL.tag = 'GIL'; +GIL.labels = {'No','inward','outward','generalized','all'}; +GIL.values = {0,1,2,3,4}; +GIL.val = {0}; +GIL.hidden = expert<2; +GIL.help = {[ ... + 'WARNING: This GI measures is still in development and not verified yet!\n\n ' ... + 'Extraction of Laplacian-based gyrification indices as local area relation between the individual folded and the unfolded surface. ' ... + 'The Laplacian approach supports an optimal mapping between the surfaces but the classical definition of the outer hull result in a measure that focuses on inward folding. ' ... + '\n\n' ... + 'The ""inward"" option use only the hull surface resulting in high sulcal values (Dahnke et al. 2010, Li et al. 2014) and is a local 3D representation of Zilles gyrification index (Zilles et al. 1989). ' ... + 'The ""outward"" option use only the core surface and result in high gyral values. However, the core definition is expected to be less robust for very strong tissue atrophy. ' ... + 'The ""generalized"" option combine both models resulting in an independent folding model that is expected to require less smoothing for surface-based analysis (15 mm). ' ... + '\n\n' ... + 'This research part of the DFG project DA 2167/1-1 (2019/04 - 2012/04).\n\n' ... +]}; + +if expert>1 + % Developer/expert parameters? + GILtype = GIL; + + % to small values may lead to problems in high resolution data? + % > compensation term in cat_surf_gyrification + laplaceerr = cfg_menu; + laplaceerr.name = 'Laplacian filter accuracy'; + laplaceerr.tag = 'laplaceerr'; + laplaceerr.labels = {'0.001','0.0001','0.00001'}; + laplaceerr.values = {0.001,0.0001,0.00001}; + laplaceerr.val = {0.0001}; + laplaceerr.help = {'Filter accuracy of the voxel-base Laplace filter applied before streamline estimation. Smaller values are more accurate but increase processing time. \n\n'}; + + % check if this compensate for voxel size! + GIstreamopt = cfg_menu; + GIstreamopt.name = 'Streamline accuracy'; + GIstreamopt.tag = 'GIstreamopt'; + GIstreamopt.labels = {'0.01','0.001','0.0001'}; + GIstreamopt.values = {0.01,0.001,0.0001}; + GIstreamopt.val = {0.01}; + GIstreamopt.help = {'Stepsize of the Laplacian streamline estimation. Small values are more accurate but increase processing and memory demands. \n\n'}; + + % normalization function + GInorm = cfg_menu; + GInorm.name = 'Normalization function'; + GInorm.tag = 'GInorm'; + GInorm.labels = {'none','2nd root','3rd root','6th root','10th root','log2','log','log10'}; + GInorm.values = {1,2,3,6,10,'log2','log','log10'}; + GInorm.val = {'log10'}; + GInorm.help = {[ ... + 'Normalization function (after area filtering) to avoid the exponential increase of the GI values and to have more gaussian-like value distribution.' ... + 'To avoid negative values in case of logarithmic functions the values were corrected by the basis of the logarithmic function, e.g. +10 for log10. ' ... + 'The logarithmic function supports stronger compensation of high values. This is especially important for the inward and outward but not generalized GI. ' ... + ]}; + + % Relative (brain size depending) or absolute (in mm) filtering? + % For animals relative should be more correct! + % + % Comment RD20190409 + % --------------------------------------------------------------------- + % Smoothing has to be done on the original surfaces to guarantee that + % the local GI is equal to the global on. + % We got similar problems for ""resample and smooth"" as for the ""area"" + % measure. + % Maybe an ""resample and smooth"" (automatic) normalization option can + % help that guarantee the right kind of handling, e.g. global mean or + % sum? + % --------------------------------------------------------------------- + + GILfs = cfg_entry; + GILfs.tag = 'GIpresmooth'; + GILfs.name = 'Final filter size'; + GILfs.strtype = 'r'; + GILfs.val = {0.1}; + GILfs.num = [1 inf]; + GILfs.help = {[ ... + 'Filter of the Laplacian based GI has to be done for the area variables of the folded and unfolded surfaces. ' ... + 'Values between 0 and 1 describe relative smoothing depending on the brain size, whereas values larger/equal than one describes the filter size in mm.']}; + + % save temporary surfaces + %{ + GIwritehull = cfg_menu; + GIwritehull.name = 'Laplacian gyrification indices hull/core surface output'; + GIwritehull.tag = 'GIwritehull'; + GIwritehull.labels = {'No','Yes'}; + GIwritehull.values = {0,1}; + GIwritehull.val = {1}; + GIwritehull.help = {'Write hull/core surface use in the Laplacian gyrification index estimation.'}; + %} + + % hull model - This is not yet implemented! + % The idea behind is that the hemisphere-based hull is artificial too + % and that are more natural definition is given by the full intra-cranial + % volume. However, this have to include the cerebellum and + % brainstem as well and needs to utilize the Yp0 map! + %{ + GIhullmodel = cfg_menu; + GIhullmodel.name = 'Hull model'; + GIhullmodel.tag = 'GIhullmodel'; + GIhullmodel.labels = {'Hemisphere-based','Skull-based'}; + GIhullmodel.values = {0,1}; + GIhullmodel.val = {0}; + GIhullmodel.help = {'There are two different hull definitions: (i) the classical using a semi-convex hull for each hemisphere and (ii) the full intracranial volume with both hemispheres and the cerebellum. ' ''}; + %} + + % core model + GIcoremodel = cfg_menu; + GIcoremodel.name = 'Core model'; + GIcoremodel.tag = 'GIcoremodel'; + GIcoremodel.labels = {'1','2','3'}; + GIcoremodel.values = {1,2,3}; + GIcoremodel.val = {1}; + GIcoremodel.help = {[ ... + 'There are multiple ways to define the central core of the brain structure and it is unclear which one fits best. ' ... + 'It should have some anatomical meaning (so the ventricles would be nice as source of cortical development) ' ... + 'but being at once independent of aging (so ventricles are not real good). ' ... + 'It should be defined on an individual level (to support the scaling/normalization of head size within and between species) ' ... + 'to remove rather than increasing individual effects. ' ... + ] '' }; + + % threshold for core estimation + %{ + GIcoreth = cfg_entry; + GIcoreth.name = 'Core threshold'; + GIcoreth.tag = 'GIcoreth'; + GIcoreth.strtype = 'r'; + GIcoreth.num = [1 1]; + GIcoreth.val = {0.2}; + GIcoreth.help = {[ ... + 'Lower thresholds remove less gyri whereas high thresholds remove more gyri depending on the used core model. ' ... + 'Initial test range between 0.05 (remove only very high frequency structures) and 0.25 (remove everything that is not close to the insula). ' ... + ] ''}; + %} + + % add own suffix to support multiple GI estimations + GIsuffix = cfg_entry; + GIsuffix.tag = 'GIsuffix'; + GIsuffix.name = 'Suffix'; + GIsuffix.strtype = 's'; + GIsuffix.num = [0 Inf]; + GIsuffix.val = {''}; + GIsuffix.help = {[ ... + 'Specify the string to be appended to the filenames of the filtered image file(s). ' ... + 'Default suffix is """".' ... + ... 'Use ""PARA"" to add input parameters, e.g. ""_lerr%1d_sacc%1d_fs%03d_smodel%d[_coreth%02d]"" with ... . ' + ] ''}; + + % main note + GIL = cfg_branch; + GIL.name = GILtype.name; + GIL.tag = GILtype.tag; + GIL.val = {GILtype,GIcoremodel,laplaceerr,GIstreamopt,GILfs,GIsuffix}; %GIhullmodel,,GIwritehull +end + +% RD202004 not required anymore because FS Tfs is now the default maybe again in furture +%{ +if expert + %% Thickness measures + Tfs = cfg_menu; + Tfs.name = 'Freesurfer thickness (Tfs)'; + Tfs.tag = 'Tfs'; + Tfs.labels = {'No','Yes'}; + Tfs.values = {0,1}; + Tfs.val = {0}; + Tfs.help = { + 'Freesurfer thickness metric: Tfs = mean( [ Tnear(IS) Tnear(OS) ] )' + }; + + Tmin = cfg_menu; + Tmin.name = 'Minimum thickness (Tmin)'; + Tmin.tag = 'Tmin'; + Tmin.labels = {'No','Yes'}; + Tmin.values = {0,1}; + Tmin.val = {0}; + Tmin.help = { + 'Minimum thickness metric: Tmin = min( [ Tnear(IS) Tnear(OS) ] )' + }; + + Tmax = cfg_menu; + Tmax.name = 'Maximum thickness (Tmax)'; + Tmax.tag = 'Tmax'; + Tmax.labels = {'No','Yes'}; + Tmax.values = {0,1}; + Tmax.val = {0}; + Tmax.help = { + 'Maximum thickness metric: Tmax = max( [ Tnear(IS) Tnear(OS) ] )' + 'This metric is only for error diagnostic!' + }; + + % main note + thickness = cfg_branch; + thickness.name = 'Additional thickness metrics'; + thickness.tag = 'thickness'; + thickness.val = {Tfs,Tmin,Tmax}; + thickness.help = { + 'For comparison of different thickness metrics in general see (MacDonalds et al. 1999, Lerch et al. 2005).' + ' Tnear .. closest point from a surface to another one' + ' Tnormal .. distance measured by following the surface normal (not really used)' + ' Tfs .. Freesurfer distance metric that is the mean of the Tnear metric of ' + ' (i) the white to the pial surface and (ii) the pial to the white surface (Fischl et al. 2000)' + ' Tpbt .. voxel-based thickness metrics (Dahnke et al., 2013)' + ' Tlaplacian .. Laplacian based thickness metric (Jones et al., 2000, Lerch et al. 2005)' + ' Tlink .. distance between surface with the same surface structure that is in general the result of a deformation' + ' Tmin .. minimum Tnear distance between two surfaces' + ' Tmax .. maximum Tnear distance between two surfaces' + }; +end +%} +% RD202004: writing of the pial and white will be also default soon but maybe some have older surface and need this function + + +%% Inner and outer surfaces +% ----------------------------------------------------------------- +OS = cfg_menu; +OS.name = 'Pial surface'; +OS.tag = 'OS'; +OS.labels = {'No','Yes'}; +OS.values = {0,1}; +OS.val = {0}; +OS.help = { + 'Creates the pial surface (outer cortical surface) by moving each vertices of the central surface by the half local thickness along the surface normal.' +}; + +IS = cfg_menu; +IS.name = 'White matter surface'; +IS.tag = 'IS'; +IS.labels = {'No','Yes'}; +IS.values = {0,1}; +IS.val = {0}; +IS.help = { + 'Creates the white matter surface (inner cortical surface) by moving each vertices of the central surface by the half local thickness along the surface normal.' +}; + +% main note +surfaces = cfg_branch; +surfaces.name = 'Additional surfaces'; +surfaces.tag = 'surfaces'; +surfaces.hidden = expert<1; +surfaces.val = {IS,OS}; + + +% Rachels fractal dimension by spherical harmonics +FD = cfg_menu; +FD.name = 'Cortical complexity (fractal dimension)'; +FD.tag = 'FD'; +FD.labels = {'No','Yes'}; +FD.values = {0,1}; +FD.val = {0}; +FD.help = { + 'Extract cortical complexity (fractal dimension) which is described in Yotter et al. Neuroimage, 56(3): 961-973, 2011.' + '' + 'Warning: Estimation of cortical complexity is very slow!' + '' +}; + + +% sulcal depth with a hull surface that based on surface-inflation. +% ADD cite! - VanEssen? +SD = cfg_menu; +SD.name = 'Sulcus depth'; +SD.tag = 'SD'; +SD.val = {1}; +SD.help = { + 'Extract sulcus depth based on the euclidean distance between the central surface and its convex hull.' + '' + 'In addition, sulcal depth can be transformed with sqrt-function to render the data more normally distributed, which is the recommended option for further statistical analysis.' + '' +}; +SD.labels = {'No','Sulcal depth','Sulcal depth (transformed with sqrt)'}; +SD.values = {0,1,2}; + + +% affine normalized measures +if expert>1 + tGI = cfg_entry; + tGI.name = 'Surface ratio (Toro''s gyrification index)'; + tGI.tag = 'tGI'; + tGI.strtype = 'r'; + tGI.num = [1 inf]; + tGI.val = {0}; + tGI.hidden = expert<1; + tGI.help = { + 'Toro''s gyrification index (#toroGI) based on local degree of folding through the surface ratio with definable radii. The original method is described in Toro et al., 2008.' + }; +else + tGI = cfg_menu; + tGI.name = 'Toro''s gyrification index (surface ratio)'; + tGI.tag = 'tGI'; + tGI.labels = {'No','Yes'}; + tGI.values = {0,1}; + tGI.val = {0}; + tGI.help = { + 'Toro''s gyrification index (#toroGI) based on local degree of folding through the surface ratio. The original method is described in Toro et al., 2008.' + }; +end + +lGI = cfg_menu; +lGI.name = 'Schaer''s local gyrification index (lGI)'; +lGI.tag = 'lGI'; +lGI.labels = {'No','Yes'}; +lGI.values = {0,1}; +lGI.val = {0}; +lGI.hidden = expert<2; +lGI.help = { + 'Marie Schaer''s local gyrification index from the FreeSurfer package. The original method is described in Schaer et al., 2008.' + 'The function is only for internal comparisons and requires modification in cat_surf_resamp and other functions.' +}; + +FS_HOME = cfg_files; +FS_HOME.tag = 'FS_HOME'; +FS_HOME.name = 'FreeSurfer home directory'; +FS_HOME.filter = 'dir'; +FS_HOME.ufilter = ''; +FS_HOME.num = [0 1]; +FS_HOME.hidden = expert<2; +FS_HOME.help = {'Select the FreeSurfer home directory.'}; + + + +% surface area +area = cfg_menu; +area.name = 'Surface area'; +area.tag = 'area'; +area.labels = {'No','Yes'}; +area.values = {0,1}; +area.val = {0}; +area.hidden = expert<2; +area.help = { + 'WARNING: IN DEVELOPMENT!' + 'This method requires a sum-based mapping rather than the mean-based interpolation. The mapping utilize the Delaunay graph to transfer the area around a vertex to its nearest neighbor(s). See Winkler et al., 2017. '}; +%{ +% Winklers method is not implemented right now (201904) +area.help = { + 'Extract log10-transformed local surface area using re-parameterized tetrahedral surface. The method is described in Winkler et al. NeuroImage, 61: 1428-1443, 2012.' + '' + 'Log-transformation is used to render the data more normally distributed.' + '' +}; +%} + +gmv = cfg_menu; +gmv.name = 'Surface GM volume'; +gmv.tag = 'gmv'; +gmv.labels = {'No','Yes'}; +gmv.values = {0,1}; +gmv.val = {0}; +gmv.hidden = expert<2; +gmv.help = { + 'WARNING: NOT WORKING RIGHT NOW!' + 'This method requires a sum-based mapping rather than the mean-based interpolation. The mapping utilize the Delaunay graph to transfer the area around a vertex to its closes neighbor(s) that is also use for the area mapping. '}; + + +% Normalization is relevant for most measures to be scaling-invariant. +% It is also required for the GI because they use a closing to create +% the hull. +% However, even with normalization we have to correct for TIV because +% larger brain have probably a different folding pattern (more folding). +% The different measures further requires log10-log10 normalization +% (allometrie) that also improves their distribution (more Gaussian like) +norm = cfg_menu; +norm.name = 'Measure normalization'; +norm.tag = 'norm'; +norm.hidden = expert<1; +norm.help = { + ['It is important to use TIV as confound in all analysis because even the measure or surface is normalized there is still a non-linear difference between smaller an larger brain (Im et al. 2008)! ' ... + 'Moreover, these biological measurements grow with different exponential factors and requires an allometric scaling by log10! ' ... + 'The measure normalization is only a technical aspect of ""equal"" (relativ vs. absolute) measurements! '] + '' + ['Complexity is in general measured in relation to the size of the structure (see also fractal dimensions). '... + 'I.e., if we compare the shape of an peach and melons we have to adapt/scale the measure by the size of the fruit or we have to normalize(scale the size of the fruit. ' ... + 'For normalization we can use measurements in 1D (e.g., average distance to the center of mass), 2D (total surface area), or 3D (total surface volume). ' ... + 'To avoid further side effects by folding, we can use the convex hull surface rather than the folded surface. ' ... + 'For brains, the convex hull is very close to the total intracranial volume (TIV) that we use in voxel-based morphometrie. ' ... + 'However, the segmentation-based TIV is not used here to use only surface-definied measures. ' ... + 'For scaling the 2D and 3D measures has to be transformed to a 1D values, where we use the spherical area/volume equation for estimation of the radius. ' ... + 'The radius is further normalized by a factor of ... to obtain an average brain size that is expected by most folding measures that use for instance a sphere for local estimation. '] + }; +% I prepared the full menu for possible tests but currently I miss the +% time and would only focus on the 31 that performed best in theory but +% also some small global tests compared to the TIV. +if expert>2 + norm.labels = {'No',... + 'Surface to COM distance (10)','Hull to COM distance (11)', ... + 'Total surface area (20)','Total hull area (21)', ... + 'Total surface volume (30)','Total hull volume (31)'}; + norm.values = {0, 10,11, 20,21, 30,31}; + norm.val = {31}; + norm.help = [norm.help; { + 'Further options for tests and evaluation.' + }]; +else + norm.labels = {'No','Yes'}; + norm.values = {0,1}; + norm.val = {0}; +end + + + %{ + % this should be better part of cat resample and smooth + log = cfg_menu; + log.name = 'Allometric normalization (log10)'; + log.tag = 'log'; + log.labels = {'No','Yes'}; + log.values = {0,1}; + log.val = {1}; + log.help = { + '' + }; + %} + +lazy.hidden = expert<1; + +% main menu +% +% TODO: +% - add a branch for measures? - no, keep it simple +% - add a branch for options? - no, keep it simple +surfextract = cfg_exbranch; +surfextract.tag = 'surfextract'; +surfextract.name = 'Extract additional surface parameters'; +surfextract.val = {data_surf_extract, ... + area,gmv, ... developer + GI, SD, FD, ... + tGI, ... + lGI, GIL, ... developer + surfaces, norm, ... expert + FS_HOME, ... + nproc, ... + lazy}; % expert +surfextract.prog = @cat_surf_parameters; +surfextract.vout = @vout_surfextract; +surfextract.help = {'Additional surface parameters can be extracted that can be used for statistical analysis.'}; + +%========================================================================== +function renderresults = cat_surf_results_GUI(expert) +%% Batch mode for cat_surf_results function. +% --------------------------------------------------------------------- + +% input data +cdata = cfg_files; +cdata.tag = 'cdata'; +cdata.name = 'Result files'; +cdata.filter = 'any'; +cdata.ufilter = '.*'; +cdata.num = [1 Inf]; +cdata.help = {'Select data for surface overlay. ' ''}; + + +% == render options == +surface = cfg_menu; +surface.name = 'Render surface'; +surface.tag = 'surface'; +surface.labels = {'Central','Inflated','Dartel','Flatmap'}; +surface.values = {1,2,3,4}; +surface.val = {1}; +surface.help = {'Select on which average surface the data should be projected. ' ''}; + +texture = cfg_menu; +texture.name = 'Surface underlay texture'; +texture.tag = 'texture'; +texture.labels = {'Mean curvature', 'Sulcal depth'}; +texture.values = {1,2}; +texture.val = {1}; +texture.help = {'Select a underlaying surface texture to illustrate the cortical folding pattern by mean curvature or sulcal depth.' ''}; + +transparency = cfg_menu; +transparency.name = 'Transparency'; +transparency.tag = 'transparency'; +transparency.labels = {'No', 'Yes'}; +transparency.values = {0,1}; +transparency.val = {1}; +transparency.help = {'Select a underlaying surface texture to illustrate the cortical folding pattern by mean curvature or sulcal depth.' ''}; + +view = cfg_menu; +view.name = 'Render view'; +view.tag = 'view'; +view.labels = {'Show top view', 'Show bottom view', 'Show only lateral and medial views'}; +view.values = {1,-1,2}; +view.val = {1}; +view.help = {'Select different types of surface views. The ""top view""/""bottom view"" shows later and medial view of the left and right hemisphere and the top/bottom view in middle. The view option has no effect in case of flatmaps.' ''}; + +colormap = cfg_menu; +colormap.name = 'Colormap'; +colormap.tag = 'colormap'; +colormap.labels = {'Jet', 'Hot', 'HSV', 'Cold-hot'}; +colormap.values = {1,2,3,4}; +colormap.val = {1}; +colormap.help = {'Select the colormap for data visualization.' ''}; + +colorbar = cfg_menu; +colorbar.name = 'Colorbar'; +colorbar.tag = 'colorbar'; +if expert>1 + colorbar.labels = {'Off', 'On', 'On with histogram'}; + colorbar.values = {0,1,2}; +else + colorbar.labels = {'Off', 'On'}; + colorbar.values = {0,1}; +end +colorbar.val = {1}; +colorbar.help = {'Print colorbar (with histogram).' ''}; + +background = cfg_menu; +background.name = 'Background color'; +background.tag = 'background'; +background.labels = {'White','Black'}; +background.values = {1,2}; +background.val = {1}; +background.help = {'Select the color of the background.' ''}; + +showfilename = cfg_menu; +showfilename.name = 'Show filename'; +showfilename.tag = 'showfilename'; +showfilename.labels = {'No','Yes'}; +showfilename.values = {0,1}; +showfilename.val = {1}; +showfilename.help = {'Print the filename at the top of the left and right hemisphere.' ''}; + +invcolormap = cfg_menu; +invcolormap.name = 'Inverse colormap'; +invcolormap.tag = 'invcolormap'; +invcolormap.labels = {'No','Yes'}; +invcolormap.values = {0,1}; +invcolormap.val = {0}; +invcolormap.help = {'Use inverse colormap.' ''}; + +clims = cfg_menu; +clims.name = 'Data range'; +clims.tag = 'clims'; +clims.labels = {'default','MSD2','MSD4','MSD8','SD2','SD4','SD8','%99.5','%99','min-max','0-max'}; +clims.values = {'','MSD2','MSD4','MSD8','SD2','SD4','SD8','%99.5','%99','min-max','0-max'}; +clims.val = {''}; +clims.hidden = expert<2; +clims.help = {'Define normalized datarange' ''}; + +% ... not working ... colorbar, +render = cfg_exbranch; +render.tag = 'render'; +render.name = 'Render options'; +render.val = {surface,view,texture,transparency,colormap,invcolormap,background,clims,showfilename}; +render.prog = @cat_surf_results; +render.help = {'Rendering options for the surface output.'}; + + +% == stat == +threshold = cfg_menu; +threshold.name = 'Threshold'; +threshold.tag = 'threshold'; +threshold.labels = {'No threshold', 'P<0.05', 'P<0.01', 'P<0.001'}; +threshold.values = {0,-log10(0.05),2,3}; +threshold.val = {0}; +threshold.help = {'Define the threshold of statistical maps.' ''}; + +hideNegRes = cfg_menu; +hideNegRes.name = 'Hide negative results'; +hideNegRes.tag = 'hide_neg'; +hideNegRes.labels = {'No','Yes'}; +hideNegRes.values = {0,1}; +hideNegRes.val = {0}; +hideNegRes.help = {'Do not show negative results.' ''}; + +stat = cfg_exbranch; +stat.tag = 'stat'; +stat.name = 'Statistical options'; +stat.val = {threshold,hideNegRes}; +stat.prog = @cat_surf_results; +stat.help = {'Additional options for statistical maps.'}; + + +% == filename == +outdir = cfg_files; +outdir.tag = 'outdir'; +outdir.name = 'Output directory'; +outdir.filter = 'dir'; +outdir.ufilter = '.*'; +outdir.num = [0 1]; +outdir.help = {'Select a directory where files are written. Empty writes in the directory of the input files.' ''}; +outdir.val{1} = {''}; + +prefix = cfg_entry; +prefix.tag = 'prefix'; +prefix.name = 'Filename prefix'; +prefix.strtype = 's'; +prefix.num = [0 Inf]; +prefix.val = {'render_'}; +prefix.help = {'Specify the string to be prepended to the filenames of the filtered image file(s). Default prefix is """".' ''}; + +suffix = cfg_entry; +suffix.tag = 'suffix'; +suffix.name = 'Filename suffix'; +suffix.strtype = 's'; +suffix.num = [0 Inf]; +suffix.val = {''}; +suffix.help = {'Specify the string to be appended to the filenames of the filtered image file(s). Default suffix is """".' ''}; + +fparts = cfg_exbranch; +fparts.tag = 'fparts'; +fparts.name = 'Filename'; +fparts.val = {outdir,prefix,suffix}; +fparts.prog = @cat_surf_results; +fparts.help = {'Define output directory and prefix and suffix.'}; + + +% == main == +renderresults = cfg_exbranch; +renderresults.tag = 'renderresults'; +renderresults.name = 'Render result data'; +renderresults.val = {cdata,render,stat,fparts}; +renderresults.prog = @(job) cat_surf_results('batch',job); +renderresults.vout = @(job) vout_cat_surf_results(job); +renderresults.help = {'CAT result render function for automatic result image export.' ''}; + +%========================================================================== +% dependency functions +%========================================================================== +function dep = vout_vol2surf(job) +%% + +if isfield(job,'merge_hemi') && job.merge_hemi + dep(1) = cfg_dep; + dep(1).sname = 'Mapped values'; + dep(1).src_output = substruct('.','mesh'); + dep(1).tgt_spec = cfg_findspec({{'filter','mesh','strtype','e'}}); +else + dep(1) = cfg_dep; + dep(1).sname = 'Left mapped values'; + dep(1).src_output = substruct('.','lh'); + dep(1).tgt_spec = cfg_findspec({{'filter','mesh','strtype','e'}}); + dep(2) = cfg_dep; + dep(2).sname = 'Right mapped values'; + dep(2).src_output = substruct('.','rh'); + dep(2).tgt_spec = cfg_findspec({{'filter','mesh','strtype','e'}}); +end + +%========================================================================== +function dep = vout_cat_surf_results(varargin) +%% + +dep(1) = cfg_dep; +dep(1).sname = 'Rendered surface data'; +dep(1).src_output = substruct('()',{1},'.','png','()',{':'}); +dep(1).tgt_spec = cfg_findspec({{'filter','any','strtype','e'}}); + +%========================================================================== +function dep = vout_cat_surf_vx2surf(job) + +job.createDEPs = 1; +out = cat_surf_vx2surf(job); + +dep = cfg_dep; +for mi = 1:numel(out.measures) + dep(mi) = cfg_dep; + dep(mi).sname = out.measures(mi).name; + dep(mi).src_output = substruct('.','measures','()',{mi},'.','files','()',{':'}); + dep(mi).tgt_spec = cfg_findspec({{'filter','any','strtype','e'}}); +end + + +%========================================================================== +function dep = vout_surfextract(job) + +measures = { % para-field , para-subfield , para-val , output-var, [left|right] dep-var-name +'GI' '' [1 3] 'GI' 'MNI gyrification'; % fast AMC on original surface +'GI' '' [2 3] 'GIp' 'Pong gyrification'; % accurate AMC on scaled surface +... +'FD' '' 1 'FD' 'fractal dimension'; +... +'SD' '' 1 'SD' 'sulcal depth'; +... +'tGI' '' 1 'tGI20mm' 'Toro GI 20 mm'; % original Toro approach with 20 mm +'tGI' '' -1 'tGIa' 'Toro GI adaptive'; % Toro GI with variable radius +'tGI' '' [] 'tGI%02dmm' 'Toro GI %d mm'; % mutliple input that replace %d +... +'lGI' '' 1 'lGI' 'Schaer''s lGI'; +... +'GIL' '' [1 4] 'iGI' 'inward-folding Laplacian-based GI'; +'GIL' '' [2 4] 'oGI' 'outward-folding Laplacian-based GI'; +'GIL' '' [3 4] 'gGI' 'generalized Laplacian-based GI'; +... +'area' '' 1 'area' 'surface area'; +... +'gmv' '' [1 3] 'gmv' 'surface GM volume'; +'gmv' '' [2 3] 'gmvp' 'projected GM volume'; +... +'surfaces' 'IS' 1 'white' 'white matter surface'; +'surfaces' 'OS' 1 'pial' 'pial surface'; +...'GIL' 'hull' [1 3] 'hull' 'hull surface'; +...'GIL' 'core' [2 3] 'core' 'core surface'; +}; +sides = { +'l' 'Left'; +...'r' 'Right'; +}; +if isfield(job,'tGI') + if any(isinf(job.tGI)), job.tGI(isinf(job.tGI)) = -1; end + job.tGI = unique(job.tGI); +end + +for si=1:size(sides,1) +for mi=1:size(measures,1) + if isfield(job,measures{mi,1}) && ... + (strcmp(measures{mi,2},'hull') || strcmp(measures{mi,2},'core')) && ... + isfield(job.(measures{mi,1}),'GIwritehull') && job.(measures{mi,1}).GIwritehull + % special case for the hull and core surface due to the write field + if any( job.(measures{mi,1}).(measures{mi,1}) == measures{mi,3} ) + if ~exist('dep','var'), dep = cfg_dep; else, dep(end+1) = cfg_dep; end %#ok + dep(end).sname = [sides{si,2} ' ' measures{mi,5}]; + dep(end).src_output = substruct('()',{1}, '.',[sides{si,1} 'P' measures{mi,4}],'()',{':'}); + dep(end).tgt_spec = cfg_findspec({{'filter','any','strtype','e'}}); + end + elseif isfield(job,measures{mi,1}) && strcmp(measures{mi,1},'tGI') && isempty(measures{mi,3}) + % special case for the hull and core surface due to the write field + for ti = 1:numel(job.(measures{mi,1})) + if job.(measures{mi,1})(ti)>1 + if ~exist('dep','var'), dep = cfg_dep; else, dep(end+1) = cfg_dep; end %#ok + dep(end).sname = [sides{si,2} ' ' sprintf( measures{mi,5} , job.(measures{mi,1})(ti) ) ]; + dep(end).src_output = substruct('()',{1}, '.',sprintf( [sides{si,1} 'P' measures{mi,4}] , job.(measures{mi,1})(ti)),'()',{':'}); + dep(end).tgt_spec = cfg_findspec({{'filter','any','strtype','e'}}); + end + end + else + if isfield(job,measures{mi,1}) && ~(strcmp(measures{mi,2},'hull') || strcmp(measures{mi,2},'core')) + if isnumeric( job.(measures{mi,1}) ) && isempty( measures{mi,3} ) % Multiple input + for mii = 1:numel( job.(measures{mi,1}) ) + if job.(measures{mi,1})(mii)>1 + if ~exist('dep','var'), dep = cfg_dep; else, dep(end+1) = cfg_dep; end %#ok + dep(end).sname = [sides{si,2} ' ' sprintf( measures{mi,5}, job.(measures{mi,1})(mii) ) ]; + dep(end).src_output = substruct('()',{1}, '.',[sides{si,1} 'P' sprintf(measures{mi,4}, job.(measures{mi,1})(mii))],'()',{':'}); + dep(end).tgt_spec = cfg_findspec({{'filter','any','strtype','e'}}); + end + end + elseif ( ( isnumeric( job.(measures{mi,1}) ) && any( job.(measures{mi,1})==measures{mi,3} ) ) || ... % no subfield + ( isfield(job.(measures{mi,1}),measures{mi,1}) && any( job.(measures{mi,1}).(measures{mi,1})==measures{mi,3} ) ) || ... % with same subfield - GI dev. mode + ( isfield(job.(measures{mi,1}),measures{mi,2}) && any( job.(measures{mi,1}).(measures{mi,2})==measures{mi,3} ) ) ) % with other subfield + if ~exist('dep','var'), dep = cfg_dep; else, dep(end+1) = cfg_dep; end %#ok + dep(end).sname = [sides{si,2} ' ' measures{mi,5}]; + dep(end).src_output = substruct('()',{1}, '.',[sides{si,1} 'P' measures{mi,4}],'()',{':'}); + dep(end).tgt_spec = cfg_findspec({{'filter','any','strtype','e'}}); + end + end + end +end +end +if ~exist('dep','var'), dep = cfg_dep; end + +%========================================================================== +function dep = vout_surf_surf2roi(job) %#ok + +dep(1) = cfg_dep; +dep(1).sname = 'Extracted Surface ROIs'; +dep(1).src_output = substruct('()',{1}, '.','xmlname','()',{':'}); +dep(1).tgt_spec = cfg_findspec({{'filter','xml','strtype','e'}}); + +%========================================================================== +function dep = vout_surf_resamp(job) + +if isfield(job,'sample') && isfield(job,'data_surf_mixed') +if isfield(job,'sample') + if isfield(job,'data_surf') + job.data_surf = [job.sample.data_surf_mixed]; + else + job.data_surf = {''}; + end +end +% simple version with mixed input +dep = cfg_dep; +if job.merge_hemi + dep(end).sname = 'Merged resampled'; + dep(end).src_output = substruct('.','sample','()',{1},'.','Psdata'); %,'()',{':'}); + dep(end).tgt_spec = cfg_findspec({{'filter','gifti','strtype','e'}}); +else + dep(end).sname = 'Left resampled'; + dep(end).src_output = substruct('.','sample','()',{1},'.','lPsdata'); %,'()',{':'}); + dep(end).tgt_spec = cfg_findspec({{'filter','gifti','strtype','e'}}); +end +else +if isfield(job,'sample') + if isfield(job,'data_surf') + job.data_surf = [job.sample.data_surf]; + else + job.data_surf = {''}; + end +end +% First we have to catch possible dependency definition problems. +if 0 % RD202211: should be ok to allow it and also a warning is not really required + % if isobject(job.data_surf) && numel(job.data_surf)>1 % simple file input + error('cat_surf_resamp:FileDepError',... + ['CAT resample and smooth support only one dependency per file input \n' ... + 'to support further separate processing. ']); +elseif iscell(job.data_surf) + nDEP = zeros(numel(job.data_surf)); + for i = 1:numel(job.data_surf) + if isobject(job.data_surf{i}) && numel(job.data_surf{i})>1 + nDEP(i) = numel(job.data_surf{i}); + end + end + msg = ['The CAT batch ""Resample and Smooth Surface Data"" supports only one \n' ... + 'dependency per input sample to support further separate processing. ']; + for i = 1:numel(job.data_surf) + if nDEP(i)>1 + msg = [msg sprintf('\n Sample %d has %d dependencies.',i,nDEP(i))]; %#ok + end + end + if sum(nDEP)>0 + error('cat_surf_resamp:SampleDepError',msg); + end +end + +%% here we have to extract the texture name to have useful output names +mname = repmat({''},1,numel(job.data_surf)); +if isobject(job.data_surf) + sep = strfind(job.data_surf(1).sname,':'); + if numel(job.data_surf) > 1 + mname{1} = [ job.data_surf(1).sname 'multiple measures' ]; + else + mname{1} = spm_str_manip( cat_io_strrep( job.data_surf.sname(sep+1:end) , {' ','Left'} ,{'' ''}) ); + end +elseif iscell(job.data_surf) + for i=1:numel(job.data_surf) + if isobject(job.data_surf{i}) + sep = strfind(job.data_surf{i}.sname,':'); + mname{i} = spm_str_manip( cat_io_strrep( job.data_surf{i}.sname(sep+1:end) , {' ','Left'} ,{'' ''}) ); + else + sinfo = cat_surf_info(job.data_surf{i}); + mname{1} = sinfo.texture; + end + end +% else is empty initialization +end + +%% +if iscell(job.data_surf) && ( iscell( job.data_surf{1} ) || isobject(job.data_surf{1} ) ) +% this differentiation is important otherwise it has problemes with cellstrings + for di = 1:numel(job.data_surf) + if ~exist('dep','var'), dep = cfg_dep; else, dep(end+1) = cfg_dep; end %#ok + if job.merge_hemi + dep(end).sname = ['Merged resampled ' mname{di}]; + dep(end).src_output = substruct('.','sample','()',{di},'.','Psdata'); %,'()',{':'}); + dep(end).tgt_spec = cfg_findspec({{'filter','gifti','strtype','e'}}); + else + dep(end).sname = ['Left resampled ' mname{di}]; + dep(end).src_output = substruct('.','sample','()',{di},'.','lPsdata'); %,'()',{':'}); + dep(end).tgt_spec = cfg_findspec({{'filter','gifti','strtype','e'}}); + end + end +else % file input - just one texture type + dep = cfg_dep; + if job.merge_hemi + dep(end).sname = ['Merged resampled ' mname{1}]; + dep(end).src_output = substruct('.','sample','()',{1},'.','Psdata'); %,'()',{':'}); + dep(end).tgt_spec = cfg_findspec({{'filter','gifti','strtype','e'}}); + else + dep(end).sname = ['Left resampled ' mname{1}]; + dep(end).src_output = substruct('.','sample','()',{1},'.','lPsdata'); %,'()',{':'}); + dep(end).tgt_spec = cfg_findspec({{'filter','gifti','strtype','e'}}); + end +end +end +%========================================================================== +function dep = vout_cat_surf_calc(job) +% improve data description +if isobject(job.cdata) + % extract dependency information + ni = find(job.cdata.sname==':',1,'first'); + if ~isempty(ni) + ni = ni + find(job.cdata.sname(ni+1:end)~=' ',1,'first'); + depsfnames = ['S=' job.cdata.sname(ni:end) '; ' job.expression]; + end +else + % direct input + depsfnames = job.expression; +end + +% create new dependency object +dep(1) = cfg_dep; +dep(1).sname = depsfnames; +dep(1).src_output = substruct('()',{1}, '.','output','()',{':'}); +dep(1).tgt_spec = cfg_findspec({{'filter','gifti','strtype','e'}}); + +%========================================================================== +function dep = vout_cat_surf_calcsub(job) +depsfnames = job.expression; + +for di = 1:numel(job.cdata) + + % extract dependency information + if isobject(job.cdata{di}) + ni = find(job.cdata{di}.sname==':',1,'first'); + if ~isempty(ni) + ni = ni + find(job.cdata{di}.sname(ni+1:end)~=' ',1,'first'); + depsfnames = ['S=' job.cdata{di}.sname(ni:end) '; ' job.expression]; + end + else + % direct input + depsfnames = job.expression; + end + + % create new dependency object + if ~exist('dep','var'), dep = cfg_dep; else, dep(end+1) = cfg_dep; end %#ok + dep(end).sname = depsfnames; + dep(end).src_output = substruct('()',{1}, '.','output','()',{di}); + dep(end).tgt_spec = cfg_findspec({{'filter','gifti','strtype','e'}}); +end + + +%========================================================================== +function dep = vout_cat_surf_flipsides(varargin) + + +dep(1) = cfg_dep; +dep(1).sname = 'Flipside'; +dep(1).src_output = substruct('()',{1}, '.','files','()',{':'}); +dep(1).tgt_spec = cfg_findspec({{'filter','gifti','strtype','e'}}); + +%========================================================================== +function dep = vout_cat_stat_spm(varargin) +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'}}); + +% further files? + +%========================================================================== +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_vol_genus0.m",".m","935","25","%CAT_VOL_GENUS0 Topology adjusted isosurface extractor. +% Topology optimized marching cubes surface creation for an existing volume +% Y and a treshold th. Also outputs the topology adjusted volume Yc. +% +% [Yc,faces,vertices] = cat_vol_genus0(Y,th[,notadjust]); +% +% Yc .. topolocy adjusted volume +% faces .. surface faces +% vertices .. surface vertices +% Y .. input volume as single datatype +% th .. threshold used for input volume Y +% notadjust .. no topology adjustment +% +% To avoid output use the MATLAB EVALC function. +% +% See also ISOSURFACE, EVALC, compile. +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_surf_info.m",".m","22534","582","function [varargout] = cat_surf_info(P,readsurf,gui,verb,useavg) +% ______________________________________________________________________ +% Extact surface information from filename. +% +% sinfo = cat_surf_info(P,readsurf,gui,verb) +% +% P .. surface filename +% readsurf .. read gifti or Freesurfer file to get more information +% gui .. interactive hemisphere selection +% verb .. verbose +% +% sinfo(i). +% fname .. full filename +% pp .. filepath +% ff .. filename +% ee .. filetype +% exist .. exist file? +% fdata .. structure from dir command +% ftype .. filetype [0=no surface,1=gifti,2=freesurfer] +% statready .. ready for statistic (^s#.*.gii) [0|1] +% side .. hemisphere [lh|rh|lc|rc|mesh] +% name .. subject/template name +% datatype .. [-1=unknown|0=nosurf|1=mesh|2=data|3=surf] +% only defined for readsurf==1 and surf=mesh+sidata +% dataname .. datafieldname [central|thickness|intensity...] +% texture .. textureclass [central|sphere|thickness|...] +% label .. labelmap +% resampled .. resampled data [0|1] +% template .. template or individual mesh [0|1] +% name .. name of the dataset +% roi .. roi data +% nvertices .. number vertices +% nfaces .. number faces +% Pmesh .. underlying meshfile +% Psphere .. sphere mesh +% Pspherereg.. registered sphere mesh +% Pdefects .. topology defects mesh +% Pdata .. datafile +% preside .. prefix before hemi info (i.e. after smoothing) +% posside .. string after hemi info +% smoothed .. smoothing size +% Phull .. convex hull mesh +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +%#ok<*RGXP1> + + if ~exist('P','var'), P=''; end + if ~exist('useavg','var'), useavg=1; end + if strcmp(P,'selftest') + pps = { + fullfile(fileparts(mfilename('fullpath')),'templates_surfaces') + fullfile('User','08.15','T1 T2','subs','mri') + }; + ffs = { + 'lh.central.freesurfer' + 'lh.mymask' + 'output' + 'lh.texture.sub1.sub2' + 'lh.tex1.tex2.resampled.sub1.sub2' + '08.15' + 's15mm.lh.tex03.33.resampled.S01.mri' + 's5mm.lh.t1.t2-3_3.resampled.S01_-.kdk.mri' + 'rh.s33mmtexture.S01.native.mri' + 'rh' + 'rh.' + 'rh.sphere.reg.sub1' + 'rc.defects.038.37.477' + 'lc.s33mmtexture.S01.native.mri' + 'rc.texture.sub1.sub2' + }; + ees = { + '' + ... '.gii' + ... '.annot' + }; + varargout = cell(numel(pps),numel(ffs),numel(ees)); + for ppsi = 1:numel(pps) + for ffsi = 1:numel(ffs) + for eesi = 1:numel(ees) + varargout{1}(ppsi,ffsi,eesi) = cat_surf_info(fullfile(pps{ppsi},[ffs{ffsi} ees{eesi}]),0,0,1); + end + end + end + return; + end + + + + if nargin<2, readsurf = 0; end + if nargin<3, gui = 0; end + if nargin<4, verb = 0; end + + P = cellstr(P); + + sinfo = struct(... + 'fname','',... % full filename + 'pp','',... % filepath + 'ff','',... % filename + 'ee','',... % filetype + 'exist','',... % exist + 'fdata','',... % datainfo (filesize) + 'ftype','',... % filetype [0=no surface,1=gifti,2=freesurfer] + 'statready',0,... % ready for statistic (^s#.*.gii) + 'side','',... % hemishphere + 'name','',... % subject/template name + 'datatype','',... % datatype [0=nosurf/file|1=mesh|2=data|3=surf] with surf=mesh+data + 'dataname','',... % datafieldname [central|thickness|s3thickness...] + 'texture','',... % textureclass [central|sphere|thickness|...] + 'label','',... % labelmap + 'resampled','',... % dataspace + 'resampled_32k','',... + 'template','',... % individual surface or tempalte + 'roi','',... % roi data + 'nvertices',[],... % number vertices + 'nfaces',[],... % number faces + 'Pmesh','',... % meshfile + 'Psphere','',... % meshfile + 'Pspherereg','',... % meshfile + 'Pdefects','',... % meshfile + 'Ppial','',... % meshfile + 'Pwhite','',... % meshfile + 'Player4','',... % meshfile + 'Pdata','',... % datafile + 'preside','', ... + 'posside','' ... + ); + + if isempty(P{1}), varargout{1}=sinfo; return; end + + for i=1:numel(P) + [pp,ff,ee] = spm_fileparts(P{i}); + if strcmp(ee,'.dat') + P{i} = spm_file(P{i},'ext','.gii'); + end + sinfo(i).fdata = dir(P{i}); + + sinfo(i).fname = P{i}; + sinfo(i).exist = exist(P{i},'file') > 0; + sinfo(i).pp = pp; + switch ee + case {'.xml','.txt','.html','.csv'} + sinfo(i).ff = ff; + sinfo(i).ee = ee; + sinfo(i).ftype = 0; + continue + case '.gii' + sinfo(i).ff = ff; + sinfo(i).ee = ee; + sinfo(i).ftype = 1; + if sinfo(i).exist && readsurf + S = gifti(P{i}); + end + case '.annot' + sinfo(i).ff = ff; + sinfo(i).ee = ee; + sinfo(i).ftype = 1; + sinfo(i).label = 1; + if sinfo(i).exist && readsurf + clear S; + try + S = cat_io_FreeSurfer('read_annotation',P{1}); + catch + cat_io_cprintf('warn',sprintf('Warning: Error while reading annotation file: \n %s\n',P{1})); + end + end + if exist('S','var') + sinfo(i).ftype = 2; + end + otherwise + sinfo(i).ff = [ff ee]; + sinfo(i).ee = ''; + sinfo(i).ftype = 0; + if sinfo(i).exist && readsurf + % this files are not specified by ending so we will just try to read something + clear S; + try %#ok + S = cat_io_FreeSurfer('read_surf',P{1}); + if ~isstruct(S) || ~isfield(S,'faces') || (size(S.faces,2)~=3 || size(S.faces,1)<10000) + clear S; + end + end + try %#ok + S.cdata = cat_io_FreeSurfer('read_surf_data',P{1}); + if size(S.face,2)==3 || size(S.face,1)<10000 + S = rmfield(S,'cdata'); + end + end + if ~exist('S','var') + cat_io_cprintf('warn',sprintf('Warning: Error while reading surface file: \n %s\n',P{1})); + end + end + if exist('S','var') + sinfo(i).ftype = 2; + end + end + + + noname = sinfo(i).ff; + + % smoothed data + sinfo(i).statready = ~isempty(regexp(noname,'^s(?\d+)\..*')); + + % side + if cat_io_contains(noname,'lh.'), sinfo(i).side='lh'; sidei = strfind(noname,'lh.'); + elseif cat_io_contains(noname,'rh.'), sinfo(i).side='rh'; sidei = strfind(noname,'rh.'); + elseif cat_io_contains(noname,'cb.'), sinfo(i).side='cb'; sidei = strfind(noname,'cb.'); + elseif cat_io_contains(noname,'mesh.'), sinfo(i).side='mesh'; sidei = strfind(noname,'mesh.'); + elseif cat_io_contains(noname,'lc.'), sinfo(i).side='lc'; sidei = strfind(noname,'lc.'); + elseif cat_io_contains(noname,'rc.'), sinfo(i).side='rc'; sidei = strfind(noname,'rc.'); + else + + % skip for volume files + if strcmp(ee,'.nii') + continue + end + + % if SPM.mat exist use that for side information + % Torben Lund Mail 20240409: issues with reading some SPM.mat files that did not include the right + if ~isempty(pp) && exist(fullfile(pp,'SPM.mat'),'file') + try %#ok + load(fullfile(pp,'SPM.mat'),'SPM'); % this will give a warning if the var SPM does not exist + end + if exist('SPM','var') + if isfield(SPM,'xY') && isfield (SPM.xY,'VY') && isfield(SPM.xY.VY(1),'fname') + [~,ff2] = spm_fileparts(SPM.xY.VY(1).fname); + + % find mesh string + hemi_ind = strfind(ff2,'mesh.'); + if ~isempty(hemi_ind) + sinfo(i).side = ff2(hemi_ind(1):hemi_ind(1)+3); + else + % find lh|rh string + hemi_ind = [strfind(ff2,'lh.') strfind(ff2,'rh.') strfind(ff2,'lc.') strfind(ff2,'rc.')]; + sinfo(i).side = ff2(hemi_ind(1):hemi_ind(1)+1); + end + + sidei = []; % handle this later + else + cat_io_cprintf('warn',sprintf('Warning: Error SPM.mat does not include required fields: \n %s\n',P{1})); + end + end + else + if gui + if cat_get_defaults('extopts.expertgui') + sinfo(i).side = spm_input('Hemisphere',1,'lh|rh|lc|rc|cb|mesh'); + else + sinfo(i).side = spm_input('Hemisphere',1,'lh|rh|mesh'); + end + else + sinfo(i).side = 'mesh'; + end + sidei = strfind(noname,[sinfo(i).side '.']); + end + end + if isempty(sidei), sidei = strfind(noname,sinfo(i).side); end + if sidei>0 + sinfo(i).preside = noname(1:sidei-1); + sinfo(i).posside = noname(sidei+numel(sinfo(i).side)+1:end); + else + sinfo(i).posside = noname; + end + + % smoothed + if isempty(sinfo(i).preside) + sinfo(i).smoothed = 0; + else + sinfo(i).smoothed = max([0,double(cell2mat(textscan(sinfo(i).preside,'s%dmm.')))]); + end + + % datatype + if sinfo(i).exist && readsurf + switch num2str([isfield(S,'vertices'),isfield(S,'cdata')],'%d%d') + case '00', sinfo(i).datatype = 0; + case '01', sinfo(i).datatype = 1; + case '10', sinfo(i).datatype = 2; + case '11', sinfo(i).datatype = 3; + end + else + sinfo(i).datatype = -1; + end + + + % resampled + sinfo(i).resampled = ~isempty(strfind(sinfo(i).posside,'.resampled')) && ... + isempty(strfind(sinfo(i).posside,'.resampled_32k')); + sinfo(i).resampled_32k = ~isempty(strfind(sinfo(i).posside,'.resampled_32k')); + % template + sinfo(i).template = cat_io_contains(lower(sinfo(1).ff),'.template'); + % CG20210226: This caused crashes in cat_surf_surf2roi.m for some files +% if sinfo(i).template, sinfo(i).resampled = 1; end + + + % name / texture + % ----------------------------------------------------------------- + % ... name extraction is a problem, because the name can include points + % and also the dataname / texture can include points ... + resi = [strfind(sinfo(i).posside,'template.'),... + strfind(sinfo(i).posside,'resampled.'),... + strfind(sinfo(i).posside,'resampled_32k.'),... + strfind(sinfo(i).posside,'sphere.reg.')]; + if ~isempty(resi) + sinfo(i).name = cat_io_strrep(sinfo(i).posside(max(resi):end),... + {'template.','resampled.','resampled_32k.','sphere.reg'},''); %sinfo(i).posside, + if ~isempty(sinfo(i).name) && sinfo(i).name(1)=='.', sinfo(i).name(1)=[]; end + sinfo(i).texture = sinfo(i).posside(1:min(resi)-2); + else + % without no template/resampled string + doti = strfind(sinfo(i).posside,'.'); + if numel(doti)==0 + % if not points exist that the string is the name + sinfo(i).name = ''; + sinfo(i).texture = sinfo(i).posside; + elseif isscalar(doti) + % if one point exist that the first string is the dataname and the second the subject name + sinfo(i).name = sinfo(i).posside(doti+1:end); + sinfo(i).texture = sinfo(i).posside(1:doti-1); + else + % this is bad + sinfo(i).name = sinfo(i).posside(min(doti)+1:end); + sinfo(i).texture = sinfo(i).posside(1:min(doti)-1); + end + end + if verb + fprintf('%50s: s%04.1f %2s ',sinfo(i).ff,sinfo(i).smoothed,sinfo(i).side); + cat_io_cprintf([0.2 0.2 0.8],'%15s',sinfo(i).texture); + cat_io_cprintf([0.0 0.5 0.2],'%15s',sinfo(i).name); + fprintf('%4s\n',sinfo(i).ee); + end + % dataname + sinfo(i).dataname = cat_io_strrep(sinfo(i).posside,{sinfo(i).name,'template.','resampled.','resampled_32k.'},''); + if ~isempty(sinfo(i).dataname) && sinfo(i).dataname(end)=='.', sinfo(i).dataname(end)=[]; end + + % if texture is empty use dataname, otherwise texture is more reliable and should + % be used instead of dataname + if isempty(sinfo(i).texture) + sinfo(i).texture = sinfo(i).dataname; + else + sinfo(i).dataname = sinfo(i).texture; + end + + % ROI + sinfo(i).roi = ~isempty(strfind(sinfo(i).posside,'.ROI')); + + + + % find Mesh and Data Files + % ----------------------------------------------------------------- + sinfo(i).Pmesh = ''; + sinfo(i).Pdata = ''; + % here we know that the gifti is a surf + if sinfo(i).statready + sinfo(i).Pmesh = sinfo(i).fname; + sinfo(i).Pdata = sinfo(i).fname; + end + % if we have read the gifti than we can check for the fields + if isempty(sinfo(i).Pmesh) && sinfo(i).exist && readsurf && isfield(S,'vertices') + sinfo(i).Pmesh = sinfo(i).fname; + end + if isempty(sinfo(i).Pdata) && sinfo(i).exist && readsurf && isfield(S,'cdata') + sinfo(i).Pdata = sinfo(i).fname; + end + + % check whether cdata field and mesh structure exist for gifti data + if strcmp(sinfo(i).ee,'.gii') && sinfo(i).exist && readsurf && (isempty(sinfo(i).Pdata) || isempty(sinfo(i).Pmesh)) + S = gifti(sinfo(i).fname); + if isfield(S,'cdata') && isfield(S,'faces') && isfield(S,'vertices') + sinfo(i).Pmesh = sinfo(i).fname; + sinfo(i).Pdata = sinfo(i).fname; + end + end + + % if the dataname is central we got a mesh or surf datafile + if isempty(sinfo(i).Pdata) || isempty(sinfo(i).Pmesh) + Pcentral = fullfile(sinfo(i).pp,[strrep(sinfo(i).ff,['.' sinfo(i).texture],'.central') sinfo(i).ee]); + switch sinfo(i).texture + %case {'defects'} % surf + % sinfo(i).Pmesh = sinfo(i).fname; + % sinfo(i).Pdata = sinfo(i).fname; + case {'central','white','pial','inner','outer','sphere','hull','core','layer4'} % only mesh + sinfo(i).Pmesh = sinfo(i).fname; + sinfo(i).Pdata = ''; + case {'pbt','thickness','thicknessfs','thicknessmin','thicknessmax',... + 'gyrification','frac','depth','sqrtdepth','GWMdepth','WMdepth','CSFdepth',... + 'depthWM','depthGWM','depthCSF','depthWMg','inwardGI','outwardGI','generalizedGI',... + 'area','defects','lGI','toroGI',... + 'intlayer4','intwhite','intpial',... + 'gyruswidth','gyruswidthWM','sulcuswidth'} % only thickness + sinfo(i).Pdata = sinfo(i).fname; + if strcmp(sinfo(i).ee,'.gii') && sinfo(i).ftype == 1 && exist(sinfo(i).fname,'file') + S = gifti(sinfo(i).fname); + if isfield(S,'vertices') && isfield(S,'faces') + sinfo(i).Pmesh = sinfo(i).fname; + end + end + Pcentral = fullfile(sinfo(i).pp,[strrep(sinfo(i).ff,['.' sinfo(i).texture],'.central') '.gii']); + if exist(Pcentral,'file') && ~useavg + sinfo(i).Pmesh = Pcentral; + end + otherwise + sinfo(i).Pdata =sinfo(i).fname; + if exist(Pcentral,'file') && ~useavg + sinfo(i).Pmesh = Pcentral; + elseif strcmp(sinfo(i).ee,'.gii') && sinfo(i).ftype == 1 && exist(sinfo(i).fname,'file') + S = gifti(sinfo(i).fname); + if isfield(S,'vertices') && isfield(S,'faces') + sinfo(i).Pmesh = sinfo(i).fname; + end + end + end + end + % if we still dont know what kind of datafile, we can try to find a + % mesh surface + if isempty(sinfo(i).Pmesh) + if strcmp(ee,'.gii') && isempty(sinfo(i).side) + sinfo(i).Pmesh = sinfo(i).fname; + sinfo(i).Pdata = sinfo(i).fname; + else + % template mesh handling !!! + Pmesh = char(cat_surf_rename(sinfo(i),'dataname','central','ee','.gii')); + if exist(Pmesh,'file') + sinfo(i).Pmesh = Pmesh; + sinfo(i).Pdata = sinfo(i).fname; + end + end + end + % if we got still no mesh than we can use SPM.mat information or average mesh + % ... + if isempty(sinfo(i).Pmesh) %&& sinfo(i).ftype==1 + try + if ischar(SPM.xVol.G) + % data or analysis moved or data are on a different computer? + if ~exist(SPM.xVol.G,'file') + [pp2,ff2,xx2] = spm_fileparts(SPM.xVol.G); + % rename old Template name from previous versions + ff2 = strrep(ff2,'Template_T1_IXI555_MNI152_GS',cat_get_defaults('extopts.shootingsurf')); + if cat_io_contains(ff2,'.central.freesurfer') || cat_io_contains(ff2,['.central.' cat_get_defaults('extopts.shootingsurf')]) + if cat_io_contains(pp2,'templates_surfaces_32k') + SPM.xVol.G = fullfile(fileparts(mfilename('fullpath')),'templates_surfaces_32k',[ff2 xx2]); + else + SPM.xVol.G = fullfile(fileparts(mfilename('fullpath')),'templates_surfaces',[ff2 xx2]); + end + end + end + + sinfo(i).Pmesh = SPM.xVol.G; + else + % 32k mesh? + if SPM.xY.VY(1).dim(1) == 32492 || SPM.xY.VY(1).dim(1) == 64984 + sinfo(i).Pmesh = fullfile(fileparts(mfilename('fullpath')),'templates_surfaces_32k',... + [sinfo(i).side '.central.freesurfer.gii']); + else + sinfo(i).Pmesh = fullfile(fileparts(mfilename('fullpath')),'templates_surfaces',... + [sinfo(i).side '.central.freesurfer.gii']); + end + end + catch + % 32k mesh? + switch sinfo(i).ee + case '.gii' + if sinfo(i).exist && ~readsurf + S = gifti(P{i}); + end + case '.annot' + if sinfo(i).exist && ~readsurf + clear S; + try + S = cat_io_FreeSurfer('read_annotation',P{1}); + catch + cat_io_cprintf('warn',sprintf('Warning: Error while reading annotation file: \n %s\n',P{1})); + end + end + end + + if exist('S','var') && isfield(S,'cdata') && (length(S.cdata) == 32492 || length(S.cdata) == 64984) + sinfo(i).Pmesh = fullfile(fileparts(mfilename('fullpath')),'templates_surfaces_32k',... + [sinfo(i).side '.central.freesurfer.gii']); + elseif exist('S','var') && isfloat(S) && (length(S) == 32492 || length(S) == 64984) + sinfo(i).Pmesh = fullfile(fileparts(mfilename('fullpath')),'templates_surfaces_32k',... + [sinfo(i).side '.central.freesurfer.gii']); + else + if sinfo(1).resampled_32k + str_32k = '_32k'; + else + str_32k = ''; + end + sinfo(i).Pmesh = fullfile(fileparts(mfilename('fullpath')),['templates_surfaces' str_32k],... + [sinfo(i).side '.central.freesurfer.gii']); + end + end + sinfo(i).Pdata = sinfo(i).fname; + end + + [ppm,ffm,eem] = fileparts(sinfo(i).Pmesh); + % RD202203 new garbage: if ~strcmp(eem,'.gii'), eem = [eem '.gii']; end + ffm = cat_io_strrep(ffm,{'thickness','central','white','pial','inner','outer','sphere','hull','core','layer4'},'central'); + % RD202203 new garbage: ffm = cat_io_strrep(ffm,{'.resampled_32k','.resampled'},''); + sinfo(i).Phull = fullfile(ppm,strrep(strrep([ffm eem],'.central.','.hull.'),'.gii','')); + sinfo(i).Pcore = fullfile(ppm,strrep(strrep([ffm eem],'.central.','.core.'),'.gii','')); + sinfo(i).Psphere = fullfile(ppm,strrep([ffm eem],'.central.','.sphere.')); + sinfo(i).Pspherereg = fullfile(ppm,strrep([ffm eem],'.central.','.sphere.reg.')); + sinfo(i).Pdefects = fullfile(ppm,strrep([ffm eem],'.central.','.defects.')); + sinfo(i).Player4 = fullfile(ppm,strrep([ffm eem],'.central.','.layer4.')); + sinfo(i).Pwhite = fullfile(ppm,strrep([ffm eem],'.central.','.white.')); + sinfo(i).Ppial = fullfile(ppm,strrep([ffm eem],'.central.','.pial.')); + + if ~exist(sinfo(i).Pdefects,'file'), sinfo(i).Pdefects = ''; end + + %{ + RD202203 new garbage + if sinfo(i).resampled_32k || sinfo(i).resampled + % in case of resampled data we have to use the freesurfer spheres ? + if sinfo(1).resampled_32k + str_32k = '_32k'; + else + str_32k = ''; + end + sinfo(i).Psphere = fullfile(fileparts(mfilename('fullpath')),['templates_surfaces' str_32k],... + [sinfo(i).side '.sphere.freesurfer.gii']); + sinfo(i).Pspherereg = fullfile(fileparts(mfilename('fullpath')),['templates_surfaces' str_32k],... + [sinfo(i).side '.sphere.reg.freesurfer.gii']); + end + %} + + % check if files exist and if they have the same structure (size) + Pmesh_data = dir(sinfo(i).Pmesh); + FN = {'Phull','Pcore','Psphere','Pspherereg','Pwhite','Ppial','Player4'}; + for fni = 1:numel(FN) + if exist(sinfo(i).(FN{fni}) ,'file') + Pdata = dir(sinfo(i).(FN{fni})); + if isempty(Pmesh_data) || isempty(Pdata) || abs(Pmesh_data.bytes - Pdata.bytes)>1500 % data saved by CAT tools may vary a little bit + sinfo(i).(FN{fni}) = ''; + end + else + sinfo(i).(FN{fni}) = ''; + end + end + + + + + if sinfo(i).exist && readsurf + if isfield(S,'vertices') + sinfo(i).nvertices = size(S.vertices,1); + else + if ~isempty(sinfo(i).Pmesh) && exist(sinfo(i).Pmesh,'file') + S2 = gifti(sinfo(i).Pmesh); + if ~isstruct(S), clear S; end + if isfield(S2,'vertices'), S.vertices = S2.vertices; else, S.vertices = []; end + if isfield(S2,'faces'), S.faces = S2.faces; else, S.faces = []; end + end + if isfield(S,'vertices') + sinfo(i).nvertices = size(S.vertices,1); + elseif isfield(S,'cdata') + sinfo(i).nvertices = size(S.cdata,1); + else + sinfo(i).nvertices = nan; + end + end + if isfield(S,'faces'), sinfo(i).nfaces = size(S.faces,1); end + if isfield(S,'cdata'), sinfo(i).ncdata = size(S.cdata,1); end + end + + [ppx,ffx] = spm_fileparts(pp); + sinfo(i).catxml = fullfile(ppx,strrep(ffx,'surf','report'),['cat_' sinfo(i).name '.xml']); + if ~exist(sinfo(i).catxml,'file'), fullfile(pp,['cat_' sinfo(i).name '.xml']); end + if ~exist(sinfo(i).catxml,'file'), sinfo(i).catxml = ''; end + + if nargout>1 + varargout{2}{i} = S; + else + clear S + end + end + varargout{1} = sinfo; +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_io_xml2csv.m",".m","14579","429","function varargout = cat_io_xml2csv(job) +%cat_io_xml2csv2. Save all variables of a set of XML-files in one csv-file. +% +% table = cat_io_xml2csv2 .. GUI version +% table = cat_io_xml2csv2(job) .. batch version +% +% job +% .files .. Cell of XML file names or structure in a cell +% .fname .. Filename of the csv to be written +% .fieldnames .. Selective field keywords that should be extracted, ie. +% only fields that inlclude these strings are used. +% Allow also the coded selction of full fields, eg. +% (defaut = {} i.e. include all) +% .avoidfields .. Deselective field keywords to avoid fields, ie. all +% fields that inlcude these strings are not used. +% (default = {'help catlog'}) +% .report .. report-setting ('default','paraonly','nopara') +% .delimiter .. Deliminiter of CSV file (default = ',') +% .dimlim .. Limit the number of matrix values (default = 256) +% +% table .. cell table with structure path as header. +% +% For conversion to MATLAB table use: +% cell2table(tab(2:end,:),'VariableNames',tab(1,:)) +% +% Examples: +% * Export structure: +% S = struct('files',{'A','B','C'},'data',[0.2 0.3 0.1],'mat',[0.3 0.4 0.2]); +% table = cat_io_xml2csv2(struct('files',{{S}})); +% +% * CAT XML files: +% table = cat_io_xml2csv2 +% +% See also cat_io_struct2table. +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ +% +%#ok<*WNOFF,*WNON,*ASGLU> + + if ~exist('job','var'), job = 'GUI'; end + + def.files = {}; + def.fname = 'CATxml.csv'; + def.fieldnames = {}; + def.avoidfields = {'help'; 'catlog'}; + def.delimiter = ','; + def.outdir = {''}; + def.conclusion = 1; + def.dimlim = 256; % extend in case of catROI below + def.report = 'default'; + def.verb = 1; + + + + % TODO: + % - define some special user-cases for the cat_*.xml? + % - setup for CSV / TSV export? + % - write error in case of too large matrices + % - dependencies + % - RD20240129: handling of missing files ""$FILENAME MISSED XML - FAILED PROCESSING""? + + + + + % GUI + if ischar(job) && strcmp(job,'GUI') + clear job; + job.files = cellstr(spm_select([1 inf],'any','Select *.xml files',{},pwd,'.*.xml$')); + job.fname = spm_input('CSV-filename',1,'s',def.fname); + job.dimlim = spm_input('Limit matrix size',2,'n', def.dimlim,1); + job.verb = 1; + job.fieldnames = spm_input('Selective field keywords? (*=all)',3,'s','*'); + job.avoidfields = spm_input('Deselective field keywords?',4,'s',''); + + if strcmp(job.fieldnames,'*'), job.fieldnames = ''; end + + if ~isempty(job.fieldnames) + job.fieldnames = textscan( job.fieldnames , '%s' ); + job.fieldnames = cellstr(job.fieldnames{1}); + else + job.fieldnames = {}; + end + if ~isempty(job.avoidfields) + job.avoidfields = textscan( job.avoidfields , '%s' ); + job.avoidfields = cellstr(job.avoidfields{1}); + else + job.avoidfields = {}; + end + else + % ########### check files? ############### + % - what is about mat files such as the SPM mat8 ? + end + + + % defaults + job = cat_io_checkinopt(job,def); + + + if job.verb + spm('FnBanner',mfilename); + end + + if isempty(job.files) || isempty(job.files{1}) + return + end + + + %% read all XML files + if isstruct( job.files{1} ) + xml = job.files{1}; + else + xml = cat_io_xml(job.files); + end + + % get fieldnames + xfieldnames = getFN(xml,job.dimlim); + + % remove some critical fieldnames + xfieldnames(contains(xfieldnames,{'.catlog','.software','.ratings_help','.atlas','.satlas','.LAB'})) = []; + + % detect special XML cases + % - in case of the catROI(s)-files, we do not want to output the name/id + % fields as columnes, that are equal for all subjects, but as part of + % the header + % - in case of the cat-report-files, we want to avoid some development + % fields + if numel(job.files)>1 + [~,Sf] = spm_str_manip(job.files,'tC'); + else + [~,Sf] = spm_str_manip([job.files;job.files],'tC'); + end + Sf.sx = strsplit(Sf.s,'_'); + if isempty(Sf.sx), xmltype = ''; else, xmltype = Sf.sx{1}; end + switch xmltype + case {'catROI','catROIs'} + % remove special fields in case of ROI XML files + job.avoidfields = [ job.avoidfields; {'names';'ids';'version';'comments'} ]; + job.dimlim = 1024; + job.fieldnames = getFN(xml,job.dimlim); + xfieldnames = job.fieldnames; + case 'cat' + job.avoidfields = [ job.avoidfields; {'help'; 'catlog'; 'error'; 'hardware'; ... + 'parameter.extopts.atlas'; 'parameter.extopts.satlas'; 'parameter.extopts.LAB'; ... + 'parameter.extopts.shootingtpms{02}'; 'parameter.extopts.shootingtpms{03}'; 'parameter.extopts.shootingtpms{04}'; 'parameter.extopts.shootingtpms{05}'; ... + 'parameter.extopts.templates{02}'; 'parameter.extopts.templates{03}'; 'parameter.extopts.templates{04}'; 'parameter.extopts.templates{05}'; ... + 'filedata.Fm'; 'filedata.Fp0'; 'filedata.file'; 'filedata.fname'; 'filedata.fnames'; 'filedata.path'; ... + 'subjectmeasures.dist_thickness_kmeans_inner3'; 'subjectmeasures.dist_thickness_kmeans_outer2'; ... + }]; + job.dimlim = 10; + + % remove developer fields + if cat_get_defaults('extopts.expertgui')<2 + job.avoidfields = [ job.avoidfields; {'ppe'}; ]; + end + + % strong selection of most relevant fields + relevant_catreport_fields = .... + {'qualityratings.IQR'; 'qualityratings.NCR'; 'qualityratings.ICR'; 'qualityratings.res_ECR'; 'qualityratings.res_RMS'; ... voxel-based QC measures + 'software.version_cat'; 'software.revision_cat'; 'software.version_spm'; ... + 'subjectmeasures.vol_abs_CGW(01)'; 'subjectmeasures.vol_abs_CGW(02)'; 'subjectmeasures.vol_abs_CGW(03)'; ... + 'subjectmeasures.vol_rel_CGW(01)'; 'subjectmeasures.vol_rel_CGW(02)'; 'subjectmeasures.vol_rel_CGW(03)'; ... + 'subjectmeasures.dist_thickness{1}(1)'; 'subjectmeasures.dist_thickness{1}(2)'; + 'subjectmeasures.surf_TSA'; 'subjectmeasures.vol_TIV'; ... + 'qualitymeasures.SurfaceEulerNumber'; 'qualitymeasures.SurfaceDefectArea'; ... + 'qualitymeasures.SurfaceIntensityRMSE'; 'qualitymeasures.SurfacePositionRMSE'; ... + 'qualitymeasures.SurfaceSelfIntersections'; ... + }; + + switch job.report + case 'paraonly' + job.fieldnames = [job.fieldnames; {'opts'; 'extopts' }]; + case 'nopara' + job.fieldnames = [job.fieldnames; relevant_catreport_fields ]; + case 'default' + job.fieldnames = [job.fieldnames; relevant_catreport_fields; {'opts'; 'extopts' }]; + end + + + otherwise + job.avoidfields = [ job.avoidfields; {'help'; 'catlog'} ]; + end + job.avoidfields(isempty(job.avoidfields)) = []; + job.fieldnames = unique(job.fieldnames); + + % select fields + if ~isempty(job.fieldnames) && (~isempty(job.fieldnames{1}) || numel(job.fieldnames)>1) + selfieldnames = false(size(xfieldnames)); + for fni = 1:numel(job.fieldnames) + if ~isempty(job.fieldnames{fni}) + selfieldnames = selfieldnames | cat_io_contains(xfieldnames,job.fieldnames{fni}); + end + end + xfieldnames = xfieldnames(selfieldnames); + end + + % remove critical fieldnames + for fni = 1:numel(job.avoidfields) + if ~isempty(job.avoidfields{fni}) + rmfieldnames = cat_io_contains(xfieldnames,job.avoidfields{fni}); + xfieldnames(rmfieldnames) = []; + end + end + + if job.verb + % some report for error handling + % # data + fprintf(' Found/prepared %d fields of %d %s files.\n',numel(xfieldnames), numel(job.files), xmltype); + end + if isempty(xfieldnames) + fprintf(' Nothing to export - no file written.\n'); + return; + end + + + + %% extract fieldnames from structure to build a table + [hdr,tab] = cat_io_struct2table(xml,xfieldnames,0); + + % create average + existxml = cellfun(@exist,job.files); % only for existing files + if job.conclusion + avg = cell(1,size(tab,2)); + for ci = 1:size(tab,2) % for each column + try + if isnumeric(cell2mat(tab(existxml>0,ci))) % for all numberic fields + try + avg{1,ci} = cat_stat_nanmean( cell2mat(tab(existxml>0,ci)) ); % average existing + avg{2,ci} = cat_stat_nanstd( cell2mat(tab(existxml>0,ci)) ); % average existing + catch + avg{1,ci} = nan; + avg{2,ci} = nan; + end + else + % try to use spm_str_manip to extract similar starts/endings + try + txt = unique( tab(existxml>0,ci) ); + if numel(txt) > 1 + [avg{1,ci},C] = spm_str_manip( avg{1,ci} ,'C'); + if all(cellfun('isempty',C.m)); avg{1,ci}(strfind(avg{1,ci},'{,'):end) = []; end + else + avg{1,ci} = char(txt); + end + avg{2,ci} = ''; + catch + avg{1,ci} = ''; + avg{2,ci} = ''; + end + end + catch + try + if isnumeric(tab{2,ci}) + avg{1,ci} = nan; + avg{2,ci} = nan; + else + avg{1,ci} = ''; + avg{2,ci} = ''; + end + end + end + end + end + + % add index + xfieldnames = ['filenames'; xfieldnames]; + hdr = [{'filename'} hdr]; + tab = [job.files(existxml>0) tab]; + if job.conclusion + avg = [{sprintf('mean (%d of %d)',sum(existxml>0),numel(existxml)); ... + sprintf('std (%d of %d)',sum(existxml>0),numel(existxml))} avg]; + end + + % cleanup some fields + ROInamelim = 30; + for hi = 2:numel(hdr) + if (strcmp(xmltype,'catROI') || strcmp(xmltype,'catROIs')) && cat_io_contains(xfieldnames(hi),'.data.') + FNP = strsplit(xfieldnames{hi},'.'); + ATL = FNP{1}; + RNR = strsplit(cat_io_strrep(FNP{end},{'(',')','{','}'},' ')); + try + RNR = round(str2double(RNR{2})); %RNR{2}; + catch + fprintf('Error: incorrect format.') + ROI = ''; + end + if isfield(xml(1).(ATL),'names') && ... % if there is a name ... + size(char(xml(1).(ATL).names),2) 0 || isempty(job.fname) + varargout{1} = table; + end +end +% ========================================================================= +function FNS = getFN(SS,dimlim) +%getFN(S). Recursive extraction of structure elements as string to eval. + + if ~exist('dimlim','var'), dimlim = 10; end + + if isempty(SS) + FNS = SS; + else + S = SS(1); + FN = fieldnames(S); + FNS = {}; + for fni = 1:numel(FN) + for si = 1:numel(SS) + if ~isempty(S.(FN{fni})), continue; else, S = SS(si); end + end + + % need this for useful order of fields + acc = num2str( 1 + round( log10( numel( S.(FN{fni}) ))) ); + + if isstruct( S.(FN{fni}) ) + % recursive call in case of structures + FNI = getFN(S.(FN{fni}),dimlim); + if isscalar(S.(FN{fni})) + for fnii = 1:numel(FNI) + FNI{fnii} = [FN{fni} '.' FNI{fnii}]; + end + else + FNI = {}; + for fnii = 1:numel(FNI) + for sii = 1:numel(S.(FN{fni})) + FNI = [FNI; sprintf(['%s(%0' acc 'd).%s'], FN{fni}, sii, FNI{fnii})]; %#ok + end + end + end + elseif ischar( S.(FN{fni}) ) + FNI{1} = sprintf('%s', FN{fni} ); + elseif iscellstr( S.(FN{fni}) ) %#ok + FNI = {}; + for fnii = 1:min(dimlim,numel( S.(FN{fni}) )) + FNI = [FNI; sprintf(['%s{%0' acc 'd}'],FN{fni},fnii) ]; %#ok + end + elseif iscell( S.(FN{fni}) ) + % recursive call in case of structures + FNI = {}; + for fnii = 1:numel( S.(FN{fni}) ) + if isscalar( S.(FN{fni}){fnii} ) + FNI = [FNI; sprintf(['%s{%0' acc 'd}'],FN{fni},fnii) ]; + else + acc = num2str( 1 + round( log10( numel( S.(FN{fni}){fnii} ))) ); + % just extract a limited number of elements + for fniii = 1:min(dimlim,numel( S.(FN{fni}){fnii} )) + FNI = [FNI; sprintf(['%s{%0' acc 'd}(%0' acc 'd)'],FN{fni},fnii,fniii) ]; %#ok + end + end + end + else + if isscalar( S.(FN{fni}) ) + FNI{1} = sprintf('%s',FN{fni}); + else + % just extract a limited number of elements + FNI = {}; + for fnii = 1:min(dimlim,numel( S.(FN{fni}) )) + FNI = [FNI; sprintf(['%s(%0' acc 'd)'],FN{fni},fnii) ]; %#ok + end + end + end + FNS = [FNS; FNI]; %#ok + end + FNS = unique(FNS); + end +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_run_job_APP_SPMinit.m",".m","16580","376","function [Ym,Ybg,WMth,bias] = cat_run_job_APP_SPMinit(job,tpm,ppe,n,ofname,nfname,mrifolder,skullstripped) +%% APP bias correction (APP1 and APP2) +% ------------------------------------------------------------ +% Bias correction is essential for stable affine registration. +% SPM further required Gaussian distributed data that is +% achieved by Smoothing in high resolution data and by +% additional noise in regions with many zeros typical in +% skull-stripped or defaced data. +% +% [Ym,Yt,Ybg,WMth,bias] +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + dbs = dbstatus; debug = 0; for dbsi=1:numel(dbs), if strcmp(dbs(dbsi).name,mfilename); debug = 1; break; end; end + + if exist('rng','file') == 2, rng('default'); rng(0); else, rand('state',0); randn('state',0); end %#ok + + V = spm_vol(job.channel(n).vols{job.subj}); + vx_vol = sqrt(sum(V.mat(1:3,1:3).^2)); + + [pp,ff] = spm_fileparts(ofname); + ppn = spm_fileparts(nfname); + onfname = fullfile(ppn,['o' ff '.nii']); + + stime = cat_io_cmd('APPs bias correction'); + if job.extopts.verb>1, fprintf('\n'); end + stime2 = cat_io_cmd(' Preparation','g5','',job.extopts.verb-1); + %if debug, copyfile(ofname,nfname); end + + % SPM segmentation parameter + preproc.channel.vols{1,1} = nfname; + preproc.channel.biasreg = min(0.01,max(0.0001,job.opts.biasreg)); + preproc.channel.biasfwhm = min(90,max(30,job.opts.biasfwhm/2)); + preproc.channel.write = [0 1]; + for ti=1:6 + preproc.tissue(ti).tpm = {[tpm.V(ti).fname ',' num2str(ti)]}; + preproc.tissue(ti).ngaus = job.opts.ngaus(ti); + preproc.tissue(ti).native = [0 0]; % native, dartel + preproc.tissue(ti).warped = [0 0]; % unmod, mod + end + preproc.warp.mrf = 1; % + preproc.warp.cleanup = 1; % this is faster and give better results! + preproc.warp.reg = [0 0.001 0.5 0.05 0.2]; + preproc.warp.affreg = strrep(job.opts.affreg,'prior',cat_get_defaults('opts.affreg')); % have to replace the prior setting from the CAT long pipeline + preproc.warp.write = [0 0]; + + if skullstripped + %% update number of SPM gaussian classes + preproc.tpm = tpm; + Ybg = 1 - spm_read_vols(preproc.tpm.V(1)) - spm_read_vols(preproc.tpm.V(2)) - spm_read_vols(preproc.tpm.V(3)); + if 1 + for k=1:3 + preproc.tpm.dat{k} = spm_read_vols(preproc.tpm.V(k)); + preproc.tpm.V(k).dt(1) = 64; + preproc.tpm.V(k).dat = double(preproc.tpm.dat{k}); + preproc.tpm.V(k).pinfo = repmat([1;0],1,size(Ybg,3)); + end + end + preproc.tissue(5:end) = []; + preproc.tpm.V(4).dat = Ybg; + preproc.tpm.dat{4} = Ybg; + preproc.tpm.V(4).pinfo = repmat([1;0],1,size(Ybg,3)); + preproc.tpm.V(4).dt(1) = 64; + preproc.tpm.dat(5:6) = []; + preproc.tpm.V(5:6) = []; + preproc.tpm.bg1(4) = preproc.tpm.bg1(6); + preproc.tpm.bg2(4) = preproc.tpm.bg1(6); + preproc.tpm.bg1(5:6) = []; + preproc.tpm.bg2(5:6) = []; + preproc.tpm.V = rmfield(preproc.tpm.V,'private'); + + % tryed 3 peaks per class, but BG detection error require manual + % correction (set 0) that is simple with only one class + job.opts.ngaus = [([job.tissue(1:3).ngaus])';1]; % 3*ones(4,1);1; + end + preproc.lkp = []; + for k=1:numel(job.opts.ngaus) + preproc.ngaus(k) = job.opts.ngaus(k); + preproc.tissue(k).ngaus = job.opts.ngaus(k); + preproc.lkp = [preproc.lkp ones(1,job.tissue(k).ngaus)*k]; + end + + %% add noise in zero regions (skull-stripping / defacing) + VF = spm_vol(nfname); + YF = single(spm_read_vols(VF)); + % some average object intensity + Tthn = cat_stat_nanmean(YF(YF(:)>cat_stat_nanmean(YF(YF(:)~=0)) & YF(:)~=0)); + % limitation is required for division data (yv98_05mm_corrected_ + YF = min( Tthn*10, YF); + % smoothing for Gaussian distribution + YF(isnan(YF(:)))=0; + YFs = YF+0; spm_smooth(YFs,YFs,0.5./vx_vol); + YM = abs( (YF-YFs)./max(eps,YFs)); + YM = min(1,smooth3(YM ./ min(0.2,max(YM(:))))); + YF = YFs.*YM + YF.*(1-YM); + Y0 = YF==0; + % add noise for Gaussian distribution in the background + if ppe.affreg.skullstripped + YF = YF + (Y0) .* (0.05*Tthn).*rand(size(YF)); + else + YF(cat_vol_morph(Y0,'o'))=nan; + end + % force floating point + VF.dt(1) = 16; + VF = rmfield(VF,'private'); + if exist(VF.fname,'file'); delete(VF.fname); end + spm_write_vol(VF,YF); + clear VF YF Tthn; + + %% try SPM preprocessing + % ---------------------------------------------------------- + % * if SPM failed we go on without bias correction + % * further iterations on different resolution are usefull + % (the first run correct the worst problems and should + % a correct registration of the next runs) + % * best results for strong corrections (fwhm 30 to 45 mm) + % * SPM preprocessing is very fast (and gives you results in + % the template resolution?) but writing results in the + % original resolution is very slow, so using 2 iterations + % is maybe optimal + % * much slower for biasfwhm<35 mm and samp<4.5 mm + % * the final operation is much slower (3 times) becauserun it + % required the estimation of the deformation field to + % write data in the orignal space + % * writing further outputs on disk will also cost more time + % >> further optimization is possible by avoiding + % temporary disk output + % ---------------------------------------------------------- + % RD2023: We can only support once general case with strong correction. + % The final setting depend also on the user defined bias filter + % size and is therefore adapted anyway. + fwhmx = [8, 2, 3/4]; % + sampx = 2:-1/(numel(fwhmx)-1):1.0; + + + spmp0 = debug; % job.extopts.verb>1; % for debugging: 0 - remove all APP data, 1 - save Ym, 2 - save Ym and Yp0 + optimize = 0; % use low resolution (in mm) input image to increase speed >> limited speed advantage :/ + % deformation requires a lot of time ... maybe its enough to use it only in case of ultra highres data + if any(vx_vol<0.6), optimize = 1.2; end % RD202311: only for extrem high resolutions! + + preproc.Yclsout = false(1,6); + preproc.tol = min(1e-2,job.opts.tol * 10); % 2 times less accurant than the final operation + copyfile(nfname,onfname); + + if optimize>0 + %% lower resolution to improve SPM processing time and use smoothing for denoising + Vi = spm_vol(nfname); + Vi = rmfield(Vi,'private'); Vn = Vi; + imat = spm_imatrix(Vi.mat); + Vi.dim = round(Vi.dim .* vx_vol./repmat(optimize,1,3)); + imat(7:9) = repmat(optimize,1,3) .* sign(imat(7:9)); + Vi.mat = spm_matrix(imat); + + spm_smooth(nfname,nfname,repmat(optimize/2,1,3)); % light denoising before downsampling + [Vi,Yi] = cat_vol_imcalc(Vn,Vi,'i1',struct('interp',5,'verb',0,'mask',-1)); + delete(nfname); spm_write_vol(Vi,Yi); + %if ~isinf(job.opts.biasstr), clear Yi; end + end + + %% + bias = zeros(size(sampx)); + for ix=1:numel(sampx) + %% parameter update + preproc.warp.samp = min(9 ,max(1 ,job.opts.samp * sampx(ix))); + preproc.channel.biasfwhm = min(1000,max(30,job.opts.biasfwhm * fwhmx(ix))); + % preproc.warp.reg = [0 0 0 0 0];ex + + stime2 = cat_io_cmd(sprintf(' SPM bias correction (samp: %0.2f mm, fwhm: %3.0f mm)',preproc.warp.samp,... + preproc.channel.biasfwhm),'g5','',job.extopts.verb-1,stime2); + + %try + % SPM bias correction + warning off; + if ix==numel(sampx) || bias(1) >= preproc.channel.biasfwhm + if job.extopts.APP==2 || spmp0>1, preproc.Yclsout = true(1,max(preproc.lkp)); end % + vout = cat_spm_preproc_run(preproc,'run'); res(ix) = vout.res; %#ok + else + vout = cat_spm_preproc_run(preproc,'run'); res(ix) = vout.res; %#ok + end + warning on; +%% + Pmn = fullfile(pp,mrifolder,['mn' ff '.nii']); + Pmn_ri = fullfile(pp,mrifolder,['mn' ff '_r' num2str(ix) '.nii']); + Pmn_r0 = fullfile(pp,mrifolder,['mn' ff '_r0.nii']); + + % estimate bias strength based on the applied corrections + % of the initial correction .. + % in case of updates, local biasfield strenght is maybe + % better (only useful if strong changes are allowed) + if ix==1 && exist('Yi','var') + Vn = spm_vol(Pmn); Vn = rmfield(Vn,'private'); + Yn = spm_read_vols(Vn); + bias(ix) = (1/cat_stat_nanstd(Yn(:)./Yi(:))) * 4; + %fprintf('bias=%5.0f mm ',bias(ix)); + bias(ix) = max(30,min(120,round(bias(ix) / 15) * 15)); + if ~debug, clear Yn; end + else + bias(ix) = 0; + end + + % backup the bias corrected image + if spmp0>0, copyfile(Pmn,Pmn_ri); end + + % backup for mixing + if (ix==2 && numel(sampx)>2) || (ix==1 && numel(sampx)<=2) || bias(1) > preproc.channel.biasfwhm + copyfile(fullfile(pp,mrifolder,['mn' ff '.nii']),Pmn_r0); + end + copyfile(fullfile(pp,mrifolder,['mn' ff '.nii']),nfname); + + % write segmentation + if spmp0>1 && exist('vout','var') && isfield(vout,'Ycls') + VF = spm_vol(nfname); VF.fname = fullfile(pp,mrifolder,['p0n' ff '.nii']); VF.dt(1) = 2; + Yp0 = single(vout.Ycls{1})/255*2 + single(vout.Ycls{2})/255*3 + single(vout.Ycls{3})/255; + spm_write_vol(VF,Yp0); + elseif spmp0==0 && ix==numel(sampx) % remove spm mat file + delete(fullfile(pp,mrifolder,['n' ff '_seg8.mat'])); + end + + %% combine low and high frequency filted images + if ix==numel(sampx) %|| (bias(1) > preproc.channel.biasfwhm && ix>1) + %% + stime2 = cat_io_cmd(' Postprocessing','g5','',job.extopts.verb-1,stime2); + if optimize + % update Ym + Vn = spm_vol(nfname); Vn = rmfield(Vn,'private'); + Vo = spm_vol(onfname); Vo = rmfield(Vo,'private'); + [Vmx,vout.Ym] = cat_vol_imcalc([Vo,Vn],Vo,'i2',struct('interp',5,'verb',0,'mask',-1)); clear Vmx; %#ok + vout.Ym = single(vout.Ym); + + %% remap Ym0 + Vn = spm_vol(Pmn_r0); Vn = rmfield(Vn,'private'); + Vo = spm_vol(onfname); Vo = rmfield(Vo,'private'); + [Vmx,Ym0] = cat_vol_imcalc([Vo,Vn],Vo,'i2',struct('interp',5,'verb',0,'mask',-1)); clear Vmx; %#ok + Ym0 = single(Ym0); + + %% replace interpolation boundary artefact + %{ + Ybd = ones(size(vout.Ym)); Ybd(3:end-2,3:end-2,3:end-2) = 0; + [D,I] = cat_vbdist(single(~(isnan(vout.Ym) | Ybd)),true(size(vout.Ym))); clear D; %#ok + vout.Ym = min(vout.Ym,vout.Ym(I)); + Ym0 = Ym0(I); + clear I; + %} + + %% update Ycls + if isfield(vout,'Ycls') + for i=1:numel(vout.Ycls) + Vn = spm_vol(nfname); Vn = rmfield(Vn,'private'); + Vo = spm_vol(onfname); Vo = rmfield(Vo,'private'); + Vn.pinfo = repmat([1;0],1,size(vout.Ycls{i},3)); + Vo.pinfo = repmat([1;0],1,Vo.dim(3)); + Vn.dt = [2 0]; + Vo.dt = [2 0]; + Vo.dat = zeros(Vo.dim(1:3),'uint8'); + if ~isempty(vout.Ycls{i}) + Vn.dat = vout.Ycls{i}; + [Vmx,vout.Ycls{i}] = cat_vol_imcalc([Vo,Vn],Vo,'i2', ... + struct('interp',5,'verb',0,'mask',-1)); clear Vmx; %#ok + vout.Ycls{i} = cat_vol_ctype(vout.Ycls{i}); + end + end + end + else + Ym0 = spm_read_vols(spm_vol(Pmn_r0)); + + %% replace interpolation boundary artefact + %{ + Ybd = ones(size(vout.Ym)); Ybd(3:end-2,3:end-2,3:end-2) = 0; + [D,I] = cat_vbdist(single(~(isnan(Ym0) | Ybd)),true(size(Ym0))); clear D; %#ok + Ym0 = min(Ym0,Ym0(I)); clear I; + %} + end + cat_io_cmd(' ','g5','',job.extopts.verb-1,stime2); + + if ~debug && exist(Pmn_r0,'file'), delete(Pmn_r0); end + if ~debug && exist(Pmn_r0,'file'), delete(Pmn_r0); end + + %% mixing + % creation of segmentation takes a lot of time because + % of the deformations. So it is much faster to load a + % rought brain mask. + if isfield(vout,'Ycls') + Yp0 = single(vout.Ycls{1})/255*2 + single(vout.Ycls{2})/255*3 + single(vout.Ycls{3})/255; + YM2 = cat_vol_smooth3X(cat_vol_smooth3X(Yp0>0,16/mean(vx_vol))>0.95,10/mean(vx_vol)); + if ~debug, clear Yp0; end + else + Pb = char(job.extopts.brainmask); + Pbt = fullfile(pp,mrifolder,['brainmask_' ff '.nii']); + VF = spm_vol(onfname); + VFa = VF; %if job.extopts.APP~=5, VFa.mat = Affine * VF.mat; end + [Vmsk,Yb] = cat_vol_imcalc([VFa,spm_vol(Pb)],Pbt,'i2',struct('interp',3,'verb',0,'mask',-1)); %#ok + Ybb = cat_vol_smooth3X(Yb>0.5,8/mean(vx_vol)); Ybb = Ybb./max(Ybb(:)); + YM2 = cat_vol_smooth3X(Ybb>0.95,8/mean(vx_vol)); YM2 = YM2./max(Ybb(:)); + if ~debug, clear Pb Pbt VFa Vmsk Yb Ybb; end + end + + %% combine the low (~60 mm, Ym0) and high frequency correction (~30 mm, vout.Ym) + Yo = spm_read_vols(spm_vol(onfname)); + + % final bias field correction + Yw = vout.Ym.*(1-YM2) + (YM2).*Ym0; + Yw = Yo./ max(eps,Yw) .* (Yo~=0 & Yw~=0); + % correct undefined voxel and assure smoothness of the bias field + Yw = cat_vol_approx(max(0,min(2,Yw)),'',vx_vol,2,struct('lfO',2)); + vout.Ym = Yo ./ max(eps,Yw); + + %% output variables + % the background class is maybe incorrect, so we use the minimum + % of the most important values per class + BGth = min(vout.res.mn(vout.res.mg(:) >= (0.5./preproc.ngaus(vout.res.lkp(:))'))); + WMth = mean(vout.res.mn(vout.res.lkp(:)==2) .* vout.res.mg(vout.res.lkp(:)==2)'); + vout.Ym(isnan(vout.Ym(:))) = min(vout.Ym(:)); + Ym = (vout.Ym - BGth) ./ (WMth - BGth); + Ybg = cat_vol_morph(cat_vol_morph(Ym<0.2,'ldo',2,vx_vol),'dc',3,vx_vol); + + % The SPM bias correction can change the overall image intensity of + % some images strongly (resulting in negative values!). Hence, we + % have to rescale the intensity based on the first segmentation. + BGth0 = min(res(1).mn(res(1).mg(:) >= (0.5./preproc.ngaus(res(1).lkp(:))'))); + WMth0 = mean(res(1).mn(res(1).lkp(:)==2) .* res(1).mg(res(1).lkp(:)==2)'); + PDT2 = res(1).mn(res(1).lkp(:)==1) < res(1).mn(res(1).lkp(:)==2); % inverse weighting > softer scalling + Yoc = max(-0.1,min(3 + 7*PDT2 , Ym .* WMth0 + BGth0)); + +Yoc(isnan(Yo)) = nan; % not sure if this is good + + %% + if ~debug, clear Yw Yo; end + Vm = spm_vol(onfname); Vm.fname = nfname; Vm.dt(1) = 16; + spm_write_vol(Vm,Yoc); + + % backup the bias corrected image + if spmp0>0 + copyfile(nfname,fullfile(pp,mrifolder,['mn' ff '_r' num2str(ix)+1 '.nii'])); + end + if exist(Pmn_r0,'file'), delete(Pmn_r0); end + %% + break + else + movefile(fullfile(pp,mrifolder,['mn' ff '.nii']),nfname); + end + try + catch + fprintf('\b\b\b\b\b\b\b\b\b(failed) '); + if exist(fullfile(pp,mrifolder,['mn' ff '.nii']),'file') + delete(fullfile(pp,mrifolder,['mn' ff '.nii'])); + end + end + + if 0 + %% just debugging + Yp0 = single(vout.Ycls{1})/255*2 + single(vout.Ycls{2})/255*3 + single(vout.Ycls{3})/255; + Tthx = max( [ median( vout.Ym(vout.Ycls{1}(:)>128)) , median( vout.Ym(vout.Ycls{2}(:)>128)) ]); + ds('d2','a',vx_vol,Ym0/Tthx,Yp0/3,vout.Ym/Tthx,vout.Ym/Tthx,120) + %% + Tthx = mean( vout.Ym( YM2(:)>0.2 & vout.Ym(:)>mean(vout.Ym(YM2(:)>0.2))) ); + ds('d2','',vx_vol,Ym0/Tthx,YM2,vout.Ym/Tthx,Ym/Tthx,80) + end + end + if debug, cat_io_cmd('','g5','',job.extopts.verb-1,stime); end + Pmn = fullfile(pp,mrifolder,['mn' ff '.nii']); + if exist(Pmn,'file'), delete(Pmn); end + + + if exist(onfname,'file'), delete(onfname); end + %fprintf('%5.0fs\n',etime(clock,stime)); + + + + +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_surf_resamp_freesurfer.m",".m","4677","141","function cat_surf_resamp_freesurfer(vargin) +%cat_surf_resamp_freesurfer to resample parameters to template +% space and smooth it. +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + rev = '$Rev$'; + + if nargin == 1 + Psubj = char(vargin.data_fs); + fwhm_surf = vargin.fwhm_surf; + outdir = vargin.outdir{1}; + mesh32k = vargin.mesh32k; + pname = vargin.measure_fs; + else + error('Not enough parameters.'); + end + + opt.debug = cat_get_defaults('extopts.verb') > 2; + + if mesh32k + opt.fsavgDir = fullfile(fileparts(mfilename('fullpath')),'templates_surfaces_32k'); + str_resamp = '.resampled_32k'; + else + opt.fsavgDir = fullfile(fileparts(mfilename('fullpath')),'templates_surfaces'); + str_resamp = '.resampled'; + end + + hemi_str = char('lh','rh'); + + if ~exist(outdir) + mkdir(outdir) + end + + % use external dat-file if defined to increase processing speed and keep SPM.mat file small + % because the cdata field is not saved with full data in SPM.mat + if cat_get_defaults('extopts.gifti_dat') + gformat = 'ExternalFileBinary'; + else + gformat = 'Base64Binary'; + end + + for i=1:size(Psubj,1) + + stime = clock; + exist_hemi = []; + [pp,name,ext] = spm_fileparts(deblank(Psubj(i,:))); + + % subject directory + dname = fullfile(pp,[name ext],'surf'); + + % check that surf subfolder exists + if ~exist(dname,'dir') + fprintf('Could not find ''surf'' subfolder in %s.\n\n',Psubj(i,:)); + continue + end + + for j=1:2 + + hemi = hemi_str(j,:); + exist_hemi = [exist_hemi j]; + + Psmoothwm = fullfile(dname,[hemi '.smoothwm']); + Psphere = fullfile(dname,[hemi '.sphere']); + Pspherereg = fullfile(dname,[hemi '.sphere.reg']); + Pmeasure = fullfile(dname,[hemi '.' pname]); + Presamp = fullfile(dname,[hemi '.smoothwm' str_resamp]); + Pvalue = fullfile(dname,[hemi '.' pname str_resamp]); + + if fwhm_surf > 0 + Pfwhm = fullfile(outdir,[sprintf('s%g.',fwhm_surf) hemi '.' pname str_resamp '.' name]); + else + Pfwhm = fullfile(outdir,[hemi '.' pname str_resamp '.' name]); + end + + % save fwhm name to merge meshes + Pfwhm_all{j} = [Pfwhm '.gii']; + + Pfsavg = fullfile(opt.fsavgDir,[hemi '.sphere.freesurfer.gii']); + Pmask = fullfile(opt.fsavgDir,[hemi '.mask']); + + fprintf('Resample %s in %s\n',hemi,deblank(Psubj(i,:))); + + % resample values using warped sphere + cmd = sprintf('CAT_ResampleSurf ""%s"" ""%s"" ""%s"" ""%s"" ""%s"" ""%s""',Psmoothwm,Pspherereg,Pfsavg,Presamp,Pmeasure,Pvalue); + cat_system(cmd,opt.debug); + + % smooth resampled values + cmd = sprintf('CAT_BlurSurfHK ""%s"" ""%s"" ""%g"" ""%s"" ""%s""',Presamp,Pfwhm,fwhm_surf,Pvalue,Pmask); + cat_system(cmd,opt.debug); + + % add values to resampled surf and save as gifti + cmd = sprintf('CAT_AddValuesToSurf ""%s"" ""%s"" ""%s""',Presamp,Pfwhm,[Pfwhm '.gii']); + cat_system(cmd,opt.debug); + + % remove path from metadata to allow that files can be moved (pathname is fixed in metadata) + [pp2,ff2,ex2] = spm_fileparts([Pfwhm '.gii']); + g = gifti([Pfwhm '.gii']); + g.private.metadata = struct('name','SurfaceID','value',[ff2 ex2]); + + if vargin.merge_hemi + save(g, [Pfwhm '.gii'], 'Base64Binary'); + else + save(g, [Pfwhm '.gii'], gformat); + end + + delete(Presamp); + delete(Pfwhm); + if fwhm_surf > 0, delete(Pvalue); end + end + + % merge hemispheres + if vargin.merge_hemi + % replace hemi info with ""mesh"" + Pfwhm = strrep(Pfwhm_all{1},['lh.' pname],['mesh.' pname]); + [pp,ff,ex] = spm_fileparts(Pfwhm); + + % combine left and right and optionally cerebellar meshes + if numel(exist_hemi) > 1 + M0 = gifti({Pfwhm_all{1}, Pfwhm_all{2}}); + delete(Pfwhm_all{1}); delete(Pfwhm_all{2}) + warning('off','MATLAB:subscripting:noSubscriptsSpecified'); + M = gifti(spm_mesh_join([M0(1) M0(2)])); + M.private.metadata = struct('name','SurfaceID','value',[ff ex]); + save(M, Pfwhm, gformat); + Psdata{i} = Pfwhm; + else + disp('No data for opposite hemisphere found!'); + end + + fprintf('(%3.0f s) Display resampled %s\n',etime(clock,stime),spm_file(Psdata{i},'link','cat_surf_display(''%s'')')); + end + + end +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_batch_cat.m",".m","3303","112","function cat_batch_cat(namefile,cat_defaults) +% wrapper for using batch mode (see cat_batch_cat.sh) +% +% namefile - array of file names or text file with file names +% cat_defaults - use this default file instead of cat_defaults.m +% +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + %#ok<*TRYNC> + +if nargin < 1 + fprintf('Syntax: cat_batch_cat(namefile,cat_defaults)\n'); + return +end + +addpath(fileparts(which(mfilename))) + +[t,pid] = system('echo $$'); +fprintf('cat_batch_cat: \n PID = %s\n\n',pid); + +global defaults cat matlabbatch %#ok + +spm_get_defaults; + +if nargin < 2 + cat_get_defaults; +else + if isempty(cat_defaults) + cat_get_defaults; + else + fprintf('Use defaults in %s.\n',cat_defaults); + [pp, name] = spm_fileparts(cat_defaults); + clear cat_defaults + oldpath = pwd; + if ~isempty(pp), cd(pp); end + eval(name); + cd(oldpath) + end +end + +if ~iscell(namefile) + [pth,nam,ext] = spm_fileparts(namefile); +end + +% check whether namefile is a cell of filenames, a nifti filename, +% or a text file with filenames +if iscell(namefile) + names0 = namefile; + is_filelist = 1; +elseif strcmp(ext,'.nii') | strcmp(ext,'.img') + names0 = cellstr(namefile); + is_filelist = 1; +else % or use list of names in text file + fid = fopen(namefile,'r'); + names0 = textscan(fid,'%q'); + names0 = names0{:}; + fclose(fid); + is_filelist = 0; +end + +n = length(names0); + +if n == 0, error(sprintf('No file found in %s.\n',namefile)); end %#ok + +i = 1; +while i <= n + % if no .nii or .img was found assume that the filenames contains spaces and is therefore divided into + % different cells + if isempty(strfind(names0{i},'.nii')) && isempty(strfind(names0{i},'.img')) && i % catch with lasterror is necessary for old matlab versions + caterr = lasterror; %#ok + sprintf('\n%s\nCAT Preprocessing error: %s:\n%s\n', repmat('-',1,72),caterr.identifier,caterr.message,repmat('-',1,72)); + for si=1:numel(caterr.stack), cat_io_cprintf('err',sprintf('%5d - %s\n',caterr.stack(si).line,caterr.stack(si).name)); end; + cat_io_cprintf('err',sprintf('%s\\n',repmat('-',1,72))); + error('Batch failed.'); +end + +% delete text file with filenames +if ~is_filelist, spm_unlink(char(namefile)); end + +warning off +exit +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_run_job_APRGs.m",".m","14968","358","function [Affine2,Yb,Ymi,Ym0] = cat_run_job_APRGs(Ysrc,Ybg,VF,Pb,Pbt,Affine,vx_vol,obj,job) +% ______________________________________________________________________ +% Skull-stripping subfunction APRG (adaptive probability region-growing) +% of cat_main_updateSPM. +% +% [Yb,Ymi,Ym0] = cat_run_job_APRGs(Ysrc,Ybg,VF,Pb,Pbt,Affine,vx_vol) +% +% Ysrc .. original input images +% Ybg .. +% res .. SPM preprocessing structure +% Yb .. binary brain mask +% Ym0 .. probability brain mask +% Yg .. absolute gradient map (eg. for tissue edges) +% Ydiv .. divergence maps (eg. for blood vessels) +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + dbs = dbstatus; debug = 0; for dbsi=1:numel(dbs), if strcmp(dbs(dbsi).name,mfilename); debug = 1; break; end; end + + % load default brain mask + VFa = VF; VFa.mat = Affine * VF.mat; %Fa.mat = res0(2).Affine * VF.mat; + if isfield(VFa,'dat'), VFa = rmfield(VFa,'dat'); end + [Vmsk,Yb0] = cat_vol_imcalc([VFa,spm_vol(Pb)],Pbt,'i2',... + struct('interp',2,'verb',0,'mask',-1)); clear Vmsk %#ok + + % remove areas far away from the brain and use low resolution + Ymi = Ysrc; + [Ysrc,BB] = cat_vol_resize(Ysrc,'reduceBrain',vx_vol,round(20/mean(vx_vol)),Yb0); + Ybg = cat_vol_resize(Ybg ,'reduceBrain',vx_vol,round(20/mean(vx_vol)),Yb0); + Yb0 = cat_vol_resize(Yb0 ,'reduceBrain',vx_vol,round(20/mean(vx_vol)),Yb0); + [Ysrc,rV] = cat_vol_resize(Ysrc,'reduceV',vx_vol,1.5,64); + Ybg = cat_vol_resize(Ybg ,'reduceV',vx_vol,1.5,64); + Yb0 = cat_vol_resize(Yb0 ,'reduceV',vx_vol,1.5,64); + + vx_vol = rV.vx_volr; + + %% estimate tissue thresholds for intensity normalization + bgth = cat_stat_kmeans(Ysrc(Ybg)); + T5th = cat_stat_kmeans( cat_stat_histth(Ysrc(Yb0>0.5) ,[0.95 0.99]),5); + T3th = T5th([1 3 5]); % use more agressive scaling to avoid skull-stripping + if 0 % WMHs? + Txth = cat_stat_kmeans(Ysrc(Yb0>0.5 & ... + Ysrc>nansum(T3th(1:2:3) .* [0.9 0.1]) & ... + Ysrc 100)>0.5; + if ~debug, clear Ybb1 Ybb2 bb; end + % filling + [Ybg,resT2] = cat_vol_resize(single(~Ybg),'reduceV',resT1.vx_volr,2,32,'meanm'); + Ybg = Ybg>0.5; + Ybg = cat_vol_morph(Ybg,'lc',4); + Ybg = cat_vol_smooth3X(Ybg,2); + Ybg = cat_vol_resize(Ybg,'dereduceV',resT2)<0.5; + end + + + %% improved brain mask by region growing + % Yb .. improving the brain mask is necessary in case of missing + % structures (e.g. in children) or failed registration where + % the TPM does not fit well and the CSF include brain tissue + % simply by chance. + BGth = double(cat_stat_nanmean(Ysrc( Ybg ))); + BVth = double(abs(diff(T3th(1:2:3)) / abs(T3th(3)) * 3)); % avoid blood vessels (high gradients) + RGth = double(abs(diff(T3th(2:3)) / abs(T3th(3)) * 0.1)); % region growing threshold + + + %% initial brain mask by region-growing + % mask for region growing and WM-GM region growing + Yhd = cat_vbdist(single(Yb0<0.5)); Yhd = Yhd ./ max(Yhd(Yhd <100)); + Yb2 = cat_vol_morph( Yb0>0.5 | (Yb0.*Ym)>0.25 & (Yb0.*Ym)<1.2 & Ym<1.2,'de',4,vx_vol); Yb=false(size(Yb0)); + Yb2 = cat_vol_morph((Ym>0.5 & Ym<1.2 & Yb2) | Yhd>0.25,'ldo',4,vx_vol); % remove skull + Yb2 = single(cat_vol_morph(Yb2 | Yhd>0.25,'ldc',4,vx_vol)); if ~debug, clear Yhd; end + %% region-growing + if T3th(1) < T3th(3) % T1 + Yh = (Yb2<0.5) & (Ysrc(T3th(3)*1.2) | Yg>BVth); + else + Yh = (Yb2<0.5) & (Ysrcsum(T3th(2:3).*[0.5 0.5]) | Yg>BVth); + end + Yh = cat_vol_morph(Yh,'dc',2,vx_vol); + Yh = cat_vol_morph(Yh,'de',1,vx_vol); Yb2(Yh) = nan; if ~debug, clear Yh; end + if T3th(1) < T3th(3) % T1 + [Yb2,YD] = cat_vol_downcut(Yb2,Ysrc/T3th(3),RGth/2); clear Yb2; %#ok + else + [Yb2,YD] = cat_vol_downcut(Yb2,1 - Ysrc/T3th(3),RGth/2); clear Yb2; %#ok + end + Yb(YD<400/mean(vx_vol)) = 1; clear YD; + Yb(smooth3(Yb)<0.5) = 0; + Yb = cat_vol_morph(Yb,'ldo',1.9,vx_vol); + Yb = cat_vol_morph(Yb,'ldc',1.9,vx_vol); + + %% + Yb = single(Yb); + if T3th(1) < T3th(3) % T1 + Yh = (Yb<0.5) & (Ysrc(T3th(3)*1.2) | Yg>BVth); + else + Yh = (Yb<0.5) & (Ysrcsum(T3th(2:3).*[0.5 0.5]) | Yg>BVth); + end + Yh = cat_vol_morph(Yh,'dc',2,vx_vol); + Yh = cat_vol_morph(Yh,'de',1,vx_vol); Yb2(Yh) = nan; if ~debug, clear Yh; end + if T3th(1) < T3th(3) % T1 + [Yb2,YD] = cat_vol_downcut(Yb,Ysrc/T3th(3),0); clear Yb2; %#ok + else + [Yb2,YD] = cat_vol_downcut(Yb,1 - Ysrc/T3th(3),0); clear Yb2; %#ok + end + Yb(YD<400/mean(vx_vol)) = 1; clear YD; + Yb(smooth3(Yb)<0.5) = 0; + Yb = cat_vol_morph(Yb,'ldo',1.9,vx_vol); + Yb = cat_vol_morph(Yb,'ldc',1.9,vx_vol); + + %% GM-CSF region + Yb2 = single(cat_vol_morph(Yb,'de',2.9,vx_vol)); + if T3th(1) < T3th(3) + Yh = (Yb2<0.5) & (Ysrc0.15 | ... + Ysrc>cat_stat_nanmean(T3th(3)*1.2) | Yg>BVth); + else + Yh = (Yb2<0.5) & (Ysrc>sum(T3th(1:2).*[0.9 0.1]) | Yg>0.15 | ... + Ysrc<(T3th(3) - sum(T3th(2:3).*[0.5 0.5])) | Yg>BVth); + end + Yh = cat_vol_morph(Yh,'dc',2) | cat_vol_morph(~Yb,'de',10,vx_vol); + Yh = cat_vol_morph(Yh,'de',1,vx_vol); Yb2(Yh) = nan; if ~debug, clear Yh; end + if T3th(1) < T3th(3) % T1 + [Yb2,YD] = cat_vol_downcut(Yb2,Ysrc/T3th(3),-RGth); clear Yb2; %#ok + else + [Yb2,YD] = cat_vol_downcut(Yb2,1 - Ysrc/T3th(3),-RGth); clear Yb2; %#ok + end + Yb(YD<200/mean(vx_vol)) = 1; clear YD; + Yb(smooth3(Yb)<0.5) = 0; Yb(smooth3(Yb)>0.5) = 1; + Yb = cat_vol_morph(Yb,'ldo',1.9,vx_vol); + Yb = cat_vol_morph(Yb,'ldc',4); + + + + + + %% CSF region + if T3th(1) < T3th(3) + %% create brain level set map + % Ym .. combination of brain tissue and CSF that is further corrected + % for noise (median) and smoothness (Laplace) an finally + % threshholded + Ybd = cat_vbdist(single(smooth3(Yb)>0.5),~Ybg,vx_vol); + mnhd = cat_stat_kmeans( Ybd( cat_vol_morph(Ybg,'d') & Ybd<10 ) ); + Ybgd = cat_vbdist(single(Ybg | Ybd>mnhd*2),~Yb,vx_vol); + Ymx = Ybgd./(Ybd+Ybgd); + % + Yb2 = single(cat_vol_morph(Yb,'de',1.9,vx_vol)); + Yh = (Yb2<0.5) & (Ymx<0.5 | (Ysrc>sum(T3th(1:2).*[0.5 0.5])) & cat_vol_morph(~Ybg,'de',2)); + Yh = cat_vol_morph(Yh,'ldc',1) | cat_vol_morph(~Yb,'de',10,vx_vol); + Yh = cat_vol_morph(Yh,'de',1,vx_vol); Yb2(smooth3(Yh)>0.9) = nan; if ~debug, clear Yh; end + %% + [Yb2,YD] = cat_vol_downcut(Yb2,Ysrc/T3th(3),-RGth); clear Yb2; %#ok + Yb(YD<400/mean(vx_vol)) = 1; clear YD; + Yb(smooth3(Yb)<0.5) = 0; Yb(smooth3(Yb)>0.5) = 1; + Yb = cat_vol_morph(Yb,'ldo',1.9,vx_vol); + Yb = cat_vol_morph(Yb,'ldc'); + end + + if 0 + %% cleanup ? + P = zeros([size(Ysrc),3],'uint8'); + Yp0toC = @(Yp0,c) 1-min(1,abs(Yp0-c)); + for c=1:3, P(:,:,:,c) = cat_vol_ctype( Yp0toC( Ysrc./T3th(3) .* Yb * 3 , c) * 255); end + P = cat_main_clean_gwc(P,2); + Ybx = sum(P,4)>128; + end + + + %% create brain level set map + % Ym .. combination of brain tissue and CSF that is further corrected + % for noise (median) and smoothness (Laplace) an finally + % threshholded + Ybd = cat_vbdist(single(smooth3(Yb)>0.5),~Ybg,vx_vol); + mnhd = cat_stat_kmeans( Ybd( cat_vol_morph(Ybg,'d') & Ybd<10 ) ); + Ybgd = cat_vbdist(single(Ybg | Ybd>mnhd),~Yb,vx_vol); + Ymx = min(1,Ybgd./(Ybd+Ybgd)); + + + %% cutting parameter + % This is maybe a nice parameter to control the CSF masking. + % And even better we can use a surface to find the optimal value. :) + if isfield(job.extopts,'cutstr') + cutstr = job.extopts.cutstr; % 0.85; + else + cutstr = 1.0; % 0.85; + end + cutstrs = linspace(0.3,0.95,4); % 0.05,0.35,0.65,0.95]; + cutstrval = nan(1,4); + if debug, cutstrsa = zeros(0,8); end + Ysrc2 = (Ysrc>T3th(1)) .* (abs(Ysrc - T3th(1))/(T3th(2) - T3th(1))) + ... + (Ysrc + if debug, cutstrsa = [cutstrsa; cutstrs, cutstrval]; end %#ok + cutstrs = linspace(cutstrs(max(1,cutstrid(1)-1)),cutstrs(min(4,cutstrid(1)+1)),4); + cutstrval = [cutstrval(max(1,cutstrid(1)-1)),nan,nan,cutstrval(min(4,cutstrid(1)+1))]; + + end + cutstr = cutstrs(cutstrid(1)); + end + + + %% normalize this map depending on the cutstr parameter + Yb = cat_vol_morph(cat_vol_morph(Ymx > cutstr,'lo'),'c'); + Yb = cat_vol_morph(Yb,'e') | (Ymx>0.9); + Yb(smooth3(Yb)<0.5)=0; + Ybb = cat_vol_ctype( max(0,min(1,(Ymx - cutstr)/(1-cutstr))) * 256); + Ym0 = Ybb; + + + %% estimate gradient (edge) and divergence maps + Yb = cat_vol_resize(Yb ,'dereduceV',rV); + Ym0 = cat_vol_resize(Ym0,'dereduceV',rV); + Yb = cat_vol_resize(Yb ,'dereduceBrain',BB); + Ym0 = cat_vol_resize(Ym0,'dereduceBrain',BB); + + %% intensity normalization + Tth.T3thx = [bgth T5th(1) T5th(3) T5th(5) T5th(5)+diff(T5th(3:2:5))]; + Tth.T3th = 0:1/3:4/3; + Tth.T3th(2)= 1/6; + %Tth.T3th(3)= 4/6; + Ymi2 = cat_main_gintnormi(Ymi/3,Tth); + Ymi2 = max(Ymi2,cat_vol_smooth3X(cat_vol_morph( (Ymi2 .* Yb) >.5,'lc',2),1)); + Ymi2 = cat_vol_smooth3X(Ymi2,1); + + %% create obj + %Yb2 = cat_vol_morph(Yb,'ldo',8,vx_vol); + %Yb2 = cat_vol_morph(Yb,'dd',10,vx_vol); + obj2 = obj; + if 1 % unit8 + obj2.image.pinfo = repmat([255/1;0],1,size(Yb,3)); + obj2.image.dt = [spm_type('UINT8') spm_platform('bigend')]; + obj2.image.dat = cat_vol_ctype( ((Ymi2 - 0.1) * 200) .* Yb); %Ymi2* + else + obj2.image.pinfo = repmat([1;0],1,size(Yb,3)); + obj2.image.dt = [spm_type('FLOAT32') spm_platform('bigend')]; + obj2.image.dat = single( Ymi2 .* Yb); + obj2.image.dat(~Yb) = nan; + end + if isfield(obj2.image,'private'), obj2.image = rmfield(obj2.image,'private'); end + obj2.samp = 3; %1.5; + obj2.fwhm = 10; + if isfield(obj2,'tpm'), obj2 = rmfield(obj2,'tpm'); end + obj2.tpm = spm_load_priors8(obj.tpm.V(1:3)); + Ybx = (exp(obj2.tpm.dat{1}) + exp(obj2.tpm.dat{2}) + exp(obj2.tpm.dat{3}))>0.5; + for i=1:3, obj2.tpm.dat{i} = obj2.tpm.dat{i} .* Ybx; end + +if 1 + %% RD202007: hmm, masking without test ... + obj2.msk = VF; + obj2.msk.pinfo = repmat([255;0],1,size(Yb,3)); + obj2.msk.dt = [spm_type('uint8') spm_platform('bigend')]; + obj2.msk.dat = uint8(Yb); + obj2.msk = spm_smoothto8bit(obj2.msk,0.1); +end + + % do registration + if ~isfield( job , 'useprior' ) || isempty( job.useprior ) && ~isempty(job.opts.affreg) + warning('off','MATLAB:RandStream:ActivatingLegacyGenerators') + % try to use the newer version that is updated in SPM12 + try + [Affine2,ll] = spm_maff8(obj2.image, obj2.samp ,obj2.fwhm ,obj2.tpm ,Affine ,job.opts.affreg ,80); + catch + fprintf('Please update SPM12!\n'); + [Affine2,ll] = spm_maff8(obj2.image, obj2.samp ,obj2.fwhm ,obj2.tpm ,Affine ,job.opts.affreg); + end + if det(Affine \ Affine2)>1.5 || det(Affine2 \ Affine)>1.5 % || ll<0.9 % RD202007: add this maybe later + % try to use the newer version that is updated in SPM12 + try + Affine2 = spm_maff8(obj2.image, obj2.samp ,obj2.fwhm ,obj2.tpm ,Affine , 'none', 80); + catch + fprintf('Please update SPM12!\n'); + Affine2 = spm_maff8(obj2.image, obj2.samp ,obj2.fwhm ,obj2.tpm ,Affine , 'none'); + end + end + else + Affine2 = Affine; + end + if any( isnan( Affine2(:) ) ) + Affine2 = Affine; + end + + %% + if 0 + %% + VF0 = spm_vol(obj.image(1)); + VF0.dt = [spm_type('UINT8') spm_platform('bigend')]; + VF0.dat = cat_vol_ctype((Ymi2.* Yb) * 200 ); + VF0.pinfo = repmat([1/255;0],1,size(Ymi2,3)); + if isfield(VF0,'private'), VF0 = rmfield(VF0,'private'); end + VF1 = spm_smoothto8bit(VF0,8); + % + VG = obj.tpm.V(1); + VG.dt = [spm_type('UINT8') spm_platform('bigend')]; + Ywp0 = 255/3 * (2*exp(obj.tpm.dat{1}) + 3*exp(obj.tpm.dat{2}) + exp(obj.tpm.dat{3})); + Ywp0(Ywp0>=255) = 0; + if isfield(VG,'dat'), VG = rmfield(VG,'dat'); end + VG.dat = cat_vol_ctype( Ywp0 ); + VG.pinfo = repmat([1;0],1,obj.tpm.V(1).dim(3)); + if isfield(VF,'private'), VG = rmfield(VG,'private'); end + VG1 = spm_smoothto8bit(VG,1); + aflags = struct('sep',obj.samp,'regtype','subj','WG',[],'WF',[],'globnorm',1); + aflags.sep = max(aflags.sep,max(sqrt(sum(VG(1).mat(1:3,1:3).^2)))); + aflags.sep = max(aflags.sep,max(sqrt(sum(VF(1).mat(1:3,1:3).^2)))); + % + [Affine2,affscale1] = spm_affreg(VG1, VF1, aflags, Affine, 1); + end + %% + % imat = spm_imatrix(Affine2); imat(7:9)=imat(7:9)*1.02; Affine2 = spm_matrix(imat); + %% + if 0 + %% visual control for development and debugging + VF = spm_vol(obj.image(1)); + VFa = VF; VFa.mat = Affine2 * VF.mat; %Fa.mat = res0(2).Affine * VF.mat; + if isfield(VFa,'dat'), VFa = rmfield(VFa,'dat'); end + [Vmsk,Ybb] = cat_vol_imcalc([VFa,spm_vol(Pb)],Pbt,'i2',struct('interp',3,'verb',0,'mask',-1)); + %[Vmsk,Yb] = cat_vol_imcalc([VFa;obj2.tpm.V(1:3)],Pbt,'i2 + i3 + i4',struct('interp',3,'verb',0)); + %[Vmsk,Yb] = cat_vol_imcalc([VFa;obj.tpm.V(5)],Pbt,'i2',struct('interp',3,'verb',0)); + %% + ds('d2sm','a',1,single(obj2.image.dat)/255,Ymi .* (0.3 + 0.7*(Ybb>0.5)),150) + %% + ds('d2sm','a',1,Ymi2.*Yb,Ymi .* (0.3 + 0.7*(Ybb>0.5)),120) + + end + cat_progress_bar('Clear'); + spm_progress_bar('Clear'); +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_io_checkdepfiles.m",".m","3826","103","function [S,Stype,removed] = cat_io_checkdepfiles(S,usedummy) +% _________________________________________________________________________ +% Remove non-existing files from the (SPM dependency) variable S. +% If there is only one file than create a dummy file to avoid batch errors. +% However, this may cause larger problems and is false by default and print +% an error message (just print a message, no real error). +% Moreover, it is possible that removing an entry can cause problems in +% related datasets that count on a specific file order, so a message is +% printed even in this case ... +% +% S = cat_io_checkdepfiles(S); +% +% [S,Stype] = cat_io_checkdepfiles(S,usedummy) +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + + if ~exist('usedummy','var') + usedummy = 0; + end + + Stype = ''; + removed = 0; + + if ischar(S) + for i = 1:size(S,1) + if ~exist(S(i,:),'file') + % Here, I remove just one element that is missing (e.g. one failed + % preprocessing). However, a following job (e.g. smoothing) does + % not count on it. + [pp,ff,ee] = spm_fileparts(S(i,:)); + S(i,:) = ''; + Stype = ee; + removed = 1; + % prevent interpreting backslash as escape character + removeFile = strrep(fullfile(pp,[ff ee]), '\', '\\'); + cat_io_cprintf('warn',sprintf(' Remove ""%s"" from dependency list because it does not exist!\n',removeFile)); + end + end + elseif iscell(S) + for i = 1:numel(S) + S{i} = cat_io_checkdepfiles( S{i} , usedummy ); + end + elseif isstruct(S) + %% + FN = fieldnames(S); + for i = 1:numel(FN) + SFN = S.(FN{i}); + for ii = 1:numel( S.(FN{i}) ) + SFNi = SFN(ii); + [SFNi,SFNtype,removed] = cat_io_checkdepfiles( SFNi ,usedummy ); + SFN(ii) = SFNi; + clear SFNi; + end + if isstruct(SFN)==0 + if isscalar(SFN) && size(SFN{1},1)==0 && ~isequal(SFN,S.(FN{i})) + if usedummy + SFN = {create_dummy_volume(SFNtype)}; + else + % Here, the full entry of a class of files becomes empty and this + % of cause will trouble an following job (empty imput). + % I give not further file information because these were given by + % the upper warning! + cat_io_cprintf('err',sprintf(['One or multiple files do not exist and were removed from the dependency list \n' ... + 'and following batches will may not work correctly!\n\n'])); + SFN = {}; + end + elseif removed + cat_io_cprintf('warn',sprintf([ + 'One or multiple files do not exist and were removed from the dependency list' \n ... + 'and following batches those file input number and order is relevant may do not work properly!\n\n'])); + end + end + S.(FN{i}) = SFN; + + clear SFN; + end + end +end +function Pdummy = create_dummy_volume(type) + switch type + case '.nii' + Pvol = fullfile(cat_get_defaults('extopts.pth_templates'),'cat.nii'); + Pdummy = fullfile(fileparts(mfilename('fullpath')),'cattest','batchdummy.nii'); + if ~exist( fileparts(Pdummy) , 'dir') + mkdir( fileparts(Pdummy) ); + end + copyfile(Pvol,Pdummy); + case {'.xml','.csv','.txt',''} + Pvol = fullfile(cat_get_defaults('extopts.pth_templates'),'mori.csv'); + Pdummy = fullfile(fileparts(mfilename('fullpath')),'cattest',['batchdummy' type]); + if ~exist( fileparts(Pdummy) , 'dir') + mkdir( fileparts(Pdummy) ); + end + copyfile(Pvol,Pdummy); + end +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_vol_qa.m",".m","44132","1133","function varargout = cat_vol_qa(action,varargin) +% CAT Preprocessing T1 Quality Control +% ______________________________________________________________________ +% +% Estimation of image quality measures like noise, inhomogeneity, +% contrast, resolution, etc. and scaling for school marks. +% +% [QAS,QAM] = cat_vol_qa(action,varargin) +% +% action .. +% 1) 'caterr' .. short version without image analysis used in the main +% CAT12 preprocessing. +% +% 2) 'cat12ver' .. process with an older cat_vol_qa version +% To use older versions, they have to be renamed (including all +% internal calls) and added to the update_rating subfunction here. +% +% 3) 'cat12' .. CAT12 internal preprocessing interface +% (this is the processing case that is also called in all other cases) +% +% [QAS,QAM] = cat_vol_qa('cat12',Yp0,Po,Ym,res[,opt]) +% +% Pp0 .. segmentation files (p0*.nii) +% Po .. original files (*.nii) +% Pm .. modified files (m*.nii) +% Yp0 .. segmentation image matrix +% Ym .. modified image matrix +% +% opt = parameter structure +% opt.verb = verbose level [ 0=nothing | 1=points | 2*=times ] +% opt.redres = resolution in mm for intensity scaling [ 4* ]; +% opt.write_csv = final cms-file +% opt.write_xml = images base xml-file +% opt.sortQATm = sort QATm output +% opt.orgval = original QAM results (no marks) +% opt.recalc = +% opt.avgfactor = +% opt.prefix = prefix of xml output file (default cat_*.xml) +% +% 4) 'p0' .. direct call +% +% qa = cat_vol_qa('p0',Pp0,opt); +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% +% $Id$ +% ______________________________________________________________________ + +%#ok<*ASGLU> + + % init output + QAS = struct(); + QAR = struct(); + + if nargin == 0, help cat_vol_qa; return; end + + if ischar(action) && strcmp(action,'getdef') + varargout{1} = upate_rating(struct(),varargin{1},1); + return + end + + if isstruct(action) + if isfield(action,'reportfolder') && isempty(action.reportfolder) + mrifolder = ''; + reportfolder = ''; + else + mrifolder = 'mri'; + reportfolder = 'report'; + end + else + try + switch action + case 'cat12err' + [mrifolder, reportfolder] = cat_io_subfolders(varargin{1}.job.data{1},varargin{1}.job); + case 'cat12' + [mrifolder, reportfolder] = cat_io_subfolders(varargin{2},varargin{6}.job); + case 'cat12ver' + if isfield(varargin{6},'reportfolder') && isempty(varargin{6}.reportfolder) + mrifolder = ''; + reportfolder = ''; + else + mrifolder = 'mri'; + reportfolder = 'report'; + end + otherwise + [mrifolder, reportfolder] = cat_io_subfolders(varargin{4}.catlog,varargin{6}.job); + end + catch + mrifolder = 'mri'; + reportfolder = 'report'; + end + end + + + % handling of batch calls, where action is the batch job-structure from + % SPM, and other actions used later + action2 = action; + if isstruct(action) + % SPM batch structure + if isfield(action,'model') + if isfield(action.model,'catp0') + Po = action.images; + Pp0 = action.model.catp0; + if numel(Po)~=numel(Pp0) && isscalar(Pp0) + Pp0 = repmat(Pp0,numel(Po),1); + end + Pm = action.images; + action.data = Pp0; + elseif isfield(action.model,'spmc0') + Po = action.images; + Pp0 = action.model.spmc0; + if numel(Po)~=numel(Pp0) && isscalar(Pp0) + Pp0 = repmat(Pp0,numel(Po),1); + end + Pm = action.images; + action.data = Pp0; + elseif isfield(action.model,'spmc1') + %% SPM case where the spmc1 should point to all other segmentation files + + % prepare and check other input files + spmp0ne = false(numel(action.model.spmc1),1); + for si = 1:numel(action.model.spmc1) + [pp,ff,ee] = spm_fileparts( action.model.spmc1{si} ); + action.model.spmp0{si,1} = fullfile(pp,['c0' ff(3:end) ee]); + action.model.spmc2{si,1} = fullfile(pp,['c2' ff(3:end) ee]); + action.model.spmc3{si,1} = fullfile(pp,['c3' ff(3:end) ee]); + spmp0ne(si,1) = ~exist(action.model.spmp0{si},'file'); + end + + % prepare batch that produce label maps + if sum(spmp0ne)>0 + fprintf('Prepare CGW-label maps:\n') + mjob.images{1} = action.images(spmp0ne); + mjob.images{2} = action.model.spmc3(spmp0ne); % CSF + mjob.images{3} = action.model.spmc1(spmp0ne); % GM + mjob.images{4} = action.model.spmc2(spmp0ne); % WM + mjob.expression = 'i1*0 + i2*1 + i3*2 + i4*3'; % the first one is just for the name + mjob.prefix = 'c0'; + mjob.verb = 0; + mjob.cleanup = 0; + mjob.ignoreBIDS = 1; + cat_vol_mimcalc(mjob); + end + + %% run QC + action2 = rmfield(action,'model'); + action2.model.spmc0 = action.model.spmp0; + action2.reportfolder = ''; + + out = cat_vol_qa(action2,varargin); + + varargout{1}.data = action2.images; + varargout{2} = out; + for pi = 1:numel(action2.images) + [pp,ff,ee] = spm_fileparts(action2.images{pi}); + varargout{1}.xmls{pi} = fullfile(pp,reportfolder,[action2.opts.prefix ff '.xml']); + end + return + + elseif isfield(action.model,'seg') + %% error('no implemented yet') + fprintf('Prepare CGW-label maps:\n') + mjob.images{1,1} = action.images; + mjob.images{2,1} = action.model.seg.cm; + mjob.images{3,1} = action.model.seg.gm; + mjob.images{4,1} = action.model.seg.wm; + mjob.expression = 'i1*0 + i2*1 + i3*2 + i4*3'; % the first one is just for the name + mjob.prefix = 'p0'; % + mjob.verb = 0; + cat_vol_mimcalc(mjob); + + action2 = rmfield(action,'model'); + action2.model.catp0 = spm_file(action.images,'prefix','p0'); + + varargout{:} = cat_vol_qa(action2,varargin); + return + + end + end + if isfield(action,'data') + Pp0 = action.data; + end + action = 'p0'; + end + if nargin==3 && isstruct(varargin{2}) && isstruct(varargin{2}) + opt = cat_check('checkinopt',varargin{2},defaults); + nopt = 1; + elseif nargin>6 && isstruct(varargin{6}) && isstruct(varargin{6}) + opt = cat_check('checkinopt',varargin{6},defaults); + nopt = 1; + else + if isstruct(action2) + opt = cat_check('checkinopt',action2.opts,defaults); + else + opt = defaults; + end + nopt = 0; + if isfield(opt,'recalc') && opt.recalc, opt.rerun = opt.recalc; end + end + if cat_io_contains(opt.prefix,'VERSION') + opt.prefix = strrep( opt.prefix , 'VERSION', strrep( opt.version ,'_','')); + end + if isfield(opt,'model') && isfield(opt.model,'spmc1') + opt.reportfolder = ''; + else + opt.reportfolder = reportfolder; + end + + + % check input by action + switch action + case 'p0' + % segment image cases + if nargin<=3 && ( ~exist('Pp0','var') || isempty(Pp0) ) + if (nargin-nopt)<2 + Pp0 = cellstr(spm_select(inf,'image',... + 'select p0-segment image',{},pwd,'^p0.*')); + if isempty(Pp0{1}), return; end + else + Pp0 = varargin{1}; + end + if numel(action)==2 + Po = Pp0; Pm = Pp0; + for fi=1:numel(Pp0) + [pp,ff,ee] = spm_fileparts(Pp0{fi}); + if strcmp(ee,'.gz'), ee =[ff(end-3:end) ee]; ff = ff(1:end-4); end + [ppa,ppb] = spm_fileparts(pp); + if strcmp(ppb,'mri'), ppo = ppa; else, ppo = pp; end + + deri = min([ strfind(ppo,[filesep 'derivatives' filesep 'CAT']), ... + strfind(ppo,[filesep 'derivatives' filesep 'SPM']), ... + strfind(ppo,[filesep 'derivatives' filesep 'T1P'])]); + if isempty( deri ) + if cat_io_contains(ff,'qcseg') + ff = strrep(ff,'p0_qcseg_',''); + Po{fi} = fullfile(ppo,[ff ee]); + elseif strcmp(ff(1:2),'p0') || strcmp(ff(1:2),'c1') + Po{fi} = fullfile(ppo,[ff(3:end) ee]); + elseif cat_io_contains(ff,'synthseg_p0') + Po{fi} = fullfile(ppo,[strrep(ff,'synthseg_p0','') ee]); + end + else + BIDShome = fileparts(ppo(1:deri(1))); + fsep = strfind( ppo(deri(1) + 16:end) , filesep ) + deri(1) + 16; + if isempty(fsep) + Pofi = cat_vol_findfiles(BIDShome,[ff(3:end) '.nii.gz']); + if isempty(Pofi) + Pofi = cat_vol_findfiles(BIDShome,[ff(3:end) '.nii']); + end + Po{fi} = Pofi{1}; + else + Po{fi} = fullfile( BIDShome, ppo(fsep(1):end) , [ff(3:end) ee] ); + end + end + Pm{fi} = fullfile(pp,['m' ff(3:end) ee]); + if ~exist(Pm{fi},'file'), Pm{fi}=[Pm{fi} '.gz']; end + if ~exist(Pm{fi},'file'), Pm{fi}=''; end + end + else + Po = cellstr(spm_select(repmat(numel(Pp0),1,2),... + 'image','select original image(s)',{},pwd,'.*')); + Pm = cellstr(spm_select(repmat(numel(Pp0),1,2),... + 'image','select modified image(s)',{},pwd,'.*')); + end + + elseif nargin<=5 && ( ~exist('Pp0','var') || isempty(Pp0) ) + Pp0 = varargin{1}; + Po = varargin{2}; + Pm = varargin{3}; + + elseif ( ~exist('Pp0','var') || isempty(Pp0) ) + error('MATLAB:cat_vol_qa:inputerror',... + 'Wrong number/structure of input elements!'); + end + + case {'cat12ver', 'cat12'} + % nothing to do + + case 'cat12err' + % again ? + %opt = cat_check('checkinopt',varargin{6},defaults); + + otherwise + + error('MATLAB:cat_vol_qa:inputerror',... + 'Wrong number/structure of input elements!'); + end + if ~exist('species','var'), species='human'; end + + + % + % -------------------------------------------------------------------- + [QA,QMAfn] = cat_stat_marks('init'); + % remove res_ECR in case of given older versions + if any( strcmp(opt.version, opt.versions0) ) + QMAfn( cat_io_contains(QMAfn,'res_ECR')) = []; + end + % remove FEC in case of given older versions + if any( strcmp(opt.version, opt.versions1) ) + QMAfn( cat_io_contains(QMAfn,'FEC')) = []; + end + stime = clock; + + + + + % Print options + % -------------------------------------------------------------------- + Cheader = {'scan'}; + Theader = sprintf(sprintf('%%%ds:',opt.snspace(1)-1),'scan'); + Tline = sprintf('%%5d) %%%ds:',opt.snspace(1)-8); + Tline2 = sprintf('%%5d) %%6s%%%ds:',opt.snspace(1)-14); + Tavg = sprintf('%%%ds:',opt.snspace(1)-1); + TlineE = sprintf('%%5d) %%%ds: %%s',opt.snspace(1)-7); + for fi=1:numel(QMAfn) + Cheader = [Cheader QMAfn{fi}]; %#ok + QAMfni = strrep( QMAfn{fi} ,'_',''); + Theader = sprintf(sprintf('%%s%%%ds',opt.snspace(2)),Theader,... + cat_io_strrep( QAMfni,{'contrastr';'resECR'},{'CON';'ECR'}) ); %(1:min(opt.snspace(2)-1,numel(QMAfn{fi}))) + Tline = sprintf('%s%%%d.%df',Tline,opt.snspace(2),opt.snspace(3)); + Tline2 = sprintf('%s%%%d.%df',Tline2,opt.snspace(2),opt.snspace(3)); + Tavg = sprintf('%s%%%d.%df',Tavg,opt.snspace(2),opt.snspace(3)); + end + Cheader = [Cheader 'IQR']; + Theader = sprintf(sprintf('%%s%%%ds',opt.snspace(2)),Theader,'IQR'); + if ~any( strcmp(opt.version,opt.versions0) ) % ~any( cat_io_contains(opt.version,opt.versions0) ) + Tline = sprintf('%s%%%d.%df',Tline,opt.snspace(2),opt.snspace(3)); + Tline2 = sprintf('%s%%%d.%df',Tline2,opt.snspace(2),opt.snspace(3)); + Cheader = [Cheader 'SIQR']; + Theader = sprintf(sprintf('%%s%%%ds',opt.snspace(2)),Theader,'SIQR'); + Tavg = sprintf('%s%%%d.%df',Tavg,opt.snspace(2),opt.snspace(3)); + end + Tline = sprintf('%s%%%d.%df%%s\n',Tline,opt.snspace(2),opt.snspace(3)); + Tline2 = sprintf('%s%%%d.%df\n',Tline2,opt.snspace(2),opt.snspace(3)); + Tavg = sprintf('%s%%%d.%df\n',Tavg,opt.snspace(2),opt.snspace(3)); + + + + % estimation part + switch action + case 'cat12' + % Direct call of the specific QC version with input images given by the + % varargin structure used in the CAT12 pipeline (processing of one case) +%sprintf('[QAS,QAR] = %s(''cat12'',varargin{:});', opt.version) +if isstruct(varargin{end-1}), varargin{end-1}.write_xml = 0; end + + eval(sprintf('[QAS,QAR] = %s(''cat12'',varargin{:});', opt.version)); + QAR = upate_rating(QAS,opt.version); + + case 'p0' + % Default case of multiple input files where we have to load the images + % and will also show the resulting ratings (batch processing of many + % files. + + % return for empty input + if isempty(Pp0) || (isempty(Pp0{1}) && numel(Pp0)<=1) + cat_io_cprintf('com','No images for QA!\n'); + return + end + + % remove num entry from SPM GUI input + Po = cat_io_strrep(Po, {'.nii.gz,1','.nii,1'},{'.nii.gz','.nii'}); + Pm = cat_io_strrep(Pm, {'.nii.gz,1','.nii,1'},{'.nii.gz','.nii'}); + Pp0 = cat_io_strrep(Pp0,{'.nii.gz,1','.nii,1'},{'.nii.gz','.nii'}); + + % if files are zipped + Poe = cellfun(@(x) exist(x,'file'), Po); + Po(Poe==0) = spm_file(Po(Poe==0),'ext','.nii.gz'); clear Poe + + + % name segmentation if possible + if isempty(Pp0{1}) + Pp0 = Po; + [pp,ff,ee] = spm_fileparts(Po{1}); + segment = 'internal'; + else + [pp,ff,ee] = spm_fileparts(Pp0{1}); + switch ff(1:2) + case 'sy', segment = 'synthseg'; + case 'c0', segment = 'SPM12'; + case 'c1', segment = 'SPM12'; + case 'p0', segment = 'CAT12'; + otherwise, segment = 'internal'; + end + end + % print title + if opt.verb>1 + fprintf('\nCAT Preprocessing T1 Quality Control ('); + [ver_cat, rev_cat] = cat_version; + cat_io_cprintf('blue',' %s',opt.version ); + cat_io_cprintf('n',' ,'); + cat_io_cprintf('blue',' %s',segment ); + cat_io_cprintf('n',' , %s ):\n',sprintf('Rev: %s %s', ver_cat, rev_cat) ); + fprintf('\n%s\n%s\n', Theader,repmat('-',size(Theader))); + end + + % preare variables + qamat = nan(numel(Po),numel(QMAfn)); + qamatm = nan(numel(Po),numel(QMAfn)); + mqamatm = 10.5*ones(numel(Po),1 + ~any( strcmp(opt.version,opt.versions0) )); + QAS = struct(); + QAR = struct(); + + QAR.mark2rps = @(mark) min(100,max(0,105 - mark*10)) + isnan(mark).*mark; + + + + % loop for multiple files + % ------------------------------------------------------------------- + for fi = 1:numel(Pp0) + stime1 = clock; + + % setup the XML file name + [pp,ff,ee] = spm_fileparts( strrep(Pp0{fi},'.nii.gz','.nii') ); ff(1:2) = []; + [ppa,ppb] = spm_fileparts(pp); + if strcmp(ppb,'mri'), ppo = fullfile(ppa,reportfolder); else, ppo = pp; end + sfile = fullfile(ppo,[opt.prefix ff '.xml']); + + if ~exist( sfile ,'file') + % test if file may exist in raw directory + ppo = spm_fileparts( strrep(Po{fi},'.nii.gz','.nii') ); + sfileo = spm_file(Po{fi},'path',ppo,'prefix',opt.prefix,'ext','.xml'); + if exist(sfileo,'file') + sfile = sfileo; + else + sfileo = spm_file(Po{fi},'path',fullfile(ppo,'report'),'prefix',opt.prefix,'ext','.xml'); + if exist(sfileo,'file') + sfile = sfileo; + end + end + end + + if ~exist( sfile ,'file') + % not processed (eg. no additional comment) + run = 1; + rerun = ''; + elseif opt.rerun == 2 || strcmp(opt.prefix,'tmp') + % forced processing + run = 1; + if cat_get_defaults('extopts.expertgui') > 1 + rerun = ' forced'; + else + rerun = ''; + end + elseif (opt.rerun == 0 && cat_io_rerun(Po{fi}, sfile , 0 , 0)) || ... load if the QC file is available and newer than the input + (opt.rerun == 1 && ( cat_io_rerun(Po{fi}, sfile , 0 , 0 ) || ... load if the QC file is newer than the input and function + (0 && cat_io_rerun(which(opt.version), sfile , 0 , 0)) ) ) + run = 1; + rerun = ' updated'; + else + run = 0; + rerun = ' loaded'; + end + + if ~run + % If no reprocessing is required then just try to load the values + % from the QC XML but update the rating + try + QASfi = cat_io_xml(sfile); + QARfi = upate_rating(QASfi,opt.version); + cat_io_xml( sfile, QARfi, 'write+'); + + %QASfix = cat_io_updateStruct(QASfi, QARfi); + + % try to update the QC structure + [QAS, QAR, qamat, qamatm, mqamatm] = updateQAstructure(QAS, ... + QASfi, QAR, QARfi, qamat, qamatm, mqamatm, QMAfn, fi); + + rerun = ' loaded'; + catch e + % in case of problems we have to reprocess + run = 1; + rerun = ' reprocessed'; + end + end + + clear e + if run + % try to run QC estimation + + % load images + try + [Yp0,Ym,Vo] = getImages(Pp0,Po,Pm,fi); + catch e + % setup default output + opt2 = opt; + opt2.subj = fi; + opt2.job = cat_get_defaults; + opt2.job.channel.vols{fi} = [Po{fi} ',1']; + opt2.job.data{fi} = [Po{fi} ',1']; + opt2.job.extopts.darteltpms = {}; + opt2.job.extopts.shootingtpms = {}; + opt2.job.extopts.subfolder = isfield(action,'model') && isfield(action.model,'spmc1'); + opt2.caterr = struct(); + opt2.caterrtxt = ''; + + [QASfi,QARfi] = cat12err(opt2,mrifolder,reportfolder); + + % try to update the QC structure + [QAS, QAR, qamat, qamatm, mqamatm] = updateQAstructure(QAS, ... + QASfi, QAR, QARfi, qamat, qamatm, mqamatm, QMAfn, fi); + + continue + end + + % general function called from CAT12 + if ~exist( Po{fi} ,'file') + continue + end + + evalc('res.image = spm_vol(Po{fi});'); + + if ~isempty(Yp0) + try + [QASfi,QARfi] = cat_vol_qa('cat12ver',Yp0,Vo,Ym,res,species,opt,Pp0{fi}); + catch + cat_io_cprintf('warn',sprintf('Failed ...run cat_vol_qa202412')); + opt2 = opt; opt2.version = 'cat_vol_qa202412'; + [QASfi,QARfi] = cat_vol_qa('cat12ver',Yp0,Vo,Ym,res,species,opt2,Pp0{fi}); + end + else + opt2 = opt; opt2.version = 'cat_vol_qa202412'; + [QASfi,QARfi] = cat_vol_qa('cat12ver',Yp0,Vo,Ym,res,species,opt2,Pp0{fi}); + end + try + % try to update the QC structure + [QAS, QAR, qamat, qamatm, mqamatm] = updateQAstructure(QAS, ... + QASfi, QAR, QARfi, qamat, qamatm, mqamatm, QMAfn, fi); + + catch + %% this is not a good solution ! + opt2 = opt; + opt2.subj = fi; + opt2.job = cat_get_defaults; + opt2.job.channel.vols{fi} = [Po{fi} ',1']; + opt2.job.data{fi} = [Po{fi} ',1']; + opt2.job.extopts.darteltpms = {}; + opt2.job.extopts.shootingtpms = {}; + opt2.caterr = struct(); + opt2.caterrtxt = ''; + + [QASfi,QARfi] = cat12err(opt2,mrifolder,reportfolder); + + %% try to update the QC structure + [QAS, QAR, qamat, qamatm, mqamatm] = updateQAstructure(QAS, ... + QASfi, QAR, QARfi, qamat, qamatm, mqamatm, QMAfn, fi); + + end + end + + % print result + if opt.verb>1 + % update the rerun parameter + rerun = sprintf('%s%3.0fs',rerun, etime(clock,stime1)); + + if exist('e','var') + % write short error-message in case of error + switch e.identifier + case {'cat_vol_qa:noYo','cat_vol_qa:noYm','cat_vol_qa:badSegmentation'} + em = e.identifier; + case 'cat_vol_qa:missingVersion' + rethrow(e); + case 'MATLAB:badsubscript' + otherwise + em = ['ERROR:\n' repmat(' ',1,10) e.message '\n']; + for ei=1:numel(e.stack) + em = sprintf('%s%s%5d: %s\n',em,repmat(' ',1,10),... + e.stack(ei).line(end),e.stack(ei).name); + end + end + + [pp,ff] = spm_fileparts(Po{fi}); + QAS(fi).filedata.fnames = [spm_str_manip(pp,sprintf('k%d',floor( (opt.snspace(1)-19) /3) - 1)),'/',... + spm_str_manip(ff,sprintf('k%d',(opt.snspace(1)-19) - floor((opt.snspace(1)-14)/3)))]; + cat_io_cprintf(opt.MarkColor(end,:),sprintf(TlineE,fi,Pp0{fi},[em '\n'])); + else + % write measurements and time + if opt.orgval + cat_io_cprintf(opt.MarkColor(min(size(opt.MarkColor,1),max(1,floor( mqamatm(fi,end)/9.5 * ... + size(opt.MarkColor,1)))),:),sprintf(Tline,fi,... + spm_str_manip(QAS(fi).filedata.fname,['a' num2str(opt.snspace(1) - 14)]),... + qamat(fi,:), max(1,min(9.5,mqamatm(fi,:))), rerun)); + else + %% + cat_io_cprintf(opt.MarkColor(min(size(opt.MarkColor,1),max(1,floor( mqamatm(fi,end)/9.5 * ... + size(opt.MarkColor,1)))),:),sprintf(Tline,fi,... + spm_str_manip(QAS(fi).filedata.fname,['a' num2str(opt.snspace(1) - 14)]),... + qamatm(fi,:), max(1,min(9.5,mqamatm(fi,:))), rerun)); + end + end + end + end + + + % sort by mean mark + % ------------------------------------------------------------------- + if opt.sortQATm && numel(Po)>1 + % sort matrix + [smqamatm,smqamatmi] = sort(mqamatm(:,end),'ascend'); + sqamatm = qamatm(smqamatmi,:); + sqamat = qamat(smqamatmi,:); + + % print matrix + if opt.verb>0 + fprintf('%s\n',repmat('-',size(Theader))); + for fi = 1:numel(QAS) + if isfield( QAS(smqamatmi(fi)), 'filedata') && isfield( QAS(smqamatmi(fi)).filedata, 'fname') + fname = spm_str_manip( QAS(smqamatmi(fi)).filedata.fname , ['a' num2str(opt.snspace(1) - opt.snspace(2) - 14)] ); + else + fname = 'FILENAME ERROR'; + end + if opt.orgval + cat_io_cprintf(opt.MarkColor(max(1,min(size(opt.MarkColor,1),... + round( mqamatm(smqamatmi(fi),end)/9.5 * ... + size(opt.MarkColor,1)))),:),sprintf(... + Tline2,fi,sprintf('(%d)',smqamatmi(fi)),... + fname, sqamat(fi,:),max(1,min(10.5,mqamatm(smqamatmi(fi),:))))); + else + cat_io_cprintf(opt.MarkColor(max(1,min(size(opt.MarkColor,1),... + round( mqamatm(smqamatmi(fi),end)/9.5 * ... + size(opt.MarkColor,1)))),:),sprintf(... + Tline2,fi,sprintf('(%d)',smqamatmi(fi)),... + fname, sqamatm(fi,:),mqamatm(smqamatmi(fi),:))); + end + end + end + end + % print the results for each scan + if opt.verb>1 && numel(Pp0)>1 + fprintf('%s\n',repmat('-',size(Theader))); + if opt.orgval + fprintf(Tavg,'mean', cat_stat_nanmean(qamat,1), cat_stat_nanmean(mqamatm,1)); %#ok + fprintf(Tavg,'std' , cat_stat_nanstd(qamat,1), cat_stat_nanstd(mqamatm,1)); %#ok + else + fprintf(Tavg,'mean', cat_stat_nanmean(qamatm,1), cat_stat_nanmean(mqamatm,1)); %#ok + fprintf(Tavg,'std' , cat_stat_nanstd(qamatm,1), cat_stat_nanstd(mqamatm,1)); %#ok + end + end + if opt.verb>0, fprintf('\n'); end + + + + % result tables (cell structures) + % ---------------------------------------------------------------- + if nargout>2 && opt.write_csv + QAT = [Cheader(1:end-1); ... there is no mean for the original measures + Po , num2cell(qamat); ... + 'mean' , num2cell(cat_stat_nanmean(qamat,1)); ... + 'std' , num2cell( cat_stat_nanstd(qamat,1,1))]; + QATm = [Cheader; ... + Po , num2cell(qamatm) , ... + num2cell(cat_stat_nanmean(qamatm,2)); ... + 'mean' , num2cell(cat_stat_nanmean(qamatm,1)) , ... + num2cell(cat_stat_nanmean(mqamatm,1)); ... + 'std' , num2cell( cat_stat_nanstd(qamatm,1,1)), ... + num2cell( cat_stat_nanstd(mqamatm,1))]; + + + % write csv results + % -------------------------------------------------------------- + if opt.write_csv + pp = spm_fileparts(Pp0{1}); + cat_io_csv(fullfile(pp,reportfolder,[opt.prefix num2str(numel(Vo),'%04d') ... + 'cat_vol_qa_values.csv']),QAT); + cat_io_csv(fullfile(pp,reportfolder,[opt.prefix num2str(numel(Vo),'%04d') ... + 'cat_vol_qa_marks.csv']),QATm); + end + end + + if opt.verb>0 + fprintf('Quality Control for %d subject was done in %0.0fs\n', ... + numel(Pp0),etime(clock,stime)); fprintf('\n'); + end + + + + case 'cat12err' + opt = cat_check('checkinopt',varargin{6},defaults); + QAS = cat12err(opt,mrifolder,reportfolder); + + + case 'cat12ver' + % main processing with subversions + [pp,ff,ee] = spm_fileparts(strrep(varargin{2}.fname,'.nii.gz','.nii')); + + % Call of different versions of the QC: + % ------------------------------------------------------------------- + % estimation of the measures for the single case by different versions. + % To use other older cat_vol_qa versions copy them into a path and + % rename the filename and the all internal use of the functionname. + % Extend the default variable versions0 for older functions without + % SIQR and res_ECR measure. + % Older versions may use different parameters - check similar + % pepared verions. + % ------------------------------------------------------------------- + if isfield(opt,'version') + if ~exist(opt.version,'file') + error('cat_vol_qa:missingVersion','Selected QC version ""%s"" is not available! ',opt.version); + elseif ~strcmp(opt.version,mfilename) + switch opt.version + % in older versions some parameters where defined different + % and we need to update them + case {'cat_vol_qa201602'} + % here the + vx_vol = sqrt(sum(varargin{2}.mat(1:3,1:3).^2)); + Yp0toC = @(Yp0,c) 1-min(1,abs(Yp0-c)); + qa.subjectmeasures.vol_TIV = sum(varargin{1}(:)>0) ./ prod(vx_vol) / 1000; + for i = 1:3 + qa.subjectmeasures.vol_abs_CGW(i) = sum( Yp0toC(varargin{1}(:),i)) ./ prod(vx_vol) / 1000; + qa.subjectmeasures.vol_rel_CGW(i) = qa.subjectmeasures.vol_abs_CGW(i) ./ ... + qa.subjectmeasures.vol_TIV; + end + varargin2 = varargin; + varargin2{6}.job.extopts.subfolders = ~isempty(reportfolder); + eval(sprintf('[QAS,QAR] = %s(''cat12'',varargin2{1:4},struct(),varargin2{5:end});',opt.version)); + otherwise + varargin2 = varargin; + varargin2{6}.job.extopts.subfolders = ~isempty(reportfolder); + eval(sprintf('[QAS,QAR] = %s(''cat12'',varargin2{:});',opt.version)); + end + else + % setup the current/default version + varargin2 = varargin; + varargin2{6}.version = 'cat_vol_qa202310'; + varargin2{6}.job.extopts.subfolders = ~isempty(reportfolder); + eval(sprintf('[QAS,QAR] = %s(''cat12'',varargin2{:});', varargin2{6}.version)); + end + end + + % redo the quality rating, ie. measure scaling + QAR = upate_rating(QAS,opt.version); + QAS.subjectratings = QAR.subjectratings; + QAS.qualityratings = QAR.qualityratings; + + + if nargin>6 + pp0 = spm_fileparts(varargin{7}); + [ppx,ffx] = spm_fileparts(pp0); + if strcmp(ffx,'mri') + sfile = fullfile(ppx,reportfolder,[opt.prefix ff '.xml']); + catfile = fullfile(ppx,reportfolder,['cat_' ff '.xml']); + else + sfile = fullfile(pp0,[opt.prefix ff '.xml']); + catfile = fullfile(pp0,['cat_' ff '.xml']); + end + else + sfile = fullfile(pp,reportfolder,[opt.prefix ff '.xml']); + catfile = fullfile(pp,reportfolder,['cat_' ff '.xml']); + end + if exist(sfile,'file') + S = cat_io_xml( sfile ); + SN = cat_io_mergeStruct( S , QAS , [], 1); + elseif exist(catfile,'file') + S = cat_io_xml( catfile ); + SN = cat_io_mergeStruct( S , QAS , [], 1); + else + SN = QAS; + end + + cat_io_xml( sfile, SN ); + + + otherwise + % catched before + end + + % export + if strcmp(action,'cat12') % exist('Pp0','var') && isscalar(Pp0) && opt.write_xml + QAS.qualityratings = QAR.qualityratings; + QAS.subjectratings = QAR.subjectratings; + QAS.ratings_help = QAR.help; + + [pp,ff] = spm_fileparts(QAS.filedata.fname); + cat_io_xml( fullfile(pp,reportfolder,[opt.prefix ff '.xml']) ,QAS,'write+'); + cat_io_xml( fullfile(pp,reportfolder,[opt.prefix ff '.xml']) ,QAR,'write+'); %struct('QAS',QAS,'QAM',QAM) + end + + if (isempty(varargin) || isstruct(varargin{1}) || isstruct(action)) && exist('Pp0','var') + % SPM batch output case + varargout{1}.data = Pp0; + for pi = 1:numel(Pp0) + [pp,ff,ee] = spm_fileparts(Pp0{pi}); + varargout{1}.xmls{pi} = fullfile(pp,reportfolder,[opt.prefix ff '.xml']); + end + else + % processing output case + if nargout>1, varargout{2} = QAR; end + if nargout>0, varargout{1} = QAS; end + end +end +%========================================================================== +function [QAS, QAR, qamat, qamatm, mqamatm] = ... + updateQAstructure(QAS, QASfi, QAR, QARfi, qamat, qamatm, mqamatm, QMAfn, fi) +%updateQAstructure. Update the quality structure. + + try + QAS = cat_io_updateStruct(QAS,QASfi,0,fi); + QAR = cat_io_updateStruct(QAR,QARfi,0,fi); + catch + fprintf('ERROR-Struct'); + end + + % color for the differen mark cases + for fni = 1:numel(QMAfn) + if isfield(QAS(fi).qualitymeasures,QMAfn{fni}) + try + qamat(fi,fni) = QAS(fi).qualitymeasures.(QMAfn{fni}); + qamatm(fi,fni) = QAR(fi).qualityratings.(QMAfn{fni}); + catch + qamat(fi,fni) = QASfi.qualitymeasures.(QMAfn{fni}); + qamatm(fi,fni) = QARfi.qualityratings.(QMAfn{fni}); + end + end + end + try + mqamatm(fi,1) = QAR(fi).qualityratings.IQR; + catch + mqamatm(fi,1) = QASfi.qualityratings.IQR; + end + + if size(mqamatm,2)==2 + try + mqamatm(fi,2) = QAR(fi).qualityratings.SIQR; + catch + mqamatm(fi,2) = QARfi.qualityratings.SIQR; + end + end + + mqamatm(fi,:) = max(0,min(10.5, mqamatm(fi,:))); + +end +%========================================================================== +function [Yp0,Ym,Vo,p0rmse] = getImages(Pp0,Po,Pm,fi) +%getImages. Load major images for QC processing. +% +% [Yp0,Ym,Vo] = getImages(Pp0,Po,Pm,fi) +% +% Yp0 .. (resampled) segmentation as labelmap (0-BG, 1-CSF, 2-GM, 3-WM) +% Ym .. bias-corrected image +% Vo .. original image + + if numel(Pp0{fi})>1 && Pp0{fi}(end-1)==',', Pp0{fi}(end-1:end) = []; end + if numel(Po{fi})>1 && Po{fi}(end-1)==',', Po{fi}(end-1:end) = []; end + if numel(Pm{fi})>1 && Pm{fi}(end-1)==',', Pm{fi}(end-1:end) = []; end + + if (isempty(Po{fi}) || ~exist(Po{fi},'file')) && ... + ~isempty(Pm{fi}) && exist(Pm{fi},'file') + Po{fi} = Pm{fi}; + if 0 %cat_get_defaults('extopts.expertgui') % RD202508: deactived as we only use the original now + cat_io_cprintf('warn','Cannot find/open original image use bias corrected: %80s\n',Pm{fi}) + end + elseif (isempty(Pm{fi}) || ~exist(Pm{fi},'file')) && ... + ~isempty(Po{fi}) && exist(Po{fi},'file') + if exist( [Pm{fi} '.gz'] , 'file') + Pm{fi} = [Pm{fi} '.gz']; + else + Pm{fi} = Po{fi}; + if 0 %cat_get_defaults('extopts.expertgui') % RD202508: deactived as we only use the original now + cat_io_cprintf('warn','Cannot find/open bias corrected image use original: %80s\n',Po{fi}) + end + end + end + if 0 %isempty(Pp0{fi}) || ~exist(Pp0{fi},'file') + % RD202508: deactived as we run a simple segmentation + warning elsewhere + cat_io_cprintf('err','Cannot find/open segmentation: \n %s\n',Pp0{fi}) + end + + + % handle gzipped original data + [pp,ff,ee] = spm_fileparts(Po{fi}); + if exist(fullfile(pp,[ff ee]),'file') + evalc('Vo = spm_vol(Po{fi});'); + %elseif exist(fullfile(pp,[ff ee '.gz']),'file') + % gunzip(fullfile(pp,[ff ee '.gz'])); + % Vo = spm_vol(Po{fi}); + % delete(fullfile(pp,[ff ee '.gz'])); + else + error('cat_vol_qa:noYo','No original image.'); + end + + % load further images - bias corrected Ym and segmentation Yp0 + evalc('Vm = spm_vol(Pm{fi})'); + [pp0,ff0,ee0] = spm_fileparts(Pp0{fi}); + if cat_io_contains(ff0,'qcseg') + Yp0 = []; + else + switch ff0(1:2) + case {'p0','sy','c0'} % cat and other label map (use c0 for SPM) + evalc('Vp0 = spm_vol(Pp0{fi});'); + if ~isempty(Vm) && any(Vp0.dim ~= Vm.dim) + [Vx,Yp0] = cat_vol_imcalc(Vp0,Vm,'i1',struct('interp',2,'verb',0)); % linear interp + else + evalc('Yp0 = single(spm_read_vols(Vp0))'); + end + case 'c1' + tval = [2 3 1]; + for ci = 1:3 + evalc('Vc = spm_vol(fullfile(pp0,sprintf(''c%d%s%s'',ci,ff0(3:end),ee0)));'); + if ci == 1 + evalc('Yp0 = tval(ci) * single(spm_read_vols(Vc))'); + else + evalc('Yp0 = Yp0 + tval(ci) * single(spm_read_vols(Vc))'); + end + end + otherwise + Yp0 = []; + end + end + Yp0(isnan(Yp0) | isinf(Yp0)) = 0; + + % Internal bias correction to handle the original images as the processed + % bias corrected image in CAT is also intensity normalized and endoised. + vx_vol = sqrt(sum(Vo.mat(1:3,1:3).^2)); + evalc('Ym = single(spm_read_vols(spm_vol(Po{fi})))'); + %WMth = cat_stat_nanmedian(Ym(Yp0>2.9)); + if ~isempty(Yp0) + Ym(isnan(Yp0) | isinf(Yp0)) = 0; + %Yw = cat_vol_morph( Yp0>2.95 , 'e',0,vx_vol) & cat_vol_morph( Yp0>2.25 , 'e',1,vx_vol); RD20250907: erode to hard for SPM + Yw = Yp0>2.9; % ### RD20250910: however this is a bit too simple in case of segmentation bugs and a check for local outliers would be good + Yb = cat_vol_approx( Ym .* Yw + Yw .* min(Ym(:)) ,'rec') - min(Ym(:)); + Ym = Ym ./ max(eps,Yb); + end + + % Detection of possible preprocessing issues in case the segmentation + % varies strongly from the original image. We intensity normalize here + % the Yp0 map to fit to the Ym. WMHs could cause problems but this is + % even intended. + if ~isempty(Yp0) + Yp0toC = @(Yp0,c) 1-min(1,abs(Yp0-c)); + T3th = zeros(1,3); for ci = 1:3, T3th(ci) = cat_stat_nanmedian(Ym( Yp0toC(Yp0(:),ci) > 0.95 )); end + Yp0t = zeros(size(Yp0)); for ci = 1:3, Yp0t = Yp0t + T3th(ci) .* Yp0toC(Yp0,ci); end + p0rmse = (cat_stat_nanmean(Ym(Yp0(:)>0) - Yp0t(Yp0(:)>0)).^2)^0.5; + if p0rmse>0.2 + cat_io_cprintf('warn', ['Segmentation is maybe not fitting to the image ' ... + '(RMSE(Ym,Yp0)=%0.2f)?:\n %s\n %s\n'], p0rmse,Pm{fi}, Pp0{fi}); + end + end +end +%========================================================================== +function [QAS,QAR] = cat12err(opt,mrifolder,reportfolder) +%cat12err. Create short report in case of CAT preprocessing error. +% This report contain basic parameters used for the CAT error report +% creation in cat_io_report. + + % file information + % ----------------------------------------------------------------------- + [pp,ff,ee] = spm_fileparts(opt.job.channel.vols{opt.subj}); + [QAS.filedata.path,QAS.filedata.file] = ... + spm_fileparts(opt.job.channel.vols{opt.subj}); + QAS.filedata.fname = opt.job.data{opt.subj}; + QAS.filedata.F = fullfile(pp,[ff ee]); + QAS.filedata.Fm = fullfile(pp,mrifolder,['m' ff ee]); + QAS.filedata.Fp0 = fullfile(pp,mrifolder,['p0' ff ee]); + QAS.filedata.fnames = [ + spm_str_manip(pp,sprintf('k%d', ... + floor( max(opt.snspace(1)-19-ff,opt.snspace(1)-19)/3) - 1)), '/',... + spm_str_manip(ff,sprintf('k%d',... + (opt.snspace(1)-19) - floor((opt.snspace(1)-14)/3))), ... + ]; + + % load header for resolution + if exist(QAS.filedata.F,'file') + V = spm_vol(QAS.filedata.F); + elseif exist(QAS.filedata.Fm,'file') + V = spm_vol(QAS.filedata.Fm); + elseif exist(QAS.filedata.Fp0,'file') + V = spm_vol(QAS.filedata.Fp0); + else + vx_vol = [0 0 0]; + end + if ~exist('vx_vol','var') + vx_vol = sqrt(sum(V.mat(1:3,1:3).^2)); + end + + % software, parameter and job information + % ----------------------------------------------------------------------- + [ver_cat, rev_cat] = cat_version; + ver_cat = ver_cat(4:end); % remove leading CAT + [nam,rev_spm] = spm('Ver'); + QAS.software.version_spm = rev_spm; + if strcmpi(spm_check_version,'octave') + QAS.software.version_octave = version; + else + A = ver; + for i=1:length(A) + if strcmp(A(i).Name,'MATLAB') + QAS.software.version_matlab = A(i).Version; + end + end + clear A + end + + % 1 line: Matlab, SPM12, CAT12 version number and GUI and experimental mode + if ispc, OSname = 'WIN'; + elseif ismac, OSname = 'MAC'; + else, OSname = 'LINUX'; + end + + QAS.software.system = OSname; + QAS.software.version_cat = ver_cat; + if ~isfield(QAS.software,'version_segment') + QAS.software.version_segment = rev_cat; + end + QAS.software.revision_cat = rev_cat; + try + QAS.hardware.numcores = max(cat_get_defaults('extopts.nproc'),1); + catch + QAS.hardware.numcores = 1; + end + + % save important preprocessing parameters + QAS.parameter.opts = opt.job.opts; + QAS.parameter.extopts = rmfield(opt.job.extopts,... + {'LAB','atlas','satlas','darteltpms','shootingtpms','fontsize'}); + QAS.parameter.caterr = opt.caterr; + QAS.error = opt.caterrtxt; + + % redo the quality rating, ie. measure scaling + QAS.qualitymeasures.NCR = NaN; + QAS.qualitymeasures.ICR = NaN; + QAS.qualitymeasures.contrastr = NaN; + QAS.qualitymeasures.res_ECR = NaN; + QAS.qualitymeasures.res_RMS = cat_stat_nanmean(vx_vol.^2).^0.5; + QAS.subjectmeasures.vol_rel_CGW = [NaN NaN NaN]; + QAS.subjectmeasures.SQR = NaN; + + QAR = upate_rating(QAS,opt.version); + + % export + if opt.write_xml + cat_io_xml(fullfile(pp,reportfolder,[opt.prefix ff '.xml']),QAS,'write+'); + cat_io_xml(fullfile(pp,reportfolder,[opt.prefix ff '.xml']),QAR,'write+'); + end +end +%========================================================================== +function def = defaults +%default. cat_vol_qa default parameters. + + def.verb = 2; % verbose level [ 0=nothing | 1=points | 2*=results ] + def.write_csv = 2; % final cms-file [ 0=do not write |1=write | 2=overwrite ] + def.write_xml = 1; % images base xml-file + def.sortQATm = 1; % sort QATm output + def.orgval = 0; % original QAM results (no marks) + def.prefix = 'cat_'; % prefix of QC variables + def.method = 'spm'; % used + def.snspace = [100,7,3]; + %def.nogui = exist('XT','var'); + def.rerun = 1; % 0-load if exist, 1-reprocess if ""necessary"", 2-reprocess + def.version = 'cat_vol_qa201901x'; + def.MarkColor = cat_io_colormaps('marks+',40); + def.versions0 = {'cat_vol_qa201602'}; % no ECR + def.versions1 = {'cat_vol_qa201602','cat_vol_qa201901','cat_vol_qa202110','cat_vol_qa202205'}; % no FEC +end +%========================================================================== +function QARfi = upate_rating(QASfi,version,getdef) +% update rating of stable versions + + if ~exist('getdef','var'), getdef = 0; end + + ndef = cat_stat_marks('default'); +%version = 'default'; + switch version + case {'cat_vol_qa201602','cat_vol_qa201901'} + % robust versions with minimal changes/differences + ndef.noise = [0.046797 0.397905]; + ndef.bias = [0.338721 2.082731]; + case 'cat_vol_qa201901x' + % final refined version of robust version 201901 ############### + ndef.noise = [ 0.0183, 0.0868]; + ndef.bias = [ 0.2270, 1.3949]; + ndef.ECR = [ 0.0202, 0.1003]; + ndef.FEC = [130.0000, 470.0000]; + case {'cat_vol_qa202110'} + % changes between 2019/01 and 2021/10 result a bit different version + % partial better, partially worse (regular successor of version 201901) + ndef.noise = [0.054406 0.439647]; + ndef.bias = [0.190741 1.209683]; + case {'cat_vol_qa202110x'} + % revised 202110 version + ndef.noise = [ 0.0183 0.1362]; + ndef.bias = [ 0.1823 1.1144]; + ndef.ECR = [ -0.0041 1.1918]; + case {'cat_vol_qa202205'} + % latest regular QC version as successor of the 202110 (~202205) + ndef.noise = [0.056985 0.460958]; + ndef.bias = [0.187620 1.206548]; + case {'cat_vol_qa202207b'} + % attempt to reorganize the QC and improve accuracy that was finally + % not successful + ndef.noise = [0.026350 0.203736]; + ndef.bias = [0.120658 0.755107]; + case {'cat_vol_qa202301'} + % latest reworked QC version as successor of the standard qa with + % 202207b as mid version that was not successful + ndef.noise = [ 0.0255 0.1887]; + ndef.bias = [ 0.1996 1.2632]; + ndef.ECR = [ 0.0596 1.1890]; + case {'cat_vol_qa202310', 'cat_vol_qa'} + % the 202310(dd) represents a new start ############### + ndef.noise = [ 0.0326 0.2417]; %0.0322 0.2418]; + ndef.bias = [ 0.1781 0.9393]; %0.1784 0.9356]; + ndef.ECR = [ 0.3597, 1.4316]; %0.3489 1.4117]; %-0.0364 1.1497]; + ndef.FEC = [110.0000, 480.0000]; + case 'cat_vol_qa202412' + % final refined version of robust version 201901 ############### + ndef.noise = [ 0.0095, 0.0740]; %[ 0.0172, 0.1234]; + ndef.bias = [ 0.1695, 0.9907]; %[ 0.1668, 1.0234]; + ndef.ECR = [ 0.3859, 1.2101]; %[ 0.4141, 1.5532]; %-0.0364 1.1497]; + ndef.FEC = [160.0000, 420.0000]; %[100.0000, 630.0000]; + case 'default' + otherwise + warning('missing scaling definition'); + ndef.noise = [0.5 0.5]; + ndef.bias = [0.33 2.0]; + end + + ndef.QS{find(cellfun('isempty',strfind(ndef.QS(:,2),'NCR'))==0,1),4} = ndef.noise; %#ok<*STRCL1> + ndef.QS{find(cellfun('isempty',strfind(ndef.QS(:,2),'ICR'))==0,1),4} = ndef.bias; + if isfield(ndef,'FEC'), ndef.QS{find(cellfun('isempty',strfind(ndef.QS(:,2),'FEC'))==0,1),4} = ndef.FEC; end + if isfield(ndef,'ECR'), ndef.QS{find(cellfun('isempty',strfind(ndef.QS(:,2),'ECR'))==0,1),4} = ndef.ECR; end + + if ~getdef + QARfi = cat_stat_marks('eval',1,QASfi,ndef); + else + QARfi = ndef; + end +end +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_stat_nanstd.m",".m","2217","79","function out = cat_stat_nanstd(in, dim) +% ---------------------------------------------------------------------- +% Standard deviation, not considering NaN values. Similar usage like +% std() or MATLAB nanstd of the statistic toolbox. Process input +% as double due to errors in large single arrays and set data class +% of ""out"" to the data class of ""in"" at the end of the processing. +% Use dim==0 to evaluate in(:) in case of dimension selection +% (e.g., in(:,:,:,2) ). +% +% out = cat_stat_nanstd(in,dim) +% +% Example 1: +% a = rand(4,6,3); +% a(rand(size(a))>0.5)=nan; +% av = cat_stat_nanstd(a,3); +% am = nanstd(a,0,3); % of the statistical toolbox ... +% fprintf('%0.4f %0.4f\n',([av(:),am(:)])'); +% +% Example 2 - special test call of example 1: +% cat_stat_nanstd('test') +% +% See also cat_stat_nansum, cat_stat_nanmedian, cat_stat_nanmean. +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + if nargin < 1 + help cat_stat_nanstd; + return; + end; + + if ischar(in) && strcmp(in,'test') + a = rand(4,6,3); + a(rand(size(a))>0.5)=nan; + av = cat_stat_nanstd(a,3); + am = nanstd(a,0,3); % of the statistical toolbox ... + fprintf('%0.4f %0.4f\n',([av(:),am(:)])'); + out = nanmean(av(:) - am(:)); + return; + end + + if nargin < 2 + if size(in,1) ~= 1 + dim = 1; + elseif size(in,2) ~= 1 + dim = 2; + else + dim = 3; + end; + end; + + if dim == 0 + in = in(:); + dim = 1; + end + + if isempty(in), out = nan; return; end + + % estimate mean + %tp = class(in); + tmpin = double(in); % single failed in large arrays + tmpin(isnan(in(:))) = 0; + mn = cat_stat_nanmean(in,dim); + + dm = size(in); dm(setdiff(1:numel(dm),dim)) = 1; + tmpmn = repmat(mn,dm); clear dm; + tmpmn(isnan(in(:))) = 0; + + % estimate std + out = (sum( (tmpin-tmpmn).^2 , dim) ./ max(1,(size(in,dim) - sum(isnan(in),dim))-1)).^0.5; + out(isnan(mn))=nan; + + %eval(sprintf('out = %s(out);',tp)); +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_stat_nansum.m",".m","1951","71","function out = cat_stat_nansum(in, dim) +% ---------------------------------------------------------------------- +% Average, not considering NaN values. Similar usage like sum() or +% MATLAB nansum of the statistic toolbox. Process input as double +% due to errors in large single arrays and set data class of ""out"" +% to the data class of ""in"" at the end of the processing. +% Use dim==0 to evaluate in(:) in case of dimension selection +% (e.g., in(:,:,:,2) ). +% +% out = cat_stat_nansum(in,dim) +% +% Example 1: +% a = rand(4,6,3); +% a(rand(size(a))>0.5)=nan; +% av = cat_stat_nansum(a,3); +% am = nansum(a,3); % of the statistical toolbox ... +% fprintf('%0.4f %0.4f\n',([av(:),am(:)])'); +% +% Example 2 - special test call of example 1: +% cat_stat_nansum('test') +% +% See also cat_stat_nanmedian, cat_stat_nanstd, cat_stat_nanmean. +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + if nargin < 1 + help cat_stat_nansum; + return; + end; + + if ischar(in) && strcmp(in,'test') + a = rand(4,6,3); + a(rand(size(a))>0.5)=nan; + av = cat_stat_nansum(a,3); + am = nansum(a,3); % of the statistical toolbox ... + fprintf('%0.4f %0.4f\n',([av(:),am(:)])'); + out = nanmean(av(:) - am(:)); + return; + end + + if nargin < 2 + if size(in,1) ~= 1 + dim = 1; + elseif size(in,2) ~= 1 + dim = 2; + else + dim = 3; + end; + end; + + if dim == 0 + in = in(:); + dim = 1; + end + + if isempty(in), out = 0; return; end + + % estimate mean + %tp = class(in); + tmpin = double(in); % single failed in large arrays + tmpin(isnan(in(:))) = 0; + out = sum(tmpin, dim); + + %eval(sprintf('out = %s(out);',tp)); % haha ... +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_surf_render.m",".m","81629","2169","function varargout = cat_surf_render(action,varargin) +% Display a surface mesh & various utilities +% FORMAT H = cat_surf_render('Disp',M,'PropertyName',propertyvalue) +% M - a GIfTI filename/object or patch structure +% H - structure containing handles of various objects +% Opens a new figure unless a 'parent' Property is provided with an axis +% handle. +% +% FORMAT H = cat_surf_render(M) +% Shortcut to previous call format. +% +% FORMAT H = cat_surf_render('ContextMenu',AX) +% AX - axis handle or structure returned by cat_surf_render('Disp',...) +% +% FORMAT H = cat_surf_render('Overlay',AX,P) +% AX - axis handle or structure given by cat_surf_render('Disp',...) +% P - data to be overlayed on mesh (see spm_mesh_project) +% +% FORMAT H = cat_surf_render('ColourBar',AX,MODE) +% AX - axis handle or structure returned by cat_surf_render('Disp',...) +% MODE - {['on'],'off'} +% +% FORMAT H = cat_surf_render('Clim',AX,[mn mx]) +% AX - axis handle or structure given by cat_surf_render('Disp',...) +% mn mx - min/max of range +% +% FORMAT H = cat_surf_render('Clip',AX,[mn mx]) +% AX - axis handle or structure given by cat_surf_render('Disp',...) +% mn mx - min/max of clipping range +% +% FORMAT H = cat_surf_render('ColourMap',AX,MAP) +% AX - axis handle or structure returned by cat_surf_render('Disp',...) +% MAP - a colour map matrix +% +% FORMAT MAP = cat_surf_render('ColourMap',AX) +% Retrieves the current colourmap. +% +% FORMAT H = cat_surf_render('Underlay',AX,P) +% AX - axis handle or structure given by cat_surf_render('Disp',...) +% P - data (curvature) to be underlayed on mesh (see spm_mesh_project) +% +% FORMAT H = cat_surf_render('Clim',AX, range) +% range - range of colour scaling +% +% FORMAT H = cat_surf_render('SaveAs',AX, filename) +% filename - filename +% +% FORMAT cat_surf_render('Register',AX,hReg) +% AX - axis handle or structure returned by cat_surf_render('Disp',...) +% hReg - Handle of HandleGraphics object to build registry in. +% See spm_XYZreg for more information. +%__________________________________________________________________________ +% Copyright (C) 2010-2011 Wellcome Trust Centre for Neuroimaging +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ + +% based on spm_mesh_render.m +% $Id$ + +%#ok<*ASGLU> +%#ok<*INUSL> +%#ok<*INUSD> +%#ok<*TRYNC> + +%-Input parameters +%-------------------------------------------------------------------------- +if ~nargin, action = 'Disp'; end + +if ~ischar(action) + varargin = {action varargin{:}}; + action = 'Disp'; +end + +varargout = {[]}; + +%-Action +%-------------------------------------------------------------------------- +switch lower(action) + + %-Display + %====================================================================== + case 'disp' + if isempty(varargin) + [M, sts] = spm_select(1,'mesh','Select surface mesh file'); + if ~sts, return; end + else + M = varargin{1}; + end + + + %-load mesh data + if ischar(M) || isstruct(M) % default - one surface + [pp,ff,ee] = spm_fileparts(M); + H.filename{1} = M; + switch ee + case '.gii' + M = gifti(M); + otherwise + M = cat_io_FreeSurfer('read_surf',M); + M = gifti(M); + end + + elseif iscellstr(M) % multiple surfaces + %% + MS = M; % save filelist + H.filename = MS; + [pp,ff,ee] = spm_fileparts(MS{1}); + switch ee + case '.gii' + M = gifti(MS{1}); + otherwise + M = cat_io_FreeSurfer('read_surf',MS{1}); + M = gifti(M); + end + for mi = 2:numel(MS) + try + MI = gifti(MS{mi}); + M.faces = [double(M.faces); double(MI.faces) + size(M.vertices,1)]; % further faces with increased vertices ids + M.vertices = [M.vertices; MI.vertices]; % further points at the end of the list + if isfield(M,'cdata'); + M.cdata = [M.cdata; MI.cdata]; % further texture values at the end of the list + end + catch + error('cat_surf_render:multisurf','Error adding surface %d: ''%s''.\n',mi,MS{mi}); + end + end + else + H.filename = {''}; + end + + + if ~isfield(M,'vertices') + try + MM = M; + + + if isempty(MM.private.metadata) + Tname = fullfile(fileparts(mfilename('fullpath')),'templates_surfaces_32k','mesh.central.freesurfer.gii'); + MM.private.metadata(1).value = Tname; + MM.private.metadata(1).name = 'SurfaceID'; + M = gifti(MM.private.metadata(1).value); + try, M.cdata = MM.cdata(); end + else + try + name = MM.private.metadata(1).value; + + % try to replace path to cat12 and correct template name to new template + if ~exist(name,'File') + [pt,nm,xt] = fileparts(name); + nm = strrep(nm,'Template_T1_IXI555_MNI152_GS','Template_T1'); + [pt2,nm2,xt2] = fileparts(pt); + MM.private.metadata(1).value = fullfile(fileparts(mfilename('fullpath')),nm2,[nm xt]); + end + end + M = gifti(MM.private.metadata(1).value); + try, M.cdata = MM.cdata(); end + end + catch + error('Cannot find a surface mesh to be displayed.'); + end + end + O = getOptions(varargin{2:end}); + if isfield(O,'results') + H.results = O.results; + else + H.results = 0; + end + if isfield(O,'cdata') % data input + M.cdata = O.cdata; + elseif isfield(O,'pcdata') % single file input + if ischar(O.pcdata) + [pp,ff,ee] = fileparts(O.pcdata); + H.filename{1} = O.pcdata; + if strcmp(ee,'.gii') + Mt = gifti(O.pcdata); + M.cdata = Mt.cdata; + elseif strcmp(ee,'.annot') + labelmap = zeros(0); labelnam = cell(0); ROIv = zeros(0); + + %% + [fsv,cdata,colortable] = cat_io_FreeSurfer('read_annotation',O.pcdata); %clear fsv; + [sentry,id] = sort(colortable.table(:,5)); + M.cdata = cdata; nid=1; + for sentryi = 1:numel(sentry) + ROI = round(cdata)==sentry(sentryi); + if sum(ROI)>0 && ( (sentryi==numel(sentry)) || sentry(sentryi)~=sentry(sentryi+1) && ... + (sentryi==1 || sentry(sentryi)~=sentry(sentryi+1))), + M.cdata(round(cdata)==sentry(sentryi)) = nid; + labelmap(nid,:) = colortable.table(id(sentryi),1:3)/255; + labelnam(nid) = colortable.struct_names(id(sentryi)); + nid=nid+1; + ROIv(nid) = sum(ROI); + end + end + %labelmap = colortable.table(id,1:3)/255; + % addition maximum element + M.cdata(M.cdata>=colortable.numEntries)=0; %colortable.numEntries+1; + labelmapclim = [min(M.cdata),max(M.cdata)]; + %labelnam = colortable.struct_names(id); + else + M.cdata = cat_io_FreeSurfer('read_surf_data',O.pcdata); + end + elseif iscell(O.pcdata) % multifile input + if ~exist('MS','var') || numel(O.pcdata)~=numel(MS) + error('cat_surf_render:multisurfcdata',... + 'Number of meshes and texture files must be equal.\n'); + end + for mi=1:numel(O.pcdata) + [pp,ff,ee] = fileparts(O.pcdata{mi}); + if strcmp(ee,'.gii') + H.filename{mi} = fullfile(pp,ff); + else + H.filename{mi} = O.pcdata{mi}; + end + end + [pp,ff,ee] = fileparts(O.pcdata{1}); + if strcmp(ee,'.gii') + MC = gifti(O.pcdata{1}); + M.cdata = MC.cdata; + elseif strcmp(ee,'.annot') + %% + [fsv,cdata,colortable] = cat_io_FreeSurfer('read_annotation',O.pcdata{1}); %clear fsv; + [sentry,id] = sort(colortable.table(:,5)); + M.cdata = cdata; nid=1; + for sentryi = 1:numel(sentry) + ROI = round(cdata)==sentry(sentryi); + if sum(ROI)>0 && ( (sentryi==numel(sentry)) || sentry(sentryi)~=sentry(sentryi+1) && ... + (sentryi==1 || sentry(sentryi)~=sentry(sentryi+1))), + M.cdata(round(cdata)==sentry(sentryi)) = nid; + labelmap(nid,:) = colortable.table(id(sentryi),1:3)/255; %#ok + labelnam(nid) = colortable.struct_names(id(sentryi)); %#ok + nid=nid+1; + ROIv(nid) = sum(ROI); %#ok + end + end + %labelmap = colortable.table(id,1:3)/255; + % addition maximum element + M.cdata(M.cdata>colortable.numEntries)=0; %colortable.numEntries+1; + labelmapclim = [min(M.cdata),max(M.cdata)]; + %labelnam = colortable.struct_names(id); + else + M.cdata = cat_io_FreeSurfer('read_surf_data',O.pcdata{1}); + end + for mi = 2:numel(MS) + [pp,ff,ee] = fileparts(O.pcdata{mi}); + if strcmp(ee,'.gii') + Mt = gifti(O.pcdata{mi}); + elseif strcmp(ee,'.annot') + %% + [fsv,cdata,colortable] = cat_io_FreeSurfer('read_annotation',O.pcdata{mi}); %clear fsv; + [sentry,id] = sort(colortable.table(:,5)); + Mt.cdata = cdata; + for sentryi = 1:numel(sentry) + ROI = round(cdata)==sentry(sentryi); + if sum(ROI)>0 && ( (sentryi==numel(sentry)) || sentry(sentryi)~=sentry(sentryi+1) && ... + (sentryi==1 || sentry(sentryi)~=sentry(sentryi+1))), + Mt.cdata(round(cdata)==sentry(sentryi)) = nid; + labelmap(nid,:) = colortable.table(id(sentryi),1:3)/255; + labelnam(nid) = colortable.struct_names(id(sentryi)); + nid=nid+1; + ROIv(nid) = sum(ROI); + end + end + %labelmap = colortable.table(id,1:3)/255; + % addition maximum element + Mt.cdata(Mt.cdata>=colortable.numEntries + labelmapclim(2))=0; %colortable.numEntries+1; + %labelnam = colortable.struct_names(id); + else + Mt.cdata = cat_io_FreeSurfer('read_surf_data',O.pcdata{mi}); + end + M.cdata = [M.cdata; Mt.cdata]; + labelmapclim = [min(double(M.cdata)),max(double(M.cdata))]; + end + if size(M.vertices,1)~=numel(M.cdata); + warning('cat_surf_render:multisurfcdata',... + 'Surface data error (number of vertices does not match number of surface data), remove texture.\n'); + M = rmfield(M,'cdata'); + end + end + else + % with values you can colorize the surface and have not the + % standard lighting ... 20160623 + % M.cdata = 0.5*ones(size(M.vertices,1),1); + end + if ~isfield(M,'vertices') || ~isfield(M,'faces') + error('cat_surf_render:nomesh','ERROR:cat_surf_render: No input mesh in ''%s''', varargin{1}); + end + + M = export(M,'patch'); + + %-Figure & Axis + %------------------------------------------------------------------ + if isfield(O,'parent') + H.issubfigure = 1; + H.axis = O.parent; + H.figure = ancestor(H.axis,'figure'); + figure(H.figure); axes(H.axis); + else + H.issubfigure = 0; + H.figure = figure('Color',[1 1 1]); + H.axis = axes('Parent',H.figure,'Visible','off'); + end + renderer = get(H.figure,'Renderer'); + set(H.figure,'Renderer','OpenGL'); + + if isfield(M,'facevertexcdata') + H.cdata = M.facevertexcdata; + else + H.cdata = []; + end + + %% -Patch + %------------------------------------------------------------------ + P = struct('vertices',M.vertices, 'faces',double(M.faces)); + H.patch = patch(P,... + 'FaceColor', [0.6 0.6 0.6],... + 'EdgeColor', 'none',... + 'FaceLighting', 'gouraud',... + 'SpecularStrength', 0.0,... 0.7 + 'AmbientStrength', 0.4,... 0.1 + 'DiffuseStrength', 0.6,... 0.7 + 'SpecularExponent', 10,... + 'Clipping', 'off',... + 'DeleteFcn', {@myDeleteFcn, renderer},... + 'Visible', 'off',... + 'Tag', 'CATSurfRender',... + 'Parent', H.axis); + setappdata(H.patch,'patch',P); + + %-Label connected components of the mesh + %------------------------------------------------------------------ + C = spm_mesh_label(P); + setappdata(H.patch,'cclabel',C); + + %-Compute mesh curvature + %------------------------------------------------------------------ + curv = spm_mesh_curvature(P); %$ > 0; + setappdata(H.patch,'curvature',curv); + + %-Apply texture to mesh + %------------------------------------------------------------------ + if isfield(M,'facevertexcdata') + T = M.facevertexcdata; + elseif isfield(M,'cdata') + T = M.cdata; + else + T = []; + end + try + updateTexture(H,T); + end + + %-Set viewpoint, light and manipulation options + %------------------------------------------------------------------ + axis(H.axis,'image'); + axis(H.axis,'off'); + view(H.axis,[90 0]); + material(H.figure,'dull'); + + % default lighting + if ismac, H.catLighting = 'inner'; else H.catLighting = 'cam'; end + %H.catLighting = 'cam'; + + H.light(1) = camlight('headlight','infinite'); set(H.light(1),'Parent',H.axis,'Tag','camlight'); + switch H.catLighting + case 'inner' + % switch off local light (camlight) + set(H.light(1),'visible','off'); + + % set inner light + H.light(2) = light('Position',[0 0 0],'Tag','centerlight'); + set(H.patch,'BackFaceLighting','unlit'); + end + + set(H.axis,'Visible','On'); + H.rotate3d = rotate3d(H.axis); + set(H.axis,'Visible','Off'); + set(H.rotate3d,'ActionPostCallback',{@myPostCallback, H}); + if ~H.results + set(H.rotate3d,'Enable','on'); + end + %try + % setAllowAxesRotate(H.rotate3d, ... + % setxor(findobj(H.figure,'Type','axes'),H.axis), false); + %end + + + + %-Store handles + %------------------------------------------------------------------ + setappdata(H.axis,'handles',H); + set(H.patch,'Visible','on'); + + setappdata(H.patch,'clip',[false NaN NaN]); + %set(H.axis,'Position',[0.1 0.1 0.8 0.8]); + if exist('labelmap','var') + %% + setappdata(H.patch,'colourmap',labelmap); + cat_surf_render('clim',H.axis,labelmapclim - 1); + try + colormap(H.axis,labelmap); + catch + colormap(labelmap); + end + caxis(labelmapclim - [1 0]); + H = cat_surf_render('ColorBar',H.axis,'on'); + labelnam2 = labelnam; for lni=1:numel(labelnam2),labelnam2{lni} = [' ' labelnam2{lni} ' ']; end + labelnam2(end+1) = {''}; labelnam2(end+1) = {''}; + labellength = min(100,max(cellfun('length',labelnam2))); + ss = max(1,round(diff(labelmapclim+1)/30)); + ytick = labelmapclim(1)-0.5:ss:labelmapclim(2)+0.5; + set(H.colourbar,'ytick',ytick,'yticklabel',labelnam2(1:ss:end),... + 'Position',[max(0.75,0.98-0.008*labellength) 0.05 0.02 0.9]); + try, set(H.colourbar,'TickLabelInterpreter','none'); end + set(H.axis,'Position',[0.1 0.1 min(0.6,0.98-0.008*labellength - 0.2) 0.8]) + H.labelmap = struct('colormap',labelmap,'ytick',ytick,'labelnam2',{labelnam2}); + setappdata(H.axis,'handles',H); + end + + % annotation with filename + %if ~H.issubfigure + % [pp,ff,ee] = fileparts(H.filename{1}); + % H.text = annotation('textbox','string',[ff ee],'position',[0.0,0.97,0.2,0.03],'LineStyle','none','Interpreter','none'); + %end + + %-Add context menu + %------------------------------------------------------------------ + cat_surf_render('ContextMenu',H); + + + % set default view + cat_surf_render2('view',H,[ 0 90]); + + axis vis3d; %zoom(1.15); + + % remember this zoom level + zoom reset + + + %-Context Menu + %====================================================================== + case 'contextmenu' + if isempty(varargin), varargin{1} = gca; end + H = getHandles(varargin{1}); + if ~isempty(get(H.patch,'UIContextMenu')), return; end + + % -- Inflate, Overlay , Underlay, Label + cmenu = uicontextmenu('Callback',{@myMenuCallback, H}); + if ~H.results + uimenu(cmenu, 'Label','Inflate', 'Interruptible','off', ... + 'Callback',{@myInflate, H}); + + uimenu(cmenu, 'Label','Underlay (Texture)...', 'Interruptible','off', ... + 'Callback',{@myUnderlay, H}); + + uimenu(cmenu, 'Label','Image Sections...', 'Interruptible','off', ... + 'Callback',{@myImageSections, H}); + + uimenu(cmenu, 'Label','Change underlying mesh...', 'Interruptible','off', ... + 'Callback',{@myChangeGeometry, H}); + else + % -- surface meshes -- + c = uimenu(cmenu, 'Label', 'Meshes'); + + sinfo1 = cat_surf_info( H.filename ); + if strcmp(sinfo1(1).texture,'defects'), set(c,'Enable','off'); end + if ~isempty(strfind(fileparts(sinfo1(1).Pmesh),'_32k')) + str32k = '_32k'; + else + str32k = ''; + end + H.meshs = {'Average' ; 'Inflated' ; 'Shooting' ; 'Custom...' }; + for i=1:numel(H.patch) + H.meshs = [ H.meshs , { + fullfile(fileparts(mfilename('fullpath')),['templates_surfaces' str32k],[sinfo1(i).side '.central.freesurfer.gii']); + fullfile(fileparts(mfilename('fullpath')),['templates_surfaces' str32k],[sinfo1(i).side '.inflated.freesurfer.gii']); + fullfile(fileparts(mfilename('fullpath')),['templates_surfaces' str32k],[sinfo1(i).side '.central.' cat_get_defaults('extopts.shootingsurf') '.gii']); + ''; + }]; + end + + uimenu(c, 'Label','Average', 'Checked','on' , 'Callback',{@myChangeMesh, H}); + uimenu(c, 'Label','Inflated', 'Checked','off', 'Callback',{@myChangeMesh, H}); + uimenu(c, 'Label','Shooting', 'Checked','off', 'Callback',{@myChangeMesh, H}); + uimenu(c, 'Label','Custom Mesh...', 'Interruptible','off','Callback',{@myChangeGeometry, H}); + + + + % -- surface overlays -- + %{ + c = uimenu(cmenu, 'Label', 'Overlay'); + % get & name images + % create menu + % add custom + uimenu(c, 'Label','Overlay...', 'Interruptible','off','Callback',{@myOverlay, H}); + %} + + end + + c = uimenu(cmenu, 'Label', 'Connected Components', 'Interruptible','off'); + C = getappdata(H.patch,'cclabel'); + for i=1:length(unique(C)) + uimenu(c, 'Label',sprintf('Component %d',i), 'Checked','on', ... + 'Callback',{@myCCLabel, H}); + end + + + % -- Views -- + if H.results + uimenu(cmenu, 'Label','Rotate', 'Checked','off', 'Separator','on', ... + 'Callback',{@mySwitchRotate, H}); + else + uimenu(cmenu, 'Label','Rotate', 'Checked','on', 'Separator','on', ... + 'Callback',{@mySwitchRotate, H}); + uimenu(cmenu, 'Label','Synchronise Views', 'Visible','off', ... + 'Checked','off', 'Tag','SynchroMenu', 'Callback',{@mySynchroniseViews, H}); + end + c = uimenu(cmenu, 'Label','View'); + uimenu(c, 'Label','Right', 'Callback', {@myView, H, [90 0]}); + uimenu(c, 'Label','Left', 'Callback', {@myView, H, [-90 0]}); + uimenu(c, 'Label','Top', 'Callback', {@myView, H, [0 90]}); + uimenu(c, 'Label','Bottom', 'Callback', {@myView, H, [-180 -90]}); + uimenu(c, 'Label','Front', 'Callback', {@myView, H, [-180 0]}); + uimenu(c, 'Label','Back', 'Callback', {@myView, H, [0 0]}); + + + % -- Colorbar -- + %if ~H.results + uimenu(cmenu, 'Label','Colorbar', 'Callback', {@myColourbar, H}); + %end + + + % -- Colormap -- + c = uimenu(cmenu, 'Label','Colormap'); + %clrmp = {'hot' 'jet' 'gray' 'hsv' 'bone' 'copper' 'pink' 'white' ... + % 'flag' 'lines' 'colorcube' 'prism' 'cool' 'autumn' ... + % 'spring' 'winter' 'summer'}; + clrmp = {'hot' 'cool' , 'jet' 'hsv' , 'autumn' 'spring' 'winter' 'summer' , ... + 'CAThot','CAThotinv','CATcold','CATcoldinv','CATtissues','CATcold&hot'}; + for i=1:numel(clrmp) + if any(i == [5,9]) + uimenu(c, 'Label', clrmp{i}, 'Checked','off', 'Callback', {@myColourmap, H}, 'Separator', 'on'); + else + if i == 1 + H.results*3 + uimenu(c, 'Label', clrmp{i}, 'Checked','on', 'Callback', {@myColourmap, H}); + myColourmap([],[],H,'colormap',clrmp{i}) + else + uimenu(c, 'Label', clrmp{i}, 'Checked','off', 'Callback', {@myColourmap, H}); + end + end + end + % custom does not work, as far as I can not update from the + % colormapeditor yet + %uimenu(c, 'Label','Custom...' , 'Checked','off', 'Callback', {@myColourmap, H, 'custom'}, 'Separator', 'on'); + + + % -- Colorrange -- + if ~H.results + c = uimenu(cmenu, 'Label','Colorrange'); + uimenu(c, 'Label','min-max' , 'Checked','off', 'Callback', {@myCaxis, H, 'auto'}); + uimenu(c, 'Label','2-98 %' , 'Checked','off', 'Callback', {@myCaxis, H, '2p'}); + uimenu(c, 'Label','5-95 %' , 'Checked','off', 'Callback', {@myCaxis, H, '5p'}); + uimenu(c, 'Label','Custom...' , 'Checked','off', 'Callback', {@myCaxis, H, 'custom'}); + uimenu(c, 'Label','Custom %...', 'Checked','off', 'Callback', {@myCaxis, H, 'customp'}); + uimenu(c, 'Label','Synchronise Colorranges', 'Visible','off', ... + 'Checked','off', 'Tag','SynchroMenu', 'Callback',{@mySynchroniseCaxis, H}); + end + + + % -- Lighting -- + c = uimenu(cmenu, 'Label','Lighting'); + macon = {'on' 'off'}; isinner = strcmp(H.catLighting,'inner'); + uimenu(c, 'Label','cam', 'Checked',macon{isinner+1}, 'Callback', {@myLighting, H,'cam'}); + if ismac + uimenu(c, 'Label','inner', 'Checked',macon{2-isinner}, 'Callback', {@myLighting, H,'inner'}); + end + uimenu(c, 'Label','set1', 'Checked','off', 'Callback', {@myLighting, H,'set1'}, 'Separator', 'on'); + uimenu(c, 'Label','set2', 'Checked','off', 'Callback', {@myLighting, H,'set2'}); + uimenu(c, 'Label','set3', 'Checked','off', 'Callback', {@myLighting, H,'set3'}); + uimenu(c, 'Label','grid', 'Checked','off', 'Callback', {@myLighting, H,'grid'}, 'Separator', 'on'); + uimenu(c, 'Label','none', 'Checked','off', 'Callback', {@myLighting, H,'none'}); + + if H.results + c = uimenu(cmenu, 'Label','Mesh Texture'); + uimenu(c, 'Label','bright', 'Checked','off', 'Callback', {@mySurfcolor, H,1.0}); + uimenu(c, 'Label','medium', 'Checked','on', 'Callback', {@mySurfcolor, H,0.5}); + uimenu(c, 'Label','dark', 'Checked','off', 'Callback', {@mySurfcolor, H,0.0}); + uimenu(c, 'Label','dull', 'Checked','on', 'Callback', {@myMaterial, H,'dull'}, 'Separator', 'on'); + uimenu(c, 'Label','shiny', 'Checked','off', 'Callback', {@myMaterial, H,'shiny'}); + uimenu(c, 'Label','metal', 'Checked','off', 'Callback', {@myMaterial, H,[0.2 0.7 0.5 2]}); + end + + % -- Cross -- + if H.results + c = uimenu(cmenu, 'Label','Crossbar'); + uimenu(c, 'Label','off', 'Checked','off', 'Callback', {@myCross, H,'setsize',0}); + uimenu(c, 'Label','small', 'Checked','off', 'Callback', {@myCross, H,'setsize',50}); + uimenu(c, 'Label','medium', 'Checked','on', 'Callback', {@myCross, H,'setsize',100}); + uimenu(c, 'Label','large', 'Checked','off', 'Callback', {@myCross, H,'setsize',200}); + uimenu(c, 'Label','red', 'Checked','on', 'Callback', {@myCross, H,'setcolor',[1 0 0]},'Separator', 'on'); + uimenu(c, 'Label','blue', 'Checked','off', 'Callback', {@myCross, H,'setcolor',[0 0 1]}); + uimenu(c, 'Label','white', 'Checked','off', 'Callback', {@myCross, H,'setcolor',[1 1 1]}); + uimenu(c, 'Label','black', 'Checked','off', 'Callback', {@myCross, H,'setcolor',[0 0 0]}); + uimenu(c, 'Label','Custom...','Checked','off', 'Callback', {@myCross, H,'setcolor',[]}); + end + + + % -- Material -- + if ~H.results + c = uimenu(cmenu, 'Label','Material'); + uimenu(c, 'Label','dull', 'Checked','on', 'Callback', {@myMaterial, H,'dull'}); + uimenu(c, 'Label','shiny', 'Checked','off', 'Callback', {@myMaterial, H,'shiny'}); + uimenu(c, 'Label','metal', 'Checked','off', 'Callback', {@myMaterial, H,[0.2 0.7 0.5 2]}); + %uimenu(c, 'Label','plastic', 'Checked','off', 'Callback', {@myMaterial, H,'plastic'}); + %uimenu(c, 'Label','greasy', 'Checked','off', 'Callback', {@myMaterial, H,'greasy'}); + %uimenu(c, 'Label','grid', 'Checked','off', 'Callback', {@myMaterial, H,'grid'}); + uimenu(c, 'Label','Custom...','Checked','off', 'Callback', {@myMaterial, H,'custom'}); + end + + + % -- Transparency -- + c = uimenu(cmenu, 'Label','Transparency'); tlevel = [0 10 40 80 90]; reson = {'on' 'off'}; + uimenu(c, 'Label','TextureTransparency', 'Checked','on', 'Callback', {@myTextureTransparency, H}); + for ti=1:numel(tlevel) + if ti==1 + uimenu(c, 'Label',sprintf('%0.0f%%',tlevel(ti)), 'Checked',reson{2 - (ti==1 + H.results*1)}, 'Callback', {@myTransparency, H}, 'Separator', 'on'); + else + uimenu(c, 'Label',sprintf('%0.0f%%',tlevel(ti)), 'Checked',reson{2 - (ti==1 + H.results*1)}, 'Callback', {@myTransparency, H}); + end + end + + + % -- Background -- + col = get(H.figure,'Color'); + if isempty(col) || all(col==[1 1 1]), col = [0.94 0.94 0.94]; end % default color + bgs = {'off','off','off','off','off'}; + if all(col==[0.94 0.94 0.94]), bgs{1} = 'on'; % light gray + elseif all(col==[0.10 0.20 0.40]), bgs{2} = 'on'; % dark blue + elseif all(col==[1.00 1.00 0.999]),bgs{3} = 'on'; % the white is slighly different + elseif all(col==[0.00 0.00 0.00]), bgs{4} = 'on'; % + else, bgs{5} = 'on'; + end + c = uimenu(cmenu, 'Label','Background Color'); + uimenu(c, 'Label','Lightgray', 'Checked',bgs{1}, 'Callback', {@myBackgroundColor, H, [0.94 0.94 0.94]}); + uimenu(c, 'Label','Darkblue', 'Checked',bgs{2}, 'Callback', {@myBackgroundColor, H, [0.10 0.20 0.40]}); + uimenu(c, 'Label','White', 'Checked',bgs{3}, 'Callback', {@myBackgroundColor, H, [1.00 1.00 0.999]}); + uimenu(c, 'Label','Black', 'Checked',bgs{4}, 'Callback', {@myBackgroundColor, H, [0.00 0.00 0.00]}); + uimenu(c, 'Label','Custom...', 'Checked',bgs{5}, 'Callback', {@myBackgroundColor, H, []}, 'Separator', 'on'); + %set(H.figure,'Color',col); whitebg(H.figure,col); set(H.figure,'Color',col); + + if H.results + % definition and loading of the atlas maps for data coursor + % - is it useful to load them at the start? + % - is it useful to show it or the outlines? + % - there is at least no space for the legend + % - use of own atlas maps? + satlas = { + 'Desikan' 'aparc_DK40'; + 'Destrieux' 'aparc_a2009s'; + 'HCP' 'aparc_HCP_MMP1'; + 'JuluchBrain3' 'JulichBrainAtlas_3.1';}; + if ~isempty(strfind(fileparts(sinfo1(1).Pmesh),'_32k')) + str32k = '_32k'; + else + str32k = ''; + end + %% + for ai = 1:size(satlas,1) + % define file + safiles = fullfile(fileparts(mfilename('fullpath')),['atlases_surfaces' str32k],... + sprintf('%s.%s.freesurfer.annot',sinfo1(1).side,satlas{ai,2})); + + % loading + [S,sdata,odata,rnames] = cat_surf_load(safiles,'mesh',2); + H.satlases(ai).adata = S.facevertexcdata; + H.satlases(ai).rnames = rnames; + H.satlases(ai).names = [satlas(ai,:) safiles]; + end + end + + % -- Data Coursor -- + uimenu(cmenu, 'Label','Data Cursor', 'Callback', {@myDataCursor, H}); + + + % -- Slider -- + if ~H.results + uimenu(cmenu, 'Label','Slider', 'Callback', {@myAddslider, H}); + end + + + % -- Save -- + uimenu(cmenu, 'Label','Save As...', 'Separator', 'on', ... + 'Callback', {@mySave, H,H.filename{1}}); + + set(H.rotate3d,'enable','off'); + try set(H.rotate3d,'uicontextmenu',cmenu); end + try set(H.patch, 'uicontextmenu',cmenu); end + if ~H.results + set(H.rotate3d,'enable','on'); + end + + dcm_obj = datacursormode(H.figure); + set(dcm_obj, 'Enable','off', 'SnapToDataVertex','on', ... + 'DisplayStyle','Window', 'Updatefcn',{@myDataCursorUpdate, H}); + + + + %-View + %====================================================================== + case 'view' + if isempty(varargin), varargin{1} = gca; end + H = getHandles(varargin{1}); + myView([],[],H,varargin{2}); + + + %-SaveAs + %====================================================================== + case 'saveas' + if isempty(varargin), varargin{1} = gca; end + H = getHandles(varargin{1}); + mySavePNG(H.patch,[],H, varargin{2}); + + + %-Underlay + %====================================================================== + case 'underlay' + if isempty(varargin), varargin{1} = gca; end + H = getHandles(varargin{1}); + if nargin < 3, varargin{2} = []; end + + v = varargin{2}; + if ischar(v) + [p,n,e] = fileparts(v); + if ~strcmp(e,'.mat') && ~strcmp(e,'.nii') && ~strcmp(e,'.gii') && ~strcmp(e,'.img') % freesurfer format + v = cat_io_FreeSurfer('read_surf_data',v); + else + try spm_vol(v); catch, v = gifti(v); end; + end + end + if isa(v,'gifti') + v = v.cdata; + end + + setappdata(H.patch,'curvature',v); + setappdata(H.axis,'handles',H); + d = getappdata(H.patch,'data'); + updateTexture(H,d); + + + %-Overlay + %====================================================================== + case 'overlay' + if isempty(varargin), varargin{1} = gca; end + H = getHandles(varargin{1}); + if nargin < 3, varargin{2} = []; end + updateTexture(H,varargin{2:end}); + try + tr1 = findobj(get(findobj('Label','Transparency'),'children'),'checked','on'); + tr2 = findobj(get(findobj('Label','Transparency'),'children'),'checked','on','Label','TextureTransparency'); + myTransparency([],[],H,get(setdiff(tr1,tr2) ,'Label')); + end + + %-Slices + %====================================================================== + case 'slices' + if isempty(varargin), varargin{1} = gca; end + H = getHandles(varargin{1}); + if nargin < 3, varargin{2} = []; end + renderSlices(H,varargin{2:end}); + + + %-Material + %====================================================================== + case 'material' + if isempty(varargin), varargin{1} = gca; end + H = getHandles(varargin{1}); + + + %-Lighting + %====================================================================== + case 'lighting' + if isempty(varargin), varargin{1} = gca; end + H = getHandles(varargin{1}); + + + %-ColourBar + %====================================================================== + case {'colourbar', 'colorbar'} + if isempty(varargin), varargin{1} = gca; end + if length(varargin) == 1, varargin{2} = 'on'; end + H = getHandles(varargin{1}); + d = getappdata(H.patch,'data'); + col = getappdata(H.patch,'colourmap'); + if strcmpi(varargin{2},'off') + if isfield(H,'colourbar') && ishandle(H.colourbar) + %set(H.colourbar,'visible','off') + if ~H.results + set(H.axis,'Position',get(H.axis,'position') .* [0.10 0.10 0.8 0.8]); + end + delete(H.colourbar); + H = rmfield(H,'colourbar'); + setappdata(H.axis,'handles',H); + end + return; + end + %{ + if strcmpi(varargin{2},'on') + if isfield(H,'colourbar') && ishandle(H.colourbar) + set(H.colourbar,'visible','on') + labelnam2 = get(H.colourbar,'yticklabel'); + labellength = min(100,max(cellfun('length',labelnam2))); + set(H.axis,'Position',[0.03 0.03 min(0.94,0.98-0.008*labellength - 0.06) 0.94]) + return + end + end + %} + if isempty(d) || ~any(d(:)), varargout = {H}; return; end + if isempty(col), col = hot(256); end + if ~isfield(H,'colourbar') || ~ishandle(H.colourbar) + if H.results + H.colourbar = colorbar('peer',H.axis,'southoutside'); %'EastOutside'); + set(H.colourbar,'Tag','','Position',get(H.axis,'position') .* [1.05 1 0.25 0.02]); + else + H.colourbar = colorbar('peer',H.axis); %'EastOutside'); + set(H.colourbar,'Tag','','Position',get(H.axis,'position') .* [.93 0.2 0.02 0.6]); + end + set(get(H.colourbar,'Children'),'Tag',''); + end + caxis(H.axis,[min(d(:)),max(d(:))] .* [1 1+eps]) + + c(1:size(col,1),1,1:size(col,2)) = col; + ic = findobj(H.colourbar,'Type','image'); + clim = getappdata(H.patch, 'clim'); + if isempty(clim), clim = [false NaN NaN]; end + + % Update colorbar colors if clipping is used + clip = getappdata(H.patch, 'clip'); + if ~isempty(clip) + if ~isnan(clip(2)) && ~isnan(clip(3)) + ncol = length(col); + col_step = (clim(3) - clim(2))/ncol; + cmin = max([1,ceil((clip(2)-clim(2))/col_step)]); + cmax = min([ncol,floor((clip(3)-clim(2))/col_step)]); + col(cmin:cmax,:) = repmat([0.5 0.5 0.5],(cmax-cmin+1),1); + c(1:size(col,1),1,1:size(col,2)) = col; + end + end + if size(d,1) > 1 + set(ic,'CData',c(1:size(d,1),:,:)); + set(ic,'YData',[1 size(d,1)]); + set(H.colourbar,'YLim',[1 size(d,1)]); + set(H.colourbar,'YTickLabel',[]); + else + set(ic,'CData',c); + clim = getappdata(H.patch,'clim'); + if isempty(clim), clim = [false min(d) max(d)]; end + if clim(3) > clim(2) + set(ic,'YData',clim(2:3)); + set(H.colourbar,'YLim',clim(2:3)); + caxis(H.axis,[min(d(:)),max(d(:))] .* [1 1+eps]) + end + end + if isfield(H,'labelmap') + labellength = min(100,max(cellfun('length',H.labelmap.labelnam2))); + ss = diff(H.labelmap.ytick(1:2)); + set(H.colourbar,'ytick',H.labelmap.ytick,'yticklabel',H.labelmap.labelnam2(1:ss:end),... + 'Position',get(H.axis,'position') .* [max(0.75,0.98-0.008*labellength) 0.05 0.02 0.9]); + try, set(H.colourbar,'TickLabelInterpreter','none'); end + set(H.axis,'Position',[0.1 0.1 min(0.6,0.98-0.008*labellength - 0.2) 0.8]) + end + setappdata(H.axis,'handles',H); + + + %-ColourMap + %====================================================================== + case {'colourmap', 'colormap'} + if isempty(varargin), varargin{1} = gca; end + H = getHandles(varargin{1}); + if length(varargin) == 1 + varargout = { getappdata(H.patch,'colourmap') }; + return; + else + setappdata(H.patch,'colourmap',varargin{2}); + d = getappdata(H.patch,'data'); + updateTexture(H,d); + end + if nargin>1 + H.colormap = colormap(H.axis,varargin{2}); + end + if isfield(H,'colourmap') + set(H.colourbar,'YLim',get(H.axis,'clim')); + end + + %{ + switch varargin{1} + case 'onecolor' + dx= spm_input('Color','1','r',[0.7 0.7 0.7],[3,1]); + H=cat_surf_render('Colourmap',H,feval(get(obj,'Label'),1)); + + if isempty(varargin{1}) + c = uisetcolor(H.figure, ... + 'Pick a background color...'); + if numel(c) == 1, return; end + else + c = varargin{1}; + end + h = findobj(H.figure,'Tag','SPMMeshRenderBackground'); + if isempty(h) + set(H.figure,'Color',c); + whitebg(H.figure,c); + set(H.figure,'Color',c); + else + set(h,'Color',c); + whitebg(h,c); + set(h,'Color',c); + end + case 'colormapeditor' + colormapeditor + H=cat_surf_render('Colourmap',H,feval(get(obj,'Label'),256)); + end + %} + +% %-ColourMap +% %====================================================================== +% case {'labelmap'} +% if isempty(varargin), varargin{1} = gca; end +% H = getHandles(varargin{1}); +% if length(varargin) == 1 +% varargout = { getappdata(H.patch,'labelmap') }; +% return; +% else +% setappdata(H.patch,'labelmap',varargin{2}); +% d = getappdata(H.patch,'data'); +% updateTexture(H,d,getappdata(H.patch,'labelmap'),'flat'); +% end + + + %-CLim + %====================================================================== + case 'clim' + if isempty(varargin), varargin{1} = gca; end + H = getHandles(varargin{1}); + if length(varargin) == 1 + c = getappdata(H.patch,'clim'); + if ~isempty(c), c = c(2:3); end + varargout = { c }; + return; + else + if strcmp(varargin{2},'on') || isempty(varargin{2}) || any(~isfinite(varargin{2})) + setappdata(H.patch,'clim',[false NaN NaN]); + else + setappdata(H.patch,'clim',[true varargin{2}]); + end + d = getappdata(H.patch,'data'); + updateTexture(H,d); + + end + + if nargin>1 && isnumeric(varargin{2}) && numel(varargin{2})==2 + % use min/max if given range is the same + if diff(varargin{2}) + caxis(H.axis,varargin{2}); + else + caxis(H.axis,[min(d),max(d)]) + end + else + caxis(H.axis,[min(d),max(d)]) + %varargin{2} = [min(d),max(d)]; + end + + %{ + if isfield(H,'colourbar') + set(H.colourbar','ticksmode','auto','LimitsMode','auto') + tick = get(H.colourbar,'ticks'); + ticklabel = get(H.colourbar,'ticklabels'); + if ~isnan(str2double(ticklabel{1})) + tickdiff = mean(diff(tick)); + if tick(1)~=varargin{2}(1) && diff([min(d),varargin{2}(1)])>tickdiff*0.05 + tick = [varargin{2}(1),tick]; ticklabel = [sprintf('%0.3f',varargin{2}(1)); ticklabel]; + end + if tick(end)~=varargin{2}(2) && diff([tick(1),varargin{2}(2)])>tickdiff*0.05, + tick = [tick,varargin{2}(2)]; ticklabel = [ticklabel; sprintf('%0.3f',varargin{2}(2))]; + end + set(H.colourbar,'ticks',tick); %,'ticklabels',ticklabel); + end + set(H.colourbar','ticksmode','manual','LimitsMode','manual') + end + %} + + %-CLip + %====================================================================== + case 'clip' + if isempty(varargin), varargin{1} = gca; end + H = getHandles(varargin{1}); + if length(varargin) == 1 + c = getappdata(H.patch,'clip'); + if ~isempty(c), c = c(2:3); end + varargout = { c }; + return; + else + if isempty(varargin{2}) || any(~isfinite(varargin{2})) + setappdata(H.patch,'clip',[false NaN NaN]); + else + setappdata(H.patch,'clip',[true varargin{2}]); + end + d = getappdata(H.patch,'data'); + updateTexture(H,d); + end + + %-Register + %====================================================================== + case 'register' + if isempty(varargin), varargin{1} = gca; end + H = getHandles(varargin{1}); + hReg = varargin{2}; + xyz = spm_XYZreg('GetCoords',hReg); + hs = myCrossBar('Create',H,xyz); + set(hs,'UserData',hReg); + spm_XYZreg('Add2Reg',hReg,hs,@myCrossBar); + + %-Slider + %====================================================================== + case 'slider' + if isempty(varargin), varargin{1} = gca; end + if length(varargin) == 1, varargin{2} = 'on'; end + H = getHandles(varargin{1}); + if strcmpi(varargin{2},'off') + if isfield(H,'slider') && ishandle(H.slider) + delete(H.slider); + H = rmfield(H,'slider'); + setappdata(H.axis,'handles',H); + end + return; + else + AddSliders(H); + end + setappdata(H.axis,'handles',H); + + + %-TextureTransparency + %====================================================================== + case 'texturetransparency' + if isempty(varargin), varargin{1} = gca; end + H = getHandles(varargin{1}); + myTextureTransparency(H,[],H) + + %-Otherwise... + %====================================================================== + otherwise + try + H = cat_surf_render('Disp',action,varargin{:}); + catch + error('Unknown action.'); + end +end + +varargout = {H}; + + + +%========================================================================== +function myChangeMesh(obj,evt,H) +pmenu = get(obj,'parent'); +meshs = {'Average','Inflated','Shooting','Custom Mesh...'}; +for mi = 1:numel(meshs), set( findobj( pmenu, 'Label',meshs{mi}) ,'Checked','off'); end +set(obj,'Checked','on'); + +% remove slices ... +oldslices = findobj(get(H.axis,'children'),'type','surf','Tag','volumeSlice'); +delete(oldslices); + +id = find(cellfun('isempty',strfind(H.meshs(:,1),obj.Label))==0); +for i=1:numel(H.patch) + if ischar(H.meshs{id,1+i}) + [pp,ff,ee] = spm_fileparts(H.meshs{id,1+i}); + switch ee + case '.gii' + M = gifti(H.meshs{id,1+i}); + otherwise + M = cat_io_FreeSurfer('read_surf',H.meshs{id,1+i}); + M = gifti(M); + end + H.patch(i).Vertices = M.vertices; + else + H.patch(i).Vertices = H.meshs{id,1+i}; + end +end +d = getappdata(H.patch(1),'data'); +updateTexture(H,d); +%========================================================================== +function AddSliders(H) + +c = getappdata(H.patch,'clim'); +mn = c(2); +mx = c(3); + +% allow slider a more extended range +mnx = 1.5*max([-mn mx]); + +sliderPanel(... + 'Parent' , H.figure, ... + 'Title' , 'Overlay min', ... + 'Position', [0.01 0.01 0.2 0.17], ... + 'Backgroundcolor', [1 1 1],... + 'Min' , -mnx, ... + 'Max' , mnx, ... + 'Value' , mn, ... + 'FontName', 'Verdana', ... + 'FontSize', 8, ... + 'NumFormat', '%f', ... + 'Callback', @slider_clim_min); + +sliderPanel(... + 'Parent' , H.figure, ... + 'Title' , 'Overlay max', ... + 'Position', [0.21 0.01 0.2 0.17], ... + 'Backgroundcolor', [1 1 1],... + 'Min' , -mnx, ... + 'Max' , mnx, ... + 'Value' , mx, ... + 'FontName', 'Verdana', ... + 'FontSize', 8, ... + 'NumFormat', '%f', ... + 'Callback', @slider_clim_max); + +sliderPanel(... + 'Parent' , H.figure, ... + 'Title' , 'Clip min', ... + 'Position', [0.01 0.83 0.2 0.17], ... + 'Backgroundcolor', [1 1 1],... + 'Min' , -mnx, ... + 'Max' , mnx, ... + 'Value' , mn, ... + 'FontName', 'Verdana', ... + 'FontSize', 8, ... + 'NumFormat', '%f', ... + 'Callback', @slider_clip_min); + +sliderPanel(... + 'Parent' , H.figure, ... + 'Title' , 'Clip max', ... + 'Position', [0.21 0.83 0.2 0.17], ... + 'Backgroundcolor', [1 1 1],... + 'Min' , -mnx, ... + 'Max' , mnx, ... + 'Value' , mn, ... + 'FontName', 'Verdana', ... + 'FontSize', 8, ... + 'NumFormat', '%f', ... + 'Callback', @slider_clip_max); + +setappdata(H.patch,'clip',[true mn mn]); +setappdata(H.patch,'clim',[true mn mx]); + +%========================================================================== +function myTextureTransparency(obj,evt,H) +y = {'on','off'}; toggle = @(x) y{1+strcmpi(x,'on')}; +set(obj,'Checked',toggle(get(obj,'Checked'))); +d = getappdata(H.patch(1),'data'); +updateTexture(H,d); +%========================================================================== + +%========================================================================== +function O = getOptions(varargin) +O = []; +if ~nargin + return; +elseif nargin == 1 && isstruct(varargin{1}) + for i=fieldnames(varargin{1}) + O.(lower(i{1})) = varargin{1}.(i{1}); + end +elseif mod(nargin,2) == 0 + for i=1:2:numel(varargin) + O.(lower(varargin{i})) = varargin{i+1}; + end +else + error('Invalid list of property/value pairs.'); +end + +%========================================================================== +function H = getHandles(H) +if ~nargin || isempty(H), H = gca; end +if ishandle(H) && ~isappdata(H,'handles') + a = H; clear H; + H.axis = a; + H.figure = ancestor(H.axis,'figure'); + H.patch = findobj(H.axis,'type','patch'); + H.light = findobj(H.axis,'type','light'); + H.rotate3d = rotate3d(H.axis); + setappdata(H.axis,'handles',H); +elseif ishandle(H) + H = getappdata(H,'handles'); +else + H = getappdata(H.axis,'handles'); +end + +%========================================================================== +function myMenuCallback(obj,evt,H) +H = getHandles(H); + +h = findobj(obj,'Label','Rotate'); +if strcmpi(get(H.rotate3d,'Enable'),'on') + set(h,'Checked','on'); +else + set(h,'Checked','off'); +end + +h = findobj(obj,'Label','Slider'); +d = getappdata(H.patch,'data'); +if isempty(d) || ~any(d(:)), set(h,'Enable','off'); else set(h,'Enable','on'); end + +if isfield(H,'slider') + if ishandle(H.slider) + set(h,'Checked','on'); + else + H = rmfield(H,'slider'); + set(h,'Checked','off'); + end +else + set(h,'Checked','off'); +end + +if numel(findobj('Tag','CATSurfRender','Type','Patch')) > 1 + h = findobj(obj,'Tag','SynchroMenu'); + set(h,'Visible','on'); +end + +h = findobj(obj,'Label','Colorbar'); +hx = findobj(obj,'Label','Colormap'); +hr = findobj(obj,'Label','Colorrange'); +d = getappdata(H.patch,'data'); +if isempty(d) || ~any(d(:)), + set(h ,'Enable','off'); + set(hx,'Enable','off'); + set(hr,'Enable','off'); +else + set(h ,'Enable','on'); + set(hx,'Enable','on'); + set(hr,'Enable','on'); +end +if isfield(H,'labelmap') + set(hx,'Enable','off'); + set(hr,'Enable','off'); +end + +if isfield(H,'colourbar') + if ishandle(H.colourbar) + set(h,'Checked','on'); + else + H = rmfield(H,'colourbar'); + set(h,'Checked','off'); + end +else + set(h,'Checked','off'); +end +setappdata(H.axis,'handles',H); + +%========================================================================== +function myPostCallback(obj,evt,H) +P = findobj('Tag','CATSurfRender','Type','Patch'); +if numel(P) == 1 + if strcmp(H.light(1).Visible,'on'), camlight(H.light(1),'headlight','infinite'); end +else + for i=1:numel(P) + H = getappdata(ancestor(P(i),'axes'),'handles'); + if strcmp(H.light(1).Visible,'on'), camlight(H.light(1),'headlight','infinite'); end + end +end +axis vis3d; + +%========================================================================== +function mySurfcolor(obj,evt,H,val) + c = get(get(obj,'parent'),'children'); + cb = get(c,'callback'); + for cbi=1:numel(cb), if strcmp(char(cb{cbi}{1}),'mySurfcolor'), set(c(cbi),'Checked','off'); end; end + set(obj,'Checked','on'); + d = getappdata(H.patch(1),'data'); + setappdata(H.axis,'handles',H); + H.surfbrightness = val; + updateTexture(H,d); + +%========================================================================== +function myCross(obj,evt,H,action,val) + hs = findobj(H.axis,'Marker','+'); + if isempty(hs), return; end + pobj = get(obj,'parent'); + switch action + case 'setsize' + if val>0 + set(hs,'MarkerSize',val,'Visible','on'); + else + set(hs,'MarkerSize',1,'Visible','off'); + end + labs = {'off','small','medium','large'}; + + case 'setcolor' + if isempty(val) + val = uisetcolor(H.axis, ... + 'Pick a crossbar color...'); + if numel(val) == 1, return; end + end + set(hs,'Color',val) + labs = {'red','blue','white','black','Custom...'}; + end + + for li = 1:numel(labs) + set(findobj(pobj,'Label',labs{li}),'Checked','off'); + end + set(obj,'Checked','on'); + +%========================================================================== +function varargout = myCrossBar(varargin) + +switch lower(varargin{1}) + + case 'create' + %---------------------------------------------------------------------- + % hMe = myCrossBar('Create',H,xyz) + H = varargin{2}; + xyz = varargin{3}; + hold(H.axis,'on'); + hs = plot3(xyz(1),xyz(2),xyz(3),'Marker','+','MarkerSize',100,'LineWidth',2,... + 'parent',H.axis,'Color',[1 0 0],'Tag','CrossBar','ButtonDownFcn',{}); + varargout = {hs}; + + case 'setcoords' + %---------------------------------------------------------------------- + % [xyz,d] = myCrossBar('SetCoords',xyz,hMe) + hMe = varargin{3}; + xyz = varargin{2}; + set(hMe,'XData',xyz(1)); + set(hMe,'YData',xyz(2)); + set(hMe,'ZData',xyz(3)); + varargout = {xyz,[]}; + + case 'setvertex' + %---------------------------------------------------------------------- + % [xyz,d] = myCrossBar('SetCoords',xyz,hMe) + hMe = varargin{3}; + id = varargin{2}; + set(hMe,'XData',id); + varargout = {id,[]}; + + otherwise + %---------------------------------------------------------------------- + error('Unknown action string') + +end +%cat_spm_results_ui('spm_list_cleanup'); % does not work? + + +%========================================================================== +function myInflate(obj,evt,H) +spm_mesh_inflate(H.patch,Inf,1); +axis(H.axis,'image'); + +%========================================================================== +function myCCLabel(obj,evt,H) +C = getappdata(H.patch,'cclabel'); +F = get(H.patch,'Faces'); +ind = sscanf(get(obj,'Label'),'Component %d'); +V = get(H.patch,'FaceVertexAlphaData'); +Fa = get(H.patch,'FaceAlpha'); +if ~isnumeric(Fa) + if ~isempty(V), Fa = max(V); else Fa = 1; end + if Fa == 0, Fa = 1; end +end +if isempty(V) || numel(V) == 1 + Ve = get(H.patch,'Vertices'); + if isempty(V) || V == 1 + V = Fa * ones(size(Ve,1),1); + else + V = zeros(size(Ve,1),1); + end +end +if strcmpi(get(obj,'Checked'),'on') + V(reshape(F(C==ind,:),[],1)) = 0; + set(obj,'Checked','off'); +else + V(reshape(F(C==ind,:),[],1)) = Fa; + set(obj,'Checked','on'); +end +set(H.patch, 'FaceVertexAlphaData', V); +if all(V) + % ensure that Fa is between 0..1 + Fa = min([1.0 Fa]); + Fa = max([0.0 Fa]); + set(H.patch, 'FaceAlpha', Fa); +else + set(H.patch, 'FaceAlpha', 'interp'); +end + +%========================================================================== +function myTransparency(obj,evt,H,varargin) +if ~isempty(varargin) + + t = 1 - sscanf(varargin{1},'%d%%') / 100; +else + t = 1 - sscanf(get(obj,'Label'),'%d%%') / 100; +end +%% +curv = getappdata(H.patch,'curvature'); +col = getappdata(H.patch,'colourmap'); +v = get( H.patch, 'UserData'); +%% +C = zeros(size(v,2),1); +clim = getappdata(H.patch, 'clim'); +if isempty(clim), clim = [false nan nan]; end +mi = clim(2); ma = clim(3); + +if size(col,1)>3 && size(col,1) ~= size(v,1) + if size(v,1) == 1 + if ~clim(1), mi = min(v(:)); ma = max(v(:)); end + C = floor(((v(:)-mi)/(ma-mi))*size(col,1)); + elseif isequal(size(v),[size(curv,1) 3]) + C = v; v = v'; + else + if ~clim(1), mi = min(v(:)); ma = max(v(:)); end + for i=1:size(v,1) + C = C + floor(((v(i,:)-mi)/(ma-mi))*size(col,1)); + end + end +else + if ~clim(1), ma = max(v(:)); end + for i=1:size(v,1) + C = C + v(i,:)'/ma * col(i,:); + end +end +%% +if any(isnan(clim)) + set(H.patch,'FaceVertexAlphaData',t + (1-t) * zeros(size(C))/255); +else + set(H.patch,'FaceVertexAlphaData',t + (1-t) * C/255); +end +set(H.patch,'FaceAlpha','interp'); +set(H.patch,'AlphaDataMapping','scaled'); +alim([0 1]); +set(get(get(obj,'parent'),'children'),'Checked','off'); +set(obj,'Checked','on'); + +%========================================================================== +function mySwitchRotate(obj,evt,H) +if strcmpi(get(H.rotate3d,'enable'),'on') + rotate3d(H.axis,'off'); + set(obj,'Checked','off'); +else + rotate3d(H.axis,'on'); + set(obj,'Checked','on'); + + % fine red lines of the SPM result table +%{ + hRes.Fgraph = spm_figure('FindWin','Graphics'); + + hRes.Fline = findobj(hRes.Fgraph,'Type','Line','Tag',''); + hRes.FlineAx = get(hRes.Fline,'parent'); + + set(hRes.Fline,'HitTest','off'); + for axi = 1:numel( hRes.FlineAx ), rotate3d(hRes.FlineAx{axi},'off'); end + %} +end + +%========================================================================== +function myView(obj,evt,H,varargin) +view(H.axis,varargin{1}); +axis(H.axis,'image'); +if strcmp(H.catLighting,'cam') && ~isempty(H.light), camlight(H.light(1),'headlight','infinite'); end + +%========================================================================== +function myColourbar(obj,evt,H) +y = {'on','off'}; toggle = @(x) y{1+strcmpi(x,'on')}; +cat_surf_render('Colourbar',H,toggle(get(obj,'Checked'))); +set(obj,'Checked',toggle(get(obj,'Checked'))); + + + +%========================================================================== +function myLighting(obj,evt,H,newcatLighting) +y = {'on','off'}; toggle = @(x) y{1+strcmpi(x,'on')}; +% set old lights +H.catLighting = newcatLighting; +delete(findall(H.axis,'Type','light','Tag','')); % remove old infinite lights +delete(findall(H.axis,'Type','light','Tag','centerlight')); +caml = findall(H.axis,'Type','light','Tag','camlight'); % switch off camlight + +% new lights +lighting gouraud +set(caml,'visible','off'); +set(H.patch,'BackFaceLighting','reverselit'); +set(H.patch,'LineStyle','-','EdgeColor','none'); +switch H.catLighting + case 'none' + case 'inner' + H.light(2) = light('Position',[0 0 0]); + ks = get(H.patch,'SpecularStrength'); set(H.patch,'SpecularStrength',min(0.1,ks)); + n = get(H.patch,'SpecularExponent'); set(H.patch,'SpecularExponent',max(2,n)); + set(H.patch,'BackFaceLighting','unlit'); + case 'top' + H.light(2) = light('Position',[ 0 0 1],'Color',repmat(1,1,3)); %#ok<*REPMAT> + case 'bottom' + H.light(2) = light('Position',[ 0 0 -1],'Color',repmat(1,1,3)); + case 'left' + H.light(2) = light('Position',[-1 0 0],'Color',repmat(1,1,3)); + case 'right' + H.light(2) = light('Position',[ 1 0 0],'Color',repmat(1,1,3)); + case 'front' + H.light(2) = light('Position',[ 0 1 0],'Color',repmat(1,1,3)); + case 'back' + H.light(2) = light('Position',[ 0 -1 0],'Color',repmat(1,1,3)); + case 'set1' + H.light(2) = light('Position',[ 1 0 .5],'Color',repmat(0.8,1,3)); + H.light(3) = light('Position',[-1 0 .5],'Color',repmat(0.8,1,3)); + H.light(4) = light('Position',[ 0 1 -.5],'Color',repmat(0.2,1,3)); + H.light(5) = light('Position',[ 0 -1 -.5],'Color',repmat(0.2,1,3)); + case 'set2' + H.light(2) = light('Position',[ 1 0 1],'Color',repmat(0.7,1,3)); + H.light(3) = light('Position',[-1 0 1],'Color',repmat(0.7,1,3)); + H.light(4) = light('Position',[ 0 1 .5],'Color',repmat(0.3,1,3)); + H.light(5) = light('Position',[ 0 -1 .5],'Color',repmat(0.3,1,3)); + H.light(5) = light('Position',[ 0 0 -1],'Color',repmat(0.2,1,3)); + case 'set3' + H.light(2) = light('Position',[ 1 0 0],'Color',repmat(0.8,1,3)); + H.light(3) = light('Position',[-1 0 0],'Color',repmat(0.8,1,3)); + H.light(4) = light('Position',[ 0 1 1],'Color',repmat(0.2,1,3)); + H.light(5) = light('Position',[ 0 -1 1],'Color',repmat(0.2,1,3)); + H.light(6) = light('Position',[ 0 0 -1],'Color',repmat(0.1,1,3)); + case 'grid' + set(H.patch,'LineStyle','-','EdgeColor',[0 0 0]); + set(H.patch,'AmbientStrength',0.7,'DiffuseStrength',0.1,'SpecularStrength',0.6,'SpecularExponent',10); + case 'cam' + camlight(H.light(1),'headlight','infinite'); + set(caml,'visible','on'); +end +set(get(get(obj,'parent'),'children'),'Checked','off'); +set(obj,'Checked','on'); + +%========================================================================== +function myMaterial(obj,evt,H,mat) +y = {'on','off'}; toggle = @(x) y{1+strcmpi(x,'on')}; +set(H.patch,'LineStyle','none'); +if ischar(mat) + switch mat + case 'shiny' + material shiny; + case 'dull' + material dull; + case 'metal' + material metal; + case 'grid' + set(H.patch,'LineStyle','-','EdgeColor',[0 0 0]); + set(H.patch,'AmbientStrength',0.7,'DiffuseStrength',0.1,'SpecularStrength',0.6,'SpecularExponent',10); + case 'greasy' + set(H.patch,'AmbientStrength',0.2,'DiffuseStrength',0.5,'SpecularStrength',0.3,'SpecularExponent',0.6); + case 'plastic' + set(H.patch,'AmbientStrength',0.1,'DiffuseStrength',0.6,'SpecularStrength',0.3,'SpecularExponent',2); + case 'metal' + set(H.patch,'AmbientStrength',0.4,'DiffuseStrength',0.9,'SpecularStrength',0.1,'SpecularExponent',1); + case 'default' + set(H.patch,'AmbientStrength',0.4,'DiffuseStrength',0.6,'SpecularStrength',0.0,'SpecularExponent',10); + case 'custom' + spm_figure('getwin','Interactive'); + % actual values + ka = get(H.patch,'AmbientStrength'); + kd = get(H.patch,'DiffuseStrength'); + ks = get(H.patch,'SpecularStrength'); + n = get(H.patch,'SpecularExponent'); + % new values + ka = spm_input('AmbientStrength',1,'r',ka,[1,1]); + kd = spm_input('DiffuseStrength',2,'r',kd,[1,1]); + ks = spm_input('SpecularStrength',3','r',ks,[1,1]); + n = spm_input('SpecularExponent',4,'r',n,[1,1]); + set(H.patch,'AmbientStrength',ka,'DiffuseStrength',kd,'SpecularStrength',ks,'SpecularExponent',n); + end +else + set(H.patch,'AmbientStrength',mat(1),'DiffuseStrength',mat(2),'SpecularStrength',mat(3),'SpecularExponent',mat(4)); +end +c = get(get(obj,'parent'),'children'); +cb = get(c,'callback'); +for cbi=1:numel(cb), if strcmp(char(cb{cbi}{1}),'myMaterial'), set(c(cbi),'Checked','off'); end; end +set(obj,'Checked','on'); + + + +%========================================================================== +function myCaxis(obj,evt,H,rangetype) +d = getappdata(H.patch,'data'); +if cat_stat_nanmean(d(:))>0 && cat_stat_nanstd(d(:),1)>0 + switch rangetype + case 'min-max', + range = [min(d) max(d)]; + case '2p' + range = cat_vol_iscaling(d,[0.02 0.98]); + case '5p' + range = cat_vol_iscaling(d,[0.05 0.95]); + case 'custom' + fc = gcf; + spm_figure('getwin','Interactive'); + range = cat_vol_iscaling(d,[0.02 0.98]); + d = spm_input('intensity range','1','r',range,[2,1]); + figure(fc); + range = [min(d) max(d)]; + case 'customp' + fc = gcf; + spm_figure('getwin','Interactive'); + dx= spm_input('percentual intensity range','1','r',[2 98],[2,1]); + range = cat_vol_iscaling(d,dx/100); + figure(fc); + otherwise + range = [min(d) max(d)]; + end + if range(1)==range(2), range = range + [-eps eps]; end + if range(1)>range(2), range = fliplr(range); end + cat_surf_render('Clim',H,range); +end +set(get(get(obj,'parent'),'children'),'Checked','off'); +set(obj,'Checked','on'); + +%========================================================================== +function mySynchroniseCaxis(obj,evt,H) +P = findobj('Tag','CATSurfRender','Type','Patch'); +range = getappdata(H.patch, 'clim'); +range = range(2:3); + +for i=1:numel(P) + H = getappdata(ancestor(P(i),'axes'),'handles'); + cat_surf_render('Clim',H,range); +end + +%========================================================================== +function myColourmap(obj,evt,H,varargin) +dx = get(H.patch,'UserData'); dx = [min(dx) min(dx(dx~=0)) max(dx)]; +if ~isempty(varargin) + switch varargin{1} + case 'color' + c = uisetcolor(H.figure,'Pick a surface color...'); + case 'colormap' + c=feval(varargin{2},256); + otherwise + c = feval(get(obj,'Label'),256); + end +else + switch get(obj,'Label') + case {'CAThot','CAThotinv','CATcold','CATcoldinv'} + catcm = get(obj,'Label'); catcm(1:3) = []; + c=cat_io_colormaps(catcm,256); + case 'CATtissues' + c=cat_io_colormaps('BCGWHw',256); + case 'CATcold&hot' + c=cat_io_colormaps('BWR',256); + otherwise + c = feval(get(obj,'Label'),256); + end +end +if ~isempty(dx), c(1:round(size(c,1) * dx(2)/dx(3)),:) = 0.5; end +cat_surf_render('Colourmap',H,c); +set(get(get(obj,'parent'),'children'),'Checked','off'); +%if isfield(H,'colourbar'),H=cat_surf_render('Clim',H,H.colourbar.Limits); end +set(obj,'Checked','on'); + +%========================================================================== +function myAddslider(obj,evt,H) +y = {'on','off'}; toggle = @(x) y{1+strcmpi(x,'on')}; +cat_surf_render('Slider',H,toggle(get(obj,'Checked'))); + +%========================================================================== +function mySynchroniseViews(obj,evt,H) +P = findobj('Tag','CATSurfRender','Type','Patch'); +v = get(H.axis,'cameraposition'); +for i=1:numel(P) + H = getappdata(ancestor(P(i),'axes'),'handles'); + set(H.axis,'cameraposition',v); + axis(H.axis,'image'); + if strcmp(H.catLighting,'cam') && ~isempty(H.light), camlight(H.light(1),'headlight','infinite'); end +end + +%========================================================================== +function myDataCursor(obj,evt,H) +dcm_obj = datacursormode(H.figure); +set(dcm_obj, 'Enable','on', 'SnapToDataVertex','on', ... + 'DisplayStyle','datatip', 'Updatefcn',{@myDataCursorUpdate, H}); %Window + +%========================================================================== +function txt = myDataCursorUpdate(obj,evt,H) +set(findobj(obj),'String',{''}); +pos = get(evt,'Position'); +txt = {['X: ',num2str(pos(1))],... + ['Y: ',num2str(pos(2))],... + ['Z: ',num2str(pos(3))]}; +i = ismember(get(H.patch,'vertices'),pos,'rows'); +if isfield(H,'results') && H.results && isfield(H,'satlases') + txt{1} = sprintf('Node: %d (%0.0f %0.0f %0.0f mm)',find(i),pos); + for ai = 1:numel(H.satlases) + txt{1 + ai} = sprintf('%s: %s', H.satlases(ai).names{1}, ... + H.satlases(ai).rnames.struct_names{ H.satlases(ai).adata(i) == H.satlases(ai).rnames.table(:,5) } ); + end +else + txt = {['Node: ' num2str(find(i))] txt{:}}; +end +d = getappdata(H.patch,'data'); +if ~isempty(d) && any(d(:)) + if any(i), txt = {txt{:} ['T: ',num2str(d(i))]}; end +end +set(findobj(obj),'String',txt); + + +hMe = findobj(H.axis,'Tag','CrossBar'); +if ~isempty(hMe) + %ws = warning('off'); + myCrossBar('SetCoords',pos,hMe); + %spm_XYZreg('SetCoords',pos,get(hMe,'UserData')); + + spm_orthviews('Reposition',pos) + %warning(ws); +end +try + cat_spm_results_ui('spm_list_cleanup'); +end + +%========================================================================== +function myBackgroundColor(obj,evt,H,varargin) + % get color + if isempty(varargin{1}) + c = uisetcolor(H.figure, ... + 'Pick a background color...'); + if numel(c) == 1, return; end + else + c = varargin{1}; + end + + % get the main figure and the possible satelite + h = findobj(H.figure,'Tag','SPMMeshRenderBackground'); + if isempty(h), h = H.figure; end + h = [h,spm_figure('FindWin','Satellite')]; + + % find color objects that should not be inverted + % ... we started with red and maybe add more later + reds = findobj(h,'Color',[1 0 0]); + + + % set new color and invert other objects (e.g., fonts and lines) + set(h,'Color',c); + whitebg(h,c); + set(h,'Color',c); + + % reset red objects + set(reds,'Color',[1 0 0]); + + set(get(get(obj,'parent'),'children'),'Checked','off'); % deactivate all + set(obj,'Checked','on'); + cat_spm_results_ui('spm_list_cleanup'); + +%========================================================================== +function mySavePNG(obj,evt,H,filename) + %% + if ~exist('filename','var') + filename = uiputfile({... + '*.png' 'PNG files (*.png)'}, 'Save as'); + else + [pth,nam,ext] = fileparts(filename); + if isempty(pth), pth = cd; end + if ~strcmp({'.gii','.png'},ext), nam = [nam ext]; end + if isempty(nam) + filename = uiputfile({... + '*.png' 'PNG files (*.png)'}, 'Save as',nam); + else + filename = fullfile(pth,[nam '.png']); + end + end + + u = get(H.axis,'units'); + set(H.axis,'units','pixels'); + p = get(H.figure,'Position'); + r = get(H.figure,'Renderer'); + hc = findobj(H.figure,'Tag','SPMMeshRenderBackground'); + if isempty(hc) + c = get(H.figure,'Color'); + else + c = get(hc,'Color'); + end + h = figure('Position',p+[0 0 0 0], ... + 'InvertHardcopy','off', ... + 'Color',c, ... + 'Renderer',r); + copyobj(H.axis,h); + copyobj(H.axis,h); + set(H.axis,'units',u); + set(get(h,'children'),'visible','off'); + colorbar('Position',[.93 0.2 0.02 0.6]); + try + colormap(H.axis,getappdata(H.patch,'colourmap')); + catch + colormap(getappdata(H.patch,'colourmap')); + end + [pp,ff,ee] = fileparts(H.filename{1}); + %H.text = annotation('textbox','string',[ff ee],'position',[0.0,0.97,0.2,0.03],'LineStyle','none','Interpreter','none'); + %a = get(h,'children'); + %set(a,'Position',get(a,'Position').*[0 0 1 1]+[10 10 0 0]); + if isdeployed + deployprint(h, '-dpng', '-opengl', fullfile(pth, filename)); + else + print(h, '-dpng', '-opengl', fullfile(pth, filename)); + end + close(h); + set(getappdata(obj,'fig'),'renderer',r); + +%========================================================================== +function mySave(obj,evt,H,filename) + if ~exist('filename','var') + [filename, pathname, filterindex] = uiputfile({... + '*.png' 'PNG files (*.png)';... + '*.gii' 'GIfTI files (*.gii)'; ... + '*.dae' 'Collada files (*.dae)';... + '*.idtf' 'IDTF files (*.idtf)'}, 'Save as'); + else + [pth,nam,ext] = fileparts(filename); + if ~strcmp({'.gii','.png'},ext), nam = [nam ext]; end + [filename, pathname, filterindex] = uiputfile({... + '*.png' 'PNG files (*.png)';... + '*.gii' 'GIfTI files (*.gii)'; ... + '*.dae' 'Collada files (*.dae)';... + '*.idtf' 'IDTF files (*.idtf)'}, 'Save as',nam); + end + +if ~isequal(filename,0) && ~isequal(pathname,0) + [pth,nam,ext] = fileparts(filename); + switch ext + case '.gii' + filterindex = 1; + case '.png' + filterindex = 2; + case '.dae' + filterindex = 3; + case '.idtf' + filterindex = 4; + otherwise + switch filterindex + case 1 + filename = [filename '.gii']; + case 2 + filename = [filename '.png']; + case 3 + filename = [filename '.dae']; + end + end + switch filterindex + case 1 + G = gifti(H.patch); + [p,n,e] = fileparts(filename); + [p,n,e] = fileparts(n); + switch lower(e) + case '.func' + save(gifti(getappdata(H.patch,'data')),... + fullfile(pathname, filename)); + case '.surf' + save(gifti(struct('vertices',G.vertices,'faces',G.faces)),... + fullfile(pathname, filename)); + case '.rgba' + save(gifti(G.cdata),fullfile(pathname, filename)); + otherwise + save(G,fullfile(pathname, filename)); + end + case 2 + u = get(H.axis,'units'); + set(H.axis,'units','pixels'); + p = get(H.figure,'Position'); % axis + r = get(H.figure,'Renderer'); + hc = findobj(H.figure,'Tag','SPMMeshRenderBackground'); + if isempty(hc) + c = get(H.figure,'Color'); + else + c = get(hc,'Color'); + end + h = figure('Position',p+[0 0 0 0], ... [0 0 10 10] + 'InvertHardcopy','off', ... + 'Color',c, ... + 'Renderer',r); + copyobj(H.axis,h); + set(H.axis,'units',u); + set(get(h,'children'),'visible','off'); + colorbar('Position',[.93 0.2 0.02 0.6]); + try + colormap(H.axis,getappdata(H.patch,'colourmap')); + catch + colormap(getappdata(H.patch,'colourmap')); + end + [pp,ff,ee] = fileparts(H.filename{1}); + %H.text = annotation('textbox','string',[ff ee],'position',[0.0,0.97,0.2,0.03],'LineStyle','none','Interpreter','none'); + %a = get(h,'children'); + %set(a,'Position',get(a,'Position').*[0 0 1 1]+[10 10 0 0]); + if isdeployed + deployprint(h, '-dpng', '-opengl', fullfile(pathname, filename)); + else + print(h, '-dpng', '-opengl', fullfile(pathname, filename)); + end + close(h); + set(getappdata(obj,'fig'),'renderer',r); + case 3 + save(gifti(H.patch),fullfile(pathname, filename),'collada'); + case 4 + save(gifti(H.patch),fullfile(pathname, filename),'idtf'); + end +end + +%========================================================================== +function myDeleteFcn(obj,evt,renderer) +try rotate3d(get(obj,'parent'),'off'); end +set(ancestor(obj,'figure'),'Renderer',renderer); + +%========================================================================== +function myOverlay(obj,evt,H) +[P, sts] = spm_select(1,'any','Select file to overlay'); +if ~sts, return; end +cat_surf_render('Overlay',H,P); + +%========================================================================== +function myUnderlay(obj,evt,H) +[P, sts] = spm_select(1,'any','Select texture file to underlay',{},fullfile(fileparts(mfilename('fullpath')),'templates_surfaces'),'[lr]h.mc.*'); +if ~sts, return; end +cat_surf_render('Underlay',H,P); + +%========================================================================== +function myImageSections(obj,evt,H) +[P, sts] = spm_select(1,'image','Select image to render'); +if ~sts, return; end +renderSlices(H,P); + +%========================================================================== +function myChangeGeometry(obj,evt,H) +[P, sts] = spm_select(1,'mesh','Select new geometry mesh'); +if ~sts, return; end +G = gifti(P); + +if size(get(H.patch,'Vertices'),1) ~= size(G.vertices,1) + error('Number of vertices must match.'); +end +set(H.patch,'Vertices',G.vertices) +set(H.patch,'Faces',G.faces) +view(H.axis,[-90 0]); + +pmenu = findobj( 'Label', 'Meshes' ); +meshs = {'Average','Inflated','Shooting','Custom Mesh...'}; +for mi = 1:numel(meshs), set( findobj( pmenu, 'Label',meshs{mi}) ,'Checked','off'); end +set(obj,'Checked','on'); + + +%========================================================================== +function renderSlices(H,P,pls) +if nargin <3 + pls = 0.05:0.2:0.9; +end +N = nifti(P); +d = size(N.dat); +pls = round(pls.*d(3)); +hold(H.axis,'on'); +for i=1:numel(pls) + [x,y,z] = ndgrid(1:d(1),1:d(2),pls(i)); + f = N.dat(:,:,pls(i)); + x1 = N.mat(1,1)*x + N.mat(1,2)*y + N.mat(1,3)*z + N.mat(1,4); + y1 = N.mat(2,1)*x + N.mat(2,2)*y + N.mat(2,3)*z + N.mat(2,4); + z1 = N.mat(3,1)*x + N.mat(3,2)*y + N.mat(3,3)*z + N.mat(3,4); + surf(x1,y1,z1, repmat(f,[1 1 3]), 'EdgeColor','none', ... + 'Clipping','off', 'Parent',H.axis); +end +hold(H.axis,'off'); +axis(H.axis,'image'); + +%========================================================================== +function C = updateTexture(H,v,col)%$,FaceColor) + +%-Get colourmap +%-------------------------------------------------------------------------- +if ~exist('col','var'), col = getappdata(H.patch,'colourmap'); end +if isempty(col), col = hot(256); end +if ~exist('FaceColor','var'), FaceColor = 'interp'; end +setappdata(H.patch,'colourmap',col); + +%-Get curvature +%-------------------------------------------------------------------------- +curv = getappdata(H.patch,'curvature'); + +if size(curv,2) == 1 + if 0 + th = 0.15; + curv((curv<-th)) = -th; + curv((curv>th)) = th; + curv = 0.5 * (curv + th)/(2*th); + curv = 0.5 + repmat(curv,1,3); + else + th = 0.30; + curv((curv<-th)) = -th; + curv((curv>th)) = th; + curv = 0.5 * (curv + th)/(2*th); + curv = 0.1 + 1.0 * repmat(curv,1,3); + %curv = 0.5 * repmat(curv,1,3) + 0.3 * repmat(~curv,1,3); + %curv = 0.5 * repmat(curv,1,3) + 0.3 * repmat(~curv,1,3); + end +end + +%-Project data onto surface mesh +%-------------------------------------------------------------------------- +if nargin < 2, v = []; end +if ischar(v) + [p,n,e] = fileparts(v); + if ~strcmp(e,'.mat') && ~strcmp(e,'.nii') && ~strcmp(e,'.gii') && ~strcmp(e,'.img') % freesurfer format + v = cat_io_FreeSurfer('read_surf_data',v); + else + if strcmp([n e],'SPM.mat') + swd = pwd; + spm_figure('GetWin','Interactive'); + [SPM,v] = spm_getSPM(struct('swd',p)); + cd(swd); + else + try spm_vol(v); catch, v = gifti(v); end; + end + end +end +if isa(v,'gifti'), v = v.cdata; end +if isa(v,'file_array'), v = v(); end + +set(H.patch,'UserData',v); + +if isempty(v) + v = zeros(size(curv))'; +elseif ischar(v) || iscellstr(v) || isstruct(v) + v = spm_mesh_project(H.patch,v); +elseif isnumeric(v) || islogical(v) + if size(v,2) == 1 + v = v'; + end +else + error('Unknown data type.'); +end +v(isinf(v)) = NaN; + +setappdata(H.patch,'data',v); + +%-Create RGB representation of data according to colourmap +%-------------------------------------------------------------------------- +C = zeros(size(v,2),3); +clim = getappdata(H.patch, 'clim'); +if isempty(clim), clim = [false NaN NaN]; end +mi = clim(2); ma = clim(3); +if any(v(:)) + if size(col,1)>3 && size(col,1) ~= size(v,1) + if size(v,1) == 1 + if ~clim(1), mi = min(v(:)); ma = max(v(:)); end + C = squeeze(ind2rgb(floor(((v(:)-mi)/(ma-mi))*size(col,1)),col)); + elseif isequal(size(v),[size(curv,1) 3]) + C = v; v = v'; + else + if ~clim(1), mi = min(v(:)); ma = max(v(:)); end + for i=1:size(v,1) + C = C + squeeze(ind2rgb(floor(((v(i,:)-mi)/(ma-mi))*size(col,1)),col)); + end + end + else + if ~clim(1), ma = max(v(:)); end + for i=1:size(v,1) + C = C + v(i,:)'/ma * col(i,:); + end + end +end + +clip = getappdata(H.patch, 'clip'); +if ~isempty(clip) + v(v>clip(2) & v"" with ""gt"" or ""lt"" +str_con(strfind(str_con,' ')) = '_'; +strpos = strfind(str_con,' > '); +if ~isempty(strpos), str_con = [str_con(1:strpos-1) '_gt_' str_con(strpos+1:end)]; end +strpos = strfind(str_con,' < '); +if ~isempty(strpos), str_con = [str_con(1:strpos-1) '_lt_' str_con(strpos+1:end)]; end +strpos = strfind(str_con,'>'); +if ~isempty(strpos), str_con = [str_con(1:strpos-1) 'gt' str_con(strpos+1:end)]; end +strpos = strfind(str_con,'<'); +if ~isempty(strpos), str_con = [str_con(1:strpos-1) 'lt' str_con(strpos+1:end)]; end +str_con = spm_str_manip(str_con,'v'); + +% build X and Y for GLM +Y = ROIvalues; +X = SPM.xX.X; + +% check whether mean relative ROI value is <0.1 and mean absolue ROI value is <0.1 of +% maximum mean ROI value +avgROIvalue = mean(Y); +avgROIvalue = avgROIvalue/max(avgROIvalue); % get value relative to max value +ind_toolow = (mean(relROIvalues) < 0.1 & avgROIvalue < 0.1); + +%-Apply global scaling +%-------------------------------------------------------------------------- +for i=1:size(Y,1) + Y(i,:) = Y(i,:)*SPM.xGX.gSF(i); +end + +% compare correlation coefficients after Fisher z-transformation +if compare_two_samples + % get two samples according to contrast -1 1 + Y1 = Y(find(X(:,find(c==-1))),:); + Y2 = Y(find(X(:,find(c== 1))),:); + + % estimate correlation and apply Fisher transformation + r1 = corrcoef(Y1); + r2 = corrcoef(Y2); + z1 = atanh(r1); + z2 = atanh(r2); + + Dz = (z1-z2)./sqrt(1/(size(Y1,1)-3)+1/(size(Y2,1)-3)); + + Pz = (1-spm_Ncdf(abs(Dz))); + Pzfdr = spm_P_FDR(Pz); + + Pz(isnan(Pz)) = 1; + Pzfdr(isnan(Pzfdr)) = 1; + + opt.label = ROInames; + + ind = (Pzfdr 2 + p_tissue = p(defined_measure); + [Psort0, indP0] = sort(p_tissue); + HBcorr = (length(Psort0):-1:1)'; + + % sometimes we have to transpose HBcorr for some unkwown reasons + HBcorr_ind = HBcorr(indP0); + if ~all(size(p_tissue) == size(HBcorr_ind)) + HBcorr_ind = HBcorr_ind'; + end + p_tissue = p_tissue.*HBcorr_ind; + Pcorr{3} = ones(size(p)); + Pcorr{3}(defined_measure) = p_tissue; + + if found_inv + p_tissue = 1 - p(defined_measure); + [Psort0, indP0] = sort(p_tissue); + HBcorr = length(Psort0):-1:1; + + % sometimes we have to transpose HBcorr for some unkwown reasons + HBcorr_ind = HBcorr(indP0); + if ~all(size(p_tissue) == size(HBcorr_ind)) + HBcorr_ind = HBcorr_ind'; + end + p_tissue = p_tissue.*HBcorr_ind; + Pcorr_inv{3} = ones(size(p)); + Pcorr_inv{3}(defined_measure) = p_tissue; + end +end + +atlas_loaded = 0; + +% set empty index for found results +ind_corr = cell(n_corr,1); +ind_corr_inv = cell(n_corr,1); +for c=1:n_corr + ind_corr{c} = []; + ind_corr_inv{c} = []; +end + +Pcorr_sel = cell(n_corr,1); +if found_inv + Pcorr_inv_sel = cell(n_corr,1); +end + +fprintf('\n%s\n',repmat('_',[1,100])); +fprintf('Analysis of %s in %s atlas using contrast %s from SPM.mat in \n%s\n',measure,atlas,str_con,cwd); +fprintf('%s\n',repmat('_',[1,100])); + +if found_inv + found_inv = spm_input('Also show inverse effects?','+1','b','yes|no',[1,0],1); +else + found_inv = 0; +end + +overlay_results = true; +print_warning = false; + +% go through left and right hemisphere and structures in both hemispheres +for i=sort(unique(hemi_code))' + + N_sel = ROInames(hemi_ind{i}); + ID_sel = ROIids(hemi_ind{i}); + B_sel = Beta(:,hemi_ind{i}); + Ze_sel = Ze(hemi_ind{i}); + statval_sel = statval(hemi_ind{i}); + hemi_code_sel = hemi_code(hemi_ind{i}); + ind_toolow_hemi = ind_toolow(hemi_ind{i}); + + for c=1:n_corr + Pcorr_sel{c} = Pcorr{c}(hemi_ind{i}); + if found_inv + Pcorr_inv_sel{c} = Pcorr_inv{c}(hemi_ind{i}); + end + end + + % sort p-values for FDR and sorted output + [Psort, indP] = sort(p(hemi_ind{i})); + if found_inv + [Psort_inv, indP_inv] = sort(1 - p(hemi_ind{i})); + end + + % select surface atlas for each hemisphere + if mesh_detected + Pinfo = cat_surf_info(SPM.xY.P{1},1); + if Pinfo(1).nvertices == 64984 + str32k = '_32k'; + else + str32k = ''; + end + + atlas_name = fullfile(fileparts(mfilename('fullpath')),['atlases_surfaces' str32k],... + [hemiabbr{i} '.' atlas '.freesurfer.annot']); + [vertices, rdata0, colortable, rcsv0] = cat_io_FreeSurfer('read_annotation',atlas_name); + data0 = round(rdata0); + + if write_beta + for k=1:length(ind_con) + dataBeta{k} = zeros(size(data0)); + end + end + + % create empty output data + for c=1:n_corr + data{c} = zeros(size(data0)); + end + else + % load volume atlas only once + if ~atlas_loaded + V = spm_vol(fullfile(cat_get_defaults('extopts.pth_templates'),[atlas '.nii'])); + data0 = round(spm_data_read(V)); + atlas_loaded = 1; + + % get number of ROIs and exclude background with ID==0 + sz_csv = size(csv,1)-1; + if csv{2,1} == 0 + sz_csv = sz_csv - 1; + end + + % compare number of ROIs between xml-file and atlas information in + % csv file and disable overlay of results if numbers differ + if sz_csv ~= numel(ROIids>0) + overlay_results = false; + show_results = 0; + fprintf('Overlay of ROIs was disabled because number of regions differ (probably due to use of older atlases): %d vs %d\n',sz_csv, numel(ROIids>0)); + end + + if write_beta + for k=1:length(ind_con) + dataBeta{k} = zeros(size(data0)); + end + end + + % create empty output data + for c=1:n_corr + data{c} = zeros(size(data0)); + end + end + end + + output_name = [num2str(100*alpha) '_' str_con '_' atlas '_' measure]; + atlas_name = [atlas '_' measure]; + + if write_beta + for k=1:length(ind_con) + for j=1:length(ID_sel) + dataBeta{k}(data0 == ID_sel(j)) = B_sel(ind_con(k),j); + end + end + end + + % display and save thresholded sorted p-values for each correction + for c=1:n_corr + ind = find(Pcorr_sel{c}(indP) 1, ind = ind'; end + if found_inv + ind_inv = find(Pcorr_inv_sel{c}(indP_inv) 1, ind_inv = ind_inv'; end + end + if ~isempty(ind) + ind_corr{c} = [ind_corr{c} ind]; + fprintf('\n%s (P<%g, %s):\n',hemistr{i},alpha,corr{c}); + if found_inv + fprintf('%9s\t%9s\t%9s\t%9s\t%s\n','P-value','contrast',[statstr '-value'],'Ze-value',atlas); + else + fprintf('%9s\t%9s\t%9s\t%s\n','P-value',[statstr '-value'],'Ze-value',atlas); + end + for j=1:length(ind) + data{c}(data0 == ID_sel(indP(ind(j)))) = -log10(Pcorr_sel{c}(indP(ind(j)))); + + % get name of ROI and exclude first hemi-indicator if necessary + if hemi_code_sel(indP(ind(j))) == 4 + rname = N_sel{indP(ind(j))}; + else + rname = N_sel{indP(ind(j))}(:,2:end); + end + + % add warning if some indicators are too low + if ind_toolow_hemi(indP(ind(j))) + warn_str = ' <--- Warning'; + print_warning = true; + else + warn_str = ''; + end + + if found_inv + fprintf('%9f\t%9s\t%9f\t%9f\t%s%s\n',Pcorr_sel{c}(indP(ind(j))),'',statval_sel(indP(ind(j))),Ze_sel(indP(ind(j))),rname,warn_str); + else + fprintf('%9f\t%9f\t%9f\t%s%s\n',Pcorr_sel{c}(indP(ind(j))),statval_sel(indP(ind(j))),Ze_sel(indP(ind(j))),rname,warn_str); + end + end + end + + if ~isempty(ind_inv) && found_inv + ind_corr_inv{c} = [ind_corr_inv{c} ind_inv]; + % print header here if no positive effects were found + if isempty(ind) + fprintf('\n%s (P<%g, %s):\n',hemistr{i},alpha,corr{c}); + if found_inv + fprintf('%9s\t%9s\t%9s\t%9s\t%s\n','P-value','contrast',[statstr '-value'],'Ze-value',atlas); + else + fprintf('%9s\t%9s\t%9s\t%s\n','P-value',[statstr '-value'],'Ze-value',atlas); + end + end + + if ~isempty(ind), fprintf('%s\n',repmat('-',[1,90])); end + for j=1:length(ind_inv) + % get name of ROI and exclude first hemi-indicator if necessary + if hemi_code_sel(indP_inv(ind_inv(j))) == 4 + rname = N_sel{indP_inv(ind_inv(j))}; + else + rname = N_sel{indP_inv(ind_inv(j))}(:,2:end); + end + + % add warning if some indicators are too low + if ind_toolow_hemi(indP_inv(ind_inv(j))) + warn_str = ' <--- Warning'; + print_warning = true; + else + warn_str = ''; + end + + data{c}(data0 == ID_sel(indP_inv(ind_inv(j)))) = log10(Pcorr_inv_sel{c}(indP_inv(ind_inv(j)))); + fprintf('%9f\t%9s\t%9f\t%9f\t%s%s\n',Pcorr_inv_sel{c}(indP_inv(ind_inv(j))),'inverse',statval_sel(indP_inv(ind_inv(j))),Ze_sel(indP_inv(ind_inv(j))),rname,warn_str); + end + end + + % write label surface with thresholded p-values + if mesh_detected + % save P-alues as float32 + filename1 = fullfile(cwd,[hemiabbr{i} '.logP' corr_short{c} output_name '.gii']); + save(gifti(struct('cdata',data{c})),filename1, 'Base64Binary'); + + if write_beta + for k=1:length(ind_con) + filename2 = sprintf('%s.beta%d_%s.gii',hemiabbr{i},ind_con(k),atlas_name); + save(gifti(struct('cdata',dataBeta{k})),filename2); + fprintf('\Beta image saved as %s.',filename2); + end + end + end + + end + fprintf('\n'); + +end + +% finally print warning if too low values were found +if print_warning + fprintf('%s\n',repmat('*',[1,90])) + fprintf('Warning: The indicated regions have values for %s that are smaller than %s of the \nrelative value and smaller than %s of the maximum tissue value.\n',measure,'20%','20%'); + fprintf('This points to regions that rather contain other more meaningful tissue classes and \nthese ROI results should be considered ctitically.\n'); + fprintf('%s\n',repmat('*',[1,90])) +end + +% prepare display ROI results according to found results +corr{n_corr+1} = 'Do not display'; +ind_show = []; + +for c=1:n_corr + if ~isempty(ind_corr{c}) || ~isempty(ind_corr_inv{c}) + ind_show = [ind_show c]; + else + fprintf('No results found for %s threshold of P<%g.\n',corr{c},alpha); + end +end + +% display ROI results +if nargin < 3 + if ~isempty(ind_show) && overlay_results + show_results = spm_input('Display ROI results?','+1','m',corr([ind_show n_corr+1]),[ind_show 0]); + else + show_results = 0; + end +end + +% merge hemispheres +if mesh_detected + + for c=1:n_corr + % name for combined hemispheres + name_lh = fullfile(cwd,['lh.logP' corr_short{c} output_name '.gii']); + name_rh = fullfile(cwd,['rh.logP' corr_short{c} output_name '.gii']); + name_mesh = fullfile(cwd,['mesh.logP' corr_short{c} output_name '.gii']); + + % combine left and right + M0 = gifti({name_lh, name_rh}); + M.cdata = [M0(1).cdata; M0(2).cdata]; + if ~found_inv, M.cdata(M.cdata < 0) = 0; end + M.private.metadata = struct('name','SurfaceID','value',name_mesh); + + if ~isempty(find(M.cdata~=0)) && overlay_results + save(gifti(M), name_mesh, 'Base64Binary'); + fprintf('\nLabel file with thresholded logP values (%s) was saved as %s.',corr{c},name_mesh); + end + spm_unlink(name_lh); + spm_unlink(name_rh); + end + + fprintf('\n'); + + if isempty(ind_show) + fprintf('No results found.\n'); + show_results = 0; + end + + % display ROI surface results + if show_results + name_mesh = fullfile(cwd,['mesh.logP' corr_short{show_results} output_name '.gii']); + cat_surf_results('Disp',name_mesh); + ROI_mode = spm_input('Use new customized ROI display?','+1','b','yes|no',[1,0],1); + if ROI_mode + cat_surf_results('texture', 3); % no texture + border_mode = 0; + if strcmp(atlas,'aparc_DK40') + border_mode = 1; + elseif strcmp(atlas,'aparc_a2009s') + border_mode = 2; + elseif strcmp(atlas,'aparc_HCP_MMP1') + border_mode = 3; + end + cat_surf_results('surface', 2); % inflated surface + if border_mode, cat_surf_results('border', border_mode); end + end + end + +else % write label volume with thresholded p-values + + if isempty(ind_show) + fprintf('No results found.\n'); + show_results = 0; + end + + % go through all corrections and save label image if sign. results were found + for c=1:n_corr + if ~isempty(ind_corr{c}) | ~isempty(ind_corr_inv{c}) + V.fname = fullfile(cwd,['logP' corr_short{c} output_name '.nii']); + V.dt(1) = 16; + if ~found_inv, data{c}(data{c} < 0) = 0; end + if ~isempty(find(data{c}~=0)) && overlay_results + spm_write_vol(V,data{c}); + fprintf('\nLabel file with thresholded logP values (%s) was saved as %s.',corr{c},V.fname); + end + end + end + + if write_beta + for k=1:length(ind_con) + V.fname = sprintf('beta%d_%s.nii',ind_con(k),atlas_name); + V.dt(1) = 16; + spm_write_vol(V,dataBeta{k}); + fprintf('\nBeta image was saved as %s.',V.fname); + end + end + + fprintf('\n'); + + % display ROI results for label image + if show_results + % display image as overlay + OV.reference_image = char(cat_get_defaults('extopts.shootingT1')); + OV.reference_range = [0.2 1.0]; % intensity range for reference image + OV.opacity = Inf; % transparency value for overlay (<1) + OV.cmap = jet; % colormap for overlay + mx = ceil(max(data{show_results}(isfinite(data{show_results})))); + OV.range = [-log10(alpha) mx]; + if found_inv & ~isempty(ind_corr_inv{show_results}) + mx = ceil(max(abs(data{show_results}(isfinite(data{show_results}))))); + OV.range = [-mx mx]; + end + OV.name = fullfile(cwd,['logP' corr_short{show_results} output_name '.nii']); + OV.save = 'png'; + OV.atlas = 'none'; + slices_str = spm_input('Select Slices','+1','m',{'-30:4:60','Estimate slices with local maxima'},{char('-30:4:60'),''}); + if ~isempty(slices_str{1}) + OV.xy = [4 6]; + end + OV.slices_str = slices_str{1}; + OV.transform = char('axial'); + cat_vol_slice_overlay(OV); + fprintf('You can again call the result file %s using Slice Overlay in CAT12 with more options to select different slices and orientations.\n',OV.name); + end + +end + +%_______________________________________________________________________ +function [p, Beta, tval] = estimate_GLM(Y,X,SPM,Ic); +% estimate GLM and return p-value for F- or T-test +% +% FORMAT [p, Beta, tval] = estimate_GLM(Y,X,SPM,Ic); +% Y - data matrix +% X - design matrix +% SPM - SPM structure +% Ic - selected contrast +% p - returned p-value +% Beta - returned beta values +% tval - returned t/F values + +c = SPM.xCon(Ic).c; +n = size(Y,1); +n_structures = size(Y,2); + +% estimate statistics for F- or T-test +if strcmp(SPM.xCon(Ic).STAT,'F') + df = [SPM.xCon(Ic).eidf SPM.xX.erdf]; + c0 = eye(size(X,2)) - c*pinv(c); + Xc = X*c; + X0 = X*c0; + + R = eye(n) - X*pinv(X); + R0 = eye(n) - X0*pinv(X0); + M = R0 - R; + + pKX = pinv(X); + trRV = n - rank(X); + p = rank(X); + p1 = rank(Xc); + + Beta = pKX * Y; + + yhat = X*Beta; + F = zeros(n,1); + + for i=1:n_structures + F(i) = (yhat(:,i)'*M*yhat(:,i))*(n-p)/((Y(:,i)'*R*Y(:,i))*p1); + end + + F(find(isnan(F))) = 0; + tval = F; + p = 1-spm_Fcdf(F,df); +else + df = SPM.xX.erdf; + pKX = pinv(X); + trRV = n - rank(X); + Beta = pKX * Y; + ResSS = sum((X*Beta - Y).^2); + + ResMS = ResSS/trRV; + + con = (c'*Beta); + Bcov = pinv(X'*X); + + ResSD = sqrt(ResMS.*(c'*Bcov*c)); + t = con./(eps+ResSD); + t(find(isnan(t))) = 0; + tval = t; + p = 1-spm_Tcdf(t,df); +end + +%_______________________________________________________________________ +function [sel_atlas, sel_measure, atlas, measure, measures] = get_atlas_measure(xml) +% get selected atlas and measure +% +% FORMAT [sel_atlas, sel_measure, atlas, measure, measures] = get_atlas_measure(xml); +% xml - xml structure +% +% sel_atlas - index of selected atlas +% sel_measure - index of selected measure +% atlas - name of selected atlas +% measure - name of selected measure +% measures - names of useful measures + +atlases = fieldnames(xml); +n_atlases = numel(atlases); + +% select one atlas +sel_atlas = spm_input('Select atlas','+1','m',atlases); +atlas = atlases{sel_atlas}; + +% get header of selected atlas +measures = fieldnames(xml.(atlas).data); + +% get rid of the thickness values that are saved for historical reasons +count = 0; +for i=1:numel(measures) + if ~strcmp(measures{i}(1),'T') + count = count + 1; + useful_measures{count} = measures{i}; + end +end +n_measures = numel(useful_measures); + +% select a measure +sel_measure = spm_input('Select measure','+1','m',useful_measures); +measure = useful_measures{sel_measure}; +measures = useful_measures; + +% remove spaces +measure = deblank(measure); +%_______________________________________________________________________ +function [ROInames, ROIids, ROIvalues, relROIvalues] = get_ROI_measure(roi_names, atlas, measures, sel_measure) +% get names, IDs and values inside ROI for a selected atlas +% +% FORMAT [ROInames ROIids ROIvalues] = get_ROI_measure(roi_names, sel_atlas, sel_measure); +% roi_names - cell of ROI xml files +% atlas - name of selected atlas +% measures - names of useful measures +% sel_measure - index of selected measure +% +% ROInames - array 2*rx1 of ROI names (r - # of ROIs) +% ROIids - array 2*rx1 of ROI IDs for left and right hemisphere +% ROIvalues - cell nxr of values inside ROI (n - # of data) +% relROIvalues - cell nxr of values inside ROI (n - # of data) relative to +% overall value + +n_data = length(roi_names); +measure = measures{sel_measure}; + +cat_progress_bar('Init',n_data,'Load xml-files','subjects completed') +for i=1:n_data + + xml = cat_io_xml(deblank(roi_names{i})); + + % remove leading catROI*_ part from name + [path2, ID] = fileparts(roi_names{i}); + ind = strfind(ID,'_'); + ID = ID(ind(1)+1:end); + + ROInames = xml.(atlas).names; + ROIids = xml.(atlas).ids; + + try + val = xml.(atlas).data.(measure); + catch + measure_found = 0; + for j=1:numel(measures) + if strcmp(deblank(measures{j}),deblank(measure_name)) + val = xml.(atlas).data.(measures{j}); + measure_found = 1; + break; + end + end + + % check that all measures were found + if ~measure_found + error('Please check your label files. Measure is not available in %s.\n',roi_names{i}); + end + end + + if i==1 + ROIvalues = zeros(n_data, numel(val)); + relROIvalues = ones(n_data, numel(val)); + end + + % get selected measure + ROIvalues(i,:) = xml.(atlas).data.(measure); + + % and also get all measures to estimate relative value + allROIvalues = zeros(1,numel(val)) + eps; + for j=1:numel(measures) + allROIvalues = allROIvalues + xml.(atlas).data.(measures{j})'; + end + relROIvalues(i,:) = ROIvalues(i,:)./allROIvalues; + + cat_progress_bar('Set',i); +end +cat_progress_bar('Clear'); +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_vol_createTPM.m",".m","31930","777","%function varagout = cat_vol_createTPM(job) +%cat_vol_createTPM. Script to create a CAT preprocessing template. +% Iterative generation of new preprocessing templates that include a tissue +% probability map (TPM), registration T1/T2 maps with/without head, a brain +% mask, Shooting and Dartel templates and atlas maps. +% It requires the Shooting input maps, and the averaged normalized tissue +% maps of GM, WM, CSF, hard and soft head, and background in the same space +% as the Shooting template. +% +% This script is part of a larger template script that should include most +% parts of an iteration (without preprocessing?). +% +% Iteration 1: +% - Run a preprocessing that support a segmentation with the 6 tissues and +% export all maps in a affine/rigid space by using a template that is +% close to your data. +% Also map the CAT atlas (or other atlas maps) to the same space. +% - Remove outlier and bad files with artifacts or too strong bias. +% - Run Shooting with class 1-2 (maybe also class 3) +% Check that the this process runs and not to many files get lost or the +% template shrinks. +% - Apply the Shooting deformation maps to all affine/rigid tissue maps and +% the CAT atlas to template space and average each map. +% - Resize the images if the boundary box is to big (to much empty space +% around the head) or parts of the heads are missing that are available +% in the input images, because the head tissues can help for bias +% correction but we do not need the whole body on the other side. +% - Run this script to obtain the first template that is maybe bias but +% should be closer than the template used at the beginning. +% Iteration 2: +% - Run everything again but this time you get hopefully the final template +% +% varagout = cat_vol_createTPM(job) +% +% job. +% files. +% ... +% verb +% ... +% +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ +% +% ToDo: +% * Documentation +% * Batch GUI +% * report/log file +% * progress bar +% * command line output +% * intensity normalization of T1 input +% * handling of T2 input and other modalities as further T1 files + + + dbs = dbstatus; debug = 0; for dbsi=1:numel(dbs), if strcmp(dbs(dbsi).name,mfilename); debug = 1; break; end; end + + if ~exist('job','var'), job = struct(); end + + % input files + def.files.tfiles = {''}; % Shooting template with 2 to 6 classes + def.files.pfiles = {''}; % 4 or 6 tissue maps + def.files.mfiles = {''}; % T1 map + def.files.afiles = {''}; % atlas maps + def.files.logfile = {''}; % log file to write on + % public parameter + def.verb = 2; % be verbose (2=display result) + def.rmShootBG = 1; % remove Shooting background class (yes for CAT but other?) + def.smoothness = 4; % main smoothing factor + def.atlasmedian = 1; % median filter atlas + % private parameter + % - template averaging parameter + def.tmixing = [0.7 0.15 0.10 0.10 0.05]; % weighting of Shooting template step + def.tsmooth = [0.125 0.25 0.50 0.75 1.00]; % smoothing of Shooting template step + def.scsize = [ 1 1 1 2 4 8 ]; % moreover we use a class specific filter size factor to support smoother head classes + % - tissue averaging parameter + def.ssize = [ 1.0 2.0 4.0 ]; % multiple smoothing levels to softly include also larger changes + def.sweight = [ 0.6 0.3 0.1 ]; % weighting of smoothing level for the average estimation + def.pweight = 0.2; % weighting of the tissue vs. shooting input + def.minprob = 0.01; % this value could be between 0.02 and 0.1 + def.fast = 1; % CAT vs. SPM smoothing + def.localsmooth = 1; % use further local smoothing within the tissue class (values from 0 to 1) + % - brain mask parameter + def.bcls = 1:3; % brain classes to define brain mask - there is maybe some subcortical classes + def.bclosing = 0.5; % just remove wholes + def.bsmoothing = 1; % final smoothing of the brain mask in voxels + % - further parameter + %def.esthdcls = 1; % estimate head classes based on the T1 map if required and possible (if T1 is available) + % write + def.write.name = 'MyTemplate'; % template name + def.write.outdir = ''; % main output directory + def.write.subdir = ''; % create sub directory + def.write.TPM = 1; % write TPM + def.write.TPMc = 1; % write separate TPM classes + def.write.TPM4 = 1; % write 4 class TPM + def.write.TPM4c = 1; % write separate 4 class TPM + def.write.T1 = 1; % write T1 + def.write.T2 = 1; % write T2 + def.write.GS = 1; % write Shooting template + def.write.DT = 1; % create and write Dartel template + job.write.brainmask = 1; % write brain mask + + job = cat_io_checkinopt(job,def); + + + if 0 + %% job.test + job.files.tfiles = { % Shooting template + '/Users/dahnke/Documents/MATLAB/spm12/toolbox/cat12/templates_animals/+chimpanzee create TPM/rchimpanzee_Template_0_GS.nii,1'; + '/Users/dahnke/Documents/MATLAB/spm12/toolbox/cat12/templates_animals/+chimpanzee create TPM/rchimpanzee_Template_1_GS.nii,1'; + '/Users/dahnke/Documents/MATLAB/spm12/toolbox/cat12/templates_animals/+chimpanzee create TPM/rchimpanzee_Template_2_GS.nii,1'; + '/Users/dahnke/Documents/MATLAB/spm12/toolbox/cat12/templates_animals/+chimpanzee create TPM/rchimpanzee_Template_3_GS.nii,1'; + '/Users/dahnke/Documents/MATLAB/spm12/toolbox/cat12/templates_animals/+chimpanzee create TPM/rchimpanzee_Template_4_GS.nii,1'; + }; + job.files.pfiles = { % normalized tissue maps - mean of the Shooting-normalized affine tissue segments ( wrp[1-6]*_affine.nii ) + '/Users/dahnke/Documents/MATLAB/spm12/toolbox/cat12/templates_animals/+chimpanzee create TPM/wp1chimp.nii,1'; + '/Users/dahnke/Documents/MATLAB/spm12/toolbox/cat12/templates_animals/+chimpanzee create TPM/wp2chimp.nii,1'; + '/Users/dahnke/Documents/MATLAB/spm12/toolbox/cat12/templates_animals/+chimpanzee create TPM/wp3chimp.nii,1'; + '/Users/dahnke/Documents/MATLAB/spm12/toolbox/cat12/templates_animals/+chimpanzee create TPM/wp4chimp.nii,1'; + '/Users/dahnke/Documents/MATLAB/spm12/toolbox/cat12/templates_animals/+chimpanzee create TPM/wp5chimp.nii,1'; + '/Users/dahnke/Documents/MATLAB/spm12/toolbox/cat12/templates_animals/+chimpanzee create TPM/wp6chimp.nii,1'; + }; + job.files.mfiles = { % normalized tissue maps - mean of the Shooting-normalized affine intensity-normalized maps ( wrm*_affine.nii) + '/Users/dahnke/Documents/MATLAB/spm12/toolbox/cat12/templates_animals/+chimpanzee create TPM/chimpanzee_T1.nii,1'; + }; + job.files.afiles = { % normalized tissue maps - mean of the Shooting-normalized affine CAT atlas maps ( wra0*_affine.nii ) + '/Users/dahnke/Documents/MATLAB/spm12/toolbox/cat12/templates_animals/+chimpanzee create TPM/chimpanzee_cat_hr.nii,1'; + '/Users/dahnke/Documents/MATLAB/spm12/toolbox/cat12/templates_animals/+chimpanzee create TPM/rchimpanzee_atlas_davi3.nii,1'; + }; + job.write.name = 'chimpanzee'; + job.write.subdir = 'chimp'; + + if 0 + %% correct cat side alignement if data was interpolated + Pm = job.files.mfiles{1}; Vm = spm_vol(Pm); Ym = spm_read_vols(Vm); + Pa = job.files.afiles{1}; Va = spm_vol(Pa); Ya = spm_read_vols(Va); + ds('d2sm','',1,Ym(:,:,:)/3 + (mod(Ya,2)==1)/3,single(Ya(:,:,:)/20),120) + %% estiate the offset + clear vxxyz; + offset = 2; % fit better for 1 mm resolution + vxi = find( (mod(Ya,2)==1 ) ); + [vxxyz(:,1),vxxyz(:,2),vxxyz(:,3)] = ind2sub(size(Ya), vxi); + vxxyz(:,1) = vxxyz(:,1) + offset; + vxi2 = sub2ind(size(Ya), vxxyz(:,1), vxxyz(:,2), vxxyz(:,3)); + modYa2 = false(size(Ya)); modYa2(vxi2) = true; + modYa2 = (mod(Ya,2)==1 ) - modYa2 & cat_vol_morph(mod(Ya,2)==0 & Ya>0,'d',offset ); + Yac = Ya; + Yac(modYa2 ) = Yac( modYa2 ) + 1 ; + ds('d2sm','',1,Ym(:,:,:)/3 + (mod(Ya,2)==1)/3, Ym(:,:,:)/3 + (mod(Yac,2)==1)/3,120) + %% save result + [ppa,ffa,eea] = spm_fileparts(Va.fname); Vac = Va; Vac.fname = fullfile(ppa,['c' ffa eea]); + spm_write_vol(Vac,Yac); + job.files.afiles{1} = Vac.fname; + end + + + + %% job.test + job.files.tfiles = { % Shooting template + '/Users/dahnke/Documents/MATLAB/spm12/toolbox/cat12/templates_animals/+macaque create TPM/rmacaque_Template_0_GS.nii,1'; + '/Users/dahnke/Documents/MATLAB/spm12/toolbox/cat12/templates_animals/+macaque create TPM/rmacaque_Template_1_GS.nii,1'; + '/Users/dahnke/Documents/MATLAB/spm12/toolbox/cat12/templates_animals/+macaque create TPM/rmacaque_Template_2_GS.nii,1'; + '/Users/dahnke/Documents/MATLAB/spm12/toolbox/cat12/templates_animals/+macaque create TPM/rmacaque_Template_3_GS.nii,1'; + '/Users/dahnke/Documents/MATLAB/spm12/toolbox/cat12/templates_animals/+macaque create TPM/rmacaque_Template_4_GS.nii,1'; + }; + job.files.pfiles = { % normalized tissue maps - mean of the Shooting-normalized affine tissue segments ( wrp[1-6]*_affine.nii ) + '/Users/dahnke/Documents/MATLAB/spm12/toolbox/cat12/templates_animals/+macaque create TPM/wp1macaque.nii,1'; + '/Users/dahnke/Documents/MATLAB/spm12/toolbox/cat12/templates_animals/+macaque create TPM/wp2macaque.nii,1'; + '/Users/dahnke/Documents/MATLAB/spm12/toolbox/cat12/templates_animals/+macaque create TPM/wp3macaque.nii,1'; + '/Users/dahnke/Documents/MATLAB/spm12/toolbox/cat12/templates_animals/+macaque create TPM/wp4macaque.nii,1'; + '/Users/dahnke/Documents/MATLAB/spm12/toolbox/cat12/templates_animals/+macaque create TPM/wp5macaque.nii,1'; + '/Users/dahnke/Documents/MATLAB/spm12/toolbox/cat12/templates_animals/+macaque create TPM/wp6macaque.nii,1'; + }; + job.files.mfiles = { % normalized tissue maps - mean of the Shooting-normalized affine intensity-normalized maps ( wrm*_affine.nii) + '/Users/dahnke/Documents/MATLAB/spm12/toolbox/cat12/templates_animals/+macaque create TPM/macaque_T1.nii,1'; + }; + job.files.afiles = { % normalized tissue maps - mean of the Shooting-normalized affine CAT atlas maps ( wra0*_affine.nii ) + '/Users/dahnke/Documents/MATLAB/spm12/toolbox/cat12/templates_animals/+macaque create TPM/macaque_cat.nii,1'; + }; + job.write.name = 'macaque'; + job.write.subdir = 'mac'; + end + + % helping functions + cell2num = @(x) cell2mat( shiftdim(x(:), -ndims(x{1})) ) ; + clsnorm = @(x) shiftdim( num2cell( cell2num(x) ./ repmat( sum( cell2num(x) , ndims(x{1}) + 1) , ... + [ones(1,ndims(x{1})),numel(x)]) , 1:ndims(x{1})) , -ndims(x{1})) ; + + + %% load main data + Vtemp0 = spm_vol(job.files.tfiles{1}); + vx_vol = sqrt(sum(Vtemp0.mat(1:3,1:3).^2)); + ncls = 6; % we allways want 6 tissue classes right now + + pp0 = spm_fileparts(job.files.tfiles{1}); + if isempty(job.write.outdir) + if isempty(job.write.subdir) + job.write.outdir = pp0; + else + job.write.outdir = fullfile(pp0,job.write.subdir); + end + if ~exist(job.write.outdir,'dir') + mkdir(job.write.outdir); + end + end + + + if numel( job.tmixing ) == 1 + job.tmixing = repmat( job.tmixing , 1 , ncls ); + end + + + + % create empty TPM + Ytpm = cell(1,ncls); + for ci = 1:ncls + Ytpm{ci} = zeros(Vtemp0.dim,'single'); + end + % load template + tempdims = 1; + for ti = 1:numel(job.files.tfiles) + [pp,ff,ee] = spm_fileparts(job.files.tfiles{ti}); + for ci = 1:ncls + Vtemp = spm_vol( fullfile(pp,sprintf('%s%s,%d',ff,ee,ci)) ); + if ~isempty(Vtemp) + Ytemp = single( spm_read_vols( Vtemp ) ); + Ytemp(isnan(Ytemp)) = 0; + Ytemp = max(0,min(1,Ytemp)); + if job.fast + Ytemp = cat_vol_smooth3X( Ytemp , job.tsmooth(ti) .* job.scsize(ci) ./ mean(vx_vol)); + else + spm_smooth(Ytemp,Ytemp,job.tsmooth(ti) .* job.scsize(ci) ./ vx_vol); + end + Ytpm{ci} = Ytpm{ci} + Ytemp .* job.tmixing(ti); + tempdims = ci; + end + end + end + % handling of Shooting background + Ytpm{tempdims} = zeros(Vtemp0.dim,'single'); + + + % load tissues + Ycls = cell(1,numel(job.files.pfiles)); + Vcls = spm_vol(char(job.files.pfiles)); + for ci = 1:numel(job.files.pfiles) + Ycls{ci} = max(0, min( 1, single( spm_read_vols( Vcls(ci) ) ) )); + end + + + % load tissues + if isempty( job.files.mfiles ) || isempty( job.files.mfiles{1} ) + Vm = spm_vol(job.files.mfiles{1}); + Ym = single( spm_read_vols( Vm ) ); + else + Ym = Ycls{3}/3 + Ycls{1}/3*2 + Ycls{2} + Ycls{5}; + Yi = Ycls{3}*2 + Ycls{1} + Ycls{2}*0.5 + Ycls{5}*2; + end + + + % load atlases + Ya = cell(1,numel(job.files.afiles)); + Va = spm_vol(char(job.files.afiles)); + for ai = 1:numel(job.files.afiles) + Ya{ai} = single( spm_read_vols( Va(ai) ) ); + end + + + + + % find background + % We cannot be sure if we got a background layer and which one it is. + % Hence, we use a box at the image boundary to count the assigned voxel to + % detect if there is a background in any given layer. If not we have to + % create one by the missed voxels, else we have to guaranty that the last + % class is the background. + bd = 4; + Ybgb = true(size(Ycls{1})); Ybgb(bd:end-(bd-1),bd:end-(bd-1),bd:end-(bd-1)) = false; + tpmbg = zeros(1,ncls); for ci = 1:ncls, tpmbg(ci) = sum(Ycls{ci}(Ybgb)>0) / sum(Ybgb(:)); end; %clear Ybgb; + [t,bg] = max(tpmbg .* (tpmbg>eps)); clear t; %#ok % bg is the old background class, we will need it + [YD,YI] = cat_vbdist(single(1-Ybgb)); clear YD; + + + % create brain mask + % Our background maybe also include CSF or other low intensity voxels. + % So we have to create a brain mask and correct it. + Yb = sum( cell2num( Ycls( unique( min( setdiff( job.bcls , bg) , numel(Ycls) )) ) ) , 4); + Yb = max(Yb, cat_vol_smooth3X(single(cat_vol_morph(Yb>0.1,'lc',job.bclosing)),job.bsmoothing/mean(vx_vol))); + Ycls{bg} = Ycls{bg} .* (1 - Yb); + + Ybg = Ycls{bg} + (1 - sum( cell2num(Ycls) , ndims(Ycls{1}) + 1)) .* ... + smooth3(sum( cell2num(Ycls(1:3)) , ndims(Ycls{1}) + 1) <= eps); + Ycls{end} = Ybg; + + + % if the t1/t2 maps does not contain the background than add it + if mean( Ym(~Yb(:) & (Ycls{4}(:) + Ycls{5}(:))>0.5) ) < 0.2 + Ym = Ym + Ycls{5}; + Yi = Yi + Ycls{5} * 2; + end + Ym = Ym(YI); + Yi = Yi(YI); + + + + %% smoothing & mixing + % the goal is to remove time point specific spatial information but keep + % the main folding pattern + Yclss = Ycls; + for si = 1:numel(job.ssize) + for ci = 1:numel(Yclss) + Yclsts = Yclss{ci} + 0 .* Ybgb; + + if job.fast + % cat_vol_smooth3X is much faster in case of higher resolutions and + % the image boundaries are better. However, the result is to strong + % filtered for higher values do to the resolution reduction and I + % use sqrt to reduce this effect here. + % This also increase the background boundary effect. + if mean(job.ssize(si) .* job.scsize(ci) ./ vx_vol) > 0 + Yclsts = cat_vol_smooth3X( Yclsts , mean( (job.ssize(si) .* ... + job.scsize(ci) .* job.smoothness ./ vx_vol).^1/2) ) * job.sweight(si); + end + else + spm_smooth( Yclsts * job.sweight(si) , Yclsts, job.ssize(si) ... + .* job.scsize(ci) .* job.smoothness ./ vx_vol ); + end + if ci<6, Yclsts = Yclsts .* (1-Ybgb); end + + % local smoothing this will further reduce the ribbon effect + if job.localsmooth + Yclsts = Yclsts * (1-job.sweight(si)) * (1-job.localsmooth) + ... + job.localsmooth .* cat_vol_localstat(Yclsts,Yclsts>0,job.localsmooth,1) * job.sweight(si); + end + + % define minimum prob of each class + Yclsts = max( Yclsts , job.minprob * job.sweight(si)); + + % use the brain mask to support a harder brain boundary + if ci<4 + Yclsts = Yclsts .* Yb; + else + Yclsts = Yclsts .* (1-Yb); + end + + % combine the different smoothing levels + if si==1 + Yclss{ci} = Yclsts; + else + Yclss{ci} = Yclss{ci} + Yclsts; + end + end + cat_progress_bar('Set',fi-0.8 + (0.7 * si / numel(job.ssize))); + end + for ci=1:3, Yclss{ci} = max( Yclss{ci} .* (1 - Ybgb) , job.minprob .* Yb ); end + for ci=4:5, Yclss{ci} = max( Yclss{ci} .* (1 - Ybgb) , job.minprob .* (1-Yb) ); end + for ci=4:6, Yclss{ci} = Yclss{ci}(YI); end + % normalize probabilities + Yclss = clsnorm(Yclss); + clear Yclsts; + + + + + %% mix Shooting and smooth tissue data + for ci = 1:tempdims-1 + Ytpm{ci} = Ytpm{ci}*(1-job.pweight) + job.pweight*Yclss{ci} .* (1-Ybgb); + end + for ci = tempdims:ncls + Ytpm{ci} = Yclss{ci}; + end + Ytpm = clsnorm(Ytpm); + + + % optimize CAT (and other) atlases ???? + % * update brain mask ? - yes + % * update tissue ? - no + % * checke range + LAB = cat_get_defaults('extopts.LAB'); + FN = fieldnames(LAB); + FN = setdiff( FN , {'NB'}); + for ai = 1:numel(job.files.afiles) + [pp,ff,ee] = spm_fileparts(job.files.afiles{ai}); + if strfind(ff,'_cat') + % udpate brain mask and head definition + for labi = 1:numel(FN); + Ya{ai}(Ya{ai} == LAB.(FN{labi}) & Yb<=eps) = 0; + end + [D,I] = cat_vbdist(single(Ya{ai})); Ys = 1 - mod(Ya{ai}(I),2); clear D I; + Ya{ai}(Ycls{5}>1/3) = LAB.HD + Ys(Ycls{5}>1/3); + else + Ya{ai}(Yb==eps) = 0; + end + if job.atlasmedian + Ya{ai} = cat_vol_median3c(Ya{ai}); + end + end + + + + %% Write output + % --------------------------------------------------------------------- + + + + % 1) TPM + % --------------------------------------------------------------------- + % TPMs were defined as uint8 range 0 to 255 + + % - save 6 class TPM + if job.write.TPM + out.tpm = fullfile(job.write.outdir,sprintf('%s_TPM.nii',job.write.name)); + Ndef = nifti; + Ndef.dat = file_array( out.tpm ,[size(Ytpm{1}),numel(Ytpm)],... + [spm_type('uint8') spm_platform('bigend')],0,1/255,0); + Ndef.mat = Vtemp0.mat; + Ndef.mat0 = Vtemp0.mat; + Ndef.descrip = sprintf('%s TPM with GM, WM, CSF, hard and soft HD, and BG',job.write.name); + create(Ndef); + Ndef.dat(:,:,:,:,:) = cell2num(Ytpm); + else + out.tpm = {}; + end + + % - save 5 class TPM + if job.write.TPMc + for ci=1:ncls + out.tpmc{ci} = fullfile(job.write.outdir,sprintf('%s_TPM_%d.nii',job.write.name,ci)); + Ndef = nifti; + Ndef.dat = file_array( out.tpmc{ci} ,size(Ytpm{ci}),... + [spm_type('uint8') spm_platform('bigend')],0,1/255,0); + Ndef.mat = Vtemp0.mat; + Ndef.mat0 = Vtemp0.mat; + Ndef.descrip = sprintf('%s TPM tissue class %d',job.write.name,ci); + create(Ndef); + Ndef.dat(:,:,:) = cell2num(Ytpm(ci)); + end + else + out.tpmc = {}; + end + + % - save 4 class TPM + if job.write.TPM4 + Ytpm4 = Ytpm(1:3); + Ytpm4{4} = sum( cell2num(Ytpm(4:end)) , ndims(Ytpm{1}) + 1); + out.tpm4 = fullfile(job.write.outdir,sprintf('%s_TPM4.nii',job.write.name)); + Ndef = nifti; + Ndef.dat = file_array( out.tpm4 ,[size(Ytpm4{1}),numel(Ytpm4)],... + [spm_type('uint8') spm_platform('bigend')],0,1/255,0); + Ndef.mat = Vtemp0.mat; + Ndef.mat0 = Vtemp0.mat; + Ndef.descrip = sprintf('%s TPM with GM, WM, CSF, and BG',job.write.name); + create(Ndef); + Ndef.dat(:,:,:,:,:) = cell2num(Ytpm4); + else + out.tpm4 = {}; + end + + % save 4 class TPM + if job.write.TPM4c + Ytpm4 = Ytpm(1:3); + Ytpm4{4} = sum( cell2num(Ytpm(4:end)) , ndims(Ytpm{1}) + 1); + for ci=1:4 + out.tpm4c{ci} = fullfile(job.write.outdir,sprintf('%s_TPM4_%d.nii',job.write.name,ci)); + + Ndef = nifti; + Ndef.dat = file_array( out.tpm4c{ci} ,size(Ytpm4{ci}),... + [spm_type('uint8') spm_platform('bigend')],0,1/255,0); + Ndef.mat = Vtemp0.mat; + Ndef.mat0 = Vtemp0.mat; + Ndef.descrip = sprintf('%s TPM tissue class %d',job.write.name,ci); + create(Ndef); + Ndef.dat(:,:,:) = cell2num(Ytpm4(ci)); + end + else + out.tpm4c = {}; + end + + + % 2) average T1/T2 maps + % --------------------------------------------------------------------- + % - write T1 output + if job.write.T1 + out.t1 = fullfile(job.write.outdir,sprintf('%s_T1.nii',job.write.name)); + Ndef = nifti; + Ndef.dat = file_array( out.t1 ,size(Ym),... + [spm_type('uint8') spm_platform('bigend')],0,1/255,0); + Ndef.mat = Vtemp0.mat; + Ndef.mat0 = Vtemp0.mat; + Ndef.descrip = sprintf('%s T1 average',job.write.name); + create(Ndef); + Ndef.dat(:,:,:) = Ym; + else + out.t1 = {}; + end + % - write T1 brain masked output + if job.write.T1 + out.t1b = fullfile(job.write.outdir,sprintf('%s_T1b.nii',job.write.name)); + Ndef = nifti; + Ndef.dat = file_array( out.t1b ,size(Ym),... + [spm_type('uint8') spm_platform('bigend')],0,1/255,0); + Ndef.mat = Vtemp0.mat; + Ndef.mat0 = Vtemp0.mat; + Ndef.descrip = sprintf('%s T1 average brainmasked',job.write.name); + create(Ndef); + Ndef.dat(:,:,:) = Ym .* Yb; + else + out.t1b = {}; + end + + % - write T2 output + if job.write.T1 + out.t2 = fullfile(job.write.outdir,sprintf('%s_T2.nii',job.write.name)); + Ndef = nifti; + Ndef.dat = file_array( out.t2 ,size(Yi),... + [spm_type('uint8') spm_platform('bigend')],0,1/255,0); + Ndef.mat = Vtemp0.mat; + Ndef.mat0 = Vtemp0.mat; + Ndef.descrip = sprintf('%s T2 average',job.write.name); + create(Ndef); + Ndef.dat(:,:,:) = Yi/2; + else + out.t2 = {}; + end + % - write T2 brain masked output + if job.write.T1 + out.t2b = fullfile(job.write.outdir,sprintf('%s_T2b.nii',job.write.name)); + Ndef = nifti; + Ndef.dat = file_array( out.t2b ,size(Yi),... + [spm_type('uint8') spm_platform('bigend')],0,1/255,0); + Ndef.mat = Vtemp0.mat; + Ndef.mat0 = Vtemp0.mat; + Ndef.descrip = sprintf('%s T2 average brainmasked',job.write.name); + create(Ndef); + Ndef.dat(:,:,:) = Yi/2 .* Yb; + else + out.t2b = {}; + end + + + + + % brain mask + % --------------------------------------------------------------------- + if job.write.brainmask + out.bm = fullfile(job.write.outdir,sprintf('%s_brainmask.nii',job.write.name)); + Ndef = nifti; + Ndef.dat = file_array( out.bm ,size(Yi),... + [spm_type('uint8') spm_platform('bigend')],0,1/255,0); + Ndef.mat = Vtemp0.mat; + Ndef.mat0 = Vtemp0.mat; + Ndef.descrip = sprintf('%s brainmask',job.write.name); + create(Ndef); + Ndef.dat(:,:,:) = Yb; + else + out.bm = {}; + end + + + + % 3) Dartel/Shooting Templates + % --------------------------------------------------------------------- + + % - Update Shooting template + % - remove background class and NaNs (e.g. from interpolation) + if job.write.GS + for ti = 1:numel(job.files.tfiles) + [pp,ff,ee] = spm_fileparts(job.files.tfiles{ti}); + Ytmp = cell(1,tempdims - job.rmShootBG); + for ci = 1:tempdims - job.rmShootBG + Vtemp = spm_vol( fullfile(pp,sprintf('%s%s,%d',ff,ee,ci)) ); + Ytmp{ci} = spm_read_vols( Vtemp ); + Ytmp{ci}(isnan(Ytmp{ci})) = 0; + Ytmp{ci} = min(1,max(0,single( Ytmp{ci} ))); + end + + out.GS{ti} = fullfile(job.write.outdir,sprintf('%s_Template_%d_GS.nii',job.write.name,ti-1)); + Ndef = nifti; + Ndef.dat = file_array( out.GS{ti} ,[size(Ytmp{1}), numel(Ytmp)],... + ...[spm_type('float32') spm_platform('bigend')],0,1,0); + [spm_type('uint8') spm_platform('bigend')],0,1/255,0); + Ndef.mat = Vtemp0.mat; + Ndef.mat0 = Vtemp0.mat; + Ndef.descrip = sprintf('%s Shooting template',job.write.name,ti); + create(Ndef); + Ndef.dat(:,:,:,:) = cell2num(Ytmp); + end + else + out.GS = {}; + end + + + % - Simulate Dartel template + if job.write.DT + job.GS2DT = { + '1' 0 1; + '2' [0 1] [0.5 0.5]; + '3' 1 1; + '4' 2 1; + '5' 3 1; + '6' 4 1; + }; + + for nti = 1:size(job.GS2DT,1) + Ytmp = cell(1,tempdims - job.rmShootBG); + for ci = 1:tempdims - job.rmShootBG + Ytmp{ci} = zeros(Vtemp0.dim,'single'); + end + + [pp,ff,ee] = spm_fileparts(job.files.tfiles{1}); + for ti = 1:numel(job.GS2DT{nti,2}) + ff1 = strrep(ff,sprintf('_0_GS'),sprintf('_%d_GS',job.GS2DT{nti,2}(ti))); + + for ci = 1:tempdims - job.rmShootBG + Vtemp = spm_vol( fullfile(pp,sprintf('%s%s,%d',ff1,ee,ci)) ); + if ~isempty(Vtemp) + Ytemp = single( spm_read_vols( Vtemp ) ); + Ytemp(isnan(Ytemp)) = 0; + Ytemp = min(1,max(0,Ytemp)); + Ytmp{ci} = Ytmp{ci} + Ytemp .* job.GS2DT{nti,3}(ti); + end + end + end + + out.DT{nti} = fullfile(job.write.outdir,sprintf('%s_Template_%d.nii',job.write.name,nti)); + Ndef = nifti; + Ndef.dat = file_array( out.DT{nti} ,[size(Ytmp{1}), numel(Ytmp)],... + ... [spm_type('float32') spm_platform('bigend')],0,1,0); + [spm_type('uint8') spm_platform('bigend')],0,1/255,0); + Ndef.mat = Vtemp0.mat; + Ndef.mat0 = Vtemp0.mat; + Ndef.descrip = sprintf('%s simulated Dartel template',job.write.name,nti); + create(Ndef); + Ndef.dat(:,:,:,:) = cell2num(Ytmp); + end + else + out.DT = {}; + end + + + + + + % - write atlas maps + if exist('Ya','var') + % get names of possible txt and csv files + for ai = 1:numel(job.files.afiles) + [pp,ff] = spm_fileparts(job.files.afiles{ai}); + Patlastxt{ai} = fullfile(pp,[ff '.txt']); + Patlascsv{ai} = fullfile(pp,[ff '.csv']); + end + % new filenames + out.atlas{1} = fullfile(job.write.outdir,sprintf('%s_cat.nii',job.write.name)); + out.atlastxt{1} = fullfile(job.write.outdir,sprintf('%s_cat.txt',job.write.name)); + out.atlascsv{1} = fullfile(job.write.outdir,sprintf('%s_cat.csv',job.write.name)); + for ai = 2:numel(job.files.afiles) + [pp,ff,ee] = spm_fileparts(job.files.afiles{ai}); + out.atlas{ai} = fullfile(job.write.outdir,sprintf('%s_%s.nii',job.write.name,ff)); + out.atlastxt{ai} = fullfile(job.write.outdir,sprintf('%s_%s.txt',job.write.name,ff)); + out.atlascsv{ai} = fullfile(job.write.outdir,sprintf('%s_%s.csv',job.write.name,ff)); + end + for ai = 1:numel(job.files.afiles) + % txt and csv + if exist( Patlastxt{ai}, 'file' ), copyfile( Patlastxt{ai}, out.atlastxt{ai},'f' ); end + if exist( Patlascsv{ai}, 'file' ), copyfile( Patlascsv{ai}, out.atlascsv{ai},'f' ); end + % nifti + if max(Ya{ai}(:))>255, dtype = 'uint16'; else, dtype = 'uint8'; end + Ndef = nifti; + Ndef.dat = file_array( out.atlas{ai} ,size(Ya{ai}),... + [spm_type(dtype) spm_platform('bigend')],0,1,0); + Ndef.mat = Vtemp0.mat; + Ndef.mat0 = Vtemp0.mat; + Ndef.descrip = sprintf('%s simulated Dartel template',job.write.name,nti); + create(Ndef); + Ndef.dat(:,:,:) = Ya{ai}; + end + else + out.atlas = {}; + end + + + %% - log output + % ####################################################################### + % It would be good to write a report / log file that include all input + % output files and their dates, file-size, datatype and resolution ... + % It should also include some based text defined at the beginning about + % this script. + % Moreover, they should be added to a general log file if given. + % ####################################################################### + out.log = fullfile(job.write.outdir,sprintf('%s.log',job.write.name)); + txt = { + [job.write.name ' template:'] + ... general text, how to use, copyrights + ' Date-time: ' + ' CAT-Version: ' + ' Script-Version: ' + ' Files: ' + }; + + + + if isempty(job.files.logfile) + % create new file + else + % copy old file and add lines + end + + + + % - display output + if job.verb + % display TPM 1-3 + % display TPM 5-6 + % display TMP 0 2 4 + % display T1 T2 bm atlas + fnum = [5,3]; pos = cell(fnum); + for j=1:fnum(1) + for i=1:fnum(2) + pos{j,i} = [ 0.01 + (i-1) * 1/fnum(2) , 1.02 - ( j * 1/fnum(1) ) , 0.96/fnum(2), 0.96/fnum(1)]; + end + end + spm_figure('Clear',spm_figure('GetWin','Graphics')); + spm_orthviews('Reset'); % remove old settings + + % title + ax = axes; + set(ax,'Position',[0 0.97 1 0.03],'visible','off') + a = annotation('textbox','Position',[0 0.97 1 0.03],'String',[job.write.name ' template'],... + 'FontSize',14,'FontWeight','bold','LineStyle','none','HorizontalAlignment','center','Interpreter','none'); + set(a,'Parent',ax); + + % row 1: T1 T2 brain mask + if ~isempty(out.t1), ho = spm_orthviews('Image',out.t1,pos{1,1}); spm_orthviews('Caption', ho, 'T1'); end + if ~isempty(out.t2), ho = spm_orthviews('Image',out.t2,pos{1,2}); spm_orthviews('Caption', ho, 'T2'); end + if ~isempty(out.bm), ho = spm_orthviews('Image',out.bm,pos{1,3}); spm_orthviews('Caption', ho, 'brainmask'); end + % row 2-3: TPM + if ~isempty(out.tpm) + for ci=1:3, ho = spm_orthviews('Image',sprintf('%s,%d',out.tpm,ci),pos{2,ci}); spm_orthviews('Caption', ho, sprintf('class %d',ci)); end + for ci=4:6, ho = spm_orthviews('Image',sprintf('%s,%d',out.tpm,ci),pos{3,ci-3}); spm_orthviews('Caption', ho, sprintf('class %d',ci)); end + elseif ~isempty(out.tpmc) + for ci=1:3, ho = spm_orthviews('Image',out.tpmc{ci},pos{2,ci}); spm_orthviews('Caption', ho, sprintf('class %d',ci)); end + for ci=4:6, ho = spm_orthviews('Image',out.tpmc{ci},pos{3,ci-3}); spm_orthviews('Caption', ho, sprintf('class %d',ci)); end + end + % row 4: template + if ~isempty(out.tpm) + for ci=1:3, ho = spm_orthviews('Image',out.GS{ci*2-1},pos{4,ci}); spm_orthviews('Caption', ho, sprintf('Shooting template %d',ci*2-1)); end + end + if ~isempty(out.atlas) + for ci=1:numel(out.atlas), ho = spm_orthviews('Image',out.atlas{ci},pos{5,ci}); spm_orthviews('Caption', ho, sprintf('atlas %d',ci)); end + end + spm_orthviews('Reposition', [0 0 0]) + + % save + job.imgprint.type = 'png'; + job.imgprint.dpi = 600; + job.imgprint.fdpi = @(x) ['-r' num2str(x)]; + job.imgprint.ftype = @(x) ['-d' num2str(x)]; + job.imgprint.fname = fullfile(job.write.outdir,[job.write.name '_Template.' job.imgprint.type]); + + fg = spm_figure('GetWin','Graphics'); + fgold.PaperPositionMode = get(fg,'PaperPositionMode'); + fgold.PaperPosition = get(fg,'PaperPosition'); + fgold.resize = get(fg,'resize'); + + % it is necessary to change some figure properties especially the fontsizes + set(fg,'PaperPositionMode','auto','resize','on','PaperPosition',[0 0 1 1]); + + % the PDF is is an image because openGL is used but -painters would not look good for surfaces ... + print(fg, job.imgprint.ftype(job.imgprint.type), job.imgprint.fdpi(job.imgprint.dpi), job.imgprint.fname); + + end +%end +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_spm_preproc_write.m",".m","12129","381","function [Ym,Ycls,Yy] = cat_spm_preproc_write(p,opts) +% Write out VBM preprocessed data +% FORMAT spm_preproc_write(p,opts) +% p - results from spm_prep2sn +% opts - writing options. A struct containing these fields: +% biascor - write bias corrected image +% cleanup - level of brain segmentation cleanup +% GM - flags for which images should be written +% WM - similar to GM +% CSF - similar to GM +%__________________________________________________________________________ +% Copyright (C) 2005-2016 Wellcome Trust Centre for Neuroimaging + +% John Ashburner +% $Id: spm_preproc_write.m 6894 2016-09-30 16:48:46Z spm $ + +if ischar(p), p = cellstr(p); end + +if nargin==1 + opts = spm_get_defaults('old.preproc.output'); +end + + +for i=1:numel(p) + if iscellstr(p), q = load(p{i}); else q = p(i); end + if i==1, + try + b0 = spm_load_priors(q.VG); + catch + which('spm_load_priors') + which('spm') + q.VG + end + end + if isscalar(p) + [Ym,Ycls,Yy] = preproc_apply(q,opts,b0); + else + if nargout~=0 + preproc_apply(q,opts,b0); + else + error('cat_spm_preproc_write:noMultifileOuput','Only output for one processing case.'); + end + end +end + + +%========================================================================== +% function preproc_apply(p,opts,b0) +%========================================================================== +function [Ym,dat,y] = preproc_apply(p,opts,b0) + +nclasses = size(fieldnames(opts),1) - 2 ; +switch nclasses + case 3 + sopts = [opts.GM ; opts.WM ; opts.CSF]; + case 4 + sopts = [opts.GM ; opts.WM ; opts.CSF ; opts.EXTRA1]; + case 5 + sopts = [opts.GM ; opts.WM ; opts.CSF ; opts.EXTRA1 ; opts.EXTRA2]; + otherwise + error('Unsupported number of classes.') +end + +T = p.flags.Twarp; +bsol = p.flags.Tbias; +d2 = [size(T) 1]; +d = p.VF.dim(1:3); + +[x1,x2,o] = ndgrid(1:d(1),1:d(2),1); +x3 = 1:d(3); +d3 = [size(bsol) 1]; +B1 = spm_dctmtx(d(1),d2(1)); +B2 = spm_dctmtx(d(2),d2(2)); +B3 = spm_dctmtx(d(3),d2(3)); +bB3 = spm_dctmtx(d(3),d3(3),x3); +bB2 = spm_dctmtx(d(2),d3(2),x2(1,:)'); +bB1 = spm_dctmtx(d(1),d3(1),x1(:,1)); + +mg = p.flags.mg; +mn = p.flags.mn; +vr = p.flags.vr; +K = length(p.flags.mg); +Kb = length(p.flags.ngaus); + +for k1=1:size(sopts,1) + dat{k1} = zeros(d(1:3),'uint8'); + if sopts(k1,3) + Vt = struct('fname', spm_file(p.VF.fname,'prefix',['c', num2str(k1)]),... + 'dim', p.VF.dim,... + 'dt', [spm_type('uint8') spm_platform('bigend')],... + 'pinfo', [1/255 0 0]',... + 'mat', p.VF.mat,... + 'n', [1 1],... + 'descrip', ['Tissue class ' num2str(k1)]); + Vt = spm_create_vol(Vt); + VO(k1) = Vt; + end +end +if opts.biascor + VB = struct('fname', spm_file(p.VF.fname,'prefix','m'),... + 'dim', p.VF.dim(1:3),... + 'dt', [spm_type('float32') spm_platform('bigend')],... + 'pinfo', [1 0 0]',... + 'mat', p.VF.mat,... + 'n', [1 1],... + 'descrip', 'Bias Corrected'); + VB = spm_create_vol(VB); +end + +lkp = []; for k=1:Kb, lkp = [lkp ones(1,p.flags.ngaus(k))*k]; end + +spm_progress_bar('init',length(x3),['Working on ' spm_file(p.VF.fname,'basename')],'Planes completed'); +M = p.VG(1).mat\p.flags.Affine*p.VF.mat; + +Ym = zeros(d(1:3),'single'); +if nargout>2 + y = zeros([d(1:3),3],'single'); +end +for z=1:length(x3) + + % Bias corrected image + f = spm_sample_vol(p.VF,x1,x2,o*x3(z),0); + cr = exp(transf(bB1,bB2,bB3(z,:),bsol)).*f; + Ym(:,:,z) = cr; + if opts.biascor + % Write a plane of bias corrected data + VB = spm_write_plane(VB,cr,z); + end + + if any(sopts(:)) + msk = (f==0) | ~isfinite(f); + [t1,t2,t3] = defs(T,z,B1,B2,B3,x1,x2,x3,M); + q = zeros([d(1:2) Kb]); + bt = zeros([d(1:2) Kb]); + + if nargout>2 + % If needed later, save in variable y + y(:,:,z,1) = t1; + y(:,:,z,2) = t2; + y(:,:,z,3) = t3; + end + + for k1=1:Kb + bt(:,:,k1) = spm_sample_priors(b0{k1},t1,t2,t3,k1==Kb); + end + b = zeros([d(1:2) K]); + for k=1:K + b(:,:,k) = bt(:,:,lkp(k))*mg(k); + end + s = sum(b,3); + for k=1:K + p1 = exp((cr-mn(k)).^2/(-2*vr(k)))/sqrt(2*pi*vr(k)+eps); + q(:,:,lkp(k)) = q(:,:,lkp(k)) + p1.*b(:,:,k)./s; + end + sq = sum(q,3)+eps; + sw = warning('off','MATLAB:divideByZero'); + for k1=1:size(sopts,1) + tmp = q(:,:,k1); + tmp(msk) = 0; + tmp = tmp./sq; + dat{k1}(:,:,z) = uint8(round(255 * tmp)); + end + warning(sw); + end + spm_progress_bar('set',z); +end +spm_progress_bar('clear'); + +if opts.cleanup > 0 + [dat{1},dat{2},dat{3}] = clean_gwc(dat{1},dat{2},dat{3}, opts.cleanup); +end +if any(sopts(:,3)) + for z=1:length(x3) + for k1=1:size(sopts,1) + if sopts(k1,3) + tmp = double(dat{k1}(:,:,z))/255; + spm_write_plane(VO(k1),tmp,z); + end + end + end +end + +for k1=1:size(sopts,1) + if any(sopts(k1,1:2)) + so = struct('wrap',[0 0 0],... + 'interp',1,... + 'vox',[NaN NaN NaN],... + 'bb',ones(2,3)*NaN,... + 'preserve',0); + ovx = abs(det(p.VG(1).mat(1:3,1:3)))^(1/3); + fwhm = max(ovx./sqrt(sum(p.VF.mat(1:3,1:3).^2))-1,0.1); + dat{k1} = decimate(dat{k1},fwhm); + dim = [size(dat{k1}) 1]; + VT = struct('fname', spm_file(p.VF.fname,'prefix',['c', num2str(k1)]),... + 'dim', dim(1:3),... + 'dt', [spm_type('uint8') spm_platform('bigend')],... + 'pinfo', [1/255 0]',... + 'mat', p.VF.mat,... + 'dat', dat{k1}); + if sopts(k1,2) + evalc('spm_write_sn(VT,p,so);'); + end + so.preserve = 1; + if sopts(k1,1) + evalc('VN = spm_write_sn(VT,p,so);'); + VN.fname = spm_file(p.VF.fname,'prefix',['mwc', num2str(k1)]); + spm_write_vol(VN,VN.dat); + end + end +end + + +%========================================================================== +% function [x1,y1,z1] = defs(sol,z,B1,B2,B3,x0,y0,z0,M) +%========================================================================== +function [x1,y1,z1] = defs(sol,z,B1,B2,B3,x0,y0,z0,M) +x1a = x0 + transf(B1,B2,B3(z,:),sol(:,:,:,1)); +y1a = y0 + transf(B1,B2,B3(z,:),sol(:,:,:,2)); +z1a = z0(z) + transf(B1,B2,B3(z,:),sol(:,:,:,3)); +x1 = M(1,1)*x1a + M(1,2)*y1a + M(1,3)*z1a + M(1,4); +y1 = M(2,1)*x1a + M(2,2)*y1a + M(2,3)*z1a + M(2,4); +z1 = M(3,1)*x1a + M(3,2)*y1a + M(3,3)*z1a + M(3,4); + + +%========================================================================== +% function t = transf(B1,B2,B3,T) +%========================================================================== +function t = transf(B1,B2,B3,T) +if ~isempty(T) + d2 = [size(T) 1]; + t1 = reshape(reshape(T, d2(1)*d2(2),d2(3))*B3', d2(1), d2(2)); + t = B1*t1*B2'; +else + t = zeros(size(B1,1),size(B2,1),size(B3,1)); +end + + +%========================================================================== +% function dat = decimate(dat,fwhm) +%========================================================================== +function dat = decimate(dat,fwhm) +% Convolve the volume in memory (fwhm in voxels). +lim = ceil(2*fwhm); +x = -lim(1):lim(1); x = spm_smoothkern(fwhm(1),x); x = x/sum(x); +y = -lim(2):lim(2); y = spm_smoothkern(fwhm(2),y); y = y/sum(y); +z = -lim(3):lim(3); z = spm_smoothkern(fwhm(3),z); z = z/sum(z); +i = (length(x) - 1)/2; +j = (length(y) - 1)/2; +k = (length(z) - 1)/2; +spm_conv_vol(dat,dat,x,y,z,-[i j k]); + + +%========================================================================== +% function [g,w,c] = clean_gwc(g,w,c,level) +%========================================================================== +function [g,w,c] = clean_gwc(g,w,c,level) +if nargin<4, level = 1; end + +b = w; +b(1) = w(1); + +% Build a 3x3x3 seperable smoothing kernel +%-------------------------------------------------------------------------- +kx=[0.75 1 0.75]; +ky=[0.75 1 0.75]; +kz=[0.75 1 0.75]; +sm=sum(kron(kron(kz,ky),kx))^(1/3); +kx=kx/sm; ky=ky/sm; kz=kz/sm; + +th1 = 0.15; +if level==2, th1 = 0.2; end +% Erosions and conditional dilations +%-------------------------------------------------------------------------- +niter = 32; +spm_progress_bar('Init',niter,'Extracting Brain','Iterations completed'); +for j=1:niter + if j>2, th=th1; else th=0.6; end % Dilate after two its of erosion + for i=1:size(b,3) + gp = double(g(:,:,i)); + wp = double(w(:,:,i)); + bp = double(b(:,:,i))/255; + bp = (bp>th).*(wp+gp); + b(:,:,i) = uint8(round(bp)); + end + spm_conv_vol(b,b,kx,ky,kz,-[1 1 1]); + spm_progress_bar('Set',j); +end +th = 0.05; +for i=1:size(b,3) + gp = double(g(:,:,i))/255; + wp = double(w(:,:,i))/255; + cp = double(c(:,:,i))/255; + bp = double(b(:,:,i))/255; + bp = ((bp>th).*(wp+gp))>th; + g(:,:,i) = uint8(round(255*gp.*bp./(gp+wp+cp+eps))); + w(:,:,i) = uint8(round(255*wp.*bp./(gp+wp+cp+eps))); + c(:,:,i) = uint8(round(255*(cp.*bp./(gp+wp+cp+eps)+cp.*(1-bp)))); +end +spm_progress_bar('Clear'); +return +% == required here but not found in parallel processing whyever == +function b0 = spm_load_priors(B) +% Loads the tissue probability maps for segmentation +% FORMAT b0 = spm_load_priors(B) +% B - structures of image volume information (or filenames) +% b0 - a cell array of tissue probabilities +%__________________________________________________________________________ +% Copyright (C) 2005-2011 Wellcome Trust Centre for Neuroimaging + +% John Ashburner +% $Id: spm_load_priors.m 4873 2012-08-30 19:06:26Z john $ + + +% deg = 3; +lm = 0; +if ~isstruct(B), B = spm_vol(B); end +Kb = length(B); +b0 = cell(Kb,1); +for k1=1:(Kb) + b0{k1} = zeros(B(1).dim(1:3)); +end + +spm_progress_bar('Init',B(1).dim(3),'Loading priors','Planes loaded'); +for i=1:B(1).dim(3) + M = spm_matrix([0 0 i]); + s = zeros(B(1).dim(1:2)); + for k1=1:Kb + tmp = spm_slice_vol(B(k1),M,B(1).dim(1:2),0)*(1-lm*2)+lm; + b0{k1}(:,:,i) = max(min(tmp,1),0); + s = s + tmp; + end + t = s>1; + if any(any(t)) + for k1=1:Kb + tmp = b0{k1}(:,:,i); + tmp(t) = tmp(t)./s(t); + b0{k1}(:,:,i) = tmp; + end + end + s(t) = 1; + b0{Kb+1}(:,:,i) = max(min(1-s,1),0); + spm_progress_bar('Set',i); +end +%for k1=1:Kb+1 +% b0{k1} = spm_bsplinc(log(b0{k1}),[deg deg deg 0 0 0]); +%end +spm_progress_bar('Clear'); +return +function [s,ds1,ds2,ds3] = spm_sample_priors(b,x1,x2,x3,bg) +% Sample prior probability maps +% FORMAT [s,ds1,ds2,ds3] = spm_sample_priors(b,x1,x2,x3,bg) +% b - a cell array containing the tissue probability +% data (see spm_load_priors) +% x1,x2,x3 - coordinates to sample +% bg - background intensity (i.e. value for points +% outside FOV) +% s - sampled values +% ds1,ds2,ds3 - spatial derivatives of sampled values +%____________________________________________________________________________ +% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging + +% John Ashburner +% $Id: spm_sample_priors.m 4873 2012-08-30 19:06:26Z john $ + + +deg = 3; +lm = 0; +bg = min(max(bg,lm),(1-lm)); +if nargout<=1, + s = spm_bsplins(b,x1,x2,x3,[deg deg deg 0 0 0]); + msk = find(~isfinite(s)); + s(msk) = bg; +else, + [s,ds1,ds2,ds3] = spm_bsplins(b,x1,x2,x3,[deg deg deg 0 0 0]); + msk = find(~isfinite(s)); + s(msk) = bg; + ds1(msk) = 0; + ds2(msk) = 0; + ds3(msk) = 0; +end; +return","MATLAB" +"Neurology","ChristianGaser/cat12","cat_conf_factorial.m",".m","76037","1539","function factorial_design = cat_conf_factorial(expert) +% Configuration file for second-level models with full factorial design +%__________________________________________________________________________ +% Copyright (C) 2005-2016 Wellcome Trust Centre for Neuroimaging + +% largely modified version of +% spm_cfg_factorial_design.m 6952 2016-11-25 16:03:13Z guillaume +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +if nargin == 0 + expert = cat_get_defaults('extopts.expertgui'); +end + +%-------------------------------------------------------------------------- +% 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','resampled.*\.(gii)$'}; +scans.ufilter = '.*'; +scans.num = [1 Inf]; +scans.preview = @(f) spm_check_registration(char(f)); + + +%-------------------------------------------------------------------------- +% 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','resampled.*\.(gii)$'}; +scans1.ufilter = '.*'; +scans1.num = [1 Inf]; +scans1.preview = @(f) spm_check_registration(char(f)); + +%-------------------------------------------------------------------------- +% 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','resampled.*\.(gii)$'}; +scans2.ufilter = '.*'; +scans2.num = [1 Inf]; +scans2.preview = @(f) spm_check_registration(char(f)); + +%-------------------------------------------------------------------------- +% 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}; + +%-------------------------------------------------------------------------- +% 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 for PET or VBM data (not second level fMRI).' + '' + '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}; +gmsca.hidden = expert<1; + +%-------------------------------------------------------------------------- +% ancova ANCOVA +%-------------------------------------------------------------------------- +ancova = cfg_menu; +ancova.tag = 'ancova'; +ancova.name = 'ANCOVA'; +ancova.help = { + 'This option is for PET or VBM data (not second level fMRI).' + '' + '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}; +ancova.hidden = expert<1; + +%========================================================================== +% 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 = {'Two-sample t-test.'}; + +%-------------------------------------------------------------------------- +% 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','resampled.*\.(gii)$'}; +scans.ufilter = '.*'; +scans.num = [2 2]; + +%-------------------------------------------------------------------------- +% 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','resampled.*\.(gii)$'}; +scans.ufilter = '.*'; +scans.num = [1 Inf]; +scans.preview = @(f) spm_check_registration(char(f)); + +%-------------------------------------------------------------------------- +% c Vector +%-------------------------------------------------------------------------- +c = cfg_entry; +c.tag = 'c'; +c.name = 'Vector'; +c.help = {'Vector of covariate values.'}; +c.strtype = 'r'; +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 = { + ['Centering refers to subtracting the mean (central) value from the covariate values, ' ... + 'which is equivalent to orthogonalising the covariate with respect to the constant column.'] + '' + ['Subtracting a constant from a covariate changes the beta for the constant term, but not that for the covariate. ' ... + 'In the simplest case, centering a covariate in a simple regression leaves the slope unchanged, ' ... + 'but converts the intercept from being the modelled value when the covariate was zero, ' ... + 'to being the modelled value at the mean of the covariate, which is often more easily interpretable. ' ... + 'For example, the modelled value at the subjects'' mean age is usually more meaningful than the (extrapolated) value at an age of zero.'] + '' + ['If a covariate value of zero is interpretable and/or you wish to preserve the values of the covariate then choose ''No centering''. ' ... + 'You should also choose not to center if you have already subtracted some suitable value from your covariate, ' ... + 'such as a commonly used reference level or the mean from another (e.g. larger) sample.'] + '' + }; +iCC.labels = {'Overall mean', 'No centering'}; +iCC.values = {1 5}; +iCC.val = {1}; + +%-------------------------------------------------------------------------- +% mcov Covariate of Interest +%-------------------------------------------------------------------------- +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 = {'Multiple regression.'}; + +%-------------------------------------------------------------------------- +% 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 = 'n'; +levels.num = [1 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 +%-------------------------------------------------------------------------- +genericf = cfg_repeat; +genericf.tag = 'generic'; +genericf.name = 'Factors'; +genericf.help = {'Specify your design a factor at a time.'}; +genericf.values = {fact}; +genericf.val = {fact}; +genericf.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 = 'n'; +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','resampled.*\.(gii)$'}; +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 +%-------------------------------------------------------------------------- +generic1f = cfg_repeat; +generic1f.tag = 'generic'; +generic1f.name = 'Cells'; +generic1f.help = {'Enter the scans a cell at a time.'}; +generic1f.values = {icell}; +generic1f.val = {icell}; +generic1f.num = [1 Inf]; + +%-------------------------------------------------------------------------- +% generic Specify cells +%-------------------------------------------------------------------------- +generic2 = cfg_repeat; +generic2.tag = 'generic'; +generic2.name = 'Cells'; +generic2.help = {'Enter the scans a cell at a time.'}; +generic2.values = {scell}; +generic2.val = {scell}; +generic2.num = [1 Inf]; + +%========================================================================== +% anova One-way 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).'}; + +%-------------------------------------------------------------------------- +% con Contrasts +%-------------------------------------------------------------------------- +con = cfg_menu; +con.tag = 'contrasts'; +con.name = 'Generate contrasts'; +con.help = {'Automatically generate the contrasts necessary to test for all main effects and interactions.'}; +con.labels = {'Yes', 'No'}; +con.values = {1 0}; +con.val = {1}; + +%========================================================================== +% fd Full factorial +%========================================================================== +fd = cfg_branch; +fd.tag = 'fd'; +fd.name = 'Any cross-sectional data (Full factorial)'; +fd.val = {genericf generic1f con}; +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 will 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 should simply type in eg. [1 2 1 2] to specify just the ''Task'' factor level, instead of, eg. for the 4th subject the matrix [4 1;4 2;4 1;4 2].' +}'; + +%-------------------------------------------------------------------------- +% 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.val = {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','resampled.*\.(gii)$'}; +scans.ufilter = '.*'; +scans.num = [1 Inf]; + +%-------------------------------------------------------------------------- +% conds Conditions +%-------------------------------------------------------------------------- +conds = cfg_entry; +conds.tag = 'conds'; +conds.name = 'Conditions'; +conds.help = {''}; +conds.strtype = 'n'; +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.val = {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','resampled.*\.(gii)$'}; +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 = 'n'; +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.' +}'; + +%-------------------------------------------------------------------------- +% timepoint Timepoints +%-------------------------------------------------------------------------- +timepoint = cfg_files; +timepoint.tag = 'timepoint'; +timepoint.name = 'Timepoint'; +timepoint.filter = {'image','resampled.*\.(gii)$'}; +timepoint.ufilter = '.*'; +timepoint.num = [1 Inf]; +timepoint.help = {'Select the same number and order of subjects for each time point. '}; + +timepoints = cfg_repeat; +timepoints.tag = 'timepoints'; +timepoints.name = 'Timepoints (only for designs with same number of time points)'; +timepoints.values = {timepoint}; +timepoints.num = [2 Inf]; +timepoints.help = {'Specify time points. This only allows to use a design with only one group and the number of time points is the same for all subjects.'}; + +group = cfg_branch; +group.tag = 'group'; +group.name = 'Group'; +group.val = {timepoints}; +group.help = {'Add a new group to your experimental design.'}; + +groups = cfg_repeat; +groups.tag = 'groups'; +groups.name = 'Groups & Timepoints'; +groups.help = {'Specify your groups and timepoints.'}; +groups.values = {group}; +groups.val = {group}; +groups.num = [1 Inf]; + +%-------------------------------------------------------------------------- +% 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 = {... + 'There are 3 different methods to define all subjects, time points and groups:' + '1. Subjects: quite flexible, but annoying to define for many subjects' + '2. Specify all: quite flexible, but you have to know how to define a factor matrix' + '3. Groups & Timepoints: easy to define, but restricted to designs with the same number of timepoints per subject'}; +fsuball.values = {generic1 specall groups}; + +%-------------------------------------------------------------------------- +% fnum Factor number +%-------------------------------------------------------------------------- +fnum = cfg_entry; +fnum.tag = 'fnum'; +fnum.name = 'Factor number'; +fnum.help = {'Enter the number of the factor.'}; +fnum.strtype = 'n'; +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 = 'n'; +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 = [0 Inf]; % 0 for factor-covariate interaction(s) only + +%========================================================================== +% fblock Flexible factorial +%========================================================================== +fblock = cfg_branch; +fblock.tag = 'fblock'; +fblock.name = 'Longitudinal data (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 mat I.' + '' + 'Thirdly, the design matrix is built up a block at a time. Each block can be a main effect or a (two-way) interaction. ' +}'; + +%-------------------------------------------------------------------------- +% 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 = 'r'; +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 = { + ['Centering, in the simplest case, refers to subtracting the mean (central) value from the covariate values, ' ... + 'which is equivalent to orthogonalising the covariate with respect to the constant column.'] + '' + ['Subtracting a constant from a covariate changes the beta for the constant term, but not that for the covariate. ' ... + 'In the simplest case, centering a covariate in a simple regression leaves the slope unchanged, ' ... + 'but converts the intercept from being the modelled value when the covariate was zero, ' ... + 'to being the modelled value at the mean of the covariate, which is often more easily interpretable. ' ... + 'For example, the modelled value at the subjects'' mean age is usually more meaningful than the (extrapolated) value at an age of zero.'] + '' + ['If a covariate value of zero is interpretable and/or you wish to preserve the values of the covariate then choose ''No centering''. ' ... + 'You should also choose not to center if you have already subtracted some suitable value from your covariate, ' ... + 'such as a commonly used reference level or the mean from another (e.g. larger) sample. ' ... + 'Note that ''User specified value'' has no effect, but is present for compatibility with earlier SPM versions.'] + '' + ['Other centering options should only be used in special cases. ' ... + 'More complicated centering options can orthogonalise a covariate or a covariate-factor interaction with respect to a factor, ' ... + 'in which case covariate values within a particular level of a factor have their mean over that level subtracted. ' ... + 'As in the simple case, such orthogonalisation changes the betas for the factor used to orthogonalise, ' ... + 'not those for the covariate/interaction being orthogonalised. ' ... + 'This therefore allows an added covariate/interaction to explain some otherwise unexplained variance, ' ... + 'but without altering the group difference from that without the covariate/interaction. ' ... + 'This is usually *inappropriate* except in special cases. One such case is with two groups and covariate that only has meaningful values for one group ' ... + '(such as a disease severity score that has no meaning for a control group); ' ... + 'centering the covariate by the group factor centers the values for the meaningful group and (appropriately) zeroes the values for the other group.'] + '' +}'; +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. TIV correction should be rather defined in ''Correction of TIV''.' + '' + 'Note that SPM does not make any distinction between effects of interest (including covariates) and nuisance effects.' + 'Covariates and confounding parameters are treated in the same way in the GLM and differ only in the contrast used.' +}; +generic.values = {cov}; +generic.num = [0 Inf]; + +%-------------------------------------------------------------------------- +% multi_reg Multiple covariates +%-------------------------------------------------------------------------- +cov = cfg_files; +cov.tag = 'files'; +cov.name = 'File(s)'; +cov.val = {{''}}; +cov.help = { + 'Select the *.mat/*.txt file(s) containing details of your multiple covariates. ' + '' + 'You will first need to create a *.mat file containing a matrix R or a *.txt file containing the covariates. Each column of R will contain a different covariate. Unless the covariates names are given in a cell array called ''names'' in the MAT-file containing variable R, the covariates will be named R1, R2, R3, ..etc.' + }'; +cov.filter = 'mat'; +cov.ufilter = '.*'; +cov.num = [0 Inf]; + +%-------------------------------------------------------------------------- +% multi_cov Covariate +%-------------------------------------------------------------------------- +multi_cov = cfg_branch; +multi_cov.tag = 'multi_cov'; +multi_cov.name = 'Covariates'; +multi_cov.val = {cov iCFI iCC}; +multi_cov.help = {'Add a new set of covariates to your experimental design.'}; + +%-------------------------------------------------------------------------- +% generic2 Multiple covariates +%-------------------------------------------------------------------------- +generic2 = cfg_repeat; +generic2.tag = 'generic'; +generic2.name = 'Multiple covariates'; +generic2.help = {'This option allows for the specification of multiple covariates from TXT/MAT files.'}; +generic2.values = {multi_cov}; +generic2.num = [0 Inf]; +generic2.hidden = expert<1; + +%-------------------------------------------------------------------------- +% tm_none None +%-------------------------------------------------------------------------- +tm_none = cfg_const; +tm_none.tag = 'tm_none'; +tm_none.name = 'None (i.e. for surface data)'; +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. The default value is a good starting point for VBM data to ensure that only the intended tissue map is analyzed.'}; +athresh.strtype = 'r'; +athresh.num = [1 1]; +athresh.val = {0.1}; + +%-------------------------------------------------------------------------- +% tma Absolute +%-------------------------------------------------------------------------- +tma = cfg_branch; +tma.tag = 'tma'; +tma.name = 'Absolute (i.e. for VBM data)'; +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 = 'r'; +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 = {'This option is intended for volume data. Images are thresholded at a given value and only voxels at which all images exceed the threshold are included. This is the recommended method for analyzing VBM data to ensure that only the intended tissue map is analyzed. '}; +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','mesh'}; +em.ufilter = '.*'; +em.num = [0 1]; + +%-------------------------------------------------------------------------- +% masking Masking +%-------------------------------------------------------------------------- +masking = cfg_branch; +masking.tag = 'masking'; +masking.name = 'Masking'; +masking.val = {tm im em}; +masking.help = { + 'This option is intended for volume data. 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_yes Omit +%-------------------------------------------------------------------------- +g_omit = cfg_const; +g_omit.tag = 'g_omit'; +g_omit.name = 'No'; +g_omit.val = {1}; +g_omit.help = {'Omit global scaling'}; + +%-------------------------------------------------------------------------- +% global_uval Global values +%-------------------------------------------------------------------------- +global_uval = cfg_entry; +global_uval.tag = 'global_uval'; +global_uval.name = 'Vector'; +global_uval.help = {'Enter the vector of values.'}; +global_uval.strtype = 'r'; +global_uval.num = [Inf 1]; + +%-------------------------------------------------------------------------- +% g_user User +%-------------------------------------------------------------------------- +g_user = cfg_branch; +g_user.tag = 'g_user'; +g_user.name = 'Global scaling'; +g_user.val = {global_uval}; +g_user.help = {'If TIV correlates with your parameter of interest, you should use global scaling with TIV.'}; + +%-------------------------------------------------------------------------- +% g_ancova Ancova +%-------------------------------------------------------------------------- +g_ancova = cfg_branch; +g_ancova.tag = 'g_ancova'; +g_ancova.name = 'ANCOVA'; +g_ancova.val = {global_uval}; +g_ancova.help = {'ANCOVA: Here, any variance that can be explained by TIV is removed from your data (i.e. in every voxel or vertex). This is the preferred option when there is no correlation between TIV and your parameter of interest. For example, a parameter of interest may be a variable in a multiple regression design that you want to relate to your structural data. If TIV is correlated with this parameter, not only will the variance explained by TIV be removed from your data, but also parts of the variance of your parameter of interest, which should be avoided.' +'' +'Note that for two-sample T-tests and Anova with more than 2 groups, an interaction is modeled between TIV and group that prevents any group differences from being removed from your data, even if TIV differs between your groups.' +'' +'Use the orthogonality check option to test for any correlations between your parameters.'}; + +%-------------------------------------------------------------------------- +% globals TIV correction +%-------------------------------------------------------------------------- +globals = cfg_choice; +globals.tag = 'globals'; +globals.name = 'Correction of TIV'; +globals.val = {g_ancova}; +globals.values = {g_omit g_ancova g_user}; +globals.help = { + 'This option is to correct for TIV for VBM data by using TIV as covariate (Ancova) or by global scaling with TIV.' + '' +}'; + +%-------------------------------------------------------------------------- +% 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 = 'r'; +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 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 = { + 'This option is for VBM data to correct for TIV as alternative to the use as covariate.' + '' + 'Global nuisance effects such as total tissue volumes for VBM can be accounted for either by dividing the intensities in each image by the image''s 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 = { + 'These options are for PET or VBM data (not second level fMRI).' + '' + '''Overall grand mean scaling'' simply scales all the data by a common factor such that the mean of all the global values is the value specified.' + '' + '''Normalisation'' refers to either proportionally scaling each image or adding a covariate to adjust for the global values.' +}'; +globalm.hidden = expert<1; + +%-------------------------------------------------------------------------- +% voxel_cov Voxel-wise covariates +%-------------------------------------------------------------------------- +cov = cfg_files; +cov.tag = 'files'; +cov.name = 'Scans'; +cov.val = {{''}}; +cov.help = { + 'Select the files with voxel-wise covariates (i.e. GM data).' + '' + 'Importantly, the ordering of of the covariate files has to be consistent with the ordering of the cells in a factorial design.' + '' + 'The approach is similar to https://doi.org/10.1016/j.neuroimage.2006.10.007 but here allows to use TFCE statistics which is usually more powerful.' +}'; +cov.filter = {'image','mesh'}; +cov.ufilter = '.*'; +cov.num = [0 Inf]; +cov.preview = @(f) spm_check_registration(char(f)); + +%-------------------------------------------------------------------------- +% multi_cov Covariate +%-------------------------------------------------------------------------- +iCC2 = iCC; +iCC2.hidden = expert<1; + +%-------------------------------------------------------------------------- +% g_user User +%-------------------------------------------------------------------------- +g_yes = cfg_branch; +g_yes.tag = 'g_user'; +g_yes.name = 'Yes'; +g_yes.val = {global_uval}; +g_yes.help = {'User defined global effects (enter your own vector of global values).'}; + +%-------------------------------------------------------------------------- +% globals2 Global calculation +%-------------------------------------------------------------------------- +globals2 = cfg_choice; +globals2.tag = 'globals'; +globals2.name = 'Global scaling'; +globals2.val = {g_omit}; +globals2.values = {g_omit g_yes}; +globals2.help = { + 'This option is to correct/normalize structural (VBM) data by TIV using global scaling.' + '' +}'; + +%-------------------------------------------------------------------------- +% 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 weights vector +%-------------------------------------------------------------------------- +convec = cfg_entry; +convec.tag = 'weights'; +convec.name = 'Weights vector'; +convec.help = { + 'Enter T-contrast weights vector.' + 'This is done similarly to the contrast manager. A 1 x n vector should be entered for T-contrasts.' + 'Contrast weight vectors will be padded with zeros to the correct length.' + }; +convec.strtype = 'r'; +convec.num = [1 Inf]; + +%========================================================================== +% tcon T-contrast +%========================================================================== +tcon = cfg_branch; +tcon.tag = 'tcon'; +tcon.name = 'T-contrast'; +tcon.val = {name convec}; +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.' + }'; + + %-------------------------------------------------------------------------- +% convec F-contrast weights matrix +%-------------------------------------------------------------------------- +convec = cfg_entry; +convec.tag = 'weights'; +convec.name = 'Weights matrix'; +convec.help = { + 'Enter F-contrast weights matrix.' + 'This is done similarly to the contrast manager.' + 'Contrast weight matrices will be padded with zeros to the correct length.' + }; +convec.strtype = 'r'; +convec.num = [Inf Inf]; + +%========================================================================== +% fcon F-contrast +%========================================================================== +fcon = cfg_branch; +fcon.tag = 'fcon'; +fcon.name = 'F-contrast'; +fcon.val = {name convec}; +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}.' + '' + }'; + +%-------------------------------------------------------------------------- +% 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.' + '' + }'; +consess.values = {tcon fcon}; +consess.num = [0 Inf]; + + +voxel_cov = cfg_branch; +voxel_cov.tag = 'voxel_cov'; +voxel_cov.name = 'Voxel-wise covariate (experimental!)'; +voxel_cov.val = {cov iCFI iCC2 globals2 consess}; +voxel_cov.help = { + 'This experimental option allows the specification of a voxel-wise covariate. This can be used (depending on the contrast defined) to (1) remove the confounding effect of structural data (e.g. GM) on functional data or (2) investigate the relationship (regression) between functional and structural data.' + '' + 'In addition, an interaction can be modeled to examine whether the regression between functional and structural data differs between two groups.' + '' + 'Please note that the saved vSPM.mat file can only be analyzed with the TFCE r221 or newer toolbox.' + }; + + +%-------------------------------------------------------------------------- +% check_SPM_zscore +%-------------------------------------------------------------------------- +use_unsmoothed_data = cfg_menu; +use_unsmoothed_data.name = 'Use unsmoothed data if found'; +use_unsmoothed_data.tag = 'use_unsmoothed_data'; +use_unsmoothed_data.labels = {'Yes','No'}; +use_unsmoothed_data.values = {1,0}; +use_unsmoothed_data.val = {1}; +use_unsmoothed_data.help = {'Check for sample homogeneity results in more reliable values if unsmoothed data are used. Unsmoothed data contain more detailed information about differences and similarities between the data.'}; + +adjust_data = cfg_menu; +adjust_data.name = 'Adjust data using nuisance parameters and global scaling'; +adjust_data.tag = 'adjust_data'; +adjust_data.labels = {'Yes','No'}; +adjust_data.values = {1,0}; +adjust_data.val = {1}; +adjust_data.help = {'This option allows to use nuisance from the design matrix to obtain adjusted data. In this case the variance explained by these parameters will be removed prior to the calculation of the Z-scores. Furthermore, global scaling (if defined) is also applied to the data.'}; + +do_check_zscore = cfg_branch; +do_check_zscore.tag = 'do_check_zscore'; +do_check_zscore.name = 'Yes'; +do_check_zscore.val = {use_unsmoothed_data adjust_data}; +do_check_zscore.help = {''}; + +none = cfg_const; +none.tag = 'none'; +none.name = 'No'; +none.val = {1}; +none.help = {''}; + +check_SPM_zscore = cfg_choice; +check_SPM_zscore.name = 'Check for sample homogeneity'; +check_SPM_zscore.tag = 'check_SPM_zscore'; +check_SPM_zscore.values = {none do_check_zscore}; +check_SPM_zscore.val = {do_check_zscore}; +check_SPM_zscore.help = { + 'In order to identify images with poor image quality or even artefacts you can use this function. The idea of this tool is to check the Z-score of all files across the sample using the files that are already defined in SPM.mat.' + '' + 'The Z-score is calculated for all images and the mean for each image is plotted using a boxplot (or violin plot) and the indicated filenames. The larger the mean A8absolute) Z-score the more deviant is this image from the sample mean. In the plot outliers from the sample are usually isolated from the majority of images which are clustered around the sample mean. The mean Z-score is plotted at the y-axis and the x-axis reflects the image order.' + '' + 'The advantage of rechecking sample homogeneity at this point is that the given statistical model (design) is used and potential nuisance parameters are taken into account. If you have longitudinal data, the time points of each data set are linked in the graph to indicate intra-subject data. Unsmoothed data (if available and in the same folder) are automatically detected and used. Finally, report files are used if present (i.e., if data has not been moved or the folders renamed) and quality parameters are loaded and displayed.' +}; + +check_SPM_ortho = cfg_menu; +check_SPM_ortho.name = 'Check for design orthogonality'; +check_SPM_ortho.tag = 'check_SPM_ortho'; +check_SPM_ortho.labels = {'Yes','No'}; +check_SPM_ortho.values = {1,0}; +check_SPM_ortho.val = {1}; +check_SPM_ortho.help = {'Review Design Orthogonality.'}; + +check_SPM = cfg_branch; +check_SPM.tag = 'check_SPM'; +check_SPM.name = 'Check design orthogonality and homogeneity'; +check_SPM.val = {check_SPM_zscore,check_SPM_ortho}; +check_SPM.help = {'Use design matrix to check for sample homogeneity of the used data and for orthogonality of parameters.'}; + +%-------------------------------------------------------------------------- +% des Design +%-------------------------------------------------------------------------- +% add voxel-wise covariates to full and flexible factorial designs +fd.val{end+1} = voxel_cov; +fblock.val{end+1} = voxel_cov; + +des = cfg_choice; +des.tag = 'des'; +des.name = 'Design'; +des.val = {fd }; +des.help = {''}; +des.values = {t2 mreg fd fblock}; + +%========================================================================== +% factorial_design Basic models +%========================================================================== +factorial_design = cfg_exbranch; +factorial_design.tag = 'factorial_design'; +factorial_design.name = 'Basic models'; +factorial_design.val = {dir des generic generic2 masking globals check_SPM}; +factorial_design.help = { + 'Configuration of 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. ' + '' + 'This interface is used for setting up analyses of PET data, morphometric data, or ''second level'' (''random effects'') fMRI data, where first level models can be used to produce appropriate summary data that are then used as raw data for the 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.' + '' + 'A separate interface handles design configuration for first level 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 = @cat_run_factorial_design; +factorial_design.vout = @vout_stats; + + +%========================================================================== +% function dep = vout_stats(job) +%========================================================================== +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'}}); + +%========================================================================== +% function out = cat_run_factorial_design(job) +%========================================================================== +function out = cat_run_factorial_design(job) +% SPM job execution function - factorial design specification +% Input: +% job - harvested job data structure (see matlabbatch help) +% Output: +% out - struct variable containing the name of the saved SPM.mat +%_________________________________________________________________________ + +% copy values from ""global scaling"" to ""global calculation"" +job.globalc = job.globals; + +voxel_covariate = false; + +% get design and enable group-specific AnCova for TIV for some designs if defined +if isfield(job.des,'fd') + fname = 'fd'; + if isfield(job.globals,'g_ancova') + for i=1:numel(job.des.fd.fact) + job.des.fd.fact(i).ancova = 1; + end + end +elseif isfield(job.des,'fblock') + fname = 'fblock'; + + % if groups are given we have to define fsubject.scans and + % fsubject.cond + if isfield(job.des.fblock.fsuball,'group') + + n_groups = numel(job.des.fblock.fsuball.group); + n_tpoints = numel(job.des.fblock.fsuball.group(1).timepoint); + + for i = 1:n_groups + if numel(job.des.fblock.fsuball.group(i).timepoint) ~= n_tpoints + spm('alert*','Number of timepoints should be the same for all groups.'); + out = []; + return + end + n_subjects{i} = numel(job.des.fblock.fsuball.group(i).timepoint{1}); + for k = 1:n_tpoints + if numel(job.des.fblock.fsuball.group(i).timepoint{k}) ~= n_subjects{i} + spm('alert*','Number of subjects should be the same for all timepoints.'); + out = []; + return + end + end + end + + scans = cell(n_tpoints,1); + conds = (1:n_tpoints)'; + + subj = 0; + for i = 1:n_groups + for j = 1:n_subjects{i} + subj = subj + 1; + for k = 1:n_tpoints + scans{k} = deblank(job.des.fblock.fsuball.group(i).timepoint{k}{j}); + end + job.des.fblock.fsuball.fsubject(subj).scans = scans; + if n_groups > 1 + job.des.fblock.fsuball.fsubject(subj).conds = [i*ones(size(conds)), conds]; + else + job.des.fblock.fsuball.fsubject(subj).conds = conds'; + end + end + end + end + + if isfield(job.des.fblock.fsuball,'specall') + + % we can indicate column with time points (e.g. 1 2 3 1 2 3) by using + % diff and checking whether we have negative diff values + if min(diff(job.des.fblock.fsuball.specall.imatrix(:,3))) < 0 + col_tpoints = 3; + col_groups = 4; + else + col_tpoints = 4; + col_groups = 3; + end + + n_subjects = max(job.des.fblock.fsuball.specall.imatrix(:,2)); + n_groups = max(job.des.fblock.fsuball.specall.imatrix(:,col_groups)); + + for i = 1:n_subjects + ind = job.des.fblock.fsuball.specall.imatrix(:,2)==i; + scans = job.des.fblock.fsuball.specall.scans(ind); + job.des.fblock.fsuball.fsubject(i).scans = scans; + if n_groups > 1 + conds = job.des.fblock.fsuball.specall.imatrix(ind,[col_groups col_tpoints]); + else + conds = job.des.fblock.fsuball.specall.imatrix(ind,col_tpoints); + end + job.des.fblock.fsuball.fsubject(i).conds = conds; + end + end + +elseif isfield(job.des,'t2') + fname = 't2'; + if isfield(job.globals,'g_ancova') + job.des.t2.ancova = 1; + end +elseif isfield(job.des,'mreg') + fname = 'mreg'; +end + +% check for voxel-wise covariate +if isfield(job.des.(fname),'voxel_cov') && isfield(job.des.(fname).voxel_cov,'files') && ~isempty(char(job.des.(fname).voxel_cov.files)) + voxel_covariate = true; + + % number of covariate scans + m = numel(job.des.(fname).voxel_cov.files); + + % get number of scans + n = 0; + if isfield(job.des,'fd') + for i=1:numel(job.des.(fname).icell) + n = n + numel(job.des.(fname).icell(i).scans); + end + else + for i=1:numel(job.des.(fname).fsuball.fsubject) + n = n + numel(job.des.(fname).fsuball.fsubject(i).scans); + end + end + + if m~=n + spm('alert*','Number of covariate files (m=%d) differs from number of files (n=%d)',m,n); + out = []; + return + end + + % get global means for covariate + gm = zeros(numel(job.des.(fname).voxel_cov.files),1); + for i=1:n + dat = spm_data_read(spm_data_hdr_read(job.des.(fname).voxel_cov.files{i})); + ind_dat = isfinite(dat) & dat ~= 0; + if any(ind_dat(:)) + gm(i) = mean(dat(ind_dat)); + else + gm(i) = 0; + end + end + + % add dummy covariate with global mean values to define design + nc = numel(job.cov); + job.cov(nc+1).c = gm - mean(gm); + job.cov(nc+1).cname = 'voxel-wise covariate'; + job.cov(nc+1).iCFI = job.des.(fname).voxel_cov.iCFI; + job.cov(nc+1).iCC = job.des.(fname).voxel_cov.iCC; +end + +% if global scaling is selected set resp. fields for global normalisation +if strcmp(char(fieldnames(job.globalc)),'g_user') + job.globalm.glonorm = 2; + job.globalm.gmsca.gmsca_yes.gmscv = mean(job.globalc.g_user.global_uval); +elseif strcmp(char(fieldnames(job.globalc)),'g_ancova') + job.globalc.g_user = job.globalc.g_ancova; + % g_ancova field should be removed + job.globalc = rmfield(job.globalc,'g_ancova'); + job.globalm.gmsca.gmsca_yes.gmscv = mean(job.globalc.g_user.global_uval); + job.globalm.glonorm = 3; +else + job.globalm.glonorm = 1; + job.globalm.gmsca.gmsca_no = 1; +end + +% call SPM factorial design two times if needed (design matrix is sometimes not displayed) +try + out = spm_run_factorial_design(job); +catch + out = spm_run_factorial_design(job); +end + +if isfield(job.check_SPM.check_SPM_zscore,'do_check_zscore') || job.check_SPM.check_SPM_ortho + job = cat_stat_check_SPM(job); +end + +if voxel_covariate + cat_stat_spm(out.spmmat{1}); + + load(out.spmmat{1}); + SPM.xC(nc+1).P = cellstr(job.des.(fname).voxel_cov.files); + SPM.xC(nc+1).VC = spm_data_hdr_read(char(job.des.(fname).voxel_cov.files)); + % save user defined global scalings + try + gSF = job.des.(fname).voxel_cov.globals.g_user.global_uval; + SPM.xC(nc+1).gSF = gSF; + end + + if isempty(job.des.(fname).voxel_cov.consess) + % contrast should be defined right after model creation + [Ic0,xCon] = spm_conman(SPM,'T',Inf,... + ' Select contrast(s)...',' ',1); + else + job2.spmmat = cellstr(fullfile(SPM.swd,'SPM.mat')); + job2.delete = 1; + Ic0 = []; + for i = 1:numel(job.des.(fname).voxel_cov.consess) + job2.consess{i} = job.des.(fname).voxel_cov.consess{i}; + if isfield(job2.consess{i},'tcon') + job2.consess{i}.tcon.sessrep = 'none'; + else + job2.consess{i}.fcon.sessrep = 'none'; + end + end + spm_run_con(job2); + for i = 1:numel(job.des.(fname).voxel_cov.consess) + if isfield(job2.consess{i},'tcon') + [c,I,emsg,imsg] = spm_conman('ParseCon',job2.consess{i}.tcon.weights,SPM.xX.xKXs,'T'); + DxCon = spm_FcUtil('Set',job2.consess{i}.tcon.name,'T','c',c,SPM.xX.xKXs); + else + [c,I,emsg,imsg] = spm_conman('ParseCon',job2.consess{i}.tcon.weights,SPM.xX.xKXs,'F'); + DxCon = spm_FcUtil('Set',job2.consess{i}.fcon.name,'F','c',job2.consess{i}.fcon.weights,SPM.xX.xKXs); + end + if isempty(SPM.xCon) + SPM.xCon = DxCon; + elseif ~isempty(DxCon) + SPM.xCon(end+1) = DxCon; + end + Ic0 = [Ic0 length(SPM.xCon)]; + xCon = SPM.xCon; + end + end + + % set threshold values to skip interactive selection because we don't need that + xSPM = SPM; + xSPM.xCon = xCon; + xSPM.Ic = Ic0; + xSPM.Im = ''; + xSPM.thresDesc = 'none'; + xSPM.u = 0.001; + xSPM.k = 0; + + SPM = spm_contrasts(xSPM,Ic0); + + % save new voxel-wise vSPM.mat and remove SPM.mat because it should not + % be used anymore + fmt = spm_get_defaults('mat.format'); + s = whos('SPM'); + if s.bytes > 2147483647, fmt = '-v7.3'; end + save(fullfile(SPM.swd,'vSPM.mat'),'SPM',fmt); + delete(fullfile(SPM.swd,'SPM.mat')) + + % update output field with new name + out.spmmat{1} = fullfile(SPM.swd,'vSPM.mat'); + + % delete beta_ and spm?_ files for voxel-wise covariate because these + % files were estimated using spm_spm and are not valid + for i=1:numel(SPM.xC(nc+1).cols) + delete(fullfile(SPM.swd,sprintf('beta_%04d.*',SPM.xC(nc+1).cols(i)))); + end + delete(fullfile(SPM.swd,sprintf('spm*_%04d.*',Ic0))); + + % print warning + spm('alert!',sprintf('SPM12 cannot handle such designs with voxel-wise covariate.\nYou must now call the TFCE Toolbox (r221 or newer) for statistical analysis.')); +else + % remove old vSPM.mat if exist + swd = fileparts(out.spmmat{1}); + if exist(fullfile(swd,'vSPM.mat')) + delete(fullfile(swd,'vSPM.mat')); + end +end +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_vol_gradient3.c",".c","5096","141","/* gradient calculation + * _____________________________________________________________________ + * Estimation of gradient of a volume L (within a ROI M). + * + * [gi,gj,gk] = cat_vol_gradient3(L[,M,norm]) + * + * L = 3d single input matrix + * M = 3d logical input matrix + * norm = 3d double input (0=no, 1=yes, default=0) + * [gi,gj,gk] = 3d single output matrix (xyz gradients defined by [-1 0 1]) + * + * ______________________________________________________________________ + * + * Christian Gaser, Robert Dahnke + * Structural Brain Mapping Group (https://neuro-jena.github.io) + * Departments of Neurology and Psychiatry + * Jena University Hospital + * ______________________________________________________________________ + * $Id$ + */ + +#include ""mex.h"" +#include ""math.h"" +/* #include ""matrix.h"" */ + +/* estimate x,y,z position of index i in an array size sx,sxy=sx*sy... */ +void ind2sub(int i,int *x,int *y, int *z, int sxy, int sy) { + *z = (int)floor( (double)i / (double)sxy ) +1; + i = i % (sxy); + *y = (int)floor( (double)i / (double)sy ) +1; + *x = i % sy + 1; +} + + +/* main function */ +void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) +{ + if (nrhs<1) mexErrMsgTxt(""ERROR:cat_vol_gradient3: not enough input elements\n""); + if (nrhs>3) mexErrMsgTxt(""ERROR:cat_vol_gradient3: too many input elements\n""); + if (nlhs<3) mexErrMsgTxt(""ERROR:cat_vol_gradient3: not enough output elements\n""); + if (nlhs>3) mexErrMsgTxt(""ERROR:cat_vol_gradient3: too many output elements\n""); + if (mxIsSingle(prhs[0])==0) mexErrMsgTxt(""ERROR:cat_vol_gradient3: input must be an 3d single matrix\n""); + + + /* main information about input data (size, dimensions, ...) */ + const mwSize *sL = mxGetDimensions(prhs[0]); + const int dL = mxGetNumberOfDimensions(prhs[0]); + const int nL = mxGetNumberOfElements(prhs[0]); + const int x = (int) sL[0]; + const int y = (int) sL[1]; + const int xy = x*y; + + if ( dL != 3 ) mexErrMsgTxt(""ERROR:cat_vol_gradient3: input must be 3d\n""); + + + /* in- and output */ + float*I = (float *)mxGetPr(prhs[0]); + bool *M; + if ( nrhs>1) { + const int nM = (int) mxGetNumberOfElements(prhs[1]); + + if ( mxGetNumberOfDimensions(prhs[1]) != 3 ) + mexErrMsgTxt(""ERROR:cat_vol_gradient3: second input must be 3d - to use a later parameter use ''true(size( input1 ))''\n""); + if ( mxIsLogical(prhs[1])==0) + mexErrMsgTxt(""ERROR:cat_vol_gradient3: second input must be a logical 3d matrix\n""); + if ( nL != nM) + mexErrMsgTxt(""ERROR:cat_vol_gradient3: second input must be a logical 3d matrix with equal size than input 1\n""); + + M = (bool *)mxGetPr(prhs[1]); + } + int norm = 0; + if ( nrhs > 2) norm = (int) round( mxGetScalar(prhs[2]) ); + + plhs[0] = mxCreateNumericArray(dL,sL,mxSINGLE_CLASS,mxREAL); + plhs[1] = mxCreateNumericArray(dL,sL,mxSINGLE_CLASS,mxREAL); + plhs[2] = mxCreateNumericArray(dL,sL,mxSINGLE_CLASS,mxREAL); + + float *G1 = (float *)mxGetPr(plhs[0]); + float *G2 = (float *)mxGetPr(plhs[1]); + float *G3 = (float *)mxGetPr(plhs[2]); + + int u,v,w,nu,nv,nw,n1i,n2i; + for (int i=0;i=nL) || (abs(nu-u)>1) || (abs(nv-v)>1) || (abs(nw-w)>1) ) n1i=i; + n2i=i+1; ind2sub(n2i,&nu,&nv,&nw,xy,x); if ( (n2i<0) || (n2i>=nL) || (abs(nu-u)>1) || (abs(nv-v)>1) || (abs(nw-w)>1) ) n2i=i; + if ( nrhs==1 ) { + G1[i] = ( I[n2i] - I[n1i] ) / 2.0; + } + else { + if ( M[n1i] && M[n2i] ) + G1[i] = ( I[n2i] - I[n1i] ) / 2.0; + else + G1[i] = 0.0; + } + + n1i=i-x; ind2sub(n1i,&nu,&nv,&nw,xy,x); if ( (n1i<0) || (n1i>=nL) || (abs(nu-u)>1) || (abs(nv-v)>1) || (abs(nw-w)>1) ) n1i=i; + n2i=i+x; ind2sub(n2i,&nu,&nv,&nw,xy,x); if ( (n2i<0) || (n2i>=nL) || (abs(nu-u)>1) || (abs(nv-v)>1) || (abs(nw-w)>1) ) n2i=i; + if ( nrhs==1 ) + G2[i] = ( I[n2i] - I[n1i] ) / 2.0; + else { + if ( M[n1i] && M[n2i] ) + G2[i] = ( I[n2i] - I[n1i] ) / 2.0; + else + G2[i] = 0.0; + } + + n1i=i-xy; ind2sub(n1i,&nu,&nv,&nw,xy,x); if ( (n1i<0) || (n1i>=nL) || (abs(nu-u)>1) || (abs(nv-v)>1) || (abs(nw-w)>1) ) n1i=i; + n2i=i+xy; ind2sub(n2i,&nu,&nv,&nw,xy,x); if ( (n2i<0) || (n2i>=nL) || (abs(nu-u)>1) || (abs(nv-v)>1) || (abs(nw-w)>1) ) n2i=i; + if ( nrhs==1 ) + G3[i] = ( I[n2i] - I[n1i] ) / 2.0; + else { + if ( M[n1i] && M[n2i] ) + G3[i] = ( I[n2i] - I[n1i] ) / 2.0; + else + G3[i] = 0.0; + } + } + + if ( norm == 1 ) { + mxArray *hlps[1]; + hlps[0] = mxCreateNumericArray(dL,sL,mxSINGLE_CLASS,mxREAL); + float*GS = (float *)mxGetPr(hlps[0]); /* distance map */ + + for (int i=0;i1) or relative (<1) voxels +% vx_vol = 1x1 or 1x3 double (default = 1) +% out = volume with the same class like the input volume +% +% Actions: +% Morphological operations with 26-neighborhood +% (cube distance): +% - d | dilate +% - e | erode +% - c | close +% - o | open +% +% Morphological operations with 26-neighborhood +% (chessboard distance): +% - cd | cdilate +% - ce | cerode +% - cc | cclose +% - co | copen +% +% Min-Max-based operations for gray-scaled data +% - gd | gdilate +% - ge | gerode +% - gc | gclose +% - go | gopen +% +% +% Morphological operations with distance operation (sphere): +% - dd | distdilate +% - de | disterode +% - dc | distclose +% - do | distopen +% +% - adc | autodistclose applies n-iterations of local adaptive +% closing to reduce topology defects +% - ado | autodistopen applies n-iterations of local adaptive +% opening to reduce topology defects +% - tc | topoclose topology correction with closing +% - to | topoopen topology correction with closing +% +% - l | lab n(1) largest object/cluster with at least +% n(2) absolute voxels for negative n(2) +% or relative voxels for positive n(2) +% - lo | labopen (disterode + distdilate + lab) +% - lc | labclose (distdilate + disterode + lab) +% +% Special operation: +% - st | selftest [in development] +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + + if nargin < 5, verb = 0; end + if nargin < 4, vx_vol = 1; end + if nargin < 3, n = 1; end + if nargin < 2, action = ''; end + + % interactive call + if nargin < 1 + P = spm_select(Inf,'image','Select images'); + V = spm_vol(P); + + actions = {'dilate','erode','open','close','labclose','labopen','cdilate',... + 'cerode','cclose','copen','labcclose','labcopen','labclosebg','labopenbg',... + 'lab','distdilate','disterode','distclose','distopen','labdistclose','labdistopen', ... + 'WMtc'}; + sel = spm_input('Operation ?',1,'m',actions); + action = actions{sel}; + if strcmp(action,'lab') + n = spm_input('# of largest objects/# of voxels','+1', 'n', '1 10'); + else + n = spm_input('Number of morphol. iterations','+1', 'n', '1'); + end + th = spm_input('Threshold','+1', 'e', '0.5'); + + for i = 1:length(V) + [pth,nam,ext] = spm_fileparts(V(i).fname); + vol = spm_read_vols(V(i)) > th; + vx_vol = sqrt(sum((V(i).mat(1:3,1:3)).^2)); + out = cat_vol_morph(vol,action,n,vx_vol); + V(i).fname = fullfile(pth,[action strrep(num2str(n),' ','_') '_' nam ext]); + V(i).dt(1) = 2; + V(i).pinfo(1) = 1; + spm_write_vol(V(i),out); + end + if nargout, varargout{1} = vol; end + return + end + + classVol = class(vol); + + if iscell(vol) || ndims(vol) ~= 3 || isempty(vol) + error('MATLAB:cat_vol_morph:Empty','Only nonempty 3D volumes!\n'); + end + + % RD202508: need further test + switch lower(action) + case {'gdilate','graydilate','gd','gerode','grayerode','ge', ... + 'grayopen','gopen','go','grayclose','gclose','gc', ... + 'autodistopen','autodistclose','ado','adc', ... + 'topoclose','tc','topoopen','to','topocorr','wmtc'} + otherwise + vol = vol>0.5; + end + vol(isnan(vol)) = 0; + + if isscalar(vx_vol), vx_vol = repmat(vx_vol,1,3); end + if any(size(vx_vol)~= [1,3]) + error('MATLAB:cat_vol_morph:vx_vol', ... + 'Wrong vx_vol size. It has to be a 1x3 matrix.\n'); + end + + nn = n; n = double(n); n(1) = round(n(1)); + switch lower(action) + case {'l','lab'} + nv = ceil(nn(1) ./ mean(vx_vol)); + otherwise + nv = ceil(nn ./ vx_vol); % used to enlarge images for closing + end + switch lower(action) + case {'l','lab','lcc','lco','labcclose','labcopen', ... + 'lc','lo','labclose','labopen', ... + 'ldc','ldo','labdistclose','labdistopen',... + 'topoclose','tc','topoopen','to','topocorr','wmtc', ... + } + % not return in this case + otherwise + if n <= 0, if nargout, varargout{1} = vol; end; return; end + end + + + % distance metric type - see text below + dtype = 'c'; % use 'd' or 'c' + + switch lower(action) + % Block of short actions that call specific functions + % =================================================================== + % The chessboard operations are larger than the euclidean based + % versions and a factor of 1.41 is required to obtain similar results. + % Therefore the chessboard operations are a little bit faster, especially + % for small distances where we have to add one voxel to the convolution + % matrix. + % + % nn = nn * 1.41; + % + + case {'dilate','d'} + vol = cat_vol_morph(vol,[dtype 'dilate'],nn,vx_vol); + case {'erode','e'} + vol = cat_vol_morph(vol,[dtype 'erode'],nn,vx_vol); + case {'open','o'} + vol = cat_vol_morph(vol,[dtype 'open'],nn,vx_vol); + case {'close','c'} + vol = cat_vol_morph(vol,[dtype 'close'],nn,vx_vol); + case {'labclose','lc'} + vol = cat_vol_morph(vol,['lab' dtype 'close'],nn,vx_vol); + case {'labopen','lo'} + vol = cat_vol_morph(vol,['lab' dtype 'open'],nn,vx_vol); + + + + % min-max-based gray-scale filters + % =================================================================== + + case {'gdilate','graydilate','gd','gerode','grayerode','ge'} + % remove the background volume that is outside the dilation region + [vol,BB] = cat_vol_resize(vol,'reduceBrain',vx_vol,n+1,vol>0); + + % use of single input for convn is faster and less memory demanding + switch lower(action) + case {'graydilate','gd','gdilate'}, minmax = 3; + case {'grayerode' ,'ge','gerode'}, minmax = 2; + end + + minvol = min(vol)+1; + vol = cat_vol_localstat( single(vol+minvol), true(size(vol)), (nn/mean(vx_vol)), minmax) - minvol; %cat_vol_morph(vol>0, dx , ceil(nn/mean(vx_vol))) + + % add background + vol = cat_vol_resize(vol,'dereduceBrain',BB); + + case {'grayopen','gopen','go'} + vol = cat_vol_morph(vol,'gerode' ,n,vx_vol); + vol = cat_vol_morph(vol,'gdilate',n,vx_vol); + + case {'grayclose','gclose','gc'} + vol = cat_vol_morph(vol,'gdilate',n,vx_vol); + vol = cat_vol_morph(vol,'gerode' ,n,vx_vol); + + + + + % chessboard distance operations (like a box) + % =================================================================== + case {'cdilate','cd'} + % remove the background volume that is outside the dilation region + [vol,BB] = cat_vol_resize(vol,'reduceBrain',vx_vol,n+1,vol>0); + + % use of single input for convn is faster and less memory demanding + vol = convn(single(vol),ones(2*round(nn/vx_vol(1))+1,... + 2*round(nn/vx_vol(2))+1,2*round(nn/vx_vol(3))+1),'same') > 0; + + % add background + vol = cat_vol_resize(vol,'dereduceBrain',BB); + + case {'cerode','ce'} + vol = ~cat_vol_morph(~vol,'cdilate',n,vx_vol); + + case {'cclose','cc'} + test = 2; % hard switch for tests + if test == 1 + % we need to enlarge the image to avoid closing by the region that + % is not in the image + sz = size(vol); + vol2 = zeros(sz(1)+(2*nv(1)),sz(2)+(2*nv(2)),sz(3)+(2*nv(3)),'uint8'); + vol2(nv(1)+1:sz(1)+nv(1),nv(2)+1:sz(2)+nv(2),nv(3)+1:sz(3)+nv(3)) = uint8(vol); + vol2 = cat_vol_morph(vol2,'cdilate',n,vx_vol); + vol2 = cat_vol_morph(vol2,'cerode' ,n,vx_vol); + vol = vol2(nv(1)+1:sz(1)+nv(1),nv(2)+1:sz(2)+nv(2),nv(3)+1:sz(3)+nv(3))>0; + elseif test == 2 + % remove the background volume that is outside the dilation region + [vol,BB] = cat_vol_resize(vol,'reduceBrain',vx_vol,1,vol>0); + + % We need to enlarge the image. Otherwise the dilation will reach + % the image boundary and final close the region between object and + % image boundary. + sz = size(vol); + vol2 = zeros(sz(1)+(2*nv(1)),sz(2)+(2*nv(2)),sz(3)+(2*nv(3)),'uint8'); + vol2(nv(1)+1:sz(1)+nv(1),nv(2)+1:sz(2)+nv(2),nv(3)+1:sz(3)+nv(3)) = uint8(vol); + vol2 = cat_vol_morph(vol2,'cdilate',n,vx_vol); + vol2 = cat_vol_morph(vol2,'cerode' ,n,vx_vol); + vol = vol2(nv(1)+1:sz(1)+nv(1),nv(2)+1:sz(2)+nv(2),nv(3)+1:sz(3)+nv(3))>0; + + % add background + vol = cat_vol_resize(vol,'dereduceBrain',BB); + else + vol = cat_vol_morph(vol,'cdilate',n,vx_vol); + vol = cat_vol_morph(vol,'cerode' ,n,vx_vol); + end + + case {'copen','co'} + vol = ~cat_vol_morph(~vol,'cclose' ,n,vx_vol); + + case {'labcclose','lcc'} + % removing of background within the object + vol = cat_vol_morph(vol,'cclose',n,vx_vol); + vol = ~cat_vol_morph(~vol,'lab',n,vx_vol); + + case {'labcopen','lco'} + vol = cat_vol_morph(vol,'copen',n,vx_vol); + vol = cat_vol_morph(vol,'lab',n,vx_vol); + + case {'labclosebg','lbc'} + % removing of other objects + vol = cat_vol_morph(~vol,'cclose',n,vx_vol); + vol = ~cat_vol_morph(vol,'lab',n,vx_vol); % removing of background within the object + + case {'labopenbg','lbo'} + vol = cat_vol_morph(~vol,'copen',n,vx_vol); + vol = ~cat_vol_morph(vol,'lab',n,vx_vol); % removing of other objects + + % =================================================================== + case {'lab','l'} + [ROI,num] = spm_bwlabel(real(vol),6); + + if num>0 + num = hist( ROI( ROI(:)>0 ) , 1:num); %#ok + [num,numi] = sort(num,'descend'); + vol = ROI == numi(1); + + if exist('n','var') && nn(1)>1 + vol = single(vol); classVol = 'single'; + + if isscalar(nn), nn(2) = 0; end + snum = sum(num); + if nn(2)>0 && nn(2)<1 + lim = find(num/snum>nn(2),1,'last'); + else + lim = find(abs(num)>nn(2),1,'last'); + end + for ni = 2:min(lim,min(numel(num),nn(1))) + if nn(2)>0 && nn(2)<1 && num(ni)/snum>nn(2) % relative + vol(ROI == numi(ni)) = ni; %numi(ni); + elseif (nn(2)<0 || nn(2)>1) && num(ni)>abs(nn(2)) % absolute + vol(ROI == numi(ni)) = ni; %numi(ni); + end + end + end + end + + + % euclidean distance operations (like a sphere) + % =================================================================== + % You have to use the original resolution, because fine structures + % are bad represented for lower resolutions and lead to unaccurate + % results. + case {'distdilate','dd'} + % remove the background volume that is outside the dilation region + [vol,BB] = cat_vol_resize(vol,'reduceBrain',vx_vol,n+1,vol>0); % RD202508: nn should be better but was not + + % RD202508: caused differences in affine registration and would need further tests + %{ + if nn / mean(vx_vol) > 3 + [vol,resYp0] = cat_vol_resize(vol,'reduceV', 1, nn/5, 32, 'meanm'); + vol = vol > .5; + nn = nn * resYp0.vx_red(1); + end + %} + + if n>5 %|| (sum(vol(:)>0)/numel(vol))>0.8 + % faster for large distances and smaller objects + vol = cat_vbdist(single(vol), true(size(vol)), vx_vol) <= nn; + else + % faster for small distances + % this is the new approach that supports euclidean distance metric + % and also include the voxel resolution + d = zeros(2*n+1,2*n+1,2*n+1,'single'); d(n+1,n+1,n+1) = 1; + d = max(0,cat_vbdist(d,true(size(d)),vx_vol) - 0.5); d(1) = d(end); + d = max(0,nn - d); + vol = min(1,convn(single(vol),d,'same')) >= 0.5; % PVE map without >0.5 + end + + if exist('resYp0','var') + vol = cat_vol_resize(vol,'dereduceV',resYp0) >= 0.5; + end + + % add background + vol = cat_vol_resize(vol,'dereduceBrain',BB); + + case {'disterode','de'} + vol = ~cat_vol_morph(~vol,'distdilate',nn,vx_vol); + + case {'distclose','dc'} + % remove the background volume that is outside the dilation region + [vol,BB] = cat_vol_resize(vol,'reduceBrain',vx_vol,n+1,vol>0); % RD202508: nn should be better but was not + + % RD202508: caused differences in affine registration and would need further tests + %{ + if nn / mean(vx_vol) > 3 + [vol,resYp0] = cat_vol_resize(single(vol),'reduceV', 1, max(2,nn/5), 32, 'meanm'); + vol = vol > .5; + nn = nn / resYp0.vx_red(1); + end + %} + + sz = size(vol); + vol2 = zeros(sz(1)+(2*nv(1)),sz(2)+(2*nv(2)),sz(3)+(2*nv(3)),'single'); + vol2(nv(1)+1:sz(1)+nv(1),nv(2)+1:sz(2)+nv(2),nv(3)+1:sz(3)+nv(3)) = single(vol); + if n>5 + + %nn = nn*1.41; n = round(nn); + + vol2 = cat_vbdist(vol2,true(size(vol2)),vx_vol)>nn; + vol2 = cat_vbdist(single(vol2>0),vol2 == 0,vx_vol) >= nn; + else + vol2 = cat_vol_morph(vol2,'distdilate',nn,vx_vol); + vol2 = cat_vol_morph(vol2,'disterode' ,nn,vx_vol); + end + vol = vol | vol2(nv(1)+1:sz(1)+nv(1),nv(2)+1:sz(2)+nv(2),nv(3)+1:sz(3)+nv(3)); + + if exist('resYp0','var') + vol = cat_vol_resize(vol,'dereduceV',resYp0) >= 0.5; + end + + % add background + vol = cat_vol_resize(vol,'dereduceBrain',BB); + + + case {'distopen','do'} + vol = ~cat_vol_morph(~vol,'distclose',nn,vx_vol); + + case {'labdistclose','ldc'} + vol = cat_vol_morph(vol,'distclose',nn,vx_vol); + vol = ~cat_vol_morph(~vol,'lab',nn,vx_vol); % removing of background within the object + + case {'labdistopen','ldo'} + vol = cat_vol_morph(vol,'distopen',nn,vx_vol); + vol = cat_vol_morph(vol,'lab',nn,vx_vol); % removing of other objects + + + % topology correction function + % =================================================================== + + case {'topoopen','to'} + if verb, vol0 = vol; ptime(1) = datetime('now'); end + if all(vol==round(vol)) + vol = cat_vol_morph(vol,'l',1)>0; + else + vol = min(vol,.5) + ( cat_vol_morph(vol,'l').*max(0,vol-.5)); + end + vol = 1 - cat_vol_morph(1 - vol, 'tc',1,vx_vol,0); + if verb, ptime(2) = datetime('now'); evaltopo(vol0,vol,action,nn,ptime); end + + case {'topoclose','tc'} + vol = single(vol); + if verb, ptime(1) = datetime('now'); end + + vol0 = vol; tbf = false(size(vol)); + evalc('tbf = ( (vol<.5) & cat_vol_morph(vol>.5,''d'') & smooth3(cat_vol_genus0(single(vol),.5))>.6 );'); + vol = max( vol , min(0.51, min(vol(:)) + diff([min(vol(:)) max(vol(:)) ]) .* (tbf & ~(vol>.5) )) ) ; + + if all(vol0==round(vol0)) + vol = cat_vol_morph(vol,'l',1)>0; + else + vol = min(vol,.5) + ( cat_vol_morph(vol,'l').*max(0,vol-.5)); + end + + if verb, ptime(2) = datetime('now'); evaltopo(vol0,vol,action,nn,ptime); end + + case 'wmtc' + % WM specific topology correction + vol = min(vol,.5) + ( cat_vol_morph(vol,'l').*max(0,vol-.5)); + + if verb, vol0 = vol; ptime(1) = datetime('now'); end + vol = cat_vol_morph(vol,'adc',1,vx_vol,0); % high bias, more defects ... maybe better to avoid here + vol = cat_vol_morph(vol,'tc',1,vx_vol,0); + vol = cat_vol_morph(vol,'to',1,vx_vol,0); + if verb, ptime(2) = datetime('now'); evaltopo(vol0,vol,action,nn,ptime); end + + case {'autodistopen','ado'} + if verb, vol0 = vol; ptime(1) = datetime('now'); end + vol = 1 - cat_vol_morph(1 - vol, 'adc',nn,vx_vol,0); + if verb, ptime(2) = datetime('now'); evaltopo(vol0,vol,action,nn,ptime); end + + case {'autodistclose','adc'} + % more iterations are do not really improve the topology and increase + % the corrected volume much stronger + + if verb, ptime(1) = datetime('now'); end + + if ~isscalar(vx_vol) && any(std(vx_vol)>0) + cat_io_cprintf('warn','cat_vol_morph:autodistcloseopen. Function not prepared for various voxel size.'); + end + + Yoc = vol > (nn/2); + + % distance operation for dilation and thickness (maximum estimation) + [Yod,Yodi] = cat_vbdist(single(Yoc)); % distance estimation + % approximate the avaible space by estimating the thickness of the structure + Ydt = cat_vol_pbtp(single(2 + Yoc), Yod, Yod*inf); % thickness estimation + Ydt(Ydt > median(Ydt(Yod(:)>0 & Yod(:)<2) )) = 0; % remove extremly high values ### * 1.5 + Ydt( abs(Ydt - cat_vol_approx(Ydt))>1 ) = 0; % remove standard outliers + Ydt = cat_vol_approx(Ydt); % approximation + Ydt = max(1,Ydt - 2); % correct to keep a skeleton + + % distance estimation for erosion + [Yodd,Yoddi] = cat_vbdist(single(Ydt(Yodi) (Ydt(Yodi(Yoddi))) ); % default would be .5 but with sc + clear Yodd Yoddi; + + % use skeleton to avoid blurring + Yocd = cat_vbdist(single(Yoc1 <= 0.1)); % not zero because of interpolation artifacts + Ydiv = smooth3(cat_vol_div(Yocd,1,1,1)); % divergence to define skeleton + Ysc = max(0,min(1, smooth3( -max(-1,Ydiv) .* (Ydiv<-.1 & Ydiv>-0.4) * 10))); clear Ydiv + Yoc = max( vol , min(0.51, smooth3( min(2, (Yoc1 * 1.5).^4 ) .* Ysc).^4 )); clear Ysc + + % Evaluation: + if verb, ptime(2) = datetime('now'); evaltopo(vol,Yoc,action,nn,ptime); end + + vol(vol>0) = Yoc(vol>0); + + + % =================================================================== + case {'selftest','st'} + % a = zeros(7,11,3); a(4,4,2) = 1; a(4,8,2) = 1; % two dots + + voltypes = {'1','2','2c','2ce'}; + volclass = {'cube','sphere'}; + method{1} = {'erode' 'e' + 'dilate' 'd' + 'open' 'o' + 'close' 'c'}; + method{2} = {'disterode' 'de' + 'distdilate' 'dd' + 'distopen' 'do' + 'distclose' 'dc'}; + method{3} = {'lab' 'l' + 'labopen' 'lo' + 'labclose' 'lc'}; + + dist = 8; %[0:0.5:3 10 20]; + + vol = cell(1,numel(voltypes)); + for vc = 1:numel(volclass) + for vt = 1:numel(voltypes) + vol{vt}.O = cat_vol_smooth3X(rand(size(vol)),2); %cat_tst_phantoms(volclass{vc},voltypes{vt}); + + for cl = 1:numel(method) + for mt = 1:size(method{cl},1) + for dt = 1:numel(dist) + vol{vt}.(method{cl}{mt,2}){dt} = cat_vol_morph(vol{vt}.O,method{cl}{mt,1},dist(dt)); + end + end + end + end + end + +%ds('d2','',[1 1 1],vol{1}.O,vol{1}.O + vol{1}.d{1} + vol{1}.e{1},vol{1}.O,vol{1}.O + vol{1}.dd{1} + vol{1}.de{1},50) + + + % =================================================================== + % case do nothing + case '' + + otherwise + error('MATLAB:cat_vol_morph:UnknownAction','Unknown action ''%s ''',action); + end + + eval(sprintf('vol = %s(vol);',classVol)); + if isa(classVol,'uint8'); vol = 255*vol; end + + if nargout, varargout{1} = vol; end +end +function EC = evaltopo(vol1,vol2,action,nn,ptime) +%evaltopo. Evaluation function of the autodistclose/open function. + + vol1 = max(0,min(1,vol1)); + vol2 = max(0,min(1,vol2)); + + [vol,l1] = spm_bwlabel(double(vol1>.5)); %#ok + evalc('[~,faces,vertices] = cat_vol_genus0(single(vol),.5,1);'); + CS = struct('faces',faces,'vertices',vertices); + EC(1) = ( size(CS.vertices,1) + size(CS.faces,1) - size(spm_mesh_edges(CS),1) - 2) + 2; + + [vol,l2] = spm_bwlabel(double(vol2>.5)); %#ok + evalc('[~,faces,vertices] = cat_vol_genus0(single(vol),.5,1);'); + CS = struct('faces',faces,'vertices',vertices); + EC(2) = ( size(CS.vertices,1) + size(CS.faces,1) - size(spm_mesh_edges(CS),1) - 2) + 2; + clear vol; + + ccol = [.5 0 0; 0.2 0.2 0.2; 0 0.5 0]; + volb = [ nnz(vol1(:)>.5), nnz(vol2(:)>.5) ] / 1000; + volp = [ sum(vol1(:)) , sum(vol2(:)) ] / 1000; + + % print + fprintf('\n Overview (operation=""%s"", n=%d): \n',action,nn) + cat_io_cprintf( ccol( ( diff(volb)/volb(1) < .02 ) + ( diff(volb)/volb(1) < .05 ) + 1 , :), sprintf( ... + ' Binary-Volume: %+6.2f%%%% (%0.0fk %+0.0fk>> %0.0fk) \n', ... + diff(volb)/volb(1) * 100, volb(1), diff( volb ), volb(2) )); + cat_io_cprintf( ccol( ( diff(volp)/volp(1) < .02 ) + ( diff(volp)/volp(1) < .05 ) + 1 , :), sprintf( ... + ' PVE-Volume: %+6.2f%%%% (%0.0fk %+0.0fk>> %0.0fk) \n', ... + diff(volp)/volp(1) * 100, volp(1), diff( volp ), volp(2) )); + cat_io_cprintf( ccol( ( diff([ l1 , l2 ])<=0 )*2 + 1 , :), sprintf( ... + ' Number of Components: %+6.0f%%%% (%3d %+3d >> %3d) \n', ... + diff([ l1 , l2 ]) ./ l1 * 100 , l1, diff([ l1 , l2 ]), l2 )); + cat_io_cprintf( ccol( ( diff([ abs(EC) ])<0 ) + ( diff([ abs(EC) ])<=0 ) + 1 , :), sprintf( ... + ' Fast abs. Euler Characteristic: %+6.0f%%%% (%3d %+3d >> %3d) \n', ... + diff([ abs(EC) ]) ./ abs(EC(1)) * 100, abs(EC(1)), diff([ abs(EC) ]), abs(EC(2)) )); + if exist('ptime','var'), fprintf(' Time: %0.0fs \n', seconds(ptime(2) - ptime(1)) ); end + fprintf('\n'); +end +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_main_reportstr.m",".m","32994","597","function str = cat_main_reportstr(job,res,qa) +% ______________________________________________________________________ +% +% Prepare text output for CAT report. This function may heavily change +% due to parameter changes. However, this only effects the output of the +% CAT report. Called from cat_main. +% +% str = cat_main_reportstr(job,res,qa,cat_warnings) +% +% str .. cellstrings with 3 elements with two strings +% str{1} .. full width table +% str{2:3} .. half width table +% +% job .. SPM/CAT parameter structure +% res .. SPM preprocessing structure +% qa .. CAT quality and subject information structure +% +% See also cat_main_reportfig and cat_main_reportcmd. +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +%#ok<*AGROW,*NOCOM> + + QMC = cat_io_colormaps('marks+',17); + color = @(QMC,m) QMC(max(1,min(size(QMC,1),round(((m-1)*3)+1))),:); + + %mark2str2 = @(mark,s,val) sprintf(sprintf('\\\\bf\\\\color[rgb]{%%0.2f %%0.2f %%0.2f}%s',s),color(QMC,mark),val); + marks2str = @(mark,str) sprintf('\\bf\\color[rgb]{%0.2f %0.2f %0.2f}%s',color(QMC,real(mark)),str); + mark2rps = @(mark) min(100,max(0,105 - real(mark)*10)) + isnan(real(mark)).*real(mark); + grades = {'A+','A','A-','B+','B','B-','C+','C','C-','D+','D','D-','E+','E','E-','F'}; + mark2grad = @(mark) grades{max(1,min([numel(grades),max(max(isnan(real(mark))*numel(grades),1),round((real(mark)+2/3)*3-3))]))}; + + catdef = cat_get_defaults; + job = cat_io_checkinopt(job,catdef); + +% blue for none defaults +% orange for warning changes + npara = '\color[rgb]{0 0 0}'; + cpara = '\color[rgb]{0 0 1}'; + wpara = '\color[rgb]{1 0.3 0}'; + + + % CAT GUI parameter: + % -------------------------------------------------------------------- + str{1} = []; + if isfield(res,'spmpp') && res.spmpp + [pp,ff] = spm_fileparts(job.data{1}); + Pseg8 = fullfile(pp,[ff(3:end) '_seg8.mat']); + if exist(Pseg8,'file') + seg8 = load(Pseg8); + end + Psegsn = fullfile(pp,[ff(3:end) '_seg_sn.mat']); + if exist(Psegsn,'file') + segsn = load(Psegsn); + end + end + if ~isfield(res,'applyBVC') + res.applyBVC = 0; + end + + % use red output if a beta version is used + catv = qa.software.revision_cat; isbeta = strfind(lower(catv),'beta'); + if ~isempty(isbeta), catv = [catv(1:isbeta-1) '\color[rgb]{0.8 0 0}' catv(isbeta:isbeta+3 ) '\color[rgb]{0.8 0 0}' catv(isbeta+4:end)]; end + +% red version in case of old version? + % 1 line: Matlab, SPM, CAT12 version number and GUI and experimental mode + if strcmpi(spm_check_version,'octave') + str{1} = [str{1} struct('name', 'Version: OS / SPM / CAT12:','value',... + sprintf('%s / %s / %s (%s)',qa.software.system,... + qa.software.version_spm,qa.software.version_cat,catv))]; + % native2unicode is working on the command line but not in the figure + cub = '^3'; + pm = '+/-'; + else + str{1} = [str{1} struct('name', 'Version: OS / Matlab / SPM / CAT12:','value',... + sprintf('%s / %s / %s / %s (%s)',qa.software.system,qa.software.version_matlab,... + qa.software.version_spm,qa.software.version_cat,catv))]; + cub = native2unicode(179, 'latin1'); % char(179); + pm = native2unicode(177, 'latin1'); + end + + % add CAT segmentation version if not current + if ~isempty(qa.software.version_segment) + str{1}(end).name = [str{1}(end).name(1:end-1) ' / seg:']; + str{1}(end).value = [str{1}(end).value ' / \color[rgb]{0 0.2 1}' qa.software.version_segment '']; + end + % write GUI mode + if job.extopts.expertgui==1, str{1}(end).value = [str{1}(end).value '\bf\color[rgb]{0 0.2 1}e']; + elseif job.extopts.expertgui==2, str{1}(end).value = [str{1}(end).value '\bf\color[rgb]{0 0.2 1}d']; + end + % write experimental flag + if str{1}(end).value(end)==')' + if job.extopts.new_release, str{1}(end).value = [str{1}(end).value(1:end-1) '\bf\color[rgb]{0 0.2 1}n\color[rgb]{0 0 0}\sf)']; end + if job.extopts.experimental, str{1}(end).value = [str{1}(end).value(1:end-1) '\bf\color[rgb]{0 0.2 1}x\color[rgb]{0 0 0}\sf)']; end + else + if isfield(job.extopts,'new_release') && job.extopts.new_release + str{1}(end).value = [str{1}(end).value(1:end-1) '\bf\color[rgb]{0 0.2 1}n\color[rgb]{0 0 0}']; + end + if isfield(job.extopts,'experimental') && job.extopts.experimental + str{1}(end).value = [str{1}(end).value '\bf\color[rgb]{0 0.2 1}x']; + end + end + if job.extopts.ignoreErrors > 2, str{1}(end).value = [str{1}(end).value ' \bf\color[rgb]{0.8 0 0}Ignore Errors!']; end + if isfield(res,'long') + %str{1}(end).value = [str{1}(end).value '\bf\color[rgb]{0 0.2 1}-longreport']; + if ~isempty(res.long.model) + str{1}(end).value = [str{1}(end).value '\bf\color[rgb]{0 0.2 1}-' res.long.model]; + end + elseif isfield(job,'useprior') && ~isempty(job.useprior) + str{1}(end).value = [str{1}(end).value '\bf\color[rgb]{0 0.2 1}-long']; + end + % additional output for longitudinal pipeline + if isfield(job,'lopts') && job.extopts.expertgui + if isfield(job.lopts,'enablepriors') && job.lopts.enablepriors==1, cp{1} = npara; else, cp{1} = cpara; end + if isfield(job.lopts,'longTPM') && job.lopts.longTPM==1, cp{2} = npara; else, cp{2} = cpara; end + if isfield(job.lopts,'enablepriors') && isfield(job.lopts,'longTPM') + str{1}(end+1).name = 'priors / longTPM:'; + str{1}(end).value = sprintf('%s%d / %s%d',cp{1},job.lopts.enablepriors, cp{2},job.lopts.longTPM); + end + if job.extopts.expertgui > 1 + if isfield(job.lopts,'prepavg') && job.lopts.prepavg==0, cp{3} = npara; else, cp{3} = cpara; end + if isfield(job.lopts,'bstr') && job.lopts.bstr==0, cp{4} = npara; else, cp{4} = cpara; end + if isfield(job.lopts,'avgLASWMHC') && job.lopts.avgLASWMHC==0, cp{5} = npara; else, cp{5} = cpara; end + if isfield(job.lopts,'prepavg') && isfield(job.lopts,'bstr') && isfield(job.lopts,'avgLASWMHC') + str{1}(end).name = [ str{1}(end).name(1:end-1) ' / prepavg / bstr / avgLASWMHC:' ]; + str{1}(end).value = sprintf('%s / %s%d / %s%d / %s%d',str{1}(end).value, ... + cp{3}, job.lopts.prepavg, cp{4}, job.lopts.bstr, cp{5}, job.lopts.avgLASWMHC); + end + end + end + if isfield(job.extopts,'BIDSfolder') && ~isempty(job.extopts.BIDSfolder) + str{1} = [str{1} struct('name','BIDS folder','value',cat_io_strrep( job.extopts.BIDSfolder , '_', '\_'))]; + end + + + % 2 lines: TPM, Template, Normalization method with voxel size + if isfield(res,'tpm') + if strcmp(res.tpm(1).fname,catdef.opts.tpm{1}) || isfield(job,'useprior') && ~isempty(job.useprior), cp{1} = npara; else, cp{1} = cpara; end + if isfield(res,'long'), TPMlstr = ' for Long. AVG (use AVG as TPM in TPs)'; else, TPMlstr = ''; end + if exist('seg8','var') + str{1} = [str{1} struct('name', ['Tissue Probability Map' TPMlstr ':'],'value',[cp{1} strrep(spm_str_manip(seg8.tpm(1).fname,'k40d'),'_','\_')])]; + else + str{1} = [str{1} struct('name', ['Tissue Probability Map' TPMlstr ':'],'value',[cp{1} strrep(spm_str_manip(res.tpm(1).fname,'k40d'),'_','\_')])]; + end + end + if res.do_dartel + if job.extopts.regstr==0 % Dartel + if strcmp(job.extopts.darteltpm{1},catdef.extopts.darteltpm{1}), cp{1} = npara; else, cp{1} = cpara; end + str{1} = [str{1} struct('name', 'Dartel Registration to: ',... + 'value',[cp{1} strrep(spm_str_manip(job.extopts.darteltpm{1},'k40d'),'_','\_')])]; + elseif job.extopts.regstr==4 % Dartel + if strcmp(job.extopts.shootingtpm{1},catdef.extopts.shootingtpm{1}), cp{1} = npara; else, cp{1} = cpara; end + str{1} = [str{1} struct('name', 'Shooting Registration to: ',... + 'value',[cp{1} strrep(spm_str_manip(job.extopts.shootingtpm{1},'k40d'),'_','\_')])]; + else + if strcmp(job.extopts.shootingtpm{1},catdef.extopts.shootingtpm{1}), cp{1} = npara; else, cp{1} = cpara; end + if job.extopts.expertgui==0 + str{1} = [str{1} struct('name','Optimized Shooting Registration to:',... + 'value',strrep(spm_str_manip(job.extopts.shootingtpm{1},'k40d'),'_','\_'))]; + else + str{1} = [str{1} struct('name', sprintf('Optimized Shooting Registration (regstr:%s) to:',sprintf('%g',job.extopts.regstr)),... + 'value',[cp{1} strrep(spm_str_manip(job.extopts.shootingtpm{1},'k40d'),'_','\_')])]; + end + end + end + + % 1 line 1: Affreg + if ~isfield(res,'spmpp') || ~res.spmpp + if isfield(job.opts,'affreg') + if strcmp(job.opts.affreg,catdef.opts.affreg), cp{1} = npara; else, cp{1} = cpara; end + if isfield(job,'useprior') && ~isempty(job.useprior) && exist(char(job.useprior),'file') + affstr = 'AVGprior'; + else + affstr = job.opts.affreg; + end + str{1} = [str{1} struct('name', 'affreg:','value',sprintf('%s{%s}',cp{1},affstr))]; + end + + % 1 line 2: APP + if job.extopts.APP == catdef.extopts.APP, cp{1} = npara; else, cp{1} = cpara; end + APPstr = {'none','SPM'}; APPstr{1071} = 'default'; APPstr{6} = 'default2'; + str{1}(end).name = [str{1}(end).name(1:end-1) ' / APP ']; + str{1}(end).value = [str{1}(end).value sprintf(' / %s{%s}',cp{1},APPstr{job.extopts.APP+1})]; + + % 1 line 3: COM + if isfield(job.extopts,'setCOM') && isfield(catdef.extopts,'setCOM') + if job.extopts.setCOM == catdef.extopts.setCOM, cp{1} = npara; else, cp{1} = cpara; end + COMstr = {'noCOM','COM'}; COMstr{10+1} = 'noTPM'; COMstr{11+1} = 'fTPM'; COMstr{120+1} = 'noMSK'; + str{1}(end).name = [str{1}(end).name(1:end-1) ' / setCOM ']; + str{1}(end).value = [str{1}(end).value sprintf(' / %s{%s}',cp{1},COMstr{job.extopts.setCOM+1})]; + end + + % display only abnormal values + if isfield(job.extopts,'affmod') && any(job.extopts.affmod ~= 0), + str{1}(end).name = [str{1}(end).name(1:end-1) ' / affmod']; + str{1}(end).value = [str{1}(end).value sprintf(' / %s{%s}',cpara,sprintf('%+0.0f ',job.extopts.affmod))]; + end + end + + +% ##### +% one new super SPM parameter? +% ##### + % 1 line 3: biasstr / biasreg+biasfwhm + if ~isfield(res,'spmpp') || ~res.spmpp + str{1}(end+1) = struct('name', '','value',''); + if isfield(job.extopts,'prior') + % ############# + % RD202201: Longituinal report settings: + % * LBC is a different batch but it renames the file and adds m as prefix + % * This would need an extra variable only for display :/ + % Would be possible to use some surf-variable that are not required + % for longitudial process but this would be highly unclear in future. + % So we keep it simple here with yes/no. + % Maybe just save an early version of the cat_long_xml? Yes. + % * other settings: + % - use priors + % - longmodel (allready inlcuded) + % ############# + [~,ff] = spm_fileparts(res.image0(1),fname); + LBCstr = {'no','yes'}; + if ff(1)=='m', LBC = 0; else, LBC = 1; end % manual setting + cl = cat_conf_long; if cl.val{4}.val{1} == 0 && LBC == 0, cp{1} = npara; else, cp{1} = cpara; end + str{1}(end).name = [str{1}(end).name(1:end-1) 'LBC /']; + str{1}(end).value = [str{1}(end).value sprintf('%s{%s}',cp{1},LBCstr{LBC})]; % {round(job.opts.LBC*4)+1} + end + if isfield(job.opts,'biasacc') && job.opts.biasacc>0 + if job.opts.biasacc == catdef.opts.biasstr, cp{1} = npara; else, cp{1} = cpara; end % yes, catdef.opts.biasstr! + biasacc = {'ultralight','light','medium','strong','heavy'}; + str{1}(end).name = [str{1}(end).name(1:end-1) 'biasstr ']; + str{1}(end).value = [str{1}(end).value sprintf('%s{%s}',cp{1},biasacc{round(job.opts.biasacc*4)+1})]; + if job.extopts.expertgui % add the value ... too long ... + str{1}(end).value = [str{1}(end).value sprintf('(%0.2f,reg:%0.0e;fwhm:%0.0f)',job.opts.biasacc,job.opts.biasreg,job.opts.biasfwhm)]; + end + elseif isfield(job.opts,'biasacc') && job.opts.biasstr>0 + if job.opts.biasstr == catdef.opts.biasstr, cp{1} = npara; else, cp{1} = cpara; end + biasstr = {'ultralight','light','medium','strong','heavy'}; + str{1}(end).name = [str{1}(end).name(1:end-1) 'biasstr ']; + str{1}(end).value = [str{1}(end).value sprintf('%s{%s}',cp{1},biasstr{round(job.opts.biasstr*4)+1})]; + if job.extopts.expertgui % add the value,job.opts.biasstr + str{1}(end).value = [str{1}(end).value sprintf('(%0.2f,reg:%0.0e;fwhm:%0.0f)',job.opts.biasacc,job.opts.biasreg,job.opts.biasfwhm)]; + end + elseif isfield(job.opts,'biasreg') + if job.opts.biasreg == catdef.opts.biasreg, cp{1} = npara; else, cp{1} = cpara; end + if job.opts.biasfwhm == catdef.opts.biasfwhm, cp{2} = npara; else, cp{2} = cpara; end + str{1}(end).name = [str{1}(end).name(1:end-1) 'biasreg / biasfwhm']; + str{1}(end).value = [str{1}(end).value sprintf('%s{%0.0e} / %s{%0.2f}',cp{1},job.opts.biasreg,cp{2},job.opts.biasfwhm)]; + end + % 1 line 3: SPM segmentation accuracy with samp and tol + if isfield(job.opts,'acc') && job.opts.acc>0 + %str{1} = [str{1} struct('name', '','value','')]; + if job.opts.acc == catdef.opts.acc, cp{3} = npara; else, cp{3} = cpara; end + if job.extopts.expertgui==0 + accstr = {'ultra low','low','std','high','ultra high','insane'}; + str{1}(end).name = [str{1}(end).name(1:end-1) ' / accuracy: ']; + str{1}(end).value = [str{1}(end).value sprintf(' / %s{%s}',co,accstr{round(job.opts.acc*4)+1})]; + else % add the value + if job.opts.samp == catdef.opts.samp, cp{1} = npara; else, cp{1} = cpara; end + if job.opts.tol == catdef.opts.tol, cp{2} = npara; else, cp{2} = cpara; end + str{1}(end).name = [str{1}(end).name(1:end-1) ' / acc (samp/tol): ']; + str{1}(end).value = [str{1}(end).value sprintf('%s|%0.2f} (%s{%0.2f}/%s{%0.0e})',cp{3},job.opts.acc,cp{1},job.opts.samp,cp{2},job.opts.tol)]; + end + else + if job.extopts.expertgui && isfield(job.opts,'samp') + %str{1} = [str{1} struct('name', '','value','')]; + if job.opts.samp == catdef.opts.samp, cp{1} = npara; else, cp{1} = cpara; end + if job.opts.tol == catdef.opts.tol, cp{2} = npara; else, cp{2} = cpara; end + str{1}(end).name = [str{1}(end).name(1:end-1) ' / samp / tol: ']; + str{1}(end).value = [str{1}(end).value sprintf(' / %s{%0.2f} / %s{%0.0e}',cp{1},job.opts.samp,cp{2},job.opts.tol)]; + end + end + + + % 1 line: adaptive noise parameter ( MRFstr + SANLM + NCstr ) + NCstr.labels = {'none','full','light','medium','strong','heavy'}; + NCstr.values = {0 1 2 -inf 4 5}; + defstr = {'none','ultralight','light','medium','strong','heavy',... sanlm vs. isarnlm + 'ultralight+','ultralight+','light+','medium+','strong+','heavy+'}; + defstrm = @(x) defstr{ round(max(0,min(2,x))*4) + 1 + (x>0) + (x>1)}; + str{1} = [str{1} struct('name', 'Noise reduction:','value','')]; + if job.extopts.NCstr == catdef.extopts.NCstr, cp{1} = npara; else, cp{1} = cpara; end + if job.extopts.NCstr==0 + if job.extopts.mrf==0 + str{1}(end).value = [cpara 'no noise correction']; + else + if job.extopts.expertgui==0 + str{1}(end).value = [cpara 'MRF']; + else + str{1}(end).value = sprintf('%sMRF(%0.2f)',cpara,job.extopts.mrf); + end + end + else + str{1}(end).value = sprintf('SANLM(%s{%s})',cp{1},NCstr.labels{find(cell2mat(NCstr.values)==job.extopts.NCstr,1,'first')}); + end + + if job.extopts.NCstr~=0 && job.extopts.mrf + if job.extopts.expertgui==0 + str{1}(end).value = '+MRF'; + else + str{1}(end).value = sprintf('%s{+MRF(%0.2f)}',cpara,job.extopts.mrf); + end + end + + + % 1 line(s): LASstr / GCUTstr / CLEANUPstr / BVCsgtr + if job.extopts.LASstr == catdef.extopts.LASstr, cp{1} = npara; else, cp{1} = cpara; end + if job.extopts.gcutstr == catdef.extopts.gcutstr, cp{2} = npara; else, cp{2} = cpara; end + if job.extopts.cleanupstr == catdef.extopts.cleanupstr, cp{3} = npara; else, cp{3} = cpara; end + if job.extopts.BVCstr == catdef.extopts.BVCstr, cp{4} = npara; else, cp{4} = cpara; end + if isfield(job.extopts,'LASmyostr') && job.extopts.LASmyostr == 0, cp{5} = npara; else, cp{5} = cpara; end + gcutstr = {'none-pm','none','SPM','GCUT','APRG','APRG2'}; + bvcastr = {'not applied','applied'}; + if ~job.extopts.expertgui + str{1}(end).name = 'LAS strength / Skull-Stripping:'; + str{1}(end).value = sprintf('%s{%s} / %s{%s}',... + cp{1},defstrm(job.extopts.LASstr),... + cp{2},gcutstr{ceil(job.extopts.gcutstr+3)}); + elseif isfield(job.extopts,'LASmyostr') && job.extopts.LASmyostr == 0 + str{1}(end).name = 'LASstr / LASmyostr / GCUTstr / CLEANUPstr / BVCstr:'; + str{1}(end).value = sprintf('%s{%s(%0.2f)} / %s{%s(%0.2f)} / %s{%s(%0.2f)} / %s{%s(%0.2f)} / %s{%s(%0.2f)} %s',... + cp{1},defstrm(job.extopts.LASstr),job.extopts.LASstr,... + cp{5},defstrm(job.extopts.LASmyostr),job.extopts.LASmyostr,... + cp{2},gcutstr{ceil(job.extopts.gcutstr+3)},job.extopts.gcutstr,... + cp{3},defstrm(job.extopts.cleanupstr),job.extopts.cleanupstr,... + cp{4},defstrm(job.extopts.BVCstr),job.extopts.BVCstr,bvcastr{res.applyBVC+1}); + else + str{1}(end).name = 'LASstr / GCUTstr / CLEANUPstr / BVCstr:'; + str{1}(end).value = sprintf('%s{%s(%0.2f)} / %s{%s(%0.2f)} / %s{%s(%0.2f)} / %s{%s(%0.2f)} %s',... + cp{1},defstrm(job.extopts.LASstr),job.extopts.LASstr,... + cp{2},gcutstr{ceil(job.extopts.gcutstr+3)},job.extopts.gcutstr,... + cp{3},defstrm(job.extopts.cleanupstr),job.extopts.cleanupstr,... + cp{4},defstrm(job.extopts.BVCstr),job.extopts.BVCstr,bvcastr{res.applyBVC+1}); + end + + if job.extopts.WMHC == catdef.extopts.WMHC, cp{1} = npara; else, cp{1} = cpara; end + if job.extopts.SLC == catdef.extopts.SLC, cp{2} = npara; else, cp{2} = cpara; end + if isfield(job.extopts,'SRP') && job.extopts.SRP == catdef.extopts.SRP, cp{3} = npara; else, cp{3} = cpara; end + if isfield(job.extopts,'restypes') + restype = char(fieldnames(job.extopts.restypes)); + else + restype = job.extopts.restype; + job.extopts.restypes.(restype) = job.extopts.resval; + end + if strcmp(restype, catdef.extopts.restype), cp{4} = npara; else, cp{4} = cpara; end + % ############ + % WMHC in case of SPM segmentation is SPM + % ############ + if job.extopts.expertgui && isfield(job.extopts,'SRP') + str{1} = [str{1} struct('name', 'WMHC / SLC / SRP / restype:','value',... + sprintf('%s{%d} / %s{%d} / %s{%d} / %s{%s}',... + cp{1},job.extopts.WMHC, cp{2},job.extopts.SLC, cp{3},job.extopts.SRP, cp{4},restype))]; + else + wmhcstr = {'none (WMH=GM)','temporary (WMH=GM)','(WMH=WM)','own class'}; + str{1} = [str{1} struct('name', 'WMH Correction / Int. Res.:',... + 'value',sprintf('%s{%s} / %s{%s}',cp{1},wmhcstr{job.extopts.WMHC+1}, cp{4},restype))]; + end + if ~strcmp(restype, 'native') + str{1}(end).value = [str{1}(end).value sprintf('(%s{%0.2f %0.2f})',npara, job.extopts.restypes.(restype))]; + end + elseif exist('seg8','var') + % biasfwhm, biasreg ... not available from seg8 file + if isfield(job.extopts,'SRP') && job.extopts.SRP == catdef.extopts.SRP, cp{4} = npara; else, cp{4} = cpara; end + if isfield(job.extopts,'spmAMAP') && job.extopts.spmAMAP, ca{4} = cpara; else, job.extopts.spmAMAP = 0; ca{4} = npara; end + str{1} = [str{1} struct('name', 'ncls / use AMAP / SRP:','value',sprintf('[%s%s] / %s{%d} / %s{%d}',... + sprintf('%d ',seg8.lkp(1:end-1)), sprintf('%d',seg8.lkp(end)), ca{4}, job.extopts.spmAMAP, cp{4}, job.extopts.SRP))]; + elseif exist('segsn','var') + % biasfwhm, biasreg ... not available from seg8 file + if isfield(job.extopts,'SRP') && job.extopts.SRP == catdef.extopts.SRP, cp{4} = npara; else, cp{4} = cpara; end + if isfield(job.extopts,'spmAMAP') && job.extopts.spmAMAP, ca{4} = cpara; else, job.extopts.spmAMAP = 0; ca{4} = npara; end + str{1} = [str{1} struct('name', 'use AMAP / SRP:','value',sprintf('%s{%d} / %s{%d}',... + ca{4}, job.extopts.spmAMAP, cp{4}, job.extopts.SRP))]; + end + + + % line 8: resolution parameter + % RD202007: I am sure if a colorrating works here - it is just too much. + v3 = sprintf('%s',native2unicode(179, 'latin1')); + if job.output.surface + str{1} = [str{1} struct('name', 'Voxel resolution (original > internal > PBT; vox):',... + 'value',sprintf('%4.2fx%4.2fx%4.2f > %4.2fx%4.2fx%4.2f > %4.2f%s mm%s; %4.2f%s mm%s ', ... + qa.qualitymeasures.res_vx_vol,qa.qualitymeasures.res_vx_voli,job.extopts.pbtres,... + v3,v3,job.extopts.vox(1),v3,v3))]; + else + str{1} = [str{1} struct('name', 'Voxel resolution (original > intern; vox):',... + 'value',sprintf('%4.2fx%4.2fx%4.2f mm%s > %4.2fx%4.2fx%4.2f mm%s; %4.2f%s mm%s', ... + qa.qualitymeasures.res_vx_vol,v3,qa.qualitymeasures.res_vx_voli,... + v3,job.extopts.vox(1),v3,v3))]; + end + % str{1} = [str{1} struct('name', 'Norm. voxel size:','value',sprintf('%0.2f mm',job.extopts.vox))]; % does not work yet + + % line 9: surface parameter + + + % Image Quality measures: + % -------------------------------------------------------------------- + str{2} = struct('name', '\bfImage and Preprocessing Quality:','value',''); + if job.extopts.expertgui >= 0 % RD202508: could maybe be shorter but lets start with this + % single ratings + str{2} = [str{2} struct('name',' Resolution (RMS):','value',marks2str(qa.qualityratings.res_RMS,... + sprintf('%5.2f%% (%s)',mark2rps(qa.qualityratings.res_RMS),mark2grad(qa.qualityratings.res_RMS))))]; + if isfield(qa.qualityratings,'res_ECR') + str{2} = [str{2} struct('name',' Edge contrast rating (ECR):','value',marks2str(qa.qualityratings.res_ECR,... + sprintf('%5.2f%% (%s)',mark2rps(qa.qualityratings.res_ECR),mark2grad(qa.qualityratings.res_ECR))))]; + end + str{2} = [str{2} struct('name',' Noise contrast rating (NCR):','value',marks2str(qa.qualityratings.NCR,... + sprintf('%5.2f%% (%s)',mark2rps(qa.qualityratings.NCR),mark2grad(qa.qualityratings.NCR))))]; + str{2} = [str{2} struct('name',' Inhomogenity contrast rating (ICR):','value',marks2str(qa.qualityratings.ICR,... + sprintf('%5.2f%% (%s)',mark2rps(qa.qualityratings.ICR),mark2grad(qa.qualityratings.ICR))))]; % not important and more confusing + if isfield(qa.qualityratings,'FEC') + str{2} = [str{2} struct('name',' Fast Euler Characteristic (FEC):','value',marks2str(qa.qualityratings.FEC,... + sprintf('%5.2f%% (%s)',mark2rps(qa.qualityratings.FEC),mark2grad(qa.qualityratings.FEC))))]; + end + % average rating + str{2} = [str{2} struct('name','\bf Weighted average (SIQR):','value',marks2str(qa.qualityratings.SIQR,... + sprintf('%5.2f%% (%s)',mark2rps(qa.qualityratings.SIQR),mark2grad(qa.qualityratings.SIQR))))]; + else + % only average rating + str{2} = [str{2} struct('name','Weighted average (SIQR):','value',marks2str(qa.qualityratings.SIQR,... + sprintf('%5.2f%% (%s)',mark2rps(qa.qualityratings.SIQR),mark2grad(qa.qualityratings.SIQR))))]; + end + + % additional surface measures + % Euler/defect number (all pipelines? - not in CS4) + if isfield(qa.qualitymeasures,'SurfaceEulerNumber') && ~isempty(qa.qualitymeasures.SurfaceEulerNumber) && isfinite(qa.qualitymeasures.SurfaceEulerNumber) + str{2} = [str{2} struct('name',' Surface Euler number:','value',marks2str(qa.qualityratings.SurfaceEulerNumber,... + sprintf('%g', qa.qualitymeasures.SurfaceEulerNumber)))]; + end + % self intersections (all pipelines?) + if job.extopts.expertgui && isfield(qa.qualitymeasures,'SurfaceSelfIntersections') && ~isempty(qa.qualitymeasures.SurfaceSelfIntersections) && ... + ~isnan(qa.qualitymeasures.SurfaceSelfIntersections) + str{2}(end).name = [str{2}(end).name(1:end-6) ' / self-inters. size:']; + str{2}(end).value = [str{2}(end).value ' / ' marks2str(qa.qualityratings.SurfaceSelfIntersections,... + sprintf('%0.2f%%', qa.qualitymeasures.SurfaceSelfIntersections)) ]; + end + % Surface Intensity/Position + if job.extopts.expertgui && isfield(qa.qualityratings,'SurfaceIntensityRMSE') + str{2} = [str{2} struct('name',' Surface intensity / position RMSE:','value',[ marks2str( qa.qualityratings.SurfaceIntensityRMSE ,... + sprintf('%0.3f', qa.qualitymeasures.SurfaceIntensityRMSE)) ' / ' ... + marks2str( qa.qualityratings.SurfacePositionRMSE ,sprintf('%0.3f', qa.qualitymeasures.SurfacePositionRMSE) ) ] ) ]; + end + + + % Subject Measures + % -------------------------------------------------------------------- + % Volume measures + + % header + str{3} = struct('name', '\bfVolumes:','value',sprintf('%5s %5s %5s ','CSF','GM','WM')); + if job.extopts.WMHC>2, str{3}(end).value = [str{3}(end).value sprintf('%5s ','WMH')]; end + if job.extopts.SLC>0, str{3}(end).value = [str{3}(end).value sprintf('%5s ','SL')]; end + + % absolute volumes + if job.extopts.WMHC<=2 && isfield(qa,'subjectmeasure') && isfield(qa.subjectmeasures,'vol_rel_WMH') && ... + ( (qa.subjectmeasures.vol_rel_WMH>0.01 || qa.subjectmeasures.vol_rel_WMH/qa.subjectmeasures.vol_rel_CGW(3)>0.02) ) + if job.extopts.WMHC == 2 + str{3} = [str{3} struct('name', ' Absolute volume:','value',... + sprintf('%5.0f %5.0f {\\bf\\color[rgb]{1 0 1}%5.0f} ', qa.subjectmeasures.vol_abs_CGW(1:3)))]; + else + str{3} = [str{3} struct('name', ' Absolute volume:','value',... + sprintf('{%5.0f \\bf\\color[rgb]{1 0 1}%5.0f} %5.0f', qa.subjectmeasures.vol_abs_CGW(1:3)))]; + end + else + str{3} = [str{3} struct('name', ' Absolute volume:','value',... + sprintf('%5.0f %5.0f %5.0f ', qa.subjectmeasures.vol_abs_CGW(1:3)))]; + end + if job.extopts.WMHC>2, str{3}(end).value = [str{3}(end).value sprintf('%5.1f ',qa.subjectmeasures.vol_abs_CGW(4))]; end + if job.extopts.SLC>0, str{3}(end).value = [str{3}(end).value sprintf('%5.1f ',qa.subjectmeasures.vol_abs_CGW(5))]; end + str{3}(end).value = [str{3}(end).value 'cm' native2unicode(179, 'latin1')]; + + % relative volumes + if job.extopts.WMHC<=2 && isfield(qa,'subjectmeasure') && isfield(qa.subjectmeasures,'vol_rel_WMH') && ... + ( (qa.subjectmeasures.vol_rel_WMH>0.01 || qa.subjectmeasures.vol_rel_WMH/qa.subjectmeasures.vol_rel_CGW(3)>0.02) ) + if job.extopts.WMHC == 2 + str{3} = [str{3} struct('name', ' Relative volume:','value',... + sprintf('%5.1f %5.1f {\\bf\\color[rgb]{1 0 1}%5.1f} ', qa.subjectmeasures.vol_rel_CGW(1:3)*100))]; + else + str{3} = [str{3} struct('name', ' Relative volume:','value',... + sprintf('{%5.1f \\bf\\color[rgb]{1 0 1}%5.1f} %5.1f ', qa.subjectmeasures.vol_rel_CGW(1:3)*100))]; + end + else + str{3} = [str{3} struct('name', ' Relative volume:','value',... + sprintf('%5.1f %5.1f %5.1f ', qa.subjectmeasures.vol_rel_CGW(1:3)*100))]; + end + if job.extopts.WMHC>2, str{3}(end).value = [str{3}(end).value sprintf('%5.1f ',qa.subjectmeasures.vol_rel_CGW(4)*100)]; end + if job.extopts.SLC>0, str{3}(end).value = [str{3}(end).value sprintf('%5.1f ',qa.subjectmeasures.vol_rel_CGW(5)*100)]; end + str{3}(end).value = [str{3}(end).value '%']; + + % warning if many WMH were found and not handled as extra class + if job.extopts.WMHC<=2 && isfield(qa,'subjectmeasures') && isfield(qa.subjectmeasures,'vol_rel_WMH') && ... + ( (qa.subjectmeasures.vol_rel_WMH>0.01 || qa.subjectmeasures.vol_rel_WMH/qa.subjectmeasures.vol_rel_CGW(3)>0.02) ) + if job.extopts.WMHC == 2 + str{3}(end-1).value = [str{3}(end-1).value sprintf('\\color[rgb]{1 0 1} (WM inc. %0.0fcm%s WMHs)', ... + qa.subjectmeasures.vol_abs_WMH,native2unicode(179, 'latin1'))]; + str{3}(end).value = [str{3}(end).value sprintf('\\color[rgb]{1 0 1} (WM inc. %0.1f%% WMHs)', qa.subjectmeasures.vol_rel_WMH)]; + %str{3}(end).value = [str{3}(end).value sprintf('\\bf\\color[rgb]{1 0 1} WMHs %0.1f%% > WM!', qa.subjectmeasures.vol_rel_WMH * 100)]; + else + str{3}(end-1).value = [str{3}(end-1).value sprintf('\\color[rgb]{1 0 1} (GM inc. %0.0fcm%s WMHs)', ... + qa.subjectmeasures.vol_abs_WMH,native2unicode(179, 'latin1'))]; + str{3}(end).value = [str{3}(end).value sprintf('\\color[rgb]{1 0 1} (GM inc. %0.1f%% WMHs)', qa.subjectmeasures.vol_rel_WMH * 100)]; + %str{3}(end).value = [str{3}(end).value sprintf('\\bf\\color[rgb]{1 0 1} WMHs %0.1f%% > GM!', qa.subjectmeasures.vol_rel_WMH * 100)]; + end + end + + str{3} = [str{3} struct('name', ' TIV:','value', sprintf(['%0.0f cm' cub],qa.subjectmeasures.vol_TIV))]; + if isfield(qa.subjectmeasures,'surf_TSA') && job.extopts.expertgui>1 + str{3}(end).name = [str{3}(end).name(1:end-1) ' / TSA:']; + str{3}(end).value = [str{3}(end).value sprintf(' / %0.0f cm%s' ,qa.subjectmeasures.surf_TSA,cub)]; + end + + % Surface measures - Thickness, (Curvature, Depth, ...) + %if cellfun('isempty',strfind({Psurf(:).Pcentral},'ch.')), thstr = 'Cerebral Thickness'; else thstr = 'Thickness'; end + if isfield(qa.subjectmeasures,'dist_thickness') && ~isempty(qa.subjectmeasures.dist_thickness) + if job.extopts.expertgui > 1 && isfield(qa.subjectmeasures,'dist_thickness_kmeans') + [tmp,kmax] = max( qa.subjectmeasures.dist_thickness_kmeans_inner3(:,3) ); clear tmp; %#ok + str{3} = [str{3} struct('name', '\bfThickness \rm(kmeans):','value',sprintf('%4.2f%s%4.2f mm (%4.2f%s%4.2f mm)', ... + qa.subjectmeasures.dist_thickness{1}(1),pm,qa.subjectmeasures.dist_thickness{1}(2), ... + qa.subjectmeasures.dist_thickness_kmeans_inner3(kmax,1),pm,... + qa.subjectmeasures.dist_thickness_kmeans_inner3(kmax,2)))]; + else + str{3} = [str{3} struct('name', '\bfThickness:','value',sprintf('%4.3f%s%4.3f mm', ... + qa.subjectmeasures.dist_thickness{1}(1),pm,qa.subjectmeasures.dist_thickness{1}(2)))]; + end + % we warn only if WMHC is off ... without WMHC you have not thresholds! + %if job.extopts.WMHC==0 && (qa.subjectmeasures.vol_rel_WMH>0.01*3 || ... % 3 times higher treshold + % qa.subjectmeasures.vol_rel_WMH/qa.subjectmeasures.vol_rel_CGW(3)>0.02*3) + % str{3}(end).value = [str{3}(end).value sprintf('\\color[rgb]{1 0 1} (may biased by WMHs!)')]; + %end + + if isfield(qa.subjectmeasures,'dist_gyruswidth') && ~isnan(qa.subjectmeasures.dist_gyruswidth{1}(1)) + str{3} = [str{3} struct('name', '\bfGyruswidth:','value',sprintf('%5.2f%s%4.2f mm', ... + qa.subjectmeasures.dist_gyruswidth{1}(1),pm,qa.subjectmeasures.dist_gyruswidth{1}(2)))]; + end + if isfield(qa.subjectmeasures,'dist_sulcuswidth') && ~isnan(qa.subjectmeasures.dist_sulcuswidth{1}(1)) + str{3} = [str{3} struct('name', '\bfSulcuswidth:','value',sprintf('%5.2f%s%4.2f mm', ... + qa.subjectmeasures.dist_sulcuswidth{1}(1),pm,qa.subjectmeasures.dist_sulcuswidth{1}(2)))]; + end + end + + % Preprocessing Time + str{2} = [str{2} struct('name','\bfProcessing time:','value',sprintf('%02.0f:%02.0f min', ... + floor(round(etime(clock,res.stime))/60),mod(round(etime(clock,res.stime)),60)))]; + +%% Warnings +% key changes? +% - use backup pipeline (with #?) +% - use AMAP/SPM/mixed ? +% - add skull-stripping, background, ... settings? + str{2} = [str{2} struct('name', '','value','')]; % empty line + wname = {'note','warning','alert'}; + wcolor = [0 0 1; 1 0.5 0; 0.8 0 0]; + valnl = 80; + for wi=2:-1:0 + warn = cat_io_addwarning(wi); + wn = numel(warn); + if wn + if job.extopts.expertgui > -wi + msg = strrep(warn(1).identifier,'_','\_') ; + for wmi=2:wn + msg = [msg ', ' strrep( warn(wmi).identifier,'_','\_') ]; +% linebreak may cause other problems ... + %if numel(msg)>valnl && wmi/dev/null` + + # first check for nii.gz + if [ ! -n ""$t1"" ]; then + t1=`ls ${j}/anat/sub*T1w.nii 2>/dev/null` + # if not found then check for nii + fi + # update list and count if something is found + if [ -n ""$t1"" ]; then + list=""${list} ${t1}"" + count=`expr $count + 1` + fi + + done + + # nothing found + if [ ""${count}"" -eq ""0"" ]; then + echo ""Could not found any *.nii* file in ${j}/anat/"" + else + # use cross-sectional pipeline for single files + if [ ""${count}"" -eq ""1"" ]; then + ${cat12_dir}/cat_batch_cat.sh $list -p 1 $fg --matlab $matlab --defaults $default $no_surf $rp --bids_folder $bids_folder_cross --logdir $log_folder + else # otherwise call longitudinal pipeline + ${cat12_dir}/cat_batch_long.sh $list $fg --matlab $matlab --defaults $default --model $model $no_surf $export_dartel --bids_folder $bids_folder_long --logdir $log_folder + fi + fi + +done + +","Shell" +"Neurology","ChristianGaser/cat12","cat_main_registration.m",".m","83147","1730","function [trans,reg,Affine] = cat_main_registration(job,dres,Ycls,Yy,Ylesion,Yp0,Ym,Ymi,Yl1) +% ______________________________________________________________________ +% Spatial registration function of cat_main preprocessing that include +% the SPM DARTEL and (optimized) SHOOTING registration approaches. +% +% There are 4 image spaces with image different dimensions and resolution: +% (1) individual/original (IR) - properties of the (interpolated) anatomical image +% (2) template (TR) - properties of the registration template image +% (3) registration (RR) - properties for the registration +% (4) output/analyse (AR) - final resolution of the normalized images +% +% DARTEL runs depending on the output resolution and RR = AR, whereas +% the original DARTEL runs always on the TR. It takes typically about +% 3 Minutes/Subject for RR = 1.5 mm. +% SHOOTING needs about 10 Minutes/Subject for RR = 1.5 mm and much more +% for higher RR and especially the low smooth deformation are important. +% The optimized version used therefore reduced resolution level to speedup +% the iteration and allow more smooth deformations and reduce the final +% costs. The changes between the deformation and the matching compared to +% the templates are used as iteration criteria. +% In 2021 a boundary box parameter was added that allows to change the size +% of the final processed images. +% Moreover, a backup routine is available that use the given nonlinear +% registration from the input (normally from the unified segmentation). +% +% Main control parameter: +% job.extopts.regstr .. +% * Main cases: +% 0 .. DARTEL, +% eps - 1 .. Optimized Shooting with low (eps; fast) to high +% to high quality (1; slow) with 0.5 as default +% 2 .. Optimized Shooting with fixed resolutions (3:(3-TR)/4:TR) +% 3 .. Optimized Shooting with fixed resolutions (TR/2:TR/4:TR) +% 4 .. Default Shooting +% +% * Fixed resolution level with interpolation: +% 11 .. hard deformations +% 12 .. medium deformations +% 13 .. soft deformations +% +% * Fixed resolution level without interpolation (max res = TR): +% 21 .. hard deformations +% 22 .. medium deformations +% 23 .. soft deformations +% +% Structure: +% [trans,reg] = cat_main_registration(job,res,Ycls,Yy[,Ylesion,Ym,Ymi,Yl1]) +% +% trans .. output variable that is used in cat_main and cat_io_writenii +% reg .. output variable that include the summarize of the deformation +% +% job .. SPM job structure with cat_main parameter +% res .. SPM parameter structure with further fields from CAT processing +% Ycls .. tissue classification that is used for deformation +% Yy .. old initial SPM deformation +% Ylesion .. template files +% [Ym,Yp0,Ymi,Yl1] .. additional maps in case of multiple registrations +% ______________________________________________________________________ +% +% The TR is expected to be between 1.0 and 1.5 mm. Higher resolution are +% possible, but not will not be become a standard CAT templates. +% +% RRs higher than the TR allow small improvements, but with improper costs. +% Tests with 0.5 mm RR lead to an shooting error (to high determinant). +% +% Lower RR lead to smoother deformations and were the focus of the +% optimization and allow further deformation cases. +% +% There are different ways to use lower resolutions: +% (LR = lowest resolution - should be better than 3 mm!): +% 1) flexible step size with fixed lower limit: +% a) LR : (LR - TR)/5 : TR +% 2) upper limit +% a) fixed levels without/without limit by TR oder by user (deformation limit) +% max( RR , 3.0 : -0.5 : 1.0 ) +% max( RR , 2.5 : -0.5 : 0.5 ) +% b) dynamic levels +% 3) TR limit +% a) TR+SS*5 : -SS : TR with SS = 0.25 - 0.5 +% 4) LR limit +% +% Although, it is possible to use the deformation to estimate finer +% rigid/affine transformation, we do not do this because rigid/affine +% output should run without spatial registration. +% +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +%#ok<*ASGLU> + + + if ~nargin, help cat_main_registration; end + + + + % if there is a breakpoint in this file set debug=1 and do not clear temporary variables + dbs = dbstatus; debug = 0; for dbsi=1:numel(dbs), if strcmp(dbs(dbsi).name,mfilename); debug = 1; break; end; end + + + % Lesions + if ~exist('Ylesion','var') || sum(Ylesion(:))==0, Ylesion = []; end + + + % initialize output + Affine = dres.Affine; + trans = struct(); + + + % ######################## + % default settings ############# mostly shooting ... not here + def.nits = 64; % Shooting iterations + def.opt.ll1th = 0.001; % smaller better/slower + def.opt.ll3th = 0.002; % + def.fast = 0; % no report, no output + def.affreg = 0; % additional affine registration + def.iterlim = inf; % + def.regra = 1; % use affine registration: 0 - rigid, 1 - affine + def.clsn = 2; % use only GM and WM ... may extend to CSF ################### DEPENDING ON TEMPLATE ############# + if ~isfield(job.extopts,'reg'), job.extopts.reg = struct(); end + if isstruct( job.extopts.reg ) + dreg = cat_io_checkinopt(job.extopts.reg,def); + else + dreg = def; + end + dres.Affine0 = dres.Affine; + if ~isfield(dres,'Yymat'), dres.Yymat = dres.tpm(1).mat; end % use matrix for input deformation Yy + % ######################## + + + % error in parallel processing - can't find shooting files (2016/12) + % switch to shooting directory + if ~exist('spm_shoot_defaults','file') || ~exist('spm_shoot_update','file') + olddir = cd; cd(fullfile(spm('dir'),'toolbox','Shoot')); + end + if job.extopts.subfolders, mrifolder = 'mri'; else, mrifolder = ''; end + + + + % this is just for me to create different templates and can be removed in a final version + if numel(job.extopts.vox)>1 || numel(job.extopts.regstr)>1 || (isfield(job,'export') && job.export) + job.extopts.multigreg = 1; + export = 1; % write files in sub-directories for tests + else + job.extopts.multigreg = 0; + export = 0; + end + + + +% #################### THIS SHOULD BE EVALUATED IN FUTURE ################# +% additional affine registration of the GM segment (or the brainmask) ? +% only if not the prior (long-pipeline) is used +% RD202101 - this (GM registration) cause problems (e.g. BUSS_2020) +% - We need to rethink if a final registration would be useful because we +% now have a much better (or even final) brainmask as well as a (first) +% segmentation. +% - GM registration would be better for unusal affine GM analysis and would +% reduce the costs of a typical GM focused deformation but it does not +% fit to previous definitions rising different issues. +% But an update with new brain mask might be interesting, but the method +% has to be choosen well - maybe the affreg of the brainmasks? or with T1 +% or the (smoothed) p0 Segmentation. maffreg will allways try to balance +% the different classes (what we probably not want) +%{ + if dreg.affreg && ( ~isfield(job,'useprior') || isempty(job.useprior) || ~exist(char(job.useprior),'file') ) + % Create maffreg obj structure similar to cat_run_job but only for the + % GM segment. + obj.image = res.image; + obj.image.pinfo = repmat([255;0],1,size(Ycls{1},3)); + obj.image.dt = [spm_type('UINT8') spm_platform('bigend')]; + obj.image.dat = cat_vol_ctype(single(Ycls{1})/2 + single(Ycls{2})); + if isfield(obj.image,'private'), obj.image = rmfield(obj.image,'private'); end + obj.samp = 1.5; + obj.fwhm = 1; + if isfield(obj,'tpm'), obj = rmfield(obj,'tpm'); end + + % call maffreg + obj.tpm = spm_load_priors8(res.tpm(1:2)); + + wo = warning('QUERY','MATLAB:RandStream:ActivatingLegacyGenerators'); wo = strfind( wo.state , 'on'); + if wo, warning('OFF','MATLAB:RandStream:ActivatingLegacyGenerators'); end + res.Affine = spm_maff8(obj.image,obj.samp,obj.fwhm,obj.tpm,res.Affine,job.opts.affreg,80); + if wo, warning('ON','MATLAB:RandStream:ActivatingLegacyGenerators'); end + Affine = res.Affine; + cat_progress_bar('Clear'); + end +%} +if dreg.affreg && ( ~isfield(job,'useprior') || isempty(job.useprior) || ~exist(char(job.useprior),'file') ) +% Final affine registration in the cross sectional case +% * Although the registration here should work, do we have to consider this +% for the Yy deformation map ? + + regname = {'brain','skull','GM','WM'}; + + stime = cat_io_cmd(sprintf('\n Affine %s registration',regname{dreg.affreg}),'g5','',job.extopts.verb); + + % load registration template with focus of brain mask + Vtmpb = spm_vol( job.extopts.templates{1} ); + if numel( Vtmpb ) < 4 % if the template has all 3 brain classes + Vtmpb = dres.tpm(1:3); + end + switch dreg.affreg + case 1, cw = [1 2 0]; % brain tissue without CSF + case 2, cw = [1 2 1]; % brain mask with lightly underlined WM + case 3, cw = [1 0 0]; % GM only + case 4, cw = [0 1 0]; % WM only + end + + % create individual and template registration image + Yb = zeros(size(Ycls{1})); + Ybt = zeros(Vtmpb(1).dim,'single'); + for ci = 1:min(numel(Vtmpb),numel(Ycls)) + Ybt = Ybt + spm_read_vols( Vtmpb(ci) ) * cw(ci); + Yb = Yb + single(Ycls{ci})/255 * cw(ci); + end + if cw(3) + Ybt = Ybt .* cat_vol_morph( cat_vol_morph(Ybt>0.25,'lo',1) , 'd'); % remove eyes + end + + % prepare data for affreg + VG = spm_vol( Vtmpb(1) ); + %VG = Vtmpb(1) ; + %if isfield(VG,'dat'), VG = rmfield(spm_vol( Vtmpb(1) ),'dat'); end + VG.dt = [spm_type('UINT8') spm_platform('bigend')]; + VG.dat(:,:,:) = cat_vol_ctype(Ybt * 208,'uint8'); + % sometimes data are not uint8 + if ~isa(VG.dat,'uint8'), VG.dat = uint8(VG.dat); end + VG.pinfo = repmat([1;0],1,size(Ybt,3)); + VG = cat_spm_smoothto8bit(VG,eps); + clear Ybt; + + VF = spm_vol( dres.image.fname ); + VF.dt = [spm_type('UINT8') spm_platform('bigend')]; + VF.dat(:,:,:) = cat_vol_ctype(Yb * 208,'uint8'); + VF.pinfo = repmat([1;0],1,size(Yb,3)); + VF = cat_spm_smoothto8bit(VF,job.opts.samp); + clear Yb; + + % affreg + aflags = struct('sep',job.opts.samp,'regtype','subj','WG',[],'WF',[],'globnorm',1); + warning off; + [Affine, affscale] = spm_affreg(VG, VF, aflags, dres.Affine); + warning on; + dres.Affine = Affine; + clear VG VF ; + fprintf('%5.0fs\n',etime(clock,stime)); +end +% ######################################################################### + + + % limit number of classes + if ~( export && numel( job.extopts.vox ) > 1 ) + Ycls( max( 4 , dreg.clsn + 1):end ) = []; % need CSF for robust skull definition + end + + + % Helping function(s): + % BB2dim estimates the new size of an image given by the old and new + % boudnary box (oldbb/newbb), image resolution (oldres/newres), and the + % size of the old image. MNI space has always a 0-slice resulting in odd + % dimensions. + BB2dim = @(oldbb,newbb,olddims,oldres,tpmres,newres) floor( ( olddims * oldres - sum( ( abs(oldbb) - abs(newbb) ) ) ) / oldres * (tpmres/newres) / 2 ) * 2 + 1; + + + + % boundary box settings: 0 - Template, 1 - TPM, +[1x1] - SPM MNI + #; -[1x1] - (TMP>0.1) + #; [2x3] - own BB + % boundary box definition: to write a correct x=-1 output image, we have to be sure that the x value of the bb is negative + Vtmp = spm_vol(job.extopts.templates{1}); + if dres.bb(1) 1 + % dynamic boundary based on the human SPM TPM that requires a + % similar lower limit (they just extend the BB to cover the + % full head but do not extend below so strong the cerebellum) + b = job.extopts.bb; + resbb = [-72 -108 -72; 72 72 72] + [ -b -b 0 ; b b b*2]; + else + % it is possible to use the template to create an dynamic + % automatic mapping + b = -job.extopts.bb; +% ######################## THIS NEED TO BE FINISHED ####################### + %Ytmp = + %tmpbb = +% ######################################################################### + tmpbb = [-72 -108 -72; 72 72 72]; + resbb = tmpbb + [ -b -b -b ; b b b]; + end + end + elseif numel( job.extopts.bb ) == 6 + if any( isinf( job.extopts.bb ) ) + resbb = spm_get_bbox( Vtmp ); + else + resbb = reshape( job.extopts.bb(:) , 2 , 3) ; % own + end + else + error('BB has to be a 2x3 matrix.'); + end + if resbb(1) 2 + [M3,R] = spm_get_closest_affine( affind(rgrid( idim ) ,M0) , affind(Yy,dres.Yymat) , single(Ycls{1} + Ycls{2} + Ycls{3})/255); clear M3; + else + [M3,R] = spm_get_closest_affine( affind(rgrid( idim ) ,M0) , affind(Yy,dres.Yymat) , single(Ycls{1} + Ycls{2})/255); clear M3; + end + Mrigid = M0\inv(R)*M1; % transformation from subject to registration space (rigid) + Maffine = M0\inv(res.Affine)*M1; % individual to registration space (affine) + mat0a = res.Affine\M1; % mat0 for affine output + mat0r = R\M1; % mat0 for rigid ouput + + % settings for new boundary box of the output images + if isfield(res,'imagesc'); trans.native.Vo = res.imagec(1); else, trans.native.Vo = res.image0(1); end + trans.native.Vi = res.image(1); + trans.affine = struct('odim',odim,'mat',M1,'mat0',mat0a,'M',Maffine,'A',res.Affine); % structure for cat_io_writenii + trans.rigid = struct('odim',odim,'mat',M1,'mat0',mat0r,'M',Mrigid ,'R',R); % structure for cat_io_writenii + + if export && debug + % template creation + fn = {'GM'}; %,'WM','CSF','HD1','HD2','BG'}; + for clsi = 1:numel(fn) + cat_io_writenii(trans.native.Vo,single(Ycls{clsi})/255,fullfile(mrifolder,'debug'),sprintf('p%d',clsi),... + sprintf('%s tissue map',fn{clsi}),'uint8',[0,1/255],[0 0 0 3],trans); + end + %continue + end + + % rigid vs. affine input in registration: + if dreg.regra % affine + Maffinerigid = Maffine; + TAR = res.Affine; + else % rigid + Maffinerigid = Mrigid; + TAR = R; + end + +%% + try + if (res.do_dartel==1 && isempty( job.extopts.darteltpm{1} ) ) || ... + (res.do_dartel>0 && res.do_dartel<1 && isempty( job.extopts.shootingtpm{1} ) ) || ... + (res.do_dartel>=2 && isempty( job.extopts.shootingtpm{1} ) ) + error('cat_main_registration:useSPMreg', ... + 'TPMs are not supported for Dartel/Shooting registration. Use previous registration.') + elseif res.do_dartel<0 + error('cat_main_registration:testBackup', ... + 'Test backup routing that should use the previous registration.') + end + + % main functions + if res.do_dartel + if job.extopts.regstr(regstri)==0 % Dartel + [trans,reg] = run_Dartel(Ycls,Ylesion,job,reg,res,trans,Mad,Maffinerigid,TAR,regstri,voxi); + elseif job.extopts.regstr(regstri)>0 % Geodesic Shooting + [trans,reg] = run_Shooting(Ycls,Ylesion,job,reg,res,trans,Maffinerigid,regstri,voxi); + end + + % Report - display registration profil + if job.extopts.verb>1 || export + report(job,reg,regstri); + end + else + %% define warping variables based on previous deformation + % estimate the inverse transformation + yid = spm_diffeo('invdef', Yy , odim, inv(tpmM\M1), M1\res.Affine*M0); + try + yi = spm_diffeo('invdef', yid, idim, inv(M1\res.Affine*M0), eye(4)); clear yid; + yi2 = spm_diffeo('invdef', yi , odim, eye(4), eye(4)); + catch + % RD202502: strange error with Rusak2021_sub-ADNI003S5209_simGMatrophy0.00mm.nii so we repalce bad voxels by neighbors + yidbad = isinf(yid) | yid<0 | yid>200; yid(yidbad) = nan; clear yidbad; + yi = spm_diffeo('invdef', yid, idim, inv(M1\res.Affine*M0), eye(4)); clear yid; + yibad = isinf(yi) | yi<0 | yi>max(size(yi)); yi(yibad) = nan; clear clear yidbad; + yi2 = spm_diffeo('invdef', yi , odim, eye(4), eye(4)); + end + w = max( eps , abs(spm_diffeo('def2det', yi2 ) ) ); + % Adaption to avoid boundary effects by correcting the voxel close + % to the image boundary that are effected by the interpolation of + % the field. + msk = cat_vol_morph( isnan( yi2(:,:,:,1)) ,'d',3); w( msk(:) ) = NaN; + wa = cat_vol_approx(w,'nn',1,4); bg = cat_stat_nanmean( wa(msk(:)) ); + msk = cat_vol_smooth3X(msk,2); w( isnan(w) ) = wa( isnan(w) ); + w = wa .* msk + (1-msk) .* w; clear msk wa; + % use half registration resolution to define the amout of smoothing to reduce registration artefacts + fs = newres / 2; w = w - bg; spm_smooth(w,w,fs); w = bg + w; % spm smoothing boudary problem where values outside are 0 + M2 = inv(Maffine); % warped - if we use the US than we may have to use rigid + + trans.warped = struct('y',yi ,'yi',yi2,'w',w,'odim',odim,'M0',M0,'M1',M1,'M2',M2,'dartel',res.do_dartel,'fs',fs); % nicer version with interpolation + if job.output.jacobian.warped + trans.jc = struct('odim',odim,'dt2',w); + end + end + % export for tests + if export || debug + write_nii(Ycls,job,trans,reg(regstri).testfolder,reg(regstri)); + end + if numel( job.extopts.vox ) > 1 % job.extopts.experimental && + % full export + job2 = job; + job2.extopts.mrifolder = fullfile('mri',reg(regstri).testfolder); + cat_main_write(Ym,Ymi,Ycls,Yp0,Yl1,job2,res,trans); + end + catch e +%% ------------------------------------------------------------------------ +% Catch problems and use the original input (e.g. from the unified +% segmentation) and prepare the output by just changing BB and vox +% and prepare the output structure we use to write the nifties. +% This uses the old deformation that was in general done by the Unified +% Segmentation. +% ------------------------------------------------------------------------ + + if strcmp( e.identifier , 'cat_main_registration:useSPMreg' ) + cat_io_addwarning('cat_main_registration:useSPMreg',... + 'No Dartel/Shooting template was given. \\nUse previous registration to TPM.',0,[1 1]); % not a error but a feature + elseif strcmp( e.identifier , 'cat_main_registration:testBackup' ) + cat_io_addwarning('cat_main_registration:testBackup', ... + 'Test backup routing that should use the previous registration.',1,[1 1]); % not a error but a feature + else + cat_io_addwarning('cat_main_registration:regError',... + 'Registration problem due to given input segmentation. \\nUse previous registration.',2,[1 1]); + end + res.Affine = res.Affine0; + + % set registration parameter + [reg,res,job] = regsetup(dreg,reg,dres,job,regstri,voxi); + + tpmM = res.tpm(1).mat; + tmpM = Vtmp(1).mat; + + % resolutions + if isscalar(job.extopts.bb) && job.extopts.bb == 0 % TPM case + tmpres = abs(tpmM(1)); % TPM resolution + newres = tmpres; % output resolution + else + % - in this case tpmres == tmpres + tmpres = abs(tmpM(1)); % template resolution + newres = job.extopts.vox(voxi); if isinf(newres), newres = tmpres; end % output resolution + end + + % image size/dimension + idim = res.image(1).dim(1:3); % (interpolated) input image size + sdim = res.tpm(1).dim; % registration template image size + tdim = res.tmp2{1}(1).dim; % registration template image size + odim = BB2dim(res.bb,resbb,res.tpm(1).dim,tmpres,tpmres,newres); % res.bb~TPM, resbb~dynamic, + + % mat matrices for different spaces + % - here M1 == M1t + M0 = res.image.mat; % for (interpolated) individual volume + % RD202403: modified to support output of the given voxel size vox - see also above. cleanup later. + %if isfield( job.extopts , 'bb' ) && numel( job.extopts.bb ) == 1 && job.extopts.bb == 1 + % M1 = tpmM; + %else + if isscalar(job.extopts.bb) && job.extopts.bb == 0 % TPM case + M1 = tpmM; + else + imat = spm_imatrix(tmpM); imat(1:3) = imat(1:3) + imat(7:9).*(tdim - (newres/tmpres*odim))/2; imat(7:9) = imat(7:9) * newres/tmpres; M1 = spm_matrix(imat); + end + + % estimate the inverse transformation + yid = spm_diffeo('invdef', Yy , sdim, inv(tpmM\M1), M1\res.Affine*M0); + try + yi = spm_diffeo('invdef', yid, idim, inv(M1\res.Affine*M0), eye(4)); clear yid; + yi2 = spm_diffeo('invdef', yi , odim, eye(4), eye(4)); + catch + % RD202502: strange error with Rusak2021_sub-ADNI003S5209_simGMatrophy0.00mm.nii so we repalce bad voxels by neighbors% RD202502: strange error with Rusak2021_sub-ADNI003S5209_simGMatrophy0.00mm.nii so we repalce bad voxels by neighbors + yidbad = isinf(yid) | yid<0 | yid>200; yid(yidbad) = nan; clear yidbad; + yi = spm_diffeo('invdef', yid, idim, inv(M1\res.Affine*M0), eye(4)); clear yid; + yibad = isinf(yi) | yi<0 | yi>max(size(yi)); yi(yibad) = nan; clear clear yidbad; + yi2 = spm_diffeo('invdef', yi , odim, eye(4), eye(4)); + end + w = max( eps , abs(spm_diffeo('def2det', yi2 ) ) ); + % Adaption to avoid boundary effects by correcting the voxel close + % to the image boundary that are effected by the interpolation of + % the field. + msk = cat_vol_morph( isnan( yi2(:,:,:,1)) ,'d',3); w( msk(:) ) = NaN; + wa = cat_vol_approx(w,'nn',1,4); bg = cat_stat_nanmean( wa(msk(:)) ); + msk = cat_vol_smooth3X(msk,2); w( isnan(w) ) = wa( isnan(w) ); + w = wa .* msk + (1-msk) .* w; clear msk wa; + % use half registration resolution to define the amout of smoothing to reduce registration artefacts + msk = true(size(w)); msk(3:end-2,3:end-2,3:end-2) = false; + fs = newres / 2; w(msk) = bg; w = log(w); spm_smooth(w,w,fs); w = exp(w); % spm smoothing boudary problem where values outside are 0 + + % affine and rigid parameters + %[M3,R] = spm_get_closest_affine( affind(rgrid( idim ) ,M0) , affind(Yy,dres.Yymat), single(Ycls{1})/255); clear M3; + if numel(Ycls) > 2 + [M3,R] = spm_get_closest_affine( affind(rgrid( idim ) ,M0) , affind(Yy,dres.Yymat) , single(Ycls{1} + Ycls{2} + Ycls{3})/255); clear M3; + else + [M3,R] = spm_get_closest_affine( affind(rgrid( idim ) ,M0) , affind(Yy,dres.Yymat) , single(Ycls{1} + Ycls{2})/255); clear M3; + end + Mrigid = M0\inv(R)*M1; % transformation from subject to registration space + Maffine = M0\inv(res.Affine)*M1; % individual to registration space + mat0r = R\M1; % mat0 for rigid ouput + mat0a = res.Affine\M1; % mat0 for affine output + M2 = inv(Maffine); % warped - if we use the US than we may have to use rigid + + % final structure + if isfield(res,'imagesc'); trans.native.Vo = res.imagec(1); else, trans.native.Vo = res.image0(1); end + trans.native.Vi = res.image(1); + trans.affine = struct('odim',odim,'mat',M1,'mat0',mat0a,'M',Maffine,'A',res.Affine); % structure for cat_io_writenii + trans.rigid = struct('odim',odim,'mat',M1,'mat0',mat0r,'M',Mrigid ,'R',R); % structure for cat_io_writenii + %trans.warped = struct('y',yid, 'odim',odim,'M0',M0,'M1',M1,'M2',M2,'dartel',res.do_dartel); % simple version with push artefacts for tests + trans.warped = struct('y',yi ,'yi',yi2,'w',w,'odim',odim,'M0',M0,'M1',M1,'M2',M2,'dartel',res.do_dartel,'fs',fs); % nicer version with interpolation + if job.output.jacobian.warped + trans.jc = struct('odim',odim,'dt2',w); + end + + % export for tests + if export || debug + write_nii(Ycls,job,trans,sprintf('US_tr%3.1f_or%3.1f',tmpres,job.extopts.vox(1))); + elseif numel( job.extopts.vox ) > 1 + % full export + job2 = job; + job2.extopts.mrifolder = fullfile('mri',reg(regstri).testfolder); + cat_main_write(Ym,Ymi,Ycls,Yp0,Yl1,job2,res,trans); + end + end + end + end + + % back to old directory + if exist('olddir','var'), cd(olddir); end +end +%======================================================================= +function [trans,reg] = run_Shooting(Ycls,Ylesion,job,reg,res,trans,Maffinerigid,regstri,voxi) +% ------------------------------------------------------------------------ +% Shooting +% ------------------------------------------------------------------------ + + % if there is a breakpoint in this file set debug=1 and do not clear temporary variables + dbs = dbstatus; debug = 0; for dbsi=1:numel(dbs), if strcmp(dbs(dbsi).name,mfilename); debug = 1; break; end; end + + +% ####################### THIS NEED FURTHER CLEANUP ####################### + + % helping functions + %BB2dim = @(oldbb,newbb,olddims,oldres,newres) floor( ( olddims * oldres - sum( ( abs(oldbb) - abs(newbb) ) ) )/newres/2)*2 + 1; + getmm = @(bb) [[bb(1,1) bb(2,1) bb(1,1) bb(2,1) bb(1,1) bb(2,1) bb(1,1) bb(2,1); + bb(1,2) bb(1,2) bb(2,2) bb(2,2) bb(1,2) bb(1,2) bb(2,2) bb(2,2); + bb(1,3) bb(1,3) bb(1,3) bb(1,3) bb(2,3) bb(2,3) bb(2,3) bb(2,3)]; + ones(1,8)]; % definition from the SPM registration function + + if isempty( Ylesion ), clear Ylesion; end + + n1 = reg(regstri).clsn; + Vtmp = spm_vol(job.extopts.templates{1}); + tmpM = Vtmp(1).mat; + idim = res.image(1).dim(1:3); + odim = trans.rigid.odim; + vx_vol = sqrt(sum(res.image(1).mat(1:3,1:3).^2)); + + % resolutions: + tmpres = abs(tmpM(1)); % template resolution + regres = reg(regstri).opt.rres; if isinf(regres), regres = tmpres; end % registration resolution + newres = job.extopts.vox(voxi); if isinf(newres), newres = tmpres; end % output resolution + + M0 = res.image.mat; + M1 = trans.rigid.mat; + M1t = tmpM; + imat = spm_imatrix(tmpM); imat(7:9) = imat(7:9) * regres/tmpres; M1r = spm_matrix(imat); + + + + % multiresolution parameter + % this part may require further work + tempres2 = reg(regstri).opt.resfac * regres; % registration resolution + if numel(reg(regstri).opt.ll3th)~=numel(tempres2), reg(regstri).opt.ll3th = repmat(reg(regstri).opt.ll3th(1),numel(tempres2)); end + + + tmpbb = spm_get_bbox( res.tmp2{1}(1) ); % Template + if tmpbb(1)10^-3 || regres~=tmpres + if job.extopts.regstr(regstri)>0 && job.extopts.regstr(regstri)<=1 + stime = cat_io_cmd(sprintf('Optimized Shooting registration with %0.2f:%0.2f:%0.2f mm (regstr=%0.2f)',... + tempres2(1),diff(tempres2(1:2)),tempres2(end),job.extopts.regstr(regstri))); + else + stime = cat_io_cmd(sprintf('Optimized Shooting registration with %0.2f:%0.2f:%0.2f mm',... + tempres2(1),diff(tempres2(1:2)),tempres2(end))); + end + else + stime = cat_io_cmd(sprintf('Default Shooting registration with %0.2f mm',reg(regstri).opt.rres)); + end + fprintf('\n Template: ""%s""\n',job.extopts.templates{1}) + end + + +% shooting parameter ... again ???? +% ######################################################################### + sd = spm_shoot_defaults; % load shooting defaults + if reg(regstri).fast, reg(regstri).opt.nits = min(reg(regstri).opt.nits,5*reg(regstri).fast); end % at least 5 iterations to use each tempalte + if (job.extopts.regstr(regstri)>0 || regres~=tmpres) && job.extopts.regstr(regstri)~=4 + %% need finer schedule for coarse to fine for ll3 adaptive threshold + nits = reg(regstri).opt.nits; % default was 24 + onits = 24; % use John's interation number for the form and just interpolate the curve to modify different interation numbers + lam = 0.25; % Decay of coarse to fine schedule (default 0.5) ... update default to 0.25 to have smoother changes + inter = 32; % Scaling of parameters at first iteration + sd.sched = (inter-1) * exp(-lam*((1:(onits))-1) )+1; %sd.sched = sd.sched/sd.sched(end); + sd.sched = ((sd.sched - min(sd.sched)) / (max(sd.sched) - min(sd.sched)) * (inter-1) + 1); + sd.sched = interp1(sd.sched,1:(numel(sd.sched)-1)/(nits-1):numel(sd.sched)); + maxoil = 8; % Maximum number of time steps for integration + sd.eul_its = round((0:(nits-1))*(maxoil-0.5001)/(nits-1)+1); % Start with fewer steps + nits = numel(sd.sched)-1; % Shooting iterations + tmpl_no = floor(((1:nits)-1)/(nits-1)*(numel(res.tmp2)-0.51))+1; % Sort out which template for each iteration (default = round with more hr-iter) + else + nits = reg(regstri).opt.nits; + tmpl_no = round(((1:nits)-1)/(nits-1)*(numel(res.tmp2)-0.51))+1; + end +% ######################################################################### + + + + + + %% The actual work + % --------------------------------------------------------------------- + it = 1; reg(regstri).dtc = zeros(1,5); ll = zeros(1,2); + while it<=nits + itime = clock; + + if it==1 || (tmpl_no(it)~=tmpl_no(it-1)) + ti = tmpl_no(it); + if debug && it>1, fo=f{1}; end %#ok % just for debugging + + + % load rigide/affine data + f = cell(1,n1+1); f{n1+1} = ones(rdims(ti,1:3),'single'); + for k1=1:n1 + Yclsk1 = single(Ycls{k1}); + f{k1} = zeros(rdims(ti,1:3),'single'); + spm_smooth(Yclsk1,Yclsk1,rred(tmpl_no(it)) * 0.1*max(0,size(rred,1) - tmpl_no(it))); % RD202101: Advanced Shooting: smoothing for resolution reduction and template level + for i=1:rdims(ti,3) + f{k1}(:,:,i) = single(spm_slice_vol(Yclsk1,Mrregs{ti}*spm_matrix([0 0 i]),rdims(ti,1:2),[1,NaN])/255); + end + msk = ~isfinite(f{k1}); + f{k1}(msk) = 0; + clear msk; + end + if debug, fx = f{1}; end %#ok % just for debugging + + + % template + g = cell(1,n1+1); g{n1+1} = ones(rdims(ti,1:3),'single'); + for k1=1:n1 + g{k1} = zeros(rdims(ti,1:3),'single'); + tpm2k1 = res.tmp2{ti}(k1).private.dat(:,:,:,k1); + spm_smooth(tpm2k1,tpm2k1,repmat( tempres2(tmpl_no(it))/tmpres ,1,3)); % RD202101: Advanced Shooting: smoothing for resolution reduction but not template level + for i=1:rdims(ti,3) + g{k1}(:,:,i) = single(spm_slice_vol(tpm2k1,Mads{ti}*spm_matrix([0 0 i]),rdims(ti,1:2),[1,NaN])); + end + g{k1}(isnan(g{k1}(:))) = min(g{k1}(:)); % remove boundary interpolation artefact + g{n1+1} = g{n1+1} - g{k1}; + if debug && k1==1, gx = g{1}; end %#ok % just for debugging + g{k1} = spm_bsplinc(log(g{k1}), sd.bs_args); + end + g{n1+1} = spm_bsplinc(log(max(g{n1+1},eps)), sd.bs_args); + + + +% ------------------------------------------------------------------------- +% RD202101: Advanced Shooting +% Seperate large ventricle +% ------------------------------------------------------------------------ +% In hydrocephalus with extremely large ventricles the outer part of the +% ventriclar CSF aspire torwards the cranial CSF causing severe problems. +% Hence, we try to seperate the ventricle as a seperate additional layer +% in segmentation and template. +% This is only necessary for very large ventricle and the errors we made +% are less important then the problems in the original setting. +% However, a better ventricular segmentation should allow improvements. +% ------------------------------------------------------------------------ + hydro = 0; + if job.extopts.regstr(regstri)~=4 + if n1>2 + % use the CSF class directly + Yven = cat_vol_morph( cat_vol_morph( cat_vol_morph(f{3},'l',[10 0.1]), 'o' ,1) ,'d'); + else + %% if CSF==BG than find the large central CSF region within the brain + Ygwm = cat_vol_localstat( single(f{2} + f{1}) , (f{2} + f{1} + f{3}/2)>0, 1 ,1); % smoothing only of tissue probs + + % the brainmask requires large close in case of open ventricles that are connected to extra-ventricluar CSF + Yb = cat_vol_morph(Ygwm,'ldc',12/tempres2(ti)); + Ybd = cat_vol_smooth3X(Yb,6/tempres2(ti)); Ybd = Ybd/max(Ybd(:)); % get some distance to the skull + + % seperate the biggest part + Yven = (Yb - Ygwm)>0.9 & Ybd>0.9; + Yven = cat_vol_morph(cat_vol_morph( cat_vol_morph( Yven ,'ldo',3,tempres2(ti)) ,'d',max(1,1/rred(ti))),'l'); + Yven = min(1,cat_vol_smooth3X(Yven,4/tempres2(ti))*1.5); + %Yven = Yven ./ max(Yven(:)); + end + + if sum(Yven(:))/sum(Yb(:))>0.2 % ############# large ventricle warning definition ################# + hydro = 1; + if job.extopts.verb && ti==1 + %cat_io_cprintf([0 0 1], ' == Very large ventricles detected. Use seperate class and adapt schedule. == \n'); + cat_io_addwarning([mfilename ':Hydrocephalus'],sprintf( ... + 'Very large ventricles detected (%0.2f%%%%%%%% of TIV). \\\\nUse seperate class and adapt schedule.', ... + 100 * sum(Yven(:))/sum(Yb(:)>.1)),1,[0 1]); + end + + +% ------------------------------------------------------------------------ +% RD202101: Advanced Shooting: +% ------------------------------------------------------------------------ +% Update schedule to have again stronger deformations to improve the +% addaption to the new template and resolution. +% This seems to help especially in worse cases with large ventricles. +% ------------------------------------------------------------------------ + if it > 1 + % at least the number of iterations for this template but maximal 4 + fac = min( (max(tmpl_no) - tmpl_no(it) + 2) * 2, sum(tmpl_no==tmpl_no(it)) ); + fac = log(fac) / log(sd.sched(it)); + sd.sched = max( sd.sched , sd.sched.^fac ); + end + + % seperate template ventricle + % no labopen because the ventricle is too small here + Ygven = exp(g{3}) .* cat_vol_smooth3X(Yven,2/tempres2(ti)); + Ygven = cat_vol_morph( cat_vol_morph( cat_vol_morph(Ygven>0.5,'l') ,'d',max(1,1/rred(ti))),'l'); + Ygven = exp(g{3}) .* cat_vol_smooth3X(Ygven,4/tempres2(ti)); + + % seperate individual ventricle + f{n1+2} = ones(rdims(ti,1:3),'single'); + f{n1+1} = max(eps,Yven - Ygwm); + + g{n1+2} = double(log(max(eps,exp(g{3}) - Ygven))); % temove ventricle from background / CSF + g{n1+1} = double(log(max(eps,Ygven))); % own class + end + if ~debug, clear Yven Ygven Ygwm Yb Ybd; end + end + + + % set lesions area by template tissues to avoid transformation + if exist('Ylesion','var') && sum(Ylesion(:))>0 + if job.extopts.verb && ti==1 + cat_io_cprintf([0 0 1], ' == Use lesion masking to limit deformations to non-masked areas == \n'); + end + + Yclsk1 = single(Ylesion); + if reg(regstri).opt.resfac(ti)>1, spm_smooth(Yclsk1,Yclsk1,repmat((reg(regstri).opt.resfac(ti)-1) * 2,1,3)); end + ls = zeros(rdims(ti,1:3),'single'); + for i=1:rdims(ti,3) + ls(:,:,i) = single(spm_slice_vol(Yclsk1,Mrregs{ti}*spm_matrix([0 0 i]),rdims(ti,1:2),[1,NaN])); + end + ls(isnan(ls(:))) = min(ls(:)); + for k1=1:n1 + tpm2k1 = res.tmp2{ti}(k1).private.dat(:,:,:,k1); + t = zeros(rdims(ti,1:3),'single'); + for i=1:rdims(ti,3) + t(:,:,i) = single(spm_slice_vol(tpm2k1,Mads{ti}*spm_matrix([0 0 i]),rdims(ti,1:2),[1,NaN])); + end + t(isnan(t(:))) = min(t(:)); + f{k1} = f{k1} .* (1-ls) + t .* ls; + end + end + + + % set background (and + for k1=1:numel(f)-1 + f{end} = f{end} - f{k1}; + msk = ~isfinite(f{k1}); + f{end}(msk) = 0.00001; + end + + + % loading segmentation and creating of images vs. updating these maps + ll = zeros(1,2); + if it==1 + % create shooting maps + y = affind( squeeze( reshape( affind( spm_diffeo('Exp',zeros([rdims(ti,:),3],'single'),[0 1]), ... + mat0reg), [rdims(ti,:),1,3] ) ) , inv(mat0reg)); clear def; %#ok % deformation field + u = zeros([rdims(ti,:) 3],'single'); %#ok % flow field + dt = ones(rdims(ti,:),'single'); %#ok % jacobian + elseif any(rdims(ti,:)~=rdims(ti-1,:)) + % updates only for changed resolutions + + if 0 + %% just test code to verify the mapping/interpolation between resolution levels + fx = cell(0); + for k1=1:numel(fo) + for i=1:rdims(ti,3) + fx{k1}(:,:,i) = single(spm_slice_vol(fo{k1},Mys{ti}*spm_matrix([0 0 i]),... + rdims(ti,1:2),[1,NaN])) / Mys{ti}(1); + end + end + fx(~isfinite(fx))=eps; + ds('d2sm','',1,f{1},(fx{1} - f{1})/2+0.5,30), cat_stat_nansum(abs(fx{1}(:) - f{1}(:))) + end + + % size update u - flow field + uo = u; + u = zeros([rdims(ti,:) 3],'single'); + for k1=1:3 + for i=1:rdims(ti,3) + u(:,:,i,k1) = single(spm_slice_vol(uo(:,:,:,k1),Mys{ti}*spm_matrix([0 0 i]),... + rdims(ti,1:2),[1,NaN])) / Mys{ti}(1); % (tempres(ti) / tempres(ti-1))^2; % adapt for res + end + end + u(~isfinite(u))=eps; + if ~debug, clear uo; end + + % update the deformation y and the determinatent by re-estimation + % rather than interpolation of low resolution data + [y,J] = spm_shoot3d(u,prm,int_args); + dt = spm_diffeo('det',J); clear J %#ok + + end + end + + + + % More regularisation in the early iterations, as well as a less accurate approximation in the integration. + % No, similar regularisation works in our case better and avoid to trap into local maxima. + vxreg = repmat(reg(regstri).opt.vxreg,1,3); % repmat(tempres(ti)^3,1,3) + prm = [vxreg, sd.rparam * sd.sched(it) * prod(vxreg)]; + int_args = [sd.eul_its(it), sd.cyc_its]; + + % Gauss-Newton iteration to re-estimate deformations for this subject + if job.extopts.verb + if reg(regstri).opt.stepsize<=10^-3 + cat_io_cprintf(sprintf('g%d',5+2*(it==1 || (tmpl_no(it)~=tmpl_no(it-1)))),sprintf('% 5d |',it)); + else + cat_io_cprintf(sprintf('g%d',5+2*(it==1 || (tmpl_no(it)~=tmpl_no(it-1)))),sprintf('% 5d | %0.2f |',it,tempres2(ti))); + end + end + + llo=ll; + + [txt,u,ll(1),ll(2)] = evalc('spm_shoot_update(g,f,u,y,dt,prm,sd.bs_args,sd.scale)'); + [y,J] = spm_shoot3d(u,prm,int_args); + dt = spm_diffeo('det',J); clear J + extdt = max([dt(:)', 1/max(eps,dt(isfinite(dt(:))))]); + if job.extopts.verb + if job.extopts.expertgui>1 + cat_io_cprintf(sprintf('g%d',5+2*(it==1 || (tmpl_no(it)~=tmpl_no(it-1)))),sprintf('%7.4f%8.4f%8.4f | %8.4f | %3.1f', ... + ll(1)/numel(u), ll(2)/numel(u), (ll(1)+ll(2))/numel(u), sd.sched(it), log10(extdt) ) ); + else + cat_io_cprintf(sprintf('g%d',5+2*(it==1 || (tmpl_no(it)~=tmpl_no(it-1)))),sprintf('%7.4f%8.4f%8.4f | %8.4f ', ... + ll(1)/numel(u), ll(2)/numel(u), (ll(1)+ll(2))/numel(u), sd.sched(it) ) ); + end + end + + wit = 0; + if job.extopts.regstr(regstri)~=4 && ( extdt>20 || any(~isfinite(dt(:))) ) + % --------------------------------------------------------------------- + % RD202101: Advanced Shooting + % Correction of local hot spots by smoothing + % --------------------------------------------------------------------- + % In some cases but in particular hydrocephalus the deformation runs + % localy into some minima and get suck at some anatomical features + % and the determinant increase stronly, pointing to problematic areas. + % However, a very high/low determinat will also occure as wanted in + % in the ventricular regions. + % The idear is now to detect such regions and filter them lightly. + % Alhough this will result in smoother deformations and lower overlap + % it will at least support that we become a result and do not run + % into a servere determinate error (with inf or nan) + % It is also better to have a smoother deformation that does not fit + % than strong local outliers. + % --------------------------------------------------------------------- + + vr = 3/tempres2(ti); + mxu = dt./cat_vol_smooth3X(dt,vr) > 1.5; % we can use local increase of the determinate to detect local outlier + mxu = cat_vol_smooth3X(mxu,2*vr); % add some neighborhood + for i=1:3, u(:,:,:,i) = cat_vol_laplace3R(u(:,:,:,i)/10,mxu>0.01, 0.1)*10; end % filtering of the deformation + for i=1:3, ux = u(:,:,:,i); uxs = cat_vol_smooth3X(ux,max(0.2,min(2,sd.sched(it)/8))); u(:,:,:,i) = uxs.*mxu + ux.*(1-mxu); end % filtering of the deformation + + % re-estimate the determinat + [y,J] = spm_shoot3d(u,prm,int_args); + dt = spm_diffeo('det',J); clear J + + extdt = max([dt(:)', 1/max(eps,dt(isfinite(dt(:))))]); + if job.extopts.verb && job.extopts.expertgui>1, fprintf(' > %0.1f', log10(extdt) ); end + + dtl = 60; + while ( any(~isfinite(dt(:))) && wit<20 ) || ... % values that we have to filter (whatever it takes) + ( extdt>dtl && wit<4 ) % regions that we should fitler + + % creating a filter mask + mxu = dt./cat_vol_smooth3X(dt,1*vr) > 1.5; % we can use local increase of the determinate to detect local outlier + mxu = cat_vol_smooth3X(mxu,2*vr) > 0.01; % add some neighborhood + mxu2 = dt>(dtl*2) | dt<1/(dtl*2); % critical regions with high determinant + for i=1:3, mxu2 = mxu2 + abs(cat_vol_div((u(:,:,:,1)))); end % local divergence in u is also a good indicator + % for i=1:3, mxu2 = mxu2 + ( cat_vol_div(u(:,:,:,1))) + ( cat_vol_div(-u(:,:,:,1))); end % local divergence in u is also a good indicator + mxu = ( mxu | mxu2>(1 - exp(g{3})) ) & exp(g{3})<0.5; % prefare filtering of regions out of the ventricles were we expect strong defs + mxu = mxu | ~isfinite(dt) | isnan(dt)| dt>1000 | dt<1/1000; % regions we have to filter anyway + % mxu = cat_vol_smooth3X(mxu,4) > 0.1; % add some neighborhood + + % filtering of the deformation + for i=1:3 + if wit>0, u(:,:,:,i) = cat_vol_smooth3X(u(:,:,:,i),1); end % global filtering in the worst-case + u(:,:,:,i) = cat_vol_laplace3R(u(:,:,:,i)/10,mxu , 0.02)*10; % local filtering + end + + % parameter updates + sd.sched = sd.sched.^1.1; % + min(0.3,0.4*(1-it/nits))); % 1.2 + prm = [vxreg, sd.rparam * sd.sched(it+1) * prod(vxreg)]; + + % re-estimate the determinat + [y,J] = spm_shoot3d(u,prm,int_args); + dt = spm_diffeo('det',J); clear J + + wit = wit + 1; + extdt = max([dt(:)', 1/max(eps,dt(isfinite(dt(:))))]); + if job.extopts.verb && job.extopts.expertgui>1, fprintf(' > %0.1f', log10(extdt) ); end + end + end + if job.extopts.verb, fprintf('\n'); end + + + % save iteration parameter for later analysis + if it==1 || (tmpl_no(it)~=tmpl_no(it-1)) + reg(regstri).ll(ti,1:4) = [ll(1)/numel(u) ll(2)/numel(u) (ll(1)+ll(2))/numel(u) ll(2)]; + dtx = dt; + dtx(dtx>eps & dtx<1) = 1./dtx(dtx>eps & dtx<1); + reg(regstri).dtc(ti) = mean(abs(dtx(:)-1)); + reg(regstri).rmsdtc(ti) = mean((dtx(:)-1).^2).^0.5; + dtg = cat_vol_grad(single(dtx)); + reg(regstri).rmsgdt(ti) = mean((dtg(:)).^2).^0.5; + clear dtx; + clear dtg; + end + + % default Shooting error detection + if any(~isfinite(dt(:)) | dt(:)>100 | dt(:)<1/100) + cat_io_cprintf('err',sprintf('Problem with Shooting (dets: %g .. %g)\n', min(dt(:)), max(dt(:)))); %it=nits; + end + + % avoid unneccessary iteration + if job.extopts.regstr(regstri)>0 && job.extopts.regstr(regstri)~=4 && wit==0 && ~hydro && ll(1)/numel(u)<0.075 && ... + ( ti>1 || (ti==1 && ll(1)/numel(u)<1 && ll(1)/max(eps,llo(1))<1 && ll(1)/max(eps,llo(1))>(1-0.01) )) && ... + ( ll(1)/numel(u)<1 && ll(1)/max(eps,llo(1))<1 && ll(1)/max(eps,llo(1))>(1-reg(regstri).opt.ll1th) ) && tmpl_no(it)>1 + it = max(it+1,find([tmpl_no,nits]>tmpl_no(it),1,'first')); + reg(regstri).ll(ti,1:4) = [ll(1)/numel(dt) ll(2)/numel(dt) (ll(1)+ll(2))/numel(dt) ll(2)]; + reg(regstri).dtc(ti) = mean(abs(dt(:)-1)); + else + it = it+1; + end + end + + % save some parameter for later .. + dtx = dt; + dtx(dtx>eps & dtx<1) = 1./dtx(dtx>eps & dtx<1); + reg(regstri).rmsdt = mean((dtx(:)-1).^2).^0.5; + reg(regstri).dt = mean(abs(dtx(:)-1)); + reg(regstri).dtc(ti+1) = mean(abs(dtx(:)-1)); + reg(regstri).rmsdtc(ti+1) = mean((dtx(:)-1).^2).^0.5; + dtg = cat_vol_grad(single(dtx)); + reg(regstri).rmsgdt(ti+1) = mean((dtg(:)).^2).^0.5; + clear dtg; + reg(regstri).ll(ti+1,1:4) = [ll(1)/numel(dt) ll(2)/numel(dt) (ll(1)+ll(2))/numel(dt) ll(2)]; + clear dt1; + + % preparte output + if job.extopts.verb + if job.extopts.regstr(regstri)==0 + cat_io_cmd(sprintf('Dartel registration with %0.2f mm takes',tempres(1))); + elseif reg(regstri).opt.stepsize>10^-3 + cat_io_cmd(sprintf('Shooting registration with %0.2f:%0.2f:%0.2f mm takes',tempres2(1),diff(tempres2(1:2)),tempres2(end))); + else + cat_io_cmd(sprintf('Shooting registration with %0.2f mm takes',tempres2(1))); + end + itime = cat_io_cmd(sprintf(' Prepare output'),'','',job.extopts.verb,stime); + end + + + + %% Modulation using spm_diffeo and push introduces aliasing artefacts, + % thus we use the def2det function of the inverted deformations to obtain the old and + % in my view a more appropriate jacobian determinant + % The 2nd reason to use the old modulation is compatibility with cat_vol_defs.m + + % RD20240924: first only for the jacobian without affine parameters / TIV as covariate + yi = spm_diffeo('invdef', y , idim, Maffinerigid * inv(M1r\M1), inv(M1r\M1)); + yi2 = spm_diffeo('invdef', yi , odim, eye(4), eye(4) / Maffinerigid); + w2 = max( eps , abs(spm_diffeo('def2det', yi2 ) ) ); + + % now for the final transformations + yi = spm_diffeo('invdef', y , idim, Maffinerigid * inv(M1r\M1), inv(M1r\M1)); %#ok + yi2 = spm_diffeo('invdef', yi , odim, eye(4), eye(4)); + % RD20240924: This would be the real jacobian that considers the also the affine registration + % in the ""correct"" but unexpected way and that would finally need TIV as covariate. + w = max( eps , abs(spm_diffeo('def2det', yi2 ) ) ); + + % avoid boundary effects that are not good for the global measurements + % use half registration resolution to define the amout of smoothing to reduce registration artefacts + if 1 + %% + vxd = M1(1)./M1r(1); + msk = w<=eps; w( msk(:) ) = NaN; + wa = cat_vol_approx(w,'rec'); bg = cat_stat_nanmean( wa(msk(:)) ); + msk = cat_vol_smooth3X(msk,1/vxd); w( isnan(w) ) = wa( isnan(w) ); + w = wa .* msk + (1-msk) .* w; clear msk wa; + fs = newres / 2; w = w - bg; spm_smooth(w,w,fs); w = bg + w; % spm smoothing boudary problem + + msk = w2<=eps; w2( msk(:) ) = NaN; + wa = cat_vol_approx(w2,'rec'); bg = cat_stat_nanmean( wa(msk(:)) ); + msk = cat_vol_smooth3X(msk,1/vxd); w2( isnan(w2) ) = wa( isnan(w2) ); + w2 = wa .* msk + (1-msk) .* w2; clear msk wa; + fs = newres / 2; w2 = w2 - bg; spm_smooth(w2,w2,fs); w2 = bg + w2; % spm smoothing boudary problem + + end + + % yi2 for fast high quality output + trans.warped = struct('y',yi,'yi',yi2,'w',w,'odim',odim,'M0',M0,'M1',M1,'M2',inv(Maffinerigid),'dartel',2,'fs',fs); + + if job.output.jacobian.warped + % RD202101: not sure if the transfomration is correct ... + uo = zeros([odim 3],'single'); + for k1=1:3 + for i=1:odim(1) + uo(:,:,i,k1) = single(spm_slice_vol(u(:,:,:,k1),(M1r\M1t)*spm_matrix([0 0 i]),odim(1:2),[1,NaN])); + end + end + uo(~isfinite(uo)) = eps; + trans.jc = struct('u',uo,'odim',odim,'dt2',w2); + end + + + if job.extopts.verb + cat_io_cmd('','','',job.extopts.verb,itime); + cat_io_cmd(' ','',''); cat_io_cmd('','','',job.extopts.verb,stime); + end + + + if debug + % just for fast internal tests + write_nii(Ycls,job,trans,'debug'); + end +end +%======================================================================= +function [trans,reg] = run_Dartel(Ycls,Ylesion,job,reg,res,trans,Mad,Maffinerigid,TAR,regstri,voxi) +% ------------------------------------------------------------------------ +% Dartel spatial normalization to given template +% ------------------------------------------------------------------------ + + if isempty( Ylesion ), clear Ylesion; end + + Vtmp = spm_vol(job.extopts.templates{1}); + tmpM = Vtmp(1).mat; + + M0 = res.image.mat; + M1 = trans.rigid.mat; + + idim = res.image(1).dim(1:3); + odim = trans.rigid.odim; + rdim = trans.rigid.odim; + + % resolutions: + tmpres = abs(tmpM(1)); % template resolution + regres = reg(regstri).opt.rres; if isinf(regres), regres = tmpres; end % registration resolution + newres = job.extopts.vox(voxi); if isinf(newres), newres = tmpres; end % output resolution + + stime = cat_io_cmd(sprintf('Dartel registration with %0.2f mm on a %0.2f mm Template',newres,tmpres)); + fprintf('\n Template: ""%s""\n',job.extopts.templates{1}) + + reg(regstri).opt.rres = newres; % + + % dartel parameter 1 + rform = 0; % regularization form: 0 - Linear Elastic Energy + code = 2; % multinomial + lmreg = 0.01; % LM regularization + cyc = 3; % cycles + its = 3; % relaxation iterations (inner iteration) + n1 = reg(regstri).clsn; % use GM/WM for dartel + if reg(regstri).fast, its = min(3,max(1,min(its,reg(regstri).fast))); end % subiteration + + % rparam .. regularization parameters: mu, lambda, id + % K .. time steps + param = struct('K',{0 0 1 2 4 6},'its',its, ... + 'rparam',{[4 2 1e-6],[2 1 1e-6],[1 0.5 1e-6],[0.5 0.25 1e-6],[0.25 0.125 1e-6],[0.25 0.125 1e-6]}); + + % initialize varibles and load anatomical image in registration space + f = zeros([rdim(1:3) 2],'single'); + g = zeros([rdim(1:3) 2],'single'); + u = zeros([rdim(1:3) 3],'single'); + for k1=1:n1 + for i=1:rdim(3) + f(:,:,i,k1) = single(spm_slice_vol(single(Ycls{k1}),Maffinerigid*spm_matrix([0 0 i]),rdim(1:2),[1,NaN])/255); + end + end + + if exist('Ylesion','var') && sum(Ylesion(:))>0 + Ylesion = single(Ylesion); + ls = zeros(rdim(1:3),'single'); + for i=1:rdim(3) + ls(:,:,i) = single(spm_slice_vol(single(Ylesion),Maffinerigid*spm_matrix([0 0 i]),rdim(1:2),[1,NaN])); + end + end + + % iterative processing + % --------------------------------------------------------------------- + it0 = 0; % main iteration number for output + reg(regstri).dtc = zeros(1,6); + for it = 1:numel(param) + prm = [rform, param(it).rparam, lmreg, cyc, its, param(it).K, code]; + % load new template for this iteration + for k1=1:n1 + for i=1:rdim(3) + g(:,:,i,k1) = single(spm_slice_vol(res.tmp2{it}(k1),Mad*spm_matrix([0 0 i]),rdim(1:2),[1,NaN])); + end + + if exist('Ylesion','var') && sum(Ylesion(:))>0 + f(:,:,:,k1) = f(:,:,:,k1) .* (1-ls) + g(:,:,:,k1) .* ls; + end + end + + for j = 1:param(it).its + it0 = it0 + 1; + [u,ll] = dartel3(u,f,g,prm); + reg(regstri).lld(it0,:) = ll ./ [prod(rdim) prod(rdim) newres^3]; + reg(regstri).lldf(it0,:) = [reg(regstri).lld(it0,1) / prod(regres),ll(1),ll(2),ll(1)+ll(2),ll(3)]; + cat_io_cprintf(sprintf('g%d',5+2*(mod(it0,its)==1)),... + sprintf('% 5d | %6.4f | %8.0f %8.0f %8.0f %8.3f \n',it0,reg(regstri).lldf(it0,:))); + + if it0==1 % simplified! use values after first iteration rather than before + [y0, dt] = spm_dartel_integrate(reshape(u,[odim(1:3) 1 3]),[1 0], 6); clear y0; + reg(regstri).ll(1,:) = reg(regstri).lldf(it0,:); + dtx = dt; + dtx(dtx>eps & dtx<1) = 1./dtx(dtx>eps & dtx<1); + reg(regstri).dtc(1) = mean(abs(dtx(:)-1)); + reg(regstri).rmsdtc(1) = mean((dtx(:)-1).^2).^0.5; + dtg = cat_vol_grad(single(dtx)); + reg(regstri).rmsgdt(1) = mean((dtg(:)).^2).^0.5; + clear dtg dt dtx; + end + end + + [y0, dt] = spm_dartel_integrate(reshape(u,[odim(1:3) 1 3]),[1 0], 6); clear y0; + reg(regstri).ll(it+1,:) = reg(regstri).lldf(it0,:) * numel(dt)/numel(u(:,:,:,1)); + reg(regstri).dtc(it+1) = mean(abs(dt(:)-1)); + reg(regstri).rmsdtc(it+1) = mean((dt(:)-1).^2).^0.5; + dtg = cat_vol_grad(single(dt)); + reg(regstri).rmsgdt(it+1) = mean((dtg(:)).^2).^0.5; + clear dtg; + end + reg(regstri).rmsdt = mean((dt(:)-1).^2).^0.5; + reg(regstri).dt = mean(abs(dt(:)-1)); + clear f g; + + + % jacobian + if job.output.jacobian.warped || (isfield(job.extopts,'multigreg') && job.extopts.multigreg) + if any(odim ~= idim) + uo = zeros([odim 3],'single'); + for k1=1:3 + for i=1:odim(1) + uo(:,:,i,k1) = single(spm_slice_vol(u(:,:,:,k1) ,spm_matrix([0 0 i]),odim(1:2),[1,NaN])); + end + end + uo(~isfinite(uo))=eps; %dto(~isfinite(dto))=eps; + else + uo = u; + end + if job.extopts.bb + trans.jc = struct('u',uo,'odim',idim); + end + clear uo + end + + % deformation + y0 = spm_dartel_integrate(reshape(u,[rdim(1:3) 1 3]),[0 1], 6); clear u; + prm = [3 3 3 0 0 0]; + Coef = cell(1,3); + Coef{1} = spm_bsplinc(y0(:,:,:,1),prm); + Coef{2} = spm_bsplinc(y0(:,:,:,2),prm); + Coef{3} = spm_bsplinc(y0(:,:,:,3),prm); + clear y0; + [t1,t2] = ndgrid(1:idim(1),1:idim(2),1); t3 = 1:idim(3); + Yy = zeros([idim 3],'single'); + for z=1:idim(3) + [t11,t22,t33] = defs2(Coef,z,Maffinerigid,prm,t1,t2,t3); + Yy(:,:,z,1) = t11; + Yy(:,:,z,2) = t22; + Yy(:,:,z,3) = t33; + end + clear Coef t1 t2 t3 t11 t22 t33 z + M = eye(4); + for i=1:size(Yy,3) + t1 = Yy(:,:,i,1); + t2 = Yy(:,:,i,2); + t3 = Yy(:,:,i,3); + Yy(:,:,i,1) = M(1,1)*t1 + M(1,2)*t2 + M(1,3)*t3 + M(1,4); + Yy(:,:,i,2) = M(2,1)*t1 + M(2,2)*t2 + M(2,3)*t3 + M(2,4); + Yy(:,:,i,3) = M(3,1)*t1 + M(3,2)*t2 + M(3,3)*t3 + M(3,4); + end + clear t1 t2 t3 M; + + + % Modulation using spm_diffeo and push introduces aliasing artefacts, + % thus we use the def2det function of the inverted deformations to obtain the old and + % in my view a more appropriate jacobian determinant + % The 2nd reason to use the old modulation is compatibility with cat_vol_defs.m + yi2 = spm_diffeo('invdef' , Yy, odim, M1\M1, eye(4)); + + w = max( eps , abs(spm_diffeo('def2det', yi2 ) ) ); % .* prod( sqrt(sum( M1(1:3,1:3).^2))); + % avoid boundary effects that are not good for the global measurements + w(:,:,[1 end]) = NaN; w(:,[1 end],:) = NaN; w([1 end],:,:) = NaN; + % use half registration resolution to define the amout of + % smoothing to reduce registration artefacts + fs = newres / 2; + spm_smooth(w,w,fs); + + + trans.warped = struct('y',Yy,'yi',yi2,'w',w,'odim',odim,'M0',M0,'M1',M1,'M2',M1\TAR*M0,'dartel',1,'fs',fs); + + + if job.extopts.verb<1, fprintf(sprintf('%s',repmat('\b',1,it0*47 + 2))); fprintf('\n'); end + fprintf('%s %4.0fs\n',repmat(' ',1,66),etime(clock,stime)); +end +%======================================================================= +%################################# NEED CLEANUP +function [reg,res,job] = regsetup(dreg,reg,res,job,regstri,voxi) +% Definition of the registration parameters reg of the i-th registration +% regstri. + + + tpmM = res.tpm(1).mat; + + if regstri < numel(job.extopts.regstr) && job.extopts.verb && ... + (numel(job.extopts.regstr) || numel(job.extopts.vox)) + fprintf('\n\n'); + end + + + % set dartel/shooting templates + if job.extopts.regstr(regstri)==0 + job.extopts.templates = job.extopts.darteltpms; + else + job.extopts.templates = job.extopts.shootingtpms; + end + res.tmp2 = cell(1,numel(job.extopts.templates)); + Vtmp = spm_vol(job.extopts.templates{1}); tmpM = Vtmp(1).mat; + n1 = max(min(2,numel(Vtmp)),numel(Vtmp)-1); % use GM and WM for shooting + + + % registration main parameter + lowres = 2.5; % lowest resolution .. best between 2 and 3 mm + tpmres = abs(tpmM(1)); % TPM resolution + tempres = abs(tmpM(1)); % template resolution + reg(regstri).opt.nits = dreg.nits; % registration iteration (shooting default = 24) + reg(regstri).opt.vxreg = tpmres; % regularisation parameter that original depend on the template resolution + reg(regstri).opt.rres = tempres; % final registration resolution + reg(regstri).opt.stepsize = (lowres - reg(regstri).opt.rres)/4; % stepsize of reduction + reg(regstri).opt.resfac = (lowres : -reg(regstri).opt.stepsize : reg(regstri).opt.rres) / reg(regstri).opt.rres; % reduction factor + reg(regstri).opt.ll1th = dreg.opt.ll1th; % smaller better/slower + reg(regstri).opt.ll3th = dreg.opt.ll3th; % smaller better/slower + reg(regstri).opt.regstr = job.extopts.regstr; + reg(regstri).fast = dreg.iterlim; % limit iterations per template level to test if processing work in principle + reg(regstri).clsn = dreg.clsn; + reg(regstri).fast = dreg.fast; + reg(regstri).regra = dreg.regra; + + + if job.extopts.regstr(regstri)==0 + % Dartel + res.do_dartel = 1; + reg(regstri).opt.rres = tempres; %job.extopts.vox(voxi); + elseif job.extopts.regstr(regstri)>0 && job.extopts.regstr(regstri)<=1 + % Optimized Shooting - manual limit + reg(regstri).opt.stepsize = (lowres - tempres)/4; % stepsize of reduction + reg(regstri).opt.resfac = (lowres : -reg(regstri).opt.stepsize : tempres) / tempres; % reduction factor + + reg(regstri).opt.ll1th = 0.0010 + 0.10*(1-job.extopts.regstr(regstri)); % smaller better/slower + reg(regstri).opt.ll3th = 0.0001 + 0.10*(1-job.extopts.regstr(regstri)); % smaller better/slower + elseif job.extopts.regstr(regstri)==4 + % Default Shooting + reg(regstri).opt.rres = tempres; % registration resolution depending on template resolution + reg(regstri).opt.stepsize = 0; % stepsize of reduction + reg(regstri).opt.nits = 24; % Dartel default iteration number + reg(regstri).opt.resfac = ones(1,5); % reduction factor + reg(regstri).opt.ll1th = 0; % smaller better/slower + reg(regstri).opt.ll3th = 0; % smaller better/slower + elseif job.extopts.regstr(regstri)==5 % this may not work because you finally need another interpolation! + % based on vox + tempres = job.extopts.vox(voxi); % template resolution + reg(regstri).opt.rres = job.extopts.vox(voxi); % registration resolution depending on template resolution + reg(regstri).opt.stepsize = (tempres*2 - tempres)/4; % stepsize of reduction + reg(regstri).opt.resfac = (tempres*2 : -reg(regstri).opt.stepsize : job.extopts.vox(voxi)) / job.extopts.vox(voxi); % reduction factor + elseif job.extopts.regstr(regstri)==2 + % Optimized Shooting - manual limit + reg(regstri).opt.stepsize = (lowres - tempres)/4; % stepsize of reduction + reg(regstri).opt.resfac = (lowres : -reg(regstri).opt.stepsize : tempres) / tempres; % reduction factor + elseif job.extopts.regstr(regstri)==3 + % Optimized Shooting - dynamic limit (depending on template resolution) + reg(regstri).opt.stepsize = (tempres/2 - tempres)/4; % stepsize of reduction + reg(regstri).opt.resfac = (tempres/2 : -reg(regstri).opt.stepsize : tempres) / tempres; % reduction factor + else + % further test cases + highres = 1.0; % 0.5 + switch job.extopts.regstr(regstri) + % ----------------------------------------------------------------- + % absolute fixed resolutions and reduction + % ----------------------------------------------------------------- + % This allows identical smooth iterations for all levels and some + % kind of frequency/deformation limit. + % The resolution levels are 1.0:0.5:3.0 mm, but can be changed to + % to 0.5:0.5:2.5 mm. + % default = 12 | 22, expert = 11:13 | 21:23 + % ----------------------------------------------------------------- + case {10,11,12,13,14,15,16,17} + % independent of the TR and therefore can include interpolation + reg(regstri).opt.rres = 1.0 + 0.5 * (job.extopts.regstr(regstri) - 11); + highres = min(highres, reg(regstri).opt.rres); + reg(regstri).opt.stepsize = 0.5; + reg(regstri).opt.ll1th = 0.005 * reg(regstri).opt.rres; % smaller better/slower + reg(regstri).opt.ll3th = 0.010 * reg(regstri).opt.rres; % smaller better/slower + reg(regstri).opt.resfac = max( highres + 4*reg(regstri).opt.stepsize:-reg(regstri).opt.stepsize : highres , reg(regstri).opt.rres ) / reg(regstri).opt.rres; + case {21,22,23,24,25} + % dependent on the TR without interpolation interpolation + reg(regstri).opt.rres = tempres; %max(tempres,1.0 + 0.5 * (job.extopts.regstr(regstri) - 21)); + reg(regstri).opt.stepsize = 0.5; + reg(regstri).opt.ll1th = 0.005 * reg(regstri).opt.rres; % smaller better/slower + reg(regstri).opt.ll3th = 0.010 * reg(regstri).opt.rres; % smaller better/slower + reg(regstri).opt.resfac = ones(1,5); %max( highres + 4*reg(regstri).opt.stepsize : -reg(regstri).opt.stepsize : highres , reg(regstri).opt.rres ) / reg(regstri).opt.rres; + % ----------------------------------------------------------------- + % There are further cases, but they all have some drawbacks: + % * Using a fixed stepsize with different final resolutions run + % into the problematic low resolution (<3 mm). + % * Using a additive or multiplicative template depending reduction + % will be bad for the GUI and it is better to have some fixed + % levels. + % ----------------------------------------------------------------- + otherwise + error('cat_main_registration:incorrectparameter','Incorrect value of ""regres"".\n'); + end + + % not required from a theoretic point of view but ... + reg(regstri).opt.ll1th = reg(regstri).opt.ll1th * tempres/tpmres; + reg(regstri).opt.ll3th = reg(regstri).opt.ll3th * tempres/tpmres; + end + + + %% manual setting of shooting parameter + if 0 + job.extopts.vox(voxi) = 1.5; %#ok % output resolution ... + reg(regstri).opt.stepsize = max(eps,0.5); % stepsize of reduction + reg(regstri).opt.rres = 1.0; % registration resolution expert parameter ... + reg(regstri).opt.vxreg = 1.5; % regularisation parameter that original depend on the template resolution + reg(regstri).opt.nits = 5; % registration iteration (shooting default = 24) + reg(regstri).opt.ll1th = 0.01; % smaller better/slower + reg(regstri).opt.ll3th = 0.04; % smaller better/slower + res.do_dartel = 2; % method, 1 - Dartel, 2 - Shooting + reg.fast = 10; % inner iterations limit + end + + + %% set default dartel/shooting templates in debug mode + % ... error for bad template numbers ... use defaults? if res.tmp2 + if 0 %debug + % only in case of the default templates + job.extopts.templates = templates; + if job.extopts.expertgui==2 && ... + (res.do_dartel==1 && job.extopts.regstr(regstri)>0) || ... + (res.do_dartel==2 && job.extopts.regstr(regstri)==0) + if res.do_dartel==2 && job.extopts.regstr(regstri)==0 + cat_io_cprintf('warn','Switch to default Dartel Template.\n'); + job.extopts.templates = cat_vol_findfiles(cat_get_defaults('extopts.pth_templates'),'Template_*_IXI555_MNI152.nii'); + job.extopts.templates(end) = []; + reg(regstri).opt.rres = job.extopts.vox(voxi); + elseif res.do_dartel==1 && job.extopts.regstr(regstri)>0 + cat_io_cprintf('warn','Switch to default Shooting Template.\n'); + job.extopts.templates = cat_vol_findfiles(cat_get_defaults('extopts.pth_templates'),'Template_*_IXI555_MNI152_GS.nii',struct('depth',1)); + end + end + res.tmp2 = cell(1,numel(job.extopts.templates)); + end + run2 = struct(); + for j=1:numel(res.tmp2) + for i=1:n1, run2(i).tpm = sprintf('%s,%d',job.extopts.templates{j},i);end + res.tmp2{j} = spm_vol(char(cat(1,run2(:).tpm))); + end + + % preparte output directory + [temppp,tempff] = spm_fileparts(job.extopts.templates{1}); clear temppp; + tempres2 = reg(regstri).opt.resfac * reg(regstri).opt.rres; + newres = job.extopts.vox(voxi); + regres = reg(regstri).opt.rres; + if job.extopts.regstr(regstri)==0 + reg(regstri).testfolder = sprintf('Dartel_%s_rr%0.1f_default',tempff,newres); + elseif job.extopts.regstr(regstri)==4 + reg(regstri).testfolder = sprintf('Shooting_%s_rr%0.1f_or%0.1f_default',tempff,regres,newres); + else + if reg(regstri).opt.stepsize>10^-3 + reg(regstri).testfolder = sprintf('Shooting_%s_tr%0.1f_rr%0.1f-%0.1f_or%0.1f_regstr%0.1f%s',tempff,tempres,tempres2([1,5]),newres,job.extopts.regstr(regstri)); + else + reg(regstri).testfolder = sprintf('Shooting_%s_tr%0.1f_rr%0.1f_or%0.1f_regstr%0.1f%s',tempff,tempres,regres,newres,job.extopts.regstr(regstri)); + end + end +end +%======================================================================= +function report(job,reg,regstri) +% report function + + % display registration power profil + if job.extopts.expertgui==2 + mdisplay = [2 2 2 2 2]; + elseif job.extopts.expertgui==1 + mdisplay = [0 2 0 2 0]; + else + mdisplay = [0 1 0 1 0]; + end + if job.extopts.regstr(regstri)==0, dartelfac = 1.5; else, dartelfac = 1.0; end + if mdisplay(1) + fprintf('Registration power: \n'); + fprintf('%30s','Jacobian determinant: '); + QMC = cat_io_colormaps('marks+',17); + reg(regstri).reldtc = reg(regstri).dtc / max(reg(regstri).dtc); + color = @(QMC,m) QMC(max(1,min(size(QMC,1),round(((m-1)*3)+1))),:); + if mdisplay(1)>1 + for dti=1:numel(reg(regstri).dtc)-1 + cat_io_cprintf( color(QMC,( 1 - reg(regstri).reldtc(dti)/dartelfac/0.25 ) *6),sprintf('%0.3f ',reg(regstri).reldtc(dti))); + end + fprintf('| '); + end + cat_io_cprintf( color(QMC,(reg(regstri).dt - 0.05)/dartelfac/0.25 * 6), sprintf(' %0.6f ',reg(regstri).dt)); + fprintf('\n'); + end + + if mdisplay(2) + fprintf('%30s','Jacobian determinant (RMS): '); + QMC = cat_io_colormaps('marks+',17); + reg(regstri).relrmsdtc = reg(regstri).rmsdtc; %/max(reg(regstri).rmsdtc); + color = @(QMC,m) QMC(max(1,min(size(QMC,1),round(((m-1)*3)+1))),:); + if mdisplay(2)>1 + for dti=1:numel(reg(regstri).relrmsdtc)-1 + cat_io_cprintf( color(QMC,reg(regstri).relrmsdtc(dti)/dartelfac/0.5*6),sprintf('%0.3f ',reg(regstri).relrmsdtc(dti))); + end + fprintf('| '); + end + cat_io_cprintf( color(QMC,(reg(regstri).rmsdt)/dartelfac/0.5 * 6), sprintf(' %0.6f ',reg(regstri).rmsdt)); + fprintf('\n'); + end + + if mdisplay(3) + fprintf('%30s','Jacobian determinant'' (RMS): '); + QMC = cat_io_colormaps('marks+',17); + color = @(QMC,m) QMC(max(1,min(size(QMC,1),round(((m-1)*3)+1))),:); + if mdisplay(3)>1 + for dti=1:numel(reg(regstri).rmsgdt)-1 + cat_io_cprintf( color(QMC,reg(regstri).rmsgdt(dti)/dartelfac/0.5*6),sprintf('%0.3f ',reg(regstri).rmsgdt(dti))); + end + fprintf('| '); + end + cat_io_cprintf( color(QMC,(reg(regstri).rmsgdt(end))/dartelfac/0.5 * 6), sprintf(' %0.6f ',reg(regstri).rmsgdt(end))); + fprintf('\n'); + end + + if mdisplay(4) + % this work very well + fprintf('%30s','Template Matching: '); + QMC = cat_io_colormaps('marks+',17); + color = @(QMC,m) QMC(max(1,min(size(QMC,1),round(((m-1)*3)+1))),:); + if mdisplay(4)>1 + for dti=1:size(reg(regstri).ll,1)-1 + cat_io_cprintf( color(QMC, (reg(regstri).ll(dti,1) - 0.05) / 0.15 * 6),sprintf('%0.3f ',reg(regstri).ll(dti,1))); + end + fprintf('| '); + end + cat_io_cprintf( color(QMC,(reg(regstri).ll(end,1) - 0.05)/0.15 * 6), sprintf(' %0.6f ',reg(regstri).ll(end,1))); + fprintf('\n'); + end + + reg(regstri).cbr = diff(reg(regstri).relrmsdtc(1:end-1)) ./ -diff(reg(regstri).ll(1:end-1,1)'); + reg(regstri).scbr = sum(diff(reg(regstri).relrmsdtc(1:end-1)) ./ -diff(reg(regstri).ll(1:end-1,1)')); + reg(regstri).mcbr = mean(diff(reg(regstri).relrmsdtc(1:end-1)) ./ -diff(reg(regstri).ll(1:end-1,1)')); + if mdisplay(5) + % this work very well + fprintf('%30s','Cost Benefit Ratio (CBR): '); + QMC = cat_io_colormaps('marks+',17); + color = @(QMC,m) QMC(max(1,min(size(QMC,1),round(((m-1)*3)+1))),:); + if mdisplay(5)>1 + for dti=1:size(reg(regstri).cbr,2) + cat_io_cprintf( color(QMC, (reg(regstri).cbr(dti))/2),sprintf('%0.3f ',reg(regstri).cbr(dti))); + end + fprintf('| '); + end + cat_io_cprintf( color(QMC,( reg(regstri).mcbr)/2), sprintf(' %0.6f ', reg(regstri).mcbr)); + fprintf('\n'); + end +end +%======================================================================= +function write_nii(Ycls,job,trans,testfolder,reg) +% Fast export of output data to test and run different settings in the same +% preprocessing. + + trans.warped.verb = 1; % test output + + stime = cat_io_cmd(sprintf('Write Output with %0.2f mm',job.extopts.vox(1))); + + mrifolder = cat_io_subfolders(trans.native.Vo.fname,job); + + if ~exist('testfolder','var'); testfolder = sprintf('backup_or%3.1f',job.extopts.vox(1)); end + [pth,nam] = spm_fileparts(trans.native.Vo.fname); + + % registration information + if exist('reg','var') + cat_io_xml(fullfile(pth,mrifolder,testfolder,['reg_', nam, '.xml']),reg) + end + + % tissue ouptut + fn = {'GM'}; %,'WM','CSF','HD1','HD2','BG'}; + for clsi = 1:numel(fn) + if ~isempty(Ycls{clsi}) + cat_io_writenii(trans.native.Vo,single(Ycls{clsi})/255,fullfile(mrifolder,testfolder),sprintf('p%d',clsi),... + sprintf('%s tissue map',fn{clsi}),'uint8' ,[0,1/255],[0 0 0 3],trans); + cat_io_writenii(trans.native.Vo,single(Ycls{clsi})/255,fullfile(mrifolder,testfolder),sprintf('p%d',clsi),... + sprintf('%s tissue map',fn{clsi}),'uint8' ,[0,1/255],[0 1 0 0],trans); + cat_io_writenii(trans.native.Vo,single(Ycls{clsi})/255,fullfile(mrifolder,testfolder),sprintf('p%d',clsi),... + sprintf('%s tissue map',fn{clsi}),'uint16',[0,1/255],[0 0 3 0],trans); + end + end + + if job.output.jacobian.warped + %% write jacobian determinant + if isfield(trans.jc,'dt2') % % shooting + dt2 = trans.jc.dt2; + dx = 10; % smaller values are more accurate, but large look better; + [D,I] = cat_vbdist(single(~(isnan(dt2) | dt2<0 | dt2>100) )); D=min(1,D/min(dx,max(D(:)))); + dt2 = dt2(I); dt2 = dt2 .* ((1-D) + D); + dt2(isnan(dt2))=1; + else % dartel + [y0, dt2] = spm_dartel_integrate(reshape(trans.jc.u,[trans.warped.odim(1:3) 1 3]),[1 0], 6); clear y0; + end + + % create nifti + N = nifti; + N.dat = file_array(fullfile(pth,mrifolder,testfolder,['wj_', nam, '.nii']),trans.warped.odim(1:3),... + [spm_type('float32') spm_platform('bigend')],0,10/256^2,0); + N.mat = trans.warped.M1; + N.mat0 = trans.warped.M1; + N.descrip = ['Jacobian' trans.native.Vo.descrip]; + create(N); + N.dat(:,:,:) = dt2; + end + + if job.output.warps(1) + %% deformations y - dartel > subject + Yy2 = spm_diffeo('invdef',trans.warped.y,trans.warped.odim,eye(4),trans.warped.M0); + N = nifti; + N.dat = file_array(fullfile(pth,mrifolder,testfolder,['y_', nam, '.nii']),[trans.warped.odim(1:3),1,3],'float32',0,1,0); + N.mat = trans.warped.M1; + N.mat0 = trans.warped.M1; + N.descrip = 'Deformation'; + create(N); + N.dat(:,:,:,:,:) = reshape(Yy2,[trans.warped.odim,1,3]); + clear Yy2; + end + + + if job.output.warps(2) + %% deformation iy - subject > dartel + if any(trans.native.Vo.dim~=trans.native.Vi.dim) + vx_voli = sqrt(sum(trans.native.Vi.mat(1:3,1:3).^2)); + vx_volo = sqrt(sum(trans.native.Vo.mat(1:3,1:3).^2)); + eyev = eye(4); eyev([1 6 11]) = eyev([1 6 11]) .* vx_volo./vx_voli; + Yy2 = zeros([trans.native.Vo.dim 1 3],'single'); + for k1 = 1:3 + for i = 1:trans.native.Vo.dim(3) + Yy2(:,:,i,:,k1) = trans.warped.M1(k1,4) + trans.warped.M1(k1,k1) * ... + single(spm_slice_vol(trans.warped.y(:,:,:,k1),eyev*spm_matrix([0 0 i]), ... + trans.native.Vo.dim(1:2),[1,NaN])); % adapt for res + end + end + else + yn = numel(trans.warped.y); + p = ones([4,yn/3],'single'); + p(1,:) = trans.warped.y(1:yn/3); + p(2,:) = trans.warped.y(yn/3+1:yn/3*2); + p(3,:) = trans.warped.y(yn/3*2+1:yn); + p = trans.warped.M1(1:3,:) * p; + + Yy2 = zeros([trans.native.Vo.dim(1:3),1,3],'single'); + Yy2(1:yn/3) = p(1,:); + Yy2(yn/3+1:yn/3*2) = p(2,:); + Yy2(yn/3*2+1:yn) = p(3,:); + end + clear p; + + % f2 = spm_diffeo('resize', f1, dim) + % write new output + Ndef = nifti; + Ndef.dat = file_array(fullfile(pth,mrifolder,testfolder,['iy_', nam, '.nii']),[trans.native.Vo.dim,1,3],... + [spm_type('float32') spm_platform('bigend')],0,1,0); + Ndef.mat = trans.native.Vo.mat; + Ndef.mat0 = trans.native.Vo.mat; + Ndef.descrip = 'Inverse Deformation'; + create(Ndef); + Ndef.dat(:,:,:,:,:) = Yy2; + clear Yy2; + end + + cat_io_cmd('','',''); cat_io_cmd('','','',job.extopts.verb,stime); + +end +%======================================================================= +function x = rgrid(d) + x = zeros([d(1:3) 3],'single'); + [x1,x2] = ndgrid(single(1:d(1)),single(1:d(2))); + for i=1:d(3) + x(:,:,i,1) = x1; + x(:,:,i,2) = x2; + x(:,:,i,3) = single(i); + end +end +%======================================================================= +function y1 = affind(y0,M) + y1 = zeros(size(y0),'single'); + for d=1:3 + y1(:,:,:,d) = y0(:,:,:,1)*M(d,1); + y1(:,:,:,d) = y1(:,:,:,d) + y0(:,:,:,2)*M(d,2); + y1(:,:,:,d) = y1(:,:,:,d) + y0(:,:,:,3)*M(d,3) + M(d,4); + end +end +%======================================================================= +function [x1,y1,z1] = defs2(sol,z,M,prm,x0,y0,z0) + iM = inv(M); + z01 = z0(z)*ones(size(x0)); + + x1a = iM(1,1)*x0 + iM(1,2)*y0 + iM(1,3)*z01 + iM(1,4); + y1a = iM(2,1)*x0 + iM(2,2)*y0 + iM(2,3)*z01 + iM(2,4); + z1a = iM(3,1)*x0 + iM(3,2)*y0 + iM(3,3)*z01 + iM(3,4); + + x1 = spm_bsplins(sol{1},x1a,y1a,z1a,prm); + y1 = spm_bsplins(sol{2},x1a,y1a,z1a,prm); + z1 = spm_bsplins(sol{3},x1a,y1a,z1a,prm); +end +%=======================================================================","MATLAB" +"Neurology","ChristianGaser/cat12","compile_test_debug.m",".m","671","26","function compile_test_debug + +if ~strcmp(mexext,'mexmaci64') + error('This tool has to be called from Mac OSX 64bit'); +% return +end + +d0 = load('debug_mexmaci64.mat'); + +mexext_str = {'mexw64','mexa64','mexglx','mexw32'}; + +for i = 1:length(mexext_str) + debugname = ['debug_' mexext_str{i} '.mat']; + d = load(debugname); + n = length(d0.d); + fprintf('Absolute difference between maci64 and %s:\n',mexext_str{i}); + for j=1:n + df = d0.d{j} - d.d{j}; + fprintf('%d: %f\n',j,max(df(:))); + end + j = j + 1; + df = d0.CS.faces - d.CS.faces; + fprintf('%d: faces %f\n',j,max(df(:))); + df = d0.CS.vertices - d.CS.vertices; + fprintf('%d: vertices %f\n',j,max(df(:))); +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_spm_affreg.m",".m","18866","507","function [M,scal] = cat_spm_affreg(VG,VF,flags,M,scal) +% Affine registration using least squares. +% FORMAT [M,scal] = spm_affreg(VG,VF,flags,M0,scal0) +% +% VG - Vector of template volumes. +% VF - Source volume. +% flags - a structure containing various options. The fields are: +% WG - Weighting volume for template image(s). +% WF - Weighting volume for source image +% Default to []. +% sep - Approximate spacing between sampled points (mm). +% Defaults to 5. +% regtype - regularisation type. Options are: +% 'none' - no regularisation +% 'rigid' - almost rigid body +% 'subj' - inter-subject registration (default). +% 'mni' - registration to ICBM templates +% globnorm - Global normalisation flag (1) +% M0 - (optional) starting estimate. Defaults to eye(4). +% scal0 - (optional) starting estimate. +% +% M - affine transform, such that voxels in VF map to those in +% VG by VG.mat\M*VF.mat +% scal - scaling factors for VG +% +% When only one template is used, then the cost function is approximately +% symmetric, although a linear combination of templates can be used. +% Regularisation is based on assuming a multi-normal distribution for the +% elements of the Henckey Tensor. See: +% ""Non-linear Elastic Deformations"". R. W. Ogden (Dover), 1984. +% Weighting for the regularisation is determined approximately according +% to: +% ""Incorporating Prior Knowledge into Image Registration"" +% J. Ashburner, P. Neelin, D. L. Collins, A. C. Evans & K. J. Friston. +% NeuroImage 6:344-352 (1997). +% +%_______________________________________________________________________ +% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging +% John Ashburner +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + +if nargin<5, scal = ones(length(VG),1); end; +if nargin<4, M = eye(4); end; + +def_flags = struct('sep',5, 'regtype','subj','WG',[],'WF',[],'globnorm',1,'debug',0); +if nargin < 3 || ~isstruct(flags), + 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; + +% Check to ensure inputs are valid... +% --------------------------------------------------------------- +if length(VF)>1, error('Can not use more than one source image'); end; +if ~isempty(flags.WF), + if length(flags.WF)>1, + error('Can only use one source weighting image'); + end; + if any(any((VF.mat-flags.WF.mat).^2>1e-8)), + error('Source and its weighting image must have same orientation'); + end; + if any(any(VF.dim(1:3)-flags.WF.dim(1:3))), + error('Source and its weighting image must have same dimensions'); + end; +end; +if ~isempty(flags.WG), + if length(flags.WG)>1, + error('Can only use one template weighting image'); + end; + tmp = reshape(cat(3,VG(:).mat,flags.WG.mat),16,length(VG)+length(flags.WG)); +else + tmp = reshape(cat(3,VG(:).mat),16,length(VG)); +end; +if any(any(diff(tmp,1,2).^2>1e-8)), + error('Reference images must all have the same orientation'); +end; +if ~isempty(flags.WG), + tmp = cat(1,VG(:).dim,flags.WG.dim); +else + tmp = cat(1,VG(:).dim); +end; +if any(any(diff(tmp(:,1:3),1,1))), + error('Reference images must all have the same dimensions'); +end; +% --------------------------------------------------------------- + +% Generate points to sample from, adding some jitter in order to +% make the cost function smoother. +% --------------------------------------------------------------- +% want the results to be consistant. +if exist('rng','file') == 2, rng('default'); rng(0); else, rand('state',0); randn('state',0); end +dg = VG(1).dim(1:3); +df = VF(1).dim(1:3); + +if length(VG)==1, + skip = sqrt(sum(VG(1).mat(1:3,1:3).^2)).^(-1)*flags.sep; + [x1,x2,x3]=ndgrid(1:skip(1):dg(1)-.5, 1:skip(2):dg(2)-.5, 1:skip(3):dg(3)-.5); + x1 = x1 + rand(size(x1))*0.5; x1 = x1(:); + x2 = x2 + rand(size(x2))*0.5; x2 = x2(:); + x3 = x3 + rand(size(x3))*0.5; x3 = x3(:); +end; + +skip = sqrt(sum(VF(1).mat(1:3,1:3).^2)).^(-1)*flags.sep; +[y1,y2,y3]=ndgrid(1:skip(1):df(1)-.5, 1:skip(2):df(2)-.5, 1:skip(3):df(3)-.5); +y1 = y1 + rand(size(y1))*0.5; y1 = y1(:); +y2 = y2 + rand(size(y2))*0.5; y2 = y2(:); +y3 = y3 + rand(size(y3))*0.5; y3 = y3(:); +% --------------------------------------------------------------- + +if flags.globnorm, + % Scale all images approximately equally + % --------------------------------------------------------------- + for i=1:length(VG), + VG(i).pinfo(1:2,:) = VG(i).pinfo(1:2,:)/spm_global(VG(i)); + end; + VF(1).pinfo(1:2,:) = VF(1).pinfo(1:2,:)/spm_global(VF(1)); +end; +% --------------------------------------------------------------- + +if length(VG)==1, + [G,dG1,dG2,dG3] = spm_sample_vol(VG(1),x1,x2,x3,1); + if ~isempty(flags.WG), + WG = abs(spm_sample_vol(flags.WG,x1,x2,x3,1))+eps; + WG(~isfinite(WG)) = 1; + end; +end; + +[F,dF1,dF2,dF3] = spm_sample_vol(VF(1),y1,y2,y3,1); +if ~isempty(flags.WF), + WF = abs(spm_sample_vol(flags.WF,y1,y2,y3,1))+eps; + WF(~isfinite(WF)) = 1; +end; +% --------------------------------------------------------------- +n_main_its = 0; +ss = Inf; +W = [Inf Inf Inf]; +est_smo = 1; +% --------------------------------------------------------------- + +for iter=1:256, + pss = ss; + p0 = [0 0 0 0 0 0 1 1 1 0 0 0]; + + % Initialise the cost function and its 1st and second derivatives + % --------------------------------------------------------------- + n = 0; + ss = 0; + Beta = zeros(12+length(VG),1); + Alpha = zeros(12+length(VG)); + + if length(VG)==1, + % Make the cost function symmetric + % --------------------------------------------------------------- + + % Build a matrix to rotate the derivatives by, converting from + % derivatives w.r.t. changes in the overall affine transformation + % matrix, to derivatives w.r.t. the parameters p. + % --------------------------------------------------------------- + dt = 0.0001; + R = eye(13); + MM0 = inv(VG.mat)*inv(spm_matrix(p0))*VG.mat; + for i1=1:12, + p1 = p0; + p1(i1) = p1(i1)+dt; + MM1 = (inv(VG.mat)*inv(spm_matrix(p1))*(VG.mat)); + R(1:12,i1) = reshape((MM1(1:3,:)-MM0(1:3,:))/dt,12,1); + end; + % --------------------------------------------------------------- + [t1,t2,t3] = coords((M*VF(1).mat)\VG(1).mat,x1,x2,x3); + msk = find((t1>=1 & t1<=df(1) & t2>=1 & t2<=df(2) & t3>=1 & t3<=df(3))); + if length(msk)<32, error_message; end; + t1 = t1(msk); + t2 = t2(msk); + t3 = t3(msk); + t = spm_sample_vol(VF(1), t1,t2,t3,1); + + % Get weights + % --------------------------------------------------------------- + if ~isempty(flags.WF) || ~isempty(flags.WG), + if isempty(flags.WF), + wt = WG(msk); + else + wt = spm_sample_vol(flags.WF(1), t1,t2,t3,1)+eps; + wt(~isfinite(wt)) = 1; + if ~isempty(flags.WG), wt = 1./(1./wt + 1./WG(msk)); end; + end; + wt = sparse(1:length(wt),1:length(wt),wt); + else + % wt = speye(length(msk)); + wt = []; + end; + % --------------------------------------------------------------- + clear t1 t2 t3 + + % Update the cost function and its 1st and second derivatives. + % --------------------------------------------------------------- + [AA,Ab,ss1,n1] = costfun(x1,x2,x3,dG1,dG2,dG3,msk,scal^(-2)*t,G(msk)-(1/scal)*t,wt); + Alpha = Alpha + R'*AA*R; + Beta = Beta + R'*Ab; + ss = ss + ss1; + n = n + n1; + % t = G(msk) - (1/scal)*t; + end; + + if 1, + % Build a matrix to rotate the derivatives by, converting from + % derivatives w.r.t. changes in the overall affine transformation + % matrix, to derivatives w.r.t. the parameters p. + % --------------------------------------------------------------- + dt = 0.0001; + R = eye(12+length(VG)); + MM0 = inv(M*VF.mat)*spm_matrix(p0)*M*VF.mat; + for i1=1:12, + p1 = p0; + p1(i1) = p1(i1)+dt; + MM1 = (inv(M*VF.mat)*spm_matrix(p1)*M*VF.mat); + R(1:12,i1) = reshape((MM1(1:3,:)-MM0(1:3,:))/dt,12,1); + end; + % --------------------------------------------------------------- + [t1,t2,t3] = coords(VG(1).mat\M*VF(1).mat,y1,y2,y3); + msk = find((t1>=1 & t1<=dg(1) & t2>=1 & t2<=dg(2) & t3>=1 & t3<=dg(3))); + if length(msk)<32, error_message; end; + + if length(msk)<32, error_message; end; + t1 = t1(msk); + t2 = t2(msk); + t3 = t3(msk); + t = zeros(length(t1),length(VG)); + + % Get weights + % --------------------------------------------------------------- + if ~isempty(flags.WF) || ~isempty(flags.WG), + if isempty(flags.WG), + wt = WF(msk); + else + wt = spm_sample_vol(flags.WG(1), t1,t2,t3,1)+eps; + wt(~isfinite(wt)) = 1; + if ~isempty(flags.WF), wt = 1./(1./wt + 1./WF(msk)); end; + end; + wt = sparse(1:length(wt),1:length(wt),wt); + else + wt = speye(length(msk)); + end; + % --------------------------------------------------------------- + + if est_smo, + % Compute derivatives of residuals in the space of F + % --------------------------------------------------------------- + [ds1,ds2,ds3] = transform_derivs(VG(1).mat\M*VF(1).mat,dF1(msk),dF2(msk),dF3(msk)); + for i=1:length(VG), + [t(:,i),dt1,dt2,dt3] = spm_sample_vol(VG(i), t1,t2,t3,1); + ds1 = ds1 - dt1*scal(i); clear dt1 + ds2 = ds2 - dt2*scal(i); clear dt2 + ds3 = ds3 - dt3*scal(i); clear dt3 + end; + dss = [ds1'*wt*ds1 ds2'*wt*ds2 ds3'*wt*ds3]; + clear ds1 ds2 ds3 + else + for i=1:length(VG), + t(:,i)= spm_sample_vol(VG(i), t1,t2,t3,1); + end; + end; + + clear t1 t2 t3 + + % Update the cost function and its 1st and second derivatives. + % --------------------------------------------------------------- + [AA,Ab,ss2,n2] = costfun(y1,y2,y3,dF1,dF2,dF3,msk,-t,F(msk)-t*scal,wt); + Alpha = Alpha + R'*AA*R; + Beta = Beta + R'*Ab; + ss = ss + ss2; + n = n + n2; + end; + + if est_smo, + % Compute a smoothness correction from the residuals and their + % derivatives. This is analagous to the one used in: + % ""Analysis of fMRI Time Series Revisited"" + % Friston KJ, Holmes AP, Poline JB, Grasby PJ, Williams SCR, + % Frackowiak RSJ, Turner R. Neuroimage 2:45-53 (1995). + % --------------------------------------------------------------- + vx = sqrt(sum(VG(1).mat(1:3,1:3).^2)); + pW = W; + W = (2*dss/ss2).^(-.5).*vx; + W = min(pW,W); + if flags.debug, fprintf('\nSmoothness FWHM: %.3g x %.3g x %.3g mm\n', W*sqrt(8*log(2))); end; + if length(VG)==1, dens=2; else dens=1; end; + smo = prod(min(dens*flags.sep/sqrt(2*pi)./W,[1 1 1])); + est_smo=0; + n_main_its = n_main_its + 1; + end; + + % Update the parameter estimates + % --------------------------------------------------------------- + nu = n*smo; + sig2 = ss/nu; + [d1,d2] = reg(M,12+length(VG),flags.regtype); + + soln = (Alpha/sig2+d2)\(Beta/sig2-d1); + scal = scal - soln(13:end); + M = spm_matrix(p0 + soln(1:12)')*M; + + if flags.debug, + fprintf('%d\t%g\n', iter, ss/n); + piccies(VF,VG,M,scal) + end; + + % If cost function stops decreasing, then re-estimate smoothness + % and try again. Repeat a few times. + % --------------------------------------------------------------- + ss = ss/n; + if iter>1, spm_plot_convergence('Set',ss); end; + if (pss-ss)/pss < 1e-6, + est_smo = 1; + end; + if n_main_its>3, break; end; + +end; +return; +%_______________________________________________________________________ + +%_______________________________________________________________________ +function [X1,Y1,Z1] = transform_derivs(Mat,X,Y,Z) +% Given the derivatives of a scalar function, return those of the +% affine transformed function +%_______________________________________________________________________ + +t1 = Mat(1:3,1:3); +t2 = eye(3); +if sum((t1(:)-t2(:)).^2) < 1e-12, + X1 = X;Y1 = Y; Z1 = Z; +else + X1 = Mat(1,1)*X + Mat(1,2)*Y + Mat(1,3)*Z; + Y1 = Mat(2,1)*X + Mat(2,2)*Y + Mat(2,3)*Z; + Z1 = Mat(3,1)*X + Mat(3,2)*Y + Mat(3,3)*Z; +end; +return; +%_______________________________________________________________________ + +%_______________________________________________________________________ +function [d1,d2] = reg(M,n,typ) +% Analytically compute the first and second derivatives of a penalty +% function w.r.t. changes in parameters. + +if nargin<3, typ = 'subj'; end; +if nargin<2, n = 13; end; + +[mu,isig] = spm_affine_priors(typ); +ds = 0.000001; +d1 = zeros(n,1); +d2 = zeros(n); +p0 = [0 0 0 0 0 0 1 1 1 0 0 0]; +h0 = penalty(p0,M,mu,isig); +for i=7:12, % derivatives are zero w.r.t. rotations and translations + p1 = p0; + p1(i) = p1(i)+ds; + h1 = penalty(p1,M,mu,isig); + d1(i) = (h1-h0)/ds; % First derivative + for j=7:12, + p2 = p0; + p2(j) = p2(j)+ds; + h2 = penalty(p2,M,mu,isig); + p3 = p1; + p3(j) = p3(j)+ds; + h3 = penalty(p3,M,mu,isig); + d2(i,j) = ((h3-h2)/ds-(h1-h0)/ds)/ds; % Second derivative + end; +end; +return; +%_______________________________________________________________________ + +%_______________________________________________________________________ +function h = penalty(p,M,mu,isig) +% Return a penalty based on the elements of an affine transformation, +% which is given by: +% spm_matrix(p)*M +% +% The penalty is based on the 6 unique elements of the Hencky tensor +% elements being multinormally distributed. +%_______________________________________________________________________ + +% Unique elements of symmetric 3x3 matrix. +els = [1 2 3 5 6 9]; + +T = spm_matrix(p)*M; +T = T(1:3,1:3); +T = 0.5*logm(T'*T); +T = T(els)' - mu; +h = T'*isig*T; +return; +%_______________________________________________________________________ + +%_______________________________________________________________________ +function [y1,y2,y3]=coords(M,x1,x2,x3) +% Affine transformation of a set of coordinates. +%_______________________________________________________________________ + +y1 = M(1,1)*x1 + M(1,2)*x2 + M(1,3)*x3 + M(1,4); +y2 = M(2,1)*x1 + M(2,2)*x2 + M(2,3)*x3 + M(2,4); +y3 = M(3,1)*x1 + M(3,2)*x2 + M(3,3)*x3 + M(3,4); +return; +%_______________________________________________________________________ + +%_______________________________________________________________________ +function A = make_A(x1,x2,x3,dG1,dG2,dG3,t) +% Generate part of a design matrix using the chain rule... +% df/dm = df/dy * dy/dm +% where +% df/dm is the rate of change of intensity w.r.t. affine parameters +% df/dy is the gradient of the image f +% dy/dm crange of position w.r.t. change of parameters +%_______________________________________________________________________ + +A = [x1.*dG1 x1.*dG2 x1.*dG3 ... + x2.*dG1 x2.*dG2 x2.*dG3 ... + x3.*dG1 x3.*dG2 x3.*dG3 ... + dG1 dG2 dG3 t]; +return; +%_______________________________________________________________________ + +%_______________________________________________________________________ +function [AA,Ab,ss,n] = costfun(x1,x2,x3,dG1,dG2,dG3,msk,lastcols,b,wt) +chunk = 10240; +lm = length(msk); +AA = zeros(12+size(lastcols,2)); +Ab = zeros(12+size(lastcols,2),1); +ss = 0; +n = 0; + +for i=1:ceil(lm/chunk), + ind = (((i-1)*chunk+1):min(i*chunk,lm))'; + msk1 = msk(ind); + + A1 = make_A(x1(msk1),x2(msk1),x3(msk1),dG1(msk1),dG2(msk1),dG3(msk1),lastcols(ind,:)); + b1 = b(ind); + if ~isempty(wt), + wt1 = wt(ind,ind); + AA = AA + A1'*wt1*A1; + %Ab = Ab + A1'*wt1*b1; + Ab = Ab + (b1'*wt1*A1)'; + ss = ss + b1'*wt1*b1; + n = n + trace(wt1); + clear wt1 + else + AA = AA + A1'*A1; + %Ab = Ab + A1'*b1; + Ab = Ab + (b1'*A1)'; + ss = ss + b1'*b1; + n = n + length(msk1); + end; + clear A1 b1 msk1 ind +end; +return; +%_______________________________________________________________________ + +%_______________________________________________________________________ +function error_message +% Display an error message for when things go wrong. +str = { 'There is not enough overlap in the images',... + 'to obtain a solution.',... + ' ',... + 'Please check that your header information is OK.',... + 'The Check Reg utility will show you the initial',... + 'alignment between the images, which must be',... + 'within about 4cm and about 15 degrees in order',... + 'for SPM to find the optimal solution.'}; +%spm('alert*',str,mfilename,sqrt(-1)); +error('insufficient image overlap') +%_______________________________________________________________________ + +%_______________________________________________________________________ +function piccies(VF,VG,M,scal) +% This is for debugging purposes. +% It shows the linear combination of template images, the affine +% transformed source image, the residual image and a histogram of the +% residuals. +%_______________________________________________________________________ + +figure(2); +Mt = spm_matrix([0 0 (VG(1).dim(3)+1)/2]); +M = (M*VF(1).mat)\VG(1).mat; +t = zeros(VG(1).dim(1:2)); +for i=1:length(VG); + t = t + spm_slice_vol(VG(i), Mt,VG(1).dim(1:2),1)*scal(i); +end; +u = spm_slice_vol(VF(1),M*Mt,VG(1).dim(1:2),1); +subplot(2,2,1);imagesc(t');axis image xy off +subplot(2,2,2);imagesc(u');axis image xy off +subplot(2,2,3);imagesc(u'-t');axis image xy off +%subplot(2,2,4);hist(b,50); % Entropy of residuals may be a nice cost function? +drawnow; +return; +%_______________________________________________________________________ +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_spm_preproc_write8.m",".m","22197","670","function [Ym,Ycls,y] = cat_spm_preproc_write8(res,tc,bf,df,mrf,cleanup,bb,vx,Yclsout) +% Write out VBM preprocessed data +% FORMAT [Ym,Ycls] = cat_spm_preproc_write8(res,tc,bf,df,mrf,cleanup,bb,vx,Yclsout) +%__________________________________________________________________________ +% Copyright (C) 2008-2016 Wellcome Trust Centre for Neuroimaging +% +% modified version of +% John Ashburner +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +% Prior adjustment factor. +% This is a fudge factor to weaken the effects of the tissue priors. The +% idea here is that the bias from the tissue priors probably needs to be +% reduced because of the spatial smoothing typically used in VBM studies. +% Having the optimal bias/variance tradeoff for each voxel is not the same +% as having the optimal tradeoff for weighted averages over several voxels. + +if isfield(res,'mg') + lkp = res.lkp; + Kb = max(lkp); +else + Kb = size(res.intensity(1).lik,2); +end + +if ~exist('Yclsout','var'), Yclsout=ones(1,Kb); end %% ADDED RD +N = numel(res.image); + +if nargin<2, tc = true(Kb,4); end % native, import, warped, warped-mod +if nargin<3, bf = false(N,2); end % field, corrected +if nargin<4, df = false(1,2); end % inverse, forward +if nargin<5, mrf = 1; end % MRF parameter +if nargin<6, cleanup = 1; end % Run the ad hoc cleanup + if nargin<7, bb = NaN(2,3); end % Default to TPM bounding box + if nargin<8, vx = NaN; end % Default to TPM voxel size + +if (any(tc(:,3)) || any(tc(:,4)) || df(2)) && nargout > 2 + error('Deformations cannot be returned if writing of deformations or warped segmentations is enabled.'); +end + +% Read essentials from tpm (it will be cleared later) +tpm = res.tpm; +if ~isstruct(tpm) || ~isfield(tpm, 'bg1') + tpm = spm_load_priors8(tpm); +end +d1 = size(tpm.dat{1}); +d1 = d1(1:3); +M1 = tpm.M; + +% Define orientation and field of view of any ""normalised"" space +% data that may be generated (wc*.nii, mwc*.nii, rc*.nii & y_*.nii). +if nargin>=7 && any(isfinite(bb(:))) + % If a bounding box is supplied, combine this with the closest + % bounding box derived from the dimensions and orientations of + % the tissue priors. + if nargin<7, bb = NaN(2,3); end % Default to TPM bounding box + if nargin<8, vx = NaN; end % Default to TPM voxel size + [bb1,vx1] = spm_get_bbox(tpm.V(1), 'old'); + bb(~isfinite(bb)) = bb1(~isfinite(bb)); + if ~isfinite(vx), vx = abs(prod(vx1))^(1/3); end + bb(1,:) = vx*round(bb(1,:)/vx); + bb(2,:) = vx*round(bb(2,:)/vx); + odim = abs(round((bb(2,1:3)-bb(1,1:3))./vx))+1; + + mm = [[bb(1,1) bb(1,2) bb(1,3) + bb(2,1) bb(1,2) bb(1,3) + bb(1,1) bb(2,2) bb(1,3) + bb(2,1) bb(2,2) bb(1,3) + bb(1,1) bb(1,2) bb(2,3) + bb(2,1) bb(1,2) bb(2,3) + bb(1,1) bb(2,2) bb(2,3) + bb(2,1) bb(2,2) bb(2,3)]'; ones(1,8)]; + vx3 = [[1 1 1 + odim(1) 1 1 + 1 odim(2) 1 + odim(1) odim(2) 1 + 1 1 odim(3) + odim(1) 1 odim(3) + 1 odim(2) odim(3) + odim(1) odim(2) odim(3)]'; ones(1,8)]; + mat = mm/vx3; +else + % Use the actual dimensions and orientations of + % the tissue priors. + odim = tpm.V(1).dim; + mat = tpm.V(1).mat; +end + + +[pth,nam] = fileparts(res.image(1).fname); +ind = res.image(1).n; +d = res.image(1).dim(1:3); + +[x1,x2,o] = ndgrid(1:d(1),1:d(2),1); +x3 = 1:d(3); + + +chan(N) = struct('B1',[],'B2',[],'B3',[],'T',[],'Nc',[],'Nf',[],'ind',[]); +for n=1:N + d3 = [size(res.Tbias{n}) 1]; + chan(n).B3 = spm_dctmtx(d(3),d3(3),x3); + chan(n).B2 = spm_dctmtx(d(2),d3(2),x2(1,:)'); + chan(n).B1 = spm_dctmtx(d(1),d3(1),x1(:,1)); + chan(n).T = res.Tbias{n}; + + % Need to fix writing of bias fields or bias corrected images, when the data used are 4D. + [pth1,nam1] = fileparts(res.image(n).fname); + chan(n).ind = res.image(n).n; + + if bf(n,2) + chan(n).Nc = nifti; + chan(n).Nc.dat = file_array(fullfile(pth1,['m', nam1, '.nii']),... + res.image(n).dim(1:3),... + [spm_type('float32') spm_platform('bigend')],... + 0,1,0); + chan(n).Nc.mat = res.image(n).mat; + chan(n).Nc.mat0 = res.image(n).mat; + chan(n).Nc.descrip = 'Bias corrected'; + create(chan(n).Nc); + end + + if bf(n,1) + chan(n).Nf = nifti; + chan(n).Nf.dat = file_array(fullfile(pth1,['BiasField_', nam1, '.nii']),... + res.image(n).dim(1:3),... + [spm_type('float32') spm_platform('bigend')],... + 0,1,0); + chan(n).Nf.mat = res.image(n).mat; + chan(n).Nf.mat0 = res.image(n).mat; + chan(n).Nf.descrip = 'Estimated Bias Field'; + create(chan(n).Nf); + end +end + +do_cls = any(tc(:)) || nargout>=1; +tiss(Kb) = struct('Nt',[]); +for k1=1:Kb + if tc(k1,4) || any(tc(:,3)) || tc(k1,2) || nargout>=1 + do_cls = true; + end + if tc(k1,1) + tiss(k1).Nt = nifti; + tiss(k1).Nt.dat = file_array(fullfile(pth,['c', num2str(k1), nam, '.nii']),... + res.image(n).dim(1:3),... + [spm_type('uint8') spm_platform('bigend')],... + 0,1/255,0); + tiss(k1).Nt.mat = res.image(n).mat; + tiss(k1).Nt.mat0 = res.image(n).mat; + tiss(k1).Nt.descrip = ['Tissue class ' num2str(k1)]; + create(tiss(k1).Nt); + do_cls = true; + end +end + +prm = [3 3 3 0 0 0]; +Coef = cell(1,3); +Coef{1} = spm_bsplinc(res.Twarp(:,:,:,1),prm); +Coef{2} = spm_bsplinc(res.Twarp(:,:,:,2),prm); +Coef{3} = spm_bsplinc(res.Twarp(:,:,:,3),prm); + +do_defs = any(df); +do_defs = do_cls | do_defs; +if do_defs + if df(1) + [pth,nam] = fileparts(res.image(1).fname); + Ndef = nifti; + Ndef.dat = file_array(fullfile(pth,['iy_', nam, '.nii']),... + [res.image(1).dim(1:3),1,3],... + [spm_type('float32') spm_platform('bigend')],... + 0,1,0); + Ndef.mat = res.image(1).mat; + Ndef.mat0 = res.image(1).mat; + Ndef.descrip = 'Inverse Deformation'; + create(Ndef); + end + if df(2) || any(any(tc(:,[2,3,4]))) || nargout>1 + y = zeros([res.image(1).dim(1:3),3],'single'); + end +end + +spm_progress_bar('init',length(x3),['Working on ' nam],'Planes completed'); +M = M1\res.Affine*res.image(1).mat; + +if do_cls + Q = zeros([d(1:3),Kb],'single'); +end + +Ym = zeros([d(1:3) N],'single'); +for z=1:length(x3) + + % Bias corrected image + cr = cell(1,N); + for n=1:N + f = spm_sample_vol(res.image(n),x1,x2,o*x3(z),0); + bf = exp(transf(chan(n).B1,chan(n).B2,chan(n).B3(z,:),chan(n).T)); + cr{n} = bf.*f; + Ym(:,:,z,n) = cr{n}; + if ~isempty(chan(n).Nc) + % Write a plane of bias corrected data + chan(n).Nc.dat(:,:,z,chan(n).ind(1),chan(n).ind(2)) = cr{n}; + end + if ~isempty(chan(n).Nf) + % Write a plane of bias field + chan(n).Nf.dat(:,:,z,chan(n).ind(1),chan(n).ind(2)) = bf; + end + end + + + if do_defs + % Compute the deformation (mapping voxels in image to voxels in TPM) + [t1,t2,t3] = defs(Coef,z,res.MT,prm,x1,x2,x3,M); + + if exist('Ndef','var') + % Write out the deformation to file, adjusting it so mapping is + % to voxels (voxels in image to mm in TPM) + tmp = M1(1,1)*t1 + M1(1,2)*t2 + M1(1,3)*t3 + M1(1,4); + Ndef.dat(:,:,z,1,1) = tmp; + tmp = M1(2,1)*t1 + M1(2,2)*t2 + M1(2,3)*t3 + M1(2,4); + Ndef.dat(:,:,z,1,2) = tmp; + tmp = M1(3,1)*t1 + M1(3,2)*t2 + M1(3,3)*t3 + M1(3,4); + Ndef.dat(:,:,z,1,3) = tmp; + end + + if exist('y','var') + % If needed later, save in variable y + y(:,:,z,1) = t1; + y(:,:,z,2) = t2; + y(:,:,z,3) = t3; + end + + if do_cls + % Generate variable Q if tissue classes are needed + msk = any((f==0) | ~isfinite(f),3); + + if isfield(res,'mg') + % Parametric representation of intensity distributions + q = zeros([d(1:2) Kb]); + q1 = likelihoods(cr,[],res.mg,res.mn,res.vr); + q1 = reshape(q1,[d(1:2),numel(res.mg)]); + b = spm_sample_priors8(tpm,t1,t2,t3); + wp = res.wp; + s = zeros(size(b{1})); + for k1 = 1:Kb + b{k1} = wp(k1)*b{k1}; + s = s + b{k1}; + end + for k1=1:Kb + tmp = sum(q1(:,:,lkp==k1),3); + tmp(msk) = 1e-3; + q(:,:,k1) = tmp.*(b{k1}./s); + end + else + % Nonparametric representation of intensity distributions + q = spm_sample_priors8(tpm,t1,t2,t3); + wp = res.wp; + s = zeros(size(q{1})); + for k1 = 1:Kb + q{k1} = wp(k1)*q{k1}; + s = s + q{k1}; + end + for k1 = 1:Kb + q{k1} = q{k1}./s; + end + q = cat(3,q{:}); + + for n=1:N + tmp = round(cr{n}*res.intensity(n).interscal(2) + res.intensity(n).interscal(1)); + tmp = min(max(tmp,1),size(res.intensity(n).lik,1)); + for k1=1:Kb + likelihood = res.intensity(n).lik(:,k1); + q(:,:,k1) = q(:,:,k1).*likelihood(tmp); + end + end + end + Q(:,:,z,:) = reshape(q,[d(1:2),1,Kb]); + end + end + spm_progress_bar('set',z); +end +spm_progress_bar('clear'); + + +cls = cell(1,Kb); +if do_cls + P = zeros([d(1:3),Kb],'uint8'); + if mrf==0 + % Normalise to sum to 1 + sQ = (sum(Q,4)+eps)/255; + for k1=1:size(Q,4) + P(:,:,:,k1) = uint8(round(Q(:,:,:,k1)./sQ)); + end + clear sQ + else + % Use a MRF cleanup procedure + nmrf_its = 10; + spm_progress_bar('init',nmrf_its,['MRF: Working on ' nam],'Iterations completed'); + G = ones([Kb,1],'single')*mrf; + vx2 = 1./single(sum(res.image(1).mat(1:3,1:3).^2)); + %save PQG P Q G tiss Kb x3 ind + for iter=1:nmrf_its + spm_mrf(P,Q,G,vx2); + spm_progress_bar('set',iter); + end + end + clear Q + + if cleanup + % Use an ad hoc brain cleanup procedure + if size(P,4)>5 + P = clean_gwc(P,cleanup); + else + warning('Cleanup not done.'); + end + end + + % Write tissues if necessary + if nargout>1 || any(tc(:,1)) + Ycls = cell(1,Kb); + for k1=1:Kb + if Yclsout(k1), Ycls{k1}(:,:,:) = P(:,:,:,k1); end + if tc(k1,1) + for z=1:length(x3) + tmp = double(P(:,:,z,k1))/255; + tiss(k1).Nt.dat(:,:,z,ind(1),ind(2)) = tmp; + end + end + end + end + spm_progress_bar('clear'); + + % Put tissue classes into a cell array... + for k1=1:Kb + if tc(k1,4) || any(tc(:,3)) || tc(k1,2) || nargout>=1 + cls{k1} = P(:,:,:,k1); + end + end + clear P % ...and remove the original 4D array +end + +clear tpm +M0 = res.image(1).mat; + +if any(tc(:,2)) + % ""Imported"" tissue class images + + % Generate mm coordinates of where deformations map from + x = affind(rgrid(d),M0); + + % Generate mm coordinates of where deformation maps to + y1 = affind(y,M1); + + % Procrustes analysis to compute the closest rigid-body + % transformation to the deformation, weighted by the + % interesting tissue classes. + ind = find(tc(:,2)); % Saved tissue classes + [dummy,R] = spm_get_closest_affine(x,y1,single(cls{ind(1)})/255); + clear x y1 + + mat0 = R\mat; % Voxel-to-world of original image space + + [pth,nam] = fileparts(res.image(1).fname); + fwhm = max(vx./sqrt(sum(res.image(1).mat(1:3,1:3).^2))-1,0.01); + for k1=1:size(tc,1) + if tc(k1,2) + + % Low pass filtering to reduce aliasing effects in downsampled images, + % then reslice and write to disk + tmp1 = decimate(single(cls{k1}),fwhm); + Ni = nifti; + Ni.dat = file_array(fullfile(pth,['rc', num2str(k1), nam, '.nii']),... + odim,... + [spm_type('float32') spm_platform('bigend')],... + 0,1,0); + Ni.mat = mat; + Ni.mat_intent = 'Aligned'; + Ni.mat0 = mat0; + Ni.mat0_intent = 'Aligned'; + Ni.descrip = ['Imported Tissue ' num2str(k1)]; + create(Ni); + for i=1:odim(3) + tmp = spm_slice_vol(tmp1,M0\mat0*spm_matrix([0 0 i]),odim(1:2),[1,NaN])/255; + Ni.dat(:,:,i) = tmp; + end + clear tmp1 + end + end +end + +if any(tc(:,3)) || any(tc(:,4)) || df(2) + % Adjust stuff so that warped data (and deformations) have the + % desired bounding box and voxel sizes, instead of being the same + % as those of the tissue probability maps. + M = mat\M1; + for i=1:size(y,3) + t1 = y(:,:,i,1); + t2 = y(:,:,i,2); + t3 = y(:,:,i,3); + y(:,:,i,1) = M(1,1)*t1 + M(1,2)*t2 + M(1,3)*t3 + M(1,4); + y(:,:,i,2) = M(2,1)*t1 + M(2,2)*t2 + M(2,3)*t3 + M(2,4); + y(:,:,i,3) = M(3,1)*t1 + M(3,2)*t2 + M(3,3)*t3 + M(3,4); + end + M1 = mat; + d1 = odim; +end + + +if any(tc(:,3)) || any(tc(:,4)) + + if any(tc(:,3)) + C = zeros([d1,Kb],'single'); + end + + spm_progress_bar('init',Kb,'Warped Tissue Classes','Classes completed'); + for k1 = 1:Kb + if ~isempty(cls{k1}) + c = single(cls{k1})/255; + if any(tc(:,3)) + [c,w] = spm_diffeo('push',c,y,d1(1:3)); + vx = sqrt(sum(M1(1:3,1:3).^2)); + spm_field('boundary',1); + C(:,:,:,k1) = spm_field(w,c,[vx 1e-6 1e-4 0 3 2]); + clear w + else + c = spm_diffeo('push',c,y,d1(1:3)); + end + if nargout>=1 + cls{k1} = c; + end + if tc(k1,4) + N = nifti; + N.dat = file_array(fullfile(pth,['mwc', num2str(k1), nam, '.nii']),... + d1,... + [spm_type('float32') spm_platform('bigend')],... + 0,1,0); + N.mat = M1; + N.mat0 = M1; + N.descrip = ['Jac. sc. warped tissue class ' num2str(k1)]; + create(N); + N.dat(:,:,:) = c*abs(det(M0(1:3,1:3))/det(M1(1:3,1:3))); + end + spm_progress_bar('set',k1); + end + end + spm_progress_bar('Clear'); + + if any(tc(:,3)) + spm_progress_bar('init',Kb,'Writing Warped Tis Cls','Classes completed'); + C = max(C,eps); + s = sum(C,4); + for k1=1:Kb + if tc(k1,3) + N = nifti; + N.dat = file_array(fullfile(pth,['wc', num2str(k1), nam, '.nii']),... + d1,'uint8',0,1/255,0); + N.mat = M1; + N.mat0 = M1; + N.descrip = ['Warped tissue class ' num2str(k1)]; + create(N); + N.dat(:,:,:) = C(:,:,:,k1)./s; + end + spm_progress_bar('set',k1); + end + spm_progress_bar('Clear'); + clear C s + end +end + +if df(2) + y = spm_diffeo('invdef',y,d1,eye(4),M0); + y = spm_extrapolate_def(y,M1); + N = nifti; + N.dat = file_array(fullfile(pth,['y_', nam, '.nii']),... + [d1,1,3],'float32',0,1,0); + N.mat = M1; + N.mat0 = M1; + N.descrip = 'Deformation'; + create(N); + N.dat(:,:,:,:,:) = reshape(y,[d1,1,3]); +end + +return; + + +%========================================================================== +% function [x1,y1,z1] = defs(sol,z,MT,prm,x0,y0,z0,M) +%========================================================================== +function [x1,y1,z1] = defs(sol,z,MT,prm,x0,y0,z0,M) +iMT = inv(MT); +x1 = x0*iMT(1,1)+iMT(1,4); +y1 = y0*iMT(2,2)+iMT(2,4); +z1 = (z0(z)*iMT(3,3)+iMT(3,4))*ones(size(x1)); + +% Eliminate NaNs (see email from Pratik on 01/09/23) +x1 = min(max(x1,1),size(sol{1},1)); +y1 = min(max(y1,1),size(sol{1},2)); +z1 = min(max(z1,1),size(sol{1},3)); + +x1a = x0 + spm_bsplins(sol{1},x1,y1,z1,prm); +y1a = y0 + spm_bsplins(sol{2},x1,y1,z1,prm); +z1a = z0(z) + spm_bsplins(sol{3},x1,y1,z1,prm); +x1 = M(1,1)*x1a + M(1,2)*y1a + M(1,3)*z1a + M(1,4); +y1 = M(2,1)*x1a + M(2,2)*y1a + M(2,3)*z1a + M(2,4); +z1 = M(3,1)*x1a + M(3,2)*y1a + M(3,3)*z1a + M(3,4); +return; + + +%========================================================================== +% function t = transf(B1,B2,B3,T) +%========================================================================== +function t = transf(B1,B2,B3,T) +if ~isempty(T) + d2 = [size(T) 1]; + t1 = reshape(reshape(T, d2(1)*d2(2),d2(3))*B3', d2(1), d2(2)); + t = B1*t1*B2'; +else + t = zeros(size(B1,1),size(B2,1),size(B3,1)); +end +return; + + +%========================================================================== +% function p = likelihoods(f,bf,mg,mn,vr) +%========================================================================== +function p = likelihoods(f,bf,mg,mn,vr) +K = numel(mg); +N = numel(f); +M = numel(f{1}); +cr = zeros(M,N); +for n=1:N + if isempty(bf) + cr(:,n) = double(f{n}(:)); + else + cr(:,n) = double(f{n}(:).*bf{n}(:)); + end +end +p = ones(numel(f{1}),K); +for k=1:K + amp = mg(k)/sqrt((2*pi)^N * det(vr(:,:,k))); + d = bsxfun(@minus,cr,mn(:,k)')/chol(vr(:,:,k)); + p(:,k) = amp*exp(-0.5*sum(d.*d,2)) + eps; +end +return; + + +%========================================================================== +% function dat = decimate(dat,fwhm) +%========================================================================== +function dat = decimate(dat,fwhm) +% Convolve the volume in memory (fwhm in voxels). +lim = ceil(2*fwhm); +x = -lim(1):lim(1); x = spm_smoothkern(fwhm(1),x); x = x/sum(x); +y = -lim(2):lim(2); y = spm_smoothkern(fwhm(2),y); y = y/sum(y); +z = -lim(3):lim(3); z = spm_smoothkern(fwhm(3),z); z = z/sum(z); +i = (length(x) - 1)/2; +j = (length(y) - 1)/2; +k = (length(z) - 1)/2; +spm_conv_vol(dat,dat,x,y,z,-[i j k]); +return; + + +%========================================================================== +% function y1 = affind(y0,M) +%========================================================================== +function y1 = affind(y0,M) +y1 = zeros(size(y0),'single'); +for d=1:3 + y1(:,:,:,d) = y0(:,:,:,1)*M(d,1) + y0(:,:,:,2)*M(d,2) + y0(:,:,:,3)*M(d,3) + M(d,4); +end +return; + + +%========================================================================== +% function x = rgrid(d) +%========================================================================== +function x = rgrid(d) +x = zeros([d(1:3) 3],'single'); +[x1,x2] = ndgrid(single(1:d(1)),single(1:d(2))); +for i=1:d(3) + x(:,:,i,1) = x1; + x(:,:,i,2) = x2; + x(:,:,i,3) = single(i); +end +return; + + +%========================================================================== +% function [P] = clean_gwc(P,level) +%========================================================================== +function [P] = clean_gwc(P,level) +if nargin<2, level = 1; end + +b = P(:,:,:,2); + +% Build a 3x3x3 seperable smoothing kernel +%-------------------------------------------------------------------------- +kx=[0.75 1 0.75]; +ky=[0.75 1 0.75]; +kz=[0.75 1 0.75]; +sm=sum(kron(kron(kz,ky),kx))^(1/3); +kx=kx/sm; ky=ky/sm; kz=kz/sm; + +th1 = 0.15; +if level==2, th1 = 0.2; end +% Erosions and conditional dilations +%-------------------------------------------------------------------------- +niter = 32; +niter2 = 32; +spm_progress_bar('Init',niter+niter2,'Extracting Brain','Iterations completed'); +for j=1:niter + if j>2, th=th1; else, th=0.6; end % Dilate after two its of erosion + for i=1:size(b,3) + gp = double(P(:,:,i,1)); + wp = double(P(:,:,i,2)); + bp = double(b(:,:,i))/255; + bp = (bp>th).*(wp+gp); + b(:,:,i) = uint8(round(bp)); + end + spm_conv_vol(b,b,kx,ky,kz,-[1 1 1]); + spm_progress_bar('Set',j); +end + +% Also clean up the CSF. +if niter2 > 0 + c = b; + for j=1:niter2 + for i=1:size(b,3) + gp = double(P(:,:,i,1)); + wp = double(P(:,:,i,2)); + cp = double(P(:,:,i,3)); + bp = double(c(:,:,i))/255; + bp = (bp>th).*(wp+gp+cp); + c(:,:,i) = uint8(round(bp)); + end + spm_conv_vol(c,c,kx,ky,kz,-[1 1 1]); + spm_progress_bar('Set',j+niter); + end +end + +th = 0.05; +for i=1:size(b,3) + slices = cell(1,size(P,4)); + for k1=1:size(P,4) + slices{k1} = double(P(:,:,i,k1))/255; + end + bp = double(b(:,:,i))/255; + bp = ((bp>th).*(slices{1}+slices{2}))>th; + slices{1} = slices{1}.*bp; + slices{2} = slices{2}.*bp; + + if niter2>0 + cp = double(c(:,:,i))/255; + cp = ((cp>th).*(slices{1}+slices{2}+slices{3}))>th; + slices{3} = slices{3}.*cp; + end + tot = zeros(size(bp))+eps; + for k1=1:size(P,4) + tot = tot + slices{k1}; + end + for k1=1:size(P,4) + P(:,:,i,k1) = uint8(round(slices{k1}./tot*255)); + end +end +spm_progress_bar('Clear'); +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_vol_mimcalc.m",".m","8511","252","function out = cat_vol_mimcalc(job) +% Just a small batch to run imcalc for multiple subject in the same, +% e.g., to apply some function or general correction. +% Extended by coregistrations and BIDS options. +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (http://www.neuro.uni-jena.de) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id: cat_main_gintnormi.m 1834 2021-05-28 14:45:20Z dahnke $ + + SVNid = '$Rev: 1901 $'; + + def.var = {}; + def.verb = 1; + def.cleanup = 1; + def.outdir = {}; + def.BIDSdir = 'derivatives/mimcalc'; + def.prefix = ''; + def.suffix = ''; + def.options.coreg = 0; + + job = cat_io_checkinopt(job,def); + + out = struct(); + + % spm banner + if job.verb + spm('FnBanner',mfilename,SVNid); + end + + % prepare file and directory handling + outdir = cell(size(job.images)); + for ri = 1:numel(job.images) + for si = 1:numel(job.images{ri}) + [~,~,~,d] = checkBIDS(job.images{ri}(si),job.BIDSdir); + outdir{si}{ri} = d{1}; + if ~isempty(job.outdir) && iscell( job.outdir ) && ~isempty( job.outdir{1} ) + fx = strfind(outdir{si}{ri},job.BIDSdir); + if ~isempty(fx) && cat_io_contains(job.BIDSdir,'derivatives') % combine out and BIDsdir + outdir{si}{ri} = fullfile( job.outdir{1} , outdir{si}{ri}(fx(end):end) ); + elseif ~cat_io_contains(job.BIDSdir,'derivatives') % do not add subdirs + outdir{si}{ri} = fullfile(job.outdir{1},job.BIDSdir); + else + outdir{si}{ri} = job.outdir{1}; + end + end + if ~exist(outdir{si}{ri},'dir'), mkdir(outdir{si}{ri}); end + end + end + + for si = 1:numel(job.images{1}) + job2 = rmfield(job,{'prefix','images','suffix','outdir'}); + Pcleanup = cell(size(job.images)); + + % handle zipped BIDS + for ri = 1:numel(job.images) + [pp,ff,ee] = spm_fileparts(job.images{ri}{si}); + job.images{ri}{si} = fullfile(pp,[ff ee]); + cleanup = 0; + if strcmp(ee,'.gz') + if ~exist(fullfile( outdir{si}{ri} , ff),'file') + gunzip(job.images{ri}{si},outdir{si}{ri}); + cleanup = 1; + end + job2.input{ri} = fullfile( outdir{si}{ri} , ff); + else + if ~strcmp( spm_fileparts(job.images{ri}{si}) , outdir{si}{ri} ) && ... + ~exist( spm_file( job.images{ri}{si},'path',outdir{si}{ri}) ,'file') + copyfile(job.images{ri}{si},outdir{si}{ri}); + end + job2.input{ri} = fullfile( outdir{si}{ri} , [ff ee]); + end + if cleanup + Pcleanup{ri} = job2.input{ri}; + end + end + + % filenameparts + [~,ff,ee] = spm_fileparts(job2.input{1}); + + % update prefix + if ~isempty( strfind(job.prefix,'\f') ) + ff = ff(1:end - numel(strfind(job.prefix,'\f'))); + prefix = strrep(job.prefix,'\f',''); + else + prefix = job.prefix; + end + + % update suffix + if ~isempty( strfind(job.suffix,'\b') ) + ff = ff(1:end - numel(strfind(job.suffix,'\b'))); + suffix = strrep(job.suffix,'\b',''); + else + suffix = job.suffix; + end + + job2.output = [prefix,ff,suffix,ee]; + job2.outdir{1} = outdir{si}{1}; + + % call + out1 = my_spm_imcalc(job2); + + % display progress file + out.Pname{si,1} = out1.files{1}; + + % remove temporary files in case of BIDS + if job.cleanup + for ri = 1:numel(Pcleanup) + if ~isempty(Pcleanup{ri}) && exist(Pcleanup{ri},'file'), delete(Pcleanup{ri}); end + end + end + end + + out.Pname(cellfun('isempty',out.Pname)==1) = []; + + % spm banner + if job.verb + spm_progress_bar('Clear') + end +end +function out = my_spm_imcalc(job) + [p,nam,ext] = spm_fileparts(job.output); + if isempty(p) + if isempty(job.outdir) || (iscell(job.outdir) && isempty(job.outdir{1})) + p = pwd; + elseif iscell(job.outdir) + p = job.outdir{1}; + else + p = job.outdir; + end + end + if isempty(nam) + nam = [spm_get_defaults('imcalc.prefix') spm_file(job.input{1},'basename')]; + ext = ['.' spm_file(job.input{1},'ext')]; + end + if isempty(ext) + ext = spm_file_ext; + end + out.files = { fullfile(p,[nam ext]) }; + extra_vars = {}; + if numel(job.var) + extra_vars = { job.var }; + end + options = {}; + if isfield(job,'options') + options = job.options; + end + + if job.options.coreg + % coregistration to support simple processing of T1w./T2w + V = spm_vol(char(job.input)); Vr = V; + for vi = 2:numel(V) + evalc( sprintf(['cormats{vi} = spm_coreg( V(1) , V(vi) , ' ... + 'struct( ''sep'' , [8 4 2 1] , ''fwhm'' , [7 7] , ' ... + '''graphics'' , 0 ) );']) ); + Y = spm_read_vols(Vr(vi)); + Vr(vi).fname = spm_file( Vr(vi).fname , 'path', job.outdir,'prefix','r'); + Vr(vi).mat = spm_matrix(cormats{vi}) \ eval(sprintf('V(vi).mat')); %#ok + spm_write_vol(Vr(vi), Y); + job.input{vi} = Vr(vi).fname; + end + end + + switch lower(job.expression) + case 'approx' + if numel(job.input)>1 + error('cat_vol_mimcalc:approx:filenumber','Only one file per subject allowed') + end + + V = spm_vol(char(job.input)); + Y = spm_read_vols(V); + Y2 = cat_vol_approx(Y); + V2 = V; V2.fname = out.files{1}; + spm_write_vol(V2,Y2); + + cmd = 'spm_image(''display'',''%s'')'; + fprintf('ImCalc-approx Image: %s\n',spm_file(out.files{1},'link',cmd)); + case {'msk-gm','msk-wm','msk-csf','msk-brain','mask-gm','mask-wm','mask-brain',... + 'brainmask','brainmsk','gm-mask','wm-mask','csf-msk'} + if numel(job.input)>1 + error('cat_vol_mimcalc:msk:filenumber','Only one file per subject allowed') + end + + if cat_io_contains( lower(job.expression),'gm') + Pmsk = cellstr([char(cat_get_defaults('extopts.shootingtpm')),',1']); + elseif cat_io_contains( lower(job.expression),'wm') + Pmsk = cellstr([char(cat_get_defaults('extopts.shootingtpm')),',2']); + elseif cat_io_contains( lower(job.expression),'brain') + Pmsk = cat_get_defaults('extopts.brainmask'); + else + error('cat_vol_mimcalc:msk:case','Unknown masking case (use ""msk-gm"",""msk-wm"",""msk-brain"").') + end + + cat_vol_imcalc(char( [ cellstr(job.input) ; Pmsk] ), out.files{1}, 'i1 .* (i2>0.1)'); + + cmd = 'spm_image(''display'',''%s'')'; + fprintf('ImCalc-mask Image: %s\n',spm_file(out.files{1},'link',cmd)); + + otherwise + try + cat_vol_imcalc(char(job.input), out.files{1}, job.expression, options, extra_vars{:}); + + cmd = 'spm_image(''display'',''%s'')'; + fprintf('ImCalc Image: %s\n',spm_file(out.files{1},'link',cmd)); + catch + cat_io_cprintf('err',sprintf('ImCalc Image: %s failed \n',out.files{1})); + out.files{1} = ''; + end + end + + if job.options.coreg + for vi = 2:numel(V) + if exist(Vr(vi).fname,'file') + delete(Vr(vi).fname) + end + end + end +end +function [sfiles,sfilesBIDS,BIDSsub,devdir] = checkBIDS(sfiles,BIDsdirname) + sfilesBIDS = false(size(sfiles)); + BIDSsub = ''; + devdir = cell(size(sfiles)); + + % if BIDS structure is detectected than use only the anat directory + for sfi = numel(sfiles):-1:1 + % detect BIDS directories + sdirs = strsplit(sfiles{sfi},filesep); + if strcmpi(sdirs{end-1}(1:min(4,numel(sdirs{end-1}))),'anat'), ana = 1; else, ana = 0; end + if strcmpi(sdirs{end-2}(1:min(4,numel(sdirs{end-2}))),'ses-'), ses = 1; else, ses = 0; end + if ses==0 + if strcmpi(sdirs{end-2}(1:min(4,numel(sdirs{end-2}))),'sub-'), sub = 1; else, sub = 0; end + else + if strcmpi(sdirs{end-3}(1:min(4,numel(sdirs{end-3}))),'sub-'), sub = 1; else, sub = 0; end + end + + % differentiate between cross and long cases + if ses && sub && ~ana, sfiles(sfi) = []; end + if ses && sub, BIDSsub = sdirs{end-3}; devi = numel(sdirs)-3; end % long + if ~ses && sub, BIDSsub = sdirs{end-2}; devi = numel(sdirs)-2; end % cross + sfilesBIDS(sfi) = sub; + + % setup result directory - without BIDS the default is used + devdir{sfi} = ''; + for di = 2:numel(sdirs)-1 + if sub && di == devi, devdir{sfi} = [devdir{sfi} filesep BIDsdirname]; end % add some directories inbetween + devdir{sfi} = [devdir{sfi} filesep sdirs{di}]; + end + end +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_surf_rename.m",".m","2542","94","function [PO,sinfo] = cat_surf_rename(P,varargin) +% ______________________________________________________________________ +% Rename parts of a cat12 surface filename. +% +% [PO,sinfo] = cat_surf_rename(P,varargin) +% +% P = 'lh.central.test.gii'; +% Pth = cat_surf_rename(P,'dataname','s3tickness'); +% +% Check the help for cat_surf_info for information about fields that +% can be renamed. +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +% Todo: update sinfo! also for other fields! + + + PN = struct(); + if mod(nargin-1,2)==1 + error('paired input'); + else + for i=1:2:numel(varargin) + PN.(varargin{i}) = varargin{i+1}; + end + end + + if ~isstruct(P) + sinfo = cat_surf_info(P); + else + sinfo = P; + end + + + if nargin>0 + FN = fieldnames(PN); + PO = cell(size(sinfo)); + for i=1:numel(sinfo) + + if ~isempty(PN) + for fni=1:numel(FN) + sinfo(i).(FN{fni}) = PN.(FN{fni}); + end + end + + if any(~cellfun('isempty',strfind(FN,'templateresampled'))) + sinfo(i).resampled = 1; + templateresampled = PN.templateresampled; + else + if sinfo(i).resampled==1 + if sinfo(i).template==1 + templateresampled=''; %.template'; + elseif sinfo(i).resampled_32k==1 + templateresampled='.resampled_32k'; + elseif sinfo(i).resampled==1 + if sinfo(i).resampled_32k + templateresampled='.resampled_32k'; + else + templateresampled='.resampled'; + end + end + else + templateresampled=''; + end + end + + if isempty(sinfo(i).name), namedot=''; else namedot='.'; end + if isempty(sinfo(i).side), sidedot=''; else sidedot='.'; end + if isempty(templateresampled), tempdot=''; else tempdot='.'; end + + PO{i} = fullfile(sinfo(i).pp,sprintf('%s%s%s%s%s%s%s%s',... + sinfo(i).preside,... + sinfo(i).side,... + sidedot, ... + sinfo(i).dataname,... + tempdot, ... + templateresampled,... + namedot,... + sinfo(i).name,... + sinfo(i).ee)); + + % .. are now used for derivates! + % if isempty(strfind(sinfo(i).ff,'..')), PO{i} = strrep(PO{i},'..','.'); end + end + else + PO = P; + end +end + ","MATLAB" +"Neurology","ChristianGaser/cat12","cat_vol_groupwise_ls.m",".m","65314","1633","function out = cat_vol_groupwise_ls(Nii, output, prec, w_settings, b_settings, s_settings, ord, use_brainmask, reduce, setCOM, isores) +% Groupwise registration via least squares +% FORMAT out = spm_groupwise_ls(Nii, output, prec, w_settings, b_settings, ... +% s_settings, ord, use_brainmask, reduce, setCOM, isores) +% Nii - a nifti object for two or more image volumes. +% output - a cell array of output options (as character strings). +% 'wimg - write realigned images to disk +% 'avg' - return average in out.avg +% 'wavg' - write average to disk, and return filename in out.avg +% 'def' - return mappings from average to individuals in out.def +% 'wdef' - write mappings to disk, and return filename in out.def +% 'div' - return divergence of initial velocities in out.div +% 'wdiv' - write divergence images to disk and return filename +% 'jac' - return Jacobian determinant maps in out.jac +% 'wjac' - write Jacobians to disk and return filename +% 'vel' - return initial velocities +% 'wvel' - write velocities to disk and return filename +% 'rigid' - return rigid-body transforms +% +% prec - reciprocal of noise variance on images. +% w_swttings - regularisation settings for warping. +% b_settings - regularisation settings for nonuniformity field. +% s_settings - number of time steps for geodesic shooting. +% ord - degree of B-spline interpolation used for sampling images. +% use_brainmask - use initial brainmask to obtain better registration +% reduce - reduce bounding box at final resolution level because usually +% there is a lot of air around the head after registration of +% multiple scans +% setCOM - set origin using center-of-mass +% isores - force isotropic average resolution +% (0-default,1-best,2-worst,3-optimal,<0-defines resolution) +% +%_______________________________________________________________________ +% Copyright (C) 2012 Wellcome Trust Centre for Neuroimaging +% +% modified version (added masked registration) of +% John Ashburner +% spm_groupwise_ls.m 6844 2016-07-28 20:02:34Z john $ +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id cat_vol_groupwise_ls.m $ + +% Get handles to NIfTI data +%----------------------------------------------------------------------- +if ~isa(Nii,'nifti') + if isa(Nii,'char') + Nii = nifti(Nii); + else + error('Unrecognised NIfTI images'); + end +end + +% Specify default settings +%----------------------------------------------------------------------- +if nargin<3, prec = NaN; end +if nargin<4, w_settings = [0 1 80 20 80]; end +if nargin<5, b_settings = [0 0 1e6]; end +if nargin<6, s_settings = 6; end +if nargin<7, ord = [3 3 3 0 0 0]; end +if nargin<8, use_brainmask = 1; end +if nargin<9, reduce = 1; end +if nargin<10, setCOM = 1; end +if nargin<11, isores = 0; end % force isotropic average resolution (<0-res,0-default,1-best,2-worst,3-optimal) + +% If settings are not subject-specific, then generate +%----------------------------------------------------------------------- +if size(w_settings,1)==1, w_settings = repmat(w_settings,numel(Nii),1); end +if size(s_settings,1)==1, s_settings = repmat(s_settings,numel(Nii),1); end +if size(b_settings,1)==1, b_settings = repmat(b_settings,numel(Nii),1); end +if numel(prec) ==1, prec = repmat(prec,1,numel(Nii)); end + +% scale all images to a global mean of 100 to ensure consistent weighting of regularisation +for i=1:numel(Nii) + g = spm_global(spm_vol(Nii(i).dat.fname)); + Nii(i).dat.scl_slope = 100/g*Nii(i).dat.scl_slope; + Nii(i).dat.scl_inter = 100/g*Nii(i).dat.scl_inter; +end + +% correct origin using COM +if setCOM + for i=1:numel(Nii) + M0 = spm_imatrix(Nii(i).mat); + M = spm_imatrix(cat_vol_set_com(spm_vol(Nii(i).dat.fname))); + M0(1:3) = M0(1:3) - M(1:3); + Nii(i).mat = spm_matrix(M0); + fprintf('\n'); + end + clear M0 M; +end + +fprintf('\n------------------------------------------------------------------------\n'); + +% Determine noise estimates when unknown +for i=1:numel(Nii) + if ~isfinite(prec(i)) + prec0 = spm_noise_estimate(Nii(i)); + fprintf('Estimated noise sd for ""%s"" = %g\n', Nii(i).dat.fname, prec0); + if isfinite(prec0) + prec(i) = prec0.^(-2); + end + end +end + +% set all values to constant of 1E-3 (empirically estimated) if NaN/Inf values were +% found in noise estimation +prec(find(~isfinite(prec))) = 1E-3; + +% Basis functions for algebra of rigid-body transform +%----------------------------------------------------------------------- +B = se3_basis; + +% Set boundary conditions +%----------------------------------------------------------------------- +spm_field('boundary',1); % Bias correction - Neumann +spm_diffeo('boundary',0); % Diffeomorphism - circulant + +% Computations for figuring out how many grid levels are likely to work +%----------------------------------------------------------------------- +d = [0 0 0]; +for i=1:numel(Nii) + dm = [size(Nii(i).dat) 1]; + d = max(d, dm(1:3)); +end +if isores<0 + d = -isores; +else + d = min(d); +end + +% Specify highest resolution data +%----------------------------------------------------------------------- +clear pyramid +pyramid(max(ceil(log2(d)-log2(4)),1)) = struct('d',[1 1 1],'mat',eye(4),'img',[]); +for i=numel(Nii):-1:1 + pyramid(1).img(i).f = single(Nii(i).dat(:,:,:,1,1)); + pyramid(1).img(i).mat = Nii(i).mat; +end + +% Generate sucessively lower resolution versions +%----------------------------------------------------------------------- +for level = 2:numel(pyramid) + for i=numel(Nii):-1:1 + pyramid(level).img(i).f = spm_diffeo('restrict',pyramid(level-1).img(i).f); + pyramid(level).img(i).f(~isfinite(pyramid(level).img(i).f)) = 0; + s1 = [size(pyramid(level-1).img(i).f) 1]; + s2 = [size(pyramid(level ).img(i).f) 1]; + s = s1(1:3)./s2(1:3); + pyramid(level).img(i).mat = pyramid(level-1).img(i).mat*[diag(s), (1-s(:))*0.5; 0 0 0 1]; + clear s1 s2 + end +end + +% Convert all image data into B-spline coefficients (for interpolation) +%----------------------------------------------------------------------- +for level=1:numel(pyramid) + for i=1:numel(Nii) + pyramid(level).img(i).f = spm_diffeo('bsplinc',pyramid(level).img(i).f,ord); + end +end + +% Adjust precision for number of subjects +%----------------------------------------------------------------------- +%nscan = numel(pyramid(1).img); +%prec = prec*(nscan-1)/nscan; + +% Stuff for figuring out the orientation, dimensions etc of the highest resolution template +%----------------------------------------------------------------------- +Mat0 = cat(3,pyramid(1).img.mat); +if isores ~= 0 + %% RD20220217: use best resolution and create an isotropic output + mati = spm_imatrix(Mat0); + vx_vol = mati(7:9); + switch isores + case 1 + vx_vol = min(vx_vol); + case 2 % need at least something like 2 mm + vx_vol = min(1.5,max(vx_vol)); + case 3 + % optimal - keep the volume similar but move it a bit torwards one + % eg. 1.0x1.0x3.0 > 1.2, 0.5x0.5x1.0 > 0.7 + vx_vol = floor( (prod(abs(vx_vol)).^(1/3) ).^0.5 * 10 ) / 10; + otherwise + vx_vol = repmat(-isores,1,3); + end + cdim = mati(7:9) ./ vx_vol; + mati(7:9) = vx_vol; + Mat0 = spm_matrix(mati); +else + cdim = [1 1 1]; +end +dims = zeros(numel(Nii),3); +for i=1:size(dims,1) + dims(i,:) = round(Nii(i).dat.dim(1:3) .* cdim); +end +[pyramid(1).mat,pyramid(1).d] = compute_avg_mat(Mat0,dims); +pyramid(1).sc = abs(det(pyramid(1).mat(1:3,1:3))); +pyramid(1).prec = prec; + +% Figure out template info for each sucessively lower resolution version +%----------------------------------------------------------------------- +for level=2:numel(pyramid) + pyramid(level).d = ceil(pyramid(level-1).d/2); + s = pyramid(level-1).d./pyramid(level).d; + pyramid(level).mat = pyramid(level-1).mat*[diag(s), (1-s(:))*0.5; 0 0 0 1]; + + % Relative scaling of regularisation + pyramid(level).sc = abs(det(pyramid(level).mat(1:3,1:3))); + pyramid(level).prec = prec*sqrt(pyramid(level).sc/pyramid(1).sc); % Note that the sqrt is ad hoc +end + + +nlevels = numel(pyramid); +mp2rage = 0; +brainmask = []; + +% check whether reduce option is enabled for non-linear registration +if all(isfinite(w_settings(:))) && reduce + reduce = 0; + use_brainmask = 0; + fprintf('Reducing bounding box is not supported for non-linear registration and will be disabled.\n'); +end + +for level=nlevels:-1:1 % Loop over resolutions, starting with the lowest + + % Collect data + %----------------------------------------------------------------------- + img = pyramid(level).img; + M_avg = pyramid(level).mat; + d = pyramid(level).d; + vx = sqrt(sum(pyramid(level).mat(1:3,1:3).^2)); + sc = pyramid(level).sc; + prec = pyramid(level).prec; + + if level==nlevels + % If lowest resolution, initialise parameter estimates to zero + %----------------------------------------------------------------------- + clear param + bias_est = zeros(numel(Nii),1); + for i=numel(Nii):-1:1 + bias_est(i) = log(mean(mean(mean(img(i).f)))); + end + bias_est = bias_est - mean(bias_est); + for i=numel(Nii):-1:1 + param(i) = struct('R', eye(4), 'r', zeros(6,1),... + 'bias',[], 'eb',0,... + 'v0', [], 'ev',0, 'y',[], 'J',[],... + 's2', 1, 'ss',1); + + if all(isfinite(b_settings(i,:))) + param(i).bias = zeros(size(img(i).f),'single')+bias_est(i); + end + + if all(isfinite(w_settings(i,:))) + param(i).v0 = zeros([d 3],'single'); + param(i).y = identity(d); + param(i).J = repmat(reshape(eye(3,'single'),[1 1 1 3 3]),[d(1:3),1,1]); + end + + end + else + % Initialise parameter estimates by prolongation of previous lower resolution versions. + %----------------------------------------------------------------------- + for i=1:numel(Nii) + + if all(isfinite(b_settings(i,:))) + vxi = sqrt(sum(img(i).mat(1:3,1:3).^2)); + spm_diffeo('boundary',1); + param(i).bias = spm_diffeo('resize',param(i).bias,size(img(i).f)); + spm_diffeo('boundary',0); + bmom = spm_field('vel2mom', param(i).bias, [vxi b_settings(i,:)*sc]); + param(i).eb = sum(bmom(:).*param(i).bias(:)); + clear bmom + else + param(i).bias = []; + param(i).eb = 0; + end + + if all(isfinite(w_settings(i,:))) + param(i).v0 = spm_diffeo('resize',param(i).v0,d); + for i1=1:3 + s = pyramid(level).d(i1)/pyramid(level+1).d(i1); + param(i).v0(:,:,:,i1) = param(i).v0(:,:,:,i1)*s; + end + m0 = spm_diffeo('vel2mom',param(i).v0,[vx w_settings(i,:)*sc]); + param(i).ev = sum(sum(sum(sum(m0.*param(i).v0)))); + clear m0 + else + param(i).v0 = []; + param(i).ev = 0; + param(i).y = []; + param(i).J = []; + end + end + + % Remove lower resolution versions that are no longer needed + pyramid = pyramid(1:(end-1)); + end + + spm_plot_convergence('Clear'); + spm_plot_convergence('Init',['Optimising (level ' num2str(level) ')'],'Objective Function','Step'); + for iter=1:(2*2^(level-1)+1) % / 8 % Use more iterations at lower resolutions (its faster, so may as well) ############# RD20220213 marked + % RD20220213: markings for future experiments + % I marked some parts of using bias correction and deformations, + % because they are interesting in case case of development, adaptions + % of the scanner protocol or device itself. + % Soft, very low frequency changes could be interesting. However, + % the necessary adaptions of the long pipeline are curenty to much + % for this quite rare case that would remain still complicated. + % Changes would need extra flag for the protocol case. + % The developmental changes would require separate processing of the + % average (with deformation) and of the single time-points (without + % deformations) to get correct measurements. + + + % Compute deformations from initial velocities + %----------------------------------------------------------------------- + + for i=1:numel(param) + if all(isfinite(w_settings(i,:))) + [param(i).y,param(i).J] = spm_shoot3d(param(i).v0,[vx w_settings(i,:)*sc],s_settings(i,:)); + end + end + + if true + % Rigid-body + %======================================================================= + % Recompute template data (with gradients) + %----------------------------------------------------------------------- + [mu,ss,nvox,D] = compute_mean(pyramid(level), param, ord); + % for i=1:numel(param), fprintf(' %12.5g %12.5g %12.5g', prec(i)*ss(i), param(i).eb, param(i).ev); end; fprintf(' 0\n'); + + if (level == 1) && (iter == 1) + vx_vol = sqrt(sum(pyramid(level).mat(1:3,1:3).^2)); + + % reduce bounding box at final resolution level + if reduce + fprintf('Reduce bounding box for final resolution level.\n'); + + % intensity normalization using 99% of data (to ignore outliers) + [msk,hth] = cat_stat_histth(smooth3(mu),0.99,0); + msk = (msk - hth(1)) ./ abs(diff(hth)); + + % masking (borrowed from head-trimming) + msk = smooth3(msk)>0.05; + msk = cat_vol_morph(msk,'do',2,vx_vol); + msk = cat_vol_morph(msk,'l',[10 0.1]); + [~,redB] = cat_vol_resize(mu,'reduceBrain',vx_vol,2,msk); + + % correct mat information and dimensions + mati = spm_imatrix(pyramid(level).mat); matio = mati; + mati(1:3) = mati(1:3) + mati(7:9).*(redB.BB(1:2:end) - 1); + pyramid(level).mat = spm_matrix(mati); + pyramid(level).d = redB.sizeTr; + + % update some size-dependent parameters + M_avg = pyramid(level).mat; + d = pyramid(level).d; + + % re-estimate mu using new dimensions + [mu,ss,nvox,D] = compute_mean(pyramid(level), param, ord); + end + + % create mask at final level to allow masked registration + if use_brainmask + fprintf('Use initial brainmask for final resolution level.\n'); + + PG = cat_get_defaults('extopts.T1'); + PB = cat_get_defaults('extopts.brainmask'); + + [pth,nam] = fileparts(Nii(1).dat.fname); + nam = fullfile(pth,['avg_' nam '.nii']); + Nio = nifti; + Nio.dat = file_array(nam,size(mu),'float32',0,1,0); + Nio.mat = M_avg; + Nio.mat0 = Nio.mat; + Nio.mat_intent = 'Aligned'; + Nio.mat0_intent = Nio.mat_intent; + Nio.descrip = sprintf('Average of %d', numel(param)); + create(Nio); + Nio.dat(:,:,:) = mu; + PF = nam; + + try + % map brainmask or use brainsmask in cases of skull-stripped data + [~, brainmask, ~, ~, ~, mp2rage] = cat_long_APP(PF,PG,PB); + brainmask(~isfinite(brainmask)) = 0; + catch + fprintf('Creation of brainmask failed. No brainmask will be used for final registration.\n'); + use_brainmask = 0; + end + + if mp2rage + % In case of MP2RAGE data we apply our MP2RAGE background + % correction on the input data (that is a copy of the RAW) + % and finally recall this function. + + % mp2rage preprocessing options + fprintf('Run MP2Rage preprocessing.\n\n') + mp2job.ofiles = {Nii(:).dat.fname}'; + mp2job.files = {Nii(:).dat.fname}'; % list of MP2Rage images + mp2job.headtrimming = 0; % trimming to brain or head (*0-none*,1-brain,2-head) + mp2job.biascorrection = 1; % biascorrection (0-no,1-light(SPM60mm),2-average(SPM60mm+X,3-strong(SPM30+X)) ####### + mp2job.skullstripping = 3; % skull-stripping (0-no, 1-SPM, 2-optimized, 3-*background-removal*) + mp2job.logscale = 0; % use log/exp scaling for more equally distributed + % tissues (0-none, 1-log, -1-exp, inf-*auto*); + mp2job.intnorm = 0; % contrast normalization using the tan of GM normed + % values with values between 1.0 - 2.0 for light to + % strong adaptiong (0-none, 1..2-manuel, -0..-2-*auto*) + mp2job.restoreLCSFnoise = 1; % restore values below zero (lower CSF noise) + mp2job.prefix = ''; % filename prefix (strong with PARA for parameter + % depending naming, e.g. ... ) + mp2job.spm_preprocessing = 2; % do SPM preprocessing (0-no, 1-yes (if required), 2-always) + mp2job.spm_cleanupfiles = 1; % remove temporary files + mp2job.report = 0; % create a report + mp2job.verb = 1; % be verbose (0-no,1-yes,2-details) + + % call mp2rage preprocessing + cat_vol_mp2rage(mp2job); + + % load the corrected images + Nii = nifti({Nii(:).dat.fname}'); + + % recalc this batch with the background corrected data and return + out = cat_vol_groupwise_ls(Nii, output, prec, w_settings, b_settings, s_settings, ord, use_brainmask, reduce, setCOM, isores); + return + + end + + % re-estimate mu using new dimensions + if use_brainmask + [brainmask,redB] = cat_vol_resize(brainmask,'reduceBrain',vx_vol, 25 ,brainmask>0.5); % area around brainmask should cover full head 20-30 mm + clear msk + + % correct mat information and dimensions + mati = spm_imatrix(pyramid(level).mat); matio = mati; + mati(1:3) = mati(1:3) + mati(7:9).*(redB.BB(1:2:end) - 1); + pyramid(level).mat = spm_matrix(mati); + pyramid(level).d = redB.sizeTr; + + % update some size-dependent parameters + M_avg = pyramid(level).mat; + d = pyramid(level).d; + + [mu,ss,~,D] = compute_mean(pyramid(level), param, ord); + end + + clear Ym + spm_plot_convergence('Clear'); + spm_plot_convergence('Init',['Optimising (level ' num2str(level) ') with brainmask'],'Objective Function','Step'); + end + end + + % Compute objective function (approximately) + %----------------------------------------------------------------------- + ll = 0; + for i=1:numel(param) + param(i).ss = ss(i); + ll = ll - 0.5*prec(i)*param(i).ss - 0.5*param(i).eb - 0.5*param(i).ev; + end + spm_plot_convergence('set',ll); + + for i=1:numel(img) + % Gauss-Newton update of logs of rigid-body matrices + %----------------------------------------------------------------------- + [R,dR] = spm_dexpm(param(i).r,B); + M = img(i).mat\R*M_avg; + dtM = abs(det(M(1:3,1:3))); + [x1a,x2a,x3a] = ndgrid(1:d(1),1:d(2),1); + + Hess = zeros(12); + gra = zeros(12,1); + for m=1:d(3) + if all(isfinite(w_settings(i,:))) + dt = spm_diffeo('det',param(i).J(:,:,m,:,:)); + y = transform_warp(M,param(i).y(:,:,m,:)); + else + dt = ones(d(1:2),'single'); + y = zeros([d(1:2) 1 3],'single'); + [y(:,:,1),y(:,:,2),y(:,:,3)] = ndgrid(single(1:d(1)),single(1:d(2)),single(m)); + y = transform_warp(M,y); + end + + f = spm_diffeo('bsplins',img(i).f,y,ord); + + if all(isfinite(b_settings(i,:))) + ebias = exp(spm_diffeo('pullc',param(i).bias,y)); + else + ebias = ones(size(f),'single'); + end + + b = f-mu(:,:,m).*ebias; + + msk = isfinite(b); + % use different mask for rigid body registration if brainmask is defined + if (level == 1) && use_brainmask && ~isempty(brainmask) + mskr = isfinite(b) & (brainmask(:,:,m) > 0.25); + else + mskr = isfinite(b); + end + + if ~all(isfinite(w_settings(i,:))) + ebias = ebias(mskr); + b = b(mskr); + else + ebias = ebias(msk); + b = b(msk); + end + + if ~all(isfinite(w_settings(i,:))) + % No need to account for the nonlinear warps when estimating + % the rigid body transform. + x1 = x1a(mskr); + x2 = x2a(mskr); + x3 = x3a(mskr)*m; + d1 = D{1}(:,:,m); + d2 = D{2}(:,:,m); + d3 = D{3}(:,:,m); + + else + % The rigid-body transform should register the nonlinearly warped + % template to match the individual. + + + % Positions where the template voxels are mapped to via the nonlinear warp. + x1 = param(i).y(:,:,m,1); x1 = x1(msk); + x2 = param(i).y(:,:,m,2); x2 = x2(msk); + x3 = param(i).y(:,:,m,3); x3 = x3(msk); + + + % Gradients of nonlinear warped template, warped back to its original space. + % Multiply by transpose of inverse of Jacobian determinants. + % First, get the Jacobians of the nonlinear warp. + J = reshape(param(i).J(:,:,m,:,:),[d(1:2) 3 3]); + + % Reciprocal of the determinants. Note that for the gradients (gra) + % idt cancels out with dt. For the Hessians (Hess), it doesn't. + idt = 1./max(dt,0.001); + + % Compute cofactors of Jacobians, where cJ = det(J)*inv(J) + cJ = zeros(size(J),'single'); + cJ(:,:,1,1) = J(:,:,2,2).*J(:,:,3,3) - J(:,:,2,3).*J(:,:,3,2); + cJ(:,:,1,2) = J(:,:,1,3).*J(:,:,3,2) - J(:,:,1,2).*J(:,:,3,3); + cJ(:,:,1,3) = J(:,:,1,2).*J(:,:,2,3) - J(:,:,1,3).*J(:,:,2,2); + + cJ(:,:,2,1) = J(:,:,2,3).*J(:,:,3,1) - J(:,:,2,1).*J(:,:,3,3); + cJ(:,:,2,2) = J(:,:,1,1).*J(:,:,3,3) - J(:,:,1,3).*J(:,:,3,1); + cJ(:,:,2,3) = J(:,:,1,3).*J(:,:,2,1) - J(:,:,1,1).*J(:,:,2,3); + + cJ(:,:,3,1) = J(:,:,2,1).*J(:,:,3,2) - J(:,:,2,2).*J(:,:,3,1); + cJ(:,:,3,2) = J(:,:,1,2).*J(:,:,3,1) - J(:,:,1,1).*J(:,:,3,2); + cJ(:,:,3,3) = J(:,:,1,1).*J(:,:,2,2) - J(:,:,1,2).*J(:,:,2,1); + + % Premultiply gradients by transpose of inverse of J + d1 = idt.*(cJ(:,:,1,1).*D{1}(:,:,m) + cJ(:,:,2,1).*D{2}(:,:,m) + cJ(:,:,3,1).*D{3}(:,:,m)); + d2 = idt.*(cJ(:,:,1,2).*D{1}(:,:,m) + cJ(:,:,2,2).*D{2}(:,:,m) + cJ(:,:,3,2).*D{3}(:,:,m)); + d3 = idt.*(cJ(:,:,1,3).*D{1}(:,:,m) + cJ(:,:,2,3).*D{2}(:,:,m) + cJ(:,:,3,3).*D{3}(:,:,m)); + + clear idt cJ + end + + if ~all(isfinite(w_settings(i,:))) + dt = dt(mskr); + d1 = d1(mskr).*ebias; + d2 = d2(mskr).*ebias; + d3 = d3(mskr).*ebias; + else + dt = dt(msk); + d1 = d1(msk).*ebias; + d2 = d2(msk).*ebias; + d3 = d3(msk).*ebias; + end + + % Derivatives w.r.t. an affine transform + A = [x1(:).*d1(:) x1(:).*d2(:) x1(:).*d3(:) ... + x2(:).*d1(:) x2(:).*d2(:) x2(:).*d3(:) ... + x3(:).*d1(:) x3(:).*d2(:) x3(:).*d3(:) ... + d1(:) d2(:) d3(:)]; + + if ~all(isfinite(w_settings(i,:))) + Hess = Hess + dtM*double(A'*A); + gra = gra + dtM*double(A'*b); + else + Hess = Hess + dtM*double(A'*bsxfun(@times,A,dt)); + gra = gra + dtM*double(A'*(dt.*b)); + end + + clear dt y f ebias b msk x1 x2 d1 d2 d3 A + end + + % For converting from derivatives w.r.t. an affine transform + % to derivatives w.r.t. the rigid-body transform parameters. + dA = zeros(12,6); + for m=1:6 + tmp = (R*M_avg)\dR(:,:,m)*M_avg; + dA(:,m) = reshape(tmp(1:3,:),12,1); + end + + Hess = dA'*Hess*dA*prec(i); + gra = dA'*gra*prec(i); + + % only use Hessian and gra if finite + if all(isfinite(Hess(:))) && all(isfinite(gra(:))) + param(i).r = param(i).r - Hess\gra; + else + fprintf('Warning: Hessian matrix could not be estimated for %s\n',Nii(i).dat.fname); + return + end + + clear R dR M x1a x2a dA tmp Hess gra + end + clear mu D + + % Mean correct the rigid-body transforms and compute exponentials + % Note that this gives us a Karcher mean. + %----------------------------------------------------------------------- + r_avg = mean(cat(2,param.r),2); + for i=1:numel(param) + param(i).r = param(i).r-r_avg; + param(i).R = spm_dexpm(param(i).r,B); + end + clear r_avg + end + + if any(all(isfinite(b_settings),2)) %&& level>4 %######## RD20220213 marked + % Bias field + %fprintf('Bias %d-%d\n',level,iter); % ######## RD20220213 marked + %======================================================================= + % Recompute template data + %----------------------------------------------------------------------- + [mu,ss] = compute_mean(pyramid(level), param, ord); + % for i=1:numel(param), fprintf(' %12.5g %12.5g %12.5g', prec(i)*ss(i), param(i).eb, param(i).ev); end; fprintf(' 1\n'); + + % Compute objective function (approximately) + %----------------------------------------------------------------------- + ll = 0; + for i=1:numel(param) + param(i).ss = ss(i); + ll = ll - 0.5*prec(i)*param(i).ss - 0.5*param(i).eb - 0.5*param(i).ev; + end + spm_plot_convergence('set',ll); + + for i=1:numel(img) + if all(isfinite(b_settings(i,:))) + % Gauss-Newton update of logs of bias field. + % Note that 1st and second derivatives are computed in template space + % and subsequently pushed back to native space for re-estimation. + %----------------------------------------------------------------------- + M = img(i).mat\param(i).R*M_avg; + gra = zeros(d,'single'); + Hess = zeros(d,'single'); + + for m=1:d(3) + if all(isfinite(w_settings(i,:))) + dt = spm_diffeo('det',param(i).J(:,:,m,:,:))*abs(det(M(1:3,1:3))); + y = transform_warp(M,param(i).y(:,:,m,:)); + else + dt = ones(d(1:2),'single')*abs(det(M(1:3,1:3))); + y = zeros([d(1:2) 1 3],'single'); + [y(:,:,1),y(:,:,2),y(:,:,3)] = ndgrid(single(1:d(1)),single(1:d(2)),m); + y = transform_warp(M,y); + end + + f = spm_diffeo('bsplins',img(i).f,y,ord); + ebias = exp(spm_diffeo('pullc',param(i).bias,y)); + + msk = isfinite(f) & isfinite(ebias); + smu = mu(:,:,m).*ebias; + f(~msk) = 0; + smu(~msk) = 0; + gra(:,:,m) = smu.*(smu-f).*dt*prec(i); + Hess(:,:,m) = smu.*smu.*dt*prec(i); + + clear dt y f ebias msk smu + end + + % Push derivatives to native space + %----------------------------------------------------------------------- + if all(isfinite(w_settings(i,:))) + y = transform_warp(M,param(i).y); + else + y = transform_warp(M,identity(d)); + end + gra = spm_diffeo('push',gra,y,size(param(i).bias)); + Hess = spm_diffeo('push',Hess,y,size(param(i).bias)); + clear y + + vxi = sqrt(sum(img(i).mat(1:3,1:3).^2)); + gra = gra + spm_field('vel2mom', param(i).bias, [vxi b_settings(i,:)*sc]); + param(i).bias = param(i).bias - spm_field(Hess,gra,[vxi b_settings(i,:)*sc 2 2]); % Gauss-Newton update + clear M gra Hess + + % Compute part of objective function + %----------------------------------------------------------------------- + bmom = spm_field('vel2mom', param(i).bias, [vxi b_settings(i,:)*sc]); + param(i).eb = sum(bmom(:).*param(i).bias(:)); + clear bmom vxi + end + end + clear mu + end + + if any(all(isfinite(w_settings),2)) %&& level>4 % ########## RD20220213 marked + % Deformations + %======================================================================= + % Recompute template data (with gradients) + %----------------------------------------------------------------------- + %fprintf('Defs %d-%d\n',level,iter); %########## RD20220213 marked + [mu,ss,nvox,D] = compute_mean(pyramid(level), param, ord); + % for i=1:numel(param), fprintf(' %12.5g %12.5g %12.5g', prec(i)*ss(i), param(i).eb, param(i).ev); end; fprintf(' 2\n'); + + % Compute objective function (approximately) + %----------------------------------------------------------------------- + ll = 0; + for i=1:numel(param) + param(i).ss = ss(i); + ll = ll - 0.5*prec(i)*param(i).ss - 0.5*param(i).eb - 0.5*param(i).ev; + end + spm_plot_convergence('set',ll); + + for i=1:numel(img) % Update velocity for each image in turn + if all(isfinite(w_settings(i,:))) + % Gauss-Newton update of velocity fields. + % These are parameterised in template space. + %----------------------------------------------------------------------- + gra = zeros([d,3],'single'); + Hess = zeros([d,6],'single'); + M = img(i).mat\param(i).R*M_avg; + + for m=1:d(3) + dt = spm_diffeo('det',param(i).J(:,:,m,:,:))*abs(det(M(1:3,1:3))); + y = transform_warp(M,param(i).y(:,:,m,:)); + f = spm_diffeo('bsplins',img(i).f,y,ord); + + if all(isfinite(b_settings(i,:))) + ebias = exp(spm_diffeo('pullc',param(i).bias,y)); + else + ebias = ones(size(f),'single'); + end + + b = f-mu(:,:,m).*ebias; + msk = ~isfinite(b); + b(msk) = 0; + dt(msk) = 0; + + d1 = D{1}(:,:,m).*ebias; % Spatial gradient of -b. + d2 = D{2}(:,:,m).*ebias; + d3 = D{3}(:,:,m).*ebias; + + gra(:,:,m,1) = b.*d1.*dt; % 1st derivatives of objecive function + gra(:,:,m,2) = b.*d2.*dt; % w.r.t. velocity field. + gra(:,:,m,3) = b.*d3.*dt; + + Hess(:,:,m,1) = d1.*d1.*dt; % 2nd derivatives (approximately) of + Hess(:,:,m,2) = d2.*d2.*dt; % objective function w.r.t. velocity. + Hess(:,:,m,3) = d3.*d3.*dt; + Hess(:,:,m,4) = d1.*d2.*dt; + Hess(:,:,m,5) = d1.*d3.*dt; + Hess(:,:,m,6) = d2.*d3.*dt; + + clear dt y f ebias b msk d1 d2 d3 + end + + param(i).y = []; % No longer needed, so free up some memory. + param(i).J = []; + + Hess = Hess*prec(i); + gra = gra*prec(i); + + gra = gra + spm_diffeo('vel2mom',param(i).v0,[vx w_settings(i,:)*sc]); + param(i).v0 = param(i).v0 - spm_diffeo('fmg',Hess, gra, [vx w_settings(i,:)*sc 2 2]); % Gauss-Newton + + clear Hess gra + end + end + clear mu D + + % If regularisation is the same for each image (apart from scaling), then adjust velocities. + %----------------------------------------------------------------------- + if sum(var(diag(sqrt(sum(w_settings.^2,2)))\w_settings,0,1)./(mean(w_settings,1).^2+eps)) < 1e-12 + wt = sqrt(sum(w_settings.^2,2)); + wt = wt/sum(wt); + v0_mean = zeros(size(param(1).v0),'single'); + for i=1:numel(param) + v0_mean = v0_mean + wt(i)*param(i).v0; + end + for i=1:numel(param) + param(i).v0 = param(i).v0 - v0_mean; + end + clear v0_mean + end + + % Compute part of objective function + %----------------------------------------------------------------------- + for i=1:numel(param) + if all(isfinite(w_settings(i,:))) + m0 = spm_diffeo('vel2mom',param(i).v0,[vx w_settings(i,:)*sc]); + param(i).ev = sum(sum(sum(sum(m0.*param(i).v0)))); + clear m0 + end + end + + end + end +end + +% Figure out what needs to be saved +%----------------------------------------------------------------------- +need_avg = false; +need_vel = false; +need_def = false; +need_div = false; +need_jac = false; +need_mom = false; +need_bia = false; +need_wimg= false; + +if any(strcmp('avg',output)) || any(strcmp('wavg',output)), need_avg = true; end +if any(strcmp('vel',output)) || any(strcmp('wvel',output)), need_vel = true; end +if any(strcmp('div',output)) || any(strcmp('wdiv',output)), need_div = true; end +if any(strcmp('def',output)) || any(strcmp('wdef',output)), need_def = true; end +if any(strcmp('jac',output)) || any(strcmp('wjac',output)), need_jac = true; end +if any(strcmp('mom',output)) || any(strcmp('wmom',output)), need_mom = true; end +if any(strcmp('bia',output)) || any(strcmp('wbia',output)), need_bia = true; end +if any(strcmp('wimg',output)), need_wimg= true; end + +out = struct; +if need_avg || need_def || need_jac + for i=numel(param):-1:1 + if all(isfinite(w_settings(i,:))) + [param(i).y,param(i).J] = spm_shoot3d(param(i).v0,[vx w_settings(i,:)*sc],s_settings(i,:)); + end + end +end + +clear out +out.mat = M_avg; + +if any(strcmp('rigid',output)) + out.rigid = {}; + for i=1:numel(param) + out.rigid{i} = param(i).R; + end +end + + +%% final processing and creation of the output +mu = compute_mean(pyramid(1), param, ord); +vol = get_transformed_images(pyramid(1), param, ord); + +% do some final bias correction between scans which is more effective and also masked +bias_nits = 8; +bias_fwhm = 60; +bias_reg = 1e-6; +bias_lmreg = 1e-6; +for i=1:numel(param) + tmp_vol = vol(:,:,:,i); + ind0 = tmp_vol == 0; % keep defacing/masking + + % RD202508: remove extrem outliers in thickness phantom (Rusak et al., 2021) + % there are still issues in the Rusak resuls + if 1 + minmax = [prctile(tmp_vol(:),0.1),prctile(tmp_vol(:),99.9)]; + tmp_vol( tmp_vol < minmax(1) ) = minmax(1); + tmp_vol( tmp_vol > minmax(2) ) = minmax(2); + % median fitler to remove extrem outliers (in Rusak) + % simple scaling by mean and filtering + avgint = cat_stat_nanmean(tmp_vol(:)) * 10; + tmp_vol = cat_vol_median3(tmp_vol / avgint, ... + true(size(tmp_vol)), true(size(tmp_vol)), 1) * avgint; + end + + % RD202508: old outlier removal try to avoid this as this may have side effects with the bias correction + [tmp_vol th99] = cat_stat_histth(tmp_vol,[0.999 0.999]); + tmp_vol = tmp_vol - th99(1); + + % if > 0.5% of values are zero then set these areas back to zero + if 100*sum(ind0(:))/numel(tmp_vol) > 0.5 + tmp_vol(ind0) = 0; + end + + % RD202508: Without BC the values in Rusak are extremly high scaled + % The bias correction therefore create similar intensities for each time points + vol(:,:,:,i) = bias_correction(mu,tmp_vol,[], pyramid(1), bias_nits, bias_fwhm, bias_reg, bias_lmreg); +end + +% correct if minimum is < 0 +min_vol = min(vol(:)); +if min_vol < 0 + for i=1:numel(param) + tmp_vol = vol(:,:,:,i); + ind0 = tmp_vol == 0; % keep defacing/masking + + tmp_vol = tmp_vol - min_vol; + + % if > 0.5% of values are zero then set these areas back to zero + if 100*sum(ind0(:))/numel(tmp_vol) > 0.5 + tmp_vol(ind0) = 0; + end + + vol(:,:,:,i) = tmp_vol; + + end +else + if min_vol < 0, vol = vol - min_vol; end +end + +% RD202508: Apply brainmask in case of skull-stripping +% Although this seems to be more correct an the images looks +% fine, the processing of the individual cases showed problems +% wheres just leaving it works fine, ie., the skull-stripping +% is detected in the average and the background masking just +% applied. +if 0 %skullstripped % DO NOT USE !!! ... if then test with thickness phantom (Rusak et al. 2021) + for i=1:numel(param) + vol(:,:,:,i) = vol(:,:,:,i) .* brainmask; + end +end + +if need_wimg + for i=1:numel(param) + img = vol(:,:,:,i); + [pth,nam] = fileparts(Nii(i).dat.fname); + nam = fullfile(pth,['r' nam '.nii']); + Nio = nifti; + Nio.dat = file_array(nam,size(img),'float32',0,1,0); + Nio.mat = M_avg; + Nio.mat0 = Nio.mat; + Nio.mat_intent = 'Aligned'; + Nio.mat0_intent = Nio.mat_intent; + Nio.descrip = sprintf('Realigned %d', numel(param)); + create(Nio); + Nio.dat(:,:,:) = img; + out.rimg{i} = nam; + end +end + +if need_avg + %% use weighted median/mean for rigid registration and mean for non-linear registration + if all(isfinite(w_settings(i,:))) % rigid registration + vol_mean = mean(vol,4); + % use median for > 2 images, otherwise use min + if numel(param) > 2 + vol_median = median(vol,4); + else + vol_median = min(vol,[],4); + end + vol_std = std(vol,[],4); + + % get 0..95% range + [nvol,hvol] = hist(vol_std(:),100); + nvol = nvol./numel(vol_std(:)); + quantile95 = hvol(find(cumsum(nvol)/sum(nvol)>0.95,1,'first')); + + % scale std image with quantile95 value and limit range 0..1 + vol_std = vol_std./quantile95; + vol_std(vol_std>1) = 1; + + % weighted scaling w.r.t. local std + mu = vol_std.*vol_median + (1-vol_std).*vol_mean; + + else % non-linear registration + mu = mean(vol,4); + end + + if any(strcmp('wavg',output)) + [pth,nam] = fileparts(Nii(1).dat.fname); + nam = fullfile(pth,['avg_' nam '.nii']); + Nio = nifti; + Nio.dat = file_array(nam,size(mu),'float32',0,1,0); + Nio.mat = M_avg; + Nio.mat0 = Nio.mat; + Nio.mat_intent = 'Aligned'; + Nio.mat0_intent = Nio.mat_intent; + Nio.descrip = sprintf('Median of %d', numel(param)); + create(Nio); + Nio.dat(:,:,:) = mu; + out.avg = {nam}; + else + out.avg = mu; + end +end + +if need_mom + out.mom = {}; + for i=1:numel(param) + if all(isfinite(w_settings(i,:))) + + mom = zeros(d,'single'); + M = img(i).mat\param(i).R*M_avg; + + for m=1:d(3) + dt = spm_diffeo('det',param(i).J(:,:,m,:,:)); + y = transform_warp(M,param(i).y(:,:,m,:)); + f = spm_diffeo('bsplins',img(i).f,y,ord); + ebias = exp(spm_diffeo('pullc',param(i).bias,y)); + b = (f-mu(:,:,m).*ebias).*ebias.*dt; + b(~isfinite(b)) = 0; + mom(:,:,m) = b; + clear dt y f ebias b msk + end + + if any(strcmp('wmom',output)) + [pth,nam] = fileparts(Nii(i).dat.fname); + nam = fullfile(pth,['a_' nam '.nii']); + Nio = nifti; + Nio.dat = file_array(nam,d,'float32',0,1,0); + Nio.mat = M_avg; + Nio.mat0 = Nio.mat; + Nio.mat_intent = 'Aligned'; + Nio.mat0_intent = Nio.mat_intent; + + Nio.descrip = sprintf('Scalar Mom (%.3g %.3g %.3g %.3g %.3g) (%d)',w_settings(i,:)*sc,s_settings(i,1)); + create(Nio); + Nio.dat(:,:,:,1,1) = mom; + out.mom{i} = nam; + else + out.mom{i} = mom; + end + clear mom + end + end +end + +clear mu; + +if need_bia + out.bia = {}; + for i=1:numel(param) + if all(isfinite(b_settings(i,:))) + + if any(strcmp('wbia',output)) + [pth,nam] = fileparts(Nii(i).dat.fname); + nam = fullfile(pth,['BiasField_' nam '.nii']); + Nio = nifti; + dm = [Nii(i).dat.dim 1]; dm = dm(1:3); + Nio.dat = file_array(nam,dm,'float32',0,1,0); + Nio.mat = Nii(i).mat; + Nio.mat0 = Nii(i).mat0; + Nio.mat_intent = Nii(i).mat_intent; + Nio.mat0_intent = Nii(i).mat0_intent; + + Nio.descrip = 'Bias Field'; + create(Nio); + Nio.dat(:,:,:) = exp(param(i).bias); + out.bia{i} = nam; + else + out.bia{i} = exp(param(i).bias); + end + clear mom + end + end +end + +if need_def + out.def = {}; + for i=numel(param):-1:1 + if all(isfinite(w_settings(i,:))) + + M = param(i).R*M_avg; + for m=1:d(3) + param(i).y(:,:,m,:) = transform_warp(M,param(i).y(:,:,m,:)); + end + if any(strcmp('wdef',output)) + [pth,nam] = fileparts(Nii(i).dat.fname); + nam = fullfile(pth,['y_' nam '.nii']); + Nio = nifti; + Nio.dat = file_array(nam,[d 1 3],'float32',0,1,0); + Nio.mat = M_avg; + Nio.mat0 = Nio.mat; + Nio.mat_intent = 'Aligned'; + Nio.mat0_intent = Nio.mat_intent; + + Nio.descrip = 'Deformation (templ. to. ind.)'; + create(Nio); + Nio.dat(:,:,:,1,1) = param(i).y(:,:,:,1); + Nio.dat(:,:,:,1,2) = param(i).y(:,:,:,2); + Nio.dat(:,:,:,1,3) = param(i).y(:,:,:,3); + out.def{i} = nam; + else + out.def{i} = param(i).y; + end + param(i).y = []; + end + end +end + +if need_jac + out.jac = {}; + for i=numel(param):-1:1 + if all(isfinite(w_settings(i,:))) + dt = spm_diffeo('det',param(i).J); + if any(strcmp('wjac',output)) + [pth,nam] = fileparts(Nii(i).dat.fname); + nam = fullfile(pth,['j_' nam '.nii']); + Nio = nifti; + Nio.dat = file_array(nam,size(dt),'float32',0,1,0); + Nio.mat = M_avg; + Nio.mat0 = Nio.mat; + Nio.mat_intent = 'Aligned'; + Nio.mat0_intent = Nio.mat_intent; + + Nio.descrip = 'Jacobian det (templ. to. ind.)'; + create(Nio); + Nio.dat(:,:,:) = dt; + out.jac{i} = nam; + else + out.jac{i} = dt; + end + clear dt + param(i).J = []; + end + end +end + +if need_div + out.div = {}; + for i=1:numel(param) + if all(isfinite(w_settings(i,:))) + dv = spm_diffeo('div',param(i).v0); + if any(strcmp('wdiv',output)) + [pth,nam] = fileparts(Nii(i).dat.fname); + nam = fullfile(pth,['dv_' nam '.nii']); + Nio = nifti; + Nio.dat = file_array(nam,size(dv),'float32',0,1,0); + Nio.mat = M_avg; + Nio.mat0 = Nio.mat; + Nio.mat_intent = 'Aligned'; + Nio.mat0_intent = Nio.mat_intent; + + Nio.descrip = sprintf('Div (%.3g %.3g %.3g %.3g %.3g) (%d)',w_settings(i,:)*sc,s_settings(i,1)); + create(Nio); + Nio.dat(:,:,:) = dv; + out.div{i} = nam; + else + out.div{i} = dv; + end + clear dv + end + end +end + +if need_vel + out.vel = {}; + for i=1:numel(param) + if all(isfinite(w_settings(i,:))) + if any(strcmp('wvel',output)) + [pth,nam] = fileparts(Nii(i).dat.fname); + nam = fullfile(pth,['v_' nam '.nii']); + Nio = nifti; + Nio.dat = file_array(nam,[d 1 3],'float32',0,1,0); + Nio.mat = M_avg; + Nio.mat0 = Nio.mat; + Nio.mat_intent = 'Aligned'; + Nio.mat0_intent = Nio.mat_intent; + + Nio.descrip = sprintf('Vel (%.3g %.3g %.3g %.3g %.3g) (%d)',w_settings(i,:)*sc,s_settings(i,1)); + create(Nio); + Nio.dat(:,:,:,1,1) = param(i).v0(:,:,:,1); + Nio.dat(:,:,:,1,2) = param(i).v0(:,:,:,2); + Nio.dat(:,:,:,1,3) = param(i).v0(:,:,:,3); + out.vel{i} = nam; + else + out.vel{i} = param(i).v0; + end + end + end +end +spm_plot_convergence('Clear'); +return; +%_______________________________________________________________________ + + +%_______________________________________________________________________ +function vol = get_transformed_images(data, param, ord) +d = data.d; +M_avg = data.mat; +img = data.img; +prec = data.prec; + +vol = zeros([d numel(img)],'single'); + +for m=1:d(3) + F = cell(1,numel(img)); + Dt = cell(1,numel(img)); + Bf = cell(1,numel(img)); + + mum = zeros(d(1:2),'single'); + + for i=1:numel(img) + M = img(i).mat\param(i).R*M_avg; + if ~isempty(param(i).y) + y = transform_warp(M,param(i).y(:,:,m,:)); + Dt{i} = spm_diffeo('det',param(i).J(:,:,m,:,:))*abs(det(M(1:3,1:3))); + else + Dt{i} = ones(d(1:2),'single')*abs(det(M(1:3,1:3))); + y = zeros([d(1:2) 1 3],'single'); + [y(:,:,1),y(:,:,2),y(:,:,3)] = ndgrid(single(1:d(1)),single(1:d(2)),m); + y = transform_warp(M,y); + end + + F{i} = spm_diffeo('bsplins',img(i).f,y,ord); + if ~isempty(param(i).bias) + Bf{i} = exp(spm_diffeo('bsplins',param(i).bias,y,[1 1 1 ord(4:end)])); % Trilinear + else + Bf{i} = ones(d(1:2),'single'); + end + + f = F{i}; + ebias = Bf{i}; + dt = Dt{i}; + scal = Bf{i}.*Dt{i}*prec(i); + vol(:,:,m,i) = F{i}.*scal; + + end +end + +return; +%_______________________________________________________________________ + +%_______________________________________________________________________ +function [mu,ss,nvox,D] = compute_mean(data, param, ord) +d = data.d; +M_avg = data.mat; +img = data.img; +prec = data.prec; + +mu = zeros(d,'single'); +nvox = zeros(numel(img),1); +ss = zeros(numel(img),1); +if nargout>=4 % Compute gradients of template + D = {zeros(d,'single'),zeros(d,'single'),zeros(d,'single')}; +end + +for m=1:d(3) + if nargout>=4 + Dm1 = {zeros(d(1:2),'single'),zeros(d(1:2),'single'),zeros(d(1:2),'single')}; + Dm2 = {zeros(d(1:2),'single'),zeros(d(1:2),'single'),zeros(d(1:2),'single')}; + Df = cell(3,1); + Db = cell(3,1); + end + F = cell(1,numel(img)); + Dt = cell(1,numel(img)); + Bf = cell(1,numel(img)); + Msk= cell(1,numel(img)); + + mum = zeros(d(1:2),'single'); + mgm = zeros(d(1:2),'single'); + + for i=1:numel(img) + M = img(i).mat\param(i).R*M_avg; + if ~isempty(param(i).y) + y = transform_warp(M,param(i).y(:,:,m,:)); + Dt{i} = spm_diffeo('det',param(i).J(:,:,m,:,:))*abs(det(M(1:3,1:3))); + else + Dt{i} = ones(d(1:2),'single')*abs(det(M(1:3,1:3))); + y = zeros([d(1:2) 1 3],'single'); + [y(:,:,1),y(:,:,2),y(:,:,3)] = ndgrid(single(1:d(1)),single(1:d(2)),m); + y = transform_warp(M,y); + end + + if nargout>=4 + % Sample image and bias field, along with their gradients. Gradients are + % then transformed by multiplying with the transpose of the Jacobain matrices + % of the deformation. + if ~isempty(param(i).J) + Jm = reshape(param(i).J(:,:,m,:,:),[d(1)*d(2),3,3]); + Jm = reshape(reshape(permute(Jm,[1 2 3]),d(1)*d(2)*3,3)*M(1:3,1:3),[d(1) d(2) 3 3]); + else + Jm = repmat(reshape(single(M(1:3,1:3)),[1 1 3 3]),[d(1) d(2) 1 1]); + end + + [F{i} ,d1,d2,d3] = spm_diffeo('bsplins',img(i).f,y,ord); + Df{1} = Jm(:,:,1,1).*d1 + Jm(:,:,2,1).*d2 + Jm(:,:,3,1).*d3; + Df{2} = Jm(:,:,1,2).*d1 + Jm(:,:,2,2).*d2 + Jm(:,:,3,2).*d3; + Df{3} = Jm(:,:,1,3).*d1 + Jm(:,:,2,3).*d2 + Jm(:,:,3,3).*d3; + + if ~isempty(param(i).bias) + [Bf{i},d1,d2,d3] = spm_diffeo('bsplins',param(i).bias,y,[1 1 1 ord(4:end)]); % Trilinear + Bf{i} = exp(Bf{i}); + Db{1} = Jm(:,:,1,1).*d1 + Jm(:,:,2,1).*d2 + Jm(:,:,3,1).*d3; + Db{2} = Jm(:,:,1,2).*d1 + Jm(:,:,2,2).*d2 + Jm(:,:,3,2).*d3; + Db{3} = Jm(:,:,1,3).*d1 + Jm(:,:,2,3).*d2 + Jm(:,:,3,3).*d3; + else + Bf{i} = ones(d(1:2),'single'); + Db{1} = zeros(d(1:2),'single'); + Db{2} = zeros(d(1:2),'single'); + Db{3} = zeros(d(1:2),'single'); + end + clear d1 d2 d3 + else + F{i} = spm_diffeo('bsplins',img(i).f,y,ord); + if ~isempty(param(i).bias) + Bf{i} = exp(spm_diffeo('bsplins',param(i).bias,y,[1 1 1 ord(4:end)])); % Trilinear + else + Bf{i} = ones(d(1:2),'single'); + end + end + + msk = isfinite(F{i}) & isfinite(Bf{i}); + Msk{i} = msk; + f = F{i}(msk); + ebias = Bf{i}(msk); + dt = Dt{i}(msk); + scal = ebias.*dt*prec(i); + mum(msk) = mum(msk) + f.*scal; + mgm(msk) = mgm(msk) + ebias.*scal; + + if nargout>=4 + % For computing gradients + Dm1{1}(msk) = Dm1{1}(msk) + (Df{1}(msk) + f.*Db{1}(msk)).*scal; + Dm1{2}(msk) = Dm1{2}(msk) + (Df{2}(msk) + f.*Db{2}(msk)).*scal; + Dm1{3}(msk) = Dm1{3}(msk) + (Df{3}(msk) + f.*Db{3}(msk)).*scal; + + scal = ebias.*scal; + Dm2{1}(msk) = Dm2{1}(msk) + Db{1}(msk).*scal; + Dm2{2}(msk) = Dm2{2}(msk) + Db{2}(msk).*scal; + Dm2{3}(msk) = Dm2{3}(msk) + Db{3}(msk).*scal; + end + end + mgm = mgm + eps; + mu(:,:,m) = mum./mgm; % Weighted mean + + if nargout>=2 + if nargout>=4 + % Compute ""gradients of template (mu)"". Note that the true gradients + % would incorporate the gradients of the Jacobians, but we do not want + % these to be part of the ""template gradients"". + wt = 2*mum./(mgm.*mgm); + D{1}(:,:,m) = Dm1{1}./mgm - Dm2{1}.*wt; + D{2}(:,:,m) = Dm1{2}./mgm - Dm2{2}.*wt; + D{3}(:,:,m) = Dm1{3}./mgm - Dm2{3}.*wt; + end + + % Compute matching term + for i=1:numel(img) + msk = Msk{i}; + f = F{i}(msk); + ebias = Bf{i}(msk); + dt = Dt{i}(msk); + mum = mu(:,:,m); + mum = mum(msk); + nvox(i) = nvox(i) + sum(dt); + ss(i) = ss(i) + sum((f-mum.*ebias).^2.*dt); + end + end +end + +for i=1:numel(img) + ss(i) = ss(i)/nvox(i)*numel(img(i).f); +end +return; +%_______________________________________________________________________ + +%_______________________________________________________________________ +function y1 = transform_warp(M,y) +% Affine transformation of a deformation +d = size(y); +y1 = reshape(bsxfun(@plus,reshape(y,[prod(d(1:3)),3])*single(M(1:3,1:3)'),single(M(1:3,4)')),d); +return; +%_______________________________________________________________________ + +%_______________________________________________________________________ +function y = identity(d) +% Generate an identity transform of size d(1) x d(2) x d(3) +y = zeros([d(1:3) 3],'single'); +[y(:,:,:,1),y(:,:,:,2),y(:,:,:,3)] = ndgrid(single(1:d(1)),single(1:d(2)),single(1:d(3))); +%_______________________________________________________________________ + +function [M_avg,d] = compute_avg_mat(Mat0,dims) +% Compute an average voxel-to-world mapping and suitable dimensions +% FORMAT [M_avg,d] = spm_compute_avg_mat(Mat0,dims) +% Mat0 - array of matrices (4x4xN) +% dims - image dimensions (Nx3) +% M_avg - voxel-to-world mapping +% d - dimensions for average image +% +%__________________________________________________________________________ +% Copyright (C) 2012-2019 Wellcome Trust Centre for Neuroimaging + +% John Ashburner +% $Id$ + + +% Rigid-body matrices computed from exp(p(1)*B(:,:,1)+p(2)+B(:,:,2)...) +%-------------------------------------------------------------------------- +B = se3_basis; + +% Find combination of 90 degree rotations and flips that brings all +% the matrices closest to axial +%-------------------------------------------------------------------------- +Matrices = Mat0; +pmatrix = [1,2,3; 2,1,3; 3,1,2; 3,2,1; 1,3,2; 2,3,1]; +for i=1:size(Matrices,3) + vx = sqrt(sum(Matrices(1:3,1:3,i).^2)); + tmp = Matrices(:,:,i)/diag([vx 1]); + R = tmp(1:3,1:3); + minss = Inf; + minR = eye(3); + for i1=1:6 + R1 = zeros(3); + R1(pmatrix(i1,1),1)=1; + R1(pmatrix(i1,2),2)=1; + R1(pmatrix(i1,3),3)=1; + for i2=0:7 + F = diag([bitand(i2,1)*2-1, bitand(i2,2)-1, bitand(i2,4)/2-1]); + R2 = F*R1; + ss = sum(sum((R/R2-eye(3)).^2)); + if ss1e-8 + + % Zooms computed from exp(p(7)*B2(:,:,1)+p(8)*B2(:,:,2)+p(9)*B2(:,:,3)) + %---------------------------------------------------------------------- + B2 = zeros(4,4,3); + B2(1,1,1) = 1; + B2(2,2,2) = 1; + B2(3,3,3) = 1; + + p = zeros(9,1); % Parameters + for it=1:10000 + [R,dR] = spm_dexpm(p(1:6),B); % Rotations + Translations + [Z,dZ] = spm_dexpm(p(7:9),B2); % Zooms + + M = R*Z; % Voxel-to-world estimate + dM = zeros(4,4,6); + for i=1:6, dM(:,:,i) = dR(:,:,i)*Z; end + for i=1:3, dM(:,:,i+6) = R*dZ(:,:,i); end + dM = reshape(dM,[16,9]); + + d = M(:)-M_avg(:); % Difference + gr = dM'*d; % Gradient + Hes = dM'*dM; % Hessian + p = p - Hes\gr; % Gauss-Newton update + if sum(gr.^2)<1e-8, break; end + end + M_avg = M; +end + +% Ensure that the FoV covers all images, with a few voxels to spare +%-------------------------------------------------------------------------- +mn = Inf*ones(3,1); +mx = -Inf*ones(3,1); +for i=1:size(Mat0,3) + dm = [dims(i,:) 1 1]; + corners = [ + 1 dm(1) 1 dm(1) 1 dm(1) 1 dm(1) + 1 1 dm(2) dm(2) 1 1 dm(2) dm(2) + 1 1 1 1 dm(3) dm(3) dm(3) dm(3) + 1 1 1 1 1 1 1 1]; + M = M_avg\Mat0(:,:,i); + vx = M(1:3,:)*corners; + mx = max(mx,max(vx,[],2)); + mn = min(mn,min(vx,[],2)); +end +mx = ceil(mx); +mn = floor(mn); +d = (mx-mn+7)'; +M_avg = M_avg * [eye(3) mn-4; 0 0 0 1]; +return; +%__________________________________________________________________________ + +%__________________________________________________________________________ +function B = se3_basis +% Basis functions for the lie algebra of the special Euclidean group +% (SE(3)). +B = zeros(4,4,6); +B(1,4,1) = 1; +B(2,4,2) = 1; +B(3,4,3) = 1; +B([1,2],[1,2],4) = [0 1;-1 0]; +B([3,1],[3,1],5) = [0 1;-1 0]; +B([2,3],[2,3],6) = [0 1;-1 0]; +return; +%__________________________________________________________________________ + + + +%_______________________________________________________________________ +function t = transf(B1,B2,B3,T) +d2 = [size(T) 1]; +t1 = reshape(reshape(T, d2(1)*d2(2),d2(3))*B3', d2(1), d2(2)); +t = B1*t1*B2'; +return; +%_______________________________________________________________________ + +%_______________________________________________________________________ +function dat = bias_correction(volG,volF,brainmask,pyramid,nits,fwhm,reg1,reg2) +% This function is intended for doing bias correction between scans inside a defined mask +% A version of the second image is returned out, that has the +% same bias as that of the first image. + +vx = sqrt(sum(pyramid.mat(1:3,1:3).^2)); +d = size(volG); +sd = vx(1)*size(volG,1)/fwhm; d3(1) = ceil(sd*2); krn_x = exp(-(0:(d3(1)-1)).^2/sd.^2)/sqrt(vx(1)); +sd = vx(2)*size(volG,2)/fwhm; d3(2) = ceil(sd*2); krn_y = exp(-(0:(d3(2)-1)).^2/sd.^2)/sqrt(vx(2)); +sd = vx(3)*size(volG,3)/fwhm; d3(3) = ceil(sd*2); krn_z = exp(-(0:(d3(3)-1)).^2/sd.^2)/sqrt(vx(3)); +Cbias = kron(krn_z,kron(krn_y,krn_x)).^(-2)*prod(d)*reg1; +Cbias = sparse(1:length(Cbias),1:length(Cbias),Cbias,length(Cbias),length(Cbias)); +B3bias = spm_dctmtx(d(3),d3(3)); +B2bias = spm_dctmtx(d(2),d3(2)); +B1bias = spm_dctmtx(d(1),d3(1)); +lmRb = speye(size(Cbias))*prod(d)*reg2; +Tbias = zeros(d3); + +% correct global scaling +thG = mean(volG(isfinite(volG)))/8; thG = mean(volG(volG>thG)); +thF = mean(volF(isfinite(volF)))/8; thF = mean(volF(volF>thF)); +volF = volF*thG/thF; +thF = mean(volF(isfinite(volF)))/8; thF = mean(volF(volF>thF)); + +ll = Inf; +spm_plot_convergence('Init','Bias Correction','- Log-likelihood','Iteration'); + +for subit=1:nits + + % Compute objective function and its 1st and second derivatives + Alpha = zeros(prod(d3),prod(d3)); % Second derivatives + Beta = zeros(prod(d3),1); % First derivatives + oll = ll; + ll = 0.5*Tbias(:)'*Cbias*Tbias(:); + + for z=1:size(volG,3) + f1o = volF(:,:,z); + f2o = volG(:,:,z); + f1o(~isfinite(f1o)) = 0; + f2o(~isfinite(f2o)) = 0; + if ~isempty(brainmask) + msk = ((f1o==0) & (f2o==0)) & (brainmask(:,:,z) < 0.25); + else + msk = (f1o==0) & (f2o==0); + end + f1o(msk) = 0; + f2o(msk) = 0; + ro = transf(B1bias,B2bias,B3bias(z,:),Tbias); + msk = abs(ro)>0.01; + + % Use the form based on an integral for bias that is + % far from uniform. + f1 = f1o(msk); + f2 = f2o(msk); + r = ro(msk); + e = exp(r); + t1 = (f2.*e-f1); + t2 = (f1./e-f2); + ll = ll + 1/4*sum(sum((t1.^2-t2.^2)./r)); + wt1 = zeros(size(f1o)); + wt2 = zeros(size(f1o)); + wt1(msk) = (2*(t1.*f2.*e+t2.*f1./e)./r + (t2.^2-t1.^2)./r.^2)/4; + wt2(msk) = ((f2.^2.*e.^2-f1.^2./e.^2+t1.*f2.*e-t2.*f1./e)./r/2 ... + - (t1.*f2.*e+t2.*f1./e)./r.^2 + (t1.^2-t2.^2)./r.^3/2); + + % Use the simple symmetric form for bias close to uniform + f1 = f1o(~msk); + f2 = f2o(~msk); + r = ro(~msk); + e = exp(r); + t1 = (f2.*e-f1); + t2 = (f1./e-f2); + ll = ll + (sum(t1.^2)+sum(t2.^2))/4; + wt1(~msk) = (t1.*f2.*e-t2.*f1./e)/2; + wt2(~msk) = ((f2.*e).^2+t1.*f2.*e + (f1./e).^2+t2.*f1./e)/2; + + b3 = B3bias(z,:)'; + Beta = Beta + kron(b3,spm_krutil(wt1,B1bias,B2bias,0)); + Alpha = Alpha + kron(b3*b3',spm_krutil(wt2,B1bias,B2bias,1)); + end; + try + spm_plot_convergence('Set',ll/prod(d)); + catch + spm_chi2_plot('Set',ll/prod(d)); + end + + % temporarily estimate whole bias field to check for huge values + r3 = zeros(size(volG)); + for z=1:size(volG,3) + r3(:,:,z) = transf(B1bias,B2bias,B3bias(z,:),Tbias); + end; + + % additionally check if 1./exp(r3) is getting too large and regularization + % should be increased + % ""-4"" equals roughly to a max value of 50 for 1./exp(r3) + if (subit > 1 && ll>oll) || min(r3(:)) < -4 + % Hasn't improved, so go back to previous solution + Tbias = oTbias; + ll = oll; + lmRb = lmRb*10; + else + % Accept new solution + oTbias = Tbias; + Tbias = Tbias(:); + Tbias = Tbias - (Alpha + Cbias + lmRb)\(Beta + Cbias*Tbias); + Tbias = reshape(Tbias,d3); + end; + +end; + +dat = zeros(size(volG)); + +for z=1:size(volG,3) + tmp = volF(:,:,z); + tmp(~isfinite(tmp)) = 0; + dat(:,:,z) = tmp; + r = transf(B1bias,B2bias,B3bias(z,:),Tbias); + r(volG(:,:,z) == 0) = 0; + dat(:,:,z) = dat(:,:,z)./exp(r); +end; + +return; +%_______________________________________________________________________ +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_vol_median3c.m",".m","1220","32","%cat_vol_median3c Median filter for label maps. +% Median Filter for 3D single image D. Bi is used to mask voxels for the +% filter process, whereas Bn is used to mask voxels that are used as +% neighbors in the filter process. +% +% This is a special subversion to filter label maps! +% +% M = cat_vol_median3c(D[,Bi,Bn,iter,nb]) +% +% D (single) .. 3D matrix for filter process +% Bi (logical) .. 3D matrix that mark voxel that should be filtered +% Bn (logical) .. 3D matrix that mark voxel that are used as neighbors +% iter (double) .. number of interations (<=10, default=1) +% nb (double) .. number of neighbors (<=10, default=1); +% +% Examples: +% 1) +% A = round(smooth3(rand(50,50,3,'single')*3)); +% B = false(size(A)); B(5:end-4,5:end-4,:)=true; +% C = cat_vol_median3c(A,B,B,2,2); +% ds('d2smns','',1,A+B,C,2); +% +% See also cat_vol_median3, compile. +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_vol_iscaling.m",".m","943","25","function clim = cat_vol_iscaling(cdata,plim) +% clim = cat_vol_iscaling(cdata,plim). Intensity scaling. +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + cdata(isnan(cdata) | isinf(cdata))=[]; + ASD = min(0.02,max(eps,0.05*std(cdata))/max(abs(cdata))); + if ~exist('plim','var'), plim = [ASD 1-ASD]; end + + bcdata = [min(cdata) max(cdata)]; + if bcdata(1) == bcdata(2) + clim = bcdata + [-eps eps]; + else + range = bcdata(1):diff(bcdata)/1000:bcdata(2); + hst = hist(cdata,range); + clim(1) = range(max(1,find(cumsum(hst)/sum(hst)>plim(1),1,'first'))); + clim(2) = range(min([numel(range),find(cumsum(hst)/sum(hst)>plim(2),1,'first')])); + end +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_surf_createCS_fun.m",".m","19390","350","function varargout = cat_surf_createCS_fun(action,varargin) +%cat_surf_createCS_fun. Subfunctions of cat_surf_createCS# functions. + + varargout = {}; + + switch action + case 'evalProcessing' + evalProcessing(varargin{:}); + + case 'addSurfaceQualityMeasures' + varargout{1} = addSurfaceQualityMeasures(varargin{:}); + + case 'quickeval' + quickeval(varargin{:}); + + case 'setFileNames' + [varargout{1},varargout{2},varargout{3},varargout{4},varargout{5},varargout{6}] = setFileNames(varargin{:}); + + case 'saveSurf' + saveSurf(varargin{:}); + + case 'loadSurf' + varargout{1} = loadSurf(varargin{:}); + + case 'createOutputFileStructures' + [varargout{1},varargout{2}] = createOutputFileStructures(varargin{:}); + + case 'fillVentricle' + [varargout{1},varargout{2}] = fillVentricle(varargin{:}); + + case 'setupprior' + varargout{1} = setupprior(varargin{:}); + end +end +%======================================================================= +function [Yp0f,Ymf] = fillVentricle(Yp0,Ym,Ya,YMF,vx_vol) +%fillVentricle. Simple filling of ventricles by a closing around a mask. + + NS = @(Ys,s) Ys==s | Ys==s+1; + LAB = cat_get_defaults('extopts.LAB'); + + % simple filling by the YMF mask + Yp0f = max(Yp0 ,min(1,YMF & ~NS(Ya,LAB.HC) & ~( cat_vol_morph( NS(Ya,LAB.HC),'dd',2,vx_vol)))); + Ymf = max(Ym ,min(1,YMF & ~NS(Ya,LAB.HC) & ~( cat_vol_morph( NS(Ya,LAB.HC),'dd',2,vx_vol)))); + + % close gaps in Yp0f + Yp0fs = cat_vol_smooth3X(Yp0f,1); + Ytmp = cat_vol_morph(YMF,'dd',3,vx_vol) & Yp0fs>2.1/3; + Yp0f(Ytmp) = max(min(Yp0(Ytmp),0),Yp0fs(Ytmp)); clear Ytmp Yp0fs; + Yp0f = Yp0f * 3; + + % close gaps in Ymfs + Ymfs = cat_vol_smooth3X(Ymf,1); + Ytmp = cat_vol_morph(YMF,'dd',3,vx_vol) & Ymfs>2.1/3; + Ymf(Ytmp) = max(min(Ym(Ytmp),0),Ymfs(Ytmp)); clear Ytmp Ymfs; + Ymf = Ymf * 3; +end +%======================================================================= +function [Vmfs,Smat] = createOutputFileStructures(V,V0,resI,BB,opt,pp0,mrifolder,ff,si) + matI = spm_imatrix(V.mat); + matI(7:9) = sign( matI(7:9)) .* repmat( opt.interpV , 1 , 3); + matiBB = spm_imatrix(V.mat * [eye(4,3) [ (BB.BB([1,3,5])' - 1) ; 1]]); + matIBB = matiBB; + matIBB(7:9) = sign( matiBB(7:9)) .* repmat( opt.interpV , 1 , 3); + Smat.matlabi_mm = V.mat * [0 1 0 0; 1 0 0 0; 0 0 1 0; 0 0 0 1]; % CAT internal space + Smat.matlabI_mm = spm_matrix(matI) * [0 1 0 0; 1 0 0 0; 0 0 1 0; 0 0 0 1]; % PBT interpolated space + Smat.matlabIBB_mm = spm_matrix(matIBB) * [0 1 0 0; 1 0 0 0; 0 0 1 0; 0 0 0 1]; % PBT interpolated + Smat.matlabiBB_mm = spm_matrix(matiBB) * [0 1 0 0; 1 0 0 0; 0 0 1 0; 0 0 0 1]; % PBT interpolated + + Vmfs = resI.hdrN; + Vmfs.pinfo = V0.pinfo; + Vmfs.fname = fullfile(pp0,mrifolder, sprintf('%s_seg-%s.nii',ff,opt.surf{si})); + if isfield(Vmfs,'dat'), Vmfs = rmfield(Vmfs,'dat'); end + if isfield(Vmfs,'private'), Vmfs = rmfield(Vmfs,'private'); end + matiBB = spm_imatrix(V.mat * [eye(4,3) [ (BB.BB([1,3,5])' - 1) ; 1]]); + Vmfs.mat(1:3,4) = matiBB(1:3); +end +%======================================================================= +function saveSurf(CS,P) + save(gifti(struct('faces',CS.faces,'vertices',CS.vertices)),P,'Base64Binary'); %#ok +end +%======================================================================= +function CS1 = loadSurf(P) + if ~exist(P,'file'), error('Surface file %s could not be found due to previous processing errors.',P); end + + try + CS = gifti(P); + catch + error('Surface file %s could not be read due to previous processing errors.',P); + end + + CS1.vertices = CS.vertices; CS1.faces = CS.faces; + if isfield(CS,'cdata'), CS1.cdata = CS.cdata; end +end +%========================================================================== +function [P,pp0,mrifolder,pp0_surffolder,surffolder,ff] = setFileNames(V0,job,opt) +%setFileNames. Define surface filenames. +%#ok<*AGROW> + + [mrifolder, ~, surffolder] = cat_io_subfolders(V0.fname,job); + + % get original filename without 'n' + [pp0,ff] = spm_fileparts(V0.fname); + + % correct '../' parts in directory for BIDS structure + [stat, val] = fileattrib(fullfile(pp0,surffolder)); + if stat, pp0_surffolder = val.Name; else, pp0_surffolder = fullfile(pp0,surffolder); end + if ~exist(fullfile(pp0_surffolder),'dir'), mkdir(fullfile(pp0_surffolder)); end + + % surface filenames + for si = 1:numel(opt.surf) + P(si).Pm = fullfile(pp0,mrifolder, sprintf('m%s.nii',ff)); % raw + P(si).Pp0 = fullfile(pp0,mrifolder, sprintf('p0%s.nii',ff)); % labelmap + P(si).Praw = fullfile(pp0_surffolder,sprintf('%s.central.nofix.%s.gii',opt.surf{si},ff)); % raw + P(si).Praw2 = fullfile(pp0_surffolder,sprintf('%s.central.nofix_sep.%s.gii',opt.surf{si},ff)); % raw + P(si).Pdefects = fullfile(pp0,mrifolder, sprintf('defects_%s.nii',ff)); % defect + P(si).Pcentral = fullfile(pp0_surffolder,sprintf('%s.central.%s.gii',opt.surf{si},ff)); % central + P(si).Pcentralh = fullfile(pp0_surffolder,sprintf('%s.centralh.%s.gii',opt.surf{si},ff)); % central + P(si).Pcentralr = fullfile(pp0_surffolder,sprintf('%s.central.resampled.%s.gii',opt.surf{si},ff));% central .. used in inactive path + P(si).Ppial = fullfile(pp0_surffolder,sprintf('%s.pial.%s.gii',opt.surf{si},ff)); % pial (GM/CSF) + P(si).Pwhite = fullfile(pp0_surffolder,sprintf('%s.white.%s.gii',opt.surf{si},ff)); % white (WM/GM) + P(si).Pthick = fullfile(pp0_surffolder,sprintf('%s.thickness.%s',opt.surf{si},ff)); % FS thickness / GM depth + P(si).Pmsk = fullfile(pp0_surffolder,sprintf('%s.msk.%s',opt.surf{si},ff)); % msk + P(si).Ppbt = fullfile(pp0_surffolder,sprintf('%s.pbt.%s',opt.surf{si},ff)); % PBT thickness / GM depth + P(si).Psphere0 = fullfile(pp0_surffolder,sprintf('%s.sphere.nofix.%s.gii',opt.surf{si},ff)); % sphere.nofix + P(si).Psphere = fullfile(pp0_surffolder,sprintf('%s.sphere.%s.gii',opt.surf{si},ff)); % sphere + P(si).Pspherereg = fullfile(pp0_surffolder,sprintf('%s.sphere.reg.%s.gii',opt.surf{si},ff)); % sphere.reg + P(si).Pgmt = fullfile(pp0,mrifolder, sprintf('%s_thickness-%s.nii',ff,opt.surf{si})); % temp thickness + P(si).Pppm = fullfile(pp0,mrifolder, sprintf('%s_ppm-%s.nii',ff,opt.surf{si})); % temp position map + P(si).Pfsavg = fullfile(opt.fsavgDir, sprintf('%s.central.freesurfer.gii',opt.surf{si})); % fsaverage central + P(si).Pfsavgsph = fullfile(opt.fsavgDir, sprintf('%s.sphere.freesurfer.gii',opt.surf{si})); % fsaverage sphere + % special maps in CS2 + P(si).Player4 = fullfile(pp0_surffolder,sprintf('%s.layer4.%s.gii',opt.surf{si},ff)); % layer4 + P(si).PintL4 = fullfile(pp0_surffolder,sprintf('%s.intlayer4.%s',opt.surf{si},ff)); % layer4 intensity + P(si).Pgwo = fullfile(pp0_surffolder,sprintf('%s.depthWMo.%s',opt.surf{si},ff)); % gyrus width / GWM depth / gyral span + P(si).Pgw = fullfile(pp0_surffolder,sprintf('%s.depthGWM.%s',opt.surf{si},ff)); % gyrus width / GWM depth / gyral span + P(si).Pgww = fullfile(pp0_surffolder,sprintf('%s.depthWM.%s',opt.surf{si},ff)); % gyrus width of the WM / WM depth + P(si).Pgwwg = fullfile(pp0_surffolder,sprintf('%s.depthWMg.%s',opt.surf{si},ff)); % gyrus width of the WM / WM depth + P(si).Psw = fullfile(pp0_surffolder,sprintf('%s.depthCSF.%s',opt.surf{si},ff)); % sulcus width / CSF depth / sulcal span + P(si).Pdefects0 = fullfile(pp0_surffolder,sprintf('%s.defects0.%s',opt.surf{si},ff)); % defects temporary file + end +end +%======================================================================= +function quickeval(V0,Vpp,Ymfs,Yppi,CS,P,Smat,res,opt,EC0,si,time_sr,pipeline) +% only for test visualization + fprintf('\n'); + + if 0 % opt.thick_measure == 1 % allways here + cmd = sprintf('CAT_SurfDistance -mean -thickness ""%s"" ""%s"" ""%s""',P(si).Ppbt,P(si).Pcentral,P(si).Pthick); + cat_system(cmd,opt.verb-3); + % apply upper thickness limit + FSthick = cat_io_FreeSurfer('read_surf_data',P(si).Pthick); + FSthick(FSthick > opt.thick_limit) = opt.thick_limit; + cat_io_FreeSurfer('write_surf_data',P(si).Pthick,FSthick); + end + + cat_surf_fun('white',P(si).Pcentral); + cat_surf_fun('pial',P(si).Pcentral); + + FSthick = cat_io_FreeSurfer('read_surf_data',P(si).Pthick); + PBTthick = cat_io_FreeSurfer('read_surf_data',P(si).Ppbt); + res.(opt.surf{si}).createCS_final = cat_surf_fun('evalCS', ... + loadSurf(P(si).Pcentral), cat_io_FreeSurfer('read_surf_data',P(si).Ppbt), cat_io_FreeSurfer('read_surf_data',P(si).Pthick), ... + Ymfs,Yppi,P(si).Pcentral,Smat.matlabIBB_mm,2,0); + CS2 = CS; CS2.cdata = PBTthick; H = cat_surf_render2(CS2); + cat_surf_render2('clim',H,[0 6]); + cat_surf_render2('view',H,cat_io_strrep(opt.surf{si},{'lh','rh','ch'},{'right','left','back'})); + cat_surf_render2('ColourBar',H,'on'); + title(sprintf('CS%d%d, nF=%0.0fk, EC=%d, Tpbt=%0.3f±%0.3f, Tfs=%0.3f±%0.3f, \n IE=%0.3f, PE=%0.3f, ptime=%0.0fs, time=%s', ... + pipeline,opt.SRP, size(CS.faces,1)/1000, EC0, ... + mean( PBTthick ), std(PBTthick), mean( FSthick ), std(FSthick), ... + mean( [ res.(opt.surf{si}).createCS_final.RMSE_Ym_white, res.(opt.surf{si}).createCS_final.RMSE_Ym_layer4, res.(opt.surf{si}).createCS_final.RMSE_Ym_pial ] ) , ... + mean( [ res.(opt.surf{si}).createCS_final.RMSE_Ypp_white, res.(opt.surf{si}).createCS_final.RMSE_Ypp_central, res.(opt.surf{si}).createCS_final.RMSE_Ypp_pial ] ) , ... + etime(clock,time_sr), datetime)) + fprintf(' Runtime: %0.0fs\n',etime(clock,time_sr)); + + % surfaces in spm_orthview + Po = P(si).Pm; if ~exist(Po,'file'); Po = V0.fname; end + if ~exist(Po,'file') && exist([V0.fname '.gz'],'file'), Po = [V0.fname '.gz']; end + Porthfiles = ['{', sprintf('''%s'',''%s''', P(si).Ppial, P(si).Pwhite ) '}']; + Porthcolor = '{''-g'',''-r''}'; + Porthnames = '{''white'',''pial''}'; + fprintf(' Show surfaces in orthview: %s\n',spm_file(Po ,'link',... + sprintf('cat_surf_fun(''show_orthview'',%s,''%s'',%s,%s)',Porthfiles,Po,Porthcolor,Porthnames))) ; + fprintf(' Show surfaces in orthview: %s | %s | %s | (%s) | %s \n', ... + spm_file([opt.surf{si} '.pbt'],'link', sprintf('H=cat_surf_display(''%s'');',P(si).Ppbt)), ... + spm_file([opt.surf{si} '.thick'],'link', sprintf('H=cat_surf_display(''%s'');',P(si).Pthick)), ... + spm_file('segmentation' ,'link', sprintf('cat_surf_fun(''show_orthview'',%s,''%s'',%s,%s)',Porthfiles,P(si).Pp0, Porthcolor,Porthnames)), ... + spm_file('ppmap' ,'link', sprintf('cat_surf_fun(''show_orthview'',%s,''%s'',%s,%s)',Porthfiles,Vpp.fname, Porthcolor,Porthnames)), ... + spm_file('original' ,'link', sprintf('cat_surf_fun(''show_orthview'',%s,''%s'',%s,%s)',Porthfiles,Po, Porthcolor,Porthnames))); + + + subtitle( strrep( spm_str_manip(P(si).Pcentral,'a90') ,'_','\_')) + fprintf(' Runtime: %0.0fs\n',etime(clock,time_sr)); + +end +%======================================================================= +function res = addSurfaceQualityMeasures(res,opt) +%addSurfaceQualityMeasures. Measures to describe surface properties. + res.mnth = []; res.sdth = []; + res.mnRMSE_Ypp = []; res.mnRMSE_Ym = []; + res.SIw = []; res.SIp = []; res.SIwa = []; res.SIpa = []; + for si=1:numel(opt.surf) + if any(strcmp(opt.surf{si},{'lh','rh'})) + if isfield(res.(opt.surf{si}).createCS_final,'fsthickness_mn_sd_md_mx') && ... + ~isnan( res.(opt.surf{si}).createCS_final.fsthickness_mn_sd_md_mx(1) ) + res.mnth = [ res.mnth res.(opt.surf{si}).createCS_final.fsthickness_mn_sd_md_mx(1) ]; + res.sdth = [ res.sdth res.(opt.surf{si}).createCS_final.fsthickness_mn_sd_md_mx(2) ]; + else + res.mnth = [ res.mnth res.(opt.surf{si}).createCS_final.thickness_mn_sd_md_mx(1) ]; + res.sdth = [ res.sdth res.(opt.surf{si}).createCS_final.thickness_mn_sd_md_mx(2) ]; + end + res.mnRMSE_Ym = [ res.mnRMSE_Ym mean([... + res.(opt.surf{si}).createCS_final.RMSE_Ym_layer4 ... + res.(opt.surf{si}).createCS_final.RMSE_Ym_white ... + res.(opt.surf{si}).createCS_final.RMSE_Ym_pial ]) ]; + res.mnRMSE_Ypp = [ res.mnRMSE_Ypp mean([... + res.(opt.surf{si}).createCS_final.RMSE_Ypp_central ... + res.(opt.surf{si}).createCS_final.RMSE_Ypp_white ... + res.(opt.surf{si}).createCS_final.RMSE_Ypp_pial ]) ]; + if isfield(res.(opt.surf{si}).createCS_final,'white_self_interections') + res.SIw = [ res.SIw res.(opt.surf{si}).createCS_final.white_self_interections ]; + res.SIp = [ res.SIp res.(opt.surf{si}).createCS_final.pial_self_interections ]; + res.SIwa = [ res.SIwa res.(opt.surf{si}).createCS_final.white_self_interection_area ]; + res.SIpa = [ res.SIpa res.(opt.surf{si}).createCS_final.pial_self_interection_area ]; + end + end + end + + % final res structure + res.EC = NaN; + res.defect_size = NaN; + res.defect_area = NaN; + res.defects = NaN; + res.mnth = mean(res.mnth); + res.sdth = mean(res.sdth); + res.RMSE_Ym = mean(res.mnRMSE_Ym); + res.RMSE_Ypp = mean(res.mnRMSE_Ypp); + if isfield(res.(opt.surf{si}).createCS_final,'white_self_interections') + res.self_intersections = mean([res.SIw,res.SIp]); + res.self_intersections_area = mean([res.SIwa,res.SIpa]); + end +end +%======================================================================= +function evalProcessing(res,opt,P,V0) + + if opt.verb && ~opt.vol + % display some evaluation + % - For normal use we limited the surface measures. + % - Surface intensity would be interesting as cortical measure similar to thickness (also age dependent). + % Especially the outer surface will describe the sulcal blurring in children. + % But the mixing of surface quality and anatomical features is problematic. + % - The position value describes how good the transformation of the PBT map into a surface worked. + % Also the position values depend on age. Children have worse pial values due to sulcal blurring but + % the white surface is may effected by aging, e.g., by WMHs. + % - However, for both intensity and position some (average) maps would be also interesting. + % Especially, some Kappa similar measure that describes the differences to the Ym or Ypp would be nice. + % - What does the Euler characteristic say? Wouldn't the defect number more useful for users? + + if any(~cellfun('isempty',strfind(opt.surf,'cb'))), cbtxt = 'cerebral '; else, cbtxt = ''; end + fprintf('Final %ssurface processing results: \n', cbtxt); + + % function to estimate the number of interactions of the surface deformation: d=distance in mm and a=accuracy + QMC = cat_io_colormaps('marks+',17); + color = @(m) QMC(max(1,min(size(QMC,1),round(((m-1)*3)+1))),:); + rate = @(x,best,worst) min(6,max(1, max(0,x-best) ./ (worst-best) * 5 + 1)); + + if cat_get_defaults('extopts.expertgui') + % color output currently only for expert ... + if isfield(res.(opt.surf{1}).createCS_final,'fsthickness_mn_sd_md_mx') + fprintf(' Average thickness (FS): '); + else + fprintf(' Average thickness (PBT): '); + end + cat_io_cprintf( color( rate( abs( res.mnth - 2.5 ) , 0 , 2.0 )) , sprintf('%0.4f' , res.mnth ) ); fprintf(' %s ',native2unicode(177, 'latin1')); + cat_io_cprintf( color( rate( abs( res.sdth - 0.5 ) , 0 , 1.0 )) , sprintf('%0.4f mm\n', res.sdth ) ); + + fprintf(' Surface intensity / position RMSE: '); + cat_io_cprintf( color( rate( mean(res.mnRMSE_Ym) , 0.05 , 0.3 ) ) , sprintf('%0.4f / ', mean(res.mnRMSE_Ym) ) ); + cat_io_cprintf( color( rate( mean(res.mnRMSE_Ypp) , 0.05 , 0.3 ) ) , sprintf('%0.4f\n', mean(res.mnRMSE_Ypp) ) ); + + if isfield(res.(opt.surf{1}).createCS_final,'white_self_interections') + fprintf(' Pial/white self-intersections: '); + cat_io_cprintf( color( rate( mean([res.SIw,res.SIp]) , 0 , 20 ) ) , sprintf('%0.2f%%%% (%0.2f mm%s)\n' , mean([res.SIw,res.SIp]) , mean([res.SIwa,res.SIpa]) , char(178) ) ); + end + else + fprintf(' Average thickness: %0.4f %s %0.4f mm\n' , res.mnth, native2unicode(177, 'latin1'), res.sdth); + end + + for si=1:numel(P) + fprintf(' Display thickness: %s\n',spm_file(P(si).Pthick,'link','cat_surf_display(''%s'')')); + end + + %% surfaces in spm_orthview + if exist(P(si).Pm,'file'), Po = P(si).Pm; else, Po = V0.fname; end + if ~exist(Po,'file') && exist([V0.fname '.gz'],'file'), Po = [V0.fname '.gz']; end + + Porthfiles = '{'; Porthcolor = '{'; Porthnames = '{'; + for si=1:numel(P) + Porthfiles = [ Porthfiles , sprintf('''%s'',''%s'',',P(si).Ppial, P(si).Pwhite )]; + Porthcolor = [ Porthcolor , '''-g'',''-r'',' ]; + Porthnames = [ Porthnames , '''pial'',''white'',' ]; + end + Porthfiles = [ Porthfiles(1:end-1) '}']; + Porthcolor = [ Porthcolor(1:end-1) '}']; + Porthnames = [ Porthnames(1:end-1) '}']; + + if 1 %debug + fprintf(' Show surfaces in orthview: %s\n',spm_file(Po ,'link',... + sprintf('cat_surf_fun(''show_orthview'',%s,''%s'',%s,%s)',Porthfiles,Po,Porthcolor,Porthnames))) ; + end + + end +end +%======================================================================= +function useprior = setupprior(opt,surffolder,P,si) +%setupprior. prepare longitidunal files + + % use surface of given (average) data as prior for longitudinal mode + if isfield(opt,'useprior') && ~isempty(opt.useprior) + % RD20200729: delete later ... && exist(char(opt.useprior),'file') + % if it not exist than filecopy has to print the error + [pp1,ff1] = spm_fileparts(opt.useprior); + % correct '../' parts in directory for BIDS structure + [stat, val] = fileattrib(fullfile(pp1,surffolder)); + if stat, pp1_surffolder = val.Name; else, pp1_surffolder = fullfile(pp1,surffolder); end + + % try to copy surface files from prior to individual surface data + useprior = 1; + useprior = useprior & copyfile(fullfile(pp1_surffolder,sprintf('%s.central.%s.gii',opt.surf{si},ff1)),P(si).Pcentral,'f'); + useprior = useprior & copyfile(fullfile(pp1_surffolder,sprintf('%s.sphere.%s.gii',opt.surf{si},ff1)),P(si).Psphere,'f'); + useprior = useprior & copyfile(fullfile(pp1_surffolder,sprintf('%s.sphere.reg.%s.gii',opt.surf{si},ff1)),P(si).Pspherereg,'f'); + + if ~useprior + warn_str = sprintf('Surface files for %s not found. Move on with individual surface extraction.\n',pp1_surffolder); + fprintf('\nWARNING: %s',warn_str); + cat_io_addwarning('cat_surf_createCS4:noPiorSurface', warn_str); + else + cat_io_cprintf('blue','\n Use existing average surface as prior and thus skip unnecessary processing steps:\n %s\n',pp1_surffolder); + end + else + useprior = 0; + end +end + + + + + +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_tst_qa_cleaner.m",".m","30795","612","function varargout = cat_tst_qa_cleaner(data,opt) +%% _____________________________________________________________________ +% Estimate quality grades of given rating of one (or more) protocols +% with 2 to 6 grads to separate passed, (unassignable) and failed +% images, by finding the first peak in the image quality histogram +% and using its width (standard deviation) in a limited range. +% If multiple protocols are used, than use the site variable opt.site +% and use the site depending output rths. +% +% The passed range can be variated by opt.cf with lower values for harder +% and higher values for softer thresholds (more passed images), where +% opt.cf=1, describes a range that is similar to about 1% BWP noise that +% is equal to 5 rps. +% ROC evaluation showed that opt.cf=0.72 allows the best separation of +% images without and with artifacts, but if the majority of your data +% include light artifacts (e.g. by movements in young children) that +% a softer weighing, e.g. opt.cf=2, is preferable (maximum is 4). +% +% Use the selftest with randomly generated data to get a first impression: +% cat_tst_qa_cleaner('test') +% _____________________________________________________________________ +% +% This tool is still in development / undert test: +% * the combination of different sites is not finished +% * multiside output required a 'stacked' output +% +% [Pth,rth,sq,rths,rthsc,sqs] = cat_tst_qa_remover(data[,opt]) +% +% Pth .. global threshold for passed images +% (for odd grades this is in the middle of the unassignable) +% rth .. all global threshold(s) between grads +% sq .. estimated first peak and its std, where the std depend on +% the number of grades! +% rths .. site depending thresholds between grads of each input +% rthsc .. site depending thresholds between grads of each input +% (global corrected, removed further low quality data) +% sqs .. site depending first peaks and stds of passed data +% +% data .. array of quality ratings or xml-files +% opt .. option structure +% .grads .. number of grads (2:6, default=6, see below) +% .cf .. factor for harder/softer thresholds (defaults=0.72) +% .figure .. display histogramm with colored ranges of grads +% 1 - use current figure +% 2 - create new figure (default) +% 3 - use one test figure (default in the selftest) +% _____________________________________________________________________ +% +% Grades: +% 2 grads: +% P passed +% F failed +% 3 grads: +% P passed +% U unassignable +% F failed +% 4 grads: +% P+ clear passed +% P- just passed +% F+ just failed +% F- clear failed +% 5 grads: +% P+ clear passed +% P- just passed +% U unassignable +% F+ just failed +% F- clear failed +% 6 grads (default): +% P+ clear passed +% P passed +% P- just passed +% F+ just failed +% F failed +% F- clear failed +% +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id: 2042 2022-07-19 $ + + + clear th; + if ~exist('opt','var'), opt = struct(); end + def.cf = 0.72; % normalization factor for rating + def.grads = 6; % number of grads (default = 6) + def.model = 1; % model used for rating + def.figure = 2; % figure=2 for new/own figure + def.smooth = 0; % smoothing of output data + def.siterf = 1000000; % round factor to identify similar resolution level + def.siteavgperc = [0.10 0.90]; % ? + opt = cat_io_checkinopt(opt,def); + opt.cf = max( 0 , min( 4 , opt.cf )); % limit of cf + + % test options + %opt.model = 2; + %opt.grads = 6; + + % if no intput is given use SPM select to get some xml-files + if ~exist('data','var') || isempty(data) + data = cellstr(spm_select(inf,'XML','select qa XML-files',{},pwd,'^cat_.*')); + elseif ischar(data) + data = cellstr(data); + end + if isempty(data) || (iscell(data) && all(cellfun('isempty',data))) + if nargout>=1, varargout{1} = 3; end + if nargout>=2, varargout{2} = 3; end + if nargout>=3, varargout{3} = [2.5 0.5]; end + if nargout>=4, varargout{4} = 3*ones(size(data)); end + if nargout>=5, varargout{5} = 3*ones(size(data)); end + if nargout>=6, varargout{6} = repmat([2.5 0.5],numel(data),1); end + + return; + end + if iscell(data) && numel(data{1})>=4 + runtest = strcmp(data{1}(1:4),'test'); + else + runtest = 0; + end + if iscell(data) && ~runtest + fprintf('Load XML data'); + P = data; + xml = cat_io_xml(data,struct(),'read',1); clear data; + for di=1:numel(xml) + opt.site(di,1) = xml(di).qualityratings.res_RMS; + data(di,1) = xml(di).qualityratings.NCR; + end + end + + + % -------------------------------------------------------------------- + % If a site variable is given (e.g. by the RMS resolution) then call + % the cleanup for each subset. The threshold will be collected in a + % vector [markthss x opt.grads] with the same length as data. + % Nevertheless an average threshold will is estimated as average of + % the percentual range give by opt.siteavgperc with e.g. [0.1 0.9] to + % concider 80% of the data. + % ------------------------------------------------------------------- + if isfield(opt,'site') + if numel(opt.site)~=numel(data) + error('cat_tst_qa_cleaner:numelsitedata','Numer of elements in data and opt.site have to be equal.\n'); + end + opt.site = round(opt.site*opt.siterf)/opt.siterf; + sites = unique(opt.site); + markth = zeros(numel(sites),opt.grads-1); + markths = zeros(numel(data),opt.grads-1); + siteth = zeros(numel(data),2); + for si=1:numel(sites) + sdatai = find(opt.site==sites(si)); + opts = opt; + opts = rmfield(opts,'site'); + opts.figure = 0; + [Sth,markth(si,:),out{1:4}] = cat_tst_qa_cleaner(data(sdatai),opts); %#ok + markths(sdatai,:) = repmat(markth(si,:),numel(sdatai),1); + siteth(sdatai,:) = out{4}; + end + % estimate global threshold + markthss = sortrows(markth); + th = cat_stat_nanmean(markthss(max(1,min(numel(sites),round(numel(sites)*opt.siteavgperc(1)))):... + max(1,min(numel(sites),round(numel(sites)*opt.siteavgperc(2)))),:),1); + sd = out{3}; + thx = out{4}; + % modify local rating based on the global one + markths2 = markths; + markths2 = min(markths2,1.2*repmat(th,size(markths2,1),1)); % higher thresholds even for sides with low rating + markths2 = max(markths2,0.8*repmat(th,size(markths2,1),1)); % lower thresholds even for sides with high rating + d = data; + + else + % ----------------------------------------------------------------- + % Simulate data, if no data is given by several normal distributed + % random numbers. + % ----------------------------------------------------------------- + if exist('data','var') && ~runtest + d = data; + if numel(d)==0 + if nargout>=1, varargout{1} = nan; end + if nargout>=2, varargout{2} = nan(1,opt.grads); end + if nargout>=3, varargout{3} = nan(1,2); end + if nargout>=4, varargout{4} = nan(size(data)); end + if nargout>=5, varargout{5} = nan(size(data)); end + if nargout>=6, varargout{6} = nan(size(data)); end + return; + end + elseif iscell(data) && runtest + % Testcases with different quality ratings + scans = 100; % number of scans (per site) for simulation + if numel(data{1})>4 + testcase = str2double(data{1}(5:end)); rng(33); + else + testcase = round(rand(1)*10); + end + randoffset = 0.5*randn(1,4); + + switch testcase + case 0 % good quality, no outlier group + d = [2.0 + randoffset(1) + 0.1*randn(1,round(scans*0.80)), ... + 2.5 + randoffset(2) + 0.3*randn(1,round(scans*0.15)), ... + 4.0 + randoffset(3) + 1.0*randn(1,round(scans*0.03)), ... + 5.0 + randoffset(4) + 1.0*randn(1,round(scans*0.02))]; + case 1 % good quality, with average outlier group + d = [2.0 + randoffset(1) + 0.1*randn(1,round(scans*0.40)), ... + 2.5 + randoffset(2) + 0.3*randn(1,round(scans*0.40)), ... + 4.0 + randoffset(3) + 1.0*randn(1,round(scans*0.15)), ... + 5.0 + randoffset(4) + 1.0*randn(1,round(scans*0.05))]; + case 2 % good-average quality, with outlier group + d = [2.0 + randoffset(1) + 0.1*randn(1,round(scans*0.10)), ... + 2.5 + randoffset(2) + 0.3*randn(1,round(scans*0.50)), ... + 4.0 + randoffset(3) + 1.0*randn(1,round(scans*0.30)), ... + 5.0 + randoffset(4) + 1.0*randn(1,round(scans*0.10))]; + case 3 % good-average quality, without outlier group + d = [2.0 + randoffset(1) + 0.2*randn(1,round(scans*0.10)), ... + 2.5 + randoffset(2) + 0.3*randn(1,round(scans*0.50)), ... + 3.0 + randoffset(3) + 1.0*randn(1,round(scans*0.30)), ... + 4.0 + randoffset(4) + 1.0*randn(1,round(scans*0.10))]; + case 4 % average to low quality, with light falloff + d = [3.0 + randoffset(1) + 0.2*randn(1,round(scans*0.10)), ... + 3.5 + randoffset(2) + 0.3*randn(1,round(scans*0.50)), ... + 4.0 + randoffset(3) + 1.0*randn(1,round(scans*0.30)), ... + 5.0 + randoffset(4) + 1.0*randn(1,round(scans*0.10))]; + case 5 % high to good quality, with light falloff + d = [1.0 + randoffset(1) + 0.2*randn(1,round(scans*0.10)), ... + 1.5 + randoffset(2) + 0.3*randn(1,round(scans*0.50)), ... + 2.0 + randoffset(3) + 1.0*randn(1,round(scans*0.30)), ... + 3.0 + randoffset(4) + 1.0*randn(1,round(scans*0.10))]; + case 6 % high quality, no outlier + d = [1.0 + randoffset(1) + 0.1*randn(1,round(scans*0.80)), ... + 1.5 + randoffset(2) + 0.3*randn(1,round(scans*0.13)), ... + 3.0 + randoffset(3) + 0.3*randn(1,round(scans*0.05)), ... + 5.0 + randoffset(4) + 0.3*randn(1,round(scans*0.02))]; + case 7 % good quality with second average peak + d = [2.0 + randoffset(1) + 0.1*randn(1,round(scans*0.30)), ... + 3.0 + randoffset(2) + 0.2*randn(1,round(scans*0.40)), ... + 4.0 + randoffset(3) + 0.5*randn(1,round(scans*0.10)), ... + 5.0 + randoffset(4) + 0.5*randn(1,round(scans*0.10))]; + case 8 % good quality with second low quality peak + d = [1.0 + randoffset(1) + 0.1*randn(1,round(scans*0.50)), ... + 4.0 + randoffset(2) + 0.2*randn(1,round(scans*0.30)), ... + 4.0 + randoffset(3) + 0.5*randn(1,round(scans*0.10)), ... + 5.0 + randoffset(4) + 0.5*randn(1,round(scans*0.10))]; + case 9 % good quality with second average and third low quality peak + d = [1.5 + randoffset(1) + 0.2*randn(1,round(scans*0.20)), ... + 3.0 + randoffset(2) + 0.3*randn(1,round(scans*0.20)), ... + 4.5 + randoffset(3) + 0.2*randn(1,round(scans*0.10)), ... + 2.0 + randoffset(4) + 0.8*randn(1,round(scans*0.50))]; + case 10 % good quality with second average and third low quality peak + d = [1.5 + randoffset(1) + 0.1*randn(1,round(scans*0.10)), ... + 3.0 + randoffset(2) + 0.2*randn(1,round(scans*0.10)), ... + 4.5 + randoffset(3) + 0.2*randn(1,round(scans*0.10)), ... + 2.5 + randoffset(4) + 1.0*randn(1,round(scans*0.60))]; + end + + % remove high quality outlier and set them to normal + cor = max(1,median(d)-std(d)/2); + md= d<(cor); d(md) = cor + 0.05*randn(1,sum(md)); + + % set selftest figure + opt.figure = 3; + elseif isfield(opt,'train') + md = opt.train; + if numel(data) ~= numel(md) + error('cat_tst_qa_cleaner:dataLabelSize','Number of values and labels must be equal'); + end + end + + + % ------------------------------------------------------------------- + % Models: + % I start with several ideas that all based on a similar idea: to + % find the first peak that is given by the subset of images without + % inferences and to use the variance of this peak for further scaling + % of subsets for other grads. As far as IQR is already scaled, we + % can limit the variance value ... e.g. the rating has an error of + % 0-2 rps (0.0-0.2 mark points) that is very low for high-quality data + % and higher for low-quality data. Due to our the general subdivion + % of the rating scale in +,o, and - (e.g. B+,B,B-) we got a subrange + % of 3.33 rps (1/3 mark points) that gives some kind of upper limit. + % ------------------------------------------------------------------- + thx = nan; sd = nan; th = zeros(1,opt.grads-1); + switch opt.model + case 0 + % only global thresholding ... + % this is just to use the color bar output + thx = 3; + sd = 1; + th = 1.5:1:100; + th(6:end) = []; + case 1 + % kmeans model: + % * estimate peaks based on the histogram + % * mix the first and second peak until it fits to 30% of the data + % or until the number of loops is similar the number of peaks + % * use the std give by one BWP noise level (0.5) to describe the + % variance the passed interval. + + %H = histogram(d,0.5:1:5.5); + H.Values = hist(d,0.5:1:5.5); + peaks = sum(H.Values>(max(H.Values)/5))*3; + [thx,sdx] = cat_stat_kmeans(d,peaks); sdx = sdx./thx; + for i=1:peaks + if sum(d(max(H.Values)/5))*3; + [thx,sdx] = cat_stat_kmeans(d,peaks); sdx = sdx./thx; + for i=1:peaks + %if numel(thx)>i && sum(di && + thx(1) = cat_stat_nanmean(thx(1:2)); + sdx(1) = cat_stat_nanstd(d(d + + if isfield(opt,'train') + rvm.train(dd, mdd); + testData = dd; + elseif isfield(opt.test) + results = opt.test.test(dd, mdd); + testData = dd; + else + % both cases for simulated test + cvIndices = false(size(dd,1),1); cvIndices(1:2:size(dd,1))=true; %crossvalind('HoldOut', length(data_), 0.3); + trainData = dd(cvIndices, :); + trainLabel = label_(cvIndices, :); + testData = dd(~cvIndices, :); + testLabel = label_(~cvIndices, :); + + rvm.train(trainData, trainLabel); + results = rvm.test(testData, testLabel); + rvm.draw(results) + + %% + fprintf('GT: IQR(passed): %4.2f IQR(failed):%4.2f\n', ... + mean(dd(cellfun('isempty',strfind( label_,pf{2}))==0)), ... + mean(dd(cellfun('isempty',strfind( label_,pf{1}))==0))); + + fprintf('ML: IQR(passed): %4.2f IQR(failed):%4.2f\n', ... + mean(testData(cellfun('isempty',strfind( results.predictedLabel,pf{2}))==0)), ... + mean(testData(cellfun('isempty',strfind( results.predictedLabel,pf{1}))==0))); + end + + if 1 + % harder - closer to my model + th = ... + median(testData(cellfun('isempty',strfind( results.predictedLabel,pf{2}))==0)): ... + ((median(testData(cellfun('isempty',strfind( results.predictedLabel,pf{1}))==0)) - ... + median(testData(cellfun('isempty',strfind( results.predictedLabel,pf{2}))==0)) ) / 4 / 2) : ... + median(testData(cellfun('isempty',strfind( results.predictedLabel,pf{1}))==0)) - ... + ((median(testData(cellfun('isempty',strfind( results.predictedLabel,pf{1}))==0)) - ... + median(testData(cellfun('isempty',strfind( results.predictedLabel,pf{2}))==0)) ) / 2); + else + % original + th = ... + median(testData(cellfun('isempty',strfind( results.predictedLabel,pf{2}))==0)): ... + ((median(testData(cellfun('isempty',strfind( results.predictedLabel,pf{1}))==0)) - ... + median(testData(cellfun('isempty',strfind( results.predictedLabel,pf{2}))==0)) ) / 4 ) : ... + median(testData(cellfun('isempty',strfind( results.predictedLabel,pf{1}))==0)); + end + end + + markths = repmat(mean(th(floor(opt.grads/2):ceil(opt.grads/2))),size(data)); + markths2 = markths; + siteth = repmat([thx(1) sd],numel(data),1); +% passed = data < markths; + + % use prediction rather than treshold + if opt.model == 4 + passed = testData(cellfun('isempty',strfind( results.predictedLabel,pf{2}))==0); + end + end + + + +%% --------------------------------------------------------------------- +% Print: +% This part is just for to plot a colorated histogram and the percents +% of images in each group. +% --------------------------------------------------------------------- + if opt.figure + if opt.figure==2 + f = figure; + set(f,'color','w') + elseif opt.figure==3 + f = findobj('type','figure','name','qa_cleaner_test'); + if isempty(f), figure('name','qa_cleaner_test'); else, figure(f(1)); clf(f(1)); end + end + box on; + + %figure + ss = 0.05; + [h,r] = hist(d,0.5:ss:10.5); + %H = histogram(d,0.5:ss:10.5); h = H.Values; r = H.BinEdges; + for i=1:opt.smooth, h(2:end-1) = cat_stat_nanmean(cat(1,h(1:end-2),h(2:end-1),h(3:end)),1); end + sh = 1; %sum(h); + + % background histogram (all data) + %bar(r,h/sh,'facecolor',[0.8 0.8 0.8],'edgecolor','none'); + %fill(r,h/sh,[0.8 0.8 0.8],'edgecolor','none'); + hold on + + yl = [0 max(h)+1]; ylim(yl); + % main grid + for i=1.5:6, plot([i i],ylim,'color',[0.8 0.8 0.8]); end + switch numel(th) + case 1 + hx = h; hx(r> th(1)+ss) = 0; fill(r,hx/sh,[0.0 0.5 0.2],'edgecolor','none'); + hx = h; hx(r<=th(1)-ss) = 0; fill(r,hx/sh,[0.6 0.15 0.1],'edgecolor','none'); + % main values + text(5,yl(2)*0.93,sprintf('%5.2f%% passed',sum(d< th(1))/numel(d)*100) ,'color',[0.0 0.5 0.2]); + text(5,yl(2)*0.85,sprintf('%5.2f%% failed',sum(d>=th(1))/numel(d)*100) ,'color',[0.6 0.15 0.1]); + case 2 + hx = h; hx(r>=th(1)+ss) = 0; fill(r,hx/sh,[0.0 0.5 0.2],'edgecolor','none'); + hx = h; hx(r<=th(1) | r>th(2)) = 0; fill(r,hx/sh,[0.85 0.75 0.3],'edgecolor','none'); + hx = h; hx(r<=th(2)-ss) = 0; fill(r,hx/sh,[0.6 0.15 0.1],'edgecolor','none'); + % main values + text(5,yl(2)*0.93,sprintf('%5.2f%% passed',sum(d=th(1) & d=th(2))/numel(d)*100) ,'color',[0.6 0.15 0.1]); + case 3 + % plot + hx = h; hx(r>=th(1)+ss) = 0; fill(r,hx/sh,[0.0 0.5 0.2],'edgecolor','none'); + hx = h; hx(r<=th(1)-ss | r>th(2)) = 0; fill(r,hx/sh,[0.7 0.8 0.2],'edgecolor','none'); + hx = h; hx(r<=th(2)-ss | r>th(3)) = 0; fill(r,hx/sh,[0.9 0.6 0.4],'edgecolor','none'); + hx = h; hx(r<=th(3)-ss) = 0; fill(r,hx/sh,[0.6 0.15 0.1],'edgecolor','none'); + % main values + text(5,yl(2)*0.93,sprintf('%5.2f%% passed',sum(d< th(2))/numel(d)*100),'color',[0 0.7 0]); + text(5,yl(2)*0.88,sprintf('%5.2f%% failed',sum(d>=th(2))/numel(d)*100),'color',[0.8 0.0 0]); + % detailed values + text(5,yl(2)*0.75,sprintf('%5.2f%% passed+',sum(d< th(1))/numel(d)*100) ,'color',[0.0 0.5 0.2]); + text(5,yl(2)*0.70,sprintf('%5.2f%% passed-',sum(d>=th(1) & d=th(2) & d=th(3))/numel(d)*100) ,'color',[0.6 0.15 0.1]); + case 4 + % plot + hx = h; hx(r>=th(1)+ss) = 0; fill(r,hx/sh,[0.0 0.5 0.2],'edgecolor','none'); + hx = h; hx(r<=th(1)-ss | r>th(2)) = 0; fill(r,hx/sh,[0.4 0.7 0.1],'edgecolor','none'); + hx = h; hx(r<=th(2)-ss | r>th(3)) = 0; fill(r,hx/sh,[0.85 0.75 0.3],'edgecolor','none'); + hx = h; hx(r<=th(3)-ss | r>th(4)) = 0; fill(r,hx/sh,[0.75 0.3 0.2],'edgecolor','none'); + hx = h; hx(r<=th(4)-ss) = 0; fill(r,hx/sh,[0.6 0.15 0.1],'edgecolor','none'); + % main values + text(5,yl(2)*0.93,sprintf('%5.2f%% passed',sum(d=th(2) & d=th(3))/numel(d)*100) ,'color',[0.7 0.0 0.0]); + % detailed values + text(5,yl(2)*0.75,sprintf('%5.2f%% passed+',sum(d=th(1) & d=th(2) & d=th(3) & d=th(4))/numel(d)*100) ,'color',[0.6 0.15 0.1]); + case 5 + % plot + testbar=0; % it would be cool to use bars but they failed at least in MATLAB R2013 and killed the axis positions... + if testbar==1 + hx = h; hx(r>=th(1)+ss) = 0; bar(r,hx/sh,'facecolor',[0.0 0.5 0.2],'edgecolor','none','barwidth',1); + hx = h; hx(r<=th(1)-ss | r>th(2)) = 0; bar(r,hx/sh,'facecolor',[0.4 0.7 0.1],'edgecolor','none','barwidth',1); + hx = h; hx(r<=th(2)-ss | r>th(3)) = 0; bar(r,hx/sh,'facecolor',[0.7 0.8 0.2],'edgecolor','none','barwidth',1); + hx = h; hx(r<=th(3)-ss | r>th(4)) = 0; bar(r,hx/sh,'facecolor',[0.9 0.6 0.4],'edgecolor','none','barwidth',1); + hx = h; hx(r<=th(4)-ss | r>th(5)) = 0; bar(r,hx/sh,'facecolor',[0.75 0.3 0.2],'edgecolor','none','barwidth',1); + hx = h; hx(r<=th(5)-ss) = 0; bar(r,hx/sh,'facecolor',[0.6 0.15 0.1],'edgecolor','none','barwidth',1); + else + hx = h; hx(r>=th(1)+ss) = 0; fill(r,hx/sh,[0.0 0.5 0.2],'edgecolor','none'); + hx = h; hx(r<=th(1)-ss | r>th(2)) = 0; fill(r,hx/sh,[0.4 0.7 0.1],'edgecolor','none'); + hx = h; hx(r<=th(2)-ss | r>th(3)) = 0; fill(r,hx/sh,[0.7 0.8 0.2],'edgecolor','none'); + hx = h; hx(r<=th(3)-ss | r>th(4)) = 0; fill(r,hx/sh,[0.9 0.6 0.4],'edgecolor','none'); + hx = h; hx(r<=th(4)-ss | r>th(5)) = 0; fill(r,hx/sh,[0.75 0.3 0.2],'edgecolor','none'); + hx = h; hx(r<=th(5)-ss) = 0; fill(r,hx/sh,[0.6 0.15 0.1],'edgecolor','none'); + end + % main values + text(5,yl(2)*0.93,sprintf('%5.2f%% passed',sum(d=th(3))/numel(d)*100),'color',[0.8 0.0 0]); + % detailed values + text(5,yl(2)*0.75,sprintf('%5.2f%% passed+',sum(d=th(1) & d=th(2) & d=th(3) & d=th(4) & d=th(5))/numel(d)*100) ,'color',[0.6 0.15 0.1]); + end + xlim([min(r),6.5]); + + % subgrid + for i=5/6:1/3:6.4, plot([i i],[0 0.03]*max(ylim),'color',[0.2 0.2 0.2]); end + + QMC = cat_io_colormaps('marks+',17); + color = @(QMC,m) QMC(max(1,min(size(QMC,1),round(((m-1)*3)+1))),:); + + + % colored main grads + FS = get(gca,'Fontsize')*1.3; + set(gca,'XTick',0.5:1:6.5,'XTickLabel',{'100','90','80','70','60','50','40'},'TickLength',[0.02 0.02]); + % further color axis objects... + axA = copyobj(gca,gcf); axB = copyobj(axA,gcf); axC = copyobj(gca,gcf); + axD = copyobj(gca,gcf); axE = copyobj(gca,gcf); axF = copyobj(gca,gcf); + % set colors... + set(axA,'YTick',[],'XTickLabel',{},'XTick',1,'XColor',color(QMC,1),'Color','none','XTicklabel','A','TickLength',[0 0],'Fontsize',FS,'Fontweight','bold'); + set(axB,'YTick',[],'XTickLabel',{},'XTick',2,'XColor',color(QMC,2),'Color','none','XTicklabel','B','TickLength',[0 0],'Fontsize',FS,'Fontweight','bold'); + set(axC,'YTick',[],'XTickLabel',{},'XTick',3,'XColor',color(QMC,3),'Color','none','XTicklabel','C','TickLength',[0 0],'Fontsize',FS,'Fontweight','bold'); + set(axD,'YTick',[],'XTickLabel',{},'XTick',4,'XColor',color(QMC,4),'Color','none','XTicklabel','D','TickLength',[0 0],'Fontsize',FS,'Fontweight','bold'); + set(axE,'YTick',[],'XTickLabel',{},'XTick',5,'XColor',color(QMC,5),'Color','none','XTicklabel','E','TickLength',[0 0],'Fontsize',FS,'Fontweight','bold'); + set(axF,'YTick',[],'XTickLabel',{},'XTick',6,'XColor',color(QMC,6),'Color','none','XTicklabel','F','TickLength',[0 0],'Fontsize',FS,'Fontweight','bold'); + hold off; + + if isfield(opt,'site') && numel(sites)>1 + title(sprintf('Histogram (cf=%0.2f) - global treshold for multisite output (n=%d)',opt.cf,numel(sites)),'Fontsize',FS); + else + title(sprintf('Histogram (cf=%0.2f)',opt.cf),'Fontsize',FS); + end + xlabel('IQR (rps)','Fontsize',FS); + ylabel('number of scans','Fontsize',FS); + end + %% + MarkColor = cat_io_colormaps('marks+',40); + if isfield(opt,'site') && numel(sites)>1, globcorr = ' (global corrected)'; else, globcorr = ''; end + if exist('P','var') + files = P(data<=markths2(:,3)); + fprintf('PASSED%s: %0.2f%%\n',globcorr,numel(files)/numel(data)*100) + if 0 + iqrs = [xml(data<=markths2(:,3)).qualityratings]; + for fi=1:numel(files) + cat_io_cprintf(MarkColor(max(1,round( iqrs(fi).IQR/9.5 * size(MarkColor,1))),:),' %s\n',files{fi,1}); + end + else + + end + + % bad files ... + files = P(data>markths2(:,3) & data<=markths2(:,4)); + fprintf('FAILED+%s: %0.2f%%\n',globcorr,numel(files)/numel(data)*100) + if 1 + iqrs = [xml(data>markths2(:,3) & data<=markths2(:,4)).qualityratings]; + for fi=1:numel(files) + cat_io_cprintf(MarkColor(max(1,round( iqrs(fi).IQR/9.5 * size(MarkColor,1))),:),' %s\n',files{fi,1}); + end + end + files = P(data>markths2(:,4) & data<=markths2(:,5)); + iqrs = [xml(data>markths2(:,4) & data<=markths2(:,5)).qualityratings]; + if 1 + fprintf('FAILED%s: %0.2f%%\n',globcorr,numel(files)/numel(data)*100) + for fi=1:numel(files) + cat_io_cprintf(MarkColor(max(1,round( iqrs(fi).IQR/9.5 * size(MarkColor,1))),:),' %s\n',files{fi,1}); + end + end + files = P(data>markths2(:,5)); + fprintf('FAILED-%s: %0.2f%%\n',globcorr,numel(files)/numel(data)*100) + if 1 + iqrs = [xml(data>markths2(:,5)).qualityratings]; + for fi=1:numel(files) + cat_io_cprintf(MarkColor(max(1,round( iqrs(fi).IQR/9.5 * size(MarkColor,1))),:),' %s\n',files{fi,1}); + end + end + end + + + %% create output + if nargout>=1, varargout{1} = mean(th(floor(opt.grads/2):ceil(opt.grads/2))); end + if nargout>=2, varargout{2} = th; end + if nargout>=3, varargout{3} = [thx(1) sd(1)]; end + if nargout>=4, varargout{4} = markths; end + if nargout>=5, varargout{5} = markths2; end + if nargout>=6, varargout{6} = siteth; end + if nargout>=7, varargout{7} = passed; end + if isfield(opt,'rvmtrain'), varargout{1} = rvm; end + if isfield(opt,'rvmtest'), varargout{2} = passed; end + + if 0 + %% + b = uicontrol('Parent',f,'Style','slider','Position',[81,54,419,23],... + 'value',zeta, 'min',0, 'max',1); + bgcolor = f.Color; + bl1 = uicontrol('Parent',f,'Style','text','Position',[50,54,23,23],... + 'String','0','BackgroundColor',bgcolor); + bl2 = uicontrol('Parent',f,'Style','text','Position',[500,54,23,23],... + 'String','1','BackgroundColor',bgcolor); + bl3 = uicontrol('Parent',f,'Style','text','Position',[240,25,100,23],... + 'String','Damping Ratio','BackgroundColor',bgcolor); + end +end +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_vol_pbtp.c",".c","9307","261","/* quasi-euclidean distance calculation + * _____________________________________________________________________________ + * [GMT,RPM] = cat_vol_pbtp(SEG,WMD,CSFD[,opt]) + * + * SEG = (single) segment image with low and high boundary bd + * GMT = (single) thickness image + * RPM = (single) radial position map + * WMD = (single) CSF distance map + * CSFD = (single) CSF distance map + * + * opt.bd = (single) [low,high] boundary values (default 1.5 and 2.5) + * opt.CSFD = calculate CSFD + * opt.PVE = use PVE information (0=none,1=fast,2=exact) + * + * ______________________________________________________________________ + * + * Christian Gaser, Robert Dahnke + * Structural Brain Mapping Group (https://neuro-jena.github.io) + * Departments of Neurology and Psychiatry + * Jena University Hospital + * ______________________________________________________________________ + * $Id$ + */ + +/* + * TODO: + * - eikonal distance for subsegmentation (region growing) + * - own labeling ( + */ + +#include ""mex.h"" +#include ""math.h"" +#include +/* #include ""matrix.h"" */ + +#ifndef min +#define min(a,b) (((a)<(b))?(a):(b)) +#endif +#ifndef max +#define max(a,b) (((a)>(b))?(a):(b)) +#endif + +struct opt_type { + int CSFD; /* use CSFD */ + int PVE; /* 0, 1=fast, 2=exact */ + float LB, HB, LLB, HLB, LHB, HHB; /* boundary */ + int sL[3]; + } opt; + +/* get all values of the voxels which are in WMD-range (children of this voxel) */ +float pmax(const float GMT[], const float RPM[], const float SEG[], const float ND[], const float WMD, const float SEGI, const int sA) { + float T[27]; + float n=0.0, maximum=WMD; + for (int i=0;i<27;i++) T[i]=-1; + + /* the pure maximum */ + /* (GMT[i]<1e15) && (maximum < GMT[i]) && ((RPM[i]-ND[i]*1.25)<=WMD) && ((RPM[i]-ND[i]*0.5)>WMD) && (SEGI)>=SEG[i] && SEG[i]>1 && SEGI>1.66) */ + for (int i=0;i<=sA;i++) { + if ( ( GMT[i] < 1e15 ) && ( maximum < GMT[i] ) && /* thickness/WMD of neighbors should be larger */ + ( SEG[i] >= 1.0 ) && ( SEGI>1.2 && SEGI<=2.75 ) && /* projection range */ + ( ( ( RPM[i] - ND[i] * 1.2 ) <= WMD ) ) && /* upper boundary - maximum distance */ + ( ( ( RPM[i] - ND[i] * 0.5 ) > WMD ) || ( SEG[i]<1.5 ) ) && /* lower boundary - minimum distance - corrected values outside */ + ( ( ( (SEGI * max(1.0,min(1.2,SEGI-1.5)) ) >= SEG[i] ) ) || ( SEG[i]<1.5 ) ) ) /* for high values will project data over sulcal gaps */ + { maximum = GMT[i]; } + } + + + /* the mean of the highest values*/ + float maximum2=maximum; float m2n=0.0; + for (int i=0;i<=sA;i++) { + if ( ( GMT[i] < 1e15 ) && ( (maximum - 1) < GMT[i] ) && + ( SEG[i] >= 1.0 ) && ( SEGI>1.2 && SEGI<=2.75 ) && + ( ( (RPM[i] - ND[i] * 1.2 ) <= WMD ) ) && + ( ( (RPM[i] - ND[i] * 0.5 ) > WMD ) || ( SEG[i]<1.5 ) ) && + ( ( ( (SEGI * max(1.0,min(1.2,SEGI-1.5)) ) >= SEG[i] ) ) || ( SEG[i]<1.5 ) ) ) + { maximum2 = maximum2 + GMT[i]; m2n++; } + } + if ( m2n > 0.0 ) maximum = (maximum2 - maximum) / m2n; + + return maximum; +} + + + + +/* estimate x,y,z position of index i in an array size sx,sxy=sx*sy... */ +void ind2sub(int i, int *x, int *y, int *z, int snL, int sxy, int sy) { + /* not here ... + * if (i<0) i=0; + * if (i>=snL) i=snL-1; + */ + + *z = (int)floor( (double)i / (double)sxy ) ; + i = i % (sxy); + *y = (int)floor( (double)i / (double)sy ) ; + *x = i % sy ; +} + + + +/* main function */ +void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { + if (nrhs<3) mexErrMsgTxt(""ERROR: not enough input elements\n""); + if (nrhs>4) mexErrMsgTxt(""ERROR: too many input elements.\n""); + if (nlhs<1) mexErrMsgTxt(""ERROR: not enough output elements.\n""); + if (nlhs>2) mexErrMsgTxt(""ERROR: too many output elements.\n""); + if (mxIsSingle(prhs[0])==0) mexErrMsgTxt(""ERROR: first input must be an 3d single matrix\n""); + + + /* main information about input data (size, dimensions, ...) */ + const mwSize *sL = mxGetDimensions(prhs[0]); + mwSize sSEG[3] = {sL[0],sL[1],sL[2]}; + const int dL = mxGetNumberOfDimensions(prhs[0]); + const int nL = mxGetNumberOfElements(prhs[0]); + const int x = sL[0]; + const int y = sL[1]; + const int xy = x*y; + const float s2 = sqrt(2.0); + const float s3 = sqrt(3.0); + const int nr = nrhs; + + /* indices of the neighbor Ni (index distance) and euclidean distance NW */ + const int sN = 14; + const int NI[14] = { 0, -1,-x+1, -x,-x-1, -xy+1,-xy,-xy-1, -xy+x+1,-xy+x,-xy+x-1, -xy-x+1,-xy-x,-xy-x-1}; + const float ND[14] = {0.0,1.0, s2,1.0, s2, s2,1.0, s2, s3, s2, s3, s3, s2, s3}; + float DN[14],DI[14],GMTN[14],WMDN[14],SEGN[14],DNm; + float du, dv, dw, dnu, dnv, dnw, d, dcf, WMu, WMv, WMw, GMu, GMv, GMw, SEGl, SEGu, tmpfloat; + int ni,u,v,w,nu,nv,nw, tmpint, WMC=0, CSFC=0; + + /* main volumes - actual without memory optimization ... */ + mxArray *hlps[1]; + hlps[0] = mxCreateNumericArray(dL,sL,mxSINGLE_CLASS,mxREAL); + plhs[0] = mxCreateNumericArray(dL,sL,mxSINGLE_CLASS,mxREAL); +/* not yet defined + plhs[2] = mxCreateNumericArray(dL,sL,mxSINGLE_CLASS,mxREAL); + plhs[3] = mxCreateNumericArray(dL,sL,mxSINGLE_CLASS,mxREAL); + plhs[4] = mxCreateNumericArray(dL,sL,mxUINT32_CLASS,mxREAL); +*/ + + /* input variables */ + float*SEG = (float *)mxGetPr(prhs[0]); + float*WMD = (float *)mxGetPr(prhs[1]); + float*CSFD = (float *)mxGetPr(prhs[2]); + + /*if ( nrhs>1) { + tmpint = (int)mxGetScalar(mxGetField(prhs[1],1,""CSFD"")); printf(""X=%d"", tmpint); if ( tmpint!=NULL && (tmpint>=0 && tmpint<=1) ) opt.CSFD = tmpint; else opt.CSFD = 1; + tmpint = (int)mxGetScalar(mxGetField(prhs[1],1,""PVE"")); printf(""X=%d"", tmpint); if ( tmpint!=NULL && (tmpint>=0 && tmpint<=2) ) opt.PVE = tmpint; else opt.PVE = 2; + tmpfloat = (float)mxGetScalar(mxGetField(prhs[1],1,""LB"")); printf(""X=%d"", tmpfloat); if ( tmpfloat!=NULL ) opt.LB = tmpfloat; else opt.LB = 1.5; + tmpfloat = (float)mxGetScalar(mxGetField(prhs[1],1,""HB"")); printf(""X=%d"", tmpfloat); if ( tmpfloat!=NULL ) opt.HB = tmpfloat; else opt.HB = 2.5; + } + else */{ opt.CSFD = 1;opt.PVE = 2;opt.LB = 1.5;opt.HB = 2.5; } + opt.LLB=floor(opt.LB), opt.HLB=ceil(opt.LB), opt.LHB=floor(opt.HB), opt.HHB=ceil(opt.HB); + + /* output variables */ + float *GMT = (float *)mxGetPr(plhs[0]); + float *RPM = (float *)mxGetPr(hlps[0]); + + + /* intitialisiation */ + for (int i=0;i=opt.HB ) WMC++; + if ( SEG[i]<=opt.LB ) CSFC++; + } + if (WMC==0) mexErrMsgTxt(""ERROR: no WM voxel\n""); + if (CSFC==0) opt.CSFD = 0; + + + +/* thickness calculation + ======================================================================= */ + for (int i=0;iopt.LLB && SEG[i]=nL) || (abs(nu-u)>1) || (abs(nv-v)>1) || (abs(nw-w)>1)) ni=i; + GMTN[n] = GMT[ni]; WMDN[n] = RPM[ni]; SEGN[n] = SEG[ni]; + } + + /* find minimum distance within the neighborhood */ + DNm = pmax(GMTN,WMDN,SEGN,ND,WMD[i],SEG[i],sN); + GMT[i] = DNm; + } + } + + for (int i=nL-1;i>=0;i--) { + if (SEG[i]>opt.LLB && SEG[i]=nL) || (abs(nu-u)>1) || (abs(nv-v)>1) || (abs(nw-w)>1)) ni=i; + GMTN[n] = GMT[ni]; WMDN[n] = RPM[ni]; SEGN[n] = SEG[ni]; + } + + /* find minimum distance within the neighborhood */ + DNm = pmax(GMTN,WMDN,SEGN,ND,WMD[i],SEG[i],sN); + if ( GMT[i] < DNm && DNm>0 ) GMT[i] = DNm; + } + } + + for (int i=0;iopt.HB) GMT[i] = 0.0; + + + + + +/* final settings... + ======================================================================= */ + float CSFDc = 0.0, GMTi, CSFDi; /* 0.125 */ + for (int i=0;i=opt.LB && SEG[i]<=opt.LB) { + GMTi = CSFD[i] + WMD[i]; + CSFDi = GMT[i] - WMD[i]; + + if ( CSFD[i]>CSFDi ) CSFD[i] = CSFDi; + else GMT[i] = GMTi; + } + } + + +/* estimate RPM + ======================================================================= */ + for (int i=0;i=opt.HB ) + RPM[i] = 1.0; + else { + if ( SEG[i]<=opt.LB || GMT[i]==0.0 ) + RPM[i] = 0.0; + else { + RPM[i] = (GMT[i] - WMD[i]) / GMT[i]; + if (RPM[i]>1.0) RPM[i] = 1.0; + if (RPM[i]<0.0) RPM[i] = 0.0; + } + } + } + + /* create second output */ + if ( nlhs > 1 ) { + plhs[1] = mxCreateNumericArray(dL,sL,mxSINGLE_CLASS,mxREAL); + float *RPMO = (float *)mxGetPr(plhs[1]); + for (int i=0;i 1 && isfield(job,'extopts') + if ~isfield(job.extopts,'subfolders') + job.extopts.subfolders = cat_get_defaults('extopts.subfolders'); + end + subfolders = job.extopts.subfolders; + if isfield(job.extopts,'BIDSfolder') || isfield(job.extopts,'BIDSfolder2') + if isfield(job.extopts,'BIDSfolder') + BIDSfolder_rel = job.extopts.BIDSfolder; + else + BIDSfolder_rel = job.extopts.BIDSfolder2; + end + end + else + subfolders = cat_get_defaults('extopts.subfolders'); + end + + if subfolders + labelfolder = 'label'; + mrifolder = 'mri'; + surffolder = 'surf'; + reportfolder = 'report'; + errfolder = 'err'; + else + labelfolder = ''; + mrifolder = ''; + surffolder = ''; + reportfolder = ''; + errfolder = ''; + end + + % in case of image headers just use the first filename + sub_ses_anat = ''; + if isstruct( fname ) + fname = fname(1).fname; + end + % check whether sub-name is found and ""anat"" and ""ses-"" subfolder + if ~isempty(fname) + fname = char(fname); + % to indicate BIDS structure rely on presence of a folder named ""sub-*"" in the path + % Support both BIDS standard (sub-) and common variant (sub_) + if exist('job','var') && isfield(job,'extopts') && (isfield(job.extopts,'BIDSfolder') || isfield(job.extopts,'BIDSfolder2')) + ppath = spm_fileparts(fname); + % Split path into parts and find the last folder starting with 'sub-' or 'sub_' + parts = strsplit(ppath, filesep); + ind = []; + for pi = length(parts):-1:1 + if ~isempty(parts{pi}) && (strncmp(parts{pi}, 'sub-', 4) || strncmp(parts{pi}, 'sub_', 4)) + % Found a subject folder, reconstruct the position in the original path + ind = strfind(ppath, [filesep parts{pi}]); + if ~isempty(ind) + ind = ind(end); % Use the last occurrence + break; + end + end + end + + if ~isempty(ind) + % Found a subject folder; derive dataset root and relative subject/session/anat path + % Use the directory path (ppath) consistently to avoid including the filename + sub_ses_anat = ppath(ind+1:end); + % Anchor derivatives at dataset root (one level above the subject folders) + BIDShome = ppath(1:ind-1); + + % sanitize BIDSfolder_rel by removing any leading ../ levels in both modes + bf = BIDSfolder_rel; + if ~isempty(bf) + while strncmp(bf, ['..' filesep], 3) + bf = bf(4:end); + end + if ~isempty(bf) && (bf(1) == filesep) + bf = bf(2:end); + end + end + + % Compute relative path from current file location (ppath) to derivatives folder + % Count directory levels from ppath to dataset root + parts_ppath = strsplit(ppath, filesep); + parts_root = strsplit(BIDShome, filesep); + % Find how many levels up we need to go from ppath to reach dataset root + levels_up = length(parts_ppath) - length(parts_root); + + % Build relative path: ../../../derivatives/CAT.../sub-.../ses-.../anat + rel_path = ''; + for i = 1:levels_up + rel_path = [rel_path '..' filesep]; + end + BIDSfolder = [rel_path bf]; + else + % RD202403: No BIDS subject folder detected -> use depth-based fallback for non-BIDS structures + % alternative definition based on the depth of the file to keep subdirectories + subdirs = strfind(BIDSfolder_rel,'../'); + fname2 = spm_file(fname,'path'); + for si = 1:numel(subdirs) + [fname2,ff,ee] = spm_fileparts(fname2); + sub_ses_anat = fullfile([ff ee], sub_ses_anat); + end + end + end + end + % (kept for backward compatibility if needed) sub_ses_anat holds the relative path from sub-* to the acquisition folder + + % add BIDS structure if defined + if exist('BIDSfolder','var') && ~isempty(BIDSfolder) + + % don't use common subfolder names if BIDS structure + % was found in filename + if ~isempty(sub_ses_anat) + labelfolder = sub_ses_anat; + mrifolder = sub_ses_anat; + surffolder = sub_ses_anat; + reportfolder = sub_ses_anat; + errfolder = sub_ses_anat; + end + + % check whether fname already contains BIDSfolder filename and don't + % use any subfolders again + if ~isempty(strfind(fname,spm_file(BIDSfolder,'filename'))) && ~isempty(sub_ses_anat) + labelfolder = ''; + mrifolder = ''; + surffolder = ''; + reportfolder = ''; + errfolder = ''; + elseif isempty(strfind(fname,spm_file(BIDSfolder,'filename'))) + % combine with BIDS folder structure + labelfolder = fullfile(BIDSfolder,labelfolder); + mrifolder = fullfile(BIDSfolder,mrifolder); + surffolder = fullfile(BIDSfolder,surffolder); + reportfolder = fullfile(BIDSfolder,reportfolder); + errfolder = fullfile(BIDSfolder,errfolder); + end + + % if BIDS structure was found but not defined leave subfolder names empty + elseif ~isempty(sub_ses_anat) + labelfolder = ''; + mrifolder = ''; + surffolder = ''; + reportfolder = ''; + errfolder = ''; + end +end","MATLAB" +"Neurology","ChristianGaser/cat12","tricases.h",".h","18566","268","/* essentially the case table from ./common/vtkMarchingCubesCases.h */ + +int tricases[256][19] = { +{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, /* 0 0 */ +{ 0, 3, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, /* 1 1 */ +{ 0, 9, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, /* 2 1 */ +{ 1, 3, 8, 9, 1, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, /* 3 2 */ +{ 1, 11, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, /* 4 1 */ +{ 0, 3, 8, 1, 11, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, /* 5 3 */ +{ 9, 11, 2, 0, 9, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, /* 6 2 */ +{ 2, 3, 8, 2, 8, 11, 11, 8, 9, -1, -1, -1, -1, -1, -1, -1}, /* 7 5 */ +{ 3, 2, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, /* 8 1 */ +{ 0, 2, 10, 8, 0, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, /* 9 2 */ +{ 1, 0, 9, 2, 10, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, /* 10 3 */ +{ 1, 2, 10, 1, 10, 9, 9, 10, 8, -1, -1, -1, -1, -1, -1, -1}, /* 11 5 */ +{ 3, 1, 11, 10, 3, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, /* 12 2 */ +{ 0, 1, 11, 0, 11, 8, 8, 11, 10, -1, -1, -1, -1, -1, -1, -1}, /* 13 5 */ +{ 3, 0, 9, 3, 9, 10, 10, 9, 11, -1, -1, -1, -1, -1, -1, -1}, /* 14 5 */ +{ 9, 11, 8, 11, 10, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, /* 15 8 */ +{ 4, 8, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, /* 16 1 */ +{ 4, 0, 3, 7, 4, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, /* 17 2 */ +{ 0, 9, 1, 8, 7, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, /* 18 3 */ +{ 4, 9, 1, 4, 1, 7, 7, 1, 3, -1, -1, -1, -1, -1, -1, -1}, /* 19 5 */ +{ 1, 11, 2, 8, 7, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, /* 20 4 */ +{ 3, 7, 4, 3, 4, 0, 1, 11, 2, -1, -1, -1, -1, -1, -1, -1}, /* 21 7 */ +{ 9, 11, 2, 9, 2, 0, 8, 7, 4, -1, -1, -1, -1, -1, -1, -1}, /* 22 7 */ +{ 2, 9, 11, 2, 7, 9, 2, 3, 7, 7, 4, 9, -1, -1, -1, -1}, /* 23 14 */ +{ 8, 7, 4, 3, 2, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, /* 24 3 */ +{10, 7, 4, 10, 4, 2, 2, 4, 0, -1, -1, -1, -1, -1, -1, -1}, /* 25 5 */ +{ 9, 1, 0, 8, 7, 4, 2, 10, 3, -1, -1, -1, -1, -1, -1, -1}, /* 26 6 */ +{ 4, 10, 7, 9, 10, 4, 9, 2, 10, 9, 1, 2, -1, -1, -1, -1}, /* 27 9 */ +{ 3, 1, 11, 3, 11, 10, 7, 4, 8, -1, -1, -1, -1, -1, -1, -1}, /* 28 7 */ +{ 1, 11, 10, 1, 10, 4, 1, 4, 0, 7, 4, 10, -1, -1, -1, -1}, /* 29 11 */ +{ 4, 8, 7, 9, 10, 0, 9, 11, 10, 10, 3, 0, -1, -1, -1, -1}, /* 30 12 */ +{ 4, 10, 7, 4, 9, 10, 9, 11, 10, -1, -1, -1, -1, -1, -1, -1}, /* 31 5 */ +{ 9, 4, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, /* 32 1 */ +{ 9, 4, 5, 0, 3, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, /* 33 3 */ +{ 0, 4, 5, 1, 0, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, /* 34 2 */ +{ 8, 4, 5, 8, 5, 3, 3, 5, 1, -1, -1, -1, -1, -1, -1, -1}, /* 35 5 */ +{ 1, 11, 2, 9, 4, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, /* 36 3 */ +{ 3, 8, 0, 1, 11, 2, 4, 5, 9, -1, -1, -1, -1, -1, -1, -1}, /* 37 6 */ +{ 5, 11, 2, 5, 2, 4, 4, 2, 0, -1, -1, -1, -1, -1, -1, -1}, /* 38 5 */ +{ 2, 5, 11, 3, 5, 2, 3, 4, 5, 3, 8, 4, -1, -1, -1, -1}, /* 39 9 */ +{ 9, 4, 5, 2, 10, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, /* 40 4 */ +{ 0, 2, 10, 0, 10, 8, 4, 5, 9, -1, -1, -1, -1, -1, -1, -1}, /* 41 7 */ +{ 0, 4, 5, 0, 5, 1, 2, 10, 3, -1, -1, -1, -1, -1, -1, -1}, /* 42 7 */ +{ 2, 5, 1, 2, 8, 5, 2, 10, 8, 4, 5, 8, -1, -1, -1, -1}, /* 43 11 */ +{11, 10, 3, 11, 3, 1, 9, 4, 5, -1, -1, -1, -1, -1, -1, -1}, /* 44 7 */ +{ 4, 5, 9, 0, 1, 8, 8, 1, 11, 8, 11, 10, -1, -1, -1, -1}, /* 45 12 */ +{ 5, 0, 4, 5, 10, 0, 5, 11, 10, 10, 3, 0, -1, -1, -1, -1}, /* 46 14 */ +{ 5, 8, 4, 5, 11, 8, 11, 10, 8, -1, -1, -1, -1, -1, -1, -1}, /* 47 5 */ +{ 9, 8, 7, 5, 9, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, /* 48 2 */ +{ 9, 0, 3, 9, 3, 5, 5, 3, 7, -1, -1, -1, -1, -1, -1, -1}, /* 49 5 */ +{ 0, 8, 7, 0, 7, 1, 1, 7, 5, -1, -1, -1, -1, -1, -1, -1}, /* 50 5 */ +{ 1, 3, 5, 3, 7, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, /* 51 8 */ +{ 9, 8, 7, 9, 7, 5, 11, 2, 1, -1, -1, -1, -1, -1, -1, -1}, /* 52 7 */ +{11, 2, 1, 9, 0, 5, 5, 0, 3, 5, 3, 7, -1, -1, -1, -1}, /* 53 12 */ +{ 8, 2, 0, 8, 5, 2, 8, 7, 5, 11, 2, 5, -1, -1, -1, -1}, /* 54 11 */ +{ 2, 5, 11, 2, 3, 5, 3, 7, 5, -1, -1, -1, -1, -1, -1, -1}, /* 55 5 */ +{ 7, 5, 9, 7, 9, 8, 3, 2, 10, -1, -1, -1, -1, -1, -1, -1}, /* 56 7 */ +{ 9, 7, 5, 9, 2, 7, 9, 0, 2, 2, 10, 7, -1, -1, -1, -1}, /* 57 14 */ +{ 2, 10, 3, 0, 8, 1, 1, 8, 7, 1, 7, 5, -1, -1, -1, -1}, /* 58 12 */ +{10, 1, 2, 10, 7, 1, 7, 5, 1, -1, -1, -1, -1, -1, -1, -1}, /* 59 5 */ +{ 9, 8, 5, 8, 7, 5, 11, 3, 1, 11, 10, 3, -1, -1, -1, -1}, /* 60 10 */ +{ 5, 0, 7, 5, 9, 0, 7, 0, 10, 1, 11, 0, 10, 0, 11, -1}, /* 61 7 */ +{10, 0, 11, 10, 3, 0, 11, 0, 5, 8, 7, 0, 5, 0, 7, -1}, /* 62 7 */ +{10, 5, 11, 7, 5, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, /* 63 2 */ +{11, 5, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, /* 64 1 */ +{ 0, 3, 8, 5, 6, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, /* 65 4 */ +{ 9, 1, 0, 5, 6, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, /* 66 3 */ +{ 1, 3, 8, 1, 8, 9, 5, 6, 11, -1, -1, -1, -1, -1, -1, -1}, /* 67 7 */ +{ 1, 5, 6, 2, 1, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, /* 68 2 */ +{ 1, 5, 6, 1, 6, 2, 3, 8, 0, -1, -1, -1, -1, -1, -1, -1}, /* 69 7 */ +{ 9, 5, 6, 9, 6, 0, 0, 6, 2, -1, -1, -1, -1, -1, -1, -1}, /* 70 5 */ +{ 5, 8, 9, 5, 2, 8, 5, 6, 2, 3, 8, 2, -1, -1, -1, -1}, /* 71 11 */ +{ 2, 10, 3, 11, 5, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, /* 72 3 */ +{10, 8, 0, 10, 0, 2, 11, 5, 6, -1, -1, -1, -1, -1, -1, -1}, /* 73 7 */ +{ 0, 9, 1, 2, 10, 3, 5, 6, 11, -1, -1, -1, -1, -1, -1, -1}, /* 74 6 */ +{ 5, 6, 11, 1, 2, 9, 9, 2, 10, 9, 10, 8, -1, -1, -1, -1}, /* 75 12 */ +{ 6, 10, 3, 6, 3, 5, 5, 3, 1, -1, -1, -1, -1, -1, -1, -1}, /* 76 5 */ +{ 0, 10, 8, 0, 5, 10, 0, 1, 5, 5, 6, 10, -1, -1, -1, -1}, /* 77 14 */ +{ 3, 6, 10, 0, 6, 3, 0, 5, 6, 0, 9, 5, -1, -1, -1, -1}, /* 78 9 */ +{ 6, 9, 5, 6, 10, 9, 10, 8, 9, -1, -1, -1, -1, -1, -1, -1}, /* 79 5 */ +{ 5, 6, 11, 4, 8, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, /* 80 3 */ +{ 4, 0, 3, 4, 3, 7, 6, 11, 5, -1, -1, -1, -1, -1, -1, -1}, /* 81 7 */ +{ 1, 0, 9, 5, 6, 11, 8, 7, 4, -1, -1, -1, -1, -1, -1, -1}, /* 82 6 */ +{11, 5, 6, 1, 7, 9, 1, 3, 7, 7, 4, 9, -1, -1, -1, -1}, /* 83 12 */ +{ 6, 2, 1, 6, 1, 5, 4, 8, 7, -1, -1, -1, -1, -1, -1, -1}, /* 84 7 */ +{ 1, 5, 2, 5, 6, 2, 3, 4, 0, 3, 7, 4, -1, -1, -1, -1}, /* 85 10 */ +{ 8, 7, 4, 9, 5, 0, 0, 5, 6, 0, 6, 2, -1, -1, -1, -1}, /* 86 12 */ +{ 7, 9, 3, 7, 4, 9, 3, 9, 2, 5, 6, 9, 2, 9, 6, -1}, /* 87 7 */ +{ 3, 2, 10, 7, 4, 8, 11, 5, 6, -1, -1, -1, -1, -1, -1, -1}, /* 88 6 */ +{ 5, 6, 11, 4, 2, 7, 4, 0, 2, 2, 10, 7, -1, -1, -1, -1}, /* 89 12 */ +{ 0, 9, 1, 4, 8, 7, 2, 10, 3, 5, 6, 11, -1, -1, -1, -1}, /* 90 13 */ +{ 9, 1, 2, 9, 2, 10, 9, 10, 4, 7, 4, 10, 5, 6, 11, -1}, /* 91 6 */ +{ 8, 7, 4, 3, 5, 10, 3, 1, 5, 5, 6, 10, -1, -1, -1, -1}, /* 92 12 */ +{ 5, 10, 1, 5, 6, 10, 1, 10, 0, 7, 4, 10, 0, 10, 4, -1}, /* 93 7 */ +{ 0, 9, 5, 0, 5, 6, 0, 6, 3, 10, 3, 6, 8, 7, 4, -1}, /* 94 6 */ +{ 6, 9, 5, 6, 10, 9, 4, 9, 7, 7, 9, 10, -1, -1, -1, -1}, /* 95 3 */ +{11, 9, 4, 6, 11, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, /* 96 2 */ +{ 4, 6, 11, 4, 11, 9, 0, 3, 8, -1, -1, -1, -1, -1, -1, -1}, /* 97 7 */ +{11, 1, 0, 11, 0, 6, 6, 0, 4, -1, -1, -1, -1, -1, -1, -1}, /* 98 5 */ +{ 8, 1, 3, 8, 6, 1, 8, 4, 6, 6, 11, 1, -1, -1, -1, -1}, /* 99 14 */ +{ 1, 9, 4, 1, 4, 2, 2, 4, 6, -1, -1, -1, -1, -1, -1, -1}, /* 100 5 */ +{ 3, 8, 0, 1, 9, 2, 2, 9, 4, 2, 4, 6, -1, -1, -1, -1}, /* 101 12 */ +{ 0, 4, 2, 4, 6, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, /* 102 8 */ +{ 8, 2, 3, 8, 4, 2, 4, 6, 2, -1, -1, -1, -1, -1, -1, -1}, /* 103 5 */ +{11, 9, 4, 11, 4, 6, 10, 3, 2, -1, -1, -1, -1, -1, -1, -1}, /* 104 7 */ +{ 0, 2, 8, 2, 10, 8, 4, 11, 9, 4, 6, 11, -1, -1, -1, -1}, /* 105 10 */ +{ 3, 2, 10, 0, 6, 1, 0, 4, 6, 6, 11, 1, -1, -1, -1, -1}, /* 106 12 */ +{ 6, 1, 4, 6, 11, 1, 4, 1, 8, 2, 10, 1, 8, 1, 10, -1}, /* 107 7 */ +{ 9, 4, 6, 9, 6, 3, 9, 3, 1, 10, 3, 6, -1, -1, -1, -1}, /* 108 11 */ +{ 8, 1, 10, 8, 0, 1, 10, 1, 6, 9, 4, 1, 6, 1, 4, -1}, /* 109 7 */ +{ 3, 6, 10, 3, 0, 6, 0, 4, 6, -1, -1, -1, -1, -1, -1, -1}, /* 110 5 */ +{ 6, 8, 4, 10, 8, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, /* 111 2 */ +{ 7, 6, 11, 7, 11, 8, 8, 11, 9, -1, -1, -1, -1, -1, -1, -1}, /* 112 5 */ +{ 0, 3, 7, 0, 7, 11, 0, 11, 9, 6, 11, 7, -1, -1, -1, -1}, /* 113 11 */ +{11, 7, 6, 1, 7, 11, 1, 8, 7, 1, 0, 8, -1, -1, -1, -1}, /* 114 9 */ +{11, 7, 6, 11, 1, 7, 1, 3, 7, -1, -1, -1, -1, -1, -1, -1}, /* 115 5 */ +{ 1, 6, 2, 1, 8, 6, 1, 9, 8, 8, 7, 6, -1, -1, -1, -1}, /* 116 14 */ +{ 2, 9, 6, 2, 1, 9, 6, 9, 7, 0, 3, 9, 7, 9, 3, -1}, /* 117 7 */ +{ 7, 0, 8, 7, 6, 0, 6, 2, 0, -1, -1, -1, -1, -1, -1, -1}, /* 118 5 */ +{ 7, 2, 3, 6, 2, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, /* 119 2 */ +{ 2, 10, 3, 11, 8, 6, 11, 9, 8, 8, 7, 6, -1, -1, -1, -1}, /* 120 12 */ +{ 2, 7, 0, 2, 10, 7, 0, 7, 9, 6, 11, 7, 9, 7, 11, -1}, /* 121 7 */ +{ 1, 0, 8, 1, 8, 7, 1, 7, 11, 6, 11, 7, 2, 10, 3, -1}, /* 122 6 */ +{10, 1, 2, 10, 7, 1, 11, 1, 6, 6, 1, 7, -1, -1, -1, -1}, /* 123 3 */ +{ 8, 6, 9, 8, 7, 6, 9, 6, 1, 10, 3, 6, 1, 6, 3, -1}, /* 124 7 */ +{ 0, 1, 9, 10, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, /* 125 4 */ +{ 7, 0, 8, 7, 6, 0, 3, 0, 10, 10, 0, 6, -1, -1, -1, -1}, /* 126 3 */ +{ 7, 6, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, /* 127 1 */ +{ 7, 10, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, /* 128 1 */ +{ 3, 8, 0, 10, 6, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, /* 129 3 */ +{ 0, 9, 1, 10, 6, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, /* 130 4 */ +{ 8, 9, 1, 8, 1, 3, 10, 6, 7, -1, -1, -1, -1, -1, -1, -1}, /* 131 7 */ +{11, 2, 1, 6, 7, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, /* 132 3 */ +{ 1, 11, 2, 3, 8, 0, 6, 7, 10, -1, -1, -1, -1, -1, -1, -1}, /* 133 6 */ +{ 2, 0, 9, 2, 9, 11, 6, 7, 10, -1, -1, -1, -1, -1, -1, -1}, /* 134 7 */ +{ 6, 7, 10, 2, 3, 11, 11, 3, 8, 11, 8, 9, -1, -1, -1, -1}, /* 135 12 */ +{ 7, 3, 2, 6, 7, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, /* 136 2 */ +{ 7, 8, 0, 7, 0, 6, 6, 0, 2, -1, -1, -1, -1, -1, -1, -1}, /* 137 5 */ +{ 2, 6, 7, 2, 7, 3, 0, 9, 1, -1, -1, -1, -1, -1, -1, -1}, /* 138 7 */ +{ 1, 2, 6, 1, 6, 8, 1, 8, 9, 8, 6, 7, -1, -1, -1, -1}, /* 139 14 */ +{11, 6, 7, 11, 7, 1, 1, 7, 3, -1, -1, -1, -1, -1, -1, -1}, /* 140 5 */ +{11, 6, 7, 1, 11, 7, 1, 7, 8, 1, 8, 0, -1, -1, -1, -1}, /* 141 9 */ +{ 0, 7, 3, 0, 11, 7, 0, 9, 11, 6, 7, 11, -1, -1, -1, -1}, /* 142 11 */ +{ 7, 11, 6, 7, 8, 11, 8, 9, 11, -1, -1, -1, -1, -1, -1, -1}, /* 143 5 */ +{ 6, 4, 8, 10, 6, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, /* 144 2 */ +{ 3, 10, 6, 3, 6, 0, 0, 6, 4, -1, -1, -1, -1, -1, -1, -1}, /* 145 5 */ +{ 8, 10, 6, 8, 6, 4, 9, 1, 0, -1, -1, -1, -1, -1, -1, -1}, /* 146 7 */ +{ 9, 6, 4, 9, 3, 6, 9, 1, 3, 10, 6, 3, -1, -1, -1, -1}, /* 147 11 */ +{ 6, 4, 8, 6, 8, 10, 2, 1, 11, -1, -1, -1, -1, -1, -1, -1}, /* 148 7 */ +{ 1, 11, 2, 3, 10, 0, 0, 10, 6, 0, 6, 4, -1, -1, -1, -1}, /* 149 12 */ +{ 4, 8, 10, 4, 10, 6, 0, 9, 2, 2, 9, 11, -1, -1, -1, -1}, /* 150 10 */ +{11, 3, 9, 11, 2, 3, 9, 3, 4, 10, 6, 3, 4, 3, 6, -1}, /* 151 7 */ +{ 8, 3, 2, 8, 2, 4, 4, 2, 6, -1, -1, -1, -1, -1, -1, -1}, /* 152 5 */ +{ 0, 2, 4, 4, 2, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, /* 153 8 */ +{ 1, 0, 9, 2, 4, 3, 2, 6, 4, 4, 8, 3, -1, -1, -1, -1}, /* 154 12 */ +{ 1, 4, 9, 1, 2, 4, 2, 6, 4, -1, -1, -1, -1, -1, -1, -1}, /* 155 5 */ +{ 8, 3, 1, 8, 1, 6, 8, 6, 4, 6, 1, 11, -1, -1, -1, -1}, /* 156 14 */ +{11, 0, 1, 11, 6, 0, 6, 4, 0, -1, -1, -1, -1, -1, -1, -1}, /* 157 5 */ +{ 4, 3, 6, 4, 8, 3, 6, 3, 11, 0, 9, 3, 11, 3, 9, -1}, /* 158 7 */ +{11, 4, 9, 6, 4, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, /* 159 2 */ +{ 4, 5, 9, 7, 10, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, /* 160 3 */ +{ 0, 3, 8, 4, 5, 9, 10, 6, 7, -1, -1, -1, -1, -1, -1, -1}, /* 161 6 */ +{ 5, 1, 0, 5, 0, 4, 7, 10, 6, -1, -1, -1, -1, -1, -1, -1}, /* 162 7 */ +{10, 6, 7, 8, 4, 3, 3, 4, 5, 3, 5, 1, -1, -1, -1, -1}, /* 163 12 */ +{ 9, 4, 5, 11, 2, 1, 7, 10, 6, -1, -1, -1, -1, -1, -1, -1}, /* 164 6 */ +{ 6, 7, 10, 1, 11, 2, 0, 3, 8, 4, 5, 9, -1, -1, -1, -1}, /* 165 13 */ +{ 7, 10, 6, 5, 11, 4, 4, 11, 2, 4, 2, 0, -1, -1, -1, -1}, /* 166 12 */ +{ 3, 8, 4, 3, 4, 5, 3, 5, 2, 11, 2, 5, 10, 6, 7, -1}, /* 167 6 */ +{ 7, 3, 2, 7, 2, 6, 5, 9, 4, -1, -1, -1, -1, -1, -1, -1}, /* 168 7 */ +{ 9, 4, 5, 0, 6, 8, 0, 2, 6, 6, 7, 8, -1, -1, -1, -1}, /* 169 12 */ +{ 3, 2, 6, 3, 6, 7, 1, 0, 5, 5, 0, 4, -1, -1, -1, -1}, /* 170 10 */ +{ 6, 8, 2, 6, 7, 8, 2, 8, 1, 4, 5, 8, 1, 8, 5, -1}, /* 171 7 */ +{ 9, 4, 5, 11, 6, 1, 1, 6, 7, 1, 7, 3, -1, -1, -1, -1}, /* 172 12 */ +{ 1, 11, 6, 1, 6, 7, 1, 7, 0, 8, 0, 7, 9, 4, 5, -1}, /* 173 6 */ +{ 4, 11, 0, 4, 5, 11, 0, 11, 3, 6, 7, 11, 3, 11, 7, -1}, /* 174 7 */ +{ 7, 11, 6, 7, 8, 11, 5, 11, 4, 4, 11, 8, -1, -1, -1, -1}, /* 175 3 */ +{ 6, 5, 9, 6, 9, 10, 10, 9, 8, -1, -1, -1, -1, -1, -1, -1}, /* 176 5 */ +{ 3, 10, 6, 0, 3, 6, 0, 6, 5, 0, 5, 9, -1, -1, -1, -1}, /* 177 9 */ +{ 0, 8, 10, 0, 10, 5, 0, 5, 1, 5, 10, 6, -1, -1, -1, -1}, /* 178 14 */ +{ 6, 3, 10, 6, 5, 3, 5, 1, 3, -1, -1, -1, -1, -1, -1, -1}, /* 179 5 */ +{ 1, 11, 2, 9, 10, 5, 9, 8, 10, 10, 6, 5, -1, -1, -1, -1}, /* 180 12 */ +{ 0, 3, 10, 0, 10, 6, 0, 6, 9, 5, 9, 6, 1, 11, 2, -1}, /* 181 6 */ +{10, 5, 8, 10, 6, 5, 8, 5, 0, 11, 2, 5, 0, 5, 2, -1}, /* 182 7 */ +{ 6, 3, 10, 6, 5, 3, 2, 3, 11, 11, 3, 5, -1, -1, -1, -1}, /* 183 3 */ +{ 5, 9, 8, 5, 8, 2, 5, 2, 6, 3, 2, 8, -1, -1, -1, -1}, /* 184 11 */ +{ 9, 6, 5, 9, 0, 6, 0, 2, 6, -1, -1, -1, -1, -1, -1, -1}, /* 185 5 */ +{ 1, 8, 5, 1, 0, 8, 5, 8, 6, 3, 2, 8, 6, 8, 2, -1}, /* 186 7 */ +{ 1, 6, 5, 2, 6, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, /* 187 2 */ +{ 1, 6, 3, 1, 11, 6, 3, 6, 8, 5, 9, 6, 8, 6, 9, -1}, /* 188 7 */ +{11, 0, 1, 11, 6, 0, 9, 0, 5, 5, 0, 6, -1, -1, -1, -1}, /* 189 3 */ +{ 0, 8, 3, 5, 11, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, /* 190 4 */ +{11, 6, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, /* 191 1 */ +{10, 11, 5, 7, 10, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, /* 192 2 */ +{10, 11, 5, 10, 5, 7, 8, 0, 3, -1, -1, -1, -1, -1, -1, -1}, /* 193 7 */ +{ 5, 7, 10, 5, 10, 11, 1, 0, 9, -1, -1, -1, -1, -1, -1, -1}, /* 194 7 */ +{11, 5, 7, 11, 7, 10, 9, 1, 8, 8, 1, 3, -1, -1, -1, -1}, /* 195 10 */ +{10, 2, 1, 10, 1, 7, 7, 1, 5, -1, -1, -1, -1, -1, -1, -1}, /* 196 5 */ +{ 0, 3, 8, 1, 7, 2, 1, 5, 7, 7, 10, 2, -1, -1, -1, -1}, /* 197 12 */ +{ 9, 5, 7, 9, 7, 2, 9, 2, 0, 2, 7, 10, -1, -1, -1, -1}, /* 198 14 */ +{ 7, 2, 5, 7, 10, 2, 5, 2, 9, 3, 8, 2, 9, 2, 8, -1}, /* 199 7 */ +{ 2, 11, 5, 2, 5, 3, 3, 5, 7, -1, -1, -1, -1, -1, -1, -1}, /* 200 5 */ +{ 8, 0, 2, 8, 2, 5, 8, 5, 7, 11, 5, 2, -1, -1, -1, -1}, /* 201 11 */ +{ 9, 1, 0, 5, 3, 11, 5, 7, 3, 3, 2, 11, -1, -1, -1, -1}, /* 202 12 */ +{ 9, 2, 8, 9, 1, 2, 8, 2, 7, 11, 5, 2, 7, 2, 5, -1}, /* 203 7 */ +{ 1, 5, 3, 3, 5, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, /* 204 8 */ +{ 0, 7, 8, 0, 1, 7, 1, 5, 7, -1, -1, -1, -1, -1, -1, -1}, /* 205 5 */ +{ 9, 3, 0, 9, 5, 3, 5, 7, 3, -1, -1, -1, -1, -1, -1, -1}, /* 206 5 */ +{ 9, 7, 8, 5, 7, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, /* 207 2 */ +{ 5, 4, 8, 5, 8, 11, 11, 8, 10, -1, -1, -1, -1, -1, -1, -1}, /* 208 5 */ +{ 5, 4, 0, 5, 0, 10, 5, 10, 11, 10, 0, 3, -1, -1, -1, -1}, /* 209 14 */ +{ 0, 9, 1, 8, 11, 4, 8, 10, 11, 11, 5, 4, -1, -1, -1, -1}, /* 210 12 */ +{11, 4, 10, 11, 5, 4, 10, 4, 3, 9, 1, 4, 3, 4, 1, -1}, /* 211 7 */ +{ 2, 1, 5, 2, 5, 8, 2, 8, 10, 4, 8, 5, -1, -1, -1, -1}, /* 212 11 */ +{ 0, 10, 4, 0, 3, 10, 4, 10, 5, 2, 1, 10, 5, 10, 1, -1}, /* 213 7 */ +{ 0, 5, 2, 0, 9, 5, 2, 5, 10, 4, 8, 5, 10, 5, 8, -1}, /* 214 7 */ +{ 9, 5, 4, 2, 3, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, /* 215 4 */ +{ 2, 11, 5, 3, 2, 5, 3, 5, 4, 3, 4, 8, -1, -1, -1, -1}, /* 216 9 */ +{ 5, 2, 11, 5, 4, 2, 4, 0, 2, -1, -1, -1, -1, -1, -1, -1}, /* 217 5 */ +{ 3, 2, 11, 3, 11, 5, 3, 5, 8, 4, 8, 5, 0, 9, 1, -1}, /* 218 6 */ +{ 5, 2, 11, 5, 4, 2, 1, 2, 9, 9, 2, 4, -1, -1, -1, -1}, /* 219 3 */ +{ 8, 5, 4, 8, 3, 5, 3, 1, 5, -1, -1, -1, -1, -1, -1, -1}, /* 220 5 */ +{ 0, 5, 4, 1, 5, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, /* 221 2 */ +{ 8, 5, 4, 8, 3, 5, 9, 5, 0, 0, 5, 3, -1, -1, -1, -1}, /* 222 3 */ +{ 9, 5, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, /* 223 1 */ +{ 4, 7, 10, 4, 10, 9, 9, 10, 11, -1, -1, -1, -1, -1, -1, -1}, /* 224 5 */ +{ 0, 3, 8, 4, 7, 9, 9, 7, 10, 9, 10, 11, -1, -1, -1, -1}, /* 225 12 */ +{ 1, 10, 11, 1, 4, 10, 1, 0, 4, 7, 10, 4, -1, -1, -1, -1}, /* 226 11 */ +{ 3, 4, 1, 3, 8, 4, 1, 4, 11, 7, 10, 4, 11, 4, 10, -1}, /* 227 7 */ +{ 4, 7, 10, 9, 4, 10, 9, 10, 2, 9, 2, 1, -1, -1, -1, -1}, /* 228 9 */ +{ 9, 4, 7, 9, 7, 10, 9, 10, 1, 2, 1, 10, 0, 3, 8, -1}, /* 229 6 */ +{10, 4, 7, 10, 2, 4, 2, 0, 4, -1, -1, -1, -1, -1, -1, -1}, /* 230 5 */ +{10, 4, 7, 10, 2, 4, 8, 4, 3, 3, 4, 2, -1, -1, -1, -1}, /* 231 3 */ +{ 2, 11, 9, 2, 9, 7, 2, 7, 3, 7, 9, 4, -1, -1, -1, -1}, /* 232 14 */ +{ 9, 7, 11, 9, 4, 7, 11, 7, 2, 8, 0, 7, 2, 7, 0, -1}, /* 233 7 */ +{ 3, 11, 7, 3, 2, 11, 7, 11, 4, 1, 0, 11, 4, 11, 0, -1}, /* 234 7 */ +{ 1, 2, 11, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, /* 235 4 */ +{ 4, 1, 9, 4, 7, 1, 7, 3, 1, -1, -1, -1, -1, -1, -1, -1}, /* 236 5 */ +{ 4, 1, 9, 4, 7, 1, 0, 1, 8, 8, 1, 7, -1, -1, -1, -1}, /* 237 3 */ +{ 4, 3, 0, 7, 3, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, /* 238 2 */ +{ 4, 7, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, /* 239 1 */ +{ 9, 8, 11, 11, 8, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, /* 240 8 */ +{ 3, 9, 0, 3, 10, 9, 10, 11, 9, -1, -1, -1, -1, -1, -1, -1}, /* 241 5 */ +{ 0, 11, 1, 0, 8, 11, 8, 10, 11, -1, -1, -1, -1, -1, -1, -1}, /* 242 5 */ +{ 3, 11, 1, 10, 11, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, /* 243 2 */ +{ 1, 10, 2, 1, 9, 10, 9, 8, 10, -1, -1, -1, -1, -1, -1, -1}, /* 244 5 */ +{ 3, 9, 0, 3, 10, 9, 1, 9, 2, 2, 9, 10, -1, -1, -1, -1}, /* 245 3 */ +{ 0, 10, 2, 8, 10, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, /* 246 2 */ +{ 3, 10, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, /* 247 1 */ +{ 2, 8, 3, 2, 11, 8, 11, 9, 8, -1, -1, -1, -1, -1, -1, -1}, /* 248 5 */ +{ 9, 2, 11, 0, 2, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, /* 249 2 */ +{ 2, 8, 3, 2, 11, 8, 0, 8, 1, 1, 8, 11, -1, -1, -1, -1}, /* 250 3 */ +{ 1, 2, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, /* 251 1 */ +{ 1, 8, 3, 9, 8, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, /* 252 2 */ +{ 0, 1, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, /* 253 1 */ +{ 0, 8, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, /* 254 1 */ +{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}}; /* 255 0 */ + +int altcases[4][19]={ +{0,8,5, 8,6,5, 8,3,6, 3,11,6, 3,0,11, 0,5,11, -1}, /* modified case 190 will be case 65 */ +{1,9,6, 9,7,6, 9,0,7, 0,10,7, 0,1,10, 1,6,10, -1}, /* modified case 125 will be case 130 */ +{5,4,10, 4,3,10, 4,9,3, 9,2,3, 9,5,2, 5,10,2, -1}, /* modified case 215 will be case 40 */ +{2,11,7, 11,4,7, 11,1,4, 1,8,4, 1,2,8, 2,7,8, -1} /* modified case 235 will be case 20 */ +}; + +","Unknown" +"Neurology","ChristianGaser/cat12","cat_main_updateSPM1639.m",".m","38685","744","function [Ysrc,Ycls,Yb,Yb0,job,res,T3th,stime2] = cat_main_updateSPM1639(Ysrc,P,Yy,tpm,job,res,stime,stime2) +% ______________________________________________________________________ +% Update SPM preprocessing. +% Subfunction of cat_main. +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + + %dbs = dbstatus; debug = 0; for dbsi=1:numel(dbs), if strcmp(dbs(dbsi).name,mfilename); debug = 1; break; end; end + + global cat_err_res; + + clsint = @(x) round( sum(res.mn(res.lkp==x) .* res.mg(res.lkp==x)') * 10^5)/10^5; + + [pth,nam] = spm_fileparts(res.image0(1).fname); %#ok % original + + % RD202211: Added SPM based detection of high intensity backgronds of MP2Rage scans + %res.isMP2RAGE = min( res.mn(res.lkp==3 & res.mg'>0.2) ) < min( res.mn(res.lkp==max(res.lkp) & res.mg'>0.2) ); + % CG20230227 disabled detection because it was not working properly + res.isMP2RAGE = false; + + % voxel size parameter + vx_vol = sqrt(sum(res.image(1).mat(1:3,1:3).^2)); % voxel size of the processed image + vx_vol0 = sqrt(sum(res.image0(1).mat(1:3,1:3).^2)); + vx_volp = prod(vx_vol)/1000; + + d = res.image(1).dim(1:3); + + %% RD20221102: Characterize usefulness of SPM classification. + % Analyse and store basic information of the SPM segmentation to improve + % handling of different protocols such as MP2rage. In general SPM gives + % some clear sharp tissue output but in some cases (e.g., registration/ + % segmentation errors) the tissues are quite smooth. See also help entry. + % I use 20 buckets to get the number of voxels below 25%, 50%, and 75%, + % but also get 90% etc. + hbuckets = 20; + if isfield(res,'spmP0'), res = rmfield(res,'spmP0'); end + for ti = 1:size(P,4) + Pti = P(:,:,:,ti); + pth = 0.05; + res.spmP0.hstbuckets = 256/(hbuckets*2):256/hbuckets:256; + res.spmP0.hst(ti,:) = hist(Pti(Pti(:)>pth),256/(hbuckets*2):256/hbuckets:256) / sum(Pti(:)>pth); %#ok + res.spmP0.hstsumi(ti,:) = 1 - cumsum(res.spmP0.hst(ti,:)); + res.spmP0.mn(ti) = cat_stat_nanmean( single(Pti(Pti(:)>pth)) / 255 ); + res.spmP0.sd(ti) = cat_stat_nanstd( single(Pti(Pti(:)>pth)) / 255 ); + res.spmP0.md(ti) = cat_stat_nanmedian( single(Pti(Pti(:)>pth)) / 255 ); + %res.spmP0.Q1(ti) = cat_stat_nanmedian( single(Pti( Pti(:)res.spmP0.md(ti)*255 ) ) / 255); + end + res.spmP0.help = { ... + 'This structure contains some parameters to characterize the initial SPM segmentation to detect possible problems. ' + sprintf('It contains a normalized histogram (hst) of %d buckets sampled at hstbuckets (center point with borders inbetween!). ',hbuckets) + 'The inverse cumultative sum of the histogram (hstsumi) defines how many values are above the histogram bucket. ' + 'A good segment should include a high proposion of high probable voxels. ' + 'Moreover, we saved the mean(mn), standard deviation (sd), median(md) of the individual tissue desnity maps of SPM. ' + 'In general, higher mn, md, Q1/2 and lower sd values (<.5) are expected otherwise segmentation is maybe inproper. ' + }; + clear Pti; + % RD20221102: Add warnings + % These threshold are arbitrary choosen and updates are maybe required! + % RD202401: updated (worst cases with *) + % BUSS Median: GM=0.75, WM=0.31, CSF=0.02** + % 4397 Median: GM=0.31, WM=0.63, CSF=0.09* + % NISALS Median: GM=0.22, WM=0.25, CSF=0.01* + % ADHD Median: GM=0.84, WM=0.97, CSF=0.00* + % OASIS Median: GM=0.22, WM=0.31, CSF=0.02* + % Colins Median: GM=0.80, WM=0.97, CSF=0.06 + % BWPT Median: GM=0.96, WM=1.00, CSF=0.05 + % HR075 Median: GM=0.75, WM=0.98, CSF=0.03 + % <0.50 <0.50 <0.02 + % + % BUSS Mean: GM=0.54, WM=0.48, CSF=0.13 + % 4397 Mean: GM=0.44, WM=0.53, CSF=0.27 + % NISALS Mean: GM=0.43, WM=0.46, CSF=0.12 + % ADHD Mean: GM=0.59, WM=0.66, CSF=0.06 + % OASIS Mean: GM=0.37, WM=0.45, CSF=0.15 + % Colins Mean: GM=0.56, WM=0.72, CSF=0.29 + % BWPT Mean: GM=0.72, WM=0.83, CSF=0.37 + % HR075 Mean: GM=0.54, WM=0.79, CSF=0.20 + % <0.5 <0.6 <0.13 + + if job.extopts.expertgui > 1 && ... + ( any( res.spmP0.md(1:3) < [.5 .5 .01],2) || ... + any( res.spmP0.mn(1:3) < [.5 .5 .10],2) || ... + any( any( res.spmP0.hstsumi(1:3,round(hbuckets*[.25,.50,.75])) < [0.6 0.5 0.4; 0.8 0.7 0.6; 0.5 0.2 0.05 ] )) ) + cat_io_addwarning('cat_main_updateSPM1639:lowSPMseg',... + sprintf(['Low SPM segmentation quality with larger areas of mixed tissues (smaller=worse). \\\\n' ... + ' Median: GM=%0.2f, WM=%0.2f, CSF=%0.2f \\\\n' ... + ' Mean: GM=%0.2f, WM=%0.2f, CSF=%0.2f'], ... + res.spmP0.md(1:3),res.spmP0.mn(1:3)),2,[1 2]); + end + + %% RD20221102: Intensity overlap in brain tissue classes + % Besides the probabilty we may check also the intensities. If two + % classes show a high overlap of intensities the segmentation is mabe + % inaccurate. + % BUZZ CG=0.81,GW=0.38,CW=0.82,CGW=0.25 + % 4397 CG=0.72,GW=0.43,CW=0.84,CGW=0.29 + % NISALS CG=0.41,GW=0.44,CW=0.62,CGW=0.18 + % ADHD CG=0.27,GW=0.31,CW=0.41,CGW=0.17 + % OASIS CG=0.39,GW=0.37,CW=0.58,CGW=0.14 + % Colins CG=0.45,GW=0.34,CW=0.48,CGW=0.24 + % BWPT CG=0.39,GW=0.23,CW=0.42,CGW=0.16 + % HR075 CG=0.67,GW=0.50,CW=0.72,CGW=0.32 + % <0.3 <0.3 <0.3 <0.15 + minprob = 32; hbuckets = 30; + trange = [min(res.mn(res.lkp<6)) max(res.mn(res.lkp<6))]; + trange = trange + [ -diff(trange) +diff(trange) ] / 4; + trange = trange(1) : diff(trange)/(hbuckets-2) : trange(2); + res.spmP0.hstibuckets = trange; + for ti=1:size(P,4) + htmp = hist(Ysrc(P(:,:,:,ti)>minprob),trange); %#ok + res.spmP0.hsti(ti,:) = htmp; %.Values; + end + res.spmP0.hstidiffCGW = [ + mean( abs(diff(res.spmP0.hsti(1:2:3,:))) ./ max(eps,sum(res.spmP0.hsti(1:2:3,:)))), ... + mean( abs(diff(res.spmP0.hsti(1:2,:))) ./ max(eps,sum(res.spmP0.hsti(1:2,:)))), ... + mean( abs(diff(res.spmP0.hsti(2:3,:))) ./ max(eps,sum(res.spmP0.hsti(2:3,:))))]; + res.spmP0.hstidiff = mean( min([ + abs(diff(res.spmP0.hsti(1:2,:))) ./ max(eps,sum(res.spmP0.hsti(1:2,:))); + abs(diff(res.spmP0.hsti(2:3,:))) ./ max(eps,sum(res.spmP0.hsti(2:3,:))); + abs(diff(res.spmP0.hsti(1:2:3,:))) ./ max(eps,sum(res.spmP0.hsti(1:2:3,:))); + ])); + res.spmP0.help = [res.spmP0.help; { + sprintf('The hsti is the histogram of the T1 image for each class (prob>%0.2f,%d buckets) ',minprob/255,hbuckets)}; + 'that are combined into the average intensity difference between classes histidiff with 1 for the ideal case without overlap and 0 for high overlap. ']; + if job.extopts.expertgui>1 && res.spmP0.hstidiff<0.15 + cat_io_addwarning('cat_main_updateSPM1639:highIntOverlapBetweenClasses',... + sprintf('High overlap of image intensies in different classes\\\\n CG=%0.2f,GW=%0.2f,CW=%0.2f,CGW=%0.2f',res.spmP0.hstidiffCGW,res.spmP0.hstidiff),2,[1 2]); + end + if 0 + %% + figure, hold on; histogram(Ysrc(P(:,:,:,1)>minprob),trange); histogram(Ysrc(P(:,:,:,2)>minprob),trange); histogram(Ysrc(P(:,:,:,3)>minprob),trange); + + end + %% + stime2 = cat_io_cmd(' Update Segmentation','g5','',job.extopts.verb-1,stime2); + + + % Create brain mask based on the the TPM classes + % cleanup with brain mask - required for ngaus [1 1 2 4 3 2] and R1/MP2Rage like data + %YbA = zeros(d,'single'); + Vb = tpm.V(1); Vb.pinfo(3) = 0; Vb.dt=16; + Vb.dat = single(exp(tpm.dat{1}) + exp(tpm.dat{2}) + exp(tpm.dat{3})); + YbA = cat_vol_sample(res.tpm(1),Vb,Yy,1); + %for z=1:d(3) + % YbA(:,:,z) = spm_sample_vol(Vb,double(Yy(:,:,z,1)),double(Yy(:,:,z,2)),double(Yy(:,:,z,3)),1); + %end + if (isfield(job,'useprior') && ~isempty(job.useprior) ), bth = 0.5; else, bth = 0.1; end + if round(max(YbA(:))/Vb.pinfo(1)), YbA=YbA>bth*Vb.pinfo(1); else, YbA=YbA>bth; end + % add some distance around brainmask (important for bias!) + YbA = YbA | cat_vol_morph(YbA & sum(P(:,:,:,1:2),4)>4 ,'dd',2.4,vx_vol); + + if size(P,4)==3 + % create background class that is required later + Yb = cat_vol_morph( smooth3( sum(P(:,:,:,1:2),4) ) > 192 , 'ldc' , 5 , vx_vol ); + Yb = cat_vol_morph( Yb , 'ldo' ); + for i=1:3, P(:,:,:,i) = P(:,:,:,i) .* cat_vol_ctype(Yb); end + P(:,:,:,4) = cat_vol_ctype((1 - Yb) * 255); + end + + % transfer tissue outside the brain mask to head ... + % RD 201807: I am not sure if this is a good idea. Please test this with children! + for i=1:3 + P(:,:,:,4) = cat_vol_ctype(single(P(:,:,:,4)) + single(P(:,:,:,i)) .* single(~YbA)); + P(:,:,:,i) = cat_vol_ctype(single(P(:,:,:,i)) .* single(YbA)); + end + + + % Cleanup for high resolution data + % Alghough the old cleanup is very slow for high resolution data, the + % reduction of image resolution removes spatial segmentation information. + if job.opts.redspmres==0 % already done in case of redspmres + if max(vx_vol)<1.5 && mean(vx_vol)<1.3 + % RD202102: resizing adds maybe too much blurring that can trouble other functions + %for i=1:size(P,4), [Pc1(:,:,:,i),RR] = cat_vol_resize(P(:,:,:,i),'reduceV',vx_vol,job.extopts.uhrlim,32); end %#ok + for i=1:size(P,4), [Pc1(:,:,:,i),BB] = cat_vol_resize(P(:,:,:,i),'reduceBrain',vx_vol,4,YbA); end %#ok + Pc1 = cat_main_clean_gwc1639(Pc1,max(1,min(2,job.extopts.cleanupstr*2))); + Ybb = ones(size(YbA),'uint8'); Ybb(BB.BB(1):BB.BB(2),BB.BB(3):BB.BB(4),BB.BB(5):BB.BB(6)) = uint8(1); + for i=1:size(P,4), P(:,:,:,i) = Ybb.*P(:,:,:,i) + cat_vol_resize(Pc1(:,:,:,i),'dereduceBrain',BB); end + %for i=1:size(P,4), P(:,:,:,i) = cat_vol_resize(Pc1(:,:,:,i),'dereduceV',RR); end + clear Pc1 Pc2 Ybb; + end + end + if ~( (isfield(job,'useprior') && ~isempty(job.useprior) ) && ... + (isfield(res,'ppe') && ~res.ppe.affreg.highBG) ) + clear YbA; + end + + % some reports + for i=1:size(P,4), Pt = P(:,:,:,i); res.ppe.SPMvols0(i) = cat_stat_nansum(single(Pt(:)))/255 .* prod(vx_vol) / 1000; end; clear Pt; + + + % garantee probability + sP = (sum(single(P),4)+eps)/255; + for k1=1:size(P,4), P(:,:,:,k1) = cat_vol_ctype(single(P(:,:,:,k1))./sP); end + clear sP; + + + % Use median for WM threshold estimation to avoid problems in case of WMHs! + WMth = double(max( clsint(2) , cat_stat_nanmedian(Ysrc(P(:,:,:,2)>192)) )); + if clsint(3)>clsint(2) % invers + CMth = clsint(3); + else + CMth = min( [ clsint(1) - diff([clsint(1),WMth]) , clsint(3) ]); + end + T3th = double([ CMth , clsint(1) , WMth]); + + + %% Some error handling + % ds('l2','',vx_vol,Ysrc./WMth,Yp0>0.3,Ysrc./WMth,Yp0,80) + Yp0 = single(P(:,:,:,3))/255/3 + single(P(:,:,:,1))/255*2/3 + single(P(:,:,:,2))/255; + if size(P,4)==4 || size(P,4)==3 || res.ppe.affreg.skullstripped + %% skull-stripped + Ybg = cat_vol_smooth3X(sum(P(:,:,:,1:2)>0,4)==0,4)>.95; + Ybg = Ysrc>=(median(Ysrc(Ybg(:))) - 2*std(Ysrc(Ybg(:)))) & ... + Ysrc<=(median(Ysrc(Ybg(:))) + 2*std(Ysrc(Ybg(:)))); + Ybx = ~cat_vol_morph(~cat_vol_morph(~Ybg,'lc'),'lc'); %clear Ybg + Yp0 = Yp0 .* Ybx; + Ysrc = Ysrc .* Ybx; + for ci = 1:(size(P,4)-1), P(:,:,:,ci) = P(:,:,:,ci) .* uint8(Ybx); end + P(:,:,:,end) = uint8(1-Ybx)*255; + end + if isfield(res,'Ylesion') && sum(res.Ylesion(:)>0) + res.Ylesion = cat_vol_ctype( single(res.Ylesion) .* (Yp0>0.2) ); + for k=1:size(P,4), Yl = P(:,:,:,k); Yl(res.Ylesion>0.5) = 0; P(:,:,:,k) = Yl; end + Yl = P(:,:,:,3); Yl(res.Ylesion>0.5) = 255; P(:,:,:,3) = Yl; clear Yl; + Yp0 = single(P(:,:,:,3))/255/3 + single(P(:,:,:,1))/255*2/3 + single(P(:,:,:,2))/255; + end + if sum(Yp0(:)>0.3)<100 + % this error often depends on a failed affine registration, where SPM + % have to find the brain in the head or background + BGth = min(cat_stat_nanmean(Ysrc( P(:,:,:,end)>128 )),clsint(6)); + HDHth = clsint(5); + HDLth = clsint(4); + clsvol = nan(1,size(P,4)); for ci=1:size(P,4), Yct = P(:,:,:,ci)>128; clsvol(ci) = sum(Yct(:))*vx_volp; end; clear Yct; + if size(P,4)==6 + error('CAT:cat_main:SPMpreprocessing:emptySegmentation', ... + sprintf(['Empty Segmentation: \n ' ... + 'Possibly the affine registration failed. Please check image orientation.\n' ... + ' Tissue class: %10s%10s%10s%10s%10s%10s\n' ... + ' Rel. to image volume: %10.2f%10.2f%10.2f%10.2f%10.2f%10.2f\n' ... + ' Rel. to brain volume: %10.2f%10.2f%10.2f%10.2f%10.2f%10.2f\n' ... + ' Tissue intensity: %10.2f%10.2f%10.2f%10.2f%10.2f%10.2f'],... + 'BG','CSF','GM','WM','HDH','HDL', ... + [ clsvol([6 3 1 2 4 5])/cat_stat_nansum(clsvol)*100, clsvol([6 3 1 2 4 5])/cat_stat_nansum(clsvol(1:3))*100, BGth,T3th,HDHth,HDLth])); %#ok + elseif size(P,4)==4 % skull-stripped + error('CAT:cat_main:SPMpreprocessing:emptySegmentation', ... + sprintf(['Empty Segmentation: \n ' ... + 'Possibly the affine registration failed. Please check image orientation.\n' ... + ' Tissue class: %10s%10s%10s%10s\n' ... + ' Rel. to image volume: %10.2f%10.2f%10.2f%10.2f\n' ... + ' Rel. to brain volume: %10.2f%10.2f%10.2f%10.2f\n' ... + ' Tissue intensity: %10.2f%10.2f%10.2f%10.2f'],... + 'BG','CSF','GM','WM', ... + [ clsvol([4 3 1 2])/cat_stat_nansum(clsvol)*100, clsvol([4 3 1 2])/cat_stat_nansum(clsvol(1:3))*100, BGth,T3th])); %#ok + else + error('CAT:cat_main:SPMpreprocessing:emptySegmentation', ['Empty Segmentation: ' ... + 'Possibly the affine registration failed. Please check image orientation.\n']); + end + end + + + + %% + Yp0(smooth3(cat_vol_morph(Yp0>0.3,'lo'))<0.5)=0; % not 1/6 because some ADNI scans have large ""CSF"" areas in the background + Yp0 = Yp0 .* cat_vol_morph(Yp0 & (Ysrc>WMth*0.05),'lc',2); + Yp0toC = @(Yp0,c) 1-min(1,abs(Yp0-c)); + + + % values are only used if errors occur + cat_err_res.init.T3th = T3th; + cat_err_res.init.subjectmeasures.vol_abs_CGW = [prod(vx_vol)/1000 .* sum(Yp0toC(Yp0(:),1)), ... CSF + prod(vx_vol)/1000 .* sum(Yp0toC(Yp0(:),2)), ... GM + prod(vx_vol)/1000 .* sum(Yp0toC(Yp0(:),3)), ... WM + prod(vx_vol)/1000 .* sum(Yp0toC(Yp0(:),4))]; % WMH + cat_err_res.init.subjectmeasures.vol_TIV = sum(cat_err_res.init.subjectmeasures.vol_abs_CGW); + cat_err_res.init.subjectmeasures.vol_rel_CGW = cat_err_res.init.subjectmeasures.vol_abs_CGW ./ ... + cat_err_res.init.subjectmeasures.vol_TIV; + [cat_err_res.init.Yp0,cat_err_res.init.BB] = cat_vol_resize(Yp0,'reduceBrain',vx_vol,2,Yp0>0.5); + cat_err_res.init.Yp0 = cat_vol_ctype(cat_err_res.init.Yp0/3*255); + clear Yp0; + + % ### This can not be reached because the mask field is removed by SPM! ### + if isfield(res,'msk') + Ybg = ~res.msk.dat; + P4 = cat_vol_ctype( single(P(:,:,:,6)) .* (Ysrc=T3th(2)) .* (Ybg<0.5) + single(P(:,:,:,5)) .* (Ybg<0.5) ); % remove air in head + P6 = cat_vol_ctype( single(sum(P(:,:,:,4:5),4)) .* (Ybg>0.5) + single(P(:,:,:,6)) .* (Ybg>0.5) ); % add objects/artifacts to background + P(:,:,:,4) = P4; + P(:,:,:,5) = P5; + P(:,:,:,6) = P6; + clear P4 P5 P6 Ybg; + end + + + + + %% Skull-Stripping + % ---------------------------------------------------------------------- + % Update Skull-Stripping 1 + % ---------------------------------------------------------------------- + stime2 = cat_io_cmd(' Update Skull-Stripping','g5','',job.extopts.verb-1,stime2); + if size(P,4)>4 && (isfield(job,'useprior') && ~isempty(job.useprior) && strcmp(job.opts.affreg,'prior') ) && ... + (isfield(res,'ppe') && ~res.ppe.affreg.highBG) && ~res.ppe.affreg.skullstripped + % RD202010: use longitudinal skull-stripping + [pp,ff,ee] = spm_fileparts(char(job.useprior)); + if isfield(job.output.BIDS,'BIDSyes') % I am not sure if separation is needed or if we simply try with/without mri-dir + Pavgp0 = fullfile(pp,[strrep(ff,'avg_','p0avg_'),ee]); + if ~exist(Pavgp0,'file') + Pavgp0 = fullfile(pp,'mri',[strrep(ff,'avg_','p0avg_'),ee]); + end + else + Pavgp0 = fullfile(pp,'mri',[strrep(ff,'avg_','p0avg_'),ee]); + if ~exist(Pavgp0,'file') + Pavgp0 = fullfile(pp,[strrep(ff,'avg_','p0avg_'),ee]); + end + end + +% RD20220213: +% For the development model with longitudinal TPM you may have to add the affine registration. +% However it seems that the adaption of the brainmask works quite well ... +% but maybe it is better to full deactive the skull-stripping in the +% plasticity/aging case + + % get gradient and divergence map (Yg and Ydiv) + [Ytmp,Ytmp,Yg,Ydiv] = cat_main_updateSPM_gcut0(Ysrc,P,vx_vol,T3th); clear Ytmp; %#ok + if exist(Pavgp0,'file') + % the p0avg should fit optimal + if any(vx_vol0 ~= vx_vol) % if the data was internaly resampled we have to load it via imcalc + [Vb,Yb] = cat_vol_imcalc(spm_vol(Pavgp0),spm_vol(res.image.fname),'i1',struct('interp',3,'verb',0,'mask',-1)); clear Vb; %#ok + else + Yb = spm_read_vols(spm_vol(Pavgp0)); + end + Yb = Yb > 0.5; + else + % otherwise it would be possible to use the individual TPM + % however, the TPM is more smoothed and is therefore only second choice + cat_io_addwarning('cat_main_updateSPM:miss_p0avg',sprintf('Cannot find p0avg use TPM for brainmask: \n %s\n',Pavgp0),2,[1 2]); + Yb = YbA > 0.5; + clear YbA + end + Ybb = cat_vol_ctype(cat_vol_smooth3X(Yb,0.5)*256); + + %% correct tissues + % RD20221224: Only the brainmask wasn't enough and we need to cleanup + % the segmentation also here (only for long pipeline) + % move brain tissue to head tissues or vice versa + for ti = 1:3 + if ti == 1 % GM with soft boundary to reduce meninges + Ynbm = cat_vol_ctype( single(P(:,:,:,ti)) .* (1 - max(0,2 * smooth3(Yb) - 1) ) ); + Ybm = cat_vol_ctype( single(P(:,:,:,5)) .* ( max(0,2 * smooth3(Yb) - 1) ) ); + elseif ti == 2 % WM with very soft boundary because we exptect no WM close to the skull + Ynbm = cat_vol_ctype( single(P(:,:,:,ti)) .* (1 - max(0,2 * single(Ybb)/255 - 1) ) ); + Ybm = cat_vol_ctype( single(P(:,:,:,5)) .* ( max(0,2 * single(Ybb)/255 - 1) ) ); + else % CSF with hard boundary + Ynbm = cat_vol_ctype( single(P(:,:,:,ti)) .* (1 - Yb) ); + Ybm = cat_vol_ctype( single(P(:,:,:,5)) .* ( Yb) ); + end + P(:,:,:,ti) = P(:,:,:,ti) - Ynbm + Ybm; + P(:,:,:,5) = P(:,:,:,5) + Ynbm - Ybm; + clear Ynbm Ybm; + end + % some extra GM cleanup for meninges + Yngm = P(:,:,:,1) .* uint8( Ybb<255 & (P(:,:,:,1)>64) & (smooth3( single(P(:,:,:,1)>64) )<0.5) ); + P(:,:,:,1) = P(:,:,:,1) - Yngm; P(:,:,:,5) = P(:,:,:,5) + Yngm; %if ~debug, clear Yngm; end + % some further hard GM cleanup ? + %{ + Yp0avg = spm_read_vols(spm_vol(Pavgp0)); + Yngm = P(:,:,:,1) .* uint8( cat_vol_morph( Yp0avg < 1.75 , 'de' , 3, vx_vol) & Yp0yvg>0 ); + P(:,:,:,1) = P(:,:,:,1) - Yngm; P(:,:,:,5) = P(:,:,:,5) + Yngm; %if ~debug, clear Yngm; end + %} + + elseif size(P,4)==4 || size(P,4)==3 % skull-stripped + [Yb,Ybb,Yg,Ydiv,P] = cat_main_updateSPM_skullstriped(Ysrc,P,res,vx_vol,T3th); + Yb = Ybx; Ybb = Ybx; + elseif job.extopts.gcutstr==0 + [Yb,Ybb,Yg,Ydiv] = cat_main_updateSPM_gcut0(Ysrc,P,vx_vol,T3th); + elseif job.extopts.gcutstr==2 + [Yb,Ybb,Yg,Ydiv] = cat_main_APRG(Ysrc,P,res,T3th); + else + [Yb,Ybb,Yg,Ydiv] = cat_main_updateSPM_gcutold(Ysrc,P,res,vx_vol,T3th); + end + + + % RD202101: cleanup+ remove small unconnected components + %{ + Pgm = P(:,:,:,1); + Ybb = cat_vol_ctype(cat_vol_morph(Yb,'de',4,vx_vol)); + Ym = Pgm>192; Ygc = cat_vol_morph(Ym | Ybb,'l',[inf,27])>0; Pgm(Ym(:)) = Pgm(Ym(:)) .* cat_vol_ctype(Ygc(Ym(:))); + Ym = Pgm>128; Ygc = cat_vol_morph(Ym | Ybb,'l',[inf,27])>0; Pgm(Ym(:)) = Pgm(Ym(:)) .* cat_vol_ctype(Ygc(Ym(:))); + Ym = Pgm> 64; Ygc = cat_vol_morph(Ym | Ybb,'l',[inf,27])>0; Pgm(Ym(:)) = Pgm(Ym(:)) .* cat_vol_ctype(Ygc(Ym(:))); + Ym = Pgm> 8; Ygc = cat_vol_morph(Ym | Ybb,'l',[inf,27])>0; Pgm(Ym(:)) = Pgm(Ym(:)) .* cat_vol_ctype(Ygc(Ym(:))); + Ygc = cat_vol_morph(Pgm> 64,'l',[inf,27])>0; Pgm = Pgm .* cat_vol_ctype(Ygc | Ybb); + P(:,:,:,2) = P(:,:,:,2) + ( (P(:,:,:,1) - Pgm) .* cat_vol_ctype(Ysrc>T3th(2))); % add to WM + P(:,:,:,3) = P(:,:,:,3) + ( (P(:,:,:,1) - Pgm) .* cat_vol_ctype(Ysrc min(0.5,max(0.25, job.extopts.gcutstr))); clear Ym0 + Yb0 = cat_vol_morph(cat_vol_morph(Yb0,'lo'),'c'); + + + +% RD202010: In some images SPM selects the image BG and brain tisssue as class 4 +%{ + volcls4 = sum(sum(sum( single(P(:,:,:,4)>64) .* (Yb>0.5) ))) .* prod(vx_vol)/1000; + volcls5 = sum(sum(sum( single(P(:,:,:,5)>64) .* (Yb>0.5 & (Ysrc>=mean(T3th(1:2)) & Ysrc64) .* (Yb>0.5 & (Ysrc>=mean(T3th(1:2)) & Ysrc10) 5*(volcls5>10) 6*(volcls6>10) ] ) , 0); + if volcls4 > 10 || volcls5 > 10 || volcls6 > 10 + PN{1} = cat_vol_ctype( single(P(:,:,:,1)) + single(sum(P(:,:,:,scls),4)) .* (Yb>0.5) .* ... + (Ysrc>=mean(T3th(1:2)) & Ysrc0.5) .* ... + (Ysrc>=mean(T3th(2:3)) & Ysrc0.5) .* ... + (Ysrc< mean(T3th(1:2))) ); % CSF + PN{4} = cat_vol_ctype( single( P(:,:,:,4) ) .* (Ysrc 0.3 + 0.2*TPisSmaller % just some threshold (RD20220103: adjusted by TPisSmaller) + % setup new background + Ynbg = Ybg>0.5 | ( P(:,:,:,end)>128 & Ysrc < mean( T3th(1:2) ) ); + Ynbg = cat_vol_morph(Ynbg,'dc',5,vx_vol); + Ynbg = uint8( 255 .* smooth3(Ynbg) ); + + % correct classes + for k1 = 1:size(P,4)-1, P(:,:,:,k1) = P(:,:,:,k1) - min(P(:,:,:,k1),Ynbg); end + P(:,:,:,end) = max( Ynbg , P(:,:,:,end) ); + clear Ynbg; + + % normalize all classes + sP = (sum(single(P),4)+eps)/255; + for k1=1:size(P,4), P(:,:,:,k1) = cat_vol_ctype(single(P(:,:,:,k1))./sP); end + clear sP; + + cat_io_addwarning('cat_main_updateSPM:ReplacedLongBackground','Detected and corrected inadequate background \\nsegmentation in longitudinal mode.',0,[1 2]); + end + clear Ybg; + end + + + + + stime2 = cat_io_cmd(' Update probability maps','g5','',job.extopts.verb-1,stime2); + if ~(any(sign(diff(T3th))==-1)) && ... + ~( (isfield(job,'useprior') && ~isempty(job.useprior) && strcmp(job.opts.affreg,'prior') ) && ... % no single longitudinal timepoint + (isfield(res,'ppe') && ~res.ppe.affreg.highBG) ) + %% Update probability maps + % background vs. head - important for noisy backgrounds such as in MT weighting + if size(P,4)==4 || size(P,4)==3 % skull-stripped + Ybg = ~Yb; + else + if sum(sum(sum(P(:,:,:,6)>240 & Ysrc10000 + Ybg = P(:,:,:,6); + [Ybgr,Ysrcr,resT2] = cat_vol_resize({Ybg,Ysrc},'reduceV',vx_vol,2,32); + Ybgrth = max(cat_stat_nanmean(Ysrcr(Ybgr(:)>128)) + 2*std(Ysrcr(Ybgr(:)>128)),T3th(1)); + Ybgr = cat_vol_morph(cat_vol_morph(cat_vol_morph(Ybgr>128,'d') & Ysrcr=T3th(2)) .* (Ybg<0.5) + single(P(:,:,:,5)) .* (Ybg<0.5) ); % remove air in head + P6 = cat_vol_ctype( single(sum(P(:,:,:,4:5),4)) .* (Ybg>0.5) + single(P(:,:,:,6)) .* (Ybg>0.5) ); % add objects/artifacts to background + P(:,:,:,4) = P4; + P(:,:,:,5) = P5; + P(:,:,:,6) = P6; + clear P4 P5 P6; + + sP = (sum(single(P),4)+eps)/255; + for k1=1:size(P,4), P(:,:,:,k1) = cat_vol_ctype(single(P(:,:,:,k1))./sP); end + + %% correct probability maps to 100% + sumP = cat_vol_ctype(255 - sum(P(:,:,:,1:6),4)); + P(:,:,:,1) = P(:,:,:,1) + sumP .* uint8( Ybg<0.5 & Yb & Ysrc>cat_stat_nanmean(T3th(1:2)) & Ysrc=cat_stat_nanmean(T3th(2:3))); + P(:,:,:,3) = P(:,:,:,3) + sumP .* uint8( Ybg<0.5 & Yb & Ysrc<=cat_stat_nanmean(T3th(1:2))); + P(:,:,:,4) = P(:,:,:,4) + sumP .* uint8( Ybg<0.5 & ~Yb & Ysrc=T3th(2)); + P(:,:,:,6) = P(:,:,:,6) + sumP .* uint8( Ybg>=0.5 & ~Yb ); + clear Ybg sumP; + + + %% head to WM + % Undercorrection of strong inhomogeneities in high field scans + % (>1.5T) can cause missalignments of the template and therefore + % miss classifications of the tissues that finally avoid further + % corrections in by LAS. + % Typically the alginment failed in this cases because the high + % intensities next to the head that were counted as head and not + % corrected by SPM. + % e.g. HR075, Magdeburg7T, SRS_SRS_Jena_DaRo81_T1_20150320-191509_MPR-08mm-G2-bw330-nbc.nii, ... + Ywm = single(P(:,:,:,2)>128 & Yg<0.3 & Ydiv<0.03); Ywm(Ybb<128 | (P(:,:,:,1)>128 & abs(Ysrc/T3th(3)-2/3)<1/3) | Ydiv>0.03) = nan; + [Ywm1,YD] = cat_vol_downcut(Ywm,1-Ysrc/T3th(3),0.02); Yb(isnan(Yb))=0; Ywm(YD<300)=1; Ywm(isnan(Ywm))=0; clear Ywm1 YD; %#ok + Ywmc = uint8(smooth3(Ywm)>0.7); + Ygmc = uint8(cat_vol_morph(Ywmc,'d',2) & ~Ywmc & Ydiv>0 & Yb & cat_vol_smooth3X(Yb,8)<0.9 & Ysrc>mean(T3th(1:2))); + P(:,:,:,[1,3:6]) = P(:,:,:,[1,3:6]) .* repmat(1-Ywmc,[1,1,1,5]); + P(:,:,:,2:6) = P(:,:,:,2:6) .* repmat(1-Ygmc,[1,1,1,5]); + P(:,:,:,1) = max(P(:,:,:,1),255*Ygmc); + P(:,:,:,2) = max(P(:,:,:,2),255*Ywmc); + Yp0 = single(P(:,:,:,3))/255/3 + single(P(:,:,:,1))/255*2/3 + single(P(:,:,:,2))/255; + clear Ygmc Ywmc; + + + %% head to GM ... important for children + [Ywmr,Ybr,resT2] = cat_vol_resize({Ywm,Yb},'reduceV',vx_vol,2,32); + Ygm = cat_vol_morph(Ywmr>0.5,'d',3) & (cat_vol_morph(~Ybr,'d',3) | cat_vol_morph(Ybr,'d',1)); clear Ybr Ywmr; % close to the head + Ygm = cat_vol_resize(single(Ygm),'dereduceV',resT2)>0.5; + Ygm = Ygm & Yp0<2/3 & Yb & Yg64)) & Ydiv64)); % add GM with low SPM prob ... + Ygm = Ygm & (Ysrc>cat_stat_nansum(T3th(1:2).*[0.5 0.5])) & (Ysrc skull (within the brainmask) + if ~(size(P,4)==4 || size(P,4)==3 || res.ppe.affreg.skullstripped) + Yhdc = uint8(smooth3( Ysrc/T3th(3).*(Ybb>cat_vol_ctype(0.2*255)) - Yp0 )>0.5); + sumP = sum(P(:,:,:,1:3),4); + P(:,:,:,4) = cat_vol_ctype( single(P(:,:,:,4)) + sumP .* ((Ybb<=cat_vol_ctype(0.05*255)) | Yhdc ) .* (Ysrc=T3th(2))); + P(:,:,:,1:3) = P(:,:,:,1:3) .* repmat(uint8(~(Ybb<=cat_vol_ctype(0.05*255)) | Yhdc ),[1,1,1,3]); + end + clear sumP Yp0 Yhdc; + end + clear Ybb; + + + + + %% MRF + % Used spm_mrf help and tested the probability TPM map for Q without good results. + nmrf_its = 0; % 10 iterations better to get full probability in thin GM areas + spm_progress_bar('init',nmrf_its,['MRF: Working on ' nam],'Iterations completed'); + if isfield(res,'mg'), Kb = max(res.lkp); else, Kb = size(res.intensity(1).lik,2); end + G = ones([Kb,1],'single'); + vx2 = single(sum(res.image(1).mat(1:3,1:3).^2)); + % P = zeros([d(1:3),Kb],'uint8'); + % P = spm_mrf(P,Q,G,vx2); % init: transfer data from Q to P + if 0 + %% use TPM as Q + Q = zeros(size(P),'uint8'); + for di=1:6 + vol = cat_vol_ctype(spm_sample_vol(tpm.V(di),... + double(Yy(:,:,:,1)),double(Yy(:,:,:,2)),double(Yy(:,:,:,3)),0)*255,'uint8'); + Q(:,:,:,di) = reshape(vol,d); + end + end + for iter=1:nmrf_its + P = spm_mrf(P,single(P),G,vx2); % spm_mrf(P,Q,G,vx2); + spm_progress_bar('set',iter); + end + + %% update segmentation for error report + Yp0 = single(P(:,:,:,3))/255/3 + single(P(:,:,:,1))/255*2/3 + single(P(:,:,:,2))/255; + [cat_err_res.init.Yp0,cat_err_res.init.BB] = cat_vol_resize(Yp0,'reduceBrain',vx_vol,2,Yp0>0.5); + cat_err_res.init.Yp0 = cat_vol_ctype(cat_err_res.init.Yp0/3*255); + + spm_progress_bar('clear'); + for k1=1:size(P,4) + Ycls{k1} = P(:,:,:,k1); %#ok + end + clear Q P q q1 Coef b cr N lkp n wp M k1 + + + if job.extopts.verb>2 + % save information for debugging and OS test + % input variables + bias corrected, bias field, class image + % strong differences in bias fields can be the result of different + % registration > check 'res.image.mat' and 'res.Affine' + [~, reportfolder] = cat_io_subfolders(res.image(1).fname,job); + [pth,nam] = spm_fileparts(res.image0(1).fname); + tpmci = 1; + tmpmat = fullfile(pth,reportfolder,sprintf('%s_%s%02d%s.mat',nam,'write',tpmci,'postbias')); + save(tmpmat,'res','tpm','job','Ysrc','Ycls'); + end + + stime2 = cat_io_cmd(' ','g5','',job.extopts.verb-1,stime2); + if job.extopts.verb + fprintf('%5.0fs\n',etime(clock,stime)); + end + + % some reports + for i=1:numel(Ycls), res.ppe.SPMvols1(i) = cat_stat_nansum(single(Ycls{i}(:)))/255 .* prod(vx_vol) / 1000; end + + % display some values for developers + if job.extopts.expertgui > 1 + % ... I want to add the intensities later + %cat_io_cprintf('blue',sprintf(' SPM volumes (CGW=TIV; in mm%s): %6.2f + %6.2f + %6.2f = %4.0f\n',... + % native2unicode(179, 'latin1'),res.ppe.SPMvols0([3 1 2]),sum(res.ppe.SPMvols0(1:3)))); + cat_io_cprintf('blue',sprintf(' SPM volumes pre (CGW=TIV; in mm%s): %7.2f +%7.2f +%7.2f = %4.0f\n',... + native2unicode(179, 'latin1'),res.ppe.SPMvols0([3 1 2]),sum(res.ppe.SPMvols0(1:3)))); + cat_io_cprintf('blue',sprintf(' SPM volumes post (CGW=TIV; in mm%s): %7.2f +%7.2f +%7.2f = %4.0f\n',... + native2unicode(179, 'latin1'),res.ppe.SPMvols1([3 1 2]),sum(res.ppe.SPMvols1(1:3)))); + end + + + +end +function [Yb,Ybb,Yg,Ydiv,P] = cat_main_updateSPM_skullstriped(Ysrc,P,res,vx_vol,T3th) + Yp0 = single(P(:,:,:,3))/255/3 + single(P(:,:,:,1))/255*2/3 + single(P(:,:,:,2))/255; + Yb = Yp0>=0.5/3; + Ybb = cat_vol_ctype(Yb)*255; + + P(:,:,:,6) = P(:,:,:,4); + P(:,:,:,4) = zeros(size(Ysrc),'uint8'); + P(:,:,:,5) = zeros(size(Ysrc),'uint8'); + res.lkp = [res.lkp 5 6]; + res.mn = [res.mn(1:end-1),0,0,0]; + res.mg = [res.mg(1:end-1);1;1;1]; + res.vr(1,1,numel(res.lkp)-1:numel(res.lkp)) = 0; + + [Ysrcb,BB] = cat_vol_resize(Ysrc,'reduceBrain',vx_vol,round(6/mean(vx_vol)),Yp0>1/3); clear Yp0; + Yg = cat_vol_grad(Ysrcb/T3th(3),vx_vol); + Ydiv = cat_vol_div(Ysrcb/T3th(3),vx_vol); + Yg = cat_vol_resize(Yg ,'dereduceBrain',BB); + Ydiv = cat_vol_resize(Ydiv ,'dereduceBrain',BB); +end +function [Yb,Ybb,Yg,Ydiv] = cat_main_updateSPM_gcut0(Ysrc,P,vx_vol,T3th) + % brain mask + Ym = single(P(:,:,:,3))/255 + single(P(:,:,:,1))/255 + single(P(:,:,:,2))/255; + Yb = (Ym > 0.5); + Yb = cat_vol_morph(cat_vol_morph(Yb,'lo'),'c'); + Ybb = cat_vol_ctype(cat_vol_smooth3X(Yb,2)*256); + + [Ysrcb,BB] = cat_vol_resize({Ysrc},'reduceBrain',vx_vol,round(6/mean(vx_vol)),Yb); + Yg = cat_vol_grad(Ysrcb/T3th(3),vx_vol); + Ydiv = cat_vol_div(Ysrcb/T3th(3),vx_vol); + Yg = cat_vol_resize(Yg ,'dereduceBrain',BB); + Ydiv = cat_vol_resize(Ydiv ,'dereduceBrain',BB); +end +function [Yb,Ybb,Yg,Ydiv] = cat_main_updateSPM_gcutold(Ysrc,P,res,vx_vol,T3th) +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% T1 only > remove in future if gcut is removed too! +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + clsint = @(x) round( sum(res.mn(res.lkp==x) .* res.mg(res.lkp==x)') * 10^5)/10^5; + voli = @(v) (v ./ (pi * 4./3)).^(1/3); % volume > radius + Yp0toC = @(Yp0,c) 1-min(1,abs(Yp0-c)); + + % old skull-stripping + Yp0 = single(P(:,:,:,3))/255/3 + single(P(:,:,:,1))/255*2/3 + single(P(:,:,:,2))/255; + brad = voli(sum(Yp0(:)>0.5).*prod(vx_vol)/1000); + [Ysrcb,Yp0,BB] = cat_vol_resize({Ysrc,Yp0},'reduceBrain',vx_vol,round(6/mean(vx_vol)),Yp0>1/3); + %Ysrcb = max(0,min(Ysrcb,max(T3th)*2)); + BGth = min(cat_stat_nanmean(Ysrc( P(:,:,:,6)>128 )),clsint(6)); + Yg = cat_vol_grad((Ysrcb-BGth)/diff([BGth,T3th(3)]),vx_vol); + Ydiv = cat_vol_div((Ysrcb-BGth)/diff([BGth,T3th(3)]),vx_vol); + Ybo = cat_vol_morph(cat_vol_morph(Yp0>0.3,'lc',2),'d',brad/2/mean(vx_vol)); + BVth = diff(T3th(1:2:3))/abs(T3th(3))*1.5; + RGth = diff(T3th(2:3))/abs(T3th(3))*0.1; + Yb = single(cat_vol_morph((Yp0>1.9/3) | (Ybo & Ysrcb>mean(T3th(2)) & ... + Ysrcbcat_stat_nanmean(T3th(3)*1.2) | Yg>BVth))=nan; + [Yb1,YD] = cat_vol_downcut(Yb,Ysrcb/T3th(3),RGth); clear Yb1; Yb(isnan(Yb))=0; Yb(YD<400/mean(vx_vol))=1; clear YD; %#ok + Yb(smooth3(Yb)<0.5)=0; Yb = single(Yb | (Ysrcb>T3th(1) & Ysrcb<1.2*T3th(3) & cat_vol_morph(Yb,'lc',4))); + + %% region-growing GM 2 + Yb(~Yb & (~Ybo | Ysrcbcat_stat_nanmean(T3th(3)*1.2) | Yg>BVth))=nan; + [Yb1,YD] = cat_vol_downcut(Yb,Ysrcb/T3th(3),RGth/2); clear Yb1; Yb(isnan(Yb))=0; Yb(YD<400/mean(vx_vol))=1; clear YD; %#ok + Yb(smooth3(Yb)<0.5)=0; Yb = single(Yb | (Ysrcb>T3th(1) & Ysrcb<1.2*T3th(3) & cat_vol_morph(Yb,'lc',4))); + + %% region-growing GM 3 + Yb(~Yb & (~Ybo | Ysrcbcat_stat_nanmean(T3th(3)*1.2) | Yg>BVth))=nan; clear Ybo; + [Yb1,YD] = cat_vol_downcut(Yb,Ysrcb/T3th(3),RGth/10); clear Yb1; Yb(isnan(Yb))=0; Yb(YD<400/mean(vx_vol))=1; clear YD; %#ok + Yb(smooth3(Yb)<0.5)=0; Yb(Yp0toC(Yp0*3,1)>0.9 & Yg<0.3 & Ysrcb>BGth & Ysrcb0,Ysrcb/T3th(3)},'reduceV',vx_vol,2,32); clear Ysrcb + Ybr = Ybr | (Ymr<0.8 & cat_vol_morph(Ybr,'lc',6)); clear Ymr; % large ventricle closing + Ybr = cat_vol_morph(Ybr,'lc',2); % standard closing + Yb = Yb | cat_vol_resize(cat_vol_smooth3X(Ybr,2),'dereduceV',resT2)>0.7; clear Ybr + Yb = smooth3(Yb)>0.5; + Ybb = cat_vol_ctype(cat_vol_smooth3X(Yb,2)*255); + Yb = cat_vol_resize(Yb , 'dereduceBrain' , BB); + Ybb = cat_vol_resize(Ybb , 'dereduceBrain' , BB); + Yg = cat_vol_resize(Yg , 'dereduceBrain' , BB); + Ydiv = cat_vol_resize(Ydiv , 'dereduceBrain' , BB); + clear Ysrcb Ybo; +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_stat_TIV.m",".m","2598","88","function varargout = cat_stat_TIV(p) +%cat_stat_TIV to read total intracranial volume (TIV) from xml-files +% +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +if ~isfield(p,'calcvol_savenames') + p.calcvol_savenames = 0; +end + +if ~p.calcvol_TIV + fprintf('%60s\t%7s\t%7s\t%7s\t%7s\t%7s\n','Name','Total','GM','WM','CSF','WMH'); +end +fid = fopen(p.calcvol_name,'w'); + +if fid < 0 + error('No write access: check file permissions or disk space.'); +end + +if p.calcvol_TIV + calcvol = zeros(length(p.data_xml),1); +else + calcvol = zeros(length(p.data_xml),5); +end + +cat_progress_bar('Init',length(p.data_xml),'Load xml-files','subjects completed') +for i=1:length(p.data_xml) + xml = cat_io_xml(deblank(p.data_xml{i})); + try + tmp = xml.subjectmeasures.vol_abs_CGW; + catch % use nan + if p.calcvol_TIV + tmp = nan; + else + tmp = nan(1,5); + end + end + + if isfield(xml,'filedata') + pth = xml.filedata.path; + file = xml.filedata.file; + filename = spm_str_manip(deblank(fullfile(xml.filedata.path,xml.filedata.file)),'a60'); + else + [pth,file] = fileparts(deblank(p.data_xml{i})); + filename = spm_str_manip(deblank(p.data_xml{i}),'a60'); + end + + % only save TIV + if p.calcvol_TIV + switch p.calcvol_savenames + case 0 + fprintf(fid,'%7.2f\n',sum(tmp)); + case 1 + fprintf(fid,'%s\t%7.2f\n',file,sum(tmp)); + case 2 + fprintf(fid,'%s\t%7.2f\n',fullfile(pth,file),sum(tmp)); + end + calcvol(i) = sum(tmp); + fprintf('%60s\t%7.2f\n',filename,sum(tmp)); + else % also save GM/WM/CSF + switch p.calcvol_savenames + case 0 + fprintf(fid,'%7.2f\t%7.2f\t%7.2f\t%7.2f\t%7.2f\n',sum(tmp),tmp(2),tmp(3),tmp(1),tmp(4)); + case 1 + fprintf(fid,'%s\t%7.2f\t%7.2f\t%7.2f\t%7.2f\t%7.2f\n',file,sum(tmp),tmp(2),tmp(3),tmp(1),tmp(4)); + case 2 + fprintf(fid,'%s\t%7.2f\t%7.2f\t%7.2f\t%7.2f\t%7.2f\n',fullfile(pth,file),sum(tmp),tmp(2),tmp(3),tmp(1),tmp(4)); + end + calcvol(i,:) = [sum(tmp),tmp(2),tmp(3),tmp(1),tmp(4)]; + fprintf('%60s\t%7.2f\t%7.2f\t%7.2f\t%7.2f\t%7.2f\n',filename,sum(tmp),tmp(2),tmp(3),tmp(1),tmp(4)); + end + cat_progress_bar('Set',i); +end +cat_progress_bar('Clear'); + +if fclose(fid)==0 + fprintf('\nValues saved in %s.\n',p.calcvol_name); + if nargout == 1 + varargout{1}.calcvol = calcvol; + end +end +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_vol_savg.m",".m","69179","1700","function out = cat_vol_savg(job) +%cat_vol_savg. Function to average images session- and subject-wise. +% +% out = cat_vol_savg(job) +% +% job .. SPM job structure +% .subjects .. cell of subjects with a cell of input files +% .ref .. coregistration reference image filenames +% .reslim .. resolution limitation of input images [inslice slice] +% .filelim .. limitation of input file number [low high] +% .sanlm .. apply denoising (0-no*,1-yes) +% .seg .. segmenation approach (SPM|CAT) +% .res .. output resolution of the final average +% .bias .. bias-fwhm for preprocessing and image-wise correction +% .norm .. intensity normalization approach (none,...) +% .mcon .. average contrast limitation (e.g., 0.05 - 0.3) +% .cleanup .. remove temporary files +% .verb .. be verbose (0-no,1-subject,2-details) +% +% out.avg .. output filenames for batch dependency +% +% ______________________________________________________________________ +% $Id: cat_surf_parameters.m 1901 2021-10-26 10:25:52Z gaser $ +% Robert Dahnke 202007 + +% TODO: +% * code documentation +% * contrast scaling (expert, default 1 = none) ? +% (auto, ^4, ^2, 1, ^0.5, ^0.25) +% +% ** mat-report with +% - segmentation measures (tissue peaks, volumes) +% - QC values +% ** QC (optional) +% > weighed integration of images based on QC (+++++) +% > localy-weighted integration of images +% use the segmentation to detect local movement artefacts (waves) +% * improve averaging > paraemter ? +% - averaging by windowed mean based on the variance (histogram) +% - use of Christian longitudinal realignment? +% - use John's long deformation model? +% . relevant in case of no real rescans from different sides +% (see also longitudinal model) +% . not really relevant! +% * reports (mat/pdf) >> pdf with otions + QC + SPM vols + mean + std +% * subject report +% * sample report ?? ... would need to save registration temporary +% * protocol report ... mean of sd +% * protocol data handling +% - mix modalities (yes/no) +% - use modalities (T1 only, separate (T1,T2,PD), mixed (T1+T2+PD), separate+mixed) +% - mixing parameter +% - protocol detection (eg. by contrast / filename ) >> imcalc+ +% +% * input of BIDS etc. ... tests +% * long support (BIDS) +% * output directories +% * only average gradient-based information +% * verbose setting +% * dependencies +% +% * Evaluation concept! +% - simulation +% - real +% - comparison to Freesurfer averaging +% - rescans (same high-quality) vs. mixed protocols (low-quality upsampling - clinical) +% +% + + SVNid = '$Rev: 1901 $'; + + % get defaults + job = get_defaults(job); + + + % for each subject + si = 1; se = 1; fi = 1; fni = 1; %#ok + out = struct(); + + + % search files in case of input directories + if ~(isfield(job,'subs') && job.printPID) + [subjects,sBIDS,sname,devdir] = getFiles(job); + end + + + % split job and data into separate processes to save computation time + if job.opts.nproc>0 && (~isfield(job,'process_index')) + job.subs = subjects; + job.nproc = job.opts.nproc; + if exist('sBIDS','var') + job.datafields = {'sBIDS','sname','devdir'}; + job.sBIDS = sBIDS; + job.sname = sname; + job.devdir = devdir; + end + if nargout==1 + out{1} = cat_parallelize(job,mfilename,'subs'); + else + cat_parallelize(job,mfilename,'subs'); + end + return + elseif isfield(job,'subs') && job.printPID + %cat_display_matlab_PID; + subjects = job.subs; + if isfield(job,'sBIDS') + sBIDS = job.sBIDS; + sname = job.sname; + devdir = job.devdir; + end + end + + + % new banner + if isfield(job,'process_index'), spm('FnBanner',mfilename,SVNid); end + + methodstr = {'CATavg','CATlong','SPMlong','Brudfors'}; + out.savg = {}; + %% main loop for all subjects + % ====================================================================== + for si = 1:numel( subjects ) + stime = clock; + if job.opts.verb > 1 + cat_io_cprintf([0.2 0.2 .5],'=== Subject %d %s ===\n', si, sname{si} ); + else + cat_io_cprintf([0.2 0.2 .5],'Subject %d: %s\n',si, sname{si} ); + end + + % ===================================================================== + % Average per sequence + % ===================================================================== + for seqi = 1:numel( subjects{si} ) + %% =================================================================== + % (1) Average per session + % =================================================================== + for sesi = 1:numel( subjects{si}{seqi} ) + if isempty( subjects{si}{seqi}{sesi} ) + out.savg{si}{seqi}{sesi,1} = ''; continue + end + + % handle zipped BIDS + subjects{si}{seqi}{sesi} = prepareBIDSgz(subjects{si}{seqi}{sesi}, sBIDS(si), devdir{si}{seqi}{sesi}); + + % bias correction and intensity normalization + if job.opts.bias > 0 + biascorrection(subjects{si}{seqi}{sesi}, job) + end + + % denoising for all methods + if job.opts.sanlm ~= 0 + denoise(subjects{si}{seqi}{sesi}, job) + end + + % no rescans? + if isscalar( subjects{si}{seqi}{sesi} ) + out.savg{si}{seqi}(sesi,1)= subjects{si}{seqi}{sesi}; continue + end + + if job.opts.verb > 1 + cat_io_cprintf([0.2 0.2 .5],'=== Subject %d - session %d: Average %d %s rescans ===\n', ... + si, sesi, numel( subjects{si}{seqi}{sesi} ), job.limits.seplist{seqi} ); + elseif job.opts.verb + cat_io_cprintf([0.2 0.2 .5],' Average %d %s-rescans in session %d.\n', ... + numel( subjects{si}{seqi}{sesi} ), job.limits.seplist{seqi} , sesi ); + end + + switch job.opts.avgmethod + case 1 + % MNI space using SPM (co)registration + [out.savg{si}{seqi}{sesi,1}, out.sesra{si}] = savg(subjects{si}{seqi}{sesi},1, methodstr{1}, job, seqi); + case 2 + % CAT longitudinal averaging function (rigid) + [out.savg{si}{seqi}{sesi,1}, out.sesra{si}] = catlong(subjects{si}{seqi}{sesi}, methodstr{2}, job, seqi); + case 3 + % SPM longitudinal averaging function (rigid) + out.savg{si}{seqi}{sesi,1} = spmlong(subjects{si}{seqi}{sesi}, methodstr{3}, job, seqi); + case 4 + % Brudfors averaging function (rigid) + out.savg{si}{seqi}{sesi,1} = brudfors(subjects{si}{seqi}{sesi}, methodstr{4}, job, seqi); + end + + end + + + % (2) average per subject + % =================================================================== + if numel( out.savg ) < si || numel( out.savg{si} ) < seqi, continue; end + if isempty( out.savg{si}(seqi) ) || isempty( out.savg{si}{seqi} ) || ... + isempty( out.savg{si}{seqi}{1} ) || isscalar( out.savg{si}{seqi} ) + out.subavg{si}{seqi,1} = ''; continue; + end + + if job.opts.verb > 1 + cat_io_cprintf([0 0 1],' Subject %d: Average %d %s-sessions.\n\n', ... + si, numel(out.savg{si}{seqi}), job.limits.seplist{seqi}), + else + cat_io_cprintf([0 0 1],' Average %d %s-sessions.\n', ... + numel(out.savg{si}{seqi}), job.limits.seplist{seqi}), + end + + switch job.opts.avgmethod + case 1 + % MNI space using SPM (co)registration + [out.subavg{si}{seqi,1}, out.sesra{si}{seqi}] = savg(out.savg{si}{seqi},1, methodstr{1}, job, seqi, 1); + case 2 + % CAT longitudinal averaging function (rigid) + [out.subavg{si}{seqi,1}, out.sesra{si}{seqi}] = catlong(out.savg{si}{seqi}, methodstr{2}, job, seqi, 1); + case 3 + % SPM longitudinal averaging function (rigid) + out.subavg{si}{seqi,1} = spmlong(out.savg{si}{seqi}, methodstr{3}, job, seqi, 1); + case 4 + % Brudfors averaging function (rigid) + out.subavg{si}{seqi,1} = brudfors(out.savg{si}{seqi}, methodstr{4}, job, seqi, 1); + end + end + + %% algin to MNI ? + + + + %% + cat_io_cmd(' ','g5','',job.opts.verb>1); + fprintf('%5.0fs\n',etime(clock,stime)); + end +end +%-------------------------------------------------------------------------- +function biascorrection(subject,job) +%biascorrection. intensity normalization and bias correction + + if job.opts.bias>1 + stime = cat_io_cmd(' Intensity Normalization & Bias Correction','g7','',job.opts.verb>1); + elseif job.opts.bias + stime = cat_io_cmd(' Intensity Normalization','g7','',job.opts.verb>1); + else + return + end + + for vi = 1:numel(subject) + V = spm_vol( subject{vi} ); + Y = single(spm_read_vols( V )); + + vx_vol = sqrt(sum(V.mat(1:3,1:3).^2)); + if job.opts.bias > 1 + Yo = Y; + + + %% iteration + Y = Yo; + for i = 0:(job.opts.bias-1) + %% use lower resolution to denoise and for speedup + [Yr,redR] = cat_vol_resize(Y,'reduceV',vx_vol,max(1.5,min(3, vx_vol*2 )),32,'meanm'); + + % use the gradient to estimate main tissues such as the WM + Ygr = cat_vol_grad(Yr,vx_vol) ./ Yr; + % avoid edges of the image + Ybb = false(size(Ygr)); Ybb(2:end-1,2:end-1,2:end-1) = true; + + % object = brain/head + Yr = Yr ./ prctile(Yr(Ygr(:)~=0 & Ygr(:)<.3),90); % 80-90 + % Yr = cat_vol_median3(Yr,Yr>.1); % quick denoising + Yt = cat_vol_morph(Yr > .2 & Ybb,'ldc'); + Ytd = cat_vbdist( single(~Yt) ); Ytd = Ytd ./ max(Ytd(:)); + + % brain tissue + Yt2 = Yr>.3 & Yt & (Ygr./Ytd.^1.2 < prctile(Ygr( Yt(:) ),50)) & Ytd>.3 & (Ygr < prctile(Ygr( Yt(:) ),80)); + Yt2 = cat_vol_morph(Yt2,'l'); + Ygg = Yt .* (Yt - Ygr); + gth = prctile(Ygg(Yt2(:)>0 & Ygg(:)>0),50); + + % intial bias field to remove inproper values + Ywr = cat_vol_approx( Yr .* (Yt2 & Ygg>gth)); + Ywr = spm_smooth3(Ywr,60 / 2^i ./ vx_vol); + Ygg(Yr ./ Ywr < 0.95 | Yr ./ Ywr > max(1.2,1.5 - .05*i)) = 0; + + % estimate and apply final interative bias field + Ywr = cat_vol_approx( Yr .* (Yt2 & Ygg>gth & Ygr .5; + Yw = cat_vol_resize(Ywr,'dereduceV',redR); + Yw = Yw ./ prctile(Yw(Yt2(:)),90) * prctile(Y(Yt2(:)),90); + Y = Y ./ Yw; + end + + %% final correction + Yw = ( Yo/prctile(Yo(Yt2(:)),90) ) ./ ( Y/prctile(Y(Yt2(:)),90)); + Ywa = cat_vol_approx( Yw ); Yw(Yw>10 | Yw<.01) = Ywa(Yw>10 | Yw<.01); + Yw = spm_smooth3(Yw,60 / (job.opts.bias-1) ./ vx_vol); + Yw = Yw / prctile(Yw(Yt2(:)),90) * prctile(Yo(Yt2(:)),90); + Ym = Yo ./ Yw; + + else + % only intensity normalization + Ym = Y / prctile(Y(:),90); + end + + %% write + V.dt(1) = 4; + V.pinfo(1) = 1e-4; + V.pinfo(2) = 0; + spm_write_vol(V,Ym); + end + + if job.opts.verb>1 + fprintf('%5.0fs\n',etime(clock,stime)); + end +end +function Y = spm_smooth3(Y,sx) +%spm_smooth3. Avoid zeros in spm_smooth + if sx > 8 + [Yr,redR] = cat_vol_resize(Y,'reduceV',1,2,32,'meanm'); + Yr = spm_smooth3(Yr,sx/2); + Y = cat_vol_resize(Yr,'dereduceV',redR); + else + % vrY = var(Y(:)); + mdY = mean(Y(:)); + Y = Y - mdY; + spm_smooth(Y,Y,sx); + % Y = Y / var(Y(:)) * vrY; + Y = Y + mdY; + end +end +%-------------------------------------------------------------------------- +function [sfiles,sfilesBIDS,BIDSsub,devdir] = checkBIDS(sfiles,BIDSdir) + +% * what about longitudinal +% * what about derivates subdir? + + sfilesBIDS = false(size(sfiles)); + BIDSsub = ''; + devdir = cell(size(sfiles)); + + %% if BIDS structure is detectected than use only the anat directory + for sfi = numel(sfiles):-1:1 + %% detect BIDS directories + sdirs = strsplit(sfiles{sfi},filesep); + if strcmpi(sdirs{end-1}(1:min(4,numel(sdirs{end-1}))),'anat'), ana = 1; else, ana = 0; end + if strcmpi(sdirs{end-2}(1:min(4,numel(sdirs{end-2}))),'ses-'), ses = 1; else, ses = 0; end + if ses==0 + if strcmpi(sdirs{end-2}(1:min(4,numel(sdirs{end-2}))),'sub-'), sub = 1; else, sub = 0; end + else + if strcmpi(sdirs{end-3}(1:min(4,numel(sdirs{end-3}))),'sub-'), sub = 1; else, sub = 0; end + end + dev = strmatch('derivatives',sdirs); + sdirs(dev:dev+1) = []; + + %% differentiate between cross and long cases + if ~ana, sfiles(sfi) = []; sfilesBIDS(sfi) = []; devdir(sfi) = []; continue; end + if ses && sub && ~ana, sfiles(sfi) = []; sfilesBIDS(sfi) = []; devdir(sfi) = []; continue; end + if ses && sub, BIDSsub = sdirs{end-3}; devi = numel(sdirs)-3; end % long + if ~ses && sub, BIDSsub = sdirs{end-2}; devi = numel(sdirs)-2; end % cross + sfilesBIDS(sfi) = sub; + + % setup result directory - without BIDS the default is used + devdir{sfi} = ''; + for di = 2:numel(sdirs)-1 + if sub && di == devi, devdir{sfi} = [devdir{sfi} filesep BIDSdir]; end % add some directories inbetween + devdir{sfi} = [devdir{sfi} filesep sdirs{di}]; + end + end +end +%-------------------------------------------------------------------------- +function [subjects,sname,sBIDS,devdir] = checksubjectfiles(sfiles,jobblacklist,jobseplist,BIDSdir) + [sfiles,BIDS,BIDSsub,devdir] = checkBIDS(sfiles,BIDSdir); + sBIDS = all(BIDS); + if any(BIDS) + sname = BIDSsub; + else + sname = ''; + end + + % check blacklist + blacklist = false(size(sfiles)); + if ~isempty(jobblacklist) + for sni = 1:numel(sfiles) + for ji = 1:numel(jobblacklist) + if any( cellfun( 'isempty' , strfind(sfiles, jobblacklist{ji} ))==0 ) + blacklist(sni) = 0; + end + end + end + end + + % check seplist + %{ + seplist = true(size(sfiles)); + if ~isempty(jobseplist) + for sni = 1:numel(sfiles) + seplist(sni) = any( cellfun( 'isempty' , strfind(sfiles, jobseplist ))==0 ); + end + end + %} + seplist = 0; + + % apply lists + subjects = sfiles(seplist | ~blacklist); + + % devdir + devdir = devdir(seplist | ~blacklist); +end +%-------------------------------------------------------------------------- +function job = get_defaults(job) +%cat_vol_savg_get_defaults. Default settings + + % update this field from char to cell + if isfield(job,'limits') + if isfield(job.limits,'seplist') + job.limits.seplist = strsplit(job.limits.seplist); + end + if isfield(job.limits,'blacklist') + job.limits.blacklist = strsplit(job.limits.blacklist); + end + if isfield(job.limits,'reqlist') + job.limits.reqlist = strsplit(job.limits.reqlist); + end + end + + % + def.subjects = {}; % datasets of each subject + + % == limits == + def.limits.filelim = inf; % testvar + def.limits.mcon = 0.1; % expert - define minimum contrast + def.limits.seplist = {'T1w','T2w','PD','FLAIR'}; % expert - T1w, T2w, PD, FLAIR + def.limits.blacklist = {}; % avoid specific strings in filename ... + def.limits.reqlist = {[filesep 'anat' filesep]}; % expert - requirements for bids? + def.limits.reslim = [2 2 8]; % expert - resolution limitation do not use images with lower resolution as [ deviation sliceres slicethickness ] + def.limits.sessionwise = 1; % in case of BIDS separate sessions + + % == opts for all methods == + def.opts.avgmethod = 2; % 1 - anyavg, 2 - spm/cat long, 3 - SPM-long, 4 - brudfors, 5 - all + def.opts.nproc = 0; % run multiple MATLAB processes + def.opts.sanlm = 0; % all + def.opts.trimming = 1; + def.opts.cleanup = 1; % remove temporary files + + % == anyavg / CAT + def.opts.setCOM = 1; % expert - anyAVG + CAT + + % == SPM exlcusive == + def.opts.SPMlongDef = 0; % 1 - use deformations (about week), 0 - no deformations + + % == anyavg exclusive setting == + def.opts.ref = { ... % anyAVG + fullfile(spm('dir'),'canonical','avg152T1.nii'); + fullfile(spm('dir'),'canonical','avg152T2.nii'); + fullfile(spm('dir'),'canonical','avg152PD.nii'); + }; + def.opts.coregmeth = 0; % 0 - auto, 1 - force realign, 2 - force coreg + def.opts.seg = ''; % expert - anyAVG: 'SPM', 'SPM+','CAT' + def.opts.res = 1; % expert - anyAVG? + def.opts.bias = 1; + def.opts.norm = 'cls'; + def.opts.debug = 1; + def.opts.regres = -1.5; % negative - job.opts.res * abs(regres); postive - 1, 1.5, 2, 3 mm + def.opts.regiter = 1; % factor for interations (higher = more accurate but slower) + + % == output settings == + %def.foutput = 1; + %def.outdir = ''; % extra result main directory + %def.usesubdirs = 0; % create same subdirecty structure from common directoy + %def.useBIDS = 0; % .. use only anat dir if ... database + def.output.prefix = ''; + def.output.BIDSdir = ['derivatives' filesep 'catavg']; + def.output.writeRescans = 0; + def.output.writeLabelmap = 0; + def.output.writeBrainmask = 0; + def.output.writeSDmap = 0; + def.output.cleanup = 1; + def.output.verb = 1; % all + def.output.copySingleFiles = 1; + def.CATDir = fullfile(spm('dir'),'toolbox','cat12'); + + % update job variable + job = cat_io_checkinopt(job,def); + + % inner field + job.opts.verb = job.output.verb; + + % add system dependent extension to CAT folder + if ispc + job.CATDir = [job.CATDir '.w32']; + elseif ismac + job.CATDir = [job.CATDir '.maci64']; + elseif isunix + job.CATDir = [job.CATDir '.glnx86']; + end + +end +%-------------------------------------------------------------------------- +%-------------------------------------------------------------------------- +function subject = prepareBIDSgz(subject,sBIDS,devdir) +% handle zipped BIDS + if all( sBIDS ) + for ri = numel(subject):-1:1 + [~,ff,ee] = spm_fileparts(subject{ri}); + if strcmp(ee,'.gz') + try + gunzip(subject{ri},devdir{ri}); + subject{ri} = fullfile( devdir{ri} , ff); %%#ok + catch + subject(ri) = []; + end + elseif ~strcmp(spm_fileparts(subject{ri}),devdir{ri}) + if ~exist(devdir{ri},'dir'), mkdir(devdir{ri}); end + copyfile(subject{ri},devdir{ri}); + subject{ri} = fullfile( devdir{ri} , [ff ee]); %%#ok + end + end + end +end +%-------------------------------------------------------------------------- +function [subAVGname,stime] = prepareAVGname(subject,si,sesi,seqi,sname,job) + % main directory of this subject + if numel(subject) > 1 + [~,px] = spm_str_manip( subject ,'C'); + else + [pp,ff,ee] = spm_fileparts(subject{1}); + runi = strfind(ff,'run-'); + if isempty(runi) + px.s = ff; + px.m = {''}; + px.e = ee; + else + rune = min(numel(ff) , runi + strfind(ff(runi:end),'_') - 1); + px.s = fullfile(pp,ff(1:runi+3)); + px.m = ff(runi+4:rune-1); + px.e = [ff(rune:end) ee]; + end + end + [~,ffs] = spm_fileparts(px.s); + [~ ,ffe] = spm_fileparts(px.e); + if isempty(ffs) && isempty(ffe), [~,mi] = min( cellfun('length',px.m) ); ffs = px.m{mi}; end + if isempty(sname) + subAVGname = ffs; + subAVGname = [ cat_io_strrep(subAVGname(1),{'_','.','-'},'') ... + subAVGname(2:end-1) cat_io_strrep(subAVGname(end),{'_','.','-'},'') ]; + else + subAVGname = sname; + end + + +% ############ +% USE OUTPUT DIR AND SUBDIR +% ############ + stime = cat_io_cmd(sprintf('Subject %4d - Session %3d/%3d - Sequence %d: %s', ... + si, numel(subject), sesi, seqi, subAVGname), 'b','',job.opts.verb); + if (job.opts.avgmethod == 1 && job.opts.verb>1) || (job.opts.avgmethod == 4 && job.opts.verb>1) + fprintf('\n'); + end + +end +%-------------------------------------------------------------------------- +function newname = update_outname(subjects,job,methodstr,seqi,subavg) + + if job.opts.res + resstr = sprintf('%0.2fmm_',job.opts.res); + else + resstr = '_'; + end + + orgname = spm_file(subjects{1},'prefix','avg_'); + newname = [methodstr resstr spm_file(subjects{1},'basename') '.nii']; + newname = cat_io_strrep( newname ,strcat('_',job.limits.seplist), ''); % remove weigthing (add again later) + newname = fullfile( spm_file(subjects{1},'path'),newname); + + if subavg % average over sessions + % replace ses-* by ses-avg in the path as well as the filename + newname = cat_io_strrep( newname ,'_run-avg', ''); % remove run-avg if exist + sesdir = strfind(spm_file(orgname,'path'),[filesep 'ses-']); + + if ~isempty(sesdir) + afterses = strfind(newname(sesdir(end)+1:end), filesep); + sesdir(2) = sesdir(1) + afterses(1); + sesname = newname(sesdir(1)+1: sesdir(2)-1); + newname = [newname(1:sesdir(1)), 'ses-avg', newname(sesdir(2):end)]; + newname = strrep(newname,['_' sesname],'_ses-avg'); + else + % nothing to do as the we also use the average + end + + else % average within session + % If the rescans were defined by the run tag within the filename + % otherwise we add _run-avg as tag. + runtag = strfind(spm_file(newname,'basename'),'_run-'); + + if ~isempty(runtag) + runtag = numel(spm_file(newname,'basename')) + 1 + runtag; + afterrun = strfind(newname(runtag(end)+1:end), '_'); + runtag(2) = runtag(1) + afterrun(1); + runname = newname(runtag(1)+1: runtag(2)-1); + newname = strrep(newname,['_' runname],'_run-avg'); + else + newname = spm_file(newname,'suffix','_run-avg'); + end + end + newname = spm_file( newname ,'suffix', ['_' job.limits.seplist{seqi} ]); + + % create dir + if subavg + pp = spm_fileparts(newname); + if ~exist(pp,'dir'), mkdir(pp); end + end + + % move file + if exist(orgname,'file') + movefile(orgname,newname); + end +end +%-------------------------------------------------------------------------- +function [subjects,sBIDS,sname,devdir] = getFiles(job) +%% search files in case of input directories + subjects = {}; sBIDS = []; sname = {}; devdir = {}; subi = 0; + for si = 1:numel( job.subjects ) + for fi = 1:numel( job.subjects{si} ) + FN = fieldnames( job.subjects{si} ); + for fni = 1:numel(FN) + if strcmp(FN{fni},'subjectdirs') || strcmp(FN{fni},'BIDSsubjects') + if ~isempty(job.subjects{si}.(FN{fni})) + for di = 1:numel( job.subjects{si}.(FN{fni}) ) + subi = subi + 1; + if exist( job.subjects{si}.(FN{fni}){di} ,'dir') + % run for each sequence + for seqi = 1:numel(job.limits.seplist) + + % find sessions + if job.limits.sessionwise + sesdir = cat_vol_findfiles( job.subjects{si}.(FN{fni}){di} , 'ses-*' , struct('dirs',1,'depth',1)); + sesdir = spm_file(sesdir,'basename'); + else + sesdir = {''}; + end + + % run for each session + for sesi = 1:numel(sesdir) + + %if seqi > numel(job.limits.seplist) && ~isempty(sfiles), break; end + + anyAVGfiles = cat_vol_findfiles( fullfile(job.subjects{si}.(FN{fni}){di},sesdir{sesi}) , ['*' job.output.prefix '*' job.limits.seplist{seqi} '.nii']); + sfiles = cat_vol_findfiles( fullfile(job.subjects{si}.(FN{fni}){di},sesdir{sesi}) , ['*' job.limits.seplist{seqi} '.nii']); + sfiles = [sfiles; cat_vol_findfiles( fullfile(job.subjects{si}.(FN{fni}){di},sesdir{sesi}) , ['*' job.limits.seplist{seqi} '.nii.gz'])]; %#ok + sfiles = setdiff(sfiles,anyAVGfiles); + + if isfield(job.limits,'blacklist') && ~isempty(job.limits.blacklist) + sfiles( cat_io_contains( sfiles , job.limits.blacklist ) ) = []; + end + + if isfield(job.limits,'reqlist') && ~isempty(job.limits.reqlist) + sfiles( ~cat_io_contains( sfiles , job.limits.reqlist ) ) = []; + end + + % only run (=add to list) if required + [subjects{subi}{seqi}{sesi}, sname{subi}, sBIDS(subi), devdir{subi}{seqi}{sesi}] = ... ,sesname{si}{sesi} + checksubjectfiles(sfiles,job.limits.blacklist,job.limits.seplist,job.output.BIDSdir); %#ok + end + end + end + end + end + elseif strcmp(FN{fni},'subject') % 'subjects') + subi = subi + 1; + if iscell( job.subjects{si}.(FN{fni}) ) + for sesi = 1:numel( job.subjects{si}.(FN{fni}) ) + for seqi = 1:numel(job.limits.seplist) + %% + if isfield( job.subjects{si}.(FN{fni}){sesi} , 'session') + sfiles = job.subjects{si}.(FN{fni}){sesi}.session; + else + anyAVGfiles = cat_vol_findfiles( job.subjects{si}.(FN{fni}){sesi}.sessiondirs{sesi} , ['*' job.output.prefix '*' job.limits.seplist{seqi} '.nii']); + sfiles = cat_vol_findfiles( job.subjects{si}.(FN{fni}){sesi}.sessiondirs{sesi} , ['*' job.limits.seplist{seqi} '.nii']); + sfiles = [sfiles; cat_vol_findfiles( job.subjects{si}.(FN{fni}){sesi}.sessiondirs{sesi} , ['*' job.limits.seplist{seqi} '.nii.gz'])]; %#ok + sfiles = setdiff(sfiles,anyAVGfiles); + + end + + for sii = numel(sfiles):-1:1 + [pp,ff,ee] = spm_fileparts(sfiles{sii}); + sfiles{sii} = fullfile(pp,[ff ee]); + end + + if isfield(job.limits,'blacklist') && ~isempty(job.limits.blacklist) + sfiles( cat_io_contains( sfiles , job.limits.blacklist ) ) = []; + end + + if isfield(job.limits,'reqlist') && ~isempty(job.limits.reqlist) + sfiles( ~cat_io_contains( sfiles , job.limits.reqlist ) ) = []; + end + + sfiles( ~cat_io_contains( sfiles , job.limits.seplist{seqi}) ) = []; + [subjects{subi}{seqi}{sesi}, sname{subi}, sBIDS(subi), devdir{subi}{seqi}{sesi}] = ... + checksubjectfiles(sfiles, job.limits.blacklist, job.limits.seplist, job.output.BIDSdir); %#ok + end + end + else + sesi = 1; + for seqi = 1:numel(job.limits.seplist) + sfiles = job.subjects{si}.(FN{fni}); + for sii = numel(sfiles):-1:1 + [pp,ff,ee] = spm_fileparts(sfiles{sii}); + sfiles{sii} = fullfile(pp,[ff ee]); + end + + if isfield(job.limits,'blacklist') && ~isempty(job.limits.blacklist) + sfiles( cat_io_contains( sfiles , job.limits.blacklist ) ) = []; + end + + if isfield(job.limits,'reqlist') && ~isempty(job.limits.reqlist) + sfiles( ~cat_io_contains( sfiles , job.limits.reqlist ) ) = []; + end + + sfiles( ~cat_io_contains( sfiles , job.limits.seplist{seqi}) ) = []; + [subjects{si}{seqi}{sesi}, sname{si}, sBIDS(si), devdir{si}{seqi}{sesi}] = ... + checksubjectfiles(sfiles, job.limits.blacklist, job.limits.seplist, job.output.BIDSdir); %#ok + end + end + else + subi = subi + 1; + sesi = 1; + for seqi = 1:numel(job.limits.seplist) + sfiles = job.subjects{si}.session; + + if isfield(job.limits,'blacklist') && ~isempty(job.limits.blacklist) + sfiles( cat_io_contains( sfiles , job.limits.blacklist ) ) = []; + end + + if isfield(job.limits,'reqlist') && ~isempty(job.limits.reqlist) + sfiles( ~cat_io_contains( sfiles , job.limits.reqlist ) ) = []; + end + + sfiles( ~cat_io_contains( sfiles , job.limits.seplist{seqi}) ) = []; + [subjects{subi}{seqi}{sesi}, sname{subi}, sBIDS(subi), devdir{subi}{seqi}{sesi}] = ... + checksubjectfiles(sfiles, job.limits.blacklist, job.limits.seplist, job.output.BIDSdir); %#ok + end + end + end + end + end + + % remove empty run and subjects but not sessions! + for si = numel( subjects ):-1:1 + for seqi = numel( subjects{si} ):-1:1 + for runi = numel( subjects{si}{seqi} ):-1:1 + if isempty(subjects{si}{seqi}{runi}) + devdir{si}{seqi}(runi) = []; + subjects{si}{seqi}(runi) = []; + end + end + end + if isempty(subjects{si}) + devdir(si) = []; + subjects(si) = []; + end + end + + % limit number of sessions and runs for quick tests + if job.limits.filelim > 0 + for si = 1:numel( subjects ) + for seqi = 1:numel( subjects{si} ) + % limit reruns + for sesi = 1:numel( subjects{si}{seqi} ) + if numel( subjects{si}{seqi}{sesi} ) > job.limits.filelim + devdir{si}{seqi}{sesi}(job.limits.filelim+1:end) = []; %#ok + subjects{si}{seqi}{sesi}(job.limits.filelim+1:end) = []; %#ok + end + end + % limit sessions + if numel( subjects{si}{seqi} ) > job.limits.filelim + devdir{si}{seqi}(job.limits.filelim+1:end) = []; %#ok + subjects{si}{seqi}(job.limits.filelim+1:end) = []; %#ok + end + end + end + end + +end +%-------------------------------------------------------------------------- +function denoise(subject,job) +%% denoising for all methods ? +% -------------------------------------------------------------------- + stime = cat_io_cmd(' SANLM Denoising','g7','',job.opts.verb>1); + for vi = 1:numel(subject) + % full denoising + job.NCstr = -1 / 2^numel(subject); + cat_vol_sanlm(struct('data',subject{vi},'verb',0,'prefix','','NCstr',job.NCstr,'outlier',0)); + end + if job.opts.verb>1, fprintf('%5.0fs\n',etime(clock,stime)); end +end +%-------------------------------------------------------------------------- +function [catlong,outcatra] = catlong(subject,methodstr,job,seqi,subavg) +%% CAT longitudinal averaging function (rigid) +% -------------------------------------------------------------------- +% cat_vol_series_align +% CAT longitudinal processing pipeline with setting of COM and final +% timming to reduce useless air around the head. +% -------------------------------------------------------------------- + if ~exist('subavg','var'), subavg = 0; end + + stime = cat_io_cmd(sprintf(' CAT Longitudinal Averaging'),'g9','',isinf(job.opts.avgmethod)); + + % matlabbatch + matlabbatch{1}.spm.tools.cat.tools.series.bparam = 1e6; % 1e4 created biased high-res images + matlabbatch{1}.spm.tools.cat.tools.series.use_brainmask = 1; + matlabbatch{1}.spm.tools.cat.tools.series.reduce = job.opts.reduce; % trimming + matlabbatch{1}.spm.tools.cat.tools.series.setCOM = job.opts.setCOM; % COM + matlabbatch{1}.spm.tools.cat.tools.series.noise = 0; % not here + matlabbatch{1}.spm.tools.cat.tools.series.write_avg = 1; + matlabbatch{1}.spm.tools.cat.tools.series.sharpen = job.opts.sharpen; + matlabbatch{1}.spm.tools.cat.tools.series.write_rimg = 1 - job.output.writeRescans; + matlabbatch{1}.spm.tools.cat.tools.series.data = subject; + matlabbatch{1}.spm.tools.cat.tools.series.isores = job.opts.res; + if job.opts.verb > 2 + spm_jobman('run',matlabbatch); + else + evalc('spm_jobman(''run'',matlabbatch)'); + end + clear matlabbatch; + + % handle avg file + catlong = update_outname(subject,job,methodstr,seqi,subavg); + + % handle rescans + catra = cell(numel(subject),1); outcatra = catra; + if job.output.writeRescans + for rsi = 1:numel(subject) + catra{rsi} = spm_file(subject{rsi},'prefix','r'); + outcatra{rsi} = spm_file(subject{rsi},'prefix',[methodstr 'r']); + if exist(catra{rsi},'file') + movefile(catra{rsi},outcatra{rsi}); + end + end + end + + if isinf(job.opts.avgmethod), fprintf('%5.0fs\n',etime(clock,stime)); end %#ok<*CLOCK,*DETIM> +end +%-------------------------------------------------------------------------- +function spmlong = spmlong(subject,methodstr,job,seqi,subavg) +%% SPM longitudinal averaging function (rigid) +% -------------------------------------------------------------------- +% spm_series_align +% +% -------------------------------------------------------------------- + if ~exist('subavg','var'), subavg = 0; end + + stime = cat_io_cmd(sprintf(' SPM Longitudinal Averaging'),'g9','',isinf(job.opts.avgmethod)); + + matlabbatch{1}.spm.tools.longit.series.vols = subject; + matlabbatch{1}.spm.tools.longit.series.times = zeros(1,numel(subject)); + matlabbatch{1}.spm.tools.longit.series.noise = NaN; + if job.opts.SPMlongDef %deform within week + matlabbatch{1}.spm.tools.longit.series.times = (0:numel(subject)-1)/52; + matlabbatch{1}.spm.tools.longit.series.wparam = [0 0 100 25 100]; + else + matlabbatch{1}.spm.tools.longit.series.wparam = [Inf Inf Inf Inf Inf]; + end + matlabbatch{1}.spm.tools.longit.series.bparam = 1e4; + matlabbatch{1}.spm.tools.longit.series.write_avg = 1; + matlabbatch{1}.spm.tools.longit.series.write_jac = 0; + matlabbatch{1}.spm.tools.longit.series.write_div = 0; + matlabbatch{1}.spm.tools.longit.series.write_def = 0; + if job.opts.verb > 2 + spm_jobman('run',matlabbatch); + else + evalc('spm_jobman(''run'',matlabbatch)'); + end + clear matlabbatch; + + % handle average + spmlong = char( update_outname(subject,job,methodstr,seqi,subavg) ); + + % handle rescans ... these files are not created and it is not our goal to do so ... + if job.output.writeRescans + cat_io_cprintf('warn','Warning: The standard SPM longitudinal processing pipeline is not pepared to output realigned images yet.\n'); + end + + if isinf(job.opts.avgmethod), fprintf('%5.0fs\n',etime(clock,stime)); end +end +%-------------------------------------------------------------------------- +function brudfors = brudfors(subject,methodstr,job,seqi,subavg) +%% Brudfors averaging function (rigid) +% -------------------------------------------------------------------- +% cat_vol_series_align +% -------------------------------------------------------------------- + if ~exist('subavg','var'), subavg = 0; end + + stime = cat_io_cmd(sprintf(' Brudfors Superres'),'g9','',isinf(job.opts.avgmethod)); + + try + if job.opts.verb>2 + spm_superres( {char( subject )},struct('Verbose',job.opts.verb>2,'VoxSize',job.opts.res)); + else + evalc('spm_superres( {char( subjects{si})},struct(''Verbose'',job.opts.verb>2,''VoxSize'',job.opts.res));'); + end + catch e + fprintf('\n'); + cat_io_cprintf('err',sprintf('Memory error in Brudfors superres. Use default resolution: \n%s','')); + if job.opts.verb>2 + spm_superres( {char( subject )},struct('Verbose',job.opts.verb>2)); + else + evalc('spm_superres( {char( subjects{si})},struct(''Verbose'',job.opts.verb>2,''VoxSize'',job.opts.res));'); + end + fprintf('\n'); + cat_io_cmd(' ','g5','',job.opts.verb>2); + end + + brudfors = char( update_outname(pm_file(subject{1},'prefix','y'),job,methodstr,seqi,subavg) ); + + if isinf(job.opts.avgmethod), fprintf('%5.0fs\n',etime(clock,stime)); end +end +%-------------------------------------------------------------------------- +function [V,vx_vol,use,stime] = removeLowRes(subject,job) + % load header + V = spm_vol( char( subject )); + use = true(1,numel(V)); + + % first we have to remove images with inproper voxel size, + % e.g., 2D (<5 slices) or with to low resolution + vx_vol = nan(numel(V),3); + vx_dim = nan(numel(V),3); + for vi = 1:numel(V) + try %#ok + vx_vol(vi,:) = sqrt(sum(V(vi).mat(1:3,1:3).^2)); + vx_dim(vi,:) = V(vi).dim; + end + end + mdvx = cat_stat_nanmedian(vx_vol(:)) + cat_stat_nanstd(vx_vol(:)) * job.limits.reslim(1); + for vi = 1:numel(V) + use(vi) = prod(vx_vol(vi,:)) <= mdvx^3 & ... % remove due to deviation + min(vx_vol(vi,:)) <= job.limits.reslim(2) & ... % remove due to slice resolution + max(vx_vol(vi,:)) <= job.limits.reslim(3) & ... % remove due to slice thickness + min(vx_dim(vi,:)) >= 4; % remove due to low number of slices + end + % second we want to avoid to many files + [vx_vols,vx_voli] = sortrows(prod(vx_vol,2)); + useni = max([1 find( vx_vols' <= vx_vols( min( numel(vx_vols) ,job.limits.filelim) ) + 0.01,numel(V),'last')]); % + 0.01 = round + usen = false(size(use)); usen( vx_voli( 1:useni ) ) = true; + use = use & usen; + if job.opts.verb>1 + cat_io_cprintf('g7',sprintf(' Select %d of %d scans for evaluation.\n',sum(use),numel(V))); + end + stime = clock; + clear usen useni vx_vols vx_voli mdvx; + +end +%-------------------------------------------------------------------------- +function [Vtbc,ihistcorr,stime] = quickBiascCorrection(V,job,stime) +%% Quick soft/smooth (temporary) bias correction + % ------------------------------------------------------------------ + % Inhomogeneities can trouble the registration and a simple fast + % (temporary) correction can reduce problems. Keeping the field very + % smooth even support permanent use. Altough a simple brain masking + % would be possible too this would limit the permanent use. + % ------------------------------------------------------------------ + ihists = zeros(100,numel(V)); + bcstr = {' Tempoary quick & soft bias-correction',' Quick & soft bias-correction'}; + Vtbc = V; %Vtbf = V; + if job.opts.bias + stime = cat_io_cmd(bcstr{job.opts.bias},'g7','',job.opts.verb>1); + + for vi = 1:numel(V) + if vi==1 + if job.opts.verb>2, fprintf('\n'); end + stime2 = cat_io_cmd(sprintf(' Scan %d',vi),'g5','',job.opts.verb>2); + else + stime2 = cat_io_cmd(sprintf(' Scan %d',vi),'g5','',job.opts.verb>2,stime2); + end + + Vtbc(vi).fname = spm_file(Vtbc(vi).fname,'prefix','bc'); + + if ~exist(Vtbc(vi).fname,'file') + + %% load image and estimate some global threshold + Y = single( spm_read_vols(V(vi)) ); + vx_vol = sqrt(sum(V(vi).mat(1:3,1:3).^2)); + [~,th] = cat_stat_histth(Y(Y(:)~=0),[99.99 96]); + th0 = cat_stat_nanmedian(Y(Y(:)~=0 & Y(:)0.3 & Ygr(:)<5 & Ygr(:)>0.01 & Ygr(:)~=0),1); + mth = cat_stat_kmeans(Ymr(Ymr(:)>0.1 & Ymr(:)<1.5 & Ygr(:)mean(mth(1)) & Ygmean(mth(1)) & (Ym ./ Yt)0,'o',2); + Yt = cat_vol_smooth3X(cat_vol_approx(Yt)); + Ym = max(0,real( (Y - th(1)) ./ abs(diff(th)))); clear Y; + Ym = Ym ./ Yt; + Ym = Ym ./ cat_stat_nanmedian(Ym(Yg(:).5)); % normalize WM + if job.opts.bias > 1 % permanent + Ym = min(3,Ym); + else + Ym = min(3,log10( min(3,Ym) + 1 ) * 3); + end +% ############# + + % brain masking? + % eg. remove outer ring? + + % save image + Vtbc(vi).fname = spm_file(Vtbc(vi).fname,'prefix','bc'); + Vtbc(vi).dt(1) = 16; + Vtbc(vi) = spm_write_vol(Vtbc(vi),Ym * abs(diff(th)/2)); + % save bias field + %Vtbf(vi).fname = spm_file(Vtbf(vi).fname,'prefix','bf'); + %spm_write_vol(Vtbf(vi),Yt * abs(diff(th)/2)); + + else + Ym = single( spm_read_vols( spm_vol( Vtbc(vi).fname) )); + Yg = cat_vol_grad(Ym) ./ Ym; + end + + ihists(:,vi) = hist(Ym(Ym(:)>0.1 & Ym(:)<2 & Yg(:)<0.5),0.11:0.01:1.1); + + + clear Ym Yt Yd Yg vx_vol th gth mth; + end + + ihistcorr = corrcoef(ihists); + + else + ihistcorr = 0; + end +end +%-------------------------------------------------------------------------- +function [Vmni0,Vavg0,cormat,stime] = createAVG0(V,Vtbc,job,regres,pps,subAVGname,stime) +%% Affine registration to TPM to get MNI orientation and first registration + % ------------------------------------------------------------------ + % 4 mm are ok but 2 is better + % ------------------------------------------------------------------ + Affscale = zeros(numel(Vtbc),12); Affines = cell(1,numel(Vtbc)); Rigids = Affines; cormat = Affines; + Vmni0ll = zeros(1,numel(Vtbc)); + Vmni0 = Vtbc; + lfs = sort([ 16 8 4 2],'descend'); + liter = [ 80 40 20 10 10 10] / job.opts.regiter; + lfsi = max(3,find(lfs >= regres,1,'last')); + stime = cat_io_cmd(sprintf(' %0.2f mm registration of MNI templates',lfs(lfsi)),'g7','',job.opts.verb>1,stime); + + Vref = spm_vol( char( job.opts.ref ) ); + tpm = spm_load_priors8(fullfile(spm('dir'),'TPM','TPM.nii')); + + for vi = 1:numel(Vmni0) + if vi==1 + if job.opts.verb>2, fprintf('\n'); end + stime2 = cat_io_cmd(sprintf(' Scan %d',vi),'g5','',job.opts.verb>2); + else + stime2 = cat_io_cmd(sprintf(' Scan %d',vi),'g5','',job.opts.verb>2,stime2); + end + warning('OFF','MATLAB:RandStream:ActivatingLegacyGenerators'); + llo = -inf; + + % reset to center of mass (COM) if the AC is outside the image + mati = spm_imatrix(V(vi).mat); + if job.opts.setCOM || any( mati(1:3).*mati(7:9) <= 0 ) || any( mati(1:3).*mati(7:9) >= V(vi).dim ) + evalc('Affine = cat_vol_set_com(V(vi));'); + Affine = inv(Affine); + else + Affine = eye(4); + end + + for li = 1:lfsi + [Affinet,ll] = spm_maff8(V(vi), max( 1, lfs(li) ), lfs(li), tpm, Affine, 'subj' , liter(li)); + if ll(1)>llo, Affine = Affinet; llo = ll(1); end + clear Affinet ll; + end + warning('ON','MATLAB:RandStream:ActivatingLegacyGenerators'); + Vmni0ll(vi) = llo; + Affines{vi} = Affine; + cormat{vi} = [0 0 0 0 0 0 1 1 1 0 0 0] + [1 1 1 1 1 1 0 0 0 0 0 0] .* spm_imatrix(Affine); + Rigids{vi} = spm_matrix(cormat{vi}); + cormat{vi} = cormat{vi}(1:6); + Affscale(vi,:) = [0 0 0 0 0 0 1 1 1 0 0 0] .* spm_imatrix(Affine); + % Vmni0(vi).mat = Rigids{vi} * Vmni0(vi).mat; + end + + % create first average in MNI space with adopted resolution + if job.opts.verb>2, stime2 = cat_io_cmd(' Averaging ','g5','',job.opts.verb>2,stime2); end + Vavg0 = Vref(1); Vavg0.fname = fullfile(pps,[job.output.prefix 'avg0_' subAVGname '.nii']); + Vavg0.pinfo(1) = 1; Vavg0.dt(1) = 16; spm_write_vol(Vavg0,zeros(Vavg0.dim)); + matlabbatch{1}.spm.tools.cat.tools.resize.data = {Vavg0.fname}; + matlabbatch{1}.spm.tools.cat.tools.resize.restype.res = max(1,min(job.opts.res * 1.5,regres)); + matlabbatch{1}.spm.tools.cat.tools.resize.interp = 1; + matlabbatch{1}.spm.tools.cat.tools.resize.prefix = ''; + matlabbatch{1}.spm.tools.cat.tools.resize.outdir = {''}; + evalc('spm_jobman(''run'',matlabbatch)'); clear matlabbatch; + % some bug in 28&me I don't understrand + Vmni0 = spm_vol(char({Vmni0(:).fname})); + for vi = 1:numel(Vmni0), Vmni0(vi).mat = Rigids{vi} * Vmni0(vi).mat; end + %for vi = usei, Vmni0(vi).mat = Affines{vi} * Vmni0(vi).mat; end + % create 1st average + evalc('spm_reslice( [spm_vol(Vavg0.fname);Vmni0 ] , struct(''which'',0,''mean'',1,''mask'',0,''interp'',1) )'); + movefile( spm_file( Vavg0.fname ,'prefix','mean'), Vavg0.fname ); + Vavg0 = spm_vol(Vavg0.fname); + if job.opts.verb>2, cat_io_cmd(' ','g5','',job.opts.verb>2,stime2); end %fprintf('%5.0fs\n',etime(clock,stime)); +end +%-------------------------------------------------------------------------- +function [Vmni1,stime] = correg2AVG0(V,Vtbc,Vmni0,Vavg0,cormat,job,regres,ihistcorr,stime) %#ok + +%% do realignment / coregistration to the first average + realginstr = {'coregistration','registration'}; + realign = ( job.opts.coregmeth==0 && exist('ihistcorr','var') && sum(ihistcorr(:)) > 0.95) || (job.opts.coregmeth==1); + +% for ii=1:2 + stime = cat_io_cmd(sprintf(' %0.2f mm %s to first average',... + min(job.opts.res*1.5,regres),realginstr{realign+1}),'g7','',job.opts.verb>1,stime); + Vmni1 = V; + cormats = cormat; + for vi = 1:numel(V) + Vmni1(vi) = spm_vol(Vmni1(vi).fname); + Vmni1(vi).mat = Vmni0(vi).mat; %Vavg0.mat; % + Vtbc(vi) = spm_vol(Vtbc(vi).fname); + Vtbc(vi).mat = Vmni0(vi).mat; + + pp = spm_fileparts(V(vi).fname); cd(pp) + if vi==1 + if job.opts.verb>2, fprintf('\n'); end + stime2 = cat_io_cmd(sprintf(' Scan %d',vi),'g5','',job.opts.verb>2); + else + stime2 = cat_io_cmd(sprintf(' Scan %d',vi),'g5','',job.opts.verb>2,stime2); + end + + % call corregistration + %vstr = {'Vmni0(vi)','Vtbc(vi)'}; + clear Vmat; + vx_vol = sqrt(sum(V(vi).mat(1:3,1:3).^2)); + if realign %&& ~(job.opts.setCOM || any( mati(1:3).*mati(7:9) <= 0 ) || any( mati(1:3).*mati(7:9) >= V(vi).dim ) ) + try + evalc( sprintf(['Vmat = spm_realign( [Vavg0 , Vtbc(vi)] , ' ... + 'struct( ''sep'' , %g , ''fwhm'' , %g, ''graphics'' , 0 ) );'],... + max(min(vx_vol(:)),min(job.opts.res,regres)), ... + max(0.5,min(1,min(job.opts.res,regres*2)))*2 )); + Vmni1(vi) = Vmat(2); + catch + fprintf('.'); + evalc( sprintf(['cormats{vi} = spm_coreg( Vavg0 , Vtbc(vi) , ' ... + 'struct( ''sep'' , %g , ''fwhm'' , [7 7] , ''params'' , ' ... + 'cormat{vi} , ''graphics'' , %d ) );'],... + max(min(vx_vol(:)),min(job.opts.res*1.5,regres*1.5)), ... + job.opts.verb>2) ); % #### use final res? ### + if any( isnan( cormats{vi}(:) ) ) + Vmni1(vi).mat = spm_matrix(cormat{vi}) * eval(sprintf('%s.mat',vstr{1+exist('Vtbc','var')})); %V(vi).mat; + %use(vi) = false; + else + Vmni1(vi).mat = spm_matrix(cormats{vi}) * eval(sprintf('%s.mat',vstr{1+exist('Vtbc','var')})); %V(vi).mat; + end + end + else + evalc( sprintf(['cormats{vi} = spm_coreg( Vavg0 , Vtbc(vi) , ' ... + 'struct( ''sep'' , [8 4 %s] , ''fwhm'' , [7 7] , ''params'' , ' ... + 'cormat{vi} , ''graphics'' , %d , ' ... + '''tol'', [%g %g %g %g %g %g]', ... + ') );'],... + max(min(vx_vol(:)),min(job.opts.res*1.5,regres)), ... + job.opts.verb>2,[0.02 0.02 0.02 0.001 0.001 0.001] * regres )); % #### use final res? ### + if any( isnan( cormats{vi}(:) ) ) + Vmni1(vi).mat = spm_matrix(cormat{vi}) * eval(sprintf('%s.mat','Vtbc(vi)')); %V(vi).mat; + %use(vi) = false; + else + Vmni1(vi).mat = spm_matrix(cormats{vi}) * eval(sprintf('%s.mat','Vtbc(vi)')); %V(vi).mat; + end + end + + end +end +%-------------------------------------------------------------------------- +function [Vmni2,Vavg1,stime] = reslice(V,Vmni1,job,pps,subAVGname,stime) +%% create an new MNI like subject template space + % ------------------------------------------------------------------ + % Reslicing has to be done by spline to get sharp images at full or super-resolution. + stime = cat_io_cmd(sprintf(' %0.2f mm reslicing & outlier detection',job.opts.res),'g7','',job.opts.verb>1,stime); + + Vavg1 = V(1); + Vavg1.fname = fullfile(pps,[job.output.prefix 'avg1_' subAVGname '.nii']); %sprintf('avghri_n%d.nii',sum(use))); + + resjob.data{1} = job.opts.ref{1}; + resjob.verb = 0; + resjob.restype.res = job.opts.res; + resjob.prefix = [job.output.prefix 'r']; + for i=1:10 + try + cat_vol_resize(resjob); + movefile(spm_file(resjob.data{1},'prefix',[job.output.prefix 'r']),Vavg1.fname); % bug where the file is not existing? + Vavg1 = spm_vol(Vavg1.fname); Y = spm_read_vols(Vavg1); + Vavg1.dt(1) = 16; spm_write_vol(Vavg1,zeros(size(Y))); + break; + catch + pause(rand(1)*5); + end + end + if isfield(Vmni1,'dat') && ~isfield(Vavg1,'dat') + Vavg1.dat = spm_read_vols(spm_vol(Vlravg.fname)); + end + %if 1 + evalc('spm_reslice( [Vavg1;Vmni1] , struct(''which'',1,''mean'',1,''mask'',0,''interp'',5,''prefix'',[job.output.prefix ''r'']) );'); + %else + % evalc('spm_reslice( [Vavg1;Vtbc] , struct(''which'',1,''mean'',1,''mask'',0,''interp'',5,''prefix'',[job.output.prefix ''r'']) );'); + %end + movefile(spm_file(Vavg1.fname,'prefix','mean'),Vavg1.fname); + Vmni2 = Vmni1; for vri = 1:numel(Vmni1); Vmni2(vri).fname = spm_file( Vmni1(vri).fname , 'prefix', 'r'); end +end +%-------------------------------------------------------------------------- +function use2 = checkdata(Vmni1,job,stime) + + %% estimate correllation between scans +% ... need a flag for rescan or some control parameter ? + use = 1:numel(Vmni1); + + if numel(Vmni1) > 1 + stime = cat_io_cmd(' Detect outliers','g7','',job.opts.verb>1,stime); + cjob = struct('data_vol',{{ ( spm_file( char({ Vmni1(use).fname }') ,'prefix',[job.output.prefix 'r'])) }} ,'gap',3,'c',[],'data_xml',{{}},'verb',0); %#ok + txt = evalc('ccov = cat_stat_check_cov_old(cjob);'); + ccov.median = cat_stat_nanmedian( ccov.covmat( reshape( ones(sum(use)) - eye(sum(use)) , 1 , sum(use)^2 )>0 ) ); + ccov.mean = cat_stat_nanmean( ccov.covmat( reshape( ones(sum(use)) - eye(sum(use)) , 1 , sum(use)^2 )>0 ) ); + ccov.std = cat_stat_nanstd( ccov.covmat( reshape( ones(sum(use)) - eye(sum(use)) , 1 , sum(use)^2 )>0 ) ); + for ci = use + cidata = ccov.covmat(ci,setdiff(1:sum(use),ci)); + cirange = cidata > ( cat_stat_nanmedian( cidata ) - cat_stat_nanstd( cidata ) ); + ccov.smedian(ci) = cat_stat_nanmedian( cidata ( cirange )); + ccov.sstd(ci) = cat_stat_nanstd( cidata ( cirange )); + if any( isnan( ccov.smedian(ci) )) || any(isnan( ccov.sstd(ci) )) + ccov.smedian(ci) = cidata; + ccov.sstd(ci) = 0; + end + end + + %% + use2 = use; use2(use) = use2(use) & ( ccov.cov' > ( cat_stat_nanmedian(ccov.smedian) - max(0.05,min(0.2, ccov.std/2 )) ) ); + if sum(use2)==0 + cat_io_cprintf('err','\n Failed correg selection use res selection.\n'); + cat_io_cmd(' ',' ','',job.opts.verb>1); + use2 = use; + end +% ############## NOT WORKING ############# + if 0 %any(use2 ~= use) + evalc(['spm_reslice( spm_file( char({ Vmni2( use2 ).fname }'') ,''prefix'',[job.output.prefix ''r'']) , ' ... + 'struct(''which'',0,''mean'',1,''mask'',0,''interp'',5) )']); + movefile(spm_file( Vmni1(find(use2>0,1,'first')).fname ,'prefix',['mean' job.output.prefix 'r']), Vavg1.fname); + end + else + use2 = use; + end +end +%-------------------------------------------------------------------------- +function Ycls = segment(Vavg1,job) +%% Tissue segmenation: + % Estiamtion of a tissue segmentation to apply bias correction and further + % image evaluate (e.g., tissue contrast and weighting) in the next steps. + ncls = 6 * (1-strcmp(job.opts.norm,'none')); % 0, 3 or 6 + switch job.opts.seg + case {'SPM','SPM+'} + % Unified segmenation: + stime = cat_io_cmd(' Run SPM segmentation of high-res average','g7','',job.opts.verb>1,stime); + + lkp = [ 1 1 2 3 4 2]; + matlabbatch{1}.spm.spatial.preproc.channel.vols = {Vavg1.fname}; + matlabbatch{1}.spm.spatial.preproc.channel.biasreg = 0.001; + matlabbatch{1}.spm.spatial.preproc.channel.biasfwhm = job.opts.bias; + matlabbatch{1}.spm.spatial.preproc.channel.write = [0 1]; + for ci = 1:6 + matlabbatch{1}.spm.spatial.preproc.tissue(ci).tpm = {fullfile(spm('dir'),'tpm',sprintf('TPM.nii,%d',ci))}; + matlabbatch{1}.spm.spatial.preproc.tissue(ci).ngaus = lkp(ci); + matlabbatch{1}.spm.spatial.preproc.tissue(ci).native = [ci<=ncls 0]; + matlabbatch{1}.spm.spatial.preproc.tissue(ci).warped = [0 0]; + end + matlabbatch{1}.spm.spatial.preproc.warp.mrf = 1; + matlabbatch{1}.spm.spatial.preproc.warp.cleanup = 1; + matlabbatch{1}.spm.spatial.preproc.warp.reg = [0 0.001 0.5 0.05 0.2]; + matlabbatch{1}.spm.spatial.preproc.warp.affreg = 'mni'; %'subj'; % use what was good before + matlabbatch{1}.spm.spatial.preproc.warp.fwhm = 0; + matlabbatch{1}.spm.spatial.preproc.warp.samp = 4.5; + matlabbatch{1}.spm.spatial.preproc.warp.write = [1 0] * (ncls>0) * strcmp(job.opts.seg,'SPM+'); + matlabbatch{1}.spm.spatial.preproc.warp.vox = NaN; + matlabbatch{1}.spm.spatial.preproc.warp.bb = [NaN NaN NaN; NaN NaN NaN]; + case 'CAT' + stime = cat_io_cmd(' Run CAT segmentation of high-res average','g7','',job.opts.verb>1,stime); +% ############ not preparted ################ + case {'none',''} + matlabbatch = {}; + otherwise + error('cat_vol_savg:unkownSegmentation','Unknown segmentation case ""%s"".',job.opts.seg); + end + if ~isempty(matlabbatch) + evalc('spm_jobman(''run'',matlabbatch)'); + end + + + %% load segments + switch job.opts.seg + case 'SPM+' % did not work well + [ppa,ffa] = spm_fileparts( Vavg1.fname ); + + % load images + Vy = nifti(fullfile( ppa, sprintf('iy_%s.nii',ffa))); + Yy = Vy.dat; + Ysrc = single(spm_read_vols(spm_vol( spm_file( Vavg1.fname ,'prefix','m')))); + Ycls = zeros([Vavg1.dim ncls],'uint8'); + for ci = 1:ncls + Vcls = spm_vol( spm_file( Vavg1.fname ,'prefix',sprintf('c%d',ci)) ); + Ycls(:,:,:,ci) = cat_vol_ctype( spm_read_vols(Vcls) * 255); + end + + % update SPM segmenation to avoid some problems + % - define CAT parameter + catjob = cat_get_defaults; + catjob.extopts.uhrlim = 1; + catjob.extopts.regstr = eps; + [tpp,tff,tee] = spm_fileparts(catjob.extopts.darteltpm{1}); + numpos = min(strfind(tff,'Template_1')) + 8; + catjob.extopts.darteltpms = cat_vol_findfiles(tpp,[tff(1:numpos) ... + '*' tff(numpos+2:end) tee],struct('depth',1)); + [tpp,tff,tee] = spm_fileparts(catjob.extopts.shootingtpm{1}); + catjob.extopts.shootingtpm{1} = fullfile(tpp,[tff,tee]); + numpos = min(strfind(tff,'Template_0')) + 8; + catjob.extopts.shootingtpms = cat_vol_findfiles(tpp,[tff(1:numpos) ... + '*' tff(numpos+2:end) tee],struct('depth',1)); + catjob.extopts.shootingtpms(cellfun('length',catjob.extopts.shootingtpms) ~= ... + length(catjob.extopts.shootingtpm{1})) = []; % remove to short/long files + + % - define SPM parameter + res = load(fullfile(ppa,[ffa '_seg8.mat'])); + res.image0 = res.image; + res.do_dartel = 0; + [bb,vx1] = spm_get_bbox(tpm.V(1), 'old'); + vx = catjob.extopts.vox(1); + if ~isfinite(vx), vx = abs(prod(vx1))^(1/3); end + bb(1,:) = vx.*round(bb(1,:)./vx); + bb(2,:) = vx.*round(bb(2,:)./vx); + res.bb = bb; + + % - update SPM processing + [Ysrc,Yclsn,Yb,Yb0,Yy,catjob,res,T3th,stime] = ... + cat_main_updateSPM(Ysrc,Ycls,Yy,tpm,catjob,res,stime,stime); + Ycls = zeros([Vavg1.dim ncls],'uint8'); + for ci = 1:ncls + Ycls(:,:,:,ci) = Yclsn{ci}; + end + clear Ysrc Yb0; + case 'SPM' + for ci = 1:ncls + Vcls = spm_vol( spm_file( Vavg1.fname ,'prefix',sprintf('c%d',ci)) ); + Ycls(:,:,:,ci) = cat_vol_ctype( spm_read_vols(Vcls) * 255); + end + case 'CAT' + for ci = 1:ncls + Vcls = spm_vol( spm_file( Vavg1.fname ,'prefix',sprintf('p%d',ci)) ); + Ycls(:,:,:,ci) = cat_vol_ctype( spm_read_vols(Vcls) * 255); + end + case {'none',''} + Ycls = []; + end + + %% save braimask & labelmap + trans.affine.Vo = Vavg1; + + if ~isempty(matlabbatch) + if ~strcmp(job.opts.seg,'SPM+') + Yb = smooth3(single(sum(Ycls(:,:,:,1:3),4)))/255; + Yb(cat_vol_morph( Yb>0.5,'lc')) = 1; + end + % save brainmask + if job.output.writeBrainmask + cat_io_writenii(Vavg1,Yb,'','bm','label map','uint8',[0,1/255], ... + struct('native',1,'warped',0,'dartel',0),trans); + end + if job.output.writeLabelmap + % save label map + Yp0 = single( Ycls(:,:,:,1) ) * 2/255 + single( Ycls(:,:,:,2) ) * ... + 3/255 + single( Ycls(:,:,:,3) ) * 1/255; + Yp0 = max(Yb,Yp0); + if ncls>3 + Yp0 = Yp0 + single( smooth3(Ycls(:,:,:,5))>192 & sum(Ycls(:,:,:,1:3),4)<4 ) * 5; + % * 0.5 + single( Ycls(:,:,:,1)>128 ) * 4; + end + cat_io_writenii(Vavg1,Yp0,'','p0','label map','uint8',[0,5/255], ... + struct('native',1,'warped',0,'dartel',0),trans); + end + + + if job.output.cleanup + % remove segment files + for ci = 1:ncls + file = spm_file( Vavg1.fname ,'prefix',sprintf('c%d',ci)); + if exist(file,'file'), delete( file ); end + end + + % remove SPM seg8.mat file + [ppa,ffa] = spm_fileparts(Vavg1.fname); + file = fullfile(ppa,[ffa '_seg8.mat']); + if exist(file,'file'), delete( file ); end + + % the bias corrected file ... later ... + end + end + +end +%-------------------------------------------------------------------------- +function out = savg(subjects,si,methodstr,job,seqstr) + + % optimize input + [V,vx_vol,use,stime] = removeLowRes(subjects{si},job); + + pps = spm_fileparts(V(1).fname); + + if sum(use)==0 + cat_io_printf('err',['\nError: Non of the %d input files survived the first check. ' ... + 'Go on with d next subject. \n']); + return + else + V = V(use); + end + + if job.opts.res == 0 + job.opts.res = min(vx_vol(:)); + end + if job.opts.regres <= 0 + regres = job.opts.res * 1.5; + else + regres = job.opts.regres; + end + + + % Quick soft/smooth (temporary) bias correction + % ------------------------------------------------------------------ + % Inhomogeneities can trouble the registration and a simple fast + % (temporary) correction can reduce problems. Keeping the field very + % smooth even support permanent use. Altough a simple brain masking + % would be possible too this would limit the permanent use. + % ------------------------------------------------------------------ + job.opts.bias = 0; + [Vtbc,ihistcorr,stime] = quickBiascCorrection(V,job,stime); + + + %% Affine registration to TPM to get MNI orientation and first registration + % ------------------------------------------------------------------ + % 4 mm are ok but 2 is better + % ------------------------------------------------------------------ + [Vmni0,Vavg0,cormat,stime] = createAVG0(V,Vtbc,job,regres,pps,subAVGname,stime); + %cat_vol_imcalc( Vmni0(use) , Vavg0.fname , 'median(X)', struct('mask',0,'dmtx',1,'interp',0,'dtype',16)); + + % do realignment / coregistration to the first average + [Vmni1,stime] = correg2AVG0(V,Vtbc,Vmni0,Vavg0,cormat,job,regres,ihistcorr,stime); + + % cleanup + if job.opts.verb>2, cat_io_cmd(' ','g5','',job.opts.verb>2,stime); end + if job.output.cleanup + if exist(Vavg0.fname,'file'), delete(Vavg0.fname); end + file = fullfile(pwd,['spm_' datestr(clock,'YYYYmmmDD') '.ps']); + if exist(file,'file'), delete(file); end + end + + + %% create an new MNI like subject template space + % ------------------------------------------------------------------ + % Reslicing has to be done by spline to get sharp images at full or super-resolution. + [Vmni2,Vavg1,stime] = reslice(V,Vmni1,job,pps,subAVGname,stime); + + % use = checkdata(Vmni1,job,stime); + if sum(use)==0 + cat_io_printf('err',['\nError: Non of the %d input files survived the second check. ' ... + 'Go on with next subject. \n']); +% ###### USE FIRST AVERAGE ? ########## + return; + end + + %% + Ycls = segment(Vavg1,job); + + + %% + out.avg{si} = fullfile(pps,sprintf('%s%s%d_%s%s.nii',job.output.prefix,'allw' ,sum(use),subAVGname,ffe)); + out.avgt1{si} = ''; t1pref = 'allt1w'; + out.avgt2{si} = ''; t2pref = 'allt2w'; + if isempty(Ycls) + stime = cat_io_cmd(' No segmentation > no bias correction, no intensity normalization','g7','',job.opts.verb>1,stime); + + elseif strcmp(job.opts.norm,'none') + stime = cat_io_cmd(' Use SPM bias correction','g7','',job.opts.verb>1,stime); + % without normalization everything is fine and we can use the current average + movefile(spm_file( Vavg1.fname ,'prefix','m'),out.avg{si}); + else + %% normalize avg + stime = cat_io_cmd(' Bias correction and intensity normalization','g7','',job.opts.verb>1,stime); + Ymm = spm_read_vols(spm_vol(spm_file( Vavg1.fname ,'prefix','m'))); + Ymm = Ymm ./ cat_vol_approx(Ymm .* (Ycls(:,:,:,2)>128)); + vx_vol = sqrt(sum(V(vi).mat(1:3,1:3).^2)); + + Tavg = zeros(1,6); + for ci = unique( min( size(Ycls,4) , [1 2 3 6] )) + Ymcr = cat_vol_resize(Ymm .* (Ycls(:,:,:,ci)>4),'reduceV',vx_vol,4,32); + Tavg(ci) = cat_stat_kmeans( Ymcr(Ymcr(:)~=0) ); clear Ymcr; + end + if job.opts.debug + Ymm = (Ymm - min(Tavg(1,:))) ./ abs(max(Tavg(1,:)) - min(Tavg(1,:))); + else + clear Ymm; + end + + %highBG = Tavg(end) > Tavg(1); + + %% normalize other images + Tcls = zeros(numel(use),size(Ycls,4)); + for vi = find(use) + Vm = spm_vol( spm_file( Vmni1(vi).fname ,'prefix',[job.output.prefix 'r']) ); + Ym = spm_read_vols( Vm ); + Ym = Ym ./ cat_vol_approx(Ym .* (Ycls(:,:,:,2)>=128)); %,2 * max(1,min(3,job.opts.bias/30))); + + for ci = 1:size(Ycls,4) + Ymcr = cat_vol_resize(Ym .* (Ycls(:,:,:,ci)>4),'reduceV',vx_vol,4,32); + Tcls(vi,ci) = cat_stat_kmeans( Ymcr(Ymcr(:)~=0) ); + end + + switch job.opts.norm + case 'WM' + ti = [1 2 3 size(Ycls,4)]; + Ym = (Ym - min(Tcls(vi,ti))) ./ abs(max(Tcls(vi,ti)) - min(Tcls(vi,ti))); + case 'cls' + Tth.T3thx = sort( [ min(Ym(:)) Tcls(vi,:) max(Ym(:)) ] ); + clsi = [0 2/3 3/3 1/3 Tcls(vi,4)/Tcls(vi,2) Tcls(vi,5)/Tcls(vi,2) Tcls(vi,6)/Tcls(vi,2) max(Ym(:))/Tcls(vi,2)]; + Tth.T3th = sort(clsi); + Ym = cat_main_gintnormi(Ym/3,Tth,1); + end + if vi == 1 + Yt1 = zeros(size(Ym)); t1n = 0; + Yt2 = zeros(size(Ym)); t2n = 0; + end + if strcmp(job.opts.norm,'cls') + if Tcls(vi,3) > Tcls(vi,2) + Ymc = 1 - Ym; + else + Ymc = Ym; + end + cat_io_writenii(Vm,Ymc,'','m','intnorm','single',[0 1],struct('native',1,'warped',0,'dartel',0),trans); + else + cat_io_writenii(Vm,Ym,'','m','intnorm','single',[0 1],struct('native',1,'warped',0,'dartel',0),trans); + end + if Tcls(vi,3) > Tcls(vi,2) + Yt2 = Yt2 + Ym; + t2n = t2n + 1; + else + Yt1 = Yt1 + Ym; + t1n = t1n + 1; + end + end + Yt1 = Yt1 / t1n; + Yt2 = Yt2 / t2n; + end + + + + + + + + + %% Detection and Suppression of Motion Artifacts (MAs) + % The idea is that random MAs are oc + if ~isempty(Ycls) + if sum(use2)>2 && use2<10 + stime = cat_io_cmd(' Motion Suppressing Averaging','g7','',job.opts.verb>1,stime); + + Vm = spm_vol( spm_file( char( ({Vmni1(use).fname})' ) ,'prefix',['m' job.output.prefix 'r']) ); + Yw = zeros(Vm(1).dim,'single'); Ym = Yw; + for xi = find( use2 == 1) + %Vm(xi).mat = Vmni1(xi).mat; + Pxi = Vm( xi ).fname; + Pnxi = char({ Vm( setxor(find( use2 == 1),xi) ).fname }'); + + Vhr1w = Vm(1); Vhr1w.fname = fullfile(pps,[job.output.prefix 'avgw_' Vhr1w.fname '.nii']); + [~, Yhr1w] = cat_vol_imcalc( [Pxi;Pnxi], Vhr1w , ... + sprintf('abs(i1 - mean(cat(4%s),4))',sprintf(',i%d',2:size([Pxi;Pnxi],1) )), ... + struct('mask',0,'dmtx',0,'interp',0,'dtype',16)); + Yhr1w = max(0.1,1 - 2*Yhr1w); + + Yw = Yw + Yhr1w; + Ym = Ym + spm_read_vols( Vm( xi ) ) .* Yhr1w; + + end + Ym = Ym ./ Yw; + + Vavg = Vm(1); + Vavg.fname = out.avg{si}; + spm_write_vol( Vavg , Ym); + else + % final average + Vm = spm_vol( spm_file( char( ({Vmni1(use).fname})' ) ,'prefix',['m' job.output.prefix 'r']) ); + evalc(['spm_reslice( spm_file( subjects{si}( use ) ,''prefix'',[''m'' job.output.prefix ''r'']), ' ... + 'struct(''which'',0,''mean'',1,''mask'',0,''interp'',1) )']); + movefile( spm_file( Vm( find(use>0,1,'first') ).fname,'prefix','mean'), out.avg{si}); + end + else + % final average + Vm = spm_vol( spm_file( char( ({Vmni1(use).fname})' ) ,'prefix',[job.output.prefix 'r']) ); + evalc(['spm_reslice( Vm ,' ... spm_file( subjects{si}( use ) ,''prefix'',[job.output.prefix ''r'']), ' ... + 'struct(''which'',0,''mean'',1,''mask'',0,''interp'',1) )']); + movefile( spm_file( Vm( find(use>0,1,'first') ).fname,'prefix','mean'), out.avg{si}); + end + + +%% + if job.output.writeSDmap && ~isempty(Ycls) && ~isempty(job.opts.norm) + %% std + Vavg = spm_vol(out.avg{si}); + Yavg = spm_read_vols(Vavg); + Ystd = zeros(size(Yavg),'single'); + for vi = find(use) + Vm = spm_vol( spm_file( Vmni1( vi ).fname ,'prefix',['m' job.output.prefix 'r']) ); + Ym = spm_read_vols( Vm ); + Ystd = Ystd + ( (Ym - Yavg)).^2; + end + Vmsd = spm_vol( out.avg{si} ); Vmsd.fname = fullfile(pps,[job.output.prefix 'sd_' subAVGname '.nii']); + cat_io_writenii(Vmsd,Ystd,'','','intnorm','single',[0 1],struct('native',1,'warped',0,'dartel',0),trans); + end + %{ + %% + out.std = Vavg; Vmsd.fname = fullfile(pps,[job.output.prefix 'sd_' subAVGname '.nii']); + cat_io_writenii(Vhr1avg,Ystd,'','std','standard deviation of rescans', ... + 'single',[0 1],struct('native',1,'warped',0,'dartel',0),trans); + movefile( spm_file(Vhr1avg.fname,'prefix',t1pref),out.std); + end + + + %% not useful without normalization + if job.output.writeSDmap + %% + Vmsd = spm_vol( out.avg{si} ); Vmsd.fname = fullfile(pps,[job.output.prefix 'sd_' subAVGname '.nii']); + cat_vol_imcalc( spm_file( subjects{si}( use ) ,'prefix',['m' job.output.prefix 'r']) , Vmsd , ... + 'std(X)',struct('mask',0,'interp',1,'dmtx',1,'dtype',16)); + ... 'max(abs(i1-i2),max(abs(i1-i3),abs(i2-i3)))',struct('mask',0,'interp',1,'dtype',16));% 'dmtx',1, + end +%} + + if ~isempty(Ycls) + stime = cat_io_cmd(' Create final average','g7','',job.opts.verb>1,stime); + if t1n>0 && t2n>0 + out.avgt1{si} = fullfile(pps,sprintf('%s%s%d_%s%s.nii',job.output.prefix,t1pref,t1n,subAVGname,ffe)); + cat_io_writenii(Vavg1,Yt1,'',t1pref,'t1 weighted average','single', ... + [0 1],struct('native',1,'warped',0,'dartel',0),trans); + movefile( spm_file(Vavg1.fname,'prefix',t1pref),out.avgt1{si}); + end + if t2n>0 + out.avgt2{si} = fullfile(pps,sprintf('%s%s%d_%s%s.nii',job.output.prefix,t2pref,t2n,subAVGname,ffe)); + cat_io_writenii(Vavg1,Yt2,'',t2pref,'t2 weighted average','single', ... + [0 1],struct('native',1,'warped',0,'dartel',0),trans); + movefile( spm_file(Vavg1.fname,'prefix',t2pref),out.avgt2{si}); + end + end + + + %% + if 0 %job.output.cleanup + for vi = find(use) + file = spm_file( subjects{si}{ vi } ,'prefix',[job.output.prefix 'r']); + if exist(file,'file'), delete(file); end + end + + if ~job.output.writeRescans + for vi = find(use) + file = spm_file( subjects{si}{ vi } ,'prefix',['m' job.output.prefix 'r']); + if exist(file,'file'), delete(file); end + end + end + + %% first avg + file = fullfile(pps,[job.output.prefix 'avg1_' subAVGname '.nii']); + if exist(file,'file'), delete(file); end + file = fullfile(pps,['m' job.output.prefix 'avg1_' subAVGname '.nii']); + if exist(file,'file'), delete(file); end + + %% delete unpacked files + if all( sBIDS(si) ) + for ri = 1:numel(subjects{si}) + if exist(subjects{si}{ri},'file'), delete(subjects{si}{ri}); end + end + end + + end + + if job.opts.verb>1 + cat_io_cmd(' ','g5','',job.opts.verb>1,stime); +% fprintf('%5.0fs\n',etime(clock,stimea)); + end + %% display something +% ######################### +% add report here +% ######################### + +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_vol_series_align.m",".m","5567","184","function out = cat_vol_series_align(job) +% Longitudinal rigid registration of image series +% FORMAT out = cat_vol_series_align(job) +%_______________________________________________________________________ +% +% modified version of +% John Ashburner +% spm_series_align.m 5044 2012-11-09 13:40:35Z john +% +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +N = numel(job.data); + +if numel(job.noise)==1 + noise = repmat(job.noise,[N,1]); +elseif numel(job.noise) ~= N + error('Incompatible numbers of noise estimates and scans.'); +else + noise = job.noise(:); +end + +prec = noise.^(-2); + +if isfield(job,'reg') && isfield(job.reg,'nonlin') + cat_io_cprintf('blue','Non-linear Registration!\n'); + tim = job.reg.nonlin.times(:); + if all(isfinite(tim)) + if numel(tim) == 1 + tim = (1:N)'; + elseif numel(tim) ~= N + error('Incompatible numbers of times and scans.'); + end + if any(abs(diff(tim)) > 50) + error('Time differences should be in years.'); + end + wparam0 = job.reg.nonlin.wparam; + + midtim = median(tim); + tim = tim - midtim; + w_settings = kron(wparam0,1./(abs(tim)+1/365)); + s_settings = round(3*abs(tim)+2); + else % use default regularization if tim is set to NAN + w_settings = job.reg.nonlin.wparam; + s_settings = 6; %round( job.reg.nonlin.wparam(5) / 25); + end +else + w_settings = [Inf Inf Inf Inf Inf]; + s_settings = Inf; +end + +b_settings = [0 0 job.bparam]; +Nii = nifti(strvcat(job.data)); +ord = [3 3 3 0 0 0]; + +output = {}; +if job.write_avg, output = [output, {'wavg'}]; end +if job.write_rimg, output = [output, {'wimg'}]; end + +if isfield(job.reg,'nonlin') + if job.reg.nonlin.write_jac, output = [output, {'wjac'} ]; end + if job.reg.nonlin.write_def, output = [output, {'wdef'} ]; end +end + +if ~isfield(job,'use_brainmask') + use_brainmask = 1; +else + use_brainmask = job.use_brainmask; +end + +if ~isfield(job,'reduce') + reduce = 1; +else + reduce = job.reduce; +end + +if ~isfield(job,'sharpen') + sharpen = 2; +else + sharpen = job.sharpen; +end + +if ~isfield(job,'setCOM') + setCOM = 1; +else + setCOM = job.setCOM; +end + +% force isotropic average resolution (0-default,1-best,2-worst,3-optimal) +if ~isfield(job,'isores') + isores = 0; +else + isores = -job.isores; +end + +% RD202510: Test voxel resolution and force minimal resolution +% this is relevant in case with high slice thickness +% for instance in the ultra-low-field data (Frantisek et al. 2025) +% https://openneuro.org/datasets/ds006557/versions/1.0.0 +% RD202511: Moreover, this would also allow superinterpolation in case of +% many rescans (similar timepoint) +minres = min([ 1.2 abs( isores(isores~=0) ) ]); % +vx_vol = nan(numel(Nii),3); +tempimgs = cell(numel(Nii),1); +for vi = 1:numel(Nii) + vx_vol(vi,:) = sqrt(sum(Nii(vi).mat(1:3,1:3).^2)); + + %% + if sharpen || any( minres < vx_vol(vi,:) * .8 ) + % only for average estimation and not long + Vx = spm_vol(job.data{vi}); + Yx = spm_read_vols(Vx); + end + + if sharpen + con = abs(diff([ prctile(Yx(:),10) prctile(Yx(:),90) ])); + sharp = min(.5,sharpen * min(con, numel(Nii).^1.5 / 20)); + Yx = min(max(Yx(:)),max(min(Yx(:)),Yx + ... + (Yx~=0) .* max(-con/6.*Yx,min(con/6.*Yx, ... + sharp/2 .* (Yx - smooth3(Yx)) + ... + sharp/4 .* (Yx - cat_vol_smooth3X(Yx,2)))))); + end + + if any( minres < vx_vol(vi,:) * .8 ) + % interpolate data + [Yx,Vx] = cat_vol_resize( Yx , 'interphdr', spm_vol(job.data{vi}), min(minres,vx_vol(vi,:)), 5); + vx_vol(vi,:) = Vx.resN; + Vx = Vx.hdrN; + + if 0 + % post correction is not working and cause issues in the longitudinal bias modeling + Yx = min(max(Yx(:)),max(min(Yx(:)),Yx + ... + (Yx~=0) .* max(-con/6.*Yx,min(con/6.*Yx, ... + sharp/2 .* (Yx - smooth3(Yx)))))); + end + end + + if sharpen || any( minres < vx_vol(vi,:) * .8 ) + % Write image to reload by the nifti routine + % We use the tempdir to keep the file name but this means that we have + % to move and cleanup data later + Vo = Vx; Vo.fname = spm_file(Vo.fname,'path',tempdir); + spm_write_vol(Vo,Yx); + Nii(vi) = nifti( Vo.fname ); + tempimgs{vi} = Vo.fname; + end +end + + +% sometimes for quite anisotropic data long. registration fails and will be +% called again with more isotropic spatial resolution using isores = 3 +% (optimal) +try + out = cat_vol_groupwise_ls(Nii, output, prec, w_settings, b_settings, s_settings, ord, use_brainmask, reduce, setCOM, isores); +catch + fprintf('Recall cat_vol_groupwise_ls again with more isotropic spatial resolution.\n') + out = cat_vol_groupwise_ls(Nii, output, prec, w_settings, b_settings, s_settings, ord, use_brainmask, reduce, setCOM, 3); +end + +% RD202510: move and cleanup interpolated data +if any( cellfun(@isempty,tempimgs) == 0 ) + % if the first file had to be interpolated we have to move it from the tmp dir + if ~strcmp( spm_file( out.avg{1} ,'path') , fileparts( job.data{1} ) ) + movefile( out.avg{1} , spm_file( out.avg{1} ,'path', fileparts( job.data{1} ) ) ); + end + if isfield( out , 'rimg' ) + for vi=1:numel(tempimgs) + % move realigned images if they where template + movefile( out.rimg{vi} , spm_file( out.rimg{vi} ,'path', fileparts( job.data{vi} ) ) ); + delete(tempimgs{vi}); + end + end +end + + +return + +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_main_roi.m",".m","18912","452","function cat_main_roi(job,trans,Ycls,Yp0,opt) +% ______________________________________________________________________ +% ROI Partitioning: +% This part estimates individual measurements for different ROIs. +% The ROIs are defined in the CAT normalized space and there are three +% ways to estimate them: (1) in (internal) subject space, (2) in +% normalized space (where also the VBM is done and that is defined +% by extopts.vox, and (3) in the atlas space. +% Estimation in normalized space is more direct and avoids further +% transformations or individual adaptations. The way over the subject space +% has the advantage that individual anatomical refinements are possible, +% but this has to be done and evaluated for each atlas and it is not so +% simple at the end. Another thing (that came up later) was the evaluation +% in atlas space, that most relevant because some atlas maps use now +% higher resolutions to describe fine structures or have a smaller +% boundary box. +% +% cat_main_roi(job,trans,Ycls,Yp0,opt) +% +% job .. cat preprocessing job +% .extopts +% .verb .. display progress +% .atlas .. +% .output +% .atlases .. setting what atlas has to be used +% +% trans .. cat preprocessing registration structure +% ... +% +% Ycls .. tissue segmentation as cell structure +% Yp0 .. label map with CSF = 1, GM = 2, and WM = 3 +% opt .. parameter structure +% .type .. mapping type +% 1 - native space (default) +% 2 - atlas space (push - faster but less accurate) +% 3 - atlas space (inv+pull - slower but more accurate) +% .write .. write debugging output +% 0 - no debugging (default) +% 1 - display some results +% 2 - display results and write some maps +% +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + if ~exist('opt','var'), opt = struct(); end + def.type = 1; % 1 - native space, 2 - atlas space push, 3 - atlas space pull + def.write = 0; % 1 - display some results, 2 - display results and write some maps + opt = cat_io_checkinopt(opt,def); + + + % file name handling + [pth,nam] = spm_fileparts( trans.native.Vo.fname ); + % in case of SPM input segmentation we have to add the name here to have a clearly different naming of the CAT output + if isfield(job,'spmpp'), nam = ['c1' nam]; end + % definition of subfolders + [mrifolder, reportfolder, surffolder, labelfolder] = cat_io_subfolders(trans.native.Vo.fname,job); + + % voxel size of the processed image + vx_vol = sqrt( sum( trans.native.Vi.mat(1:3,1:3).^2 ) ); + + % print progress + if job.extopts.expertgui + types = {'native','push atlas','pull atlas'}; + stime = cat_io_cmd(sprintf('ROI estimation in %s space',types{opt.type})); if job.extopts.verb, fprintf('\n'); end + else + stime = cat_io_cmd('ROI estimation'); if job.extopts.verb, fprintf('\n'); end + end + + % get atlases maps that should be evaluated + FAF = job.extopts.atlas; + FA = {}; fai = 1; + AN = fieldnames(job.output.atlases); + for ai = 1:numel(AN) + fafi = find(cellfun('isempty',strfind(FAF(:,1),[AN{ai} '.']))==0,1); + if ~isempty(fafi) && (isempty(job.output.atlases.(AN{ai})) || job.output.atlases.(AN{ai})) + FA(fai,:) = FAF(fafi,:); %#ok + fai = fai+1; + end + + % add WMHC class if there is an extra class (WMHC==3) + if job.extopts.WMHC == 3 + if fai-1 > 0 + FA{fai-1,3} = unique( [FA{fai-1,3} {'wmh'}] ); %#ok + else + cat_io_cprintf('warn',sprintf(' Indexing faild. Could not consider WMHs! \n')); + end + end + end + + if isempty(FA) + % deactivate output + FN = fieldnames(job.output.atlas); + for ai = 1:numel(FN) + job.output.atlas.(FN{ai}) = 0; + end + else + % get atlas resolution + % we sort the atlases to reduce data resampling + VA = spm_vol(char(FA(:,1))); + for ai=1:numel(VA), VAvx_vol(ai,:) = sqrt(sum(VA(ai).mat(1:3,1:3).^2)); end %#ok + [VAs,VAi] = sortrows(VAvx_vol); %#ok + FA = FA(VAi,:); VA = VA(VAi,:); VAvx_vol = VAvx_vol(VAi,:); + end + + if opt.type == 1 % native space + wYp0 = Yp0; wYcls = cell(1:numel(Ycls)); + for i = 1:numel(Ycls), wYcls{i} = single(Ycls{i})/255; end + vx_volw = vx_vol; + end + for ai=1:size(FA,1) + %% map data to actual template space + [px,atlas] = fileparts(FA{ai,1}); clear px; %#ok + if ai==1 + stime2 = cat_io_cmd(sprintf(' ROI estimation of ''%s'' atlas',atlas),'g5','', job.extopts.verb-1); + else + stime2 = cat_io_cmd(sprintf(' ROI estimation of ''%s'' atlas',atlas),'g5','', job.extopts.verb-1,stime2); + end + + + % resample data in atlas resolution for the first time or if the atlas resolution changes + transw = trans.warped; + transw.odim = VA(ai).dim; % size of the boundary box of the atlas we have to render the tissues + transw.M1 = VA(ai).mat; % boundary box position + % adapt y for the atlas resolution (for loop) and for the new position (matit) + mati = trans.affine.mat(13:15) - VA(ai).mat(13:15); + vdim = spm_imatrix( VA(ai).mat ); % trans.affine.mat ); + matit = mati(1:3) ./ vdim(7:9); + % use vox(1) because vox can have multiple values in development mode + for i=1:3, transw.y(:,:,:,i) = transw.y(:,:,:,i) .* job.extopts.vox(1) ./ VAvx_vol(ai,i); end + transw.y = cat(4,transw.y(:,:,:,1) + matit(1), transw.y(:,:,:,2) + matit(2), transw.y(:,:,:,3) + matit(3) ); + transw.ViVt = prod(vx_vol) ./ job.extopts.vox(1)^3; + + if opt.type == 3 + % Modulation using spm_diffeo and push introduces aliasing artefacts, + % thus we use the def2det function of the inverted deformations to obtain the old and + % in my view a more appropriate jacobian determinant + % The 2nd reason to use the old modulation is compatibility with cat_vol_defs.m + transw.yi = spm_diffeo('invdef' , transw.y, VA(ai).dim, eye(4),eye(4)); + transw.w = max( eps , spm_diffeo('def2det', transw.yi) * transw.ViVt ); + % avoid boundary effects that are not good for the global measurements + transw.w(:,:,[1 end]) = NaN; transw.w(:,[1 end],:) = NaN; transw.w([1 end],:,:) = NaN; + % filter the resampled data to reduce interpolation artefacts + transw.fs = transw.fs .* job.extopts.vox(1) ./ VAvx_vol(ai,i); + spm_smooth(transw.w,transw.w,transw.fs); % filter determinant to reduce interpolation artefacts + clear maxw; + end + + % map segments for new atlas space + if opt.type == 2 || opt.type == 3 % atlas space + wYp0 = cat_vol_roi_map2atlas(Yp0 ,transw,0,opt.type==3); + wYcls = cat_vol_roi_map2atlas(Ycls,transw,1,opt.type==3); + wYa = cat_vol_roi_load_atlas(FA{ai,1}); + vx_volw = repmat(job.extopts.vox(1),1,3); + else + wYa = cat_vol_roi_load_atlas(FA{ai,1}, transw); + end + + % extract ROI data + csv = cat_vol_ROIestimate(wYp0,wYa,wYcls,ai,'V',[],FA{ai,3},FA,vx_volw); % volume + + % thickness + % RD202006: this case does not exist anymore but may come back later + if exist('Yth1','var') + % For thickness we want to avoid values in non-cortical regions such as + % the ventricles or regions with relative low GM volume or high CSF volume. + csv = cat_vol_ROIestimate(wYp0,wYa,wYth1,ai,'T',csv,{'gm'},FA); %.*wYmim + % correct for ventricular regions that use the 'Ven' keyword. + ven = find(cellfun('isempty',strfind( csv(:,2) , 'Ven'))==0); + csv(ven,end) = {nan}; %#ok + % correct for regions with relative low GM (<10%) or high CSF volume (>50%). + csvf = cat_vol_ROIestimate(wYp0,wYa,wYcls * prod(vx_volw),ai,'V',[],{'csf','gm','wm'},FA); + vola = [nan,nan,nan;cell2mat(csvf(2:end,3:end))]; + volr = vola ./ repmat(sum(vola,2),1,3); + csv(volr(:,2)<0.1 | volr(:,2)>0.5,end) = {nan}; + end + + % xml-export one file for all (this is a structure) + ROI.(atlas) = csv; + + + % display and debugging + if opt.write + %% this does not work in case of trimmed atlases set do not include the full brain + % * keep in mind that cobra is + % - only defined for some regions + % - has a smaller boundary box resulting in smaller global atlas space values and distortions close to the boudary (timmed?~= not trimmed) + % * mori is WM atlas and not all GM voxels were aligned to a region + GMi = find(cellfun('isempty',strfind(FA{ai,3},'gm'))==0); + fprintf('\n%8s %8s %8s | %8s | %8s %8s %8s %8s %8s %8s\n','GM','WM','CSF','sum(RGM)','R1','R2','R3','R4','R5','R6') %* prod(vx_vol) + fprintf('%8.2f %8.2f %8.2f | %8.2f | %8.2f %8.2f %8.2f %8.2f %8.2f %8.2f\n', ... + [cat_stat_nansum(wYcls{1}(:)) ,cat_stat_nansum(wYcls{2}(:)),cat_stat_nansum(wYcls{3}(:))] * prod(vx_volw) / 1000, ... + sum( cell2mat( csv(2:end,2+GMi))), cell2mat( csv(2:7,2+GMi) )); + fprintf('%8.2f %8.2f %8.2f\n', ... + [cat_stat_nansum(Ycls{1}(:)) ,cat_stat_nansum(Ycls{2}(:)) ,cat_stat_nansum(Ycls{3}(:)) ] * prod(vx_vol) / 1000 / 255); + fprintf('%8.2f %8.2f %8.2f\n', ... + ([cat_stat_nansum(wYcls{1}(:)),cat_stat_nansum(wYcls{2}(:)),cat_stat_nansum(wYcls{3}(:))] * prod(vx_volw) / 1000) ./ ... + ([cat_stat_nansum(Ycls{1}(:)) ,cat_stat_nansum(Ycls{2}(:)) ,cat_stat_nansum(Ycls{3}(:)) ] * prod(vx_vol) / 1000 / 255) * 100); + fprintf('\n'); + + if opt.write>1 + %% save mapped tissue map + if opt.type == 2 + patlas = '-pushed'; + wVai = spm_vol(FA{ai,1}); % atlas volume information + elseif opt.type == 3 + patlas = '-pulled'; + wVai = spm_vol(FA{ai,1}); % atlas volume information + else + patlas = '-native'; + wVai = spm_vol(trans.native.Vi.fname); % internal volume information + end + wVai.fname = fullfile(pth,labelfolder,[nam '_' atlas patlas '.nii']); + wVai.dt(1) = 2; + wVai.pinfo(1) = 1; + spm_write_vol(wVai,wYa); + + wVai.fname = fullfile(pth,labelfolder,[nam '_' atlas '_p0' patlas '.nii']); + wVai.dt(1) = 2; + wVai.pinfo(1) = 0.02; + spm_write_vol(wVai,wYp0); + + wVai.fname = fullfile(pth,labelfolder,[nam '_' atlas '_p1' patlas '.nii']); + wVai.dt(1) = 4; + wVai.pinfo(1) = 0.001; %modulated! + spm_write_vol(wVai,wYcls{1}); + end + end + end + + + % write results + if size(FA,1)>0 % if there was an atlas + cat_io_cmd(' Write results','g5','',job.extopts.verb,stime2); + + catROI = cat_roi_fun('csvtab2xmlroi',ROI); + cat_io_xml(fullfile(pth,labelfolder,['catROI_' nam '.xml']),catROI,'write'); + + % central warning for missed csv files + fst = 0; + for ai = 1:numel(VA) + [pp,ff] = fileparts(FA{ai,1}); + csvf = fullfile(pp,[ff '.csv']); + if ~exist(csvf,'file') + if fst==0, cat_io_cmd('','g5','',job.extopts.verb,stime2); fst = 1; end + cat_io_cprintf('warn',sprintf(' Cannot find ''%s'' csv-file with region names! \n',ff)); + end + end + if fst==0 + cat_io_cmd(' ','g5','',job.extopts.verb,stime2); + else + cat_io_cmd(' ','g5','',job.extopts.verb); + end + + end + cat_io_cmd('','n','',1,stime); + +return +%======================================================================= +function wYa2 = cat_vol_roi_load_atlas(FAai,warped) +% ---------------------------------------------------------------------- +% just load atlas in its own space +% ---------------------------------------------------------------------- + [pp,ff,ee] = spm_fileparts(FAai); + FAai1 = fullfile(pp,[ff ee]); + if ~exist(FAai1,'file') + error('cat:cat_main:missAtlas','Miss cat atlas-file ''%s''!',FAai1); + end + % try multiple times, because of read error in parallel processing + for i=1:5 + try + wVa = spm_vol(FAai1); + dt = wVa(1).private.dat.dtype; + if ~exist('warped','var') + wYa = spm_read_vols(wVa); + else + mati = spm_imatrix(wVa.mat); + if 0 % mati(1)<0 && mati(7)>0 + wVa.mat = spm_matrix( mati .* [-1 1 1, 1 1 1, -1 1 1, 1 1 1] ); %wVa = rmfield(wVa,'private'); + wVa.mat0 = wVa.mat; + wVa.private.mat0 = spm_matrix( mati .* [-1 1 1, 1 1 1, -1 1 1, 1 1 1] ); + end + + wYa = spm_sample_vol(wVa,double(warped.y(:,:,:,1)),double(warped.y(:,:,:,2)),double(warped.y(:,:,:,3)),0); + wYa = reshape(wYa,size(warped.y(:,:,:,1))); + + if sum(wYa(:))==0 % && mati(1)<0 && mati(7)>0 + wYa2 = spm_read_vols(wVa); + if sum(wYa2(:))==0 + cat_io_addwarning('cat_main_roi:emptyAtlas','Atlas has no values!',1,[1 0]) + else + cat_io_addwarning('cat_main_roi:emptyMappedAtlas', ... + ['The remapped atlas has no values and x dimension is positiv (should be negative). \\n' ... + 'Check your atlas orientation with SPM display to confirm that the image is in MNI space.'],1,[1 1]) + end + end + end + break + catch + pause(0.5 + rand(1)) + end + end + + %% final data type setting + if ~isempty(strfind( dt , 'FLOAT' )) || ~isempty(strfind( dt , 'DOUBLE' )) + %% convert to (usinged) integer datatype + dtypes = {'uint8','int8','uint16','int16','uint32','int32'}; + for di = 1:numel(dtypes) + if min(wYa(:))>=intmin(dtypes{di}) && max(wYa(:))2, csv(:,3:end)=[]; end + for ri=size(csv,1):-1:1 + if isempty(csv{ri,1}) || isempty(csv{ri,2}) || ... + any(csv{ri,1}==0) || (ri>2 && ~isnumeric(csv{ri,1})) + csv(ri,:)=[]; + end + end + end + name = genvarname(strrep(strrep(name,'-','_'),' ','_')); + + if isempty(csv) || size(csv,1)<=1 + cat_io_addwarning('cat_main_roi:emptyAtlas','Cannot find atlas ROIs and export empty atlas.',1,[1 1]) + return; + end + + %% volume case + Yp0toC = @(Yp0,c) 1-min(1,abs(Yp0-c)); + % other maps with masks + for ti=1:numel(tissue) + switch name(1) + case 'V' % volume + csv{1,end+1} = [name tissue{ti}]; %#ok + for ri=1:size(csv,1) + if isnumeric(csv{ri,1}) + switch lower(tissue{ti}) + case 'csf', Ymm = single(Yv{3}) .* single(Ya==csv{ri,1}); + case 'gm', Ymm = single(Yv{1}) .* single(Ya==csv{ri,1}); + case 'wm', Ymm = single(Yv{2}) .* single(Ya==csv{ri,1}); + case 'wmh', Ymm = single(Yv{7}) .* single(Ya==csv{ri,1}); + case 'brain', Ymm = single(Yv{1} + Yv{2} + Yv{3} + Yv{7}) .* single(Ya==csv{ri,1}); + case 'tissue', Ymm = single( Yv{2} + Yv{3} + Yv{7}) .* single(Ya==csv{ri,1}); + case '', Ymm = single(Ya==csv{ri,1}); + end + csv{ri,end} = 1/1000 * cat_stat_nansum(Ymm(:)) .* prod(vx_vox); + end + end + otherwise % + csv{1,end+1} = strrep([name tissue{ti}],'Tgm','ct'); %#ok + switch lower(tissue{ti}) + case 'csf', Ymm = Yp0toC(Yp0,1); + case 'gm', Ymm = Yp0toC(Yp0,2); + case 'wm', Ymm = Yp0toC(Yp0,3); + case 'wmh', Ymm = Yp0toC(Yp0,4); + case 'brain', Ymm = Yp0>0.5; + case 'tissue', Ymm = Yp0>1.5; + case '', Ymm = true(size(Yp0)); + end + for ri=1:size(csv,1) + if isnumeric(csv{ri,1}) + csv{ri,end} = cat_stat_nanmean(Yv(Ya(:)==csv{ri,1} & Ymm(:))); + end + end + end + end +return","MATLAB" +"Neurology","ChristianGaser/cat12","cat_spm_smoothto8bit.m",".m","2944","92","function VO = cat_spm_smoothto8bit(V,fwhm) +% 3 dimensional convolution of an image to 8bit data in memory +% FORMAT VO = cat_spm_smoothto8bit(V,fwhm) +% V - mapped image to be smoothed +% fwhm - FWHM of Guassian filter width in mm +% VO - smoothed volume in a form that can be used by the +% spm_*_vol.mex* functions. +%_______________________________________________________________________ +% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging +% John Ashburner +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + +if nargin>1 && fwhm>0, + VO = smoothto8bit(V,fwhm); +else + VO = V; +end +return; +%_______________________________________________________________________ + +%_______________________________________________________________________ +function VO = smoothto8bit(V,fwhm) +% 3 dimensional convolution of an image to 8bit data in memory +% FORMAT VO = smoothto8bit(V,fwhm) +% V - mapped image to be smoothed +% fwhm - FWHM of Guassian filter width in mm +% VO - smoothed volume in a form that can be used by the +% spm_*_vol.mex* functions. +%_______________________________________________________________________ + +vx = sqrt(sum(V.mat(1:3,1:3).^2)); +s = (fwhm./vx./sqrt(8*log(2)) + eps).^2; +r = cell(1,3); +for i=1:3, + r{i}.s = ceil(3.5*sqrt(s(i))); + x = -r{i}.s:r{i}.s; + r{i}.k = exp(-0.5 * (x.*x)/s(i))/sqrt(2*pi*s(i)); + r{i}.k = r{i}.k/sum(r{i}.k); +end + +VO = V; +VO.dt = [spm_type('uint8') spm_platform('bigend')]; +V0.dat = uint8(0); +V0.dat(VO.dim(1:3)) = uint8(0); +VO.pinfo = []; + +img = single(spm_read_vols(V)); img(isnan(img(:)) | isinf(img(:))) = 0; + +% use the more exact spm_smooth routine +spm_smooth(img,img,fwhm./vx); + +mx = max(img(:)); +mn = min(img(:)); +VO.pinfo = repmat([1;0],1,size(img,3)); +VO.dat = uint8(round((img-mn)*(255/(mx-mn)))); + +%{ +for i=1:V.dim(3)+r{3}.s, + + if i<=V.dim(3), + img = spm_slice_vol(V,spm_matrix([0 0 i]),V.dim(1:2),0); + msk = find(~isfinite(img)); + img(msk) = 0; + buff(:,:,rem(i-1,r{3}.s*2+1)+1) = ... + conv2(conv2(img,r{1}.k,'same'),r{2}.k','same'); + else + buff(:,:,rem(i-1,r{3}.s*2+1)+1) = 0; + end + + mx = max(buff(:)); + mn = min(buff(:)); + if mx==mn, mx=mn+eps; end + if i>r{3}.s, + kern = zeros(size(r{3}.k')); + kern(rem((i:(i+r{3}.s*2))',r{3}.s*2+1)+1) = r{3}.k'; + img = reshape(buff,[prod(V.dim(1:2)) r{3}.s*2+1])*kern; + img = reshape(img,V.dim(1:2)); + ii = i-r{3}.s; + VO.pinfo(1:2,ii) = [(mx-mn)/255 mn]'; + VO.dat(:,:,ii) = uint8(round((img-mn)*(255/(mx-mn)))); + end +end +%} +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_vol_qa202207b.m",".m","59993","1312","function varargout = cat_vol_qa202207b(action,varargin) +% CAT Preprocessing T1 Quality Control +% ______________________________________________________________________ +% +% Estimation of image quality measures like noise, inhomogeneity, +% contrast, resolution, etc. and scaling for school marks. +% +% [QAS,QAM] = cat_vol_qa(action,varargin) +% +% +% 1) Use GUI interface to choose segmentation and automatic setting of +% original and modified image (if available) +% [QAS,QAM] = cat_vol_qa() = cat_vol_qa('p0') +% +% [QAS,QAM] = cat_vol_qa('p0'[,opt]) - p0 class image +% [QAS,QAM] = cat_vol_qa('p#'[,opt]) - p1,p2,p3 class images +% [QAS,QAM] = cat_vol_qa('c#'[,opt]) - c1,c2,c3 class images +% [QAS,QAM] = cat_vol_qa('*#'[,opt]) - csf,gm,wm class images +% [QAS,QAM] = cat_vol_qa('p0',Pp0[,opt]) - no GUI call +% [QAS,QAM] = cat_vol_qa('p#',Pp1,Pp2,Pp3,[,opt]) - no GUI call +% [QAS,QAM] = cat_vol_qa('c#',Pc1,Pc2,Pc3,[,opt]) - no GUI call +% [QAS,QAM] = cat_vol_qa('c#',Pcsf,Pgm,Pwm,[,opt]) - no GUI call +% +% +% 2) Use GUI interface to choose all images like for other segmentations +% and modalities with a similar focus of CSF, GM, and WM tissue +% contrast such as PD, T2, or FLASH. +% [QAS,QAM] = cat_vol_qa('p0+'[,opt]) - p0 class image +% [QAS,QAM] = cat_vol_qa('p#+'[,opt]) - p1,p2,p3 class images +% [QAS,QAM] = cat_vol_qa('c#+'[,opt]) - c1,c2,c3 class images +% [QAS,QAM] = cat_vol_qa('*#+'[,opt]) - csf,gm,wm class images +% [QAS,QAM] = cat_vol_qa('p0+',Pp0,Po[,Pm,opt]) - no GUI call +% [QAS,QAM] = cat_vol_qa('p#+',Pp1,Pp2,Pp3,Po[,Pm,opt]) - no GUI call +% [QAS,QAM] = cat_vol_qa('c#+',Pc1,Pc2,Pc3,Po[,Pm,opt]) - no GUI call +% +% +% 3) Use GUI interface to choose all images. I.e. for other segmentations +% and modalities without focus of GM-WM contrast such as DTI MTI. +% [ not implemented yet ] +% +% +% 4) CAT12 internal preprocessing interface +% (this is the processing case that is also called in all other cases) +% [QAS,QAM] = cat_vol_qa('cat12',Yp0,Po,Ym,res[,opt]) +% +% +% Pp0 - segmentation files (p0*.nii) +% Po - original files (*.nii) +% Pm - modified files (m*.nii) +% Yp0 - segmentation image matrix +% Ym - modified image matrix +% +% opt = parameter structure +% opt.verb = verbose level [ 0=nothing | 1=points | 2*=times ] +% opt.redres = resolution in mm for intensity scaling [ 4* ]; +% opt.write_csv = final cms-file +% opt.write_xml = images base xml-file +% opt.sortQATm = sort QATm output +% opt.orgval = original QAM results (no marks) +% opt.recalc = +% opt.avgfactor = +% opt.prefix = prefix of xml output file (default cat_*.xml) +% +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (http://www.neuro.uni-jena.de) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% +% $Id: cat_vol_qa.m 2001 2022-06-17 20:40:16Z dahnke $ +% ______________________________________________________________________ + +%#ok<*ASGLU> + + % get current release number and version + [ver_cat, rev_cat] = cat_version; + ver_cat = ver_cat(4:end); % remove leading CAT + + % init output + QAS = struct(); + QAR = struct(); + %if nargout>0, varargout = cell(1,nargout); end + + try + if strcmp(action,'cat12err') + [mrifolder, reportfolder] = cat_io_subfolders(varargin{1}.job.data,varargin{1}.job); + elseif strcmp(action,'cat12') + [mrifolder, reportfolder] = cat_io_subfolders(varargin{2},varargin{6}.job); + else + [mrifolder, reportfolder] = cat_io_subfolders(varargin{4}.catlog,varargin{6}.job); + end + catch + mrifolder = 'mri'; + reportfolder = 'report'; + end + + % no input and setting of default options + action2 = action; + if nargin==0, action='p0'; end + if isstruct(action) + if isfield(action,'model') + if isfield(action.model,'catp0') + Po = action.images; + Pp0 = action.model.catp0; + if numel(Po)~=numel(Pp0) && numel(Pp0)==1 + Pp0 = repmat(Pp0,numel(Po),1); + end + Pm = action.images; + action.data = Pp0; + end + end + if isfield(action,'data') + Pp0 = action.data; + end + action = 'p0'; + end + if nargin>1 && isstruct(varargin{end}) && isstruct(varargin{end}) + opt = cat_check('checkinopt',varargin{end},defaults); + nopt = 1; + else + if isstruct(action2) + opt = cat_check('checkinopt',action2.opts,defaults); + else + opt = defaults; + end + nopt = 0; + end + + % check input by action + switch action + case {'p0','p0+'} + % segment image cases + if nargin<=3 && ( ~exist('Pp0','var') || isempty(Pp0) ) + if (nargin-nopt)<2 + Pp0 = cellstr(spm_select(inf,'image',... + 'select p0-segment image',{},pwd,'^p0.*')); + if isempty(Pp0{1}), return; end + else + Pp0 = varargin{1}; + end + if numel(action)==2 + Po = Pp0; Pm = Pp0; + for fi=1:numel(Pp0) + [pp,ff,ee] = spm_fileparts(Pp0{fi}); + [ppa,ppb] = spm_fileparts(pp); + if strcmp(ppb,'mri'), ppo = ppa; else, ppo = pp; end + + Po{fi} = fullfile(ppo,[ff(3:end) ee]); + Pm{fi} = fullfile(pp,[opt.mprefix ff(3:end) ee]); + %Pmv{fi} = fullfile(pp,['m' ff(3:end) ee]); %#ok + %if ~exist(Pm{fi},'file') && strcmp(opt.mprefix,'nm') && exist(Pmv{fi},'file') + % fprintf('Preparing %s.\n',Pmv{fi}); + % cat_vol_sanlm(Pmv{fi},'n'); + %end + + % if ~exist(Po{fi},'file'), Po{fi}=''; end + if ~exist(Pm{fi},'file'), Pm{fi}=''; end + end + else + Po = cellstr(spm_select(repmat(numel(Pp0),1,2),... + 'image','select original image(s)',{},pwd,'.*')); + Pm = cellstr(spm_select(repmat(numel(Pp0),1,2),... + 'image','select modified image(s)',{},pwd,'.*')); + end + elseif nargin<=5 && ( ~exist('Pp0','var') || isempty(Pp0) ) + Pp0 = varargin{1}; + Po = varargin{2}; + Pm = varargin{3}; + elseif ( ~exist('Pp0','var') || isempty(Pp0) ) + error('MATLAB:cat_vol_qa:inputerror',... + 'Wrong number/structure of input elements!'); + end + case {'p#','c#','*#','p#+','c#+','*#+'} + % tissue class image cases + if nargin-1<=2 % GUI + if (nargin-nopt)<2 + if action(1)=='p' || action(1)=='c' + % cat/spm case + Pcsf = cellstr(spm_select(inf,'image',... + 'select p1-segment image',{},pwd,['^' action(1) '1.*'])); + if isempty(Pcsf{1}), return; end + Pgm=Pcsf; Pwm=Pcsf; + for fi=1:numel(Pcsf) + [pp,ff,ee] = spm_fileparts(Pcsf{fi}); + + Pgm{fi} = fullfile(pp,[action(1) '2' ff(3:end) ee]); + Pwm{fi} = fullfile(pp,[action(1) '3' ff(3:end) ee]); + end + else + Pcsf = cellstr(spm_select(inf,'image',... + 'select CSF segment image(s)',{},pwd,'.*')); + if isempty(Pcsf{1}), return; end + %Pgm = cellstr(spm_select(repmat(numel(Pcsf),1,2),... + % 'image','select GM segment image(s)',{},pwd,'.*')); + %Pwm = cellstr(spm_select(repmat(numel(Pcsf),1,2),... + % 'image','select WM segment image(s)',{},pwd,'.*')); + end + if numel(action)==2 + Pp0=Pcsf; Po=Pcsf; Pm=Pcsf; + for fi=1:numel(Pcsf) + [pp,ff,ee] = spm_fileparts(Pcsf{fi}); + Po{fi} = fullfile(pp,[ff(3:end) ee]); + Pm{fi} = fullfile(pp,['m' ff(3:end) ee]); + Pp0{fi} = fullfile(pp,['p0' ff(3:end) ee]); + end + else + Po = cellstr(spm_select(repmat(numel(Pcsf),1,2),... + 'image','select original image(s)',{},pwd,'.*')); + Pm = cellstr(spm_select(repmat(numel(Pcsf),1,2),... + 'image','select modified image(s)',{},pwd,'.*')); + Pp0=Pcsf; + for fi=1:numel(Pcsf) + [pp,ff,ee] = spm_fileparts(Pcsf{fi}); + Pp0{fi} = fullfile(pp,['p0' ff(3:end) ee]); + end + end + + % wie komm ich zum p0??? + else + Pp0 = varargin{1}; + end + elseif nargin==5 || nargin==6 + else + error('MATLAB:cat_vol_qa:inputerror',... + 'Wrong number/structure of input elements!'); + end + + Yp0 = 1; + case 'cat12err' + opt = cat_check('checkinopt',varargin{end},defaults); + case 'cat12' + % CAT12 internal input + if nargin>3 + Yp0 = varargin{1}; +% Octave is starting with many warning messages here ... +% if strcmpi(spm_check_version,'octave'), warning off; end + Vo = spm_vol(varargin{2}); +% if strcmpi(spm_check_version,'octave'), warning on; end + Yo = single(spm_read_vols(Vo)); + Ym = varargin{3}; + res = varargin{4}; + V = res.image; + species = varargin{5}; + if isfield(varargin{6},'qa') + if isfield(varargin{6}.qa,'software') && isfield(varargin{6}.qa.software,'version_segment'), QAS.software.version_segment = varargin{6}.qa.software.version_segment; end + if isfield(varargin{6}.qa,'qualitymeasures'), QAS.qualitymeasures = cat_io_updateStruct(QAS,varargin{6}.qa.qualitymeasures); end + if isfield(varargin{6}.qa,'subjectmeasures'), QAS.subjectmeasures = cat_io_updateStruct(QAS,varargin{6}.qa.subjectmeasures); end + end + % opt = varargin{end} in line 96) +% opt.verb = 0; + + % reduce to original native space if it was interpolated + sz = size(Yp0); + if any(sz(1:3)~=Vo.dim(1:3)) + if isfield(Vo,'private'), Vo = rmfield(Vo,'private'); end + if isfield(Vo,'mat0'), Vo = rmfield(Vo,'mat0'); end + Vo.dat = zeros(Vo.dim,'single'); Vo.dt(1) = 16; Vo.pinfo = [1;0;0]; + + Vp0t = res.image; + if isfield(Vp0t,'private'), Vp0t = rmfield(Vp0t,'private'); end + if isfield(Vp0t,'mat0'), Vp0t = rmfield(Vp0t,'mat0'); end + Vp0t.dt(1) = 16; + Vp0t.pinfo = [1;0;0]; + Vp0t.dat = Yp0; + + % resampling and corrections of the Yp0 + % Vp0t = spm_write_vol(Vp0t,double(Yp0)); + [Vtpm,Yp0] = cat_vol_imcalc(Vp0t,Vo,'i1',struct('interp',2,'verb',0)); + rf = 50; + Yp0 = single(Yp0); + Yp0r = round(Yp0*rf)/rf; + YMR = false(size(Yp0)); + for i=1:4, YMR = YMR | (Yp0>(i-1/rf) & Yp0<(i+1/rf)); end + Yp0(YMR) = Yp0r(YMR); clear YMR Ynr; + + % resampling of the corrected image + Vp0t.dat = Ym; + [Vtpm,Ym] = cat_vol_imcalc(Vp0t,Vo,'i1',struct('interp',6,'verb',0)); + Ym = single(Ym); + end + + else + error('MATLAB:cat_vol_qa:inputerror',... + 'Wrong number/structure of input elements!'); + end + otherwise + error('MATLAB:cat_vol_qa:inputerror',... + 'Wrong number/structure of input elements!'); + end + if ~exist('species','var'), species='human'; end + + + % + % -------------------------------------------------------------------- + [QA,QMAfn] = cat_stat_marks('init'); + stime = clock; + stime2 = clock; + + + + % Print options + % -------------------------------------------------------------------- + opt.snspace = [70,7,3]; + opt.snspace = [100,7,3]; + Cheader = {'scan'}; + Theader = sprintf(sprintf('%%%ds:',opt.snspace(1)-1),'scan'); + Tline = sprintf('%%5d) %%%ds:',opt.snspace(1)-8); + Tline2 = sprintf('%%5d) %%6s%%%ds:',opt.snspace(1)-14); + Tavg = sprintf('%%%ds:',opt.snspace(1)-1); + TlineE = sprintf('%%5d) %%%ds: %%s',opt.snspace(1)-7); + for fi=1:numel(QMAfn) + Cheader = [Cheader QMAfn{fi}]; %#ok + Theader = sprintf(sprintf('%%s%%%ds',opt.snspace(2)),Theader,... + QMAfn{fi}(1:min(opt.snspace(2)-1,numel(QMAfn{fi})))); + Tline = sprintf('%s%%%d.%df',Tline,opt.snspace(2),opt.snspace(3)); + Tline2 = sprintf('%s%%%d.%df',Tline2,opt.snspace(2),opt.snspace(3)); + Tavg = sprintf('%s%%%d.%df',Tavg,opt.snspace(2),opt.snspace(3)); + end + Cheader = [Cheader 'IQR']; + Theader = sprintf(sprintf('%%s%%%ds',opt.snspace(2)),Theader,'IQR'); + Tline = sprintf('%s%%%d.%df',Tline,opt.snspace(2),opt.snspace(3)); + Tline2 = sprintf('%s%%%d.%df',Tline2,opt.snspace(2),opt.snspace(3)); + Tavg = sprintf('%s%%%d.%df',Tavg,opt.snspace(2),opt.snspace(3)); + Cheader = [Cheader 'SIQR']; + Theader = sprintf(sprintf('%%s%%%ds',opt.snspace(2)),Theader,'SIQR'); + Tline = sprintf('%s%%%d.%df%%s\n',Tline,opt.snspace(2),opt.snspace(3)); + Tline2 = sprintf('%s%%%d.%df\n',Tline2,opt.snspace(2),opt.snspace(3)); + Tavg = sprintf('%s%%%d.%df\n',Tavg,opt.snspace(2),opt.snspace(3)); + + + + + + % estimation part + switch action + case {'p0','p#','c#','*#','p0+','p#+','c#+','*#+'} + % loop for multiple files + % return for empty input + if isempty(Pp0) || (isempty(Pp0{1}) && numel(Pp0)<=1) + cat_io_cprintf('com','No images for QA!\n'); + return + end + + if opt.verb>1 + fprintf('\n%s\n\n%s\n%s\n', ... + sprintf('CAT Preprocessing T1 Quality Control (%s):',... + sprintf('Rev: %s',rev_cat)), Theader,repmat('-',size(Theader))); + end + + qamat = nan(numel(Po),numel(QMAfn)); + qamatm = nan(numel(Po),numel(QMAfn)); + mqamatm = 10.5*ones(numel(Po),2); + + + QAS = struct(); QAR = struct(); + QAR.mark2rps = @(mark) min(100,max(0,105 - mark*10)) + isnan(mark).*mark; + + for fi=1:numel(Pp0) + + try + stime = cat_io_cmd(' Any segmentation Input:','g5','',opt.verb>2); + + [pp,ff,ee] = spm_fileparts(Po{fi}); + if exist(fullfile(pp,[ff ee]),'file') + Vo = spm_vol(Po{fi}); + elseif exist(fullfile(pp,[ff ee '.gz']),'file') + gunzip(fullfile(pp,[ff ee '.gz'])); + Vo = spm_vol(Po{fi}); + delete(fullfile(pp,[ff ee '.gz'])); + else + error('cat_vol_qa:noYo','No original image.'); + end + + if opt.rerun || cat_io_rerun(Vo.fname, fullfile(pp,reportfolder,[opt.prefix ff '.xml']) , 0 ) + Vm = spm_vol(Pm{fi}); + Vp0 = spm_vol(Pp0{fi}); + if any(Vp0.dim ~= Vm.dim) + [Vx,Yp0] = cat_vol_imcalc(Vp0,Vm,'i1',struct('interp',2,'verb',0)); + else + Yp0 = single(spm_read_vols(Vp0)); + end + Yp0(isnan(Yp0) | isinf(Yp0)) = 0; + if ~isempty(Pm{fi}) && exist(Pm{fi},'file') + Ym = single(spm_read_vols(spm_vol(Pm{fi}))); + Ym(isnan(Yp0) | isinf(Yp0)) = 0; + elseif 1 %end + stime = cat_io_cmd(' Optimize Segmentation:','g5','',opt.verb>3,stime); + + %if ~exist(Ym,'var') || round( cat_stat_nanmean(Ym(round(Yp0)==3)) * 100) ~= 100 + Ym = single(spm_read_vols(spm_vol(Po{fi}))); + Ym(isnan(Yp0) | isinf(Yp0)) = 0; + + vx_vol = sqrt(sum(Vm.mat(1:3,1:3).^2)); + [Ymr,Yp0r,resR] = cat_vol_resize({Ym,Yp0} ,'reduceV' ,vx_vol,1.7,32,'meanm'); % CSF thr. (minimum to avoid PVE) + Yw = Yp0r>2.95 | cat_vol_morph( Yp0r>2.25 , 'e'); + Ywi = Ymr .* Yw + Yw .* min(Ymr(:)); + % added the estimation of the local variance to + Yws = cat_vol_localstat(Ywi,Ywi~=0,1,4); + Yws = cat_vol_localstat(Yws./Ywi,Yws~=0,1,1); + Yw = (Yw & Yws0))*2) | cat_vol_morph( Yp0r>2.25 , 'e' ,2); + Ywi = Ymr .* Yw + Yw .* min(Ymr(:)); + Yb = cat_vol_approx( Ywi ) - min(Ymr(:)); + Yb = cat_vol_resize(Yb ,'dereduceV' ,resR); % CSF thr. (minimum to avoid PVE) + + %Yb = Yb / mean(Ym(Yw(:))); + Ym = Ym ./ max(eps,Yb) .* (Ym~=0); + + else + error('cat_vol_qa:noYm','No corrected image.'); + end + rmse = (mean(Ym(Yp0(:)>0) - Yp0(Yp0(:)>0)/3).^2).^0.5; + if rmse>0.2 + cat_io_cprintf('warn',sprintf(' Segmentation is maybe not fitting to the image (RMSE(Ym,Yp0)=%0.2f)?:\n %s\n %s\n',rmse,Pm{fi},Pp0{fi})); + end + else + Yp0 = false(Vo.dim); + Ym = Yp0; + end + res.image = spm_vol(Pp0{fi}); + [QASfi,QAMfi] = cat_vol_qa202207b('cat12',Yp0,Vo,Ym,res,species,opt); + + if isnan(QASfi.qualitymeasures.NCR) + fprintf(''); + end + + try + QAS = cat_io_updateStruct(QAS,QASfi,0,fi); + QAR = cat_io_updateStruct(QAR,QAMfi,0,fi); + catch + fprintf('ERROR-Struct'); + end + + % color for the differen mark cases (opt.process) + for fni=1:numel(QMAfn) + qamat(fi,fni) = QAS(fi).qualitymeasures.(QMAfn{fni}); + qamatm(fi,fni) = QAR(fi).qualityratings.(QMAfn{fni}); + end + mqamatm(fi,1) = QAR(fi).qualityratings.IQR; + mqamatm(fi,1) = max(0,min(10.5, mqamatm(fi,1))); + mqamatm(fi,2) = QAR(fi).qualityratings.SIQR; + mqamatm(fi,2) = max(0,min(10.5, mqamatm(fi,2))); + + + %% print the results for each scan + if opt.verb>1 + if opt.rerun || cat_io_rerun(Vo.fname, fullfile(pp,reportfolder,[opt.prefix ff '.xml']) , 0 ) + rerun = ' updated'; + elseif exist( fullfile(pp,reportfolder,[opt.prefix ff '.xml']) , 'file') + rerun = ' loaded'; + else + rerun = ' '; % new + end + + if opt.orgval + cat_io_cprintf(opt.MarkColor(max(1,floor( mqamatm(fi,2)/9.5 * ... + size(opt.MarkColor,1))),:),sprintf(Tline,fi,... + QAS(fi).filedata.fnames, ... spm_str_manip(QAS(fi).filedata.file,['f' num2str(opt.snspace(1) - 14)]),... + qamat(fi,:),max(1,min(9.5,mqamatm(fi,:))),rerun)); + else + cat_io_cprintf(opt.MarkColor(max(1,floor( mqamatm(fi,2)/9.5 * ... + size(opt.MarkColor,1))),:),sprintf(Tline,fi,... + QAS(fi).filedata.fnames, ... spm_str_manip(QAS(fi).filedata.file,['f' num2str(opt.snspace(1) - 14)]),... + qamatm(fi,:),max(1,min(9.5,mqamatm(fi,:))),rerun)); + end + end + catch %#ok ... normal ""catch err"" does not work for MATLAB 2007a + try %#ok + e = lasterror; %#ok ... normal ""catch err"" does not work for MATLAB 2007a + + switch e.identifier + case {'cat_vol_qa:noYo','cat_vol_qa:noYm','cat_vol_qa:badSegmentation'} + em = e.identifier; + otherwise + em = ['ERROR:\n' repmat(' ',1,10) e.message '\n']; + for ei=1:numel(e.stack) + em = sprintf('%s%s%5d: %s\n',em,repmat(' ',1,10),... + e.stack(ei).line(end),e.stack(ei).name); + end + end + + [pp,ff] = spm_fileparts(Po{fi}); + QAS(fi).filedata.fnames = [spm_str_manip(pp,sprintf('k%d',floor( (opt.snspace(1)-19) /3) - 1)),'/',... + spm_str_manip(ff,sprintf('k%d',(opt.snspace(1)-19) - floor((opt.snspace(1)-14)/3)))]; + cat_io_cprintf(opt.MarkColor(end,:),sprintf(TlineE,fi,Pp0{fi},[em '\n'])); +% spm_str_manip(Po{fi},['f' num2str(opt.snspace(1) - 14)]),em)); + end + end + end + + + + % sort by mean mark + % ---------------------------------------------------------------- + if opt.sortQATm && numel(Po)>1 + % sort matrix + [smqamatm,smqamatmi] = sort(mqamatm(:,2),'ascend'); + sqamatm = qamatm(smqamatmi,:); + sqamat = qamat(smqamatmi,:); + + % print matrix + if opt.verb>0 + fprintf('%s\n',repmat('-',size(Theader))); + for fi=1:numel(QAS) + if opt.orgval + cat_io_cprintf(opt.MarkColor(max(1,min(size(opt.MarkColor,1),... + round( mqamatm(smqamatmi(fi),2)/9.5 * ... + size(opt.MarkColor,1)))),:),sprintf(... + Tline2,fi,sprintf('(%d)',smqamatmi(fi)),... + spm_str_manip(Pp0{fi},'l80'), ...QAS(smqamatmi(fi)).filedata.fnames, ... + ...spm_str_manip(QAS(smqamatmi(fi)).filedata.file,['f' num2str(opt.snspace(1) - 14)]),... + sqamat(fi,:),max(1,min(10.5,mqamatm(smqamatmi(fi),:))))); + else + cat_io_cprintf(opt.MarkColor(max(1,min(size(opt.MarkColor,1),... + round( mqamatm(smqamatmi(fi),2)/9.5 * ... + size(opt.MarkColor,1)))),:),sprintf(... + Tline2,fi,sprintf('(%d)',smqamatmi(fi)),... + spm_str_manip(Pp0{fi},'l80'), ... QAS(smqamatmi(fi)).filedata.fnames, ... + ...spm_str_manip(QAS(smqamatmi(fi)).filedata.file,['f' num2str(opt.snspace(1) - 14)]),... + sqamatm(fi,:),mqamatm(smqamatmi(fi),:))); + end + end + end + else + %[smqamatm,smqamatmi] = sort(mqamatm,'ascend'); + %sqamatm = qamatm(smqamatmi,:); + end + % print the results for each scan + if opt.verb>1 && numel(Pp0)>1 + fprintf('%s\n',repmat('-',size(Theader))); + if opt.orgval + fprintf(Tavg,'mean',cat_stat_nanmean(qamat,1), cat_stat_nanmean(mqamatm,1)); %#ok + fprintf(Tavg,'std' , cat_stat_nanstd(qamat,1), cat_stat_nanstd(mqamatm,1)); %#ok + else + fprintf(Tavg,'mean',cat_stat_nanmean(qamatm,1), cat_stat_nanmean(mqamatm,1)); %#ok + fprintf(Tavg,'std' , cat_stat_nanstd(qamatm,1), cat_stat_nanstd(mqamatm,1)); %#ok + end + %fprintf('%s\n',repmat('-',size(Theader))); + %fprintf(Tavg,'mean',mean(qamat,1)); + %fprintf(Tavg,'std', std(qamat,1)); + end + if opt.verb>0, fprintf('\n'); end + + + + % result tables (cell structures) + % ---------------------------------------------------------------- + if nargout>2 && opt.write_csv + QAT = [Cheader(1:end-1); ... there is no mean for the original measures + Po , num2cell(qamat); ... + 'mean' , num2cell(cat_stat_nanmean(qamat,1)); ... + 'std' , num2cell( cat_stat_nanstd(qamat,1,1))]; + QATm = [Cheader; ... + Po , num2cell(qamatm) , ... + num2cell(cat_stat_nanmean(qamatm,2)); ... + 'mean' , num2cell(cat_stat_nanmean(qamatm,1)) , ... + num2cell(cat_stat_nanmean(mqamatm,1)); ... + 'std' , num2cell( cat_stat_nanstd(qamatm,1,1)), ... + num2cell( cat_stat_nanstd(mqamatm,1))]; + + + % write csv results + % -------------------------------------------------------------- + if opt.write_csv + pp = spm_fileparts(Pp0{1}); + cat_io_csv(fullfile(pp,reportfolder,[opt.prefix num2str(numel(Vo),'%04d') ... + 'cat_vol_qa_values.csv']),QAT); + cat_io_csv(fullfile(pp,reportfolder,[opt.prefix num2str(numel(Vo),'%04d') ... + 'cat_vol_qa_marks.csv']),QATm); + end + end + + if opt.verb>0 + fprintf('Quality Control for %d subject was done in %0.0fs\n', ... + numel(Pp0),etime(clock,stime)); fprintf('\n'); + end + + + case 'cat12err' + stime = clock; + + % file information + % ---------------------------------------------------------------- + [pp,ff,ee] = spm_fileparts(opt.job.channel.vols{opt.subj}); + [QAS.filedata.path,QAS.filedata.file] = spm_fileparts(opt.job.channel.vols{opt.subj}); + QAS.filedata.fname = opt.job.data{opt.subj}; + QAS.filedata.F = opt.job.data{opt.subj}; + QAS.filedata.Fm = fullfile(pp,mrifolder,['m' ff ee]); + QAS.filedata.Fp0 = fullfile(pp,mrifolder,['p0' ff ee]); + QAS.filedata.fnames = [spm_str_manip(pp,sprintf('k%d',... + floor( max(opt.snspace(1)-19-ff,opt.snspace(1)-19)/3) - 1)),'/',... + spm_str_manip(ff,sprintf('k%d',... + (opt.snspace(1)-19) - floor((opt.snspace(1)-14)/3)))]; + + + % software, parameter and job information + % ---------------------------------------------------------------- + [nam,rev_spm] = spm('Ver'); + QAS.software.version_spm = rev_spm; + if strcmpi(spm_check_version,'octave') + QAS.software.version_octave = version; + else + A = ver; + for i=1:length(A) + if strcmp(A(i).Name,'MATLAB') + QAS.software.version_matlab = A(i).Version; + end + end + clear A + end + % 1 line: Matlab, SPM12, CAT12 version number and GUI and experimental mode + if ispc, OSname = 'WIN'; + elseif ismac, OSname = 'MAC'; + else OSname = 'LINUX'; + end + + QAS.software.system = OSname; + QAS.software.version_cat = ver_cat; + if ~isfield(QAS.software,'version_segment') + QAS.software.version_segment = rev_cat; + end + QAS.software.revision_cat = rev_cat; + try + QAS.hardware.numcores = max(cat_get_defaults('extopts.nproc'),1); + catch + QAS.hardware.numcores = 1; + end + + + % save important preprocessing parameter + % remove LAS + QAS.parameter.opts = opt.job.opts; + QAS.parameter.extopts = rmfield(opt.job.extopts,... + {'LAB','atlas','satlas','darteltpms','shootingtpms','fontsize'}); + %QAS.parameter.output = opt.job.output; + QAS.parameter.caterr = opt.caterr; + QAS.error = opt.caterrtxt; + + % export + if opt.write_xml + cat_io_xml(fullfile(pp,reportfolder,[opt.prefix ff '.xml']),QAS,'write'); + end + + case 'cat12' + % estimation of the measures for the single case + +[pp,ff,ee] = spm_fileparts(Vo.fname); +if opt.rerun || cat_io_rerun(Vo.fname, fullfile(pp,reportfolder,[opt.prefix ff '.xml']) , 0 ) + stime = cat_io_cmd(' Main:','g5','',opt.verb>3,stime); + + % file information + % ---------------------------------------------------------------- + [pp,ff,ee] = spm_fileparts(Vo.fname); +% if strcmpi(spm_check_version,'octave'), warning off; end + [QAS.filedata.path,QAS.filedata.file] = spm_fileparts(Vo.fname); + QAS.filedata.fname = char(Vo.fname); + QAS.filedata.F = char(Vo.fname); +% if strcmpi(spm_check_version,'octave'), warning on; end +% if strcmpi(spm_check_version,'octave'), warning off; end + QAS.filedata.Fm = fullfile(pp,mrifolder,['m' ff ee]); + QAS.filedata.Fp0 = fullfile(pp,mrifolder,['p0' ff ee]); +% if strcmpi(spm_check_version,'octave'), warning on; end + QAS.filedata.fnames = [spm_str_manip(pp,sprintf('k%d',... + floor( max(opt.snspace(1)-19-ff,opt.snspace(1)-19)/3) - 1)),'/',... + spm_str_manip(ff,sprintf('k%d',... + (opt.snspace(1)-19) - floor((opt.snspace(1)-14)/3)))]; + + + % software, parameter and job information + % ---------------------------------------------------------------- + [nam,rev_spm] = spm('Ver'); + if ispc, OSname = 'WIN'; + elseif ismac, OSname = 'MAC'; + else OSname = 'LINUX'; + end + + QAS.software.system = char(OSname); + QAS.software.version_spm = rev_spm; + if strcmpi(spm_check_version,'octave') + QAS.software.version_matlab = ['Octave ' version]; + else + A = ver; + for i=1:length(A) + if strcmp(A(i).Name,'MATLAB') + QAS.software.version_matlab = A(i).Version; + end + end + clear A + end + QAS.software.version_cat = ver_cat; + if ~isfield(QAS.software,'version_segment') + QAS.software.version_segment = rev_cat; + end + QAS.software.revision_cat = rev_cat; + QAS.software.function = which('cat_vol_qa'); + QAS.software.markdefs = which('cat_stat_marks'); + QAS.software.qamethod = action; + QAS.software.date = datestr(clock,'yyyymmdd-HHMMSS'); + % RD202007: not requried + %{ + %warning off + %QAS.software.opengl = opengl('INFO'); + %QAS.software.opengldata = opengl('DATA'); + %warning on + %} + QAS.software.cat_warnings = cat_io_addwarning; + % replace matlab newlines by HTML code + for wi = 1:numel( QAS.software.cat_warnings ) + QAS.software.cat_warnings(wi).message = cat_io_strrep( QAS.software.cat_warnings(wi).message , {'\\n', '\n'} , {'
','
'} ); + end + + %QAS.parameter = opt.job; + if isfield(opt,'job') && isfield(opt.job,'opts'), QAS.parameter.opts = opt.job.opts; end + if isfield(opt,'job') && isfield(opt.job,'extopts'), QAS.parameter.opts = opt.job.extopts; end + if exist('res','var') + rf = {'Affine','Affine0','lkp','mn','vr','ll'}; % important SPM preprocessing variables + for rfi=1:numel(rf) + if isfield(res,rf{rfi}), QAS.SPMpreprocessing.(rf{rfi}) = res.(rf{rfi}); end + end + end + + + %% resolution, boundary box + % --------------------------------------------------------------- + vx_vol = sqrt(sum(Vo.mat(1:3,1:3).^2)); + vx_voli = sqrt(sum(V.mat(1:3,1:3).^2)); + Yp0toC = @(Yp0,c) 1-min(1,abs(Yp0-c)); + + % resolution + QAS.qualitymeasures.res_vx_vol = vx_vol; + if 1 % CAT internal resolution + QAS.qualitymeasures.res_vx_voli = vx_voli; + end + QAS.qualitymeasures.res_RMS = cat_stat_nanmean(vx_vol.^2).^0.5; + % further unused measure (just for test/comparison) + %QAS.qualitymeasures.res_isotropy = max(vx_vol)./min(vx_vol); + %QAS.qualitymeasures.res_vol = prod(abs(vx_vol)); + %QAS.qualitymeasures.res_MVR = mean(vx_vol); + + %% boundary box - brain tissue next to image boundary + % RD20220415: + % * Although it is quite rare that the boundary box is to small and the + % brain scan is incomplete, it is of course essential to detect such + % cases: see OpenNeuro:BEANstudy: https://openneuro.org/datasets/ds003877/versions/1.0.1 + % * In addition, inhomogeneities close to image boundaries can be a + % severe problem that can be seen only be trained experts. The bias + % can even result a distorted cortex-like structure with normal + % thickness values. + % * need some tests +%{ + Ybw = cat_vbdist(single(Yp0<0.5),true(size(Yp0)),vx_vol) - ... + cat_vbdist(single(Yp0>0.5),true(size(Yp0)),vx_vol); + Ybb = Ybw>0 & Ybw<2*mean(vx_vol); sumYbb = sum(Ybb(:)); % use the brain boundary for normalization + M = ones(size(Yp0),'single'); + dmm = [10 5]; % inner and outer boundary range in mm + Ybw = max(0,Ybw + dmm(2)); % in mm + for bbth = 1:ceil( dmm(1) / cat_stat_nanmean(vx_vol) ) + M(bbth:end-bbth+1,bbth:end-bbth+1,bbth:end-bbth+1) = ... + 2 * (floor( dmm(1) / cat_stat_nanmean(vx_vol) ) - bbth + 1) / floor( dmm(1) / cat_stat_nanmean(vx_vol) ); + end + QAS.qualitymeasures.res_BB = sum( (1+Yp0(:)) .* Ybw(:) .* M(:)) / sumYbb * prod(abs(vx_vol)); +%} + + %% check segmentation + spec = species; for ai=num2str(0:9); spec = strrep(spec,ai,''); end + bvol = species; for ai=char(65:122); bvol = strrep(bvol,ai,''); end; bvol = str2double(bvol); + + subvol = [sum(Yp0(:)>2.5 & Yp0(:)<3.1)*prod(vx_vol)/1000,... + sum(Yp0(:)>1.5 & Yp0(:)<2.5)*prod(vx_vol)/1000,... + sum(Yp0(:)>0.5 & Yp0(:)<1.5)*prod(vx_vol)/1000]; + + if isempty(bvol) + switch spec + case 'human' + bvol = 1400; + otherwise + warning('cat_vol_qa:species',... + sprintf('Unknown species %s (C=%0.0f,G=%0.0f,W=%0.0f).',species,subvol)); %#ok + end + end + if sum(subvol)bvol*3 + warning('cat_vol_qa:badSegmentation',... + sprintf('Bad %s segmentation (C=%0.0f,G=%0.0f,W=%0.0f).',species,subvol)) %#ok + end + if ~isfield(QAS,'subjectmeasures') + %% in case of external/batch calls + QAS.subjectmeasures.vol_TIV = sum(Yp0(:)>0) ./ prod(vx_vol) / 1000; + for i = 1:3 + QAS.subjectmeasures.vol_abs_CGW(i) = sum( Yp0toC(Yp0(:),i)) ./ prod(vx_vol) / 1000; + QAS.subjectmeasures.vol_rel_CGW(i) = QAS.subjectmeasures.vol_abs_CGW(i) ./ ... + QAS.subjectmeasures.vol_TIV; + end + end + + %% estimate QA + % --------------------------------------------------------------- + % remove space arount the brain for speed-up + [Yo,Ym,Yp0] = cat_vol_resize({Yo,Ym,Yp0},'reduceBrain',vx_vol,4,Yp0>1.5); + + %Yp0o = Yp0; + stime = cat_io_cmd(' Optimize Segmentation:','g5','',opt.verb>3,stime); + + % detection and correct for noisy segmentation problems (RD20220705) + Yp0r = cat_vol_resize( min(3,max(0,Yp0)) ,'reduceV',vx_vol,3,32,'mean'); + noisep0 = max(0,min(2,cat_stat_nanstd(Yp0r(cat_vol_morph(Yp0r>2.2,'e'))))); clear Yp0r + if noisep0 > 0.1 + if noisep0 > 0.5 + Yp0 = Yp0*(1 - min(1,noisep0*2)) + min(1,noisep0*2) * smooth3(Yp0); + end + Yp0 = cat_vol_median3( Yp0 ,Yp0>0.2 & Yp0~=round(Yp0)); + Yp0 = min( 3 , max( 0 , Yp0 ) ); + % update skull-stripping to avoid holes + [Yp0r,Ymr,resV] = cat_vol_resize( { Yp0 , Ym } ,'reduceV',vx_vol,3,32,'meanm'); + Yp0r = smooth3(cat_vol_morph( Yp0r > 0.2 , 'lc',6) & Ymr<2/3 & Ymr>0); + Yp0r = cat_vol_resize(Yp0r,'dereduceV',resV); + Yp0 = min( 3 * (Ym>0 & Ym<1.5), max( Yp0r , Yp0 )) .* ... + ~((Yp0==0 | Yp0==1) & (Ym==0 | Yo==0) ); % update Yp0 but be careful with masked voxels + clear Yp0r Ymr; + end + +% WMHs? + % fast skull-stripping to remove possible head tissues + stime = cat_io_cmd(' Optimize Segmentation - Skull-Stripping:','g5','',opt.verb>3,stime); + [Yp0r,Ymr,Yor,resV] = cat_vol_resize({Yp0,Ym,Yo},'reduceV',vx_vol,3,32,'meanm'); % CSF thr. (minimum to avoid PVE) + Ybr = cat_vol_morph( Yp0r > 2.5 , 'l',[0.3 3]); % find biggest WM elements + Ybr = cat_vol_morph( Ybr , 'o',1); % opening of WM tissue to seperate skull + if ( sum(Ybr(:)) / sum(Yp0r(:)>2.5) ) < 0.5 % if the opening is to aggressive then undo it + Ybr = Yp0r > 2.5; + end + Ybr = cat_vol_morph( Ybr , 'l',[0.2 3]); % find biggest WM elements + Ybr = Ybr | ( cat_vol_morph( Ybr , 'd',2) & Yp0r>1.5 & Yp0r<=2); % add GM + Ybr = cat_vol_morph( Ybr , 'lc',5); % final closing + Yb = cat_vol_resize(Ybr,'dereduceV',resV); % go back to original resolution and apply masking + Yp0 = Yp0 .* (Yb & ~( (Yp0==0 | Yp0==1) & (Ym==0 | Yo==0) )); % update Yp0 but be careful with masked voxels + Yp0r = Yp0r .* (Ybr & ~( (Yp0r==0 | Yp0r==1) & (Ymr==0 | Yor==0) )); + + + % rought contast and noise estimation to get a stable T1 map for threshold estimation + T1th = [cat_stat_kmeans(Ymr(Yp0toC(Yp0r(:),1)>0.9)) ... + cat_stat_kmeans(Ymr(Yp0toC(Yp0r(:),2)>0.9)) ... + cat_stat_kmeans(Ymr(Yp0toC(Yp0r(:),3)>0.9))]; + noise = max(0,min(1,cat_stat_nanstd(Ymr(cat_vol_morph(Yp0r>2.1,'e') | Yp0r>2.9)) / min(abs(diff(T1th))))); + + + % smoothing to reduce high frequency noise + stime = cat_io_cmd(' Denoise & gradients:','g5','',opt.verb>3,stime); + Yms = Ym+0; spm_smooth(Yms,Yms,repmat(double(noise)*4,1,3)); + Ygrad = cat_vol_grad(max(2/3,min(1,Yms) .* (Yp0>0)) , vx_vol ); + + +if 1 + % general reduction of image size to avoid to high processing time in + % case of high-resolution data. + res = 1.8; + Ymsk = cat_vol_resize( (Yp0==0 | Yp0==1) & (abs(Ym)<0.01 | abs(Yo)<0.01) & Ygrad == 0 ,'reduceV' ,vx_vol,res,32,'meanm')>0; + Ymsk = cat_vol_morph( cat_vol_morph( Ymsk ,'o') ,'d',1); + [Ygrad,resI] = cat_vol_resize(Ygrad,'reduceV' ,vx_vol,res,32,'meanm'); % CSF thr. (minimum to avoid PVE) + Yo = cat_vol_resize(Yo,'reduceV' ,vx_vol,res,32,'meanm'); % CSF thr. (minimum to avoid PVE) + Ym = cat_vol_resize(Ym,'reduceV' ,vx_vol,res,32,'meanm'); % GM thr. + Yms = cat_vol_resize(Yms,'reduceV' ,vx_vol,res,32,'meanm'); % GM thr. + Yp0 = cat_vol_resize(Yp0,'reduceV',vx_vol,res,32,'meanm'); % WM thr. and bias correction (Ywme) + Ym(Ymsk) = 0; + Yp0(Ymsk) = 0; + vx_vol = resI.vx_volr; +end + + stime = cat_io_cmd(' Optimize Segmentation - Refine Segments:','g5','',opt.verb>3,stime); + %% basic tissue classes - erosion to avoid PVE, std to avoid other tissues (like WMHs) + voli = @(v) (v ./ (pi * 4./3)).^(1/3); + rad = voli( QAS.subjectmeasures.vol_TIV) ./ cat_stat_nanmean(vx_vol); + Ysc = 1-cat_vol_smooth3X(smooth3(Yp0)<0.1 | Ym==0,min(24,max(16,rad*2))); % fast 'distance' map + if T1th(1) < T1th(2) && T1th(2) < T1th(3) + Ycm = cat_vol_morph(Yp0>0.5 & Yp0<1.5 & Ym~=0 & Yms0.75 & Yp0<1.25;% avoid PVE & ventricle focus + if sum(Ycm(:)>0)<10; Ycm=cat_vol_morph(Yp0>0.5 & Yp0<1.5 & Yms0)<10; Ycm=Yp0>0.5 & Ym~=0 & Yms0)<10; Ycm=Yp0>0.5 & Yp0<1.5; end + + Ygm = round(Yp0)==2 & Ysc<0.9; %(Ygm1 | Ygm2) & Ysc<0.9; % avoid PVE & no subcortex + Ywm = cat_vol_morph(Yp0>2.1,'e') & Yp0>max(2.5,2.9-noise/2) & ... % avoid PVE & subcortex + Yms>min(cat_stat_nanmean(T1th(2:3)),(T1th(2) + 2*noise*abs(diff(T1th(2:3))))); % avoid WMHs2 + else + Ycm = cat_vol_morph(Yp0>0 & Yp0<2,'e'); + Ygm = cat_vol_morph(Yp0>1 & Yp0<3,'e') & Ysc<0.9; + Ywm = cat_vol_morph(Yp0>2 & Yp0<4,'e'); + end + + %% Ygms = cat_vol_localstat(Ym,smooth3(Ygm)>0.2,1,1,3); % dilate the GM segment by smoothing and remove noise + Ygms = cat_vol_localstat(Ym,Ygm>0.5,1,1,3); % dilate the GM segment by smoothing and remove noise % SPEED + Ygmsr = cat_vol_resize( Ygms ,'reduceV',vx_vol,3,32,'meanm'); + [a,b] = cat_stat_kmeans(Ygmsr(Ygmsr(:)~=0)); % estimate peak and local variance + Ygm = abs(Ygms - a) < max(1/12,min(1/8,b*8)) & Ysc<0.9; + + Ywi = Ym .* Ywm + Ywm .* min(Ym(:)); + % added the estimation of the local varaiance to + Yws = cat_vol_localstat(Ywi,Ywi~=0,1,4); + Yws = cat_vol_localstat(Yws./Ywi,Yws~=0,1,1); + Ywm = (Ywm & Yws0))*2) | cat_vol_morph( Yp0>2.25 , 'e' ,2); + clear Ygm1 Ygm2 Yws Ywi; % Ysc; + + % further refinements of the tissue maps + if T1th(1) < T1th(2) && T1th(2) < T1th(3) + %% + T2th = [cat_stat_kmeans(Yms(Ycm)) cat_stat_kmeans(Yms(Ygm)) cat_stat_kmeans(Yms(Ywm))]; + Ycm = Ycm & Yms>(T2th(1)-16*noise*diff(T2th(1:2))) & Ysc &... + Yms<(T2th(1)+0.1*noise*diff(T2th(1:2))); + if sum(Ycm(:)>0)<10; Ycm=cat_vol_morph(Yp0>0.5 & Yp0<1.5 & Yms0)<10; Ycm=Yp0>0.5 & Yms(T2th(2)-2*noise*abs(diff(T1th(2:3)))) & Yms<(T2th(2)+2*noise*abs(diff(T1th(2:3)))); + Ygm(smooth3(Ygm)<0.2) = 0; + end + Ycm = cat_vol_morph(Ycm,'lc'); % to avoid holes + Ywm = cat_vol_morph(Ywm,'lc'); % to avoid holes + Ywe = cat_vol_morph(Ywm,'e'); + % test necessity of erosion (RD202207) + % if the PVE is very small than its not needed (eg. WM unterestimation by the given segmenation) + % if it is huge than another erosion is required + Ywd = cat_vol_morph(Ywm,'d'); + twe = abs( cat_stat_kmeans(Ym(Ywm(:) & ~Ywe(:))) - cat_stat_kmeans(Ym(Ywd(:))) ); + if twe < 0.008 + Ywe = Ywm; Ywm = Ywd; + end + twe = abs( cat_stat_kmeans(Ym(Ywm(:) & ~Ywe(:))) - cat_stat_kmeans(Ym(Ywe(:))) ); + if twe < 0.008 + Ywe = Ywm; + elseif twe > 0.02 + Ywe = cat_vol_morph(Ywe,'e'); + end + if noisep0 > 0.1 % ########### this may also remove variance due to motion artifacts !!! ############### + %% + Ywms = cat_vol_localstat(Ym,Ywm,1,1,3); % dilate the GM segment by smoothing and remove noise + [a,b] = cat_stat_kmeans(Ywms(Ywm(:))); % estimate peak and local variance + Ywm = Ywm & abs(Ywms - a) < max(1/12,min(1/8,b*8)); + + Ywms = cat_vol_localstat(Ym,Ywe,1,1,3); % dilate the GM segment by smoothing and remove noise + [a,b] = cat_stat_kmeans(Ywms(Ywe(:))); % estimate peak and local variance + Ywe = Ywe & abs(Ywms - a) < max(1/12,min(1/8,b*8)); + clear Ywms + end + if sum(Ywe(:)) / sum(Yp0(:)>0) > 0.2 + Ywe = cat_vol_morph(Ywe,'e'); + end + if sum(Ywm(:)) / sum(Yp0(:)>0) > 0.2 + Ywm = cat_vol_morph(Ywm,'e'); + end + + +%% new resolution thing +% ------------------------------------------------------------------------- +% Although voxel resolution is a good measure in most raw data, interpolated +% or resampled data, e.g. by interpolation/resampling/reslicing or directly +% within the protocol/reconstruction process. +% Although the BWP did not ofter a direct independent solution, we can use +% any image and resample or smooth it. Real data test are highly important +% to avoid unforeseen side effects but finaly the evaluation has to take +% place also on the BWP, where the measure have to be tested for possible +% side effects of noise (could be a problem) and inhomogeneities (should +% be ok). +% - interpolate/reduce by a factor: 0.5x, 0.75x, 1.0x (low-res >= 1.0 mm) +% 1.0x, 1.50x, 2.0x (high-res <= 0.7 mm) +% - sampling to a specific resolution: 0.4, 0.6, 0.8, 1.0, 1.2 mm +% - smoothing in mm: 0.2, 0.4, 0.6, 0.8, 1.0 mm +% ------------------------------------------------------------------------- +% +% +%% A) by gradient (RD20220324) +% ------------------------------------------------------------------------- +% The basic idea is that edges in smoothed and interpolated images are +% softer/smoother and that the slope is simply smaller compared to +% sharp data. There are also the cases of to sharp images, e.g. +% binarized data like the SPM segmention with very hard partial volume +% effect. +% +% Of course there are side effects from noise but as far as we have an +% independent noise estimation we can maybe include this. +% In addition, edges beween WM and CSF are stronger and the CSF/GM +% boundary is probably blurred. Hence, we quantify only voxels at the +% WM/GM boudnary and limit also the normalized images with some GM-like +% value. +% +% The basic pour idea is to quantify the gradient close to the WM +% boundary in relation to its voxel size by using kmeans with two +% peaks (the first one for the background low intensity, the higher one +% for the edge) close to the possible GM/WM interface defined by Ymsk. +% Ymsk was original simple (Ymsk=Yp0>2.05 & Yp0<2.95) but instable for +% faulty segmentations. +% +% Ygrad = cat_vol_grad(max(2/3,min(1,Ym) .* (Yp0>0)) , vx_vol); +% Ymsk = ~cat_vol_morph(cat_vol_morph(Ygm | Ycm | Yp0<2,'dc',2),'e') & ... +% Ysc>0.45 & Ysc<0.97 & ~Ywe & ~cat_vol_morph(Yp0<=1.05,'d',1.9); +% [res_ECR,b,c] = cat_stat_kmeans(Ygrad(Ymsk(:)),2); res_ECR(1) = []; +% +% The first tests are promissing. Although noise and contrast are +% affecting the measurements it is similar stable as the NCR rating. +% ------------------------------------------------------------------------- +stime = cat_io_cmd(' Measures - ECR:','g5','',opt.verb>3,stime); +for sm = 0%noise %-1:0.5:1 + %% + Yms2 = Ym + 0; %sm = -1; + if sm<0, Yms2 = round(Ym*3)/3*(0-sm) + Yms2*(1+sm); end + if sm>0, spm_smooth(Yms2,Yms2,repmat(max(0,sm),1,3)); end +% Ygrad = cat_vol_grad(max(2/3,min(1,Yms) .* (Yp0>0)) , vx_vol ); + + %Ymsk = Yp0>1.95 & cat_vol_morph(Yp0>2.05,'dd',1.5) & Ysc<0.9 & Ysc>0.55 & ~Ywe & ~cat_vol_morph(Yp0<1.5,'d',3); + %Ymsk = Yp0>max(1.8,2-noise) & cat_vol_morph(Yp0>2.05,'dd',3) & Ysc<0.97 & Ysc>0.45 & ~Ywe; % & ~cat_vol_morph(Yp0<1.5,'d',1.9); + %Ymsk = cat_vol_morph( Ywm ,'d',2) & ~cat_vol_morph(cat_vol_morph(Ygm | Ycm | Yp0<2,'dc',2),'e'); + Ymsk = ~cat_vol_morph(cat_vol_morph(Ygm | Ycm | Yp0<2,'dc',2),'e') & Ysc>0.45 & Ysc<0.97 & ~Ywe & ~cat_vol_morph(Yp0<=1.05,'d',1.9); % FINAL + [res_ECR,b,c] = cat_stat_kmeans(Ygrad(Ymsk(:)),2); res_ECR(1) = []; + %QAS.qualitymeasures.res_ECR = (abs(a-1/4) + abs(b - 0.025) ) / mean(vx_vol); + + %ds('d2sm','',1,Yms,Ygrad,100) +end + + + + +% Image/processing quality: Euler Number of Surface +% ------------------------------------------------------------------------- +% It is known (and was shown) that lower image quality correlates with the +% number of surface defects. However, ""abnormal"" anatomy can also cause +% problems because sulci are blurred in children or gyri are underdeveloped +% /unmyelinated in childen or atrophied in elderly. +% Moreover, we avoid surface-based measures to be open for fast VBM solutions. +% However, it would be possible to create an intial surface based on the +% WM segment and estimate the number of surface defects. +% ------------------------------------------------------------------------- + + +stime = cat_io_cmd(' Measures - NCR/ICR/contrast:','g5','',opt.verb>3,stime); + %% low resolution tissue intensity maps (smoothing) + % High frequency noise is mostly uncritical as far as simple smoothing can reduce it. + % Although the very low frequency interferences (inhomogeneity) is unproblematic in most cases, + % but will influence the noise pattern. + % But most important is the noise with the medium high frequencies, that we try do detect by + % reducing the very high and low noise pattern by filtering and pixel smoothing by reduction. + res = 2; vx_volx = 1; + Yos = cat_vol_localstat(Yo,Ywm,1,1); Yo(Yos>0)=Yos(Yos>0); % reduce high frequency noise in WM + Yos = cat_vol_localstat(Yo,Ycm,1,1); Yo(Yos>0)=Yos(Yos>0); % reduce high frequency noise in CSF + + Yc = cat_vol_resize(Yo .* Ycm,'reduceV',vx_volx,res,32,'min'); % CSF thr. (minimum to avoid PVE) + Yg = cat_vol_resize(Yo .* Ygm,'reduceV',vx_volx,res,32,'meanm'); % GM thr. + Yw = cat_vol_resize(Yo .* Ywe,'reduceV',vx_volx,res,32,'meanm'); % WM thr. and bias correction (Ywme) + Ywc = cat_vol_resize(Ym .* Ywe,'reduceV',vx_volx,res,32,'meanm'); % for bias correction + Ywb = cat_vol_resize( (Yo + min(Yo(:))) .* Ywm,'reduceV',vx_volx,res,32,'max') - min(Yo(:)); % for WM inhomogeneity estimation (avoid PVE) + Ywn = cat_vol_resize(Yo .* Ywm,'reduceV',vx_volx,res,32,'meanm'); % for WM noise + Ycn = cat_vol_resize(Yo .* Ycm,'reduceV',vx_volx,res,32,'meanm'); % for CSF noise + Ycm = cat_vol_resize(Ycm ,'reduceV',vx_volx,res,32,'meanm'); % CSF thr. (minimum to avoid PVE) + Ygm = cat_vol_resize(Ygm ,'reduceV',vx_volx,res,32,'meanm'); % GM thr. + Ywm = cat_vol_resize(Ywm ,'reduceV',vx_volx,res,32,'meanm'); % WM thr. and bias correction (Ywme) + Ywe = cat_vol_resize(Ywe ,'reduceV',vx_volx,res,32,'meanm'); % WM thr. and bias correction (Ywme) + + % only voxel that were the product of + Yc = Yc .* (Ycm>=0.5); Yg = Yg .* (Ygm>=0.5); Yw = Yw .* (Ywe>=0.5); + Ywc = Ywc .* (Ywe>=0.5); Ywb = Ywb .* (Ywm>=0.5); Ywn = Ywn .* (Ywm>=0.5); + Ycn = Ycn .* (Ycm>=0.5); + + + %clear Ycm Ygm Ywm Ywme; + [Yo,Ym,Yp0,resr] = cat_vol_resize({Yo,Ym,Yp0},'reduceV',vx_volx,res,32,'meanm'); + resr.vx_volo = vx_vol; vx_vol=resr.vx_red .* resr.vx_volo; + + %% intensity scaling for normalized Ym maps like in CAT12 + if cat_stat_nanmean(Yo(Yp0(:)>2))<0 + Ywc = Ywc .* (cat_stat_kmeans(Yo(Yp0(:)>2))/cat_stat_nanmean(2 - Ym(Yp0(:)>2))); % RD202004: negative values in chimp data showed incorrect scalling + else + Ywc = Ywc .* (cat_stat_kmeans(Yo(Yp0(:)>2))/cat_stat_nanmean(Ym(Yp0(:)>2))); + end + + %% bias correction for original map, based on the + WI = zeros(size(Yw),'single'); WI(Ywc(:)~=0) = Yw(Ywc(:)~=0)./Ywc(Ywc(:)~=0); WI(isnan(Ywe) | isinf(WI) | Ywe==0) = 0; + WI = cat_vol_approx(WI,'rec',2); + WI = cat_vol_smooth3X(WI,1); + + Ywn = Ywn./max(eps,WI); Ywn = round(Ywn*1000)/1000; + Ymi = Yo ./max(eps,WI); Ymi = round(Ymi*1000)/1000; + Yc = Yc ./max(eps,WI); Yc = round(Yc *1000)/1000; + Yg = Yg ./max(eps,WI); Yg = round(Yg *1000)/1000; + Yw = Yw ./max(eps,WI); Yw = round(Yw *1000)/1000; + + clear WIs ; + + + % tissue segments for contrast estimation etc. + CSFth = cat_stat_kmeans(Yc(~isnan(Yc(:)) & Yc(:)~=0)); + GMth = cat_stat_kmeans(Yg(~isnan(Yg(:)) & Yg(:)~=0)); + WMth = cat_stat_kmeans(Yw(~isnan(Yw(:)) & Yw(:)~=0)); + T3th = [CSFth GMth WMth]; + + + % estimate background + [Ymir,resYbg] = cat_vol_resize(Ymi,'reduceV',1,6,32,'meanm'); + try + warning 'off' 'MATLAB:cat_vol_morph:NoObject' + BGCth = min(T3th)/2; + Ybgr = cat_vol_morph(cat_vol_morph(Ymir0.5; clear Yosr Ybgr; + if sum(Ybg(:))<32, Ybg = cat_vol_morph(Yo0.5; clear Yosr Ybgr; + if sum(Ybg(:))<32, Ybg = cat_vol_morph(YoGMth + QAS.qualitymeasures.tissue_weighting = 'T1'; + elseif WMth0.5 & ~isinf(Yp0(:)))); + end + QAS.qualitymeasures.tissue_stdr = QAS.qualitymeasures.tissue_std ./ (WMth-BGth); + + % (relative) (mininum) tissue contrast ( CSF-GM-WM ) + % - the CSF threshold varies strongly due to bad segmentations, + % and anatomica variance, so its better to use GM-WM contrast + % and take care of overoptimisation with values strongly >1/3 + % of the relative contrast + signal_intensity = abs( diff( [min(BGth,CSFth) , max(GMth,WMth)] )); + contrast = min(abs(diff(QAS.qualitymeasures.tissue_mn(2:4)))) ./ signal_intensity; % default contrast + contrast = contrast + min(0,13/36 - contrast) * 1.2; % avoid overoptimsization + QAS.qualitymeasures.contrast = contrast * (max([WMth,GMth])); + QAS.qualitymeasures.contrastr = contrast / (max([WMth,GMth]) / signal_intensity); + + + + QAS.qualitymeasures.res_ECR = 1 - abs( res_ECR / (contrast / (max([WMth,GMth]) / signal_intensity)) ).^1 ; + %fprintf(' ( %0.4f ) ', QAS.qualitymeasures.res_ECR); + + %% noise estimation (original (bias corrected) image) + % WM variance only in one direction to avoid WMHs! + rms=1; nb=1; + if 1 + NCww = sum(Ywn(:)>0) * prod(vx_vol); + NCwc = sum(Ycn(:)>0) * prod(vx_vol); + [Yos2,YM2,R] = cat_vol_resize({Ywn,Ywn>0},'reduceV',vx_vol,3,16,'meanm'); + signal_intensity = abs( diff( [min(BGth,CSFth) , max(GMth,WMth)] )); + NCRw = estimateNoiseLevel(Yos2,YM2>0.5,nb,rms) / signal_intensity / contrast ; + else + % RD202005: not correct working? + Ywmn = cat_vol_morph(Ywm,'o'); + NCww = sum(Ywmn(:)) * prod(vx_vol); + NCwc = sum(Ycm(:)) * prod(vx_vol); + signal_intensity = abs( diff( [max(BGth,CSFth) , max(GMth,WMth)] )); + [Yos2,YM2,R] = cat_vol_resize({Ywn,Ywmn},'reduceV',vx_vol,max(3 * min(vx_vol) ,3),16,'meanm'); + YM2 = cat_vol_morph(YM2,'o'); % we have to be sure that there are neigbors otherwise the variance is underestimated + NCRw = estimateNoiseLevel(Yos2,YM2>0.5,nb,rms) / signal_intensity / contrast ; + if isnan(NCRw) + NCRw = estimateNoiseLevel(Ywn,Ywmn,nb,rms) / signal_intensity / contrast ; + end + end + NCRw = NCRw * (1 + log(28 - prod(R.vx_red)))/(1 + log(28 - 1)); % compensate voxel averageing + if BGth<-0.1 && WMth<3, NCRw=NCRw/3; end% MT weighting + % clear Yos0 Yos1 Yos2 YM0 YM1 YM2; + + %% CSF variance of large ventricle + % for typical T2 images we have too much signal in the CSF and can't use it for noise estimation! + wcth = 200; + if CSFthwcth + if 1 + [Yos2,YM2,red] = cat_vol_resize({Ycn,Ycn>0},'reduceV',vx_vol,3,16,'meanm'); + NCRc = estimateNoiseLevel(Yos2,YM2>0.5,nb,rms) / signal_intensity / contrast ; + else + % RD202005: not correct working? + [Yos2,YM2,red] = cat_vol_resize({Ycn,Ycm},'reduceV',vx_vol,max(3 * min(vx_vol) ,3),16,'meanm'); + NCRc = estimateNoiseLevel(Yos2,YM2>0.5,nb,rms) / signal_intensity / contrast ; + if isnan(NCRc) + NCRc = estimateNoiseLevel(Ycn,Ycm,nb,rms) / signal_intensity / contrast ; + end + end + % clear Yos0 Yos1 Yos2 YM0 YM1 YM2; + else + red = R; + NCRc = 0; + NCwc = 0; + end + % 1/sqrt(volume) to compensate for noise differency due to different volumen size. + % Overall there are better chances to correct high resolution noise. + % Nitz W R. Praxiskurs MRT. Page 28. + NCwc = min(wcth,max(0,NCwc-wcth)); NCww = min(wcth,NCww) - NCwc; % use CSF if possible + if NCwc<3*wcth && NCww<10*wcth, NCRc = min(NCRc,NCRw); end + QAS.qualitymeasures.NCR = max(0,NCRw*NCww + NCRc*NCwc)/(NCww+NCwc); + QAS.qualitymeasures.NCR = real( QAS.qualitymeasures.NCR * 3 ); % abs(prod(resr.vx_volo*res))^0.4 * 5/4); %* 7.5; %15; + %QAS.qualitymeasures.CNR = 1 / QAS.qualitymeasures.NCR; +%fprintf('NCRw: %8.3f, NCRc: %8.3f, NCRf: %8.3f\n',NCRw,NCRc,(NCRw*NCww + NCRc*NCwc)/(NCww+NCwc)); + + + %% Bias/Inhomogeneity (original image with smoothed WM segment) + Yosm = cat_vol_resize(Ywb,'reduceV',vx_vol,3,32,'meanm'); Yosmm = Yosm~=0; % resolution and noise reduction + for si=1:max(1,min(3,round(QAS.qualitymeasures.NCR*4))), mth = min(Yosm(:)) + 1; Yosm = cat_vol_localstat(Yosm + mth,Yosmm,1,1) - mth; end + % BWP-like definition + QAS.qualitymeasures.ICR = cat_stat_nanstd(Yosm(Yosmm(:))) / signal_intensity / contrast; + %QAS.qualitymeasures.CIR = 1 / QAS.qualitymeasures.ICR; + % local concept that could work also on the BWP? + Yosm2 = cat_vol_localstat(Yosm,Yosmm,1,4) / mean(red.vx_volr)/3; +% QAS.qualitymeasures.ICRk = cat_stat_kmeans( (Yosm2(Yosmm(:)) / signal_intensity / contrast * 100 + 1).^4 ).^(1/4); +% fprintf('ICR: %8.3f, ICRk: %8.6f\n',QAS.qualitymeasures.ICR,QAS.qualitymeasures.ICRk); + +if isnan(QAS.qualitymeasures.ICR ) + disp(1) +end + + %% marks + QAR = cat_stat_marks('eval',1,QAS); + + % export + if opt.write_xml + QAS.qualityratings = QAR.qualityratings; + QAS.subjectratings = QAR.subjectratings; + QAS.ratings_help = QAR.help; + + cat_io_xml(fullfile(pp,reportfolder,[opt.prefix ff '.xml']),QAS,'write'); %struct('QAS',QAS,'QAM',QAM) + end + + cat_io_cmd(' ','g5','',opt.verb>3,stime); + if opt.verb>3, fprintf('%5.0fs\n',etime(clock,stime2)); end + + % be verbose to detect problems + if opt.verb>2 + fprintf('Intensity(CGW):%6.0f %6.0f %6.0f - Volume(CGW):%8.2f %8.2f %8.2f - Noise(m,p0):%5.3f %5.3f. %0.fs %s\n', T3th, ... + cat_stat_nansum(Yc(:)>0)/1000,cat_stat_nansum(Yg(:)>0)/1000,cat_stat_nansum(Yw(:)>0)/1000,noise,noisep0,etime(clock,stime2)); + end +else + QAS = cat_io_xml(fullfile(pp,reportfolder,[opt.prefix ff '.xml']),'load'); %struct('QAS',QAS,'QAM',QAM) + QAR = cat_stat_marks('eval',1,QAS); +end + + + clear Yi Ym Yo Yos Ybc + clear Ywm Ygm Ycsf Ybg + + end + + if (isempty(varargin) || isstruct(varargin{1})) + if exist('Pp0','var') + varargout{1}.data = Pp0; + else + varartout{1}.data = {}; + end + else + if nargout>1, varargout{2} = QAR; end + if nargout>0, varargout{1} = QAS; end + end + + +end +%======================================================================= +function def=defaults + % default parameter + def.verb = 2; % verbose level [ 0=nothing | 1=points | 2=results | 3=details] + def.write_csv = 2; % final cms-file [ 0=dont write |1=write | 2=overwrite ] + def.write_xml = 1; % images base xml-file + def.sortQATm = 1; % sort QATm output + def.orgval = 0; % original QAM results (no marks) + def.avgfactor = 2; % + def.prefix = 'cat_'; % intensity scaled image + def.mprefix = 'm'; % prefix of the preprocessed image + def.process = 3; % used image [ 0=T1 | 1=mT1 | 2=avg | 3=both ] + def.calc_MPC = 0; + def.calc_STC = 0; + def.calc_MJD = 0; + def.method = 'spm'; + def.snspace = [70,7,3]; + def.nogui = exist('XT','var'); + def.rerun = 0; + def.MarkColor = cat_io_colormaps('marks+',40); +end + +function noise = estimateNoiseLevel(Ym,YM,r,rms,vx_vol) +% ---------------------------------------------------------------------- +% noise estimation within Ym and YM. +% ---------------------------------------------------------------------- + if ~exist('vx_vol','var') + vx_vol=[1 1 1]; + end + if ~exist('r','var') + r = 1; + else + r = min(10,max(max(vx_vol),r)); + end + if ~exist('rms','var') + rms = 1; + end + + Ysd = cat_vol_localstat(single(Ym),YM,r ,4); + Ysd2 = cat_vol_localstat(single(Ym),YM,r+1,4); % RD20210617: more stable for sub-voxel resolutions ? + Ysd = Ysd * mod(r,1) + (1-mod(r,1)) * Ysd2; % RD20210617: more stable for sub-voxel resolutions ? + %noise = cat_stat_nanstat1d(Ysd(YM).^rms,'median').^(1/rms); % RD20210617: + noise = cat_stat_kmeans(Ysd(YM),1); % RD20210617: more robust ? +end +%======================================================================= +","MATLAB" +"Neurology","ChristianGaser/cat12","check_pipeline.sh",".sh","17785","546","#! /bin/bash +# Check CAt12 pipleine +# ______________________________________________________________________ +# +# Christian Gaser, Robert Dahnke +# Structural Brain Mapping Group (https://neuro-jena.github.io) +# Departments of Neurology and Psychiatry +# Jena University Hospital +# ______________________________________________________________________ +# $Id$ + +######################################################## +# global parameters +######################################################## + +matlab=matlab # you can use other matlab versions by changing the matlab parameter +spm12_tmp=/tmp/spm12_$$ +calc_tmp=/tmp/calc$$ +proc_dir=$PWD +bg_flag="" -fg -p 1"" +bg_flag_long="" -fg"" +bg=0 +do_scp=1 +postprocess_only=0 +volumes_only=0 +scp_target=""dbm.neuro.uni-jena.de:/volume1/web/check_pipeline/"" + +######################################################## +# run main +######################################################## + +main () +{ + parse_args ${1+""$@""} + + if [ $postprocess_only -eq 0 ]; then + copy_files + get_release + run_pipeline + fi + + # don't run postprocess if check_pipeline is running in the background + if [ $bg -eq 0 ]; then + postprocess + fi + + exit 0 +} + +######################################################## +# check arguments and files +######################################################## + +parse_args () +{ + local optname optarg files_to_calculate all_files + count=0 + count_long=0 + files_to_calculate=0 + all_files=0 + while [ $# -gt 0 ] + do + optname=""`echo $1 | sed 's,=.*,,'`"" + optarg=""`echo $2 | sed 's,^[^=]*=,,'`"" + case ""$1"" in + --matlab* | -m*) + exit_if_empty ""$optname"" ""$optarg"" + matlab=$optarg + shift + ;; + --release* | -r*) + exit_if_empty ""$optname"" ""$optarg"" + release=$optarg + shift + ;; + --spm* | -s*) + exit_if_empty ""$optname"" ""$optarg"" + spm12_dir=$optarg + shift + ;; + --dir* | -d*) + exit_if_empty ""$optname"" ""$optarg"" + proc_dir=$optarg + shift + ;; + --file* | -f*) + exit_if_empty ""$optname"" ""$optarg"" + listfile=$optarg + shift + list=$(< $listfile); + for F in $list; do + ARRAY[$count]=$F + ((count++)) + done + ;; + --long* | -l*) + exit_if_empty ""$optname"" ""$optarg"" + listfile=$optarg + shift + list_long=$(< $listfile); + for F in $list_long; do + ARRAY_LONG[$count_long]=$F + ((count_long++)) + done + ;; + --bg* | -b*) + exit_if_empty ""$optname"" ""$optarg"" + bg_flag="" -p ""$optarg + bg_flag_long="""" + bg=1 + shift + ;; + --post* | -p*) + exit_if_empty ""$optname"" ""$optarg"" + postprocess_only=$optarg + shift + ;; + --no-surf* | -ns*) + exit_if_empty ""$optname"" ""$optarg"" + volumes_only=1 + ;; + --no-scp* | -np*) + exit_if_empty ""$optname"" ""$optarg"" + do_scp=0 + ;; + -h | --help | -v | --version | -V) + help + exit 1 + ;; + -*) + echo ""`basename $0`: ERROR: Unrecognized option \""$1\"""" >&2 + ;; + *) + ARRAY[$count]=$1 + ((count++)) + ;; + esac + shift + done + +} + +######################################################## +# check and copy files +######################################################## + +copy_files () +{ + + if [ ! -n ""$spm12_dir"" ]; then + echo ""SPM12 directory is undefined!"" + fi + + SIZE_OF_ARRAY=${#ARRAY[@]} + SIZE_OF_ARRAY_LONG=${#ARRAY_LONG[@]} + + old_dir=$PWD + + if [ ""$SIZE_OF_ARRAY"" -eq 0 ] && [ ""$SIZE_OF_ARRAY_LONG"" -eq 0 ]; then + echo 'ERROR: No files given!' >&2 + help + exit 1 + fi + + if [ ""$SIZE_OF_ARRAY_LONG"" -gt 2 ]; then + echo 'ERROR: Only two longitudinal scans are currently supported!' >&2 + help + exit 1 + fi + + if [ ""$SIZE_OF_ARRAY"" -gt 0 ]; then + + mkdir -p $calc_tmp + cd $calc_tmp + + i=0 + while [ ""$i"" -lt ""$SIZE_OF_ARRAY"" ]; do + if [ ! -f ""${ARRAY[$i]}"" ]; then + if [ ! -L ""${ARRAY[$i]}"" ]; then + if curl --output /dev/null --silent --head --fail ""${ARRAY[$i]}""; then + curl -O ${ARRAY[$i]} + else + echo File or url ${ARRAY[$i]} does not exist + exit + fi + fi + fi + cp ${ARRAY[$i]} ${calc_tmp}/ + ((i++)) + done + + cd $old_dir + fi + + if [ ""$SIZE_OF_ARRAY_LONG"" -gt 0 ]; then + mkdir -p ${calc_tmp}/long + + cd ${calc_tmp}/long + + i=0 + while [ ""$i"" -lt ""$SIZE_OF_ARRAY_LONG"" ]; do + if [ ! -f ""${ARRAY_LONG[$i]}"" ]; then + if [ ! -L ""${ARRAY_LONG[$i]}"" ]; then + if curl --output /dev/null --silent --head --fail ""${ARRAY_LONG[$i]}""; then + curl -O ${ARRAY_LONG[$i]} + else + echo File or url ${ARRAY_LONG[$i]} does not exist + exit + fi + fi + fi + cp ${ARRAY_LONG[$i]} ${calc_tmp}/long/ + ((i++)) + done + cd $old_dir + fi + +} + +######################################################## +# check arguments +######################################################## + +exit_if_empty () +{ + local desc val + + desc=""$1"" + shift + val=""$*"" + + if [ ! -n ""$val"" ] + then + echo ERROR: ""No argument given with \""$desc\"" command line argument!"" >&2 + exit 1 + fi +} + +######################################################## +# run get_release +######################################################## + +get_release () +{ + if [ ! -d ""${spm12_dir}"" ]; then + echo Directory $spm12_dir does not exist! + exit 1 + fi + + # copy current spm12 installation to tmp folder + cp -r $spm12_dir $spm12_tmp + + if [ ! -n ""$release"" ]; then + echo ""Use current release."" + else + # remove old cat12 folder + rm -r ${spm12_tmp}/toolbox/cat12 + + # check whether it's a file + if [ -f ""$release"" ]; then + unzip -q $release -d ${spm12_tmp}/toolbox/ + else # or a web-address + cat12_tmp=/tmp/cat12$$.zip + curl -o $cat12_tmp $release + unzip -q $cat12_tmp -d ${spm12_tmp}/toolbox/ + rm $cat12_tmp + fi + fi + + # allow execution of mexmaci64 file on MAC + if [ ""$ARCH"" == ""Darwin"" ]; then + echo ""Please login as admin to allow execution of mex files on MAC OS"" + sudo xattr -r -d com.apple.quarantine $spm12_tmp + sudo find $spm12_tmp -name \*.mexmaci64 -exec spctl --add {} \; + fi +} + +######################################################## +# run run_pipeline +######################################################## + +run_pipeline () +{ + + PID=$$ + echo PID is $PID + + # set ROI output and surface output + if [ $volumes_only -eq 0 ]; then + echo ""cat.output.surface = 1;"" >> ${spm12_tmp}/toolbox/cat12/cat_defaults.m + str_surf="""" + else + echo ""cat.output.surface = 0;"" >> ${spm12_tmp}/toolbox/cat12/cat_defaults.m + str_surf="" -ns "" + fi + echo ""cat.output.ROI = 1;"" >> ${spm12_tmp}/toolbox/cat12/cat_defaults.m + echo ""cat.extopts.ignoreErrors = 1;"" >> ${spm12_tmp}/toolbox/cat12/cat_defaults.m + + # run cat12 in foreground with all files in tmp folder + if [ ""$SIZE_OF_ARRAY"" -gt 0 ]; then + if [ -f ""${spm12_tmp}/toolbox/cat12/cat_batch_cat.sh"" ]; then + ${spm12_tmp}/toolbox/cat12/cat_batch_cat.sh -m ${matlab} -l ${proc_dir} ${bg_flag} ${calc_tmp}/*.[in][mi][gi] + else + ${spm12_tmp}/toolbox/cat12/cat_batch_vbm.sh -m ${matlab} -l ${proc_dir} ${bg_flag} ${calc_tmp}/*.[in][mi][gi] + fi + fi + + if [ ""$SIZE_OF_ARRAY_LONG"" -gt 0 ]; then + large=`grep ""\-large"" ${spm12_tmp}/toolbox/cat12/cat_batch_long.sh` + # call ""-large"" option only if available for that release + if [ -n ""$large"" ]; then + ${spm12_tmp}/toolbox/cat12/cat_batch_long.sh -m ${matlab} ${str_surf} -large ${bg_flag_long} ${calc_tmp}/long/*.[in][mi][gi] + else + ${spm12_tmp}/toolbox/cat12/cat_batch_long.sh -m ${matlab} ${str_surf} ${bg_flag_long} ${calc_tmp}/long/*.[in][mi][gi] + fi + fi + +} + +######################################################## +# run postprocess +######################################################## + +postprocess () +{ + + # if postprocess_only > 0 we assume that this is a pid + if [ $postprocess_only -gt 0 ]; then + pid=""$postprocess_only"" + if [ -d /tmp/calc${pid} ]; then + spm12_tmp=/tmp/spm12${pid} + calc_tmp=/tmp/calc${pid} + else + echo Please check process ID. Directory /tmp/calc${pid} was not found. + exit 1 + fi + fi + + # if postprocess_only < 0 we assume that this is the release number + if [ $postprocess_only -lt 0 ]; then + release=`echo $postprocess_only| cut -f2 -d'-'` + if [ ! -d ${proc_dir}/check_r${release} ]; then + echo Please check release number. Directory ${proc_dir}/check_r${release} was not found. + exit 1 + fi + calc_tmp=${proc_dir}/check_r${release} + fi + + # check whether xml files are found + for folder in """" ""/long""; do + calc_tmp2=${calc_tmp}/${folder} + + # remove all average files from long mode + rm ${calc_tmp}/long/*/*avg* 2>/dev/null + + tmp=`ls ${calc_tmp2}/report/cat_*xml 2>/dev/null` + + if [ -n ""$tmp"" ]; then + for i in ${calc_tmp2}/report/cat_*xml; do + revision_cat=`grep revision_cat ${i}| cut -f2 -d"">""|cut -f1 -d""<""` + if [ ! -n ""$revision_cat"" ]; then + revision_cat=`grep version_cat ${i}| cut -f2 -d"">""|cut -f1 -d""<""` + fi + label=${calc_tmp2}/label/catROI_`basename $i| sed -e 's/cat_//g'` + labels=${calc_tmp2}/label/catROIs_`basename $i| sed -e 's/cat_//g'` + report=${calc_tmp2}/report/cat_`basename $i| sed -e 's/cat_//g'` + subj=`basename $i | sed -e 's/\.xml//g' -e 's/cat_//g'` + + echo Finalize $subj with revision $revision_cat + + # get current csv files from dbm server + if [ $do_scp -eq 1 ]; then + scp -q -P $PORT ${scp_target}/${subj}*csv . + fi + + # grep for vol_TIV and vol_abs_CGW and update csv file + # check first for keywords and print next 5 lines + vol_TIV=`grep -A5 """"|cut -f1 -d""<""` + vol_CGW=`grep ""> ${subj}_vol.csv + cat ${subj}_vol.csv |sort -r|uniq > tmp$$ + mv tmp$$ ${proc_dir}/${subj}_vol.csv + fi + + # grep for Vgm and update csv file + # check first for keyword neuromorphometrics and print next 200 lines + Vgm=`grep -A200 ""> ${subj}_Vgm.csv + cat ${subj}_Vgm.csv |sort -r|uniq > tmp$$ + mv tmp$$ ${proc_dir}/${subj}_Vgm.csv + fi + + # grep for Vcsf and update csv file + # check first for keyword neuromorphometrics and print next 200 lines + Vcsf=`grep -A200 ""> ${subj}_Vcsf.csv + cat ${subj}_Vcsf.csv |sort -r|uniq > tmp$$ + mv tmp$$ ${proc_dir}/${subj}_Vcsf.csv + fi + + # grep for thickness and update csv file + # check first for keyword neuromorphometrics and print next 200 lines + thickness=`grep -A200 ""> ${subj}_thickness.csv + cat ${subj}_thickness.csv |sort -r|uniq > tmp$$ + mv tmp$$ ${proc_dir}/${subj}_thickness.csv + fi + + # scp updated csv files to dbm server + if [ $do_scp -eq 1 ]; then + scp -q -P $PORT *.csv ${scp_target} + fi + + done + fi + done + + # sometimes xml-files were not saved + if [ ! -n ""$revision_cat"" ]; then + echo Could not find xml-files. Give 4-digit release number: + read revision_cat + fi + + # rename tmp-folder and zip and scp them + if [ ! $postprocess_only -lt 0 ]; then + if [ -d ${proc_dir}/check_r${revision_cat} ]; then + mv ${calc_tmp}/*/ ${proc_dir}/check_r${revision_cat}/ + else + mv ${calc_tmp} ${proc_dir}/check_r${revision_cat} + fi + fi + + # prepare renderview if tool is found and surface processing is enabled + if ([ ! -z `which CAT_View_Thickness_ui` ]) && [ $volumes_only -eq 0 ]; then + mkdir -p ${proc_dir}/check_r${revision_cat}/surf + ln -s ${proc_dir}/check_r${revision_cat}/long/surf/* ${proc_dir}/check_r${revision_cat}/surf/ >/dev/null 2>&1 + CAT_View_Thickness_ui -output -range 1 5 ${proc_dir}/check_r${revision_cat}/surf/lh.central.* + mv check_r${revision_cat}*.png ${proc_dir}/ >/dev/null 2>&1 + if [ $do_scp -eq 1 ]; then + scp -q -P $PORT ${proc_dir}/check_r${revision_cat}*.png $scp_target + fi + else + echo ""You need render_surf.sh and image_matrix.sh for preparing render view."" + fi + + # delete original files, WM and normalized T1 images + if [ ! $postprocess_only -lt 0 ]; then + rm ${proc_dir}/check_r${revision_cat}/*.[in][mi][gi] 2>/dev/null + rm ${proc_dir}/check_r${revision_cat}/mri/*mwp2* 2>/dev/null + rm ${proc_dir}/check_r${revision_cat}/mri/wm* 2>/dev/null + + if [ -d ${proc_dir}/check_r${revision_cat}/long ]; then + rm ${proc_dir}/check_r${revision_cat}/long/*.[in][mi][gi] 2>/dev/null + rm ${proc_dir}/check_r${revision_cat}/long/mri/mwp2* 2>/dev/null + rm ${proc_dir}/check_r${revision_cat}/long/mri/wm* 2>/dev/null + fi + + zip -q ${proc_dir}/check_r${revision_cat}.zip -r ${proc_dir}/check_r${revision_cat} + if [ $do_scp -eq 1 ]; then + scp -q -P $PORT ${proc_dir}/check_r${revision_cat}.zip $scp_target + fi + fi + +} + +######################################################## +# help +######################################################## + +help () +{ +cat <<__EOM__ + +USAGE: + check_pipeline.sh -s spm12_folder [-m matlab_command] [-p process_id] [-r cat12_zip_file] [-d proc_folder] [-b number_of_processes] [-ns] [-f file_list | filenames] + + --release | -r zip-file of CAT12 release that will be used for checking. If no zip-file is given, then the current CAT12 release will be used. + --spm | -s folder of spm12 installation + --dir | -d folder for writing processed files and results (default $proc_folder) + --matlab | -m matlab command (matlab version) (default matlab) + --file | -f list with file names for checking + --post | -p post-process given pid + --bg | -b run check_pipeline.sh in the background + --no-surf | -ns run check_pipeline.sh without surface processing + --no-scp | -np skip scp transfer + + All given files will be processed using either the current CAT12 version or the defined CAT12 release with the ""-r"" flag. + For the latter case the zip-file can be defined as local file or as url-address. During processing temporary folder are + saved in /tmp and modulated gray matter images and surfaces are calculated for each file. Finally, the post-processing will + be applied. During post-processing the temporary folders are renamed according to the found release number (check_rxxxx). + Finally, the csv-files, the zipped check-folders, and the render views are transfered to ${scp_target}. + If you run check_pipeline.sh in the background the post-processing has to be called manually using the ""-p"" flag if the + processing for all data is finished. + + +PURPOSE: + check_pipeline.sh a cat12 release + +INPUT: + nifti files + +OUTPUT: + The following files are saved in the current folder: + csv-files with ROI volumes + render views + check_r* folders with release name + +EXAMPLE: + check_pipeline.sh -s ~/spm/spm12 -r http://dbm.neuro.uni-jena.de/cat12/cat12_r1318.zip file1 file2 file3 file4 file5 + Run check_pipeline.sh with given 5 files and use CAT12 release 1318 from dbm-server and the defined SPM12 folder. + + check_pipeline.sh -s ~/spm/spm12 -bg 8 -f /Volumes/UltraMax/check_pipeline/check_pipeline_files.txt -l /Volumes/UltraMax/check_pipeline/check_pipeline_files_long.txt + check_pipeline.sh -p pid + Run check_pipeline.sh in the background with 8 processes with given file list and use current CAT12 release and the defined SPM12 folder. + Finally, post-processing can be called with the given pid if processing is finished. + + check_pipeline.sh -p -xxxx + Run post-processing again for release xxxx. This command is helpful if you have to re-calculated single data set because of a previous crash. + Please note the ""-"" before the release number to indicate that this is not a pid but a release number. + +USED FUNCTIONS: + CAT12 toolbox + SPM12 + CAT_View_Thickness_ui + +This script was written by Christian Gaser (christian.gaser@uni-jena.de). + +__EOM__ +} + +######################################################## +# call main program +######################################################## + +main ${1+""$@""} + +","Shell" +"Neurology","ChristianGaser/cat12","cat_vol_smooth3X.m",".m","2724","89","function S=cat_vol_smooth3X(S,s,filter) +% S=cat_vol_smooth3X(S,s,filter) +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% TODO - vx_vol!!!!!!! +% - filter strength is also influcenced by the downsampling!!! + if ~exist('s','var'), s=1; end + if ~exist('filter','var'); filter='s'; end + + s = mean(s); + S(isnan(S(:)) | isinf(-S(:)) | isinf(S(:)))=0; % correct bad cases + + SO=S; + if size(size(S),2) == 2 + slice = 1; + S = repmat(S,1,1,2*s+1); + elseif size(size(S),2) == 1 + error('ERROR: cat_vol_smooth3X: Input S has to be a matrix or volume!'); + else + slice = 0; + end + + if s>0 && s<0.5 + S = smooth3(S,'gaussian',3,0.5)*s + S*(1-s); + elseif s>=0.5 && s<=1.0 + S = smooth3(S,'gaussian',3,s); + elseif s>1.0 && all(size(S)>6) + SR = reduceRes(S); + SR = cat_vol_smooth3X(SR,s/2); + S = dereduceRes(SR,size(S)); + elseif s>=1.0 && any(size(S)<=6) + S = smooth3(S,'gaussian',5,s); + elseif s==0 + % nothing to do + else + S = smooth3(S,'gaussian',1,s); +% error('ERROR: smooth3: s has to be greater 0'); + end + switch filter + case {'min'}, S = min(S,SO); + case {'max'}, S = max(S,SO); + end + + S(isnan(S(:)) | isinf(-S(:)) | isinf(S(:)))=0; + + if slice + S = S(:,:,2); + end +end +function D=reduceRes(D,method) + if ~exist('method','var'), method='linear'; end + if mod(size(D,1),2)==1, D(end+1,:,:)=D(end,:,:); end + if mod(size(D,2),2)==1, D(:,end+1,:)=D(:,end,:); end + if mod(size(D,3),2)==1, D(:,:,end+1)=D(:,:,end); end + + [Rx,Ry,Rz] = meshgrid(single(1.5:2:size(D,2)),single(1.5:2:size(D,1)),single(1.5:2:size(D,3))); + D=cat_vol_interp3f(imgExp(single(D),0),Rx,Ry,Rz,method); +end +function D=dereduceRes(D,sD,method) + if ~exist('method','var'), method='linear'; end + sD=sD/2+0.25; + [Rx,Ry,Rz] = meshgrid(single(0.75:0.5:sD(2)),single(0.75:0.5:sD(1)),single(0.75:0.5:sD(3))); + + D=cat_vol_interp3f(single(imgExp(D,0)),Rx,Ry,Rz,method); +end +function D2=imgExp(D,d) + if nargin<2, d=1; end + if d>1, D=imgExp(D,d-1); end + if d>0 + D2=zeros(size(D)+1,class(D)); + D2(1:end-1,1:end-1,1:end-1) = D; clear D; + for i=1:2 + D2(1:end,1:end,end) = D2(1:end,1:end,end-1); + D2(1:end,end,1:end) = D2(1:end,end-1,1:end); + D2(end,1:end,1:end) = D2(end-1,1:end,1:end); + end + else + D2=D; + end +end +function D2=imgDeExp(D,d) + if nargin<2, d=1; end + if d>0, D2=D(1:end-d,1:end-d,1:end-d); else D2=D; end +end","MATLAB" +"Neurology","ChristianGaser/cat12","cat_io_addwarning.m",".m","7211","176","function varargout = cat_io_addwarning(id,mess,level,nline,data,usebox,verb) +%cat_io_addwarning. Collect preprocessing warnings in CAT12 +% Uses the global struture cat_err_res to collect warnings in the CAT12 +% preprocessing function cat_run_job, cat_run_main, etc. +% Structure will be exported in cat_tst +% +% See also ../cat12/html/cat_methods_warnings.html +% +% cat_io_addwarning(id,mess,level,nline,data,usebox) +% warning_structure = cat_io_addwarning(level); +% +% id .. identifier +% mess .. message +% The message will be printed as with the word WARNING at the +% beginning where \\n will not break the line and add some +% spaces, e.g. 'message line 1 \\nmessage line 2': +% >>WARNING: message line 1 +% >> message line 2 +% level .. warning level +% 0 - note - only relevant for experts/developer +% 1 - caution - uncitical aspectes that could be checked +% 2 - alert - severe problems that should be checked +% 3 - warning - real matlab warning (full report) +% 4 - error - real matlab error (stops processing) +% nline .. new line [before after] warning or by the following codes +% 1 - add new line in command line output before message +% 2 - add new line in command line output also after meassage +% 3 - add also some space to processing time at the end +% data .. structure with fields that are related to the warning, +% e.g., parameter or test results that cause the warning +% (in development) +% usebox .. add a box around the message for command line output +% verb .. be verbose +% +% Examples: +% cat_io_addwarning('reset') +% +% cat_io_addwarning('err99','Processing failed',2,[0 1]); +% cat_io_addwarning('warn0815','Processing bad',1,[0 1]); +% cat_io_addwarning('note3','Comment',0,[0 1]); +% +% cat_io_addwarning % get all warnings & notes +% cat_io_addwarning(2) % only get warnings +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + global cat_err_res + + if ~isfield(cat_err_res,'cat_warnings') + cat_err_res.cat_warnings = struct('identifier',{},'message',{},'level',[],'data',{}); + elseif (nargin==1 && strcmp(id,'reset') ) + cat_err_res = rmfield(cat_err_res,'cat_warnings'); + cat_err_res.cat_warnings = struct('identifier',{},'message',{},'level',[],'data',{}); + if nargout>0 + varargout{1} = struct('identifier',{},'message',{},'level',[],'data',{}); + end + return; + end + + if nargin > 1 && ischar( id ) + % variables + if ~exist('nline','var'), nline = [0 1]; end + if ~exist('level','var'), level = 1; end + if ~exist('data','var'), data = {}; end + if ~exist('usebox','var'), usebox = 1; end + if ~exist('verb','var'), verb = 1; end + % expert = cat_get_defaults('extopts.expertgui'); % not sure if the expert setting work + + if numel(nline) == 1 + switch nline + case 0, nline2 = [0 0]; + case 1, nline2 = [1 0]; + case 2, nline2 = [1 1]; + case 3, nline2 = [1 2]; + otherwise, nline2 = [1 1]; + end + elseif numel(nline) == 2 + nline2 = nline; + else + nline2 = [0 1]; + end + + if nargin<2 + mess = id; + end + if ~ischar(id) + error('cat_io_addwarning:idstr','Identifier must be a char'); + end + if ~ischar(mess) + error('cat_io_addwarning:messstr','Message must be a char'); + end + if ~isnumeric(level) + error('cat_io_addwarning:levelnum','Level must be numeric'); + end + level = max(0,min(2,level)); + + cat_err_res.cat_warnings(end+1) = struct('identifier',id,'message',mess,'level',level,'data',{data}); + + % Define a box that is open at the right side because it is not so + % easys to replace each linebreak with the right number of spaces. + usebox = usebox + 1; + messi = [0,strfind(mess,'\\n'),numel(mess)]; + bsize = max([ 68 + 4 , diff(messi) + 10 + 4]); % normal + oversize + box(1) = struct('s','','i','','e',''); + box(2) = struct(... + 's',[' ' repmat('-',1,bsize) '\n'], ... char(9559) + 'i',[' ' ' '], ... + 'e',['\n ' repmat('-',1,bsize) '']); % char(9595) + box(3) = struct(... + 's',[' ' repmat('=',1,bsize) '\n'], ... char(9559) + 'i',[' ' ' '], ... + 'e',['\n ' repmat('=',1,bsize) '']); % char(9595) + if strcmpi(spm_check_version,'octave') + % octave: ""warning: range error for conversion to character value"" + box(4) = box(3); + else + box(4) = struct(... % the chars are not vissible in the log file + 's',[' ' char(9556) repmat(char(9552),1,bsize) '\n'], ... char(9559) + 'i',[' ' char(9553) ' '], ... + 'e',['\n ' char(9562) repmat(char(9552),1,bsize) '']); % char(9595) + end + + % print output + if verb + if nline2(1)>0, fprintf('\n'); end + warnstr = strrep(mess,'\\n',['\n' box(usebox).i ' ']); + if level==0 + cat_io_cmd(sprintf([box(usebox).s box(usebox).i 'NOTE %02d: ' id '\n' box(usebox).i ' ' warnstr box(usebox).e ],numel(cat_io_addwarning(0))),'note'); + elseif level==1 + cat_io_cmd(sprintf([box(usebox).s box(usebox).i 'WARNING %02d: ' id '\n' box(usebox).i ' ' warnstr box(usebox).e ],numel(cat_io_addwarning(1))),'warning'); + elseif level==2 + cat_io_cmd(sprintf([box(usebox+1).s box(usebox+1).i 'ALERT %02d: ' id '\n' box(usebox+1).i ' ' warnstr box(usebox+1).e ],numel(cat_io_addwarning(2))),'error'); + elseif level==3 + warning(id,warnstr) + else + error(id,warnstr) + end + if nline2(2) == 1 + fprintf('\n'); + elseif nline2(2) == 2 + fprintf('\n'); cat_io_cmd(' ',''); + end + end + end + + if nargout || nargin==0 || nargin==1 + if nargin == 0 + varargout{1} = cat_err_res.cat_warnings; + else + if isnumeric( id ) + if numel(cat_err_res.cat_warnings)>0 + varargout{1} = cat_err_res.cat_warnings( [ cat_err_res.cat_warnings(:).level ] == id ); + else + varargout{1} = struct('identifier',{},'message',{},'level',[],'data',{}); + end + elseif strcmp(id,'reset') && nargout>0 % required for octave + cat_err_res = rmfield(cat_err_res,'cat_warnings'); + cat_err_res.cat_warnings = struct('identifier',{},'message',{},'level',[],'data',{}); + varargout{1} = struct('identifier',{},'message',{},'level',[],'data',{}); + else + error('ERROR:cat_io_addwarning:incorrectInput',... + ['Using only one input is limited to the keyword ""reset"" and \n' ... + 'to output collected warnings by level (0,1,2,3 or 4): \n' ... + ' ""cat_io_addwarning(''reset''); \n' ... + ' ""warning_structure = cat_io_addwarning(level);""\n']); + end + end + end + +return","MATLAB" +"Neurology","ChristianGaser/cat12","cat_vbdist.c",".c","9122","248","/* voxel-based euclidean distance calculation + * ________________________________________________________________________ + * Calculates the euclidean distance without PVE to an object in P with a + * boundary of 0.5 for all voxels within a given mask M that should define + * a convex hull with direct connection between object and estimation + * voxels. Unvisited points were set to FLT_MAX. + * + * [D,I,L] = vbdist(P[,M]) + * + * P (single) input image with zero for non elements + * M (logical) mask to limit the distance calculation roughly, e.g., to + * the brain defined by a convex hull + * WARNING: Voxels have to see objects within the mask! + * D (single) distance image + * L (uint8) label map + * I (uint32) index of nearest point + * + * Examples: + * % (1) distance from two points with a simple mask + * A = zeros(50,50,3,'single'); A(15,25,2)=1; A(35,25,2)=1; + * B = false(size(A)); B(5:end-5,5:end-5,:) = true; + * D = cat_vbdist(A,B); + * ds('d2sm','',1,A/3+B/3+1/3,D/20,2); + * + * % (2) not working mask definition + * B = false(size(A)); B(5:end-5,5:end-5,:) = true; + * B(10:end-10,10:end-10,:) = false; + * D = cat_vbdist(A,B); + * ds('d2sm','',1,A/3+B/3+1/3,D/20,2); + * ______________________________________________________________________ + * + * Christian Gaser, Robert Dahnke + * Structural Brain Mapping Group (https://neuro-jena.github.io) + * Departments of Neurology and Psychiatry + * Jena University Hospital + * ______________________________________________________________________ + * $Id$ + */ + +#include ""mex.h"" +#include ""math.h"" +/* #include ""matrix.h"" */ +#include ""float.h"" +#include +#include + + +#ifdef _MSC_VER + #define FINFINITY (FLT_MAX+FLT_MAX); + static const unsigned long __nan[2] = {0xffffffff, 0x7fffffff}; + #define FNAN (*(const float *) __nan) +#else + #define FINFINITY 1.0f/0.0f; + #define FNAN 0.0f/0.0f +#endif + +/* estimate minimum of A and its index in A */ +void pmin(float A[], int sA, float *minimum, int *index) +{ + *minimum = FLT_MAX; *index = 0; /* printf(""%d "",sizeof(A)/8); */ + for(int i=0; i0.0) && (*minimum>A[i])) + { + *minimum = A[i]; + *index = i; + } + } +} + + +/* estimate x,y,z position of index i in an array size sx,sxy=sx*sy... */ +void ind2sub(int i, int *x, int *y, int *z, int sxy, int sy) { + *z = (int)floor( (double)i / (double)sxy ) +1; + i = i % (sxy); + *y = (int)floor( (double)i / (double)sy ) +1; + *x = i % sy + 1; +} + +/* main function */ +void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { + if (nrhs<1) mexErrMsgTxt(""ERROR:cat_vbdist: not enough input elements\n""); + if (nlhs>4) mexErrMsgTxt(""ERROR:cat_vbdist: too many output elements.\n""); + if (mxIsSingle(prhs[0])==0) mexErrMsgTxt(""ERROR:cat_vbdist: first input (object) must be an 3d single matrix\n""); + if (nrhs==2 && mxIsLogical(prhs[1])==0) mexErrMsgTxt(""ERROR:cat_vbdist: second input (mask) must be an 3d logical matrix\n""); + if (nrhs==3 && mxIsDouble(prhs[2])==0) mexErrMsgTxt(""ERROR:cat_vbdist: third input (vx_vol) must be an double matrix\n""); + if (nrhs==3 && mxGetNumberOfElements(prhs[2])!=3) mexErrMsgTxt(""ERROR:cat_vbdist: third input (vx_vol) must have 3 Elements""); + if (nrhs==4 && mxIsDouble(prhs[3])==0) mexErrMsgTxt(""ERROR:cat_vbdist: fourth input (debug) must be one double value\n""); + if ( mxGetNumberOfElements(prhs[0])>=2147483647 ) mexErrMsgTxt(""ERROR:cat_vbdist: Matrix size is too big for currently used integer datatype.\n""); + + /* main information about input data (size, dimensions, ...) */ + const mwSize *sL = mxGetDimensions(prhs[0]); + const int dL = mxGetNumberOfDimensions(prhs[0]); + const int nL = mxGetNumberOfElements(prhs[0]); + const int x = (int)sL[0]; + const int y = (int)sL[1]; + const int xy = x*y; + + /* get parameters or set defaults */ + bool debug; + const mwSize sS[2] = {1,3}; + mxArray *SS = mxCreateNumericArray(2,sS,mxDOUBLE_CLASS,mxREAL); + double *S = mxGetPr(SS); + if (nrhs<3) {S[0]=1.0; S[1]=1.0; S[2]=1.0;} else {S = mxGetPr(prhs[2]);} + if (nrhs<4) {debug=false;} else {double*debugd = (double *) mxGetPr(prhs[3]); debug= (*debugd) > 0;} + + float s1 = (float)fabs(S[0]),s2 = (float)fabs(S[1]),s3 = (float)fabs(S[2]); + const float s12 = (float) sqrt( (double) s1*s1 + s2*s2); /* xy - voxel size */ + const float s13 = (float) sqrt( (double) s1*s1 + s3*s3); /* xz - voxel size */ + const float s23 = (float) sqrt( (double) s2*s2 + s3*s3); /* yz - voxel size */ + const float s123 = (float) sqrt( (double) s12*s12 + s3*s3); /* xyz - voxel size */ + + /* indices of the neighbor Ni (index distance) and euclidean distance NW */ + const int sN = 14; + const int NI[14] = { 0, -1,-x+1, -x,-x-1, -xy+1,-xy,-xy-1, -xy+x+1,-xy+x,-xy+x-1, -xy-x+1,-xy-x,-xy-x-1}; + const float ND[14] = {0.0, s1, s12, s2, s12, s13, s3, s13, s123, s23, s123, s123, s23, s123}; + float DN[14]; + float DNm = FLT_MAX; + int DNi; + + /* data intern */ + mxArray *Y[2]; + Y[0] = mxCreateNumericArray(dL,sL,mxUINT32_CLASS,mxREAL); + Y[1] = mxCreateNumericArray(dL,sL,mxUINT8_CLASS,mxREAL); + unsigned int *I = (unsigned int *)mxGetPr(Y[0]); + unsigned char *L = (unsigned char *)mxGetPr(Y[1]); + + /* data output depending on nlhs */ + plhs[0] = mxCreateNumericArray(dL,sL,mxSINGLE_CLASS,mxREAL); + if (nlhs>1) plhs[1] = mxCreateNumericArray(dL,sL,mxUINT32_CLASS,mxREAL); + if (nlhs>2) plhs[2] = mxCreateNumericArray(dL,sL,mxUINT8_CLASS,mxREAL); + + float *D; unsigned int * IO; unsigned char * LO; + D = (float *)mxGetPr(plhs[0]); + if (nlhs>1) IO = (unsigned int *)mxGetPr(plhs[1]); + if (nlhs>2) LO = (unsigned char *)mxGetPr(plhs[2]); + + /* get data */ + float *V = (float*)mxGetPr(prhs[0]); + bool *R; if (nrhs>1) R=(bool *)mxGetPr(prhs[1]); + bool e255 = false; + + + /* intitialisation */ + for (int i=0;i=0.5) D[i]=0.0; else D[i]=FLT_MAX; + if (L[i]>255.0) + { + if (e255==false) + { + printf(""Warning: First parameter of vbdist > 255!\n""); + e255 = true; + } + L[i] = 255; + } + } + + if (debug) { + printf("" Debug: debug = %d\n"",debug); + printf("" Size: nL=%d, sN=%d\n"",nL,sN); + printf("" Neighbour distances: x=%1.2f,y=%1.2f,z=%1.2f - xy=%1.2f,yz=%1.2f,xz=%1.2f - xyz=%1.2f\n"",s1,s2,s3,s12,s23,s13,s123); + } + + int u,v,w,nu,nv,nw; + /* forward direction that consider all points smaller than i */ + for (int i=0;i0) && (nrhs==1 || (nrhs>1 && R[i]==true) ) ) + { + ind2sub(i,&u,&v,&w,xy,x); + + /* read neighbor values */ + for (int n=0;n=nL) || (abs(nu-u)>1) || (abs(nv-v)>1) || (abs(nw-w)>1) ) ni=i; + DN[n] = D[ni] + ND[n]; + } + + /* find minimum distance within the neighborhood */ + pmin(DN,sN,&DNm,&DNi); + + /* update values */ + if (DNi>0) { + L[i] = L[i+NI[DNi]]; + I[i] = (unsigned int) I[i+NI[DNi]]; + D[i] = DNm; + ind2sub((int)I[i],&nu,&nv,&nw,xy,x); + D[i] = (float)sqrt(pow((double)(u-nu)*s1,2) + pow((double)(v-nv)*s2,2) + pow((double)(w-nw)*s3,2)); + } + } + } + + /* backward direction that consider all points larger than i */ + for (int i=nL-1;i>=0;i--) + { + if ( (D[i]>0) && (nrhs==1 || (nrhs>1 && R[i]==true) ) ) + { + + ind2sub(i,&u,&v,&w,xy,x); + + /* read neighbor values */ + for (int n=0;n=nL) || (abs(nu-u)>1) || (abs(nv-v)>1) || (abs(nw-w)>1) ) ni=i; + DN[n] = D[ni] + ND[n]; + } + + /* find minimum distance within the neighborhood */ + pmin(DN,sN,&DNm,&DNi); + + /* update values */ + if (DNi>0) { + L[i] = L[i-NI[DNi]]; + I[i] = (unsigned int) I[i-NI[DNi]]; + D[i] = DNm; + ind2sub((int)I[i],&nu,&nv,&nw,xy,x); + D[i] = (float)sqrt(pow((double)(u-nu)*s1,2) + pow((double)(v-nv)*s2,2) + pow((double)(w-nw)*s3,2)); + } + } + } + + /* clear internal variables */ + /* + mxDestroyArray(plhs[1]); + mxDestroyArray(plhs[2]); + */ + + /* set outputs and correct index values */ + if (nlhs>1) for (int i=0;i2) for (int i=0;i> see also useBrainMasking + def.fast = 1; % CAT vs. SPM smoothing + def.median = 1; % use median filter (values from 0 to 1) + def.sanlm = 0; % use sanlm filter (0|1) + def.localsmooth = 1; % use further local smoothing within the tissue class (values from 0 to 1) + def.defTPM = fullfile(spm('dir'),'tpm','TPM.nii'); % SPM TPM + def.defTPMmix = 0.05; % percentual use of the SPM TPM + def.fstrength = 0; + % public GUI + def.prefixTPM = 'longTPM_'; + def.prefixBM = 'longbrain_'; + def.smoothness = 1; % main smoothing factor + def.verb = 0; % be verbose + def.useBrainMasking = 2; % 0-none, 1-brainmask, 2-brainmask+backgroundmask + % RD20201220: extended for further plasticity tests + % 0-old approach (R1844) + job = cat_io_checkinopt(job,def); + + + % main parameter to define three major settings + if job.fstrength == 1 % hard TPM small changes in plasticity + job.localsmooth = 0.2; % this filters only within the tissue PVE range and distribute the local tissue amount more equaly + job.median = 0.2; % the median remove more details als localsmooth + job.smoothness = 0.2; % this is the main weight of the Gaussian smoothing filter scsize + job.defTPMmix = 0.001; % only very low amount of the standard SPM TPM + elseif job.fstrength == 2 % hard TPM small changes in plasticity + job.localsmooth = 0.5; % this filters only within the tissue PVE range and distribute the local tissue amount more equaly + job.median = 0.5; % the median remove more details als localsmooth + job.smoothness = 0.5; % this is the main weight of the Gaussian smoothing filter scsize + job.defTPMmix = 0.01; % only very low amount of the standard SPM TPM + elseif job.fstrength == 3 % medium changes in aging (default) + job.localsmooth = 1; + job.median = 1; + job.smoothness = 2; + job.defTPMmix = 0.05; + elseif job.fstrength == 4 % soft TPM for strong changes in development + job.localsmooth = 1; + job.median = 1; + job.smoothness = 2; + job.defTPMmix = 0.1; + end + + % helping functions + cell2num = @(x) cell2mat( shiftdim(x(:), -ndims(x{1})) ) ; + clsnorm = @(x) shiftdim( num2cell( cell2num(x) ./ repmat( sum( cell2num(x) , ndims(x{1}) + 1) , ... + [ones(1,ndims(x{1})),numel(x)]) , 1:ndims(x{1})) , ndims(x{1})) ; + + if 0 + %% test case + job.files = { + ...'/Users/dahnke/Documents/MATLAB/spm12/toolbox/cat12/cattest/CAT12.1R1391_MACI64/mri/p1single_subj_t1.nii,1'; + ...'/Users/dahnke/MRdataBO/mri/rp1M017_affine.nii,1'; + '/Volumes/WD4TBE/MRData/SIMON/mri/rp1SIMON_32633_T1_ANZ_SI30_sd20151117-rs00_affine.nii,1'; + }; + end + + + if isfield(job,'process_index') && job.verb, spm('FnBanner',mfilename); end + + % display something + spm_clf('Interactive'); + spm_progress_bar('Init',numel(job.files),'TPM creation','Volumes Completed'); + + for fi = 1:numel(job.files) + spm_progress_bar('Set',fi-0.9); + + %% first we need the paths to the other classes + [pp,ff,ee] = spm_fileparts( job.files{fi} ); + files = cell(1,6); p1=strfind(ff,'p1'); + if job.verb, fprintf('Process ""%s"" ',spm_str_manip(... + fullfile(pp,sprintf('%s%s',ff,ee)),'a70')); + end + for ci=1:6 + files{ci} = fullfile(pp,sprintf('%s%d%s%s',ff(1:p1),ci,ff(p1+2:end),ee)); + if ~exist(files{ci},'file') + error('cat_long_createTPM:missInput','Can not find class %d file: ""%s""',ci,files{ci}); + end + end + + + % now we can load all images + Ytpm = cell(1,6); + for ci = 1:6 + Vtemp = spm_vol( files{ci} ); + vx_vol = sqrt(sum(Vtemp.mat(1:3,1:3).^2)); + Ytpm{ci} = single( spm_read_vols( Vtemp ) ); + end + Ytpm = clsnorm(Ytpm); + + + % load SPM TPM with 1.5 mm + Vdtpm = spm_vol( job.defTPM ); + if all(Vtemp.dim == Vdtpm(1).dim) %&& (sum(sum((Vtemp.mat-Vdtpm(1).mat).^2)) < 1e-6) + Ydtpm = spm_load_priors(Vdtpm); for ci=1:6, Ydtpm{ci} = single(Ydtpm{ci}); end + else + Ydtpm = cat_vol_load_priors(Vdtpm, Vtemp); for ci=1:6, Ydtpm{ci} = single(Ydtpm{ci}); end + cat_io_cprintf('warn','\n Image resolutions differs from SPM TPM resolution. Cannot mix the images.\n'); + end + spm_progress_bar('Init',numel(job.files),'TPM creation','Volumes Completed');% have to reset it + spm_progress_bar('Set',fi-0.2); + + + % complete background + Ys = sum( cell2num(Ytpm) , 4); + Ytpm{6} = Ytpm{6} + (1-Ys); + Ytpm{6}(isnan(Ys)) = 1; + Ytpm{5} = Ytpm{5}.^2; % use exp. to reduce low skull-intensities + Ytpm{6} = single(real(Ytpm{6}.^(1/2))); % use exp. to reduce low skull-intensities + % create brainmask + Yb = sum( cell2num(Ytpm(1:3)) , 4); + Yb = max(Yb, cat_vol_smooth3X(single(cat_vol_morph(Yb>0.1,'lc',1)),1.5)); + % avoid boundary problems for CAT report skull surface by setting the + % edge to background or to the SPM TPM value + bd = 1; + Ybgb = true(size(Ytpm{1})) & sum( cell2num(Ytpm(1:5)) , 4)<0.5; Ybgb(bd+1:end-bd,bd+1:end-bd,bd+1:end-bd) = false; + Ybgb = Ybgb | cat_vol_morph(isnan(Ys) & ~Yb,'d',2); % more problems close to NaN regions + Ybgb = smooth3(Ybgb); + for ci=1:5, Ytpm{ci}(isnan(Ytpm{ci})) = 0; Ytpm{ci} = Ytpm{ci} .* (1-Ybgb); end + Ytpm{6}(isnan(Ytpm{ci})) = 0; Ytpm{6} = max(Ytpm{6},Ybgb); + Ytpm = clsnorm(Ytpm); + + spm_progress_bar('Set',fi-0.8); + + + + %% smoothing & mixing + % the goal is to remove time point specific spatial information but keep + % the main folding pattern + + + Ytpms = Ytpm; + if ~debug, clear Ytpm; end + + for ci = 1:numel(Ytpms) + % median filter .. this works quite well + if job.median + Ytpms{ci} = Ytpms{ci} .* (1-job.median) + job.median .* cat_vol_median3(Ytpms{ci},Yb>0,Yb>0); %,Ytpms{ci}>0,Ytpms{ci}>-1); + end + + % denoising - too small effect and too slow + if job.sanlm + cat_sanlm(Ytpms{ci},1,3); + end + end + Ytpms = clsnorm(Ytpms); + + + % RD20211028: Keep the backround with very high probability to avoid + % miss-classificaktion by other head tissue classes. + if job.useBrainMasking > 0 + Ybg = cat_vol_smooth3X( Ytpms{6} > 128 ,max(1,job.smoothness/2)); + end + + % main smooting + for si = 1:numel(job.ssize) + for ci = 1:numel(Ytpms) + Ytpmts = Ytpms{ci} + 0 .* Ybgb; + + if job.fast + % cat_vol_smooth3X is much faster in case of higher resolutions and + % the image boundaries are better. However, the result is to strong + % filtered for higher values do to the resolution reduction and I + % use sqrt to reduce this effect here. + % This also increase the background boundary effect. + if mean(job.ssize(si) .* job.scsize(ci) ./ vx_vol) > 0 + Ytpmts = cat_vol_smooth3X( Ytpmts , mean( (job.ssize(si) .* ... + job.scsize(ci) .* job.smoothness ./ vx_vol).^1/2) ) * job.sweight(si); + end + else + spm_smooth( Ytpmts * job.sweight(si) , Ytpmts, job.ssize(si) ... + .* job.scsize(ci) .* job.smoothness ./ vx_vol ); + end + if ci<6, Ytpmts = Ytpmts .* (1-Ybgb); end + + % local smoothing this will further reduce the ribbon effect + if job.localsmooth + Ytpmts = Ytpmts * (1-job.sweight(si)) * (1-job.localsmooth) + ... + job.localsmooth .* cat_vol_localstat(Ytpmts,Ytpmts>0,job.localsmooth,1) * job.sweight(si); + end + + % define minimum prob of each class + Ytpmts = max( Ytpmts , job.minprob * job.sweight(si)); + Ytpmts = Ytpmts ./ max(Ytpmts(:)); + + % mix individual and SPM default TPM + if job.defTPMmix>0 %&& sum(sum((Vtemp.mat-Vdtpm(1).mat).^2)) < 1e-6 + Ytpmts = Ytpmts.*(1-job.defTPMmix) + (job.defTPMmix).*Ydtpm{ci}; + end + + % use the brain mask to support a harder brain boundary + if job.useBrainMasking == 2 + if ci<4 + Ytpmts = Ytpmts .* max(job.minprob,Yb) .* max(job.minprob,1 - Ybg); + else + Ytpmts = Ytpmts .* max(job.minprob,1-Yb) .* max(job.minprob,1 - Ybg); + end + elseif job.useBrainMasking == 1 + if ci<4 + Ytpmts = Ytpmts .* max(job.minprob,Yb); + else + Ytpmts = Ytpmts .* max(job.minprob,1-Yb); + end + else + if ci<4 + Ytpmts = Ytpmts .* Yb; + else + Ytpmts = Ytpmts .* (1-Yb); + end + end + %Ytpmts = min(1,max(Ytpmts,job.minprob)); + + % combine the different smoothing levels + if si==1 + Ytpms{ci} = Ytpmts; + else + Ytpms{ci} = Ytpms{ci} + Ytpmts; + end + end + spm_progress_bar('Set',fi-0.8 + (0.7 * si / numel(job.ssize))); + end + + % final setting with minimal probability + if job.useBrainMasking > 0 + % new correction with full background + for ci=1:3, Ytpms{ci} = max( Ytpms{ci} .* Yb .* (1 - Ybg), job.minprob * (1 - Ybg)); end + for ci=4:5, Ytpms{ci} = max( Ytpms{ci} .* (1-Yb) .* (1 - Ybg), job.minprob * (1 - Ybg)); end + Ytpms{6} = max(Ytpms{6},job.minprob * 6); %Ybgb - job.minprob * 5 ); + else + % old correction by boxed backgrounds (R1844) + for ci=1:3, Ytpms{ci} = max( Ytpms{ci} .* (1 - Ybgb) , job.minprob); end % .* Yb ); end + for ci=4:5, Ytpms{ci} = max( Ytpms{ci} .* (1 - Ybgb) , job.minprob); end % .* (1-Yb) ); end + Ytpms{6} = max(Ytpms{6},job.minprob); %Ybgb - job.minprob * 5 ); + end + Ytpms = clsnorm(Ytpms); + clear Ytpmts; + + + + + %% write result TPM + out.tpm{fi} = fullfile(pp,[job.prefixTPM ff ee ',1']); + for li=1:numel(Ytpms) + out.tpmtiss{fi}{li} = fullfile(pp,[job.prefixTPM ff ee sprintf(',%d',li)]); + end + + Ndef = nifti; + Ndef.dat = file_array(fullfile(pp,[job.prefixTPM ff ee]),[size(Ytpms{1}),numel(Ytpms)],... + [spm_type('float32') spm_platform('bigend')],0,1,0); + Ndef.mat = Vtemp(1).mat; + Ndef.mat0 = Vtemp(1).mat; + Ndef.descrip = sprintf(['individual TPM for longitudinal processing in CAT ' ... + 'created by cat_long_createTPM (smoothness=%d)'],job.smoothness); + create(Ndef); + Ndef.dat(:,:,:,:,:) = cell2num(Ytpms); + + + % brainmask + if job.writeBM + Ndef = nifti; + Ndef.dat = file_array(fullfile(pp,[job.prefixBM ff '.nii']),size(Yb),... + [spm_type('uint8') spm_platform('bigend')],0,1/255,0); + Ndef.mat = Vtemp(1).mat; + Ndef.mat0 = Vtemp(1).mat; + Ndef.descrip = sprintf(['individual TPM for longitudinal processing in CAT ' ... + 'created by cat_long_createTPM (smoothness=%d)'],job.smoothness); + create(Ndef); + Ndef.dat(:,:,:) = Yb; + end + + + %% + if job.verb + fprintf('done > %s. \n',spm_file('Display','link',... + sprintf('spm_image(''Display'',''%s'')',fullfile(pp,[job.prefixTPM ff ee ',1'])) )); + end + spm_progress_bar('Set',fi); + + %% + clear Ytpms Yb + end + if isfield(job,'process_index') && job.verb + fprintf('\nDone\n'); + end + spm_progress_bar('Clear'); + +function b0 = cat_vol_load_priors(B,Vo) +% Loads the tissue probability maps for segmentation +% FORMAT b0 = cat_vol_load_priors(B,Vo) +% B - structures of image volume information (or filenames) +% b0 - a cell array of tissue probabilities +%__________________________________________________________________________ +% Copyright (C) 2005-2011 Wellcome Trust Centre for Neuroimaging + +% John Ashburner +% $Id$ + +if nargin < 2 + Vo = B(1); +end + +% deg = 3; +lm = 0; +if ~isstruct(B), B = spm_vol(B); end +Kb = length(B); +b0 = cell(Kb,1); +for k1=1:(Kb) + b0{k1} = zeros(Vo.dim(1:3)); +end + +spm_progress_bar('Init',Vo.dim(3),'Loading priors','Planes loaded'); +for i=1:Vo.dim(3) + M0 = spm_matrix([0 0 -i 0 0 0 1 1 1]); + s = zeros(Vo.dim(1:2)); + M = inv(M0 * inv(Vo.mat) * B(1).mat); + for k1=1:Kb + tmp = spm_slice_vol(B(k1),M,Vo.dim(1:2),0)*(1-lm*2)+lm; + b0{k1}(:,:,i) = max(min(tmp,1),0); + s = s + tmp; + end + t = s>1; + if any(any(t)) + for k1=1:Kb + tmp = b0{k1}(:,:,i); + tmp(t) = tmp(t)./s(t); + b0{k1}(:,:,i) = tmp; + end + end + s(t) = 1; + b0{Kb+1}(:,:,i) = max(min(1-s,1),0); + spm_progress_bar('Set',i); +end +spm_progress_bar('Clear'); +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_io_data2mat.m",".m","10352","359","function out = cat_io_data2mat(opt,par,scaling) +% Save spatially registered volume or resampled surface data as Matlab data matrix for further +% use with machine learning tools such as relevance/support vector approaches or Gaussian Process +% models. Spatial structure of the data is not considered. +% Volume data will be optionally masked to remove non-brain areas. +% +% FORMAT cat_io_data2mat(opt,scaling) +% +% volume or surface data: +% opt.data - cell of char array of filenames +% opt.c - confounds data to be removed +% opt.fname - filename for saving mat-file +% opt.outdir - output directory of saved mat-file +% +% additional parameters for volume data only: +% opt.resolution - resampling spatial resolution for volume data +% opt.mask - optional brainmask for volume data +% opt.mask_th - optional threshold for brainmask for volume data +% opt.fwhm - optional Gaussian smoothing kernel size in FWHM +% +% additional parameters to be saved with mat file: +% par - structure with parameter as name and the values +% +% scaling - optionally define either a vector for user-specified scaling data or a +% constant (2 for global scaling) +% +% saved parameters: +% Y - data matrix with size number of subjects x number of voxels/vertices +% label - label of samples +% ind - index for volume or surface data inside mask +% dim - dimension of original data +% V - structure array containing data information of surface or resampled volume +% sample - structure array containing sample information +% +% Examples: +% Select recursively all gray matter segments from folder1 +% for the 1st sample and folder 2 from the 2nd sample and save resampled data +% with 4mm resampling spatial resolution after filtering with fwhm of 8mm. +% Additionally save age and male as parameter in the mat-file. +% the parameter ""files"" should be defined as ""{files}"") +% files{1} = spm_select('FPListRec',folder1,'^mwp1.*\.nii$'); +% files{2} = spm_select('FPListRec',folder2,'^mwp1.*\.nii$'); +% cat_io_data2mat(struct('data',{files},'resolution',4,'fwhm',8,'mask',cat_get_defaults('extopts.brainmask'),... +% 'fname','Data.mat'),struct('age',age,'male',male)); +% +% Select recursively all 12mm smoothed and resampled thickness data from current folder +% and save Data.mat in subfolder test +% files = spm_select('FPListRec',pwd,'^s12.mesh.thickness.resampled_32k.*\.gii$'); +% cat_io_data2mat(struct('data',files,'fname','Data.mat','outdir','test')); +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +%#ok<*NASGU,*AGROW> + +if ~exist('opt','var') || (~isfield(opt,'data_type') && ~isfield(opt,'data') ) + error('No data defined.'); +end + +if ~exist('opt','var'), opt = struct(); end +def.c = []; +def.fname = 'Data.mat'; +def.outdir = {'.'}; +opt = cat_io_checkinopt(opt,def); + +if isfield(opt,'data') % use simpler field structure for call as script + if ischar(opt.data) + sample.data{1} = opt.data; + else + sample.data = opt.data; + end + if isfield(opt,'mask') + brainmask = opt.mask; + end + if isfield(opt,'mask_th') + mask_th = opt.mask_th; + else + mask_th = 0.5; + end + if isfield(opt,'resolution') + resolution = opt.resolution; + end + if isfield(opt,'fwhm') + fwhm = opt.fwhm; + end +elseif isfield(opt.data_type,'vol_data') % volume data + brainmask = char(opt.data_type.vol_data.mask); + sample = opt.data_type.vol_data; + resolution = sample.resolution; +elseif isfield(opt.data_type,'surf_data') % surface data + sample = opt.data_type.surf_data; +else + error('No data defined.'); +end + +n_samples = numel(sample.data); +n_subjects = zeros(n_samples,1); +label = []; + +V = cell(n_samples,1); +label = []; +for i = 1:n_samples + V{i} = spm_data_hdr_read(char(sample.data{i})); + n_subjects(i) = size(V{i},1); + label = [label; i*ones(n_subjects(i),1)]; +end +n_all_subjects = numel(label); + +% cell structure is expected +if ~isempty(opt.c) && isnumeric(opt.c), opt.c = {opt.c}; end + +n_confounds = numel(opt.c); +confounds = []; +for i = 1:n_confounds + [m,n] = size(opt.c{i}); + + % transpose if necessary + if m ~= n_all_subjects && n == n_all_subjects + opt.c{i} = opt.c{i}'; + m = size(opt.c{i},1); + end + + % check size of confounds + if m ~= n_all_subjects + error('Length of nuisance parameters (m=%d) differs from number of subjects (n=%d)',m,n_all_subjects); + end + + confounds = [confounds opt.c{i}]; +end + +outname = opt.fname; +out.fname{1} = outname; +outdir = opt.outdir{1}; +if ~isempty(outdir) + if ~exist(outdir,'dir') + mkdir(outdir); + end + outname = fullfile(outdir,outname); +end + +% 3D data +if ~spm_mesh_detect(V{1}(1)) + % this is probably not the most elegant way but used here for compatibility with my BrainAGE tools... + % 1mm reference fields + Vres.mat = [1 0 0 -90; 0 1 0 -126; 0 0 1 -72; 0 0 0 1]; + Vres.dim = [181 217 181]; + + if ~isempty(brainmask) + Vm = spm_vol(brainmask); + end + + Vres.dim = round(Vres.dim/resolution); + Vres.mat(1:3,1:3) = resolution*Vres.mat(1:3,1:3); + Vres.mat(1:3,4) = Vres.mat(1:3,4) - [resolution resolution resolution]'; + dim = Vres.dim(1:3); + +else + % check that mesh contains data + if isfield(V{1}(1),'private') && ~isfield(V{1}(1).private,'cdata') + if ~isfield(V{1}(1),'cdata') + error('No data found in mesh') + end + end + + % use mask from first mesh and assume this holds for all data + if isfield(V{1}(1),'private') + ind = find(isfinite(V{1}(1).private.cdata(:))); + else + ind = find(isfinite(V{1}(1).cdata(:))); + end + dim = V{1}(1).dim(1); +end + +% global scaling +if nargin > 2 + % user specified scaling + if isvector(scaling) + % check size of scaling vector + if numel(scaling) ~= n_all_subjects + error('Size of scaling parameter (n=%d) does not fit to number of subjects (n=%d)',numel(scaling), n_all_subjects) + end + count = 1; + for j=1:n_samples + for i = 1:n_subjects(j) +% RD20240925: I added this to create the variable ""g"" that was missing before. + % compute mean voxel value (within per image fullmean/8 mask) + if ~spm_mesh_detect(V{1}(1)) + g = spm_global(V{j}(i)); + else + if isfield(V{1}(1),'private') + y = V{j}(i).private.cdata(:); + else + y = V{j}(i).cdata(:); + end + g = mean(y(isfinite(y))); + end +% RD20240925: end added part. + V{j}(i).pinfo(1:2,:) = V{j}(i).pinfo(1:2,:)/g(count); % <<< the g is not existing otherwise! + count = count + 1; + end + end + % mean scaling + elseif scaling == 2 + fprintf('Calculating globals\n') + for j=1:n_samples + for i = 1:n_subjects(j) + % compute mean voxel value (within per image fullmean/8 mask) + if ~spm_mesh_detect(V{1}(1)) + g = spm_global(V{j}(i)); + else + if isfield(V{1}(1),'private') + y = V{j}(i).private.cdata(:); + else + y = V{j}(i).cdata(:); + end + g = mean(y(isfinite(y))); + end + V{j}(i).pinfo(1:2,:) = V{j}(i).pinfo(1:2,:)/g; + end + end + end + +end + +Y = []; +Ymean = []; +C = zeros(n_all_subjects); + +% 3D data +if ~spm_mesh_detect(V{1}(1)) + + if ~exist('mask_th') || isempty(mask_th) + mask_th = 0.5; + end + M1 = cell(Vres.dim(3),1); + + if isempty(brainmask) + mask_ind = ones(Vres.dim,'logical'); + else + mask_ind = zeros(Vres.dim,'logical'); + end + ind = find(mask_ind); + + for sl=1:Vres.dim(3) + % read mask + M = spm_matrix([0 0 sl 0 0 0 1 1 1]); + + if ~isempty(brainmask) + Mm = Vres.mat\Vm.mat\M; + mask_slice = spm_slice_vol(Vm,Mm,Vres.dim(1:2),1); + mask_ind(:,:,sl) = mask_slice > mask_th; + end + M1{sl} = Vres.mat\V{1}(1).mat\M; + end + + + for j=1:n_samples + if n_subjects(j) > 500, cat_progress_bar('Init',n_subjects(j),'reading...','subjects completed','cmd%'); end + yi = zeros(n_subjects(j), sum(mask_ind(:)), 'single'); + for i = 1:n_subjects(j) + + vol = spm_read_vols(V{j}(i)); + + % optional smoothing if fwhm is defined + if exist('fwhm','var') + if isscalar(fwhm) + fwhm = repmat(fwhm,1,3); + end + if sum(fwhm) > 0 + spm_smooth(vol,vol,fwhm,0); + end + end + + ysl = []; + for sl=1:Vres.dim(3) + + % read data inside mask + if ~isempty(mask_ind(:,:,sl)) + try + d = spm_slice_vol(vol,M1{sl},Vres.dim(1:2),1); + catch + fprintf('File %s could not be read\n',V{j}(i).fname); + return + end + end + ysl = [ysl; d(mask_ind(:,:,sl))]; + end + yi(i,:) = single(ysl); + + if n_subjects(j) > 500, cat_progress_bar('Set',i); end + end + if n_subjects(j) > 500, cat_progress_bar('Clear'); end + + Y = [Y; yi]; + end + +else % meshes + Y = zeros(n_all_subjects,numel(ind)); + count = 1; + for j=1:n_samples + for i = 1:n_subjects(j) + if dim ~= V{j}(i).dim(1) + error('Mesh size of %s differs (%d vs. %d)',V{j}(i).fname,V{j}(i).dim(1),dim) + end + try + if isfield(V{1}(1),'private') + Y(count,:) = V{j}(i).private.cdata(ind); + else + Y(count,:) = V{j}(i).cdata(ind); + end + catch + fprintf('File %s could not be read\n',V{j}(i).fname); + return + end + count = count + 1; + end + end +end + +% remove confounds +if ~isempty(confounds) + beta = pinv(confounds)*Y; + Y = Y - confounds*beta; +end + +% save surface or resampled volume structure +if spm_mesh_detect(V{1}(1)) + if isfield(V{1}(1),'private') + V = V{1}(1).private; + else + V = V{1}(1); + end + try V = rmfield(V,'cdata'); end %#ok +else + V = Vres; +end + +save(outname,'Y','label','dim','V','ind','sample','-v7.3'); +fprintf('Save data (Y,label,V,dim,ind) in %s.\n',outname); + +% add additional parameters if defined +if nargin > 1 + fnames = fieldnames(par); + str = []; + fprintf('Append:'); + for i = 1:numel(fnames) + name = fnames{i}; + eval([name '=par.(name);']); + save(outname,'-append',name); + fprintf(' %s',name); + end + fprintf('\n'); +end +","MATLAB" +"Neurology","ChristianGaser/cat12","cat_ornlm.m",".m","1439","42","function out = cat_ornlm(in, v, f, h) +% FORMAT out = cat_ornlm(in, v, f, h) +% +% Optimized Blockwise Non Local Means Denoising Filter +% +% v - size of search volume (M in paper) +% f - size of neighborhood (d in paper) +% h - smoothing parameter +% +% Details on ONLM filter +% *************************************************************************** +% The ONLM filter is described in: +% +% P. Coupe, P. Yger, S. Prima, P. Hellier, C. Kervrann, C. Barillot. +% An Optimized Blockwise Non Local Means Denoising Filter for 3D Magnetic +% Resonance Images. IEEE Transactions on Medical Imaging, 27(4):425-441, +% April 2008 +% *************************************************************************** +% +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +rev = '$Rev$'; + +disp('Compiling cat_ornlm.c') + +pth = fileparts(which(mfilename)); +p_path = pwd; +cd(pth); +mex -O cat_ornlm.c ornlm_float.c +cd(p_path); + +out = cat_ornlm(in, v, f, h); + +return +","MATLAB" +"Neurology","ChristianGaser/cat12","development/cat_io_3Dto4D.m",".m","1495","61","function cat_io_3Dto4D(P,filename,avg) + +%#ok<*ASGLU> + + if ~exist('P','var') + P = spm_select(inf,'image','select image of the same space'); + end + if isempty(P), return; end + + if ~exist('filename','var') + filename = '4D'; + end + + if ~exist('avg','var') + avg = 0; + end + + V = spm_vol(P); + P = cellstr(P); + desc=''; + csv = {'ROIid','ROIname'}; + for i=1:numel(P) + [pp,ff]=spm_fileparts(P{i}); + if any(V(1).dim(1:3) ~= V(i).dim(1:3)) %any(V(1).mat(:) ~= V(i).mat(:)) || + error('MATLAB:cat_io_3Dto4D:input_error','Bad resolution: %s %5d\n',i); + end + desc = sprintf('%s%s (%d),',ff,i); + csv = [csv; {i,ff}]; %#ok + end + desc(end)=''; + cat_io_csv(fullfile(spm_fileparts(P{1}),[filename '.csv']),csv); + + if 1 + % real 4D-image + N = nifti; + N.dat = V(1).private.dat; + N.dat.fname = fullfile(spm_fileparts(P{1}),[filename '.nii']); + N.dat.dim(4) = numel(P); + N.mat = V(1).mat; + N.mat0 = V(1).private.mat0; + N.descrip = desc; + create(N); + + for i=1:numel(P) + Y = spm_read_vols(V(i)); + N.dat(:,:,:,i) = Y; + end + end + + if avg + N = nifti; + N.dat = V(1).private.dat; + N.dat.fname = fullfile(spm_fileparts(P{1}),'A4D.nii'); + N.mat = V(1).mat; + N.mat0 = V(1).private.mat0; + N.descrip = desc; + create(N); + Y = spm_read_vols(spm_vol(fullfile(spm_fileparts(P{1}),[filename '.nii']))); + [maxx,N.dat(:,:,:)] = nanmax(Y,[],4); + end +end","MATLAB" +"Neurology","ChristianGaser/cat12","development/cat_vol_average.m",".m","4978","166","function PO = cat_vol_average(P,filename,PT,dt,nr,mask) +% ______________________________________________________________________ +% Creates median images of a set of files P or volumes V with the same +% image properties. +% +% VO = cat_vol_average(V[,filename,PT,dt,nr]) +% VO = cat_vol_average(P[,filename,PT,dt,nr]) +% +% P = char or cell array with filenames +% PT = template image with another resolution (for interpolation) +% V = SPM volume structure +% VO = output volume +% dt = for [median,mean,std] images with spm nii datatype +% (0=no image, 2=uint8, 4=int16, 16=single, ...) +% nr = use number in filename +% filename = name of the outputfile, add median/mean/std automaticly +% mypath/myname.nii > mypath/median003_myname.nii ... +% mask = value for masking +% ______________________________________________________________________ +% Robert Dahnke 2013_08 +% Structural Brain Mapping Group +% University Jena +% +% $Id$ +% ______________________________________________________________________ + + if isstruct(P) + V = P; clear P; + for fi = 1:numel(V), P{fi} = V(fi).fname; end + end + P = char(P); + if isempty(P), VO=struct(); return; end + + if ~exist('nr','var') || isempty(nr) + nr = 0; + end + if nr==0 + nstr = ''; + else + nstr=num2str(size(P,1),'%3.0f'); + end + + if ~exist('filename','var') || isempty(filename) + [pp,ff,ee] = spm_fileparts(P(1,:)); + filename2{1} = fullfile(pp,['median' nstr '_' ff ee]); + filename2{2} = fullfile(pp,['mean' nstr '_' ff ee]); + filename2{3} = fullfile(pp,['std' nstr '_' ff ee]); + else + if iscell(filename) + filename2 = filename; + else + [pp,ff,ee] = spm_fileparts(filename); + filename2{1} = fullfile(pp,['median' nstr '_' ff ee]); + filename2{2} = fullfile(pp,['mean' nstr '_' ff ee]); + filename2{3} = fullfile(pp,['std' nstr '_' ff ee]); + end + end + + if ~exist('dt','var') || isempty(dt) + % median, mean, sd + dt = [16 16 16]; + end + if size(P,1)<2, + warning('MATLAB:cat_vol_average:input','WARNING:cat_vol_average:to small input (n=1)!\n'); + VO=struct(); return; + end + if size(P,1)<3, + warning('MATLAB:cat_vol_average:input','WARNING:cat_vol_average:to small input for median and std (n=2)!\n'); + dt(1)=0; dt(1)=0; + end + + + if numel(dt)==1; dt=repmat(dt,1,3); end + + if exist('PT','var') && ~isempty(PT) %&& exist(PT,'file') + % reslicing + if iscell(PT) && size(PT,1)0 + % median + + + V = spm_vol(P); if exist(filename2{i},'file'), delete(filename2{i}); end + VO1 = V(1); VO1.fname = filename2{i}; VO1.dt(1) = 16; + switch i + case 1, VO1.descript = sprintf('median image of %s scans',size(P,1)); + case 2, VO2.descript = sprintf('mean image of %s scans',size(P,1)); + case 3, VO3.descript = sprintf('std image of %s scans',size(P,1)); + end + + VO1 = spm_create_vol(VO1); + Y = zeros([VO1.dim(1:2),1,size(P,1)],'single'); + for p=1:V(1).dim(3) + for fi = 1:size(P,1), + Y(:,:,1,fi) = single(spm_slice_vol(V(fi),spm_matrix([0 0 p]),V(fi).dim(1:2),0)); + end + switch i + case 1, YO = cat_stat_nanmedian(Y,4); + case 2, YO = cat_stat_nanmean(Y,4); + case 3, YO = cat_stat_nanstd(Y,4); + end + if mask + YM = cat_stat_nansum(Y>0,4)>=(mask*size(P,1)); + YO = YO .* YM; + end + VO1 = spm_write_plane(VO1,YO,p); + end + + if exist('dt','var') + Y = spm_read_vols(VO1); + VO1.dt(1) = dt(i); + if dt(i)==2 || dt(i)==4 + VO1.pinfo(1) = round(max(Y(:))/(16^dt(i)-1)); + end + VO1 = rmfield(VO1,'private'); + if exist(filename2{i},'file'), delete(filename2{i}); end + + spm_write_vol(VO1,Y); + end + PO{i}=filename2{i}; + end + end + + if exist('PT','file') + for fi = 1:numel(P) + delete(P(fi,:)) + end + end +end +function cat_stat_spm_reprint(str,lines) + if ~exist('str','var'), str = ''; end + if ~exist('lines','var'), lines=3; end + if lines>0 + fprintf(sprintf('%s',repmat('\b',1,lines*73+1))); + else + fprintf(sprintf('%s',repmat('\b',1,-lines))); + end + fprintf(str); +end +","MATLAB" +"Neurology","ChristianGaser/cat12","development/Atlas_correct_scaling.m",".m","815","25","function Atlas_correct_scaling +% Correct scaling factors for atlases to 1 +%_______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +csv_file = spm_select('FPList',cat_get_defaults('extopts.pth_templates'),'.csv'); + +for i = 1:size(csv_file,1) + [pth,nam,ext] = spm_fileparts(deblank(csv_file(i,:))); + atlas_file = fullfile(pth,[nam '.nii']); + N = nifti(atlas_file); + atlas = N.dat(:,:,:); + max(atlas(:)) + N.dat.scl_slope = 1; + N.dat.scl_inter = 0; + create(N); + N.dat(:,:,:) = round(atlas); + fprintf('Save corrected atlas %s\n',atlas_file); +end","MATLAB" +"Neurology","ChristianGaser/cat12","development/cat_vol_multiply.m",".m","750","28","function out = cat_vol_multiply(job) +% simply multiply two images +% job +% .data .. original images +% .mask .. mask images to multiply +% out - computation results, usually a struct variable. +%__________________________________________________________________________ +% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging + +% $Id$ + +out.files = cell(size(job.data)); + +for i = 1:numel(job.data) + [pth,nam,ext,num] = spm_fileparts(job.data{i}); + out.files{i} = fullfile(pth,['m' nam ext]); + V = spm_vol(char(job.mask{i},job.data{i})); + Q = V(1); + + % use float32 + Q.dt = V(2).dt; + Q.pinfo = V(2).pinfo; + Q.dt(1) = 16; + Q.pinfo(1) = 1; + Q.fname = out.files{i}; + spm_imcalc(V,Q,'i2.*i1'); +end +","MATLAB" +"Neurology","ChristianGaser/cat12","development/cat_vol_atlas.m",".m","82727","2174","function cat_vol_atlas(atlas,refinei) +%_______________________________________________________________________ +% Function to create a Atlas for a set of subjects with T1 data and +% manualy generated ROIs. If no preprocessing was done CAT is used to +% create the basic images to project the ROI to group space as a 4D +% probability map and a 3D label map for each subject. Based on the 4D +% a 4D probability map and a 3D label map were generated for the group. +% A refinement (median-filter + complete brain labeling) is possible. +% Each Atlas should have a txt-file with information +% +% WARNING: This script only creates uint8 maps! +% +% cat_vol_atlas(atlas,refine) +% +% atlas = name of the atlas +% refine = further refinements (median-filter + complete brain labeling) +% +% Predefined maps for CAT. +% - ibsr (subcortical,ventricle,brainstem,...) +% - hammers (subcortical,cortical,brainstem,...) +% - mori=mori2|mori1|mori3 (subcortical,WM,cortical,brainstem,...) +% - anatomy (some ROIs) +% - aal (subcortical,cortical) +% - lpba40 +% - broadmann (Colins?) +% - neuromorphometrics +% +% ROI description should be available as csv-file: +% ROInr; ROIname [; ROInameid] +% +%_______________________________________________________________________ + +%_______________________________________________________________________ +% TODO: +% - 2 Typen von Atlanten: +% 1) nicht optimiert: +% nur projektion, ggf. original csv-struktur, nummer, ... +% 2) optimiert .... atlas+.nii +% ... meins +% - opt-struktur für parameter +% +% - Zusammenfassung von Atlanten: +% Zusatzfunktion die auf den normalisierten Daten aufbauen könnte. +% Dazu muessten für die Atlantenauswahl mittel Selbstaufruf die Grund- +% daten generieren und könnte anschließen eine Merge-Funtkion starten. +% Hierbei wird es sich um eine vollständig manuell zu definierede Fkt. +% handeln! +% - Region-Teilregion +%_______________________________________________________________________ +% $Id$ + +%#ok<*ASGLU,*WNOFF,*WNON,*TRYNC> + + if ~exist('atlas','var'), atlas=''; end + + [P,PA,Pcsv,Ps,Ptxt,resdir,refine,Pxml] = mydata(atlas); + if isempty(P)|| isempty(P{1}) + P = cellstr(spm_select(inf,'image','select T1 images')); + if isempty(P) || isempty(P{1}) + cat_io_cprintf([1 0 0],'Exit without atlas mapping, because of missing data.\n'); return; + end + PA = cellstr(spm_select(numel(P),'image','select ROIs')); + if isempty(PA) || isempty(PA{1}) + cat_io_cprintf([1 0 0],'Exit without atlas mapping, because of missing data.\n'); return; + end + Pcsv = cellstr(spm_select(1,'image','select ROI csv file')); + if isempty(Pcsv) || isempty(Pcsv{1}) + cat_io_cprintf([1 0 0],'Exit without atlas mapping, because of missing data.\n'); return; + end + resdir = cellstr(spm_select(1,'dirs','result directory')); + if isempty(resdir) || isempty(resdir{1}) + cat_io_cprintf([1 0 0],'Exit without atlas mapping, because of missing data.\n'); return; + end + atlas = 'atlas'; + if ~exist('refinei','var') || isempty(refinei), refine = refini; else refine = 0; end + end + if isempty(P) || isempty(PA), return; end + + nlabel = 1; + recalc = 0; + mode = 0; % modulation of each label map? .. do not work yet ... see cat_vol_defs + if mode, modm='m'; else modm=''; end %#ok + + + % refinement of expert label (smoothing) + if strcmpi(atlas,'anatomy') + % for the anatomy toolbox we got a different input... + % -------------------------------------------------------------------- + + % use CAT to create a segmentation and mapping + Pp0=P; Pwp0=P; Py=P; + for fi = 1:numel(P); + [pp1,ff1] = spm_fileparts(P{fi}); + Py{fi} = fullfile(pp1 ,sprintf('%s%s.nii','y_r',ff1)); + Pp0{fi} = fullfile(pp1 ,sprintf('%s%s.nii','p0' ,ff1)); + Pwp0{fi} = fullfile(pp1 ,sprintf('%s%s.nii','wp0',ff1)); + + if recalc || ~exist(Pp0{fi},'file') || ~exist(Py{fi},'file') + call_cat(P{fi}); + end + + if recalc || ~exist(Pwp0{fi},'file') + calldefs(Py{fi},Pp0{fi},3,0); + end + end + + % side image + Pws=P; + for fi = 1:numel(Ps); + [pps,ffs] = spm_fileparts(Ps{fi}); + Pws{fi} = fullfile(pps,sprintf('%s%s%s.nii',modm,'w' ,ffs)); + + if exist(Ps{fi},'file') +% if refine +% if recalc || ~exist(Pws{fi},'file') +% Vbfi = spm_vol(Pb{fi}); +% Ybfi = single(spm_read_vols(Vbfi)); +% Ybfi = cat_vol_median3(Ybfi); +% Vbfi.fname = Pb{fi}; spm_write_vol(Vafi,Yafi); +% end +% end + if recalc || ~exist(Pws{fi},'file') + calldefs(Py{fi},Ps{fi},0,0); + end + end + end + + % roi maps + Py=P; Pwa=P; Pa=P; PwA=P; + for fi = 1:numel(PA); + [ppa,ffa] = spm_fileparts(PA{fi}); + Py{fi} = fullfile(pp1,sprintf('%s%s.nii','y_r',ff1)); + Pa{fi} = fullfile(ppa,sprintf('%s%s.nii','a' ,ffa)); + Pwa{fi} = fullfile(ppa,sprintf('%s%s%s.nii',modm,'wa' ,ffa)); + PwA{fi} = fullfile(ppa,sprintf('%s%s%s.nii',modm,'w' ,ffa)); + + + % map ROI to atlas + if refine + if recalc || ~exist(Pa{fi},'file') + Vafi = spm_vol(PA{fi}); + Yafi = single(spm_read_vols(Vafi)); + Yafi = cat_vol_median3(Yafi); + spm_smooth(Yafi,Yafi,1); + Vafi.fname = Pa{fi}; spm_write_vol(Vafi,Yafi); + end + + if recalc || ~exist(Pwa{fi},'file') + calldefs(Py{fi},Pa{fi},3,mode); + end + else + if recalc || ~exist(PA{fi},'file') + calldefs(Py{fi},PA{fi},3,mode); + end + end + end + if refine + ROIavg(Pwp0,Pwa,Pws,Pcsv,Ptxt,atlas,resdir,Pxml,nlabel); + else + ROIavg(Pwp0,PwA,Pws,Pcsv,Ptxt,atlas,resdir,Pxml,nlabel); + end + + + % creation of a final CAT atlas as average of other maps + % -------------------------------------------------------------------- + elseif strcmpi(atlas,'cat12') + + cat12tempdir = fullfile(spm('dir'),'toolbox','cat12','templates_volumes'); + + A.l1A = fullfile(cat12tempdir,'l1A.nii'); + A.ham = fullfile(cat12tempdir,'hammers.nii'); + A.ana = fullfile(cat12tempdir,'anatomy.nii'); + A.ibs = fullfile(cat12tempdir,'ibsr.nii'); + %A.lpb = fullfile(cat12tempdir,'lpba40.nii'); + %A.nmm = fullfile(cat12tempdir,'neuromorphometrics.nii'); + + % output file + C = fullfile(cat12tempdir,'cat12.nii'); + + % LAB.CT = { 1,{'l1A'},{[1,2]}}; % cortex + % LAB.BV = { 7,{'l1A'},{[7,8]}}; % Blood Vessels + % LAB.HD = {21,{'l1A'},{[21,22]}}; % head + % LAB.ON = {11,{'l1A'},{[11,12]}}; % Optical Nerv + + % LAB.CT2 = { 1,{'ibs'},{'Cbr'}}; % cortex + if 0 + LAB.MB = {13,{'ham','ibs'},{'MBR','VenV'}}; % MidBrain + LAB.BS = {13,{'ham','ibs' },{'Bst'}}; % BrainStem + LAB.CB = { 3,{'ham','ibs'},{'Cbe'}}; % Cerebellum + LAB.BG = { 5,{'ham','ibs'},{'Put','Pal','CauNuc'}}; % BasalGanglia + LAB.TH = { 9,{'ham','ibs'},{'Tha'}}; % Hypothalamus + LAB.HC = {19,{'ham','ibs'},{'Hip'}}; % Hippocampus + LAB.AM = {19,{'ham','ibs'},{'Amy'}}; % Amygdala + LAB.VT = {15,{'ham','ibs'},{'LatV','LatTemV','VenV'}}; % Ventricle + LAB.NV = {17,{'ham','ibs'},{'Ins','3thV','4thV'}}; % no Ventricle + else + LAB.MB = {13,{'ham'},{'MBR','VenV'}}; % MidBrain + LAB.BS = {13,{'ham'},{'Bst'}}; % BrainStem + LAB.CB = { 3,{'ham'},{'Cbe'}}; % Cerebellum + LAB.BG = { 5,{'ham'},{'Put','Pal','CauNuc'}}; % BasalGanglia + LAB.TH = { 9,{'ham'},{'Tha'}}; % Hypothalamus + LAB.HC = {19,{'ham'},{'Hip'}}; % Hippocampus + LAB.AM = {19,{'ham'},{'Amy'}}; % Amygdala + LAB.VT = {15,{'ham'},{'LatV','LatTemV','VenV'}}; % Ventricle + LAB.NV = {17,{'ham'},{'Ins','3thV','4thV'}}; % no Ventricle + end + create_cat_atlas(A,C,LAB); + + + + + else + % this is the standard pipeline + % -------------------------------------------------------------------- + + % preparte subject + Pp0=P; Pwp0=P; Py=P; Pwa=P; Pa=P; PwA=P; + for fi=1:numel(P) + % other filenames + [pp ,ff ] = spm_fileparts(P{fi}); + [ppa,ffa] = spm_fileparts(PA{fi}); + Pp0{fi} = fullfile(pp ,sprintf('%s%s.nii','p0' ,ff )); + Pwp0{fi} = fullfile(pp ,sprintf('%s%s.nii','wp0',ff )); + Py{fi} = fullfile(pp ,sprintf('%s%s.nii','y_r',ff )); + Pa{fi} = fullfile(ppa,sprintf('%s%s.nii','a' ,ffa)); + Pwa{fi} = fullfile(ppa,sprintf('%s%s%s.nii',modm,'wa' ,ffa)); + PwA{fi} = fullfile(ppa,sprintf('%s%s%s.nii',modm,'w' ,ffa)); + + if ~exist(Py{fi},'file') + Py{fi} = fullfile(pp ,sprintf('%s%s.nii','y_',ff )); + end + + % use CAT to create a segmentation and mapping + if recalc || ~exist(Pp0{fi},'file') || ~exist(Py{fi},'file') + call_cat(P{fi}); + end + + if refine + refiter = round(refine); + refsize = round(refine); + + if recalc || ( ~exist(Pwa{fi},'file') || ~exist(Pwp0{fi},'file') ) + % refinement of the expert label + Vafi = spm_vol(PA{fi}); Yafi = single(spm_read_vols(Vafi)); + % Vp0fi = spm_vol(Pp0{fi}); Yp0fi = single(spm_read_vols(Vp0fi)); Vafi.mat = Vp0fi.mat; + for xi=1:refiter, Yafi=cat_vol_localstat(Yafi,true(size(Yafi)),refsize*2,7); end + % Fill unaligned regions: + % This do not work! + % das ergibt leider nicht immer sinn!!! beim aal gibts bsp, kein + % hirnstamm und das kleinhirn besetzt hier dann alles!!! + %vx_vol = sqrt(sum(Vafi.mat(1:3,1:3).^2)); + %[YD,YI,Yafi]=cat_vbdist(Yafi,smooth3(Yp0fi)>0); Yafi=single(Yafi); clear YD YI; + Vafi.dt = [4 0]; Vafi.pinfo(1) = 1; + Vafi.fname = Pa{fi}; spm_write_vol(Vafi,Yafi); + + % map ROI to atlas + calldefs(Py{fi},Pa{fi} ,0,mode); + calldefs(Py{fi},Pp0{fi},3,0); + + % refinement of normalized map + Vwafi = spm_vol(Pwa{fi}); Ywafi = single(spm_read_vols(Vwafi)); + Vwp0fi = spm_vol(Pwp0{fi}); Ywp0fi = single(spm_read_vols(Vwp0fi)); + Ym = cat_vol_morph(Ywp0fi>0.5 | Ywafi>0.5,'lc',1); + for xi=1:refiter, Ywafi=cat_vol_localstat(single(Ywafi),Ym,1*refsize,7); end + %[YD,YI,Ywafi]=cat_vbdist(Ywafi,Ywp0fi>0.5); Ywafi=single(Ywafi); clear YD YI; + Vwafi.fname = Pwa{fi}; spm_write_vol(Vwafi,Ywafi); + end + else + if recalc || ( ~exist(PwA{fi},'file') || ~exist(Pwp0{fi},'file') ) + % map ROI to atlas + calldefs(Py{fi},PA{fi} ,0,mode); + calldefs(Py{fi},Pp0{fi},3,0); + end + end + end + % create the final probability ROI map as a 4D dataset, the simplyfied + % atlas map for the CAT toolbox and a mean p0 images + if refine + subROIavg(Pwp0,Pwa,Ps,Pcsv,Ptxt,atlas,resdir,Pxml,nlabel) + else + subROIavg(Pwp0,PwA,Ps,Pcsv,Ptxt,atlas,resdir,Pxml,nlabel) + end + end +end + +function [P,PA,Pcsv,Ps,Ptxt,resdir,refine,Pxml] = mydata(atlas) +% ---------------------------------------------------------------------- +% This fucntion contains the paths to our atlas maps and the csv files. +% ---------------------------------------------------------------------- + rawdir = '/Volumes/MyBook/MRData/Regions/'; + resdir = '/Volumes/MyBook/MRData/Regions/vbmROIs'; + Pxml = struct(); + species = 'human'; + + switch lower(atlas) + case 'ibsr' + mdir = fullfile(rawdir,'ibsr'); + PA = cat_vol_findfiles(mdir,'IBSR_*_seg_ana.nii'); + Ps = {''}; + P = cat_vol_findfiles(mdir,'IBSR_*_ana.nii'); + P = setdiff(P,PA); + Pcsv = cat_vol_findfiles(mdir,'IBSR.csv'); + Ptxt = cat_vol_findfiles(mdir,'IBSR.txt'); + refine = 1; + Pxml.ver = 0.9; + Pxml.lic = 'IBSR terms'; + Pxml.url = 'http://www.nitrc.org/projects/ibsr'; + Pxml.des = [ ... + 'CAT12 was used to preprocess the T1 data to map each label to IXI555 space. ' ... + 'A 3D median filter was used to remove outliers in the label map. ROI-IDs ' ... + 'were reset to guaranty that left side ROIs were described by odd numbers, ' ... + 'whereas right-hand side ROIs only have even numbers. ROIs without side-alignment ' ... + 'in the original atlas like the brainstem were broken into a right and left part. ' ... + 'Therefore, a Laplace filter was used to estimate the potential field of unaligned' ... + 'regions between the left an right potential. ' ... + 'When publishing results using the data, acknowledge the source by including' ... + 'the statement, ""The MR brain data sets and their manual segmentations were' ... + 'provided by the Center for Morphometric Analysis at Massachusetts General' ... + 'Hospital and are available at http://www.cma.mgh.harvard.edu/ibsr/.""' ... + ]; + Pxml.ref = 'http://www.nitrc.org/projects/ibsr'; + + case 'hammers' + mdir = fullfile(rawdir,'brain-development.org/Pediatric Brain Atlas/Hammers_mith_atlases_n20r67_for_pvelab'); + P = cat_vol_findfiles(mdir,'MRalex.img'); + PA = cat_vol_findfiles(mdir,'VOIalex.img'); + Ps = {''}; + Pcsv = cat_vol_findfiles(mdir,'VOIalex.csv'); + %Pcsv = cat_vol_findfiles(mdir,'hammers.csv'); % bad structure + Ptxt = cat_vol_findfiles(mdir,'hammers.txt'); + refine = 1; + Pxml.ver = 1.0; + Pxml.lic = 'CC BY-NC'; + Pxml.url = 'http://biomedic.doc.ic.ac.uk/brain-development/index.php?n=Main.Atlases'; + Pxml.des = [ ... + 'This atlas, based on Alexander Hammers brain atlas, made available for the ' ... + 'Euripides project, Nov 2009 (A). ' ... + 'CAT12 was used to segment the T1 data and estimate Dartel normalization to the ' ... + 'CAT IXI550 template for each subject. Dartel mapping was then applied for label ' ... + 'map. A 3D median filter was used to remove outliers in the label map. ROI-IDs ' ... + 'were reset to guaranty that left side ROIs were described by odd numbers, ' ... + 'whereas right-hand side ROIs only have even numbers. ROIs without side-alignment ' ... + 'in the original atlas like the brainstem were broken into a right and left part. ' ... + 'Therefore, a Laplace filter was used to estimate the potential field of unaligned ' ... + 'regions between the left an right potential. ' ... + 'Hammers A, Allom R, Koepp MJ, Free SL, Myers R, Lemieux L, Mitchell TN, ' ... + 'Brooks DJ, Duncan JS. Three-dimensional maximum probability atlas of the human ' ... + 'brain, with particular reference to the temporal lobe. Hum Brain Mapp 2003, 19:' ... + '224-247. ' ... + ]; + Pxml.ref = [ ... + 'Hammers A, Allom R, Koepp MJ, Free SL, Myers R, Lemieux L, Mitchell TN, ' ... + 'Brooks DJ, Duncan JS. Three-dimensional maximum probability atlas of the human ' ... + 'brain, with particular reference to the temporal lobe. Hum Brain Mapp 2003, 19:' ... + '224-247. ' ... + ]; + + case {'mori','mori1','mori2','mori3'} + if numel(atlas)==5, aid=atlas(5); else aid='2'; end + mdir = fullfile(rawdir,'www.spl.harvard.edu/2010_JHU-MNI-ss Atlas'); + P = cat_vol_findfiles(mdir,'JHU_MNI_SS_T1.nii'); + PA = cat_vol_findfiles(mdir,sprintf('JHU_MNI_SS_WMPM_Type-%s.nii',repmat('I',1,str2double(aid)))); + Ps = {''}; + Pcsv = cat_vol_findfiles(mdir,sprintf('JHU_MNI_SS_WMPM_Type-%s_SlicerLUT.csv',repmat('I',1,str2double(aid)))); + Ptxt = cat_vol_findfiles(mdir,'mori.txt'); + refine = 1; + Pxml.ver = 0.9; + Pxml.lic = 'CC BY-NC'; + Pxml.url = 'http://www.spl.harvard.edu/publications/item/view/1883'; + Pxml.des = [ ... + 'This atlas based on the ""Slicer3:Mori_Atlas_labels_JHU-MNI_SS_Type-II"" atlas ' ... + '(http://www.spl.harvard.edu/publications/item/view/1883)' ... + 'of Version 2010-05. The T1 and label data was segmented and normalized by CAT12 ' ... + 'to projected the atlas to IXI550 template space. ' ... + 'If you use these atlases, please cite the references below. ' ... + 'Reference: Atlas-based whole brain white matter analysis using large deformation ' ... + 'diffeomorphic metric mapping: application to normal elderly and Alzheimers ' ... + 'disease participants. Oishi K, Faria A, Jiang H, Li X, Akhter K, Zhang J, Hsu JT, ' ... + 'Miller MI, van Zijl PC, Albert M, Lyketsos CG, Woods R, Toga AW, Pike GB, ' ... + 'Rosa-Neto P, Evans A, Mazziotta J, Mori S.' ... + ]; + Pxml.ref = [ ... + 'Reference: Atlas-based whole brain white matter analysis using large deformation ' ... + 'diffeomorphic metric mapping: application to normal elderly and Alzheimers ' ... + 'disease participants. Oishi K, Faria A, Jiang H, Li X, Akhter K, Zhang J, Hsu JT, ' ... + 'Miller MI, van Zijl PC, Albert M, Lyketsos CG, Woods R, Toga AW, Pike GB, ' ... + 'Rosa-Neto P, Evans A, Mazziotta J, Mori S.' ... + ]; + + case 'anatomy' + mdir = fullfile(rawdir,'Anatomy2.0'); + P = cat_vol_findfiles(mdir,'colin27T1_seg.nii'); + PA = [cat_vol_findfiles(fullfile(mdir,'PMaps'),'*.nii'); ... + cat_vol_findfiles(fullfile(mdir,'Fiber_Tracts','PMaps'),'*.img')]; + Ps = cat_vol_findfiles(mdir,'AnatMask.nii'); + Pmat = fullfile(mdir,'Anatomy_v20_MPM.mat'); + Pmat2 = fullfile(mdir,'Fiber_Tracts','AllFibres_v15_MPM.mat'); + Pcsv = {fullfile(mdir,[Pmat(1:end-8) '.csv'])}; + Ptxt = cat_vol_findfiles(mdir,'anatomy.txt'); + refine = 1; + + + % create csv ... + load(Pmat); names = [{MAP.name}' {MAP.ref}' {MAP.ref}']; + load(Pmat2); names = [names; {MAP.name}' {MAP.ref}' {MAP.ref}']; + + PAff = PA; + for ni=1:numel(PA) + [pp,ff] = spm_fileparts(PA{ni}); PAff{ni}=ff; + end + for ni=size(names,1):-1:1 + [pp,ff] = spm_fileparts(names{ni,2}); + names{ni,2} = ff; + PAid = find(strcmp(PAff,ff),1,'first'); + if ~isempty(PAid) + names{ni,3} = PA{PAid}; + else + names(ni,:) = []; + end + end + names = sortrows(names); + PA = names(:,3); + csv = [num2cell(1:size(names,1))' names(:,1:2)]; + cat_io_csv(Pcsv{1},csv); + + case 'aala' % anatomy toolbox version + mdir = fullfile(rawdir,'Anatomy'); + P = cat_vol_findfiles(mdir,'colin27T1_seg.img'); + PA = cat_vol_findfiles(mdir,'MacroLabels.img'); + Ps = {''}; + Pcsv = cat_vol_findfiles(mdir,'Macro.csv'); + Ptxt = cat_vol_findfiles(mdir,'aal.txt'); + refine = 1; + + case 'aal' + mdir = fullfile(rawdir,'aal_for_SPM8'); + P = cat_vol_findfiles(mdir,'Collins.nii'); + PA = cat_vol_findfiles(mdir,'aal.nii'); + Ps = {''}; + Pcsv = cat_vol_findfiles(mdir,'aal.csv'); + Ptxt = cat_vol_findfiles(mdir,'aal.txt'); + refine = 1; + + case 'lpba40' + mdir = fullfile(rawdir,'LPBA40'); + P = cat_vol_findfiles(mdir,'.img'); + PA = cat_vol_findfiles(mdir,'.nii'); + Ps = {''}; + Pcsv = cat_vol_findfiles(mdir,'.csv'); + Ptxt = cat_vol_findfiles(mdir,'.txt'); + refine = 1; + + case 'neuromorphometrics' + mdir = fullfile(rawdir,'MICCAI2012-Neuromorphometrics'); + P = cat_vol_findfiles(fullfile(mdir,'full'),'1*_3.nii'); + PA = cat_vol_findfiles(fullfile(mdir,'full'),'1*_3_glm.nii'); + Ps = {''}; + Pcsv = cat_vol_findfiles(mdir,'MICCAI2012-Neuromorphometrics.csv'); + Ptxt = cat_vol_findfiles(mdir,'MICCAI2012-Neuromorphometrics.txt'); + refine = 1; + Pxml.ver = 0.9; + Pxml.lic = 'CC BY-NC'; + Pxml.url = 'https://masi.vuse.vanderbilt.edu/workshop2012/index.php/Challenge_Details'; + Pxml.des = [ ... + 'Maximum probability tissue labels derived from the ``MICCAI 2012 Grand Challenge and Workshop ' ... + 'on Multi-Atlas Labeling'' (https://masi.vuse.vanderbilt.edu/workshop2012/index.php/Challenge_Details).' ... + 'These data were released under the Creative Commons Attribution-NonCommercial (CC BY-NC) with no end date. ' ... + 'Users should credit the MRI scans as originating from the OASIS project (http://www.oasis-brains.org/) and ' ... + 'the labeled data as ""provided by Neuromorphometrics, Inc. (http://Neuromorphometrics.com/) under academic ' ... + 'subscription"". These references should be included in all workshop and final publications.' ... + ]; + + case 'inia' + mdir = fullfile(rawdir,'animals','inia19'); + P = cat_vol_findfiles(mdir,'inia19-t1-brain.nii'); + PA = cat_vol_findfiles(mdir,'inia19-NeuroMaps.nii'); + Ps = {''}; + Pcsv = cat_vol_findfiles(mdir,'MICCAI2012-Neuromorphometrics.csv'); + Ptxt = cat_vol_findfiles(mdir,'MICCAI2012-Neuromorphometrics.txt'); + refine = 1; + Pxml.ver = 0.9; + Pxml.lic = 'CC BY-NC'; + Pxml.url = 'https://masi.vuse.vanderbilt.edu/workshop2012/index.php/Challenge_Details'; + Pxml.des = [ ... + 'Maximum probability tissue labels derived from the ``MICCAI 2012 Grand Challenge and Workshop ' ... + 'on Multi-Atlas Labeling'' (https://masi.vuse.vanderbilt.edu/workshop2012/index.php/Challenge_Details).' ... + 'These data were released under the Creative Commons Attribution-NonCommercial (CC BY-NC) with no end date. ' ... + 'Users should credit the MRI scans as originating from the OASIS project (http://www.oasis-brains.org/) and ' ... + 'the labeled data as ""provided by Neuromorphometrics, Inc. (http://Neuromorphometrics.com/) under academic ' ... + 'subscription"". These references should be included in all workshop and final publications.' ... + ]; + % for this atlas I have no source and no labels... + %{ + case 'brodmann' + mdir = '/Volumes/MyBook/MRData/Regions/Anatomy'; + P = cat_vol_findfiles(mdir,'colin27T1_seg.img'); + PA = cat_vol_findfiles(mdir,'MacroLabels.img'); + Pcsv = cat_vol_findfiles(mdir,'Macro.csv'); + refine = 1; + %} + + % ibaspm115 is the aal atlas, and ibaspm71 do not fit for collins! + %{ + case {'ibaspm116','ibaspm71'} + mdir = '/Volumes/MyBook/MRData/Regions/Anatomy'; + P = cat_vol_findfiles(mdir,'colin27T1_seg.img'); + PA = cat_vol_findfiles(mdir,'MacroLabels.img'); + Pcsv = cat_vol_findfiles(mdir,'Macro.csv'); + refine = 1; + %} + + case 'cat12' + mdir = resdir; %fullfile(spm('dir'),'toolbox','cat12','templates_volumes'); + P = cat_vol_findfiles(mdir,'*.nii'); + PA = cat_vol_findfiles(mdir,'*.nii'); + Ps = {''}; + Pcsv = {''}; + Ptxt = {''}; + refine = 0; + Pxml.ver = 1.0; + Pxml.lic = 'CC BY-NC'; + Pxml.url = 'https://masi.vuse.vanderbilt.edu/workshop2012/index.php/Challenge_Details'; + Pxml.des = [ ... + 'Internal atlas of CAT12.' ... + ]; + + otherwise % GUI ... + P = {''}; + PA = {''}; + Ps = {''}; + Pcsv = {''}; + Ptxt = {''}; + refine = 0; + end + + % combination of different atlas maps ... +end + +function call_cat(P) +% ---------------------------------------------------------------------- +% This function call CAT segmentation to estimate the normalization +% parameters for the atlas map. +% ---------------------------------------------------------------------- +% Job saved on 28-Oct-2013 14:37:37 by cfg_util (rev $Rev$) +% spm SPM - SPM12b (5298) +% cfg_basicio BasicIO - Unknown +% ---------------------------------------------------------------------- + matlabbatch{1}.spm.tools.cat.estwrite.data = {P}; + + matlabbatch{1}.spm.tools.cat.estwrite.opts.tpm = ... + {fullfile(spm('dir'),'tpm','TPM.nii')}; + matlabbatch{1}.spm.tools.cat.estwrite.opts.biasreg = 0.0001; + matlabbatch{1}.spm.tools.cat.estwrite.opts.biasfwhm = 60; + matlabbatch{1}.spm.tools.cat.estwrite.opts.affreg = 'mni'; + matlabbatch{1}.spm.tools.cat.estwrite.opts.warpreg = [0 0.001 0.5 0.05 0.2]; + matlabbatch{1}.spm.tools.cat.estwrite.extopts.darteltpm = ... + {fullfile(spm('dir'),'toolbox','cat12','templates_volumes','Template_1_IXI555_MNI152.nii')}; + matlabbatch{1}.spm.tools.cat.estwrite.extopts.print = 1; + matlabbatch{1}.spm.tools.cat.estwrite.extopts.surface = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.GM.native = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.GM.warped = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.GM.modulated = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.GM.dartel = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.WM.native = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.WM.warped = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.WM.modulated = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.WM.dartel = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.CSF.native = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.CSF.warped = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.CSF.modulated = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.CSF.dartel = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.label.native = 1; + matlabbatch{1}.spm.tools.cat.estwrite.output.label.warped = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.label.dartel = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.bias.native = 1; + matlabbatch{1}.spm.tools.cat.estwrite.output.bias.warped = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.bias.affine = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.jacobian.warped = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.warps = [1 1]; + + warning off; + try + spm_jobman('initcfg'); + spm_jobman('run',matlabbatch); + end + warning on; +end + +function calldefs(Py,PA,interp,modulate) +% ---------------------------------------------------------------------- +% This function calls the CAT mapping routine to transfer the subject ROI +% to group space. +% ---------------------------------------------------------------------- + + matlabbatch{1}.spm.tools.cat.tools.defs.field1 = {Py}; + matlabbatch{1}.spm.tools.cat.tools.defs.images = {PA}; + matlabbatch{1}.spm.tools.cat.tools.defs.interp = interp; + matlabbatch{1}.spm.tools.cat.tools.defs.modulate = modulate; + + warning off; + try + spm_jobman('initcfg'); + spm_jobman('run',matlabbatch); + end + warning on; +end + +function subROIavg(P,PA,Ps,Pcsv,Ptxt,atlas,resdir,Pxml,nlabel) +% ---------------------------------------------------------------------- +% create the final probability ROI map as a 4D dataset, the simplyfied +% atlas map for the CAT toolbox and a mean p0 images +% ---------------------------------------------------------------------- + + if ~exist('resdir','var'), resdir = spm_fileparts(PA{1}); end + if ~exist(resdir,'dir'), mkdir(resdir); end + + + + % get csv-data + % -------------------------------------------------------------------- + if ~isempty(Pcsv) && exist(Pcsv{1},'file') + csv = cat_io_csv(Pcsv{1}); + + % normalization of ROI-names ... + csv=translateROI(csv,atlas,nlabel); + + if size(csv,2)<3, for ROIi=2:size(csv,1), csv{ROIi,3} = csv{ROIi,2}; end; end + if isnumeric(csv{1}) || (ischar(csv{1}) && isempty(str2double(csv{1}))) + header = {'ROIidO','ROInameO','ROIname','ROIabbr','ROIn','ROIs','ROIidOall','ROInameOall'}; + csv = [header;csv]; + end + dsc = atlas; for ROIi=2:size(csv,1), dsc = sprintf('%s,%s-%s',dsc,csv{ROIi,1},csv{ROIi,3}); end + else + dsc = atlas; + end + + + + % images + % -------------------------------------------------------------------- + % First we need a optimized labeling to avoid a oversized 4d file. + % Therefore we create a table cod that contain in the first column the + % original label and in the second column the optimized value. + % -------------------------------------------------------------------- + VC = spm_vol(fullfile(spm('dir'),'toolbox','cat12','templates_volumes/Template_1_IXI555_MNI152.nii')); + V = spm_vol(char(P)); + VA = spm_vol(char(PA)); + Y = spm_read_vols(VA(1)); + %vx_vol = sqrt(sum(V.mat(1:3,1:3).^2)); + + switch VA(1).private.dat.dtype + case 'INT8-LE', Y = int8(Y); dt = 'int8'; + case 'INT16-LE', Y = int16(Y); dt = 'int16'; + case 'UINT8-LE', Y = uint8(Y); dt = 'uint8'; + case 'UINT16-LE', Y = uint16(Y); dt = 'uint16'; + otherwise + end + if min(Y(:))>=0 + switch dt + case 'int8', dt='uint8'; Y=uint8(Y); + case 'int16'; dt='uint16'; Y=uint16(Y); + end + else + error('ERROR:cat_vol_atlas:bad_label_map','No negative Labels are allowed\n'); + end + if max(abs(Y(:)))<256 + switch dt + case 'int16', dt='int8'; Y=int8(Y); + case 'uint16'; dt='uint8'; Y=uint8(Y); + end + end + + + %% + hb = [intmin(dt) intmax(dt)]; + datarange = hb(1):hb(2); + H = hist(single(max(hb(1),min(hb(2),Y(:)))),single(datarange)); H(hb(1)+1)=0; + cod = repmat(datarange',1,4); + if hb(2)>0 + if nlabel, codi=cod(H>0,1); else codi=[csv{2:end,1}]'; end + for codii=1:numel(codi), codi(codii) = csv{1+find([csv{2:end,1}]==codi(codii)),6}; end + if nlabel, cod(H>0,4) = codi; else cod([csv{2:end,1}],4) = codi; end + + if nlabel,codi=cod(H>0,2); else codi=[csv{2:end,1}]'; end + for codii=1:numel(codi), codi(codii) = csv{1+find([csv{2:end,1}]==codi(codii)),5}; end + if nlabel, cod(H>0,2) = codi; else cod([csv{2:end,1}],4) = codi; end + + % nicht alle alten strukturen sind doppel zu nehmen... + [ia,ib,ic] = unique(codi); + cod(H>0,3) = ic*2; + del = setdiff([csv{2:end,1}],[csv{2:end,5}]); + codi = setdiff(codi,del); + + csvx = {'ROIid' 'ROIabbr' 'ROIname' 'ROIbaseid' 'ROIbasename'; 0 'BG' 'Background' '[0]' 'Background'}; + for ri=1:numel(codi) + id = find([csv{2:end,5}]==codi(ri),'1','first'); + csvx{(ri*2)+1,1} = (ri*2)-1; % ROIid + csvx{(ri*2)+2,1} = (ri*2); + csvx{(ri*2)+1,2} = csv{id+1,4}; % ROIabbr + csvx{(ri*2)+2,2} = csv{id+1,4}; + csvx{(ri*2)+1,3} = csv{id+1,3}; % ROIname + csvx{(ri*2)+2,3} = csv{id+1,3}; + csvx{(ri*2)+1,4} = sprintf('[ %s]',sprintf('%d ',unique([csv{id+1,7}]))); % ROIbaseid = ROIidO + csvx{(ri*2)+2,4} = sprintf('[ %s]',sprintf('%d ',unique([csv{id+1,7}]))); + csvx{(ri*2)+1,5} = csv{id+1,8}; % ROIbase = ROInameO + csvx{(ri*2)+2,5} = csv{id+1,8}; + end + + %% +% %for idi=1:2:numel(ia); id(idi) = find([csv{2:end,5}]==idi,1,'first'); end +% csvx(:,1) = [{'ROIid'};num2cell((0:numel(ia)*2)')]; +% csvx(:,2) = [{'ROIabbr';'BG'};csv(reshape(repmat((1+ia)',2,1),2*numel(ia),1),4)]; +% csvx(:,3) = [{'ROIname';'Background'};csv(reshape(repmat((1+ib)',2,1),2*numel(ia),1),3)]; +% csvx(:,4) = [{'ROIoname';'Background'};csv(reshape(repmat((1+ib)',2,1),2*numel(ia),1),2)]; +% + %{ + csvx(:,2) = [{'ROIabbr';'BG'};csv(reshape(repmat((1+cod(ia+1,3)/2)',2,1),2*numel(ia),1),4)]; + csvx(:,3) = [{'ROIname';'Background'};csv(reshape(repmat((1+cod(ia+1,3)/2)',2,1),2*numel(ia),1),3)]; + csvx(:,4) = [{'ROIoname';'Background'};csv(reshape(repmat((1+cod(ia+1,3)/2)',2,1),2*numel(ia),1),2)]; + %} + + for si=3:size(csvx,1) + if mod(si,2)==1, csvx{si,2} = ['l',csvx{si,2}]; csvx{si,3} = ['Left ' ,csvx{si,3}]; + else csvx{si,2} = ['r',csvx{si,2}]; csvx{si,3} = ['Right ',csvx{si,3}]; + end + end + + end + if max([csv{5,:}]) %max(round(cod(H>0,3)))<256 + dt2='uint8'; + else + dt2='uint16'; + end + + + Pa4D = fullfile(resdir,['a4D' atlas '.nii']); + Pa3D = fullfile(resdir,[atlas '.nii']); + Pp0 = fullfile(resdir,['p0' atlas '.nii']); + + recalc = 1; + + if ~exist(Pa4D,'file') || ~exist(Pa3D,'file') || ~exist(Pp0,'file') || recalc + %% 4D-probability map + % -------------------------------------------------------------------- + % Here we create the probability map for each label with the optimized + % labeling cod. + % -------------------------------------------------------------------- + N = nifti; + N.dat = file_array(fullfile(resdir,['a4D' atlas '.nii']),[VC(1).dim(1:3) ... + max(round(cod(H>0,3)))+1],[spm_type(dt2) spm_platform('bigend')],0,1,0); + N.mat = VC(1).mat; + N.mat0 = VC(1).private.mat0; + N.descrip = dsc; + create(N); + + + % hier gehen noch zwei sachen schief... + % 1) liegt kein links rechts vor, dann mist + % 2) ist links rechts mist, dann bleibts mist + % x) seitenzuweisung ist irgendwie qatsch + for j=1:min(max([csv{2:end,1}]),(N.dat.dim(4))) + if j==1 + stime = cat_io_cmd(sprintf(' Label %d',j),'g5','',1); + else + stime = cat_io_cmd(sprintf(' Label %d',j),'g5','',1,stime); + end + Y = zeros(VA(1).dim,dt2); + for i=1:numel(PA) + Yi = spm_read_vols(VA(i)); + if ~isempty(Yi==j) + % optimize label + switch dt + case 'uint8' + Ys = single(intlut(uint8(Yi),uint8(cod(:,4)'))); + Ys(Ys==0)=nan; Ys(Ys==3)=1.5; Ys=round(cat_vol_laplace3R(Ys,Ys==1.5,0.01)); + Yi = intlut(uint8(Yi),uint8(cod(:,3)')); + case 'uint16' + Ys = single(intlut(uint16(Yi),uint16(cod(:,4)'))); + Ys(Ys==0)=nan; Ys(Ys==3)=1.5; Ys=round(cat_vol_laplace3R(Ys,Ys==1.5,0.01)); + Yi = intlut(uint16(Yi),uint16(cod(:,3)')); + case 'int8' + Ys = single(intlut(int8(Yi),int8(cod(:,4)'))); + Ys(Ys==0)=nan; Ys(Ys==3)=1.5; Ys=round(cat_vol_laplace3R(Ys,Ys==1.5,0.01)); + Yi = intlut(int8(Yi),int8(cod(:,3)')); + case 'int16' + Ys = single(intlut(int16(Yi),int16(cod(:,4)'))); + Ys(Ys==0)=nan; Ys(Ys==3)=1.5; Ys=round(cat_vol_laplace3R(Ys,Ys==1.5,0.01)); + Yi = intlut(int16(Yi),int16(cod(:,3)')); + end + % flip LR + [x,y,z]=ind2sub(size(Ys),find(Ys==1)); %#ok + if mean(x)>(size(Ys,1)/2), Ys(Ys==1)=1.5; Ys(Ys==2)=1; Ys(Ys==1.5)=2; end + % add case j + switch dt2 + case 'uint8' + Y = Y + uint8(Yi==(ceil(j/2)*2) & (Ys)==(mod(j,2)+1)); + case 'uint16' + Y = Y + uint16(Yi==(ceil(j/2)*2) & (Ys)==(mod(j,2)+1)); + case 'int8' + Y = Y + int8(Yi==(ceil(j/2)*2) & (Ys)==(mod(j,2)+1)); + case 'int16' + Y = Y + int16(Yi==(ceil(j/2)*2) & (Ys)==(mod(j,2)+1)); % mod(j+1,2)+1 mit seitenfehler + end + end + end + clear Ps; + N.dat(:,:,:,j) = Y; + end + + + %% p0-mean map + % -------------------------------------------------------------------- + stime = cat_io_cmd('p0-mean map','n','',1,stime); + N = nifti; + N.dat = file_array(fullfile(resdir,['p0' atlas '.nii']),... + VC(1).private.dat.dim(1:3),[spm_type(dt2) spm_platform('bigend')],0,3/255,0); + N.mat = VC(1).mat; + N.mat0 = VC(1).private.mat0; + N.descrip = ['p0 ' atlas]; + create(N); + Y = zeros(VA(1).dim,'single'); + for i=1:numel(P) + Y = Y + spm_read_vols(spm_vol(P{i})); + end + N.dat(:,:,:) = double(Y/numel(P)); + + + + %% 3d-label map + % -------------------------------------------------------------------- + stime = cat_io_cmd('3d-label map','n','',1,stime); + + M = smooth3(cat_vol_morph((Y/numel(P))>0.1,'labclose',1))>0.2; + + N = nifti; + N.dat = file_array(fullfile(resdir,[atlas '.nii']),VC(1).dim(1:3),... + [spm_type(dt2) spm_platform('bigend')],0,1,0); + N.mat = VC(1).mat; + N.mat0 = VC(1).private.mat0; + N.descrip = dsc; + create(N); + Y = single(spm_read_vols(spm_vol(fullfile(resdir,['a4D' atlas '.nii'])))); + Y = cat(4,~max(Y,[],4),Y); % add background class + [maxx,Y] = max(Y,[],4); clear maxx; Y = Y-1; + for xi=1:3, Y = cat_vol_localstat(single(Y),M,1,7); end + + % restor old labeling or use optimized + if 0 + switch dt + case 'uint8', Y = intlut(uint8(Y.*M),uint8(cod(:,1)')); + case 'uint16', Y = intlut(uint16(Y.*M),uint16(cod(:,1)')); + case 'int8', Y = intlut(int8(Y.*M),int8(cod(:,1)')); + case 'int16', Y = intlut(int16(Y.*M),int16(cod(:,1)')); + end + else + Y = Y.*M; + end + switch dt2 + case 'uint8', Y = uint8(Y); + case 'uint16', Y = uint16(Y); + case 'int8', Y = int8(Y); + case 'int16', Y = int16(Y); + end + N.dat(:,:,:) = Y; + end + + Va3D = spm_vol(Pa3D); + Ya3D = single(spm_read_vols(Va3D)); + + vx_vol = sqrt(sum(Va3D.mat(1:3,1:3).^2)); + matx = spm_imatrix(Va3D.mat); + vox = hist(Ya3D(:),0:max(Ya3D(:))); + vol = vox .* prod(vx_vol)/1000; + xyz = cell(max(Ya3D(:))+1,1); + for i=0:max(Ya3D(:)) + ind = find(Ya3D==i); + [x,y,z]=ind2sub(size(Ya3D),ind); + + xyz{i+1,1} = sprintf('%0.2f,%0.2f,%0.2f', ... + [matx(1) + mean(x)*matx(7) ... + matx(2) + mean(y)*matx(8) ... + matx(3) + mean(z)*matx(9) ]); + + end + csvx = [csvx ['Voxel' ; mat2cell(num2str(vox','%0.0f'),ones(1,size(csvx,1)-1))] ... + ['Volume' ; mat2cell(num2str(vol','%0.2f'),ones(1,size(csvx,1)-1))] ... + ['XYZ' ; xyz] ... + ]; + + + % filling???? + % -------------------------------------------------------------------- + % At this point it would be possible to dilate the maps. But this cannot + % simply be done by cat_vbdist, because for most cases not all regions are + % defined. I.e. for AAL the brainstem is missing and so the cerebellum + % will be aligned. + % So one thing is that I can use the group map to add lower regions for + % GM. But what can I do in WM areas? For the gyri I need it, but not for + % the brainstem ... + % Another solution would be the creation of a common own atlas from + % multiple atlas maps. + + + %% csv and txt data + % -------------------------------------------------------------------- + if ~isempty(Pcsv) && exist(Pcsv{1},'file') + if exist('csvx','var') + cat_io_csv(fullfile(resdir,[atlas '.csv']),csvx); + else + cat_io_csv(fullfile(resdir,[atlas '.csv']),csv); + end + end + + create_spm_atlas_xml(fullfile(resdir,[atlas '.xml']),csv,csvx,Pxml); + + if ~isempty(Ptxt) && exist(Ptxt{1},'file') + copyfile(Ptxt{1},fullfile(resdir,[atlas '.txt']),'f'); + end + +end + +function ROIavg(P,PA,Ps,Pcsv,Ptxt,atlas,resdir,Pxml,nlabel) +% ---------------------------------------------------------------------- +% create the final probability ROI map as a 4D dataset, the simplyfied +% atlas map for the CAT toolbox and a mean p0 images +% ---------------------------------------------------------------------- + + if ~exist('resdir','var'), resdir = spm_fileparts(PA{1}); end + if ~exist(resdir,'dir'), mkdir(resdir); end + + % get csv-data + if ~isempty(Pcsv) && exist(Pcsv{1},'file') + csv = cat_io_csv(Pcsv{1}); + + % normalization of ROI-names ... + csv=translateROI(csv,atlas,nlabel); + + + if size(csv,2)<3, for ROIi=2:size(csv,1), csv{ROIi,3} = csv{ROIi,2}; end; end + if isnumeric(csv{1}) || (ischar(csv{1}) && isempty(str2double(csv{1}))) + header = {'ROIidO','ROInameO','ROIname','ROIabbr','ROIn','ROIs'}; + csv = [header;csv]; + end + dsc = atlas; for ROIi=2:size(csv,1), dsc = sprintf('%s,%s-%s',dsc,csv{ROIi,1},csv{ROIi,3}); end + else + dsc = atlas; + end + + + %% images + V = spm_vol(char(P)); + VA = spm_vol(char(PA)); + Y = spm_read_vols(VA(1)); + + switch VA(1).private.dat.dtype + case 'INT8-LE', Y = int8(Y); dt = 'int8'; + case 'INT16-LE', Y = int16(Y); dt = 'int16'; + case 'UINT8-LE', Y = uint8(Y); dt = 'uint8'; + case 'UINT16-LE', Y = uint16(Y); dt = 'uint16'; + otherwise, Y = single(Y); dt = 'uint8'; Y(Y<0)=0; Y(isnan(Y) | isinf(Y) )=0; + end + % if min(Y(:))>=0 + switch dt + case 'int8', dt='uint8'; Y=uint8(Y); + case 'int16'; dt='uint16'; Y=uint16(Y); + end + % else + % error('ERROR:cat_vol_atlas:bad_label_map','No negative Labels are allowed\n'); + % end + if max(abs(Y(:)))<256 + switch dt + case 'int16', dt='int8'; Y=int8(Y); + case 'uint16'; dt='uint8'; Y=uint8(Y); + end + end + + + + % actual we got only the anatomy toolbox case... + hb = [intmin(dt) intmax(dt)]; + datarange = hb(1):hb(2); + H = datarange0 + codi=cod(H>0,1); + for codii=1:numel(codi), codi(codii) = csv{1+find([csv{2:end,1}]==codi(codii)),6}; end + cod(H>0,4) = codi; + + codi=cod(H>0,1); + for codii=1:numel(codi), codi(codii) = csv{1+find([csv{2:end,1}]==codi(codii)),5}; end + cod(H>0,2) = codi; + + [ia,ib,ic] = unique(codi); + cod(H>0,3) = ic*2; + + csvx(:,1) = [{'ROIid'};num2cell((0:numel(ia)*2)')]; + csvx(:,2) = [{'ROIabbr';'BG'};csv(reshape(repmat(1+ia',2,1),2*numel(ia),1),4)]; + csvx(:,3) = [{'ROIname';'Background'};csv(reshape(repmat(1+ia',2,1),2*numel(ia),1),3)]; + csvx(:,4) = [{'ROIoname';'Background'};csv(reshape(repmat(1+ia',2,1),2*numel(ia),1),2)]; + + for si=3:size(csvx,1) + if mod(si,2)==1, csvx{si,2} = ['l',csvx{si,2}]; csvx{si,3} = ['Left ' ,csvx{si,3}]; + else csvx{si,2} = ['r',csvx{si,2}]; csvx{si,3} = ['Right ',csvx{si,3}]; + end + end + end + if max(round(cod(H>0,3)))<256 + dt2='uint8'; + else + dt2='uint16'; + end + + + + + % 4D-probability map + % -------------------------------------------------------------------- + VC = spm_vol(fullfile(spm('dir'),'toolbox','cat12','templates_volumes/Template_1_IXI555_MNI152.nii')); VC=VC(1); + + N = nifti; + N.dat = file_array(fullfile(resdir,['a4D' atlas '.nii']),[VC.dim(1:3) ... + numel(PA)*2],[spm_type(dt2) spm_platform('bigend')],0,1/255,0); + N.mat = VC(1).mat; + N.mat0 = VC(1).private.mat0; + N.descrip = dsc; + create(N); + + if exist(Ps{1},'file') + Ys = single(spm_read_vols(spm_vol(char(Ps)))); + Yp0 = single(spm_read_vols(spm_vol(char(P)))); + [Yd,Yi] = cat_vbdist(single(Ys>0)); Ys = Ys(Yi); + end + for i=1:numel(PA) + Y = single(spm_read_vols(VA(i))); + if nanmax(Y(:))>1, mx = 255; else mx = 1; end + if exist('Ys','var') + for si=1:2 + Yi = Y .* (Ys==si) .* Yp0>0.5; + N.dat(:,:,:,i*2 - (si==1) ) = double(Yi)/mx; + end + else + N.dat(:,:,:,i) = double(Y)/mx; + end + end + + %% p0-mean map + % -------------------------------------------------------------------- + + N = nifti; + N.dat = file_array(fullfile(resdir,['p0' atlas '.nii']),VC.dim(1:3), ... + [spm_type(dt2) spm_platform('bigend')],0,3/255,0); + N.mat = VC(1).mat; + N.mat0 = VC(1).private.mat0; + N.descrip = ['p0 ' atlas]; + create(N); + Y = zeros(VA(1).dim,'single'); + for i=1:numel(P) + Y = Y + spm_read_vols(spm_vol(P{i})); + end + N.dat(:,:,:) = double(Y/numel(P)); + + + %% 3d-label map + % -------------------------------------------------------------------- + M = cat_vol_morph((Y/numel(P))>0.5,'labclose'); + N = nifti; + N.dat = file_array(fullfile(resdir,[atlas '.nii']),VC(1).dim(1:3),... + [spm_type(dt2) spm_platform('bigend')],0,1,0); + N.mat = VC(1).mat; + N.mat0 = VC(1).private.mat0; + N.descrip = dsc; + create(N); + Y = single(spm_read_vols(spm_vol(fullfile(resdir,['a4D' atlas '.nii'])))); + Y = cat(4,~max(Y,[],4),Y); % add background class + [maxx,Y] = max(Y,[],4); clear maxx; Y = Y-1; + for xi=1:3, Y = cat_vol_localstat(single(Y),M,1,7); end + + % restor old labeling or use optimized + if 0 + switch dt + case 'uint8' + Y = intlut(uint8(Y.*M),uint8(cod(:,1)')); + case 'uint16' + Y = intlut(uint16(Y.*M),uint16(cod(:,1)')); + case 'int8' + Y = intlut(int8(Y.*M),int8(cod(:,1)')); + case 'int16' + Y = intlut(int16(Y.*M),int16(cod(:,1)')); + end + else + Y = Y.*M; + end + switch dt2 + case 'uint8', Y = uint8(Y); + case 'uint16', Y = uint16(Y); + case 'int8', Y = int8(Y); + case 'int16', Y = int16(Y); + end + N.dat(:,:,:) = double(Y); + + + %% csv and txt data + % -------------------------------------------------------------------- + if ~isempty(Pcsv) && exist(Pcsv{1},'file') + if exist('csvx','var') + cat_io_csv(fullfile(resdir,[atlas '.csv']),csvx); + else + cat_io_csv(fullfile(resdir,[atlas '.csv']),csv); + end + end + + create_spm_atlas_xml(fullfile(resdir,[atlas '.xml']),csv,Pxml); + + if ~isempty(Ptxt) && exist(Ptxt{1},'file') + copyfile(Ptxt{1},fullfile(resdir,[atlas '.txt']),'f'); + end +end + +function csv=translateROI(csv,atlas,nlabel) +%% --------------------------------------------------------------------- +% Translate the string by some key words definied in dict. +% --------------------------------------------------------------------- + if ~isempty(find([csv{:,1}]==0,1)) + %csv{[csv{:,1}]==0,2} = 'Background'; + csv([csv{:,1}]==0,:) = []; + else + %csv = [csv(1,:);csv]; + %csv{1,1} = 0; csv{1,2} = 'Background'; + end + if size(csv,2)>3, csv(:,3:end) = []; end % remove other stuff + + csv(:,5) = num2cell((1:size(csv,1))'); %csv(:,1); % + dict = ROIdict; + + for i=1:size(csv,1) + %% side + csv{i,2} = [csv{i,2} ' ']; csv{i,3}=''; csv{i,4}=''; csv{i,6}=''; csv{i,6}=0; + + indi=zeros(1,size(dict.sides,1)); + for di=1:size(dict.sides,1) + for pi=1:numel(dict.sides{di,2}) + sid = strfind(lower(csv{i,2}),lower(dict.sides{di,2}{pi})); + indi(di) = ~isempty(sid); + if indi(di)==1, break; end + end + for pi=1:numel(dict.sides{di,3}) + nsid = strfind(lower(csv{i,2}),lower(dict.sides{di,3}{pi})); + if indi(di) && ~isempty(nsid) && numel(nsid)>=numel(sid) + indi(di) = 0; + end + end + end + %% + indi = find(indi,1,'first'); + if ~isempty(indi) + csv{i,6}=1+strcmpi(dict.sides{indi,1},'r'); + csv{i,4}=[csv{i,4} dict.sides{indi,1}]; + csv{i,3}=[csv{i,3} dict.sides{indi,2}{1}]; + end + if isempty(csv{i,4}) + csv{i,6}=3; + csv{i,4}=[csv{i,4} 'b']; + csv{i,3}=[csv{i,3} 'Bothside']; + end + + %% directions + %fn = {'regions','directions','structures','addon'}; + fn = {'directions','regions','structures','addon'}; + for fni=1:numel(fn) + indi=zeros(1,size(dict.(fn{fni}),1)); + for di=1:size(dict.(fn{fni}),1) + for pi=1:numel(dict.(fn{fni}){di,2}) + indi(di) = ~isempty(strfind(lower(csv{i,2}),lower(dict.(fn{fni}){di,2}{pi}))); + if indi(di)==1, break; end + end + for pi=1:numel(dict.(fn{fni}){di,3}) + if indi(di) && ~isempty(strfind(lower(csv{i,2}),lower(dict.(fn{fni}){di,3}{pi}))) + indi(di) = 0; + end + end + end + [x,indi] = find(indi); + for indii=1:numel(indi) + if ~isempty(indi) + if isempty( dict.(fn{fni}){indi(indii),1} ) && csv{i,5}>0 && nlabel + csv{i,4} = ''; + csv{i,3} = ''; + csv{i,5} = 0; + else + if strcmp(fn{fni},'regions') && indii>1 + csv{i,4} = [csv{i,4} '+' dict.(fn{fni}){indi(indii),1}]; + csv{i,3} = [csv{i,3} ' and ' dict.(fn{fni}){indi(indii),2}{1}]; + else + csv{i,4} = [csv{i,4} dict.(fn{fni}){indi(indii),1}]; + csv{i,3} = [csv{i,3} ' ' dict.(fn{fni}){indi(indii),2}{1}]; + end + end + end + end + end + % atlas specific + end + + %% atlas specific structures + for i=1:size(csv,1) + fn = {atlas}; + for fni=1:numel(fn) + indi=zeros(1,size(dict.(fn{fni}),1)); + for di=1:size(dict.(fn{fni}),1) + for pi=1:numel(dict.(fn{fni}){di,2}) + indi(di) = ~isempty(strfind(lower(csv{i,2}),lower(dict.(fn{fni}){di,2}{pi}))); + if indi(di)==1, break; end + end + for pi=1:numel(dict.(fn{fni}){di,3}) + if indi(di) && ~isempty(strfind(lower(csv{i,2}),lower(dict.(fn{fni}){di,3}{pi}))) + indi(di) = 0; + end + end + end + [x,indi] = find(indi); + for indii=1:numel(indi) + if ~isempty(indi) + if isempty( dict.(fn{fni}){indi(indii),1} ) && csv{i,5} + csv{i,4}=''; + csv{i,3}=''; + csv{i,5}=0; + elseif isempty( deblank(dict.(fn{fni}){indi(indii),1}) ) + % do not remove completelly, but do not add something + else + csv{i,4}=[csv{i,4} dict.(fn{fni}){indi(indii),1}]; + csv{i,3}=[csv{i,3} ' ' dict.(fn{fni}){indi(indii),2}{1}]; + end + end + end + end + csv{i,2} = deblank(csv{i,2}); + csv{i,4} = deblank(csv{i,4}); + end + for i=1:size(csv,1), csv{i,3}=strrep(csv{i,3},' ',' '); end + + % remove side alignement + rmside = 1; + for i=1:size(csv,1) + if rmside + csv{i,3} = strrep(strrep(strrep(csv{i,3},'Left ',''),'Right ',''),'Bothside ',''); + csv{i,4} = csv{i,4}(rmside+1:end); + end + end + + %% + if ~nlabel + for i=1:size(csv,1) + if csv{i,4}=='B' + tmp = deblank(csv{i,2}); + tmp = strrep(strrep(strrep(tmp,' ','-'),'_','-'),'.','-'); + tmp = strrep(strrep(tmp,'Left-',''),'Right-',''); + tmp = strrep(strrep(tmp,'_L',''),'_R',''); + csv{i,3} = tmp; + csv{i,4} = tmp; + end + end + end + + %% reset label for structures with similar appreservations + for i=1:size(csv,1) + sids=strcmp(csv(:,4),csv{i,4}); + + fset = find(sids); fset=unique(fset); + csv{i,7} = [csv{fset',1}]; tmp = cell(1); + if nlabel + if i==1 + csv{i,5}=1; + else + if min(fset) == i + csv{i,5} = max([csv{1:i-1,5}])+1; + else + csv{i,5} = csv{fset(1),5}; + end + end + else + csv{i,5} = fset(1); + end + + LRB = zeros(size(fset)); + for ii=1:numel(fset); + LRB(ii) = csv{fset(ii),6}; + tmp{ii} = deblank(csv{fset(ii),2}); + tmp{ii} = strrep(strrep(strrep(tmp{ii},' ','-'),'_','-'),'.','-'); + tmp{ii} = strrep(strrep(tmp{ii},'Left-',''),'Right-',''); + tmp{ii} = strrep(strrep(tmp{ii},'_L',''),'_R',''); + end + if any(LRB==1) && any(LRB==2) && all(LRB~=3) + csv{i,8} = ['Left/Right:' strjoin(unique(tmp))]; + elseif any(LRB==1) && any(LRB==2) && any(LRB==3) + csv{i,8} = ['Left/Right/Both:' strjoin(unique(tmp))]; + elseif all(LRB==1) + csv{i,8} = ['Left:' strjoin(unique(tmp))]; + elseif all(LRB==2) + csv{i,8} = ['Right:' strjoin(unique(tmp))]; + elseif all(LRB==3) + csv{i,8} = ['Both:' strjoin(unique(tmp))]; + else + csv{i,8} = ['Unk:' strjoin(unique(tmp))]; + end + csv{i,8} = strrep(csv{i,8},' ','.'); + end + + + + +end + +function dict=ROIdict() + dict.sides = { + 'l' {'Left' '_L'} {'_Lo','_La','_Li'} + 'r' {'Right' '_R'} {'_Ro','_Ra','_Ru','_Re'} + }; + dict.directions = { + ... + 'Ant' {'Anterior' 'ant_' 'ant-' 'ant ' 'antarior'} {} + 'Inf' {'Inferior ' 'inf_' 'inf-' 'inf ' 'Infero'} {} + 'Pos' {'Posterior' 'pos_' 'pos-' 'pos ' 'poss_'} {} + 'Sup' {'Superior' 'sup_' 'sup-' 'sup ' 'supp_'} {} + ... + 'Med' {'Medial' 'med_' 'med-' 'mid '} {} + 'Mid' {'Middle' 'mid_' 'mid-' 'mid '} {} + 'Cen' {'Central'} {'Precentral' 'Pre-central' 'Postcentral' 'Post-central'} + ... + 'Sag' {'Sagital' 'sag_' 'sag-' 'sag ' 'sagittal'} {} + 'Fro' {'Frontal'} {'Lobe' 'Orbito-Frontal' 'Frotono-Orbital' 'Orbitofrontal' ... + 'Occipito-Frontal' 'Fronto-Occupital'} + 'Bas' {'Basal'} {} + 'Lat' {'Lateral' 'lat_' 'lat-' 'lat '} {} + 'Lon' {'Longitudinal'} {} + 'Occ' {'Occipital'} {'Fronto-Occupital' 'Occupital-Frontal' 'Lobe'} + 'OrbFro' {'Orbito-Frontal' 'Frotono-Orbital' 'Orbitofrontal'} {}; + 'Orb' {'Orbital' '_orb' '-orb'} {'Frotono-Orbital' 'Orbitofrontal'} + 'FroOcc' {'Fronto-Occupital' 'Occipito-Frontal'} {} + ... + 'Par' {'Parietal' 'Pariatal'} {'Lobe'} + 'Pac' {'Paracentral'} {} + 'PoC' {'Postcentral'} {} + 'PrFro' {'Prefrontal'} {} + 'PrMot' {'Premotor'} {} + 'Prc' {'Precentral'} {} + 'Tem' {'Temporal'} {'Lobe'} + 'Tra' {'Transverse'} {} + 'Ven' {'Ventral'} {} + ... + 'Ext' {'Exterior'} {} + }; + dict.structures = { ... % unspecific multiple cases + '1st' {'First','1st'} {} + '2nd' {'Sencond','2nd'} {} + '3th' {'Third','3rd'} {} + '4th' {'Fourth','4th'} {} + '5th' {'Fifth','5th'} {} + ... + 'TeLo' {'Temporal Lobe' 'Temporal Lobe'} {} + 'PaLo' {'Pariatal Lobe' 'Pariatal Lobe' 'Parietal Lobe' 'Parietal-Lobe'} {} + 'OcLo' {'Occipital Lobe' 'Occipital Lobe'} {} + 'FrLo' {'Frontal Lobe' 'Frontal Lobe'} {} + ... + 'BG' {'Background'} {} + 'Cap' {'Capsule' 'Capsula'} {} + 'Gy' {'Gyrus'} {} + 'Gy' {'Gyri'} {} + 'Po' {'Pole'} {} + 'Su' {'Sulcus'} {} + 'Su' {'Sulci'} {} + 'Lo' {'Lobe'} {'Lobes' 'Pariatal-lobe' 'Pariatal Lobe' 'Parietal Lobe' 'Parietal-Lobe' ... + 'Temporal-lobe' 'Temporal Lobe' ... + 'Occipital-lobe' 'Occipital Lobe' ... + 'Frontal-lobe' 'Frontal Lobe'} + 'Lo' {'Lobule'} {} + 'Lo' {'Lobes'} {'Lobe'} + 'Fa' {'Fasiculus'} {} + 'Fas' {'Fascicle'} {} + 'Fib' {'Fiber'} {} + 'Ven' {'Ventricle' 'Vent'} {} + 'Ven' {'Ventricles'} {} + 'Les' {'Lesion'} {} + 'Les' {'Lesions'} {} + 'Nuc' {'Nucleus'} {'Red-Nucleus' 'red_nucleus'} + 'Nuc' {'Nucli'} {} + 'Ope' {'Operculum' 'Oper_'} {} + 'Ple' {'Plexus'} {} + 'Ple' {'Plexi'} {} + 'Pro' {'Proper'} {} + 'Ped' {'Peduncle'} {} + 'Ver' {'Vermis'} {} + 'Ukn' {'Unknown' 'undetermine'} {'Background'} + 'Bone' {'Bone'} {} + 'Fat' {'Fat'} {} + 'BV' {'Blood-vessel' 'blood' 'vessel'} {} + 'OC' {'Optic Chiasm'} {} + }; + dict.regions = { ... % specific - one case + ... 'Area' {'Area'} {} + 'Acc' {'Accumbens'} {} + 'Ang' {'Angular'} {} + 'Amb' {'Ambient'} {} + 'Amy' {'Amygdala'} {} + 'Bst' {'Brainstem' 'Brain-Stem' 'Brain Stem'} {} + 'Cal' {'Calcarine'} {} + 'Cbe' {'Cerebellum' 'cerebelum'} {} + 'Cbe' {'Cerebellar'} {} + 'Cbr' {'Cerebrum' 'Brain' 'Cortex' 'White-Matter' 'Exterior'} {'Cerebellum' 'Cerebellar' 'Stem' 'Midbrain'} + 'Cbr' {'Cerebral'} {'Brain' 'Cortex' 'White-Matter' 'Exterior' 'Midbrain'} + 'Cin' {'Cinguli' 'cinuli'} {} + 'Cin' {'Cingulus' 'cinulus'} {} + 'Cin' {'Cingulate'} {} + 'Cin' {'Cingulum'} {} + 'Cun' {'Cuneus'} {'Precuneus'} + 'PCu' {'Precuneus'} {} + 'Cau' {'Caudate'} {} + 'Clo' {'Choroid'} {} + 'Ent' {'Entorhinal Area'} {} + 'Fus' {'Fusiform'} {} + 'Fob' {'Forebrain'} {} + 'Gen' {'geniculate'} {} + 'Hes' {'Heschl' 'heschls'} {} + 'Hip' {'Hippocampus'} {'Parahippocampus' 'Parahippocampal'} + 'Ins' {'Insula'} {} + 'Lin' {'Lingual'} {} + 'Lem' {'Lemniscus'} {} + 'Mot' {'Motor'} {'Premotor'} + 'Olf' {'Olfactory'} {} + 'Rec' {'Rectus'} {} + 'Rol' {'Rolandic'} {} + 'Pal' {'Pallidum'} {} + 'ParHip' {'Parahippocampus' 'Parahippocampal'} {'Parahippocampus'} + 'ParHip' {'Parahippocampal' 'Parahippocampus'} {'Parahippocampal'} + 'Pla' {'Planum Polare'} {} + 'Put' {'Putamen'} {} + 'Rec' {'Rectal'} {} + 'SCA' {'Subcallosal Area'} {} + 'Som' {'Somatosensory'} {} + 'SubNig' {'Substancia-Nigra' 'substancia_nigra'} {} + 'SupMar' {'Supramarginal'} {} + 'Tha' {'Thalamus' 'Thal:'} {} + 'Tap' {'Tapatum'} {} + 'CC' {'Corpus Callosum' 'corpus-callosum' 'corpus callosum' 'corpuscallosum' 'callosum'} {} + 'Ste' {'Stellate'} {} + 'Vis' {'Visual'} {} + }; + dict.addon = { + 'Gen' {'(Genu)' 'genu'} {} + 'Bod' {'(Body)' 'bod'} {} + 'Rem' {'(Remainder)'} {} + 'Spe' {'(Splenium)'} {} + }; + dict.ibsr = { + 'Cbr' {'Cerebrum' 'Exterior'} {'brainstem' 'brain-stem'} + 'Cbr' {'Cerebrum' 'Line-1'} {'brainstem' 'brain-stem'} + 'Cbr' {'Cerebrum' 'Line-2'} {'brainstem' 'brain-stem'} + 'Cbr' {'Cerebrum' 'Line-3'} {'brainstem' 'brain-stem'} + 'Cbr' {'Cerebrum' 'CSF'} {'brainstem' 'brain-stem'} + 'Cbr' {'Cerebrum' 'F3orb'} {'brainstem' 'brain-stem'} + 'Cbr' {'Cerebrum' 'lOg'} {'brainstem' 'brain-stem'} + 'Cbr' {'Cerebrum' 'aOg'} {'brainstem' 'brain-stem'} + 'Cbr' {'Cerebrum' 'mOg'} {'brainstem' 'brain-stem'} + 'Cbr' {'Cerebrum' 'pOg'} {'brainstem' 'brain-stem'} + 'Cbr' {'Cerebrum' 'Porg'} {'brainstem' 'brain-stem'} + 'Cbr' {'Cerebrum' 'Aorg'} {'brainstem' 'brain-stem'} + 'BG' {'Background' 'Bright-Unknown'} {} + 'BG' {'Background' 'Dark_Unknown'} {} + }; + dict.aala = { + 'SMA' {'SMA'} {} + 'CerVer' {'cerebella Vermis'} {} + }; + dict.aal = { + 'Cr1' {'Cruis1'} {} + '3' {'3' '_3'} {} + '4-5' {'4-5' '_4_5'} {} + '6' {'6' '_6'} {} + '7b' {'7b' '_7b'} {} + '8' {'8' '_8'} {} + '9' {'9' '_9'} {} + '10' {'10' '_10'} {} + '1-2' {'1-2' '_1_2'} {} + }; + dict.mori = { + 'CST' {'corticospinal_tract'} {} + 'LIC' {'Limb of Internal' 'Limb_of_internal'} {} + 'ThR' {'Thalamic Radiation' 'thalamic_radiation'} {} + 'CR' {'Corona Radiata' 'corona_radiata'} {} + 'For' {'Fornix'} {} + 'RedNuc' {'Red-Nucleus' 'red_nucleus'} {} + 'MBR' {'Midbrain'} {} + 'PNS' {'Pons'} {} + 'MDA' {'Medulla'} {} + 'Ent' {'Entorhinal Area' 'entorhinal_area'} {} + 'Ext' {'External'} {} + 'UNC' {'Uncinate'} {} + 'RetLenINC' {'Retrolenticular_part_of_internal_capsule'} {} + 'Str' {'Stratum'} {} + 'Ext' {'External Capsule' 'external_capule'} {} + 'PCT' {'Pontine Crossing Tract' 'pontine_crossing_tract'} {} + 'Spl' {'Splentum'} {} + 'GloPal' {'Globus Pallidus' 'globus_pallidus'} {} + 'Str' {'Stria'} {} + 'Ter' {'Terminalis'} {} + 'Lon' {'Longitudinal'} {} + 'Col' {'Column'} {} + ... + }; + dict.hammers = { + ... + }; + dict.anatomy = { + ... numbers + ... + 'AcuRad' {'Acoustic radiation'} {} + 'CM' {'Amygdala (CM)' 'Amyg (CM)'} {} + 'LB' {'Amygdala (LB)' 'Amyg (LB)'} {} + 'SF' {'Amygdala (SF)' 'Amyg (SF)'} {} + ... % brodmann areas + 'Brod01' {'Brodmann Area 1' 'Area 1'} {'Area 17'} % PSC 1 + 'Brod02' {'Brodmann Area 2' 'Area 2'} {'Area 18'} % PSC 2 + 'Brod03a' {'Brodmann Area 3a' 'Area 3a'} {} + 'Brod03b' {'Brodmann Area 3b' 'Area 3b'} {} + 'Brod04a' {'Brodmann Area 4a' 'Area 4a'} {} % motor + 'Brod04p' {'Brodmann Area 4p' 'Area 4p'} {} % motor + 'Brod17' {'Brodmann Area 17' 'Area 17'} {} + 'Brod18' {'Brodmann Area 18' 'Area 18'} {} + 'Brod44' {'Brodmann Area 44' 'Area 44'} {} + 'Brod45' {'Brodmann Area 45' 'Area 45'} {} + 'Brod06' {'Brodmann Area 6' 'Area 6'} {} + ... SPL - Area 5, 7 + 'SPL_Brod5Ci' {'Brodmann Area 5Ci (SPL)' 'Area 5Ci'} {} + 'SPL_Brod5l' {'Brodmann Area 5l (SPL)' 'Area 5l'} {} + 'SPL_Brod5m' {'Brodmann Area 5m (SPL)' 'Area 5m'} {} + 'SPL_Brod7A' {'Brodmann Area 7A (SPL)' 'Area 7A'} {} + 'SPL_Brod7M' {'Brodmann Area 7M (SPL)' 'Area 7M'} {} + 'SPL_Brod7P' {'Brodmann Area 7P (SPL)' 'Area 7P'} {} + 'SPL_Brod7PC' {'Brodmann Area 7PC (SPL)' 'Area 7PC'} {'Area 7P'} + ... FG + 'BrodFG1' {'Area FG1'} {} + 'BrodFG2' {'Area FG2'} {} + ... Fp + 'BrodFp1' {'Area Fp1'} {} + 'BrodFp2' {'Area Fp2'} {} + ... IPL + 'IPL_BrodFP' {'Area PF (IPL)'} {} + 'IPL_BrodFPcm' {'Area PFcm (IPL)'} {} + 'IPL_BrodFPm' {'Area PFm (IPL)'} {} + 'IPL_BrodFPop' {'Area PFop (IPL)'} {} + 'IPL_BrodFP' {'Area PFt (IPL)'} {} + 'IPL_BrodPGa' {'Area PGa (IPL)'} {} + 'IPL_BrodPGp' {'Area PGp (IPL)'} {} + ... + 'BF_CH1-3' {'BF (Ch 1-3)'} {} + 'BF_Ch4' {'BF (Ch 4)'} {} + 'CST' {'Corticospinal tract'} {} + 'EC' {'Entorhinal Cortex'} {} + 'Fo' {'Fornix'} {} + ...'HATA' {'HATA Region'} {} % Hipp HATA + 'OR' {'Optic radiation'} {} + 'SC' {'Subiculum'} {} + ... + 'Unc' {'Uncinate'} {} + ... hOc + 'hOc1' {'hcO1 [V1]','hOc1 [V1]'} {} + 'hOc2' {'hOc2 [V2]'} {} + 'hOc3d' {'hOc3d [V3d]'} {} + 'hOc3v' {'hOc3v [V3v]'} {} + 'hOc4d' {'hOc4d [V3A]'} {} + 'hOc4v' {'hOc4v [V4(v)]'} {} + 'hOc5' {'hOc5 [V5/MT]'} {} + ... hippocampus + 'CA' {'Hippocampus (CA)' 'HIPP (CA)'} {} + 'PF' {'Hippocampus (PF)' 'HIPP (PF)'} {} + 'EC' {'Hippocampus (EC)' 'Hipp (EC)'} {} + 'FD' {'Hippocampus (FD)' 'Hipp (FD)'} {} + 'DG' {'Hippocampus (DG)' 'Hipp (DG)' 'DG (Hippocampus)' 'hippocampus_DG'} {} + 'HATA' {'Hippocampus (HATA)' 'Hipp (HATA)' 'HATA'} {} + 'Sub' {'Hippocampus (SUB)' 'Hipp (SUB)'} {} + 'CA1' {'Hippocampus (CA1)' 'CA1 (Hippocampus)','hippocampus_CA1'} {} + 'CA2' {'Hippocampus (CA2)' 'CA2 (Hippocampus)','hippocampus_CA3'} {} + 'CA3' {'Hippocampus (CA3)' 'CA3 (Hippocampus)','hippocampus_CA3'} {} + ... IPL + 'IPL_PF' {'IPL (PF)' 'Area PF (IPL)' 'IPL_PF'} {'IPL_PFcm' 'IPL_PFm' 'IPL_Pfop' 'IPL_Pfa' 'IPL_Pft' 'IPL_Pfp'} + 'IPL_PFcm' {'IPL (PFcm)' 'Area PFcm (IPL)' 'IPL_PFcm'} {} + 'IPL_PFm' {'IPL (PFm)' 'Area PFm (IPL)' 'IPL_PFm'} {} + 'IPL_PFop' {'IPL (PFop)' 'Area PFop (IPL)' 'IPL_Pfop'} {} + 'IPL_PFt' {'IPL (PFt)' 'Area PFt (IPL)' 'IPL_Pft'} {} + 'IPL_PFa' {'IPL (PFa)' 'Area PFa (IPL)' 'IPL_Pfa'} {} + 'IPL_PFp' {'IPL (PFp)' 'Area PFp (IPL)' 'IPL_Pfp'} {} + ... inula + 'Id1' {'(Id1)' 'Insula (Id1)' 'Area Id1 (Insula)' 'Insula_Id1'} {} % anatomy + 'Ig1' {'(Ig1)' 'Insula (Ig1)' 'Area Ig1 (Insula)' 'Insula_Ig1'} {} % anatomy + 'Ig2' {'(Ig2)' 'Insula (Ig2)' 'Area Ig2 (Insula)' 'Insula_Ig2'} {} % anatomy + ... cerebellum + 'Cbe10H' {'Lobule X (Hem)'} {} + 'Cbe10V' {'Lobule X (Verm)' 'Lobule X (Vermis)'} {} + 'Cbe9H' {'Lobule IX (Hem)'} {} + 'Cbe9V' {'Lobule IX (Vermis)' 'Lobule IX (Vermis)'} {} + 'Cbe8aH' {'Lobule VIIIa (Hem)'} {} + 'Cbe8aV' {'Lobule VIIIa (Verm)' 'Lobule VIIIa (Vermis)'} {} + 'Cbe8bH' {'Lobule VIIIb (Hem)'} {} + 'Cbe8bV' {'Lobule VIIIb (Verm)' 'Lobule VIIIb (Vermis)'} {} + 'Cbe7a1H' {'Lobule VIIa Crus I (Hem)' 'Lobule VIIa crusI (Hem)'} {} + 'Cbe7a1V' {'Lobule VIIa Crus I (Verm)' 'Lobule VIIa crusI (Verm)' 'Lobule VIIa Crus I (Vermis)'} {} + 'Cbe7a2H' {'Lobule VIIa Crus II (Hem)' 'Lobule VIIa crusII (Hem)' } {} + 'Cbe7a2V' {'Lobule VIIa Crus II (Verm)' 'Lobule VIIa crusII (Verm)' 'Lobule VIIa Crus II (Vermis)'} {} + 'Cbe7b' {'Lobule VIIb (Hem)' 'Cerebellum_VIIb_Hem'} {} + 'Cbe7b' {'Lobule VIIb (Verm)' 'Cerebellum_VIIb_Verm' 'Lobule VIIb (Vermis)'} {} + 'Cbe6H' {'Lobule VI (Hem)'} {} + 'Cbe6V' {'Lobule VI (Verm)' 'Lobule VI (Vermis)'} {} + 'Cbe5' {'Lobule V '} {} + 'Cbe5H' {'Lobule V (Hem)'} {} + 'Cbe5V' {'Lobule V (Verm)' 'Lobule V (Vermis)'} {} + 'Cbe1_4H' {'Lobules I-IV (Hem)' 'Lobule I IV (Hem)'} {} + ... Area OP + 'OP1' {'OP 1'} {} + 'OP2' {'OP 2'} {} + 'OP3' {'OP 3'} {} + 'OP4' {'OP 4'} {} + ... SPL + 'SPL5Ci' {'SPL (5Ci)'} {} + 'SPL5L' {'SPL (5L)'} {} + 'SPL5M' {'SPL (5M)'} {} + 'SPL7A' {'SPL (7A)'} {} + 'SPL7M' {'SPL (7M)'} {} + 'SPL7P' {'SPL (7P)'} {} + 'SPL7PC' {'SPL (7PC)'} {} + ... Area TE (auditory) + 'TE10' {'TE 1.0'} {} + 'TE11' {'TE 1.1'} {} + 'TE12' {'TE 1.2'} {} + 'TE3' {'TE 3'} {} + ... hIP + 'IPS_hIP1' {'IPS_hIP1' 'Area hIP1 (IPS)' 'AIPS_IP1'} {} + 'IPS_hIP2' {'IPS_hIP2' 'Area hIP2 (IPS)' 'AIPS_IP2'} {} + 'IPS_hIP3' {'IPS_hIP3' 'Area hIP3 (IPS)' 'AIPS_IP3'} {} + ... hOC + 'hOC3v' {'hOC3v (V3v)'} {} + 'hOC4' {'hOC4v (V4)'} {} + 'hOC5' {'hOC5 (V5)'} {} + ... ?? + 'CalMam' {'Callosal body & Mamillary body'} {} + }; + dict.neuromorphometrics = { + ' ' {'Ventricle'} {} + 'Cbe1-5' {'Cerebellar Vermal Lobules I-V'} {} + 'Cbe6-7' {'Cerebellar Vermal Lobules VI-VII'} {} + 'Cbe8-10' {'Cerebellar Vermal Lobules VIII-X'} {} + 'Forb' {'Forbrain'} {} + ... replace abbreviations by an empty space + ' ' {'ACgG','AIns','AOrG','AnG','Calc','CO','Cun','Ent',... + 'FO','FRP','FuG','GRe','LOrG','MCgG','MFC','MFG',... + 'MOG','MOrG','MPoG','MPrG','MSFG','MTG','OCP',... + 'OFuG','OpIFG','PCgG','PCu','PHG','PIns','PO','PoG',... + 'POrG','PP','PrG','PT','SCA','SFG','SMC','SMG','SOG',... + 'SPL','STG','TMP','TrIFG','TTG'} {} + 'Br' {'Brain'} {'brainstem' 'brain-stem' 'brain stem'} + 'WM' {'White Matter'} {}; + 'CSF' {'CSF'} {}; + }; +end + +function create_cat_atlas(A,C,LAB) +%% +% ToDo: +% - T1-Data für feineren Abgleich mit Gewebewahrscheinlichkeit? +% - Mitteln/Ergänzen von Regionen + + % output file +% VC = spm_vol(A.ham); VC.fname = C; + VC = spm_vol(fullfile(spm('dir'),'toolbox','cat12','templates_volumes/Template_1_IXI555_MNI152.nii')); VC=VC(1); + VC.fname = C; + + if 1 + clear LAB + + LAB.BV = { 7,{'l1A'},{[7,8]}}; % Blood Vessels + LAB.HD = {21,{'l1A'},{[21,22]}}; % head + LAB.ON = {11,{'l1A'},{[11,12]}}; % Optical Nerv + + LAB.CT = { 1,{'ibs'},{'Cbr'}}; % cortex + LAB.MB = {13,{'ham'},{'MBR','VenV'}}; % MidBrain + LAB.BS = {13,{'ham'},{'Bst'}}; % BrainStem + LAB.CB = { 3,{'ham'},{'Cbe'}}; % Cerebellum + LAB.BG = { 5,{'ham'},{'Put','Pal','CauNuc'}}; % BasalGanglia + LAB.TH = { 9,{'ham'},{'Tha'}}; % Hypothalamus + LAB.HC = {19,{'ham'},{'Hip'}}; % Hippocampus + LAB.AM = {19,{'ham'},{'Amy'}}; % Amygdala + LAB.VT = {15,{'ham'},{'LatV','LatTemV','VenV'}}; % Ventricle + LAB.NV = {17,{'ham'},{'Ins','3thV','4thV'}}; % no Ventricle + end + + % get atlas and descriptions + AFN=fieldnames(A); + for afni=1:numel(AFN) + [pp,ff]=fileparts(A.(AFN{afni})); + try + csv.(AFN{afni})=cat_io_csv(fullfile(pp,[ff '.csv'])); + catch + csv.(AFN{afni})={}; + end + VA.(AFN{afni}) = spm_vol(A.(AFN{afni})); + YA.(AFN{afni}) = uint8(round(spm_read_vols(VA.(AFN{afni})))); + YB.(AFN{afni}) = zeros(VC.dim,'uint8'); + end + csv.l1A = { ... + 1 'lCbr'; + 2 'rCbr'; + 3 'lCbe'; + 4 'rCbe'; + 5 'lBG'; + 6 'rBG'; + 7 'lBV'; + 8 'rBV'; + 9 'lTha'; + 10 'rTha'; + 15 'lLatV'; + 16 'rLatV'; + 19 'lAmy'; + 20 'rAmy'; + 21 'lHD'; + 22 'rHD'; + }; + + + % convert main atlas data + LFN=fieldnames(LAB); + for lfni=1:numel(LFN) + for afni=1:numel(LAB.(LFN{lfni}){2}) + for ri=1:numel(LAB.(LFN{lfni}){3}) + fprintf('%2d %2d\n',lfni,ri); + if ischar(LAB.(LFN{lfni}){3}{ri}) + fi = find(cellfun('isempty',strfind( csv.(LAB.(LFN{lfni}){2}{afni})(:,2) , LAB.(LFN{lfni}){3}{ri} ))==0); + ni = cell2mat(csv.(LAB.(LFN{lfni}){2}{afni})(fi,1)); %#ok + else + ni = LAB.(LFN{lfni}){3}{ri}; + end + + for si = 1:numel(ni) + YB.(LAB.(LFN{lfni}){2}{afni})(YA.(LAB.(LFN{lfni}){2}{afni})==ni(si)) = LAB.(LFN{lfni}){1} + si-1; + end + end + end + end + + %% convert expert data + LFN=fieldnames(LAB); + + for afni=2:numel(AFN) + [pp,atlas]=fileparts(A.(AFN{afni})); + [tmp0,PA,Pcsv] = mydata(atlas); clear tmp0; + csv2=cat_io_csv(Pcsv{1}); + csv2=translateROI(csv2,atlas); + for pai=1:numel(PA) + VPA = spm_vol(PA{pai}); + YPA = uint8(round(spm_read_vols(VPA))); + YPB = YPA*0; + fprintf('%2d %2d\n',afni,pai); + + for lfni=1:numel(LFN) + for ri=1:numel(LAB.(LFN{lfni}){3}) + if ischar(LAB.(LFN{lfni}){3}{ri}) + fi = find(cellfun('isempty',strfind( csv.(AFN{afni})(:,2) , LAB.(LFN{lfni}){3}{ri} ))==0); % entry in the mean map + if ~isempty(fi) + rn = csv.(AFN{afni})(fi,4); % long roi name + fi2 = find(cellfun('isempty',strfind( csv2(:,2) , rn{1} ))==0); % entry in the original map + ni = cell2mat(csv2(fi2,1)); % id in the original map + xi = csv2(fi2,6); % its side alignment + for si = 1:numel(xi) + YPB(YPA==ni(si)) = LAB.(LFN{lfni}){1} + 1*uint8(xi{si}==1); + end + end + end + end + end + VPB = VPA; [pp,ff] = fileparts(VPB.fname); + switch atlas + case 'hammers' + [pp1,pp2]=fileparts(pp); + VPB.fname = fullfile(pp1,['cat12a1_' ff '_' pp2 '.nii']); + otherwise + VPB.fname = fullfile(pp,['cat12a1_' ff '.nii']); + end + spm_write_vol(VPB,YPB); + end + end + + + +%% + if 0 + % STAPLE + for afni=1:numel(AFN) + VB=VC; VB.fname = sprintf('cat_vol_create_Atlas%d.nii',afni); P{afni}=VB.fname; + spm_write_vol(VB,YB.(AFN{afni})); + end + cat_tst_staple_multilabels(char(P),'',C,1); + for afni=1:numel(AFN) + delete(P{afni}); + end + else + N = nifti; + N.dat = file_array(C,VC(1).dim(1:3),... + [spm_type(2) spm_platform('bigend')],0,1,0); + N.mat = VC(1).mat; + N.mat0 = VC(1).private.mat0; + N.descrip = 'cat atlas map'; + YC = zeros(N.dat.dim,'single'); + for lfni=1:numel(LFN) % für jeden layer + for si=0:1 + ll = LAB.(LFN{lfni}){1} + si; + Ysum = zeros(size(YB.(AFN{afni})),'single'); esum=0; + for afni=1:numel(AFN) + Ysum = Ysum + single(YB.(AFN{afni})==ll); + esum = esum + (sum(YB.(AFN{afni})(:)==ll)>0); + end + YC((Ysum/esum)>0.5)=ll; + end + fprintf('%s %2d %2d %2d\n',LFN{lfni},lfni,ri,esum); + end + N.dat(:,:,:) = double(YC); + create(N); + end + +end + +function create_spm_atlas_xml(fname,csv,csvx,opt) +% create an spm12 compatible xml version of the csv data + if ~exist('opt','var'), opt = struct(); end + + [pp,ff,ee] = spm_fileparts(fname); + + def.name = ff; + def.desc = ''; + def.url = ''; + def.lic = 'CC BY-NC'; + def.cor = 'MNI DARTEL'; + def.type = 'Label'; + def.images = [ff '.nii']; + + opt = cat_io_checkinopt(opt,def); + + xml.header = [... + '\n' ... + '\n' ... + ' \n' ... + '
\n' ... + ' ' opt.name '\n' ... + ' 1.0\n' ... + ' ' opt.desc '\n' ... + ' ' opt. url '\n' ... + ' ' opt.lic '\n' ... + ' ' opt.cor '\n' ... + ' ' opt.type '\n' ... + ' \n' ... + ' ' opt.images '\n' ... + ' \n' ... + '
\n' ... + ' \n' ... + ' \n' ... + ]; + %sidel = {'Left ' 'Right ' 'Bothside '}; + %sides = {'l' 'r' 'b'}; + %sidev = [1 2 1]; + %xml.data = sprintf([' \n'],0,'BG','Background'); + xml.data = ''; + for di = 2:size(csvx,1); + % index = label id + % name = long name SIDE STRUCTURE TISSUE + % short_name = short name + % RGBA = RGB color + % XYZmm = XYZ coordinate + xml.data = sprintf('%s%s\n',xml.data,sprintf([' '],... + csvx{di,1}, csvx{di,2},csvx{di,3},csvx{di,8})); + % (csvx{di,5}-1)*2 + sidev(csv{di,6}),... + % [sides{csv{di,6}} csv{di,4}],... + % [sidel{csv{di,6}} csv{di,3}])); + end + xml.footer = [ ... + ' \n' ... + '
\n' ... + ]; + + fid = fopen(fullfile(pp,['labels_dartel_' ff ee]),'w'); + fprintf(fid,[xml.header,xml.data,xml.footer]); + fclose(fid); +end + +% newer matlab functions +%-------------------------------------------------------------------------- +function [c, matches] = strsplit(str, aDelim, varargin) +%STRSPLIT Split string at delimiter +% C = STRSPLIT(S) splits the string S at whitespace into the cell array +% of strings C. +% +% C = STRSPLIT(S, DELIMITER) splits S at DELIMITER into C. DELIMITER can +% be a string or a cell array of strings. If DELIMITER is a cell array of +% strings, STRSPLIT splits S along the elements in DELIMITER, in the +% order in which they appear in the cell array. +% +% C = STRSPLIT(S, DELIMITER, PARAM1, VALUE1, ... PARAMN, VALUEN) modifies +% the way in which S is split at DELIMITER. +% Valid parameters are: +% 'CollapseDelimiters' - If true (default), consecutive delimiters in S +% are treated as one. If false, consecutive delimiters are treated as +% separate delimiters, resulting in empty string '' elements between +% matched delimiters. +% 'DelimiterType' - DelimiterType can have the following values: +% 'Simple' (default) - Except for escape sequences, STRSPLIT treats +% DELIMITER as a literal string. +% 'RegularExpression' - STRSPLIT treats DELIMITER as a regular +% expression. +% In both cases, DELIMITER can include the following escape +% sequences: +% \\ Backslash +% \0 Null +% \a Alarm +% \b Backspace +% \f Form feed +% \n New line +% \r Carriage return +% \t Horizontal tab +% \v Vertical tab +% +% [C, MATCHES] = STRSPLIT(...) also returns the cell array of strings +% MATCHES containing the DELIMITERs upon which S was split. Note that +% MATCHES always contains one fewer element than C. +% +% Examples: +% +% str = 'The rain in Spain stays mainly in the plain.'; +% +% % Split on all whitespace. +% strsplit(str) +% % {'The', 'rain', 'in', 'Spain', 'stays', +% % 'mainly', 'in', 'the', 'plain.'} +% +% % Split on 'ain'. +% strsplit(str, 'ain') +% % {'The r', ' in Sp', ' stays m', 'ly in the pl', '.'} +% +% % Split on ' ' and on 'ain' (treating multiple delimiters as one). +% strsplit(str, {' ', 'ain'}) +% % ('The', 'r', 'in', 'Sp', 'stays', +% % 'm', 'ly', 'in', 'the', 'pl', '.'} +% +% % Split on all whitespace and on 'ain', and treat multiple +% % delimiters separately. +% strsplit(str, {'\s', 'ain'}, 'CollapseDelimiters', false, ... +% 'DelimiterType', 'RegularExpression') +% % {'The', 'r', '', 'in', 'Sp', '', 'stays', +% % 'm', 'ly', 'in', 'the', 'pl', '.'} +% +% See also REGEXP, STRFIND, STRJOIN. + +% Copyright 2012 The MathWorks, Inc. +% $Revision$ $Date$ + +%narginchk(1, Inf); + +% Initialize default values. +collapseDelimiters = true; +delimiterType = 'Simple'; + +% Check input arguments. +if nargin < 2 + delimiterType = 'RegularExpression'; + aDelim = '\s'; +end +if ~isString(str) + error(message('MATLAB:strsplit:InvalidStringType')); +end +if isString(aDelim) + aDelim = {aDelim}; +elseif ~isCellString(aDelim) + error(message('MATLAB:strsplit:InvalidDelimiterType')); +end +if nargin > 2 + funcName = mfilename; + p = inputParser; + p.FunctionName = funcName; + p.addParamValue('CollapseDelimiters', collapseDelimiters); + p.addParamValue('DelimiterType', delimiterType); + p.parse(varargin{:}); + collapseDelimiters = verifyScalarLogical(p.Results.CollapseDelimiters, ... + funcName, 'CollapseDelimiters'); + delimiterType = validatestring(p.Results.DelimiterType, ... + {'RegularExpression', 'Simple'}, funcName, 'DelimiterType'); +end + +% Handle DelimiterType. +if strcmp(delimiterType, 'Simple') + % Handle escape sequences and translate. + aDelim = strescape(aDelim); + aDelim = regexptranslate('escape', aDelim); +else + % Check delimiter for regexp warnings. + regexp('', aDelim, 'warnings'); +end + +% Handle multiple delimiters. +aDelim = strjoin(aDelim, '|'); + +% Handle CollapseDelimiters. +if collapseDelimiters + aDelim = ['(?:', aDelim, ')+']; +end + +% Split. +[c, matches] = regexp(str, aDelim, 'split', 'match'); + +end + +function tf = verifyScalarLogical(tf, funcName, parameterName) + +if isscalar(tf) && isnumeric(tf) && any(tf == [0, 1]) + tf = logical(tf); +else + validateattributes(tf, {'logical'}, {'scalar'}, funcName, parameterName); +end + +end +%-------------------------------------------------------------------------- +function joinedStr = strjoin(c, aDelim) +%STRJOIN Join cell array of strings into single string +% S = STRJOIN(C) constructs the string S by linking each string within +% cell array of strings C together with a space. +% +% S = STRJOIN(C, DELIMITER) constructs S by linking each element of C +% with the elements of DELIMITER. DELIMITER can be either a string or a +% cell array of strings having one fewer element than C. +% +% If DELIMITER is a string, then STRJOIN forms S by inserting DELIMITER +% between each element of C. DELIMITER can include any of these escape +% sequences: +% \\ Backslash +% \0 Null +% \a Alarm +% \b Backspace +% \f Form feed +% \n New line +% \r Carriage return +% \t Horizontal tab +% \v Vertical tab +% +% If DELIMITER is a cell array of strings, then STRJOIN forms S by +% interleaving the elements of DELIMITER and C. In this case, all +% characters in DELIMITER are inserted as literal text, and escape +% characters are not supported. +% +% Examples: +% +% c = {'one', 'two', 'three'}; +% +% % Join with space. +% strjoin(c) +% % 'one two three' +% +% % Join as a comma separated list. +% strjoin(c, ', ') +% % 'one, two, three' +% +% % Join with a cell array of strings DELIMITER. +% strjoin(c, {' + ', ' = '}) +% % 'one + two = three' +% +% See also STRCAT, STRSPLIT. + +% Copyright 2012 The MathWorks, Inc. +% $Revision$ $Date$ + +%narginchk(1, 2); + +% Check input arguments. +if ~isCellString(c) + error(message('MATLAB:strjoin:InvalidCellType')); +end +if nargin < 2 + aDelim = ' '; +end + +% Allocate a cell to join into - the first row will be C and the second, D. +numStrs = numel(c); +joinedCell = cell(2, numStrs); +joinedCell(1, :) = reshape(c, 1, numStrs); +if isString(aDelim) + if numStrs < 1 + joinedStr = ''; + return; + end + escapedDelim = strescape(aDelim); + joinedCell(2, 1:numStrs-1) = {escapedDelim}; +elseif isCellString(aDelim) + numDelims = numel(aDelim); + if numDelims ~= numStrs - 1 + error(message('MATLAB:strjoin:WrongNumberOfDelimiterElements')); + end + joinedCell(2, 1:numDelims) = aDelim(:); +else + error(message('MATLAB:strjoin:InvalidDelimiterType')); +end + +% Join. +joinedStr = [joinedCell{:}]; + +end + +function y=isString(x) + y = ischar(x); +end + +function y=isCellString(x) + y = 0; + if iscell(x) + for i=1:numel(x) + if ~ischar(x{i}), return; end + end + else + return + end + y = 1; +end + +function escapedStr = strescape(str) +%STRESCAPE Escape control character sequences in a string. +% STRESCAPE(STR) converts the escape sequences in a string to the values +% they represent. +% +% Example: +% +% strescape('Hello World\n') +% +% See also SPRINTF. + +% Copyright 2012 The MathWorks, Inc. +% $Revision$ $Date$ + +escapeFcn = @escapeChar; %#ok +escapedStr = regexprep(str, '\\(.|$)', '${escapeFcn($1)}'); + +end +%-------------------------------------------------------------------------- +function c = escapeChar(c) + switch c + case '0' % Null. + c = char(0); + case 'a' % Alarm. + c = char(7); + case 'b' % Backspace. + c = char(8); + case 'f' % Form feed. + c = char(12); + case 'n' % New line. + c = char(10); + case 'r' % Carriage return. + c = char(13); + case 't' % Horizontal tab. + c = char(9); + case 'v' % Vertical tab. + c = char(11); + case '\' % Backslash. + case '' % Unescaped trailing backslash. + c = '\'; + otherwise + warning(message('MATLAB:strescape:InvalidEscapeSequence', c, c)); + end +end + +","MATLAB" +"Neurology","ChristianGaser/cat12","development/Atlas_summarize_MPM.m",".m","5421","118","function Atlas_summarize_MPM(sel) +% Tool to select the best threshold for the MPM atlases by comparing volumes of gray matter inside the labels +%_______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +if nargin == 0 + sel = spm_input('Which Atlas?', 1, 'm',{'LPBA40','Cobra','IBSR2','Neuromorphometrics','Hammers'}); +end + +switch sel + +case 1 + atlas_file = cellstr(spm_select('FPList','/Volumes/UltraMax/LPBA40/delineation_space','^MPM_th.*S.delineation')); + def_file = cellstr(spm_select('FPList','/Volumes/UltraMax/LPBA40/delineation_space/mri','^y_')); + value_file = cellstr(spm_select('FPList','/Volumes/UltraMax/LPBA40/delineation_space/mri','^p1')); + label_file = cellstr(spm_select('FPList','/Volumes/UltraMax/LPBA40/delineation_space','^S.*delineation.structure.label')); +case 2 + atlas_file = cellstr(spm_select('FPList','/Volumes/UltraMax/WinterburnHippocampalAtlas_NIfTI/labels','^MPM_th*')); + def_file = cellstr(spm_select('FPList','/Volumes/UltraMax/WinterburnHippocampalAtlas_NIfTI/resampled_registered/mri','^y_')); + value_file = cellstr(spm_select('FPList','/Volumes/UltraMax/WinterburnHippocampalAtlas_NIfTI/resampled_registered/mri','^p1lowresR2x2x2')); + label_file = cellstr(spm_select('FPList','/Volumes/UltraMax/WinterburnHippocampalAtlas_NIfTI/resampled_registered','^lowresR2x2x2_subject.*labels.nii')); +case 3 + atlas_file = cellstr(spm_select('FPList','/Volumes/UltraMax/IBSR2','^MPM_th.*IBSR')); + def_file = cellstr(spm_select('FPList','/Volumes/UltraMax/IBSR2/mri','^y_')); + value_file = cellstr(spm_select('FPList','/Volumes/UltraMax/IBSR2/mri','^p1')); + label_file = cellstr(spm_select('FPList','/Volumes/UltraMax/IBSR2','^IBSR.*seg_ana')); +case 4 + atlas_file = cellstr(spm_select('FPList','/Volumes/UltraMax/Neuromorphometrics_MICCAI2012/','^MPM_th.*glm')); + def_file = cellstr(spm_select('FPList',{'/Volumes/UltraMax/Neuromorphometrics_MICCAI2012/testing-images/mri','/Volumes/UltraMax/Neuromorphometrics_MICCAI2012/training-images/mri'},'^y_')); + value_file = cellstr(spm_select('FPList',{'/Volumes/UltraMax/Neuromorphometrics_MICCAI2012/testing-images/mri','/Volumes/UltraMax/Neuromorphometrics_MICCAI2012/training-images/mri'},'^p1')); + label_file = cellstr(spm_select('FPList',{'/Volumes/UltraMax/Neuromorphometrics_MICCAI2012/testing-labels','/Volumes/UltraMax/Neuromorphometrics_MICCAI2012/training-labels'},'^1.*glm')); +case 5 + atlas_file = cellstr(spm_select('FPList','/Volumes/UltraMax/HammersAtlas/Hammers_mith-n30r95','^MPM_th.*')); + def_file = cellstr(spm_select('FPList','/Volumes/UltraMax/HammersAtlas/Hammers_mith-n30r95/mri','^y_')); + value_file = cellstr(spm_select('FPList','/Volumes/UltraMax/HammersAtlas/Hammers_mith-n30r95/mri','^p1')); + label_file = cellstr(spm_select('FPList','/Volumes/UltraMax/HammersAtlas/Hammers_mith-n30r95','^a.*-seg')); +end + +if numel(def_file) ~= numel(value_file) | numel(def_file) ~= numel(label_file) + error('Number of files for deformations (n=%d), values (n=%d) or label (n=%d) differ\n',numel(def_file),numel(value_file),numel(label_file)); +end + +n_subjects = numel(def_file); +n_atlas = numel(atlas_file); + +fprintf('Number of atlases:\t%d\nNumber of subjects:\t%d\n',n_atlas,n_subjects); + +% use relative error or absolute error +calc_relative_error = 1; + +err_arr = NaN(n_subjects,n_atlas); +mean_arr = NaN(n_subjects,n_atlas); + +V = spm_vol(atlas_file{1}); +atlas = round(spm_read_vols(V)); +structures = sort(unique(atlas(atlas > 0))); +n_structures = numel(structures); + +for si=1:n_subjects + + fprintf('%s:\n',value_file{si}); + V = spm_vol(value_file{si}); + value = spm_read_vols(V); + label = round(spm_read_vols(spm_vol(label_file{si}))); + + % IBSR2 atlas should be permuted because of wrong orientation + if sel == 3 + label = permute(label,[1 3 2]); + end + vx_vol = sqrt(sum(V.mat(1:3,1:3).^2)); + + ref_val = zeros(n_structures,1); + for ri = 1:n_structures + ref_val(ri) = prod(vx_vol)*sum(value(label==structures(ri)))/1000; + end + + Y = cat_vol_ROI_summarize(struct('atlases',{atlas_file},'field1',{{def_file{si}}},'images',{{value_file{si}}},'fhandle','volume')); + + ind = (ref_val ~= 0); + + for ai=1:n_atlas + [pp,atlas_name] = spm_fileparts(atlas_file{ai}); + if calc_relative_error + perc_err = 100*mean((Y{ai,1}(ind)-ref_val(ind))./ref_val(ind)); + else + perc_err = mean((Y{ai,1}(ind)-ref_val(ind))); + end + mean_Y = mean(Y{ai,1}(ind)./ref_val(ind)); + fprintf('%3.6f\t%3.6f\t%s\n',perc_err,mean_Y,atlas_name); + err_arr(si,ai) = perc_err; + mean_arr(si,ai) = mean_Y; + end +end + +[tmp, name] = spm_str_manip(atlas_file,'C'); +fprintf('Atlas names:%s\n',tmp) +fprintf('%20s\t%30s\t%30s\n','Atlas','median error (should be low)','median ratio (should be close to one)'); +med_err = median(err_arr); +med_mean = median(mean_arr); +for ai=1:n_atlas + fprintf('%20s\t%30.5f\t%30.5f\n',name.m{ai},med_err(ai), med_mean(ai)); +end + +figure(11) +cat_plot_boxplot(err_arr(:,:,1),struct('violin',0,'showdata',1,'names',{name.m})); +title('median error (should be low)') + +figure(12) +cat_plot_boxplot(mean_arr(:,:,1),struct('violin',0,'showdata',1,'names',{name.m})); +title('median ratio (should be close to one)') + +","MATLAB" +"Neurology","ChristianGaser/cat12","development/cat_stat_spm_results_ui.m",".m","76148","1755","function varargout = cat_stat_spm_results_ui(varargin) +% User interface for SPM/PPM results: Display and analysis of regional effects +% FORMAT [hReg,xSPM,SPM] = spm_results_ui('Setup',[xSPM]) +% +% hReg - handle of MIP XYZ registry object +% (see spm_XYZreg.m for details) +% xSPM - structure containing specific SPM, distribution & filtering details +% (see spm_getSPM.m for contents) +% SPM - SPM structure containing generic parameters +% (see spm_spm.m for contents) +% +% NB: Results section GUI CallBacks use these data structures by name, +% which therefore *must* be assigned to the correctly named variables. +%__________________________________________________________________________ +% +% The SPM results section is for the interactive exploration and +% characterisation of the results of a statistical analysis. +% +% The user is prompted to select a SPM{T} or SPM{F}, that is thresholded at +% user specified levels. The specification of the contrasts to use and the +% height and size thresholds are described in spm_getSPM.m. The resulting +% SPM is then displayed in the Graphics window as a maximum intensity +% projection, alongside the design matrix and contrasts employed. +% +% The cursors in the MIP can be moved (dragged) to select a particular +% voxel. The three mouse buttons give different drag and drop behaviour: +% Button 1 - point & drop; Button 2 - ""dynamic"" drag & drop with +% co-ordinate & SPM value updating; Button 3 - ""magnetic"" drag & drop, +% where the cursor jumps to the nearest suprathreshold voxel in the MIP, +% and shows the value there. +% See spm_mip_ui.m, the MIP GUI handling function for further details. +% +% The design matrix and contrast pictures are ""surfable"": Click and drag +% over the images to report associated data. Clicking with different +% buttons produces different results. Double-clicking extracts the +% underlying data into the base workspace. +% See spm_DesRep.m for further details. +% +% The current voxel specifies the voxel, suprathreshold cluster, or +% orthogonal planes (planes passing through that voxel) for subsequent +% localised utilities. +% +% A control panel in the Interactive window enables interactive exploration +% of the results. +% +% p-values buttons: +% (i) volume - Tabulates p-values and statistics for entire volume. +% - see spm_list.m +% (ii) cluster - Tabulates p-values and statistics for nearest cluster. +% - Note that the cursor will jump to the nearest +% suprathreshold voxel, if it is not already at a +% location with suprathreshold statistic. +% - see spm_list.m +% (iii) S.V.C - Small Volume Correction: +% Tabulates p-values corrected for a small specified +% volume of interest. (Tabulation by spm_list.m) +% - see spm_VOI.m +% +% Data extraction buttons: +% Eigenvariate/CVA +% - Extracts the principal eigenvariate for small volumes +% of interest; or CVA of data within a specified volume +% - Data can be adjusted or not for eigenvariate summaries +% - If temporal filtering was specified (fMRI), then it is +% the filtered data that is returned. +% - Choose a VOI of radius 0 to extract the (filtered &) +% adjusted data for a single voxel. Note that this vector +% will be scaled to have a 2-norm of 1. (See spm_regions.m +% for further details.) +% - The plot button also returns fitted and adjusted +% (after any filtering) data for the voxel being plotted.) +% - Note that the cursor will jump to the nearest voxel for +% which raw data was saved. +% - see spm_regions.m +% +% Visualisation buttons: +% (i) plot - Graphs of adjusted and fitted activity against +% various ordinates. +% - Note that the cursor will jump to the nearest +% suprathreshold voxel, if it is not already at a +% location with suprathreshold statistic. +% - Additionally, returns fitted and adjusted data to the +% MATLAB base workspace. +% - see spm_graph.m +% (ii) overlays - Popup menu: Overlays of filtered SPM on a structural image +% - slices - Slices of the thresholded statistic image overlaid +% on a secondary image chosen by the user. Three +% transverse slices are shown, being those at the +% level of the cursor in the z-axis and the two +% adjacent to it. - see spm_transverse.m +% - sections - Orthogonal sections of the thresholded statistic +% image overlaid on a secondary image chosen by the user. +% The sections are through the cursor position. +% - see spm_sections.m +% - render - Render blobs on previously extracted cortical surface +% - see spm_render.m +% (iii) save - Write out thresholded SPM as image +% - see spm_write_filtered.m +% +% The current cursor location can be set by editing the co-ordinate widgets +% at the bottom of the Interactive window. (Note that many of the results +% section facilities are ""linked"" and can update co-ordinates. E.g. +% clicking on the co-ordinates in a p-value listing jumps to that location.) +% +% Graphics appear in the bottom half of the Graphics window, additional +% controls and questions appearing in the Interactive window. +% +% ---------------- +% +% The MIP uses a template outline in MNI space. Consequently for the +% results section to display properly the input images to the statistics +% section should be in MNI space. +% +% Similarly, secondary images should be aligned with the input images used +% for the statistical analysis. +% +% ---------------- +% +% In addition to setting up the results section, spm_results_ui.m sets +% up the results section GUI and services the CallBacks. FORMAT +% specifications for embedded CallBack functions are given in the main +% body of the code. +%__________________________________________________________________________ +% Copyright (C) 1996-2018 Wellcome Trust Centre for Neuroimaging + +% Karl Friston & Andrew Holmes +% $Id$ + + +%========================================================================== +% - FORMAT specifications for embedded CallBack functions +%========================================================================== +%( This is a multi function function, the first argument is an action ) +%( string, specifying the particular action function to take. ) +% +% spm_results_ui sets up and handles the SPM results graphical user +% interface, initialising an XYZ registry (see spm_XYZreg.m) to co-ordinate +% locations between various location controls. +% +%__________________________________________________________________________ +% +% FORMAT [hreg,xSPM,SPM] = spm_results_ui('Setup') +% Query SPM and setup GUI. +% +% FORMAT [hreg,xSPM,SPM] = spm_results_ui('Setup',xSPM) +% Query SPM and setup GUI using a xSPM input structure. This allows to run +% results setup without user interaction. See spm_getSPM for details of +% allowed fields. +% +% FORMAT hReg = spm_results_ui('SetupGUI',M,DIM,xSPM,Finter) +% Setup results GUI in Interactive window +% M - 4x4 transformation matrix relating voxel to ""real"" co-ordinates +% DIM - 3 vector of image X, Y & Z dimensions +% xSPM - structure containing xSPM. Required fields are: +% .Z - minimum of n Statistics {filtered on u and k} +% .XYZmm - location of voxels {mm} +% Finter - handle (or 'Tag') of Interactive window (default 'Interactive') +% hReg - handle of XYZ registry object +% +% FORMAT spm_results_ui('DrawButts',hReg,DIM,Finter,WS,FS) +% Draw GUI buttons +% hReg - handle of XYZ registry object +% DIM - 3 vector of image X, Y & Z dimensions +% Finter - handle of Interactive window +% WS - WinScale [Default spm('WinScale') ] +% FS - FontSizes [Default spm('FontSizes')] +% +% FORMAT hFxyz = spm_results_ui('DrawXYZgui',M,DIM,xSPM,xyz,hReg) +% Setup editable XYZ control widgets at foot of Interactive window +% M - 4x4 transformation matrix relating voxel to ""real"" co-ordinates +% DIM - 3 vector of image X, Y & Z dimensions +% xSPM - structure containing SPM; Required fields are: +% .Z - minimum of n Statistics {filtered on u and k} +% .XYZmm - location of voxels {mm} +% xyz - Initial xyz location {mm} +% hReg - handle of XYZ registry object +% hFxyz - handle of XYZ control - the frame containing the edit widgets +% +% FORMAT spm_results_ui('EdWidCB') +% Callback for editable XYZ control widgets +% +% FORMAT spm_results_ui('UpdateSPMval',hFxyz) +% FORMAT spm_results_ui('UpdateSPMval',UD) +% Updates SPM value string in Results GUI (using data from UserData of hFxyz) +% hFxyz - handle of frame enclosing widgets - the Tag object for this control +% UD - XYZ data structure (UserData of hFxyz). +% +% FORMAT xyz = spm_results_ui('GetCoords',hFxyz) +% Get current co-ordinates from editable XYZ control +% hFxyz - handle of frame enclosing widgets - the Tag object for this control +% xyz - current co-ordinates {mm} +% NB: When using the results section, should use XYZregistry to get/set location +% +% FORMAT [xyz,d] = spm_results_ui('SetCoords',xyz,hFxyz,hC) +% Set co-ordinates to XYZ widget +% xyz - (Input) desired co-ordinates {mm} +% hFxyz - handle of XYZ control - the frame containing the edit widgets +% hC - handle of calling object, if used as a callback. [Default 0] +% xyz - (Output) Desired co-ordinates are rounded to nearest voxel if hC +% is not specified, or is zero. Otherwise, caller is assumed to +% have checked verity of desired xyz co-ordinates. Output xyz returns +% co-ordinates actually set {mm}. +% d - Euclidean distance between desired and set co-ordinates. +% NB: When using the results section, should use XYZregistry to get/set location +% +% FORMAT hFxyz = spm_results_ui('FindXYZframe',h) +% Find/check XYZ edit widgets frame handle, 'Tag'ged 'hFxyz' +% h - handle of frame enclosing widgets, or containing figure [default gcf] +% If ischar(h), then uses spm_figure('FindWin',h) to locate named figures +% hFxyz - handle of confirmed XYZ editable widgets control +% Errors if hFxyz is not an XYZ widget control, or a figure containing +% a unique such control +% +% FORMAT spm_results_ui('PlotUi',hAx) +% GUI for adjusting plot attributes - Sets up controls just above results GUI +% hAx - handle of axes to work with +% +% FORMAT spm_results_ui('PlotUiCB') +% CallBack handler for Plot attribute GUI +% +% FORMAT Fgraph = spm_results_ui('Clear',F,mode) +% Clears results subpane of Graphics window, deleting all but semi-permanent +% results section stuff +% F - handle of Graphics window [Default spm_figure('FindWin','Graphics')] +% mode - 1 [default] - clear results subpane +% - 0 - clear results subpane and hide results stuff +% - 2 - clear, but respect 'NextPlot' 'add' axes +% (which is set by `hold on`) +% Fgraph - handle of Graphics window +% +% FORMAT hMP = spm_results_ui('LaunchMP',M,DIM,hReg,hBmp) +% Prototype callback handler for integrating MultiPlanar toolbox +% +% FORMAT spm_results_ui('Delete',h) +% deletes HandleGraphics objects, but only if they're valid, thus avoiding +% warning statements from MATLAB. +%__________________________________________________________________________ +% +% modified version of +% spm_results_ui.m 7388 2018-08-06 + +%-Condition arguments +%-------------------------------------------------------------------------- +if nargin == 0, Action='Setup'; else Action=varargin{1}; end +useCAT = 2; % 0-like SPM, 1-surface handling, 2-cat_surf_renderer + +global cat_stat_spm_result_ui_varargout oldGraphicsRes; + +% get old figure rending settings +try + fg = spm_figure('FindWin','Graphics'); + + restext = char(fg.ExportsetupWindow.restext); + resstr = min(strfind( restext ,'selectedItemReminder')); + resstrend = resstr + [ min( strfind( restext(resstr:end),'=') ) , ... + min( [ strfind(restext(resstr:end),',') , ... + strfind(restext(resstr:end),']') ] - 1) ]; + if numel(resstrend)==2 + if exist('oldGraphicsRes','var') && isempty(oldGraphicsRes) + oldGraphicsRes = restext; %restext(resstrend(1):resstrend(2)-1); + end + restext = [restext(1:resstrend(1)-1) '75' restext(resstrend(2):end)]; + fg.ExportsetupWindow.restext = restext; + end +end + + +%========================================================================== +switch lower(Action), case 'setup' %-Set up results +%========================================================================== + + %-Initialise + %---------------------------------------------------------------------- + spm('FnBanner',mfilename); + try + dcm = datacursormode(spm_figure('FindWin','Graphics')); + set(dcm,'Enable','off','UpdateFcn',[]); + + spm_figure('Clear',spm_figure('FindWin','Graphics')); + end + [Finter,Fgraph,CmdLine] = spm('FnUIsetup','Stats: Results'); + spm_clf('Satellite'); + + %-Get thresholded xSPM data and parameters of design + %====================================================================== + if nargin > 1 + [SPM,xSPM] = spm_getSPM(varargin{2}); + else + [SPM,xSPM] = spm_getSPM; + end + + if isempty(xSPM) + varargout = {[],[],[]}; + return; + end + + %-Ensure pwd = swd so that relative filenames are valid + %---------------------------------------------------------------------- + cd(SPM.swd) + + %-Get space information + %====================================================================== + M = SPM.xVol.M; + DIM = SPM.xVol.DIM; + + %-Space units + %---------------------------------------------------------------------- + try + try + units = SPM.xVol.units; + catch + units = xSPM.units; + end + catch + try + Modality = spm('CheckModality'); + catch + Modality = {'PET','FMRI','EEG'}; + selected = spm_input('Modality: ','+1','m',Modality); + Modality = Modality{selected}; + spm('ChMod',Modality); + end + if strcmp(Modality,'EEG') + datatype = {... + 'Volumetric (2D/3D)',... + 'Scalp-Time',... + 'Scalp-Frequency',... + 'Time-Frequency',... + 'Frequency-Frequency'}; + selected = spm_input('Data Type: ','+1','m',datatype); + datatype = datatype{selected}; + else + datatype = 'Volumetric (2D/3D)'; + end + + switch datatype + case 'Volumetric (2D/3D)' + units = {'mm' 'mm' 'mm'}; + case 'Scalp-Time' + units = {'mm' 'mm' 'ms'}; + case 'Scalp-Frequency' + units = {'mm' 'mm' 'Hz'}; + case 'Time-Frequency' + units = {'Hz' 'ms' ''}; + case 'Frequency-Frequency' + units = {'Hz' 'Hz' ''}; + otherwise + error('Unknown data type.'); + end + end + +% CAT.begin +% ------------------------------------------------------------------------- +% ToDo: +% * add batch call with render settings > cat_conf_stools +% * add atlas data coursor > cat_surf_render +% * add colorbar > cat_surf_render +% * fix contrast box boundaries +% * full atlas integration > spm_atlas, spm_XYZreg, spm_list (lot of work) +% ------------------------------------------------------------------------- +if useCAT + [pp,ff,ee] = spm_fileparts(xSPM.Vspm.fname); + if strcmp(ee,'.gii') + datatype = 'Surface (3D)'; + % units = {'mm' 'mm'}; + end + + % change surface ? + % - first we have to use the Shooting Surface for the statistic to + % obtain more meaningful MNI coordinates + % - here we have to change to the used surface (FSaverage) + defsurf = 1; % 0-no change, 1-FS, 2-GS; + if defsurf + FSavg = '.freesurfer.gii'; + GSavg = '.Template_T1_IXI555_MNI152_GS.gii'; + SPM.xVol.G = strrep(SPM.xVol.G,GSavg,FSavg); + end + + % change coordinates to spherial ?? + %XYZmmFS = xSPM. + +end +% ------------------------------------------------------------------------- +% CAT.end + + if spm_mesh_detect(xSPM.Vspm) + DIM(3) = Inf; % force 3D coordinates + elseif DIM(3) == 1 + units{3} = ''; + if DIM(2) == 1 + units{2} = ''; + end + end + xSPM.units = units; + SPM.xVol.units = units; + + + %-Setup Results User Interface; Display MIP, design matrix & parameters + %====================================================================== + + %-Setup results GUI + %---------------------------------------------------------------------- + spm_clf(Finter); + spm('FigName',['SPM{',xSPM.STAT,'}: Results'],Finter,CmdLine); + hReg = cat_stat_spm_results_ui('SetupGUI',M,DIM,xSPM,Finter); + + %-Setup design interrogation menu + %---------------------------------------------------------------------- + hDesRepUI = spm_DesRep('DesRepUI',SPM); + + %-Setup contrast menu + %---------------------------------------------------------------------- + hConUI = cat_stat_spm_results_ui('SetupConMenu',xSPM,SPM,Finter); + + %-Atlas menu + %---------------------------------------------------------------------- + + +% CAT.begin +% ------------------------------------------------------------------------- +% Here we call an additional surface atlas setting ... + + if isequal(units,{'mm' 'mm' 'mm'}) + + if strcmp(datatype,'Surface (3D)') + %hAtlasUI = cat_stat_spm_results_ui('SetupSurfAtlasMenu',Finter,xSPM.Vspm); % RD202003 not working yet + else + hAtlasUI = cat_stat_spm_results_ui('SetupAtlasMenu',Finter); + end + end + +% ------------------------------------------------------------------------- +% CAT.end + + + %-Setup Maximum intensity projection (MIP) & register + %---------------------------------------------------------------------- + FS = spm('FontSizes'); + hMIPax = axes('Parent',Fgraph,'Position',[0.05 0.60 0.55 0.36],'Visible','off'); + if spm_mesh_detect(xSPM.Vspm) + + +% CAT.begin +% ------------------------------------------------------------------------- + % block to call cat_surf_render rather than spm_mesh_render + if useCAT>1 + hMax = cat_surf_render('Disp',SPM.xVol.G,'Parent',hMIPax,'Results',1); + tmp = zeros(1,prod(xSPM.DIM)); + tmp(xSPM.XYZ(1,:)) = xSPM.Z; + cat_surf_render('Colorbar'); + hMax = cat_surf_render('Overlay',hMax,tmp); + hMax = cat_surf_render('Register',hMax,hReg); + else + hMax = spm_mesh_render('Disp',SPM.xVol.G,'Parent',hMIPax); + tmp = zeros(1,prod(xSPM.DIM)); + tmp(xSPM.XYZ(1,:)) = xSPM.Z; + hMax = spm_mesh_render('Overlay',hMax,tmp); + hMax = spm_mesh_render('Register',hMax,hReg); + end +% ------------------------------------------------------------------------- +% CAT.end + + + elseif isequal(units(2:3),{'' ''}) + set(hMIPax, 'Position',[0.05 0.65 0.55 0.25]); + [allS,allXYZmm] = spm_read_vols(xSPM.Vspm); + plot(hMIPax,allXYZmm(1,:),allS,'Color',[0.6 0.6 0.6]); + set(hMIPax,'NextPlot','add'); + MIP = NaN(1,xSPM.DIM(1)); + MIP(xSPM.XYZ(1,:)) = xSPM.Z; + XYZmm = xSPM.M(1,:)*[1:xSPM.DIM(1);zeros(2,xSPM.DIM(1));ones(1,xSPM.DIM(1))]; + plot(hMIPax,XYZmm,MIP,'b-+','LineWidth',2); + plot(hMIPax,[XYZmm(1) XYZmm(end)],[xSPM.u xSPM.u],'r'); + clim = get(hMIPax,'YLim'); + axis(hMIPax,[sort([XYZmm(1) XYZmm(end)]) 0 clim(2)]); + %set(hMIPax,'XTick',[],'YTick',[]); + else + hMIPax = spm_mip_ui(xSPM.Z,xSPM.XYZmm,M,DIM,hMIPax,units); + spm_XYZreg('XReg',hReg,hMIPax,'spm_mip_ui'); + end + + if xSPM.STAT == 'P' + str = xSPM.STATstr; + else + str = ['SPM\{',xSPM.STATstr,'\}']; + end + text(240,260,str,... + 'Interpreter','TeX',... + 'FontSize',FS(14),'Fontweight','Bold',... + 'Parent',hMIPax) + + + %-Print comparison title + %---------------------------------------------------------------------- + hTitAx = axes('Parent',Fgraph,... + 'Position',[0.02 0.96 0.96 0.04],... + 'Visible','off'); + + text(0.5,0.5,xSPM.title,'Parent',hTitAx,... + 'HorizontalAlignment','center',... + 'VerticalAlignment','top',... + 'FontWeight','Bold','FontSize',FS(14)) + + + %-Print SPMresults: Results directory & thresholding info + %---------------------------------------------------------------------- + hResAx = axes('Parent',Fgraph,... + 'Position',[0.05 0.55 0.45 0.05],... + 'DefaultTextVerticalAlignment','baseline',... + 'DefaultTextFontSize',FS(9),... + 'DefaultTextColor',[1,1,1]*.7,... + 'Units','points',... + 'Visible','off'); + AxPos = get(hResAx,'Position'); set(hResAx,'YLim',[0,AxPos(4)]) + h = text(0,24,'SPMresults:','Parent',hResAx,... + 'FontWeight','Bold','FontSize',FS(14)); + text(get(h,'Extent')*[0;0;1;0],24,spm_file(SPM.swd,'short30'),'Parent',hResAx) + try + thresDesc = xSPM.thresDesc; + if strcmp(xSPM.STAT,'P') + text(0,12,sprintf('Height threshold %s',thresDesc),'Parent',hResAx) + else + text(0,12,sprintf('Height threshold %c = %0.6f {%s}',xSPM.STAT,xSPM.u,thresDesc),'Parent',hResAx) + end + catch + text(0,12,sprintf('Height threshold %c = %0.6f',xSPM.STAT,xSPM.u),'Parent',hResAx) + end + if spm_mesh_detect(xSPM.Vspm), str = 'vertices'; else str = 'voxels'; end + text(0,00,sprintf('Extent threshold k = %0.0f %s',xSPM.k,str), 'Parent',hResAx) + + + %-Plot design matrix + %---------------------------------------------------------------------- + hDesMtx = axes('Parent',Fgraph,'Position',[0.65 0.55 0.25 0.25]); + hDesMtxIm = image((SPM.xX.nKX + 1)*32,'Parent',hDesMtx); + xlabel(hDesMtx,'Design matrix','FontSize',FS(10)) + set(hDesMtxIm,'ButtonDownFcn','spm_DesRep(''SurfDesMtx_CB'')',... + 'UserData',struct(... + 'X', SPM.xX.xKXs.X,... + 'fnames', {reshape({SPM.xY.VY.fname},size(SPM.xY.VY))},... + 'Xnames', {SPM.xX.name})) + + %-Plot contrasts + %---------------------------------------------------------------------- + nPar = size(SPM.xX.X,2); + xx = [repmat([0:nPar-1],2,1);repmat([1:nPar],2,1)]; + nCon = length(xSPM.Ic); + xCon = SPM.xCon; + if nCon + dy = 0.15/max(nCon,2); + hConAx = axes('Parent',Fgraph, 'Position',[0.65 (0.80 + dy*.1) 0.25 dy*(nCon-.1)],... + 'Tag','ConGrphAx','Visible','off'); + str = 'contrast'; + if nCon > 1, str = [str 's']; end + title(hConAx,str) + htxt = get(hConAx,'title'); + set(htxt,'FontSize',FS(10),'FontWeight','normal','Visible','on','HandleVisibility','on') + end + + for ii = nCon:-1:1 + hCon = axes('Parent',Fgraph, 'Position',[0.65 (0.80 + dy*(nCon - ii +.1)) 0.25 dy*.9]); + if xCon(xSPM.Ic(ii)).STAT == 'T' && size(xCon(xSPM.Ic(ii)).c,2) == 1 + + %-Single vector contrast for SPM{t} - bar + %-------------------------------------------------------------- + yy = [zeros(1,nPar);repmat(xCon(xSPM.Ic(ii)).c',2,1);zeros(1,nPar)]; + h = patch(xx,yy,[1,1,1]*.5,'Parent',hCon); + set(hCon,'Tag','ConGrphAx',... + 'Box','off','TickDir','out',... + 'XTick',spm_DesRep('ScanTick',nPar,10) - 0.5,'XTickLabel','',... + 'XLim', [0,nPar],... + 'YTick',[-1,0,+1],'YTickLabel','',... + 'YLim',[min(xCon(xSPM.Ic(ii)).c),max(xCon(xSPM.Ic(ii)).c)] +... + [-1 +1] * max(abs(xCon(xSPM.Ic(ii)).c))/10 ) + + else + + %-F-contrast - image + %-------------------------------------------------------------- + h = image((xCon(xSPM.Ic(ii)).c'/max(abs(xCon(xSPM.Ic(ii)).c(:)))+1)*32,... + 'Parent',hCon); + set(hCon,'Tag','ConGrphAx',... + 'Box','on','TickDir','out',... + 'XTick',spm_DesRep('ScanTick',nPar,10),'XTickLabel','',... + 'XLim', [0,nPar]+0.5,... + 'YTick',[0:size(SPM.xCon(xSPM.Ic(ii)).c,2)]+0.5,... + 'YTickLabel','',... + 'YLim', [0,size(xCon(xSPM.Ic(ii)).c,2)]+0.5 ) + + end + ylabel(hCon,num2str(xSPM.Ic(ii)),'FontSize',FS(10),'FontWeight','normal') + set(h,'ButtonDownFcn','spm_DesRep(''SurfCon_CB'')',... + 'UserData', struct( 'i', xSPM.Ic(ii),... + 'h', htxt,... + 'xCon', xCon(xSPM.Ic(ii)))) + end + + + %-Store handles of results section Graphics window objects + %---------------------------------------------------------------------- + H = get(Fgraph,'Children'); + H = findobj(H,'flat','HandleVisibility','on'); + H = findobj(H); + Hv = get(H,'Visible'); + set(hResAx,'Tag','PermRes','UserData',struct('H',H,'Hv',{Hv})) + + %-Finished results setup + %---------------------------------------------------------------------- + varargout = {hReg,xSPM,SPM}; + spm('Pointer','Arrow') + + + +% CAT.begin +% ------------------------------------------------------------------------- +% This block is required for postprocessing the SPM result figure. +% It include fixes to avoid rotation of non 3D elements and some other tiny +% changes to the contrast & design matrix. + + % create SPM result table and fix elements to avoid rotation of tables + spm_list('List',xSPM,hReg); + spm_list_cleanup; %(hReg); + + % corrections for top elements + hRes.Fgraph = spm_figure('GetWin','Graphics'); + hRes.FgraphC = get( hRes.Fgraph ,'children'); + hRes.FgraphAx = findobj( hRes.FgraphC,'Type','Axes'); + hRes.FgraphAxPos = cell2mat(get( hRes.FgraphAx , 'Position')); + hRes.Ftext = findobj(hRes.Fgraph,'Type','Text'); + % fine red lines of the SPM result table + hRes.Fline = findobj(hRes.Fgraph,'Type','Line','Tag','');% ,'UIcontextMenu',[]); + hRes.FlineAx = get(hRes.Fline,'parent'); + + % find the SPM result texts to fix them against rotation + hres.Ftext = findobj(hRes.Fgraph,'Type','Text','Color',[0.7 0.7 0.7]); + hRes.Ftext3dres = get( hres.Ftext ,'parent'); + % for axi=1:numel(hRes.Ftext), set( hRes.Ftext(axi),'Color',[0.2 0.2 0.2]); end + for axi = 1:numel(hRes.Ftext3dres), set( hRes.Ftext3dres{axi},'HitTest','off'); end + for axi = 1:numel(hRes.FlineAx ), set( hRes.FlineAx{axi},'visible','off'); end + + % make nice contrast box that is a bit larger than the orinal boxes + hRes.Fcons = hRes.FgraphAx( hRes.FgraphAxPos(:,1) == 0.65 & hRes.FgraphAxPos(:,2) > 0.6 ) ; + for axi = 1:numel( hRes.Fcons ), l = get( hRes.Fcons(axi) , 'ylim'); set(hRes.Fcons(axi) , 'box','on','ylim', round(l) + [-0.015 0.015]); end + + % remove non integer values + hRes.Fdesm = hRes.FgraphAx( hRes.FgraphAxPos(:,1) == 0.65 & hRes.FgraphAxPos(:,2) < 0.6 ) ; + xt = get(hRes.Fdesm,'xtick'); xt(round(xt)~=xt) = []; set(hRes.Fdesm,'xtick',xt); + + % + hRes.Fval = hRes.FgraphAx( hRes.FgraphAxPos(:,1) > 10); + hRes.Fsurf = hRes.FgraphAx( hRes.FgraphAxPos(:,1) == 0.05); + hRes.Flabels = [ hRes.FgraphAx( hRes.FgraphAxPos(:,1) == 0.65); hRes.FgraphAx( hRes.FgraphAxPos(:,1) == 0.02)]; + for axi = 1:numel( hRes.Flabels ), set(hRes.Flabels(axi),'HitTest','off'); end + + if nargout==0, + cat_io_cprintf('err', sprintf( ... + ['\n' ... + '========================================================================\n' ... + ' You have to call [cat_stat_]spm_results_ui with all output parameters: \n' ... + ' [hReg,xSPM,SPM] = cat_stat_spm_results_ui; \n\n' ... + ' Otherwise, the menu and tables will not work probalby! Call now: \n %s\n'... + '========================================================================\n\n'], ... + spm_file('[hReg,xSPM,SPM] = cat_stat_spm_results_ui(''Output'');',... + 'link','[hReg,xSPM,SPM] = cat_stat_spm_results_ui(''Output'');'))); + + cat_stat_spm_result_ui_varargout = varargout; + clear varargout; + end +% ------------------------------------------------------------------------- +% CAT.end + + %====================================================================== + case 'output' %-Set up results section GUI + %====================================================================== + fprintf('Updated cat_stat_spm_result_ui output.\n'); + varargout = cat_stat_spm_result_ui_varargout; + + %====================================================================== + case 'setupgui' %-Set up results section GUI + %====================================================================== + % hReg = spm_results_ui('SetupGUI',M,DIM,xSPM,Finter) + if nargin < 5, Finter='Interactive'; else Finter = varargin{5}; end + if nargin < 4, error('Insufficient arguments'), end + M = varargin{2}; + DIM = varargin{3}; + Finter = spm_figure('GetWin',Finter); + WS = spm('WinScale'); + FS = spm('FontSizes'); + + %-Create frame for Results GUI objects + %------------------------------------------------------------------ + hPan = uipanel('Parent',Finter,'Title','','Units','Pixels',... + 'Position',[001 001 400 190].*WS,... + 'BorderType','Line', 'HighlightColor',[0 0 0],... + 'BackgroundColor',spm('Colour')); + hReg = uipanel('Parent',hPan,'Title','','Units','Pixels',... + 'BorderType','Etchedin', ... + 'Position',[005 005 390 180].*WS,... + 'BackgroundColor',[179 179 179]/255); + + %-Initialise registry in hReg frame object + %------------------------------------------------------------------ + [hReg,xyz] = spm_XYZreg('InitReg',hReg,M,DIM,[0;0;0]); + + %-Setup editable XYZ widgets & cross register with registry + %------------------------------------------------------------------ + hFxyz = cat_stat_spm_results_ui('DrawXYZgui',M,DIM,varargin{4},xyz,hReg); + spm_XYZreg('XReg',hReg,hFxyz,'spm_results_ui'); + + %-Set up buttons for results functions + %------------------------------------------------------------------ + cat_stat_spm_results_ui('DrawButts',hReg,DIM,Finter,WS,FS); + + if spm_check_version('matlab','7.11') ~= 0 + drawnow; % required to force ""ratio locking"" + set(findobj(hPan),'Units','Normalized','FontUnits','Normalized'); + end + + varargout = {hReg}; + + %====================================================================== + case 'drawbutts' %-Draw results section buttons in Interactive window + %====================================================================== + % spm_results_ui('DrawButts',hReg,DIM,Finter,WS,FS) + % + if nargin < 3, error('Insufficient arguments'), end + hReg = varargin{2}; + DIM = varargin{3}; + if nargin < 4, Finter = spm_figure('FindWin','Interactive'); + else Finter = varargin{4}; end + if nargin < 5, WS = spm('WinScale'); else WS = varargin{5}; end + if nargin < 6, FS = spm('FontSizes'); else FS = varargin{6}; end + + %-p-values + %------------------------------------------------------------------ + hPan = uipanel('Parent',hReg,'Title','p-values','Units','Pixels',... + 'Position',[005 085 110 092].*WS,... + 'BorderType','Beveledout', ... + 'ShadowColor',[0.5 0.5 0.5],... + 'FontAngle','Italic',... + 'FontSize',FS(10),... + 'ForegroundColor',[1 1 1],... + 'BackgroundColor',[179 179 179]/255); + uicontrol('Parent',hPan,'Style','PushButton','String','whole brain',... + 'Units','Pixels',... + 'FontSize',FS(10),... + 'ToolTipString',... + 'Tabulate summary of local maxima, p-values & statistics',... + 'Callback','TabDat = spm_list(''List'',xSPM,hReg); cat_stat_spm_results_ui(''spm_list_cleanup'',hReg);',... + 'Interruptible','on','Enable','on',... + 'Position',[005 055 100 020].*WS); + uicontrol('Parent',hPan,'Style','PushButton','String','current cluster',... + 'Units','Pixels',... + 'FontSize',FS(10),... + 'ToolTipString',... + 'Tabulate p-values & statistics for local maxima of nearest cluster',... + 'Callback','TabDat = spm_list(''ListCluster'',xSPM,hReg); cat_stat_spm_results_ui(''spm_list_cleanup'',hReg);',... + ...'Interruptible','on','Enable','on',... % CAT: RD202003: spm_list error - not in mesh yet + 'Interruptible','off','Enable','off',... % CAT: RD202003: spm_list error - not in mesh yet + 'Position',[005 030 100 020].*WS); + uicontrol('Parent',hPan,'Style','PushButton','String','small volume',... + 'Units','Pixels',... + 'FontSize',FS(10),... + 'ToolTipString',['Small Volume Correction - corrected p-values ',... + 'for a small search region'],... + 'Callback','TabDat = spm_VOI(SPM,xSPM,hReg);',... + ...'Interruptible','on','Enable','on',... % CAT: RD202003: spm_read_vols error - no mesh function + 'Interruptible','off','Enable','off',... % CAT: RD202003: spm_read_vols error - no mesh function + 'Position',[005 005 100 020].*WS); + + + %-SPM area - used for Volume of Interest analyses + %------------------------------------------------------------------ + hPan = uipanel('Parent',hReg,'Title','Multivariate','Units','Pixels',... + 'Position',[120 085 150 092].*WS,... + 'BorderType','Beveledout', ... + 'ShadowColor',[0.5 0.5 0.5],... + 'FontAngle','Italic',... + 'FontSize',FS(10),... + 'ForegroundColor',[1 1 1],... + 'BackgroundColor',[179 179 179]/255); + uicontrol('Parent',hPan,'Style','PushButton','String','eigenvariate',... + 'Position',[005 055 069 020].*WS,... + 'ToolTipString',... + 'Responses (principal eigenvariate) in volume of interest',... + 'Callback','[Y,xY] = spm_regions(xSPM,SPM,hReg)',... + 'Interruptible','on','Enable','on',... + 'FontSize',FS(10)); + uicontrol('Parent',hPan,'Style','PushButton','String','CVA',... + 'Position',[076 055 069 020].*WS,... + 'ToolTipString',... + 'Canonical variates analysis for the current contrast and VOI',... + 'Callback','CVA = spm_cva_ui('''',xSPM,SPM)',... + ...'Interruptible','on','Enable','on',... % CAT: RD202003: not prepared yet + 'Interruptible','off','Enable','off',... % CAT: RD202003: not prepared yet + 'FontSize',FS(10)); + uicontrol('Parent',hPan,'Style','PushButton','String','multivariate Bayes',... + 'Position',[005 030 140 020].*WS,... + 'ToolTipString',... + 'Multivariate Bayes',... + 'Callback','[MVB] = spm_mvb_ui(xSPM,SPM)',... + ...'Interruptible','on','Enable','on',... % CAT: RD202003: not prepared yet + 'Interruptible','off','Enable','off',... % CAT: RD202003: not prepared yet + 'FontSize',FS(10)); + uicontrol('Parent',hPan,'Style','PushButton','String','BMS',... + 'Position',[005 005 069 020].*WS,... + 'ToolTipString',... + 'Compare or review a multivariate Bayesian model',... + 'Callback','[F,P] = spm_mvb_bmc',... + ...'Interruptible','on','Enable','on',... % CAT: RD202003: not prepared yet + 'Interruptible','off','Enable','off',... % CAT: RD202003: not prepared yet + 'FontSize',FS(8),'ForegroundColor',[1 1 1]/3); + uicontrol('Parent',hPan,'Style','PushButton','String','p-value',... + 'Position',[076 005 069 020].*WS,... + 'ToolTipString',... + 'Randomisation testing of a multivariate Bayesian model',... + 'Callback','spm_mvb_p',... + ...'Interruptible','on','Enable','on',... % CAT: RD202003: not prepared yet + 'Interruptible','off','Enable','off',... % CAT: RD202003: not prepared yet + 'FontSize',FS(8),'ForegroundColor',[1 1 1]/3); + + %-Hemodynamic modelling + %------------------------------------------------------------------ + if strcmp(spm('CheckModality'),'FMRI') + uicontrol('Parent',hReg,'Style','PushButton','String','Hemodynamics',... + 'FontSize',FS(10),... + 'ToolTipString','Hemodynamic modelling of regional response',... + 'Callback','[Ep,Cp,K1,K2] = spm_hdm_ui(xSPM,SPM,hReg);',... + ...'Interruptible','on','Enable','on',... % CAT: RD202003: not prepared yet + 'Interruptible','off','Enable','off',... % CAT: RD202003: not prepared yet + 'Position',[125 050 140 020].*WS,... + 'ForegroundColor',[1 1 1]/3); + end + + %-Not currently used + %------------------------------------------------------------------ + %uicontrol('Parent',hReg,'Style','PushButton','String','',... + % 'FontSize',FS(10),... + % 'ToolTipString','',... + % 'Callback','',... + % 'Interruptible','on','Enable','on',... + % 'Position',[010 050 100 020].*WS); + + %-Visualisation + %------------------------------------------------------------------ + hPan = uipanel('Parent',hReg,'Title','Display','Units','Pixels',... + 'Position',[275 085 110 092].*WS,... + 'BorderType','Beveledout',... + 'ShadowColor',[0.5 0.5 0.5],... + 'FontAngle','Italic',... + 'FontSize',FS(10),... + 'ForegroundColor',[1 1 1],... + 'BackgroundColor',[179 179 179]/255); + uicontrol('Parent',hPan,'Style','PushButton','String','plot',... + 'FontSize',FS(10),... + 'ToolTipString','plot data & contrasts at current voxel',... + 'Callback','[Y,y,beta,Bcov] = spm_graph_ui(xSPM,SPM,hReg);',... + 'Interruptible','on','Enable','on',... + 'Position',[005 055 100 020].*WS,... + 'Tag','plotButton'); + + str = {'overlays...',... + ...'slices', ... % CAT: RD202003 - no working + 'sections', ... + 'CAT T1 IXI555 GS', ... + ... 'montage',... % CAT: RD202003 - working but not useful for surfaces + 'render',... % CAT: RD202003 - working but not useful for surfaces? + 'previous sections',... + 'previous render'}; + tstr = { 'overlay filtered SPM on another image: ',... + ...'3 slices / ',... + 'slice overlay /', ... + 'T1 avg slice overlay /', ... + ... 'ortho sections / ', ... + 'render /', ... + 'previous ortho sections /', ... + 'previous surface rendering'}; + + tmp = { ... 'spm_transverse(''set'',xSPM,hReg)',... + ['spm_sections(xSPM,hReg);','spm_orthviews(''RemoveBlobs'',1);'],... % CAT RD202003 - remove blobs colorbar + ['spm_sections(xSPM,hReg,fullfile(spm(''dir''),''toolbox'',''cat12'','... + '''templates_volumes'',''Template_T1_IXI555_MNI152_GS.nii''));',... + 'spm_orthviews(''RemoveBlobs'',1);', ... + ...'cat_stat_spm_results_ui(''spm_list_cleanup'');',... + ],... % CAT RD202003 - add T1 avg + ....{@myslover},... + ['spm_render( struct( ''XYZ'', xSPM.XYZ,',... + '''t'', xSPM.Z'',',... + '''mat'', xSPM.M,',... + '''dim'', xSPM.DIM))'],... + ['global prevsect;','spm_sections(xSPM,hReg,prevsect);','spm_orthviews(''RemoveBlobs'',1);'],... + ['global prevrend;','if ~isstruct(prevrend)',... + 'prevrend = struct(''rendfile'','''',''brt'',[],''col'',[]); end;',... + 'spm_render( struct( ''XYZ'', xSPM.XYZ,',... + '''t'', xSPM.Z'',',... + '''mat'', xSPM.M,',... + '''dim'', xSPM.DIM),prevrend.brt,prevrend.rendfile)']}; + + uicontrol('Parent',hPan,'Style','popupmenu','String',str,... + 'FontSize',FS(10),... + 'ToolTipString',cat(2,tstr{:}),... + 'Callback','spm(''PopUpCB'',gcbo)',... + 'UserData',tmp,... + 'Interruptible','on','Enable','on',... + 'Position',[005 030 100 020].*WS); + + str = {'save...',... + 'thresholded SPM',... + 'all clusters (binary)',... + 'all clusters (n-ary)',... + 'current cluster'}; + tmp = {{@mysavespm, 'thresh' },... + {@mysavespm, 'binary' },... + {@mysavespm, 'n-ary' },... + {@mysavespm, 'current'}}; + + uicontrol('Parent',hPan,'Style','popupmenu','String',str,... + 'FontSize',FS(10),... + 'ToolTipString','Save as image',... + 'Callback','spm(''PopUpCB'',gcbo)',... + 'UserData',tmp,... + 'Interruptible','on','Enable','on',... + 'Position',[005 005 100 020].*WS); + + %-ResultsUI controls + %------------------------------------------------------------------ + uicontrol('Parent',hReg,'Style','PushButton','String','clear',... + 'ToolTipString','Clear results subpane',... + 'FontSize',FS(9),'ForegroundColor','b',... + 'Callback',['spm_results_ui(''Clear''); ',... + 'spm_input(''!DeleteInputObj''),',... + 'spm_clf(''Satellite'')'],... + 'Interruptible','on','Enable','on',... + 'DeleteFcn','spm_clf(''Graphics'')',... + 'Position',[280 050 048 020].*WS); + + uicontrol('Parent',hReg,'Style','PushButton','String','exit',... + 'ToolTipString','Exit the results section',... + 'FontSize',FS(9),'ForegroundColor','r',... + 'Callback','spm_results_ui(''close'')',... + 'Interruptible','on','Enable','on',... + 'Position',[332 050 048 020].*WS); + + + %====================================================================== + case 'setupconmenu' %-Setup Contrast Menu + %====================================================================== + % spm_results_ui('SetupConMenu',xSPM,SPM,Finter) + if nargin < 4, Finter = 'Interactive'; else Finter = varargin{4}; end + if nargin < 3, error('Insufficient arguments'), end + xSPM = varargin{2}; + SPM = varargin{3}; + Finter = spm_figure('GetWin',Finter); + hC = uimenu(Finter,'Label','Contrasts', 'Tag','ContrastsUI'); + hC1 = uimenu(hC,'Label','New Contrast...',... + 'UserData',struct('Ic',0),... + 'Callback',{@mychgcon,xSPM}); + hC1 = uimenu(hC,'Label','Change Contrast'); + for i=1:numel(SPM.xCon) + hC2 = uimenu(hC1,'Label',[SPM.xCon(i).STAT, ': ', SPM.xCon(i).name], ... + 'UserData',struct('Ic',i),... + 'Callback',{@mychgcon,xSPM}); + if any(xSPM.Ic == i) + set(hC2,'ForegroundColor',[0 0 1],'Checked','on'); + end + end + hC1 = uimenu(hC,'Label','Previous Contrast',... + 'Accelerator','P',... + 'UserData',struct('Ic',xSPM.Ic-1),... + 'Callback',{@mychgcon,xSPM}); + if xSPM.Ic-1<1, set(hC1,'Enable','off'); end + hC1 = uimenu(hC,'Label','Next Contrast',... + 'Accelerator','N',... + 'UserData',struct('Ic',xSPM.Ic+1),... + 'Callback',{@mychgcon,xSPM}); + if xSPM.Ic+1>numel(SPM.xCon), set(hC1,'Enable','off'); end + hC1 = uimenu(hC,'Label','Significance level','Separator','on'); + xSPMtmp = xSPM; xSPMtmp.thresDesc = ''; + uimenu(hC1,'Label','Change...','UserData',struct('Ic',xSPM.Ic),... + 'Callback',{@mychgcon,xSPMtmp}); + + if strcmp(xSPM.STAT,'P') + xSPMtmp = xSPM; xSPMtmp.thresDesc = 'LogBF'; + uimenu(hC1,'Label','Set LogBF','UserData',struct('Ic',xSPM.Ic),... + 'Callback',{@mychgcon,xSPMtmp}); + else + xSPMtmp = xSPM; xSPMtmp.thresDesc = 'p<0.05 (FWE)'; + uimenu(hC1,'Label','Set to 0.05 (FWE)','UserData',struct('Ic',xSPM.Ic),... + 'Callback',{@mychgcon,xSPMtmp}); + xSPMtmp = xSPM; xSPMtmp.thresDesc = 'p<0.001 (unc.)'; + uimenu(hC1,'Label','Set to 0.001 (unc.)','UserData',struct('Ic',xSPM.Ic),... + 'Callback',{@mychgcon,xSPMtmp}); + end + + uimenu(hC1,'Label',[xSPM.thresDesc ', k=' num2str(xSPM.k)],... + 'Enable','off','Separator','on'); + + hC1 = uimenu(hC,'Label','Multiple display...',... + 'Separator','on',... + 'Callback',{@mycheckres,xSPM}); + + varargout = {hC}; + + + %====================================================================== + case 'setupatlasmenu' %-Setup Atlas Menu + %====================================================================== + % spm_results_ui('SetupAtlasMenu',Finter) + + Finter = varargin{2}; + + %hC = uicontextmenu; + hC = uimenu(Finter,'Label','Atlas', 'Tag','AtlasUI'); + + hC1 = uimenu(hC,'Label','Label using'); + + list = spm_atlas('List','installed'); + for i=1:numel(list) + uimenu(hC1,'Label',list(i).name,... + 'Callback',sprintf('spm_list(''label'',''%s''); cat_stat_spm_results_ui(''spm_list_cleanup'');',list(i).name)); + end + if isempty(list), set(hC1,'Enable','off'); end + + %hC2 = uimenu(hC,'Label','Download Atlas...',... + % 'Separator','on',... + % 'Callback','spm_atlas(''install'');'); + + varargout = {hC}; + + + %====================================================================== + case 'spm_list_cleanup' + %====================================================================== + % cat_stat_spm_results_ui('spm_list_cleanup',hReg) + if nargin>1 + spm_list_cleanup(varargin{2}); + else + spm_list_cleanup + end + + + %====================================================================== + case 'setupsurfatlasmenu' %-Setup Atlas Menu + %====================================================================== + % spm_results_ui('SetupSurfAtlasMenu',Finter) + % RD202003 NOT WORKING YET + % requires update of spm_list('label',atlas) and spm_atlas + + Finter = varargin{2}; + Vspm = varargin{3}; + + %hC = uicontextmenu; + hC = uimenu(Finter,'Label','Atlas', 'Tag','AtlasUI'); + + hC1 = uimenu(hC,'Label','Label using'); + + %% + satlases = cat_get_defaults('extopts.satlas'); + expert = cat_get_defaults('extopts.expertgui'); + listi = 1; + for si = 1:size(satlases,1) + [pp,ff,ee] = spm_fileparts(satlases{si,1}); + if expert >= satlases{si,3} + list(listi) = struct('file',satlases{si,2},'name',satlases{si,1}); + list(listi).file = strrep(list(listi).file,'lh.','mesh.'); + if Vspm.dim(1) == 64984 + list(listi).file = strrep(list(listi).file,'atlases_surfaces','atlases_surfaces_32k'); + end + listi = listi + 1; + end + end + for i=1:numel(list) + uimenu(hC1,'Label',list(i).name,... + 'Callback',sprintf('spm_list(''label'',''%s''); cat_stat_spm_results_ui(''spm_list_cleanup''); ',list(i).name)); + end + if isempty(list), set(hC1,'Enable','off'); end + + %hC2 = uimenu(hC,'Label','Download Atlas...',... + % 'Separator','on',... + % 'Callback','spm_atlas(''install'');'); + + varargout = {hC}; + + + %====================================================================== + case 'drawxyzgui' %-Draw XYZ GUI area + %====================================================================== + % hFxyz = spm_results_ui('DrawXYZgui',M,DIM,xSPM,xyz,hReg) + if nargin<6, hReg=spm_XYZreg('FindReg','Interactive'); + else hReg=varargin{6}; end + if nargin < 5, xyz=[0;0;0]; else xyz=varargin{5}; end + if nargin < 4, error('Insufficient arguments'), end + DIM = varargin{3}; + M = varargin{2}; + xyz = spm_XYZreg('RoundCoords',xyz,M,DIM); + + %-Font details + %------------------------------------------------------------------ + WS = spm('WinScale'); + FS = spm('FontSizes'); + PF = spm_platform('fonts'); + + %-Create XYZ control objects + %------------------------------------------------------------------ + hFxyz = uipanel('Parent',hReg,'Title','co-ordinates','Units','Pixels',... + 'Position',[005 005 265 040].*WS,... + 'BorderType','Beveledout',... + 'ShadowColor',[0.5 0.5 0.5],... + 'FontAngle','Italic',... + 'FontSize',FS(10),... + 'ForegroundColor',[1 1 1],... + 'BackgroundColor',[179 179 179]/255); + + uicontrol('Parent',hReg,'Style','Text','String','x =',... + 'Position',[015 010 024 018].*WS,... + 'FontName',PF.times,'FontSize',FS(10),'FontAngle','Italic',... + 'HorizontalAlignment','Center'); + hX = uicontrol('Parent',hReg,'Style','Edit','String',sprintf('%.2f',xyz(1)),... + 'ToolTipString','enter x-coordinate',... + 'Position',[039 010 056 020].*WS,... + 'FontSize',FS(10),'BackGroundColor',[.8,.8,1],... + 'HorizontalAlignment','Right',... + 'Tag','hX',... + 'Callback','spm_results_ui(''EdWidCB'')'); + + uicontrol('Parent',hReg,'Style','Text','String','y =',... + 'Position',[100 010 024 018].*WS,... + 'FontName',PF.times,'FontSize',FS(10),'FontAngle','Italic',... + 'HorizontalAlignment','Center'); + hY = uicontrol('Parent',hReg,'Style','Edit','String',sprintf('%.2f',xyz(2)),... + 'ToolTipString','enter y-coordinate',... + 'Position',[124 010 056 020].*WS,... + 'FontSize',FS(10),'BackGroundColor',[.8,.8,1],... + 'HorizontalAlignment','Right',... + 'Tag','hY',... + 'Callback','spm_results_ui(''EdWidCB'')'); + + if DIM(3) ~= 1 + uicontrol('Parent',hReg,'Style','Text','String','z =',... + 'Position',[185 010 024 018].*WS,... + 'FontName',PF.times,'FontSize',FS(10),'FontAngle','Italic',... + 'HorizontalAlignment','Center'); + hZ = uicontrol('Parent',hReg,'Style','Edit','String',sprintf('%.2f',xyz(3)),... + 'ToolTipString','enter z-coordinate',... + 'Position',[209 010 056 020].*WS,... + 'FontSize',FS(10),'BackGroundColor',[.8,.8,1],... + 'HorizontalAlignment','Right',... + 'Tag','hZ',... + 'Callback','spm_results_ui(''EdWidCB'')'); + else + hZ = []; + end + + %-Statistic value reporting pane + %------------------------------------------------------------------ + hPan = uipanel('Parent',hReg,'Title','statistic','Units','Pixels',... + 'Position',[275 005 110 040].*WS,... + 'BorderType','Beveledout', ... + 'ShadowColor',[0.5 0.5 0.5],... + 'FontAngle','Italic',... + 'FontSize',FS(10),... + 'ForegroundColor',[1 1 1],... + 'BackgroundColor',[179 179 179]/255); + hSPM = uicontrol('Parent',hPan,'Style','Text','String','',... + 'Position',[005 001 100 020].*WS,... + 'FontSize',FS(10),... + 'HorizontalAlignment','Center'); + + + %-Store data + %------------------------------------------------------------------ + set(hFxyz,'Tag','hFxyz','UserData',struct(... + 'hReg', [],... + 'M', M,... + 'DIM', DIM,... + 'XYZ', varargin{4}.XYZmm,... + 'Z', varargin{4}.Z,... + 'hX', hX,... + 'hY', hY,... + 'hZ', hZ,... + 'hSPM', hSPM,... + 'xyz', xyz )); + + set([hX,hY,hZ],'UserData',hFxyz) + varargout = {hFxyz}; + + + %====================================================================== + case 'edwidcb' %-Callback for editable widgets + %====================================================================== + % spm_results_ui('EdWidCB') + + hC = gcbo; + d = find(strcmp(get(hC,'Tag'),{'hX','hY','hZ'})); + hFxyz = get(hC,'UserData'); + UD = get(hFxyz,'UserData'); + xyz = UD.xyz; + nxyz = xyz; + + o = evalin('base',['[',get(hC,'String'),']'],'sprintf(''error'')'); + if ischar(o) || length(o)>1 + warning(sprintf('%s: Error evaluating ordinate:\n\t%s',... + mfilename,lasterr)) + else + nxyz(d) = o; + nxyz = spm_XYZreg('RoundCoords',nxyz,UD.M,UD.DIM); + end + + if abs(xyz(d)-nxyz(d))>0 + UD.xyz = nxyz; set(hFxyz,'UserData',UD) + if ~isempty(UD.hReg), spm_XYZreg('SetCoords',nxyz,UD.hReg,hFxyz); end + set(hC,'String',sprintf('%.3f',nxyz(d))) + cat_stat_spm_results_ui('UpdateSPMval',UD) + end + + + %====================================================================== + case 'updatespmval' %-Update SPM value in GUI + %====================================================================== + % spm_results_ui('UpdateSPMval',hFxyz) + % spm_results_ui('UpdateSPMval',UD) + if nargin<2, error('insufficient arguments'), end + if isstruct(varargin{2}), UD=varargin{2}; else UD = get(varargin{2},'UserData'); end + i = spm_XYZreg('FindXYZ',UD.xyz,UD.XYZ); + if isempty(i), str = ''; else str = sprintf('%6.2f',UD.Z(i)); end + set(UD.hSPM,'String',str); + + + %====================================================================== + case 'getcoords' % Get current co-ordinates from XYZ widget + %====================================================================== + % xyz = spm_results_ui('GetCoords',hFxyz) + if nargin<2, hFxyz='Interactive'; else hFxyz=varargin{2}; end + hFxyz = cat_stat_spm_results_ui('FindXYZframe',hFxyz); + varargout = {getfield(get(hFxyz,'UserData'),'xyz')}; + + + %====================================================================== + case 'setcoords' % Set co-ordinates to XYZ widget + %====================================================================== + % [xyz,d] = spm_results_ui('SetCoords',xyz,hFxyz,hC) + if nargin<4, hC=NaN; else hC=varargin{4}; end + if nargin<3, hFxyz=cat_stat_spm_results_ui('FindXYZframe'); else hFxyz=varargin{3}; end + if nargin<2, error('Set co-ords to what!'); else xyz=varargin{2}; end + + %-If this is an internal call, then don't do anything + if isequal(hFxyz,hC), return, end + + UD = get(hFxyz,'UserData'); + + %-Check validity of coords only when called without a caller handle + %------------------------------------------------------------------ + if ~ishandle(hC) + [xyz,d] = spm_XYZreg('RoundCoords',xyz,UD.M,UD.DIM); + if d>0 && nargout<2, warning(sprintf(... + '%s: Co-ords rounded to nearest voxel centre: Discrepancy %.2f',... + mfilename,d)) + end + else + d = []; + end + + %-Update xyz information & widget strings + %------------------------------------------------------------------ + UD.xyz = xyz; set(hFxyz,'UserData',UD) + set(UD.hX,'String',sprintf('%.2f',xyz(1))) + set(UD.hY,'String',sprintf('%.2f',xyz(2))) + set(UD.hZ,'String',sprintf('%.2f',xyz(3))) + cat_stat_spm_results_ui('UpdateSPMval',UD); + + %-Tell the registry, if we've not been called by the registry... + %------------------------------------------------------------------ + if (~isempty(UD.hReg) && ~isequal(UD.hReg,hC)) + spm_XYZreg('SetCoords',xyz,UD.hReg,hFxyz); + end + + %-Return arguments + %------------------------------------------------------------------ + varargout = {xyz,d}; + + + %====================================================================== + case 'findxyzframe' % Find hFxyz frame + %====================================================================== + % hFxyz = spm_results_ui('FindXYZframe',h) + % Sorts out hFxyz handles + if nargin<2, h='Interactive'; else h=varargin{2}; end + if ischar(h), h=spm_figure('FindWin',h); end + if ~ishandle(h), error('invalid handle'), end + if ~strcmp(get(h,'Tag'),'hFxyz'), h=findobj(h,'Tag','hFxyz'); end + if isempty(h), error('XYZ frame not found'), end + if length(h)>1, error('Multiple XYZ frames found'), end + varargout = {h}; + + + %====================================================================== + case 'plotui' %-GUI for plot manipulation + %====================================================================== + % spm_results_ui('PlotUi',hAx) + if nargin<2, hAx=gca; else hAx=varargin{2}; end + + WS = spm('WinScale'); + FS = spm('FontSizes'); + Finter=spm_figure('FindWin','Interactive'); + figure(Finter) + + %-Check there aren't already controls! + %------------------------------------------------------------------ + hGraphUI = findobj(Finter,'Tag','hGraphUI'); + if ~isempty(hGraphUI) %-Controls exist + hBs = get(hGraphUI,'UserData'); + if hAx==get(hBs(1),'UserData') %-Controls linked to these axes + return + else %-Old controls remain + delete(findobj(Finter,'Tag','hGraphUIbg')) + end + end + + %-Frames & text + %------------------------------------------------------------------ + hGraphUIbg = uipanel('Parent',Finter,'Title','','Tag','hGraphUIbg',... + 'BackgroundColor',spm('Colour'),... + 'BorderType','Line', 'HighlightColor',[0 0 0],... + 'Units','Pixels','Position',[001 195 400 055].*WS); + hGraphUI = uipanel('Parent',hGraphUIbg,'Title','','Tag','hGraphUI',... + 'BorderType','Etchedin', ... + 'BackgroundColor',[179 179 179]/255,... + 'Units','Pixels','Position',[005 005 390 046].*WS); + hGraphUIButtsF = uipanel('Parent',hGraphUI,'Title','plot controls',... + 'Units','Pixels','Position',[005 005 380 039].*WS,... + 'BorderType','Beveledout', ... + 'FontAngle','Italic',... + 'FontSize',FS(10),... + 'ForegroundColor',[1 1 1],... + 'BackgroundColor',[179 179 179]/255); + + %-Controls + %------------------------------------------------------------------ + h1 = uicontrol('Parent',hGraphUIButtsF,'Style','CheckBox','String','hold',... + 'ToolTipString','toggle hold to overlay plots',... + 'FontSize',FS(10),... + 'Value',double(strcmp(get(hAx,'NextPlot'),'add')),... + 'Callback',[... + 'if get(gcbo,''Value''), ',... + 'set(get(gcbo,''UserData''),''NextPlot'',''add''), ',... + 'else, ',... + 'set(get(gcbo,''UserData''),''NextPlot'',''replace''), ',... + 'end'],... + 'Interruptible','on','Enable','on',... + 'Tag','holdButton',... + 'Position',[005 005 070 020].*WS); + h2 = uicontrol('Parent',hGraphUIButtsF,'Style','CheckBox','String','grid',... + 'ToolTipString','toggle axes grid',... + 'FontSize',FS(10),... + 'Value',double(strcmp(get(hAx,'XGrid'),'on')),... + 'Callback',[... + 'if get(gcbo,''Value''), ',... + 'set(get(gcbo,''UserData''),''XGrid'',''on'','... + '''YGrid'',''on'',''ZGrid'',''on''), ',... + 'else, ',... + 'set(get(gcbo,''UserData''),''XGrid'',''off'','... + '''YGrid'',''off'',''ZGrid'',''off''), ',... + 'end'],... + 'Interruptible','on','Enable','on',... + 'Position',[080 005 070 020].*WS); + h3 = uicontrol('Parent',hGraphUIButtsF,'Style','CheckBox','String','Box',... + 'ToolTipString','toggle axes box',... + 'FontSize',FS(10),... + 'Value',double(strcmp(get(hAx,'Box'),'on')),... + 'Callback',[... + 'if get(gcbo,''Value''), ',... + 'set(get(gcbo,''UserData''),''Box'',''on''), ',... + 'else, ',... + 'set(get(gcbo,''UserData''),''Box'',''off''), ',... + 'end'],... + 'Interruptible','on','Enable','on',... + 'Position',[155 005 070 020].*WS); + h4 = uicontrol('Parent',hGraphUIButtsF,'Style','popupmenu',... + 'ToolTipString','edit axis text annotations',... + 'FontSize',FS(10),... + 'String',{'text','Title','Xlabel','Ylabel'},... + 'Callback','spm_results_ui(''PlotUiCB'')',... + 'Interruptible','on','Enable','on',... + 'Position',[230 005 070 020].*WS); + h5 = uicontrol('Parent',hGraphUIButtsF,'Style','popupmenu',... + 'ToolTipString','change various axes attributes',... + 'FontSize',FS(10),... + 'String',{'attrib','LineWidth','XLim','YLim','handle'},... + 'Callback','spm_results_ui(''PlotUiCB'')',... + 'Interruptible','off','Enable','on',... + 'Position',[305 005 070 020].*WS); + + %-Handle storage for linking, and DeleteFcns for linked deletion + %------------------------------------------------------------------ + set(hGraphUI,'UserData',[h1,h2,h3,h4,h5]) + set([h1,h2,h3,h4,h5],'UserData',hAx) + + set(hGraphUIbg,'UserData',... + [hGraphUI,hGraphUIButtsF,h1,h2,h3,h4,h5],... + 'DeleteFcn','spm_results_ui(''Delete'',get(gcbo,''UserData''))') + set(hAx,'UserData',hGraphUIbg,... + 'DeleteFcn','spm_results_ui(''Delete'',get(gcbo,''UserData''))') + + + %====================================================================== + case 'plotuicb' + %====================================================================== + % spm_results_ui('PlotUiCB') + hPM = gcbo; + v = get(hPM,'Value'); + if v==1, return, end + str = cellstr(get(hPM,'String')); + str = str{v}; + + hAx = get(hPM,'UserData'); + switch str + case 'Title' + h = get(hAx,'Title'); + set(h,'String',spm_input('Enter title:',-1,'s+',get(h,'String'))) + case 'Xlabel' + h = get(hAx,'Xlabel'); + set(h,'String',spm_input('Enter X axis label:',-1,'s+',get(h,'String'))) + case 'Ylabel' + h = get(hAx,'Ylabel'); + set(h,'String',spm_input('Enter Y axis label:',-1,'s+',get(h,'String'))) + case 'LineWidth' + lw = spm_input('Enter LineWidth',-1,'e',get(hAx,'LineWidth'),1); + set(hAx,'LineWidth',lw) + case 'XLim' + XLim = spm_input('Enter XLim',-1,'e',get(hAx,'XLim'),[1,2]); + set(hAx,'XLim',XLim) + case 'YLim' + YLim = spm_input('Enter YLim',-1,'e',get(hAx,'YLim'),[1,2]); + set(hAx,'YLim',YLim) + case 'handle' + varargout={hAx}; + otherwise + warning(['Unknown action: ',str]) + end + + set(hPM,'Value',1) + + + %====================================================================== + case 'clear' %-Clear results subpane + %====================================================================== + % Fgraph = spm_results_ui('Clear',F,mode) + % mode 1 [default] usual, mode 0 - clear & hide Res stuff, 2 - RNP + + if nargin<3, mode=1; else mode=varargin{3}; end + if nargin<2, F='Graphics'; else F=varargin{2}; end + F = spm_figure('FindWin',F); + + %-Clear input objects from 'Interactive' window + %------------------------------------------------------------------ + %spm_input('!DeleteInputObj') + + + %-Get handles of objects in Graphics window & note permanent results objects + %------------------------------------------------------------------ + H = get(F,'Children'); %-Get contents of window + H = findobj(H,'flat','HandleVisibility','on'); %-Drop GUI components + h = findobj(H,'flat','Tag','PermRes'); %-Look for 'PermRes' object + + if ~isempty(h) + %-Found 'PermRes' object + % This has handles of permanent results objects in it's UserData + tmp = get(h,'UserData'); + HR = tmp.H; + HRv = tmp.Hv; + else + %-No trace of permanent results objects + HR = []; + HRv = {}; + end + H = setdiff(H,HR); %-Drop permanent results obj + + + %-Delete stuff as appropriate + %------------------------------------------------------------------ + if mode==2 %-Don't delete axes with NextPlot 'add' + H = setdiff(H,findobj(H,'flat','Type','axes','NextPlot','add')); + end + + delete(H) + %set(F,'resize','on');set(F,'resize','off') + + if mode==0 %-Hide the permanent results section stuff + set(HR,'Visible','off') + else + set(HR,{'Visible'},HRv) + end + + + %====================================================================== + case 'close' %-Close Results + %====================================================================== + set(spm_figure('GetWin','Graphics'),'Color',[1 1 1]); + spm_clf('Interactive'); + spm_clf('Graphics'); + close(spm_figure('FindWin','Satellite')); + evalin('base','clear') + + fg = spm_figure('FindWin','Graphics'); + if ~isempty(oldGraphicsRes) + fg.ExportsetupWindow.restext = oldGraphicsRes; + end + + + %====================================================================== + case 'launchmp' %-Launch multiplanar toolbox + %====================================================================== + % hMP = spm_results_ui('LaunchMP',M,DIM,hReg,hBmp) + if nargin<5, hBmp = gcbo; else hBmp = varargin{5}; end + hReg = varargin{4}; + DIM = varargin{3}; + M = varargin{2}; + + %-Check for existing MultiPlanar toolbox + hMP = get(hBmp,'UserData'); + if ishandle(hMP) + figure(ancestor(hMP,'figure')); + varargout = {hMP}; + return + end + + %-Initialise and cross-register MultiPlanar toolbox + hMP = spm_XYZreg_Ex2('Create',M,DIM); + spm_XYZreg('Xreg',hReg,hMP,'spm_XYZreg_Ex2'); + + %-Setup automatic deletion of MultiPlanar on deletion of results controls + set(hBmp,'Enable','on','UserData',hMP) + set(hBmp,'DeleteFcn','spm_results_ui(''delete'',get(gcbo,''UserData''))') + + varargout = {hMP}; + + + %====================================================================== + case 'delete' %-Delete HandleGraphics objects + %====================================================================== + % spm_results_ui('Delete',h) + h = varargin{2}; + delete(h(ishandle(h))); + + + %====================================================================== + otherwise + %====================================================================== + error('Unknown action string') + varargout = {[],[],[]}; + +end + +%========================================================================== +function mychgcon(obj,evt,xSPM) +%========================================================================== +xSPM2.swd = xSPM.swd; +try, xSPM2.units = xSPM.units; end +xSPM2.Ic = getfield(get(obj,'UserData'),'Ic'); +if isempty(xSPM2.Ic) || all(xSPM2.Ic == 0), xSPM2 = rmfield(xSPM2,'Ic'); end +xSPM2.Im = xSPM.Im; +xSPM2.pm = xSPM.pm; +xSPM2.Ex = xSPM.Ex; +xSPM2.title = ''; +if ~isempty(xSPM.thresDesc) + if strcmp(xSPM.STAT,'P') + % These are soon overwritten by spm_getSPM + xSPM2.thresDesc = xSPM.thresDesc; + xSPM2.u = xSPM.u; + xSPM2.k = xSPM.k; + % xSPM.STATstr contains Gamma + else + td = regexp(xSPM.thresDesc,'p\D?(?[\.\d]+) \((?\S+)\)','names'); + if isempty(td) + td = regexp(xSPM.thresDesc,'\w=(?[\.\d]+)','names'); + td.thresDesc = 'none'; + end + if strcmp(td.thresDesc,'unc.'), td.thresDesc = 'none'; end + xSPM2.thresDesc = td.thresDesc; + xSPM2.u = str2double(td.u); + xSPM2.k = xSPM.k; + end +end +hReg = spm_XYZreg('FindReg',spm_figure('GetWin','Interactive')); +xyz = spm_XYZreg('GetCoords',hReg); +[hReg,xSPM,SPM] = cat_stat_spm_results_ui('setup',xSPM2); +TabDat = spm_list('List',xSPM,hReg); +spm_XYZreg('SetCoords',xyz,hReg); +% CAT.begin +spm_list_cleanup; +% CAT.end +assignin('base','hReg',hReg); +assignin('base','xSPM',xSPM); +assignin('base','SPM',SPM); +assignin('base','TabDat',TabDat); +figure(spm_figure('GetWin','Interactive')); + +%========================================================================== +function mycheckres(obj,evt,xSPM) +%========================================================================== +spm_check_results([],xSPM); + +%========================================================================== +function mysavespm(action) +%========================================================================== +xSPM = evalin('base','xSPM;'); +XYZ = xSPM.XYZ; + +switch lower(action) + case 'thresh' + Z = xSPM.Z; + + case 'binary' + Z = ones(size(xSPM.Z)); + + case 'n-ary' + if ~isfield(xSPM,'G') + Z = spm_clusters(XYZ); + num = max(Z); + [n, ni] = sort(histc(Z,1:num), 2, 'descend'); + n = size(ni); + n(ni) = 1:num; + Z = n(Z); + else + C = NaN(1,size(xSPM.G.vertices,1)); + C(xSPM.XYZ(1,:)) = ones(size(xSPM.Z)); + C = spm_mesh_clusters(xSPM.G,C); + Z = C(xSPM.XYZ(1,:)); + end + + case 'current' + [xyzmm,i] = spm_XYZreg('NearestXYZ',... + cat_stat_spm_results_ui('GetCoords'),xSPM.XYZmm); + cat_stat_spm_results_ui('SetCoords',xSPM.XYZmm(:,i)); + + if ~isfield(xSPM,'G') + A = spm_clusters(XYZ); + j = find(A == A(i)); + Z = ones(1,numel(j)); + XYZ = xSPM.XYZ(:,j); + else + C = NaN(1,size(xSPM.G.vertices,1)); + C(xSPM.XYZ(1,:)) = ones(size(xSPM.Z)); + C = spm_mesh_clusters(xSPM.G,C); + C = C==C(xSPM.XYZ(1,i)); + Z = C(xSPM.XYZ(1,:)); + end + + otherwise + error('Unknown action.'); +end + +if isfield(xSPM,'G') + F = spm_input('Output filename',1,'s'); + if isempty(spm_file(F,'ext')) + F = spm_file(F,'ext','.gii'); + end + F = spm_file(F,'CPath'); + M = gifti(xSPM.G); + C = zeros(1,size(xSPM.G.vertices,1)); + C(xSPM.XYZ(1,:)) = Z; % or use NODE_INDEX + M.cdata = C; + save(M,F); + cmd = 'cat_surf_render(''Disp'',''%s'')'; +else + V = spm_write_filtered(Z, XYZ, xSPM.DIM, xSPM.M,... + sprintf('SPM{%c}-filtered: u = %5.3f, k = %d',xSPM.STAT,xSPM.u,xSPM.k)); + cmd = 'spm_image(''display'',''%s'')'; + F = V.fname; +end + +fprintf('Written %s\n',spm_file(F,'link',cmd)); %-# + +%========================================================================== +function myslover +%========================================================================== +spm_input('!DeleteInputObj'); +xSPM = evalin('base','xSPM;'); + +so = slover; +[img,sts] = spm_select(1,'image','Select image for rendering on'); +if ~sts, return; end +so.img.vol = spm_vol(img); +%obj.img.type = 'truecolour'; +%obj.img.cmap = gray; +%[mx,mn] = slover('volmaxmin', obj.img.vol); +%obj.img.range = [mn mx]; +so.img.prop = 1; + +so = add_spm(so,xSPM); + +so.transform = deblank(spm_input('Image orientation', '+1', ... + 'Axial|Coronal|Sagittal', char('axial','coronal','sagittal'), 1)); +so = fill_defaults(so); +slices = so.slices; +so.slices = spm_input('Slices to display (mm)', '+1', 'e', ... + sprintf('%0.0f:%0.0f:%0.0f',slices(1),mean(diff(slices)),slices(end))); + +so.figure = spm_figure('GetWin', 'SliceOverlay'); +so = paint(so); +assignin('base','so',so); + + + +% CAT.begin +%========================================================================== +function spm_list_cleanup(hReg) +%========================================================================== + hRes.Fgraph = [spm_figure('FindWin','Graphics'),spm_figure('FindWin','Satellite')]; + + % fine red lines of the SPM result table + hRes.Fline = findobj(hRes.Fgraph,'Type','Line','Tag','');% ,'UIcontextMenu',[]); + hRes.FlineAx = get(hRes.Fline,'parent'); + + set(hRes.Fline,'HitTest','off'); % + for axi = 1:numel( hRes.FlineAx ), rotate3d(hRes.FlineAx{axi},'off'); end + for axi = 1:numel( hRes.FlineAx ), set(hRes.FlineAx{axi},'visible','off'); end + + %% + hRes.Img = get(findobj(hRes.Fgraph,'Type','Image','Tag','Transverse'),'parent'); + for axi = 1:numel( hRes.Img ), rotate3d(hRes.Img{axi},'off'); end + + %% find the SPM string within the surface axis + hRes.Ftext = findobj(hRes.Fgraph,'Type','Text'); + stext = get(hRes.Ftext,'String'); + hRes.Ftext3dspm = findobj(hRes.Fgraph,'Type','Text','String', ... + stext{ find(~cellfun('isempty',strfind(stext,'SPM\{'))) } ); + set(hRes.Ftext3dspm,'visible','off','HitTest','off'); + + %% get backgroundcolor + bgc = get(spm_figure('FindWin','Graphics'),'Color'); + % get low contrast texts + Ftextcol = cell2mat(get(hRes.Ftext,'Color')); + %% invert text + rms = @(x) mean(x.^2,2).^0.5; + bgcdist = rms(Ftextcol - repmat(bgc, numel(hRes.Ftext), 1)); + bgcdist = abs(bgcdist)<0.3; + if ~isempty(bgcdist) + for fi = 1:numel(bgcdist) + if bgcdist(fi)>0 + set( hRes.Ftext( fi ) , 'Color' , min(1,max(0, 1 - Ftextcol( fi ,:))) ); + end + end + end + + %% update spm_XYZreg XYZ update function + if ~exist('hReg','var') + ListXYZ=findobj('ButtonDownFcn','spm_XYZreg(''SetCoords'',get(gcbo,''UserData''),hReg,1);'); + for i=1:numel(ListXYZ) + set(ListXYZ(i),'ButtonDownFcn',[get(ListXYZ(i),'ButtonDownFcn') ' cat_stat_spm_results_ui(''spm_list_cleanup'');']); + end + end +%========================================================================== +% CAT.end +","MATLAB" +"Neurology","ChristianGaser/cat12","development/cat_surf_createCS.m",".m","29143","612","function [Yth1,S,Psurf] = cat_surf_createCS(V,Ym,Ya,YMF,opt) +% ______________________________________________________________________ +% Surface creation and thickness estimation. +% +% [Yth1,S]=cat_surf_createCS(V,Ym,Ya,YMF,opt) +% +% Yth1 = thickness map +% S = structure with surfaces, like the left hemishere, that contains +% vertices, faces, GM thickness (th1), and the transformation to +% map to nifti space (vmat) and back (vmati). +% V = spm_vol-structure +% Ym = the (local) intensity, noise, and bias corrected T1 image +% Ya = the atlas map with the ROIs for left and right hemispheres +% (this is generated with cat_vol_partvol) +% YMF = a logical map with the area that has to be filled +% (this is generated with cat_vol_partvol) +% +% opt.surf = {'lh','rh'[,'cerebellum','brain']} - side +% .reduceCS = 100000 - number of faces +% +% Options set by cat_defaults.m +% .interpV = 0.5 - mm-resolution for thickness estimation +% +% Here we used the intensity normalized image Ym, rather that the Yp0 +% image, because it has more information about sulci that we need +% especialy for asymetrical sulci. +% Furthermore, all non-cortical regions and blood vessels were removed +% (for left and right surface). Blood vessels (with high contrast) can +% lead to strong error in the topology correction. Higher resolution +% also helps to reduce artifacts. +% ______________________________________________________________________ +% Robert Dahnke +% Structural Brain Mapping Group +% University Jena +% ______________________________________________________________________ +% $Id$ + +%#ok<*AGROW> + + % set defaults + vx_vol = sqrt(sum(V.mat(1:3,1:3).^2)); + if ~exist('opt','var'), opt=struct(); end + def.verb = 2; + def.surf = {'lh','rh'}; % {'lh','rh','cerebellum','brain'} + def.interpV = max(0.25,min([min(vx_vol),opt.interpV,1])); + def.reduceCS = 100000; + def.tca = cat_get_defaults('extopts.tca'); + def.LAB = cat_get_defaults('extopts.LAB'); + def.usePPmap = 1; + def.fsavgDir = fullfile(spm('dir'),'toolbox','cat12','templates_surfaces'); + opt = cat_io_updateStruct(def,opt); + + Psurf = struct(); + + % correction for 'n' prefix for noise corrected and/or interpolated files + [pp,ff] = spm_fileparts(V.fname); + + if cat_get_defaults('extopts.subfolders') + surffolder = 'surf'; + mrifolder = 'mri'; + pp = spm_str_manip(pp,'h'); % remove 'mri' in pathname that already exists + else + surffolder = ''; + mrifolder = ''; + end + + if ff(1)=='n' + if (exist(fullfile(pp,[ff(2:end) '.nii']), 'file')) || (exist(fullfile(pp,[ff(2:end) '.img']), 'file')) + ff = ff(2:end); + end + end + + % get both sides in the atlas map + NS = @(Ys,s) Ys==s | Ys==s+1; + + % noise reduction for higher resolutions (>=1 mm full correction, 1.5 mm as lower limit) + % (added 20160920 ~R1010 due to servere sulcus reconstruction problems with 1.5 Tesla data) + Yms = Ym + 0; cat_sanlm(Yms,3,1); + %noise = std(Yms(Yms(:)>0) - Ym(Yms(:)>0)); % more selective filtering? + %vx_vol = [0.5;0.75;1;1.25;1.5;2]; [vx_vol + %min(1,max(0,3-2*mean(vx_vol,2))) min(1,max(0,1-mean(vx_vol,2))/2) 0.5*min(1,max(0,1.5-mean(vx_vol,2)))] % filter test + mf = min(1,max(0,3-2*mean(vx_vol,2))); + Ym = mf * Yms + (1-mf) * Ym; + + % filling + Ymf = max(Ym,min(0.95,YMF)); + Ymfs = cat_vol_smooth3X(Ymf,1); + Ytmp = cat_vol_morph(YMF,'d',3) & Ymfs>2.3/3; + Ymf(Ytmp) = max(min(Ym(Ytmp),0),Ymfs(Ytmp)); clear Ytmp Ymfs YMF; + Ymf = Ymf*3; + + + % reduction of artifact, blood vessel, and meninges next to the cortex + % (are often visible as very thin structures that were added to the WM + % or removed from the brain) + Ycsfd = cat_vbdist(single(Ymf<1.5),Ymf>1,vx_vol); + Yctd = cat_vbdist(single(Ymf<0.5),Ymf>0,vx_vol); + Ysroi = Ymf>2 & Yctd<10 & Ycsfd>0 & Ycsfd<2 & ... + cat_vol_morph(~NS(Ya,opt.LAB.HC) & ~NS(Ya,opt.LAB.HI) & ... + ~NS(Ya,opt.LAB.PH) & ~NS(Ya,opt.LAB.VT),'erode',4); + Ymfs = cat_vol_median3(Ymf,Ysroi,Ymf>eps,0.1); % median filter + Ymf = mf * Ymfs + (1-mf) * Ymf; + + % closing of small WMHs in cases with reduced WM volume + %vols = [sum(round(Ymf(:))==1) sum(round(Ymf(:))==2) sum(round(Ymf(:))==3)] / sum(round(Ymf(:))>0); + %volt = min(1,max(0,mean([ (vols(1)-0.20)*5 (1 - max(0,min(0.3,vols(3)-0.2))*10) ]))); + %Ywmh = cat_vol_morph(Ymf>max(2.2,2.5 - 0.3*volt),'lc',volt); + %Ymf = max(Ymf,smooth3(Ywmh)*2.9); + + % gaussian filter? ... only in tissue regions + %Ymfs = cat_vol_smooth3X(max(1,Ymf),0.5*min(1,max(0,1.5-mean(vx_vol)))); + %Ymf(Ymf>1) = Ymfs(Ymf>1); + + clear Ysroi Ywmd Ymfs; + + + + Yth1 = zeros(size(Ymf),'single'); + if opt.expertgui > 1 + Ywd = zeros(size(Ymf),'single'); + Ycd = zeros(size(Ymf),'single'); + end + + [D,I] = cat_vbdist(single(Ya>0)); Ya = Ya(I); % for sides + + for si=1:numel(opt.surf) + + % surface filenames + Praw = fullfile(pp,surffolder,sprintf('%s.central.nofix.%s.gii',opt.surf{si},ff)); % raw + Psphere0 = fullfile(pp,surffolder,sprintf('%s.sphere.nofix.%s.gii',opt.surf{si},ff)); % sphere.nofix + Pcentral = fullfile(pp,surffolder,sprintf('%s.central.%s.gii',opt.surf{si},ff)); % fiducial + Pthick = fullfile(pp,surffolder,sprintf('%s.thickness.%s',opt.surf{si},ff)); % thickness / GM depth + Pgwo = fullfile(pp,surffolder,sprintf('%s.depthWMo.%s',opt.surf{si},ff)); % gyrus width / GWM depth / gyral span + Pgw = fullfile(pp,surffolder,sprintf('%s.depthGWM.%s',opt.surf{si},ff)); % gyrus width / GWM depth / gyral span + Pgww = fullfile(pp,surffolder,sprintf('%s.depthWM.%s',opt.surf{si},ff)); % gyrus witdh of the WM / WM depth + Pgwwg = fullfile(pp,surffolder,sprintf('%s.depthWMg.%s',opt.surf{si},ff)); % gyrus witdh of the WM / WM depth + Psw = fullfile(pp,surffolder,sprintf('%s.depthCSF.%s',opt.surf{si},ff)); % sulcus width / CSF depth / sulcal span + Pdefects0 = fullfile(pp,surffolder,sprintf('%s.defects.%s',opt.surf{si},ff)); % defects temporary file + Pdefects = fullfile(pp,surffolder,sprintf('%s.defects.%s.gii',opt.surf{si},ff)); % defects + Psphere = fullfile(pp,surffolder,sprintf('%s.sphere.%s.gii',opt.surf{si},ff)); % sphere + Pspherereg = fullfile(pp,surffolder,sprintf('%s.sphere.reg.%s.gii',opt.surf{si},ff)); % sphere.reg + Pfsavg = fullfile(opt.fsavgDir,sprintf('%s.central.freesurfer.gii',opt.surf{si})); % fsaverage central + Pfsavgsph = fullfile(opt.fsavgDir,sprintf('%s.sphere.freesurfer.gii',opt.surf{si})); % fsaverage sphere + + surffile = {'Praw','Psphere0','Pcentral','Pthick','Pgw','Pgww','Psw',... + 'Pdefects0','Pdefects','Psphere','Pspherereg','Pfsavg','Pfsavgsph'}; + for sfi=1:numel(surffile) + eval(sprintf('Psurf(si).%s = %s;',surffile{sfi},surffile{sfi})); + end + + % reduce for object area + switch opt.surf{si} + case {'L','lh'}, Ymfs = Ymf .* (Ya>0) .* ~(NS(Ya,opt.LAB.CB) | NS(Ya,opt.LAB.BV) | NS(Ya,opt.LAB.ON) | NS(Ya,opt.LAB.MB)) .* (mod(Ya,2)==1); Yside = mod(Ya,2)==1; + case {'R','rh'}, Ymfs = Ymf .* (Ya>0) .* ~(NS(Ya,opt.LAB.CB) | NS(Ya,opt.LAB.BV) | NS(Ya,opt.LAB.ON) | NS(Ya,opt.LAB.MB)) .* (mod(Ya,2)==0); Yside = mod(Ya,2)==0; + case {'C','cerebellum'}, Ymfs = Ymf .* (Ya>0) .* NS(Ya,opt.LAB.CB); Yside = NS(Ya,opt.LAB.CB)>0; + case {'B','brain'}, Ymfs = Ymf .* (Ya>0); Yside = true(size(Ya)); + end + + % get dilated mask of gyrus parahippocampalis and hippocampus of both sides + mask_parahipp = cat_vol_morph(NS(Ya,opt.LAB.PH) | NS(Ya,opt.LAB.HC),'d',6); + + %% thickness estimation + if si==1, fprintf('\n'); end + fprintf('%s:\n',opt.surf{si}); + stime = cat_io_cmd(sprintf(' Thickness estimation (%0.2f mm%s)',opt.interpV,native2unicode(179, 'latin1'))); + + [Ymfs,Yside,mask_parahipp,BB] = cat_vol_resize({Ymfs,Yside,mask_parahipp},'reduceBrain',vx_vol,6,Ymfs>0.2); % removing background + [Ymfs,resI] = cat_vol_resize(Ymfs,'interp',V,opt.interpV); % interpolate volume + Yside = cat_vol_resize(Yside,'interp',V,opt.interpV)>0.5; % interpolate volume + mask_parahipp = cat_vol_resize(mask_parahipp,'interp',V,opt.interpV)>0.5; % interpolate volume + + %% pbt calculation + [Yth1i,Yppi] = cat_vol_pbt(max(1,Ymfs),struct('resV',opt.interpV)); % avoid underestimated thickness in gyri + if ~opt.expertgui, clear Ymfs; end + Yth1i(Yth1i>10)=0; Yppi(isnan(Yppi))=0; + [D,I] = cat_vbdist(Yth1i,Yside); Yth1i = Yth1i(I); clear D I; % add further values around the cortex + Yth1t = cat_vol_resize(Yth1i,'deinterp',resI); clear Yth1i; % back to original resolution + Yth1t = cat_vol_resize(Yth1t,'dereduceBrain',BB); % adding background + Yth1 = max(Yth1,Yth1t); % save on main image + clear Yth1t; + fprintf('%4.0fs\n',etime(clock,stime)); + + %% PBT estimation of the gyrus and sulcus width + if opt.expertgui > 1 + %% gyrus width / WM depth + % For the WM depth estimation it is better to use the L4 boundary + % and correct later for thickness, because the WM is very thin in + % gyral regions and will cause bad values. + % On the other side we do not want the whole filled block of the + % Yppi map and so we have to mix both the original WM map and the + % Yppi map. + % As far as there is no thickness in pure WM regions there will + % be no correction. + % + % figure, isosurface(smooth3(Yppi),0.5,Yth1i), axis equal off + stime = cat_io_cmd(' WM depth estimation'); + [Yar,Ymr,BB] = cat_vol_resize({Ya,Ym},'reduceBrain',vx_vol,BB.BB); % removing background + Yar = uint8(cat_vol_resize(Yar,'interp',V,opt.interpV,'nearest')); % interpolate volume + Ymr = cat_vol_resize(Ymr,'interp',V,opt.interpV); % interpolate volume + switch opt.surf{si} + case {'L','lh'}, + Ymr = Ymr .* (Yar>0) .* ~(NS(Yar,3) | NS(Yar,7) | NS(Yar,11) | NS(Yar,13)) .* (mod(Yar,2)==1); + Ynw = smooth3(cat_vol_morph(NS(Yar,5) | NS(Yar,9) | NS(Yar,15) | NS(Yar,23),'d',2) | ... + (cat_vol_morph(Yppi==1,'e',2) & Ymr>1.7/3 & Ymr<2.5/3) & (mod(Yar,2)==1)); + case {'R','rh'}, + Ymr = Ymr .* (Yar>0) .* ~(NS(Yar,3) | NS(Yar,7) | NS(Yar,11) | NS(Yar,13)) .* (mod(Yar,2)==0); + Ynw = smooth3(cat_vol_morph(NS(Yar,5) | NS(Yar,9) | NS(Yar,15) | NS(Yar,23),'d',2) | ... + (cat_vol_morph(Yppi==1,'e',2) & Ymr>1.7/3 & Ymr<2.5/3) & (mod(Yar,2)==0)); + case {'C','cerebellum'}, Ymr = Ymr .* (Yar>0) .* NS(Yar,3); + case {'B','brain'}, Ymr = Ymr .* (Yar>0); + end + % clear Yar; + %% + Yppis = Yppi .* (1-Ynw) + max(0,min(1,Ymr*3-2)) .* Ynw; % adding real WM map + Ywdt = cat_vbdist(1-Yppis); % estimate distance map to central/WM surface + Ywdt = cat_vol_pbtp(max(2,4-Ymfs),Ywdt,inf(size(Ywdt),'single'))*opt.interpV; + [D,I] = cat_vbdist(single(Ywdt>0),Yside); Ywdt = Ywdt(I); clear D I; % add further values around the cortex + %% + Ywdt = cat_vol_median3(Ywdt); Ywdt = smooth3(Ywdt); % smoothing + Ywdt = cat_vol_resize(Ywdt,'deinterp',resI); + Ywdt = cat_vol_resize(Ywdt,'dereduceBrain',BB); % adding background + Ywd = max(Ywd,Ywdt); + clear Ywdt; + + %% sulcus width / CSF depth + % for the CSF depth we cannot use the origal data, because of + % sulcal blurring, but we got the PP map at half distance and + % correct later for half thickness + fprintf('%4.0fs\n',etime(clock,stime)); + stime = cat_io_cmd(' CSF depth estimation'); + YM = smooth3(cat_vol_morph(Ymfs>0.5,'o',4))>0.5; % smooth CSF/background-skull boundary + Yppis = min(Ymr,Yppi); Yppis(isnan(Yppis))=0; % we want also CSF within the ventricle (for tests) + Ycdt = cat_vbdist(Yppis,YM); clear Yppis % distance to the cental/CSF-GM boundary + Ycdt = cat_vol_pbtp(max(2,Ymfs),Ycdt,inf(size(Ycdt),'single'))*opt.interpV; + Ycdt(~YM)=0; + [D,I] = cat_vbdist(single(Ycdt>0),Yside); Ycdt = Ycdt(I); clear D I; % add further values around the cortex + Ycdt = cat_vol_median3(Ycdt); Ycdt = smooth3(Ycdt); % smoothing + Ycdt = cat_vol_resize(Ycdt,'deinterp',resI); + Ycdt = cat_vol_resize(Ycdt,'dereduceBrain',BB); + Ycd = max(Ycd,Ycdt); + clear Ycdt; + fprintf('%4.0fs\n',etime(clock,stime)); + clear Ymr; + end + clear Ymfs; + + + %% Write Ypp for final deformation + % Write Yppi file with 1 mm resolution for the final deformation, + % because CAT_DeformSurf_ui cannot handle higher resolutions. + if opt.usePPmap + Yppt = cat_vol_resize(Yppi,'deinterp',resI); % back to original resolution + Yppt = cat_vol_resize(Yppt,'dereduceBrain',BB); % adding of background + Vpp = cat_io_writenii(V,Yppt,'','pp','percentage position map','uint8',[0,1/255],[1 0 0 0]); + clear Yppt; + + Vpp1 = Vpp; + Vpp1.fname = fullfile(pp,mrifolder,['pp1' ff '.nii']); + vmat2 = spm_imatrix(Vpp1.mat); + Vpp1.dim(1:3) = round(Vpp1.dim .* abs(vmat2(7:9))); + vmat2(7:9) = sign(vmat2(7:9)).*[1 1 1]; + Vpp1.mat = spm_matrix(vmat2); + + Vpp1 = spm_create_vol(Vpp1); + for x3 = 1:Vpp1.dim(3), + M = inv(spm_matrix([0 0 -x3 0 0 0 1 1 1])*inv(Vpp1.mat)*Vpp.mat); %#ok + v = spm_slice_vol(Vpp,M,Vpp1.dim(1:2),1); + Vpp1 = spm_write_plane(Vpp1,v,x3); + end; + clear M v x3; + end + + %% surface coordinate transformations + stime = cat_io_cmd(' Create initial surface','g5','',opt.verb); fprintf('\n'); + vmatBBV = spm_imatrix(V.mat); + + vmat = V.mat(1:3,:)*[0 1 0 0; 1 0 0 0; 0 0 1 0; 0 0 0 1]; + vmati = inv([vmat; 0 0 0 1]); vmati(4,:) = []; + + % if we can use the PP map we can start with a surface that is close to WM surface because this might minimize severe + % topology defects. Otherwise we use a threshold of 0.5 which is the central surface. + % However, this approach did not really improved topology correction, thus we again use a value of 0.5 + if opt.usePPmap, th_initial = 0.5; else th_initial = 0.5; end + + % apply TCA from BrainSuite for initial intensity-based topology correction + if opt.tca + Yppi0 = Yppi; + VN = resI.hdrN; + VN.dt(1) = 2; + VN.pinfo(1) = 1; + VN.fname = fullfile(pp,mrifolder,['tca_' ff '.nii']); + if isfield(VN,'pinfo'), VN = rmfield(VN,'pinfo'); end + if isfield(VN,'dat'), VN = rmfield(VN,'dat'); end + spm_write_vol(VN,255*(Yppi>th_initial)); + cmd = sprintf('tca -m 10000 -n 0 --delta 20 -i ""%s"" -o ""%s""',VN.fname,VN.fname); + [ST, RS] = cat_system(cmd); cat_check_system_output(ST,RS,opt.debug); + + % load topology corrected image in the correct orientation + VN2 = spm_vol(VN.fname); + Yppi_tca = Yppi; + for z=1:size(Yppi,3) + B = spm_matrix([0 0 -z 0 0 0 1 1 1]); + Yppi_tca(:,:,z) = single(spm_slice_vol(VN2,VN2.mat\VN.mat*inv(B),VN.dim(1:2),0)); + end + Yppi_tca = Yppi_tca/255; + delete(VN.fname); + + if opt.tca > 1 + % use tca-correction + Yppi = Yppi_tca; + else + % use only inside hippocampal mask tca-corrected version + Yppi(mask_parahipp) = Yppi_tca(mask_parahipp); + end + clear Yppi_tca; + fprintf('%s %4.0fs\n',repmat(' ',1,66),etime(clock,stime)); + end + + [tmp,CS.faces,CS.vertices] = cat_vol_genus0(Yppi,th_initial); + + % check whether tca+genus0 was successful, otherwise run genus0 with original data + if isempty(CS.faces) && opt.tca + [tmp,CS.faces,CS.vertices] = cat_vol_genus0(Yppi0,th_initial); + opt.tca = 0; + end + + clear tmp Yppi Yppi0; + + % correction for the boundary box used within the surface creation process + CS.vertices = CS.vertices .* repmat(abs(opt.interpV ./ vmatBBV([8,7,9])),size(CS.vertices,1),1); + CS.vertices = CS.vertices + repmat( BB.BB([3,1,5]) - 1,size(CS.vertices,1),1); + + fprintf('%s %4.0fs\n',repmat(' ',1,66),etime(clock,stime)); + + % correct the number of vertices depending on the number of major objects + if opt.reduceCS>0, + switch opt.surf{si} + case {'B','brain'}, CS = reducepatch(CS,opt.reduceCS*2); + otherwise, CS = reducepatch(CS,opt.reduceCS); + end + stime = cat_io_cmd(sprintf(' Reduce surface to %d faces:',size(CS.faces,1)),'g5','',opt.verb); + end + + % transform coordinates + CS.vertices = (vmat*[CS.vertices' ; ones(1,size(CS.vertices,1))])'; + save(gifti(struct('faces',CS.faces,'vertices',CS.vertices)),Praw); + + if opt.reduceCS>0, + % after reducepatch many triangles have very large area which causes isses for resampling + % RefineMesh adds triangles in those areas + cmd = sprintf('CAT_RefineMesh ""%s"" ""%s"" %0.2f',Praw,Praw,2); + [ST, RS] = cat_system(cmd); cat_check_system_output(ST,RS,opt.debug); + + % remove some unconnected meshes + cmd = sprintf('CAT_SeparatePolygon ""%s"" ""%s"" -1',Praw,Praw); % CAT_SeparatePolygon works here + [ST, RS] = cat_system(cmd); cat_check_system_output(ST,RS,opt.debug); + end + + % spherical surface mapping 1 of the uncorrected surface for topology correction + cmd = sprintf('CAT_Surf2Sphere ""%s"" ""%s"" 5',Praw,Psphere0); + [ST, RS] = cat_system(cmd); cat_check_system_output(ST,RS,opt.debug); + + % mark defects and save as gifti + if opt.debug == 2 + cmd = sprintf('CAT_MarkDefects -binary ""%s"" ""%s"" ""%s""',Praw,Psphere0,Pdefects0); + [ST, RS] = cat_system(cmd); cat_check_system_output(ST,RS,opt.debug); + cmd = sprintf('CAT_AddValuesToSurf ""%s"" ""%s"" ""%s""',Praw,Pdefects0,Pdefects); + [ST, RS] = cat_system(cmd); cat_check_system_output(ST,RS,opt.debug); + end + + %% topology correction and surface refinement + if ~opt.tca || opt.reduceCS>0 + stime = cat_io_cmd(' Topology correction and surface refinement','g5','',opt.verb,stime); + cmd = sprintf('CAT_FixTopology -deform -n 81920 -refine_length 2 ""%s"" ""%s"" ""%s""',Praw,Psphere0,Pcentral); + [ST, RS] = cat_system(cmd); cat_check_system_output(ST,RS,opt.debug); + else + stime = cat_io_cmd(' Resampling and surface refinement','g5','',opt.verb,stime); + cmd = sprintf('CAT_ResampleSphericalSurf ""%s"" ""%s"" ""%s"" 327680',Praw,Psphere0,Pcentral); + [ST, RS] = cat_system(cmd); cat_check_system_output(ST,RS,opt.debug); + end + + if opt.usePPmap + % we use thickness values to get from the initial (white matter) surface to the central surface + % the extent depends on the inital threshold of the surface creation + extent = th_initial - 0.5; + if extent ~= 0 + CS = gifti(Pcentral); + CS.vertices = (vmati*[CS.vertices' ; ones(1,size(CS.vertices,1))])'; + facevertexcdata = isocolors2(Yth1,CS.vertices); + cat_io_FreeSurfer('write_surf_data',Pthick,facevertexcdata); + + cmd = sprintf('CAT_Central2Pial ""%s"" ""%s"" ""%s"" ""%g""',Pcentral,Pthick,Pcentral,extent); + [ST, RS] = cat_system(cmd); cat_check_system_output(ST,RS,opt.debug); + end + + % surface refinement by surface deformation based on the PP map + th = 0.5; + cmd = sprintf(['CAT_DeformSurf ""%s"" none 0 0 0 ""%s"" ""%s"" none 0 1 -1 .1 ' ... + 'avg -0.01 0.01 .1 .1 5 0 ""%g"" ""%g"" n 0 0 0 100 0.01 0.0'], ... + Vpp1.fname,Pcentral,Pcentral,th,th); + [ST, RS] = cat_system(cmd); cat_check_system_output(ST,RS,opt.debug); + + % need some more refinement because some vertices are distorted after CAT_DeformSurf + cmd = sprintf('CAT_RefineMesh ""%s"" ""%s"" %0.2f',Pcentral,Pcentral,1.5); + [ST, RS] = cat_system(cmd); cat_check_system_output(ST,RS,opt.debug); + + cmd = sprintf(['CAT_DeformSurf ""%s"" none 0 0 0 ""%s"" ""%s"" none 0 1 -1 .5 ' ... + 'avg -0.1 0.1 .1 .1 5 0 ""%g"" ""%g"" n 0 0 0 100 0.01 0.0'], ... + Vpp1.fname,Pcentral,Pcentral,th,th); + [ST, RS] = cat_system(cmd); cat_check_system_output(ST,RS,opt.debug); + else + % surface refinement by simple smoothing + cmd = sprintf('CAT_BlurSurfHK ""%s"" ""%s"" %0.2f',Pcentral,Pcentral,2); + [ST, RS] = cat_system(cmd); cat_check_system_output(ST,RS,opt.debug); + end + + %% spherical surface mapping 2 of corrected surface + stime = cat_io_cmd(' Spherical mapping with areal smoothing','g5','',opt.verb,stime); + cmd = sprintf('CAT_Surf2Sphere ""%s"" ""%s"" 10',Pcentral,Psphere); + [ST, RS] = cat_system(cmd); cat_check_system_output(ST,RS,opt.debug); + + % spherical registration to fsaverage template + stime = cat_io_cmd(' Spherical registration','g5','',opt.verb,stime); + cmd = sprintf('CAT_WarpSurf -type 0 -i ""%s"" -is ""%s"" -t ""%s"" -ts ""%s"" -ws ""%s""',Pcentral,Psphere,Pfsavg,Pfsavgsph,Pspherereg); + [ST, RS] = cat_system(cmd); cat_check_system_output(ST,RS,opt.debug); + + % read final surface and map thickness data + stime = cat_io_cmd(' Thickness / Depth mapping','g5','',opt.verb,stime); + if ~opt.usePPmap || ((th_initial - 0.5) == 0) + CS = gifti(Pcentral); + CS.vertices = (vmati*[CS.vertices' ; ones(1,size(CS.vertices,1))])'; + facevertexcdata = isocolors2(Yth1,CS.vertices); + cat_io_FreeSurfer('write_surf_data',Pthick,facevertexcdata); + end + + % map WM and CSF width data (corrected by thickness) + if opt.expertgui > 1 + %% + facevertexcdata2 = isocolors2(Ywd,CS.vertices); + facevertexcdata2c = max(eps,facevertexcdata2 - facevertexcdata/2); + cat_io_FreeSurfer('write_surf_data',Pgwo,facevertexcdata2c); % gyrus width WM only + facevertexcdata2c = correctWMdepth(CS,facevertexcdata2c,100,0.2); + cat_io_FreeSurfer('write_surf_data',Pgww,facevertexcdata2c); % gyrus width WM only + facevertexcdata3c = facevertexcdata2c + facevertexcdata; % ); + cat_io_FreeSurfer('write_surf_data',Pgw,facevertexcdata3c); % gyrus width (WM and GM) + facevertexcdata4 = estimateWMdepthgradient(CS,facevertexcdata2c); + cat_io_FreeSurfer('write_surf_data',Pgwwg,facevertexcdata4); % gyrus width WM only > gradient + % smooth resampled values + try + cmd = sprintf('CAT_BlurSurfHK ""%s"" ""%s"" ""%g"" ""%s""',Pcentral,Pgwwg,3,Pgwwg); + [ST, RS] = cat_system(cmd); cat_check_system_output(ST,RS,opt.debug); + end + %% + %clear facevertexcdata2 facevertexcdata2c facevertexcdata3c facevertexcdata4; + % just a test ... problem with other species ... + %norm = sum(Ymf(:)>0.5) / prod(vx_vol) / 1000 / 1400; + %norm = mean([2 1 1].*diff([min(CS.vertices);max(CS.vertices)])); + %norm = mean([2 1 1].*std(CS.vertices)); % maybe the hull surface is better... + + facevertexcdata3 = isocolors2(Ycd,CS.vertices); + facevertexcdata3 = max(eps,facevertexcdata3 - facevertexcdata/2); + cat_io_FreeSurfer('write_surf_data',Psw,facevertexcdata3); + end + fprintf('%4.0fs\n',etime(clock,stime)); + + % visualize a side + % csp=patch(CS); view(3), camlight, lighting phong, axis equal off; set(csp,'facecolor','interp','edgecolor','none') + + % create output structure + S.(opt.surf{si}).vertices = CS.vertices; + S.(opt.surf{si}).faces = CS.faces; + S.(opt.surf{si}).vmat = vmat; + S.(opt.surf{si}).vmati = vmati; + S.(opt.surf{si}).th1 = facevertexcdata; + if opt.expertgui > 1 + S.(opt.surf{si}).th2 = facevertexcdata2; + S.(opt.surf{si}).th3 = facevertexcdata3; + end + clear Yth1i + + % we have to delete the original faces, because they have a different number of vertices after + % CAT_FixTopology! + delete(Praw); + if opt.debug == 2 + delete(Pdefects0); + end + delete(Psphere0); + if opt.usePPmap + delete(Vpp.fname); + delete(Vpp1.fname); + end + clear CS + end + + if opt.debug && opt.verb + for si=1:numel(Psurf) + fprintf('Display thickness: %s\n',spm_file(Psurf(si).Pthick,'link','cat_surf_display(''%s'')')); + end + end +end + +%======================================================================= +function [cdata,i] = correctWMdepth(CS,cdata,iter,lengthfactor) +% ______________________________________________________________________ +% Correct deep WM depth values that does not fit to the local thickness +% of the local gyri. +% +% lengthfactor should be between 0.2 and 0.4 +% ______________________________________________________________________ + + if ~exist('lengthfactor','var'), lengthfactor = 1/3; end + if ~exist('iter','var'), iter = 100; end + + %% + SV = CS.vertices; % Surface Vertices + SE = unique([CS.faces(:,1:2);CS.faces(:,2:3);CS.faces(:,3:-2:1)],'rows'); % Surface Edges + SEv = single(diff(cat(3,SV(SE(:,1),:),SV(SE(:,2),:)),1,3)); % Surface Edge Vector + SEL = sum(SEv.^2,2).^0.5; % Surface Edge Length + clear SEv + + + %% + i=0; cdatac = cdata+1; pc = 1; oc = 0; + while i0.05 ); + i=i+1; cdatac = cdata; + + M = (cdatac(SE(:,1)) - SEL(SE(:,1))*lengthfactor ) > cdatac(SE(:,2)); + cdata(SE(M,1)) = cdatac(SE(M,2)) + SEL(SE(M,1))*lengthfactor; + M = (cdata(SE(:,2)) - SEL(SE(:,2))*lengthfactor ) > cdatac(SE(:,1)); + cdata(SE(M,2)) = cdatac(SE(M,1)) + SEL(SE(M,1))*lengthfactor; + oc = sum( abs(cdata - cdatac)>0.05 ); + + %fprintf('%d - %8.2f - %d\n',i,sum( abs(cdata - cdatac)>0.05 ),pc~=oc) + + end + +end +%======================================================================= +function V = isocolors2(R,V,opt) +% ______________________________________________________________________ +% calculates a linear interpolated value of a vertex in R +% We have to calculate everything with double, thus larger images will +% cause memory issues. +% ______________________________________________________________________ + + if isempty(V), return; end + if ndims(R)~=3, error('MATLAB:isocolor2:dimsR','Only 2 or 3 dimensional input of R.'); end + if ~exist('opt','var'), opt=struct(); end + + def.interp = 'linear'; + opt = cat_io_checkinopt(opt,def); + + if isa(R,'double'), R = single(R); end + if ~isa(V,'double'), V = double(V); VD=0; else VD=1; end + + nV = size(V,1); + ndim = size(V,2); + + switch opt.interp + case 'nearest' + V = max(1,min(round(V),repmat(ndim,nV,1))); + V = R(sub2ind(size(R),V(:,2),V(:,1),V(:,3))); + case 'linear' + nb = repmat(shiftdim(double([0 0 0;0 0 1;0 1 0;0 1 1;1 0 0;1 0 1;1 1 0;1 1 1]'),-1),nV,1); + enb = repmat(shiftdim((ones(8,1,'double')*[size(R,2),size(R,1),size(R,3)])',-1),nV,1); + + % calculate the weight of a neigbor (volume of the other corner) and + w8b = reshape(repmat(V,1,2^ndim),[nV,ndim,2^ndim]); clear V; + % if the streamline ist near the boundery of the image you could be out of range if you add 1 + n8b = min(floor(w8b) + nb,enb); clear enb + n8b = max(n8b,1); + w8b = flipdim(prod(abs(n8b - w8b),2),3); + + % multiply this with the intensity-value of R + V = sum(R(sub2ind(size(R),n8b(:,2,:),n8b(:,1,:),n8b(:,3,:))) .* w8b,3); + end + if ~VD, V = single(V); end +end + %======================================================================= +function cdata = estimateWMdepthgradient(CS,cdata) +% ______________________________________________________________________ +% Estimates the maximum local gradient of a surface. +% Major use is the WM depth that grows with increasing sulcal depth. +% It measures the amount of WM behind the cortex, but more relevant is +% the amout of WM fibers that this reagion will add to the WM depth. +% The width of the street next to a house gives not the connectivity of +% this house, but the width of the entrance does! +% This measure can be improved by furhter information of sulcal depth. +% ______________________________________________________________________ + + %% + SV = CS.vertices; % Surface Vertices + SE = unique([CS.faces(:,1:2);CS.faces(:,2:3);CS.faces(:,3:-2:1)],'rows'); % Surface Edges + SEv = single(diff(cat(3,SV(SE(:,1),:),SV(SE(:,2),:)),1,3)); % Surface Edge Vector + SEL = sum(SEv.^2,2).^0.5; % Surface Edge Length + clear SEv + + + %% + cdata_l = inf(size(cdata),'single'); + cdata_h = zeros(size(cdata),'single'); + for i=1:size(SE,1) + val = (cdata(SE(i,2)) - cdata(SE(i,1)))*SEL(SE(i,1)); + cdata_l(SE(i,1)) = min([cdata_l(SE(i,1)),val]); + cdata_h(SE(i,1)) = max([cdata_h(SE(i,2)),val]); + end + cdata = cdata_h - cdata_l; +end + +","MATLAB" +"Neurology","ChristianGaser/cat12","development/cat_main_LAS.m",".m","29490","556","function [Yml,Ymg,Ycls,Ycls2,T3th] = cat_main_LAS(Ysrc,Ycls,Ym,Yb0,Yy,T3th,res,vx_vol,extopts,Tth) +% This is an exclusive subfunction of cat_main. +% ______________________________________________________________________ +% +% Local Adaptive Segmentation (LAS): +% +% This version of the local adaptive intensity correction includes a +% bias correction that based on a maximum filter for the WM and a mean +% filter of the GM to stabilize the correction in region with less WM. +% +% The extension based mostly on the assumption that the tissue next to +% the CSF (and high divergence sulci) has to be WM (maximum, high +% divergence) or GM. For each tissue a refined logical map is generated +% and used to estimate the local intensity threshold. +% +% It is important to avoid high intensity blood vessels in the process, +% because they will push down local WM and GM intensity. +% +% There are further regionwise correction, e.g. , to avoid overfitting in +% cerebellum, or adapt for age specific changes, e.g. enlarged ventricle. +% +% Based on this values a intensity transformation is used. Compared to +% the global correciton this has to be done for each voxel. To save time +% only a rough linear transformation is used. +% ______________________________________________________________________ +% +% [Yml,Ycls,Ycls2,T3th] = ... +% cat_main_LAS(Ysrc,Ycls,Ym,Yb0,Yy,T3th,res,vx_vol,PA,template) +% +% Yml .. local intensity correct image +% Ycls .. corrected SPM tissue class map +% Ycls2 .. ? +% T3th .. tissue thresholds of CSF, GM, and WM in Ysrc +% +% Ysrc .. (bias corrected) T1 image +% Ym .. intensity corrected T1 image (BG=0,CSF=1/3,GM=2/3,WM=1) +% Ycls .. SPM tissue class map +% Yb0 .. brain mask +% Yy .. deformation map +% res .. SPM segmentation structure +% vx_vol .. voxel dimensions +% PA .. CAT atlas map +% template .. ? +% ______________________________________________________________________ +% +% internal maps: +% +% Yg .. gradient map - edges between tissues +% Ydiv .. divergence map - sulci, gyris pattern, and blood vessels +% Yp0 .. label map - tissue classes (BG=0,CSF=1,GM=2,WM=3) +% +% Ysw .. save WM tissue map +% Ybv .. blood vessel map +% Ycp .. CSF / background area for distances estimation +% Ycd .. CSF / background distance +% Ycm .. CSF +% Ygm .. GM +% Ywm .. WM +% Yvt .. WM next to the ventricle map +% Ygmt .. cortical thickness map +% Ypp .. cortical percentage position map +% ______________________________________________________________________ +% +% Robert Dahnke (robert.dahnke@uni-jena.de) +% Structural Brain Mapping Group (https://neuro-jena.github.io/) +% Department of Neurology +% University Jena +% ______________________________________________________________________ +% $Id$ + + % set this variable to 1 for simpler debuging without reduceBrain + % function (that normally save half of processing time) + if isfield(extopts,'debug'); debug = extopts.debug; else, debug = 0; end + verb = extopts.verb-1; + vxv = 1/ mean(vx_vol); + dsize = size(Ysrc); + NS = @(Ys,s) Ys==s | Ys==s+1; % function to ignore brain hemisphere coding + LASstr = max(eps,min(1,extopts.LASstr)); % LAS strenght (for GM/WM threshold)3 + LAB = extopts.LAB; % atlas labels + cleanupstr = min(1,max(0,extopts.gcutstr)); % required to avoid critical regions + cleanupdist = min(3,max(1,1 + 2*cleanupstr)); + + + +%% --------------------------------------------------------------------- +% First, we have to optimize the segments using further information that +% SPM do not use, such as the gradient, divergence and distance maps. +% The gradient map (average of the first derivate of the T1 map) is an +% edge map and independent of the image intensity. It helps to avoid PVE +% regions and meninges. +% The divergence (second derivate of the T1 map) help to identfiy sulcal +% and gyral pattern and therefore to find WM and CSF regions for furhter +% corrections and to avoid meninges and blood vessels. +% Furhtermore, special assumption can be used. +% The first one is the maximum property of the WM in T1 data that allows +% using of a maxim filter for the GM/WM region. +% The second is the relative stable estimation of CSF/BG that allows to +% estimat a distance map. Because, most regions have a thin layer of +% GM around the WM we can avoid overestimation of the WM by the other +% maps (especially the divergence). +% --------------------------------------------------------------------- + fprintf('\n'); + stime = cat_io_cmd(' Prepare maps','g5','',verb); dispc=1; + + + % brain segmentation can be restricted to the brain to save time + [Ym,Yb,BB] = cat_vol_resize({Ym,Yb0},'reduceBrain',vx_vol,round(10/mean(vx_vol)),Yb0); + Yclsr=cell(size(Ycls)); for i=1:6, Yclsr{i} = cat_vol_resize(Ycls{i},'reduceBrain',vx_vol,BB.BB); end + + + % help maps to detect edges (Yg) and sulci/gyris (Ydiv) + Yg = cat_vol_grad(Ym,vx_vol); % mean gradient map + Ydiv = cat_vol_div(max(0.33,Ym),vx_vol); % divergence map + Yp0 = single(Yclsr{1})/255*2 + single(Yclsr{2})/255*3 + single(Yclsr{3})/255; % tissue label map + Yb = smooth3(Yb | (cat_vol_morph(Yb,'d',2*vxv) & Ym<0.8 & Yg<0.3 & Ym>0 & Yp0>0.2))>0.5; % increase brain mask, for missing GM + + + + %% adding of atlas information (for subcortical structures) + % ------------------------------------------------------------------- + stime = cat_io_cmd(' Prepare partitions','g5','',verb,stime); dispc=dispc+1; + + % map atlas to RAW space + for i=1:5 + try + Vl1A = spm_vol(extopts.cat12atlas{1}); + break + catch + % read error in parallel processing + pause(1) + end + end + Yl1 = cat_vol_ctype(round(spm_sample_vol(Vl1A,double(Yy(:,:,:,1)),double(Yy(:,:,:,2)),double(Yy(:,:,:,3)),0))); + Yl1 = reshape(Yl1,dsize); + + % load WM of the TPM or Dartel/Shooting Template for WMHs + Vtemplate = spm_vol(extopts.templates{end}); + Ywtpm = cat_vol_ctype(spm_sample_vol(Vtemplate(2),double(Yy(:,:,:,1)),double(Yy(:,:,:,2)),double(Yy(:,:,:,3)),0)*255,'uint8'); + Ywtpm = reshape(Ywtpm,dsize); spm_smooth(Ywtpm,Ywtpm,2*vxv); + Ywtpm = single(Ywtpm)/255; + + % brain segmentation can be restricted to the brain to save time + Yl1 = cat_vol_resize(Yl1 ,'reduceBrain',vx_vol,round(4/mean(vx_vol)),BB.BB); + Ywtpm = cat_vol_resize(Ywtpm,'reduceBrain',vx_vol,round(4/mean(vx_vol)),BB.BB); + if ~debug, clear Yy; end + + + %% adaptation of the LASstr depending on average basal values + LASmod = min(2,max(0,mean((Ym( NS(Yl1,LAB.BG) & Yg<0.1 & Ydiv>-0.05 & Yclsr{1}>4)) - 2/3) * 8)); + LASstr = min(1,max(0.05,LASstr * LASmod)); clear LASmod % adaptation by local BG variation + LASfs = 1 / max(0.05,LASstr); % smoothing filter strength + LASi = min(8,round(LASfs)); % smoothing interation (limited) + + + %% GM thickness (Ygmt) and percentage possition map (Ypp) estimation + % ------------------------------------------------------------------- + % The Ypp and Ygmt maps are used to refine the GM especially to correct + % highly myelinated GM regions. + % Interpolation look a little bit better, but I am not sure if it is + % necessary, so we do this only for lower/average resolutions. + % It is further unclear who to handle subcortical regions ... + if 0 + PBTinterpol = 0*mean(vx_vol)>0.9; + tic + if PBTinterpol + Yli = interp3(Yl1,1,'nearest'); + Ymi = interp3(Ym,1); + Ybi = interp3(single(Yb),1)>0.5; + Ywtpmi = interp3(Ywtpm,1); + Ydivi = interp3(Ydiv,1); + vx_voli = vx_vol/2; + else + Yli = Yl1; + Ymi = cat_vol_smooth3X(Ym,0.5/mean(vx_vol)); + Ybi = Yb; + Ywtpmi = Ywtpm; + Ydivi = Ydiv; + vx_voli = vx_vol; + end + + % PBT thickness and percentage position estimation + Ybgc = cat_vol_smooth3X(Ymi>0.7 & Ymi<0.95 & (NS(Yli,LAB.BG) | NS(Yli,LAB.TH)),2/mean(vx_voli)); % correction for subcortical structures + Ybgc = (Ymi-2/3) .* (Ymi>2/3 & Ybgc>0.3); + Ycsfd = cat_vbdist(2-Ybi-Ymi,(Ymi-Ybgc)<2.5/3); + Ywmh = cat_vol_morph((((Ymi-Ybgc+((Ywtpmi - Ydivi*0.1)>0.98)).*Ybi)*3-2)>0.5,'lc',1/mean(vx_voli)); % WM hyperintensity + clear Ywtpmi Ydivi; + Ywmd = cat_vbdist(((Ymi-Ybgc+Ywmh).*Ybi)*3-2,Ybi); + Ygmt = cat_vol_pbtp((Ymi-Ybgc+Ywmh).*Ybi*3,Ywmd,Ycsfd); + for i=1:1, Ygmt = cat_vol_localstat(Ygmt,Ygmt>0,1,1); end + Ypp = zeros(size(Ybi)); + Ypp(Ygmt>0) = min(Ybi(Ygmt>0),min(Ycsfd(Ygmt>0),Ygmt(Ygmt>0)-Ywmd(Ygmt>0))./max(eps,Ygmt(Ygmt>0))); + Ypp((Ymi>5/6 & Ybi & ~(NS(Yli,LAB.BG) | NS(Yli,LAB.TH))) | (Ymi>0.95 & Ybi)) = 1; + Ypp((((Ymi-Ybgc+Ywmh).*Ybi)*3-2)>0.5)=1; + Ypp = cat_vol_smooth3X(Ypp,0.5/mean(vx_voli)); + + % thickness correction and back to original resolution + Ygmt = Ygmt*mean(vx_vol); Ygmt(Ygmt>10 | isnan(Ygmt)) = 0; + clear Ycsfd Ywmd Ymi Ybi Yli vx_voli + if PBTinterpol + Ygmt = cat_vol_resize(Ygmt,'reduceV',1,2,10,'meanm'); + Ypp = cat_vol_resize(Ypp,'reduceV',1,2,10,'meanm'); + Ywmh = cat_vol_resize(Ywmh,'reduceV',1,2,10,'meanm'); + end + [D,I] = cat_vbdist(single(Ygmt>eps),Yp0>0); Ygmt = Ygmt(I); clear D I; + + % subcortical structures + %Ypp( NS(Yl1,LAB.BG) & Ym>2.1/3 & Ym<2.9/3 )=0.5; + %Ypp = cat_vol_median3(Ypp,Ypp<0.1 & Ym>=1.9/3 & Yb,true(size(Ym))); + + Ywmh = Ywmh.*0; + else + [Ygmt,Ypp] = cat_vol_pbt( (Yp0 + (Ym*3 .* (Yp0>0)))/2 ); + Ygmt = Ygmt*mean(vx_vol); Ygmt(Ygmt>10 | isnan(Ygmt)) = 0; + [D,I] = cat_vbdist(single(Ygmt>eps),Yp0>0); Ygmt = Ygmt(I); clear D I; + end + + %% helping segments + % ------------------------------------------------------------------- + stime = cat_io_cmd(' Prepare segments','g5','',verb,stime); dispc=dispc+1; + % Ybb .. don't trust SPM to much by using Yp0 because it may miss some areas! Shood be better now with MRF. + Ybb = cat_vol_morph((Yb & Ym>1.5/3 & Ydiv<0.05) | Yp0>1.5,'lo',vxv); + + % Ysw .. save WM and blood vessels mpas + % Ybv .. possible blood vessels + Ysw = cat_vol_morph(Yclsr{2}>128 & (min(1,Ym)-Ydiv)<1.5,'lc',vxv*2) & (Ym-Ydiv)>5/6; % 1.2 + Ybv = ((min(1,Ym) - Ydiv + Yg)>2.0 | (Yclsr{5}>16 & Ym<0.6 & Yclsr{1}<192)) & ... + ~cat_vol_morph(Ysw,'d',1) & Ym>0.2; + + % Ycp .. for CSF/BG distance initialization + Ycp = (Yclsr{3}>240 & Ydiv>0 & Yp0<1.1 & Ym<0.5) | ... % typcial CSF + (Yclsr{5}>8 & Yclsr{2}<32 & Ym<0.6 & Ydiv>0) | ... % venes + ((Ym-Ydiv/4<0.4) & Yclsr{3}>4 & Yclsr{3}>16) | ... % sulcal CSF + (single(Yclsr{6})+single(Yclsr{5})+single(Yclsr{4}))>192 | ... % save non-csf + ~cat_vol_morph(Ybb,'lc',5) | ... % add background + Ym<0.3 | Ypp2.5),Yp0>0.5,vx_vol); % WM distance for skelelton + Ycp(smooth3(Ycp)>0.4)=1; % remove some meninges + Ycd = cat_vbdist(single(Ycp),~Ycp,vx_vol); % real CSF distance + Ycd((Ym-Ydiv<2/3 | Ydiv>0.1) & Yclsr{3}>4 & Yclsr{3}>1) = ... % correction for sulci + min(Ycd((Ym-Ydiv<2/3 | Ydiv>0.1) & Yclsr{3}>4 & Yclsr{3}>1),1.5); % maybe a second distance estimation??? + % we need to remove strong edge regions, because here is no GM layer between CSF and WM ??? + % Yb = cat_vol_morph(~Ycp | (Ycls{3}>128),'lc',1); + Ybd = cat_vbdist(single(~Yb),Yb,vx_vol); + Yvt = (Yg+abs(Ydiv))>0.4 & smooth3(single(Yclsr{1})/255)<0.5 & Ybd>20 & ... + cat_vol_morph(Yclsr{3}>8,'d',vxv) & cat_vol_morph(Yclsr{2}>8,'d',vxv); + Yvt = smooth3(Yvt)>0.7; + Yvt = smooth3(Yvt)>0.2; + + + + %% final tissue maps: Ycm = CSF, Ygm = GM, Ywm = WM + % ------------------------------------------------------------------- + Ysc = Ycp & Yb & Yclsr{3}>192 & ~Ybv & Ym<0.45 & Yg<0.1; + Ycm = Ycp & Yb & Yclsr{3}>192 & ~Ybv & (Yb | Ym>1/6) & Ym<0.45 & Yg<0.25 & Ym>0; % & Ydiv>-0.05; + %Ycm = Ycm | (Yb & (Ym-max(0,Ydiv))<0.5); + Ywm = (Ysw | Yclsr{2}>252 | ((Ycd-Ydiv)>2 & Ydiv<0 & (Ym-Ydiv)>(0.9+LASstr*0.05) & Yb) | ... % save WM + ((Ycd-Ydiv.*Ycd)>4 & (Ydiv<-0.01) & Yb & Ym>0.5 & Ybd<20 & Ycd>2) | ... + (mean(cat(4,Ym,Yp0/3),4)-Ydiv)>0.9 & Ym<1.1 & Yp0>2.1) & ... + ... ((Ycd-Ydiv*5)>3 & (Ydiv<-0.01 & (Yg + max(0,0.05-Ycd/100))<0.1) & Yb & Ym>0.4 & Ybd<20 & Ycd>2.5) ) & ... % further WM + ~Ybv & Yb & Ybd>1 & (Ycd>1.0 | (Yvt & Yp0>2.9) | (mean(cat(4,Ym,Yp0/3),4)-Ydiv)>0.9 & Ym<1.1 & Yp0>2.1) & (Yg+Ydiv<(Ybd/50) | (Ydiv-Ym)<-1.2); % Ybd/800 + Ycd/50 + Ywm = Ywm & ~(Ygmt<3 & Ycd<3 & (Ym-Ydiv)<0.90); + Ywms = smooth3(Ywm); Ywm(Ywms>0.75)=1; clear Ywms; + %% + Ygm = ~Yvt & Ybb & ~Ybv & ~Ywm & ~Ycm & Ycd>0.5 & (Ym-Ydiv-max(0,2-Ycd)/10)<0.9 & ... (Ym+Ydiv)>0.5 & ... ~Ysk & + (Yclsr{1}>4 | (Ym>0.7 & Yclsr{3}>64) | Ycd<(Ym+Ydiv)*3 ) & Ypp>0.2 & ... + smooth3(Yg>(Ybd/800) & Yclsr{2}<240 )>0.6; % avoid GM next to hard boundies in the middle of the brain + Ygx = Ybb & ~Ycm & Ym>1/3 & Ym<2.8/3 & Yp0<2.5 & Yg<0.4 & (Ym-Ydiv)>1/3 & (Ym-Ydiv)<1; Ygx(smooth3(Ygx)<0.5) = 0; + Ygm = Ygm | Ygx; clear Ygx; + Ygm = Ygm | (Ym>1.5/3 & Ym<2.8/3 & Yp0<2.5 & ~Ycm & Ybb); + Ygm = Ygm | (Ygmt>eps & Ygmt<8 & Ycd0))*(1.5-Ym) & Ym<0.98 & Yl1 & ~Yvt & Yl1<3 & Yp0<2.5 & Yp0>1.5); + Ygm = Ygm | (Yp0>2 & Yp0<2.5); + %% + %Ygm = Ygm & Ypp>0.5/max(1,Ygmt*2) & ~((Ypp-Ygmt/10)>0.2 & Ygmt>max(2,min(3,mean(Ygmt(Ygmt>0))*0.75))); % & ~Ywmh; + Ygm = Ygm & (Ygmt>2 | Ypp>0.2); + Ygms = smooth3(Ygm); Ygm(Ygms<0.25)=0; Ygm(Ygms>0.75 & Ypp>0.2)=1; clear Ygms; + + %% Ygw = Ygm & smooth3(Ywm)<0.1 & smooth3(Ycm)<0.4 & Ycd>0 & Ycd<2 & Ydiv<0.4 & Ydiv>-0.3 & Yg<0.1; %& (Ydiv>-0.4 | Ycd>1.5) + if ~debug, clear Ybv Ycp; end %Ycd + + if debug>1 + try %#ok + [pth,nam] = spm_fileparts(res.image0(1).fname); tpmci=0; + tpmci=tpmci+1; tmpmat = fullfile(pth,reportfolder,sprintf('%s_%s%02d%s.mat',nam,'LAS',tpmci,'prepeaks')); + save(tmpmat); + end + end + + + + %% ------------------------------------------------------------------ + % SPM GM segmentation can be affected by inhomogeneities and some GM + % is missclassified as CSF/GM (Ycls{5}). But for some regions we can + % trust these information more + % ------------------------------------------------------------------ + Ybd = cat_vbdist(single(~Yb),Yb,vx_vol); + Ycbp = cat_vbdist(single(NS(Yl1,LAB.CB)),Yb,vx_vol); % next to the cerebellum + Ycbn = cat_vbdist(single(~NS(Yl1,LAB.CB)),Yb,vx_vol); % not to deep in the cerebellum + Ylhp = cat_vbdist(single(mod(Yl1,2)==1 & Yb & Yl1>0),Yb,vx_vol); % GM next to the left hemisphere + Yrhp = cat_vbdist(single(mod(Yl1,2)==0 & Yb & Yl1>0),Yb,vx_vol); % GM next to the righ hemishpere + Ybv2 = Yclsr{5}>2 & Ym<0.7 & Ym>0.3 & Yb & (... + ((Ylhp+Ybd/2)0.5; + Ybvv = (Ym-max(0,6-abs(Ycbp-6))/50)<0.6 & Ym>0.4 & Yb & Ycbp<8 & Ycbp>1; + + % subcortical map refinements + THth = 0.8 - LASstr*0.6; %0.5; % lower more thalamus + YTH = NS(Yl1,LAB.TH) | (cat_vol_morph(NS(Yl1,LAB.TH),'d',3) & Ym>0.5 & Yclsr{1}>128); + Ytd = cat_vbdist(single(Ym<0.45),YTH | NS(Yl1,LAB.BG),vx_vol); Ytd(Ytd>2^16)=0; % CSF distance in the TH + Yxd = cat_vbdist(single(NS(Yl1,LAB.BG)),YTH,vx_vol); Yxd(Yxd>2^16)=0; % BG distance in the TH + %Yyd = cat_vbdist(single(NS(Yl1,LAB.TH)),NS(Yl1,LAB.BG),vx_vol); Yyd(Yyd>2^16)=0; % TH distance in the BG + Yss = NS(Yl1,LAB.BG) | NS(Yl1,LAB.TH); + Yss = Yss | (cat_vol_morph(Yss,'d',vxv*2) & Ym>2.25/3 & Ym<2.75/3 & Ydiv>-0.01); % add ihger tissue around mask + Yss = Yss | (cat_vol_morph(Yss,'d',vxv*3) & NS(Yl1,LAB.VT) & Yp0>1.5 & Yp0<2.3); % add lower tissue around mask + Yss = Yss & Yp0>1.5 & (Yp0<2.75 | (Ym<(2.5+LASstr*0.45)/3 & Ydiv>-0.05)); % by intensity + Yss = Yss | ((Yxd./max(eps,Ytd+Yxd))>THth/2 & (Yp0<2.75 | (Ym<(2.75+LASstr*0.20)/3 & Ydiv>-0.05))); + % save TH by distances - for overcorrected images + Yss = cat_vol_morph(Yss,'o'); + Ynw = (Yxd./max(eps,Ytd+Yxd))>THth/2 | (NS(Yl1,LAB.BG) & Ydiv>-0.01); + if ~debug, clear Ytd Yxd ; end + % increase CSF roi + Yvt = cat_vol_morph( (NS(Yl1,LAB.VT) | cat_vol_morph(Ycm,'o',3) ) ... + & Ycm & ~NS(Yl1,LAB.BG) & ~NS(Yl1,LAB.TH) & Ybd>30,'d',vxv*3) & ~Yss; % ventricle roi to avoid PVE GM between WM and CSF + Ycx = (NS(Yl1,LAB.CB) & ((Ym-Ydiv)<0.55 | Yclsr{3}>128)) | (((Ym-Ydiv)<0.45 & Yclsr{3}>8)| Yclsr{3}>240); + % in the crebellum tissue can be differentated by div etc. + Ycwm = NS(Yl1,LAB.CB) & (Ym-Ydiv*4)>5/6 & Ycd>3 & Yg>0.05; + Yccm = NS(Yl1,LAB.CB) & Ydiv>0.02 & Ym<1/2 & Yg>0.05; + Ybwm = (Ym-Ydiv*4)>0.9 & Ycd>3 & Yg>0.05; %Ydiv<-0.04 & Ym>0.75 & Ycd>3; + Ybcm = Ydiv>0.04 & Ym<0.55 & Yg>0.05; + % correction 1 of tissue maps + Ywmtpm = (Ywtpm.*Ym.*(1-Yg-Ydiv).*cat_vol_morph(NS(Yl1,1).*Ybd/5,'e',1))>0.6; % no WM hyperintensities in GM! + Ygm = Ygm | (Yss & ~Yvt & ~Ycx & ~Ybv2 & ~Ycwm & ~(Yccm | Ybcm)); + Ygm = Ygm & ~Ywmtpm & ~Ybvv; % no WMH area + Ygm = Ygm & ~Yvt; % & ~Ywmh; + Ywm = (Ywm & ~Yss & ~Ybv2 & ~Ynw) | Ycwm | Ybwm; clear Ybwm; %& ~NS(Yl1,LAB.BG) + Ywmtpm(smooth3(Ywmtpm & Ym<11/12)<0.5)=0; + Ywm = Ywm & ~Ywmtpm & ~Ybvv & ~Yss; % no WM area + Ycm = Ycm | ( (Ycx | Yccm | Ybcm) & Yg<0.2 & Ym>0 & Ydiv>-0.05 & Ym<0.3 & Yb ) | Ybvv; + if ~debug, clear Ycwm Yccm; end + % mapping of the brainstem to the WM (well there were some small GM + % structures, but the should not effect the local segmentation to much. + Ybs = cat_vol_morph(NS(Yl1,LAB.BS) & Ym<1.2 & Ym>0.9 & Yp0>2.5,'c',2*vxv) & Ym<1.2 & Ym>0.9 & Yp0>1.5; + Ygm = (Ygm & ~Ybs & ~Ybv2 & ~Ywm) | Yss; + Ywm = Ywm | (Ybs & Ym<1.1 & Ym>0.9 & Yp0>1.5) ; + if ~debug, clear Ycx; end + + %% Parahippocampal Gyrus for surface reconstruction + % noch nicht n?tig + %{ + Yphcg = Ywtpm>0.1 & Ydiv<0.02 & Ym>2.2/3 & Ym<3.5/3 &... + cat_vol_morph(NS(Yl1,LAB.PH),'d',3/mean(vx_vol)) & ... + ~cat_vol_morph(NS(Yl1,LAB.BS) | NS(Yl1,LAB.CB),'d',1/mean(vx_vol)); + Yphcg = cat_vol_morph(Yphcg & mod(Yl1,2)==0,'l') | ... + cat_vol_morph(Yphcg & mod(Yl1,2)==1,'l'); + %} + + + %% back to original resolution for full bias field estimation + [Ycm,Ygm,Ywm] = cat_vol_resize({Ycm,Ygm,Ywm},'dereduceBrain',BB); % ,Ygw + [Yvt,Yb,Yss,Ybb,Ysc,Ybs,Ybv2] = cat_vol_resize({Yvt,Yb,Yss,Ybb,Ysc,Ybs,Ybv2},'dereduceBrain',BB); + [Ym,Yp0,Yl1] = cat_vol_resize({Ym,Yp0,Yl1},'dereduceBrain',BB); + Ybd = cat_vol_resize(Ybd,'dereduceBrain',BB); + %Yphcg = cat_vol_resize(Yphcg,'dereduceBrain',BB); + [Yg,Ydiv] = cat_vol_resize({Yg,Ydiv},'dereduceBrain',BB); + [Ygmt,Ypp] = cat_vol_resize({Ygmt,Ypp},'dereduceBrain',BB); + [Ywd] = cat_vol_resize(Ywd,'dereduceBrain',BB); % Ysk + [Ycd] = cat_vol_resize(Ycd,'dereduceBrain',BB); % Ysk + clear Yclso Ybv; + + if debug>1 + try %#ok % windows requires this... i don't know why ... maybe the file size + tpmci=tpmci+1; tmpmat = fullfile(pth,reportfolder,sprintf('%s_%s%02d%s.mat',nam,'LAS',tpmci,'prepeaks')); + save(tmpmat); + end + end + + +%% --------------------------------------------------------------------- +% Now, we can estimate the local peaks +% --------------------------------------------------------------------- + % Estimation of the local WM threshold with ""corrected"" GM voxels to + % avoid overfitting (see BWP cerebellum). + % CSF is problematic in high contrast or skull-stripped image should + % not be used here, or in GM peak estimation + mres = 1.1; + stime = cat_io_cmd(' Estimate local tissue thresholds','g5','',verb,stime); dispc=dispc+1; + Ysrcm = cat_vol_median3(Ysrc.*Ywm,Ywm,Ywm); + rf = [10^5 10^4]; + T3th3 = max(1,min(10^6,rf(2) / (round(T3th(3)*rf(1))/rf(1)))); + Ysrcm = round(Ysrcm*T3th3)/T3th3; + Ygw2 = Ycls{1}>128 & Ym>2/3-0.04 & Ym<2/3+0.04 & Ygm .*Ydiv>0.01; + Ygw2 = Ygw2 | (Ycls{1}>128 & Yg<0.05 & abs(Ydiv)<0.05 & ~Ywm & Ym<3/4); % large stable GM areas - like the BWP cerebellum + Ygw3 = Ycls{3}>128 & Yg<0.05 & ~Ywm & ~Ygm & Ywd<3; + Ygw3(smooth3(Ygw3)<0.5)=0; + [Yi,resT2] = cat_vol_resize(Ysrcm,'reduceV',vx_vol,mres,32,'max'); % maximum reduction for the WM + %% + if cat_stat_nanmean(Ym(Ygw3))>0.1, % not in images with to low CSF intensity (error in skull-stripped) + Ygi = cat_vol_resize(Ysrc.*Ygw2*T3th(3)/mean(Ysrc(Ygw2(:))) + ... + Ysrc.*Ygw3*T3th(3)/mean(Ysrc(Ygw3(:))),'reduceV',vx_vol,mres,32,'meanm'); clear Ygw2; % mean for other tissues + else + % mean for other tissues + Ygi = cat_vol_resize(Ysrc.*Ygw2*T3th(3)/mean(Ysrc(Ygw2(:))),'reduceV',vx_vol,mres,32,'meanm'); clear Ygw2; + end + for xi=1:2*LASi, Ygi = cat_vol_localstat(Ygi,Ygi>0,2,1); end; Ygi(smooth3(Ygi>0)<0.3)=0; + Yi = cat_vol_localstat(Yi,Yi>0,1,3); % one maximum for stabilization of small WM structures + Yi(Yi==0 & Ygi>0)=Ygi(Yi==0 & Ygi>0); + for xi=1:2*LASi, Yi = cat_vol_localstat(Yi,Yi>0,2,1); end % no maximum here! + Yi = cat_vol_approx(Yi,'nh',resT2.vx_volr,2); Yi = cat_vol_smooth3X(Yi,LASfs); + Ylab{2} = max(eps,cat_vol_resize(Yi,'dereduceV',resT2)); + % Ylab{2} = Ylab{2} .* mean( [median(Ysrc(Ysw(:))./Ylab{2}(Ysw(:))),1] ); + if debug==0; clear Ysw; end + + %% update GM tissue map + %Ybb = cat_vol_morph((Yb & Ysrc./Ylab{2}<(T3th(1) + 0.25*diff(T3th(1:2))) & Ydiv<0.05) | Yp0>1.5,'lo',1); + Ygm(Ysrc./Ylab{2}>(T3th(2) + 0.90*diff(T3th(2:3)))/T3th(3))=0; % correct GM mean(T3th([2:3,3]))/T3th(3) + Ygm(Ysrc./Ylab{2}<(T3th(2) + 0.75*diff(T3th(2:3)))/T3th(3) & ... + Ysrc./Ylab{2}<(T3th(2) - 0.75*diff(T3th(2:3)))/T3th(3) & ... + Ydiv<0.3 & Ydiv>-0.3 & Ybb & ~Ywm & ~Yvt & ~Ybv2 & Ycls{1}>48)=1; + Ygm = Ygm | (Ygmt>eps & Ygmt<8 & Ycd0))*(1.5-Ym) & NS(Yl1,1) & ~Ybs); + Ygm = Ygm & Ypp>0.5/max(1,Ygmt) & ~((Ypp-Ygmt/10)>0.2 & Ygmt>max(2,min(3,mean(Ygmt(Ygmt>0))*0.75))); + Ywmd2 = cat_vbdist(single(Ywm),Yb); + Ygx = Ywmd2-Ym+Ydiv>0.5 & Ym+0.5-Ydiv-Yg-Ywmd2/10>1/3 & ~Ybv2 & ... low intensity tissue + ~(Ym-min(0.2,Yg+Ywmd2/10-Ydiv)<1/4) & Yg0.5 & ~Ywm; + Ygx(smooth3(Ygx)<0.5)=0; + Ygm = Ygm | Ygx; % correct gm (spm based) + %% + Ycm = ~Ygm & ~Ywm & ~Ybv2 & Yg<0.6 & (Ycm | (Yb & (Ysrc./Ylab{2})<((T3th(1)*0.5 + 0.5*T3th(2))/T3th(3)))); + % + Ycp = (Ycls{2}<128 & Ydiv>0 & Yp0<2.1 & Ysrc./Ylab{2}32 & Ycls{2}<32 & Ysrc./Ylab{2}0) | ... % venes + ((Ym-Ydiv<0.4) & Ycls{3}>4 & Ycls{3}>16 & Ysrc./Ylab{2}192 | ... % save non-csf + Ysrc./Ylab{2}0.4)=1; % remove some meninges + Ycp(Ypp<(0.2+0.1*max(0,5-Ygmt)) & ~Yss)=1; + Ycd = cat_vbdist(single(Ycp),~Ycp,vx_vol); + %% + Ygm = Ygm & ~Ycm & ~Ywm & Ywd<5; % & ~Ywmh; % & ~Ybvv & ~Ysk + Ygm = Ygm | (NS(Yl1,1) & Ybd<20 & (Ycd-Ydiv)<2 & Ycls{1}>0 & ~Ycm & Ybb & Ym>0.6 & Yg0.5/max(1,Ygmt*2) & ~((Ypp-Ygmt/10)>0.2 & Ygmt>max(2,min(3,mean(Ygmt(Ygmt>0))*0.75))); + Ybb = cat_vol_morph(smooth3(Ygm | Ywm | Yp0>1.5 | (Ym>1.2/3 & Ym<3.1/3 & Yb))>0.6,'lo',min(1,vxv)); % clear Yp0 Yvt + Ygm(~Ybb)=0; Ygm(smooth3(Ygm)<0.3)=0; + Ygm(smooth3(Ygm)>0.4 & Ysrc./Ylab{2}>mean(T3th(1)/T3th(2)) & Ysrc./Ylab{2}<(T3th(2)*0.1+0.9*T3th(3)) & Ypp>0.2)=1; + Ygm = (Ygm & Ypp>0.2 & Ywd<3) | (Ygm & Ywd>=2); + %% + if debug==0; clear Ybb Ybd Yvt Ybvv Ycp Ycd Yl1 Yss; end %Ydiv Yg + %Ygm = Ygm & smooth3(smooth3(Ypp)>0.1)>0.7 & Ym<0.90; + + %% GM +% Yi = (Ysrc./Ylab{2} .* Ygm , Ysrc./Ylab{2}.*Ywm.*Ybs.*(T3th(2)+0.8*diff(T3th(2:3)))/T3th(3)); +% Yi(Ybv2) = Ysrc(Ybv2)./Ylab{2}(Ybv2) .* T3th(2)/mean(T3th(1:2)); + Yi = Ysrc./Ylab{2} .* Ygm; + Yi = round(Yi*rf(2))/rf(2); + % Yi(Ybv2) = Ysrc(Ybv2)./Ylab{2}(Ybv2) .* T3th(2)/mean(T3th(1:2)); % ???? + Yi(Ybs) = Ysrc(Ybs)./Ylab{2}(Ybs) .* T3th(2)/T3th(3); + Yi = cat_vol_median3(Yi,Yi>0.5,Yi>0.5); +% Ycmx = smooth3(Ycm & Ysrc<(T3th(1)*0.8+T3th(2)*0.2))>0.9; Tcmx = mean(Ysrc(Ycmx(:))./Ylab{2}(Ycmx(:)))*T3th(3); +% Yi(Ycmx) = Ysrc(Ycmx)./Ylab{2}(Ycmx) .* T3th(2)/Tcmx; + %Yii = Ysrc./Ylab{2} .* Ycm * T3th(2) / cat_stat_nanmedian(Ysrc(Ycm(:))); + [Yi,Yii,resT2] = cat_vol_resize({Yi,Ylab{2}/T3th(3)},'reduceV',vx_vol,1,32,'meanm'); + for xi=1:2*LASi, Yi = cat_vol_localstat(Yi,Yi>0,3,1); end + Yi = cat_vol_approx(Yi,'nh',resT2.vx_volr,2); + Yi = min(Yi,Yii*(T3th(2) + 0.90*diff(T3th(2:3)))/T3th(3)); + Yi = cat_vol_smooth3X(Yi,LASfs); + Ylab{1} = cat_vol_resize(Yi,'dereduceV',resT2).*Ylab{2}; + %Ylab{1}(Ygm) = Ysrc(Ygm); Ylab{1} = cat_vol_smooth3X(Ylab{1},LASfs); % can lead to overfitting + Ycm = (single(Ycls{3})/255 - Yg*4 + abs(Ydiv)*2)>0.5 & Ysrc<(Ylab{1}*mean(T3th([1,1:2]))/T3th(2)); + %Ycm & Ysrc<(Ylab{1}*mean(T3th(1:2))/T3th(2)) & Yg<0.1; + Ycm(smooth3(Ycm)<0.5)=0; + Ycm(Yb & cat_vol_morph(Ysrc128 | (~Yb & Yg<=0.001),'e',4*vxv); + [Yx,Yc,resT2] = cat_vol_resize({round(Ysrc./Ylab{2} .* Ynb .* ((Ysrc./Ylab{2})<0.1) * rf(2))/rf(2),... + round(Ysrc./Ylab{2} .* (smooth3(Ycm | Ysc)>0.5) * rf(2))/rf(2)},'reduceV',vx_vol,8,16,'min');% only pure CSF !!! + Yx(Yc>0)=0; Yc(Yx>0)=0; + meanYx = min(median(Yc(Yc(:)>0)),median(Yx(Yx(:)>0))); + meanYc = max(median(Yc(Yc(:)>0)),median(Yx(Yx(:)>0))); + stdYbc = mean([std(Yc(Yc(:)>0)),std(Yx(Yx(:)>0))]); + %Yx = min(max(meanYx/2,Yx),min(meanYx*4,meanYc/2)); + %Yc = min(max(meanYc/2,Yx),meanYc/2); + Yxa = cat_vol_approx(Yx ,'nh',resT2.vx_volr,16); %+(Yb>0).*stdYbc + Yc.*meanYb/max(eps,meanYc) + Yca = cat_vol_approx(Yc + min(max( meanYx + stdYbc , meanYc - stdYbc ),... + Yx.*meanYc/max(eps,meanYx)),'nh',resT2.vx_volr,16); % + Yb.*meanYc/max(eps,meanYb) + Yca = Yca*0.7 + 0.3*max(mean(Yca(:)),T3th(1)/T3th(3)); + %% + Yxa = cat_vol_smooth3X(Yxa,LASfs*2); + Yca = cat_vol_smooth3X(Yca,LASfs*2); + Ylab{3} = cat_vol_smooth3X(cat_vol_resize(Yca,'dereduceV',resT2).*Ylab{2},LASfs*2); + Ylab{6} = cat_vol_smooth3X(cat_vol_resize(Yxa,'dereduceV',resT2).*Ylab{2},LASfs*2); + clear Yxa Yca Yx Yc Y %Ydiv + + %% local intensity modification of the original image + % -------------------------------------------------------------------- + Yml = zeros(size(Ysrc)); + Yml = Yml + ( (Ysrc>=Ylab{2} ) .* (3 + (Ysrc-Ylab{2}) ./ max(eps,Ylab{2}-Ylab{1})) ); + Yml = Yml + ( (Ysrc>=Ylab{1} & Ysrc=Ylab{3} & Ysrc10)=10; + + + %% global + Ymg = max(eps,Ysrc./Ylab{2}); + Ymg = cat_main_gintnorm(Ymg*Tth.T3th(5),Tth); + + %% + if debug>1 + try %#ok % windows requires this... i don't know why + tpmci=tpmci+1; tmpmat = fullfile(pth,reportfolder,sprintf('%s_%s%02d%s.mat',nam,'LAS',tpmci,'postpeaks')); + save(tmpmat); + end + end + + %% fill up CSF in the case of a skull stripped image + if max(res.mn(res.lkp==5 & res.mg'>0.1)) < mean(res.mn(res.lkp==3 & res.mg'>0.3)) + YM = cat_vol_morph(Yb,'d'); + Ymls = smooth3(max(Yml,YM*0.5)); + Yml(YM & Yml<0.5)=Ymls(YM & Yml<0.5); + clear Ymls YM + end + + + %% class correction and second logical class map Ycls2 + Ynwm = Ywm & ~Ygm & Yml/3>0.95 & Yml/3<1.3; + Ynwm = Ynwm | (smooth3(Ywm)>0.6 & Yml/3>5/6); Ynwm(smooth3(Ynwm)<0.5)=0; + Yngm = Ygm & ~Ywm & Yml/3<0.95; Yngm(smooth3(Yngm)<0.5)=0; + Yncm = ~Ygm & ~Ywm & ((Yml/3)>1/6 | Ycls{3}>128) & (Yml/3)<0.5 & Yb; + Ycls{2} = cat_vol_ctype(single(Ycls{2}) + (Ynwm & ~Yngm & Yp0>=1.5)*256 - (Yngm & ~Ynwm & Yp0>=2)*256,'uint8'); + Ycls{1} = cat_vol_ctype(single(Ycls{1}) - (Ynwm & ~Yngm & Yp0>=1.5)*256 + (Yngm & ~Ynwm & Yp0>=2)*256,'uint8'); + %Ycls{3} = cat_vol_ctype(single(Ycls{3}) - ((Ynwm | Yngm) & Yp0>=2)*256,'uint8'); + %Ycls{3} = cat_vol_ctype(single(Ycls{3}) + (Yb & Yml<1.1 & ~Ynwm & ~Yngm)*256,'uint8'); + Ycls{1} = cat_vol_ctype(single(Ycls{1}) - (Yb & Yml<1.1 & ~Ynwm & ~Yngm)*256,'uint8'); + Ycls{2} = cat_vol_ctype(single(Ycls{2}) - (Yb & Yml<1.1 & ~Ynwm & ~Yngm)*256,'uint8'); + Ycls2 = {Yngm,Ynwm,Yncm}; + clear Yngm Ynwm Yncm; + + %% + Yml = Yml/3; + cat_io_cmd('','','',verb,stime); + % if debug + % cat_io_cmd(' ','','',verb,stime); + % else + % cat_io_cmd(' ','','',verb,stime); + % cat_io_cmd('cleanup',dispc,'',verb); + % end + +end + +","MATLAB" +"Neurology","ChristianGaser/cat12","development/Atlas_ROI_tissue.m",".m","1669","51","function Atlas_ROI_tissue +% Get probable tissues for all ROIs using Shooting template and its tissue +% probabilities and ROIs of atlases +%_______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +% get all available atlases +pth = cat_get_defaults('extopts.pth_templates'); +P = spm_select('FPList',pth,'.*csv'); + +Vt = spm_vol(fullfile(pth,'Template_4_GS.nii')); + +for i=1:size(P,1) + [pth, atlas] = spm_fileparts(P(i,:)); + V = spm_vol(fullfile(pth,[atlas '.nii'])); + data = round(spm_read_vols(V)); + + [Vtpm,gm] = cat_vol_imcalc([V Vt(1)],'','i2',struct('interp',1,'verb',0)); + [Vtpm,wm] = cat_vol_imcalc([V Vt(2)],'','i2',struct('interp',1,'verb',0)); + [Vtpm,csf] = cat_vol_imcalc([V Vt(3)],'','i2',struct('interp',1,'verb',0)); + + csv = cat_io_csv(P(i,:),'','',struct('delimiter',';')); + if strcmp(csv{1,2},'ROIname') + ind = 2; + else + ind = 3; + end + fprintf('Atlas %s\n',atlas); + fprintf('%6s\t%6s\t%6s\t%3s\t%s\n','relGM','relWM','relCSF','ID', 'ROIname') + for j=2:size(csv,1) + ID = csv{j,1}; + ROIname = csv{j,ind}; + ROI = find(data == ID); + if ~isempty(ROI) + ROIgm = sum(gm(ROI)); + ROIwm = sum(wm(ROI)); + ROIcsf = sum(csf(ROI)); + ROIsum = ROIgm + ROIwm + ROIcsf; + else + ROIgm = 0; ROIwm = 0; ROIcsf = 0; + ROIsum = 1; + end + fprintf('%3.3f\t%3.3f\t%3.3f\t%d\t%s\n',ROIgm/ROIsum, ROIwm/ROIsum, ROIcsf/ROIsum, ID, ROIname) + end +end","MATLAB" +"Neurology","ChristianGaser/cat12","development/correct_tpm2one.m",".m","748","28","function correct_tpm2one +% correct last class of TPM or GS-Template to ensure sum=1 + +P = spm_select(Inf,'image','Select TPMs or GS-Templates'); + +for i=1:size(P,1) + N = nifti(deblank(P(i,:))); + dat = zeros(N.dat.dim); + dat(:,:,:,:) = N.dat(:,:,:,:); + nc = N.dat.dim(4); + sum_dat = sum(dat(:,:,:,1:(nc-1)),4); + sum_dat(sum_dat>1) = 1; + + % correct last class and ensure sum=1 + dat(:,:,:,nc) = 1 - sum_dat; + + [pth,nam,ext] = spm_fileparts(N.dat.fname); + + % write corrected TPM + No = nifti; + No.dat = file_array(fullfile(pth,['c' nam ext]),size(dat),N.dat.dtype,... + N.dat.offset,N.dat.scl_slope,N.dat.scl_inter); + No.mat = N.mat; + No.mat0 = N.mat; + No.descrip = N.descrip; + create(No); + No.dat(:,:,:,:) = dat(:,:,:,:); +end","MATLAB" +"Neurology","ChristianGaser/cat12","development/Atlas_JulichBrain2CAT12.m",".m","7040","189","function Atlas_JulichBrain2CAT12 +% Convert JulichBrain atlas to CAT12 atlas +% +% https://search.kg.ebrains.eu/instances/f1fe19e8-99bd-44bc-9616-a52850680777 +%_______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +%Vlh = spm_vol(spm_select(1,'image','Select lh image',{},pwd,'JulichBrain_MPMAtlas_l_N10_nlin2Stdicbm152asym2009c')); +%Vrh = spm_vol(spm_select(1,'image','Select rh image',{},pwd,'JulichBrain_MPMAtlas_r_N10_nlin2Stdicbm152asym2009c')); +Vlh = spm_vol(fullfile(spm('dir'),'toolbox','cat12','development','JulichBrainAtlas_3.1_207areas_MPM_lh_MNI152.nii')); +Vrh = spm_vol(fullfile(spm('dir'),'toolbox','cat12','development','JulichBrainAtlas_3.1_207areas_MPM_rh_MNI152.nii')); +lh = spm_read_vols(Vlh); +rh = spm_read_vols(Vrh); + +% set doubled defined areas at midline to 0 +lhgt0 = lh>0; +rhgt0 = rh>0; +ind = find(lhgt0 & rhgt0); +lh(ind) = 0; +rh(ind) = 0; + +% left/right coding +atlas = zeros(size(lh)); +atlas(lhgt0) = 2*lh(lhgt0) - 1; +atlas(rhgt0) = 2*rh(rhgt0); + +% replace remaining holes with median value +holes = atlas > 0; +holes = (cat_vol_morph(holes,'c') - holes) > 0; +tmp = atlas; %cat_vol_median3c(single(atlas)); +atlas(holes) = double(tmp(holes)); + +Vlh.fname = fullfile(spm('dir'),'toolbox','cat12','development','julichbrain_refined.nii'); +Vlh.descrip = 'JulichBrain v3.1'; +Vlh.dt(1) = 4; +spm_write_vol(Vlh,atlas); + +%% roi information +%Slh = cat_io_xml(spm_select(1,'xml','Select lh xml',{},pwd,'JulichBrain_MPMAtlas_l_N10_nlin2Stdicbm152asym2009c')); +%Srh = cat_io_xml(spm_select(1,'xml','Select rh xml',{},pwd,'JulichBrain_MPMAtlas_r_N10_nlin2Stdicbm152asym2009c')); +Slh = cat_io_xml(fullfile(spm('dir'),'toolbox','cat12','development','JulichBrainAtlas_3.1_207areas_MPM_lh_MNI152.xml')); +Srh = cat_io_xml(fullfile(spm('dir'),'toolbox','cat12','development','JulichBrainAtlas_3.1_207areas_MPM_rh_MNI152.xml')); + +fid = fopen( fullfile(spm('dir'),'toolbox','cat12','templates_MNI152NLin2009cAsym','julichbrain.csv'),'w'); +fprintf(fid,'ROIid;ROIabbr;ROIname\n'); + +Xlh = Slh.Structures.Structure; +Xrh = Srh.Structures.Structure; +n_lh = numel(Xlh); +n_rh = numel(Xrh); +n = n_lh + n_rh; +Name = cell(n,1); +ID = zeros(n,1); + +for i=1:n_lh + Name{(2*i)-1} = Xlh(i).CONTENT; + ID((2*i)-1) = 2*Xlh(i).ATTRIBUTE.grayvalue-1; +end + +for i=1:n_rh + Name{2*i} = Xrh(i).CONTENT; + ID(2*i) = 2*Xrh(i).ATTRIBUTE.grayvalue; +end + +% write csv file for CAT12 +for i=1:n + % create short name without not needed information + ShortName = strrep(Name{i},'Area',''); + ind = strfind(ShortName,'('); + if ~isempty(ind) + ShortName = ShortName(1:ind-1); + end + ShortName = strrep(ShortName,' ',''); + + % write left/right information + if rem(i,2) + fprintf(fid,'%d;l%s;Left %s\n',ID(i),ShortName,Name{i}); + else + fprintf(fid,'%d;r%s;Right %s\n',ID(i),ShortName,Name{i}); + end +end + +fclose(fid); + +% use imcalc to get to template space +matlabbatch{1}.spm.util.imcalc.input = { + fullfile(cat_get_defaults('extopts.pth_templates'),'aal3.nii') + Vlh.fname + }; +matlabbatch{1}.spm.util.imcalc.output = 'julichbrain3.nii'; +matlabbatch{1}.spm.util.imcalc.outdir = {fullfile(spm('dir'),'toolbox','cat12','templates_MNI152NLin2009cAsym')}; +matlabbatch{1}.spm.util.imcalc.expression = 'i2'; +matlabbatch{1}.spm.util.imcalc.var = struct('name', {}, 'value', {}); +matlabbatch{1}.spm.util.imcalc.options.dmtx = 0; +matlabbatch{1}.spm.util.imcalc.options.mask = 0; +matlabbatch{1}.spm.util.imcalc.options.interp = 0; +matlabbatch{1}.spm.util.imcalc.options.dtype = 4; + +spm_jobman('run',matlabbatch) + +V = spm_vol('julichbrain3.nii'); +vol = round(spm_read_vols(V)); +V.pinfo(1) = 1; +spm_write_vol(V,vol); + + +%% Surfaces + +% Jubrain surfaces +Alh = gifti(fullfile(spm('dir'),'toolbox','cat12','development','lh.JulichBrainAtlas_3.1.label.gii')); +Arh = gifti(fullfile(spm('dir'),'toolbox','cat12','development','rh.JulichBrainAtlas_3.1.label.gii')); + +% template surfaces +Slh = gifti(fullfile(spm('dir'),'toolbox','cat12','templates_surfaces','lh.sphere.freesurfer.gii')); +Srh = gifti(fullfile(spm('dir'),'toolbox','cat12','templates_surfaces','rh.sphere.freesurfer.gii')); + +% template surfaces +S32lh = gifti(fullfile(spm('dir'),'toolbox','cat12','templates_surfaces_32k','lh.sphere.freesurfer.gii')); +S32rh = gifti(fullfile(spm('dir'),'toolbox','cat12','templates_surfaces_32k','rh.sphere.freesurfer.gii')); + +% simple mapping via sphere +A32lh = cat_surf_fun('cdatamapping', S32lh, Slh, Alh.cdata); +A32rh = cat_surf_fun('cdatamapping', S32rh, Srh, Arh.cdata); + +% prepare values for FreeSurfer annot standard (correct for undefined entry) +rgbalh = int64(round(Alh.labels.rgba(2:end,:)*255)); rgbalh(:,4) = 0; +rgbarh = int64(round(Arh.labels.rgba(2:end,:)*255)); rgbarh(:,4) = 0; + +% save maps +fname = { + fullfile(spm('dir'),'toolbox','cat12','atlases_surfaces','lh.JulichBrainAtlas_3.1.freesurfer.annot'); + fullfile(spm('dir'),'toolbox','cat12','atlases_surfaces','rh.JulichBrainAtlas_3.1.freesurfer.annot'); + }; +Alhfs = Alh.cdata; Arhfs = Arh.cdata; +for i=1:max(Alh.cdata) + Alhfs(Alh.cdata==i) = rgbalh(i,1) + rgbalh(i,2)*2^8 + rgbalh(i,3)*2^16 + rgbalh(i,4)*2^24; +end +for i=1:max(A32rh) + Arhfs(Arh.cdata==i) = rgbarh(i,1) + rgbarh(i,2)*2^8 + rgbarh(i,3)*2^16 + rgbarh(i,4)*2^24; +end +cat_io_FreeSurfer('write_annotation', fname{1}, ... + 1:numel(Alh.cdata), Alhfs, struct('numEntries',max(Alh.cdata), 'orig_tab','JulichBrainAtlas_3.1.label', ... + 'struct_names', {Alh.labels.name'},'table',rgbalh)); +cat_io_FreeSurfer('write_annotation', fname{2}, ... + 1:numel(Arh.cdata), Arhfs, struct('numEntries',max(Arh.cdata), 'orig_tab','JulichBrainAtlas_3.1.label', ... + 'struct_names', {Alh.labels.name'},'table',rgbarh)); +cat_io_cprintf('blue',' %s\n',fname{1}) + + +% save 32k data +fname32 = { + fullfile(spm('dir'),'toolbox','cat12','atlases_surfaces_32k','lh.JulichBrainAtlas_3.1.freesurfer.annot'); + fullfile(spm('dir'),'toolbox','cat12','atlases_surfaces_32k','rh.JulichBrainAtlas_3.1.freesurfer.annot'); + }; +A32lhfs = A32lh; A32rhfs = A32rh; +for i=1:max(A32lh) + A32lhfs(A32lh==i) = rgbalh(i,1) + rgbalh(i,2)*2^8 + rgbalh(i,3)*2^16 + rgbalh(i,4)*2^24; +end +for i=1:max(A32rh) + A32rhfs(A32lh==i) = rgbarh(i,1) + rgbarh(i,2)*2^8 + rgbarh(i,3)*2^16 + rgbarh(i,4)*2^24; +end +cat_io_FreeSurfer('write_annotation', fname32{1}, ... + 1:numel(A32lh), A32lhfs, struct('numEntries',max(A32lh), 'orig_tab','JulichBrainAtlas_3.1.label', ... + 'struct_names', {Alh.labels.name'},'table',rgbalh)); +cat_io_FreeSurfer('write_annotation', fname32{2}, ... + 1:numel(A32rh), A32rhfs, struct('numEntries',max(A32rh), 'orig_tab','JulichBrainAtlas_3.1.label', ... + 'struct_names', {Alh.labels.name'},'table',rgbarh)); +cat_io_cprintf('blue',' %s\n',fname32{1}) + + + + + + + + + + + + + + +","MATLAB" +"Neurology","ChristianGaser/cat12","development/Atlas_Anatomy2CAT12.m",".m","2177","66","function Atlas_Anatomy2CAT12 +% Convert Anatomy3 atlas to CAT12 atlas +%_______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +load JuBrain_Data_public_v30.mat + +V = JuBrain.Vo; +V.fname ='Anatomy3_refined.nii'; +V.pinfo(1) = 1; +atlas = zeros(V.dim); +n_structures = numel(JuBrain.Namen); + +% flip hemisphere coding +JuBrain.lr = 2 - JuBrain.lr; + +fid = fopen('anatomy3.csv','w'); +fprintf(fid,'ROIid;ROIabbr;ROIname;ROIoname\n'); + +% code left/right hemispheres +tmp = 2*JuBrain.mpm - JuBrain.lr; + +% correct atlas regions that were zero before +tmp(JuBrain.mpm == 0) = 0; +atlas(JuBrain.idx) = tmp; + +% replace remaining holes with median value +holes = atlas > 0; +holes = (cat_vol_morph(holes,'c') - holes) > 0; +tmp = cat_vol_median3c(single(atlas)); +atlas(holes) = double(tmp(holes)); + +spm_write_vol(V,atlas); + +% write csv file for CAT12 +for i=1:n_structures + fprintf(fid,'%d;l%s;Left %s;%s\n',2*i-1,deblank(JuBrain.Files{i}),deblank(JuBrain.Namen{i}),deblank(JuBrain.Namen{i})); + fprintf(fid,'%d;r%s;Right %s;%s\n',2*i-1,deblank(JuBrain.Files{i}),deblank(JuBrain.Namen{i}),deblank(JuBrain.Namen{i})); +end +fclose(fid); + +matlabbatch{1}.spm.util.imcalc.input = { + fullfile(cat_get_defaults('extopts.pth_templates'),'aal3.nii') + 'Anatomy3_refined.nii' + }; +matlabbatch{1}.spm.util.imcalc.output = 'anatomy3.nii'; +matlabbatch{1}.spm.util.imcalc.outdir = {''}; +matlabbatch{1}.spm.util.imcalc.expression = 'i2'; +matlabbatch{1}.spm.util.imcalc.var = struct('name', {}, 'value', {}); +matlabbatch{1}.spm.util.imcalc.options.dmtx = 0; +matlabbatch{1}.spm.util.imcalc.options.mask = 0; +matlabbatch{1}.spm.util.imcalc.options.interp = 0; +matlabbatch{1}.spm.util.imcalc.options.dtype = 2; + +spm_jobman('run',matlabbatch) + +V = spm_vol('anatomy3.nii'); +vol = round(spm_read_vols(V)); +V.pinfo(1) = 1; +spm_write_vol(V,vol);","MATLAB" +"Neurology","ChristianGaser/cat12","development/cat_stat_results.m",".m","2869","66","function hRes = cat_stat_results +% just a batch used to create cat_spm_results_ui +% delete 202006 or later + + + + %% call modified SPM statistic + if 0%exist('xSPM','var'); + xSPM.thresDesc = 'FWE'; + [hReg,xSPM] = cat_spm_results_ui('Setup',xSPM); + else + [hReg,xSPM] = cat_spm_results_ui; + end + + % create SPM result table + %spm_list('List',xSPM,hReg); + + + %% SPM figure + hRes.Fgraph = spm_figure('GetWin','Graphics'); + hRes.FgraphC = get( hRes.Fgraph ,'children'); + hRes.Fmenu3d = findobj( hRes.FgraphC ,'Type','uicontextmenu','Tag',''); + hRes.FmenuTab = findobj( hRes.FgraphC ,'Type','uicontextmenu','Tag','TabDat'); + hRes.FgraphAx = findobj( hRes.FgraphC,'Type','Axes'); + hRes.FgraphAxPos = cell2mat(get( hRes.FgraphAx , 'Position')); + hRes.Ftext = findobj(hRes.Fgraph,'Type','Text'); + + % find the SPM string within the surface axis + stext = get(hRes.Ftext,'String'); + hRes.Ftext3dspm = findobj(hRes.Fgraph,'Type','Text','String', ... + stext{ find(~cellfun('isempty',strfind(stext,'SPM\{'))) } ); + set(hRes.Ftext3dspm,'visible','off','HitTest','off'); + + % find the SPM result text + hRes.Ftext3dres = get( findobj(hRes.Fgraph,'Type','Text','Color',[0.7 0.7 0.7]),'parent'); + for axi=1:numel(hRes.Ftext3dres), set( hRes.Ftext3dres{axi},'HitTest','off'); end + + % fine red lines of the SPM result table + hRes.Fline = findobj(hRes.Fgraph,'Type','Line','Tag',''); + hRes.Flinewhite = findobj(hRes.Fgraph,'Color',[1 1 1]); %findobj(hRes.Fgraph,'Type','Line','Color',[1 1 1]); + hRes.Fsurf = findobj(hRes.Fgraph,'Type','Line','Tag','CrossBar'); + set( hRes.Fsurf , 'LineWidth', 2, 'MarkerSize', 200, 'Color', [1 0 0]) + + hRes.FlineAx = get(hRes.Fline,'parent'); + hRes.Flabels = [ hRes.FgraphAx( hRes.FgraphAxPos(:,1) == 0.65); hRes.FgraphAx( hRes.FgraphAxPos(:,1) == 0.02)]; + + % make nice contrast box that is a bit larger than the original boxes + hRes.Fcons = hRes.FgraphAx( hRes.FgraphAxPos(:,1) == 0.65 & hRes.FgraphAxPos(:,2) > 0.6 ) ; + for axi = 1:numel( hRes.Fcons ), l = get( hRes.Fcons(axi) , 'ylim'); set(hRes.Fcons(axi) , 'box','on','ylim', round(l) + [-0.015 0.015]); end + + % remove non integer values + hRes.Fdesm = hRes.FgraphAx( hRes.FgraphAxPos(:,1) == 0.65 & hRes.FgraphAxPos(:,2) < 0.6 ) ; + xt = get(hRes.Fdesm,'xtick'); xt(round(xt)~=xt) = []; set(hRes.Fdesm,'xtick',xt); + + + % + hRes.Fval = hRes.FgraphAx( hRes.FgraphAxPos(:,1) > 10); + hRes.Fsurf = hRes.FgraphAx( hRes.FgraphAxPos(:,1) == 0.05); + %hRes.Flabels = setdiff( hRes.FgraphAx , hRes.Fval ); + set(hRes.Fline,'HitTest','off') + for axi = 1:numel( hRes.Flabels ), set(hRes.Flabels(axi),'HitTest','off'); end + for axi = 1:numel( hRes.FlineAx ), set(hRes.FlineAx{axi},'HitTest','off'); end + % rotate3d(hRes.FmenuTab,'off') + + + ","MATLAB" +"Neurology","ChristianGaser/cat12","standalone/cat_standalone_resample.m",".m","1404","30","% Batch file for CAT12 Resample & Smooth for SPM12/CAT12 standalone installation +% +%_______________________________________________________________________ +% $Id$ + +% data field, that will be dynamically replaced by cat_standalone.sh +matlabbatch{1}.spm.tools.cat.stools.surfresamp.sample{1}.data_surf = ''; + +% Entry for choosing smoothing filter size surface values +% Remove comments and edit entry if you would like to change the parameter. +% Otherwise the default value from cat_defaults.m is used. +% Or use 1st parameter field, that will be dynamically replaced by cat_standalone.sh +% use 12-15mm for cortical thickness and 20-25mm for folding measures +%matlabbatch{1}.spm.tools.cat.stools.surfresamp.fwhm_surf = ''; + +% Entry for using 32k mesh from HCP or 164k mesh from Freesurfer +% Remove comments and edit entry if you would like to change the parameter. +% Otherwise the default value from cat_defaults.m is used. +% Or use 2nd parameter field, that will be dynamically replaced by cat_standalone.sh +%matlabbatch{1}.spm.tools.cat.stools.surfresamp.mesh32k = ''; + +% merge hemispheres? +matlabbatch{1}.spm.tools.cat.stools.surfresamp.merge_hemi = 1; + +% set this to 1 for skipping processing if already processed data exist +matlabbatch{1}.spm.tools.cat.stools.surfresamp.lazy = 0; + +% disable parallel processing +matlabbatch{1}.spm.tools.cat.stools.surfresamp.nproc = 0; +","MATLAB" +"Neurology","ChristianGaser/cat12","standalone/cat_standalone_segment.m",".m","9762","181","% Batch file for CAT12 segmentation for SPM12/CAT12 standalone installation +% +%_______________________________________________________________________ +% $Id$ + +% first undefined data field, that will be dynamically replaced by cat_standalone.sh +matlabbatch{1}.spm.tools.cat.estwrite.data = ''; + +% Entry for choosing TPM +% Remove comments and edit entry if you would like to change the parameter. +% Otherwise the default value from cat_defaults.m is used. +% Or use 1st parameter field, that will be dynamically replaced by cat_standalone.sh +%matlabbatch{1}.spm.tools.cat.estwrite.opts.tpm = ''; + +% Entry for choosing shooting template +% Remove comments and edit entry if you would like to change the parameter. +% Otherwise the default value from cat_defaults.m is used. +% Or use 2nd parameter field, that will be dynamically replaced by cat_standalone.sh +%matlabbatch{1}.spm.tools.cat.estwrite.extopts.registration.regmethod.shooting.shootingtpm = ''; + +% Strength of Shooting registration: 0 - Dartel, eps (fast), 0.5 (default) to 1 (accurate) optimized Shooting, 4 - default Shooting; default 0.5 +%matlabbatch{1}.spm.tools.cat.estwrite.extopts.registration.regmethod.shooting.regstr = 0.5; + +% voxel size for normalized data (EXPERIMENTAL: inf - use Tempate values) +matlabbatch{1}.spm.tools.cat.estwrite.extopts.registration.vox = 1.5; + +% additional bounding box +matlabbatch{1}.spm.tools.cat.estwrite.extopts.registration.bb = 12; + +% Affine regularisation (SPM12 default = mni) - '';'mni';'eastern';'subj';'none';'rigid' +matlabbatch{1}.spm.tools.cat.estwrite.opts.affreg = 'mni'; + +% Strength of the bias correction that controls the biasreg and biasfwhm parameter (CAT only!) +% 0 - use SPM parameter; eps - ultralight, 0.25 - light, 0.5 - medium, 0.75 - strong, and 1 - heavy corrections +% job.opts.biasreg = min( 10 , max( 0 , 10^-(job.opts.biasstr*2 + 2) )); +% job.opts.biasfwhm = min( inf , max( 30 , 30 + 60*job.opts.biasstr )); +matlabbatch{1}.spm.tools.cat.estwrite.opts.biasstr = 0.5; + +% Affine PreProcessing (APP) with rough bias correction and brain extraction for special anatomies (nonhuman/neonates) +% 0 - none; 1070 - default; [1 - SPM; 5 - animal (no affreg)] +matlabbatch{1}.spm.tools.cat.estwrite.extopts.segmentation.APP = 1070; + +% Strength of the local adaptation: 0 to 1; default 0.5 +matlabbatch{1}.spm.tools.cat.estwrite.extopts.segmentation.LASstr = 0.5; + +% Strength of the noise correction: 0 to 1; 0 - no filter, -Inf - auto, 1 - full, 2 - ISARNLM (else SANLM), default -Inf +matlabbatch{1}.spm.tools.cat.estwrite.extopts.segmentation.NCstr = -Inf; + +% Strength of skull-stripping: 0 - SPM approach; eps to 1 - gcut; 2 - new APRG approach; -1 - no skull-stripping (already skull-stripped); default = 2 +matlabbatch{1}.spm.tools.cat.estwrite.extopts.segmentation.gcutstr = 2; + +% Strength of the cleanup process: 0 to 1; default 0.5 +matlabbatch{1}.spm.tools.cat.estwrite.extopts.segmentation.cleanupstr = 0.5; + +% resolution handling: 'native','fixed','best', 'optimal' +matlabbatch{1}.spm.tools.cat.estwrite.extopts.segmentation.restypes.optimal = [1 0.3]; + +% use center-of-mass approach for estimating origin +matlabbatch{1}.spm.tools.cat.estwrite.extopts.segmentation.setCOM = 1; + +% modify affine scaling +matlabbatch{1}.spm.tools.cat.estwrite.extopts.segmentation.affmod = 0; + +% Correction of WM hyperintensities: 0 - no correction, 1 - only for Dartel/Shooting +% 2 - also correct segmentation (to WM), 3 - handle as separate class; default 1 +matlabbatch{1}.spm.tools.cat.estwrite.extopts.segmentation.WMHC = 2; + +% Stroke lesion correction (SLC): 0 - no correction, 1 - handling of manual lesion that have to be set to zero! +% 2 - automatic lesion detection (in development) +matlabbatch{1}.spm.tools.cat.estwrite.extopts.segmentation.SLC = 0; + +% surface options +matlabbatch{1}.spm.tools.cat.estwrite.extopts.surface.pbtres = 0.5; +matlabbatch{1}.spm.tools.cat.estwrite.extopts.surface.pbtmethod = 'pbt2x'; +matlabbatch{1}.spm.tools.cat.estwrite.extopts.surface.reduce_mesh = 1; +matlabbatch{1}.spm.tools.cat.estwrite.extopts.surface.scale_cortex = 0.7; +matlabbatch{1}.spm.tools.cat.estwrite.extopts.surface.add_parahipp = 0.1; +matlabbatch{1}.spm.tools.cat.estwrite.extopts.surface.close_parahipp = 0; +matlabbatch{1}.spm.tools.cat.estwrite.extopts.surface.SRP = 22; + +% set this to 1 for skipping preprocessing if already processed data exist +matlabbatch{1}.spm.tools.cat.estwrite.extopts.admin.lazy = 0; + +% catch errors: 0 - stop with error (default); 1 - catch preprocessing errors (requires MATLAB 2008 or higher); +matlabbatch{1}.spm.tools.cat.estwrite.extopts.admin.ignoreErrors = 1; + +% verbose output: 1 - default; 2 - details; 3 - write debugging files +matlabbatch{1}.spm.tools.cat.estwrite.extopts.admin.verb = 2; + +% display and print out pdf-file of results: 0 - off, 2 - volume only, 2 - volume and surface (default) +matlabbatch{1}.spm.tools.cat.estwrite.extopts.admin.print = 2; + +% surface and thickness creation: 0 - no (default), 1 - lh+rh, 2 - lh+rh+cerebellum, +% 3 - lh, 4 - rh, 5 - lh+rh (fast, no registration, only for quick quality check and not for analysis), +% 6 - lh+rh+cerebellum (fast, no registration, only for quick quality check and not for analysis) +% 9 - thickness only (for ROI analysis, experimental!) +% +10 to estimate WM and CSF width/depth/thickness (experimental!) +matlabbatch{1}.spm.tools.cat.estwrite.output.surface = 1; + +% BIDS output +matlabbatch{1}.spm.tools.cat.estwrite.output.BIDS.BIDSno = 1; + +% define here volume atlases +matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.neuromorphometrics = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.lpba40 = 0; +matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.cobra = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.hammers = 0; +matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.ibsr = 0; +matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.aal3 = 0; +matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.mori = 0; +matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.thalamus = 0; +matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.anatomy3 = 0; +matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.julichbrain3 = 0; +matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.Schaefer2018_100Parcels_17Networks_order = 0; +matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.Schaefer2018_200Parcels_17Networks_order = 0; +matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.Schaefer2018_400Parcels_17Networks_order = 0; +matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.Schaefer2018_600Parcels_17Networks_order = 0; +matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.ownatlas = {''}; + +% Writing options (see cat_defaults for the description of parameters) +% native 0/1 (none/yes) +% warped 0/1 (none/yes) +% mod 0/1/2/3 (none/affine+nonlinear/nonlinear only/both) +% dartel 0/1/2/3 (none/rigid/affine/both) + +% GM/WM/CSF/WMH +matlabbatch{1}.spm.tools.cat.estwrite.output.GM.native = 0; +matlabbatch{1}.spm.tools.cat.estwrite.output.GM.warped = 0; +matlabbatch{1}.spm.tools.cat.estwrite.output.GM.mod = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.GM.dartel = 0; +matlabbatch{1}.spm.tools.cat.estwrite.output.WM.native = 0; +matlabbatch{1}.spm.tools.cat.estwrite.output.WM.warped = 0; +matlabbatch{1}.spm.tools.cat.estwrite.output.WM.mod = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.WM.dartel = 0; +matlabbatch{1}.spm.tools.cat.estwrite.output.CSF.native = 0; +matlabbatch{1}.spm.tools.cat.estwrite.output.CSF.warped = 0; +matlabbatch{1}.spm.tools.cat.estwrite.output.CSF.mod = 0; +matlabbatch{1}.spm.tools.cat.estwrite.output.CSF.dartel = 0; +matlabbatch{1}.spm.tools.cat.estwrite.output.WMH.native = 0; +matlabbatch{1}.spm.tools.cat.estwrite.output.WMH.warped = 0; +matlabbatch{1}.spm.tools.cat.estwrite.output.WMH.mod = 0; +matlabbatch{1}.spm.tools.cat.estwrite.output.WMH.dartel = 0; + +% stroke lesion tissue maps (only for opt.extopts.SLC>0) - in development +matlabbatch{1}.spm.tools.cat.estwrite.output.SL.native = 0; +matlabbatch{1}.spm.tools.cat.estwrite.output.SL.warped = 0; +matlabbatch{1}.spm.tools.cat.estwrite.output.SL.mod = 0; +matlabbatch{1}.spm.tools.cat.estwrite.output.SL.dartel = 0; + +% Tissue classes 4-6 to create own TPMs +matlabbatch{1}.spm.tools.cat.estwrite.output.TPMC.native = 0; +matlabbatch{1}.spm.tools.cat.estwrite.output.TPMC.warped = 0; +matlabbatch{1}.spm.tools.cat.estwrite.output.TPMC.mod = 0; +matlabbatch{1}.spm.tools.cat.estwrite.output.TPMC.dartel = 0; + +% atlas maps (for evaluation) +matlabbatch{1}.spm.tools.cat.estwrite.output.atlas.native = 0; + +% label +% background=0, CSF=1, GM=2, WM=3, WMH=4 (if opt.extopts.WMHC==3), SL=1.5 (if opt.extopts.SLC>0) +matlabbatch{1}.spm.tools.cat.estwrite.output.label.native = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.label.warped = 0; +matlabbatch{1}.spm.tools.cat.estwrite.output.label.dartel = 0; + +% bias and noise corrected, global intensity normalized +matlabbatch{1}.spm.tools.cat.estwrite.output.bias.native = 0; +matlabbatch{1}.spm.tools.cat.estwrite.output.bias.warped = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.bias.dartel = 0; + +% bias and noise corrected, (locally - if LAS>0) intensity normalized +matlabbatch{1}.spm.tools.cat.estwrite.output.las.native = 0; +matlabbatch{1}.spm.tools.cat.estwrite.output.las.warped = 0; +matlabbatch{1}.spm.tools.cat.estwrite.output.las.dartel = 0; + +% jacobian determinant 0/1 (none/yes) +matlabbatch{1}.spm.tools.cat.estwrite.output.jacobianwarped = 0; + +% deformations, order is [forward inverse] +matlabbatch{1}.spm.tools.cat.estwrite.output.warps = [1 0]; + +","MATLAB" +"Neurology","ChristianGaser/cat12","standalone/cat_parallelize.sh",".sh","6703","259","#! /bin/bash +# ______________________________________________________________________ +# +# Christian Gaser, Robert Dahnke +# Structural Brain Mapping Group (https://neuro-jena.github.io) +# Departments of Neurology and Psychiatry +# Jena University Hospital +# ______________________________________________________________________ +# $Id$ + +######################################################## +# global parameters +######################################################## +version='cat_parallelize.sh $Id$' + +CPUINFO=/proc/cpuinfo +ARCH=`uname` +LOGDIR=$PWD +time=`date ""+%Y%b%d_%H%M""` + +######################################################## +# run main +######################################################## + +main () +{ + parse_args ${1+""$@""} + check_files + get_no_of_cpus + parallelize + + exit 0 +} + +######################################################## +# check arguments and files +######################################################## + +parse_args () +{ + local optname optarg + count=0 + while [ $# -gt 0 ]; do + optname=""`echo $1 | sed 's,=.*,,'`"" + optarg=""$2"" + case ""$1"" in + --command* | -c*) + exit_if_empty ""$optname"" ""$optarg"" + COMMAND=$optarg + shift + ;; + --processes* | -p*) + exit_if_empty ""$optname"" ""$optarg"" + NUMBER_OF_JOBS=$optarg + shift + ;; + --logdir* | -l*) + exit_if_empty ""$optname"" ""$optarg"" + LOGDIR=$optarg + shift + ;; + --test* | -t*) + TEST=1 + ;; + -h | --help | -v | --version | -V) + help + exit 1 + ;; + -*) + echo ""`basename $0`: ERROR: Unrecognized option \""$1\"""" >&2 + ;; + *) + ARRAY[$count]=$1 + ((count++)) + ;; + esac + shift + done + +} + +######################################################## +# check arguments +######################################################## + +exit_if_empty () +{ + local desc val + + desc=""$1"" + shift + val=""$*"" + + if [ ! -n ""$val"" ] + then + echo ERROR: ""No argument given with \""$desc\"" command line argument!"" >&2 + exit 1 + fi +} + +######################################################## +# check files +######################################################## + +check_files () +{ + if [ ! -n ""$COMMAND"" ]; + then + echo ""$FUNCNAME ERROR - no command defined."" + help + exit 1 + fi + + SIZE_OF_ARRAY=""${#ARRAY[@]}"" + if [ ""$SIZE_OF_ARRAY"" -eq 0 ] + then + echo 'ERROR: No files given!' >&2 + help + exit 1 + fi + + i=0 + while [ ""$i"" -lt ""$SIZE_OF_ARRAY"" ] + do + if [ ! -f ""${ARRAY[$i]}"" ] && [ ! -d ""${ARRAY[$i]}"" ]; then + echo ERROR: File or directory ${ARRAY[$i]} not found + help + exit 1 + fi + ((i++)) + done + +} + +######################################################## +# get # of cpus +######################################################## +# modified code from +# PPSS, the Parallel Processing Shell Script +# +# Copyright (c) 2009, Louwrentius +# All rights reserved. + +get_no_of_cpus () { + + if [ ! -n ""$NUMBER_OF_JOBS"" ]; then + if [ ""$ARCH"" == ""Linux"" ]; then + NUMBER_OF_PROC=`grep ^processor $CPUINFO | wc -l` + elif [ ""$ARCH"" == ""Darwin"" ]; then + NUMBER_OF_PROC=`sysctl -a hw | grep -w hw.logicalcpu | awk '{ print $2 }'` + elif [ ""$ARCH"" == ""FreeBSD"" ]; then + NUMBER_OF_PROC=`sysctl hw.ncpu | awk '{ print $2 }'` + else + NUMBER_OF_PROC=`grep ^processor $CPUINFO | wc -l` + fi + + if [ ! -n ""$NUMBER_OF_PROC"" ]; then + echo ""$FUNCNAME ERROR - number of CPUs not obtained. Use -p to define number of processes."" + exit 1 + fi + fi +} + +######################################################## +# run parallelize +######################################################## + +parallelize () +{ + SIZE_OF_ARRAY=""${#ARRAY[@]}"" + BLOCK=$((10000* $SIZE_OF_ARRAY / $NUMBER_OF_JOBS )) + + i=0 + while [ ""$i"" -lt ""$SIZE_OF_ARRAY"" ]; do + count=$((10000* $i / $BLOCK )) + if [ ! -n ""${ARG_LIST[$count]}"" ]; then + ARG_LIST[$count]=""${ARRAY[$i]}"" + else + ARG_LIST[$count]=""${ARG_LIST[$count]} ${ARRAY[$i]}"" + fi + ((i++)) + done + + time=`date ""+%Y%b%d_%H%M""` + log=${LOGDIR}/parallelize_${HOSTNAME}_${time}.log + if [ ! -n ""${TEST}"" ]; then + echo Check $log for logging information + echo > $log + echo + fi + + i=0 + while [ ""$i"" -lt ""$NUMBER_OF_JOBS"" ]; do + if [ ! ""${ARG_LIST[$i]}"" == """" ]; then + j=$(($i+1)) + echo job ${j}/""$NUMBER_OF_JOBS"": + echo $COMMAND ${ARG_LIST[$i]} + if [ ! -n ""${TEST}"" ]; then + echo job ${j}/""$NUMBER_OF_JOBS"": $COMMAND ${ARG_LIST[$i]} >> $log + nohup bash -c ""for k in ${ARG_LIST[$i]}; do $COMMAND \$k; done"" >> $log 2>&1 & + fi + fi + ((i++)) + done + +} + +######################################################## +# help +######################################################## + +help () +{ +cat <<__EOM__ + +USAGE: + cat_parallelize.sh filenames|filepattern [-p number_of_processes] [-l log_folder] [-t] -c command_to_parallelize + + -p | --processes number of parallel jobs (=number of processors) + (default $NUMBER_OF_JOBS) + -c | --command shell command to call other shell scripts + -t | --test do not call command, but print files to be processed + -l | --logdir directory for log-file (default $LOGDIR) + + Only one filename or pattern is allowed. This can be either a single file or a pattern + with wildcards to process multiple files. Optionally you can set number of processes, + that are automatically set to the number of processors as default. + +PURPOSE: + Parallelize a job or command + +OUTPUT: + parallelize_${HOSTNAME}_${time}.log with current data and time in name as log-file + +EXAMPLE + cat_parallelize.sh -c ""niismooth -v -fwhm 8"" sTRIO*.nii + Parallelize smoothing with fwhm of 8mm for all files sTRIO*.nii. Use + verbose mode to see diagnostic output. + + cat_parallelize.sh -c gunzip *.zip + Parallelize unzipping of all zip-files in current folder. + + cat_parallelize.sh -p 8 -l /tmp -c ""cat_standalone.sh -s ~/spm/standalone/ -m /Applications/MATLAB/MATLAB_Runtime/v232/ -b cat_standalone_segment.m"" sTRIO*.nii + Parallelize CAT12 preprocessing by splitting all sTRIO*.nii files into 8 jobs + (processes) and save log-file in /tmp folder. + +This script was written by Christian Gaser (christian.gaser@uni-jena.de). +This is ${version}. + +__EOM__ +} + +######################################################## +# call main program +######################################################## + +main ${1+""$@""} + +","Shell" +"Neurology","ChristianGaser/cat12","standalone/cat_standalone_get_TIV.m",".m","1361","26","% Batch file for getting TIV values for SPM12/CAT12 standalone installation +% +%_______________________________________________________________________ +% $Id$ + +% data field, that will be dynamically replaced by cat_standalone.sh +matlabbatch{1}.spm.tools.cat.tools.calcvol.data_xml = ''; + +% Entry for output filename +% Remove comments and edit entry if you would like to change the parameter. +% Otherwise the default value from cat_defaults.m is used. +% Or use 1st parameter field, that will be dynamically replaced by cat_standalone.sh +%matlabbatch{1}.spm.tools.cat.tools.calcvol.calcvol_name = ''; + +% Entry for option to save TIV only +% Remove comments and edit entry if you would like to change the parameter. +% Otherwise the default value from cat_defaults.m is used. +% Or use 2nd parameter field, that will be dynamically replaced by cat_standalone.sh +%matlabbatch{1}.spm.tools.cat.tools.calcvol.calcvol_TIV = ''; + +% Entry to add filename to 1st column +% Remove comments and edit entry if you would like to change the parameter. +% Otherwise the default value from cat_defaults.m is used. +% Or use 3rd parameter field, that will be dynamically replaced by cat_standalone.sh +% 0 - save values only; 1 - add filename; 2 - add folder and filename +%matlabbatch{1}.spm.tools.cat.tools.calcvol.calcvol_savenames = '';","MATLAB" +"Neurology","ChristianGaser/cat12","standalone/cat_standalone_deface.m",".m","272","7","% Batch file for defacing for SPM12/CAT12 standalone installation +% +%_______________________________________________________________________ +% $Id$ + +% data field, that will be dynamically replaced by cat_standalone.sh +matlabbatch{1}.spm.util.deface.images = '';","MATLAB" +"Neurology","ChristianGaser/cat12","standalone/cat_standalone_get_quality.m",".m","984","20","% Batch file for getting quality measures for SPM12/CAT12 standalone installation +% +%_______________________________________________________________________ +% $Id$ + +% data field, that will be dynamically replaced by cat_standalone.sh +matlabbatch{1}.spm.tools.cat.tools.quality_measures.data = ''; + +% Entry for csv output filename +% Remove comments and edit entry if you would like to change the parameter. +% Otherwise the default value from cat_defaults.m is used. +% Or use 1st parameter field, that will be dynamically replaced by cat_standalone.sh +%matlabbatch{1}.spm.tools.cat.tools.quality_measures.csv_name = ''; + +% Entry for enabling global scaling with TIV +% Remove comments and edit entry if you would like to change the parameter. +% Otherwise the default value from cat_defaults.m is used. +% Or use 2nd parameter field, that will be dynamically replaced by cat_standalone.sh +%matlabbatch{1}.spm.tools.cat.tools.quality_measures.globals = ''; +","MATLAB" +"Neurology","ChristianGaser/cat12","standalone/cat_standalone_dicom2nii.m",".m","1259","33","% Batch file for importing DICOM data for SPM12/CAT12 standalone installation +% +%_______________________________________________________________________ +% $Id$ + +% data field, that will be dynamically replaced by cat_standalone.sh +matlabbatch{1}.spm.util.import.dicom.data = ''; + +% Entry for choosing directory structure +% Remove comments and edit entry if you would like to change the parameter. +% Otherwise the default value from cat_defaults.m is used. +% Or use 1st parameter field, that will be dynamically replaced by cat_standalone.sh +%matlabbatch{1}.spm.util.import.dicom.root = ''; + +% Entry for choosing output directory +% Remove comments and edit entry if you would like to change the parameter. +% Otherwise the default value from cat_defaults.m is used. +% Or use 2nd parameter field, that will be dynamically replaced by cat_standalone.sh +%matlabbatch{1}.spm.util.import.dicom.outdir = ''; + +% protocol name filter +matlabbatch{1}.spm.util.import.dicom.protfilter = '.*'; + +% output image format +matlabbatch{1}.spm.util.import.dicom.convopts.format = 'nii'; + +% export metadata +matlabbatch{1}.spm.util.import.dicom.convopts.meta = 1; + +% use IDEDims in filename +matlabbatch{1}.spm.util.import.dicom.convopts.icedims = 0; + +","MATLAB" +"Neurology","ChristianGaser/cat12","standalone/cat_standalone_segment_enigma.m",".m","11106","192","% Batch file for CAT12 segmentation for SPM12/CAT12 standalone installation +% modified parameters for ENIGMA +% +%_______________________________________________________________________ +% $Id$ + +% first undefined data field, that will be dynamically replaced by cat_standalone.sh +matlabbatch{1}.spm.tools.cat.estwrite.data = ''; + +% Entry for choosing TPM +% Remove comments and edit entry if you would like to change the parameter. +% Otherwise the default value from cat_defaults.m is used. +% Or use 1st parameter field, that will be dynamically replaced by cat_standalone.sh +%matlabbatch{1}.spm.tools.cat.estwrite.opts.tpm = ''; + +% Entry for choosing shooting template +% Remove comments and edit entry if you would like to change the parameter. +% Otherwise the default value from cat_defaults.m is used. +% Or use 2nd parameter field, that will be dynamically replaced by cat_standalone.sh +%matlabbatch{1}.spm.tools.cat.estwrite.extopts.registration.regmethod.shooting.shootingtpm = ''; + +% Strength of Shooting registration: 0 - Dartel, eps (fast), 0.5 (default) to 1 (accurate) optimized Shooting, 4 - default Shooting; default 0.5 +%matlabbatch{1}.spm.tools.cat.estwrite.extopts.registration.regmethod.shooting.regstr = 0.5; + +% voxel size for normalized data (EXPERIMENTAL: inf - use Tempate values) +matlabbatch{1}.spm.tools.cat.estwrite.extopts.registration.vox = 1.5; + +% additional bounding box +matlabbatch{1}.spm.tools.cat.estwrite.extopts.registration.bb = 12; + +% Affine regularisation (SPM12 default = mni) - '';'mni';'eastern';'subj';'none';'rigid' +matlabbatch{1}.spm.tools.cat.estwrite.opts.affreg = 'mni'; + +% Strength of the bias correction that controls the biasreg and biasfwhm parameter (CAT only!) +% 0 - use SPM parameter; eps - ultralight, 0.25 - light, 0.5 - medium, 0.75 - strong, and 1 - heavy corrections +% job.opts.biasreg = min( 10 , max( 0 , 10^-(job.opts.biasstr*2 + 2) )); +% job.opts.biasfwhm = min( inf , max( 30 , 30 + 60*job.opts.biasstr )); +matlabbatch{1}.spm.tools.cat.estwrite.opts.biasstr = 0.5; + +% Affine PreProcessing (APP) with rough bias correction and brain extraction for special anatomies (nonhuman/neonates) +% 0 - none; 1070 - default; [1 - SPM; 5 - animal (no affreg)] +matlabbatch{1}.spm.tools.cat.estwrite.extopts.segmentation.APP = 1070; + +% Strength of the local adaptation: 0 to 1; default 0.5 +matlabbatch{1}.spm.tools.cat.estwrite.extopts.segmentation.LASstr = 0.5; + +% Strength of the noise correction: 0 to 1; 0 - no filter, -Inf - auto, 1 - full, 2 - ISARNLM (else SANLM), default -Inf +matlabbatch{1}.spm.tools.cat.estwrite.extopts.segmentation.NCstr = -Inf; + +% Strength of skull-stripping: 0 - SPM approach; eps to 1 - gcut; 2 - new APRG approach; -1 - no skull-stripping (already skull-stripped); default = 2 +matlabbatch{1}.spm.tools.cat.estwrite.extopts.segmentation.gcutstr = 2; + +% Strength of the cleanup process: 0 to 1; default 0.5 +matlabbatch{1}.spm.tools.cat.estwrite.extopts.segmentation.cleanupstr = 0.5; + +% resolution handling: 'native','fixed','best', 'optimal' +matlabbatch{1}.spm.tools.cat.estwrite.extopts.segmentation.restypes.optimal = [1 0.3]; + +% use center-of-mass approach for estimating origin +matlabbatch{1}.spm.tools.cat.estwrite.extopts.segmentation.setCOM = 1; + +% modify affine scaling +matlabbatch{1}.spm.tools.cat.estwrite.extopts.segmentation.affmod = 0; + +% Correction of WM hyperintensities: 0 - no correction, 1 - only for Dartel/Shooting +% 2 - also correct segmentation (to WM), 3 - handle as separate class; default 1 +matlabbatch{1}.spm.tools.cat.estwrite.extopts.segmentation.WMHC = 2; + +% Stroke lesion correction (SLC): 0 - no correction, 1 - handling of manual lesion that have to be set to zero! +% 2 - automatic lesion detection (in development) +matlabbatch{1}.spm.tools.cat.estwrite.extopts.segmentation.SLC = 0; + +% surface options +matlabbatch{1}.spm.tools.cat.estwrite.extopts.surface.pbtres = 0.5; +matlabbatch{1}.spm.tools.cat.estwrite.extopts.surface.pbtmethod = 'pbt2x'; +matlabbatch{1}.spm.tools.cat.estwrite.extopts.surface.reduce_mesh = 1; +matlabbatch{1}.spm.tools.cat.estwrite.extopts.surface.scale_cortex = 0.7; +matlabbatch{1}.spm.tools.cat.estwrite.extopts.surface.add_parahipp = 0.1; +matlabbatch{1}.spm.tools.cat.estwrite.extopts.surface.close_parahipp = 0; +matlabbatch{1}.spm.tools.cat.estwrite.extopts.surface.SRP = 22; + +% set this to 1 for skipping preprocessing if already processed data exist +matlabbatch{1}.spm.tools.cat.estwrite.extopts.admin.lazy = 0; + +% catch errors: 0 - stop with error (default); 1 - catch preprocessing errors (requires MATLAB 2008 or higher); +matlabbatch{1}.spm.tools.cat.estwrite.extopts.admin.ignoreErrors = 1; + +% verbose output: 1 - default; 2 - details; 3 - write debugging files +matlabbatch{1}.spm.tools.cat.estwrite.extopts.admin.verb = 2; + +% display and print out pdf-file of results: 0 - off, 2 - volume only, 2 - volume and surface (default) +matlabbatch{1}.spm.tools.cat.estwrite.extopts.admin.print = 2; + +% surface and thickness creation: 0 - no (default), 1 - lh+rh, 2 - lh+rh+cerebellum, +% 3 - lh, 4 - rh, 5 - lh+rh (fast, no registration, only for quick quality check and not for analysis), +% 6 - lh+rh+cerebellum (fast, no registration, only for quick quality check and not for analysis) +% 9 - thickness only (for ROI analysis, experimental!) +% +10 to estimate WM and CSF width/depth/thickness (experimental!) +matlabbatch{1}.spm.tools.cat.estwrite.output.surface = 1; + +% BIDS output +matlabbatch{1}.spm.tools.cat.estwrite.output.BIDS.BIDSyes.BIDSfolder = cat_version; + +% define here volume atlases +matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.neuromorphometrics = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.lpba40 = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.cobra = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.hammers = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.ibsr = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.aal3 = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.mori = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.thalamus = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.anatomy3 = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.julichbrain3 = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.Schaefer2018_100Parcels_17Networks_order = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.Schaefer2018_200Parcels_17Networks_order = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.Schaefer2018_400Parcels_17Networks_order = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.Schaefer2018_600Parcels_17Networks_order = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.ownatlas = {''}; + +% Writing options (see cat_defaults for the description of parameters) +% native 0/1 (none/yes) +% warped 0/1 (none/yes) +% mod 0/1/2/3 (none/affine+nonlinear/nonlinear only/both) +% dartel 0/1/2/3 (none/rigid/affine/both) + +% GM/WM/CSF/WMH +matlabbatch{1}.spm.tools.cat.estwrite.output.GM.native = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.GM.warped = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.GM.mod = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.GM.dartel = 0; +matlabbatch{1}.spm.tools.cat.estwrite.output.WM.native = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.WM.warped = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.WM.mod = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.WM.dartel = 0; +matlabbatch{1}.spm.tools.cat.estwrite.output.CSF.native = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.CSF.warped = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.CSF.mod = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.CSF.dartel = 0; +matlabbatch{1}.spm.tools.cat.estwrite.output.WMH.native = 0; +matlabbatch{1}.spm.tools.cat.estwrite.output.WMH.warped = 0; +matlabbatch{1}.spm.tools.cat.estwrite.output.WMH.mod = 0; +matlabbatch{1}.spm.tools.cat.estwrite.output.WMH.dartel = 0; + +% stroke lesion tissue maps (only for opt.extopts.SLC>0) - in development +matlabbatch{1}.spm.tools.cat.estwrite.output.SL.native = 0; +matlabbatch{1}.spm.tools.cat.estwrite.output.SL.warped = 0; +matlabbatch{1}.spm.tools.cat.estwrite.output.SL.mod = 0; +matlabbatch{1}.spm.tools.cat.estwrite.output.SL.dartel = 0; + +% Tissue classes 4-6 to create own TPMs +matlabbatch{1}.spm.tools.cat.estwrite.output.TPMC.native = 0; +matlabbatch{1}.spm.tools.cat.estwrite.output.TPMC.warped = 0; +matlabbatch{1}.spm.tools.cat.estwrite.output.TPMC.mod = 0; +matlabbatch{1}.spm.tools.cat.estwrite.output.TPMC.dartel = 0; + +% atlas maps (for evaluation) +matlabbatch{1}.spm.tools.cat.estwrite.output.atlas.native = 1; + +% label +% background=0, CSF=1, GM=2, WM=3, WMH=4 (if opt.extopts.WMHC==3), SL=1.5 (if opt.extopts.SLC>0) +matlabbatch{1}.spm.tools.cat.estwrite.output.label.native = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.label.warped = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.label.dartel = 0; + +% bias and noise corrected, global intensity normalized +matlabbatch{1}.spm.tools.cat.estwrite.output.bias.native = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.bias.warped = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.bias.dartel = 0; + +% bias and noise corrected, (locally - if LAS>0) intensity normalized +matlabbatch{1}.spm.tools.cat.estwrite.output.las.native = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.las.warped = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.las.dartel = 0; + +% jacobian determinant 0/1 (none/yes) +matlabbatch{1}.spm.tools.cat.estwrite.output.jacobianwarped = 1; + +% deformations, order is [forward inverse] +matlabbatch{1}.spm.tools.cat.estwrite.output.warps = [1 1]; + +% registration matrix +matlabbatch{1}.spm.tools.cat.estwrite.output.rmat = 1; + +% deface native intensity normalized images in native space +matlabbatch{2}.spm.util.deface.images(1) = cfg_dep('CAT12: Segmentation: Native Bias Corr. Image', substruct('.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('()',{1}, '.','biascorr', '()',{':'})); +matlabbatch{2}.spm.util.deface.images(2) = cfg_dep('CAT12: Segmentation: Native LAS Bias Corr. Image', substruct('.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('()',{1}, '.','ibiascorr', '()',{':'})); + +% and remove images that are not defaced +matlabbatch{3}.cfg_basicio.file_dir.file_ops.file_move.files(1) = cfg_dep('CAT12: Segmentation: Native Bias Corr. Image', substruct('.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('()',{1}, '.','biascorr', '()',{':'})); +matlabbatch{3}.cfg_basicio.file_dir.file_ops.file_move.files(2) = cfg_dep('CAT12: Segmentation: Native LAS Bias Corr. Image', substruct('.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('()',{1}, '.','ibiascorr', '()',{':'})); +matlabbatch{3}.cfg_basicio.file_dir.file_ops.file_move.action.delete = false;","MATLAB" +"Neurology","ChristianGaser/cat12","standalone/cat_standalone_segment_long.m",".m","7627","140","% Batch file for CAT12 longitudinal segmentation for SPM12/CAT12 standalone installation +% +%_______________________________________________________________________ +% $Id$ + +% first undefined data field, that will be dynamically replaced by cat_standalone.sh +% The different definitions of the subjects-field are necessary to be compatible +% with CAT12 longitudinal batch (using ""{}"") and cat_standalone where the +% UNDEFINED field is necessary. The clear command prevents error due to different +% datatypes and the comented out part for cat_standalone will be removed in the +% shell script and the last definition of subjects is finally used. Looks weird, +% but only works in that way. +matlabbatch{1}.spm.tools.cat.long.datalong.subjects = {}; +clear matlabbatch +%matlabbatch{1}.spm.tools.cat.long.datalong.subjects = ''; + +% Entry for choosing longitudinal model +% Remove comments and edit entry if you would like to change the parameter. +% Otherwise the default value from cat_defaults.m is used. +% Or use 1st parameter field, that will be dynamically replaced by cat_standalone.sh +% (0) large changes with brain/head growth (i.e. developmental effects) +% (1) small changes (i.e. plasticity/learning effects) +% (2) large changes (i.e. aging effects) +% (3) save results for both models 1 and 2 +%matlabbatch{1}.spm.tools.cat.long.longmodel = ''; + +% Entry for choosing TPM +% Remove comments and edit entry if you would like to change the parameter. +% Otherwise the default value from cat_defaults.m is used. +% Or use 2nd parameter field, that will be dynamically replaced by cat_standalone.sh +%matlabbatch{1}.spm.tools.cat.long.opts.tpm = ''; + +% use priors for longitudinal data +matlabbatch{1}.spm.tools.cat.long.enablepriors = 1; + +% Remove comments and edit entry if you would like to change the Dartel/Shooting approach +% Otherwise the default value from cat_defaults.m is used. +% entry for choosing shooting approach +%matlabbatch{1}.spm.tools.cat.long.extopts.registration.regmethod.shooting.shootingtpm = {fullfile(fileparts(mfilename('fullpath')),'templates_MNI152NLin2009cAsym','Template_0_GS.nii')}; +% entry for choosing dartel approach +%matlabbatch{1}.spm.tools.cat.long.extopts.registration.regmethod.dartel.darteltpm = {fullfile(fileparts(mfilename('fullpath')),'templates_MNI152NLin2009cAsym','Template_1_Dartel.nii')}; +% Strength of Shooting registration: 0 - Dartel, eps (fast), 0.5 (default) to 1 (accurate) optimized Shooting, 4 - default Shooting; default 0.5 +%matlabbatch{1}.spm.tools.cat.long.extopts.registration.regmethod.shooting.regstr = 0.5; + +% additional bounding box +matlabbatch{1}.spm.tools.cat.long.extopts.registration.bb = 12; + +% Affine regularisation (SPM12 default = mni) - '';'mni';'eastern';'subj';'none';'rigid' +matlabbatch{1}.spm.tools.cat.long.opts.affreg = 'mni'; + +% Strength of the bias correction that controls the biasreg and biasfwhm parameter (CAT only!) +% 0 - use SPM parameter; eps - ultralight, 0.25 - light, 0.5 - medium, 0.75 - strong, and 1 - heavy corrections +% job.opts.biasreg = min( 10 , max( 0 , 10^-(job.opts.biasstr*2 + 2) )); +% job.opts.biasfwhm = min( inf , max( 30 , 30 + 60*job.opts.biasstr )); +matlabbatch{1}.spm.tools.cat.long.opts.biasstr = 0.5; + +matlabbatch{1}.spm.tools.cat.long.opts.accstr = 0.5; + +% surface options +matlabbatch{1}.spm.tools.cat.long.extopts.surface.pbtres = 0.5; +matlabbatch{1}.spm.tools.cat.long.extopts.surface.pbtmethod = 'pbt2x'; +matlabbatch{1}.spm.tools.cat.long.extopts.surface.SRP = 22; +matlabbatch{1}.spm.tools.cat.long.extopts.surface.reduce_mesh = 1; +matlabbatch{1}.spm.tools.cat.long.extopts.surface.vdist = 1.33333333333333; +matlabbatch{1}.spm.tools.cat.long.extopts.surface.scale_cortex = 0.7; +matlabbatch{1}.spm.tools.cat.long.extopts.surface.add_parahipp = 0.1; +matlabbatch{1}.spm.tools.cat.long.extopts.surface.close_parahipp = 0; + +matlabbatch{1}.spm.tools.cat.long.extopts.admin.experimental = 0; +matlabbatch{1}.spm.tools.cat.long.extopts.admin.new_release = 0; +matlabbatch{1}.spm.tools.cat.long.extopts.admin.lazy = 0; +matlabbatch{1}.spm.tools.cat.long.extopts.admin.ignoreErrors = 1; +matlabbatch{1}.spm.tools.cat.long.extopts.admin.verb = 2; +matlabbatch{1}.spm.tools.cat.long.extopts.admin.print = 2; + +matlabbatch{1}.spm.tools.cat.long.extopts.segmentation.NCstr = -Inf; +matlabbatch{1}.spm.tools.cat.long.extopts.segmentation.cleanupstr = 0.5; +matlabbatch{1}.spm.tools.cat.long.extopts.segmentation.BVCstr = 0.5; +matlabbatch{1}.spm.tools.cat.long.extopts.segmentation.WMHC = 2; +matlabbatch{1}.spm.tools.cat.long.extopts.segmentation.SLC = 0; +matlabbatch{1}.spm.tools.cat.long.extopts.segmentation.mrf = 1; + +% Affine PreProcessing (APP) with rough bias correction and brain extraction for special anatomies (nonhuman/neonates) +% 0 - none; 1070 - default; [1 - SPM; 5 - animal (no affreg)] +matlabbatch{1}.spm.tools.cat.long.extopts.segmentation.APP = 1070; + +% Strength of the local adaptation: 0 to 1; default 0.5 +matlabbatch{1}.spm.tools.cat.long.extopts.segmentation.LASstr = 0.5; + +% Strength of skull-stripping: 0 - SPM approach; eps to 1 - gcut; 2 - new APRG approach; -1 - no skull-stripping (already skull-stripped); default = 2 +matlabbatch{1}.spm.tools.cat.long.extopts.segmentation.gcutstr = 2; + +% voxel size for normalized data (EXPERIMENTAL: inf - use Template values) +matlabbatch{1}.spm.tools.cat.long.extopts.registration.vox = 1.5; + +% resolution handling: 'native','fixed','best', 'optimal' +matlabbatch{1}.spm.tools.cat.long.extopts.segmentation.restypes.optimal = [1 0.3]; + +% use center-of-mass approach for estimating origin +matlabbatch{1}.spm.tools.cat.long.extopts.segmentation.setCOM = 1; + +% surface and thickness creation: 0 - no (default), 1 - lh+rh, 2 - lh+rh+cerebellum, +% 3 - lh, 4 - rh, 5 - lh+rh (fast, no registration, only for quick quality check and not for analysis), +% 6 - lh+rh+cerebellum (fast, no registration, only for quick quality check and not for analysis) +% 9 - thickness only (for ROI analysis, experimental!) +% +10 to estimate WM and CSF width/depth/thickness (experimental!) +matlabbatch{1}.spm.tools.cat.long.output.surface = 1; + +% BIDS output +matlabbatch{1}.spm.tools.cat.long.output.BIDS.BIDSno = 1; + +% define here volume atlases +matlabbatch{1}.spm.tools.cat.long.ROImenu.atlases.neuromorphometrics = 1; +matlabbatch{1}.spm.tools.cat.long.ROImenu.atlases.lpba40 = 0; +matlabbatch{1}.spm.tools.cat.long.ROImenu.atlases.cobra = 1; +matlabbatch{1}.spm.tools.cat.long.ROImenu.atlases.hammers = 0; +matlabbatch{1}.spm.tools.cat.long.ROImenu.atlases.ibsr = 0; +matlabbatch{1}.spm.tools.cat.long.ROImenu.atlases.aal3 = 0; +matlabbatch{1}.spm.tools.cat.long.ROImenu.atlases.mori = 0; +matlabbatch{1}.spm.tools.cat.long.ROImenu.atlases.thalamus = 0; +matlabbatch{1}.spm.tools.cat.long.ROImenu.atlases.anatomy3 = 0; +matlabbatch{1}.spm.tools.cat.long.ROImenu.atlases.julichbrain3 = 0; +matlabbatch{1}.spm.tools.cat.long.ROImenu.atlases.Schaefer2018_100Parcels_17Networks_order = 0; +matlabbatch{1}.spm.tools.cat.long.ROImenu.atlases.Schaefer2018_200Parcels_17Networks_order = 0; +matlabbatch{1}.spm.tools.cat.long.ROImenu.atlases.Schaefer2018_400Parcels_17Networks_order = 0; +matlabbatch{1}.spm.tools.cat.long.ROImenu.atlases.Schaefer2018_600Parcels_17Networks_order = 0; +matlabbatch{1}.spm.tools.cat.long.ROImenu.atlases.ownatlas = {''}; + +% create and use longitudinal TPM to get more stable segmentations +matlabbatch{1}.spm.tools.cat.long.longTPM = 1; + +% apply modulation +matlabbatch{1}.spm.tools.cat.long.modulate = 1; + +% save dartel export +matlabbatch{1}.spm.tools.cat.long.dartel = 0; + +% delete temporary files +matlabbatch{1}.spm.tools.cat.long.delete_temp = 1; +","MATLAB" +"Neurology","ChristianGaser/cat12","standalone/cat_standalone.sh",".sh","23266","615","#! /bin/bash +# ______________________________________________________________________ +# +# Christian Gaser, Robert Dahnke +# Structural Brain Mapping Group (https://neuro-jena.github.io) +# Departments of Neurology and Psychiatry +# Jena University Hospital +# ______________________________________________________________________ +# $Id$ + +######################################################## +# global parameters +######################################################## +version='cat_standalone.sh $Id$' + +cwd=$(dirname ""$0"") + +if [ ! -n ""$SPMROOT"" ]; then + SPMROOT=$(dirname ""${cwd}"") +fi + +# get cat12 dir +ARCH=`uname` +if [ ""$ARCH"" == ""Darwin"" ]; then + cat12_dir=""${SPMROOT}/spm25.app/Contents/MacOS/spm12/toolbox/cat12"" +else + cat12_dir=""your_folder/spm12/toolbox/cat12"" +fi + +# default values +standalone=1 +expert=0 +fg=0 +matlab=matlab # you can use other matlab versions by changing the matlab parameter + +######################################################## +# run main +######################################################## + +main () +{ + parse_args ${1+""$@""} + check_files + run_cat + + exit 0 +} + +######################################################## +# check arguments and files +######################################################## + +parse_args () +{ + local optname optarg + count=0 + paras= + + if [ $# -lt 1 ]; then + help + exit 1 + fi + + while [ $# -gt 0 ]; do + optname=""`echo $1 | sed 's,=.*,,'`"" + optarg=""`echo $2`"" + paras=""$paras $optname $optarg"" + case ""$1"" in + --batch* | -b*) + exit_if_empty ""$optname"" ""$optarg"" + BATCHFILE=$optarg + shift + ;; + --mcr* | -m*) + exit_if_empty ""$optname"" ""$optarg"" + MCRROOT=$optarg + shift + ;; + --spm* | -s*) + exit_if_empty ""$optname"" ""$optarg"" + SPMROOT=$optarg + shift + ;; + --arg1* | -a1*) + exit_if_empty ""$optname"" ""$optarg"" + ARG1=$optarg + shift + ;; + --arg2* | -a2*) + exit_if_empty ""$optname"" ""$optarg"" + ARG2=$optarg + shift + ;; + --arg3* | -a3*) + exit_if_empty ""$optname"" ""$optarg"" + ARG3=$optarg + shift + ;; + --add* | -a*) + exit_if_empty ""$optname"" ""$optarg"" + add_to_batch=""$optarg"" + shift + ;; + --fg* | -fg*) + exit_if_empty ""$optname"" ""$optarg"" + fg=1 + ;; + --no-s* | -ns*) + exit_if_empty ""$optname"" ""$optarg"" + standalone=0 + ;; + --e* | -e*) + exit_if_empty ""$optname"" ""$optarg"" + expert=1 + ;; + -h* | --h* | -v | --version | -V) + help + exit 1 + ;; + -*) + echo ""`basename $0`: ERROR: Unrecognized option \""$1\"""" >&2 + ;; + *) + ARRAY[$count]=$1 + ((count++)) + ;; + esac + shift + done +} + +######################################################## +# check arguments +######################################################## + +exit_if_empty () +{ + local desc val + + desc=""$1"" + shift + val=""$*"" + +} + +######################################################## +# check files +######################################################## + +check_files () +{ + + # check for SPM parameter + if [ ! -n ""$SPMROOT"" ]; then + echo ""No SPM folder defined."" + help + exit 1 + fi + + # check this only for standalone version + if [ $standalone == 1 ]; then + # check for MCR parameter + if [ ! -n ""$MCRROOT"" ]; then + echo ""No MCR folder defined."" + help + exit 1 + fi + + # check for MCR folder + if [ ! -d ""$MCRROOT"" ]; then + echo ""No MCR folder found."" + help + exit 1 + fi + + # check for SPM folder + if [ ! -f ""$SPMROOT/run_spm25.sh"" ]; then + echo ""File $SPMROOT/run_spm25.sh not found found."" + help + exit 1 + fi + else + # we use the same flag as for MCRROOT, but here for Matlab command + if [ -n ""$MCRROOT"" ]; then + eval ""matlab=\""$MCRROOT\"";"" + fi + + found=`which ""${matlab}"" 2>/dev/null` + if [ ! -n ""$found"" ]; then + echo $matlab not found. + exit 1 + fi + fi + + # check for batch file + if [ ! -n ""$BATCHFILE"" ]; then + echo ""No batch file defined."" + help + exit 1 + fi + + # check for files + i=0 + while [ ""$i"" -lt ""$count"" ] + do + if [ ! -f ""${ARRAY[$i]}"" ]; then + if [ ! -L ""${ARRAY[$i]}"" ]; then + echo ERROR: File ${ARRAY[$i]} not found + help + exit 1 + fi + fi + ((i++)) + done + +} + +######################################################## +# run CAT +######################################################## + +run_cat () +{ + + # if no files are given expect that file name is defined + # in batch file and execute that file + if [ ""$count"" -eq ""0"" ] && [ $standalone == 1 ] ; then + eval ""\""${SPMROOT}/run_spm25.sh\"""" $MCRROOT ""batch"" $BATCHFILE + exit 0 + fi + + if [ ""$count"" -eq ""0"" ] ; then + c2=1 + c3=2 + c4=3 + else + c2=2 + c3=3 + c4=4 + fi + + # create temporary batch file + TMP=/tmp/cat_$$.m + + # copy everything except rows with UNDEFINED to temp file + grep -v """" $BATCHFILE > $TMP + + if [ ! ""$count"" -eq ""0"" ] ; then + # extract parameter name of data structure (1st occurance of """") + data=`grep -m 1 """" $BATCHFILE | cut -f1 -d'='| sed -e 's,%,,'` + + # surface data need an additional curly bracket + if grep -q -e ""\.datalong"" $BATCHFILE ; then + echo ""$data = {{"" >> $TMP + else + echo ""$data = {"" >> $TMP + fi + fi + + # extract parameter name of optional argument(s) (additional occurances of """") + if [ -n ""$ARG1"" ]; then # ARG1 defined? + param1=`grep -m $c2 """" $BATCHFILE | tail -n 1 | cut -f1 -d'=' | sed -e 's,%,,'` + # extract parameter name of optional argument (3rd occurance of """") + if [ -n ""$ARG2"" ]; then # ARG2 defined? + param2=`grep -m $c3 """" $BATCHFILE | tail -n 1 | cut -f1 -d'=' | sed -e 's,%,,'` + # extract parameter name of optional argument (4th occurance of """") + if [ -n ""$ARG3"" ]; then # ARG3 defined? + param3=`grep -m $c4 """" $BATCHFILE | tail -n 1 | cut -f1 -d'=' | sed -e 's,%,,'` + fi + fi + fi + + i=0 + ARG_LIST="""" + while [ ""$i"" -lt ""$count"" ]; do + + # check whether absolute or relative names were given + if [ ! -f ${ARRAY[$i]} ]; then + if [ -f ${PWD}/${ARRAY[$i]} ]; then + FILE=${PWD}/${ARRAY[$i]} + fi + else + FILE=${ARRAY[$i]} + fi + + # add file list + echo ""'${FILE}'"" >> $TMP + + ((i++)) + done + + if [ ! ""$count"" -eq ""0"" ] ; then + # surface data need an additional curly bracket + if grep -q -e ""\.datalong"" $BATCHFILE ; then + echo "" }};"" >> $TMP + else + echo "" };"" >> $TMP + fi + fi + + if [ -n ""$ARG1"" ]; then # ARG1 defined? + echo ""$param1 = $ARG1 ;"" >> $TMP + if [ -n ""$ARG2"" ]; then # ARG2 defined? + echo ""$param2 = $ARG2 ;"" >> $TMP + if [ -n ""$ARG3"" ]; then # ARG3 defined? + echo ""$param3 = $ARG3 ;"" >> $TMP + fi + fi + fi + + # add optional lines to batch file + if [ -n ""$add_to_batch"" ]; then + echo ""${add_to_batch}"" >> ${TMP} + fi + + if [ $standalone == 1 ]; then + eval ""\""${SPMROOT}/run_spm25.sh\"""" $MCRROOT ""batch"" $TMP + rm $TMP + exit 0 + else + DIR=$(dirname ""${TMP}"") + + # we have to check where spm.m is found + if [ ! -f ${SPMROOT}/spm.m ]; then + SPMROOT=$(dirname ""${SPMROOT}"") + SPMROOT=$(dirname ""${SPMROOT}"") + fi + + BATCHFILE=$(basename ""${TMP}"") + BATCHFILE=$(echo ""${BATCHFILE}"" | cut -f1 -d'.') + cat12_dir=""${SPMROOT}/toolbox/cat12"" + export MATLABPATH=${SPMROOT}:${cat12_dir}:${DIR} + eval ""COMMAND=\""$BATCHFILE\"";"" + + if [ $expert == 1 ]; then + COMMAND=""spm; spm_get_defaults; cat_get_defaults; global defaults cat matlabbatch; cat12('expert'); $COMMAND;spm_jobman('run',matlabbatch); exit;""; + else + COMMAND=""spm; spm_get_defaults; cat_get_defaults; global defaults cat matlabbatch;$COMMAND;spm_jobman('run',matlabbatch); exit;""; + fi + if [ ""$fg"" -eq 0 ]; then + nohup nice ${matlab} -nodisplay -nosplash -r ""$COMMAND"" 2>&1 & + else + nohup nice ${matlab} -nodisplay -nosplash -r ""$COMMAND"" 2>&1 + fi + fi +} + + +######################################################## +# help +######################################################## + +help () +{ + + # do not use a single dot + if [ ""$SPMROOT"" == ""."" ]; then + SPMROOT=""SPMROOT"" + fi + +cat <<__EOM__ + +USAGE: + cat_standalone.sh filename(s) [-s spm_standalone_folder] [-m mcr_folder] [-b batch_file] + [-a1 additional_argument1] [-a2 additional_argument2] + [-a add_to_batch] [-ns -e -fg] + + -s | --spm SPM12 folder of standalone version (can be also defined by SPMROOT) + Often you don't need to define that option because the SPM12 folder + is automatically found. + -m | --mcr Matlab Compiler Runtime (MCR) folder (can be also defined by MCRROOT) + -b | --batch batch file to execute + -a1 | --arg1 1st additional argument (otherwise use defaults or batch) + -a2 | --arg2 2nd additional argument (otherwise use defaults or batch) + -a3 | --arg3 3rd additional argument (otherwise use defaults or batch) + -a | --add add option to batch file + + options for calling standard Matlab mode + -ns | --no-standalone call the standard Matlab version instead of the standalone version + -e | --expert call CAT12 in expert mode (needed for using standalone batches!) + -fg | --fg do not run matlab process in background + -m | --m Matlab command (matlab version) (default $matlab) + + The first occurance of the parameter """" in the batch file will be replaced by the + list of input files. You can use the existing batch files in this folder or create your own batch + file with the SPM12 batch editor and leave the data field undefined. Please note that for creating + your own batch file CAT12 has to be called in expert mode because the CAT12 standalone installation + will only run in expert mode to allow more options. + See cat_standalone_segment.m for an example. + + You can also define one or two optional arguments to change other parameters that are indicated by + """" in the batch file. Please take care of the order of the """" fields in the + batch file! If no additional arguments are defined the default values are used. + Also, you must use multiple quotes if the argument is a string (e.g. "" 'your_string' ""). + + If you use a computer cluster it is recommended to use the batch files to only process one data set + and use a job or queue tool to call the (single) jobs on the cluster. + + Although this tool is mainly intended for calling scripts for the standalone version of Matlab without + a Matlab license, you can also use it to call the standard version of Matlab. If you have a Matlab + license, this has the advantage that you can use the same scripts as for the standalone version, but + you can run CAT12 without a GUI. Please note that standalone batches must be called in CAT12 expert + mode. Of course, you can also create and use your own batches that you use regulary in CAT12 or + SPM12. With this script you can run these batches in headless mode without any display. + + PURPOSE: + Command line call of (CAT12) batch files for SPM12 standalone installation + +EXAMPLES + ----------------------------------------------------------------------------------------------- + Dicom Import + -a1 directory structure + -a2 output directory + ----------------------------------------------------------------------------------------------- + cat_standalone.sh -m /Applications/MATLAB/MATLAB_Runtime/v232 \ + -b ${cwd}/cat_standalone_dicom2nii.m *.dcm \ + -a1 "" 'patid_date' "" -a2 ""{'converted'}"" + Import DICOM files *.dcm and save converted nifti files in directory ""converted"" with structure + ./// + Other options for directory structure are: + 'flat' No directory hierarchy + 'series' ./ + 'patid_date' ./// + 'patid' .// + 'date_time' .// + Please note the multiple quotes for parameter a1. + + ----------------------------------------------------------------------------------------------- + De-facing + ----------------------------------------------------------------------------------------------- + cat_standalone.sh -m /Applications/MATLAB/MATLAB_Runtime/v232 \ + -b ${cwd}/cat_standalone_deface.m sTRIO*.nii + Apply de-facing to sTRIO*.nii and save the files prefixed by ""anon_"". + + ----------------------------------------------------------------------------------------------- + Segmentation + -a1 TPM + -a2 Shooting template + ----------------------------------------------------------------------------------------------- + cat_standalone.sh -m /Applications/MATLAB/MATLAB_Runtime/v232 \ + -b ${cwd}/cat_standalone_segment.m sTRIO0001.nii + Preprocess (segment) the single file sTRIO0001.nii using the default CAT12 preprocessing batch. + SPM12 standalone version is located in $SPMROOT and Matlab Compiler Runtime in + /Applications/MATLAB/MATLAB_Runtime/v232. + + cat_standalone.sh -m /Applications/MATLAB/MATLAB_Runtime/v232 \ + -b ${cwd}/cat_standalone_segment.m sTRIO000*.nii.gz \ + -a1 "" '${cat12_dir}/templates_MNI152NLin2009cAsym/TPM_Age11.5.nii' "" \ + -a2 "" '${cat12_dir}/templates_MNI152NLin2009cAsym/Template_0_GS1mm.nii' "" + Unzip and preprocess (segment) the files sTRIO0001.nii.gz using the default CAT12 preprocessing + batch, but use the children TPM provided with CAT12 and a 1mm Shooting template (not provided + with CAT12). Please note that zipped file can only be handled with this standalone batch and also + note the multiple quotes for parameter a1 and a2. + + cat_standalone.sh -m /Applications/MATLAB/MATLAB_Runtime/v232 \ + -b ${cwd}/cat_standalone_segment.m sTRIO0001.nii \ + -a ""matlabbatch{1}.spm.tools.cat.estwrite.output.surface = 0;"" + Preprocess (segment) the single file sTRIO0001.nii using the default CAT12 preprocessing batch, + but skip surface estimation. + + ----------------------------------------------------------------------------------------------- + Longitudinal segmentation + -a1 longitudinal model (0 - developmental; 1 - plasticity/learning; 2 - aging; 3 - save models 1 and 2) + -a2 TPM + ----------------------------------------------------------------------------------------------- + cat_standalone.sh -m /Applications/MATLAB/MATLAB_Runtime/v232 \ + -b ${cwd}/cat_standalone_segment_long.m sTRIO000*.nii \ + -a1 ""2"" + Preprocess (segment) the files sTRIO000*.nii with the longitudinal pipeline optimized for + detecting aging/developmental effects. In order to choose the longitudinal model optimized for + detecting small changes due to plasticity/learning change the a1 parameter to ""1"". + + cat_standalone.sh -m /Applications/MATLAB/MATLAB_Runtime/v232 \ + -b ${cwd}/cat_standalone_segment_long.m sTRIO000*.nii \ + -a1 ""1"" -a2 "" '${cat12_dir}/templates_MNI152NLin2009cAsym/TPM_Age11.5.nii' "" + Preprocess (segment) the files sTRIO000*.nii with the longitudinal pipeline optimized for + detecting plasticity/learning effects and use the children TPM provided with CAT12. + Please note the multiple quotes for parameter a2. + + ----------------------------------------------------------------------------------------------- + Segmentation (simple mode) + ----------------------------------------------------------------------------------------------- + cat_standalone.sh -m /Applications/MATLAB/MATLAB_Runtime/v232 \ + -b ${cwd}/cat_standalone_simple.m sTRIO0001.nii + Process the single file sTRIO0001.nii using the simple processing batch. + + ----------------------------------------------------------------------------------------------- + Resample & smooth surfaces + -a1 smoothing filter size surface values + -a2 use 32k mesh from HCP (or 164k mesh from Freesurfer) + ----------------------------------------------------------------------------------------------- + cat_standalone.sh -m /Applications/MATLAB/MATLAB_Runtime/v232 \ + -b ${cwd}/cat_standalone_resample.m surf/lh.thickness.sTRIO0001 \ + -a1 ""12"" -a2 ""1"" + Resample and smooth the single thickness file lh.thickness.sTRIO0001 with 12mm and save the + resampled mesh as 32k mesh (HCP conform mesh). Only the left surface file has to be defined. + The right hemisphere is processed automatically. + + ----------------------------------------------------------------------------------------------- + Smoothing + -a1 smoothing filter size + -a2 prepending string for smoothed file (e.g. 's6') + ----------------------------------------------------------------------------------------------- + cat_standalone.sh -m /Applications/MATLAB/MATLAB_Runtime/v232 \ + -b ${cwd}/cat_standalone_smooth.m mri/sTRIO*nii \ + -a1 ""[6 6 6]"" -a2 "" 's6' "" + Smooth the volume files sTRIO*nii with 6mm and prepend the string ""s6"" to the smoothed files. + Please note the multiple quotes for parameter a2. + + ----------------------------------------------------------------------------------------------- + Estimate and save quality measures for volumes or surfaces + -a1 csv output filename + -a2 enable global scaling with TIV (only for volumes meaningful) + ----------------------------------------------------------------------------------------------- + cat_standalone.sh -m /Applications/MATLAB/MATLAB_Runtime/v232 \ + -b ${cwd}/cat_standalone_get_quality.m mri/mwp1sTRIO*nii \ + -a1 "" 'Quality_measures.csv' "" -a2 ""1"" + Estimate sample homogeneity (after preprocessing) using mean z-scores with global scaling with TIV + for the files mwp1sTRIO*nii and save quality measures in Quality_measures.csv for external analysis. + Processing of surface meshes is also supported. + Please note the multiple quotes for parameter a1. + + ----------------------------------------------------------------------------------------------- + Estimate and save weighted overall image quality + -a1 csv output filename + -a2 enable global scaling with TIV (only for volumes meaningful) + ----------------------------------------------------------------------------------------------- + cat_standalone.sh -m /Applications/MATLAB/MATLAB_Runtime/v232 \ + -b ${cwd}/cat_standalone_get_IQR.m report/cat_*.xml \ + -a1 "" 'IQR.txt' "" + Estimate weighted overall image quality (before preprocessing) using xml-files in report folder + and save IQR measures in IQR.txt for external analysis. + Please note the multiple quotes for parameter a1. + + ----------------------------------------------------------------------------------------------- + Estimate mean/volume inside ROI + -a1 output-file string + ----------------------------------------------------------------------------------------------- + cat_standalone.sh -m /Applications/MATLAB/MATLAB_Runtime/v232 \ + -b ${cwd}/cat_standalone_get_ROI_values.m label/catROI_*.xml \ + -a1 "" 'ROI' "" + Save mean volume values in mL (e.g. GM volume) or the mean surface values (e.g. thickness) for + all data catROI_*.xml in a csv-file. The csv-file is named ""ROI_"" followed by the atlas name + and the name of the measure (e.g. Vgm). + Please note the multiple quotes for parameter a1. + + ----------------------------------------------------------------------------------------------- + Estimate total intra-cranial volume (TIV) or all global tissue volumes (in ml) + -a1 output filename + -a2 save TIV only + -a3 add filenames + ----------------------------------------------------------------------------------------------- + cat_standalone.sh -m /Applications/MATLAB/MATLAB_Runtime/v232 \ + -b ${cwd}/cat_standalone_getTIV.m report/cat_*.xml \ + -a1 "" 'TIV.txt' "" -a2 ""1"" -a3 ""1"" + Estimate TIV only and save file names and values for each data set in TIV.txt. + The parameter a3 allows to add file names to 1st column: + 0 - save values only; 1 - add file name; 2 - add folder and file name + Please note the multiple quotes for parameter a1. + + ----------------------------------------------------------------------------------------------- + TFCE statistical estimation + -a1 contrast number + -a2 number of permutations + ----------------------------------------------------------------------------------------------- + cat_standalone.sh -m /Applications/MATLAB/MATLAB_Runtime/v232 \ + -b ${cwd}/cat_standalone_tfce.m SPM.mat \ + -a1 ""2"" -a2 ""20000"" + Call estimation of TFCE statistics for the given SPM.mat file for contrast number 2 with 20000 + permutations. + + ----------------------------------------------------------------------------------------------- + Calling standard Matlab mode + ----------------------------------------------------------------------------------------------- + cat_standalone.sh -ns -e -m matlab_R2023b \ + -b ${cwd}/cat_standalone_segment.m sTRIO0001.nii \ + -a ""matlabbatch{1}.spm.tools.cat.estwrite.output.surface = 0;"" + Preprocess (segment) the single file sTRIO0001.nii in standard Matlab mode (using CAT12 expert + mode) and the default CAT12 preprocessing batch, but skip surface estimation. As Matlab command + matlab_R2023b is used. + + ----------------------------------------------------------------------------------------------- + Parallelization + ----------------------------------------------------------------------------------------------- + cat_parallelize.sh -p 8 -l /tmp \ + -c ""cat_standalone.sh -m /Applications/MATLAB/MATLAB_Runtime/v232 -b ${cwd}/cat_standalone_segment.m"" sTRIO*.nii + Parallelize CAT12 preprocessing by splitting all sTRIO*.nii files into 8 jobs + (processes) and save log file in /tmp folder. + + The parameters SPMROOT and MCRROOT have to be defined (exported) to skip the use of the flags -s -m. + +INPUT: + nifti files or surface data + +OUTPUT: + processed images and optionally surfaces according to settings in cat_standalone_*.m + +USED FUNCTIONS: + cat_parallelize.sh + SPM12 standalone version (compiled) + CAT12 toolbox (compiled within SPM12 if installed) + MATLAB Compiler Runtime R2023b (Version 23.2) + +This script was written by Christian Gaser (christian.gaser@uni-jena.de). +This is ${version}. + +__EOM__ +} + +######################################################## +# call main program +######################################################## + +main ${1+""$@""} +","Shell" +"Neurology","ChristianGaser/cat12","standalone/cat_standalone_tfce.m",".m","1304","29","% Batch file for TFCE statistics for SPM12/CAT12 standalone installation +% +%_______________________________________________________________________ +% $Id$ + +% data field, that will be dynamically replaced by cat_standalone.sh +matlabbatch{1}.spm.tools.tfce_estimate.data = ''; + +% Entry for contrast number +% Remove comments and edit entry if you would like to change the contrast number. +% Otherwise the default value is used. +% Or use 1st parameter field, that will be dynamically replaced by cat_standalone.sh +%matlabbatch{1}.spm.tools.tfce_estimate.conspec.contrasts = ''; + +% Entry for number of permutations +% Remove comments and edit entry if you would like to change the number of permutations. +% Otherwise the default value is used. +% Or use 2nd parameter field, that will be dynamically replaced by cat_standalone.sh +%matlabbatch{1}.spm.tools.tfce_estimate.conspec.n_perm = ''; + +matlabbatch{1}.spm.tools.tfce_estimate.nproc = 0; +matlabbatch{1}.spm.tools.tfce_estimate.mask = ''; +matlabbatch{1}.spm.tools.tfce_estimate.conspec.titlestr = ''; +matlabbatch{1}.spm.tools.tfce_estimate.nuisance_method = 2; +matlabbatch{1}.spm.tools.tfce_estimate.tbss = 0; +matlabbatch{1}.spm.tools.tfce_estimate.E_weight = 0.5; +matlabbatch{1}.spm.tools.tfce_estimate.singlethreaded = 0; + +","MATLAB" +"Neurology","ChristianGaser/cat12","standalone/cat_standalone_get_IQR.m",".m","632","14","% Batch file for getting weighted overall image quality for SPM12/CAT12 standalone installation +% +%_______________________________________________________________________ +% $Id$ + +% data field, that will be dynamically replaced by cat_standalone.sh +matlabbatch{1}.spm.tools.cat.tools.iqr.data_xml = ''; + +% Entry for txt output filename +% Remove comments and edit entry if you would like to change the parameter. +% Otherwise the default value from cat_defaults.m is used. +% Or use 1st parameter field, that will be dynamically replaced by cat_standalone.sh +%matlabbatch{1}.spm.tools.cat.tools.iqr.iqr_name = ''; +","MATLAB" +"Neurology","ChristianGaser/cat12","standalone/cat_standalone_get_ROI_values.m",".m","737","17","% Batch file for getting ROI values for SPM12/CAT12 standalone installation +% +%_______________________________________________________________________ +% $Id$ + +% data field, that will be dynamically replaced by cat_standalone.sh +matlabbatch{1}.spm.tools.cat.tools.calcroi.roi_xml = ''; + +% Entry for output-file string +% Remove comments and edit entry if you would like to change the parameter. +% Otherwise the default value from cat_defaults.m is used. +% Or use 1st parameter field, that will be dynamically replaced by cat_standalone.sh +%matlabbatch{1}.spm.tools.cat.tools.calcroi.calcroi_name = ''; + +matlabbatch{1}.spm.tools.cat.tools.calcroi.point = '.'; +matlabbatch{1}.spm.tools.cat.tools.calcroi.outdir = {''}; +","MATLAB" +"Neurology","ChristianGaser/cat12","standalone/cat_standalone_smooth.m",".m","1032","24","% Batch file for volume smoothing for SPM12/CAT12 standalone installation +% +%_______________________________________________________________________ +% $Id$ + +% data field, that will be dynamically replaced by cat_standalone.sh +matlabbatch{1}.spm.spatial.smooth.data = ''; + +% Entry for choosing smoothing filter size +% Remove comments and edit entry if you would like to change the parameter. +% Otherwise the default value from cat_defaults.m is used. +% Or use 1st parameter field, that will be dynamically replaced by cat_standalone.sh +%matlabbatch{1}.spm.spatial.smooth.fwhm = ''; + +% Entry for prepending string for smoothed file (e.g. 's6') +% Remove comments and edit entry if you would like to change the parameter. +% Otherwise the default value from cat_defaults.m is used. +% Or use 1st parameter field, that will be dynamically replaced by cat_standalone.sh +%matlabbatch{1}.spm.spatial.smooth.prefix = ''; + +matlabbatch{1}.spm.spatial.smooth.dtype = 0; +matlabbatch{1}.spm.spatial.smooth.im = 0; + +","MATLAB" +"Neurology","ChristianGaser/cat12","standalone/cat_standalone_simple.m",".m","3472","60","% Batch file for CAT12 simple processing for SPM12/CAT12 standalone installation +% +%_______________________________________________________________________ +% $Id$ + +% data field, that will be dynamically replaced by cat_standalone.sh +matlabbatch{1}.spm.tools.cat.cat_simple.data = ''; + +% template for initial affine registration/segmentation; 'adult','children' +matlabbatch{1}.spm.tools.cat.cat_simple.tpm = 'adults'; + +matlabbatch{1}.spm.tools.cat.cat_simple.registration.regmethod.shooting.shootingtpm = {fullfile(fileparts(mfilename('fullpath')),'templates_MNI152NLin2009cAsym','Template_0_GS.nii')}; + +% voxel size and bounding box +matlabbatch{1}.spm.tools.cat.cat_simple.registration.vox = 1.5; +matlabbatch{1}.spm.tools.cat.cat_simple.registration.bb = 12; + +% smoothing filter size for volumes +matlabbatch{1}.spm.tools.cat.cat_simple.fwhm_vol = 6; + +% define here volume atlases +matlabbatch{1}.spm.tools.cat.cat_simple.ROImenu.atlases.neuromorphometrics = 1; +matlabbatch{1}.spm.tools.cat.cat_simple.ROImenu.atlases.lpba40 = 0; +matlabbatch{1}.spm.tools.cat.cat_simple.ROImenu.atlases.cobra = 1; +matlabbatch{1}.spm.tools.cat.cat_simple.ROImenu.atlases.hammers = 0; +matlabbatch{1}.spm.tools.cat.cat_simple.ROImenu.atlases.ibsr = 0; +matlabbatch{1}.spm.tools.cat.cat_simple.ROImenu.atlases.aal3 = 0; +matlabbatch{1}.spm.tools.cat.cat_simple.ROImenu.atlases.mori = 0; +matlabbatch{1}.spm.tools.cat.cat_simple.ROImenu.atlases.thalamus = 0; +matlabbatch{1}.spm.tools.cat.cat_simple.ROImenu.atlases.anatomy3 = 0; +matlabbatch{1}.spm.tools.cat.cat_simple.ROImenu.atlases.julichbrain3 = 0; +matlabbatch{1}.spm.tools.cat.cat_simple.ROImenu.atlases.Schaefer2018_100Parcels_17Networks_order = 0; +matlabbatch{1}.spm.tools.cat.cat_simple.ROImenu.atlases.Schaefer2018_200Parcels_17Networks_order = 0; +matlabbatch{1}.spm.tools.cat.cat_simple.ROImenu.atlases.Schaefer2018_400Parcels_17Networks_order = 0; +matlabbatch{1}.spm.tools.cat.cat_simple.ROImenu.atlases.Schaefer2018_600Parcels_17Networks_order = 0; +matlabbatch{1}.spm.tools.cat.cat_simple.ROImenu.atlases.ownatlas = {''}; + +% catch errors: 0 - stop with error (default); 1 - catch preprocessing errors (requires MATLAB 2008 or higher); +matlabbatch{1}.spm.tools.cat.cat_simple.ignoreErrors = 1; + +% define here surface atlases +matlabbatch{1}.spm.tools.cat.cat_simple.surface.yes.sROImenu.satlases.Desikan = 1; +matlabbatch{1}.spm.tools.cat.cat_simple.surface.yes.sROImenu.satlases.HCP = 0; +matlabbatch{1}.spm.tools.cat.cat_simple.surface.yes.sROImenu.satlases.Destrieux = 0; +matlabbatch{1}.spm.tools.cat.cat_simple.surface.yes.sROImenu.satlases.Schaefer2018_100P_17N = 0; +matlabbatch{1}.spm.tools.cat.cat_simple.surface.yes.sROImenu.satlases.Schaefer2018_200P_17N = 0; +matlabbatch{1}.spm.tools.cat.cat_simple.surface.yes.sROImenu.satlases.Schaefer2018_400P_17N = 0; +matlabbatch{1}.spm.tools.cat.cat_simple.surface.yes.sROImenu.satlases.Schaefer2018_600P_17N = 0; +matlabbatch{1}.spm.tools.cat.cat_simple.surface.yes.sROImenu.satlases.ownatlas = {''}; + +% smoothing filter size for cortical thickness (fwhm_surf1) and gyrification (fwhm_surf2) +matlabbatch{1}.spm.tools.cat.cat_simple.surface.yes.fwhm_surf1 = 12; +matlabbatch{1}.spm.tools.cat.cat_simple.surface.yes.fwhm_surf2 = 20; + +% in order to skip surface processing remove this comment and add comments +% to all line with parameter "".surface.yes"" +% matlabbatch{1}.spm.tools.cat.cat_simple.surface.no = 1; + +% disable parallel processing +","MATLAB" +"Neurology","ChristianGaser/cat12","batches/cat12_postmortem.m",".m","44078","627","%----------------------------------------------------------------------- +% Job saved on 05-Aug-2021 10:59:09 by cfg_util (rev $Rev$) +% spm SPM - SPM12 (7771) +% cfg_basicio BasicIO - Unknown +%----------------------------------------------------------------------- + +%----------------------------------------------------------------------- +% Batch for preprocess high-resolution ex-vivo PD data with SPM and CAT +% to create volume and surfaces data for structural analyses. The batch +% presented only a first attempt and to process the data presented in +% (Edlow et al., 2019). +% +% Edlow, B.L., Mareyam, A., Horn, A., Polimeni, J.R., Witzel, T., +% Tisdall, M.D., Augustinack, J.C., Stockmann, J.P., Diamond, B.R., +% Stevens, A., Tirrell, L.S., Folkerth, R.D., Wald, L.L., Fischl, B.R., +% van der Kouwe, A., 2019. +% 7 Tesla MRI of the ex vivo human brain at 100 micron resolution. +% Sci. Data 6, 1-10. doi:10.1038/s41597-019-0254-8 +% +% Data: +% https://kottke.org/19/07/the-highest-resolution-mri-scan-of-a-human-brain +% +% +% Use: +% * Start SPM/CAT with: +% spm 'fmri'; cat12('developer') +% * Specify your own directories below +% * Update some variables such as ""resolution"" and ""spm_res_factor"" that +% are defined for a fast test run +% * Open the SPM batch mode via SPM GUI +% * Open this batch in the SPM batch mode +% * Start the batch (if it is not ready or create errors then start +% checking the input files) +% +% +% Known limitations and problems (20210808): +% * I am currently limited to only 2 test datasets. +% +% * There were multiple problems due to the segmentation, even with reduced +% classes. I tried two models: (1) a 3-class model with GM, WM, and +% CSF/BG (background) and (2) a 4-class model with GM, WM, CSF, and BG. +% Both are not really perfect but the simpler model fit a bit better. +% +% * The 4-class model can also be used to skull-stripping the image. This +% can help in some way (e.g. bias correction) but there are some strange +% side effect and in the stripped background the TPM probability appeared +% (i.e. there was soft GM ribbon around the old brainmask). +% +% * I tried different number of Gaussians per tissue but it did not work in +% the way I see by eye in the images. Besides the SPM/CAT defaults [1 1 2] +% for [GM,WM,CSF/BG] I got good results for [2,1,3]. +% +% * Intensity normalization/limitation helped overall to remove some crazy +% outliers and I added it multiple times. +% +% * Moreover, I observed that increased segmentation sampling resolution +% (samp<3) result in larger problems especially in images with higher +% resolution (the background was often miss-classified as GM or WM). +% I also tried high numbers of Gaussians per tissue class without success. +% +% In conclusion, I think the samp parameter of the unified segmentation has +% the strongest effect and I was not able to find a way to use higher +% sampling (samp<3) here that generally improve segmentation quality. +% In addition, the changed gaussians, as well as the intensity limitation +% improved the result +% +% +% Methods: +% (1) Trimming +% (2) Denoising +% (3) Downsampling +% (4) Data range limitation +% (5) Unified segmentation +% (6) CAT12 preprocessing for SPM segmentation +% (7) CAT12 preprocessing +% +% Further directions/optimizations: +% * The high-res PD data may allow an enhanced cortical model with two or +% three GM MRI layer with very bright layer (lamina 1-2?), a medium dark +% layer (lamina 3,5 and 6?) and a dark layer (lamina 4). On the other +% side, a higher number of Gaussians is quite similar and also not really +% working, i.e., high affords but low benefit . +% * Moreover, some WM regions could be defined as separate class, as well +% as some damaged areas (lesions?). However, this would require to create +% a standard GM,WM,CSF/background input model. +% +% * Moreover, the surface reconstruction has to use the segmentation and +% not the original data as far as this pipeline (cat_surf_create[2]) is +% optimized for T1 data. +% > a simulated T1 dataset (inverted image) maybe works better +% +%----------------------------------------------------------------------- +% Robert Dahnke 2020/09 (robert.dahnke@uni-jena.de) +%----------------------------------------------------------------------- +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +%----------------------------------------------------------------------- +% $Id$ + + +% Todo: +% - extend to strongly trimmed images or better set up CAT processing +% - add non-developer version + +% set random generators for SPM (not really working) +if exist('rng','file') == 2, rng('default'); rng(0); else, rand('state',0); randn('state',0); end +warning('OFF','MATLAB:RandStream:ActivatingLegacyGenerators'); + +% clear old stuff +clear matlabbatch; + + +% (0) Define the path to your files and directories here! +data = { + {'/Volumes/WD4TBE/MRData/202106 UHR PD/Acquired_FA25_downsampled_200um.nii,1'} + }; +TPM = fullfile(spm('dir'),'TPM','TPM.nii'); +template_dir = fullfile(spm('dir'),'toolbox','cat12','templates_MNI152NLin2009cAsym'); +resolution = 0.5; %0.8; % define here the resolution you want (0 - original resolution) + % for fast test use 0.8 mm +samp = 3.0; % 3 mm is ok, +tol = 1e-32; % super accurate to correct even strong inhomogeneities but it will take a while +%spm_res_factor = 1.5/resolution; % use x-times lower sampling resolution (depending on the resolution variable) for SPM for faster tests + % for a resolution of 0.8 and spm_res_factor of 2 SPM will use 1.6 mm (default is 3 mm for human data and) +nproc = 0; % number of parallel processes of the CAT preprocessing +surfaces = 1; % (0 - none, 1 - yes) +reduce_mesh = 5; % more accurate but maybe with fatal Matlab crash (just try to rerun) otherwise use 1 (optimal by volume reduction) +%ngaus = [1 1 2 3]; % [GM WM CSF[/BG | BG]] ... [2 1 3 4] seems also to work +ngaus = [2 1 3 4]; % [GM WM CSF[/BG | BG]] ... [2 1 3 4] seems also to work +BGmodel = 2; % 0 - 4-class, 1 - 4-class-skull-stripped, 2 - 3-class(CSFBG) +BC = 0; +lazy = 1; % do not reprocess data if the input was not modified (default = 0) + + +% (0) Display parameter ... +%{ +fprintf('Ultra-high resolution preprocessing batch: ') +for fi = 1:numel(data) + [pp,ff,ee] = spm_fileparts(data{fi}); + file = fullfile(pp,[ff ee]); + if ~exist(file,'file') + cat_io_printf('err',sprintf('ERROR: Image %d/%d - ""%s"" does not exist!\n',fi,numel(data),) + end +end +%} + +% (1) Trimm the image and remove empty space around the brain to save +% memory and increase processing time. There are many parameters but +% no changes are required. +% ######### +% TODO: +% * It would be better to use mm rather than voxel for the limitation +% * It could be helpful to guaranty some boundary (e.g. for resampling) +% ######### +mi=1; +matlabbatch{mi}.spm.tools.cat.tools.datatrimming.image_selector.subjectimages = data; +matlabbatch{mi}.spm.tools.cat.tools.datatrimming.prefix = 'trimmed_'; +matlabbatch{mi}.spm.tools.cat.tools.datatrimming.mask = 1; +matlabbatch{mi}.spm.tools.cat.tools.datatrimming.suffix = ''; +matlabbatch{mi}.spm.tools.cat.tools.datatrimming.intlim1 = 90; +matlabbatch{mi}.spm.tools.cat.tools.datatrimming.pth = 0.4; +matlabbatch{mi}.spm.tools.cat.tools.datatrimming.avg = 0; +matlabbatch{mi}.spm.tools.cat.tools.datatrimming.open = 2; +matlabbatch{mi}.spm.tools.cat.tools.datatrimming.addvox = 50; % default 2; 0.2 mm > 1 cm +matlabbatch{mi}.spm.tools.cat.tools.datatrimming.spm_type = 0; +matlabbatch{mi}.spm.tools.cat.tools.datatrimming.intlim = 100; +matlabbatch{mi}.spm.tools.cat.tools.datatrimming.lazy = lazy; + + + + +% (2) De-noise the image but also add some basic noise in the background +% that is important for SPM to fit Gaussian curves there. Noise is only +% added in regions without noise! +mi = mi + 1; misanlm = mi; +matlabbatch{mi}.spm.tools.cat.tools.sanlm.data(1) = cfg_dep('Image data trimming: first images of all subjects', substruct('.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','image_selector', '.','firstimages')); +matlabbatch{mi}.spm.tools.cat.tools.sanlm.spm_type = 16; +matlabbatch{mi}.spm.tools.cat.tools.sanlm.prefix = 'sanlm_'; +matlabbatch{mi}.spm.tools.cat.tools.sanlm.suffix = ''; +matlabbatch{mi}.spm.tools.cat.tools.sanlm.intlim = 100; +matlabbatch{mi}.spm.tools.cat.tools.sanlm.addnoise = 0.5; + % We have to guaranty some principle noise in noise-free regions. + % However, I am not sure if this is optimal in this special case. +matlabbatch{mi}.spm.tools.cat.tools.sanlm.rician = 0; +matlabbatch{mi}.spm.tools.cat.tools.sanlm.replaceNANandINF = 1; +matlabbatch{mi}.spm.tools.cat.tools.sanlm.nlmfilter.expert.NCstr = -Inf; +matlabbatch{mi}.spm.tools.cat.tools.sanlm.nlmfilter.expert.iter = 0; +matlabbatch{mi}.spm.tools.cat.tools.sanlm.nlmfilter.expert.iterm = 0; +matlabbatch{mi}.spm.tools.cat.tools.sanlm.nlmfilter.expert.outlier = 1; +matlabbatch{mi}.spm.tools.cat.tools.sanlm.nlmfilter.expert.relativeIntensityAdaption = 1; +matlabbatch{mi}.spm.tools.cat.tools.sanlm.nlmfilter.expert.relativeIntensityAdaptionTH = 2; +matlabbatch{mi}.spm.tools.cat.tools.sanlm.nlmfilter.expert.relativeFilterStengthLimit = 1; +matlabbatch{mi}.spm.tools.cat.tools.sanlm.nlmfilter.expert.resolutionDependency = 0; +matlabbatch{mi}.spm.tools.cat.tools.sanlm.nlmfilter.expert.resolutionDependencyRange = [1 2.5]; +matlabbatch{mi}.spm.tools.cat.tools.sanlm.nlmfilter.expert.red = 0; +matlabbatch{mi}.spm.tools.cat.tools.sanlm.nlmfilter.expert.lazy = lazy; + + + + +% (3) Create an new CSF/background class to have a suitable SPM unified +% segmentation model. We prepare a 3 class model with GM, WM, and a +% CSF/background class (1 - (GM + WM)). The result is used as 3rd +% tissue class in the unified segmentation below. +% +% 3 class model +mi = mi + 1; miBG = mi; +pp = spm_fileparts(data{1}{1}); % we write into the default output directory +if BGmodel == 2 + matlabbatch{mi}.spm.util.imcalc.input = { + [TPM ',1']; + [TPM ',2']; + }; + matlabbatch{mi}.spm.util.imcalc.output = 'TPM3of3_BG'; + matlabbatch{mi}.spm.util.imcalc.expression = '1 - (i1 + i2)'; +else + matlabbatch{mi}.spm.util.imcalc.input = { + [TPM ',1']; + [TPM ',2']; + [TPM ',3']; + }; + matlabbatch{mi}.spm.util.imcalc.output = 'TPM4of4_BG'; + matlabbatch{mi}.spm.util.imcalc.expression = '1 - (i1 + i2 + i3)'; +end +matlabbatch{mi}.spm.util.imcalc.outdir = {pp}; +matlabbatch{mi}.spm.util.imcalc.var = struct('name', {}, 'value', {}); +matlabbatch{mi}.spm.util.imcalc.options.dmtx = 0; +matlabbatch{mi}.spm.util.imcalc.options.mask = 0; +matlabbatch{mi}.spm.util.imcalc.options.interp = 1; +matlabbatch{mi}.spm.util.imcalc.options.dtype = 4; + + + + +% (4) Resize the image for (faster) tests with lower resolution. +% This is done by a special function that smooth the data to simulate +% the partial volume effect (PVE) for denoising the data. Otherwise, +% only the sample points are used and noise is preserved. +mi = mi + 1; miResize = mi; +matlabbatch{mi}.spm.tools.cat.tools.resize.data(1) = cfg_dep('Spatially adaptive non-local means (SANLM) denoising filter: SANLM Images', substruct('.','val', '{}',{misanlm}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','files')); +matlabbatch{mi}.spm.tools.cat.tools.resize.restype.res = resolution; +matlabbatch{mi}.spm.tools.cat.tools.resize.interp = -2005; +matlabbatch{mi}.spm.tools.cat.tools.resize.prefix = 'auto'; % this will create some resolution specific values +matlabbatch{mi}.spm.tools.cat.tools.resize.outdir = {''}; +% (5) Normalize and limit image intensities. +% The SPM segmentation seems to have some issues with strong outliers. +mi = mi + 1; mihlim = mi; +matlabbatch{mi}.spm.tools.cat.tools.spmtype.data(1) = cfg_dep('Resize images: Resized', substruct('.','val', '{}',{miResize}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','res', '()',{':'})); +matlabbatch{mi}.spm.tools.cat.tools.spmtype.ctype = 16; +matlabbatch{mi}.spm.tools.cat.tools.spmtype.prefix = 'hlim_'; +matlabbatch{mi}.spm.tools.cat.tools.spmtype.suffix = ''; +matlabbatch{mi}.spm.tools.cat.tools.spmtype.range = 99.9999; +matlabbatch{mi}.spm.tools.cat.tools.spmtype.intscale = 1; +matlabbatch{mi}.spm.tools.cat.tools.spmtype.lazy = 1; + + + +if BC + % ----------------------------------------------------------------------- + % only bias correction with very high sampling (<= 1 mm) that was not + % working quite well for this segmentation itself but helps to model + % the brain in the following steps. + % ----------------------------------------------------------------------- + mi = mi + 1; segment0 = mi; + matlabbatch{mi}.spm.spatial.preproc.channel.vols(1) = cfg_dep('Image data type converter: Converted Images', substruct('.','val', '{}',{mihlim}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','files', '()',{':'})); + matlabbatch{mi}.spm.spatial.preproc.channel.biasreg = 0; + matlabbatch{mi}.spm.spatial.preproc.channel.biasfwhm = 30; % default = 60 (for 1.5 Tesla and precorrected 3.0 Tesla (T1) data in humans) + matlabbatch{mi}.spm.spatial.preproc.channel.write = [0 1]; % we also write the bias corrected image + matlabbatch{mi}.spm.spatial.preproc.tissue(1).tpm = {[TPM ',1']}; + matlabbatch{mi}.spm.spatial.preproc.tissue(1).ngaus = ngaus(1); + matlabbatch{mi}.spm.spatial.preproc.tissue(1).native = [1 0]; + matlabbatch{mi}.spm.spatial.preproc.tissue(1).warped = [0 0]; + matlabbatch{mi}.spm.spatial.preproc.tissue(2).tpm = {[TPM ',2']}; + matlabbatch{mi}.spm.spatial.preproc.tissue(2).ngaus = ngaus(2); + matlabbatch{mi}.spm.spatial.preproc.tissue(2).native = [1 0]; + matlabbatch{mi}.spm.spatial.preproc.tissue(2).warped = [0 0]; + if BGmodel == 2 + matlabbatch{mi}.spm.spatial.preproc.tissue(3).tpm(1) = cfg_dep('Image Calculator: ImCalc Computed Image: TPM3of3_BG', substruct('.','val', '{}',{miBG}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','files')); + matlabbatch{mi}.spm.spatial.preproc.tissue(3).ngaus = ngaus(3); + matlabbatch{mi}.spm.spatial.preproc.tissue(3).native = [1 0]; + matlabbatch{mi}.spm.spatial.preproc.tissue(3).warped = [0 0]; + else + matlabbatch{mi}.spm.spatial.preproc.tissue(3).tpm = {[TPM ',3']}; + matlabbatch{mi}.spm.spatial.preproc.tissue(3).ngaus = ngaus(3); + matlabbatch{mi}.spm.spatial.preproc.tissue(3).native = [1 0]; + matlabbatch{mi}.spm.spatial.preproc.tissue(3).warped = [0 0]; + matlabbatch{mi}.spm.spatial.preproc.tissue(4).tpm(1) = cfg_dep('Image Calculator: ImCalc Computed Image: TPM4of4_BG', substruct('.','val', '{}',{miBG}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','files')); + matlabbatch{mi}.spm.spatial.preproc.tissue(4).ngaus = ngaus(4); + matlabbatch{mi}.spm.spatial.preproc.tissue(4).native = [0 0]; + matlabbatch{mi}.spm.spatial.preproc.tissue(4).warped = [0 0]; + end + matlabbatch{mi}.spm.spatial.preproc.warp.mrf = 0; + matlabbatch{mi}.spm.spatial.preproc.warp.cleanup = 0; + matlabbatch{mi}.spm.spatial.preproc.warp.reg = [0 0.001 0.5 0.05 0.2]; + matlabbatch{mi}.spm.spatial.preproc.warp.affreg = 'mni'; + matlabbatch{mi}.spm.spatial.preproc.warp.fwhm = 0; + matlabbatch{mi}.spm.spatial.preproc.warp.samp = 0.5; % there are problems for high-resolution combined with high sampling ... no idea why + matlabbatch{mi}.spm.spatial.preproc.warp.write = [0 0]; + matlabbatch{mi}.spm.spatial.preproc.warp.vox = nan; + matlabbatch{mi}.spm.spatial.preproc.warp.bb = [nan nan nan; nan nan nan]; + % Create a label map p0 for fast visual checks. + mi = mi + 1; + [pp,ff,ee] = spm_fileparts(data{1}{1}); % we write into the default output directory + matlabbatch{mi}.spm.util.imcalc.input(1) = cfg_dep('Segment: c1 Images', substruct('.','val', '{}',{segment0}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','tiss', '()',{1}, '.','c', '()',{':'})); + matlabbatch{mi}.spm.util.imcalc.input(2) = cfg_dep('Segment: c2 Images', substruct('.','val', '{}',{segment0}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','tiss', '()',{2}, '.','c', '()',{':'})); + matlabbatch{mi}.spm.util.imcalc.input(3) = cfg_dep('Segment: c3 Images', substruct('.','val', '{}',{segment0}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','tiss', '()',{3}, '.','c', '()',{':'})); + matlabbatch{mi}.spm.util.imcalc.output = spm_file([ff ee],'prefix',sprintf('p0masked_r%04.0f_sanlm_trimmed_',resolution*1000)); + matlabbatch{mi}.spm.util.imcalc.outdir = {pp}; + matlabbatch{mi}.spm.util.imcalc.expression = 'i1*2 + i2*3 + i3'; + matlabbatch{mi}.spm.util.imcalc.var = struct('name', {}, 'value', {}); + matlabbatch{mi}.spm.util.imcalc.options.dmtx = 0; + matlabbatch{mi}.spm.util.imcalc.options.mask = 0; + matlabbatch{mi}.spm.util.imcalc.options.interp = 1; + matlabbatch{mi}.spm.util.imcalc.options.dtype = 4; + % Intensity normalization and limitiation. + mi = mi + 1; mihlim0 = mi; + matlabbatch{mi}.spm.tools.cat.tools.spmtype.data(1) = cfg_dep('Segment: Bias Corrected (1)', substruct('.','val', '{}',{segment0}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','channel', '()',{1}, '.','biascorr', '()',{':'})); + matlabbatch{mi}.spm.tools.cat.tools.spmtype.ctype = 16; + matlabbatch{mi}.spm.tools.cat.tools.spmtype.prefix = 'hlimbc_'; + matlabbatch{mi}.spm.tools.cat.tools.spmtype.suffix = ''; + matlabbatch{mi}.spm.tools.cat.tools.spmtype.range = 99.999; + matlabbatch{mi}.spm.tools.cat.tools.spmtype.intscale = 1; + matlabbatch{mi}.spm.tools.cat.tools.spmtype.lazy = lazy; + % Delete c1-c4 that we don't need anymore (we will do another SPM segmentation) + mi = mi + 1; + matlabbatch{mi}.cfg_basicio.file_dir.file_ops.file_move.files(1) = cfg_dep('Segment: c1 Images', substruct('.','val', '{}',{segment0}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','tiss', '()',{1}, '.','c', '()',{':'})); + matlabbatch{mi}.cfg_basicio.file_dir.file_ops.file_move.files(2) = cfg_dep('Segment: c2 Images', substruct('.','val', '{}',{segment0}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','tiss', '()',{2}, '.','c', '()',{':'})); + matlabbatch{mi}.cfg_basicio.file_dir.file_ops.file_move.files(3) = cfg_dep('Segment: c3 Images', substruct('.','val', '{}',{segment0}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','tiss', '()',{3}, '.','c', '()',{':'})); + matlabbatch{mi}.cfg_basicio.file_dir.file_ops.file_move.action.delete = false; + % ----------------------------------------------------------------------- +end + + + + +% (6) Unified segmentation with 3 or 4 classes with a strong bias correction. +% First a pre-correction that helps to build a more accurate second level model. +% Check the p0 images to see the difference (especially the WM in the occipital lobe. +mi = mi + 1; segment1 = mi; +if BC + matlabbatch{mi}.spm.spatial.preproc.channel.vols(1) = cfg_dep('Image data type converter: Converted Images', substruct('.','val', '{}',{mihlim0}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','files', '()',{':'})); + else + matlabbatch{mi}.spm.spatial.preproc.channel.vols(1) = cfg_dep('Image data type converter: Converted Images', substruct('.','val', '{}',{mihlim}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','files', '()',{':'})); +end +matlabbatch{mi}.spm.spatial.preproc.channel.biasreg = 0; +matlabbatch{mi}.spm.spatial.preproc.channel.biasfwhm = 30; % default = 60 (for 1.5 Tesla and precorrected 3.0 Tesla (T1) data in humans) +matlabbatch{mi}.spm.spatial.preproc.channel.write = [0 1]; % we also write the bias corrected image +matlabbatch{mi}.spm.spatial.preproc.tissue(1).tpm = {[TPM ',1']}; +matlabbatch{mi}.spm.spatial.preproc.tissue(1).ngaus = ngaus(1); +matlabbatch{mi}.spm.spatial.preproc.tissue(1).native = [1 0]; +matlabbatch{mi}.spm.spatial.preproc.tissue(1).warped = [0 0]; +matlabbatch{mi}.spm.spatial.preproc.tissue(2).tpm = {[TPM ',2']}; +matlabbatch{mi}.spm.spatial.preproc.tissue(2).ngaus = ngaus(2); +matlabbatch{mi}.spm.spatial.preproc.tissue(2).native = [1 0]; +matlabbatch{mi}.spm.spatial.preproc.tissue(2).warped = [0 0]; +if BGmodel == 2 + matlabbatch{mi}.spm.spatial.preproc.tissue(3).tpm(1) = cfg_dep('Image Calculator: ImCalc Computed Image: TPM3of3_BG', substruct('.','val', '{}',{miBG}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','files')); + matlabbatch{mi}.spm.spatial.preproc.tissue(3).ngaus = ngaus(3); + matlabbatch{mi}.spm.spatial.preproc.tissue(3).native = [1 0]; + matlabbatch{mi}.spm.spatial.preproc.tissue(3).warped = [0 0]; +else + matlabbatch{mi}.spm.spatial.preproc.tissue(3).tpm = {[TPM ',3']}; + matlabbatch{mi}.spm.spatial.preproc.tissue(3).ngaus = ngaus(3); + matlabbatch{mi}.spm.spatial.preproc.tissue(3).native = [1 0]; + matlabbatch{mi}.spm.spatial.preproc.tissue(3).warped = [0 0]; + matlabbatch{mi}.spm.spatial.preproc.tissue(4).tpm(1) = cfg_dep('Image Calculator: ImCalc Computed Image: TPM4of4_BG', substruct('.','val', '{}',{miBG}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','files')); + matlabbatch{mi}.spm.spatial.preproc.tissue(4).ngaus = ngaus(4); + matlabbatch{mi}.spm.spatial.preproc.tissue(4).native = [1 0]; + matlabbatch{mi}.spm.spatial.preproc.tissue(4).warped = [0 0]; +end +matlabbatch{mi}.spm.spatial.preproc.warp.mrf = 1; +matlabbatch{mi}.spm.spatial.preproc.warp.cleanup = 1; +matlabbatch{mi}.spm.spatial.preproc.warp.reg = [0 0.001 0.5 0.05 0.2]; +matlabbatch{mi}.spm.spatial.preproc.warp.affreg = 'mni'; +matlabbatch{mi}.spm.spatial.preproc.warp.fwhm = 0; +matlabbatch{mi}.spm.spatial.preproc.warp.samp = samp; % there are problems for high-resolution combined with high sampling ... no idea why +matlabbatch{mi}.spm.spatial.preproc.warp.write = [0 0]; +matlabbatch{mi}.spm.spatial.preproc.warp.vox = nan; +matlabbatch{mi}.spm.spatial.preproc.warp.bb = [nan nan nan; nan nan nan]; +% (7) Create a label map p0 for fast visual checks. +mi = mi + 1; +[pp,ff,ee] = spm_fileparts(data{1}{1}); % we write into the default output directory +matlabbatch{mi}.spm.util.imcalc.input(1) = cfg_dep('Segment: c1 Images', substruct('.','val', '{}',{segment1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','tiss', '()',{1}, '.','c', '()',{':'})); +matlabbatch{mi}.spm.util.imcalc.input(2) = cfg_dep('Segment: c2 Images', substruct('.','val', '{}',{segment1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','tiss', '()',{2}, '.','c', '()',{':'})); +matlabbatch{mi}.spm.util.imcalc.input(3) = cfg_dep('Segment: c3 Images', substruct('.','val', '{}',{segment1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','tiss', '()',{3}, '.','c', '()',{':'})); +matlabbatch{mi}.spm.util.imcalc.output = spm_file([ff ee],'prefix',sprintf('p0masked_r%04.0f_sanlm_trimmed_',resolution*1000)); +matlabbatch{mi}.spm.util.imcalc.outdir = {pp}; +matlabbatch{mi}.spm.util.imcalc.expression = 'i1*2 + i2*3 + i3'; +matlabbatch{mi}.spm.util.imcalc.var = struct('name', {}, 'value', {}); +matlabbatch{mi}.spm.util.imcalc.options.dmtx = 0; +matlabbatch{mi}.spm.util.imcalc.options.mask = 0; +matlabbatch{mi}.spm.util.imcalc.options.interp = 1; +matlabbatch{mi}.spm.util.imcalc.options.dtype = 4; +% (8) Intensity normalization and limitiation. +mi = mi + 1; mihlim2 = mi; +matlabbatch{mi}.spm.tools.cat.tools.spmtype.data(1) = cfg_dep('Segment: Bias Corrected (1)', substruct('.','val', '{}',{segment1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','channel', '()',{1}, '.','biascorr', '()',{':'})); +matlabbatch{mi}.spm.tools.cat.tools.spmtype.ctype = 16; +matlabbatch{mi}.spm.tools.cat.tools.spmtype.prefix = 'hlim_'; +matlabbatch{mi}.spm.tools.cat.tools.spmtype.suffix = ''; +matlabbatch{mi}.spm.tools.cat.tools.spmtype.range = 99.9999; +matlabbatch{mi}.spm.tools.cat.tools.spmtype.intscale = 1; +matlabbatch{mi}.spm.tools.cat.tools.spmtype.lazy = lazy; +% (9) Create a brain masked image for CAT (really required) +if BGmodel == 1 + mi = mi + 1; miMSK = mi; + [pp,ff,ee] = spm_fileparts(data{1}{1}); % we write into the default output directory + matlabbatch{mi}.spm.util.imcalc.input(1) = cfg_dep('Image data type converter: Converted Images', substruct('.','val', '{}',{mihlim2}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','files', '()',{':'})); + matlabbatch{mi}.spm.util.imcalc.input(2) = cfg_dep('Segment: c4 Images', substruct('.','val', '{}',{segment1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','tiss', '()',{4}, '.','c', '()',{':'})); + matlabbatch{mi}.spm.util.imcalc.output = spm_file([ff ee],'prefix',sprintf('masked_r%04.0f_sanlm_trimmed_',resolution*1000)); + matlabbatch{mi}.spm.util.imcalc.outdir = {pp}; + matlabbatch{mi}.spm.util.imcalc.expression = 'i1 .* (i2 < 0.8)'; % X(:,:,:,1) .* smooth3(X(:,:,:,2) < 0.5)'; + matlabbatch{mi}.spm.util.imcalc.var = struct('name', {}, 'value', {}); + matlabbatch{mi}.spm.util.imcalc.options.dmtx = 0; + matlabbatch{mi}.spm.util.imcalc.options.mask = 0; + matlabbatch{mi}.spm.util.imcalc.options.interp = 1; + matlabbatch{mi}.spm.util.imcalc.options.dtype = 16; +end +% (10) Delete c1-c4 that we don't need anymore (we will do another SPM segmentation) +mi = mi + 1; +matlabbatch{mi}.cfg_basicio.file_dir.file_ops.file_move.files(1) = cfg_dep('Segment: c1 Images', substruct('.','val', '{}',{segment1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','tiss', '()',{1}, '.','c', '()',{':'})); +matlabbatch{mi}.cfg_basicio.file_dir.file_ops.file_move.files(2) = cfg_dep('Segment: c2 Images', substruct('.','val', '{}',{segment1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','tiss', '()',{2}, '.','c', '()',{':'})); +matlabbatch{mi}.cfg_basicio.file_dir.file_ops.file_move.files(3) = cfg_dep('Segment: c3 Images', substruct('.','val', '{}',{segment1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','tiss', '()',{3}, '.','c', '()',{':'})); +if BGmodel < 2 + matlabbatch{mi}.cfg_basicio.file_dir.file_ops.file_move.files(4) = cfg_dep('Segment: c4 Images', substruct('.','val', '{}',{segment1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','tiss', '()',{4}, '.','c', '()',{':'})); +end +matlabbatch{mi}.cfg_basicio.file_dir.file_ops.file_move.action.delete = false; +% ############ +% * a morph-ops batch would be helpful +% * a gradient / divergence batch maybe too +% * cleanup module +% * bias correction +% * intensity normalization with SPM mat or segments? +% ########### + + + + +% (11) Final SPM segmentation +mi = mi + 1; segmentf = mi; +if BGmodel == 1 % skull-stripped + matlabbatch{mi}.spm.spatial.preproc.channel.vols(1) = cfg_dep(sprintf('Image Calculator: ImCalc Computed Image: %s',matlabbatch{miMSK}.spm.util.imcalc.output), substruct('.','val', '{}',{miMSK}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','files')); +else + matlabbatch{mi}.spm.spatial.preproc.channel.vols(1) = cfg_dep('Image data type converter: Converted Images', substruct('.','val', '{}',{mihlim2}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','files', '()',{':'})); +end +matlabbatch{mi}.spm.spatial.preproc.channel.biasreg = 0; +matlabbatch{mi}.spm.spatial.preproc.channel.biasfwhm = 30; % default = 60 (for 1.5 Tesla and precorrected 3.0 Tesla (T1) data in humans) +matlabbatch{mi}.spm.spatial.preproc.channel.write = [0 1]; % we also write the bias corrected image +matlabbatch{mi}.spm.spatial.preproc.tissue(1).tpm = {[TPM ',1']}; +matlabbatch{mi}.spm.spatial.preproc.tissue(1).ngaus = ngaus(1); +matlabbatch{mi}.spm.spatial.preproc.tissue(1).native = [1 0]; +matlabbatch{mi}.spm.spatial.preproc.tissue(1).warped = [0 0]; +matlabbatch{mi}.spm.spatial.preproc.tissue(2).tpm = {[TPM ',2']}; +matlabbatch{mi}.spm.spatial.preproc.tissue(2).ngaus = ngaus(2); +matlabbatch{mi}.spm.spatial.preproc.tissue(2).native = [1 0]; +matlabbatch{mi}.spm.spatial.preproc.tissue(2).warped = [0 0]; +if BGmodel == 2 + matlabbatch{mi}.spm.spatial.preproc.tissue(3).tpm(1) = cfg_dep('Image Calculator: ImCalc Computed Image: TPM3of3_BG', substruct('.','val', '{}',{miBG}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','files')); + matlabbatch{mi}.spm.spatial.preproc.tissue(3).ngaus = ngaus(3); + matlabbatch{mi}.spm.spatial.preproc.tissue(3).native = [1 0]; + matlabbatch{mi}.spm.spatial.preproc.tissue(3).warped = [0 0]; +else + matlabbatch{mi}.spm.spatial.preproc.tissue(3).tpm(1) = {[TPM ',3']}; + matlabbatch{mi}.spm.spatial.preproc.tissue(3).ngaus = ngaus(3); + matlabbatch{mi}.spm.spatial.preproc.tissue(3).native = [1 0]; + matlabbatch{mi}.spm.spatial.preproc.tissue(3).warped = [0 0]; + matlabbatch{mi}.spm.spatial.preproc.tissue(4).tpm(1) = cfg_dep('Image Calculator: ImCalc Computed Image: TPM4of4_BG', substruct('.','val', '{}',{miBG}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','files')); + matlabbatch{mi}.spm.spatial.preproc.tissue(4).ngaus = ngaus(4); + matlabbatch{mi}.spm.spatial.preproc.tissue(4).native = [1 0]; + matlabbatch{mi}.spm.spatial.preproc.tissue(4).warped = [0 0]; +end +matlabbatch{mi}.spm.spatial.preproc.warp.mrf = 1; +matlabbatch{mi}.spm.spatial.preproc.warp.cleanup = 1; +matlabbatch{mi}.spm.spatial.preproc.warp.reg = [0 0.001 0.5 0.05 0.2]; +matlabbatch{mi}.spm.spatial.preproc.warp.affreg = 'mni'; +matlabbatch{mi}.spm.spatial.preproc.warp.fwhm = 0; +matlabbatch{mi}.spm.spatial.preproc.warp.samp = samp; % max(0.5,min(2,resolution * spm_res_factor * 2)); +matlabbatch{mi}.spm.spatial.preproc.warp.write = [0 0]; +matlabbatch{mi}.spm.spatial.preproc.warp.vox = nan; +matlabbatch{mi}.spm.spatial.preproc.warp.bb = [nan nan nan; nan nan nan]; +if 0 %BGmodel == 1 + % apply skull-stripping! + for ci = 1:3 + mi = mi + 1; + matlabbatch{mi}.spm.util.imcalc.input(1) = cfg_dep('Segment: c1 Images', substruct('.','val', '{}',{segmentf}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','tiss', '()',{1}, '.','c', '()',{':'})); + matlabbatch{mi}.spm.util.imcalc.input(2) = cfg_dep('Segment: c1 Images', substruct('.','val', '{}',{segmentf}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','tiss', '()',{1}, '.','c', '()',{':'})); + matlabbatch{mi}.spm.util.imcalc.output = spm_file([ff ee],'prefix',sprintf('p0mmasked_r%04.0f_sanlm_trimmed_',resolution*1000)); + matlabbatch{mi}.spm.util.imcalc.outdir = {pp}; + matlabbatch{mi}.spm.util.imcalc.expression = 'i1 .* i2'; + matlabbatch{mi}.spm.util.imcalc.var = struct('name', {}, 'value', {}); + matlabbatch{mi}.spm.util.imcalc.options.dmtx = 0; + matlabbatch{mi}.spm.util.imcalc.options.mask = 0; + matlabbatch{mi}.spm.util.imcalc.options.interp = 1; + matlabbatch{mi}.spm.util.imcalc.options.dtype = 4; + end +end + +% (12) Create a label map p0* for visual checks. +mi = mi + 1; +matlabbatch{mi}.spm.util.imcalc.input(1) = cfg_dep('Segment: c1 Images', substruct('.','val', '{}',{segmentf}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','tiss', '()',{1}, '.','c', '()',{':'})); +matlabbatch{mi}.spm.util.imcalc.input(2) = cfg_dep('Segment: c2 Images', substruct('.','val', '{}',{segmentf}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','tiss', '()',{2}, '.','c', '()',{':'})); +matlabbatch{mi}.spm.util.imcalc.input(3) = cfg_dep('Segment: c3 Images', substruct('.','val', '{}',{segmentf}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','tiss', '()',{3}, '.','c', '()',{':'})); +matlabbatch{mi}.spm.util.imcalc.output = spm_file([ff ee],'prefix',sprintf('p0mmasked_r%04.0f_sanlm_trimmed_',resolution*1000)); +matlabbatch{mi}.spm.util.imcalc.outdir = {pp}; +matlabbatch{mi}.spm.util.imcalc.expression = 'i1*2 + i2*3 + i3'; +matlabbatch{mi}.spm.util.imcalc.var = struct('name', {}, 'value', {}); +matlabbatch{mi}.spm.util.imcalc.options.dmtx = 0; +matlabbatch{mi}.spm.util.imcalc.options.mask = 0; +matlabbatch{mi}.spm.util.imcalc.options.interp = 1; +matlabbatch{mi}.spm.util.imcalc.options.dtype = 4; +% normalize intensities +mi = mi + 1; mihlim3 = mi; +matlabbatch{mi}.spm.tools.cat.tools.spmtype.data(1) = cfg_dep('Segment: Bias Corrected (1)', substruct('.','val', '{}',{segmentf}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','channel', '()',{1}, '.','biascorr', '()',{':'}));; +matlabbatch{mi}.spm.tools.cat.tools.spmtype.ctype = 16; +matlabbatch{mi}.spm.tools.cat.tools.spmtype.prefix = 'hlim_'; +matlabbatch{mi}.spm.tools.cat.tools.spmtype.suffix = ''; +matlabbatch{mi}.spm.tools.cat.tools.spmtype.range = 99.9; +matlabbatch{mi}.spm.tools.cat.tools.spmtype.intscale = 1; +matlabbatch{mi}.spm.tools.cat.tools.spmtype.lazy = lazy; + + + +% (6) CAT12 preprocessing with given SPM segmentation without CAT voxel- +% based preprocessing (especially the AMAP segmentation) to be more +% flexible with different image modalities (CAT prefers T1). +mi = mi + 1; +matlabbatch{mi}.spm.tools.cat.estwrite_spm.data(1) = cfg_dep('Segment: c1 Images', substruct('.','val', '{}',{segmentf}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','tiss', '()',{1}, '.','c', '()',{':'})); +matlabbatch{mi}.spm.tools.cat.estwrite_spm.nproc = nproc; +matlabbatch{mi}.spm.tools.cat.estwrite_spm.extopts.registration.T1 = {fullfile(template_dir,'Template_T1.nii')}; +matlabbatch{mi}.spm.tools.cat.estwrite_spm.extopts.registration.brainmask = {fullfile(template_dir,'brainmask.nii')}; +matlabbatch{mi}.spm.tools.cat.estwrite_spm.extopts.registration.cat12atlas = {fullfile(template_dir,'cat.nii')}; +matlabbatch{mi}.spm.tools.cat.estwrite_spm.extopts.registration.darteltpm = {fullfile(template_dir,'Template_1.nii')}; +matlabbatch{mi}.spm.tools.cat.estwrite_spm.extopts.registration.shootingtpm = {fullfile(template_dir,'Template_0_GS.nii')}; +matlabbatch{mi}.spm.tools.cat.estwrite_spm.extopts.registration.regstr = 0.5; +matlabbatch{mi}.spm.tools.cat.estwrite_spm.extopts.registration.bb = 12; +matlabbatch{mi}.spm.tools.cat.estwrite_spm.extopts.registration.vox = 15; %0.5; +matlabbatch{mi}.spm.tools.cat.estwrite_spm.extopts.vox = 0.5; +matlabbatch{mi}.spm.tools.cat.estwrite_spm.extopts.bb = 12; +matlabbatch{mi}.spm.tools.cat.estwrite_spm.extopts.surface.pbtres = 0.8; %min(0.5,max(0.3,resolution)); +matlabbatch{mi}.spm.tools.cat.estwrite_spm.extopts.surface.pbtmethod = 'pbt2x'; +matlabbatch{mi}.spm.tools.cat.estwrite_spm.extopts.surface.SRP = 22; +matlabbatch{mi}.spm.tools.cat.estwrite_spm.extopts.surface.reduce_mesh = reduce_mesh; +matlabbatch{mi}.spm.tools.cat.estwrite_spm.extopts.surface.vdist = 2; +matlabbatch{mi}.spm.tools.cat.estwrite_spm.extopts.surface.scale_cortex = 0.7; +matlabbatch{mi}.spm.tools.cat.estwrite_spm.extopts.surface.add_parahipp = 0.1; +matlabbatch{mi}.spm.tools.cat.estwrite_spm.extopts.surface.close_parahipp = 1; +matlabbatch{mi}.spm.tools.cat.estwrite_spm.extopts.admin.experimental = 0; +matlabbatch{mi}.spm.tools.cat.estwrite_spm.extopts.admin.new_release = 0; +matlabbatch{mi}.spm.tools.cat.estwrite_spm.extopts.admin.lazy = lazy; +matlabbatch{mi}.spm.tools.cat.estwrite_spm.extopts.admin.ignoreErrors = 1; +matlabbatch{mi}.spm.tools.cat.estwrite_spm.extopts.admin.verb = 2; +matlabbatch{mi}.spm.tools.cat.estwrite_spm.extopts.admin.print = 2; +% ############ Use this part to define the output of both CAT preprocessings ############## +matlabbatch{mi}.spm.tools.cat.estwrite_spm.output.BIDS.BIDSno = 1; +matlabbatch{mi}.spm.tools.cat.estwrite_spm.output.surface = surfaces; +matlabbatch{mi}.spm.tools.cat.estwrite_spm.output.ROImenu.atlases.neuromorphometrics = 1; +matlabbatch{mi}.spm.tools.cat.estwrite_spm.output.ROImenu.atlases.lpba40 = 0; +matlabbatch{mi}.spm.tools.cat.estwrite_spm.output.ROImenu.atlases.cobra = 1; +matlabbatch{mi}.spm.tools.cat.estwrite_spm.output.ROImenu.atlases.hammers = 0; +matlabbatch{mi}.spm.tools.cat.estwrite_spm.output.ROImenu.atlases.thalamus = 0; +matlabbatch{mi}.spm.tools.cat.estwrite_spm.output.ROImenu.atlases.ibsr = 0; +matlabbatch{mi}.spm.tools.cat.estwrite_spm.output.ROImenu.atlases.aal3 = 0; +matlabbatch{mi}.spm.tools.cat.estwrite_spm.output.ROImenu.atlases.mori = 0; +matlabbatch{mi}.spm.tools.cat.estwrite_spm.output.ROImenu.atlases.anatomy3 = 0; +matlabbatch{mi}.spm.tools.cat.estwrite_spm.output.ROImenu.atlases.julichbrain3 = 0; +matlabbatch{mi}.spm.tools.cat.estwrite_spm.output.ROImenu.atlases.Schaefer2018_100Parcels_17Networks_order = 0; +matlabbatch{mi}.spm.tools.cat.estwrite_spm.output.ROImenu.atlases.Schaefer2018_200Parcels_17Networks_order = 0; +matlabbatch{mi}.spm.tools.cat.estwrite_spm.output.ROImenu.atlases.Schaefer2018_400Parcels_17Networks_order = 0; +matlabbatch{mi}.spm.tools.cat.estwrite_spm.output.ROImenu.atlases.Schaefer2018_600Parcels_17Networks_order = 0; +matlabbatch{mi}.spm.tools.cat.estwrite_spm.output.ROImenu.atlases.ownatlas = {''}; +matlabbatch{mi}.spm.tools.cat.estwrite_spm.output.GM.warped = 0; +matlabbatch{mi}.spm.tools.cat.estwrite_spm.output.GM.mod = 1; +matlabbatch{mi}.spm.tools.cat.estwrite_spm.output.GM.dartel = 0; +matlabbatch{mi}.spm.tools.cat.estwrite_spm.output.WM.warped = 0; +matlabbatch{mi}.spm.tools.cat.estwrite_spm.output.WM.mod = 1; +matlabbatch{mi}.spm.tools.cat.estwrite_spm.output.WM.dartel = 0; +matlabbatch{mi}.spm.tools.cat.estwrite_spm.output.CSF.warped = 0; +matlabbatch{mi}.spm.tools.cat.estwrite_spm.output.CSF.mod = 0; +matlabbatch{mi}.spm.tools.cat.estwrite_spm.output.CSF.dartel = 0; +matlabbatch{mi}.spm.tools.cat.estwrite_spm.output.label.native = 1; +matlabbatch{mi}.spm.tools.cat.estwrite_spm.output.label.warped = 0; +matlabbatch{mi}.spm.tools.cat.estwrite_spm.output.label.dartel = 0; +matlabbatch{mi}.spm.tools.cat.estwrite_spm.output.labelnative = 1; +matlabbatch{mi}.spm.tools.cat.estwrite_spm.output.jacobianwarped = 0; +matlabbatch{mi}.spm.tools.cat.estwrite_spm.output.warps = [1 0]; + + + + +% (7) Full CAT preprocessing with AMAP segmentation. +% However, I am not really satisfied with the results and the GM seems +% to be underestimated. +%%{ +mi = mi + 1; +matlabbatch{mi}.spm.tools.cat.estwrite.data(1) = cfg_dep('Image data type converter: Converted Images', substruct('.','val', '{}',{mihlim3}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','files', '()',{':'})); +matlabbatch{mi}.spm.tools.cat.estwrite.data_wmh = {''}; +matlabbatch{mi}.spm.tools.cat.estwrite.nproc = nproc; +matlabbatch{mi}.spm.tools.cat.estwrite.useprior = ''; +matlabbatch{mi}.spm.tools.cat.estwrite.opts.tpm = {TPM}; +matlabbatch{mi}.spm.tools.cat.estwrite.opts.affreg = 'none'; +matlabbatch{mi}.spm.tools.cat.estwrite.opts.ngaus = [ngaus 4 4]; % default parameters are ok here +matlabbatch{mi}.spm.tools.cat.estwrite.opts.warpreg = [0 0.001 0.5 0.05 0.2]; +matlabbatch{mi}.spm.tools.cat.estwrite.opts.bias.spm.biasfwhm = 30; % strong bias correction +matlabbatch{mi}.spm.tools.cat.estwrite.opts.bias.spm.biasreg = 0.00001; % strong bias correction +matlabbatch{mi}.spm.tools.cat.estwrite.opts.acc.spm.samp = samp; %max(0.3,min(1.5,resolution * spm_res_factor)); % higher resolution for SPM preprocessing +matlabbatch{mi}.spm.tools.cat.estwrite.opts.acc.spm.tol = tol; % higher accuracy for SPM preprocessing +matlabbatch{mi}.spm.tools.cat.estwrite.opts.redspmres = 0; +matlabbatch{mi}.spm.tools.cat.estwrite.extopts.segmentation.restypes.best = [0.5 0.3]; +matlabbatch{mi}.spm.tools.cat.estwrite.extopts.segmentation.setCOM = 1; +matlabbatch{mi}.spm.tools.cat.estwrite.extopts.segmentation.APP = 1070; +matlabbatch{mi}.spm.tools.cat.estwrite.extopts.segmentation.affmod = 0; +matlabbatch{mi}.spm.tools.cat.estwrite.extopts.segmentation.NCstr = -Inf; +matlabbatch{mi}.spm.tools.cat.estwrite.extopts.segmentation.LASstr = 0.5; +matlabbatch{mi}.spm.tools.cat.estwrite.extopts.segmentation.LASmyostr = 0; % not working in PD ? +matlabbatch{mi}.spm.tools.cat.estwrite.extopts.segmentation.gcutstr = -2; % post-mortem skull-stripping model +matlabbatch{mi}.spm.tools.cat.estwrite.extopts.segmentation.cleanupstr = 1.0; % strong cleanup (default = 0.5) +matlabbatch{mi}.spm.tools.cat.estwrite.extopts.segmentation.BVCstr = 1.0; % strong correction +matlabbatch{mi}.spm.tools.cat.estwrite.extopts.segmentation.WMHC = 0; +matlabbatch{mi}.spm.tools.cat.estwrite.extopts.segmentation.SLC = 0; +matlabbatch{mi}.spm.tools.cat.estwrite.extopts.segmentation.mrf = 1; +matlabbatch{mi}.spm.tools.cat.estwrite.extopts.registration = matlabbatch{mi-1}.spm.tools.cat.estwrite_spm.extopts.registration; +matlabbatch{mi}.spm.tools.cat.estwrite.extopts.surface = matlabbatch{mi-1}.spm.tools.cat.estwrite_spm.extopts.surface; +matlabbatch{mi}.spm.tools.cat.estwrite.extopts.admin = matlabbatch{mi-1}.spm.tools.cat.estwrite_spm.extopts.admin; +matlabbatch{mi}.spm.tools.cat.estwrite.output = matlabbatch{mi-1}.spm.tools.cat.estwrite_spm.output; + +%}","MATLAB" +"Neurology","ChristianGaser/cat12","batches/cat12_batch_prepana_smoothandmore.m",".m","19878","416","%batch_prepara_smoothandmore. Create a matlabbatch for add. smoohted values +% Smoothing of volumes (smoothing) and surfaces (ssmoothing) for a subset +% of image types (vdata) and surface types (sdata) found in a set of given +% directories (pdirs). It processing (zipped) files and write zgipped ouput. +% +% * This batch can be loaded as SPM matlabbatch but come become quite long +% in case of many filtersizes. +% * Input has to be available and if the file selector is not able to find +% something the pipeline will crash. +% +% Variables: +% pdirs .. search directories +% smoothing .. isotropic filter size for volumes in mm (default = [4 8]) +% ssmoothing .. filter size for surfaces in mm (default = [12 24]) +% vdata .. search prefix for nifti data (default = +% {'mwp1','mwp2','mwp3','mwp7','mwmwp1','mwmwp2', ... +% 'mwmwp3','mwmwp7','rp1','rp2','rp3','rp7','mw'} ) +% sdata .. structure to setup (additional) surface parameter +% (default = struct('thickness',1, 'gyrification',1, ... +% 'sulcaldepth', 1, 'fractaldimension', 1, 'toroGI20mm', 1) ) +% gzipped .. use gzip in-/output (default = 1) +% gzipo .. gzip output (default = 1) +% cleanup .. remove gunzipped files after processing (default = 1) +% +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + +% input data = all normalized CAT tissue maps +catdir = fileparts(which('spm_cat12')); +if ~exist('pdirs','var') % projectdir + pdirs = { + pwd; + }; +end +if ~exist('smoothing','var'), smoothing = [4 8]; end % isotropic Gaussian filter size for input +if ~exist('ssmoothing','var'), ssmoothing = [12 24]; end % surface Gaussian filter size for input +if ~exist('resolution','var'), resolution = [4 8]; end % isotropic reduced image resolution +if ~exist('vdata','var'), vdata = {'mwp1','mwp2','mwp3','mwp7','mwmwp1','mwmwp2','mwmwp3','mwmwp7','rp1','rp2','rp3','rp7','mw'}; end +if ~exist('sdata','var'), sdata = struct('thickness',1, 'gyrification',1, 'sulcaldepth', 1, 'fractaldimension', 0, 'toroGI20mm', 1, 'area', 1, 'gmv', 1); end +if ~exist('gzipped','var'), gzipped = 1; end % used gzipped input +if ~exist('cleanup','var'), cleanup = 1; end % remove unzipped files after processing +if ~exist('gzipo','var'), gzipo = 1; end % save time or space? +if ~exist('verb','var'), verb = 1; end + +if verb + pdirsstr = ''; for pi = 1:numel(pdirs), pdirsstr = sprintf('%s %s\n',pdirsstr,pdirs{pi}); end + FN = fieldnames(sdata); + vdatastr = ''; for vi = 1:numel(vdata), vdatastr = sprintf('%s%s ',vdatastr,vdata{vi}); end + sdatastr = ''; for fni = 1:numel(FN), if sdata.(FN{fni}), sdatastr = sprintf('%s%s ',sdatastr,FN{fni}); end; end + fprintf(['\nRun ""%s"": \n', ... + ' pdirs (that will need extra SPM file selector batches): \n%s', ... + ' volume smoohting: %s\n', ... + ' surface smoothing: %s\n', ... + ' vdata: %s\n', ... + ' sdata: %s\n', ... + ' gzipped: %d\n', ... + ' gzip output: %d\n', ... + ' cleanup: %d\n\n', ... + ],mfilename,pdirsstr,sprintf('%0.0f ',smoothing),sprintf('%0.0f ',ssmoothing), ... + sprintf('%s ',vdatastr), sprintf('%s ',sdatastr),... + gzipped,gzipo,cleanup); +end + +if ischar(pdirs) + pdirs = cellstr(pdirs); +end + +mi = 0; matlabbatch = cell(0); +clear mID; + +if any( smoothing ~= round(smoothing) ) || any( ssmoothing ~= round(ssmoothing) ) || any( resolution ~= round(resolution) ) + error('Smoothing and resolution values has to be integers for simple filenames otherwise modify the script.') +end + + + +% === extraction of inforamtion from the CSV/TSV === +% no glue if this is useful here - no its not and this comment is to remember this + + + +% === VOLUME-based === +% if a list of files is given then process it +if exist(vdata{1},'file') + vdata = {['files_' name]'}; +end +if gzipped, gzstr = '.gz'; else, gzstr = ''; end %#ok + +if ~isempty(vdata) + % prepare selection string + vdatasstr = sprintf('(%s',vdata{1}); + for vi = 2:numel(vdata), vdatasstr = sprintf('%s|%s',vdatasstr,vdata{vi}); end + vdatasstr = sprintf('%s)',vdatasstr); + + % == selection == + for pi = 1:numel(pdirs) + mi = mi + 1; mID.fileselgz(pi) = mi; mID.filesel(pi) = mi; + matlabbatch{mi}.cfg_basicio.file_dir.file_ops.file_fplist.filter = sprintf('^%s.*\\.nii%s$',vdatasstr,gzstr); + matlabbatch{mi}.cfg_basicio.file_dir.file_ops.file_fplist.dir = pdirs(pi); + matlabbatch{mi}.cfg_basicio.file_dir.file_ops.file_fplist.rec = 'FPListRec'; + end + + % == gunzip == + if gzipped + mi = mi + 1; mID.filesel = mi; + for pi = 1:numel(pdirs) + matlabbatch{mi}.cfg_basicio.file_dir.file_ops.cfg_gunzip_files.files(pi) = ... + cfg_dep('File Selector (Batch Mode): Selected Volumes', ... + substruct('.','val', '{}',{mID.fileselgz(pi)}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), ... + substruct('.','files')); + end + matlabbatch{mi}.cfg_basicio.file_dir.file_ops.cfg_gunzip_files.outdir = {''}; + matlabbatch{mi}.cfg_basicio.file_dir.file_ops.cfg_gunzip_files.keep = true; + end + + % == smoothing == + for si = 1:numel(smoothing) + mi = mi + 1; mID.smoothing(si) = mi; + if gzipped + matlabbatch{mi}.spm.spatial.smooth.data(1) = ... + cfg_dep('Gunzip Files: Gunzipped Files', ... + substruct('.','val', '{}',{mID.filesel}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), ... + substruct('()',{':'})); + else + for pi = 1:numel(pdirs) + matlabbatch{mi}.spm.spatial.smooth.data(vi) = ... + cfg_dep('File Selector (Batch Mode): Selected Volumes', ... + substruct('.','val', '{}',{mID.fileselgz(pi)}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), ... + substruct('.','files')); + end + end + matlabbatch{mi}.spm.spatial.smooth.fwhm = repmat(smoothing(si),1,3); + matlabbatch{mi}.spm.spatial.smooth.dtype = 0; + matlabbatch{mi}.spm.spatial.smooth.im = 0; + matlabbatch{mi}.spm.spatial.smooth.prefix = sprintf('s%0.0f',smoothing(si)); + end + + % == resolution == + for ri = 1:numel(resolution) + mi = mi + 1; mID.resolution(ri) = mi; + for si = 1:numel(mID.smoothing) + matlabbatch{mi}.spm.tools.cat.tools.resize.data(si) = ... + cfg_dep('Smooth: Smoothed Images', ... + substruct('.','val', '{}',{mID.smoothing(si)}, '.','val', '{}',{1}, '.','val', '{}',{1}), ... + substruct('.','files')); + end + matlabbatch{mi}.spm.tools.cat.tools.resize.restype.res = resolution(ri); + matlabbatch{mi}.spm.tools.cat.tools.resize.interp = -5; + matlabbatch{mi}.spm.tools.cat.tools.resize.prefix = sprintf('r%0.0f',resolution(ri)); + matlabbatch{mi}.spm.tools.cat.tools.resize.outdir = {''}; + end + + % == zip smoothed output == + if gzipo + mi = mi + 1; + for si = 1:numel(mID.smoothing) + matlabbatch{mi}.cfg_basicio.file_dir.file_ops.cfg_gzip_files.files(si) = ... + cfg_dep('Smooth: Smoothed Images', ... + substruct('.','val', '{}',{mID.smoothing(si)}, '.','val', '{}',{1}, '.','val', '{}',{1}), ... + substruct('.','files')); + end + if ~isempty(resolution) + for ri = 1:numel(mID.resolution) + matlabbatch{mi}.cfg_basicio.file_dir.file_ops.cfg_gzip_files.files(end+1) = ... + cfg_dep('Resize images: Resized', ... + substruct('.','val', '{}',{mID.resolution(ri) }, '.','val', '{}',{1}, ... + '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), ... + substruct('.','res', '()',{':'})); + end + end + matlabbatch{mi}.cfg_basicio.file_dir.file_ops.cfg_gzip_files.outdir = {''}; + matlabbatch{mi}.cfg_basicio.file_dir.file_ops.cfg_gzip_files.keep = false; + end + + % remove unzipped volumes + if gzipped && cleanup + mi = mi + 1; + for vi = 1:numel(mID.filesel) + matlabbatch{mi}.cfg_basicio.file_dir.file_ops.file_move.files(vi) = ... + cfg_dep('Gunzip Files: Gunzipped Files', ... + substruct('.','val', '{}',{mID.filesel(vi)}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), ... + substruct('()',{':'})); + end + matlabbatch{mi}.cfg_basicio.file_dir.file_ops.file_move.action.delete = false; + end + +end + + + + +% === SURFACE-based === +%if iscell(sdata) && exist(sdata{1},'file') +% sdata = {['files_' name]}; +%end +side = {'lh','rh'}; +giitype = {'central','sphere'}; +if ~isempty(sdata) + % == select input == + % surfaces + if gzipped + for pi = 1:numel(pdirs) + mi = mi + 1; mID.sfileselgz(pi) = mi; + matlabbatch{mi}.cfg_basicio.file_dir.file_ops.file_fplist.dir = pdirs(pi); + matlabbatch{mi}.cfg_basicio.file_dir.file_ops.file_fplist.filter = sprintf('^(lh|rh).(central|sphere).*\\.gii%s$',gzstr); + matlabbatch{mi}.cfg_basicio.file_dir.file_ops.file_fplist.rec = 'FPListRec'; + end + + % == gunzip == + mi = mi + 1; mID.fileselunzipped = mi; + for pi = 1:numel(pdirs) + matlabbatch{mi}.cfg_basicio.file_dir.file_ops.cfg_gunzip_files.files(pi) = ... + cfg_dep('File Selector (Batch Mode): Selected Surface Files', ... + substruct('.','val', '{}',{mID.sfileselgz(pi)}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), ... + substruct('.','files')); + end + matlabbatch{mi}.cfg_basicio.file_dir.file_ops.cfg_gunzip_files.outdir = {''}; + matlabbatch{mi}.cfg_basicio.file_dir.file_ops.cfg_gunzip_files.keep = true; + end + + % == get central == + for pi = 1:numel(pdirs) + mi = mi + 1; mID.sfileselcentral(pi) = mi; + matlabbatch{mi}.cfg_basicio.file_dir.file_ops.file_fplist.dir = pdirs(pi); + matlabbatch{mi}.cfg_basicio.file_dir.file_ops.file_fplist.filter = sprintf('^lh.central.*.gii$'); + matlabbatch{mi}.cfg_basicio.file_dir.file_ops.file_fplist.rec = 'FPListRec'; + end + + % == get thickness == + for pi = 1:numel(pdirs) + mi = mi + 1; mID.sfileselth(pi) = mi; + matlabbatch{mi}.cfg_basicio.file_dir.file_ops.file_fplist.dir = pdirs(pi); + matlabbatch{mi}.cfg_basicio.file_dir.file_ops.file_fplist.filter = sprintf('^lh.thickness.*'); + matlabbatch{mi}.cfg_basicio.file_dir.file_ops.file_fplist.rec = 'FPListRec'; + end + + % == extract parameters == + surfdata = { + 'Extract additional surface parameters: Left MNI gyrification' 'lPGI' sdata.gyrification; + 'Extract additional surface parameters: Left fractal dimension' 'lPFD' sdata.fractaldimension; + 'Extract additional surface parameters: Left sulcal depth' 'lPSD' sdata.sulcaldepth; + 'Extract additional surface parameters: Left Toro GI 20 mm' 'lPtGI20mm' sdata.toroGI20mm; + 'Extract additional surface parameters: Left area' 'lParea' sdata.area; + 'Extract additional surface parameters: Left GM volume' 'lPgmv' sdata.area; + }; + mi = mi + 1; mID.fileselsdata = mi; + for pi = 1:numel(pdirs) + matlabbatch{mi}.spm.tools.cat.stools.surfextract.data_surf(pi) = ... + cfg_dep('File Selector (Batch Mode): Selected Surface Files', ... + substruct('.','val', '{}',{ mID.sfileselcentral(pi) }, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), ... + substruct('.','files')); + end + matlabbatch{mi}.spm.tools.cat.stools.surfextract.area = surfdata{5,3}; % not validated yet + matlabbatch{mi}.spm.tools.cat.stools.surfextract.gmv = surfdata{6,3}; % not validated yet + matlabbatch{mi}.spm.tools.cat.stools.surfextract.GI = surfdata{1,3}; + matlabbatch{mi}.spm.tools.cat.stools.surfextract.FD = surfdata{2,3}; + matlabbatch{mi}.spm.tools.cat.stools.surfextract.SD = surfdata{3,3}; + matlabbatch{mi}.spm.tools.cat.stools.surfextract.tGI = surfdata{4,3}; + matlabbatch{mi}.spm.tools.cat.stools.surfextract.lGI = 0; % Schaer's local GI that need freesurfer installation and was tested only roughly + matlabbatch{mi}.spm.tools.cat.stools.surfextract.GIL = 0; % different GI's that are not evaluated and not useful yet + matlabbatch{mi}.spm.tools.cat.stools.surfextract.surfaces.IS = 0; + matlabbatch{mi}.spm.tools.cat.stools.surfextract.surfaces.OS = 0; + matlabbatch{mi}.spm.tools.cat.stools.surfextract.norm = 0; + matlabbatch{mi}.spm.tools.cat.stools.surfextract.FS_HOME = ''; + matlabbatch{mi}.spm.tools.cat.stools.surfextract.nproc = 0; + matlabbatch{mi}.spm.tools.cat.stools.surfextract.lazy = 0; + + % == extraction of other intensity measures == + % This can be also done later as far as it is not so slow. + % (1) in native space we can do this only for the original (maybe biased) + % and intensity-specific T1 (where we could use cat*XML information) + % as far as we have not writen the bias corrected intensity normalized + % T1 m*.nii + % (2) we could also use the template surface and the normalized wm*.nii + % but this would be less accurate + % (3) we could extract information from other modalities T2/PD/Flair but + % this is depend on the availability and would need some alignment + % between the T1 data and other files ... so probably not so easy + + % == resample & smoothing == + expert = cat_get_defaults('extopts.expertgui'); + mID.ssmoothing = []; + for si = 1:numel(ssmoothing) + if expert + % expert matlabbatch structure + + % folding files + mi = mi + 1; mID.ssmoothing(end+1) = mi; + vi = 0; + if sdata.thickness + % add thickness file + vi = vi + 1; + matlabbatch{mi}.spm.tools.cat.stools.surfresamp.sample{1}.data_surf_mixed(vi) = ... + cfg_dep('File Selector (Batch Mode): Selected Files (^lh.thickness.*)', ... + substruct('.','val', '{}',{mID.sfileselth}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), ... + substruct('.','files')); + end + for vii = 1:size(surfdata,1) + if surfdata{vii,3} + % add folding files + vi = vi + 1; + matlabbatch{mi}.spm.tools.cat.stools.surfresamp.sample{1}.data_surf_mixed(vi) = ... + cfg_dep(surfdata{vii,1}, ... + substruct('.','val', '{}',{mID.fileselsdata}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), ... + substruct('()',{1}, '.',surfdata{vii,2}, '()',{':'})); + end + end + matlabbatch{mi}.spm.tools.cat.stools.surfresamp.mesh32k = 1; + matlabbatch{mi}.spm.tools.cat.stools.surfresamp.fwhm_surf = ssmoothing(si); + matlabbatch{mi}.spm.tools.cat.stools.surfresamp.lazy = 0; + matlabbatch{mi}.spm.tools.cat.stools.surfresamp.nproc = 0; + + else + % default matlabbatch structure + + % folding files + if sdata.thickness + % add thickness file + mi = mi + 1; mID.ssmoothing(end+1) = mi; + for pi = 1:numel(pdirs) + matlabbatch{mi}.spm.tools.cat.stools.surfresamp.data_surf(pi) = ... + cfg_dep('File Selector (Batch Mode): Selected Files (^lh.thickness.*)', ... + substruct('.','val', '{}',{mID.sfileselth(pi)}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), ... + substruct('.','files')); + end + matlabbatch{mi}.spm.tools.cat.stools.surfresamp.mesh32k = 1; + matlabbatch{mi}.spm.tools.cat.stools.surfresamp.fwhm_surf = ssmoothing(si); + matlabbatch{mi}.spm.tools.cat.stools.surfresamp.lazy = 0; + matlabbatch{mi}.spm.tools.cat.stools.surfresamp.nproc = 0; + end + % add folding files + for vii = 1:size(surfdata,1) + if surfdata{vii,3} + if ~isempty(mID.ssmoothing) + matlabbatch{mi}.spm.tools.cat.stools.surfresamp.data_surf(end+1) = cfg_dep(surfdata{vii,1}, ... + substruct('.','val', '{}',{mID.fileselsdata}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), ... + substruct('()',{1}, '.',surfdata{vii,2}, '()',{':'})); + else + mi = mi + 1; mID.ssmoothing(end+1) = mi; + matlabbatch{mi}.spm.tools.cat.stools.surfresamp.data_surf(1) = cfg_dep(surfdata{vii,1}, ... + substruct('.','val', '{}',{mID.fileselsdata}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), ... + substruct('()',{1}, '.',surfdata{vii,2}, '()',{':'})); + matlabbatch{mi}.spm.tools.cat.stools.surfresamp.mesh32k = 1; + matlabbatch{mi}.spm.tools.cat.stools.surfresamp.fwhm_surf = ssmoothing(si); + matlabbatch{mi}.spm.tools.cat.stools.surfresamp.lazy = 0; + matlabbatch{mi}.spm.tools.cat.stools.surfresamp.nproc = 0; + end + end + end + end + end + + % == extract regional values == + mi = mi + 1; + for vii = 1:size(surfdata,1) + matlabbatch{mi}.spm.tools.cat.stools.surf2roi.cdata{1}(vi) = cfg_dep(surfdata{vii,1}, ... + substruct('.','val', '{}',{mID.fileselsdata}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), ... + substruct('()',{1}, '.',surfdata{vii,2}, '()',{':'})); + end + matlabbatch{mi}.spm.tools.cat.stools.surf2roi.rdata = { + '/Users/rdahnke/Documents/MATLAB/spm12g/toolbox/cat12/atlases_surfaces/lh.aparc_HCP_MMP1.freesurfer.annot' + '/Users/rdahnke/Documents/MATLAB/spm12g/toolbox/cat12/atlases_surfaces/lh.aparc_DK40.freesurfer.annot' + }; + + % == zip smoothed mesh output == + % or more precise we have to gzip the data files that store the data and not the nifti header) + if gzipo + mi = mi + 1; mID.sfileseldat(pi) = mi; + matlabbatch{mi}.cfg_basicio.file_dir.file_ops.file_fplist.dir = pdirs(pi); + matlabbatch{mi}.cfg_basicio.file_dir.file_ops.file_fplist.filter = sprintf('^s.*\\.dat$'); + matlabbatch{mi}.cfg_basicio.file_dir.file_ops.file_fplist.rec = 'FPListRec'; + + mi = mi + 1; + matlabbatch{mi}.cfg_basicio.file_dir.file_ops.cfg_gzip_files.files(1) = ... + cfg_dep('File Selector (Batch Mode): Selected Files (s*dat)', ... + substruct('.','val', '{}',{mID.sfileseldat(pi)}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), ... + substruct('.','files')); + matlabbatch{mi}.cfg_basicio.file_dir.file_ops.cfg_gzip_files.outdir = {''}; + matlabbatch{mi}.cfg_basicio.file_dir.file_ops.cfg_gzip_files.keep = false; + + % old dependency base solution + %{ + for si = 1:numel(mID.ssmoothing) + matlabbatch{mi}.cfg_basicio.file_dir.file_ops.cfg_gzip_files.files(si) = ... + cfg_dep('Resample and Smooth Surface Data', ... + substruct('.','val', '{}',{ mID.ssmoothing(si) }, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), ... + substruct('.','sample', '()',{1}, '.','Psdata')); + end + matlabbatch{mi}.cfg_basicio.file_dir.file_ops.cfg_gzip_files.outdir = {''}; + matlabbatch{mi}.cfg_basicio.file_dir.file_ops.cfg_gzip_files.keep = false; + %} + end + + % == remove unzipped surface files == + if gzipped && cleanup + mi = mi + 1; + matlabbatch{mi}.cfg_basicio.file_dir.file_ops.file_move.files(1) = ... + cfg_dep('Gunzip Files: Gunzipped Files', ... + substruct('.','val', '{}',{mID.fileselunzipped}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), ... + substruct('()',{':'})); + matlabbatch{mi}.cfg_basicio.file_dir.file_ops.file_move.action.delete = false; + end + + +end + + + +","MATLAB" +"Neurology","ChristianGaser/cat12","batches/cat12batch_RBM_and_SBM_for_SPM.m",".m","5217","66","%----------------------------------------------------------------------- +% Job saved on 26-Oct-2016 14:08:52 by cfg_util (rev $Rev$) +% spm SPM - SPM12 (6685) +% cfg_basicio BasicIO - Unknown +%----------------------------------------------------------------------- +% sanlm denoising +matlabbatch{1}.spm.tools.cat.tools.sanlm.data = ''; +matlabbatch{1}.spm.tools.cat.tools.sanlm.prefix = 'sanlm_'; +matlabbatch{1}.spm.tools.cat.tools.sanlm.NCstr = Inf; +matlabbatch{1}.spm.tools.cat.tools.sanlm.rician = 0; +% SPM segment +matlabbatch{2}.spm.spatial.preproc.channel.vols(1) = cfg_dep('Spatially adaptive non-local means denoising filter: All Output Files', substruct('.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','vfiles')); +matlabbatch{2}.spm.spatial.preproc.channel.biasreg = 0.001; +matlabbatch{2}.spm.spatial.preproc.channel.biasfwhm = 60; +matlabbatch{2}.spm.spatial.preproc.channel.write = [0 1]; +matlabbatch{2}.spm.spatial.preproc.tissue(1).tpm = {fullfile(spm('dir'),'tpm','TPM.nii,1')}; +matlabbatch{2}.spm.spatial.preproc.tissue(1).ngaus = 1; +matlabbatch{2}.spm.spatial.preproc.tissue(1).native = [1 0]; +matlabbatch{2}.spm.spatial.preproc.tissue(1).warped = [0 0]; +matlabbatch{2}.spm.spatial.preproc.tissue(2).tpm = {fullfile(spm('dir'),'tpm','TPM.nii,2')}; +matlabbatch{2}.spm.spatial.preproc.tissue(2).ngaus = 1; +matlabbatch{2}.spm.spatial.preproc.tissue(2).native = [1 0]; +matlabbatch{2}.spm.spatial.preproc.tissue(2).warped = [0 0]; +matlabbatch{2}.spm.spatial.preproc.tissue(3).tpm = {fullfile(spm('dir'),'tpm','TPM.nii,3')}; +matlabbatch{2}.spm.spatial.preproc.tissue(3).ngaus = 2; +matlabbatch{2}.spm.spatial.preproc.tissue(3).native = [1 0]; +matlabbatch{2}.spm.spatial.preproc.tissue(3).warped = [0 0]; +matlabbatch{2}.spm.spatial.preproc.tissue(4).tpm = {fullfile(spm('dir'),'tpm','TPM.nii,4')}; +matlabbatch{2}.spm.spatial.preproc.tissue(4).ngaus = 3; +matlabbatch{2}.spm.spatial.preproc.tissue(4).native = [0 0]; +matlabbatch{2}.spm.spatial.preproc.tissue(4).warped = [0 0]; +matlabbatch{2}.spm.spatial.preproc.tissue(5).tpm = {fullfile(spm('dir'),'tpm','TPM.nii,5')}; +matlabbatch{2}.spm.spatial.preproc.tissue(5).ngaus = 4; +matlabbatch{2}.spm.spatial.preproc.tissue(5).native = [0 0]; +matlabbatch{2}.spm.spatial.preproc.tissue(5).warped = [0 0]; +matlabbatch{2}.spm.spatial.preproc.tissue(6).tpm = {fullfile(spm('dir'),'tpm','TPM.nii,6')}; +matlabbatch{2}.spm.spatial.preproc.tissue(6).ngaus = 2; +matlabbatch{2}.spm.spatial.preproc.tissue(6).native = [0 0]; +matlabbatch{2}.spm.spatial.preproc.tissue(6).warped = [0 0]; +matlabbatch{2}.spm.spatial.preproc.warp.mrf = 1; +matlabbatch{2}.spm.spatial.preproc.warp.cleanup = 1; +matlabbatch{2}.spm.spatial.preproc.warp.reg = [0 0.001 0.5 0.05 0.2]; +matlabbatch{2}.spm.spatial.preproc.warp.affreg = 'mni'; +matlabbatch{2}.spm.spatial.preproc.warp.fwhm = 0; +matlabbatch{2}.spm.spatial.preproc.warp.samp = 3; +matlabbatch{2}.spm.spatial.preproc.warp.write = [0 0]; +% CAT SPM segment +matlabbatch{3}.spm.tools.cat.estwrite_spm.data(1) = cfg_dep('Segment: c1 Images', substruct('.','val', '{}',{2}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','tiss', '()',{1}, '.','c', '()',{':'})); +matlabbatch{3}.spm.tools.cat.estwrite_spm.nproc = max(0,round(feature('numcores') ./ (1+ispc))); +matlabbatch{3}.spm.tools.cat.estwrite_spm.extopts.darteltpm = {fullfile(spm('dir'),'toolbox','cat12','templates_volumes','Template_1_IXI555_MNI152.nii')}; +matlabbatch{3}.spm.tools.cat.estwrite_spm.extopts.vox = 1.5; +matlabbatch{3}.spm.tools.cat.estwrite_spm.extopts.ignoreErrors = 0; +matlabbatch{3}.spm.tools.cat.estwrite_spm.output.ROI = 1; +matlabbatch{3}.spm.tools.cat.estwrite_spm.output.surface = 1; +matlabbatch{3}.spm.tools.cat.estwrite_spm.output.GM.warped = 0; +matlabbatch{3}.spm.tools.cat.estwrite_spm.output.GM.mod = 1; +matlabbatch{3}.spm.tools.cat.estwrite_spm.output.GM.dartel = 0; +matlabbatch{3}.spm.tools.cat.estwrite_spm.output.WM.warped = 0; +matlabbatch{3}.spm.tools.cat.estwrite_spm.output.WM.mod = 1; +matlabbatch{3}.spm.tools.cat.estwrite_spm.output.WM.dartel = 0; +matlabbatch{3}.spm.tools.cat.estwrite_spm.output.CSF.warped = 0; +matlabbatch{3}.spm.tools.cat.estwrite_spm.output.CSF.mod = 0; +matlabbatch{3}.spm.tools.cat.estwrite_spm.output.CSF.dartel = 0; +matlabbatch{3}.spm.tools.cat.estwrite_spm.output.jacobian.warped = 0; +matlabbatch{3}.spm.tools.cat.estwrite_spm.output.warps = [0 0]; +","MATLAB" +"Neurology","ChristianGaser/cat12","batches/cattest/cat12_101_MAIN_segment.m",".m","8719","142","% --------------------------------------------------------------------- +% Test batch ""Segment Data"" for VBM, SBM, and RBM preprocessing of +% cat_tst_cat.est. +% --------------------------------------------------------------------- +% Robert Dahnke +% $Id$ + +if ~exist('files_human','var') + files_human = {''}; + exp = cat_get_defaults('extopts.expertgui'); +elseif isempty(files_human) + return; +end + +% batch +% -- opts -------------------------------------------------------------- +matlabbatch{1}.spm.tools.cat.estwrite.data = files_human; +matlabbatch{1}.spm.tools.cat.estwrite.nproc = 0; +matlabbatch{1}.spm.tools.cat.estwrite.opts.tpm = { fullfile( spm('dir') , 'tpm' , 'TPM.nii' ) }; +matlabbatch{1}.spm.tools.cat.estwrite.opts.affreg = 'mni'; +matlabbatch{1}.spm.tools.cat.estwrite.opts.biasstr = 0.5; +if exp>0 % EXPERT + matlabbatch{1}.spm.tools.cat.estwrite.opts.ngaus = [1 1 2 3 4 2]; + matlabbatch{1}.spm.tools.cat.estwrite.opts.biasreg = 0.001; + matlabbatch{1}.spm.tools.cat.estwrite.opts.biasfwhm = 60; + matlabbatch{1}.spm.tools.cat.estwrite.opts.warpreg = [0 0.001 0.5 0.05 0.2]; + matlabbatch{1}.spm.tools.cat.estwrite.opts.samp = 3; + matlabbatch{1}.spm.tools.cat.estwrite.opts.tol = 1e-4; +end +% -- extopts ----------------------------------------------------------- +matlabbatch{1}.spm.tools.cat.estwrite.extopts.APP = 1070; +matlabbatch{1}.spm.tools.cat.estwrite.extopts.LASstr = 0.5; +matlabbatch{1}.spm.tools.cat.estwrite.extopts.gcutstr = 0.5; +% registration +matlabbatch{1}.spm.tools.cat.estwrite.extopts.registration.darteltpm = ... + { fullfile( spm('dir') , 'toolbox' , 'cat12' , 'templates_volumes' , 'Template_1_IXI555_MNI152.nii' ) }; +matlabbatch{1}.spm.tools.cat.estwrite.extopts.registration.shootingtpm = ... + { fullfile( spm('dir') , 'toolbox' , 'cat12' , 'templates_volumes' , 'Template_0_IXI555_MNI152_GS.nii' ) }; +matlabbatch{1}.spm.tools.cat.estwrite.extopts.registration.regstr = 0; matlabbatch{1}.spm.tools.cat.estwrite.extopts.vox = 1.5; +matlabbatch{1}.spm.tools.cat.estwrite.extopts.restypes.fixed = [1 0.1]; % use 2 mm for faster +if exp>0 % EXPERT + % segmentation + matlabbatch{1}.spm.tools.cat.estwrite.extopts.segmentation.APP = 1070; + matlabbatch{1}.spm.tools.cat.estwrite.extopts.segmentation.LASstr = 0.5; + matlabbatch{1}.spm.tools.cat.estwrite.extopts.segmentation.gcutstr = 0.5; + matlabbatch{1}.spm.tools.cat.estwrite.extopts.segmentation.regstr = 0; + matlabbatch{1}.spm.tools.cat.estwrite.extopts.segmentation.cleanupstr = 0.5; + matlabbatch{1}.spm.tools.cat.estwrite.extopts.segmentation.NCstr = -Inf; % noise filter strength + matlabbatch{1}.spm.tools.cat.estwrite.extopts.segmentation.WMHCstr = 0.5; + matlabbatch{1}.spm.tools.cat.estwrite.extopts.segmentation.WMHC = 1; + % surfaces + matlabbatch{1}.spm.tools.cat.estwrite.extopts.surface.pbtres = 0.5; + matlabbatch{1}.spm.tools.cat.estwrite.extopts.surface.scale_cortex = 0.7; + matlabbatch{1}.spm.tools.cat.estwrite.extopts.surface.add_parahipp = 0.1; + matlabbatch{1}.spm.tools.cat.estwrite.extopts.surface.close_parahipp = 0; + % admin + matlabbatch{1}.spm.tools.cat.estwrite.extopts.admin.experimental = 0; + matlabbatch{1}.spm.tools.cat.estwrite.extopts.admin.ignoreErrors = 0; + matlabbatch{1}.spm.tools.cat.estwrite.extopts.admin.verb = 2; + matlabbatch{1}.spm.tools.cat.estwrite.extopts.admin.print = 2; +end +if exp>1 % DEVELOPER + matlabbatch{1}.spm.tools.cat.estwrite.extopts.segmentation.BVCstr = 0; + matlabbatch{1}.spm.tools.cat.estwrite.extopts.registration.cat12atlas = { fullfile( spm('dir') , 'toolbox' , 'cat12' , 'templates_volumes' , 'cat.nii' ) }; + matlabbatch{1}.spm.tools.cat.estwrite.extopts.registration.brainmask = { fullfile( spm('dir') , 'toolbox' , 'FieldMap' , 'brainmask.nii' ) }; + matlabbatch{1}.spm.tools.cat.estwrite.extopts.registration.T1 = { fullfile( spm('dir') , 'toolbox' , 'FieldMap' , 'T1.nii' ) }; +% matlabbatch{1}.spm.tools.cat.estwrite.extopts.mrf = 1; + matlabbatch{1}.spm.tools.cat.estwrite.extopts.admin.lazy = 0; +end +% -- output ------------------------------------------------------------ +% surfaces +matlabbatch{1}.spm.tools.cat.estwrite.output.surface = 1; % SBM preprocessing +% ROIs +matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.neuromorphometrics = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.lpba40 = 0; +matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.cobra = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.hammers = 0; +if exp + matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.ibsr = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.aal3 = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.mori = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.anatomy = 0; +end +% GM +matlabbatch{1}.spm.tools.cat.estwrite.output.GM.native = 1; +if exp>0, matlabbatch{1}.spm.tools.cat.estwrite.output.GM.warped = 1; end +matlabbatch{1}.spm.tools.cat.estwrite.output.GM.mod = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.GM.dartel = 1; +% WM +matlabbatch{1}.spm.tools.cat.estwrite.output.WM.native = 1; +if exp>0, matlabbatch{1}.spm.tools.cat.estwrite.output.WM.warped = 1; end +matlabbatch{1}.spm.tools.cat.estwrite.output.WM.mod = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.WM.dartel = 1; +% CSF +if exp>0 % EXPERT + matlabbatch{1}.spm.tools.cat.estwrite.output.CSF.native = 1; + matlabbatch{1}.spm.tools.cat.estwrite.output.CSF.warped = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.CSF.mod = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.CSF.dartel = 0; + % WMH (for WMHC>0) + matlabbatch{1}.spm.tools.cat.estwrite.output.WMH.native = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.WMH.warped = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.WMH.mod = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.WMH.dartel = 0; + % label map + matlabbatch{1}.spm.tools.cat.estwrite.output.label.native = 1; + matlabbatch{1}.spm.tools.cat.estwrite.output.label.warped = 1; + matlabbatch{1}.spm.tools.cat.estwrite.output.label.dartel = 1; + % global intensity normalized + matlabbatch{1}.spm.tools.cat.estwrite.output.bias.native = 1; + matlabbatch{1}.spm.tools.cat.estwrite.output.bias.warped = 1; + matlabbatch{1}.spm.tools.cat.estwrite.output.bias.dartel = 1; + % local intensity normalized + matlabbatch{1}.spm.tools.cat.estwrite.output.las.native = 1; + matlabbatch{1}.spm.tools.cat.estwrite.output.las.warped = 1; + matlabbatch{1}.spm.tools.cat.estwrite.output.las.dartel = 1; +end +if exp>1 % DEVELOPER + % thickness + matlabbatch{1}.spm.tools.cat.estwrite.output.ct.native = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.ct.warped = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.ct.dartel = 0; + % Stroke + matlabbatch{1}.spm.tools.cat.estwrite.output.SL.native = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.SL.warped = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.SL.mod = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.SL.dartel = 0; + % TPMC (for TPM creation, e.g., to create an animal template) + matlabbatch{1}.spm.tools.cat.estwrite.output.TPMC.native = 1; + matlabbatch{1}.spm.tools.cat.estwrite.output.TPMC.warped = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.TPMC.mod = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.TPMC.dartel = 0; + % atlas maps (for atlas creation, e.g., in an animal tempate) + matlabbatch{1}.spm.tools.cat.estwrite.output.atlas.native = 1; + matlabbatch{1}.spm.tools.cat.estwrite.output.atlas.warped = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.atlas.dartel = 0; +end +% jacobian +matlabbatch{1}.spm.tools.cat.estwrite.output.jacobianwarped = 1; +% deformation +matlabbatch{1}.spm.tools.cat.estwrite.output.warps = [1 1]; +","MATLAB" +"Neurology","ChristianGaser/cat12","batches/cattest/cat12_104_MAIN_segment_SPM.m",".m","5646","80","%----------------------------------------------------------------------- +% Job saved on 24-Oct-2016 12:26:14 by cfg_util (rev $Rev$) +% spm SPM - SPM12 (6685) +% cfg_basicio BasicIO - Unknown +%----------------------------------------------------------------------- +%% + +if ~exist('files_human','var') + files_human = {''}; + exp = cat_get_defaults('extopts.expertgui'); +elseif isempty(files_human) + return; +end + +if exp + % sanlm denoising + matlabbatch{1}{1}.spm.tools.cat.tools.sanlm.data = files; + matlabbatch{1}{1}.spm.tools.cat.tools.sanlm.prefix = 'sanlm_'; + matlabbatch{1}{1}.spm.tools.cat.tools.sanlm.NCstr = inf; + matlabbatch{1}{1}.spm.tools.cat.tools.sanlm.rician = 0; + + % SPM segment + matlabbatch{1}{2}.spm.spatial.preproc.channel.vols(1) = cfg_dep('Spatially adaptive non-local means denoising filter: All Output Files', substruct('.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','vfiles')); + matlabbatch{1}{2}.spm.spatial.preproc.channel.biasreg = 0.001; + matlabbatch{1}{2}.spm.spatial.preproc.channel.biasfwhm = 60; + matlabbatch{1}{2}.spm.spatial.preproc.channel.write = [0 1]; + matlabbatch{1}{2}.spm.spatial.preproc.tissue(1).tpm = {fullfile(spm('dir'),'tpm','TPM.nii,1')}; + matlabbatch{1}{2}.spm.spatial.preproc.tissue(1).ngaus = 1; + matlabbatch{1}{2}.spm.spatial.preproc.tissue(1).native = [1 0]; + matlabbatch{1}{2}.spm.spatial.preproc.tissue(1).warped = [0 0]; + matlabbatch{1}{2}.spm.spatial.preproc.tissue(2).tpm = {fullfile(spm('dir'),'tpm','TPM.nii,2')}; + matlabbatch{1}{2}.spm.spatial.preproc.tissue(2).ngaus = 1; + matlabbatch{1}{2}.spm.spatial.preproc.tissue(2).native = [1 0]; + matlabbatch{1}{2}.spm.spatial.preproc.tissue(2).warped = [0 0]; + matlabbatch{1}{2}.spm.spatial.preproc.tissue(3).tpm = {fullfile(spm('dir'),'tpm','TPM.nii,3')}; + matlabbatch{1}{2}.spm.spatial.preproc.tissue(3).ngaus = 2; + matlabbatch{1}{2}.spm.spatial.preproc.tissue(3).native = [1 0]; + matlabbatch{1}{2}.spm.spatial.preproc.tissue(3).warped = [0 0]; + matlabbatch{1}{2}.spm.spatial.preproc.tissue(4).tpm = {fullfile(spm('dir'),'tpm','TPM.nii,4')}; + matlabbatch{1}{2}.spm.spatial.preproc.tissue(4).ngaus = 3; + matlabbatch{1}{2}.spm.spatial.preproc.tissue(4).native = [0 0]; + matlabbatch{1}{2}.spm.spatial.preproc.tissue(4).warped = [0 0]; + matlabbatch{1}{2}.spm.spatial.preproc.tissue(5).tpm = {fullfile(spm('dir'),'tpm','TPM.nii,5')}; + matlabbatch{1}{2}.spm.spatial.preproc.tissue(5).ngaus = 4; + matlabbatch{1}{2}.spm.spatial.preproc.tissue(5).native = [0 0]; + matlabbatch{1}{2}.spm.spatial.preproc.tissue(5).warped = [0 0]; + matlabbatch{1}{2}.spm.spatial.preproc.tissue(6).tpm = {fullfile(spm('dir'),'tpm','TPM.nii,6')}; + matlabbatch{1}{2}.spm.spatial.preproc.tissue(6).ngaus = 2; + matlabbatch{1}{2}.spm.spatial.preproc.tissue(6).native = [0 0]; + matlabbatch{1}{2}.spm.spatial.preproc.tissue(6).warped = [0 0]; + matlabbatch{1}{2}.spm.spatial.preproc.warp.mrf = 1; + matlabbatch{1}{2}.spm.spatial.preproc.warp.cleanup = 1; + matlabbatch{1}{2}.spm.spatial.preproc.warp.reg = [0 0.001 0.5 0.05 0.2]; + matlabbatch{1}{2}.spm.spatial.preproc.warp.affreg = 'mni'; + matlabbatch{1}{2}.spm.spatial.preproc.warp.fwhm = 0; + matlabbatch{1}{2}.spm.spatial.preproc.warp.samp = 3; + matlabbatch{1}{2}.spm.spatial.preproc.warp.write = [0 0]; + + % CAT SPM segment + matlabbatch{1}{3}.spm.tools.cat.estwrite_spm.data(1) = cfg_dep('Segment: c1 Images', substruct('.','val', '{}',{2}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','tiss', '()',{1}, '.','c', '()',{':'})); + matlabbatch{1}{3}.spm.tools.cat.estwrite_spm.nproc = 0; + matlabbatch{1}{3}.spm.tools.cat.estwrite_spm.extopts.darteltpm = {fullfile(spm('dir'),'toolbox','cat12','templates_volumes','Template_1_IXI555_MNI152.nii')}; + matlabbatch{1}{3}.spm.tools.cat.estwrite_spm.extopts.vox = 1.5; + if exp + matlabbatch{1}{3}.spm.tools.cat.estwrite_spm.extopts.ignoreErrors = 0; + end + matlabbatch{1}{3}.spm.tools.cat.estwrite_spm.output.ROI = 1; + matlabbatch{1}{3}.spm.tools.cat.estwrite_spm.output.surface = 1; + matlabbatch{1}{3}.spm.tools.cat.estwrite_spm.output.GM.warped = 0; + matlabbatch{1}{3}.spm.tools.cat.estwrite_spm.output.GM.mod = 1; + matlabbatch{1}{3}.spm.tools.cat.estwrite_spm.output.GM.dartel = 0; + matlabbatch{1}{3}.spm.tools.cat.estwrite_spm.output.WM.warped = 0; + matlabbatch{1}{3}.spm.tools.cat.estwrite_spm.output.WM.mod = 1; + matlabbatch{1}{3}.spm.tools.cat.estwrite_spm.output.WM.dartel = 0; + matlabbatch{1}{3}.spm.tools.cat.estwrite_spm.output.CSF.warped = 0; + matlabbatch{1}{3}.spm.tools.cat.estwrite_spm.output.CSF.mod = 0; + matlabbatch{1}{3}.spm.tools.cat.estwrite_spm.output.CSF.dartel = 0; + matlabbatch{1}{3}.spm.tools.cat.estwrite_spm.output.jacobian.warped = 0; + matlabbatch{1}{3}.spm.tools.cat.estwrite_spm.output.warps = [0 0]; +end","MATLAB" +"Neurology","ChristianGaser/cat12","batches/cattest/cat12_102_MAIN_segment_greaterapes.m",".m","6080","93","% --------------------------------------------------------------------- +% Test batch ""Segment Data"" for VBM, SBM, and RBM preprocessing of +% greater apes of cat_tst_cattest. +% --------------------------------------------------------------------- +% Robert Dahnke +% $Id$ + +if ~exist('files_greaterapes','var') + files_greaterapes = {''}; +elseif isempty(files_greaterapes) + return; +end + +% batch +% -- opts -------------------------------------------------------------- +matlabbatch{1}.spm.tools.cat.estwrite.data = files_greaterapes; +matlabbatch{1}.spm.tools.cat.estwrite.nproc = 0; +matlabbatch{1}.spm.tools.cat.estwrite.opts.tpm = { fullfile( spm('dir') , 'toolbox' , 'cat12' , 'templates_animals' , 'ape_greater_TPM.nii' ) }; +matlabbatch{1}.spm.tools.cat.estwrite.opts.ngaus = [3 3 2 3 4 2]; +matlabbatch{1}.spm.tools.cat.estwrite.opts.biasreg = 0.001; +matlabbatch{1}.spm.tools.cat.estwrite.opts.biasfwhm = 50; +matlabbatch{1}.spm.tools.cat.estwrite.opts.warpreg = [0 0.001 0.5 0.05 0.2]; +matlabbatch{1}.spm.tools.cat.estwrite.opts.affreg = 'mni'; +matlabbatch{1}.spm.tools.cat.estwrite.opts.samp = 2; +% -- extopts ----------------------------------------------------------- +matlabbatch{1}.spm.tools.cat.estwrite.extopts.lazy = 0; % EXPERT +matlabbatch{1}.spm.tools.cat.estwrite.extopts.APP = 5; +matlabbatch{1}.spm.tools.cat.estwrite.extopts.sanlm = 2; % noise filter +matlabbatch{1}.spm.tools.cat.estwrite.extopts.NCstr = Inf; % noise filter strength +matlabbatch{1}.spm.tools.cat.estwrite.extopts.LASstr = 0.5; % EXPERT +matlabbatch{1}.spm.tools.cat.estwrite.extopts.gcutstr = 0.5; % EXPERT +matlabbatch{1}.spm.tools.cat.estwrite.extopts.cleanupstr = 0.5; +matlabbatch{1}.spm.tools.cat.estwrite.extopts.BVCstr = 0; % EXPERT +matlabbatch{1}.spm.tools.cat.estwrite.extopts.WMHCstr = 0.5; % EXPERT +matlabbatch{1}.spm.tools.cat.estwrite.extopts.WMHC = 1; % EXPERT +matlabbatch{1}.spm.tools.cat.estwrite.extopts.darteltpm = { fullfile( spm('dir') , 'toolbox' , 'cat12' , 'templates_animals' , 'ape_greater_Template_1.nii' ) }; +matlabbatch{1}.spm.tools.cat.estwrite.extopts.cat12atlas = { fullfile( spm('dir') , 'toolbox' , 'cat12' , 'templates_animals' , 'ape_greater_cat.nii' ) }; +matlabbatch{1}.spm.tools.cat.estwrite.extopts.brainmask = { fullfile( spm('dir') , 'toolbox' , 'cat12' , 'templates_animals' , 'ape_greater_brainmask.nii' ) }; +matlabbatch{1}.spm.tools.cat.estwrite.extopts.T1 = { fullfile( spm('dir') , 'toolbox' , 'cat12' , 'templates_animals' , 'ape_greater_T1.nii' ) }; +matlabbatch{1}.spm.tools.cat.estwrite.extopts.restypes.best = [0.7 0.3]; % EXPERT +matlabbatch{1}.spm.tools.cat.estwrite.extopts.vox = 1.0; +matlabbatch{1}.spm.tools.cat.estwrite.extopts.pbtres = 0.5; +matlabbatch{1}.spm.tools.cat.estwrite.extopts.ignoreErrors = 1; % EXPERT +matlabbatch{1}.spm.tools.cat.estwrite.extopts.debug = 1; % EXPERT? +matlabbatch{1}.spm.tools.cat.estwrite.extopts.verb = 2; % EXPERT? +% -- output ------------------------------------------------------------ +matlabbatch{1}.spm.tools.cat.estwrite.output.ROI = 1; % RBM preprocessing +matlabbatch{1}.spm.tools.cat.estwrite.output.surface = 1; % SBM preprocessing +% GM +matlabbatch{1}.spm.tools.cat.estwrite.output.GM.native = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.GM.warped = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.GM.mod = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.GM.dartel = 1; +% WM +matlabbatch{1}.spm.tools.cat.estwrite.output.WM.native = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.WM.warped = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.WM.mod = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.WM.dartel = 1; +% CSF +matlabbatch{1}.spm.tools.cat.estwrite.output.CSF.native = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.CSF.warped = 0; +matlabbatch{1}.spm.tools.cat.estwrite.output.CSF.mod = 0; +matlabbatch{1}.spm.tools.cat.estwrite.output.CSF.dartel = 0; +% WMH (for WMHC>0) +matlabbatch{1}.spm.tools.cat.estwrite.output.WMH.native = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.WMH.warped = 0; +matlabbatch{1}.spm.tools.cat.estwrite.output.WMH.mod = 0; +matlabbatch{1}.spm.tools.cat.estwrite.output.WMH.dartel = 0; +% TPMC (for TPM creation, e.g., to create an animal template) +matlabbatch{1}.spm.tools.cat.estwrite.output.TPMC.native = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.TPMC.warped = 0; +matlabbatch{1}.spm.tools.cat.estwrite.output.TPMC.mod = 0; +matlabbatch{1}.spm.tools.cat.estwrite.output.TPMC.dartel = 0; +% atlas maps (for atlas creation, e.g., in an animal tempate) +matlabbatch{1}.spm.tools.cat.estwrite.output.atlas.native = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.atlas.warped = 0; +matlabbatch{1}.spm.tools.cat.estwrite.output.atlas.dartel = 0; +% label map +matlabbatch{1}.spm.tools.cat.estwrite.output.label.native = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.label.warped = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.label.dartel = 1; +% global intensity normalized +matlabbatch{1}.spm.tools.cat.estwrite.output.bias.native = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.bias.warped = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.bias.dartel = 1; +% local intensity normalized +matlabbatch{1}.spm.tools.cat.estwrite.output.las.native = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.las.warped = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.las.dartel = 1; +% jacobian +matlabbatch{1}.spm.tools.cat.estwrite.output.jacobian.warped = 1; +% deformation +matlabbatch{1}.spm.tools.cat.estwrite.output.warps = [1 1];","MATLAB" +"Neurology","ChristianGaser/cat12","batches/cattest/cat12_202_VBM_tools.m",".m","3212","97","% --------------------------------------------------------------------- +% Test batch for surfcalc of cat_tst_cattest. +% --------------------------------------------------------------------- +% Robert Dahnke +% $Id$ + +%#ok<*SAGROW> + +% prepare filenames +% --------------------------------------------------------------------- +if exist('files','var') + xmls = {}; + vols = {}; + for fi = 1:numel(files_human) + [pp,ff] = spm_fileparts(files_human{fi}); + xmls{fi,1} = fullfile( pp , reportdir , ['cat_' ff '.xml'] ); + vols{fi,1} = fullfile( pp , mridir , ['wm' ff '.nii'] ); + end + outdir = {fullfile( job.resdir , 'RBMexport' )}; +else + files = {''}; + xmls = {''}; + vols = {''}; + outdir = {''}; + exp = cat_get_defaults('extopts.expertgui'); +end + + + +% batch +% ---------------------------------------------------------------------- + +% show slices +mix=1; +matlabbatch{mix}.spm.tools.cat.tools.showslice.data_vol = repmat(files,3,1); +matlabbatch{mix}.spm.tools.cat.tools.showslice.scale = 0; +matlabbatch{mix}.spm.tools.cat.tools.showslice.orient = 3; +matlabbatch{mix}.spm.tools.cat.tools.showslice.slice = 0; + +% covariance ... volume vs. surface ... +if numel(vols)>1 % this can not work ... + mix=mix+1; + matlabbatch{mix}.spm.tools.cat.tools.check_cov.data_vol = {vols}; + matlabbatch{mix}.spm.tools.cat.tools.check_cov.data_xml = {}; + matlabbatch{mix}.spm.tools.cat.tools.check_cov.gap = 3; + matlabbatch{mix}.spm.tools.cat.tools.check_cov.c = {}; + + if numel(vols)>3 + mix=mix+1; + matlabbatch{mix}.spm.tools.cat.tools.check_cov.data_vol = { + vols(1:floor(numel(vols)/2)); + vols(floor(numel(vols)/2)+1:end); + }; + matlabbatch{mix}.spm.tools.cat.tools.check_cov.data_xml = { + xmls(1:floor(numel(xmls)/2)); + xmls(floor(numel(vols)/2)+1:end); + }; + matlabbatch{mix}.spm.tools.cat.tools.check_cov.gap = 3; + matlabbatch{mix}.spm.tools.cat.tools.check_cov.c = {}; + end +end + +% can not open this part as batch ... +if numel(xmls) % and not Shooting ... + % export IQR + mix=mix+1; + matlabbatch{mix}.spm.tools.cat.tools.iqr.data_xml = xmls; + matlabbatch{mix}.spm.tools.cat.tools.iqr.iqr_name = 'IQR.txt'; + % export TIV + mix=mix+1; + matlabbatch{mix}.spm.tools.cat.tools.calcvol.data_xml = xmls; + matlabbatch{mix}.spm.tools.cat.tools.calcvol.calcvol_TIV = 0; + matlabbatch{mix}.spm.tools.cat.tools.calcvol.calcvol_name = 'CGWHV.txt'; + % export TIV + mix=mix+1; + matlabbatch{mix}.spm.tools.cat.tools.calcvol.data_xml = xmls; + matlabbatch{mix}.spm.tools.cat.tools.calcvol.calcvol_TIV = 1; + matlabbatch{mix}.spm.tools.cat.tools.calcvol.calcvol_name = 'TIV.txt'; +end + +% test sanlm script > data? +if numel(files) + mix=mix+1; + matlabbatch{mix}.spm.tools.cat.tools.sanlm.data = files(1); + matlabbatch{mix}.spm.tools.cat.tools.sanlm.prefix = 'sanlm_'; + matlabbatch{mix}.spm.tools.cat.tools.sanlm.NCstr = -inf; + matlabbatch{mix}.spm.tools.cat.tools.sanlm.rician = 0; +end +%} +% NOT FINISHED YET +%{ + +% flip sides +matlabbatch{6}.spm.tools.cat.stools.flipsides.cdata = ''; +% surfcalc - difference + +%}","MATLAB" +"Neurology","ChristianGaser/cat12","batches/cattest/cat12_106_MAIN_segment_1173.m",".m","8479","132","% --------------------------------------------------------------------- +% Test batch ""Segment Data"" for VBM, SBM, and RBM preprocessing of +% cat_tst_cat.est. +% --------------------------------------------------------------------- +% Robert Dahnke +% $Id$ + +if ~exist('files_human','var') + files_human1173 = {''}; + exp = cat_get_defaults1173('extopts1173.expertgui'); +elseif isempty(files_human1173) + return; +end + +% batch +% -- opts -------------------------------------------------------------- +matlabbatch{1}.spm.tools.cat.estwrite1173.data = files_human1173; +matlabbatch{1}.spm.tools.cat.estwrite1173.nproc = 0; +matlabbatch{1}.spm.tools.cat.estwrite1173.opts.tpm = { fullfile( spm('dir') , 'tpm' , 'TPM.nii' ) }; +matlabbatch{1}.spm.tools.cat.estwrite1173.opts.affreg = 'mni'; +matlabbatch{1}.spm.tools.cat.estwrite1173.opts.biasstr = 0.5; +if exp>0 % EXPERT + matlabbatch{1}.spm.tools.cat.estwrite1173.opts.ngaus = [1 1 2 3 4 2]; + matlabbatch{1}.spm.tools.cat.estwrite1173.opts.biasreg = 0.001; + matlabbatch{1}.spm.tools.cat.estwrite1173.opts.biasfwhm = 60; + matlabbatch{1}.spm.tools.cat.estwrite1173.opts.warpreg = [0 0.001 0.5 0.05 0.2]; + matlabbatch{1}.spm.tools.cat.estwrite1173.opts.samp = 3; +end +% -- extopts ----------------------------------------------------------- +matlabbatch{1}.spm.tools.cat.estwrite1173.extopts.APP = 1070; +matlabbatch{1}.spm.tools.cat.estwrite1173.extopts.LASstr = 0.5; +matlabbatch{1}.spm.tools.cat.estwrite1173.extopts.gcutstr = 0.5; +% registration +matlabbatch{1}.spm.tools.cat.estwrite1173.extopts.registration.darteltpm = ... + { fullfile( spm('dir') , 'toolbox' , 'cat12' , 'templates_volumes' , 'Template_1_IXI555_MNI152.nii' ) }; +matlabbatch{1}.spm.tools.cat.estwrite1173.extopts.registration.shootingtpm = ... + { fullfile( spm('dir') , 'toolbox' , 'cat12' , 'templates_volumes' , 'Template_0_IXI555_MNI152_GS.nii' ) }; +matlabbatch{1}.spm.tools.cat.estwrite1173.extopts.registration.regstr = 0; matlabbatch{1}.spm.tools.cat.estwrite1173.extopts.vox = 1.5; +matlabbatch{1}.spm.tools.cat.estwrite1173.extopts.restypes.fixed = [1 0.1]; % use 2 mm for faster +if exp>0 % EXPERT + % segmentation + matlabbatch{1}.spm.tools.cat.estwrite1173.extopts.segmentation.APP = 1070; + matlabbatch{1}.spm.tools.cat.estwrite1173.extopts.segmentation.LASstr = 0.5; + matlabbatch{1}.spm.tools.cat.estwrite1173.extopts.segmentation.gcutstr = 0.5; + matlabbatch{1}.spm.tools.cat.estwrite1173.extopts.segmentation.regstr = 0; + matlabbatch{1}.spm.tools.cat.estwrite1173.extopts.segmentation.cleanupstr = 0.5; + matlabbatch{1}.spm.tools.cat.estwrite1173.extopts.segmentation.NCstr = -Inf; % noise filter strength + matlabbatch{1}.spm.tools.cat.estwrite1173.extopts.segmentation.WMHCstr = 0.5; + matlabbatch{1}.spm.tools.cat.estwrite1173.extopts.segmentation.WMHC = 1; + % surfaces + matlabbatch{1}.spm.tools.cat.estwrite1173.extopts.surface.pbtres = 0.5; + matlabbatch{1}.spm.tools.cat.estwrite1173.extopts.surface.scale_cortex = 0.7; + matlabbatch{1}.spm.tools.cat.estwrite1173.extopts.surface.add_parahipp = 0.1; + matlabbatch{1}.spm.tools.cat.estwrite1173.extopts.surface.close_parahipp = 0; + % admin + matlabbatch{1}.spm.tools.cat.estwrite1173.extopts.admin.experimental = 0; + matlabbatch{1}.spm.tools.cat.estwrite1173.extopts.admin.ignoreErrors = 0; + matlabbatch{1}.spm.tools.cat.estwrite1173.extopts.admin.verb = 2; + matlabbatch{1}.spm.tools.cat.estwrite1173.extopts.admin.print = 2; +end +if exp>1 % DEVELOPER + matlabbatch{1}.spm.tools.cat.estwrite1173.extopts.segmentation.BVCstr = 0; + matlabbatch{1}.spm.tools.cat.estwrite1173.extopts.registration.cat12atlas = { fullfile( spm('dir') , 'toolbox' , 'cat12' , 'templates_volumes' , 'cat.nii' ) }; + matlabbatch{1}.spm.tools.cat.estwrite1173.extopts.registration.brainmask = { fullfile( spm('dir') , 'toolbox' , 'FieldMap' , 'brainmask.nii' ) }; + matlabbatch{1}.spm.tools.cat.estwrite1173.extopts.registration.T1 = { fullfile( spm('dir') , 'toolbox' , 'FieldMap' , 'T1.nii' ) }; +% matlabbatch{1}.spm.tools.cat.estwrite1173.extopts.mrf = 1; + matlabbatch{1}.spm.tools.cat.estwrite1173.extopts.admin.lazy = 0; +end +% -- output ------------------------------------------------------------ +% surfaces +matlabbatch{1}.spm.tools.cat.estwrite1173.output.surface = 1; % SBM preprocessing +% ROIs +matlabbatch{1}.spm.tools.cat.estwrite1173.output.ROImenu.atlases.neuromorphometrics = 1; +matlabbatch{1}.spm.tools.cat.estwrite1173.output.ROImenu.atlases.lpba40 = 0; +matlabbatch{1}.spm.tools.cat.estwrite1173.output.ROImenu.atlases.cobra = 1; +matlabbatch{1}.spm.tools.cat.estwrite1173.output.ROImenu.atlases.hammers = 0; +if exp + matlabbatch{1}.spm.tools.cat.estwrite1173.output.ROImenu.atlases.ibsr = 0; + matlabbatch{1}.spm.tools.cat.estwrite1173.output.ROImenu.atlases.aal3 = 0; + matlabbatch{1}.spm.tools.cat.estwrite1173.output.ROImenu.atlases.mori = 0; + matlabbatch{1}.spm.tools.cat.estwrite1173.output.ROImenu.atlases.anatomy = 0; +end +% GM +matlabbatch{1}.spm.tools.cat.estwrite1173.output.GM.native = 1; +if exp>0, matlabbatch{1}.spm.tools.cat.estwrite1173.output.GM.warped = 1; end +matlabbatch{1}.spm.tools.cat.estwrite1173.output.GM.mod = 1; +matlabbatch{1}.spm.tools.cat.estwrite1173.output.GM.dartel = 1; +% WM +matlabbatch{1}.spm.tools.cat.estwrite1173.output.WM.native = 1; +if exp>0, matlabbatch{1}.spm.tools.cat.estwrite1173.output.WM.warped = 1; end +matlabbatch{1}.spm.tools.cat.estwrite1173.output.WM.mod = 1; +matlabbatch{1}.spm.tools.cat.estwrite1173.output.WM.dartel = 1; +% CSF +if exp>0 % EXPERT + matlabbatch{1}.spm.tools.cat.estwrite1173.output.CSF.native = 1; + matlabbatch{1}.spm.tools.cat.estwrite1173.output.CSF.warped = 0; + matlabbatch{1}.spm.tools.cat.estwrite1173.output.CSF.mod = 0; + matlabbatch{1}.spm.tools.cat.estwrite1173.output.CSF.dartel = 0; + % WMH (for WMHC>0) + matlabbatch{1}.spm.tools.cat.estwrite1173.output.WMH.native = 1; + matlabbatch{1}.spm.tools.cat.estwrite1173.output.WMH.warped = 0; + matlabbatch{1}.spm.tools.cat.estwrite1173.output.WMH.mod = 0; + matlabbatch{1}.spm.tools.cat.estwrite1173.output.WMH.dartel = 0; + % label map + matlabbatch{1}.spm.tools.cat.estwrite1173.output.label.native = 1; + matlabbatch{1}.spm.tools.cat.estwrite1173.output.label.warped = 1; + matlabbatch{1}.spm.tools.cat.estwrite1173.output.label.dartel = 1; + % global intensity normalized + matlabbatch{1}.spm.tools.cat.estwrite1173.output.bias.native = 1; + matlabbatch{1}.spm.tools.cat.estwrite1173.output.bias.warped = 1; + matlabbatch{1}.spm.tools.cat.estwrite1173.output.bias.dartel = 1; + % local intensity normalized + matlabbatch{1}.spm.tools.cat.estwrite1173.output.las.native = 1; + matlabbatch{1}.spm.tools.cat.estwrite1173.output.las.warped = 1; + matlabbatch{1}.spm.tools.cat.estwrite1173.output.las.dartel = 1; +end +if exp>1 % DEVELOPER + % TPMC (for TPM creation, e.g., to create an animal template) + matlabbatch{1}.spm.tools.cat.estwrite1173.output.TPMC.native = 1; + matlabbatch{1}.spm.tools.cat.estwrite1173.output.TPMC.warped = 0; + matlabbatch{1}.spm.tools.cat.estwrite1173.output.TPMC.mod = 0; + matlabbatch{1}.spm.tools.cat.estwrite1173.output.TPMC.dartel = 0; + % atlas maps (for atlas creation, e.g., in an animal tempate) + matlabbatch{1}.spm.tools.cat.estwrite1173.output.atlas.native = 1; + matlabbatch{1}.spm.tools.cat.estwrite1173.output.atlas.warped = 0; + matlabbatch{1}.spm.tools.cat.estwrite1173.output.atlas.dartel = 0; +end +% jacobian +matlabbatch{1}.spm.tools.cat.estwrite1173.output.jacobianwarped = 1; +% deformation +matlabbatch{1}.spm.tools.cat.estwrite1173.output.warps = [1 1]; +","MATLAB" +"Neurology","ChristianGaser/cat12","batches/cattest/cat12_203_VBM_exportRBM.m",".m","1162","36","% --------------------------------------------------------------------- +% Test batch for surface data resampling and smoothing of cat_tst_cattest. +% This batch exports all ROI measures contained in the XML files. +% --------------------------------------------------------------------- +% Robert Dahnke +% $Id$ + +%#ok<*SAGROW> + +% prepare filenames +% --------------------------------------------------------------------- +if exist('files','var') + xmls = {}; + for fi = 1:numel(files) + [pp,ff] = spm_fileparts(files{fi}); + xmls{end+1,1} = fullfile( pp , roidir , ['catROI_' ff '.xml'] ); + end + outdir = {fullfile( pp , 'RBMexport' )}; +else + xmls = {''}; + outdir = {''}; +end + + + + +% batch +% --------------------------------------------------------------------- + +% VBM atlases +matlabbatch{1}.spm.tools.cat.tools.calcroi.roi_xml = xmls; +matlabbatch{1}.spm.tools.cat.tools.calcroi.folder = 0; +matlabbatch{1}.spm.tools.cat.tools.calcroi.point = '.'; +matlabbatch{1}.spm.tools.cat.tools.calcroi.outdir = outdir; +matlabbatch{1}.spm.tools.cat.tools.calcroi.calcroi_name = 'VBMatlases'; +","MATLAB" +"Neurology","ChristianGaser/cat12","batches/cattest/cat12_302_SBM_MapNormVol2AvgSurf.m",".m","5201","78","% --------------------------------------------------------------------- +% Test batch to test the Mapping of Normalized Volumes to the average +% surface. Used in cat_tst_cattest. +% --------------------------------------------------------------------- +% Robert Dahnke +% $Id$ + +%#ok<*SAGROW> + +% prepare filename +%----------------------------------------------------------------------- +if exist('files','var') + for fi = 1:numel(files) + [pp,ff] = spm_fileparts(files{fi}); + vols{fi,1} = fullfile( pp , mridir , ['wm' ff '.nii'] ); + end +else + vols = {''}; + exp = cat_get_defaults('extopts.expertgui'); +end +surfs = { fullfile(spm('dir'),'toolbox','cat12','templates_surfaces','lh.central.Template_T1_IXI555_MNI152_GS.gii') }; + +% batch +% ---------------------------------------------------------------------- + +% cat default value - 3 average points in the GM (CSF/GM - GM - GM/WM) +matlabbatch{1}.spm.tools.cat.stools.vol2surf.data_vol = vols; +matlabbatch{1}.spm.tools.cat.stools.vol2surf.data_mesh_lh = surfs; +matlabbatch{1}.spm.tools.cat.stools.vol2surf.sample = {'avg'}; +if exp, matlabbatch{1}.spm.tools.cat.stools.vol2surf.interp = {'linear'}; end +matlabbatch{1}.spm.tools.cat.stools.vol2surf.datafieldname = 'GM-T1-intensity'; +matlabbatch{1}.spm.tools.cat.stools.vol2surf.mapping.rel_mapping.class = 'GM'; +matlabbatch{1}.spm.tools.cat.stools.vol2surf.mapping.rel_mapping.startpoint = 0; +matlabbatch{1}.spm.tools.cat.stools.vol2surf.mapping.rel_mapping.stepsize = 0.5; +matlabbatch{1}.spm.tools.cat.stools.vol2surf.mapping.rel_mapping.endpoint = 1; + +% L1 intensity of equal distance layer +matlabbatch{2}.spm.tools.cat.stools.vol2surf.data_vol = vols; +matlabbatch{2}.spm.tools.cat.stools.vol2surf.data_mesh_lh = surfs; +matlabbatch{2}.spm.tools.cat.stools.vol2surf.sample = {'avg'}; +if exp, matlabbatch{2}.spm.tools.cat.stools.vol2surf.interp = {'linear'}; end +matlabbatch{2}.spm.tools.cat.stools.vol2surf.datafieldname = 'EquiDist-Layer0-Intensity'; +matlabbatch{2}.spm.tools.cat.stools.vol2surf.mapping.rel_mapping.class = 'GM'; +matlabbatch{2}.spm.tools.cat.stools.vol2surf.mapping.rel_mapping.startpoint = 1/13; +matlabbatch{2}.spm.tools.cat.stools.vol2surf.mapping.rel_mapping.stepsize = 0; +matlabbatch{2}.spm.tools.cat.stools.vol2surf.mapping.rel_mapping.endpoint = 0; +% L4 intensity of equal distance layer +matlabbatch{3}.spm.tools.cat.stools.vol2surf.data_vol = vols; +matlabbatch{3}.spm.tools.cat.stools.vol2surf.data_mesh_lh = surfs; +matlabbatch{3}.spm.tools.cat.stools.vol2surf.sample = {'avg'}; +if exp, matlabbatch{3}.spm.tools.cat.stools.vol2surf.interp = {'linear'}; end +matlabbatch{3}.spm.tools.cat.stools.vol2surf.datafieldname = 'EquiDist-Layer4-Intensity'; +matlabbatch{3}.spm.tools.cat.stools.vol2surf.mapping.rel_mapping.class = 'GM'; +matlabbatch{3}.spm.tools.cat.stools.vol2surf.mapping.rel_mapping.startpoint = 7/13; +matlabbatch{3}.spm.tools.cat.stools.vol2surf.mapping.rel_mapping.stepsize = 0; +matlabbatch{3}.spm.tools.cat.stools.vol2surf.mapping.rel_mapping.endpoint = 0; +% L6 intensity of equal distance layer +matlabbatch{4}.spm.tools.cat.stools.vol2surf.data_vol = vols; +matlabbatch{4}.spm.tools.cat.stools.vol2surf.data_mesh_lh = surfs; +matlabbatch{4}.spm.tools.cat.stools.vol2surf.sample = {'avg'}; +if exp, matlabbatch{4}.spm.tools.cat.stools.vol2surf.interp = {'linear'}; end +matlabbatch{4}.spm.tools.cat.stools.vol2surf.datafieldname = 'EquiDist-Layer6-Intensity'; +matlabbatch{4}.spm.tools.cat.stools.vol2surf.mapping.rel_mapping.class = 'GM'; +matlabbatch{4}.spm.tools.cat.stools.vol2surf.mapping.rel_mapping.startpoint = 12/13; +matlabbatch{4}.spm.tools.cat.stools.vol2surf.mapping.rel_mapping.stepsize = 0; +matlabbatch{4}.spm.tools.cat.stools.vol2surf.mapping.rel_mapping.endpoint = 0; + +% WM value at 1.5 times of the local thickness (half thickness into the WM) +matlabbatch{5}.spm.tools.cat.stools.vol2surf.data_vol = vols; +matlabbatch{5}.spm.tools.cat.stools.vol2surf.data_mesh_lh = surfs; +matlabbatch{5}.spm.tools.cat.stools.vol2surf.sample = {'avg'}; +if exp, matlabbatch{5}.spm.tools.cat.stools.vol2surf.interp = {'linear'}; end +matlabbatch{5}.spm.tools.cat.stools.vol2surf.datafieldname = 'WM-Intensity-at150percentCT'; +matlabbatch{5}.spm.tools.cat.stools.vol2surf.mapping.rel_mapping.class = 'GM'; +matlabbatch{5}.spm.tools.cat.stools.vol2surf.mapping.rel_mapping.startpoint = 1.5; +matlabbatch{5}.spm.tools.cat.stools.vol2surf.mapping.rel_mapping.stepsize = 0; +matlabbatch{5}.spm.tools.cat.stools.vol2surf.mapping.rel_mapping.endpoint = 0; +","MATLAB" +"Neurology","ChristianGaser/cat12","batches/cattest/cat12_103_MAIN_segment_oldworldmonkeys.m",".m","6120","93","% --------------------------------------------------------------------- +% Test batch ""Segment Data"" for VBM, SBM, and RBM preprocessing of +% oldworld monkeys of cat_tst_cattest. +% --------------------------------------------------------------------- +% Robert Dahnke +% $Id$ + +if ~exist('files_oldworldmonkeys','var') + files_oldworldmonkeys = {''}; +elseif isempty(files_oldworldmonkeys) + return; +end + +% batch +% -- opts -------------------------------------------------------------- +matlabbatch{1}.spm.tools.cat.estwrite.data = files_oldworldmonkeys; +matlabbatch{1}.spm.tools.cat.estwrite.nproc = 0; +matlabbatch{1}.spm.tools.cat.estwrite.opts.tpm = { fullfile( spm('dir') , 'toolbox' , 'cat12' , 'templates_animals' , 'monkey_oldworld_TPM.nii' ) }; +matlabbatch{1}.spm.tools.cat.estwrite.opts.ngaus = [3 3 2 3 4 2]; +matlabbatch{1}.spm.tools.cat.estwrite.opts.biasreg = 0.001; +matlabbatch{1}.spm.tools.cat.estwrite.opts.biasfwhm = 50; +matlabbatch{1}.spm.tools.cat.estwrite.opts.warpreg = [0 0.001 0.5 0.05 0.2]; +matlabbatch{1}.spm.tools.cat.estwrite.opts.affreg = 'mni'; +matlabbatch{1}.spm.tools.cat.estwrite.opts.samp = 2; +% -- extopts ----------------------------------------------------------- +matlabbatch{1}.spm.tools.cat.estwrite.extopts.lazy = 0; % EXPERT +matlabbatch{1}.spm.tools.cat.estwrite.extopts.APP = 5; +matlabbatch{1}.spm.tools.cat.estwrite.extopts.sanlm = 2; % noise filter +matlabbatch{1}.spm.tools.cat.estwrite.extopts.NCstr = Inf; % noise filter strength +matlabbatch{1}.spm.tools.cat.estwrite.extopts.LASstr = 0.5; % EXPERT +matlabbatch{1}.spm.tools.cat.estwrite.extopts.gcutstr = 0.5; % EXPERT +matlabbatch{1}.spm.tools.cat.estwrite.extopts.cleanupstr = 0.5; +matlabbatch{1}.spm.tools.cat.estwrite.extopts.BVCstr = 0; % EXPERT +matlabbatch{1}.spm.tools.cat.estwrite.extopts.WMHCstr = 0.5; % EXPERT +matlabbatch{1}.spm.tools.cat.estwrite.extopts.WMHC = 1; % EXPERT +matlabbatch{1}.spm.tools.cat.estwrite.extopts.darteltpm = { fullfile( spm('dir') , 'toolbox' , 'cat12' , 'templates_animals' , 'monkey_oldworld_Template_1.nii' ) }; +matlabbatch{1}.spm.tools.cat.estwrite.extopts.cat12atlas = { fullfile( spm('dir') , 'toolbox' , 'cat12' , 'templates_animals' , 'monkey_oldworld_cat.nii' ) }; +matlabbatch{1}.spm.tools.cat.estwrite.extopts.brainmask = { fullfile( spm('dir') , 'toolbox' , 'cat12' , 'templates_animals' , 'monkey_oldworld_brainmask.nii' ) }; +matlabbatch{1}.spm.tools.cat.estwrite.extopts.T1 = { fullfile( spm('dir') , 'toolbox' , 'cat12' , 'templates_animals' , 'monkey_oldworld_T1.nii' ) }; +matlabbatch{1}.spm.tools.cat.estwrite.extopts.restypes.best = [0.7 0.3]; % EXPERT +matlabbatch{1}.spm.tools.cat.estwrite.extopts.vox = 1.0; +matlabbatch{1}.spm.tools.cat.estwrite.extopts.pbtres = 0.5; +matlabbatch{1}.spm.tools.cat.estwrite.extopts.ignoreErrors = 1; % EXPERT +matlabbatch{1}.spm.tools.cat.estwrite.extopts.debug = 1; % EXPERT? +matlabbatch{1}.spm.tools.cat.estwrite.extopts.verb = 2; % EXPERT? +% -- output ------------------------------------------------------------ +matlabbatch{1}.spm.tools.cat.estwrite.output.ROI = 1; % RBM preprocessing +matlabbatch{1}.spm.tools.cat.estwrite.output.surface = 1; % SBM preprocessing +% GM +matlabbatch{1}.spm.tools.cat.estwrite.output.GM.native = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.GM.warped = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.GM.mod = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.GM.dartel = 1; +% WM +matlabbatch{1}.spm.tools.cat.estwrite.output.WM.native = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.WM.warped = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.WM.mod = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.WM.dartel = 1; +% CSF +matlabbatch{1}.spm.tools.cat.estwrite.output.CSF.native = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.CSF.warped = 0; +matlabbatch{1}.spm.tools.cat.estwrite.output.CSF.mod = 0; +matlabbatch{1}.spm.tools.cat.estwrite.output.CSF.dartel = 0; +% WMH (for WMHC>0) +matlabbatch{1}.spm.tools.cat.estwrite.output.WMH.native = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.WMH.warped = 0; +matlabbatch{1}.spm.tools.cat.estwrite.output.WMH.mod = 0; +matlabbatch{1}.spm.tools.cat.estwrite.output.WMH.dartel = 0; +% TPMC (for TPM creation, e.g., to create an animal template) +matlabbatch{1}.spm.tools.cat.estwrite.output.TPMC.native = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.TPMC.warped = 0; +matlabbatch{1}.spm.tools.cat.estwrite.output.TPMC.mod = 0; +matlabbatch{1}.spm.tools.cat.estwrite.output.TPMC.dartel = 0; +% atlas maps (for atlas creation, e.g., in an animal tempate) +matlabbatch{1}.spm.tools.cat.estwrite.output.atlas.native = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.atlas.warped = 0; +matlabbatch{1}.spm.tools.cat.estwrite.output.atlas.dartel = 0; +% label map +matlabbatch{1}.spm.tools.cat.estwrite.output.label.native = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.label.warped = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.label.dartel = 1; +% global intensity normalized +matlabbatch{1}.spm.tools.cat.estwrite.output.bias.native = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.bias.warped = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.bias.dartel = 1; +% local intensity normalized +matlabbatch{1}.spm.tools.cat.estwrite.output.las.native = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.las.warped = 1; +matlabbatch{1}.spm.tools.cat.estwrite.output.las.dartel = 1; +% jacobian +matlabbatch{1}.spm.tools.cat.estwrite.output.jacobian.warped = 1; +% deformation +matlabbatch{1}.spm.tools.cat.estwrite.output.warps = [1 1];","MATLAB" +"Neurology","ChristianGaser/cat12","batches/cattest/cat12_308_SBM_Surf2ROI.m",".m","2396","63","% --------------------------------------------------------------------- +% This is a test batch to map surface data to atlases called by the +% cat_tst_cattest function. +% +% Important sub test cases: +% - original vs. resampled data file +% - FreeSurfer vs. GIFTI input +% - default vs. expert mode +% - bad cases??? +% * non existing files +% * bad data structures +% --------------------------------------------------------------------- +% Robert Dahnke +% $Id$ + +%#ok<*SAGROW> + +% prepare filename +% --------------------------------------------------------------------- +if exist('files','var') + cdata = {}; + cdatares = {}; + for fi = 1:numel(files) + [pp,ff] = spm_fileparts(files{fi}); + cdata{end+1,1} = fullfile( pp , surfdir , ['mesh.thickness.' ff ] ); + cdata{end+1,1} = fullfile( pp , surfdir , ['mesh.gyrification.' ff] ); + + cdatares{end+1,1} = fullfile( pp , surfdir , ['s15mm.mesh.thickness.resampled.' ff '.gii'] ); + cdatares{end+1,1} = fullfile( pp , surfdir , ['s15mm.mesh.gyrification.resampled.' ff '.gii'] ); + end +else + cdata = {''}; + cdatares = {''}; +end +rdata = cat_vol_findfiles( fullfile(spm('dir') , 'toolbox' , 'cat12' , 'atlases_surfaces'), 'lh*.annot' ); + + +% batch +% --------------------------------------------------------------------- +% original +matlabbatch{1}.spm.tools.cat.stools.surf2roi.cdata = {cdata}; +if exp + matlabbatch{1}.spm.tools.cat.stools.surf2roi.rdata = rdata; + matlabbatch{1}.spm.tools.cat.stools.surf2roi.nproc = 0; + matlabbatch{1}.spm.tools.cat.stools.surf2roi.avg.mean = 1; + matlabbatch{1}.spm.tools.cat.stools.surf2roi.avg.std = 0; + matlabbatch{1}.spm.tools.cat.stools.surf2roi.avg.min = 0; + matlabbatch{1}.spm.tools.cat.stools.surf2roi.avg.max = 0; + matlabbatch{1}.spm.tools.cat.stools.surf2roi.avg.median = 0; +end + +% resampled +matlabbatch{2}.spm.tools.cat.stools.surf2roi.cdata = {cdatares}; +if exp + matlabbatch{2}.spm.tools.cat.stools.surf2roi.rdata = rdata; + matlabbatch{2}.spm.tools.cat.stools.surf2roi.nproc = 0; + matlabbatch{2}.spm.tools.cat.stools.surf2roi.avg.mean = 1; + matlabbatch{2}.spm.tools.cat.stools.surf2roi.avg.std = 0; + matlabbatch{2}.spm.tools.cat.stools.surf2roi.avg.min = 0; + matlabbatch{2}.spm.tools.cat.stools.surf2roi.avg.max = 0; + matlabbatch{2}.spm.tools.cat.stools.surf2roi.avg.median = 0; +end + ","MATLAB" +"Neurology","ChristianGaser/cat12","batches/cattest/cat12_309_SBM_exportRBM.m",".m","1197","37","% --------------------------------------------------------------------- +% Test batch for surface data resampling and smoothing of cat_tst_cattest. +% This batch exports all ROI measures contained in the XML files. +% --------------------------------------------------------------------- +% Robert Dahnke +% $Id$ + +%#ok<*SAGROW> + +% prepare filenames +% --------------------------------------------------------------------- +if exist('files','var') + sxmls = {}; + for fi = 1:numel(files) + [pp,ff] = spm_fileparts(files{fi}); + sxmls{end+1,1} = fullfile( pp , roidir , ['catROIs_' ff '.xml'] ); + end + outdir = {fullfile( pp , 'RBMexport' )}; +else + sxmls = {''}; + outdir = {''}; +end + + + + +% batch +% --------------------------------------------------------------------- + +% SBM atlases with full path in subject name +matlabbatch{1}.spm.tools.cat.tools.calcroi.roi_xml = sxmls; +matlabbatch{1}.spm.tools.cat.tools.calcroi.folder = 1; +matlabbatch{1}.spm.tools.cat.tools.calcroi.point = ','; +matlabbatch{1}.spm.tools.cat.tools.calcroi.outdir = outdir; +matlabbatch{1}.spm.tools.cat.tools.calcroi.calcroi_name = 'SBMatlases'; + +","MATLAB" +"Neurology","ChristianGaser/cat12","batches/cattest/cat12_303_SBM_MapVol2IndSurf.m",".m","5253","82","% --------------------------------------------------------------------- +% Test batch for volume to surface mapping of cat_tst_cattest. +% --------------------------------------------------------------------- +% Robert Dahnke +% $Id$ + +% prepare filename +% ---------------------------------------------------------------------- +if exist('files','var') + vols = files; + surfs = files; + for fi = 1:numel(files) + [pp,ff] = spm_fileparts(files{fi}); + if exp + vols{fi,1} = fullfile( pp , mridir , ['m' ff '.nii'] ); + else + vols{fi,1} = fullfile( pp , [ff '.nii'] ); % no m*.nii user original + end + surfs{fi,1} = fullfile( pp , surfdir , ['lh.central.' ff '.gii'] ); + end +else + vols = {''}; + surfs = {''}; + exp = cat_get_defaults('extopts.expertgui'); +end + +% batch +% ---------------------------------------------------------------------- + +% cat default value - 3 average points in the GM (CSF/GM - GM - GM/WM) +matlabbatch{1}.spm.tools.cat.stools.vol2surf.data_vol = vols; +matlabbatch{1}.spm.tools.cat.stools.vol2surf.data_mesh_lh = surfs; +matlabbatch{1}.spm.tools.cat.stools.vol2surf.sample = {'avg'}; +if exp, matlabbatch{1}.spm.tools.cat.stools.vol2surf.interp = {'linear'}; end +matlabbatch{1}.spm.tools.cat.stools.vol2surf.datafieldname = 'GM-T1-intensity'; +matlabbatch{1}.spm.tools.cat.stools.vol2surf.mapping.rel_mapping.class = 'GM'; +matlabbatch{1}.spm.tools.cat.stools.vol2surf.mapping.rel_mapping.startpoint = 0; +matlabbatch{1}.spm.tools.cat.stools.vol2surf.mapping.rel_mapping.stepsize = 0.5; +matlabbatch{1}.spm.tools.cat.stools.vol2surf.mapping.rel_mapping.endpoint = 1; + +% L1 intensity of equal distance layer +matlabbatch{2}.spm.tools.cat.stools.vol2surf.data_vol = vols; +matlabbatch{2}.spm.tools.cat.stools.vol2surf.data_mesh_lh = surfs; +matlabbatch{2}.spm.tools.cat.stools.vol2surf.sample = {'avg'}; +if exp, matlabbatch{2}.spm.tools.cat.stools.vol2surf.interp = {'linear'}; end +matlabbatch{2}.spm.tools.cat.stools.vol2surf.datafieldname = 'EquiDist-Layer0-Intensity'; +matlabbatch{2}.spm.tools.cat.stools.vol2surf.mapping.rel_mapping.class = 'GM'; +matlabbatch{2}.spm.tools.cat.stools.vol2surf.mapping.rel_mapping.startpoint = 1/13; +matlabbatch{2}.spm.tools.cat.stools.vol2surf.mapping.rel_mapping.stepsize = 0; +matlabbatch{2}.spm.tools.cat.stools.vol2surf.mapping.rel_mapping.endpoint = 0; +% L4 intensity of equal distance layer +matlabbatch{3}.spm.tools.cat.stools.vol2surf.data_vol = vols; +matlabbatch{3}.spm.tools.cat.stools.vol2surf.data_mesh_lh = surfs; +matlabbatch{3}.spm.tools.cat.stools.vol2surf.sample = {'avg'}; +if exp, matlabbatch{3}.spm.tools.cat.stools.vol2surf.interp = {'linear'}; end +matlabbatch{3}.spm.tools.cat.stools.vol2surf.datafieldname = 'EquiDist-Layer4-Intensity'; +matlabbatch{3}.spm.tools.cat.stools.vol2surf.mapping.rel_mapping.class = 'GM'; +matlabbatch{3}.spm.tools.cat.stools.vol2surf.mapping.rel_mapping.startpoint = 7/13; +matlabbatch{3}.spm.tools.cat.stools.vol2surf.mapping.rel_mapping.stepsize = 0; +matlabbatch{3}.spm.tools.cat.stools.vol2surf.mapping.rel_mapping.endpoint = 0; +% L6 intensity of equal distance layer +matlabbatch{4}.spm.tools.cat.stools.vol2surf.data_vol = vols; +matlabbatch{4}.spm.tools.cat.stools.vol2surf.data_mesh_lh = surfs; +matlabbatch{4}.spm.tools.cat.stools.vol2surf.sample = {'avg'}; +if exp, matlabbatch{4}.spm.tools.cat.stools.vol2surf.interp = {'linear'}; end +matlabbatch{4}.spm.tools.cat.stools.vol2surf.datafieldname = 'EquiDist-Layer6-Intensity'; +matlabbatch{4}.spm.tools.cat.stools.vol2surf.mapping.rel_mapping.class = 'GM'; +matlabbatch{4}.spm.tools.cat.stools.vol2surf.mapping.rel_mapping.startpoint = 12/13; +matlabbatch{4}.spm.tools.cat.stools.vol2surf.mapping.rel_mapping.stepsize = 0; +matlabbatch{4}.spm.tools.cat.stools.vol2surf.mapping.rel_mapping.endpoint = 0; + +% WM value at 1.5 times of the local thickness (half thickness into the WM) +matlabbatch{5}.spm.tools.cat.stools.vol2surf.data_vol = vols; +matlabbatch{5}.spm.tools.cat.stools.vol2surf.data_mesh_lh = surfs; +matlabbatch{5}.spm.tools.cat.stools.vol2surf.sample = {'avg'}; +if exp, matlabbatch{5}.spm.tools.cat.stools.vol2surf.interp = {'linear'}; end +matlabbatch{5}.spm.tools.cat.stools.vol2surf.datafieldname = 'WM-Intensity-at150percentCT'; +matlabbatch{5}.spm.tools.cat.stools.vol2surf.mapping.rel_mapping.class = 'GM'; +matlabbatch{5}.spm.tools.cat.stools.vol2surf.mapping.rel_mapping.startpoint = 1.5; +matlabbatch{5}.spm.tools.cat.stools.vol2surf.mapping.rel_mapping.stepsize = 0; +matlabbatch{5}.spm.tools.cat.stools.vol2surf.mapping.rel_mapping.endpoint = 0; +","MATLAB" +"Neurology","ChristianGaser/cat12","batches/cattest/cat12_105_MAIN_segment_1173plus.m",".m","9037","135","% --------------------------------------------------------------------- +% Test batch ""Segment Data"" for VBM, SBM, and RBM preprocessing of +% cat_tst_cat.est. +% --------------------------------------------------------------------- +% Robert Dahnke +% $Id$ + +if ~exist('files_human1173plus','var') + files_human1173plus = {''}; + exp = cat_get_defaults1173plus('extopts1173plus.expertgui'); +elseif isempty(files_human1173plus) + return; +end + + +% batch +% -- opts -------------------------------------------------------------- +matlabbatch{1}.spm.tools.cat.estwrite1173plus.data = files_human1173plus; +matlabbatch{1}.spm.tools.cat.estwrite1173plus.nproc = 0; +matlabbatch{1}.spm.tools.cat.estwrite1173plus.opts.tpm = { fullfile( spm('dir') , 'tpm' , 'TPM.nii' ) }; +matlabbatch{1}.spm.tools.cat.estwrite1173plus.opts.affreg = 'mni'; +matlabbatch{1}.spm.tools.cat.estwrite1173plus.opts.biasstr = 0.5; +if exp>0 % EXPERT + matlabbatch{1}.spm.tools.cat.estwrite1173plus.opts.ngaus = [1 1 2 3 4 2]; + matlabbatch{1}.spm.tools.cat.estwrite1173plus.opts.biasreg = 0.001; + matlabbatch{1}.spm.tools.cat.estwrite1173plus.opts.biasfwhm = 60; + matlabbatch{1}.spm.tools.cat.estwrite1173plus.opts.warpreg = [0 0.001 0.5 0.05 0.2]; + matlabbatch{1}.spm.tools.cat.estwrite1173plus.opts.samp = 3; +end +% -- extopts ----------------------------------------------------------- +% registration +matlabbatch{1}.spm.tools.cat.estwrite1173plus.extopts.registration.darteltpm = ... + { fullfile( spm('dir') , 'toolbox' , 'cat12' , 'templates_volumes' , 'Template_1_IXI555_MNI152.nii' ) }; +matlabbatch{1}.spm.tools.cat.estwrite1173plus.extopts.registration.shootingtpm = ... + { fullfile( spm('dir') , 'toolbox' , 'cat12' , 'templates_volumes' , 'Template_0_IXI555_MNI152_GS.nii' ) }; +matlabbatch{1}.spm.tools.cat.estwrite1173plus.extopts.registration.regstr = 0; matlabbatch{1}.spm.tools.cat.estwrite1173plus.extopts.vox = 1.5; +if exp==0 + matlabbatch{1}.spm.tools.cat.estwrite1173plus.extopts.APP = 1070; + matlabbatch{1}.spm.tools.cat.estwrite1173plus.extopts.LASstr = 0.5; + matlabbatch{1}.spm.tools.cat.estwrite1173plus.extopts.gcutstr = 2; + matlabbatch{1}.spm.tools.cat.estwrite1173plus.extopts.restypes.fixed = [1 0.1]; % use 2 mm for faster default pp +elseif exp>0 % EXPERT + % segmentation + matlabbatch{1}.spm.tools.cat.estwrite1173plus.extopts.segmentation.APP = 1070; + matlabbatch{1}.spm.tools.cat.estwrite1173plus.extopts.segmentation.LASstr = 0.5; + matlabbatch{1}.spm.tools.cat.estwrite1173plus.extopts.segmentation.gcutstr = 2; + matlabbatch{1}.spm.tools.cat.estwrite1173plus.extopts.segmentation.regstr = 0; + matlabbatch{1}.spm.tools.cat.estwrite1173plus.extopts.segmentation.cleanupstr = 0.5; + matlabbatch{1}.spm.tools.cat.estwrite1173plus.extopts.segmentation.NCstr = -Inf; % noise filter strength + matlabbatch{1}.spm.tools.cat.estwrite1173plus.extopts.segmentation.WMHCstr = 0.5; + matlabbatch{1}.spm.tools.cat.estwrite1173plus.extopts.segmentation.WMHC = 1; + matlabbatch{1}.spm.tools.cat.estwrite1173plus.extopts.segmentation.restypes.fixed = [1 0.1]; % use 2 mm for faster default pp + % surfaces + matlabbatch{1}.spm.tools.cat.estwrite1173plus.extopts.surface.pbtres = 0.5; + matlabbatch{1}.spm.tools.cat.estwrite1173plus.extopts.surface.scale_cortex = 0.7; + matlabbatch{1}.spm.tools.cat.estwrite1173plus.extopts.surface.add_parahipp = 0.1; + matlabbatch{1}.spm.tools.cat.estwrite1173plus.extopts.surface.close_parahipp = 0; + % admin + matlabbatch{1}.spm.tools.cat.estwrite1173plus.extopts.admin.experimental = 0; + matlabbatch{1}.spm.tools.cat.estwrite1173plus.extopts.admin.ignoreErrors = 0; + matlabbatch{1}.spm.tools.cat.estwrite1173plus.extopts.admin.verb = 2; + matlabbatch{1}.spm.tools.cat.estwrite1173plus.extopts.admin.print = 2; +end +if exp>1 % DEVELOPER + matlabbatch{1}.spm.tools.cat.estwrite1173plus.extopts.segmentation.BVCstr = 0; + matlabbatch{1}.spm.tools.cat.estwrite1173plus.extopts.registration.cat12atlas = { fullfile( spm('dir') , 'toolbox' , 'cat12' , 'templates_volumes' , 'cat.nii' ) }; + matlabbatch{1}.spm.tools.cat.estwrite1173plus.extopts.registration.brainmask = { fullfile( spm('dir') , 'toolbox' , 'FieldMap' , 'brainmask.nii' ) }; + matlabbatch{1}.spm.tools.cat.estwrite1173plus.extopts.registration.T1 = { fullfile( spm('dir') , 'toolbox' , 'FieldMap' , 'T1.nii' ) }; +% matlabbatch{1}.spm.tools.cat.estwrite1173plus.extopts.mrf = 1; + matlabbatch{1}.spm.tools.cat.estwrite1173plus.extopts.admin.lazy = 0; +end +% -- output ------------------------------------------------------------ +% surfaces +matlabbatch{1}.spm.tools.cat.estwrite1173plus.output.surface = 1; % SBM preprocessing +% ROIs +matlabbatch{1}.spm.tools.cat.estwrite1173plus.output.ROImenu.atlases.neuromorphometrics = 1; +matlabbatch{1}.spm.tools.cat.estwrite1173plus.output.ROImenu.atlases.lpba40 = 0; +matlabbatch{1}.spm.tools.cat.estwrite1173plus.output.ROImenu.atlases.cobra = 1; +matlabbatch{1}.spm.tools.cat.estwrite1173plus.output.ROImenu.atlases.hammers = 0; +if exp + matlabbatch{1}.spm.tools.cat.estwrite1173plus.output.ROImenu.atlases.ibsr = 0; + matlabbatch{1}.spm.tools.cat.estwrite1173plus.output.ROImenu.atlases.aal3 = 0; + matlabbatch{1}.spm.tools.cat.estwrite1173plus.output.ROImenu.atlases.mori = 0; + matlabbatch{1}.spm.tools.cat.estwrite1173plus.output.ROImenu.atlases.anatomy = 0; +end +% GM +matlabbatch{1}.spm.tools.cat.estwrite1173plus.output.GM.native = 1; +if exp>0, matlabbatch{1}.spm.tools.cat.estwrite1173plus.output.GM.warped = 1; end +matlabbatch{1}.spm.tools.cat.estwrite1173plus.output.GM.mod = 1; +matlabbatch{1}.spm.tools.cat.estwrite1173plus.output.GM.dartel = 1; +% WM +matlabbatch{1}.spm.tools.cat.estwrite1173plus.output.WM.native = 1; +if exp>0, matlabbatch{1}.spm.tools.cat.estwrite1173plus.output.WM.warped = 1; end +matlabbatch{1}.spm.tools.cat.estwrite1173plus.output.WM.mod = 1; +matlabbatch{1}.spm.tools.cat.estwrite1173plus.output.WM.dartel = 1; +% CSF +if exp>0 % EXPERT + matlabbatch{1}.spm.tools.cat.estwrite1173plus.output.CSF.native = 1; + matlabbatch{1}.spm.tools.cat.estwrite1173plus.output.CSF.warped = 0; + matlabbatch{1}.spm.tools.cat.estwrite1173plus.output.CSF.mod = 0; + matlabbatch{1}.spm.tools.cat.estwrite1173plus.output.CSF.dartel = 0; + % WMH (for WMHC>0) + matlabbatch{1}.spm.tools.cat.estwrite1173plus.output.WMH.native = 1; + matlabbatch{1}.spm.tools.cat.estwrite1173plus.output.WMH.warped = 0; + matlabbatch{1}.spm.tools.cat.estwrite1173plus.output.WMH.mod = 0; + matlabbatch{1}.spm.tools.cat.estwrite1173plus.output.WMH.dartel = 0; + % label map + matlabbatch{1}.spm.tools.cat.estwrite1173plus.output.label.native = 1; + matlabbatch{1}.spm.tools.cat.estwrite1173plus.output.label.warped = 1; + matlabbatch{1}.spm.tools.cat.estwrite1173plus.output.label.dartel = 1; + % global intensity normalized + matlabbatch{1}.spm.tools.cat.estwrite1173plus.output.bias.native = 1; + matlabbatch{1}.spm.tools.cat.estwrite1173plus.output.bias.warped = 1; + matlabbatch{1}.spm.tools.cat.estwrite1173plus.output.bias.dartel = 1; + % local intensity normalized + matlabbatch{1}.spm.tools.cat.estwrite1173plus.output.las.native = 1; + matlabbatch{1}.spm.tools.cat.estwrite1173plus.output.las.warped = 1; + matlabbatch{1}.spm.tools.cat.estwrite1173plus.output.las.dartel = 1; +end +if exp>1 % DEVELOPER + % TPMC (for TPM creation, e.g., to create an animal template) + matlabbatch{1}.spm.tools.cat.estwrite1173plus.output.TPMC.native = 1; + matlabbatch{1}.spm.tools.cat.estwrite1173plus.output.TPMC.warped = 0; + matlabbatch{1}.spm.tools.cat.estwrite1173plus.output.TPMC.mod = 0; + matlabbatch{1}.spm.tools.cat.estwrite1173plus.output.TPMC.dartel = 0; + % atlas maps (for atlas creation, e.g., in an animal tempate) + matlabbatch{1}.spm.tools.cat.estwrite1173plus.output.atlas.native = 1; + matlabbatch{1}.spm.tools.cat.estwrite1173plus.output.atlas.warped = 0; + matlabbatch{1}.spm.tools.cat.estwrite1173plus.output.atlas.dartel = 0; +end +% jacobian +matlabbatch{1}.spm.tools.cat.estwrite1173plus.output.jacobianwarped = 1; +% deformation +matlabbatch{1}.spm.tools.cat.estwrite1173plus.output.warps = [1 1]; +","MATLAB" +"Neurology","ChristianGaser/cat12","batches/cattest/cat12_305_SBM_SurfCalc.m",".m","1614","46","% --------------------------------------------------------------------- +% Test batch for surfcalc of cat_tst_cattest. +% --------------------------------------------------------------------- +% Robert Dahnke +% $Id$ + +%#ok<*SAGROW> + +% prepare filename +% --------------------------------------------------------------------- +if exist('files','var') + cdata = {}; + for fi = 1:numel(files) + [pp,ff] = spm_fileparts(files{fi}); + cdata{end+1,1} = fullfile( pp , surfdir , ['lh.thickness.' ff] ); + cdata{end+1,1} = fullfile( pp , surfdir , ['rh.thickness.' ff] ); + cdata{end+1,1} = fullfile( pp , surfdir , ['lh.gyrification.' ff] ); + cdata{end+1,1} = fullfile( pp , surfdir , ['rh.gyrification.' ff] ); + end +else + cdata = {''}; +end + +multisubject = {''}; + +% batch +% --------------------------------------------------------------------- +% combine data - +matlabbatch{1}.spm.tools.cat.stools.surfcalc.cdata = cdata; +matlabbatch{1}.spm.tools.cat.stools.surfcalc.dataname = 'output'; +matlabbatch{1}.spm.tools.cat.stools.surfcalc.outdir = {''}; +matlabbatch{1}.spm.tools.cat.stools.surfcalc.expression = 's1'; +matlabbatch{1}.spm.tools.cat.stools.surfcalc.dmtx = 0; + +% for multiple subjects ... sqrt +%{ +matlabbatch{1}.spm.tools.cat.stools.surfcalcsub.cdata = multisubject; +matlabbatch{1}.spm.tools.cat.stools.surfcalcsub.dataname = 'output'; +matlabbatch{1}.spm.tools.cat.stools.surfcalcsub.outdir = {''}; +matlabbatch{1}.spm.tools.cat.stools.surfcalcsub.expression = 'sqrt(s1)'; +matlabbatch{1}.spm.tools.cat.stools.surfcalcsub.dmtx = 0; +%} + + + +","MATLAB" +"Neurology","ChristianGaser/cat12","batches/cattest/cat12_304_SBM_ResampAndSmooth.m",".m","1180","32","% --------------------------------------------------------------------- +% Test batch for surface data resampling and smoothing of cat_tst_cattest. +% --------------------------------------------------------------------- +% Robert Dahnke +% $Id$ + +%#ok<*SAGROW> + +% prepare filename +% --------------------------------------------------------------------- +if exist('files','var') + cdata = {}; + for fi = 1:numel(files) + [pp,ff] = spm_fileparts(files{fi}); + cdata{end+1,1} = fullfile( pp , surfdir , ['lh.thickness.' ff] ); + cdata{end+1,1} = fullfile( pp , surfdir , ['rh.thickness.' ff] ); + cdata{end+1,1} = fullfile( pp , surfdir , ['lh.gyrification.' ff] ); + cdata{end+1,1} = fullfile( pp , surfdir , ['rh.gyrification.' ff] ); + end +else + cdata = {''}; + exp = cat_get_defaults('extopts.expertgui'); +end + +% batch +% --------------------------------------------------------------------- +matlabbatch{1}.spm.tools.cat.stools.surfresamp.data_surf = cdata; +matlabbatch{1}.spm.tools.cat.stools.surfresamp.fwhm = 15; +matlabbatch{1}.spm.tools.cat.stools.surfresamp.nproc = 0; +if exp + matlabbatch{1}.spm.tools.cat.stools.surfresamp.lazy = 0; +end","MATLAB" +"Neurology","ChristianGaser/cat12","batches/cattest/cat12_301_SBM_extractAddSurfPara.m",".m","1884","39","% --------------------------------------------------------------------- +% Test batch for surface measures of cat_tst_cattest. +% --------------------------------------------------------------------- +% Robert Dahnke +% $Id$ + +%#ok<*SAGROW> + +% prepare filename +% ---------------------------------------------------------------------- +if exist('files','var') + for fi = 1:numel(files) + [pp,ff] = spm_fileparts(files{fi}); + surfs{fi*2-1,1} = fullfile( pp , surfdir , ['lh.central.' ff '.gii'] ); + surfs{fi*2 ,1} = fullfile( pp , surfdir , ['rh.central.' ff '.gii'] ); + end +else + surfs = {''}; + exp = cat_get_defaults('extopts.expertgui'); +end + +% batch +% ---------------------------------------------------------------------- +matlabbatch{1}.spm.tools.cat.stools.surfextract.data_surf = surfs; % required the lh and rh surface! +matlabbatch{1}.spm.tools.cat.stools.surfextract.GI = 1; % abs mean curvature +matlabbatch{1}.spm.tools.cat.stools.surfextract.FD = 1; % fractal dimention +matlabbatch{1}.spm.tools.cat.stools.surfextract.SD = 1; % sulcal depth +matlabbatch{1}.spm.tools.cat.stools.surfextract.nproc = 0; % multi processes (not for this script) +% expert options that are still in development +if exp==2 % DEVELOPER + matlabbatch{1}.spm.tools.cat.stools.surfextract.area = 1; % EXPERT + matlabbatch{1}.spm.tools.cat.stools.surfextract.GIA = 0; % EXPERT + matlabbatch{1}.spm.tools.cat.stools.surfextract.GII = 0; % EXPERT + matlabbatch{1}.spm.tools.cat.stools.surfextract.GIL = 1; % EXPERT laplacican GI + matlabbatch{1}.spm.tools.cat.stools.surfextract.GIS = 0; % EXPERT sperical GI + matlabbatch{1}.spm.tools.cat.stools.surfextract.IS = 1; % EXPERT + matlabbatch{1}.spm.tools.cat.stools.surfextract.OS = 1; % EXPERT + matlabbatch{1}.spm.tools.cat.stools.surfextract.lazy = 0; % EXPERT +end","MATLAB" +"Neurology","ChristianGaser/cat12","batches/cattest/cat12_201_VBM_deformation.m",".m","10157","220","%----------------------------------------------------------------------- +% Job saved on 01-Nov-2016 17:42:45 by cfg_util (rev $Rev$) +% spm SPM - SPM12 (6685) +% cfg_basicio BasicIO - Unknown +%----------------------------------------------------------------------- +% - dartel vs. shooting +% - modulated vs. unmodulated +% - spm def vs. cat def tools +% - interpolation (default and altas case) +% - template resolution +% +% * need copys of all files for CAT that does not allow differt output +% dirs or another prefix + +% prepare filenames +% --------------------------------------------------------------------- + +% template images +PT1 = {fullfile(spm('dir'),'toolbox','cat12','templates_volumes','Template_T1_IXI555_MNI152_GS.nii')}; +PA = {fullfile(spm('dir'),'toolbox','cat12','templates_volumes','neuromorphometrics.nii')}; +% SPM result directory +Dres = {'/Users/dahnke/Neuroimaging/spm12/toolbox/cat12/cattest/CAT12R1054_PCWIN64/mri/'}; + +% individual maps +if exist('files','var') + Pm = cell(numel(files_human),1); + Pmc = cell(numel(files_human),1); + Pms = cell(numel(files_human),1); + + Pp1 = cell(numel(files_human),1); + Pp1c = cell(numel(files_human),1); + Pp1s = cell(numel(files_human),1); + + Py = cell(numel(files_human),1); + Piy = cell(numel(files_human),1); + + Pa = cell(numel(files_human),1); + Pwmc = cell(numel(files_human),1); + Pwp1c = cell(numel(files_human),1); + + for fi = 1:numel(files_human) + [pp,ff] = spm_fileparts(files_human{fi}); + if exp + Pm{fi,1} = fullfile( pp , mridir , ['m' ff '.nii'] ); + Pmc{fi,1} = fullfile( pp , mridir , ['mc' ff '.nii'] ); + Pwmc{fi,1} = fullfile( pp , mridir , ['wmc' ff '.nii'] ); + Pms{fi,1} = fullfile( pp , mridir , ['spmypush_m' ff '.nii'] ); + else + Pm{fi,1} = fullfile( pp , [ ff '.nii'] ); + Pmc{fi,1} = fullfile( pp , mridir , ['c' ff '.nii'] ); + Pwmc{fi,1} = fullfile( pp , mridir , ['wc' ff '.nii'] ); + Pms{fi,1} = fullfile( pp , mridir , ['spmypush_' ff '.nii'] ); + end + Pp1{fi,1} = fullfile( pp , mridir , ['p1' ff '.nii'] ); + Pp1c{fi,1} = fullfile( pp , mridir , ['p1c' ff '.nii'] ); + Pp1s{fi,1} = fullfile( pp , mridir , ['spmypush_p1' ff '.nii'] ); + + Pwp1c{fi,1} = fullfile( pp , mridir , ['mwp1c' ff '.nii'] ); + + Py{fi,1} = fullfile( pp , mridir , ['y_' ff '.nii'] ); + Piy{fi,1} = fullfile( pp , mridir , ['iy_' ff '.nii'] ); + + [ppa,ffa] = spm_fileparts(PA{1}); + Pa{fi,1} = fullfile( pp , mridir , [ffa '.nii'] ); + end + outdir = {fullfile( pp , mridir )}; +else + Pm = {''}; + Pmc = {''}; + Pwmc = {''}; + + Pp1 = {''}; + Pp1c = {''}; + Pwp1c = {''}; + + Py = {''}; + Piy = {''}; + + Pa = {''}; + outdir = {''}; % SPM result directory + exp = cat_get_defaults('extopts.expertgui'); +end + + + + + +% batch +% ---------------------------------------------------------------------- + +mix=0; +% ---------------------------------------------------------------------- +% 1. SPM deformation tool +% ---------------------------------------------------------------------- +% 1.1 unmodulated mapping with push and pull +% 1.1.1 individual to template space - PUSH with inverse y +mix=mix+1; +matlabbatch{mix}.spm.util.defs.comp{1}.inv.comp{1}.def = Py; +matlabbatch{mix}.spm.util.defs.comp{1}.inv.space = Pm; +matlabbatch{mix}.spm.util.defs.out{1}.push.fnames = Pm; +matlabbatch{mix}.spm.util.defs.out{1}.push.weight = {''}; +matlabbatch{mix}.spm.util.defs.out{1}.push.savedir.saveusr = outdir; +matlabbatch{mix}.spm.util.defs.out{1}.push.fov.file = PT1; +matlabbatch{mix}.spm.util.defs.out{1}.push.preserve = 0; +matlabbatch{mix}.spm.util.defs.out{1}.push.fwhm = [0 0 0]; +matlabbatch{mix}.spm.util.defs.out{1}.push.prefix = 'spmypush_'; +% 1.2 template to individual space - PULL with inverse y +mix=mix+1; +matlabbatch{mix}.spm.util.defs.comp{1}.inv.comp{1}.def = Py; +matlabbatch{mix}.spm.util.defs.comp{1}.inv.space = Pm; +matlabbatch{mix}.spm.util.defs.out{1}.pull.fnames = Pms; +matlabbatch{mix}.spm.util.defs.out{1}.pull.savedir.saveusr = outdir; +matlabbatch{mix}.spm.util.defs.out{1}.pull.interp = 4; +matlabbatch{mix}.spm.util.defs.out{1}.pull.mask = 1; +matlabbatch{mix}.spm.util.defs.out{1}.pull.fwhm = [0 0 0]; +matlabbatch{mix}.spm.util.defs.out{1}.pull.prefix = 'spmypull_'; +% ---------------------------------------------------------------------- +% 1.2 modulated mapping only with push +% 1.2.1 individual to template space - PUSH with inverse y +mix=mix+1; +matlabbatch{mix}.spm.util.defs.comp{1}.inv.comp{1}.def = Py; +matlabbatch{mix}.spm.util.defs.comp{1}.inv.space = Pp1; +matlabbatch{mix}.spm.util.defs.out{1}.push.fnames = Pp1; +matlabbatch{mix}.spm.util.defs.out{1}.push.weight = {''}; +matlabbatch{mix}.spm.util.defs.out{1}.push.savedir.saveusr = outdir; +matlabbatch{mix}.spm.util.defs.out{1}.push.fov.file = PT1; +matlabbatch{mix}.spm.util.defs.out{1}.push.preserve = 1; +matlabbatch{mix}.spm.util.defs.out{1}.push.fwhm = [0 0 0]; +matlabbatch{mix}.spm.util.defs.out{1}.push.prefix = 'spmypush_'; +% 1.2.2 modulated template to individual space - PULL with inverse y +mix=mix+1; +matlabbatch{mix}.spm.util.defs.comp{1}.def = Py; +matlabbatch{mix}.spm.util.defs.out{1}.push.fnames = Pp1s; +matlabbatch{mix}.spm.util.defs.out{1}.push.weight = {''}; +matlabbatch{mix}.spm.util.defs.out{1}.push.savedir.saveusr = outdir; +matlabbatch{mix}.spm.util.defs.out{1}.push.fov.file = Pp1; +matlabbatch{mix}.spm.util.defs.out{1}.push.preserve = 1; +matlabbatch{mix}.spm.util.defs.out{1}.push.fwhm = [0 0 0]; +matlabbatch{mix}.spm.util.defs.out{1}.push.prefix = 'spmypull_'; +% ---------------------------------------------------------------------- +% 1.3 test of iy_*.nii and comparison of push and pull +% 1.3.1 iy with pull +mix=mix+1; +matlabbatch{mix}.spm.util.defs.comp{1}.inv.comp{1}.def = Piy; +matlabbatch{mix}.spm.util.defs.comp{1}.inv.space = PT1; +matlabbatch{mix}.spm.util.defs.out{1}.pull.fnames = Pm; +matlabbatch{mix}.spm.util.defs.out{1}.pull.savedir.saveusr = outdir; +matlabbatch{mix}.spm.util.defs.out{1}.pull.interp = 4; +matlabbatch{mix}.spm.util.defs.out{1}.pull.mask = 1; +matlabbatch{mix}.spm.util.defs.out{1}.pull.fwhm = [0 0 0]; +matlabbatch{mix}.spm.util.defs.out{1}.pull.prefix = 'spmiypull_'; +% 1.3.2 iy with push +mix=mix+1; +matlabbatch{mix}.spm.util.defs.comp{1}.def = Piy; +matlabbatch{mix}.spm.util.defs.out{1}.push.fnames = Pm; +matlabbatch{mix}.spm.util.defs.out{1}.push.weight = {''}; +matlabbatch{mix}.spm.util.defs.out{1}.push.savedir.saveusr = outdir; +matlabbatch{mix}.spm.util.defs.out{1}.push.fov.file = PT1; +matlabbatch{mix}.spm.util.defs.out{1}.push.preserve = 0; +matlabbatch{mix}.spm.util.defs.out{1}.push.fwhm = [0 0 0]; +matlabbatch{mix}.spm.util.defs.out{1}.push.prefix = 'spmiypush_'; +% ---------------------------------------------------------------------- + +%{ + copyfile(Pm{fi,1} ,Pmc{fi,1} ); + copyfile(Pp1{fi,1} ,Pp1c{fi,1} ); + copyfile(PA{fi,1} ,Pa{fi,1} ); + +matlabbatch{mix}.cfg_basicio.file_dir.file_ops.file_move.files = { Pm(fi,1) }; +matlabbatch{mix}.cfg_basicio.file_dir.file_ops.file_move.action.copyto = { Pmc(fi,1) }; + +matlabbatch{mix}.cfg_basicio.file_dir.file_ops.file_move.files = { Pp1(fi,1) }; +matlabbatch{mix}.cfg_basicio.file_dir.file_ops.file_move.action.copyto = { Pp1c(fi,1) }; + +matlabbatch{mix}.cfg_basicio.file_dir.file_ops.file_move.files = { Pm(fi,1) }; +matlabbatch{mix}.cfg_basicio.file_dir.file_ops.file_move.action.copyto = { Pmc(fi,1) }; +%} + +%{ +% ---------------------------------------------------------------------- +% 2. CAT deformation tool +% ---------------------------------------------------------------------- +% 2.1 individual to template space +% 2.1.1 unmodulated +% deformation of intensity maps for analysis in template space, e.g., of normalized T1 data +% comparison of Ym preprocessing result? +mix=mix+1; +matlabbatch{mix}.spm.tools.cat.tools.defs.field1 = Py; +matlabbatch{mix}.spm.tools.cat.tools.defs.images = Pmc; +matlabbatch{mix}.spm.tools.cat.tools.defs.interp = 5; +matlabbatch{mix}.spm.tools.cat.tools.defs.modulate = 0; +mix=mix+1; +matlabbatch{mix}.spm.tools.cat.tools.defs.field1 = Piy; +matlabbatch{mix}.spm.tools.cat.tools.defs.images = Pwmc; +matlabbatch{mix}.spm.tools.cat.tools.defs.interp = 5; +matlabbatch{mix}.spm.tools.cat.tools.defs.modulate = 0; +% ---------------------------------------------------------------------- +% 2.1.2 modulated +% deformation of tissue maps for analysis in template space, e.g. the GM volume segmentation +% comparison of Yp1 preprocessing result? +mix=mix+1; +matlabbatch{mix}.spm.tools.cat.tools.defs.field1 = Py; +matlabbatch{mix}.spm.tools.cat.tools.defs.images = Pp1c; +matlabbatch{mix}.spm.tools.cat.tools.defs.interp = 5; +matlabbatch{mix}.spm.tools.cat.tools.defs.modulate = 1; +mix=mix+1; +matlabbatch{mix}.spm.tools.cat.tools.defs.field1 = Piy; +matlabbatch{mix}.spm.tools.cat.tools.defs.images = Pwp1c; +matlabbatch{mix}.spm.tools.cat.tools.defs.interp = 5; +matlabbatch{mix}.spm.tools.cat.tools.defs.modulate = 1; +% ---------------------------------------------------------------------- +% 2.2 template to individual space +% 2.2.3 unmodulated nearest interpolation (atlas mapping) +mix=mix+1; +matlabbatch{mix}.spm.tools.cat.tools.defs.field1 = Piy; +matlabbatch{mix}.spm.tools.cat.tools.defs.images = Pa; +matlabbatch{mix}.spm.tools.cat.tools.defs.interp = 0; +matlabbatch{mix}.spm.tools.cat.tools.defs.modulate = 0; +%} +","MATLAB" +"Neurology","ChristianGaser/cat12","internal/cat_io_createXML.m",".m","2930","90","function out = cat_io_createXML(job) + +if 0 + job.data = {}; + job.data = cat_vol_findfiles(fullfile('/Volumes/WDE18TB/MRDataPP/202505_CS4/derivatives/T1PrepAMAPds1','mri'),'p0*.nii.gz'); + job.data = cat_vol_findfiles(fullfile('/Volumes/WDE18TB/MRDataPP/202505_CS4/derivatives/T1Prep','mri'),'p0*.nii.gz'); +end +%% +def.prefix = 'cat_'; +def.rerun = 0; +def.runQC = 0; +job = cat_io_checkinopt(job,def); + +out.data = cat_io_strrep( job.data , ... + { [filesep 'mri' filesep], [filesep 'p0'], '.nii.gz'}, ... + { [filesep 'report' filesep], filesep , '.nii'} ); +out.data = spm_file(out.data,'prefix','cat_','ext','.xml'); + +avols = zeros(numel(job.data),3); rvols = avols; +Pdata = cell(numel(job.data),3); +vx_vol = zeros(numel(job.data),3); +tiv = zeros(numel(job.data),1); +area = zeros(numel(job.data),1); +ar = zeros(numel(job.data),2); +th = zeros(numel(job.data),2); +Psurf = cell(numel(job.data),3); +Pthick = cell(numel(job.data),3); +%% +dn = 0; +for di = 1:numel(job.data) + + % avoid rerun if the file exist + if exist(out.data{di},'file') && ~job.rerun, continue; end + dn = dn + 1; + + %% estimate volumes + if job.runQC + X = cat_vol_qa('p0',job.data(di),struct('prefix',job.prefix)); + else + fprintf('%5d/%5d) %s:\n', di, numel(job.data), job.data{di}); + evalc('V = spm_vol( job.data{di} )'); + Y = spm_read_vols( V ); + Yp0toC = @(Yp0,c) 1-min(1,abs(Yp0-c)); + vx_vol(di,:) = sqrt(sum(V.mat(1:3,1:3).^2)); + for i = 1:3 + avols(di,i) = sum( Yp0toC(Y(:),i) * prod(vx_vol(di,:) )) / 1000; % cm3 + end + tiv(di,1) = sum( avols(di,:) ); + rvols(di,:) = avols(di,:) ./ tiv(di,1); + X.subjectmeasures.vol_abs_CGW = avols(di,:); + X.subjectmeasures.vol_rel_CGW = rvols(di,:); + X.subjectmeasures.vol_TIV = tiv(di); + end + + + %% estimate thickness and area + try + S = cell(1,2); T = S; + side = {'lh','rh'}; + for si = 1:2 + Pdata{di,si} = cat_io_strrep( job.data{di} , ... + {[filesep 'mri' filesep]; [filesep 'p0']; '.nii.gz'}, ... + {[filesep 'surf' filesep]; [filesep '']; '.nii'}); + Psurf{di,si} = spm_file( Pdata{di,si}, 'prefix' , sprintf('%s.central.',side{si}) , 'ext', '.gii' ); + Pthick{di,si} = spm_file( Pdata{di,si}, 'prefix' , sprintf('%s.thickness.',side{si}), 'ext', '' ); + + S{si} = gifti( Psurf{di,si} ); + T{si} = cat_io_FreeSurfer('read_surf_data',Pthick{di,si}); + + ar(di,si) = sum(cat_surf_fun('area',S{si})); + th(di,si) = [cat_stat_nanmean(T{si}(:)) cat_stat_nanstd(T{si}(:))]; + end + area(di,1) = sum( ar(di,:) ); + catch + area(di,1) = nan; + end + X.subjectmeasures.dist_thickness{1} = th(di,si); + X.subjectmeasures.area_TSA = area(di) / 100; % cm3 + X.subjectmeasures.EC_abs = NaN; + X.subjectmeasures.defect_size = NaN; + + % estimate intensity? + + + % save data + cat_io_xml(out.data{di},X); +end +if dn, fprintf('done.\n'); end + +","MATLAB" +"Neurology","ChristianGaser/cat12","internal/MBeautify.m",".m","23061","460","classdef MBeautify + % Provides static methods to perform code formatting targeting file(s), the currently active editor page or the + % current selection in editor. + % The rules of the formatting are defined in the ""MBeautyConfigurationRules.xml"" in the resources directory. This + % file can be modified to affect the formatting. + % Important: Runtime, the M equivalent of this XML file is used, which is created whenever the ""setup"" static + % method is called, therefore always call this method if the XML file has been modified. + % To restore the XML file to the default configuration, the ""createDefaultConfiguration"" static method can be + % called. + % + % Example usage: + % + % MBeautify.setup(); % Creates the default rules + % MBeautify.formatCurrentEditorPage(); % Formats the current page in editor without saving + % MBeautify.formatCurrentEditorPage(); % Formats the current page in editor with saving + % MBeautify.formatFile('D:\testFile.m', 'D:\testFileNew.m'); % Formats the first file into the second file + % MBeautify.formatFile('D:\testFile.m', 'D:\testFile.m'); % Formats the first file in-place + % MBeautify.formatFiles('D:\mydir', '*.m'); % Formats all files in the specified diretory in-place + + properties(Access = private, Constant) + RulesXMLFile = 'MBeautyConfigurationRules.xml'; + RulesMFile = 'MBeautyConfigurationRules.m' + SettingDirectory = [fileparts(mfilename('fullpath')), filesep, 'resources', filesep, 'settings']; + RulesMFileFull = [fileparts(mfilename('fullpath')), filesep, 'resources', filesep, 'settings', filesep, 'MBeautyConfigurationRules.m']; + RulesXMLFileFull = [fileparts(mfilename('fullpath')), filesep, 'resources', filesep, 'settings', filesep, 'MBeautyConfigurationRules.xml']; + end + + %% Public API + + methods(Static = true) + + function setup() + % MBeautify.setup() initializes MBeautifier for first use and usable to update the formatting configuration. + % It optionally writes the default settings XML file, reads in the settings XML file and then writes the + % configuration M-file which will be used in runtime. + + if ~exist(MBeautify.RulesXMLFileFull, 'file') + MBeautify.writeSettingsXML(); + end + + MBeautify.writeConfigurationFile(MBeautify.readSettingsXML()); + + fprintf('Configuration was successfully exported to:\n%s\n', MBeautify.RulesMFileFull); + MBeautify.parsingUpToDate(false); + end + + function createDefaultConfiguration() + % Writes the default configuration XML file. + + MBeautify.writeSettingsXML(); + end + + function formatFile(file, outFile) + % Formats the file specified in the first argument. The file is opened in the Matlab Editor. If the second + % argument is also specified, the formatted source is saved to this file. Otherwise the formatted input + % file remains opened in the Matlab Editor. The input and the output file can be the same. + if ~exist(file, 'file') + return; + end + + document = matlab.desktop.editor.openDocument(file); + % Format the code + formatter = MFormatter(MBeautify.getConfigurationStruct()); + document.Text = formatter.performFormatting(document.Text); + + document.smartIndentContents(); + + if nargin >= 2 + if exist(outFile, 'file') + fileattrib(outFile, '+w'); + end + + document.saveAs(outFile) + document.close(); + end + end + + function formatFiles(directory, fileFilter) + % Formats the files in-place (files are overwritten) in the specified directory, collected by the specified filter. + % The file filter is a wildcard expression used by the dir command. + + files = dir(fullfile(directory, fileFilter)); + + for iF = 1:numel(files) + file = fullfile(directory, files(iF).name); + MBeautify.formatFile(file, file); + end + end + + function formatEditorSelection(doSave) + % Performs formatting on selection of the currently active Matlab Editor page. + % The selection is automatically extended until the first empty line above and below. + % This method can be useful for large files, but using ""formatCurrentEditorPage"" is always suggested. + % Optionally saves the file (if it is possible) and it is forced on the first argument (true). By default + % the file is not saved. + + currentEditorPage = matlab.desktop.editor.getActive(); + + if isempty(currentEditorPage) + return; + end + + currentSelection = currentEditorPage.Selection; + + if isempty(currentEditorPage.SelectedText) + return; + end + + if nargin == 0 + doSave = false; + end + + % Expand the selection from the beginnig of the first line to the end of the last line + expandedSelection = [currentSelection(1), 1, currentSelection(3), Inf]; + + + % Search for the first empty line before the selection + if currentSelection(1) > 1 + lineBeforePosition = [currentSelection(1) - 1, 1, currentSelection(1) - 1, Inf]; + + currentEditorPage.Selection = lineBeforePosition; + lineBeforeText = currentEditorPage.SelectedText; + + while lineBeforePosition(1) > 1 && ~isempty(strtrim(lineBeforeText)) + lineBeforePosition = [lineBeforePosition(1) - 1, 1, lineBeforePosition(1) - 1, Inf]; + currentEditorPage.Selection = lineBeforePosition; + lineBeforeText = currentEditorPage.SelectedText; + end + end + expandedSelection = [lineBeforePosition(1), 1, expandedSelection(3), Inf]; + + % Search for the first empty line after the selection + lineAfterSelection = [currentSelection(3) + 1, 1, currentSelection(3) + 1, Inf]; + currentEditorPage.Selection = lineAfterSelection; + lineAfterText = currentEditorPage.SelectedText; + beforeselect = currentSelection(1); + while ~isequal(lineAfterSelection(1), beforeselect) && ~isempty(strtrim(lineAfterText)) + beforeselect = lineAfterSelection(1); + lineAfterSelection = [lineAfterSelection(1) + 1, 1, lineAfterSelection(1) + 1, Inf]; + currentEditorPage.Selection = lineAfterSelection; + lineAfterText = currentEditorPage.SelectedText; + + end + + endReached = isequal(lineAfterSelection(1), currentSelection(1)); + + expandedSelection = [expandedSelection(1), 1, lineAfterSelection(3), Inf]; + + if isequal(currentSelection(1), 1) + codeBefore = ''; + else + codeBeforeSelection = [1, 1, expandedSelection(1), Inf]; + currentEditorPage.Selection = codeBeforeSelection; + codeBefore = currentEditorPage.SelectedText; + end + + if endReached + codeAfter = ''; + else + codeAfterSelection = [expandedSelection(3) + 1, 1, Inf, Inf]; + currentEditorPage.Selection = codeAfterSelection; + codeAfter = currentEditorPage.SelectedText; + + end + + currentEditorPage.Selection = expandedSelection; + codeToFormat = currentEditorPage.SelectedText; + selectedPosition = currentEditorPage.Selection; + + % Format the code + formatter = MFormatter(MBeautify.getConfigurationStruct()); + formattedSource = formatter.performFormatting(codeToFormat); + + % Save back the modified data then use Matlab samrt indent functionality + % Set back the selection + currentEditorPage.Text = [codeBefore, formattedSource, codeAfter]; + if ~isempty(selectedPosition) + currentEditorPage.goToLine(selectedPosition(1)); + end + currentEditorPage.smartIndentContents(); + currentEditorPage.makeActive(); + + % Save if it is possible + if doSave + fileName = currentEditorPage.Filename; + if exist(fileName, 'file') && numel(fileparts(fileName)) + fileattrib(fileName, '+w'); + currentEditorPage.saveAs(currentEditorPage.Filename) + end + end + end + + function formatCurrentEditorPage(doSave) + % Performs formatting on the currently active Matlab Editor page. + % Optionally saves the file (if it is possible) and it is forced on the first argument (true). By default + % the file is not saved. + + currentEditorPage = matlab.desktop.editor.getActive(); + if isempty(currentEditorPage) + return; + end + + if nargin == 0 + doSave = false; + end + + selectedPosition = currentEditorPage.Selection; + + % Format the code + formatter = MFormatter(MBeautify.getConfigurationStruct()); + currentEditorPage.Text = formatter.performFormatting(currentEditorPage.Text); + + % Set back the selection + if ~isempty(selectedPosition) + currentEditorPage.goToLine(selectedPosition(1)); + end + % Use Smart Indent + currentEditorPage.smartIndentContents(); + currentEditorPage.makeActive(); + + % Save if it is possible + if doSave + fileName = currentEditorPage.Filename; + if exist(fileName, 'file') && numel(fileparts(fileName)) + fileattrib(fileName, '+w'); + currentEditorPage.saveAs(currentEditorPage.Filename) + end + end + end + + end + + %% Private helpers + + methods(Static = true, Access = private) + + % Method to mimic a static data member + % Indicates that the token parsing is up to date or the rules file should be reparsed + function val = parsingUpToDate(val) + persistent currentval; + if isempty(currentval) + currentval = true; + end + if nargin >= 1 + currentval = val; + end + + val = currentval; + end + + function configurationStruct = getConfigurationStruct() + % MBeautify.getConfigurationStruct returns the configuration struct from the rules file + + % Persistent variable to store the returned rules + % If MBeautify.setup was not called, the stored struct should be returned + persistent configurationStructStored; + + if isempty(configurationStructStored) || ~MBeautify.parsingUpToDate() + currCD = cd(); + cd(MBeautify.SettingDirectory); + configurationStruct = eval(MBeautify.RulesMFile(1:end - 2)); + cd(currCD) + configurationStructStored = configurationStruct; + MBeautify.parsingUpToDate(true); + else + configurationStruct = configurationStructStored; + end + + end + + + function writeConfigurationFile(resStruct) + % MBeautify.writeConfigurationFile creates the configuration M file from the structure of the configuration XML file. + + operetorRules = resStruct.OperatorRules; + opFields = fields(operetorRules); + + [pathOfMFile, nameOfMFile] = fileparts(MBeautify.RulesMFileFull); %#ok + + settingMFileString = ['function this = ', nameOfMFile, '()', sprintf('\n'), ... + 'this = struct();', sprintf('\n'), sprintf('\n')]; + + settingMFileString = [settingMFileString, 'this.OperatorRules = struct();', sprintf('\n'), sprintf('\n')]; + + for iOp = 1:numel(opFields) + + settingMFileString = [settingMFileString, sprintf('\n')]; + settingMFileString = [settingMFileString, ['this.OperatorRules.', opFields{iOp}, ' = struct();'], sprintf('\n')]; + + valueFrom = regexptranslate('escape', operetorRules.(opFields{iOp}).ValueFrom); + valueTo = regexptranslate('escape', operetorRules.(opFields{iOp}).ValueTo); + + settingMFileString = [settingMFileString, ['this.OperatorRules.', opFields{iOp}, '.ValueFrom = ''', valueFrom, ''';'], sprintf('\n')]; + settingMFileString = [settingMFileString, ['this.OperatorRules.', opFields{iOp}, '.ValueTo = ''', valueTo, ''';'], sprintf('\n')]; + end + + + settingMFileString = [settingMFileString, 'this.SpecialRules = struct();', sprintf('\n'), sprintf('\n')]; + + specialRules = resStruct.SpecialRules; + spFields = fields(specialRules); + + for iSp = 1:numel(spFields) + settingMFileString = [settingMFileString, sprintf('\n')]; %#ok<*AGROW> + settingMFileString = [settingMFileString, ['this.SpecialRules.', spFields{iSp}, ' = struct();'], sprintf('\n')]; + settingMFileString = [settingMFileString, ['this.SpecialRules.', spFields{iSp}, 'Value = ''', specialRules.(spFields{iSp}).Value, ''';'], sprintf('\n')]; + end + + settingMFileString = [settingMFileString, 'end']; + + if exist(MBeautify.RulesMFileFull, 'file') + fileattrib(MBeautify.RulesMFileFull, '+w'); + end + fid = fopen(MBeautify.RulesMFileFull, 'w'); + fwrite(fid, settingMFileString); + fclose(fid); + + end + + + %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + % Writes the default settings XML file + function writeSettingsXML() + % MBeautify.writeSettingsXML creates the default configuration XML structure to the configuration XML file. + + docNode = com.mathworks.xml.XMLUtils.createDocument('MBeautifyRuleConfiguration'); + docRootNode = docNode.getDocumentElement(); + + operatorPaddings = docNode.createElement('OperatorPadding'); + docRootNode.appendChild(operatorPaddings); + + specialRules = docNode.createElement('SpecialRules'); + docRootNode.appendChild(specialRules); + + %% Add operator rules + operatorPaddings = appendOperatorPaddingRule('ShortCircuitAnd', '&&', ' && ', operatorPaddings, docNode); + operatorPaddings = appendOperatorPaddingRule('ShortCircuitOr', '||', ' || ', operatorPaddings, docNode); + operatorPaddings = appendOperatorPaddingRule('LogicalAnd', '&', ' & ', operatorPaddings, docNode); + operatorPaddings = appendOperatorPaddingRule('LogicalOr', '|', ' | ', operatorPaddings, docNode); + operatorPaddings = appendOperatorPaddingRule('LessEquals', '<=', ' <= ', operatorPaddings, docNode); + operatorPaddings = appendOperatorPaddingRule('Less', '<', ' < ', operatorPaddings, docNode); + operatorPaddings = appendOperatorPaddingRule('GreaterEquals', '>=', ' >= ', operatorPaddings, docNode); + operatorPaddings = appendOperatorPaddingRule('Greater', '>', ' > ', operatorPaddings, docNode); + operatorPaddings = appendOperatorPaddingRule('Equals', '==', ' == ', operatorPaddings, docNode); + operatorPaddings = appendOperatorPaddingRule('NotEquals', '~=', ' ~= ', operatorPaddings, docNode); + operatorPaddings = appendOperatorPaddingRule('Assignment', '=', ' = ', operatorPaddings, docNode); + operatorPaddings = appendOperatorPaddingRule('Plus', '+', ' + ', operatorPaddings, docNode); + operatorPaddings = appendOperatorPaddingRule('Minus', '-', ' - ', operatorPaddings, docNode); + operatorPaddings = appendOperatorPaddingRule('ElementWiseMultiplication', '.*', ' .* ', operatorPaddings, docNode); + operatorPaddings = appendOperatorPaddingRule('Multiplication', '*', ' * ', operatorPaddings, docNode); + operatorPaddings = appendOperatorPaddingRule('RightArrayDivision', './', ' ./ ', operatorPaddings, docNode); + operatorPaddings = appendOperatorPaddingRule('LeftArrayDivision', '.\', ' .\ ', operatorPaddings, docNode); + operatorPaddings = appendOperatorPaddingRule('Division', '/', ' / ', operatorPaddings, docNode); + operatorPaddings = appendOperatorPaddingRule('LeftDivision', '\', ' \ ', operatorPaddings, docNode); + operatorPaddings = appendOperatorPaddingRule('ElementWisePower', '.^', '.^', operatorPaddings, docNode); + operatorPaddings = appendOperatorPaddingRule('Power', '^', '^', operatorPaddings, docNode); + operatorPaddings = appendOperatorPaddingRule('Not', '~', ' ~', operatorPaddings, docNode); + operatorPaddings = appendOperatorPaddingRule('Comma', ',', ', ', operatorPaddings, docNode); + operatorPaddings = appendOperatorPaddingRule('SemiColon', ';', '; ', operatorPaddings, docNode); + appendOperatorPaddingRule('Colon', ':', ':', operatorPaddings, docNode); + + %% Add special rules + specialRules = appendSpecialRule('MaximalNewLines', '2', specialRules, docNode); + specialRules = appendSpecialRule('AddCommasToMatrices', '1', specialRules, docNode); + specialRules = appendSpecialRule('AddCommasToCellArrays', '1', specialRules, docNode); + specialRules = appendSpecialRule('CellArrayIndexing_ArithmeticOperatorPadding', '0', specialRules, docNode); + appendSpecialRule('MatrixIndexing_ArithmeticOperatorPadding', '0', specialRules, docNode); + + xmlwrite(MBeautify.RulesXMLFileFull, docNode); + + fprintf('Default configuration XML has been created:\n%s\n', MBeautify.RulesXMLFileFull); + + + function operatorPaddings = appendOperatorPaddingRule(key, valueFrom, valueTo, operatorPaddings, docNode) + opPaddingRule = docNode.createElement('OperatorPaddingRule'); + + keyElement = docNode.createElement('Key'); + keyElement.appendChild(docNode.createTextNode(key)); + + valueFromElement = docNode.createElement('ValueFrom'); + valueFromElement.appendChild(docNode.createTextNode(valueFrom)); + + valueToElement = docNode.createElement('ValueTo'); + valueToElement.appendChild(docNode.createTextNode(valueTo)); + + opPaddingRule.appendChild(keyElement); + opPaddingRule.appendChild(valueFromElement); + opPaddingRule.appendChild(valueToElement); + + operatorPaddings.appendChild(opPaddingRule); + + end + + function specialRules = appendSpecialRule(key, value, specialRules, docNode) + specialRule = docNode.createElement('SpecialRule'); + + keyElement = docNode.createElement('Key'); + keyElement.appendChild(docNode.createTextNode(key)); + + valueElement = docNode.createElement('Value'); + valueElement.appendChild(docNode.createTextNode(value)); + + specialRule.appendChild(keyElement); + specialRule.appendChild(valueElement); + + specialRules.appendChild(specialRule); + + end + + end + + % Reads the settings XML file to a structure + function settingsStruct = readSettingsXML() + % MBeautify.readSettingsXML reads the configuration XML file to a structure. + + settingsStruct = struct('OperatorRules', struct(), 'SpecialRules', struct()); + + XMLDoc = xmlread(MBeautify.RulesXMLFileFull); + + allOperatorItems = XMLDoc.getElementsByTagName('OperatorPaddingRule'); + operatorNode = settingsStruct.OperatorRules; + + for iOperator = 0:allOperatorItems.getLength() -1 + + currentOperator = allOperatorItems.item(iOperator); + + key = char(currentOperator.getElementsByTagName('Key').item(0).getTextContent().toString()); + operatorNode.(key) = struct(); + operatorNode.(key).ValueFrom = removeXMLEscaping(char(currentOperator.getElementsByTagName('ValueFrom').item(0).getTextContent().toString())); + operatorNode.(key).ValueTo = removeXMLEscaping(char(currentOperator.getElementsByTagName('ValueTo').item(0).getTextContent().toString())); + end + + settingsStruct.OperatorRules = operatorNode; + + allSpecialItems = XMLDoc.getElementsByTagName('SpecialRule'); + specialRulesNode = settingsStruct.SpecialRules; + + for iSpecRule = 0:allSpecialItems.getLength() -1 + + currentRule = allSpecialItems.item(iSpecRule); + + key = char(currentRule.getElementsByTagName('Key').item(0).getTextContent().toString()); + specialRulesNode.(key) = struct(); + specialRulesNode.(key).Value = char(currentRule.getElementsByTagName('Value').item(0).getTextContent().toString()); + end + + settingsStruct.SpecialRules = specialRulesNode; + + function escapedValue = removeXMLEscaping(value) + escapedValue = regexprep(value, '<', '<'); + escapedValue = regexprep(escapedValue, '&', '&'); + escapedValue = regexprep(escapedValue, '>', '>'); + + end + + end + end +end + +","MATLAB" +"Neurology","ChristianGaser/cat12","internal/cat_tst_main.m",".m","3505","66","% cat_tst_main +% +% Todo: +% - Documentation +% - standardized processing cases for future comparision only based on results? +addpath( fullfile( fileparts( which('cat12')) , 'internal') ); + +% setup methods and data +Praw = '/Volumes/WDE18TB/MRDataPP/202505_CS4/derivatives'; +Pmethod = { +... NAME PATH COLOR MARKER COMMENT +... 'CAT12-CS22' fullfile(Praw,'CAT12.9','CAT12.9_2679_CS2') [.0 .8 .0] 'd' % +... 'CAT12-CS24o' fullfile(Praw,'CAT12.9','CAT12.9_2679_CS24') [.3 .6 .0] 'p' % old with sharpening +... 'CAT12-CS42' fullfile(Praw,'CAT12.9','CAT12.9_2679_CS42') [.6 .0 .8] '>' % sharpening + 'CAT12-CS11' fullfile(Praw,'CAT12.9','CAT12.9_2712_CS11') [.0 .9 .0] 'd' % + 'CAT12-CS22' fullfile(Praw,'CAT12.9','CAT12.9_2712_CS22') [.3 .6 .0] 'p' % + 'CAT12-CS24' fullfile(Praw,'CAT12.9','CAT12.9_2712_CS24') [.6 .3 .0] 'p' % ... missing data + 'CAT12-CS40' fullfile(Praw,'CAT12.9','CAT12.9_2712_CS40') [.3 .0 .5] '<' % + 'CAT12-CS42' fullfile(Praw,'CAT12.9','CAT12.9_2712_CS42R3') [.6 .0 .8] '<' % + ... 'CAT12-CS42R' fullfile(Praw,'CAT12.9','CAT12.9_2712_CS42R4_gyrusrecon2') [.7 .0 .9] '<' % + 'CAT12-CS42Rb' fullfile(Praw,'CAT12.9','CAT12.9_2712_CS42R4_gyrusrecon2b') [.8 .0 .99] '<' % + ... +... 'SPM25-CS22' fullfile(Praw,'CAT12.9_SPM25','CAT12.9_2701_SPMorg_CS22','SPM25') [.0 .4 .0] 'd' % +... 'SPM25-CS24o' fullfile(Praw,'CAT12.9_SPM25','CAT12.9_2701_SPMorg_CS24','SPM25') [.15 .3 .0] 'p' % old with sharpening + 'SPM25-CS11' fullfile(Praw,'CAT12.9_SPM25','CAT12.9_2712_CS11','SPM25') [.0 .9 .5] 's' % + 'SPM25-CS22' fullfile(Praw,'CAT12.9_SPM25','CAT12.9_2712_CS22','SPM25') [.3 .6 .5] '+' % + 'SPM25-CS24' fullfile(Praw,'CAT12.9_SPM25','CAT12.9_2712_CS24','SPM25') [.6 .3 .5] '+' % ... + 'SPM25-CS40' fullfile(Praw,'CAT12.9_SPM25','CAT12.9_2712_CS40','SPM25') [.3 .5 .5] '>' % ... Rusak .5 is strange + 'SPM25-CS42' fullfile(Praw,'CAT12.9_SPM25','CAT12.9_2712_CS42R3','SPM25') [.6 .5 .8] '>' % + ... + 'T1Prep' fullfile(Praw,'T1Prep','V20250429') [.0 .1 .9] 'v' % [3 + 'T1PrepAmapV2' fullfile(Praw,'T1Prep','AMAP_V20250515') [.0 .6 .4] '^' % [2 1 0 + }; +Presdir = '/Volumes/WDE18TB/MRDataPP/202505_CS4/derivatives/results'; +Presdir = fullfile(Presdir,char(datetime('now','format','yyyyMMdd') )); +subsets = { + '10_AgingIXI'; % 18-90 + '11_Aging'; % 18-90 + '12_Elderly'; % + '13_Development'; + ...'15_MRART'; +}; +methset = 1:12; %[ 2 4 5]; %[3 4 7 8]; %1 4 5 8]; +Pmethod = Pmethod(methset,:); +Pmethod(:,1) + +% run processing +% - find RAW files and check if they were processed +%cat_test_runpp(Pmethod) + +% TODO: +% + update function for stat +% + main effect only / dual effect (reduce stat by factor 2) +% + +% run tests +% - cat_tst_dataview(Pmethod,Presdir) % not existing yet +%cat_tst_BWP(Pmethod,Presdir,1) % last variable: use_subset +%cat_tst_Rusak2021(Pmethod,Presdir,1) % last variable: use_subset +cat_tst_aging(Pmethod,Presdir,fileparts(Praw),subsets) + +% further extensions (not existing yet) +% - cat_tst_MRART() % ~400 dataset +% - cat_tst_SRS() % << Buchert? +% - cat_tst_VBMGT % << old ground truth data +","MATLAB" +"Neurology","ChristianGaser/cat12","internal/cat_vol_nlmus.m",".m","14971","446","function varargout = cat_vol_nlmus(varargin) +% Non Local Means UpSampling (NLMUS) with Spatial Adaptive Non Local +% Means (SANLM) Filter. +% +% Filter a set of images and add the prefix 'nlmus_'. Main goal is to +% restore slice resolution of unisotropic images e.g. to get from +% 1x1x3 mm3 to 1x1x1 mm3. +% +% The upsampling does not work on label maps such as the p0*.nii! +% +% Missing input will use defaults. +% +% Input: +% job - harvested job data structure (see matlabbatch help) +% +% Output: +% out - computation results, usually a struct variable. +% +% cat_vol_sanlm(job) +% job.data = set of images +% job.prefix = prefix for filtered images (default = 'nlmus_') +% job.rician = noise distribution +% job.prefix = 'nlmus_'; +% job.sanlm = noise reduction before interpolation +% job.verb = display iterations +% job.interp = 1x1 integer gives upsampling value +% 1x3 float values gives goal resolution +% (default = [1 1 1]); +% job.maxiter = maximum number of iterations (default = 0 = auto) +% job.writeinit = write simple interpolated image for comparison +% +% Example: +% cat_vol_nlmus(struct('data','','prefix','us','rician',0)); +% +% The upsampling run intro problems for segment and + +% cat_vol_nlmus(struct('data','../p0sub.nii','sanlmiter',0, ... +% 'interp','linear'); +% +%_______________________________________________________________________ +% +% Robert Dahnke - robert.dahnke@uni-jena.de +% Center of Neuroimaging +% Department of Psychiatry and Psychotherapy +% University Hospital Jena +%_______________________________________________________________________ +% +% Jose V. Manjon - jmanjon@fis.upv.es +% Universidad Politecinca de Valencia, Spain +% Pierrick Coupe - pierrick.coupe@gmail.com +% Brain Imaging Center, Montreal Neurological Institute. +% Mc Gill University +% +% Copyright (C) 2010 Jose V. Manjon and Pierrick Coupe +%_______________________________________________________________________ +% $Id$ + +% job.rf = round the initial interpolation (10^-2); +% job.intmeth = {'spline'|'cubic','linear'} (default = 'spline') + + if nargin == 0 + job.data = cellstr(spm_select([1 Inf],'image','select images to filter')); + elseif nargin == 1 && isstruct(varargin{1}) + job = varargin{1}; + else + src = varargin{1}; + if nargin>1 + if isstruct( varargin{2} ) + job = varargin{2}; + else + job.interp = varargin{2}; + end + end + if nargin>2 + job.vx_vol = varargin{3}; + end + job.data = 'matlab'; + job.src = 1; + end + + if ~isfield(job,'data') || isempty(job.data) + job.data = cellstr(spm_select([1 Inf],'image','select images to filter')); + else + job.data = cellstr(job.data); + end + if isempty(job.data{1}), return; end + + def.prefix = 'nlmus_'; + def.intmeth = {'spline','nearest'}; + def.verb = 1; + def.interp = [1 1 1]; + def.vx_vol = [1 1 1]; + def.maxiter = 0; + def.rician = 1; + def.rf = 0.001; + def.writeinit = 1; + def.sanlm = 0; + def.mask = 0; + def.src = 0; + def.finalinterp = 0; + + job = cat_io_checkinopt(job,def); + + if job.sanlm + job.prefix = [job.prefix 'sanlm_']; + end + + if ~job.src + V = spm_vol(char(job.data)); Vn = V; + %V = rmfield(V,'private'); + + fnames = cell(size(job.data)); + spm_clf('Interactive'); + spm_progress_bar('Init',numel(job.data),'NLM-Interpolation','Volumes Complete'); + else + V.mat = eye(4); + V.fname = ''; + V.descrip = ''; + end + for i = 1:numel(job.data) + [pth,nm,xt,vr] = spm_fileparts(deblank(V(i).fname)); + + % load and prepare data + if ~job.src + src = single(spm_read_vols(V(i))); + src(isnan(src)) = 0; % prevent NaN + vx_vol = sqrt(sum(V(i).mat(1:3,1:3).^2)); % voxel resolution + if V(i).dt(1)<16, V(i).dt(1) = 16; end % use at least float precision + else + vx_vol = job.vx_vol; + end + + if job.verb + % interpolation factor + if numel(job.interp)==1 + lf3 = repmat(2.^job.interp,1,3); + elseif numel(job.interp)==3 && all(job.interp>=1) && all(job.interp==round(job.interp)) + lf3 = job.interp; + elseif numel(job.interp)==3 && any(job.interp<=vx_vol) + lf3 = vx_vol ./ job.interp; + else + error('Error cat_vol_nlmus ""job.interp"" has to be 1 element (interpolation factor) or 3 elements (goal resolution).'); + end + if any(vx_vol./lf3)<0.2, error('To large.\n'); end + + cat_io_cmd(sprintf('Process ""%s"" %0.2fx%0.2fx%0.2f > %0.2fx%0.2fx%0.2f\n',... + nm,vx_vol,vx_vol./lf3),'n','',job.verb); fprintf('\n'); + end + + + %% SANLM or ISARNLM noise correction + % ----------------------------------------------------------------- + if ~job.src && job.sanlm + %% + if job.verb, stime = cat_io_cmd('\n SANLM-filtering','g5',''); end + cat_vol_sanlm(struct('data',V(i).fname,'verb',0,'prefix','n','NCstr',-inf)); + Vn(i)=spm_vol(spm_file(V(i).fname,'prefix','n')); + src = single(spm_read_vols(Vn(i))); + end + + th = max(mean(src(src(:)>0)),abs(mean(src(src(:)<0)))); + src = (src / th) * 100; + + % histogram limit for sigma ... + [hsrc,hval] = hist(src(:),10000); hp = cumsum(hsrc)./sum(hsrc); itol = 0.0001; + minfsrc = hval(find(hp>itol,1,'first')); + maxfsrc = hval(find(hp<(1-itol),1,'last')); + if job.sanlm==0 + if min(src(:))~=0, src(srcitol,1,'first'))) = hval(find(hp>itol,1,'first')); end + src(src>hval(find(hp<(1-itol),1,'last'))) = hval(find(hp<(1-itol),1,'last')); + end + %job.interp = job.interp .* 1./round(job.interp./min(job.interp)); + + % interpolation factor + if numel(job.interp)==1 + lf3 = repmat(2.^job.interp,1,3); + %lf = round(vx_vol ./ repmat(min(vx_vol),1,3) ) * job.interp; + lf = repmat(2.^job.interp,1,3); + elseif numel(job.interp)==3 && all(job.interp>=1) && all(job.interp==round(job.interp)) + lf3 = job.interp; + lf = job.interp; + elseif numel(job.interp)==3 && any(job.interp<=1) %&& any(job.interp~=round(job.interp)) + lf3 = vx_vol ./ job.interp; + lf = round(vx_vol ./ job.interp); + else + error('Error cat_vol_nlmus ""job.interp"" has to be 1 element (interpolation factor) or 3 elements (goal resolution).'); + end + if any(vx_vol./lf3)<0.2, error('To large.\n'); end + + + + + %% write spline interpolation image for comparison + % ----------------------------------------------------------------- + if ~job.src && job.writeinit + if job.verb + if exist('stime','var') + stime = cat_io_cmd(sprintf(' Write intial %s interpolation',job.intmeth{1}),'g5','',job.verb,stime); + else + stime = cat_io_cmd(sprintf(' Write intial %s interpolation',job.intmeth{1}),'g5','',job.verb); + end + end + for ii=1:min(numel(job.intmeth),job.writeinit) + %% spline interpolation + Vx = V(i); + if any(lf3~=1) + src2 = InitialInterpolation(src,lf3,job.intmeth{ii},job.rf); + mat = spm_imatrix(Vx.mat); mat(7:9) = mat(7:9)./lf3; + Vx.mat = spm_matrix(mat); + Vx.dim = size(src2); + else + src2 = src; + end + + % write result + Vx.fname = fullfile(pth,[job.prefix nm '_' job.intmeth{ii} '.nii' vr]); + Vx = rmfield(Vx,'private'); + spm_write_vol(Vx, src2); + + clear src2; + end + end + + + + + + + %% NLM upsampling (& final interpolation) + % ----------------------------------------------------------------- + if any(lf>1) + if exist('stime','var') + stime = cat_io_cmd(' Initial Interpolation','g5','',job.verb,stime); + else + stime = cat_io_cmd(' Initial Interpolation','g5','',job.verb); + end + + + % Parameters + sigma = std(src(src(:)>minfsrc & src(:)0 + maxiter = job.maxiter; + else + maxiter = prod(lf)*8; + end + + % Initial interpolation + src = InitialInterpolation(src,lf,job.intmeth{1},job.rf); + last = src; + + + + %% use mask? + if job.mask + grad = cat_vol_grad(src); + mask = src>sigma & grad>sigma/10; + mask = cat_vol_morph(mask,'d'); + mask = cat_vol_morph(mask,'c'); + end + + %% Iterative reconstruction + while ii<=maxiter*1.2 + stime = cat_io_cmd(sprintf(' Iteration %d',ii),'g5','',job.verb,stime); + + if job.mask + [src,masks,BB] = cat_vol_resize({src,mask},'reduceBrain',vx_vol,1,mask); + masks=masks>0.5; src(~masks)=nan; + if any(mod(BB.sizeTr,2)), ns=BB.sizeTr + mod(BB.sizeTr,2); src(ns(1),ns(2),ns(3))=nan; end + end + src = double(src); + F2 = cat_vol_cMRegularizarNLM3D(src,v,1,level,lf); + F2 = single(F2); + % label maps generate NaNs in the worst case, but there are no changes in other regions + if job.mask + F2 = F2(1:BB.sizeTr(1),1:BB.sizeTr(2),1:BB.sizeTr(3)); + F2 = cat_vol_resize(F2,'dereduceBrain',BB); + src = src(1:BB.sizeTr(1),1:BB.sizeTr(2),1:BB.sizeTr(3)); + src = cat_vol_resize(src,'dereduceBrain',BB); + end + F2(isnan(F2)) = last(isnan(F2)); + + d(ii) = mean(abs(src(:)-F2(:))); %#ok + if(d(ii)1 + if job.verb, fprintf('%s%18s',sprintf(repmat('\b',1,18)),sprintf('(%0.2f,%0.2f)w',d(ii)/tol,level)); end + Vt=V(i); Vt.fname = fullfile(pth,[job.prefix nm '_' num2str(iii,'%02d') '.nii' vr]); + mat = spm_imatrix(Vt.mat); mat(7:9) = mat(7:9)./lf; + Vt.mat = spm_matrix(mat); + Vt.dim = size(F2); + spm_write_vol(Vt, (F2 / 100) * th); + else + if job.verb, fprintf('%s%18s',sprintf(repmat('\b',1,18)),sprintf('(%0.2f,%0.2f) ',d(ii)/tol,level)); end + end + + level = level/2; + + if (levelmaxiter), break; end; + + dss(iii) = mean(abs(last(:)-F2(:))); %#ok + if(dss(iii)=1, varargout{1} = fnames; end + if nargout>=2, varargout{2} = V; end + end +end + + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +function [nima1]=InitialInterpolation(nima1,lf,intmeth,roundfactor) +%% + warning off; + + s = size(nima1).*lf; + ori = ((1+lf)/2); + + % reconstruc using spline interpolation + [x,y,z] = ndgrid( ori(1):lf(1):1-ori(1)+s(1),ori(2):lf(2):1-ori(2)+s(2),ori(3):lf(3):1-ori(3)+s(3)); + [xi,yi,zi] = ndgrid(1:s(1),1:s(2),1:s(3)); + nima1 = interpn(x,y,z,nima1,xi,yi,zi,intmeth); + + if roundfactor>0 + nima1 = round(nima1/roundfactor)*roundfactor; + end + + s = round(s); + % deal with extreme slices + for i=1:floor(lf(1)/2) + nima1(i,:,:) = nima1(floor(lf(1)/2)+1,:,:); + end + for i=1:floor(lf(2)/2) + nima1(:,i,:) = nima1(:,floor(lf(2)/2)+1,:); + end + for i=1:floor(lf(3)/2) + nima1(:,:,i) = nima1(:,:,floor(lf(3)/2)+1); + end + + for i=1:floor(lf(1)/2) + nima1(s(1)-i+1,:,:) = nima1(s(1)-floor(lf(1)/2),:,:); + end + for i=1:floor(lf(2)/2) + nima1(:,s(2)-i+1,:) = nima1(:,s(2)-floor(lf(2)/2),:); + end + for i=1:floor(lf(3)/2) + nima1(:,:,s(3)-i+1) = nima1(:,:,s(3)-floor(lf(3)/2)); + end + + + % mean correction + % ... don't know why Jose was using this, but it is realy slow and looks unimportant + %{ + lfr=floor(lf); + for i=1:lf(1):s(1) + for j=1:lf(2):s(2) + for k=1:lf(3):s(3) + tmp = bima2(i:i+lfr(1)-1,j:j+lfr(2)-1,k:k+lfr(3)-1); + off = nima1((i+lf(1)-1)/lf(1),(j+lf(2)-1)/lf(2),(k+lf(3)-1)/lf(3)) - mean(tmp(:)); + bima(i:i+lfr(1)-1,j:j+lfr(2)-1,k:k+lfr(3)-1) = bima2(i:i+lfr(1)-1,j:j+lfr(2)-1,k:k+lfr(3)-1)+off; + end + end + end + %} + + warning on; +end + +","MATLAB" +"Neurology","ChristianGaser/cat12","internal/correct_HCP_annot.m",".m","1005","32","function correct_HCP_annot +% replace right hemipshere names and labels with that from left hemipshere to be compatible to other +% annot-files +%_______________________________________________________________________ +% Christian Gaser +% $Id$ + +[vl, fl, cl] = cat_io_FreeSurfer('read_annotation','lh.HCP-MMP1.annot'); +[vr, fr, cr] = cat_io_FreeSurfer('read_annotation','rh.HCP-MMP1.annot'); + +n = cl.numEntries; + +for i=1:n + struct_names = cl.struct_names(i); + + % don't change first ""???"" entry + if i>1 + % remove L_/R_ and _ROI parts of the name + cl.struct_names(i) = {struct_names{1}(3:end-4)}; + cr.struct_names(i) = {struct_names{1}(3:end-4)}; + end + + % replace labels + fr(find(fr==cr.table(i,5))) = cl.table(i,5); + + % correct colortable + cr.table(i,:) = cl.table(i,:); +end + +cat_io_FreeSurfer('write_annotation', 'atlases_surfaces/lh.aparc_HCP_MMP1.freesurfer.annot', vl, fl, cl); +cat_io_FreeSurfer('write_annotation', 'atlases_surfaces/rh.aparc_HCP_MMP1.freesurfer.annot', vr, fr, cr); +","MATLAB" +"Neurology","ChristianGaser/cat12","internal/cat_vol_increaseAtlasGMregion.m",".m","2821","105","function cat_vol_increaseAtlasGMregion +%_______________________________________________________________________ +% Simple internal function to improve atlas maps that were thresholded +% by tissue probality such as the neuromorphometrics atlas. +%_______________________________________________________________________ +% Robert Dahnke +% Structural Brain Mapping Group +% University Jena +% +% $Id$ +% ______________________________________________________________________ + + Pt = spm_select([1 1],'image','select TPM'); + Pa = cellstr(spm_select([1 Inf],'image','select atlas maps')); + pth = 0.0; + method = 'vbdist'; % vbdist, downcut + + %% ROIs + % region of changes + DelRoi = {'Cerebral White Matter'}; + % region that should not change + noDilRoi = { + 'Ventricle' + 'Accumbens' + 'Amygdala' + 'Hippocampus' + 'Pallidum' + 'Putamen' + 'Thalamus' + 'Caudate' + 'Thalamus' + }; + + for ai=1:numel(Pa) + %% prepare data + [pp,ff,ee] = spm_fileparts(Pa{ai}); + + % find csv-file + csv = cat_io_csv(fullfile(pp,[ff '.csv'])); + id = cell2mat(csv(2:end,1)); + roi = csv(2:end,3); + + DelRoiIds = []; + for dri=1:numel(DelRoi) + DelRoiIds = [DelRoiIds;id(~cellfun('isempty',strfind(roi,DelRoi{dri})))]; %#ok + end + DelRoiIds = unique(DelRoiIds); + + noDilRoiIds = []; + for ndri=1:numel(noDilRoi) + noDilRoiIds = [noDilRoiIds;id(~cellfun('isempty',strfind(roi,noDilRoi{ndri})))]; %#ok + end + noDilRoiIds = unique(noDilRoiIds); + + %% load images + Va = spm_vol(Pa{ai}); + Vt = spm_vol(Pt); + + Ya = spm_read_vols(Va); + Yt = spm_read_vols(Vt); + + Ya2 = Ya; + for dri=1:numel(DelRoiIds) + Ya2(Ya2==DelRoiIds(dri))=0; + end + + switch method + case 'vbdist' + % simple distance + [YD,YI] = cat_vbdist(single(Ya2>0),Yt>pth); Ya3=Ya(YI); + + Ya3(Ya3==0) = Ya(Ya3==0); + for dri=1:numel(noDilRoiIds) + Ya3(Ya3==noDilRoiIds(dri) & Ya~=noDilRoiIds(dri)) = ... + Ya( Ya3==noDilRoiIds(dri) & Ya~=noDilRoiIds(dri)); + end + Ya2 = Ya3; + case 'downcut' + % region-growing ... simpler is better! this is just for tests + Ya2 = single(Ya2); Ya2(Yt0); + + %% display things + ds('l2','',1.5,Yt,single(Ya3)>0,single(Ya)/80,single(Ya2)/80,60) + + %% write result + copyfile(fullfile(pp,[ff ee]),fullfile(pp,[ff '_orginal' ee])); + spm_write_vol(Va,Ya2); + + end +end + + + +","MATLAB" +"Neurology","ChristianGaser/cat12","internal/cat_vol_optimizeTemplate.m",".m","3255","101","function cat_vol_optimizeTemplate(job) +% _______________________________________________________________________ +% Set resolution and data type of a Dartel or Shooting template to save +% disk space. This is a private function that is not intensivly tested. +% +% cat_vol_optimizeTemplate(job) +% +% job.vox = resolution of the new template images (default = 1.5) +% job.repair = repair artifacts in the template with a median filter that +% modify only a few incorrect voxels +% (quick and dirty solution that rewrite the original data!) +% +% _______________________________________________________________________ +% $Id$ + + + %% prepare data structur + if ~exist('job','var'), job = struct(); end + def.data = {}; + def.vox = 0.8; + def.repair = 0; + job = cat_io_checkinopt(job,def); + + % choose files + if isempty(job.data) + job.data = cellstr(spm_select(Inf,'image','Choose Template Maps')); + end + + % set ouput path/name + if ~isfield('output',job) || isempty(job.output) + job.output = spm_input('output path and suffix','+1','s',fullfile(spm('dir'),'toolbox','cat12','templates_volumes','restest','IXI555_MNI152_new.nii')); + end + + % + [pp,ff,ee] = spm_fileparts(char(job.output)); + if ~exist(pp,'dir'), mkdir(pp); end + for di = 1:numel(job.data) + % load main header + Vdi = spm_vol(job.data{di}(1:end-2)); + + for ii = 1:numel(Vdi) + %% + Vo = Vdi; + + % load image + Pbt = fullfile(pp,sprintf('Template_%d_%s%s,%d',di - (numel(job.data)==4),ff,ee,ii)); + if ~isempty(job.vox) + vxo = abs(Vdi(ii).mat(1)); + Vo(ii).dim = ceil( Vo(ii).dim .* vxo ./ job.vox ); + Vo(ii).mat([1,6,11]) = Vo(ii).mat([1,6,11]) .* ( job.vox / vxo ); + + % ... also just a quick and dirty correction of the AC + if vxo==1 + Vo(ii).mat(13:15) = [91.5 -127.5 -73.5]; + end + + % repair the images + if job.repair + Yo = spm_read_vols(Vdi(ii)); + if ii==1 + Yos = cat_vol_median3(single(Yo),Yo<=0.05,true(size(Yo)),0.1); + Ych = Yos - Yo; + Yo = Yos; + elseif ii==numel(Vdi) + Yo = Yo - Ych; + end + [pp,ff,ee,xx] = spm_fileparts(Vdi(ii).fname); + Vdic(ii).fname = fullfile(pp,[ff '_corrected' ee xx]); %#ok + spm_write_vol(Vdic(ii),Yo); + + [Vo2,Yo] = cat_vol_imcalc([Vo(ii),Vdic(ii)],Pbt,'i2',struct('interp',3,'verb',0)); + delete(Vdic(ii).fname); + else + [Vo2,Yo] = cat_vol_imcalc([Vo(ii),Vdi(ii)],Pbt,'i2',struct('interp',3,'verb',0)); + end + + else + Yo = spm_read_vols(Vdi(ii)); + end + Yo(isnan(Yo(:))) = min(Yo(:)); + + % prepare output data + Voo = Vo(ii); + if numel(job.data)==5 + Voo.dt(1) = 512; + Voo.pinfo = [1/256^2;0]; + GSstr = '_GS'; + else + Voo.dt(1) = 2; + Voo.pinfo = [1/256;0]; + GSstr = ''; + end + Voo.fname = fullfile(pp,sprintf('Template_%d_%s%s%s',di - (numel(job.data)==5),ff,GSstr,ee)); + if ii==1 && exist(Voo.fname,'file'), delete(Voo.fname); end + spm_write_vol(Voo,Yo); + + clear Yo Vo; + end + end + +end","MATLAB" +"Neurology","ChristianGaser/cat12","internal/cg_io_send_to_server.m",".m","13231","368","function cat_io_send_to_server +% This function will send Matlab version information to the SBM server +% The mac address is only used for creating a uniqe id to not count visits +% several times +% If you don't want to send this information to the SBM server +% (for internal use only) change the flag cat.extopts.send_info in +% cat_defaults.m +% +%_______________________________________________________________________ +% Christian Gaser +% $Id$ + +% don't do anything if default is not set +if ~cat_get_defaults('extopts.send_info'), return; end + +mac = MACAddress(); + +% remove ""-"" or "":"" in mac address +mac = strrep(mac,'-',''); +mac = strrep(mac,':',''); + +% use 16 hex digits +mac = ['0000' mac]; + +url = sprintf('https://neuro-jena.github.io/piwik/piwik.php?idsite=1&rec=1&_id=%s&action_name=%s%s%s',mac,'Start','%2F',version('-release')); +try, urlread(url); end + +function [mac, st] = MACAddress(allMac) +% [mac, st] = MACAddress() +% +% The default is to return one MAC address, likely for ethernet adaptor. If the +% optional input is provided and true, all MAC address are returned in cellstr. +% No internet connection is required for this to work. +% +% The optional 2nd output, if requested, is a struct with following fields: +% st.FriendlyName (meaningful for Windows only) +% st.Description (OS dependent description) +% st.MAC_address (the same order as the 1st output) +% st.IPv4_address (empty if not available) +% st.IPv6_address (empty if not available) +% +% Examples: +% mac = MACAddress(); % return 1st MAC in string +% The format is like F0-4D-A2-DB-00-37 for Windows, f0:4d:a2:db:00:37 otherwise. +% +% macs = MACAddress(1); % return all MAC on the computer +% The output is cell even if only one MAC found. +% +% [macs, st] = MACAddress(1); % also return more info in st +% +% To get numeric: +% num = uint8(sscanf(MACAddress, '%2x%*c', 6))'; + +% 170510 Adapted this from RTBox code (Xiangrui.Li at gmail.com). +% 170525 Include mex for MS Windows. +% 171030 mex.c more robust. Include Octave 4 mex. +% 180525 use jsystem('ipconfig') for Windows; java method moved behind. +% 180626 implement 2nd optional output for both m and mex (almost rewritten). + +if nargin<1 || isempty(allMac), allMac = false; end % default to first MAC + +if ispc + [tmp, str] = jsystem({'ipconfig.exe' '/all'}); + str = regexprep(str, '\r', ''); + mac_expr = 'Physical Address.*?:\s*((?:[0-9A-F]{2}-){5}[0-9A-F]{2})\s'; + nam_expr = '\nEthernet adapter\s+(.*?):?\n'; % nam/des/ip4/ip6 all in a block + des_expr = 'Description.*?:\s*(.*?)\n'; + ip4_expr = 'IP(?:v4)? Address.*?:\s*((?:\d{1,3}\.){3}\d{1,3})'; + ip6_expr = 'IPv6 Address.*?:\s*((?:[0-9a-f]{0,4}:){1,7}[0-9a-f]{0,4})'; + fmt = '%02X-%02X-%02X-%02X-%02X-%02X'; % adopt OS format preference +elseif ismac + % [tmp, str] = jsystem({'networksetup' '-listallhardwareports'}); + [tmp, str] = jsystem({'ifconfig'}); + mac_expr = '\n\s+ether\s+((?:[0-9a-f]{2}:){5}[0-9a-f]{2})\s'; + des_expr = '\n(.*?):\s+'; + nam_expr = des_expr; + ip4_expr = 'inet\s+((?:\d{1,3}\.){3}\d{1,3})'; + ip6_expr = 'inet6\s+((?:[0-9a-f]{0,4}:){1,7}[0-9a-f]{0,4})'; + fmt = '%02x:%02x:%02x:%02x:%02x:%02x'; +else % linux + [err, str] = jsystem({'ip' 'address'}); % later Linux + if ~err % almost always + mac_expr = '\s+link/ether\s+((?:[0-9a-f]{2}:){5}[0-9a-f]{2})\s'; + des_expr = '\n\d+:\s+(.*?):\s+'; + ip4_expr = '\s+inet\s+((?:\d{1,3}\.){3}\d{1,3})'; + ip6_expr = '\s+inet6\s+((?:[0-9a-f]{0,4}:){1,7}[0-9a-f]{0,4})'; + else % use ifconfig for old linux + cmd = '/sbin/ifconfig'; + if ~exist(cmd, 'file'), cmd = 'ifconfig'; end + [tmp, str] = jsystem({cmd}); + mac_expr = '\s+HWaddr\s+((?:[0-9a-f]{2}:){5}[0-9a-f]{2})\s'; + des_expr = '\n*(.*?)\s+'; + ip4_expr = 'inet addr:\s*((?:\d{1,3}\.){3}\d{1,3})'; + ip6_expr = 'inet6 addr:\s*((?:[0-9a-f]{0,4}:){1,7}[0-9a-f]{0,4})'; + end + nam_expr = des_expr; + fmt = '%02x:%02x:%02x:%02x:%02x:%02x'; +end + +if allMac, [mac, ind] = regexp(str, mac_expr, 'tokens', 'start'); +else, [mac, ind] = regexp(str, mac_expr, 'tokens', 'start', 'once'); +end +mac = [mac{:}]; +% if iscell(mac) && numel(ind)>1 % make mac unique +% [tmp, ia] = unique(mac); +% ia = sort(ia); % [mac, ia] = unique(mac, 'stable'); ind = ind(ia); +% mac = mac(ia); +% ind = ind(ia); +% end + +if nargout>1 && ~isempty(mac) + st = struct('FriendlyName', [], 'Description', [], 'MAC_address', mac, ... + 'IPv4_address', [], 'IPv6_address', []); + i0 = [1 regexp(str, '\n\S') numel(str)]; % split str into blocks + for i = 1:numel(ind) + j = find(i01, st = []; end + if allMac, mac = {}; end + ni = java.net.NetworkInterface.getNetworkInterfaces; + while ni.hasMoreElements + aa = ni.nextElement; + a = aa.getHardwareAddress; + if numel(a)~=6 || all(a==0), continue; end % not valid mac + a = typecast(a, 'uint8'); % from int8 + m = sprintf(fmt, a); + if nargout>1 + st(end+1).FriendlyName = char(aa.getName); %#ok + st(end).Description = char(aa.getDisplayName); + st(end).MAC_address = m; + aa = aa.getInetAddresses; + while aa.hasMoreElements + c = char(aa.nextElement); + a = regexp(c, '(\d{1,3}\.){3}\d{1,3}', 'match', 'once'); + if ~isempty(a), st(end).IPv4_address = a; end + a = regexp(c, '(([0-9a-f]{0,4}:){1,7}[0-9a-f]{0,4})', 'match', 'once'); + if ~isempty(a) + st(end).IPv6_address = strrep(a, 'fe80:0:0:0:', 'fe80::'); + end + end + end + if allMac, mac{end+1} = m; %#ok + else, mac = m; break; % done after finding 1st + end + end +end +end + +% If all attemps fail, give warning and return a random MAC +if isempty(mac) + a = zeros(1,6); + mac = sprintf(fmt, a); + if nargout>1 + st = struct('FriendlyName', [], ... + 'Description', 'Failed to find network adapter', ... + 'MAC_address', mac, 'IPv4_address', [], 'IPv6_address', []); + end + if allMac, mac = {mac}; end +end + +%% faster than system: based on https://github.com/avivrosenberg/matlab-jsystem +function [err, out] = jsystem(cmd) +% cmd is cell str, no quotation marks needed for file names with space. +try + pb = java.lang.ProcessBuilder(cmd); + pb.redirectErrorStream(true); % ErrorStream to InputStream + process = pb.start(); + scanner = java.util.Scanner(process.getInputStream).useDelimiter('\A'); + if scanner.hasNext(), out = char(scanner.next()); else, out = ''; end + err = process.exitValue; % err = process.waitFor() may hang + if err, error('java.lang.ProcessBuilder error'); end +catch % fallback to system() if java fails like for Octave + cmd = regexprep(cmd, '.+? .+', '""$0""'); % double quotes if with middle space + [err, out] = system(sprintf('%s ', cmd{:})); +end + +function [varargout] = judp(actionStr,varargin) +% +% judp.m--Uses Matlab's Java interface to handle User Datagram Protocol +% (UDP) communications with another application, either on the same +% computer or a remote one. +% +% JUDP('SEND',PORT,HOST,MSSG) sends a message to the specifed port and +% host. HOST can be either a hostname (e.g., 'www.example.com') or a string +% representation of an IP address (e.g., '192.0.34.166'). Port is an +% integer port number between 1025 and 65535. The specified port must be +% open in the receiving machine's firewall. +% +% MSSG = JUDP('RECEIVE',PORT,PACKETLENGTH) receives a message over the +% specified port. PACKETLENGTH should be set to the maximum expected +% message length to be received in the UDP packet; if too small, the +% message will be truncated. +% +% MSSG = JUDP('RECEIVE',PORT,PACKETLENGTH,TIMEOUT) attempts to receive a +% message but times out after TIMEOUT milliseconds. If TIMEOUT is not +% specified, as in the previous example, a default value is used. +% +% [MSSG,SOURCEHOST] = JUDP('RECEIVE',...) returns a string representation +% of the originating host's IP address, in addition to the received +% message. +% +% Messages sent by judp.m are in int8 format. The int8.m function can be +% used to convert integers or characters to the correct format (use +% double.m or char.m to convert back after the datagram is received). +% Non-integer values can be converted to int8 format using typecast.m (use +% typecast.m to convert back). +% +% e.g., mssg = judp('receive',21566,10); char(mssg') +% judp('send',21566,'208.77.188.166',int8('Howdy!')) +% +% e.g., [mssg,sourceHost] = judp('receive',21566,10,5000) +% judp('send',21566,'www.example.com',int8([1 2 3 4])) +% +% e.g., mssg = judp('receive',21566,200); typecast(mssg,'double') +% judp('send',21566,'localhost',typecast([1.1 2.2 3.3],'int8')) + +% Developed in Matlab 7.8.0.347 (R2009a) on GLNX86. +% Kevin Bartlett (kpb@uvic.ca), 2009-06-18 16:11 +%------------------------------------------------------------------------- + +SEND = 1; +RECEIVE = 2; +DEFAULT_TIMEOUT = 1000; % [milliseconds] + +% Handle input arguments. +if strcmpi(actionStr,'send') + action = SEND; + + if nargin < 4 + error([mfilename '.m--SEND mode requires 4 input arguments.']); + end % if + + port = varargin{1}; + host = varargin{2}; + mssg = varargin{3}; + +elseif strcmpi(actionStr,'receive') + action = RECEIVE; + + if nargin < 3 + error([mfilename '.m--RECEIVE mode requires 3 input arguments.']); + end % if + + port = varargin{1}; + packetLength = varargin{2}; + + timeout = DEFAULT_TIMEOUT; + + if nargin > 3 + % Override default timeout if specified. + timeout = varargin{3}; + end % if + +else + error([mfilename '.m--Unrecognised actionStr ''' actionStr ''.']); +end % if + +% Test validity of input arguments. +if ~isnumeric(port) || rem(port,1)~=0 || port < 1025 || port > 65535 + error([mfilename '.m--Port number must be an integer between 1025 and 65535.']); +end % if + +if action == SEND + if ~ischar(host) + error([mfilename '.m--Host name/IP must be a string (e.g., ''www.examplecom'' or ''208.77.188.166''.).']); + end % if + + if ~isa(mssg,'int8') + error([mfilename '.m--Mssg must be int8 format.']); + end % if + +elseif action == RECEIVE + + if ~isnumeric(packetLength) || rem(packetLength,1)~=0 || packetLength < 1 + error([mfilename '.m--packetLength must be a positive integer.']); + end % if + + if ~isnumeric(timeout) || timeout <= 0 + error([mfilename '.m--timeout must be positive.']); + end % if + +end % if + +% Code borrowed from O'Reilly Learning Java, edition 2, chapter 12. +import java.io.* +import java.net.DatagramSocket +import java.net.DatagramPacket +import java.net.InetAddress + +if action == SEND + try + addr = InetAddress.getByName(host); + packet = DatagramPacket(mssg, length(mssg), addr, port); + socket = DatagramSocket; + socket.setReuseAddress(1); + socket.send(packet); + socket.close; + catch + sendPacketError + try + socket.close; + catch + closeError + % do nothing. + end % try + + error('%s.m--Failed to send UDP packet.\nJava error message follows:\n%s',mfilename,sendPacketError.message); + + end % try + +else + try + socket = DatagramSocket(port); + socket.setSoTimeout(timeout); + socket.setReuseAddress(1); + packet = DatagramPacket(zeros(1,packetLength,'int8'),packetLength); + socket.receive(packet); + socket.close; + mssg = packet.getData; + mssg = mssg(1:packet.getLength); + inetAddress = packet.getAddress; + sourceHost = char(inetAddress.getHostAddress); + varargout{1} = mssg; + + if nargout > 1 + varargout{2} = sourceHost; + end % if + + catch + receiveError + + % Determine whether error occurred because of a timeout. + if ~isempty(strfind(receiveError.message,'java.net.SocketTimeoutException')) + errorStr = sprintf('%s.m--Failed to receive UDP packet; connection timed out.\n',mfilename); + else + errorStr = sprintf('%s.m--Failed to receive UDP packet.\nJava error message follows:\n%s',mfilename,receiveError.message); + end % if + + try + socket.close; + catch + closeError + % do nothing. + end % try + + error(errorStr); + + end % try + +end % if + + +","MATLAB" +"Neurology","ChristianGaser/cat12","internal/cat_io_send_udp_to_server.m",".m","14076","393","function cat_io_send_udp_to_server +% This function will send mac-address and version information to the SBM server +%_______________________________________________________________________ +% Christian Gaser +% $Id$ + +% don't do anything if default is not set +if ~cat_get_defaults('extopts.send_info'), return; end + +mac = MACAddress(); + +% replace ""-"" by ""."" for windows systems +mac = strrep(mac,'-',':'); + +[nam,rev_cat] = cat_version; +[nam,rev_spm] = spm('Ver'); + +% platform OS +platform = system_dependent('getos'); +if ispc + platform = [platform, ' ', system_dependent('getwinsys')]; +elseif ismac + [status, result] = unix('sw_vers'); + if status == 0 + platform = strrep(result, 'ProductName:', ''); + platform = strrep(platform, sprintf('\t'), ''); + platform = strrep(platform, sprintf('\n'), ' '); + platform = strrep(platform, 'ProductVersion:', ' Version: '); + platform = strrep(platform, 'BuildVersion:', 'Build: '); + end +end + +% replace ""-"" by ""_"" +platform = strrep(platform,'-','_'); + +% date +dt = datestr(now,'yyyy/mm/dd'); + +% check CAT binaries +[ST, RS] = cat_system('CAT_3dVol2Surf'); +if isempty(strfind(RS,'Usage')); + info = sprintf('%s,%s,CAT%s,SPM%s,MATLAB%s,%s,%s,%s',mac,dt,rev_cat,rev_spm,version('-release'),computer,platform,RS); +else + info = sprintf('%s,%s,CAT%s,SPM%s,MATLAB%s,%s,%s',mac,dt,rev_cat,rev_spm,version('-release'),computer,platform); +end + +try + judp('send',2222,'dbm.neuro.uni-jena.de',int8(info)); + info = strrep(info,',',' '); + fprintf('\n%s\nIf you don''t want to send this information to the SBM server dbm.neuro.uni-jena.de (for internal use only) change the flag ''cat.extopts.send_info'' in cat_defaults.m.\n',info); +end + +function [mac, st] = MACAddress(allMac) +% [mac, st] = MACAddress() +% +% The default is to return one MAC address, likely for ethernet adaptor. If the +% optional input is provided and true, all MAC address are returned in cellstr. +% No internet connection is required for this to work. +% +% The optional 2nd output, if requested, is a struct with following fields: +% st.FriendlyName (meaningful for Windows only) +% st.Description (OS dependent description) +% st.MAC_address (the same order as the 1st output) +% st.IPv4_address (empty if not available) +% st.IPv6_address (empty if not available) +% +% Examples: +% mac = MACAddress(); % return 1st MAC in string +% The format is like F0-4D-A2-DB-00-37 for Windows, f0:4d:a2:db:00:37 otherwise. +% +% macs = MACAddress(1); % return all MAC on the computer +% The output is cell even if only one MAC found. +% +% [macs, st] = MACAddress(1); % also return more info in st +% +% To get numeric: +% num = uint8(sscanf(MACAddress, '%2x%*c', 6))'; + +% 170510 Adapted this from RTBox code (Xiangrui.Li at gmail.com). +% 170525 Include mex for MS Windows. +% 171030 mex.c more robust. Include Octave 4 mex. +% 180525 use jsystem('ipconfig') for Windows; java method moved behind. +% 180626 implement 2nd optional output for both m and mex (almost rewritten). + +if nargin<1 || isempty(allMac), allMac = false; end % default to first MAC + +if ispc + [tmp, str] = jsystem({'ipconfig.exe' '/all'}); + str = regexprep(str, '\r', ''); + mac_expr = 'Physical Address.*?:\s*((?:[0-9A-F]{2}-){5}[0-9A-F]{2})\s'; + nam_expr = '\nEthernet adapter\s+(.*?):?\n'; % nam/des/ip4/ip6 all in a block + des_expr = 'Description.*?:\s*(.*?)\n'; + ip4_expr = 'IP(?:v4)? Address.*?:\s*((?:\d{1,3}\.){3}\d{1,3})'; + ip6_expr = 'IPv6 Address.*?:\s*((?:[0-9a-f]{0,4}:){1,7}[0-9a-f]{0,4})'; + fmt = '%02X-%02X-%02X-%02X-%02X-%02X'; % adopt OS format preference +elseif ismac + % [tmp, str] = jsystem({'networksetup' '-listallhardwareports'}); + [tmp, str] = jsystem({'ifconfig'}); + mac_expr = '\n\s+ether\s+((?:[0-9a-f]{2}:){5}[0-9a-f]{2})\s'; + des_expr = '\n(.*?):\s+'; + nam_expr = des_expr; + ip4_expr = 'inet\s+((?:\d{1,3}\.){3}\d{1,3})'; + ip6_expr = 'inet6\s+((?:[0-9a-f]{0,4}:){1,7}[0-9a-f]{0,4})'; + fmt = '%02x:%02x:%02x:%02x:%02x:%02x'; +else % linux + [err, str] = jsystem({'ip' 'address'}); % later Linux + if ~err % almost always + mac_expr = '\s+link/ether\s+((?:[0-9a-f]{2}:){5}[0-9a-f]{2})\s'; + des_expr = '\n\d+:\s+(.*?):\s+'; + ip4_expr = '\s+inet\s+((?:\d{1,3}\.){3}\d{1,3})'; + ip6_expr = '\s+inet6\s+((?:[0-9a-f]{0,4}:){1,7}[0-9a-f]{0,4})'; + else % use ifconfig for old linux + cmd = '/sbin/ifconfig'; + if ~exist(cmd, 'file'), cmd = 'ifconfig'; end + [tmp, str] = jsystem({cmd}); + mac_expr = '\s+HWaddr\s+((?:[0-9a-f]{2}:){5}[0-9a-f]{2})\s'; + des_expr = '\n*(.*?)\s+'; + ip4_expr = 'inet addr:\s*((?:\d{1,3}\.){3}\d{1,3})'; + ip6_expr = 'inet6 addr:\s*((?:[0-9a-f]{0,4}:){1,7}[0-9a-f]{0,4})'; + end + nam_expr = des_expr; + fmt = '%02x:%02x:%02x:%02x:%02x:%02x'; +end + +if allMac, [mac, ind] = regexp(str, mac_expr, 'tokens', 'start'); +else, [mac, ind] = regexp(str, mac_expr, 'tokens', 'start', 'once'); +end +mac = [mac{:}]; +% if iscell(mac) && numel(ind)>1 % make mac unique +% [tmp, ia] = unique(mac); +% ia = sort(ia); % [mac, ia] = unique(mac, 'stable'); ind = ind(ia); +% mac = mac(ia); +% ind = ind(ia); +% end + +if nargout>1 && ~isempty(mac) + st = struct('FriendlyName', [], 'Description', [], 'MAC_address', mac, ... + 'IPv4_address', [], 'IPv6_address', []); + i0 = [1 regexp(str, '\n\S') numel(str)]; % split str into blocks + for i = 1:numel(ind) + j = find(i01, st = []; end + if allMac, mac = {}; end + ni = java.net.NetworkInterface.getNetworkInterfaces; + while ni.hasMoreElements + aa = ni.nextElement; + a = aa.getHardwareAddress; + if numel(a)~=6 || all(a==0), continue; end % not valid mac + a = typecast(a, 'uint8'); % from int8 + m = sprintf(fmt, a); + if nargout>1 + st(end+1).FriendlyName = char(aa.getName); %#ok + st(end).Description = char(aa.getDisplayName); + st(end).MAC_address = m; + aa = aa.getInetAddresses; + while aa.hasMoreElements + c = char(aa.nextElement); + a = regexp(c, '(\d{1,3}\.){3}\d{1,3}', 'match', 'once'); + if ~isempty(a), st(end).IPv4_address = a; end + a = regexp(c, '(([0-9a-f]{0,4}:){1,7}[0-9a-f]{0,4})', 'match', 'once'); + if ~isempty(a) + st(end).IPv6_address = strrep(a, 'fe80:0:0:0:', 'fe80::'); + end + end + end + if allMac, mac{end+1} = m; %#ok + else, mac = m; break; % done after finding 1st + end + end +end +end + +% If all attemps fail, give warning and return a random MAC +if isempty(mac) + a = zeros(1,6); + mac = sprintf(fmt, a); + if nargout>1 + st = struct('FriendlyName', [], ... + 'Description', 'Failed to find network adapter', ... + 'MAC_address', mac, 'IPv4_address', [], 'IPv6_address', []); + end + if allMac, mac = {mac}; end +end + +%% faster than system: based on https://github.com/avivrosenberg/matlab-jsystem +function [err, out] = jsystem(cmd) +% cmd is cell str, no quotation marks needed for file names with space. +try + pb = java.lang.ProcessBuilder(cmd); + pb.redirectErrorStream(true); % ErrorStream to InputStream + process = pb.start(); + scanner = java.util.Scanner(process.getInputStream).useDelimiter('\A'); + if scanner.hasNext(), out = char(scanner.next()); else, out = ''; end + err = process.exitValue; % err = process.waitFor() may hang + if err, error('java.lang.ProcessBuilder error'); end +catch % fallback to system() if java fails like for Octave + cmd = regexprep(cmd, '.+? .+', '""$0""'); % double quotes if with middle space + [err, out] = system(sprintf('%s ', cmd{:})); +end + +function [varargout] = judp(actionStr,varargin) +% +% judp.m--Uses Matlab's Java interface to handle User Datagram Protocol +% (UDP) communications with another application, either on the same +% computer or a remote one. +% +% JUDP('SEND',PORT,HOST,MSSG) sends a message to the specifed port and +% host. HOST can be either a hostname (e.g., 'www.example.com') or a string +% representation of an IP address (e.g., '192.0.34.166'). Port is an +% integer port number between 1025 and 65535. The specified port must be +% open in the receiving machine's firewall. +% +% MSSG = JUDP('RECEIVE',PORT,PACKETLENGTH) receives a message over the +% specified port. PACKETLENGTH should be set to the maximum expected +% message length to be received in the UDP packet; if too small, the +% message will be truncated. +% +% MSSG = JUDP('RECEIVE',PORT,PACKETLENGTH,TIMEOUT) attempts to receive a +% message but times out after TIMEOUT milliseconds. If TIMEOUT is not +% specified, as in the previous example, a default value is used. +% +% [MSSG,SOURCEHOST] = JUDP('RECEIVE',...) returns a string representation +% of the originating host's IP address, in addition to the received +% message. +% +% Messages sent by judp.m are in int8 format. The int8.m function can be +% used to convert integers or characters to the correct format (use +% double.m or char.m to convert back after the datagram is received). +% Non-integer values can be converted to int8 format using typecast.m (use +% typecast.m to convert back). +% +% e.g., mssg = judp('receive',21566,10); char(mssg') +% judp('send',21566,'208.77.188.166',int8('Howdy!')) +% +% e.g., [mssg,sourceHost] = judp('receive',21566,10,5000) +% judp('send',21566,'www.example.com',int8([1 2 3 4])) +% +% e.g., mssg = judp('receive',21566,200); typecast(mssg,'double') +% judp('send',21566,'localhost',typecast([1.1 2.2 3.3],'int8')) + +% Developed in Matlab 7.8.0.347 (R2009a) on GLNX86. +% Kevin Bartlett (kpb@uvic.ca), 2009-06-18 16:11 +%------------------------------------------------------------------------- + +SEND = 1; +RECEIVE = 2; +DEFAULT_TIMEOUT = 1000; % [milliseconds] + +% Handle input arguments. +if strcmpi(actionStr,'send') + action = SEND; + + if nargin < 4 + error([mfilename '.m--SEND mode requires 4 input arguments.']); + end % if + + port = varargin{1}; + host = varargin{2}; + mssg = varargin{3}; + +elseif strcmpi(actionStr,'receive') + action = RECEIVE; + + if nargin < 3 + error([mfilename '.m--RECEIVE mode requires 3 input arguments.']); + end % if + + port = varargin{1}; + packetLength = varargin{2}; + + timeout = DEFAULT_TIMEOUT; + + if nargin > 3 + % Override default timeout if specified. + timeout = varargin{3}; + end % if + +else + error([mfilename '.m--Unrecognised actionStr ''' actionStr ''.']); +end % if + +% Test validity of input arguments. +if ~isnumeric(port) || rem(port,1)~=0 || port < 1025 || port > 65535 + error([mfilename '.m--Port number must be an integer between 1025 and 65535.']); +end % if + +if action == SEND + if ~ischar(host) + error([mfilename '.m--Host name/IP must be a string (e.g., ''www.examplecom'' or ''208.77.188.166''.).']); + end % if + + if ~isa(mssg,'int8') + error([mfilename '.m--Mssg must be int8 format.']); + end % if + +elseif action == RECEIVE + + if ~isnumeric(packetLength) || rem(packetLength,1)~=0 || packetLength < 1 + error([mfilename '.m--packetLength must be a positive integer.']); + end % if + + if ~isnumeric(timeout) || timeout <= 0 + error([mfilename '.m--timeout must be positive.']); + end % if + +end % if + +% Code borrowed from O'Reilly Learning Java, edition 2, chapter 12. +import java.io.* +import java.net.DatagramSocket +import java.net.DatagramPacket +import java.net.InetAddress + +if action == SEND + try + addr = InetAddress.getByName(host); + packet = DatagramPacket(mssg, length(mssg), addr, port); + socket = DatagramSocket; + socket.setReuseAddress(1); + socket.send(packet); + socket.close; + catch + sendPacketError + try + socket.close; + catch + closeError + % do nothing. + end % try + + error('%s.m--Failed to send UDP packet.\nJava error message follows:\n%s',mfilename,sendPacketError.message); + + end % try + +else + try + socket = DatagramSocket(port); + socket.setSoTimeout(timeout); + socket.setReuseAddress(1); + packet = DatagramPacket(zeros(1,packetLength,'int8'),packetLength); + socket.receive(packet); + socket.close; + mssg = packet.getData; + mssg = mssg(1:packet.getLength); + inetAddress = packet.getAddress; + sourceHost = char(inetAddress.getHostAddress); + varargout{1} = mssg; + + if nargout > 1 + varargout{2} = sourceHost; + end % if + + catch + receiveError + + % Determine whether error occurred because of a timeout. + if ~isempty(strfind(receiveError.message,'java.net.SocketTimeoutException')) + errorStr = sprintf('%s.m--Failed to receive UDP packet; connection timed out.\n',mfilename); + else + errorStr = sprintf('%s.m--Failed to receive UDP packet.\nJava error message follows:\n%s',mfilename,receiveError.message); + end % if + + try + socket.close; + catch + closeError + % do nothing. + end % try + + error(errorStr); + + end % try + +end % if + + +","MATLAB" +"Neurology","ChristianGaser/cat12","internal/cat_vol_flipside.m",".m","2106","71","function varargout = cat_vol_flipside(job) +%_______________________________________________________________________ +% Flip x-dimension of images with GUI. +% +% varargout = cat_vol_flipside(job) +% +% job.backup .. create backupdirectory with original file +% job.labelmap .. flipping of label maps where odd values should be left +% job.negx .. negative x axis +% job.verb .. verbose output +%_______________________________________________________________________ +% Robert Dahnke +% $Id$ + + if ~exist('job','var'), job = struct(); end + + + if ~isfield(job,'data') + % GUI mode (no batch GUI prepared) + P = spm_select([1 Inf],'image','select images to flip'); + job.backup = spm_input('Backup',1,'No|Yes',[0,1],2); + job.labelmap = spm_input('Labelmap',1,'No|Yes',[0,1],1); + job.negx = spm_input('Negative x-axis',1,'No|Yes',[0,1],2); + job.verb = 1; + else + % job mode (as batch structure) + def.verb = 1; % create backup + def.backup = 1; % create backup + def.labelmap = 0; % flipping of label maps where odd values should be left + def.negx = 1; % negative x axis + job = cat_io_checkinopt(job,def); + P = char(job.data); + end + + V = spm_vol(P); Vs = V; + + for vi=1:numel(V) + Y = spm_read_vols(V(vi)); + + % flip side + Y2=Y; for z=1:size(Y,3), Y2(:,:,z) = flipud(Y(:,:,z)); end + + % flip side coding + if job.labelmap + Y2 = Y2 + (Y2>0) - 2*(mod(Y2,2)==0 & Y2>0) ; + end + + [pp,ff,ee] = spm_fileparts(V(vi).fname); + backupdir = fullfile(pp,'beforeflip'); + if ~exist(backupdir,'dir'), mkdir(backupdir); end + Vs(vi).fname = fullfile(backupdir,[ff ee]); + + if job.negx + vmat = spm_imatrix(V(vi).mat); if vmat(7)>0, vmat([1 7]) = -vmat([1 7]); end; V(vi).mat = spm_matrix(vmat); + end + + % ds('l2','',1,Y2,Y2,single(Y)/20,single(Y2)/20,50); + if job.backup, + spm_write_vol(Vs(vi),Y); + end + spm_write_vol(V(vi),Y2); + + if job.verb + fprintf('Flip %s\n',spm_file(Vs(vi).fname,'link','spm_display(''%s'')')); + end + end + + if nargout>0 + varargout{1} = Vs; + end +end","MATLAB" +"Neurology","ChristianGaser/cat12","internal/cat_stat_factorial_design.m",".m","2194","34","%----------------------------------------------------------------------- +% Job saved on 12-Feb-2018 11:14:32 by cfg_util (rev $Rev$) +% spm SPM - SPM12 (7219) +% cfg_basicio BasicIO - Unknown +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +matlabbatch{1}.spm.tools.cat.factorial_design.dir = ''; +matlabbatch{1}.spm.tools.cat.factorial_design.des.fd.fact.name = ''; +matlabbatch{1}.spm.tools.cat.factorial_design.des.fd.fact.levels = ''; +matlabbatch{1}.spm.tools.cat.factorial_design.des.fd.fact.dept = 0; +matlabbatch{1}.spm.tools.cat.factorial_design.des.fd.fact.variance = 1; +matlabbatch{1}.spm.tools.cat.factorial_design.des.fd.fact.gmsca = 0; +matlabbatch{1}.spm.tools.cat.factorial_design.des.fd.fact.ancova = 0; +matlabbatch{1}.spm.tools.cat.factorial_design.des.fd.icell.levels = ''; +matlabbatch{1}.spm.tools.cat.factorial_design.des.fd.icell.scans = ''; +matlabbatch{1}.spm.tools.cat.factorial_design.des.fd.contrasts = 0; +matlabbatch{1}.spm.tools.cat.factorial_design.cov = struct('c', {}, 'cname', {}, 'iCFI', {}, 'iCC', {}); +matlabbatch{1}.spm.tools.cat.factorial_design.multi_cov = struct('files', {}, 'iCFI', {}, 'iCC', {}); +matlabbatch{1}.spm.tools.cat.factorial_design.masking.tm.tma.athresh = 0.1; +matlabbatch{1}.spm.tools.cat.factorial_design.masking.im = 1; +matlabbatch{1}.spm.tools.cat.factorial_design.masking.em = {''}; +matlabbatch{1}.spm.tools.cat.factorial_design.globals.g_omit = 1; +matlabbatch{2}.spm.tools.cat.tools.check_SPM.spmmat(1) = cfg_dep('Factorial design specification: SPM.mat File', substruct('.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','spmmat')); +matlabbatch{2}.spm.tools.cat.tools.check_SPM.check_SPM_cov.do_check_cov.use_unsmoothed_data = 1; +matlabbatch{2}.spm.tools.cat.tools.check_SPM.check_SPM_cov.do_check_cov.adjust_data = 1; +matlabbatch{2}.spm.tools.cat.tools.check_SPM.check_SPM_ortho = 1; +","MATLAB" +"Neurology","ChristianGaser/cat12","internal/cg_create_MPM.m",".m","14321","338","function se_create_MPM + +global defaults +global st +spm_defaults + +spm_figure('GetWin','Interactive'); +Vb = spm_vol(spm_select(1,'image','Select Background',[],spm('Dir','se_anatomy'))); +AnatMask = spm_vol(spm_select(1,'image','select AnatMask')); + +MAPname = spm_input('Title of anatomical map',1,'s',''); +smooth = spm_input('Do smoothed PMaps exist ?','+1','y/n',[1,0],2); +if ~smooth; kernel = spm_input('smoothing {FWHM in mm}','+1','i',6); end +MAP = struct('name',{},'GV',{},'ref',{},'smoothed',{},'VOL',{}); + +P = spm_select(Inf,'image','select PMaps'); +V = spm_vol(P); +nrParts = length(V); + +[tmp fname] = spm_str_manip(char(V.fname),'C'); + +for i=1:nrParts + + MAP(i).ref = V(i).fname; + MAP(i).name = char(fname.m(i,:)); + MAP(i).smoothed = [MAP(i).ref(1:end-size(spm_str_manip(MAP(i).ref,'t'),2)) 's' spm_str_manip(MAP(i).ref,'t')]; +end + +if ~smooth + spm('Pointer','Watch'); + spm('FigName','Smooth: working'); + cat_progress_bar('Init',nrParts,'Smoothing','Volumes Complete'); + for i = 1:nrParts + Q = deblank(MAP(i).ref); + [pth,nm,xt,vr] = fileparts(deblank(Q)); + U = fullfile(pth,['s' nm xt vr]); + spm_smooth(Q,U,kernel); + cat_progress_bar('Set',i); + end + cat_progress_bar('Clear'); + spm('Pointer'); +end + + +count = 1; +for i=1:nrParts + Vi(i) = spm_vol(MAP(i).ref); + Vs(i) = spm_vol(MAP(i).smoothed); + MAP(i).GV = count; + count = count + 2; + fprintf('%d\t%s\n',MAP(i).GV, MAP(i).name); +end + +errorMap = se_check_PMap(Vi); +if errorMap + warning('No original PBmaps!'); +end + + +switch spm('FnBanner'); + case 'SPM2' + Vo = struct('fname', [MAPname '.img'],... + 'dim', [Vb.dim(1:3),spm_type('uint8')],... + 'mat', Vb.mat,... + 'pinfo', [1 0 0]',... + 'descrip', 'Maximum probability map'); + otherwise + Vo = struct('fname', [MAPname '.img'],... + 'dim', Vb.dim(1:3),... + 'dt', [spm_type('uint8') spm_platform('bigend')],... + 'mat', Vb.mat,... + 'pinfo', [1 0 0]',... + 'descrip', 'Maximum probability map'); +end + +dmtx = 1; hold = 0; +n = prod(size(Vi)); + +dat = spm_read_vols(Vb); + +Yp = zeros(size(dat)); + +cat_progress_bar('Init',Vo.dim(3),'MPM calculation'); +save all +for p = 1:Vo.dim(3), + if any(any(dat(:,:,p))) + M = inv(spm_matrix([0 0 -p 0 0 0 1 1 1])*inv(Vo.mat)*Vi(i).mat); + for i = 1:n + X(:,:,i) = spm_slice_vol(Vi(i),M,Vo.dim(1:2),0); + end + if any(any(sum(X,3)>75)) + [h,j] = find(max(X,[],3)>75 | sum(X,3)>125); + for px = 1:size(h,1) + if prod(size(find(X(h(px),j(px),:) == max(X(h(px),j(px),:))))) == 1 + Yp(h(px),j(px),p) = MAP(find(X(h(px),j(px),:) == max(X(h(px),j(px),:)))).GV; + else + infrage = find(X(h(px),j(px),:) == max(X(h(px),j(px),:))); + msk = [h(px)-1 j(px)-1 p-1; h(px)+0 j(px)-1 p-1; h(px)+1 j(px)-1 p-1; + h(px)-1 j(px)+0 p-1; h(px)+0 j(px)+0 p-1; h(px)+1 j(px)+0 p-1; + h(px)-1 j(px)+1 p-1; h(px)+0 j(px)+1 p-1; h(px)+1 j(px)+1 p-1; + h(px)-1 j(px)-1 p+0; h(px)+0 j(px)-1 p+0; h(px)+1 j(px)-1 p+0; + h(px)-1 j(px)+0 p+0; h(px)+0 j(px)+0 p+0; h(px)+1 j(px)+0 p+0; + h(px)-1 j(px)+1 p+0; h(px)+0 j(px)+1 p+0; h(px)+1 j(px)+1 p+0; + h(px)-1 j(px)-1 p+1; h(px)+0 j(px)-1 p+1; h(px)+1 j(px)-1 p+1; + h(px)-1 j(px)+0 p+1; h(px)+0 j(px)+0 p+1; h(px)+1 j(px)+0 p+1; + h(px)-1 j(px)+1 p+1; h(px)+0 j(px)+1 p+1; h(px)+1 j(px)+1 p+1;]'; + surround = []; + for area = 1:size(infrage,1) + sx = spm_sample_vol(Vi(infrage(area)),msk(1,:),msk(2,:),msk(3,:),0); + sx(sx==0) = NaN; + surround(area) = mean(sx(~isnan(sx))); + end + if prod(size(find(surround == max(surround)))) == 1 + Yp(h(px),j(px),p) = MAP(infrage(find(surround == max(surround)))).GV; + else + infrage = infrage(find(surround == max(surround))); + sX = []; for i=1:prod(size(infrage)); sX(i) = spm_sample_vol(Vs(infrage(i)),h(px),j(px),p,0); end + if prod(size(infrage(find(sX == max(sX))))) == 1 + Yp(h(px),j(px),p) = MAP(infrage(find(sX == max(sX)))).GV; + else + infrage = infrage(find(sX == max(sX))); + msk = [h(px)-1 j(px)-1 p-1; h(px)+0 j(px)-1 p-1; h(px)+1 j(px)-1 p-1; + h(px)-1 j(px)+0 p-1; h(px)+0 j(px)+0 p-1; h(px)+1 j(px)+0 p-1; + h(px)-1 j(px)+1 p-1; h(px)+0 j(px)+1 p-1; h(px)+1 j(px)+1 p-1; + h(px)-1 j(px)-1 p+0; h(px)+0 j(px)-1 p+0; h(px)+1 j(px)-1 p+0; + h(px)-1 j(px)+0 p+0; h(px)+0 j(px)+0 p+0; h(px)+1 j(px)+0 p+0; + h(px)-1 j(px)+1 p+0; h(px)+0 j(px)+1 p+0; h(px)+1 j(px)+1 p+0; + h(px)-1 j(px)-1 p+1; h(px)+0 j(px)-1 p+1; h(px)+1 j(px)-1 p+1; + h(px)-1 j(px)+0 p+1; h(px)+0 j(px)+0 p+1; h(px)+1 j(px)+0 p+1; + h(px)-1 j(px)+1 p+1; h(px)+0 j(px)+1 p+1; h(px)+1 j(px)+1 p+1;]'; + surround = []; + for area = 1:size(infrage,1) + sx = spm_sample_vol(Vs(infrage(area)),msk(1,:),msk(2,:),msk(3,:),0); + sx(sx==0) = NaN; + surround(area) = mean(sx(~isnan(sx))); + end + if prod(size(find(surround == max(surround)))) == 1 + Yp(h(px),j(px),p) = MAP(infrage(find(surround == max(surround)))).GV; + else + whos + infrage(1) + Yp(h(px),j(px),p) = MAP(infrage(1)).GV; + end + end + end + end + end + end + end + cat_progress_bar('Set',p); +end +cat_progress_bar('Clear') + + +out = Yp; +clear X; +cat_progress_bar('Init',Vo.dim(3),'Filter 1'); +for z=2:Vb.dim(3)-1, + cat_progress_bar('Set',z); + [h,j] = find(Yp(:,:,z)<100 & Yp(:,:,z)>0); + for px = 1:size(h,1) + x=h(px); y=j(px); p = z; + surround = Yp(x-1:x+1,y-1:y+1,z-1:z+1); + if sum(surround > 99)>13 + sux = []; for i=unique(surround(surround>0))'; sux(find([MAP.GV] == i)) = sum(surround == i); end + if (any(sux>13)), out(x,y,z) = MAP(find(sux == max(sux))).GV; + else + X = []; + for i=1:n; X(i) = spm_sample_vol(Vi(i),x,y,z,0); end + if sum(X == max(X)) == 1, out(x,y,z) = MAP(find(X == max(X))).GV; + else + infrage = find(X == max(X)); surround = []; + msk = [h(px)-1 j(px)-1 p-1; h(px)+0 j(px)-1 p-1; h(px)+1 j(px)-1 p-1; h(px)-1 j(px)+0 p-1; h(px)+0 j(px)+0 p-1; h(px)+1 j(px)+0 p-1; + h(px)-1 j(px)+1 p-1; h(px)+0 j(px)+1 p-1; h(px)+1 j(px)+1 p-1; h(px)-1 j(px)-1 p+0; h(px)+0 j(px)-1 p+0; h(px)+1 j(px)-1 p+0; + h(px)-1 j(px)+0 p+0; h(px)+0 j(px)+0 p+0; h(px)+1 j(px)+0 p+0; h(px)-1 j(px)+1 p+0; h(px)+0 j(px)+1 p+0; h(px)+1 j(px)+1 p+0; + h(px)-1 j(px)-1 p+1; h(px)+0 j(px)-1 p+1; h(px)+1 j(px)-1 p+1; h(px)-1 j(px)+0 p+1; h(px)+0 j(px)+0 p+1; h(px)+1 j(px)+0 p+1; + h(px)-1 j(px)+1 p+1; h(px)+0 j(px)+1 p+1; h(px)+1 j(px)+1 p+1;]'; + for area = 1:size(infrage,1) + sx = spm_sample_vol(Vi(infrage(area)),msk(1,:),msk(2,:),msk(3,:),0); + sx(sx==0) = NaN; surround(area) = mean(sx(~isnan(sx))); + end + if sum(surround == max(surround)) == 1 + out(x,y,z) = MAP(infrage(find(surround == max(surround)))).GV; + else, sX = []; + infrage = infrage(find(surround == max(surround))); + for i=1:numel(infrage); sX(i) = spm_sample_vol(Vs(infrage(i)),h(px),j(px),p,0); end + if prod(size(infrage(find(sX == max(sX))))) == 1 + out(x,y,z) = MAP(infrage(find(sX == max(sX)))).GV; + else + infrage = infrage(find(sX == max(sX))); + msk = [h(px)-1 j(px)-1 p-1; h(px)+0 j(px)-1 p-1; h(px)+1 j(px)-1 p-1; h(px)-1 j(px)+0 p-1; h(px)+0 j(px)+0 p-1; h(px)+1 j(px)+0 p-1; + h(px)-1 j(px)+1 p-1; h(px)+0 j(px)+1 p-1; h(px)+1 j(px)+1 p-1; h(px)-1 j(px)-1 p+0; h(px)+0 j(px)-1 p+0; h(px)+1 j(px)-1 p+0; + h(px)-1 j(px)+0 p+0; h(px)+0 j(px)+0 p+0; h(px)+1 j(px)+0 p+0; h(px)-1 j(px)+1 p+0; h(px)+0 j(px)+1 p+0; h(px)+1 j(px)+1 p+0; + h(px)-1 j(px)-1 p+1; h(px)+0 j(px)-1 p+1; h(px)+1 j(px)-1 p+1; h(px)-1 j(px)+0 p+1; h(px)+0 j(px)+0 p+1; h(px)+1 j(px)+0 p+1; + h(px)-1 j(px)+1 p+1; h(px)+0 j(px)+1 p+1; h(px)+1 j(px)+1 p+1;]'; surround = []; + for area = 1:size(infrage,1) + sx = spm_sample_vol(Vs(infrage(area)),msk(1,:),msk(2,:),msk(3,:),0); + sx(sx==0) = NaN; surround(area) = mean(sx(~isnan(sx))); + end + if prod(size(infrage(find(surround == max(surround))))) == 1 + out(x,y,z) = MAP(infrage(find(surround == max(surround)))).GV; + end + end + end + end + end + end + end +end +cat_progress_bar('Clear') + + +Yp = out; + +clear X; +cat_progress_bar('Init',Vo.dim(3),'Filter 2'); +for z=2:Vb.dim(3)-1, + cat_progress_bar('Set',z); + [h,j] = find(Yp(:,:,z)>100); + for px = 1:size(h,1) + x=h(px); y=j(px); p = z; + surround = Yp(x-1:x+1,y-1:y+1,z-1:z+1); + if prod(size(find(surround > 99)))>16 + sux = []; for i=unique(surround(surround>0))'; sux(find([MAP.GV] == i)) = prod(size(find(surround == i))); end + if (any(sux>16)), + out(x,y,z) = MAP(find(sux == max(sux))).GV; + end + end + end +end +cat_progress_bar('Clear') + + +hemi = spm_read_vols(AnatMask); +ind_hemi = find(hemi>0); +% add 1 for left hemisphere +out(ind_hemi) = out(ind_hemi) + round(hemi(ind_hemi)) - 1; + +mat = Vo.mat; M = Vo.mat; +Vo = spm_create_vol(Vo); for p=1:Vo.dim(3), Vo = spm_write_plane(Vo,out(:,:,p),p); end; save([MAPname '.mat'],'mat','M'); +switch spm('FnBanner'); + case 'SPM2' + Vo= spm_close_vol(Vo); + otherwise +end + + +MAP(1).MaxMap = Vo; + +for locNr=1:size(MAP,2) + MAP(locNr).XYZ = []; + for z=1:Vb.dim(3) + if any(any(out(:,:,z) == MAP(locNr).GV)) + [x, y] = find(out(:,:,z) == MAP(locNr).GV); + MAP(locNr).XYZ = [MAP(locNr).XYZ [x y z*ones(size(x,1),1)]']; + end + end + MAP(locNr).XYZmm = []; + MAP(locNr).XYZmm(1,:) = MAP(locNr).XYZ(1,:)+MAP(1).MaxMap.mat(1,4); + MAP(locNr).XYZmm(2,:) = MAP(locNr).XYZ(2,:)+MAP(1).MaxMap.mat(2,4); + MAP(locNr).XYZmm(3,:) = MAP(locNr).XYZ(3,:)+MAP(1).MaxMap.mat(3,4); +end + +MAP(1).orient = 1; + +cat_progress_bar('Init',size(MAP,2),'PMap'); +for p = 1:size(MAP,2) + MAP(p).Z = spm_sample_vol(spm_vol(MAP(p).ref),MAP(p).XYZ(1,:),MAP(p).XYZ(2,:),MAP(p).XYZ(3,:),0); + cat_progress_bar('Set',p); +end +cat_progress_bar('clear'); + +%AnatMask = spm_vol([spm('Dir','se_anatomy') filesep 'AnatMask.img']); +for i=1:size(MAP,2) + tmp = spm_sample_vol(AnatMask,MAP(i).XYZ(1,:),MAP(i).XYZ(2,:),MAP(i).XYZ(3,:),0); + MAP(i).LR = zeros(size(MAP(i).Z)); + MAP(i).LR(tmp == 2) = -1; + MAP(i).LR(tmp == 1) = 1; + MAP(i).VOL = [size(find(tmp == 2),2) size(find(tmp == 1),2)]; +end + + + +for i=1:size(MAP,2); MAP(i).PMap = spm_vol([spm('Dir','se_anatomy') filesep 'PMaps' filesep spm_str_manip(MAP(i).ref,'t')]); end + +spm_figure('GetWin','Interactive'); +cat_progress_bar('Init',size(MAP,2),'Preparing data'); +for m=1:size(MAP,2) + MAP(m).allXYZ = []; + MAP(m).allZ = []; + dat = spm_read_vols(MAP(m).PMap); + for p = 1:MAP(m).PMap.dim(3) + [i,j,z] = find(dat(:,:,p)); + if any(i), MAP(m).allXYZ = [MAP(m).allXYZ [i'; j'; p*ones(1,length(i))]]; MAP(m).allZ = [MAP(m).allZ (z')/25]; end + end + MAP(m).allLR = spm_get_data(AnatMask,MAP(m).allXYZ); + MAP(m).allLR(MAP(m).allLR == 2) = -1; + cat_progress_bar('Set',m); +end +spm_figure('Clear','Interactive'); + +MAP = rmfield(MAP,'PMap'); + +try + load(fullfile(spm('Dir','se_anatomy'),'cmap2.mat')); + MAP(1).cmap = cmap; +end + +try + load(fullfile(spm('Dir','spm'),'rend','render_single_subj.mat')); + if (exist('rend') ~= 1), % Assume old format... + rend = cell(size(Matrixes,1),1); + for i=1:size(Matrixes,1), + rend{i}=struct('M',eval(Matrixes(i,:)),... + 'ren',eval(Rens(i,:)),... + 'dep',eval(Depths(i,:))); + rend{i}.ren = rend{i}.ren/max(max(rend{i}.ren)); + end; + end; + + for i=1:length(rend), + rend{i}.max=0; + rend{i}.data = cell(1,1); + if issparse(rend{i}.ren), + d = size(rend{i}.ren); + B1 = spm_dctmtx(d(1),d(1)); + B2 = spm_dctmtx(d(2),d(2)); + rend{i}.ren = B1*rend{i}.ren*B2'; + rend{i}.dep = exp(B1*rend{i}.dep*B2')-1; + end; + msk = find(rend{i}.ren>1);rend{i}.ren(msk)=1; + msk = find(rend{i}.ren<0);rend{i}.ren(msk)=0; + end; + MAP(1).rend = rend; +end + +save([MAPname '_MPM.mat'],'MAP') +","MATLAB" +"Neurology","ChristianGaser/cat12","internal/cat_tst_BWP.m",".m","9259","235","function cat_tst_BWP(Pmethod,Presdir0,datas,fast) +% +% cat_tst_BWP(Pmethod,Presdir) +% +% See cat_tst_main. +% + +% TODO: +% * separate evaluation of 1mm case and all 5 resolution cases +% > overlap measures? stat tests? +% +% - addapt fontsize with more figures +% - single plot of each subfigure? +% - overlapping plot not really helpful for mor than 6 cases > skip +% - overlapping plot miss labels +% - missed data -> missed method (add print) + +%#ok<*SAGROW +Presdir = fullfile(Presdir0,'BWP'); +if ~exist(Presdir,'dir'), mkdir(Presdir); end +if ~exist('datas','var'), datas = {'thickness','pbt'}; end + +% find surface data (texture) for analysis +tcase = {'100mm','mm'}; fasti = 2-fast; +for datasi = 1:numel(datas) + % get files from the Bestoff or Phantom (multiple resolutions) directoy + Pdata = cell(size(Pmethod,1),1); + for pi = 1:size(Pmethod,1) + if fasti == 2 && exist( fullfile(Pmethod{pi,2},'07_Phantoms') ,'dir') + Pdata{pi} = cat_vol_findfiles( fullfile(Pmethod{pi,2},'07_Phantoms') , sprintf( 'lh.%s.BWPT*%s' ,datas{datasi},tcase{fasti}) ); + elseif exist( fullfile(Pmethod{pi,2},'01_Bestoff') ,'dir') + Pdata{pi} = cat_vol_findfiles( fullfile(Pmethod{pi,2},'01_Bestoff') , sprintf( 'lh.%s.BWPT*%s' ,datas{datasi},tcase{fasti}) ); + elseif exist( Pmethod{pi,2} ,'dir') + Pdata{pi} = cat_vol_findfiles( Pmethod{pi,2} , sprintf( 'lh.%s.BWPT*%s',datas{datasi},tcase{fasti}) ); + else + error('ERROR: Miss startfolder: %s\n',Pmethod{pi,2} ); + end + end + + + %% plot histogram + if fasti == 1 + % just one case + Pdata = cellfun(@(x) char(x), Pdata, 'UniformOutput', false); + cph = cat_plot_histogram(char(Pdata), struct('color',cell2mat(Pmethod(:,3)))); + yrange = round( get(get(cph(1),'Parent'),'YLim')*1.5 / 2,2)*2; + else + % extend version for multiple intput datasets per method (resolution levels) + + % get main plot to set up range + Pdatatmp = [Pdata{:}]; Pdatatmp = Pdatatmp(1:6:end); + cph = cat_plot_histogram(char(Pdatatmp), struct('color',cell2mat(Pmethod(:,3)))); + ax0 = cph.Parent; fg0 = ax0(1).Parent; fg0.Visible = false; + %yrange = round( get(get(cph(1),'Parent'),'YLim')/2,2); + yrange = [0. .03]; + + for pi = 1:size(Pmethod,1) + %% get basic plot + cphpi{pi} = cat_plot_histogram(char(Pdata{pi}), struct('color',jet(numel(Pdata{pi})))); + ax1 = cphpi{pi}.Parent; fg1 = ax1(1).Parent; fg1.Visible = false; + + % optimize plot + orgax = get(cphpi{pi}(1),'parent'); + delete(findobj(orgax.Children,'DisplayName','')) + orgax.FontSize = 13; + hdata = reshape( [cphpi{pi}(:).YData], numel( cphpi{pi}(1).YData ), numel(cphpi{pi}) )'; + hdatamn = mean( hdata ); + hold on + pmn = plot( cphpi{pi}(1).XData , hdatamn,'-'); pmn.Color = [0 0 0]; pmn.LineWidth = 2; + orgfig = get(orgax(1),'parent'); + xlim(orgax,[0,4]); ylim(orgax,yrange); + orgax.XTick = .5:.5:3.5; + grid(orgax,'on'); box(orgax,'on'); + ylabel(datas{datasi}); + xlabel('thickness (mm)'); + title(orgax,Pmethod(pi,1)); + legend({'0.7 mm','1.00 mm','1.25 mm','1.50 mm','1.75 mm','2.00 mm','average'}); + ff = sprintf('cat_tst_BWP_multires%d_plot3_%s_%s',fasti-1,datas{datasi},Pmethod{pi,1}); + print(orgfig(1),fullfile(Presdir,ff),'-r300','-dpng'); + + cph(pi).XData = cphpi{pi}(:).XData; + cph(pi).YData = mean( hdata ); + cph(pi).Color = Pmethod{pi,3}; + + end + + end + + + + %% create two figures: + % fi==1 with subplots for all figures + % fi==2 with all methods in one figure (not so usefull) + fi=1; si = 1; %#ok + for fi = 1 % :2 + %% + fh = figure(394); clf(fh); set(fh,'Visible',false); + if fi==1 + subplots = size(Pmethod,1); + xt = ceil(size(Pmethod,1) .^ .5 * 2/3); + if size(Pmethod,1)>6 & size(Pmethod,1)<13, xt = 2; end + tiledlayout(xt, ceil(size(Pmethod,1) / xt), ... + 'TileSpacing', 'compact', 'Padding', 'compact'); + else + subplots = 1; + end + fh.Position(3:4) = [200 300] .* [ceil(size(Pmethod,1) / xt),xt]; + %% + for si = 1:subplots + if fi==1 + ax = nexttile; hold on; + spi = si; + copyobj( cphpi{si}, ax); + lh = ax.Children; + mh = copyobj( cph(si), ax); + set(lh,'Color',min(1,.85 + cph(si).Color*0.15)) + set(mh,'LineWidth',1.5); + + close(get(get(cphpi{si}(1),'parent'),'parent')); + else + % single print on one figure + ax = axes; + spi = 1:size(Pmethod,1); + orgax = allchild( get(cph(1),'parent') ); + copyobj( orgax(numel(orgax)/2+1:numel(orgax)) , ax); + ax.FontSize = 13; + % add marker for highest value + hold on; + axC = flip( ax.Children); % reverse order + for axci = 1:numel(axC) + [maxy,maxxi] = max(axC(axci).YData); + maxx = axC(axci).XData(maxxi); + plx = plot(maxx,maxy); + plx.Color = Pmethod{axci,3}; + plx.Marker = Pmethod{axci,4}; + plx.MarkerEdgeColor = plx.Color; + plx.MarkerFaceColor = plx.Color; + end + + end + + + %% + xlim(ax,[1,3]); ylim(ax,yrange); + ax.XTick = 1:.5:3; + grid(ax,'on'); box(ax,'on'); + ylabel(datas{datasi}); + xlabel('thickness (mm)'); + if fi==1 + title(ax,sprintf('BWPT-%s',Pmethod{si,1})); + md = zeros(1,3); std = md; pk = md; + else + title(ax,'Brain Web Phantom Thickness'); + md = zeros(size(Pmethod,1),3); std = md; pk = md; + end + + + %% estimate some numbers + for pi = spi + if fasti == 1 + cdata{pi} = [ + cat_io_FreeSurfer('read_surf_data',Pdata{pi}); + cat_io_FreeSurfer('read_surf_data',strrep(Pdata{pi},[filesep 'lh'],[filesep 'rh']))]; %#ok + else + if 0 + cdata{pi} = cph(pi).YData; + else + cdata{pi} = []; + for xi = 1:numel(Pdata{pi}) + cdata{pi} = [ cdata{pi} ; + cat_io_FreeSurfer('read_surf_data',Pdata{pi}{xi}); + cat_io_FreeSurfer('read_surf_data',strrep(Pdata{pi}{xi},[filesep 'lh'],[filesep 'rh']))]; + end + end + end + tval = 1.5:0.5:2.5; d=cell(1,3); xp = zeros(1,3); + for di = 1:3 + range = [tval(di)-0.2 tval(di)+0.2]; + d{di} = smooth( cph(pi).YData( cph(pi).XData(:)>range(1) & cph(pi).XData(:)0.5 & cdata{pi}<2.9) ,3); + [pk(pi,di), xp(di)] = max( d{di} ); + pkv(pi,di) = cph(pi).XData(xp(di) + nnz( cph(pi).XData(:) + pkx(pi,di) = abs(pkv(pi,di) - tval(di)); %#ok + px(pi,di) = cph(pi).XData(xp(di) + nnz( cph(pi).XData(:) + if fi==1 + plot(ax, repmat( cph(pi).XData(xp(di) + nnz( cph(pi).XData(:) + close(get(get(cph(1),'parent'),'parent')); + end +end + +%% + +close(fh); + +","MATLAB" +"Neurology","ChristianGaser/cat12","internal/cat_vol_cMRegularizarNLM3Dw.c",".c","8645","344","/************************************************************************** +% +% Jose V. Manjon - jmanjon@fis.upv.es +% Universidad Politecinca de Valencia, Spain +% Pierrick Coupe - pierrick.coupe@gmail.com +% Brain Imaging Center, Montreal Neurological Institute. +% Mc Gill University +% +% Copyright (C) 2010 Jose V. Manjon and Pierrick Coupe +% +% +**************************************************************************/ + +#include ""math.h"" +#include ""mex.h"" +#include +#include ""matrix.h"" +// undef needed for LCC compiler +#undef EXTERN_C +#include +#include + +typedef struct{ + int rows; + int cols; + int slices; + double * in_image; + double * out_image; + double * mean_image; + double * pesos; + int ini; + int fin; + int radio; + int f; + int th; + int sigma; +}myargument; + + +double distancia(double* ima,int x,int y,int z,int nx,int ny,int nz,int f,int sx,int sy,int sz) +{ +double d,acu,distancetotal; +int i,j,k,ni1,nj1,ni2,nj2,nk1,nk2; + +distancetotal=0; + +for(k=-f;k<=f;k++) +{ + nk1=z+k; + nk2=nz+k; + if(nk1<0) nk1=-nk1; + if(nk2<0) nk2=-nk2; + if(nk1>=sz) nk1=2*sz-nk1-1; + if(nk2>=sz) nk2=2*sz-nk2-1; + + for(j=-f;j<=f;j++) + { + nj1=y+j; + nj2=ny+j; + if(nj1<0) nj1=-nj1; + if(nj2<0) nj2=-nj2; + if(nj1>=sy) nj1=2*sy-nj1-1; + if(nj2>=sy) nj2=2*sy-nj2-1; + + for(i=-f;i<=f;i++) + { + ni1=x+i; + ni2=nx+i; + if(ni1<0) ni1=-ni1; + if(ni2<0) ni2=-ni2; + if(ni1>=sx) ni1=2*sx-ni1-1; + if(ni2>=sx) ni2=2*sx-ni2-1; + + distancetotal = distancetotal + ((ima[nk1*(sx*sy)+(nj1*sx)+ni1]-ima[nk2*(sx*sy)+(nj2*sx)+ni2])*(ima[nk1*(sx*sy)+(nj1*sx)+ni1]-ima[nk2*(sx*sy)+(nj2*sx)+ni2])); + } + } +} + +acu=(2*f+1)*(2*f+1)*(2*f+1); +d=distancetotal/acu; + +return d; + +} + +unsigned __stdcall ThreadFunc( void* pArguments ) +{ + double *ima,*fima,*medias,*pesos,w,d,hh,th,t1; + int ii,jj,kk,ni,nj,nk,i,j,k,ini,fin,rows,cols,slices,v,p,p1,f,rc; + + myargument arg; + arg=*(myargument *) pArguments; + + rows=arg.rows; + cols=arg.cols; + slices=arg.slices; + ini=arg.ini; + fin=arg.fin; + ima=arg.in_image; + fima=arg.out_image; + medias=arg.mean_image; + pesos=arg.pesos; + v=arg.radio; + f=arg.f; + th=arg.th; + hh=arg.sigma; + rc=rows*cols; + + /* filter*/ + for(k=ini;k=0 && nj>=0 && nk>=0 && nith) continue; + + d=distancia(ima,i,j,k,ni,nj,nk,f,cols,rows,slices); + + d=d/hh-1; + if(d<0) d=0; + + w = exp(-d); + + fima[p] = fima[p] + w*ima[p1]; + pesos[p] = pesos[p] + w; + + fima[p1] = fima[p1] + w*ima[p]; + pesos[p1] = pesos[p1] + w; + } + } + } + } + } + } + } + + _endthreadex( 0 ); + return 0; +} + + + +void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) +{ + +/*Declarations*/ +const mxArray *xData; +double *ima, *fima,*pesos,*lf; +const mxArray *Mxmedias,*Mxpesos,*xtmp; +double *medias,*tmp; +const mxArray *pv; +double off,h,media,th,hh; +int ini,fin,i,j,k,ii,jj,kk,ni,nj,nk,v,ndim,indice,f,Nthreads,rc,ft; +const int *dims; +int fac[3]; +bool salir; + +myargument *ThreadArgs; +HANDLE *ThreadList; // Handles to the worker threads + +if(nrhs<5) +{ + printf(""Wrong number of arguments!!!\r""); + return; +} + +/*Copy input pointer x*/ +xData = prhs[0]; + +/*Get matrix x*/ +ima = mxGetPr(xData); + +ndim = mxGetNumberOfDimensions(prhs[0]); +dims= mxGetDimensions(prhs[0]); + +pv = prhs[1]; +v = (int)(mxGetScalar(pv)); +pv = prhs[2]; +f = (int)(mxGetScalar(pv)); +pv = prhs[3]; +h = (double)(mxGetScalar(pv)); +hh=2*h*h; +pv = prhs[4]; +lf = (double*)(mxGetPr(pv)); +for(i=0;i<3;i++) fac[i]=(int)lf[i]; + +/*Allocate memory and assign output pointer*/ + +plhs[0] = mxCreateNumericArray(ndim,dims,mxDOUBLE_CLASS, mxREAL); +Mxmedias = mxCreateNumericArray(ndim,dims,mxDOUBLE_CLASS, mxREAL); +xtmp = mxCreateNumericArray(ndim,dims,mxDOUBLE_CLASS, mxREAL); +tmp = mxGetPr(xtmp); + +/*Get a pointer to the data space in our newly allocated memory*/ +fima = mxGetPr(plhs[0]); +medias = mxGetPr(Mxmedias); + +Mxpesos = mxCreateNumericArray(ndim,dims,mxDOUBLE_CLASS, mxREAL); +pesos = mxGetPr(Mxpesos); + +rc=dims[0]*dims[1]; +for(k=0;k=dims[0]) ni=2*dims[0]-ni-1; + for(jj=-1;jj<=1;jj++) + { + nj=j+jj; + if(nj<0) nj=-nj; + if(nj>=dims[1]) nj=2*dims[1]-nj-1; + for(kk=-1;kk<=1;kk++) + { + nk=k+kk; + if(nk<0) nk=-nk; + if(nk>=dims[2]) nk=2*dims[2]-nk-1; + + media = media + ima[nk*rc+nj*dims[0]+ni]; + } + } + } + medias[k*rc+j*dims[0]+i]=media/27; + } +} +} + +ft=fac[2]*fac[1]*fac[0]; +for(k=0;k1000); % paralize only large amounts + + + % resdir settings + resdir = fullfile(Presdir, sprintf('%s_%s_aging_N%d',dataname,Pmethod,numel(age))); + if exist(resdir,'dir'), cd('..'); rmdir(resdir,'s'); end + mkdir(resdir); + cd(resdir) + + + if exist('sub','var') + save(fullfile(resdir,'cat_tst_ana_input.mat'), ... + 'files', 'Presdir', 'Pmethod', 'dataname', 'age', 'sex', 'cohort', 'tiv', 'order', 'sub'); + else + save(fullfile(resdir,'cat_tst_ana_input.mat'), ... + 'files', 'Presdir', 'Pmethod', 'dataname', 'age', 'sex', 'cohort', 'tiv', 'order'); + end + + % avoid/reduce additional reprocessing + mi = 1; + [~,ff,ee] = spm_fileparts(files{1}); + if strcmp(ee,'.gz'), [~,~,ee2] = spm_fileparts(ff); ee=[ee2 ee]; end + if strcmp(ee,'.nii.gz') + files2 = spm_str_manip(files,'r'); + sexist = cellfun( @(x) exist(x,'file'), files2); + % gunzip is not working on my computer whyever ""An internal error has occurred."" + %gunzip( ( files(sexist==0)) ) + files3 = files(sexist==0); + if ~isempty(files3) + fprintf('gunzip files!\n'); + for fi = 1:numel(files3) + fprintf(' %s\n',files3{fi}); + if ~exist(spm_str_manip(files3{fi},'r'),'file') + system(sprintf('gunzip -k %s',files3{fi})); + end + end + fprintf('done\n'); + end + clear files3 + files = spm_str_manip(files,'r'); ee = '.nii'; + end + if strcmp(ee,'.nii') || strcmp(ee,'.nii.gz') + isvol = 1; + % define smoothed names + sfiles = spm_file(files,'prefix','s'); + sexist = cellfun( @(x) exist(x,'file'), sfiles); + files( sexist>0 ) = []; + + % smoothing + if ~isempty(files) && ~onlyAllreadySmoothed + matlabbatch{mi}.spm.spatial.smooth.data = files; + matlabbatch{mi}.spm.spatial.smooth.fwhm = repmat(smoothingVS(1),1,3); + matlabbatch{mi}.spm.spatial.smooth.dtype = 2; + matlabbatch{mi}.spm.spatial.smooth.im = 0; + matlabbatch{mi}.spm.spatial.smooth.prefix = 's'; + mi = mi+1; + else + nocohort = sexist==0; + cohort(nocohort) = []; + sfiles(nocohort) = []; + age(nocohort) = []; + sex(nocohort) = []; + tiv(nocohort) = []; + if exist('sub','var'), sub(nocohort) = []; end + end + else + %% defined names + isvol = 0; + pid = strfind(files{1},[filesep 'lh.'])+4; + pid2 = strfind(files{1}(pid:end),'.'); + sdata = files{1}(pid:pid + pid2(1)-2); + sfiles = cat_io_strrep(files, sprintf('lh.%s.',sdata), sprintf('mesh.%s.resampled_32k.',sdata)); + sfiles = spm_file(sfiles,'prefix',sprintf('s%d.',smoothingVS(2))); + sfiles = strcat(sfiles,'.gii'); + sexist = cellfun( @(x) exist(x,'file'), sfiles); + files( sexist>0 ) = []; + + % resample & smooth + if ~isempty(files) && ~onlyAllreadySmoothed + if expert < 1 + matlabbatch{mi}.spm.tools.cat.stools.surfresamp.data_surf = files; + else + matlabbatch{mi}.spm.tools.cat.stools.surfresamp.sample{1}.data_surf = files; + end + matlabbatch{mi}.spm.tools.cat.stools.surfresamp.merge_hemi = 1; + matlabbatch{mi}.spm.tools.cat.stools.surfresamp.mesh32k = 1; + matlabbatch{mi}.spm.tools.cat.stools.surfresamp.fwhm_surf = 12; + matlabbatch{mi}.spm.tools.cat.stools.surfresamp.lazy = 2; + matlabbatch{mi}.spm.tools.cat.stools.surfresamp.nproc = nprog; + mi = mi+1; + else + nocohort = sexist==0; + sfiles(nocohort) = []; + cohort(nocohort) = []; + age(nocohort) = []; + sex(nocohort) = []; + tiv(nocohort) = []; + if exist('sub','var'), sub(nocohort) = []; end + end + end + + % not working + if isempty(sfiles), matlabbatch = {}; return; end + + + % nonlinear aging + page = cat_stat_polynomial(age,order); + + + + % statistic design + mistat = mi; + if exist('sub','var') + usesex = 0; + matlabbatch{mi}.spm.tools.cat.factorial_design.dir = { resdir }; + % + matlabbatch{mi}.spm.tools.cat.factorial_design.des.fblock.fac(1).name = 'subject'; + matlabbatch{mi}.spm.tools.cat.factorial_design.des.fblock.fac(1).dept = 0; + matlabbatch{mi}.spm.tools.cat.factorial_design.des.fblock.fac(1).variance = 1; + matlabbatch{mi}.spm.tools.cat.factorial_design.des.fblock.fac(1).gmsca = 0; + matlabbatch{mi}.spm.tools.cat.factorial_design.des.fblock.fac(1).ancova = 0; + % + matlabbatch{mi}.spm.tools.cat.factorial_design.des.fblock.fac(2).name = 'time'; + matlabbatch{mi}.spm.tools.cat.factorial_design.des.fblock.fac(2).dept = 1; + matlabbatch{mi}.spm.tools.cat.factorial_design.des.fblock.fac(2).variance = 1; + matlabbatch{mi}.spm.tools.cat.factorial_design.des.fblock.fac(2).gmsca = 0; + matlabbatch{mi}.spm.tools.cat.factorial_design.des.fblock.fac(2).ancova = 0; + % add data + for si = 1:max(sub) + matlabbatch{mi}.spm.tools.cat.factorial_design.des.fblock.fsuball.fsubject(si).scans = sfiles( sub == si ); % subject + matlabbatch{mi}.spm.tools.cat.factorial_design.des.fblock.fsuball.fsubject(si).conds = 1:sum( sub == si ); % timepoint + end + %matlabbatch{mi}.spm.tools.cat.factorial_design.des.fblock.maininters = {}; + matlabbatch{mi}.spm.tools.cat.factorial_design.des.fblock.maininters{1}.fmain.fnum = 2; + matlabbatch{mi}.spm.tools.cat.factorial_design.des.fblock.maininters{2}.fmain.fnum = 1; + % experimental + matlabbatch{mi}.spm.tools.cat.factorial_design.des.fblock.voxel_cov.files = {''}; + matlabbatch{mi}.spm.tools.cat.factorial_design.des.fblock.voxel_cov.iCFI = 1; + matlabbatch{mi}.spm.tools.cat.factorial_design.des.fblock.voxel_cov.iCC = 1; + matlabbatch{mi}.spm.tools.cat.factorial_design.des.fblock.voxel_cov.globals.g_omit = 1; + matlabbatch{mi}.spm.tools.cat.factorial_design.des.fblock.voxel_cov.consess = {}; + % confounds > subject initial state or timediff? + %matlabbatch{mi}.spm.tools.cat.factorial_design.cov = struct('c', {}, 'cname', {}, 'iCFI', {}, 'iCC', {}); + matlabbatch{mi}.spm.tools.cat.factorial_design.cov = struct('c', age, 'cname', 'age', 'iCFI', {}, 'iCC', 1); + matlabbatch{mi}.spm.tools.cat.factorial_design.multi_cov = struct('files', {}, 'iCFI', {}, 'iCC', {}); + matlabbatch{mi}.spm.tools.cat.factorial_design.masking.tm.tm_none = 1; + matlabbatch{mi}.spm.tools.cat.factorial_design.masking.im = 0; + matlabbatch{mi}.spm.tools.cat.factorial_design.masking.em = {''}; + if isvol + matlabbatch{mi}.spm.tools.cat.factorial_design.globals.g_ancova.global_uval = tiv; + else + matlabbatch{mi}.spm.tools.cat.factorial_design.globals.g_omit = 1; + end + matlabbatch{mi}.spm.tools.cat.factorial_design.check_SPM.check_SPM_zscore.do_check_zscore.use_unsmoothed_data = 1; + matlabbatch{mi}.spm.tools.cat.factorial_design.check_SPM.check_SPM_zscore.do_check_zscore.adjust_data = 1; + matlabbatch{mi}.spm.tools.cat.factorial_design.check_SPM.check_SPM_ortho = 1; + else + if isscalar( numel( cohortid ) ) + % regression analysis + matlabbatch{mi}.spm.tools.cat.factorial_design.dir = { resdir }; + matlabbatch{mi}.spm.tools.cat.factorial_design.des.mreg.scans = sfiles; + % age + if order==1 + matlabbatch{mi}.spm.tools.cat.factorial_design.des.mreg.mcov.c = age; + matlabbatch{mi}.spm.tools.cat.factorial_design.des.mreg.mcov.cname = 'age'; + matlabbatch{mi}.spm.tools.cat.factorial_design.des.mreg.mcov.iCC = 1; + else + for pagei = 1:order + matlabbatch{mi}.spm.tools.cat.factorial_design.des.mreg.mcov(pagei).c = page(:,1); + matlabbatch{mi}.spm.tools.cat.factorial_design.des.mreg.mcov(pagei).cname = sprintf('age^%d',pagei); + matlabbatch{mi}.spm.tools.cat.factorial_design.des.mreg.mcov(pagei).iCC = 1; + end + end + % sex + usesex = 0; + if usesex + pagei = pagei + 1; + matlabbatch{mi}.spm.tools.cat.factorial_design.des.mreg.mcov(pagei).c = sex; + matlabbatch{mi}.spm.tools.cat.factorial_design.des.mreg.mcov(pagei).cname = 'sex'; + matlabbatch{mi}.spm.tools.cat.factorial_design.des.mreg.mcov(pagei).iCC = 1; + end + % ... + matlabbatch{mi}.spm.tools.cat.factorial_design.des.mreg.incint = 1; + matlabbatch{mi}.spm.tools.cat.factorial_design.cov = struct('c', {}, 'cname', {}, 'iCFI', {}, 'iCC', {}); + matlabbatch{mi}.spm.tools.cat.factorial_design.multi_cov = struct('files', {}, 'iCFI', {}, 'iCC', {}); + matlabbatch{mi}.spm.tools.cat.factorial_design.masking.tm.tm_none = 1; + matlabbatch{mi}.spm.tools.cat.factorial_design.masking.im = 0; + matlabbatch{mi}.spm.tools.cat.factorial_design.masking.em = {''}; + if isvol + matlabbatch{mi}.spm.tools.cat.factorial_design.globals.g_ancova.global_uval = tiv; + else + matlabbatch{mi}.spm.tools.cat.factorial_design.globals.g_omit = 1; + end + matlabbatch{mi}.spm.tools.cat.factorial_design.check_SPM.check_SPM_zscore.do_check_zscore.use_unsmoothed_data = 1; + matlabbatch{mi}.spm.tools.cat.factorial_design.check_SPM.check_SPM_zscore.do_check_zscore.adjust_data = 1; + matlabbatch{mi}.spm.tools.cat.factorial_design.check_SPM.check_SPM_ortho = 1; + else + + end + end + + % estimate design + mi = mi + 1; mi_design = mi; + matlabbatch{mi}.spm.stats.fmri_est.spmmat(1) = ... + cfg_dep('Basic models: SPM.mat File', ... + substruct('.','val', '{}',{mistat}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), ... + substruct('.','spmmat'));matlabbatch{mi}.spm.stats.fmri_est.write_residuals = 0; + matlabbatch{mi}.spm.stats.fmri_est.method.Classical = 1; + + % setup contrasts + mi = mi + 1; mi_con = mi; + matlabbatch{mi}.spm.stats.con.spmmat(1) = ... + cfg_dep('Model estimation: SPM.mat File', ... + substruct('.','val', '{}',{mi_design}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','spmmat')); + + if exist('sub','var') + nsub = numel(unique(sub)); + ntime = numel(sub) ./ nsub; + tps = -1:2/(ntime-1):1; + tpa = age(1:ntime); tpa = tpa-min(tpa); tpa = tpa ./ max(tpa); tpa = tpa*2 -1; + k = ntime; %[eye(k)-1/k eye(k)-1/k]; %(eye(k).*(tpa*tpa').^.5)-1/k + + matlabbatch{mi}.spm.stats.con.consess{1}.tcon.name = 'tloss'; + matlabbatch{mi}.spm.stats.con.consess{1}.tcon.weights = -tps; +% matlabbatch{mi}.spm.stats.con.consess{end+1}.tcon.name = 'tgain'; +% matlabbatch{mi}.spm.stats.con.consess{end}.tcon.weights = tps; + + matlabbatch{mi}.spm.stats.con.consess{end+1}.fcon.name = 'fcon'; + matlabbatch{mi}.spm.stats.con.consess{end}.fcon.weights = [ eye(k)-1/k eye(k)-1/k ]; +% matlabbatch{mi}.spm.stats.con.consess{end+1}.fcon.name = 'fconw'; +% matlabbatch{mi}.spm.stats.con.consess{end}.fcon.weights = [ (eye(k).*(tpa*tpa').^.5)-1/k (eye(k).*(tpa*tpa').^.5)-1/k ]; + + else + matlabbatch{mi}.spm.stats.con.consess{1}.tcon.name = 'tloss'; + matlabbatch{mi}.spm.stats.con.consess{1}.tcon.weights = [0 -1]; +% matlabbatch{mi}.spm.stats.con.consess{end+1}.tcon.name = 'tgain'; +% matlabbatch{mi}.spm.stats.con.consess{end}.tcon.weights = [0 1]; + end + + for ci = 1:numel(matlabbatch{mi}.spm.stats.con.consess) + con = fieldnames( matlabbatch{mi}.spm.stats.con.consess{ci} ); + for coi = 1:numel(con) + if usesex + matlabbatch{mi}.spm.stats.con.consess{ci}.(con{coi}).weights(end+1) = 0; + end + if isvol % add TIV + matlabbatch{mi}.spm.stats.con.consess{ci}.(con{coi}).weights(end+1) = 0; + end + matlabbatch{mi}.spm.stats.con.consess{ci}.(con{coi}).sessrep = 'none'; + end + end + matlabbatch{mi}.spm.stats.con.delete = 1; + + + % statistic setup + mi = mi + 1; mi_res = mi; + matlabbatch{mi}.spm.tools.cat.stools.results.spmmat(1) = ... + cfg_dep('Contrast Manager: SPM.mat File', ... + substruct('.','val', '{}',{mi_con}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','spmmat')); + for ci = 1:numel(matlabbatch{mi_con}.spm.stats.con.consess) + matlabbatch{mi}.spm.tools.cat.stools.results.conspec(ci).titlestr = ... + sprintf('%s_%s_0.001_%s', dataname, matlabbatch{mi_con}.spm.stats.con.consess{1}.tcon.name, Pmethod); + % sprintf('%s_%s_FWE0.05_%s', dataname, matlabbatch{mi_con}.spm.stats.con.consess{1}.tcon.name, Pmethod); + matlabbatch{mi}.spm.tools.cat.stools.results.conspec(ci).contrasts = ci; + matlabbatch{mi}.spm.tools.cat.stools.results.conspec(ci).threshdesc = 'none'; %'FWE'; + matlabbatch{mi}.spm.tools.cat.stools.results.conspec(ci).thresh = 0.001; % 0.05; + matlabbatch{mi}.spm.tools.cat.stools.results.conspec(ci).extent = 0; + matlabbatch{mi}.spm.tools.cat.stools.results.conspec(ci).conjunction = 1; + matlabbatch{mi}.spm.tools.cat.stools.results.conspec(ci).mask.none = 1; + end + matlabbatch{mi}.spm.tools.cat.stools.results.units = 1; + matlabbatch{mi}.spm.tools.cat.stools.results.export{1}.png = true; + + + % render results + nfiles = numel( age ); + nfiles = round( nfiles , floor(log10( max(1,nfiles) )) ); + if ~isvol + for ddi = 1:3 + mi = mi + 1; + switch ddi + case 1 + matlabbatch{mi}.spm.tools.cat.stools.renderresults.cdata(1) = ... + cfg_dep('Contrast Manager: All Stats Images', ... + substruct('.','val', '{}',{mi_con}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','spm')); + matlabbatch{mi}.spm.tools.cat.stools.renderresults.fparts.prefix = 'renderStat_'; + matlabbatch{mi}.spm.tools.cat.stools.renderresults.render.clims = ... + sprintf('C 0 %d', round( (log( nfiles ) * 4 ) / 4 ) * 4 ); % 'C 0 16'; + case 2 + matlabbatch{mi}.spm.tools.cat.stools.renderresults.cdata(1) = ... + cfg_dep('Contrast Manager: All Con Images', ... + substruct('.','val', '{}',{mi_con}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','con')); + matlabbatch{mi}.spm.tools.cat.stools.renderresults.fparts.prefix = 'renderCon_'; + matlabbatch{mi}.spm.tools.cat.stools.renderresults.render.clims = ... + sprintf('C 0 %d', round( .2 / log( nfiles ) , 2 )); % 'C 0 0.02'; + case 3 + matlabbatch{mi}.spm.tools.cat.stools.renderresults.cdata(1) = { + fullfile( resdir , 'ResMS.gii' ); + }; + matlabbatch{mi}.spm.tools.cat.stools.renderresults.fparts.prefix = 'renderResMS_'; + matlabbatch{mi}.spm.tools.cat.stools.renderresults.render.clims = ... + sprintf('C 0 %d', round( 2 / log( nfiles ) , 2 ) ); % 'C 0 0.3'; + end + matlabbatch{mi}.spm.tools.cat.stools.renderresults.render.view = 1; + matlabbatch{mi}.spm.tools.cat.stools.renderresults.render.texture = 1; + matlabbatch{mi}.spm.tools.cat.stools.renderresults.render.transparency = 1; + matlabbatch{mi}.spm.tools.cat.stools.renderresults.render.colormap = 1; + matlabbatch{mi}.spm.tools.cat.stools.renderresults.render.invcolormap = 0; + matlabbatch{mi}.spm.tools.cat.stools.renderresults.render.background = 1; + matlabbatch{mi}.spm.tools.cat.stools.renderresults.render.showfilename = 1; + matlabbatch{mi}.spm.tools.cat.stools.renderresults.stat.threshold = 0; % the colormap is maybe not updated ... + matlabbatch{mi}.spm.tools.cat.stools.renderresults.stat.hide_neg = 0; + matlabbatch{mi}.spm.tools.cat.stools.renderresults.fparts.outdir = { spm_fileparts(resdir) }; + matlabbatch{mi}.spm.tools.cat.stools.renderresults.fparts.suffix = ''; + end + end +end","MATLAB" +"Neurology","ChristianGaser/cat12","internal/cat_tst_aging.m",".m","29668","704","function cat_tst_aging(Pmethod, Presdir, Praw, subsets) + %% - prepare and add further test sites + % Aspects and expectations: + % - all results depend on the underlying segmentation + % - evaluation of atrophy in (i) aging ... and (ii) disease (e.g. AD,MCI,HC) ... controled? + % higher correlation and clear decline over different protocols with + % less outiers + % - evaluation of field strength + % less effects by scanner or protocol + % - use intensity values? + + + % TODO: + % - handling of many curvs >> additional subfigure plot (1-3 lines) + % - save tables + % - regression estimation on healthy only + % - run multiple fit functions and select the best fitting one + % - check steps: + % - name missing files (for reprocessing) or just to count the failures + % - add SPM parameter tests >> to improve segmentation? + % - use different age ranges: + % - full + % - development (<18) + % - adult (>=18) + % - elderly and Alzheimers (>50) + % + % - integrate further variables (problem is - what do we expect? ) + % - intensity + % - curvature + % - global GI? + % + % - extend super young and super old + % - add non-healty in ageing plot + % - add further cohorts plots + % - need real tests > plot of stat histograms + % - create subfunctions + % + + % SIDE ISSUE + %#ok<*AGROW> + addpath(fullfile(fileparts(which('cat12')),'internal')); + + + + + % Find preocessed data that is available for all methods. + % ---------------------------------------------------------------------- + datas = 'pbt'; Pdata = cell(1,size(Pmethod,1),1); + for pi = 1:size(Pmethod,1) + if pi == 1 + if ~exist(Pmethod{pi,2},'dir') && ~exist(fullfile(Pmethod{pi,2},subsets{sdi}),'dir') + error('Need to start with a SPM/CAT directory with subdirectories.\n'); + end + for sdi = 1:numel(subsets) + Pdata{pi} = [ Pdata{pi}; cat_vol_findfiles(fullfile(Pmethod{pi,2}, subsets{sdi}), ... + sprintf('lh.%s.*',datas),struct('depth',1)) ]; % pbt + end + elseif exist( fullfile(Pmethod{pi,2},'01_Bestoff'),'dir') + Pdata{pi} = cat_io_strrep( Pdata{1}, Pmethod{1,2}, Pmethod{pi,2}) ; + else + Pdata{pi} = spm_file( Pdata{1}, 'path', fullfile(Pmethod{pi,2},'surf') ); + end + % find missing files + Pexist(:,pi) = cellfun(@(x) exist(x,'file'),Pdata{pi}) & ... + cellfun(@(x) exist(x,'file'),cat_io_strrep(Pdata{pi},[filesep 'lh.'],[filesep 'rh.'])); + end + % remove missing files in all testsets + for pi = 1:size(Pmethod,1) + Pdata{pi}( sum(Pexist==0,2)>0 ) = []; + end + % print report + fprintf('\nFound %d/%d cases for evaluation of %d methods: \n', numel(Pdata{1}), size(Pdata,1), size(Pmethod,1)); + for pi = 1:size(Pmethod,1) + fprintf('%16s: %4d files\n', Pmethod{pi,1}, nnz(Pexist(:,pi)>0) ); + end + fprintf('----------------------------\n'); + fprintf('%16s: %4d files\n\n', 'overlap', length(Pdata{pi}) ); + + + + + %% define further files + % ---------------------------------------------------------------------- + for pi = 1:size(Pmethod,1) + + Pcentral{pi} = cat_io_strrep( Pdata{pi}, datas, 'central'); + Pwhite{pi} = cat_io_strrep( Pdata{pi}, datas, 'white'); + Ppial{pi} = cat_io_strrep( Pdata{pi}, datas, 'pial'); + Pgmv{pi} = spm_file( cat_io_strrep( Pdata{pi}, ... + {[filesep 'surf' filesep], [filesep sprintf('lh.%s.',datas)]}, ... + {[filesep 'mri' filesep], filesep}), 'ext', '.nii','prefix','mwp1'); + Pp0{pi} = strrep( Pgmv{pi} , [filesep 'mwp1'], [filesep 'p0']); + if all( cellfun( @(x) exist(x,'file') , Pgmv{pi} )==0 ) + Pgmv{pi} = strcat(Pgmv{pi},'.gz'); + end + if all( cellfun( @(x) exist(x,'file')==0, Pp0{pi} ) ) + Pp0{pi} = strcat(Pp0{pi},'.gz'); + end + Pxml{pi} = spm_file( cat_io_strrep( Pdata{pi}, ... + {[filesep 'surf' filesep], [filesep sprintf('lh.%s.',datas)]}, ... + {[filesep 'report' filesep], filesep}), 'ext', '.xml','prefix','cat_'); + if any(contains(Pmethod{pi,1},{'S25','SPM'})), Pxml{pi} = cat_io_strrep(Pxml{pi},[filesep 'cat_'],[filesep 'cat_c1']); end + if any(contains(Pmethod{pi,1},{'S25','SPM'})), Pgmv{pi} = cat_io_strrep(Pgmv{pi},[filesep 'mwp1'],[filesep 'mwp1c1']); end + Pff{pi} = strrep(spm_str_manip(Pcentral{pi}','tr'),'lh.central',''); + + % get mini xml if no xml is available + cat_io_createXML( struct('data', {Pp0{pi}( ... + cellfun(@(x) exist(x,'file')==0, Pxml{pi}) & cellfun(@(x) exist(x,'file')==2, Pp0{pi}) )} ) ); + Pexistx(:,pi) = cellfun(@(x) exist(x,'file'),Pxml{pi}); + end + for pi = 1:size(Pmethod,1) + Pdata{pi}( sum(Pexistx==0,2)>0 ) = []; + Pwhite{pi}( sum(Pexistx==0,2)>0 ) = []; + Ppial{pi}( sum(Pexistx==0,2)>0 ) = []; + Pgmv{pi}( sum(Pexistx==0,2)>0 ) = []; + Pp0{pi}( sum(Pexistx==0,2)>0 ) = []; + Pff{pi}( sum(Pexistx==0,2)>0 ) = []; + Pxml{pi}( sum(Pexistx==0,2)>0 ) = []; + end + Pdemo = spm_file( cat_io_strrep( Pdata{1}, {sprintf('lh.%s.',datas); Pmethod{1,2}}, {'',Praw}), 'ext','.xml'); + + + + + %% extract basic demographic parameters + % ---------------------------------------------------------------------- + age = []; sex = []; siten = {}; project = {}; cohortn = []; scanner = {}; + for si = 1:numel(Pdemo) + demo = cat_io_xml( Pdemo{si} ); + FN = fieldnames(demo); + FNp = FN{ contains( FN ,'patternCog_') }; + try age(si,1) = demo.(FNp).Age; catch, age(si,1) = -1; end + try sex(si,1) = demo.(FNp).Sex; catch, sex(si,1) = str2double(cat_io_strrep(demo.(FNp).Sex,{'''';'F';'M'},{'','0','1'})); end + try cohortn{si,1} = strrep( demo.(FNp).Cohort ,'''',''); catch, cohort{si,1} = 'NA'; end + try field(si,1) = demo.(FNp).Fieldstrength; catch, field(si,1) = -1; end + try scanner{si,1} = strrep( demo.(FNp).Scanner ,'''',''); catch, scanner{si,1} = ''; end + try + project{si,1} = cat_io_strrep(FNp,{'patternCog_';'_demographics_T1w'},{'',''}); + if isnumeric( demo.(FNp).Site ) + siten{si,1} = [ project{si,1} '_' sprintf('%d',demo.(FNp).Site)]; + else + siten{si,1} = [ project{si,1} '_' strrep( demo.(FNp).Site , '''', '')]; + end + catch + project{si,1} = cat_io_strrep(FNp,{'patternCog_';'_demographics_T1w'},{'',''}); + siten{si,1} = [ project{si,1} ""_NA""]; + end + end + site = str2double(cat_io_strrep( siten , ... + unique(siten), cellfun(@(x) {num2str(x)},num2cell(1:numel(unique(siten))))) ); + cohort = str2double(cat_io_strrep( cohortn , ... + unique(cohortn), cellfun(@(x) {num2str(x)},num2cell(1:numel(unique(cohortn))))) ); %#ok + HC = contains(cohortn,'HC'); + + % ##### CSV import for special cases ##### + % MR-ART? + if 0 + csv = cat_io_csv(Pcsv{pi}{1}); + csv = sortrows(csv,1); + csvf = contains(csv(2:end,1), files); + IDage = contains(csv(1,:),'Age'); + IDsex = contains(csv(1,:),'Sex'); + IDsite = contains(csv(1,:),'Site'); + age = [age cell2mat(csv(2:end,IDage)) ]; + sex = [sex cell2mat(csv(2:end,IDsex))==1 ]; + site = [site (sdi*1000 + str2double(cat_io_strrep( csv(2:end,IDsite) , ... + unique(csv(2:end,IDsite)), cellfun(@(x) {num2str(x)},num2cell(1:numel(unique(csv(2:end,IDsite))))) ) ) ) ]; + end + + + % update result directory + Presdir = fullfile(Presdir,sprintf('aging_%0.0f-%0.0f_N%d_M%d',min(age),max(age),numel(age),size(Pmethod,1))); + if ~exist(Presdir,'dir'), mkdir(Presdir); end + + + % #### + % What about folding depending thickness? - We would expect less variation (although sulci fund are probably sig. thinner) + % + tiv = zeros(numel(Pdata{pi}),size(Pmethod,1)); rGMV = tiv; tsa = tiv; + for pi = 1:size(Pmethod,1) + fprintf('\n Method %2d/%2d: %16s', pi, size(Pmethod,1), Pmethod{pi} ); + + % estimate average thickness + for si = 1:numel(Pdata{pi}) + txt = sprintf(' Load subjects %4d/%4d', si, numel(Pdata{pi})); + if si>1, fprintf(repmat('\b',1,numel(txt))); end + fprintf(txt'); + + cdata{pi,si} = cat_io_FreeSurfer('read_surf_data',Pdata{pi}{si}); + mnthick(si,pi) = cat_stat_nanmean(cdata{pi,si}); + end + + % CAT XML data + xml{pi} = cat_io_xml( Pxml{pi} ); + for si = 1:numel(Pdata{pi}) + try + tiv(si,pi) = xml{pi}(si).subjectmeasures.vol_TIV; + catch + tiv(si,pi) = nan; + end + try + if isfield( xml{pi}(si).subjectmeasures,'vol_rel_CGW') + rGMV(si,pi) = xml{pi}(si).subjectmeasures.vol_rel_CGW(2); + elseif isfield( xml{pi}(si).subjectmeasures,'vol_CGW_rel') + rGMV(si,pi) = xml{pi}(si).subjectmeasures.vol_CGW_rel(2); + end + catch + rGMV(si,pi) = nan; + end + try + tsa(si,pi) = xml{pi}(si).subjectmeasures.surf_TSA; + catch + try + tsa(si,pi) = xml{pi}(si).subjectmeasures.TSA / 100; + catch + tsa(si,pi) = nan; + end + end + end + end + + fprintf('\n'); + + +%% Pdata{pi} + onlyAllreadySmoothed = 0; %##################### + for pi=1:size(Pmethod,1) + +% matlabbatch = cat_tst_agereg( Pgmv{pi}, Presdir, Pmethod{pi,1}, 'GMV', age, sex, cohort==1, tiv(:,pi), 1, onlyAllreadySmoothed); +% if ~isempty(matlabbatch), spm_jobman('run',matlabbatch); end + +% thickness not working + for sm = {'pbt','thickness'} + %% + Pdatapi = strrep( Pdata{pi} ,sprintf('lh.%s.',datas), sprintf('lh.%s.',sm{1})); + matlabbatch = cat_tst_agereg( Pdatapi, Presdir, Pmethod{pi,1}, sm{1}, age, sex, HC, tiv(:,pi), 1, onlyAllreadySmoothed); + if ~isempty(matlabbatch), spm_jobman('run',matlabbatch); end + end + end + + + + %% global statistics + % ---------------------------------------------------------------------- + fprintf('Print figures: \n'); + fh = figure(50); set(fh,'Visible',1,'Interruptible',0); + %% + for mi = 1:4 + % fitting models: + % - not working: cubicinterp + % - not fitting: log10 + % - too simple: logistic4 + % - too fitting: smoothingspline + % >> test the poly# fit and use the best fitting one + dfit = {'poly1','poly2','poly3','poly4','poly5'}; + roundf = 1; + xrange = [ floor( prctile(age(:),.1)/5)*5 , ceil( prctile(age(:),99.9)/5)*5 ]; + switch mi + case 1 + data = mnthick; + ylab = 'cortical thickness (mm)'; + tlab = 'CT'; + range = [1.5 4]; + case 2 + data = rGMV; + ylab = 'relative gray matter volume'; + tlab = 'rGMV'; + range = [0.2 .7]; + case 3 + data = tsa; + ylab = 'TSA (total surface area)'; + tlab = 'TSA'; + %dfit = {'poly2'}; + range = [1000 3000]; + roundf = -3; + case 4 + data = (mnthick .* tsa) ./ tiv; + ylab = 'relative surface volume'; + tlab = 'rCTV '; + range = [2 5]; + end + if isempty(range) + range = round( [ prctile(data(:),.1) , prctile(data(:),99.9) ], roundf-1); + end + fprintf(' Measure %d - %s:\n',mi,tlab); + + + for spi = 1:2 + clf(fh); + + fh.Position(3:4) = [600*spi 600]; + if spi == 2 + tiledlayout( round(size(Pmethod,1)/3) , ... + ceil(size(Pmethod,1) / round(size(Pmethod,1)/3)), ... + 'TileSpacing', 'compact', 'Padding', 'compact'); + end + + % print just for legend + if spi == 1 + fhagex = axes(fh); hold(fhagex,'on'); %#ok + for pi = 1:size(Pmethod,1) + sh = scatter(fhagex, age(1),data(1,pi)); + sh.MarkerFaceColor = Pmethod{pi,3}; + sh.MarkerEdgeColor = Pmethod{pi,3}; + sh.MarkerFaceAlpha = .2; + sh.MarkerEdgeAlpha = .3; + sh.Marker = Pmethod{pi,4}; + end + end + + % main print + for pi = 1:size(Pmethod,1) + if spi == 2 + fhagex = nexttile; hold(fhagex,'on'); + end + + sh = scatter(fhagex, age(HC),data(HC,pi)); + sh.MarkerFaceColor = Pmethod{pi,3}; + sh.MarkerEdgeColor = Pmethod{pi,3}; + sh.MarkerFaceAlpha = .1; + sh.MarkerEdgeAlpha = .2; + sh.Marker = Pmethod{pi,4}; + + if ~all( isnan(data(:,pi)) ) + ndnan = ~isnan(data(:,pi)) & HC; + %% + [afit{pi}, agof{pi}, afitr{pi}, agofr{pi}, bfit{pi}] = bestfit(age(ndnan(:)) , data(ndnan(:),pi),dfit); + arsq(pi) = agof{pi}.rsquare; + arsqr(pi) = agofr{pi}.rsquare; + acor(pi) = corr( age(ndnan) , data(ndnan,pi) ,'Type','Spearman'); + + if spi == 2 || size(Pmethod,1)<5 + xint = linspace(0, 100,100); + CIF = predint(afit{pi},xint,0.95,'Functional'); + CIO = predint(afit{pi},xint,0.95,'obs'); + p = fill(fhagex, [xint'; flip(xint')],[CIO(:,1); flip(CIO(:,2))], ... + Pmethod{pi,3}); p.FaceAlpha = .1; p.EdgeAlpha = .2; p.EdgeColor = Pmethod{pi,3}; + p = fill(fhagex, [xint'; flip(xint')],[CIF(:,1); flip(CIF(:,2))], ... + Pmethod{pi,3}); p.FaceAlpha = .3; p.EdgeAlpha = .4; p.EdgeColor = Pmethod{pi,3}; + end + + fph = plot( fhagex, afit{pi} ); + fph.Color = Pmethod{pi,3}; + fph.LineWidth = 1; + fph.MarkerFaceColor = fph.Color; + else + acor(pi) = nan; + arsq(pi) = nan; + end + + if spi==2 + grid(fhagex, 'on'); box(fhagex, 'on'); + ylim(range); xlim(xrange); + xlabel(fhagex, 'age (years)'); ylabel(fhagex, ylab); + title(fhagex, sprintf('%s (Nsub=%d)',Pmethod{pi,1} ,sum(ndnan))); + lgd = legend( fhagex, strcat( ... + ' (', bfit{pi} ,', r=', num2str(acor(pi),'%0.3f'), ', r^2=', num2str(arsq(pi),'%0.3f'), ')' )); %, ', rr^2=', num2str(arsqr(pi),'%0.3f') + end + + end + % format + if spi==1 + grid(fhagex, 'on'); box(fhagex, 'on'); + xlabel(fhagex, 'age (years)'); ylabel(fhagex, ylab); + title(fhagex, sprintf('%s (Nsub=%d, Nsites=%d)',tlab,numel(age),numel(unique(site)))); + subtitle(sprintf('[ r=corr(Spearman), r^2-fit, rr^2-robustfit ]')); + lgd = legend( fhagex, strcat( Pmethod(:,1), ... + ' (', bfit', ' ,r=', num2str(acor','%0.2f'), ', r^2=', num2str(arsq','%0.2f'), ')' )); %, ', rr^2=', num2str(arsqr','%0.2f') + fhagex.FontSize = 12; lgd.FontSize = 12; + end + ylim(range); xlim(xrange); + if spi==2, spis = 'single'; else, spis = 'mixed'; end + print(fh,fullfile(Presdir,sprintf('cat_tst_aging_%s%s',spis,deblank(tlab))),'-r300','-dpng'); + fprintf(' %s\n',fullfile(Presdir,sprintf('cat_tst_aging_%s%s.png',spis,deblank(tlab)))); + end + + + + %matlabbatch = cat_tst_aging(age,data,); + %spm('run',matlabbatch); + + + + + %% fieldstrength diffs + % regress out age from data + for pi = 1:size(Pmethod,1) + % Get regression coefficients + b = regress(data(HC,pi), [ones(size(age(HC), 1), 1), age(HC)]); + % Predicted Y from X + d_hat(:,pi) = [ones(size(age, 1), 1), age] * b; + % Residuals = part of Y not explained by X + data_residual(:,pi) = data(:,pi) - d_hat(:,pi); + end + + + + %% test of field strength difference + % - this is not really working as it does not consider the diffent slopes in aging + % (eg. a method that did not show aging might have better results here) + clear name dstrength methodfielddiff + dsi = 0; fields = [1.5 3.0]; subname = ''; + for pi = 1:size(Pmethod,1) + for si = 1:numel(fields) + dsi = dsi + 1; + dstrength{dsi} = data_residual( age>5 & age<95 & field==fields(si) ,pi); + name{dsi} = sprintf('%sT%0.1f',Pmethod{pi},fields(si)); + if si == numel(fields) + [~,ttsp(pi),tts] = ttest2( dstrength{dsi-1} , dstrength{dsi} ); + methodfielddiff(pi) = diff(tts); + end + end + subname = sprintf('%s %s(tst p=%0.3f)',subname,Pmethod{pi,1},ttsp(pi)); + end + mylim = round( prctile(abs(cell2mat(dstrength')),99),roundf) * 1.2; + clf(fh); fh.Position(3:4) = [500 200 + 50*size(Pmethod,1)]; + fhfieldx = axes(fh); %#ok + cat_plot_boxplot( dstrength , struct('names',{name},'ygrid',1, 'ylim',[-mylim mylim],... + 'subsets',mod( 1+round((1:size(Pmethod,1)*2)/2),2) , ... + 'groupcolor',min(1,max(0,cell2mat(reshape( [Pmethod(:,3)'; Pmethod(:,3)'] , ... + size(Pmethod,1)*2, 1)) + repmat([-.2;+.2],size(Pmethod,1),1))))); + title(fhfieldx, sprintf('Method vs. fieldstrength (Nsub=%d, Nsites=%d, higher p-values are better)', ... + numel(age), numel(unique(site))) ); subtitle(fhfieldx,subname); + xlabel(fhfieldx,'Method + fieldstrength'); ylabel(fhfieldx,ylab,'Rotation',90); + print(fh,fullfile(Presdir,sprintf('cat_tst_fieldstrength_%s',deblank(tlab))),'-r300','-dpng'); + fprintf(' %s\n',fullfile(Presdir,sprintf('cat_tst_fieldstrength_%s.png',deblank(tlab)))); + + + + %% group-diffs + % - also not optimal + clear name dstrength methodfielddiff tts ttsp + projects = {'ADNI','AIBL','OASIS3'}; + dsi = 0; subname = ''; cohorts = {'HC','MCI','AD'}; %unique(cohortn); + for pi = 1:size(Pmethod,1) + % regress out age from data + % Get regression coefficients + for si = 1:numel(cohorts) + dsi = dsi + 1; + dstrength{dsi} = data_residual( age>50 & contains(cohortn, cohorts{si}) & contains(project,projects),pi); + name{dsi} = sprintf('%sT%s',Pmethod{pi},cohorts{si}); + if si > 1 + [~,ttsp(pi,si-1),tts{pi,si-1}] = ttest2( dstrength{dsi-1} , dstrength{dsi} ); + end + if si == numel(cohorts) + [~,ttsp(pi,si),tts{pi,si}] = ttest2( dstrength{dsi+(1-numel(cohorts))} , dstrength{dsi} ); + methodfielddiff(pi) = mean( diff([tts{pi,:}]) ); + end + end + subname = sprintf('%s %s(p=%0.3f)', subname, Pmethod{pi,1}, mean(ttsp(pi,end))); + end + if any( cellfun(@(x) ~isempty(x), dstrength )) + clf(fh); fh.Position(3:4) = [600 400]; + mylim = round( prctile(abs(cell2mat(dstrength')),99),roundf) * 1.2; + fhcohortx = axes(fh); %#ok + cat_plot_boxplot( dstrength , struct('names',{name},'ygrid',1,'maxwhisker',1.5,'ylim',[-mylim mylim],... + 'handle',fh,'subsets',mod( floor( (0:size(Pmethod,1)*3-1)/3) ,2), ... + 'groupcolor',repmat( cat_io_colormaps('trafficlight',3), size(Pmethod,1), 1) )); + title(fhcohortx, sprintf('Alzheimer''s in %s (tst HC vs. AD, Nsub=%d, Nsites=%d, lower p-values are better)', ... + [projects{:}], numel(age), numel(unique(site))) ); subtitle(fhcohortx, subname); + xlabel(fhcohortx, 'Method+Cohort'); ylabel(fhcohortx, ylab,'Rotation',90); hold on; + % ... save ... + print(fh, fullfile(Presdir,sprintf('cat_tst_Alzheimers_%s',deblank(tlab))),'-r300','-dpng'); + fprintf(' %s\n',fullfile(Presdir,sprintf('cat_tst_Alzheimers_%s.png',deblank(tlab)))); + end + + + + %% sex differences (in puberty) + clf(fh); + fh.Position(3:4) = [1200 800]; sgcolor = [.5 0 0; 0 0 .5]; sgmarker = {'o','^'}; + tiledlayout( round(size(Pmethod,1)*2) , ... + ceil(size(Pmethod,1) / round(size(Pmethod,1)*2)), ... + 'TileSpacing', 'compact', 'Padding', 'compact'); + for pi = 1:size(Pmethod,1) + nexttile; + hold on; + for si = 1:2 + sg = HC & sex==(si-1) & ~isnan(data(:,pi)); + if sum(sg)>0 + [afit{pi}, agof{pi}, afitr{pi}, agofr{pi}, bfit{pi}] = bestfit(age(sg(:)) , data(sg(:),pi),dfit); + arsq(pi) = agof{pi}.rsquare; + arsqr(pi) = agofr{pi}.rsquare; + afitp1(pi) = afit{pi}.p1; + afitp2(pi) = afit{pi}.p2; + acor(pi) = corr( age(sg) , data(sg,pi) ,'Type','Spearman'); + + xint = linspace(0, 100,100); + CIF = predint(afit{pi},xint,0.80,'Functional'); + CIO = predint(afit{pi},xint,0.80,'obs'); + p = fill([xint'; flip(xint')],[CIO(:,1); flip(CIO(:,2))], sgcolor(si,:)); p.FaceAlpha = .1; p.EdgeAlpha = .2; p.EdgeColor = sgcolor(si,:); + p = fill([xint'; flip(xint')],[CIF(:,1); flip(CIF(:,2))], sgcolor(si,:)); p.FaceAlpha = .2; p.EdgeAlpha = .3; p.EdgeColor = sgcolor(si,:); + + sh = scatter(age(sg),data(sg,pi)); + sh.Marker = sgmarker{si}; + sh.MarkerFaceColor = sgcolor(si,:); sh.MarkerFaceAlpha = .1; + sh.MarkerEdgeColor = sgcolor(si,:); sh.MarkerEdgeAlpha = .1; + + fph = plot( afit{pi} ); + fph.Color = sgcolor(si,:); + fph.LineWidth = 1; + + legend off; + + title(sprintf('sex difference %s',Pmethod{pi,1})); %subtitle(subname); + xlim(xrange); ylim(range); + xlabel('age'); ylabel(ylab); box on; grid on; + end + end + ylim(round([prctile(data(:),2) prctile(data(:),98)] .* [.8 1.1],1)) + end + print(fh,fullfile(Presdir,sprintf('cat_tst_sex_%s',deblank(tlab))),'-r300','-dpng'); + fprintf(' %s\n',fullfile(Presdir,sprintf('cat_tst_sex_%s.png',deblank(tlab)))); + + end + fprintf('done.\n') +end +function [afit,agof,afitr,agofr,bfit] = bestfit(x,y,dfit) %#ok +%#ok<*NODEF> + for fi = 1:numel(dfit) + evalc('[afitr{fi}, agofr{fi}] = fit( x , y, dfit{fi},''Robust'',''Bisquare'');'); %,struct('robust','LAR'));Bisquare + evalc('[afit{fi}, agof{fi}] = fit( x , y, dfit{fi});'); + if strcmp(lastwarn,'Equation is badly conditioned. Remove repeated data points or try centering and scaling.') + lastwarn(''); + rs(fi) = 0; + else + rs(fi) = agofr{fi}.rsquare; %mean( [ agof{fi}.rsquare, agofr{fi}.rsquare ]); + end + end + [~,bfid] = max(rs); + + afit = afit{bfid}; + agof = agof{bfid}; + afitr = afitr{bfid}; + agofr = agofr{bfid}; + bfit = dfit{bfid}; +end +function matlabbatch = SPMpreprocessing4bc(BWPfilesSPM) +%----------------------------------------------------------------------- +% Job saved on 07-Mar-2025 14:46:45 by cfg_util (rev $Rev: 8183 $) +% spm SPM - SPM25 (25.01.02) +% cfg_basicio BasicIO - Unknown +%----------------------------------------------------------------------- + matlabbatch{1}.spm.spatial.preproc.channel.vols = BWPfilesSPM; + matlabbatch{1}.spm.spatial.preproc.channel.biasreg = 0.0001; + matlabbatch{1}.spm.spatial.preproc.channel.biasfwhm = 60; + matlabbatch{1}.spm.spatial.preproc.channel.write = [0 1]; + matlabbatch{1}.spm.spatial.preproc.tissue(1).tpm = {fullfile(spm('dir'),'tpm','TPM.nii,1')}; + matlabbatch{1}.spm.spatial.preproc.tissue(1).ngaus = 1; + matlabbatch{1}.spm.spatial.preproc.tissue(1).native = [0 0]; + matlabbatch{1}.spm.spatial.preproc.tissue(1).warped = [0 0]; + matlabbatch{1}.spm.spatial.preproc.tissue(2).tpm = {fullfile(spm('dir'),'tpm','TPM.nii,2')}; + matlabbatch{1}.spm.spatial.preproc.tissue(2).ngaus = 1; + matlabbatch{1}.spm.spatial.preproc.tissue(2).native = [0 0]; + matlabbatch{1}.spm.spatial.preproc.tissue(2).warped = [0 0]; + matlabbatch{1}.spm.spatial.preproc.tissue(3).tpm = {fullfile(spm('dir'),'tpm','TPM.nii,3')}; + matlabbatch{1}.spm.spatial.preproc.tissue(3).ngaus = 2; + matlabbatch{1}.spm.spatial.preproc.tissue(3).native = [0 0]; + matlabbatch{1}.spm.spatial.preproc.tissue(3).warped = [0 0]; + matlabbatch{1}.spm.spatial.preproc.tissue(4).tpm = {fullfile(spm('dir'),'tpm','TPM.nii,4')}; + matlabbatch{1}.spm.spatial.preproc.tissue(4).ngaus = 3; + matlabbatch{1}.spm.spatial.preproc.tissue(4).native = [0 0]; + matlabbatch{1}.spm.spatial.preproc.tissue(4).warped = [0 0]; + matlabbatch{1}.spm.spatial.preproc.tissue(5).tpm = {fullfile(spm('dir'),'tpm','TPM.nii,5')}; + matlabbatch{1}.spm.spatial.preproc.tissue(5).ngaus = 4; + matlabbatch{1}.spm.spatial.preproc.tissue(5).native = [0 0]; + matlabbatch{1}.spm.spatial.preproc.tissue(5).warped = [0 0]; + matlabbatch{1}.spm.spatial.preproc.tissue(6).tpm = {fullfile(spm('dir'),'tpm','TPM.nii,6')}; + matlabbatch{1}.spm.spatial.preproc.tissue(6).ngaus = 2; + matlabbatch{1}.spm.spatial.preproc.tissue(6).native = [0 0]; + matlabbatch{1}.spm.spatial.preproc.tissue(6).warped = [0 0]; + matlabbatch{1}.spm.spatial.preproc.warp.mrf = 0; + matlabbatch{1}.spm.spatial.preproc.warp.cleanup = 0; + matlabbatch{1}.spm.spatial.preproc.warp.reg = [0 0 0.1 0.01 0.04]; + matlabbatch{1}.spm.spatial.preproc.warp.affreg = 'mni'; + matlabbatch{1}.spm.spatial.preproc.warp.fwhm = 0; + matlabbatch{1}.spm.spatial.preproc.warp.samp = 3; + matlabbatch{1}.spm.spatial.preproc.warp.write = [0 0]; + matlabbatch{1}.spm.spatial.preproc.warp.vox = NaN; + matlabbatch{1}.spm.spatial.preproc.warp.bb = [NaN NaN NaN + NaN NaN NaN]; +end +function CS1 = loadSurf(P) + if ~exist(P,'file'), error('Surface file %s could not be found due to previous processing errors.',P); end + + try + CS = gifti(P); + catch + error('Surface file %s could not be read due to previous processing errors.',P); + end + + CS1.vertices = CS.vertices; CS1.faces = CS.faces; + if isfield(CS,'cdata'), CS1.cdata = CS.cdata; end +end +function borderintensity( Praw , Pdata) +%% outsource into function + % native data gunzipping + [~,~,ee] = fileparts(Pdata{pi}{si}); + Prawsi = cat_vol_findfiles(Praw,sprintf('%s.nii',ee(2:end))); + if isempty(Prawsi) + Prawgz = cat_vol_findfiles(Praw,sprintf('%s.nii.gz',ee(2:end))); + gunzip(Prawgz{1}) + delraw = 1; + Prawsi = cat_vol_findfiles(Praw,sprintf('%s.nii',ee(2:end))); + else + delraw = 0; + end + + %% bias-corrected > but not intensity normalized :/ + Pbcsi = cat_vol_findfiles(Praw,sprintf('m%s.nii',ee(2:end))); + if numel(Pbcsi) < numel(Prawsi) + BWPfilesSPM = Prawsi; + BWPfilesSPM( cellfun(@(x) exist(x,'file'),spm_file(BWPfilesSPM,'prefix','m'))>0 ) = []; + if ~isempty( BWPfilesSPM ) + matlabbatchbc = SPMpreprocessing4bc( BWPfilesSPM ) ; + if verbose, spm_jobman('run',matlabbatchbc); else, evalc( 'spm_jobman(''run'',matlabbatchbc);'); end + end + end + + %% + Pbcsi = cat_vol_findfiles(Praw,sprintf('m%s.nii',ee(2:end))); + Pgsi = spm_file(Pbcsi,'prefix','g'); + if ~exist(Pgsi{1},'file') + %% + Vbcsi = spm_vol(char(Pbcsi)); + Ybcsi = spm_read_vols(Vbcsi); + Ygsi = cat_vol_grad(Ybcsi,1) ./ max( prctile( Ybcsi(:),90) , cat_vol_smooth3X(Ybcsi,4) ) * 3; + Ygsi(Ygsi>1) = max(0,1 - 1/3*(Ygsi(Ygsi>1))); + Ygsi = log10(Ygsi * 9 + 1); + cat_sanlm(Ygsi,1,3); + Vgsi = Vbcsi; Vgsi.fname = Pgsi{1}; + spm_write_vol(Vgsi,Ygsi); + end + + + S = gifti(Pcentral{pi}{si}); + %% + surfname = {'white','pial','layer4','cortex'}; + for bi = 1:3 + clear matlabbatch; + matlabbatch{1}.spm.tools.cat.stools.vol2surf.data_vol = Pbcsi; % Pgsi + matlabbatch{1}.spm.tools.cat.stools.vol2surf.datafieldname = 'int'; + if bi == 1 + matlabbatch{1}.spm.tools.cat.stools.vol2surf.data_mesh_lh = Pwhite{pi}(si); + elseif bi == 2 + matlabbatch{1}.spm.tools.cat.stools.vol2surf.data_mesh_lh = Ppial{pi}(si); + else + matlabbatch{1}.spm.tools.cat.stools.vol2surf.data_mesh_lh = Pcentral{pi}(si); + matlabbatch{1}.spm.tools.cat.stools.vol2surf.datafieldname = sprintf('int_%s',surfname{bi}); + end + matlabbatch{1}.spm.tools.cat.stools.vol2surf.sample = {'mean'}; + matlabbatch{1}.spm.tools.cat.stools.vol2surf.interp = {'linear'}; + matlabbatch{1}.spm.tools.cat.stools.vol2surf.mapping.rel_equivol_mapping.class = 'GM'; + if bi == 4 + matlabbatch{1}.spm.tools.cat.stools.vol2surf.sample = {'weighted_avg'}; %'multi' + matlabbatch{1}.spm.tools.cat.stools.vol2surf.mapping.rel_equivol_mapping.startpoint = -0.5; + matlabbatch{1}.spm.tools.cat.stools.vol2surf.mapping.rel_equivol_mapping.steps = 7; + matlabbatch{1}.spm.tools.cat.stools.vol2surf.mapping.rel_equivol_mapping.endpoint = 0.5; + else + matlabbatch{1}.spm.tools.cat.stools.vol2surf.mapping.rel_equivol_mapping.startpoint = 0; + matlabbatch{1}.spm.tools.cat.stools.vol2surf.mapping.rel_equivol_mapping.steps = 1; + matlabbatch{1}.spm.tools.cat.stools.vol2surf.mapping.rel_equivol_mapping.endpoint = 0; + end + +% request for gradient or STD? + if verbose, spm_jobman('run',matlabbatch); else, evalc( 'spm_jobman(''run'',matlabbatch);'); end + + %% + if bi == 3 + Pint{pi}{si}{bi,1} = strrep( spm_str_manip( Pcentral{pi}{si}, 'r'), '.central.', ... + sprintf('.%s_%s.', char(matlabbatch{1}.spm.tools.cat.stools.vol2surf.datafieldname), ... + char(spm_str_manip(matlabbatch{1}.spm.tools.cat.stools.vol2surf.data_vol,'tr')))); + else + Pint{pi}{si}{bi,1} = strrep( spm_str_manip( Pcentral{pi}{si}, 'r'), '.central.', ... + sprintf('.%s_%s_%s.', char(matlabbatch{1}.spm.tools.cat.stools.vol2surf.datafieldname), ... + surfname{bi}, char(spm_str_manip(matlabbatch{1}.spm.tools.cat.stools.vol2surf.data_vol,'tr')))); + end + %cdata = cat_io_FreeSurfer('read_surf_data', Pint{pi}{si}{bi} ); + Pintp{si}{bi}{pi,1} = Pint{pi}{si}{bi,1}; + end + +%% + if 0 % need intnorm and orient! + Ybcsi = spm_read_vols(spm_vol(char(Pbcsi))); + rres = cat_surf_fun('evalCS', ... + loadSurf(Pcentral{pi}{si}), cat_io_FreeSurfer('read_surf_data',Pdata{pi}{si}), cat_io_FreeSurfer('read_surf_data',Pdata{pi}{si}), ... + Ybcsi,Ybcsi,Pcentral{pi}{si},[],2,cat_get_defaults('extopts.expertgui')>1); + end +%% + if delraw, delete(Prawsi{1}); end + + + if 0 + %% + datalim = 3; + [hst1_int,hst2_int] = cat_plot_histogram( char([Pintp{1}{1:datalim}]) , struct( ... + 'color', min(1,repmat( cat_io_colormaps('nejm',size(Pintp{1}{1},1)),datalim,1) + ... + repmat( round(1:size(Pintp{1}{1},1)*datalim)' / size(Pintp{1}{1},1)*datalim / 20 -.05,1,3) ) )); + %% thickness + [hst1_data,hst2_data] = cat_plot_histogram( char([Pdata{1}(1); Pdata{2}(1); Pdata{3}(1)]) , struct( ... + 'color', repmat( cat_io_colormaps('nejm',size(Pintp{1}{1},1)),1,1))); + end + +end","MATLAB" +"Neurology","ChristianGaser/cat12","internal/MFormatter.m",".m","43203","911","classdef MFormatter < handle + % Performs the actual code formatting. Should not be used directly but only by MBeautify. + + properties (Access = private) + SettingConfiguration; + AllOperators; + + % Properties used during the formatting + StringTokenStructs; + BlockCommentDepth; + IsInBlockComment; + + MatrixIndexingOperatorPadding; + CellArrayIndexingOperatorPadding; + end + + properties(Access = private, Constant) + WhiteSpaceToken = '#MBeauty_WhiteSpace_Token'; + ContainerOpeningBrackets = {'[', '{', '('}; + ContainerClosingBrackets = {']', '}', ')'}; + TokenStruct = MFormatter.getTokenStruct(); + end + + methods + + function obj = MFormatter(settingConfiguration) + % Creates a new formatter using the passed configuration. + + obj.SettingConfiguration = settingConfiguration; + + obj.MatrixIndexingOperatorPadding = str2double(obj.SettingConfiguration.SpecialRules.MatrixIndexing_ArithmeticOperatorPaddingValue); + obj.CellArrayIndexingOperatorPadding = str2double(obj.SettingConfiguration.SpecialRules.CellArrayIndexing_ArithmeticOperatorPaddingValue); + + % Init run-time members + obj.StringTokenStructs = {}; + obj.BlockCommentDepth = 0; + obj.IsInBlockComment = false; + + % All of these because of performance reasons + % Update the setting configuration with more members: mostly tokens and regular expressions that can be + % calculated only once, and it costs a lot if they are calculated for every line. + + fieldList = fields(obj.SettingConfiguration.OperatorRules); + obj.AllOperators = cell(numel(fieldList), 1); + + wsTokenLength = numel(obj.WhiteSpaceToken); + + for i = 1:numel(fieldList) + + obj.AllOperators{i} = obj.SettingConfiguration.OperatorRules.(fieldList{i}).ValueFrom; + obj.SettingConfiguration.OperatorRules.(fieldList{i}).OperatorToken = ['#MBeauty_OP_', fieldList{i}, '#']; + + tokenizedReplaceString = strrep(obj.SettingConfiguration.OperatorRules.(fieldList{i}).ValueTo, ... + ' ', obj.WhiteSpaceToken); + % Calculate the starting WS count + leadingWSNum = 0; + matchCell = regexp(tokenizedReplaceString, ['^(', obj.WhiteSpaceToken, ')+'], 'match'); + if numel(matchCell) + leadingWSNum = numel(matchCell{1}) / wsTokenLength; + end + + % Calculate ending whitespace count + endingWSNum = 0; + matchCell = regexp(tokenizedReplaceString, ['(', obj.WhiteSpaceToken, ')+$'], 'match'); + if numel(matchCell) + endingWSNum = numel(matchCell{1}) / wsTokenLength; + end + + obj.SettingConfiguration.OperatorRules.(fieldList{i}).ReplacementPattern = ... + ['\s*(', obj.WhiteSpaceToken, '){0,', num2str(leadingWSNum), '}', ... + obj.SettingConfiguration.OperatorRules.(fieldList{i}).OperatorToken, ... + '(', obj.WhiteSpaceToken, '){0,', num2str(endingWSNum), '}\s*']; + + + if numel(regexp(obj.SettingConfiguration.OperatorRules.(fieldList{i}).ValueFrom, '\+|\-|\/|\*')) + if ~str2double(obj.SettingConfiguration.SpecialRules.MatrixIndexing_ArithmeticOperatorPaddingValue) + obj.SettingConfiguration.OperatorRules.(fieldList{i}).MatrixIndexingReplacementPattern = ... + ['\s*(', obj.WhiteSpaceToken, '){0,0}', ... + obj.SettingConfiguration.OperatorRules.(fieldList{i}).OperatorToken, ... + '(', obj.WhiteSpaceToken, '){0,0}\s*']; + else + obj.SettingConfiguration.OperatorRules.(fieldList{i}).MatrixIndexingReplacementPattern = ... + obj.SettingConfiguration.OperatorRules.(fieldList{i}).ReplacementPattern; + end + + if ~str2double(obj.SettingConfiguration.SpecialRules.CellArrayIndexing_ArithmeticOperatorPaddingValue) + obj.SettingConfiguration.OperatorRules.(fieldList{i}).CellArrayIndexingReplacementPattern = ... + ['\s*(', obj.WhiteSpaceToken, '){0,0}', ... + obj.SettingConfiguration.OperatorRules.(fieldList{i}).OperatorToken, ... + '(', obj.WhiteSpaceToken, '){0,0}\s*']; + else + obj.SettingConfiguration.OperatorRules.(fieldList{i}).CellArrayIndexingReplacementPattern = ... + obj.SettingConfiguration.OperatorRules.(fieldList{i}).ReplacementPattern; + end + end + end + end + + function formattedSource = performFormatting(obj, source) + % Performs formatting on the specified source. + + obj.StringTokenStructs = {}; + obj.BlockCommentDepth = 0; + obj.IsInBlockComment = false; + + nMaximalNewLines = str2double(obj.SettingConfiguration.SpecialRules.MaximalNewLinesValue); + newLine = sprintf('\n'); + + contTokenStruct = MFormatter.TokenStruct.ContinueToken; + + textArray = regexp(source, newLine, 'split'); + + replacedTextArray = {}; + isInContinousLine = 0; + containerDepth = 0; + contLineArray = cell(0, 2); + + nNewLinesFound = 0; + for j = 1:numel(textArray) + line = textArray{j}; + + %% Process the maximal new-line count + if isempty(strtrim(line)) + if nNewLinesFound >= nMaximalNewLines + continue; + end + nNewLinesFound = nNewLinesFound + 1; + else + nNewLinesFound = 0; + end + + %% Determine the position where the line shall be splitted into code and comment + [actCode, actComment, splittingPos] = obj.findComment(line); + + %% Check for line continousment (...) + % Continous lines have to be converted into one single code line to perform replacement on it + % The continousment characters have to be replaced by tokens and the comments of the lines must be stored + % After replacement, the continuosment has to be re-created along with the comments. + + trimmedCode = strtrim(actCode); + if ~numel(trimmedCode) + actCodeFinal = ''; + else + containerDepth = containerDepth + obj.calculateContainerDepthDeltaOfLine(trimmedCode); + + % Auto append ""..."" to the lines of continuous containers + if containerDepth && ~(numel(trimmedCode) >= 3 && strcmp(trimmedCode(end - 2:end), '...')) + if strcmp(trimmedCode(end), ',') || strcmp(trimmedCode(end), ';') + actCode = [trimmedCode, ' ...']; + else + actCode = [actCode, '; ...']; + end + + end + + trimmedCode = strtrim(actCode); + + % Line ends with ""..."" + if (numel(trimmedCode) >= 3 && strcmp(trimmedCode(end - 2:end), '...')) ... + || (isequal(splittingPos, 1) && isInContinousLine) + isInContinousLine = true; + contLineArray{end + 1, 1} = actCode; + contLineArray{end, 2} = actComment; + % Step to next line + continue; + else + % End of cont line + if isInContinousLine + isInContinousLine = false; + contLineArray{end + 1, 1} = actCode; + contLineArray{end, 2} = actComment; + + % Build the line for replacement + replacedLines = ''; + for iLine = 1:size(contLineArray, 1) -1 + tempRow = strtrim(contLineArray{iLine, 1}); + tempRow = [tempRow(1:end - 3), [' ', contTokenStruct.Token, ' ']]; + tempRow = regexprep(tempRow, ['\s+', contTokenStruct.Token, '\s+'], [' ', contTokenStruct.Token, ' ']); + replacedLines = [replacedLines, tempRow]; + end + replacedLines = [replacedLines, actCode]; + + % Replace + actCodeFinal = obj.performReplacements(replacedLines); + + % Re-create the original structure + splitToLine = regexp(actCodeFinal, contTokenStruct.Token, 'split'); + + line = ''; + for iSplitLine = 1:numel(splitToLine) -1 + line = [line, strtrim(splitToLine{iSplitLine}), [' ', contTokenStruct.StoredValue, ' '], contLineArray{iSplitLine, 2}, newLine]; + end + + line = [line, strtrim(splitToLine{end}), actComment]; %#ok<*AGROW> + replacedTextArray = [replacedTextArray, {line, sprintf('\n')}]; + contLineArray = cell(0, 2); + + continue; + end + + end + + actCodeFinal = obj.performReplacements(actCode); + end + + line = [strtrim(actCodeFinal), ' ', actComment]; + replacedTextArray = [replacedTextArray, {line, sprintf('\n')}]; + end + % The last new-line must be removed: inner new-lines are removed by the split, the last one is an additional one + if numel(replacedTextArray) + replacedTextArray(end) = []; + end + + formattedSource = [replacedTextArray{:}]; + end + end + + methods (Access = private, Static) + + function outStr = joinString(cellStr, delim) + + outStr = ''; + for i = 1:numel(cellStr) + outStr = [outStr, cellStr{i}, delim]; + end + + outStr(end-numel(delim)+1:end) = ''; + + end + + function tokenStructs = getTokenStruct() + % Returns the tokens used in replacement. + + % Persistent variable to serve as cache + persistent tokenStructStored; + if isempty(tokenStructStored) + + tokenStructs = struct(); + tokenStructs.ContinueToken = newStruct('...', '#MBeutyCont#'); + tokenStructs.StringToken = newStruct('', '#MBeutyString#'); + tokenStructs.ArrayElementToken = newStruct('', '#MBeutyArrayElement#'); + tokenStructs.TransposeToken = newStruct('''', '#MBeutyTransp#'); + tokenStructs.NonConjTransposeToken = newStruct('.''', '#MBeutyNonConjTransp#'); + tokenStructs.NormNotationPlus = newStruct('+', '#MBeauty_OP_NormNotationPlus'); + tokenStructs.NormNotationMinus = newStruct('-', '#MBeauty_OP_NormNotationMinus'); + tokenStructs.UnaryPlus = newStruct('+', '#MBeauty_OP_UnaryPlus'); + tokenStructs.UnaryMinus = newStruct('-', '#MBeauty_OP_UnaryMinus'); + + tokenStructStored = tokenStructs; + else + tokenStructs = tokenStructStored; + end + + function retStruct = newStruct(storedValue, replacementString) + retStruct = struct('StoredValue', storedValue, 'Token', replacementString); + end + end + + function code = restoreTransponations(code) + % Restores transponation tokens to original transponation signs. + + trnspTokStruct = MFormatter.TokenStruct.TransposeToken; + nonConjTrnspTokStruct = MFormatter.TokenStruct.NonConjTransposeToken; + + code = regexprep(code, trnspTokStruct.Token, trnspTokStruct.StoredValue); + code = regexprep(code, nonConjTrnspTokStruct.Token, nonConjTrnspTokStruct.StoredValue); + end + + function actCode = replaceTransponations(actCode) + % Replaces transponation signs in the code with tokens. + + trnspTokStruct = MFormatter.TokenStruct.TransposeToken; + nonConjTrnspTokStruct = MFormatter.TokenStruct.NonConjTransposeToken; + + charsIndicateTranspose = '[a-zA-Z0-9\)\]\}\.]'; + + tempCode = ''; + isLastCharDot = false; + isLastCharTransp = false; + isInStr = false; + for iStr = 1:numel(actCode) + actChar = actCode(iStr); + + if isequal(actChar, '''') + % .' => NonConj transpose + if isLastCharDot + tempCode = [tempCode(1:end - 1), nonConjTrnspTokStruct.Token]; + isLastCharTransp = true; + else + if isLastCharTransp + tempCode = [tempCode, trnspTokStruct.Token]; + else + if numel(tempCode) && ~isInStr && numel(regexp(tempCode(end), charsIndicateTranspose)) + tempCode = [tempCode, trnspTokStruct.Token]; + isLastCharTransp = true; + else + tempCode = [tempCode, actChar]; + isInStr = ~isInStr; + isLastCharTransp = false; + end + end + end + + isLastCharDot = false; + elseif isequal(actChar, '.') && ~isInStr + isLastCharDot = true; + tempCode = [tempCode, actChar]; + isLastCharTransp = false; + else + isLastCharDot = false; + tempCode = [tempCode, actChar]; + isLastCharTransp = false; + end + end + actCode = tempCode; + end + end + + + methods (Access = private) + function actCodeTemp = replaceStrings(obj, actCode) + % Replaces strings in the code with string tokens while filling StringTokenStructs member to store the + % original values. + + %% Strings + splittedCode = regexp(actCode, '''', 'split'); + + obj.StringTokenStructs = cell(1, ceil(numel(splittedCode) / 2)); + strArray = cell(1, numel(splittedCode)); + + for iSplit = 1:numel(splittedCode) + % Not string + if ~isequal(mod(iSplit, 2), 0) + strArray{iSplit} = splittedCode{iSplit}; + else % String + strTokenStruct = MFormatter.TokenStruct.StringToken; + + strArray{iSplit} = strTokenStruct.Token; + strTokenStruct.StoredValue = splittedCode{iSplit}; + obj.StringTokenStructs{iSplit} = strTokenStruct; + end + end + + obj.StringTokenStructs = obj.StringTokenStructs(cellfun(@(x) ~isempty(x), obj.StringTokenStructs)); + actCodeTemp = [strArray{:}]; + end + + function actCodeFinal = restoreStrings(obj, actCodeTemp) + % Replaces string tokens with the original string from the StringTokenStructs member. + + strTokStructs = obj.StringTokenStructs; + splitByStrTok = regexp(actCodeTemp, MFormatter.TokenStruct.StringToken.Token, 'split'); + + if numel(strTokStructs) + actCodeFinal = ''; + for iSplit = 1:numel(strTokStructs) + actCodeFinal = [actCodeFinal, splitByStrTok{iSplit}, '''', strTokStructs{iSplit}.StoredValue, '''']; + end + + if numel(splitByStrTok) > numel(strTokStructs) + actCodeFinal = [actCodeFinal, splitByStrTok{end}]; + end + else + actCodeFinal = actCodeTemp; + end + end + + function code = performReplacements(obj, code) + % Wrapper around code replacement: Replace transponations -> replace strings -> perform other replacements + % (operators, containers, ...) -> restore strings -> restore transponations. + + code = obj.replaceStrings(obj.replaceTransponations(code)); + code = obj.performFormattingSingleLine(code); + code = obj.restoreTransponations(obj.restoreStrings(code)); + end + + function [actCode, actComment, splittingPos] = findComment(obj, line) + % Splits a continous line into code and comment parts. + + %% Set the variables + retComm = -1; + exclamationPos = -1; + actCode = line; + actComment = ''; + splittingPos = -1; + + trimmedLine = strtrim(line); + + %% Handle some special cases + if isempty(trimmedLine) + return; + elseif strcmp(trimmedLine, '%{') + retComm = 1; + obj.IsInBlockComment = true; + obj.BlockCommentDepth = obj.BlockCommentDepth + 1; + elseif strcmp(trimmedLine, '%}') && obj.IsInBlockComment + retComm = 1; + + obj.BlockCommentDepth = obj.BlockCommentDepth - 1; + obj.IsInBlockComment = obj.BlockCommentDepth > 0; + else + if obj.IsInBlockComment + retComm = 1; + obj.IsInBlockComment = true; + end + end + + if isequal(trimmedLine, '%') || (numel(trimmedLine) > 7 && isequal(trimmedLine(1:7), 'import ')) + retComm = 1; + elseif isequal(trimmedLine(1), '!') + exclamationPos = 1; + end + + splittingPos = max(retComm, exclamationPos); + + if isequal(splittingPos, 1) + actCode = ''; + actComment = line; + return + end + + %% Searh for comment signs(%) and exclamation marks(!) + + exclamationInd = strfind(line, '!'); + commentSignIndexes = strfind(line, '%'); + contIndexes = strfind(line, '...'); + + if ~iscell(exclamationInd) + exclamationInd = num2cell(exclamationInd); + end + if ~iscell(commentSignIndexes) + commentSignIndexes = num2cell(commentSignIndexes); + end + if ~iscell(contIndexes) + contIndexes = num2cell(contIndexes); + end + + % Make the union of indexes of '%' and '!' symbols then sort them + indexUnion = [commentSignIndexes, exclamationInd, contIndexes]; + indexUnion = sortrows(indexUnion(:))'; + + % Iterate through the union + commentSignCount = numel(indexUnion); + if ~commentSignCount + retComm = -1; + exclamationPos = -1; + else + + for iCommSign = 1:commentSignCount + currentIndex = indexUnion{iCommSign}; + + % Check all leading parts that can be ""code"" + % Replace transponation (and noin-conjugate transponations) to avoid not relevant matches + possibleCode = obj.replaceTransponations(line(1:currentIndex - 1)); + + % The line is currently ""not in string"" + if isequal(mod(numel(strfind(possibleCode, '''')), 2), 0) + if ismember(currentIndex, [commentSignIndexes{:}]) + retComm = currentIndex; + elseif ismember(currentIndex, [exclamationInd{:}]) + exclamationPos = currentIndex; + else + % Branch of '...' + retComm = currentIndex + 3; + end + + break; + end + end + end + + splittingPos = max(retComm, exclamationPos); + + if isequal(splittingPos, 1) + actCode = ''; + actComment = line; + elseif splittingPos == -1 + actCode = line; + actComment = ''; + else + actCode = line(1:max(splittingPos - 1, 1)); + actComment = strtrim(line(splittingPos:end)); + end + end + + function data = performFormattingSingleLine(obj, data, doIndexing, contType) + % Performs formatting on a code snippet, where the strings and transponations are already replaced: + % operator, container formatting + + if isempty(data) + return; + end + + if nargin < 3 + doIndexing = false; + end + + if nargin < 4 + contType = ''; + end + + setConfigOperatorFields = fields(obj.SettingConfiguration.OperatorRules); + % At this point, the data contains one line of code, but all user-defined strings enclosed in '' are replaced by #MBeutyString# + + % Old-style function calls, such as 'subplot 211' or 'disp Hello World' -> return unchanged + if numel(regexp(data, '^[a-zA-Z0-9_]+\s+[^(=]')) + + splitData = regexp(strtrim(data), ' ', 'split'); + % The first elemen is not a keyword and does not exist (function on the path) + if numel(splitData) && ~any(strcmp(splitData{1}, iskeyword())) && exist(splitData{1}) %#ok + return + end + end + + % Process matrixes and cell arrays + % All containers are processed element wised. The replaced containers are placed into a map where the key is a token + % inserted to the original data + [data, arrayMapCell] = obj.replaceContainer(data); + + % Convert all operators like + * == etc to #MBeauty_OP_whatever# tokens + opBuffer = {}; + operatorList = obj.AllOperators; + operatorAppearance = regexp(data, operatorList); + + if ~isempty([operatorAppearance{:}]) + for iOpConf = 1:numel(setConfigOperatorFields) + currField = setConfigOperatorFields{iOpConf}; + currOpStruct = obj.SettingConfiguration.OperatorRules.(currField); + dataNew = regexprep(data, ['\s*', currOpStruct.ValueFrom, '\s*'], currOpStruct.OperatorToken); + if ~strcmp(data, dataNew) + opBuffer{end + 1} = currField; + end + data = dataNew; + end + end + + % Remove all duplicate space + data = regexprep(data, '\s+', ' '); + keywords = iskeyword(); + + % Handle special + and - cases: + % - unary plus/minus, such as in (+1): replace #MBeauty_OP_Plus/Minus# by #MBeauty_OP_UnaryPlus/Minus# + % - normalized number format, such as 7e-3: replace #MBeauty_OP_Plus/Minus# by #MBeauty_OP_NormNotation_Plus/Minus# + % Then convert UnaryPlus tokens to '+' signs same for minus) + plusMinusCell = {'Plus', 'Minus'}; + unaryPlusOperatorPresent = false; + unaryMinusOperatorPresent = false; + normPlusOperatorPresent = false; + normMinusOperatorPresent = false; + + for iOpConf = 1:numel(plusMinusCell) + + if any(strcmp(plusMinusCell{iOpConf}, opBuffer)) + + currField = plusMinusCell{iOpConf}; + isPlus = isequal(currField, 'Plus'); + + opToken = obj.SettingConfiguration.OperatorRules.(currField).OperatorToken; + + splittedData = regexp(data, opToken, 'split'); + + replaceTokens = {}; + for iSplit = 1:numel(splittedData) -1 + beforeItem = strtrim(splittedData{iSplit}); + if ~isempty(beforeItem) && numel(regexp(beforeItem, ... + ['([0-9a-zA-Z_)}\]\.]|', MFormatter.TokenStruct.TransposeToken.Token, '|#MBeauty_ArrayToken_.*#)$'])) && ... + (~numel(regexp(beforeItem, ['(?=^|\s)(', MFormatter.joinString(keywords', '|'), ')$'])) || doIndexing) + % + or - is a binary operator after: + % - numbers [0-9.], + % - variable names [a-zA-Z0-9_] or + % - closing brackets )}] + % - transpose signs ', here represented as #MBeutyTransp# + % - keywords + + % Special treatment for E: 7E-3 or 7e+4 normalized notation + % In this case the + and - signs are not operators so shoud be skipped + if numel(beforeItem) > 1 && strcmpi(beforeItem(end), 'e') && numel(regexp(beforeItem(end - 1), '[0-9.]')) + if isPlus + replaceTokens{end + 1} = MFormatter.TokenStruct.NormNotationPlus.Token; + normPlusOperatorPresent = true; + else + replaceTokens{end + 1} = MFormatter.TokenStruct.NormNotationMinus.Token; + normMinusOperatorPresent = true; + end + else + replaceTokens{end + 1} = opToken; + end + else + if isPlus + replaceTokens{end + 1} = MFormatter.TokenStruct.UnaryPlus.Token; + unaryPlusOperatorPresent = true; + else + replaceTokens{end + 1} = MFormatter.TokenStruct.UnaryMinus.Token; + unaryMinusOperatorPresent = true; + end + end + end + + replacedSplittedData = cell(1, numel(replaceTokens) + numel(splittedData)); + tokenIndex = 1; + for iSplit = 1:numel(splittedData) + replacedSplittedData{iSplit * 2 - 1} = splittedData{iSplit}; + if iSplit < numel(splittedData) + replacedSplittedData{iSplit * 2} = replaceTokens{tokenIndex}; + end + tokenIndex = tokenIndex + 1; + end + data = [replacedSplittedData{:}]; + end + end + + %% + % At this point the data is in a completely tokenized representation, e.g.'x#MBeauty_OP_Plus#y' instead of the 'x + y'. + % Now go backwards and replace the tokens by the real operators + + % Special tokens: Unary Plus/Minus, Normalized Number Format + % Performance tweak: only if there were any unary or norm operators + if unaryPlusOperatorPresent + data = regexprep(data, ['\s*', MFormatter.TokenStruct.UnaryPlus.Token, '\s*'], [' ', MFormatter.TokenStruct.UnaryPlus.StoredValue]); + end + if unaryMinusOperatorPresent + data = regexprep(data, ['\s*', MFormatter.TokenStruct.UnaryMinus.Token, '\s*'], [' ', MFormatter.TokenStruct.UnaryMinus.StoredValue]); + end + if normPlusOperatorPresent + data = regexprep(data, ['\s*', MFormatter.TokenStruct.NormNotationPlus.Token, '\s*'], MFormatter.TokenStruct.NormNotationPlus.StoredValue); + end + if normMinusOperatorPresent + data = regexprep(data, ['\s*', MFormatter.TokenStruct.NormNotationMinus.Token, '\s*'], MFormatter.TokenStruct.NormNotationMinus.StoredValue); + end + + + + % Replace all other operators + for iOpConf = 1:numel(setConfigOperatorFields) + + currField = setConfigOperatorFields{iOpConf}; + + if any(strcmp(currField, opBuffer)) + + currOpStruct = obj.SettingConfiguration.OperatorRules.(currField); + + valTo = currOpStruct.ValueTo; + if doIndexing && ~isempty(contType) && numel(regexp(currOpStruct.ValueFrom, '\+|\-|\/|\*')) + if strcmp(contType, 'matrix') + replacementPattern = currOpStruct.MatrixIndexingReplacementPattern; + if ~obj.MatrixIndexingOperatorPadding + valTo = strrep(valTo, ' ', ''); + end + + elseif strcmp(contType, 'cell') + replacementPattern = currOpStruct.CellArrayIndexingReplacementPattern; + if ~obj.CellArrayIndexingOperatorPadding + valTo = strrep(valTo, ' ', ''); + end + end + else + + replacementPattern = currOpStruct.ReplacementPattern; + end + + tokenizedReplaceString = strrep(valTo, ' ', obj.WhiteSpaceToken); + + % Replace only the amount of whitespace tokens that are actually needed by the operator rule + data = regexprep(data, replacementPattern, tokenizedReplaceString); + end + end + + data = regexprep(data, obj.WhiteSpaceToken, ' '); + + data = regexprep(data, ' \)', ')'); + data = regexprep(data, ' \]', ']'); + data = regexprep(data, '\( ', '('); + data = regexprep(data, '\[ ', '['); + + % Restore containers + data = obj.restoreContainers(data, arrayMapCell); + + % Fix semicolon whitespace at end of line + data = regexprep(data, '\s+;\s*$', ';'); + end + + function ret = calculateContainerDepthDeltaOfLine(obj, code) + % Calculates the delta of container depth in a single code line. + + % Pre-check for opening and closing brackets: the final delta has to be calculated after the transponations and the + % strings are replaced, which are time consuming actions + ret = 0; + if numel(regexp(code, '{|[')) || numel(regexp(code, '}|]')) + actCodeTemp = obj.replaceStrings(obj.replaceTransponations(code)); + ret = numel(regexp(actCodeTemp, '{|[')) - numel(regexp(actCodeTemp, '}|]')); + end + end + + function [containerBorderIndexes, maxDepth] = calculateContainerDepths(obj, data) + % Calculates the container boundaries with container depth for a continous code line. + + containerBorderIndexes = {}; + depth = 1; + maxDepth = 1; + for i = 1:numel(data) + borderFound = true; + if any(strcmp(data(i), obj.ContainerOpeningBrackets)) + newDepth = depth + 1; + maxDepth = newDepth; + elseif any(strcmp(data(i), obj.ContainerClosingBrackets)) + newDepth = depth - 1; + depth = depth - 1; + else + borderFound = false; + end + + if borderFound + containerBorderIndexes{end + 1, 1} = i; + containerBorderIndexes{end, 2} = depth; + depth = newDepth; + end + end + end + + function [data, arrayMap] = replaceContainer(obj, data) + % Replaces containers in a code line with container tokens while storing the original container contents in + % the second output argument. + + arrayMap = containers.Map(); + if isempty(data) + return + end + + data = regexprep(data, '\s+;', ';'); + + operatorArray = {'+', '-', '&', '&&', '|', '||', '/', './', '\', '.\', '*', '.*', ':', '^', '.^', '~'}; + contTokenStruct = MFormatter.TokenStruct.ContinueToken; + + [containerBorderIndexes, maxDepth] = obj.calculateContainerDepths(data); + + id = 0; + + while maxDepth > 0 + + if isempty(containerBorderIndexes) + break; + end + + indexes = find([containerBorderIndexes{:, 2}] == maxDepth, 2); + + if ~numel(indexes) || mod(numel(indexes), 2) ~= 0 + maxDepth = maxDepth - 1; + continue; + end + + openingBracket = data(containerBorderIndexes{indexes(1), 1}); + closingBracket = data(containerBorderIndexes{indexes(2), 1}); + + isContainerIndexing = numel(regexp(data(1:containerBorderIndexes{indexes(1), 1}), ['[a-zA-Z0-9_]\s*[', openingBracket, ']$'])); + preceedingKeyWord = false; + if isContainerIndexing + keywords = iskeyword(); + prevStr = strtrim(data(1:containerBorderIndexes{indexes(1), 1} - 1)); + + if numel(prevStr) >= 2 + + for i = 1:numel(keywords) + if numel(regexp(prevStr, ['(\s|^)', keywords{i}, '$'])) + isContainerIndexing = false; + preceedingKeyWord = true; + break; + end + end + end + end + + doIndexing = isContainerIndexing; + contType = ''; + if doIndexing + if strcmp(openingBracket, '(') + doIndexing = true; + contType = 'matrix'; + elseif strcmp(openingBracket, '{') + doIndexing = true; + contType = 'cell'; + else + doIndexing = false; + end + end + + str = data(containerBorderIndexes{indexes(1), 1}:containerBorderIndexes{indexes(2), 1}); + str = regexprep(str, '\s+', ' '); + str = regexprep(str, [openingBracket, '\s+'], openingBracket); + str = regexprep(str, ['\s+', closingBracket], closingBracket); + + if ~strcmp(openingBracket, '(') + if doIndexing + strNew = strtrim(str); + strNew = [strNew(1), strtrim(obj.performFormattingSingleLine(strNew(2:end - 1), doIndexing, contType)), strNew(end)]; + else + elementsCell = regexp(str, ' ', 'split'); + + firstElem = strtrim(elementsCell{1}); + lastElem = strtrim(elementsCell{end}); + + if numel(elementsCell) == 1 + elementsCell{1} = firstElem(2:end - 1); + else + elementsCell{1} = firstElem(2:end); + elementsCell{end} = lastElem(1:end - 1); + end + + for iElem = 1:numel(elementsCell) + elem = strtrim(elementsCell{iElem}); + if numel(elem) && strcmp(elem(1), ',') + elem = elem(2:end); + end + elementsCell{iElem} = elem; + end + + isInCurlyBracket = 0; + for elemInd = 1:numel(elementsCell) -1 + + currElem = strtrim(elementsCell{elemInd}); + nextElem = strtrim(elementsCell{elemInd + 1}); + + if ~numel(currElem) + continue; + end + + isInCurlyBracket = isInCurlyBracket || numel(strfind(currElem, openingBracket)); + isInCurlyBracket = isInCurlyBracket && ~numel(strfind(currElem, closingBracket)); + + currElemStripped = regexprep(currElem, ['[', openingBracket, closingBracket, ']'], ''); + nextElemStripped = regexprep(nextElem, ['[', openingBracket, closingBracket, ']'], ''); + + currElem = strtrim(obj.performFormattingSingleLine(currElem, doIndexing)); + + if strcmp(openingBracket, '[') + addCommas = str2double(obj.SettingConfiguration.SpecialRules.AddCommasToMatricesValue); + else + addCommas = str2double(obj.SettingConfiguration.SpecialRules.AddCommasToCellArraysValue); + end + + if numel(currElem) && addCommas && ... + ~(strcmp(currElem(end), ',') || strcmp(currElem(end), ';')) && ~isInCurlyBracket && ... + ~strcmp(currElem, contTokenStruct.Token) && ... + ~any(strcmp(currElemStripped, operatorArray)) && ~any(strcmp(nextElemStripped, operatorArray)) && ... + ~numel(regexp(currElemStripped, '^@#MBeauty_ArrayToken_\d+#$')) + + elementsCell{elemInd} = [currElem, '#MBeauty_OP_Comma#']; + else + elementsCell{elemInd} = [currElem, ' ']; + end + end + + elementsCell{end} = strtrim(obj.performFormattingSingleLine(elementsCell{end}, doIndexing)); + + strNew = [openingBracket, elementsCell{:}, closingBracket]; + end + else + strNew = strtrim(str); + strNew = [strNew(1), strtrim(obj.performFormattingSingleLine(strNew(2:end - 1), doIndexing, contType)), strNew(end)]; + end + + datacell = cell(1, 3); + if containerBorderIndexes{indexes(1), 1} == 1 + datacell{1} = ''; + else + + datacell{1} = data(1:containerBorderIndexes{indexes(1), 1} - 1); + if isContainerIndexing + datacell{1} = strtrim(datacell{1}); + elseif preceedingKeyWord + datacell{1} = strtrim(datacell{1}); + datacell{1} = [datacell{1}, ' ']; + end + end + + if containerBorderIndexes{indexes(2), 1} == numel(data) + datacell{end} = ''; + else + datacell{end} = data(containerBorderIndexes{indexes(2), 1} + 1:end); + end + + idAsStr = num2str(id); + idStr = [repmat('0', 1, 5 - numel(idAsStr)), idAsStr]; + tokenOfCUrElem = ['#MBeauty_ArrayToken_', idStr, '#']; + arrayMap(tokenOfCUrElem) = strNew; + id = id + 1; + datacell{2} = tokenOfCUrElem; + data = [datacell{:}]; + + containerBorderIndexes = obj.calculateContainerDepths(data); + end + end + + function data = restoreContainers(obj, data, map) + % Replaces container tokens with the original container contents. + + arrayTokenList = map.keys(); + if isempty(arrayTokenList) + return; + end + + for iKey = numel(arrayTokenList):-1:1 + data = regexprep(data, arrayTokenList{iKey}, regexptranslate('escape', map(arrayTokenList{iKey}))); + end + + data = regexprep(data, obj.SettingConfiguration.OperatorRules.Comma.OperatorToken, ... + obj.SettingConfiguration.OperatorRules.Comma.ValueTo); + end + + end +end +","MATLAB" +"Neurology","ChristianGaser/cat12","internal/cat_surf_reduceAvgSurf.m",".m","3711","110","function cat_surf_reduceAvgSurf(P) +% cat_surf_reduceAvgSurf(P) +% ______________________________________________________________________ +% Function to reduce a set of average surface to allow faster +% processing. Although this function worked well, surface processing +% speed was not improved :/ +% +% WARNING: +% The reduction based on the geometry of the average is will trend to +% have large face. +% ______________________________________________________________________ +% Robert Dahnke +% Structural Brain Mapping Group +% University Jena +% ______________________________________________________________________ +% $Id$ + + + if ~isfield('job','P') || isempty(P) + job.P = fullfile(spm('dir'),'toolbox','cat12','templates_surfaces','lh.central.freesurfer.gii'); + end + + def.reduce = 1; % 1 = Matlab; 2=Caret + def.debug = 1; % display debug information + def.reduceCS = 20000; % number of faces of the reduce surfaces + def.CATDir = fullfile(spm('dir'),'toolbox','cat12','CAT'); + + job = cat_io_checkinopt(job,def); + + % add system dependent extension to CAT folder + if ispc + job.CATDir = [job.CATDir '.w32']; + elseif ismac + job.CATDir = [job.CATDir '.maci64']; + elseif isunix + job.CATDir = [job.CATDir '.glnx86']; + end + + + + side = {'lh.','rh.'}; + for si = 1:numel(side) + %% + fprintf('Reduce Average Surface %s\n',side{si}) + + % surface names + [pp,ff,ee] = spm_fileparts(job.P); + + ff = strrep(ff,'lh.',side{si}); + job.Po = fullfile(pp,sprintf('%s%s',ff,ee)); + job.Pr = fullfile(pp,sprintf('%s.%dk%s',ff,job.reduceCS/1000,ee)); + + + % reduce the original surface + if job.reduce == 1 % matlab + CS = gifti(job.Po); clear CSr; + CSr.vertices = double(CS.vertices); CSr.faces = double(CS.faces); + CSr = reducepatch(CSr,job.reduceCS); + save(gifti(struct('faces',int32(CSr.faces),'vertices',single(CSr.vertices))),job.Pr); + + if 0 + % refine to avoid to large faces ... + % the problem is that this will introduce further vertices that do + % not exist in the original surface + % the alternative will be to use caret surface reduction that do + % this more equaly + meshres = 2 * 100000/job.reduceCS; + cmd = sprintf('CAT_RefineMesh ""%s"" ""%s"" %0.2f',job.Pr,job.Pr,meshres); + [ST, RS] = system(fullfile(job.CATDir,cmd)); cat_check_system_output(ST,RS,job.debug); + end + elseif job.reduce == 2 % Caret + % Caret Dir + % hmmm ... no caret_command :/ + + + else + error('job.reduce has to be 1 (Matlab) or 2 (Caret). No reduction make no sense.\n'); + end + + fprintf(' Display reduced average %s\n',spm_file(job.Pr,'link','cat_surf_display(''%s'')')); + + + % create mapping between old and new surace + CSr = gifti(job.Pr); + vusedo = true(size(CS.vertices,1),1); + for vi=1:size(CSr.vertices,1) + vusedo(find(all([CS.vertices(:,1)==CSr.vertices(vi,1), ... + CS.vertices(:,2)==CSr.vertices(vi,2), ... + CS.vertices(:,3)==CSr.vertices(vi,3)],2),1,'first'))=0; + end + + % use mapping for other surface + other = {'sphere','inflated'}; + for oi = 1:numel(other) + job.Pox{oi} = strrep(job.Po,'central',other{oi}); + job.Prx{oi} = strrep(job.Pr,'central',other{oi}); + + CSo = gifti(job.Pox{oi}); + + CSon.vertices = CSo.vertices(vusedo,:); + CSon.faces = CSr.faces; + + save(gifti(struct('faces',int32(CSon.faces),'vertices',single(CSon.vertices))),job.Prx{oi}); + + fprintf(' Display reduced %s %s\n',other{oi},spm_file(job.Pr,'link','cat_surf_display(''%s'')')); + end + end + +end +","MATLAB" +"Neurology","ChristianGaser/cat12","internal/cat_vol_cMRegularizarNLM3D.c",".c","10067","360","/************************************************************************** + * % + * % Jose V. Manjon - jmanjon@fis.upv.es + * % Universidad Politecinca de Valencia, Spain + * % Pierrick Coupe - pierrick.coupe@gmail.com + * % Brain Imaging Center, Montreal Neurological Institute. + * % Mc Gill University + * % + * % Copyright (C) 2010 Jose V. Manjon and Pierrick Coupe + * % + * % + **************************************************************************/ + +#include ""math.h"" +#include ""mex.h"" +#include +#include +#include +#include + +struct myargument +{ + int rows; + int cols; + int slices; + double * in_image; + double * out_image; + double * mean_image; + double * pesos; + int ini; + int fin; + int radio; + int f; + int th; + int sigma; +}; + + +double distancia(double* ima,int x,int y,int z,int nx,int ny,int nz,int f,int sx,int sy,int sz) +{ + double d,acu,distancetotal,inc; + int i,j,k,ni1,nj1,ni2,nj2,nk1,nk2; + + distancetotal=0; + + for(k=-f;k<=f;k++) + { + nk1=z+k; + nk2=nz+k; + if(nk1<0) nk1=-nk1; + if(nk2<0) nk2=-nk2; + if(nk1>=sz) nk1=2*sz-nk1-1; + if(nk2>=sz) nk2=2*sz-nk2-1; + + for(j=-f;j<=f;j++) + { + nj1=y+j; + nj2=ny+j; + if(nj1<0) nj1=-nj1; + if(nj2<0) nj2=-nj2; + if(nj1>=sy) nj1=2*sy-nj1-1; + if(nj2>=sy) nj2=2*sy-nj2-1; + + for(i=-f;i<=f;i++) + { + ni1=x+i; + ni2=nx+i; + if(ni1<0) ni1=-ni1; + if(ni2<0) ni2=-ni2; + if(ni1>=sx) ni1=2*sx-ni1-1; + if(ni2>=sx) ni2=2*sx-ni2-1; + + distancetotal = distancetotal + ((ima[nk1*(sx*sy)+(nj1*sx)+ni1]-ima[nk2*(sx*sy)+(nj2*sx)+ni2])*(ima[nk1*(sx*sy)+(nj1*sx)+ni1]-ima[nk2*(sx*sy)+(nj2*sx)+ni2])); + } + } + } + + acu=(2*f+1)*(2*f+1)*(2*f+1); + d=distancetotal/acu; + + return d; + +} + +void * ThreadFunc( void* pArguments ) +{ + double *ima,*fima,*medias,*pesos,w,d,hh,th,t1; + int ii,jj,kk,ni,nj,nk,i,j,k,ini,fin,rows,cols,slices,v,p,p1,f,rc; + + struct myargument arg; + arg=*(struct myargument *)pArguments; + + rows=arg.rows; + cols=arg.cols; + slices=arg.slices; + ini=arg.ini; + fin=arg.fin; + ima=arg.in_image; + fima=arg.out_image; + medias=arg.mean_image; + pesos=arg.pesos; + v=arg.radio; + f=arg.f; + th=arg.th; + hh=arg.sigma; + rc=rows*cols; + + /* filter*/ + for(k=ini;k=0 && nj>=0 && nk>=0 && nith) continue; + + d=distancia(ima,i,j,k,ni,nj,nk,f,cols,rows,slices); + + d=d/hh-1; + if(d<0) d=0; + + w = exp(-d); + + fima[p] = fima[p] + w*ima[p1]; + pesos[p] = pesos[p] + w; + + fima[p1] = fima[p1] + w*ima[p]; + pesos[p1] = pesos[p1] + w; + } + } + } + } + } + } + } + + pthread_exit(0); +} + + + +void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) +{ + +/*Declarations*/ + const mxArray *xData; + double *ima, *fima,*pesos,*lf; + mxArray *Mxmedias,*Mxpesos,*xtmp; + double *medias,*tmp; + const mxArray *pv; + double off,h,media,th,hh; + int ini,fin,i,j,k,ii,jj,kk,ni,nj,nk,v,ndim,indice,f,Nthreads,rc,ft; + const mwSize *dims; + int fac[3]; + bool salir; + void *retval; + + struct myargument *ThreadArgs; + pthread_t *ThreadList; + + if(nrhs<5) + { + printf(""Wrong number of arguments!!!\r""); + return; + } + +/*Copy input pointer x*/ + xData = prhs[0]; + +/*Get matrix x*/ + ima = mxGetPr(xData); + + ndim = mxGetNumberOfDimensions(prhs[0]); + dims= mxGetDimensions(prhs[0]); + + pv = prhs[1]; + v = (int)(mxGetScalar(pv)); + pv = prhs[2]; + f = (int)(mxGetScalar(pv)); + pv = prhs[3]; + h = (double)(mxGetScalar(pv)); + hh=2*h*h; + pv = prhs[4]; + lf = (double*)(mxGetPr(pv)); + for(i=0;i<3;i++) fac[i]=(int)lf[i]; + +/*Allocate memory and assign output pointer*/ + + plhs[0] = mxCreateNumericArray(ndim,dims,mxDOUBLE_CLASS, mxREAL); + Mxmedias = mxCreateNumericArray(ndim,dims,mxDOUBLE_CLASS, mxREAL); + xtmp = mxCreateNumericArray(ndim,dims,mxDOUBLE_CLASS, mxREAL); + tmp = mxGetPr(xtmp); + +/*Get a pointer to the data space in our newly allocated memory*/ + fima = mxGetPr(plhs[0]); + medias = mxGetPr(Mxmedias); + + Mxpesos = mxCreateNumericArray(ndim,dims,mxDOUBLE_CLASS, mxREAL); + pesos = mxGetPr(Mxpesos); + + + /* das ist doch nur ein median filter oder? */ + /* ---------------------------------------- */ + rc=dims[0]*dims[1]; + for(k=0;k=dims[0]) ni=2*dims[0]-ni-1; + for(jj=-1;jj<=1;jj++) { + nj=j+jj; + if(nj<0) nj=-nj; + if(nj>=dims[1]) nj=2*dims[1]-nj-1; + for(kk=-1;kk<=1;kk++) { + nk=k+kk; + if(nk<0) nk=-nk; + if(nk>=dims[2]) nk=2*dims[2]-nk-1; + + media += ima[nk*rc+nj*dims[0]+ni]; + } + } + } + medias[k*rc+j*dims[0]+i]=media/27; + } + } + } + + /* ein weiterer median filter... */ + /* ----------------------------- */ + ft=fac[2]*fac[1]*fac[0]; + for(k=0;k0.3)) ... + min([ cat_stat_nanmean(res.mn(res.lkp==1 & res.mg'>0.3)) - ... + diff([cat_stat_nanmean(res.mn(res.lkp==1 & res.mg'>0.3)),cat_stat_nanmean(res.mn(res.lkp==2 & res.mg'>0.3))]),... + cat_stat_nanmean(res.mn(res.lkp==3 & res.mg'>0.3))]) ... CSF + cat_stat_nanmean(res.mn(res.lkp==1 & res.mg'>0.3)) ... GMth + cat_stat_nanmean(res.mn(res.lkp==2 & res.mg'>0.3)) ... WMth + cat_stat_nanmean(res.mn(res.lkp==2 & res.mg'>0.3)) + ... WM+ + abs(diff(max(... + [cat_stat_nanmean(res.mn(res.lkp==1 & res.mg'>0.3)),cat_stat_nanmean(res.mn(res.lkp==2 & res.mg'>0.3))],... + [cat_stat_nanmean(res.mn(res.lkp==1 & res.mg'>0.3)),cat_stat_nanmean(res.mn(res.lkp==3 & res.mg'>0.3))]/2)*1.5)) ... + max(Ysrc(:))]; + T3thx = [0,0.05,1,2,3,4,5]; + else + T3ths = [min(Ysrc(:)),myint{id,2}(1:5),myint{id,2}(5) + abs(diff(myint{id,2}(3:2:5))),max(Ysrc(:))]; + T3thx = [0,0.05,1,1.66,2.33,3,4,5]; + end + + [T3ths,si] = sort(T3ths); + T3thx = T3thx(si); + Ym = Ysrc+0; + for i=numel(T3ths):-1:2 + M = Ysrc>T3ths(i-1) & Ysrc<=T3ths(i); + Ym(M(:)) = T3thx(i-1) + (Ysrc(M(:)) - T3ths(i-1))/diff(T3ths(i-1:i))*diff(T3thx(i-1:i)); + end + M = Ysrc>=T3ths(end); + Ym(M(:)) = numel(T3ths)/6 + (Ysrc(M(:)) - T3ths(i))/diff(T3ths(end-1:end))*diff(T3thx(i-1:i)); + + + % create brainmask + id = find(cellfun('isempty',strfind(mymask(:,1),ff))==0); %#ok + if isempty(id) + Yb = smooth3(Yp0>0.5 | (Yp0>0.2 & Ym<1.5))>0.1; + else + Yb = Ym>0; + end + + + % copy of the original bias corrected + copyfile(Vm.fname,fullfile(rpp,sprintf('b%s.nii',ff))); + + + % ISARNLM noise correction and creation of output image + if job.isarnlm, fprintf('ISAR1 .. ',ff); Ysrc = cat_vol_sanlm(struct(),Vm,1,Ysrc); end + Vm2 = Vm; Vm2.fname = fullfile(rpp,sprintf('m%s.nii',ff)); + spm_write_vol(Vm2,Ysrc); + + + % ISARNLM noise correction and creation of output image + if job.isarnlm, fprintf('ISAR2 .. ',ff); Ym = cat_vol_sanlm(struct(),Vm,1,Ym); end + Vm2 = Vm; Vm2.fname = fullfile(rpp,sprintf('n%s.nii',ff(2:end))); + spm_write_vol(Vm2,Ym); + + + + + %% -- create slice mask ----------------------------------------------- + mati = spm_imatrix(Vm.mat); %*res.Affine); % .*sign(mati(7:9)) res.Affine + %slicepointsubject = round((slicepoint - mati(1:3))./mati(7:9)); + id = find(cellfun('isempty',strfind(mypoints(:,1),ff))==0); + if isempty(id) || isempty(mypoints{id,2}) + vmat = res.Affine * Vm.mat; vmat = inv(vmat); + slicepointsubject = round(vmat * [slicepoints .* sign(mati(7:9)) ,1]'); slicepointsubject = slicepointsubject(1:3)'; + else + vmat = res.Affine * Vm.mat; vmat = inv(vmat); + slicepointsubject = round(vmat * [mypoints{id,2} .* sign(mati(7:9)) ,1]'); slicepointsubject = slicepointsubject(1:3)'; + end + + Yslicemask = false(size(Ym)); + for si=1:size(slicepointsubject,1) + Yslicemask(slicepointsubject(1),:,:) = true; + Yslicemask(:,slicepointsubject(2),:) = true; + Yslicemask(:,:,slicepointsubject(3)) = true; + end + + % display + try + %% + ds('l2','',vx_vol,Ym/3,Yp0 +3 * Yslicemask,Ysrc/T3ths(end-2),round(Ym)/3,slicepointsubject(3)+1); + T3ths/T3ths(end-2), T3ths(end-2) + end + + %% intensity-based segmentation + id = find(cellfun('isempty',strfind(mysmooth(:,1),ff))==0); + if isempty(id) || isempty(mysmooth{id,2}) + Yp0pm = round( max(1, Ym ) ); + else + Yp0pm = cat_vol_smooth3X(Ym,mysmooth{id,2}); %/mean(vx_vol) + Yp0pm = round( max(1, Yp0pm ) ); + end + Yp0pm(Yp0pm>3.5 | ~Yb) = 0; + Vp0m = Vm; Vp0m.fname = fullfile(rpp,sprintf('p0m%s.nii',ff)); + spm_write_vol(Vp0m,Yp0pm); + Vp0m = Vm; Vp0m.fname = fullfile(rpp,sprintf('p0s%s.nii',ff)); + spm_write_vol(Vp0m,Yp0pm.*Yslicemask); + + if 1 + %% display + ds('l2','m',vx_vol,Ym/3,Yp0pm +3 * Yslicemask,Ysrc/T3ths(end-2),round(Ym)/3,slicepointsubject(1)+1); + %% + ds('l2','a',vx_vol,Ym/3,Yp0pm +3 * Yslicemask,Ysrc/T3ths(end-2),round(Ym)/3,slicepointsubject(2)+1); + %% + ds('l2','',vx_vol,Ym/3,Yp0pm +3 * Yslicemask,Ysrc/T3ths(end-2),round(Ym)/3,slicepointsubject(3)+1); + end + + %% + if 0 + ds('l2','',vx_vol,Ym/3,Yb+6*Yslicemask,Ym/3,round( max(1,Ym) )/3,slicepointsubject(3)+1); + T3ths/T3ths(end-2), T3ths(end-2), fprintf('\n '); + end + + % slicemask + %system('/opt/local/lib/cmtk/bin/cmtk convertx + + end +end + + + + + + +","MATLAB" +"Neurology","ChristianGaser/cat12","internal/cat_stat_check_cov2.m",".m","219619","5328","function varargout = cat_stat_check_cov2(job) +% cat_stat_check_cov +% _________________________________________________________________________ +% Function to check covariance and image quality across samples. +% Use the CAT GUI or SPM batch mod for initialization. +% +% Selected volumes have to be in the same orientation with same voxel +% size and dimension (e.g., spatially registered images), whereas surfaces +% have to be same size (number of vertices; i.e., resampled surfaces). +% +% varargout = cat_stat_check_cov(job) +% +% job .. spm job structure +% .data_vol .. volume input files +% .data_surf .. surface input files +% .c .. nuisance variables (cell) +% [.gap] .. gap between slices (in case of volume input) +% varargout .. +% +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + +%#ok<*AGROW,*ASGLU,*TRYNC,*MINcscc.data.V,*INUSD,*INUSL,*MINV> + + +% ------------------------------------------------------------------------- +% Extra development +% +% - (X) CAT version & parameter control +% - Show cat-version in datatip +% > required version management update in cat_tst_qa +% - Use CAT version number as nuisance variable +% > ask Christian .. maybe as flag +% - (X) Create CAT segmentation parameter as nuisance variable: +% n-dimensional distance of biasstr, APP, GCUT+cleanup, LASstr, regstr? +% +% ------------------------------------------------------------------------- +% +% Development: +% - (5) Load surfaces in graphic window or close to it (sorted). +% - (5) Data trashing +% - message window if no images were selected +% - (5) Colorbar: +% - Define Colorbar (min-max, auto=sd-factor), (+-)-buttons? +% - Auto/fixed colorbar in scatterplot > redraw function? +% - sample / protocol / global scaling ... +% > scatter plot update function +% - (4) Use resampled surface if possible (faster) +% - if more than one > which one? > fastest & less smoothed +% - (1) Autotrash > groups with percentual number of files ? +% - (1) add LEFT/RIGHT, COLUMN/ROW legend to surface slice print +% +% ------------------------------------------------------------------------- +% +% Possible extensions: +% - (2) Options button with a submenu to set default display options and behavior +% - open original vs. normalized volumes / surfaces +% - affine registered volumes +% - use global scale for processing / visualization (initial parameter) +% - display datatip variables +% - choose colormap +% - choose window colors +% - (0) Icons for (sorted) Matrixplot, Maha Dist, Worst MNC Cases, +% (Sub)Boxplots (MNC, QA, nuisance) ? +% - (1) overlay with half transparency for 1-2 SD +% - (1) Data viewing GUI +% - open all similar objects in scatter plot? - Use colored edges? +% - (5) show load progress in case of surface display +% > not so easy > cat_surf_render! +% - (4) Button to enlarge the slice-figure in the SPM graphics window +% (close to slider) +% - (2) multiview of highly correlated datasets in scatterplot with +% modified check icons (Button for on/off?) +% - (1) try to get all figure handles even in case of additional surface +% figures (and not try to close figure 2:26) +% - (1) error message if all scans of a group are missing +% - (1) mark critical selections, e.g of protokol/sample (red background) with redraw +% - (0) more space for the title of the boxplot (in case of complex group paths) +% +% ------------------------------------------------------------------------- +% +% Rejected ideas: +% - Use ROI-files to check regions? +% > This would be a separate call of Checkcov that is not required yet. +% +% - Longitudinal mode? +% > Too complex right now due to manifold data structure and varying +% number of scans. +% +% - Use multiple datatips? +% > Multiple datatips would be nice to view and (de)exclude multiple +% objects but will have unclear behavior for the slice window. +% > Deselection is not intuitive! The required number variates (many for +% delete, less for view). +% > This would be elaborate and confusing and it is easier to use only +% one at all! +% +% - Save/load functions (buttons) for the selection list? +% > This requires a strong interaction between the disk data and virtual +% data structure. +% > Elaborative and not really important. +% +% - Boxplot dependency for ?Data selection?, i.e. show only data visible +% in matrix/scatter plot? +% > No, because this generally removes the samples and this is not required. +% +% - Use of a table with parameters (MNC, IQR, PIQR, IQRratio, nuisance, autotrash, +% tissue volume, cat_pp_version, cat_pp_para, Euler, ...) in an extra +% figure or the SPM Graphics window? +% > No, this is not required and elaborative, because Checkcov is a graphic +% tool that already combines such information in abstract figures +% (covar matrix, IQRratio). +% +% - Show autotrash in datatip +% > No, because it depend on further autotrash options +% +% - Display additional data (IQR,MNC, ?) in/close to sliceplot +% > No, the data was added to the datatip. Overall there is not enough +% space for this, requiring an additional figure ... +% +% ------------------------------------------------------------------------- + + if nargin == 0, error('No argument given.'); end + + % remove old figure + oldfig = findobj('type','figure','number',2); + if ~isempty(oldfig); delete(oldfig); end + + % create default SPM windows if required + if isempty(spm_figure('FindWin','Interactive')) + spm('createintwin'); + end + if isempty(spm_figure('FindWin','Graphics')) + spm_figure('Create','Graphics',sprintf('%s: Graphics',spm('version'))); + end + + cat_io_cprintf('err','\nWARNING: cat_stat_check_cov2 is in development!\n\n') + + +% ------------------------------------------------------------------------- +% Overview of the main global datastructure of cscc of cat_stat_check_cov +% ------------------------------------------------------------------------- +% cscc .. cat_stat_check_cov (cscc) data structure as short unique global +% variable that nobody else use +% .H .. object/button/image/axis handles +% .mesh_detected .. volume vs. surface mode (=1) +% .isscatter .. Covariance matrix vs. Mahanalobis plot (=1) +% .isxml .. CAT XML are available +% .sorted .. sorted Covariance matrix? +% .show_name .. show names in boxplot +% .inorm .. normalize image intensity (for display) ??? +% .cbar .. Colorbar +% ... .. see create_figure subfunction +% .pos .. position values for GUI objects/buttons +% ... .. see initialization below +% .data +% .YpY .. covariance matrix +% .QM .. Quality measures from xml files +% .QMnames .. name of the cscc.data.QM rows +% .mean_cov .. mean covariance matrix +% .img .. slice image(s) for GUI display +% .img_alpha .. slice image(s) for GUI display +% .cata .. minimum/maximum value of the mesh +% .V .. header of the input files (volume/surface) +% .Vo .. header of the original volume files (used for +% preprocessing +% .img_alpa .. +% *Vchanged .. modified volume header for 4D-structures +% *Vchanged_names .. modified volume header for 4D-structures +% .X .. data structure for Norm. Ratio IQR/mean correlation +% .X2 .. data structure for Norm. Ratio IQR/mean correlation +% .IQRratio .. data structure for Norm. Ratio IQR/mean correlation +% .IQRratio .. data structure for Norm. Ratio IQR/mean correlation +% .files .. CAT preprocessing files +% .data .. normalized input files of cat_stat_check_cov +% (e.g. wmp1, thickness, curv, ...) +% .org .. original files used for preprocessing +% .surf .. surface files (thickness, mesh) +% .surfr .. resampled files (thickness, mesh) +% .xml .. cscc.data.XML data of CAT preprocessing +% .log .. log-file of CAT preprocessing +% .pdf .. pdf-file of CAT preprocessing (report figure) +% .jpg .. pdf-file of CAT preprocessing (report figure) +% .fname .. structure from spm_str_manip with grouped filenames +% .dataprefix .. only the prefix of the data input +% .select +% .trashlist .. index list of subjects to remove +% .trashhist .. undo trash list +% .trashhistf .. redo trash list +% .trash1d .. 1D mask for files on the trash list +% .trash2d .. 2D mask for files on the trash list +% .samp1d .. 1D mask for cscc.datagroups.sample view +% .samp2d .. 2D mask for cscc.datagroups.sample view +% .prot1d .. 1D mask for cscc.datagroups.protocol view +% .prot2d .. 2D mask for cscc.datagroups.protocol view +% .datagroups +% .n_samples +% .sample +% .protocol +% .protocols +% .display .. display and print variables +% .WS .. SPM window size +% .FS .. list of SPM font size +% .FSi .. main selection of SPM font size +% .figcolor .. background color of main figure +% .useicons .. use button icons (use JAcscc.data.VA workaround) +% ------------------------------------------------------------------------- + + clearvars -GLOBAL cscc; % clear old + global cscc; % create new + cscc.job = job; + cscc.job.expertgui = cat_get_defaults('extopts.expertgui'); + cscc.H = struct(); + cscc.H.cbarfix.Value = 0; % inactive + + + cscc.display = struct( ... display and print variables + 'WS', spm('Winsize','Graphics'), ... SPM window size + 'FS', spm('FontSizes'), ... list of SPM font size + 'FSi', 8, ... main selection of SPM font size + 'figcolor',[0.8 0.8 0.8], ... background color of main figure + 'useicons',1); % use button icons (use JAcscc.data.VA workaround!) + + + cscc.select.trashlist = []; % start with empty list + cscc.select.trashhist = []; % history of trash operations (for undo) + cscc.select.trashhistf = []; % history of trash operations (for redo) + + + cscc.H.sorted = 0; % show data by file order + cscc.H.isscatter = 0; % active GUI surface plot + cscc.H.show_name = 0; % show filenames in boxplot rather small dots + cscc.H.inorm = 1; % normalize slice intensity even in normalized data + + + % volume or surfaces + if isfield(job,'data_vol') + datafield = 'data_vol'; + datadir = 'mri'; + cscc.H.mesh_detected = 0; + elseif isfield(job,'data_surf') + datafield = 'data_surf'; + datadir = 'surf'; + cscc.H.mesh_detected = 1; + end + cscc.files.datafield = datafield; + + + % positions & global font size option + cscc.display.WP = get(spm_figure('FindWin','Graphics'),'Position'); + if cscc.display.WP(2)>0 && cscc.display.WP(2)<50 + cscc.display.WP = cscc.display.WP(2); + else + cscc.display.WP = 10; + end + + cscc.H.show_violin = 1; + + popb = [0.038 0.035]; % size of the small buttons + popm = 0.780; % x-position of the control elements + + + cscc.posp = struct('naviui',0.835,'trashui',0.725,'checkui',0.780); % y-pos of major control elements + cscc.pos = struct(... + 'fig', [cscc.display.WP(1) cscc.display.WP(1) ... + 1.4*cscc.display.WS(3) 1.2*cscc.display.WS(3)],... % figure + 'popup', [10 10 200 100 ],... % popup in case of closing with non-empty trash list + 'trashpopup', [0.7*cscc.display.WS(3) 0.4*cscc.display.WS(3) ... + 1.2*cscc.display.WS(3) 0.9*cscc.display.WS(3)],... % figure + ... + 'corr', [0.045 0.050 0.700 0.820],... % correlation matrix + 'slice', [0.780 0.060 0.190 0.450] - cscc.H.mesh_detected*[0 0.01 0 0],... % image plot + ...'surfi', [0.780 0.050 0.190 0.560],... % image plot + 'cbar', [0.045 0.950 0.700 0.020],... % colorbar for correlation matrix + ...'cbar', [0.045 0.950 0.580 0.020],... % colorbar for correlation matrix (active cbarfix) + ...'cbarfix', [0.657 0.943 0.100 0.030],... % colorbar fix/auto option (active cbarfix) + ... see also cscc.H.cbarfix.Value and checkbox_cbarfix function! + ... + 'boxplot', [0.100 0.055 0.880 0.915],... % boxplot axis + 'refresh', [0.100 0.003 0.055 0.032],... % refresh boxplot + 'worst', [0.150 0.003 0.200 0.032],... % show worst (in boxplot) + 'fnamesbox', [0.830 0.001 0.160 0.032],... % show filenames in boxplot + 'plotbox', [0.830 0.022 0.160 0.032],... % switch between boxplot and violin plot + ... + 'close', [0.775 0.935 0.100 0.040],... % close button + 'help', [0.875 0.935 0.100 0.040],... % help button + ... + 'sort', [0.772 0.880 0.110 0.050],... % list to use ordered matrix or IQRratio + 'boxp', [0.872 0.880 0.110 0.050],... % list to display different variables as boxplot + 'samp', [0.772 0.615 0.110 0.055],... % list to use ordered matrix or IQRratio + 'prot', [0.872 0.615 0.110 0.055],... % list to display different variables as boxplot + 'showtrash', [0.776 0.610 0.110 0.025],... % colorbar fix/auto option + ... + 'alphabox', [0.775 -0.001 0.200 0.030] + cscc.H.mesh_detected*[0 0.016 0 0],... % show filenames in boxplot + 'sslider', [0.780 0.030 0.193 0.040],... % slider for z-slice + ... + ... == navigation unit == + 'scSelect', [popm+popb(1)*0 cscc.posp.naviui popb],... % select (default) + 'scZoomReset', [popm+popb(1)*1 cscc.posp.naviui popb],... % standard zoom + 'scZoomIn', [popm+popb(1)*2 cscc.posp.naviui popb],... % zoom in + 'scZoomOut', [popm+popb(1)*3 cscc.posp.naviui popb],... % zoom out + 'scPan', [popm+popb(1)*4 cscc.posp.naviui popb],... % pan (moving hand) + ... + ... == tashlist unit == + 'newtrash', [popm+popb(1)*0 cscc.posp.trashui popb],... % new trash list + 'disptrash', [popm+popb(1)*1 cscc.posp.trashui popb],... % print trash list + 'trash', [popm+popb(1)*2 cscc.posp.trashui popb],... % add data to trash list + 'detrash', [popm+popb(1)*3 cscc.posp.trashui popb],... % remove data from trash list + 'autotrash', [popm+popb(1)*4 cscc.posp.trashui popb],... % button to mark data with low IQR + ... second row + 'undo', [popm+popb(1)*0 cscc.posp.trashui-popb(2) popb],... % undo last trash list operation + 'redo', [popm+popb(1)*1 cscc.posp.trashui-popb(2) popb],... % redo last trash list operation + 'trashrow', [popm+popb(1)*2 cscc.posp.trashui-popb(2) popb],... % add data to trash list + 'detrashrow', [popm+popb(1)*3 cscc.posp.trashui-popb(2) popb],... % button to mark data with low IQR + 'ziptrash', [popm+popb(1)*4 cscc.posp.trashui-popb(2) popb],... % pack data from trash list + ... + ... == checklist unit == + 'checkvol', [popm+popb(1)*0 cscc.posp.checkui popb],... % open checkvol + 'checksurf', [popm+popb(1)*1 cscc.posp.checkui popb],... % open checksurf + 'checklog', [popm+popb(1)*2 cscc.posp.checkui popb],... % open log-txt + 'checkxml', [popm+popb(1)*3 cscc.posp.checkui popb],... % open xml-txt + 'checkpdf', [popm+popb(1)*4 cscc.posp.checkui popb]); % open pdf in external viewer + % checksurfn? + + + + + %% get all filenames from the data_vol/surf input + % ---------------------------------------------------------------------- + + % get all input scans/surfaces + cscc.files.data = {}; cscc.files.dataid = zeros(0,3); + for i = 1:numel(job.(datafield)) + cscc.files.data = [cscc.files.data;cellstr(char(job.(datafield){i}))]; + cscc.files.dataid = [cscc.files.dataid; ... + [(numel(cscc.files.dataid) + (1:numel(job.(datafield){i})) - 1)', ... + repmat(i,numel(job.(datafield){i}),1), ... + (1:numel(job.(datafield){i}))']]; + end + + + + % define trash directory + % ---------------------------------------------------------------------- + trashdirname = '+cat_checkcov_excluded'; + if ~isfield(job,'trashdirhome') + [dirnames,dparts] = spm_str_manip(char(cscc.files.data(:)),'hC'); + [pp,dd,ee] = spm_fileparts(dparts.s); dd = [dd ee]; + else + pp = job.trashdirhome; + end + cscc.trashdir = fullfile(pp,trashdirname); + try + if ~exist(cscc.trashdir,'dir'), mkdir(cscc.trashdir); end + catch + cat_io_cprintf('warn','Was not able to create default exclusion directory:\n %s',cscc.trashdir); + cscc.trashdir = fullfile(pp,dd,trashdirname); + try + if ~exist(cscc.trashdir,'dir'), mkdir(cscc.trashdir); end + catch + cat_io_cprintf('warn','Was not able to create alternative exclusion directory:\n %s',cscc.trashdir); + cscc.trashdir = fullfile(spm_select(1,'dir','Select exclusion home directory'),trashdirname); + try + if ~exist(cscc.trashdir,'dir'), mkdir(cscc.trashdir); end + catch + error('cat_stat_check_cov2:mktrashdir',... + 'Was not able to create exclusion directory (check writing rights):\n %s',cscc.trashdir); + end + end + end + fprintf('Exclusion directory: \n %s\n\n',cscc.trashdir) + + + + % remove files that do not exist + cscc.oldtrash = cat_vol_findfiles(cscc.trashdir,'*-*-*',struct('depth',1)); + isfirst = 1; + for fi=numel(cscc.files.data):-1:1 + [pp,ff,ee] = spm_fileparts(cscc.files.data{fi}); + + % remove MAC OS hidden files + if strcmp(ff(1:2),'._') + cscc.files.data(fi) = []; + job.(datafield){cscc.files.dataid(fi,2)}(cscc.files.dataid(fi,3)) = []; + if isfield(job,'data_xml') && ~isempty(job.data_xml) && numel(job.data_xml)>fi + job.data_xml(fi) = []; + end + if ~isempty(job.c) + for i=1:numel(job.c) + job.c{i}(fi) = []; + end + end + continue + end + + + % remove non existing OS hidden files + if ~exist(fullfile(pp,[ff ee]),'file') + if isfirst + fprintf('Miss input data:\n') + isfirst=0; + end + fprintf(' %s\n',cscc.files.data{fi}); + cscc.files.data(fi) = []; + job.(datafield){cscc.files.dataid(fi,2)}(cscc.files.dataid(fi,3)) = []; + if ~isempty(job.data_xml) && numel(job.data_xml)>fi + job.data_xml(fi) = []; + end + if ~isempty(job.c) + for i=1:numel(job.c) + job.c{fi}(i) = []; + end + end + end + end + + + + % number of scans, samples and prtocols; trash mask arrays, sample array + n_subjects = numel(cscc.files.data); + cscc.datagroups.n_samples = numel(job.(datafield)); + cscc.datagroups.n_subjects = numel(cscc.files.data); + cscc.select.trash1d = true(n_subjects,1); % trash list mask 1D matrix + cscc.select.trash2d = true(n_subjects,n_subjects); % trash list mask 2D matrix + cscc.select.samp1d = cscc.select.trash1d; + cscc.select.samp2d = cscc.select.trash2d; + cscc.select.prot1d = cscc.select.trash1d; + cscc.select.prot2d = cscc.select.trash2d; + cscc.datagroups.sample = []; + cscc.datagroups.protocol = []; + for i = 1:cscc.datagroups.n_samples + cscc.datagroups.sample = ... + [cscc.datagroups.sample, i * ones(1,size(job.(datafield){i},1))]; + end + + + + + %% get the different files + % ---------------------------------------------------------------------- + spm_progress_bar('Init',numel(cscc.files.data),'Search files','subjects completed') + spm_figure('GetWin','Interactive'); + [filenames,fparts] = spm_str_manip(cscc.files.data,'trC'); + cscc.files.out = cscc.files.data; + cscc.files.org = cscc.files.data; + cscc.files.pdf = cscc.files.data; + cscc.files.jpg = cscc.files.data; + cscc.files.xml = cscc.files.data; + cscc.files.log = cscc.files.data; + cscc.files.surf = cscc.files.data; + cscc.files.surfr = cscc.files.data; + + % get real prefix + % - expect that all files have the same prefix + % - fparts.s is not enough if all file start similar, eg. mwp1ADNI_*.nii + [tmp,lfname] = max(cellfun('length',fparts.m)); % longest filename + [pp,ff,ee] = spm_fileparts(cscc.files.data{lfname}); + [pp1,pp2] = spm_fileparts(pp); + orgfile = cat_vol_findfiles(pp1,... + ['*' cat_io_strrep(ff,fparts.s,'') '.nii'],struct('depth',1)); + if isempty(orgfile) + orgfile = cat_vol_findfiles(pp1,... + ['*' cat_io_strrep(ff,fparts.s,'') '.img'],struct('depth',1)); + end + [tmp,sfname] = min(cellfun('length',orgfile)); % shortest of the longest + [ppo,ffo,eeo] = spm_fileparts(orgfile{sfname}); + cscc.files.dataprefix = ff(1:strfind(ff,ffo)-1); + clear orgfile; + + % find files + for i = 1:numel(cscc.files.data) + [pp,ff,ee] = spm_fileparts(cscc.files.data{i}); + [pp1,pp2] = spm_fileparts(pp); + + % output files + cscc.files.out{i} = fullfile(pp,ff,ee); + + % set subdirectories + if strcmp(pp2,datadir) + reportdir = 'report'; + surfdir = 'surf'; + else + reportdir = ''; + surfdir = ''; + end + + fname = cat_io_strrep(ff,cscc.files.dataprefix,''); + % set original input files of the CAT preprocessing + cscc.files.org{i} = fullfile(pp1,[fname '.nii']); + if ~exist(cscc.files.org{i},'file') + cscc.files.org{i} = fullfile(pp1,... + [cat_io_strrep(ff,cscc.files.dataprefix,'') '.img']); + if ~exist(cscc.files.org{i},'file') + f1 = cat_vol_findfiles(pp1,[fname '.nii']); + if ~isempty(f1) && exist(f1{1},'file') + cscc.files.org{i} = f1{1}; + else %if ~exist(cscc.files.org{i},'file') + cscc.files.org{i} = ''; + end + end + end + + cscc.files.p0{i} = fullfile(pp,['p0' fname '.nii']); + if ~exist(cscc.files.p0{i},'file') + cscc.files.p0{i} = ''; + end + + % try to find the cscc.data.XML file if not given + if ~isfield(job,'data_xml') || isempty( char(job.data_xml) ) + cscc.files.xml{i} = fullfile(pp1,reportdir,['cat_' fname ... + cat_io_strrep(ee,{'.nii','.img','.gii'},'.xml')]); + if ~exist(cscc.files.xml{i},'file') + cscc.files.xml{i} = ''; + end + else + cscc.files.xml = cellstr(job.data_xml); + end + + % set report pdf + cscc.files.pdf{i} = fullfile(pp1,reportdir,['catreport_' fname '.pdf']); + if ~exist(cscc.files.pdf{i},'file') + cscc.files.pdf{i} = ''; + end + + % set report jpg + cscc.files.jpg{i} = fullfile(pp1,reportdir,['catreportj_' fname '.jpg']); + if ~exist(cscc.files.jpg{i},'file') + cscc.files.jpg{i} = ''; + end + + % log files + cscc.files.log{i} = fullfile(pp1,reportdir,['catlog_' fname '.txt']); + if ~exist(cscc.files.log{i},'file') + cscc.files.log{i} = ''; + end + + % surface files + cscc.files.surf{i} = fullfile(pp1,surfdir,... + ['lh.thickness.' fname ]); + if ~exist(cscc.files.surf{i},'file') + cscc.files.surf{i} = ''; + end + + % resampled surface files + if exist(fullfile(pp1,surfdir),'dir') + try + surf = cat_vol_findfiles(fullfile(pp1,surfdir),... + ['s*.thickness.resampled.' fname '.gii'],struct); + catch + surf = {}; + end + if ~isempty(surf) + cscc.files.surfr{i} = surf{1}; + else + cscc.files.surfr{i} = ''; + end + end + spm_progress_bar('Set',i); + end + spm_progress_bar('Clear'); + + if all(cellfun('isempty',cscc.files.org)) + cat_io_cprintf('warn','Failed to find the original files!\n'); + end + if all(cellfun('isempty',cscc.files.pdf)) + cat_io_cprintf('warn','Failed to find the report files!\n'); + end + if all(cellfun('isempty',cscc.files.xml)) + cat_io_cprintf('warn','Failed to find the XML files!\n'); + end + + + + %% load header + % ---------------------------------------------------------------------- + % Load data scan by scan because the surfaces V-structure already include + % the texture data that slow down loading. Moreover, this is more save if + % some org-files are missing. + spm_progress_bar('Init',numel(cscc.files.data),'Load data','subjects completed') + spm_figure('GetWin','Interactive'); + for i=1:numel(cscc.files.data) + cscc.data.V(i) = spm_data_hdr_read(cscc.files.data{i}); + cscc.data.Vo(i) = spm_data_hdr_read(cscc.files.org{i}); + spm_progress_bar('Set',i); + end + spm_progress_bar('Clear'); + + + %% load cscc.data.XML data + % ---------------------------------------------------------------------- + if all(cellfun('isempty',cscc.files.xml)) + cscc.H.isxml = 0; + cscc.data.QM_names = ''; + else + cscc.H.isxml = 1; + + if size(cscc.files.xml,1) ~= n_subjects + error('XML-files must have the same number as cscc.datagroups.sample size'); + end + + cscc.data.QM = nan(n_subjects,4 + ... + (cscc.job.expertgui) + 2*cscc.H.mesh_detected); + cscc.data.QM_names = {... + 'Noise rating (NCR)';... + 'Bias rating (ICR)';... + 'Resoution rating (RES)';... + 'Weighted overall image quality rating (IQR)';... + 'Protocol-based IQR (PIQR)'; ... + 'Euler number';... + 'Size of topology defects (TDS)'}; + cscc.data.QM_names = cscc.data.QM_names(1:min( numel(cscc.data.QM_names) , size(cscc.data.QM,2) )); % remove Euler + + spm_progress_bar('Init',n_subjects,'Load xml-files','subjects completed') + spm_figure('GetWin','Interactive'); + for i=1:n_subjects + % get basename for xml- and data files + [pth, xml_name] = fileparts(deblank(cscc.files.xml{i})); + [pth, data_name] = fileparts(cscc.data.V(i).fname); + + % remove leading 'cat_' + xml_name = xml_name(5:end); + + % check for filenames + if isempty(strfind(data_name,xml_name)) && ~isempty(xml_name) + fprintf('Please check file names because of deviating subject names:\n %s vs. %s\n',... + cscc.data.V(i).fname,cscc.files.xml{i}); + end + + xml = cat_io_xml(deblank(cscc.files.xml{i})); + if isempty(cscc.files.org{i}) + cscc.files.org{i} = xml.filedata.fname; + end + + cscc.data.catrev = xml.software.version_cat; + if isfield(xml,'qualityratings') + cscc.data.QM(i,1:4) = [xml.qualityratings.NCR xml.qualityratings.ICR ... + xml.qualityratings.res_RMS xml.qualityratings.IQR]; + RMS(i,1) = xml.qualityratings.res_RMS; + elseif isfield(xml,'QAM') % also try to use old version + cscc.data.QM(i,1:4) = [xml.QAM.cscc.data.QM.NCR xml.QAM.cscc.data.QM.ICR ... + xml.qualityratings.res_RMS xml.QAM.cscc.data.QM.res_RMS xml.QAM.cscc.data.QM.IQR]; + RMS(i,1) = xml.QAM.res_RMS; + else + RMS(i,1) = nan; + end + if cscc.job.expertgui + cscc.data.QM(i,5) = nan; + end + if cscc.H.mesh_detected && isfield(xml.subjectmeasures,'EC_abs') + cscc.data.QM(i,end-1:end) = ... + [xml.subjectmeasures.EC_abs xml.subjectmeasures.defect_size]; + end + spm_progress_bar('Set',i); + end + spm_progress_bar('Clear'); + + % detect cscc.datagroups.protocols by resolution + pacc = 2; % larger values to detect many cscc.datagroups.protocols, small values to have less + RMS(isnan(RMS)) = 11; % avoid cscc.H.multiple NaN center + [cscc.datagroups.protocols,tmp,cscc.datagroups.protocol] = ... + unique(round(RMS*10^pacc)/10^pacc); clear pid RMS + cscc.datagroups.protocols(cscc.datagroups.protocols==11) = 21; + cscc.datagroups.protocols = cscc.datagroups.protocols/2; % average mm rather than rating + + % remove last two columns if EC_abs and defect_size are not defined + if cscc.H.mesh_detected && all(all(isnan(cscc.data.QM(:,end-1:end)))) + cscc.data.QM = cscc.data.QM(:,end-1:end); + end + + % added cscc.datagroups.protocol depending QA parameter + + [Pth,rth,sq,rths,rthsc,sqs] = cat_tst_qa_cleaner_intern(... + cscc.data.QM(:,4),struct('site',{cscc.datagroups.protocol},'figure',0)); + cscc.data.QM_names = [cscc.data.QM_names;{'Protocol IQR difference (PIQR)'}]; + cscc.data.QM(:,5) = rth(:,1) - cscc.data.QM(:,4); + + % convert marks into rps rating + mark2rps = @(mark) min(100,max(0,105 - mark*10)) + isnan(mark).*mark; + markd2rpsd = @(mark) ( mark*10) + isnan(mark).*mark; + cscc.data.QM(:,1:4) = mark2rps(cscc.data.QM(:,1:4)); + if cat_get_defaults('exptops.expertgui')>1 + cscc.data.QM(:,5) = markd2rpsd(cscc.data.QM(:,5)); + end + end + + + + %% add constant to nuisance parameter + % ---------------------------------------------------------------------- + G = []; + if ~isempty(job.c) + for i=1:numel(job.c) + G = [G job.c{i}]; + end + if size(G,1) ~= n_subjects + G = G'; + end + G = [ones(n_subjects,1) G]; + end + + + + %% load surface data, prepare volume data loading + % ---------------------------------------------------------------------- + if cscc.H.mesh_detected + % load surface texture data + Y = spm_data_read(cscc.data.V)'; + cscc.data.data_array_org = Y'; + + % optional global scaling + if isfield(job,'gSF') + for i=1:numel(cscc.data.V) + Y(:,2) = Y(:,2)*job.gSF(i); + end + end + + Y(isnan(Y)) = 0; + + % rescue unscaled data min/max + cscc.data.cdata(1) = min(Y(:)); + cscc.data.cdata(2) = max(Y(:)); + Y = Y - repmat(mean(Y,2), [1 size(Y,2)]); + + % remove nuisance and add mean again (otherwise correlations are quite small and misleading) + if ~isempty(G) + [indinf,tmp] = find(isinf(G) | isnan(G)); + if ~isempty(indinf) + fprintf('Nuisance parameter for %s is Inf or NaN.\n',V(indinf).fname); + return + end + Ymean = repmat(mean(Y), [n_subjects 1]); + Y = Y - G*(pinv(G)*Y) + Ymean; + end + + cscc.data.data_array = Y'; + cscc.data.YpY = (Y*Y')/n_subjects; + + % calculate residual mean square of mean adjusted Y + Y = Y - repmat(mean(Y,1), [n_subjects 1]); + cscc.data.data_array_diff = Y'; + + %MSE = sum(Y.*Y,2); + else + if length(cscc.data.V)>1 && any(any(diff(cat(1,cscc.data.V.dim),1,1),1)) + error('images don''t all have same dimensions') + end + if max(max(max(abs(diff(cat(3,cscc.data.V.mat),1,3))))) > 1e-8 + error('images don''t all have same orientation & voxel size') + end + + % consider image aspect ratio + cscc.pos.slice(4) = cscc.pos.slice(4) * cscc.data.V(1).dim(2) / cscc.data.V(1).dim(1); + + slices = 1:job.gap:cscc.data.V(1).dim(3); + + dimx = length(1:job.gap:cscc.data.V(1).dim(1)); + dimy = length(1:job.gap:cscc.data.V(1).dim(2)); + Y = zeros(n_subjects, prod(dimx*dimy)); + cscc.data.YpY = zeros(n_subjects); + %MSE = zeros(n_subjects,1); + cscc.data.data_array = zeros([cscc.data.V(1).dim(1:2) n_subjects]); + + + + %-Start progress plot + %----------------------------------------------------------------------- + spm_progress_bar('Init',cscc.data.V(1).dim(3),'Check correlation','planes completed') + spm_figure('GetWin','Interactive'); + + for j=slices + + M = spm_matrix([0 0 j 0 0 0 job.gap job.gap job.gap]); + + for i = 1:n_subjects + cscc.data.img = spm_slice_vol(cscc.data.V(i),M,[dimx dimy],[1 0]); + cscc.data.img(isnan(cscc.data.img)) = 0; + Y(i,:) = cscc.data.img(:); + if isfield(job,'gSF') + Y(i,:) = Y(i,:)*job.gSF(i); + end + end + + % make sure data is zero mean + Y = Y - repmat(mean(Y,2), [1 prod(dimx*dimy)]); + + % remove nuisance and add mean again + % (otherwise correlations are quite small and misleading) + if ~isempty(G) + Ymean = repmat(mean(Y), [n_subjects 1]); + Y = Y - G*(pinv(G)*Y) + Ymean; + end + + cscc.data.YpY = cscc.data.YpY + (Y*Y')/n_subjects; + + % calculate residual mean square of mean adjusted Y + Y = Y - repmat(mean(Y,1), [n_subjects 1]); + + %MSE = MSE + sum(Y.*Y,2); + + spm_progress_bar('Set',j); + + end + + % correct filenames for 4D data + if strcmp(cscc.data.V(1).fname, cscc.data.V(2).fname) + cscc.data.Vchanged_names = 1; + cscc.data.Vchanged = cscc.data.V; + for i=1:n_subjects + [pth,nam,ext] = spm_fileparts(cscc.data.V(i).fname); + cscc.data.V(i).fname = fullfile(pth, [nam sprintf('%04d',i) ext]); + end + else + cscc.data.Vchanged_names = 0; + end + + spm_progress_bar('Clear'); + end + clear Y + + + + %% normalize cscc.data.YpY and estimate cscc.data.mean_cov + % ---------------------------------------------------------------------- + d = sqrt(diag(cscc.data.YpY)); % sqrt first to avoid under/overflow + dd = d*d'; + cscc.data.YpY = cscc.data.YpY./(dd+eps); + t = find(abs(cscc.data.YpY) > 1); + cscc.data.YpY(t) = cscc.data.YpY(t)./abs(cscc.data.YpY(t)); + cscc.data.YpY(1:n_subjects+1:end) = sign(diag(cscc.data.YpY)); + clear t d dd; + + % extract mean correlation for each data set + cscc.data.mean_cov = zeros(n_subjects,1); + for i=1:n_subjects + cov0 = cscc.data.YpY(i,:); % extract row for each subject + cov0(i) = []; % remove cov with its own + cscc.data.mean_cov(i) = mean(cov0); + end + clear cov0; + + + + %% output compressed filenames structure + % ---------------------------------------------------------------------- + fprintf('\n'); + fname_m = []; + fname_tmp = cell(cscc.datagroups.n_samples,1); + fname_s = cell(cscc.datagroups.n_samples,1); + fname_e = cell(cscc.datagroups.n_samples,1); + for i=1:cscc.datagroups.n_samples + [tmp, fname_tmp{i}] = ... + spm_str_manip(char(cscc.data.V(cscc.datagroups.sample == i).fname),'C'); + fname_m = [fname_m; fname_tmp{i}.m]; + fname_s{i} = fname_tmp{i}.s; + cat_io_cprintf('n','Compressed filenames sample %d: ',i); + cat_io_cprintf('b',sprintf('%s %s \n',spm_str_manip(tmp,'f120'),... + repmat('.',1,3*(numel(tmp)>120)))); + end + cscc.files.fname = struct('s',{fname_s},'e',{fname_e},'m',{fname_m}); + clear fname_e fname_m fname_s fname_tmp tmp + + + + %% print suspecious files with high cov + % use slightly higher threshold for (smoothed) mesh data + % ------------------------------------------------------------------------ + cscc.data.YpY_tmp = cscc.data.YpY - tril(cscc.data.YpY); + if cscc.H.mesh_detected + [indx, indy] = find(cscc.data.YpY_tmp>0.950 & cscc.data.YpY_tmp < (1-eps)); + else + [indx, indy] = find(cscc.data.YpY_tmp>0.925); + end + [siv,si] = sort(cscc.data.YpY(sub2ind(size(cscc.data.YpY),indx,indy)),'descend'); + % if more than 25% of the data this points to longitudinal data of one + % subject and no warning will appear + cscc.data.islongitudinal = (length(indx) > 0.25*n_subjects); + if ~isempty(indx) + if ~cscc.data.islongitudinal + fprintf('\nUnusual large correlation (check that subjects are not identical):\n'); + for i=si' + % exclude diagonal + if indx(i) ~= indy(i) + cat_io_cprintf('w',sprintf(' %0.4f',cscc.data.YpY(indx(i),indy(i)))); + cat_io_cprintf('n',' between '); + cat_io_cprintf('b',cscc.files.fname.m{indx(i)}); cat_io_cprintf('n',' and '); + cat_io_cprintf('b',cscc.files.fname.m{indy(i)}); fprintf('\n'); + end + end + else + fprintf('\nMany unusual large correlations were found (e.g. common in longitudinal data).\n'); + end + end + + [indx, indy] = find(cscc.data.YpY_tmp == 1); + % give warning that data are identical + if ~isempty(indx) + fprintf('\nWARNING: Data of these subjects are identical!\n'); + for i=1:length(indx) + if cscc.datagroups.n_samples > 1 + fprintf('%s (sample %d) and %s (sample %d)\n',filename.m{indx(i)},sample(indx(i)),filename.m{indy(i)},sample(indy(i))); + cat_io_cprintf('w',sprintf(' %0.4f',cscc.data.YpY(indx(i),indy(i)))); + cat_io_cprintf('n',' between '); + cat_io_cprintf('b',sprintf('%s (sample %d)',cscc.files.fname.m{indx(i)},cscc.datagroups.sample(indx(i)))); cat_io_cprintf('n',' and '); + cat_io_cprintf('b',sprintf('%s (sample %d)',cscc.files.fname.m{indy(i)},cscc.datagroups.sample(indy(i)))); fprintf('\n'); + else + cat_io_cprintf('w',sprintf(' %0.4f',cscc.data.YpY(indx(i),indy(i)))); + cat_io_cprintf('n',' between '); + cat_io_cprintf('b',cscc.files.fname.m{indx(i)}); cat_io_cprintf('n',' and '); + cat_io_cprintf('b',cscc.files.fname.m{indy(i)}); fprintf('\n'); + end + end + end + + + + %% sort data and estimate critical files + % ------------------------------------------------------------------------ + [cscc.data.mean_cov_cscc.H.sorted, cscc.data.ind_sorted] = sort(cscc.data.mean_cov,'descend'); + threshold_cov = mean(cscc.data.mean_cov) - 2*std(cscc.data.mean_cov); + n_thresholded = find(cscc.data.mean_cov_cscc.H.sorted < threshold_cov,1,'first'); + if ~isempty(n_thresholded) + fprintf('\nThese data have a mean correlation below 2 standard deviations. \n'); + fprintf('This does not necessarily mean that you have to exclude these data. \n'); + fprintf('However, these data have to be carefully checked:\n'); + for i=n_thresholded:n_subjects + cat_io_cprintf('r',sprintf(' %0.4f ',cscc.data.mean_cov_cscc.H.sorted(i))); + cat_io_cprintf('b',cscc.data.V(cscc.data.ind_sorted(i)).fname); fprintf('\n'); + end + end + + + + %% output structure + % ------------------------------------------------------------------------ + if nargout>0 + varargout{1} = struct(... + 'table',[cscc.files.out,num2cell(cscc.data.mean_cov)],... + 'covmat',cscc.data.YpY,... + 'sorttable',[cellstr(cscc.data.V(cscc.data.ind_sorted).fname),... + num2cell(cscc.data.mean_cov_cscc.H.sorted)],... + 'sortcovmat',cscc.data.YpY(cscc.data.ind_sorted,cscc.data.ind_sorted), ... + 'cov',cscc.data.mean_cov,... + 'threshold_cov',threshold_cov); + end + clear cscc.data.mean_cov_cscc.H.sorted threshold_cov; + + + + % check for replicates + for i=1:n_subjects + for j=1:n_subjects + if (i>j) && (cscc.data.mean_cov(i) == cscc.data.mean_cov(j)) + try + nami = deblank(cscc.data.V(i).fname); + namj = deblank(cscc.data.V(j).fname); + if strcmp(nami(end-1:end),',1') + nami = nami(1:end-2); + end + if strcmp(namj(end-1:end),',1') + namj = namj(1:end-2); + end + s = unix(['diff ' nami ' ' namj]); + if (s==0), fprintf(['\nWarning: ' nami ' and ' namj ' are same files?\n']); end + end + end + end + end + + %% create figure + % ---------------------------------------------------------------------- + if cscc.H.mesh_detected + create_figures(job) + else + create_figures(job,slices) + end + show_boxplot; + + +return +%-End +%-------------------------------------------------------------------------- +function create_figures(job,slices) +% ------------------------------------------------------------------------- +% Create the main GUI figures of cat_stat_check_cov2. +% ------------------------------------------------------------------------- + + global cscc + + + cscc.H.graphics = spm_figure('FindWin','Graphics'); + cscc.H.figure = figure(2); + set(cscc.H.figure,'MenuBar','none','Position',cscc.pos.fig,... + 'NumberTitle','off','Resize','off','Visible','on',... + 'HitTest','off','Interruptible','off',... + 'color',cscc.display.figcolor,'CloseRequestFcn',@closeWindows); %,'cat_stat_check_cov2(''closeWindows'')'); + + + % move SPM Graphics figure to have no overlap + fcscc.pos = get(cscc.H.figure,'Position'); + cscc.display.WP = get(cscc.H.graphics,'Position'); + set(cscc.H.graphics,'Position',[sum(fcscc.pos(1:2:3)) + 20 cscc.display.WP(2:4)]); + clear fcscc.pos cscc.display.WP; + + if cscc.H.mesh_detected + set(cscc.H.figure,'Name','CAT Check Covariance: Click in image to display surfaces'); + else + set(cscc.H.figure,'Name','CAT Check Covariance: Click in image to display slices'); + end + + + % cursormode and update function + cscc.H.dcm = datacursormode(cscc.H.figure); + set(cscc.H.dcm,'UpdateFcn',@myupdatefcn,'SnapToDataVertex','on','Enable','on'); + + + % create two-area colormap + colormap([jet(64); gray(64)]); + + + % add colorbar without ticks and colorbar image + cscc.H.cbar = axes('Position',cscc.pos.cbar,'Parent',... + cscc.H.figure,'Visible','off'); + image(cscc.H.cbar,1:64); set(get(cscc.H.cbar,'children'),... + 'HitTest','off','Interruptible','off'); + set(cscc.H.cbar,'Ytick','','YTickLabel',''); + + + % set correlation matrix image as image + cscc.H.corr = axes('Position',cscc.pos.corr,'Parent',cscc.H.figure,... + 'Color',cscc.display.figcolor,'Ytick','','YTickLabel','',... + 'XTickLabel','','XTick','','XTickLabel',''); + image(cscc.H.corr,64 * tril(cscc.data.YpY)); axis image; + + + % scatter plot + if cscc.H.isxml + cscc.H.scat(1) = axes('Position',cscc.pos.corr,'Parent',cscc.H.figure, ... + 'visible','off','Box','on','Color',[0.85 0.85 0.85]); + + if cscc.job.expertgui + cscc.H.scat(2) = axes('Position',cscc.pos.corr,'Parent',cscc.H.figure, ... + 'visible','off','Box','on','Color',[0.85 0.85 0.85]); + end + end + + + % slice axis + cscc.H.slice = axes('Position',cscc.pos.slice,'Parent',cscc.H.figure, ... + 'visible','off','Box','off','Color',cscc.display.figcolor,... + 'Ytick','','YTickLabel','','XTickLabel','',... + 'XTick','','XTickLabel',''); + if ~cscc.H.mesh_detected, axis off; end + + + % add button for closing all windows + cscc.H.close = uicontrol(cscc.H.figure,... + 'Units','normalized','position',cscc.pos.close,'Style','Pushbutton',... + 'callback',@closeWindows,'string','Close','ToolTipString','Close windows',... + 'FontSize',cscc.display.FS(cscc.display.FSi),'ForegroundColor',[0.8 0 0],... + 'Visible','off'); + + + % check worst scans >> maybe on the SPM graphics figure?! + % this would allow to show the worst data specific for the boxplot data! + cscc.H.worst = uicontrol(cscc.H.figure,... + 'Units','normalized','position',cscc.pos.close,'Style','Pushbutton',... + 'HorizontalAlignment','center','callback',@check_worst_data,... + 'string','Check worst','ToolTipString','Display most deviating files (MNC)',... + 'FontSize',cscc.display.FS(cscc.display.FSi),'ForegroundColor',[0.8 0 0]); + + + % add button to open the HTML help + cscc.H.help = uicontrol(cscc.H.figure,... + 'Units','normalized','position',cscc.pos.help,'Style','Pushbutton',... + 'string','Help','ToolTipString','Open help window',... + 'ForegroundColor',[0 0 0.8],'FontSize',cscc.display.FS(cscc.display.FSi),... + 'callback',['global cscc; spm_help(''!Disp'',fullfile(spm(''Dir''),''toolbox'... + ',''cat12'',''html'',''cat_tools_checkcov.html'','''',cscc.H.graphics);']); + + + + + + %% create popoup menu for SPM grafix window + + % MNC + str = { 'Boxplot','Mean correlation'}; + tmp = { {@show_boxplot, cscc.data.mean_cov, 'Mean correlation (MNC) ', 1} }; + + if cscc.H.isxml + + % manual control of output + showEQM = cscc.job.expertgui; % other QM (noise,bias,res) + showPIQR = cscc.job.expertgui; % PIQR and IQRratio2 plot + + % add QM header and IQR + if showEQM || ( size(cscc.data.QM,2)>6 && cscc.H.mesh_detected ) + str = [str,{'Quality measures:'}]; + tmp = [ tmp , { { @show_boxplot, cscc.data.QM(:,4), cscc.data.QM_names{4}, 1 } } ]; + + % IQR + str = [ str , { ' Overall image quality rating (IQR)' } ]; + tmp = [ tmp , { { @show_boxplot, cscc.data.QM(:,4), cscc.data.QM_names{4}, 1 } } ]; + else + % only IQR + str = [ str , { 'Overall image quality rating' } ]; + tmp = [ tmp , { { @show_boxplot, cscc.data.QM(:,4), cscc.data.QM_names(4,:), 1 } } ]; + end + + % add other QM + % PIQR + if showPIQR + str = [ str , { ' Protocol-based image quality rating (PIQR)' } ]; + tmp = [ tmp , { { @show_boxplot, cscc.data.QM(:,5), cscc.data.QM_names{5}, 1 } } ]; + end + % NCR, ICR, RES + if showEQM + for qmi = 1:3 + str = [ str , { [' ' cscc.data.QM_names{qmi}] } ]; + tmp = [ tmp , { {@show_boxplot, cscc.data.QM(:,qmi), cscc.data.QM_names{qmi}, 1} }]; + end + end + % surfaces QM measures + if size(cscc.data.QM,2)>6 && cscc.H.mesh_detected + for qmi = 6:7 + str = [ str , { [' ' cscc.data.QM_names{qmi}] } ]; + tmp = [ tmp , { {@show_boxplot, cscc.data.QM(:,qmi), cscc.data.QM_names{qmi}, 2} }]; + end + end + + + % estimate ratio between weighted overall quality (IQR) and mean corr. + cscc.data.X = [cscc.data.mean_cov, cscc.data.QM(:,4)]; + cscc.data.X(isnan(cscc.data.X)) = 0; + cscc.data.IQRratio = (cscc.data.X(:,2)/std(cscc.data.X(:,2)))./(cscc.data.X(:,1)/std(cscc.data.X(:,1))); + + % if PIQR is used than we need further variables (similar to IQR) + if showPIQR + cscc.data.X2 = [cscc.data.mean_cov, cscc.data.QM(:,5)]; + cscc.data.X2(isnan(cscc.data.X2)) = 0; + cscc.data.IQRratio2 = (cscc.data.X2(:,2)/std(cscc.data.X2(:,2)))./(cscc.data.X2(:,1)/std(cscc.data.X2(:,1))); + end + + % add PIQR + if showPIQR + str = [str,{'Norm. Ratio IQR/mean correlation:'}]; %tmp = [ tmp , {{@sprintf,''}}]; + tmp = [ tmp , { {@show_boxplot, cscc.data.IQRratio , 'Norm. Ratio IQR/mean correlation ', 2 } } ]; + str = [ str , { ' with IQR' } ]; + tmp = [ tmp , { {@show_boxplot, cscc.data.IQRratio , 'Norm. Ratio IQR/mean correlation ', 2 } } ]; + str = [ str , { ' with PIQR' } ]; + tmp = [ tmp , { {@show_boxplot, cscc.data.IQRratio2, 'Norm. Ratio PIQR/mean correlation ', 2 } } ]; + else + str = [ str , { 'Norm. Ratio IQR/mean correlation' } ]; + tmp = [ tmp , { {@show_boxplot, cscc.data.IQRratio, 'Norm. Ratio IQR/mean correlation ', 2 } } ]; + end + + end + + + % add nuisance variable(s) + % maybe as separate button? + if isfield(job,'c') & ~isempty(job.c); + if numel(job.c)>1 + str = [str,{'Nuisance variables:'}]; %tmp = [ tmp , {{@sprintf,''}}]; + else + str = [str,{'Nuisance variable'}]; + end + tmp = [ tmp , {{@show_boxplot, job.c{1} ,sprintf('Nuisance variable %d ',1), 0}}]; + if numel(job.c)>1 + for ci = 1:numel(1) + str = [str,{sprintf(' Variable %d',ci)}]; + tmp = [ tmp , {{@show_boxplot, job.c{ci} ,sprintf('Nuisance variable %d ',ci), 0}}]; + end + end + end + + + % final create + cscc.H.boxp = uicontrol(cscc.H.figure,... + 'Units','normalized','position',cscc.pos.boxp,'Style','PopUp',... + 'callback','spm(''PopUpCB'',gcbo)','string',str,'UserData',tmp,... + 'ToolTipString','Display boxplot','FontSize',cscc.display.FS(cscc.display.FSi)); + + + + + + + %% create popoup menu for main check_cov window + if cscc.H.isxml + str = { 'Plot',... + 'Corr. matrix order by selected files', ... + 'Corr. matrix sorted by mean corr.', ... + 'Norm. Ratio IQR/mean correlation'}; + tmp = { {@show_matrix, cscc.data.YpY, 0},... + {@show_matrix, cscc.data.YpY(cscc.data.ind_sorted,cscc.data.ind_sorted), 1},... + {@show_IQRratio, cscc.data.X, cscc.data.IQRratio, 1}}; + if showPIQR + str{4} = [ str{4} ' (IQR)']; + str = char([cellstr(str),{'Norm. Ratio PIQR/mean correlation'}]); + tmp = [ tmp , ... + {{@show_IQRratio, cscc.data.X2, cscc.data.IQRratio2, 2}}]; + end + else + str = { 'Plot',... + 'Order by data selection',... + 'Sorted by mean correlation'}; + tmp = { {@show_matrix, cscc.data.YpY, 0},... + {@show_matrix, cscc.data.YpY(cscc.data.ind_sorted,cscc.data.ind_sorted), 1} }; + end + + cscc.H.sort = uicontrol(cscc.H.figure,... + 'Units','normalized','position',cscc.pos.sort,'Style','PopUp',... + 'UserData',tmp,'callback','spm(''PopUpCB'',gcbo)','string',str,... + 'ToolTipString','Sort matrix','FontSize',cscc.display.FS(cscc.display.FSi)); + + onoff = {'on','off'}; + + + + + %% == navigation unit == + cscc.H.selectuitext = uicontrol(cscc.H.figure,... + 'Units','normalized','Style','text','BackgroundColor',cscc.display.figcolor,... + 'Position',[cscc.pos.samp(1) cscc.pos.samp(2)+0.055 0.2 0.02],... + 'String','Data selection','FontSize',cscc.display.FS(cscc.display.FSi)); + + % choose only one cscc.datagroups.sample for display + str = { 'Sample',sprintf('full (%d)',numel(cscc.datagroups.sample))}; + tmp = { {@show_sample, 0, 1} }; + for i=1:cscc.datagroups.n_samples, + str = [str,sprintf('S%d (%d)',i,sum(cscc.datagroups.sample==i))]; + tmp = [ tmp , {{@show_sample, i, 1}} ]; + end + cscc.H.samp = uicontrol(cscc.H.figure,... + 'Units','normalized','position',cscc.pos.samp,'Style','PopUp',... + 'UserData',tmp,'enable',onoff{1 + (cscc.datagroups.n_samples==1)},... + 'callback','spm(''PopUpCB'',gcbo)','string',str,... + 'ToolTipString','Select sample to display','FontSize',cscc.display.FS(cscc.display.FSi)); + + % choose center + if ~isfield(cscc.datagroups,'protocols') + cscc.datagroups.protocols = 1:max(cscc.datagroups.protocol); % only protocol ids + end + str = { 'Protocol',sprintf('all (%d)',numel(cscc.datagroups.protocol))}; + tmp = { {@show_protocol, 0} }; + for i=1:numel(cscc.datagroups.protocols), + %str = [str,sprintf('P%03d',cscc.datagroups.protocols(i))]; % only protocol ids + str = [str,sprintf('%5.2f (%d)',cscc.datagroups.protocols(i),... + sum(cscc.datagroups.protocol==i))]; + tmp = [ tmp , {{@show_protocol, i}} ]; + end + cscc.H.prot = uicontrol(cscc.H.figure,... + 'Units','normalized','position',cscc.pos.prot,'Style','PopUp',... + 'UserData',tmp,'enable',onoff{ min( 2 , 1 + (numel(cscc.datagroups.protocols)==1) + ... + 1 - cscc.job.expertgui ) },... + 'callback','spm(''PopUpCB'',gcbo)','string',str,... + 'ToolTipString','Select protocol by its RMS resolution','FontSize',cscc.display.FS(cscc.display.FSi)); + + + %% + cscc.H.alphabox = uicontrol(cscc.H.figure,... + 'Units','normalized','position',cscc.pos.alphabox,'Style','CheckBox',... + 'callback',@update_alpha,... + 'string','Colorize diff. to sample mean','Value',1,... + 'ToolTipString','Colorize difference to sample mean (pos=green;neg=red)',... + 'Visible','off','BackgroundColor',cscc.display.figcolor,... + 'FontSize',cscc.display.FS(cscc.display.FSi)); + + %{ + cscc.H.cbarfix = uicontrol(cscc.H.figure,... + 'Units','normalized','Style','CheckBox','position',cscc.pos.cbarfix,... + 'callback',{@checkbox_cbarfix},... + 'string','Fixed range','ToolTipString','Switch between fixed and auto-scaled colorbar',... + 'Value',0,'BackgroundColor',cscc.display.figcolor,... + 'FontSize',cscc.display.FS(cscc.display.FSi)); + %} + + cscc.H.showtrash = uicontrol(cscc.H.figure,... + 'Units','normalized','Style','CheckBox','position',cscc.pos.showtrash,... + 'callback',{@checkbox_showtrash},'enable','off',... + 'string','Show excluded','ToolTipString','Show excluded records',... + 'Value',0,'BackgroundColor',cscc.display.figcolor,'FontSize',... + cscc.display.FS(cscc.display.FSi)); + + + + + %% add slider only for volume data + if ~cscc.H.mesh_detected + % voxelsize and origin + vx = sqrt(sum(cscc.data.V(1).mat(1:3,1:3).^2)); + Orig = cscc.data.V(1).mat\[0 0 0 1]'; + + cscc.H.mm = uicontrol(cscc.H.figure,... + 'Units','normalized','position',cscc.pos.sslider,... + ...'Min',(1 - Orig(3))*vx(3) ,'Max',(cscc.data.V(1).dim(3) - Orig(3))*vx(3),... + 'Min', -sum(slicesOrig(3)) * job.gap * vx(3),... + 'Style','slider','HorizontalAlignment','center',... + 'callback',@update_slices_array,... + 'ToolTipString','Select slice for display',... + 'SliderStep',[1 job.gap] / (cscc.data.V(1).dim(3)-1),'Visible','off'); + + cscc.H.mm_txt = uicontrol(cscc.H.figure,... + 'Units','normalized','HorizontalAlignment','center',... + 'Style','text','BackgroundColor',cscc.display.figcolor,... + 'Position',[cscc.pos.sslider(1) cscc.pos.sslider(2)-0.005 0.2 0.02],... + 'String','0 mm','Visible','off','FontSize',cscc.display.FS(cscc.display.FSi)); + + update_slices_array; + end + + + + + %% == navigation unit == + cscc.H.naviuitext = uicontrol(cscc.H.figure,... + 'Units','normalized','Style','text','BackgroundColor',cscc.display.figcolor,... + 'Position',[cscc.pos.scSelect(1) cscc.pos.scSelect(2)+0.035 0.2 0.02],... + 'String','Navigation options','FontSize',cscc.display.FS(cscc.display.FSi)); + + cscc.H.naviui.select = uicontrol(cscc.H.figure,... + 'Units','normalized','position',cscc.pos.scSelect,'callback','datacursormode(''on'')',... + 'Style','Pushbutton','enable','on','ToolTipString','Data selection'); + + cscc.H.naviui.zoomReset = uicontrol(cscc.H.figure,... + 'Units','normalized','position',cscc.pos.scZoomReset,... + 'callback','zoom out; datacursormode(''on'')',... + 'Style','Pushbutton','enable','on','ToolTipString','Reset zoom'); + + cscc.H.naviui.zoomIn = uicontrol(cscc.H.figure,... + 'Units','normalized','position',cscc.pos.scZoomIn,'callback',... + ['global cscc; ' ... + 'if cscc.H.isscatter, ' ... + ' hz = zoom(cscc.H.scat(cscc.H.scata)); ' ... + ' else ' ... + ' hz = zoom(cscc.H.corr);' ... + ' end;' ... + 'set(hz,''enable'',''on'',''direction'',''in'')'], ... + 'Style','Pushbutton','enable','on','ToolTipString','Zoom in'); + + cscc.H.naviui.zoomOut = uicontrol(cscc.H.figure,... + 'Units','normalized','position',cscc.pos.scZoomOut,'callback',... + ['global cscc; ' ... + 'if cscc.H.isscatter, ' ... + ' hz = zoom(cscc.H.scat(cscc.H.scata)); ' ... + ' else ' ... + ' hz = zoom(cscc.H.corr);' ... + ' end;' ... + 'set(hz,''enable'',''on'',''direction'',''out'')'], ... + 'Style','Pushbutton','enable','on','ToolTipString','Zoom out'); + + cscc.H.naviui.pan = uicontrol(cscc.H.figure,... + 'Units','normalized','position',cscc.pos.scPan,'Enable','off','callback','pan on',... + 'Style','Pushbutton','enable','on','ToolTipString','Hand'); + + + + + %% == check unit == + cscc.H.checkuitext = uicontrol(cscc.H.figure,... + 'Units','normalized','HorizontalAlignment','center','Style','text',... + 'BackgroundColor',cscc.display.figcolor,... + 'Position',[cscc.pos.checkvol(1) cscc.pos.checkvol(2)+0.035 0.2 0.02],... + 'String','View selected data','FontSize',cscc.display.FS(cscc.display.FSi)); + + % add button to open one image with SPM check_reg + cscc.H.checkui.vol = uicontrol(cscc.H.figure,... + 'Units','normalized','position',cscc.pos.checkvol,'callback',@checkvol,... + 'string','VOL','ToolTipString','Display original volume(s) in SPM graphics window',... + 'Style','Pushbutton','FontSize',cscc.display.FS(cscc.display.FSi),'Enable','off'); + + % add button to open one image with SPM check_reg + cscc.H.checkui.surf = uicontrol(cscc.H.figure,... + 'Units','normalized','position',cscc.pos.checksurf,'callback',@checksurf,... + 'string','SURF','ToolTipString','Display surface(s) in own figures',... + 'Style','Pushbutton','FontSize',cscc.display.FS(cscc.display.FSi),'Enable','off'); + + % add button to open one image with SPM check_reg + cscc.H.checkui.log = uicontrol(cscc.H.figure,... + 'Units','normalized','position',cscc.pos.checklog,'callback',@checklog,... + 'string','LOG','ToolTipString','Display log-file in SPM Graphics',... + 'Style','Pushbutton','FontSize',cscc.display.FS(cscc.display.FSi),'Enable','off'); + + % add button to open one image with SPM check_reg + cscc.H.checkui.xml = uicontrol(cscc.H.figure,... + 'Units','normalized','position',cscc.pos.checkxml,'callback',@checkxml,... + 'string','XML','FontSize',cscc.display.FS(cscc.display.FSi),... + 'ToolTipString','Display xml-file in SPM Graphics',... + 'Style','Pushbutton','Enable','off'); + + % add button to open the pdf in an external viewer + cscc.H.checkui.pdf = uicontrol(cscc.H.figure,... + 'Units','normalized','position',cscc.pos.checkpdf,'callback',@checkpdf,... + 'ToolTipString','Display PDF report in external viewer',... + 'Style','Pushbutton','Enable','off'); + + + + + %% == trashlist unit == + cscc.H.trashuitext = uicontrol(cscc.H.figure,... + 'Units','normalized','Style','text',... + 'Position',[cscc.pos.newtrash(1) cscc.pos.newtrash(2)+0.035 0.2 0.02],... + 'BackgroundColor',cscc.display.figcolor,'String','Exclusion operations',... + 'FontSize',cscc.display.FS(cscc.display.FSi)); + + % add button for new garbage mask + cscc.H.trashui.new = uicontrol(cscc.H.figure,... + 'Units','normalized','position',cscc.pos.newtrash,'callback',@newtrash,... + 'string','NEW','ForegroundColor',[ 0 0 0.8],'FontSize',cscc.display.FS(cscc.display.FSi),... + 'ToolTipString','Reset exclusion list','Style','Pushbutton','Enable','off'); + + % add button to set the active image as garbage + cscc.H.trashui.trash = uicontrol(cscc.H.figure,... + 'Units','normalized','position',cscc.pos.trash,'callback',@trash,... + 'string','TIP+','ForegroundColor',[0.8 0 0],'FontSize',cscc.display.FS(cscc.display.FSi),... + 'ToolTipString','Exclude record','Style','Pushbutton','Enable','off'); + + cscc.H.trashui.trashcol = uicontrol(cscc.H.figure,... + 'Units','normalized','position',cscc.pos.trash,'callback',@trash,... + 'string','COL-','ForegroundColor',[0.8 0 0],'FontSize',cscc.display.FS(cscc.display.FSi),... + 'ToolTipString','Exclude column','Style','Pushbutton','Enable','off'); + + % add button to remove the active image from garbage + cscc.H.trashui.detrash = uicontrol(cscc.H.figure,... + 'Units','normalized','position',cscc.pos.detrash,'callback',@detrash,... + 'string','TIP-','ForegroundColor',[0 0.8 0],'FontSize',cscc.display.FS(cscc.display.FSi),... + 'ToolTipString','Include record','Style','Pushbutton','Enable','off'); + + cscc.H.trashui.detrashcol = uicontrol(cscc.H.figure,... + 'Units','normalized','position',cscc.pos.detrash,'callback',@detrash,... + 'string','COL+','ForegroundColor',[0 0.8 0],'FontSize',cscc.display.FS(cscc.display.FSi),... + 'ToolTipString','Include column','Style','Pushbutton','Enable','off'); + + % add button for mask below threshold as garbage + cscc.H.trashui.disptrash = uicontrol(cscc.H.figure,... + 'Units','normalized','position',cscc.pos.disptrash,'callback',@disptrash,... + 'FontSize',cscc.display.FS(cscc.display.FSi),... + 'ToolTipString','Print exclusion list in command window',... + 'string','VIEW','Style','Pushbutton','Enable','off'); + + if isfield(cscc.data,'QM') + cscc.H.trashui.autotrash = uicontrol(cscc.H.figure,... + 'Units','normalized','position',cscc.pos.autotrash,'callback',@autotrash,... + 'string','AUTO','FontSize',cscc.display.FS(cscc.display.FSi),... + 'ToolTipString','Automatic exclusion','ForegroundColor',[0 0.8 0],... + 'Style','Pushbutton','Enable',onoff{(size(cscc.data.QM,2)<4) + 1}); + end + + % == second row == + cscc.H.trashui.undo = uicontrol(cscc.H.figure,... + 'Units','normalized','position',cscc.pos.undo,'callback',@trashundo,... + 'Style','Pushbutton','Enable','off','ToolTipString','Undo last exclusion operation'); + + cscc.H.trashui.redo = uicontrol(cscc.H.figure,... + 'Units','normalized','position',cscc.pos.redo,'callback',@trashredo,... + 'Style','Pushbutton','Enable','off','ToolTipString','Redo last exclusion operation'); + + cscc.H.trashui.trashrow = uicontrol(cscc.H.figure,... + 'Units','normalized','position',cscc.pos.trashrow,'callback',@trashrow,... + 'string','ROW-','ForegroundColor',[0.8 0 0],'FontSize',cscc.display.FS(cscc.display.FSi),... + 'ToolTipString','Exclude row','Style','Pushbutton','Enable','off'); + + cscc.H.trashui.detrashrow = uicontrol(cscc.H.figure,... + 'Units','normalized','position',cscc.pos.detrashrow,'callback',@detrashrow,... + 'string','ROW+','ForegroundColor',[0 0.8 0],'FontSize',cscc.display.FS(cscc.display.FSi),... + 'ToolTipString','Include row','Style','Pushbutton','Enable','off'); + + cscc.H.trashui.ziptrash = uicontrol(cscc.H.figure,... + 'Units','normalized','position',cscc.pos.ziptrash,'callback',@ziptrash,... + 'string','DEL','ForegroundColor',[0.8 0 0],'FontWeight','bold',... + 'FontSize',cscc.display.FS(cscc.display.FSi),... + 'ToolTipString','Move excluded records to exclusion directory',... + 'Style','Pushbutton','Enable','off'); + + + + + %% print real data + show_matrix(cscc.data.YpY, cscc.H.sorted); + + set(cscc.H.figure,'Visible','on'); + try % catch main figure closing + buttonupdate + + % redraw buttons + pause(0.2) % Wait for the figure construction complete. + warning off; %#ok + jFig = get(cscc.H.figure, 'JavaFrame'); % get JavaFrame. You might see some warnings. + warning on; %#ok + jWindow = jFig.fHG2Client.getWindow; % before 2011a it could be `jFig.fFigureClient.getWindow`. + jbh = handle(jWindow,'CallbackProperties'); % Prevent memory leak + set(jbh,'ComponentMovedCallback',{@(~,~)(buttonupdate)}); + + % show plot + show_boxplot(cscc.data.mean_cov,'Mean correlation ',1); + set(cscc.H.figure,'HitTest','on','Interruptible','on'); + end + +return + +function buttonupdate +%----------------------------------------------------------------------- +% Put icons on buttons of the main GUI. +%----------------------------------------------------------------------- + global cscc + + % Update figure icons + % close + % help + + + %% == navi buttons == + buttonicon(cscc.H.naviui.select,'DC' ,... + fullfile(matlabroot,'toolbox','matlab','icons','tool_data_cursor.png')); + buttonicon(cscc.H.naviui.zoomReset,'Zo' ,... + fullfile(spm('dir'),'toolbox','cat12','html','icons','tool_fit.png')); + buttonicon(cscc.H.naviui.zoomIn,'Z+' ,... + fullfile(matlabroot,'toolbox','matlab','icons','tool_zoom_in.png')); + buttonicon(cscc.H.naviui.zoomOut,'Z-' ,... + fullfile(matlabroot,'toolbox','matlab','icons','tool_zoom_out.png')); + buttonicon(cscc.H.naviui.pan,'H' ,... + fullfile(matlabroot,'toolbox','matlab','icons','tool_hand.png')); + + + + %% == check buttons == + buttonicon(cscc.H.checkui.vol,'VOL' ,... + fullfile(spm('dir'),'toolbox','cat12','html','icons','file_spm_view.png')); + buttonicon(cscc.H.checkui.surf,'SURF',... + fullfile(spm('dir'),'toolbox','cat12','html','icons','file_surfc.png')); + buttonicon(cscc.H.checkui.log ,'LOG' ,... + fullfile(spm('dir'),'toolbox','cat12','html','icons','file_cat_log.png')); + buttonicon(cscc.H.checkui.xml,'XML' ,... + fullfile(spm('dir'),'toolbox','cat12','html','icons','file_cat_xml.png')); + buttonicon(cscc.H.checkui.pdf,'PDF' ,... + fullfile(spm('dir'),'toolbox','cat12','html','icons','file_cat_report_surf.png')); + + + + %% == trash buttons == + buttonicon(cscc.H.trashui.new,'NEW' ,... + fullfile(spm('dir'),'toolbox','cat12','html','icons','file_new.png')); + buttonicon(cscc.H.trashui.disptrash,'VIEW' ,... + fullfile(spm('dir'),'toolbox','cat12','html','icons','file_export.png')); + buttonicon(cscc.H.trashui.undo,'UNDO' ,... + fullfile(spm('dir'),'toolbox','cat12','html','icons','undo.png')); + buttonicon(cscc.H.trashui.redo,'REDO' ,... + fullfile(spm('dir'),'toolbox','cat12','html','icons','redo.png')); + buttonicon(cscc.H.trashui.trash,'TIP-' ,... + fullfile(spm('dir'),'toolbox','cat12','html','icons','trash_tip_rm.png')); + buttonicon(cscc.H.trashui.detrash,'TIP+' ,... + fullfile(spm('dir'),'toolbox','cat12','html','icons','trash_tip_add.png')); + set([cscc.H.trashui.trash,cscc.H.trashui.detrash],'visible','off'); + buttonicon(cscc.H.trashui.trashcol,'COL-' ,... + fullfile(spm('dir'),'toolbox','cat12','html','icons','trash_col_rm.png')); + buttonicon(cscc.H.trashui.detrashcol,'COL+' ,... + fullfile(spm('dir'),'toolbox','cat12','html','icons','trash_col_add.png')); + buttonicon(cscc.H.trashui.trashrow,'ROW-' ,... + fullfile(spm('dir'),'toolbox','cat12','html','icons','trash_row_rm.png')); + buttonicon(cscc.H.trashui.detrashrow,'ROW+' ,... + fullfile(spm('dir'),'toolbox','cat12','html','icons','trash_row_add.png')); + buttonicon(cscc.H.trashui.autotrash,'AUTO' ,... + fullfile(spm('dir'),'toolbox','cat12','html','icons','trash_auto.png')); + buttonicon(cscc.H.trashui.ziptrash,'DEL' ,... + fullfile(spm('dir'),'toolbox','cat12','html','icons','file_delete.png')); + +return +%----------------------------------------------------------------------- + +function buttonicon(h,str,Picon,useboth) +%----------------------------------------------------------------------- +% Function to print an image file Picon on the button with handle h. Use +% the string str if the global variable cscc.display.useicons<1 or other +% errors. +%----------------------------------------------------------------------- + global cscc + + + usethisicon = cscc.display.useicons; + + set(h,'Visible','on'); + + if ~exist(Picon,'file') + warning('Button Icon ""%s"" does not exist!',Picon); + end + + if ~exist('useboth','var') + useboth = 0; + end + + if ~exist('cat_io_findjobj','file') + warning('JAVA Function for ""%s"" does not exist!',Picon); + cscc.display.useicons = 0; + end + + set(h,'string',''); + + if usethisicon + try + jButton = cat_io_findjobj(h); + jButton.setIcon(javax.swing.ImageIcon(Picon)); + jButton.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT); + jButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); + catch + usethisicon = 0; + end + end + + try + if usethisicon<1 || useboth + set(h,'string',str,'FontSize',cscc.display.FS(cscc.display.FSi)); + else + set(h,'string',''); + end + end +return +%----------------------------------------------------------------------- + +function estimateExclusion(varargin) +%----------------------------------------------------------------------- +% Estimate critical scans that should be excluded and list them on the +% global variable ""at"". +%----------------------------------------------------------------------- + + global cscc at + + useIQR = isfield(cscc.data,'QM') & cscc.H.ETB.PIQRrslider.isEnabled; + + % if a gui is available use it + if isfield(cscc.H,'ETB') && nargin>0; + %MNCath = get(cscc.H.ETB.MNCaslider,'Value')/10; + MNCrth = get(cscc.H.ETB.MNCrslider,'Value')/10; + %PIQRath = get(cscc.H.ETB.PIQRaslider,'Value'); + PIQRrth = get(cscc.H.ETB.PIQRrslider,'Value')/10; + else + MNCrth = at.MNCrth; + PIQRrth = at.PIQRrth; + end + MNCath = at.MNCath*2; + PIQRath = at.PIQRath*2; + + % image quality + % ---------------------------------------------------------------------- + datat = false(size(cscc.data.QM,1),1); + datat(cscc.select.trashlist) = 1; + + if useIQR + delIQRa = find( cscc.data.QM(:,5) < -at.PIQRath ); + mdPIQR = cat_stat_nanmedian(cscc.data.QM(:,5)); + sdPIQR = cat_stat_nanstd(cscc.data.QM(:,5)); + dataf = (cscc.data.QM(:,5) < (mdPIQR - PIQRath) ) | ... + (cscc.data.QM(:,5) < (mdPIQR - PIQRrth * sdPIQR)); + dataf(datat) = 0; + delIQR = unique( [ delIQRa ; find( dataf ) ] ); + dataf(delIQRa)=1; + if isfield(cscc.H,'ETB'); + cscc.H.ETB.histPIQRp.Data = cscc.data.QM(~dataf & ~datat,5); + cscc.H.ETB.histPIQRf.Data = cscc.data.QM( dataf,5); + cscc.H.ETB.histPIQRt.Data = cscc.data.QM( datat,5); + end + datafiqr=dataf; + end + + % removal of data based on the mean covarance + % ---------------------------------------------------------------------- + % negative outlier that does not fit well to this dataset + % - using relative weighting based on the median and the standard + % deviation (eg. scans lower than 2*sdMNC from mdMNC) + % - using a absolute value (eg. < mdMNC - 0.05 ) + mdMNC = cat_stat_nanmedian(cscc.data.mean_cov); + sdMNC = cat_stat_nanstd(cscc.data.mean_cov); + dataf = (cscc.data.mean_cov < (mdMNC - MNCath) ) | ... % records below absolute lower threshold + (cscc.data.mean_cov < (mdMNC - MNCrth * sdMNC) ); + delMNCl = find( dataf ); % records below relative lower threshold + + + % create final exclusion list for MNC + datad = false(size(dataf)); + if ~cscc.data.islongitudinal + % positive outlier that fit well to another dataset (dublicate entries / rescans) + delMNCh = find((tril(cscc.data.YpY,-1) > (mdMNC + MNCath) ) & ... % records above absolute higher threshold + (tril(cscc.data.YpY,-1) > (mdMNC + MNCrth * sdMNC) ) ); + + % get x ad y record + [delMNCh(:,2),delMNCh(:,1)] = ind2sub(size(cscc.data.YpY),delMNCh); + + % remove both entries if they are in different groups + groups = any(cscc.datagroups.sample(delMNCh) ~= ... + repmat(cscc.datagroups.sample(delMNCh(:,1))',1,2),2); + multigroup = delMNCh([groups;groups]); + delMNCh = delMNCh(:,2); + + datad([delMNCh; multigroup(:)]) = 1; + delMNC = [delMNCl;delMNCh;multigroup(:)]; + else + delMNC = delMNCl; + end + + if isfield(cscc.H,'ETB') + cscc.H.ETB.histMNCp.Data = cscc.data.mean_cov(~dataf & ~datad & ~datat); + cscc.H.ETB.histMNCf.Data = cscc.data.mean_cov( dataf); + cscc.H.ETB.histMNCd.Data = cscc.data.mean_cov( datad); + cscc.H.ETB.histMNCt.Data = cscc.data.mean_cov( datat); + end + + % final combination + if useIQR + del = unique([delIQR',delMNC']); + else + del = unique(delMNC'); + end + del = setdiff( del , cscc.select.trashlist); + + if isfield(cscc.H,'ETB') && isfield(cscc.H.ETB,'tab') && any(cscc.H.ETB.tab(:).isvalid) + %% + isdel{4}=false(size(dataf)); isdel{4}(unique([cscc.select.trashlist,del]))=1; isdel{3}=~isdel{4}; + for i=3:size(cscc.H.ETB.tab,1) + for j=2:size(cscc.H.ETB.tab,2) + if cscc.H.ETB.tab(1,j).isvalid + switch cscc.H.ETB.tab(1,j).String(1) + case 'R' + set(cscc.H.ETB.tab(i,j),'String',sprintf('%0.2f%% (%d)',... + 100 * (sum(isdel{i})) ./ numel(isdel{i}),sum(isdel{i}))); + case 'G' + k = str2double(cscc.H.ETB.tab(1,j).String(2:end)); + set(cscc.H.ETB.tab(i,j),'String',sprintf('%d',sum(cscc.datagroups.sample'==k & isdel{i}))); + case 'N' + k = str2double(cscc.H.ETB.tab(1,j).String(2:end)); + set(cscc.H.ETB.tab(i,j),'String',sprintf('%0.2f',mean(cscc.job.c{k}(isdel{i})))); + case 'M' + set(cscc.H.ETB.tab(i,j),'String',sprintf('%0.3f',mean(cscc.data.mean_cov(isdel{i})))); + case 'I' + set(cscc.H.ETB.tab(i,j),'String',sprintf('%0.2f',mean(cscc.data.QM(isdel{i},4)))); + case 'P' + set(cscc.H.ETB.tab(i,j),'String',sprintf('%0.2f',mean(cscc.data.QM(isdel{i},5)))); + case 'E' + set(cscc.H.ETB.tab(i,j),'String',sprintf('%0.2f',mean(cscc.data.QM(isdel{i},6)))); + end + end + end + end + end + if isfield(cscc.H,'ETB') && isfield(cscc.H.ETB,'tab') + %% + legends = {'histMNClegend','histPIQRlegend'}; + for i=1:numel(legends) + if isfield(cscc.H.ETB,legends{i}) && any(cscc.H.ETB.(legends{i})(:).isvalid) + for j=1:numel(cscc.H.ETB.(legends{i}).String) + switch cscc.H.ETB.(legends{i}).String{j}(1:2) + case 'pa', + if i==1 + cscc.H.ETB.(legends{i}).String{j} = sprintf('passed (%d)',sum(~dataf & ~datad)); + else + cscc.H.ETB.(legends{i}).String{j} = sprintf('passed (%d)',sum(~datafiqr)); + end + case 'ex', + if i==1 + cscc.H.ETB.(legends{i}).String{j} = sprintf('excluded (%d)',sum( dataf & ~datad & ~datat)); + else + cscc.H.ETB.(legends{i}).String{j} = sprintf('excluded (%d)',sum( datafiqr & ~datat)); + end + case 're', cscc.H.ETB.(legends{i}).String{j} = sprintf('rescans (%d)',sum(datad & ~datat)); + case 'al', cscc.H.ETB.(legends{i}).String{j} = sprintf('alr. exc. (%d)',sum(datat)); + end + end + end + end + end + + at.del = del; +return +%----------------------------------------------------------------------- + +function autotrashGUI +%----------------------------------------------------------------------- +% GUI to control the exlusion of scans by low mean correlation or low +% image quality. +%----------------------------------------------------------------------- + global cscc + + useIQR = isfield(cscc.data,'QM') && 1; + + + %% move to begin if finished +cscc.pos.trashpopup = [cscc.H.figure.Position(1:2) 1.2*cscc.display.WS(3) 0.8*cscc.display.WS(3)]; +cscc.pos.trashpopup(1) = cscc.H.figure.Position(1) + (cscc.H.figure.Position(3) - cscc.pos.trashpopup(3))/2; +cscc.pos.trashpopup(2) = cscc.H.figure.Position(2) + (cscc.H.figure.Position(4) - cscc.pos.trashpopup(4)) - 24; + + % use the dialog if finished + if isfield( cscc.H ,'ETB' ) && isfield( cscc.H.ETB ,'main' ) && ... + ~isempty( cscc.H.ETB.main ) && isvalid(cscc.H.ETB.main ) + fpos = get(cscc.H.ETB.main,'Position'); + delete(cscc.H.ETB.main); + else + fpos = cscc.pos.trashpopup; + end + + %cscc.H.ETB.main = dialog('Position',cscc.pos.trashpopup,'Name','Remove problematic data'); + cscc.H.ETB.main = figure('Position',fpos,'Name','Remove problematic data','MenuBar','none'); + + % == MNC histogram == + mncrvals = [5 2 100 max(std(cscc.data.mean_cov)*400,150*(median(cscc.data.mean_cov) - min(cscc.data.mean_cov)))]; + mncbvals = [1 0 7 4]; + %cscc.H.ETB.mncbvalues = 2.^( (mncbvals(1):1:mncbvals(3)) - (mncbvals(3) - 4) )/100; % automatic + cscc.H.ETB.mncbvalues = [0.001 0.002 1/300 0.005 0.01 0.02 1/30]; + cscc.H.ETB.histMNC = subplot('position',[0.05 0.5 0.425 0.450]); + cscc.H.ETB.histMNCrange = 0 : cscc.H.ETB.mncbvalues(mncbvals(4)) : 1; + + if 0 %useIQR + cscc.H.ETB.histMNCcb = uicontrol(cscc.H.ETB.main ,... + 'Units','normalized','Style','CheckBox','position',[0.05 0.96 0.03 0.03],'callback','',... + 'string','Fixed range','ToolTipString','Use MNC Thresholding',... + 'Value',1,'FontSize',cscc.display.FS(cscc.display.FSi)); + cscc.H.ETB.histPIQRcb = uicontrol(cscc.H.ETB.main ,... + 'Units','normalized','Style','CheckBox','position',[0.52 0.96 0.03 0.03],'callback','',... + 'string','Fixed range','ToolTipString','Use PIQR Thresholding',... + 'Value',1,'FontSize',cscc.display.FS(cscc.display.FSi)); + end + + % plot histrogam + hold on; + cscc.H.ETB.histMNCp = histogram(cscc.H.ETB.histMNC,... + cscc.data.mean_cov(cscc.data.mean_cov(:) > 0),cscc.H.ETB.histMNCrange); + cscc.H.ETB.histMNCf = histogram(cscc.H.ETB.histMNC,... + cscc.data.mean_cov(cscc.data.mean_cov(:) < 0),cscc.H.ETB.histMNCrange); + cscc.H.ETB.histMNCd = histogram(cscc.H.ETB.histMNC,... + cscc.data.mean_cov(cscc.data.mean_cov(:) < 0),cscc.H.ETB.histMNCrange); + cscc.H.ETB.histMNCt = histogram(cscc.H.ETB.histMNC,... + cscc.data.mean_cov(cscc.data.mean_cov(:) < 0),cscc.H.ETB.histMNCrange); + set(cscc.H.ETB.histMNCp,'FaceColor',[0 0.7 0 ],'EdgeColor',[0 0.7 0 ],'LineStyle','none','FaceAlpha',1); + set(cscc.H.ETB.histMNCf,'FaceColor',[1.0 0 0 ],'EdgeColor',[0.9 0 0 ],'LineStyle','none','FaceAlpha',1); + set(cscc.H.ETB.histMNCd,'FaceColor',[0.0 0.5 1.0],'EdgeColor',[1.0 0.4 0.2],'LineStyle','none','FaceAlpha',1); + set(cscc.H.ETB.histMNCt,'FaceColor',[0.5 0 0 ],'EdgeColor',[0.5 0 0 ],'LineStyle','none','FaceAlpha',1); + cscc.H.ETB.histMNClegend = legend(... + [cscc.H.ETB.histMNCp,cscc.H.ETB.histMNCf,cscc.H.ETB.histMNCd,cscc.H.ETB.histMNCt],... + {'passed','excluded','rescans','alr. exc.'}); + hold off; + + % add title and set limits + title('mean correlation (MNC)'); box on; grid on + ylim( cscc.H.ETB.histMNC , ylim .* [1 1.2]); + xlim( cscc.H.ETB.histMNC , max(0,min(1,median(cscc.data.mean_cov)*1.01 + ... + mncrvals(4)/10 * [-1 1/3] * median(cscc.data.mean_cov)/10 ))); + set(gca,'Xdir','reverse'); + + + + + % IQR histogram + % print inactive looking elements if not available + if useIQR, Color = zeros(1,3); else Color = ones(1,3) * 0.6; end + if useIQR + piqrvals = [5 1 10*max([20;abs(cscc.data.QM(:,5))])^(1/1.2) 10*max([3;1.8*abs(cscc.data.QM(:,5))])^(1/1.2)]; + piqbvals = [1 0 7 4]; + cscc.H.ETB.piqrvals = piqrvals; + %cscc.H.ETB.piqbvalues = 2.^( (piqbvals(1):1:piqbvals(3)) - (piqbvals(3) - 2) ); + cscc.H.ETB.piqbvalues = [0.01 0.02 1/30 0.05 0.1 0.2 1/3 0.5]; + + cscc.H.ETB.histPIQR = subplot('position',[0.525 0.5 0.425 0.450]); + cscc.H.ETB.histPIQRrange = ... + [ fliplr( 0 : -cscc.H.ETB.piqbvalues(piqbvals(4)) : min(-8,floor(min(cscc.data.QM(:,5))) )) ... + cscc.H.ETB.piqbvalues(piqbvals(4)) : cscc.H.ETB.piqbvalues(piqbvals(4)) : max(32,ceil(max(cscc.data.QM(:,5)))) ]; + + hold on + cscc.H.ETB.histPIQRp = histogram(cscc.H.ETB.histPIQR,... + cscc.data.QM(cscc.data.QM(:,5) < 3,5),cscc.H.ETB.histPIQRrange); + cscc.H.ETB.histPIQRf = histogram(cscc.H.ETB.histPIQR,... + cscc.data.QM(cscc.data.QM(:,5) > 3,5),cscc.H.ETB.histPIQRrange); + cscc.H.ETB.histPIQRt = histogram(cscc.H.ETB.histPIQR,... + cscc.data.QM(cscc.data.QM(:,5) > 3,5),cscc.H.ETB.histPIQRrange); + hold off + set(cscc.H.ETB.histPIQRp,'FaceColor',[0 0.7 0],'EdgeColor',[0 0.4 0],'LineStyle','none','FaceAlpha',1); + set(cscc.H.ETB.histPIQRf,'FaceColor',[1 0 0],'EdgeColor',[0.4 0 0],'LineStyle','none','FaceAlpha',1); + set(cscc.H.ETB.histPIQRt,'FaceColor',[0.5 0 0],'EdgeColor',[0.5 0 0],'LineStyle','none','FaceAlpha',1); + + title('protocol-base image quality rating (PIQR)'); box on; grid on + ylim( ylim .* [1 1.2]); + xlim( cscc.H.ETB.histPIQR , max(min([-piqrvals(3)*2;cscc.data.QM(:,5)]),... + min(max([piqrvals(3);cscc.data.QM(:,5)]),piqrvals(3)/100)^1.2 * [-1 1/2] ) ) + set(gca,'Xdir','reverse') + cscc.H.ETB.histPIQRlegend = legend(... + [cscc.H.ETB.histPIQRp,cscc.H.ETB.histPIQRf,cscc.H.ETB.histPIQRt],... + {'passed','excluded','alr. exc.'}); + else + cscc.H.ETB.histPIQR = subplot('position',[0.525 0.5 0.425 0.450],... + 'Color',ones(1,3) * 0.97,'XColor',Color,'YColor',Color); + hold on + plot(cscc.H.ETB.histPIQR,[0,1],[1,0],'Color',Color); + plot(cscc.H.ETB.histPIQR,[0,1],[0,1],'Color',Color); + hold off + box on; + title('protocol-base image quality rating (PIQR)','Color',Color) + end + + + + + % == View sliders == + % MNC view slider + posm = [0.03 0.37 0.235 0.045]; + post = round((posm + [0 0.045 0 -0.015]) .* cscc.pos.trashpopup([3:4,3:4])); + poss = round(posm .* cscc.pos.trashpopup([3:4,3:4])); + cscc.H.ETB.MNCvslider = javax.swing.JSlider; + javacomponent(cscc.H.ETB.MNCvslider,poss); + uicontrol('Parent',cscc.H.ETB.main,'Style','text','position',post,'String','window aperture'); + set(cscc.H.ETB.MNCvslider,'Minimum',mncrvals(1),'Maximum',mncrvals(3),'Value',mncrvals(4),'snapToTicks',0,... + 'minorTickSpacing',mncrvals(2),'MajorTickSpacing',mncrvals(1),'PaintTicks',false, 'PaintLabels',false); + set(cscc.H.ETB.MNCvslider,... + 'StateChangedCallback',... + ['global cscc;' ... + 'xlim( cscc.H.ETB.histMNC , max(0,min(1,median(cscc.data.mean_cov)*1.01+ '... + ' (double(get(cscc.H.ETB.MNCvslider,''Value''))/10)^1.2 * [-1 1/3] * median(cscc.data.mean_cov)/10 ))); ' ... + 'set(cscc.H.ETB.histMNC,''Xdir'',''reverse'');']); + + % PIQR view slider + posm = [0.51 0.37 0.235 0.045]; + post = round((posm + [0 0.045 0 -0.015]) .* cscc.pos.trashpopup([3:4,3:4])); + poss = round(posm .* cscc.pos.trashpopup([3:4,3:4])); + uicontrol('Parent',cscc.H.ETB.main,'Style','text','position',post,'String','window aperture','ForegroundColor',Color); + cscc.H.ETB.PIQRvslider = javax.swing.JSlider; + javacomponent(cscc.H.ETB.PIQRvslider,poss); + if useIQR + set(cscc.H.ETB.PIQRvslider,'Minimum',piqrvals(1),'Maximum',piqrvals(3),'Value',piqrvals(4),'snapToTicks',0,... + 'minorTickSpacing',piqrvals(2),'MajorTickSpacing',piqrvals(1),'PaintTicks',false, 'PaintLabels',false); + set(cscc.H.ETB.PIQRvslider,... + 'StateChangedCallback',... + ['global cscc;' ... + 'xlim( cscc.H.ETB.histPIQR , max(min([-cscc.H.ETB.piqrvals(3)*2;cscc.data.QM(:,5)]),' ... + ' min(max([cscc.H.ETB.piqrvals(3);cscc.data.QM(:,5)]), ' ... + ' (double(get(cscc.H.ETB.PIQRvslider,''Value''))/10)^1.2 * [-1 1/2] ) ) ); '... + 'set(cscc.H.ETB.histPIQR,''Xdir'',''reverse'');']); + else + cscc.H.ETB.PIQRvslider.disable; + end + % change slider font size ??? + % fs = cscc.H.ETB.MNCvslider.getFont; + % fs.setSize = cscc.display.FS(cscc.display.FSi-1); + % cscc.H.ETB.MNCvslider.setFont(fs); % nothing to set the font-size + % create new font? but how? + + + + % == Bin sliders == + % MNC bin slider + posm = [0.26 0.37 0.235 0.045]; + post = round((posm + [0 0.045 0 -0.015]) .* cscc.pos.trashpopup([3:4,3:4])); + poss = round(posm .* cscc.pos.trashpopup([3:4,3:4])); + cscc.H.ETB.MNCbslider = javax.swing.JSlider; + javacomponent(cscc.H.ETB.MNCbslider,poss); + uicontrol('Parent',cscc.H.ETB.main,'Style','text','position',post,'String','bin width'); + set(cscc.H.ETB.MNCbslider,'Minimum',mncbvals(1),'Maximum',mncbvals(3),'Value',mncbvals(4),'snapToTicks',1,... + 'minorTickSpacing',mncbvals(2),'MajorTickSpacing',mncbvals(1),'PaintTicks',0, 'PaintLabels',false); + set(cscc.H.ETB.MNCbslider,'StateChangedCallback',['global cscc; ' ... + 'val = cscc.H.ETB.mncbvalues(get(cscc.H.ETB.MNCbslider,''Value'')); ' ... + 'cscc.H.ETB.histMNCp.BinWidth = val;' ... + 'cscc.H.ETB.histMNCf.BinWidth = val;' ... + 'cscc.H.ETB.histMNCt.BinWidth = val;' ... + 'cscc.H.ETB.histMNCd.BinWidth = val;' ... + 'ylim( cscc.H.ETB.histMNC , ''auto'' ); ylim( cscc.H.ETB.histMNC , ylim( cscc.H.ETB.histMNC ) .* [1 1.2]); ']); + + % PIQR bin slider + posm = [0.74 0.37 0.235 0.045]; + post = round((posm + [0 0.045 0 -0.015]) .* cscc.pos.trashpopup([3:4,3:4])); + poss = round(posm .* cscc.pos.trashpopup([3:4,3:4])); + uicontrol('Parent',cscc.H.ETB.main,'Style','text','position',post,'String','bin width','ForegroundColor',Color); + cscc.H.ETB.PIQRbslider = javax.swing.JSlider; + javacomponent(cscc.H.ETB.PIQRbslider,poss); + if useIQR + set(cscc.H.ETB.PIQRbslider,'Minimum',piqbvals(1),'Maximum',piqbvals(3),'Value',piqbvals(4),'snapToTicks',1,... + 'minorTickSpacing',piqbvals(2),'MajorTickSpacing',piqbvals(1),'PaintTicks',0, 'PaintLabels',false); + set(cscc.H.ETB.PIQRbslider,'StateChangedCallback',['global cscc;' ... + 'val = cscc.H.ETB.piqbvalues(get(cscc.H.ETB.PIQRbslider,''Value'')); ' ... + 'cscc.H.ETB.histPIQRp.BinWidth = val;' ... + 'cscc.H.ETB.histPIQRf.BinWidth = val;' ... + 'cscc.H.ETB.histPIQRt.BinWidth = val;' ... + 'ylim( cscc.H.ETB.histPIQR , ''auto'' ); ylim( cscc.H.ETB.histPIQR , ylim( cscc.H.ETB.histPIQR ) .* [1 1.2]); ']); + else + cscc.H.ETB.PIQRvslider.disable; + end + + + + % == Exclusion sliders == + + % MNC exclusion slider + posm = [0.03 0.26 0.465 0.06]; %0.465 + post = round((posm + [0 0.068 0 -0.03]) .* cscc.pos.trashpopup([3:4,3:4])); + poss = round(posm .* cscc.pos.trashpopup([3:4,3:4])); + cscc.H.ETB.MNCrslider = javax.swing.JSlider; mncrvals = [10 1 50 30]; + javacomponent(cscc.H.ETB.MNCrslider,poss); + set(cscc.H.ETB.MNCrslider,'Minimum',mncrvals(1),'Maximum',mncrvals(3),'Value',mncrvals(4),'snapToTicks',1,... + 'minorTickSpacing',mncrvals(2),'MajorTickSpacing',mncrvals(1),'PaintTicks',true, 'PaintLabels',false); + set(cscc.H.ETB.MNCrslider,'StateChangedCallback',@estimateExclusion); + uicontrol('Parent',cscc.H.ETB.main,'Style','text','position',post,'String','standard deviation limit'); + for i=1:5 + uicontrol('Parent',cscc.H.ETB.main,'Style','text','String',sprintf('%d',i),'Fontsize',9,... + 'Units','normalized','position', [ posm(1:2) + [0.007 + (i-1)*0.1056 -0.03] 0.03 0.03]); + end + + % PIQR exclusion slider + posm = [0.51 0.26 0.465 0.06]; + post = round((posm +[0 0.068 0 -0.03]) .* cscc.pos.trashpopup([3:4,3:4])); + poss = round(posm .* cscc.pos.trashpopup([3:4,3:4])); + uicontrol('Parent',cscc.H.ETB.main,'Style','text','position',post,'String','standard deviation limit','ForegroundColor',Color); + cscc.H.ETB.PIQRrslider = javax.swing.JSlider; mncrvals = [10 1 50 30]; + javacomponent(cscc.H.ETB.PIQRrslider,poss); + set(cscc.H.ETB.PIQRrslider,'Minimum',mncrvals(1),'Maximum',mncrvals(3),'Value',mncrvals(4),'snapToTicks',1,... + 'minorTickSpacing',mncrvals(2),'MajorTickSpacing',mncrvals(1),'PaintTicks',true, 'PaintLabels',false); %,... + set(cscc.H.ETB.PIQRrslider,'StateChangedCallback',@estimateExclusion); + if ~useIQR, cscc.H.ETB.PIQRrslider.disable; end + for i=1:5 + uicontrol('Parent',cscc.H.ETB.main,'Style','text','String',sprintf('%d',i),'Fontsize',9,... + 'Units','normalized','position', [ posm(1:2) + [0.007 + (i-1)*0.1056 -0.03] 0.03 0.03]); + end + + % === table and buttongroup === + cscc.H.ETB.bg = uibuttongroup(cscc.H.ETB.main,... + 'Position',[-0.01 -0.01 1.02 0.22]); + + % table with rows for total, passed and failed scans + % with MNC, IQR PIQR, Euler, Nuisance1-3 as for loop table + posm = [0.03 0.03 0 0.04]; + clear tab; + tab(1,1) = struct('str','Group' ,'col',[0 0 0 ],'width',0.09,'ad',0); + tab(2,1) = struct('str','Total:' ,'col',[0 0 0 ],'width',0.09,'ad',0); + tab(3,1) = struct('str','Accepted:','col',[0 0.5 0 ],'width',0.09,'ad',0); + tab(4,1) = struct('str','Excluded:','col',[0.9 0 0 ],'width',0.09,'ad',0); + + tab(1,2) = struct('str','Ratio' ,'col',[0 0 0 ],'width',... + 0.05 + 0.02*cscc.datagroups.n_samples,'ad',0.01); + tab(2,2) = struct('str',sprintf('100%% (%d)',cscc.datagroups.n_subjects),... + 'col',[0 0 0],'width',0,'ad',0); + for i=1:min(10,cscc.datagroups.n_samples) + tab(1,end+1) = struct('str',sprintf('G%d',i),'col',[0 0 0],'width',... + 0.015*ceil(cscc.datagroups.n_subjects^(1/10)),'ad',0.02*(i==1)); + tab(2,end) = struct('str',sprintf('%d',sum(cscc.datagroups.sample==i)),... + 'col',[0 0 0],'width',0,'ad',0); + end + + % mean correlation + tab(1,end+1) = struct('str','MNC' ,'col',[0 0 0 ],'width',0.06,'ad',0.02); + tab(2,end) = struct('str',sprintf('%0.3f',mean( cscc.data.mean_cov)),... + 'col',[0 0 0 ],'width',0.06,'ad',0.02); + + % xml variables + if useIQR + tab(1,end+1) = struct('str','IQR','col',[0 0 0 ],'width',0.06,'ad',0); + tab(2,end) = struct('str',sprintf('%0.2f',mean( cscc.data.QM(:,4))),... + 'col',[0 0 0 ],'width',0.06,'ad',0.02); + tab(1,end+1) = struct('str','PIQR','col',[0 0 0 ],'width',0.06,'ad',0); + tab(2,end) = struct('str',sprintf('%0.2f',mean( cscc.data.QM(:,5))),... + 'col',[0 0 0 ],'width',0.06,'ad',0.02); + if size(cscc.data.QM,2)>5 + tab(1,end+1) = struct('str','Euler','col',[0 0 0 ],'width',0.06,'ad',0); + tab(2,end) = struct('str',sprintf('%0.2f',mean( cscc.data.QM(:,6))),... + 'col',[0 0 0 ],'width',0.06,'ad',0.02); + end + end + + % nuisance variables + for i=1:min(3,numel(cscc.job.c)) + tab(1,end+1) = struct('str',sprintf('N%d',i),'col',[0 0 0],'width',0.07,'ad',0.02*(i==1)); + tab(2,end) = struct('str',sprintf('%0.2f',mean(cscc.job.c{i})),'col',[0 0 0],'width',0,'ad',0); + end + + % scale table + adx = (0.8 - (sum([tab(1,:).width]) + sum([tab(1,:).ad])) ) / size(tab,2); + for j=2:size(tab,2), tab(1,j).ad = tab(1,j).ad + adx; end + + % print table + for i=1:size(tab,1) + for j=1:size(tab,2) + cscc.H.ETB.tab(i,j) = uicontrol('Parent',cscc.H.ETB.main,'Style','text',... + 'position',round((posm + [ sum([tab(1,1:j-1).width]) + sum([tab(1,1:j).ad]) ... + (4-i)*0.035 tab(1,j).width 0]) .* cscc.pos.trashpopup([3:4,3:4])),... + 'HorizontalAlignment','right','Fontsize',cscc.display.FS(cscc.display.FSi+4),... + 'ForegroundColor',tab(i,1).col); + if ~isempty(tab(i,j).str), set(cscc.H.ETB.tab(i,j),'String',tab(i,j).str); end + if ~isempty(tab(i,j).col), set(cscc.H.ETB.tab(i,j),'ForegroundColor',tab(i,j).col); end + if i==1, set(cscc.H.ETB.tab(i,j),'FontWeight','bold','ForegroundColor',[0.3 0.3 0.3]); end + + end + end + % + estimateExclusion; + + + posm = [0.91 0.035 0.06 0.07]; + % add button to open the help HTML + + cscc.H.ETB.auto = uicontrol(cscc.H.ETB.main,... + 'Units','normalized','position',posm + [-posm(3)+0.005 posm(4)-0.01 0 0],'Style','Pushbutton',... + 'string','Auto','ToolTipString','Set defaults','ForegroundColor',[0 0.8 0],... + 'FontSize',cscc.display.FS(cscc.display.FSi+4),'enable','off',... + 'callback',''); + + % add button to open the help HTML + cscc.H.ETB.help = uicontrol(cscc.H.ETB.main,... + 'Units','normalized','position',posm + [0 posm(4)-0.01 0 0],'Style','Pushbutton',... + 'string','Help','ToolTipString','Open help of this window','ForegroundColor',[0 0 0.8],... + 'FontSize',cscc.display.FS(cscc.display.FSi+4),'callback',... + ['global cscc; ' ... + 'if ~isfield(cscc.H,''helpfig'') || ~isvalid(cscc.H.helpfig) ' ... + ' cscc.H.helpfig = spm_figure(''Create'',''CAThelp'',''CAT help''); ' ... + ' cscc.H.helpfig.Position = cscc.H.graphics.Position;' ... + 'end; ' ... + 'spm_help(''!Disp'',fullfile(spm(''Dir''),''toolbox'',''cat12'',''html'... + ',''cat_tools_checkcov.html'','''',cscc.H.helpfig);']); + + % reject button + closefunction = ['global cscc; ' ... + 'delete(cscc.H.ETB.main); ' ... + 'cscc.H = rmfield(cscc.H,''ETB'');' ... + 'clearvars -global at;']; + cscc.H.ETB.reject = uicontrol(cscc.H.ETB.main,... + 'Units','normalized','position',posm + [-posm(3)+0.005 0 0 0],'Style','Pushbutton',... + 'string','Reject','ToolTipString','Close window without settings','ForegroundColor',[0.8 0 0],... + 'FontSize',cscc.display.FS(cscc.display.FSi+4),'callback', closefunction ); + cscc.H.ETB.main.CloseRequestFcn = closefunction; + + % apply button + cscc.H.ETB.apply = uicontrol(cscc.H.ETB.main,... + 'Units','normalized','position',posm,'Style','Pushbutton',... + 'string','Apply','ToolTipString','Apply settings and close window','ForegroundColor',[0 0.6 0 ],... + 'FontSize',cscc.display.FS(cscc.display.FSi+4),'callback',@autotrash); + + % + buttonicon(cscc.H.ETB.auto ,'Auto' ,fullfile(spm('dir'),'toolbox','cat12','html','icons','trash_auto.png')); + buttonicon(cscc.H.ETB.help ,'Help' ,fullfile(spm('dir'),'toolbox','cat12','html','icons','status_help.png')); + buttonicon(cscc.H.ETB.reject ,'Reject' ,fullfile(spm('dir'),'toolbox','cat12','html','icons','status_failed.png')); + buttonicon(cscc.H.ETB.apply ,'Apply' ,fullfile(spm('dir'),'toolbox','cat12','html','icons','status_passed.png')); + + + + +return +%----------------------------------------------------------------------- + +function autotrash(obj, event_obj) +%----------------------------------------------------------------------- +% Subfunction of cat_check_cov2 that calls another GUI (autotrashGUI) or +% directly estimates the worst datasets that should be excluded. Uses an +% additional global variable ""at"" for default parameter and the new +% exclusion list that is finally added to the trashlist. +%----------------------------------------------------------------------- + global cscc at + + % set default values + if ~exist('at','var') || isempty(at) + at.MNCath = 0.05; + at.MNCrth = 2; + at.PIQRath = 4; + at.PIQRrth = 2; + + if ~isfield(at,'del') && 1 %cscc.job.expertgui + autotrashGUI; + return + else + % estimate list + estimateExclusion + if isempty(at.del) + fprintf('Nothing to delete.\n'); + end + end + end + + + if isfield(at,'del') && ~isempty(at.del) + if isfield(cscc.pos,'x'), oldx = cscc.pos.x; end + if isfield(cscc.pos,'y'), oldy = cscc.pos.y; cscc.H.y = rmfield(cscc.pos,'y'); end + + % remove the different datasets + for di=1:numel(at.del) + cscc.pos.x = at.del(di); + trash + end + + % sort by IQRratio + [ss,si] = sort(cscc.data.IQRratio(at.del),'descend'); + at.del = at.del(si); + + cscc.select.trashlist = [cscc.select.trashlist, at.del]; + cscc.select.trashhist = [cscc.select.trashhist, at.del]; + cscc.select.trashhistf = []; + + if exist('oldx','var'), cscc.pos.x = oldx; end + if exist('oldy','var'), cscc.pos.y = oldy; end + + set([cscc.H.trashui.new,cscc.H.trashui.disptrash,cscc.H.trashui.undo... + cscc.H.trashui.autotrash,cscc.H.trashui.ziptrash],'enable','on'); + set(cscc.H.trashui.redo,'enable','off'); + + % update boxplot + show_boxplot + + % set fields + if isfield(cscc.H,'showtrash') && ishandle(cscc.H.showtrash), set(cscc.H.showtrash,'Enable','on'); end + end + + % cleanup + if isfield(cscc.H,'ETB') + if isfield(cscc.H.ETB,'main') && isvalid(cscc.H.ETB.main ) + delete(cscc.H.ETB.main) + end + cscc.H = rmfield(cscc.H,'ETB'); + end + + clearvars -global at; +return + +%----------------------------------------------------------------------- +function trash(obj, event_obj) +%----------------------------------------------------------------------- +% Puts a record on the trash list and marks it with a red cross in the +% Ratio IQR/mean correlation plot. +%----------------------------------------------------------------------- + global cscc + + if isfield(cscc.pos,'x') && all( cscc.select.trashlist~=cscc.pos.x ) + if exist('obj','var') + cscc.select.trashlist = [cscc.select.trashlist cscc.pos.x]; + cscc.select.trashhist = [cscc.select.trashhist cscc.pos.x]; + end + + showtrash = get(cscc.H.showtrash,'Value'); + if ~showtrash && ~cscc.H.isscatter + cscc.H.dcm.removeAllDataCursors; + end + + if exist('obj','var') + set(cscc.H.trashui.undo ,'Enable','on' ); + set(cscc.H.trashui.new ,'Enable','on' ); + set(cscc.H.trashui.disptrash,'Enable','on' ); + set(cscc.H.trashui.ziptrash ,'Enable','on' ); + set(cscc.H.trashui.undo ,'Enable','on' ); + set(cscc.H.trashui.redo ,'Enable','off' ); + end + if ~cscc.H.isscatter + set(cscc.H.trashui.trashcol ,'Enable','off'); + set(cscc.H.trashui.detrashcol,'Enable','on' ); + set(cscc.H.showtrash ,'Enable','on' ); + else + set(cscc.H.trashui.trash ,'Enable','off'); + set(cscc.H.trashui.detrash ,'Enable','on' ); + end + + cscc.select.trash1d(cscc.pos.x) = 0; + cscc.select.trash2d(cscc.pos.x,:) = 0; + cscc.select.trash2d(:,cscc.pos.x) = 0; + + for scati=1:numel(cscc.H.scat) + sc.posx = findobj(cscc.H.scat(scati),'type','scatter'); + sc.posxv = cell2mat(get(sc.posx,'UserData')); + sc.posxi = find(sc.posxv==cscc.pos.x,1,'first'); + + set(sc.posx(sc.posxi),'sizedatasource',... + get(sc.posx(sc.posxi),'marker'),... + 'marker','x','SizeData',40,'MarkerEdgeColor',[1 0 0.5],... + 'ZDataSource','trash','MarkerFaceAlpha',0); + end + if ~cscc.H.isscatter + update_matrix + end + + + end +return + +%----------------------------------------------------------------------- +function trashrow(obj, event_obj) +%----------------------------------------------------------------------- +% Puts a record on the trash list and marks it with a red cross in the +% Ratio IQR/mean correlation plot. +%----------------------------------------------------------------------- + global cscc + + if isfield(cscc.pos,'y') && all( cscc.select.trashlist~=cscc.pos.y ) + cscc.select.trashlist = [cscc.select.trashlist cscc.pos.y]; + cscc.select.trashhist = [cscc.select.trashhist cscc.pos.y]; + + set(cscc.H.trashui.trashrow ,'Enable','off'); + set(cscc.H.trashui.detrashrow,'Enable','on' ); + set(cscc.H.trashui.ziptrash ,'Enable','on' ); + set(cscc.H.trashui.undo ,'Enable','on' ); + set(cscc.H.showtrash ,'Enable','on' ); + + cscc.select.trash1d(cscc.pos.y) = 0; + cscc.select.trash2d(cscc.pos.y,:) = 0; + cscc.select.trash2d(:,cscc.pos.y) = 0; + + for scati=1:numel(cscc.H.scat) + sc.posx = findobj(cscc.H.scat,'type','scatter'); + sc.posxv = cell2mat(get(sc.posx,'UserData')); + sc.posxi = find(sc.posxv==cscc.pos.y,1,'first'); + + set(sc.posx(sc.posxi),'sizedatasource',... + get(sc.posx(sc.posxi),'marker'),... + 'marker','x','SizeData',40,'MarkerEdgeColor',[1 0 0.5],... + 'ZDataSource','trash','MarkerFaceAlpha',0); + end + + if ~cscc.H.isscatter + update_matrix; + end + + end +return + +%----------------------------------------------------------------------- +function detrash(obj, event_obj) +%----------------------------------------------------------------------- +% Removes a record from trash list and restores the old look like in the +% Ratio IQR/mean correlation plot. +%----------------------------------------------------------------------- + global cscc + + if isfield(cscc.pos,'x') && any( cscc.select.trashlist==cscc.pos.x ) + if exist('obj','var') + cscc.select.trashlist = setdiff(cscc.select.trashlist,cscc.pos.x); + cscc.select.trashhist = [cscc.select.trashhist -cscc.pos.x]; + + if cscc.H.isscatter + set(cscc.H.trashui.trash ,'Enable','on' ); + set(cscc.H.trashui.detrash,'Enable','off'); + else + set(cscc.H.trashui.trashcol ,'Enable','on' ); + set(cscc.H.trashui.detrashcol,'Enable','off'); + end + end + + % update matrix + cscc.select.trash1d(cscc.pos.x) = 1; + cscc.select.trash2d(cscc.pos.x,:) = sum(cscc.select.trash2d,1)>0; + cscc.select.trash2d(:,cscc.pos.x) = sum(cscc.select.trash2d,2)>0; + + % update scatter + for scati=1:numel(cscc.H.scat) + sccscc.posx = findobj(cscc.H.scat(scati),'type','scatter'); + sccscc.posxv = cell2mat(get(sccscc.posx,'UserData')); + sccscc.posxi = find(sccscc.posxv==cscc.pos.x,1,'first'); + + set(sccscc.posx(sccscc.posxi),'marker',... + get(sccscc.posx(sccscc.posxi),'sizedatasource'),... + 'ZDataSource','','MarkerEdgeColor','flat','MarkerFaceAlpha',1/3); + end + + if ~cscc.H.isscatter + update_matrix; + if isempty(cscc.select.trashlist), set(cscc.H.showtrash,'Enable','off'); end + end + + if isempty(cscc.select.trashlist) + set([cscc.H.showtrash,cscc.H.trashui.ziptrash],'Enable','off'); + end + end +return + +%----------------------------------------------------------------------- +function detrashrow(obj, event_obj) +%----------------------------------------------------------------------- +% Removes a record from trash list and restores the old look like in the +% Ratio IQR/mean correlation plot. +%----------------------------------------------------------------------- + global cscc + + if isfield(cscc.pos,'y') && any( cscc.select.trashlist==cscc.pos.y ) + cscc.select.trashlist = setdiff(cscc.select.trashlist,cscc.pos.y); + cscc.select.trashhist = [cscc.select.trashhist -cscc.pos.y]; + + set(cscc.H.trashui.trashrow ,'Enable','on' ); + set(cscc.H.trashui.detrashrow,'Enable','off'); + + % update matrix + cscc.select.trash1d(cscc.pos.y) = 1; + cscc.select.trash2d(cscc.pos.y,:) = sum(cscc.select.trash2d,1)>0; + cscc.select.trash2d(:,cscc.pos.y) = sum(cscc.select.trash2d,2)>0; + + % update scatter + for scati=1:numel(cscc.H.scat) + sccscc.posx = findobj(cscc.H.scat(scati),'type','scatter'); + sccscc.posxv = cell2mat(get(sccscc.posx,'UserData')); + sccscc.posxi = find(sccscc.posxv==cscc.pos.y,1,'first'); + + marker = get(sccscc.posx(sccscc.posxi),'sizedatasource'); + if isempty(strfind(marker,'+o*.xsdv^>0 + % last element was added to the cscc.select.trashlist + detrash + cscc.select.trashlist(end) = []; + else + trash + cscc.select.trashlist(end+1) = cscc.select.trashhist(end); + end + cscc.select.trashhistf(end+1) = cscc.select.trashhist(end); + cscc.select.trashhist(end) = []; + + set(cscc.H.trashui.redo,'enable','on'); + if isempty(cscc.select.trashhist), set(cscc.H.trashui.undo,'enable','off'); end + + if exist('oldx','var') + cscc.pos.x = oldx; + else + cscc.pos = rmfield(cscc.pos,'x'); + end + if exist('oldy','var') + cscc.pos.y = oldy; + elseif isfield(cscc.pos,'y') + cscc.pos = rmfield(cscc.pos,'y'); + end + if exist('oldtar_mouseget','var') + cscc.pos.tar_mouseget = oldtar_mouseget; + elseif isfield(cscc.pos,'tar_mouseget') + cscc.pos = rmfield(cscc.pos,'tar_mouseget'); + end + if isempty(cscc.select.trashlist) + set([cscc.H.showtrash,cscc.H.trashui.ziptrash],'Enable','off'); + else + set([cscc.H.showtrash,cscc.H.trashui.ziptrash],'Enable','on'); + end +return + +%----------------------------------------------------------------------- +function trashredo(obj, event_obj) +%----------------------------------------------------------------------- +% List all records of the trash list in the command window. +%----------------------------------------------------------------------- + global cscc + + if isfield(cscc.pos,'x'), oldx = cscc.pos.x; end + if isfield(cscc.pos,'y'), oldy = cscc.pos.y; end + if isfield(cscc.pos,'tar_mouseget'), oldtar_mouseget = cscc.pos.tar_mouseget; end + cscc.pos.x = cscc.select.trashhistf(end); + + if isempty(cscc.select.trashlist) && cscc.select.trashhistf(end)<0 + detrash + cscc.select.trashlist(end) = []; + else + trash + cscc.select.trashlist(end+1) = cscc.select.trashhistf(end); + end + cscc.select.trashhist(end+1) = cscc.select.trashhistf(end); + cscc.select.trashhistf(end) = []; + + set(cscc.H.trashui.undo,'enable','on'); + if isempty(cscc.select.trashhistf), set(cscc.H.trashui.redo,'enable','off'); end + + if exist('oldx','var') + cscc.pos.x = oldx; + else + cscc.pos = rmfield(cscc.pos,'x'); + end + if exist('oldy','var') + cscc.pos.y = oldy; + elseif isfield(cscc.pos,'y') + cscc.pos = rmfield(cscc.pos,'y'); + end + if exist('oldtar_mouseget','var') + cscc.pos.tar_mouseget = oldtar_mouseget; + elseif isfield(cscc.pos,'tar_mouseget') + cscc.pos = rmfield(cscc.pos,'tar_mouseget'); + end + if isempty(cscc.select.trashlist) + set([cscc.H.showtrash,cscc.H.trashui.ziptrash],'Enable','off'); + else + set([cscc.H.showtrash,cscc.H.trashui.ziptrash],'Enable','on'); + end +return + +%----------------------------------------------------------------------- +function ziptrash(obj, event_obj) +%----------------------------------------------------------------------- +% Remove records and related files from the file system by zipping or +% storing in a separate directory (NOT READY). +%----------------------------------------------------------------------- + global cscc + + % dialog box with question to proceed + d = dialog('Position',cscc.pos.popup,'Name','Remove unfitting data',... + 'Position',[cscc.H.figure.Position(1:2) + cscc.H.figure.Position(3:4).*[1 0.7] - ... + cscc.pos.popup(3:4)/2 cscc.pos.popup(3:4)]); + uicontrol('Parent',d,'Style','text','Position',[20 60 160 20],... + 'String',{sprintf('Copy %d scans into trash directory!',numel(cscc.select.trashlist)),... + }); + uicontrol('Parent',d,'TooltipString','Stop operation!','selected','on',... + 'Position',[20 20 50 25],'String','No','Foregroundcolor',[ 0.8 0 0 ],... + 'Callback','delete(gcf);'); + uicontrol('Parent',d,'TooltipString','Go on!','selected','on',... + 'Position',[75 20 50 25],'String','Yes','Foregroundcolor',[ 0 0.6 0 ],... + 'Callback',@emptytrash); + uicontrol('Parent',d,'TooltipString','More information to this operation',... + 'Position',[130 20 50 25],'String','Help','Foregroundcolor',[ 0 0 0.8 ],... + 'Callback',['delete(gcf); spm_help(''!Disp'',fullfile(spm(''Dir''),''toolbox'... + ',''cat12'',''html'',''cat_tools_checkcov.html'','''',spm_figure(''GetWin'',''Graphics'')); ']); % +return + +%----------------------------------------------------------------------- +function emptytrash(obj, event_obj) +%----------------------------------------------------------------------- +% Remove records and related files from the file system by zipping or +% storing in a separate directory (NOT READY). +%----------------------------------------------------------------------- + global cscc + + close(get(obj,'Parent')) + set(cscc.H.figure,'Visible','off') + + testtrash = 0; + + % unique main trashsubdir + tid = char([48:57 65:90 97:122]); + newtrashdir = [datestr(clock,'yyyymmdd_HHMMSS') '_' ... + tid(floor( rand(1,6)*numel(tid-1) + 1))]; + newtrashfile = fullfile(cscc.trashdir,... + ['restore_' newtrashdir '.m']); + + % otherwise we go and by creating the new specific trash directory + try mkdir(fullfile(cscc.trashdir,newtrashdir)); end + + + %% trash + + + +%----------------------------------------------------------------------- +% open popup to avoid interaction +%----------------------------------------------------------------------- +%% + spm_figure('GetWin','Interactive'); + + if 0 + popup = dialog('Position',cscc.pos.popup,'Name','Remove unfitting data',... + 'Position',[cscc.H.figure.Position(1:2) + cscc.H.figure.Position(3:4).*[1 0.7] - ... + cscc.pos.popup(3:4)/2 cscc.pos.popup(3:4)]); + uicontrol('Parent',popup,'Style','text','Position',[20 30 160 40],... + 'String',{sprintf('Copy scans into trash directory!',numel(cscc.select.trashlist)),... + 'Do not interrupt!','This window close when finished.'}); + end + + %% + spm_progress_bar('Init',numel(cscc.select.trashlist),'Search related files','subjects completed') + spm_figure('GetWin','Interactive'); + for fi=1:numel(cscc.select.trashlist) + %% find preprocessed data and create data structure for store thrash + [pp,ff,ee] = spm_fileparts(cscc.files.org{cscc.select.trashlist(fi)}); + trash(fi).dir = pp; + trash(fi).fname = cscc.files.org{cscc.select.trashlist(fi)}; + trash(fi).MNC = cscc.data.mean_cov(cscc.select.trashlist(fi)); + trash(fi).IQRratio = cscc.data.IQRratio(cscc.select.trashlist(fi)); + try + trash(fi).IQR = cscc.data.QM(cscc.select.trashlist(fi),4); + trash(fi).PIQR = cscc.data.QM(cscc.select.trashlist(fi),5); + end + + + %% find related files + % -------------------------------------------------------------------- + % This is the most difficult part that has no perfect solution due to + % the different types how data could be stored (see also finding the + % original image). The are two major ways to store data (i) with no + % subdirectories or (ii) with many. In case of many directories, the + % filesname are possible identical and the subject specific + % information is stored in the directory names. Names could further + % include a pre and suffix with e.g. protocol information etc. + % 1) ../[pre][name][post].* + % 2) ../dir_1/../dir_n/t1.* + % + % Steps: + % 1) find all files that have include the original file name + % 2) remove files that include this name more than once, ie. in set + % of scans {""1.nii"", ""2.nii"", ... , ""11.nii"", ...} the file ""11"" + % is not a processed version of ""1"". + % 3) ... + % + % -------------------------------------------------------------------- + % 1) find all files with the main filename + trash(fi).sim_files = cat_vol_findfiles(pp,['*' ff '*.nii'],struct('maxdepth',1)); + % 2) find files that inlude the main filename more than once and remove them + trash(fi).sim_files0 = cat_vol_findfiles(pp,['*' ff '*' ff '*.nii'],struct('maxdepth',1)); + trash(fi).sim_files = setdiff(trash(fi).sim_files,trash(fi).sim_files0); + % 3) ... + trash(fi).sim_files = [fullfile(pp,[ff ee]); setdiff(trash(fi).sim_files, fullfile(pp,[ff ee]))]; + for si=1:numel(trash(fi).sim_files); + [pps,ffs] = spm_fileparts(trash(fi).sim_files{si}); + pp_files{si} = cat_vol_findfiles(pps,['*' ffs '*']); + pp_files0 = cat_vol_findfiles(pps,['*' ffs '*' ffs '*']); + pp_files{si} = setdiff(pp_files{si},pp_files0); + pp_files{si} = setdiff(pp_files{si},trash(fi).sim_files); + for fsi = numel(pp_files{si}):-1:1 + ppfs = spm_str_manip(pp_files{si}{fsi},'hht'); + switch ppfs + case 'err', pp_files{si}(fsi) = []; + end + end + pp_files{si} = setdiff(pp_files{si},trash(fi).sim_files{si}); + if si==1 + pp_filescor = pp_files{si}; + else + pp_filescor = setdiff(pp_filescor,pp_files{si}); + end + end + trash(fi).sim_files = [trash(fi).sim_files; pp_filescor]; + spm_progress_bar('Set',fi); + end + spm_progress_bar('Clear'); + + % replace leading path by the new trashdirectory + [tmp,grouphome] = spm_str_manip(cscc.files.fname.s,'C'); + for fi=1:numel(cscc.select.trashlist) + trash(fi).sim_filest = cat_io_strrep(trash(fi).sim_files,... + grouphome.s,fullfile(cscc.trashdir,[newtrashdir filesep])); + end + + + %% create restore script + + % start with some help + script = { + ['%% restore_' newtrashdir '.m'] + '% -------------------------------------------------------------------' + '% This is an automaticly generated script to restore files that were ' + '% previously removed in a quality control process based on the mean' + '% covariance (MNC) and the protocol image qualtiy rating (PIQR). The' + '% files are stored in the equaly named subdirectory and listed below.' + '% ------------------------------------------------------------------' + '% ' + ' ' + '%% List of scans: ' + '% ------------------------------------------------------------------' + '% Structure with the name of the removed scan, its mean covariance ' + '% (MNC), image quality rating (IQR), the protocol image qualtiy ' + '% rating (PIQR), IQRratio and file to file lists one ' + '% of the orinal files and one of the trashed files.' + '% ------------------------------------------------------------------' + }; + + % add a data structur that include major information especial the filelists + for fi=1:numel(cscc.select.trashlist) + script{end+1} = sprintf('scan(%d).fname = ''%s'';',fi,trash(fi).fname); + script{end+1} = sprintf('scan(%d).MNC = %0.4f;' ,fi,trash(fi).MNC ); + script{end+1} = sprintf('scan(%d).IQR = %0.2f;' ,fi,trash(fi).IQR ); + script{end+1} = sprintf('scan(%d).PIQR = %0.2f;' ,fi,trash(fi).PIQR ); + script{end+1} = sprintf('scan(%d).IQRratio = %0.2f;' ,fi,trash(fi).IQRratio ); + script{end+1} = sprintf('scan(%d).files = {',fi); + for fii=1:numel(trash(fi).sim_files) + if testtrash + script{end+1} = sprintf(' ''%s'';',cat_io_strrep(trash(fi).sim_files{fii},... + grouphome.s,fullfile(cscc.trashdir,['restore' filesep]))); + else + script{end+1} = sprintf(' ''%s'';',trash(fi).sim_files{fii}); + end + end + script{end+1} = ' };'; + script{end+1} = sprintf('scan(%d).tfiles = {',fi); + for fii=1:numel(trash(fi).sim_filest) + script{end+1} = sprintf(' ''%s'';',trash(fi).sim_filest{fii}); + end + script{end+1} = ' };'; + end + + +%% FUTURE DEVELOPMENT +% ------------------------------------------------------------------------ +% the idea is to add a GUI with a menu that allows do select different +% scans for restoring +%{ +script(end+1) = { +'' +'' % ask for type (1) 'restore all' (2) 'deside each by question' (3) 'deside each by id-area' +'' % sort by quality? +'' +%} +% ------------------------------------------------------------------------ + + + + % this part now describes the major operation for restore the previously + % defined filelists + script = [script;{ + '%% restore files' + '% ------------------------------------------------------------------' + ['fprintf(''Restore %d files of ' newtrashdir ':\\n'',numel(scan));'] + 'for si = 1:numel(scan)' + ' fprintf('' Restore ""%s"":'',scan(si).fname ); si_err=0;' + ' for i = 1:numel(scan(si).files)' + ' if exist(scan(si).tfiles{i},''file'') && ... ' + ' ~exist(scan(si).files{i},''file'')' + ' pp = spm_fileparts(scan(si).files{i});' + ' if ~exist(pp,''dir''), mkdir(pp); end' + ' movefile(scan(si).tfiles{i},scan(si).files{i});' + ' else' + ' % error message? ' + ' si_err = 1;' + ' end' + ' end' + ' if si_err' + ' cat_io_cprintf(''err'','' ERROR.\\n'');' + ' else' + ' cat_io_cprintf([0 0.8 0],'' OK.\\n'');' + ' end' + 'end' + '' + ['cat_io_rmdir(''' fullfile(cscc.trashdir,newtrashdir) ''')'] + '' + '% ------------------------------------------------------------------' + '% end of script' + }]; + + + % save the final script + fid = fopen(newtrashfile,'w'); + for li=1:numel(script), fprintf(fid,[strrep(script{li},'%','%%') '\n']); end + fclose(fid); + + + %% + spm_progress_bar('Init',numel(cscc.select.trashlist),'Trash related files','subjects completed') + spm_figure('GetWin','Interactive'); + for fi=1:numel(cscc.select.trashlist) + for fii=1:numel(trash(fi).sim_files) + fprintf(' Trash: %s\n',trash(fi).fname) + pp = spm_fileparts(trash(fi).sim_filest{fii}); + if ~exist(pp,'dir'), mkdir(pp); end + if testtrash + copyfile(trash(fi).sim_files{fii},trash(fi).sim_filest{fii}); + else + movefile(trash(fi).sim_files{fii},trash(fi).sim_filest{fii}); + end + end + + %% zip the list and remove the files + % we need to go into the directory and use the short filenames + % to opbtain save the relative path in the zip file! + if 0 + pp_filescor1 = cat_io_strrep(pp_filescor,[pp filesep],''); + ffzip = fullfile(pp,sprintf('%s_cor%2.2f_IQR%2.2f_trashed%s',... + ff,cscc.data.X(cscc.select.trashlist(fi),1),... + cscc.data.QM(cscc.select.trashlist(fi),3),trashtime)); + zip(ffzip,pp_filescor1,pp); + for fii=1:numel(pp_filescor1), delete(pp_filescor1{fii}); end + end + + spm_progress_bar('Set',fi); + end + spm_progress_bar('Clear'); + +% close popup +%delete(popup); + + + %% + for fi=1:numel(trash) + cat_io_rmdir(trash(fi).dir) + end + + %% restore cat_stat_check_cov with updated filelist + job2 = cscc.job; + for fi = sort(cscc.select.trashlist,'descend') + job2.(cscc.files.datafield){cscc.files.dataid(fi,2)}(cscc.files.dataid(fi,3)) = []; + if ~isempty(job2.data_xml) && numel(job2.data_xml)>fi + job2.data_xml(fi) = []; + end + if ~isempty(job2.c) + for ci=1:numel(job2.c) + job2.c{ci}(fi) = []; + end + end + end + + cat_stat_check_cov2(job2); +return + +%----------------------------------------------------------------------- +function closeWindows(obj, event_obj) +%----------------------------------------------------------------------- +% Close all windows and remove variables. +%----------------------------------------------------------------------- + global cscc + + if strcmp( event_obj.Source.Type , 'figure') + cscc.posx = get(event_obj.Source,'Position'); + else + cscc.posx = get(get(event_obj.Source,'Parent'),'Position'); + end + cscc.pos.popup(1:2) = [cscc.posx(1) + cscc.posx(3)*0.8, cscc.posx(1) + cscc.posx(4)*0.9]; + + if isfield(cscc,'select') && isfield(cscc.select,'trashlist') && ~isempty(cscc.select.trashlist) + d = dialog('Position',cscc.pos.popup,'Name','Close Checkcov'); + uicontrol('Parent',d,'Style','text','Position',[20 60 160 20],... + 'String','Trashlist not empty!'); + uicontrol('Parent',d,'TooltipString','Sopt closing',... + 'Position',[25 20 70 25],'String','Cancel','Callback','delete(gcf)'); + uicontrol('Parent',d,'TooltipString','Close windows without last changes',... + 'Position',[100 20 70 25],'String','Close','ForegroundColor',[0.8 0 0],... + 'Callback',[ % see standard closing in else case + 'global scss;'... + 'set(cscc.H.graphics,''Color'',[1 1 1]);' ... + 'spm_figure(''Clear'',cscc.H.graphics); ' ... + 'set(cscc.H.graphics,''Position'',cscc.display.WP); ' ... + 'for i=3:26, try close(i); end; end;' ... + 'clearvars -GLOBAL cscc;']); + else + % clear SPM graphics window + try set(cscc.H.graphics,'Color',[1 1 1]); end + try + spm_figure('Clear',cscc.H.graphics); + set(cscc.H.graphics,'Position',cscc.display.WP); + catch + try + spm_figure('Clear',spm_figure('FindWin','Graphics')); + set(spm_figure('FindWin','Graphics'),'Position',cscc.display.WP); + end + end + + % clear other surface window figures + for i=3:26, try close(i); end; end; + delete(gcbf); % remove figure with closerequest + + % clear vars + clearvars -GLOBAL cscc; + end +return + +%----------------------------------------------------------------------- +function id = mygetCursorInfo +%----------------------------------------------------------------------- +% +%----------------------------------------------------------------------- + global cscc + + curs = cscc.H.dcm.getCursorInfo; + + if cscc.H.isscatter + sc = unique([curs(:).Target]); + id = get(sc,'UserData')'; + if iscell(id), id = cell2mat(id); end + else + id = unique([cscc.pos.x, cscc.pos.y]); + %{ + cscc.pos = reshape([curs(:).Position],numel(curs),2); + cscc.posx = unique(cscc.pos(:,1)); + cscc.posy = unique(cscc.pos(:,2)); + + if cscc.H.sorted + + else + + end + %} + end + +return + +%----------------------------------------------------------------------- +function checkpdf(obj, event_obj) +%----------------------------------------------------------------------- +% Open PDF report of selected subjects. +% This is only possible for using an extern viewer. +% Hence, it would be useful to save a JPG or HTML file in cat_main. +%----------------------------------------------------------------------- + global cscc + + id = mygetCursorInfo; + if all(~cellfun('isempty',cscc.files.jpg(id))) || numel(id)>2 + %% + spm_figure('Clear',cscc.H.graphics); + spm_figure('Focus',cscc.H.graphics); + + if cscc.H.isscatter || cscc.pos.x == cscc.pos.y + ppos = [0 0 1 1]; + jpg = imread(cscc.files.jpg{cscc.pos.x}); + set(gca,'position',ppos(1,:)); + gpos = cscc.H.graphics.Position; + [Xq,Yq] = meshgrid(1:size(jpg,2)/gpos(3)/2:size(jpg,2),... + 1:size(jpg,1)/gpos(4)/2:size(jpg,1)); + jpgi = zeros([size(Xq,1) size(Xq,2) 3],'uint8'); + for i=1:3, jpgi(:,:,i) = uint8(interp2(single(jpg(:,:,i)),Xq,Yq,'linear')); end + image(cscc.H.graphics.CurrentAxes,jpgi); + set(gca,'Visible','off'); + else + ppos = [0.0 0.502 1.0 0.498 ; 0.0 0.0 1.0 0.498]; + jpg = {imread(cscc.files.jpg{cscc.pos.x});imread(cscc.files.jpg{cscc.pos.y})}; + for fi=1:2 + ax(fi) = subplot(2,1,fi); + set(ax(fi),'position',ppos(fi,:)); + gpos = cscc.H.graphics.Position; + [Xq,Yq] = meshgrid(1:size(jpg{fi},2)/gpos(3)/2:size(jpg{fi},2),... + 1:size(jpg{fi},1)/gpos(4)/2:size(jpg{fi},1)); + jpgi = zeros([size(Xq,1) size(Xq,2) 3],'uint8'); + for i=1:3, jpgi(:,:,i) = uint8(interp2(single(jpg{fi}(:,:,i)),Xq,Yq,'linear')); end + image(cscc.H.graphics.CurrentAxes,jpgi); + set(gca,'Visible','off'); axis equal tight; zoom(2); axis fill + end + pan yon + linkaxes(ax) + end + else + for i=1:numel(id), open(cscc.files.pdf{id(i)}); end + end +return + +%----------------------------------------------------------------------- +function checksurf(obj, event_obj) +%----------------------------------------------------------------------- +% Open surface files of selected subjects. +% This is very slow and some feedback would be useful. +%----------------------------------------------------------------------- + global cscc + + spm_progress_bar('Init',2 - cscc.H.isscatter,'Load surfaces','subjects completed') + if cscc.H.isscatter + h = cat_surf_display(struct('data',cscc.files.surf{cscc.pos.x},'multisurf',1)); + h.Position(1:2) = cscc.H.graphics.Position .* [1.05 0.95]; + else + h = cat_surf_display(struct('data',char(cscc.files.surf(unique([cscc.pos.x,cscc.pos.y]))),'multisurf',1)); + end + spm_progress_bar('Clear'); + + % give some feedback because loading take so long +return + +%----------------------------------------------------------------------- +function checkvol(obj, event_obj) +%----------------------------------------------------------------------- +% Load the original image of selected files in SPM graphics window. +% Some further information or legend would be helpful. +%----------------------------------------------------------------------- + global cscc st + + spm_figure('Clear',cscc.H.graphics); + spm_figure('Focus',cscc.H.graphics); + spm_orthviews('Reset') + [zl,rl] = spm_orthviews('ZoomMenu'); + if size(zl,1) > 1 + zl = zl'; + rl = rl'; + end + if numel(zl)==8 + zl = [zl(1:end-2) 60 zl(end-1:end)]; + rl = [rl(1:end-2) 1 rl(end-1:end)]; + end + spm_orthviews('ZoomMenu',zl,rl); + job.colormapc = flipud(cat_io_colormaps('BCGWHcheckcov')); + job.prop = 0.2; + + %% + cscc.H.multi = 1; + if cscc.H.isscatter + xeqy = 0; + + if cscc.H.multi + id = mygetCursorInfo'; + + spm_check_registration(char(unique(cscc.files.org(id)))); + + + if exist(cscc.files.p0{cscc.pos.x},'file') + spm_orthviews('addtruecolourimage',1,cscc.files.p0{cscc.pos.x},... + job.colormapc,job.prop,0,5); + end + + vx_vol = sqrt(sum(st.vols{1}.mat(1:3,1:3).^2)); + Ysrc = cat_vol_resize(st.vols{1}.private.dat,'reduceV',vx_vol,vx_vol * 2,2,'meanm'); + [Ysrc,th] = cat_stat_histth(Ysrc,99); + spm_orthviews('window',1,th + [ 0.1*-diff(th) 0.3*diff(th)] ); + + else + ppos = [0.02 0.01 0.96 0.98]; + tpos = [0.50 0.98 0.96 0.02]; + end + else + xeqy = cscc.pos.x == cscc.pos.y; + + if xeqy + ppos = [0.02 0.01 0.96 0.98]; + tpos = [0.50 0.98 0.96 0.02]; + else + ppos = [0.02 0.545 0.96 0.48 ; 0.02 0.010 0.96 0.48]; + tpos = [0.50 0.980 0.96 0.02 ; 0.50 0.475 0.96 0.02]; + end + end + + + if ~cscc.H.isscatter || ~cscc.H.multi || xeqy + + hi1 = spm_orthviews('Image',spm_vol(cscc.files.org{cscc.pos.x}),ppos(1,:)); + spm_orthviews('AddContext',hi1); + + gax = axes('Visible','off','Position',[0 0 1 1]); + text(gax,tpos(1,1),tpos(1,2),spm_str_manip(cscc.files.org{cscc.pos.x},'k100'),... + 'FontSize',cscc.display.FS(cscc.display.FSi+1),'Color',[0 0 0.8],'LineStyle','none',... + 'HorizontalAlignment','center'); + + if exist(cscc.files.p0{cscc.pos.x},'file') + spm_orthviews('addtruecolourimage',1,cscc.files.p0{cscc.pos.x},... + job.colormapc,job.prop,0,5); + end + end + + if ~cscc.H.isscatter && ~xeqy + + hi2 = spm_orthviews('Image',spm_vol(cscc.files.org{cscc.pos.y}),ppos(2,:)); + spm_orthviews('AddContext',hi2); + + gax = axes('Visible','off','Position',[0 0 1 1]); + text(gax,tpos(1,1),tpos(2,2),spm_str_manip(cscc.files.org{cscc.pos.y},'k100'),... + 'FontSize',cscc.display.FS(cscc.display.FSi+1),'Color',[0 0 0.8],'LineStyle','none',... + 'HorizontalAlignment','center'); + + if exist(cscc.files.p0{cscc.pos.y},'file') + spm_orthviews('addtruecolourimage',2,cscc.files.p0{cscc.pos.y},... + job.colormapc,job.prop,0,5); + end + + end + spm_orthviews('Reposition',[0 0 0]); + spm_orthviews('Zoom',120) + + spm_orthviews('redraw'); +return + +%----------------------------------------------------------------------- +function check_worst_data(obj, event_obj) +%----------------------------------------------------------------------- +% Old check worst function. The spm_input could be replaced by an popup +% window. A specification of the data range would rather than the x worst +% images would be useful. +%----------------------------------------------------------------------- + + global cscc bp + + if isempty(spm_figure('FindWin','Interactive')), spm('createintwin'); end + + if isempty(bp) + data = cscc.data.V; + name = 'Mean correlation'; + else + data = bp.data; + name = bp.name; + end + switch deblank(name) + case 'Noise rating (NCR)', name = 'NCR'; + case 'Bias rating (ICR)', name = 'ICR'; + case 'Resoution rating (RES)', name = 'RES'; + case 'Weighted overall image quality rating (IQR)', name = 'IQR'; + case 'Euler number', name = 'Euler'; + case 'Size of topology defects (TDS)', name = 'TDS'; + case 'Mean correlation', name = 'MNC'; + case 'Protocol-based IQR (PIQR)', name = 'PIQR'; + case 'Norm. Ratio IQR/mean correlation', name = 'IQRratio'; + case 'Norm. Ratio PIQR/mean correlation',name = 'PIQRratio'; + end + if ~cscc.H.showtrash.Value + data = setdiff(data,cscc.select.trashlist); + end + [sdata,order] = sort(data,'descend'); + + + n = numel(data); + number = min([n 24]); + number = spm_input('How many files?',1,'e',number); + number = max([number 1]); + number = min([number 24]); + number = min([number n]); + + sdata = sdata(n:-1:1); + list = cellstr(char(cscc.data.V(order(n:-1:1)).fname)); + list2 = list(1:number); + + if cscc.H.mesh_detected + % display single meshes and correct colorscale of colorbar + for i=1:number + h = cat_surf_render('Disp',deblank(list2(i,:))); + + % shift each figure slightly + if i==1 + pos = get(h.figure,'Position'); + else + pos = pos - [20 20 0 0]; + end + + % remove menubar and toolbar, use filename as title + set(h.figure,'MenuBar','none','Toolbar','none',... + 'Name',spm_file(list2{i},'short50'),... + 'NumberTitle','off','Position',pos); + cat_surf_render('ColourMap',h.axis,jet); + cat_surf_render('ColourBar',h.axis,'on'); + cat_surf_render('CLim',h,[mn_data mx_data]); + end + else + % break the filename into smaller pieces to display it close to the figure + [fnames0,fnames] = spm_str_manip(list2,'C'); + if isempty(fnames) + fnames.m = list2; + fnames.s = ''; + end + for fi=1:numel(fnames.m) + if ~isempty(fnames.s) && numel(spm_str_manip(fnames.m{fi},'H'))>1 + fnames.m{fi} = ['.' filesep fnames.m{fi}]; + end + pp = spm_str_manip(fnames.m{fi},'Hl199'); pp(end+1) = filesep; + ff = spm_str_manip(fnames.m{fi},'t'); + + ssep = round(70 ./ sqrt(numel(fnames.m))); + lpp = round( ceil( numel(pp)/(ssep/2) ) * (ssep/2) ); + lff = round( ceil( numel(ff)/(ssep/2) ) * (ssep/2) ); + lpp = lpp:-ssep:1; lpp(lpp>numel(pp)) = []; + lff = lff:-ssep:1; lff(lff>numel(ff)) = []; + for pi = lpp, pp = sprintf('%s\n%s',pp(1:pi),pp(pi+1:end)); end + for pi = lff, ff = sprintf('%s\n%s',ff(1:pi),ff(pi+1:end)); end + + % some values + val = sprintf('%s=%0.2f',name,sdata(fi)); + + if numel(pp)>7 + list3{fi} = sprintf('%s\n%s\n%s',val,pp,ff); + else + list3{fi} = sprintf('%s\n%s%s',val,pp,ff); + end + end + + % + spm_check_registration(char(list2)); + + % add caption + for fi=1:numel(fnames.m); + spm_orthviews('Caption',fi,list3{fi},... + 'FontSize',cscc.display.FS(cscc.display.FSi-1)); + end + spm_orthviews('Resolution',0.2); + set(cscc.H.boxp,'Visible','on'); + end + + figure(cscc.H.figure); +return + +%----------------------------------------------------------------------- +function checkxml(obj, event_obj) +%----------------------------------------------------------------------- +% Load XML report in SPM graphics window (see also checklog). +% This is just the first fast version of this function. +% Finally, I want to use the xml structure from the file to print some +% specific information similar to the CAT report in cat_main. +%----------------------------------------------------------------------- + global cscc + + % visdiff(cscc.files.xml{cscc.pos.x}, cscc.files.xml{cscc.pos.y},'text') + + spm_figure('Clear',cscc.H.graphics); + spm_figure('Focus',cscc.H.graphics); + axis off; + + if cscc.H.isscatter || (cscc.pos.x == cscc.pos.y) + textbox = [0 0 1 1]; + files = cscc.files.xml(cscc.pos.x); + else + textbox = [0 0.5 1 0.5; 0 0 1 0.5]; + files = cscc.files.xml([cscc.pos.y,cscc.pos.x]); + end + + % avoid some long useless text passages + badtacks = {'software>','catlog>','H.data>','LAB>'}; + badmode = 0; bdid = badtacks; + for fi=1:numel(files); + fid = fopen(files{fi}); + ph = uipanel(cscc.H.graphics,'Units','normalized','position',textbox(fi,:), ... + 'BorderWidth',0,'title',[spm_str_manip(files{fi},'k100') ' (extract)'],'ForegroundColor',[0 0 0.8]); + lbh = uicontrol(ph,'style','listbox','Units','normalized',... + 'fontname','Fixedwidth','position',[ 0 0 1 1 ],'FontSize',9); + indic = 1; + indit = 1; + while 1 + tline = fgetl(fid); + if ~ischar(tline), + break + end + for bi = 1:numel(badtacks), bdid{bi} = strfind(tline,badtacks{bi}); end + if any(~cellfun('isempty',bdid)) + badmode = ~badmode; + end + if ~badmode + strings{indit}=tline; + indit = indit + 1; + end + indic = indic + 1; + end + fclose(fid); + + set(lbh,'string',strings); + set(lbh,'Value',1); + set(lbh,'Selected','on'); + end +return + +%----------------------------------------------------------------------- +function show_sample(obj,event_obj) +%----------------------------------------------------------------------- +% Function to control the visibility of the samples in the main plots. +% See also show_protocol. +%----------------------------------------------------------------------- + + global cscc + + % set entry of the GUI element + if exist('obj','var') + if obj>0 + set(cscc.H.samp,'Value',obj + 2); + cscc.select.samp1d(:) = cscc.datagroups.sample==obj; + else + set(cscc.H.samp,'Value',1); + cscc.select.samp1d(:) = true(size(cscc.select.samp1d)); + end + else + obj = get(cscc.H.samp,'Value') - 2; + if obj>0 + cscc.select.samp1d(:) = cscc.datagroups.sample==obj; + else + cscc.select.samp1d(:) = true(size(cscc.select.samp1d)); + end + end + + cscc.select.samp2d = (single(cscc.select.samp1d) * single(cscc.select.samp1d'))>0; + + groups = unique(cscc.datagroups.sample); + symbols = repmat('.',1,numel(groups)); % default symbol + symbols(1:11) = 'o+^v<>ph*sd'; + + % update scatter + if cscc.H.isscatter + if 0 %obj>0 + % find all (also deleted) scatter points of the active scatter plot + sc.pos = [ + findobj(cscc.H.scat(cscc.H.scata),'type','scatter','marker',symbols(obj)); + findobj(cscc.H.scat(cscc.H.scata),'type','scatter','sizedatasource',symbols(obj))]; + else + sc.pos = findobj(cscc.H.scat(cscc.H.scata),'type','scatter'); + end + sc.posn = findobj(cscc.H.scat(cscc.H.scata),'type','scatter'); + + % remove legend objects + sc.pos = setdiff(sc.pos ,[cscc.H.sclegend{cscc.H.scata}]); + sc.posn = setdiff(sc.posn,[cscc.H.sclegend{cscc.H.scata}]); + + % remove objects without ID + sc.pos( cellfun('isempty',{sc.pos.UserData}) ) = []; + sc.posn( cellfun('isempty',{sc.posn.UserData}) ) = []; + + %% remove inactive protocols / samples + [pset,pseti] = setdiff( [sc.pos.UserData] , find( cscc.select.prot1d==0 ) ); sc.pos = sc.pos( pseti ); + [pset,pseti] = setdiff( [sc.pos.UserData] , find( cscc.select.samp1d==0 ) ); sc.pos = sc.pos( pseti ); + + % + sc.posn = setdiff(sc.posn,sc.pos); + + % remove trashed objects + if ~cscc.H.showtrash.Value && ~isempty(sc.pos) + sc.pos(strcmp({sc.pos.ZDataSource},'trash'))=[]; + end + + set(sc.pos ,'Visible','on'); + set(sc.posn,'Visible','off'); + + + for linei=1:numel(cscc.H.corrline{cscc.H.scata}) + indxy = get(cscc.H.corrline{cscc.H.scata}(linei),'UserData'); + if any(indxy(1) == [sc.pos.UserData]) && any(indxy(2) == [sc.pos.UserData]) + set(cscc.H.corrline{cscc.H.scata}(linei),'Visible','on'); + else + set(cscc.H.corrline{cscc.H.scata}(linei),'Visible','off'); + end + end + + xlim(cscc.H.scat(cscc.H.scata),'auto'); + xticks = get(cscc.H.scat(cscc.H.scata),'xtick'); + xlim([xticks(1) - diff(xticks(1:2)/2) xticks(end) + diff(xticks(1:2)/2)]); + + ylim(cscc.H.scat(cscc.H.scata),'auto'); + yticks = get(cscc.H.scat(cscc.H.scata),'ytick'); + ylim([yticks(1) - diff(yticks(1:2)/2) yticks(end) + diff(yticks(1:2)/2)]); + + zoom(cscc.H.scat(cscc.H.scata),'reset'); + else + update_matrix + end + + cscc.H.dcm.removeAllDataCursors +return + +%----------------------------------------------------------------------- +function show_protocol(obj,event_obj) +%----------------------------------------------------------------------- +% Function to control the visibility of protocols in the main plots. +% See also show_sample. +%----------------------------------------------------------------------- + + global cscc + + % set GUI element entry + if exist('obj','var') + if obj>0 + set(cscc.H.prot,'Value',obj + 2); + cscc.select.prot1d(:) = cscc.datagroups.protocol==obj; + else + set(cscc.H.prot,'Value',1); + cscc.select.prot1d(:) = true(size(cscc.select.prot1d)); + end + else + obj = get(cscc.H.prot,'Value') - 2; + if obj>0 + cscc.select.prot1d(:) = cscc.datagroups.protocol==obj; + else + cscc.select.prot1d(:) = true(size(cscc.select.prot1d)); + end + end + + cscc.select.prot2d = (single(cscc.select.prot1d) * single(cscc.select.prot1d'))>0; + + % update scatter + if cscc.H.isscatter + if obj>0 + % find all (also deleted) scatter points of the active scatter plot + sc.pos = findobj(cscc.H.scat(cscc.H.scata),'type','scatter','ZDataSource',num2str(obj,'%d')); + else + sc.pos = findobj(cscc.H.scat(cscc.H.scata),'type','scatter'); + end + sc.posn = findobj(cscc.H.scat(cscc.H.scata),'type','scatter'); + + % remove legend objects + sc.pos = setdiff(sc.pos ,[cscc.H.sclegend{cscc.H.scata}]); + sc.posn = setdiff(sc.posn,[cscc.H.sclegend{cscc.H.scata}]); + + sc.posn( cellfun('isempty',{sc.posn.UserData}) ) = []; + if ~isempty(sc.pos) + % remove objects without ID + sc.pos( cellfun('isempty',{sc.pos.UserData}) ) = []; + + % remove inactive protocols / samples + [pset,pseti] = setdiff( [sc.pos.UserData] , find( cscc.select.prot1d==0 )); sc.pos = sc.pos( pseti ); + + [pset,pseti] = setdiff( [sc.pos.UserData] , find( cscc.select.samp1d==0 )); sc.pos = sc.pos( pseti ); + end + + sc.posn = setdiff(sc.posn,sc.pos); + + if ~cscc.H.showtrash.Value && ~isempty(sc.pos) + sc.pos(strcmp({sc.pos.ZDataSource},'trash'))=[]; + end + + set(sc.pos ,'Visible','on'); + set(sc.posn,'Visible','off'); + + % remove lines if not both points are visible + for linei=1:numel(cscc.H.corrline{cscc.H.scata}) + indxy = get(cscc.H.corrline{cscc.H.scata}(linei),'UserData'); + + if ~isempty(sc.pos) && ... + (any(indxy(1) == [sc.pos.UserData]) && any(indxy(2) == [sc.pos.UserData])) + set(cscc.H.corrline{cscc.H.scata}(linei),'Visible','on'); + else + set(cscc.H.corrline{cscc.H.scata}(linei),'Visible','off'); + end + end + + + xlim(cscc.H.scat(cscc.H.scata),'auto'); + xticks = get(cscc.H.scat(cscc.H.scata),'xtick'); + xlim([xticks(1) - diff(xticks(1:2)/2) xticks(end) + diff(xticks(1:2)/2)]); + + ylim(cscc.H.scat(cscc.H.scata),'auto'); + yticks = get(cscc.H.scat(cscc.H.scata),'ytick'); + ylim([yticks(1) - diff(yticks(1:2)/2) yticks(end) + diff(yticks(1:2)/2)]); + + zoom(cscc.H.scat(cscc.H.scata),'reset'); + else + update_matrix + end + + cscc.H.dcm.removeAllDataCursors +return + +%----------------------------------------------------------------------- +function checklog(obj, event_obj) +%----------------------------------------------------------------------- +% Load the log-file from cat_main of the selected subjects into the SPM +% graphics window. +%----------------------------------------------------------------------- + global cscc + + spm_figure('Clear',cscc.H.graphics); + spm_figure('Focus',cscc.H.graphics); + axis off; + + if cscc.H.isscatter || (cscc.pos.x == cscc.pos.y) + textbox = [0 0 1 1]; + files = cscc.files.log(cscc.pos.x); + else + textbox = [0 0.5 1 0.5; 0 0 1 0.5]; + files = cscc.files.log([cscc.pos.x,cscc.pos.y]); + end + + for fi=1:numel(files); + fid = fopen(files{fi}); + ph = uipanel(cscc.H.graphics,'Units','normalized','position',textbox(fi,:), ... + 'BorderWidth',0,'title',spm_str_manip(files{fi},'k100'),'ForegroundColor',[0 0 0.8]); + lbh = uicontrol(ph,'style','listbox','Units','normalized',... + 'fontname','Fixedwidth','position',[ 0 0 1 1 ],'FontSize',9); + indic = 1; + while 1 + tline = fgetl(fid); + if ~ischar(tline), + break + end + strings{indic}=tline; + indic = indic + 1; + end + fclose(fid); + set(lbh,'string',strings); + set(lbh,'Value',1); + set(lbh,'Selected','on'); + end +return + +%----------------------------------------------------------------------- +function checkbox_showtrash(obj, event_obj) +%----------------------------------------------------------------------- + global oldx oldy + global cscc + + showtrash = get(cscc.H.showtrash,'Value'); + + if ~showtrash + if isfield(cscc.pos,'x'), oldx = cscc.pos.x; else oldx = 0; end + if isfield(cscc.pos,'y'), oldy = cscc.pos.y; else oldy = 0; end + else + if oldx>0, cscc.pos.x = oldx; end + if oldy>0, cscc.pos.y = oldy; end + end + cscc.H.dcm.removeAllDataCursors; + set(cscc.H.slice,'visible','off'); + + if ~showtrash + if ~cscc.H.isscatter + if isfield(cscc.pos,'x'), cscc.pos = rmfield(cscc.pos,'x'); end + if isfield(cscc.pos,'y'), cscc.pos = rmfield(cscc.pos,'y'); end + cscc.H.dcm.removeAllDataCursors; + end + end + + if cscc.H.isscatter + sc.pos = findobj(cscc.H.scat(cscc.H.scata),'type','scatter','ZDataSource','trash'); + + if ~showtrash + set(sc.pos,'visible','off'); + else + set(sc.pos,'visible','on'); + end + + % remove lines if not both points are visible + for linei=1:numel(cscc.H.corrline{cscc.H.scata}) + indxy = get(cscc.H.corrline{cscc.H.scata}(linei),'UserData'); + + if ~isempty(sc.pos) && ~showtrash && ... + (any(indxy(1) == [sc.pos.UserData]) || any(indxy(2) == [sc.pos.UserData])) + set(cscc.H.corrline{cscc.H.scata}(linei),'Visible','off'); + else + set(cscc.H.corrline{cscc.H.scata}(linei),'Visible','on'); + end + end + + + xlim(cscc.H.scat(cscc.H.scata),'auto'); + xticks = get(cscc.H.scat(cscc.H.scata),'xtick'); + xlim([xticks(1) - diff(xticks(1:2)/2) xticks(end) + diff(xticks(1:2)/2)]); + + ylim(cscc.H.scat(cscc.H.scata),'auto'); + yticks = get(cscc.H.scat(cscc.H.scata),'ytick'); + ylim([yticks(1) - diff(yticks(1:2)/2) yticks(end) + diff(yticks(1:2)/2)]); + + zoom(cscc.H.scat(cscc.H.scata),'reset'); + else + update_matrix; + end + + %{ + if showtrash + %createDatatip(cscc.H.dcm,get(cscc.H.corr,'children'),[oldx oldy]); + else + %createDatatip(cscc.H.dcm,get(cscc.H.corr,'children'),[oldx oldy]); + end + %} +return + +%{ +%----------------------------------------------------------------------- +function checkbox_cbarfix(obj, event_obj) +%----------------------------------------------------------------------- + global cscc + + if cscc.H.isscatter + % do something + else + update_matrix; + end + +return +%} + +%----------------------------------------------------------------------- +function show_IQRratio(X,IQRratio,scata) +%----------------------------------------------------------------------- + global cscc + + if ~exist('scata','var') + if isfield(cscc.H,'scata') + scata = cscc.H.scata; + else + scata = 1; cscc.H.scata = scata; + end + else + cscc.H.scata = scata; + end + axis(cscc.H.scat(cscc.H.scata)); + + + + if ~cscc.H.isscatter + set([cscc.H.corr,get(cscc.H.corr,'children')],'visible','off','HitTest','off','Interruptible','off') + if isfield(cscc.H,'cbarfix') && ishandle(cscc.H.cbarfix), set(cscc.H.cbarfix ,'enable' ,'off'); end + if isfield(cscc.H,'showtrash') && ishandle(cscc.H.showtrash), set(cscc.H.showtrash,'Value' ,1); end + + % remove sliders and text + if isfield(cscc.pos,'tar_mouse') + delete(cscc.pos.tar_mouse); + cscc.pos = rmfield(cscc.pos,'tar_mouse'); + set(cscc.H.alphabox,'Visible','off'); + + if isfield(cscc.pos,'x'), cscc.pos = rmfield(cscc.pos,'x'); end + if isfield(cscc.pos,'y'), cscc.pos = rmfield(cscc.pos,'y'); end + + if isfield(cscc.H,'slice') && ishandle(cscc.H.slice) + set(cscc.H.slice,'Visible','off'); cla(cscc.H.slice); + end + if isfield(cscc.H,'sslider') && ishandle(cscc.H.sslider) + set(cscc.H.sslider,'Visible','off'); + end + if isfield(cscc.H,'alphabox') && ishandle(cscc.H.alphabox) + set(cscc.H.alphabox,'Visible','off'); + end + if isfield(cscc.H,'mm') && ishandle(cscc.H.mm), + set([cscc.H.mm,cscc.H.mm_txt],'Visible','off'); + end + + if ~cscc.H.mesh_detected + set([cscc.H.mm,cscc.H.mm_txt],'Visible','off'); + end + end + + set([cscc.H.trashui.trash,cscc.H.trashui.detrash,... + cscc.H.trashui.trashcol,cscc.H.trashui.detrashcol,... + cscc.H.trashui.trashrow,cscc.H.trashui.detrashrow],'Visible','off','Enable','off'); + set([cscc.H.trashui.trash,cscc.H.trashui.detrash],'Visible','on'); + + unit = struct2cell(cscc.H.checkui); set([unit{:}],'Enable','off'); + + end + + for i=setdiff(1:numel(cscc.H.scat),cscc.H.scata) + set([cscc.H.scat(i);get(cscc.H.scat(i),'Children')],... + 'visible','off','HitTest','off','Interruptible','off'); + end + set([cscc.H.scat(cscc.H.scata);get(cscc.H.scat(cscc.H.scata),'children')],... + 'visible','on','HitTest','on','Interruptible','on'); + try set([cscc.H.sclegend{:}],'visible','off'); end + set(findobj('type','Legend'),'visible','on'); + + if isempty(get(cscc.H.scat(cscc.H.scata),'children')) + % get very similar scans + cscc.data.YpY_tmp = cscc.data.YpY - tril(cscc.data.YpY); + [indx, indy] = find(cscc.data.YpY_tmp>0.925); + + groups = unique(cscc.datagroups.sample); + symbols = repmat('.',1,numel(groups)); % default symbol + symbols(1:11) = 'o+^v<>ph*sd'; % need x for unset + + %% Create legend by creation of hidden dummy objects + % display first object for the legend + hold(cscc.H.scat(cscc.H.scata),'on'); + for gi=1:numel(groups) + txt{gi} = sprintf('sample %d \n',gi); + Xt = cscc.data.X(cscc.datagroups.sample==groups(gi),:); + cscc.H.sclegend{scata}(gi) = scatter(cscc.H.scat(cscc.H.scata),... + Xt(1,1),Xt(1,2),30,[0 0 0],symbols(gi),'Linewidth',2); + if ~isempty( strfind('osd^v<>ph', symbols(gi) ) ) + set(cscc.H.sclegend{scata}(gi),'MarkerFaceColor','flat','markerFaceAlpha',1/3); + end + end + txt{end+1} = 'excluded'; + cscc.H.sclegend{scata}(gi+1) = scatter(cscc.H.scat(cscc.H.scata),... + Xt(1,1),Xt(1,2),30,[1 0 0],'x','Linewidth',2,'Visible','off'); + if numel(indx)/size(cscc.data.YpY,1)<0.5 && numel(indx)>0 + txt{end+1} = 'highly corr. scans'; + cscc.H.sclegend{scata}(gi+2) = plot(cscc.H.scat(cscc.H.scata),... + [cscc.data.X(indx(1),1);cscc.data.X(indy(1),1)],... + [cscc.data.X(indx(1),2);cscc.data.X(indy(1),2)],'Color',[0 0 0],'Linewidth',2); + end + % create legend + hl = legend(cscc.H.scat(cscc.H.scata),txt,'location','southwest'); + set(get(hl,'title'),'string','Legend'); + hold(cscc.H.scat(cscc.H.scata),'off'); + set([cscc.H.sclegend{scata}],'visible','off'); + + + %% + %cscc.data.X(isnan(cscc.data.X)) = 0; + %S = cov(cscc.data.X); + % mu = mean(cscc.data.X); + % cscc.data.IQRratio = (cscc.data.X-repmat(mu,[size(cscc.data.X,1),1]))*inv(S)*(cscc.data.X-repmat(mu,[numel(cscc.data.X),1]))'; + % cscc.data.IQRratio = diag(cscc.data.IQRratio); + + % because we use a splitted colormap we have to set the color values explicitely + IQRratios = 63*(IQRratio-min(IQRratio))/(max(IQRratio)-min(IQRratio)); + C = zeros(numel(IQRratio),3); + cmap = [jet(64); gray(64)]; + for i=1:numel(IQRratio) + C(i,:) = cmap(round(IQRratios(i))+1,:); + end + + hold(cscc.H.scat(cscc.H.scata),'on') + + % plot lines between similar objects + if numel(indx)/size(cscc.data.YpY,1)<0.5 && numel(indx) + for i=1:numel(indx) + cscc.H.corrline{scata}(i) = plot( cscc.H.scat(cscc.H.scata),... + [X(indx(i),1);X(indy(i),1)],[X(indx(i),2);X(indy(i),2)],'-','Color',... + repmat(cscc.display.figcolor(1)*0.9 - cscc.display.figcolor(1)*0.9 * ... + ((cscc.data.YpY_tmp(indx(i),indy(i)) - 0.925)/0.0725),1,3),... + 'LineWidth',2,'HitTest','off','Interruptible','off'); + set(cscc.H.corrline{scata}(i),'UserData',[indx(i) indy(i)]); + end + else + cscc.H.corrline{scata} = plot([]); + end + + % plot data entries + I = 1:size(X,1); + for gi=1:numel(groups) + It = I(cscc.datagroups.sample==groups(gi)); + Xt = X(cscc.datagroups.sample==groups(gi),:); + Ct = C(cscc.datagroups.sample==groups(gi),:); + Pt = cscc.datagroups.protocol(cscc.datagroups.sample==groups(gi),:); + cscc.H.sc{scata} = cell(size(Xt,1),1); + for sci=1:size(Xt,1) + cscc.H.sc{scata}{gi}{sci} = scatter( cscc.H.scat(cscc.H.scata), ... + Xt(sci,1), ... + Xt(sci,2), ... + 30,... + Ct(sci,:),... + symbols(gi), ... + 'ZDataSource',num2str(Pt(sci),'%d'),... + 'UserData',It(sci),... + 'Linewidth',2); + if ~isempty( strfind('osd^v<>ph', symbols(gi) ) ) + set(cscc.H.sc{scata}{gi}{sci},'MarkerFaceColor','flat','markerFaceAlpha',1/3); + end + if any(It(sci)==cscc.select.trashlist) + set(cscc.H.sc{scata}{gi}{sci},'sizedatasource',get(cscc.H.sc{scata}{gi}{sci},'marker'),... + 'marker','x','SizeData',40,'MarkerEdgeColor',[1 0 0.5],... + 'ZDataSource','trash','MarkerFaceAlpha',0); + end + end + end + + hold(cscc.H.scat(cscc.H.scata),'off') + end + + xlabel(cscc.H.scat(cscc.H.scata),... + '<----- Worst --- Mean correlation --- Best ------> ',... + 'FontSize',cscc.display.FS(cscc.display.FSi),'FontWeight','Bold'); + ylabel(cscc.H.scat(cscc.H.scata),... + '<----- Worst --- Weighted overall image quality rating --- Best ------> ',... + 'FontSize',cscc.display.FS(cscc.display.FSi),'FontWeight','Bold'); + title(cscc.H.scat(cscc.H.scata),... + '<--- Smallest -- Norm. Ratio IQR/mean correlation (Color) -- Largest ----> ','FontSize',... + cscc.display.FS(cscc.display.FSi+2),'FontWeight','Bold'); + + + % update colorbar + cticks = 7; + mn = 0; + mx = 10; %round(max(cscc.data.IQRratio)/6)*6; + ticks = linspace(mn,mx,cticks); + set(cscc.H.cbar,'XTick',1:63/(numel(ticks)-1):64,... + 'XTickLabel',cellstr(num2str(ticks','%0.2f'))); + %round(100*linspace(min(cscc.data.YpYt(:)),max(cscc.data.YpYt(:)),5))/100); + %caxis(cscc.H.scat(cscc.H.scata),[mn mx]) + + cscc.H.isscatter = 1; + + show_sample + %show_protocol + + xlim(cscc.H.scat(cscc.H.scata),'auto'); + xticks = get(cscc.H.scat(cscc.H.scata),'xtick'); + xlim([xticks(1) - diff(xticks(1:2)/2) xticks(end) + diff(xticks(1:2)/2)]); + + ylim(cscc.H.scat(cscc.H.scata),'auto'); + yticks = get(cscc.H.scat(cscc.H.scata),'ytick'); + ylim([yticks(1) - diff(yticks(1:2)/2) yticks(end) + diff(yticks(1:2)/2)]); + + zoom reset +return + +%----------------------------------------------------------------------- +function update_matrix(data, order) +%----------------------------------------------------------------------- +%----------------------------------------------------------------------- + global cscc + + showtrash = get(cscc.H.showtrash,'Value'); + + if ~exist('order','var') + order = cscc.H.sorted; + else + cscc.H.sorted = order; + end + + if ~exist('data' ,'var') + if order + data = cscc.data.YpY(cscc.data.ind_sorted,cscc.data.ind_sorted); + else + data = cscc.data.YpY; + end + end + + if order + cscc.select.trash1dt = cscc.select.trash1d(cscc.data.ind_sorted); + cscc.select.trash2dt = cscc.select.trash2d(cscc.data.ind_sorted,cscc.data.ind_sorted); + + cscc.select.samp1dt = cscc.select.samp1d(cscc.data.ind_sorted); + cscc.select.samp2dt = cscc.select.samp2d(cscc.data.ind_sorted,cscc.data.ind_sorted); + cscc.select.prot1dt = cscc.select.prot1d(cscc.data.ind_sorted); + cscc.select.prot2dt = cscc.select.prot2d(cscc.data.ind_sorted,cscc.data.ind_sorted); + else + cscc.select.trash1dt = cscc.select.trash1d; + cscc.select.trash2dt = cscc.select.trash2d; + + cscc.select.samp1dt = cscc.select.samp1d; + cscc.select.samp2dt = cscc.select.samp2d; + cscc.select.prot1dt = cscc.select.prot1d; + cscc.select.prot2dt = cscc.select.prot2d; + end + + + if ~showtrash + data = reshape(data(cscc.select.trash2dt & cscc.select.samp2dt & cscc.select.prot2dt),... + sum(cscc.select.trash1dt .* cscc.select.samp1dt .* cscc.select.prot1dt),... + sum(cscc.select.trash1dt .* cscc.select.samp1dt .* cscc.select.prot1dt)); + cscc.select.trash2dt = reshape(cscc.select.trash2dt( ... + cscc.select.trash2dt & cscc.select.samp2dt & cscc.select.prot2dt),... + sum(cscc.select.trash1dt .* cscc.select.samp1dt .* cscc.select.prot1dt),... + sum(cscc.select.trash1dt .* cscc.select.samp1dt .* cscc.select.prot1dt)); + else + data = reshape(data(cscc.select.samp2dt & cscc.select.prot2dt),... + sum(cscc.select.samp1dt .* cscc.select.prot1dt),sum(cscc.select.samp1dt .* cscc.select.prot1dt)); + cscc.select.trash2dt = reshape(cscc.select.trash2dt(cscc.select.samp2dt & cscc.select.prot2dt),... + sum(cscc.select.samp1dt .* cscc.select.prot1dt),sum(cscc.select.samp1dt .* cscc.select.prot1dt)); + end + + + %% scale data + cticks = 7; + ltick = cticks - 1; + htick = ltick/2; + if cscc.H.cbarfix.Value==1 + mx = 1.0; + if cscc.H.mesh_detected + mn = 0.8; + else + mn = 0.7; + end + elseif cscc.H.cbarfix.Value==2 + mx = 1.0; + md = median(cscc.data.mean_cov); + mn = mx - ltick * ceil((mx - md)/htick * 100)/100; + else + md = round(median(cscc.data.mean_cov)*100)/100; + dd = min( round( (1 - md) / htick * 100) /100 * htick, ... + htick * round(2 * std(cscc.data.mean_cov) * 100 ) / 100 ); + dd = round(dd * 100 ) / 100; + mx = md + dd; + mn = md - dd; + end + ticks = linspace(mn,mx,cticks); + + data_scaled = min(1,max(0,(data - mn)/(mx - mn))); + + % create image if not exist + if isempty(get(cscc.H.corr,'children')) + image(cscc.H.corr,data_scaled); + else + if showtrash + mylim = 0.5 + [0 size(cscc.data.YpY,1)] - [0 numel(cscc.data.mean_cov) - ... + sum(cscc.select.samp1dt .* cscc.select.prot1dt)]; + else + mylim = (0.5 + [0 size(cscc.data.YpY,1)]) - [0 numel(cscc.data.mean_cov) - ... + sum(cscc.select.trash1dt .* cscc.select.samp1dt .* cscc.select.prot1dt)]; + end + if diff(mylim)==0 + % deselect all images + set(get(cscc.H.corr,'children'),'Cdata',65); + xlim(cscc.H.corr,[0.5 1.5]); + ylim(cscc.H.corr,[0.5 1.5]); + axis off + return + end + xlim(cscc.H.corr,mylim); + ylim(cscc.H.corr,mylim); + end + + % show only lower left triangle + bg = 119; + if showtrash + set(get(cscc.H.corr,'children'),'Cdata',64 * (data_scaled + 65/64*(1-cscc.select.trash2dt)) .* tril(data>0) + bg*(~tril(data>0)) ); + else + set(get(cscc.H.corr,'children'),'Cdata',64 * (data_scaled) .* tril(data>0) + bg*(~tril(data>0)) ); + end + + % update colorbar + set(cscc.H.cbar,'XTick',1:63/(numel(ticks)-1):64,... + 'XTickLabel',cellstr(num2str(ticks','%0.2f'))); + %round(100*linspace(min(cscc.data.YpYt(:)),max(cscc.data.YpYt(:)),5))/100); + + % update axis limits + if 0 && ~cscc.H.isscatter + if showtrash + mylim = 0.5 + [0 size(cscc.data.YpY,1)]; + else + mylim = (0.5 + [0 size(cscc.data.YpY,1)]) - [0 numel(cscc.select.trashlist)]; + end + xlim(cscc.H.corr,mylim); + ylim(cscc.H.corr,mylim); + end + + if isempty(cscc.H.dcm.getCursorInfo) + unit = struct2cell(cscc.H.checkui); + set([unit{cellfun(@ishandle,unit)}],'Enable','off'); + set([cscc.H.trashui.trash;cscc.H.trashui.detrash; ... + cscc.H.trashui.trashcol;cscc.H.trashui.detrashcol; ... + cscc.H.trashui.trashrow;cscc.H.trashui.detrashrow],'Enable','off'); + end +return + +%----------------------------------------------------------------------- +function show_matrix(data, order) +%----------------------------------------------------------------------- +%----------------------------------------------------------------------- + global cscc + + set([cscc.H.corr,get(cscc.H.corr,'children')],'visible','on','HitTest','on','Interruptible','on'); + set(findobj('type','Legend'),'visible','off','HitTest','off','Interruptible','off'); + try + for i=1:numel(cscc.H.scat), set([cscc.H.scat(i);get(cscc.H.scat(i),'Children')],... + 'visible','off','HitTest','off','Interruptible','off'); end; + end + axis(cscc.H.corr); + if isfield(cscc.H,'cbarfix') && ishandle(cscc.H.cbarfix) + set(cscc.H.cbarfix ,'enable' ,'on'); + end + if isfield(cscc.H,'showtrash') && ishandle(cscc.H.showtrash) + if isempty(cscc.select.trashlist) + set(cscc.H.showtrash,'enable' ,'off'); + else + set(cscc.H.showtrash,'enable' ,'on'); + end + end + try set([cscc.H.sclegend{:}],'visible','off'); end + + % == set GUI fields == + + % update buttons and remove cursor, slices/surfaces? and text + if isfield(cscc.pos,'tar_mouse') + delete(cscc.pos.tar_mouse); + cscc.pos = rmfield(cscc.pos,'tar_mouse'); + + if isfield(cscc.pos,'x'), cscc.pos = rmfield(cscc.pos,'x'); end + if isfield(cscc.pos,'y'), cscc.pos = rmfield(cscc.pos,'y'); end + + if isfield(cscc.H,'slice') && ishandle(cscc.H.slice), set(cscc.H.slice ,'Visible','off'); cla(cscc.H.slice); end + if isfield(cscc.H,'sslider') && ishandle(cscc.H.sslider), set(cscc.H.sslider ,'Visible','off'); end + if isfield(cscc.H,'alphabox') && ishandle(cscc.H.alphabox), set(cscc.H.alphabox ,'Visible','off'); end + if isfield(cscc.H,'mm') && ishandle(cscc.H.mm), set([cscc.H.mm,cscc.H.mm_txt],'Visible','off'); end + + set(cscc.H.alphabox,'Visible','off'); + end + + set([cscc.H.trashui.trash,cscc.H.trashui.detrash,... + cscc.H.trashui.trashcol,cscc.H.trashui.detrashcol,... + cscc.H.trashui.trashrow,cscc.H.trashui.detrashrow],'Enable','off','visible','on'); + set([cscc.H.trashui.trash,cscc.H.trashui.detrash],'Visible','off'); + unit = struct2cell(cscc.H.checkui); set([unit{cellfun(@ishandle,unit)}],'Enable','off'); + + + cscc.H.isscatter = 0; + + % get sorting order + cscc.H.sorted = order; + + % update image + update_matrix(data,order) + + % update title and label elements + if cscc.H.sorted + xlabel(cscc.H.corr,'<----- Best --- File Order --- Worst ------> ',... + 'FontSize',cscc.display.FS(cscc.display.FSi),'FontWeight','Bold'); + ylabel(cscc.H.corr,'<----- Worst --- File Order --- Best ------> ',... + 'FontSize',cscc.display.FS(cscc.display.FSi),'FontWeight','Bold'); + title(cscc.H.corr,'Sorted Sample Correlation Matrix ','FontSize',... + cscc.display.FS(cscc.display.FSi+2),'FontWeight','Bold'); + else + xlabel(cscc.H.corr,'<----- First --- File Order --- Last ------> ',... + 'FontSize',cscc.display.FS(cscc.display.FSi),'FontWeight','Bold'); + ylabel(cscc.H.corr,'<----- Last --- File Order --- First ------> ',... + 'FontSize',cscc.display.FS(cscc.display.FSi),'FontWeight','Bold'); + title(cscc.H.corr,'Sample Correlation Matrix ','FontSize',... + cscc.display.FS(cscc.display.FSi+2),'FontWeight','Bold'); + end + + zoom reset + return + +%----------------------------------------------------------------------- +function checkbox_names(obj, event_obj) +%----------------------------------------------------------------------- + global cscc + cscc.H.show_name = get(cscc.H.chbox,'Value'); + show_boxplot; +return + +%----------------------------------------------------------------------- +function checkbox_plot(obj, event_obj) +%----------------------------------------------------------------------- + global cscc + cscc.H.show_violin = get(cscc.H.plotbox,'Value'); + show_boxplot; +return + +%----------------------------------------------------------------------- +function show_boxplot(data_boxp, name_boxp, quality_order, obj) +%----------------------------------------------------------------------- + global cscc bp + + if nargin <3 + data_boxp = bp.data; + name_boxp = bp.name; + quality_order = bp.order; + else + bp.data = data_boxp; + bp.name = name_boxp; + bp.order = quality_order; + end + + if iscell(name_boxp), name_boxp = name_boxp{1}; end + + spm_figure('Clear',cscc.H.graphics); + spm_figure('Focus',cscc.H.graphics); + + cscc.H.boxplot = axes('Position',cscc.pos.boxplot,'Parent',cscc.H.graphics); + set(cscc.H.graphics,'Renderer','OpenGL','color',[0.95 0.95 0.95]); + + %if isfield(cscc.H,'chbox'), nval = ~get(cscc.H.chbox,'value'), else nval = 1; end + + cscc.H.refresh = uicontrol(cscc.H.graphics,... + 'Units','normalized','position',cscc.pos.refresh,'callback',@show_boxplot,... + 'string','REF','ForegroundColor',[0 0.8 0],'FontSize',cscc.display.FS(cscc.display.FSi),... + 'ToolTipString','Include row','Style','Pushbutton','Enable','on'); + buttonicon(cscc.H.refresh,'REF' ,... + fullfile(spm('dir'),'toolbox','cat12','html','icons','refresh.png')); + + switch deblank(name_boxp) + case 'Noise rating (NCR)', name = 'NCR'; + case 'Bias rating (ICR)', name = 'ICR'; + case 'Resoution rating (RES)', name = 'RES'; + case 'Weighted overall image quality rating (IQR)', name = 'IQR'; + case 'Euler number', name = 'Euler'; + case 'Size of topology defects (TDS)', name = 'TDS'; + case 'Mean correlation', name = 'MNC'; + case 'Protocol-based IQR (PIQR)', name = 'PIQR'; + case 'Norm. Ratio IQR/mean correlation', name = 'IQRratio'; + case 'Norm. Ratio PIQR/mean correlation',name = 'PIQRratio'; + otherwise, name = ''; + end + + cscc.H.worst = uicontrol(cscc.H.graphics,... + 'Units','normalized','position',cscc.pos.worst,'Style','Pushbutton',... + 'HorizontalAlignment','center','callback',@check_worst_data, ..., bp.data, bp.name},... + 'string',['Check worst ' name],'ToolTipString','Display most deviating files',... + 'FontSize',cscc.display.FS(cscc.display.FSi),'ForegroundColor',[0.8 0 0]); + + cscc.H.chbox = uicontrol(cscc.H.graphics,... + 'string','Show filenames','Units','normalized',... + 'position',cscc.pos.fnamesbox,'callback',@checkbox_names,... + 'Style','CheckBox','HorizontalAlignment','center',... + 'ToolTipString','Show filenames in boxplot','value',cscc.H.show_name,... + 'Interruptible','on','Visible','on','FontSize',cscc.display.FS(cscc.display.FSi)); + + cscc.datagroups.n_samples = max(cscc.datagroups.sample); + + xcscc.pos = cell(1,cscc.datagroups.n_samples); + data = cell(1,cscc.datagroups.n_samples); + + %% create filenames + hold on + allow_violin = 1; + for i=1:cscc.datagroups.n_samples + indtype = { cscc.select.trash1d' 'k.' [0 0 0] 10; ~cscc.select.trash1d' 'rx' [1 0 0] 3}; + gnames{i} = sprintf('S%d',i); + for ii=1:size(indtype,1) + ind = find(cscc.datagroups.sample == i & indtype{ii,1}); + if numel(ind>0) + datap{i} = data_boxp(ind); + if ii==1, data{i} = datap{i}; end + + if length(ind)<10 + allow_violin = 0; + cscc.H.show_violin = 0; + end + + if cscc.datagroups.n_samples == 1 + xcscc.pos{i} = (i-1)+2*(0:length(ind)-1)/(length(ind)-1); + else + xcscc.pos{i} = 0.5/length(ind) + 0.5+(i-1)+1*(0:length(ind)-1)/(length(ind)); + end + + if get(cscc.H.chbox,'value') + for j=1:length(ind) + cscc.H.fnames{j,i} = text(xcscc.pos{i}(j),datap{i}(j),... + cscc.files.fname.m{ind(j)},'Color',indtype{ii,3},... + 'FontSize',cscc.display.FS(cscc.display.FSi-1),'HorizontalAlignment','center'); + end + else + for j=1:length(ind) + cscc.H.fnames{j,i} = plot(xcscc.pos{i}(j),datap{i}(j),indtype{ii,2},'MarkerSize',indtype{ii,4}); + end + end + end + end + end + +% allow violin plot onl if samples are all large enough +if allow_violin + cscc.H.plotbox = uicontrol(cscc.H.graphics,... + 'string','Violinplot','Units','normalized',... + 'position',cscc.pos.plotbox,'callback',@checkbox_plot,... + 'Style','CheckBox','HorizontalAlignment','center',... + 'ToolTipString','Switch to Violinplot','value',cscc.H.show_violin,... + 'Interruptible','on','Visible','on','FontSize',cscc.display.FS(cscc.display.FSi)); +end + + %% create boxplot + opt = struct('groupnum',0,'ygrid',1,'box',1,'violin',2*cscc.H.show_violin,'median',2,... + 'groupcolor',jet(cscc.datagroups.n_samples),'names',{gnames},... + 'xlim',[-.25 cscc.datagroups.n_samples+1.25]); + if max(data_boxp) > min(data_boxp) + ylim_add = 0.075; + yamp = max(data_boxp) - min(data_boxp); + ylim_min = min(data_boxp) - ylim_add * yamp; + ylim_max = max(data_boxp) + ylim_add * yamp; + norm = round(20/yamp); + if norm==0 + norm = round(yamp/20); + end + opt.ylim = round( [ylim_min ylim_max] * norm ) / norm; + end + cat_plot_boxplot(data,opt); box on; + + + %% add colored labels and title + if cscc.datagroups.n_samples > 1 + [tmp, tmp2] = spm_str_manip(char(cscc.files.fname.s),'C'); %spm_file(char(tmp2.s),'short25') + if length(tmp)>80,tmp = sprintf('../%s',strrep(tmp,tmp2.s,'')); end + title_str = sprintf('Common filename: %s*',tmp); + else + title_str = sprintf('Common filename: %s*',spm_file(char(cscc.files.fname.s),'short25')); + end + title({['Boxplot: ' name_boxp],title_str},'FontSize',cscc.display.FS(cscc.display.FSi+1),'FontWeight','Bold'); + xlabel('<----- First --- File Order --- Last ------> ','FontSize',cscc.display.FS(10),... + 'FontWeight','Bold'); + + xcscc.pos = -0.35 - cscc.datagroups.n_samples*0.1; + + if quality_order >= 2 + % reverse order to have the good things allways on the top + set(gca, 'YDir','reverse'); + quality_order = 1; + t = ylim_min; ylim_min = ylim_max; ylim_max = t; + end + if (length(data_boxp) > 2) + if quality_order > 0 + text(xcscc.pos, ylim_min,'<----- Low rating (poor quality) ','Color','red','Rotation',... + 90,'HorizontalAlignment','left','FontSize',cscc.display.FS(9),'FontWeight','Bold') + text(xcscc.pos, ylim_max,'High rating (good quality) ------> ','Color',[0 0.8 0],'Rotation',... + 90,'HorizontalAlignment','right','FontSize',cscc.display.FS(9),'FontWeight','Bold') + elseif quality_order < 0 + if strfind(name_boxp,'Ratio') + text(xpos, ylim_max,'Low rating (poor quality) ------> ','Color','red','Rotation',... + 90,'HorizontalAlignment','right','FontSize',FS,'FontWeight','Bold') + text(xpos, ylim_min,'<----- High rating (good quality) ','Color','green','Rotation',... + 90,'HorizontalAlignment','left','FontSize',FS,'FontWeight','Bold') + else + text(xpos, ylim_max,'Low rating (poor quality) ------> ','Color','red','Rotation',... + 90,'HorizontalAlignment','right','FontSize',FS,'FontWeight','Bold') + text(xpos, ylim_min,'<----- High rating (good quality) ','Color','green','Rotation',... + 90,'HorizontalAlignment','left','FontSize',FS,'FontWeight','Bold') + end + end + text(xcscc.pos, (ylim_max+ylim_min)/2,sprintf('%s',name_boxp),'Color','black','Rotation',... + 90,'HorizontalAlignment','center','FontSize',cscc.display.FS(9),'FontWeight','Bold') + end + + hold off + + +return + +%----------------------------------------------------------------------- +function update_alpha(obj, event_obj) +%----------------------------------------------------------------------- +%----------------------------------------------------------------------- + global cscc + + alphaval = get(cscc.H.alphabox,'Value'); + + % display image with 2nd colorbar (gray) + image(cscc.H.slice,65 + cscc.data.img); + set(cscc.H.slice,'Position',cscc.pos.slice .* [1 1 1 1 - 0.5*cscc.H.isscatter],'visible','off'); + + if ~cscc.H.mesh_detected + set(cscc.H.slice,'HitTest','off','Interruptible','off'); + end + + % prepare alpha overlays for red and green colors + if alphaval > 0 + % get 2%/98% ranges of difference image + range = cat_vol_iscaling(cscc.data.img_alpha(:),[0.02 0.98]); + + hold(cscc.H.slice,'on') + if ~cscc.H.mesh_detected + alpha_g = cat(3, zeros(size(cscc.data.img_alpha)), ... + alphaval*ones(size(cscc.data.img_alpha)), zeros(size(cscc.data.img_alpha))); + alpha_r = cat(3, alphaval*ones(size(cscc.data.img_alpha)), ... + zeros(size(cscc.data.img_alpha)), zeros(size(cscc.data.img_alpha))); + else + alpha_r = cat(3, zeros(size(cscc.data.img_alpha)), ... + alphaval*ones(size(cscc.data.img_alpha)), zeros(size(cscc.data.img_alpha))); + alpha_g = cat(3, alphaval*ones(size(cscc.data.img_alpha)), ... + zeros(size(cscc.data.img_alpha)), zeros(size(cscc.data.img_alpha))); + end + hg = image(cscc.H.slice,alpha_g); + set(hg, 'AlphaData', cscc.data.img_alpha .* (cscc.data.img_alpha>range(2))); + if ~cscc.H.mesh_detected, set(hg,'HitTest','off','Interruptible','off','AlphaDataMapping','scaled'); end + hr = image(cscc.H.slice,alpha_r); + set(hr, 'AlphaData',-cscc.data.img_alpha .* (cscc.data.img_alpha 0 + colormap(cscc.H.slice,[gray(64);gray(64)]); + else + colormap(cscc.H.slice,[gray(64);jet(64)]); + end + end +return + +%----------------------------------------------------------------------- +function update_slices_array(obj, event_obj) +%----------------------------------------------------------------------- + global cscc + + if isfield(cscc.H,'mm') + slice_mm = get(cscc.H.mm,'Value'); + else + slice_mm = 0; + end + + if cscc.data.Vchanged_names + P = cscc.data.Vchanged; + else + P = cscc.data.V; + end + + vx = sqrt(sum(P(1).mat(1:3,1:3).^2)); + Orig = P(1).mat\[0 0 0 1]'; + sl = round(slice_mm/vx(3)+Orig(3)); + + % if slice is outside of image use middle slice + if (sl>P(1).dim(3)) || (sl<1) + sl = round(P(1).dim(3)/2); + end + set(cscc.H.mm,'Value',(sl-Orig(3))*vx(3)); + + M = spm_matrix([0 0 sl]); + cscc.data.data_array_diff = cscc.data.data_array; + + %% + for i = 1:length(cscc.data.V) + cscc.data.img = spm_slice_vol(P(i),M,P(1).dim(1:2),[1 0]); + cscc.data.img(isnan(cscc.data.img)) = 0; + + % rescue unscaled data + cscc.data.data_array_diff(:,:,i) = cscc.data.img; + + if cscc.H.inorm %&& ~isempty(strfind(cscc.files.dataprefix,'wp')) + cscc.data.imgscale = median(cscc.data.img(cscc.data.img ~= 0)); + cscc.data.data_array(:,:,i) = cscc.data.img/cscc.data.imgscale; + else + cscc.data.data_array(:,:,i) = cscc.data.img; + end + end + %% + cscc.data.imgscale = median(cscc.data.data_array(cscc.data.data_array ~= 0)); % scale image according to mean + cscc.data.data_array = cscc.data.data_array / cscc.data.imgscale * 0.3; + + % calculate individual difference to mean image + for i=1:size(cscc.data.data_array_diff,3) + cscc.data.data_array_diff(:,:,i) = cscc.data.data_array_diff(:,:,i) - mean(cscc.data.data_array_diff,3); + end + + % enhance contrast and scale image to 0..64 + %mn = min(cscc.data.data_array(:)); + %mx = max(cscc.data.data_array(:)); + cscc.data.data_array = min(64,max(1,63 * cscc.data.data_array + 1)); + + if cscc.H.sorted + if isfield(cscc.pos,'x') + x = cscc.data.ind_sorted(cscc.pos.x); + if ~cscc.H.isscatter + y = cscc.data.ind_sorted(cscc.pos.y); + end + end + else + if isfield(cscc.pos,'x') + x = cscc.pos.x; + if ~cscc.H.isscatter + y = cscc.pos.y; + end + end + end + + % check whether mouse position is defined + if isfield(cscc.pos,'x') + if cscc.H.isscatter + cscc.data.img = cscc.data.data_array(:,:,x)'; + cscc.data.img_alpha = cscc.data.data_array_diff(:,:,x)'; + else + cscc.data.img = [cscc.data.data_array(:,:,y) cscc.data.data_array(:,:,x)]'; + cscc.data.img_alpha = [cscc.data.data_array_diff(:,:,y) cscc.data.data_array_diff(:,:,x)]'; + end + + % correct orientation + cscc.data.img = rot90(cscc.data.img,2); + cscc.data.img_alpha = rot90(cscc.data.img_alpha,2); + + % use gray scale colormap for values > 64 + update_alpha + + set(cscc.H.mm_txt,'String',sprintf('%0.1f mm',get(cscc.H.mm,'Value'))); + end + +return + +%----------------------------------------------------------------------- +function txt = myupdatefcn(obj, event_obj) +%----------------------------------------------------------------------- + global cscc + + alphaval = get(cscc.H.alphabox,'Value'); + cscc.H.surfori = 0; + + if gca ~= cscc.H.slice + showtrash = get(cscc.H.showtrash,'Value'); + + + cscc.H.datatip = event_obj; + + cscc.pos.pos_mouse = get(event_obj, 'Position'); + cscc.pos.tar_mouse = get(event_obj, 'Target'); + + % Limit the number of datatips: + % Although it is cscc.posible or maybe use to mark cscc.H.multiple objects for + % comparision of volumes, surfaces and PDFs, the other check cases + % cscc.data.XML and LOG-files are worse to handle. + % Furthermore, it is elaboritiv to suport all cscc.select.trashlist operations. + dcmlim = 0; % + 6*cscc.H.isscatter; % up to 6 plot objects? + dcm = findall(gcf,'Type','hggroup','selected','off'); + if numel(dcm)>dcmlim, delete(dcm(dcmlim+1:end)); end + set(findall(gcf,'Type','hggroup'),'Visible','on') + + + + % check for valid mouse position + if cscc.H.isscatter + cscc.pos.x = find(cscc.data.X(:,1) == cscc.pos.pos_mouse(1)); + if isempty(cscc.pos.x) + cscc.pos.pos_mouse = get(event_obj, 'Position'); + cscc.pos.x = find(cscc.data.X(:,2) == cscc.pos.pos_mouse(2)); + end + + %{ + if isfield(cscc.job,'c') + for ci=1:size(size(cscc.job.c,2)) + if round(cscc.job.c(x,ci)) == cscc.job.c(cscc.pos.x,ci) + nuisx = sprintf('; N%d=%d',ci,cscc.job.c(cscc.pos.x,ci)); + else + nuisx = sprintf('; N%d=%d',ci,cscc.job.c(cscc.pos.x,ci)); + end + end + if size(cscc.job.c,2)>3 + nuisx2 = ['\n ' nuisx(3:end)]; nuisx = []; + end + end + %} + + % text info for data cursor window + txt = {sprintf('S%d:%s',cscc.datagroups.sample(cscc.pos.x),cscc.files.fname.m{cscc.pos.x}); + sprintf('MNC=%5.3f',cscc.data.mean_cov(cscc.pos.x))}; + txt{2} = sprintf('%s; IQR=%5.2f',txt{2},cscc.data.QM(cscc.pos.x,4)); + if numel(cscc.datagroups.protocols)>1 + txt{2} = sprintf('%s (P=%0.2f)',txt{2},... + cscc.datagroups.protocols(cscc.datagroups.protocol(cscc.pos.x))); + end + txt{2} = sprintf('%s; IQRratio=%0.2f' ,txt{2},cscc.data.IQRratio(cscc.pos.x)); + + set(cscc.H.slice,'Position',cscc.pos.slice .* [1 1 1 0.5],'Visible','on'); + + x = cscc.pos.x; + else % covariance matrix + + if cscc.pos.pos_mouse(1) > cscc.pos.pos_mouse(2) || ... + cscc.pos.pos_mouse(1)>length(cscc.datagroups.sample) || cscc.pos.pos_mouse(2)>length(cscc.datagroups.sample) + %txt = {''}; + set([cscc.H.slice,cscc.H.alphabox],'Visible','off'); + if ~cscc.H.mesh_detected + set([cscc.H.mm,cscc.H.mm_txt],'Visible','off'); + end + set(get(cscc.H.slice,'children'),'Visible','off'); + unit = struct2cell(cscc.H.checkui); set([unit{cellfun(@ishandle,unit)}],'Enable','off'); + set([cscc.H.trashui.trash,cscc.H.trashui.detrash,... + cscc.H.trashui.trashcol,cscc.H.trashui.detrashcol,... + cscc.H.trashui.trashrow,cscc.H.trashui.detrashrow],'Enable','off'); + set(findall(gcf,'Type','hggroup'),'Visible','off') + return + elseif cscc.pos.pos_mouse(1)==1 && cscc.pos.pos_mouse(2)==1 && ... + get(get(cscc.H.corr,'children'),'CData')==65 + txt = 'Error: No datapoints available.\nModify data selection!'; + return + end + + % save position of mouse + cscc.pos.x = find(cumsum(max(showtrash,cscc.select.trash1d) & ... + cscc.select.samp1d & cscc.select.prot1d)==cscc.pos.pos_mouse(1),1,'first'); + cscc.pos.y = find(cumsum(max(showtrash,cscc.select.trash1d) & ... + cscc.select.samp1d & cscc.select.prot1d)==cscc.pos.pos_mouse(2),1,'first'); + + + if cscc.H.sorted + if isfield(cscc.pos,'x') + x = cscc.data.ind_sorted(cscc.pos.x); cscc.pos.x = x; + y = cscc.data.ind_sorted(cscc.pos.y); cscc.pos.y = y; + end + else + if isfield(cscc.pos,'x') + x = cscc.pos.x; + y = cscc.pos.y; + end + end + + % text info for data cursor window + if isfield(cscc.data,'QM') & size(cscc.data.QM,2)>=4 + QMtxtx = sprintf('; IQR=%5.2f; IQRratio=%5.2f',cscc.data.QM(x,4),cscc.data.IQRratio(x)); + QMtxty = sprintf('; IQR=%5.2f; IQRratio=%5.2f',cscc.data.QM(y,4),cscc.data.IQRratio(y)); + end + nuisx = ''; nuisy = ''; + + if isfield(cscc.job,'c') & ~isempty(cscc.job.c) + for ci=1:size(cscc.job.c,2) + if round(cscc.job.c{ci}(x)) == cscc.job.c{ci}(x) + nuisx = sprintf('; N_%d=%d',ci,cscc.job.c{ci}(x)); + nuisy = sprintf('; N%d=%d',ci,cscc.job.c{ci}(y)); + else + nuisx = sprintf('; N%d=%0.2f',ci,cscc.job.c{ci}(x)); + nuisy = sprintf('; N%d=%0.2f',ci,cscc.job.c{ci}(y)); + end + end + if size(cscc.job.c,2)>2 % new separate line + nuisx = sprintf('Column (Top): %s',nuisx(3:end)); + nuisy = sprintf('Row (Bottom): %s',nuisy(3:end)); + end + end + + if isfield(cscc.data,'QM') & size(cscc.data.QM,2)>=4 + txt = { + sprintf('Correlation: %3.3f',cscc.data.YpY(x,y)),... + sprintf('Column (Top): S%d:%s',cscc.datagroups.sample(x),cscc.files.fname.m{x}), ... + sprintf('Row (Bottom): S%d:%s',cscc.datagroups.sample(y),cscc.files.fname.m{y}), ... + sprintf('Column (Top): MNC=%5.3f%s%s',cscc.data.mean_cov(x),QMtxtx,nuisx),... + sprintf('Row (Bottom): MNC=%5.3f%s%s',cscc.data.mean_cov(y),QMtxty,nuisy)... + }; + else + txt = { + sprintf('Correlation: %3.3f',cscc.data.YpY(x,y)),... + sprintf('Column (Top): S%d:%s',cscc.datagroups.sample(x),cscc.files.fname.m{x}), ... + sprintf('Row (Bottom): S%d:%s',cscc.datagroups.sample(y),cscc.files.fname.m{y}), ... + sprintf('Column (Top): MNC=%5.3f%s',cscc.data.mean_cov(x),nuisx),... + sprintf('Row (Bottom): MNC=%5.3f%s',cscc.data.mean_cov(y),nuisy)... + }; + end + set(cscc.H.slice,'Position',cscc.pos.slice,'Visible','on'); + + end + + % == check unit == + onoff = {'on','off'}; + if cscc.H.isscatter + set(cscc.H.checkui.vol ,'Enable',onoff{ isempty(cscc.files.org{cscc.pos.x})+1 }); + set(cscc.H.checkui.surf,'Enable',onoff{ isempty(cscc.files.surf{cscc.pos.x})+1 }); + set(cscc.H.checkui.xml ,'Enable',onoff{ isempty(cscc.files.xml{cscc.pos.x})+1 }); + set(cscc.H.checkui.log ,'Enable',onoff{ isempty(cscc.files.log{cscc.pos.x})+1 }); + set(cscc.H.checkui.pdf ,'Enable',onoff{ isempty(cscc.files.pdf{cscc.pos.x})+1 }); + else + set(cscc.H.checkui.vol ,'Enable',onoff{ (isempty(cscc.files.org{cscc.pos.x}) | isempty(cscc.files.org{cscc.pos.y})) + 1 }); + set(cscc.H.checkui.surf,'Enable',onoff{ (isempty(cscc.files.surf{cscc.pos.x}) | isempty(cscc.files.surf{cscc.pos.y})) + 1 }); + set(cscc.H.checkui.xml ,'Enable',onoff{ (isempty(cscc.files.xml{cscc.pos.x}) | isempty(cscc.files.xml{cscc.pos.y})) + 1 }); + set(cscc.H.checkui.log ,'Enable',onoff{ (isempty(cscc.files.log{cscc.pos.x}) | isempty(cscc.files.log{cscc.pos.y})) + 1 }); + set(cscc.H.checkui.pdf ,'Enable',onoff{ (isempty(cscc.files.pdf{cscc.pos.x}) | isempty(cscc.files.pdf{cscc.pos.y})) + 1 }); + end + + % == trash list unit == + if ~isempty(cscc.pos.x) + if all( cscc.select.trashlist~=cscc.pos.x ) + set([cscc.H.trashui.trash ,cscc.H.trashui.trashcol ],'Enable','on' ); + set([cscc.H.trashui.detrash,cscc.H.trashui.detrashcol],'Enable','off'); + else + set([cscc.H.trashui.trash ,cscc.H.trashui.trashcol ],'Enable','off' ); + set([cscc.H.trashui.detrash,cscc.H.trashui.detrashcol],'Enable','on'); + end + %else + % set([cscc.H.trashui.trash,cscc.H.trashui.detrash],'Enable','off'); + end + if ~cscc.H.isscatter && isfield(cscc.pos,'y') && ~isempty(cscc.pos.y) + if all( cscc.select.trashlist~=cscc.pos.y ) + set(cscc.H.trashui.trashrow ,'Enable','on'); + set(cscc.H.trashui.detrashrow,'Enable','off'); + else + set(cscc.H.trashui.trashrow ,'Enable','off'); + set(cscc.H.trashui.detrashrow,'Enable','on'); + end + end + if ~isempty(cscc.select.trashlist) + set([cscc.H.trashui.new,cscc.H.trashui.disptrash,cscc.H.trashui.ziptrash],'Enable','on'); + else + set([cscc.H.trashui.new,cscc.H.trashui.disptrash,cscc.H.trashui.ziptrash],'Enable','off'); + end + + set(cscc.H.alphabox,'Visible','on'); + + + + if cscc.H.mesh_detected + % use indexed 2D-sheet to display surface data as image + % check surface size to use indexed 2D map + if (length(cscc.data.data_array(:,x)) == 163842) || (length(cscc.data.data_array(:,x)) == 32492) + % combined surface + + if (length(cscc.data.data_array(:,x)) == 163842) + ind = spm_load(fullfile(spm('dir'),'toolbox','cat12','templates_surfaces','fsavg.index2D_256x128.txt')); + else + ind = spm_load(fullfile(spm('dir'),'toolbox','cat12','templates_surfaces_32k','fsavg.index2D_256x128.txt')); + end + + if cscc.H.isscatter + cscc.data.img = reshape(cscc.data.data_array(ind,x),[256,128]); + else + cscc.data.img = [reshape(cscc.data.data_array(ind,x),[256,128]) reshape(cscc.data.data_array(ind,y),[256,128])]; + end + cscc.data.img = circshift(cscc.data.img,128); + + % alpha overlay + if cscc.H.isscatter + cscc.data.img_alpha = reshape(cscc.data.data_array_diff(ind,x),[256,128]); + else + cscc.data.img_alpha = [reshape(cscc.data.data_array_diff(ind,x),[256,128]) ... + reshape(cscc.data.data_array_diff(ind,y),[256,128])]; + end + cscc.data.img_alpha = circshift(cscc.data.img_alpha,128); + + + elseif (length(cscc.data.data_array(:,x)) == 327684) || (length(cscc.data.data_array(:,x)) == 64984) + is32k = length(cscc.data.data_array(:,x)) == 64984; + if is32k + atlasdir = 'atlases_surfaces_32k'; + tmpdir = 'templates_surfaces_32k'; + else + atlasdir = 'atlase_surfaces'; + tmpdir = 'templates_surfaces'; + end + lrb = [size(cscc.data.data_array,1)/2,size(cscc.data.data_array,1)/2+1]; + lab = fullfile(spm('dir'),'toolbox','cat12',atlasdir,'lh.aparc_DK40.freesurfer.annot'); + ind = spm_load(fullfile(spm('dir'),'toolbox','cat12',tmpdir,'fsavg.index2D_256x128.txt')); + + %% average both atlas maps to keep it simpler + [vr{1},lb{1},tb{1}] = cat_io_FreeSurfer('read_annotation',lab); + [vr{2},lb{2},tb{2}] = cat_io_FreeSurfer('read_annotation',strrep(lab,'lh.','rh.')); + cscc.data.atlastable = {tb{1}.table(:,5), tb{1}.struct_names}; + cscc.data.atlas_lh = circshift(reshape(lb{1}(ind),[256,128]),64)'; + cscc.data.atlas_rh = circshift(reshape(lb{2}(ind),[256,128]),64)'; + cscc.data.atlas1 = cat_vol_median3(single(cat(3,cscc.data.atlas_lh,cscc.data.atlas_rh))); + [gx,gy] = gradient(cscc.data.atlas1(:,:,1)); + cscc.data.atlasmsk = single(((abs(gy) + abs(gx))./cscc.data.atlas1(:,:,1))<0.05); + cscc.data.atlasmsk(cscc.data.atlasmsk==0) = nan; + cscc.data.atlasmsk = flipud(cscc.data.atlasmsk); + %cscc.data.atlas1 = flipud(circshift(reshape(cscc.data.atlas1(ind),[256,128]),64)'); + cscc.data.atlas1 = flipud(cscc.data.atlas1(:,:,1)); + + %% load data array entry + cscc.data.data_array_x_lh = cscc.data.data_array(1:lrb(2),x); + cscc.data.data_array_x_rh = cscc.data.data_array(lrb(2):end,x); + if ~cscc.H.isscatter + cscc.data.data_array_y_lh = cscc.data.data_array(1:lrb(1),y); + cscc.data.data_array_y_rh = cscc.data.data_array(lrb(2):end,y); + end + + % rotate the image (') and shift it (64) to have a cscc.posterior cutting edge + cscc.data.img_x_lh = flipud(circshift(reshape(cscc.data.data_array_x_lh(ind),[256,128]),64)'); + cscc.data.img_x_rh = flipud(circshift(reshape(cscc.data.data_array_x_rh(ind),[256,128]),64)'); + if ~cscc.H.isscatter + cscc.data.img_y_lh = flipud(circshift(reshape(cscc.data.data_array_y_lh(ind),[256,128]),64)'); + cscc.data.img_y_rh = flipud(circshift(reshape(cscc.data.data_array_y_rh(ind),[256,128]),64)'); + end + %% + if cscc.H.surfori + if cscc.H.isscatter + cscc.data.img = [cscc.data.img_x_lh .* cscc.data.atlasmsk', cscc.data.img_x_rh .* cscc.data.atlasmsk']; + cscc.data.atlas = [cscc.data.atlas1'; cscc.data.atlas1']; + else + cscc.data.img = [cscc.data.img_x_lh' .* cscc.data.atlasmsk', cscc.data.img_y_lh' .* cscc.data.atlasmsk'; ... + cscc.data.img_x_rh' .* cscc.data.atlasmsk', cscc.data.img_y_rh' .* cscc.data.atlasmsk']; + cscc.data.atlas = [cscc.data.atlas1', cscc.data.atlas1'; ... + cscc.data.atlas1', cscc.data.atlas1']; + end + else + if cscc.H.isscatter + cscc.data.img = [cscc.data.img_x_lh' .* cscc.data.atlasmsk', fliplr(cscc.data.img_x_rh' .* cscc.data.atlasmsk')]; + cscc.data.imgo = [cscc.data.img_x_lh', fliplr(cscc.data.img_x_rh')]; + cscc.data.atlas = [cscc.data.atlas1', fliplr(cscc.data.atlas1')]; + else + cscc.data.img = [cscc.data.img_x_lh' .* cscc.data.atlasmsk', fliplr(cscc.data.img_x_rh' .* cscc.data.atlasmsk'); ... + cscc.data.img_y_lh' .* cscc.data.atlasmsk', fliplr(cscc.data.img_y_rh' .* cscc.data.atlasmsk')]; + cscc.data.imgo = [cscc.data.img_x_lh', fliplr(cscc.data.img_x_rh'); ... + cscc.data.img_y_lh', fliplr(cscc.data.img_y_rh')]; + cscc.data.atlas = [cscc.data.atlas1' fliplr(cscc.data.atlas1'); ... + cscc.data.atlas1' fliplr(cscc.data.atlas1')]; + end + end + + %% alpha overlay + cscc.data.data_array_x_lh = cscc.data.data_array_diff(1:lrb(2),x); + cscc.data.data_array_x_rh = cscc.data.data_array_diff(lrb(2):end,x); + if ~cscc.H.isscatter + cscc.data.data_array_y_lh = cscc.data.data_array_diff(1:lrb(1),y); + cscc.data.data_array_y_rh = cscc.data.data_array_diff(lrb(2):end,y); + end + cscc.data.img_x_lh = flipud(circshift(reshape(cscc.data.data_array_x_lh(ind),[256,128]),64)'); + cscc.data.img_x_rh = flipud(circshift(reshape(cscc.data.data_array_x_rh(ind),[256,128]),64)'); + if ~cscc.H.isscatter + cscc.data.img_y_lh = flipud(circshift(reshape(cscc.data.data_array_y_lh(ind),[256,128]),64)'); + cscc.data.img_y_rh = flipud(circshift(reshape(cscc.data.data_array_y_rh(ind),[256,128]),64)'); + end + + if cscc.H.surfori + if cscc.H.isscatter + cscc.data.img_alpha = [cscc.data.img_x_lh .* cscc.data.atlasmsk; cscc.data.img_x_rh .* fliplr(cscc.data.atlasmsk)]; + else + cscc.data.img_alpha = [cscc.data.img_x_lh .* cscc.data.atlasmsk; cscc.data.img_y_lh .* fliplr(cscc.data.atlasmsk); ... + cscc.data.img_x_rh .* cscc.data.atlasmsk; cscc.data.img_y_rh .* fliplr(cscc.data.atlasmsk)]; + end + else + if cscc.H.isscatter + cscc.data.img_alpha = [cscc.data.img_x_lh' .* cscc.data.atlasmsk', fliplr(cscc.data.img_x_rh' .* cscc.data.atlasmsk')]; + else + cscc.data.img_alpha = [cscc.data.img_x_lh' .* cscc.data.atlasmsk', fliplr(cscc.data.img_x_rh' .* cscc.data.atlasmsk'); ... + cscc.data.img_y_lh' .* cscc.data.atlasmsk', fliplr(cscc.data.img_y_rh' .* cscc.data.atlasmsk')]; + end + end + + else + if cscc.H.isscatter + cscc.data.img = cscc.data.data_array(:,x)'; + % alpha overlay + cscc.data.img_alpha = cscc.data.data_array_diff(:,x)'; + else + cscc.data.img = [cscc.data.data_array(:,y) cscc.data.data_array(:,x)]'; + % alpha overlay + cscc.data.img_alpha = [cscc.data.data_array_diff(:,y) cscc.data.data_array_diff(:,x)]'; + end + end + + % scale cscc.data.img to 0..64 + if 0 %strfind(cscc.files.dataprefix,'thickness') + mn = 0.0; + mx = 5.0; + else + sd = std(cscc.data.data_array(:)); + mn = -sd*2; + mx = sd*2; + end + cscc.data.img = 64*((cscc.data.img - mn)/(mx-mn)); + else + % add slider for colume data + set(cscc.H.mm,'Visible','on'); + set(cscc.H.mm_txt,'Visible','on'); + if cscc.H.isscatter + cscc.data.img = cscc.data.data_array(:,:,x)'; + % alpha overlay + cscc.data.img_alpha = cscc.data.data_array_diff(:,:,x)'; + else + cscc.data.img = [cscc.data.data_array(:,:,y) cscc.data.data_array(:,:,x)]'; + % alpha overlay + cscc.data.img_alpha = [cscc.data.data_array_diff(:,:,y) cscc.data.data_array_diff(:,:,x)]'; + end + end + + % set(cscc.H.cbar,'TickLength',[0 0],'XTickLabel',linspace(0.7,1.0,7)); + %round(100*linspace(min(cscc.data.YpY(cscc.select.trash2d(:))),max(cscc.data.YpY(cscc.select.trash2d(:))),5))/100); + + + % correct orientation + cscc.data.img = rot90(cscc.data.img,2); + cscc.data.img_alpha = rot90(cscc.data.img_alpha,2); + if cscc.H.mesh_detected + cscc.data.imgo = rot90(cscc.data.imgo,2); + cscc.data.atlas = rot90(cscc.data.atlas,2); + end + + % display image with 2nd colorbar (gray) + image(cscc.H.slice,65 + cscc.data.img); + set(cscc.H.slice,'visible','off'); + + % prepare alpha overlays for red and green colors + if alphaval > 0 + %% get 2%/98% ranges of difference image + range = cat_vol_iscaling(cscc.data.img_alpha(:),[0.02 0.98]); + + hold(cscc.H.slice,'on'); + alpha_g = cat(3, zeros(size(cscc.data.img_alpha)), ... + alphaval*ones(size(cscc.data.img_alpha)), zeros(size(cscc.data.img_alpha))); + alpha_r = cat(3, alphaval*ones(size(cscc.data.img_alpha)), ... + zeros(size(cscc.data.img_alpha)), zeros(size(cscc.data.img_alpha))); + hg = image(cscc.H.slice,alpha_g); + set(hg, 'AlphaData', cscc.data.img_alpha.*(cscc.data.img_alpha>range(2))); + if ~cscc.H.mesh_detected, set(hg,'HitTest','off','Interruptible','off','AlphaDataMapping','scaled'); end + hr = image(cscc.H.slice,alpha_r); + set(hr, 'AlphaData',-cscc.data.img_alpha.*(cscc.data.img_alpha 0 + dt = cscc.data.imgo(ax,ay); + else + dt = cscc.data.img_alpha(ax,ay); + end + + txt = {sprintf('%s (%d,%d)',roi,ax,ay) sprintf('Value: %0.2f',dt) }; + end +return + +%----------------------------------------------------------------------- +function varargout = cat_tst_qa_cleaner_intern(data,opt) +%% Tcscc.HIS FUNCTION IS TO FAT - SEPARATE AND CLEAN IT! +% Do not forget to remove old external version from Scscc.data.VN if this is done. +% _____________________________________________________________________ +% Estimate quality grades of given rating of one (or more) cscc.datagroups.protocols +% with 2 to 6 grads to separate passed, (unassignable) and failed +% images, by finding the first peak in the image quality histogram +% and using its width (standard deviation) in a limited range. +% If cscc.H.multiple cscc.datagroups.protocols are used, than use the site variable opt.site +% and use the site depending output rths. +% +% The passed range can be variated by opt.cf with lower values for harder +% and higher values for softer thresholds (more passed images), where +% opt.cf=1, describes a range that is similar to about 1% BWP noise that +% is equal to 5 rps. +% ROC evaluation showed that opt.cf=0.72 allows the best separation of +% images without and with artifacts, but if the majority of your data +% include light artifacts (e.g. by movements in young children) that +% a softer weighing, e.g. opt.cf=2, is preferable (maximum is 4). +% +% Use the selftest with randomly generated data to get a first impression: +% cat_tst_qa_cleaner('test') +% _____________________________________________________________________ +% +% This tool is still in development / undert test: +% * the combination of different sites is not finished +% * cscc.H.multiside output required a 'stacked' output +% +% [Pth,rth,sq,rths,rthsc,sqs] = cat_tst_qa_remover(data[,opt]) +% +% Pth .. global threshold for passed images +% (for odd grades this is in the middle of the unassignable) +% rth .. all global threshold(s) between grads +% sq .. estimated first peak and its std, where the std depend on +% the number of grades! +% rths .. site depending thresholds between grads of each input +% rthsc .. site depending thresholds between grads of each input +% (global corrected, removed further low quality data) +% sqs .. site depending first peaks and stds of passed data +% +% data .. array of quality ratings or xml-files +% opt .. option structure +% .grads .. number of grads (2:6, default=6, see below) +% .cf .. factor for harder/softer thresholds (defaults=0.72) +% .figure .. display histogramm with colored ranges of grads +% 1 - use current figure +% 2 - create new figure (default) +% 3 - use one test figure (default in the selftest) +% _____________________________________________________________________ +% +% Grades: +% 2 grads: +% P passed +% F failed +% 3 grads: +% P passed +% U unassignable +% F failed +% 4 grads: +% P+ clear passed +% P- just passed +% F+ just failed +% F- clear failed +% 5 grads: +% P+ clear passed +% P- just passed +% U unassignable +% F+ just failed +% F- clear failed +% 6 grads (default): +% P+ clear passed +% P passed +% P- just passed +% F+ just failed +% F failed +% F- clear failed +% +% ______________________________________________________________________ +% Robert Dahnke +% Structural Brain Mapping Group +% University Jena +% ______________________________________________________________________ +% $Id$ + + global cscc + + clear th; + if ~exist('opt','var'), opt = struct(); end + def.cf = 0.72; % normalization factor for rating + def.grads = 6; % number of grads (default = 6) + def.model = 1; % model used for rating + def.figure = 2; % figure=2 for new/own figure + def.smooth = 0; % smoothing of output data + def.siterf = 1000000; % round factor to identify similar resolution level + def.siteavgperc = [0.10 0.90]; % ? + opt = cat_io_checkinopt(opt,def); + opt.cf = max( 0 , min( 4 , opt.cf )); % limit of cf + + % test options + %opt.model = 2; + %opt.grads = 6; + + % if no intput is given use SPM select to get some xml-files + if ~exist('data','var') || isempty(data) + data = cellstr(spm_select(inf,'XML','select qa cscc.data.XML-files',{},pwd,'^cat_.*')); + elseif ischar(data) + data = cellstr(data); + end + if isempty(data) || (iscell(data) && all(cellfun('isempty',data))) + if nargout>=1, varargout{1} = 3; end + if nargout>=2, varargout{2} = 3; end + if nargout>=3, varargout{3} = [2.5 0.5]; end + if nargout>=4, varargout{4} = 3*ones(size(data)); end + if nargout>=5, varargout{5} = 3*ones(size(data)); end + if nargout>=6, varargout{6} = repmat([2.5 0.5],numel(data),1); end + + return; + end + if iscell(data) && ~strcmp(data{1},'test') + fprintf('Load cscc.data.XML data'); + P = data; + xml = cat_io_xml(data,struct(),'read',1); clear data; + for di=1:numel(xml) + opt.site(di,1) = xml(di).qualityratings.res_RMS; + data(di,1) = xml(di).qualityratings.NCR; + end, + end + + + % -------------------------------------------------------------------- + % If a site variable is given (e.g. by the RMS resolution) then call + % the cleanup for each subset. The threshold will be collected in a + % vector [markthss x opt.grads] with the same length as data. + % Nevertheless an average threshold will is estimated as average of + % the percentual range give by opt.siteavgperc with e.g. [0.1 0.9] to + % concider 80% of the data. + % ------------------------------------------------------------------- + if isfield(opt,'site') + if numel(opt.site)~=numel(data), + error('cat_tst_qa_cleaner_intern:numelsitedata','Numer of elements in data and opt.site have to be equal.\n'); + end + opt.site = round(opt.site*opt.siterf)/opt.siterf; + sites = unique(opt.site); + markth = zeros(numel(sites),opt.grads-1); + markths = zeros(numel(data),opt.grads-1); + siteth = zeros(numel(data),2); + for si=1:numel(sites) + sdatai = find(opt.site==sites(si)); + opts = opt; + opts = rmfield(opts,'site'); + opts.figure = 0; + [Sth,markth(si,:),out{1:4}] = cat_tst_qa_cleaner_intern(data(sdatai),opts); + markths(sdatai,:) = repmat(markth(si,:),numel(sdatai),1); + siteth(sdatai,:) = out{4}; + end + % estimate global threshold + markthss = sortrows(markth); + th = cat_stat_nanmean(markthss(max(1,min(numel(sites),round(numel(sites)*opt.siteavgperc(1)))):... + max(1,min(numel(sites),round(numel(sites)*opt.siteavgperc(2)))),:),1); + sd = out{3}; + thx = out{4}; + % modify local rating based on the global one + markths2 = markths; + markths2 = min(markths2,1.2*repmat(th,size(markths2,1),1)); % higher thresholds even for sides with low rating + markths2 = max(markths2,0.8*repmat(th,size(markths2,1),1)); % lower thresholds even for sides with high rating + d = data; + + else + % ----------------------------------------------------------------- + % Simulate data, if no data is given by several normal distributed + % random numbers. + % ----------------------------------------------------------------- + if exist('data','var') && ~(iscell(data) && strcmp(data{1},'test')) + d = data; + if numel(d)==0, + if nargout>=1, varargout{1} = nan; end + if nargout>=2, varargout{2} = nan(1,opt.grads); end + if nargout>=3, varargout{3} = nan(1,2); end + if nargout>=4, varargout{4} = nan(size(data)); end + if nargout>=5, varargout{5} = nan(size(data)); end + if nargout>=6, varargout{6} = nan(size(data)); end + return; + end + elseif iscell(data) && strcmp(data{1},'test') + % Testcases with different quality ratings + scans = 100; % number of scans (per site) for simulation + testcase = round(rand(1)*10); + randoffset = 0.5*randn(1,4); + + switch testcase + case 0 % good quality, no outlier group + d = [2.0 + randoffset(1) + 0.1*randn(1,round(scans*0.80)), ... + 2.5 + randoffset(2) + 0.3*randn(1,round(scans*0.15)), ... + 4.0 + randoffset(3) + 1.0*randn(1,round(scans*0.03)), ... + 5.0 + randoffset(4) + 1.0*randn(1,round(scans*0.02))]; + case 1 % good quality, with average outlier group + d = [2.0 + randoffset(1) + 0.1*randn(1,round(scans*0.40)), ... + 2.5 + randoffset(2) + 0.3*randn(1,round(scans*0.40)), ... + 4.0 + randoffset(3) + 1.0*randn(1,round(scans*0.15)), ... + 5.0 + randoffset(4) + 1.0*randn(1,round(scans*0.05))]; + case 2 % good-average quality, with outlier group + d = [2.0 + randoffset(1) + 0.1*randn(1,round(scans*0.10)), ... + 2.5 + randoffset(2) + 0.3*randn(1,round(scans*0.50)), ... + 4.0 + randoffset(3) + 1.0*randn(1,round(scans*0.30)), ... + 5.0 + randoffset(4) + 1.0*randn(1,round(scans*0.10))]; + case 3 % good-average quality, without outlier group + d = [2.0 + randoffset(1) + 0.2*randn(1,round(scans*0.10)), ... + 2.5 + randoffset(2) + 0.3*randn(1,round(scans*0.50)), ... + 3.0 + randoffset(3) + 1.0*randn(1,round(scans*0.30)), ... + 4.0 + randoffset(4) + 1.0*randn(1,round(scans*0.10))]; + case 4 % average to low quality, with light falloff + d = [3.0 + randoffset(1) + 0.2*randn(1,round(scans*0.10)), ... + 3.5 + randoffset(2) + 0.3*randn(1,round(scans*0.50)), ... + 4.0 + randoffset(3) + 1.0*randn(1,round(scans*0.30)), ... + 5.0 + randoffset(4) + 1.0*randn(1,round(scans*0.10))]; + case 5 % high to good quality, with light falloff + d = [1.0 + randoffset(1) + 0.2*randn(1,round(scans*0.10)), ... + 1.5 + randoffset(2) + 0.3*randn(1,round(scans*0.50)), ... + 2.0 + randoffset(3) + 1.0*randn(1,round(scans*0.30)), ... + 3.0 + randoffset(4) + 1.0*randn(1,round(scans*0.10))]; + case 6 % high quality, no outlier + d = [1.0 + randoffset(1) + 0.1*randn(1,round(scans*0.80)), ... + 1.5 + randoffset(2) + 0.3*randn(1,round(scans*0.13)), ... + 3.0 + randoffset(3) + 0.3*randn(1,round(scans*0.05)), ... + 5.0 + randoffset(4) + 0.3*randn(1,round(scans*0.02))]; + case 7 % good quality with second average peak + d = [2.0 + randoffset(1) + 0.1*randn(1,round(scans*0.30)), ... + 3.0 + randoffset(2) + 0.2*randn(1,round(scans*0.40)), ... + 4.0 + randoffset(3) + 0.5*randn(1,round(scans*0.10)), ... + 5.0 + randoffset(4) + 0.5*randn(1,round(scans*0.10))]; + case 8 % good quality with second low quality peak + d = [1.0 + randoffset(1) + 0.1*randn(1,round(scans*0.50)), ... + 4.0 + randoffset(2) + 0.2*randn(1,round(scans*0.30)), ... + 4.0 + randoffset(3) + 0.5*randn(1,round(scans*0.10)), ... + 5.0 + randoffset(4) + 0.5*randn(1,round(scans*0.10))]; + case 9 % good quality with second average and third low quality peak + d = [1.5 + randoffset(1) + 0.2*randn(1,round(scans*0.20)), ... + 3.0 + randoffset(2) + 0.3*randn(1,round(scans*0.20)), ... + 4.5 + randoffset(3) + 0.2*randn(1,round(scans*0.10)), ... + 2.0 + randoffset(4) + 0.8*randn(1,round(scans*0.50))]; + case 10 % good quality with second average and third low quality peak + d = [1.5 + randoffset(1) + 0.1*randn(1,round(scans*0.10)), ... + 3.0 + randoffset(2) + 0.2*randn(1,round(scans*0.10)), ... + 4.5 + randoffset(3) + 0.2*randn(1,round(scans*0.10)), ... + 2.5 + randoffset(4) + 1.0*randn(1,round(scans*0.60))]; + end + + % remove high quality outlier and set them to normal + cor = max(1,median(d)-std(d)/2); + md= d<(cor); d(md) = cor + 0.05*randn(1,sum(md)); + + % set selftest figure + opt.figure = 3; + end + + + %% Models + % ------------------------------------------------------------------- + % I start with several ideas that all based on a similar idea: to + % find the first peak that is given by the subset of images without + % inferences and to use the variance of this peak for further scaling + % of subsets for other grads. As far as IQR is already scaled, we + % can limit the variance value ... e.g. the rating has an error of + % 0-2 rps (0.0-0.2 mark points) that is very low for high-quality data + % and higher for low-quality data. Due to our the general subdivion + % of the rating scale in +,o, and - (e.g. B+,B,B-) we got a subrange + % of 3.33 rps (1/3 mark points) that gives some kind of upper limit. + % ------------------------------------------------------------------- + thx = nan; sd = nan; th = zeros(1,opt.grads-1); + switch opt.model + case 0 + % only global thresholding ... + % this is just to use the color bar output + thx = 3; + sd = 1; + th = 1.5:1:100; + th(6:end) = []; + case 1 + % kmeans model: + % * estimate peaks based on the histogram + % * mix the first and second peak until it fits to 30% of the data + % or until the number of loops is similar the number of peaks + % * use the std give by one BWP noise level (0.5) to describe the + % variance the passed interval. + + hx = hist(d,0.5:1:5.5); + peaks = sum(hx>(max(hx)/5))*3; + [thx,sdx] = cat_stat_kmeans(d,peaks); sdx = sdx./thx; + for i=1:peaks + if sum(d(max(hx)/5))*3; + [thx,sdx] = cat_stat_kmeans(d,peaks); sdx = sdx./thx; + for i=1:peaks + %if numel(thx)>i && sum(di && + thx(1) = cat_stat_nanmean(thx(1:2)); + sdx(1) = cat_stat_nanstd(d(d th(1)+ss) = 0; fill(r,hx/sh,[0.0 0.5 0.2],'edgecolor','none'); + hx = h; hx(r<=th(1)-ss) = 0; fill(r,hx/sh,[0.6 0.15 0.1],'edgecolor','none'); + % main values + text(5,yl(2)*0.93,sprintf('%5.2f%% passed',sum(d< th(1))/numel(d)*100) ,'color',[0.0 0.5 0.2]); + text(5,yl(2)*0.85,sprintf('%5.2f%% failed',sum(d>=th(1))/numel(d)*100) ,'color',[0.6 0.15 0.1]); + case 2 + hx = h; hx(r>=th(1)+ss) = 0; fill(r,hx/sh,[0.0 0.5 0.2],'edgecolor','none'); + hx = h; hx(r<=th(1) | r>th(2)) = 0; fill(r,hx/sh,[0.85 0.75 0.3],'edgecolor','none'); + hx = h; hx(r<=th(2)-ss) = 0; fill(r,hx/sh,[0.6 0.15 0.1],'edgecolor','none'); + % main values + text(5,yl(2)*0.93,sprintf('%5.2f%% passed',sum(d=th(1) & d=th(2))/numel(d)*100) ,'color',[0.6 0.15 0.1]); + case 3 + % plot + hx = h; hx(r>=th(1)+ss) = 0; fill(r,hx/sh,[0.0 0.5 0.2],'edgecolor','none'); + hx = h; hx(r<=th(1)-ss | r>th(2)) = 0; fill(r,hx/sh,[0.7 0.8 0.2],'edgecolor','none'); + hx = h; hx(r<=th(2)-ss | r>th(3)) = 0; fill(r,hx/sh,[0.9 0.6 0.4],'edgecolor','none'); + hx = h; hx(r<=th(3)-ss) = 0; fill(r,hx/sh,[0.6 0.15 0.1],'edgecolor','none'); + % main values + text(5,yl(2)*0.93,sprintf('%5.2f%% passed',sum(d< th(2))/numel(d)*100),'color',[0 0.7 0]); + text(5,yl(2)*0.88,sprintf('%5.2f%% failed',sum(d>=th(2))/numel(d)*100),'color',[0.8 0.0 0]); + % detailed values + text(5,yl(2)*0.75,sprintf('%5.2f%% passed+',sum(d< th(1))/numel(d)*100) ,'color',[0.0 0.5 0.2]); + text(5,yl(2)*0.70,sprintf('%5.2f%% passed-',sum(d>=th(1) & d=th(2) & d=th(3))/numel(d)*100) ,'color',[0.6 0.15 0.1]); + case 4 + % plot + hx = h; hx(r>=th(1)+ss) = 0; fill(r,hx/sh,[0.0 0.5 0.2],'edgecolor','none'); + hx = h; hx(r<=th(1)-ss | r>th(2)) = 0; fill(r,hx/sh,[0.4 0.7 0.1],'edgecolor','none'); + hx = h; hx(r<=th(2)-ss | r>th(3)) = 0; fill(r,hx/sh,[0.85 0.75 0.3],'edgecolor','none'); + hx = h; hx(r<=th(3)-ss | r>th(4)) = 0; fill(r,hx/sh,[0.75 0.3 0.2],'edgecolor','none'); + hx = h; hx(r<=th(4)-ss) = 0; fill(r,hx/sh,[0.6 0.15 0.1],'edgecolor','none'); + % main values + text(5,yl(2)*0.93,sprintf('%5.2f%% passed',sum(d=th(2) & d=th(3))/numel(d)*100) ,'color',[0.7 0.0 0.0]); + % detailed values + text(5,yl(2)*0.75,sprintf('%5.2f%% passed+',sum(d=th(1) & d=th(2) & d=th(3) & d=th(4))/numel(d)*100) ,'color',[0.6 0.15 0.1]); + case 5 + % plot + testbar=0; % it would be cool to use bars but they failed at least in MATLAB R2013 and killed the axis positions... + if testbar==1 + hx = h; hx(r>=th(1)+ss) = 0; bar(r,hx/sh,'facecolor',[0.0 0.5 0.2],'edgecolor','none','barwidth',1); + hx = h; hx(r<=th(1)-ss | r>th(2)) = 0; bar(r,hx/sh,'facecolor',[0.4 0.7 0.1],'edgecolor','none','barwidth',1); + hx = h; hx(r<=th(2)-ss | r>th(3)) = 0; bar(r,hx/sh,'facecolor',[0.7 0.8 0.2],'edgecolor','none','barwidth',1); + hx = h; hx(r<=th(3)-ss | r>th(4)) = 0; bar(r,hx/sh,'facecolor',[0.9 0.6 0.4],'edgecolor','none','barwidth',1); + hx = h; hx(r<=th(4)-ss | r>th(5)) = 0; bar(r,hx/sh,'facecolor',[0.75 0.3 0.2],'edgecolor','none','barwidth',1); + hx = h; hx(r<=th(5)-ss) = 0; bar(r,hx/sh,'facecolor',[0.6 0.15 0.1],'edgecolor','none','barwidth',1); + else + hx = h; hx(r>=th(1)+ss) = 0; fill(r,hx/sh,[0.0 0.5 0.2],'edgecolor','none'); + hx = h; hx(r<=th(1)-ss | r>th(2)) = 0; fill(r,hx/sh,[0.4 0.7 0.1],'edgecolor','none'); + hx = h; hx(r<=th(2)-ss | r>th(3)) = 0; fill(r,hx/sh,[0.7 0.8 0.2],'edgecolor','none'); + hx = h; hx(r<=th(3)-ss | r>th(4)) = 0; fill(r,hx/sh,[0.9 0.6 0.4],'edgecolor','none'); + hx = h; hx(r<=th(4)-ss | r>th(5)) = 0; fill(r,hx/sh,[0.75 0.3 0.2],'edgecolor','none'); + hx = h; hx(r<=th(5)-ss) = 0; fill(r,hx/sh,[0.6 0.15 0.1],'edgecolor','none'); + end + % main values + text(5,yl(2)*0.93,sprintf('%5.2f%% passed',sum(d=th(3))/numel(d)*100),'color',[0.8 0.0 0]); + % detailed values + text(5,yl(2)*0.75,sprintf('%5.2f%% passed+',sum(d=th(1) & d=th(2) & d=th(3) & d=th(4) & d=th(5))/numel(d)*100) ,'color',[0.6 0.15 0.1]); + end + xlim([min(r),6.5]); + + % subgrid + for i=5/6:1/3:6.4, plot([i i],[0 0.03]*max(ylim),'color',[0.2 0.2 0.2]); end + + QMC = cat_io_colormaps('marks+',17); + color = @(QMC,m) QMC(max(1,min(size(QMC,1),round(((m-1)*3)+1))),:); + + + % colored main grads + cscc.display.FS = get(gca,'Fontsize')*1.3; + set(gca,'XTick',0.5:1:6.5,'XTickLabel',{'100','90','80','70','60','50','40'},'TickLength',[0.02 0.02]); + % further color axis objects... + axA = copyobj(gca,gcf); axB = copyobj(axA,gcf); axC = copyobj(gca,gcf); + axD = copyobj(gca,gcf); axE = copyobj(gca,gcf); axF = copyobj(gca,gcf); + % set colors... + set(axA,'YTick',[],'XTickLabel',{},'XTick',1,... + 'XColor',color(QMC,1),'Color','none',... + 'XTicklabel','A','TickLength',[0 0],... + 'Fontsize',cscc.display.FS,'Fontweight','bold'); + set(axB,'YTick',[],'XTickLabel',{},'XTick',2,... + 'XColor',color(QMC,2),'Color','none',... + 'XTicklabel','B','TickLength',[0 0],... + 'Fontsize',cscc.display.FS,'Fontweight','bold'); + set(axC,'YTick',[],'XTickLabel',{},'XTick',3,... + 'XColor',color(QMC,3),'Color','none',... + 'XTicklabel','C','TickLength',[0 0],... + 'Fontsize',cscc.display.FS,'Fontweight','bold'); + set(axD,'YTick',[],'XTickLabel',{},'XTick',4,... + 'XColor',color(QMC,4),'Color','none',... + 'XTicklabel','D','TickLength',[0 0],... + 'Fontsize',cscc.display.FS,'Fontweight','bold'); + set(axE,'YTick',[],'XTickLabel',{},'XTick',5,... + 'XColor',color(QMC,5),'Color','none',... + 'XTicklabel','E','TickLength',[0 0],... + 'Fontsize',cscc.display.FS,'Fontweight','bold'); + set(axF,'YTick',[],'XTickLabel',{},'XTick',6,... + 'XColor',color(QMC,6),'Color','none',... + 'XTicklabel','F','TickLength',[0 0],... + 'Fontsize',cscc.display.FS,'Fontweight','bold'); + hold off; + + if isfield(opt,'site') && numel(sites>1); + title(sprintf('Histogram (cf=%0.2f) - global treshold for cscc.H.multisite output (n=%d)',... + opt.cf,numel(sites)),'Fontsize',cscc.display.FS); + else + title(sprintf('Histogram (cf=%0.2f)',opt.cf),... + 'Fontsize',cscc.display.FS); + end + xlabel('IQR (rps)','Fontsize',cscc.display.FS); + ylabel('number of scans','Fontsize',cscc.display.FS); + end + %% + MarkColor = cat_io_colormaps('marks+',40); + if isfield(opt,'site') && numel(sites)>1, globcorr = ' (global corrected)'; else globcorr = ''; end + if exist('P','var') + files = P(data<=markths2(:,3)); + fprintf('PASSED%s: %0.2f%%\n',globcorr,numel(files)/numel(data)*100) + + % bad files ... + files = P(data>markths2(:,3) & data<=markths2(:,4)); + fprintf('FAILED+%s: %0.2f%%\n',globcorr,numel(files)/numel(data)*100) + if 1 + iqrs = [xml(data>markths2(:,3) & data<=markths2(:,4)).qualityratings]; + for fi=1:numel(files) + cat_io_cprintf(MarkColor(max(1,round( iqrs(fi).IQR/9.5 * size(MarkColor,1))),:),' %s\n',files{fi,1}); + end + end + files = P(data>markths2(:,4) & data<=markths2(:,5)); + iqrs = [xml(data>markths2(:,4) & data<=markths2(:,5)).qualityratings]; + if 1 + fprintf('FAILED%s: %0.2f%%\n',globcorr,numel(files)/numel(data)*100) + for fi=1:numel(files) + cat_io_cprintf(MarkColor(max(1,round( iqrs(fi).IQR/9.5 * size(MarkColor,1))),:),' %s\n',files{fi,1}); + end + end + files = P(data>markths2(:,5)); + fprintf('FAILED-%s: %0.2f%%\n',globcorr,numel(files)/numel(data)*100) + if 1 + iqrs = [xml(data>markths2(:,5)).qualityratings]; + for fi=1:numel(files) + cat_io_cprintf(MarkColor(max(1,round( iqrs(fi).IQR/9.5 * size(MarkColor,1))),:),' %s\n',files{fi,1}); + end + end + end + + + %% create output + if nargout>=1, varargout{1} = mean(th(floor(opt.grads/2):ceil(opt.grads/2))); end + if nargout>=2, varargout{2} = th; end + if nargout>=3, varargout{3} = [thx(1) sd(1)]; end + if nargout>=4, varargout{4} = markths; end + if nargout>=5, varargout{5} = markths2; end + if nargout>=6, varargout{6} = siteth; end + if nargout>=7, varargout{7} = sites; end + + +return +","MATLAB" +"Neurology","ChristianGaser/cat12","internal/cat_tst_histBWPT.m",".m","2484","78","function cat_tst_histBWPT(S,qa,msave,ff) +% cat_test_BWPT_hist. Print figure of histogram for thickness phantom. + + s = 0; + + if ~exist('msave','var'), msave = 0; end + if ~exist('ff','var') + ff = ''; + else + [~,ff] = spm_fileparts(ff); + end + + % smoothing for robust peaks + if s > 0 + M = spm_mesh_smooth(S.rh); + T = single(spm_mesh_smooth(M,double(S.rh.th1),s)); + else + T = S.rh.th1; + end + + + if msave + fh = figure(4949); + else + fh = figure; + end + + ss = 0.01; + hx = ss/2:ss:5; + hy = hist(T,hx); + hy(2:end-1) = hy(2:end-1)*0.5 + hy(1:end-2)*0.25 + hy(3:end)*0.25; %smooth + gh = histogram(T,hx); + + fh.Position = [1151 1 560 420]; + gh.EdgeColor = 'none'; gh.FaceColor = [0 0.2 0.4]; gh.FaceAlpha = .9; + grid on; xlim([0 4]); ylim([1 1.2] .* ylim); + + [hy15,hx15] = max(hy .* (hx>1.25 & hx<=1.75)); hx15x = hx(hx15) - 1.5; + [hy20,hx20] = max(hy .* (hx>1.75 & hx<=2.25)); hx20x = hx(hx20) - 2.0; + [hy25,hx25] = max(hy .* (hx>2.25 & hx<=2.75)); hx25x = hx(hx25) - 2.5; + + % print title + justnow = datestr(datetime,'YYYYmmdd-HHMM'); + if exist('qa','var') + title(sprintf('histogram thickness BWPT'), ... + sprintf('%s [th=%0.0f, RMSE=%0.3f mm, Int: %0.3f, Pos: %0.3f, IS: %0.03f%%]', ... + justnow, sum([hy15,hy20,hy25]), sum([hx15x,hx20x,hx25x].^2).^0.5, ... + mean([qa.rh.createCS_final.RMSE_Ym_white, ... + qa.rh.createCS_final.RMSE_Ym_layer4, ... + qa.rh.createCS_final.RMSE_Ym_pial]), ... + mean([qa.rh.createCS_final.RMSE_Ypp_white, ... + qa.rh.createCS_final.RMSE_Ypp_central, ... + qa.rh.createCS_final.RMSE_Ypp_pial]), ... + mean([qa.rh.createCS_final.white_self_interections, ... + qa.rh.createCS_final.pial_self_interections]) )); + else + title(sprintf('histogram thickness BWPT'), ... + sprintf('%s [th=%d, RMSE=%0.3f mm]', ... + justnow, sum([hy15,hy20,hy25]), sum([hx15x,hx20x,hx25x].^2).^0.5)); + end + + % add datatips for 3 peaks + dp = datatip(gh,'dataindex',hx15); dp.Location = ""northwest""; + dp = datatip(gh,'dataindex',hx20); + dp = datatip(gh,'dataindex',hx25); + + if msave + %% + sdir = fullfile(spm('dir'),'toolbox','cat12','internal','CSx_pbt_test',justnow); + mkdir(sdir); + copyfile(which('cat_vol_pbtsimple'),sdir); + copyfile(which('cat_surf_createCS3'),sdir); + print( fh, fullfile(fileparts(sdir),sprintf('BWPT_result_%s%s.png',ff,justnow)) ,'-dpng') + end + if msave > 1 + close( fh ) + end +end","MATLAB" +"Neurology","ChristianGaser/cat12","internal/cat_example_surfsmooth.m",".m","2770","72","%% function cat_example_volsurfsmooth + +resdir = '/Users/dahnke/Neuroimaging/spm12/toolbox/cat12/tmp'; +%S = '/Users/dahnke/Neuroimaging/spm12/toolbox/cat12/templates_surfaces/lh.central.freesurfer.gii'; +%S = '/Volumes/vbmDB/MRData/vbm12tst/results/deffiles/cat_defaults_rd/BO/surf/lh.central.Collins.gii'; +%S = '/Volumes/vbmDB/MRData/vbm12tst/results/deffiles/cat_defaults_rd/BO/surf/s15mm.lh.thickness.resampled.Collins.gii'; +S = '/Volumes/vbmDB/MRData/vbm12tst/results/deffiles/cat_defaults_rd/BO/surf/s15mm.rh.thickness.resampled.Collins.gii'; +%P = '/Users/dahnke/Neuroimaging/spm12/toolbox/cat12/templates_volumes/Template_T1_IXI555_MNI152.nii'; + +if ~exist(resdir,'dir'), mkdir(resdir); end + +SG = gifti(S); + +s = 32; +ROI.vertex = 59595; % motorcortex +ROI.vertex = 34111; % superior temporal lobe +ROI.vertex = [59595,34111]; % superior temporal lobe +ROI.vertex = [142556,138036,149965,65103]; % superior temporal lobe +ROI.vertex = [138036,96286,62104]; % superior temporal lobe +ROI.xyz = SG.vertices(ROI.vertex,:); +sinfo = cat_surf_info(S); + +%% -- Volume smoothing ---------------------------------------------------- +% smooth volume +V = spm_vol(P); +Y = zeros(V.dim,'single'); +mati = spm_imatrix(V.mat); % .*sign(mati(7:9)) +for pi=1:numel(ROI.vertex) + ROI.xyz2 = round((ROI.xyz(pi,:) - mati(1:3))./mati(7:9)); + Y(sub2ind(V.dim,ROI.xyz2(1),ROI.xyz2(2),ROI.xyz2(3))) = 1000; +end +spm_smooth(Y,Y,repmat(s/1.5,1,3)); +Y = Y + 1; +V.fname = fullfile(resdir,sprintf('cat_example_volsurfsmooth_v%0.0fs%0.0f_vol.%s.nii',ROI.vertex(1),s,sinfo.name)); +V.dt(1) = 16; +spm_write_vol(V,Y); + +% project volume to surface +job = struct(); +job.data_mesh_lh = S; +job.data_vol = {V.fname}; +job.mapping.abs_mapping.startpoint = -0.5; +job.mapping.abs_mapping.endpoint = +0.5; +job.mapping.abs_mapping.stepsize = 1; +job.datafieldname = sprintf('cat_example_volsurfsmooth_v%0.0fs%0.0f_vol',ROI.vertex(1),s); +cat_surf_vol2surf(job); + +%% -- Surface smoothing --------------------------------------------------- +% create mapping +copyfile(S,resdir); +copyfile(sinfo.Psphere,resdir); +SG.cdata = ones(size(SG.vertices,1),1); +for pi=1:numel(ROI.vertex) + SG.cdata(ROI.vertex(pi)) = 1000; +end +if sinfo.resampled, res = 'resampled.'; else res = ''; end +SS1 = fullfile(resdir,sprintf('lh.cat_example_volsurfsmooth_v%ds%0.0f_catblur.%s%s.gii',ROI.vertex(1),s,res,sinfo.name)); +SS2 = fullfile(resdir,sprintf('lh.cat_example_volsurfsmooth_v%ds%0.0f_spmblur.%s%s.gii',ROI.vertex(1),s,res,sinfo.name)); +save(gifti(SG),SS1); +save(gifti(SG),SS2); +% smoothing +job = struct(); +job.data = {SS1}; +job.fwhm = s*1; +job.datafieldname = sprintf('surfsmooth_%d',ROI.vertex(1)); +job.catblur = 1; +cat_surf_smooth(job); +% smoothing 2 +job.data = {SS2}; +job.catblur = 0; +cat_surf_smooth(job); +","MATLAB" +"Neurology","ChristianGaser/cat12","internal/cat_vol_gbdist.m",".m","8007","216","function varargout = cat_vol_gbdist(I,M,bth,side,interp,BP,IVR,IMinf) +%cat_vol_gbdist. Voxel-based distance estimation. +% ______________________________________________________________________ +% Calculates the distance of all points p with I(p)>lth and I(p)2 && isstruct(bth) + else + % check input + if ~exist('bth','var'), bth=eps; end + if ~exist('side','var'), side=1; else side=sign(side); end + if side==0, error('side must be a positive or negativ number'); end + if ~exist('interp','var'), interp=0; end + if ~exist('BP','var'), BP=[]; end + if ~isempty(BP) && size(BP,2)~=3, error('only 3d'); end + % if ~exist('IVR','var'); IVR=1; end + if ~exist('IMinf','var'); IMinf=0; end + end + if isa(I,'double'), I=single(I); end + if ~exist('M','var'), M = Ifaceth, VBI=reducepatch(VBI,faceth); end; + VB=VB.vertices; VBI=VBI.vertices; + VB=unique([VB;VBI],'rows'); clear VBI; + else + if ~isempty(VB) && size(VB.faces,1)>faceth, VB=reducepatch(VB,faceth); end; + VB=VB.vertices; + end + clear I; + + % add other boundary points + if ~isempty(BP), VB=unique([VB;BP],'rows'); end + + try %#ok error + [x,xi]=intersect(VR,VB,'rows'); + VR(xi,:)=[]; VRi(xi)=[]; + clear x xi; + end + + % create delaunayn triangularisation - error if failed + save('gbdisttmp.mat','VR','VRi','signI'); clear VR Ri signI; + T=delaunayn(VB); if ~exist('T','var'), error('Delaunayn triangulation failed.'); end + load('gbdisttmp.mat','VR'); + + try + [VID,VDD] = dsearchn(VB,T,VR); + catch %#ok + npoints = size(VB,1); + maxpartsize = 1000; + parts = max(1,ceil(npoints / maxpartsize)); + partsize = floor(npoints/(parts)); + VDD=zeros(size(VR,1),1,'single'); + if nargout==2, VID=zeros(size(VR,1),1,'single'); end + for p = 1:parts + [l,h] = getrange(p,partsize,parts,npoints); + [VIDt,VDDt] = dsearchn(VB,T,VR(l:h,:)); + VDD(l:h) = single(VDDt); + if nargout==2, VID(l:h) = single(VIDt); end + end + end + clear VR T; + load('gbdisttmp.mat','VRi','signI'); delete('gbdisttmp.mat'); + + if IMinf + varargout{1}=inf(sizeI,'single'); + else + varargout{1}=zeros(sizeI,'single'); + end; + varargout{1}(VRi) = VDD; + varargout{1} = side * varargout{1} .* (1 - 2*single(signI)); % setup side + varargout{1}(isnan(varargout{1}))=0; % remove nans + + if nargout==2 + varargout{2} = reshape(1:prod(sizeI),sizeI); + varargout{2}(VRi) = sub2ind(sizeI,max(1,min(sizeI(1),round(VB(VID,2)))),max(1,min(sizeI(2),round(VB(VID,1)))),max(1,min(sizeI(3),round(VB(VID,3))))); + end +end +function S=cat_surf_meshinterp(S,interp,method,distth) + if ~exist('interp','var'), interp = 1; else interp=single(interp); end + if interp==0, return, end + if ~exist('method','var'), method = 'linear'; end + + if ~isfield(S,'vertices') || size(S.vertices,1)==0, warning('Meshinterp:NoVertices','S has no vertices'); return; end + if ~isfield(S,'faces') || size(S.faces,1)==0, warning('Meshinterp:NoFaces','S has no faces'); return; end + if ~isfield(S,'facevertexcdata') || size(S.facevertexcdata,1)==0; else C=S.facevertexcdata; end + if exist('C','var'); CT=(size(C,1)==size(S.vertices,1))+1; else CT=0; end + + V=S.vertices; F=single(S.faces); clear S; + + for i=1:interp + nV=single(size(V,1)); nF=single(size(F,1)); + + NF=(1:nF)'; + + switch method + case 'linear' + + % addition vertices (middle of the edge) + V1 = V(F(:,1),:) + 0.5*diff(cat(3,V(F(:,1),:),V(F(:,2),:)),1,3); + V2 = V(F(:,2),:) + 0.5*diff(cat(3,V(F(:,2),:),V(F(:,3),:)),1,3); + V3 = V(F(:,3),:) + 0.5*diff(cat(3,V(F(:,3),:),V(F(:,1),:)),1,3); + + % new faces which replace the old one + F1 = [F(:,1), nV + 2*nF + NF, nV + NF]; + F2 = [F(:,2), nV + NF, nV + nF + NF]; + F3 = [F(:,3), nV + nF + NF, nV + 2*nF + NF]; + F4 = [nV + NF, nV + 2*nF + NF, nV + nF + NF]; + + % colors + if CT==2, C=[C;nanmean(C(F(:,1),:),C(F(:,2),:));nanmean(C(F(:,2),:),C(F(:,3),:));nanmean(C(F(:,3),:),C(F(:,1),:))]; %#ok + elseif CT==1, C=repmat(C,4,1); + end + + V = [V;V1;V2;V3]; clear V1 V2 V3; %#ok + F = [F1;F2;F3;F4]; clear F1 F2 F3 F4; + + % remove double vertices + if CT==0, [V,F] = reduce_points(V,F); + else [V,F,C] = reduce_points(V,F,C); + end + + case 'dist' + if ~exist('distth','var'), distth=sqrt(2); end + + % addition vertices (middle of the edge) + E1 = diff(cat(3,V(F(:,1),:),V(F(:,2),:)),1,3); + E2 = diff(cat(3,V(F(:,2),:),V(F(:,3),:)),1,3); + E3 = diff(cat(3,V(F(:,3),:),V(F(:,1),:)),1,3); + + V1 = V(F(:,1),:) + repmat((sum(E1.^2,2).^0.5)>=distth,1,3) .* (0.5*E1); + V2 = V(F(:,2),:) + repmat((sum(E2.^2,2).^0.5)>=distth,1,3) .* (0.5*E2); + V3 = V(F(:,3),:) + repmat((sum(E3.^2,2).^0.5)>=distth,1,3) .* (0.5*E3); + + % new faces which replace the old one + F1 = [F(:,1), nV + 2*nF + NF, nV + NF]; + F2 = [F(:,2), nV + NF, nV + nF + NF]; + F3 = [F(:,3), nV + nF + NF, nV + 2*nF + NF]; + F4 = [nV + NF, nV + 2*nF + NF, nV + nF + NF]; + + % colors + if CT==2, C=[C;nanmean(C(F(:,1),:),C(F(:,2),:));nanmean(C(F(:,2),:),C(F(:,3),:));nanmean(C(F(:,3),:),C(F(:,1),:))]; %#ok + elseif CT==1, C=repmat(C,4,1); + end + + V = [V;V1;V2;V3]; clear V1 V2 V3; %#ok + F = [F1;F2;F3;F4]; clear F1 F2 F3 F4; + + + % remove double vertices + if CT==0, [V,F] = reduce_points(V,F); + else [V,F,C] = reduce_points(V,F,C); + end + + % remove degnerated faces + F((F(:,1)==F(:,2)) | (F(:,1)==F(:,3)) | (F(:,2)==F(:,3)),:)=[]; + + otherwise + error('ERROR: Unknown method ""%s""',method); + end + end + S.vertices = V; S.faces = double(F); if exist('C','var'), S.facevertexcdata = C; end +end +function [V,F,C]=reduce_points(V,F,C) + try + [V,~,j] = unique(V, 'rows'); + catch %#ok + V=single(V); + [V,~,j] = unique(V, 'rows'); + end + j(end+1) = nan; + F(isnan(F)) = length(j); + if size(F,1)==1, F = j(F)'; if exist('C','var'), C=j(C)'; end + else F = j(F); if exist('C','var'), C=j(C); end + end +end +","MATLAB" +"Neurology","ChristianGaser/cat12","internal/cat_io_findjobj.m",".m","166710","3445","function [handles,levels,parentIdx,listing] = findjobj(container,varargin) %#ok<*CTCH,*ASGLU,*MSNU,*NASGU> +%findjobj Find java objects contained within a specified java container or Matlab GUI handle +% +% Syntax: +% [handles, levels, parentIds, listing] = findjobj(container, 'PropName',PropValue(s), ...) +% +% Input parameters: +% container - optional handle to java container uipanel or figure. If unsupplied then current figure will be used +% 'PropName',PropValue - optional list of property pairs (case insensitive). PropName may also be named -PropName +% 'position' - filter results based on those elements that contain the specified X,Y position or a java element +% Note: specify a Matlab position (X,Y = pixels from bottom left corner), not a java one +% 'size' - filter results based on those elements that have the specified W,H (in pixels) +% 'class' - filter results based on those elements that contain the substring (or java class) PropValue +% Note1: filtering is case insensitive and relies on regexp, so you can pass wildcards etc. +% Note2: '-class' is an undocumented findobj PropName, but only works on Matlab (not java) classes +% 'property' - filter results based on those elements that possess the specified case-insensitive property string +% Note1: passing a property value is possible if the argument following 'property' is a cell in the +% format of {'propName','propValue'}. Example: FINDJOBJ(...,'property',{'Text','click me'}) +% Note2: partial property names (e.g. 'Tex') are accepted, as long as they're not ambiguous +% 'depth' - filter results based on specified depth. 0=top-level, Inf=all levels (default=Inf) +% 'flat' - same as specifying: 'depth',0 +% 'not' - negates the following filter: 'not','class','c' returns all elements EXCEPT those with class 'c' +% 'persist' - persist figure components information, allowing much faster results for subsequent invocations +% 'nomenu' - skip menu processing, for ""lean"" list of handles & much faster processing; +% This option is the default for HG containers but not for figure, Java or no container +% 'print' - display all java elements in a hierarchical list, indented appropriately +% Note1: optional PropValue of element index or handle to java container +% Note2: normally this option would be placed last, after all filtering is complete. Placing this +% option before some filters enables debug print-outs of interim filtering results. +% Note3: output is to the Matlab command window unless the 'listing' (4th) output arg is requested +% 'list' - same as 'print' +% 'debug' - list found component positions in the Command Window +% +% Output parameters: +% handles - list of handles to java elements +% levels - list of corresponding hierarchy level of the java elements (top=0) +% parentIds - list of indexes (in unfiltered handles) of the parent container of the corresponding java element +% listing - results of 'print'/'list' options (empty if these options were not specified) +% +% Note: If no output parameter is specified, then an interactive window will be displayed with a +% ^^^^ tree view of all container components, their properties and callbacks. +% +% Examples: +% findjobj; % display list of all javaelements of currrent figure in an interactive GUI +% handles = findjobj; % get list of all java elements of current figure (inc. menus, toolbars etc.) +% findjobj('print'); % list all java elements in current figure +% findjobj('print',6); % list all java elements in current figure, contained within its 6th element +% handles = findjobj(hButton); % hButton is a matlab button +% handles = findjobj(gcf,'position',getpixelposition(hButton,1)); % same as above but also return hButton's panel +% handles = findjobj(hButton,'persist'); % same as above, persist info for future reuse +% handles = findjobj('class','pushbutton'); % get all pushbuttons in current figure +% handles = findjobj('class','pushbutton','position',123,456); % get all pushbuttons at the specified position +% handles = findjobj(gcf,'class','pushbutton','size',23,15); % get all pushbuttons with the specified size +% handles = findjobj('property','Text','not','class','button'); % get all non-button elements with 'text' property +% handles = findjobj('-property',{'Text','click me'}); % get all elements with 'text' property = 'click me' +% +% Sample usage: +% hButton = uicontrol('string','click me'); +% jButton = findjobj(hButton,'nomenu'); +% % or: jButton = findjobj('property',{'Text','click me'}); +% jButton.setFlyOverAppearance(1); +% jButton.setCursor(java.awt.Cursor.getPredefinedCursor(java.awt.Cursor.HAND_CURSOR)); +% set(jButton,'FocusGainedCallback',@myMatlabFunction); % some 30 callback points available... +% jButton.get; % list all changeable properties... +% +% hEditbox = uicontrol('style','edit'); +% jEditbox = findjobj(hEditbox,'nomenu'); +% jEditbox.setCaretColor(java.awt.Color.red); +% jEditbox.KeyTypedCallback = @myCallbackFunc; % many more callbacks where this came from... +% jEdit.requestFocus; +% +% Technical explanation & details: +% http://undocumentedmatlab.com/blog/findjobj/ +% http://undocumentedmatlab.com/blog/findjobj-gui-display-container-hierarchy/ +% +% Known issues/limitations: +% - Cannot currently process multiple container objects - just one at a time +% - Initial processing is a bit slow when the figure is laden with many UI components (so better use 'persist') +% - Passing a simple container Matlab handle is currently filtered by its position+size: should find a better way to do this +% - Matlab uipanels are not implemented as simple java panels, and so they can't be found using this utility +% - Labels have a write-only text property in java, so they can't be found using the 'property',{'Text','string'} notation +% +% Warning: +% This code heavily relies on undocumented and unsupported Matlab functionality. +% It works on Matlab 7+, but use at your own risk! +% +% Bugs and suggestions: +% Please send to Yair Altman (altmany at gmail dot com) +% +% Change log: +% 2017-04-13: Fixed two edge-cases (one suggested by H. Koch) +% 2016-04-19: Fixed edge-cases in old Matlab release; slightly improved performance even further +% 2016-04-14: Improved performance for the most common use-case (single input/output): improved code + allow inspecting groot +% 2016-04-11: Improved performance for the most common use-case (single input/output) +% 2015-01-12: Differentiate between overlapping controls (for example in different tabs); fixed case of docked figure +% 2014-10-20: Additional fixes for R2014a, R2014b +% 2014-10-13: Fixes for R2014b +% 2014-01-04: Minor fix for R2014a; check for newer FEX version up to twice a day only +% 2013-12-29: Only check for newer FEX version in non-deployed mode; handled case of invisible figure container +% 2013-10-08: Fixed minor edge case (retrieving multiple scroll-panes) +% 2013-06-30: Additional fixes for the upcoming HG2 +% 2013-05-15: Fix for the upcoming HG2 +% 2013-02-21: Fixed HG-Java warnings +% 2013-01-23: Fixed callbacks table grouping & editing bugs; added hidden properties to the properties tooltip; updated help section +% 2013-01-13: Improved callbacks table; fixed tree refresh failure; fixed: tree node-selection didn't update the props pane nor flash the selected component +% 2012-07-25: Fixes for R2012a as well as some older Matlab releases +% 2011-12-07: Fixed 'File is empty' messages in compiled apps +% 2011-11-22: Fix suggested by Ward +% 2011-02-01: Fixes for R2011a +% 2010-06-13: Fixes for R2010b; fixed download (m-file => zip-file) +% 2010-04-21: Minor fix to support combo-boxes (aka drop-down, popup-menu) on Windows +% 2010-03-17: Important release: Fixes for R2010a, debug listing, objects not found, component containers that should be ignored etc. +% 2010-02-04: Forced an EDT redraw before processing; warned if requested handle is invisible +% 2010-01-18: Found a way to display label text next to the relevant node name +% 2009-10-28: Fixed uitreenode warning +% 2009-10-27: Fixed auto-collapse of invisible container nodes; added dynamic tree tooltips & context-menu; minor fix to version-check display +% 2009-09-30: Fix for Matlab 7.0 as suggested by Oliver W; minor GUI fix (classname font) +% 2009-08-07: Fixed edge-case of missing JIDE tables +% 2009-05-24: Added support for future Matlab versions that will not support JavaFrame +% 2009-05-15: Added sanity checks for axes items +% 2009-04-28: Added 'debug' input arg; increased size tolerance 1px => 2px +% 2009-04-23: Fixed location of popupmenus (always 20px high despite what's reported by Matlab...); fixed uiinspect processing issues; added blog link; narrower action buttons +% 2009-04-09: Automatic 'nomenu' for uicontrol inputs; significant performance improvement +% 2009-03-31: Fixed position of some Java components; fixed properties tooltip; fixed node visibility indication +% 2009-02-26: Indicated components visibility (& auto-collapse non-visible containers); auto-highlight selected component; fixes in node icons, figure title & tree refresh; improved error handling; display FindJObj version update description if available +% 2009-02-24: Fixed update check; added dedicated labels icon +% 2009-02-18: Fixed compatibility with old Matlab versions +% 2009-02-08: Callbacks table fixes; use uiinspect if available; fix update check according to new FEX website +% 2008-12-17: R2008b compatibility +% 2008-09-10: Fixed minor bug as per Johnny Smith +% 2007-11-14: Fixed edge case problem with class properties tooltip; used existing object icon if available; added checkbox option to hide standard callbacks +% 2007-08-15: Fixed object naming relative property priorities; added sanity check for illegal container arg; enabled desktop (0) container; cleaned up warnings about special class objects +% 2007-08-03: Fixed minor tagging problems with a few Java sub-classes; displayed UIClassID if text/name/tag is unavailable +% 2007-06-15: Fixed problems finding HG components found by J. Wagberg +% 2007-05-22: Added 'nomenu' option for improved performance; fixed 'export handles' bug; fixed handle-finding/display bugs; ""cleaner"" error handling +% 2007-04-23: HTMLized classname tooltip; returned top-level figure Frame handle for figure container; fixed callbacks table; auto-checked newer version; fixed Matlab 7.2 compatibility issue; added HG objects tree +% 2007-04-19: Fixed edge case of missing figure; displayed tree hierarchy in interactive GUI if no output args; workaround for figure sub-menus invisible unless clicked +% 2007-04-04: Improved performance; returned full listing results in 4th output arg; enabled partial property names & property values; automatically filtered out container panels if children also returned; fixed finding sub-menu items +% 2007-03-20: First version posted on the MathWorks file exchange: http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=14317 +% +% See also: +% java, handle, findobj, findall, javaGetHandles, uiinspect (on the File Exchange) + +% License to use and modify this code is granted freely to all interested, as long as the original author is +% referenced and attributed as such. The original author maintains the right to be solely associated with this work. + +% Programmed and Copyright by Yair M. Altman: altmany(at)gmail.com +% $Revision$ $Date$ +% ______________________________________________________________________ +% +% Christian Gaser, Robert Dahnke +% Structural Brain Mapping Group (https://neuro-jena.github.io) +% Departments of Neurology and Psychiatry +% Jena University Hospital +% ______________________________________________________________________ +% $Id$ + + % Ensure Java AWT is enabled + error(javachk('awt')); + + persistent pContainer pHandles pLevels pParentIdx pPositions + + try + % Initialize + handles = handle([]); + levels = []; + parentIdx = []; + positions = []; % Java positions start at the top-left corner + %sizes = []; + listing = ''; + hg_levels = []; + hg_handles = handle([]); % HG handles are double + hg_parentIdx = []; + nomenu = false; + menuBarFoundFlag = false; + hFig = []; + + % Force an EDT redraw before processing, to ensure all uicontrols etc. are rendered + drawnow; pause(0.02); + + % Default container is the current figure's root panel + if nargin + if isempty(container) % empty container - bail out + return; + elseif ischar(container) % container skipped - this is part of the args list... + varargin = [{container}, varargin]; + origContainer = getCurrentFigure; + [container,contentSize] = getRootPanel(origContainer); + elseif isequal(container,0) % root + origContainer = handle(container); + container = com.mathworks.mde.desk.MLDesktop.getInstance.getMainFrame; + contentSize = [container.getWidth, container.getHeight]; + elseif ishghandle(container) % && ~isa(container,'java.awt.Container') + container = container(1); % another current limitation... + hFig = ancestor(container,'figure'); + origContainer = handle(container); + if isa(origContainer,'uimenu') || isa(origContainer,'matlab.ui.container.Menu') + % getpixelposition doesn't work for menus... - damn! + varargin = {'class','MenuPeer', 'property',{'Label',strrep(get(container,'Label'),'&','')}, varargin{:}}; + elseif ~isa(origContainer, 'figure') && ~isempty(hFig) && ~isa(origContainer, 'matlab.ui.Figure') + % For a single input & output, try using the fast variant + if nargin==1 && nargout==1 + try + handles = findjobj_fast(container); + if ~isempty(handles) + try handles = handle(handles,'callbackproperties'); catch, end + return + end + catch + % never mind - proceed normally using the slower variant below... + end + end + + % See limitations section above: should find a better way to directly refer to the element's java container + try + % Note: 'PixelBounds' is undocumented and unsupported, but much faster than getpixelposition! + % ^^^^ unfortunately, its Y position is inaccurate in some cases - damn! + %size = get(container,'PixelBounds'); + pos = fix(getpixelposition(container,1)); + %varargin = {'position',pos(1:2), 'size',pos(3:4), 'not','class','java.awt.Panel', varargin{:}}; + catch + try + figName = get(hFig,'name'); + if strcmpi(get(hFig,'number'),'on') + figName = regexprep(['Figure ' num2str(hFig) ': ' figName],': $',''); + end + mde = com.mathworks.mde.desk.MLDesktop.getInstance; + jFig = mde.getClient(figName); + if isempty(jFig), error('dummy'); end + catch + warning('off','MATLAB:HandleGraphics:ObsoletedProperty:JavaFrame'); % R2008b compatibility + jFig = get(get(hFig,'JavaFrame'),'FigurePanelContainer'); + end + pos = []; + try + pxsize = get(container,'PixelBounds'); + pos = [pxsize(1)+5, jFig.getHeight - (pxsize(4)-5)]; + catch + % never mind... + end + end + if size(pos,2) == 2 + pos(:,3:4) = 0; + end + if ~isempty(pos) + if isa(handle(container),'uicontrol') && strcmp(get(container,'style'),'popupmenu') + % popupmenus (combo-box dropdowns) are always 20px high + pos(2) = pos(2) + pos(4) - 20; + pos(4) = 20; + end + %varargin = {'position',pos(1:2), 'size',size(3:4)-size(1:2)-10, 'not','class','java.awt.Panel', varargin{:}}; + varargin = {'position',pos(1:2)+[0,pos(4)], 'size',pos(3:4), 'not','class','java.awt.Panel', 'nomenu', varargin{:}}; + end + elseif isempty(hFig) + hFig = handle(container); + end + [container,contentSize] = getRootPanel(hFig); + elseif isjava(container) + % Maybe a java container obj (will crash otherwise) + origContainer = container; + contentSize = [container.getWidth, container.getHeight]; + else + error('YMA:findjobj:IllegalContainer','Input arg does not appear to be a valid GUI object'); + end + else + % Default container = current figure + origContainer = getCurrentFigure; + [container,contentSize] = getRootPanel(origContainer); + end + + % Check persistency + if isequal(pContainer,container) + % persistency requested and the same container is reused, so reuse the hierarchy information + [handles,levels,parentIdx,positions] = deal(pHandles, pLevels, pParentIdx, pPositions); + else + % Pre-allocate space of complex data containers for improved performance + handles = repmat(handles,1,1000); + positions = zeros(1000,2); + + % Check whether to skip menu processing + nomenu = paramSupplied(varargin,'nomenu'); + + % Traverse the container hierarchy and extract the elements within + traverseContainer(container,0,1); + + % Remove unnecessary pre-allocated elements + dataLen = length(levels); + handles (dataLen+1:end) = []; + positions(dataLen+1:end,:) = []; + end + + % Process persistency check before any filtering is done + if paramSupplied(varargin,'persist') + [pContainer, pHandles, pLevels, pParentIdx, pPositions] = deal(container,handles,levels,parentIdx,positions); + end + + % Save data for possible future use in presentObjectTree() below + allHandles = handles; + allLevels = levels; + allParents = parentIdx; + selectedIdx = 1:length(handles); + %[positions(:,1)-container.getX, container.getHeight - positions(:,2)] + + % Debug-list all found compponents and their positions + if paramSupplied(varargin,'debug') + for origHandleIdx = 1 : length(allHandles) + thisObj = handles(origHandleIdx); + pos = sprintf('%d,%d %dx%d',[positions(origHandleIdx,:) getWidth(thisObj) getHeight(thisObj)]); + disp([repmat(' ',1,levels(origHandleIdx)) '[' pos '] ' char(toString(thisObj))]); + end + end + + % Process optional args + % Note: positions is NOT returned since it's based on java coord system (origin = top-left): will confuse Matlab users + processArgs(varargin{:}); + + % De-cell and trim listing, if only one element was found (no use for indented listing in this case) + if iscell(listing) && length(listing)==1 + listing = strtrim(listing{1}); + end + + % If no output args and no listing requested, present the FINDJOBJ interactive GUI + if nargout == 0 && isempty(listing) + + % Get all label positions + hg_labels = []; + labelPositions = getLabelsJavaPos(container); + + % Present the GUI (object tree) + if ~isempty(container) + presentObjectTree(); + else + warnInvisible(varargin{:}); + end + + % Display the listing, if this was specifically requested yet no relevant output arg was specified + elseif nargout < 4 && ~isempty(listing) + if ~iscell(listing) + disp(listing); + else + for listingIdx = 1 : length(listing) + disp(listing{listingIdx}); + end + end + end + + % If the number of output handles does not match the number of inputs, try to match via tooltips + if nargout && numel(handles) ~= numel(origContainer) + newHandles = handle([]); + switchHandles = false; + handlesToCheck = handles; + if isempty(handles) + handlesToCheck = allHandles; + end + for origHandleIdx = 1 : numel(origContainer) + try + thisContainer = origContainer(origHandleIdx); + if isa(thisContainer,'figure') || isa(thisContainer,'matlab.ui.Figure') + break; + end + try + newHandles(origHandleIdx) = handlesToCheck(origHandleIdx); %#ok + catch + % maybe no corresponding handle in [handles] + end + + % Assign a new random tooltip to the original (Matlab) handle + oldTooltip = get(thisContainer,'Tooltip'); + newTooltip = num2str(rand,99); + set(thisContainer,'Tooltip',newTooltip); + drawnow; % force the Java handle to sync with the Matlab prop-change + try + % Search for a Java handle that has the newly-generated tooltip + for newHandleIdx = 1 : numel(handlesToCheck) + testTooltip = ''; + thisHandle = handlesToCheck(newHandleIdx); + try + testTooltip = char(thisHandle.getToolTipText); + catch + try testTooltip = char(thisHandle.getTooltipText); catch, end + end + if isempty(testTooltip) + % One more attempt - assume it's enclosed by a scroll-pane + try testTooltip = char(thisHandle.getViewport.getView.getToolTipText); catch, end + end + if strcmp(testTooltip, newTooltip) + newHandles(origHandleIdx) = thisHandle; + switchHandles = true; + break; + end + end + catch + % never mind - skip to the next handle + end + set(thisContainer,'Tooltip',oldTooltip); + catch + % never mind - skip to the next handle (maybe handle doesn't have a tooltip prop) + end + end + if switchHandles + handles = newHandles; + end + end + + % Display a warning if the requested handle was not found because it's invisible + if nargout && isempty(handles) + warnInvisible(varargin{:}); + end + + return; %debug point + + catch + % 'Cleaner' error handling - strip the stack info etc. + err = lasterror; %#ok + err.message = regexprep(err.message,'Error using ==> [^\n]+\n',''); + if isempty(strfind(mfilename,err.message)) + % Indicate error origin, if not already stated within the error message + err.message = [mfilename ': ' err.message]; + end + rethrow(err); + end + + %% Display a warning if the requested handle was not found because it's invisible + function warnInvisible(varargin) + try + if strcmpi(get(hFig,'Visible'),'off') + pos = get(hFig,'Position'); + set(hFig, 'Position',pos-[5000,5000,0,0], 'Visible','on'); + drawnow; pause(0.01); + [handles,levels,parentIdx,listing] = findjobj(origContainer,varargin{:}); + set(hFig, 'Position',pos, 'Visible','off'); + end + catch + % ignore - move on... + end + try + stk = dbstack; + stkNames = {stk.name}; + OutputFcnIdx = find(~cellfun(@isempty,regexp(stkNames,'_OutputFcn'))); + if ~isempty(OutputFcnIdx) + OutputFcnName = stkNames{OutputFcnIdx}; + warning('YMA:FindJObj:OutputFcn',['No Java reference was found for the requested handle, because the figure is still invisible in ' OutputFcnName '()']); + elseif ishandle(origContainer) && isprop(origContainer,'Visible') && strcmpi(get(origContainer,'Visible'),'off') + warning('YMA:FindJObj:invisibleHandle','No Java reference was found for the requested handle, probably because it is still invisible'); + end + catch + % Never mind... + end + end + + %% Check existence of a (case-insensitive) optional parameter in the params list + function [flag,idx] = paramSupplied(paramsList,paramName) + %idx = find(~cellfun('isempty',regexpi(paramsList(cellfun(@ischar,paramsList)),['^-?' paramName]))); + idx = find(~cellfun('isempty',regexpi(paramsList(cellfun('isclass',paramsList,'char')),['^-?' paramName]))); % 30/9/2009 fix for ML 7.0 suggested by Oliver W + flag = any(idx); + end + + %% Get current figure (even if its 'HandleVisibility' property is 'off') + function curFig = getCurrentFigure + oldShowHidden = get(0,'ShowHiddenHandles'); + set(0,'ShowHiddenHandles','on'); % minor fix per Johnny Smith + curFig = gcf; + set(0,'ShowHiddenHandles',oldShowHidden); + end + + %% Get Java reference to top-level (root) panel - actually, a reference to the java figure + function [jRootPane,contentSize] = getRootPanel(hFig) + try + contentSize = [0,0]; % initialize + jRootPane = hFig; + figName = get(hFig,'name'); + if strcmpi(get(hFig,'number'),'on') + figName = regexprep(['Figure ' num2str(hFig) ': ' figName],': $',''); + end + mde = com.mathworks.mde.desk.MLDesktop.getInstance; + jFigPanel = mde.getClient(figName); + jRootPane = jFigPanel; + jRootPane = jFigPanel.getRootPane; + catch + try + warning('off','MATLAB:HandleGraphics:ObsoletedProperty:JavaFrame'); % R2008b compatibility + jFrame = get(hFig,'JavaFrame'); + jFigPanel = get(jFrame,'FigurePanelContainer'); + jRootPane = jFigPanel; + jRootPane = jFigPanel.getComponent(0).getRootPane; + catch + % Never mind + end + end + try + % If invalid RootPane - try another method... + warning('off','MATLAB:HandleGraphics:ObsoletedProperty:JavaFrame'); % R2008b compatibility + jFrame = get(hFig,'JavaFrame'); + jAxisComponent = get(jFrame,'AxisComponent'); + jRootPane = jAxisComponent.getParent.getParent.getRootPane; + catch + % Never mind + end + try + % If invalid RootPane, retry up to N times + tries = 10; + while isempty(jRootPane) && tries>0 % might happen if figure is still undergoing rendering... + drawnow; pause(0.001); + tries = tries - 1; + jRootPane = jFigPanel.getComponent(0).getRootPane; + end + + % If still invalid, use FigurePanelContainer which is good enough in 99% of cases... (menu/tool bars won't be accessible, though) + if isempty(jRootPane) + jRootPane = jFigPanel; + end + contentSize = [jRootPane.getWidth, jRootPane.getHeight]; + + % Try to get the ancestor FigureFrame + jRootPane = jRootPane.getTopLevelAncestor; + catch + % Never mind - FigurePanelContainer is good enough in 99% of cases... (menu/tool bars won't be accessible, though) + end + end + + %% Traverse the container hierarchy and extract the elements within + function traverseContainer(jcontainer,level,parent) + persistent figureComponentFound menuRootFound + + % Record the data for this node + %disp([repmat(' ',1,level) '<= ' char(jcontainer.toString)]) + thisIdx = length(levels) + 1; + levels(thisIdx) = level; + parentIdx(thisIdx) = parent; + try newHandle = handle(jcontainer,'callbackproperties'); catch, newHandle = handle(jcontainer); end + try handles(thisIdx) = newHandle; catch, handles = newHandle; end + try + positions(thisIdx,:) = getXY(jcontainer); + %sizes(thisIdx,:) = [jcontainer.getWidth, jcontainer.getHeight]; + catch + positions(thisIdx,:) = [0,0]; + %sizes(thisIdx,:) = [0,0]; + end + if level>0 + positions(thisIdx,:) = positions(thisIdx,:) + positions(parent,:); + if ~figureComponentFound && ... + strcmp(jcontainer.getName,'fComponentContainer') && ... + isa(jcontainer,'com.mathworks.hg.peer.FigureComponentContainer') % there are 2 FigureComponentContainers - only process one... + + % restart coordinate system, to exclude menu & toolbar areas + positions(thisIdx,:) = positions(thisIdx,:) - [jcontainer.getRootPane.getX, jcontainer.getRootPane.getY]; + figureComponentFound = true; + end + elseif level==1 + positions(thisIdx,:) = positions(thisIdx,:) + positions(parent,:); + else + % level 0 - initialize flags used later + figureComponentFound = false; + menuRootFound = false; + end + parentId = length(parentIdx); + + % Traverse Menu items, unless the 'nomenu' option was requested + if ~nomenu + try + for child = 1 : getNumMenuComponents(jcontainer) + traverseContainer(jcontainer.getMenuComponent(child-1),level+1,parentId); + end + catch + % Probably not a Menu container, but maybe a top-level JMenu, so discard duplicates + %if isa(handles(end).java,'javax.swing.JMenuBar') + if ~menuRootFound && strcmp(class(java(handles(end))),'javax.swing.JMenuBar') %faster... + if removeDuplicateNode(thisIdx) + menuRootFound = true; + return; + end + end + end + end + + % Now recursively process all this node's children (if any), except menu items if so requested + %if isa(jcontainer,'java.awt.Container') + try % try-catch is faster than checking isa(jcontainer,'java.awt.Container')... + %if jcontainer.getComponentCount, jcontainer.getComponents, end + if ~nomenu || menuBarFoundFlag || isempty(strfind(class(jcontainer),'FigureMenuBar')) + lastChildComponent = java.lang.Object; + child = 0; + while (child < jcontainer.getComponentCount) + childComponent = jcontainer.getComponent(child); + % Looping over menus sometimes causes jcontainer to get mixed up (probably a JITC bug), so identify & fix + if isequal(childComponent,lastChildComponent) + child = child + 1; + childComponent = jcontainer.getComponent(child); + end + lastChildComponent = childComponent; + %disp([repmat(' ',1,level) '=> ' num2str(child) ': ' char(class(childComponent))]) + traverseContainer(childComponent,level+1,parentId); + child = child + 1; + end + else + menuBarFoundFlag = true; % use this flag to skip further testing for FigureMenuBar + end + catch + % do nothing - probably not a container + %dispError + end + + % ...and yet another type of child traversal... + try + if ~isdeployed % prevent 'File is empty' messages in compiled apps + jc = jcontainer.java; + else + jc = jcontainer; + end + for child = 1 : jc.getChildCount + traverseContainer(jc.getChildAt(child-1),level+1,parentId); + end + catch + % do nothing - probably not a container + %dispError + end + + % TODO: Add axis (plot) component handles + end + + %% Get the XY location of a Java component + function xy = getXY(jcontainer) + % Note: getX/getY are better than get(..,'X') (mem leaks), + % ^^^^ but sometimes they fail and revert to getx.m ... + % Note2: try awtinvoke() catch is faster than checking ismethod()... + % Note3: using AWTUtilities.invokeAndWait() directly is even faster than awtinvoke()... + try %if ismethod(jcontainer,'getX') + %positions(thisIdx,:) = [jcontainer.getX, jcontainer.getY]; + cls = getClass(jcontainer); + location = com.mathworks.jmi.AWTUtilities.invokeAndWait(jcontainer,getMethod(cls,'getLocation',[]),[]); + x = location.getX; + y = location.getY; + catch %else + try + x = com.mathworks.jmi.AWTUtilities.invokeAndWait(jcontainer,getMethod(cls,'getX',[]),[]); + y = com.mathworks.jmi.AWTUtilities.invokeAndWait(jcontainer,getMethod(cls,'getY',[]),[]); + catch + try + x = awtinvoke(jcontainer,'getX()'); + y = awtinvoke(jcontainer,'getY()'); + catch + x = get(jcontainer,'X'); + y = get(jcontainer,'Y'); + end + end + end + %positions(thisIdx,:) = [x, y]; + xy = [x,y]; + end + + %% Get the number of menu sub-elements + function numMenuComponents = getNumMenuComponents(jcontainer) + + % The following line will raise an Exception for anything except menus + numMenuComponents = jcontainer.getMenuComponentCount; + + % No error so far, so this must be a menu container... + % Note: Menu subitems are not visible until the top-level (root) menu gets initial focus... + % Try several alternatives, until we get a non-empty menu (or not...) + % TODO: Improve performance - this takes WAY too long... + if jcontainer.isTopLevelMenu && (numMenuComponents==0) + jcontainer.requestFocus; + numMenuComponents = jcontainer.getMenuComponentCount; + if (numMenuComponents == 0) + drawnow; pause(0.001); + numMenuComponents = jcontainer.getMenuComponentCount; + if (numMenuComponents == 0) + jcontainer.setSelected(true); + numMenuComponents = jcontainer.getMenuComponentCount; + if (numMenuComponents == 0) + drawnow; pause(0.001); + numMenuComponents = jcontainer.getMenuComponentCount; + if (numMenuComponents == 0) + jcontainer.doClick; % needed in order to populate the sub-menu components + numMenuComponents = jcontainer.getMenuComponentCount; + if (numMenuComponents == 0) + drawnow; %pause(0.001); + numMenuComponents = jcontainer.getMenuComponentCount; + jcontainer.doClick; % close menu by re-clicking... + if (numMenuComponents == 0) + drawnow; %pause(0.001); + numMenuComponents = jcontainer.getMenuComponentCount; + end + else + % ok - found sub-items + % Note: no need to close menu since this will be done when focus moves to the FindJObj window + %jcontainer.doClick; % close menu by re-clicking... + end + end + end + jcontainer.setSelected(false); % de-select the menu + end + end + end + end + + %% Remove a specific tree node's data + function nodeRemovedFlag = removeDuplicateNode(thisIdx) + nodeRemovedFlag = false; + for idx = 1 : thisIdx-1 + if isequal(handles(idx),handles(thisIdx)) + levels(thisIdx) = []; + parentIdx(thisIdx) = []; + handles(thisIdx) = []; + positions(thisIdx,:) = []; + %sizes(thisIdx,:) = []; + nodeRemovedFlag = true; + return; + end + end + end + + %% Process optional args + function processArgs(varargin) + + % Initialize + invertFlag = false; + listing = ''; + + % Loop over all optional args + while ~isempty(varargin) && ~isempty(handles) + + % Process the arg (and all its params) + foundIdx = 1 : length(handles); + if iscell(varargin{1}), varargin{1} = varargin{1}{1}; end + if ~isempty(varargin{1}) && varargin{1}(1)=='-' + varargin{1}(1) = []; + end + switch lower(varargin{1}) + case 'not' + invertFlag = true; + case 'position' + [varargin,foundIdx] = processPositionArgs(varargin{:}); + if invertFlag, foundIdx = ~foundIdx; invertFlag = false; end + case 'size' + [varargin,foundIdx] = processSizeArgs(varargin{:}); + if invertFlag, foundIdx = ~foundIdx; invertFlag = false; end + case 'class' + [varargin,foundIdx] = processClassArgs(varargin{:}); + if invertFlag, foundIdx = ~foundIdx; invertFlag = false; end + case 'property' + [varargin,foundIdx] = processPropertyArgs(varargin{:}); + if invertFlag, foundIdx = ~foundIdx; invertFlag = false; end + case 'depth' + [varargin,foundIdx] = processDepthArgs(varargin{:}); + if invertFlag, foundIdx = ~foundIdx; invertFlag = false; end + case 'flat' + varargin = {'depth',0, varargin{min(2:end):end}}; + [varargin,foundIdx] = processDepthArgs(varargin{:}); + if invertFlag, foundIdx = ~foundIdx; invertFlag = false; end + case {'print','list'} + [varargin,listing] = processPrintArgs(varargin{:}); + case {'persist','nomenu','debug'} + % ignore - already handled in main function above + otherwise + error('YMA:findjobj:IllegalOption',['Option ' num2str(varargin{1}) ' is not a valid option. Type ''help ' mfilename ''' for the full options list.']); + end + + % If only parent-child pairs found + foundIdx = find(foundIdx); + if ~isempty(foundIdx) && isequal(parentIdx(foundIdx(2:2:end)),foundIdx(1:2:end)) + % Return just the children (the parent panels are uninteresting) + foundIdx(1:2:end) = []; + end + + % If several possible handles were found and the first is the container of the second + if length(foundIdx) == 2 && isequal(handles(foundIdx(1)).java, handles(foundIdx(2)).getParent) + % Discard the uninteresting component container + foundIdx(1) = []; + end + + % Filter the results + selectedIdx = selectedIdx(foundIdx); + handles = handles(foundIdx); + levels = levels(foundIdx); + parentIdx = parentIdx(foundIdx); + positions = positions(foundIdx,:); + + % Remove this arg and proceed to the next one + varargin(1) = []; + + end % Loop over all args + end + + %% Process 'print' option + function [varargin,listing] = processPrintArgs(varargin) + if length(varargin)<2 || ischar(varargin{2}) + % No second arg given, so use the first available element + listingContainer = handles(1); %#ok - used in evalc below + else + % Get the element to print from the specified second arg + if isnumeric(varargin{2}) && (varargin{2} == fix(varargin{2})) % isinteger doesn't work on doubles... + if (varargin{2} > 0) && (varargin{2} <= length(handles)) + listingContainer = handles(varargin{2}); %#ok - used in evalc below + elseif varargin{2} > 0 + error('YMA:findjobj:IllegalPrintFilter','Print filter index %g > number of available elements (%d)',varargin{2},length(handles)); + else + error('YMA:findjobj:IllegalPrintFilter','Print filter must be a java handle or positive numeric index into handles'); + end + elseif ismethod(varargin{2},'list') + listingContainer = varargin{2}; %#ok - used in evalc below + else + error('YMA:findjobj:IllegalPrintFilter','Print filter must be a java handle or numeric index into handles'); + end + varargin(2) = []; + end + + % use evalc() to capture output into a Matlab variable + %listing = evalc('listingContainer.list'); + + % Better solution: loop over all handles and process them one by one + listing = cell(length(handles),1); + for componentIdx = 1 : length(handles) + listing{componentIdx} = [repmat(' ',1,levels(componentIdx)) char(handles(componentIdx).toString)]; + end + end + + %% Process 'position' option + function [varargin,foundIdx] = processPositionArgs(varargin) + if length(varargin)>1 + positionFilter = varargin{2}; + %if (isjava(positionFilter) || iscom(positionFilter)) && ismethod(positionFilter,'getLocation') + try % try-catch is faster... + % Java/COM object passed - get its position + positionFilter = positionFilter.getLocation; + filterXY = [positionFilter.getX, positionFilter.getY]; + catch + if ~isscalar(positionFilter) + % position vector passed + if (length(positionFilter)>=2) && isnumeric(positionFilter) + % Remember that java coordinates start at top-left corner, Matlab coords start at bottom left... + %positionFilter = java.awt.Point(positionFilter(1), container.getHeight - positionFilter(2)); + filterXY = [container.getX + positionFilter(1), container.getY + contentSize(2) - positionFilter(2)]; + + % Check for full Matlab position vector (x,y,w,h) + %if (length(positionFilter)==4) + % varargin{end+1} = 'size'; + % varargin{end+1} = fix(positionFilter(3:4)); + %end + else + error('YMA:findjobj:IllegalPositionFilter','Position filter must be a java UI component, or X,Y pair'); + end + elseif length(varargin)>2 + % x,y passed as separate arg values + if isnumeric(positionFilter) && isnumeric(varargin{3}) + % Remember that java coordinates start at top-left corner, Matlab coords start at bottom left... + %positionFilter = java.awt.Point(positionFilter, container.getHeight - varargin{3}); + filterXY = [container.getX + positionFilter, container.getY + contentSize(2) - varargin{3}]; + varargin(3) = []; + else + error('YMA:findjobj:IllegalPositionFilter','Position filter must be a java UI component, or X,Y pair'); + end + else + error('YMA:findjobj:IllegalPositionFilter','Position filter must be a java UI component, or X,Y pair'); + end + end + + % Compute the required element positions in order to be eligible for a more detailed examination + % Note: based on the following constraints: 0 <= abs(elementX-filterX) + abs(elementY+elementH-filterY) < 7 + baseDeltas = [positions(:,1)-filterXY(1), positions(:,2)-filterXY(2)]; % faster than repmat()... + %baseHeight = - baseDeltas(:,2);% -abs(baseDeltas(:,1)); + %minHeight = baseHeight - 7; + %maxHeight = baseHeight + 7; + %foundIdx = ~arrayfun(@(b)(invoke(b,'contains',positionFilter)),handles); % ARGH! - disallowed by Matlab! + %foundIdx = repmat(false,1,length(handles)); + %foundIdx(length(handles)) = false; % faster than repmat()... + foundIdx = (abs(baseDeltas(:,1)) < 7) & (abs(baseDeltas(:,2)) < 7); % & (minHeight >= 0); + %fi = find(foundIdx); + %for componentIdx = 1 : length(fi) + %foundIdx(componentIdx) = handles(componentIdx).getBounds.contains(positionFilter); + + % Search for a point no farther than 7 pixels away (prevents rounding errors) + %foundIdx(componentIdx) = handles(componentIdx).getLocationOnScreen.distanceSq(positionFilter) < 50; % fails for invisible components... + + %p = java.awt.Point(positions(componentIdx,1), positions(componentIdx,2) + handles(componentIdx).getHeight); + %foundIdx(componentIdx) = p.distanceSq(positionFilter) < 50; + + %foundIdx(componentIdx) = sum(([baseDeltas(componentIdx,1),baseDeltas(componentIdx,2)+handles(componentIdx).getHeight]).^2) < 50; + + % Following is the fastest method found to date: only eligible elements are checked in detailed + % elementHeight = handles(fi(componentIdx)).getHeight; + % foundIdx(fi(componentIdx)) = elementHeight > minHeight(fi(componentIdx)) && ... + % elementHeight < maxHeight(fi(componentIdx)); + %disp([componentIdx,elementHeight,minHeight(fi(componentIdx)),maxHeight(fi(componentIdx)),foundIdx(fi(componentIdx))]) + %end + + varargin(2) = []; + else + foundIdx = []; + end + end + + %% Process 'size' option + function [varargin,foundIdx] = processSizeArgs(varargin) + if length(varargin)>1 + sizeFilter = lower(varargin{2}); + %if (isjava(sizeFilter) || iscom(sizeFilter)) && ismethod(sizeFilter,'getSize') + try % try-catch is faster... + % Java/COM object passed - get its size + sizeFilter = sizeFilter.getSize; + filterWidth = sizeFilter.getWidth; + filterHeight = sizeFilter.getHeight; + catch + if ~isscalar(sizeFilter) + % size vector passed + if (length(sizeFilter)>=2) && isnumeric(sizeFilter) + %sizeFilter = java.awt.Dimension(sizeFilter(1),sizeFilter(2)); + filterWidth = sizeFilter(1); + filterHeight = sizeFilter(2); + else + error('YMA:findjobj:IllegalSizeFilter','Size filter must be a java UI component, or W,H pair'); + end + elseif length(varargin)>2 + % w,h passed as separate arg values + if isnumeric(sizeFilter) && isnumeric(varargin{3}) + %sizeFilter = java.awt.Dimension(sizeFilter,varargin{3}); + filterWidth = sizeFilter; + filterHeight = varargin{3}; + varargin(3) = []; + else + error('YMA:findjobj:IllegalSizeFilter','Size filter must be a java UI component, or W,H pair'); + end + else + error('YMA:findjobj:IllegalSizeFilter','Size filter must be a java UI component, or W,H pair'); + end + end + %foundIdx = ~arrayfun(@(b)(invoke(b,'contains',sizeFilter)),handles); % ARGH! - disallowed by Matlab! + foundIdx(length(handles)) = false; % faster than repmat()... + for componentIdx = 1 : length(handles) + %foundIdx(componentIdx) = handles(componentIdx).getSize.equals(sizeFilter); + % Allow a 2-pixel tollerance to account for non-integer pixel sizes + foundIdx(componentIdx) = abs(handles(componentIdx).getWidth - filterWidth) <= 3 && ... % faster than getSize.equals() + abs(handles(componentIdx).getHeight - filterHeight) <= 3; + end + varargin(2) = []; + else + foundIdx = []; + end + end + + %% Process 'class' option + function [varargin,foundIdx] = processClassArgs(varargin) + if length(varargin)>1 + classFilter = varargin{2}; + %if ismethod(classFilter,'getClass') + try % try-catch is faster... + classFilter = char(classFilter.getClass); + catch + if ~ischar(classFilter) + error('YMA:findjobj:IllegalClassFilter','Class filter must be a java object, class or string'); + end + end + + % Now convert all java classes to java.lang.Strings and compare to the requested filter string + try + foundIdx(length(handles)) = false; % faster than repmat()... + jClassFilter = java.lang.String(classFilter).toLowerCase; + for componentIdx = 1 : length(handles) + % Note: JVM 1.5's String.contains() appears slightly slower and is available only since Matlab 7.2 + foundIdx(componentIdx) = handles(componentIdx).getClass.toString.toLowerCase.indexOf(jClassFilter) >= 0; + end + catch + % Simple processing: slower since it does extra processing within opaque.char() + for componentIdx = 1 : length(handles) + % Note: using @toChar is faster but returns java String, not a Matlab char + foundIdx(componentIdx) = ~isempty(regexpi(char(handles(componentIdx).getClass),classFilter)); + end + end + + varargin(2) = []; + else + foundIdx = []; + end + end + + %% Process 'property' option + function [varargin,foundIdx] = processPropertyArgs(varargin) + if length(varargin)>1 + propertyName = varargin{2}; + if iscell(propertyName) + if length(propertyName) == 2 + propertyVal = propertyName{2}; + propertyName = propertyName{1}; + elseif length(propertyName) == 1 + propertyName = propertyName{1}; + else + error('YMA:findjobj:IllegalPropertyFilter','Property filter must be a string (case insensitive name of property) or cell array {propName,propValue}'); + end + end + if ~ischar(propertyName) + error('YMA:findjobj:IllegalPropertyFilter','Property filter must be a string (case insensitive name of property) or cell array {propName,propValue}'); + end + propertyName = lower(propertyName); + %foundIdx = arrayfun(@(h)isprop(h,propertyName),handles); % ARGH! - disallowed by Matlab! + foundIdx(length(handles)) = false; % faster than repmat()... + + % Split processing depending on whether a specific property value was requested (ugly but faster...) + if exist('propertyVal','var') + for componentIdx = 1 : length(handles) + try + % Find out whether this element has the specified property + % Note: findprop() and its return value schema.prop are undocumented and unsupported! + prop = findprop(handles(componentIdx),propertyName); % faster than isprop() & enables partial property names + + % If found, compare it to the actual element's property value + foundIdx(componentIdx) = ~isempty(prop) && isequal(get(handles(componentIdx),prop.Name),propertyVal); + catch + % Some Java classes have a write-only property (like LabelPeer with 'Text'), so we end up here + % In these cases, simply assume that the property value doesn't match and continue + foundIdx(componentIdx) = false; + end + end + else + for componentIdx = 1 : length(handles) + try + % Find out whether this element has the specified property + % Note: findprop() and its return value schema.prop are undocumented and unsupported! + foundIdx(componentIdx) = ~isempty(findprop(handles(componentIdx),propertyName)); + catch + foundIdx(componentIdx) = false; + end + end + end + varargin(2) = []; + else + foundIdx = []; + end + end + + %% Process 'depth' option + function [varargin,foundIdx] = processDepthArgs(varargin) + if length(varargin)>1 + level = varargin{2}; + if ~isnumeric(level) + error('YMA:findjobj:IllegalDepthFilter','Depth filter must be a number (=maximal element depth)'); + end + foundIdx = (levels <= level); + varargin(2) = []; + else + foundIdx = []; + end + end + + %% Convert property data into a string + function data = charizeData(data) + if isa(data,'com.mathworks.hg.types.HGCallback') + data = get(data,'Callback'); + end + if ~ischar(data) && ~isa(data,'java.lang.String') + newData = strtrim(evalc('disp(data)')); + try + newData = regexprep(newData,' +',' '); + newData = regexprep(newData,'Columns \d+ through \d+\s',''); + newData = regexprep(newData,'Column \d+\s',''); + catch + %never mind... + end + if iscell(data) + newData = ['{ ' newData ' }']; + elseif isempty(data) + newData = ''; + elseif isnumeric(data) || islogical(data) || any(ishandle(data)) || numel(data) > 1 %&& ~isscalar(data) + newData = ['[' newData ']']; + end + data = newData; + elseif ~isempty(data) + data = ['''' data '''']; + end + end % charizeData + + %% Prepare a hierarchical callbacks table data + function setProp(list,name,value,category) + prop = eval('com.jidesoft.grid.DefaultProperty();'); % prevent JIDE alert by run-time (not load-time) evaluation + prop.setName(name); + prop.setType(java.lang.String('').getClass); + prop.setValue(value); + prop.setEditable(true); + prop.setExpert(true); + %prop.setCategory(['' category ' callbacks']); + prop.setCategory([category ' callbacks']); + list.add(prop); + end % getTreeData + + %% Prepare a hierarchical callbacks table data + function list = getTreeData(data) + list = java.util.ArrayList(); + names = regexprep(data,'([A-Z][a-z]+).*','$1'); + %hash = java.util.Hashtable; + others = {}; + for propIdx = 1 : size(data,1) + if (propIdx < size(data,1) && strcmp(names{propIdx},names{propIdx+1})) || ... + (propIdx > 1 && strcmp(names{propIdx},names{propIdx-1})) + % Child callback property + setProp(list,data{propIdx,1},data{propIdx,2},names{propIdx}); + else + % Singular callback property => Add to 'Other' category at bottom of the list + others(end+1,:) = data(propIdx,:); %#ok + end + end + for propIdx = 1 : size(others,1) + setProp(list,others{propIdx,1},others{propIdx,2},'Other'); + end + end % getTreeData + + %% Get callbacks table data + function [cbData, cbHeaders, cbTableEnabled] = getCbsData(obj, stripStdCbsFlag) + % Initialize + cbData = {'(no callbacks)'}; + cbHeaders = {'Callback name'}; + cbTableEnabled = false; + cbNames = {}; + + try + try + classHdl = classhandle(handle(obj)); + cbNames = get(classHdl.Events,'Name'); + if ~isempty(cbNames) && ~iscom(obj) %only java-based please... + cbNames = strcat(cbNames,'Callback'); + end + propNames = get(classHdl.Properties,'Name'); + catch + % Try to interpret as an MCOS class object + try + oldWarn = warning('off','MATLAB:structOnObject'); + dataFields = struct(obj); + warning(oldWarn); + catch + dataFields = get(obj); + end + propNames = fieldnames(dataFields); + end + propCbIdx = []; + if ischar(propNames), propNames={propNames}; end % handle case of a single callback + if ~isempty(propNames) + propCbIdx = find(~cellfun(@isempty,regexp(propNames,'(Fcn|Callback)$'))); + cbNames = unique([cbNames; propNames(propCbIdx)]); %#ok logical is faster but less debuggable... + end + if ~isempty(cbNames) + if stripStdCbsFlag + cbNames = stripStdCbs(cbNames); + end + if iscell(cbNames) + cbNames = sort(cbNames); + if size(cbNames,1) < size(cbNames,2) + cbNames = cbNames'; + end + end + hgHandleFlag = 0; try hgHandleFlag = ishghandle(obj); catch, end %#ok + try + obj = handle(obj,'CallbackProperties'); + catch + hgHandleFlag = 1; + end + if hgHandleFlag + % HG handles don't allow CallbackProperties - search only for *Fcn + %cbNames = propNames(propCbIdx); + end + if iscom(obj) + cbs = obj.eventlisteners; + if ~isempty(cbs) + cbNamesRegistered = cbs(:,1); + cbData = setdiff(cbNames,cbNamesRegistered); + %cbData = charizeData(cbData); + if size(cbData,2) > size(cbData(1)) + cbData = cbData'; + end + cbData = [cbData, cellstr(repmat(' ',length(cbData),1))]; + cbData = [cbData; cbs]; + [sortedNames, sortedIdx] = sort(cbData(:,1)); + sortedCbs = cellfun(@charizeData,cbData(sortedIdx,2),'un',0); + cbData = [sortedNames, sortedCbs]; + else + cbData = [cbNames, cellstr(repmat(' ',length(cbNames),1))]; + end + elseif iscell(cbNames) + cbNames = sort(cbNames); + %cbData = [cbNames, get(obj,cbNames)']; + cbData = cbNames; + oldWarn = warning('off','MATLAB:hg:JavaSetHGProperty'); + warning('off','MATLAB:hg:PossibleDeprecatedJavaSetHGProperty'); + for idx = 1 : length(cbNames) + try + cbData{idx,2} = charizeData(get(obj,cbNames{idx})); + catch + cbData{idx,2} = '(callback value inaccessible)'; + end + end + warning(oldWarn); + else % only one event callback + %cbData = {cbNames, get(obj,cbNames)'}; + %cbData{1,2} = charizeData(cbData{1,2}); + try + cbData = {cbNames, charizeData(get(obj,cbNames))}; + catch + cbData = {cbNames, '(callback value inaccessible)'}; + end + end + cbHeaders = {'Callback name','Callback value'}; + cbTableEnabled = true; + end + catch + % never mind - use default (empty) data + end + end % getCbsData + + %% Get relative (0.0-1.0) divider location + function divLocation = getRalativeDivlocation(jDiv) + divLocation = jDiv.getDividerLocation; + if divLocation > 1 % i.e. [pixels] + visibleRect = jDiv.getVisibleRect; + if jDiv.getOrientation == 0 % vertical + start = visibleRect.getY; + extent = visibleRect.getHeight - start; + else + start = visibleRect.getX; + extent = visibleRect.getWidth - start; + end + divLocation = (divLocation - start) / extent; + end + end % getRalativeDivlocation + + %% Try to set a treenode icon based on a container's icon + function setTreeNodeIcon(treenode,container) + try + iconImage = []; + iconImage = container.getIcon; + if ~isempty(findprop(handle(iconImage),'Image')) % get(iconImage,'Image') is easier but leaks memory... + iconImage = iconImage.getImage; + else + a=b; %#ok cause an error + end + catch + try + iconImage = container.getIconImage; + catch + try + if ~isempty(iconImage) + ge = java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment; + gd = ge.getDefaultScreenDevice; + gc = gd.getDefaultConfiguration; + image = gc.createCompatibleImage(iconImage.getIconWidth, iconImage.getIconHeight); % a BufferedImage object + g = image.createGraphics; + iconImage.paintIcon([], g, 0, 0); + g.dispose; + iconImage = image; + end + catch + % never mind... + end + end + end + if ~isempty(iconImage) + iconImage = setIconSize(iconImage); + treenode.setIcon(iconImage); + end + end % setTreeNodeIcon + + %% Present the object hierarchy tree + function presentObjectTree() + persistent lastVersionCheck + if isempty(lastVersionCheck), lastVersionCheck = now-1; end + + import java.awt.* + import javax.swing.* + hTreeFig = findall(0,'tag','findjobjFig'); + iconpath = [matlabroot, '/toolbox/matlab/icons/']; + cbHideStd = 0; % Initial state of the cbHideStdCbs checkbox + if isempty(hTreeFig) + % Prepare the figure + hTreeFig = figure('tag','findjobjFig','menuBar','none','toolBar','none','Name','FindJObj','NumberTitle','off','handleVisibility','off','IntegerHandle','off'); + figIcon = ImageIcon([iconpath 'tool_legend.gif']); + drawnow; + try + mde = com.mathworks.mde.desk.MLDesktop.getInstance; + jTreeFig = mde.getClient('FindJObj').getTopLevelAncestor; + jTreeFig.setIcon(figIcon); + catch + warning('off','MATLAB:HandleGraphics:ObsoletedProperty:JavaFrame'); % R2008b compatibility + jTreeFig = get(hTreeFig,'JavaFrame'); + jTreeFig.setFigureIcon(figIcon); + end + vsplitPaneLocation = 0.8; + hsplitPaneLocation = 0.5; + else + % Remember cbHideStdCbs checkbox & dividers state for later + userdata = get(hTreeFig, 'userdata'); + try cbHideStd = userdata.cbHideStdCbs.isSelected; catch, end %#ok + try + vsplitPaneLocation = getRalativeDivlocation(userdata.vsplitPane); + hsplitPaneLocation = getRalativeDivlocation(userdata.hsplitPane); + catch + vsplitPaneLocation = 0.8; + hsplitPaneLocation = 0.5; + end + + % Clear the figure and redraw + clf(hTreeFig); + figure(hTreeFig); % bring to front + end + + % Traverse all HG children, if root container was a HG handle + if ishghandle(origContainer) %&& ~isequal(origContainer,container) + traverseHGContainer(origContainer,0,0); + end + + % Prepare the tree pane + warning('off','MATLAB:uitreenode:MigratingFunction'); % R2008b compatibility + warning('off','MATLAB:uitreenode:DeprecatedFunction'); % R2008a compatibility + tree_h = com.mathworks.hg.peer.UITreePeer; + try tree_h = javaObjectEDT(tree_h); catch, end + tree_hh = handle(tree_h,'CallbackProperties'); + hasChildren = sum(allParents==1) > 1; + icon = [iconpath 'upfolder.gif']; + [rootName, rootTitle] = getNodeName(container); + try + root = uitreenode('v0', handle(container), rootName, icon, ~hasChildren); + catch % old matlab version don't have the 'v0' option + root = uitreenode(handle(container), rootName, icon, ~hasChildren); + end + setTreeNodeIcon(root,container); % constructor must accept a char icon unfortunately, so need to do this afterwards... + if ~isempty(rootTitle) + set(hTreeFig, 'Name',['FindJObj - ' char(rootTitle)]); + end + nodedata.idx = 1; + nodedata.obj = container; + set(root,'userdata',nodedata); + root.setUserObject(container); + setappdata(root,'childHandle',container); + tree_h.setRoot(root); + treePane = tree_h.getScrollPane; + treePane.setMinimumSize(Dimension(50,50)); + jTreeObj = treePane.getViewport.getComponent(0); + jTreeObj.setShowsRootHandles(true) + jTreeObj.getSelectionModel.setSelectionMode(javax.swing.tree.TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION); + %jTreeObj.setVisible(0); + %jTreeObj.getCellRenderer.setLeafIcon([]); + %jTreeObj.getCellRenderer.setOpenIcon(figIcon); + %jTreeObj.getCellRenderer.setClosedIcon([]); + treePanel = JPanel(BorderLayout); + treePanel.add(treePane, BorderLayout.CENTER); + progressBar = JProgressBar(0); + progressBar.setMaximum(length(allHandles) + length(hg_handles)); % = # of all nodes + treePanel.add(progressBar, BorderLayout.SOUTH); + + % Prepare the image pane +%disable for now, until we get it working... +%{ + try + hFig = ancestor(origContainer,'figure'); + [cdata, cm] = getframe(hFig); %#ok cm unused + tempfname = [tempname '.png']; + imwrite(cdata,tempfname); % don't know how to pass directly to BufferedImage, so use disk... + jImg = javax.imageio.ImageIO.read(java.io.File(tempfname)); + try delete(tempfname); catch end + imgPanel = JPanel(); + leftPanel = JSplitPane(JSplitPane.VERTICAL_SPLIT, treePanel, imgPanel); + leftPanel.setOneTouchExpandable(true); + leftPanel.setContinuousLayout(true); + leftPanel.setResizeWeight(0.8); + catch + leftPanel = treePanel; + end +%} + leftPanel = treePanel; + + % Prepare the inspector pane + classNameLabel = JLabel([' ' char(class(container))]); + classNameLabel.setForeground(Color.blue); + updateNodeTooltip(container, classNameLabel); + inspectorPanel = JPanel(BorderLayout); + inspectorPanel.add(classNameLabel, BorderLayout.NORTH); + % TODO: Maybe uncomment the following when we add the HG tree - in the meantime it's unused (java properties are un-groupable) + %objReg = com.mathworks.services.ObjectRegistry.getLayoutRegistry; + %toolBar = awtinvoke('com.mathworks.mlwidgets.inspector.PropertyView$ToolBarStyle','valueOf(Ljava.lang.String;)','GROUPTOOLBAR'); + %inspectorPane = com.mathworks.mlwidgets.inspector.PropertyView(objReg, toolBar); + inspectorPane = com.mathworks.mlwidgets.inspector.PropertyView; + identifiers = disableDbstopError; %#ok ""dbstop if error"" causes inspect.m to croak due to a bug - so workaround + inspectorPane.setObject(container); + inspectorPane.setAutoUpdate(true); + % TODO: Add property listeners + % TODO: Display additional props + inspectorTable = inspectorPane; + try + while ~isa(inspectorTable,'javax.swing.JTable') + inspectorTable = inspectorTable.getComponent(0); + end + catch + % R2010a + inspectorTable = inspectorPane.getComponent(0).getScrollPane.getViewport.getComponent(0); + end + toolTipText = 'hover mouse over the red classname above to see the full list of properties'; + inspectorTable.setToolTipText(toolTipText); + jideTableUtils = []; + try + % Try JIDE features - see http://www.jidesoft.com/products/JIDE_Grids_Developer_Guide.pdf + com.mathworks.mwswing.MJUtilities.initJIDE; + jideTableUtils = eval('com.jidesoft.grid.TableUtils;'); % prevent JIDE alert by run-time (not load-time) evaluation + jideTableUtils.autoResizeAllColumns(inspectorTable); + inspectorTable.setRowAutoResizes(true); + inspectorTable.getModel.setShowExpert(1); + catch + % JIDE is probably unavailable - never mind... + end + inspectorPanel.add(inspectorPane, BorderLayout.CENTER); + % TODO: Add data update listeners + + % Prepare the callbacks pane + callbacksPanel = JPanel(BorderLayout); + stripStdCbsFlag = true; % initial value + [cbData, cbHeaders, cbTableEnabled] = getCbsData(container, stripStdCbsFlag); + %{ + %classHdl = classhandle(handle(container)); + %eventNames = get(classHdl.Events,'Name'); + %if ~isempty(eventNames) + % cbNames = sort(strcat(eventNames,'Callback')); + % try + % cbData = [cbNames, get(container,cbNames)']; + % catch + % % R2010a + % cbData = cbNames; + % if isempty(cbData) + % cbData = {}; + % elseif ~iscell(cbData) + % cbData = {cbData}; + % end + % for idx = 1 : length(cbNames) + % cbData{idx,2} = get(container,cbNames{idx}); + % end + % end + % cbTableEnabled = true; + %else + % cbData = {'(no callbacks)',''}; + % cbTableEnabled = false; + %end + %cbHeaders = {'Callback name','Callback value'}; + %} + try + % Use JideTable if available on this system + %callbacksTableModel = javax.swing.table.DefaultTableModel(cbData,cbHeaders); %#ok + %callbacksTable = eval('com.jidesoft.grid.PropertyTable(callbacksTableModel);'); % prevent JIDE alert by run-time (not load-time) evaluation + try + list = getTreeData(cbData); %#ok + model = eval('com.jidesoft.grid.PropertyTableModel(list);'); %#ok prevent JIDE alert by run-time (not load-time) evaluation + + % Auto-expand if only one category + if model.getRowCount==1 % length(model.getCategories)==1 fails for some unknown reason... + model.expandFirstLevel; + end + + %callbacksTable = eval('com.jidesoft.grid.TreeTable(model);'); %#ok prevent JIDE alert by run-time (not load-time) evaluation + callbacksTable = eval('com.jidesoft.grid.PropertyTable(model);'); %#ok prevent JIDE alert by run-time (not load-time) evaluation + + %callbacksTable.expandFirstLevel; + callbacksTable.setShowsRootHandles(true); + callbacksTable.setShowTreeLines(false); + %callbacksTable.setShowNonEditable(0); %=SHOW_NONEDITABLE_NEITHER + callbacksPane = eval('com.jidesoft.grid.PropertyPane(callbacksTable);'); % prevent JIDE alert by run-time (not load-time) evaluation + callbacksPane.setShowDescription(false); + catch + callbacksTable = eval('com.jidesoft.grid.TreeTable(cbData,cbHeaders);'); % prevent JIDE alert by run-time (not load-time) evaluation + end + callbacksTable.setRowAutoResizes(true); + callbacksTable.setColumnAutoResizable(true); + callbacksTable.setColumnResizable(true); + jideTableUtils.autoResizeAllColumns(callbacksTable); + callbacksTable.setTableHeader([]); % hide the column headers since now we can resize columns with the gridline + callbacksLabel = JLabel(' Callbacks:'); % The column headers are replaced with a header label + callbacksLabel.setForeground(Color.blue); + %callbacksPanel.add(callbacksLabel, BorderLayout.NORTH); + + % Add checkbox to show/hide standard callbacks + callbacksTopPanel = JPanel; + callbacksTopPanel.setLayout(BoxLayout(callbacksTopPanel, BoxLayout.LINE_AXIS)); + callbacksTopPanel.add(callbacksLabel); + callbacksTopPanel.add(Box.createHorizontalGlue); + jcb = JCheckBox('Hide standard callbacks', cbHideStd); + set(handle(jcb,'CallbackProperties'), 'ActionPerformedCallback',{@cbHideStdCbs_Callback,callbacksTable}); + try + set(jcb, 'userdata',callbacksTable, 'tooltip','Hide standard Swing callbacks - only component-specific callbacks will be displayed'); + catch + jcb.setToolTipText('Hide standard Swing callbacks - only component-specific callbacks will be displayed'); + %setappdata(jcb,'userdata',callbacksTable); + end + callbacksTopPanel.add(jcb); + callbacksPanel.add(callbacksTopPanel, BorderLayout.NORTH); + catch + % Otherwise, use a standard Swing JTable (keep the headers to enable resizing) + callbacksTable = JTable(cbData,cbHeaders); + end + cbToolTipText = 'Callbacks may be ''strings'', @funcHandle or {@funcHandle,arg1,...}'; + callbacksTable.setToolTipText(cbToolTipText); + callbacksTable.setGridColor(inspectorTable.getGridColor); + cbNameTextField = JTextField; + cbNameTextField.setEditable(false); % ensure that the callback names are not modified... + cbNameCellEditor = DefaultCellEditor(cbNameTextField); + cbNameCellEditor.setClickCountToStart(intmax); % i.e, never enter edit mode... + callbacksTable.getColumnModel.getColumn(0).setCellEditor(cbNameCellEditor); + if ~cbTableEnabled + try callbacksTable.getColumnModel.getColumn(1).setCellEditor(cbNameCellEditor); catch, end + end + hModel = callbacksTable.getModel; + set(handle(hModel,'CallbackProperties'), 'TableChangedCallback',{@tbCallbacksChanged,container,callbacksTable}); + %set(hModel, 'UserData',container); + try + cbScrollPane = callbacksPane; %JScrollPane(callbacksPane); + %cbScrollPane.setHorizontalScrollBarPolicy(cbScrollPane.HORIZONTAL_SCROLLBAR_NEVER); + catch + cbScrollPane = JScrollPane(callbacksTable); + cbScrollPane.setVerticalScrollBarPolicy(cbScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); + end + callbacksPanel.add(cbScrollPane, BorderLayout.CENTER); + callbacksPanel.setToolTipText(cbToolTipText); + + % Prepare the top-bottom JSplitPanes + vsplitPane = JSplitPane(JSplitPane.VERTICAL_SPLIT, inspectorPanel, callbacksPanel); + vsplitPane.setOneTouchExpandable(true); + vsplitPane.setContinuousLayout(true); + vsplitPane.setResizeWeight(0.8); + + % Prepare the left-right JSplitPane + hsplitPane = JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel, vsplitPane); + hsplitPane.setOneTouchExpandable(true); + hsplitPane.setContinuousLayout(true); + hsplitPane.setResizeWeight(0.6); + pos = getpixelposition(hTreeFig); + + % Prepare the bottom pane with all buttons + lowerPanel = JPanel(FlowLayout); + blogUrlLabel = 'Undocumented
Matlab.com
'; + jWebsite = createJButton(blogUrlLabel, @btWebsite_Callback, 'Visit the UndocumentedMatlab.com blog'); + jWebsite.setContentAreaFilled(0); + lowerPanel.add(jWebsite); + lowerPanel.add(createJButton('Refresh
tree', {@btRefresh_Callback, origContainer, hTreeFig}, 'Rescan the component tree, from the root down')); + lowerPanel.add(createJButton('Export to
workspace', {@btExport_Callback, jTreeObj, classNameLabel}, 'Export the selected component handles to workspace variable findjobj_hdls')); + lowerPanel.add(createJButton('Request
focus', {@btFocus_Callback, jTreeObj, root}, 'Set the focus on the first selected component')); + lowerPanel.add(createJButton('Inspect
object', {@btInspect_Callback, jTreeObj, root}, 'View the signature of all methods supported by the first selected component')); + lowerPanel.add(createJButton('Check for
updates', {@btCheckFex_Callback}, 'Check the MathWorks FileExchange for the latest version of FindJObj')); + + % Display everything on-screen + globalPanel = JPanel(BorderLayout); + globalPanel.add(hsplitPane, BorderLayout.CENTER); + globalPanel.add(lowerPanel, BorderLayout.SOUTH); + [obj, hcontainer] = javacomponent(globalPanel, [0,0,pos(3:4)], hTreeFig); + set(hcontainer,'units','normalized'); + drawnow; + hsplitPane.setDividerLocation(hsplitPaneLocation); % this only works after the JSplitPane is displayed... + vsplitPane.setDividerLocation(vsplitPaneLocation); % this only works after the JSplitPane is displayed... + %restoreDbstopError(identifiers); + + % Refresh & resize the screenshot thumbnail +%disable for now, until we get it working... +%{ + try + hAx = axes('Parent',hTreeFig, 'units','pixels', 'position',[10,10,250,150], 'visible','off'); + axis(hAx,'image'); + image(cdata,'Parent',hAx); + axis(hAx,'off'); + set(hAx,'UserData',cdata); + set(imgPanel, 'ComponentResizedCallback',{@resizeImg, hAx}, 'UserData',lowerPanel); + imgPanel.getGraphics.drawImage(jImg, 0, 0, []); + catch + % Never mind... + end +%} + % If all handles were selected (i.e., none were filtered) then only select the first + if (length(selectedIdx) == length(allHandles)) && ~isempty(selectedIdx) + selectedIdx = 1; + end + + % Store handles for callback use + userdata.handles = allHandles; + userdata.levels = allLevels; + userdata.parents = allParents; + userdata.hg_handles = hg_handles; + userdata.hg_levels = hg_levels; + userdata.hg_parents = hg_parentIdx; + userdata.initialIdx = selectedIdx; + userdata.userSelected = false; % Indicates the user has modified the initial selections + userdata.inInit = true; + userdata.jTree = jTreeObj; + userdata.jTreePeer = tree_h; + userdata.vsplitPane = vsplitPane; + userdata.hsplitPane = hsplitPane; + userdata.classNameLabel = classNameLabel; + userdata.inspectorPane = inspectorPane; + userdata.callbacksTable = callbacksTable; + userdata.jideTableUtils = jideTableUtils; + try + userdata.cbHideStdCbs = jcb; + catch + userdata.cbHideStdCbs = []; + end + + % Update userdata for use in callbacks + try + set(tree_h,'userdata',userdata); + catch + setappdata(handle(tree_h),'userdata',userdata); + end + try + set(callbacksTable,'userdata',userdata); + catch + setappdata(callbacksTable,'userdata',userdata); + end + set(hTreeFig,'userdata',userdata); + + % Select the root node if requested + % Note: we must do so here since all other nodes except the root are processed by expandNode + if any(selectedIdx==1) + tree_h.setSelectedNode(root); + end + + % Set the initial cbHideStdCbs state + try + if jcb.isSelected + drawnow; + evd.getSource.isSelected = jcb.isSelected; + cbHideStdCbs_Callback(jcb,evd,callbacksTable); + end + catch + % never mind... + end + + % Set the callback functions + set(tree_hh, 'NodeExpandedCallback', {@nodeExpanded, tree_h}); + set(tree_hh, 'NodeSelectedCallback', {@nodeSelected, tree_h}); + + % Set the tree mouse-click callback + % Note: default actions (expand/collapse) will still be performed? + % Note: MousePressedCallback is better than MouseClickedCallback + % since it fires immediately when mouse button is pressed, + % without waiting for its release, as MouseClickedCallback does + handleTree = tree_h.getScrollPane; + jTreeObj = handleTree.getViewport.getComponent(0); + jTreeObjh = handle(jTreeObj,'CallbackProperties'); + set(jTreeObjh, 'MousePressedCallback', {@treeMousePressedCallback,tree_h}); % context (right-click) menu + set(jTreeObjh, 'MouseMovedCallback', @treeMouseMovedCallback); % mouse hover tooltips + + % Update userdata + userdata.inInit = false; + try + set(tree_h,'userdata',userdata); + catch + setappdata(handle(tree_h),'userdata',userdata); + end + set(hTreeFig,'userdata',userdata); + + % Pre-expand all rows + %treePane.setVisible(false); + expandNode(progressBar, jTreeObj, tree_h, root, 0); + %treePane.setVisible(true); + %jTreeObj.setVisible(1); + + % Hide the progressbar now that we've finished expanding all rows + try + hsplitPane.getLeftComponent.setTopComponent(treePane); + catch + % Probably not a vSplitPane on the left... + hsplitPane.setLeftComponent(treePane); + end + hsplitPane.setDividerLocation(hsplitPaneLocation); % need to do it again... + + % Set keyboard focus on the tree + jTreeObj.requestFocus; + drawnow; + + % Check for a newer version (only in non-deployed mode, and only twice a day) + if ~isdeployed && now-lastVersionCheck > 0.5 + checkVersion(); + lastVersionCheck = now; + end + + % Reset the last error + lasterr(''); %#ok + end + + %% Rresize image pane + function resizeImg(varargin) %#ok - unused (TODO: waiting for img placement fix...) + try + hPanel = varargin{1}; + hAx = varargin{3}; + lowerPanel = get(hPanel,'UserData'); + newJPos = cell2mat(get(hPanel,{'X','Y','Width','Height'})); + newMPos = [1,get(lowerPanel,'Height'),newJPos(3:4)]; + set(hAx, 'units','pixels', 'position',newMPos, 'Visible','on'); + uistack(hAx,'top'); % no good... + set(hPanel,'Opaque','off'); % also no good... + catch + % Never mind... + dispError + end + return; + end + + %% ""dbstop if error"" causes inspect.m to croak due to a bug - so workaround by temporarily disabling this dbstop + function identifiers = disableDbstopError + dbStat = dbstatus; + idx = find(strcmp({dbStat.cond},'error')); + identifiers = [dbStat(idx).identifier]; + if ~isempty(idx) + dbclear if error; + msgbox('''dbstop if error'' had to be disabled due to a Matlab bug that would have caused Matlab to crash.', 'FindJObj', 'warn'); + end + end + + %% Restore any previous ""dbstop if error"" + function restoreDbstopError(identifiers) %#ok + for itemIdx = 1 : length(identifiers) + eval(['dbstop if error ' identifiers{itemIdx}]); + end + end + + %% Recursively expand all nodes (except toolbar/menubar) in startup + function expandNode(progressBar, tree, tree_h, parentNode, parentRow) + try + if nargin < 5 + parentPath = javax.swing.tree.TreePath(parentNode.getPath); + parentRow = tree.getRowForPath(parentPath); + end + tree.expandRow(parentRow); + progressBar.setValue(progressBar.getValue+1); + numChildren = parentNode.getChildCount; + if (numChildren == 0) + pause(0.0002); % as short as possible... + drawnow; + end + nodesToUnExpand = {'FigureMenuBar','MLMenuBar','MJToolBar','Box','uimenu','uitoolbar','ScrollBar'}; + numChildren = parentNode.getChildCount; + for childIdx = 0 : numChildren-1 + childNode = parentNode.getChildAt(childIdx); + + % Pre-select the node based upon the user's FINDJOBJ filters + try + nodedata = get(childNode, 'userdata'); + try + userdata = get(tree_h, 'userdata'); + catch + userdata = getappdata(handle(tree_h), 'userdata'); + end + %fprintf('%d - %s\n',nodedata.idx,char(nodedata.obj)) + if ~ishghandle(nodedata.obj) && ~userdata.userSelected && any(userdata.initialIdx == nodedata.idx) + pause(0.0002); % as short as possible... + drawnow; + if isempty(tree_h.getSelectedNodes) + tree_h.setSelectedNode(childNode); + else + newSelectedNodes = [tree_h.getSelectedNodes, childNode]; + tree_h.setSelectedNodes(newSelectedNodes); + end + end + catch + % never mind... + dispError + end + + % Expand child node if not leaf & not toolbar/menubar + if childNode.isLeafNode + + % This is a leaf node, so simply update the progress-bar + progressBar.setValue(progressBar.getValue+1); + + else + % Expand all non-leaves + expandNode(progressBar, tree, tree_h, childNode); + + % Re-collapse toolbar/menubar etc., and also invisible containers + % Note: if we simply did nothing, progressbar would not have been updated... + try + childHandle = getappdata(childNode,'childHandle'); %=childNode.getUserObject + visible = childHandle.isVisible; + catch + visible = 1; + end + visible = visible && isempty(strfind(get(childNode,'Name'),'color=""gray""')); + %if any(strcmp(childNode.getName,nodesToUnExpand)) + %name = char(childNode.getName); + if any(cellfun(@(s)~isempty(strmatch(s,char(childNode.getName))),nodesToUnExpand)) || ~visible + childPath = javax.swing.tree.TreePath(childNode.getPath); + childRow = tree.getRowForPath(childPath); + tree.collapseRow(childRow); + end + end + end + catch + % never mind... + dispError + end + end + + %% Create utility buttons + function hButton = createJButton(nameStr, handler, toolTipText) + try + jButton = javax.swing.JButton(['
' nameStr]); + jButton.setCursor(java.awt.Cursor.getPredefinedCursor(java.awt.Cursor.HAND_CURSOR)); + jButton.setToolTipText(toolTipText); + try + minSize = jButton.getMinimumSize; + catch + minSize = jButton.getMinimumSize; % for HG2 - strange indeed that this is needed! + end + jButton.setMinimumSize(java.awt.Dimension(minSize.getWidth,35)); + hButton = handle(jButton,'CallbackProperties'); + set(hButton,'ActionPerformedCallback',handler); + catch + % Never mind... + a= 1; + end + end + + %% Flash a component off/on for the specified duration + % note: starts with 'on'; if numTimes is odd then ends with 'on', otherwise with 'off' + function flashComponent(jComps,delaySecs,numTimes) + persistent redBorder redBorderPanels + try + % Handle callback data from right-click (context-menu) + if iscell(numTimes) + [jComps,delaySecs,numTimes] = deal(numTimes{:}); + end + + if isempty(redBorder) % reuse if possible + redBorder = javax.swing.border.LineBorder(java.awt.Color.red,2,0); + end + for compIdx = 1 : length(jComps) + try + oldBorder{compIdx} = jComps(compIdx).getBorder; %#ok grow + catch + oldBorder{compIdx} = []; %#ok grow + end + isSettable(compIdx) = ismethod(jComps(compIdx),'setBorder'); %#ok grow + if isSettable(compIdx) + try + % some components prevent border modification: + oldBorderFlag = jComps(compIdx).isBorderPainted; + if ~oldBorderFlag + jComps(compIdx).setBorderPainted(1); + isSettable(compIdx) = jComps(compIdx).isBorderPainted; %#ok grow + jComps(compIdx).setBorderPainted(oldBorderFlag); + end + catch + % do nothing... + end + end + if compIdx > length(redBorderPanels) + redBorderPanels{compIdx} = javax.swing.JPanel; + redBorderPanels{compIdx}.setBorder(redBorder); + redBorderPanels{compIdx}.setOpaque(0); % transparent interior, red border + end + try + redBorderPanels{compIdx}.setBounds(jComps(compIdx).getBounds); + catch + % never mind - might be an HG handle + end + end + for idx = 1 : 2*numTimes + if idx>1, pause(delaySecs); end % don't pause at start + visible = mod(idx,2); + for compIdx = 1 : length(jComps) + try + jComp = jComps(compIdx); + + % Prevent Matlab crash (java buffer overflow...) + if isa(jComp,'com.mathworks.mwswing.desk.DTSplitPane') || ... + isa(jComp,'com.mathworks.mwswing.MJSplitPane') + continue; + + % HG handles are highlighted by setting their 'Selected' property + elseif isa(jComp,'uimenu') || isa(jComp,'matlab.ui.container.Menu') + if visible + oldColor = get(jComp,'ForegroundColor'); + setappdata(jComp,'findjobj_oldColor',oldColor); + set(jComp,'ForegroundColor','red'); + else + oldColor = getappdata(jComp,'findjobj_oldColor'); + set(jComp,'ForegroundColor',oldColor); + rmappdata(jComp,'ForegroundColor'); + end + + elseif ishghandle(jComp) + if visible + set(jComp,'Selected','on'); + else + set(jComp,'Selected','off'); + end + + else %if isjava(jComp) + + jParent = jComps(compIdx).getParent; + + % Most Java components allow modifying their borders + if isSettable(compIdx) + if visible + jComp.setBorder(redBorder); + try jComp.setBorderPainted(1); catch, end %#ok + else %if ~isempty(oldBorder{compIdx}) + jComp.setBorder(oldBorder{compIdx}); + end + jComp.repaint; + + % The other Java components are highlighted by a transparent red-border + % panel that is placed on top of them in their parent's space + elseif ~isempty(jParent) + if visible + jParent.add(redBorderPanels{compIdx}); + jParent.setComponentZOrder(redBorderPanels{compIdx},0); + else + jParent.remove(redBorderPanels{compIdx}); + end + jParent.repaint + end + end + catch + % never mind - try the next component (if any) + end + end + drawnow; + end + catch + % never mind... + dispError; + end + return; % debug point + end % flashComponent + + %% Select tree node + function nodeSelected(src, evd, tree) %#ok + try + if iscell(tree) + [src,node] = deal(tree{:}); + else + node = evd.getCurrentNode; + end + %nodeHandle = node.getUserObject; + nodedata = get(node,'userdata'); + nodeHandle = nodedata.obj; + try + userdata = get(src,'userdata'); + catch + try + userdata = getappdata(java(src),'userdata'); + catch + userdata = getappdata(src,'userdata'); + end + if isempty(userdata) + try userdata = get(java(src),'userdata'); catch, end + end + end + if ~isempty(nodeHandle) && ~isempty(userdata) + numSelections = userdata.jTree.getSelectionCount; + selectionPaths = userdata.jTree.getSelectionPaths; + if (numSelections == 1) + % Indicate that the user has modified the initial selection (except if this was an initial auto-selected node) + if ~userdata.inInit + userdata.userSelected = true; + try + set(src,'userdata',userdata); + catch + try + setappdata(java(src),'userdata',userdata); + catch + setappdata(src,'userdata',userdata); + end + end + end + + % Update the fully-qualified class name label + numInitialIdx = length(userdata.initialIdx); + thisHandle = nodeHandle; + try + if ~ishghandle(thisHandle) + thisHandle = java(nodeHandle); + end + catch + % never mind... + end + if ~userdata.inInit || (numInitialIdx == 1) + userdata.classNameLabel.setText([' ' char(class(thisHandle))]); + else + userdata.classNameLabel.setText([' ' num2str(numInitialIdx) 'x handles (some handles hidden by unexpanded tree nodes)']); + end + if ishghandle(thisHandle) + userdata.classNameLabel.setText(userdata.classNameLabel.getText.concat(' (HG handle)')); + end + userdata.inspectorPane.dispose; % remove props listeners - doesn't work... + updateNodeTooltip(nodeHandle, userdata.classNameLabel); + + % Update the data properties inspector pane + % Note: we can't simply use the evd nodeHandle, because this node might have been DE-selected with only one other node left selected... + %nodeHandle = selectionPaths(1).getLastPathComponent.getUserObject; + nodedata = get(selectionPaths(1).getLastPathComponent,'userdata'); + nodeHandle = nodedata.obj; + %identifiers = disableDbstopError; % ""dbstop if error"" causes inspect.m to croak due to a bug - so workaround + userdata.inspectorPane.setObject(thisHandle); + + % Update the callbacks table + try + stripStdCbsFlag = getappdata(userdata.callbacksTable,'hideStdCbs'); + [cbData, cbHeaders, cbTableEnabled] = getCbsData(nodeHandle, stripStdCbsFlag); %#ok cbTableEnabled unused + try + % Use JideTable if available on this system + list = getTreeData(cbData); %#ok + callbacksTableModel = eval('com.jidesoft.grid.PropertyTableModel(list);'); %#ok prevent JIDE alert by run-time (not load-time) evaluation + + % Expand if only one category + if length(callbacksTableModel.getCategories)==1 + callbacksTableModel.expandFirstLevel; + end + catch + callbacksTableModel = javax.swing.table.DefaultTableModel(cbData,cbHeaders); + end + set(handle(callbacksTableModel,'CallbackProperties'), 'TableChangedCallback',{@tbCallbacksChanged,nodeHandle,userdata.callbacksTable}); + %set(callbacksTableModel, 'UserData',nodeHandle); + userdata.callbacksTable.setModel(callbacksTableModel) + userdata.callbacksTable.setRowAutoResizes(true); + userdata.jideTableUtils.autoResizeAllColumns(userdata.callbacksTable); + catch + % never mind... + %dispError + end + pause(0.005); + drawnow; + %restoreDbstopError(identifiers); + + % Highlight the selected object (if visible) + flashComponent(nodeHandle,0.2,3); + + elseif (numSelections > 1) % Multiple selections + + % Get the list of all selected nodes + jArray = javaArray('java.lang.Object', numSelections); + toolTipStr = ''; + sameClassFlag = true; + for idx = 1 : numSelections + %jArray(idx) = selectionPaths(idx).getLastPathComponent.getUserObject; + nodedata = get(selectionPaths(idx).getLastPathComponent,'userdata'); + try + if ishghandle(nodedata.obj) + if idx==1 + jArray = nodedata.obj; + else + jArray(idx) = nodedata.obj; + end + else + jArray(idx) = java(nodedata.obj); + end + catch + jArray(idx) = nodedata.obj; + end + toolTipStr = [toolTipStr ' ' class(jArray(idx)) ' ']; %#ok grow + if (idx < numSelections), toolTipStr = [toolTipStr '
']; end %#ok grow + try + if (idx > 1) && sameClassFlag && ~isequal(jArray(idx).getClass,jArray(1).getClass) + sameClassFlag = false; + end + catch + if (idx > 1) && sameClassFlag && ~isequal(class(jArray(idx)),class(jArray(1))) + sameClassFlag = false; + end + end + end + toolTipStr = [toolTipStr '']; + + % Update the fully-qualified class name label + if sameClassFlag + classNameStr = class(jArray(1)); + else + classNameStr = 'handle'; + end + if all(ishghandle(jArray)) + if strcmp(classNameStr,'handle') + classNameStr = 'HG handles'; + else + classNameStr = [classNameStr ' (HG handles)']; + end + end + classNameStr = [' ' num2str(numSelections) 'x ' classNameStr]; + userdata.classNameLabel.setText(classNameStr); + userdata.classNameLabel.setToolTipText(toolTipStr); + + % Update the data properties inspector pane + %identifiers = disableDbstopError; % ""dbstop if error"" causes inspect.m to croak due to a bug - so workaround + if isjava(jArray) + jjArray = jArray; + else + jjArray = javaArray('java.lang.Object', numSelections); + for idx = 1 : numSelections + jjArray(idx) = java(jArray(idx)); + end + end + userdata.inspectorPane.getRegistry.setSelected(jjArray, true); + + % Update the callbacks table + try + % Get intersecting callback names & values + stripStdCbsFlag = getappdata(userdata.callbacksTable,'hideStdCbs'); + [cbData, cbHeaders, cbTableEnabled] = getCbsData(jArray(1), stripStdCbsFlag); %#ok cbHeaders & cbTableEnabled unused + if ~isempty(cbData) + cbNames = cbData(:,1); + for idx = 2 : length(jArray) + [cbData2, cbHeaders2] = getCbsData(jArray(idx), stripStdCbsFlag); %#ok cbHeaders2 unused + if ~isempty(cbData2) + newCbNames = cbData2(:,1); + [cbNames, cbIdx, cb2Idx] = intersect(cbNames,newCbNames); %#ok cb2Idx unused + cbData = cbData(cbIdx,:); + for cbIdx = 1 : length(cbNames) + newIdx = find(strcmp(cbNames{cbIdx},newCbNames)); + if ~isequal(cbData2,cbData) && ~isequal(cbData2{newIdx,2}, cbData{cbIdx,2}) + cbData{cbIdx,2} = ''; + end + end + else + cbData = cbData([],:); %=empty cell array + end + if isempty(cbData) + break; + end + end + end + cbHeaders = {'Callback name','Callback value'}; + try + % Use JideTable if available on this system + list = getTreeData(cbData); %#ok + callbacksTableModel = eval('com.jidesoft.grid.PropertyTableModel(list);'); %#ok prevent JIDE alert by run-time (not load-time) evaluation + + % Expand if only one category + if length(callbacksTableModel.getCategories)==1 + callbacksTableModel.expandFirstLevel; + end + catch + callbacksTableModel = javax.swing.table.DefaultTableModel(cbData,cbHeaders); + end + set(handle(callbacksTableModel,'CallbackProperties'), 'TableChangedCallback',{@tbCallbacksChanged,jArray,userdata.callbacksTable}); + %set(callbacksTableModel, 'UserData',jArray); + userdata.callbacksTable.setModel(callbacksTableModel) + userdata.callbacksTable.setRowAutoResizes(true); + userdata.jideTableUtils.autoResizeAllColumns(userdata.callbacksTable); + catch + % never mind... + dispError + end + + pause(0.005); + drawnow; + %restoreDbstopError(identifiers); + + % Highlight the selected objects (if visible) + flashComponent(jArray,0.2,3); + end + + % TODO: Auto-highlight selected object (?) + %nodeHandle.requestFocus; + end + catch + dispError + end + end + + %% IFF utility function for annonymous cellfun funcs + function result = iff(test,trueVal,falseVal) %#ok + try + if test + result = trueVal; + else + result = falseVal; + end + catch + result = false; + end + end + + %% Get an HTML representation of the object's properties + function dataFieldsStr = getPropsHtml(nodeHandle, dataFields) + try + % Get a text representation of the fieldnames & values + undefinedStr = ''; + hiddenStr = ''; + dataFieldsStr = ''; % just in case the following croaks... + if isempty(dataFields) + return; + end + dataFieldsStr = evalc('disp(dataFields)'); + if dataFieldsStr(end)==char(10), dataFieldsStr=dataFieldsStr(1:end-1); end + + % Strip out callbacks + dataFieldsStr = regexprep(dataFieldsStr,'^\s*\w*Callback(Data)?:[^\n]*$','','lineanchors'); + + % Strip out internal HG2 mirror properties + dataFieldsStr = regexprep(dataFieldsStr,'^\s*\w*_I:[^\n]*$','','lineanchors'); + dataFieldsStr = regexprep(dataFieldsStr,'\n\n+','\n'); + + % Sort the fieldnames + %fieldNames = fieldnames(dataFields); + try + [a,b,c,d] = regexp(dataFieldsStr,'(\w*): '); + fieldNames = strrep(d,': ',''); + catch + fieldNames = fieldnames(dataFields); + end + try + [fieldNames, sortedIdx] = sort(fieldNames); + s = strsplit(dataFieldsStr, sprintf('\n'))'; + dataFieldsStr = strjoin(s(sortedIdx), sprintf('\n')); + catch + % never mind... - ignore, leave unsorted + end + + % Convert into a Matlab handle() + %nodeHandle = handle(nodeHandle); + try + % ensure this is a Matlab handle, not a java object + nodeHandle = handle(nodeHandle, 'CallbackProperties'); + catch + try + % HG handles don't allow CallbackProperties... + nodeHandle = handle(nodeHandle); + catch + % Some Matlab class objects simply cannot be converted into a handle() + end + end + + % HTMLize tooltip data + % First, set the fields' font based on its read-write status + for fieldIdx = 1 : length(fieldNames) + thisFieldName = fieldNames{fieldIdx}; + %accessFlags = get(findprop(nodeHandle,thisFieldName),'AccessFlags'); + try + hProp = findprop(nodeHandle,thisFieldName); + accessFlags = get(hProp,'AccessFlags'); + visible = get(hProp,'Visible'); + catch + accessFlags = []; + visible = 'on'; + try if hProp.Hidden, visible='off'; end, catch, end + end + %if isfield(accessFlags,'PublicSet') && strcmp(accessFlags.PublicSet,'on') + if (~isempty(hProp) && isprop(hProp,'SetAccess') && isequal(hProp.SetAccess,'public')) || ... % isequal(...'public') and not strcmpi(...) because might be a cell array of classes + (~isempty(accessFlags) && isfield(accessFlags,'PublicSet') && strcmpi(accessFlags.PublicSet,'on')) + % Bolden read/write fields + thisFieldFormat = ['' thisFieldName ':$2']; + %elseif ~isfield(accessFlags,'PublicSet') + elseif (isempty(hProp) || ~isprop(hProp,'SetAccess')) && ... + (isempty(accessFlags) || ~isfield(accessFlags,'PublicSet')) + % Undefined - probably a Matlab-defined field of com.mathworks.hg.peer.FigureFrameProxy... + thisFieldFormat = ['' thisFieldName ':$2']; + undefinedStr = ', undefined'; + else % PublicSet=='off' + % Gray-out & italicize any read-only fields + thisFieldFormat = ['' thisFieldName ':$2']; + end + if strcmpi(visible,'off') + %thisFieldFormat = ['' thisFieldFormat '']; %#ok + thisFieldFormat = regexprep(thisFieldFormat, {'(.*):(.*)','<.?b>'}, {'$1:$2',''}); %'(.*):(.*)', '$1:$2'); + hiddenStr = ', hidden'; + end + dataFieldsStr = regexprep(dataFieldsStr, ['([\s\n])' thisFieldName ':([^\n]*)'], ['$1' thisFieldFormat]); + end + catch + % never mind... - probably an ambiguous property name + %dispError + end + + % Method 1: simple
list + %dataFieldsStr = strrep(dataFieldsStr,char(10),' 
  '); + + % Method 2: 2-column + dataFieldsStr = regexprep(dataFieldsStr, '^\s*([^:]+:)([^\n]*)\n^\s*([^:]+:)([^\n]*)$', '', 'lineanchors'); + dataFieldsStr = regexprep(dataFieldsStr, '^[^<]\s*([^:]+:)([^\n]*)$', '', 'lineanchors'); + dataFieldsStr = ['(documented' undefinedStr hiddenStr ' & read-only fields)

  

 $1 $2    $3 $4 
 $1 $2  
' dataFieldsStr '
']; + end + + %% Update tooltip string with a node's data + function updateNodeTooltip(nodeHandle, uiObject) + try + toolTipStr = class(nodeHandle); + dataFieldsStr = ''; + + % Add HG annotation if relevant + if ishghandle(nodeHandle) + hgStr = ' HG Handle'; + else + hgStr = ''; + end + + % Prevent HG-Java warnings + oldWarn = warning('off','MATLAB:hg:JavaSetHGProperty'); + warning('off','MATLAB:hg:PossibleDeprecatedJavaSetHGProperty'); + warning('off','MATLAB:hg:Root'); + + % Note: don't bulk-get because (1) not all properties are returned & (2) some properties cause a Java exception + % Note2: the classhandle approach does not enable access to user-defined schema.props + ch = classhandle(handle(nodeHandle)); + dataFields = []; + [sortedNames, sortedIdx] = sort(get(ch.Properties,'Name')); + for idx = 1 : length(sortedIdx) + sp = ch.Properties(sortedIdx(idx)); + % TODO: some fields (see EOL comment below) generate a Java Exception from: com.mathworks.mlwidgets.inspector.PropertyRootNode$PropertyListener$1$1.run + if strcmp(sp.AccessFlags.PublicGet,'on') % && ~any(strcmp(sp.Name,{'FixedColors','ListboxTop','Extent'})) + try + dataFields.(sp.Name) = get(nodeHandle, sp.Name); + catch + dataFields.(sp.Name) = 'Error!'; + end + else + dataFields.(sp.Name) = '(no public getter method)'; + end + end + dataFieldsStr = getPropsHtml(nodeHandle, dataFields); + catch + % Probably a non-HG java object + try + % Note: the bulk-get approach enables access to user-defined schema-props, but not to some original classhandle Properties... + try + oldWarn3 = warning('off','MATLAB:structOnObject'); + dataFields = struct(nodeHandle); + warning(oldWarn3); + catch + dataFields = get(nodeHandle); + end + dataFieldsStr = getPropsHtml(nodeHandle, dataFields); + catch + % Probably a missing property getter implementation + try + % Inform the user - bail out on error + err = lasterror; %#ok + dataFieldsStr = ['

' strrep(err.message, char(10), '
')]; + catch + % forget it... + end + end + end + + % Restore warnings + try warning(oldWarn); catch, end + + % Set the object tooltip + if ~isempty(dataFieldsStr) + toolTipStr = [' ' char(toolTipStr) '' hgStr ': ' dataFieldsStr '']; + end + uiObject.setToolTipText(toolTipStr); + end + + %% Expand tree node + function nodeExpanded(src, evd, tree) %#ok + % tree = handle(src); + % evdsrc = evd.getSource; + evdnode = evd.getCurrentNode; + + if ~tree.isLoaded(evdnode) + + % Get the list of children TreeNodes + childnodes = getChildrenNodes(tree, evdnode); + + % Add the HG sub-tree (unless already included in the first tree) + childHandle = getappdata(evdnode.handle,'childHandle'); %=evdnode.getUserObject + if evdnode.isRoot && ~isempty(hg_handles) && ~isequal(hg_handles(1).java, childHandle) + childnodes = [childnodes, getChildrenNodes(tree, evdnode, true)]; + end + + % If we have a single child handle, wrap it within a javaArray for tree.add() to ""swallow"" + if (length(childnodes) == 1) + chnodes = childnodes; + childnodes = javaArray('com.mathworks.hg.peer.UITreeNode', 1); + childnodes(1) = java(chnodes); + end + + % Add child nodes to the current node + tree.add(evdnode, childnodes); + tree.setLoaded(evdnode, true); + end + end + + %% Get an icon image no larger than 16x16 pixels + function iconImage = setIconSize(iconImage) + try + iconWidth = iconImage.getWidth; + iconHeight = iconImage.getHeight; + if iconWidth > 16 + newHeight = fix(iconHeight * 16 / iconWidth); + iconImage = iconImage.getScaledInstance(16,newHeight,iconImage.SCALE_SMOOTH); + elseif iconHeight > 16 + newWidth = fix(iconWidth * 16 / iconHeight); + iconImage = iconImage.getScaledInstance(newWidth,16,iconImage.SCALE_SMOOTH); + end + catch + % never mind... - return original icon + end + end % setIconSize + + %% Get list of children nodes + function nodes = getChildrenNodes(tree, parentNode, isRootHGNode) + try + iconpath = [matlabroot, '/toolbox/matlab/icons/']; + nodes = handle([]); + try + userdata = get(tree,'userdata'); + catch + userdata = getappdata(handle(tree),'userdata'); + end + hdls = userdata.handles; + nodedata = get(parentNode,'userdata'); + if nargin < 3 + %isJavaNode = ~ishghandle(parentNode.getUserObject); + isJavaNode = ~ishghandle(nodedata.obj); + isRootHGNode = false; + else + isJavaNode = ~isRootHGNode; + end + + % Search for this parent node in the list of all nodes + parents = userdata.parents; + nodeIdx = nodedata.idx; + + if isJavaNode && isempty(nodeIdx) % Failback, in case userdata doesn't work for some reason... + for hIdx = 1 : length(hdls) + %if isequal(handle(parentNode.getUserObject), hdls(hIdx)) + if isequal(handle(nodedata.obj), hdls(hIdx)) + nodeIdx = hIdx; + break; + end + end + end + if ~isJavaNode + if isRootHGNode % =root HG node + thisChildHandle = userdata.hg_handles(1); + childName = getNodeName(thisChildHandle); + hasGrandChildren = any(parents==1); + icon = []; + if hasGrandChildren && length(hg_handles)>1 + childName = childName.concat(' - HG root container'); + icon = [iconpath 'figureicon.gif']; + end + try + nodes = uitreenode('v0', thisChildHandle, childName, icon, ~hasGrandChildren); + catch % old matlab version don't have the 'v0' option + try + nodes = uitreenode(thisChildHandle, childName, icon, ~hasGrandChildren); + catch + % probably an invalid handle - ignore... + end + end + + % Add the handler to the node's internal data + % Note: could also use 'userdata', but setUserObject() is recommended for TreeNodes + % Note2: however, setUserObject() sets a java *BeenAdapter object for HG handles instead of the required original class, so use setappdata + %nodes.setUserObject(thisChildHandle); + setappdata(nodes,'childHandle',thisChildHandle); + nodedata.idx = 1; + nodedata.obj = thisChildHandle; + set(nodes,'userdata',nodedata); + return; + else % non-root HG node + parents = userdata.hg_parents; + hdls = userdata.hg_handles; + end % if isRootHGNode + end % if ~isJavaNode + + % If this node was found, get the list of its children + if ~isempty(nodeIdx) + %childIdx = setdiff(find(parents==nodeIdx),nodeIdx); + childIdx = find(parents==nodeIdx); + childIdx(childIdx==nodeIdx) = []; % faster... + numChildren = length(childIdx); + for cIdx = 1 : numChildren + thisChildIdx = childIdx(cIdx); + try thisChildHandle = hdls(thisChildIdx); catch, continue, end + childName = getNodeName(thisChildHandle); + try + visible = thisChildHandle.Visible; + if visible + try visible = thisChildHandle.Width > 0; catch, end %#ok + end + if ~visible + childName = ['' char(childName) '']; %#ok grow + end + catch + % never mind... + end + hasGrandChildren = any(parents==thisChildIdx); + try + isaLabel = isa(thisChildHandle.java,'javax.swing.JLabel'); + catch + isaLabel = 0; + end + if hasGrandChildren && ~any(strcmp(class(thisChildHandle),{'axes'})) + icon = [iconpath 'foldericon.gif']; + elseif isaLabel + icon = [iconpath 'tool_text.gif']; + else + icon = []; + end + try + nodes(cIdx) = uitreenode('v0', thisChildHandle, childName, icon, ~hasGrandChildren); + catch % old matlab version don't have the 'v0' option + try + nodes(cIdx) = uitreenode(thisChildHandle, childName, icon, ~hasGrandChildren); + catch + % probably an invalid handle - ignore... + end + end + + % Use existing object icon, if available + try + setTreeNodeIcon(nodes(cIdx),thisChildHandle); + catch + % probably an invalid handle - ignore... + end + + % Pre-select the node based upon the user's FINDJOBJ filters + try + if isJavaNode && ~userdata.userSelected && any(userdata.initialIdx == thisChildIdx) + pause(0.0002); % as short as possible... + drawnow; + if isempty(tree.getSelectedNodes) + tree.setSelectedNode(nodes(cIdx)); + else + newSelectedNodes = [tree.getSelectedNodes, nodes(cIdx).java]; + tree.setSelectedNodes(newSelectedNodes); + end + end + catch + % never mind... + end + + % Add the handler to the node's internal data + % Note: could also use 'userdata', but setUserObject() is recommended for TreeNodes + % Note2: however, setUserObject() sets a java *BeenAdapter object for HG handles instead of the required original class, so use setappdata + % Note3: the following will error if invalid handle - ignore + try + if isJavaNode + thisChildHandle = thisChildHandle.java; + end + %nodes(cIdx).setUserObject(thisChildHandle); + setappdata(nodes(cIdx),'childHandle',thisChildHandle); + nodedata.idx = thisChildIdx; + nodedata.obj = thisChildHandle; + set(nodes(cIdx),'userdata',nodedata); + catch + % never mind (probably an invalid handle) - leave unchanged (like a leaf) + end + end + end + catch + % Never mind - leave unchanged (like a leaf) + %error('YMA:findjobj:UnknownNodeType', 'Error expanding component tree node'); + dispError + end + end + + %% Get a node's name + function [nodeName, nodeTitle] = getNodeName(hndl,charsLimit) + try + % Initialize (just in case one of the succeding lines croaks) + nodeName = ''; + nodeTitle = ''; + if ~ismethod(hndl,'getClass') + try + nodeName = class(hndl); + catch + nodeName = hndl.type; % last-ditch try... + end + else + nodeName = hndl.getClass.getSimpleName; + end + + % Strip away the package name, leaving only the regular classname + if ~isempty(nodeName) && ischar(nodeName) + nodeName = java.lang.String(nodeName); + nodeName = nodeName.substring(nodeName.lastIndexOf('.')+1); + end + if (nodeName.length == 0) + % fix case of anonymous internal classes, that do not have SimpleNames + try + nodeName = hndl.getClass.getName; + nodeName = nodeName.substring(nodeName.lastIndexOf('.')+1); + catch + % never mind - leave unchanged... + end + end + + % Get any unique identifying string (if available in one of several fields) + labelsToCheck = {'label','title','text','string','displayname','toolTipText','TooltipString','actionCommand','name','Tag','style'}; %,'UIClassID'}; + nodeTitle = ''; + strField = ''; %#ok - used for debugging + while ((~isa(nodeTitle,'java.lang.String') && ~ischar(nodeTitle)) || isempty(nodeTitle)) && ~isempty(labelsToCheck) + try + nodeTitle = get(hndl,labelsToCheck{1}); + strField = labelsToCheck{1}; %#ok - used for debugging + catch + % never mind - probably missing prop, so skip to next one + end + labelsToCheck(1) = []; + end + if length(nodeTitle) ~= numel(nodeTitle) + % Multi-line - convert to a long single line + nodeTitle = nodeTitle'; + nodeTitle = nodeTitle(:)'; + end + if isempty(char(nodeTitle)) + % No title - check whether this is an HG label whose text is gettable + try + location = hndl.getLocationOnScreen; + pos = [location.getX, location.getY, hndl.getWidth, hndl.getHeight]; + %dist = sum((labelPositions-repmat(pos,size(labelPositions,1),[1,1,1,1])).^2, 2); + dist = sum((labelPositions-repmat(pos,[size(labelPositions,1),1])).^2, 2); + [minVal,minIdx] = min(dist); + % Allow max distance of 8 = 2^2+2^2 (i.e. X&Y off by up to 2 pixels, W&H exact) + if minVal <= 8 % 8=2^2+2^2 + nodeTitle = get(hg_labels(minIdx),'string'); + % Preserve the label handles & position for the tooltip & context-menu + %hg_labels(minIdx) = []; + %labelPositions(minIdx,:) = []; + end + catch + % never mind... + end + end + if nargin<2, charsLimit = 25; end + extraStr = regexprep(nodeTitle,{sprintf('(.{%d,%d}).*',charsLimit,min(charsLimit,length(nodeTitle)-1)),' +'},{'$1...',' '},'once'); + if ~isempty(extraStr) + if ischar(extraStr) + nodeName = nodeName.concat(' (''').concat(extraStr).concat(''')'); + else + nodeName = nodeName.concat(' (').concat(num2str(extraStr)).concat(')'); + end + %nodeName = nodeName.concat(strField); + end + catch + % Never mind - use whatever we have so far + %dispError + end + end + + %% Strip standard Swing callbacks from a list of events + function evNames = stripStdCbs(evNames) + try + stdEvents = {'AncestorAdded', 'AncestorMoved', 'AncestorRemoved', 'AncestorResized', ... + 'ComponentAdded', 'ComponentRemoved', 'ComponentHidden', ... + 'ComponentMoved', 'ComponentResized', 'ComponentShown', ... + 'FocusGained', 'FocusLost', 'HierarchyChanged', ... + 'KeyPressed', 'KeyReleased', 'KeyTyped', ... + 'MouseClicked', 'MouseDragged', 'MouseEntered', 'MouseExited', ... + 'MouseMoved', 'MousePressed', 'MouseReleased', 'MouseWheelMoved', ... + 'PropertyChange', 'VetoableChange', ... + 'CaretPositionChanged', 'InputMethodTextChanged', ... + 'ButtonDown', 'Create', 'Delete'}; + stdEvents = [stdEvents, strcat(stdEvents,'Callback'), strcat(stdEvents,'Fcn')]; + evNames = setdiff(evNames,stdEvents)'; + catch + % Never mind... + dispError + end + end + + %% Callback function for checkbox + function cbHideStdCbs_Callback(src, evd, callbacksTable, varargin) %#ok + try + % Store the current checkbox value for later use + if nargin < 3 + try + callbacksTable = get(src,'userdata'); + catch + callbacksTable = getappdata(src,'userdata'); + end + end + if evd.getSource.isSelected + setappdata(callbacksTable,'hideStdCbs',1); + else + setappdata(callbacksTable,'hideStdCbs',[]); + end + + % Rescan the current node + try + userdata = get(callbacksTable,'userdata'); + catch + userdata = getappdata(callbacksTable,'userdata'); + end + nodepath = userdata.jTree.getSelectionModel.getSelectionPath; + try + ed.getCurrentNode = nodepath.getLastPathComponent; + nodeSelected(handle(userdata.jTreePeer),ed,[]); + catch + % ignore - probably no node selected + end + catch + % Never mind... + dispError + end + end + + %% Callback function for button + function btWebsite_Callback(src, evd, varargin) %#ok + try + web('http://UndocumentedMatlab.com','-browser'); + catch + % Never mind... + dispError + end + end + + %% Callback function for button + function btRefresh_Callback(src, evd, varargin) %#ok + try + % Set cursor shape to hourglass until we're done + hTreeFig = varargin{2}; + set(hTreeFig,'Pointer','watch'); + drawnow; + object = varargin{1}; + + % Re-invoke this utility to re-scan the container for all children + findjobj(object); + catch + % Never mind... + end + + % Restore default cursor shape + set(hTreeFig,'Pointer','arrow'); + end + + %% Callback function for button + function btExport_Callback(src, evd, varargin) %#ok + try + % Get the list of all selected nodes + if length(varargin) > 1 + jTree = varargin{1}; + numSelections = jTree.getSelectionCount; + selectionPaths = jTree.getSelectionPaths; + hdls = handle([]); + for idx = 1 : numSelections + %hdls(idx) = handle(selectionPaths(idx).getLastPathComponent.getUserObject); + nodedata = get(selectionPaths(idx).getLastPathComponent,'userdata'); + try + hdls(idx) = handle(nodedata.obj,'CallbackProperties'); + catch + if idx==1 % probably due to HG2: can't convert object to handle([]) + hdls = nodedata.obj; + else + hdls(idx) = nodedata.obj; + end + end + end + + % Assign the handles in the base workspace & inform user + assignin('base','findjobj_hdls',hdls); + classNameLabel = varargin{2}; + msg = ['Exported ' char(classNameLabel.getText.trim) ' to base workspace variable findjobj_hdls']; + else + % Right-click (context-menu) callback + data = varargin{1}; + obj = data{1}; + varName = data{2}; + if isempty(varName) + varName = inputdlg('Enter workspace variable name','FindJObj'); + if isempty(varName), return; end % bail out on + varName = varName{1}; + if isempty(varName) || ~ischar(varName), return; end % bail out on empty/null + varName = genvarname(varName); + end + assignin('base',varName,handle(obj,'CallbackProperties')); + msg = ['Exported object to base workspace variable ' varName]; + end + msgbox(msg,'FindJObj','help'); + catch + % Never mind... + dispError + end + end + + %% Callback function for button + function btFocus_Callback(src, evd, varargin) %#ok + try + % Request focus for the specified object + object = getTopSelectedObject(varargin{:}); + object.requestFocus; + catch + try + object = object.java.getPeer.requestFocus; + object.requestFocus; + catch + % Never mind... + %dispError + end + end + end + + %% Callback function for button + function btInspect_Callback(src, evd, varargin) %#ok + try + % Inspect the specified object + if length(varargin) == 1 + object = varargin{1}; + else + object = getTopSelectedObject(varargin{:}); + end + if isempty(which('uiinspect')) + + % If the user has not indicated NOT to be informed about UIInspect + if ~ispref('FindJObj','dontCheckUIInspect') + + % Ask the user whether to download UIINSPECT (YES, no, no & don't ask again) + answer = questdlg({'The object inspector requires UIINSPECT from the MathWorks File Exchange. UIINSPECT was created by Yair Altman, like this FindJObj utility.','','Download & install UIINSPECT?'},'UIInspect','Yes','No','No & never ask again','Yes'); + switch answer + case 'Yes' % => Yes: download & install + try + % Download UIINSPECT + baseUrl = 'http://www.mathworks.com/matlabcentral/fileexchange/17935'; + fileUrl = [baseUrl '?controller=file_infos&download=true']; + %file = urlread(fileUrl); + %file = regexprep(file,[char(13),char(10)],'\n'); %convert to OS-dependent EOL + + % Install... + %newPath = fullfile(fileparts(which(mfilename)),'uiinspect.m'); + %fid = fopen(newPath,'wt'); + %fprintf(fid,'%s',file); + %fclose(fid); + [fpath,fname,fext] = fileparts(which(mfilename)); + zipFileName = fullfile(fpath,'uiinspect.zip'); + urlwrite(fileUrl,zipFileName); + unzip(zipFileName,fpath); + rehash; + catch + % Error downloading: inform the user + msgbox(['Error in downloading: ' lasterr], 'UIInspect', 'warn'); %#ok + web(baseUrl); + end + + % ...and now run it... + %pause(0.1); + drawnow; + dummy = which('uiinspect'); %#ok used only to load into memory + uiinspect(object); + return; + + case 'No & never ask again' % => No & don't ask again + setpref('FindJObj','dontCheckUIInspect',1); + + otherwise + % forget it... + end + end + drawnow; + + % No UIINSPECT available - run the good-ol' METHODSVIEW()... + methodsview(object); + else + uiinspect(object); + end + catch + try + if isjava(object) + methodsview(object) + else + methodsview(object.java); + end + catch + % Never mind... + dispError + end + end + end + + %% Callback function for button + function btCheckFex_Callback(src, evd, varargin) %#ok + try + % Check the FileExchange for the latest version + web('http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=14317'); + catch + % Never mind... + dispError + end + end + + %% Check for existence of a newer version + function checkVersion() + try + % If the user has not indicated NOT to be informed + if ~ispref('FindJObj','dontCheckNewerVersion') + + % Get the latest version date from the File Exchange webpage + baseUrl = 'http://www.mathworks.com/matlabcentral/fileexchange/'; + webUrl = [baseUrl '14317']; % 'loadFile.do?objectId=14317']; + webPage = urlread(webUrl); + modIdx = strfind(webPage,'>Updates<'); + if ~isempty(modIdx) + webPage = webPage(modIdx:end); + % Note: regexp hangs if substr not found, so use strfind instead... + %latestWebVersion = regexprep(webPage,'.*?>(20[\d-]+).*','$1'); + dateIdx = strfind(webPage,'class=""date"">'); + if ~isempty(dateIdx) + latestDate = webPage(dateIdx(end)+13 : dateIdx(end)+23); + try + startIdx = dateIdx(end)+27; + descStartIdx = startIdx + strfind(webPage(startIdx:startIdx+999),''); + descEndIdx = startIdx + strfind(webPage(startIdx:startIdx+999),''); + descStr = webPage(descStartIdx(1)+3 : descEndIdx(1)-2); + descStr = regexprep(descStr,'',''); + catch + descStr = ''; + end + + % Get this file's latest date + thisFileName = which(mfilename); %#ok + try + thisFileData = dir(thisFileName); + try + thisFileDatenum = thisFileData.datenum; + catch % old ML versions... + thisFileDatenum = datenum(thisFileData.date); + end + catch + thisFileText = evalc('type(thisFileName)'); + thisFileLatestDate = regexprep(thisFileText,'.*Change log:[\s%]+([\d-]+).*','$1'); + thisFileDatenum = datenum(thisFileLatestDate,'yyyy-mm-dd'); + end + + % If there's a newer version on the File Exchange webpage (allow 2 days grace period) + if (thisFileDatenum < datenum(latestDate,'dd mmm yyyy')-2) + + % Ask the user whether to download the newer version (YES, no, no & don't ask again) + msg = {['A newer version (' latestDate ') of FindJObj is available on the MathWorks File Exchange:'], '', ... + ['\color{blue}' descStr '\color{black}'], '', ... + 'Download & install the new version?'}; + createStruct.Interpreter = 'tex'; + createStruct.Default = 'Yes'; + answer = questdlg(msg,'FindJObj','Yes','No','No & never ask again',createStruct); + switch answer + case 'Yes' % => Yes: download & install newer file + try + %fileUrl = [baseUrl '/download.do?objectId=14317&fn=findjobj&fe=.m']; + fileUrl = [baseUrl '/14317?controller=file_infos&download=true']; + %file = urlread(fileUrl); + %file = regexprep(file,[char(13),char(10)],'\n'); %convert to OS-dependent EOL + %fid = fopen(thisFileName,'wt'); + %fprintf(fid,'%s',file); + %fclose(fid); + [fpath,fname,fext] = fileparts(thisFileName); + zipFileName = fullfile(fpath,[fname '.zip']); + urlwrite(fileUrl,zipFileName); + unzip(zipFileName,fpath); + rehash; + catch + % Error downloading: inform the user + msgbox(['Error in downloading: ' lasterr], 'FindJObj', 'warn'); %#ok + web(webUrl); + end + case 'No & never ask again' % => No & don't ask again + setpref('FindJObj','dontCheckNewerVersion',1); + otherwise + % forget it... + end + end + end + else + % Maybe webpage not fully loaded or changed format - bail out... + end + end + catch + % Never mind... + end + end + + %% Get the first selected object (might not be the top one - depends on selection order) + function object = getTopSelectedObject(jTree, root) + try + object = []; + numSelections = jTree.getSelectionCount; + if numSelections > 0 + % Get the first object specified + %object = jTree.getSelectionPath.getLastPathComponent.getUserObject; + nodedata = get(jTree.getSelectionPath.getLastPathComponent,'userdata'); + else + % Get the root object (container) + %object = root.getUserObject; + nodedata = get(root,'userdata'); + end + object = nodedata.obj; + catch + % Never mind... + dispError + end + end + + %% Update component callback upon callbacksTable data change + function tbCallbacksChanged(src, evd, object, table) + persistent hash + try + % exit if invalid handle or already in Callback + %if ~ishandle(src) || ~isempty(getappdata(src,'inCallback')) % || length(dbstack)>1 %exit also if not called from user action + if isempty(hash), hash = java.util.Hashtable; end + if ~ishandle(src) || ~isempty(hash.get(src)) % || length(dbstack)>1 %exit also if not called from user action + return; + end + %setappdata(src,'inCallback',1); % used to prevent endless recursion % can't use getappdata(src,...) because it fails on R2010b!!! + hash.put(src,1); + + % Update the object's callback with the modified value + modifiedColIdx = evd.getColumn; + modifiedRowIdx = evd.getFirstRow; + if modifiedRowIdx>=0 %&& modifiedColIdx==1 %sanity check - should always be true + %table = evd.getSource; + %object = get(src,'userdata'); + modifiedRowIdx = table.getSelectedRow; % overcome issues with hierarchical table + cbName = strtrim(table.getValueAt(modifiedRowIdx,0)); + try + cbValue = strtrim(char(table.getValueAt(modifiedRowIdx,1))); + if ~isempty(cbValue) && ismember(cbValue(1),'{[@''') + cbValue = eval(cbValue); + end + if (~ischar(cbValue) && ~isa(cbValue, 'function_handle') && (~iscell(cbValue) || iscom(object(1)))) + revertCbTableModification(table, modifiedRowIdx, modifiedColIdx, cbName, object, ''); + else + for objIdx = 1 : length(object) + obj = object(objIdx); + if ~iscom(obj) + try + try + if isjava(obj) + obj = handle(obj,'CallbackProperties'); + end + catch + % never mind... + end + set(obj, cbName, cbValue); + catch + try + set(handle(obj,'CallbackProperties'), cbName, cbValue); + catch + % never mind - probably a callback-group header + end + end + else + cbs = obj.eventlisteners; + if ~isempty(cbs) + cbs = cbs(strcmpi(cbs(:,1),cbName),:); + obj.unregisterevent(cbs); + end + if ~isempty(cbValue) && ~strcmp(cbName,'-') + obj.registerevent({cbName, cbValue}); + end + end + end + end + catch + revertCbTableModification(table, modifiedRowIdx, modifiedColIdx, cbName, object, lasterr) %#ok + end + end + catch + % never mind... + end + %setappdata(src,'inCallback',[]); % used to prevent endless recursion % can't use setappdata(src,...) because it fails on R2010b!!! + hash.remove(src); + end + + %% Revert Callback table modification + function revertCbTableModification(table, modifiedRowIdx, modifiedColIdx, cbName, object, errMsg) %#ok + try + % Display a notification MsgBox + msg = 'Callbacks must be a ''string'', or a @function handle'; + if ~iscom(object(1)), msg = [msg ' or a {@func,args...} construct']; end + if ~isempty(errMsg), msg = {errMsg, '', msg}; end + msgbox(msg, ['Error setting ' cbName ' value'], 'warn'); + + % Revert to the current value + curValue = ''; + try + if ~iscom(object(1)) + curValue = charizeData(get(object(1),cbName)); + else + cbs = object(1).eventlisteners; + if ~isempty(cbs) + cbs = cbs(strcmpi(cbs(:,1),cbName),:); + curValue = charizeData(cbs(1,2)); + end + end + catch + % never mind... - clear the current value + end + table.setValueAt(curValue, modifiedRowIdx, modifiedColIdx); + catch + % never mind... + end + end % revertCbTableModification + + %% Get the Java positions of all HG text labels + function labelPositions = getLabelsJavaPos(container) + try + labelPositions = []; + + % Ensure we have a figure handle + try + h = hFig; %#ok unused + catch + hFig = getCurrentFigure; + end + + % Get the figure's margins from the Matlab properties + hg_labels = findall(hFig, 'Style','text'); + units = get(hFig,'units'); + set(hFig,'units','pixels'); + outerPos = get(hFig,'OuterPosition'); + innerPos = get(hFig,'Position'); + set(hFig,'units',units); + margins = abs(innerPos-outerPos); + + figX = container.getX; % =outerPos(1) + figY = container.getY; % =outerPos(2) + %figW = container.getWidth; % =outerPos(3) + figH = container.getHeight; % =outerPos(4) + + % Get the relevant screen pixel size + %monitorPositions = get(0,'MonitorPositions'); + %for monitorIdx = size(monitorPositions,1) : -1 : 1 + % screenSize = monitorPositions(monitorIdx,:); + % if (outerPos(1) >= screenSize(1)) % && (outerPos(1)+outerPos(3) <= screenSize(3)) + % break; + % end + %end + %monitorBaseY = screenSize(4) - monitorPositions(1,4); + + % Compute the labels' screen pixel position in Java units ([0,0] = top left) + for idx = 1 : length(hg_labels) + matlabPos = getpixelposition(hg_labels(idx),1); + javaX = figX + matlabPos(1) + margins(1); + javaY = figY + figH - matlabPos(2) - matlabPos(4) - margins(2); + labelPositions(idx,:) = [javaX, javaY, matlabPos(3:4)]; %#ok grow + end + catch + % never mind... + err = lasterror; %#ok debug point + end + end + + %% Traverse an HG container hierarchy and extract the HG elements within + function traverseHGContainer(hcontainer,level,parent) + try + % Record the data for this node + thisIdx = length(hg_levels) + 1; + hg_levels(thisIdx) = level; + hg_parentIdx(thisIdx) = parent; + try + hg_handles(thisIdx) = handle(hcontainer); + catch + hg_handles = handle(hcontainer); + end + parentId = length(hg_parentIdx); + + % Now recursively process all this node's children (if any) + %if ishghandle(hcontainer) + try % try-catch is faster than checking ishghandle(hcontainer)... + allChildren = allchild(handle(hcontainer)); + for childIdx = 1 : length(allChildren) + traverseHGContainer(allChildren(childIdx),level+1,parentId); + end + catch + % do nothing - probably not a container + %dispError + end + + % TODO: Add axis (plot) component handles + catch + % forget it... + end + end + + %% Debuggable ""quiet"" error-handling + function dispError + err = lasterror; %#ok + msg = err.message; + for idx = 1 : length(err.stack) + filename = err.stack(idx).file; + if ~isempty(regexpi(filename,mfilename)) + funcname = err.stack(idx).name; + line = num2str(err.stack(idx).line); + msg = [msg ' at ' funcname ' line #' line '']; %#ok grow + break; + end + end + disp(msg); + return; % debug point + end + + %% ML 7.0 - compatible ischar() function + function flag = ischar(data) + try + flag = builtin('ischar',data); + catch + flag = isa(data,'char'); + end + end + + %% Set up the uitree context (right-click) menu + function jmenu = setTreeContextMenu(obj,node,tree_h) + % Prepare the context menu (note the use of HTML labels) + import javax.swing.* + titleStr = getNodeTitleStr(obj,node); + titleStr = regexprep(titleStr,'


.*',''); + menuItem0 = JMenuItem(titleStr); + menuItem0.setEnabled(false); + menuItem0.setArmed(false); + %menuItem1 = JMenuItem('Export handle to findjobj_hdls'); + if isjava(obj), prefix = 'j'; else, prefix = 'h'; end %#ok + varname = strrep([prefix strtok(char(node.getName))], '$','_'); + varname = genvarname(varname); + varname(2) = upper(varname(2)); % ensure lowerCamelCase + menuItem1 = JMenuItem(['Export handle to ' varname]); + menuItem2 = JMenuItem('Export handle to...'); + menuItem3 = JMenuItem('Request focus (bring to front)'); + menuItem4 = JMenuItem('Flash component borders'); + menuItem5 = JMenuItem('Display properties & callbacks'); + menuItem6 = JMenuItem('Inspect object'); + + % Set the menu items' callbacks + set(handle(menuItem1,'CallbackProperties'), 'ActionPerformedCallback', {@btExport_Callback,{obj,varname}}); + set(handle(menuItem2,'CallbackProperties'), 'ActionPerformedCallback', {@btExport_Callback,{obj,[]}}); + set(handle(menuItem3,'CallbackProperties'), 'ActionPerformedCallback', {@requestFocus,obj}); + set(handle(menuItem4,'CallbackProperties'), 'ActionPerformedCallback', {@flashComponent,{obj,0.2,3}}); + set(handle(menuItem5,'CallbackProperties'), 'ActionPerformedCallback', {@nodeSelected,{tree_h,node}}); + set(handle(menuItem6,'CallbackProperties'), 'ActionPerformedCallback', {@btInspect_Callback,obj}); + + % Add all menu items to the context menu (with internal separator) + jmenu = JPopupMenu; + jmenu.add(menuItem0); + jmenu.addSeparator; + handleValue=[]; try handleValue = double(obj); catch, end; %#ok + if ~isempty(handleValue) + % For valid HG handles only + menuItem0a = JMenuItem('Copy handle value to clipboard'); + set(handle(menuItem0a,'CallbackProperties'), 'ActionPerformedCallback', sprintf('clipboard(''copy'',%.99g)',handleValue)); + jmenu.add(menuItem0a); + end + jmenu.add(menuItem1); + jmenu.add(menuItem2); + jmenu.addSeparator; + jmenu.add(menuItem3); + jmenu.add(menuItem4); + jmenu.add(menuItem5); + jmenu.add(menuItem6); + end % setTreeContextMenu + + %% Set the mouse-press callback + function treeMousePressedCallback(hTree, eventData, tree_h) %#ok hTree is unused + if eventData.isMetaDown % right-click is like a Meta-button + % Get the clicked node + clickX = eventData.getX; + clickY = eventData.getY; + jtree = eventData.getSource; + treePath = jtree.getPathForLocation(clickX, clickY); + try + % Modify the context menu based on the clicked node + node = treePath.getLastPathComponent; + userdata = get(node,'userdata'); + obj = userdata.obj; + jmenu = setTreeContextMenu(obj,node,tree_h); + + % TODO: remember to call jmenu.remove(item) in item callback + % or use the timer hack shown here to remove the item: + % timerFcn = {@menuRemoveItem,jmenu,item}; + % start(timer('TimerFcn',timerFcn,'StartDelay',0.2)); + + % Display the (possibly-modified) context menu + jmenu.show(jtree, clickX, clickY); + jmenu.repaint; + + % This is for debugging: + userdata.tree = jtree; + setappdata(gcf,'findjobj_hgtree',userdata) + catch + % clicked location is NOT on top of any node + % Note: can also be tested by isempty(treePath) + end + end + end % treeMousePressedCallback + + %% Remove the extra context menu item after display + function menuRemoveItem(hObj,eventData,jmenu,item) %#ok unused + jmenu.remove(item); + end % menuRemoveItem + + %% Get the title for the tooltip and context (right-click) menu + function nodeTitleStr = getNodeTitleStr(obj,node) + try + % Display the full classname and object name in the tooltip + %nodeName = char(node.getName); + %nodeName = strrep(nodeName, '',''); + %nodeName = strrep(nodeName, '',''); + nodeName = char(getNodeName(obj,99)); + [objClass,objName] = strtok(nodeName); + objName = objName(3:end-1); % strip leading ( and trailing ) + if isempty(objName), objName = '(none found)'; end + nodeName = char(node.getName); + objClass = char(obj.getClass.getName); + nodeTitleStr = sprintf('Class name: %s
Text/title: %s',objClass,objName); + + % If the component is invisible, state this in the tooltip + if ~isempty(strfind(nodeName,'color=""gray""')) + nodeTitleStr = [nodeTitleStr '
*** Invisible ***']; + end + nodeTitleStr = [nodeTitleStr '
Right-click for context-menu']; + catch + % Possible not a Java object - try treating as an HG handle + try + handleValueStr = sprintf('#: %.99g',double(obj)); + try + type = ''; + type = get(obj,'type'); + type(1) = upper(type(1)); + catch + if ~ishandle(obj) + type = ['Invalid ' char(node.getName) '']; + handleValueStr = '!!!
Perhaps this handle was deleted after this UIInspect tree was
already drawn. Try to refresh by selecting any valid node handle'; + end + end + nodeTitleStr = sprintf('%s handle %s',type,handleValueStr); + try + % If the component is invisible, state this in the tooltip + if strcmp(get(obj,'Visible'),'off') + nodeTitleStr = [nodeTitleStr '
Invisible']; + end + catch + % never mind... + end + catch + % never mind... - ignore + end + end + end % getNodeTitleStr + + %% Handle tree mouse movement callback - used to set the tooltip & context-menu + function treeMouseMovedCallback(hTree, eventData) + try + x = eventData.getX; + y = eventData.getY; + jtree = eventData.getSource; + treePath = jtree.getPathForLocation(x, y); + try + % Set the tooltip string based on the hovered node + node = treePath.getLastPathComponent; + userdata = get(node,'userdata'); + obj = userdata.obj; + tooltipStr = getNodeTitleStr(obj,node); + set(hTree,'ToolTipText',tooltipStr) + catch + % clicked location is NOT on top of any node + % Note: can also be tested by isempty(treePath) + end + catch + dispError; + end + return; % denug breakpoint + end % treeMouseMovedCallback + + %% Request focus for a specific object handle + function requestFocus(hTree, eventData, obj) %#ok hTree & eventData are unused + % Ensure the object handle is valid + if isjava(obj) + obj.requestFocus; + return; + elseif ~ishandle(obj) + msgbox('The selected object does not appear to be a valid handle as defined by the ishandle() function. Perhaps this object was deleted after this hierarchy tree was already drawn. Refresh this tree by selecting a valid node handle and then retry.','FindJObj','warn'); + beep; + return; + end + + try + foundFlag = 0; + while ~foundFlag + if isempty(obj), return; end % sanity check + type = get(obj,'type'); + obj = double(obj); + foundFlag = any(strcmp(type,{'figure','axes','uicontrol'})); + if ~foundFlag + obj = get(obj,'Parent'); + end + end + feval(type,obj); + catch + % never mind... + dispError; + end + end % requestFocus + +end % FINDJOBJ + +% Fast implementation +function jControl = findjobj_fast(hControl, jContainer) + try jControl = hControl.Table; return, catch, end % fast bail-out for old uitables + try jControl = hControl.JavaFrame.getGUIDEView; return, catch, end % bail-out for HG2 matlab.ui.container.Panel + oldWarn = warning('off','MATLAB:HandleGraphics:ObsoletedProperty:JavaFrame'); + if nargin < 2 || isempty(jContainer) + % Use a HG2 matlab.ui.container.Panel jContainer if the control's parent is a uipanel + try + hParent = get(hControl,'Parent'); + catch + % Probably indicates an invalid/deleted/empty handle + jControl = []; + return + end + try jContainer = hParent.JavaFrame.getGUIDEView; catch, jContainer = []; end + end + if isempty(jContainer) + hFig = ancestor(hControl,'figure'); + jf = get(hFig, 'JavaFrame'); + jContainer = jf.getFigurePanelContainer.getComponent(0); + end + warning(oldWarn); + jControl = []; + counter = 100; + oldTooltip = get(hControl,'Tooltip'); + set(hControl,'Tooltip','!@#$%^&*'); + while isempty(jControl) && counter>0 + counter = counter - 1; + pause(0.001); + jControl = findTooltipIn(jContainer); + end + set(hControl,'Tooltip',oldTooltip); + try jControl.setToolTipText(oldTooltip); catch, end + try jControl = jControl.getParent.getView.getParent.getParent; catch, end % return JScrollPane if exists +end +function jControl = findTooltipIn(jContainer) + try + jControl = []; % Fix suggested by H. Koch 11/4/2017 + tooltipStr = jContainer.getToolTipText; + %if strcmp(char(tooltipStr),'!@#$%^&*') + if ~isempty(tooltipStr) && tooltipStr.startsWith('!@#$%^&*') % a bit faster + jControl = jContainer; + else + for idx = 1 : jContainer.getComponentCount + jControl = findTooltipIn(jContainer.getComponent(idx-1)); + if ~isempty(jControl), return; end + end + end + catch + % ignore + end +end + +%% TODO TODO TODO +%{ +- Enh: Improve interactive-GUI performance - esp. expandNode() +- Enh: Add property listeners - same problem in MathWork's inspect.m +- Enh: Display additional properties - same problem in MathWork's inspect.m +- Enh: Add axis (plot, Graphics) component handles +- Enh: Add figure thumbnail image below the java tree (& indicate corresponding jObject when selected) +- Enh: scroll initially-selected node into view (problem because treenode has no pixel location) +- Fix: java exceptions when getting some fields (com.mathworks.mlwidgets.inspector.PropertyRootNode$PropertyListener$1$1.run) +- Fix: use EDT if available (especially in flashComponent) +%}","MATLAB" +"Neurology","ChristianGaser/cat12","internal/cat_tst_Rusak2021.m",".m","16261","410","function cat_tst_Rusak2021(Pmethod,Presdir,datas,localstat,subset) +%cat_tst_Rusak2021. Evaluate Rusak 2021 phantom data from cat_tst_main. +% +% cat_tst_Rusak2021(Pmethod,Presdir,subset) +% +% Pmethod .. see cat_tst_main +% Presdir .. see cat_tst_main +% subset .. use subset with 6 subjects and 6 cases, i.e., n36 +% otherwise use full set (20 subjects, 20 cases, i.e., n400) +% +% TODO: +% - add local change maps ? +% - add other measures (rGMV, intensity, ...) +% - add SPM regression analysis + +%#ok<*SAGROW +%#ok<*AGROW> + + % add Rusak subdir + if ~exist('subset','var'), subset = 1; end + if ~exist('datas','var'), datas = {'thickness','pbt'}; end + if subset, subsetn = 'n36'; else, subsetn = 'n400'; end + for pi = size(Pmethod,1):-1:1 + if any(contains(Pmethod{pi,1},'T1Prep')) + if exist(fullfile(Pmethod{pi,2}, 'surf'),'dir') + Pmethod(pi,2) = fullfile(Pmethod(pi,2), 'surf'); + else + Pmethod(pi,2) = fullfile(Pmethod(pi,2), sprintf('16_Rusak2021%s',subsetn), 'surf'); + end + else + Pmethod(pi,2) = fullfile(Pmethod(pi,2), sprintf('16_Rusak2021%s',subsetn)); + end + if ~exist( Pmethod{pi,2} ,'dir') + cat_io_cprintf('err','Miss directory %s.\n',Pmethod{pi,2}); + Pmethod(pi,:) = []; + end + end + Presdir = fullfile(Presdir,sprintf('Rusak2021',subsetn')); + + + %% load data + fprintf('Load data 1: '); + for di = 1:numel(datas) + mnthick = nan(1,size(Pmethod,1)); + mdthick = nan(1,size(Pmethod,1)); + Psurf = cell(1,size(Pmethod,1)); + Pdata = cell(1,size(Pmethod,1)); + for pi = 1:size(Pmethod,1) + fprintf('\n Method %2d/%2d: %16s', pi, size(Pmethod,1), Pmethod{pi} ) + if pi == 1 + Psurf{pi} = cat_vol_findfiles(Pmethod{pi,2},'lh.central.sub-ADNI*simGMatrophy*'); + Pdata{pi} = cat_vol_findfiles(Pmethod{pi,2},sprintf('lh.%s.sub-ADNI*simGMatrophy*',datas{di})); + Pexist = zeros(numel(Pdata{pi}), size(Pmethod,1)); + else + Psurf{pi} = cat_io_strrep(Psurf{1}, Pmethod{1,2}, Pmethod{pi,2} ); + Pdata{pi} = cat_io_strrep(Pdata{1}, Pmethod{1,2}, Pmethod{pi,2} ); + end + % find missing files + Pexist(:,pi) = cellfun(@(x) exist(x,'file'),Pdata{pi}); + end + + % remove full method in case of the to many missing files (or if just the n36 are done in case of T1Prep) + for pi = size(Pmethod,1):-1:1 + if ~subset && sum( Pexist(:,pi) )/2 < 350 + cat_io_cprintf('err','\nMiss full data of method %d. Exclude method (path: %s).', pi, Pmethod{pi,2}); + Pmethod(pi,:) = []; + Pexist(:,pi) = []; + Psurf{1,pi} = []; + Pdata{1,pi} = []; + mnthick(pi) = []; + mdthick(pi) = []; + end + end + + + %% remove missing files in all testsets + if any(Pexist(:)==0) + cat_io_cprintf('err','\n\nMissing files:'); + for pi = 1:size(Pmethod,1) + if all(Pexist(:,pi)==0) + cat_io_cprintf('err','Miss all files in %s',Pmethod{pi,2}) + elseif ~all(Pexist(:,pi)==2) + Psurf{pi}( Pexist(:,pi)==0 ) + end + end + else + cat_io_cprintf([0 0.5 0],'\n\nNo missing files!\n'); + end + + % remove unused + %for pi = 1:size(Pmethod,1) + % Psurf{pi}( sum(Pexist==0,2)>0 ) = []; + % Pfiles{pi}( sum(Pexist==0,2)>0 ) = []; + %end + fprintf('\nLoad data 2: '); + S = cell(size(Pmethod,1),numel(Pdata{pi})); cdata = S; + for pi = 1:size(Pmethod,1) + fprintf('\n Method %2d/%2d: %16s', pi, size(Pmethod,1), Pmethod{pi} ) + for si = 1:numel(Pdata{pi}) + txt = sprintf(' Load subject %3d/%3d', si,numel(Pdata{pi})); + if si > 1, fprintf(repmat('\b',1,numel(txt))); end + fprintf(txt); + + try + S{pi,si} = gifti(Psurf{pi}{si}); + cdata{pi,si} = cat_io_FreeSurfer('read_surf_data',Pdata{pi}{si}); + catch + S{pi,si} = struct(); + cdata{pi,si} = nan; + end + + % masking of the CC would be better ... but no simple way + mnthick(si,pi) = cat_stat_nanmean(cdata{pi,si}); %(cdata{pi,si}>.75)); + mdthick(si,pi) = cat_stat_nanmedian(cdata{pi,si}); %(cdata{pi,si}>.75)); + end + end + + + % get basic information from filename + ff = spm_str_manip(Pdata{pi},'t'); + ffsubid = strfind(ff{1},'sub-ADNI'); + subject = cellfun(@(ffc) ffc(ffsubid+8:ffsubid+8+7),ff,'UniformOutput',false); + subid = zeros(size(subject)); sd = unique(subject); for si = 1:numel(sd), subid( contains(subject,sd{si}) ) = si; end + atrophy = cellfun(@(ffc) ffc(end-5:end-2),ff,'UniformOutput',false); + atrophynum = cellfun( @str2num, atrophy); + age = 20 + 80*atrophynum; + sex = zeros(size(atrophynum)); + HC = ones(size(atrophynum)); + tiv = 1000 * ones(size(atrophynum,1),size(Pmethod,1)); + % #### get real values from ADNI files or is there a CSV? ####### + scan = strcat(subject,'_',atrophy); + fprintf('\nLoad data done. \n\n'); + + + %% local mapping + %% ??? + % - what with CC? masking? + if 0 + fprintf('Map data: \n'); + rmse = @(x) mean(x.^2).^.5; + + for pi = 1:size(Pmethod,1) + fprintf(' Method %2d/%2d: %16s\n', pi, Pmethod{pi}, size(Pmethod,1)) + + for si = 1:numel(subject) + fprintf(' Process subject %d - %s\n', si, scan{si}) + if atrophynum(si) > 0 + cdatam{pi,si} = cat_surf_fun('cdatamapping', ... + S{pi,contains(scan,[subject{si} '_0.00'])}, S{pi,si}, cdata{pi,si}); + else + cdatam{pi,si} = cdata{pi,si}; + end + try + cdatadiff(si,pi) = rmse( cdatam{pi,si} - 1/3 .* cat_stat_nanmean( [ ... + (cdatam{pi,contains(scan,[subject{si} '_0.00'])} + 0.00), ... + (cdatam{pi,contains(scan,[subject{si} '_0.02'])} + 0.02), ... + (cdatam{pi,contains(scan,[subject{si} '_0.05'])} + 0.05) ] ) ); + catch + cdatadiff(si,pi) = rmse( cdatam{pi,si} - cdatam{pi,contains(scan,[subject{si} '_0.00'])} ); + end + end + end + %% this is not working + if 1 + clear cdatasub cdatamed0 cdatadiff + for pi = 1:size(Pmethod,1) + for si = 1:numel(subject) + cdatamed0{pi,si} = cdatam{pi,si}; % + atrophynum(si); + end + for ssi = 1:max(subid(:)) + cdatasub{pi,ssi} = median( [ cdatamed0{pi,subid==ssi}] ,2 ); + end + % + % for si = 1:numel(subject) + % cdatadiff(pi,si) = rmse( cdatam{pi,si} - cdatasub{pi,subid(si)} ); + % end + end + end + end + + +% Presdir, age, + + + %% create statistics ... as (i) cross-sectional and (ii) as longitudinal analysis + onlyAllreadySmoothed = 0; + if localstat + for subset = 1 %1:3 + %% + for pi=1:size(Pmethod,1) + % VBM + %matlabbatch = cat_tst_agereg( Pgmv{pi}, Presdir, Pmethod{pi,1}, 'GMV', age, sex, cohort==1, tiv(:,pi), 1, onlyAllreadySmoothed); + %if ~isempty(matlabbatch), spm_jobman('run',matlabbatch); end + + % SBM + for sm = {'pbt'} %,'thickness'} ... thickness not working - similar results ... + %% + nsub = numel(unique(subid) ); + Pdatapi = strrep( Pdata{pi} ,sprintf('lh.%s.',datas{di}), sprintf('lh.%s.',sm{1})); + switch subset + case 1, ss = (1:numel(age))'; Presdirss = fullfile( Presdir, '6TP_1.0mm'); + case 2, ss = repmat( [1 0 0 0 1 1], 1, nsub)'>0; Presdirss = fullfile(Presdir, '3TP_1.0mm'); % three time points with 0 0.5 and 1 mm loss + case 3, ss = repmat( [1 0 1 1 0 0], 1, nsub)'>0; Presdirss = fullfile(Presdir, '3TP_0.1mm'); % three time points with 0 0.05 and .1 mm loss + case 4, ss = repmat( [1 0 0 1 0 0], 1, nsub)'>0; Presdirss = fullfile(Presdir, '2TP_0.5mm'); % two time points with .5 mm loss + end + %% + matlabbatch = cat_tst_agereg( Pdatapi(ss), [Presdirss '_long'], Pmethod{pi,1}, sm{1}, age(ss), sex(ss), HC(ss), tiv(ss,pi), 1, onlyAllreadySmoothed, subid(ss)); + if ~exist(fullfile(Presdir,'batches'),'dir'), mkdir(Presdir,'batches'); end + save(fullfile(Presdir,'batches',sprintf('Rusak.%s.mat',sm{1})),'matlabbatch'); + if ~isempty(matlabbatch) + try + spm_jobman('run',matlabbatch); + catch + cat_io_cprintf('err',sprintf('Error running matlabbatch ""%s""',Presdirss)); + end + end + %% + if subset == 1 + matlabbatch = cat_tst_agereg( Pdatapi(ss), [Presdirss '_cs'], Pmethod{pi,1}, sm{1}, age(ss), sex(ss), HC(ss), tiv(ss,pi), 1, onlyAllreadySmoothed); + if ~isempty(matlabbatch) + try + spm_jobman('run',matlabbatch); + catch + cat_io_cprintf('err',sprintf('Error running matlabbatch ""%s""',Presdirss)); + end + end + end + end + end + end + end + + + %% create figure + mnthickloss = zeros(numel(subject), size(Pmethod,1)); + mdthickloss = mnthickloss; + fh = figure(33); % set(fh,'Visible',0,'Interruptible',0); + for fi = 1:2 + %% + fprintf('Analyse Rusak data: \n'); + acor = zeros(1,size(Pmethod,1)); afit = cell(size(acor)); + afitp1 = zeros(1,size(Pmethod,1)); + clf, hold on; + fh.Position(3:4) = [600*fi 700]; %+200*(fi-1)]; + + % print for legend + if fi==1 + for pi = 1:size(Pmethod,1) + plot(0,0,'Color',Pmethod{pi,3},'Marker', ... + Pmethod{pi,4},'MarkerFaceColor',Pmethod{pi,3}); + end + else + xt = ceil(size(Pmethod,1) / 5); + tiledlayout(xt, ceil(size(Pmethod,1) / xt), ... + 'TileSpacing', 'compact', 'Padding', 'compact'); + end + + + % main print + for pi = 1:size(Pmethod,1) + if fi==2, fhagex = nexttile; hold on; end + + for si = 1:numel(subject) + try + if 1 + mnthickloss(si,pi) = mnthick(si,pi) - .5 * ... + (mnthick( contains(scan,[subject{si} '_0.00']), pi ) + mnthick( contains(scan,[subject{si} '_0.02']), pi ) +0.02); + mdthickloss(si,pi) = mdthick(si,pi) - .5 * ... + (mdthick( contains(scan,[subject{si} '_0.00']), pi ) + mnthick( contains(scan,[subject{si} '_0.02']), pi ) +0.02); + else + % not only normalize for first scan but for the first x scans corrected for expected atrophy + % ... this is not working + mnthickloss(si,pi) = mnthick(si,pi) - mean(cdatasub{pi,subid(si)}); + mdthickloss(si,pi) = mdthick(si,pi) - median(cdatasub{pi,subid(si)}); + end + catch + % no 0.00 case + mnthickloss(si,pi) = nan; + mdthickloss(si,pi) = nan; + end + end + subs = unique(subject); + if fi == 2 + for si = 1:numel(subs) + subi = contains(scan,subs{si}); + ph = plot( atrophynum(subi) , mnthickloss(subi, pi) ); + ph.Color = max(0,min(1,Pmethod{pi,3}.^.5)); + ph.LineWidth = .25; + ph.Marker = Pmethod{pi,4}; + ph.LineStyle = '--'; + ph.MarkerFaceColor = ph.Color; + end + end + + % plot fit (only linear tissue loss!) + nonan = ~isnan(atrophynum) & ~isnan(mnthickloss(:,pi)); + if any(nonan) + [afit{pi},bfit{pi}] = fit( atrophynum(nonan) , mnthickloss(nonan,pi), 'poly1'); + afitp1(pi) = afit{pi}.p1; + arsq(pi) = bfit{pi}.rsquare; + else + afit{pi} = []; + afitp1(pi) = nan; + arsq(pi) = nan; + end + if ~isempty(afit{pi}) + acor(pi) = corr( atrophynum(nonan) , mnthickloss(nonan,pi) ); + else + acor(pi) = nan; + end + + % plot confidence interval ... ah not really happy with this one + xint = linspace(0, 90,90); + if fi == 1, cover = 0.5; else, cover = 0.05:.1:0.95; end + for ci = 1:numel(cover) + if ~isempty(afit{pi}) + CIO = predint(afit{pi},xint,cover(ci),'obs'); + p = fill([xint'; flip(xint')],[CIO(:,1); flip(CIO(:,2))], Pmethod{pi,3}); + p.FaceAlpha = .1; p.EdgeAlpha = .0; p.EdgeColor = Pmethod{pi,3}; + end + end + + if ~isempty(afit{pi}) + fph = plot( afit{pi}); + fph.Color = Pmethod{pi,3}; + fph.LineWidth = 1.5; + fph.MarkerFaceColor = fph.Color; + % plot main marker + mph = plot( 1, afit{pi}.p1 + afit{pi}.p2 ); + mph.MarkerFaceColor = Pmethod{pi,3}; + mph.MarkerEdgeColor = Pmethod{pi,3}; + mph.Marker = Pmethod{pi,4}; + mph.MarkerSize = 8; + end + + % format + grid on; box on; + ylim([-1.2,0.1]); + xlabel('simulated atrophy (mm)'); + ylabel('estimated atrophy (mm)'); + + xlim([0,1]); + ylim([-1.1 .1]); + plot([0 1],[0 -1],'Color',[0.5 .5 .5]); + set(gca,'FontSize',max(7,min(16,16 / (size(Pmethod,1)/12))),'XTick',0:.2:1,'XTickLabelRotation',0); + if fi==2 + legend off; + title(sprintf('%s',Pmethod{pi,1})); + st = subtitle( strcat(strcat( ... + ... 'n=', num2str(nnz(Pexist(:,pi)==2),'%0.0f'), ', ', ... + 'p1=', num2str(afitp1(pi)','%0.3f'), ... + ', r=', num2str(acor(pi)','%0.3f'), ... + ', r^2=', num2str(arsq(pi),'%0.3f') ))); + st.FontSize = st.FontSize-2; + end + end + if fi==1 + title(sprintf('Rusak2021n%d atrophy phantom',nnz(Pexist(:,pi)==2))); + lgd = legend( strcat( strcat(Pmethod(:,1), ' (', ... + ... 'n=', num2str(sum(Pexist==2)','%0.0f'), ', ', ... + 'p1=', num2str(afitp1','%0.3f'), ... + ', r=', num2str(acor','%0.3f'), ... + ', r^2=', num2str(arsq','%0.3f') , ')' ))); + lgd.Location = 'southwest'; + end + + % ... save ... + ff = sprintf('cat_tst_Rusak2021_plot%d',fi); + if ~exist(Presdir,'dir'), mkdir(Presdir); end + print(fh,fullfile(Presdir,ff),'-r300','-dpng'); + end + + %close(fh); + + + %% write CSV table + tab = [{'method'},{'rho'},{'p1'},{'r^2'},{'n'},{'failed'}; + Pmethod(:,1), num2cell(acor'), num2cell(afitp1'), ... + num2cell(arsq'), num2cell(sum(Pexist==0)'), num2cell(sum(Pexist==2)') ]; + cat_io_csv(fullfile(Presdir, sprintf('%s.csv',ff)),tab); + end + fprintf('done.\n\n'); +end +function matlabbatch = longreport(x) + + mi = 1; + matlabbatch{mi}.spm.tools.cat.tools.check_cov.data_vol = {}; + matlabbatch{mi}.spm.tools.cat.tools.check_cov.data_xml = {''}; + matlabbatch{mi}.spm.tools.cat.tools.check_cov.gap = 3; + matlabbatch{mi}.spm.tools.cat.tools.check_cov.c = {}; + matlabbatch{mi}.spm.tools.cat.tools.check_cov.outdir = {''}; + matlabbatch{mi}.spm.tools.cat.tools.check_cov.fname = 'CATcheckdesign_'; + matlabbatch{mi}.spm.tools.cat.tools.check_cov.save = 0; + + for si = 1:numel() + matlabbatch{si}.spm.tools.cat.tools.long_report.data_vol = {''}; + matlabbatch{si}.spm.tools.cat.tools.long_report.avg_vol = {''}; + matlabbatch{si}.spm.tools.cat.tools.long_report.data_surf = {''}; %% + matlabbatch{si}.spm.tools.cat.tools.long_report.data_xml = {''}; %% + matlabbatch{si}.spm.tools.cat.tools.long_report.timepoints = []; %% + matlabbatch{si}.spm.tools.cat.tools.long_report.opts.smoothvol = 3; + matlabbatch{si}.spm.tools.cat.tools.long_report.opts.smoothsurf = 12; + matlabbatch{si}.spm.tools.cat.tools.long_report.opts.midpoint = 0; + matlabbatch{si}.spm.tools.cat.tools.long_report.opts.plotGMWM = 1; + matlabbatch{si}.spm.tools.cat.tools.long_report.output.vols = 0; + matlabbatch{si}.spm.tools.cat.tools.long_report.output.surfs = 0; + matlabbatch{si}.spm.tools.cat.tools.long_report.output.xml = 1; + matlabbatch{si}.spm.tools.cat.tools.long_report.printlong = 2; + end +end","MATLAB" +"Neurology","ChristianGaser/cat12","internal/PAIL/pale_ui_help.m",".m","2962","74","function varargout = pale_ui_help(varargin) +% PALE_UI_HELP MATLAB code for pale_ui_help.fig +% PALE_UI_HELP, by itself, creates a new PALE_UI_HELP or raises the existing +% singleton*. +% +% H = PALE_UI_HELP returns the handle to a new PALE_UI_HELP or the handle to +% the existing singleton*. +% +% PALE_UI_HELP('CALLBACK',hObject,eventData,handles,...) calls the local +% function named CALLBACK in PALE_UI_HELP.M with the given input arguments. +% +% PALE_UI_HELP('Property','Value',...) creates a new PALE_UI_HELP or raises the +% existing singleton*. Starting from the left, property value pairs are +% applied to the GUI before pale_ui_help_OpeningFcn gets called. An +% unrecognized property name or invalid value makes property application +% stop. All inputs are passed to pale_ui_help_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 pale_ui_help + +% Last Modified by GUIDE v2.5 10-May-2017 01:15:22 + +% Begin initialization code - DO NOT EDIT +gui_Singleton = 1; +gui_State = struct('gui_Name', mfilename, ... + 'gui_Singleton', gui_Singleton, ... + 'gui_OpeningFcn', @pale_ui_help_OpeningFcn, ... + 'gui_OutputFcn', @pale_ui_help_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 pale_ui_help is made visible. +function pale_ui_help_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 pale_ui_help (see VARARGIN) + +% Choose default command line output for pale_ui_help +handles.output = hObject; + +% Update handles structure +guidata(hObject, handles); + +% UIWAIT makes pale_ui_help wait for user response (see UIRESUME) +% uiwait(handles.figure1); + + +% --- Outputs from this function are returned to the command line. +function varargout = pale_ui_help_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; +","MATLAB" +"Neurology","ChristianGaser/cat12","internal/PAIL/spm_ov_pale.m",".m","11950","269","%========================================================================== +% PALE - Point And Label setting Extension +%========================================================================== +% Plugin for spm_image to add points to labels to loadet image. Just start +% it with the context-menu entry: Start PALE. +% ADD: +% To add a Point click on screen while holding one of the keys 1-9, which +% represents the boundarys. +% Alternatively you can choose the boundary with the GUI. But then you have +% to deselect the boundary manually with the deselect button. You can change +% the current slice with the keys 'e' and 'd'. +% DELETE: +% You can delete in two ways. +% When you want to remove the last points of the current boundary, you can +% use 'r'. Also you can click on the point you want to remove. For better +% Visibility of them, pressing 'f' makes all visible points bigger. Moving +% the crosshair undo this effect. +%========================================================================== + +function ret = spm_ov_pale(varargin) + global st; + switch varargin{1} + case 'context_menu' + uimenu(varargin{3}, 'Label', 'Start PALE', 'Callback',@start); + case 'redraw' + % precalculate matrix + is = inv(st.Space); + a = is(1:3,1:3); + b = is(1:3,4); + % color declaration - change on wish + colors = [ 1 0 0; 0 0 1; 0 1 0; 0 1 1; 1 1 0; 1 0 1; 0 1 0.5; 1 0.5 1; 0.5 0 1]; + fields = fieldnames(st.vols{1}.pale.labelData); + if(st.vols{1}.pale.currentBoundary == 0) + % remove all old points + if(~isempty(st.vols{1}.pale.lines)) + % delete object + delete(st.vols{1}.pale.lines(:)); + % delete addresses + st.vols{1}.pale.lines = []; + st.vols{1}.pale.lineC = {}; + end + % screen all points in bound + for j=1:9 + color = colors(j,:); + for i=1:size(st.vols{1}.pale.labelData.(fields{st.vols{1}.pale.currentLabel}).(['Boundary' num2str(j)]),2) + for k=1:3 + if ~inSlice(st.centre(k), st.vols{1}.pale.labelData.(fields{st.vols{1}.pale.currentLabel}).(['Boundary' num2str(j)])(:,i), k) + continue; + end + display_point(st.vols{1}.pale.labelData.(fields{st.vols{1}.pale.currentLabel}).(['Boundary' num2str(j)])(:,i), st.bb, k, color, a, b, j, i); + end + end + end + else + XYZmm = spm_orthviews('Pos'); + % when any label is selected, write in it + if isempty(st.vols{1}.pale.labelData.(fields{st.vols{1}.pale.currentLabel}).(['Boundary' num2str(st.vols{1}.pale.currentBoundary)])) + st.vols{1}.pale.labelData.(fields{st.vols{1}.pale.currentLabel}).(['Boundary' num2str(st.vols{1}.pale.currentBoundary)])(:,end+1) = XYZmm(:); + elseif ~isequal(round(st.vols{1}.pale.labelData.(fields{st.vols{1}.pale.currentLabel}).(['Boundary' num2str(st.vols{1}.pale.currentBoundary)])(:,end),0), round(XYZmm(:),0)) + st.vols{1}.pale.labelData.(fields{st.vols{1}.pale.currentLabel}).(['Boundary' num2str(st.vols{1}.pale.currentBoundary)])(:,end+1) = XYZmm(:); + for k=1:3 + display_point(XYZmm(:,end), st.bb,k, colors(st.vols{1}.pale.currentBoundary,:),a,b, st.vols{1}.pale.currentBoundary, size(st.vols{1}.pale.labelData.(fields{st.vols{1}.pale.currentLabel}).(['Boundary' num2str(st.vols{1}.pale.currentBoundary)]),2)); + end + end + end + otherwise + end +end + + +function res = inSlice(slice, pos, axe, bb) + if round(slice) == round(pos(axe)) + res = 1; + return; + end + res = 0; + return; +end + +function display_point(point, bb, axis, color, a,b, boundary, id) + global st; + % transform point into screen coordinates with precalculated matrices + pos = a * point(:) + b; + % depending on axis draw point + switch axis + case 1 + % this view can be flipped, so st.mode contains this data + if st.mode == 0 + st.vols{1}.pale.lines(end+1) = line(st.vols{1}.ax{3}.ax, pos(3)-bb(1,3)+1, pos(2)-bb(1,2)+1, 'Marker', 's', 'MarkerSize', st.vols{1}.pale.markerSize, 'Color', color, 'MarkerFaceColor', color, 'ButtonDownFcn',@lineCallback); + else + st.vols{1}.pale.lines(end+1) = line(st.vols{1}.ax{3}.ax, bb(2,2)+1-pos(2), pos(3)-bb(1,3)+1, 'Marker', 's', 'MarkerSize', st.vols{1}.pale.markerSize, 'Color', color, 'MarkerFaceColor', color, 'ButtonDownFcn',@lineCallback); + end + case 2 + st.vols{1}.pale.lines(end+1) = line(st.vols{1}.ax{2}.ax, pos(1)-bb(1,1)+1, pos(3)-bb(1,3)+1, 'Marker', 's', 'MarkerSize', st.vols{1}.pale.markerSize, 'Color', color, 'MarkerFaceColor', color, 'ButtonDownFcn',@lineCallback); + case 3 + st.vols{1}.pale.lines(end+1) = line(st.vols{1}.ax{1}.ax, pos(1)-bb(1,1)+1, pos(2)-bb(1,2)+1, 'Marker', 's', 'MarkerSize', st.vols{1}.pale.markerSize, 'Color', color, 'MarkerFaceColor', color, 'ButtonDownFcn',@lineCallback); + end + % save the point object in pale structure to enable removing them later + s = struct(); + s.boundary = boundary; + s.id = id; + st.vols{1}.pale.lineC{end+1} = s; +end + +function start(varargin) + global st; + % activate pale + if isfield(st.vols{1}, 'pale') == 0 + st.paleUI_handle = pale_ui; + set(st.fig, 'CloseRequestFcn', @close); + set(st.fig, 'KeyPressFcn', @key_pressed); + set(st.fig, 'KeyReleaseFcn', @key_released); + else + disp('PALE already running!'); + end +end + +function lineCallback(varargin) +global st; +line = get(gcf, 'CurrentObject'); +try + for a=1:size(st.vols{1}.pale.lines,2) + anyLine = get(st.vols{1}.pale.lines(a)); + if(anyLine.XData == line.XData && anyLine.YData == line.YData) + st.vols{1}.pale.labelData.(['Region' num2str(st.vols{1}.pale.currentLabel)]).(['Boundary' num2str(st.vols{1}.pale.lineC{a}.boundary)])(:,st.vols{1}.pale.lineC{a}.id) = []; + delete(st.vols{1}.pale.lines(a)) + st.vols{1}.pale.lines(a) = []; + st.vols{1}.pale.lineC{a} = []; + st.vols{1}.pale.lineC = st.vols{1}.pale.lineC(~cellfun('isempty',st.vols{1}.pale.lineC)); + return; + end +end +catch ME + redraw(); +end +end + +function key_pressed(hObject, eventdata, handles) + global st; + if isfield(st.vols{1}, 'pale') ~= 0 + % when key is in possible boundaryID limits + if(str2double(eventdata.Character) <= 9 && str2double(eventdata.Character) > 0) + st.vols{1}.pale.currentBoundary = str2double(eventdata.Character); + st.vols{1}.pale.lastBoundary = str2double(eventdata.Character); + end + switch eventdata.Character + case 'e' + pos = spm_orthviews('pos'); + % get axis + currentAxis = get(gcf,'CurrentObject'); + for i=1:3 + if currentAxis.Position == st.vols{1}.ax{i}.ax.Position + if(i == 1) + axis = 3; + elseif(i == 2) + axis = 2; + else + axis = 1; + end + break; + end + end + pos(axis) = pos(axis)+1; + spm_orthviews('reposition',pos); + case 'd' + pos = spm_orthviews('pos'); + % get axis + currentAxis = get(gcf,'CurrentObject'); + for i=1:3 + if currentAxis.Position == st.vols{1}.ax{i}.ax.Position + if(i == 1) + axis = 3; + elseif(i == 2) + axis = 2; + else + axis = 1; + end + break; + end + end + pos(axis) = pos(axis)-1; + spm_orthviews('reposition',pos); + case 'r' + % remove last + % prevent errors during empty label data + if isempty(st.vols{1}.pale.lineC) + return; + end + % continue when boundary is the same as last selected + if st.vols{1}.pale.lineC{end}.boundary ~= st.vols{1}.pale.lastBoundary + return; + end + refObj = st.vols{1}.pale.lineC{end}; + refEndObj = st.vols{1}.pale.lineC{end}; + st.vols{1}.pale.labelData.(['Region' num2str(st.vols{1}.pale.currentLabel)]).(['Boundary' num2str(st.vols{1}.pale.lastBoundary)])(:,end) = []; + % remove all point duplicities from other orthviews + while refObj.id == refEndObj.id && refObj.boundary == refEndObj.boundary + delete(st.vols{1}.pale.lines(end)) + st.vols{1}.pale.lines(end) = []; + st.vols{1}.pale.lineC{end} = []; + st.vols{1}.pale.lineC = st.vols{1}.pale.lineC(~cellfun('isempty',st.vols{1}.pale.lineC)); + if(isempty(st.vols{1}.pale.lineC)) + break; + end + refEndObj = st.vols{1}.pale.lineC{end}; + end + case 'f' + % delete mode -> draw marker bigger + % draw + if st.vols{1}.pale.markerSize == 3 + st.vols{1}.pale.markerSize = 7; + redraw(); + end + otherwise + end + end +end + +function key_released(hObject, eventdata, handles) + global st; + if isfield(st.vols{1}, 'pale') ~= 0 + if(str2double(eventdata.Key) > 0 && str2double(eventdata.Key) < 10) + st.vols{1}.pale.currentBoundary = 0; + end + st.vols{1}.pale.markerSize = 3; + end +end + +function close(hObject, eventdata) +global st; +if(isfield(st, 'paleUI_handle')) + delete(st.paleUI_handle); + st = rmfield(st, 'paleUI_handle'); +end +delete(hObject); +end + +function redraw() + global st; + % precalculate matrix + is = inv(st.Space); + a = is(1:3,1:3); + b = is(1:3,4); + % color declaration - change on wish + colors = [ 1 0 0; 0 0 1; 0 1 0; 0 1 1; 1 1 0; 1 0 1; 0 1 0.5; 1 0.5 1; 0.5 0 1]; + fields = fieldnames(st.vols{1}.pale.labelData); + if(st.vols{1}.pale.currentBoundary == 0) + % remove all old points + if(~isempty(st.vols{1}.pale.lines)) + % delete object + delete(st.vols{1}.pale.lines(:)); + % delete addresses + st.vols{1}.pale.lines = []; + st.vols{1}.pale.lineC = {}; + end + % screen all points in bound + for j=1:9 + color = colors(j,:); + for i=1:size(st.vols{1}.pale.labelData.(fields{st.vols{1}.pale.currentLabel}).(['Boundary' num2str(j)]),2) + for k=1:3 + if ~inSlice(st.centre(k), st.vols{1}.pale.labelData.(fields{st.vols{1}.pale.currentLabel}).(['Boundary' num2str(j)])(:,i), k) + continue; + end + display_point(st.vols{1}.pale.labelData.(fields{st.vols{1}.pale.currentLabel}).(['Boundary' num2str(j)])(:,i), st.bb, k, color, a, b, j, i); + end + end + end + end +end","MATLAB" +"Neurology","ChristianGaser/cat12","internal/PAIL/pale_ui.m",".m","11440","327","function varargout = pale_ui(varargin) +% PALE_UI MATLAB code for pale_ui.fig +% PALE_UI, by itself, creates a new PALE_UI or raises the existing +% singleton*. +% +% H = PALE_UI returns the handle to a new PALE_UI or the handle to +% the existing singleton*. +% +% PALE_UI('CALLBACK',hObject,eventData,handles,...) calls the local +% function named CALLBACK in PALE_UI.M with the given input arguments. +% +% PALE_UI('Property','Value',...) creates a new PALE_UI or raises the +% existing singleton*. Starting from the left, property value pairs are +% applied to the GUI before pale_ui_OpeningFcn gets called. An +% unrecognized property name or invalid value makes property application +% stop. All inputs are passed to pale_ui_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 pale_ui + +% Last Modified by GUIDE v2.5 10-May-2017 00:40:42 + +% Begin initialization code - DO NOT EDIT +gui_Singleton = 1; +gui_State = struct('gui_Name', mfilename, ... + 'gui_Singleton', gui_Singleton, ... + 'gui_OpeningFcn', @pale_ui_OpeningFcn, ... + 'gui_OutputFcn', @pale_ui_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 pale_ui is made visible. +function pale_ui_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 pale_ui (see VARARGIN) + +% Choose default command line output for pale_ui +handles.output = hObject; + +% Update handles structure +guidata(hObject, handles); + +% UIWAIT makes pale_ui wait for user response (see UIRESUME) +% uiwait(handles.figure1); +global st; +splittedPath = strsplit(st.vols{1}.fname,'/'); +% initalize pale main struct +st.vols{1}.pale = struct(); +st.vols{1}.pale.image = {cell2mat(splittedPath(end))}; +st.vols{1}.pale.path = {st.vols{1}.fname}; +st.vols{1}.pale.labelData = struct(); +st.vols{1}.pale.currentLabel = 1; +st.vols{1}.pale.lines = []; +st.vols{1}.pale.removeMode = 0; +st.vols{1}.pale.currentBoundary = 0; +st.vols{1}.pale.lastBoundary = 0; +st.vols{1}.pale.lineC = {}; +st.vols{1}.pale.markerSize = 3; + +% initalize first label +newBoundary = struct(); +for i=1:9 + newBoundary.(['Boundary' num2str(i)]) = []; +end +st.vols{1}.pale.labelData.('Region1') = newBoundary; +handles.popupmenu3.String = {'Region 1'}; + + +% --- Outputs from this function are returned to the command line. +function varargout = pale_ui_OutputFcn(hObject, eventdata, handles) +varargout{1} = handles.output; + + +% --- Executes on button press in pushbutton1. : new +function pushbutton1_Callback(hObject, eventdata, handles) +global st; +if isfield(st.vols{1}, 'pale') ~= 0 + if ~isempty('st.vols{1}.pale.lines') + delete(st.vols{1}.pale.lines(:)); + st.vols{1}.pale.lines = []; + st.vols{1}.pale.lineC = {}; + end +end +splittedPath = strsplit(st.vols{1}.fname,'/'); + +% initalize pale main struct +st.vols{1}.pale = struct(); +st.vols{1}.pale.image = {cell2mat(splittedPath(end))}; +st.vols{1}.pale.path = {st.vols{1}.fname}; +st.vols{1}.pale.labelData = struct(); +st.vols{1}.pale.currentLabel = 1; +st.vols{1}.pale.lines = []; +st.vols{1}.pale.removeMode = 0; +st.vols{1}.pale.currentBoundary = 0; +st.vols{1}.pale.lastBoundary = 0; +st.vols{1}.pale.lineC = {}; +st.vols{1}.pale.markerSize = 3; + +% initalize first label +newBoundary = struct(); +for i=1:9 + newBoundary.(['Boundary' num2str(i)]) = []; +end +st.vols{1}.pale.labelData.('Region1') = newBoundary; +handles.popupmenu3.String = {'Region 1'}; + +% --- Executes on button press in pushbutton2. : load file +function pushbutton2_Callback(hObject, eventdata, handles) +global st; +try + [file, path] = uigetfile(); + load([path, file]); + st.vols{1}.pale = pale; + % update dropdowns : rid + RIDs = fieldnames(st.vols{1}.pale.labelData); + for i=1:size(RIDs,1) + tmp=get(handles.popupmenu3,'string'); + tmp{end+1}=RIDs{i}; + set(handles.popupmenu3,'string',tmp); + end +catch ME + disp('Error: Invalid Selection'); +end + +% --- Executes on button press in pushbutton3. : close +function pushbutton3_Callback(hObject, eventdata, handles) +global st; +if isfield(st.vols{1}, 'pale') ~= 0 + handles.popupmenu3.String = {' - '}; + handles.popupmenu3.Value = 1; + if ~isempty(st.vols{1}.pale.lines) + delete(st.vols{1}.pale.lines(:)); + st.vols{1}.pale.lines = []; + st.vols{1}.pale.lineC = {}; + end + st.vols{1} = rmfield(st.vols{1}, 'pale'); +else + disp('you have to press: ""new"" or ""load"" a file'); +end + +% --- Executes on button press in pushbutton4.: save +function pushbutton4_Callback(hObject, eventdata, handles) +global st; +if isfield(st.vols{1}, 'pale') ~= 0 + name = strsplit(st.vols{1}.pale.image{1}, '.'); + [file,path] = uiputfile([name{1} '_PALE' '.mat']); + pale = st.vols{1}.pale; + % delete lines + pale.lines = []; + pale.lineC = {}; + % save in file + try + save([path file], 'pale'); + catch ME + disp('Error: Invalid Selection'); + end +else + disp('you have to press: ""new"" or ""load"" a file'); +end + +% --- Executes on selection change in popupmenu2. : Boundary +function popupmenu2_Callback(hObject, eventdata, handles) +global st; +if isfield(st.vols{1}, 'pale') ~= 0 + st.vols{1}.pale.currentBoundary = hObject.Value; +else + disp('you have to press: ""new"" or ""load"" a file'); +end + +% --- Executes during object creation, after setting all properties. +function popupmenu2_CreateFcn(hObject, eventdata, handles) +if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) + set(hObject,'BackgroundColor','white'); +end +hObject.String = {'Boundary 1'}; +for i=1:8 + tmp=get(hObject,'string'); + elements = size(tmp,1); + tmp{end+1}=['Boundary ' num2str(elements+1)]; + set(hObject,'string',tmp); +end + +% --- Executes on selection change in popupmenu3. : Region +function popupmenu3_Callback(hObject, eventdata, handles) +global st; +if isfield(st.vols{1}, 'pale') ~= 0 + st.vols{1}.pale.currentLabel = hObject.Value; +else + disp('you have to press: ""new"" or ""load"" a file'); +end + +% --- Executes during object creation, after setting all properties. +function popupmenu3_CreateFcn(hObject, eventdata, handles) +if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) + set(hObject,'BackgroundColor','white'); +end +hObject.String = {'Region 1'}; + + +% --- Executes on button press in togglebutton1. : remove Mode +function togglebutton1_Callback(hObject, eventdata, handles) +global st; +if isfield(st.vols{1}, 'pale') ~= 0 + st.vols{1}.pale.removeMode = hObject.Value; +else + disp('you have to press: ""new"" or ""load"" a file'); +end + +% --- Executes on button press in pushbutton7. : add Label +function pushbutton7_Callback(hObject, eventdata, handles) +global st; +if isfield(st.vols{1}, 'pale') ~= 0 + % create empty Boundary + newBoundary = struct(); + for j=1:9 + newBoundary.(['Boundary' num2str(j)]) = []; + end + % add new Label + allLabels = fieldnames(st.vols{1}.pale.labelData); + st.vols{1}.pale.labelData.(['Region' num2str(size(allLabels,1)+1)]) = newBoundary; + % update popupmenue + tmp=get(handles.popupmenu3,'string'); + elements = size(tmp,1); + tmp{end+1}=['Region ' num2str(elements+1)]; + set(handles.popupmenu3,'string',tmp); +else + disp('you have to press: ""new"" or ""load"" a file'); +end + +% --- Executes on button press in pushbutton8. : remove specific Label +function pushbutton8_Callback(hObject, eventdata, handles) +global st; +if isfield(st.vols{1}, 'pale') ~= 0 + try + input = (inputdlg('Enter Labels ID:')); + labels = fieldnames(st.vols{1}.pale.labelData); + if(input{1} <= size(labels,1) && input{1} > 0) + % delete points on screen + delete(st.vols{1}.pale.lines(:)); + st.vols{1}.pale.lines = []; + st.vols{1}.pale.lineC = {}; + % override label with empty boundaries + newBoundary = struct(); + for i=1:9 + newBoundary.(['Boundary' num2str(i)]) = []; + end + st.vols{1}.pale.labelData.(labels{i}) = newBoundary; + end + catch ME + disp('Error: Invalid Selection'); + end +else + disp('you have to press: ""new"" or ""load"" a file'); +end + +function pushbutton9_Callback(hObject, eventdata, handles) +global st; +if isfield(st.vols{1}, 'pale') ~= 0 + st.vols{1}.pale.currentBoundary = 0; +end + +% --- Executes on button press in pushbutton10. : remove last +function pushbutton10_Callback(hObject, eventdata, handles) +global st; +if isfield(st.vols{1}, 'pale') ~= 0 + % prevent errors during empty label data + if isempty(st.vols{1}.pale.lineC) + return; + end + % continue when boundary is the same as last selected + refObj = st.vols{1}.pale.lineC{end}; + refEndObj = st.vols{1}.pale.lineC{end}; + st.vols{1}.pale.labelData.(['Region' num2str(st.vols{1}.pale.currentLabel)]).(['Boundary' num2str(st.vols{1}.pale.lastBoundary)])(:,end) = []; + % remove all point duplicities from other orthviews + while refObj.id == refEndObj.id && refObj.boundary == refEndObj.boundary + delete(st.vols{1}.pale.lines(end)) + st.vols{1}.pale.lines(end) = []; + st.vols{1}.pale.lineC{end} = []; + st.vols{1}.pale.lineC = st.vols{1}.pale.lineC(~cellfun('isempty',st.vols{1}.pale.lineC)); + if(isempty(st.vols{1}.pale.lineC)) + break; + end + refEndObj = st.vols{1}.pale.lineC{end}; + end +else + disp('you have to press: ""new"" or ""load"" a file'); +end + +% --- Executes when user attempts to close figure1. +function figure1_CloseRequestFcn(hObject, eventdata, handles) +global st; +if isfield(st.vols{1}, 'pale') ~= 0 + if ~isempty('st.vols{1}.pale.lines') + delete(st.vols{1}.pale.lines(:)); + st.vols{1}.pale.lines = []; + st.vols{1}.pale.lineC = {}; + end + st.vols{1} = rmfield(st.vols{1}, 'pale'); +end +delete(hObject); + + +% --- Executes on button press in pushbutton11. +function pushbutton11_Callback(hObject, eventdata, handles) +% hObject handle to pushbutton11 (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) +pale_ui_help; +","MATLAB" +"Neurology","ChristianGaser/cat12","catQC/cat_tst_qa_bwpmaintest.m",".m","67315","1293","function cat_tst_qa_bwpmaintest( datadir, qaversions, segment, fasttest, rerun ) +% -- BWP test script -------------------------------------------------- +% +% Requirements: +% 1. Matlab with statistics and machine learning toolbox (robustfit). +% 2. Download and install SPM and CAT +% 3. Download IXI T1 data from: +% http://biomedic.doc.ic.ac.uk/brain-development/downloads/IXI/IXI-T1.tar +% +% 4. Specify in this script: +% 1) the data directory ""datadir"" +% 2) the QC version you would like to test (the file has to exist in the cat directory) +% 3) the segmentation you would like to use +% +% See also cat_tst_qa_main. +% ------------------------------------------------------------------------ + + +%#ok<*SAGROW,*AGROW,*UNRCH> + +% full/faster test design with directory name + +cat_io_cprintf([0 0.5 0],'\n\n== Run cat_tst_qa_bwpmaintest ==\n') + +if ~license('test', 'Statistics_Toolbox') + error('This function requires the ""Statistics and Machine Learning Toolbox"" of MATLAB.\n') +end + +% ### datadir ### +if ~exist( 'datadir' , 'var' ) + opt.maindir = pwd; +else + opt.maindir = datadir; +end + +if ~exist( fullfile( opt.maindir, 'BWP') , 'dir') + error('Cannot find the required ""BWP"" directory in ""%s"".', opt.maindir) +end +if ~exist( fullfile( opt.maindir, 'BWPr') , 'dir') + error('Cannot find the required ""BWP"" directory in ""%s"".', opt.maindir) +end +if ~exist( fullfile( opt.maindir, 'BWPgt') , 'dir') + error('Cannot find the required ""BWPgt"" directory in ""%s"".', opt.maindir) +end + + +%% ### segmention ### +if ~exist( 'segment' , 'var') + segment = {'CAT'}; % {'SPM','CAT','qcseg'}; % qcseg requires cat_vol_qa2024012 +end + +% ### QC version ### +if ~exist( 'qaversions' , 'var') + qaversions = { + ...'cat_vol_qa201901'; % classic version (quite stable since 2016) + 'cat_vol_qa201901x'; % refined, debugged version of 201901 + ...'cat_vol_qa202110'; % second classic version (successor of 201901) + ...'cat_vol_qa202110x'; % refined, debugged version of 202110 + ...'cat_vol_qa202205'; % last regular version before update (successor of 202110, stopped) + ...'cat_vol_qa202310'; % redesigned version based on 201901 and 202110 * default * + ...'cat_vol_qa202412'; % experimental version with internal segmentation >> qcseg + }; +end + +if ~exist( 'fasttest', 'var'), fasttest = 0; end +if ~exist( 'rerun', 'var'), rerun = 0; end +fast = {'full','fast'}; +corrtype = 'Spearman'; +opt.type = '-depsc'; +opt.res = '-r300'; +opt.dpi = 90; +opt.closefig = 0; +%opt.resdir = fullfile(opt.maindir,'+results', ... +% sprintf('%s_%s_%s', 'BWPmain', fast{fasttest+1}, datestr(clock,'YYYYmm')) ); +opt.resdir = fullfile(opt.maindir,'+results', ... + sprintf('%s_%s_%s', 'BWPmain', fast{fasttest+1}, '202508' )); +recalc.qa = 2 * rerun; +recalc.kappa = 0*2 * rerun; +recalc.runPP = 1; +if ~exist(opt.resdir,'dir'), mkdir(opt.resdir); end + +% preprocessing +if recalc.runPP + BWPfiles = [ + cat_vol_findfiles( fullfile( opt.maindir, 'BWP'), 'BWP*.nii' ,struct('depth',0)); + cat_vol_findfiles( fullfile( opt.maindir, 'BWPr' ), 'rBWP*.nii' ,struct('depth',0)); + cat_vol_findfiles( fullfile( opt.maindir, 'BWPr' ), 'irBWP*.nii',struct('depth',0))]; + + for si = 1:numel(segment) + clear matlabbatch; + + switch segment{si} + case 'CAT' + CATpreprocessing4qc; + BWPfilesCAT = BWPfiles; + BWPfilesCAT( cellfun(@(x) exist(x,'file'),spm_file(BWPfilesCAT,'prefix',['mri' filesep 'p0']))>0 ) = []; + if ~isempty( BWPfilesCAT ) + matlabbatch{1}.spm.tools.cat.estwrite.data = BWPfiles; + matlabbatch{1}.spm.tools.cat.estwrite.extopts.admin.lazy = 1; + spm_jobman('run',matlabbatch); + end + case 'SPM' + SPMpreprocessing4qc; + BWPfilesSPM = BWPfiles; + BWPfilesSPM( cellfun(@(x) exist(x,'file'),spm_file(BWPfilesSPM,'prefix','c1'))>0 ) = []; + if ~isempty( BWPfilesSPM ) + matlabbatch{1}.spm.spatial.preproc.channel.vols = BWPfilesSPM; + spm_jobman('run',matlabbatch); + end + case 'synthseg' + error('synthseg is not prepared in the public script ... use MATLAB help') + case 'qcseg' + fprintf('No preprocessing required.\n\n'); + end + end +end + +% +% * prepare figure for SPM comparison under simple conditions +% - plot noise estimation (1-9%, 20-40 ABC bias, full res) for CAT vs SPM vs. GT +% - MR-ART for SPM! + +qais = 1:numel(qaversions); +qai = 1; %#ok + + +for qai = qais + % prepare things and print + qafile = qaversions{qai}; + cat_io_cprintf('b',sprintf('\n%s:\n\n',qafile)); + if ~exist(opt.resdir,'dir'), mkdir(opt.resdir); end + + + % -- directories ---------------------------------------------------- + % search path of the QA-xml-files + P.p0gt = fullfile(opt.maindir,'BWPgt','p0phantom_1.0mm_normal_cor.nii'); + P.bwpx = { + ...'GT' fullfile(opt.maindir,'BWP') '.' [0.0 0.5 0.0] '-'; ... + 'CAT12' fullfile(opt.maindir,'BWP') '<' [1.0 0.2 0.0] '-'; ... % UPDATE + 'SPM12' fullfile(opt.maindir,'BWP') '^' [0.0 0.8 0.0] '-'; ... % UPDATE + ...'synthseg' fullfile(opt.maindir,'BWP') '.' [0.0 0.5 0.0] '-'; ... + 'qcseg' fullfile(opt.maindir,'BWP') '.' [0.0 0.5 0.5] '-'; ... + }; + + methodx = [ any(contains(segment,'CAT')) any(contains(segment,'SPM')) any(contains(segment,'qcseg')) ]; + P.bwpx = P.bwpx(methodx,:); + method = 1; + + for si = 1:size(P.bwpx,1) + P.bwp = P.bwpx(si,:); + + % -- find p0-files -------------------------------------------------- + rsdir = 'r'; + % find specific BWP segmentations + if strcmp(P.bwp(1,1),'qcseg') && ~strcmp( qaversions{qai} , 'cat_vol_qa202412' ) + cat_io_cprintf('err','ERROR: qcseg only supported for cat_vol_qa202412!\n\n'); + continue + end + for mi = 1 %method + % find p0 images + if strcmp(P.bwp(mi,1),'CAT12') + P.p0m{mi} = [cat_vol_findfiles(fullfile( P.bwp{mi,2} ,'mri'),'p0B*0p*00x*00x*00.nii',struct('depth',0)); + cat_vol_findfiles(fullfile([P.bwp{mi,2} rsdir],'mri'),'p0rB*0p*00x*00x*00.nii',struct('depth',0)); + cat_vol_findfiles(fullfile([P.bwp{mi,2} rsdir],'mri'),'p0irB*0p*00x*00x*00.nii',struct('depth',0))]; + elseif strcmp(P.bwp(mi,1),'GT') + P.p0m{mi} = [cat_vol_findfiles(fullfile( P.bwp{mi,2} ,'mri'),'p0B*0p*00x*00x*00.nii',struct('depth',0)); + cat_vol_findfiles(fullfile([P.bwp{mi,2} rsdir],'mri'),'p0rB*0p*00x*00x*00.nii',struct('depth',0)); + cat_vol_findfiles(fullfile([P.bwp{mi,2} rsdir],'mri'),'p0irB*0p*00x*00x*00.nii',struct('depth',0))]; + P.p0m{mi} = repmat( P.p0gt, size(Pp0m{mi},1), size(Pp0m{mi},2)); + elseif strcmp(P.bwp(mi,1),'synthseg') + P.p0m{mi} = [cat_vol_findfiles( P.bwp{mi,2} ,'synthseg_p0B*0p*00x*00x*00.nii',struct('depth',0)); + cat_vol_findfiles([P.bwp{mi,2} rsdir],'synthseg_p0rB*0p*00x*00x*00.nii',struct('depth',0)); + cat_vol_findfiles([P.bwp{mi,2} rsdir],'synthseg_p0irB*0p*00x*00x*00.nii',struct('depth',0))]; + elseif strcmp(P.bwp(mi,1),'qcseg') + P.p0m{mi} = [cat_vol_findfiles( P.bwp{mi,2} ,'B*0p*00x*00x*00.nii',struct('depth',0)); + cat_vol_findfiles([P.bwp{mi,2} rsdir],'rB*0p*00x*00x*00.nii',struct('depth',0)); + cat_vol_findfiles([P.bwp{mi,2} rsdir],'irB*0p*00x*00x*00.nii',struct('depth',0))]; + else + % SPM12 + P.c1{mi} = [cat_vol_findfiles(P.bwp{mi,2},'c1B*0p*00x*00x*00.nii',struct('depth',0)); + cat_vol_findfiles([P.bwp{mi,2} rsdir],'c1rB*0p*00x*00x*00.nii',struct('depth',0)); + cat_vol_findfiles([P.bwp{mi,2} rsdir],'c1irB*0p*00x*00x*00.nii',struct('depth',0))]; + P.c2{mi} = [cat_vol_findfiles(P.bwp{mi,2},'c2B*0p*00x*00x*00.nii',struct('depth',0)); + cat_vol_findfiles([P.bwp{mi,2} rsdir],'c2rB*0p*00x*00x*00.nii',struct('depth',0)); + cat_vol_findfiles([P.bwp{mi,2} rsdir],'c2irB*0p*00x*00x*00.nii',struct('depth',0))]; + P.c3{mi} = [cat_vol_findfiles(P.bwp{mi,2},'c3B*0p*00x*00x*00.nii',struct('depth',0)); + cat_vol_findfiles([P.bwp{mi,2} rsdir],'c3rB*0p*00x*00x*00.nii',struct('depth',0)); + cat_vol_findfiles([P.bwp{mi,2} rsdir],'c3irB*0p*00x*00x*00.nii',struct('depth',0))]; + P.p0m{mi} = cat_io_strrep(P.c1{mi},'c1','p0'); + Pp0e = false(1,numel(P.p0m{mi})); + for fi = 1:numel(P.p0m{mi}) + Pp0e(fi) = exist(P.p0m{mi}{fi},'file') && ~cat_io_rerun(P.c1{mi}{fi},P.p0m{mi}{fi},0); + end + if any(Pp0e~=1) + cat_io_cgw2seg(P.c3{mi}(Pp0e~=1),P.c1{mi}(Pp0e~=1),P.c2{mi}(Pp0e~=1)); + end + end + + % + P.p0m{mi} = P.p0m{mi}(cellfun('isempty',strfind(P.p0m{mi},'_pn0_'))); + for fi = 1:numel(P.p0m{mi}) + [PPP{mi}{fi},FFF{mi}{fi}] = fileparts(P.p0m{mi}{fi}); + end + end + % only data that was processed by all methods + PP{1} = PPP{method(1)}; + FF{1} = FFF{method(1)}; + if numel(method)>1 + for mi = setdiff( method , 1) + [FF{1},fii,fim] = intersect(FF{1},FFF{mi}); + PP{mi} = PPP{mi}(fim); + for mii = setdiff( method(1:mi) , 1) + FF{mii} = FFF{mii}(fii); + PP{mii} = PPP{mii}(fii); + end + end + end + % remove old p0 files and create a new list that only includes test cases that are available for all methods + %P = rmfield(P,'p0'); + for mi = method + for fi = 1:numel(FF{1}) + P.p0{mi}{fi,1} = fullfile(PP{mi}{fi},[FF{1}{fi} '.nii']); + end + end + + % remove cases for faster preliminary tests + if fasttest + % only field A, only extrem and average cases + % (1%, 5%, 9% noise; 20%, 60%, 100% inhomogeneity, 1x1x1, 1x1x2, 2x2x2 mm resolution) + removeEntries = {'pB_','pC_','pn3','pn7','rf040','rf080',... + 'vx100x200x100','vx200x100x100','vx100x200x200','vx200x100x200','vx200x200x100'}; + else + % remove these cases as they play no practical role + removeEntries = {'vx100x200x200','vx200x100x200','vx200x200x100'}; + end + if ~isempty(removeEntries) + for pi = numel(P.p0{1}):-1:1 + [pp,ff,ee] = spm_fileparts( P.p0{1}{pi} ); + if contains(ff,removeEntries) + for mi = method, P.p0{mi}(pi) = []; P.p0m{mi}(pi) = []; end + end + end + end + fprintf(' Found %d files (%d methods). ',numel(P.p0{method(1)}),numel(method)); + + + + + % estimate the qa and kappa values for the p0-files + Q = struct(); P.xml = {}; + Q.kappa = zeros(numel(P.p0{mi}),numel(method)); + for mi = method + % -- do QA --------------------------------------------------------- + % xml-filenames + P.p0a{mi} = P.p0{mi}; + for pi=1:numel(P.p0{mi}) + [pp,ff] = fileparts(P.p0{mi}{pi}); + if strcmp(P.bwp(mi,1),'CAT12') + P.xml{mi}{pi,1} = fullfile(fileparts(pp),'report',[qafile '_' ff(3:end) '.xml']); + elseif strcmp(P.bwp(mi,1),'SPM12') + P.xml{mi}{pi,1} = fullfile(pp,[qafile '_spm_' ff(3:end) '.xml']); %'report', + P.p0a{mi}{pi,1} = fullfile(pp,['c1' ff(3:end) '.nii']); % for kappa + elseif strcmp(P.bwp(mi,1),'synthseg') + P.xml{mi}{pi,1} = fullfile(pp,'report',[qafile '_' strrep(ff,'synthseg_p0','synthseg_') '.xml']); + elseif strcmp(P.bwp(mi,1),'qcseg') + P.xml{mi}{pi,1} = fullfile(pp,'report',[qafile '_qcseg_' ff '.xml']); + P.p0a{mi}{pi,1} = fullfile(pp,['p0_qcseg_' ff '.nii']); % for kappa + end + P.p0e{mi}(pi) = exist(P.xml{mi}{pi},'file') | strcmp(P.bwp(mi,1),'qcseg') && (recalc.qa(1)<2); + % check data + if P.p0e{mi}(pi) + if ~exist(P.xml{mi}{pi},'file') + P.p0e{mi}(pi) = 0; + else + xmlt = cat_io_xml(P.xml{mi}{pi}); + if ~isfield(xmlt,'filedata') || isempty(xmlt.filedata) + P.p0e{mi}(pi) = 0; + end + end + end + end + + %% (re)calcqa and load xml files + P.qamat{mi} = fullfile(opt.resdir,['bwp_' qafile '_NIR' P.bwp{mi,1} '.mat']); + if ~exist(P.qamat{mi},'file') || recalc.qa(1)>0 || any(P.p0e{mi}==0) + qaopt = struct('prefix',[qafile '_'],'write_csv',0,'mprefix','m','orgval',0,'rerun',recalc.qa(1)); + if strcmp(P.bwp(mi,1),'synthseg') + qav = [qaversions{qai} '_synthseg_']; + elseif strcmp(P.bwp(mi,1),'qcseg') + qav = [qaversions{qai} '_qcseg_']; + elseif strcmp(P.bwp(mi,1),'SPM12') + qav = [qaversions{qai} '_spm_']; + else + qav = [qaversions{qai} '_']; + end + if recalc.qa(1)>1 + cat_vol_qa('p0',P.p0a{mi},struct('prefix',qav,'version',qafile,'rerun',2)); + else + cat_vol_qa('p0',P.p0a{mi}(P.p0e{mi}==0),struct('prefix',qav,'version',qafile,'rerun',0)); + end + xml = cat_io_xml(P.xml{mi}); + save(P.qamat{mi},'xml'); + else + load(P.qamat{mi},'xml'); + end + X(mi).xml = xml; + + + + + % -- estimate kappa -------------------------------------------------- + for ki=1:numel(P.p0{mi}) + if strcmp(P.bwp(mi,1),'qcseg') + P.p0r(ki) = ~isempty(strfind(P.p0{mi}{ki},'rBWP')); + else + P.p0r(ki) = ~isempty(strfind(P.p0{mi}{ki},'p0r')); + end + end + if fasttest + P.kappamat{mi} = fullfile(opt.resdir,sprintf('bwp_kappa_NIR%d_%s_fast.mat',numel(P.p0{mi}),P.bwp{mi,1})); + else + P.kappamat{mi} = fullfile(opt.resdir,sprintf('bwp_kappa_NIR%d_%s.mat',numel(P.p0{mi}),P.bwp{mi,1})); + end + if (qai == 1 && ( ~exist(P.kappamat{mi},'file')) || recalc.kappa(1)) + %% + clear val; + [~,valo] = eva_vol_calcKappa(P.p0{mi}(~P.p0r),{P.p0gt},struct('recalc',recalc.kappa(1),'realign',0,'realignres',1)); + [~,vali] = eva_vol_calcKappa(P.p0{mi}(P.p0r) ,{P.p0gt},struct('recalc',recalc.kappa(1),'realign',2,'realignres',2)); + val(1,:) = valo(1,:); + val(find(P.p0r==0)+1,:) = valo(2:end-2,:); + val(find(P.p0r==1)+1,:) = vali(2:end-2,:); + val(end+1:end+2,:) = vali(end-1:end,:); + save(P.kappamat{mi},'val') + else + load(P.kappamat{mi}) + end + + try + if mi==1 + Q.kappa = mean(cell2mat(val(2:end-2,2:4)),2); + else + Q.kappa(:,mi) = mean(cell2mat(val(2:end-2,2:4)),2); + end + catch + %eva_vol_calcKappa(P.p0{mi}(P.p0r),{P.p0gt},struct('recalc',1,'realign',2,'realignres',1)); + %[~,val] = eva_vol_calcKappa(P.p0{mi},P.p0gt,struct('recalc',0,'realign',0,'realignres',1)); + %Q.kappa(:,mi) = mean(cell2mat(val(2:end-2,2:4)),2); + %save(P.kappamat{mi},'val') + end + clear val + end + + + + + %% -- prepare QA data ------------------------------------------------ + cat_io_cmd(' Prepare quality measurements:','g5','',1); + nx = 4; + + % create a new, simpler structure based on the xml-files + mi = find(method>0,1,'first'); + Q.method = repmat(1:5,size(Q.kappa,1),1); + Q.noise = nan(numel(P.xml{mi}),1); + Q.bias = nan(numel(P.xml{mi}),1); + Q.field = nan(numel(P.xml{mi}),1); + Q.vx_voli = nan(numel(P.xml{mi}),3); + Q.vx_vol = nan(numel(P.xml{mi}),3); vx_vol_digit = 3; + Q.vx_int = nan(numel(P.xml{mi}),1); + Q.ECR = nan(numel(P.xml{mi}),1); + Q.ECRgt = nan(numel(P.xml{mi}),1); + Q.ECRmm = nan(numel(P.xml{mi}),1); + Q.ECRmmgt = nan(numel(P.xml{mi}),1); + if fasttest + Q.train = ones(numel(P.xml{mi}),1); % train/test subset (split half) + else + %Q.train = rand(numel(Q.bias),2)' > 5; % train/test subset (split half) + Q.train = mod(1:numel(Q.bias),8)' < 4; % train/test subset (split half) + end + for pi=1:numel(P.xml{mi}) + [~,ff] = spm_fileparts(P.xml{mi}{pi}); + pni = strfind(ff,'pn'); + rfi = strfind(ff,'rf'); + vxi = strfind(ff,'vx'); + + Q.noise(pi) = str2double(ff(pni+2)); + Q.bias(pi) = sign(0.5-(ff(rfi+5)=='n')).*str2double( ff(rfi+2:rfi+4)); + Q.field(pi) = char(ff(rfi+6)); + Q.vx_int(pi,1) = contains(ff,'irBWP'); + Q.SIQRgt = repmat(((Q.bias-20)/160*4)+1,1,numel(method)); + Q.vx_vol(pi,:) = [str2double(ff(vxi+2 : vxi+1+vx_vol_digit )), ... + str2double(ff(vxi+3+vx_vol_digit : vxi+2+vx_vol_digit*2 )), ... + str2double(ff(vxi+4+vx_vol_digit*2 : vxi+3+vx_vol_digit*3 ))]/100; + end + Q.NCRgt = repmat(((Q.noise-1)/8*4)+1,1,numel(method)); + Q.ICRgt = repmat(((Q.bias-20)/160*4)+1,1,numel(method)); + Q.RESgt = repmat((mean(Q.vx_vol.^2,2).^0.5)*2,1,numel(method)); + Q.ECRgt = Q.RESgt - 1; + Q.FECgt = Q.NCRgt; + Q.IQRgt = mean([Q.NCRgt, Q.ICRgt, Q.RESgt].^nx,2).^(1/nx); + Q.SIQRgt = mean([Q.NCRgt, Q.ICRgt, Q.RESgt, Q.ECRgt, Q.FECgt].^nx,2).^(1/nx); + + + % -- map QM data ---------------------------------------------------- + fieldxml = 'xml'; + QM = {'NCR','ICR','res_RMS','res_ECR','res_ECRmm','FEC','contrastr','IQR','SIQR'}; % ################## reprocess *IQR* + for qmi = 1:numel(QM) + % create a version with original values + if any(strcmp(QM{qmi},{'NCR','ICR','res_ECR','res_ECRmm','FEC'})) + field = [QM{qmi} 'o']; + fieldqm = 'qualitymeasures'; + else + field = QM{qmi}; + fieldqm = 'qualityratings'; + end + Q.(field) = zeros(numel(Q.noise),numel(method)); + for pi=1:numel(P.(fieldxml){mi}) + for mi = method + try + Q.(field)(pi,mi) = X(mi).(fieldxml)(pi).(fieldqm).(QM{qmi}); + catch + Q.(field)(pi,mi) = nan; + end + end + end + end + for pi=1:numel(P.(fieldxml){mi}) + try + Q.vx_voli(pi,:) = X(mi).(fieldxml)(pi).qualitymeasures.res_vx_vol; + end + end + Q.CMV = zeros(numel(Q.noise),numel(method)); + Q.GMV = zeros(numel(Q.noise),numel(method)); + Q.WMV = zeros(numel(Q.noise),numel(method)); + for mi = method + for pi=1:numel(P.xml{mi}) + try + Q.CMV(pi,mi) = X(mi).xml(pi).subjectmeasures.vol_rel_CGW(1); + Q.GMV(pi,mi) = X(mi).xml(pi).subjectmeasures.vol_rel_CGW(2); + Q.WMV(pi,mi) = X(mi).xml(pi).subjectmeasures.vol_rel_CGW(3); + catch + fprintf('Failed: X(%d).xml(%d)\n',mi,pi) + Q.CMV(pi,mi) = nan; + Q.GMV(pi,mi) = nan; + Q.WMV(pi,mi) = nan; + end + end + end + + + % -- fit marks ------------------------------------------------------ + % * 0% noise and 0% bias are excluded because they are instable in SPM pp + % and also smaller datasets (no fields) + % * more problematic is the detection of using low resolution data also + % for the general evaluation because the data is (i) no real standard, + % (ii) not representing the majority of data, and (iii) less accurate/robust + for tstseti = 4 + default = cat_stat_marks('default'); + + opt.bwptestset = tstseti; % ######## focus on 1 mm ! + switch opt.bwptestset + case 1, M = (fasttest | Q.train) & Q.noise>0 & Q.bias>0 & Q.vx_int==0 & all(Q.vx_vol==1,2); % 1 mm focus for better results (in general the images have this resolution) + case 2, M = (fasttest | Q.train) & Q.noise>0 & Q.bias>0 & Q.vx_int==0; % only non interpolated cases + case 3, M = (fasttest | Q.train) & Q.noise>0 & Q.bias>0 & all(Q.vx_voli==1,2); % only isotropic cases + case 4, M = (fasttest | Q.train) & Q.noise>0 & Q.bias>0; % all cases + end + MECR = (fasttest | Q.train) & Q.noise>0 & Q.bias>0 & (all(Q.vx_vol==1,2) | all(Q.vx_vol==2,2) ); % here we need also the other resolutions + MECRT = (fasttest | ~Q.train) & Q.noise>0 & Q.bias>0; % here we need also the other resolutions + + + % -- fit for rating -------------------------------------------------- + rmse = @(a,b) cat_stat_nanmean( (a-b).^2 ).^(1/.5); + % NCR + cat_io_cmd(sprintf(' Mark range of %s (N_train=%d/%d):',qafile,sum(M),sum(Q.train)),'n','',1); + [Q.fit.noiseNCR, Q.fit.noiseNCRstat] = robustfit(Q.NCRgt(M,1),Q.NCRo(M,1)); + default.QS{contains(default.QS(:,2),'NCR'),4} = ... + [Q.fit.noiseNCR(1) + Q.fit.noiseNCR(2),Q.fit.noiseNCR(1) + Q.fit.noiseNCR(2) * 6]; %#ok<*FNDSB> + + % ICR + [Q.fit.biasICR, Q.fit.biasICRstat] = robustfit(Q.ICRgt(M,1),Q.ICRo(M,1)); + default.QS{contains(default.QS(:,2),'ICR'),4} = ... + [Q.fit.biasICR(1) + Q.fit.biasICR(2),Q.fit.biasICR(1) + Q.fit.biasICR(2) * 6]; + + % ECR + ECRpos = find(cellfun('isempty',strfind(default.QS(:,2),'ECR' ))==0,1,'first'); %#ok<*STRCL1> + [Q.fit.resECR, Q.fit.resECRstat] = robustfit(Q.ECRgt(MECR,1),Q.res_ECRo(MECR,1)); + default.QS{ECRpos,4} = [Q.fit.resECR(1) + Q.fit.resECR(2),Q.fit.resECR(1) + Q.fit.resECR(2) * 6]; % we start with mark 2 + save(fullfile(opt.resdir,['qadefault_' qafile '.mat']),'default'); + fprintf('\n'); + + % FEC + FECpos = find(cellfun('isempty',strfind(default.QS(:,2),'FEC'))==0); + try + warning off; + [Q.fit.FEC, Q.fit.FECstat] = robustfit(Q.FECgt(M,1),Q.FECo(M,1)); + warning on; + if ~isempty(FECpos) + default.QS{FECpos,4} = round([Q.fit.FEC(1) + Q.fit.FEC(2), Q.fit.FEC(1) + Q.fit.FEC(2) * 6], -1); + end + catch + Q.fit.FEC = [nan nan]; Q.fit.FECstat = struct('coeffcorr',nan(2,2),'p',nan(2,2)); + default.QS{find(cellfun('isempty',strfind(default.QS(:,2),'FEC'))==0),4} = [100 850]; + end + + + % -- remarks -------------------------------------------------------- + cat_io_cmd(' Remark:','g5','',1); + for mi = method + for pi=1:numel(P.xml{mi}) + try + X(mi).xml2(pi) = cat_stat_marks('eval',0,X(mi).xml(pi),default); + Q.NCR(pi,mi) = X(mi).xml2(pi).qualityratings.NCR; + Q.ICR(pi,mi) = X(mi).xml2(pi).qualityratings.ICR; + if isfield( X(mi).xml2(pi).qualityratings,'res_ECR') + Q.ECR(pi,mi) = X(mi).xml2(pi).qualityratings.res_ECR; + else + Q.ECR(pi,mi) = nan; + end + Q.IQR(pi,mi) = X(mi).xml2(pi).qualityratings.IQR; + try + Q.SIQR(pi,mi) = X(mi).xml2(pi).qualityratings.SIQR; + catch + Q.SIQR(pi,mi) = X(mi).xml2(pi).qualityratings.IQR; + end + if isfield( X(mi).xml2(pi).qualityratings,'FEC') + Q.FEC(pi,mi) = X(mi).xml2(pi).qualityratings.FEC; + else + Q.FEC(pi,mi) = nan; + end + catch + Q.NCR(pi,mi) = nan; + Q.ICR(pi,mi) = nan; + Q.ECR(pi,mi) = nan; + Q.FEC(pi,mi) = nan; + Q.IQR(pi,mi) = nan; + Q.SIQR(pi,mi) = nan; + end + end + end + if all( isnan( Q.SIQR(:) ) ) + Q.SIQR = Q.IQR; + end + + fprintf('\n NCR: [%8.4f, %8.4f] (r=%0.4f, p=%0.1e, RMSE=%0.4f)',... + default.QS{contains(default.QS(:,2),'NCR'),4}, Q.fit.noiseNCRstat.coeffcorr(2), ... + Q.fit.noiseNCRstat.p(2), rmse( Q.NCRgt(M,1), Q.NCR(M,1)) ); + fprintf('\n ICR: [%8.4f, %8.4f] (r=%0.4f, p=%0.1e, RMSE=%0.4f)',... - keep in mind that the BWP bias is scaled to 3 (i.e., mult. by 2 times!) + default.QS{contains(default.QS(:,2),'ICR'),4}, Q.fit.biasICRstat.coeffcorr(2), ... + Q.fit.biasICRstat.p(2), rmse( Q.ICRgt(M,1), Q.ICR(M,1))); + fprintf('\n ECR: [%8.4f, %8.4f] (r=%0.4f, p=%0.1e, RMSE=%0.4f)',... + default.QS{ECRpos,4}, Q.fit.resECRstat.coeffcorr(2), ... + Q.fit.resECRstat.p(2), rmse( Q.ECRgt(M,1), Q.ECR(M,1))); + fprintf('\n FEC: [%8.4f, %8.4f] (r=%-7.4f, p=%0.1e, RMSE=%0.4f)\n',... + default.QS{FECpos,4}, Q.fit.FECstat.coeffcorr(2), ... + Q.fit.FECstat.p(2), rmse( Q.FECgt(M,1), Q.FEC(M,1)) ); + + + + + % -- results -------------------------------------------------------- + % table for IQR values by method ... + def.bstm = 1; % best mark + def.wstm = 6; % worst mark + def.wstmn = 8.624; % worst mark to get a 4 for values with std + def.bstl = 0.5+eps*2; % highest rating ... 0.5 because of rounding values + def.wstl = 10.5-eps*2; % lowest rating ... to have only values with 1 digit .. but % scaling... + + setnan = [1 nan]; + evallinear = @(x,bst,wst) setnan(isnan(x)+1) .* ... + (min(def.wstl,max(def.bstl,(sign(wst-bst)*x - sign(wst-bst)*bst) ./ abs(diff([wst ,bst])) .* abs(diff([def.bstm,def.wstm])) + def.bstm))); + rms = @(a,fact) max(0,cat_stat_nanmean(a.^fact).^(1/fact)); + mark2rps = @(mark) min(100,max(0,105 - mark*10)); + + + + %% -- create figure -------------------------------------------------- + + cat_io_cmd(' Create figure:','g5','',1); + testmethods = [1 0]; testmethods(numel(method)+1:end) = []; + + % BWP main figure + sizex=9; + FS=[7 6 2]*(opt.dpi/120)*2; b2 = 0.04/(9/9); subx = 5; suby = 4; pos = cell(suby,subx); dimx=sizex*opt.dpi*1.2; + for x=1:subx + for y=1:suby + pos{y,x}=[(x-1)/subx + b2*1.2, (suby - y)/suby + b2*1.5 , 1/subx-b2*1.3 , 1/suby - b2*2]; + end + end + + if exist('fh1','var') && ishghandle(fh1) + clf(fh1); %figure(fh1); + else + fh1 = figure('Name','figure 1 - bwp main','Visible','off','Interruptible', 'off','Position', ... + [0 0 dimx round(dimx*(suby/subx))],'color',[1 1 1],'PaperPositionMode','auto'); + end + + % ---------------------------------------------------------------------- + % A) BWP test variables + % - measures should be more accurate in high quality data + % - the resolution datasets for 1 and 2 mm are 3x smaller than the + % 1x1x2 and 1x2x2 datasets because of the permutations + % ---------------------------------------------------------------------- + rps = 1; % ########## use rps is here a bit inoptimal + rpsnam = {'grade','%'}; + if rps, nlim = [40 100]; else, nlim = [0.5 6.5]; end + if rps, mlim = mark2rps(6:-1:1); else, mlim = 1:6; end + + QM = {'NCR','ICR','res_RMS','res_ECR','FEC','SIQR'}; + cl = [.8 0 .2; 0.8 0.6 0; 0.2 0.5 0; .0 .5 .9; 0. 0 0.9; 0 0 0 ]; + + % noise + % -------------------------------------------------------------------- + subplot('Position',pos{1,1}); clear MMC + M3=repmat(testmethods,size(M,1),1); + M2=repmat(M,numel(method),1) & M3(:); + [nln,~,nlid2]=unique(repmat(Q.noise(M),numel(method),1)); MM=repmat(Q.NCR(M2),numel(method),1); %.*sum(M2>0,1)/numel(M2) + for nlni=1:numel(nln); if rps, MMC{nlni} = mark2rps(MM(nlid2==nlni)); else, MMC{nlni} = MM(nlid2==nlni); end; end + cat_plot_boxplot(MMC,struct('names',... + [num2str(unique(Q.noise(M))) repmat('%',numel(num2str(unique(Q.noise(M)))),1)], ... + 'sort',0,'ylim',nlim,'groupnum',0,'ygrid',0,'groupcolor',... + min(1,flip([1./(2:-1/(numel(MMC)/2-1):1) 1:1/((numel(MMC)-1)/2):2])' * cl(1,:) * .6), ... + 'style',4,'datasymbol','o','usescatter',1)); set(gca,'FontSize',FS(2)); + set(gca,'ylim',nlim,'ytick',mlim,'FontSize',FS(2),'YGrid','on'); ylabel('NCR'); + title(sprintf('noise (n=%d)', numel(M)),'FontSize',FS(1),'FontWeight','bold'); + xlabel('BWP noise levels'); ylabel(sprintf('NCR (%s)',rpsnam{rps+1})); + if ~rps, set(gca,'YDir','reverse'); end + + + % bias + % -------------------------------------------------------------------- + subplot('Position',pos{1,2}); clear MMC + M3=repmat(testmethods,size(M,1),1); + M2=repmat(M,numel(method),1) & M3(:); + [nln,~,nlid2]=unique(repmat(Q.bias(M),numel(method),1)); MM=repmat(Q.ICR(M2),numel(method),1); + for nlni=1:numel(nln); if rps, MMC{nlni} = mark2rps(MM(nlid2==nlni)); else, MMC{nlni} = MM(nlid2==nlni); end; end + cat_plot_boxplot(MMC,struct('names',[num2str(nln) repmat('%',size(num2str(nln),1),1)], ... + 'sort',0,'ylim',nlim,'groupnum',0,'ygrid',0,'groupcolor',... + min(1,flip([1./(2:-1/(numel(MMC)/2-1):1) 1:1/((numel(MMC)-1)/2):2])' * cl(2,:) * .6), ... + 'style',4,'datasymbol','o','usescatter',1)); set(gca,'FontSize',FS(2)); hold on + set(gca,'ylim',nlim,'ytick',mlim,'FontSize',FS(2),'YGrid','on','XTickLabelRotation',0); + title('inhomogeneity','FontSize',FS(1),'FontWeight','bold'); + xlabel('BWP inhomogeneity levels'); ylabel(sprintf('ICR (%s)',rpsnam{rps+1})); + if ~rps, set(gca,'YDir','reverse'); end + + + % resolution + % -------------------------------------------------------------------- + subplot('Position',pos{1,3},'box','on'); hold on; clear res + res.sf = 2; + res.rms = @(a) (mean(a.^res.sf)).^(1/res.sf); + res.defres = 1; + res.res = 0.25:0.1:3.25; + res.resp = res.defres:0.5:3.25; + res.resa = res.defres:0.5:3.25; + res.iso = [res.res' res.res' res.res']; + res.ani = [res.defres*ones(numel(res.res),2) res.res']; + res.ani2 = [res.defres*ones(numel(res.res),1) res.res' res.res']; + res.isop = [res.resp' res.resp' res.resp']; + res.anip = [res.defres*ones(numel(res.resa),2) res.resa']; + res.anip2= [res.defres*ones(numel(res.resp),1) res.resp' res.resp']; + plot(res.res,res.rms(res.iso'),'r-'); plot(res.res,res.rms(res.ani'),'b-'); plot(res.res,res.rms(res.ani2'),'g-'); + plot(res.resp,res.rms(res.isop'),'r+'); plot(res.resa,res.rms(res.anip'),'b+'); plot(res.resp,res.rms(res.anip2'),'g+'); + legend({'isotr. [R,R,R]',... + sprintf('sliceres. [%0.0f %0.0f R]',res.defres,res.defres),... + sprintf('sliceth. [R R %0.0f]',res.defres)},... + 'Location','Southwest','Fontsize',FS(2)*0.8); + xlim([0.25 res.res(end)+eps]); ylim([0.25 res.res(end)]); + set(gca,'xtick',0.5:0.5:res.resp(end)+eps,'ytick',0:0.5:res.resp(end),'FontSize',FS(2)); + set(gca,'ylim',[0.25 3.25],'ytick',0.5:0.5:3,'yticklabel',num2str((1:6)'),'FontSize',FS(2)); + title('voxel resolution','FontSize',FS(1),'FontWeight','bold'); + xlabel('BWP resolution (R in mm)'); ylabel(sprintf('RES (%s)',rpsnam{rps+1})); + grid on; + if ~rps, set(gca,'YDir','reverse'); end + + + % ECR + % -------------------------------------------------------------------- + if isfield( X(mi).xml2(pi).qualityratings,'res_ECR') + subplot('Position',pos{1,4}); clear MMC + M3=repmat(testmethods,size(MECRT,1),1); + M2=repmat(MECRT,numel(method),1) & M3(:); + [nln,~,nlid2]=unique(repmat(Q.ECRgt(MECRT),numel(method),1)); MM=repmat(Q.ECR(M2),numel(method),1); + for nlni=1:numel(nln); if rps, MMC{nlni} = mark2rps(MM(nlid2==nlni)); else, MMC{nlni} = MM(nlid2==nlni); end; end + switch size(MMC,2) + case 2, MMCnames = {'1x1x1','2x2x2'}; + case 3, MMCnames = {'1x1x1','1x1x2','2x2x2'}; + case 4, MMCnames = {'1x1x1','1x1x2','1x2x2','2x2x2'}; + end + cat_plot_boxplot(MMC,struct('names',{MMCnames}, ... [num2str(nln,'%0.2f')], ... + 'sort',0,'ylim',nlim,'groupnum',0,'ygrid',0, 'groupcolor',... + min(1,flip([1./(2:-1/(numel(MMC)/2-1):1) 1:1/((numel(MMC)-1)/2):2])' * cl(4,:) * .6), ... + 'style',4,'datasymbol','o','usescatter',1)); set(gca,'FontSize',FS(2)); hold on + set(gca,'ylim',nlim,'ytick',mlim,'FontSize',FS(2),'YGrid','on'); + title('edge resolution','FontSize',FS(1),'FontWeight','bold'); + xlabel('BWP resolution levels'); ylabel(sprintf('ECR (%s)',rpsnam{rps+1})); + end + if ~rps, set(gca,'YDir','reverse'); end + + + % FEC + % -------------------------------------------------------------------- + subplot('Position',pos{1,5}); clear MMC + M3=repmat(testmethods,size(M,1),1); + M2=repmat(M,numel(method),1) & M3(:); + [nln,~,nlid2]=unique(repmat(Q.noise(M),numel(method),1)); MM=repmat(Q.FEC(M2),numel(method),1); + for nlni=1:numel(nln); if rps, MMC{nlni} = mark2rps(MM(nlid2==nlni)); else, MMC{nlni} = MM(nlid2==nlni); end; end + cat_plot_boxplot(MMC,struct('names',... + [num2str(unique(Q.noise(M))) repmat('%',numel(num2str(unique(Q.noise(M)))),1)], ... + 'sort',0,'ylim',nlim,'groupnum',0,'ygrid',0,'groupcolor',... + min(1,flip([1./(2:-1/(numel(MMC)/2-1):1) 1:1/((numel(MMC)-1)/2):2])' * cl(5,:) * .6), ... + 'style',4,'datasymbol','o','usescatter',1)); set(gca,'FontSize',FS(2)) + set(gca,'ylim',nlim,'ytick',mlim,'FontSize',FS(2),'YGrid','on'); ylabel('NCR'); + title(sprintf('Fast Euler Characteristic', opt.bwptestset,numel(M)),'FontSize',FS(1),'FontWeight','bold'); + xlabel('BWP noise level'); ylabel(sprintf('FEC (%s)',rpsnam{rps+1})); + if ~rps, set(gca,'YDir','reverse'); end + + + % RMSEs + % -------------------------------------------------------------------- + if rps + NCRgtdiff = mark2rps(Q.NCR(M,1)) - mark2rps(Q.NCRgt(M)); + ICRgtdiff = mark2rps(Q.ICR(M,1)) - mark2rps(Q.ICRgt(M)); + RESgtdiff = mark2rps(Q.res_RMS(M,1)) - mark2rps(Q.ECRgt(M)); + ECRgtdiff = mark2rps(Q.ECR(M,1)) - mark2rps(Q.ECRgt(M)); + FECgtdiff = mark2rps(Q.FEC(M,1)) - mark2rps(Q.FECgt(M)); + CONgtdiff = mark2rps(Q.contrastr(M,1)) - mark2rps( median(Q.contrastr(M)) ); + IQRgtdiff = mark2rps(Q.IQR(M,1)) - mark2rps(Q.IQRgt(M)); + SIQRgtdiff = mark2rps(Q.SIQR(M,1)) - mark2rps(Q.SIQRgt(M)); + + NCRgtdiffn = (mark2rps(Q.NCR(M,1)) - mark2rps(Q.NCRgt(M)) ) ./ mark2rps(Q.NCRgt(M)) * 100; + ICRgtdiffn = (mark2rps(Q.ICR(M,1)) - mark2rps(Q.ICRgt(M)) ) ./ mark2rps(Q.ICRgt(M)) * 100; + RESgtdiffn = (mark2rps(Q.res_RMS(M,1)) - mark2rps(Q.ECRgt(M)) ) ./ mark2rps(Q.ECRgt(M)) * 100; + ECRgtdiffn = (mark2rps(Q.ECR(M,1)) - mark2rps(Q.ECRgt(M)) ) ./ mark2rps(Q.ECRgt(M)) * 100; + FECgtdiffn = (mark2rps(Q.FEC(M,1)) - mark2rps(Q.FECgt(M)) ) ./ mark2rps(Q.FECgt(M)) * 100; + CONgtdiffn = (mark2rps(Q.contrastr(M,1)) - mark2rps( median(Q.contrastr(M)) ) ) ./ mark2rps( median(Q.contrastr(M)) ) * 100; + IQRgtdiffn = (mark2rps(Q.IQR(M,1)) - mark2rps(Q.IQRgt(M)) ) ./ mark2rps(Q.IQRgt(M)) * 100; + SIQRgtdiffn = (mark2rps(Q.SIQR(M,1)) - mark2rps(Q.SIQRgt(M)) ) ./ mark2rps(Q.SIQRgt(M)) * 100; + + rmseNCR = rms( mark2rps(Q.NCR(M,1)) - mark2rps(Q.NCRgt(M)) , 2 ); + rmseICR = rms( mark2rps(Q.ICR(M,1)) - mark2rps(Q.ICRgt(M)) , 2 ); + rmseRES = rms( mark2rps(Q.res_RMS(M,1)) - mark2rps(Q.ECRgt(M)) , 2 ); + rmseECR = rms( mark2rps(Q.ECR(M,1)) - mark2rps(Q.ECRgt(M)) , 2 ); + rmseFEC = rms( mark2rps(Q.FEC(M,1)) - mark2rps(Q.FECgt(M)) , 2 ); + rmseCON = rms( mark2rps(Q.contrastr(M,1)) - mark2rps( median(Q.contrastr(M))) , 2 ); + rmseIQR = rms( mark2rps(Q.IQR(M,1)) - mark2rps(Q.IQRgt(M)) , 2 ); + rmseSIQR = rms( mark2rps(Q.SIQR(M,1)) - mark2rps(Q.SIQRgt(M)) , 2 ); + + Bscaling = { [-30 30] , [-30 30] }; + else + NCRgtdiff = (Q.NCR(M,1)) - (Q.NCRgt(M)); + ICRgtdiff = (Q.ICR(M,1)) - (Q.ICRgt(M)); + RESgtdiff = (Q.res_RMS(M,1)) - (Q.ECRgt(M)); + ECRgtdiff = (Q.ECR(M,1)) - (Q.ECRgt(M)); + FECgtdiff = (Q.FEC(M,1)) - (Q.FECgt(M)); + CONgtdiff = (Q.contrastr(M,1)) - median(Q.contrastr(M)); + IQRgtdiff = (Q.IQR(M,1)) - (Q.IQRgt(M)); + SIQRgtdiff = (Q.SIQR(M,1)) - (Q.SIQRgt(M)); + + NCRgtdiffn = ((Q.NCR(M,1)) - (Q.NCRgt(M)) ) ./ (Q.NCRgt(M)) * 100; + ICRgtdiffn = ((Q.ICR(M,1)) - (Q.ICRgt(M)) ) ./ (Q.ICRgt(M)) * 100; + RESgtdiffn = ((Q.res_RMS(M,1)) - (Q.ECRgt(M)) ) ./ (Q.ECRgt(M)) * 100; + ECRgtdiffn = ((Q.ECR(M,1)) - (Q.ECRgt(M)) ) ./ (Q.ECRgt(M)) * 100; + FECgtdiffn = ((Q.FEC(M,1)) - (Q.FECgt(M)) ) ./ (Q.FECgt(M)) * 100; + CONgtdiffn = ((Q.contrastr(M,1)) - median(Q.contrastr(M)) ) ./ median(Q.contrastr(M)) * 100; + IQRgtdiffn = ((Q.IQR(M,1)) - (Q.IQRgt(M)) ) ./ (Q.IQRgt(M)) * 100; + SIQRgtdiffn = ((Q.SIQR(M,1)) - (Q.SIQRgt(M)) ) ./ (Q.SIQRgt(M)) * 100; + + rmseNCR = rms( (Q.NCR(M,1)) - (Q.NCRgt(M)) , 2 ); + rmseICR = rms( (Q.ICR(M,1)) - (Q.ICRgt(M)) , 2 ); + rmseRES = rms( (Q.res_RMS(M,1)) - (Q.ECRgt(M)) , 2 ); + rmseECR = rms( (Q.ECR(M,1)) - (Q.ECRgt(M)) , 2 ); + rmseFEC = rms( (Q.FEC(M,1)) - (Q.FECgt(M)) , 2 ); + rmseCON = rms( (Q.contrastr(M,1)) - ( median(Q.contrastr(M))) , 2 ); + rmseIQR = rms( (Q.IQR(M,1)) - (Q.IQRgt(M)) , 2 ); + rmseSIQR = rms( (Q.SIQR(M,1)) - (Q.SIQRgt(M)) , 2 ); + + Bscaling = { [-3 3] , [-100 100] }; + end + + % absolute and RMS error + subplot('Position',pos{3,4}); + cat_plot_boxplot({NCRgtdiff, ICRgtdiff, RESgtdiff, ECRgtdiff, FECgtdiff, SIQRgtdiff},... + struct('names',{{'NCR','ICR','RES','ECR','FEC','SIQR'}},'sort',0,'ylim',Bscaling{1},... + 'groupcolor',cl,'style',4,'datasymbol','o','usescatter',1,'groupnum',0,'ygrid',0)); + h = gca; h.XTickLabelRotation = 0; h.YGrid = 'on'; + ylabel(sprintf('rating (%s)',rpsnam{rps+1})); xlabel('(measure - goldstd)'); set(gca,'FontSize',FS(2)); + title('absolute error','FontSize',FS(1),'FontWeight','bold'); + %if ~rps, set(gca,'YDir','reverse'); end + + subplot('Position',pos{3,5}); + rmseval = [ rmseNCR, rmseICR, rmseRES, rmseECR, rmseFEC, rmseSIQR ]; + bh = bar(rmseval(1:end)); bh.CData = cl; bh.FaceColor = 'flat'; + ylim(max(0,Bscaling{1})); xlim([.4 6.6]); xticklabels({'NCR','ICR','RES','ECR','FEC','SIQR'}); + h = gca; h.YGrid = 'on'; h.XTickLabelRotation = 0; + ylabel(sprintf('rating (%s)',rpsnam{rps+1})); xlabel('root(mean((measure - goldstd)^2))'); set(gca,'FontSize',FS(2)); + title('RMSE'); + for fi = 1:numel(rmseval) + dt(fi) = text(fi-.45, rmseval(fi) + .1 + 1*(rps), sprintf('%0.3f',rmseval(fi)),'FontSize',8,'Color',cl(fi,:)); + end + fprintf('\nRMSE values from figure: \n') + fprintf('Measure: %s\n', sprintf(repmat('%10s',1,6),'NCR','ICR','RES','ECR','FEC','SIQR') ); + fprintf('RMSE: %s\n', sprintf('%10.4f',rmseval) ); + fprintf('\n') + tabRMSE = [{'Measure:','NCR','ICR','RES','ECR','FEC','SIQR'}; + {'RMSE:'}, num2cell(rmseval) ]; + fname = fullfile(opt.resdir,sprintf('tst_bwpmaintest_%s_RMSEtable_%s.csv',qafile,segment{mi})); + cat_io_csv(fname, tabRMSE); + cat_io_cprintf('blue',sprintf(' Write %s\n',fname)); + %if ~rps, set(gca,'YDir','reverse'); end + + + % + % ---------------------------------------------------------------------- + % B) relation between different BWP aspects and the QM + % ---------------------------------------------------------------------- + + % The relative error is smaller compared to the absolute one because the + % higher variance in low res data is weighted lower. + % However, I am not sure if this is practically useful and clear. + % For development it was more relevant to know ... + + % NCR + subplot('Position',pos{2,1}); clear MMC; + M2 = (fasttest | ~Q.train) & Q.noise==5 & Q.bias==20 & Q.vx_int==0; MMC{1}=repmat(Q.NCR(M2),numel(method),1); + M2 = (fasttest | ~Q.train) & Q.noise==5 & Q.bias==60 & Q.vx_int==0; MMC{2}=repmat(Q.NCR(M2),numel(method),1); + M2 = (fasttest | ~Q.train) & Q.noise==5 & Q.bias==100 & Q.vx_int==0; MMC{3}=repmat(Q.NCR(M2),numel(method),1); + M2 = (fasttest | ~Q.train) & Q.noise==5 & Q.bias>0 & Q.vx_int==0 & all(Q.vx_vol==1,2); MMC{4}=repmat(Q.NCR(M2),numel(method),1); + M2 = (fasttest | ~Q.train) & Q.noise==5 & Q.bias>0 & Q.vx_int==0 & all(Q.vx_vol==2,2); MMC{5}=repmat(Q.NCR(M2),numel(method),1); + M2 = (fasttest | ~Q.train) & Q.noise==5 & Q.bias>0 & Q.vx_int==1; MMC{6}=repmat(Q.NCR(M2),numel(method),1); + if rps, for ci=1:numel(MMC), MMC{ci} = mark2rps(MMC{ci}); end; end + cat_plot_boxplot(MMC,struct('names',{{'B2','B6','B10','R','rR','irR'}}, 'subsets',[0 0 0 1 1 1],... + 'style',4,'datasymbol','o','usescatter',1,'sort',0,'ylim',nlim,'groupnum',0,'ygrid',0)); set(gca,'FontSize',FS(2)); hold on + set(gca,'ylim',nlim,'ytick',mlim,'FontSize',FS(2),'ygrid',1); + title('NCR at 5% noise (grad 3)','FontSize',FS(1),'FontWeight','bold'); + xlabel(sprintf('BWP bias (%d) / RES (%d-%d)',numel(MMC{1}),numel(MMC{4}),numel(MMC{5}))); ylabel(sprintf('NCR (%s)',rpsnam{rps+1})); + if ~rps, set(gca,'YDir','reverse'); end + + % ICR + subplot('Position',pos{2,2}); clear MMC; + M2 = (fasttest | ~Q.train) & Q.noise==1 & Q.bias==60 & Q.vx_int==0; MMC{1}=repmat(Q.ICR(M2),numel(method),1); + M2 = (fasttest | ~Q.train) & Q.noise==5 & Q.bias==60 & Q.vx_int==0; MMC{2}=repmat(Q.ICR(M2),numel(method),1); + M2 = (fasttest | ~Q.train) & Q.noise==9 & Q.bias==60 & Q.vx_int==0; MMC{3}=repmat(Q.ICR(M2),numel(method),1); + M2 = (fasttest | ~Q.train) & Q.noise>0 & Q.bias==60 & Q.vx_int==0 & all(Q.vx_vol==1,2); MMC{4}=repmat(Q.ICR(M2),numel(method),1); + M2 = (fasttest | ~Q.train) & Q.noise>0 & Q.bias==60 & Q.vx_int==0 & all(Q.vx_vol==2,2); MMC{5}=repmat(Q.ICR(M2),numel(method),1); + M2 = (fasttest | ~Q.train) & Q.noise>0 & Q.bias==60 & Q.vx_int==1; MMC{6}=repmat(Q.ICR(M2),numel(method),1); + if rps, for ci=1:numel(MMC), MMC{ci} = mark2rps(MMC{ci}); end; end + cat_plot_boxplot(MMC,struct('names',{{'N1','N5','N9','R','rR','irR'}}, 'subsets',[0 0 0 1 1 1],... + 'style',4,'datasymbol','o','usescatter',1,'sort',0,'ylim',nlim,'groupnum',0,'ygrid',0)); set(gca,'FontSize',FS(2)); hold on + set(gca,'ylim',nlim,'ytick',mlim,'FontSize',FS(2),'ygrid',1); + title('60% bias (grad 2)','FontSize',FS(1),'FontWeight','bold'); + xlabel(sprintf('BWP noise (%d) / RES (%d-%d)',numel(MMC{1}),numel(MMC{4}),numel(MMC{5}))); ylabel(sprintf('ICR (%s)',rpsnam{rps+1})); + if ~rps, set(gca,'YDir','reverse'); end + + % CON + subplot('Position',pos{2,3}); clear MMC; + M2 = (fasttest | ~Q.train) & Q.noise>0 & Q.bias==60 & Q.vx_int==0 & all(Q.vx_vol==1,2); MMC{1}=repmat(Q.contrastr(M2),numel(method),1); + M2 = (fasttest | ~Q.train) & Q.noise>0 & Q.bias==60 & Q.vx_int==0 & all(Q.vx_vol==2,2); MMC{3}=repmat(Q.contrastr(M2),numel(method),1); + M2 = (fasttest | ~Q.train) & Q.noise>0 & Q.bias==60 & Q.vx_int==1; MMC{5}=repmat(Q.contrastr(M2),numel(method),1); + M2 = (fasttest | ~Q.train) & Q.noise==5 & Q.bias>0 & Q.vx_int==0 & all(Q.vx_vol==1,2); MMC{2}=repmat(Q.contrastr(M2),numel(method),1); + M2 = (fasttest | ~Q.train) & Q.noise==5 & Q.bias>0 & Q.vx_int==0 & all(Q.vx_vol==2,2); MMC{4}=repmat(Q.contrastr(M2),numel(method),1); + M2 = (fasttest | ~Q.train) & Q.noise==5 & Q.bias>0 & Q.vx_int==1; MMC{6}=repmat(Q.contrastr(M2),numel(method),1); + if rps, for ci=1:numel(MMC), MMC{ci} = mark2rps(MMC{ci}); end; end + cat_plot_boxplot(MMC,struct('names',{{'N','B','rN','rB','irN','irB'}},'subsets',[0 0 1 1 0 0], ... + 'style',4,'datasymbol','o','usescatter',1,'sort',0,'ylim',nlim,'groupnum',0,'ygrid',0)); set(gca,'FontSize',FS(2)); hold on + set(gca,'ylim',nlim,'ytick',mlim,'FontSize',FS(2),'ygrid',1); + title('contrast','FontSize',FS(1),'FontWeight','bold'); + xlabel('BWP noise/bias/RES levels'); ylabel(sprintf('contrast (%s)',rpsnam{rps+1})); + if ~rps, set(gca,'YDir','reverse'); end + + % ECR + switch qafile + case 'cat_vol_qa201901_202302' + subplot('Position',pos{2,3}); clear MMC; + M2 = (fasttest | ~Q.train) & Q.noise>0 & Q.bias==60 & Q.vx_int==0 & all(Q.vx_vol==2,2); MMC{1}=repmat(Q.ECR(M2),numel(method),1); + M2 = (fasttest | ~Q.train) & Q.noise>0 & Q.bias==60 & Q.vx_int==0 & all(Q.vx_vol==1,2); MMC{3}=repmat(Q.ECR(M2),numel(method),1); + M2 = (fasttest | ~Q.train) & Q.noise>0 & Q.bias==60 & Q.vx_int==1 & any(Q.vx_vol~=2,2); MMC{5}=repmat(Q.ECR(M2),numel(method),1); + M2 = (fasttest | ~Q.train) & Q.noise>0 & Q.bias==60 & Q.vx_int==1 & all(Q.vx_vol==2,2); MMC{7}=repmat(Q.ECR(M2),numel(method),1); + M2 = (fasttest | ~Q.train) & Q.noise==5 & Q.bias>0 & Q.vx_int==0 & all(Q.vx_vol==2,2); MMC{2}=repmat(Q.ECR(M2),numel(method),1); + M2 = (fasttest | ~Q.train) & Q.noise==5 & Q.bias>0 & Q.vx_int==0 & all(Q.vx_vol==1,2); MMC{4}=repmat(Q.ECR(M2),numel(method),1); + M2 = (fasttest | ~Q.train) & Q.noise==5 & Q.bias>0 & Q.vx_int==1 & any(Q.vx_vol~=2,2); MMC{6}=repmat(Q.ECR(M2),numel(method),1); + M2 = (fasttest | ~Q.train) & Q.noise==5 & Q.bias>0 & Q.vx_int==1 & all(Q.vx_vol==2,2); MMC{8}=repmat(Q.ECR(M2),numel(method),1); + if rps, for ci=1:numel(MMC), MMC{ci} = mark2rps(MMC{ci}); end; end + cat_plot_boxplot(MMC,struct('names',{{'r2N','r2B','r1N','r1B','ir1N','ir1B','ir2N','ir2B'}},'subsets',[0 0 1 1 0 0], ... + 'style',4,'datasymbol','o','usescatter',1,'sort',0,'ylim',nlim,'groupnum',0,'ygrid',0)); set(gca,'FontSize',FS(2)); hold on + set(gca,'ylim',nlim,'ytick',mlim,'FontSize',FS(2),'ygrid',0); + title('ECR at 5% noise','FontSize',FS(1),'FontWeight','bold'); + xlabel('BWP noise/bias/resolution levels'); ylabel(sprintf('ECR (%s)',rpsnam{rps+1})); + otherwise + subplot('Position',pos{2,4}); clear MMC; + M2 = (fasttest | ~Q.train) & Q.noise>0 & Q.bias==60 & Q.vx_int==0 & all(Q.vx_vol==1,2); MMC{1}=repmat(Q.ECR(M2),numel(method),1); + M2 = (fasttest | ~Q.train) & Q.noise>0 & Q.bias==60 & Q.vx_int==0 & all(Q.vx_vol==2,2); MMC{3}=repmat(Q.ECR(M2),numel(method),1); + M2 = (fasttest | ~Q.train) & Q.noise>0 & Q.bias==60 & Q.vx_int==1; MMC{5}=repmat(Q.ECR(M2),numel(method),1); + M2 = (fasttest | ~Q.train) & Q.noise==5 & Q.bias>0 & Q.vx_int==0 & all(Q.vx_vol==1,2); MMC{2}=repmat(Q.ECR(M2),numel(method),1); + M2 = (fasttest | ~Q.train) & Q.noise==5 & Q.bias>0 & Q.vx_int==0 & all(Q.vx_vol==2,2); MMC{4}=repmat(Q.ECR(M2),numel(method),1); + M2 = (fasttest | ~Q.train) & Q.noise==5 & Q.bias>0 & Q.vx_int==1; MMC{6}=repmat(Q.ECR(M2),numel(method),1); + if rps, for ci=1:numel(MMC), MMC{ci} = mark2rps(MMC{ci}); end; end + cat_plot_boxplot(MMC,struct('names',{{'N','B','rN','rB','irN','irB'}},'subsets',[0 0 1 1 0 0], ... + 'style',4,'datasymbol','o','usescatter',1,'sort',0,'ylim',nlim,'groupnum',0,'ygrid',0)); set(gca,'FontSize',FS(2)); hold on + set(gca,'ylim',nlim,'ytick',mlim,'FontSize',FS(2),'ygrid',1); + title('ECR estimation','FontSize',FS(1),'FontWeight','bold'); + xlabel('BWP noise/bias/resolution levels'); ylabel(sprintf('ECR (%s)',rpsnam{rps+1})); + end + if ~rps, set(gca,'YDir','reverse'); end + + % FEC + subplot('Position',pos{2,5}); clear MMC; + M2 = (fasttest | ~Q.train) & Q.noise==5 & Q.bias==20 & Q.vx_int==0; MMC{1}=repmat(Q.FEC(M2),numel(method),1); + M2 = (fasttest | ~Q.train) & Q.noise==5 & Q.bias==60 & Q.vx_int==0; MMC{2}=repmat(Q.FEC(M2),numel(method),1); + M2 = (fasttest | ~Q.train) & Q.noise==5 & Q.bias==100 & Q.vx_int==0; MMC{3}=repmat(Q.FEC(M2),numel(method),1); + M2 = (fasttest | ~Q.train) & Q.noise==5 & Q.bias>0 & Q.vx_int==0 & all(Q.vx_vol==1,2); MMC{4}=repmat(Q.FEC(M2),numel(method),1); + M2 = (fasttest | ~Q.train) & Q.noise==5 & Q.bias>0 & Q.vx_int==0 & all(Q.vx_vol==2,2); MMC{5}=repmat(Q.FEC(M2),numel(method),1); + M2 = (fasttest | ~Q.train) & Q.noise==5 & Q.bias>0 & Q.vx_int==1; MMC{6}=repmat(Q.FEC(M2),numel(method),1); + if rps, for ci=1:numel(MMC), MMC{ci} = mark2rps(MMC{ci}); end; end + cat_plot_boxplot(MMC,struct('names',{{'B2','B6','B10','R','rR','irR'}}, 'subsets',[0 0 0 1 1 1],... + 'style',4,'datasymbol','o','usescatter',1,'sort',0,'ylim',nlim,'groupnum',0,'ygrid',0)); set(gca,'FontSize',FS(2)); hold on + set(gca,'ylim',nlim,'ytick',mlim,'FontSize',FS(2),'ygrid',1); + title('FEC at 5% noise (grad 3)','FontSize',FS(1),'FontWeight','bold'); + xlabel(sprintf('BWP bias (%d) /resolution levels (%d-%d)',numel(MMC{1}),numel(MMC{4}),numel(MMC{5}))); ylabel(sprintf('FEC (%s)',rpsnam{rps+1})); + if ~rps, set(gca,'YDir','reverse'); end + + + + %% + % ---------------------------------------------------------------------- + % C) relation between QM and kappa + % ---------------------------------------------------------------------- + marklab = {'mark','percentage'}; + method = method; + + % comments + annotation('textbox',[0 0.965 0.04 0.04],'String','A','FontSize',FS(1)*1.5,'FontWeight','bold','EdgeColor','none') + annotation('textbox',[0 0.715 0.04 0.04],'String','B','FontSize',FS(1)*1.5,'FontWeight','bold','EdgeColor','none') + annotation('textbox',[0 0.465 0.04 0.04],'String','C','FontSize',FS(1)*1.5,'FontWeight','bold','EdgeColor','none') + annotation('line' ,[0 1],[0.76 0.76],'Color',repmat(0.2,1,3)); + annotation('line' ,[0 1],[0.51 0.51],'Color',repmat(0.2,1,3)); + + clear MX, + MX{1} = M & Q.vx_int==0 & all(Q.vx_vol==1,2); % 1mm not-interpolated + MX{2} = M & Q.vx_int==1; % 1mm interpolated + MX{3} = M & Q.vx_int==0 & ~all(Q.vx_vol==1,2); % 2mm non-interpolated + MXN = {'1 mm','I(> 1 mm)','> 1 mm',}; + MXTL = {'-' '-' '-','-'; 0.5 0.5 0.5 1}; + mrk = {'o','^','v',''}; + kcol = [0.2 0.5 0; 0 0.2 .8; .8 0 0]; + + % (S)IQR + if 1 + if strcmp(P.bwp(mi,1),'CAT12') + ktx = {'kappa','SIQR',[0.725 0.975],[0 6] ,[40 100]; + 'kappa','GMV' ,[0.725 0.975],[0.425 0.485],[0.425 0.485]; + 'GMV' ,'SIQR',[0.425 0.485],[0 6] ,[40 100]}; + elseif strcmp(P.bwp(mi,1),'SPM12') + ktx = {'kappa','SIQR',[.55 0.95],[0 6] ,[20 100]; + 'kappa','GMV' ,[.55 0.95],[0.3 0.6],[0.30 0.6]; + 'GMV' ,'SIQR',[0.3 0.6],[0 6] ,[20 100]}; + elseif strcmp(P.bwp(mi,1),'synthseg') + ktx = {'kappa','SIQR',[.6 0.85],[0 6] ,[40 100]; + 'kappa','GMV' ,[.6 0.85],[0.42 0.53],[0.42 0.53]; + 'GMV' ,'SIQR',[0.42 0.53],[0 6] ,[40 100]}; + end + else % equal + ktx = {'kappa','SIQR',[0.6 1], [0 6] ,[20 100]; + 'kappa','GMV' ,[0.6 1], [0.3 0.6],[0.3 0.6]; + 'GMV' ,'SIQR',[0.3 0.6],[0 6] ,[20 100]}; + end + for kti = 1:size(ktx,1) + subplot('Position',pos{3,kti},'replace','box','on'); hold off; clear MMC + for mi=method + if method(mi)>0 + for mtxi = 1:numel(MX) + if rps==0 || kti==2 + hs = scatter(Q.(ktx{kti,1})(MX{mtxi},mi), Q.(ktx{kti,2})(MX{mtxi},mi),14,mrk{mtxi}); hold on + else + hs = scatter(Q.(ktx{kti,1})(MX{mtxi},mi), mark2rps(Q.(ktx{kti,2})(MX{mtxi},mi)),14,mrk{mtxi}); hold on + end + set(hs,'markeredgecolor',kcol(mtxi,:),'markerfacecolor',kcol(mtxi,:),'MarkerFaceAlpha',0.3,'MarkerEdgeAlpha',0.4); + end + end + end + for mi=method + if method(mi)>0 + for mtxi = 1:numel(MX) + if rps==0 || kti==2 + Q.fit.methKapa{mi} = robustfit(Q.(ktx{kti,1})(MX{mtxi},mi),Q.(ktx{kti,2})(MX{mtxi},mi)); + else + Q.fit.methKapa{mi} = robustfit(Q.(ktx{kti,1})(MX{mtxi},mi),mark2rps(Q.(ktx{kti,2})(MX{mtxi},mi))); + end + plot([0,1],[Q.fit.methKapa{mi}(1),Q.fit.methKapa{mi}(1) + Q.fit.methKapa{mi}(2) ],... + MXTL{1,mtxi},'color',kcol(mtxi,:),'LineWidth',MXTL{2,mtxi}); + end + end + end + hold off; + if (kti == 1 || kti == 3) && ~rps, set(gca,'YDir','reverse'); end + switch kti + case 1, set( gca, 'xdir', 'reverse' , 'YTick', 25:10:95, 'XTick', .55:.1:0.95, 'XTickLabelRotation',0); + case 2, set( gca, 'xdir', 'reverse' , 'YTick', ktx{2,4}(1):round(diff(ktx{2,4})/6,2):ktx{2,4}(2), 'XTick', .55:.1:0.95, 'XTickLabelRotation',0); + case 3, set( gca, 'xdir', 'reverse' , 'YTick', 25:10:95, 'XTick', ktx{3,4}(1):round(diff(ktx{2,4})/6,2):ktx{3,4}(2), 'XTickLabelRotation',0); + end + xlim(ktx{kti,3}); ylim(ktx{kti,4+rps}); + title(sprintf('%s vs. %s',ktx{kti,1},ktx{kti,2}),'FontSize',FS(1),'FontWeight','bold'); + xlabel(ktx{kti,1}); ylabel(sprintf('%s (%s)',ktx{kti,2},rpsnam{rps+1})); box on; grid on; legend off; + legend(MXN(1:3),'Location','Southwest','FontSize',6); + end + + + + % -- correlations --------------------------------------------------- + cat_io_cmd(' Estimate correlations:','g5','',1); + %M = Q.noise>0 & Q.bias>0; + M2 = repmat(M,1,size(Q.kappa,2)) & repmat(method,size(Q.noise,1),1); + QMnames = {'noise','bias','resRMS','NCR','ICR','RES','ECR','FEC','IQR','SIQR','Kappa','rCSFV','rGMV','rWMV'}; + QMcorrs = [ + repmat(Q.noise(M),numel(method),1), ... + double(repmat(Q.bias(M),numel(method),1)) ,... + Q.RESgt(M2), ... + Q.NCR(M2) , Q.ICR(M2) , Q.res_RMS(M2) , Q.ECR(M2) , Q.FEC(M2), Q.IQR(M2), Q.SIQR(M2), ... + Q.kappa(M2) , ... + Q.CMV(M2),Q.GMV(M2),Q.WMV(M2)]; + + [C.QM.r, C.QM.p] = corr(QMcorrs,'type',corrtype); + C.QM.rtab = [ [{''} QMnames]; [QMnames',num2cell(round(C.QM.r*10000)/10000)] ]; + C.QM.ptab = [ [{''} QMnames]; [QMnames',num2cell(C.QM.p)] ]; + C.QM.etab = cell(1,size(C.QM.rtab,2)); C.QM.xtab = C.QM.etab; + C.QM.xtab{1} = sprintf('%s (r/p-value)',corrtype); + + if isfield(C.QM,'txt'), C.QM = rmfield(C.QM,'txt'); end + T.ixiPPC = sprintf('\n%s correlation on BWP:\n%s\n',corrtype,... + '------------------------------------------------------------------------------'); + for di=2:size(C.QM.rtab,2) + T.ixiPPC = sprintf('%s%8s ',T.ixiPPC,C.QM.rtab{1,di}); + C.QM.xtab{1,di} = C.QM.rtab{1,di}; + end + for dj=2:size(C.QM.rtab,1) + T.ixiPPC = sprintf('%s\n%8s ',T.ixiPPC,C.QM.rtab{1,dj}); + C.QM.xtab{dj,1} = C.QM.rtab{dj,1}; + for di=2:size(C.QM.rtab,2) + if C.QM.ptab{dj,di}<0.000001, star='***'; + elseif C.QM.ptab{dj,di}<0.000100, star='** '; + elseif C.QM.ptab{dj,di}<0.010000, star='* '; + else star=' '; + end + if di0 & Q.bias>0; + for mi=1:numel(method) + T.RMS{mi+1,1} = sprintf('RMSE %s',P.bwp{method(mi),1}); + for fi=1:numel(QMfields) + T.RMS{mi+1,fi+1} = rms(mark2rps(Q.(QMfields{fi})(MZ,method(mi))) - ... + mark2rps(Q.([QMfields{fi} 'gt'])(MZ,1)),2); + end + end + if 0 %numel( methods ) > 1 + T.RMS{mi+numel(method),1} = sprintf('RMSE all'); + for fi=1:numel(QMfields) + T.RMS{mi+numel(method),fi+1} = rms(reshape(mark2rps(Q.(QMfields{fi})(:,method)),1,numel(method)*size(Q.(QMfields{fi}),1)) - ... + reshape(mark2rps(repmat(Q.([QMfields{fi} 'gt'])(:,1),1,numel(method))),1,numel(method)*size(Q.(QMfields{fi}),1)),2); + end + end + % RMSE ... compare QR to the rated BWP values + T.RMShq = T.RMS(1,:); + MH = Q.noise>0 & Q.noise<5 & Q.bias>0; % & Q.bias<120; %& all(Q.vx_vol==1,2); + for mi=1:numel(method) + T.RMShq{mi+1,1} = sprintf('RMSE %s',P.bwp{method(mi),1}); + for fi=1:numel(QMfields) + T.RMShq{mi+1,fi+1} = rms(mark2rps(Q.(QMfields{fi})(MH,method(mi))) - ... + mark2rps(Q.([QMfields{fi} 'gt'])(MH,1)),2); + end + end + T.RMSlq = T.RMS(1,:); + ML = Q.noise>5 & Q.bias>=0; % & Q.field=='A'; + for mi=1:numel(method) + T.RMSlq{mi+1,1} = sprintf('RMSE %s (%d)',P.bwp{method(mi),1}); + for fi=1:numel(QMfields) + T.RMSlq{mi+1,fi+1} = rms(mark2rps(Q.(QMfields{fi})(ML,method(mi))) - ... + mark2rps(Q.([QMfields{fi} 'gt'])(ML,1)),2); + end + end + if numel( method ) > 1 + T.RMS(mi+numel(method)+0,:) = [sprintf('RMSE mean (N=%d)',sum(MZ)), num2cell(mean(cell2mat(T.RMS(2:end,2:end))))]; + T.RMS(mi+numel(method)+1,:) = [sprintf('RMSE std (N=%d)',sum(MZ)), num2cell(std( cell2mat(T.RMS(2:end,2:end))))]; + end + T.RMS(mi+numel(method)+(numel(method)>1)*2+0,:) = [sprintf('RMSE HQ (N=%d)',sum(MH)), num2cell(mean(cell2mat(T.RMShq(2:end,2:end)),1))]; + T.RMS(mi+numel(method)+(numel(method)>1)*2+1,:) = [sprintf('RMSE LQ (N=%d)',sum(ML)), num2cell(mean(cell2mat(T.RMSlq(2:end,2:end)),1))]; + T.RMS(mi+numel(method)+(numel(method)>1)*2+2,:) = [sprintf('RMSE ALL(N=%d)',sum(MZ)), num2cell(mean(cell2mat(T.RMS(2:end,2:end)),1))]; + fc = fullfile(opt.resdir,sprintf('tst_bwpmaintest_%s_rms_%s.csv',qafile,segment{mi})); + cat_io_csv(fc,T.RMS) + cat_io_cprintf('blue',' Write %s\n',fc); + + + % -- save images --------------------------------------------------- + mi = 1; + cat_io_cmd(' Print figures:','g5','',1); + fc = fullfile(opt.resdir,sprintf('tst_bwpmaintest_%s_%s.csv',qafile,segment{mi})); + f = fopen(fc,'w'); if f~=-1, fprintf(f,C.QM.txt); fclose(f); end + cat_io_cprintf('blue','\n Write %s\n',fc); + + fc = fullfile(opt.resdir,sprintf('fig1_bwpmaintest_%s_%s',qafile,segment{mi})); + print(fh1,fc,opt.res,'-dpng'); + cat_io_cprintf('blue',' Save %s.png\n',fc); + if opt.closefig, close(fh1); end + + + + + %% -- NCR vs. CNR --------------------------------------------------- + % Based on a reviewer request here the comparison between the NCR vs. + % CNR definition. + % The NCR support a more linear scaling with lower/higher variance for + % good/bad ratings (lower values for good quality), whereas the CNR shows + % the oposit pattern, ie, higher/lower variance for good/bad values with + % higher values for good quality. + % The NCR focuses therefore more on finer separation of low quality data + % whereas the CNR focuses more on further separation of high quality data. + % The relevance becomes more clear together with the Kappa ratings, + % where the CNR presents a clear linear relation. + % However, the NCR is maybe more helpful in separating ultra-high + % resolution data and is less depening on the RMS rating concept. + + cat_io_cmd(' Print NCR vs. CNR figure:','g5','',1); fprintf('\n'); + + % get raw measures for NCR and CNR + for mi = 1 + for pi = 1:numel(X(mi).xml) + Q2.NCR(pi,mi) = X(mi).xml(pi).qualityratings.NCR; + Q2.CNR(pi,mi) = X(mi).xml(pi).qualitymeasures.contrast ./ ... + (X(mi).xml(pi).qualitymeasures.NCR*X(mi).xml(pi).qualitymeasures.contrast); + + Q2.ICR(pi,mi) = X(mi).xml(pi).qualityratings.ICR; + Q2.CIR(pi,mi) = X(mi).xml(pi).qualitymeasures.contrast ./ ... + (X(mi).xml(pi).qualitymeasures.ICR*X(mi).xml(pi).qualitymeasures.contrast); + end + end + + corrNCR = [ corr(Q2.NCR,Q2.CNR,'Type','Spearman'), corr(Q2.NCR,Q2.CNR,'Type','Pearson') ]; + corrICR = [ corr(Q2.ICR,Q2.CIR,'Type','Spearman'), corr(Q2.ICR,Q2.CIR,'Type','Pearson') ]; + + corrNCRkappa = [ corr(Q2.NCR,Q.kappa,'Type','Spearman'), corr(Q2.NCR,Q.kappa,'Type','Pearson') ]; + corrCNRkappa = [ corr(Q2.CNR,Q.kappa,'Type','Spearman'), corr(Q2.CNR,Q.kappa,'Type','Pearson') ]; + + + for figSize = 2%1:2 + fh1 = figure(333); + if figSize==1, fh1.Position(3:4) = [1200 400]; else fh1.Position(3:4) = [750 250]; end + clf(fh1); fh1.Visible = 'on'; + + MM = Q.RESgt==2; % take only 1 mm to make it easier + biases = unique(Q.bias); biascolors = cool(numel(biases)); + noises = unique(Q.noise); noisemarker = 'o<>^v'; lg = {}; + tiledlayout(1, 3, 'TileSpacing', 'compact', 'Padding', 'compact'); + for ti = 1:3 + nexttile; hold on; + + for nf = 1:numel(noises) + for bf = 1:numel(biases) + MMM = MM & Q.bias == biases(bf) & Q.noise == noises(nf); + switch ti + case 1, sc(bf) = scatter(Q2.NCR(MMM),Q2.CNR(MMM),'filled'); + case 2, sc(bf) = scatter(Q2.NCR(MMM),Q.kappa(MMM),'filled'); + case 3, sc(bf) = scatter(Q2.CNR(MMM),Q.kappa(MMM),'filled'); + end + sc(bf).Marker = noisemarker(nf); + sc(bf).MarkerFaceAlpha = .8; + sc(bf).MarkerEdgeAlpha = .0; + sc(bf).SizeData = 50; + sc(bf).MarkerEdgeColor = biascolors(bf,:); + sc(bf).MarkerFaceColor = sc(bf).MarkerEdgeColor; + lg = [lg; sprintf('nf=%0.0f%% bf=%0.0f%%',noises(nf),biases(bf))]; + end + end + box on; grid on; + + switch ti + case 1 + title('CNR vs. NCR') + ylabel('worse << \bf NCR \rm >> better') + xlabel('better << \bf CNR (mark) \rm >> worse'); + if figSize==2, set(gca,'XTick',1:5); xlim([.5 5.5]); end + if figSize==1 || fasttest, legend(lg,'Location','Northeast','FontSize',7); end + case 2 + title('CNR vs. Kappa') + ylabel('worse << \bf Kappa \rm >> better') + xlabel('better << \bf CNR (mark) \rm >> worse'); + if figSize==2, set(gca,'XTick',1:5); xlim([.5 5.5]); end + ylim([.84 .94]+0.01*(figSize==1)); + case 3 + title('NCR vs. Kappa') + ylabel('worse << \bf Kappa \rm >> better') + xlabel('worse << \bf NCR \rm >> better'); + ylim([.84 .94]+0.01*(figSize==1)); + set(gca,'XTick',0:20:80); + end + %subtitle('(1 mm resolution with 3 bias fields per group)'); + %ax = gca; ax.YScale = 'log'; + end + fc = fullfile(opt.resdir,sprintf('fig2_bwpmaintest_%s_rps%0.0f_CNRvsNCR%d_%s',qafile,rps,figSize,segment{mi})); + print(fh1,fc,opt.res,'-dpng'); + cat_io_cprintf('blue',' Save %s.png\n',fc); + if opt.closefig, close(fh1); end + end + if opt.closefig, close(fh1); end + + end + + end +end + +fprintf('BWP done.\n') +","MATLAB" +"Neurology","ChristianGaser/cat12","catQC/cat_tst_qa_resizeBWP.m",".m","33971","650","function cat_tst_qa_resizeBWP( datadir0, qaversions, rerun ) +%% BWP resolutions +% ------------------------------------------------------------------------ +% This function resizes and renames the BWP files to obtain some +% additional resolution versions for further tests (especially of the +% image resolution). +% +% ------------------------------------------------------------------------ +% +% Main Theses: +% (1) Upsampling should not effect a good (resolution) rating. +% Using a pure voxel-based measure (RES) is of course biased, +% whereas the edge-based measure (edgeRES) should be not effected. +% (2) Downsampling should effect the (resolution) rating +% Both resolution measures (RES, edgeRES) should be affected in the +% same way. +% (3) Smoothing an image should be reduce the spatial resolution and +% therefore also the overlap to the original images used as ground- +% truth, e.g., to estimate Kappa or the RMSE. +% A pure voxel-based measure (RES) is here unaffected but the new +% edge-based measure result in worse ratings similar to a reduction +% of image resoltion. +% +% Side Aspects: +% (1) Using real rather than the ground-truth segmentation should not +% largely affect the results. +% (2) Using simulated randomly distored segmentation should not bias +% the results as far as these changes are not biased itself. I.e., +% (i) the skull-stripping could be inoptimal +% (ii) the segmentation could be +% +% Data: +% (1) BWP - my standard, but default resolution of 1.0 mm with +% partial volume effects (sufficent results) +% (2) Tohoku - only private, average 0.5 mm +% (possible supplement) +% (3) 28&me - publicly availbe, should allow 0.5 mm average +% (good supplement) +% (4) Falk7T - publicly availbe, should allow <0.5 mm average +% (not suitable now, would need deforamtions) +% (5) Buchert - similar to Falk7T (need deformations) +% +% See also cat_tst_qa_main. +% ------------------------------------------------------------------------ + + +% TODO: +% * real data test +% * anisotrophy test > add somehow to figure? +% +% * add further case? - Yes, to stabilize the scaling and values +% - bias fields? - easy, should be save +% - noise levels? - maybe challanging, but good for variance +% - bias levels - similar to noise but less effective +% >> try with noise ... hmmm noise is a problem because it will change :-/ +% >> use bias ABC and 40% to get more values and more stable results +% >> test just a noise case to check for problems and maybe add this later +% +++++++++++ loop data +% +++++++++++ add 28&me +% + + cat_io_cprintf([0 0.5 0],'\n\n== Run cat_tst_qa_resizeBWP ==\n') + + % ### data ### + if ~exist( 'datadir0' , 'var' ) + datadir = '/Volumes/SG5TB/MRData/202503_QA'; + else + datadir = datadir0; + end + % ### QC version ### + if ~exist( 'qaversions' , 'var') + qaversions = { + ...'cat_vol_qa201901'; % classic version (quite stable since 2016) + 'cat_vol_qa201901x'; % refined, debugged version of 201901 + ...'cat_vol_qa202110'; % second classic version (successor of 201901) + ...'cat_vol_qa202110x'; % refined, debugged version of 202110 + ...'cat_vol_qa202205'; % last regular version before update (successor of 202110, stopped) + ...'cat_vol_qa202310'; % redesigned version based on 201901 and 202110 * default * + ...'cat_vol_qa202412'; % experimental version with internal segmentation >> qcseg + }; + end + if ~exist( 'rerun', 'var'), rerun = 0; end + + outdir = fullfile(datadir,'BWPrestest'); + resdir = fullfile(datadir, '+results',['BWPrestest_202508']); % char(datetime('now','format','yyyyMM'))]); + if ~exist(fullfile(outdir,'mri'),'dir'), mkdir(fullfile(outdir,'mri')); end + + % testdata from BWP + Po = { + fullfile(datadir,'BWP','BWPC_HC_T1_pn1_rf020pA_vx100x100x100.nii') + ...fullfile(datadir,'BWP','BWPC_HC_T1_pn1_rf020pB_vx100x100x100.nii') + ...fullfile(datadir,'BWP','BWPC_HC_T1_pn1_rf020pB_vx100x100x100.nii') + }; + P = spm_file(Po,'path',outdir); + Pp0o = spm_file(Po,'prefix',['mri' filesep 'p0']); + Pp0 = spm_file(P ,'prefix',['mri' filesep 'p0']); + for fi = 1:numel(Po), copyfile(Po{fi} ,P{fi}); end + for fi = 1:numel(Po), copyfile(Pp0o{fi},Pp0{fi}); end + + testcase = 1; + switch testcase + case 1 % BWP isotroph + res = repmat( ( 1:0.25:3 )', 1,3); + ss = repmat( ( 0:0.25:3 )', 1,3); + case 2 % BWP anisotroph + res = 1:0.25:3; res = [ones(numel(res),2) res']; + ss = 0:0.25:3; ss = [zeros(numel(ss) ,2) ss']; + end + + % qc matlabbatch basic + qcmatlabbatch{1}.spm.tools.cat.tools.iqe.opts.outdir = outdir; + qcmatlabbatch{1}.spm.tools.cat.tools.iqe.opts.verb = 1; + for qai = 1%6:numel(qaversions) + qafile = qaversions{qai}; + + % main variables + recalc = rerun; % force reprocessing of QC + pi = 1; % loop variable + FN = {'NCR','ICR','SIQR','IQR','res_RMS','res_ECR'}; + Prs = cell(numel(P),size(res,1)); + Prp = cell(numel(P),size(ss,1)); + Pss = cell(numel(P),size(ss,1)); + Psp = cell(numel(P),size(ss,1)); + Pp0real = cell(numel(P),1); + Pp0rs = cell(numel(P),1); + Pp0ss = cell(numel(P),1); + Preal = cell(numel(P),1); + Pproc = cell(numel(P),1); + Prsp0 = cell(numel(P),size(res,1)); + Prsp0qc = cell(numel(P),size(res,1)); + Pssp0 = cell(numel(P),size(ss,1)); + Pssp0qc = cell(numel(P),size(ss,1)); + + + % print overview of parameters + fprintf('\nCAT QC resolution measure test: \n') + fprintf('========================================================================\n') + fprintf(' Testcase: %d\n' , testcase) + fprintf(' File: %s' , sprintf(' %s\n',char(P{pi}) ) ); + fprintf(' Outdir: %s\n' , outdir); + fprintf(' QC-file: %s\n' , qafile); + fprintf(' Resolutions:\n%s' , sprintf(' %0.2fx%0.2fx%0.2f\n',res') ); + fprintf(' Smoothings: \n%s' , sprintf(' %0.2fx%0.2fx%0.2f\n',ss') ); + fprintf('========================================================================\n') + + + %% main loop + for pi = 1:numel(P) + [pp,ff,ee] = spm_fileparts(P{pi}); + fprintf('\n %s:', ff); + + + % Resmapling resolution changes + % ----------------------------------------------------------------------- + fprintf('\n Resolution Reduction:'); + rxlabel = cell(1,size(res,1)); + for ri = 1:size(res,1) + rxlabel{ri} = sprintf('r%0.2fx%0.2fx%0.2fmm',res(ri,:)); + fprintf('\n %s',rxlabel{ri}); + + % define both output (the Prs for processing and the Prp and Pp0rs as its simulated and real result for evaluation) + Prs{pi,ri} = char(spm_file(P{pi},'path',fullfile(outdir), 'prefix',sprintf('r%0.2fx%0.2fx%0.2fmm_',res(ri,:)))); + Prp{pi,ri} = char(spm_file(P{pi},'path',fullfile(outdir), 'prefix',sprintf('p0r%0.2fx%0.2fx%0.2fmm_',res(ri,:)))); + Pp0rs{pi,ri} = char(spm_file(P{pi},'path',fullfile(outdir,'mri'),'prefix',sprintf('p0r%0.2fx%0.2fx%0.2fmm_',res(ri,:)))); + + % we just use the batch functionality of the cat_vol_resize function + if recalc>0 || ~exist(Pp0rs{pi,ri},'file') + %% T1 + clear job; + job.data = P(pi); + job.restype.res = res(ri,:); + job.interp = -2005; % linear?, cubic?-no!, smooth-linear?, smooth-cubic? + job.prefix = [rxlabel{ri} '_']; + job.outdir = {outdir}; + job.verb = 0; + job.lazy = 1-recalc; + rr = cat_vol_resize(job); % (1) reduction + Prs{pi,ri} = rr.res{1}; + job = rmfield(job,'restype'); + job.data = Prs(pi,ri); + job.restype.Pref = P(pi); + job.prefix = ''; + cat_vol_resize(job); % (2) reinterpolate + + %% P0 + % this simulates the case of optimal low resolution + % segmentation and following interpolation. + job = rmfield(job,'restype'); + job.data = Pp0(pi); + job.restype.res = res(ri,:); + job.interp = -2002; + job.prefix = [rxlabel{ri} '_']; + rr = cat_vol_resize(job); % (1) reduction + + Prp{pi,ri} = rr.res{1}; + job = rmfield(job,'restype'); + job.data = Prp(pi,ri); + job.restype.Pref = P(pi); + job.prefix = ''; + cat_vol_resize(job); + end + + end + fprintf('\n'); + + + + % smooth + % ----------------------------------------------------------------------- + fprintf('\n Smoothing:'); + sxlabel = cell(1,size(ss,1)); + for si = 1:size(ss,1) + sxlabel{si} = sprintf('s%0.2fx%0.2fx%0.2fmm',ss(si,:)); + % define both output (the Pss for processing and the Pp0ss as its result for evaluation) + Pss(pi,si) = spm_file(P(pi) ,'path',outdir,'prefix',[sxlabel{si} '_']); + Psp(pi,si) = spm_file(Pp0(pi),'path',outdir,'prefix',[sxlabel{si} '_']); + Pp0ss{pi,si} = char(spm_file(P{pi},'path',fullfile(outdir,'mri'),'prefix',sprintf('p0s%0.2fx%0.2fx%0.2fmm_',ss(si,:)))); + + fprintf('\n %s',sxlabel{si}); + if ~exist(Pss{pi,si},'file') + spm_smooth(P{pi},Pss{pi,si},ss(si,:)); + end + % How does Kappa changes if we just smooth the original segmentation. + % However, this is not realistic because there should be no interpolated + % segmentation and we assume that intermediate values are from the PVE. + if ~exist(Psp{pi,si},'file') + spm_smooth(Pp0{pi},Psp{pi,si},ss(si,:)); + end + + end + fprintf('\n'); + + + % run preprocessing for real segmentations + fprintf('\n CAT Preprocessing:'); + Preal{pi} = [ P{pi} , Prs(pi,:) , Pss(pi,:) ]; + Pproc{pi} = [ P{pi} , Prs(pi,:) , Pss(pi,:) ]; + Pp0real{pi} = spm_file(Pproc{pi},'prefix',['mri' filesep 'p0']); + for fi = numel(Pp0real{pi}):-1:1 + if exist(Pp0real{pi}{fi},'file'), Pproc{pi}(fi) = []; end + end + if ~isempty(Pproc{pi}) + CATpreprocessing4qc; + matlabbatch{1}.spm.tools.cat.estwrite.data = Pproc{pi}'; + matlabbatch{1}.spm.tools.cat.estwrite.extopts.admin.lazy = 1; + spm_jobman('run',matlabbatch); + fprintf(' .. done.\n'); + else + fprintf(' .. is not required.\n'); + end + + + % Kappa estimation + % - estimate kappa resolution + [~,valr] = eva_vol_calcKappa([Pp0;Pp0rs(pi,2:end)'],Pp0,struct('recalc',1 + recalc,'realign',0)); + % - estimate kappa smooth + [~,vals] = eva_vol_calcKappa([Pp0;Pp0ss(pi,2:end)'],Pp0,struct('recalc',1 + recalc,'realign',0)); + + + %% Image quality estimation + stepsize = 1; % this is only for fast test and should be 1 by default + + % run with ground truth segmentation + prefixgt = ['qc_gt_' qafile]; + qcmatlabbatch{1}.spm.tools.cat.tools.iqe.images = Prs(pi,1:stepsize:end)'; + qcmatlabbatch{1}.spm.tools.cat.tools.iqe.model.catp0 = Pp0; + qcmatlabbatch{1}.spm.tools.cat.tools.iqe.opts.prefix = prefixgt; + qcmatlabbatch{1}.spm.tools.cat.tools.iqe.opts.verb = 2; + qcmatlabbatch{1}.spm.tools.cat.tools.iqe.opts.rerun = 0; + qcmatlabbatch{1}.spm.tools.cat.tools.iqe.opts.version = qafile; + Prsqc = spm_file( Prs(pi,:) ,'path',fullfile(outdir,'report'),'prefix',prefixgt,'ext','.xml'); + spm_jobman('run',qcmatlabbatch); + xmlr = cat_io_xml(Prsqc); clear Xr; + for fni=1:numel(FN) + for xi=1:numel(xmlr) + try + Xr.(FN{fni})(xi) = xmlr(xi).qualityratings.(FN{fni}); + catch + Xr.(FN{fni})(xi) = nan; + end + end + end + + %% run with ground truth segmentation + qcmatlabbatch{1}.spm.tools.cat.tools.iqe.images = Psp(pi,1:stepsize:end)'; + qcmatlabbatch{1}.spm.tools.cat.tools.iqe.model.catp0 = Pp0; + Pspqc = spm_file( Psp(pi,:) ,'path',fullfile(outdir,'report'),'prefix',prefixgt,'ext','.xml'); + spm_jobman('run',qcmatlabbatch); + xmls = cat_io_xml(Pspqc); clear Xs + for fni=1:numel(FN) + for xi=1:numel(xmls) + try + Xs.(FN{fni})(xi) = xmls(xi).qualityratings.(FN{fni}); + catch + Xs.(FN{fni})(xi) = nan; + end + end + end + + + + %% run with real segmentation (resolution) + prefixp0 = ['qc_p0_' qafile]; + Prs(pi,1) = Pss(pi,1); % ############# the image is somehow modified + Prsp0(pi,:) = spm_file( Prs(pi,:) ,'path',fullfile(outdir,'mri') ,'prefix','p0'); + Prsp0qc(pi,:) = spm_file( Prs(pi,:) ,'path',fullfile(outdir,'report'),'prefix',prefixp0,'ext','.xml'); + qcmatlabbatch{1}.spm.tools.cat.tools.iqe.images = Prs(pi,1:stepsize:end)'; + qcmatlabbatch{1}.spm.tools.cat.tools.iqe.model.catp0 = Prsp0(pi,1:stepsize:end)'; + qcmatlabbatch{1}.spm.tools.cat.tools.iqe.opts.prefix = prefixp0; + spm_jobman('run',qcmatlabbatch); + xmlr2 = cat_io_xml(Prsp0qc); clear Xr2 + for fni=1:numel(FN) + for xi=1:numel(xmlr2) + try + Xr2.(FN{fni})(xi) = xmlr2(xi).qualityratings.(FN{fni}); + catch + Xr2.(FN{fni})(xi) = nan; + end + end + end + + %% run with real segmentation (smoothing) + Pssp0(pi,:) = spm_file( Pss(pi,:) ,'path',fullfile(outdir,'mri') ,'prefix','p0'); + Pssp0qc(pi,:) = spm_file( Pss(pi,:) ,'path',fullfile(outdir,'report'),'prefix',prefixp0,'ext','.xml'); + qcmatlabbatch{1}.spm.tools.cat.tools.iqe.images = Pss(pi,1:stepsize:end)'; + qcmatlabbatch{1}.spm.tools.cat.tools.iqe.model.catp0 = Pssp0(pi,1:stepsize:end)'; + spm_jobman('run',qcmatlabbatch); + xmls2 = cat_io_xml(Pssp0qc(1:end)'); clear Xs2 + for fni=1:numel(FN) + for xi=1:numel(xmls2) + try + Xs2.(FN{fni})(xi) = xmls2(xi).qualityratings.(FN{fni}); + catch + Xs2.(FN{fni})(xi) = nan; + end + end + end + + + + %% run interpolation test + % interpolate image from 1 to 0.9:0.1:0.5 mm + % run kappa + % run QC + % eval + + + + % +++++ estimate correlations ... just some code fragment for fast adaptions + if 0 + %% + %ECR = [.2700 .2568 .2406 .2292 0.2182 .2081 .2017 .1980 0.1965]; + ECR = [.2901 .2756 .2480 .2303 0.2295 .2161 .2080 .2019 0.1947]; + ECRs = [.2699 .2483 .2288 .2096 .1922 .1810 .1731]; + K = cell2mat([vals(2,5);valr(3:end-2,5)]); + Ks = cell2mat(vals(2:end-2,5)); + EX = @(x) log10( (max(0,x - 0.15) ) ); + figure(3); plot(ECR ,K,'x-'); hold on; plot(ECRs ,Ks,'o-'); hold off; + figure(4); plot(EX(ECR),K,'x-'); hold on; plot(EX(ECRs),Ks,'o-'); hold off; + end + + + + + %% create some figure with subfigure# + measures = {'res_RMS','res_ECR','NCR','ICR','IQR','SIQR'}; % print measures (see loop for limited tests) + mr = [1 7]; % limitation of marks + for mi = 1:numel(measures) % real measures and side effects ... 1:numel(measures) + figid = 201; + measure = measures{mi}; + + %% corr + [rhor,pvalr] = corr( Xr.(measure)' , cell2mat(valr(2:end-2,5)')' ); + [rhos,pvals] = corr( Xs.(measure)' , cell2mat(vals(2:end-2,5)')' ); + + + % --------------------------------------------------------------------- + % Figure 1 with just some bars for kappa (1st row), measure with ground + % truth (2nd row), and measure with real segmentation (3rd row). + % --------------------------------------------------------------------- + figure(figid); fp = get(gcf,'Position'); fp(4) = 700; set(gcf,'Position',fp,'name',sprintf('%s-%s',qafile,measure)); + + % plot kappa values + figure(figid); subplot(3,2,1); bar(cell2mat(valr(2:end-2,5))); grid on; ylim([0.85 1]); xlim([0 numel(rxlabel)+1]) + title('Resolution (processing quality)'); ylabel('Kappa') + set(gca,'XTick',1:size(res,1),'xTickLabel',rxlabel,'TickLabelInterpreter','none','XTickLabelRotation',90); + figure(figid); subplot(3,2,2); bar(cell2mat(vals(2:end-2,5))); ylim([0.9 1]); xlim([0 numel(sxlabel)+1]); grid on; + title('Smoothing (processing quality)'); ylabel('Kappa') + set(gca,'XTick',1:size(ss,1),'xTickLabel',sxlabel,'TickLabelInterpreter','none','XTickLabelRotation',90); + + % plot measures for ground turth segmentation + figure(figid); subplot(3,2,3); bar(Xr.(measure)); ylim(mr); grid on; + title(sprintf('QC measure (%s; GT)',strrep(measure,'_',' '))); + ylabel('grad') %ylabel(sprintf('QC grad (%s;r=0.2f)',measure,kmr)); + set(gca,'XTick',1:size(res,1),'xTickLabel',rxlabel,'TickLabelInterpreter','none','XTickLabelRotation',90); + figure(figid); subplot(3,2,4); bar(Xs.(measure)); ylim(mr); grid on; + title(sprintf('QC measure (%s; GT)',strrep(measure,'_',' '))); + ylabel('grad') %ylabel(sprintf('QC grad (%s;r=0.2f)',measure,kmr)); + set(gca,'XTick',1:size(ss,1),'xTickLabel',sxlabel,'TickLabelInterpreter','none','XTickLabelRotation',90); + + % plot measures for real segmentation + figure(figid); subplot(3,2,5); bar(Xr2.(measure)); ylim(mr); grid on + title(sprintf('QC measure (%s; DS); rho=%0.3f, p=%0.0e)',strrep(measure,'_',' '),rhor,pvalr)); + ylabel('grad') %ylabel(sprintf('QC grad (%s;r=0.2f)',measure,kmr)); + set(gca,'XTick',1:size(res,1),'xTickLabel',rxlabel,'TickLabelInterpreter','none','XTickLabelRotation',90); + figure(figid); subplot(3,2,6); bar(Xs2.(measure)); ylim(mr); grid on + title(sprintf('QC measure (%s; DS; rho=%0.3f, p=%0.0e)',strrep(measure,'_',' '),rhos,pvals)); + ylabel('grad') %ylabel(sprintf('QC grad (%s;r=0.2f)',measure,kmr)); + set(gca,'XTick',1:size(ss,1),'xTickLabel',sxlabel,'TickLabelInterpreter','none','XTickLabelRotation',90); + + % save figures + % update this here to have up to date value in case of batch mode + printoutdir = resdir; + if ~exist(printoutdir,'dir'), mkdir(printoutdir); end + [~,ff] = spm_fileparts(P{pi}); + printname = sprintf('testcase%d_%s',testcase,ff); + + % final print of the figure + print(figid, '-djpeg', '-r300', fullfile(printoutdir,sprintf('%s_bars-%s_%s',printname,measure,qafile))); + + + + %% --------------------------------------------------------------------- + % Second figure with kappa vs. measure. + % --------------------------------------------------------------------- + plotGT = 0; % plot only real data (2 lines) or also GT cases (4 lines) + plotIdeal = 0; % plot some ideal line + mark2rps = @(mark) min(100,max(0,105 - mark*10)) + isnan(mark).*mark; + figid = 202; + colors = lines(4); + + fh = figure(figid); fh.Name = measure; fh.Position(3:4) = [260 260]; clf; hold on; + % line plots + if plotGT + plot( Xr.(measure) , cell2mat(valr(2:end-2,5)') ,'Marker','<', 'Color', colors(3,:),'Markerfacecolor',[1 1 1]); + plot( Xs.(measure) , cell2mat(vals(2:end-2,5)') ,'Marker','>', 'Color', colors(4,:),'Markerfacecolor',[1 1 1]); + end + plot( Xr2.(measure) , cell2mat(valr(2:end-2,5)') ,'Marker','o', 'Color', colors(1,:),'Markerfacecolor',[1 1 1]); + plot( Xs2.(measure) , cell2mat(vals(2:end-2,5)') ,'Marker','s', 'Color', colors(2,:),'Markerfacecolor',[1 1 1]); + if plotIdeal + plot( 2* mean(res.^2,2).^0.5 , cell2mat(valr(2:end-2,5)') ,'Marker','^', 'Color', [0.6 0.7 0.8],'Markerfacecolor',[1 1 1],'LineStyle','--'); + end + + % Mark the full resolution values with filled symbols (e.g. 1,2,3 mm) - this is hard coded + if numel(Xr2.(measure))==9 + for ri = [1,5,9] + if plotGT + plot( Xr.(measure)(ri) , cell2mat(valr(ri+1,5)') ,'Marker','<', 'Color', colors(3,:), 'MarkerFaceColor', colors(3,:) ); + end + if plotIdeal + plot( 2* mean(res(ri,:).^2,2).^0.5 , cell2mat(valr(ri+1,5)') ,'Marker','^', 'Color', [0.6 0.7 0.8], 'MarkerFaceColor', [0.6 0.7 0.8]); + end + plot( Xr2.(measure)(ri) , cell2mat(valr(ri+1,5)') ,'Marker','o', 'Color', colors(1,:), 'MarkerFaceColor', colors(1,:) ); + end + end + if numel(Xs2.(measure))==13 + for si = [1,5,9,13] + if plotGT + plot( Xs.(measure)(si) , cell2mat(vals(si+1,5)') ,'Marker','>', 'Color', colors(4,:), 'MarkerFaceColor', colors(4,:) ); + end + plot( Xs2.(measure)(si) , cell2mat(vals(si+1,5)') ,'Marker','s', 'Color', colors(2,:), 'MarkerFaceColor', colors(2,:) ); + end + %plot( Xr2.(measure)(1) , cell2mat(valr(2,5)') ,'Marker','s', 'Color', colors(2,:), 'MarkerFaceColor', colors(2,:) ); + end + + % add legend + hold off; box on; grid on; ylim([0.795 1.005]); xlim([0 10]); + ylabel('Kappa'); xlabel(strrep([measure ' (grade)'],'_','\_')); + ax = gca; ax.XTick = [1:8]; ax.YTick = [.8:0.02:1.0]; ax.Position(3) = .83; + if plotGT + leg = {'ResamplingGT','SmoothingGT','Resampling','Smoothing'}; + else + leg = {sprintf('Resampling (\\it{}rho\\rm{}=%0.3f, \\it{}p\\rm{}=%0.0e)',rhor,pvalr), ... + sprintf('Smoothing (\\it{}rho\\rm{}=%0.3f, \\it{}p\\rm{}=%0.0e)',rhos,pvals)}; + end + if plotIdeal + leg = [leg,{'Expected for lower res.'}]; + end + legend(leg,'Location','South') + title('Quantification of anatomical resolution'); + + % add further in figure text to sign out the marked elements - hard coded + if plotGT + if numel(Xr.(measure))==9 + % resolution data labels + text(Xr.(measure)(1) , valr{2,5} , sprintf('\\leftarrow %s','1 mm') , 'Color', colors(3,:)); + text(Xr.(measure)(5) , valr{6,5} , sprintf('%s\\rightarrow','2 mm') , 'Color', colors(3,:),'HorizontalAlignment','right'); + text(Xr.(measure)(end) , valr{end-2,5} , sprintf('%s\\rightarrow','3 mm') , 'Color', colors(3,:),'HorizontalAlignment','right'); + end + if numel(Xs.(measure))==13 + % smoothing data labels + text(Xs.(measure)(1) , vals{2,5} , sprintf('\\leftarrow %s','0 mm') , 'Color', colors(4,:)); + text(Xs.(measure)(5) , vals{6,5} , sprintf('\\leftarrow %s','1 mm') , 'Color', colors(4,:)); + text(Xs.(measure)(9) , vals{10,5} , sprintf('\\leftarrow %s','2 mm') , 'Color', colors(4,:)); + text(Xs.(measure)(13) , vals{end-2,5} , sprintf('\\leftarrow %s','3 mm') , 'Color', colors(4,:)); + end + end + if numel(Xr2.(measure))==9 && plotIdeal + % resolution data labels + text(2* mean(res(1,:).^2,2).^0.5 , valr{2,5} , sprintf('\\leftarrow %s','1 mm') , 'Color', [0.6 0.6 .8]); + text(2* mean(res(round(end/2),:).^2,2).^0.5 , valr{6,5} , sprintf('\\leftarrow %s','2 mm') , 'Color', [0.6 0.6 .8]); + text(2* mean(res(end,:).^2,2).^0.5 , valr{end-2,5} , sprintf('\\leftarrow %s','3 mm') , 'Color', [0.6 0.6 .8]); + end + if numel(Xr2.(measure))==9 + % resolution data labels + text(Xr2.(measure)(1) , valr{2,5} , sprintf('\\leftarrow %s','1 mm') , 'Color', colors(1,:),'HorizontalAlignment','left'); + text(Xr2.(measure)(5) , valr{6,5} , sprintf('\\leftarrow %s','2 mm') , 'Color', colors(1,:),'HorizontalAlignment','left'); + text(Xr2.(measure)(end) , valr{end-2,5} , sprintf('\\leftarrow %s','3 mm') , 'Color', colors(1,:),'HorizontalAlignment','left'); + end + if numel(Xs2.(measure))==13 + % smoothing data labels + text(Xs2.(measure)(1) , vals{2,5} , sprintf('%s \\rightarrow','0 mm') , 'Color', colors(2,:),'HorizontalAlignment','right'); + text(Xs2.(measure)(5) , vals{6,5} , sprintf('%s \\rightarrow','1 mm') , 'Color', colors(2,:),'HorizontalAlignment','right'); + text(Xs2.(measure)(9) , vals{10,5} , sprintf('%s \\rightarrow','2 mm') , 'Color', colors(2,:),'HorizontalAlignment','right'); + text(Xs2.(measure)(13) , vals{end-2,5} , sprintf('%s \\rightarrow','3 mm') , 'Color', colors(2,:),'HorizontalAlignment','right'); + end + + % final print of the figure + print(fh, '-djpeg', '-r300', fullfile(printoutdir,sprintf('%s_Kappa-%s_%s',printname,measure,qafile))); + end + end + end +end +% == this is the CAT job for preprocessing in developer mode! == +function matlabbatch = catjob(nproc) +% There are some minor changes to avoid reprocessing and output of unused +% volumes and especially surfaces. + + if ~exist('nproc','var'), nproc = 0; end + + matlabbatch{1}.spm.tools.cat.estwrite.data = ''; + matlabbatch{1}.spm.tools.cat.estwrite.data_wmh = {''}; + matlabbatch{1}.spm.tools.cat.estwrite.nproc = nproc; + matlabbatch{1}.spm.tools.cat.estwrite.useprior = ''; + matlabbatch{1}.spm.tools.cat.estwrite.opts.tpm = {'/Users/dahnke/Documents/MATLAB/spm12/tpm/TPM.nii'}; + matlabbatch{1}.spm.tools.cat.estwrite.opts.affreg = 'mni'; + matlabbatch{1}.spm.tools.cat.estwrite.opts.ngaus = [1 1 2 3 4 2]; + matlabbatch{1}.spm.tools.cat.estwrite.opts.warpreg = [0 0.001 0.5 0.05 0.2]; + matlabbatch{1}.spm.tools.cat.estwrite.opts.bias.biasstr = 0.5; + matlabbatch{1}.spm.tools.cat.estwrite.opts.acc.accstr = 0.5; + matlabbatch{1}.spm.tools.cat.estwrite.opts.redspmres = 0; + matlabbatch{1}.spm.tools.cat.estwrite.extopts.segmentation.restypes.optimal = [1 0.3]; + matlabbatch{1}.spm.tools.cat.estwrite.extopts.segmentation.setCOM = 1; + matlabbatch{1}.spm.tools.cat.estwrite.extopts.segmentation.APP = 1070; + matlabbatch{1}.spm.tools.cat.estwrite.extopts.segmentation.affmod = 0; + matlabbatch{1}.spm.tools.cat.estwrite.extopts.segmentation.NCstr = -Inf; + matlabbatch{1}.spm.tools.cat.estwrite.extopts.segmentation.spm_kamap = 0; + matlabbatch{1}.spm.tools.cat.estwrite.extopts.segmentation.LASstr = 0.5; + matlabbatch{1}.spm.tools.cat.estwrite.extopts.segmentation.LASmyostr = 0; + matlabbatch{1}.spm.tools.cat.estwrite.extopts.segmentation.gcutstr = 2; + matlabbatch{1}.spm.tools.cat.estwrite.extopts.segmentation.cleanupstr = 0.5; + matlabbatch{1}.spm.tools.cat.estwrite.extopts.segmentation.BVCstr = 0.5; + matlabbatch{1}.spm.tools.cat.estwrite.extopts.segmentation.WMHC = 2; + matlabbatch{1}.spm.tools.cat.estwrite.extopts.segmentation.SLC = 0; + matlabbatch{1}.spm.tools.cat.estwrite.extopts.segmentation.mrf = 1; + matlabbatch{1}.spm.tools.cat.estwrite.extopts.registration.T1 = ... + {'/Users/dahnke/Documents/MATLAB/spm12/toolbox/cat12/templates_MNI152NLin2009cAsym/T1.nii'}; + matlabbatch{1}.spm.tools.cat.estwrite.extopts.registration.brainmask = ... + {'/Users/dahnke/Documents/MATLAB/spm12/toolbox/cat12/templates_MNI152NLin2009cAsym/brainmask.nii'}; + matlabbatch{1}.spm.tools.cat.estwrite.extopts.registration.cat12atlas = ... + {'/Users/dahnke/Documents/MATLAB/spm12/toolbox/cat12/templates_MNI152NLin2009cAsym/cat.nii'}; + matlabbatch{1}.spm.tools.cat.estwrite.extopts.registration.darteltpm = ... + {'/Users/dahnke/Documents/MATLAB/spm12/toolbox/cat12/templates_MNI152NLin2009cAsym/Template_1_Dartel.nii'}; + matlabbatch{1}.spm.tools.cat.estwrite.extopts.registration.shootingtpm = ... + {'/Users/dahnke/Documents/MATLAB/spm12/toolbox/cat12/templates_MNI152NLin2009cAsym/Template_0_GS.nii'}; + matlabbatch{1}.spm.tools.cat.estwrite.extopts.registration.regstr = 0.5; + matlabbatch{1}.spm.tools.cat.estwrite.extopts.registration.bb = 12; + matlabbatch{1}.spm.tools.cat.estwrite.extopts.registration.vox = 1.5; + matlabbatch{1}.spm.tools.cat.estwrite.extopts.surface.pbtres = 0.5; + matlabbatch{1}.spm.tools.cat.estwrite.extopts.surface.pbtmethod = 'pbt2x'; + matlabbatch{1}.spm.tools.cat.estwrite.extopts.surface.SRP = 22; + matlabbatch{1}.spm.tools.cat.estwrite.extopts.surface.reduce_mesh = 1; + matlabbatch{1}.spm.tools.cat.estwrite.extopts.surface.vdist = 2; + matlabbatch{1}.spm.tools.cat.estwrite.extopts.surface.scale_cortex = 0.7; + matlabbatch{1}.spm.tools.cat.estwrite.extopts.surface.add_parahipp = 0.1; + matlabbatch{1}.spm.tools.cat.estwrite.extopts.surface.close_parahipp = 1; + matlabbatch{1}.spm.tools.cat.estwrite.extopts.admin.experimental = 0; + matlabbatch{1}.spm.tools.cat.estwrite.extopts.admin.new_release = 0; + matlabbatch{1}.spm.tools.cat.estwrite.extopts.admin.lazy = 1; % ########## changed + matlabbatch{1}.spm.tools.cat.estwrite.extopts.admin.ignoreErrors = 1; + matlabbatch{1}.spm.tools.cat.estwrite.extopts.admin.verb = 2; + matlabbatch{1}.spm.tools.cat.estwrite.extopts.admin.print = 2; + matlabbatch{1}.spm.tools.cat.estwrite.output.BIDS.BIDSno = 1; + matlabbatch{1}.spm.tools.cat.estwrite.output.surface = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.surf_measures = 3; + matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.neuromorphometrics = 0; % ########## changed + matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.lpba40 = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.cobra = 0; % ########## changed + matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.hammers = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.thalamus = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.suit = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.ibsr = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.aal3 = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.mori = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.anatomy3 = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.julichbrain3 = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.Schaefer2018_100Parcels_17Networks_order = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.Schaefer2018_200Parcels_17Networks_order = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.Schaefer2018_400Parcels_17Networks_order = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.Schaefer2018_600Parcels_17Networks_order = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.ownatlas = {''}; + matlabbatch{1}.spm.tools.cat.estwrite.output.GM.native = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.GM.warped = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.GM.mod = 0; % ########## changed + matlabbatch{1}.spm.tools.cat.estwrite.output.GM.dartel = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.WM.native = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.WM.warped = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.WM.mod = 0; % ########## changed + matlabbatch{1}.spm.tools.cat.estwrite.output.WM.dartel = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.CSF.native = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.CSF.warped = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.CSF.mod = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.CSF.dartel = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.ct.native = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.ct.warped = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.ct.dartel = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.pp.native = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.pp.warped = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.pp.dartel = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.WMH.native = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.WMH.warped = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.WMH.mod = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.WMH.dartel = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.SL.native = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.SL.warped = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.SL.mod = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.SL.dartel = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.TPMC.native = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.TPMC.warped = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.TPMC.mod = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.TPMC.dartel = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.atlas.native = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.atlas.warped = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.atlas.dartel = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.label.native = 1; + matlabbatch{1}.spm.tools.cat.estwrite.output.label.warped = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.label.dartel = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.labelnative = 1; + matlabbatch{1}.spm.tools.cat.estwrite.output.bias.native = 1; + matlabbatch{1}.spm.tools.cat.estwrite.output.bias.warped = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.bias.dartel = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.las.native = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.las.warped = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.las.dartel = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.jacobianwarped = 0; + matlabbatch{1}.spm.tools.cat.estwrite.output.warps = [0 0]; % ########## changed + matlabbatch{1}.spm.tools.cat.estwrite.output.rmat = 0; +end + +","MATLAB" +"Neurology","ChristianGaser/cat12","catQC/cat_tst_qa_Rusak_aging.m",".m","12739","296","function cat_tst_qa_Rusak_aging( datadir0, qaversions, segment, fasttest, rerun ) +%% Rusak_aging +% ------------------------------------------------------------------------ +% +% Requirements: +% 1. Matlab with statistic toolbox (corr,robustfit) +% 2. Download and install SPM and CAT +% 3. Download Rusak T1 data from: +% https://doi.org/10.25919/4ycc-fc11 +% +% 4. Specify in this script: +% 1) the data directory ""datadir"" +% 2) the QC version you would like to tests (the file has to exist in the cat directory) +% 3) the segmentation you would like to use +% +% See also cat_tst_qa_main. +% ------------------------------------------------------------------------ + +%#ok<*AGROW> + +cat_io_cprintf([0 0.5 0],'\n\n== Run cat_tst_qa_Rusak_aging ==\n') + +if ~license('test', 'Statistics_Toolbox') + error('This function requires the ""Statistics and Machine Learning Toolbox"" of MATLAB.\n') +end + +% directories +runPP = 1; + +% ### datadir ### +if ~exist( 'datadir0' , 'var' ) + datadir = fullfile(pwd,'Rusak2021'); +else + datadir = fullfile(datadir0,'Rusak2021'); +end +if ~exist( datadir , 'dir' ) + error('Cannot find the ""Rusak2021"" directory in ""%s"".', fileparts(datadir)) +end +%% +% ### segmention ### +if ~exist( 'segment' , 'var') + segment = {'CAT'}; % {'SPM','CAT','qcseg'}; % qcseg requires cat_vol_qa2024012 +end +% ### QC version ### +if ~exist( 'qaversions' , 'var') + qaversions = { + ...'cat_vol_qa201901'; % classic version (quite stable since 2016) + 'cat_vol_qa201901x'; % refined, debugged version of 201901 + ...'cat_vol_qa202110'; % second classic version (successor of 201901) + ...'cat_vol_qa202110x'; % refined, debugged version of 202110 + ...'cat_vol_qa202205'; % last regular version before update (successor of 202110, stopped) + ...'cat_vol_qa202310'; % redesigned version based on 201901 and 202110 * default * + ...'cat_vol_qa202412'; % experimental version with internal segmentation >> qcseg + }; +end +if ~exist( 'fasttest', 'var'), fasttest = 0; end +if ~exist( 'rerun', 'var'), rerun = 0; end +fast = {'full','fast'}; + +resdir = fullfile(fileparts(datadir), '+results',['Rusak2021_' fast{fasttest+1} '_202508']); %' datestr(clock,'YYYYmm')]); +if ~exist(resdir,'dir'), mkdir(resdir); end + + +if runPP + for si = 1:numel(segment) + clear matlabbatch; + Rusakfiles = cat_vol_findfiles( datadir , 'sub-ADNI*.nii', struct('maxdepth',3)); + %Rusakfiles( contains( Rusakfiles , 'err' ) ) = []; + if isempty(Rusakfiles), fprintf('Cannot find Rusak''s files. Check the directory but also the depth parameter parameter in the line ahead this message.'); end + switch segment{si} + case 'CAT' + CATpreprocessing4qc; + RusakfilesCAT = Rusakfiles; + RusakfilesCAT( cellfun(@(x) exist(x,'file'),spm_file(Rusakfiles,'prefix',['mri' filesep 'p0']))>0 ) = []; + if ~isempty( RusakfilesCAT ) + matlabbatch{1}.spm.tools.cat.estwrite.data = RusakfilesCAT; + matlabbatch{1}.spm.tools.cat.estwrite.extopts.admin.lazy = 1; + spm_jobman('run',matlabbatch); + end + case 'SPM' + SPMpreprocessing4qc; + RusakfilesSPM = Rusakfiles; + RusakfilesSPM( cellfun(@(x) exist(x,'file'),spm_file(RusakfilesSPM,'prefix','c1'))>0 ) = []; + if ~isempty( RusakfilesSPM ) + matlabbatch{1}.spm.spatial.preproc.channel.vols = RusakfilesSPM; + spm_jobman('run',matlabbatch); + end + case 'synthseg' + error('synthseg is not prepared in the public script ... use MATLAB help') + case 'qcseg' + fprintf('No preprocessing required.\n\n'); + end + end +end + +%% +qias = 1:numel(qaversions); +for segi = 1:numel(segment) + switch segment{segi} + case 'CAT' + Pp0{segi} = cat_vol_findfiles( datadir ,'p0*',struct('depth',0)); + %Pp0{segi} = cat_vol_findfiles(fullfile(datadir,'derivatives','CAT12.9_2583'),'p0*.nii'); + case 'SPM' + Pp0{segi} = cat_vol_findfiles( datadir , 'c1*',struct('depth',0)); + case 'synthseg' + Pp0{segi} = cat_vol_findfiles( datadir , 'synthseg_p0*',struct('depth',0)); + case 'qcseg' + Pp0{segi} = cat_vol_findfiles( datadir , 'sub*.nii',struct('depth',2)); + end + if fasttest, Pp0{si} = Pp0{si}(1:20*3); Pp0{si} = Pp0{si}(1:2:end); end + fprintf('Process Rusak2021: \n') + for qai = qias + switch segment{segi} + case 'CAT' + cat_vol_qa('p0',Pp0{segi},struct('prefix','VERSION_','version',qaversions{ qai },'rerun',rerun)); + case 'SPM' + cat_vol_qa('p0',Pp0{segi},struct('prefix','VERSION_spm_','version',qaversions{ qai },'rerun',rerun)); + case 'synthseg' + cat_vol_qa('p0',Pp0{segi},struct('prefix','VERSION_synthseg_','version',qaversions{ qai },'rerun',rerun)); + case 'qcseg' + cat_vol_qa('p0',Pp0{segi},struct('prefix','VERSION_qcseg_','version',qaversions{ qai },'rerun',rerun)); + end + end + fprintf('Process Rusak2021 done. \n') + + + + + %% evaluate test + sub = cat_vol_findfiles(datadir,'sub*',struct('dirs',true,'depth',2)); + if fasttest, sub = sub(1:3); end + for qai = qias + % get and read XMLs, set subjects and time points + Pxml = {}; SID = []; TID = []; TP = []; + for si = 1:numel(sub) + switch segment{segi} + case 'CAT' + Pxmls = sort(cat_vol_findfiles( fullfile( sub{si} ,'report') , sprintf('%s_sub*.xml',strrep(qaversions{qai},'_','')) )); + case 'SPM' + Pxmls = sort(cat_vol_findfiles( sub{si} , sprintf('%s_spm_sub*.xml',strrep(qaversions{qai},'_','')) )); + case 'qcseg' + Pxmls = sort(cat_vol_findfiles( fullfile( sub{si} ,'report') , sprintf('%s_qcseg_sub*.xml',strrep(qaversions{qai},'_','')) )); + end + %fprintf('%d - %d - %s\n',si,numel(Pxmls),sub{si}); + if fasttest, Pxmls = Pxmls(1:2:end); end + Pxml = [Pxml; Pxmls]; + TPs = char(Pxmls); TPs = str2num(TPs(:,end-9:end-6)); %#ok + TP = [TP; TPs]; + SID(end+1:end+numel(Pxmls)) = si; + TID(end+1:end+numel(Pxmls)) = 1:numel(Pxmls); + end + XML = cat_io_xml(Pxml); + + %% + clear Q N; + ptn = {'full','short'}; + for pt = 2 %:2 + % set QMs + if pt == 1 + mylabel = 'grad error'; + QM = {'NCR','FEC','res_RMS','res_ECR','ICR','contrastr','IQR','SIQR'}; + cl = max(0,flip(hsv(8)) - 0.2); cl(end,:) = [ 0 0 0]; + mylim = [-1 1]; loc = 'Southwest'; + else + % Paper version with less values + mylabel = 'error (rps)'; + QM = {'NCR','ICR', 'res_RMS','res_ECR','FEC','SIQR'}; % + cl = [.8 0 .2; 0.8 0.6 0; 0.2 0.5 0; .0 .5 .9; 0.1 0 0.9; 0 0 0 ]; % + mylim = [-1 1]*3; loc = 'Southwest'; + end + QMs = cat_io_strrep(QM,{'res_RMS','res_ECR','contrastr'},{'RMS','ECR','CON'}); + cm = '<>^vosdph*+_.<>^vosdph*+_.'; + for qmi = 1:numel(QM) + for xi = 1:numel(Pxml) + if isfield(XML(xi).qualityratings,QM{qmi}) + Q.(QM{qmi})(SID(xi),TID(xi)) = XML(xi).qualityratings.(QM{qmi}); + N.(QM{qmi})(SID(xi),TID(xi)) = Q.(QM{qmi})(SID(xi),TID(xi)) - Q.(QM{qmi})(SID(xi),1); + else + Q.(QM{qmi})(SID(xi),TID(xi)) = XML(xi).subjectmeasures.vol_rel_CGW(2) * 10; + N.(QM{qmi})(SID(xi),TID(xi)) = Q.(QM{qmi})(SID(xi),TID(xi)) - Q.(QM{qmi})(SID(xi),1) ; + end + end + try + [N.r.(QM{qmi}), N.p.(QM{qmi})] = corr(TP,N.(QM{qmi})(:)); + catch + N.r.(QM{qmi}) = nan; + N.p.(QM{qmi}) = nan; + end + try + [N.fit.(QM{qmi}), N.fit.([QM{qmi} '_stat'])] = robustfit(TP,N.(QM{qmi})(:)); + [N.fitm.(QM{qmi}), N.fitm.([QM{qmi} '_stat'])] = robustfit(TPs,mean(N.(QM{qmi}))); + catch + N.fit.(QM{qmi}) = nan(1,2); + N.fitm.(QM{qmi}) = nan(1,2); + N.fit.([QM{qmi} '_stat']) = nan(1,2); + N.fitm.([QM{qmi} '_stat']) = nan(1,2); + end + end + + % figure + fh = figure(4); clf; + fh.Position(3:4) = [1000 400]; + fname = sprintf('Rusak2021_%s',qaversions{qai}); %,datestr(clock,'YYYYmmdd')); + annotation('textbox',[0 0.95 1 0.05 ],'FitBoxToText','off','LineStyle','none','Fontsize',12,'String',... + sprintf('Rusak2021: %s - %s', strrep(qaversions{qai},'_','\_'), datestr(clock,'YYYYmmdd')) ); + pos = [1 1 2 2 3 3 4 4 5 5 6 6; + 2 1 2 1 2 1 2 1 2 1 2 1] - 1; + mpos = @(pos,qmi) [0.03+(0.85/max(1+pos(1,:)))*pos(1,qmi) 0.09+(.95/max(1+pos(2,:)))*pos(2,qmi) .68/max(pos(1,:)) 0.33]; + + + % print each QR + for qmi = 1:numel(QM) + subplot('Position',mpos(pos,qmi)); hold on; + for si=1:max(SID) + try + pl = scatter(TP(SID==si), N.(QM{qmi})(si,:)); pl.SizeData = 10; pl.Marker = cm(qmi); + pl.MarkerFaceColor = cl(qmi,:); pl.MarkerEdgeColor = pl.MarkerFaceColor; pl.MarkerFaceAlpha = .3; pl.MarkerEdgeAlpha = .4; + pl = plot(TP(SID==si), N.(QM{qmi})(si,:)); pl.Color = [cl(qmi,:) .05]; pl.LineWidth = .5; + end + end + try + pl = plot(TP(SID==1), mean(N.(QM{qmi}),1)); pl.Color = max(0,cl(qmi,:)-.2); pl.LineWidth = 1; + end + a=gca; a.XTick = [0 0.1 0.5 1]; + if pos(1,qmi)==0, ylabel(mylabel); else, a.YTickLabel = {}; end + xlabel('atrophy (in mm)'); + QMsx{qmi} = sprintf('%s (%+0.2f,r=%0.2f,p=%0.0e)',QMs{qmi}, ... + N.fitm.(QM{qmi})(2), N.r.(QM{qmi}), N.p.(QM{qmi}) ); + ylim(mylim); title(QMsx{qmi}); box on; grid on; + if strcmp(QM{qmi},'GMV'), ylim([-0.15 0.15]); end + end + + + % overview + subplot('Position',(mpos(pos,9) + [.05 0 0 0]) .* [1 1 1 1]); hold on, + for qmi = 1:numel(QM) + try + pl = plot(TP(SID==1), mean(N.(QM{qmi}),1)); + pl.Color = [cl(qmi,:) 0.4 + 0.6*(qmi==numel(QM))]; pl.LineWidth = .5 + .5*(qmi > (numel(QM)-2)); + pl.Marker = cm(qmi); pl.MarkerSize = 4; pl.MarkerFaceColor = pl.Color; + end + end + for qmi = 1:numel(QM) + try + pl = scatter(TP(SID==1), mean(N.(QM{qmi}),1)); pl.SizeData = 10; pl.Marker = cm(qmi); + pl.MarkerFaceColor = cl(qmi,:); pl.MarkerEdgeColor = pl.MarkerFaceColor; + pl.MarkerFaceAlpha = .2 + 0.8*(qmi > (size(QM,1)-2)); pl.MarkerEdgeAlpha = pl.MarkerFaceAlpha; + end + end + a=gca; a.XTick = [0 0.1 0.5 1]; + legend(QMsx,'location',loc,'FontSize',6,'box','off'); + ylabel(mylabel); xlabel('atrophy (in mm)'); title(sprintf('overview QRs')); + ylim(mylim); box on; grid on; a=gca; %a.YTickLabel = {}; + + + % boxplot + subplot('Position',(mpos(pos,10) + [.05 0 0 0]) .* [1 1 1 1]); hold on, clear boxval; + for qmi = 1:numel(QM), boxval{qmi} = single(N.(QM{qmi})(:)); end + cat_plot_boxplot( boxval , struct('names',{QMs},'ylim',mylim,'style',0,'usescatter',1,'ygrid',1,'groupcolor',cl)); + ylabel(mylabel); title(sprintf('boxplot QRs')); a=gca; a.XTickLabelRotation = 90; + + % change + subplot('Position',(mpos(pos,11) + [.1 0 0 0]) .* [1 1 1 1]); hold on, clear boxval; + for qmi = 1:numel(QM), mcorr(qmi) = N.fitm.(QM{qmi})(2); end + mcorr(qmi+1) = mean(mcorr); + bh = bar(mcorr(1:end-1)); bh.CData = cl; bh.FaceColor = 'flat'; + ylim(mylim); xlim([.4 qmi+0.6]); xticks(1:numel(QMs)); xticklabels([QMs {'avg'}]); + a=gca; a.XTickLabelRotation = 90; a.YGrid = 'on'; + ylabel(mylabel); box on; + title(sprintf('Change (avg=%0.3f)',mcorr(end)),'FontWeight','bold','Fontsize',10 - 2*(pt==1)); + for fi = 1:numel(mcorr)-1 + dt(fi) = text(fi-.45, mcorr(fi) + (1-2*(mcorr(fi)<0)) * .065*mylim(2), sprintf('%0.3f',mcorr(fi)),'FontSize',8,'Color',cl(fi,:)); %#ok<*SAGROW> + end + + % RMSE + rmse = @(a) max(0,cat_stat_nanmean(a.^2).^(1/2)); clear rmseval + subplot('Position',(mpos(pos,12) + [.1 0 0 0]) .* [1 1 1 1]); hold on, clear boxval; + for qmi = 1:numel(QM), rmseval(qmi) = rmse(N.(QM{qmi})(:)); end + rmseval(qmi+1) = mean(rmseval); + bh = bar(rmseval(1:end-1)); bh.CData = cl; bh.FaceColor = 'flat'; + ylim([0,mylim(2)]); xlim([.4 qmi+0.6]); xticks(1:numel(QMs)); xticklabels([QMs {'avg'}]); + a=gca; a.XTickLabelRotation = 90; a.YGrid = 'on'; + ylabel(mylabel); box on; + title(sprintf('RMSE (avg=%0.3f)',rmseval(end)),'FontWeight','bold','Fontsize',10 - 2*(pt==1)); + for fi = 1:numel(rmseval)-1 + dt(fi) = text(fi-.45, rmseval(fi) + .1/3*mylim(2), sprintf('%0.3f',rmseval(fi)),'FontSize',8,'Color',cl(fi,:)); %#ok<*SAGROW> + end + + % print + print(fh, '-dpng', '-r600', fullfile(resdir,[ptn{pt} '_' segment{segi} '_' fname])); + end + end +end +fprintf('Evaluate Rusak2021 done.\n'); + +","MATLAB" +"Neurology","ChristianGaser/cat12","catQC/cat_tst_qa_ADHD200.m",".m","2165","62","function cat_tst_qa_ADHD200( datadir, qaversions, segment, fasttest) +%cat_tst_qa_ADHD200. +% +% 1) Downlaod raw data: +% https://fcon_1000.projects.nitrc.org/indi/adhd200/index.html +% 2) Unzip T1 files into a train_raw and test_raw directory +% 3) There should be also a phenotypic directory with the +% ADHD200.csv with age, sex and site information +% + + + %% setup + dataset = 'ADHD200'; + datadir = fullfile(datadir,dataset); + CATver = 'CAT12.9_2874'; + resdir = fullfile(datadir,'+results','ADHD200'); + if fasttest + files = cat_vol_findfiles( fullfile( datadir , 'test_raw') , '*.nii.gz',struct('depth',1)); + else + files = [ + cat_vol_findfiles( fullfile( datadir , 'train_raw'), '*.nii.gz',struct('depth',1)); + cat_vol_findfiles( fullfile( datadir , 'test_raw'), '*.nii.gz',struct('depth',1)); + ]; + end + if ~exist(resdir,'dir'), mkdir(resdir); end + + +%% run preprocessing + for si = 1:numel(segment) + clear matlabbatch; + switch segment{si} + case 'CAT' + CATpreprocessing4qc; + filesCAT = files; + matlabbatch{1}.spm.tools.cat.estwrite.output.BIDS.BIDSyes.BIDSdir = ... + fullfile('..','derivatives',CATver); + filesCAT2 = strrep( filesCAT , datadir , fullfile( datadir, 'derivatives',CATver) ); + filesCAT( cellfun(@(x) exist(x,'file'), ... + spm_file(filesCAT2, 'prefix','p0') )>0 ) = []; + if ~isempty( filesCAT ) + matlabbatch{1}.spm.tools.cat.estwrite.data = filesCAT; + matlabbatch{1}.spm.tools.cat.estwrite.extopts.admin.lazy = 1; + spm_jobman('run',matlabbatch); + end + case 'SPM' + SPMpreprocessing4qc; + IXIfilesSPM = files; + IXIfilesSPM( cellfun(@(x) exist(x,'file'),spm_file(IXIfilesSPM,'prefix','c1'))>0 ) = []; + if ~isempty( IXIfilesSPM ) + matlabbatch{1}.spm.spatial.preproc.channel.vols = IXIfilesSPM; + spm_jobman('run',matlabbatch); + end + case 'synthseg' + error('synthseg is not prepared in the public script ... use MATLAB help') + case 'qcseg' + fprintf('No preprocessing required.\n\n'); + end + end + + +% run QC +","MATLAB" +"Neurology","ChristianGaser/cat12","catQC/eva_surf_calcKappa.m",".m","12394","357","function varargout = eva_surf_calcKappa(varargin) +% ______________________________________________________________________ +% Estimates Kappa values for the values of a set of input surfaces files +% P for one or an equal number of reference surface(s) Pref. I.e. the +% surface values rather than the surface position is evaluated. +% +%??[txt,val] = eva_surf_calcKappa(P,Pref,opt) +% +% P .. list of surfaces +% Pref .. ground truth segmentation +% opt +% .methodname .. just to display (default = datasubpath) +% .verb .. verbose level (default = 1) +% .finishsound .. bong (default = 0) +% .spaces .. length of filename field (default = 50) +% ______________________________________________________________________ +% based on cat_tst_calc_kappa +% +% Robert Dahnke +% University Jena +% +% $Id: cat_tst_calc_kappa.m 1319 2018-05-23 12:11:55Z dahnke $ +% ______________________________________________________________________ +%#ok<*AGROW> +%#ok<*ASGLU> + +% ______________________________________________________________________ +% ToDo: +% ______________________________________________________________________ + + + % if there is a breakpoint in this file set debug=1 and do not clear temporary variables + %dbs = dbstatus; debug = 0; for dbsi=1:numel(dbs), if strcmp(dbs(dbsi).name,mfilename); debug = 1; break; end; end + + + if nargin==1 % SPM job + if isfield(varargin{1},'P'), P = varargin{1}.P; end + if isfield(varargin{1},'Pref'), Pref = varargin{1}.Pref; end + if isfield(varargin{1},'opt'), opt = varargin{1}.opt; end + elseif nargin>=2 + P = varargin{1}; + Pref = varargin{2}; + if nargin>2 + opt = varargin{3}; + end + end + + +%% initialize output + txt = ''; + val = struct('fname','','path','','name','', ... + 'BE',struct('kappa',[],'accuracy',[],'FP','','FN','', ... + 'sensit_all',[],'sensit',[],'specif',[],'dice',[],'jaccard',[]),... + 'SEG',struct('kappa',[],'rms',[],'kappaGW',[],'rmsGW',[])); + + if exist('nargin','var') + if nargout>0, varargout{1}=''; end + if nargout>1, varargout{2}={''}; end + if nargout>2, varargout{3}=val; end + end + +% first input - test data + if ~exist('P','var') || isempty(P) || isempty(P{1}) + P = spm_select(Inf,'any','Select surface data to compare'); + else + if isa(P,'cell'), if size(P,1)1 && nargout>2)+1 + + + % create header of output table + if opt.verb>1 + fprintf('eva_surf_calcKappa with %d classes.\n',ncls); + end + tab = {['File ' sprintf(sprintf('%%%ds',opt.spaces-4),opt.methodname)],... + 'kappa','jaacard','dice','sens.','spec.','FP(F)','FN(N)','N/(P+N)','RMS'}; + txt{1} = sprintf(sprintf('\\n%%%ds%%6s%%8s%%8s%%8s%%8s%%8s%%8s%%8s%%8s%%8s\\n',opt.spaces),... + estr,tab{1},tab{2},tab{3},tab{4},tab{5},tab{6},tab{7},tab{8},tab{9},tab{10}); + k = zeros(n,9); + txt{2} = ''; + if opt.verb && ~isempty(txt{1}) && opt.verb>1, fprintf(txt{1}); end + + + %% data evaluation + for i=1:n + %% for all test cases + [pth, name] = fileparts(V(i).fname); + val(i).fname = V(i).fname; + val(i).path = pth; + val(i).name = name; + fnamestr = [spm_str_manip(pth,sprintf('k%d',max(0,min(floor(opt.spaces/3),opt.spaces-numel(name)-1)-1))),'/',... + spm_str_manip(name,sprintf('k%d',opt.spaces - floor(opt.spaces/3)))]; + + % if only one ground-truth image is give use this, otherwise their + % should be a gound-truth for each image + if numel(Vref)==numel(V), Vrefi=i; else, Vrefi=1; end + + % load old results + Pkfname = fullfile(pth,[opt.prefix name '.xml']); + loaderr = 0; + if ~( ~exist(Pkfname,'file') || opt.reprocess || ~cat_io_rerun(Pkfname,V(i).fname) || ~cat_io_rerun(Pkfname,Vref(Vrefi).fname) ) + try + X = cat_io_xml( Pkfname ); k(i,:) = X.ki; txti = X.txti; colori = X.colori; clear X; + catch + loaderr = 1; + end + end + + + if ~exist(Pkfname,'file') || opt.reprocess || ~cat_io_rerun(Pkfname,V(i).fname) || ~cat_io_rerun(Pkfname,Vref(Vrefi).fname) || loaderr + + if numel(Vref)==numel(V) || i==1 + S1 = gifti(Pref{Vrefi}); + S1 = export(S1,'patch'); + vol1 = single(S1.facevertexcdata); + end + S2 = gifti(deblank(P(i,:))); + S2 = export(S2,'patch'); + vol2 = single(S2.facevertexcdata); + + + + % class-based evaluation + if ncls == 1 + try + [kappa_all, kappa, accuracy_all, accuracy, sensit_all, sensit, specif, confusion, dice, jaccard] = ... + cg_confusion_matrix(uint8((round(vol1(:))>opt.thr)+1), uint8((round(vol2(:))>opt.thc)+1), 2); + catch + disp('ERROR'); + end + + + rms = sqrt( cat_stat_nanmean( ( ( vol1(:) - vol2(:) ).^2 ) )); + + FP = confusion(1,2); FN = confusion(2,1); + k(i,:) = [kappa_all,jaccard(1),dice(1),sensit(1),sensit(2),FP,FN,FN/(FN+FP),rms]; + + val(i).BE = struct('kappa',kappa_all,'accuracy',accuracy_all, ... + 'FP',FP,'FN',FN, ... + 'sensit_all',sensit_all,'sensit',sensit(1),'specif',specif(1),'dice',dice(1),'jaccard',jaccard(1)); + + rms = calcRMS(vol1,vol2); + k(i,end) = rms(end); + txti = sprintf(sprintf('%%%ds:%%8.4f%%8.4f%%8.4f%%8.4f%%8.4f%%8.0f%%8.0f%%8.4f%%8.4f\\n', ... + opt.spaces),fnamestr,k(i,:)); + + val(i).SEG = struct('kappa',kappa_all(1),'rms',rms); + colori = kappa_all(1); + else + if numel(Vref)==numel(V), Vrefi=i; else, Vrefi=1; end + vol1 = single(spm_read_vols(Vref(Vrefi))); + vol2 = single(spm_read_vols(V(i))); + + for c=1:ncls, kappa_all(i,c) = cg_confusion_matrix(uint8((round(vol1(:))==c)+1),uint8((round(vol2(:))==c)+1), 2); end + colori = mean(kappa_all); + end + + % save results + if exist(Pkfname,'file'), delete(Pkfname); end + tx = textscan(txt{1},'%s','delimiter','\n'); + cat_io_xml( Pkfname, ... + struct('P',P(i,:),'Pref',Pref{Vrefi}, 'ki',k(i,:), ... + 'Accuracy', accuracy(1) , 'Sensitivity', sensit(1), 'Specificity' , specif(1), ... + 'Confusion',confusion,... + 'Kappa',k(i,1), ... + 'txti',txti, 'txthdr' , tx{1}{5} ,'colori', colori) ); + + end + + + %% + if opt.verb + if ncls==1 + cat_io_cprintf(MarkColor(round(min(40,max(1,evallinearb(colori,1.00,0.80,6)/10*40))),:),txti); + else + cat_io_cprintf(MarkColor(round(min(40,max(1,evallinearb(colori,0.95,0.65,6)/10*40))),:),txti); + end + end + txt{2}=[txt{2} txti]; tab=[tab;[{name},num2cell(k(i,:))]]; + end + + + %% conclustion + if numel(n) + switch ncls + case 1, txt{3} = sprintf(sprintf( ... + ['\\n%%%ds:%%8.4f%%8.4f%%8.4f%%8.4f%%8.4f%%8.0f%%8.0f%%8.4f%%8.4f\\n', ... + '%%%ds:%%8.4f%%8.4f%%8.4f%%8.4f%%8.4f%%8.0f%%8.0f%%8.4f%%8.4f\\n\\n'], ... + opt.spaces,opt.spaces),'mean',mean(k,1),'std',std(k,1,1)); + case 3, txt{3} = sprintf(sprintf( ... + ['\\n%%%ds:%%8.4f%%8.4f%%8.4f%%8.4f%%8.4f |%%8.4f%%8.4f%%8.4f%%8.4f%%8.4f\\n' ... + '%%%ds:%%8.4f%%8.4f%%8.4f%%8.4f%%8.4f |%%8.4f%%8.4f%%8.4f%%8.4f%%8.4f\\n\\n'], ... + opt.spaces,opt.spaces),'mean',mean(k,1),'std',std(k,1,1)); + end + if opt.verb>1 && n>1, fprintf(txt{3}); end + tab = [tab;[{'mean'},num2cell(mean(k,1));'std',num2cell(std(k,1,1))]]; + end + + % export + if nc==1 + if nargout>0, varargout{1}=txt'; end + if nargout>1, varargout{2}=tab; end + if nargout>2, varargout{3}=val; end + else + if nargout>0, varargout{1}=[varargout{1};txt']; end + if nargout>1, varargout{2}{nc}=tab; end + if nargout>2, varargout{3}{nc}=val; end + end + ncls=1; + end + + if opt.finishsound + load gong.mat; + soundsc(y(5000:25000),Fs) + end +end +function rms=calcRMS(v1,v2) +% boundary box???? + for ci=1:max(v1(:)) + c1 = (v1-(ci-1)).* (v1>(ci-1) & v1=ci & v1<(ci+1)); + c2 = (v2-(ci-1)).* (v2>(ci-1) & v2=ci & v2<(ci+1)); + rms(1,ci) = sqrt(cat_stat_nanmean((c1(:)-c2(:)).^2)); + end + + rms(1,end+1) = sqrt(cat_stat_nanmean((v2(:)-v1(:)).^2)); +end +function varargout = cg_confusion_matrix(reference, classified, n_class) +% compute statistic from confusion matrix +% [kappa_all, kappa, accuracy_all, accuracy, sensit_all, sensit, specif, confusion] = cg_confusion_matrix(reference, classified, n_class) + + % get sure that image is integer + + if nargin < 3 + n_class = max(classified); + end + + % build confusion matrix + confusion = zeros(n_class,n_class); + for i = 1:n_class + for j = 1:n_class + confusion(i,j) = length(find(round(reference)==i & round(classified)==j)); + end + end + + N = sum(confusion(:)); + kappa = zeros(size(confusion,1),1,'single'); + sensit = zeros(size(confusion,1),1,'single'); + specif = zeros(size(confusion,1),1,'single'); + accuracy = zeros(size(confusion,1),1,'single'); + + sum_col = sum(confusion,1); + sum_row = sum(confusion,2); + + Pc = 0; + for i = 1:n_class + sum_row_x_col = sum_row(i)*sum_col(i); + + % calculate a..d of confusion matrix + a = confusion(i,i); + b = sum_col(i) - a; + c = sum_row(i) - a; + d = N - (a + b + c); + + specif(i) = d/(b+d); + sensit(i) = a/(a+c); + accuracy(i) = 1-(b+c)/N; + dice(i) = d/(0.5*(d+d+b+c)); % Shattuck 2008, Online resource for validation of brain segmentation methods + jaccard(i) = d/(d+b+c); % Shattuck 2008, Online resource for validation of brain segmentation methods + + kappa(i) = (N*confusion(i,i) - sum_row_x_col)/(N*sum_row(i) - sum_row_x_col + eps); + Pc = Pc + sum_row_x_col/N^2; + end + + P0 = sum(diag(confusion))/N; + + kappa_all = (P0-Pc)/(1-Pc); + sensit_all = P0; + accuracy_all = P0; + + varargout{1} = kappa_all; + varargout{2} = kappa; + varargout{3} = accuracy_all; + varargout{4} = accuracy; + varargout{5} = sensit_all; + varargout{6} = sensit; + varargout{7} = specif; + varargout{8} = confusion; + varargout{9} = dice; + varargout{10} = jaccard; +end","MATLAB" +"Neurology","ChristianGaser/cat12","catQC/eva_vol_calcKappa.m",".m","19504","489","function varargout = eva_vol_calc_kappa(varargin) +% ______________________________________________________________________ +% Estimates Kappa for a set of input images P to one or an equal number of +% reference image(s) Pref. Use realgignment if image properties does not +% match. +% +%??[txt,val] = cat_tst_calc_kappa(P,Pref,opt) +% +% P .. list of images +% Pref .. ground truth segmentation +% opt +% .methodname .. just to display (default = datasubpath) +% .verb .. verbose level (default = 1) +% .realign .. force realignment (default = 0) +% .realignres .. resolution of realignment (default = 1.5) +% .diffimg .. write difference image (default = 0) +% .testcase .. evalution of specific label maps (default = 'auto') +% .finishsound .. bong (default = 0) +% ... +% .spaces .. length of filename field (default = 50) +% ______________________________________________________________________ +% based on cg_calc_kappa by Christian Gaser +% +% Robert Dahnke +% Structural Brain Mapping Group +% University Jena +% +% $Id: cat_tst_calc_kappa.m 1319 2018-05-23 12:11:55Z dahnke $ +% ______________________________________________________________________ +%#ok<*AGROW> +%#ok<*ASGLU> + +% ______________________________________________________________________ +% ToDo: +% - opt.fname .. csv-result file % not yet +% - single segment comparison with input of the first image c1 or p1 +% - csv file export +% - xml file update / export +% - update for 4 class p0 case of CAT12 +% - interpolate to gt resolution +% +% - slicewise and tissue class based evaluation +% ______________________________________________________________________ + + if nargin==1 + if isfield(varargin{1},'P'), P = varargin{1}.P; end + if isfield(varargin{1},'Pref'), Pref = varargin{1}.Pref; end + if isfield(varargin{1},'opt'), opt = varargin{1}.opt; end + else + P = varargin{1}; + Pref = varargin{2}; + opt = varargin{3}; + end + + +% initialize output + txt = ''; + val = struct('fname','','path','','name','', ... + 'BE',struct('kappa',[],'accuracy',[],'FP','','FN','', ... + 'sensit_all',[],'sensit',[],'specif',[],'dice',[],'jaccard',[]),... + 'SEG',struct('kappa',[],'rms',[],'kappaGW',[],'rmsGW',[])); + if nargout>0, varargout{1}=''; end + if nargout>1, varargout{2}={''}; end + if nargout>2, varargout{3}=val; end + + +% first input - test data + if ~exist('P','var') || isempty(P) || isempty(P{1}) + P = spm_select(Inf,'image','Select images to compare'); + else + if isa(P,'cell'), if size(P,1)0)-1); + case 'binary' + ncls = 1; + case 'IBSR' + ncls = 3; + case 'p03' + ncls = 3; + case 'p04', + ncls = 4; + otherwise + ncls = max(round(vol(:))); + if ncls==255, ncls=1; + elseif ncls==254, ncls=3; % IBSR + elseif ncls==4, ncls=3; % default 3-class label images with CSF,GM and WM (and + end + end + clear vol; + +% rating system and color output + MarkColor = cat_io_colormaps('marks+',40); + setnan = [0 nan]; + evallinearb = @(x,best,worst,marks) min(marks,max( 1,(abs(best-x) ./ ... + abs(diff([worst,best]))*(marks-1)+1))) + setnan(isnan(x)+1); + estr = sprintf('%s\n%s\n\n',spm_str_manip(P(1,:),'h'),Vref(1).fname); + + Yp0toC = @(Yp0,c) 1-min(1,abs(Yp0-c)); +% loop + for nc=1:(ncls>1 && nargout>2)+1 + + + % create header of output table + if opt.verb>1 + fprintf('cat_tst_calc_kappa with %d classes.\n',ncls); + end + switch ncls + case 0, txt{1}='Error ground truth empty!'; continue + case 1, tab = {['File ' sprintf(sprintf('%%%ds',opt.spaces-4),opt.methodname)],... + 'kappa','jaacard','dice','sens.','spec.','FP(F)','FN(N)','N/(P+N)','RMS'}; + txt{1} = sprintf(sprintf('\\n%%%ds%%6s%%8s%%8s%%8s%%8s%%8s%%8s%%8s%%8s%%8s\\n',opt.spaces),... + estr,tab{1},tab{2},tab{3},tab{4},tab{5},tab{6},tab{7},tab{8},tab{9},tab{10}); + k = zeros(n,9); + case 3, tab = {['File ' sprintf(sprintf('%%%ds',opt.spaces-4),opt.methodname)],... + 'K(C)','K(G)','K(W)','K(CGW)','K(B)','RMS(C)','RMS(G)','RMS(W)','RMS(CGW)','RMS(B)'}; + txt{1} = sprintf(sprintf('\\n%%%ds%%s%%8s%%8s%%8s%%8s%%8s |%%8s%%8s%%8s%%8s%%8s\\n',opt.spaces),... + estr,tab{1},tab{2},tab{3},tab{4},tab{5},tab{6},tab{7},tab{8},tab{9},tab{10},tab{11}); + k = zeros(n,10); + end + txt{2} = ''; + if opt.verb && ~isempty(txt{1}) && opt.verb>1, fprintf(txt{1}); end + + + % data evaluation + for i=1:n + %% for all test cases + [pth, name] = fileparts(V(i).fname); + val(i).fname = V(i).fname; + val(i).path = pth; + val(i).name = name; + fnamestr = [spm_str_manip(pth,sprintf('k%d',max(0,min(floor(opt.spaces/3),opt.spaces-numel(name)-1)-1))),'/',... + spm_str_manip(name,sprintf('k%d',opt.spaces - floor(opt.spaces/3)))]; + + % if only one ground-truth image is give use this, otherwise their + % should be a gound-truth for each image + if numel(Vref)==numel(V), Vrefi=i; else Vrefi=1; end + if numel(Vref)==numel(V) || i==1 + vol1 = single(spm_read_vols(Vref(Vrefi))); + end + vx_vol = sqrt(sum(Vref(Vrefi).mat(1:3,1:3).^2)); + + % realginment + if any(V(i).dim ~= Vref(Vrefi).dim) || opt.realign>1 %|| any(V(i).mat(:) ~= Vref(Vrefi).mat(:)) + [pp,ff,ee] = spm_fileparts(V(i).fname); + if opt.realign + Vir = [tempname ee]; + try + copyfile(V(i).fname,Vir); warning off; + if 1 + realigntxt = evalc([ .... + 'spm_realign(char([{Vref(Vrefi).fname};{Vir}]), ' ... + 'struct(''sep'',opt.realignres,''rtm'',0,''interp'',4,''graphics'',0,''fwhm'',opt.realignres));']); + else % old + spm_realign(char([{Vref(Vrefi).fname};{Vir}]),... + struct('sep',opt.realignres,'rtm',0,'interp',4,'graphics',0,'fwhm',opt.realignres)); + fprintf(repmat('\b',1,73*3+1)) + end + warning on; + catch + delete(Vir); + warning on; + end + else + Vir = V(i).fname; + end + [V(i),vol2] = cat_vol_imcalc(Vir,Vref(Vrefi),'i1',struct('interp',6,'verb',0)); + else + vol2 = single(spm_read_vols(V(i))); + end + + + %% ds('l2','',1,vol2/ncls,vol1/ncls,vol2/ncls,vol1/ncls,126) + switch opt.testcase + case 'slices' + %% + vol1 = round(vol1); + %vol2 = round(vol2); + + xsum = shiftdim(sum(sum(vol1,2),3),1); xslices = find(xsum>max(xsum)*.1); + ysum = sum(sum(vol1,1),3); yslices = find(ysum>max(ysum)*.1); + zsum = shiftdim(sum(sum(vol1,1),2),1); zslices = find(zsum>max(zsum)*.1); + mask = false(size(vol1)); + for xi=1:numel(xslices), mask(xslices(xi),:,:) = true; end + for yi=1:numel(yslices), mask(:,yslices(yi),:) = true; end + for zi=1:numel(zslices), mask(:,:,zslices(zi)) = true; end + %% + switch ncls + case 1 + [kappa_all, kappa, accuracy_all, accuracy, sensit_all, sensit, specif, confusion, dice, jaccard] = ... + cg_confusion_matrix( uint8(vol1(mask(:))>0) + 1, uint8( round(vol2(mask(:))) == max(vol1(:))-1) + 1, 2); + + % rms for GM class + rms = sqrt( cat_stat_nanmean( ( (vol1(mask(:))>0) - Yp0toC(vol2(mask(:)),2) ).^2 ) ); + + FP = confusion(1,2); FN = confusion(2,1); + k(i,:) = [kappa_all,jaccard(1),dice(1),sensit(1),sensit(2),FP,FN,FN/(FN+FP),rms]; + txti = sprintf(sprintf('%%%ds:%%8.4f%%8.4f%%8.4f%%8.4f%%8.4f%%8.0f%%8.0f%%8.4f%%8.4f\\n',opt.spaces),... + fnamestr,k(i,:)); + + val(i).BE = struct('kappa',kappa_all,'accuracy',accuracy_all, ... + 'FP',FP,'FN',FN, ... + 'sensit_all',sensit_all,'sensit',sensit(1),'specif',specif(1),'dice',dice(1),'jaccard',jaccard(1),'rms',rms); + colori = mean(kappa_all); + case 3 + vol1o = vol1; vol1 = (vol1o==1) + (vol1o==3)*2 + (vol1o==6)*3 + (vol1o==5)*4; +%% + if opt.allkappa + [kappa_all,kappa] = cg_confusion_matrix( uint8(round(vol1(mask(:))+1)) ,uint8(round(vol2(mask(:))+1)), 4); + kappa_all = [kappa(2:4)' kappa_all kappa(1)]; + else + for c=1:2, kappa_all(1,c) = cg_confusion_matrix(uint8((round(vol1(mask(:)))==c)+1),uint8((round(vol2(mask(:)))==c)+1), 2); end + c=3; kappa_all(1,c) = cg_confusion_matrix(uint8((round(vol1(mask(:)))==c)+1),uint8((round(vol2(mask(:)))>=c)+1), 2); + bth=0.5; kappa_all(1,5) = cg_confusion_matrix(uint8((vol1(mask(:))>=bth)+1 ),uint8((vol2(mask(:))>=bth)+1 ), 2); + kappa_all(1,4) = mean(kappa_all(1,1:3)); + end + % rms + rms = calcRMS(vol1(mask(:)),vol2(mask(:))); rms = [rms(1:3) mean(rms(1:3)) rms(4)]; + k(i,:) = [kappa_all,rms]; + txti = sprintf(sprintf('%%%ds:%%8.4f%%8.4f%%8.4f%%8.4f%%8.4f |%%8.4f%%8.4f%%8.4f%%8.4f%%8.4f\\n', ... + opt.spaces),fnamestr,k(i,:)); + + val(i).SEG = struct('kappa',kappa_all(1:3),'rms',rms(1:3),'kappaGW',kappa_all(4),'rmsGW',rms(4)); + + %val(i).BE = struct('kappa',kappa_all,'accuracy',accuracy_all, ... + % 'FP',FP,'FN',FN, ... + % 'sensit_all',sensit_all,'sensit',sensit(1),'specif',specif(1),'dice',dice(1),'jaccard',jaccard(1),'rms',rms); + + colori = mean(kappa_all(1,2:3)); % colori = kappa_all(4); + end + otherwise + %% + + + + if opt.diffimg + [pp,ff,ee] = spm_fileparts(V(i).fname); + [pr,fr] = spm_fileparts(Vref(Vrefi).fname); + + Vd = Vref(Vrefi); + %Vd.fname = fullfile(pp,['diffimg.' strrep(ff,'-','') '-' strrep(fr,'-','') '.' genvarname(strrep(opt.methodname,'/','-')) ee]); + Vd.fname = fullfile(pr,['diffimg.' ff '.' fr '.' ... + strrep(genvarname(strrep(['XNT',opt.methodname],'/','-')),'XNT','') ee]); + spm_write_vol(Vd,vol2-vol1); + end + + + + + %% class-based evaluation + switch ncls + case 1 + %if length(Vref)==n, vol1 = spm_read_vols(Vref(i))/255+1; + %else vol1 = spm_read_vols(Vref(i)); + %end + + maxv=max((vol1(:))); if maxv==255, vol1=vol1/maxv; else vol1=vol1/maxv; end + + [kappa_all, kappa, accuracy_all, accuracy, sensit_all, sensit, specif, confusion, dice, jaccard] = ... + cg_confusion_matrix(uint8((round(vol1(:))>opt.th1)+1), uint8((round(vol2(:))>opt.th2)+1), 2); + + rms = sqrt( cat_stat_nanmean( ( ( vol1(:) - vol2(:) ).^2 ) )); + + FP = confusion(1,2); FN = confusion(2,1); + k(i,:) = [kappa_all,jaccard(1),dice(1),sensit(1),sensit(2),FP,FN,FN/(FN+FP),rms]; + txti = sprintf(sprintf('%%%ds:%%8.4f%%8.4f%%8.4f%%8.4f%%8.4f%%8.0f%%8.0f%%8.4f%%8.4f\\n',opt.spaces),... + fnamestr,k(i,:)); + + val(i).BE = struct('kappa',kappa_all,'accuracy',accuracy_all, ... + 'FP',FP,'FN',FN, ... + 'sensit_all',sensit_all,'sensit',sensit(1),'specif',specif(1),'dice',dice(1),'jaccard',jaccard(1)); + colori = mean(kappa_all); + case 3 + maxv=max((vol1(:))); + switch opt.testcase + case 'IBSR' + vol1=round(vol1); + if maxv>3 + vol1=round(((vol1-64)/(maxv-64)) * 3); + end + otherwise + if maxv>4, vol1=round(vol1); vol1=vol1/maxv*3; end + end + + if 0 + % temporare + % bei dem BWP test bei fsl gibts einen ungekl??rten versatz + if ~isempty(strfind(upper(V(i).fname),'FSL')) && ~isempty(strfind(upper(V(i).fname),'BWP')) + vol2(2:end,:,:)=vol2(1:end-1,:,:); + end + end + + if opt.allkappa + [kappa_all,kappa] = cg_confusion_matrix( uint8(round(vol1(:)+1)) ,uint8(round(vol2(:)+1)), 4); + kappa_all = [kappa(2:4)' kappa_all kappa(1)]; + else + for c=1:2, kappa_all(1,c) = cg_confusion_matrix(uint8((round(vol1(:))==c)+1),uint8((round(vol2(:))==c)+1), 2); end + c=3; kappa_all(1,c) = cg_confusion_matrix(uint8((round(vol1(:))==c)+1),uint8((round(vol2(:))>=c)+1), 2); + bth=0.5; kappa_all(1,5) = cg_confusion_matrix(uint8((vol1(:)>=bth)+1 ),uint8((vol2(:)>=bth)+1 ), 2); + kappa_all(1,4) = mean(kappa_all(1,1:3)); + end + + rms = calcRMS(vol1,vol2); rms = [rms(1:3) mean(rms(1:3)) rms(4)]; + k(i,:) = [kappa_all,rms]; + txti = sprintf(sprintf('%%%ds:%%8.4f%%8.4f%%8.4f%%8.4f%%8.4f |%%8.4f%%8.4f%%8.4f%%8.4f%%8.4f\\n', ... + opt.spaces),fnamestr,k(i,:)); + + val(i).SEG = struct('kappa',kappa_all(1:3),'rms',rms(1:3),'kappaGW',kappa_all(4),'rmsGW',rms(4)); + switch opt.testcase + case 'IBSR' + colori = mean(kappa_all(2:3)); + otherwise + colori = kappa_all(4); + end + otherwise + if numel(Vref)==numel(V), Vrefi=i; else Vrefi=1; end + vol1 = single(spm_read_vols(Vref(Vrefi))); + vol2 = single(spm_read_vols(V(i))); + + for c=1:ncls, kappa_all(i,c) = cg_confusion_matrix(uint8((round(vol1(:))==c)+1),uint8((round(vol2(:))==c)+1), 2); end + colori = mean(kappa_all); + end + if exist('Vo','var') && exist(Vo.fname,'file') + txti = [txti(1:end-1) 'i' txti(end)]; + delete(Vo.fname); + clear Vo; + end + end + + %% + if opt.verb + if ncls==1 && ~strcmp(opt.testcase,'slices') + cat_io_cprintf(MarkColor(round(min(40,max(1,evallinearb(colori,1.00,0.80,6)/10*40))),:),txti); + else + cat_io_cprintf(MarkColor(round(min(40,max(1,evallinearb(colori,0.95,0.65,6)/10*40))),:),txti); + end + end; + txt{2}=[txt{2} txti]; tab=[tab;[{name},num2cell(k(i,:))]]; + end + + + %% conclustion + if numel(n) + switch ncls + case 1, txt{3} = sprintf(sprintf( ... + ['\\n%%%ds:%%8.4f%%8.4f%%8.4f%%8.4f%%8.4f%%8.0f%%8.0f%%8.4f%%8.4f\\n', ... + '%%%ds:%%8.4f%%8.4f%%8.4f%%8.4f%%8.4f%%8.0f%%8.0f%%8.4f%%8.4f\\n\\n'], ... + opt.spaces,opt.spaces),'mean',mean(k,1),'std',std(k,1,1)); + case 3, txt{3} = sprintf(sprintf( ... + ['\\n%%%ds:%%8.4f%%8.4f%%8.4f%%8.4f%%8.4f |%%8.4f%%8.4f%%8.4f%%8.4f%%8.4f\\n' ... + '%%%ds:%%8.4f%%8.4f%%8.4f%%8.4f%%8.4f |%%8.4f%%8.4f%%8.4f%%8.4f%%8.4f\\n\\n'], ... + opt.spaces,opt.spaces),'mean',mean(k,1),'std',std(k,1,1)); + end + if opt.verb>1 && n>1, fprintf(txt{3}); end; + tab = [tab;[{'mean'},num2cell(mean(k,1));'std',num2cell(std(k,1,1))]]; + end + + % export + if nc==1 + if nargout>0, varargout{1}=txt'; end + if nargout>1, varargout{2}=tab; end + if nargout>2, varargout{3}=val; end + else + if nargout>0, varargout{1}=[varargout{1};txt']; end + if nargout>1, varargout{2}{nc}=tab; end + if nargout>2, varargout{3}{nc}=val; end + end + ncls=1; + end + + if opt.finishsound + load gong.mat; + soundsc(y(5000:25000),Fs) + end +end +function rms=calcRMS(v1,v2) +% boundary box???? + v1(v1>3)=3; + v2(v2>3)=3; + + for ci=1:3 + c1 = (v1-(ci-1)).* (v1>(ci-1) & v1=ci & v1<(ci+1)); + c2 = (v2-(ci-1)).* (v2>(ci-1) & v2=ci & v2<(ci+1)); + rms(1,ci) = sqrt(cat_stat_nanmean((c1(:)-c2(:)).^2)); + end + + rms(1,4) = sqrt(cat_stat_nanmean((v2(:)-v1(:)).^2)); +end +function varargout = cg_confusion_matrix(reference, classified, n_class) +% compute statistic from confusion matrix +% [kappa_all, kappa, accuracy_all, accuracy, sensit_all, sensit, specif, confusion] = cg_confusion_matrix(reference, classified, n_class) + + % get sure that image is integer + + if nargin < 3 + n_class = max(classified); + end + + % build confusion matrix + confusion = zeros(n_class,n_class); + for i = 1:n_class + for j = 1:n_class + confusion(i,j) = length(find(round(reference)==i & round(classified)==j)); + end + end + + N = sum(confusion(:)); + kappa = zeros(size(confusion,1),1,'single'); + sensit = zeros(size(confusion,1),1,'single'); + specif = zeros(size(confusion,1),1,'single'); + accuracy = zeros(size(confusion,1),1,'single'); + + sum_col = sum(confusion,1); + sum_row = sum(confusion,2); + + Pc = 0; + for i = 1:n_class + sum_row_x_col = sum_row(i)*sum_col(i); + + % calculate a..d of confusion matrix + a = confusion(i,i); + b = sum_col(i) - a; + c = sum_row(i) - a; + d = N - (a + b + c); + + specif(i) = d/(b+d); + sensit(i) = a/(a+c); + accuracy(i) = 1-(b+c)/N; + dice(i) = d/(0.5*(d+d+b+c)); % Shattuck 2008, Online resource for validation of brain segmentation methods + jaccard(i) = d/(d+b+c); % Shattuck 2008, Online resource for validation of brain segmentation methods + + kappa(i) = (N*confusion(i,i) - sum_row_x_col)/(N*sum_row(i) - sum_row_x_col + eps); + Pc = Pc + sum_row_x_col/N^2; + end + + P0 = sum(diag(confusion))/N; + + kappa_all = (P0-Pc)/(1-Pc); + sensit_all = P0; + accuracy_all = P0; + + varargout{1} = kappa_all; + varargout{2} = kappa; + varargout{3} = accuracy_all; + varargout{4} = accuracy; + varargout{5} = sensit_all; + varargout{6} = sensit; + varargout{7} = specif; + varargout{8} = confusion; + varargout{9} = dice; + varargout{10} = jaccard; +end","MATLAB" +"Neurology","ChristianGaser/cat12","catQC/Rusak2021makeSimpleBids.sh",".sh","420","25","# prepare Rusak + +maindir=20211122-SyntheticDataset +resdir=Rusak2021/SimAthrophy +subjects=$(find $maindir -name ""*_S_*"" -depth 1 ) + +for S in $subjects +do + SN=$(basename $S | tr -d _) + SN2=sub-ADNI$SN + + mkdir -p $resdir/$SN2 + + SES=$(ls $S) + for SI in $SES + do + SN3=$(printf ${SN2}_simGMatrophy%0.2fmm.nii.gz $SI ) + cp ./$S/$SI/SyntheticMRI.nii.gz $resdir/$SN2/$SN3 + done + + gunzip $resdir/$SN2/*.nii.gz + exit +done + +","Shell" +"Neurology","ChristianGaser/cat12","catQC/cat_tst_qa_real.m",".m","114906","1986","%function cat_tst_qa_real6 +% qa_group_test +% Test the automatic QA for 2-3 groups with expert quality rating. +% Problematic is the difference between image quality (the acutal +% rating) and that the final QA measure was scaled to match kappa. +% Therefore, it requires a rating for the final preprocessing quality +% of each method and not only of the original image quality. +% As compro1se noise rating can be used ... +% +% Another problem is the scaling question of the marks ... + +% TODO2022: +% * add machine learning outlier detection +% * add BIDS support for QC ? +% * test the input variability of the methods? n-fold? +% +% Details +% * use two test scenarious (remove light, remove severe artefacts)? +% - not fitting for all ratings! but also no useful effect +% +% Processing / Rating: +% * Rating CAMCAN +% + +%#ok<*SAGROW,*AGROW> + + + +% -- group test skript ---------------------------------------------- +% P .. file-structure +% .p0 .. segmentation files +% .rating .. expert ratings [0 - none, 0.25 ~ very very light; 0.5 ~ light; 0.75 ~ ; 1 - obvious; 1.5 - severe] +% .csv .. csv files with expert ratings and p0-filenames +% .mdirs .. ? +% .xml .. catxml files +% .p0e .. existing p0-files +% X .. XML-data structure +% Q .. XML-data (qc, global values) + + + + % the qafile is used to test different versions of the QC estimation [ IMPORTANT ] + rerun = 2; + fasttest = 0; fast = {'full7','fast7'}; + qaversions = { + 'cat_vol_qa202412'; + ... 'cat_vol_qa202310'; + ... 'cat_vol_qa201901x'; + }; + qais = 1:numel(qaversions); + quai = 1; +% +segment = {'qcseg'}; si=1; + for quai = qais + qafile = qaversions{quai}; + + + % default parameter + if ~exist('opt','var'), opt = struct(); end + % printing options + def.type = '-dpng'; % dataype -depsc + def.res = '-r300'; % resolution + def.dpi = 72; + def.closefig = 1; % close figure after printing + opt.maindir = '/Volumes/SG5TB/MRData/202105_QA'; % main project directory [ IMPORTANT ] + opt.resdir = fullfile(opt.maindir,'+results',['private_' fast{fasttest+1}]); % directory for results + opt.printdir = fullfile(opt.maindir,'+figure' ,['private_' fast{fasttest+1}]); % directory for figures + opt = cat_io_checkinopt(opt,def); + + % translate marks into percentage rating + mark2rps = @(mark) min(100,max(0,105 - mark*10)); + + % create result directories + if ~exist(opt.resdir,'dir'), mkdir(opt.resdir); end + if ~exist(opt.printdir,'dir'), mkdir(opt.printdir); end + + + % ############ + % * add site variable or even sex and age + % ############ + % files with ratings and additional variables + opt.rateCSV = { % NIFTIs CSV column + fullfile(opt.maindir,'ATLAS','ATLASR1.1a'), fullfile(opt.maindir,'+ratings','QC2022_Atlas.csv'), 'ATLASm', 5; % 2x avg + fullfile(opt.maindir,'ATLAS','ATLASR1.1b'), fullfile(opt.maindir,'+ratings','QC2022_Atlas.csv'), 'ATLASo', 5; % 2x avg + fullfile(opt.maindir,'private','Site J - Calgary preschool'), fullfile(opt.maindir,'+ratings','QC2022_Calgary.csv'), 'Calgary', 9; % 3x avg + fullfile(opt.maindir,'private','Site M - BEANstudy'), fullfile(opt.maindir,'+ratings','QC2022_BEAN.csv'), 'BEAN', 5; % 1x + fullfile(opt.maindir,'private','Site O - ABIDE'), fullfile(opt.maindir,'+ratings','QC2022_ABIDE2.csv'), 'ABIDE', 5; % 1x + checked + fullfile(opt.maindir,'private','Site Q - NIH-HBD'), fullfile(opt.maindir,'+ratings','QC2022_NIH.csv'), 'NIH', 5; % 1x + fullfile(opt.maindir,'IXI'), fullfile(opt.maindir,'+ratings','QC2022_IXI.csv'), 'IXI', 5; % 1x + fullfile(opt.maindir,'private','fHKS'), fullfile(opt.maindir,'+ratings','QC2022_fHKS.csv'), 'fHKS', 5; % 1x avg + ... PPMI ? > publication rules issue + ... INDI ? > yes, it support a lot of cites + ... NKI neu?? + ... ds0000144 anxiety ? + ... ds0030097 AOMIC 1000 ? + ... ds# QTIM ? > yes, because I can use this later + ... ds# QTAB ? > yes, because I can use this later + }; + + % -- find p0-files -------------------------------------------------- + stime = cat_io_cmd('Find segmentation files:','','',1); fprintf('\n'); + + + % (1) QC ratings by groups as external ratings from function + % ######## would be good to transfer this into the google table ######### + [good,bad] = get_rating; + get_rating_sites = { % fieldname , directory + 'NKI', 'Site G - NKI'; + 'NYC', 'Site H - ADHD_NYC'; + 'ORE', 'Site I - ADHD_ORE'; + }; + + + % (2) QC ratings from group-wise CSV files to good, to bad, and to P.p0{1} list + P.p0{1} = cell(0); stime2 = []; % used different methods + P.rating = zeros(0); + % search CSV files + if size(opt.rateCSV,1)>0, cat_io_cmd(' CSV files:','g8','',1); stime=[]; fprintf('\n'); end + for fi = 1:size(opt.rateCSV,1) + stime = cat_io_cmd(sprintf(' %s:',opt.rateCSV{fi,3}),'g5','',1,stime); stime2 = stime; + + % read table and remove empty name or rating fields + csv = cat_io_csv(opt.rateCSV{fi,2}); + Pp0ff = csv(2:end,1); + Pp0ffrating = csv(2:end,opt.rateCSV{fi,4}); + Pp0ffrating(cellfun('isempty',Pp0ff)) = []; Pp0ff(cellfun('isempty',Pp0ff)) = []; + Pp0ff(cellfun('isempty',Pp0ffrating)) = []; Pp0ffrating(cellfun('isempty',Pp0ffrating)) = []; + Pp0ffrating = cell2mat(Pp0ffrating); + P.csv.(opt.rateCSV{fi,3}) = csv; + + % remove previous entries of the study on both list + if isfield( bad , opt.rateCSV{fi,3} ) + bad = rmfield( bad , opt.rateCSV{fi,3}); + else + bad.(opt.rateCSV{fi,3}) = {}; + end + if isfield( good , opt.rateCSV{fi,3} ) + good = rmfield( good , opt.rateCSV{fi,3}); + else + good.(opt.rateCSV{fi,3}) = {}; + end + + % add the segmentation file and the ratings based on the csv list + for pi = 1:size(Pp0ff,1) + % first get the file fromd different possible dirs .... + [pp,ff,ee] = spm_fileparts(Pp0ff{pi}); + if strcmp(ee,'.gz'), exnii = ''; else, exnii = '.nii'; end % catch .nii.gz cases + + % first try to find the default mri dir + if exist(fullfile(opt.rateCSV{fi,1},pp,'mri'),'dir') + file = fullfile( opt.rateCSV{fi,1} , pp , 'mri' , ['p0' ff exnii] ); + else % otherwise try the maindir + file = fullfile( opt.rateCSV{fi,1} , pp , ['p0' ff exnii] ); + end + + % if nothing was found try to search for the files + if ~exist(file,'file') + % search for the file (this is slow so we try to avoid it before) + if exist(fullfile(opt.rateCSV{fi,1},pp,'mri'),'dir') + file = cat_vol_findfiles(fullfile(opt.rateCSV{fi,1},pp,'mri'), ['p0*' ff exnii],struct('chararr',1)); + else + file = cat_vol_findfiles(fullfile(opt.rateCSV{fi,1},pp), ['p0*' ff exnii],struct('chararr',1)); + end + + if ~exist(file,'file') + fprintf('Miss: ""%s""\n',Pp0ff{pi}); + file = ''; + end + end + + % add the files to the list depending on the rating + if ~isempty(file) + P.p0{1} = [P.p0{1}; file ]; + if Pp0ffrating(pi) > 0.5 + bad.( opt.rateCSV{fi,3} ) = [ bad.( opt.rateCSV{fi,3} ); file ]; + else + good.( opt.rateCSV{fi,3} ) = [ good.( opt.rateCSV{fi,3} ); file ]; + end + + P.rating(end+1) = Pp0ffrating(pi); + end + end + end + + + % add files from good/bad list + catDBsites = setdiff( fieldnames(good) , opt.rateCSV(:,3) ) ; + for sitei = 1:numel(catDBsites) + sname = get_rating_sites{ strmatch(catDBsites{sitei},get_rating_sites(:,1)) , 1}; + sdir = get_rating_sites{ strmatch(catDBsites{sitei},get_rating_sites(:,1)) , 2}; + stime2 = cat_io_cmd(sprintf(' %s:',sname),'g5','',1,stime2); + + % add good images to file list + for fi = 1:numel(good.(catDBsites{sitei})) + [~,ff] = fileparts(good.(catDBsites{sitei}){fi}); + file = fullfile(fullfile(opt.maindir,'private'),sdir, 'mri',sprintf('p0%s.nii',ff)); + if ~exist(file,'file') + file = fullfile(fullfile(opt.maindir,'private'),sdir,sprintf('p0%s.nii',ff)); + end + if ~exist(file,'file') + file = cat_vol_findfiles(fullfile(opt.maindir,'private',sdir),sprintf('p0%s*.nii',ff)); + end + if ~isempty(file) + P.p0{1} = [P.p0{1};file]; + P.rating(end+1) = 0; + end + end + + % add bad images to file list + for fi = 1:numel(bad.(catDBsites{sitei})) + [~,ff] = fileparts(bad.(catDBsites{sitei}){fi}); + file = fullfile(fullfile(opt.maindir,'private'),sdir, 'mri',sprintf('p0%s.nii',ff)); + if ~exist(file,'file') + file = fullfile(fullfile(opt.maindir,'private'),sdir,sprintf('p0%s.nii',ff)); + end + if ~exist(file,'file') + file = cat_vol_findfiles(fullfile(opt.maindir,'private',sdir),sprintf('p0%s*.nii',ff)); + end + if ~isempty(file) + P.p0{1} = [P.p0{1};file]; + P.rating(end+1) = 1; + end + end + end + + + + % search path of the QA-xml-files with good and bad + stime2 = cat_io_cmd(' QC dirs:','g8','',1,stime2); + P.mdirs{1} = { + 'CAT12' fullfile(opt.maindir,'private','QA_good') '<' [1.0 0.2 0.0] '-'; ... + }; + P.mdirs{2} = P.mdirs{1}; + for fi = 1:size(P.mdirs{1},1), P.mdirs{2}{fi,2} = strrep(P.mdirs{1}{fi,2},'QA_good','QA_bad'); end + for ei = 1:2 + files = cat_vol_findfiles(P.mdirs{ei}{1,2},'p0*.nii'); + P.p0{1} = [P.p0{1}; files]; + P.rating(end+1:end+numel(files)) = (ei==2); % * ones(1,numel(files)); + end + + + + %% fasttest + % ------------------------------------------------------------------------ + + % get site directories + if fasttest + nlim = 20; + stime2 = cat_io_cmd(sprintf(' Limiting dataset to %d scans:',nlim),'g8','',1,stime2); + P.dirs = spm_str_manip(P.p0{1},'hh'); + ses = contains(P.dirs,'anat'); % get BIDS dirs + P.dirs(ses) = spm_str_manip(P.dirs(ses),'hhh'); % rm sub BIDS dirs + P.udirs = unique(P.dirs); % get sites + for pi = 1:numel(P.udirs) + Pdirs = contains(P.dirs,P.udirs{pi}); + if sum(Pdirs) > nlim + rm = Pdirs & cumsum(Pdirs)>nlim; + P.p0{1}(rm) = []; + P.dirs(rm) = []; + P.rating(rm) = []; + end + end + end + + + %% estimate the qa and kappa values for the p0-files + stime2 = cat_io_cmd(' XML files:','g8','',1,stime2); + if isfield(P,'xml'), P = rmfield(P,'xml'); end + if isfield(P,'p0e'), P = rmfield(P,'p0e'); end + % -- do QA --------------------------------------------------------- + % xml-filenames + for pi = 1:numel(P.p0{1}) + [pp,ff] = fileparts(P.p0{1}{pi}); + [~,ppmri] = fileparts(pp); + if strcmp(ppmri,'mri') + P.xml{1}{pi,1} = fullfile(strrep(pp,'mri','report'),[qafile '_' ff(3:end) '.xml']); + else + P.xml{1}{pi,1} = fullfile(pp,'report',[qafile '_' ff(3:end) '.xml']); + end + P.p0e{1}(pi,1) = exist(P.xml{1}{pi},'file')>0; + end + + + + + + %% (re)calcqa and load xml files + % ------------------------------------------------------------------------ + stime2 = cat_io_cmd(sprintf(' Process QC of %d files:',sum(P.p0e{1})),'g8','',1,stime2); + P.qamat{1} = fullfile(opt.resdir,['group_' qafile '_NIR' P.mdirs{ei}{1,1} '.mat']); + % run quality estimation + switch segment{si} + case 'CAT' + PX = P.p0{1}; + qaopt = struct('prefix',[qafile '_'],'write_csv',0,'mprefix','m','orgval',0,'rerun',rerun,'verb',2,'version',qafile); % ########################################## + case 'qcseg' + PX = cat_io_strrep(P.p0{1},'/mri/p0','/'); + qaopt = struct('prefix',[qafile '_qcseg_'],'write_csv',0,'mprefix','m','orgval',0,'rerun',rerun,'verb',2,'version',qafile); % ########################################## + end + if 1 %sum(P.p0e{1}==0)>0 + %eval(sprintf('%s(''p0'',P.p0{1}(P.p0e{1}==0),qaopt);',qafile)); + % cat_vol_qa('p0',P.p0{1}(P.p0e{1}==0),qaopt); + cat_vol_qa('p0',PX(497:end),qaopt); + % cat_vol_qa('p0',P.p0{1},qaopt); + end + % if some files cannot process at all then have to remove them + for pi = sort( find( P.p0e{1}==0 ) , 'descend' )' + if exist(P.xml{1}{pi},'file')==0 + cat_io_cprintf('err',sprintf('Error %s - missing measures. Remove entry\n', P.p0{1}{pi} )); + P.p0{1}(pi) = []; + P.p0e{1}(pi) = []; + P.xml{1}(pi) = []; + P.rating(pi) = []; + end + end + % load quality measures + X.xml = cat_io_xml(P.xml{1}); + if 1 + %% bug correction + reprocess = false(size(P.p0{1})); + for xi=1:numel(X.xml) + if isempty( X.xml(xi).filedata ) + reprocess(xi) = true; + end + end + if sum(reprocess)>0 + cat_vol_qa('p0',P.p0{1}(reprocess),qaopt); + X.xml = cat_io_xml(P.xml{1}); + end + end + + + + + + %% -- prepare QA data ------------------------------------------------ + % re-estimate new rating QR based on the existing measures QM + Q = struct(); + stime = cat_io_cmd(' Prepare quality measurements:','g5','',1,stime2); + if isfield(P,'xml2'), P = rmfield(P,'xml2'); end + if 1 + for pi = 1:numel(P.xml{1}) + [pp,ff] = spm_fileparts(P.p0{1}{pi}); + Q.fname{pi,1} = P.p0{1}{pi}; + Q.fpp{pi,1} = pp; + Q.fff{pi,1} = ff; + if 0 + try + % -- remarks ----------------------------------------------------- + X.xml2(pi) = cat_stat_marks('eval',0,X.xml(pi)); %,default); %,P.mdirs{1,1}); + catch + cat_io_cprintf('err','remarking failed for scan %d: %s',pi); + end + end + end + end + X.xml2 = X.xml; + + + + % -- map QM data ---------------------------------------------------- + % map values to the evaluation structure Q + fieldxml = 'xml2'; % use original (xml) or updated (xml2) rating + QM = {'NCR','ICR','res_RMS','res_ECR','res_ECRmm','FEC','contrastr','IQR','SIQR'}; + for q1 = 1:numel(QM) + field = QM{q1}; + fieldqm = 'qualityratings'; + for pi=1:numel(P.xml{1}) + try + Q.(field)(pi,1) = X.(fieldxml)(pi).(fieldqm).(QM{q1}); + catch + Q.(field)(pi,1) = nan; + end + end + end + for pi=1:numel(P.xml{1}) + try + Q.vx_vol(pi,:) = X.xml(pi).qualitymeasures.res_vx_vol; + catch + Q.vx_vol = nan(1,3); + end + end + + % remove low resolution entries + if 1 + LR = any(Q.vx_vol>2,2); + + P.p0{1}(LR) = []; + P.xml{1}(LR) = []; + P.p0e{1}(LR) = []; + P.rating(LR) = []; + + X.xml(LR) = []; + X.xml2(LR) = []; + + FN = fieldnames(Q); + for fni = 1:numel(FN) + Q.(FN{fni})(LR) = []; + end + end + + % remove unclear entries + if 0 + LR = P.rating>0.2 & P.rating<0.9; + + P.p0{1}(LR) = []; + P.xml{1}(LR) = []; + P.p0e{1}(LR) = []; + P.rating(LR) = []; + + X.xml(LR) = []; + X.xml2(LR) = []; + + FN = fieldnames(Q); + for fni = 1:numel(FN) + Q.(FN{fni})(LR) = []; + end + end + + + + % site alignment + % ----------------------------------------------------------------------- + % Seperation by part of the path with a short name (siten) and an id (site) + % ----------------------------------------------------------------------- + for pi = numel(X.xml):-1:1 + path = X.xml(pi).filedata.path; hhd = ''; + for tpi = 1:6 + hhdo = hhd; + try + [path,hhd,eed] = fileparts( path ); hhd = [hhd eed]; + catch + hhd = 'nan'; + end + switch hhd + case 'Site A - sCMV', Q.siten{pi} = 'CMV'; Q.site(pi) = 1; % ok + case 'Site B - FHD-Boston', Q.siten{pi} = 'FHD'; Q.site(pi) = 2; % ok + case 'Site C - ADHD200_NYC', Q.siten{pi} = 'AD2k'; Q.site(pi) = 3; % ok + case 'Site D - fHKS', Q.siten{pi} = 'fHKS'; Q.site(pi) = 4; % ok + case 'Site E - 99s_113c', Q.siten{pi} = '99s'; Q.site(pi) = 5; % ok + case 'Site F - FHD-Boston_read', Q.siten{pi} = 'FHDB'; Q.site(pi) = 6; % ok + case 'Site G - NKI', Q.siten{pi} = 'NKI'; Q.site(pi) = 7; % ok + case 'Site H - ADHD_NYC', Q.siten{pi} = 'ADNYC'; Q.site(pi) = 8; % ok + case 'Site I - ADHD_ORE', Q.siten{pi} = 'ADORE'; Q.site(pi) = 9; % ok + case 'IXI' + site = double(P.csv.IXI{find(cellfun('isempty',strfind( P.csv.IXI(:,1) , X.xml(pi).filedata.file))==0,1,'first'),8}); + Q.siten{pi} = sprintf('IXI%d',site); + Q.site(pi) = 9 + site; % + ... Calgary preschool: + ... - the protocoll is overall problematic and even the best images are extremly noisy + ... - see also ONRC_2_part# (that uses a rescan concept for averaging) + ... - you can try to keep only the best and worst? |? remove only the worst (higher rating treshold?) + case 'Site J - Calgary preschool'; Q.siten{pi} = 'Calga'; Q.site(pi) = 13; % removed due to general low procoll qualy (but **highres**) + case 'Site M - BEANstudy'; Q.siten{pi} = 'BEAN'; Q.site(pi) = 14; % R1 + checked, ok + ... case 'Site N - twins'; Q.siten{pi} = 'Twins'; Q.site(pi) = 15; % need rating & need procesing + case 'ABIDEII-BNI_1'; Q.siten{pi} = 'ABNI'; Q.site(pi) = 16; % R1 + checked, ok + case 'ABIDEII-EMC_1'; Q.siten{pi} = 'AEMC'; Q.site(pi) = 17; % R1 + checked, ok + case 'ABIDEII-ETH_1'; Q.siten{pi} = 'AETH'; Q.site(pi) = 18; % R1 + checked, ok + case 'ABIDEII-GU_1'; Q.siten{pi} = 'AGU'; Q.site(pi) = 19; % R1 + checked, ok + case 'ABIDEII-IP_1'; Q.siten{pi} = 'AIP'; Q.site(pi) = 20; % R1 + checked + ... - the protocol is quite noisy (1.5 T?) but ok + case 'ABIDEII-IU_1'; Q.siten{pi} = 'AIU'; Q.site(pi) = 21; % R1 + checked, ok - highres + case 'ABIDEII-KKI_1_29273_29322'; Q.siten{pi} = 'AKKI'; Q.site(pi) = 22; % R1 + checked + case 'ABIDEII-KKI_1_29323_29372'; Q.siten{pi} = 'AKKI'; Q.site(pi) = 22; % R1 + checked + case 'ABIDEII-KKI_1_29373_29423'; Q.siten{pi} = 'AKKI'; Q.site(pi) = 22; % R1 + checked + case 'ABIDEII-KKI_1_29424_29485'; Q.siten{pi} = 'AKKI'; Q.site(pi) = 22; % R1 + checked + case 'ABIDEII-KUL_3'; Q.siten{pi} = 'AKUL'; Q.site(pi) = 23; % R1 + chekced, ok, Nf=1 + case 'ABIDEII-NYU_1'; Q.siten{pi} = 'ANYU'; Q.site(pi) = 24; % R1 + checked, ok + case 'ABIDEII-NYU_2'; Q.siten{pi} = 'ANYU'; Q.site(pi) = 24; % R1 + checked, ok + case 'ABIDEII-OHSU_1'; Q.siten{pi} = 'AOHS'; Q.site(pi) = 25; % R1 + checked, ok, various resolutions + ... ABIDE ORNC removed because: + ... - a fast/noisy protocol with many rescans was used + ... - in such noise data the variation by MAs is in range of ""normal"" SNR + ... - image averaging is an essential step here and the question could be if + ... rescans with severe MAs could be detected before averaging + ... well, I would argue that this should be part of the averaging + ... routine that support a much more specific test-retest + case 'ABIDEII-ONRC_2_part1'; Q.siten{pi} = 'AORN'; Q.site(pi) = 26; % R1 - **highres**, highnoise + case 'ABIDEII-ONRC_2_part2'; Q.siten{pi} = 'AORN'; Q.site(pi) = 26; % R1 + case 'ABIDEII-ONRC_2_part3'; Q.siten{pi} = 'AORN'; Q.site(pi) = 26; % R1 + case 'ABIDEII-ONRC_2_part4'; Q.siten{pi} = 'AORN'; Q.site(pi) = 26; % R1 + ... + case 'ABIDEII-SDSU_1'; Q.siten{pi} = 'ASDS'; Q.site(pi) = 27; % R1 + checked2, ok + case 'ABIDEII-STANFORD'; Q.siten{pi} = 'ASTA'; Q.site(pi) = 28; % R1 + checked, ~ok + case 'ABIDEII-TCD_1'; Q.siten{pi} = 'ATCD'; Q.site(pi) = 29; % R1 + checked2, ~ok + case 'ABIDEII-UCD_1'; Q.siten{pi} = 'AUCD'; Q.site(pi) = 30; % R1 + checked2, ok, Nf<10 + case 'ABIDEII-UCLA_1'; Q.siten{pi} = 'AUCL'; Q.site(pi) = 31; % R1 + checked, ok + case 'ABIDEII-UCLA_Long'; Q.siten{pi} = 'AUCL'; Q.site(pi) = 31; % R1 + checked, ok .. longitudinal + case 'ABIDEII-UM'; Q.siten{pi} = 'AUM'; Q.site(pi) = 32; % R1 + checked, ok + case 'ABIDEII-USM_1'; Q.siten{pi} = 'AUSM'; Q.site(pi) = 33; % R1 + checked, ok, Nf=4, **highres** + case 'Site Q - NIH-HBD' + try + site = P.csv.NIH{find(cellfun('isempty',strfind( P.csv.NIH(:,1) , X.xml(pi).filedata.file))==0,1,'first'),8}; + Q.siten{pi} = sprintf('DEV%d',site); + Q.site(pi) = 33 + site; % R1 + catch + Q.siten{pi} = sprintf('DEV1'); + Q.site(pi) = 33 + 1; + end + case 'ATLASR1.1a' + site = str2double(hhdo(2:end)); + Q.siten{pi} = sprintf('ATM%d',site); + Q.site(pi) = 40 + site; + case 'ATLASR1.1b' + site = str2double(hhdo(2:end)); + Q.siten{pi} = sprintf('ATO%d',site); + Q.site(pi) = 51 + site; + ... case 'Site O - PPMI'; Q.siten{pi} = 'P'; Q.site(pi) = 34; % + % case 'IXI' + otherwise + if tpi == 5 && isempty(Q.siten{pi}) + %% + fprintf('""%s"" - %s\n',hhd,P.p0{1}{pi}); + end + + % ################# + % remove entries ? + % ################# + end + end + end + for ti = unique(Q.site), Q.N(Q.site==ti) = sum(Q.site==ti); end + %% + + + + if 0 + % ----------------------------------------------------------------------- + % This part is for manual setups of the variables and ratings. E.g., to + % check the expert ratings (that where done on a xyz-slice preview) for + % deeper problems and miss-alignment (i.e., wrong fields). + % ----------------------------------------------------------------------- + + + % check resolution and other variables + fprintf('Site: %4s %4s %4s %4s %4s %6s >> %6s\n','pass','fail','x','y','z','min','RES'); + for si = unique(Q.site) + xi = find( Q.site == si , 1, 'first'); + fprintf('Site %2d: %4d %4d %4.2fx%4.2fx%4.2f %6.2f >> %6.2f\n',... + si, numel( Q.site == si & Q.group == 0), numel( Q.site == si & Q.group == 0), Q.vx_vol( xi , :), min(Q.vx_vol( xi , :)) , Q.res_RMS(xi) ); + end + + + %% check for outlieres of the fast expert ratings + % -------------------------------------------------------------------- + % I.e., passed images with very low IQR values and failed images with + % very high IQR values. In the fast rating procedure (based on a xyz- + % slice preview) local motion artifacts can be over-seen (often) or + % over-interpretaded (rare). + % -------------------------------------------------------------------- + clc + tsite = 42; % select a site (see site definition above) + tsort = 0; % sort the output with the most relant cases on top) + % threshold between groups as the mean of the median of the lower + % (passed) and upper (failed) median (the sides of the boxplot) + trating = mean( [ median( Q.SIQR ( Q.site' == tsite & Q.group == 0 )) , ... + median( Q.SIQR ( Q.site' == tsite & Q.group == 1 )) ] ); + tgroup{1} = Q.SIQR > trating & Q.site' == tsite & Q.group == 0 & Q.res_RMS < 3; % passed but low IQR + tgroup{2} = Q.SIQR < trating & Q.site' == tsite & Q.group == 1 & Q.res_RMS < 3; % failed but high IQR + texgroup{1} = P.p0{1}(tgroup{1}); + texgroup{2} = P.p0{1}(tgroup{2}); + texgval{1} = Q.SIQR(tgroup{1}); + texgval{2} = Q.SIQR(tgroup{2}); + id{1} = find( tgroup{1} ); + id{2} = find( tgroup{2} ); + tname = {'Expert passed but low IQR (over-seen MAs)'; + 'Expert failed but relative good IQR (over-interpretated MAs)'}; + tcolor = {[0 0.5 0]; [0.5 0 0] }; + torder = {'descend'; 'ascend'}; + fprintf('Site %d ""%s"" (theshold=%0.2f):\n',tsite, Q.siten{find(Q.site==tsite,1,'first')},trating); + for gi = 1:2 + fprintf('%s:\n',tname{gi}); + if tsort, [~,sid] = sort(texgval{gi},torder{gi}); else, sid = 1:numel(texgval{gi}); end + for fi = 1:numel(texgroup{gi}) + cat_io_cprintf(tcolor{gi},sprintf(' %4d - %0.2f - %s\n', id{gi}(sid(fi)), ... + texgval{gi}(sid(fi)), spm_str_manip( texgroup{gi}{sid(fi)} ,'a70'))); + end + end + % general histogram plot of IQR values + figure(933); clf(933); + M = Q.methods(:,1:size(Q.group,2))>0 & Q.group==0 & Q.site' == tsite; + [hg,hr] = hist(Q.(IQRfield)(M(:)),0.5:0.05:6.5); + M = Q.methods(:,1:size(Q.group,2))>0 & Q.group==1 & Q.site' == tsite; + [hb,hr] = hist(Q.(IQRfield)(M(:)),0.5:0.05:6.5); hold on + fill([hr,hr(end)],[hb 0],[0.9 0.0 0.2],'facealpha',0.2); + fill([hr,hr(end)],[hg 0],[0.0 0.8 0.2],'facealpha',0.2); + plot(hr,hg,'color',[0.0 0.8 0.2],'Linestyle','-','linewidth',1.5); + plot(hr,hb,'color',[0.9 0.0 0.2],'Linestyle','-','linewidth',1.5); + xlim([0.5 6.5]); ylim([0 max([hg,hb])*1.2]); hold off; box on; grid on; + title('IQR histogram of expert rated scans','FontSize',FS(1),'FontWeight','bold'); + xlabel('IQR','FontSize',FS(2)); ylabel('number of scans','FontSize',FS(2)); + legend({'passed','failed'},'Location','northeast'); legend('boxoff'); + + + %% independent QC processing test (different xml-files!) + % ATLAS 346, 462, 436, 486 with incorrect segmentation (incorrect setup) + rerun = 2; % FEC: 2,25,27,21 || ECR: 27,24, 20 ||  + tside = unique(Q.site); %1; % 1, 3, 5, 6, ... 18 23 30! 32 33 ... 41 42! 44 45 46 48 47 49 ... +11 + slim = 5; + qaversions = {'cat_vol_qa201901'; 'cat_vol_qa202110'; 'cat_vol_qa'; 'cat_vol_qa202207b';'cat_vol_qa202210'}; + qaversions = {'cat_vol_qa202310'}; + qafield = {'NCR','ICR','res_RMS','res_ECR','FEC','IQR', 'SIQR',}; clear testIQR; + for tsi = tside + for qai = numel(qaversions) + qaopt2 = struct('prefix','test_','write_csv',0,'mprefix','m','orgval',0,'rerun',rerun,'verb',2,'version',qaversions{qai}); + sideidg = find(Q.site == tside(tsi) & P.rating<0.5); if numel(sideidg)>slim, sideidg = sideidg(1:round(numel(sideidg)/slim):end); end %sideidg = []; + sideidb = find(Q.site == tside(tsi) & P.rating>=.5); if numel(sideidb)>slim, sideidb = sideidb(1:round(numel(sideidb)/slim):end); end + sideidx = [sideidg , sideidb]; + if isempty(sideidx), continue; end + fprintf('Run site %d - %s:\n',tside(tsi),Q.siten{sideidx(1)}); + qar = cat_vol_qa('p0',P.p0{1}( sideidx ),qaopt2); + %qar = cat_io_xml( P.xml{1}(sideidx) ); + for qaii = 1:numel(qafield), for qi = 1:numel(qar), testIQR{qaii}(qi) = qar(qi).qualityratings.(qafield{qaii}); end; end + fhx=figure(939); fhx.Position(3:4) = [1000 200]; fhx.Name = sprintf('(%d) %s - %s',tside(tsi),Q.siten{sideidx(1)},qaversions{qai}); + for qaii = 1:numel(qafield) + %nr = cat_tst_qa_normer( testIQR{qaii}' , struct('figure',0,'model',0,'cmodel',2)); + fhx=figure(939); subplot(1,numel(qafield),qaii); + cat_plot_boxplot({ testIQR{qaii}(P.rating( sideidx )<0.5); testIQR{qaii}(P.rating( sideidx )>=0.5) }, ... + struct('usescatter',1,'style',4,'datasymbol','o','ygrid',0,'colormap',[0 .5 0; .5 0 0])); ylim([0 10]); grid on + title(sprintf('%s',strrep(qafield{qaii},'_','\_'))); + + end + if ~exist(fullfile(opt.printdir,'fstsideboxplot'),'dir'), mkdir(fullfile(opt.printdir,'fstsideboxplot')); end + print(fhx,fullfile(opt.printdir,'fstsideboxplot',sprintf('fig_perExpertGroups_%d-%s_%s_%s',tside(tsi),Q.siten{sideidx(1)},qaversions{qai},datestr(clock,'YYYYmm'))),opt.res,opt.type); + + end + end + %% rerun one site to update the CQ after sever changes + qaopt2 = struct('prefix',[qafile '_'],'write_csv',0,'mprefix','m','orgval',0,'rerun',rerun,'verb',2); + eval(sprintf('qar = %s(''p0'', P.p0{1}( Q.site == 32 ) ,qaopt2);',qafile)); % + % - update Q? + % - tmp-xml-name = filename + + %% + cat_tst_qa_normer( Q.(IQRfield)(Q.site' == 21 & Q.train == 1) , struct('figure',3,'model',0,'cmodel',2)); + + %% + for si=unique(Q.site) + cat_tst_qa_normer( Q.(IQRfield)(Q.site' == si), struct('figure',3,'model',4,'cmodel',2)); + title(sprintf('Site %d (n=%d)',si,sum(Q.site' == si))); pause(0.5); + end + + end + + + % setup group and add grouped data + allgood = {}; allbad = {}; + goodfields = fieldnames(good); + for fi=1:numel(goodfields), allgood = [allgood; good.(goodfields{fi})]; end + for fi=1:numel(goodfields), allbad = [allbad; bad.(goodfields{fi})]; end + for pi = 1:numel(P.xml{1}) + [~,ff] = fileparts(fileparts(X(1).xml(pi).filedata.path)); + Q.group(pi,1) = (~contains(ff,'QA_good') && contains(ff,'QA_bad') ) || ... + ( ~strcmp(X(1).xml(pi).filedata.file,'anat') && ... + any(cellfun('isempty',strfind( allbad , X(1).xml(pi).filedata.file ))==0 )) || ... + ( strcmp(X(1).xml(pi).filedata.file,'anat') && ... + any(cellfun('isempty',strfind( allbad , fullfile( ... + spm_str_manip( X(1).xml(pi).filedata.path , 'hhht'), ... + spm_str_manip( X(1).xml(pi).filedata.path , 'hht'), ... + spm_str_manip( X(1).xml(pi).filedata.path , 'ht') ... + ) ))==0 )); + Q.ff{pi,1} = ff; + + try + Q.CMV(pi,1) = X(1).xml(pi).subjectmeasures.vol_rel_CGW(1); + Q.GMV(pi,1) = X(1).xml(pi).subjectmeasures.vol_rel_CGW(2); + Q.WMV(pi,1) = X(1).xml(pi).subjectmeasures.vol_rel_CGW(3); + catch + Q.CMV(pi,1) = nan; + Q.GMV(pi,1) = nan; + Q.WMV(pi,1) = nan; + end + end + % Q.GMVC = Q.GMV - repmat(mean(Q.GMV,1),size(Q.GMV,1),1) + mean(Q.GMV(:)); % should this not be group-site? + + + + + % -- prepare group data --------------------------------------------- + stime = cat_io_cmd(' Prepare group data:','g5','',1,stime); + groups = '2'; groupsn = {'P';'F'}; + gcolor = lines(max(Q.site)); gcolor = repmat(gcolor,1,str2double(groups)); + gcolor = reshape(gcolor',3,numel(gcolor)/3)'; + Q.methods = 1; % ############################ REMOVE ??? ############### + Q.methods = repmat(Q.methods,size(Q.NCR,1),1); + %Q.train = rand(size(Q.CMV))<0.3; % use random value + Q.train = mod(1:numel(Q.CMV),3)' > 0; % split half, third, quad, ... + % create groups + FPgroups = cell(1,str2double(groups)); + for gi=1:str2double(groups) + FPgroups{gi} = Q.group==(gi-1) & Q.methods(:,1:max(1)); + end + + + + + + + %% -- create figure -------------------------------------------------- + + IQRfields = {'NCR','SIQR','IQR','ICR','res_ECR','FEC','res_RMS'}; + %IQRfields = {'NCR','SIQR','IQR','res_ECR','FEC'}; + + for IQRfieldi = 1:numel(IQRfields) + + IQRfield = IQRfields{IQRfieldi}; + norm = {'' 'n'}; + Pfields = {IQRfield,['n' IQRfield]}; + FS = [8 8 2] * (opt.dpi/100) * 2; + rmse = @(x) mean( x.^2 ).^0.5; + + if all(isnan(Q.(IQRfield))), continue; end + + % ########## subdata = 1; % test just a subset, run only good? + model = 0; + cmodel = 1; + onlygood = 0; % print only passed values on the site specific second figure + % mod-cmod: + % 01 vs 02: the median model is surprisingly good (cmod=2 is ok) + % 11 vs 12: quite good but similar to 0# (cmod=2 is also not working) + % 21 vs 22: many positve outliers (cmod=2 is not working) + % 31 vs 32: ok + % 41 vs 42: ok + % 51 vs 52: ok (cmod=2 is not working) + % 6???? + + testsites = unique(Q.site); + testsites = setdiff( unique(Q.site) , [13 25 26 28 37:60]); + %testsites = [13 26 28 21 42 44 45 47 55 56 30 29 2 27 53 58 17 20]; + %testsites = [1 2 3 4 5 6 7 8 9 18 19 20 23 24 25 31 32 33]; + %testsites = [1 2 3 4 5 6 7 8 9 18 19 20 23 24 25 31 32 33]; + for ti = numel(testsites):-1:1 + if sum(Q.site==testsites(ti))<10 || sum(Q.site'==testsites(ti) & Q.group==0)<5 || sum(Q.site'==testsites(ti) & Q.group==1)<5, testsites(ti) = []; end + end + + + % prepare normalized values with full dataset as far as this is only for visualization + for si = unique(Q.site) + Mt = Q.site' == si; + Q.(['n' IQRfield])(Mt) = cat_tst_qa_normer( Q.(IQRfield)(Mt), ... + struct('model',model,'figure',0,'cmodel',cmodel,'train',4)); + end + stime = cat_io_cmd(sprintf(' Create figure (%s,%s,model=%d,cmodel=%d):',qafile,IQRfield,model,cmodel),'b','',1,stime); + + for nci = numel(Pfields) + % general histogram plot of N(S)IQR values ( 2 groups ) + fi = 934 + model + 7*(cmodel-1); + fdn = sprintf('%dsites_model%d_cmodel%d',numel(testsites),model,cmodel); + fd = figure(fi); clf(fi); fd.Name = fdn; fd.Position(3) = 600; fd.Position(4) = 400; + + subplot(2,2,1); + Mp = Q.methods(:,1:size(Q.group,2))>0 & Q.group==0 & ... + any(repmat(Q.site',1,numel(testsites)) == testsites,2); + Mf = Q.methods(:,1:size(Q.group,2))>0 & Q.group==1 & ... + any(repmat(Q.site',1,numel(testsites)) == testsites,2); + if nci == 1 + [hp,hr] = hist(105 - 10*Q.([norm{nci} IQRfield])(Mp(:)),0:100); + [hf,hr] = hist(105 - 10*Q.([norm{nci} IQRfield])(Mf(:)),0:100); hold on + myxlim = [40 100]; + else + [hp,hr] = hist(0 - 10 * Q.([norm{nci} IQRfield])(Mp(:)),-80:0.5:40); + [hf,hr] = hist(0 - 10 * Q.([norm{nci} IQRfield])(Mf(:)),-80:0.5:40); hold on + myxlim = [-60 10]; + end + + th = cat_stat_nanmean( [cat_stat_nanmedian( Q.([norm{nci} IQRfield])( Mf(:) & Q.([norm{nci} IQRfield])(:)cat_stat_nanmedian(Q.([norm{nci} IQRfield])(Mp(:))) ) ) ] ); + if nci == 1, thp = 105 - 10 * th; else, thp = -10 * th; end + + plot([thp thp],[0 max([hf,hp])*1.2],'Color',[0 0.5 1],'linewidth',0.5); + fill([hr,hr(1)],[hp 0],[0.0 0.8 0.2],'facealpha',0.2); + fill([hr,hr(1)],[hf 0],[0.9 0.0 0.2],'facealpha',0.1); + plot(hr,hp,'color',[0.0 0.8 0.2],'Linestyle','-','linewidth',1.5); + plot(hr,hf,'color',[0.9 0.0 0.2],'Linestyle','-','linewidth',1.5); + xlim(myxlim); ylim([0 max([hp,hf])*1.2]); hold off; box on; grid on; ax=gca; ax.XDir = 'reverse'; + title(sprintf('%s histogram of expert rated scans',['n' IQRfield]),'FontSize',FS(1),'FontWeight','bold'); + xlabel(['n' IQRfield],'FontSize',FS(2)); ylabel('number of scans','FontSize',FS(2)); + + % ######## add DICE? + + legend(... + {sprintf('threshold (%0.2f)',thp), ... + sprintf('passed (%0.2f±%0.2f)',-10*cat_stat_nanmedian(Q.([norm{nci} IQRfield])(Mp(:))), 10*cat_stat_nanstd(Q.([norm{nci} IQRfield])(Mp(:)))), ... + sprintf('failed (%0.2f±%0.2f)',-10*cat_stat_nanmedian(Q.([norm{nci} IQRfield])(Mf(:))), 10*cat_stat_nanstd(Q.([norm{nci} IQRfield])(Mf(:))))},... + 'Location','northeast'); legend('boxoff'); + subplot(2,2,2); + if nci == 1 + cdata = { 105 - 10 * Q.(IQRfield)(Mp(:)) , 105 - 10 * Q.(IQRfield)(Mf(:)) }; + else + cdata = { 0 - 10 * Q.(['n' IQRfield])(Mp(:)) , 0 - 10 * Q.(['n' IQRfield])(Mf(:)) }; + end + cat_plot_boxplot( cdata ,struct('names',{{'passed','failed'}} ,'usescatter',1,... + 'style',4,'datasymbol','o','groupcolor',[0 0.8 0; 0.8 0 0], ... + 'sort',0,'ylim',myxlim,'groupnum',1,'ygrid',1)); set(gca,'FontSize',FS(2)*0.8) + hold on; plot([-0.5 2.5],[thp thp],'Color',[0 0.5 1],'linewidth',0.5); + title(sprintf('%s boxplot of expert rated groups',[norm{nci} IQRfield]),'FontSize',FS(1),'FontWeight','bold'); + ylabel(['n' strrep(IQRfield,'_','\_')],'FontSize',FS(2)); xlabel('expert groups','FontSize',FS(2)); + + + fprintf('\n'); + fprintf(' Passed: % 5.2f ±% 5.2f\n', -10*cat_stat_nanmedian(Q.([norm{nci} IQRfield])(Mp(:))), 10*cat_stat_nanstd(Q.([norm{nci} IQRfield])(Mp(:))) ); + fprintf(' Failed: % 5.2f ±% 5.2f\n', -10*cat_stat_nanmedian(Q.([norm{nci} IQRfield])(Mf(:))), 10*cat_stat_nanstd(Q.([norm{nci} IQRfield])(Mf(:))) ); + fprintf(' Incorr: % 5.2f % 5.2f%% (MF: %0.2f%%, MP: %0.2f%%)\n', thp , ... + cat_stat_nansum(Q.([norm{nci} IQRfield])(Mf(:)) < th) / sum(Mf(:)) + sum(Q.([norm{nci} IQRfield])(Mp(:)) > th) / sum(Mp(:)) * 100, ... + cat_stat_nansum(Q.([norm{nci} IQRfield])(Mf(:)) < th) / sum(Mf(:)) * 100, sum(Q.([norm{nci} IQRfield])(Mp(:)) > th) / sum(Mp(:)) * 100); + + + % general histogram plot of N(S)IQR values ( 3 groups ) + subplot(2,2,3); + Mp = Q.methods(:,1:size(Q.group,2))>0 & P.rating'<0.5 & ... + any(repmat(Q.site',1,numel(testsites)) == testsites,2); + Mq = Q.methods(:,1:size(Q.group,2))>0 & P.rating'>=0.5 & P.rating'<1.0 & ... + any(repmat(Q.site',1,numel(testsites)) == testsites,2); + Mf = Q.methods(:,1:size(Q.group,2))>0 & P.rating'>=1.0 & ... + any(repmat(Q.site',1,numel(testsites)) == testsites,2); + if nci == 1 + [hp,hr] = hist(105 - 10 * Q.([norm{nci} IQRfield])(Mp(:)),0:100); + [hq,hr] = hist(105 - 10 * Q.([norm{nci} IQRfield])(Mq(:)),0:100); hold on + [hf,hr] = hist(105 - 10 * Q.([norm{nci} IQRfield])(Mf(:)),0:100); hold on + else + [hp,hr] = hist(0 - 10 * Q.([norm{nci} IQRfield])(Mp(:)),-80:0.5:40); + [hq,hr] = hist(0 - 10 * Q.([norm{nci} IQRfield])(Mq(:)),-80:0.5:40); hold on + [hf,hr] = hist(0 - 10 * Q.([norm{nci} IQRfield])(Mf(:)),-80:0.5:40); hold on + end + + plot([thp thp],[0 max([hf,hp])*1.2],'Color',[0 0.5 1],'linewidth',0.5); + fill([hr,hr(1)],[hp 0],[0.0 0.8 0.2],'facealpha',0.2); + fill([hr,hr(1)],[hq 0],[0.9 0.7 0.0],'facealpha',0.3); + fill([hr,hr(1)],[hf 0],[0.9 0.0 0.2],'facealpha',0.1); + plot(hr,hp,'color',[0.0 0.8 0.2],'Linestyle','-','linewidth',1.5); + plot(hr,hq,'color',[0.9 0.7 0.0],'Linestyle','-','linewidth',1.5); + plot(hr,hf,'color',[0.9 0.0 0.2],'Linestyle','-','linewidth',1.5); + xlim(myxlim); ylim([0 max([hp,hf])*1.2]); hold off; box on; grid on; ax=gca; ax.XDir = 'reverse'; + title(sprintf('%s histogram of expert rated scans',[norm{nci} IQRfield]),'FontSize',FS(1),'FontWeight','bold'); + xlabel(['n' IQRfield],'FontSize',FS(2)); ylabel('number of scans','FontSize',FS(2)); + legend( ... + {sprintf('threshold (%0.2f)',thp), ... + sprintf('passed (%0.2f±%0.2f)' , 10*cat_stat_nanmedian(Q.([norm{nci} IQRfield])(Mp(:))), 10*cat_stat_nanstd(Q.([norm{nci} IQRfield])(Mp(:)))), ... + sprintf('questionable (%0.2f±%0.2f)', 10*cat_stat_nanmedian(Q.([norm{nci} IQRfield])(Mq(:))), 10*cat_stat_nanstd(Q.([norm{nci} IQRfield])(Mq(:)))), ... + sprintf('failed (%0.2f±%0.2f)' , 10*cat_stat_nanmedian(Q.([norm{nci} IQRfield])(Mf(:))), 10*cat_stat_nanstd(Q.([norm{nci} IQRfield])(Mf(:))))}, ... + 'Location','northeast'); legend('boxoff'); + % + subplot(2,2,4); + if nci == 1 + pdata = { 105 - 10 * Q.(IQRfield)(Mp(:)) , 105 - 10 * Q.(IQRfield)(Mq(:)) , 105 - 10 * Q.(IQRfield)(Mf(:)) }; + else + pdata = { 0 - 10 * Q.(['n' IQRfield])(Mp(:)) , 0 - 10 * Q.(['n' IQRfield])(Mq(:)) , 0 - 10 * Q.(['n' IQRfield])(Mf(:)) }; + end + cat_plot_boxplot( pdata ,struct('names',{{'passed','question.','failed'}},'usescatter',1,...'boxwidth',-1,... + 'style',4,'datasymbol','o','groupcolor',[0 0.8 0; 0.8 0.7 0; 0.8 0 0], ... + 'sort',0,'ylim',myxlim,'groupnum',1,'ygrid',1)); set(gca,'FontSize',FS(2)*0.8); + hold on; plot([-0.5 3.5],[thp thp],'Color',[0 0.5 1],'linewidth',0.5); + title(sprintf('%s boxplot of expert rated scans',[norm{nci} IQRfield]),'FontSize',FS(1),'FontWeight','bold'); + ylabel(['n' strrep(IQRfield,'_','\_')],'FontSize',FS(2)); xlabel('expert groups','FontSize',FS(2)); + + if 0 + fprintf('\n'); + fprintf(' Passed: % 5.2f ±% 5.2f\n', 10*median(Q.([norm{nci} IQRfield])(Mp(:))), 10*std(Q.([norm{nci} IQRfield])(Mp(:)))); + fprintf(' Questo: % 5.2f ±% 5.2f\n', 10*median(Q.([norm{nci} IQRfield])(Mq(:))), 10*std(Q.([norm{nci} IQRfield])(Mq(:)))); + fprintf(' Failed: % 5.2f ±% 5.2f\n', 10*median(Q.([norm{nci} IQRfield])(Mf(:))), 10*std(Q.([norm{nci} IQRfield])(Mf(:)))); + end + + % save figure + ndir = fullfile(opt.printdir,'boxplot'); if ~exist(ndir,'dir'); mkdir(ndir); end + print(fd,fullfile(opt.printdir,'boxplot',sprintf('fig_%s_perExpertGroups_%s_%s_%s',IQRfield,fdn,qafile,datestr(clock,'YYYYmm'))),opt.res,opt.type); + if opt.closefig, close(fd); end + end + + + %% + % ======================================================================= + % Figure Quality Values for Expert Groups + % ======================================================================= + if 0 + for ai = 1:2 + for pfi = 1:numel(Pfields) + for tfi = 1:2 % sort + % create/use figure + if exist('fh','var') && numel(fh)>=tfi && fh(tfi).isvalid + clf(fh(tfi)); figure(fh(tfi)) + else + fh(tfi) = figure('Name',sprintf('figure %d - %s %s values per expert group (mod=%d,cmod=%d)',tfi,Pfields{pfi},model,cmodel),'Position',... + [0 0 2000 400],'color',[1 1 1],'PaperPositionMode','auto'); + end + + % extract IQR values + MMCR = cell(''); groupsn2 = cell(''); n = str2double(groups); gxi=1; + for si = testsites %unique(Q.site)% (~isinf(Q.site))) %[1,3:7,9:max(Q.site)] + for gi=1:n + if pfi == 1 + MMCR{gxi} = mark2rps( Q.(Pfields{pfi})( FPgroups{gi} & repmat(Q.site'==si,1,size(FPgroups{gi},2)) ) ); + else + MMCR{gxi} = 0 - 10 * Q.(Pfields{pfi})( FPgroups{gi} & repmat(Q.site'==si,1,size(FPgroups{gi},2)) ); + end + if ai == 1 + groupsn2{gxi} = sprintf('%s%s(%02d)', lower(groupsn{gi}), Q.siten{find(Q.site==si,1,'first')}, Q.site(find(Q.site==si,1,'first')) ); % identifier + else + groupsn2{gxi} = sprintf('%s%02d', lower(groupsn{gi}), Q.site(find(Q.site==si,1,'first')) ); % just a shortcut + end + gxi = gxi+1; + end + % sorting scores + MMCRbadn(gxi - 2) = min([numel(MMCR{gxi - 2}),numel(MMCR{gxi - 1})]); + MMCRbadn(gxi - 1) = MMCRbadn(gxi - 2); + MMCRgoodsep(gxi - 2) = (( median(MMCR{gxi - 2}( MMCR{gxi - 2} < median(MMCR{gxi - 2})) )) - ... + ( median(MMCR{gxi - 1}( MMCR{gxi - 1} > median(MMCR{gxi - 1})) ))) / ... + median(MMCR{gxi - 2}); + MMCRgoodsep(gxi - 1) = MMCRgoodsep(gxi - 2) - eps; + end + % sort by group + if tfi == 2 % + [~,MMCRmeansorti] = sort(MMCRgoodsep,'descend'); + else + MMCRmeansorti = 1:numel(MMCR); + end + boxMMCR = MMCR(MMCRmeansorti); + boxgroupsn2 = groupsn2(MMCRmeansorti); + boxMMCRbadn = MMCRbadn(MMCRmeansorti); + % remove center with low number of cases + mincases = 5; + if mincases>0 + boxMMCR = boxMMCR(boxMMCRbadn>=mincases); + boxgroupsn2 = boxgroupsn2(boxMMCRbadn>=mincases); + boxgcolor = gcolor(MMCRbadn>=mincases,:); + end + + if onlygood + boxMMCR = boxMMCR(1:2:end); + boxgroupsn2 = boxgroupsn2(1:2:end); + boxgcolor = gcolor(1:2:end,:); + end + + % create boxplot + if pfi == 1 + [bp1,bp2] = cat_plot_boxplot(boxMMCR,struct('names',{boxgroupsn2},'boxwidth',-1,... + 'style',4,'groupcolor',boxgcolor, 'usescatter',1,... + 'sort',0,'ylim',[20 100],'groupnum',1,'ygrid',1)); set(gca,'FontSize',FS(2)*0.8) + else + [bp1,bp2] = cat_plot_boxplot(boxMMCR,struct('names',{boxgroupsn2},'boxwidth',1.5 * (2 - onlygood),... + 'style',4,'groupcolor',boxgcolor, 'usescatter',1,... + 'sort',0,'ylim',[-60 + 30*onlygood 10],'groupnum',1,'ygrid',1)); set(gca,'FontSize',FS(2)*0.8) + end + set(gca,'xTickLabelRotation',90) + set(gca,'Position',[0.05 0.25 0.94 0.70]); + title(sprintf('%s by expert quality group',Pfields{pfi},numel(1)),... + 'FontSize',FS(1),'FontWeight','bold'); + xlabel(sprintf('qualitygroups p=pass (n=%d) and f=failed (n=%d) per site',... + [sum(cellfun(@(x) numel(x),boxMMCR(1:2:end))),sum(cellfun(@(x) numel(x),boxMMCR(2:2:end)))]),... + 'FontSize',FS(2)); ylabel('rating score in percent','FontSize',FS(2)); + + % print + if strcmp(Pfields,'nSIQR') + print(fh(tfi),fullfile(opt.printdir,sprintf('fig_ROC_anno%d_ordered%d_%s_model%d_cmodel%d_%s',... + ai>1,tfi>1,Pfields{pfi},model,cmodel)),opt.res,opt.type,datestr(clock,'YYYYmm')); + else + print(fh(tfi),fullfile(opt.printdir,sprintf('fig_ROC_anno%d_ordered%d_%s_%s',... + ai>1,tfi>1,Pfields{pfi})),opt.res,opt.type,datestr(clock,'YYYYmm')); + end + % if opt.closefig, close(fd); end + + + % average/std of each group + if tfi == 1 + fprintf('\nMean and SD of the expert groups in rps: \n'); + else + fprintf('\nSorted mean and SD of the expert groups in rps: \n'); + end + fprintf('Site: %11s%11s','avg','SD'); for si=MMCRmeansorti(1:2:end), fprintf('%11s', groupsn2{si} ); end; fprintf('\n') + fprintf(' mean good:'); fprintf('%10.2f ',[mean(cellfun(@(x) median(x) , MMCR(1:2:end))), ... + std(cellfun(@(x) median(x) , MMCR(1:2:end))), cellfun(@(x) median(x) , MMCR(1:2:end))]); fprintf('\n'); + fprintf(' std good:'); fprintf('%10.2f ',[mean(cellfun(@(x) std(x) , MMCR(1:2:end))), ... + std(cellfun(@(x) std(x) , MMCR(1:2:end))), cellfun(@(x) std(x) , MMCR(1:2:end))]); fprintf('\n'); + fprintf(' mean bad: '); fprintf('%10.2f ',[mean(cellfun(@(x) median(x) , MMCR(2:2:end))), ... + std(cellfun(@(x) median(x) , MMCR(2:2:end))), cellfun(@(x) median(x) , MMCR(2:2:end))]); fprintf('\n'); + fprintf(' std bad: '); fprintf('%10.2f ',[mean(cellfun(@(x) std(x) , MMCR(2:2:end))), ... + std(cellfun(@(x) std(x) , MMCR(2:2:end))), cellfun(@(x) std(x) , MMCR(2:2:end))]); fprintf('\n'); + fprintf(' qant diff:'); fprintf('%10.2f ',[ ... + mean(cellfun(@(x,y) median(x(xmedian(y)))) , MMCR(1:2:end), MMCR(2:2:end) )), ... + std(cellfun(@(x,y) median(x(xmedian(y)))) , MMCR(1:2:end), MMCR(2:2:end) )), ... + cellfun(@(x,y) median(x(xmedian(y)))) , MMCR(1:2:end), MMCR(2:2:end)) ]); fprintf('\n'); %#### better !!! #### + fprintf('\n'); + + % ################### print to file + end + end + end + end + + + + + if 0 + %% GM values for expert groups + % -------------------------------------------------------------------- + % problem is here that the group are not balanced for age (and sex) + %subplot('Position',[b2 pos{2,1}(2) 0.95-b2*1.1 pos{1,1}(4)]); + MMCV = cell(0); groupsn2 = cell(''); n = str2double(groups); gxi=1; + MMCVM = cell(1,2); + %sitenx2 = upper('a_bcdef_ghi'); + for si=1:max(Q.site) % [1,3:7,9:max(Q.site)] + for gi=1:n + MMCV{gxi} = Q.GMV(M3{gi} & repmat(Q.site'==si,1,size(M3{gi},2))); + %sitenx = Q.siten(Q.site'==si); + %groupsn2{gxi} = sprintf('%s%s',lower(groupsn{gi}),sitenx2(si)); %sitenx{1}); + %xx = kmeans3D(MMC{gxi},3); + gxi = gxi+1; + end + if 1 + sitemean = mean(MMCV{gxi-2}); + MMCV{gxi-2} = MMCV{gxi-2} - sitemean; + MMCV{gxi-1} = MMCV{gxi-1} - sitemean; + MMCVM{1} = [MMCVM{1}; MMCV{gxi-2}]; + MMCVM{2} = [MMCVM{2}; MMCV{gxi-1}]; + end + end + if 0 + MMCRmeansorti + end + if 0 + %% + cat_plot_boxplot(MMCVM,struct('boxwidth',-1,'names',{{'pass','failed'}},'usescatter',1,... + 'sort',0,'ylim',[-0.2 0.2],'groupnum',1,'ygrid',1)); set(gca,'FontSize',FS(2)*0.8) + else + cat_plot_boxplot(MMCV,struct('boxwidth',-1,'names',{groupsn2},'usescatter',1,... + 'sort',0,'ylim',[-0.2 0.2],'groupnum',1,'ygrid',1,'groupcolor',gcolor)); set(gca,'FontSize',FS(2)*0.8) + title(sprintf('GMV by expert quality group',numel(1)),... + 'FontSize',FS(1),'FontWeight','bold'); + set(gca,'xTickLabelRotation',90,'Position',[0.05 0.25 0.94 0.70]); + xlabel(sprintf('qualitygroups p=pass (n=%d) and f=failed (n=%d) per site (A-I)',... + [sum(cellfun(@(x) numel(x),MMCV(1:2:end))),sum(cellfun(@(x) numel(x),MMCV(2:2:end)))]),... + 'FontSize',FS(2)); ylabel('GMV','FontSize',FS(2)); + + end + + fprintf('GMV diff: %0.2f\n\n',... + mean( ((cellfun(@mean,MMCV(1:2:end)) - cellfun(@mean,MMCV(2:2:end))) ./ ... + (cellfun(@mean,MMCR(1:2:end)) - cellfun(@mean,MMCR(2:2:end)))).^2 ).^0.5 * 100); + + end + + + + + %% NCR, ICR, IQR, SIQR, NXIQR? + IQRfield = IQRfields{IQRfieldi}; + + fign = 33 + model + 6*(cmodel-1); + fhtmp = figure(fign); fhtmp.Position(3:4) = [1200 400]; clf(fign); + if 0 % default + th = [0.5:0.02:1, 1:0.01:3, 3.02:0.02:4, 4.05:0.05:5, 5.1:0.1:6.5]; % global IQR threshold test range (school grades) + cf = [-1:0.1:-0.1, -0.08:0.02:0, 0:0.01:0.4, 0.42:0.02:0.8, 0.85:0.05:2, 2.1:0.1:3]; % protocoll-specific dIQR threshold test range (school grad range) + elseif 1 % default + th = [0.5:0.05:1.5, 1.52:0.02:2, 2.01:0.01:3, 3.02:0.02:3.5, 3.55:0.05:4, 4.1:0.1:6.5]; % global IQR threshold test range (school grades) + cf = [-1:0.1:-0.5, -0.45:0.05:-0.1, -0.08:0.02:0, 0:0.01:0.6, 0.62:0.02:1.0, 1.05:0.05:1.5, 1.6:0.1:2, 2.2:0.2:3]; % protocoll-specific dIQR threshold test range (school grad range) + else % fast test + th = [0.5:0.1:1, 1:0.05:3, 3.05:0.1:4, 4.1:0.2:6.5]; % global IQR threshold test range (school grades) + cf = [-1:0.2:-0.2, -0.18:0.05:0.5, 0.6:0.1:1, 1.2:0.2:3]; % protocoll-specific dIQR threshold test range (school grad range) + end + erth = 0.5; % expert rating threshold + nontest = [0.15 0.95]; + usenontest = 1; + + + % testsites - a smaller sample of usefull sites is preferable + % 3 sites are inoptimal: + % - Calgary (13) where all images have some kind of artifacts + % - ABIDE ... (26) with an high-res, high-noise rescans protocol for averaging + % - ABIDE Standford (28) where nearly all scans have motion artifacts +% testsites = unique(Q.site(1:4)); + testsites = setdiff( unique(Q.site) , [13 26 28]); + + for ti = numel(testsites):-1:1 + if sum(Q.site==testsites(ti))<10 || sum(Q.site'==testsites(ti) & Q.group==0)<5 || sum(Q.site'==testsites(ti) & Q.group==1)<5, testsites(ti) = []; end + end + fdn = sprintf('%dsites_model%d_cmodel%d',numel(testsites),model,cmodel); + + % (1) general site-unspecific threshold + % _______________________________________________________________________ + % + % Process all cases with the global treshold ""th"" in range of the quality + % measure. There is no further selection here - just process everything! + % _______________________________________________________________________ + if 1 %~exist('sens','var') + sens = {nan(numel(th),1),nan(numel(th),1)}; spec = sens; acc = sens; auc = sens; + sensg = {nan(numel(th),max(Q.site)); nan(numel(th),max(Q.site))}; + specg = sensg; accg = sensg; aucg = sensg; + for i = 1:numel(th) % apply global IQR tresholds for ROC statistic + for ti = 1:2 % train vs. test + M = any( repmat(Q.site',1,numel(testsites)) == repmat(testsites,size(Q.site,1)) , 2); + M = M & Q.train == ti-1; + if usenontest, M = M & (P.rating'nontest(2)); end + + TP = Q.group> erth & Q.(IQRfield) > th(i); TPs = sum(TP(M)); + FP = Q.group<=erth & Q.(IQRfield) > th(i); FPs = sum(FP(M)); + TN = Q.group<=erth & Q.(IQRfield) <= th(i); TNs = sum(TN(M)); + FN = Q.group> erth & Q.(IQRfield) <= th(i); FNs = sum(FN(M)); + + sens{ti}(i) = TPs ./ max(1,TPs + FNs); + spec{ti}(i) = TNs ./ max(1,TNs + FPs); + acc{ti}(i) = (TPs + TNs) / max(1,TPs + FNs + TNs + FPs); + + try + [~,~,~,auc{ti}(i)] = perfcurve( Q.group(M) , Q.(IQRfield)(M) - th(i) , 'true'); + catch + auc{ti}(i) = 1; + end + + % site-specific values + for gi = testsites + Mt = Q.site' == gi & Q.train == ti-1; + if usenontest, Mt = Mt & (P.rating'nontest(2)); end + + TP = Q.group> erth & Q.(IQRfield) > th(i); TPs = sum(TP(Mt)); + FP = Q.group<=erth & Q.(IQRfield) > th(i); FPs = sum(FP(Mt)); + TN = Q.group<=erth & Q.(IQRfield) <= th(i); TNs = sum(TN(Mt)); + FN = Q.group> erth & Q.(IQRfield) <= th(i); FNs = sum(FN(Mt)); + + sensg{ti}(i,gi) = TPs ./ max(1,TPs + FNs); + specg{ti}(i,gi) = TNs ./ max(1,TNs + FPs); + accg{ti}(i,gi) = (TPs + TNs) / max(1,TPs + FNs + TNs + FPs); + + try + [~,~,~,aucg{ti}(i)] = perfcurve( Q.group(Mt) , Q.(IQRfield)(Mt) - th(i) , 'true'); + catch + aucg{ti}(i) = 1; + end + end + end + end + end + + + sens2 = {nan(numel(cf),1),nan(numel(cf),1)}; spec2 = sens2; acc2 = sens2; auc2 = sens2; + sensg2 = {nan(numel(cf),max(Q.site)); nan(numel(cf),max(Q.site))}; + specg2 = sensg2; accg2 = sensg2; aucg2 = sensg2; + Q.Nmn = nan(size(Q.IQR)); Q.Nsd = Q.Nmn; Q.NXIQR = Q.Nmn; + for i = 1:numel(cf) % apply global IQR tresholds for ROC statistic + for ti = 1:2 % train vs. test + M = any( repmat(Q.site',1,numel(testsites)) == repmat(testsites,size(Q.site,1)) , 2); + M = M & Q.train == ti-1; + if usenontest, M = M & (P.rating'nontest(2)); end + + if ti == 1 + [ Q.NXIQR(M) , Q.Nmn(M) , Q.Nsd(M)] = cat_tst_qa_normer( Q.(IQRfield)(M), ... + struct('model',model,'figure',0,'cmodel',cmodel,'sites',Q.site(M)')); + else + for gi = testsites + Q.Nmn(Q.site == gi) = cat_stat_nanmean( Q.Nmn(Q.site == gi) ); + Q.Nsd(Q.site == gi) = cat_stat_nanmean( Q.Nsd(Q.site == gi) ); + end + if cmodel == 1 + Q.NXIQR = Q.(IQRfield) - Q.Nmn; + else + Q.NXIQR = (Q.(IQRfield) - Q.Nmn) ./ Q.Nsd; + end + end + + TP = Q.group> erth & Q.NXIQR > cf(i); TPs = sum(TP(M)); + FP = Q.group<=erth & Q.NXIQR > cf(i); FPs = sum(FP(M)); + TN = Q.group<=erth & Q.NXIQR <= cf(i); TNs = sum(TN(M)); + FN = Q.group> erth & Q.NXIQR <= cf(i); FNs = sum(FN(M)); + + sens2{ti}(i) = TPs ./ max(1,TPs + FNs); + spec2{ti}(i) = TNs ./ max(1,TNs + FPs); + acc2{ti}(i) = (TPs + TNs) / max(1,TPs + FNs + TNs + FPs); + + try + [~,~,~,auc2{ti}(i)] = perfcurve( Q.group(M) , Q.NXIQR(M) - cf(i) , 'true'); + catch + auc2{ti}(i) = 1; + end + end + % site-specific values + for ti = 1:2 + for gi = testsites + Mt = Q.site' == gi & Q.train == ti-1; + if usenontest, Mt = Mt & (P.rating'nontest(2)); end + + TP = Q.group> erth & Q.NXIQR > cf(i); TPs = sum(TP(Mt)); + FP = Q.group<=erth & Q.NXIQR > cf(i); FPs = sum(FP(Mt)); + TN = Q.group<=erth & Q.NXIQR <= cf(i); TNs = sum(TN(Mt)); + FN = Q.group> erth & Q.NXIQR <= cf(i); FNs = sum(FN(Mt)); + + sensg2{ti}(i,gi) = TPs ./ max(1,TPs + FNs); + specg2{ti}(i,gi) = TNs ./ max(1,TNs + FPs); + accg2{ti}(i,gi) = (TPs + TNs) / max(1,TPs + FNs + TNs + FPs); + + try + [~,~,~,aucg2{ti}(i,gi)] = perfcurve( Q.group(Mt) , Q.NXIQR(Mt) - cf(i) , 'true'); + catch + aucg2{ti}(i,gi) = 1; + end + end + end + end + + + %% subfigure 1 with global value/threshold + [~,mxthi] = max( cat_stat_nanmean([ spec{2} , sens{2} ] , 2) ); % train + [~,mxcci] = max( cat_stat_nanmean([ spec2{2} , sens2{2} ] , 2) ); % train + + subplot('Position',[0.05 0.1 0.28 0.85]); + hold on; box on; + for gi = testsites + plot(th,sensg{2}(:,gi),'color',min(1,max(0,[0.0 0.4 0.0]/2+0.6)),'linewidth',0.5); + plot(th,specg{2}(:,gi),'color',min(1,max(0,[0.8 0.0 0.0]/2+0.6)),'linewidth',0.5); + end + plot(th,sens{2},'color',[0.0 0.5 0.0],'Linestyle','-','linewidth',1.5); % [0.0 0.4 1.0] + plot(th,spec{2},'color',[0.8 0.0 0.0],'Linestyle','-','linewidth',1.5); % [0.9 0.0 0.2] + plot( [th(mxthi) th(mxthi)] , [0 1.02] ,'color',[0.8 0.0 0.6],'Linestyle','-','linewidth',2); + hold off; xlim([min(th),max(th)]); ylim([0 1.02]); + title('sensitivity/specificity of site-unspecific threshold','FontSize',FS(1),'FontWeight','bold'); + xlabel([strrep(IQRfield,'_','\_') ' (site-unspecific)'],'FontSize',FS(2) ); ylabel('sensitivity/specificity','FontSize',FS(2)); + legend({'average sensitivity','average specificity','site sensitivity ','site specificity'},... + 'Location','Northeast'); legend('boxoff'); + + + % subfigure 2 with normalized value + subplot('Position',[0.38 0.1 0.28 0.85]); + hold on; box on; + for gi = testsites + plot(cf,sensg2{2}(:,gi),'color',min(1,max(0,[0.0 0.4 0.0]/2+0.6)),'linewidth',0.5); + plot(cf,specg2{2}(:,gi),'color',min(1,max(0,[0.8 0.0 0.0]/2+0.6)),'linewidth',0.5); + end + plot(cf,sens2{2},'color',[0.0 0.5 0.0],'Linestyle','-','linewidth',1.5); + plot(cf,spec2{2},'color',[0.8 0.0 0.0],'Linestyle','-','linewidth',1.5); + plot( [cf(mxcci) cf(mxcci)] , [0 1.02] ,'color',[0.0 0.4 0.8],'Linestyle','-','linewidth',2); + hold off; xlim([min(cf),max(cf)]); ylim([0 1.02]); + title(sprintf('sensitivity/specificity of site-specific threshold (N_{SITE}=%d,N_{SCANS}=%d)', ... + numel(testsites),sum(~Q.train)),'FontSize',FS(1),'FontWeight','bold'); + xlabel(['N' strrep(IQRfield,'_','\_') ' (site-specific)'],'FontSize',FS(2)); ylabel('sensitivity/specificity','FontSize',FS(2)); + legend({'average sensitivity','average specificity','site sensitivity ','site specificity'},... + 'Location','Northeast'); legend('boxoff'); + + + % subfigure 3 with ROC + subplot('Position',[0.70 0.1 0.28 0.85],'box','on'); cla; hold on; grid on; + plot(1- mean(cell2mat(spec) ,2), mean(cell2mat(sens) ,2) ,'color',[0.8 0.0 0.6],'linewidth',1.5); + plot(1- mean(cell2mat(spec2),2), mean(cell2mat(sens2),2) ,'color',[0.0 0.4 0.8],'linewidth',1.5); + plot(1-spec{1} ,sens{1} ,'color',[0.8 0.0 0.6]/2+0.6,'linewidth',0.8); + plot(1-spec{2} ,sens{2} ,'color',[0.8 0.0 0.6]/2+0.6,'linewidth',0.8); + plot(1-spec2{1} ,sens2{1} ,'color',[0.0 0.4 0.8]/2+0.6,'linewidth',0.8); + plot(1-spec2{2} ,sens2{2} ,'color',[0.0 0.4 0.8]/2+0.6,'linewidth',0.8); + hold off; ylim([0.5 1.004]); xlim([-0.004 0.65]); ylim([0 1.0]); xlim([0 1]) + title('receiver operating characteristic (ROC)','FontSize',FS(1),'FontWeight','bold'); + xlabel('False positive rate (1-specificity)','FontSize',FS(2)); + ylabel('True positive rate (sensitivity)','FontSize',FS(2)); + legend({...sprintf('global threshold run1: AUC=%0.3f \n (th=%0.2f rps, ACC=%0.3f)',... + ... auc{1}(mxthi), mark2rps(th(mxthi)), acc{1}(mxthi) ),... + ...sprintf('global threshold run2: AUC=%0.3f \n (th=%0.2f rps, ACC=%0.3f)',... + ... auc{2}(mxthi), mark2rps(th(mxthi)), acc{2}(mxthi) ),... + sprintf('%s (site-unspecific threshold): AUC=%0.3f \n (th=%0.2f rps, ACC=%0.3f)',... + strrep(IQRfield,'_','\_'), ... + mean([auc{1}(mxthi),auc{2}(mxthi)]), th(mxthi), mean([acc{1}(mxthi),acc{2}(mxthi)]) ),... + ...sprintf('site specific threshold run1: AUC=%0.3f \n (cf=%0.2f, ACC=%0.3f)',... + ... auc2{1}(mxcci), cf(mxcci), acc2{1}(mxcci) ),... + ...sprintf('site specific threshold run2: AUC=%0.3f \n (cf=%0.2f, ACC=%0.3f)',... + ... auc2{2}(mxcci), cf(mxcci), acc2{2}(mxcci) ),... + sprintf('N%s (site-specific threshold): AUC=%0.3f \n (th=%0.2f rps, ACC=%0.3f)',... + strrep(IQRfield,'_','\_'), ... + mean([auc2{1}(mxcci),auc2{2}(mxcci)]), cf(mxcci), mean([acc2{1}(mxcci),acc2{2}(mxcci)]) ),... + },'Location','southeast'); + + % + print(fhtmp, fullfile(opt.printdir,sprintf('fig_ROC_%s_%s_%s_%s', IQRfield, qafile, fdn, datestr(clock,'YYYYmm') )), opt.res, opt.type); + % + %if opt.closefig, close(fhtmp); end + + %% print(fh1,fullfile(opt.printdir,sprintf('fig_ROC_%s',ff)),opt.res,opt.type); + + + + if 1 + %% + opt.MarkColor = cat_io_colormaps('marks+',10); + fprintf('\nResults per site (Model: %d-%d):',model,cmodel); + fprintf('\n Site:%8s | ','All'); for ti = testsites, fprintf('%8s | ',sprintf('%d-%s',ti,Q.siten{find(Q.site==ti,1,'first')})); end + fprintf('\n N: %8d | ',-1); for ti = testsites, fprintf('%8d | ',sum(Q.site==ti)); end + fprintf('\n AUC1:%8.3f | ',auc2{1}(mxcci)); for ti = testsites, cat_io_cprintf( opt.MarkColor( max(1,min(size(opt.MarkColor,1), round( 10 - cat_stat_nanmean( aucg2{1}(mxcci,ti) , 2 ) * size(opt.MarkColor,1)))) ,:), ... + sprintf('%8.2f | ',cat_stat_nanmean( aucg2{1}(mxcci,ti) , 2 ))); end + fprintf('\n AUC2:%8.3f | ',auc2{2}(mxcci)); for ti = testsites, cat_io_cprintf( opt.MarkColor( max(1,min(size(opt.MarkColor,1), round( 10 - cat_stat_nanmean( aucg2{2}(mxcci,ti) , 2 ) * size(opt.MarkColor,1)))) ,:), ... + sprintf('%8.2f | ',cat_stat_nanmean( aucg2{2}(mxcci,ti) , 2 ))); end + fprintf('\n ACC1:%8.3f | ',acc2{1}(mxcci)); for ti = testsites, cat_io_cprintf( opt.MarkColor( max(1,min(size(opt.MarkColor,1), round( 10 - cat_stat_nanmean( accg2{1}(mxcci,ti) , 2 ) * size(opt.MarkColor,1)))) ,:), ... + sprintf('%8.2f | ',cat_stat_nanmean( accg2{1}(mxcci,ti) , 2 ))); end + fprintf('\n ACC2:%8.3f | ',acc2{2}(mxcci)); for ti = testsites, cat_io_cprintf( opt.MarkColor( max(1,min(size(opt.MarkColor,1), round( 10 - cat_stat_nanmean( accg2{2}(mxcci,ti) , 2 ) * size(opt.MarkColor,1)))) ,:), ... + sprintf('%8.2f | ',cat_stat_nanmean( accg2{2}(mxcci,ti) , 2 ))); end + fprintf('\n MN: %8.3f | ',mean([auc2{1}(mxcci),auc2{2}(mxcci),acc2{1}(mxcci),acc2{2}(mxcci)])); + for ti = testsites + cat_io_cprintf( opt.MarkColor( max(1,min(size(opt.MarkColor,1), ... + round( 10 - cat_stat_nanmean( [aucg2{1}(mxcci,ti), aucg2{2}(mxcci,ti), accg2{1}(mxcci,ti) , accg2{2}(mxcci,ti)] , 2 ) * size(opt.MarkColor,1)))) ,:), ... + sprintf('%8.2f | ',cat_stat_nanmean( [aucg2{1}(mxcci,ti), aucg2{2}(mxcci,ti), accg2{1}(mxcci,ti) , accg2{2}(mxcci,ti)] , 2 ))); + end + fprintf('\n MNG: %8.3f | ',mean([auc{1}(mxcci),auc{2}(mxcci),acc{1}(mxcci),acc{2}(mxcci)])); + for ti = testsites + cat_io_cprintf( opt.MarkColor( max(1,min(size(opt.MarkColor,1), ... + round( 10 - cat_stat_nanmean( [aucg{1}(mxcci,ti), aucg{2}(mxcci,ti), accg{1}(mxcci,ti) , accg{2}(mxcci,ti)] , 2 ) * size(opt.MarkColor,1)))) ,:), ... + sprintf('%8.2f | ',cat_stat_nanmean( [aucg{1}(mxcci,ti), aucg{2}(mxcci,ti), accg{1}(mxcci,ti) , accg{2}(mxcci,ti)] , 2 ))); + end + fprintf('\n'); + end + + + + if 0 + %% -- correlations --------------------------------------------------- + stime = cat_io_cmd(' Estimate correlations:','g5','',1,stime); + + M = true(size(Q.group,1),1); + M2 = repmat(M,1,size(Q.NCR,2)); M2 = M2(:); + QMnames = {'NCR','ICR','RES','IQR','group','rCSFV','rGMV','rWMV'}; %,'method' + QMcorrs = [ Q.NCR(M2) , Q.ICR(M2) , Q.res_RMS(M2) , Q.(IQRfield)(M2), ... + Q.group(M2) Q.CMV(M2), Q.GMV(M2), Q.WMV(M2)]; + [C.QM.r, C.QM.p] = corr(QMcorrs,'type','Spearman'); + C.QM.rtab = [ [{''} QMnames]; [QMnames',num2cell(round((C.QM.r)*10000)/10000)] ]; + C.QM.ptab = [ [{''} QMnames]; [QMnames',num2cell(round((C.QM.p)*10000)/10000)] ]; + + try C.QM = rmfield(C.QM,'txt'); end %#ok<*TRYNC> + T.ixiPPC = sprintf('\nPCC on IXI database:\n%s\n',... + '------------------------------------------------------------------------------'); + for di=1:size(C.QM.rtab,2)-1, T.ixiPPC = sprintf('%s%8s ',T.ixiPPC,C.QM.rtab{1,di}); end + for dj=3:size(C.QM.rtab,1) + T.ixiPPC = sprintf('%s\n%8s ',T.ixiPPC,C.QM.rtab{1,dj}); + for di=2:size(C.QM.rtab,2) + if C.QM.ptab{dj,di}<0.000001, star='***'; + elseif C.QM.ptab{dj,di}<0.000100, star='** '; + elseif C.QM.ptab{dj,di}<0.010000, star='* '; + else star=' '; + end + if di /dev/null 2>&1 + done +fi + + + +# resultdirnames +HDIR=$(pwd)/results; +FULL_RDIR=""$HDIR/BWPC_full""; # main result with all test cases - removed +NOISE_RDIR=""$HDIR/BWPC_noise""; # smaller resultdir with only the important test +BIAS_RDIR=""$HDIR/BWPC_bias""; # smaller resultdir with only the important test +#RES_RDIR=""$HDIR/BWPC_res""; # smaller resultdir with only the important test - download required +FIELD_RDIR=""$HDIR/BWPC_field""; # smaller resultdir with only the important test +RESR_RDIR=""$HDIR/BWPC_resr""; # smaller resultdir with only the important test +RESI_RDIR=""$HDIR/BWPC_resi""; # smaller resultdir with only the important test +NIR_RDIR=""$HDIR/BWPC_NIR""; # smaller resultdir with only the important test +CON_RDIR=""$HDIR/BWPC_con""; # smaller resultdir with only the important test - further downloads required +WC_RDIR=""$HDIR/BWPC_WC""; # smaller resultdir with only the important test +MS_RDIR=""$HDIR/BWPM""; # smaller resultdir with only the important test - further downloads required T2 PD ... +GT_RDIR=""$HDIR/BWPC_gt""; # groud thruth data +REWRITE=1; + +# further downloads +# - other non T1-T2-PD modalities with pn3 and rf040pA +# - MS PD and T2 with pn3 and rf040pA (and pn7 and rf080pA) +# - other resolution of T1, T2, and PD with pn3 and rf040pA + +#init_matlab=""addpath '/Users/dahnke/Neuroimaging/SPM12Rbeta' '/Users/dahnke/Neuroimaging/SPM12Rbeta/toolbox/vbm12'""; + +# create resultdirs +for TT in T1 T2 PD +do + if [ ! -d ""$FULL_RDIR/$TT"" ]; then mkdir -p ""$FULL_RDIR/$TT""; else if [ ""$REWRITE"" == ""1"" ]; then find $FULL_RDIR/$TT -name ""*.nii"" -delete; fi + fi + if [ ! -d ""$NOISE_RDIR/$TT"" ]; then mkdir -p ""$NOISE_RDIR/$TT""; else if [ $REWRITE ]; then find $NOISE_RDIR/$TT -name ""*.nii"" -delete; fi + fi + if [ ! -d ""$BIAS_RDIR/$TT"" ]; then mkdir -p ""$BIAS_RDIR/$TT""; else if [ $REWRITE ]; then find $BIAS_RDIR/$TT -name ""*.nii"" -delete; fi + fi + #if [ ! -d ""$RES_RDIR/$TT"" ]; then mkdir -p ""$RES_RDIR/$TT""; else if [ $REWRITE ]; then find $RES_RDIR/$TT -name ""*.nii"" -delete; fi + #fi + if [ ! -d ""$FIELD_RDIR/$TT"" ]; then mkdir -p ""$FIELD_RDIR/$TT""; else if [ $REWRITE ]; then find $FIELD_RDIR/$TT -name ""*.nii"" -delete; fi + fi + if [ ! -d ""$RESR_RDIR/$TT"" ]; then mkdir -p ""$RESR_RDIR/$TT""; else if [ $REWRITE ]; then find $RESR_RDIR/$TT -name ""*.nii"" -delete; fi + fi + if [ ! -d ""$RESI_RDIR/$TT"" ]; then mkdir -p ""$RESI_RDIR/$TT""; else if [ $REWRITE ]; then find $RESI_RDIR/$TT -name ""*.nii"" -delete; fi + fi + if [ ! -d ""$NIR_RDIR/$TT"" ]; then mkdir -p ""$NIR_RDIR/$TT""; else if [ $REWRITE ]; then find $NIR_RDIR/$TT -name ""*.nii"" -delete; fi + fi + if [ ! -d ""$WC_RDIR/$TT"" ]; then mkdir -p ""$WC_RDIR/$TT""; else if [ $REWRITE ]; then find $WC_RDIR/$TT -name ""*.nii"" -delete; fi + fi + if [ ! -d ""$MS_RDIR/$TT"" ]; then mkdir -p ""$MS_RDIR/$TT""; else if [ $REWRITE ]; then find $MS_RDIR/$TT -name ""*.nii"" -delete; fi + fi + if [ ! -d ""$GT_RDIR/$TT"" ]; then mkdir -p ""$GT_RDIR/$TT""; else if [ $REWRITE ]; then find $GT_RDIR/$TT -name ""*.nii"" -delete; fi + fi +done +if [ ! -d ""$CON_RDIR"" ]; then mkdir -p ""$CON_RDIR""; else if [ $REWRITE ]; then find $CON_RDIR -name ""*.nii"" -delete; fi +fi + +# GT-copy + + +#RES=""1.00 1.25 1.50 1.75 2.00 2.25 2.50 2.75 3.00"" +#RES=""1.00 2.00 3.00"" +#RES2=""1.00 2.00"" +i=0; +for T in $TC +do + (( i++ )) + + F=$(dirname $T)/$(basename $T .mnc); + FF=$(basename $T .mnc); + + # find txt file & check if correct number -> diplay success or error + if [ -a $F.txt ] + then + S=$(grep $FF $F.txt); + if [ ""$S"" == """" ] + then printf ""%04d - $F: ERROR wrong content in txt-file\n"" $i; continue; + else printf ""%04d - $F "" $i + fi + else + printf ""%04d -$F: ERROR no txt-file\n"" $i; continue; + fi + + # read parameter + ECHO_TIME1=$(grep echo_times $F.txt | cut -d = -f 2- | cut -d , -f 1 | tr -d "" "" ); + ECHO_TIME2=$(grep echo_times $F.txt | cut -d = -f 2- | cut -d , -f 2 | tr -d "" "" ); + FLIP_ANGLE=$(grep flip_angle $F.txt| cut -d = -f 2- | tr -d "" "" ); + INU_FIELD=$(grep inu_field $F.txt | cut -d = -f 2- | tr -d "" "" ); + NO_OF_ECHOES=$(grep no_of_echoes $F.txt | cut -d = -f 2- | tr -d "" "" ); + PERCENT_INU=$(grep percent_inu $F.txt | cut -d = -f 2- | tr -d "" "" ); + PERCENT_NOISE=$(grep percent_noise $F.txt | cut -d = -f 2- | tr -d "" "" ); + PHANTOM=$(grep phantom $F.txt | cut -d = -f 2- | tr -d "" "" ); + RANDOM_SEED=$(grep ""random_seed"" $F.txt | cut -d = -f 2- | tr -d "" "" ); + REFERENCE_TISSUE=$(grep ""reference_tissue"" $F.txt | cut -d = -f 2- | tr -d "" "" ); + SCAN_TECHNIQUE=$(grep ""scan_technique"" $F.txt | cut -d = -f 2- | tr -d "" "" ); + SLICE_THICKNESS=$(grep ""slice_thickness"" $F.txt | cut -d = -f 2- | tr -d "" "" ); + SLICE_RES=$(echo ""scale=0;$SLICE_THICKNESS*100"" | bc | cut -d . -f 1); + TI=$(grep ""ti = "" $F.txt | cut -d = -f 2- | tr -d "" "" ); + TR=$(grep ""tr ="" $F.txt | cut -d = -f 2- | tr -d "" "" ); + TR=$(grep ""tr ="" $F.txt | cut -d = -f 2- | tr -d "" "" ); + + case $SCAN_TECHNIQUE in + DSE_LATE) TT=T2;; + DSE_EARLY) TT=PD;; + SFLASH) TT=T1;; + FLASH) TT=FL;; + FISP) TT=FI;; + IR) TT=IR;; + SE) TT=SE;; + CEFAST) TT=CE;; + *) printf ""> non-default scan_technique $SCAN_TECHNIQUE \n""; continue;; + esac + + case $PHANTOM in + normal) TG=HC;; + msles1) TG=MS1;; + msles2) TG=MS2;; + msles3) TG=MS3;; + *) printf ""> non-default scan_technique $TG \n""; continue;; + esac + + # create filename + APERCENT_INU=$(echo $PERCENT_INU | tr -d -); + case $PERCENT_INU in -*) SPERCENT_INU=""n"";; *) SPERCENT_INU=""p"";; esac + if [ ""$APERCENT_INU"" == ""0"" ]; then SPERCENT_INU=""0""; INU_FIELD=""0""; fi + if [ \( ""$TT"" == ""T1"" -a ""$FLIP_ANGLE"" == ""30"" -a ""$TR"" == ""18"" -a ""$TI"" == """" \) -o \( ""$TT"" == ""T2"" -a ""$FLIP_ANGLE"" == ""90"" -a ""$TR"" == ""3300"" -a ""$TI"" == """" \) -o \( ""$TT"" == ""PD"" -a ""$FLIP_ANGLE"" == ""90"" -a ""$TR"" == ""3300"" -a ""$TI"" == """" \) ] + then + # default case + FN=$(printf ""BWPC_%s_%s_pn%01d_rf%03d%s%s_vx100x100x%03d"" $TG $TT $PERCENT_NOISE $APERCENT_INU $SPERCENT_INU $INU_FIELD $SLICE_RES); + else + # spacial case + FN=$(printf ""BWPC_%s_%s_pn%01d_rf%03d%s%s_vx100x100x%03d_fa%03d_tr%03d_ti%03d"" $TG $TT $PERCENT_NOISE $APERCENT_INU $SPERCENT_INU $INU_FIELD $SLICE_RES $FLIP_ANGLE $TR $TI); + if [ ! -d ""$CON_RDIR"" ]; then mkdir -p ""$CON_RDIR""; fi + + # if [ ""$TG"" == ""HC"" -a ""$SLICE_THICKNESS"" == ""1"" -a \( ""$SPERCENT_INU"" == ""p"" -o ""$SPERCENT_INU"" == ""0"" \) -a ""$INU_FIELD"" == ""A"" -a ""$APERCENT_INU"" == ""40"" -a ""$PERCENT_NOISE"" == ""3"" ] + # then + # convert to nii + mri_convert $F.mnc $CON_RDIR/$FN.nii > /dev/null 2>&1 + # fi + + printf ""> $FN done\n""; + continue + fi + + # convert to nii + mri_convert $F.mnc $FN.nii > /dev/null 2>&1 + + FD=$(pwd); + + # /Applications/MATLAB_R2013b.app/bin/matlab -nodesktop -nodisplay -r ""addpath(fullfile(spm('dir'),'toolbox','vbm12')); cd(fullfile(spm('dir'),'toolbox','vbm12','private')); vbm_tst_reduceRes(fullfile('$FD','$FN.nii'),[2 2 2;1 1 2;2 2 1]); exit"" #> /dev/null 2>&1 + NFN=$(find *.nii -depth 0); mv $NFN $FULL_RDIR/$TT/ + continue + + # cp for NIR (noise inhomogeneity resolution) directory ... 64 cases + # N C R + # N 5 2 2 = 20 + # I 2 6 2 = 24 + # R 2 2 5 = 20 + # 64 * 3 Felder = 196 + if [ ""$TG"" == ""HC"" -a ""$SLICE_THICKNESS"" == ""1"" -a \( ""$SPERCENT_INU"" == ""p"" -o ""$SPERCENT_INU"" == ""0"" \) -a \( ""$APERCENT_INU"" -le ""20"" -o ""$PERCENT_NOISE"" -ge ""1"" \) ] #-a \( ""$INU_FIELD"" == ""A"" -o ""$INU_FIELD"" == ""0"" \) + then + /Applications/MATLAB_R2013b.app/bin/matlab -nodesktop -nodisplay -r ""addpath(fullfile(spm('dir'),'toolbox','vbm12')); cd(fullfile(spm('dir'),'toolbox','vbm12','private')); vbm_tst_reduceRes(fullfile('$FD','$FN.nii'),[2 2 2;1 1 2;2 2 1]); exit"" #> /dev/null 2>&1 + # if [ ""$PERCENT_NOISE"" == ""3"" -a ""$APERCENT_INU"" == ""40"" ] + # then + # printf "">>""; + # /Applications/MATLAB_R2013b.app/bin/matlab -nodesktop -nodisplay -r ""vbm_tst_reduceRes('$FN.nii'); exit"" > /dev/null 2>&1 + # fi + # find *i.nii -depth 0 -delete + #IFN=$(find *i.nii -depth 0); rm $IFN; #mv $IFN $NIR_RDIR/$TT/ + RFN=$(find *r.nii -depth 0); mv $RFN $NIR_RDIR/$TT/ + NFN=$(find *.nii -depth 0); cp $NFN $NIR_RDIR/$TT/ + fi + + + # cp for CON directory - 6 cases + if [ ""$TG"" == ""HC"" -a ""$APERCENT_INU"" == ""40"" -a ""$SPERCENT_INU"" == ""p"" -a ""$INU_FIELD"" == ""A"" -a ""$SLICE_THICKNESS"" == ""1"" -a \( ""TT"" == ""T2"" -o ""TT"" == ""PD"" \) ] + then + FN2=$(printf ""BWPC_%s_%s_pn%01d_rf%03d%s%s_vx100x100x%03d_fa%03d_tr%03d_ti%03d"" $TG $TT $PERCENT_NOISE $APERCENT_INU $SPERCENT_INU $INU_FIELD $SLICE_RES $FLIP_ANGLE $TR $TI); + cp $FN.nii $CON_RDIR/$FN2.nii; + fi + + # cp for noise directory - 6 cases + if [ ""$TG"" == ""HC"" -a ""$APERCENT_INU"" == ""40"" -a ""$SPERCENT_INU"" == ""p"" -a ""$INU_FIELD"" == ""A"" -a ""$SLICE_THICKNESS"" == ""1"" ] + then + cp $FN.nii $NOISE_RDIR/$TT/; + fi + + # cp for bias directory - 6 cases + if [ ""$TG"" == ""HC"" -a ""$PERCENT_NOISE"" == ""3"" -a \( ""$SPERCENT_INU"" == ""p"" -o ""$SPERCENT_INU"" == ""0"" \) -a \( ""$INU_FIELD"" == ""A"" -o ""$INU_FIELD"" == ""0"" \) -a ""$SLICE_THICKNESS"" == ""1"" ] + then + cp $FN.nii $BIAS_RDIR/$TT/; + fi + + # cp for bias field directory - 6 cases (pA,nA,pB,nB,pC,nC) + if [ ""$TG"" == ""HC"" -a ""$PERCENT_NOISE"" == ""3"" -a ""$APERCENT_INU"" == ""40"" -a ""$SLICE_THICKNESS"" == ""1"" ] + then + cp $FN.nii $FIELD_RDIR/$TT/; + fi + + # cp for res directory - 5 cases (1,3,5,7 mm slice thickness) + if [ ""$TG"" == ""HC"" -a ""$PERCENT_NOISE"" == ""3"" -a ""$APERCENT_INU"" == ""40"" -a ""$SPERCENT_INU"" == ""p"" -a ""$INU_FIELD"" == ""A"" ] + then + cp $FN.nii $BIAS_RDIR/$TT/; + fi + + # copy for ground truth directory - 1 case + if [ ""$TG"" == ""HC"" -a ""$PERCENT_NOISE"" == ""0"" -a ""$APERCENT_INU"" == ""0"" -a ""$SLICE_THICKNESS"" == ""1"" ]; + then + cp $FN.nii $GT_RDIR/$TT/; + fi + + # copy for ground truth directory - 1 case + if [ ""$TT"" == ""T1w"" -a ""$TG"" == ""HC"" -a ""$PERCENT_NOISE"" == ""3"" -a ""$APERCENT_INU"" == ""40"" -a ""$SPERCENT_INU"" == ""p"" -a ""$INU_FIELD"" == ""A"" -a ""$SLICE_THICKNESS"" == ""1"" ]; + then + cp $FN.nii $CON_RDIR/$TT/; + fi + + # copy for worst case directory - 6 cases + if [ ""$TG"" == ""HC"" -a ""$PERCENT_NOISE"" == ""9"" -a ""$APERCENT_INU"" == ""100"" -a ""$SLICE_THICKNESS"" == ""1"" ]; + then + cp $FN.nii $WC_RDIR/$TT/; + fi + + # create own reduced resolutions + if [ ""$TG"" == ""HC"" -a ""$PERCENT_NOISE"" == ""3"" -a ""$APERCENT_INU"" == ""40"" -a ""$SPERCENT_INU"" == ""p"" -a ""$INU_FIELD"" == ""A"" -a ""$SLICE_THICKNESS"" == ""1"" ] + then + /Applications/MATLAB_R2013b.app/bin/matlab -nodesktop -nodisplay -r ""addpath(fullfile(spm('dir'),'toolbox','vbm12')); cd(fullfile(spm('dir'),'toolbox','vbm12','private')); vbm_tst_reduceRes(fullfile('$FD','$FN.nii'));; exit"" > /dev/null 2>&1 + IFN=$(find *i.nii -depth 0); mv $IFN $RESI_RDIR/$TT/ + RFN=$(find *r.nii -depth 0); mv $RFN $RESR_RDIR/$TT/ + NFN=$(find *.nii -depth 0); cp $NFN $RESR_RDIR/$TT/ + + # another way to reduce image - more standard, but wit increased noise and bias because of the resampling rather than PVE reduction + if [ ""0"" == ""1"" ] + then + echo simple resampling + for R in $RES + do + # isotropic + RX=$(echo $R*100 | bc | tr . ,); RY=$(echo $R*100 | bc | tr . ,); RZ=$(echo $R*100 | bc | tr . ,); + FN2=$(printf ""BWPC_%s_%s_pn%01d_rf%03d%s%s_res%03.0fx%03.0fx%03.0f"" $TG $TT $PERCENT_NOISE $APERCENT_INU $SPERCENT_INU $INU_FIELD $RX $RY $RZ); + caret_command -volume-resample ""$FN.nii"" ""$RESR_RDIR/$TT/$FN2.nii"" $R $R $R INTERP_CUBIC + caret_command -volume-resample ""$RESR_RDIR/$TT/$FN2.nii"" ""$RESI_RDIR/$TT/${FN2}I.nii"" 1 1 1 INTERP_CUBIC > /dev/null 2>&1 + # sliceresolution + RX=$(echo $R*100 | bc | tr . ,); RY=$(echo $R*100 | bc | tr . ,); RZ=$(echo 1*100 | bc | tr . ,); + FN2=$(printf ""BWPC_%s_%s_pn%01d_rf%03d%s%s_res%03.0fx%03.0fx%03.0f"" $TG $TT $PERCENT_NOISE $APERCENT_INU $SPERCENT_INU $INU_FIELD $RX $RY $RZ); + caret_command -volume-resample ""$FN.nii"" ""$RESR_RDIR/$TT/$FN2.nii"" $R $R 1 INTERP_CUBIC + caret_command -volume-resample ""$RESR_RDIR/$TT/$FN2.nii"" ""$RESI_RDIR/$TT/${FN2}I.nii"" 1 1 1 INTERP_CUBIC > /dev/null 2>&1 + # slicethickness + RX=$(echo 1*100 | bc | tr . ,); RY=$(echo 1*100 | bc | tr . ,); RZ=$(echo $R*100 | bc | tr . ,); + FN2=$(printf ""BWPC_%s_%s_pn%01d_rf%03d%s%s_res%03.0fx%03.0fx%03.0f"" $TG $TT $PERCENT_NOISE $APERCENT_INU $SPERCENT_INU $INU_FIELD $RX $RY $RZ); + caret_command -volume-resample ""$FN.nii"" ""$RESR_RDIR/$TT/$FN2.nii"" 1 1 $R INTERP_CUBIC + caret_command -volume-resample ""$RESR_RDIR/$TT/$FN2.nii"" ""$RESI_RDIR/$TT/${FN2}I.nii"" 1 1 1 INTERP_CUBIC > /dev/null 2>&1 + done + fi + fi + + + # move to final directory - HC or MS + if [ ""$TG"" == ""HC"" ] + then + rm $FN.nii + #mv $FN.nii $FULL_RDIR/$TT + else + mv $FN.nii $MS_RDIR/$TT/; + fi + printf ""> $FN done\n""; + +done +","Shell" +"Neurology","ChristianGaser/cat12","catQC/cat_tst_qa_simerrBWP.m",".m","33861","656","function cat_tst_qa_simerrBWP( datadir, qaversions, fasttest, rerun ) +%% BWP resolutions +% ------------------------------------------------------------------------ +% This function modifies an existing segmentation to test how segmentation +% errors effects the quality measuresments by modifying the Yp0 label map. +% (goal is the evaluation of the general mean effect) +% +% (1) Simulation of skull-stripping errors +% - missing parts +% - additional parts +% - interpreation of intensity scaled Ym as Yp0 segment +% >> this works quite well and the QC is stable even for low Kappas +% +% (2) Simulation of segmentation bias +% - WM overestimation by WM dilatation (> GM erosion) +% - WM underestimation by WM erosion (GM dilation) +% - CSF overestimation by GM/WM erosion (CSF dilation) +% - CSF underestimation by GM/WM dilation (CSF erosion) +% - use of min/max-filters rather than binar morphometric +% operations +% >> this was a bit challenging but it is also ok +% +% (3) Distortion of p0 by noise and smoothing or random deformations +% >> noise worked well +% +% (4) Role of partial volume effects (PVE) - yes/no +% >> not important +% +% Allows quasi-random cases and levels: +% - size in percent of the TIV, e.g., 0:5:20 or 0,5,10,20,40 +% - dist in mm, e.g., 0:5:20 or 0,5,10,20,40; +% - Kappa value as final outcome, e.g., range 0.5 - 1.0 +% +% See also cat_tst_qa_main. +% ------------------------------------------------------------------------ + +%#ok<*UNRCH> +%#ok<*SAGROW> + +cat_io_cprintf([0 0.5 0],'\n\n== Run cat_tst_qa_simerrBWP ==\n') + +if ~license('test', 'Statistics_Toolbox') + error('This function requires the ""Statistics and Machine Learning Toolbox"" of MATLAB.\n') +end + +% ### datadir ### +if ~exist( 'datadir' , 'var' ) + Pddir = '/Volumes/SG5TB/MRData/202503_QA/BWP'; +else + Pddir = fullfile(datadir,'BWP'); +end +% ### QC version ### +if ~exist( 'qaversions' , 'var') + qaversions = { + ...'cat_vol_qa201901'; % classic version (quite stable since 2016) + 'cat_vol_qa201901x'; % refined, debugged version of 201901 + ...'cat_vol_qa202110'; % second classic version (successor of 201901) + ...'cat_vol_qa202110x'; % refined, debugged version of 202110 + ...'cat_vol_qa202205'; % last regular version before update (successor of 202110, stopped) + ...'cat_vol_qa202310'; % redesigned version based on 201901 and 202110 * default * + ...'cat_vol_qa202412'; % experimental version with internal segmentation >> qcseg + }; +end +if ~exist( 'fasttest', 'var'), fasttest = 0; end +if ~exist( 'rerun', 'var'), rerun = 0; end + +outdir = {fullfile(fileparts(Pddir),'BWPE')}; + +% Brain Web Phantom (BWP): +% * Using also cases with strong inhomogeneity causees severe changes of +% NCR and IQR (as expected), whereas contrast and ECR are quite stable. +P = {fullfile(Pddir,'BWPC_HC_T1_pn1_rf020pA_vx100x100x100.nii')}; +Pt = { + { + fullfile(Pddir,'BWPC_HC_T1_pn1_rf020pA_vx100x100x100.nii'); + fullfile(Pddir,'BWPC_HC_T1_pn3_rf020pA_vx100x100x100.nii'); + fullfile(Pddir,'BWPC_HC_T1_pn5_rf020pA_vx100x100x100.nii'); + fullfile(Pddir,'BWPC_HC_T1_pn7_rf020pA_vx100x100x100.nii'); + fullfile(Pddir,'BWPC_HC_T1_pn9_rf020pA_vx100x100x100.nii'); + fullfile(Pddir,'BWPC_HC_T1_pn1_rf020pB_vx100x100x100.nii'); + fullfile(Pddir,'BWPC_HC_T1_pn3_rf020pB_vx100x100x100.nii'); + fullfile(Pddir,'BWPC_HC_T1_pn5_rf020pB_vx100x100x100.nii'); + fullfile(Pddir,'BWPC_HC_T1_pn7_rf020pB_vx100x100x100.nii'); + fullfile(Pddir,'BWPC_HC_T1_pn9_rf020pB_vx100x100x100.nii'); + fullfile(Pddir,'BWPC_HC_T1_pn1_rf020pC_vx100x100x100.nii'); + fullfile(Pddir,'BWPC_HC_T1_pn3_rf020pC_vx100x100x100.nii'); + fullfile(Pddir,'BWPC_HC_T1_pn5_rf020pC_vx100x100x100.nii'); + fullfile(Pddir,'BWPC_HC_T1_pn7_rf020pC_vx100x100x100.nii'); + fullfile(Pddir,'BWPC_HC_T1_pn9_rf020pC_vx100x100x100.nii'); + ... other bias level introduce a lot of variapCe in pCR as they localy change the noise pattern + ... same for negative fields (probably even worse) + ... but maybe your measure is now biased a bit > ########### may run an additional test later ############## + ... maybe as some add data loop with other BWP settings ... + } + }; +Pt{1}( cellfun(@(x) exist(x,'file'),Pt{1})==0 ) = []; + +% 60% bias as average bias case (or 40% as old worst case) but with stronger differences for noise +replaceRF = 20; +if replaceRF + for pti = 1:numel(Pt) + Pt{pti} = strrep(Pt{pti},'_rf020',sprintf('_rf%03d',replaceRF)); + end +end + +% some other normalized Yp0 maps +%Px = { +% { fullfile( spm('dir'),'toolbox','cat12','templates_MNI152NLin2009cAsym','trimmed_Template_T1_masked.nii') }; +% }; +Pp0 = spm_file(P,'prefix',['mri' filesep 'p0']); +%res = repmat( ( 1:0.25:2 )', 1,3); +%ss = repmat( ( 0.25:0.25:2 )', 1,3); + +Pcolor1 = cat_io_colormaps('cold',4); +Pcolor2 = flip( cat_io_colormaps('hot',4) ,1); +Pcolor = [Pcolor1(2:end-1,:); mean([Pcolor1(2:end-1,:);Pcolor2(2:end-1,:)]); Pcolor2(2:end-1,:)]; +Pcolor = repmat( Pcolor , max(1,numel(Pt{1}) / 5) , 1); +QR = {'NCR','ICR','res_ECR','FEC','contrastr','SIQR'}; +QRname = {'NCR','ICR','ECR','FEC','CON','SIQR'}; +markrange = [-.5 .5] * 2 * 3; +fastname = {'full','fast'}; +rerunqc = rerun; +rerunkappa = rerun; + +if fasttest && numel(Pt{1})>=15 + % 1%, 3%, and 9% noise of field A + 9% of field B and C + % (e.g. all worst cases that drives the outliers) + Pt{1} = Pt{1}([1:2:5,10,15]); +else + Pt{1} = Pt{1}(1:end); +end +printdir = fullfile(fileparts(Pddir),'+results',['BWPE_' fastname{fasttest+1} '_' '202508']); %datestr(clock,'YYYYmm')]); + +f29 = figure(3235); +f29.Visible = 'off'; +%f29.Interruptible = 'off'; +set(f29,'Position',[0 0 1600 200],'Name','Skull-Stripping','color',[1 1 1]); +clear valr2; + +qais = 1:numel(qaversions); +for qai = qais + %% + qafile = qaversions{qai}; + + % (1) Simulation of skull-stripping errors + for pi = 1:numel(P) + cat_io_cprintf('blue',sprintf(' Prepare subject %0.0f/%0.0f with %d cases\n',pi,numel(P),numel(Pt{pi}))); + + [~,printname] = spm_fileparts(P{pi}); + + V = spm_vol(P{pi}); + Vp0 = spm_vol(Pp0{pi}); + + Y = spm_read_vols(V); + Yp0 = spm_read_vols(Vp0); + + % simple global intensity normalization + bth = cat_stat_kmeans(Y(Yp0(:)==0)); + wth = cat_stat_kmeans(Y(round(Yp0(:))==3)); + Ym = (Y - bth) ./ abs(diff([bth wth])) ; + Yp0e = max(Yp0,(Yp0==0) .* min(3,Ym*3)); + + % estimate brainmask distance as weighting + Yp0d = cat_vbdist(single(Yp0>0.5)); + Yp0di = cat_vbdist(single(Yp0<0.5)); + + fx = 1; dx = 40; % some paraemters to control the size of the modified area that I am not furhter using + Yp0dw = max( 0 , (Yp0d>0) - Yp0d/dx) + max( 0 , (Yp0di>0) - Yp0di/dx); + + + + + %% (1) Brain masking test + % ---------------------------------------------------------------------- + % There are obvious differences for strong bias in the NCR (and ICR) + % rating that are related to the BWP, i.e. real changes. + % + + % create some quasi-random changes + rng('default') + rng(33*pi); Ymsk = cat_vol_smooth3X( randn(size(Y)) , 8 * fx) * 16; + rng(48*pi); Ymsk = Ymsk + cat_vol_smooth3X( randn(size(Y)) , 4 * fx) * 8; + rng(99*pi); Ymsk = Ymsk + cat_vol_smooth3X( randn(size(Y)) , 2 * fx) * .5; + Ymsk = (Ymsk - mean(Ymsk(:))) ./ std(Ymsk(:)); + + % bstr 16 is kappa ~0.12 and maybe to bad enough to be ingnored + if fasttest + bstr = [0 4 8 12 14 ]; + else + bstr = [0 1 2 4 6 8 10 12 14 ]; + end + ptix = 0; + clear ktab Vmskb; + cat_io_cprintf('blue',sprintf(' Brain masking simulation of %d subcase of %d testcases\n',numel(bstr),numel(Pt{pi}))); + for bstri = 1:numel(bstr) + % create brainmask + % I tried first just to use some distance-weighted cloudy field to create + % some distortions but this was generally not enough. + % bstr = 0.5; % strenght of distortion from 0 (none) to 8 (severe) + + Pp0BSE = spm_file(Pt{pi},'path',outdir,'prefix',sprintf('p0BSE%d',bstr(bstri))); + if ~all(cellfun(@exist,Pp0BSE)==2) + Ymskb = cat_vol_smooth3X( (min(1,Yp0) + Ymsk * bstr(bstri).^2 .* Yp0dw.^4 )>=0.5 , ... + min(8,4*bstr(bstri))) >= 0.5 - 0.01*min(2,bstr(bstri)); + + % Hence, I added some simplyfied Skull-Stripping like model of opening + % and closing to avoid strange holes or large outstanding parts. + [Ymskbr,resr] = cat_vol_resize(Ymskb,'reduceV',1,4); + Ymskbr = cat_vol_morph(Ymskbr,'l'); + Ymskbr = cat_vol_morph(Ymskbr,'do',bstr(bstri)/2); + Ymskbr = cat_vol_morph(Ymskbr,'ldc',bstr(bstri)/2); + Ymskbr = cat_vol_morph(Ymskbr,'ldo',bstr(bstri)/2); + Ymskb = cat_vol_resize(Ymskbr,'dereduceV',resr); + end + + % write data + for pti = 1:numel(Pt{pi}) + ptix = ptix + 1; + Pp0BSEpti = spm_file(Pt{pi}{pti},'path',outdir,'prefix',sprintf('p0BSE%d',bstr(bstri))); + + if ~exist(outdir{1},'dir'), mkdir(outdir{1}); end + if ~exist(Pp0BSEpti,'file') + Vmskb(bstri,pti) = Vp0; Vmskb(bstri,pti).fname = Pp0BSEpti; + spm_write_vol(Vmskb(bstri,pti),Yp0e .* Ymskb); + else + Vmskb(bstri,pti) = spm_vol(Pp0BSEpti); + end + + % T1 copies + if ~exist(spm_file(Pt{pi}{pti},'path',outdir,'prefix',sprintf('BSE%d',bstr(bstri))),'file') + copyfile( Pt{pi}{pti} , spm_file(Pt{pi}{pti},'path',outdir,'prefix',sprintf('BSE%d',bstr(bstri))) ); + end + if ~exist(spm_file(Pt{pi}{pti},'path',outdir,'prefix',sprintf('mBSE%d',bstr(bstri))),'file') + copyfile( Pt{pi}{pti} , spm_file(Pt{pi}{pti},'path',outdir,'prefix',sprintf('mBSE%d',bstr(bstri))) ); + end + end + end + + + %% estimate QC and Kappa + qav = cat_vol_qa('p0',{Vmskb(:).fname},struct('prefix',[qafile '_'],'version',qafile,'rerun',rerunqc)); + if ~exist('valr','var') + [~,valr] = eva_vol_calcKappa({Vmskb(:).fname},Pp0,struct('recalc',rerunkappa)); + end + + + %% Evaluation + set(f29,'Position',[0 0 1800 200],'Name','Skull-Stripping','color',[1 1 1]); + clf(f29); hold on; clear tab; + qav2r = reshape(qav,numel(bstr),numel(Pt{pi})); + RMSE = @(x) mean(x.^2).^0.5; + for qri = 1:numel(QR) + sp29 = subplot('Position',[ (qri-1) * 1 / (numel(QR) + 2) + 0.035 , 0.17 , 0.73 / (numel(QR) + 2) , 0.73],'replace'); + for pti = 1:numel(Pt{pi}) % BWP test case + for bstri = 1:numel(bstr) % skull-stripping + try + tab.(QR{qri})(bstri,pti) = qav2r(bstri,pti).qualityratings.(QR{qri}); + catch + tab.(QR{qri})(bstri,pti) = nan; + end + ktab(bstri,pti) = valr{bstri+1,5}; + end + end + + tab.(QR{qri}) = tab.(QR{qri}) - repmat(tab.(QR{qri})(1,:),numel(bstr),1); + hold on; pl=plot([0 10],[0 0]); pl.Color = [0.3 0.3 0.3]; + for pti = 1:numel(Pt{pi}), px = plot( ktab(:,1), tab.(QR{qri})(:,pti) ); set(px,'Color',Pcolor(pti,:) ); end + pt = plot( ktab(:,1), mean(tab.(QR{qri}),2)); set(pt,'LineWidth',2,'Color',[0 0 0],'Marker','x'); + xlim([0.25,1]), ylim(markrange); grid on; box on; + title(strrep(QRname{qri},'_','\_')); + xlabel('Kappa'); ylabel('mark error'); + set(sp29,'ytick',markrange(1):1:markrange(2),'yticklabel',num2str((markrange(1):1:markrange(2))','%0.2f '), ... + 'xtick',0:0.25:1,'xticklabel',num2str((0:0.25:1)','%0.2f ') ); + end + + % absolute error + subplot('Position',[ (numel(QR)) / (numel(QR) + 2) + 0.035 , 0.17 , 0.72 / (numel(QR) + 2) , 0.73]); + cat_plot_boxplot([ tab.NCR(:) , tab.ICR(:) , tab.res_ECR(:) , tab.FEC(:) , tab.contrastr(:) , ... + tab.SIQR(:) ],struct('names',{QRname},'ygrid',0,'ylim',markrange,'style',4,'datasymbol','o','usescatter',1)) + ax=gca; ax.XTickLabelRotation = 0; ax.YGrid = 'on'; ax.FontSize = 9.5; + set(ax,'ytick',markrange(1):1:markrange(2),'yticklabel',num2str((markrange(1):1:markrange(2))','%0.2f ')); + title('Absolute error'); xlabel('measure'); ylabel('mark error'); + + % RMSE + subplot('Position',[ (numel(QR) + 1) / (numel(QR) + 2) + 0.032 , 0.17 , 0.72 / (numel(QR) + 2) , 0.73]); + rms = @(a) max(0,cat_stat_nanmean(a.^2).^(1/2)); + rmseval = [ rms(tab.NCR(:)) , rms(tab.ICR(:)) , rms(tab.res_ECR(:)) , rms(tab.FEC(:)) , rms(tab.contrastr(:)) , ... + rms(tab.SIQR(:)) ]; + bar(rmseval(1:end)); + ylim([0,markrange(2)]); xlim([.4 6.6]); xticklabels(QRname); + h = gca; h.YGrid = 'on'; h.XTickLabelRotation = 0; + for fi = 1:numel(rmseval) + text(fi-.38, rmseval(fi) + .05, sprintf('%0.3f',rmseval(fi)),'FontSize',7,'Color',[.0 .2 .4]); + end + ax=gca; ax.XTickLabelRotation = 0; ax.YGrid = 'on'; ax.FontSize = 9.5; + set(ax,'ytick',markrange(1):0.5:markrange(2),'yticklabel',num2str((markrange(1):0.5:markrange(2))','%0.2f ')); + title(sprintf('RMSE (%0.3f)',mean(rmseval))); xlabel('measure'); ylabel('mark error'); + + % caption + capf = 1.3; + f29.Position(4) = f29.Position(4)*capf; ax = findobj(f29.Children,'type','Axes'); + for axi=1:numel(ax), ax(axi).Position(4) = ax(axi).Position(4)/1.3; ax(axi).Position(2) = (capf-1) * capf; end + an = annotation('textbox',[0 0 1 ((capf-1)/capf + 0.02) ],'FitBoxToText','off','LineStyle','none','String',{['\bfFig. 2 (' ... + strrep(qafile,'_','\_') '):\rm '... + 'Shown are the results of the quality ratings (as school marks) for simuated brain extraction problems ' ... + 'quantified by the Kappa rating. Even in case of strong errors (Kappa<0.5) the measures stay relative stable ' ... + 'and it has to be considered that the worst Kappa rating of CAT12 was about 0.8. ' ... + 'Blue lines indicate low noise data (BWP noise 1 and 3%), whereas red lines represent noisy data (BWP noise 7 and 9%). ' ... + 'For the\it noise contrast rating\rm (\bfNCR\rm) a half mark is equal to one BWP noise levels and indicate light (motion) artifacts. ' ... + 'For the\it inhomogeneity contrast rating\rm (\bfICR\rm) a 1/4 grade presents a change of 20% of the BWP inhomogeneity. ' ... + 'For\it edge contrast rating\rm (\bfECR\rm) a change of 1 grade correspond to a change of 0.5 mm that is somewhat similar like ' ... + 'Gaussian smoothing of 1.4 mm). ' ... + 'The\it structural image quality rating\rm (\bfSIQR\rm) is the weighted combination of the single measures. ' ... + '']},'Fontsize',12); + + subdir = fullfile(printdir,'Fig2-skullstripping'); + if ~exist(subdir,'dir'), mkdir(subdir); end + fname = fullfile(subdir,sprintf('%s_skullstrippingphantom_%s.jpg',printname,qafile)); + cat_io_cprintf('blue',sprintf(' Write %s\n',fname)); + print(f29, '-djpeg', '-r300', fname); + %delete(an); + + fname = fullfile(subdir,sprintf('%s_skullstrippingphantom_%s_RMSE.csv',printname,qafile)); + tableRMSE = [{'measure:'}, QR; + {'RMSE-skull-stripping'}, num2cell(rmseval)]; + cat_io_csv(fname,tableRMSE); + + + + %% (2) Tissue Segment Modification + % ---------------------------------------------------------------------- + % Tissue changes affect the NCR and ECR but in oposit direction what + % partially depends on the contrast rating. ICR is quite stable. + % Especially the dilatation of the WM was critical - probably because it + % strongly reduce the GM ribbon. + % + + if fasttest + levels = 2; + else + levels = 1:2; %3:4; %1:2; + end + segmentation = cell(1,numel(levels)); seg = segmentation; + for li = 1:numel(levels) + seg{li} = sprintf('L%d',levels(li)); + segmentation{li} = sprintf('segmentation L%d',levels(li)); + end + clear Vmsks; + qav2 = cell(1,numel(levels)); + tabsegt = cell(1,numel(levels)); + ktabsegt = cell(1,numel(levels)); + tcaselong = {'original','dilated WM','eroded WM','dilated CSF','eroded CSF', ... + 'dilated WM and CSF (~eroded GM)','eroded WM and CSF (dilated GM'}; + %% + for li = 1:numel(levels) + tcase = {'org','dw','ew','dc','ec','dd','ee'}; + for ti = 2:numel(tcase), tcase{ti} = sprintf('%s%d',tcase{ti},levels(li)); end + + for ti = 1:numel(tcase) + fprintf(' %s\n', tcase{ti}(1:3)) + deval = str2double(tcase{ti}(3)) / 2; + deval2 = mod(str2double(tcase{ti}(3)) + 1,2) / 2 + 0.5; + Yp0d = Yp0; + Pp0SEG = spm_file(Pt{pi},'path',outdir,'prefix',sprintf('p0SEG%s',tcase{ti})); + if ~all(cellfun(@exist,Pp0SEG)==2) + for it = 1:ceil( deval ) + Yp0o = Yp0d; + switch tcase{ti}(1:2) + case 'or' + Yp0d = Yp0; + case 'dw' % increased NCR, reduced ECR, but ok + Yp0d = max( Yp0d .* (Yp0d<=2) , cat_vol_localstat(single(Yp0d) , Yp0d>=2,1,3)); + case 'ew' % strongly increased NCR, reduced ECR, NOT OK + Yp0d = max( Yp0d .* (Yp0d<=2) , cat_vol_localstat(single(Yp0d) , Yp0d>=2,1,2)); + case 'dc' % increased NCR, reduced ECR, but ok (similar to dw) + Yp0d = max( Yp0d .* (Yp0d>=2.01) , cat_vol_localstat(single(Yp0d) , Yp0d<=2.01,1,2)); + case 'ec' % strongly increased NCR, reduced ECR, NOT OK (better than ew) + Yp0d = max( Yp0d .* (Yp0d>=2.01) , cat_vol_localstat(single(Yp0d) , Yp0d<=2.01,1,3)); + case 'ee' % this is ok + Yp0d = max( Yp0d .* (Yp0d<=2) , cat_vol_localstat(single(Yp0d) , Yp0d>=2,1,2)); + Yp0d = max( Yp0d .* (Yp0d>=2.01) , cat_vol_localstat(single(Yp0d) , Yp0d<=2.01,1,3)); + case 'dd' % dilate WM and CSF result in very small GM ribbon and strong overestimation of NCR and unterstimtion of ECR + Yp0d = max( Yp0d .* (Yp0d<=2) , cat_vol_localstat(single(Yp0d) , Yp0d>=2,1,3)); + Yp0d = max( Yp0d .* (Yp0d>=2.01) , cat_vol_localstat(single(Yp0d) , Yp0d<=2.01,1,2)); + otherwise + error('unknown case') + end + Yp0dc = Yp0d - Yp0o; + Yp0d = Yp0o + min(deval,0.75) * min(min(deval2,1),max(-min(deval2,1),Yp0dc)); %min(min(deval2,1)/2,max(-min(deval2,1)/2,Yp0dc)); + end + + + % write data + for pti = 1:numel(Pt{pi}) + if ~exist(outdir{1},'dir'), mkdir(outdir{1}); end + Pp0SEGpti = spm_file(Pt{pi}{pti},'path',outdir,'prefix',sprintf('p0SEG%s',tcase{ti})); + if ~exist(Pp0SEGpti,'file') + Vmsks(ti,pti) = Vp0; Vmsks(ti,pti).fname = Pp0SEGpti; + spm_write_vol(Vmsks(ti,pti),Yp0d); + else + Vmsks(ti,pti) = spm_vol(Pp0SEGpti); + end + + % T1 copies + if ~exist(spm_file(Pt{pi}{pti},'path',outdir,'prefix',sprintf('SEG%s',tcase{ti})),'file') + copyfile( Pt{pi}{pti} , spm_file(Pt{pi}{pti},'path',outdir,'prefix',sprintf('SEG%s',tcase{ti})) ); + end + if ~exist(spm_file(Pt{pi}{pti},'path',outdir,'prefix',sprintf('mSEG%s',tcase{ti})),'file') + copyfile( Pt{pi}{pti} , spm_file(Pt{pi}{pti},'path',outdir,'prefix',sprintf('mSEG%s',tcase{ti})) ); + end + end + else + for pti = 1:numel(Pt{pi}) + Pp0SEGpti = spm_file(Pt{pi}{pti},'path',outdir,'prefix',sprintf('p0SEG%s',tcase{ti})); + Vmsks(ti,pti) = Vp0; Vmsks(ti,pti).fname = Pp0SEGpti; + end + end + end + + + %% estimate QC + % eval(sprintf('qav2{li} = %s(''p0'',{Vmsks(:).fname},qaopt);',qafile)); + qav2{li} = cat_vol_qa('p0',{Vmsks(:).fname},struct('prefix',[qafile '_'],'version',qafile,'rerun',rerunqc)); + if ~exist('valr2','var') || numel(valr2)
  • + end + data{qri} = cell(1,numel(levels)+1); + kappa{qri} = cell(1,numel(levels)+1); + data{qri}{1} = tab.(QRP{qri})(:); + kappa{qri}{1} = repmat( ktab(:,1), numel(tab.(QRP{qri})) ./ size(ktab,1) ,1); + for li = numel(levels):-1:1 + data{qri}{li+1} = tabsegt{li}.(QRP{qri})(:); + kappa{qri}{li+1} = repmat( ktabsegt{li}(:,1), numel(tabsegt{li}.(QRP{qri})) ./ size(ktabsegt{li},1) ,1 ); + end + + + % scatterplot of the different phantoms + hold(sp32,'on'); + for di = 1:numel(data{qri}) + hs = scatter(sp32, kappa{qri}{di}, data{qri}{di} , marker(di),'filled'); + set(hs,'MarkerEdgeAlpha',0.5 - 0.2,'MarkerFaceAlpha',0.5 - 0.3, ... + 'MarkerFaceColor', dcolor(di,:),'MarkerEdgeColor', dcolor(di,:)); + end + pl=plot([0 1],[0 0]); pl.Color = [0.3 0.3 0.3]; + + % ########### add lines (maybe not for the final print) + if 1 + hold on; + tab.(QRP{qri}) = tab.(QRP{qri}) - repmat(tab.(QRP{qri})(1,:),numel(bstr),1); + pl=plot([0 10],[0 0]); pl.Color = [0.3 0.3 0.3]; + for pti = 1:numel(Pt{pi}), px = plot( ktab(:,1), tab.(QRP{qri})(:,pti) ); set(px,'Color',min([.8 .8 .8],Pcolor(pti,:)+.5) ); end + pt = plot( ktab(:,1), mean(tab.(QRP{qri}),2)); set(pt,'LineWidth',1.5,'Color',ones(1,3)*.3,'Marker','x'); + end + + % add a legend to the first plot with NCR that only have overestimation + if qri == 1 + legend(sp32,[{'brain extraction (BE)'},segmentation],'Location','Southwest','box','off'); + end + + + xlim([0.25,1]), ylim(sp32,markrange); grid(sp32); box on; + title(sp32,strrep(QRPname{qri},'_','\_')); xlabel(sp32,'Kappa'); ylabel(sp32,'mark error') + set(sp32,'ytick',markrange(1):1:markrange(2),'yticklabel',num2str((markrange(1):1:markrange(2))','%0.2f '), ... + 'xtick',0:0.25:1,'xticklabel',num2str((0:0.25:1)','%0.2f ') ); + end + + %% create the final boxplot of all phantoms + subplot('Position',[ numel(QRP) / (numel(QRP) + 3) + 0.035 , 0.17 , 0.7 / (numel(QRP) + 3) , 0.73],'replace'); + pdata = cell(1,numel(data{1})); + for qri = 1:numel(QRP), for pti = 1:numel(data{qri}), pdata{pti} = [pdata{pti}; data{qri}{pti}]; end; end + cat_plot_boxplot( pdata , struct('names',{[{'BE'},seg]},'ygrid',0,'ylim',markrange,... + 'groupcolor',dcolor,'style',4,'datasymbol','o','usescatter',1)); + ax=gca; ax.XTickLabelRotation = 0; ax.YGrid = 'on'; + set(ax,'ytick',markrange(1):1:markrange(2),'yticklabel',num2str((markrange(1):1:markrange(2))','%0.2f ')); + title('Phantoms (all measures)'); xlabel('phantom'); ylabel('mark error') + hold on, pl=plot([0 10],[0 0]); pl.Color = [0.3 0.3 0.3]; + + % create the final boxplot of all measures + subplot('Position',[ (numel(QRP) + 1) / (numel(QRP) + 3) + 0.035 , 0.17 , 0.7 / (numel(QRP) + 3) , 0.73],'replace'); + fdata = cell(1,numel(QRP)); + for qri = 1:numel(QRP), fdata{qri} = [fdata{qri}; cell2mat(data{qri}(:)) ]; end + cat_plot_boxplot( fdata , struct('names',{QRPname},'ygrid',0,'ylim',markrange,'box',1,'style',4,'datasymbol','o','usescatter',1)); + ax=gca; ax.XTickLabelRotation = 0; ax.YGrid = 'on'; + set(ax,'ytick',markrange(1):1:markrange(2),'yticklabel',num2str((markrange(1):1:markrange(2))','%0.2f ')); + title('Measures (all phantoms)'); xlabel('measure'); ylabel('mark error') + hold on, pl=plot([0 10],[0 0]); pl.Color = [0.3 0.3 0.3]; + + % RMSE plot + sp30 = subplot('Position',[ (numel(QRP) + 2) / (numel(QRP) + 3) + 0.035 , 0.17 , 0.7 / (numel(QRP) + 3) , 0.73]); + rmseval = [ rms(fdata{1}(:)) , rms(fdata{2}(:)) , rms(fdata{3}(:)) , rms(fdata{4}(:)) , rms(fdata{5}(:)) ]; + bh = bar(rmseval(1:end)); + ylim([0,markrange(2)]); xlim([.4 5.6]); xticklabels(QRPname); + h = gca; h.YGrid = 'on'; h.XTickLabelRotation = 0; + for fi = 1:numel(rmseval) + text(fi-.38, rmseval(fi) + .05, sprintf('%0.2f',rmseval(fi)),'FontSize',8,'Color',[.0 .2 .4]); + end + ax=gca; ax.XTickLabelRotation = 0; ax.YGrid = 'on'; ax.FontSize = 9.5; + set(ax,'ytick',markrange(1):0.5:markrange(2),'yticklabel',num2str((markrange(1):0.5:markrange(2))','%0.2f ')); + title(sprintf('RMSE (%0.3f)',mean(rmseval))); xlabel('measure'); ylabel('mark error'); + + + % caption + capf = 1.3; + f29.Position(4) = f29.Position(4)*capf; ax = findobj(f29.Children,'type','Axes'); + for axi=1:numel(ax), ax(axi).Position(4) = ax(axi).Position(4)/capf; ax(axi).Position(2) = (capf-1) * capf; end + annotation('textbox',[0 0 1 ((capf-1)/capf + 0.04) ],'FitBoxToText','off','LineStyle','none','String',{['\bfFig. 1 (' ... + strrep(qafile,'_','\_') '):\rm '... + 'Shown are the deviations of different quality ratings in case of simulated brain extraction (\bfBE\rm; blue circles) and ' ... + 'segmentation errors (with two levels with chnanges of a half (\bfL1\rm - yellow >) and full voxel (\bfL2\rm - red <)) ' ... + 'in relation to the Kappa rating of the modified segmentation used for quality estimation. ' ... + 'Overall the ratings are quite robust against brain-extraction errors but more susceptible for segmentation errors ' ... + 'of erosion/dilation of the WM and CSF tissue that affect the measures as well as the contrast estimation. ' ... + 'All ratings are defined as school marks (1 grade = 10 rps of the percentage system). ' ... + 'For the\it noise contrast rating\rm (\bfNCR\rm) a half mark is equal to one BWP noise levels and indicate light (motion) artifacts,' ... + 'whereas for the\it inhomogeneity contrast rating\rm (\bfICR\rm) a 1/4 grade presents a change of 20% of the BWP inhomogeneity. ' ... + 'For\it edge contrast rating\rm (\bfECR\rm) a change of 1 grade correspond to a change of 0.5 mm that is somewhat similar like ' ... + 'Gaussian smoothing of 1.4 mm). ' ... + 'The\it structural image quality rating\rm (\bfSIQR\rm) is the weighted combination of the single measures. ' ... + '']},'Fontsize',12); + + % save image + subdir = fullfile(printdir,'Fig1-overview'); + if ~exist(subdir,'dir'), mkdir(subdir); end + fname = fullfile(subdir,sprintf('%s_conclusion_%s.jpg',printname,qafile)); + print(f29, '-djpeg', '-r300', fname); + + %% + tableRMSE = [{'measure:'}, QRP; + {'RMSE-conclusion'}, num2cell(rmseval)]; + fname = fullfile(subdir,sprintf('%s_segmentationphantom_%s_conclusion.csv',printname,qafile)); + cat_io_csv(fname,tableRMSE); + + end +end +fprintf('BWPE done.\n') + +","MATLAB" +"Neurology","ChristianGaser/cat12","catQC/cat_tst_qa_iqrRMS.m",".m","23311","536","function cat_tst_qa_iqrRMS( datadir, qaversions, segment, fasttest) +% This script is about how to set up the average rating function. +% +% - Correlation between Volume/Kappa and SIQR on BWP and MRART dataset +% +% - Kappa is defined in relation to the zero-artifact case. +% +% - My original orientation was: +% Image with severe artifacts should be rated with worse than 4 what +% mostly effected the defintion of the NCR estimation. +% +% - Averaging with higher powers should reduce the impact of single good ratings. +% This is important as the average score should be useful to detect outliers +% that might cause issues in preprocessing. +% +% - In early versions of the QC we (had to) focused on NCR and res_RMS, +% while the ICR caused more problems then it was useful +% (e.g. highfield has strong bias but also better SNR) +% As the additional later measures (FEC and res_ECR) where also sensitive +% for motion artifacts lower power values become more useful. +% +% - We also have to consider that we only have two evaluation datasets and +% the BWP and MRART that both have some limiations: +% BWP: artificial with 1/3 interpolated data +% (what troubles the res_RMS measure), and is overrepresented) +% MRART: only one protocol (one resolution) +% +% - It is also possible to weight the tissue classes as WM and GM are much +% more relevant for processing and evaluation. +% +% - Different segmentations will also influence the result. +% Especially on the BWP SPM performend quite pour in some cases that +% are not fully representive for real data. +% +% - The results should therefore not be overinterpretated. +% + +cat_io_cprintf([0 0.5 0],'\n\n== Run cat_tst_qa_iqrRMS ==\n') + +%#ok<*AGROW> + +if ~exist( 'fasttest', 'var'), fasttest = 0; end +fast = {'full','fast'}; + +opt.type = '-depsc'; +opt.res = '-r300'; +opt.dpi = 90; +opt.closefig = 0; +opt.maindir = datadir; +opt.resdir = fullfile(opt.maindir,'+results','SIQRweighting'); +opt.resdirBWP = fullfile(opt.maindir,'+results', ... + sprintf('%s_%s_%s', 'BWPmain', fast{fasttest+1}, '202508' )); %f datestr(clock,'YYYYmm')) ); +opt.resdirART = fullfile(opt.maindir,'+results', ... + sprintf('%s_%s_%s', 'MR-ART', fast{fasttest+1}, '202508' )); %f datestr(clock,'YYYYmm')) ); + +% get BWP and MRART files +P.BWPfiles = [ + cat_vol_findfiles( fullfile( datadir, 'BWP'), 'BWP*.nii' ,struct('depth',0)); + cat_vol_findfiles( fullfile( datadir, 'BWPr' ), 'rBWP*.nii' ,struct('depth',0)); + cat_vol_findfiles( fullfile( datadir, 'BWPr' ), 'irBWP*.nii',struct('depth',0))]; +MRARTdir = 'ds004173-download'; +P.ARTfiles = cat_vol_findfiles( fullfile( datadir, MRARTdir) , 'sub*.nii',struct('depth',3)); + + +%% find XML files +qai = 1; mi = 1; qcsi =1; +segmentname = cat_io_strrep(segment,{'CAT','SPM'},{'','spm_'}); +BWPkappaname = cat_io_strrep(segment,{'CAT','SPM'},{'CAT12','SPM12'}); + +% Defintion of quality ratings use for averaging +% It is possible to test different combinations of the quality measures +% However, for the article we focus only on the final one that use all QMs. +if 1 % ... not working need another cell layer + QCs = { + { + {'NCR','res_RMS'}; % 2 para - old without ICR + {'NCR','ICR','res_RMS'}; % 3 para - old with ICR + {'NCR','ICR','res_RMS','res_ECR','FEC'}; + {'NCR','res_RMS','res_ECR','FEC'}; + }; + }; +elseif true + QCs = { + { + {'NCR','res_RMS','res_ECR','FEC'}; + } + }; +else + QCs = { + { + {'ICR','res_RMS','res_ECR'}; {'NCR','res_RMS','res_ECR'}; {'NCR','ICR','res_ECR'}; {'NCR','ICR','res_RMS'}; + {'ICR','res_RMS','FEC'}; {'NCR','res_RMS','FEC'}; {'NCR','ICR','FEC'}; {'NCR','ICR','res_RMS'}; + {'ICR','FEC','res_ECR'}; {'NCR','FEC','res_ECR'}; {'NCR','ICR','res_ECR'}; {'NCR','ICR','FEC'}; + {'FEC','res_RMS','res_ECR'}; {'NCR','res_RMS','res_ECR'}; {'NCR','FEC','res_ECR'}; {'NCR','FEC','res_RMS'}; + {'ICR','res_RMS','res_ECR'}; {'FEC','res_RMS','res_ECR'}; {'FEC','ICR','res_ECR'}; {'FEC','ICR','res_RMS'}; + + {'NCR','ICR','res_RMS','res_ECR'}; {'NCR','ICR','res_RMS','FEC'}; {'NCR','ICR','FEC','res_ECR'}; + {'NCR','FEC','res_RMS','res_ECR'}; {'FEC','ICR','res_RMS','res_ECR'}; + {'NCR','ICR','res_RMS','res_ECR','FEC'}; + + {'NCR','res_RMS','res_ECR','FEC'}; + } + }; +end + +bwptestset = 1; +tissue = {'CSF','GM','WM','avg'}; % use the average also the CSF is quite bad +%CM = cat_io_colormaps('set1',numel(QCs{qcsi})); CM(end,:) = [0 0 0]; +MK = '<>^vso+x'; +%corrtype = 'Spearman'; % use pearson to focus on linear relationship +corrtype = 'Pearson'; + + +%% +clear kappa X QC SIQR rkappa name rtissue; +for mi = 1:numel(segment) + %% loading QC ratings + for qai = 1:numel(qaversions) + P.BWPfilesX{mi,qai} = spm_file(P.BWPfiles,'prefix',['report' filesep qaversions{qai} '_' segmentname{mi}],'ext','xml'); + %P.ARTfilesX{mi,qai} = cat_vol_findfiles( fullfile( datadir, 'ds004173-download','derivatives', 'CAT12.9') , ... + % sprintf('%s_sub*.xml',qaversions{qai}),struct('depth',3)); + for fi = 1:numel(P.ARTfiles) % 'derivatives' filesep 'CAT12.9' filesep + P.ARTfilesX{mi,qai}{fi} = spm_file(P.ARTfiles{fi},'prefix',[qaversions{qai} '_' segmentname{mi}],'ext','xml', ... + 'path', strrep(spm_file(P.ARTfiles{fi},'path'),MRARTdir,fullfile(MRARTdir,'derivatives','CAT12.9') )); + end + + % load XML + X{1,mi,qai} = cat_io_xml(P.BWPfilesX{mi,qai}); + X{2,mi,qai} = cat_io_xml(P.ARTfilesX{mi,qai}); + end + + %% BWP kappa (search for the results from the prevous script) + %P.BWPkappamat{mi} = fullfile(opt.resdirBWP,sprintf('bwp_kappa_NIR%d_%s.mat',numel(P.BWPfilesX{mi}),BWPkappaname{mi})); + tmp = cat_vol_findfiles(fileparts(fullfile(opt.resdirBWP,'BWPmain_full_202508')), sprintf('bwp_kappa_NIR%d_%s.mat',numel(P.BWPfilesX{mi}),BWPkappaname{mi})); + if ~isempty(tmp), P.BWPkappamat{mi} = tmp{1}; else, P.BWPkappamat{mi} = ''; end + if ~exist(P.BWPkappamat{mi},'file') + error('Cannot find BWP kappa estimates. Run cat_tst_qa_bwpmaintest in cat_tst_qa_main.') + else + S = load(P.BWPkappamat{mi}); + end + kappa{1} = cell2mat(S.val(2:end-2,2:5)); + + % only BWP test dataset (see cat_tst_qa_bwpmaintest) + if bwptestset + test = ~( mod(1:numel(P.BWPfiles),8)' < 4); + P.BWPfiles(test) = []; + for qai = 1:numel(qaversions) + P.BWPfilesX{mi,qai}(test) = []; + X{1,mi,qai}(test) = []; + end + kappa{1}(test,:) = []; + end + + + %% MRART kappa + di = 2; % this is dataset two + for si = 1:numel(X{di,1,1}) + subID{di}{si} = X{di,1,1}(si).filedata.file(5:10); + BL{di}(si) = contains(X{di,1}(si).filedata.file,'standard'); + P.ARTfilesp0{mi}{si} = X{di,1,1}(si).filedata.Fp0; %, ... + % {'ds004173-download','mri'},{fullfile('ds004173-download','derivatives','CAT12.9'),''}); + end + tmp = cat_vol_findfiles(fileparts(opt.resdirART), sprintf('mrart_kappa_NIR%d_%s.mat',numel(P.ARTfilesX{mi}),BWPkappaname{mi})); + if ~isempty(tmp), P.ARTkappamat{mi} = tmp{1}; else, P.ARTkappamat{mi} = ''; end + if ~exist(P.ARTkappamat{mi},'file') + P.ARTkappamat{mi} = fullfile(opt.resdirART,sprintf('mrart_kappa_NIR%d_%s.mat',numel(P.ARTfilesX{mi}),BWPkappaname{mi})); + for si = 1:numel( P.ARTfilesp0{mi}) % only first dim! + BLsiID(si) = find( contains( subID{di} , subID{di}{si}) & BL{di} == 1); + end + + [~,val] = eva_vol_calcKappa(P.ARTfilesp0{mi} ,P.ARTfilesp0{mi}(BLsiID) ,struct('recalc',0,'realign',2,'realignres',1)); + if ~exist(opt.resdirART,'dir'), mkdir(opt.resdirART); end + save(P.ARTkappamat{mi},'val'); + kappa{2} = real(cell2mat(val(2:end-2,2:5))); + else + S = load(P.ARTkappamat{mi}); + kappa{2} = real(cell2mat(S.val(2:end-2,2:5))); + end + + + %% estimate correlations + clear rkappa rtissue + for qai = 1:numel(qaversions) + for qcsi = 1:numel(QCs) + %% + clear SIQR name rBV; + for di = 1:size(X,1) % datasets + for qi = 1:numel(QCs{qcsi}) % quality measure set + for si = 1:numel(X{di,mi,qai}) % subject + for qci = 1:numel(QCs{qcsi}{qi}) % quality measure + try + QC{di,qi}(si,qci) = X{di,mi,qai}(si).qualityratings.(QCs{qcsi}{qi}{qci}); + catch + QC{di,qi}(si,qci) = nan; + end + if qci == 1 + name{qi} = sprintf('%d %s',qi,QCs{qcsi}{qi}{qci}); + else + name{qi} = sprintf('%s+%s',name{qi},QCs{qcsi}{qi}{qci}); + end + end + end + + % estimate general SIQR measure and the correlation to Kappa + % * genSIQR .. subjectwise SIQR values ( {dataset,QMset}( subject , averagemode ) + % * gkappa .. correlation kappa-generalSIQR ( {segmentation,QCversion,dataset}(QMset,rms-potenial,tissue) + % * rkappa .. correlation kappa-SIQR ( {segmentation,QCversion,dataset}(QMset,rms-potenial,tissue) + genSIQRmod = {'median','mean','rms^2','rms^4','rms^8','rms^{16}','max'}; + genSIQR{di,qi}(:,1) = cat_stat_nanmedian( QC{di,qi} ,2); + genSIQR{di,qi}(:,2) = cat_stat_nanmean( QC{di,qi},2); + genSIQR{di,qi}(:,3) = cat_stat_nanmean( QC{di,qi}.^2 ,2).^(1/2); + genSIQR{di,qi}(:,4) = cat_stat_nanmean( QC{di,qi}.^4 ,2).^(1/4); + genSIQR{di,qi}(:,5) = cat_stat_nanmean( QC{di,qi}.^8 ,2).^(1/8); + genSIQR{di,qi}(:,6) = cat_stat_nanmean( QC{di,qi}.^16,2).^(1/16); + genSIQR{di,qi}(:,7) = max( QC{di,qi},[],2); + % estimate RMS-based SIQR measure and the correlation to Kappa + for rmsi = 1:16 + SIQR{di,qi}(:,rmsi) = cat_stat_nanmean( QC{di,qi}.^rmsi ,2).^(1/rmsi); + if bwptestset && di==1 + % to have similar values as before we use here directly the average as in cat_tst_qa_bwpmaintest + rkappa{mi,qai,di}(qi,rmsi,1:size(kappa{1},2)) = repmat( ... + corr(cat_stat_nanmean(kappa{di}(:,1:3),2), SIQR{di,qi}(:,rmsi), 'Type',corrtype) , 1, size(kappa{di},2)); + if rmsi <= size(genSIQR{di,qi},2) + gkappa{mi,qai,di}(qi,rmsi,1:size(kappa{1},2)) = repmat( ... + corr(cat_stat_nanmean(kappa{di}(:,1:3),2), genSIQR{di,qi}(:,rmsi), 'Type',corrtype), 1, size(kappa{di},2)); + end + else + for ti = 1:size(kappa{1},2) + rkappa{mi,qai,di}(qi,rmsi,ti) = corr(kappa{di}(:,ti), SIQR{di,qi}(:,rmsi), 'Type',corrtype); + if rmsi <= size(genSIQR{di,qi},2) + gkappa{mi,qai,di}(qi,rmsi,ti) = corr(kappa{di}(:,ti), genSIQR{di,qi}(:,rmsi),'Type',corrtype); + end + end + end + end + + if isfield( X{di,mi,qai}(si) , 'subjectmeasures' ) + for si = 1:numel(X{di}) % subject + if di==1 + % normalize by first scan of the BWP without distortions + rBV{di}(si,1:3) = X{di,mi,qai}(si).subjectmeasures.vol_rel_CGW - ... + X{di,mi,qai}(1).subjectmeasures.vol_rel_CGW; + else + % normalize by standard scan (without motion artifacts) + BLsi = contains( subID{di} , subID{di}{si}) & BL{di}; + + rBV{di}(si,1:3) = X{di,mi,qai}(si).subjectmeasures.vol_rel_CGW - ... + X{di,mi,qai}(BLsi).subjectmeasures.vol_rel_CGW ; + end + end + else + fprintf('ERR') + end + + % average + for ti = 1:size(rBV{di},2) + for rmsi = 1:16 + rtissue{mi,qai,di}(qi,rmsi,ti) = abs( corr(rBV{di}(:,ti), SIQR{di,qi}(:,rmsi),'Type',corrtype) ); + if rmsi <= size(genSIQR{di,qi},2) + gtissue{mi,qai,di}(qi,rmsi,ti) = abs( corr(rBV{di}(:,ti), genSIQR{di,qi}(:,rmsi),'Type',corrtype) ); + end + end + end + end + ti = size(rBV{di},2)+1; + rtissue{mi,qai,di}(:,:,ti) = cat_stat_nanmean(abs(rtissue{mi,qai,di}),3); + gtissue{mi,qai,di}(:,:,ti) = cat_stat_nanmean(abs(gtissue{mi,qai,di}),3); + end + end + end +end + + +%% +if numel(QCs{1})>1 + maindir = fullfile(datadir,'ds004173-download'); + exprating = fullfile(maindir,'derivatives','scores.tsv'); + copyfile(exprating,strrep(exprating,'.tsv','.csv')); + tsv = cat_io_csv(exprating,'','',struct('delimiter','\t')); + for ti = 2:size(tsv,1) + tid = find( contains( P.ARTfiles , tsv{ti,1}) == 1); + group(tid,1) = tsv{ti,2}; + end + + di = 2; % + + fx = figure(23); fx.Visible = 'on'; + fx.Position(3:4) = [1700 500]; + gcolor = [0 0.8 0; 0.8 0.7 0; 0.8 0 0]; + for plotcase = 1:2 + if plotcase + subpl = size(genSIQR{di,1},2); + else + subpl = size(kappa{1},2); + end + tiledlayout(2, subpl, 'TileSpacing', 'compact', 'Padding', 'compact'); + for qi = [1,numel(QCs{1})] + for ddi = 1:subpl + nexttile; + tmp = genSIQR{di,qi}(:,ddi); + if plotcase == 1 + cat_plot_boxplot( { tmp(group==1), tmp(group==2), tmp(group==3) }, ... + struct('usescatter',1,'groupcolor',gcolor,'names', ... + {{'no','light','strong'}})); + ylim([1.5 6.5]); hold on + plot([0.5 3.5],[4 4],'--','Color',[.8 0 0]) + plot([0.5 3.5],[3 3],'--','Color',[.5 .5 0]) + plot([0.5 3.5],[2 2],'--','Color',[0 .5 0]) + else + for ti = 1:3 + sch = scatter( ... + tmp(group==ti & kappa{di}(:,4)<1) , ... + kappa{di}(group==ti & kappa{di}(:,4)<1,qi),'filled' ); hold on + sch.MarkerEdgeAlpha = .5; + sch.MarkerFaceAlpha = .5; + sch.MarkerEdgeColor = gcolor(ti,:); + sch.MarkerFaceColor = gcolor(ti,:); + end + [curve1{ti}, goodness] = fit( tmp(kappa{di}(:,qi)<1) , ... + kappa{di}( kappa{di}(:,qi)<1 ,qi) ,'poly2');%,'robust','LAR'); + ph = plot(curve1{ti}); + set(ph,'Color',gcolor(ti,:)); + legend(sprintf('fit(r^2=%0.6f)',goodness.rsquare)) + end + title(genSIQRmod{ddi}); + if ddi==1, ylabel( name{end}(3:end),'Interpreter','none'); end + grid on + end + end + + % save result + if plotcase == 1 + fx.Name = sprintf('maincorrelation%d_boxplotMRART_SIQR_%s_%s',qcsi,segment{mi},qaversions{qai}); + else + fx.Name = sprintf('maincorrelation%d_kappaMRART_SIQR_%s_%s',qcsi,segment{mi},qaversions{qai}); + end + if ~exist(opt.resdir,'dir'), mkdir(opt.resdir); end + print(fx, '-djpeg', '-r300', fullfile(opt.resdir,fx.Name)); + end +end + + + +%% create a average variable over all segments and QC versions +qaisel = 1:numel(qaversions); +clear tgtissue tgkappa +for di = 1:size(X,1) + tgtissue{di} = gtissue{mi,qai,di}*0; + tgkappa{di} = gkappa{mi,qai,di}*0; + for mi = 1:numel(segment) + for qai = qaisel + %qaversions{qai} + tgtissue{di} = tgtissue{di} + gtissue{mi,qai,di}(end,:,:) / (numel(segment) * numel(qaisel)); + tgkappa{di} = tgkappa{di} + gkappa{mi,qai,di}(end,:,:) / (numel(segment) * numel(qaisel)); + end + end +end + +% main table +% BWP and MRART volume values for each class +C1 = num2cell( abs([ shiftdim(tgtissue{1}(1,:,:),1) , shiftdim(tgtissue{2}(1,:,:),1)] )); +cell2table( C1 , 'RowNames',genSIQRmod,'VariableNames',[strcat('BWP-',tissue),strcat('MRART-',tissue)] ); +% BWP and MRART kappa values for each class +C2 = num2cell( abs([ shiftdim(tgkappa{1}(1,:,:),1) , shiftdim(tgkappa{2}(1,:,:),1)] )); +cell2table( C2 , 'RowNames',genSIQRmod,'VariableNames',[strcat('BWP-',tissue),strcat('MRART-',tissue)]); +% BWP and MRART volume and kappa values (average tissues values) +C3 = num2cell( abs([ ... + shiftdim(tgtissue{1}(1,:,4),1) , shiftdim(tgtissue{2}(1,:,4),1) ... + shiftdim(tgkappa{1}(1,:,4),1) , shiftdim(tgkappa{2}(1,:,4),1) ... + mean( abs( [shiftdim(tgtissue{1}(1,:,4),1) , shiftdim(tgtissue{2}(1,:,4),1), ... + shiftdim(tgkappa{1}(1,:,4),1) , shiftdim(tgkappa{2}(1,:,4),1) ] ),2) ] )); +C4 = num2cell( abs([ ... + gtissue{mi,qai,1}(end,:,4)', gtissue{mi,qai,2}(end,:,4)', ... + gkappa{mi,qai,1}(end,:,4)', gkappa{mi,qai,2}(end,:,4)', ... + mean( abs( [gtissue{mi,qai,1}(end,:,4)', gtissue{mi,qai,2}(end,:,4)', ... + gkappa{mi,qai,1}(end,:,4)', gkappa{mi,qai,2}(end,:,4)' ] ) , 2)])); +CH = [strcat('Vol-BWP-',tissue(4)), strcat('Vol-MRART-',tissue(4)), ... + strcat('Kappa-BWP-',tissue(4)), strcat('Kappa-MRART-',tissue(4)) ,'avg']; +T = cell2table( C3 ,'RowNames',genSIQRmod,'VariableNames', CH); + +% save result +if ~exist(opt.resdir,'dir'), mkdir(opt.resdir); end +fname = fullfile(opt.resdir,... + sprintf('table_correlation_avgQRs_%0.0fsegmentations_%0.0fQAversion', ... + numel(segment), numel(qaversions))); +cat_io_csv(fname, [{corrtype} CH; genSIQRmod' C3]); +fname = fullfile(opt.resdir,... + sprintf('table_correlation_SIQR_%0.0fsegmentations_%0.0fQAversion', ... + numel(segment), numel(qaversions))); +T = cell2table( C4 ,'RowNames',genSIQRmod,'VariableNames', CH) +cat_io_csv(fname, [{corrtype} CH; genSIQRmod' C4]); +%% +for mi = 1:numel(segment) + for qai = 1:numel(qaversions) + for qcsi = 1:numel(QCs) + CM = cat_io_colormaps('set1',numel(QCs{qcsi})); CM(end,:) = [0 0 0]; + + + %% table + C1 = num2cell( abs([ shiftdim(gtissue{mi,1}(1,:,:),1) , shiftdim(gtissue{mi,2}(1,:,:),1)] )); + cell2table( C1 , 'RowNames',genSIQRmod,'VariableNames',[strcat('BWP-',tissue),strcat('MRART-',tissue)] ); + + C2 = num2cell( abs([ shiftdim(gkappa{mi,1}(1,:,:),1) , shiftdim(gkappa{mi,2}(1,:,:),1)] )); + cell2table( C2 , 'RowNames',genSIQRmod,'VariableNames',[strcat('BWP-',tissue),strcat('MRART-',tissue)]) + + C3 = num2cell( abs([ ... + shiftdim(gtissue{mi,1}(1,:,4),1) , shiftdim(gtissue{mi,2}(1,:,4),1) ... + shiftdim(gkappa{mi,1}(1,:,4),1) , shiftdim(gkappa{mi,2}(1,:,4),1) ... + mean( abs( [shiftdim(gtissue{mi,1}(1,:,4),1) , shiftdim(gtissue{mi,2}(1,:,4),1), ... + shiftdim(gkappa{mi,1}(1,:,4),1) , shiftdim(gkappa{mi,2}(1,:,4),1) ] ),2) ] )); + cell2table( C3 , 'RowNames',genSIQRmod,'VariableNames', ... + [strcat('Vol-BWP-',tissue(4)), strcat('Vol-MRART-',tissue(4)), strcat('Kappa-BWP-',tissue(4)), strcat('Kappa-MRART-',tissue(4)) ,'avg']) + + + %% correlation between tissue volume reduction and SIQR measures + + if 0 + for di = 1:4 + fx = figure(di+1); clf(di+1); fx.Position(3:4) = [1200 400]; + + switch di + case 1, fx.Name = sprintf('correlation%d-Volume-SIQR_BWP_%s_%s' ,qcsi,segment{mi},qaversions{qai}); + case 2, fx.Name = sprintf('correlation%d-Volume-SIQR_MRART_%s_%s',qcsi,segment{mi},qaversions{qai}); + case 3, fx.Name = sprintf('correlation%d-Kappa-SIQR_BWP_%s_%s' ,qcsi,segment{mi},qaversions{qai}); + case 4, fx.Name = sprintf('correlation%d-Kappa-SIQR_MRART_%s_%s' ,qcsi,segment{mi},qaversions{qai}); + end + + % create subfigures for the tissues as well as the average + tiledlayout(1, 4, 'TileSpacing', 'compact', 'Padding', 'compact'); + for ti = 1:4 % 3 tissue + avg + nexttile; + + % select figure + if di>=3 + p = plot(abs(rkappa{mi,di-2}(:,:,ti)')); + title(sprintf('corr(%sKappa,SIQR)',tissue{ti}),'Interpreter','none') + ylabel([tissue{ti} ' Kappa']); + else + p = plot(abs(rtissue{mi,qai,di}(:,:,ti)')); + title(sprintf('corr(%sV,SIQR)', tissue{ti}),'Interpreter','none') + ylabel([corrtype ' correlation']); + end + + % format lines + for pi=1:numel(p), p(pi).Color = CM(pi,:); p(pi).LineWidth = 1.5; p(pi).Marker = MK( 1+mod(pi,numel(MK))); end + + % label + subtitle(sprintf('%s - %s',qaversions{qai}, segment{mi}),'Interpreter','none'); + xlabel('power used for SIQR') + if ti == 4, legend(name,'Interpreter','none','Location','SouthEast'); end + ax=gca; ax.XTick = [1 2 4 8 16]; grid on + switch qcsi + case 1 + switch di + %case {1}, ylim([.4 .8]); + %case {2}, ylim([.4 .8]); + %case {3}, ylim([.5 1]); + case {4}, ylim([.82 .9]); + end + otherwise + switch di + case {1}, ylim([.4 .9]); + %case {2}, ylim([.4 .95]); + case {3}, ylim([.6 1]); + case {4}, ylim([.75 .92]); + end + end + end + + % save result + if ~exist(opt.resdir,'dir'), mkdir(opt.resdir); end + print(fx, '-djpeg', '-r300', fullfile(opt.resdir,fx.Name)); + end + end + + + %% total figure only with averages + tisnam = {'CSF','GM','WM','avg'}; + for ti = 1:4 + fy = figure(6); clf(6); fy.Position(3:4) = [1200 350]; + fy.Name = sprintf('maincorrelation%d-SIQR_%s_%s_%s',... + qcsi,segment{mi},tisnam{ti},qaversions{qai}); + tiledlayout(1, 5, 'TileSpacing', 'compact', 'Padding', 'compact'); + dataset = {'BWP','MRART','BWP','MRART'}; + for di = 1:5 + nexttile; hold on + + % select figure + if di >= 5 + p = plot( (abs(rkappa{mi,1}(:,:,ti)') + abs(rkappa{mi,2}(:,:,ti)') + ... + abs(rtissue{mi,qai,1}(:,:,ti)') + abs(rtissue{mi,qai,2}(:,:,ti)') ) / 4); + title(sprintf('corr(%sKappa+dV%s,SIQR) BWP+MRART',tissue{ti},tissue{ti}),'Interpreter','none') + ylabel([tissue{ti} ' Kappa']); + elseif di >= 3 + p = plot(abs(rkappa{mi,di-2}(:,:,ti)')); + title(sprintf('corr(%sKappa,SIQR) %s',tissue{ti}, dataset{di}),'Interpreter','none') + ylabel([tissue{ti} ' Kappa']); + else + p = plot(abs(rtissue{mi,qai,di}(:,:,ti)')); + title(sprintf('corr(dV%s,SIQR) %s', tissue{ti}, dataset{di}),'Interpreter','none') + ylabel([corrtype ' correlation']); + end + + % format lines + for pi=1:numel(p), p(pi).Color = CM(1+mod(pi-1,size(CM,1)),:); p(pi).LineWidth = 1.5; p(pi).Marker = MK( 1+mod(pi,numel(MK) )); end + + % label + subtitle(sprintf('%s - %s',qaversions{qai}, segment{mi}),'Interpreter','none'); + xlabel('power used for SIQR') + if di==5, legend(name,'Interpreter','none','Location','SouthWest'); end + ax=gca; ax.XTick = [1 2 4 8 16]; grid on; box on; + if 1 + ylim(ax,[0 1]) + else + switch qcsi + case 1 + switch di + case {1 2}, ylim(ax,[.40 1]); + case {3 4}, ylim(ax,[.40 1]); + end + otherwise + switch di + case {1 2}, ylim(ax,[.45 .80]); + case {3 4}, ylim(ax,[.75 1]); + end + end + end + end + % save result + if ~exist(opt.resdir,'dir'), mkdir(opt.resdir); end + print(fy, '-djpeg', '-r300', fullfile(opt.resdir,fy.Name)); + end + end + end +end +","MATLAB" +"Neurology","ChristianGaser/cat12","catQC/cat_tst_qa_ATLAS.m",".m","11043","308","function cat_tst_qa_ATLAS( datadir0, qaversions, segment, fasttest ) +%% Evaluation of CATQC in ATLAS +% ------------------------------------------------------------------------ +% QC evaluation of the ATLAS lesion dataset for original and lesion-masked +% images. In the ideal case the measures are somewhat similar and the QC +% measures are not or less affected by the tissue changes in lesions. +% +% Requirements: +% 0. Download and install SPM and CAT +% 1. Download ATLAS T1 data from: +% +% 2. Specify in this script: +% 1) the data directory ""datadir"" +% 2) the QC version you would like to tests (the file has to exist in the cat directory) +% 3) the segmentation you would like to use +% +% ------------------------------------------------------------------------ + +cat_io_cprintf([0 0.5 0],'\n\n== Run cat_tst_qa_ATLAS ==\n') + +% ### datadir ### +if ~exist( 'datadir0' , 'var' ) + datadir = '/Volumes/SG5TB/MRData/202503_QA/ATLAS_R1.1'; +else + datadir = fullfile(datadir0,'ATLAS'); +end + +% ### QC version ### +if ~exist( 'qaversions' , 'var') + qaversions = { + ...'cat_vol_qa201901'; % classic version (quite stable since 2016) + 'cat_vol_qa201901x'; % refined, debugged version of 201901 + ...'cat_vol_qa202110'; % second classic version (successor of 201901) + ...'cat_vol_qa202110x'; % refined, debugged version of 202110 + ...'cat_vol_qa202205'; % last regular version before update (successor of 202110, stopped) + ...'cat_vol_qa202310'; % redesigned version based on 201901 and 202110 * default * + ...'cat_vol_qa202412'; % experimental version with internal segmentation >> qcseg + }; +end + +% ### segmention ### +if ~exist( 'segment' , 'var') + segment = {'CAT'}; % {'SPM','CAT','qcseg'}; % qcseg requires cat_vol_qa2024012 +end + +if ~exist( 'fasttest', 'var'), fasttest = 0; end +fast = {'full','fast'}; + +resdir = fullfile(fileparts(datadir), '+results', ['ATLAS_' fast{fasttest+1} '_' datestr(clock,'YYYYmm')]); +if ~exist(resdir,'dir'), mkdir(resdir); end + +% directories +runPP = 1; +rerun = 1; + +% prepare data +% - gunzip +% - imcalc + + +if runPP + for si = 1:numel(segment) + clear matlabbatch; + ATLASfiles = cat_vol_findfiles( datadir , 'ATLAS*.nii',struct('depth',3)); + switch segment{si} + case 'CAT' + CATpreprocessing4qc; + matlabbatch{1}.spm.tools.cat.estwrite.data = ATLASfiles; + matlabbatch{1}.spm.tools.cat.estwrite.extopts.admin.lazy = 1; + spm_jobman('run',matlabbatch); + case 'SPM' + SPMpreprocessing4qc; + matlabbatch{1}.spm.spatial.preproc.channel.vols = ATLASfiles; + spm_jobman('run',matlabbatch); + case 'synthseg' + error('synthseg is not prepared in the public script ... use MATLAB help') + case 'qcseg' + fprintf('No preprocessing required.\n\n'); + end + end +end + + + +% +qais = 1:numel(qaversions); +% (re)process QC values +datadira = fullfile(datadir,'ATLASR1.1a'); % msk +datadirb = fullfile(datadir,'ATLASR1.1b'); % org +switch segment{si} + case 'CAT' + Pp0b = cat_vol_findfiles( datadirb , 'p0ATLAS*.nii',struct('depth',3)); %spm_fileparts(datadir) + case 'SPM' + Pp0b = cat_vol_findfiles( datadirb , 'c1ATLAS*.nii',struct('depth',2)); %spm_fileparts(datadir) + case 'synthseg' + case 'qcseg' + Pp0b = cat_vol_findfiles( datadirb , 'p0_qcseg_ATLAS*.nii',struct('depth',2)); %spm_fileparts(datadir) +end +Pp0a = cat_io_strrep(Pp0b,{'ATLASR1.1b';'ATLASorg'},{'ATLASR1.1a';'ATLASmsk'}); %cat_vol_findfiles( datadira , 'p0*'); %spm_fileparts(datadir) +if fasttest % 5 ~> 50 scans + Pp0a = Pp0a(1:12:end); + Pp0b = Pp0b(1:12:end); +end +Pp0 = [Pp0a, Pp0b]; Pp0 = Pp0'; Pp0 = Pp0(:); % [msk, org] +for qai = qais + switch segment{si} + case 'CAT', qcv = [qaversions{qai} '_']; + case 'SPM', qcv = [qaversions{qai} '_spm_']; + case 'qcseg', qcv = [qaversions{qai} '_qcseg_']; Pp0 = cat_io_strrep(Pp0,[filesep 'mri' filesep 'p0'],filesep); + end + cat_vol_qa('p0',Pp0,struct('prefix',qcv,'version',qaversions{ qai },'rerun',rerun)); +end +verb = 'on'; + +% +clear NCR ICR IQR ECR SIQR rGMV +for qai = qais + + %% find xml files + switch segment{si} + case 'CAT' + Pxml{1} = spm_file(cat_io_strrep(Pp0a,['mri' filesep 'p0'],['report' filesep]), ... + 'prefix',sprintf('%s_',qaversions{ qai }),'ext','.xml'); + Pxml{2} = cat_io_strrep(Pxml{1},{'ATLASR1.1a';'ATLASmsk'},{'ATLASR1.1b';'ATLASorg'}); + case 'SPM' + Pxml{1} = spm_file(cat_io_strrep(Pp0a,['c1'],['report' filesep]), ... + 'prefix',sprintf('%s_spm_',qaversions{ qai }),'ext','.xml'); + Pxml{2} = cat_io_strrep(Pxml{1},{'ATLASR1.1a';'ATLASmsk'},{'ATLASR1.1b';'ATLASorg'}); + case 'qcseg' + Pxml{1} = spm_file(cat_io_strrep(Pp0a,['p0_'],['report' filesep]), ... + 'prefix',sprintf('%s_',qaversions{ qai }),'ext','.xml'); + Pxml{2} = cat_io_strrep(Pxml{1},{'ATLASR1.1a';'ATLASmsk'},{'ATLASR1.1b';'ATLASorg'}); + end + for xsi = numel(Pxml{1}):-1:1 + if ~exist(Pxml{1}{xsi},'file') || ~exist(Pxml{2}{xsi},'file') + Pxml{1}(xsi) = []; + Pxml{2}(xsi) = []; + end + end + + % load xml data + xml = cell(1,2); for i=1:numel(Pxml), xml{i} = cat_io_xml(Pxml{i}); end + + % extract measure + for i=1:numel(Pxml) + for si = 1:numel(xml{i}) + try + fname{si,i} = xml{i}(si).filedata.file; + TIV(si,i) = xml{i}(si).subjectratings.vol_TIV; + NCR(si,i) = xml{i}(si).qualityratings.NCR; + ICR(si,i) = xml{i}(si).qualityratings.ICR; + if isfield(xml{i}(si).qualityratings,'FEC') + FEC(si,i) = xml{i}(si).qualityratings.FEC; + else + FEC(si,i) = nan; + end + ECR(si,i) = xml{i}(si).qualityratings.res_ECR; + IQR(si,i) = xml{i}(si).qualityratings.IQR; + SIQR(si,i) = xml{i}(si).qualityratings.SIQR; + rGMV(si,i) = xml{i}(si).subjectmeasures.vol_rel_CGW(2); + + % get ID of the XML entry + seps = find( fname{si} == '_' ); + siten{si,i} = fname{si}(seps(1)+2:seps(1)+5); + end + end + end + dIQR = diff(IQR,1,2); % msk - org + rmse = @(x) mean(x.^2).^.5; + + % store for later + QAVdiff{qai} = dIQR; + if 0 + + %numel(Pp0b( abs(QAVdiff{qai}) > .5 )) / numel(Pp0b); + %% + ss = find(abs(QAVdiff{qai}) > 1); + %% ss = ss(11); + switch segment{si} + case 'CAT', qcv = [qaversions{qai} '_']; + case 'qcseg', qcv = [qaversions{qai} '_qcseg_']; + end + cat_vol_qa('p0',Pp0a( ss ) ,struct('prefix',qcv,'version',qaversions{ qai },'rerun',1)); + cat_vol_qa('p0',Pp0b( ss ) ,struct('prefix',qcv,'version',qaversions{ qai },'rerun',1)); + end + + + %% create figure + if 1 + for sm = 0:1 + if ~exist('fh','var') || ~isvalid(fh), fh = figure(39); end + if ~fasttest, fh.Visible = verb; end + if sm, fh.Position(3:4) = [200 160]; else, fh.Position(3:4) = [300 250]; end + ss = 0.05 * (sm + 1); clf(fh); + try + hst = histogram(dIQR,round(-max(abs(dIQR))/ss)*ss - ss/2:ss:round(max(abs(dIQR))/ss)*ss); + catch + hst = histogram(dIQR); + end + ylabel('number'); grid on; + if sm + title('masked vs. original'); smstr = '_sm'; + xlabel(sprintf('SIQR (RMSE=%0.3f)', rmse(dIQR) )); hold on; + else + title('SIQR difference between masked and original images'); smstr = ''; + xlabel(sprintf('SIQR difference (RMSE=%0.4f) %s', rmse(dIQR), strrep(qaversions{qai},'_','\_') )); hold on; + %ph = plot([0 0],ylim); ph.Color = [0 0 0.5]; ph.LineStyle = '--'; ph.LineWidth = 1; + end + + xlim([-3 3]); %xlim([-1 1] * ceil(max(abs(dIQR)))); + ylim([ 0 1] * ceil( max(hst.Values)*1.1 / 10)*10); + + % print figure + print(fh,fullfile(resdir ,sprintf('ATLAS_%s%s',qaversions{qai},smstr)),'-r600','-djpeg'); + end + end + + %% create figure + for sm = 0:1 + if ~exist('fh','var'), fh = figure(39); end + if ~fasttest, fh.Visible = verb; end + if sm, fh.Position(3:4) = [160 160]; else, fh.Position(3:4) = [150 250]; end + clf(fh); + if sm + title('masked vs. original'); smstr = '_sm'; + xlabel(sprintf('SIQR (RMSE=%0.3f)', rmse(dIQR) )); hold on; + else + title('SIQR difference between masked and original images'); smstr = ''; + xlabel(sprintf('SIQR difference (RMSE=%0.4f) %s', rmse(dIQR), strrep(qaversions{qai},'_','\_') )); hold on; + %ph = plot([0 0],ylim); ph.Color = [0 0 0.5]; ph.LineStyle = '--'; ph.LineWidth = 1; + end + cat_plot_boxplot( QAVdiff(qai) , struct('names',{{sprintf('SIQR (RMSE=%0.3f)', rmse(dIQR) )}},'usescatter',1,... + 'style',4,'datasymbol','o','ylim', [-3 3],'ygrid',0 )); %[-.1 .1] * ceil(max(abs( QAVdiff{qai} ))) ) ); + title('masked vs. original'); set(gca,'YGrid',1); + + % print figure + print(fh,fullfile(resdir ,sprintf('ATLAS_boxplot_%s%s',qaversions{qai},smstr)),'-r600','-djpeg'); + end +end + + + + +%% final figure +fh = figure(38); fh.Position(3:4) = [150 300]; +cat_plot_boxplot( QAVdiff , struct('names',{qaversions},'style',4,... + 'usescatter',1,'datasymbol','o','ylim',[-3 3],'ygrid',0) ); +title('SIQR difference between masked and original images'); +xlabel('QA versions'); ylabel('SIQR difference'); +ax = gca; ax.FontSize = 10; ax.YGrid = 1; hold on; +%ph = plot([0.4 numel(QAVdiff)+.6],[0 0]); ph.Color = [0 0 0.5]; ph.LineStyle = '--'; ph.LineWidth = 1; +ylim([-3 3]); + +% print figure +print(fh,fullfile(resdir ,sprintf('ATLAS_boxplot_all')),'-r600','-djpeg'); + + + +%% estimate size of leason +Po = spm_file(cat_io_strrep(Pp0a,['mri' filesep 'p0'],'')); +for pi = 1:numel(Pp0a) + Plesmat{pi} = spm_file(Pp0a{pi},'prefix','lesionvol_','ext','.mat'); + if exist(Plesmat{pi},'file') + load(Plesmat{pi},'Vles'); + else + try + V = spm_vol(Pp0a{pi}); + catch + V = spm_vol(Po{pi}); + end + Y = spm_read_vols(V); + TIVvx = sum(Y(:) > 0); + + V = spm_vol(Po{pi}); + Y = spm_read_vols(V); + Y = smooth3( Y ) > .5; + + Vles = sum(Y(:)==0) ./ TIVvx; + save(Plesmat{pi},'Vles'); + end + Vlesion(pi) = Vles; +end + + +% +fh = figure(37); clf; hold on +fh.Position(3:4) = [300 200]; +cmap = cat_io_colormaps('nejm',numel(qais)); +marker = {'o' 's' 'd' 'v' '^' '>' '<' 'p' 'h' }; +for qai = qais + hs = scatter( Vlesion , QAVdiff{qai} ); hold on; + hs.MarkerEdgeColor = cmap(qai,:); hs.MarkerFaceColor = hs.MarkerEdgeColor; + hs.MarkerFaceAlpha = .2; hs.MarkerEdgeAlpha = .2; hs.SizeData = 20; hs.Marker = marker{qai}; +end +ylim([-3,3]); +for qai = qais + lesfit{qai} = fit( Vlesion(~isinf(Vlesion))' , QAVdiff{qai}(~isinf(Vlesion)) ,'poly1'); hp = plot(lesfit{qai}); hp.Color = cmap(qai,:); %#ok<*SAGROW> +end +if numel(qaversions)>1, legend(strrep(qaversions,'_','\_')); else, legend off; end +set(gca,'XTick',0:10); +grid on; box on; +ylabel('SIQR error (masked - raw)'); +xlabel('lesion volume in % of the TIV'); +title('ATLAS SQIR difference by lesion volume'); + +% print figure +print(fh,fullfile(resdir ,sprintf('ATLAS_scatterplot_lesionsize')),'-r1200','-djpeg'); +","MATLAB" +"Neurology","ChristianGaser/cat12","catQC/cat_tst_qa_IXI.m",".m","40562","825","function cat_tst_qa_IXI( datadir0 , qaversions , segment, fasttest, rerun, dataset ) +%% Evaluation of CATQC in IXI +% ------------------------------------------------------------------------ +% +% Requirements: +% 1. Matlab with curve fitting toolbox (fit) +% 2. Download and install SPM and CAT +% 3. Download IXI T1 data from: +% https://brain-development.org/ixi-dataset/ +% http://biomedic.doc.ic.ac.uk/brain-development/downloads/IXI/IXI-T1.tar +% +% 4. Specify in this script: +% 1) the data directory ""datadir"" +% 2) the QC version you would like to tests (the file has to exist in the cat directory) +% 3) the segmentation you would like to use +% +% See also cat_tst_qa_main. +% ------------------------------------------------------------------------ + + cat_io_cprintf([0 0.5 0],'\n\n== Run cat_tst_qa_IXI ==\n') + if ~exist('dataset','var'), dataset = 'IXI'; end + + if license('test', 'Curve_Fitting_Toolbox') + error('This function requires the ""Curve Fitting Toolbox"" of MATLAB.\n') + end + + % ### datadir ### + if ~exist( 'datadir0' , 'var' ) + switch dataset + case 'IXI', datadir = '/Volumes/SG5TB/MRData/202503_QA/IXI'; + case 'ADHD200', datadir = '/Volumes/WDE18TB/MRDataPP/202503_QA/ADHD200'; + case 'ABIDE', datadir = '/Volumes/WDE18TB/MRDataPP/202105_QA/private/Site O - ABIDE'; + case 'NKIrs', datadir = '/Volumes/WDE18TB/MRDataPP/202105_QA/private/Site G - NKI'; + case 'NKI', datadir = '/Volumes/WDE18TB/MRDataPP/202105_QA/NKI'; + case 'ADHD200NYC', datadir = '/Volumes/WDE18TB/MRDataPP/202105_QA/private/Site H - ADHD_NYC'; + case 'ADHD200ORE', datadir = '/Volumes/WDE18TB/MRDataPP/202105_QA/private/Site H - ADHD_ORE'; + case 'ds000256', datadir = '/Volumes/SG5TB/MRData/202503_QA/ds000256'; + end + else + switch dataset + case 'IXI', datadir = fullfile(datadir0,'IXI-T1'); + case 'ADHD200', datadir = fullfile(datadir0,'ADHD200'); + case 'ABIDE', datadir = '/Volumes/WDE18TB/MRDataPP/202105_QA/private/Site O - ABIDE'; + case 'NKIrs', datadir = '/Volumes/WDE18TB/MRDataPP/202105_QA/private/Site G - NKI'; + case 'NKI', datadir = '/Volumes/WDE18TB/MRDataPP/202105_QA/NKI'; + case 'ADHD200NYC', datadir = '/Volumes/WDE18TB/MRDataPP/202105_QA/private/Site H - ADHD_NYC'; + case 'ADHD200ORE', datadir = '/Volumes/WDE18TB/MRDataPP/202105_QA/private/Site I - ADHD_ORE'; + case 'ds000256', datadir = fullfile(datadir0,'ds000256-ChildrenHeadMotionN24'); + end + end + + % ### QC version ### + if ~exist( 'qaversions' , 'var') + qaversions = { + ...'cat_vol_qa201901'; % classic version (quite stable since 2016) + 'cat_vol_qa201901x'; % refined, debugged version of 201901 + ...'cat_vol_qa202110'; % second classic version (successor of 201901) + ...'cat_vol_qa202110x'; % refined, debugged version of 202110 + ...'cat_vol_qa202205'; % last regular version before update (successor of 202110, stopped) + ...'cat_vol_qa202310'; % redesigned version based on 201901 and 202110 * default * + ...'cat_vol_qa202412'; % experimental version with internal segmentation >> qcseg + }; + end + + % ### segmention ### + if ~exist( 'segment' , 'var') + segment = {'CAT'}; % {'SPM','CAT','qcseg'}; % qcseg requires cat_vol_qa2024012 + end + + if ~exist( 'fasttest', 'var'), fasttest = 0; end + if ~exist( 'rerun', 'var'), rerun = 0; end + fast = {'full','fast'}; + + runPP = 0; % run CAT/SPM preprocessing + useratings = 1; + printall = 1; + + resdir = fullfile(fileparts(datadir), '+results',[dataset '_' fast{fasttest+1} '_202508']); %' datestr(clock,'YYYYmm')]); + if ~exist(resdir,'dir'), mkdir(resdir); end + + qias = 1:numel(qaversions); + + if runPP + for si = 1:numel(segment) + clear matlabbatch; + switch dataset + case 'IXI', IXIfiles = cat_vol_findfiles( datadir , 'IXI*.nii',struct('depth',0)); + case 'ADHD200', IXIfiles = [ + cat_vol_findfiles( fullfile( datadir , 'train_raw'), '*.nii.gz',struct('depth',1)); + ...cat_vol_findfiles( fullfile( datadir , 'test_raw'), '*.nii.gz',struct('depth',1)); + ]; + case 'ABIDE', IXIfiles = cat_vol_findfiles( datadir , 'anat.nii',struct('depth',5)); + case 'NKI', IXIfiles = cat_vol_findfiles( datadir , 'NKI*.nii',struct('depth',0)); + case {'ADHD200NYC','ADHD200ORE'} + IXIfiles = cat_vol_findfiles( datadir , 'ADHD*.nii',struct('depth',0)); + case 'ds000256', IXIfiles = cat_vol_findfiles( datadir , 'sub*T1w.nii.gz',struct('depth',3)); + end + switch segment{si} + case 'CAT' + CATpreprocessing4qc; + IXIfilesCAT = IXIfiles; + switch dataset + case {'IXI'} + IXIfilesCAT( cellfun(@(x) exist(x,'file'),... + spm_file(IXIfilesCAT,'prefix',['mri' filesep 'p0']))>0 ) = []; + case {'ABIDE','ADHD200NYC','ADHD200ORE','NKI','NKIrs'} + IXIfilesCAT( cellfun(@(x) exist(x,'file'),... + spm_file(IXIfilesCAT,'prefix',['mri' filesep 'p0']))>0 ) = []; + case 'ds000256' + matlabbatch{1}.spm.tools.cat.estwrite.output.BIDS.BIDSyes.BIDSdir = ... + fullfile('..','derivatives','CAT12.9_2874'); + IXIfilesCAT2 = strrep( IXIfilesCAT , datadir , fullfile( datadir, 'derivatives','CAT12.9_2874') ); + IXIfilesCAT( cellfun(@(x) exist(x,'file'), ... + spm_file(IXIfilesCAT2, 'prefix','p0','ext','') )>0 ) = []; % remove gz + end + if ~isempty( IXIfilesCAT ) + matlabbatch{1}.spm.tools.cat.estwrite.data = IXIfilesCAT; + matlabbatch{1}.spm.tools.cat.estwrite.extopts.admin.lazy = 1; + spm_jobman('run',matlabbatch); + end + case 'SPM' + switch dataset + case 'IXI' + SPMpreprocessing4qc; + IXIfilesSPM = IXIfiles; + IXIfilesSPM( cellfun(@(x) exist(x,'file'),spm_file(IXIfilesSPM,'prefix','c1'))>0 ) = []; + if ~isempty( IXIfilesSPM ) + matlabbatch{1}.spm.spatial.preproc.channel.vols = IXIfilesSPM; + spm_jobman('run',matlabbatch); + end + otherwise + error('%s is not prepared',dataset); + end + case 'synthseg' + error('synthseg is not prepared in the public script ... use MATLAB help') + case 'qcseg' + fprintf('No preprocessing required.\n\n'); + end + end + end + + + + + %% (re)process QC values + fprintf('Prepare %s: \n',dataset) + for si = 1:numel(segment) + for qai = qias + switch segment{si} + case 'CAT' + switch dataset + case {'IXI','ADHD200NYC','ADHD200ORE','NKI','NKIrs'} + Pp0{si}{qai} = cat_vol_findfiles( fullfile( datadir , 'mri') , 'p0*',struct('depth',0)); + case 'ADHD200' + Pp0{si}{qai} = cat_vol_findfiles( datadir , 'p0*',struct('depth',3)); + case 'ABIDE' + Pp0{si}{qai} = cat_vol_findfiles( datadir , 'p0anat.nii',struct('depth',6)); + case 'ds000256' + Pp0{si}{qai} = cat_vol_findfiles( datadir , 'p0*T1w.nii',struct('depth',5)); + end + case 'SPM' + Pp0{si}{qai} = cat_vol_findfiles( datadir , 'c1*',struct('depth',0)); + case 'synthseg' + Pp0{si}{qai} = cat_vol_findfiles( datadir , 'synthseg_p0*',struct('depth',0)); + case 'qcseg' + Pp0{si}{qai} = cat_vol_findfiles( datadir , 'IXI*.nii',struct('depth',0)); + end + fasttestss = 10; + if fasttest, Pp0{si}{qai} = Pp0{si}{qai}(1:fasttestss:end); end + end + end + fprintf('Prepare %s done. \n',dataset) + + %% + fprintf('Process %s: \n',dataset) + for si = 1:numel(segment) + for qai = qias + switch segment{si} + case 'CAT' + cat_vol_qa('p0',Pp0{si}{qai},struct('prefix',[qaversions{qai} '_'],'version',qaversions{ qai },'rerun',rerun)); + case 'SPM' + cat_vol_qa('p0',Pp0{si}{qai},struct('prefix',[qaversions{qai} '_spm_'],'version',qaversions{ qai },'rerun',rerun)); + case 'synthseg' + cat_vol_qa('p0',Pp0{si}{qai},struct('prefix',[qaversions{qai} '_synthseg_'],'version',qaversions{ qai },'rerun',rerun)); + case 'qcseg' + cat_vol_qa('p0',Pp0{si}{qai},struct('prefix',[qaversions{qai} '_qcseg_'],'version',qaversions{ qai },'rerun',rerun)); + end + end + end + fprintf('Process %s done. \n',dataset) + %% + fprintf('Print %s: \n',dataset) + switch dataset + case 'IXI' + Pcsv = fullfile( fileparts(datadir) , 'IXI_2019main.csv' ); + csv = cat_io_csv(Pcsv,'','',struct('delimiter',';','csv','.')); + case 'ABIDE1' + Pcsv = fullfile( datadir , '+META', 'Phenotypic_V1_0b.csv'); + csv = cat_io_csv(Pcsv,'','',struct('delimiter',',','csv','.')); + csv(end,:) = []; + case 'ABIDE' + Pcsv = fullfile( datadir , '+META', 'ABIDEII_Composite_Phenotypic2.csv' ); + csv = cat_io_csv(Pcsv,'','',struct('delimiter',',','csv','.')); + csv(end,:) = []; + case 'ADHD200' + Pcsv = fullfile( datadir , 'phenotypic', 'tables', 'ADHD200c.csv' ); + csv = cat_io_csv(Pcsv,'','',struct('delimiter',',','csv','.')); + case 'ds000256' + Pcsv = fullfile( datadir , 'participantsQC.tsv' ); + csv = cat_io_csv(Pcsv,'','',struct('delimiter','\t','csv','.')); + case 'NKI' + Pcsv = fullfile( datadir , 'participants.tsv' ); + csv = cat_io_csv(Pcsv,'','',struct('delimiter','\t','csv','.')); + case {'ADHD200NYC','ADHD200ORE','NKIrs'} + clear csv; + Pcsv = spm_file(cat_io_strrep(Pp0{1}{1},fullfile('mri','p0'),'vbmdb_'),'ext','.csv'); + for csvi = 1:numel(Pcsv) + csvtmp = cat_io_csv(Pcsv{csvi},'','',struct('delimiter',',','csv','.')); + if ~isempty(csvtmp) + if ~exist('csv','var'), csv = csvtmp; else, csv = [csv; csvtmp(2,:)]; end + else + if ~exist('csv','var'), csv = csvtmp; else, csv = [csv; repmat({''},1,size(csv,2))]; end + end + end + end + + %% create figure + fh = figure(39); + fh.Visible = 'off'; + fh.Interruptible = 'off'; + fh.Position(3:4) = [600,200]; + for si = 1:numel(segment) + for qai = qias + fprintf(' Print %s with %s: \n',qaversions{qai},segment{si}) + + % find and load QC XML files + if exist('Pp0','var') % old + clear Pxml; + for pi = 1:numel(Pp0{si}{qai}) + [pp,ff] = fileparts(Pp0{si}{qai}{pi}); + switch segment{si} + case 'CAT' + Pxml{pi,1} = fullfile(strrep(pp,[filesep 'mri'],[filesep 'report']),[qaversions{qai} '_' ff(3:end) '.xml']); + case 'SPM' + Pxml{pi,1} = fullfile(pp,'report',[qaversions{qai} '_spm_' ff(3:end) '.xml']); + case 'synthseg' + Pxml{pi,1} = fullfile(pp,'report',strrep([qaversions{qai} ff '.xml'],'synthseg_p0','_synthseg_')); + case 'qcseg' + Pxml{pi,1} = fullfile(pp,'report',[qaversions{qai} '_qcseg_' ff '.xml']); + end + end + else + Pxml = cat_vol_findfiles( fullfile( datadir , 'report') , sprintf('%s_IXI*.xml',qaversions{qai}) ); + if fasttest && numel(Pxml)>numel(Pp0{si}{qai}), Pxml = Pxml(1:fasttestss:end); end + end + xml = cat_io_xml(Pxml); + + % read out CAT XML QC value and get age values + clear siten; + if printall + measures = {'NCR','ICR','ECR','SIQR','FEC','CON','IQR','TIV','rGMV','rWMV','rCSFV'}; + scaling = {[.5 6.5],[.5 6.5],[.5 6.5],[.5 6.5],[.5 6.5],[.5 6.5],[.5 6.5],[900 2100],[.2 .6],[.2 .6],[.2 .6]}; + else + measures = {'SIQR','rGMV'}; + scaling = {[.5 6.5],[.2 .6]}; + end + + clear NCR IQR ICR SIQR ECR ECRmm FEC CON TIV rGMV ID csvID age sex qc dx; ni = -1; + for xi = 1:numel(xml) + % + try + CON(xi) = xml(xi).qualityratings.contrastr; + TIV(xi) = xml(xi).subjectmeasures.vol_TIV; + rGMV(xi) = xml(xi).subjectmeasures.vol_rel_CGW(2); + catch + CON(xi) = nan; + NCR(xi) = nan; + ICR(xi) = nan; + IQR(xi) = nan; + FEC(xi) = nan; + SIQR(xi) = nan; + TIV(xi) = nan; + rGMV(xi) = nan; + res_RMS(xi) = nan; + siten{xi} = ''; + age(xi) = 0; + sex(xi) = 0; + continue + end + NCR(xi) = xml(xi).qualityratings.NCR; + ICR(xi) = xml(xi).qualityratings.ICR; + IQR(xi) = xml(xi).qualityratings.IQR; + res_RMS(xi) = xml(xi).qualityratings.res_RMS; + try + FEC(xi) = xml(xi).qualityratings.FEC; + catch + FEC(xi) = nan; + end + SIQR(xi) = xml(xi).qualityratings.SIQR; + if isfield(xml(xi).qualityratings,'res_ECR') + ECR(xi) = xml(xi).qualityratings.res_ECR; + end + if isfield(xml(xi).qualityratings,'res_ECRmm') + ECRmm(xi) = xml(xi).qualityratings.res_ECRmm; + end + % get ID of the XML entry + + + % get age of the subject with the ID + fname{xi} = xml(xi).filedata.file; %#ok<*SAGROW> + siten{xi} = ''; + try + switch dataset + case 'IXI' + seps = find( fname{xi} == '-' ); + ID(xi) = str2double( fname{xi}(4:6)); + csvID(xi) = find( cell2mat(csv(2:end,1)) == ID(xi) , 1 , 'first' ) + 1; % not all exist + age(xi) = csv{ csvID(xi) , end }; + sex(xi) = csv{ csvID(xi) , 2 }==1; + siten{xi} = fname{xi}(seps(1)+1:seps(2)-1); + case 'ABIDE1' + ID{xi} = spm_file( fileparts( fileparts( fileparts(xml(xi).filedata.fname) )) , 'basename'); + csvID(xi) = find( contains( cellstr(num2str( ([csv{2:end,2}])')), ID{xi})==1 , 1 , 'first' ) + 1; %([csv{2:end,2}])' + age(xi) = csv{ csvID(xi) , 5 }; + sex(xi) = csv{ csvID(xi) , 6 }==1; + siten{xi} = csv{ csvID(xi) , 1 } ; + case 'ABIDE' % ABIDE2 + ID{xi} = spm_file( fileparts( fileparts( fileparts(xml(xi).filedata.fname) )) , 'basename'); + csvID(xi) = find( contains( cellstr(num2str( ([csv{2:end,2}])')), ID{xi})==1 , 1 , 'first' ) + 1; %([csv{2:end,2}])' + age(xi) = csv{ csvID(xi) , 7 }; + sex(xi) = csv{ csvID(xi) , 8 }==1; + siten{xi} = csv{ csvID(xi) , 1 } ; + case 'ADHD200' + ID{xi} = spm_file( spm_file( xml(xi).filedata.fname, 'basename'),'ext',''); + csvID(xi) = find( cat_io_contains( cellfun(@num2str,csv(2:end,1),'UniformOutput',false) , ... + num2str(str2double(ID{xi})) ) ==1 , 1 , 'first' ) + 1; + if ~isempty(csvID(xi)) + age(xi) = csv{ csvID(xi) , 4 }; + sex(xi) = csv{ csvID(xi) , 3 }==1; + siten{xi} = num2str(csv{ csvID(xi) , 2 }); + end + dx(xi) = isempty(csv{ csvID(xi) , 6 }) | (csv{ csvID(xi), 6 }>0); + if isnumeric(csv{ csvID(xi) , 22 }) + qc(xi) = csv{ csvID(xi) , 22 }; + else + qc(xi) = csv{ csvID(xi) , 18 }; + end + case 'NKI' + ID{xi} = cat_io_strrep(fname{xi},{'_T1w','.nii','.gz','sub-'},{'','','',''}); + csvID(xi) = find( cat_io_contains( csv(2:end,1), ID{xi}(1:9)) ==1 , 1 , 'first' ) + 1; + age(xi) = csv{ csvID(xi) , 2 }; + sex(xi) = strcmp( csv{ csvID(xi) , 3 }, 'MALE'); + case {'ADHD200NYC','ADHD200ORE','NKIrs'} + ID{xi} = cat_io_strrep(fname{xi},{'_T1w','.nii','.gz'},{'','',''}); + csvID(xi) = find( cat_io_contains( spm_file(csv(2:end,1),'path','','ext',''), ID(xi)) , 1 , 'first' ) + 1; + age(xi) = csv{ csvID(xi) , 6 }; + sex(xi) = csv{ csvID(xi) , 11 }=='M'; + case 'ds000256' + ID{xi} = cat_io_strrep(fname{xi},{'_T1w','.nii','.gz'},{'','',''}); + csvID(xi) = find( contains( csv(2:end,1), ID{xi} )==1, 1 , 'first' ) + 1; + age(xi) = csv{ csvID(xi) , 2 }; + sex(xi) = csv{ csvID(xi) , 3 }=='M'; + qc(xi) = csv{ csvID(xi) , 5 }; + end + catch + csvID(xi) = ni; + ni = ni - 1; + age(xi) = 0; + sex(xi) = 0; + siten{xi} = 'XXX'; + end + end + + % remove posible disease cases + if exist('dx','var') + dx = dx | age<=0 | contains(siten{xi},'XXX'); + else + dx = age<=0; + end + + for mii = 1:numel(measures) + if exist(measures{mii},'var') + eval(sprintf('%s(dx) = [];',measures{mii})); + end + end + res_RMS(dx) = []; + csvID( dx ) = []; + age( dx ) = []; + sex( dx ) = []; + siten( dx ) = []; + fname( dx ) = []; + xml( dx ) = []; + if exist('qc','var') + qc( dx ) = []; + end + %Pxml + dx( dx ) = []; + + % ignore cases without age + age(age<=0) = 0; + for mii=1:numel(measures) + if exist(measures{mii},'var') + eval(sprintf('%s(%s<=0) = nan;',measures{mii},measures{mii})); + end + end + + [siteu,~,site] = unique(siten); + % remove undefined sites + siteu(cellfun(@isempty,siteu)) = []; + siteu(contains(siteu,'XXX')) = []; + + + if useratings + mark2rps = @(mark) min(100,max(0,105 - mark*10)); + ratings = {'NCR','IQR','ICR','SIQR','ECR','FEC','CON','res_RMS'}; + for ri = 1:numel(ratings) + if exist(ratings{ri},'var') + eval(sprintf('%s = mark2rps(%s);',ratings{ri},ratings{ri})); + end + end + lgpos = 'South'; + else + lgpos = 'North'; + end + + %% basic overview over dataset + datasettable = cell(10,numel(siteu)+1); + datasettable(1:5,1:2) = ... + {'Datset:', dataset; + 'N:' , numel(age); + 'Sites' , numel(siteu); + 'Age:' , sprintf('%0.2f%s%0.2f',cat_stat_nanmean(age),char(177),cat_stat_nanstd(age)); + 'Males:' , sum(sex==1)/numel(sex)}; + + datasettable(7:7+3,1) = {'Site:';'N:';'Age';'Males'}; + for sii = 1:numel(siteu) + datasettable{7,sii+1} = sprintf('%d) %s',sii,siteu{sii}); + datasettable{8,sii+1} = sum(site==sii); + datasettable{9,sii+1} = sprintf('%0.2f%s%0.2f',cat_stat_nanmean(age(site==sii)),char(177),cat_stat_nanstd(age(site==sii))); + datasettable{10,sii+1} = sum(sex(site==sii)==1) / sum(site==sii); + for ri = 1:numel(ratings) + if exist(ratings{ri},'var') + datasettable{10+ri*2-1,1} = sprintf('mean(%s):',ratings{ri}); + eval(sprintf(' datasettable{10+ri*2-1,sii+1} = cat_stat_nanmean(%s(site==sii));',ratings{ri})); + datasettable{10+ri*2,1} = sprintf('std(%s):',ratings{ri}); + eval(sprintf(' datasettable{10+ri*2,sii+1} = cat_stat_nanstd(%s(site==sii));',ratings{ri})); + end + end + end + pfname = fullfile(resdir,sprintf('%s_dataset.csv',dataset)); + cat_io_csv(pfname,datasettable); + cat_io_cprintf('blue',' Print %s\n',pfname); + + +%% + usenormmain = numel(siteu)>1; + for usenorm = 0:usenormmain + for ri = find(contains(measures,ratings)) + if usenorm + scaling{ri} = [-15 45]; + else + scaling{ri} = [40 100]; + end + end + + if usenorm>0 + switch dataset + case {'ABIDE', 'ADHD200', 'IXI'} + for sdi = 1:numel(siteu) + M = contains(siten,siteu{sdi}); + if sum(M)>0 + for fni=1:numel(ratings) + if ~strcmp( ratings{fni} , 'res_RMS') + eval(sprintf(['%s(M) = -cat_tst_qa_normer( %s(M), ' ... + 'struct(''figure'',0,''sites'',res_RMS(M),''siterf'',%0.0f,''cmodel'',1,''model'',0));'], ... + ratings{fni}, ratings{fni}, 10 + 100*contains('ABIDE',dataset) )); + end + end + end + end + otherwise + usenorm = 0; + end + end + + % + avar = {'age','TIV'}; % analysis variables (x-axis) + avart = {'in years; '; 'in ml; '}; + switch dataset + case 'IXI' + avars = {[20 90];[900 1900]}; + acols = [[0.0 0.4 0]; [0.2 0.6 0.2]; [0.4 .8 0.4];]; % aging + gcols = {[0.5 0 0]; [0 0 0.5 ]; [.5 .5 0]}; % group + scols = [[0.0 0.4 0.8]; [1 0.5 0.0]; [0.8 .0 0.1];]; + otherwise + avars = ... + {[floor(min(age(age>0 & age0 & age0 & TIV0 & TIVF'}; + tables.siteanova = {'measure','F','Prob>F'}; + tables.tivanova = {'measure','F','Prob>F'}; + tables.sexanova = {'measure','F','Prob>F'}; + tables.sexmwwt = {'measure','p','Z','U'}; + tables.sidestd = {'measure','std(site1)','std(site2)','std(site3)'}; + %% + for mi = 1:numel(measures) + if usenorm && any( contains({'rGMV','rWMV','rCSFV','res_RMS'},measures{mi}) ) + continue; + end + + if exist(measures{mi},'var') && eval(sprintf('any(~isnan(%s))',measures{mi})) + for ai = 1:numel(avar) + + if ~strcmp( avar{ai} , measures{mi} ) + %% first subfigure with scatter plot of all values colored by density + clf + marker = {'o' 's' 'd' 'v' '^' '>' '<' 'p' 'h' }; + subplot('position',[0.08 0.16 .25 .75]); + hold on; + switch dataset + case 'IXI' + eval(sprintf('scatter( %s(site==1)'' , %s(site==1)'' ,20, ''o'')', avar{ai},measures{mi})); + eval(sprintf('scatter( %s(site==2)'' , %s(site==2)'' ,20, ''^'')', avar{ai},measures{mi})); + eval(sprintf('scatter( %s(site==3)'' , %s(site==3)'' ,20, ''v'')', avar{ai},measures{mi})); + case {'ADHD200','ABIDE'} + for sitei = 1:numel(siteu) + %% + evalc( sprintf('sch = scatter( %s(site==%d & ~isnan(%s''))'' , %s(site==%d & ~isnan(%s''))'' ,20, ''o'')', ... + avar{ai}, sitei, avar{ai}, measures{mi}, sitei, avar{ai}) ); + sch.Marker = marker{mod(sitei,numel(marker)-1)+1}; + end + otherwise + if exist('qc','var') + eval(sprintf('scatter( %s(qc==0)'' , %s(qc==0)'' ,20, ''o'')', avar{ai},measures{mi})); + eval(sprintf('scatter( %s(qc==1)'' , %s(qc==1)'' ,20, ''s'')', avar{ai},measures{mi})); + eval(sprintf('scatter( %s(qc==2)'' , %s(qc==2)'' ,20, ''s'')', avar{ai},measures{mi})); + else + eval(sprintf('scatter( %s'' , %s'' ,20, ''o'')', avar{ai},measures{mi})); + end + end + ax = gca; + switch dataset + case {'ADHD200','ABIDE'} + ax.Position = [0.08 0.16 .27 .75]; + otherwise + ax.Position = [0.08 0.16 .40 .75]; + end + ax.FontSize = 10; + if usenorm + ax.YDir = 'reverse'; + end + % + hsd = findobj( get(ax,'Children') ,'Type','Scatter'); + for hsdi = 1:numel(hsd) + switch dataset + case 'ds000256' + scols = [0 0.8 0; 0.8 0.7 0; 0.8 0 0]; + hsd(hsdi).MarkerEdgeColor = scols(hsdi,:); + otherwise + hsd(hsdi).MarkerEdgeColor = scols(numel(hsd) + 1 - hsdi,:); + end + hsd(hsdi).MarkerFaceColor = hsd(hsdi).MarkerEdgeColor; + hsd(hsdi).MarkerFaceAlpha = 0.2; + hsd(hsdi).MarkerEdgeAlpha = 0.4; + end + box on; + title(sprintf('%s density in aging (%s, N=%d)',dataset,measures{mi},numel(NCR))); + myylim = scaling{mi}; % round( ax.YLim .* [0.9 1.1] * 4 ) / 4 ; + xlim(avars{ai}); + % fitting biased by outiers ... this is pearson ... + switch dataset + case 'IXI' + eval(sprintf('[R1,P1] = corrcoef( %s(site==1) , %s(site==1));',avar{ai},measures{mi})); + eval(sprintf('[R2,P2] = corrcoef( %s(site==2) , %s(site==2));',avar{ai},measures{mi})); + eval(sprintf('[R3,P3] = corrcoef( %s(site==3) , %s(site==3));',avar{ai},measures{mi})); + eval(sprintf('[R4,P4] = corrcoef( %s , %s);',avar{ai},measures{mi})); + P = cat_stat_nanmean([P1(2),P2(2),P3(2)]); + R = cat_stat_nanmean([R1(2),R2(2),R3(2)]); + otherwise + eval(sprintf('[R,P] = corrcoef( %s , %s);',avar{ai},measures{mi})); + end + warning off; + if mi==1 && ai==1 % licence call + try + eval(sprintf('[curve1, goodness, output] = fit( %s(site==1)'', double(%s(site==1))'',''poly1'');', ... + avar{ai}, measures{mi})); cplot(1) = plot(curve1); cplot(1).Color = gcols{1}; + end + pause(1); + end + warning on + + + % correlation + warning off; + switch dataset + case 'IXI' + %% + eval(sprintf('[curve1, goodness, output] = fit( %s(site(:)==1 & ~isnan(%s(:)))'', double(%s(site(:)==1 & ~isnan(%s(:))))'',''poly1'');', ... + avar{ai}, measures{mi}, measures{mi}, measures{mi})); cplot(1) = plot(curve1); cplot(1).Color = scols(1,:); + eval(sprintf('[curve2, goodness, output] = fit( %s(site(:)==2 & ~isnan(%s(:)))'', double(%s(site(:)==2 & ~isnan(%s(:))))'',''poly1'');', ... + avar{ai}, measures{mi}, measures{mi}, measures{mi})); cplot(2) = plot(curve2); cplot(2).Color = scols(2,:); + eval(sprintf('[curve3, goodness, output] = fit( %s(site(:)==3 & ~isnan(%s(:)))'', double(%s(site(:)==3 & ~isnan(%s(:))))'',''poly1'');', ... + avar{ai}, measures{mi}, measures{mi}, measures{mi})); cplot(3) = plot(curve3); cplot(3).Color = scols(3,:); + eval(sprintf('[curve4, goodness, output] = fit( %s(~isnan(%s(:)))'', double(%s(~isnan(%s(:))))'',''poly1'');', ... + avar{ai}, measures{mi}, measures{mi}, measures{mi})); cplot(4) = plot(curve4); cplot(4).Color = [ 0.2 0.2 0.2 ]; cplot(4).LineStyle = '--'; + pan = cat_stat_nanmean([curve1.p1, curve2.p1, curve3.p1]); + otherwise + pan = 0; + for sii = 1:numel(siteu) + try + eval(sprintf('[curves(sii), goodness, output] = fit( %s(site(:)==sii & ~isnan(%s(:)))'', double(%s(site(:)==sii & ~isnan(%s(:))))'',''poly1'');', ... + avar{ai}, measures{mi}, measures{mi}, measures{mi})); cplot(sii) = plot(curves(sii)); cplot(sii).Color = scols(sii,:); + pan = pan + curves(sii).p1; + catch + + end + end + end + legend off; + warning on; + + % anova + try + tab = cell2table([num2cell(age'),num2cell(site),num2cell(TIV')],'Variablenames',{'age','site','TIV'},'rownames',cellstr(num2str(csvID','IXI%03d'))); + eval(sprintf('[an0] = anova(tab,%s'');',measures{mi})); + cat_io_csv(fullfile(resdir,'anovas',sprintf('IXI_anova_%s-age-site_%s_%s.csv', measures{mi}, qaversions{qai}, segment{si})),... + [{''} an0.stats.Properties.VariableNames; an0.stats.Properties.RowNames table2cell(an0.stats)]); + end + + + % man-wikney + switch dataset + case 'IXI' + tables.sidestd = [ tables.sidestd ; + [ measures(mi) , num2cell( eval(sprintf('[std(%s(site==1)),std(%s(site==2)),std(%s(site==3))];',measures{mi},measures{mi},measures{mi})))] ]; + if ai == 1 + tables.agecorr = [ tables.agecorr ; + [ measures(mi) num2cell( [R1(2),R2(2),R3(2),R4(2),R, P1(2),P2(2),P3(2),P4(2),P, curve1.p1,curve2.p1,curve3.p1,curve4.p1,pan ]) ] ]; + else + tables.tivcorr = [ tables.tivcorr ; + [ measures(mi) num2cell( [R1(2),R2(2),R3(2),R4(2),R, P1(2),P2(2),P3(2),P4(2),P, curve1.p1,curve2.p1,curve3.p1,curve3.p1,pan ]) ] ]; + end + otherwise + end + ylim( myylim ); xlim(avars{ai}); + set(gca,'Ygrid',1) + if useratings && any(contains(measures{mi},ratings)) && ~usenorm + set(gca,'Ytick',scaling{mi}(1)+5 : 10 : scaling{mi}(2)); + end + if strcmp(measures{mi},'rGMV'), set(gca,'YTickLabel',num2str(get(gca,'YTick')','%0.2f') ); end + if isnan( R(min(numel(R),2)) ) + xlabel(sprintf('%s (%s)',avar{ai}, avart{ai})); + else + xlabel(sprintf('%s (%s b=%0.3f, \\it{r}\\rm{}=%0.3f, \\it{p}\\rm{}=%0.03f)',avar{ai}, avart{ai}, pan, R(min(numel(R),2)), P(min(numel(P),2)))); + end + ylabel(measures{mi}); grid on; hold on; + switch dataset + case 'IXI' + legend({ + sprintf('Guys (b=%0.3f, \\it{r}\\rm{}=%0.3f, \\it{p}\\rm{}=%0.3f)',curve1.p1, R1(2), P1(2) ), ... + sprintf('HH (b=%0.3f, \\it{r}\\rm{}=%0.3f, \\it{p}\\rm{}=%0.3f)' ,curve2.p1, R2(2), P2(2)) , ... + sprintf('IOP (b=%0.3f, \\it{r}\\rm{}=%0.3f, \\it{p}\\rm{}=%0.3f)' ,curve3.p1, R3(2), P3(2)) , ... + },'Location',lgpos) + otherwise + end + if usenorm, ylabel(['N' get(get(gca,'Ylabel'),'String')]); end + + + % second figure with poxplot of age groups + switch dataset + case {'ABIDE','ADHD200'} + subplot('position',[0.425 0.16 .16 .75]); + otherwise + subplot('position',[0.575 0.16 .16 .75]); + end + if ai == 1 + switch dataset + case 'IXI' + eval(sprintf('[an0,anova1age{mi}] = anova1(%s,1 +(age>40) + (age>60),''off'');',measures{mi})); + bxtxt = '{ %s(age<40); %s(age>40 & age<60); %s(age>60) }'; + bxnames = {'20-40','40-60','60-90'}; + otherwise + km = cat_stat_kmeans(age(age>prctile(age,10) & age0)), mean(km(1:2)), mean(km(2:3)), max(age)]); + bxtxt = sprintf('{ %%s(age<%0.2f); %%s(age>%0.2f & age<%0.2f); %%s(age>%0.2f) }',km2(2),km(2:3),km(3)); + eval(sprintf('[an0,anova1age{mi}] = anova1(%s,1 +(age>%d) + (age>%d),''off'');',measures{mi},km(2:3))); + bxnames = {sprintf('<%d',km2(2)),sprintf('%d-%d',km2(2:3)),sprintf('>%d',km2(3))}; + end + tables.ageanova = [ tables.siteanova; [ measures(mi) anova1age{mi}(2,4) anova1age{mi}(2,5) ] ]; + cat_plot_boxplot( eval(sprintf(bxtxt,... + measures{mi},measures{mi},measures{mi})) , ... + struct('names',{bxnames},'style',4,'ylim',myylim,'ygrid',0, ... + 'datasymbol','o','usescatter',1,'groupcolor',acols) ); + title('age groups'); + xlabel('range (years)'); ylabel(measures{mi}); + else + if max(age)>60 + eval(sprintf('[an0,anova1tiv{mi}] = anova1(%s,1 +(age>1300) + (age>1500),''off'');',measures{mi})); + bxtxt = '{ %s(TIV<1300); %s(TIV>1300 & TIV<1500); %s(TIV>1500) }'; + bxnames = {'<1.3','~1.4','>1.5'}; + else + km = cat_stat_kmeans(TIV(TIV>prctile(TIV,10) & TIV0),5), mean(km(1:2)), mean(km(2:3)), prctile(TIV,95)]/100)*100; + bxtxt = sprintf('{ %%s(TIV<%0.1f); %%s(TIV>%0.1f & TIV<%0.1f); %%s(TIV>%0.1f) }',km2(2),km(2:3),km(3)); + eval(sprintf('[an0,anova1tiv{mi}] = anova1(%s,1 +(TIV>%d) + (TIV>%d),''off'');',measures{mi},km(2:3))); + bxnames = {sprintf('<%0.1f',km2(2)/1000),sprintf('%0.1f-%0.1f',km2(2:3)/1000),sprintf('>%0.1f',km2(3)/1000)}; + end + tables.tivanova = [ tables.siteanova; [ measures(mi) anova1tiv{mi}(2,4) anova1tiv{mi}(2,5) ] ]; + cat_plot_boxplot( eval(sprintf(bxtxt,... + measures{mi},measures{mi},measures{mi})) , ... + struct('names',{bxnames},'style',4,'ylim',myylim,'ygrid',0, ... + 'datasymbol','o','usescatter',1,'groupcolor',acols) ); + title('TIV groups'); + xlabel('TIV (liter)'); ylabel(measures{mi}); + end + ax = gca; ax.FontSize = 10; hold on; + ylim( myylim ); hold off; set(gca,'Ygrid',1,'YTickLabelRotation',0,'XTickLabelRotation',0); + if strcmp(measures{mi},'rGMV'), set(gca,'YTickLabel',num2str(get(gca,'YTick')','%0.2f') ); end + if useratings && any(contains(measures{mi},ratings)) + set(gca,'Ytick',scaling{mi}(1)+5 : 10 : scaling{mi}(2)) + end + if usenorm, set(gca,'YDir','reverse'); ylabel(['N' get(get(gca,'Ylabel'),'String')]); end + + % second figure with poxplot of centers + switch dataset + case {'ABIDE','ADHD200'} + subplot('position',[0.66 0.16 .32 .75]); + otherwise + subplot('position',[0.83 0.16 .16 .75]); + end + if ai == 1 + eval(sprintf('[an0,anova1site{mi}] = anova1(%s,site,''off'');',measures{mi})); + tables.siteanova = [ tables.siteanova; [ measures(mi) anova1site{mi}(2,4)' anova1site{mi}(2,5)' ] ]; + switch dataset + case 'IXI' + cat_plot_boxplot( eval(sprintf('{ %s(site==1) ; %s(site==2); %s(site==3) }',... + measures{mi},measures{mi},measures{mi})) , ... + struct('names',{{'Guys','HH','IOP'}},'style',4,'ylim',myylim ,'ygrid',0, ... siteu + 'datasymbol','o','usescatter',1,'groupcolor',scols) ); + otherwise + if numel(siteu)>0 + sitestr = ''; sitenam = {}; + for sxi=1:numel(siteu) + sitestr = [sitestr sprintf('%s(site==%d);',measures{mi},sxi)]; %#ok<*AGROW> + sitenam = [sitenam siteu(sxi)]; + end + cat_plot_boxplot( eval( sprintf('{ %s}',sitestr)) , ... + struct('style',4,'ylim',myylim ,'ygrid',0,'names',{siteu}, ... + 'datasymbol','o','usescatter',1,'groupcolor',scols) ); + else + cat_plot_boxplot( eval(sprintf('{ %s(qc==0) ; %s(qc==1); %s(qc==2) }',... + measures{mi},measures{mi},measures{mi})) , ... + struct('names',{{'no MA','lMA','sMA'}},'style',4,'ylim',myylim ,'ygrid',0, ... siteu + 'datasymbol','o','usescatter',1,'groupcolor',scols) ); + end + end + title('scan sites'); + xlabel('center'); ylabel(measures{mi}); + else + if ~exist('mwwtest','file') + warning('Miss mwwtest function (https://github.com/dnafinder/mwwtest/blob/master/mwwtest.m) use anova1.') + eval(sprintf('[an0,anova1sex{mi}] = anova1(%s,sex,''off'');',measures{mi})); + tables.sexanova = [ tables.sexanova; [ measures(mi) anova1sex{mi}(2,5:6) ] ]; + else + % https://github.com/dnafinder/mwwtest/blob/master/mwwtest.m + txt = evalc( sprintf('mwwt = mwwtest( %s(sex==0 & ~isnan(%s)) , %s(sex==1 & ~isnan(%s)) );',... + measures{mi}, measures{mi}, measures{mi}, measures{mi} )); + if isfield(mwwt,'Z') + tables.sexmwwt = [ tables.sexmwwt; [ measures(mi) mwwt.p(2) mean(mwwt.U) mwwt.Z] ]; + else + tables.sexmwwt = [ tables.sexmwwt; [ measures(mi) mwwt.p(2) mean(mwwt.U) nan] ]; + end + end + cat_plot_boxplot( eval(sprintf('{ %s(sex==0) ; %s(sex==1); }',... + measures{mi},measures{mi})) , ... + struct('names',{{'female','male'}},'style',4,'ylim',myylim ,'ygrid',0, ... siteu + 'datasymbol','o','usescatter',1) ); + title('sex'); + xlabel('sex'); ylabel(measures{mi}); + end + if usenorm, set(gca,'YDir','reverse'); ylabel(['N' get(get(gca,'Ylabel'),'String')]); end + ax = gca; ax.FontSize = 10; hold on; + if 0 %strcmp(measures{mi},'IQR') || strcmp(measures{mi},'SIQR') + ph = plot([0 20],[1.9 1.9]); ph.Color = [1 0 0 ]; ph.LineStyle = '--'; ph.LineWidth = 1.5; + end + ylim( myylim ); + + if useratings && any(contains(measures{mi},ratings)) + set(gca,'Ytick',scaling{mi}(1)+5 : 10 : scaling{mi}(2)) + end + set(gca,'Ygrid',1,'XTickLabelRotation',0); + if strcmp(measures{mi},'rGMV'), set(gca,'YTickLabel',num2str(get(gca,'YTick')','%0.2f') ); end + + + % print figure + pdir = fullfile(resdir,sprintf('%s',measures{mi})); + if ~exist(pdir,'dir'), mkdir(pdir); end + pfname = fullfile(pdir,sprintf('%s_%s_%s_%s_%s_norm%d.jpg',dataset,avar{ai}, measures{mi}, qaversions{qai}, segment{si}, usenorm)); + print(fh,pfname,'-r1200','-djpeg'); + cat_io_cprintf('blue',' Print %s\n',pfname); + end + end + end + end + end + + % print final table + tf = fieldnames(tables); + for tfi = 1:numel(tf) + pfname = fullfile(resdir,sprintf('%s_%s_%s_%s.csv', dataset, tf{tfi}, qaversions{qai}, segment{si})); + cat_io_csv(pfname,tables.(tf{tfi})); + cat_io_cprintf('blue',' Save %s\n',pfname); + end + end + end + fprintf('Print %s done. \n',dataset) +","MATLAB" +"Neurology","ChristianGaser/cat12","catQC/cat_tst_qa_resampleBWP.m",".m","2013","66","function cat_tst_qa_resampleBWP(maindir) +%% BWP resolutions +% This function resizes and renames the BWP files to obtain some +% additional resolution versions for further tests (especially of the +% image resolution). +% + +P = cellstr( cat_vol_findfiles( fullfile( maindir , 'BWP'), 'BWP*.nii', struct('depth',-1))); + +% resolutions setings +res = [ + 1 1 2; + 1 2 1; + 2 1 1; + ... 1 2 2; + ... 2 1 2; + ... 2 2 1; + 2 2 2; + ]; +if 0 + % add further values + res = [ + 1 1 1.5; + 1 1.5 1; + ... 1 1.5 1.5; + 1.5 1 1; + ... 1.5 1 1.5; + ... 1.5 1.5 1; + 1.5 1.5 1.5; + ]; +end + +% run resampling +for ri = 1:size(res,1) + for pi = 1:numel(P) + + % be lazy + resdir = fullfile( spm_fileparts(spm_fileparts(P{pi})) ,'BWPr'); + rfile = strrep( spm_file(P{pi},'path',resdir,'prefix','r') ,'_vx100x100x100',sprintf('_vx%dx%dx%d',round(res(ri,:)*100))); + irfile = strrep( spm_file(P{pi},'path',resdir,'prefix','ir') ,'_vx100x100x100',sprintf('_vx%dx%dx%d',round(res(ri,:)*100))); + if exist( rfile , 'file' ) && exist( irfile , 'file' ), continue; end + + % Downsampling using the batch functionality of the cat_vol_resize function + clear job; + job.data = P(pi); + job.restype.res = res(ri,:); + job.interp = -2005; % different interpolation approaches (2005: smooth+spline) + job.prefix = 'r'; + job.outdir = {resdir}; + job.verb = 1; + job.lazy = 0; + Prx = cat_vol_resize(job); + + % change name + movefile(Prx.res{1}, strrep(Prx.res{1},'_vx100x100x100',sprintf('_vx%dx%dx%d',round(res(ri,:)*100))) ); + + % Upsampling using the batch functionality of the cat_vol_resize function + job.data = {strrep(Prx.res{1},'_vx100x100x100',sprintf('_vx%dx%dx%d',round(res(ri,:)*100)))}; + job = rmfield(job,'restype'); + job.restype.Pref = P(pi); + job.interp = -5; % spline + job.prefix = 'i'; + cat_vol_resize(job); + + end +end","MATLAB" +"Neurology","ChristianGaser/cat12","catQC/cat_tst_qa_main.m",".m","11611","219","% QA main script to run the various analysis in (Dahnke et al., 2025) +% +% Dahnke R., Kalc P., Ziegler G., Grosskreutz J., Gaser C. +% The Good, the Bad, and the Ugly: Segmentation-Based Quality Control +% of Structural Magnetic Resonance Images +% https://www.biorxiv.org/content/10.1101/2025.02.28.640096v1 +% +% ------------------------------------------------------------------------- +% The package comes with data from the brain web phantom (BWP) that were +% created as customized simulations (Cocosco et al., 1997, Collins et al., +% 1998, AubertBroche et al., 2006). +% The data were converted to NIFTI and organized via the shell script: +% +% ./BWPgt/convertCollinsR2.sh +% +% to rename the files in the following structure: +% +% BWPC_HC_T1_pn[1:2:9]_rf[20:20:100]p[A,B,C]_vx100x100x100.nii +% +% with 5 noise level (pn), 5 inhomogeneity levels (rf) and 3 fields (ABC). +% +% The dataset also includes the segmentation of CAT and SPM to run the tests. +% Using different segmentation (versions) is expected to result in (slightly) +% different results. +% +% Requirements / steps: +% 1. MATLAB (or OCTAVE) +% MATLAB is recommended as OCTAVE does not support full functionality. +% Although SPM and CAT do not require additional toolboxes, these +% scripts use the ""Statistics and Machine Learning Toolbox"" +% +% 2. Download and install SPM and CAT from: +% SPM: https://www.fil.ion.ucl.ac.uk/spm/software/download/ +% CAT: https://neuro-jena.github.io/cat/index.html#DOWNLOAD +% +% The latest code is available from the SPM and CAT GITHUB sites: +% SPM: https://github.com/spm +% CAT: https://github.com/ChristianGaser/cat12 +% +% 3. Download and unpack IXI, ATLAS, Rusak, and MR-ART data from: +% Rusak (15.2 GB): https://doi.org/10.25919/4ycc-fc11 +% IXI-T1 (4.8 GB): http://biomedic.doc.ic.ac.uk/brain-development/downloads/IXI/IXI-T1.tar +% ATLAS (2.8 GB): https://fcon_1000.projects.nitrc.org/indi/retro/atlas.html +% (Here you need to signup and approval) +% MR-ART (10.9 GB): https://openneuro.org/datasets/ds004173/versions/1.0.2 +% (As we need all files, the direct download is the easiest) +% +% 4. Download the preprocessed data for each dataset from the Giga +% Science server. Unpack the preprocessed data and merge them with the +% specific project directory (see 5. for directory structure). +% +% dataset N comment +% BWP 675 (75 + 300 + 300) +% BWPE # +% IXI 581 +% ATLAS # (# subjects with masked/unmasked lesions) +% MR-ART # (148 subject with no/light/severe motion artifacts) +% Rusak 400 (20 subject with 20 thickness levels) +% total # +% +% SPM and CAT segmentation run about 4 and 7 minutes per scan. +% +% +% 5. The script gunzips files and creates the following additional directories +% (if you did not download the preprocessed files): +% +% The data directory should look like: +% ./BWP # basic BWP image (provided nifti's) +% ./BWPr # BWP files with lower resolution (created with cat_tst_qa_resampleBWP) +% ./BWPgt # the ground-truth segmentation as labelmap + shell script to oranize BWP data +% ./BWPrestest # BWP resolution/smoothing tests +% ./IXI-T1 # unpacked IXI data +% ./ATLAS_2 # unpacked ATLAS 2.0 dataset +% ./ds004173-download # unpacked MR-ART +% ./20211122-SyntheticDataset # unpacked Rusak atrophy RAW data +% use Rusak2021makeSimpleBids.sh to reorganize the files +% ./Rusak2021 # unpacked reorganized Rusak RAW and preprocessed data +% ./+results # directory that includes result figures of the different tests +% ./+slices # example slices used in the figures +% +% The directories typically include: +% (1) the SPM preprocessing files in the same directory as the raw images +% (c1*.nii, c2*.nii, c3*.nii, m*.nii, *seg8.mat) +% (2) the CAT preprocessing files in the mri (p0*.nii, m*.nii) and report directory +% (catreportj*.jpg, catreport*.pdf, catlog*.txt, cat_*.xml, cat_*.mat) +% in case of the MR-ART, the cat-files are in the derivatives directory +% (3) the QC files (cat_vol_qa######_*) are in the report directory +% +% +% 6. Your specification: +% 1) your main data directory +% 2) the QC version you would like to test +% 3) the segmentation you would like to use (default is CAT) +% +% ------------------------------------------------------------------------- +% All figures in the paper were composed using Adobe Illustrator. +% Scripts to produce the underlying plots/tables of the paper figures: +% +% Figure 1: Manually selected slices, visualized with Mango. +% Approach X and Y represent publicly available tools used to +% processes the BWP data in 2014 (illustrative purpose). +% The plot was created in Excel. +% Figure 2: Manually selected slices form different datasets visualized +% with MATLAB and Mango. +% Figure 3: QC table. +% Figure 4: Screenshot of CAT QC GUI tools. +% Figure 5: BWP results: +% (A-D) cat_tst_qa_bwpmaintest +% (E/D) cat_tst_qa_simerrBWP +% (F/D) cat_tst_qa_Rusak_aging +% Figure 6: IXI, ATLAS & ADHD200 results: +% (A) IXI: cat_tst_qa_IXI( ... , 'IXI') +% (B) ATLAS: cat_tst_qa_ATLAS2 +% (C) ADHD200: cat_tst_qa_IXI( ... , 'ADHD200') +% Figure 7: MR-ART: +% cat_tst_qa_MRART_expertgroups +% Figure 8: MR-ART MRIQC +% cat_tst_qa_MRART_expertgroups +% Figure 9: Tohoku test-retest: +% cat_tst_qa_Tohoku +% Figure 10: NCR vs. CNR vs. Kappa +% cat_tst_qa_bwpmaintest +% Figure 11: Resolution - ECR: +% cat_tst_qa_resizeBWP +% Figure S1: cat_tst_qa_MRART_expertgroups +% Figure S2: cat_tst_qa_simerrBWP +% Figure S3: cat_tst_qa_Rusak_aging +% Table S1: cat_tst_qa_resizeBWP +% Figure S4: cat_tst_qa_IXI( ... , 'IXI') +% Figure S5ff: cat_tst_qa_MRART_expertgroups +% +% ------------------------------------------------------------------------- + + +% specify the main QC test directory +maindir = pwd; % go to the directory with the unzipped data or enter the path +[~,ff] = fileparts(maindir); +if strcmp(ff,'Dahnke2025_QCr1') + datadir = maindir; +else + datadir = fullfile(maindir,'Dahnke2025_QCr1'); +end +if ~exist(datadir,'dir') + error(['Cannot see the ""Dahnke2025_QCr1"" subdirectory. ' ... + 'Please go to the directory with the unzipped data or change the ""maindir"" variable']); +end + +% specify the CAT QC version +% Over time, we tried to improve the estimation in some specific cases that +% do not always improve the overall performance. While updating the QC paper, +% we tried to fix bugs, balance the processing, and integrate additional +% measures (e.g. for resolution) that were integrated in the cat_vol_qa*x +% version. +qaversions = { + 'cat_vol_qa201901'; % classic version (quite stable since 2016) + 'cat_vol_qa201901x'; % refined, debugged version of 201901 (* default *) + 'cat_vol_qa202110'; % second classic version (successor of 201901) - problems in bias estimation + 'cat_vol_qa202110x'; % refined, debugged version of 202110 + 'cat_vol_qa202205'; % last regular version before update (successor of 202110, stopped) + 'cat_vol_qa202310'; % redesigned version based on 201901 and 202110 + 'cat_vol_qa202412'; % experimental version with internal segmentation >> qcseg + }; +qaversions = {'cat_vol_qa201901x'}; % let's start with one + +% specify the used preprocessing: {'SPM','CAT'}, where qcseg requires cat_vol_qa2024012 +% some test cases (cat_tst_qa_simerrBWP, cat_tst_qa_resizeBWP) do not support other input segmentations than CAT +segment = {'CAT'}; % let's start with one (SPM is prepared for the BWP and MR-ART) +fasttest = 0; % run test just on a subset +recalcQC = 0; % re-estimate QC values + +% we use the developer mode to use the lazy flag to +if ~exist('cat_get_defaults','file'), spm 'fmri'; cat12('developer'); end +if cat_get_defaults('extopts.expertgui')<2, cat12('developer'); end +set(0,'DefaultFigureVisible','off'); + +% extend BWP test data (if required) +cat_tst_qa_resampleBWP( datadir ) +% gunzip all files for SPM +if any(contains(segment,'SPM')) + excludedirs = {'20211122-SyntheticDataset','Testing','ds000256-ChildrenHeadMotionN24','ADHD200'}; + gzfiles = cat_vol_findfiles( datadir , '*.nii.gz' ); + gzfiles( cellfun( @(x) any( contains(x,excludedirs)), gzfiles )) = []; % don't unzip files from these dirs + for fi = 1:numel(gzfiles) + fprintf(' Gunzip %s\n',gzfiles{fi}); + system(sprintf('gunzip %s',gzfiles{fi})); + end +end + +% test for matlab toolboxes (using the functions corr, fit, robustfit for evaluation) +if ~license('test', 'Statistics_Toolbox') + warning('Some functions requires the ""Statistics and Machine Learning Toolbox"" of MATLAB.\n') +end +if license('test', 'Curve_Fitting_Toolbox') + warning('Some functions requires the ""Curve Fitting Toolbox"" of MATLAB.\n') +end + +% try to avoid popup figure ... +set(0, 'DefaultFigureVisible', 'off'); %,'DefaultFigureInterruptible', 'off') + + +%% run tests us (un)commenting to run/avoid specific tests +cat_tst_qa_bwpmaintest( datadir, qaversions, segment, fasttest, recalcQC ) % test/scaling setup of the QMs on the brain web phantom +cat_tst_qa_simerrBWP( datadir, qaversions, fasttest, recalcQC ) % effects of segmentation problems on QM (CAT only) +cat_tst_qa_resizeBWP( datadir, qaversions, recalcQC ) % test of the resolution QM (CAT only) +cat_tst_qa_Rusak_aging( datadir, qaversions, segment, fasttest, recalcQC ) % test of the QM in simulated atrophy data based on real ADNI scans + +cat_tst_qa_IXI( datadir, qaversions, segment, fasttest, recalcQC, 'IXI') % aging/sex/site effects in healty adult population +cat_tst_qa_IXI( datadir, qaversions, segment, fasttest, recalcQC, 'ds000256') % aging/sex/site effects in healty children population +%cat_tst_qa_IXI( datadir, qaversions, segment, fasttest, recalcQC, 'ABIDE') % aging/sex/site effects in healty children population (many sites) +cat_tst_qa_IXI( datadir, qaversions, segment, fasttest, recalcQC, 'ADHD200') % aging/sex/site effects in healty children population (many sites) +cat_tst_qa_ATLAS2( datadir, qaversions, segment, fasttest, recalcQC ) % differences between original and masked stroke lesions + +cat_tst_qa_MRART_expertgroups( datadir, qaversions, segment, fasttest, recalcQC ) % real data with movement artifacts +cat_tst_qa_iqrRMS( datadir, qaversions, segment, fasttest) % evaluation of the power function to average QMs into SIQR +cat_tst_qa_Tohoku( datadir, qaversions, segment, fasttest) % test retest dataset with ground truth average + +% +set(0, 'DefaultFigureVisible', 'on'); %,'DefaultFigureInterruptible', 'on') +","MATLAB" +"Neurology","ChristianGaser/cat12","catQC/cat_tst_qa_Tohoku.m",".m","7508","206","function cat_tst_qa_Tohoku( datadir, qaversions, segment, fasttest) +%cat_tst_qa_Tohoku. Plot Tohoku dataset properties + + rerunqa = 0; + fasttest = 1; + + if ~license('test', 'Statistics_Toolbox') + error('This function requires the ""Statistics and Machine Learning Toolbox"" of MATLAB.\n') + end + + %% setup + Pgt = fullfile(datadir,'TRT_Tohoku','rmean_p0_R0500my_Tohoku_VBM12bo.nii'); + if fasttest + dataset = 'TRT_Tohoku'; + CATver = 'CAT12.9_2890'; + resdir = fullfile(datadir,'+results','Tohoku'); + datadir = fullfile(datadir,dataset); + files = cat_vol_findfiles( datadir , '*.nii',struct('depth',1)); + else + dataset = 'TRT_Tohoku_full'; + CATver = 'CAT12.9_2890'; + resdir = fullfile(datadir,'+results','Tohoku_full'); + datadir = fullfile(datadir,dataset); + files = cat_vol_findfiles( fullfile( datadir , 'nii') , '20*.nii',struct('depth',1)); + end + if ~exist(resdir,'dir'), mkdir(resdir); end + + + %% run preprocessing + for si = 1:numel(segment) + clear matlabbatch; + switch segment{si} + case 'CAT' + CATpreprocessing4qc; + filesCAT = setdiff(files,Pgt); + matlabbatch{1}.spm.tools.cat.estwrite.output.BIDS.BIDSyes.BIDSdir = ... + fullfile('..','derivatives',CATver); + filesCAT2 = strrep( filesCAT , datadir , fullfile( datadir, 'derivatives',CATver,'mri') ); + filesCAT( cellfun(@(x) exist(x,'file'), ... + spm_file(filesCAT2, 'prefix','p0') )>0 ) = []; + if ~isempty( filesCAT ) + matlabbatch{1}.spm.tools.cat.estwrite.data = filesCAT; + matlabbatch{1}.spm.tools.cat.estwrite.extopts.admin.lazy = 1; + spm_jobman('run',matlabbatch); + end + case 'SPM' + SPMpreprocessing4qc; + IXIfilesSPM = setdiff(files,Pgt); + IXIfilesSPM( cellfun(@(x) exist(x,'file'),spm_file(IXIfilesSPM,'prefix','c1'))>0 ) = []; + if ~isempty( IXIfilesSPM ) + matlabbatch{1}.spm.spatial.preproc.channel.vols = IXIfilesSPM; + spm_jobman('run',matlabbatch); + end + case 'synthseg' + error('synthseg is not prepared in the public script ... use MATLAB help') + case 'qcseg' + fprintf('No preprocessing required.\n\n'); + end + end + + + %% get segmentation + qias = 1:numel(qaversions); + fprintf('Prepare %s: \n',dataset) + for si = 1:numel(segment) + switch segment{si} + case 'CAT' + Pp0{si} = cat_vol_findfiles( datadir , 'p0*.nii',struct('depth',4)); + case 'SPM' + Pp0{si} = cat_vol_findfiles( datadir , 'c1*',struct('depth',0)); + case 'synthseg' + Pp0{si} = cat_vol_findfiles( datadir , 'synthseg_p0*',struct('depth',0)); + case 'qcseg' + Pp0{si} = cat_vol_findfiles( datadir , 'IXI*.nii',struct('depth',0)); + end + end + fprintf('Prepare %s done. \n',dataset) + + + %% QA processing + fprintf('Process %s: \n',dataset) + for si = 1:numel(segment) + for qai = qias + switch segment{si} + case 'CAT' + Pxml{si}{qai} = cat_vol_qa('p0',Pp0{si},struct('prefix',[qaversions{qai} '_'],'version',qaversions{ qai },'rerun',rerunqa)); + case 'SPM' + Pxml{si}{qai} = cat_vol_qa('p0',Pp0{si},struct('prefix',[qaversions{qai} '_spm_'],'version',qaversions{ qai },'rerun',rerunqa)); + case 'synthseg' + Pxml{si}{qai} = cat_vol_qa('p0',Pp0{si},struct('prefix',[qaversions{qai} '_synthseg_'],'version',qaversions{ qai },'rerun',rerunqa)); + case 'qcseg' + Pxml{si}{qai} = cat_vol_qa('p0',Pp0{si},struct('prefix',[qaversions{qai} '_qcseg_'],'version',qaversions{ qai },'rerun',rerunqa)); + end + end + end + fprintf('Process %s done. \n',dataset) + + + %% Kappa estimation + for si = 1:numel(segment) + Pkappamat{si} = fullfile(resdir, sprintf('Tohoku_kappa_N%d_%s.mat',numel(Pp0{si}),segment{si})); + if ~exist(Pkappamat{si},'file') + %[~,val] = cat_tst_calc_kappa(Pp0{si} ,{Pgt} ,struct('recalc',0,'realign',1,'realignres',1)); + [~,val] = eva_vol_calcKappa(Pp0{si} ,{Pgt} ,struct('recalc',0,'realign',2,'realignres',1)); + save(Pkappamat{si},'val'); + kappa{si} = real(cell2mat(val(2:end-2,2:5))); + else + S = load(Pkappamat{si}); + kappa{si} = real(cell2mat(S.val(2:end-2,2:5))); + end + end + + + %% get CSV data + QM = {'NCR','ICR','res_RMS','res_ECR','FEC','SIQR'}; + mark2rps = @(mark) min(100,max(0,105 - mark*10)); + illus = { + '20120701_112011MPRAGE1SENSEs1001a1010.nii'; + '20120701_112011MPRAGE3SENSEs301a1003.nii'; + '20120701_112011MPRAGE6SENSEs2201a1022.nii'; + '20120707_124735veryshortMPRAGESENSEs2901a1029.nii'; + '20120802_113755MPRAGE24SENSEs1201a1012.nii'; + '20120808_113817shorterMPRAGESENSEs901a1009.nii'; + }; + Pcsv = fullfile( datadir , 'tohoku_repeated_mprage_sequencesummary.csv' ); + csv = cat_io_csv(Pcsv,'','',struct('delimiter',',','csv','.')); + for si = 1:numel(segment) + for qai = qias + for ci = 1:numel(Pp0{si}) + use(ci) = true; + if si == 1 && qai == 1 + % get csv information + try + ID{ci} = spm_file(Pp0{si}{ci},'path',''); ID{ci}(1:2) = []; + csvid{ci} = find( contains( csv(2:end,1) , ID{ci} ) == 1,1,'first') + 1; + stime(ci) = csv{csvid{ci},13} / 60; % Convert to seconds relative to zero + sense(ci) = eval(['prod([' csv{csvid{ci},3} '])']); + illu(ci) = any( contains( illus , ID{ci} ) ); + catch + illu(ci) = 0; + use(ci) = false; + end + end + + % get xml information + for qmi = 1:numel(QM) + tmp = Pxml{si}{qai}(ci).qualityratings.(QM{qmi}); + tmp = mark2rps( tmp ); + eval(sprintf('%s{si,qai}(ci) = tmp;',QM{qmi})); + end + rGMV{si,qai}(ci) = Pxml{si}{qai}(ci).subjectmeasures.vol_rel_CGW(2); + vxvol{si,qai}(ci) = prod(Pxml{si}{qai}(ci).qualitymeasures.res_vx_vol); + end + + + + % - estimate Kappa ... not working + % - percentage rating rather than marks + % - correlation + + if 0 + %% + fh = figure(99); fh.Visible = true; clf; hold on + sa = scatter(stime,kappa{si}(:,4),10+vxvol{si,qai}*40,'filled'); + end + + + %% print figure + fh = figure(99); fh.Visible = true; clf; hold on + corr1 = corr(stime(use)',SIQR{si,qai}(use)','type','Spearman'); + sa = scatter(stime( illu & use),SIQR{si,qai}( illu & use),10+vxvol{si,qai}( illu & use)*40,'filled'); + sc = scatter(stime(~illu & use),SIQR{si,qai}(~illu & use),10+vxvol{si,qai}(~illu & use)*40,'filled'); + sc.MarkerFaceAlpha = .5; sc.MarkerFaceColor = [.0 .5 .8 ]; + sa.MarkerFaceAlpha = .9; sa.MarkerFaceColor = [.8 0 0 ]; + try + % fit + curve = fit( stime(use)', SIQR{si,qai}(use)','poly','robust','LAR'); + pc = plot(curve); pc.Color = [.0 .5 .8 ]; + end + box on; grid on; + legend({'select scans by resolution and scantime','all available scans'}) + title('scantime vs. SIQR') + subtitle(sprintf('radius ~ voxel volume; rho = %0.4f',corr1)) + ylabel('SIQR'); + xlabel('scantime (minutes)'); + ylim([40 100]); + if 0 + ax = gca; + ax.XScale = 'log'; + ax.XTick = 0:12; + end + + %pfname = fullfile(resdir,sprintf('%s_stime-SIQR_%s_%s.csv', dataset, qaversions{qai}, segment{si})); + %cat_io_csv(pfname,tables.(tf{tfi})); + %cat_io_cprintf('blue',' Save %s\n',pfname); + end + end +end + + + + + + + + ","MATLAB" +"Neurology","ChristianGaser/cat12","catQC/cat_tst_qa_ATLAS2.m",".m","12812","338","function cat_tst_qa_ATLAS2( datadir0, qaversions, segment, fasttest, recalcQC ) +%% Evaluation of CATQC in ATLAS +% ------------------------------------------------------------------------ +% QC evaluation of the ATLAS lesion dataset for original and lesion-masked +% images. In the ideal case the measures are somewhat similar and the QC +% measures are not or less affected by the tissue changes in lesions. +% +% Requirements: +% 1. Matlab with curve fitting toolbox (fit) +% 2. Download and install SPM and CAT +% 3. Download ATLAS T1 data from: +% +% 4. Specify in this script: +% 1) the data directory ""datadir"" +% 2) the QC version you would like to tests (the file has to exist in the cat directory) +% 3) the segmentation you would like to use +% +% See also cat_tst_qa_main. +% ------------------------------------------------------------------------ + +cat_io_cprintf([0 0.5 0],'\n\n== Run cat_tst_qa_ATLAS ==\n') + +if license('test', 'Curve_Fitting_Toolbox') + error('This function requires the ""Curve Fitting Toolbox"" of MATLAB.\n') +end + +% ### datadir ### +if ~exist( 'datadir0' , 'var' ) + datadir = '/Volumes/WDE18TB/MRData/Dahnke2025_QC/ATLAS_2/Training'; +else + datadir = fullfile(datadir0,'ATLAS_2','Training'); +end + +% ### QC version ### +if ~exist( 'qaversions' , 'var') + qaversions = { + ...'cat_vol_qa201901'; % classic version (quite stable since 2016) + 'cat_vol_qa201901x'; % refined, debugged version of 201901 + ...'cat_vol_qa202110'; % second classic version (successor of 201901) + ...'cat_vol_qa202110x'; % refined, debugged version of 202110 + ...'cat_vol_qa202205'; % last regular version before update (successor of 202110, stopped) + ...'cat_vol_qa202310'; % redesigned version based on 201901 and 202110 * default * + ...'cat_vol_qa202412'; % experimental version with internal segmentation >> qcseg + }; +end + +% ### segmention ### +if ~exist( 'segment' , 'var') + segment = {'CAT'}; % {'SPM','CAT','qcseg'}; % qcseg requires cat_vol_qa2024012 +end + +if ~exist( 'fasttest', 'var'), fasttest = 0; end +fast = {'full','fast'}; + +resdir = fullfile( fileparts( fileparts(datadir) ), '+results', ['ATLAS_' fast{fasttest+1} '_202508']); %' datestr(clock,'YYYYmm')]); +if ~exist(resdir,'dir'), mkdir(resdir); end + +% directories +rerun = recalcQC; + +% prepare data +% - gunzip +% - imcalc + +ATLASfiles = cat_vol_findfiles( datadir , 'sub*.nii.gz',struct('depth',5)); +if ~isempty(ATLASfiles) + gunzip(ATLASfiles); + for fi = 1:numel( ATLASfiles), delete(ATLASfiles{fi}); end +end + + +%% mask atlas files +ATLASfiles = cat_vol_findfiles( datadir , 'sub*T1w.nii',struct('depth',5)); +mskATLASfiles = cat_vol_findfiles( datadir , 'masked_sub*T1w.nii',struct('depth',5)); +if numel(ATLASfiles) > numel(mskATLASfiles) + t1w = cat_vol_findfiles( datadir , 'sub*T1w.nii' ,struct('depth',5)); + msk = cat_vol_findfiles( datadir , 'sub*mask.nii',struct('depth',5)); + te = cellfun(@exist, spm_file(t1w,'prefix','masked_')); + matlabbatch{1}.spm.tools.cat.tools.maskimg.data = t1w(~te); + matlabbatch{1}.spm.tools.cat.tools.maskimg.mask = msk(~te); + matlabbatch{1}.spm.tools.cat.tools.maskimg.bmask = {''}; + matlabbatch{1}.spm.tools.cat.tools.maskimg.recalc = 1; + matlabbatch{1}.spm.tools.cat.tools.maskimg.prefix = 'masked_'; + spm_jobman('run',matlabbatch); clear matlabbatch + mskATLASfiles = cat_vol_findfiles( datadir , 'masked_sub*.nii',struct('depth',5)); +end + + + +%% preprocessing +for si = 1:numel(segment) + clear matlabbatch; + switch segment{si} + case 'CAT' + CATpreprocessing4qc; + ATLASfilesCAT = [ATLASfiles; mskATLASfiles]; + ATLASfilesCAT( cellfun(@(x) exist(x,'file'),spm_file(ATLASfilesCAT,'prefix',['mri' filesep 'p0']))>0 ) = []; + if ~isempty( ATLASfilesCAT ) + matlabbatch{1}.spm.tools.cat.estwrite.data = ATLASfilesCAT; + matlabbatch{1}.spm.tools.cat.estwrite.extopts.admin.lazy = 1; + spm_jobman('run',matlabbatch); + end + case 'SPM' + SPMpreprocessing4qc; + ATLASfilesSPM = [ATLASfiles; mskATLASfiles]; + ATLASfilesSPM( cellfun(@(x) exist(x,'file'),spm_file(ATLASfilesSPM,'prefix','c1'))>0 ) = []; + if ~isempty( ATLASfilesSPM ) + matlabbatch{1}.spm.spatial.preproc.channel.vols = ATLASfilesSPM; + spm_jobman('run',matlabbatch); + end + case 'synthseg' + error('synthseg is not prepared in the public script ... use MATLAB help') + case 'qcseg' + fprintf('No preprocessing required.\n\n'); + end +end + + +%% +for si = 1:numel(segment) + qais = 1:numel(qaversions); + % (re)process QC values + switch segment{si} + case 'CAT' + Pp0b = cat_vol_findfiles( datadir , 'p0masked_sub*.nii',struct('depth',6)); %spm_fileparts(datadir) + case 'SPM' + Pp0b = cat_vol_findfiles( datadir , 'c1masked_sub*.nii',struct('depth',5)); %spm_fileparts(datadir) + case 'synthseg' + case 'qcseg' + Pp0b = cat_vol_findfiles( datadir , 'p0_qcseg_masked_sub*.nii',struct('depth',5)); %spm_fileparts(datadir) + end + Pp0a = cat_io_strrep(Pp0b,{'masked_'},{''}); %cat_vol_findfiles( datadira , 'p0*'); %spm_fileparts(datadir) + if fasttest % 5 ~> 50 scans + Pp0a = Pp0a(1:12:end); + Pp0b = Pp0b(1:12:end); + end + Pp0 = [Pp0a, Pp0b]; Pp0 = Pp0'; Pp0 = Pp0(:); % [msk, org] + if rerun + for qai = qais + switch segment{si} + case 'CAT', qcv = [qaversions{qai} '_']; + case 'SPM', qcv = [qaversions{qai} '_spm_']; + case 'qcseg', qcv = [qaversions{qai} '_qcseg_']; Pp0 = cat_io_strrep(Pp0,[filesep 'mri' filesep 'p0'],filesep); + end + cat_vol_qa('p0',Pp0,struct('prefix',qcv,'version',qaversions{ qai },'rerun',rerun)); + end + end + verb = 'on'; + + + + %% estimate size of leason + fprintf('Get lesion size: '); + switch segment{si} + case 'CAT' + Po = spm_file(cat_io_strrep(Pp0b,{['mri' filesep 'p0masked_'],'T1w'},{'','label-L_desc-T1lesion_mask'})); + case 'SPM' + Po = spm_file(cat_io_strrep(Pp0b,{'c1masked_','T1w'},{'','label-L_desc-T1lesion_mask'})); + end + for pi = 1:numel(Pp0b) + Plesmat{pi} = spm_file(Pp0b{pi},'prefix','lesionvol_','ext','.mat'); + if exist(Plesmat{pi},'file') + load(Plesmat{pi},'Vles'); + else + fprintf('\b\b\b\b\b\b\b\b\b%4d/%4d',pi,numel(Pp0b)); + try + V = spm_vol(Pp0a{pi}); + catch + V = spm_vol(Po{pi}); + end + Y = spm_read_vols(V); + TIVvx = sum(Y(:) > 0.5); + + V = spm_vol(Po{pi}); + Y = spm_read_vols(V); + + Vles = sum(Y(:) > 0.5) ./ TIVvx; + save(Plesmat{pi},'Vles'); + end + Vlesion(pi) = Vles; + end + + + %% + clear NCR ICR IQR ECR SIQR rGMV + for qai = qais + + %% find xml files + switch segment{si} + case 'CAT' + Pxml{1} = spm_file(cat_io_strrep(Pp0b,['mri' filesep 'p0'],['report' filesep]), ... + 'prefix',sprintf('%s_',qaversions{ qai }),'ext','.xml'); + Pxml{2} = cat_io_strrep(Pxml{1},{'masked_'},{''}); + case 'SPM' + Pxml{1} = spm_file(cat_io_strrep(Pp0b,'c1',['report' filesep]), ... + 'prefix',sprintf('%s_spm_',qaversions{ qai }),'ext','.xml'); + Pxml{2} = cat_io_strrep(Pxml{1},{'masked_'},{''}); + case 'qcseg' + Pxml{1} = spm_file(cat_io_strrep(Pp0b,'p0_',['report' filesep]), ... + 'prefix',sprintf('%s_',qaversions{ qai }),'ext','.xml'); + Pxml{2} = cat_io_strrep(Pxml{1},{'masked_'},{''}); + end + for xsi = numel(Pxml{1}):-1:1 + if ~exist(Pxml{1}{xsi},'file') || ~exist(Pxml{2}{xsi},'file') + Pxml{1}(xsi) = []; + Pxml{2}(xsi) = []; + end + end + + % load xml data + xml = cell(1,2); for i=1:numel(Pxml), xml{i} = cat_io_xml(Pxml{i}); end + + % extract measure + for i=1:numel(Pxml) + for ssi = 1:numel(xml{i}) + try + fname{ssi,i} = xml{i}(ssi).filedata.file; + TIV(ssi,i) = xml{i}(ssi).subjectratings.vol_TIV; + NCR(ssi,i) = xml{i}(ssi).qualityratings.NCR; + ICR(ssi,i) = xml{i}(ssi).qualityratings.ICR; + if isfield(xml{i}(ssi).qualityratings,'FEC') + FEC(ssi,i) = xml{i}(ssi).qualityratings.FEC; + else + FEC(ssi,i) = nan; + end + ECR(ssi,i) = xml{i}(ssi).qualityratings.res_ECR; + IQR(ssi,i) = xml{i}(ssi).qualityratings.IQR; + SIQR(ssi,i) = xml{i}(ssi).qualityratings.SIQR; + rGMV(ssi,i) = xml{i}(ssi).subjectmeasures.vol_rel_CGW(2); + + % get ID of the XML entry + seps = find( fname{si} == '_' ); + siten{ssi,i} = fname{ssi}(seps(1)+2:seps(1)+5); + end + end + end + dIQR = diff(SIQR,1,2); % msk - org + rmse = @(x) mean(x.^2).^.5; + + % store for later + QAVdiff{qai} = dIQR; + if 0 + + %numel(Pp0b( abs(QAVdiff{qai}) > .5 )) / numel(Pp0b); + %% + ss = find(abs(QAVdiff{qai}) > 1); + %% ss = ss(11); + switch segment{si} + case 'CAT', qcv = [qaversions{qai} '_']; + case 'qcseg', qcv = [qaversions{qai} '_qcseg_']; + end + cat_vol_qa('p0',Pp0a( ss ) ,struct('prefix',qcv,'version',qaversions{ qai },'rerun',1)); + cat_vol_qa('p0',Pp0b( ss ) ,struct('prefix',qcv,'version',qaversions{ qai },'rerun',1)); + end + + + %% create figure + if 1 + for sm = 0 + if ~exist('fh','var') || ~isvalid(fh), fh = figure(39); end + fh.Interruptible = 'off'; fh.Visible = 'off'; + if sm, fh.Position(3:4) = [200 160]; else, fh.Position(3:4) = [300 250]; end + ss = 0.05 * (sm + 1); clf(fh); + try + hst = histogram(dIQR,round(-max(abs(dIQR))/ss)*ss - ss/2:ss:round(max(abs(dIQR))/ss)*ss); + catch + hst = histogram(dIQR); + end + ylabel('number'); grid on; + if sm + title('masked vs. original'); smstr = '_sm'; + xlabel(sprintf('SIQR (RMSE=%0.3f)', rmse(dIQR) )); hold on; + else + title('SIQR difference between masked and original images'); smstr = ''; + xlabel(sprintf('SIQR difference (RMSE=%0.4f) %s', rmse(dIQR), strrep(qaversions{qai},'_','\_') )); hold on; + %ph = plot([0 0],ylim); ph.Color = [0 0 0.5]; ph.LineStyle = '--'; ph.LineWidth = 1; + end + + xlim([-3 3]); %xlim([-1 1] * ceil(max(abs(dIQR)))); + ylim([ 0 1] * ceil( max(hst.Values)*1.1 / 10)*10); + + % print figure + print(fh,fullfile(resdir ,sprintf('ATLAS_%s%s_%s',qaversions{qai},smstr,segment{si})),'-r600','-djpeg'); + end + end + + %% create figure + for sm = 0%:1 + if ~exist('fh','var'), fh = figure(39); end + fh.Interruptible = 'off'; fh.Visible = 'off'; + if sm, fh.Position(3:4) = [160 160]; else, fh.Position(3:4) = [150 250]; end + clf(fh); + if sm + title('masked vs. original'); smstr = '_sm'; + xlabel(sprintf('SIQR (RMSE=%0.3f)', rmse(dIQR) )); hold on; + else + title('SIQR difference between masked and original images'); smstr = ''; + xlabel(sprintf('SIQR difference (RMSE=%0.4f) %s', rmse(dIQR), strrep(qaversions{qai},'_','\_') )); hold on; + %ph = plot([0 0],ylim); ph.Color = [0 0 0.5]; ph.LineStyle = '--'; ph.LineWidth = 1; + end + cat_plot_boxplot( QAVdiff(qai) , struct('names',{{sprintf('SIQR (RMSE=%0.3f)', rmse(dIQR) )}},'usescatter',1,... + 'style',4,'datasymbol','o','ylim', [-3 3],'ygrid',0 )); %[-.1 .1] * ceil(max(abs( QAVdiff{qai} ))) ) ); + title('masked vs. original'); set(gca,'YGrid',1); + + % print figure + print(fh,fullfile(resdir ,sprintf('ATLAS_boxplot_%s%s_%s',qaversions{qai},smstr,segment{si})),'-r600','-djpeg'); + end + + + %% lesion size figure + fh = figure(37); clf; hold on + fh.Position(3:4) = [300 200]; fh.Interruptible = 'off'; fh.Visible = 'off'; + cmap = cat_io_colormaps('nejm',numel(qais)); + marker = {'o' 's' 'd' 'v' '^' '>' '<' 'p' 'h' }; + + hs = scatter( Vlesion , QAVdiff{qai} ); hold on; + hs.MarkerEdgeColor = cmap(1,:); hs.MarkerFaceColor = hs.MarkerEdgeColor; + hs.MarkerFaceAlpha = .2; hs.MarkerEdgeAlpha = .2; hs.SizeData = 20; hs.Marker = marker{1}; + ylim([-3,3]); + lesfit{qai} = fit( Vlesion(~isinf(Vlesion))' , QAVdiff{qai}(~isinf(Vlesion)) ,'poly1'); hp = plot(lesfit{qai}); hp.Color = cmap(1,:); %#ok<*SAGROW> + legend(strrep(qaversions{qai},'_','\_')); + + set(gca,'XTick',0:0.05:0.3,'XTickLabel',0:5:30); xlim([0 .3]); + grid on; box on; + ylabel('SIQR error (masked - raw)'); + xlabel('lesion volume in % of the TIV'); + title('ATLAS SQIR difference by lesion volume'); + + % print figure + print(fh,fullfile(resdir ,sprintf('ATLAS_lesionsize_%s_%s',qaversions{qai},segment{si})),'-r1200','-djpeg'); + + + end + +end +fprintf('ATLAS done.\n\n'); + +","MATLAB" +"Neurology","ChristianGaser/cat12","catQC/cat_tst_qa_MRART_expertgroups.m",".m","54012","1174","function cat_tst_qa_MRART_expertgroups( datadir, qaversions, segment, fasttest, rerun ) +%% cat_tst_qa_MRART_expertgroups. QC evaluation script +% ------------------------------------------------------------------------ +% Script to evaluate the CAT QC measures on the MR-ART dataset with motion +% affected groups (1 - no MA, 2 - light MA, and 3 - strong MA). +% +% Requirements: +% 1. Matlab with curve fitting toolbox (fit) +% 2. Download and install SPM and CAT +% 3. Download MR-ART data from OpenNeuro: +% https://openneuro.org/datasets/ds004173/versions/1.0.2 +% +% 4. Specify in this script: +% 1) the data directory ""datadir"" +% 2) the QC version you would like to tests (the file has to exist in the cat directory) +% 3) the segmentation you would like to use +% +% ------------------------------------------------------------------------ + +cat_io_cprintf([0 0.5 0],'\n\n== Run cat_tst_qa_MRART_expertgroups ==\n') + +if license('test', 'Curve_Fitting_Toolbox') + error('This function requires the ""Curve Fitting Toolbox"" of MATLAB.\n') +end + +% ### datadir ### +if ~exist( 'datadir' , 'var' ) + maindir = '/Volumes/WDE18TB/MRData/Dahnke2025_QC/ds004173-download'; +else + maindir = fullfile(datadir,'ds004173-download'); +end + + + +% ### QC version ### +if ~exist( 'qaversions' , 'var') + qaversions = { + ...'cat_vol_qa201901'; % classic version (quite stable since 2016) + 'cat_vol_qa201901x'; % refined, debugged version of 201901 + ...'cat_vol_qa202110'; % second classic version (successor of 201901) + ...'cat_vol_qa202110x'; % refined, debugged version of 202110 + ...'cat_vol_qa202205'; % last regular version before update (successor of 202110, stopped) + ...'cat_vol_qa202310'; % redesigned version based on 201901 and 202110 * default * + ...'cat_vol_qa202412'; % experimental version with internal segmentation >> qcseg + }; +end + +% ### segmention ### +if ~exist( 'segment' , 'var') + segment = {'CAT'}; % {'SPM','CAT','qcseg'}; % qcseg requires cat_vol_qa2024012 +end + +if ~exist( 'fasttest', 'var'), fasttest = 0; end +if ~exist( 'rerun', 'var'), rerun = 0; else, rerun = min(1,rerun); end +fast = {'full','fast'}; + +warning off +printslices = 0; % ###### + +[cv,rn] = cat_version; +catppdir = fullfile(maindir,'derivatives',sprintf('%s',cv)); %sprintf('%s_R%s',cv,rn)); +[~,CATver,ext] = fileparts(catppdir); CATver = [CATver ext]; clear ext +mriqcdir = fullfile(maindir,'derivatives','mriqc-0.16.1'); +resultdir = fullfile(maindir,'derivatives',['results_' CATver]); +printdir = fullfile(fileparts(maindir),'+results',sprintf('MR-ART_%s_%s',fast{fasttest+1},'202508')); %datestr(clock,'YYYYmm'))); +exprating = fullfile(maindir,'derivatives','scores.tsv'); +partis = fullfile(maindir,'participants.tsv'); +FS = [10 10]; +if fasttest, pres = '-r300'; else, pres = '-r1200'; end +% translate marks into percentage ratingop +mark2rps = @(mark) min(100,max(0,105 - mark*10)); +verb = 0; + +si = 1; +qais = 1:numel(qaversions); + + +% preprocessing +for si = 1:numel(segment) + clear matlabbatch; + ARTfiles = cat_vol_findfiles( maindir , 'sub*.nii',struct('depth',3)); + switch segment{si} + case 'CAT' + CATpreprocessing4qc; + ARTfilesCAT = ARTfiles; + for fi = 1:numel(ARTfiles) + p0files{fi} = spm_file(ARTfiles{fi},'path',fullfile(maindir,'derivatives','CAT12.9',spm_str_manip(ARTfiles{fi},'hht'),'anat'),'prefix','p0'); + end + ARTfilesCAT( cellfun(@(x) exist(x,'file'),p0files)>0 ) = []; + if ~isempty( ARTfilesCAT ) + matlabbatch{1}.spm.tools.cat.estwrite.data = ARTfilesCAT; + matlabbatch{1}.spm.tools.cat.estwrite.extopts.admin.lazy = 1; + matlabbatch{1}.spm.tools.cat.estwrite.output.BIDS = ... + struct('BIDSyes',struct('BIDSfolder',fullfile('..','derivatives','CAT12.9'))); + spm_jobman('run',matlabbatch); + end + case 'SPM' + SPMpreprocessing4qc; + ARTfilesSPM = ARTfiles; + ARTfilesSPM( cellfun(@(x) exist(x,'file'),spm_file(ARTfiles,'prefix','c1'))>0 ) = []; + if ~isempty( ARTfilesSPM ) + matlabbatch{1}.spm.spatial.preproc.channel.vols = ARTfilesSPM; + spm_jobman('run',matlabbatch); + end + case 'synthseg' + error('synthseg is not prepared in the public script ... use MATLAB help') + case 'qcseg' + fprintf('No preprocessing required.\n\n'); + end +end + + + +%% +for qai = qais + Pp0{qai} = cat_vol_findfiles( catppdir , 'p0*.nii'); + Pc1{qai} = cat_vol_findfiles( maindir , 'c1*.nii'); + Pss{qai} = cat_vol_findfiles( maindir , 'synthseg_p0*.nii'); + Pqs{qai} = cat_vol_findfiles( maindir , 'sub*.nii'); + if fasttest, Pp0{qai} = Pp0{qai}(1:4:end); end + if fasttest, Pc1{qai} = Pc1{qai}(1:4:end); end + if fasttest, Pss{qai} = Pss{qai}(1:4:end); end + if fasttest, Pqs{qai} = Pqs{qai}(1:4:end); end + %% (re)processing of QC values + %if rerun + for si = 1:numel(segment) + switch segment{si} + case 'CAT' + cat_vol_qa('p0',Pp0{qai},struct('prefix',[qaversions{qai} '_'],'version',qaversions{ qai },'rerun',rerun*2)); + case 'SPM' + cat_vol_qa('p0',Pc1{qai},struct('model',struct('spmc1',1),'prefix',[qaversions{qai} '_spm_'],'version',qaversions{ qai },'rerun',rerun*2)); + case 'synthseg' + cat_vol_qa('p0',Pss{qai},struct('prefix',[qaversions{qai} '_synthseg_'],'version',qaversions{ qai },'rerun',rerun*2)); + case 'qcseg' + cat_vol_qa('p0',Pqs{qai},struct('prefix',[qaversions{qai} '_qcseg_'],'version',qaversions{ qai },'rerun',rerun*2)); + end + end + %end +end + + +CSV = cat_io_csv(partis,struct('delimiter',' ')); + +%% create figure +%segment = 'SPM';%SPM'; %'synthseg'; +for si = 1:numel(segment) + for qai = qais + fprintf('MRART %s:\n',qaversions{qai}) + + resultdirqai = [resultdir '_' fast{fasttest+1} '_202508' ]; % datestr(clock,'YYYYmm') ]; + + if ~exist(resultdirqai,'dir'), mkdir(resultdirqai); end + if ~exist(printdir ,'dir'), mkdir(printdir); end + + % find CAT XML files - catppdir + clear Pxml Pxmlspm; + if exist('Pp0','var') + for pi=1:numel(Pp0{qai}) + [pp,ff] = fileparts(Pp0{qai}{pi}); + if contains( segment{si} ,'synthseg') + [pp,ff] = fileparts(Pss{qai}{pi}); + Pxml{pi,1} = fullfile(pp,'report',[qaversions{qai} '_' strrep(ff,'synthseg_p0','synthseg_') '.xml']); + elseif contains( segment{si} ,'SPM') + [pp,ff] = fileparts(Pc1{qai}{pi}); + Pxml{pi,1} = fullfile(pp,[qaversions{qai} '_spm_' ff(3:end) '.xml']); % spm_c1 + elseif contains( segment{si} ,'qcseg') + [pp,ff] = fileparts(Pqs{qai}{pi}); + Pxml{pi,1} = fullfile(pp,'report',[qaversions{qai} '_qcseg_' ff '.xml']); % spm_c1 + else + %Pxml{pi,1} = fullfile(maindir,spm_str_manip(pp,'ht'),spm_str_manip(pp,'t'),[qaversions{qai} '_' ff(3:end) '.xml']); + Pxml{pi,1} = fullfile(pp,[qaversions{qai} '_' ff(3:end) '.xml']); + if ~exist(Pxml{pi},'file') + Pxml{pi,1} = fullfile(maindir,spm_str_manip(pp,'ht'),[qaversions{qai} '_' ff(3:end) '.xml']); + end + if ~exist(Pxml{pi},'file') + Pxml{pi,1} = fullfile(pp,'report',[qaversions{qai} '_' ff(3:end) '.xml']); + end + end + [pp,ff] = fileparts(Pc1{qai}{pi}); + Pxmlspm{pi,1} = fullfile(pp,[qaversions{qai} '_spm_' ff(3:end) '.xml']); + end + else + Pxml = cat_vol_findfiles(fullfile(maindir),sprintf('%s_sub*.xml',qaversions{qai})); % ,'derivatives' + if fasttest && numel(Pp0)>numel(Pxml), Pxml = Pxml(1:4:end); end + end + xml = cat_io_xml(Pxml); + if 0 %contains( segment{si} ,'CAT') + xmlspm = cat_io_xml(Pxmlspm); + end + + % get json and other files + clear Q; + %% + for xi = 1:numel(Pxml) + + % get json and other files + if any( contains(segment{si},'CAT' ) ) + [pp,ff,ee] = fileparts(strrep(Pxml{xi},[qaversions{qai} '_'],'')); + SID{xi} = spm_str_manip(Pxml{xi},'hht'); + elseif any( contains(segment{si},'SPM' ) ) + [pp,ff,ee] = fileparts(strrep(strrep(Pxml{xi},[qaversions{qai} '_'],''),'spm_','')); + SID{xi} = spm_str_manip(Pxml{xi},'hht'); + elseif any( contains(segment{si},'qcseg' ) ) + [pp,ff,ee] = fileparts(strrep(strrep(Pxml{xi},[qaversions{qai} '_'],''),'qcseg_','')); + SID{xi} = spm_str_manip(Pxml{xi},'hhht'); + else + [pp,ff,ee] = fileparts(strrep(strrep(Pxml{xi},[qaversions{qai} '_'],''),'synthseg_','')); + SID{xi} = spm_str_manip(Pxml{xi},'hhht'); + end + jsonfile{xi,1} = fullfile(mriqcdir,SID{xi},'anat',[ff '.json']); + + % get age/sex from csv + csvSIDi = find(contains(CSV(:,1),SID{xi})); + xml(xi).age = CSV{ csvSIDi , 3}; + xml(xi).sex = CSV{ csvSIDi , 2}=='M'; + Q.age(1,xi) = xml(xi).age; + Q.sex(1,xi) = xml(xi).sex; + + %% get SPM + [pp,ff] = fileparts(Pp0{qai}{xi}); pp = strrep(pp,catppdir,maindir); + spm_vol_mat = fullfile(pp,['spmvol_' ff(3:end) '.mat']); + if exist(spm_vol_mat,'file') + load(spm_vol_mat,'spmvol'); + else + for ci = 1:3 + P = fullfile(pp,sprintf('c%d%s.nii',ci,ff(3:end))); + V = spm_vol(P); + Y = spm_read_vols(V); + vx_vol = sqrt(sum(V.mat(1:3,1:3).^2)); + spmvol(ci) = sum(Y(:)) * prod(vx_vol)/1000; + end + save(spm_vol_mat,'spmvol'); + end + spmvols(xi,1:3) = spmvol / sum(spmvol); + + if contains(segment{si},'CAT') + xml(xi).subjectmeasures.SPMrGMV = spmvols(xi,1); + xml(xi).subjectmeasures.SPMrCSFV = spmvols(xi,3); + xml(xi).subjectmeasures.SPMrWMV = spmvols(xi,2); + else + xml(xi).subjectmeasures.vol_rel_CGW(1:3) = spmvols(xi,[3,1,2]); + end + + %% get synthseg + if contains(segment{si},'synthseg') + [pp,ff] = fileparts(Pp0{qai}{xi}); pp = strrep(pp,catppdir,maindir); + synthseg_vol_mat = fullfile(pp,['synthsegvol_' ff(3:end) '.mat']); + Yp0toC = @(Yp0,c) 1-min(1,abs(Yp0-c)); + if exist(synthseg_vol_mat,'file') + load(synthseg_vol_mat,'synthsegvol'); + else + P = fullfile(pp,sprintf('synthseg_%s.nii',ff)); + V = spm_vol(P); + Y = spm_read_vols(V); + vx_vol = sqrt(sum(V.mat(1:3,1:3).^2)); + for ci = 1:3 + synthsegvol(ci) = sum(Yp0toC(Y(:),ci)) * prod(vx_vol)/1000; + end + save(synthseg_vol_mat,'synthsegvol'); + end + synthsegvols(xi,1:3) = synthsegvol / sum(synthsegvol); + + xml(xi).subjectmeasures.vol_rel_CGW(1:3) = synthsegvols(xi,:); + end + + + + end + json = cat_io_json(jsonfile); + + + %% inverse measure + evalmriqc = 0; + + mriqcQFNinv = {'cjv','efc','qi_1','inu','snr_CSF' ... + 'wm_p95_','wm_stdv_','wm_median_','wm_mean_','wm_mad_','bg_p95','bg_stdv' ... + 'bg_mad','bg_mean','bg_median','bg_p95','bg_stdv', ... + 'csf_mean','csf_median','csf_n', ... + 'gm_mad','gm_mean','gm_median','gm_p95','gm_stdv', ... + 'wm_mad','wm_mean','wm_median','wm_p95','wm_stdv', ... + }; + if 0 + mriqcQFN = { + 'snr_total'; 'snr_wm'; % excelent + 'cnr'; 'cjv'; 'fber'; % good + ...'summary_bg_p95'; 'summary_bg_stdv'; + ...'summery_gm_p95'; 'summery_gm_k'; 'summery_gm_mad'; 'summery_gm_mean'; + ...'summery_wm_p95'; 'summery_wm_k'; 'summery_wm_mad'; 'summery_wm_mean'; + }; + else + mriqcQFN = { + 'cnr'; 'cjv'; 'fber'; 'efc'; 'qi_1'; 'qi_2'; 'wm2max'; + 'fwhm_avg'; 'fwhm_x'; 'fwhm_y'; 'fwhm_z'; + 'icvs_csf'; 'icvs_gm'; 'icvs_wm'; + 'inu_med'; 'inu_range'; + 'rpve_csf'; 'rpve_gm'; 'rpve_wm'; + 'snr_csf'; 'snr_gm'; 'snr_total'; 'snr_wm'; + 'snrd_csf'; 'snrd_gm'; 'snrd_total'; 'snrd_wm'; + 'summary_bg_k'; 'summary_bg_mad'; 'summary_bg_mean'; 'summary_bg_median'; 'summary_bg_n'; 'summary_bg_p05'; 'summary_bg_p95'; 'summary_bg_stdv'; + 'summary_csf_k'; 'summary_csf_mad'; 'summary_csf_mean'; 'summary_csf_median'; 'summary_csf_n'; 'summary_csf_p05'; 'summary_csf_p95'; 'summary_csf_stdv'; + 'summary_gm_k'; 'summary_gm_mad'; 'summary_gm_mean'; 'summary_gm_median'; 'summary_gm_n'; 'summary_gm_p05'; 'summary_gm_p95'; 'summary_gm_stdv'; + 'summary_wm_k'; 'summary_wm_mad'; 'summary_wm_mean'; 'summary_wm_median'; 'summary_wm_n'; 'summary_wm_p05'; 'summary_wm_p95'; 'summary_wm_stdv'; + 'tpm_overlap_csf'; 'tpm_overlap_gm'; 'tpm_overlap_wm'; + }'; + end + for fni = 1:numel(mriqcQFN) + for xi = 1:numel(Pxml) + Q.(mriqcQFN{fni})(xi,1) = json(xi).(mriqcQFN{fni}); + end + if any(contains( mriqcQFN(fni) , mriqcQFNinv )) + Q.(mriqcQFN{fni}) = -Q.(mriqcQFN{fni}); + end + end + + % read expert rating (rename tsv as csv) + copyfile(exprating,strrep(exprating,'.tsv','.csv')); + tsv = cat_io_csv(exprating,'','',struct('delimiter','\t')); + + + + + % extract IQR values + % QFN: { fieldname1 fieldname2 fieldindex outlier range name print } + QFN = { + 'qualityratings' 'NCR' 1 1 [1 6] 'NCR' 1 + 'qualityratings' 'ICR' 1 1 [1 6] 'ICR' 1 + ...'qualityratings' 'res_RES' 1 1 [1 6] 'res_RES' 0-fasttest + 'qualityratings' 'res_ECR' 1 1 [1 6] 'res_ECR' 1 + 'qualityratings' 'FEC' 1 1 [1 6] 'FEC' 1 + ...'qualityratings' 'IQR' 1 1 [1 6] 'IQR' 1 + 'qualityratings' 'SIQR' 1 1 [1 6] 'SIQR' 1 + ... 'qualityratings' 'contrastr' 1 1 [1 6] 'CON' 1 + 'subjectmeasures' 'vol_rel_CGW' 2 0 [0 1] 'rGMV' 1 %-fasttest + 'subjectmeasures' 'vol_rel_CGW' 1 0 [0 1] 'rCSFV' 1-fasttest + 'subjectmeasures' 'vol_rel_CGW' 3 0 [0 1] 'rWMV' 1-fasttest + ...'subjectmeasures' 'SPMrGMV' 1 0 [0 1] 'SPMrGMV' 1-fasttest + ...'subjectmeasures' 'SPMrWMV' 1 0 [0 1] 'SPMrCSFV' 1-fasttest + ...'subjectmeasures' 'SPMrCSFV' 1 0 [0 1] 'SPMrWMV' 1-fasttest + ...'subjectmeasures' 'vol_abs_CGW' 1 0 [400 800] 'CSFV' 0 + ...'subjectmeasures' 'vol_abs_CGW' 2 0 [400 800] 'GMV' 0 + ...'subjectmeasures' 'vol_abs_CGW' 3 0 [400 800] 'WMV' 0 + ...'subjectmeasures' 'vol_TIV' 1 0 [800 2000] 'TIV' 1-fasttest + }; + QS = Q; + for xi = 1:numel(xml) + Q.name{xi,1} = xml(xi).filedata.file; + QS.name{xi,1} = xml(xi).filedata.file; + for fni1 = 1:size(QFN,1) + if isfield(xml(xi),QFN{fni1,1}) && isfield(xml(xi).(QFN{fni1,1}),QFN{fni1,2}) + Q.(QFN{fni1,6})(xi,1) = xml(xi).(QFN{fni1,1}).(QFN{fni1,2})(QFN{fni1,3}); + else + Q.(QFN{fni1,6})(xi,1) = nan; + end + if exist('xmlspm','var') + if xi<=numel(xmlspm) + if isfield(xmlspm(xi),QFN{fni1,1}) && isfield(xmlspm(xi).(QFN{fni1,1}),QFN{fni1,2}) + QS.(QFN{fni1,6})(xi,1) = xmlspm(xi).(QFN{fni1,1}).(QFN{fni1,2})(QFN{fni1,3}); + else + QS.(QFN{fni1,6})(xi,1) = nan; + end + end + end + end + end + + Q.site = ones(size(Q.NCR)); + + + + % get the motion groups by instruction + for xi = 1:numel(xml) + Q.sub{xi,1} = Q.name{xi}(1:10); + + if ~isempty( strfind(Q.name{xi},'standard') ) + Q.group0(xi,1) = 1; + elseif ~isempty( strfind(Q.name{xi},'headmotion1_T1w') ) + Q.group0(xi,1) = 2; + elseif ~isempty( strfind(Q.name{xi},'headmotion2_T1w') ) + Q.group0(xi,1) = 3; + end + end + + + if evalmriqc == 2, QFN = {}; qaversions{qai} = 'mriQC'; end + if evalmriqc + for fni = 1:numel(mriqcQFN) + QFN = [ QFN ; {'' mriqcQFN{fni} 1 1 ... + [min(Q.(mriqcQFN{fni})) max(Q.(mriqcQFN{fni}))] mriqcQFN{fni} 1 } ]; + end + end + + + %% + if 0 + clear QSD; + fh = figure(22); + fh.Visible = 'off'; + fh.Interruptible = 'off'; + fh.Position(3:4) = [200 200]; + QM = {'NCR','ICR','res_RES','res_ECR','FEC','SIQR'}; + cl = [.8 0 .2; 0.8 0.6 0; 0.2 0.5 0; .0 .5 .9; 0. 0 0.9; 0 0 0 ]; + for fni1 = 1:numel(QM) + QSD.(QM{fni1}) = [Q.(QM{fni1}), QS.(QM{fni1})]; + QSD.MAE{fni1} = Q.(QM{fni1}) - QS.(QM{fni1}); + QSD.RMSE(fni1) = mean(QSD.MAE{fni1}.^2).^.5; + end + cat_plot_boxplot( QSD.MAE,struct('ygrid',0,'style',4,'names',{cat_io_strrep(QM,'res_','')},'datasymbol','o', ... + 'usescatter',1,'groupcolor',cl)); + set(gca,'ygrid','on','ylim',[-3 3],'XTickLabelRotation',0); + title(sprintf('MAE (%s)',segment{si})), xlabel('measures'); ylabel('error') + if ~exist(fullfile(printdir,'boxplot'),'dir'), mkdir(fullfile(printdir,'boxplot')); end + fname = fullfile(printdir,'boxplot',['MRART_boxplot_MAE_' qaversions{ qai } '_' segment{si} '.png']); + print(fh,fname,'-dpng',pres) + cat_io_cprintf('blue',sprintf(' Print %s\n',fname)); + + %% + bh = bar(QSD.RMSE); bh.CData = cl; bh.FaceColor = 'flat'; + ylim([0 3]); xlim([.4 6.6]); xticklabels({'NCR','ICR','RES','ECR','FEC','SIQR'}); + h = gca; h.YGrid = 'on'; h.XTickLabelRotation = 0; + title(sprintf('RMSE %s',segment{si})); xlabel('measures'); ylabel('error') + for fi = 1:numel(QSD.RMSE) + dt(fi) = text(fi-.45, QSD.RMSE(fi) + .1, sprintf('%0.3f',QSD.RMSE(fi)),'FontSize',8,'Color',cl(fi,:)); + end + set(gca,'ygrid','on','ylim',[0 3],'XTickLabelRotation',0); + if ~exist(fullfile(printdir,'boxplot'),'dir'), mkdir(fullfile(printdir,'boxplot')); end + fname = fullfile(printdir,'boxplot',['MRART_boxplot_RMSE_' qaversions{ qai } '_' segment{si} '.png']); + print(fh,fname,'-dpng',pres) + cat_io_cprintf('blue',sprintf(' Print %s\n',fname)); + end + + + %% find alignment xml and tsv + mytable.ROC = repmat({{'measure','AUC','ACC'}},1,4); + mytable.ANOVA = {'measure','F-value','p-value'}; + mark2rps = @(mark) min(100,max(0,105 - mark*10)); + gradlim = [40 100]; % gradlim = [0.5 9.5]; + gradtick = 40:10:100; % 45:10:95; + for fni1 = 1:size(QFN,1) + data = cell(1,3); + for ti = 2:size(tsv,1) + name = tsv{ti,1}; + group = tsv{ti,2}; + + sid = find( strcmp(Q.name,name),1); + if ~isempty(sid) + if strcmp(QFN{fni1,1},'qualityratings') + data{ group }(end+1) = mark2rps( Q.(QFN{fni1,6})( sid )); + else + data{ group }(end+1) = Q.(QFN{fni1,6})( sid ); + end + Q.group( sid , 1) = group; + end + end + + + %% + if QFN{fni1,7} + % ANOVA + if fni1 == 1 + try + % call stat toolbox licence + [an_p(fni1), an_tab{fni1}, an_obj{fni1}] = anova1( mark2rps(Q.(QFN{fni1,6})) , uint8(Q.group) , 'off' ); + end + pause(1); + end + if strcmp(QFN{fni1,1},'qualityratings') + [an_p(fni1), an_tab{fni1}, an_obj{fni1}] = anova1( mark2rps(Q.(QFN{fni1,6})) , uint8(Q.group) , 'off' ); + else + [an_p(fni1), an_tab{fni1}, an_obj{fni1}] = anova1( Q.(QFN{fni1,6}) , uint8(Q.group) , 'off' ); + end + + % print boxplot figure + if verb, fig = figure(40); else, fig = figure(); end + fig.Visible = 'off'; + fig.Interruptible = 'off'; + fig.Position(3:4) = [130 200]; + fig.Name = sprintf('MR-ART - Boxplot - %s %s',qaversions{qai},strrep(QFN{fni1,6},'_','\_')); + if verb, fig.Visible = 'on'; else, fig.Visible = 'off'; end + + if strcmp(QFN{fni1,1},'qualityratings') + cat_plot_boxplot(data,struct('ygrid',0,'style',4,'names',{{'no','light','strong'}},'datasymbol','o', ... + 'usescatter',1,'groupcolor',[0 0.8 0; 0.8 0.7 0; 0.8 0 0],'ylim',gradlim)); + else + cat_plot_boxplot(data,struct('ygrid',0,'style',4,'names',{{'no','light','strong'}},'datasymbol','o', ... + 'usescatter',1,'groupcolor',[0 0.8 0; 0.8 0.7 0; 0.8 0 0])); + end + %% + title(sprintf('MA groups %s', strrep(QFN{fni1,6},'_','\_'))); box on; + subtitle(sprintf('F=%0.1f, p=%0.1e', an_tab{fni1}{2,5}, an_p(fni1))) + mytable.ANOVA = [mytable.ANOVA; + QFN(fni1,6), an_tab{fni1}(2,5), {an_p(fni1)}]; + if strcmp(QFN{fni1,1},'qualityratings') + set(gca,'ygrid','on','ytick',gradtick,'XTickLabelRotation',0); + else + set(gca,'ygrid','on','XTickLabelRotation',0); + end + xlabel('groups'); ylabel(sprintf('%s (grades)',strrep(QFN{fni1,6},'_','\_'))); + if ~exist(fullfile(printdir,'boxplot'),'dir'), mkdir(fullfile(printdir,'boxplot')); end + fname = fullfile(printdir,'boxplot',['MRART_boxplot_' strrep(QFN{fni1,6},'res_','') '_' qaversions{ qai } '_' segment{si} '.png']); + print(fig,fname,'-dpng',pres) + cat_io_cprintf('blue',sprintf(' Print %s\n',fname)); + if ~verb, close(fig); end + end + + + + + %% age dependency + fig = figure(12); fig.Position(3:4) = [300 200]; clf; + fig.Visible = 'off'; + fig.Interruptible = 'off'; + gcol = [0 0.8 0; 0.8 0.7 0; 0.8 0 0]; hold on; + gnam = {'no','light','strong'}; + if 0 + % select measure for tests + fni2 = find(contains(QFN(:,2),'vol_rel_CGW')); if numel(fni2)>1, fni2 = fni2(1); end + else + fni2 = fni1; + end + warning off; + for gi = 1:max(Q.group) + if strcmp(QFN{fni2,1},'qualityratings') + sc = scatter(Q.age(Q.group==gi), mark2rps(Q.(QFN{fni2,6})(Q.group==gi)), 20); + [curve1{gi}, goodness, output] = fit( double(Q.age(Q.group==gi))', ... + double(mark2rps(Q.(QFN{fni2,6})(Q.group==gi))),'poly1','robust','LAR'); + else + if strcmp(QFN{fni2,6},'rWMV'), deg = 'poly2'; else, deg = 'poly1'; end + sc = scatter(Q.age(Q.group==gi), Q.(QFN{fni2,6})(Q.group==gi), 20); + [curve1{gi}, goodness, output] = fit( double(Q.age(Q.group==gi & ~isnan(Q.(QFN{fni2,6}) )))', ... + double(Q.(QFN{fni2,6})(Q.group==gi & ~isnan(Q.(QFN{fni2,6})))) , deg,'robust','LAR'); + end + set(sc,'MarkerFaceColor',gcol(gi,:),'MarkerEdgeColor',gcol(gi,:), ... + 'MarkerFaceAlpha',0.3,'MarkerEdgeAlpha',0.3); + mylegend{gi} = sprintf('%s (b=%0.3f/100a)',gnam{gi},curve1{gi}.p1 * 100); + Q.agefit.p1(gi) = curve1{gi}.p1; + end + warning on; + xlim([15 85]); + for gi = 1:max(Q.group) + ph = plot(curve1{gi}); + set(ph,'Color',gcol(gi,:)); + end + box on; grid on; + title(sprintf('MA groups %s (diff(good/bad)=%0.3f)', strrep(QFN{fni2,6},'_','\_'),... + abs(diff([mean(Q.(QFN{fni2,6})(Q.group==1)),mean(Q.(QFN{fni2,6})(Q.group==3))])))); + xlabel('age (years)'); + warning off; + if strcmp(QFN{fni2,1},'qualityratings') + ylabel(sprintf('%s (rps)',strrep(QFN{fni2,6},'_','\_'))); + ylim(gradlim - 10*(1-strcmp(QFN{fni2,2},'ICR'))); %set(gca,'YTick',45:10:95); + legend(mylegend,'Location','SouthEast'); + else + ylabel(sprintf('%s',strrep(QFN{fni2,6},'_','\_'))); + if mean(Q.(QFN{fni2,6})(Q.group==1)) > mean(Q.(QFN{fni2,6})(Q.group==3)) & ~strcmp(QFN{fni2,1},'subjectmeasures') + legend(mylegend,'Location','SouthEast'); + else + legend(mylegend,'Location','NorthEast'); + end + end + warning on; + set(gca,'XTick',20:10:80); + tdir = fullfile(printdir,'aging'); if ~exist(tdir,'dir'), mkdir(tdir); end + fname = fullfile(tdir, sprintf('MRART_aging_%s_%s_%s.png', strrep(QFN{fni2,6},'res_','') , qaversions{qai} , segment{si})); + print(fig, fname, '-dpng',pres); + cat_io_cprintf('blue',sprintf(' Print %s\n',fname)); + + + + + + %% outlier detection + if fasttest, tss = 0.05; else tss = 0.01; end; ppos = [0 2 1 3]; + clear sens2 spec2 sensg2 specg2 cf + if QFN{fni1,4} + fig = figure; fig.Position(3:4) = [600 200]; + fig.Visible = 'off'; + fig.Interruptible = 'off'; + fig.Name = sprintf('MR-ART - ROC - %s',qaversions{qai}); + if ~verb, fig.Visible = 'off'; end + + erths = [2.5 2.0 1.5]; % expert rating threshold for 3 groups (1=no MA, 2=light MAs, 3=severe MAs) + for erthi = 1:numel(erths) + erth = erths(erthi); + + % -------------------------------------------------------------------- + Q.train = mod( round( 1/3:1/3:numel(Q.group)/3 )' , 2 ); % to get more or less all groups + + IQRfield = QFN{fni1,6}; + model = 10; + cmodel = 1; + rps = 1; + + if contains( QFN{fni1,2}, mriqcQFN) + th = min( Q.(QFN{fni1,2}) ):tss/10 * (max( Q.(QFN{fni1,2}) ) - min( Q.(QFN{fni1,2}) )):max( Q.(QFN{fni1,2}) ); + cf{erthi} = th; + else + th = 0.5:tss:6.5; % global IQR threshold test range (school grades) + cf{erthi} = -10:tss*10:30; % protocoll-specific dIQR threshold test range (school grad range) + end + + % + testsites = 1; + sens2{erthi} = {nan(numel(cf{erthi}),1),nan(numel(cf{erthi}),1)}; %#ok<*SAGROW> + spec2{erthi} = sens2{erthi}; acc2{erthi} = sens2{erthi}; auc2{erthi} = sens2{erthi}; + Q.Nmn = nan(size(Q.SIQR)); Q.Nsd = Q.Nmn; Q.NXIQR = Q.Nmn; + for i = 1:numel(cf{erthi}) % apply global IQR tresholds for ROC statistic + TPFN{erthi}{i} = nan([size(Q.SIQR,1),4]); + NXIQR{erthi}{i} = nan([size(Q.SIQR,1),1]); + traingroup{erthi}{i} = nan([size(Q.SIQR,1),1]); + for ti = 1:2 % train vs. test + M = Q.train == ti-1; nM = ~M; + switch erthi + case 2, M(Q.group==2) = 0; nM(Q.group==2) = 0; + end + + if contains( QFN{fni1,2}, mriqcQFN) + Q.NXIQR = Q.(IQRfield); + else + % get thresholds + if rps + [ Q.NXIQR(M) , Q.Nmn(M) , Q.Nsd(M)] = cat_tst_qa_normer( mark2rps( Q.(IQRfield)(M) ) , ... + struct('model',model,'figure',0,'cmodel',cmodel)); + else + [ Q.NXIQR(M) , Q.Nmn(M) , Q.Nsd(M)] = cat_tst_qa_normer( Q.(IQRfield)(M) , ... + struct('model',model,'figure',0,'cmodel',cmodel)); + end + + % estimate for all values + for gi = testsites + Q.Nmn(Q.site == gi) = cat_stat_nanmean( Q.Nmn(Q.site == gi) ); + Q.Nsd(Q.site == gi) = cat_stat_nanmean( Q.Nsd(Q.site == gi) ); + end + if cmodel == 1 + if rps + Q.NXIQR = -(mark2rps(Q.(IQRfield)) - Q.Nmn); + else + Q.NXIQR = Q.(IQRfield) - Q.Nmn; + end + else + if rps + Q.NXIQR = (mark2rps(Q.(IQRfield)) - Q.Nmn ) ./ Q.Nsd; + else + Q.NXIQR = (Q.(IQRfield) - Q.Nmn ) ./ Q.Nsd; + end + end + end + + % T = motion, F = no motion, P = + TP = Q.group(M)> erth & Q.NXIQR(M) > cf{erthi}(i); TPs = sum(TP); + FP = Q.group(M)< erth & Q.NXIQR(M) > cf{erthi}(i); FPs = sum(FP); + TN = Q.group(M)< erth & Q.NXIQR(M) < cf{erthi}(i); TNs = sum(TN); + FN = Q.group(M)> erth & Q.NXIQR(M) < cf{erthi}(i); FNs = sum(FN); + + traingroup{erthi}{i} = M+1; + TPFN{erthi}{i}(M,:) = [TP FP TN FN]; + NXIQR{erthi}{i}(M,:) = Q.NXIQR(M); + + sens2{erthi}{ti}(i) = TPs ./ max(1,TPs + FNs); + spec2{erthi}{ti}(i) = TNs ./ max(1,TNs + FPs); + acc2{erthi}{ti}(i) = (TPs + TNs) / max(1,TPs + FNs + TNs + FPs); + + [~,~,~,auc2{erthi}{ti}(i)] = perfcurve( (Q.group(nM)>erth), Q.NXIQR(nM) - cf{erthi}(i), 'true'); + end + end + + + % get best value + [~,mxcci1] = max( cat_stat_nanmean([ spec2{erthi}{1} , sens2{erthi}{1} ] , 2) ); % train + [~,mxcci2] = max( cat_stat_nanmean([ spec2{erthi}{2} , sens2{erthi}{2} ] , 2) ); % test + + % prepare and write table + % --------------------------------------------------------------- + % select thresholds used for the opposite group + cfth = nan(size(Q.SIQR,1),1); + cfth(traingroup{erthi}{i}==1,1) = cf{erthi}(mxcci2); + cfth(traingroup{erthi}{i}==2,1) = cf{erthi}(mxcci1); + + % select TPFN group for the opposite group + TPFNth = nan(size(Q.SIQR,1),4); + TPFNth(traingroup{erthi}{i}==1,:) = TPFN{erthi}{mxcci2}(traingroup{erthi}{i}==1,:); + TPFNth(traingroup{erthi}{i}==2,:) = TPFN{erthi}{mxcci1}(traingroup{erthi}{i}==2,:); + + % select normalized QM for the factor defined on the opposite group + NXIQRth = nan(size(Q.SIQR,1),1); + NXIQRth(traingroup{erthi}{i}==1,:) = NXIQR{erthi}{mxcci2}(traingroup{erthi}{i}==1,:); + NXIQRth(traingroup{erthi}{i}==2,:) = NXIQR{erthi}{mxcci1}(traingroup{erthi}{i}==2,:); + + % create a table with most relevant measures + csvtable = [{ + 'Filename', 'age', 'sex', 'group', 'exgroup', 'rGMV', IQRfield, ['N' IQRfield], ... + 'traingroup', ['N' IQRfield ' threshold'], 'TP', 'FP', 'TN', 'FN'}; + spm_file( Pp0{1},'path',''), ... + num2cell(Q.age'), num2cell(Q.sex'), num2cell(Q.group0), num2cell(Q.group), num2cell(Q.rGMV), ... + num2cell(mark2rps(Q.(IQRfield))), num2cell(NXIQRth), ... + num2cell(traingroup{erthi}{i}), num2cell(cfth), ... + num2cell(TPFNth(:,1)), num2cell(TPFNth(:,2)), num2cell(TPFNth(:,3)), num2cell(TPFNth(:,4)) ; + ]; + if ~exist(fullfile(printdir,'tables'),'dir'); mkdir(fullfile(printdir,'tables')); end + fname = fullfile(printdir,'tables',sprintf('MRART_TPFN_%s_%s_%s.csv',segment{si},qaversions{qai},IQRfield)); + cat_io_csv(fname, csvtable); + cat_io_cprintf('blue',sprintf(' Save %s\n',fname)); + + % write FP and FN tables + Pm{si} = strrep( Pp0{si} , [filesep 'p0'] , [filesep 'm'] ); + TPstr = {'TP', 'FP', 'TN', 'FN'}; + EGname = {'noMA','lMA','sMA'}; + rig = {'noLight-severe','no-severe','no-lightSevere','average'}; + %% + + tdir = fullfile(printdir,'TP-FP-TN-FN',IQRfield); if ~exist(tdir,'dir'), mkdir(tdir); end + for tpi = 1:4 %[2 4] %1:numel(TPstr) + %% + subs = 35; % 24, 35, + subtable = csvtable([false; TPFNth(:,tpi)>0],:); + fname = fullfile(printdir,'TP-FP-TN-FN',IQRfield, ... + sprintf('MRART_%s_%s_%s_%s_%s.csv',segment{si},qaversions{qai}, IQRfield,rig{erthi},TPstr{tpi})); + cat_io_csv(fname, csvtable( [true; TPFNth(:,tpi)>0], : ) ); + cat_io_cprintf('blue',sprintf(' Save %s\n',fname)); + + if printslices + printimg = Pm{si}(TPFNth(:,tpi)>0); + if ~isempty(printimg) + for imgi = 1:ceil(numel(printimg)/subs) + drange = ( (imgi-1)*subs + 1):min(numel(printimg),(imgi)*subs); + txt = evalc('cat_stat_showslice_all(struct(''data_vol'',printimg(drange),''scale'',0,''slice'',30,''orient'',1))'); + fspm = spm_figure('GetWin'); fspm.Color = [0 0 0]; + fspm.Visible = 'off'; fspm.Interruptible = 'off'; + ax = gca; + % upate text + axis(ax,'equal') + axfnames = get(ax,'Children'); + for axfi = 1:min(numel(axfnames)-1,subs) + switch tpi + case 1, axfnames(axfi).Color = [1 0 0]; + case 2, axfnames(axfi).Color = [.7 1 0]; + case 3, axfnames(axfi).Color = [0 1 0]; + case 4, axfnames(axfi).Color = [1 .7 0]; + end + axfnames(axfi).FontSize = 6 / (sqrt(subs)/sqrt(24)); % need to be smaller for print + axfnames(axfi).String = [{ [spm_file(axfnames(axfi).String,'path','') ... + sprintf(' (EG=%0.0f, %s)', subtable{ axfi, 5}, EGname{subtable{ axfi, 5}})] }, ... + {sprintf('%s=%0.1f, N%s=%0.1f, TH=%0.1f, %s', ... + IQRfield, subtable{ axfi, 7}, ... + IQRfield, subtable{ axfi, 8}, ... + subtable{ axfi, 10}, TPstr{tpi} ... + )}]; + end + + % print result + fname = fullfile(printdir,'TP-FP-TN-FN',IQRfield,sprintf('MRART_%s_%s_%s_%s_%s%0.0f.png',... + segment{si},qaversions{qai}, IQRfield,rig{erthi},TPstr{tpi},imgi)); + print(fspm, fname, '-dpng',pres); + cat_io_cprintf('blue',sprintf(' Print %s\n',fname)); + end + end + end + end + %% + + + + + %% figure + % ----------------------------------------------------------------- + figure(fig); + subplot('Position',[.06 + 0.33 * ppos(erthi) 0.12 0.27 0.77],'box','on'); cla; hold on; grid on; + plot(1-spec2{erthi}{1} ,sens2{erthi}{1} ,'color',[0.8 0.0 0.6],'linewidth',0.5); + plot(1-spec2{erthi}{2} ,sens2{erthi}{2} ,'color',[0.0 0.4 0.8],'linewidth',0.5); + plot(1-mean([spec2{erthi}{1},spec2{erthi}{2}],2) ,mean([sens2{erthi}{1},sens2{erthi}{2}],2) ,'color',[0.0 0.2 0.4],'linewidth',1); + hold off; ylim([0.5 1.004]); xlim([-0.004 0.65]); ylim([0 1.0]); xlim([0 1]) + title(sprintf('ROC %s',cat_io_strrep(IQRfield,{'res_','_'},{'','\_'}))); + switch erthi + case 1, subtitle(sprintf('no vs. light/severe MAs (n=%d)',sum(M))); + case 2, subtitle(sprintf('no/light vs. severe MAs (n=%d)',sum(M))); + case 3, subtitle(sprintf('no vs. severe MAs (n=%d)',sum(M))); + end + ax = gca; ax.FontSize = FS(2)*.8; + xlabel('False positive rate (1-specificity)','FontSize',FS(2)*.9); + ylabel('True positive rate (sensitivity)','FontSize',FS(2)*.9); + lg = legend({... + sprintf('run1: AUC=%0.3f\n (th=%0.2f rps: ACC=%0.3f)', auc2{erthi}{1}(mxcci2), cf{erthi}(mxcci2), acc2{erthi}{1}(mxcci2) ),... + sprintf('run2: AUC=%0.3f\n (th=%0.2f rps: ACC=%0.3f)', auc2{erthi}{2}(mxcci1), cf{erthi}(mxcci1), acc2{erthi}{2}(mxcci1) ),... + sprintf('avg.: AUC=%0.3f\n (th=%0.2f rps: ACC=%0.3f)',... + mean([auc2{erthi}{1}(mxcci2), auc2{erthi}{2}(mxcci1)]), ... + mean([cf{erthi}(mxcci2), cf{erthi}(mxcci1)]), ... + mean([acc2{erthi}{1}(mxcci2), acc2{erthi}{2}(mxcci1)]))... + },'Location','southeast','Fontsize',FS(2)*.8); lg.Box = 'off'; + yticks(0:0.2:1); + xticks(0:0.2:1); + + end + + + % print + tdir = fullfile(printdir,'ROC'); if ~exist(tdir,'dir'), mkdir(tdir); end + fname = fullfile(tdir, sprintf('MRART_ROC_%s_%s_%s.png', strrep(IQRfield,'res_','') , qaversions{qai} , segment{si})); + print(fig, fname, '-dpng',pres); + cat_io_cprintf('blue',sprintf(' Print %s\n',fname)); + if ~verb, close(fig); end + + + %PTPFN{1}{1}{mxcci2}( TPFN{2}{1}{mxcci2}(:,2) ) %TN + %PTPFN{1}{2}{mxcci1}( TPFN{2}{1}{mxcci1}(:,3) ) %FP + + + % age dependency in normalized data + fig = figure(12); fig.Position(3:4) = [300 200]; clf; + fig.Visible = 'off'; + fig.Interruptible = 'off'; + gcol = [0 0.8 0; 0.8 0.7 0; 0.8 0 0]; hold on; + gnam = {'no','light','strong'}; + for gi = 1:max(Q.group) + sc = scatter(Q.age(Q.group==gi), Q.NXIQR(Q.group==gi), 20); + [curve1{gi}, goodness, output] = fit( Q.age(Q.group==gi)', Q.NXIQR(Q.group==gi) ,'poly1'); + set(sc,'MarkerFaceColor',gcol(gi,:),'MarkerEdgeColor',gcol(gi,:), ... + 'MarkerFaceAlpha',0.3,'MarkerEdgeAlpha',0.3); + mylegend{gi} = sprintf('%s (b=%0.3f/100a)',gnam{gi},curve1{gi}.p1 * 100); + Q.agefit.p1(gi) = curve1{gi}.p1; + end + xlim([15 85]); set(gca,'XTick',20:20:80); xlabel('age (years)'); + for gi = 1:max(Q.group) + ph = plot(curve1{gi}); + set(ph,'Color',gcol(gi,:)); + end + box on; grid on; + title(sprintf('MA groups %s (diff(good/bad)=%0.3f)', strrep(QFN{fni1,6},'_','\_'),... + abs(diff([mean(Q.(QFN{fni1,6})(Q.group==1)),mean(Q.(QFN{fni1,6})(Q.group==3))])))); + ylabel(sprintf('n%s (rps)',strrep(QFN{fni1,6},'_','\_'))); + legend(mylegend,'Location','SouthEast'); + + tdir = fullfile(printdir,'aging_n'); if ~exist(tdir,'dir'), mkdir(tdir); end + fname = fullfile(tdir, sprintf('MRART_aging_%s_%s_%s.png', strrep(QFN{fni1,6},'res_','') , qaversions{qai} , segment{si})); + print(fig, fname, '-dpng',pres); + cat_io_cprintf('blue',sprintf(' Print %s\n',fname)); + + + + + %% figure 2 + % ----------------------------------------------------------------- + fig = figure(); fig.Position(3:4) = [800 200]; + fig.Visible = 'off'; + fig.Interruptible = 'off'; + fig.Name = sprintf('MR-ART - ROC - %s',qaversions{qai}); + if ~verb, fig.Visible = 'off'; end + + for i=1:2, spec2{4}{i} = mean([spec2{1}{i},spec2{2}{i},spec2{3}{i}],2); end + for i=1:2, sens2{4}{i} = mean([sens2{1}{i},sens2{2}{i},sens2{3}{i}],2); end + for i=1:2, auc2{4}{i} = mean([auc2{1}{i},auc2{2}{i},auc2{3}{i}],2); end + for i=1:2, acc2{4}{i} = mean([acc2{1}{i},acc2{2}{i},acc2{3}{i}],2); end + cf{4} = mean([cf{1};cf{2};cf{3}],1); erths(4) = 3; + for erthi = 1:numel(erths) + % get best value + %[~,mxcci] = max( cat_stat_nanmean([ spec2{erthi}{2} , sens2{erthi}{2} ] , 2) ); % train + [~,mxcci1] = max( cat_stat_nanmean([ spec2{erthi}{1} , sens2{erthi}{1} ] , 2) ); % train + [~,mxcci2] = max( cat_stat_nanmean([ spec2{erthi}{2} , sens2{erthi}{2} ] , 2) ); % train + + + %erth = erths(erthi); % expert rating threshold for 3 groups (1=no MA, 2=light MAs, 3=severe MAs) + subplot('Position',[.045 + 1/4 * ppos(erthi) 0.12 0.20 0.74],'box','on'); cla; hold on; grid on; + plot(1-spec2{erthi}{1} ,sens2{erthi}{1} ,'color',min(1,[0.8 0.0 0.6]+.3),'linewidth',0.5); + plot(1-spec2{erthi}{2} ,sens2{erthi}{2} ,'color',min(1,[0.0 0.4 0.8]+.3),'linewidth',0.5); + plot(1-mean([spec2{erthi}{1},spec2{erthi}{2}],2) ,mean([sens2{erthi}{1},sens2{erthi}{2}],2) ,'color',[0.0 0.2 0.4],'linewidth',1); + hold off; ylim([0.5 1.004]); xlim([-0.004 0.65]); ylim([0 1.0]); xlim([0 1]) + title(sprintf('ROC %s',cat_io_strrep(IQRfield,{'res_','_'},{'','\_'}))); + switch erthi + case 1, subtitle(sprintf('no vs. light/severe MAs (n=%d)',sum(M))); + case 2, subtitle(sprintf('no/light vs. severe MAs (n=%d)',sum(M))); + case 3, subtitle(sprintf('no vs. severe MAs (n=%d)',sum(M))); + otherwise, subtitle(sprintf('average ROC of MAs',sum(M))); + end + ax = gca; ax.FontSize = FS(2)*.8; + xlabel('False positive rate (1-specificity)','FontSize',FS(2)); + ylabel('True positive rate (sensitivity)','FontSize',FS(2)); + lg = legend({ ... + sprintf('run1: AUC=%0.3f\n (th=%0.2f rps: ACC=%0.3f)', auc2{erthi}{1}(mxcci2), cf{erthi}(mxcci2), acc2{erthi}{1}(mxcci2) ),... + sprintf('run2: AUC=%0.3f\n (th=%0.2f rps: ACC=%0.3f)', auc2{erthi}{2}(mxcci1), cf{erthi}(mxcci1), acc2{erthi}{2}(mxcci1) ),... + sprintf('avg.: AUC=%0.3f\n (th=%0.2f rps: ACC=%0.3f)', ... + mean([auc2{erthi}{1}(mxcci2), auc2{erthi}{2}(mxcci1)]), ... + mean([cf{erthi}(mxcci2), cf{erthi}(mxcci1)]), ... + mean([acc2{erthi}{1}(mxcci2), acc2{erthi}{2}(mxcci1)]))... + },'Location','southeast','Fontsize',FS(2)*.8); lg.Box = 'off'; + yticks(0:0.2:1); + xticks(0:0.2:1); + + mytable.ROC{erthi} = [ mytable.ROC{erthi}; {IQRfield}, ... + {mean([auc2{erthi}{1}(mxcci2),auc2{erthi}{2}(mxcci1)])}, {mean([acc2{erthi}{1}(mxcci2), acc2{erthi}{2}(mxcci1)])} ]; + end + fprintf(' %s done.\n',IQRfield) + + + + + % print + tdir = fullfile(printdir,'ROC4_only-for-fast-evaluation'); if ~exist(tdir,'dir'), mkdir(tdir); end + fname = fullfile(tdir, sprintf('MRART_ROC4_%s_%s_%s.png', strrep(IQRfield,'res_','') , qaversions{qai} , segment{si})); + print(fig, fname, '-dpng',pres); + cat_io_cprintf('blue',sprintf(' Print %s\n',fname)); + close(fig); + end + + + + end + + + + + + %% scatter plot and correlation between dIQR and dGMV + dlim = [0 4]; + if ~fasttest + QM1 = find( contains( QFN(:,1) ,'subjectmeasures') ); + %QM1 = find( contains( QFN(:,2) ,'SPM') ); + for fni1 = 1:numel(QM1) + % * need to run for all QM compared to rGMV + % * there is a lot of normal variance :( + + %if ~exist('fig4','var'), + if verb, fig = figure(41); else, fig = figure(); end; clf; + fig.Visible = 'off'; + fig.Interruptible = 'off'; + fig.Position(3:4) = [600 200]; + fig.Name = sprintf('MR-ART - rGMV changes - %s',qaversions{qai}); + if ~verb, fig.Visible = 'off'; else, fig.Visible = 'on'; end + + QM2 = find( contains( QFN(:,1) ,'qualityratings') ); + %QM2 = [QM2 QM1]; + for fni2 = 1:numel(QM2) + dfield1 = ['d' QFN{QM1(fni1),6}]; + dfield2 = ['d' QFN{QM2(fni2),6}]; + dfield = [dfield1 '_' dfield2]; + Q.(dfield) = zeros(numel(Q.sub),1); + Q.(dfield1) = zeros(numel(Q.sub),1); + Q.(dfield2) = zeros(numel(Q.sub),1); + for sxi = 1:numel(Q.sub) + %% + subids = find(contains(Q.sub,Q.sub{sxi})); + G1 = find(Q.group0(subids)==1); + val1 = Q.(QFN{QM1(fni1),6})(subids(G1)); + val2 = Q.(QFN{QM2(fni2),6})(subids(G1)); + + Q.(dfield1)(sxi,1) = Q.(QFN{QM1(fni1),6})(sxi) - val1; + Q.(dfield2)(sxi,1) = Q.(QFN{QM2(fni2),6})(sxi) - val2; + end + + + %% robustfit + subplot('Position',[0.07 + 0.90*(fni2-1)/numel(QM2) 0.15, 0.85/numel(QM2) .7]); + + plot(dlim,[0 0],'color',[0 0 0]); hold on; + hs = scatter( Q.(dfield2)( Q.(dfield2)>0 & Q.group==3) , Q.(dfield1)(Q.(dfield2)>0 & Q.group==3)); + hs.MarkerEdgeColor = [.8 0 .2]; hs.MarkerFaceColor = hs.MarkerEdgeColor; + hs.MarkerFaceAlpha = .1; hs.MarkerEdgeAlpha = .15; hs.SizeData = 20; hs.Marker = 'v'; + hs = scatter( Q.(dfield2)( Q.(dfield2)>0 & Q.group==2) , Q.(dfield1)(Q.(dfield2)>0 & Q.group==2)); + hs.MarkerEdgeColor = [0.7 0.3 0]; hs.MarkerFaceColor = hs.MarkerEdgeColor; + hs.MarkerFaceAlpha = .1; hs.MarkerEdgeAlpha = .15; hs.SizeData = 20; hs.Marker = '^'; + ah = gca; ylim([-1,1] * max(ceil(abs(ah.YLim)*20)/20)); xlim(dlim); + ah.XTick = ah.XLim(1):round( diff([ah.XLim(1),ah.XLim(2)]) / 4 ,0):ah.XLim(2); + ah.YTick = ah.YLim(1):round( diff([ah.YLim(1),ah.YLim(2)]) / 10 ,2):ah.YLim(2); + + if fni2>1, ylabel off; ah.YTickLabel = {}; end + %Q.fit.(dfield) = fit( double(Q.(dfield2)(Q.(dfield2)>0 & Q.group==2)) , double(Q.(dfield1)(Q.(dfield2)>0 & Q.group==2)) ,'poly1'); hp = plot(Q.fit.(dfield)); hp.Color = [0 0.5 0]; + %Q.fit.(dfield) = fit( double(Q.(dfield2)(Q.(dfield2)>0 & Q.group==3)) , double(Q.(dfield1)(Q.(dfield2)>0 & Q.group==3)) ,'poly1'); hp = plot(Q.fit.(dfield)); hp.Color = [0.5 0 0]; + try + Q.fit.(dfield) = fit( double(Q.(dfield2)(Q.(dfield2)>0 & ~isnan(Q.(dfield1)) & ~isnan(Q.(dfield2)))) , ... + double(Q.(dfield1)( Q.(dfield2)>0 & ~isnan(Q.(dfield1)) & ~isnan(Q.(dfield2)))) ,'poly1'); + hp = plot(Q.fit.(dfield)); hp.Color = [0.6 0 0]; + legend off; grid on; box on; + if fni2==1, ylabel([QFN{QM1(fni1),6} ' change ']); else, ylabel(''); end + xlabel(strrep(dfield2,'_','\_')); + subtitle(sprintf('%0.3f',Q.fit.(dfield).p1)); + end + title(sprintf('%s change',strrep(QFN{QM2(fni2),2},'_','\_'))) + end + + tdir = fullfile(printdir,'rGMVchanges'); if ~exist(tdir,'dir'), mkdir(tdir); end + fname = fullfile(tdir, sprintf('MRART_%s_%s_%s.png', ['d' QFN{QM1(fni1),6}] , qaversions{qai}, segment{si} )); + print(fig, fname, '-dpng',pres); + cat_io_cprintf('blue',sprintf(' Print %s\n',fname)); + if ~verb, close(fig); end + end + end + + %% + rig = {'no-lightSevere','noLight-severe','no-severe','average'}; + for ri = 1:4 + fname = fullfile( printdir , sprintf('MRART_ROC%d%s_%s_%s_%s.csv', ri, rig{ri}, strrep(IQRfield,'res_','') , qaversions{qai} , segment{si})); + cat_io_csv( fname , mytable.ROC{ri} ) ; + cat_io_cprintf('blue',sprintf(' Save %s\n',fname)); + end + fname = fullfile( printdir , sprintf('MRART_ANOVA_%s_%s_%s.csv', strrep(IQRfield,'res_','') , qaversions{qai}, segment{si})); + cat_io_csv( fname , mytable.ANOVA ); + cat_io_cprintf('blue',sprintf(' Save %s\n',fname)); + + fprintf('%s done.\n',segment{si}) + end + + + + + %% MRART kappa + % ====================================================================== + if ~fasttest + opt.resdirART = fullfile(datadir,'+results', ... + sprintf('%s_%s_%s', 'MR-ART', fast{fasttest+1}, '202508' )); %f datestr(clock,'YYYYmm')) ); + for ssi = 1:numel(xml) + subID{ssi} = xml(ssi).filedata.file(5:10); + BL(ssi) = contains(xml(ssi).filedata.file,'standard'); + P.ARTfilesp0{ssi} = cat_io_strrep( xml(ssi).filedata.Fp0, ... + {'ds004173-download','mri'}, ... + {fullfile('ds004173-download','derivatives','CAT12.9'),''}); + end + + segmentname = cat_io_strrep(segment{si},{'CAT','SPM'},{'','spm_'}); + BWPkappaname = cat_io_strrep(segment{si},{'CAT','SPM'},{'CAT12','SPM12'}); + P.ARTfilesX = spm_file( strrep(P.ARTfilesp0,{['mri' filesep 'p0']},{['report' filesep qaversions{qai},'_' segmentname]}) ,'ext','xml'); + tmp = cat_vol_findfiles(fullfile(opt.resdirART,sprintf('mrart_kappa_NIR%d_%s.mat',numel(P.ARTfilesX),BWPkappaname))); + if ~isempty(tmp), P.ARTkappamat = tmp{1}; else, P.ARTkappamat = ''; end + if ~exist(P.ARTkappamat,'file') + P.ARTkappamat = fullfile(opt.resdirART,sprintf('mrart_kappa_NIR%d_%s.mat',numel(P.ARTfilesX),BWPkappaname)); + for ssi = 1:numel( P.ARTfilesp0) % only first dim! + BLsiID(ssi) = find( contains( subID , subID{ssi}) & BL == 1); + end + + [~,val] = eva_vol_calcKappa(P.ARTfilesp0 ,P.ARTfilesp0(BLsiID) ,struct('recalc',0,'realign',2,'realignres',2)); + if ~exist(opt.resdirART,'dir'), mkdir(opt.resdirART); end + save(P.ARTkappamat,'val'); + Q.kappa = cat_stat_nanmean(real(cell2mat(val(2:end-2,2:4))),2); + else + S = load(P.ARTkappamat); + Q.kappa = cat_stat_nanmean(real(cell2mat(S.val(2:end-2,2:4))),2); + end + end + + + + + %% correlation plot of all my measures to mriqc measures + % ====================================================================== + fprintf('Correlation table.\n'); + fh = figure(33); fh.Visible = 'on'; + corrtype = {'Spearman','Pearson'}; + subsetname = {'allQM', 'selectQM', 'selectQM2'}; + for ci = 1:numel(corrtype) + for subset = 1:3 + clear R RP; clf(fh) + switch subset + case 1 + base = {'age', 'sex','group0','group'}; + bcat = {'rCSFV','rGMV','rWMV','drCSFV','drGMV','drWMV','kappa'}; + FLDs = [base, bcat, QFN(1:5,2)', mriqcQFN]; + fh.Position(3:4) = [1050 1000]; + case 2 % smaller subset with QC MA focus + base = {'age','sex','group0','group'}; + bcat = {'rCSFV','rGMV','rWMV','drGMV','drGMV','drWMV','kappa'}; + FLDs = [base, bcat, QFN(1:5,2)', mriqcQFN([1 2 3 4, 5:7, 22 23 ,34 35, 60:62]), ]; + fh.Position(3:4) = [550 500]; + case 3 % smaller subset with QC side effects on individual data + base = {'group'}; + bcat = {'drGMV','kappa'}; + FLDs = [base, bcat, QFN(1:5,2)', mriqcQFN([1 2 22 23 34 35]), ]; + fh.Position(3:4) = [450 400]; + end + fh.Name = sprintf('MRART_ANOVA_%s_%s_%s_%s', ... + qaversions{qai}, segment{si}, subsetname{subset}, corrtype{ci} ); + + for mriqci = 1:numel(FLDs) + for mriqcj = 1:numel(FLDs) + if isfield( Q, FLDs{mriqcj}) + if size(Q.(FLDs{mriqcj}),1) > 1 + if size(Q.(FLDs{mriqci}),1) > 1 + [R(mriqci,mriqcj),RP(mriqci,mriqcj)] = corr( Q.(FLDs{mriqci}) , Q.(FLDs{mriqcj}) , 'Type', corrtype{ci}); + else + [R(mriqci,mriqcj),RP(mriqci,mriqcj)] = corr( Q.(FLDs{mriqci})' , Q.(FLDs{mriqcj}) , 'Type', corrtype{ci}); + end + else + if size(Q.(FLDs{mriqci}),1) > 1 + [R(mriqci,mriqcj),RP(mriqci,mriqcj)] = corr( Q.(FLDs{mriqci}) , Q.(FLDs{mriqcj})' , 'Type', corrtype{ci}); + else + [R(mriqci,mriqcj),RP(mriqci,mriqcj)] = corr( Q.(FLDs{mriqci})' , Q.(FLDs{mriqcj})' , 'Type', corrtype{ci}); + end + end + end + end + end + imagesc(abs(R)); box off; hold on; % .^2 + + if ~exist(fullfile(printdir,'corrs'),'dir'), mkdir(fullfile(printdir,'corrs')); end + mytable.corrR{ci,subset} = [ {''} FLDs; FLDs', num2cell(R)]; + fname = fullfile( printdir , 'corrs', sprintf('MRART_CORR_%s_set%0.0f_%s_%s.csv', corrtype{ci}, subset , qaversions{qai}, segment{si})); + cat_io_csv( fname , mytable.corrR{ci,subset} ); + cat_io_cprintf('blue',sprintf(' Save %s\n',fname)); + mytable.corrR{ci,subset} = [ {''} FLDs; FLDs', num2cell(RP)]; + fname = fullfile( printdir , 'corrs', sprintf('MRART_CORRp_%s_set%0.0f_%s_%s.csv', corrtype{ci}, subset , qaversions{qai}, segment{si})); + cat_io_csv( fname , mytable.corrR{ci,subset} ); + cat_io_cprintf('blue',sprintf(' Save %s\n',fname)); + + % set axis and labels + ax = gca; + ax.TickLabelInterpreter = 'none'; + ax.TickLength = [0 0]; + ax.XTick = 1:numel(R); ax.XTickLabel = FLDs; ax.XTickLabelRotation = 90; + ax.YTick = 1:numel(R); ax.YTickLabel = FLDs; + + % lines + px = [numel(base) + [0.5;0.5], ... + numel(base) + numel(bcat) + [0.5;0.5], ... + numel(base) + numel(bcat) + 5 + [0.5;0.5] + ]; + py = [0 0 0; size(R,1)+1 size(R,1)+1 size(R,1)+1]; + plot(px,py,'w','LineWidth',3); plot(py,px,'w','LineWidth',3); + + % smaller lines + px = [2 + [0.5;0.5], ... + numel(base) + 3 + [0.5;0.5], ... + numel(base) + 6 + [0.5;0.5], ... + numel(base) + numel(bcat) + 5 + [0.5;0.5], ... + find(contains(FLDs,'icvs_csf')) - [0.5;0.5], ... + find(contains(FLDs,'wm2max')) + [0.5;0.5], ... + find(contains(FLDs,'fwhm_avg')) - [0.5;0.5], ... + find(contains(FLDs,'icvs_csf')) - [0.5;0.5], ... + find(contains(FLDs,'inu_med')) - [0.5;0.5], ... + find(contains(FLDs,'rpve_csf')) - [0.5;0.5], ... + find(contains(FLDs,'snr_csf')) - [0.5;0.5], ... + find(contains(FLDs,'snrd_csf')) - [0.5;0.5], ... + find(contains(FLDs,'summary_bg_k')) - [0.5;0.5], ... + find(contains(FLDs,'summary_gm_k')) - [0.5;0.5], ... + find(contains(FLDs,'summary_csf_k')) - [0.5;0.5], ... + find(contains(FLDs,'summary_gm_k')) - [0.5;0.5], ... + find(contains(FLDs,'summary_wm_k')) - [0.5;0.5], ... + find(contains(FLDs,'tpm_overlap_csf')) - [0.5;0.5], ... + ]; + py = [zeros(1,size(px,2)); repmat( size(R,1)+1, 1, size(px,2))]; + plot(px,py,'w','LineWidth',.5); plot(py,px,'w','LineWidth',.5); + + % title and axis names + title('CAT12 quality ratings and MRIQC quality measures'); + subtitle(sprintf('%s correlation',corrtype{ci})); + xlabel('measures'); ylabel('measures'); + colorbar + colormap jet + + ffh = fullfile(fullfile(printdir,'corrs'),[fh.Name '.jpg']); + print(fh, '-djpeg', '-r300', ffh); + cat_io_cprintf('blue',' Write %s\n',ffh); + end + end + + %% EFC plot for reviewer 3 + fh = figure(33); %fh.Visible = 'on'; + for QMX = {'ECR','ICR'} + clf(fh) + sc = scatter(Q.(strrep(QMX{1},'ECR','res_ECR')),Q.efc,'filled','MarkerFaceAlpha',.5); + title(sprintf('Spearman correlation between %s and EFC = %0.4f',QMX{1},corr(Q.(strrep(QMX{1},'ECR','res_ECR')),Q.efc,'Type','Spearman'))); + fh.Name = sprintf('rho_%s_EFC',QMX{1}); + box on; grid on; + xlabel('ECR'); ylabel('EFC'); + ffh = fullfile(fullfile(printdir,'corrs'),[fh.Name '.jpg']); + print(fh, '-djpeg', '-r300',ffh); + cat_io_cprintf('blue',' Write %s\n',ffh); + end + + %% + if 0 + fh = figure(33); fh.Visible = 'on'; clf(fh) + sc = scatter(Q.res_ECR,Q.kappa,'filled','MarkerFaceAlpha',.5); + box on; grid on; + end +end +fprintf('all done.\n') +warning on + +","MATLAB" +"Neurology","ChristianGaser/cat12","catQC/SPMpreprocessing4qc.m",".m","2691","44","%----------------------------------------------------------------------- +% Job saved on 07-Mar-2025 14:46:45 by cfg_util (rev $Rev: 8183 $) +% spm SPM - SPM25 (25.01.02) +% cfg_basicio BasicIO - Unknown +%----------------------------------------------------------------------- +matlabbatch{1}.spm.spatial.preproc.channel.vols = ''; +matlabbatch{1}.spm.spatial.preproc.channel.biasreg = 0.0001; +matlabbatch{1}.spm.spatial.preproc.channel.biasfwhm = 60; +matlabbatch{1}.spm.spatial.preproc.channel.write = [0 1]; +matlabbatch{1}.spm.spatial.preproc.tissue(1).tpm = {fullfile(spm('dir'),'tpm','TPM.nii,1')}; +matlabbatch{1}.spm.spatial.preproc.tissue(1).ngaus = 1; +matlabbatch{1}.spm.spatial.preproc.tissue(1).native = [1 0]; +matlabbatch{1}.spm.spatial.preproc.tissue(1).warped = [0 0]; +matlabbatch{1}.spm.spatial.preproc.tissue(2).tpm = {fullfile(spm('dir'),'tpm','TPM.nii,2')}; +matlabbatch{1}.spm.spatial.preproc.tissue(2).ngaus = 1; +matlabbatch{1}.spm.spatial.preproc.tissue(2).native = [1 0]; +matlabbatch{1}.spm.spatial.preproc.tissue(2).warped = [0 0]; +matlabbatch{1}.spm.spatial.preproc.tissue(3).tpm = {fullfile(spm('dir'),'tpm','TPM.nii,3')}; +matlabbatch{1}.spm.spatial.preproc.tissue(3).ngaus = 2; +matlabbatch{1}.spm.spatial.preproc.tissue(3).native = [1 0]; +matlabbatch{1}.spm.spatial.preproc.tissue(3).warped = [0 0]; +matlabbatch{1}.spm.spatial.preproc.tissue(4).tpm = {fullfile(spm('dir'),'tpm','TPM.nii,4')}; +matlabbatch{1}.spm.spatial.preproc.tissue(4).ngaus = 3; +matlabbatch{1}.spm.spatial.preproc.tissue(4).native = [0 0]; +matlabbatch{1}.spm.spatial.preproc.tissue(4).warped = [0 0]; +matlabbatch{1}.spm.spatial.preproc.tissue(5).tpm = {fullfile(spm('dir'),'tpm','TPM.nii,5')}; +matlabbatch{1}.spm.spatial.preproc.tissue(5).ngaus = 4; +matlabbatch{1}.spm.spatial.preproc.tissue(5).native = [0 0]; +matlabbatch{1}.spm.spatial.preproc.tissue(5).warped = [0 0]; +matlabbatch{1}.spm.spatial.preproc.tissue(6).tpm = {fullfile(spm('dir'),'tpm','TPM.nii,6')}; +matlabbatch{1}.spm.spatial.preproc.tissue(6).ngaus = 2; +matlabbatch{1}.spm.spatial.preproc.tissue(6).native = [0 0]; +matlabbatch{1}.spm.spatial.preproc.tissue(6).warped = [0 0]; +matlabbatch{1}.spm.spatial.preproc.warp.mrf = 1; +matlabbatch{1}.spm.spatial.preproc.warp.cleanup = 1; +matlabbatch{1}.spm.spatial.preproc.warp.reg = [0 0 0.1 0.01 0.04]; +matlabbatch{1}.spm.spatial.preproc.warp.affreg = 'mni'; +matlabbatch{1}.spm.spatial.preproc.warp.fwhm = 0; +matlabbatch{1}.spm.spatial.preproc.warp.samp = 3; +matlabbatch{1}.spm.spatial.preproc.warp.write = [0 0]; +matlabbatch{1}.spm.spatial.preproc.warp.vox = NaN; +matlabbatch{1}.spm.spatial.preproc.warp.bb = [NaN NaN NaN + NaN NaN NaN]; +","MATLAB" +"Neurology","ChristianGaser/cat12","check_pipeline/batch_surface_pipeline.m",".m","10154","107","function batch_surface_pipeline + +pth = pwd; + +spm_jobman('initcfg'); + +%__________________________________________________________________________ +matlabbatch{1}.spm.tools.cat.stools.surfextract.data_surf = { + fullfile(pth,'surf/lh.central.IXI002-Guys-0828-T1.gii') + fullfile(pth,'surf/lh.central.IXI016-Guys-0697-T1.gii') + fullfile(pth,'surf/lh.central.IXI017-Guys-0698-T1.gii') + fullfile(pth,'surf/lh.central.IXI019-Guys-0702-T1.gii') + }; +matlabbatch{1}.spm.tools.cat.stools.surfextract.GI = 1; +matlabbatch{1}.spm.tools.cat.stools.surfextract.FD = 0; +matlabbatch{1}.spm.tools.cat.stools.surfextract.SD = 0; +matlabbatch{1}.spm.tools.cat.stools.surfextract.nproc = 0; +%__________________________________________________________________________ +matlabbatch{2}.spm.tools.cat.stools.surfresamp.data_surf(1) = cfg_dep('Extract additional surface parameters: Left MNI gyrification', substruct('.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('()',{1}, '.','lPGI', '()',{':'})); +matlabbatch{2}.spm.tools.cat.stools.surfresamp.merge_hemi = 1; +matlabbatch{2}.spm.tools.cat.stools.surfresamp.mesh32k = 1; +matlabbatch{2}.spm.tools.cat.stools.surfresamp.fwhm_surf = 12; +matlabbatch{2}.spm.tools.cat.stools.surfresamp.nproc = 0; +%__________________________________________________________________________ +matlabbatch{3}.spm.tools.cat.tools.check_homogeneity.data{1}(1) = cfg_dep('Resample and Smooth Surface Data: Merged resampled MNIgyrification', substruct('.','val', '{}',{2}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','sample', '()',{1}, '.','Psdata')); +matlabbatch{3}.spm.tools.cat.tools.check_homogeneity.sel_xml.data_xml = { + fullfile(pth,'report/cat_IXI002-Guys-0828-T1.xml') + fullfile(pth,'report/cat_IXI016-Guys-0697-T1.xml') + fullfile(pth,'report/cat_IXI017-Guys-0698-T1.xml') + fullfile(pth,'report/cat_IXI019-Guys-0702-T1.xml') + }; +matlabbatch{3}.spm.tools.cat.tools.check_homogeneity.c = cell(1, 0); +%__________________________________________________________________________ +matlabbatch{4}.spm.tools.cat.stools.surf2roi.cdata{1}(1) = cfg_dep('Extract additional surface parameters: Left MNI gyrification', substruct('.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('()',{1}, '.','lPGI', '()',{':'})); +matlabbatch{4}.spm.tools.cat.stools.surf2roi.rdata = {fullfile(spm('dir'),'toolbox','cat12','atlases_surfaces/lh.aparc_DK40.freesurfer.annot')}; +%__________________________________________________________________________ +matlabbatch{5}.spm.tools.cat.tools.T2x_surf.data_T2x = {fullfile(pth,'analysis/surface/spmT_0002.gii')}; +matlabbatch{5}.spm.tools.cat.tools.T2x_surf.conversion.sel = 2; +matlabbatch{5}.spm.tools.cat.tools.T2x_surf.conversion.threshdesc.uncorr.thresh001 = 0.001; +matlabbatch{5}.spm.tools.cat.tools.T2x_surf.conversion.inverse = 0; +matlabbatch{1}.spm.tools.cat.tools.T2x_surf.conversion.cluster.none = 1; +%__________________________________________________________________________ +matlabbatch{6}.spm.tools.cat.tools.F2x_surf.data_F2x = {fullfile(pth,'analysis/surface/spmF_0001.gii')}; +matlabbatch{6}.spm.tools.cat.tools.F2x_surf.conversion.sel = 2; +matlabbatch{6}.spm.tools.cat.tools.F2x_surf.conversion.threshdesc.uncorr.thresh001 = 0.001; +matlabbatch{6}.spm.tools.cat.tools.F2x_surf.conversion.cluster.none = 1; +%__________________________________________________________________________ +matlabbatch{7}.spm.tools.cat.tools.calcvol.data_xml = { + fullfile(pth,'report/cat_IXI002-Guys-0828-T1.xml') + fullfile(pth,'report/cat_IXI016-Guys-0697-T1.xml') + fullfile(pth,'report/cat_IXI017-Guys-0698-T1.xml') + fullfile(pth,'report/cat_IXI019-Guys-0702-T1.xml') + }; +matlabbatch{7}.spm.tools.cat.tools.calcvol.calcvol_TIV = 1; +matlabbatch{7}.spm.tools.cat.tools.calcvol.calcvol_name = 'TIV.txt'; +%__________________________________________________________________________ + +matlabbatch{8}.spm.tools.cat.stools.vol2surf.data_vol = {fullfile(pth,'IXI002-Guys-0828-T1.nii,1')}; +matlabbatch{8}.spm.tools.cat.stools.vol2surf.data_mesh_lh = {fullfile(pth,'surf/lh.central.IXI002-Guys-0828-T1.gii')}; +matlabbatch{8}.spm.tools.cat.stools.vol2surf.sample = {'maxabs'}; +matlabbatch{8}.spm.tools.cat.stools.vol2surf.interp = {'linear'}; +matlabbatch{8}.spm.tools.cat.stools.vol2surf.datafieldname = 'intensity'; +matlabbatch{8}.spm.tools.cat.stools.vol2surf.mapping.rel_equivol_mapping.class = 'GM'; +matlabbatch{8}.spm.tools.cat.stools.vol2surf.mapping.rel_equivol_mapping.startpoint = -0.6; +matlabbatch{8}.spm.tools.cat.stools.vol2surf.mapping.rel_equivol_mapping.steps = 7; +matlabbatch{8}.spm.tools.cat.stools.vol2surf.mapping.rel_equivol_mapping.endpoint = 0.6; +%_____________________________________________________________ +matlabbatch{9}.spm.tools.cat.stools.renderresults.cdata(1) = cfg_dep('Threshold and transform spmT surfaces: Transform & Threshold spm surfaces', substruct('.','val', '{}',{5}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','Pname')); +matlabbatch{9}.spm.tools.cat.stools.renderresults.render.surface = 1; +matlabbatch{9}.spm.tools.cat.stools.renderresults.render.view = 1; +matlabbatch{9}.spm.tools.cat.stools.renderresults.render.texture = 1; +matlabbatch{9}.spm.tools.cat.stools.renderresults.render.transparency = 1; +matlabbatch{9}.spm.tools.cat.stools.renderresults.render.colormap = 1; +matlabbatch{9}.spm.tools.cat.stools.renderresults.render.invcolormap = 0; +matlabbatch{9}.spm.tools.cat.stools.renderresults.render.background = 1; +matlabbatch{9}.spm.tools.cat.stools.renderresults.render.showfilename = 1; +matlabbatch{9}.spm.tools.cat.stools.renderresults.stat.threshold = 0; +matlabbatch{9}.spm.tools.cat.stools.renderresults.stat.hide_neg = 0; +matlabbatch{9}.spm.tools.cat.stools.renderresults.fparts.outdir = {''}; +matlabbatch{9}.spm.tools.cat.stools.renderresults.fparts.prefix = 'render_'; +matlabbatch{9}.spm.tools.cat.stools.renderresults.fparts.suffix = ''; +%__________________________________________________________________________ +matlabbatch{10}.cfg_basicio.file_dir.file_ops.file_move.files(1) = cfg_dep('Extract additional surface parameters: Left MNI gyrification', substruct('.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('()',{1}, '.','lPGI', '()',{':'})); +matlabbatch{10}.cfg_basicio.file_dir.file_ops.file_move.files(2) = cfg_dep('Resample and Smooth Surface Data: Merged resampled MNIgyrification', substruct('.','val', '{}',{2}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','sample', '()',{1}, '.','Psdata')); +matlabbatch{10}.cfg_basicio.file_dir.file_ops.file_move.files(3) = cfg_dep('Extract ROI-based surface values: Extracted Surface ROIs', substruct('.','val', '{}',{4}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('()',{1}, '.','xmlname', '()',{':'})); +matlabbatch{10}.cfg_basicio.file_dir.file_ops.file_move.files(4) = cfg_dep('Threshold and transform spmT surfaces: Transform & Threshold spm surfaces', substruct('.','val', '{}',{5}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','Pname')); +matlabbatch{10}.cfg_basicio.file_dir.file_ops.file_move.files(5) = cfg_dep('Threshold and transform spmF surfaces: Transform & Threshold spm surfaces', substruct('.','val', '{}',{6}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','Pname')); +matlabbatch{10}.cfg_basicio.file_dir.file_ops.file_move.files(6) = cfg_dep('Map Volume (Native Space) to Individual Surface: Left mapped values', substruct('.','val', '{}',{8}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','lh')); +matlabbatch{10}.cfg_basicio.file_dir.file_ops.file_move.files(7) = cfg_dep('Map Volume (Native Space) to Individual Surface: Right mapped values', substruct('.','val', '{}',{8}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','rh')); +matlabbatch{10}.cfg_basicio.file_dir.file_ops.file_move.action.delete = false; +%__________________________________________________________________________ +spm_jobman('run',matlabbatch); +%__________________________________________________________________________ + +%__________________________________________________________________________ +cat_stat_analyze_ROIs(fullfile(pth,'analysis/surface/SPM.mat'), 0.05, 1); + +%__________________________________________________________________________ +clear matlabbatch +matlabbatch{1}.cfg_basicio.file_dir.file_ops.file_fplist.dir = {pth}; +matlabbatch{1}.cfg_basicio.file_dir.file_ops.file_fplist.filter = 'logP|png|gyrification'; +matlabbatch{1}.cfg_basicio.file_dir.file_ops.file_fplist.rec = 'FPListRec'; +matlabbatch{2}.cfg_basicio.file_dir.file_ops.file_move.files(1) = cfg_dep('File Selector (Batch Mode): Selected Files', substruct('.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','files')); +matlabbatch{2}.cfg_basicio.file_dir.file_ops.file_move.action.delete = false; +spm_jobman('run',matlabbatch); + +","MATLAB" +"Neurology","ChristianGaser/cat12","check_pipeline/batch_volume_pipeline.m",".m","4443","80","function batch_volume_pipeline + +pth=pwd; + +spm_jobman('initcfg'); + +matlabbatch{1}.spm.tools.cat.tools.calcvol.data_xml = { + fullfile(pth,'report/cat_IXI002-Guys-0828-T1.xml') + fullfile(pth,'report/cat_IXI016-Guys-0697-T1.xml') + fullfile(pth,'report/cat_IXI017-Guys-0698-T1.xml') + fullfile(pth,'report/cat_IXI019-Guys-0702-T1.xml') + }; +matlabbatch{1}.spm.tools.cat.tools.calcvol.calcvol_TIV = 1; +matlabbatch{1}.spm.tools.cat.tools.calcvol.calcvol_name = 'TIV.txt'; + +%__________________________________________________________________________ +matlabbatch{2}.spm.tools.cat.tools.check_homogeneity.data = { + { + fullfile(pth,'mri/mwp1IXI002-Guys-0828-T1.nii,1') + fullfile(pth,'mri/mwp1IXI016-Guys-0697-T1.nii,1') + fullfile(pth,'mri/mwp1IXI017-Guys-0698-T1.nii,1') + fullfile(pth,'mri/mwp1IXI019-Guys-0702-T1.nii,1') + } + }'; +matlabbatch{2}.spm.tools.cat.tools.check_homogeneity.sel_xml.data_xml = { + fullfile(pth,'report/cat_IXI002-Guys-0828-T1.xml') + fullfile(pth,'report/cat_IXI016-Guys-0697-T1.xml') + fullfile(pth,'report/cat_IXI017-Guys-0698-T1.xml') + fullfile(pth,'report/cat_IXI019-Guys-0702-T1.xml') + }; +matlabbatch{2}.spm.tools.cat.tools.check_homogeneity.c{1}(1) = cfg_dep('Estimate TIV and global tissue volumes: TIV', substruct('.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','calcvol')); + +%__________________________________________________________________________ +matlabbatch{3}.spm.tools.cat.tools.T2x.data_T2x = {fullfile(pth,'analysis/volume/spmT_0002.nii,1')}; +matlabbatch{3}.spm.tools.cat.tools.T2x.conversion.sel = 2; +matlabbatch{3}.spm.tools.cat.tools.T2x.conversion.threshdesc.uncorr.thresh001 = 0.001; +matlabbatch{3}.spm.tools.cat.tools.T2x.conversion.inverse = 1; +matlabbatch{3}.spm.tools.cat.tools.T2x.conversion.cluster.fwe2.thresh05 = 0.05; +matlabbatch{3}.spm.tools.cat.tools.T2x.conversion.cluster.fwe2.noniso = 1; +matlabbatch{3}.spm.tools.cat.tools.T2x.atlas = 'Neuromorphometrics'; + +%__________________________________________________________________________ +matlabbatch{4}.spm.tools.cat.tools.F2x.data_F2x = {fullfile(pth,'analysis/volume/spmF_0001.nii,1')}; +matlabbatch{4}.spm.tools.cat.tools.F2x.conversion.sel = 2; +matlabbatch{4}.spm.tools.cat.tools.F2x.conversion.threshdesc.uncorr.thresh001 = 0.001; +matlabbatch{4}.spm.tools.cat.tools.F2x.conversion.cluster.fwe2.thresh05 = 0.05; +matlabbatch{4}.spm.tools.cat.tools.F2x.conversion.cluster.fwe2.noniso = 1; +matlabbatch{4}.spm.tools.cat.tools.F2x.atlas = 'Neuromorphometrics'; + +%__________________________________________________________________________ +spm_jobman('run',matlabbatch); +%__________________________________________________________________________ + +OV.reference_image = char(cat_get_defaults('extopts.shootingT1')); +OV.reference_range = [0.2 1.0]; % intensity range for reference image +OV.opacity = Inf; % transparence value for overlay (<1) +OV.cmap = jet; % colormap for overlay +OV.name = char(fullfile(pth,'analysis/volume/logP_neg_p0.1_pkFWE5_k317_bi.nii')); +OV.range =[[3 6]]; +OV.slices_str = char('-20:5:45'); +OV.transform = char('coronal'); +OV.atlas = 'none'; +OV.xy = [3 5]; +OV.save = 'result.png'; +OV.labels.format = '%3.1f'; +cat_vol_slice_overlay(OV) + +%__________________________________________________________________________ +cat_stat_analyze_ROIs(fullfile(pth,'analysis/volume/SPM.mat'), 0.05, 1); + +%__________________________________________________________________________ +clear matlabbatch +matlabbatch{1}.cfg_basicio.file_dir.file_ops.file_fplist.dir = {pth}; +matlabbatch{1}.cfg_basicio.file_dir.file_ops.file_fplist.filter = 'logP|png|gyrification'; +matlabbatch{1}.cfg_basicio.file_dir.file_ops.file_fplist.rec = 'FPListRec'; +matlabbatch{2}.cfg_basicio.file_dir.file_ops.file_move.files(1) = cfg_dep('File Selector (Batch Mode): Selected Files', substruct('.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','files')); +matlabbatch{2}.cfg_basicio.file_dir.file_ops.file_move.action.delete = false; +spm_jobman('run',matlabbatch); + +","MATLAB" +"Neurology","artdillon/AI_CDM_for_ICH","1_b.py",".py","973","38","import pandas as pd +from sklearn.linear_model import LogisticRegression + +# 读取数据 +df1 = pd.read_csv('表1.csv') +df2 = pd.read_csv('表2.csv') +df3 = pd.read_csv('表3.csv') + +# 提取前100例患者的数据 +df1_train = df1.loc[df1['ID'].isin(range(1, 101)), :] +df2_train = df2.loc[df2['ID'].isin(range(1, 101)), :] +df3_train = df3.loc[df3['ID'].isin(range(1, 101)), :] + +# 合并为训练集 +train = pd.concat([df1_train, df2_train, df3_train], axis=1) + +# 模型训练 +X_train = train.loc[:, '年龄':'Kurtosis'] # 特征 +y_train = train['是否发生血肿扩张'] # 目标变量 + +lr = LogisticRegression() +lr.fit(X_train, y_train) + +# 所有患者数据 +df1_all = df1 +df2_all = df2 +df3_all = df3 + +# 预测 +X_all = df1_all.merge(df2_all, on='ID').merge(df3_all, on='ID') +X_all = X_all.loc[:, '年龄':'Kurtosis'] + +prob = lr.predict_proba(X_all)[:,1] + +# 写入表4 +df4 = pd.read_csv('表4.csv') +df4['血肿扩张预测概率'] = prob +df4.to_csv('表4.csv', index=False)","Python" +"Neurology","artdillon/AI_CDM_for_ICH","main.py",".py","21","1","print(""Hello World!"")","Python"