Title: | Read, Manipulate and Visualise Magnetic Resonance Images |
---|---|
Description: | Functions for working with magnetic resonance images. Reading and writing of popular file formats (DICOM, Analyze, NIfTI-1, NIfTI-2, MGH); interactive and non-interactive visualisation; flexible image manipulation; metadata and sparse image handling. |
Authors: | Jon Clayden |
Maintainer: | Jon Clayden <[email protected]> |
License: | GPL-2 |
Version: | 3.4.2 |
Built: | 2024-09-13 06:10:34 UTC |
Source: | https://github.com/tractor/tractor |
Indexing methods for SparseArray
and MriImage
objects. For the latter class, arguments are passed to the equivalents for
array
or SparseArray
, except where i
is another
MriImage
object, where its nonzero region will be used to
provide the indices. For SparseArray
, indexing may be blank,
or by numeric vector or matrix.
## S4 method for signature 'SparseArray,ANY,ANY' x[i, j, ..., drop = TRUE] ## S4 replacement method for signature 'SparseArray,ANY,ANY' x[i, j, ...] <- value ## S4 method for signature 'MriImage,missing,missing' x[i, j, ..., drop = TRUE] ## S4 method for signature 'MriImage,ANY,missing' x[i, j, ..., drop = TRUE] ## S4 method for signature 'MriImage,missing,ANY' x[i, j, ..., drop = TRUE] ## S4 method for signature 'MriImage,ANY,ANY' x[i, j, ..., drop = TRUE] ## S4 method for signature 'MriImage,MriImage,missing' x[i, j, ..., drop = TRUE] ## S4 replacement method for signature 'MriImage,missing,missing' x[i, j, ...] <- value ## S4 replacement method for signature 'MriImage,ANY,missing' x[i, j, ...] <- value ## S4 replacement method for signature 'MriImage,missing,ANY' x[i, j, ...] <- value ## S4 replacement method for signature 'MriImage,ANY,ANY' x[i, j, ...] <- value ## S4 replacement method for signature 'MriImage,MriImage,missing' x[i, j, ...] <- value
## S4 method for signature 'SparseArray,ANY,ANY' x[i, j, ..., drop = TRUE] ## S4 replacement method for signature 'SparseArray,ANY,ANY' x[i, j, ...] <- value ## S4 method for signature 'MriImage,missing,missing' x[i, j, ..., drop = TRUE] ## S4 method for signature 'MriImage,ANY,missing' x[i, j, ..., drop = TRUE] ## S4 method for signature 'MriImage,missing,ANY' x[i, j, ..., drop = TRUE] ## S4 method for signature 'MriImage,ANY,ANY' x[i, j, ..., drop = TRUE] ## S4 method for signature 'MriImage,MriImage,missing' x[i, j, ..., drop = TRUE] ## S4 replacement method for signature 'MriImage,missing,missing' x[i, j, ...] <- value ## S4 replacement method for signature 'MriImage,ANY,missing' x[i, j, ...] <- value ## S4 replacement method for signature 'MriImage,missing,ANY' x[i, j, ...] <- value ## S4 replacement method for signature 'MriImage,ANY,ANY' x[i, j, ...] <- value ## S4 replacement method for signature 'MriImage,MriImage,missing' x[i, j, ...] <- value
x |
An object of the appropriate type. |
i , j , ...
|
Indexing objects. |
drop |
Scalar value: should unitary dimensions be dropped? |
value |
New value(s) for replacement forms. |
A vector, array or SparseArray
.
Jon Clayden
This function tests whether all elements of the specified vector are equal
to each other, i.e., whether the vector contains only a single unique value.
For lists, equality is determined using equivalent
.
allEqual(x, ignoreMissing = FALSE, ...)
allEqual(x, ignoreMissing = FALSE, ...)
x |
A vector of any mode, including a list. |
ignoreMissing |
If |
... |
Additional arguments to |
TRUE
if all elements test equivalent; FALSE
otherwise.
Jon Clayden
Please cite the following reference when using TractoR in your work:
J.D. Clayden, S. Muñoz Maniega, A.J. Storkey, M.D. King, M.E. Bastin & C.A. Clark (2011). TractoR: Magnetic resonance imaging and tractography with R. Journal of Statistical Software 44(8):1-18. doi:10.18637/jss.v044.i08.
equivalent
for elementwise equivalence of two
vectors.
allEqual(c(1,1,1)) # TRUE allEqual(c(1,1,NA)) # FALSE allEqual(c(1,1,NA), ignoreMissing=TRUE) # TRUE
allEqual(c(1,1,1)) # TRUE allEqual(c(1,1,NA)) # FALSE allEqual(c(1,1,NA), ignoreMissing=TRUE) # TRUE
Functions for creating MriImage objects from data, including other images.
All of these functions use data from arrays or MriImage
objects to
create a new MriImage
object. asMriImage
is the basic fucntion
for creating an object from its constituents: an array of voxel values and
some metadata (and/or a template image).
asMriImage(data, templateImage = nilObject(), imageDims = NA, voxelDims = NA, voxelDimUnits = NA, origin = NA, tags = NA, reordered = NA) extractMriImage(image, dim, loc) trimMriImage(image, clearance = 4, indices = NULL) reorderMriImage(image)
asMriImage(data, templateImage = nilObject(), imageDims = NA, voxelDims = NA, voxelDimUnits = NA, origin = NA, tags = NA, reordered = NA) extractMriImage(image, dim, loc) trimMriImage(image, clearance = 4, indices = NULL) reorderMriImage(image)
data |
An array of pixel/voxel data. |
templateImage |
An optional |
imageDims , voxelDims , voxelDimUnits , origin , tags , reordered
|
Metadata for
the new image object. These values override any from the metadata object
or data array. See |
image |
An |
dim , loc
|
The dimension and location along that dimension for which data should be extracted. |
clearance |
The number of voxels' clearance left around a trimmed image. |
indices |
A list of indices to keep along each dimension. Determined
from the specified |
extractMriImage
reduces the dimensionality of the source image by
one, by extracting a single “slice” of data along one dimension.
trimMriImage
trims empty space from the edges of an image, reducing
the dimensions of the image and thus avoiding the storage of lots of zeroes.
reorderMriImage
reorders the image data (and corresponding metadata)
to the LAS convention, an operation which is usually performed when an
image is read from file.
An MriImage
object.
Jon Clayden
Please cite the following reference when using TractoR in your work:
J.D. Clayden, S. Muñoz Maniega, A.J. Storkey, M.D. King, M.E. Bastin & C.A. Clark (2011). TractoR: Magnetic resonance imaging and tractography with R. Journal of Statistical Software 44(8):1-18. doi:10.18637/jss.v044.i08.
The viewImages
function provides a simple interactive viewer for
MriImage
objects. 3D and 4D images may be used.
augmentedInfoPanel(indexNames = NULL) polarPlotPanel(directions, bValues = NULL) viewImages(images, colourScales = NULL, point = NULL, interactive = TRUE, crosshairs = TRUE, orientationLabels = TRUE, infoPanel = RNifti::defaultInfoPanel, ...)
augmentedInfoPanel(indexNames = NULL) polarPlotPanel(directions, bValues = NULL) viewImages(images, colourScales = NULL, point = NULL, interactive = TRUE, crosshairs = TRUE, orientationLabels = TRUE, infoPanel = RNifti::defaultInfoPanel, ...)
indexNames |
A list whose elements are either |
directions |
A matrix of 3D acquisition direction vectors, one per row. |
bValues |
A vector of b-values, if the image is diffusion-weighted. |
images |
An |
colourScales |
A list of colour scales to use for each image, which
will be recycled to the length of |
point |
A length-3 integer vector giving the initial location of the crosshairs, in voxels. |
interactive |
A single logical value. If |
crosshairs |
A single logical value. If |
orientationLabels |
A single logical value. If |
infoPanel |
A function with at least three arguments, which must plot
something to fill the bottom-right panel of the viewer after each change
of crosshair location. The three mandatory arguments correspond to the
current location in the image, the image values at that location, and the
names of each image. The |
... |
Additional arguments to |
These functions are called for their side effects.
The defaultInfoPanel
and timeSeriesPanel
functions are
not intended to be called directly. They are simple examples of valid
values for the infoPanel
argument to viewImages
.
Jon Clayden
Please cite the following reference when using TractoR in your work:
J.D. Clayden, S. Muñoz Maniega, A.J. Storkey, M.D. King, M.E. Bastin & C.A. Clark (2011). TractoR: Magnetic resonance imaging and tractography with R. Journal of Statistical Software 44(8):1-18. doi:10.18637/jss.v044.i08.
This function calculates information about a cuboidal region of an image, with a centre and a fixed voxel width.
createNeighbourhoodInfo(width, dim = 3, centre = rep(0, dim))
createNeighbourhoodInfo(width, dim = 3, centre = rep(0, dim))
width |
An integer voxel width. Must be odd. |
dim |
An integer giving the dimensionality of the neighbourhood. Currently must be 3. |
centre |
A numeric vector giving the centre voxel of the neighbourhood.
Must have exactly |
createNeighbourhoodInfo
returns a list with class
"neighbourhoodInfo"
and elements
Copied from the width
argument.
Copied from the dim
argument.
Copied from the centre
argument.
dim
x width^dim
matrix whose columns give
the locations of each point in the neighbourhood.
A square, symmetric matrix of inner products between every location in the neighbourhood and every other.
Jon Clayden
Please cite the following reference when using TractoR in your work:
J.D. Clayden, S. Muñoz Maniega, A.J. Storkey, M.D. King, M.E. Bastin & C.A. Clark (2011). TractoR: Magnetic resonance imaging and tractography with R. Journal of Statistical Software 44(8):1-18. doi:10.18637/jss.v044.i08.
Visualise MriImage
objects noninteractively using an R graphics
device. See viewImages
for an interactive alternative. These
functions create 2D visualisations of 3D images by slicing or maximum
intensity projection.
createSliceGraphic(image, x = NA, y = NA, z = NA, device = c("internal", "png"), colourScale = 1, add = FALSE, file = NULL, zoomFactor = 1, windowLimits = NULL) createProjectionGraphic(image, axis, device = c("internal", "png"), colourScale = 1, add = FALSE, file = NULL, zoomFactor = 1, windowLimits = NULL) createContactSheetGraphic(image, axis, device = c("internal", "png"), colourScale = 1, add = FALSE, file = NULL, zoomFactor = 1, windowLimits = NULL, clearance = NULL, nColumns = NULL)
createSliceGraphic(image, x = NA, y = NA, z = NA, device = c("internal", "png"), colourScale = 1, add = FALSE, file = NULL, zoomFactor = 1, windowLimits = NULL) createProjectionGraphic(image, axis, device = c("internal", "png"), colourScale = 1, add = FALSE, file = NULL, zoomFactor = 1, windowLimits = NULL) createContactSheetGraphic(image, axis, device = c("internal", "png"), colourScale = 1, add = FALSE, file = NULL, zoomFactor = 1, windowLimits = NULL, clearance = NULL, nColumns = NULL)
image |
An |
x , y , z
|
Integer vectors, each of length 1. Exactly one of these must be specified to indicate the plane of interest. |
device |
Either |
colourScale |
A colour scale definition, of the sort generated by
|
add |
Overlay the graphic on a previous one. Used only when
|
file |
A file name, to be used when |
zoomFactor |
Factor by which to enlarge the image. Applies only when
|
windowLimits |
Numeric vector of length 2 giving the limits of the
colour scale, or |
axis |
A vector of axes along which slice/projection images should be created. 1 is left-right, 2 is anterior-posterior, 3 is superior-inferior. |
clearance |
Number of voxels' clearance to leave around each slice
image in the contact sheet. Passed to |
nColumns |
Number of slices per row in the contact sheet grid. If
|
These functions are called for their side effects.
When the device
option is set to "png"
, the "png"
and "mmand"
packages are required by these functions.
Jon Clayden
Please cite the following reference when using TractoR in your work:
J.D. Clayden, S. Muñoz Maniega, A.J. Storkey, M.D. King, M.E. Bastin & C.A. Clark (2011). TractoR: Magnetic resonance imaging and tractography with R. Journal of Statistical Software 44(8):1-18. doi:10.18637/jss.v044.i08.
See viewImages
for an interactive alternative, and
getColourScale
for details of how colour scales are specified.
Also image
, which is used as the underlying plot function.
This function returns its arguments, after concatenating them using c
and then removing elements with duplicate names. The first element with each
name will remain, possibly with subsequent elements' content appended to it.
Unnamed elements are retained.
deduplicate(..., merge = FALSE)
deduplicate(..., merge = FALSE)
... |
One or more vectors of any mode, usually named. |
merge |
If |
The concatenated and deduplicated vector.
Jon Clayden
Please cite the following reference when using TractoR in your work:
J.D. Clayden, S. Muñoz Maniega, A.J. Storkey, M.D. King, M.E. Bastin & C.A. Clark (2011). TractoR: Magnetic resonance imaging and tractography with R. Journal of Statistical Software 44(8):1-18. doi:10.18637/jss.v044.i08.
This class represents DICOM metadata, which typically contains detailed information about the scan parameters and subject.
source
String naming the source file
tags
Data frame of tag information
tagOffset
Starting offset for tags in the file
dataOffset
Starting offset for pixel data in the file
dataLength
Pixel data length
explicitTypes
Logical value indicating whether explicit types are used in the file
endian
String naming the endianness of the file
asciiFields
Character vector containing the contents of the ASCII header, if requested and present in the file.
transferSyntax
Transfer syntax string, if specified in the file; otherwise the empty string.
getAsciiFields(regex = NULL)
Retrieve the value of one or more fields in the ASCII header. Returns NA if no fields match
getTagValue(group, element)
Retrieve the value of a given tag, using an appropriate R type. Returns NA if the tag is missing
Merge a vector of strings with a common prefix and/or suffix into one string with the unique parts in braces, comma-separated.
embrace(strings)
embrace(strings)
strings |
A vector, which will be coerced to mode |
A single merged string, with the common prefix and suffix as attributes.
Jon Clayden
Please cite the following reference when using TractoR in your work:
J.D. Clayden, S. Muñoz Maniega, A.J. Storkey, M.D. King, M.E. Bastin & C.A. Clark (2011). TractoR: Magnetic resonance imaging and tractography with R. Journal of Statistical Software 44(8):1-18. doi:10.18637/jss.v044.i08.
embrace(c("image.hdr", "image.img"))
embrace(c("image.hdr", "image.img"))
The empty matrix is a standard matrix of dimensions 0 x 0. It is intended to be used as a placeholder where a matrix is required but no information is stored.
emptyMatrix() is.emptyMatrix(object)
emptyMatrix() is.emptyMatrix(object)
object |
Any object. |
emptyMatrix
returns the empty matrix, equivalent to
matrix(NA,0,0)
. is.emptyMatrix
returns TRUE
if its
argument is identical to the empty matrix.
Jon Clayden
Please cite the following reference when using TractoR in your work:
J.D. Clayden, S. Muñoz Maniega, A.J. Storkey, M.D. King, M.E. Bastin & C.A. Clark (2011). TractoR: Magnetic resonance imaging and tractography with R. Journal of Statistical Software 44(8):1-18. doi:10.18637/jss.v044.i08.
This function is a wrapper for isTRUE(all.equal(x,y,...{}))
, but
with the additional capability of doing sign-insensitive comparison.
equivalent(x, y, signMatters = TRUE, ...)
equivalent(x, y, signMatters = TRUE, ...)
x |
The first numeric vector. |
y |
The second numeric vector. |
signMatters |
Logical value: if FALSE then equivalence in absolute value is sufficient. |
... |
Additional arguments to |
TRUE
if all elements of x
match all elements of
y
to within tolerance, ignoring signs if required. FALSE
otherwise.
Jon Clayden
Please cite the following reference when using TractoR in your work:
J.D. Clayden, S. Muñoz Maniega, A.J. Storkey, M.D. King, M.E. Bastin & C.A. Clark (2011). TractoR: Magnetic resonance imaging and tractography with R. Journal of Statistical Software 44(8):1-18. doi:10.18637/jss.v044.i08.
equivalent(c(-1,1), c(1,1)) # FALSE equivalent(c(-1,1), c(1,1), signMatters=FALSE) # TRUE equivalent(1:2, 2:3, tolerance=2) # TRUE
equivalent(c(-1,1), c(1,1)) # FALSE equivalent(c(-1,1), c(1,1), signMatters=FALSE) # TRUE equivalent(1:2, 2:3, tolerance=2) # TRUE
These functions provide a shorthand route to simple anonymous functions.
fx(expr) fxy(expr) fxyz(expr) fi(expr)
fx(expr) fxy(expr) fxyz(expr) fi(expr)
expr |
A (single or compound) expression forming the body of the function. |
The function constructed.
Jon Clayden
Please cite the following reference when using TractoR in your work:
J.D. Clayden, S. Muñoz Maniega, A.J. Storkey, M.D. King, M.E. Bastin & C.A. Clark (2011). TractoR: Magnetic resonance imaging and tractography with R. Journal of Statistical Software 44(8):1-18. doi:10.18637/jss.v044.i08.
The getColourScale
function can be used to obtain a standard or
customised colour scale for use in the package's image visualisation
functions.
getColourScale(n)
getColourScale(n)
n |
A number, colour name or list (see Details). |
Colour scales can be specified in any of three ways. Firstly, by a single
number, representing a predefined colour scale. Currently valid values are 1
(greyscale, black background), 2 (red to yellow heat scale, red background),
3 (blue to red rainbow scale, blue background), 4 (blue to white to red
diverging scale, white background), 5 (white to red, white background), 6
(white to blue, white background), 7 (yellow to orange to red) and 8 (purple
to green to yellow, perceptually uniform). Secondly, a single colour name
can be given (see colours
); in this case the background will
be black. This is useful for binary images. Thirdly, and most flexibly, a
list with two named elements can be given: colours
, a vector of
colours representing the colour scale, perhaps created using using the
shades
package; and background
, a single colour representing
the background.
A list with elements
A character-mode vector representing the colours in the scale, usually of length 100. This can be passed as a colour scale to R's plotting functions.
A single character string representing the background colour.
Jon Clayden
Please cite the following reference when using TractoR in your work:
J.D. Clayden, S. Muñoz Maniega, A.J. Storkey, M.D. King, M.E. Bastin & C.A. Clark (2011). TractoR: Magnetic resonance imaging and tractography with R. Journal of Statistical Software 44(8):1-18. doi:10.18637/jss.v044.i08.
colours
, rgb
, colorRamp
,
and the shades
package for colour manipulation.
getColourScale(1)
getColourScale(1)
Functions for reading, writing, locating, copying and removing MRI images stored in NIfTI, Analyze, MGH and MRtrix formats.
identifyImageFileNames(fileName, fileType = NULL, errorIfMissing = TRUE, auxiliaries = c("dirs", "lut", "tags"), ...) imageFileExists(fileName, fileType = NULL) removeImageFiles(fileName, ...) symlinkImageFiles(from, to, overwrite = FALSE, relative = TRUE, ...) copyImageFiles(from, to, overwrite = FALSE, deleteOriginals = FALSE, ...) readImageFile(fileName, fileType = NULL, metadataOnly = FALSE, volumes = NULL, sparse = FALSE, mask = NULL, reorder = TRUE, ...) writeImageFile(image, fileName = NULL, fileType = NA, overwrite = TRUE, datatype = "fit", writeTags = FALSE)
identifyImageFileNames(fileName, fileType = NULL, errorIfMissing = TRUE, auxiliaries = c("dirs", "lut", "tags"), ...) imageFileExists(fileName, fileType = NULL) removeImageFiles(fileName, ...) symlinkImageFiles(from, to, overwrite = FALSE, relative = TRUE, ...) copyImageFiles(from, to, overwrite = FALSE, deleteOriginals = FALSE, ...) readImageFile(fileName, fileType = NULL, metadataOnly = FALSE, volumes = NULL, sparse = FALSE, mask = NULL, reorder = TRUE, ...) writeImageFile(image, fileName = NULL, fileType = NA, overwrite = TRUE, datatype = "fit", writeTags = FALSE)
fileName , from , to
|
File names, with or without appropriate extension. |
fileType |
A character vector of length one, giving the file type
required or expected. If this option is missing, the file type used for
writing images will be taken from the |
errorIfMissing |
Logical value: raise an error if no suitable files were found? |
auxiliaries |
A character vector of auxiliary file suffixes to search for. |
... |
For |
overwrite |
Logical value: overwrite an existing image file? For
|
relative |
Logical value: if |
deleteOriginals |
Logical value: if |
metadataOnly |
Logical value: if |
volumes |
An optional integer vector specifying a subset of volumes to read (generally to save memory). If given, only the requested volumes in the 4D file will be read. |
sparse |
Logical value: should the image data be stored in a
|
mask |
An optional |
reorder |
Logical value: should the image data be reordered to LAS? This is recommended in most circumstances. |
image |
An |
datatype |
A datatype string, such as |
writeTags |
Logical value: should tags be written in YAML format to an auxiliary file? |
NIfTI and Analyze are related formats for storing magnetic resonance images. NIfTI is a more recent extension of Analyze, and contains more specific information about, for example, the orientation of the image. Its use is therefore recommended where possible. MGH format is used by the popular image processing package FreeSurfer, and MRtrix format by the software of the same name. These formats use a number of different file extensions, but the details are abstracted away from the user by these functions.
TractoR does not allow for files with the same basic name using multiple
Analyze/NIfTI/MGH/MRtrix formats in a single directory (e.g.
"foo.nii"
AND "foo.img"
), and these functions will produce an
error if multiple compatible files exist.
Suitable values for fileType
(and the tractorFileType
option,
which is used as a default for writing) are "NIFTI"
,
"NIFTI_PAIR"
(the two-file NIfTI format), "MGH"
, and
corresponding gzipped versions of these with "_GZ"
appended. File
types "ANALYZE"
and "MRTRIX"
, and "_GZ"
variants, are
additionally available for reading only. "NIFTI_GZ"
is the default
value for the tractorFileType
option, but that can be changed using a
call to options
, or by setting the TRACTOR_FILETYPE
environment variable before loading the tractor.base
package.
Since multiple files may be involved, copying, moving or symlinking images
is not trivial. copyImageFiles
and symlinkImageFiles
are
wrappers around the standard functions file.copy
and
file.symlink
which handle this complexity.
readImageFile
returns an MriImage
object. imageFileExists
returns TRUE
if an existing file
with the specified name exists (all file extensions are checked), and
FALSE
otherwise. removeImageFiles
returns the result of
unlink
applied to all relevant files. writeImageFile
and identifyImageFileNames
return a list with the following elements,
describing the identified or written files:
The file name without extension.
The full header file name.
The full image file name.
The format of the files ("Nifti"
, "Analyze"
or "Mgh"
). Not returned by writeImageFile
.
copyImageFiles
and symlinkImageFiles
are called for their
side effects.
Jon Clayden
Please cite the following reference when using TractoR in your work:
J.D. Clayden, S. Muñoz Maniega, A.J. Storkey, M.D. King, M.E. Bastin & C.A. Clark (2011). TractoR: Magnetic resonance imaging and tractography with R. Journal of Statistical Software 44(8):1-18. doi:10.18637/jss.v044.i08.
The NIfTI-1 standard (http://nifti.nimh.nih.gov/nifti-1) and
MriImage
.
Create a character string by concatenating the elements of a vector, using a separator and optional final separator.
implode(strings, sep = "", finalSep = NULL, ranges = FALSE)
implode(strings, sep = "", finalSep = NULL, ranges = FALSE)
strings |
A vector, which will be coerced to mode |
sep |
A unit length character vector giving the separator to insert between elements. |
finalSep |
An optional unit length character vector giving the separator to insert between the final two elements. |
ranges |
Logical value. If |
A character vector of length one.
Jon Clayden
Please cite the following reference when using TractoR in your work:
J.D. Clayden, S. Muñoz Maniega, A.J. Storkey, M.D. King, M.E. Bastin & C.A. Clark (2011). TractoR: Magnetic resonance imaging and tractography with R. Journal of Statistical Software 44(8):1-18. doi:10.18637/jss.v044.i08.
implode(1:3, ", ") # "1, 2, 3" implode(1:3, ", ", " and ") # "1, 2 and 3" implode(1:2, ", ", " and ") # "1 and 2" implode(1:3, ", ", ranges=TRUE) # "1-3"
implode(1:3, ", ") # "1, 2, 3" implode(1:3, ", ", " and ") # "1, 2 and 3" implode(1:2, ", ", " and ") # "1 and 2" implode(1:3, ", ", ranges=TRUE) # "1-3"
Given a list-like first argument, this function extracts one or more of its elements. Numeric and character indexing are allowed.
indexList(list, index = NULL)
indexList(list, index = NULL)
list |
A list-like object, with a |
index |
A vector of integers or strings, or |
If index
is NULL
, the whole list is returned.
Otherwise, if index
has length one, the corresponding element is
extracted and returned. Otherwise a list containing the requested subset
is returned.
This function is not type-safe, in the sense that its return type depends on its arguments. It should therefore be used with care.
Jon Clayden
Please cite the following reference when using TractoR in your work:
J.D. Clayden, S. Muñoz Maniega, A.J. Storkey, M.D. King, M.E. Bastin & C.A. Clark (2011). TractoR: Magnetic resonance imaging and tractography with R. Journal of Statistical Software 44(8):1-18. doi:10.18637/jss.v044.i08.
This is a very simple infix function for the common TractoR idiom whereby
NULL
is used as a default argument value, but later needs to be
resolved to a meaningful value if not overridden in the call. It returns its
first argument unless it is NULL
, in which case it falls back on the
second argument.
X %||% Y
X %||% Y
X , Y
|
R objects, possibly |
X
, if it is not NULL
; otherwise Y
.
Jon Clayden
Please cite the following reference when using TractoR in your work:
J.D. Clayden, S. Muñoz Maniega, A.J. Storkey, M.D. King, M.E. Bastin & C.A. Clark (2011). TractoR: Magnetic resonance imaging and tractography with R. Journal of Statistical Software 44(8):1-18. doi:10.18637/jss.v044.i08.
where
, which resolves a value if an expression is
TRUE
. Several calls to that function can be conveniently chained
together with this one.
Rather than using R's save
and load
functions
directly for reference objects, TractoR uses the
SerialisableObject
class and these functions to save
and load objects. The main difference is that this approach stores only the
data in the object, and not the functions which operate on them. This helps
backward compatibility when new member functions are added.
isDeserialisable(object, expectedClass = NULL) serialiseReferenceObject(object, file = NULL) deserialiseReferenceObject(file = NULL, object = NULL, raw = FALSE) registerDeserialiser(className, deserialiser)
isDeserialisable(object, expectedClass = NULL) serialiseReferenceObject(object, file = NULL) deserialiseReferenceObject(file = NULL, object = NULL, raw = FALSE) registerDeserialiser(className, deserialiser)
object |
For |
expectedClass |
A class name which the object is expected to inherit.
Any class is acceptable if this parameter is |
file |
A file name to deserialise from. |
raw |
If |
className |
A string naming a class to be handled by the specified deserialiser. |
deserialiser |
A function taking as its argument a list of serialised fields, and returning a suitable deserialised object. |
The serialiseReferenceObject
function, or the serialise
member
function of the SerialisableObject
class can be used to create
and/or save
a version of an object which contains a
hierarchical representation of the data embedded in it. These serialised
objects are standard R lists, with an "originalClass"
attribute
describing the class of the original object. The
deserialiseReferenceObject
function can be used to deserialise them.
Custom deserialisers can be specified using registerDeserialiser
,
typically for legacy classes.
Note that this should generally NOT be used as the primary mechanism for
saving and loading MriImage
objects. Saving to standard
NIfTI/Analyze format is usually preferable, and can be done using
writeImageFile
.
isDeserialisable
returns TRUE
if the object
is
deserialisable and inherits from the specified class.
deserialiseReferenceObject
returns a raw or reconstituted object
after deserialisation.
Jon Clayden
Please cite the following reference when using TractoR in your work:
J.D. Clayden, S. Muñoz Maniega, A.J. Storkey, M.D. King, M.E. Bastin & C.A. Clark (2011). TractoR: Magnetic resonance imaging and tractography with R. Journal of Statistical Software 44(8):1-18. doi:10.18637/jss.v044.i08.
SerialisableObject
, save
,
load
, writeImageFile
.
The execute
function is a wrapper around the system2
function in base, which additionally echoes the command being run (including
the full path to the executable) if the reportr output level is
Debug
. locateExecutable
simply returns the path to an
executable file on the system PATH
.
locateExecutable(fileName, errorIfMissing = TRUE) execute(executable, params = NULL, errorOnFail = TRUE, silent = FALSE, ...)
locateExecutable(fileName, errorIfMissing = TRUE) execute(executable, params = NULL, errorOnFail = TRUE, silent = FALSE, ...)
executable , fileName
|
Name of the executable to run. |
params |
A character vector giving the parameters to pass to the executable, if any. Elements will be separated by a space. |
errorOnFail , errorIfMissing
|
Logical value: should an error be produced if the executable can't be found? |
silent |
Logical value: should the executable be run without any output? |
... |
Additional arguments to |
For execute
, the return value of the underlying call to
system2
. For locateExecutable
, the location of the
requested executable, or NULL
if it could not be found.
These functions are designed for Unix systems and may not work on Windows.
Jon Clayden
Please cite the following reference when using TractoR in your work:
J.D. Clayden, S. Muñoz Maniega, A.J. Storkey, M.D. King, M.E. Bastin & C.A. Clark (2011). TractoR: Magnetic resonance imaging and tractography with R. Journal of Statistical Software 44(8):1-18. doi:10.18637/jss.v044.i08.
This function concatenates the data from a series of MriImage
objects, and then attempts to work out the final dimensions of the merged
image and returns it.
mergeMriImages(..., bindDim = NULL, padTags = FALSE)
mergeMriImages(..., bindDim = NULL, padTags = FALSE)
... |
|
bindDim |
An integer specifying the dimension along which to bind the
data, or |
padTags |
Logical value. If |
A merged image.
Tags are retained as-is if they are identical in each image. Otherwise
they are concatenated if their lengths match the number of blocks in each
image, or concatenated with NAs for missing values if padTags
is
TRUE
.
Jon Clayden
Please cite the following reference when using TractoR in your work:
J.D. Clayden, S. Muñoz Maniega, A.J. Storkey, M.D. King, M.E. Bastin & C.A. Clark (2011). TractoR: Magnetic resonance imaging and tractography with R. Journal of Statistical Software 44(8):1-18. doi:10.18637/jss.v044.i08.
This class represents an MRI image. An object of this class is made up of
some voxel data, stored as a sparse or dense numeric array, and some
metadata, such as the file it was read from, the voxel dimensions, and so
on. The group generic functions Math
, Ops
and
Summary
are defined for this class, as are methods for
coercing to and from a standard array
.
imageDims
Integer vector of dimensions
voxelDims
Numeric vector of pixel/voxel spacings
voxelDimUnits
Character vector of spatial and/or temporal spacing units. Millimetres and seconds (i.e., c("mm","s")) are typical
source
String naming the file(s) that the image was read from. This is reset to the empty string if the image is modified
origin
Numeric vector giving the spatial coordinate origin
xform
Numeric matrix giving the NIfTI-style xform matrix associated with the image, which indicates its orientation
reordered
Logical value indicating whether the image has been
reordered. See reorderMriImage
tags
Named list of arbitrary DICOM-style tags
data
Sparse or dense array of data, or NULL
apply(...)
Apply a function to the margins of the image
binarise()
Binarise the image by setting nonzero values to one
fill(value)
Fill the image with a particular value
find(fun = NULL, ..., array = TRUE)
Find voxels whose values are not zero, or satisfy a function
getDataAtPoint(...)
Obtain the value of the image at a particular point
getMetadata()
Obtain a version of the image with any data removed
getNonzeroIndices(array = TRUE, positiveOnly = FALSE)
Find voxels whose values are not zero
getSlice(dim, loc)
Extract data from a slice of the image along one dimension
getSparseness()
Obtain the proportion of zeroes in the image
getTags(keys = NULL)
Retrieve some or all of the tags stored with the image
getXform(implicit = TRUE)
Retrieve the stored or implicit xform matrix
map(fun, ..., sparse = NULL)
Replace the current data with the result of a function
mask(maskImage)
Mask the image, setting zero voxels in the mask to zero
setData(newData)
Replace the data in the image
setOrigin(newOrigin)
Update the origin of the image
setSource(newSource)
Update the source of the image
setTags(..., merge = FALSE)
Add, replace or merge metadata tags
setXform(newXform)
Update the xform matrix associated with the image
summarise()
Summarise key aspects of the object
threshold(level, defaultValue = 0)
Threshold the image by setting values below the threshold level to zero
This function creates a SparseArray
object from its
constituent parts.
newSparseArrayWithData(data, coordinates, dims)
newSparseArrayWithData(data, coordinates, dims)
data |
A vector of (nonzero) array elements. |
coordinates |
A matrix with as many rows as |
dims |
The dimensions of the array. |
A SparseArray
object.
Jon Clayden
Please cite the following reference when using TractoR in your work:
J.D. Clayden, S. Muñoz Maniega, A.J. Storkey, M.D. King, M.E. Bastin & C.A. Clark (2011). TractoR: Magnetic resonance imaging and tractography with R. Journal of Statistical Software 44(8):1-18. doi:10.18637/jss.v044.i08.
The nil object is an empty object of class SerialisableObject
.
It can be used as a placeholder where such an object of this class, or one
of its subclasses, is required. It serialises to the empty list.
nilObject() is.nilObject(object)
nilObject() is.nilObject(object)
object |
Any object. |
nilObject
returns the nil object. is.nilObject
returns
TRUE
if its argument is identical to the nil object, or if it is
equivalent in the sense of serialising to an identical result.
Jon Clayden
Please cite the following reference when using TractoR in your work:
J.D. Clayden, S. Muñoz Maniega, A.J. Storkey, M.D. King, M.E. Bastin & C.A. Clark (2011). TractoR: Magnetic resonance imaging and tractography with R. Journal of Statistical Software 44(8):1-18. doi:10.18637/jss.v044.i08.
This function chooses the singular or plural form of a word based on the length of an associated vector, or an integer.
pluralise(singular, x = NULL, n = NULL, plural = NULL)
pluralise(singular, x = NULL, n = NULL, plural = NULL)
singular |
The singular form of the word. |
x |
A vector of any mode, whose length is used to choose the correct
word form, unless |
n |
An integer which is used to choose the correct word form (singular
if n = 1, plural otherwise). Take priority over |
plural |
The plural form of the word. If |
Either singular
or plural
, as appropriate.
Jon Clayden
Please cite the following reference when using TractoR in your work:
J.D. Clayden, S. Muñoz Maniega, A.J. Storkey, M.D. King, M.E. Bastin & C.A. Clark (2011). TractoR: Magnetic resonance imaging and tractography with R. Journal of Statistical Software 44(8):1-18. doi:10.18637/jss.v044.i08.
This is a simple function to print a series of labels and associated data values, or key-value pairs.
printLabelledValues(labels, values, outputLevel = OL$Info, leftJustify = FALSE)
printLabelledValues(labels, values, outputLevel = OL$Info, leftJustify = FALSE)
labels |
A character vector of labels. |
values |
A character vector of values. Must have the same length as
|
outputLevel |
The output level to print the output to. See
|
leftJustify |
Logical value: if |
This function is called for its side effect.
Jon Clayden
Please cite the following reference when using TractoR in your work:
J.D. Clayden, S. Muñoz Maniega, A.J. Storkey, M.D. King, M.E. Bastin & C.A. Clark (2011). TractoR: Magnetic resonance imaging and tractography with R. Journal of Statistical Software 44(8):1-18. doi:10.18637/jss.v044.i08.
setOutputLevel
for the reportr output level system.
The promote
function promotes a vector argument to a single-column or
single-row matrix. Matrix arguments are returned unmodified.
promote(x, byrow = FALSE)
promote(x, byrow = FALSE)
x |
A vector or matrix. |
byrow |
Logical value: if |
A matrix version of the x
argument.
Jon Clayden
Please cite the following reference when using TractoR in your work:
J.D. Clayden, S. Muñoz Maniega, A.J. Storkey, M.D. King, M.E. Bastin & C.A. Clark (2011). TractoR: Magnetic resonance imaging and tractography with R. Journal of Statistical Software 44(8):1-18. doi:10.18637/jss.v044.i08.
This function scans a directory for files in DICOM format, and converts them to a single Analyze/NIfTI-format image of the appropriate dimensionality.
readDicomDirectory(dicomDir, method = c("internal", "divest"), readDiffusionParams = FALSE, untileMosaics = TRUE, ...)
readDicomDirectory(dicomDir, method = c("internal", "divest"), readDiffusionParams = FALSE, untileMosaics = TRUE, ...)
dicomDir |
Character vector of length one giving the name of a directory containing DICOM files. |
method |
Character string specifying whether to use the internal DICOM
reading code or use the |
readDiffusionParams |
Logical value. Should diffusion MRI parameters (b-values and gradient directions) be retrieved from the files if possible? |
untileMosaics |
Logical value. Should Siemens mosaic images be
converted into 3D volumes? This may occasionally be performed in error,
which can be prevented by setting this value to |
... |
Additional arguments to |
A list containing elements
An MriImage
object.
Diffusion b-values, if requested. Will be NA
if
the information could not be found in files.
Diffusion gradient vectors, if requested. Will be
NA
if the information could not be found in the files.
Jon Clayden
Please cite the following reference when using TractoR in your work:
J.D. Clayden, S. Muñoz Maniega, A.J. Storkey, M.D. King, M.E. Bastin & C.A. Clark (2011). TractoR: Magnetic resonance imaging and tractography with R. Journal of Statistical Software 44(8):1-18. doi:10.18637/jss.v044.i08.
DicomMetadata
, MriImage
,
sortDicomDirectories
.
This function reads a DICOM file into a DicomMetadata
object.
Only DICOM files from magnetic resonance scanners are supported.
readDicomFile(fileName, checkFormat = TRUE, stopTag = NULL, ignoreTransferSyntax = FALSE, ascii = TRUE)
readDicomFile(fileName, checkFormat = TRUE, stopTag = NULL, ignoreTransferSyntax = FALSE, ascii = TRUE)
fileName |
The name of a DICOM file. |
checkFormat |
If |
stopTag |
An integer vector giving the group and element numbers (in
that order) of a DICOM tag, or |
ignoreTransferSyntax |
If |
ascii |
If |
readDicomFile
returns a DicomMetadata
object, or NULL
on failure.
Jon Clayden
Please cite the following reference when using TractoR in your work:
J.D. Clayden, S. Muñoz Maniega, A.J. Storkey, M.D. King, M.E. Bastin & C.A. Clark (2011). TractoR: Magnetic resonance imaging and tractography with R. Journal of Statistical Software 44(8):1-18. doi:10.18637/jss.v044.i08.
The DICOM standard, found online at
https://www.dicomstandard.org/. (Warning: may produce headaches!)
Also readDicomDirectory
for information on how to create
MriImage
objects from DICOM files.
Functions for expanding file paths, finding relative paths and ensuring that a file name has the required suffix.
resolvePath(path, ...) relativePath(path, referencePath) matchPaths(path, referencePath) registerPathHandler(regex, handler) expandFileName(fileName, base = getwd()) ensureFileSuffix(fileName, suffix, strip = NULL)
resolvePath(path, ...) relativePath(path, referencePath) matchPaths(path, referencePath) registerPathHandler(regex, handler) expandFileName(fileName, base = getwd()) ensureFileSuffix(fileName, suffix, strip = NULL)
path , referencePath
|
Character vectors whose elements represent file paths (which may or may not currently exist). |
... |
Additional arguments to custom path handlers. |
regex |
A Ruby-style regular expression. |
handler |
A function taking and returning a string. |
fileName |
A character vector of file names. |
base |
If |
suffix |
A character vector of file suffixes, which will be recycled if
shorter than |
strip |
A character vector of suffixes to remove before appending
|
The resolvePath
function passes its arguments elementwise through any
matching path handler, and returns the resolved paths. Nonmatching elements
are returned as-is. registerPathHandler
registers a new path handler
for special syntaxes, and is for advanced use only. relativePath
returns the specified path
, expressed relative to
referencePath
. matchPaths
resolves a vector of paths against a
vector of reference paths. expandFileName
returns the full path to
the specified file name, collapsing ".."
elements if appropriate.
ensureFileSuffix
returns the specified file names with the requested
suffixes appended (if they are not already).
A character vector.
Jon Clayden
Please cite the following reference when using TractoR in your work:
J.D. Clayden, S. Muñoz Maniega, A.J. Storkey, M.D. King, M.E. Bastin & C.A. Clark (2011). TractoR: Magnetic resonance imaging and tractography with R. Journal of Statistical Software 44(8):1-18. doi:10.18637/jss.v044.i08.
normalizePath
does most of the work for
expandFileName
.
These functions provide the (Euclidean) length of a vector, the vector cross product or angle between two vectors.
resolveVector(len, ...) vectorLength(vector) vectorCrossProduct(a, b) angleBetweenVectors(v1, v2)
resolveVector(len, ...) vectorLength(vector) vectorCrossProduct(a, b) angleBetweenVectors(v1, v2)
len |
The expected length of the vector. |
... |
Elements of the vector, to be concatenated together. |
vector , v1 , v2
|
Numeric vectors of any length. |
a , b
|
Numeric 3-vectors. |
For vectorLength
, the Euclidean norm or length of the
specified vector, given by sqrt(sum(vector^2))
. For
vectorCrossProduct
, the vector cross product of the two specified
vectors; and for angleBetweenVectors
, the angle (in radians)
between the two specified vectors. The resolveVector
function
concatenates the values given in ...{}
, and if the result is a
vector of length len
then it is returned. If not, NULL
is
returned.
Jon Clayden
Please cite the following reference when using TractoR in your work:
J.D. Clayden, S. Muñoz Maniega, A.J. Storkey, M.D. King, M.E. Bastin & C.A. Clark (2011). TractoR: Magnetic resonance imaging and tractography with R. Journal of Statistical Software 44(8):1-18. doi:10.18637/jss.v044.i08.
crossprod
for the matrix cross product.
This reference class extends TractorObject
by adding a
function for simple serialisation of the data fields of an object, either to
a list or a file. This is intended to be used for classes whose state can
meaningfully be restored from a list of standard R objects (not including
transient C/C++ pointers, for example). A serialised object may be
deserialised using the deserialiseReferenceObject
function.
serialise(file = NULL)
Serialise the object to a list or file
This function sorts a directory containing DICOM files into subdirectories by series UID (DICOM tag 0x0020,0x000e), subject name (0x0010,0x0010) and/or scan date (0x0008,0x0020). Each unique identifier, together with its description for series, will be used as the name for a new subdirectory, and all relevant files will be copied into that subdirectory. Duplicate file names are disambiguated if necessary.
sortDicomDirectories(directories, method = c("internal", "divest"), deleteOriginals = FALSE, sortOn = "series", seriesId = c("UID", "number", "time"), nested = TRUE, ...)
sortDicomDirectories(directories, method = c("internal", "divest"), deleteOriginals = FALSE, sortOn = "series", seriesId = c("UID", "number", "time"), nested = TRUE, ...)
directories |
A character vector giving the directories to search for DICOM files. Subdirectories will also be searched. |
method |
Character string specifying whether to use the internal DICOM
reading code or use the |
deleteOriginals |
A single logical value. If |
sortOn |
The string |
seriesId |
A string describing the kind of series identifier to use for
sorting by series: |
nested |
Logical value. If |
... |
Additional arguments to pass to |
This function is called for its side effect.
Jon Clayden
Please cite the following reference when using TractoR in your work:
J.D. Clayden, S. Muñoz Maniega, A.J. Storkey, M.D. King, M.E. Bastin & C.A. Clark (2011). TractoR: Magnetic resonance imaging and tractography with R. Journal of Statistical Software 44(8):1-18. doi:10.18637/jss.v044.i08.
readDicomDirectory
for reading DICOM files into an
MriImage
object.
This class represents an array with any number of dimensions, in which a
significant proportion of entries are zero. The coordinates of nonzero
entries are stored along with their values, with all remaining entries
assumed to be zero. Methods are provided to index into the array in the
standard way, using matrix or vector indices; and for coercing between
SparseArray
objects and standard (dense) arrays.
data
Vector of nonzero data values
coords
Integer matrix of nonzero data
locations, one per row
dims
Integer vector of dimensions
aperm(perm)
Permute the dimensions of the array
apply(margin, fun, ...)
Apply a function to margins of the array
flip(dimsToFlip)
Flip the array along one or more directions
setCoordinatesAndData(newCoords, newData)
Update the nonzero locations and data values in the array
setDimensions(newDims)
Change the dimensions of the image
summarise()
Summarise key aspects of the object
This function is a wrapper around tempfile
, which creates
temporary file names whose path contains the process ID of the calling
process. This avoids clashes between threads created by functions such as
mclapply
(in the “parallel” package), which can easily occur with
the standard tempfile
function.
threadSafeTempFile(pattern = "file")
threadSafeTempFile(pattern = "file")
pattern |
Character vector giving the initial part of each file name. |
A character vector of temporary file names. No files are actually created.
Jon Clayden
Please cite the following reference when using TractoR in your work:
J.D. Clayden, S. Muñoz Maniega, A.J. Storkey, M.D. King, M.E. Bastin & C.A. Clark (2011). TractoR: Magnetic resonance imaging and tractography with R. Journal of Statistical Software 44(8):1-18. doi:10.18637/jss.v044.i08.
This reference class extends the standard envRefClass
class, adding methods for finding all of the field or methods available for
an object. There is also a method for summarising key elements of the object
as a named character vector, which can be suitable overridden by inheriting
classes. The show
method prints this summary as a labelled list.
fields()
Retrieve a list of all field names
methods()
Retrieve a list of all method names
summarise()
Summarise key aspects of the object
This simple function checks whether its first argument is a logical value
that evaluates to TRUE
. If so, it returns its second argument. If
not, it returns its third argument.
where(condition, value, fallback = NULL)
where(condition, value, fallback = NULL)
condition |
An expression that resolves to a single logical value. |
value , fallback
|
Any expression. |
This function differs from the standard ifelse
function in
that it does not act elementwise, and that the third argument is optional,
defaulting to NULL
.
value
, if condition
evaluates to TRUE
;
otherwise fallback
.
Jon Clayden
Please cite the following reference when using TractoR in your work:
J.D. Clayden, S. Muñoz Maniega, A.J. Storkey, M.D. King, M.E. Bastin & C.A. Clark (2011). TractoR: Magnetic resonance imaging and tractography with R. Journal of Statistical Software 44(8):1-18. doi:10.18637/jss.v044.i08.
ifelse