Chapter 4 Structural Neuroimaging

4.1 DICOM to Nifti conversion

/home/mrphys/mencai/Downloads/mricron/Resources/dcm2niix -f "%f_%p_%t_%s" -p y -z y "/project/3015083.01/mengfei/Dengbo_Nifti/luxinyi_head_CT/DICOM"

OR 

$dcm2niiexec -ba n -f "${sub}"_"${ses}"_flair   -o . -z y ./*3dflair

4.2 Conversion jobs for Caixin DICOM files


dcm2niix -ba n -f SMG-001_t1   -o /home/neuro/caixin/processed -z y /home/neuro/caixin/raw/SMG-001/t1

dcm2niix -ba n -f SMG-001_t2   -o /home/neuro/caixin/processed -z y /home/neuro/caixin/raw/SMG-001/t2

dcm2niix -ba n -f SMG-001_t2flair   -o /home/neuro/caixin/processed -z y /home/neuro/caixin/raw/SMG-001/t2flair

dcm2niix -ba n -f SMG-001_rest  -o /home/neuro/caixin/processed -z y /home/neuro/caixin/raw/SMG-001/rest

4.3 T1 Volume calculation


cd /project/3015083.01/processed/

# calculate the CSF volume
csf_list=$(find . -name '*T1*corrected*')
for i in $csf_list;
do T1_volume=$(fslstats $i -V);
#echo detailed vol is $csf_volume
T1_volume2=$(echo $T1_volume | awk -F'[ ]' '{print $2}')
echo simple vol is $T1_volume2
echo $i $T1_volume2 >> /project/3015083.01/mengfei/T1_vol_rating.txt;
done

4.4 Deep and Periventricular white matter separation

#!/bin/sh

# This script is based on the scripts from Michelle to calculate the volumes of
# deep and periventricular WMH based on the distance from the ventricle.
#
# The methods are described in the article from Griffanti et al, 2018,
# NeuroImage. The threshold is set at 10 mm from the ventricles.
#
# Created at 24-4-2020

# echo "/project/3015083.01/mengfei/script/D_PWMH_micelle.sh sub-004" | qsub -N 'sub-004' -l 'nodes=1:ppn=4,mem=10gb,walltime=8:00:00'
#  echo "/project/3015083.01/mengfei/script/D_PWMH_micelle.sh sub-015" | qsub -N 'sub-015' -l 'nodes=1:ppn=4,mem=10gb,walltime=8:00:00'

module unload fsl

module load fsl/6.0.3

ID=$1
proc=/project/3015083.01/processed
echo " this is $ID"
# Specify the name of the subject
cd $proc

# Temporarily directory (All work done here)
tempfolder="$proc"/sub-"$ID"/ses-mri01/FLAIRreslice/temp

mkdir -p $tempfolder

echo " using resliced FLAIR and resliced MWH ==== mathcing 2006 FOV and resolution "

echo "copy t1 WMH flair files"
#/project/3015083.01/processed/sub-004/ses-mri01/FLAIRreslice/sub-004_ses-mri01_WMH.nii.gz
cp /project/3015083.01/nifti/sub-"$ID"/ses-mri01/anat/sub-"$ID"_ses-mri01_flair_reslice.nii.gz "$tempfolder"/flair.nii.gz
cp "$proc"/sub-"$ID"/ses-mri01/FLAIRreslice/sub-"$ID"_ses-mri01_WMH.nii.gz "$tempfolder"/wmh.nii.gz
cp "$proc"/sub-"$ID"/ses-mri01/T1/sub-"$ID"_ses-mri01_T1pseudo.nii.gz "$tempfolder"/t1w.nii.gz

# cp /project/3015083.01/nifti/sub-"$ID"/ses-mri01/anat/sub-"$ID"_ses-mri01_flair.nii.gz "$tempfolder"/flair.nii.gz
# cp "$proc"/"$ID"/ses-mri01/FLAIR/"$ID"_ses-mri01_WMH.nii.gz "$tempfolder"/wmh.nii.gz

################################################################################
# Registration
################################################################################
echo "Registration of the structural images to standard space"

cd $tempfolder

echo Brain extraction and copy header information before registration
bet t1w.nii.gz t1w_brain -f 0.6 -g -0.25
bet flair.nii.gz flair_brain -R -B -f 0.4

echo  Linear registration flair to t1 image
flirt -in flair_brain -ref t1w_brain -out flair_to_t1 -omat flair_to_t1.mat -cost corratio -interp trilinear

echo Linear and non-linear registration T1 - MNI
flirt -in t1w_brain -ref /opt/fsl/6.0.1/data/standard/MNI152_T1_2mm_brain -out t1_to_MNI_1 -omat t1_to_MNI.mat -bins 256 -cost corratio -searchrx -90 90 -searchry -90 90 -searchrz -90 90 -dof 12  -interp trilinear
fnirt --ref=/opt/fsl/6.0.1/data/standard/MNI152_T1_2mm_brain --in=t1w_brain --iout=t1_to_MNI_2 --aff=t1_to_MNI.mat --cout=t1_to_MNI_Warp

echo Flair and WMH to MNI
applywarp --ref=/opt/fsl/6.0.0/data/standard/MNI152_T1_2mm_brain --in=flair_brain --out=flair_to_MNI  --warp=t1_to_MNI_Warp --premat=flair_to_t1.mat
applywarp --ref=/opt/fsl/6.0.0/data/standard/MNI152_T1_2mm_brain --in=wmh --out=wmh_to_MNI --warp=t1_to_MNI_Warp --premat=flair_to_t1.mat --interp=nn

################################################################################
echo Segmentation and calculation
################################################################################
echo Segmentation and calculation of the periventricular and deep WMH

echo Brain segmentation using FAST to obtain CSF mask
fast -t 1 -o t1w_brain t1w_brain
invwarp -w t1_to_MNI_Warp.nii.gz -o invwarpvol -r t1w_brain

echo Make ventricle mask using make_bianca_mask
# Note: names below are mandatory - otherwise script does not work
make_bianca_mask t1w t1w_brain_pve_0.nii.gz invwarpvol

# Register ventricle and brain mask to FLAIR image
echo Create inverse warp FLAIR to T1
convert_xfm -omat t1_to_flair.mat -inverse flair_to_t1.mat

echo Apply inverse warp to register ventricle mask to FLAIR
flirt -in t1w_ventmask.nii.gz -ref flair_brain.nii.gz -out ventmask_to_flair -init t1_to_flair.mat -applyxfm
flirt -in t1w_brain_mask.nii.gz -ref flair_brain.nii.gz -out flair_brain_mask -init t1_to_flair.mat -applyxfm

echo Create distancemap
distancemap -i ventmask_to_flair.nii.gz -o flair_dist_to_vent -m flair_brain_mask

# Threshold distance maps
echo Threshold distance map to obtain periventricular WMH mask. Threshold 10 mm
fslmaths flair_dist_to_vent.nii.gz -uthr 10 -bin flair_dist_to_vent_periventricular

echo Threshold distance map to obtain deep WMH mask
fslmaths flair_dist_to_vent -thr 10 -bin flair_dist_to_vent_deep

echo Make WH maps periventricular or deep WMH
fslmaths wmh -bin -mul flair_dist_to_vent_deep DWMH_seg
fslmaths wmh -bin -mul flair_dist_to_vent_periventricular PWMH_seg

echo Copy files to the folder

cp DWMH_seg.nii.gz ../sub-"$id"_DWMH_seg.nii.gz
cp PWMH_seg.nii.gz ../sub-"$id"_PWMH_seg.nii.gz
cp flair_dist_to_vent.nii.gz ../sub-"$id"_flair_dist_to_vent.nii.gz

echo "Delete temp folder"
cd $tempfolder
rm -r tempfolder

4.5 Reslice/resample the Images

- For example, let’s say that you created a mask in FSL, and you would like to extract the data from a statistical map. You can use flirt to resample the mask to the statistical image:

> flirt -in mask.nii.gz -ref stats.nii.gz -out mask_RS.nii.gz -applyxfm

Or in AFNI:

> 3dresample -input mask.nii.gz -master stats.nii.gz -prefix mask_RS.nii.gz

And you would then be able to use an ROI extraction command, such as 3dmaskave or fslstats, to extract data from the mask.

In order to resample an image to an isotropic voxel size, such as 3x3x3, you can use the following options with flirt:

> flirt -in volume.nii -ref volume.nii -applyisoxfm 3.0 -nosearch -out volume_3x3x3.nii

To resample to an anisotropic voxel resolution, you can use AFNI’s 3dresample command, e.g.:

> 3dresample -input 10091_thin.nii.gz -prefix 10091_thick_3mm_convert.nii.gz -dxyz 0.5 0.5 3

4.6 Obtain the overlap mask from Two Images

# You can use a command like this to trim the lesion so it only occupies the region that overlaps the brain mask, e.g.:

 fslmaths lesion_mask -mul native_brain_mask -bin lesion_mask -odt char

# This command says: Multiply the lesion_mask and the native_brain_mask, retaining only voxels that are in both. Then binarize the lesion mask with -bin and ensure that it doesn’t take up too much space on your drive with -odt char which sets the output datatype to 8 bits.

4.7 Regsitration

4.7.1 WM/GM/WMH registration into IVIM space

#!/bin/bash

# Environment
# Environment
module unload fsl
module unload ANTs
module load fsl/6.0.1
module load ANTs/20180607

antsReg=/project/3015083.01/res/normalization/antsRegistrationSyNx.sh

niftifolder=/project/3015083.01/nifti
raw_procfolder=/project/3015083.01/mengfei/raw_backup/processed
procfolder=/project/3015083.01/processed
#t1folder=/project/3015083.01/processed/sub-"${ID}"/ses-mri01/T
# /project/3015083.01/processed/sub-"${ID}"/ses-mri01/ivim/

cd ${procfolder} # this is home folder for processed folders
# ID for 20 cases with a wide range of WMH burden: 036 090 140 161 190 200 221 286 296 300 308 363 366 367 404 434 439 444 485 507;
for ID in 036 090 140 161 190 200 221 286 296 300 308 363 366 367 404 434 439 444 485 507;
do
        echo  "    "
        echo "this subject is $ID"
        echo  "    "
    if [ -d "${procfolder}"/sub-"${ID}"/ses-mri01/ivim ]; then  ## space after "[" is very important
        cd "${procfolder}"/sub-"${ID}"/ses-mri01/ivim
        echo "found ivim folder...and do further co-registration"

        # select b1000 images from IVIM processed data
        select_dwi_vols "${procfolder}"/sub-"${ID}"/ses-mri01/ivim/sub-"${ID}"_ses-mri01_ivim-data.nii.gz \
        "${procfolder}"/sub-"${ID}"/ses-mri01/ivim/sub-"${ID}"_ses-mri01_ivim.bval "${procfolder}"/sub-"${ID}"/ses-mri01/ivim/sub-"${ID}"_ivim_mean_b1000.nii.gz 1000 -m

        # brain extraction from T1 T1_pseudo
        echo  "    "
        echo " =================brain extraction from T1 T1_pseudo...."
        fslmaths "${raw_procfolder}"/sub-"${ID}"/ses-mri01/T1/sub-"${ID}"_ses-mri01_T1pseudo.nii.gz \
        -mul "${raw_procfolder}"/sub-"${ID}"/ses-mri01/T1/sub-"${ID}"_ses-mri01_T1pseudo-bmask.nii.gz \
        "${raw_procfolder}"/sub-"${ID}"/ses-mri01/T1/sub-"${ID}"_ses-mri01_T1pseudo_bet.nii.gz

        # register T1 to mean_IVIM_b1000, then put the output into raw_processed_ivim folders

        echo  "    "
        echo " =================register T1 to mean_IVIM_b1000... "
        echo  "    "
        ${antsReg} -d 3 -f "${procfolder}"/sub-"${ID}"/ses-mri01/ivim/sub-"${ID}"_ivim_mean_b1000.nii.gz \
        -m "${raw_procfolder}"/sub-"${ID}"/ses-mri01/T1/sub-"${ID}"_ses-mri01_T1pseudo_bet.nii.gz \
        -o "${procfolder}"/sub-"${ID}"/ses-mri01/ivim/sub-"${ID}"_T1_to_mean_b1000_ants -t r -p f -n 12  # output should not end wiht [.nii.gz]

        # Register GM WM CSF mask to (T1-->IVIM), respectively
        echo  "    "
        echo " =================Register GM WM CSF mask to (T1-->IVIM), respectively.... "
        echo  "    "

        antsApplyTransforms -d 3 --float 1 -i "${raw_procfolder}"/sub-"${ID}"/ses-mri01/T1/spm_derivatives/sub-"${ID}"_ses-mri01_T1-gm-corrected.nii.gz \
        -o "${procfolder}"/sub-"${ID}"/ses-mri01/ivim/sub-"${ID}"_GM_to_mean_b1000.nii.gz \
        -r "${procfolder}"/sub-"${ID}"/ses-mri01/ivim/sub-"${ID}"_ivim_mean_b1000.nii.gz \
            -t ["${procfolder}"/sub-"${ID}"/ses-mri01/ivim/sub-"${ID}"_T1_to_mean_b1000_ants_0GenericAffine.mat] \
          -n BSpline

        antsApplyTransforms -d 3 --float 1 -i "${raw_procfolder}"/sub-"${ID}"/ses-mri01/T1/spm_derivatives/sub-"${ID}"_ses-mri01_T1-wm-corrected.nii.gz \
        -o "${procfolder}"/sub-"${ID}"/ses-mri01/ivim/sub-"${ID}"_WM_to_mean_b1000.nii.gz \
        -r "${procfolder}"/sub-"${ID}"/ses-mri01/ivim/sub-"${ID}"_ivim_mean_b1000.nii.gz \
            -t ["${procfolder}"/sub-"${ID}"/ses-mri01/ivim/sub-"${ID}"_T1_to_mean_b1000_ants_0GenericAffine.mat] \
          -n BSpline

        antsApplyTransforms -d 3 --float 1 -i "${raw_procfolder}"/sub-"${ID}"/ses-mri01/T1/spm_derivatives/sub-"${ID}"_ses-mri01_T1-csf-corrected.nii.gz \
        -o "${procfolder}"/sub-"${ID}"/ses-mri01/ivim/sub-"${ID}"_CSF_to_mean_b1000.nii.gz \
        -r "${procfolder}"/sub-"${ID}"/ses-mri01/ivim/sub-"${ID}"_ivim_mean_b1000.nii.gz \
            -t ["${procfolder}"/sub-"${ID}"/ses-mri01/ivim/sub-"${ID}"_T1_to_mean_b1000_ants_0GenericAffine.mat] \
          -n BSpline

        # to binarize the output
        echo  "    "
        echo " =================to binarize the output... "
        echo  "    "
        fslmaths  "${procfolder}"/sub-"${ID}"/ses-mri01/ivim/sub-"${ID}"_GM_to_mean_b1000.nii.gz -thr 0.5 \
        -bin  "${procfolder}"/sub-"${ID}"/ses-mri01/ivim/sub-"${ID}"_GM_to_mean_b1000_binary.nii.gz

        fslmaths  "${procfolder}"/sub-"${ID}"/ses-mri01/ivim/sub-"${ID}"_WM_to_mean_b1000.nii.gz -thr 0.5 \
        -bin  "${procfolder}"/sub-"${ID}"/ses-mri01/ivim/sub-"${ID}"_WM_to_mean_b1000_binary.nii.gz

        fslmaths  "${procfolder}"/sub-"${ID}"/ses-mri01/ivim/sub-"${ID}"_CSF_to_mean_b1000.nii.gz -thr 0.5 \
        -bin  "${procfolder}"/sub-"${ID}"/ses-mri01/ivim/sub-"${ID}"_CSF_to_mean_b1000_binary.nii.gz
    else
        echo "there is no IVIM folder"
        cd ${procfolder}
    fi
done

4.7.2 Register WMH into MNI space


#!/bin/bash

# Supposed to be run as ./t1_volumes.sh sub-xxx ses-yyy

module unload fsl
module load fsl/6.0.3

cd /project/3015083.01/mengfei/WMH_into_MNI_test/sub-016_test

echo ".. registering WMH into T1 --> get the .mat file"
flirt -in flair_brain.nii.gz -ref T1_brain.nii.gz -out flairt_2_T1 -omat flair_2_T1.mat
flirt -in WMH.nii.gz -out WMHinT1 -ref T1_brain.nii.gz -init flair_2_T1.mat -applyxfm -interp nearestneighbour
# step1: to get flair_2_T1.mat by registering flair-->T1 , this is very important !!!!
# step2; then use flair_2_T1.mat; register WMH-->T1; to get the WMHinT1
echo "MNI--step1...Initiate MNI registration...running flirt..to MNI space.."
flirt  -in T1_brain.nii.gz -ref $FSLDIR/data/standard/MNI152_T1_2mm_brain.nii.gz -dof 12 \
-out T1toMNIlin -omat T1toMNIlin.mat
 # using the raw t1w, not skull stripped  # .cnf is  important
 # Here, the input T1 should be with skull; it will make FNIRT more accurate; 
 # check this link:    ###https://fsl.fmrib.ox.ac.uk/fsl/fslwiki/FDT/UserGuide#DTIFIT
 # In the GUI, it is possible to use nonlinear FNIRT registration between structural and standard space. In this case, the user needs to provide a non-brain-extracted structural image, as this will make FNIRT more accurate.


echo "MNI--stpe2...running fnirt...  --> to get the .warp file "
fnirt --in=T1w.nii.gz --aff=T1toMNIlin.mat \
--config=/opt/fsl/dev/etc/flirtsch/T1_2_MNI152_2mm.cnf \
--iout=T1toMNInonlin_2mm --cout=T1toMNI_coef --fout=T1toMNI_warp

echo "MNI--step3...running applywarp...--> native T1 to MNI"
applywarp -i T1w.nii.gz -r $FSLDIR/data/standard/MNI152_T1_1mm.nii.gz -w T1toMNI_warp.nii.gz -o T1toMNInonlin_1mm.nii.gz
# /opt/fsl/dev/etc/flirtsch/T1_2_MNI152_2mm.cnf

echo "WMH to MNI...combining the transformations..."
applywarp -i WMH.nii.gz -r $FSLDIR/data/standard/MNI152_T1_1mm.nii.gz --premat=flair_2_T1.mat -w T1toMNI_warp.nii.gz -o WMHtoMNI_1mm.nii.gz
applywarp -i WMHinT1.nii.gz -r $FSLDIR/data/standard/MNI152_T1_1mm.nii.gz -w T1toMNI_warp.nii.gz -o WMHtoMNI_1mm_via_WMHinT1.nii.gz
fslmaths WMHtoMNI_1mm_via_WMHinT1.nii.gz -thr 0.5 -bin WMHtoMNI_1mm_via_WMHinT1_thr05_bin.nii.gz
#flirt -in /project/3015083.01/mengfei/WMH_into_MNI_test/sub-004_WMH_to_T1.nii.gz -ref /project/3015083.01/mengfei/WMH_into_MNI_test/MNI152_T1_1mm.nii.gz -out sub-004_WMHinT1_to_MNI_1mm.nii.gz

#cp "$wmh_file" /project/3015083.01/mengfei/WMH_lacune_masks061115/WMH_masks/sub-"$ID"/mask_native_2006

done

4.8 Segmentation

4.8.2 SAMSEG

(SAMSEG_Freesurfer)[https://surfer.nmr.mgh.harvard.edu/fswiki/Samseg]

Sequence Adaptive Multimodal SEGmentation (SAMSEG) is a tool to robustly segment dozens of brain structures from head MRI scans without preprocessing. The characteristic property of SAMSEG is that it accepts multi-contrast MRI data without prior assumptions on the specific type of scanner or pulse sequences used. Dedicated versions to handle longitudinal data, or to segment white matter lesions in multiple sclerosis (MS) patients are also available.

The figure below illustrates a typical SAMSEG segmentation result on a T1w-FLAIR scan of a MS patient:

SAMSEG_fig
SAMSEG_fig

In its most basic form SAMSEG takes one or more co-registered MRI volumes as input, and produces an output segmentation in around 10 min on a good desktop computer (with multi-threading enabled). Preprocessing of the scan(s) with FreeSurfer is neither required nor recommended (e.g., no reformatting to 1mm isotropic resolution, no bias field correction and no skull stripping is needed nor recommended). The command line is:


> run_samseg --input <file> [<file> ...] --output <dir> [--threads <threads>] [--pallidum-separate] 
where:

<file>: is the path to the input volume(s) in Nifti (.nii/.nii.gz) or FreeSurfer (.mgz) file format. If you have more than one contrast (e.g., both T1w and T2w) you can simply list all the input contrasts you want to use -- the only requirement is that all input volumes are co-registered with each other, and have the same image grid size and voxel dimensions (see below for instructions on how to do that with FreeSurfer).

<dir>: is the path to the output directory where the results will be saved. If this directory doesn't exist, it will be created automatically.

<threads> (optional): is the number of threads to be used by SAMSEG (default uses one thread). Set the number of threads to the number of CPU cores on your computer to get the fastest run time.

--pallidum-separate (optional): by default SAMSEG will treat the pallidum internally as a white matter structure, since it typically can't be discerned easily from white matter in T1w scans. However, if your combination of input volumes includes contrasts where the pallidum is clearly discernible (e.g., T2w or FLAIR) you should add this flag to your command line.

The output will consist of the following set of files, which can be found under the specified <dir> directory:

seg.mgz: is the output segmentation volume, where each voxel has been assigned to one anatomical structure. This file is similar to the "aseg.mgz" file produced by the standard volumetric stream in FreeSurfer: the correspondence between structure numbers and neuroanatomical labels is according to $FREESURFER_HOME/FreeSurferColorLUT.txt.

samseg.stats: contains the estimated volume (in cubic mm) for each segmented structure. These volumes will be very close (but not identical to) the number of voxels assigned to each structure in "seg.mgz" -- the reason for the discrepancy is that "seg.mgz" is computed in a winner-takes-all fashion, ignoring the uncertainty about the underlying voxel assignments (and therefore yielding slightly less accurate volume estimates).

mode0X_bias_corrected.mgz (with X=1,2,...): the bias field corrected MRI volume corresponding to each input contrast.

mode0X_bias_field.mgz (with X=1,2,...): the estimated bias field for each input contrast.

4.8.3 SAMSEG tiv and regional volume extraction

## regional volume 

cd /home/neuro/MRI_GDPH/ppmi/PPMI_t1_only/PPMI_t1_only_processed/

regional_vol_list=$(find . -name 'samseg.stats' | head -n 1 )

for i in $regional_vol_list;
do
regional_vol=$(cat $i | awk -F'[,]' '{print  $1}' | tr -s [:space:] ' ' | awk '{print $0}' )
echo "regional_vol is $regional_vol"
echo $i $regional_vol >> /home/neuro/MRI_GDPH/ppmi/PPMI_t1_only/ppmi_t1_only_regional_vol.txt
done

## tiv volume 

tiv_vol_list=$(find . -name 'sbtiv.stats' )

for j in $tiv_vol_list;
do
tiv_vol=$(cat $j | awk -F'[,]' '{print  $2}' | tr -s [:space:] ' ' | awk '{print $0}' )
echo "tiv is $tiv_vol "
echo $j $tiv_vol >> /home/neuro/codebank/GDPH/ppmi_t1_tiv_vol.txt
done

4.9 BIANCA

BIANCA_tutorial


module unload fsl
module unload ANTs

module load fsl/6.0.3
module load ANTs/20180607

i="$1"

antsReg=/project/3015083.01/res/normalization/antsRegistrationSyNx.sh

cd /project/3015083.01/processed
proc=/project/3015083.01/processed
temp=/project/3015083.01/mengfei/temp_BIANCA

## files preparation

cp "$proc"/"$i"/ses-mri01/T1/"$i"_ses-mri01_T1pseudo_brain.nii.gz "$temp"/T1_brain/

t1file="$temp"/T1_brain/"$i"_ses-mri01_T1pseudo_brain.nii.gz

flair_file="$temp"/FLAIR_brain/"$i"_ses-mri01_flair_brain.nii.gz

# extract the brain from flair to get flair_brain

 bet "$temp"/FLAIR/"${i}"_ses-mri01_flair.nii.gz "$temp"/FLAIR_brain/"${i}"_ses-mri01_flair_brain -R -m

# bias filed correction

N4BiasFieldCorrection -d 3 -i "$t1file" -o "$temp"/T1_brain/"$i"_ses-mri01_T1pseudo_brainN4.nii.gz
N4BiasFieldCorrection -d 3 -i "$flair_file" -o "$temp"/FLAIR_brain/"$i"_ses-mri01_flair_brainN4.nii.gz

# T1_brain --> flair_brain registration
${antsReg} -d 3 -f "$temp"/FLAIR_brain/"$i"_ses-mri01_flair_brainN4.nii.gz \
-m "$temp"/T1_brain/"$i"_ses-mri01_T1pseudoN4_brain.nii.gz -o "$temp"/T1_to_FLAIR/"$i"_ses-mri01_T1toflair -t r -p f -n 12

# to prepare the T1toMNI_warp_inv, which is needed for make_bianca_mask

flirt -v -in "$temp"/T1_brain/"$i"_ses-mri01_T1pseudo_brainN4.nii.gz -ref $FSLDIR/data/standard/MNI152_T1_2mm_brain.nii.gz -dof 12 \
-out "$temp"/T1_MNI_reg/derivates/"$i"_ses-mri01_T1toMNIlin -omat "$temp"/T1_MNI_reg/derivates/"$i"_ses-mri01_T1toMNIlin.mat

fnirt -v --in="$temp"/T1_brain/"$i"_ses-mri01_T1pseudo_brainN4.nii.gz --aff="$temp"/T1_MNI_reg/derivates/"$i"_ses-mri01_T1toMNIlin.mat \
--config=T1_2_MNI152_2mm.cnf --iout="$temp"/T1_MNI_reg/"$i"_ses-mri01_T1toMNInonlin \
--cout="$temp"/T1_MNI_reg/"$i"_ses-mri01_T1toMNI_coef --fout="$temp"/T1_MNI_reg/"$i"_ses-mri01_T1toMNI_warp

applywarp -i "$temp"/T1_brain/"$i"_ses-mri01_T1pseudo_brainN4.nii.gz -r $FSLDIR/data/standard/MNI152_T1_1mm.nii.gz \
-w "$temp"/T1_MNI_reg/"$i"_ses-mri01_T1toMNI_warp.nii.gz -o "$temp"/T1_MNI_reg/"$i"_ses-mri01_T1toMNInonlin_1mm.nii.gz

invwarp -v -w "$temp"/T1_MNI_reg/"$i"_ses-mri01_T1toMNI_warp.nii.gz -r "$temp"/T1_brain/"$i"_ses-mri01_T1pseudo_brainN4.nii.gz \
-o "$temp"/T1_MNI_reg/"$i"_ses-mri01_T1toMNI_warp_inv.nii.gz

## fast to seg , to get the PVE_0, which is CSF based and needed for **make_bianca_mask**
## pay attention to the flag

fast -o "$temp"/FAST_seg/"$i"_T1pseudoN4_brain_fast \
-S 1 -t 1 -n 3 -b -B -p "$temp"/T1_brain/"$i"_ses-mri01_T1pseudoN4_brain.nii.gz

### ======the main part  structure-image nanming format is crucial
## sub-004_ses-mri01_T1pseudoN4_brain is the very crucial, but stupid name
cd "$temp"/bianca_mask
make_bianca_mask "$temp"/T1_brain/"$i"_ses-mri01_T1pseudoN4 \
"$temp"/FAST_seg/"$i"_T1pseudoN4_brain_fast_pve_0.nii.gz \
"$temp"/T1_MNI_reg/"$i"_ses-mri01_T1toMNI_warp_inv.nii.gz

echo  Register T1_bianca_mask to flair base space
${antsReg} -d 3 -f "$temp"/FLAIR_brain/"$i"_ses-mri01_flair_brainN4.nii.gz \
-m "$temp"/T1_brain/"$i"_ses-mri01_T1pseudoN4_bianca_mask.nii.gz  -o "$temp"/bianca_mask/"$i"_ses-mri01_bianca_mask_to_flair -t r -p f -n 12

echo bianrize the xxx-ses-mri01_bianca_mask_to_flair

fslmaths "$temp"/bianca_mask/"$i"_ses-mri01_bianca_mask_to_flair.nii.gz -thr 0.5 \
-bin "$temp"/bianca_mask/"$i"_ses-mri01_bianca_mask_to_flair_binary.nii.gz

## use xxx_ses-mri01_bianca_mask_to_flair_binary.nii.gz to mask the flair_brain, only to get the WM-based mask, which will be used for bianca

fslmaths "$temp"/FLAIR_brain/"$i"_ses-mri01_flair_brainN4.nii.gz \
-mas "$temp"/bianca_mask/"$i"_ses-mri01_bianca_mask_to_flair_binary.nii.gz \
"$temp"/masked_flair/"$i"_ses-mri01_bianca_mask_to_flair_masked.nii.gz

## prepare Masterfile

 echo "$temp"/masked_flair/"$i"_ses-mri01_bianca_mask_to_flair_masked.nii.gz "$temp"/T1_to_FLAIR/"$i"_ses-mri01_T1toflair.nii.gz \
"$temp"/WMHmasks/"$i"_ses-mri01_WMH.nii.gz >> masterfile.txt

bianca --singlefile=masterfile.txt --labelfeaturenum=3 --brainmaskfeaturenum=1 --querysubjectnum=1 --trainingnums=1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20 \
--featuresubset=1,2 --trainingpts=2000 --nonlespts=10000 --selectpts=noborder -o "$temp"/bianca_output/"$i"_bianca_output  –v


done

cd $temp
paste flair_brain.txt T1_to_FLAIR.txt WMH.txt -d' ' > master.txt

  newname=$(echo "T1pseudo_bet.nii.gz" | sed 's/.nii.gz/_reslice.nii.gz/')

  mv -v T1pseudo_bet.nii.gz "$i"_ses-mri01_T1pseudo_brain.nii.gz

cp -v /project/3015083.01/nifti/"$i"/ses-mri01/anat/"$i"_ses-mri01_flair.nii.gz /project/3015083.01/mengfei/temp_BIANCA/FLAIR

cp -v /project/3015083.01/processed/"$i"/ses-mri01/FLAIR/"$i"_ses-mri01_WMH.nii.gz /project/3015083.01/mengfei/temp_BIANCA/WMHmasks

cp -v /project/3015083.01/processed/"$i"/ses-mri01/T1/"$i"_ses-mri01_T1pseudo.nii.gz /project/3015083.01/mengfei/temp_BIANCA/T1

flirt -in "$temp"/T1_brain/"$i"_ses-mri01_T1pseudo_brainN4.nii.gz -ref "$temp"/FLAIR_brain/"$i"_ses-mri01_flair_brainN4.nii.gz -out "$temp"/T1_to_FLAIR/"${i}"_T1_to_FLAIR.nii.gz -paddingsize 0.0 -interp trilinear -dof 6

bet "$temp"/FLAIR/"${i}"_ses-mri01_flair.nii.gz "$temp"/FLAIR_brain/"${i}"_ses-mri01_flair_brain -R -m

ls /project/3015083.01/mengfei/temp_BIANCA/FLAIR_brain > "$temp"/flair_brain.txt
# echo ls /project/3015083.01/mengfei/temp_BIANCA/T1 > "$temp"/T1.txt
ls /project/3015083.01/mengfei/temp_BIANCA/WMHmasks > "$temp"/WMH.txt
ls /project/3015083.01/mengfei/temp_BIANCA/T1_to_FLAIR > "$temp"/T1_to_FLAIR.txt

4.10 WMH seg by LST_AI


#!/bin/bash


# Function to process a single T1 MRI file
process_LST_AI() {
    start=`date +%s`
    flair="$1"   # flair=/home/neuro/caixin/processed/HC-001/ses-1/flair/HC-001_flair.nii.gz

    group_id=$(echo $flair | awk -F'/' '{print $6}' ) # ---> HC-001

   # flair=/home/neuro/caixin/nifti/"$group_id"/ses-1/flair/"$group_id"_flair.nii.gz
 
# Check if the file exists
file_path="/home/neuro/caixin/processed/"$group_id"/ses-1/WMH_lst/temp/space-flair_seg-lst.nii.gz"

# Check if the file exists
    if [ -e "$file_path" ]; then
        echo "File exists. Skipping job script."
    else
        echo "=============File does not exist. Running LST job script."


   "===================gropu_id is  $group_id =======
  ================ Running LST_AI job script."

t1=/home/neuro/caixin/nifti/"$group_id"/ses-1/anat/"$group_id"_t1.nii.gz

mkdir -p /home/neuro/caixin/processed/"$group_id"/ses-1/WMH_lst/temp
cp $t1 $flair /home/neuro/caixin/processed/"$group_id"/ses-1/WMH_lst/temp
cd /home/neuro/caixin/processed/"$group_id"/ses-1/WMH_lst/temp

lst --t1 "$group_id"_t1.nii.gz --flair  "$group_id"_flair.nii.gz --output . --temp . --device cpu

    fi

    end_LST=$(date +%s)
    runistime1=$((end_LST-start))
    echo "=========runtime1  $runtime1==========="

    sleep  1
}

# Export the process_acapulco function to make it available to GNU parallel
export -f process_LST_AI

# Set environment variable to make GPUs invisible to CUDA
export CUDA_VISIBLE_DEVICES=""
# Read the T1 MRI file paths from ppmi_t1_only_nif_list.txt and process them in parallel
#  cat /home/neuro/caixin/nif_t1_id_20240501_test.txt | parallel -j $(nproc --ignore=1) -N 10 process_samseg
#This command processes 10 lines at a time per job.
#dynamically calculates the number of available CPU cores minus two,
# so if your machine has 8 cores, it will use 6 cores for parallel processing

# parallel -v -a /home/neuro/caixin/nif_flair_list_0520.txt -j $(nproc --ignore=1) -N 9 process_LST_AI

cat /home/neuro/caixin/nif_flair_list_0601_missing_2.txt | parallel -j $(nproc --ignore=1)  process_LST_AI

# Calculate the total runtime for all files
end_all_LST=$(date +%s)
all_time_LST=$((end_all_LST-start))
echo "==== all LST_AI time taken: $all_time_LST === "

4.11 Difference images

difference_image_T1_FLAIR
difference_image_T1_FLAIR

Ref: Ter Telgte A, Wiegertjes K, Gesierich B, Marques JP, Huebner M, de Klerk JJ, Schreuder FHBM, Araque Caballero MA, Kuijf HJ, Norris DG, Klijn CJM, Dichgans M, Tuladhar AM, Duering M, de Leeuw FE. Contribution of acute infarcts to cerebral small vessel disease progression. Ann Neurol. 2019 Oct;86(4):582-592. doi: 10.1002/ana.25556. Epub 2019 Aug 12.

 #!/bin/bash
  
  # Environment
  module unload fsl
  module unload ANTs
  
  module load fsl/6.0.1
  module load ANTs/20180607
  
  niifolder=/project/3015083.01/nifti
  profolder=/project/3015083.01/processed
  prefolder=/project/3015083.01/RUNDMC_MRIdata
  antsReg=/project/3015083.01/res/normalization/antsRegistrationSyNx.sh
  
  
  id="$1"
  echo "subject ID: $id"
  cd /project/3015083.01/RUNDMC_MRIdata/difference0611
  mkdir -p sub-"${id}"
  cd sub-"${id}"
  echo "current folder: $PWD"
  
  folder=/project/3015083.01/RUNDMC_MRIdata
  
  # Masks and bias correction inputs
  t1file06="${folder}"/T1/T1_2006/RUNDMC_"$id"_T1_2006.nii.gz
  t1file11="${folder}"/T1/T1_2011/RUNDMC_"$id"_T1_2011.nii.gz
  
  flairfile06="${folder}"/FLAIR/FLAIR_2006/RUNDMC_"$id"_FLAIR_2006.nii.gz
  flairfile11="${folder}"/FLAIR/FLAIR_2011/RUNDMC_"$id"_FLAIR_2011.nii.gz
  
  ## 2006 T1 and flair bias correction
  
  bet "$t1file06" sub-"$id"_T1_2006-bet -R -m
  mv sub-"$id"_T1_2006-bet_mask.nii.gz sub-"$id"_T1_2006-bmask.nii.gz  ## rename the extracted brain into *bmask
  N4BiasFieldCorrection -d 3 -i "$t1file06" -w sub-"$id"_T1_2006-bmask.nii.gz  -o sub-"$id"_T1_2006N4.nii.gz
  
  bet "$flairfile06" sub-"$id"_FLAIR_2006-bet -R -m
  mv sub-"$id"_FLAIR_2006-bet_mask.nii.gz sub-"$id"_FLAIR_2006-bmask.nii.gz
  N4BiasFieldCorrection -d 3 -i "$flairfile06" -w sub-"$id"_FLAIR_2006-bmask.nii.gz  -o sub-"$id"_FLAIR_2006N4.nii.gz
  
  ## 2011 T1 and flair bias correction
  
  bet "$t1file11" sub-"$id"_T1_2011-bet -R -m
  mv sub-"$id"_T1_2011-bet_mask.nii.gz sub-"$id"_T1_2011-bmask.nii.gz
  N4BiasFieldCorrection -d 3 -i "$t1file11" -w sub-"$id"_T1_2011-bmask.nii.gz  -o sub-"$id"_T1_2011N4.nii.gz
  
  bet "$flairfile11" sub-"$id"_FLAIR_2011-bet -R -m
  mv sub-"$id"_FLAIR_2011-bet_mask.nii.gz sub-"$id"_FLAIR_2011-bmask.nii.gz
  N4BiasFieldCorrection -d 3 -i "$flairfile11" -w sub-"$id"_FLAIR_2011-bmask.nii.gz  -o sub-"$id"_FLAIR_2011N4.nii.gz
  
  #--- previous FLAIR to previous T1
  ${antsReg} -d 3 -f sub-"$id"_T1_2006N4.nii.gz -m sub-"$id"_FLAIR_2006N4.nii.gz -o preFLAIR_ants2_preT1 -t r -p f -n 12
  
  #--- previous T1 to current T1
  ${antsReg} -d 3 -f sub-"$id"_T1_2011N4.nii.gz -m sub-"$id"_T1_2006N4.nii.gz -o sub-"$id"_preT1_ants2_curT1 -t r -p f -n 12
  
  #--- previous FLAIR to current T1
  antsApplyTransforms -d 3 --float 1 -i sub-"$id"_FLAIR_2006N4.nii.gz -o sub-"$id"_preFLAIR_ants2_curT1.nii.gz  -r sub-"$id"_T1_2011N4.nii.gz \
    -t [sub-"$id"_preT1_ants2_curT1_0GenericAffine.mat] \
    -t [preFLAIR_ants2_preT1_0GenericAffine.mat] \
    -n BSpline
  #
  #--- current FLAIR to current T1
  ${antsReg} -d 3 -f sub-"$id"_T1_2011N4.nii.gz -m sub-"$id"_FLAIR_2011N4.nii.gz -o sub-"$id"_curflair_ants_curT1  -t r -p f -n 12
  
  # # Difference images and copy
  dest=/project/3015083.01/RUNDMC_MRIdata/difference0611/sub-"$id"/Diff
  mkdir -p "$dest"
  fslmaths sub-"$id"_T1_2011N4.nii.gz         -mas sub-"$id"_T1_2011-bmask.nii.gz -inm 1 "$dest"/sub-"$id"_T1-N4.nii.gz
  fslmaths sub-"$id"_curflair_ants_curT1.nii.gz     -mas sub-"$id"_T1_2011-bmask.nii.gz -inm 1 "$dest"/sub-"$id"_FL-N4reg.nii.gz
  fslmaths sub-"$id"_preT1_ants2_curT1.nii.gz        -mas sub-"$id"_T1_2011-bmask.nii.gz -inm 1 "$dest"/sub-"$id"_T1pre-N4reg.nii.gz
  fslmaths sub-"$id"_preFLAIR_ants2_curT1.nii.gz -mas sub-"$id"_T1_2011-bmask.nii.gz -inm 1 "$dest"/sub-"$id"_FLpre-N4reg.nii.gz
  
  fslmaths "$dest"/sub-"$id"_T1-N4.nii.gz -sub "$dest"/sub-"$id"_T1pre-N4reg.nii.gz "$dest"/sub-"$id"_T1diff.nii.gz
  fslmaths "$dest"/sub-"$id"_FL-N4reg.nii.gz    -sub "$dest"/sub-"$id"_FLpre-N4reg.nii.gz "$dest"/sub-"$id"_FLdiff.nii.gz
  
  # cleanup
  
  rm * # remove all files except directory, to save more space
  

Refs:

  1. Smith SM. Fast robust automated brain extraction. Hum Brain Mapp. 2002;17(3):143-155. doi:10.1002/hbm.10062
  2. Yushkevich PA, Piven J, Hazlett HC, et al. User-guided 3D active contour segmentation of anatomical structures: Significantly improved efficiency and reliability. NeuroImage. 2006;31(3):1116-1128. doi:10.1016/j.neuroimage.2006.01.015
  3. Avants BB, Tustison NJ, Song G, Cook PA, Klein A, Gee JC. A reproducible evaluation of ANTs similarity metric performance in brain image registration. NeuroImage. 2011;54(3):2033-2044. doi:10.1016/j.neuroimage.2010.09.025
  4. Maldjian JA, Laurienti PJ, Kraft RA, Burdette JH. An automated method for neuroanatomic and cytoarchitectonic atlas-based interrogation of fMRI data sets. NeuroImage. 2003;19(3):1233-1239. doi:10.1016/S1053-8119(03)00169-1

4.12 FLAIR in MNI space

cd /project/3015083.01/mengfei/Dengbo_Nifti/subjects-20210705/shenweiming/

shenweiming_base_flair=/project/3015083.01/mengfei/Dengbo_Nifti/subjects-20210705/shenweiming/shenweiming_AX_T2W_FLAIR_20170103173833_3.nii.gz

%% remove the skull

bet shenweiming_AX_T2W_FLAIR_20170103173833_3.nii.gz shenweiming_20170103_flair_brain.nii.gz -R -B -f 0.4

%% get the affine matrix and deformation mappting (warp file)
%% FLAIR_GG_853_1mm tempate was used

${antsReg} -d 3 -f $FLAIR_853  \
-m  nishixiang_20210112_flair_brain.nii.gz \
-o nishixiang_20210112_to_853_FLAIR_s_ants -t s -p f -n 12

%% register the FLAIR lesion mask into GG853 space (for lesion probability map)

antsApplyTransforms -d 3 --float 1 -i nishixiang_20210112_lesion.nii.gz -o nishixiang_20210112_lesion_in_853_FLAIR.nii.gz \
-r $FLAIR_853 \
-t [ nishixiang_20210112_to_853_FLAIR_s_ants_0GenericAffine.mat ] \
-n BSpline

fslmaths nishixiang_20210112_lesion_in_853_FLAIR.nii.gz -thr 0.5 -bin nishixiang_20210112_lesion_in_853_FLAIR_thr05_bin.nii.gz


cd /project/3015083.01/mengfei/Dengbo_Nifti/masks

%% first, obtain regional atlas mask by ijviewer (2mm in MNI space)
%% second, resampe the 2mm isotropic regional atlas into 1mm isotropic 

flirt -in frontal_lobe_2mm.nii.gz -ref frontal_lobe_2mm.nii.gz -applyisoxfm 1.0 -nosearch -out frontal_lobe_1mm.nii.gz
fslmaths frontal_lobe_1mm.nii.gz -thr 0.6 -bin frontal_lobe_thr06_1mm.nii.gz


%% register 1mm isotropic regional mask into subject-specific native space
%% please note, we should use the [inverse_matrix] and [InverseWarp file]

antsApplyTransforms -d 3 --float 1 -i /project/3015083.01/mengfei/Dengbo_Nifti/masks/frontal_lobe_thr06_1mm.nii.gz \
-o /project/3015083.01/mengfei/Dengbo_Nifti/subjects-20210705/shenweiming/20170103/frontal_lobe_in_shenweiming_NN.nii.gz \
-r /project/3015083.01/mengfei/Dengbo_Nifti/subjects-20210705/shenweiming/20170103/shenweiming_20170103_flair_brain.nii.gz \
-t [ /project/3015083.01/mengfei/Dengbo_Nifti/subjects-20210705/shenweiming/20170103/shenweiming_20170103_to_853_FLAIR_s_ants_0GenericAffine.mat,1 ] \
-t /project/3015083.01/mengfei/Dengbo_Nifti/subjects-20210705/shenweiming/20170103/shenweiming_20170103_to_853_FLAIR_s_ants_1InverseWarp.nii.gz \
-n NearestNeighbor

%% To gett the mask and volume of VOI

Note : the regional mask (e.g., frontal mask should be in native space )
  
  fslmathsshenweiming_20170103_lesion.nii.gz -mul frontal_lobe_in*NN.nii.gz frontal_lesion.nii.gz
  frontal_lesion_vol=$(fslstats frontal_lesion.nii.gz -V | awk -F'[ ]' '{print $2}')

4.13 Acapulco Cerebellum segmentation

Pipeline + Tutorial

Sigularity or Docker file installation Download link

Ref:

Kerestes R, Han S, Balachander S, Hernandez-Castillo C, Prince JL, Diedrichsen J, Harding IH. A Standardized Pipeline for Examining Human Cerebellar Grey Matter Morphometry using Structural Magnetic Resonance Imaging. J Vis Exp. 2022 Feb 4;(180). doi: 10.3791/63340. PMID: 35188124.

4.14 Acapulco cerebellar volume extraction


#!/bin/bash

start=`date +%s`

# t1_list=$(find . -name '*t1.nii*')
# echo "$t1_list" >> /home/neuro/codebank/GDPH/t1_list.txt

# basename   /home/neuro/MRI_GDPH/nifti/PD-348/anat/PD-348_visit_1_t1.nii.gz _t1.nii.gz
## output: PD-348_visit_1

cd /home/neuro/codebank/GDPH/cerebellum/enigma/acapulco

# file= /home/neuro/MRI_GDPH/ppmi/20220919_ppmi/ppmi_PD_HC_nifti/3102/Visit-00/t1/3102_Visit-00_t1.nii.gz
for file in $(cat /home/neuro/MRI_GDPH/ppmi/PPMI_t1_only/ppmi_t1_only_nif_list.txt  ); do
subj=$(basename $file _t1.nii.gz)
echo "=========

subj ID is $subj
==========="

mkdir -p output/${subj}
cp $file output/${subj}
singularity run --cleanenv -B $PWD:$PWD acapulco-0.2.1.sif -i $file -o output/${subj};

end1=`date +%s`
runtime1=$((end1-start))
echo "runtime1 is $runtime1"

done

4.15 sc-limbic segementation

#!/bin/bash


for input in $(cat /media/neuro/16t/ppmi_t1_long_all/all_t1_longitudinal_brain.txt );do

echo "$input"
#input=/media/neuro/16t/ppmi_t1_long_all/t1_longitudinal_freesurfer_template_all/3102_BL.long.3102_template/mri/brain.mgz
output_mgz=${input%.mgz}.sclimbic.mgz
output_nii_gz=${input%.mgz}.sclimbic.nii.gz
cBF_mask=${input%.mgz}.sclimbic.cBF.nii.gz

mri_sclimbic_seg --i "$input" --o "$output_mgz" --write_volumes --write_qa_stats
mri_convert "$output_mgz" "$output_nii_gz"

# 865,866 as L and R basal forebrain index 

fslmaths "$output_nii_gz" -thr 865 -uthr 866 -bin "$cBF_mask"

done