Literature DB >> 35051581

ciftiTools: A package for reading, writing, visualizing, and manipulating CIFTI files in R.

Damon D Pham1, John Muschelli2, Amanda F Mejia3.   

Abstract

There is significant interest in adopting surface- and grayordinate-based analysis of MR data for a number of reasons, including improved whole-cortex visualization, the ability to perform surface smoothing to avoid issues associated with volumetric smoothing, improved inter-subject alignment, and reduced dimensionality. The CIFTI grayordinate file format introduced by the Human Connectome Project further advances grayordinate-based analysis by combining gray matter data from the left and right cortical hemispheres with gray matter data from the subcortex and cerebellum into a single file. Analyses performed in grayordinate space are well-suited to leverage information shared across the brain and across subjects through both traditional analysis techniques and more advanced statistical methods, including Bayesian methods. The R statistical environment facilitates use of advanced statistical techniques, yet little support for grayordinates analysis has been previously available in R. Indeed, few comprehensive programmatic tools for working with CIFTI files have been available in any language. Here, we present the ciftiTools R package, which provides a unified environment for reading, writing, visualizing, and manipulating CIFTI files and related data formats. We illustrate ciftiTools' convenient and user-friendly suite of tools for working with grayordinates and surface geometry data in R, and we describe how ciftiTools is being utilized to advance the statistical analysis of grayordinate-based functional MRI data.
Copyright © 2022. Published by Elsevier Inc.

Entities:  

Keywords:  Grayordinate; Toolbox; fMRI

Mesh:

Year:  2022        PMID: 35051581      PMCID: PMC9119143          DOI: 10.1016/j.neuroimage.2022.118877

Source DB:  PubMed          Journal:  Neuroimage        ISSN: 1053-8119            Impact factor:   7.400


Introduction

Surface-based analysis of magnetic resonance (MR) data was pioneered by Freesurfer (Fischl, 2012) and further popularized by the Human Connectome Project (HCP) (Van Essen et al., 2013). There is significant interest in adopting surface-based analysis for a number of reasons, including improved whole-cortex visualization (Fischl et al., 1999a; Van Essen, 2012), mitigating problems associated with volumetric smoothing such as reduced sensitivity and specificity (Coalson et al., 2018; Brodoehl et al., 2020), improved inter-subject alignment of cortical folding patterns and functional areas (Fischl et al., 1999b; Anticevic et al., 2008; Glasser et al., 2016), and reduced dimensionality. Until fairly recently, surface-based MR data were only stored in data formats that exclude relevant subcortical and cerebellar gray matter regions of the brain. For example, GIFTI files are a type of surface format that can contain either metric data (e.g. functional MRI [fMRI] timeseries), label data (e.g. a parcellation) or surface geometry data for a particular hemisphere. Incorporating subcortical and/or cerebellar gray matter in an analysis would require pairing the surface data with volumetric data stored in a traditional NIFTI file. To address this limitation and to advance and promote the adoption of “grayordinates” MR data —a term referring collectively to the cortical, subcortical, and cerebellar gray matter —the HCP introduced the CIFTI file format (Glasser et al., 2013). “CIFTI” is an acronym for the “Connectivity Informatics Technology Initiative.” (The “N” in “NIFTI” stands for “Neuroscience” and the “G” in “GIFTI” stands for “Geometry.”) CIFTI files are a type of NIFTI file with a numeric matrix for all the grayordinates data, paired with an XML header containing information on the size and type of the data, column names, and brain structure labels. CIFTI files are thus a single data representation for all grayordinates. This combined format provides a convenient and compact file structure for users to perform analysis across all gray matter areas of the brain. Grayordinate-based analysis of MR data also facilitates leveraging information shared across (1) individuals, since spatial alignment of functional areas across subjects is improved, and (2) the brain, since distances along the cortex and within specific gray matter structures tend to be inversely related to similarity of functional and structural features. Traditional MR analysis techniques benefit from these properties when adapted to grayordinate space, such as group averaging, geodesic surface smoothing and parcel-constrained volumetric smoothing. Accuracy and power can be further improved through Bayesian statistical techniques, many of which are implemented in the R statistical environment (R Core Team, 2021). Examples include Markov chain Monte Carlo (Martin et al., 2011), an interface to the Stan probabilistic programming language (Stan Development Team, 2021b), Bayesian hierarchical models (Plummer, 2003), integrated nested Laplace approximation (INLA) for fast and accurate posterior estimation (Rue et al., 2009), spatial process priors suitable for surface-based modeling (Lindgren and Rue, 2015), and excursion set approaches useful for performing joint inference across the cortex to leverage spatial information (Bolin and Lindgren, 2016). However, the ability to use these advanced statistical methods is currently limited by a lack of tools available for working with CIFTI-format and other surface-based neuroimaging data in R. Here, we present the ciftiTools R package, which provides a user-friendly, high-level interface for accessing and analyzing CIFTI and GIFTI data. Specifically, ciftiTools is a suite of tools for reading, writing, visualizing, processing, and manipulating CIFTI data and compatible surface geometries (Fig. 1). It supports three CIFTI intents or file types: “dtseries” (for timeseries data), “dscalar” (for structural, continuously-valued data), and “dlabel” (for parcellations, labels, or categorical data). It also supports GIFTI metric data (analogous to “dtseries” or “dscalar”) and label data (analogous to “dlabel”) for wider applicability to surface-based analysis. We introduce the object class “xifti”, which refers to the combination of metric or label data (traditionally encoded in CIFTI files or GIFTI metric or label files) with surface geometries encoded in GIFTI surface geometry files. This facilitates the visualization, processing, and analysis of surface data, since the data and its geometric organization are contained within a single object. Below, we describe the structure and functionality of the ciftiTools package (Section 2) and demonstrate its use in an example seed correlation analysis (Section 3). We also explain its relationship with other packages and applications (Section 4, summarized in Table 1) to illustrate that ciftiTools uniquely provides unified support for reading, writing, plotting, and manipulating CIFTI-format data.
Fig. 1.

Summary of ciftiTools functionality.

ciftiTools supports reading and writing (A), visualization (B), Workbench processing (C), and data manipulation and math (D) for CIFTI- and GIFTI-format data.

Table 1

Summary of comparison between programmatic tools for CIFTI and GIFTI files.

Checkmarks are assigned if the tool (rows) directly enables a user to complete the task (columns). A “3” for CIFTI functionalities in ciftiTools indicates that only three CIFTI intents are supported: “dtseries,” “dscalar,” and “dlabel.” Moreover, tools receiving checkmarks in the same column may enable the task to different extents. For example, the manipulation functions in hcp-utils support normalizing data values and applying a parcellation, whereas those in cifti-matlab support data and metadata replacement. While ciftiTools is designed to support all listed tasks, other tools are not meant to support all these tasks on their own. For example, hcp-utils is designed to be used in conjunction with NiBabel and nilearn. Lastly, note that some tools have external dependencies: ciftiTools also requires the Connectome Workbench for most of its functionality, ggsegExtra requires FreeSurfer for reading in new parcellations, and ciftify uses FSL, FreeSurfer and the Connectome Workbench to convert and manipulate CIFTI files. An asterisk has been added to the “Language” column for these tools to indicate the need for additional software.

LanguageRead
Write
Plot
Manipulate
CIFTIGIFTICIFTIGIFTICortexSubcortexCIFTIGIFTI
ciftiToolsR *333
ciftiR
giftiR
freesurferformats, fsbrainR
ggseg, ggseg3d, ggsegExtraR *
ciftifyPython *
NiBabelPython
nilearnPython
hcp-utilsPython
cifti-matlabMATLAB
GIfTIMATLAB

Overview of ciftiTools structure and functionality

Figure 1 illustrates the general use case for ciftiTools. A “xifti” object can be constructed from either a CIFTI file or a combination of GIFTI metric or label files and a NIFTI file. In either case, two GIFTI surface geometry files may also be included (Panel A). The “xifti” can subsequently be visualized (Panel B), processed and manipulated (Panels C and D), and written back to a file(s) (Panel A). The integration of surface geometry is convenient because surfaces are required for visualizing and smoothing the cortical data, since no cortical spatial information is included in CIFTI files. Subcortical voxel locations and brain structure labels, in contrast, are contained in the CIFTI XML. In this section, we first describe the structure of the “xifti” object class, and then describe the functionality illustrated in each panel of Fig. 1 in greater detail. For the sake of brevity we will not catalog every function belonging to each panel, nor will we cover the functions which do not fit into any of the four panels. However, an organized list of the most commonly used functions can be accessed in Appendix A and is reproduced in R with the command help(ciftiTools). A complete, alphabetical list of all ciftiTools functions can be accessed with the command help(package = “ciftiTools”). For each function, more information can be accessed at its help page using the command help(function_name), e.g. help(read_xifti).

The “xifti” object class

Figure 2 illustrates the structure of the “xifti” object class. It is organized as a nested list with three entries at the first level: data, the data matrices for each brain structure; surf, the left and right cortical surface geometries; and meta, the various metadata including medial wall masks (see Appendix B for information about the medial wall), subcortical labels and mask, and CIFTI intent-specific information. If any entry is not present in the “xifti” it will have a value of NULL. Since a “xifti” is a list, its contents can be parsed with $. For example, xii$meta$cifti$intent returns the CIFTI intent of the “xifti” object xii.
Fig. 2.

The structure of a “xifti“ object.

A “xifti“ object can be constructed from CIFTI data and GIFTI surface geometry data using read_xifti. The object is a nested, ordered list, and any components that are absent will be NULL, for example if the CIFTI did not contain every brain structure or if no surfaces were provided. Using read_xifti2 or as.xifti, it is also possible to construct a “xifti” object from GIFTI files which contain cortical data and/or a NIFTI file which contains subcortical data, rather than from a CIFTI file. In this case, the CIFTI metadata (intent, brain structures, intent-specific metadata, misc.) will be absent.

The left and right cortical surface geometries are themselves objects of class “surf”. A “surf” object is a list with three entries: vertices, faces, and hemisphere. A “surf” object can also exist separately from any “xifti” object, allowing for direct visualization, resampling, and manipulation of surface geometry data in the absence of metric or label data. The function is.xifti can be used to verify that an R object is a correctly-formatted “xifti” object. This validation is especially useful if the user has manually manipulated the data or metadata in a “xifti” and requires it to be correctly formatted, for example if they plan to write it to a file, visualize it, or further process it with ciftiTools. Several S3 methods are implemented in ciftiTools. S3 methods control the behaviors of certain base R functions when applied to objects of a specific class. Currently, “xifti” objects have S3 methods for summary, print, plot, and several mathematical operations. For example, plot(xii) will invoke the functions view_xifti_surface and/or view_xifti_volume, as described in Section 2.3. “surf” objects have S3 methods for summary, print, and plot. For both “xifti” and “surf” objects, summary and print will display an overview of the object’s contents. Other S3 methods for “xifti” and “surf” objects are described in the corresponding subsections below.

Reading and writing

Figure 1 A shows how the ciftiTools function read_xifti imports CIFTI data into R as a “xifti” object. read_xifti may also import GIFTI surface geometry data alongside the CIFTI data. Any surfaces will be resampled to match the cortical data resolution in the CIFTI, if there is a difference in resolution. The flow of data is reversed when a “xifti” is written out with write_xifti : surfaces, if any, are written to GIFTI files, and everything else is written to a CIFTI file. Two functions, as.xifti and read_xifti2, provide alternative methods for constructing a “xifti” object. as.xifti creates a “xifti” from R data matrices instead of a CIFTI file, allowing the user to store grayordinate data which may not originate from real neuroimaging, e.g. simulated data. For example, with as.xifti the user can simulate data using a number of powerful simulation tools in R, and then format the data as “xifti” grayordinate data. This “xifti” can then be analyzed with ciftiTools, or it can be written to a CIFTI file for analysis or visualization with methods and software outside of R. The other alternative function, read_xifti2, creates a “xifti” from GIFTI metric or label files instead of a CIFTI file. It is provided to allow for greater flexibility in analyses that are focused on the cortical surface specifically, which would not require the CIFTI format. Additional functions related to reading and writing include separate_xifti, which splits a CIFTI file into GIFTI metric or label files for the cortical data and a NIFTI file for the subcortical data, and info_xifti, which reads in only the metadata of a CIFTI file. write_xifti2 does the opposite of read_xifti2 : it writes a “xifti” with surface data to GIFTI metric or label files. And for surfaces, read_surf and write_surf translate between GIFTI surface geometry files and “surf” objects. A “xifti” object can also be written to an RDS data file using saveRDS, and read back in with readRDS, both base R functions. This allows R users to store CIFTI data and GIFTI surfaces in a single file. However, RDS files are generally not compatible with other programming platforms such as MATLAB or Python. Users interested in cross-platform compatibility should instead use write_xifti to generate CIFTI and GIFTI surface geometry files for subsequent use with MATLAB, Python, or other tools (see Section 4.4).

Visualization

Figure 1 B illustrates how the grayordinates data in a “xifti” object can be visualized with view_xifti. Equivalently, the generic R function plot can be applied to a “xifti” object, since view_xifti is the plot S3 method for “xifti” objects. view_xifti will plot the cortical data with view_xifti_surface and the subcortical data with view_xifti_volume. If the “xifti” object contains both cortical and subcortical data, the two plots will share the same color scale, palette, and color scale limits. view_xifti_surface and view_xifti_volume can also both be called directly. The functions have similar interfaces: for example, they both can produce either interactive widgets or static images exportable to PNG files. However, they differ in a few notable ways, as described below. The view_xifti_surface function produces a 3D rendering of the cortical surface data using the rgl package (Murdoch and Adler, 2021). By default, the data are plotted on averaged “inflated” surfaces from the HCP included with ciftiTools (Glasser et al., 2013) unless other surfaces are contained in the “xifti” or provided in the optional function arguments. (The default “inflated” surfaces are shown in Fig. 1; see Appendix D for a list of other surfaces included in ciftiTools). Additional arguments control the color scale type (sequential, diverging, or qualitative); palette and color scale limits; the hemisphere(s) and view(s) (medial and/or lateral) to show; the data column(s) to display; and whether the plot should be interactive or written to a PNG file(s). If an interactive plot is created with view_xifti_surface, the user may click and drag to rotate the surfaces and scroll to resize them. The interactive plot will usually open in an OpenGL window (Shreiner, 2009) but in specific cases will open in an HTML widget (Vaidyanathan et al., 2020). The help page help(view_xifti_surface) explains in depth when each is used, but in general, the HTML widget is used only if: multiple measurements are requested (since it can include a slider bar to control the measurement being displayed); the argument widget is set to TRUE; or if the computing platform is not compatible with OpenGL. All three output types (PNG files, OpenGL windows, and HTML widgets) can be embedded in HTML R Markdown documents, and the PNG files can be embedded in PDF R Markdown documents (see Appendix C). Note that for PNG files and HTML widgets, each plot first needs to be rendered in a temporary OpenGL window which will close automatically. The view_xifti_volume function produces a 2D slicewise plot of the subcortical and cerebellar data overlaid on a 2 mm MNI structural template by default (Evans et al., 2012). It has the same arguments as view_xifti_surface for controlling the measurement(s) being plotted and the interactivity or file saving. The non-interactive plot is based on the overlay function from the oro.nifti package (Whitcher et al., 2011) and additionally has the same arguments for color scale type, palette, and color scale limits as view_xifti_surface. It also includes arguments to control the anatomical plane and slice indices being shown. The interactive plot is a wrapper to the namesake function of the papayar package (Muschelli, 2016) and allows the user to scroll through slices along each anatomical axis and read the value at each voxel. The color scale, palette, and color scale limits can be adjusted within the GUI. The non-interactive plot can be exported to a PNG file and then embedded in R Markdown documents (see Appendix C). “surf” objects can also be visualized independently of any “xifti” data using the function view_surf. The plot S3 method for “surf” objects serves as an alias for view_surf. Like view_xifti_surface, view_surf is based on the rg1 package (Murdoch and Adler, 2021) and includes arguments to control the view(s) to show and whether the plot should be interactive or written to a PNG file. ciftiTools also includes the function view_comp to assist users with displaying multiple PNG files at a time. view_comp could be used to display the data for multiple columns or “xifti” objects all in a grid, or to display corresponding cortical and subcortical plots side-by-side.

Processing

The Connectome Workbench is a suite of open-source software tools for neuroimaging data designed especially for HCP data (Marcus et al., 2011). It includes numerous command-line tools that can execute operations on CIFTI files and other data formats. The ciftiTools package provides a convenient interface for a few Workbench commands including two common processing operations, namely resampling and smoothing, as illustrated in Fig. 1 C. Both “xifti” objects and CIFTI files can be directly resampled and smoothed using ciftiTools, as described below. A full list of Workbench commands used by ciftiTools is in Section 4.1.1, and more interfaces to Workbench commands may be implemented in the future based on user needs. To resample cortical data with resample_xifti, the user simply provides the “xifti” object or path to a CIFTI file, along with the target resolution specified in vertices per hemisphere. Other necessary files, such as the spherical geometries in-register with the target and original resolutions, will be generated automatically in a temporary directory. Note that the exact number of vertices after resampling may differ slightly from the target resolution due to the spherical mapping process by which resampling is performed. Also, note that the subcortex and cerebellum are never resampled. If surfaces are included in the “xifti” object or are specified as GIFTI files by the user, they will be resampled along with the CIFTI data matrix to the same target resolution. It is also possible to resample metric, label, and surface geometry GIFTI files with the function resample_gifti and “surf” objects with the function resample_surf. Smoothing can be performed geodesically along the cortical surface and volumetrically for subcortical and cerebellar data using the function smooth_cifti. The user simply provides a “xifti” object or path to a CIFTI file and the full width at half maximum (FWHM) of the smoothing kernel. Cortical geodesic smoothing will be performed based on the default “inflated” surfaces unless other surfaces are included in the “xifti” or provided in the optional function arguments. By default, volumetric smoothing is constrained within each subcortical structure to avoid blurring across regional boundaries. It is also possible to smooth metric GIFTI files with the function smooth_gifti. One consideration for both resample_xifti and smooth_xifti is that they will process a CIFTI file faster than its equivalent “xifti” object. This is because the Connectome Workbench commands operate on CIFTI files, so “under the hood” of both functions operating on a “xifti” object, that object must be written to a CIFTI file, resampled or smoothed, and then read back in. Writing a “xifti” object is trivially fast for CIFTI data with one or few measurements, but can be slow for a high-resolution CIFTI with many measurements, such as fMRI timeseries data. In the latter case, it is therefore more efficient to directly resample or smooth the CIFTI file before reading it in, if possible.

Math and manipulation

As illustrated in Fig. 1 D, ciftiTools provides several convenient functions for altering “xifti” objects while preserving a valid “xifti” object structure. These fall into two categories: manipulation and math. Manipulation functions explicitly alter one or multiple “xifti” objects. Several of these are listed on the left of Panel D (see Appendix A for a full list with descriptions). They include functions to add or remove brain structures, subset the data matrix or combine it with others, etc. Manipulation functions reduce the need for users to manually edit individual brain structure entries within a “xifti” object while ensuring that the metadata is updated appropriately to preserve a valid “xifti” format. Math functions perform mathematical operations, such as arithmetic and univariate transformations, on just the data matrix of one or more “xifti” objects. These are base R functions that can be applied directly to “xifti” objects. For example, the data matrices of two “xifti” objects can be added together with the command xii1 + xii2; the data matrix of a single “xifti” object can be log-transformed using the command log(xii1). xii1 - xii1 == 0 returns a “xifti” with all values equal to 1, representing TRUE. All Math functions are implemented as S3 methods for “xifti” objects; as such, they are limited to fundamental arithmetic and univariate operations (see Appendix A for a full list with descriptions). To perform more advanced mathematical manipulation or analysis of “xifti” objects, we recommend that users extract the data matrix with as.matrix, make the desired changes, and then update the data matrix of the “xifti” object using the function newdata_xifti. For simple operations, though, the manipulation and math functions included in ciftiTools allow users to work with CIFTI data conveniently and with concise code, while providing the building blocks for users to create more involved processing routines specific to their needs.

Example

In this section, we will illustrate some of the ciftiTools functionality through a simple example analysis of computing and visualizing seed correlations for a resting-state fMRI (rfMRI) scan from the HCP (Van Essen et al., 2013) which has been pre-processed with ICA-FIX (Salimi-Khorshidi et al., 2014). Our seed will be the posterior cingulate cortex (PCC), a highly-connected node of the default mode network (DMN). We will use functional parcellations created by Schaefer et al., 2018 to define the PCC and other brain regions. The analysis is divided into four steps: (1) reading in and smoothing the fMRI data; (2) reading in the parcellation; (3) calculating seed correlations; and (4) visualizing and saving the results. An expanded demonstration which includes data cleaning, the subcortical data, and more functions from ciftiTools is available in the Supplementary Materials. Note that we will read in the rfMRI data from a subfolder Data, and we will write out plot image files to a subfolder Plots, so to run this code again these two directories would need to be created, and a rfMRI CIFTI file would need to be downloaded from the HCP and placed in Data.

Reading in and smoothing the fMRI data

We begin by loading ciftiTools and pointing to the Connectome Workbench folder. Now we can read in the CIFTI file containing the resting-state fMRI (rfMRI) data with read_xifti. By default, only the left and right cortex are read in: set brainstructures = “a11” to also read in the subcortex. For simplicity, we will not include the subcortex in this analysis (see the expanded demonstration in the Supplementary Materials). xii stores the CIFTI data as a “xifti” object. summary, or equivalently invoking the implicit print S3 method, will produce an overview of its contents: The S3 method as.matrix will return the timeseries data in matrix form, with locations (vertices and/or voxels) along the rows and measurements (timepoints) along the columns. Functions like dim which coerce their inputs to data matrices will behave accordingly: Now we will spatially smooth the data with smooth_xifti using a geodesic Gaussian smoother. We will use the default 5 mm FWHM width, but other levels of smoothing are possible using the surf_FWHM argument to smooth_xifti. As suggested at the end of Section 2.4, we smooth the original CIFTI file and then read it in, rather than smoothing xii which would be slower. We can plot the first columns of xii and xii_sm to get an idea of the data scale, range, and effect of smoothing. plot will create a 3D visualization of the cortical data by invoking view_xifti_surface, as described above in Section 2.3. There are several options for displaying the plots (see Appendix C). Here we will plot each “xifti” separately, save the two plots to PNG files, and then composite the PNG files together with view_comp (Figure 3).
Fig. 3.

First fMRI volume before and after smoothing with smooth_xifti.

The color scale limits have been automatically determined based on the data, so they are close but slightly different. Nonetheless, the data on the right are clearly similar to the original except smoother across space.

Reading in the parcellation

Now we will load the parcellation. For convenience, ciftiTools includes a few commonly used parcellations, which can be read in using load_parc (refer to Appendix D) (Schaefer et al., 2018; Thomas Yeo et al., 2011). Here we will use the Schaefer parcellation with 400 parcels. Other parcellations in CIFTI or GIFTI format can be read in using read_xifti or read_xifti2, respectively. Again, we can get an overview of the “xifti” object parc by using summary. The parcellation includes data for the left and right cortical hemispheres at the same resolution of the rfMRI data (approx. 32,000 vertices per hemisphere). The parcellation has the “dlabel” intent which indicates that it contains label i.e. categorical data. Specifically, for each measurement (column) every data location is assigned an integer “key” which corresponds to a certain label and color. A table in the metadata gives the label and color of each key, for each measurement. This file has only one measurement, “parcels”. Its keys range from 0 to 400, with 0 indicating the medial wall and 1–400 indicating a specific parcel. When visualizing the parcellation with plot, each parcel will be colored according to the label table colors by default. In this parcellation, parcels are grouped by network, and those in the same network are colored identically. Therefore, adjacent parcels in the same network are impossible to delineate by color. We can use the border argument of view_xifti_surface to draw outlines between vertices of different keys, allowing us to visualize both the networks, according to color, and the individual parcels, according to outlines. We will also separately visualize parcel 14, which corresponds closely to the PCC. We use transform_xifti to create a mask of only that parcel. The full parcellation and the masked PCC parcel are shown side-by-side in Fig. 4.
Fig. 4.

Schaefer parcellation and PCC parcel.

Computing seed correlations

Now that we have the smoothed rfMRI data and parcellation, we can compute the seed correlations. We begin by obtaining the mean timeseries of each parcel. This is easier done with the parcel data directly, rather than with the parc “xifti” object, so we will start by converting the parcellation to a vector. Then, we’ll replace the medial wall vertices in xii_sm with NA data values so that the length of the parcellation vector, parc_vec, will match the number of cortical data vertices in xii_sm. (See Appendix B for information about the medial wall.) Now for each parcel we will obtain the mean time series across its constituent vertices. Specifically, we will pre-allocate a matrix xii_pmean, and then for each parcel we will obtain the fMRI timeseries for all its vertices, take the average across space while ignoring medial wall values, and then save the resulting timeseries to a row of xii_pmean. We then calculate the seed correlations between the PCC parcel and every other parcel.

Visualizing and saving the results

We can visualize the results by creating a new “xifti” with newdata_xifti. It will contain one measurement (column) in which the value of each vertex will be the seed correlation for the parcel it belongs to. Notice how the parcellation was converted from a “xifti” to a numeric matrix in the previous section with as.matrix, and after several mathematical operations, it’s now being returned to a “xifti” with newdata_xifti. As suggested in Section 2.5, this is a workflow to use when it is not possible to obtain the result with only the operations built in to ciftiTools. First we’ll convert parc_vec, which gives the parcel key of each vertex, to xii_seed, which gives the seed correlation of the parcel each vertex belongs to. Then we will initialize a one-column “xifti” using select_xifti and replace its data with xii_seed using newdata_xifti. Now we can use the “xifti” S3 method plot again. We’ll use it twice to demonstrate the ability of view_xifti to automatically choose an appropriate zlim (Fig. 5).
Fig. 5.

PCC seed correlation.

As expected, we find that most seed correlation values are positive or near zero, and the brain regions with the highest seed correlation are components of the DMN. Lastly, we can save the result of our analysis with write_xifti. We will write the data to a “dscalar” CIFTI because it does not represent a timeseries (“dtseries”) nor categorical/label data (“dlabel”).

Relationships with other tools and packages

In this section we describe a few key dependencies and reverse dependencies of ciftiTools, and we compare ciftiTools with similar tools in R as well as in other programming environments.

Dependencies of ciftiTools

ciftiTools has one external dependency, the Connectome Workbench, and several dependencies on other R packages.

Connectome Workbench

Several functions in ciftiTools depend on Connectome Workbench commands (Marcus et al., 2011), and are listed in Table 2. To access the full functionality of ciftiTools, including reading and writing files, the user must therefore have the Workbench installed in their computing environment, and the path to the Connectome Workbench must be indicated at the beginning of each session after loading the package as previously demonstrated in Section 3 :
Table 2

Connectome Workbench commands used by ciftiTools.

Note that any Workbench command, including those not currently integrated in the package, can be executed from within R using the ciftiTools function run_wb_cmd, which conveniently appends the Workbench path to the beginning of the command. Workbench commands can also be executed within the R environment using the base R function system.

ciftiTools functionWorkbench command(s) it interfaces with
info_cifti-nifti-information
read_xifti-cifti-convert, -metric-merge
write_xifti-cifti-create-dense-timeseries, -cifti-create-dense-scalar, -cifti-create-label
separate_cifti-cifti-separate
write_nifti-volume-label-import
resample_xifti and resample_gifti-cifti-separate, -metric-resample, -label-resample, -surface-resample, -surface-create-sphere, -surface-flip-lr, -set-structure, -cifti-create-dense-timeseries, -cifti-create-dense-scalar, cifti-create-label
resample_cifti_from_template-cifti-resample
smooth_xifti-cifti-smoothing, -cifti-change-mapping
smooth_gifti-metric-smoothing
convert_xifti-cifti-change-mapping
where /path/to/workbench is the location of either the Connectome Workbench folder or the executable file inside of it (wb_command on Mac and Linux or wb_command.exe on Windows). The path to the executable will be printed to indicate that it was set correctly; otherwise, a warning message will be displayed. If Workbench-dependent tasks are attempted prior to setting the Workbench path, an error message will be displayed. The view_xifti_surface function does not rely on Workbench commands, but was designed to emulate several aspects of visualization using the Workbench, including the layout and default color scales. Appendix E shows a comparison between a plot produced with ciftiTools and one produced with the Connectome Workbench for the same data. Similarly, some manipulation functions resemble Workbench commands but do not depend on them: for example, merge_xifti emulates -cifti-merge, apply_xifti is similar to -cifti-reduce, and transform_xifti is analogous to -cifti-math. These manipulation functions operate completely inside R, saving time by avoiding the need to write the “xifti” to a CIFTI file, process it with Workbench, and then read it back in, as is required for resample_xifti and smooth_xifti. apply_xifti and transform_xifti also benefit from being able to use any R function, including one created by the user, compared to the Workbench commands which are limited to predefined arguments.

Other R packages

ciftiTools depends on several other R packages for working with GIFTI and NIFTI-format data. Specifically, the gifti package (Muschelli, 2020) supports reading, writing, and parsing GIFTI files. The RNifti package (Clayden et al., 2021) supports reading and writing NIFTI files, in particular subcortical data which has been separated from a CIFTI file. Cortical visualizations are based on the rgl package (Murdoch and Adler, 2021). Subcortical visualizations are based on the oro.nifti package (Whitcher et al., 2011) for static plots and the papayar package (Muschelli, 2016) for interactive plots. A full list of dependencies can be found in the package DESCRIPTION file.

R packages building on ciftiTools for grayordinates data analysis

Several R packages depend on ciftiTools to apply both traditional and more advanced statistical analysis techniques to fMRI in grayordinates format. The BayesfMRI package (Spencer et al., 2021) can be used to perform general linear model (GLM) analysis on task fMRI data for identifying activations. It includes a spatial Bayesian approach designed for cortical surface analysis (Mejia et al., 2020b) in addition to the classical massive univariate approach (Friston et al., 1994). The package templateICAr (Mejia, 2021) includes routines for group independent component analysis (ICA) and estimation of corresponding subject-level independent components (ICs) via dual regression (Beckmann et al., 2009) or template ICA (Mejia et al., 2020a). Lastly, fMRIscrub (Pham et al., 2021a) includes routines for data-driven scrubbing (Smyser et al., 2011; Mejia et al., 2017; Afyouni and Nichols, 2018; Pham et al., 2021b), motion scrubbing (Power et al., 2014), and denosing strategies such as anatomical CompCor (Behzadi et al., 2007).

Comparison with other R packages for working with CIFTI files

As listed in Table 1, a few R packages also support CIFTI files, to varying extents. Below we describe each package in more detail and compare its functionality with that of ciftiTools.

The cifti R package

The cifti R package reads in CIFTI files with any intent (Muschelli, 2018). It does not currently support writing or visualizing CIFTI files. In contrast, ciftiTools was designed to work specifically with the “dtseries,” “dscalar,” and “dlabel” intents. Given this more limited scope, ciftiTools aims to provide easy access and analysis of CIFTI data with these intents. For example, to extract the right cortex data from a “xifti” object named xii using the ciftiTools package, the code is whereas the corresponding code for a “cifti” object named cii using the cifti package, shown below, is more verbose. This is because the “cifti” object more closely resembles the original structure of the CIFTI XML, which must be generalizable to all CIFTI intents. Another important difference is that ciftiTools integrates the Connectome Workbench and support for GIFTI surface geometry, which opens up more functionalities, particularly those listed in Panels B and C of Fig. 1. In contrast, the cifti package does not have any external dependencies. In summary, whereas ciftiTools makes it easy to work with dtseries, dscalar, or dlabel CIFTI files, users interested in working with other intent types, who want to read in the data structured similarly to the original CIFTI file, or who do not want to depend on the Connectome Workbench should look to cifti as an alternative. The R package xml2 may also be helpful for parsing the XML metadata in CIFTI files at a low level (Wickham et al., 2020).

The gifti R package

The gifti R package reads and writes GIFTI files, but does not provide further support (Muschelli, 2020). ciftiTools depends on gifti for reading and writing GIFTI files, for example with read_xifti2 and write_xifti2, and therefore builds on top of it to provide additional support for surface-based analyses including visualization and data manipulation. The “xifti” object also allows users to work with the corresponding left and right hemisphere data together, rather than having to separately process the left and right GIFTI files.

The freesurferformats and fsbrain R packages

The R package freesurferformats provides low-level reading and writing functionality for many different types of neuroimaging files, and fsbrain interfaces with it to offer higher-level reading and writing functions as well as a suite of visualization tools (Schäfer and Ecker, 2020; Schäfer and Ecker, 2021). The focus of these packages is on structural surface modalities. They are especially designed to support Freesurfer output, but are not limited to the FreeSurfer files or organization structures. There is limited support for CIFTI-format files. For example, the function for reading CIFTI files in freesurferformats, which is built on top of the cifti package, does not distinguish between the left and right hemispheres when reading in data from across the entire cortex. As with cifti, it cannot write out CIFTI files. Compared with ciftiTools, code to accomplish the same task can be more verbose. For example, to plot the cortical data with ciftiTools the command is

The ggseg, ggseg3d, and ggsegExtra R packages

Brain atlases (i.e. segmentations or parcellations) can be plotted with 2-dimensional graphics using ggseg and 3-dimensional, interactive graphics using ggseg3d (Mowinckel and Vidal-Piñeiro, 2020). ggseg relies on ggplot2 whereas ggseg3d relies on plotly. Each package includes two parcellations —the Desikan-Killiany cortical atlas (Desikan et al., 2006) and the Fischl subcortical segmentation (Fischl et al., 2002) —and additional parcellations can be loaded with a separate package, ggsegExtra. While both ciftiTools and ggseg3d can dis- play cortical data on a 3D mesh, ggseg and ggseg3d offer additional visualizations not provided by ciftiTools : ggseg can display cortical data as orthogonal slices, and ggseg3d can display subcortical data as 3D, interactive images. However, these visualizations are primarily useful for parcellated data. In contrast, ciftiTools can display parcellated data but is not limited to it, having the ability to visualize the cortical surface and subcortical volume at the same resolution as the original data. Another important distinction is that ciftiTools is designed for CIFTI, GIFTI, and NIFTI file compatibility whereas ggseg, ggseg3d, and ggsegExtra are designed for Freesurfer-format file directories. In fact, to import new parcellations with ggsegExtra, an installation of Freesurfer is required. Conversion between Freesurfer-format file directories and CIFTI or GIFTI files is possible but non-trivial, so we recommend using ggseg, ggseg3d, and ggsegExtra to work with Freesurfer-format parcellations, and ciftiTools to work with CIFTI files, GIFTI files, and/or non-parcellated data.

Working with CIFTI files in other programming environments

Several tools have been developed in the Python (van Rossum and Drake, 1995) and MATLAB (MATLAB, 2021) programming languages to provide varying levels of support for CIFTI processing, analysis, and visualization. In this section we describe those listed in Table 1 in greater detail.

Python

The ciftify module (Dickie et al., 2019) converts volumetric fMRI images with accompanying structural T1 -weighted files to the CIFTI format using fmriprep tools, allowing CIFTI-based Workbench and HCP tools to be used on data not originally in the CIFTI format. ciftify has functionality for analyzing and visualizing the resulting files, including a comparison with the original data for quality assurance. The fMRI data are not read into the environment; rather, ciftify functions operate on the files directly and write any results or plots to files. A CIFTI file created by ciftify could be read in with ciftiTools for manipulation and interactive visualization. The NiBabel library (Brett et al., 2016) supports reading, writing, and manipulation of many neuroimaging file formats, including CIFTI files of all intents. It includes methods for parsing the CIFTI files once read in. For example, the data from a specific brain structure can be extracted as a numpy array, the data matrix structure commonly used by machine learning tools in Python. It does not include support for visualizations. The nilearn toolbox (Huntenburg et al., 2017) does not currently support CIFTI files per se, but it has functions for projecting data onto surface geometry for visualization. Users can read in CIFTI and GIFTI data with NiBabel and then use nilearn to visualize it. hcp-utils (Janik, 2020) provides high-level access to CIFTI files, including visualization, parcellation, and spatial masking. hcp-utils extends upon the functionality provided by NiBabel and nilearn, and thus requires both to be installed.

MATLAB

cifti-matlab is a software toolbox recommended by the HCP for working with CIFTI-format data within MATLAB (Oostenveld, 2021). It does not depend on the Connectome Workbench and supports reading, writing, creation, and some manipulation of CIFTI files. It is currently under development. No visualization support for CIFTI-format data is currently available natively in MATLAB to our knowledge, though GIFTI-format data can be read, written, and visualized using the GIFTI library (Flandin, 2021).

Discussion

Here we have presented and illustrated ciftiTools, an R package for reading, writing, visualizing, and manipulating CIFTI and GIFTI files. The stable version of ciftiTools is available via CRAN [1] as well as GitHub [2], where development and archived versions of the package, and a tutorial vignette, can also be found. The primary goal of ciftiTools is to provide a comprehensive, user-friendly programmatic and visualization tool supporting CIFTI- and GIFTI-based workflows. The neuroimaging community is currently in a period of active development of tools for working with grayordinates data. Today, a number of tools in MATLAB, Python, and R have been adapted to provide support for working with CIFTI files. However, ciftiTools is one of the few that has been developed specifically for CIFTI-format data. As such, the set of functionalities provided by ciftiTools for working with and visualizing CIFTI-format data is one of the most extensive and user-friendly among programmatic CIFTI-compatible tools. Moreover, the functionalities provided by ciftiTools will continue to expand as the needs of the user base evolve and become clear. A secondary goal of ciftiTools is to facilitate the use of advanced statistical methods available in R for grayordinate-based fMRI analysis. Prior to the development of ciftiTools, CIFTI files could be read into R but not written out or directly visualized. R users were required to adopt a patchwork approach to visualization of analysis results, first writing results to a generic text or CSV file, reading that data into another program such as MATLAB or Python capable of writing out CIFTI-format data, then finally visualizing the results, e.g. via the Connectome Workbench. To state the obvious, this did not represent a convenient workflow for analysis of grayordinates data in R. By simplifying CIFTI-and GIFTI-based workflows, ciftiTools bridges a gap between existing statistical methods available in R and grayordinates-based MR data for which they are well suited to analyze. Bayesian techniques in particular hold promise for extracting more accurate, specific, and individualized insights by taking advantage of the improved alignment of structural and functional features across subjects, geodesic distances, and reduced dimensionality of grayordinate-based and surface-based MR data. As the statistics and neuroimaging communities working with R continue to grow, our hope is that ciftiTools will also serve as a foundation for the development and adoption of future Bayesian techniques and other advanced statistical methods for grayordinate-based and surface-based MR data.
Table 3

Commonly used functions currently available in ciftiTools.

Reading in CIFTI or GIFTI data
read_xiftiRead in a CIFTI file as a“xifti“
read_xifti2Read in GIFTI files as a“xifti“
as.xiftiCombine numeric data to form a“xifti“
read_surfRead in a surface GIFTI file as a“surf“
info_ciftiRead the metadata in a CIFTI file
load_surfRead in a surface included in“ciftiTools“
load_parcRead in a parcellation included in“ciftiTools“
Writing CIFTI or GIFTI data
write_ciftiWrite a“xifti“ to a CIFTI file
write_cifti2Write a“xifti“ to GIFTI and NIFTI files
write_metric_giftiWrite a numeric data matrix to a metric GIFTI file
write_surf_giftiWrite a“surf“ to a surface GIFTI file
write_subcort_niftiWrite subcortical data to NIFTI files
separate_ciftiSeparate a CIFTI file into GIFTI and NIFTI files
Manipulating a“xifti“
apply_xiftiApply a function along the rows or columns of the“xifti“ data matrix
combine_xiftiCombine multiple“xifti“s with non-overlapping brain structures
convert_xiftiConvert the intent of a“xifti“
merge_xiftiConcatenate data matrices from multiple“xifti“s
newdata_xiftiReplace the data matrix in a“xifti“
remove_xiftiRemove a brain structure or surface from a“xifti“
select_xiftiSelect data matrix columns of a“xifti“
transform_xiftiApply a univariate transformation to a“xifti“ or pair of“xifti“s
add_surfAdd surfaces to a“xifti“
move_from_mwallMove medial wall vertices back into the“xifti“ data matrix
move_to_mwallMove rows with a certain value into the“xifti“ medial wall mask
S3 methods for“xifti“s
summary and printSummarize the contents
as.matrixConvert data to a locations by measurements numeric matrix
dimObtain number of locations and number of measurements
plotVisualize the cortical surface and/or subcortical data
+, -, *, /, ˆ, %%, %/%, ==, ! =Operation between a“xifti“ and a scalar, or between two“xifti“s
abs, ceiling, exp, floor, log, round, sign, sqrtUnivariate transformation of“xifti“ data
Working with“surf“s
read_surfRead in a surface GIFTI file as a“surf“
is.surfVerify a“surf“
write_surf_giftiWrite a“surf“ to a surface GIFTI file
view_surfVisualize a“surf“
resample_surfResample a“surf“
rotate_surfRotate the geometry of a“surf“
  26 in total

1.  Whole brain segmentation: automated labeling of neuroanatomical structures in the human brain.

Authors:  Bruce Fischl; David H Salat; Evelina Busa; Marilyn Albert; Megan Dieterich; Christian Haselgrove; Andre van der Kouwe; Ron Killiany; David Kennedy; Shuna Klaveness; Albert Montillo; Nikos Makris; Bruce Rosen; Anders M Dale
Journal:  Neuron       Date:  2002-01-31       Impact factor: 17.173

2.  An automated labeling system for subdividing the human cerebral cortex on MRI scans into gyral based regions of interest.

Authors:  Rahul S Desikan; Florent Ségonne; Bruce Fischl; Brian T Quinn; Bradford C Dickerson; Deborah Blacker; Randy L Buckner; Anders M Dale; R Paul Maguire; Bradley T Hyman; Marilyn S Albert; Ronald J Killiany
Journal:  Neuroimage       Date:  2006-03-10       Impact factor: 6.556

3.  Comparing surface-based and volume-based analyses of functional neuroimaging data in patients with schizophrenia.

Authors:  Alan Anticevic; Donna L Dierker; Sarah K Gillespie; Grega Repovs; John G Csernansky; David C Van Essen; Deanna M Barch
Journal:  Neuroimage       Date:  2008-03-07       Impact factor: 6.556

4.  PCA leverage: outlier detection for high-dimensional functional magnetic resonance imaging data.

Authors:  Amanda F Mejia; Mary Beth Nebel; Ani Eloyan; Brian Caffo; Martin A Lindquist
Journal:  Biostatistics       Date:  2017-07-01       Impact factor: 5.899

5.  A Bayesian General Linear Modeling Approach to Cortical Surface fMRI Data Analysis.

Authors:  Amanda F Mejia; Yu Ryan Yue; David Bolin; Finn Lindgren; Martin A Lindquist
Journal:  J Am Stat Assoc       Date:  2019-06-12       Impact factor: 5.033

6.  The impact of traditional neuroimaging methods on the spatial localization of cortical areas.

Authors:  Timothy S Coalson; David C Van Essen; Matthew F Glasser
Journal:  Proc Natl Acad Sci U S A       Date:  2018-06-20       Impact factor: 11.205

7.  Ciftify: A framework for surface-based analysis of legacy MR acquisitions.

Authors:  Erin W Dickie; Alan Anticevic; Dawn E Smith; Timothy S Coalson; Mathuvanthi Manogaran; Navona Calarco; Joseph D Viviano; Matthew F Glasser; David C Van Essen; Aristotle N Voineskos
Journal:  Neuroimage       Date:  2019-05-12       Impact factor: 6.556

8.  Local-Global Parcellation of the Human Cerebral Cortex from Intrinsic Functional Connectivity MRI.

Authors:  Alexander Schaefer; Ru Kong; Evan M Gordon; Timothy O Laumann; Xi-Nian Zuo; Avram J Holmes; Simon B Eickhoff; B T Thomas Yeo
Journal:  Cereb Cortex       Date:  2018-09-01       Impact factor: 5.357

9.  Automatic denoising of functional MRI data: combining independent component analysis and hierarchical fusion of classifiers.

Authors:  Gholamreza Salimi-Khorshidi; Gwenaëlle Douaud; Christian F Beckmann; Matthew F Glasser; Ludovica Griffanti; Stephen M Smith
Journal:  Neuroimage       Date:  2014-01-02       Impact factor: 6.556

View more

北京卡尤迪生物科技股份有限公司 © 2022-2023.