Friday, 21 August 2015

Unix commands

Queue commands

echo 'command1 --option arg1 arg2' | at -q b -m now
echo 'command2 ...' | at -q b -m now

Tuesday, 14 April 2015

TBSS preparation

ExploreDTI to set up files for RA/AD

Open matlab by typing matlab into terminal

Go up in current directory to find the folder ‘exploredti’ then go into it and drag and drop ‘source’ and ‘MainExploreDTI’ into terminal.

Type MainExploreDTI

-          ‘plugins’ – ‘export stuff to *.nii files’ – select ‘multiple’- select ‘FA/largest eigenvalue’-  select ‘MD/Radial/transverse diffusivity’ – ‘ok’
S    Select file containing mat files and then select files to save the files in.


- - This will produce nifti files for the measures that you have selected.

     TBSS


      http://fsl.fmrib.ox.ac.uk/fsl/fslwiki/TBSS/UserGuide


All data should be in NIFTI format and corrected for the effects of eddy current distortions and head motion.

Make directories called 'TBSSmain' and inside that 'mytbss'
Copy FA nifti files into mytbss
Navigate into 'mytbss'

Preprocessing


-    %tbss_1_preproc *.nii
-         % tbss_2_reg -T 
-         %  tbss_3_postreg –S

-          %  tbss_4_prestats 0.2

n    These commands perform a non-linear registration and affine transformation into MNI space using the non-linear registration tool. This creates mean FA and skeletonised images.
S   See TBSS UserGuide for other options.

Freesurfer longitudinal processing stream

https://surfer.nmr.mgh.harvard.edu/fswiki/LongitudinalProcessing

https://surfer.nmr.mgh.harvard.edu/fswiki/FsTutorial/LongitudinalTutorial

1. Cross-sectionally process your data (recon-all)

2. Create template for all timepoints for each subject.

recon-all -base <templateid> -tp <tp1id> -tp <tp2id> ... -all

3. Longitudinally process all timepoints

  recon-all -long <tpNid> <templateid> -all

4. Inspect the base and longitudinal data




Wednesday, 25 March 2015

DTI preparation for TBSS analysis

Before anything else you need to be sure that the data you need (diffusion and T1 images) have all been retrieved from Dougal into /data/blinded and contain no duplicates.
1) LOGIN IN TO ONE OF THE LINUX SERVERS (nanlnx1, nanlnx2,...)
% ssh kxxxxxxx@nanlnx1.iop.kcl.ac.uk
2) ADD THE NBL MODULE (THIS WILL SET UP YOU ENVIRONMENT SO YOU CAN RUN THE PIPELINE COMMANDS)
%  module add /home/k1339392/software/nbl /etc/nblmodule
3) CREATE THE FOLDERS FOR YOUR PROJECT (i.e. DRUM_PROJECT)
% mkdir ~/DRUM_PROJECT
% mkdir ~/DRUM_PROJECT/nandata
% mkdir ~/DRUM_PROJECT/dtidata
% mkdir ~/DRUM_PROJECT/expdtidata
% cd ~/DRUM_PROJECT
% ls
4) GET THE DATA FROM DOUGAL (add new folders with NIFTI data to ./nandata with NIFTI data)
% getnandata /data/blinded/CNSCNSD ./nandata DRUMPILOT01
% ls ./nandata
5) PREPARE DTI DATA FOR PREPROCESSING ( adds *.nii.gz *.bvec *.bval _mask.nii.gz files to ./dtidata). Use -C option if your data was acquired in the old CNS scanner using the 32 directions pulse sequence (i.e. BRCATLAS and MIAMRC projects).
% prepdti -C  ./nandata ./dtidata DRUMPILOT01 DTI_2mm_60B1500_FDA
% ls ./dtidata
6) PREPARE T1 DATA REQUIRED FOR EPI CORRECTION (adds new _T1.nii.gz _T1_mask.nii.gz files to ./dtidata)
% prept  ./nandata ./dtidata DRUMPILOT01 MPRAGE
7) RUN EXPLORE DTI PREPROCESSING SCRIPT (creates new *.mat *_EPI.mat files in ./expdtidata )
SM/EC CORRECTION ONLY
% expdticorr -R  ./dtidata ./expdtidata DRUMPILOT01 _SMEC
% ls ./expdtidata
SM/EC/EPI CORRECTION
% expdticorr -E  -R  ./dtidata ./expdtidata DRUMPILOT01 _EPI
% ls ./expdtidata

The final result will be a new file in ./expdtidata called DRUMPILOT01_[EPI/SMEC].mat. This file can only be opened with ExploreDTI. Using Explore DTI you will be able to generate any kind of diffusion images/maps you need, including of course tractography datasets.


See DTI pipeline document for more detail

Thursday, 5 March 2015

Random freesurfer commands and links

Table of surface areas (Desikan atlas)

aparc2statstable --hemi lh --subjects <list subjects> --tablefile lh.aparc.area.table

Table of thickness values (Desikan Atlas)

aparcstats2table --hemi lh --subjects <list subjects> -meas thickness --parc aparc --tablefile  lh.aparc.stats.thickness.table

Table of cortical volumes (Desikan Atlas)

aparcstats2table --subjects bert ernie fred margaret --parc aparc.a2005s --hemi rh --meas volume --tablefile aparc_stats_rh.txt

Table of subcortical volumes
asegstats2table --subjects bert ernie fred --meas volume --tablefile aseg_stats.txt

or create text file with path of all subjects and 

asegstats2table --subjectsfile=subject_to_write --meas volume --tablefile aseg_stats.txt

Change background of figure to white:
convert -fill white -opaque black <tksurfer_image_black_background>
<new_image_with_white_background>

http://ftp.nmr.mgh.harvard.edu/fswiki/FsTutorial/MorphAndRecon

Command line Group Analysis
https://surfer.nmr.mgh.harvard.edu/fswiki/FsTutorial/GroupAnalysis

Smoothing/qcache command
http://freesurfer.net/fswiki/FsTutorial/QdecGroupAnalysis_freeview

Methods citation
https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferMethodsCitation

Check surfaces
tkmedit your_subject_name wm.mgz rh.white -aux brain.mgz \
tkmedit your_subject_name wm.mgz lh.white -aux brain.mgz
https://surfer.nmr.mgh.harvard.edu/fswiki/BasicReconstruction

Check subcortical segmentation
tkmedit SUBJECT orig.mgz -aux-segmentation aseg.mgz

Explanation of steps of reconstruction
http://ftp.nmr.mgh.harvard.edu/fswiki/FsTutorial/MorphAndRecon


Recon-all descriptions
https://surfer.nmr.mgh.harvard.edu/fswiki/recon-all







Friday, 13 February 2015

TRACULA preprocessing

Step 1 (preprocessing)- 
  • Eddy-current compensation
  • Computing measures of head motion during the DWI scan
  • Intra-subject registration (individual DWI to individual T1)
  • Inter-subject registration (individual T1 to a common template space)
  • Creation of cortical and white-matter masks from FreeSurfer reconstructions
  • Tensor fitting for extract of tensor-based measures (FA, MD, etc)
  • Computing anatomical priors for white-matter pathways from the TRACULA atlas
Command is:

% trac-all -prep -c /home/.../config.file

Errors:
  • May get errors when trying to include all subjects in config file, couldn't figure out why so I created several config files splitting the subjects into smaller groups.
  • There may be issues with registration of the T1 to DTI data. You can check this by either overlaying the dmri/dtifit_FA.nii.gz and dlabel/aparc+aseg.bbr.nii files is fslview or freeview. Alternatively you can check the registration specifically using the command:
% tkregister2 --mov /home/.../dmri/dwi.nii.gz \
--reg /home/../dmir/xfms/anatorig2diff.bbr.dat --surf

  • There are several options for correcting a bad registration. Go into the TRACULA_OUTPUT/subject/scripts and open the trac-all.log. In there search for bbregister, keep searching until you find the bbregister command line and copy this into the command line to test on one subject only. You can substitute '--init-fsl' for '--init-header', '--init-spm' or --init-rr' (if don't have spm). I tried several options and in the end it was --init-spm that worked the best. - The command should be something like
% bbregister --s PDPLUS010 --init-header --dti --mov /home/.../dmri/dwi.nii.gz --reg /home/../dmri/xfms/anatorig2diff.bbr.dat --fslmat /home/../dmri/xfms/diff2anatorig.bbr.mat

use the command bbregister prints out to check the registration.

  • If this works and you now need to run all of the registrations again with the new option you will need to edit the trac-preproc script. Find $FREESURFER_HOME/bin/trac-preproc and copy it to your account. There you can search for '--init-header' and change this to '--init-spm'. You will also need a system administrator to copy the main trac-all script and edit this to specify that the new trac-preproc script is to be used. These edits mean that the one directory where this has been done will need to be used for all analysis, and for each command you will need to specify ./trac-all (whilst in the directory) for each command e.g.:
% ls /home/.../bbreg_TRAC
% ./trac-all -prep -c /home/config.file

  • You can now rerun the whole of the first preprocessing step again on all subjects. Check using fslview.
Step 2 (Ball and Stick model fit):
  • TRACULA uses the ball-and-stick model of diffusion to reconstruct the pathways from the DWI data. FSL's bedpostX fits the ball-and-stick model to the DWI data, estimating probability distributions of the parameters of this model at every voxel. This command will run bedpostX on the pre-processed data of all the subjects specified in the configuration file.
% ./trac-all -bedp -c /home/.../config.file
  • I did get some errors at this stage, system administrator fixed this (not sure what it was)
Step 3 (Reconstructing white matter pathways)

The final step is to generate the probability distributions for each white-matter bundles you specified in the configuration file. This is done by simultaneously fitting the shape of each pathway to the results of the ball-and-stick model of diffusion from above and to the prior knowledge of the pathway anatomy given by the set of manually labeled training subjects in the TRACULA atlas. The following command will reconstruct the probabilistic distribution of the pathways. 

% ./trac-all -path -c /home/.../config.file

  • you can check the output of the tract reconstruction either individual tracts:
freeview -v $TUTORIAL_DATA/diffusion_tutorial/elmo.2012/dmri/dtifit_FA.nii.gz \
            $TUTORIAL_DATA/diffusion_tutorial/elmo.2012/dpath/rh.ilf_AS_avg33_mni_bbr/path.pd.nii.gz:colormap=jet:isosurface=0,0:color='Red':name=rh.ilf \
            $TUTORIAL_DATA/diffusion_tutorial/elmo.2012/dpath/lh.ilf_AS_avg33_mni_bbr/path.pd.nii.gz:colormap=jet:isosurface=0,0:color='Red':name=lh.ilf
  • Or all together:
freeview -tv $TUTORIAL_DATA/diffusion_tutorial/elmo.2012/dpath/merged_avg33_mni_bbr.mgz \
         -v $TUTORIAL_DATA/diffusion_tutorial/elmo.2012/dmri/dtifit_FA.nii.gz &


  • Errors: you may find that some tracts are not reconstructed and do not show in the 3D view. I have created a separate page on how to fix this.











TRACULA Configuration file

Create a configuration file (text file):

Step 1: Create a configuration file. This is a simple text file, so you can create it with any text editor (gedit, vi, emacs, etc). On a Mac, run  open -e  to open a text file. For the purposes of this tutorial, we have already created a configuration file called dmrirc.tutorial. Open this file to see the example and follow along as we explain the commands:
gedit $TUTORIAL_DATA/diffusion_tutorial/dmrirc.tutorial &
Note that lines preceded by the # sign are "comments" and so will not be run as commands. The # symbol can be handy for adding descriptions of what each command will do, or to "comment out" commands that you want to disable temporarily. The tutorial configuration file looks like this:
# FreeSurfer SUBJECTS_DIR
# T1 images and FreeSurfer segmentations are expected to be found here
#
setenv SUBJECTS_DIR $TUTORIAL_DATA/diffusion_recons

# Output directory where trac-all results will be saved
# Default: Same as SUBJECTS_DIR
#
set dtroot = $TUTORIAL_DATA/diffusion_tutorial

# Subject IDs
#
set subjlist = ( elmo.2005 \
                 elmo.2008 \
                 elmo.2012 )

# Input diffusion DICOMs (file names relative to dcmroot)
# If original DICOMs don't exist, these can be in other image format
# but then bvecfile and bvalfile must be specified
#
set dcmroot = $TUTORIAL_DATA/diffusion_tutorial
set dcmlist = ( elmo.2005/orig/656000-11-1.dcm \
                elmo.2008/orig/97000-000017-000001.dcm \
                elmo.2012/orig/MR.1.3.12.2.1107.5.2.32.35006.2012121819455034689828982 )
This is the simplest configuration file possible, where only the most basic inputs are specified. We will now go through the options specified in the file above.

Step 2: Specify the FreeSurfer subject directory
setenv SUBJECTS_DIR $TUTORIAL_DATA/diffusion_recons
This variable must be set to the directory where all the subjects' FreeSurfer reconstructions are located. It is assumed that FreeSurfer has already been run on the subjects' T1-weighted data. TRACULA will use the aparc+aseg.mgz from each subject's FreeSurfer reconstruction - this is where the "underlying anatomy" part of TRACULA comes from.

Step 3: Specify the TRACULA output directory
set dtroot = $TUTORIAL_DATA/diffusion_tutorial
Use this variable to specify the directory where the TRACULA outputs for all subjects will be saved. If this is not specified, results will be saved under $SUBJECTS_DIR by default.

Step 4: Specify the list of subject IDs
set subjlist = (elmo.2005 elmo.2008 elmo.2012)
Use this variable to specify the ID of all the subjects you want to process with TRACULA. This can be a single subject, or it can be multiple subjects for batch processing.

Step 5: Specify the location of diffusion DICOM files
set dcmroot = $TUTORIAL_DATA/diffusion_tutorial
Use this variable to specify the directory under which the diffusion DICOM files for all subjects can be found.

Step 6: Specify the list of input DWIs
set dcmlist = ( elmo.2005/orig/656000-11-1.dcm \
                elmo.2008/orig/97000-000017-000001.dcm \
                elmo.2012/orig/MR.1.3.12.2.1107.5.2.32.35006.2012121819455034689828982 )
Use this variable to specify the input DWI data, one entry per subject. The file names are assumed be relative to the directory specified in dcmroot above. If DICOM files are available, you just need to specify the first DICOM file in the series that contains the DWIs, assuming the remaining DICOM files from the same series are in the same directory. If your DWIs are in a format other than DICOM, you can still specify the DWI volumes here, as long as they are in a format that can be read by mri_convert.
For DICOMs acquired with the standard Siemens diffusion sequences, the diffusion-encoding gradient table and the b-value table will be determined based on information in the DICOM header. For DICOM files acquired with other sequences or for files formats other than DICOM, you will need to specify the location of the diffusion-encoding gradient table (see bvecfileor bveclist below) and the b-value table (see bvalfile below).

In addition to the basic options in the simple configuration file above, there are several other options that you can use to customize data processing for your study. These are listed in a more extensive example configuration file, which is also available as part of the FreeSurfer distribution. We will now go through some of these additional options.

Step 7: Specify which subjects to analyze
set runlist = (2 3)
Use this variable if you only want to run the analysis on a subset of the subjects included in subjlist. The example above would run the analysis only on the second and third subject. This is useful if, e.g., you need to rerun a specific part of the analysis on a few of your subjects only. If this variable is not set, the analysis will be run on all subjects by default.

Step 8: Specify the diffusion-encoding gradient table
You can specify either a different gradient table for each of the scans in the study (with bveclist) or a single gradient table for all scans in the study (with bvecfile).
To specify a different gradient table for each of the scans in the study:
set bveclist = ( /path/to/elmo.2005/bvecs.txt \
                 /path/to/elmo.2008/bvecs.txt \
                 /path/to/elmo.2012/bvecs.txt )
To specify a single gradient table for all scans in the study:
set bvecfile = /path/to/bvecs.txt
Use either one of these variables to specify the location of the gradient table(s), if your DWI data is not in Siemens DICOM format. (The tutorial data is in Siemens DICOM format, so this step is not required.)
A gradient table must be saved in a simple text file either in three-column format (one row for each volume in the DWI series) or in three-row format (one column for each volume in the DWI series). An example is shown below:
 0  0  0
 0  0  0
 0  0  0
 1  0  1
-1  0  1
 0  1  1
 0  1 -1
 1  1  0
-1  1  0
In this example the first 3 rows of the gradient table are all-zero, indicating that 3 low-b (non-diffusion-weighted) volumes were acquired first, while the remaining 6 rows correspond to 6 diffusion-weighted volumes acquired with different diffusion-encoding gradients.

Step 9: Specify the b-value table
set bvalfile = /path/to/bvals.txt
Use this variable to specify the location of the b-value table, if your DWI data is not in Siemens DICOM format. (The tutorial data is in Siemens DICOM format, so this step is not required.)
The b-value table must be saved in a simple text file, one value for each volume in the DWI series. An example is shown below:
0
0
0
1000
1000
1000
1000
1000
1000
In this example the DWI series would include 3 non-diffusion-weighted (b=0) images, followed by 6 diffusion-weighted images acquired with b=1000mm^-2.

Step 10: Specify if eddy-current compensation will be performed
set doeddy = 1
Use this variable to specify if eddy-current compensation will be performed as part of DWI pre-processing. This compensation consists of an affine registration of all DWIs to the first image in the series, which is meant to mitigate distortions due to eddy currents and head motion. By default this variable is set to 1, so eddy-current compensation is performed. Set it to 0 to disable it.

Step 11: Specify if the gradients will be rotated to match eddy-current compensation
set dorotbvecs = 1
Use this variable to specify if the vectors in the diffusion-encoding gradient table will be rotated to match the rotations applied to the corresponding images by the eddy-current compensation. This is recommended if eddy-current compensation is performed.

Step 12: Specify if an anatomical brain mask will be used
set usemaskanat = 1
Use this variable to specify if the T1-weighted scan will be used to extract the brain mask instead of the DWI scan. If this is set to 1, which is the default, the brain mask will be obtained by dilating the aparc+aseg.mgz from the FreeSurfer segmentation and then mapping it to DWI space. To use a mask derived by thresholding the DWI scan instead, set this to 0.

Step 13: Set the threshold for DWI-based brain mask extraction
set thrbet = 0.3
Use this variable to set the threshold for creating a brain mask from the DWIs using FSL's Brain Extraction Tool (BET). This value is specified as a fraction of the maximum image intensity, so it must be a number between 0 and 1. The default is 0.3. Note that by default the brain mask used by TRACULA is extracted from the T1-weighted images, not the DWIs, in which case this variable will not have much of an effect on the analysis (see usemaskanat above).

Step 14: Specify the intra-subject registration method
There are two options for registering each subject's DWIs to the subject's own T1-weighted image: bbregister or FSL's FLIRT. They both perform affine registration but bbregister also uses the FreeSurfer surface reconstruction to optimize the affine registration between the diffusion and anatomical scan.
The following selects the default option, which is to use bbregister and not FLIRT:
set doregflt = 0
set doregbbr = 1
To use FLIRT and not bbregister, set doregflt to 1 and doregbbr to 0. If you do not have a preference and want the analysis performed with both options for comparison purposes, set both of these variables to 1 (this will take longer).

Step 15: Specify the inter-subject registration method
There are two options for registering each subject to the tract atlas used by TRACULA: affine registration to the MNI template (MNI152) or nonlinear registration to the CVS template (cvs_avg35). Although TRACULA performs tractography in each subject's own native diffusion space, this inter-subject registration is needed to map the individual to the tract atlas that TRACULA's anatomical priors are derived from. Note that the prior information extracted from this atlas is not the exact spatial location of the tracts, but the IDs of the anatomical segmentation labels that the tracts go through or next to. Thus a rough spatial alignment is sufficient for these anatomical priors to be accurate. However, another purpose for which the mapping to a common template is used, is to choose an initial guess of the tract location to initialize TRACULA. If the study subject's anatomy is significantly different from that of a normal population, this initialization may be more accurate when nonlinear registration is used.
The following selects the default options, which is to use MNI and not CVS registration:
set doregmni = 1
set doregcvs = 0
To use CVS and not MNI registration, set doregcvs to 1 and doregmni to 0 (this will take much longer). If you do not have a preference and want the analysis performed with both options for comparison purposes, set both of these variables to 1 (this will take even longer).
It is possible to specify the location of MNI template. If it is not specified, this will be assumed by default:
set mnitemp = $FSLDIR/data/standard/MNI152_T1_1mm_brain.nii.gz
It is also possible to specify the location of CVS template. If it is not specified, this will be assumed by default:
set cvstemp = cvs_avg35
set cvstempdir = $FREESURFER_HOME/subjects

Step 16: Specify which white-matter pathways to reconstruct
set pathlist = ( lh.cst_AS rh.cst_AS \
                 lh.ilf_AS rh.ilf_AS \
                 lh.unc_AS rh.unc_AS \
                 fmajor_PP fminor_PP \
                 lh.atr_PP rh.atr_PP \
                 lh.cab_PP rh.cab_PP \
                 lh.ccg_PP rh.ccg_PP \
                 lh.slfp_PP rh.slfp_PP \
                 lh.slft_PP rh.slft_PP )
Use this variable to specify which of the 18 pathways included in the TRACULA tract atlas to reconstruct. The default is to reconstruct all 18 pathways, defined below:
  • lh.cst_AS: Left corticospinal tract
  • rh.cst_AS: Right corticospinal tract
  • lh.ilf_AS: Left inferior longitudinal fasciculus
  • rh.ilf_AS: Right inferior longitudinal fasciculus
  • lh.unc_AS: Left uncinate fasciculus
  • rh.unc_AS: Right uncinate fasciculus
  • fmajor_PP: Corpus callosum - forceps major
  • fminor_PP: Corpus callosum - forceps minor
  • lh.atr_PP: Left anterior thalamic radiations
  • rh.atr_PP: Right anterior thalamic radiations
  • lh.ccg_PP: Left cingulum - cingulate gyrus endings
  • rh.ccg_PP: Right cingulum - cingulate gyrus endings
  • lh.cab_PP: Left cingulum - angular bundle
  • rh.cab_PP: Right cingulum - angular bundle
  • lh.slfp_PP: Left superior longitudinal fasciculus - parietal endings
  • rh.slfp_PP: Right superior longitudinal fasciculus - parietal endings
  • lh.slft_PP: Left superior longitudinal fasciculus - temporal endings
  • rh.slft_PP: Right superior longitudinal fasciculus - temporal endings

Step 17: Specify the number of path control points
set ncpts = (6 6 5 5 5 5 7 5 5 5 5 5 4 4 5 5 5 5)

Use this variable to specify the number of control points that will be used to model each of the pathways in pathlist as a spline. Any number greater than 2 is a valid choice but, as a rule of thumb, a fairly straight pathway can be modeled using only a few control points, whereas a highly curved pathway may require more control points. The default, as shown above, is to use 7 for the forceps major, 6 for the corticospinal tract, 4 for the angular bundle, and 5 for all other pathways.



TRACULA - if reconstruction of tract fails

After all processing steps you will need to check the reconstruction of the white matter tracts either by viewing each tract individually:

freeview -v $TUTORIAL_DATA/diffusion_tutorial/elmo.2012/dmri/dtifit_FA.nii.gz \
            $TUTORIAL_DATA/diffusion_tutorial/elmo.2012/dpath/rh.ilf_AS_avg33_mni_bbr/path.pd.nii.gz:colormap=jet:isosurface=0,0:color='Red':name=rh.ilf \
            $TUTORIAL_DATA/diffusion_tutorial/elmo.2012/dpath/lh.ilf_AS_avg33_mni_bbr/path.pd.nii.gz:colormap=jet:isosurface=0,0:color='Red':name=lh.ilf

Or by viewing the tracts simultaneously:

freeview -tv $TUTORIAL_DATA/diffusion_tutorial/elmo.2012/dpath/merged_avg33_mni_bbr.mgz \
         -v $TUTORIAL_DATA/diffusion_tutorial/elmo.2012/dmri/dtifit_FA.nii.gz &


If you notice that any of the tracts look wrong, or do not appear in 3D at all, this may mean that the intialisation of the tract failed and will need to be corrected.

To re-run this, you will need to add in a command to the config.file that you have set up. Just before specifying which tracts to reconstruct add the command ' set reinit = 1'.

You will then also need to specify below, which tract/tracts need to be reinitialised. Remember to also change the number of controls points. ( Any number greater than 2 is a valid choice but, as a rule of thumb, a fairly straight pathway can be modeled using only a few control points, whereas a highly curved pathway may require more control points. The default, as shown above, is to use 7 for the forceps major, 6 for the corticospinal tract, 4 for the angular bundle, and 5 for all other pathways.)

Then also specify which subject this needs to corrected for.

You can then run two commands:

trac-all -prior -c /home/config.file

trac-all -path -c /home/config.file

Re-check the paths.