freesurferformats

GNU R package to read and write structural neuroimaging file formats. Comes with support for file formats used by FreeSurfer, CAT12/SPM, FSL, BrainVoyager, MRtrix3, Diffusion Toolkit/TrackVis and other neuroimaging software packages.

Vis

Supported formats | Installation | Documentation | License | Citation | Development

A note to end users

This low-level package provides well-tested file format readers and writers for FreeSurfer neuroimaging data. Typically, you want to access not only individual files, but datasets of subjects stored in the standardized output structure of recon-all (your $SUBJECTS_DIR) when doing neuroimaging research. In that case, I recommend to use the high-level functions from the fsbrain package instead of re-inventing the wheel. The fsbrain package is built on top of freesurferformats and provides functions for working with the data of your study, including visualization of results on brain meshes.

Supported formats

You do not need to have FreeSurfer installed to use this package. It implements its own readers and writers for the following file formats:

We also provide wrappers and adapter functions for existing neuroimaging file format packages, which load the data into freesurferformats data structures:

News

You can also find all releases in the releases section.

Installation

The package is on CRAN, so you can simply:

install.packages("freesurferformats")

If you want support for as many neuroimaging file formats as possible, do this instead to install with all optional dependencies:

install.packages("freesurferformats", dependencies=TRUE);

In case something goes wrong, don't worry. Just install the missing system dependencies and retry.

System dependencies

Note: You can ignore this section unless you want to build the freesurferformats package from the source code.

A system dependency is a non-R software that is needed for the installation of a package. System dependencies cannot be installed automatically using the R package system, so you need to install them manually or using the package manager of your operating system.

If you install R packages from source (the default under Linux) and want support for the GIFTI XML file format, you will need libxml2-dev. If you do not have it installed already, before installing freesurferformats, run the following command in your system shell (not in R):

sudo apt-get install libxml2-dev libcurl4-openssl-dev
sudo yum install libxml2-devel libcurl-devel

Documentation

Quick Usage

Before using any functions, of course load the package itself:

library("freesurferformats")

Now you can call the following functions:

read.fs.mgh()         # read volume or morphometry data from files in MGH or MGZ format, e.g., `mri/brain.mgz` or `surf/lh.area.fwhm10.fsaverage.mgh`.
read.fs.volume.nrrd() # read a volume in NRRD format (`.nrrd`/`.nhdr`), e.g. one written by 3D Slicer.
read.fs.volume.analyze() # read a volume in ANALYZE 7.5 or two-file NIFTI v1 format (`.hdr`/`.img`), e.g. FSL output.
read.fs.curv()        # read morphometry data from 'curv' format files like `surf/lh.area`
read.fs.morph()       # read any morphometry file (mgh/mgz/curv). The format is derived from the file extension.
read.fs.annot()       # read annotation data or brain atlas labels from files like `label/lh.aparc.annot`
read.fs.surface()     # read a surface mesh, like `surf/lh.white`, supports many standard mesh formats
read.fs.label()       # read a label file, like `label/lh.cortex.label`
read.fs.colortable()  # read a color lookup table (LUT), like `$FREESURFER_HOME/FreeSurferColorLUT.txt`
read.fs.weight()      # read scalar data for a subset of vertices, defined by index. Known as `weight`, `paint` or simply `w` format.
read.fs.patch()       # read a surface patch, which is a part of a surface.
read.fs.transform()   # read spatial transformation matrix
read.dti.tck()        # read DTI tracks from MRtrix3 'TCK' format
read.dti.trk()        # read DTI tracks from Diffusion Toolkit/TrakVis 'TRK' format
read.dti.tsf()        # read DTI per-point track scalar data from MRtrix3 'TSF' format
read.dti.gradients()  # read and validate a diffusion gradient table (FSL '.bvec'/'.bval' pair or MRtrix format)
read.fs.tracts.vtk()  # read streamlines from a VTK polydata file, as written by Paraview, TrackVis or DSI Studio
read.fs.parcellation.cifti() # read a cortical parcellation from a CIFTI dlabel file
read.cifti()          # read the data matrix and the metadata of a CIFTI-2 file
read.cifti.rows()     # read selected rows of a large CIFTI-2 file without loading it
read.cifti.header()   # read only the XML metadata of a CIFTI-2 file
cifti.structure.data() # extract the data of one brain structure (surface or volume) from a CIFTI-2 file
write.cifti()         # write a CIFTI-2 file (any of the nine standard file types)
write.fs.morph.cifti() # write morphometry data to a CIFTI dscalar file
write.fs.series.cifti() # write time series data to a CIFTI dtseries file
write.fs.parcellation.cifti() # write a parcellation to a CIFTI dlabel file
read.fs.connectome.cifti() # read a CIFTI connectome (dconn, pconn, pdconn, dpconn)
write.fs.connectome.cifti() # write a CIFTI connectome (dconn, pconn, pdconn, dpconn)
write.fs.parcellated.cifti() # write a parcellated CIFTI file (pscalar, ptseries)
cifti.axis.parcels.from.annot() # build the parcels of a parcellated CIFTI file from an atlas

write.fs.mgh()        # write data with 1 to 4 dimensions to an MGH format file
write.fs.curv()       # write a data vector to a 'curv' format file
write.fs.morph()      # write any morphometry file (mgh/mgz/curv). The format is derived from the file extension.
write.fs.surface()    # write a surface mesh
write.fs.label()      # write a label file
write.fs.annot()      # write an annotation file
write.fs.colortable() # write a color lookup table (LUT)
write.fs.weight()     # write scalar vertex data in weight or w format
write.fs.patch()      # write a surface patch, which is a part of a surface.
write.fs.transform()  # write a spatial transformation matrix (LTA, register.dat, xfm, FSL or ITK format)
write.dti.tck()       # write DTI tracks to MRtrix3 'TCK' format
write.dti.trk()       # write DTI tracks to Diffusion Toolkit/TrackVis 'TRK' format
write.dti.tsf()       # write DTI per-point track scalar data to MRtrix3 'TSF' format
write.dti.bvec()      # write b-vectors in the FSL '.bvec' format (see also write.dti.bval(), write.dti.grad())
write.atlas.to.lut.and.csv() # write a brain atlas to a colortable (LUT) and a per-vertex label file

The documentation is included in the package and not repeated on this website.

Full Documentation

The documentation can be accessed from within an R session after you have loaded the freesurferformats package:

An example R session: Reading Bert's brain

One of the example subjects that comes with FreeSurfer is bert. The following example shows how to load Bert's brain. If you have FreeSurfer installed, you can start GNU R by typing R in your favourite terminal application and run the following commands:

install.packages("freesurferformats")

# Load volume from file
library("freesurferformats")
berts_brain = paste(Sys.getenv("FREESURFER_HOME"), "/subjects/bert/mri/brain.mgz", sep="")
mgh = read.fs.mgh(berts_brain, with_header=TRUE);

# Compute the vox2ras matrix from the header:
mghheader.vox2ras(mgh)
#     [,1] [,2] [,3]      [,4]
#[1,]   -1    0    0  133.3997
#[2,]    0    0    1 -110.0000
#[3,]    0   -1    0  128.0000
#[4,]    0    0    0    1.0000

# ...and the data:
mean(mgh$data)
#[1] 8.214322
dim(drop(mgh$data))
# [1] 256 256 256

If you do not have FreeSurfer installed and thus don't have Bert, replace berts_brain with the example brain that comes with freesurferformats:

fsf_brain = system.file("extdata", "brain.mgz", package = "freesurferformats", mustWork = TRUE);

Security configuration

The freesurferformats package includes protection against malformed or malicious input files, including a maximum allocation limit that defaults to 2 GB of memory per file. This should be plenty for standard neuroimaging applications, and you should typically not need to worry about this. However, if you are working with exceptionally large files, or in environments where you allow users to upload files you work with and expect very small files, it is definitely worth it to adapt the limits. Here is how to do that:

# Directly in an R session or script, via R options (recommended for interactive use):
options(freesurferformats.max_alloc_bytes = 1e9)   # 1 GB
options(freesurferformats.max_alloc_bytes = Inf)    # disable (use with care)
# Via environment variable (recommended for CI/containers):
Sys.setenv(FREESURFERFORMATS_MAX_ALLOC_BYTES = 5e8) # 500 MB

License and Author

Written by Tim Schäfer.

The freesurferformats package is free software, published under the MIT license.

Note: The file LICENSE in this repository is a CRAN license template only (as required by CRAN) and does not contain the full MIT license text. See the file LICENSE_FULL for the full license text.

Citation

A paper is in the making. For now, please cite the R package. You can generate the citation for the version you use by typing the following command in R:

citation("freesurferformats")

This will ouput something like this (but for the version you actually used, which is important for reproducibility):

To cite package ‘freesurferformats’ in publications use:

  Tim Schäfer (2020). freesurferformats: Read and Write 'FreeSurfer'
  Neuroimaging File Formats. R package version 0.1.9.
  https://CRAN.R-project.org/package=freesurferformats

A BibTeX entry for LaTeX users is

  @Manual{,
    title = {freesurferformats: Read and Write 'FreeSurfer' Neuroimaging File Formats},
    author = {Tim Schäfer},
    year = {2020},
    note = {R package version 0.1.9,
    url = {https://CRAN.R-project.org/package=freesurferformats},
    doi = {10.5281/zenodo.3540434},
    url = {https://dx.doi.org/10.5281/zenodo.3540434},
  }

The Digital Object Identifier (DOI) for freesurferformats is: 10.5281/zenodo.3540434. Note that this DOI always points to the latest version, so be sure to still include the package version in the citation.

A poster of freesurferformats has been presented at INSAR 2020 Annual Meeting: Abstract, ePoster

Developer Information

Please refer to README_DEVELOPMENT.md.