Overview of spm12r functions

Requires MATLAB (installs SPM to R library)

  • spm12_slice_timing - slices are not taken instantaneously
  • spm12_realign - people move
  • spm12_coregister - structural imaging is higher resolution
  • spm12_segment - where’s the gray matter?
  • spm12_normalize - brains look better in MNI
  • spm12_smooth - turn that noise down

Data used

library(httr)
install_dir = tempdir()
url = paste0("https://ndownloader.figshare.com/articles/",
             "5442298/versions/1")
zipfile = tempfile(fileext = ".zip")
res = GET(
  url, 
  write_disk(path = zipfile),
  if (interactive()) progress())
run_dir = tempfile()
if (!dir.exists(run_dir)) {
  dir.create(run_dir)
}
out_files = utils::unzip(zipfile, exdir = run_dir)
names(out_files) = neurobase::nii.stub(
  out_files, bn = TRUE)
file.remove(zipfile)

We know the repetition time (TR) is 2 seconds for this data. It may be encoded in the NIfTI file itself or come from a parameter file from the scanner. We will drop the first 20 seconds to allow for signal stabilization.

library(neurobase)
##################################
# Added quick reading of nifti header
##################################
oro_pkg = packageVersion("oro.nifti")
neuro_pkg = packageVersion("neurobase")
if (oro_pkg < 0.8 || neuro_pkg < 1.22) {
  get_nifti = neurobase::check_nifti 
} else {
  get_nifti = neurobase::check_nifti_header
}

fmri_filename = out_files["fmri"]
t1_fname = out_files["anat"]
tr = 1.8 # seconds
hdr = get_nifti(fmri_filename) # getting nifti header

nslices = oro.nifti::nsli(hdr)
n_time_points = oro.nifti::ntim(hdr)
time_points = seq(n_time_points)
ta = 0
slice_order = c(
  1740, 1680, 1620, 1560, 1500, 1440, 1380, 
  1320, 1260, 1200, 1140, 1080, 1020, 960, 
  900, 840, 780, 720, 660, 600, 540, 480, 
  420, 360, 300, 240, 180, 120, 60, 0, 
  1740, 1680, 1620, 1560, 1500, 1440, 1380, 
  1320, 1260, 1200, 1140, 1080, 1020, 960, 
  900, 840, 780, 720, 660, 600, 540, 480, 420, 
  360, 300, 240, 180, 120, 60, 0)
ref_slice = 900

Checking MATLAB

As SPM requires MATLAB and calls all the functions through the matlabr package, we will have checks in this vignette/workflow that the user has MATLAB. The have_matlab() function returns a logical that is TRUE when matlabr can find MATLAB to run the subsequent commands.

library(matlabr)
have_matlab()
## [1] FALSE

If this is not TRUE, almost none of the functionality below will run because it would simply result in errors.

Overall Processing

We will show how to do spatial realignment, slice-timing correction, spatial normalization to the MNI template (2 different ways), and spatial smoothing. Overall, there are many different ways to order these operations, with different options, so this represents just one way to organize a preprocessing pipeline.

Image Realignment

Realignment is referring to in this case as within-subject registration of the 4D fMRI data.

library(spm12r)
####################################
# Realignment
####################################
if (have_matlab()) {
  
  realigned = spm12_realign( 
    filename = fmri_filename,
    time_points = time_points,
    quality = 0.98, 
    separation = 3,
    register_to = "mean",
    est_interp = "bspline4",
    reslice_interp = "bspline4",
    clean = FALSE,
    install_dir = install_dir
  )
  ################################
  # reading in the mean image
  ##########################
  mean_img = realigned[["mean"]]
  mean_nifti = readnii(mean_img)
  
  rpfile = realigned[['rp']]
  rp = read.table(file = rpfile, header = FALSE)
}

Overall the spm12_realign does the realignment. There is some discussion of performing realignment before slice-timing correction because estimation of motion parameters may be skewed after slice-timing correction. We see that the output realigned has the output 4D fMRI data (outfiles), the realignment parameters (rp), voxel-wise mean after realignment (mean), and the matrix of transformations for the 4D series (mat).

Reading in the RP file

Here we can read in the rp file to show the estimated parameters. These can be used as regressors in motion correction for further analyses.

####################################
# Read in Motion data
####################################
if (have_matlab()) {
  rpfile = realigned[['rp']]
  rp = read.table(file = rpfile, header = FALSE)
  colnames(rp) = c("x", "y", "z", 
                   "roll", "pitch", "yaw")
  rp = as.matrix(rp)
  print(head(rp))
  print(dim(rp))
}

Slice-Timing Correction

A slice-timing correction does interpolation since each slice was not actually taken at the same time point, but a shifted time point over the course of an entire TR. The correction requires you to input the reference slice (in this case the median, ref_slice), the repetition time (tr), time between the first and the last slice within one scan (ta), and the order the slices were acquired. In our case, it was done in an ascending, contiguous order, so we created the slice order as such. If you used descending or interleaved acquisition, then this must be changed accordingly.

####################################
# Slice Timing Correction
####################################
if (have_matlab()) {
  
  aimg = spm12_slice_timing(
    filename = realigned[['outfiles']],
    nslices = nslices,
    tr = tr, 
    slice_order = slice_order,
    time_points = seq(n_time_points),
    ta = ta, 
    ref_slice = ref_slice,
    prefix = "a", 
    clean = FALSE, 
    retimg = FALSE,
    install_dir = install_dir
    )
  print(aimg)
}

We see the output aimg has the filename of the slice-timing corrected 4D image.

Spatial Normalization

AC-PC Alignment

For the subsequent image normalization steps, SPM assumes the data is aligned along the anterior commissure (AC) posterior commissure (PC) line (AC-PC). The acpc_reorient function (based on nii_setOrigin from Dr. Chris Rorden) will do this. The syntax is that the first file (mean_img) is used to estimate the line/plane and the subsequent files are reoriented using this estimation (aimg). These are changes to the header of the image and the image with the new header is written to the same file as the input file.

# if (have_matlab()) {
#   acpc_reorient(
#     infiles = c(mean_img, aimg),
#     modality = "T1")
# }

Anatomical MRI Coregistration to Mean fMRI

Here we will perform the registration of the T1-weighted anatomical image into the space of the mean fMRI image after realignment. This is referred to as “co-registration” as it is within-subject registration, but across modalities (where we referred to within-subject, within-modality as realignment).

Here, we also reorient the anatomical image the AC-PC line. We then perform the coregistration using spm12_coregister, where the fixed image is the mean image and the moving image is the anatomical.

if (have_matlab()) {
  # acpc_reorient(
  # infiles = t1_fname,
  # modality = "T1")
  coreg = spm12_coregister_estimate(
    fixed = realigned[["mean"]], 
    moving = t1_fname, 
    cost_fun = "nmi",
    retimg = FALSE,
    install_dir = install_dir
    )
}

We see the anatomical image has been transformed and resliced into the mean fMRI image space (and thus has the resolution of that image).

Anatomical MRI Segmentation (and Spatial Normalize Estimation)

Here we perform the segmentation of the co-registered anatomical image from above. This will segment the image into 6 different regions, where the regions are gray matter, white matter, cerebrospinal fluid (CSF), bone, soft tissue, and the background. You should inspect these visually before using them to ensure quality and no reordering due to artifacts.

if (have_matlab()) {
  seg = spm12_segment(
    filename = coreg$outfile,
    set_origin = FALSE, 
    bias_corrected = TRUE,
    native = TRUE,
    dartel = TRUE,
    unmodulated = TRUE,
    modulated = TRUE,
    affine = "mni",
    sampling_distance = 1.5,
    retimg = FALSE,
    install_dir = install_dir
    )
  print(names(seg))
}

In order to segment the image, SPM spatially normalizes the image to the MNI template, however. This transformation will be the one we use to transform the fMRI data to MNI space. We see in seg_reg a deformation file, which is the transformation. We also see the output segmentation files of the probability of each class, in native space. We only tend to care about the first 3 categories.

Applying Spatial Normalization Transformation

Now that we have estimated the transformation from the T1 image, we can take that deformation and apply it to the fMRI data using spm12_normalize_write. Again, we are registering to the MNI template and will use a standard bounding box. We pass the anatomical, mean fMRI, and 4D fMRI data in to be transformed.

if (have_matlab()) {
  norm = spm12_normalize_write(
    deformation = seg$deformation,
    other.files = aimg$outfile,
    bounding_box = matrix(
      c(-78, -112, -70, 
        78, 76, 85), nrow = 2, 
      byrow = TRUE),
    interp = "bspline5",
    retimg = FALSE,
    install_dir = install_dir
    )
  
  anat_norm = spm12_normalize_write(
    deformation = seg$deformation,
    other.files = seg$bias_corrected,
    bounding_box = matrix(
      c(-78, -112, -70, 
        78, 76, 85), nrow = 2, 
      byrow = TRUE),
    interp = "bspline5",
    voxel_size = c(1, 1, 1),
    retimg = FALSE,
    install_dir = install_dir
  )
  
  anat_norm2x2x2 = spm12_normalize_write(
    deformation = seg$deformation,
    other.files = seg$bias_corrected,
    bounding_box = matrix(
      c(-78, -112, -70, 
        78, 76, 85), nrow = 2, 
      byrow = TRUE),
    interp = "bspline5",
    voxel_size = c(2, 2, 2),
    retimg = FALSE,
    install_dir = install_dir
  )  
}

Now we have the indirect spatially normalized data in MNI template space.

Spatial Smoothing

Here we will perform spatial smoothing of the 4D fMRI data in template space. We can set the full-width half max (FWHM) for the Gaussian smoother. The relationship between the FWHM and the Gaussian standard deviation is:

\[ FWHM = \sigma \sqrt{8 \log(2)} \] where \(\log\)` is the natural log.

if (have_matlab()) {
  smooth_norm = spm12_smooth(
    norm$outfiles[[1]], 
    fwhm = 5, 
    prefix = "s5",
    retimg = FALSE,
    install_dir = install_dir
    )
}

In many applications, this is the data you will use for post-processing and analysis. Motion correction has usually been applied above, but some motion correct this data as well.

First Level Model

Estimate Model

output_directory = file.path(run_dir, "output")
if (!dir.exists(output_directory)) {
  dir.create(output_directory)
}
output_directory = normalizePath(output_directory)

################################
# Same model just using condition list
################################
condition_list = list(
  list(name = "LeftHand",
       onset = c(20, 100, 180, 260, 340, 420),
       duration = c(20, 20, 20, 20, 20, 20)
  ),
  list(name = "RightHand",
       onset = c(60, 140, 220, 300, 380, 460),
       duration = c(20, 20, 20, 20, 20, 20)
  )
)
if (have_matlab()) {
  first_model = spm12_first_level(
    scans = smooth_norm$outfiles,
    n_time_points = n_time_points,
    units = "secs",
    slice_timed = FALSE,
    tr = tr,
    condition_list = condition_list,
    regressor_mat = rpfile,
    outdir = output_directory,
    clean = FALSE,
    install_dir = install_dir
  )
  
  cons = list.files(
    pattern = "beta.*[.]nii", 
    path = output_directory,
    full.names = TRUE)
  print(cons)
}

Contrast Manager - Creating Contrasts

contrasts = list(
  list(
    name = "LeftHand",
    weights = c(1, rep(0, 7)),
    replicate = "none",
    type = "T" ),
  list(name = "RightHand",
       weights = c(0, 1, rep(0, 6)),
       replicate = "none",
       type = "T"), 
  list(name = "AllEffects",
       weights = rbind(
         c(1, rep(0, 7)),
         c(0, 1, rep(0, 6))
       ),
       replicate = "none",
       type = "F")   
)


if (have_matlab()) {
  contrast_res = spm12_contrast_manager(
    spm = first_model$spmmat,
    delete_existing = TRUE,
    contrast_list = contrasts,
    clean = FALSE,
    install_dir = install_dir
  )
}
if (have_matlab()) {
  dir(output_directory)
  
  cons = list.files(
    pattern = "con.*[.]nii", path = output_directory,
    full.names = TRUE)
  print(cons)
  stats = list.files(
    pattern = "spm(T|F).*[.]nii", 
    path = output_directory,
    full.names = TRUE)
  print(stats)
  # anat_img = readnii(anat_norm2x2x2$outfiles)
  # stat_t = readnii(stats[2])
}
contrast_query_list = list(
  list(name = "LeftHand",
       weights = 1,
       threshold_type = "FWE",
       number_extent_voxels = 0,
       mask_type = "None"),
  list(name = "RightHand",
       weights = 2,
       threshold_type = "FWE",
       number_extent_voxels = 0,
       mask_type = "None")  
)

contrast_query_list = 
  list(
    list(
    name = "All Contrasts",
    weights = Inf,
    threshold_type = "FWE",
    number_extent_voxels = 0,
    mask_type = "None")
  )
if (have_matlab()) {
  display = all(Sys.getenv("DISPLAY") != "")
  desktop = display
  result_format = "csv"
  results = spm12_results(
    spm = first_model$spmmat,
    units = "Volumetric",
    result_format = result_format,
    contrast_list = contrast_query_list,
    clean = FALSE,
    display = display,
    desktop = FALSE,
    write_images = "binary_clusters",
    image_basename = "thresholded",
    install_dir = install_dir
    )
  out_results = list.files(
    pattern = paste0("spm.*[.]", result_format),
    path = output_directory,
    full.names = TRUE)  
  # out_dir = spm_directory(spm = first_model$spmmat)
}

Bibliography