| Type: | Package |
| Title: | Read and Write 'FreeSurfer' Neuroimaging File Formats |
| Version: | 1.1.0 |
| Maintainer: | Tim Schäfer <ts+code@rcmd.org> |
| Description: | Provides functions to read and write neuroimaging data in various file formats, with a focus on 'FreeSurfer' formats. This includes, but is not limited to, the following file formats: 1) MGH/MGZ/NIFTI format files, which can contain multi-dimensional images or other data. Typically they contain time-series of three-dimensional brain scans acquired by magnetic resonance imaging (MRI). They can also contain vertex-wise measures of surface morphometry data. The MGH format is named after the Massachusetts General Hospital, and the MGZ format is a compressed version of the same format. 2) 'FreeSurfer' morphometry data files in binary 'curv' format. These contain vertex-wise surface measures, i.e., one scalar value for each vertex of a brain surface mesh. These are typically values like the cortical thickness or brain surface area at each vertex. 3) Annotation file format. This contains a brain surface parcellation derived from a cortical atlas. 4) Surface file format. Contains a brain surface mesh, given by a list of vertices and a list of faces. |
| License: | MIT + file LICENSE |
| Copyright: | Tim Schäfer (package code); the optional data files that can be downloaded at runtime are owned by their respective copyright holders, see 'inst/COPYRIGHTS'. |
| Encoding: | UTF-8 |
| URL: | https://github.com/dfsp-spirit/freesurferformats, https://dfsp-spirit.github.io/freesurferformats/ |
| BugReports: | https://github.com/dfsp-spirit/freesurferformats/issues |
| Imports: | utils, pkgfilecache (≥ 0.1.1), xml2 |
| Suggests: | knitr, rmarkdown, curl, testthat (≥ 2.1.0), oro.nifti (≥ 0.9), gifti (≥ 0.7.5), cifti (≥ 0.4.5) |
| VignetteBuilder: | knitr |
| Config/roxygen2/version: | 8.0.0 |
| NeedsCompilation: | no |
| Packaged: | 2026-09-24 10:02:44 UTC; ts |
| Author: | Tim Schäfer |
| Repository: | CRAN |
| Date/Publication: | 2026-09-24 18:00:02 UTC |
Bring a gradient table into the canonical 'one row per volume' layout.
Description
Gradient tables occur in two orientations in the wild: the FSL layout, in which the first axis is the vector component (3 rows of N values for b-vectors, a single row of N values for b-values), and the volumes layout, in which each line is one volume (N rows of 3 values for b-vectors, as used by HCP, and N rows of 4 values for the MRtrix gradient table format). This helper maps both to one row per volume.
Usage
.canonicalize.gradient.table(
m,
n_components,
layout,
what,
square_is_ambiguous = FALSE
)
Arguments
m |
numeric matrix, the table as read from the file. |
n_components |
integer, the number of values per volume (3 for b-vectors, 4 for a gradient table, 1 for b-values). |
layout |
character string, one of 'auto', 'components' or 'volumes'. How to interpret the input. With 'auto' (the default), the orientation is derived from the matrix dimensions. |
what |
character string, a human-readable description of the data, used in the messages. |
square_is_ambiguous |
logical, how to handle a table that has exactly
|
Value
a numeric matrix with one row per volume and n_components columns.
Note
A square 3x3 file is ambiguous, and the two reference implementations
do not agree on it: MRtrix3 reads such a b-vectors file with the components
in the rows, while DIPY reads it with the volumes in the rows. Like
MRtrix3, read.dti.bvec treats the lines as
components, and warns, because silently guessing here would scramble the
gradient directions. Matrices passed in memory are read with one row per
volume, which is the R convention, and no warning is needed.
Convert a label table to the format the package has always returned.
Description
The readers document a label table with the column names 'Key', 'Red', 'Green', 'Blue', 'Alpha' and 'Label'; keep that spelling (and the column order) for the user-facing functions, while the internal representation uses lower case column names and also stores the optional label coordinates.
Usage
.cifti.label.table.for.users(labels)
Arguments
labels |
a data.frame as returned by |
Value
a data.frame with the columns 'Key', 'Red', 'Green', 'Blue', 'Alpha' and 'Label'.
Get the b-value threshold below which a volume counts as a b=0 volume.
Description
MRtrix3 treats any volume whose b-value is at most this
threshold as a b=0 volume. See the BZeroThreshold configuration entry
of MRtrix3, which defaults to 10 s/mm^2.
Usage
.dti.bzero.threshold()
Value
numeric scalar, the threshold in s/mm^2.
Find the b-value file that belongs to a b-vector file.
Description
Looks for the bvals file next to a bvecs file, by replacing
the bvec/bvecs part of the file name with bval/bvals, and by
replacing the file extension if that does not match. This makes the
readers work out of the box on standard datasets, e.g. the BIDS files
sub-01_dwi.bvec and sub-01_dwi.bval.
Usage
.find.bval.file(bvec_filepath)
Arguments
bvec_filepath |
character string, path to the b-vector file. |
Value
character string, the path to the existing b-value file, or NULL if none of the candidates exists.
Format numeric values for a gradient table text file.
Description
Writes gradient values with enough significant digits to
survive a round trip, in a plain decimal or scientific notation that the
FSL, MRtrix3, DIPY and NumPy readers all accept. Note that
formatC(..., digits = 15) cannot be used here: with the default
width = NULL it treats digits as the field width and pads
every value with spaces, which makes the files hard to read.
Usage
.format.gradient.values(x)
Arguments
x |
numeric vector, the values to format. |
Value
character vector of the same length as x.
Format a possibly missing TRK header size for an error message.
Description
Format a possibly missing TRK header size for an error message.
Usage
.format.header.size(value)
Arguments
value |
integer vector, the result of a |
Value
character string.
Name the columns of an MRtrix gradient table.
Description
Name the columns of an MRtrix gradient table.
Usage
.name.gradient.table.columns(gt)
Arguments
gt |
numeric matrix with 4 columns, one row per volume. |
Value
the matrix with columns named 'x', 'y', 'z' and 'b'.
Read DTI tracking data from MRtrix TCK and TSF files.
Description
Read DTI tracking data from MRtrix TCK and TSF files.
Usage
.read.dti.tcktsf(
filepath,
max_tracks = Inf,
skip_tracks = 0L,
bbox = NULL,
chunk_values = 4e+06
)
Arguments
filepath |
character string, path to the |
max_tracks |
numeric, the maximum number of tracks to read. Use
|
skip_tracks |
integer, the number of tracks to skip before reading any. Skipped tracks are never held in memory. |
bbox |
numeric vector of length 6 or NULL. If given, only tracks that
have at least one point inside the box are read, the box is given as
|
chunk_values |
integer, the number of payload values that are read per chunk. This is an advanced tuning parameter that does not change the result, only the peak memory usage (at most one chunk is buffered at a time) and the granularity of the file reads. The default of 4e6 values corresponds to about 32 MB of doubles. Lower it on a machine with very little free memory. |
Value
named list with entries header and either tracks (for
TCK files) or scalars (for TSF files).
Read a whitespace-separated numeric table from a text file.
Description
Low-level parser shared by all gradient table readers. Values
may be separated by spaces, tabs or commas, and both blank lines and lines
starting with # are ignored. All remaining lines must contain the same
number of values.
Usage
.read.numeric.table(filepath, allow_count_header = FALSE)
Arguments
filepath |
character string, path to the file. Gzip-compressed files are detected by their magic bytes, not by the file name. |
allow_count_header |
logical, whether a first line that consists of a
single integer may be interpreted as a count header and dropped. Only the
MRtrix gradient table reader enables this, because the historical
|
Value
a numeric matrix, one row per input line.
Write a numeric table to a text file, one matrix row per line.
Description
Write a numeric table to a text file, one matrix row per line.
Usage
.write.numeric.table(filepath, m)
Arguments
filepath |
character string, path to the output file. Files ending in
|
m |
numeric matrix, the table to write. |
Value
NULL, invisibly.
The NIFTI v2 extension code that holds the CIFTI-2 XML metadata.
Description
The CIFTI-2 XML document is stored in a NIFTI v2 header extension with this code.
Usage
CIFTI_EXTENSION_CODE
Subset an fs.tracts instance.
Description
Subset an fs.tracts instance.
Usage
## S3 method for class 'fs.tracts'
x[i]
Arguments
x |
an |
i |
index vector (integer, numeric or logical), as usual in R. |
Value
a new fs.tracts instance containing the selected tracts.
Examples
## Not run:
tck <- read.dti.tck("brain.tck");
first_ten <- tck$tracks[1:10];
## End(Not run)
Access a single tract of an fs.tracts instance.
Description
For TCK data (see read.dti.tck), a tract is an n x 3
numeric matrix of coordinates. For TRK data (see read.dti.trk), a
tract is a named list with the entries coords (n x 3 matrix),
num_points (integer), scalars (n x n_scalars matrix or NULL)
and properties (numeric vector or NULL).
This returns a copy of the requested tract, the data is stored in a single matrix internally.
Usage
## S3 method for class 'fs.tracts'
x[[i]]
Arguments
x |
an |
i |
positive integer, the index of the tract to retrieve. |
Value
the tract, see the description.
Examples
## Not run:
tck <- read.dti.tck("brain.tck");
first_tract_coords <- tck$tracks[[1]];
## End(Not run)
Adjust integer matrix to target min value.
Description
This takes a matrix of integers, and adjusts the values such that the minimal value is the 'target_min_index' value. It is used to adjust from 0-based to 1-based indices in meshes.
Usage
adjust.face.indices.to(faces, target_min_index = 1L)
Arguments
faces |
3xn integer matrix, the vertex indices of the faces |
target_min_index |
integer, one of 1L or 0L. The target minimal value that the data should have afterwards. |
Value
3xn integer matrix, the adjusted values
Note
The current and the target min values must be 0 or 1.
Compute the R data type and the number of bytes per value for an ANALYZE data type.
Description
Compute the R data type and the number of bytes per value for an ANALYZE data type.
Usage
analyze.dtype.info(analyzeheader, filepath = NULL)
Arguments
analyzeheader |
named list, an ANALYZE 7.5 header as returned by |
filepath |
character string, the path of the file the header was read from. Only used for warning and error messages. |
Value
named list with the entries datatype and bitpix (the data type fields to use for reading the data,
which may differ from the values in the file if the file contradicts itself), num_bytes (the number of bytes
per value) and r_dtype (the R type to read the values as).
Note
ANALYZE files in the wild sometimes have a wrong bitpix field, since the format was used by many tools
that did not care about it. The data type is the reliable field, so if the two fields contradict each other, the
bitpix value that belongs to the data type is used, with a warning.
Check whether an ANALYZE 7.5 header is suitable for writing.
Description
Check whether an ANALYZE 7.5 header is suitable for writing.
Usage
analyze.header.check(analyzeheader)
Arguments
analyzeheader |
named list, an ANALYZE 7.5 header as returned by |
Value
logical, whether the header passed the checks. Fields that cannot be written as requested are reported
with a message.
Note
The checks are in no way meant to be exhaustive. They only verify that the fields that are written to the file have a length that fits into their fixed size slots in the 348 byte header, since writing a longer value would shift all fields behind it and produce a corrupt file.
Compute a transformation matrix from the fields of an ANALYZE 7.5 header.
Description
Compute the voxel-to-RAS matrix for an ANALYZE 7.5 image, using the conventions of SPM and of the
original ANALYZE software. See the "geometry" section of read.fs.volume.analyze for what this
matrix is and is not.
Usage
analyze.header.to.vox2ras(analyzeheader)
Arguments
analyzeheader |
named list, an ANALYZE 7.5 header as returned by |
Value
a 4x4 numeric matrix, the voxel-to-RAS transformation matrix. The matrix assumes that the first voxel
axis points to the left (i.e. it contains -pix_dim[2] in its first column), which is the convention of the
format. If the SPM origin is present in the header, the matrix maps the origin to the world position that the
SPM fields describe, otherwise the center of the image is used as the origin, exactly as the reference
implementation of the format (nibabel) does it.
Compute the voxel-to-RAS matrix from the MATLAB sidecar file of an ANALYZE image.
Description
Read the transformation matrix that SPM and FreeSurfer write into the .mat file next to an ANALYZE
image, and convert it to the convention used by this package (0-based voxel indices, right-anterior-superior
world coordinates). See the geometry section of read.fs.volume.analyze for the details.
Usage
analyze.mat.sidecar.to.vox2ras(matfile)
Arguments
matfile |
character string, the path of the |
Value
named list with the entries vox2ras (a 4x4 numeric matrix, or NULL if the file could not be read or
contains no usable matrix) and reason (a character string describing the problem, or NULL on success).
Determine the header and data file of an ANALYZE 7.5 or NIFTI v1 pair file.
Description
The two formats ANALYZE 7.5 and NIFTI v1 (in its two-file variant) store the image in a header file
(<base>.hdr) and a data file (<base>.img). This function computes the two file names from any of them, so
that the user can pass any of the possible spellings.
Usage
analyze.pair.files(filepath, require_header = FALSE)
Arguments
filepath |
character string, the path to the header file, to the data file, or to the base name (with or
without a |
require_header |
logical, whether to stop with an error if the header file does not exist. If |
Value
named list with the entries header and image, the full paths to the header and the data file, the
logical entries header_exists and image_exists, and the entries mat (the path of the MATLAB sidecar file
that SPM and FreeSurfer write next to the image file, see read.fs.volume.analyze) and
mat_exists, which report whether such a file is present.
Note
Compression is handled the way the other implementations of the format handle it: the suffix .gz (and
.hdr/.img) is stripped from the file name to get the base name, and the two file names are constructed from
it. A name like vol.hdr.gz therefore describes the pair vol.hdr.gz and vol.img.gz, and vol.nii.gz would
be the pair vol.nii.hdr.gz and vol.nii.img.gz. Note that many tools only read uncompressed pairs, so
compressed pairs should only be written if the software that reads them supports this.
Read a fixed length character field of an ANALYZE 7.5 header.
Description
Read a fixed length character field of an ANALYZE 7.5 header.
Usage
analyze.read.char.field(filehandle, n)
Arguments
filehandle |
connection to read from. |
n |
integer, the number of bytes of the field. |
Value
character string, the field content with the trailing zero bytes removed. The bytes are interpreted as
ISO-8859-1 (latin-1) and converted to UTF-8, which cannot fail: the ANALYZE 7.5 fields originator,
generated, patient_id and friends contain whatever the software that wrote the file put there, including
bytes that are not valid UTF-8 (the SPM software, for example, stores an image origin as 3 little endian
integers in the originator field). Decoding them as UTF-8 would fail or return NA for a subset of the
possible byte values.
Read ANALYZE 7.5 header from file.
Description
Read ANALYZE 7.5 header from file.
Usage
analyze.read.header.internal(filepath, little_endian = TRUE)
Arguments
filepath |
character string, the path to the |
little_endian |
logical, leave this alone. The endianness is detected automatically, and messing with this parameter only makes the detection report a wrong endianness for a file of the other one. |
Value
named list, the ANALYZE 7.5 header. See read.analyze.header.
Read the 4 magic bytes of an ANALYZE 7.5 or NIFTI v1 header.
Description
Read the 4 magic bytes of an ANALYZE 7.5 or NIFTI v1 header.
Usage
analyze.read.magic(filepath)
Arguments
filepath |
character string, the path to the header file of a pair. |
Value
character string, the 4 bytes at offset 344 of the file, interpreted as a string. This is the NIFTI v1
magic field, which is empty ('') for ANALYZE 7.5 files (where the same bytes are the smin field), 'ni1'
for a NIFTI v1 pair file and 'n+1' for a single file NIFTI v1 file.
Write the voxel data of an ANALYZE 7.5 image to a connection.
Description
Write the voxel data of an ANALYZE 7.5 image to a connection.
Usage
analyze.write.data.internal(fh, analyzedata, analyzeheader)
Arguments
fh |
connection to write to. |
analyzedata |
array of numeric data. |
analyzeheader |
named list, a valid ANALYZE 7.5 header that describes the data. |
Value
the data that was written, after conversion to the data type stated in the header.
Create ANALYZE 7.5 header suitable for given data.
Description
Create ANALYZE 7.5 header suitable for given data.
Usage
analyzeheader.for.data(analyzedata, ...)
Arguments
analyzedata |
array of numeric (integer or double) data, can have up to 7 dimensions. |
... |
extra parameters passed on to |
Value
an ANALYZE 7.5 header (see analyzeheader.template) in which the datatype, bitpix,
dim, cal_min and cal_max fields have been set to values suitable for the given data. Feel free to change
the other fields, e.g. the voxel sizes in pix_dim or the orient code.
Note
ANALYZE 7.5 has much fewer data types than NIFTI: integers are stored as 32 bit signed integers and floating
point data as 32 bit floats, which is what this function selects (the same choice that
ni1header.for.data makes for NIFTI v1). To store 16 bit integers, which is the classic ANALYZE
data type, set datatype to 4L and bitpix to 16L in the returned header after calling this function.
Examples
analyzeheader <- analyzeheader.for.data(array(1:24, dim = c(4, 3, 2)))
analyzeheader$datatype
Create a template ANALYZE 7.5 header. You will have to adapt it for your use case.
Description
This function returns a valid ANALYZE 7.5 header with all fields present, filled with the default
values of the format. You will most likely have to adapt at least the dim, datatype, bitpix and pix_dim
fields to your data, which is what analyzeheader.for.data does for you.
Usage
analyzeheader.template()
Value
named list, the ANALYZE 7.5 header. The fields endian, magic, header_format and spm_origin are not
part of the ANALYZE 7.5 header: endian and magic describe how the file is stored, header_format tells
which variant of the 348 byte header this is ('analyze' or 'nifti1_pair'), and spm_origin is the
interpretation of the originator field that the SPM software uses.
Note
The fields spm_origin and magic are derived when a file is read, they are documented in
read.analyze.header.
See Also
analyzeheader.for.data, read.analyze.header, write.analyze
Examples
analyzeheader <- analyzeheader.template()
analyzeheader$dim <- c(3L, 4L, 3L, 2L, 1L, 1L, 1L, 1L)
analyzeheader$pix_dim <- c(1., 1., 1., 1., 0., 0., 0., 0.)
Get max region index of an fs.annot instance.
Description
Get max region index of an fs.annot instance.
Usage
annot.max.region.idx(annot)
Arguments
annot |
fs.annot instance |
Value
integer, the max region index. They typically start with 0 and are consecutive, but this is not enforced or checked in any way.
Note
This is a helper function to be used with annot.unique, see the example there.
Make the region names and indices unique across hemispheres for a parcellation.
Description
Sometimes you need an annotation to use unique IDs and region names across hemispheres, but that is not the case for the standard FreeSurfer parcellations. So what you need to do is change the codes and names for one hemi. Typically the left hemi annot will be left as is, and the right hemi annot will be modified using this function.
Usage
annot.unique(
annot,
add_to_region_indices,
region_name_prefix = "rh_",
region_name_suffix = NULL,
set_first_idx_zero = FALSE
)
Arguments
annot |
the annot in which to change the ids and names. |
add_to_region_indices |
integer, a single value to add to the region indices. This is typically equal to the number of regions in the left hemisphere plus one (e.g., 36+1=37 for the 'aparc' atlas), as the region indices typically start at 0 and are consecutive, but you may want to check the maximal region id of the left hemi is in doubt. Pass |
region_name_prefix |
character string, a prefix to modify the region names to make them unique. Pass |
region_name_suffix |
character string, a suffix to modify the region names to make them unique. Pass |
set_first_idx_zero |
logical, whether to apply special treatment to first region (the 'unknown' region) in annot and set its ID to |
Note
This function is not part of the official API and should not be used. It is currently broken.
Examples
## Not run:
lh_annot <- read.fs.annot("~/data/study1/subject1/label/lh.aparc.annot")
lh_annot
# shows info including region IDs
rh_annot <- read.fs.annot("~/data/study1/subject1/label/rh.aparc.annot")
rh_annot_mod <- annot.unique(rh_annot, annot.max.region.idx(lh_annot) + 1L,
region_name_prefix = "rh_")
## End(Not run)
Apply an affine to a set of coordinates.
Description
Apply an affine to a set of coordinates.
Usage
apply.affine.to.coords(coords, affine)
Arguments
coords |
numeric matrix with 3 columns, the coordinates. |
affine |
4x4 numeric matrix. |
Value
numeric matrix with 3 columns, the transformed coordinates.
Convert a collection of tracts to an fs.tracts instance.
Description
Accepts an fs.tracts instance, a list of numeric matrices
with 3 columns, or a single such matrix (which is then treated as one
tract), and returns an fs.tracts instance. This is what the writers
use to accept several input types.
Usage
as.fs.tracts(tracts, kind = "tck")
Arguments
tracts |
the input, see the description. |
kind |
character string, 'tck' or 'trk', used for the returned instance. |
Value
an fs.tracts instance.
Examples
tracts <- as.fs.tracts(list(matrix(c(0, 0, 0, 1, 1, 1), ncol = 3, byrow = TRUE)));
length(tracts);
Convert an fs.tracts instance to a plain list of tracts.
Description
Converts to the classic representation as a list with one
entry per tract. This is convenient for interacting with code that expects
a plain list, but note that it materializes one R object per tract and is
therefore much more expensive in both memory and time. Prefer [[
for accessing individual tracts.
Usage
## S3 method for class 'fs.tracts'
as.list(x, ...)
Arguments
x |
an |
... |
ignored. |
Value
list with one entry per tract.
Examples
## Not run:
tck <- read.dti.tck("brain.tck");
tracts_list <- as.list(tck$tracks);
## End(Not run)
Convert scalar values for streamlines to a list of vectors.
Description
Normalizes the several input forms accepted by
write.dti.tsf to a list of numeric vectors, one per
streamline, and checks the lengths for consistency.
Usage
as.tsf.scalars(tracts, lengths = NULL)
Arguments
tracts |
the input, see |
lengths |
integer vector or NULL, the number of values per streamline.
Only used when |
Value
named list with entries values (list of numeric vectors) and
lengths (integer vector).
Stop unless surf is an fs.surface
Description
Stop unless surf is an fs.surface
Usage
assert.surface(surface, param_name = "surface")
Arguments
surface |
fs.surface instance or anything else |
param_name |
character string, used in stop message to identify the parameter. |
Value
Called for the side effect of stopping if surface is not an fs.surface instance.
Construct a brain atlas from a colortable (LUT) file and a per-vertex label file.
Description
Construct a brain atlas (surface annotation) from a FreeSurfer ASCII colortable lookup table (LUT) file and a text file that assigns a label (struct index) to each vertex of a brain surface. This is useful when an atlas is distributed as two text files: a colortable (LUT) plus a per-vertex label assignment, for example the cortical atlases bundled with the Python package 'yabplot' (files like 'aparc_LUT.txt' and 'aparc_conte69.csv').
Usage
atlas.from.lut.and.csv(
lut_file,
csv_file = NULL,
label_indices = NULL,
num_vertices = NULL,
unknown_label_name = "unknown",
unknown_index = 0L,
include_unknown_in_colortable = TRUE
)
Arguments
lut_file |
string, path to a colortable file in FreeSurfer ASCII LUT format (see |
csv_file |
string, path to a text file that assigns a label to each vertex. The file must contain one integer per line: the struct index (label ID) of the region for that vertex, as defined in the first column of the LUT file. See parameter |
label_indices |
integer vector, an alternative to parameter 'csv_file'. The per-vertex struct indices, one per vertex. If given, 'csv_file' is ignored. |
num_vertices |
integer, optional. The expected number of vertices. If given, it must match the number of label indices read from 'csv_file' or 'label_indices'. |
unknown_label_name |
string, the name to use for unlabeled vertices (e.g., the medial wall). Defaults to 'unknown'. |
unknown_index |
integer, the struct index that is used in the label file to mark unlabeled vertices. Defaults to 0. |
include_unknown_in_colortable |
logical, whether to add a region for unlabeled vertices to the colortable of the returned annotation, in case the LUT file does not already contain a region with the 'unknown_index'. Defaults to TRUE. This ensures that vertices without a valid label (e.g., the medial wall) get a proper region name and color in the returned annotation. |
Value
an 'fs.annot' instance with class 'fs.annot', see read.fs.annot for the structure. Can be written to a FreeSurfer annotation file with write.fs.annot.
See Also
Other atlas functions:
colortable.from.annot(),
read.fs.annot(),
read.fs.colortable(),
write.atlas.to.lut.and.csv(),
write.fs.annot(),
write.fs.annot.gii(),
write.fs.colortable()
Examples
## Not run:
# Example for the yabplot cortical atlas files (LUT + per-vertex indices):
annot <- atlas.from.lut.and.csv("aparc_LUT.txt", "aparc_conte69.csv")
write.fs.annot("lh.aparc.annot", fs.annot = annot)
## End(Not run)
Convert axis codes to an orientation array.
Description
Convert axis codes to an orientation array.
Usage
axcodes2ornt(axcodes)
Arguments
axcodes |
character vector with one code per input axis, e.g.
|
Value
numeric matrix with 3 rows and 2 columns, see
io.orientation.
Build the text header of an MRtrix streamlines file.
Description
MRtrix streamlines files (TCK for the tracks, TSF for per-point values along the tracks) share one header format, they only differ in the identifier line and in the meaning of the payload. The header is ASCII text, and its length is stored within the header itself as the offset at which the binary payload starts.
Usage
build.mrtrix.header(header_id, entries, datatype, count, offset)
Arguments
header_id |
character string, the file type identifier, one of 'mrtrix tracks' (TCK) or 'mrtrix track scalars' (TSF). |
entries |
named list of additional header entries. |
datatype |
character string, the datatype. |
count |
integer, the number of streamlines. |
offset |
numeric, the byte offset at which the payload starts. |
Value
character string, the header including the terminating newline.
Determine the length of an MRtrix streamlines header.
Description
The length of the header determines the data offset that is stored inside the header, so the two have to be reconciled: the offset is written with a number of digits that depends on its own value, which can change the length of the header. Starting from an offset guess and recomputing until it is stable always terminates, since the length only ever grows with the number of digits and that number is bounded.
Usage
build.mrtrix.header.stable(header_id, entries, datatype, count)
Arguments
header_id |
character string, the file type identifier, one of 'mrtrix tracks' (TCK) or 'mrtrix track scalars' (TSF). |
entries |
named list of additional header entries. |
datatype |
character string, the datatype. |
count |
integer, the number of streamlines. |
Value
named list with entries text (the header) and offset.
Create new bvsmp instance encoding morph data for Brainvoyager.
Description
Create new bvsmp instance encoding morph data for Brainvoyager.
Usage
bvsmp(morph_data)
Arguments
morph_data |
numeric vector, the morphometry data to store in the bvsmp instance (one value per mesh vertex). |
Value
bvsmp instance, can be used to write Brainvoyager SMP format morphometry files using write.smp.brainvoyager. Modify as needed before writing.
Examples
morph_data <- rnorm(100L, 3.0, 1.0)
mybvsmp <- bvsmp(morph_data)
mybvsmp$smp_version
Create CDATA element string from string.
Description
Create CDATA element string from string.
Usage
cdata(string)
Arguments
string |
character string, the input string, freeform text. Must not contain the cdata start and end tags. |
Value
character string, the input wrapped in the cdata tags
Note
This returns a string, not an XML node. See xml_cdata if you want a node.
Check whether the dtype is suitable for the data.
Description
This function provides an educated guess on whether the given dtype is suitable for the data. It is usually called for the site effect of printing warnings in case something seems off.
Usage
check.dtype.for.data(mridata, mri_dtype_code)
Arguments
mridata |
the data to check, a vector, matrix or array typically |
mri_dtype_code |
integer, the MRI data type code. See |
Value
logical, whether the dtype could be suitable. This is only a guess, as the checks are in no way complete.
Check that a numeric vector or matrix contains only finite values.
Description
Stops with an error if the input contains NA, NaN,
or Inf values.
Usage
check_all_finite(x, label = "data")
Arguments
x |
a numeric vector or matrix. |
label |
character string, a human-readable label for the data (used in the error message). |
Value
TRUE (invisibly) if all values are finite. Stops otherwise.
Warn about common errors in combining data and datatype.
Description
Warn about common errors in combining data and datatype.
Usage
check_data_and_settings_consistency(
index,
data,
datatype,
intent,
force = FALSE
)
Arguments
index |
positive integer, the dataarray index to report. Makes it easier for the user to find the broken one. |
data |
vector or matrix, the data to write to the GIFTI file. Checked against the datatype. |
datatype |
NIFTI datatype string, the datatype to use when writing to the GIFTI file. Checked against the data. |
intent |
NIFTI intent string, checked independently. In no way do we check whether it makes sense for the data. |
Note
The checks in here are in no way exhaustive.
Check that a file is large enough to contain the expected data payload.
Description
Compares the expected data size against the file size on disk. Stops with an error if the file is too small (truncated or corrupt).
Usage
check_file_size(filepath, header_bytes, data_bytes)
Arguments
filepath |
character string, path to the file. |
header_bytes |
single numeric value, the number of bytes consumed by the file header (everything before the data payload). |
data_bytes |
single numeric value, the expected number of bytes in the data payload. |
Value
logical, TRUE (invisibly) if the file is large enough.
Stops with an error otherwise.
Accept the input forms of a set of annotations.
Description
Accept the input forms of a set of annotations.
Usage
cifti.annot.list(annots, structure = NULL)
Arguments
annots |
an |
structure |
character string or |
Value
a named list of fs.annot instances, named by canonical brain structure name.
Collect the vertices of each region of an annotation.
Description
Collect the vertices of each region of an annotation.
Usage
cifti.annot.parcels(annot, structure_name, default_label_name = "unknown")
Arguments
annot |
an |
structure_name |
character string, the brain structure of the annotation, used in error messages. |
default_label_name |
character string, the name for vertices without a region name. |
Value
a named list of integer vectors, one entry per region that contains at least one vertex: the 0-based vertex indices of the region, in ascending order. The entries are ordered like the label table of the annotation (the atlas order).
Create an array like the input, with a different first dimension.
Description
Create an array like the input, with a different first dimension.
Usage
cifti.array.with.new.first.dim(data, first_dim_size)
Arguments
data |
the array, its first dimension is the one that is replaced. |
first_dim_size |
integer, the size of the new first dimension. |
Value
an array of NA of the data type of data, with the new first
dimension and all other dimensions of data.
Assign rows of an array, reordered or repeated.
Description
Assign rows of an array, reordered or repeated.
Usage
cifti.assign.rows(target, to, from, data)
Arguments
target |
array, the array to write to. |
to |
integer vector, the row indices of |
from |
integer vector, the row indices of |
data |
array, the source array. |
Value
target with the requested rows assigned.
Group axes into MatrixIndicesMap elements.
Description
A CIFTI-2 file describes its matrix dimensions with MatrixIndicesMap
elements, and the format says that the same element must be used for both dimensions
when they describe the same thing. This is the case for connectome files (a .dconn
or .pconn has the same brainordinates or parcels in both dimensions), and Connectome
Workbench writes such a file with a single element that applies to both dimensions,
while nibabel writes one per dimension. The merged form is what this writer produces.
Usage
cifti.axes.to.maps(axes)
Arguments
axes |
list of axes, named by matrix dimension. |
Value
a list of lists with the entries 'axis' (the axis) and 'dims' (the matrix dimensions it describes).
Create a CIFTI-2 axis for brain models.
Description
A brain model axis describes which surface vertices and volume voxels a
matrix dimension of a CIFTI-2 file contains, in the order in which they appear in the
matrix. This is the mapping of a dense file (.dscalar, .dtseries, .dlabel,
.dconn), and of the files that mix dense and parcellated data.
The index ranges of the models are computed from the index lists, so the models cover the dimension without gaps, which the format requires. A structure may appear in several models (e.g. as a surface and as a volume part in a grayordinates file), and the order of the models is the order of the matrix indices.
Usage
cifti.axis.brain.models(models, surfaces = NULL, volume = NULL)
Arguments
models |
list of brain model entries, as created by
|
surfaces |
named integer vector or |
volume |
a volume, see |
Value
a named list with the entries 'type', 'brain_models', 'surfaces' and 'volumes',
an axis to be passed to cifti.header.from.axes or
write.cifti.
See Also
Other cifti functions:
cifti.axis.from.template(),
cifti.axis.labels(),
cifti.axis.parcels(),
cifti.axis.parcels.from.annot(),
cifti.axis.scalars(),
cifti.axis.series(),
cifti.brain.model.surface(),
cifti.brain.model.volume(),
cifti.dim.labels(),
cifti.file.type.for.axes(),
cifti.grayordinates(),
cifti.header.from.axes(),
cifti.label.table(),
cifti.parcel(),
cifti.parcels(),
cifti.series.info(),
cifti.structure.data(),
cifti.structures(),
cifti.volume(),
print.fs.cifti(),
print.fs.cifti.data(),
print.fs.connectome(),
read.cifti(),
read.cifti.header(),
read.cifti.rows(),
read.fs.connectome.cifti(),
write.cifti(),
write.fs.connectome.cifti(),
write.fs.morph.cifti(),
write.fs.parcellated.cifti(),
write.fs.parcellation.cifti(),
write.fs.series.cifti()
Examples
axis <- cifti.axis.brain.models(list(
cifti.brain.model.surface("lh", 10L),
cifti.brain.model.surface("rh", 12L)))
axis$type
Build the axis for a set of maps.
Description
Build the axis for a set of maps.
Usage
cifti.axis.for.maps(map_names, nx, template_map_axis = NULL)
Arguments
map_names |
character vector or |
nx |
integer, the number of maps in the data. |
template_map_axis |
the axis of the template file for this dimension, or |
Value
an axis, see cifti.axis.scalars.
Create a CIFTI-2 axis from a template file.
Description
Read the axes of an existing CIFTI-2 file, so that a new file can be written with the same mapping. This is the recommended way to write a file for real data: the mapping of an HCP grayordinates file (which vertices are in the file, and which volume voxels) can not be invented, it has to come from the file the data was derived from.
Usage
cifti.axis.from.template(x, dim = NULL)
Arguments
x |
character string (the path of a CIFTI-2 file), an |
dim |
integer or |
Value
the axis of the requested dimension (a named list, see
cifti.axis.brain.models), or a list of axes (one per dimension; note
that a file whose dimensions share a single XML mapping returns the same axis for
both, as two entries).
See Also
Other cifti functions:
cifti.axis.brain.models(),
cifti.axis.labels(),
cifti.axis.parcels(),
cifti.axis.parcels.from.annot(),
cifti.axis.scalars(),
cifti.axis.series(),
cifti.brain.model.surface(),
cifti.brain.model.volume(),
cifti.dim.labels(),
cifti.file.type.for.axes(),
cifti.grayordinates(),
cifti.header.from.axes(),
cifti.label.table(),
cifti.parcel(),
cifti.parcels(),
cifti.series.info(),
cifti.structure.data(),
cifti.structures(),
cifti.volume(),
print.fs.cifti(),
print.fs.cifti.data(),
print.fs.connectome(),
read.cifti(),
read.cifti.header(),
read.cifti.rows(),
read.fs.connectome.cifti(),
write.cifti(),
write.fs.connectome.cifti(),
write.fs.morph.cifti(),
write.fs.parcellated.cifti(),
write.fs.parcellation.cifti(),
write.fs.series.cifti()
Examples
cifti_file <- system.file("extdata", "cifti", "tiny.dscalar.nii", package = "freesurferformats")
axes <- cifti.axis.from.template(cifti_file)
length(axes)
axes[[2L]]$type
Create a CIFTI-2 axis for label maps.
Description
See cifti.axis.scalars; a labels axis is the same thing with
integer label keys instead of scalar values, and it stores the label table that
defines the keys.
Usage
cifti.axis.labels(names = NULL, label_tables = NULL, metadata = NULL)
Arguments
names |
character vector or |
label_tables |
list of label tables or |
metadata |
list of metadata lists or |
Value
a named list with the entries 'type' and 'named_maps', an axis to be passed to
cifti.header.from.axes or write.cifti.
See Also
Other cifti functions:
cifti.axis.brain.models(),
cifti.axis.from.template(),
cifti.axis.parcels(),
cifti.axis.parcels.from.annot(),
cifti.axis.scalars(),
cifti.axis.series(),
cifti.brain.model.surface(),
cifti.brain.model.volume(),
cifti.dim.labels(),
cifti.file.type.for.axes(),
cifti.grayordinates(),
cifti.header.from.axes(),
cifti.label.table(),
cifti.parcel(),
cifti.parcels(),
cifti.series.info(),
cifti.structure.data(),
cifti.structures(),
cifti.volume(),
print.fs.cifti(),
print.fs.cifti.data(),
print.fs.connectome(),
read.cifti(),
read.cifti.header(),
read.cifti.rows(),
read.fs.connectome.cifti(),
write.cifti(),
write.fs.connectome.cifti(),
write.fs.morph.cifti(),
write.fs.parcellated.cifti(),
write.fs.parcellation.cifti(),
write.fs.series.cifti()
Examples
label_table <- data.frame(key = 0:1, red = c(1, 0), green = c(1, 0.5), blue = c(1, 1),
alpha = c(0, 1), label = c("???", "PARCEL_A"))
axis <- cifti.axis.labels("parcellation", label_tables = list(label_table))
axis$named_maps[[1]]$labels$label
Create a CIFTI-2 axis for named maps (internal helper).
Description
Create a CIFTI-2 axis for named maps (internal helper).
Usage
cifti.axis.named.maps(names, metadata, label_tables, type)
Arguments
names |
character vector, the map names, or |
metadata |
list of metadata lists, or |
label_tables |
list of label tables, or |
type |
character string, 'CIFTI_INDEX_TYPE_SCALARS' or 'CIFTI_INDEX_TYPE_LABELS'. |
Value
a named list with the entries 'type' and 'named_maps'.
Create a CIFTI-2 axis for parcels.
Description
A parcel axis describes the parcels of a parcellated matrix dimension (the
mapping of .pscalar, .ptseries, .pconn and the second dimension of .pdconn).
As for brain models, the index of a parcel is its position in the list.
Usage
cifti.axis.parcels(parcels, surfaces = NULL, volume = NULL)
Arguments
parcels |
list of parcels, as created by |
surfaces |
named integer vector or |
volume |
a volume, see |
Value
a named list with the entries 'type', 'parcels', 'surfaces' and 'volumes', an
axis to be passed to cifti.header.from.axes or
write.cifti.
See Also
Other cifti functions:
cifti.axis.brain.models(),
cifti.axis.from.template(),
cifti.axis.labels(),
cifti.axis.parcels.from.annot(),
cifti.axis.scalars(),
cifti.axis.series(),
cifti.brain.model.surface(),
cifti.brain.model.volume(),
cifti.dim.labels(),
cifti.file.type.for.axes(),
cifti.grayordinates(),
cifti.header.from.axes(),
cifti.label.table(),
cifti.parcel(),
cifti.parcels(),
cifti.series.info(),
cifti.structure.data(),
cifti.structures(),
cifti.volume(),
print.fs.cifti(),
print.fs.cifti.data(),
print.fs.connectome(),
read.cifti(),
read.cifti.header(),
read.cifti.rows(),
read.fs.connectome.cifti(),
write.cifti(),
write.fs.connectome.cifti(),
write.fs.morph.cifti(),
write.fs.parcellated.cifti(),
write.fs.parcellation.cifti(),
write.fs.series.cifti()
Examples
axis <- cifti.axis.parcels(list(
cifti.parcel("PARCEL_A", list(CORTEX_LEFT = 0:2)),
cifti.parcel("PARCEL_B", list(CORTEX_LEFT = 3:5))))
length(axis$parcels)
Create a CIFTI-2 parcels axis from brain surface annotations.
Description
A parcellated CIFTI-2 file stores no label table, it describes each parcel
by its name and by the vertices (per brain structure) and volume voxels it contains.
This function builds such a parcels axis from brain surface annotations (see
read.fs.annot), which assign a region label to every vertex of a
hemisphere, so that data that was computed per region of an atlas (a FreeSurfer
parcellation, a Schaefer atlas, ...) can be written to a parcellated file.
The vertices of a parcel are collected by the name of the region, not by its label
key: the hemispheres of an atlas usually use the same names for the same region, but
the names often carry a hemisphere marker (e.g. L_superiorfrontal in one hemisphere
and R_superiorfrontal in the other, or 7Networks_LH_Vis_1 and
7Networks_RH_Vis_1), and a parcel of a parcellated CIFTI-2 file is a region that
spans the structures it occurs in. The markers are removed before the names are
compared, see cifti.region.name.without.hemisphere for the exact rules.
Vertices whose label is not in the label table of the annotation (the medial wall,
which is usually the 'unknown' region with key 0) form a parcel like any other, named
default_label_name: a parcellated file has no 'no value' case, and dropping the
medial wall silently would change the data.
Usage
cifti.axis.parcels.from.annot(
annots,
structure = NULL,
parcel_names = NULL,
default_label_name = "unknown"
)
Arguments
annots |
an |
structure |
character string or |
parcel_names |
character vector or |
default_label_name |
character string, the name to use for vertices whose label is not in the label table of the annotation. |
Value
an axis of type 'CIFTI_INDEX_TYPE_PARCELS', see
cifti.axis.parcels, to be passed to write.cifti or to one
of the writers that accept it (e.g. write.fs.parcellated.cifti).
See Also
Other cifti functions:
cifti.axis.brain.models(),
cifti.axis.from.template(),
cifti.axis.labels(),
cifti.axis.parcels(),
cifti.axis.scalars(),
cifti.axis.series(),
cifti.brain.model.surface(),
cifti.brain.model.volume(),
cifti.dim.labels(),
cifti.file.type.for.axes(),
cifti.grayordinates(),
cifti.header.from.axes(),
cifti.label.table(),
cifti.parcel(),
cifti.parcels(),
cifti.series.info(),
cifti.structure.data(),
cifti.structures(),
cifti.volume(),
print.fs.cifti(),
print.fs.cifti.data(),
print.fs.connectome(),
read.cifti(),
read.cifti.header(),
read.cifti.rows(),
read.fs.connectome.cifti(),
write.cifti(),
write.fs.connectome.cifti(),
write.fs.morph.cifti(),
write.fs.parcellated.cifti(),
write.fs.parcellation.cifti(),
write.fs.series.cifti()
Examples
lh_annot_file <- system.file("extdata", "lh.aparc.annot.gz", package = "freesurferformats")
lh_annot <- read.fs.annot(lh_annot_file)
axis <- cifti.axis.parcels.from.annot(lh_annot, structure = "lh")
length(axis$parcels)
axis$parcels[[1L]]$name
Create a CIFTI-2 axis for scalar or label maps.
Description
A scalars axis holds a set of maps (e.g. the myelin map and the cortical
thickness of a subject in one .dscalar file), a labels axis holds a set of label maps
(one per parcellation in a .dlabel file). Both are described by their map names; a
labels axis can additionally have a label table per map, which maps the integer label
keys in the data to names and colors.
Usage
cifti.axis.scalars(names = NULL, metadata = NULL)
Arguments
names |
character vector or |
metadata |
list of metadata lists or |
Value
a named list with the entries 'type' and 'named_maps', an axis to be passed to
cifti.header.from.axes or write.cifti.
See Also
Other cifti functions:
cifti.axis.brain.models(),
cifti.axis.from.template(),
cifti.axis.labels(),
cifti.axis.parcels(),
cifti.axis.parcels.from.annot(),
cifti.axis.series(),
cifti.brain.model.surface(),
cifti.brain.model.volume(),
cifti.dim.labels(),
cifti.file.type.for.axes(),
cifti.grayordinates(),
cifti.header.from.axes(),
cifti.label.table(),
cifti.parcel(),
cifti.parcels(),
cifti.series.info(),
cifti.structure.data(),
cifti.structures(),
cifti.volume(),
print.fs.cifti(),
print.fs.cifti.data(),
print.fs.connectome(),
read.cifti(),
read.cifti.header(),
read.cifti.rows(),
read.fs.connectome.cifti(),
write.cifti(),
write.fs.connectome.cifti(),
write.fs.morph.cifti(),
write.fs.parcellated.cifti(),
write.fs.parcellation.cifti(),
write.fs.series.cifti()
Examples
axis <- cifti.axis.scalars(c("thickness", "area"))
length(axis$named_maps)
Create a CIFTI-2 axis for a series.
Description
A series axis describes a dimension that holds an ordered sequence of
samples, usually the time points of a .dtseries or .ptseries file. The value of
series index i (0-based) is (start + i * step) * 10^exponent, in the unit that
unit names.
Usage
cifti.axis.series(
number_of_series_points,
start = 0,
step = 1,
exponent = 0L,
unit = "SECOND"
)
Arguments
number_of_series_points |
integer, the number of samples, which must match the size of that matrix dimension of the data. |
start |
numeric, the value of the first sample. |
step |
numeric, the difference between consecutive samples. |
exponent |
integer, the power of ten the values are in (e.g. -3 for milliseconds). |
unit |
character string, one of 'SECOND', 'HERTZ', 'METER' or 'RADIAN'. |
Value
a named list with the entries 'type' and 'series', an axis to be passed to
cifti.header.from.axes or write.cifti.
See Also
Other cifti functions:
cifti.axis.brain.models(),
cifti.axis.from.template(),
cifti.axis.labels(),
cifti.axis.parcels(),
cifti.axis.parcels.from.annot(),
cifti.axis.scalars(),
cifti.brain.model.surface(),
cifti.brain.model.volume(),
cifti.dim.labels(),
cifti.file.type.for.axes(),
cifti.grayordinates(),
cifti.header.from.axes(),
cifti.label.table(),
cifti.parcel(),
cifti.parcels(),
cifti.series.info(),
cifti.structure.data(),
cifti.structures(),
cifti.volume(),
print.fs.cifti(),
print.fs.cifti.data(),
print.fs.connectome(),
read.cifti(),
read.cifti.header(),
read.cifti.rows(),
read.fs.connectome.cifti(),
write.cifti(),
write.fs.connectome.cifti(),
write.fs.morph.cifti(),
write.fs.parcellated.cifti(),
write.fs.parcellation.cifti(),
write.fs.series.cifti()
Examples
axis <- cifti.axis.series(10L, start = 0, step = 0.72, unit = "SECOND")
axis$series$number_of_series_points
The number of matrix entries an axis covers.
Description
The number of matrix entries an axis covers.
Usage
cifti.axis.size(axis)
Arguments
axis |
an axis, see |
Value
integer, the size of that matrix dimension.
Get the surface sizes of an axis as a named vector.
Description
Get the surface sizes of an axis as a named vector.
Usage
cifti.axis.surface.sizes(axis)
Arguments
axis |
an axis of type 'CIFTI_INDEX_TYPE_BRAIN_MODELS'. |
Value
named integer vector or NULL, the number of vertices per structure, see
cifti.axis.brain.models.
Create the Surface elements of an axis.
Description
Create the Surface elements of an axis.
Usage
cifti.axis.surfaces(surfaces)
Arguments
surfaces |
named integer vector or |
Value
a list of lists with the entries 'brain_structure' and
'surface_number_of_vertices', or NULL.
Create a CIFTI-2 brain model entry for a surface.
Description
A surface brain model entry describes a set of surface vertices that one
matrix dimension of a CIFTI-2 file contains, e.g. one hemisphere. The vertex indices
are 0-based and refer to the vertices of the surface mesh that the file is defined
on. If they are NULL, the model covers all vertices of the surface, which is only
allowed if their number matches the size of the index range (the reader validates
this, and the writer computes the range from the index list).
Usage
cifti.brain.model.surface(
structure,
surface_number_of_vertices,
vertices = NULL
)
Arguments
structure |
character string, the brain structure, see
|
surface_number_of_vertices |
integer, the number of vertices of the complete surface (not the number of vertices in this model: a grayordinates file of the HCP leaves out the medial wall, so its models usually cover fewer vertices than the surface has). |
vertices |
integer vector or |
Value
a named list, one brain model entry, to be passed to
cifti.axis.brain.models.
See Also
Other cifti functions:
cifti.axis.brain.models(),
cifti.axis.from.template(),
cifti.axis.labels(),
cifti.axis.parcels(),
cifti.axis.parcels.from.annot(),
cifti.axis.scalars(),
cifti.axis.series(),
cifti.brain.model.volume(),
cifti.dim.labels(),
cifti.file.type.for.axes(),
cifti.grayordinates(),
cifti.header.from.axes(),
cifti.label.table(),
cifti.parcel(),
cifti.parcels(),
cifti.series.info(),
cifti.structure.data(),
cifti.structures(),
cifti.volume(),
print.fs.cifti(),
print.fs.cifti.data(),
print.fs.connectome(),
read.cifti(),
read.cifti.header(),
read.cifti.rows(),
read.fs.connectome.cifti(),
write.cifti(),
write.fs.connectome.cifti(),
write.fs.morph.cifti(),
write.fs.parcellated.cifti(),
write.fs.parcellation.cifti(),
write.fs.series.cifti()
Examples
model <- cifti.brain.model.surface("lh", 10L, vertices = 0:4)
model$index_count
Create a CIFTI-2 brain model entry for volume voxels.
Description
A volume brain model entry describes the voxels of one subcortical
structure, as 0-based IJK indices into the voxel grid of the volume that is part of
the same axis (see cifti.volume). If the indices are NULL, the model
covers all voxels of that grid.
Usage
cifti.brain.model.volume(structure, voxel_indices_ijk = NULL)
Arguments
structure |
character string, the brain structure, see
|
voxel_indices_ijk |
n x 3 integer matrix or |
Value
a named list, one brain model entry, to be passed to
cifti.axis.brain.models.
See Also
Other cifti functions:
cifti.axis.brain.models(),
cifti.axis.from.template(),
cifti.axis.labels(),
cifti.axis.parcels(),
cifti.axis.parcels.from.annot(),
cifti.axis.scalars(),
cifti.axis.series(),
cifti.brain.model.surface(),
cifti.dim.labels(),
cifti.file.type.for.axes(),
cifti.grayordinates(),
cifti.header.from.axes(),
cifti.label.table(),
cifti.parcel(),
cifti.parcels(),
cifti.series.info(),
cifti.structure.data(),
cifti.structures(),
cifti.volume(),
print.fs.cifti(),
print.fs.cifti.data(),
print.fs.connectome(),
read.cifti(),
read.cifti.header(),
read.cifti.rows(),
read.fs.connectome.cifti(),
write.cifti(),
write.fs.connectome.cifti(),
write.fs.morph.cifti(),
write.fs.parcellated.cifti(),
write.fs.parcellation.cifti(),
write.fs.series.cifti()
Examples
voxels <- matrix(c(0L, 0L, 2L, 1L, 0L, 2L), ncol = 3L, byrow = TRUE)
model <- cifti.brain.model.volume("CEREBELLUM", voxels)
model$index_count
Get the brainordinate dimension of a CIFTI-2 file.
Description
Find the matrix dimension of a CIFTI-2 file that holds the brain
structures. Most files have exactly one (dimension 1 for a .dscalar,
.dtseries or .dlabel, dimension 0 for the special case of a
.dpconn-style file), while connectome files like a .dconn have brain
models in both dimensions.
Usage
cifti.brainordinate.dim(cii)
Arguments
cii |
an |
Value
integer, the dimension. Stops with a descriptive error if there is no brainordinate dimension or if there are two.
Get all matrix dimensions of a CIFTI-2 file that hold brain models.
Description
A single MatrixIndicesMap element can apply to both matrix
dimensions (this is the case for connectome files like .dconn and
.pconn), so the dimensions have to be counted, not the mapping elements.
Usage
cifti.brainordinate.dims(cii)
Arguments
cii |
an |
Value
integer vector, the dimensions that contain brain models (usually one,
two for a file like .dconn).
Check a list of axes and name the dimensions.
Description
Check a list of axes and name the dimensions.
Usage
cifti.check.axes(axes)
Arguments
axes |
list of axes, see |
Value
the list, with the axes named by their matrix dimension.
Check and prepare the data for a set of axes.
Description
Check and prepare the data for a set of axes.
Usage
cifti.check.data.for.axes(data, axes)
Arguments
data |
the data, see |
axes |
list of axes, see |
Value
the data as an array with the dimensions of the axes.
Check a vector of 0-based indices.
Description
Check a vector of 0-based indices.
Usage
cifti.check.index.list(indices, what, max_index = NULL)
Arguments
indices |
integer vector, the indices. |
what |
character string, a description of the indices, used in error messages. |
max_index |
integer or |
Value
the indices as an integer vector.
Check a matrix index selection.
Description
Check a matrix index selection.
Usage
cifti.check.index.selection(selection, max_index, what, filepath)
Arguments
selection |
integer vector or |
max_index |
integer, the size of the matrix dimension. |
what |
character string, the name of the selection ('rows' or 'columns'), used in the error message. |
filepath |
character string, the path of the file, used in the error message. |
Value
the selection as an integer vector, or NULL.
Check a label table for writing.
Description
Check a label table for writing.
Usage
cifti.check.label.table(label_table, map_idx)
Arguments
label_table |
a data.frame, see |
map_idx |
integer, the number of the map, used in the error message. |
Value
the label table, or NULL.
Check that an object is an fs.cifti instance.
Description
Check that an object is an fs.cifti instance.
Usage
cifti.check.object(cii)
Arguments
cii |
the object to check. |
Value
the object, invisibly.
Compute the index ranges of brain model entries.
Description
The IndexOffset and IndexCount fields of a brain model entry say which
matrix entries it covers. They are derived from the index lists (and from the surface
sizes or the volume for a model that covers everything), and they have to cover the
dimension without gaps, so they are always computed here rather than taken from the
caller.
Usage
cifti.compute.index.ranges(models, volume = NULL)
Arguments
models |
list of brain model entries, see |
volume |
a volume or |
Value
the models, with index_offset and index_count set.
Determine the two axes of a connectome file.
Description
Determine the two axes of a connectome file.
Usage
cifti.connectome.axes(axes, template_cii = NULL)
Arguments
axes |
list of one or two axes or |
template_cii |
an |
Value
a list of two axes, named by matrix dimension.
Assemble the data values of all vertices for a file without a template.
Description
Assemble the data values of all vertices for a file without a template.
Usage
cifti.data.for.all.vertices(data, structures, what = "data")
Arguments
data |
the data, see |
structures |
character vector, the canonical structure names, in file order. |
what |
character string, a description of the data, used in error messages. |
Value
a matrix with one row per vertex (structures one after the other) and one column per map.
Accept the input forms of a CIFTI-2 connectome.
Description
Accept the input forms of a CIFTI-2 connectome.
Usage
cifti.data.for.connectome(filepath, rows = NULL, columns = NULL)
Arguments
filepath |
character string, |
rows |
integer vector or |
columns |
integer vector or |
Value
an fs.cifti.data object, see read.cifti.
Select the data values of the grayordinates of a file.
Description
Select the data values of the grayordinates of a file.
Usage
cifti.data.for.grayordinates(data, structures, index_table, what)
Arguments
data |
the data, see |
structures |
character vector, the canonical structure names, in file order. |
index_table |
the brainordinate table, see |
what |
character string, a description of the data, used in error messages. |
Value
a matrix with one row per grayordinate (in file order) and one column per map.
Accept the input forms of a CIFTI-2 data object.
Description
Accept the input forms of a CIFTI-2 data object.
Usage
cifti.data.object(x)
Arguments
x |
an |
Value
an fs.cifti.data object, see read.cifti.
Get the per-structure data of one structure.
Description
Get the per-structure data of one structure.
Usage
cifti.data.per.structure(data, structure_name, what)
Arguments
data |
the data, see |
structure_name |
character string, the canonical structure name. |
what |
character string, a description of the data, used in error messages. |
Value
a matrix with one row per vertex of the complete surface and one column per map.
Determine the structures of per-vertex data.
Description
Determine the structures of per-vertex data.
Usage
cifti.data.structures(data, structure = NULL)
Arguments
data |
the data, see |
structure |
character string or |
Value
character vector of canonical structure names, or NULL if the data are not a
named list and no structure was given.
The number of vertices of the surface of one structure.
Description
The number of vertices of the surface of one structure.
Usage
cifti.data.surface.size(data, structure_name)
Arguments
data |
the data, see |
structure_name |
character string, the canonical structure name. |
Value
integer, the number of vertices.
Get the dense data matrix of one structure for the user-facing readers.
Description
Workhorse of read.fs.morph.cifti and friends: like
cifti.structure.data, but requires the structure to have a
surface part and returns the per-vertex matrix directly. This keeps the
user-facing functions working for the structures they support today, and
turns the unsupported ones into a descriptive error.
Usage
cifti.dense.structure.matrix(x, structure)
Arguments
x |
an |
structure |
character string, the canonical name of the brain structure. |
Value
a numeric matrix, one row per surface vertex, one column per index of the other matrix dimension.
Get axis labels for a matrix dimension of a CIFTI-2 file.
Description
Get a label for each index of one matrix dimension of a CIFTI-2
file, e.g. the map names of a .dscalar, the parcel names of a .pconn or
identifiers for the grayordinates of a dense file. This is what
read.cifti uses to name the dimensions of the data array.
Usage
cifti.dim.labels(cii, dim = 0L)
Arguments
cii |
an |
dim |
integer, the matrix dimension to get the brain models for. CIFTI-2
files have two dimensions, so this is usually 0 (Workbench calls it the ROW
dimension) or 1 (the COLUMN dimension). See
|
Value
character vector of length cii$matrix$dim_sizes[dim + 1], the labels,
or NULL if no labels are known for this kind of dimension.
See Also
Other cifti functions:
cifti.axis.brain.models(),
cifti.axis.from.template(),
cifti.axis.labels(),
cifti.axis.parcels(),
cifti.axis.parcels.from.annot(),
cifti.axis.scalars(),
cifti.axis.series(),
cifti.brain.model.surface(),
cifti.brain.model.volume(),
cifti.file.type.for.axes(),
cifti.grayordinates(),
cifti.header.from.axes(),
cifti.label.table(),
cifti.parcel(),
cifti.parcels(),
cifti.series.info(),
cifti.structure.data(),
cifti.structures(),
cifti.volume(),
print.fs.cifti(),
print.fs.cifti.data(),
print.fs.connectome(),
read.cifti(),
read.cifti.header(),
read.cifti.rows(),
read.fs.connectome.cifti(),
write.cifti(),
write.fs.connectome.cifti(),
write.fs.morph.cifti(),
write.fs.parcellated.cifti(),
write.fs.parcellation.cifti(),
write.fs.series.cifti()
Examples
cifti_file <- system.file("extdata", "cifti", "tiny.ptseries.nii", package = "freesurferformats")
cii <- read.cifti.header(cifti_file)
cifti.dim.labels(cii, dim = 1L)
Move one dimension of an array to the front.
Description
Move one dimension of an array to the front.
Usage
cifti.dim.to.front(data, dim)
Arguments
data |
the array. |
dim |
integer, the dimension to move, counted from 0 (CIFTI style). |
Value
the array with the requested dimension first, and all other dimensions in their original order.
Check whether a file looks like a CIFTI-1 file.
Description
This is a heuristic used to produce a helpful error message when a CIFTI-1 file is passed to the reader: CIFTI-1 files are NIFTI-1 files (not NIFTI-2), and this function searches the first bytes of the file for the string 'CIFTI'. It is not used for any other purpose.
Usage
cifti.file.looks.like.cifti1(filepath)
Arguments
filepath |
character string, the path to a CIFTI-2 file (usually one of
|
Value
logical, whether the file looks like a CIFTI-1 file.
Check whether a file is a CIFTI-2 file (internal helper).
Description
Cheap and silent check whether a file is a CIFTI-2 file, i.e. a NIFTI v2
file with a header extension of code 32, the extension that holds the CIFTI XML
metadata. The format dispatchers (read.fs.morph(), read.fs.volume()) use it to
give a helpful error: the payload of a CIFTI-2 file is a matrix whose dimensions the
XML describes, not a volume or a per-vertex vector, so reading it with the NIFTI
reader silently returns values in an order that means nothing.
Usage
cifti.file.looks.like.cifti2(filepath)
Arguments
filepath |
character string, the path to a CIFTI-2 file (usually one of
|
Value
logical, whether the file is a CIFTI-2 file. A file that does not exist or
cannot be parsed is reported as FALSE.
Get the standard CIFTI-2 file type for a set of axes.
Description
Look up the file type that the format defines for the combination of matrix
index types of the axes, see cifti.file.types.
Usage
cifti.file.type.for.axes(axes)
Arguments
axes |
list of axes, see |
Value
a one row data.frame, see cifti.file.types, or a row with
intent_code = 3000 ('ConnUnknown') and empty file name extension for a combination
that the standard does not define.
See Also
Other cifti functions:
cifti.axis.brain.models(),
cifti.axis.from.template(),
cifti.axis.labels(),
cifti.axis.parcels(),
cifti.axis.parcels.from.annot(),
cifti.axis.scalars(),
cifti.axis.series(),
cifti.brain.model.surface(),
cifti.brain.model.volume(),
cifti.dim.labels(),
cifti.grayordinates(),
cifti.header.from.axes(),
cifti.label.table(),
cifti.parcel(),
cifti.parcels(),
cifti.series.info(),
cifti.structure.data(),
cifti.structures(),
cifti.volume(),
print.fs.cifti(),
print.fs.cifti.data(),
print.fs.connectome(),
read.cifti(),
read.cifti.header(),
read.cifti.rows(),
read.fs.connectome.cifti(),
write.cifti(),
write.fs.connectome.cifti(),
write.fs.morph.cifti(),
write.fs.parcellated.cifti(),
write.fs.parcellation.cifti(),
write.fs.series.cifti()
Examples
axis_brain <- cifti.axis.brain.models(list(cifti.brain.model.surface("lh", 10L)))
type <- cifti.file.type.for.axes(list(cifti.axis.scalars("m"), axis_brain))
type$extension
The CIFTI-2 file type a file name names.
Description
The CIFTI-2 file type a file name names.
Usage
cifti.file.type.for.extension(filepath)
Arguments
filepath |
character string, a file name. |
Value
character string, the standard file name extension the name ends with (e.g. '.pscalar.nii'), or the empty string if it does not end with one of them.
The standard CIFTI-2 file types.
Description
The nine standard CIFTI-2 file types, as defined by the format: which matrix index types the two matrix dimensions must have, the file name extension, and the NIFTI intent code and name that identify the type in the file header. The extension of a file decides which entry is used when writing, and a mismatch between the file name and the axes of the data is an error.
Usage
cifti.file.types()
Value
a data.frame with one row per file type and the columns 'extension', 'intent_code', 'intent_name', 'dim0_type' and 'dim1_type'.
Get the brainordinate table of a CIFTI-2 file.
Description
Get the mapping from the matrix indices of one dimension to the
individual surface vertices and volume voxels a CIFTI-2 file contains. This
is the per-index version of the table returned by
cifti.structures, which reports index ranges instead of single
indices. It is useful to find out which vertex or voxel a data row belongs
to, or to find the data index of a vertex or voxel.
Note that the same vertex or voxel can only appear once per dimension (the matrix has one entry per brainordinate), but a structure can be split over several brain model entries, and the vertices of a grayordinates file are a subset of the vertices of the surface it refers to.
Usage
cifti.grayordinates(cii, dim = 0L)
Arguments
cii |
an |
dim |
integer, the matrix dimension to get the brain models for. CIFTI-2
files have two dimensions, so this is usually 0 (Workbench calls it the ROW
dimension) or 1 (the COLUMN dimension). See
|
Value
a data.frame with one row per index of the matrix dimension and the
columns 'index' (integer, 0-based matrix index), 'structure' (character
string, the brain structure as spelled in the file), 'structure_short'
(without the CIFTI_STRUCTURE_ prefix), 'model_type' ('SURFACE' or
'VOXELS'), 'vertex_index' (integer, 0-based index of the vertex in the
surface for surface models, NA for volume models) and 'i', 'j', 'k'
(integer, 0-based voxel indices for volume models, NA for surface models).
See Also
Other cifti functions:
cifti.axis.brain.models(),
cifti.axis.from.template(),
cifti.axis.labels(),
cifti.axis.parcels(),
cifti.axis.parcels.from.annot(),
cifti.axis.scalars(),
cifti.axis.series(),
cifti.brain.model.surface(),
cifti.brain.model.volume(),
cifti.dim.labels(),
cifti.file.type.for.axes(),
cifti.header.from.axes(),
cifti.label.table(),
cifti.parcel(),
cifti.parcels(),
cifti.series.info(),
cifti.structure.data(),
cifti.structures(),
cifti.volume(),
print.fs.cifti(),
print.fs.cifti.data(),
print.fs.connectome(),
read.cifti(),
read.cifti.header(),
read.cifti.rows(),
read.fs.connectome.cifti(),
write.cifti(),
write.fs.connectome.cifti(),
write.fs.morph.cifti(),
write.fs.parcellated.cifti(),
write.fs.parcellation.cifti(),
write.fs.series.cifti()
Examples
cifti_file <- system.file("extdata", "cifti", "tiny.dscalar.nii", package = "freesurferformats")
cii <- read.cifti.header(cifti_file)
grayordinates <- cifti.grayordinates(cii, dim = 1L)
head(grayordinates)
Build the brainordinate table of an axis.
Description
Build the brainordinate table of an axis.
Usage
cifti.grayordinates.for.axes(axis)
Arguments
axis |
an axis of type 'CIFTI_INDEX_TYPE_BRAIN_MODELS'. |
Value
a data.frame, see cifti.grayordinates.
Expand one brain model entry into a brainordinate table.
Description
Expand one brain model entry into a brainordinate table.
Usage
cifti.grayordinates.for.model(map, model)
Arguments
map |
the indices map the brain model belongs to, see
|
model |
one brain model entry of the map. |
Value
a data.frame, see cifti.grayordinates.
Create the CIFTI-2 XML metadata for a set of axes.
Description
Build the CIFTI-2 XML document (the part of a CIFTI-2 file that describes
what the data matrix contains) from a set of axes. This is the inverse of the XML
parsing that read.cifti.header performs: pass the result of this
function to cifti.parse.xml or to read.cifti.header (after
storing it in a file) and you get back the axes you put in.
Usage
cifti.header.from.axes(axes, metadata = NULL)
Arguments
axes |
list of axes, one per matrix dimension, as created by the
|
metadata |
named character vector or named list or |
Value
character string, the CIFTI-2 XML document.
See Also
Other cifti functions:
cifti.axis.brain.models(),
cifti.axis.from.template(),
cifti.axis.labels(),
cifti.axis.parcels(),
cifti.axis.parcels.from.annot(),
cifti.axis.scalars(),
cifti.axis.series(),
cifti.brain.model.surface(),
cifti.brain.model.volume(),
cifti.dim.labels(),
cifti.file.type.for.axes(),
cifti.grayordinates(),
cifti.label.table(),
cifti.parcel(),
cifti.parcels(),
cifti.series.info(),
cifti.structure.data(),
cifti.structures(),
cifti.volume(),
print.fs.cifti(),
print.fs.cifti.data(),
print.fs.connectome(),
read.cifti(),
read.cifti.header(),
read.cifti.rows(),
read.fs.connectome.cifti(),
write.cifti(),
write.fs.connectome.cifti(),
write.fs.morph.cifti(),
write.fs.parcellated.cifti(),
write.fs.parcellation.cifti(),
write.fs.series.cifti()
Examples
axis_series <- cifti.axis.series(4L, start = 0, step = 2.5)
axis_brain <- cifti.axis.brain.models(list(
cifti.brain.model.surface("lh", 10L),
cifti.brain.model.surface("rh", 12L)))
xml <- cifti.header.from.axes(list(axis_series, axis_brain))
cat(substr(xml, 1, 200))
Accept the input forms of a CIFTI-2 header.
Description
Accept the input forms of a CIFTI-2 header.
Usage
cifti.header.of(x)
Arguments
x |
character string (a file path), an |
Value
an fs.cifti object, see read.cifti.header.
The short name of a CIFTI-2 matrix index type.
Description
The short name of a CIFTI-2 matrix index type.
Usage
cifti.index.type.short(type)
Arguments
type |
character string, a CIFTI-2 matrix index type, see
|
Value
character string, the type without the prefix, e.g. 'BRAIN_MODELS'.
The CIFTI-2 index types (mapping types).
Description
The CIFTI-2 index types (mapping types).
Usage
cifti.index.types()
Check whether an axis describes a connectome dimension.
Description
Check whether an axis describes a connectome dimension.
Usage
cifti.is.connectome.axis(axis)
Arguments
axis |
an axis, see |
Value
logical, whether the axis holds brainordinates or parcels.
Get a label table from a CIFTI-2 label file.
Description
Get the label table of one label map (a .dlabel file can
contain several maps). The label table maps integer label keys to names and
RGBA colors, and is the CIFTI analogue of a FreeSurfer color lookup table.
Usage
cifti.label.table(cii, dim = 0L, map = 1L)
Arguments
cii |
an |
dim |
integer, the matrix dimension to get the brain models for. CIFTI-2
files have two dimensions, so this is usually 0 (Workbench calls it the ROW
dimension) or 1 (the COLUMN dimension). See
|
map |
integer, the number of the label map to get the label table for
(1-based). A CIFTI label file can contain several maps, use
|
Value
a data.frame with one row per label and the columns 'key' (integer,
the label key used in the data), 'red', 'green', 'blue', 'alpha' (numeric,
in range 0 to 1) and 'label' (character string, the label name), plus 'x',
'y', 'z' (numeric, the optional label coordinates; NA if not present in
the file). Returns NULL if the specified matrix dimension does not contain
label maps, or if the specified map has no label table.
See Also
Other cifti functions:
cifti.axis.brain.models(),
cifti.axis.from.template(),
cifti.axis.labels(),
cifti.axis.parcels(),
cifti.axis.parcels.from.annot(),
cifti.axis.scalars(),
cifti.axis.series(),
cifti.brain.model.surface(),
cifti.brain.model.volume(),
cifti.dim.labels(),
cifti.file.type.for.axes(),
cifti.grayordinates(),
cifti.header.from.axes(),
cifti.parcel(),
cifti.parcels(),
cifti.series.info(),
cifti.structure.data(),
cifti.structures(),
cifti.volume(),
print.fs.cifti(),
print.fs.cifti.data(),
print.fs.connectome(),
read.cifti(),
read.cifti.header(),
read.cifti.rows(),
read.fs.connectome.cifti(),
write.cifti(),
write.fs.connectome.cifti(),
write.fs.morph.cifti(),
write.fs.parcellated.cifti(),
write.fs.parcellation.cifti(),
write.fs.series.cifti()
Examples
cifti_file <- system.file("extdata", "cifti", "tiny.dlabel.nii", package = "freesurferformats")
cii <- read.cifti.header(cifti_file)
cifti.label.table(cii, dim = 0L, map = 1L)
Convert a label table to the format the writer expects.
Description
Convert a label table to the format the writer expects.
Usage
cifti.label.table.for.writing(label_table)
Arguments
label_table |
a data.frame, see |
Value
a data.frame with the columns 'key', 'red', 'green', 'blue', 'alpha' and
'label', or NULL.
Get the CIFTI indices map for a matrix dimension.
Description
Get the single MatrixIndicesMap (mapping) that describes the
given matrix dimension. A CIFTI-2 file can have several mappings, and one
mapping can apply to several dimensions (this is the case for connectome
files like .dconn and .pconn).
Usage
cifti.map.for.dim(cii, dim)
Arguments
cii |
an |
dim |
integer, the matrix dimension to get the brain models for. CIFTI-2
files have two dimensions, so this is usually 0 (Workbench calls it the ROW
dimension) or 1 (the COLUMN dimension). See
|
Value
the indices map, a named list, see read.cifti.header.
Get the name of one named map of a CIFTI-2 file.
Description
Get the name of one named map of a CIFTI-2 file.
Usage
cifti.map.name(cii, dim, map = 1L)
Arguments
cii |
an |
dim |
integer, the matrix dimension that holds the named maps. |
map |
integer, the number of the map (1-based). |
Value
character string, the map name, or NULL if the map is unnamed.
Describe a CIFTI-2 index type for humans.
Description
Describe a CIFTI-2 index type for humans.
Usage
cifti.map.type.description(type)
Arguments
type |
character string, a CIFTI-2 index type, see |
Value
character string, a short description.
Determine the sizes of the CIFTI matrix dimensions.
Description
The CIFTI-2 matrix dimensions 0, 1, ... are stored in the
dim field of the NIFTI-2 header, starting at its 6th entry (R index
vectors are 1-based, so matrix dimension 0 is entry 6). The dimension order
in the XML refers to matrix dimensions, so a MatrixIndicesMap with
AppliesToMatrixDimension="0" describes the 6th entry of dim.
Usage
cifti.matrix.dim.sizes(niiheader, filepath = "")
Arguments
niiheader |
the NIFTI-2 header of the file, required to determine the sizes of the matrix dimensions. |
filepath |
character string, the path of the file the XML was read from. Only used in error messages. |
Value
integer vector, the sizes of the matrix dimensions.
Merge explicitly given axes with the axes of a template.
Description
Merge explicitly given axes with the axes of a template.
Usage
cifti.merge.axes(axes, template_cii)
Arguments
axes |
list of axes or |
template_cii |
an |
Value
the merged list of axes, named by matrix dimension.
The CIFTI-2 brain model types.
Description
The CIFTI-2 brain model types.
Usage
cifti.model.types()
Build the NIFTI-2 header of a CIFTI-2 file.
Description
CIFTI-2 files are NIFTI-2 files whose header has a fixed shape: the matrix
dimensions are stored in the dim field (dimension 0 in dim[5], dimension 1 in
dim[6], which is why dim[0] is 6 for a two-dimensional matrix), the intent code
names the file type, the voxel sizes, the scaling and the geometry fields are unused
(the geometry of a CIFTI-2 file is in its XML), and the data start after the header
extension that holds the XML.
Usage
cifti.nifti.header.for.axes(axes, intent_code, intent_name)
Arguments
axes |
list of axes, see |
intent_code |
integer, the NIFTI intent code of the file type, see
|
intent_name |
character string, the NIFTI intent name of the file type. |
Value
a named list, a NIFTI-2 header as returned by read.nifti2.header.
Get the other matrix dimension of a 2-dimensional CIFTI-2 matrix.
Description
Get the other matrix dimension of a 2-dimensional CIFTI-2 matrix.
Usage
cifti.other.dim(cii, dim)
Arguments
cii |
an |
dim |
integer, the matrix dimension to exclude. |
Value
integer, the other matrix dimension. Stops for files with more than two matrix dimensions.
Create a CIFTI-2 parcel.
Description
Create one parcel, i.e. a named set of surface vertices (per structure) and volume voxels. The name is the only label a parcellated file has: the position in the list of parcels is the parcel index, and the reader returns the names.
Usage
cifti.parcel(name, vertices = NULL, voxel_indices_ijk = NULL)
Arguments
name |
character string, the parcel name. |
vertices |
named list or |
voxel_indices_ijk |
n x 3 integer matrix or |
Value
a named list, one parcel, to be passed to cifti.axis.parcels.
See Also
Other cifti functions:
cifti.axis.brain.models(),
cifti.axis.from.template(),
cifti.axis.labels(),
cifti.axis.parcels(),
cifti.axis.parcels.from.annot(),
cifti.axis.scalars(),
cifti.axis.series(),
cifti.brain.model.surface(),
cifti.brain.model.volume(),
cifti.dim.labels(),
cifti.file.type.for.axes(),
cifti.grayordinates(),
cifti.header.from.axes(),
cifti.label.table(),
cifti.parcels(),
cifti.series.info(),
cifti.structure.data(),
cifti.structures(),
cifti.volume(),
print.fs.cifti(),
print.fs.cifti.data(),
print.fs.connectome(),
read.cifti(),
read.cifti.header(),
read.cifti.rows(),
read.fs.connectome.cifti(),
write.cifti(),
write.fs.connectome.cifti(),
write.fs.morph.cifti(),
write.fs.parcellated.cifti(),
write.fs.parcellation.cifti(),
write.fs.series.cifti()
Examples
parcel <- cifti.parcel("PARCEL_A", list(CORTEX_LEFT = 0:2, CORTEX_RIGHT = 4:5))
parcel$name
Get the parcel table of a CIFTI-2 file.
Description
Get the parcels for one matrix dimension of a parcellated
CIFTI-2 file. A parcel is a named set of surface vertices and/or volume
voxels; its index is its position in the list (CIFTI-2 parcels have no index
attribute). The vertex lists themselves are in the field 'vertices' of the
fs.cifti object, see read.cifti.header.
Usage
cifti.parcels(cii, dim = 0L)
Arguments
cii |
an |
dim |
integer, the matrix dimension to get the brain models for. CIFTI-2
files have two dimensions, so this is usually 0 (Workbench calls it the ROW
dimension) or 1 (the COLUMN dimension). See
|
Value
a data.frame with one row per parcel and the columns 'index' (integer, 0-based parcel index), 'name' (character string, the parcel name), 'num_vertices' (integer, the total number of surface vertices in this parcel) and 'num_voxels' (integer, the number of volume voxels in this parcel). The result is ordered by parcel index.
See Also
Other cifti functions:
cifti.axis.brain.models(),
cifti.axis.from.template(),
cifti.axis.labels(),
cifti.axis.parcels(),
cifti.axis.parcels.from.annot(),
cifti.axis.scalars(),
cifti.axis.series(),
cifti.brain.model.surface(),
cifti.brain.model.volume(),
cifti.dim.labels(),
cifti.file.type.for.axes(),
cifti.grayordinates(),
cifti.header.from.axes(),
cifti.label.table(),
cifti.parcel(),
cifti.series.info(),
cifti.structure.data(),
cifti.structures(),
cifti.volume(),
print.fs.cifti(),
print.fs.cifti.data(),
print.fs.connectome(),
read.cifti(),
read.cifti.header(),
read.cifti.rows(),
read.fs.connectome.cifti(),
write.cifti(),
write.fs.connectome.cifti(),
write.fs.morph.cifti(),
write.fs.parcellated.cifti(),
write.fs.parcellation.cifti(),
write.fs.series.cifti()
Examples
cifti_file <- system.file("extdata", "cifti", "tiny.ptseries.nii", package = "freesurferformats")
cii <- read.cifti.header(cifti_file)
cifti.parcels(cii, dim = 1L)
Get the parcels axis of a template file.
Description
Get the parcels axis of a template file.
Usage
cifti.parcels.axis.of(template_cii)
Arguments
template_cii |
an |
Value
the parcels axis of the file, see cifti.axis.parcels.
Read and validate an attribute value of an XML node.
Description
Read and validate an attribute value of an XML node.
Usage
cifti.parse.attr(node, attr_name, required = FALSE, context = "")
Arguments
node |
an xml2 node. |
attr_name |
character string, the name of the attribute. |
required |
logical, whether the attribute must be present. |
context |
character string, used in the error message. |
Value
character string, or NA_character_ if the attribute is absent and
not required.
Parse the BrainModel elements of a MatrixIndicesMap element.
Description
Parse the BrainModel elements of a MatrixIndicesMap element.
Usage
cifti.parse.brain.models(node, filepath = "")
Arguments
node |
an xml2 node, the |
filepath |
character string, the path of the file the XML was read from. Only used in error messages. |
Value
a list of lists, or NULL if there are no BrainModel elements.
Parse a required or optional child element holding integer values.
Description
Parse a required or optional child element holding integer values.
Usage
cifti.parse.child.int.vector(node, child_name, filepath = "")
Arguments
node |
an xml2 node, the parent element. |
child_name |
character string, the name of the child element. |
filepath |
character string, the path of the file the XML was read from. Only used in error messages. |
Value
integer vector, or NULL if the child element is missing or empty.
Parse the optionally present VoxelIndicesIJK child element as a matrix.
Description
Parse the optionally present VoxelIndicesIJK child element as a matrix.
Usage
cifti.parse.child.voxel.indices(node, filepath = "")
Arguments
node |
an xml2 node, the parent element. |
filepath |
character string, the path of the file the XML was read from. Only used in error messages. |
Value
an n x 3 integer matrix of 0-based voxel indices, or NULL if the
child element is missing or empty.
Parse one MatrixIndicesMap element.
Description
Parse one MatrixIndicesMap element.
Usage
cifti.parse.indices.map(node, dim_sizes, filepath = "")
Arguments
node |
an xml2 node, the |
filepath |
character string, the path of the file the XML was read from. Only used in error messages. |
Value
a named list, see read.cifti.header.
Parse a whitespace-separated list of integers from XML text content.
Description
Parse a whitespace-separated list of integers from XML text content.
Usage
cifti.parse.int.vector(text, what = "an element", context = "")
Arguments
text |
character string, the text content of an XML element. |
what |
character string, the element/attribute name, used in error messages. |
context |
character string, additional context for error messages. |
Value
integer vector. Empty integer vector for empty input.
Parse a CIFTI LabelTable element.
Description
Parse a CIFTI LabelTable element.
Usage
cifti.parse.label.table(node)
Arguments
node |
an xml2 node, the |
Value
a data.frame with the columns 'key', 'red', 'green', 'blue', 'alpha',
'label', 'x', 'y' and 'z', or NULL if the node is missing.
Parse the MetaData element of a CIFTI XML node.
Description
Parse the MetaData element of a CIFTI XML node.
Usage
cifti.parse.metadata(node)
Arguments
node |
an xml2 node that may contain a |
Value
a named list of character strings, the metadata entries in file order. Empty list if the node has no metadata.
Parse the NamedMap elements of a MatrixIndicesMap element.
Description
Parse the NamedMap elements of a MatrixIndicesMap element.
Usage
cifti.parse.named.maps(node, filepath = "")
Arguments
node |
an xml2 node, the |
filepath |
character string, the path of the file the XML was read from. Only used in error messages. |
Value
a list of lists with the entries 'name', 'metadata' and 'labels', or
NULL if there are no NamedMap elements.
Parse a whitespace-separated list of numbers from XML text content.
Description
Parse a whitespace-separated list of numbers from XML text content.
Usage
cifti.parse.numeric.vector(text, what = "an element", context = "")
Arguments
text |
character string, the text content of an XML element. |
what |
character string, the element/attribute name, used in error messages. |
context |
character string, additional context for error messages. |
Value
numeric vector. Empty numeric vector for empty input.
Parse the Parcel elements of a MatrixIndicesMap element.
Description
Parse the Parcel elements of a MatrixIndicesMap element.
Usage
cifti.parse.parcels(node, filepath = "")
Arguments
node |
an xml2 node, the |
filepath |
character string, the path of the file the XML was read from. Only used in error messages. |
Value
a list of lists, or NULL if there are no Parcel elements.
Parse the series attributes of a MatrixIndicesMap element.
Description
Parse the series attributes of a MatrixIndicesMap element.
Usage
cifti.parse.series(node, filepath = "")
Arguments
node |
an xml2 node, the |
filepath |
character string, the path of the file the XML was read from. Only used in error messages. |
Value
a named list with the entries 'number_of_series_points', 'start',
'step', 'exponent' and 'unit', or NULL if the element has no series
attributes.
Parse the Surface elements of a MatrixIndicesMap element.
Description
Parse the Surface elements of a MatrixIndicesMap element.
Usage
cifti.parse.surfaces(node, filepath = "")
Arguments
node |
an xml2 node, the |
filepath |
character string, the path of the file the XML was read from. Only used in error messages. |
Value
a list of lists with the entries 'brain_structure' and
'surface_number_of_vertices', or NULL if there are no Surface elements.
Parse the Volume elements of a MatrixIndicesMap element.
Description
Parse the Volume elements of a MatrixIndicesMap element.
Usage
cifti.parse.volumes(node, filepath = "")
Arguments
node |
an xml2 node, the |
filepath |
character string, the path of the file the XML was read from. Only used in error messages. |
Value
a list of lists with the entries 'dimensions', 'meter_exponent' and
'transformation_matrix', or NULL if there are no Volume elements.
Parse the CIFTI XML metadata.
Description
Parse the CIFTI XML metadata.
Usage
cifti.parse.xml(xml_text, filepath = "", niiheader = NULL)
Arguments
xml_text |
character string, the XML document. |
filepath |
character string, the path of the file the XML was read from. Only used in error messages. |
niiheader |
the NIFTI-2 header of the file, required to determine the sizes of the matrix dimensions. |
Value
an fs.cifti object, see read.cifti.header.
Prepare per-vertex data for writing to a CIFTI-2 file.
Description
Common work of the user-facing CIFTI-2 writers: turn data that are given for the complete surface into the matrix of a dense CIFTI-2 file, i.e. one row per map (or series point, or label map) and one column per brainordinate, in the order of the grayordinates of the file.
Usage
cifti.prepare.surface.data(
data,
structure = NULL,
template = NULL,
what = "data"
)
Arguments
data |
numeric vector or matrix, or a named list of them, the per-vertex data. |
structure |
character string or |
template |
character string, |
what |
character string, a description of the data, used in error messages. |
Value
a named list with the entries 'matrix' (the data matrix to write), 'axes' (the
axes, with the brainordinate axis filled in and the other axis left NULL), 'template'
(the template object or NULL) and 'template_map_axis' (the axis of the template for
the other matrix dimension, or NULL).
Read the data matrix of a CIFTI-2 file.
Description
Read the data matrix of a CIFTI-2 file.
Usage
cifti.read.matrix(cii, rows = NULL, columns = NULL)
Arguments
cii |
an |
rows |
integer vector or |
columns |
integer vector or |
Value
the data array, see read.cifti.
Read the requested matrix rows of a CIFTI-2 file.
Description
Workhorse of read.cifti.rows: read some indices of
matrix dimension 0 without reading the rest of the rows. If a column
selection is given, only those columns are read (they are contiguous blocks
of the file), otherwise the file is read once, in chunks, keeping the
requested rows.
Usage
cifti.read.rows(cii, rows, columns = NULL, chunk_values = 4000000L)
Arguments
cii |
an |
rows |
integer vector, the indices of matrix dimension 0 to read. At least
one index has to be given; the indices are 1-based, see |
columns |
integer vector or |
chunk_values |
integer, the number of data values that are read from the file per chunk. This does not change the result, only the peak memory usage and the I/O granularity, so it is rarely needed: the default of 4 millions values corresponds to about 16 MB. The chunk size is rounded up to a whole number of matrix columns, and the result is the same for every chunk size. |
Value
a numeric matrix with one row per requested row index.
Read raw values from the data section of a CIFTI-2 file.
Description
Read raw values from the data section of a CIFTI-2 file.
Usage
cifti.read.values(cii, num_values, skip_values = 0L, fh = NULL)
Arguments
cii |
an |
num_values |
integer, the number of values to read. |
skip_values |
integer, the number of values to skip first. |
fh |
optional connection to the file, positioned at the start of the data
section if |
Value
vector of values, see read.nifti.values.
Remove hemisphere markers from region names of a parcellation.
Description
Region names of brain atlases often carry a marker that identifies the
hemisphere a region belongs to, e.g. L_superiorfrontal / R_superiorfrontal,
pericalcarine_LH / pericalcarine_RH, or 7Networks_LH_Vis_1 /
7Networks_RH_Vis_1. The same region of the two hemispheres has to be recognized as
one parcel when building a parcel axis for a CIFTI-2 file, so these markers are
removed here.
A marker that is removed is one of L, R, LH, RH, Left or Right (matched
case-insensitively), at the start of the name or at its end, followed or preceded by
_ or -, or enclosed by two separators anywhere in the name (in which case the two
separators collapse into one). Names without such a marker are returned unchanged, and
so are names that consist of nothing but a marker.
Usage
cifti.region.name.without.hemisphere(region_names)
Arguments
region_names |
character vector, the region names. |
Value
character vector, the names without hemisphere markers.
Get the series information of a CIFTI-2 file.
Description
Get the description of the series dimension of a CIFTI-2 file,
e.g. the time points of a .dtseries or .ptseries file. The time (or
other unit) of the series index i is
(start + i * step) * 10^exponent, with i starting at 0.
Usage
cifti.series.info(cii, dim = 0L)
Arguments
cii |
an |
dim |
integer, the matrix dimension to get the brain models for. CIFTI-2
files have two dimensions, so this is usually 0 (Workbench calls it the ROW
dimension) or 1 (the COLUMN dimension). See
|
Value
a named list with the entries 'number_of_series_points' (integer),
'start' (numeric), 'step' (numeric), 'exponent' (integer) and 'unit'
(character string, one of 'SECOND', 'HERTZ', 'METER', 'RADIAN'), or NULL
if the specified matrix dimension is not a series. To check whether a
dimension is a series, inspect the field 'type' of the corresponding entry
of cii$matrix$indices_maps.
See Also
Other cifti functions:
cifti.axis.brain.models(),
cifti.axis.from.template(),
cifti.axis.labels(),
cifti.axis.parcels(),
cifti.axis.parcels.from.annot(),
cifti.axis.scalars(),
cifti.axis.series(),
cifti.brain.model.surface(),
cifti.brain.model.volume(),
cifti.dim.labels(),
cifti.file.type.for.axes(),
cifti.grayordinates(),
cifti.header.from.axes(),
cifti.label.table(),
cifti.parcel(),
cifti.parcels(),
cifti.structure.data(),
cifti.structures(),
cifti.volume(),
print.fs.cifti(),
print.fs.cifti.data(),
print.fs.connectome(),
read.cifti(),
read.cifti.header(),
read.cifti.rows(),
read.fs.connectome.cifti(),
write.cifti(),
write.fs.connectome.cifti(),
write.fs.morph.cifti(),
write.fs.parcellated.cifti(),
write.fs.parcellation.cifti(),
write.fs.series.cifti()
Examples
cifti_file <- system.file("extdata", "cifti", "tiny.dtseries.nii", package = "freesurferformats")
cii <- read.cifti.header(cifti_file)
cifti.series.info(cii, dim = 0L)
Refuse to read a CIFTI file as a volume or morphometry file.
Description
The generic readers of this package dispatch on the file name, and a CIFTI
file is a NIFTI file as far as the name is concerned: read.fs.morph() used to
interpret a .dscalar.nii as a NIFTI morphometry file and silently returned the raw
matrix as a per-vertex vector (for the official Conte69 .dtseries, a 121,902 element
vector of a 60,951 x 2 matrix, i.e. plausible looking numbers in an order that means
nothing), and read.fs.volume() failed with the unrelated 'This is not a one-file
NIFTI format' message of oro.nifti. This function detects the CIFTI files and stops
with an error that names the reader to use instead, see read.cifti.
The check only costs a header read, and only for files whose name ends with .nii or
.nii.gz, since a CIFTI file always has such a name.
Usage
cifti.stop.if.cifti(filepath)
Arguments
filepath |
character string, the path to a CIFTI-2 file (usually one of
|
Value
NULL, invisibly. Stops if the file is a CIFTI file.
Refuse a CIFTI-2 file name for a file that is not a CIFTI-2 file.
Description
The writers of this package that are not CIFTI writers (write.fs.morph(),
write.fs.volume()) derive the format from the file name, and a CIFTI-2 file name
looks like a NIFTI name. Writing a NIFTI file under a name like .dscalar.nii would
produce a file whose content contradicts its name: this package (and Connectome
Workbench) refuse to read it, because the name promises the CIFTI XML metadata that
describes what the matrix dimensions contain. This function turns that into an error
that names the writer to use instead.
Usage
cifti.stop.if.cifti.name(filepath)
Arguments
filepath |
character string, the name of the file that is about to be written. |
Value
NULL, invisibly. Stops if the name is one of the standard CIFTI-2 file names.
Normalize a CIFTI brain structure name.
Description
CIFTI brain structure names are written in several spellings by
different software: Connectome Workbench uses CIFTI_STRUCTURE_CORTEX_LEFT,
nibabel also accepts CortexLeft, and this package uses the aliases lh and
rh (and also left/right) for the cortical surfaces. This function
normalizes all of them to the canonical CIFTI_STRUCTURE_* spelling.
Usage
cifti.structure.canonical(brain_structure)
Arguments
brain_structure |
character string, a brain structure name in any of the supported spellings. |
Value
character string, the canonical structure name (e.g.
'CIFTI_STRUCTURE_CORTEX_LEFT'), or NA_character_ if the input is NA.
Extract the data of one brain structure from a CIFTI-2 file.
Description
Get the data values of a single brain structure (e.g. one
hemisphere) from a CIFTI-2 file, reconstructed for the full surface. The
result has one row per vertex of the surface (in the order of the surface,
which is the order the vertices have in the surface mesh files) and one
column per index of the other matrix dimension of the file. Vertices of the
surface that have no value in the file are reported as NA: grayordinates
files have a reduced mesh (the medial wall vertices are missing), and
returning the values for the complete surface is what makes such files
usable together with the standard surface meshes of a subject.
Volume structures (a brain model of type 'CIFTI_MODEL_TYPE_VOXELS', which subcortical structures use) cannot be expanded like this, because the voxels a structure consists of are not a rectangular block of a volume and are not ordered in any meaningful way. For those, the data values are returned together with the voxel indices and the affine transformation that maps them to coordinates, see the Value section.
Usage
cifti.structure.data(x, structure = NULL, dim = NULL)
Arguments
x |
an |
structure |
character string or |
dim |
integer or |
Value
If 'structure' is a single structure: a named list with the entries
'structure' (character string, the canonical name of the structure, e.g.
'CIFTI_STRUCTURE_CORTEX_LEFT'), 'structure_short' (the name without the
prefix, e.g. 'CORTEX_LEFT'), 'model_type' (character string, one of
'SURFACE', 'VOXELS' or 'SURFACE_AND_VOXELS'), 'surface' and 'volume'. If
'structure' is NULL: a named list of such lists, one per structure, named
by the short structure name.
For a selection that contains a surface model, the 'surface' entry holds a
numeric (or integer) array with one row per vertex of the full surface and
the remaining dimensions of the data, with NA for vertices that the file
does not contain. Its dimensions beyond the first are named like in
read.cifti. If the selection contains no surface model,
'surface' is NULL.
For a selection that contains a volume model, the 'volume' entry holds a
named list with the entries 'values' (an array like 'surface', but with one
row per voxel of the structure instead of per surface vertex), 'voxel_indices_ijk'
(an n x 3 integer matrix of 0-based voxel indices, in the same order as the
rows of 'values'), 'dimensions' (integer vector of length 3, the dimensions
of the volume the voxel indices refer to) and 'transformation_matrix' and
'meter_exponent' (the 4x4 row-major matrix from the file that maps the voxel
indices to coordinates in units of 10^meter_exponent, and the exponent).
If the selection contains no volume model, 'volume' is NULL.
See Also
Other cifti functions:
cifti.axis.brain.models(),
cifti.axis.from.template(),
cifti.axis.labels(),
cifti.axis.parcels(),
cifti.axis.parcels.from.annot(),
cifti.axis.scalars(),
cifti.axis.series(),
cifti.brain.model.surface(),
cifti.brain.model.volume(),
cifti.dim.labels(),
cifti.file.type.for.axes(),
cifti.grayordinates(),
cifti.header.from.axes(),
cifti.label.table(),
cifti.parcel(),
cifti.parcels(),
cifti.series.info(),
cifti.structures(),
cifti.volume(),
print.fs.cifti(),
print.fs.cifti.data(),
print.fs.connectome(),
read.cifti(),
read.cifti.header(),
read.cifti.rows(),
read.fs.connectome.cifti(),
write.cifti(),
write.fs.connectome.cifti(),
write.fs.morph.cifti(),
write.fs.parcellated.cifti(),
write.fs.parcellation.cifti(),
write.fs.series.cifti()
Examples
cifti_file <- system.file("extdata", "cifti", "tiny.dscalar.nii", package = "freesurferformats")
cii <- read.cifti(cifti_file)
lh_data <- cifti.structure.data(cii, "lh")
dim(lh_data$surface)
# vertices beyond the end of the mesh in the file are NA:
sum(is.na(lh_data$surface[, 1]))
# Volume structures are returned with their voxel indices:
vol_file <- system.file("extdata", "cifti", "tiny_volume.dscalar.nii",
package = "freesurferformats")
vol_cii <- read.cifti(vol_file)
cerebellum <- cifti.structure.data(vol_cii, "CEREBELLUM")
cerebellum$volume$voxel_indices_ijk
Get the matrix dimension a brain structure lives in.
Description
The counterpart of cifti.other.dim for a structure
name: look up the dimension of the file that contains brain models for the
given structure. Needed by the user-facing readers, which get a structure name
from the user and must decide which dimension of the data matrix it refers to.
Usage
cifti.structure.data.dim(cii, structure)
Arguments
cii |
an |
structure |
character string, the canonical name of the brain structure. |
Value
integer, the matrix dimension.
Extract the data of one brain structure (internal).
Description
Extract the data of one brain structure (internal).
Usage
cifti.structure.data.one(cii, map, brainordinates, data, structure)
Arguments
cii |
an |
map |
the indices map of the brainordinate dimension, see
|
brainordinates |
the brainordinate table, see
|
data |
the data array with the brainordinate dimension first, see
|
structure |
character string, the canonical name of the structure. |
Value
a named list, see cifti.structure.data.
Resolve a user-supplied structure specifier to a canonical name.
Description
Accept the structure spellings the user-facing readers support: a structure name in any of the supported spellings, or the index of a structure in the file (deprecated, but part of the documented interface of the readers).
Usage
cifti.structure.from.specifier(cii, brain_structure)
Arguments
cii |
an |
brain_structure |
character string or integer, the specifier. |
Value
character string, the canonical structure name.
Get the short name of a CIFTI brain structure.
Description
Strip the CIFTI_STRUCTURE_ prefix from a brain structure name,
normalizing it first, see cifti.structure.canonical.
Usage
cifti.structure.short(brain_structure)
Arguments
brain_structure |
character string, a brain structure name in any of the supported spellings. |
Value
character string, the structure name without the prefix (e.g. 'CORTEX_LEFT').
Get the brain model table of a CIFTI-2 file.
Description
Get the brain model entries for one matrix dimension of a CIFTI-2 file, i.e. the mapping from matrix indices to surface vertices or volume voxels. Note that a brain structure can appear in several brain model entries: a grayordinates file can contain a surface part and a volume part for the same structure, and a structure can be split into several index ranges. Always use the index ranges from this table to map data values, never the structure names.
Usage
cifti.structures(cii, dim = 0L)
Arguments
cii |
an |
dim |
integer, the matrix dimension to get the brain models for. CIFTI-2
files have two dimensions, so this is usually 0 (Workbench calls it the ROW
dimension) or 1 (the COLUMN dimension). See
|
Value
a data.frame with one row per brain model entry and the columns
'structure' (character string, the brain structure in the spelling used in
the file), 'structure_short' (character string, the normalized name without
the CIFTI_STRUCTURE_ prefix, e.g. 'CORTEX_LEFT'), 'model_type' ('SURFACE'
or 'VOXELS'), 'index_offset' (integer, 0-based index of the first matrix
entry covered by this brain model), 'index_count' (integer, the number of
matrix entries covered) and 'surface_number_of_vertices' (integer, the
number of vertices of the complete surface, for surface models; NA for
volume models). Use index_offset and index_count to extract the data
values for a brain model from the data matrix.
See Also
Other cifti functions:
cifti.axis.brain.models(),
cifti.axis.from.template(),
cifti.axis.labels(),
cifti.axis.parcels(),
cifti.axis.parcels.from.annot(),
cifti.axis.scalars(),
cifti.axis.series(),
cifti.brain.model.surface(),
cifti.brain.model.volume(),
cifti.dim.labels(),
cifti.file.type.for.axes(),
cifti.grayordinates(),
cifti.header.from.axes(),
cifti.label.table(),
cifti.parcel(),
cifti.parcels(),
cifti.series.info(),
cifti.structure.data(),
cifti.volume(),
print.fs.cifti(),
print.fs.cifti.data(),
print.fs.connectome(),
read.cifti(),
read.cifti.header(),
read.cifti.rows(),
read.fs.connectome.cifti(),
write.cifti(),
write.fs.connectome.cifti(),
write.fs.morph.cifti(),
write.fs.parcellated.cifti(),
write.fs.parcellation.cifti(),
write.fs.series.cifti()
Examples
cifti_file <- system.file("extdata", "cifti", "tiny.dscalar.nii", package = "freesurferformats")
cii <- read.cifti.header(cifti_file)
cifti.structures(cii, dim = 1L)
Subset one dimension of an array.
Description
Subset one dimension of an array.
Usage
cifti.subset.dim(data, dim, selection)
Arguments
data |
the array to subset. |
dim |
integer, the dimension to subset. |
selection |
integer vector or |
Value
the subset, with the dimensions of data preserved.
Get the number of vertices of one surface of a CIFTI-2 mapping.
Description
Get the size of the complete surface a brain model refers to. The
Surface elements of the mapping are used if the file has them, otherwise
the SurfaceNumberOfVertices attributes of the brain models are used: the
Surface elements are optional, and the files written by Connectome
Workbench (including the official CIFTI-2 example files) do not contain any,
they report the surface size in the brain models only.
Usage
cifti.surface.vertex.count(map, structure)
Arguments
map |
the indices map, see |
structure |
character string, the canonical name of the brain structure. |
Value
integer, the number of vertices, or NA_integer_ if the structure has
no surface model in this mapping.
Get the number of vertices of the surfaces declared in a CIFTI mapping.
Description
Get the number of vertices of the surfaces declared in a CIFTI mapping.
Usage
cifti.surface.vertex.counts(map)
Arguments
map |
a parsed indices map, see |
Value
named integer vector, the number of vertices per canonical brain structure short name (e.g. 'CORTEX_LEFT'). Empty if the mapping declares no surfaces.
Validate the axes of a CIFTI-2 file.
Description
Check the things about a set of axes that make a file invalid rather than just unusual: the sizes of the axes, the index ranges of the brain models, the structures a volume model or a parcel refers to, and the label keys of a label table.
Usage
cifti.validate.axes(axes)
Arguments
axes |
list of axes, see |
Value
NULL, invisibly. Stops with a descriptive error.
Validate the brain model entries of a CIFTI mapping.
Description
Validate the brain model entries of a CIFTI mapping.
Usage
cifti.validate.brain.models(map, dim_size, filepath = "")
Arguments
map |
a parsed indices map, see |
filepath |
character string, the file path, used in error messages. |
Value
NULL, invisibly. Stops with a descriptive error if an entry is
inconsistent.
Check that all matrix dimensions are described exactly once.
Description
Check that all matrix dimensions are described exactly once.
Usage
cifti.validate.dims.coverage(indices_maps, dim_sizes, filepath = "")
Arguments
indices_maps |
list of parsed indices maps. |
filepath |
character string, the path of the file the XML was read from. Only used in error messages. |
Value
NULL, invisibly. Stops if a dimension is described twice or not at
all.
Check the file extension against the axes of the data.
Description
A CIFTI-2 file name states the file type (.dscalar, .pdconn, ...), and
the type decides which matrix index types the two dimensions have. A file whose name
contradicts its content is silently misread by other software, so this is an error.
Usage
cifti.validate.file.extension(filepath, file_type)
Arguments
filepath |
character string, the file name to write. |
file_type |
a one row data.frame, see |
Value
NULL, invisibly. Stops if the file name names a different file type.
Check that all indices are within a valid range.
Description
Check that all indices are within a valid range.
Usage
cifti.validate.index.range(indices, max_index, what, filepath = "")
Arguments
indices |
integer vector, the indices to check. |
max_index |
integer, the largest allowed index. |
what |
character string, a description of what the indices are, used in the error message. |
filepath |
character string, the file path, used in error messages. |
Value
NULL, invisibly. Stops with a descriptive error if an index is out
of range.
Validate a parsed CIFTI MatrixIndicesMap.
Description
Check that the mapping is consistent with the size of the matrix dimension it describes, and that the index ranges it declares are valid. These checks exist because a mismatch would silently misalign the data.
Usage
cifti.validate.indices.map(map, filepath = "")
Arguments
map |
a parsed indices map, see |
filepath |
character string, the file path, used in error messages. |
Value
NULL, invisibly. Stops with a descriptive error if the mapping is
inconsistent.
Validate the parcels of a CIFTI mapping.
Description
Validate the parcels of a CIFTI mapping.
Usage
cifti.validate.parcels(map, filepath = "")
Arguments
map |
a parsed indices map, see |
filepath |
character string, the file path, used in error messages. |
Value
NULL, invisibly. Stops with a descriptive error if a parcel refers
to vertices outside of a declared surface.
Check the safety limit for reading a CIFTI-2 data matrix.
Description
Check the requested allocation against the package safety limit
(see validate_allocation_size) and add a CIFTI specific hint to
the error message if it is exceeded: the data of a large file can be read in
parts by selecting matrix columns, which is not possible in the same way for
other image formats.
Usage
cifti.validate.read.size(dims, bytes_per_elem, filepath)
Arguments
dims |
integer vector, the dimensions of the requested data matrix. |
bytes_per_elem |
numeric, the number of bytes per data value. |
filepath |
character string, the path of the file, used in the error message. |
Value
NULL, invisibly. Stops if the limit is exceeded.
Create a CIFTI-2 axis for a volume.
Description
A volume axis describes the voxel grid that the volume brain models of a
CIFTI-2 file refer to: its dimensions and the 4x4 transformation matrix that maps the
(0-based) IJK voxel indices to coordinates. The matrix is stored row by row in the
file, and the coordinates it produces are in units of 10^meter_exponent (which is
-3, i.e. millimeters, for the files that Connectome Workbench writes).
Usage
cifti.volume(dimensions, transformation_matrix, meter_exponent = -3L)
Arguments
dimensions |
integer vector of length 3, the dimensions of the voxel grid. |
transformation_matrix |
4x4 numeric matrix, the transformation from (0-based)
voxel indices to coordinates. There is no default: a CIFTI-2 file does not store the
voxel size or the position of a volume anywhere else, so a wrong or invented matrix
silently puts the voxels of a structure in the wrong place. Pass the matrix that the
template file has (see |
meter_exponent |
integer, the exponent of the unit of the coordinates. |
Value
a named list with the entries 'dimensions', 'meter_exponent' and
'transformation_matrix', to be passed to cifti.axis.brain.models or
cifti.axis.parcels.
See Also
Other cifti functions:
cifti.axis.brain.models(),
cifti.axis.from.template(),
cifti.axis.labels(),
cifti.axis.parcels(),
cifti.axis.parcels.from.annot(),
cifti.axis.scalars(),
cifti.axis.series(),
cifti.brain.model.surface(),
cifti.brain.model.volume(),
cifti.dim.labels(),
cifti.file.type.for.axes(),
cifti.grayordinates(),
cifti.header.from.axes(),
cifti.label.table(),
cifti.parcel(),
cifti.parcels(),
cifti.series.info(),
cifti.structure.data(),
cifti.structures(),
print.fs.cifti(),
print.fs.cifti.data(),
print.fs.connectome(),
read.cifti(),
read.cifti.header(),
read.cifti.rows(),
read.fs.connectome.cifti(),
write.cifti(),
write.fs.connectome.cifti(),
write.fs.morph.cifti(),
write.fs.parcellated.cifti(),
write.fs.parcellation.cifti(),
write.fs.series.cifti()
Examples
volume <- cifti.volume(c(4L, 4L, 4L), diag(c(2, 2, 2, 1)))
volume$dimensions
Add a MatrixIndicesMap element to the Matrix element.
Description
Add a MatrixIndicesMap element to the Matrix element.
Usage
cifti.xml.add.indices.map(matrix_node, axis, dims)
Arguments
matrix_node |
an xml2 node, the |
axis |
the axis to write, see |
dims |
integer vector, the matrix dimensions the element applies to. |
Value
NULL, invisibly. The element is added as a child of matrix_node.
Add a MetaData element to an XML node.
Description
Add a MetaData element to an XML node.
Usage
cifti.xml.add.metadata(node, metadata)
Arguments
node |
an xml2 node, the parent element. |
metadata |
named character vector, named list or |
Value
NULL, invisibly. The element is added as a child of node.
Format an integer vector for an XML text node.
Description
Format an integer vector for an XML text node.
Usage
cifti.xml.int.vector(x)
Arguments
x |
integer vector. |
Value
character string, the values separated by single spaces.
Format a number like the reference implementations do.
Description
Connectome Workbench writes fixed point values with 10 decimal places in
the XML (e.g. SeriesStep="2.5000000000"), and this keeps the output comparable with
the files it writes. Colors of a label table are written with the precision the file
had, which is 3 decimal places in the official example files.
Usage
cifti.xml.num(x, decimals = 10L)
Arguments
x |
numeric, the value. |
decimals |
integer, the number of decimal places. |
Value
character string.
Format a numeric vector for an XML text node.
Description
Format a numeric vector for an XML text node.
Usage
cifti.xml.num.vector(x, decimals = 10L)
Arguments
x |
numeric vector. |
decimals |
integer, the number of decimal places. |
Value
character string, the values separated by single spaces.
The CIFTI version this package writes.
Description
The CIFTI version this package writes.
Usage
cifti.xml.version()
Value
character string, '2'.
Find vertex index closest to given query coordinate using Euclidean distance.
Description
Find vertex index closest to given query coordinate using Euclidean distance.
Usage
closest.vert.to.point(surface, point_coords)
Arguments
surface |
an fs.surface instance or a nx3 numerical matrix representing mesh points. |
point_coords |
nx3 matrix of query coords. If a vector, will be transformed |
Value
named list with entries: 'vertex_id' integer vector, the index of the closest vertex, and 'dist': double vector, the Euclidean distance to that vertex.
See Also
Other Euclidean distance util functions:
vertex.euclid.dist(),
vertexdists.to.point()
Extract color lookup table (LUT) from annotation.
Description
Extract a colortable lookup table (LUT) from an annotation. Such a LUT can also be read from files like FREESURFER_HOME/FreeSurferColorLUT.txt or saved as a file, check the 'See Also' section below.
Usage
colortable.from.annot(annot, compute_colorcode = FALSE)
Arguments
annot |
An annotation, as returned by |
compute_colorcode |
logical, indicates whether the unique color codes should be computed and added to the returned data.frame as an extra integer column named 'code'. Defaults to FALSE. |
Value
the colortable data.frame extracted from the annotation.
See Also
Other atlas functions:
atlas.from.lut.and.csv(),
read.fs.annot(),
read.fs.colortable(),
write.atlas.to.lut.and.csv(),
write.fs.annot(),
write.fs.annot.gii(),
write.fs.colortable()
Other colorLUT functions:
read.fs.colortable(),
write.fs.colortable()
Examples
annotfile <- system.file("extdata", "lh.aparc.annot.gz",
package = "freesurferformats", mustWork = TRUE
)
annot <- read.fs.annot(annotfile)
colortable <- colortable.from.annot(annot)
head(colortable)
Compute the bounding box of a set of coordinates.
Description
Compute the bounding box of a set of coordinates.
Usage
coord.bbox(coords)
Arguments
coords |
numeric matrix with 3 columns. |
Value
numeric vector of length 6,
c(xmin, xmax, ymin, ymax, zmin, zmax), or NULL if there are no rows.
Turn coordinate vector into string.
Description
Turn coordinate vector into string.
Usage
coord.to.key(coord, digits = 6L)
Arguments
coord |
double vector of length 3, the xyz coord |
digits |
integer, the number of digits (after the decimal separator) to use |
Value
character string
Delete all data in the package cache.
Description
Delete all data in the package cache.
Usage
delete_all_opt_data()
Value
integer. The return value of the unlink() call: 0 for success, 1 for failure. See the unlink() documentation for details.
Detect the format of a DTI tract file.
Description
Detect the format of a DTI tract file.
Usage
detect.dti.tract.format(filepath)
Arguments
filepath |
character string, path to the file. |
Value
character string, one of 'tck', 'tsf' or 'trk'.
Apply a spatial transformation matrix to the given coordinates.
Description
Apply a spatial transformation matrix to the given coordinates.
Usage
doapply.transform.mtx(coords, mtx, as_mat = FALSE)
Arguments
coords |
nx3 (cartesian) or nx4 (homogeneous) numerical matrix, the input coordinates. If nx4, left as is for homogeneous notation, if nx3 (cartesian) a 1 will be appended as the 4th position. |
mtx |
a 4x4 numerical transformation matrix |
as_mat |
logical, whether to force the output coords into a matrix (even if the input was a vector/a single coordinate triple). |
Value
the coords after applying the transformation. If coords was nx3, nx3 is returned, otherwise nx4.
Examples
coords_tf <- doapply.transform.mtx(c(1.0, 1.0, 1.0), mni152reg())
coords_tf
doapply.transform.mtx(coords_tf, solve(mni152reg()))
Download optional data for the freesurferformats package.
Description
Ensure that the optional data is available locally in the package cache. Will try to download the data only if it is not available. This data is not required for the package to work, but it is used in the examples, in the unit tests and also in the example code from the vignette. Downloading it is highly recommended. The downloaded data files are owned by their respective copyright holders and are subject to their respective licenses; see the file 'inst/COPYRIGHTS' for attribution and license details.
Usage
download_opt_data(
dl_from = c("rcmd.org", "github_fsf_release"),
scheme = c("https", "http")
)
Arguments
dl_from |
string, the source to download from. Either |
scheme |
string, the URL scheme to use. Either |
Value
Named list. The list has entries: "available": vector of strings. The names of the files that are available in the local file cache. You can access them using get_optional_data_file(). "missing": vector of strings. The names of the files that this function was unable to retrieve.
Compute the bounding box of all tract coordinates in a file.
Description
Streams through the tract file and returns the bounding box of all coordinates, without keeping the coordinates in memory. This is useful to determine the axis limits for plotting a large tractogram.
Usage
dti.track.bbox(filepath, chunk_values = 4e+06)
Arguments
filepath |
character string, path to the |
chunk_values |
integer, the number of payload values to read per chunk.
Advanced tuning parameter, see |
Value
numeric vector of length 6,
c(xmin, xmax, ymin, ymax, zmin, zmax), or NULL if the file
contains no coordinates. The coordinates are in the coordinate system used
by the file, see the note in read.dti.trk.
Examples
## Not run:
bbox <- dti.track.bbox("brain.tck");
## End(Not run)
Count the tracts in a DTI tract file.
Description
Counts the tracts in a TRK, TCK or TSF file without reading
their coordinates, so this works on arbitrarily large tractograms with a
small and constant amount of memory. This is the equivalent of
tckinfo <file> -count in MRtrix.
Usage
dti.track.count(filepath, chunk_values = 4e+06)
Arguments
filepath |
character string, path to the |
chunk_values |
integer, the number of payload values to read per chunk.
Advanced tuning parameter, see |
Value
integer, the number of tracts in the file. Note that this can differ
from the count entry in the file header, which the MRtrix
documentation explicitly describes as unreliable, and which does not count
empty tracts.
Examples
## Not run:
dti.track.count("brain.tck");
## End(Not run)
Create an iterator over the tracts of a DTI tract file.
Description
Reads a TRK, TCK or TSF file tract by tract, so that a
tractogram of any size can be processed with a constant amount of memory.
This is the low-level interface behind dti.track.count and
friends, use it when neither reading a subset
(max_tracks, skip_tracks, bbox in
read.dti.tck) nor one of the aggregate functions fits your
use case.
The returned object is an environment with the following entries:
-
next.track(): returns the next tract (a n x 3 matrix for TCK, a numeric vector of per-point values for TSF, and a list with the entriescoords,num_points,scalarsandpropertiesfor TRK, just liketracks[[i]]does for the readers), orNULLwhen there are no more tracts. -
close(): closes the underlying file connection. It is safe to call this more than once, and it is also called automatically when the iterator is garbage collected. -
tracks.read: the number of tracts returned so far. -
filepath,format: the file and its detected format.
Usage
dti.track.iterator(
filepath,
skip_tracks = 0L,
bbox = NULL,
chunk_values = 4e+06
)
Arguments
filepath |
character string, path to the |
skip_tracks |
integer, the number of tracks to skip before reading any. Skipped tracks are never held in memory. |
bbox |
numeric vector of length 6 or NULL. If given, only tracks that
have at least one point inside the box are read, the box is given as
|
chunk_values |
integer, the number of payload values that are read per chunk. This is an advanced tuning parameter that does not change the result, only the peak memory usage (at most one chunk is buffered at a time) and the granularity of the file reads. The default of 4e6 values corresponds to about 32 MB of doubles. Lower it on a machine with very little free memory. |
Value
the iterator environment, see the description.
Examples
## Not run:
itr <- dti.track.iterator("brain.tck");
total_points <- 0;
while (!is.null(track <- itr$next.track())) {
total_points <- total_points + nrow(track);
}
itr$close();
## End(Not run)
Compute Euclidean distance.
Description
Compute Euclidean distance.
Usage
euclidian.dist(x1, x2)
Arguments
x1 |
numerical vector, coords of first point |
x2 |
numerical vector, coords of second point |
Value
the Euclidean distance between x1 and x2.
Convert quadrangular faces or polygons to triangular ones.
Description
Convert quadrangular faces or polygons to triangular ones.
Usage
faces.quad.to.tris(quad_faces)
Arguments
quad_faces |
nx4 integer matrix, the indices of the vertices making up the n quad faces. |
Value
2nx3 integer matrix, the indices of the vertices making up the 2n tris faces.
Note
This function does no fancy remeshing, it simply splits each quad into two triangles.
See Also
Other mesh functions:
read.fs.surface(),
read.fs.surface.asc(),
read.fs.surface.bvsrf(),
read.fs.surface.geo(),
read.fs.surface.gii(),
read.fs.surface.ico(),
read.fs.surface.obj(),
read.fs.surface.off(),
read.fs.surface.ply(),
read.fs.surface.vtk(),
read.mesh.brainvoyager(),
read_nisurface(),
read_nisurfacefile(),
write.fs.surface(),
write.fs.surface.asc(),
write.fs.surface.byu(),
write.fs.surface.gii(),
write.fs.surface.mz3(),
write.fs.surface.vtk()
Convert tris faces to quad faces by simple merging.
Description
This is experimental. Note that it can only work if the number of 'tris_faces' is even, as two consecutive tris-faces will be merged into one quad face. We could set the index to NA in that case, but I do not know how FreeSurfer handles this, so we do not guess.
Usage
faces.tris.to.quad(tris_faces)
Arguments
tris_faces |
nx3 integer matrix, the indices of the vertices making up the n tris faces. |
Value
n/2x4 integer matrix, the indices of the vertices making up the n quad faces.
Note
This function does not implement proper remeshing of tri-meshes to quad-meshes. Use a proper mesh library if you need that.
Get connection to a binary file, gz or not.
Description
Get connection to a binary file, gz or not.
Usage
fileopen.gz.or.not(filepath)
Arguments
filepath |
path to the binary file. |
Open a connection for writing, with gzip support based on the file name.
Description
Open a connection for writing, with gzip support based on the file name.
Usage
fileopen.write.gz.or.not(filepath)
Arguments
filepath |
character string, the path of the file to write. |
Value
a connection, either a gzfile or a plain file connection.
Check whether filepath ends with extension.
Description
Check whether filepath ends with extension.
Usage
filepath.ends.with(filepath, extensions)
Arguments
filepath |
string. Path to a file, including filename and extension. |
extensions |
list of strings. A list of suffixes to check. Case does not matter. Example: |
Value
logical, whether the filepath end with one of the extensions.
Check which rows of a matrix consist of finite values only.
Description
Check which rows of a matrix consist of finite values only.
Usage
finite.rows(mat)
Arguments
mat |
numeric matrix. |
Value
logical vector with one entry per row.
Write fixed width integers to one or several lines.
Description
Write fixed width integers to one or several lines.
Usage
fixed.vec.format.int(
vdata,
num_chars_per_entry,
max_entries_per_line = NULL,
align_right = TRUE
)
Arguments
vdata |
integer vector, the data |
num_chars_per_entry |
field length of a single formatted integer in characters |
max_entries_per_line |
integer, how many entries are allowed per line. Leave at NULL for no limit, which will return all in a single line. |
align_right |
logical, whether to align the integers to the right. As you may have guessed, set to |
Value
vector of character strings, the formatted data lines.
Flip a 2D matrix.
Description
Flip a 2D matrix.
Usage
flip2D(slice, how = "horizontally")
Arguments
slice |
a 2D matrix |
how |
character string, one of 'vertically' / 'v' or 'horizontally' / 'h'. Note that flipping horizontally means that the image will be mirrored along the central vertical axis. If |
Value
2D matrix, the flipped matrix.
Flip a 3D array along an axis.
Description
Flip the slice of an 3D array horizontally or vertically along an axis. This leads to an output array with identical dimensions.
Usage
flip3D(volume, axis = 1L, how = "horizontally")
Arguments
volume |
a 3D image volume |
axis |
positive integer in range 1L..3L or an axis name, the axis to use. |
how |
character string, one of 'horizontally' / 'h' or 'vertically' / 'v'. How to flip the 2D slices. Note that flipping horizontally means that the image will be mirrored along the central vertical axis. |
Value
a 3D image volume, flipped around the axis. The dimensions are identical to the dimensions of the input image.
See Also
Other volume math:
rotate3D()
Format a number of bytes for human consumption.
Description
Used in the error messages of validate_allocation_size,
so that sizes below one gigabyte stay readable. A limit of a few hundred
kilobytes would otherwise be reported as '0.00 GB', which is useless when
debugging a failed read.
Usage
format_bytes_human(num_bytes)
Arguments
num_bytes |
single numeric value, the number of bytes. |
Value
character string, the size with a unit.
Read 3-byte integer.
Description
Read a 3-byte integer from a binary file handle. Advances the pointer accordingly.
Usage
fread3(filehandle)
Arguments
filehandle |
file handle |
Value
integer, The read integer.
Determine morphometry file extension from format
Description
Given a morphometry file format, derive the proper file extension.
Usage
fs.get.morph.file.ext.for.format(format)
Arguments
format |
string. One of c("mgh", "mgz", "curv", "gii"). |
Value
file ext, string. The standard file extension for the format. (May be an empty string for some formats.)
See Also
Other morphometry functions:
fs.get.morph.file.format.from.filename(),
read.fs.curv(),
read.fs.mgh(),
read.fs.morph(),
read.fs.morph.gii(),
read.fs.volume(),
read.fs.weight(),
write.fs.curv(),
write.fs.label.gii(),
write.fs.mgh(),
write.fs.morph(),
write.fs.morph.asc(),
write.fs.morph.gii(),
write.fs.morph.ni1(),
write.fs.morph.ni2(),
write.fs.morph.smp(),
write.fs.morph.txt(),
write.fs.weight(),
write.fs.weight.asc()
Determine morphometry file format from filename
Description
Given a morphometry file name, derive the proper file format, based on the end of the string. Case is ignored, i.e., cast to lowercase before checks. If the filepath ends with "mgh", returns format "mgh". For suffix "mgz", returns "mgz" format. For all others, returns "curv" format.
Usage
fs.get.morph.file.format.from.filename(filepath)
Arguments
filepath |
string. A path to a file. |
Value
format, string. The format, one of c("mgz", "mgh", "curv", "gii", "smp").
See Also
Other morphometry functions:
fs.get.morph.file.ext.for.format(),
read.fs.curv(),
read.fs.mgh(),
read.fs.morph(),
read.fs.morph.gii(),
read.fs.volume(),
read.fs.weight(),
write.fs.curv(),
write.fs.label.gii(),
write.fs.mgh(),
write.fs.morph(),
write.fs.morph.asc(),
write.fs.morph.gii(),
write.fs.morph.ni1(),
write.fs.morph.ni2(),
write.fs.morph.smp(),
write.fs.morph.txt(),
write.fs.weight(),
write.fs.weight.asc()
Constructor for fs.patch
Description
Constructor for fs.patch
Usage
fs.patch(vertices, faces = NULL)
Arguments
vertices |
numerical nx5 matrix (or nx7 matrix), see |
faces |
numerical nx5 matrix, see |
Value
instance of class fs.patch
See Also
Other patch functions:
read.fs.patch(),
read.fs.patch.asc(),
write.fs.patch()
Examples
num_vertices <- 6L
# a tiny patch
vertices <- matrix(rep(0., num_vertices * 5), ncol = 5)
vertices[, 1] <- seq.int(num_vertices)
# 1-based vertex indices
vertices[, 2:4] <- matrix(rnorm(num_vertices * 3, 8, 2), ncol = 3)
# vertex coords
vertices[, 5] <- rep(0L, num_vertices)
# is_border
vertices[3, 5] <- 1L
# set a vertex to be a border vertex
patch <- fs.patch(vertices)
patch
Get an rgl tmesh3d instance from a brain surface mesh.
Description
Convert fs.surface to tmesh without the rgl package.
Usage
fs.surface.to.tmesh3d(surface)
Arguments
surface |
an fs.surface instance, as returned |
Value
a tmesh3d instance representing the surface, see rgl::tmesh3d for details. It has classes mesh3d and shape3d.
Create an fs.tracts instance from a compact tract representation.
Description
Creates the compact container used by the DTI tract readers and
writers. Reading a track file with read.dti.tck,
read.dti.trk or read.dti.tsf returns instances of
this class, and this function is the way to build one from your own data,
e.g., to write a tractogram that was assembled or edited in R with
write.dti.tck or write.dti.trk.
Usage
fs.tracts(coords, lengths, scalars = NULL, properties = NULL, kind = "tck")
Arguments
coords |
numeric matrix with 3 columns, the concatenated coordinates of all tracts. |
lengths |
integer vector, the number of points of each tract. Must sum
up to |
scalars |
numeric matrix or NULL. Per-point data, with one row per
point (i.e., |
properties |
numeric matrix or NULL. Per-tract data, with one row per tract. |
kind |
character string, either 'tck' or 'trk'. Determines what
|
Value
an fs.tracts instance.
Examples
# Two tracts, the first with two points and the second with one.
coords <- matrix(c(0, 0, 0, 1, 1, 1, 5, 5, 5), ncol = 3, byrow = TRUE);
tracts <- fs.tracts(coords, lengths = c(2L, 1L));
length(tracts);
tracts[[1]];
Get the concatenated coordinates of fs.tracts instances.
Description
Returns all tract coordinates as a single N x 3 matrix, with the tracts concatenated along the rows. This is the compact representation used internally, and the fastest way to access all coordinates, e.g., for plotting or for computing a bounding box.
Usage
fs.tracts.coords(tracts)
Arguments
tracts |
an |
Value
numeric matrix with 3 columns and one row per point of all tracts.
Examples
## Not run:
tck <- read.dti.tck("brain.tck");
coords <- fs.tracts.coords(tck$tracks);
bbox <- apply(coords, 2, range);
## End(Not run)
Get the number of tracts.
Description
Get the number of tracts.
Usage
fs.tracts.count(tracts)
Arguments
tracts |
an |
Value
integer, the number of tracts.
Get the number of points of each tract.
Description
Returns one integer per tract, the number of points it consists
of. The coordinates of tract i are the rows
(cumsum(c(1, lengths))[i]):(cumsum(lengths)[i]) of
fs.tracts.coords().
Usage
fs.tracts.lengths(tracts)
Arguments
tracts |
an |
Value
integer vector with one entry per tract.
Examples
## Not run:
tck <- read.dti.tck("brain.tck");
lengths <- fs.tracts.lengths(tck$tracks);
mean(lengths);
## End(Not run)
Get the total number of points of all tracts.
Description
Get the total number of points of all tracts.
Usage
fs.tracts.point.count(tracts)
Arguments
tracts |
an |
Value
integer, the total number of points.
Create an fs.transform instance.
Description
An fs.transform is a linear transformation matrix together with the coordinate spaces that it
maps between. It is the common representation that all transformation file format readers and writers in this
package return and accept, so that a matrix read from a file always states what its numbers mean: a bare 4x4
matrix does not tell whether it maps voxel indices or world coordinates, in which direction it goes, or
whether the voxel indices are zero- or one-based.
The matrix field always maps from the source to the target, i.e., applying it to a coordinate means
target_coord = matrix \%*\% c(source_coord, 1), which is the same convention that
doapply.transform.mtx uses. The inverse of the transformation is never stored, see
invert.fs.transform.
Usage
fs.transform(
matrix,
space_in = NA_character_,
space_out = NA_character_,
voxel_base = NA_integer_,
src = NULL,
dst = NULL,
format = NA_character_,
source = NULL,
type = NULL,
...
)
Arguments
matrix |
4x4 numerical matrix, the transformation matrix. Required. |
space_in |
character string, the kind of coordinates the matrix maps from, one of 'voxel' (voxel indices
of a volume), 'ras' (world coordinates, right-anterior-superior in millimeters) or 'lps' (world coordinates,
left-posterior-superior in millimeters, used by ITK and ITK-based tools like ANTs). Use |
space_out |
character string, the kind of coordinates the matrix maps to, see |
voxel_base |
integer, either 0 or 1. The index of the first voxel in the coordinates the matrix consumes
and produces, i.e. 1 for the convention used by FreeSurfer and tkregister, and 0 for the one used by
NIfTI, FSL and ITK. Must be |
src |
|
dst |
|
format |
character string, the file format the transform was read from, one of 'lta', 'dat', 'xfm' or
'fslmat'. Use |
source |
|
type |
|
... |
additional named fields to store in the transform, e.g. the parsed header of the file it was read from. They are not validated and are preserved for formats that carry extra metadata. |
Value
an fs.transform instance.
Compute the matrix that maps FSL voxel coordinates of a volume to FSL world coordinates.
Description
FSL does not use the world coordinates of the image header. Its tools work in a space in which the voxel axes have unit length (the voxel sizes are divided out) and in which the first voxel axis points to the left, i.e. the transformation has a negative determinant, which is why FSL calls its images 'radiological'. For a volume whose header already uses that convention, the FSL space equals the header space; otherwise the first axis is flipped, and the origin of that axis is moved to the other end of the volume.
This function implements the mapping that both MRtrix3 (in transformconvert ... flirt_import) and
FreeSurfer (in lta_convert --infsl) apply, and it was verified against both of them on real data: the
resulting transformation matrix is identical to the one of these tools up to numerical precision, while the
plain composition of the header voxel-to-RAS matrices is not (it differs by more than 100 mm on real data).
Usage
fsl.scaled.voxel.matrix(geometry)
Arguments
geometry |
named list, the volume geometry as returned by |
Value
4x4 numerical matrix, the transformation from (zero-based) voxel indices to FSL world coordinates.
Write 3-byte integer.
Description
Write a 3-byte integer to a binary file handle.
Usage
fwrite3(filehandle, data)
Arguments
filehandle |
file handle (connection) |
data |
number to write |
Determine endianness of TRK file.
Description
Determine endianness of TRK file.
Usage
get.dti.trk.endianness(filepath)
Arguments
filepath |
character string, path to file in trk format. Gzip-compressed
files are supported as well (the compression is detected from the file
content, so a |
Value
endina character string. one of 'little' or 'big'.
Note
This function checks endiannes via the header size field of the file header, which must be 1000 for TRK files when read with correct enianness. It will stop if the file is not in TRK format, i.e., if the field is not 1000 in any endianness.
Compute MGH orientation string and direction
Description
Compute MGH orientation string and direction
Usage
get.slice.orientation(Mdc)
Arguments
Mdc |
numeric 3x3 matrix, typically from the |
Value
named list with entries: orientation_string: character string of length 3, one uppercase letter per axis. direction_name: slice direction, character string, one of 'sagittal', 'coronal', 'axial' or 'unknown'.
Get the configured maximum allocation size in bytes.
Description
Returns the maximum number of bytes that the package is allowed
to allocate when reading binary data payloads. The limit is resolved in
this order: (1) environment variable FREESURFERFORMATS_MAX_ALLOC_BYTES,
(2) R option freesurferformats.max_alloc_bytes, (3) the hard-coded
default of 2 GB. Set the limit to Inf to disable the check.
Usage
get_max_alloc_bytes()
Value
a single numeric value, the maximum allocation size in bytes.
Access a single file from the package cache by its file name.
Description
Access a single file from the package cache by its file name.
Usage
get_opt_data_filepath(filename, mustWork = TRUE)
Arguments
filename |
string. The filename of the file in the package cache. |
mustWork |
logical. Whether an error should be created if the file does not exist. If mustWork=FALSE and the file does not exist, the empty string is returned. |
Value
string. The full path to the file in the package cache or the empty string if there is no such file available. Use this in your application code to open the file.
Write data to a gifti file.
Description
Write data to a gifti file.
Usage
gifti_writer(filepath, ...)
Arguments
filepath |
path to the output gifti file |
... |
parameters passed to |
References
https://www.nitrc.org/frs/download.php/2871/GIFTI_Surface_Format.pdf
Examples
## Not run:
outfile <- tempfile(fileext = ".gii")
dataarrays <- list(rep(3.1, 3L), matrix(seq(6), nrow = 2L))
gifti_writer(outfile, dataarrays, datatype = c("NIFTI_TYPE_FLOAT32", "NIFTI_TYPE_INT32"))
## End(Not run)
Get GIFTI XML representation of data.
Description
Creates a GIFTI XML tree from your datasets (vectors and matrices). The tree can be further modified to add additional data, or written to a file as is to produce a valid GIFTI file (see gifti_xml_write).
Usage
gifti_xml(
data_array,
intent = "NIFTI_INTENT_SHAPE",
datatype = "NIFTI_TYPE_FLOAT32",
encoding = "GZipBase64Binary",
endian = "LittleEndian",
transform_matrix = NULL,
force = FALSE
)
Arguments
data_array |
list of data vectors and/or data matrices. |
intent |
vector of NIFTI intent strings for the data vectors in 'data_array' parameter, see |
datatype |
vector of NIFTI datatype strings. Example: 'NIFTI_TYPE_FLOAT32'. Should be suitable for your data. |
encoding |
vector of encoding definition strings. One of 'ASCII', 'Base64Binary', 'GZipBase64Binary'. |
endian |
vector of endian definition strings. One of 'LittleEndian' or 'BigEndian'. See |
transform_matrix |
optional, a list of transformation matrices, one for each data_array. If one of the data arrays has none, pass |
force |
logical, whether to force writing the data, even if issues like a mismatch of datatype and data values are detected. |
Value
xml tree, see xml2 package. One could modify this tree as needed using xml2 functions, e.g., add metadata.
Note
Unless you want to modify the returned tree manually, you should not need to call this function. Use gifti_writer instead.
References
See https://www.nitrc.org/frs/download.php/2871/GIFTI_Surface_Format.pdf
See Also
The example for gifti_xml_write shows how to modify the tree.
Examples
## Not run:
my_data_sets <- list(rep(3.1, 3L), matrix(seq(6) + 0.1, nrow = 2L))
transforms <- list(NA, list(
"transform_matrix" = diag(4), "data_space" = "NIFTI_XFORM_UNKNOWN",
"transformed_space" = "NIFTI_XFORM_UNKNOWN"
))
xmltree <- gifti_xml(my_data_sets, datatype = "NIFTI_TYPE_FLOAT32", transform_matrix = transforms)
# Verify that the tree is a valid GIFTI file:
gifti_xsd <- "https://www.nitrc.org/frs/download.php/158/gifti.xsd"
xml2::xml_validate(xmltree, xml2::read_xml(gifti_xsd))
## End(Not run)
Add metadata to GIFTI XML tree.
Description
Add metadata to GIFTI XML tree.
Usage
gifti_xml_add_global_metadata(xmltree, metadata_named_list, as_cdata = TRUE)
Arguments
xmltree |
XML tree from xml2 |
metadata_named_list |
named list, the metadata entries |
as_cdata |
logical, whether to wrap the value in cdata tags |
Value
the modified tree.
Note
Assumes that there already exists a global MetaData node. Also not that this is not supposed to be used for adding metadata to datarrays.
Examples
## Not run:
xmltree <- gifti_xml(list(rep(3.1, 3L), matrix(seq(6) + 0.1, nrow = 2L)))
newtree <- gifti_xml_add_global_metadata(xmltree, list("User" = "Me", "Weather" = "Great"))
gifti_xsd <- "https://www.nitrc.org/frs/download.php/158/gifti.xsd"
xml2::xml_validate(newtree, xml2::read_xml(gifti_xsd))
## End(Not run)
Write XML tree to a gifti file.
Description
Write XML tree to a gifti file.
Usage
gifti_xml_write(filepath, xmltree, options = c("as_xml", "format"))
Arguments
filepath |
path to the output gifti file |
xmltree |
XML tree from xml2 |
options |
output options passed to |
References
https://www.nitrc.org/frs/download.php/2871/GIFTI_Surface_Format.pdf
Examples
## Not run:
outfile <- tempfile(fileext = ".gii")
my_data_sets <- list(rep(3.1, 3L), matrix(seq(6) + 0.1, nrow = 2L))
xmltree <- gifti_xml(my_data_sets, datatype = "NIFTI_TYPE_FLOAT32")
# Here we add global metadata:
xmltree <- gifti_xml_add_global_metadata(xmltree, list("User" = "Me", "Day" = "Monday"))
# Validating your XML never hurts
gifti_xsd <- "https://www.nitrc.org/frs/download.php/158/gifti.xsd"
xml2::xml_validate(xmltree, xml2::read_xml(gifti_xsd))
gifti_xml_write(outfile, xmltree)
# Write your custom tree to a file.
## End(Not run)
Add a label tabel from an annotation to a GIFTI XML tree.
Description
Computes the LabelTable XML node for the given annotation and adds it to the XML tree.
Usage
giftixml_add_labeltable_from_annot(xmltree, annot)
Arguments
xmltree |
an XML tree from xml2, typically the return value from |
annot |
an fs.annotation, the included data will be used to compute the LabelTable node |
Value
XML tree from xml2, the modified tree with the LabelTable added below the root node.
Add a standard label tabel for to a GIFTI XML tree.
Description
This label table is suitable for labels in the FreeSurfer sense, i.e., if only a positive label (1) and a negative label (0) exist in the label data.
Usage
giftixml_add_labeltable_posneg(xmltree)
Arguments
xmltree |
an XML tree from xml2, typically the return value from |
Value
XML tree from xml2, the modified tree with the LabelTable added below the root node.
Compute the first row of every group in a concatenated matrix.
Description
Compute the first row of every group in a concatenated matrix.
Usage
group.start.rows(lengths)
Arguments
lengths |
integer vector, the number of rows of each group. |
Value
integer vector with one entry per group.
Check which groups have at least one point inside a box.
Description
Check which groups have at least one point inside a box.
Usage
groups.in.bbox(points, lengths, bbox)
Arguments
points |
numeric matrix with 3 columns, the concatenated points. |
lengths |
integer vector with the number of points of each group. |
bbox |
numeric vector of length 6:
|
Value
logical vector with one entry per group.
Guess whether a file is gzipped.
Description
Guess whether a file is gzipped, based on the file extension.
Usage
guess.filename.is.gzipped(filepath, gz_extensions = c(".gz", ".mgz"))
Arguments
filepath |
string. Path to a file. |
gz_extensions |
list of strings. A list of suffixes that is considered indicative for the file being gzipped. Defaults to c(".gz", ".mgz"). Case does not matter. |
Value
logical, whether this function thinks the file is gzipped.
Determine the format of a transformation file.
Description
Guess the format of a transformation file from its extension and its content. Content is needed because the extension '.mat' is used by FSL for text matrices and by ANTs/ITK for binary transformations, which have nothing in common. A file that is identified as an ITK/ANTs transformation is reported as such instead of failing with a parse error, since that format is not supported yet.
Usage
guess.transform.format(filepath)
Arguments
filepath |
character string, the full path to the transform file. |
Value
character string, the file format, one of 'xfm', 'dat', 'lta' or 'fslmat'.
Determine the format of a transformation file to write.
Description
Guess the transformation file format from the file name extension, for the formats this package can write.
Usage
guess.writable.transform.format(filepath)
Arguments
filepath |
character string, the full path of the file to write. |
Value
character string, the file format.
Check for pandoc availability on system.
Description
Check for pandoc availability on system.
Usage
has_pandoc()
Value
logical, whether Pandoc is available.
Check which rows of a matrix consist of infinite values only.
Description
Check which rows of a matrix consist of infinite values only.
Usage
infinite.rows(mat)
Arguments
mat |
numeric matrix. |
Value
logical vector with one entry per row.
Convert 32 bit integer to RGB color as described in Brainvoyager SRF file spec.
Description
Convert 32 bit integer to RGB color as described in Brainvoyager SRF file spec.
Usage
int.to.col.brainvoyager(int_val)
Arguments
int_val |
the 32 bit integer |
Value
an rgb color
Build the affine that undoes an orientation transform.
Description
This is the equivalent of
nibabel.orientations.inv_ornt_aff(): given an orientation and the
shape of the array it was applied to, it returns the affine that maps
coordinates in the transformed space back to coordinates in the original
space.
Usage
inv.ornt.aff(ornt, shape)
Arguments
ornt |
numeric matrix with 2 columns, the orientation. |
shape |
numeric vector, the shape (dimensions) of the array. |
Value
a 4x4 numeric matrix.
Invert a transformation.
Description
Compute the transformation that undoes the given one, i.e. the one that maps the target coordinates back to the source coordinates. The source and target of the result are swapped, along with the coordinate spaces, and the matrix is inverted. A transformation is never stored inverted, use this function when you need the reverse mapping.
Usage
invert.fs.transform(tf)
Arguments
tf |
an |
Value
an fs.transform instance that maps from the target of tf back to its source.
Note
The format-specific fields of tf (e.g. the parsed header and the volume info of an LTA file, or the
intensity of a register.dat file) describe the file that tf was read from and are therefore copied to the
result unchanged. They are metadata, not part of the mapping.
See Also
Other header coordinate space:
is.fs.transform(),
mghheader.is.ras.valid(),
mghheader.ras2vox(),
mghheader.ras2vox.tkreg(),
mghheader.scanner2tkreg(),
mghheader.tkreg2scanner(),
mghheader.vox2ras(),
mghheader.vox2ras.tkreg(),
print.fs.transform(),
read.fs.transform(),
read.fs.transform.dat(),
read.fs.transform.fslmat(),
read.fs.transform.itk(),
read.fs.transform.lta(),
read.fs.transform.xfm(),
sm0to1(),
sm1to0(),
summary.fs.transform(),
transform2lps(),
transform2ras(),
transform2voxel(),
transform2world(),
write.fs.transform(),
write.fs.transform.dat(),
write.fs.transform.fslmat(),
write.fs.transform.itk(),
write.fs.transform.lta(),
write.fs.transform.xfm()
Examples
tf <- read.fs.transform(system.file("extdata", "talairach.xfm",
package = "freesurferformats", mustWork = TRUE
))
tf_back <- invert.fs.transform(tf)
tf_back$space_in # the spaces are swapped
max(abs(tf_back$matrix %*% tf$matrix - diag(4))) # the identity
Determine the orientation of an affine's input axes.
Description
For each of the 3 input (voxel) axes, determines which output
(world) axis it corresponds to and whether it is flipped. This is the
simplified equivalent of nibabel.orientations.io_orientation(): the
dominant output axis of every input axis is used, with output axes removed
from consideration once they have been assigned. nibabel additionally
applies a polar decomposition first, which only matters for affines that
contain shear.
Usage
io.orientation(affine)
Arguments
affine |
4x4 numeric matrix. |
Value
numeric matrix with 3 rows and 2 columns, as returned by
io.orientation. Row i holds the 0-based output axis index and
the direction (+1 or -1) of input axis i.
Check whether a file is an ANALYZE 7.5 file.
Description
Check whether a file is an ANALYZE 7.5 file.
Usage
is.analyze.file(filepath)
Arguments
filepath |
character string, the path to a |
Value
logical, whether the 348 byte header is an ANALYZE 7.5 header. This is the case when the header contains
neither of the two NIFTI v1 magic strings, i.e. when the magic is empty. Files that use the ni1 magic are
NIFTI v1 pair files, see read.nifti1.header, and files with the n+1 magic are single file NIFTI
v1 files.
Note
Note that this function returns TRUE for any two-file header that does not carry a NIFTI magic, which is
what "ANALYZE 7.5" means in practice: these files were written by ANALYZE itself, by SPM, by AFNI or by
FreeSurfer. Only the fields of the ANALYZE specification are defined for them, but SPM stores extra
information in fields that ANALYZE leaves unused, see read.fs.volume.analyze.
A file path that does not describe an existing pair file (for example a single file NIFTI image, or a
file that does not exist) returns FALSE rather than an error.
Examples
hdrfile <- system.file("extdata", "analyze", "tiny_u8.hdr",
package = "freesurferformats", mustWork = TRUE
)
is.analyze.file(hdrfile)
Check whether object is a bvsmp instance.
Description
Check whether object is a bvsmp instance.
Usage
is.bvsmp(x)
Arguments
x |
any |
Value
TRUE if its argument is an bvsmp instane (that is, has "bvsmp" amongst its classes) and FALSE otherwise.
Check whether object is an fs.annot
Description
Check whether object is an fs.annot
Usage
is.fs.annot(x)
Arguments
x |
any |
Value
TRUE if its argument is a brain surface annotation (that is, has "fs.annot" amongst its classes) and FALSE otherwise.
Check whether object is an fs.label
Description
Check whether object is an fs.label
Usage
is.fs.label(x)
Arguments
x |
any |
Value
TRUE if its argument is a brain surface label (that is, has fs.label amongst its classes) and FALSE otherwise.
Check whether object is an fs.surface
Description
Check whether object is an fs.surface
Usage
is.fs.surface(x)
Arguments
x |
any |
Value
TRUE if its argument is a brain surface (that is, has "fs.surface" amongst its classes) and FALSE otherwise.
Check whether an object is an fs.tracts instance.
Description
Check whether an object is an fs.tracts instance.
Usage
is.fs.tracts(x)
Arguments
x |
any R object. |
Value
logical, TRUE if x is an fs.tracts instance.
Examples
is.fs.tracts("not tracts");
Check whether an object is an fs.transform instance.
Description
Check whether an object is an fs.transform instance.
Usage
is.fs.transform(x)
Arguments
x |
any object. |
Value
logical, whether x is an fs.transform instance.
See Also
Other header coordinate space:
invert.fs.transform(),
mghheader.is.ras.valid(),
mghheader.ras2vox(),
mghheader.ras2vox.tkreg(),
mghheader.scanner2tkreg(),
mghheader.tkreg2scanner(),
mghheader.vox2ras(),
mghheader.vox2ras.tkreg(),
print.fs.transform(),
read.fs.transform(),
read.fs.transform.dat(),
read.fs.transform.fslmat(),
read.fs.transform.itk(),
read.fs.transform.lta(),
read.fs.transform.xfm(),
sm0to1(),
sm1to0(),
summary.fs.transform(),
transform2lps(),
transform2ras(),
transform2voxel(),
transform2world(),
write.fs.transform(),
write.fs.transform.dat(),
write.fs.transform.fslmat(),
write.fs.transform.itk(),
write.fs.transform.lta(),
write.fs.transform.xfm()
Examples
tf <- read.fs.transform(system.file("extdata", "talairach.xfm",
package = "freesurferformats", mustWork = TRUE
))
is.fs.transform(tf)
is.fs.transform("no transform")
Check whether object is an fs.volume
Description
Check whether object is an fs.volume
Usage
is.fs.volume(x)
Arguments
x |
any |
Value
TRUE if its argument is a brain volume (that is, has "fs.volume" amongst its classes) and FALSE otherwise.
Check whether a file is gzip-compressed, based on its magic bytes.
Description
Uses the gzip magic number (0x1f 0x8b) rather than the file
extension, since files are regularly renamed or stripped of their
extension. Reading a gzip-compressed payload from a plain file()
connection silently produces garbage.
Usage
is.gzip.file(filepath)
Arguments
filepath |
character string, path to the file to check. |
Value
logical, TRUE if the file starts with the gzip magic number.
Check whether a matrix is (close to) the identity.
Description
Check whether a matrix is (close to) the identity.
Usage
is.identity.matrix(mat, tolerance = 1e-06)
Arguments
mat |
numeric matrix. |
tolerance |
numeric, the tolerance for the comparison. |
Value
logical.
Check whether object is an mghheader
Description
Check whether object is an mghheader
Usage
is.mghheader(x)
Arguments
x |
any |
Value
TRUE if its argument is an MGH header (that is, has "mghheader" amongst its classes) and FALSE otherwise.
Check whether a header line terminates the MRtrix header.
Description
Check whether a header line terminates the MRtrix header.
Usage
is.mrtrix.end.line(line)
Arguments
line |
character string, a single header line. |
Value
logical, TRUE if the line reads 'END' (ignoring surrounding whitespace and a possible DOS line ending).
Read the value of a key of an ITK transform file.
Description
ITK text transforms store their content as 'key: value' lines, e.g. 'Transform: AffineTransform_float_3_3'. This helper returns the value of such an entry.
Usage
itk.key.value(lines, key)
Arguments
lines |
character vector, the key/value lines of the file. |
key |
character string, the name of the entry, e.g. 'Transform'. |
Value
NULL if the entry does not exist, its value as a character string otherwise.
Read a numerical entry of an ITK transform file.
Description
Read a numerical entry of an ITK transform file.
Usage
itk.numeric.value(lines, key, filepath)
Arguments
lines |
character vector, the key/value lines of the file. |
key |
character string, the name of the entry, e.g. 'Parameters'. |
filepath |
character string, the path of the file, used in error messages only. |
Value
numerical vector, the values of the entry. It is an error if the entry is missing or holds no numbers.
Number of tracts in an fs.tracts instance.
Description
Number of tracts in an fs.tracts instance.
Usage
## S3 method for class 'fs.tracts'
length(x)
Arguments
x |
an |
Value
integer, the number of tracts.
Split a string into fixed-length parts.
Description
Split a string into fixed-length parts.
Usage
linesplit.fixed(
cline,
length_per_part,
num_parts_expected = NULL,
error_tag = NULL
)
Arguments
cline |
character string, the input line |
length_per_part |
integer, number of characters per part |
num_parts_expected |
integer, the number of parts. Leave at NULL if this is not known. |
error_tag |
optional character string, how to identify the line in a parsing error message. Could be the line number, or whatever. Only relevant if 'num_parts_expected' is not matched. |
Get file names available in package cache.
Description
Get file names of optional data files which are available in the local package cache. You can access these files with get_optional_data_file().
Usage
list_opt_data()
Value
vector of strings. The file names available, relative to the package cache.
Write the volume info section of an LTA file.
Description
The volume info section records the geometry of one of the two volumes an LTA file relates:
its dimensions, voxel sizes and the direction vectors and center that describe its RAS space. The geometry
is written from a volume descriptor, and the direction vectors are the columns of its voxel-to-RAS matrix
while the center is the RAS coordinate of voxel index dim/2, which is what FreeSurfer records there.
Usage
lta.volume.info.lines(descriptor, section_name)
Arguments
descriptor |
|
section_name |
character string, either 'src' or 'dst'. |
Value
character vector, the lines of the section.
Compute quaternion representation of a rotation from a 4x4 rotation matrix.
Description
Compute quaternion representation of a rotation from a 4x4 rotation matrix.
Usage
m44_to_quaternion(m)
Arguments
m |
the input 4x4 matrix encoding the rotation, with homogeneous column |
Value
numeric vector of length 4, the quaternion representation (qw, qx, qy, qz).
Merge two bounding boxes.
Description
Merge two bounding boxes.
Usage
## S3 method for class 'bbox'
merge(bbox1, bbox2)
Arguments
bbox1 |
numeric vector of length 6 or NULL. |
bbox2 |
numeric vector of length 6 or NULL. |
Value
numeric vector of length 6, the union of the two boxes.
Compute the normals of the triangles of a mesh.
Description
The normal of a triangle is the unit vector orthogonal to its plane, it is computed as the normalized cross product of two of its edges. The STL format stores one normal per triangle, and the value is computed from the geometry instead of being taken from the data, since a mesh in index representation does not store normals at all.
Usage
mesh.face.normals(vertex_coords, faces)
Arguments
vertex_coords |
n x 3 matrix of doubles, the vertex coordinates. |
faces |
n x 3 matrix of integers, the vertex indices of the triangles. |
Value
n x 3 matrix of doubles, the normalized normal of every face. Rows of degenerate triangles (whose 3 vertices lie on one line, which includes triangles with repeated vertices) are zero vectors, since such triangles have no plane and hence no normal.
Determine whether an MGH volume is conformed.
Description
In the FreeSurfer sense, conformed means that the volume is in coronal primary slice direction, has dimensions 256x256x256 and a voxel size of 1 mm in all 3 directions. The slice direction can only be determined if the header contains RAS information, if it does not, the volume is not conformed.
Usage
mgh.is.conformed(mgh_header, voxel_size_tolerance = 1e-04)
Arguments
mgh_header |
Header of the mgh datastructure, as returned by |
voxel_size_tolerance |
double, the tolerance to accept when comparing the voxel size to the required value of |
Value
logical, whether the volume is conformed.
Constructor to init MGH header instance.
Description
Constructor to init MGH header instance.
Usage
mghheader(dims, mri_dtype_code)
Arguments
dims |
integer vector of length 4, the header dimensions. Example: |
mri_dtype_code |
integer, a valid MRI datatype. See |
Value
a named list representing the header
Compute RAS coords of center voxel.
Description
Compute RAS coords of center voxel.
Usage
mghheader.centervoxelRAS.from.firstvoxelRAS(header, first_voxel_RAS)
Arguments
header |
Header of the mgh datastructure, as returned by |
first_voxel_RAS |
numerical vector of length 3, the RAS coordinate of the first voxel in the volume. The first voxel is the voxel with |
Value
numerical vector of length 3, the RAS coordinate of the center voxel. Also known as CRAS or center RAS.
Compute MGH volume orientation string.
Description
Compute MGH volume orientation string.
Usage
mghheader.crs.orientation(header)
Arguments
header |
Header of the mgh datastructure, as returned by |
Value
character string of length 3, one uppercase letter per axis. Each of the three position is a letter from the alphabet: LRISAP?. The meaning is L for left, R for right, I for inferior, S for superior, P for posterior, A for anterior. If the direction cannot be computed, all three characters are ? for unknown. Of course, each axis (L/R, I/S, A/P) is only represented once in the string.
Determine whether an MGH volume is conformed.
Description
In the FreeSurfer sense, conformed means that the volume is in coronal primary slice direction, has dimensions 256x256x256 and a voxel size of 1 mm in all 3 directions. The slice direction can only be determined if the header contains RAS information, if it does not, the volume is not conformed.
Usage
mghheader.is.conformed(header)
Arguments
header |
Header of the mgh datastructure, as returned by |
Value
logical, whether the volume is conformed.
Check whether header contains valid ras information
Description
Check whether header contains valid ras information
Usage
mghheader.is.ras.valid(header)
Arguments
header |
mgh header or |
Value
logical, whether header contains valid ras information (according to the ras_good_flag).
See Also
Other header coordinate space:
invert.fs.transform(),
is.fs.transform(),
mghheader.ras2vox(),
mghheader.ras2vox.tkreg(),
mghheader.scanner2tkreg(),
mghheader.tkreg2scanner(),
mghheader.vox2ras(),
mghheader.vox2ras.tkreg(),
print.fs.transform(),
read.fs.transform(),
read.fs.transform.dat(),
read.fs.transform.fslmat(),
read.fs.transform.itk(),
read.fs.transform.lta(),
read.fs.transform.xfm(),
sm0to1(),
sm1to0(),
summary.fs.transform(),
transform2lps(),
transform2ras(),
transform2voxel(),
transform2world(),
write.fs.transform(),
write.fs.transform.dat(),
write.fs.transform.fslmat(),
write.fs.transform.itk(),
write.fs.transform.lta(),
write.fs.transform.xfm()
Examples
brain_image <- system.file("extdata", "brain.mgz",
package = "freesurferformats",
mustWork = TRUE
)
vdh <- read.fs.mgh(brain_image, with_header = TRUE)
mghheader.is.ras.valid(vdh$header)
Compute MGH primary slice direction
Description
Compute MGH primary slice direction
Usage
mghheader.primary.slice.direction(header)
Arguments
header |
Header of the mgh datastructure, as returned by |
Value
character string, the slice direction. One of 'sagittal', 'coronal', 'axial' or 'unknown'.
Compute ras2vox matrix from basic MGH header fields.
Description
This is also known as the 'scanner' or 'native' ras2vox. It is the inverse of the respective vox2ras, see mghheader.vox2ras.
Usage
mghheader.ras2vox(header)
Arguments
header |
the MGH header |
Value
4x4 numerical matrix, the transformation matrix
See Also
Other header coordinate space:
invert.fs.transform(),
is.fs.transform(),
mghheader.is.ras.valid(),
mghheader.ras2vox.tkreg(),
mghheader.scanner2tkreg(),
mghheader.tkreg2scanner(),
mghheader.vox2ras(),
mghheader.vox2ras.tkreg(),
print.fs.transform(),
read.fs.transform(),
read.fs.transform.dat(),
read.fs.transform.fslmat(),
read.fs.transform.itk(),
read.fs.transform.lta(),
read.fs.transform.xfm(),
sm0to1(),
sm1to0(),
summary.fs.transform(),
transform2lps(),
transform2ras(),
transform2voxel(),
transform2world(),
write.fs.transform(),
write.fs.transform.dat(),
write.fs.transform.fslmat(),
write.fs.transform.itk(),
write.fs.transform.lta(),
write.fs.transform.xfm()
Examples
brain_image <- system.file("extdata", "brain.mgz",
package = "freesurferformats",
mustWork = TRUE
)
vdh <- read.fs.mgh(brain_image, with_header = TRUE)
mghheader.ras2vox(vdh$header)
Compute ras2vox-tkreg matrix from basic MGH header fields.
Description
This is also known as the 'tkreg' ras2vox. It is the inverse of the respective vox2ras, see mghheader.vox2ras.tkreg.
Usage
mghheader.ras2vox.tkreg(header)
Arguments
header |
the MGH header |
Value
4x4 numerical matrix, the transformation matrix
See Also
Other header coordinate space:
invert.fs.transform(),
is.fs.transform(),
mghheader.is.ras.valid(),
mghheader.ras2vox(),
mghheader.scanner2tkreg(),
mghheader.tkreg2scanner(),
mghheader.vox2ras(),
mghheader.vox2ras.tkreg(),
print.fs.transform(),
read.fs.transform(),
read.fs.transform.dat(),
read.fs.transform.fslmat(),
read.fs.transform.itk(),
read.fs.transform.lta(),
read.fs.transform.xfm(),
sm0to1(),
sm1to0(),
summary.fs.transform(),
transform2lps(),
transform2ras(),
transform2voxel(),
transform2world(),
write.fs.transform(),
write.fs.transform.dat(),
write.fs.transform.fslmat(),
write.fs.transform.itk(),
write.fs.transform.lta(),
write.fs.transform.xfm()
Examples
brain_image <- system.file("extdata", "brain.mgz",
package = "freesurferformats",
mustWork = TRUE
)
vdh <- read.fs.mgh(brain_image, with_header = TRUE)
mghheader.ras2vox.tkreg(vdh$header)
Compute scanner-RAS 2 tkreg-RAS matrix from basic MGH header fields.
Description
This is also known as the 'scanner2tkreg' matrix. Note that this is a RAS-to-RAS matrix. It is the inverse of the 'tkreg2scanner' matrix, see mghheader.tkreg2scanner.
Usage
mghheader.scanner2tkreg(header)
Arguments
header |
the MGH header |
Value
4x4 numerical matrix, the transformation matrix
See Also
Other header coordinate space:
invert.fs.transform(),
is.fs.transform(),
mghheader.is.ras.valid(),
mghheader.ras2vox(),
mghheader.ras2vox.tkreg(),
mghheader.tkreg2scanner(),
mghheader.vox2ras(),
mghheader.vox2ras.tkreg(),
print.fs.transform(),
read.fs.transform(),
read.fs.transform.dat(),
read.fs.transform.fslmat(),
read.fs.transform.itk(),
read.fs.transform.lta(),
read.fs.transform.xfm(),
sm0to1(),
sm1to0(),
summary.fs.transform(),
transform2lps(),
transform2ras(),
transform2voxel(),
transform2world(),
write.fs.transform(),
write.fs.transform.dat(),
write.fs.transform.fslmat(),
write.fs.transform.itk(),
write.fs.transform.lta(),
write.fs.transform.xfm()
Examples
brain_image <- system.file("extdata", "brain.mgz",
package = "freesurferformats",
mustWork = TRUE
)
vdh <- read.fs.mgh(brain_image, with_header = TRUE)
mghheader.scanner2tkreg(vdh$header)
Compute tkreg-RAS to scanner-RAS matrix from basic MGH header fields.
Description
This is also known as the 'tkreg2scanner' matrix. Note that this is a RAS-to-RAS matrix. It is the inverse of the 'scanner2tkreg' matrix, see mghheader.scanner2tkreg.
Usage
mghheader.tkreg2scanner(header)
Arguments
header |
the MGH header |
Value
4x4 numerical matrix, the transformation matrix
See Also
Other header coordinate space:
invert.fs.transform(),
is.fs.transform(),
mghheader.is.ras.valid(),
mghheader.ras2vox(),
mghheader.ras2vox.tkreg(),
mghheader.scanner2tkreg(),
mghheader.vox2ras(),
mghheader.vox2ras.tkreg(),
print.fs.transform(),
read.fs.transform(),
read.fs.transform.dat(),
read.fs.transform.fslmat(),
read.fs.transform.itk(),
read.fs.transform.lta(),
read.fs.transform.xfm(),
sm0to1(),
sm1to0(),
summary.fs.transform(),
transform2lps(),
transform2ras(),
transform2voxel(),
transform2world(),
write.fs.transform(),
write.fs.transform.dat(),
write.fs.transform.fslmat(),
write.fs.transform.itk(),
write.fs.transform.lta(),
write.fs.transform.xfm()
Examples
brain_image <- system.file("extdata", "brain.mgz",
package = "freesurferformats",
mustWork = TRUE
)
vdh <- read.fs.mgh(brain_image, with_header = TRUE)
mghheader.tkreg2scanner(vdh$header)
Update mghheader fields from vox2ras matrix.
Description
Update mghheader fields from vox2ras matrix.
Usage
mghheader.update.from.vox2ras(header, vox2ras)
Arguments
header |
Header of the mgh datastructure, as returned by |
vox2ras |
4x4 numerical matrix, the vox2ras transformation matrix. |
Value
a named list representing the header
Compute vox2ras matrix from basic MGH header fields.
Description
This is also known as the 'scanner' or 'native' vox2ras. It is the inverse of the respective ras2vox, see mghheader.ras2vox.
Usage
mghheader.vox2ras(header)
Arguments
header |
the MGH header |
Value
4x4 numerical matrix, the transformation matrix
See Also
Other header coordinate space:
invert.fs.transform(),
is.fs.transform(),
mghheader.is.ras.valid(),
mghheader.ras2vox(),
mghheader.ras2vox.tkreg(),
mghheader.scanner2tkreg(),
mghheader.tkreg2scanner(),
mghheader.vox2ras.tkreg(),
print.fs.transform(),
read.fs.transform(),
read.fs.transform.dat(),
read.fs.transform.fslmat(),
read.fs.transform.itk(),
read.fs.transform.lta(),
read.fs.transform.xfm(),
sm0to1(),
sm1to0(),
summary.fs.transform(),
transform2lps(),
transform2ras(),
transform2voxel(),
transform2world(),
write.fs.transform(),
write.fs.transform.dat(),
write.fs.transform.fslmat(),
write.fs.transform.itk(),
write.fs.transform.lta(),
write.fs.transform.xfm()
Examples
brain_image <- system.file("extdata", "brain.mgz",
package = "freesurferformats",
mustWork = TRUE
)
vdh <- read.fs.mgh(brain_image, with_header = TRUE)
mghheader.vox2ras(vdh$header)
Compute vox2ras-tkreg matrix from basic MGH header fields.
Description
This is also known as the 'tkreg' vox2ras. It is the inverse of the respective ras2vox, see mghheader.ras2vox.tkreg.
Usage
mghheader.vox2ras.tkreg(header)
Arguments
header |
the MGH header |
Value
4x4 numerical matrix, the transformation matrix
See Also
Other header coordinate space:
invert.fs.transform(),
is.fs.transform(),
mghheader.is.ras.valid(),
mghheader.ras2vox(),
mghheader.ras2vox.tkreg(),
mghheader.scanner2tkreg(),
mghheader.tkreg2scanner(),
mghheader.vox2ras(),
print.fs.transform(),
read.fs.transform(),
read.fs.transform.dat(),
read.fs.transform.fslmat(),
read.fs.transform.itk(),
read.fs.transform.lta(),
read.fs.transform.xfm(),
sm0to1(),
sm1to0(),
summary.fs.transform(),
transform2lps(),
transform2ras(),
transform2voxel(),
transform2world(),
write.fs.transform(),
write.fs.transform.dat(),
write.fs.transform.fslmat(),
write.fs.transform.itk(),
write.fs.transform.lta(),
write.fs.transform.xfm()
Examples
brain_image <- system.file("extdata", "brain.mgz",
package = "freesurferformats",
mustWork = TRUE
)
vdh <- read.fs.mgh(brain_image, with_header = TRUE)
mghheader.vox2ras.tkreg(vdh$header)
Compute vox2vox matrix between two volumes.
Description
Compute vox2vox matrix between two volumes.
Usage
mghheader.vox2vox(header_from, header_to)
Arguments
header_from |
the MGH header of the source volume |
header_to |
the MGH header of the target volume |
Value
4x4 numerical matrix, the transformation matrix
Get fsaverage (MNI305) to MNI152 transformation matrix.
Description
The uses the 4x4 matrix from the FreeSurfer CoordinateSystems documentation.
Usage
mni152reg()
Note
There are better ways to achieve this transformation than using this matrix, see Wu et al., 'Accurate nonlinear mapping between MNI volumetric and FreeSurfer surface coordinate system', Hum Brain Mapp. 2018 Sep; 39(9): 3793–3808. doi: 10.1002/hbm.24213. The mentioned method is available in R from the 'regfusionr' package (GitHub only atom, not on CRAN).
Examples
coords_tf <- doapply.transform.mtx(c(10.0, -20.0, 35.0), mni152reg())
coords_tf
# 10.695, -18.409, 36.137
doapply.transform.mtx(coords_tf, solve(mni152reg()))
Get size of MRI dtype in bytes.
Description
Get size of MRI dtype in bytes.
Usage
mri_dtype_numbytes(mri_dtype_code)
Arguments
mri_dtype_code |
integer, the MRI data type code. See |
Value
integer, the number of bytes
Create an iterator over the tracts of an MRtrix TCK or TSF file.
Description
Create an iterator over the tracts of an MRtrix TCK or TSF file.
Usage
mrtrix.track.iterator(
filepath,
skip_tracks = 0L,
bbox = NULL,
chunk_values = 4e+06
)
Arguments
filepath |
character string, path to the file. |
skip_tracks |
integer, the number of tracts to skip. |
bbox |
numeric vector of length 6 or NULL, a bounding box, see
|
chunk_values |
integer, the number of payload values to read per chunk. This only affects the peak memory usage and the I/O granularity of the iterator, and is rarely needed. For TRK files it is ignored, since those records are read one at a time. |
Value
the iterator environment.
Compute the next capacity for a growing result buffer.
Description
Validates that the data actually needed fits into the configured allocation limit, then returns the new buffer capacity to allocate. The capacity grows geometrically to keep the number of reallocations logarithmic, but it is capped at the limit: an overshoot of the growth must not make a read fail that would have fit into memory, and it must not exceed the limit either.
Usage
next.buffer.capacity(needed, capacity, bytes_per_elem = 8, label = NULL)
Arguments
needed |
numeric, the number of rows that the buffer must hold. |
capacity |
numeric, the current capacity. |
bytes_per_elem |
numeric, bytes per row (for integer vectors this is the size of a single element). |
label |
character string or NULL, description used in error messages. |
Value
numeric, the new capacity.
Create NIFTI v1 header suitable for given data.
Description
Create NIFTI v1 header suitable for given data.
Usage
ni1header.for.data(niidata, allow_fshack = FALSE, pair = FALSE)
Arguments
niidata |
array of numeric (integer or double) data, can have up to 7 dimensions. |
allow_fshack |
logical, whether to allow data in which the first dimension is larger than 32767, and use the FreeSurfer NIFTI v1 hack to support his. The hack will be used only if needed. WARNING: Files written with the hack do not conform to the NIFTI v1 standard and will not be read correctly by most software. All FreeSurfer tools and the Python 'nibabel' module support it. |
pair |
logical, whether the header should describe a NIFTI v1 pair (a |
Value
a NIFTI v1 header (see ni1header.template) in which the datatype, bitpix, dim and dim_raw fields have been set to values suitable for the given data. Feel free to change the other fields.
Create a template NIFTI v1 header. You will have to adapt it for your use case.
Description
Create a template NIFTI v1 header. You will have to adapt it for your use case.
Usage
ni1header.template(pair = FALSE)
Arguments
pair |
logical, whether the template describes a NIFTI v1 pair file (a |
Value
named list, the NIFTI v1 header. All fields are present and filled with values of a proper type. Whether or not they make sense is up to you, but you will most likely have to adapt at least the following fields to your data: dim_raw, datatype, bitpix.
Note
Commonly used data type settings are: for signed integers datatype = 8L and bitpix = 32L; for floats datatype = 16L and bitpix = 32L. See the NIFTI v1 standard for more options. You may want to call ni1header.for.data instead of this function.
See Also
Create NIFTI v2 header suitable for given data.
Description
Create NIFTI v2 header suitable for given data.
Usage
ni2header.for.data(niidata)
Arguments
niidata |
array of numeric (integer or double) data, can have up to 7 dimensions. |
Value
a NIFTI v2 header (see ni2header.template) in which the datatype, bitpix, dim and dim_raw fields have been set to values suitable for the given data. Feel free to change the other fields.
Create a template NIFTI v2 header. You will have to adapt it for your use case.
Description
Create a template NIFTI v2 header. You will have to adapt it for your use case.
Usage
ni2header.template()
Value
named list, the NIFTI v2 header. All fields are present and filled with values of a proper type. Whether or not they make sense is up to you, but you will most likely have to adapt at least the following fields to your data: dim_raw, datatype, bitpix.
Note
Commonly used data type settings are: for signed integers datatype = 8L and bitpix = 32L; for floats datatype = 16L and bitpix = 32L. See the NIFTI v2 standard for more options. You may want to call ni2header.for.data instead of this function.
The 'magic' field of a NIFTI v2 file must be the string 'n+2'. Versions of this package before 1.1.0 wrote the NIFTI v1 magic 'n+1' here, which violates the standard and makes other software (nibabel, Connectome Workbench) refuse the file; write.nifti2 writes the full 8 byte magic of the standard.
See Also
Compute data dimensions from the 'dim' field of the NIFTI (v1 or v2) header.
Description
Compute data dimensions from the 'dim' field of the NIFTI (v1 or v2) header.
Usage
nifti.datadim.from.dimfield(dimfield)
Arguments
dimfield |
integer vector of length 8, the |
Value
integer vector of length <= 7. The lengths of the used data dimensions. The 'dim' field always has length 8, and the first entry is the number of actually used dimensions. The return value is constructed by stripping the first field and returning the used fields.
See Also
Other NIFTI helper functions:
nifti.datadim.to.dimfield()
Examples
nifti.datadim.from.dimfield(c(3, 256, 256, 256, 1, 1, 1, 1))
Compute NIFTI dim field for data dimension.
Description
Compute NIFTI dim field for data dimension.
Usage
nifti.datadim.to.dimfield(datadim)
Arguments
datadim |
integer vector, the result of calling |
Value
NIFTI header dim field, an integer vector of length 8
See Also
Other NIFTI helper functions:
nifti.datadim.from.dimfield()
Examples
nifti.datadim.to.dimfield(c(256, 256, 256))
Compute NIFTI v1 data type info from datatype and bitpix header field.
Description
Compute NIFTI v1 data type info from datatype and bitpix header field.
Usage
nifti.dtype.info(datatype, bitpix)
Arguments
datatype |
integer, the |
bitpix |
integer, the |
Value
named list with entries: mri_dtype: the MRI data type, as used by FreeSurfer for MGH files, r_dtype: the R data type, size: the number of bytes per value, signed: logical, whether the values are signed (only meaningful for integer types, NA for floating point types) and is_float: logical, whether the type is a floating point type.
Note
The signed entry matters for reading the data: an unsigned 8 bit value of 200 is read as -56 if it is read as a signed value, which is a silent change of the data. See read.nifti.values.
Compute the 'datatype' and 'bitpix' fields used in the NIFTI1 header from an MGH/MGZ datatype code.
Description
Compute the 'datatype' and 'bitpix' fields used in the NIFTI1 header from an MGH/MGZ datatype code.
Usage
nifti.dtypebitpix.info.from.mgh.dtype(mgh_dtype_code)
Arguments
mgh_dtype_code |
integer, the MGH/MGZ datatype code (as returned by |
Value
named list with entries: datatype and bitpix containing the translated data for the respective NIfTI-1 header fields.
Note
This is useful to compute a NIFTI v1 header from an MGH header.
Check whether vector has expected length.
Description
Check whether vector has expected length.
Usage
nifti.field.check.length(niiheader, fields, dlength)
Arguments
niiheader |
named list, representing a NIFTI v1 or v2 header |
fields |
vector of character string, the field names to check |
dlength |
integer, the expected length of all fields |
Value
logical, whether the checks were okay
Check whether character string fields have less than or equal to expected length.
Description
Check whether character string fields have less than or equal to expected length.
Usage
nifti.field.check.nchar.max(niiheader, fields, dlength)
Arguments
niiheader |
named list, representing a NIFTI v1 or v2 header |
fields |
vector of character string, the field names to check |
dlength |
integer, the max length of all fields |
Value
logical, whether the checks were okay
Determine whether a NIFTI file uses the FreeSurfer hack.
Description
Determine whether a NIFTI file uses the FreeSurfer hack.
Usage
nifti.file.uses.fshack(filepath)
Arguments
filepath |
path to a NIFTI v1 file (single file version), which can contain the FreeSurfer hack. |
Value
logical, whether the file header contains the FreeSurfer format hack. See read.nifti1.header for details. This function detects NIFTI v2 files, but as they cannot contain the hack, it will always return FALSE for them.
Note
Applying this function to files which are not in NIFTI format will result in an error. See nifti.file.version to determine whether a file is a NIFTI file.
Determine NIFTI file version information and whether file is a NIFTI file.
Description
Determine NIFTI file version information and whether file is a NIFTI file.
Usage
nifti.file.version(filepath)
Arguments
filepath |
path to a file in NIFTI v1 or v2 format. |
Value
integer, the NIFTI file version. One if 1 for NIFTI v1 files, 2 for NIFTI v2 files, or NULL if the file is not a NIFTI file.
Perform basic sanity checks on NIFTI header data. These are in no way meant to be exhaustive.
Description
Perform basic sanity checks on NIFTI header data. These are in no way meant to be exhaustive.
Usage
nifti.header.check(niiheader, nifti_version = 1L)
Arguments
niiheader |
named list, the NIFTI header. |
nifti_version |
integer, one of 1L or 2L. The NIFTI format version. |
Value
logical, whether the check was okay
Compute the voxel-to-RAS matrix from the geometry fields of a NIFTI v1 header.
Description
The NIFTI v1 header can store up to two descriptions of the mapping from voxel indices to world
coordinates: the sform (a full affine matrix in the srow_x, srow_y and srow_z fields) and the qform (a
rotation, given as a quaternion, plus a translation, given in the quoffset fields). Each of them is only valid
if the corresponding code field is not zero, and the sform takes precedence over the qform if both are
present. This is the same rule that the NIFTI standard defines and that other implementations (nibabel,
oro.nifti) follow.
Usage
nifti.header.to.vox2ras(niiheader)
Arguments
niiheader |
named list, a NIFTI v1 header as returned by |
Value
a 4x4 numeric matrix (the voxel-to-RAS transformation), or NULL if the header contains neither an
sform nor a qform. The matrix implements the NIFTI convention that the rotation of the qform applies to
the left of the scaled voxel axes and that the third axis is flipped if the qfac field (pix_dim[1]) is
negative.
Note
This is a header based re-implementation of the geometry computation of read.fs.volume.nii,
which reads an oro.nifti instance. The two are compared against each other in the unit tests, and against
nibabel in dev_tools/check_analyze_conversion.R.
Read the header information and the data of a NIFTI file into a plain list.
Description
This is the file reading part of read.fs.volume.nii. The returned list uses plain
entry names instead of the oro.nifti slot names, so that no code outside of this file depends on the
name of an oro.nifti slot. The data scaling fields of the NIFTI header are applied, see the details in
read.fs.volume.nii.
Usage
nifti.info.from.file(filepath)
Arguments
filepath |
character string, the path to a NIFTI v1 or v2 file. The file extension may be omitted, see
|
Value
named list with the NIFTI header fields magic, datatype, bitpix, dim (the 8 entry NIFTI
dim field, its first entry the number of used dimensions), glmin (the field used to store the true
dimension for the FreeSurfer hack files, -1 for NIFTI v2 files, which do not have it), scl_slope,
scl_inter, xyzt_units, pixdim (the 8 entry NIFTI pixdim field, its first entry qfac),
sform_code, srow_x, srow_y, srow_z, qform_code, quatern_b, quatern_c, quatern_d,
qoffset_x, qoffset_y, qoffset_z, and the data array in data.
See Also
Extract the header information and the data of an oro.nifti instance into a plain list.
Description
Extract the header information and the data of an oro.nifti instance into a plain list.
Usage
nifti.info.from.oro.instance(nifti_img)
Arguments
nifti_img |
an instance of class |
Value
named list, see nifti.info.from.file.
Note
The data scaling fields of the instance are not applied here, they are expected to be applied already:
instances read by oro.nifti::readNIfTI are rescaled unless rescale_data = FALSE was used.
See Also
Resolve the path of a NIFTI file which is given without a file extension.
Description
Resolve the path of a NIFTI file which is given without a file extension.
Usage
nifti.resolve.filepath(filepath)
Arguments
filepath |
character string, the path to a NIFTI file. |
Value
character string, the path of an existing file. If filepath itself does not exist, the usual
NIFTI file extensions are appended to it and the first existing file is returned.
Compute NIFTI space unit info from xyzt_units header field.
Description
Compute NIFTI space unit info from xyzt_units header field.
Usage
nifti.space.info(xyzt_units)
Arguments
xyzt_units |
a single character, the |
Value
named list with entries: code: the NIFTI unit code as a decimal integer, name: character string, the unit name, scaling: float, the scaling factor for the unit, relative to the FreeSurfer space unit (mm).
Compute NIFTI time unit info from xyzt_units header field.
Description
Compute NIFTI time unit info from xyzt_units header field.
Usage
nifti.time.info(xyzt_units)
Arguments
xyzt_units |
a single character, the |
Value
named list with entries: code: the NIFTI unit code as a decimal integer, name: character string, the unit name, scaling: float, the scaling factor for the unit, relative to the FreeSurfer time unit (ms).
Get the name of the transform type from a form code.
Description
The form code is a code stored in the sform_code and/or qform_code NIFTI header fields.
Usage
nifti.transform.type.name(form_code)
Arguments
form_code |
integer, the value retrieved from the |
Value
character string, the meaning of the code. Usually this expresses to what the data will be aligned after application of the vox2ras transformation method. (The type of transformation to perform in order to achieve this alignment depends on whether the value was retrieved from the sform or the qform field and does not matter here.)
Create a NIFTI v2 header extension.
Description
NIFTI v2 files can store arbitrary data in header extensions, in the area between the header and the voxel data. This function creates such an extension. Pass the result to write.nifti2, which writes it to the file, and later read it back with read.nifti2.header plus nifti2.get.extension.
Usage
nifti2.extension(ecode, content = NULL)
Arguments
ecode |
integer, the extension code. This identifies the type of the payload, but the code is not interpreted in any way. The CIFTI2 XML metadata uses code |
content |
raw vector, character string, or |
Value
named list with the entries 'ecode' and 'content', representing one NIFTI v2 header extension.
See Also
nifti2.get.extension, nifti2.extension.text
Other nifti2 extensions:
nifti2.extension.content(),
nifti2.extension.size(),
nifti2.extension.text(),
nifti2.get.extension()
Get the payload of a NIFTI v2 header extension as raw bytes.
Description
Get the payload of a NIFTI v2 header extension as raw bytes.
Usage
nifti2.extension.content(extension, strip_nul = TRUE)
Arguments
extension |
a NIFTI v2 header extension, a named list with entries 'ecode' and 'content', see |
strip_nul |
logical, whether to remove NUL bytes from the payload. This is required to convert the payload to a character string. |
Value
a raw vector, the payload of the extension.
See Also
Other nifti2 extensions:
nifti2.extension(),
nifti2.extension.size(),
nifti2.extension.text(),
nifti2.get.extension()
Compute the size of a NIFTI v2 header extension in a file.
Description
A NIFTI v2 header extension occupies a multiple of 16 bytes in the file, because the payload is padded with NUL bytes. See nifti2.extension for details.
Usage
nifti2.extension.size(extension)
Arguments
extension |
a NIFTI v2 header extension, a named list with entries 'ecode' and 'content', see |
Value
integer, the size of the extension in bytes, as it is stored in the file. This includes the 8 bytes of meta data (the size and code fields) and the padding.
See Also
Other nifti2 extensions:
nifti2.extension(),
nifti2.extension.content(),
nifti2.extension.text(),
nifti2.get.extension()
Get the payload of a NIFTI v2 header extension as text.
Description
Convert the payload of a header extension to a character string. The trailing NUL bytes, which are only used to pad the extension to a multiple of 16 bytes, are removed. Note that embedded NUL bytes cannot be represented in an R string and are removed as well, so this function is only meaningful for text payloads (like the CIFTI2 XML metadata).
Usage
nifti2.extension.text(extension)
Arguments
extension |
a NIFTI v2 header extension, a named list with entries 'ecode' and 'content', see |
Value
character string, the payload of the extension. The string is marked as UTF-8 encoded, which is the encoding required by the NIFTI standard.
See Also
Other nifti2 extensions:
nifti2.extension(),
nifti2.extension.content(),
nifti2.extension.size(),
nifti2.get.extension()
Get a NIFTI v2 header extension by code.
Description
Retrieve one header extension from a NIFTI v2 header, by its extension code. See nifti2.extension for details on header extensions.
Usage
nifti2.get.extension(niiheader, ecode)
Arguments
niiheader |
named list, a NIFTI v2 header as returned by |
ecode |
integer, the extension code to search for. The CIFTI2 XML metadata uses code |
Value
the extension (a named list with entries 'ecode' and 'content', see nifti2.extension), or NULL if the header contains no extension with this code.
See Also
Other nifti2 extensions:
nifti2.extension(),
nifti2.extension.content(),
nifti2.extension.size(),
nifti2.extension.text()
Read the header extensions of a NIFTI v2 file.
Description
Read the header extensions of a NIFTI v2 file.
Usage
nifti2.read.extensions(fh, available, endian = "little")
Arguments
fh |
filehandle, a connection to a NIFTI v2 file, positioned at the first byte after the fixed-size header (i.e., at the extension flag bytes). |
available |
integer, the number of bytes available for header extensions, i.e., |
endian |
character string, the endianness of the file, either 'little' or 'big'. |
Value
list of header extensions, see nifti2.extension. Empty list if the file has no extensions.
Remove NUL bytes from a raw vector.
Description
Remove all NUL bytes from a raw vector. This is needed for the payload of NIFTI v2 header extensions, which are padded with NUL bytes, and for the payload of MATLAB files, but the function is not specific to any format.
Usage
nifti2.strip.nul(rawdata)
Arguments
rawdata |
raw vector or integer vector with values in range 0 to 255. |
Value
raw vector, the input without any NUL bytes.
Remove trailing NUL bytes from a raw vector.
Description
Remove the NUL bytes at the end of a raw vector, but keep any NUL bytes before them. This is needed for the payload of NIFTI v2 header extensions, which is padded with NUL bytes to a multiple of 16 bytes, but can in theory contain NUL bytes as part of the payload.
Usage
nifti2.trailing.nul.removed(rawdata)
Arguments
rawdata |
raw vector or integer vector with values in range 0 to 255. |
Value
raw vector, the input without trailing NUL bytes.
Write the header extensions of a NIFTI v2 file.
Description
Write the header extensions of a NIFTI v2 file.
Usage
nifti2.write.extensions(fh, extensions, endian = "little")
Arguments
fh |
filehandle, a connection to a NIFTI v2 file, positioned at the first byte after the fixed-size header (i.e., where the extension flag bytes go). |
extensions |
list of header extensions, see |
endian |
character string, the endianness of the file, either 'little' or 'big'. |
Value
integer, the number of bytes written (the extension flag bytes plus all extensions). The data must start at 544 + <return value>.
Create a NIFTI v1 header from the header information contained in an fs.volume instance.
Description
Create a NIFTI v1 header from the header information contained in an fs.volume instance.
Usage
nii1header.for.mgh(mgh, endian = "little", pair = FALSE)
Arguments
mgh |
an |
endian |
character string, the endianness to use. Either 'little' or 'big'. Defaults to 'little'. |
pair |
logical, whether the header should describe a NIFTI v1 pair (a |
Value
a NIFTI v1 header structure (see ni1header.template). Note that the header may or may not contain full RAS information, depending on whether the source fs.volume contained such information or not. If the MGH header does not have valid RAS information, the qform and sform codes will be set to 0 (unknown).
Note
This is intended to be used with write.nifti1, which allows users to convert MGH/MGZ data to NIFTI files.
See Also
Other nifti1 writers:
write.fs.morph.ni1(),
write.nifti1()
Parse the diffusion metadata of a NRRD header.
Description
The teem/DTI-TK/3D Slicer convention for diffusion MRI data in NRRD files stores the b-value in the field 'DWMRI_b-value' and one gradient vector per volume in the fields 'DWMRI_gradient_0000', 'DWMRI_gradient_0001' and so on. The optional 'measurement frame' field is the rotation that maps the gradient vectors, which are given in the image (voxel) frame, into the frame in which the gradients were measured. The values are returned exactly as they are stored, i.e. in the image frame, together with the measurement frame, so that a caller can apply it (or hand the values to the gradient table functions of this package, which expect gradients in image axes as well).
Usage
nrrd.dwi.info(fields, num_volumes)
Arguments
fields |
named list, the parsed header fields. |
num_volumes |
integer, the number of volumes (the size of the last axis), used to check the number of gradients. |
Value
named list with entries b_value (numeric or NULL), bvec (numeric matrix
with one row per gradient, or NULL), num_gradients (integer, 0 when there are none) and
measurement_frame (3x3 numeric matrix or NULL). Returns NULL when the header contains
no DWI information at all.
Look up a field in a parsed NRRD header.
Description
Look up a field in a parsed NRRD header.
Usage
nrrd.field(fields, name, default = NULL)
Arguments
fields |
named list, the fields of the header, as returned by |
name |
character string, the field name to look up, e.g. 'space origin'. |
default |
the value to return when the field is not present. |
Value
the value of the field, or default when the field is not present.
Parse a NRRD header field name into a lookup key.
Description
NRRD field names are matched case-insensitively and some fields are spelled in two ways ('line skip' and 'lineskip', 'data file' and 'datafile'), so a key is computed by lowercasing the name and dropping everything that is not a letter or a digit.
Usage
nrrd.field.key(name)
Arguments
name |
character string, the field name as it occurs in the file. |
Value
character string, the normalized key.
Parse a NRRD header field value.
Description
Converts the string value of a header field into an R value: a number for the
integer and floating point fields, a vector for the list fields, a vector or a matrix for the
vector and matrix fields (the syntax is (1,2,3), several vectors separated by
whitespace, and the value none for a missing vector), and a character vector for the
string list fields.
Usage
nrrd.parse.field.value(key, value)
Arguments
key |
character string, the normalized field name, see |
value |
character string, the raw value from the header. |
Value
the parsed value.
Parse the header lines of a NRRD file.
Description
Splits the header lines into an NRRD magic line and a named list of typed field
values. Field names are normalized for lookup (see nrrd.field.key), the original
spelling is kept in the result. A field may be written as 'name: value' or as 'name:=value',
the latter meaning that the value is a string, which is how the tools that write custom fields
(e.g. the DWI metadata, or pynrrd) store them. The special 'data file: LIST' mode is handled as
well: the lines that follow it, up to the end of the header, are the names of the data files.
Usage
nrrd.parse.header(lines, filepath = "")
Arguments
lines |
character vector, the header lines, see |
filepath |
character string, path to the file, used in error messages. |
Value
named list with entries magic (character string), fields (named list,
keyed by the normalized field name), field_names (named character vector, the original
spelling per key) and data_file_names (character vector, the file names of the LIST
mode, or NULL).
Parse a NRRD matrix value like '(1,0,0) (0,1,0) (0,0,1)'.
Description
Parse a NRRD matrix value like '(1,0,0) (0,1,0) (0,0,1)'.
Usage
nrrd.parse.matrix(value)
Arguments
value |
character string, the field value. |
Value
numeric matrix, or NULL for 'none'.
Parse a quoted NRRD string list.
Description
Parse a quoted NRRD string list.
Usage
nrrd.parse.quoted.list(value)
Arguments
value |
character string, the field value, e.g. 'left right' or '"some label"'. |
Value
character vector.
Parse a NRRD vector value like '(1,2,3)'.
Description
Parse a NRRD vector value like '(1,2,3)'.
Usage
nrrd.parse.vector(value)
Arguments
value |
character string, the field value. |
Value
numeric vector, or NULL for 'none'.
Parse a NRRD vector list value like '(1,0,0) (0,1,0) (0,0,1)'.
Description
Used for the 'space directions' field. Any component may be the string 'none', which marks a non-space axis (e.g. the time axis of a 4D volume).
Usage
nrrd.parse.vector.list(value)
Arguments
value |
character string, the field value. |
Value
numeric matrix with one row per vector, or NULL for 'none'. Rows of a non-space axis contain NA.
Convert raw bytes of wide integer types into numbers.
Description
R's readBin can read integers of 1, 2 and 4 bytes, but an unsigned 4 byte
integer does not fit into R's signed integer type and there is no integer type of 8 bytes at
all, so these types are interpreted here from their raw bytes. The values are computed in
double precision, which is exact up to 2^53 (for the 64 bit types, larger values lose their low
bits, see the note in read.fs.volume.nrrd).
Usage
nrrd.raw.to.numeric(bytes, type_info, endian)
Arguments
bytes |
raw vector, the bytes of the values. |
type_info |
named list, the R data type information, see |
endian |
character string, 'little' or 'big'. |
Value
numeric vector, one value per 4 or 8 bytes.
Read the data section of a NRRD file.
Description
Reads the values of a volume, from the header file itself or from the data files it names, and checks that their number matches the dimensions stated in the header.
Usage
nrrd.read.data(filepath, info, type_info)
Arguments
filepath |
character string, path to the header file. |
info |
named list, the parsed header, see |
type_info |
named list, the R data type information, see |
Value
vector of values, of length prod(sizes).
Read the ASCII header of a NRRD file.
Description
Reads the header bytes of a file in NRRD format, up to and including the blank line that terminates the header, and returns the header lines together with the byte offset at which the data starts. The whole header is ASCII text, so it is safe to read it as a string; the binary data behind it is never touched here.
Usage
nrrd.read.header.lines(filepath, max_header_bytes = 10L * 1024L * 1024L)
Arguments
filepath |
character string, path to the file. |
max_header_bytes |
integer, the maximum number of bytes to read while looking for the blank line that ends the header. NRRD headers are small (a few KB even for large DWI gradient tables), this limit only exists to keep a malformed file from producing an endless read. |
Value
named list with entries lines (character vector, the header lines without the
terminating blank line), data_offset (numeric, the byte offset at which the data starts,
counted from the beginning of the file, or NA for a gzip-compressed file, in which the data
cannot be seeked to), gzipped_file (logical, whether the whole file is gzip-compressed)
and header_bytes (integer, the number of bytes the header occupies).
Read the remaining bytes of a connection.
Description
Reads everything from the current position to the end of the file, in chunks, to keep the peak memory of the intermediate buffers bounded. This is used for the bzip2 encoding, which R cannot decompress as a stream.
Usage
nrrd.read.remainder(con)
Arguments
con |
a connection opened in binary read mode. |
Value
raw vector.
Read NRRD values from a connection or a file.
Description
Reads the scalar values of a NRRD data section, dispatching on the encoding. The connection has to be positioned at the start of the data. For the compressed encodings the stream starts at the current position: gzip data are read through a decompression filter (which also works when the stream is preceded by junk, e.g. an ASCII header), bzip2 data have to be decompressed in one piece, since R has no streaming bzip2 connection.
Usage
nrrd.read.values(
filepath,
data_offset,
num_values,
info,
type_info,
num_values_exact = TRUE
)
Arguments
filepath |
character string, path to the file that holds the data. |
data_offset |
numeric or NA, the byte offset of the data in the file. NA means that the data start at the current position of a connection that cannot be seeked in. |
num_values |
numeric, the number of values to read. For the LIST mode this is computed per
file from the file size, see |
info |
named list, the parsed header, see |
type_info |
named list, the R data type information, see |
num_values_exact |
logical, whether |
Value
numeric or integer vector, the values.
Resolve the data location of a NRRD file.
Description
Determines where the data of a NRRD file are stored: in the file itself, in a file named by the 'data file' header field (a path relative to the directory of the header file), or in the several files that the 'data file: LIST' mode names.
Usage
nrrd.resolve.data.files(fields, data_file_names, filepath)
Arguments
fields |
named list, the parsed header fields. |
data_file_names |
character vector or NULL, the file names of the LIST mode. |
filepath |
character string, path to the header file. |
Value
character vector of data file paths, or NULL when the data are attached to the header file.
Skip whole lines of a connection.
Description
Used for the NRRD 'line skip' header field, which announces that the data does not
start directly behind the header but behind a number of newline-terminated lines. Unlike
skip.connection.bytes, this has to work for connections that cannot be seeked in, so the
bytes are read and discarded.
Usage
nrrd.skip.lines(con, num_lines, filepath = "")
Arguments
con |
a connection opened in binary read mode. |
num_lines |
integer, the number of lines to skip. |
filepath |
character string, used in error messages only. |
Value
TRUE, invisibly.
Convert the NRRD type name of a volume into R data type information.
Description
The NRRD spec names the data type of the values with a set of aliases for the
standard integer and floating point types ('uint8', 'unsigned char', 'uchar', ...), see
https://teem.sourceforge.net/nrrd/format.html. The 64 bit integer types have no R
equivalent and are read as doubles, which is exact up to 2^53.
Usage
nrrd.type.info(type_name, filepath = "")
Arguments
type_name |
character string, the value of the 'type' header field. |
filepath |
character string, the file the header was read from, used in error messages. |
Value
named list with entries what (the readBin type), size (bytes per
value), signed (logical, for integer types), itemsize (bytes per value),
r_class ('integer' or 'double'), is_int64 (logical) and wide (logical,
whether the type has to be interpreted from its raw bytes instead of being read by
readBin).
Compute the voxel-to-RAS matrix of a NRRD volume.
Description
NRRD stores the geometry of a volume as one direction vector per space axis ('space directions'), the world position of the center of voxel (0,0,0) ('space origin') and the world space these refer to ('space'). Voxel indices are 0-based. The matrix returned here always maps to RAS+ coordinates (x = right, y = anterior, z = superior), which is the space used by FreeSurfer, by the NIfTI standard and by the rest of this package: a file that states the LPS space therefore has the sign of its first two axes flipped.
Usage
nrrd.vox2ras(fields, dimension, filepath = "")
Arguments
fields |
named list, the parsed header fields. |
dimension |
integer, the number of dimensions of the volume. |
filepath |
character string, path to the file, used in warnings. |
Value
named list with entries matrix (the 4x4 voxel-to-RAS matrix, or NULL when the
file carries no space information at all) and source (character string, how the matrix
was derived: 'space directions', 'spacings' or NULL).
Open a connection that transparently handles gzip compression.
Description
Open a connection that transparently handles gzip compression.
Usage
## S3 method for class 'maybe.gzip'
open(filepath, gzipped, mode = "rb")
Arguments
filepath |
character string, path to the file. |
gzipped |
logical, whether the file is gzip-compressed (see
|
mode |
character string, 'r' for text or 'rb' for binary. |
Value
a connection, call close() on it when done.
Open the payload of an MRtrix TCK/TSF file for reading.
Description
Parses and validates the header and returns everything needed to
read the payload. The caller is responsible for closing con.
Usage
## S3 method for class 'mrtrix.payload'
open(filepath, max_tracks = Inf)
Arguments
filepath |
character string, path to the file. |
max_tracks |
numeric, the maximum number of tracks that will be read. Used to decide whether an up-front allocation check makes sense. |
Value
named list with entries con, header, offset,
dsize, endian, values_per_point, gzipped,
is_tck and expected_groups.
Determine the orientation transform between two orientations.
Description
Determine the orientation transform between two orientations.
Usage
ornt.transform(start_ornt, end_ornt)
Arguments
start_ornt |
numeric matrix with 2 columns, the initial orientation. |
end_ornt |
numeric matrix with 2 columns, the target orientation. |
Value
numeric matrix with 2 columns, the orientation that maps
start_ornt onto end_ornt.
Convert an orientation array to axis codes.
Description
Convert an orientation array to axis codes.
Usage
ornt2axcodes(ornt)
Arguments
ornt |
numeric matrix with 2 columns, see |
Value
character vector with one code per input axis, drawn from
c('L','R','P','A','I','S'). Dropped axes become NA.
Parse the 'count' entry of an MRtrix TCK/TSF header.
Description
The entry is optional: the MRtrix documentation lists only 'file' and 'datatype' as required header keys, and explicitly notes that the value may not reflect the number of streamlines actually stored, e.g., when a command was terminated prematurely. The value is therefore used as a hint only, never to decide how much data to read.
Usage
parse.mrtrix.count(header)
Arguments
header |
named list, the parsed header. |
Value
numeric, the stored count, or NA if it is absent or not parseable.
Validate and describe the datatype entry of an MRtrix TCK/TSF header.
Description
Validate and describe the datatype entry of an MRtrix TCK/TSF header.
Usage
parse.mrtrix.datatype(header, filepath = "")
Arguments
header |
named list, the parsed header. |
filepath |
character string, the path of the file, used in messages only. |
Value
named list with entries dsize (bytes per value) and
endian ('little' or 'big').
Parse the 'file' entry of an MRtrix TCK/TSF header.
Description
The entry has the form 'file: . OFFSET', where the file name part must be a single dot for single-file TCK/TSF files and the offset gives the byte position at which the binary payload starts.
Usage
parse.mrtrix.file.entry(header, filepath = "")
Arguments
header |
named list, the parsed header. |
filepath |
character string, the path of the file, used in messages only. |
Value
named list with entries filename_part (character) and
offset (numeric).
Parse the key-value pairs of an MRtrix TCK/TSF header.
Description
Splits each header line at its first colon. Values may contain
colons (e.g., in command_history entries), they are preserved. Lines
without a colon are ignored, as the MRtrix reference implementation does.
Keys that occur more than once are collected into a vector.
Usage
parse.mrtrix.header(lines, filepath = "")
Arguments
lines |
character vector, the header lines, including the first line and the terminating 'END' line. |
filepath |
character string, the path of the file, used in error messages only. |
Value
named list, the parsed header.
Parse and validate the datatype of an MRtrix streamlines file.
Description
The TCK and TSF formats store float values of 32 or 64 bit, in either byte order.
Usage
parse.mrtrix.write.datatype(datatype)
Arguments
datatype |
character string, the datatype. |
Value
named list with entries dsize (bytes per value) and
endian ('little' or 'big').
Parse a single ASCII STL face.
Description
Parse a single ASCII STL face.
Usage
parse.stl.ascii.face(stl_face_lines)
Arguments
stl_face_lines |
vector of exactly 7 character strings, the lines from an STL ASCII file defining a triangular face. |
Value
named list with entries: 'face_normal': double matrix with 1 row and 3 columns, the face normal. 'vertex_coords': double matrix with 3 rows and 3 columns, the 3x3 vertex coordinates of the face, each row contain the x, y, and z coordinate of a vertex.
Parse matrix from text file lines.
Description
Parse matrix from text file lines.
Usage
parse.transform.matrix.lines(file_lines, ignore_line_suffix = ";")
Arguments
file_lines |
vector of 3 character strings, the matrix lines. The separator is assumed to be a single space. |
ignore_line_suffix |
character string, a line suffix that will be stripped from the end of each line if it exists. |
Value
numerical 4x4 matrix, the parsed matrix
Generate PLY format header lines
Description
Generate PLY format header lines
Usage
ply.header.lines(num_verts, num_faces, use_vertex_colors)
Turn polygon soup into indexed mesh.
Description
Some mesh file formats like STL do not store the faces as indices into a vertex list ('indexed mesh'), but repeat all vertex coordinates for each face ('polygon soup'). This function creates an indexed mesh from a polysoup.
Usage
polygon.soup.to.indexed.mesh(faces_vertex_coords, digits = 6)
Arguments
faces_vertex_coords |
numerical matrix with n rows and 3 columns, the vertex coordinates of the faces. Each row contains the x,y,z coordinates of a single vertex, and three consecutive vertex rows form a triangular face. |
digits |
the precision (number of digits after decimal separator) to use when to determine whether two x,y,z coords define the same vertex. |
Value
an indexed mesh, as an fs.surface instance (see read.fs.surface).
Print a tract file iterator.
Description
Print a tract file iterator.
Usage
## S3 method for class 'dti.track.iterator'
print(x, ...)
Arguments
x |
a |
... |
ignored. |
Value
the iterator, invisibly.
Print description of a brain atlas or annotation.
Description
Print description of a brain atlas or annotation.
Usage
## S3 method for class 'fs.annot'
print(x, ...)
Arguments
x |
brain surface annotation or atlas with class |
... |
further arguments passed to or from other methods |
Print an fs.cifti instance.
Description
Print an fs.cifti instance.
Usage
## S3 method for class 'fs.cifti'
print(x, ...)
Arguments
x |
an |
... |
ignored. |
Value
the instance, invisibly.
See Also
Other cifti functions:
cifti.axis.brain.models(),
cifti.axis.from.template(),
cifti.axis.labels(),
cifti.axis.parcels(),
cifti.axis.parcels.from.annot(),
cifti.axis.scalars(),
cifti.axis.series(),
cifti.brain.model.surface(),
cifti.brain.model.volume(),
cifti.dim.labels(),
cifti.file.type.for.axes(),
cifti.grayordinates(),
cifti.header.from.axes(),
cifti.label.table(),
cifti.parcel(),
cifti.parcels(),
cifti.series.info(),
cifti.structure.data(),
cifti.structures(),
cifti.volume(),
print.fs.cifti.data(),
print.fs.connectome(),
read.cifti(),
read.cifti.header(),
read.cifti.rows(),
read.fs.connectome.cifti(),
write.cifti(),
write.fs.connectome.cifti(),
write.fs.morph.cifti(),
write.fs.parcellated.cifti(),
write.fs.parcellation.cifti(),
write.fs.series.cifti()
Print an fs.cifti.data instance.
Description
Print an fs.cifti.data instance.
Usage
## S3 method for class 'fs.cifti.data'
print(x, ...)
Arguments
x |
an |
... |
ignored. |
Value
the instance, invisibly.
See Also
Other cifti functions:
cifti.axis.brain.models(),
cifti.axis.from.template(),
cifti.axis.labels(),
cifti.axis.parcels(),
cifti.axis.parcels.from.annot(),
cifti.axis.scalars(),
cifti.axis.series(),
cifti.brain.model.surface(),
cifti.brain.model.volume(),
cifti.dim.labels(),
cifti.file.type.for.axes(),
cifti.grayordinates(),
cifti.header.from.axes(),
cifti.label.table(),
cifti.parcel(),
cifti.parcels(),
cifti.series.info(),
cifti.structure.data(),
cifti.structures(),
cifti.volume(),
print.fs.cifti(),
print.fs.connectome(),
read.cifti(),
read.cifti.header(),
read.cifti.rows(),
read.fs.connectome.cifti(),
write.cifti(),
write.fs.connectome.cifti(),
write.fs.morph.cifti(),
write.fs.parcellated.cifti(),
write.fs.parcellation.cifti(),
write.fs.series.cifti()
Print an fs.connectome instance.
Description
Print an fs.connectome instance.
Usage
## S3 method for class 'fs.connectome'
print(x, ...)
Arguments
x |
an |
... |
ignored. |
Value
the instance, invisibly.
See Also
Other cifti functions:
cifti.axis.brain.models(),
cifti.axis.from.template(),
cifti.axis.labels(),
cifti.axis.parcels(),
cifti.axis.parcels.from.annot(),
cifti.axis.scalars(),
cifti.axis.series(),
cifti.brain.model.surface(),
cifti.brain.model.volume(),
cifti.dim.labels(),
cifti.file.type.for.axes(),
cifti.grayordinates(),
cifti.header.from.axes(),
cifti.label.table(),
cifti.parcel(),
cifti.parcels(),
cifti.series.info(),
cifti.structure.data(),
cifti.structures(),
cifti.volume(),
print.fs.cifti(),
print.fs.cifti.data(),
read.cifti(),
read.cifti.header(),
read.cifti.rows(),
read.fs.connectome.cifti(),
write.cifti(),
write.fs.connectome.cifti(),
write.fs.morph.cifti(),
write.fs.parcellated.cifti(),
write.fs.parcellation.cifti(),
write.fs.series.cifti()
Print description of a brain surface label.
Description
Print description of a brain surface label.
Usage
## S3 method for class 'fs.label'
print(x, ...)
Arguments
x |
brain surface label with class |
... |
further arguments passed to or from other methods |
Print description of a brain surface patch.
Description
Print description of a brain surface patch.
Usage
## S3 method for class 'fs.patch'
print(x, ...)
Arguments
x |
brain surface patch with class |
... |
further arguments passed to or from other methods |
Print description of a brain surface.
Description
Print description of a brain surface.
Usage
## S3 method for class 'fs.surface'
print(x, ...)
Arguments
x |
brain surface with class |
... |
further arguments passed to or from other methods |
Print an fs.tracts instance.
Description
Print an fs.tracts instance.
Usage
## S3 method for class 'fs.tracts'
print(x, ...)
Arguments
x |
an |
... |
ignored. |
Value
the instance, invisibly.
Print an fs.transform instance.
Description
Print an fs.transform instance.
Usage
## S3 method for class 'fs.transform'
print(x, ...)
Arguments
x |
an |
... |
ignored, only present for consistency with the generic. |
Value
the transform x, invisibly.
See Also
Other header coordinate space:
invert.fs.transform(),
is.fs.transform(),
mghheader.is.ras.valid(),
mghheader.ras2vox(),
mghheader.ras2vox.tkreg(),
mghheader.scanner2tkreg(),
mghheader.tkreg2scanner(),
mghheader.vox2ras(),
mghheader.vox2ras.tkreg(),
read.fs.transform(),
read.fs.transform.dat(),
read.fs.transform.fslmat(),
read.fs.transform.itk(),
read.fs.transform.lta(),
read.fs.transform.xfm(),
sm0to1(),
sm1to0(),
summary.fs.transform(),
transform2lps(),
transform2ras(),
transform2voxel(),
transform2world(),
write.fs.transform(),
write.fs.transform.dat(),
write.fs.transform.fslmat(),
write.fs.transform.itk(),
write.fs.transform.lta(),
write.fs.transform.xfm()
Examples
tf <- read.fs.transform(system.file("extdata", "talairach.lta",
package = "freesurferformats", mustWork = TRUE
))
print(tf)
Print description of a brain volume.
Description
Print description of a brain volume.
Usage
## S3 method for class 'fs.volume'
print(x, ...)
Arguments
x |
brain volume with class |
... |
further arguments passed to or from other methods |
Translate RAS coordinates, as used in volumes by applying vox2ras, to surface RAS.
Description
Translate RAS coordinates, as used in volumes by applying vox2ras, to surface RAS.
Usage
ras.to.surfaceras(header_cras, ras_coords, first_voxel_RAS = c(1, 1, 1))
Arguments
header_cras |
an MGH header instance from which to extract the cras (center RAS), or the cras vector, i.e., a numerical vector of length 3 |
ras_coords |
nx3 numerical vector, the input surface RAS coordinates. Could be the vertex coordinates of an 'fs.surface' instance, or the RAS coords from a surface label. |
first_voxel_RAS |
the RAS of the first voxel, see |
Value
the surface RAS coords for the input RAS coords
Note
The RAS can be computed from Surface RAS by adding the center RAS coordinates, i.e., it is nothing but a translation.
Compute MNI talairach coordinates from RAS coords.
Description
Compute MNI talairach coordinates from RAS coords.
Usage
ras.to.talairachras(ras_coords, talairach, invert_transform = FALSE)
Arguments
ras_coords |
nx3 numerical vector, the input surface RAS coordinates. Could be the vertex coordinates of an 'fs.surface' instance, or the RAS coords from a surface label. |
talairach |
the 4x4 numerical talairach matrix, or a character string which will be interpreted as the path to an xfm file containing the matrix (typically |
invert_transform |
logical, whether to invert the transform. Do not use this, call |
Value
the Talairach RAS coordinates for the given RAS coordinates
Note
You can use this to compute the Talairach coordinate of a voxel, based on its RAS coordinate.
Read ANALYZE 7.5 data from file.
Description
Read ANALYZE 7.5 data from file.
Usage
read.analyze.data(filepath, header = NULL, drop_empty_dims = TRUE)
Arguments
filepath |
character string, the path to the |
header |
optional ANALYZE 7.5 header as returned by |
drop_empty_dims |
logical, whether to drop empty dimensions in the returned data array, see
|
Value
the data in the .img file of the pair, as an array (or a vector for 1D data). Note that the fields of
the header are not applied in any way: the data are returned exactly as they are stored in the file, in the
storage order of the format (the first dimension varies fastest, which is also the order used by R and by the
MGH/MGZ format), and the funused1 field that SPM uses as a scale factor is not applied (see
read.fs.volume.analyze if you want that).
See Also
Examples
hdrfile <- system.file("extdata", "analyze", "tiny_u8.hdr",
package = "freesurferformats", mustWork = TRUE
)
data <- read.analyze.data(hdrfile)
dim(data)
Read ANALYZE 7.5 header from file.
Description
Read the header of an ANALYZE 7.5 file, i.e. of a file in the two-file format that stores the voxel
data in a separate .img file.
Usage
read.analyze.header(filepath)
Arguments
filepath |
character string, the path to the |
Value
named list with the ANALYZE 7.5 header fields, in the field naming of the format specification. See
analyzeheader.template for a description of all of them. In addition to the fields of the
specification, the following entries are present:
endiancharacter string, the endianness of the file,
'little'or'big'. It is detected from thesizeof_hdrfield.magiccharacter string, the 4 bytes at offset 344 (which are the
sminfield of the ANALYZE specification), interpreted as a string. It is empty for ANALYZE files, seeis.analyze.file.header_formatcharacter string, always
'analyze'here. The other variant of the two-file format is reported as'nifti1_pair', seeread.fs.volume.analyze.spm_origininteger vector of length 3, the interpretation that SPM gives to the
originatorfield: the voxel coordinates of the image origin, as stored in the first 6 bytes of the field. It isNULLif all of them are zero, which means that the field does not store an origin.originator_bytesraw vector of length 10, the unmodified content of the
originatorfield. Theoriginatorentry is the same content with the zero bytes removed and interpreted as a string, which loses information for the files in which SPM stores the image origin there.filepath_header,filepath_imagecharacter strings, the paths of the two files of the pair.
Note
ANALYZE 7.5 does not define the meaning of the world coordinate system of an image: the header stores the
voxel sizes but neither the direction of the voxel axes nor the position of the image in space. This function
therefore reports the fields as they are stored and does not derive a transformation matrix. See
read.fs.volume.analyze for the ways to get a matrix anyway, and for what is known and unknown
about them.
See Also
read.analyze.data, analyzeheader.template
Examples
hdrfile <- system.file("extdata", "analyze", "tiny_u8.hdr",
package = "freesurferformats", mustWork = TRUE
)
analyzeheader <- read.analyze.header(hdrfile)
analyzeheader$datatype
analyzeheader$pix_dim
Read a CIFTI-2 file.
Description
Read a CIFTI-2 file, i.e. its XML metadata (see
read.cifti.header) and its data values. The data are returned
as an array in the order in which they are stored in the file: the first
array dimension is CIFTI matrix dimension 0 (which Connectome Workbench
calls the ROW dimension), the second one is matrix dimension 1 (the COLUMN
dimension). This is the same order that other CIFTI implementations use for
their data arrays.
For a dense file like a .dscalar, dimension 0 holds the scalars (maps) and
dimension 1 the brainordinates (surface vertices and volume voxels), so the
data matrix has one row per map and one column per grayordinate. For a
.dtseries, dimension 0 holds the series, so the matrix has one row per
series point. The functions cifti.series.info and
cifti.map.for.dim tell you what a dimension is; never conclude
it from the file name. Use cifti.structure.data to extract the
data of a brain structure, which is the more convenient interface for most
purposes and the one that the read.fs.*.cifti functions are built on.
Reading a file twice (once for the header, once for the data) is not necessary to extract a single structure, but it is what this function does; use it if you need more than one structure or the raw matrix.
Usage
read.cifti(filepath, rows = NULL, columns = NULL)
Arguments
filepath |
character string, the path to a CIFTI-2 file. Note that a CIFTI-2 file is a NIFTI-2 file, but its data are not a 3D volume; gzipped CIFTI files do not exist (the format forbids compression so that random access remains possible). |
rows |
integer vector or |
columns |
integer vector or |
Value
a named list with the entries 'header' (an fs.cifti object, see
read.cifti.header) and 'data' (the numeric or integer array).
The array dimensions are named with the axis labels of the corresponding
matrix dimensions, see cifti.dim.labels. The object has class
'fs.cifti.data'.
Note
The generic readers read.fs.morph and
read.fs.volume dispatch on the file name and would therefore
match a CIFTI-2 file (which is a NIFTI-2 file), so they detect this case and
stop with a pointer to this function and the other CIFTI readers instead of
returning the values of the matrix in an order that means nothing.
See Also
Other cifti functions:
cifti.axis.brain.models(),
cifti.axis.from.template(),
cifti.axis.labels(),
cifti.axis.parcels(),
cifti.axis.parcels.from.annot(),
cifti.axis.scalars(),
cifti.axis.series(),
cifti.brain.model.surface(),
cifti.brain.model.volume(),
cifti.dim.labels(),
cifti.file.type.for.axes(),
cifti.grayordinates(),
cifti.header.from.axes(),
cifti.label.table(),
cifti.parcel(),
cifti.parcels(),
cifti.series.info(),
cifti.structure.data(),
cifti.structures(),
cifti.volume(),
print.fs.cifti(),
print.fs.cifti.data(),
print.fs.connectome(),
read.cifti.header(),
read.cifti.rows(),
read.fs.connectome.cifti(),
write.cifti(),
write.fs.connectome.cifti(),
write.fs.morph.cifti(),
write.fs.parcellated.cifti(),
write.fs.parcellation.cifti(),
write.fs.series.cifti()
Examples
cifti_file <- system.file("extdata", "cifti", "tiny.dscalar.nii", package = "freesurferformats")
cii <- read.cifti(cifti_file)
dim(cii$data)
# The first 3 grayordinates of the first map:
cii$data[1, 1:3]
Read CIFTI-2 header (XML metadata).
Description
Read the metadata of a CIFTI version 2 file, i.e. the XML
document that describes everything except the actual data values: the matrix
dimensions and their meaning, the brain models (surface vertices and volume
voxels), the parcels, the series information, and the label tables. CIFTI-2
files are NIFTI-2 files that store this XML in a NIFTI v2 header extension
with the extension code 32. Use read.cifti to read the data
values as well (not implemented yet), or the accessor functions
cifti.structures, cifti.parcels,
cifti.series.info and cifti.label.table to
inspect the result.
Usage
read.cifti.header(filepath)
Arguments
filepath |
character string, the path to a CIFTI-2 file (usually one of
|
Value
an fs.cifti object, a named list with the entries: 'filepath' (the
file path), 'niiheader' (the NIFTI-2 header as returned by
read.nifti2.header), 'version' (the CIFTI version, always '2'
for files that can be read), and 'matrix', a named list with the entries
'metadata' (the matrix-level metadata, a named list of character strings, in
file order; the names may repeat) and 'indices_maps' (a list of the
MatrixIndicesMap elements, see below), plus 'dim_sizes' (the integer sizes
of the matrix dimensions; these are stored in entries 5, 6, ... of the dim
field of the NIFTI-2 header, and R index vectors are 1-based, so the 6th
entry of dim holds matrix dimension 0).
Each element of indices_maps is a named list with the entries: 'dims'
(integer vector, the 0-based matrix dimensions this mapping applies to; it
has several entries for files like a .dconn, where one mapping describes
both dimensions), 'applies_to' (the same as a character string, as found in
the file), 'type' (character string, one of 'CIFTI_INDEX_TYPE_BRAIN_MODELS',
'CIFTI_INDEX_TYPE_PARCELS', 'CIFTI_INDEX_TYPE_SERIES',
'CIFTI_INDEX_TYPE_SCALARS' or 'CIFTI_INDEX_TYPE_LABELS'), 'size' (integer
vector, the size of the dimension(s) from 'dims'), 'series' (a list with
entries 'number_of_series_points', 'start', 'step', 'exponent' and 'unit',
for series mappings; NULL otherwise), 'surfaces' (a list of lists with
entries 'brain_structure' and 'surface_number_of_vertices'), 'volumes' (a
list of lists with entries 'dimensions' (integer vector of length 3),
'meter_exponent' and 'transformation_matrix' (4x4 numeric matrix, row-major
as in the file, mapping 0-based voxel indices to coordinates in units of
10^meter_exponent)), 'brain_models' (a list of lists with entries
'index_offset' (0-based), 'index_count', 'model_type',
'brain_structure', 'surface_number_of_vertices' (surfaces only, NA
otherwise), 'vertex_indices' (0-based integer vector, or NULL if all
vertices of the surface are used) and 'voxel_indices_ijk' (an n x 3 integer
matrix of 0-based voxel indices, or NULL) ), 'parcels' (a list of lists
with entries 'index' (0-based position in the list), 'name', 'vertices'
(named list of 0-based vertex index vectors, named by the canonical brain
structure name, e.g. 'CORTEX_LEFT') and 'voxel_indices_ijk'), and
'named_maps' (a list of lists with entries 'name', 'metadata' and 'labels';
'labels' is a data.frame with the columns 'key', 'red', 'green', 'blue',
'alpha', 'label', 'x', 'y' and 'z', see cifti.label.table).
Note
This function performs structural validation of the XML and stops with a descriptive error if the file is not a CIFTI-2 file, if the XML is inconsistent (e.g., index ranges that do not cover the data, or a number of parcels that does not match the matrix dimension), or if a file in the outdated CIFTI-1 format is passed (which has to be converted first, see the error message).
See Also
Other cifti functions:
cifti.axis.brain.models(),
cifti.axis.from.template(),
cifti.axis.labels(),
cifti.axis.parcels(),
cifti.axis.parcels.from.annot(),
cifti.axis.scalars(),
cifti.axis.series(),
cifti.brain.model.surface(),
cifti.brain.model.volume(),
cifti.dim.labels(),
cifti.file.type.for.axes(),
cifti.grayordinates(),
cifti.header.from.axes(),
cifti.label.table(),
cifti.parcel(),
cifti.parcels(),
cifti.series.info(),
cifti.structure.data(),
cifti.structures(),
cifti.volume(),
print.fs.cifti(),
print.fs.cifti.data(),
print.fs.connectome(),
read.cifti(),
read.cifti.rows(),
read.fs.connectome.cifti(),
write.cifti(),
write.fs.connectome.cifti(),
write.fs.morph.cifti(),
write.fs.parcellated.cifti(),
write.fs.parcellation.cifti(),
write.fs.series.cifti()
Examples
cifti_file <- system.file("extdata", "cifti", "tiny.dscalar.nii", package = "freesurferformats")
cii <- read.cifti.header(cifti_file)
cii
cii$matrix$indices_maps[[1]]$type
cifti.structures(cii, dim = 1L)
Read selected matrix rows of a CIFTI-2 file without loading the whole matrix.
Description
Read a few indices of CIFTI matrix dimension 0 (the rows of the
data matrix) from a large file, without ever holding the values of the rows
that are not requested in memory. read.cifti supports the same
selection, but it reads the whole matrix first and then drops the unrequested
rows, which is impossible for a file that does not fit into memory: the
matrix of an HCP subject (91,282 grayordinates in both dimensions) is 33 GB.
This function streams through the file in chunks and keeps only the requested
rows, so its memory usage is the size of the result plus one chunk (32 MB by
default), regardless of the size of the file.
Note which direction of a CIFTI-2 file is the cheap one: the values of a
cell of a row are stored with a stride (dim[5] values lie between the
values of one row), while the values of a column are contiguous. Reading
rows therefore has to touch every value of the file once (it is a
single sequential pass, not a seek per value, but the I/O is the size of the
file), while selecting columns reads only what was asked for. Use
read.cifti with the columns parameter if the rows you need are
the ones that a column selection can give you, e.g. because the matrix is
symmetric (which a .dconn is), and use this function for the cases that
need rows: for a .dtseries, one row is one time point of all grayordinates,
so reading the first few time points of a 1.7 GB file with this function
needs a few KB instead of the whole file.
Usage
read.cifti.rows(filepath, rows, columns = NULL, chunk_values = 4000000L)
Arguments
filepath |
character string, the path to a CIFTI-2 file. Note that a CIFTI-2 file is a NIFTI-2 file, but its data are not a 3D volume; gzipped CIFTI files do not exist (the format forbids compression so that random access remains possible). |
rows |
integer vector, the indices of matrix dimension 0 to read. At least
one index has to be given; the indices are 1-based, see |
columns |
integer vector or |
chunk_values |
integer, the number of data values that are read from the file per chunk. This does not change the result, only the peak memory usage and the I/O granularity, so it is rarely needed: the default of 4 millions values corresponds to about 16 MB. The chunk size is rounded up to a whole number of matrix columns, and the result is the same for every chunk size. |
Value
a named list with the entries 'header' and 'data', see
read.cifti. The 'data' entry holds the requested rows, with the
requested columns if columns was given.
See Also
Other cifti functions:
cifti.axis.brain.models(),
cifti.axis.from.template(),
cifti.axis.labels(),
cifti.axis.parcels(),
cifti.axis.parcels.from.annot(),
cifti.axis.scalars(),
cifti.axis.series(),
cifti.brain.model.surface(),
cifti.brain.model.volume(),
cifti.dim.labels(),
cifti.file.type.for.axes(),
cifti.grayordinates(),
cifti.header.from.axes(),
cifti.label.table(),
cifti.parcel(),
cifti.parcels(),
cifti.series.info(),
cifti.structure.data(),
cifti.structures(),
cifti.volume(),
print.fs.cifti(),
print.fs.cifti.data(),
print.fs.connectome(),
read.cifti(),
read.cifti.header(),
read.fs.connectome.cifti(),
write.cifti(),
write.fs.connectome.cifti(),
write.fs.morph.cifti(),
write.fs.parcellated.cifti(),
write.fs.parcellation.cifti(),
write.fs.series.cifti()
Examples
cifti_file <- system.file("extdata", "cifti", "tiny.dtseries.nii", package = "freesurferformats")
# The first two time points of all grayordinates:
first_frames <- read.cifti.rows(cifti_file, rows = 1:2)
dim(first_frames$data)
# A few time points and a few grayordinates:
subset <- read.cifti.rows(cifti_file, rows = 2, columns = 1:3)
subset$data
Read b-values from a FSL-style bvals file.
Description
Reads the b-values of a diffusion MRI dataset, i.e. the diffusion weighting of each volume in units of s/mm^2. This implements the bvals part of the FSL format: a plain text file with one value per volume, usually in a single row. The HCP variant, which stores one value per line, is read as well.
Usage
read.dti.bval(filepath, layout = "auto")
Arguments
filepath |
character string, path to the b-values file, typically
ending in |
layout |
character string, one of 'auto', 'components' or 'volumes'.
|
Value
numeric vector of length n, the b-value of each of the n volumes.
See Also
Other dti functions:
read.dti.bvec(),
read.dti.grad(),
read.dti.gradients(),
write.dti.bval(),
write.dti.bvec(),
write.dti.grad()
Read b-vectors from a FSL-style bvecs file.
Description
Reads the diffusion gradient directions of a diffusion MRI dataset, i.e. the b-vectors part of the FSL bvecs/bvals format. The file contains unit vectors (or zero vectors for the b=0 volumes), stored as three rows of n values, one row per component, one column per volume.
Usage
read.dti.bvec(filepath, layout = "auto")
Arguments
filepath |
character string, path to the b-vectors file, typically
ending in |
layout |
character string, one of 'auto', 'components' or 'volumes'.
|
Value
a numeric matrix with n rows and 3 columns, one row per volume, the
columns being the x, y and z component of the gradient direction. Note that
these vectors are given with respect to the image axes, not to the
scanner axes, so they are only meaningful together with the image they
belong to: converting them to scanner space requires the transform of that
image. Use read.dti.gradients to read
b-vectors and b-values together, with consistency checks.
Note
The b-vectors are returned exactly as they are stored, i.e. they are
not renormalized, and missing values (see
read.dti.gradients) are not replaced here.
See Also
Other dti functions:
read.dti.bval(),
read.dti.grad(),
read.dti.gradients(),
write.dti.bval(),
write.dti.bvec(),
write.dti.grad()
Read a gradient table in MRtrix3 format.
Description
Reads a diffusion gradient table in MRtrix format: a plain text
file with one line per DWI volume, each line holding the four
space-separated values [ x y z b ], with the direction in scanner
space and the b-value in s/mm^2. This is the format expected by the
-grad option of the MRtrix3 commands (and produced by
-export_grad_mrtrix), and it is also the format in which MRtrix3 stores
the table in the dw_scheme entry of a .mif header. A first line
consisting of a single integer is accepted as a volume count header.
Usage
read.dti.grad(filepath, layout = "auto")
Arguments
filepath |
character string, path to the file. There is no fixed file
name convention, |
layout |
character string, one of 'auto', 'components' or 'volumes'.
|
Value
a numeric matrix with n rows and 4 columns named 'x', 'y', 'z' and 'b', one row per volume. The directions are in scanner space.
See Also
Other dti functions:
read.dti.bval(),
read.dti.bvec(),
read.dti.gradients(),
write.dti.bval(),
write.dti.bvec(),
write.dti.grad()
Read and validate a diffusion MRI gradient table.
Description
The main entry point for reading diffusion gradients. It reads
b-vectors and b-values from either a pair of FSL-style files or from a
single MRtrix-style gradient table file, checks that they are consistent,
and reports suspicious entries. Use this rather than calling
read.dti.bvec and
read.dti.bval separately if you intend to
use the gradients for anything, because a mismatched or malformed gradient
table is silently wrong otherwise.
Usage
read.dti.gradients(bvec, bval = NULL, n_volumes = NULL, layout = "auto")
Arguments
bvec |
character string (path to a b-vectors file), or a numeric matrix with one row per volume (or one column per volume) and 3 columns. |
bval |
character string (path to a b-values file), or a numeric vector
with one value per volume. Can be |
n_volumes |
scalar numeric or integer, the number of volumes in the DWI
image that the gradients belong to, used to check that the table matches
the image. Typically |
layout |
character string, passed on to the readers, one of 'auto', 'components' or 'volumes'. |
Details
Both parameters accept either a file path or already read data, so
the function can also be used to validate gradients that were obtained from
somewhere else. If bval is NULL and bvec is a single file path, the
file is interpreted as follows. A file whose name contains bvec is read
as a b-vectors file (since the name is the user's clearest statement about
the content, and a b-vectors file with 4 volumes would otherwise look
exactly like a 3-volume gradient table). Otherwise, a file that has 4
values per line, or 4 lines, is read as an MRtrix gradient table. Otherwise
the file is read as b-vectors and a matching b-values file is looked up
next to it, which covers the common dataset layouts such as BIDS
(sub-01_dwi.bvec with sub-01_dwi.bval).
Value
a named list with the entries bvec (numeric matrix with n rows
and 3 columns, one row per volume, components in image space) and bval
(numeric vector of length n).
Note
The following problematic cases are reported, but the data is always
returned as read, except for the missing values, which are replaced by
zeros: (1) NA/NaN entries, which are interpreted as b=0 volumes, as
MRtrix3 does, provided that they do not leave a volume with a b-value but
no direction or vice versa, which is an error; (2) gradient vectors whose
norm deviates from 1, which is reported because MRtrix3 rescales the
b-value by the squared norm in this situation; (3) volumes with a b-value
above the b=0 threshold but a zero direction; (4) volumes with a small
positive b-value but a non-zero direction.
See Also
Other dti functions:
read.dti.bval(),
read.dti.bvec(),
read.dti.grad(),
write.dti.bval(),
write.dti.bvec(),
write.dti.grad()
Read DTI tracking data from file in MRtrix 'TCK' format.
Description
Reads streamlines from a TCK file, optionally gzip-compressed.
Usage
read.dti.tck(
filepath,
max_tracks = Inf,
skip_tracks = 0L,
bbox = NULL,
chunk_values = 4e+06
)
Arguments
filepath |
character string, path to the |
max_tracks |
numeric, the maximum number of tracks to read. Use
|
skip_tracks |
integer, the number of tracks to skip before reading any. Skipped tracks are never held in memory. |
bbox |
numeric vector of length 6 or NULL. If given, only tracks that
have at least one point inside the box are read, the box is given as
|
chunk_values |
integer, the number of payload values that are read per chunk. This is an advanced tuning parameter that does not change the result, only the peak memory usage (at most one chunk is buffered at a time) and the granularity of the file reads. The default of 4e6 values corresponds to about 32 MB of doubles. Lower it on a machine with very little free memory. |
Value
named list with entries 'header' and 'tracks'. The tracks are stored
in an is.fs.tracts instance: all coordinates are kept in a
single matrix and tracks[[i]] returns the n x 3 coordinate matrix of
the i-th track. Use fs.tracts.lengths(tck$tracks) to get the number
of points of each track, and as.list(tck$tracks) to convert to a
plain list of matrices.
Examples
## Not run:
tckf <- "~/simple.tck"
tck <- read.dti.tck(tckf)
# Read only the first 1000 streamlines of a huge tractogram:
first_tracks <- read.dti.tck(tckf, max_tracks = 1000)
# Read the streamlines passing through a region:
region <- read.dti.tck(tckf, bbox = c(-10, 10, -20, 20, 0, 30))
## End(Not run)
Read the header of a file in MRtrix 'TCK' or 'TSF' format.
Description
Reads only the ASCII header of the file, without touching the binary payload. This is cheap even for huge tractograms and can be used to inspect a file before deciding whether to read its tracks.
Usage
read.dti.tck.header(filepath)
Arguments
filepath |
character string, path to the |
Value
named list, the parsed header. The entries of the 'derived' entry describe the payload (data offset, datatype, endianness, and whether the file is gzip-compressed).
Examples
## Not run:
hdr <- read.dti.tck.header("brain.tck");
hdr$count; # number of streamlines stated in the header
hdr$derived$gzipped; # TRUE for a .tck.gz file
## End(Not run)
Read fiber tracks from Diffusion Toolkit in trk format.
Description
Read fiber tracks from Diffusion Toolkit in trk format.
Usage
read.dti.trk(
filepath,
shift_origin = TRUE,
max_tracks = Inf,
skip_tracks = 0L,
bbox = NULL,
coords = NULL
)
Arguments
filepath |
character string, path to file in trk format. Gzip-compressed
files are supported as well (the compression is detected from the file
content, so a |
shift_origin |
logical, whether to apply the half-voxel origin shift when computing the corrected vox2ras matrix. The TRK format stores a matrix that maps to the voxel corner, not the voxel center (as is the NIfTI convention). Set to |
max_tracks |
numeric, the maximum number of tracks to read. Use |
skip_tracks |
integer, the number of tracks to skip before reading any.
Skipped tracks are never held in memory. Note that the count refers to the
tracks that a reader returns, and that empty tracks (tracks without any
point, which the TRK format allows) are returned as well, e.g., a file with
one regular track, then an empty one, yields the empty track for
|
bbox |
numeric vector of length 6 or NULL. If given, only tracks that
have at least one point inside the box are read, the box is given as
|
coords |
character string or NULL, the coordinate system of the returned
track coordinates. One of 'native' (the coordinates exactly as stored in the
file, which for TRK files is usually 'voxelmm' space, in which the
coordinates refer to voxel corners) or 'ras' (RAS+ mm space in which a
coordinate of (0,0,0) is the center of the first voxel, which is what
'nibabel' and DIPY return by default). If The |
Value
named list, the parsed file data. The naming of the variables follows the spec at http://trackvis.org/docs/?subsect=fileformat. The returned header will contain the field vox2ras (the raw matrix stored in the TRK file, mapping from mm space to RAS) and, if shift_origin is TRUE, the additional field vox2ras_corrected (the computed matrix mapping from voxel indices to voxel center RAS coordinates). It also contains the entry coords_space ('native' or 'ras'), which records the coordinate system the returned tracks are in, so that the result can be passed to write.dti.trk() without losing that information. The tracks are stored in an is.fs.tracts instance: tracks[[i]] returns a list with the entries coords (n x 3 matrix), num_points (integer), scalars (matrix or NULL) and properties (numeric vector or NULL) for the i-th track. Use fs.tracts.lengths(trk$tracks) to get the number of points of each track, and as.list(trk$tracks) to convert to a plain list.
Note
The 4x4 matrix stored in TRK files (labeled vox_to_ras in the spec) is actually a transformation from mm space to RAS, not from voxel space to RAS. The TRK format was designed by TrackVis with the assumption that voxels are 1 mm^3, and that coordinates refer to voxel corners rather than centers. To obtain the actual vox2ras matrix (voxel center in RAS), the raw matrix must be combined with a voxel-size scaling and a half-voxel offset correction: vox2ras_corrected = mm2ras %*% mm_correction %*% vox2mm, where vox2mm scales by the inverse voxel size and mm_correction shifts by -0.5 mm. Note that DSI Studio does not apply this half-voxel shift, so you may need to set shift_origin=FALSE for DSI Studio files.
Use coords = 'ras' to have the transformation applied to the returned coordinates. That transformation additionally accounts for the voxel_order stored in the header, like the reference implementation in 'nibabel' does, see trackvis.affine.to.rasmm. Note that the matrix stored in the header alone is not sufficient to transform the coordinates: it has to be combined with the voxel sizes, the half-voxel offset and the orientation.
Examples
## Not run:
trk <- read.dti.trk("~/simple.trk")
trk2 <- read.dti.trk("~/standard.trk")
trk3 <- read.dti.trk("~/complex_big_endian.trk")
# Coordinates in RAS+ mm, ready for plotting against an MNI template:
trk_ras <- read.dti.trk("~/simple.trk", coords = "ras")
## End(Not run)
Read the header of a TrackVis TRK file.
Description
Reads and parses the 1000 byte header of a TRK file without touching the track data. This is cheap even for huge tractograms and can be used to inspect a file before deciding whether to read its tracks.
Usage
read.dti.trk.header(filepath, shift_origin = TRUE)
Arguments
filepath |
character string, path to a file in TRK format. Gzip-compressed
files (typically named |
shift_origin |
logical, whether to compute the corrected |
Value
named list, the header. It contains all fields of the TRK header as
described at http://trackvis.org/docs/?subsect=fileformat, plus
vox2ras (the matrix stored in the file) and, if
shift_origin is TRUE, vox2ras_corrected.
Examples
## Not run:
hdr <- read.dti.trk.header("brain.trk");
hdr$n_count; # number of tracks stated in the header
hdr$voxel_order;
## End(Not run)
Read DTI tracking per-coord data from file in MRtrix 'TSF' format.
Description
Reads per-vertex track scalars from a TSF file, optionally gzip-compressed.
Usage
read.dti.tsf(
filepath,
max_tracks = Inf,
skip_tracks = 0L,
chunk_values = 4e+06
)
Arguments
filepath |
character string, path to the |
max_tracks |
numeric, the maximum number of tracks to read. Use
|
skip_tracks |
integer, the number of tracks to skip before reading any. Skipped tracks are never held in memory. |
chunk_values |
integer, the number of payload values that are read per chunk. This is an advanced tuning parameter that does not change the result, only the peak memory usage (at most one chunk is buffered at a time) and the granularity of the file reads. The default of 4e6 values corresponds to about 32 MB of doubles. Lower it on a machine with very little free memory. |
Value
named list with entries 'header' and 'scalars'. The scalar data are available in 3 representations: 'merged' (a vector of all values), 'lengths' (the number of values per track) and 'scalar_list' (a list of vectors, one per track, which is expensive for large files and should be avoided for whole-brain data in favour of 'merged' and 'lengths').
Examples
## Not run:
tsff <- "~/simple.tsf"
tsf <- read.dti.tsf(tsff)
## End(Not run)
Read the header of a file in MRtrix 'TSF' format.
Description
Reads only the ASCII header of the file, see
read.dti.tck.header.
Usage
read.dti.tsf.header(filepath)
Arguments
filepath |
character string, path to the |
Value
named list, the parsed header.
Examples
## Not run:
hdr <- read.dti.tsf.header("brain.tsf");
## End(Not run)
Determine element counts from PLY file header.
Description
Determine element counts from PLY file header.
Usage
read.element.counts.ply.header(ply_lines)
Arguments
ply_lines |
vector character strings, all lines of the PLY file |
Read fixed length char, possibly containing embedded zeroes, from binary file.
Description
Read fixed length char, possibly containing embedded zeroes, from binary file.
Usage
read.fixed.char.binary(filehandle, n, to = "UTF-8")
Arguments
filehandle |
connection to read. |
n |
the number of bytes to read. |
to |
the target character encoding. |
Value
the string in the target encoding, with the embedded zeroes removed.
Author(s)
The original version was written by Brandon Whitcher and Volker Schmid. See the source for the full legal info. The coding style was adapted to freesurferformats and the docs were added by Tim Schäfer.
Read file in FreeSurfer annotation format
Description
Read a data annotation file in FreeSurfer format. Such a file assigns a label and a color to each vertex of a brain surface. The assignment of labels to vertices is based on at atlas or brain parcellation file. Typically the atlas is available for some standard template subject, and the labels are assigned to another subject by registering it to the template. For a subject (MRI image pre-processed with FreeSurfer) named 'bert', an example file would be 'bert/label/lh.aparc.annot', which contains the annotation based on the Desikan-Killiany Atlas for the left hemisphere of bert.
Usage
read.fs.annot(
filepath,
empty_label_name = "empty",
metadata = list(),
default_label_name = ""
)
Arguments
filepath |
string. Full path to the input annotation file. Note: gzipped files are supported and gz format is assumed if the filepath ends with ".gz". |
empty_label_name |
character string, a base name to use to rename regions with empty name in the label table. This should not occur, and you can ignore this parameter setting. A warning will be thrown if this ever triggers. Not to be confused with parameter |
metadata |
named list of arbitrary metadata to store in the instance. |
default_label_name |
character string, the label name to use for vertices which have a label code that does not occur in the label table. This is typically the case for the 'unknown' region, which often has code |
Value
named list, entries are: "vertices" vector of n vertex indices, starting with 0. "label_codes": vector of n integers, each entry is a color code, i.e., a value from the 5th column in the table structure included in the "colortable" entry (see below). "label_names": the n brain structure names for the vertices, already retrieved from the colortable using the code. "hex_colors_rgb": Vector of hex color for each vertex. The "colortable" is another named list with 3 entries: "num_entries": int, number of brain structures. "struct_names": vector of strings, the brain structure names. "table": numeric matrix with num_entries rows and 5 colums. The 5 columns are: 1 = color red channel, 2=color blue channel, 3=color green channel, 4=color alpha channel, 5=unique color code. "colortable_df": The same information as a dataframe. Contains the extra columns "hex_color_string_rgb" and "hex_color_string_rgba" that hold the color as an RGB(A) hex string, like "#rrggbbaa".
See Also
Other atlas functions:
atlas.from.lut.and.csv(),
colortable.from.annot(),
read.fs.colortable(),
write.atlas.to.lut.and.csv(),
write.fs.annot(),
write.fs.annot.gii(),
write.fs.colortable()
Examples
annot_file <- system.file("extdata", "lh.aparc.annot.gz",
package = "freesurferformats",
mustWork = TRUE
)
annot <- read.fs.annot(annot_file)
print(annot)
Read an annotation or label in GIFTI format.
Description
Read an annotation or label in GIFTI format.
Usage
read.fs.annot.gii(
filepath,
element_index = 1L,
labels_only = FALSE,
rgb_column_names = c("Red", "Green", "Blue", "Alpha"),
key_column_name = "Key",
empty_label_name = "unknown"
)
Arguments
filepath |
string. Full path to the input label file in GIFTI format. |
element_index |
positive integer, the index of the dataarray to return. Ignored unless the file contains several dataarrays. |
labels_only |
logical, whether to ignore the colortable and region names. The returned annotation will only contain the a vector that contains one integer label per vertex (as entry 'label_codes'), but no region names and colortable information. |
rgb_column_names |
vector of exactly 4 character strings, order is important. The column names for the red, green, blue and alpha channels in the lable table. If a column does not exist, pass NA. If you do not know the column names, just call the function, it will print them. See 'labels_only' if you do not care. |
key_column_name |
character string, the column name for the key column in the lable table. This is the column that holds the label value from the raw vector (see 'labels_only') that links a label value to a row in the label table. Without it, one cannot recostruct the region name and color of an entry. Passing NA has the same effect as setting 'labels_only' to TRUE. |
empty_label_name |
character string, a base name to use to rename regions with empty name in the label table. This should not occur, and you can ignore this parameter setting. A warning will be thrown if this ever triggers. Not to be confused with parameter |
See Also
Other gifti readers:
read.fs.label.gii(),
read.fs.morph.gii(),
read.fs.surface.gii()
Read colortable file in FreeSurfer ASCII LUT format.
Description
Read a colortable from a text file in FreeSurfer ASCII colortable lookup table (LUT) format. An example file is FREESURFER_HOME/FreeSurferColorLUT.txt.
Usage
read.fs.colortable(filepath, compute_colorcode = FALSE)
Arguments
filepath |
string. Full path to the output colormap file. |
compute_colorcode |
logical, indicates whether the unique color codes should be computed and added to the returned data.frame as an extra integer column named 'code'. Defaults to FALSE. |
Value
the data.frame that was read from the LUT file. It contains the following columns that were read from the file: 'struct_index': integer, index of the struct entry. 'struct_name': character string, the label name. 'r': integer in range 0-255, the RGBA color value for the red channel. 'g': same for green channel. 'b': same for blue channel. 'a': same for alpha (transparency) channel. If 'compute_colorcode' is TRUE, it also contains the following columns which were computed from the color values: 'code': integer, unique color identifier computed from the RGBA values.
See Also
Other atlas functions:
atlas.from.lut.and.csv(),
colortable.from.annot(),
read.fs.annot(),
write.atlas.to.lut.and.csv(),
write.fs.annot(),
write.fs.annot.gii(),
write.fs.colortable()
Other colorLUT functions:
colortable.from.annot(),
write.fs.colortable()
Examples
lutfile <- system.file("extdata", "colorlut.txt", package = "freesurferformats", mustWork = TRUE)
colortable <- read.fs.colortable(lutfile, compute_colorcode = TRUE)
head(colortable)
Read a CIFTI-2 connectome file.
Description
Read a CIFTI-2 file whose two matrix dimensions both describe
brainordinates or parcels, i.e. a dense connectome (.dconn), a parcellated
connectome (.pconn) or one of the mixed types (.pdconn, .dpconn). The result
contains the matrix and the parcels or brainordinates its rows and columns belong to;
this is what makes a connectome file usable, since the numbers alone do not say which
pair of regions a value describes.
Both values of a connectome are stored in the file (the matrix is not symmetric on
disk, and the diagonal is stored as well), so reading a .pconn gives a square matrix
with the number of parcels as its number of rows and columns. A real .dconn (an HCP
subject has 91,282 grayordinates, i.e. 8.3 billion values, 33 GB) can not be read into
memory at all: use the rows and columns parameters to read only the part you need,
which is a contiguous block of the file for each requested column.
Usage
read.fs.connectome.cifti(filepath, rows = NULL, columns = NULL)
Arguments
filepath |
character string, the path of a CIFTI-2 file, see |
rows |
integer vector or |
columns |
integer vector or |
Value
a named list with class 'fs.connectome':
'data': numeric matrix, the connectome, with the parcels or brainordinates as the dimnames of its rows and columns (see
cifti.dim.labels),'parcel_names': character vector, the names of the parcels, or
NULLif the file has no parcellated dimension,'parcels': data.frame with one row per parcel (the columns 'index', 'name', 'num_vertices' and 'num_voxels', see
cifti.parcels), orNULL,'parcels_dim': integer, the matrix dimension that holds the parcels (0 or 1), or
NAif the file has none,'grayordinates': data.frame with one row per brainordinate of the dense dimension (see
cifti.grayordinates), orNULL,'grayordinates_dim': integer, the matrix dimension that holds the dense brainordinates (0 or 1), or
NAif the file has none,'header': the
fs.ciftimetadata object, seeread.cifti.header.
Note that the parcels and brainordinates describe all indices of the dimension they
belong to, not only the ones selected with rows or columns.
See Also
Other cifti functions:
cifti.axis.brain.models(),
cifti.axis.from.template(),
cifti.axis.labels(),
cifti.axis.parcels(),
cifti.axis.parcels.from.annot(),
cifti.axis.scalars(),
cifti.axis.series(),
cifti.brain.model.surface(),
cifti.brain.model.volume(),
cifti.dim.labels(),
cifti.file.type.for.axes(),
cifti.grayordinates(),
cifti.header.from.axes(),
cifti.label.table(),
cifti.parcel(),
cifti.parcels(),
cifti.series.info(),
cifti.structure.data(),
cifti.structures(),
cifti.volume(),
print.fs.cifti(),
print.fs.cifti.data(),
print.fs.connectome(),
read.cifti(),
read.cifti.header(),
read.cifti.rows(),
write.cifti(),
write.fs.connectome.cifti(),
write.fs.morph.cifti(),
write.fs.parcellated.cifti(),
write.fs.parcellation.cifti(),
write.fs.series.cifti()
Examples
pconn_file <- system.file("extdata", "cifti", "tiny.pconn.nii", package = "freesurferformats")
conn <- read.fs.connectome.cifti(pconn_file)
dim(conn$data)
conn$parcel_names
conn$data[1:2, 1:2]
Read file in FreeSurfer curv format
Description
Read vertex-wise brain morphometry data from a file in FreeSurfer 'curv' format. Both the binary and ASCII versions are supported. For a subject (MRI image pre-processed with FreeSurfer) named 'bert', an example file would be 'bert/surf/lh.thickness', which contains n values. Each value represents the cortical thickness at the respective vertex in the brain surface mesh of bert.
Usage
read.fs.curv(filepath, format = "auto", with_header = FALSE)
Arguments
filepath |
string. Full path to the input curv file. Note: gzipped binary curv files are supported and gz binary format is assumed if the filepath ends with ".gz". |
format |
one of 'auto', 'asc', 'bin', 'nii' or 'txt'. The format to assume. If set to 'auto' (the default), binary format will be used unless the filepath ends with '.asc' or '.txt'. The latter is just one float value per line in a text file. |
with_header |
logical, whether to return named list with 'header' and 'data' parts. Only valid with FreeSurfer binary curv format. |
Value
data vector of floats. The brain morphometry data, one value per vertex.
See Also
Other morphometry functions:
fs.get.morph.file.ext.for.format(),
fs.get.morph.file.format.from.filename(),
read.fs.mgh(),
read.fs.morph(),
read.fs.morph.gii(),
read.fs.volume(),
read.fs.weight(),
write.fs.curv(),
write.fs.label.gii(),
write.fs.mgh(),
write.fs.morph(),
write.fs.morph.asc(),
write.fs.morph.gii(),
write.fs.morph.ni1(),
write.fs.morph.ni2(),
write.fs.morph.smp(),
write.fs.morph.txt(),
write.fs.weight(),
write.fs.weight.asc()
Examples
curvfile <- system.file("extdata", "lh.thickness",
package = "freesurferformats", mustWork = TRUE
)
ct <- read.fs.curv(curvfile)
cat(sprintf(
"Read data for %d vertices. Values: min=%f, mean=%f, max=%f.\n",
length(ct), min(ct), mean(ct), max(ct)
))
Read FreeSurfer GCA file.
Description
Read FreeSurfer GCA file.
Usage
read.fs.gca(filepath)
Arguments
filepath |
character string, path to a file in binary GCA format. Stores array of Gaussian classifiers for probabilistic atlas. |
Value
named list, the file fields. The GCA data is in the data field.
Author(s)
This function is based on Matlab code by Bruce Fischl, published under the FreeSurfer Open Source License available at https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense. The R version was written by Tim Schaefer.
Examples
## Not run:
gca_file <- file.path(Sys.getenv("FREESURFER_HOME"), "average", "face.gca")
gca <- read.fs.gca(gca_file)
## End(Not run)
Read a label file.
Description
Read a label file.
Usage
read.fs.label(filepath, format = "auto", ...)
Arguments
filepath |
string. Full path to the input label file. |
format |
character string, one of 'auto' to detect by file extension, 'asc' for native FreeSurfer ASCII label format, or 'gii' for GIFTI label format. |
... |
extra paramters passed to the respective label function for the format |
Note
See read.fs.label.native for more details, including important information on loading FreeSurfer volume labels.
See Also
Other label functions:
read.fs.label.gii(),
read.fs.label.native(),
write.fs.label()
Examples
labelfile <- system.file("extdata", "lh.entorhinal_exvivo.label",
package = "freesurferformats", mustWork = TRUE
)
label <- read.fs.label(labelfile)
Read a label from a GIFTI label/annotation file.
Description
Read a label from a GIFTI label/annotation file.
Usage
read.fs.label.gii(filepath, label_value = 1L, element_index = 1L)
Arguments
filepath |
string. Full path to the input label file. |
label_value |
integer, the label value of interest to extract from the annotation: the indices of the vertices with this value will be returned. See the note for details.. It is important to set this correctly, otherwise you may accidently load the vertices which are not part of the label. |
element_index |
positive integer, the index of the data array to return. Ignored unless the file contains several data arrays. |
Value
integer vector, the vertex indices of the label
Note
A GIFTI label is more like a FreeSurfer annotation, as it assigns a label integer (region code) to each vertex of the surface instead of listing only the set of 'positive' vertex indices. If you are not sure about the contents of the label file, it is recommended to read it with read.fs.annot.gii instead. The read.fs.label.gii function only extracts one of the regions from the annotation as a label, while read.fs.annot.gii reads the whole annotation and gives you access to the label table, which should assign region names to each region, making it clearer which 'label_value' you want.
See Also
Other label functions:
read.fs.label(),
read.fs.label.native(),
write.fs.label()
Other gifti readers:
read.fs.annot.gii(),
read.fs.morph.gii(),
read.fs.surface.gii()
Read file in FreeSurfer label format
Description
Read a mask in FreeSurfer label format. A label defines a list of vertices (of an associated surface or morphometry file) which are part of it. All others are not. You can think of it as binary mask. Label files are ASCII text files, which have 5 columns (vertex index, coord1, coord2, coord3, value), but only the vertex indices are of interest. A label can also contain voxels, in that case the indices are -1 and the coordinates are important.
Usage
read.fs.label.native(
filepath,
return_one_based_indices = TRUE,
full = FALSE,
metadata = list()
)
Arguments
filepath |
string. Full path to the input label file. |
return_one_based_indices |
logical. Whether the indices should be 1-based. Indices are stored zero-based in the file, but R uses 1-based indices. Defaults to TRUE, which means that 1 will be added to all indices read from the file before returning them. Notice that for volume labels, the indices are negative (-1), and the coord fields contain the positions of the voxels it tkras space (not the voxel indices in a volume). If a file contains negative indices, they will NOT be incremented, no matter what this is set to. |
full |
logical, whether to return a full object of class |
metadata |
named list of arbitrary metadata to store in the instance, ignored unless the paramter |
Value
vector of integers or fs.label instance (see parameter full). The vertex indices from the label file. See the parameter return_one_based_indices for important information regarding the start index.
Note
To load volume/voxel labels, you will have to set the 'full' parameter to TRUE.
See Also
Other label functions:
read.fs.label(),
read.fs.label.gii(),
write.fs.label()
Examples
labelfile <- system.file("extdata", "lh.entorhinal_exvivo.label",
package = "freesurferformats", mustWork = TRUE
)
label <- read.fs.label(labelfile)
Read file in FreeSurfer MGH or MGZ format
Description
Read multi-dimensional brain imaging data from a file in FreeSurfer binary MGH or MGZ format. The MGZ format is just a gzipped version of the MGH format. For a subject (MRI image pre-processed with FreeSurfer) named 'bert', an example file would be 'bert/mri/T1.mgz', which contains a 3D brain scan of bert.
Usage
read.fs.mgh(
filepath,
is_gzipped = "AUTO",
flatten = FALSE,
with_header = FALSE,
drop_empty_dims = FALSE
)
Arguments
filepath |
string. Full path to the input MGZ or MGH file. |
is_gzipped |
a logical value or the string 'AUTO'. Whether to treat the input file as gzipped, i.e., MGZ instead of MGH format. Defaults to 'AUTO', which tries to determine this from the last three characters of the 'filepath' parameter. Files with extensions 'mgz' and '.gz' (in arbitrary case) are treated as MGZ format, all other files are treated as MGH. In the special case that 'filepath' has less than three characters, MGH is assumed. |
flatten |
logical. Whether to flatten the return volume to a 1D vector. Useful if you know that this file contains 1D morphometry data. |
with_header |
logical. Whether to return the header as well. If TRUE, return an instance of class |
drop_empty_dims |
logical, whether to drop empty dimensions of the returned data |
Value
data, multi-dimensional array. The brain imaging data, one value per voxel. The data type and the dimensions depend on the data in the file, they are read from the header. If the parameter flatten is TRUE, a numeric vector is returned instead. Note: The return value changes if the parameter with_header is TRUE, see parameter description.
See Also
To derive more information from the header, see the mghheader.* functions, like mghheader.vox2ras.tkreg.
Other morphometry functions:
fs.get.morph.file.ext.for.format(),
fs.get.morph.file.format.from.filename(),
read.fs.curv(),
read.fs.morph(),
read.fs.morph.gii(),
read.fs.volume(),
read.fs.weight(),
write.fs.curv(),
write.fs.label.gii(),
write.fs.mgh(),
write.fs.morph(),
write.fs.morph.asc(),
write.fs.morph.gii(),
write.fs.morph.ni1(),
write.fs.morph.ni2(),
write.fs.morph.smp(),
write.fs.morph.txt(),
write.fs.weight(),
write.fs.weight.asc()
Examples
brain_image <- system.file("extdata", "brain.mgz",
package = "freesurferformats",
mustWork = TRUE
)
vd <- read.fs.mgh(brain_image)
cat(sprintf(
"Read voxel data with dimensions %s. Values: min=%d, mean=%f, max=%d.\n",
paste(dim(vd), collapse = " "), min(vd), mean(vd), max(vd)
))
# Read it again with full header data:
vdh <- read.fs.mgh(brain_image, with_header = TRUE)
# Use the vox2ras matrix from the header to compute RAS coordinates at CRS voxel (0, 0, 0):
vdh$header$vox2ras_matrix %*% c(0, 0, 0, 1)
Read morphometry data file in any FreeSurfer format.
Description
Read vertex-wise brain surface data from a file. The file can be in any of the supported formats, and the format will be determined from the file extension.
Usage
read.fs.morph(filepath, format = "auto")
Arguments
filepath |
string. Full path to the input file. The suffix determines the expected format as follows: ".mgz" and ".mgh" will be read with the read.fs.mgh function, all other file extensions will be read with the read.fs.curv function. |
format |
character string, the format to use. One of c("auto", "mgh", "mgz", "curv", "gii"). The default setting "auto" will determine the format from the file extension. |
Value
data, vector of floats. The brain morphometry data, one value per vertex.
Note
CIFTI-2 files (which are NIFTI-2 files, see read.cifti) are
refused with an error instead of being read as NIFTI morphometry data: their
payload is a matrix whose dimensions the CIFTI XML metadata describes, so the
values would come back in an order that means nothing. Use
read.fs.morph.cifti to read the morphometry data of one brain
structure, or read.cifti for the matrix itself.
See Also
Other morphometry functions:
fs.get.morph.file.ext.for.format(),
fs.get.morph.file.format.from.filename(),
read.fs.curv(),
read.fs.mgh(),
read.fs.morph.gii(),
read.fs.volume(),
read.fs.weight(),
write.fs.curv(),
write.fs.label.gii(),
write.fs.mgh(),
write.fs.morph(),
write.fs.morph.asc(),
write.fs.morph.gii(),
write.fs.morph.ni1(),
write.fs.morph.ni2(),
write.fs.morph.smp(),
write.fs.morph.txt(),
write.fs.weight(),
write.fs.weight.asc()
Examples
curvfile <- system.file("extdata", "lh.thickness",
package = "freesurferformats", mustWork = TRUE
)
ct <- read.fs.morph(curvfile)
cat(sprintf(
"Read data for %d vertices. Values: min=%f, mean=%f, max=%f.\n",
length(ct), min(ct), mean(ct), max(ct)
))
mghfile <- system.file("extdata", "lh.curv.fwhm10.fsaverage.mgz",
package = "freesurferformats", mustWork = TRUE
)
curv <- read.fs.morph(mghfile)
cat(sprintf(
"Read data for %d vertices. Values: min=%f, mean=%f, max=%f.\n",
length(ct), min(ct), mean(ct), max(ct)
))
Read morphometry data from ASCII curv format file
Description
Read morphometry data from ASCII curv format file
Usage
read.fs.morph.asc(filepath)
Arguments
filepath |
path to a file in FreeSurfer ASCII curv format. Such a file contains, on each line, the following fields, separated by spaces: vertex_index, vertex_coord_x, vertex_coord_y, vertex_coord_z, morph_data_value. |
Value
numeric vector, the curv data
Note
This format is also known as dpv (data-per-vertex) format.
Read Brainvoyager vertex-wise statistical surface data from SMP file.
Description
Read Brainvoyager vertex-wise statistical surface data from SMP file.
Usage
read.fs.morph.bvsmp(filepath, map_index = 1L)
Arguments
filepath |
character string, path to file in Brainvoyager SMP file format. Alternatively, a 'bvsmp' instance read with |
map_index |
positive integer or character string, the surface value map to load (an SMP file can contain several values per vertex, i.e., several surface maps). If an integer, interpreted as the index of the map. If a character string, as the name of the map. |
Value
numeric vector, the values from the respective map.
Read surface morphometry data from CIFTI dscalar files.
Description
Read the data from a CIFTI dscalar file (or any other CIFTI-2 file with a single brainordinate dimension, e.g. a '.dtseries') and reconstruct it for one brain structure, based on the metadata like vertex counts, indices and offset in the CIFTI file. The result is a vector with one value per vertex of the surface.
Usage
read.fs.morph.cifti(
filepath,
brain_structure = "CIFTI_STRUCTURE_CORTEX_LEFT",
data_column = 1L
)
Arguments
filepath |
character string, the full path to a file in CIFTI 2 format, should end with '.dscalar.nii'. Note that this is NOT a NIFTI file, despite the '.nii' part. It uses a CIFTIv2 header though. See the spec for details. An 'fs.cifti' object from |
brain_structure |
character string or integer, the brain structure for which the data should be extracted from the file. Can be a CIFTI brain structure string (one of 'CIFTI_STRUCTURE_CORTEX_LEFT' or 'CIFTI_STRUCTURE_CORTEX_RIGHT'), or simply one of 'lh', 'rh' (which are used as aliases for the former). If you specify 'both', the concatenated data for 'lh' (first) and 'rh' will be returned, but you will get no information on hemi boundaries. If it is an integer, it will be interpreted as an index into the list of structures within the CIFTI file, use with care. |
data_column |
integer, the data column to return. A CIFTI file can contain several measures in different data columns (e.g., cortical thickness and surface area) in a single file. This specifies which column/measure you want. The columns are not named, so you will need to know this in advance if the file has several measures. |
Value
The reconstructed data for the given surface, one value per vertex in the surface. The value for vertices which did not have a value in the CIFTI data is set to NA. Note that the result always has the length of the complete surface: CIFTI files like the ones used in the HCP leave out the medial wall vertices, and the result reports those as NA.
References
See https://www.nitrc.org/forum/attachment.php?attachid=341&group_id=454&forum_id=1955 for the CIFTI 2 file format spec. See https://www.nitrc.org/projects/cifti/ for more details on CIFTI, including example files.
Examples
cifti_file <- system.file("extdata", "cifti", "tiny.dscalar.nii", package = "freesurferformats")
morph_lh <- read.fs.morph.cifti(cifti_file, "lh")
length(morph_lh)
morph_lh2 <- read.fs.morph.cifti(cifti_file, "lh", 2L)
morph_both <- read.fs.morph.cifti(cifti_file, "both")
Read morphometry data file in GIFTI format.
Description
Read vertex-wise brain surface data from a GIFTI file. The file must be a GIFTI func file (not a GIFTI surf file containing a mesh, use read_nisurface for loading GIFTI surf files).
Usage
read.fs.morph.gii(filepath, element_index = 1L)
Arguments
filepath |
string. Full path to the input GIFTI file. |
element_index |
integer, the element to load in case the GIFTI file containes several datasets (usually time series). Defaults to the first element, 1L. |
Value
data, vector of double or integer. The brain morphometry data, one value per vertex. The data type depends on the data type in the file.
Note
This function requires the gifti package, which is an optional dependency, to be installed. It also assumes that the dataset contains a vector or a matrix/array in which all dimensions except for 1 are empty.
See Also
Other morphometry functions:
fs.get.morph.file.ext.for.format(),
fs.get.morph.file.format.from.filename(),
read.fs.curv(),
read.fs.mgh(),
read.fs.morph(),
read.fs.volume(),
read.fs.weight(),
write.fs.curv(),
write.fs.label.gii(),
write.fs.mgh(),
write.fs.morph(),
write.fs.morph.asc(),
write.fs.morph.gii(),
write.fs.morph.ni1(),
write.fs.morph.ni2(),
write.fs.morph.smp(),
write.fs.morph.txt(),
write.fs.weight(),
write.fs.weight.asc()
Other gifti readers:
read.fs.annot.gii(),
read.fs.label.gii(),
read.fs.surface.gii()
Read morphometry data from FreeSurfer NIFTI v1 format files.
Description
Read morphometry data from FreeSurfer NIFTI v1 format files.
Usage
read.fs.morph.ni1(filepath)
Arguments
filepath |
path to a file in FreeSurfer NIFTI v1 format, potentially with the FreeSurfer hack. See |
Value
numeric vector, the morphometry data
Note
This function uses our internal NIFTI reader that supports NIFTI v1 files with the FreeSurfer hack. This function assumes that the data in a file is a 1D vector and flattens it accordingly. It is not suitable to load NIFTI files with arbitrary dimensions.
Read morphometry data from FreeSurfer NIFTI v2 format files.
Description
Read morphometry data from FreeSurfer NIFTI v2 format files.
Usage
read.fs.morph.ni2(filepath)
Arguments
filepath |
path to a file in FreeSurfer NIFTI v2 format, potentially with the FreeSurfer hack. See |
Value
numeric vector, the morphometry data
Read morphometry data from FreeSurfer NIFTI format files, determine NIFTI version automatically.
Description
Read morphometry data from FreeSurfer NIFTI format files, determine NIFTI version automatically.
Usage
read.fs.morph.nii(filepath)
Arguments
filepath |
path to a file in FreeSurfer NIFTI v1 or v2 format, potentially with the FreeSurfer hack for v1. See |
Value
numeric vector, the morphometry data
Read morphometry data from plain text file
Description
Read morphometry data from plain text file
Usage
read.fs.morph.txt(filepath)
Arguments
filepath |
path to a file in plain text format. Such a file contains, on each line, a single float value. This very simply and limited format is used by the LGI tool by Lyu et al., and easy to generate in shell scripts. |
Value
numeric vector, the curv data
Read surface parcellation data from CIFTI dlabel files.
Description
Read the data from a CIFTI dlabel file (a dense surface parcellation, i.e., an integer label key per vertex) and return the per-vertex label keys for a single brain structure. This is the CIFTI analogue of a FreeSurfer annotation file.
Usage
read.fs.parcellation.cifti(
filepath,
brain_structure = "CIFTI_STRUCTURE_CORTEX_LEFT",
data_column = 1L,
with_label_table = FALSE
)
Arguments
filepath |
character string, the full path to a file in CIFTI 2 format, should end with '.dlabel.nii'. Note that this is NOT a NIfTI file, despite the '.nii' part; it uses a CIFTI 2 header instead. See the spec for details. An 'fs.cifti' object from |
brain_structure |
character string or integer, the brain structure for which the data should be extracted from the file. Can be a CIFTI brain structure string (one of 'CIFTI_STRUCTURE_CORTEX_LEFT' or 'CIFTI_STRUCTURE_CORTEX_RIGHT'), or simply one of 'lh', 'rh' (which are used as aliases for the former). If you specify 'both', the concatenated data for 'lh' (first) and 'rh' will be returned, but you will get no information on hemi boundaries. If it is an integer, it will be interpreted as an index into the list of structures within the CIFTI file, use with care. |
data_column |
integer, the data column (map) to return. A CIFTI dlabel file can contain several parcellations in different columns in a single file; this selects which one. The columns are not named, so you will need to know this in advance if the file has several maps (you can use the 'with_label_table' option to inspect the map names). |
with_label_table |
logical, whether to also return the label table (the mapping from label key to region name and RGBA color) for the selected map. If 'TRUE', the return value is a list, see the Value section. |
Value
If 'with_label_table' is 'FALSE' (the default), an integer vector with one label key per vertex in the surface. Vertices which did not have a value in the CIFTI data are set to NA; a key of 0 denotes the unknown / medial wall label (see the label table). If 'with_label_table' is 'TRUE', a named list with entries: 'label_keys' (the integer vector), 'label_table' (a data.frame with columns 'Key', 'Red', 'Green', 'Blue', 'Alpha' and 'Label', where the RGBA values are in the range 0 to 1), 'map_name' (the name of the selected map as a character string, or 'NULL' if unnamed), and 'brain_structure' (a character string). If 'brain_structure' is 'both' and 'with_label_table' is 'TRUE', a named list with entries 'lh' and 'rh', each as described above.
References
See https://www.nitrc.org/forum/attachment.php?attachid=341&group_id=454&forum_id=1955 for the CIFTI 2 file format spec. See https://www.nitrc.org/projects/cifti/ for more details on CIFTI, including example files.
Examples
label_file <- system.file("extdata", "cifti", "tiny.dlabel.nii", package = "freesurferformats")
parc_lh <- read.fs.parcellation.cifti(label_file, "lh")
table(parc_lh)
parc_with_table <- read.fs.parcellation.cifti(label_file, "lh", with_label_table = TRUE)
parc_with_table$label_table
Read FreeSurfer binary or ASCII patch file.
Description
A patch is a subset of a surface. Note that the contents of ASCII and binary patch format files is different. A binary format patch contains vertices only, without connection (face) information. ASCII patch files can also contain face data. See the return value description for details.
Usage
read.fs.patch(filepath, format = "auto")
Arguments
filepath |
string. Full path to the input patch file. An example file is |
format |
one of 'auto', 'asc', or 'bin'. The format to assume. If set to 'auto' (the default), binary format will be used unless the filepath ends with '.asc'. |
Value
named list with 2 entries: "faces": can be NULL, only available if the format is ASCII, see return value of read.fs.patch.asc. "vertices": numerical nx7 matrix. The columns are named, and appear in the following order: 'vert_index1': the one-based (R-style) vertex index. 'x', 'y', 'z': float vertex coordinates. 'is_border': integer, 1 if the vertex lies on the patch border, 0 otherwise (treat as logical). 'raw_vtx': integer, the raw vtx value encoding index and border. 'vert_index0': the zero-based (C-style) vertex index.
See Also
Other patch functions:
fs.patch(),
read.fs.patch.asc(),
write.fs.patch()
Read FreeSurfer ASCII format patch.
Description
An ASCII format patch is a part of a brain surface mesh, and is a mesh itself. It consists of vertices and faces. The ASCII patch format is very similar to the ASCII surface format. Note: The contents of ASCII and binary patch format files is different. The ASCII patch format is not ideal for parsing, and loading such files is currently quite slow.
Usage
read.fs.patch.asc(filepath)
Arguments
filepath |
string. Full path to the input patch file in ASCII patch format. |
Value
named list. The list has the following named entries: "vertices": see return value of read.fs.patch. "faces": numerical nx5 matrix. The columns are named, and appear in the following order: 'face_index1': the one-based (R-style) face index. 'vert1_index1', 'vert2_index1', 'vert3_index1': integer vertex indices of the face, they are one-based (R-style). 'face_index0': the zero-based (C-style) face index.
See Also
Other patch functions:
fs.patch(),
read.fs.patch(),
write.fs.patch()
Read surface time series data from CIFTI dtseries files.
Description
Read the data from a CIFTI dtseries file (a dense surface time series) and return the per-vertex time series for a single brain structure as a matrix.
Usage
read.fs.series.cifti(filepath, brain_structure = "CIFTI_STRUCTURE_CORTEX_LEFT")
Arguments
filepath |
character string, the full path to a file in CIFTI 2 format, should end with '.dtseries.nii'. Note that this is NOT a NIfTI file, despite the '.nii' part; it uses a CIFTI 2 header instead. See the spec for details. An 'fs.cifti' object from |
brain_structure |
character string or integer, the brain structure for which the data should be extracted from the file. Can be a CIFTI brain structure string (one of 'CIFTI_STRUCTURE_CORTEX_LEFT' or 'CIFTI_STRUCTURE_CORTEX_RIGHT'), or simply one of 'lh', 'rh' (which are used as aliases for the former). If you specify 'both', a named list with entries 'lh' and 'rh' will be returned. If it is an integer, it will be interpreted as an index into the list of structures within the CIFTI file, use with care. |
Value
A numeric matrix with one row per vertex in the surface and one column per time point (series point) in the file. The value for vertices which did not have a value in the CIFTI data is set to NA. If 'brain_structure' is 'both', a named list with entries 'lh' and 'rh', each a matrix as described above.
References
See https://www.nitrc.org/forum/attachment.php?attachid=341&group_id=454&forum_id=1955 for the CIFTI 2 file format spec. See https://www.nitrc.org/projects/cifti/ for more details on CIFTI, including example files.
Examples
cifti_file <- system.file("extdata", "cifti", "tiny.dtseries.nii", package = "freesurferformats")
series_lh <- read.fs.series.cifti(cifti_file, "lh")
dim(series_lh)
series_both <- read.fs.series.cifti(cifti_file, "both")
names(series_both)
Read file in FreeSurfer surface format or various mesh formats.
Description
Read a brain surface mesh consisting of vertex and face data from a file in FreeSurfer binary or ASCII surface format. For a subject (MRI image pre-processed with FreeSurfer) named 'bert', an example file would be 'bert/surf/lh.white'.
Usage
read.fs.surface(filepath, format = "auto")
Arguments
filepath |
string. Full path to the input surface file. Note: gzipped files are supported and gz format is assumed if the filepath ends with ".gz". |
format |
one of 'auto', 'asc', 'vtk', 'ply', 'gii', 'mz3', 'stl', 'byu', 'geo', 'ico', 'tri', 'obj', 'off' or 'bin'. The format to assume. If set to 'auto' (the default), binary format will be used unless the filepath ends with '.asc'. |
Value
named list. The list has the following named entries: "vertices": nx3 double matrix, where n is the number of vertices. Each row contains the x,y,z coordinates of a single vertex. "faces": nx3 integer matrix. Each row contains the vertex indices of the 3 vertices defining the face. This datastructure is known as a is a face index set. WARNING: The indices are returned starting with index 1 (as used in GNU R). Keep in mind that you need to adjust the index (by substracting 1) to compare with data from other software.
See Also
Other mesh functions:
faces.quad.to.tris(),
read.fs.surface.asc(),
read.fs.surface.bvsrf(),
read.fs.surface.geo(),
read.fs.surface.gii(),
read.fs.surface.ico(),
read.fs.surface.obj(),
read.fs.surface.off(),
read.fs.surface.ply(),
read.fs.surface.vtk(),
read.mesh.brainvoyager(),
read_nisurface(),
read_nisurfacefile(),
write.fs.surface(),
write.fs.surface.asc(),
write.fs.surface.byu(),
write.fs.surface.gii(),
write.fs.surface.mz3(),
write.fs.surface.vtk()
Examples
surface_file <- system.file("extdata", "lh.tinysurface",
package = "freesurferformats", mustWork = TRUE
)
mesh <- read.fs.surface(surface_file)
cat(sprintf(
"Read data for %d vertices and %d faces. \n",
nrow(mesh$vertices), nrow(mesh$faces)
))
Read FreeSurfer ASCII format surface.
Description
Read FreeSurfer ASCII format surface.
Usage
read.fs.surface.asc(filepath, with_values = TRUE, header_numlines = 2L)
Arguments
filepath |
string. Full path to the input surface file in ASCII surface format. |
with_values |
logical, whether to read per-vertex and per-face values. |
header_numlines |
scalar positive integer, the number of header lines. |
Value
named list. The list has the following named entries: "vertices": nx3 double matrix, where n is the number of vertices. Each row contains the x,y,z coordinates of a single vertex. "faces": nx3 integer matrix. Each row contains the vertex indices of the 3 vertices defining the face. WARNING: The indices are returned starting with index 1 (as used in GNU R). Keep in mind that you need to adjust the index (by substracting 1) to compare with data from other software.
Note
This is also known as srf format.
See Also
Other mesh functions:
faces.quad.to.tris(),
read.fs.surface(),
read.fs.surface.bvsrf(),
read.fs.surface.geo(),
read.fs.surface.gii(),
read.fs.surface.ico(),
read.fs.surface.obj(),
read.fs.surface.off(),
read.fs.surface.ply(),
read.fs.surface.vtk(),
read.mesh.brainvoyager(),
read_nisurface(),
read_nisurfacefile(),
write.fs.surface(),
write.fs.surface.asc(),
write.fs.surface.byu(),
write.fs.surface.gii(),
write.fs.surface.mz3(),
write.fs.surface.vtk()
Read Brainvoyager srf format (.srf) mesh as surface.
Description
Read a mesh and associated data like color and normals from a binary file in BrainVoyager SRF mesh format.
Usage
read.fs.surface.bvsrf(filepath)
Arguments
filepath |
string. Full path to the input surface file in SRF mesh format. |
Value
fs.surface instance
References
The srf format spec is at https://support.brainvoyager.com/brainvoyager/automation-development/84-file-formats/344-users-guide-2-3-the-format-of-srf-files.
See Also
Other mesh functions:
faces.quad.to.tris(),
read.fs.surface(),
read.fs.surface.asc(),
read.fs.surface.geo(),
read.fs.surface.gii(),
read.fs.surface.ico(),
read.fs.surface.obj(),
read.fs.surface.off(),
read.fs.surface.ply(),
read.fs.surface.vtk(),
read.mesh.brainvoyager(),
read_nisurface(),
read_nisurfacefile(),
write.fs.surface(),
write.fs.surface.asc(),
write.fs.surface.byu(),
write.fs.surface.gii(),
write.fs.surface.mz3(),
write.fs.surface.vtk()
Read mesh in BYU format.
Description
The BYU or Brigham Young University format is an old ASCII mesh format that is based on fixed character positions in lines (as opposed to whitespace-separated elements). I consider it a bit counter-intuitive.
Usage
read.fs.surface.byu(filepath, part = 1L)
Arguments
filepath |
full path of the file in BYU format. |
part |
positive integer, the index of the mesh that should be loaded from the file. Only relevant if the file contains more than one mesh. |
Value
an fs.surface instance, aka a mesh
References
See http://www.eg-models.de/formats/Format_Byu.html for a format description.
Read GEO format mesh as surface.
Description
This reads meshes from text files in GEO mesh format. This is an ASCII format.
Usage
read.fs.surface.geo(filepath)
Arguments
filepath |
string. Full path to the input surface file in GEO mesh format. |
Value
named list. The list has the following named entries: "vertices": nx3 double matrix, where n is the number of vertices. Each row contains the x,y,z coordinates of a single vertex. "faces": nx3 integer matrix. Each row contains the vertex indices of the 3 vertices defining the face. WARNING: The indices are returned starting with index 1 (as used in GNU R). Keep in mind that you need to adjust the index (by substracting 1) to compare with data from other software.
Note
This is a fixed width format.
See Also
Other mesh functions:
faces.quad.to.tris(),
read.fs.surface(),
read.fs.surface.asc(),
read.fs.surface.bvsrf(),
read.fs.surface.gii(),
read.fs.surface.ico(),
read.fs.surface.obj(),
read.fs.surface.off(),
read.fs.surface.ply(),
read.fs.surface.vtk(),
read.mesh.brainvoyager(),
read_nisurface(),
read_nisurfacefile(),
write.fs.surface(),
write.fs.surface.asc(),
write.fs.surface.byu(),
write.fs.surface.gii(),
write.fs.surface.mz3(),
write.fs.surface.vtk()
Read GIFTI format mesh as surface.
Description
Read GIFTI format mesh as surface.
Usage
read.fs.surface.gii(filepath)
Arguments
filepath |
string. Full path to the input surface file in GIFTI format. |
Value
named list. The list has the following named entries: "vertices": nx3 double matrix, where n is the number of vertices. Each row contains the x,y,z coordinates of a single vertex. "faces": nx3 integer matrix. Each row contains the vertex indices of the 3 vertices defining the face. WARNING: The indices are returned starting with index 1 (as used in GNU R). Keep in mind that you need to adjust the index (by substracting 1) to compare with data from other software.
See Also
Other mesh functions:
faces.quad.to.tris(),
read.fs.surface(),
read.fs.surface.asc(),
read.fs.surface.bvsrf(),
read.fs.surface.geo(),
read.fs.surface.ico(),
read.fs.surface.obj(),
read.fs.surface.off(),
read.fs.surface.ply(),
read.fs.surface.vtk(),
read.mesh.brainvoyager(),
read_nisurface(),
read_nisurfacefile(),
write.fs.surface(),
write.fs.surface.asc(),
write.fs.surface.byu(),
write.fs.surface.gii(),
write.fs.surface.mz3(),
write.fs.surface.vtk()
Other gifti readers:
read.fs.annot.gii(),
read.fs.label.gii(),
read.fs.morph.gii()
Read ICO format mesh as surface.
Description
This reads meshes from text files in ICO / TRI mesh format. This format is not to be confused with the the image format used to store tiny icons.
Usage
read.fs.surface.ico(filepath)
Arguments
filepath |
string. Full path to the input surface file in ICO or TRI mesh format. |
Value
named list. The list has the following named entries: "vertices": nx3 double matrix, where n is the number of vertices. Each row contains the x,y,z coordinates of a single vertex. "faces": nx3 integer matrix. Each row contains the vertex indices of the 3 vertices defining the face. WARNING: The indices are returned starting with index 1 (as used in GNU R). Keep in mind that you need to adjust the index (by substracting 1) to compare with data from other software.
Note
This is a fixed width format.
See Also
Other mesh functions:
faces.quad.to.tris(),
read.fs.surface(),
read.fs.surface.asc(),
read.fs.surface.bvsrf(),
read.fs.surface.geo(),
read.fs.surface.gii(),
read.fs.surface.obj(),
read.fs.surface.off(),
read.fs.surface.ply(),
read.fs.surface.vtk(),
read.mesh.brainvoyager(),
read_nisurface(),
read_nisurfacefile(),
write.fs.surface(),
write.fs.surface.asc(),
write.fs.surface.byu(),
write.fs.surface.gii(),
write.fs.surface.mz3(),
write.fs.surface.vtk()
Read surface mesh in mz3 format, used by Surf-Ice.
Description
The mz3 format is a binary file format that can store a mesh (vertices and faces), and optionally per-vertex colors or scalars.
Usage
read.fs.surface.mz3(filepath)
Arguments
filepath |
full path to surface mesh file in mz3 format. |
Value
an fs.surface instance. If the mz3 file contained RGBA per-vertex colors or scalar per-vertex data, these are available in the 'metadata' property.
References
See https://github.com/neurolabusc/surf-ice for details on the format.
Read OBJ format mesh as surface.
Description
This reads meshes from text files in Wavefront OBJ mesh format. This is an ASCII format.
Usage
read.fs.surface.obj(filepath)
Arguments
filepath |
string. Full path to the input surface file in Wavefront object mesh format. Files with non-standard vertex colors (3 additional float fields after the vertex coordinates in order R, G, B) are supported, and the colors will be returned in the field 'vertex_colors' if present. |
Value
named list. The list has the following named entries: "vertices": nx3 double matrix, where n is the number of vertices. Each row contains the x,y,z coordinates of a single vertex. "faces": nx3 integer matrix. Each row contains the vertex indices of the 3 vertices defining the face. WARNING: The indices are returned starting with index 1 (as used in GNU R). Keep in mind that you need to adjust the index (by substracting 1) to compare with data from other software.
Note
This is a simple but very common mesh format supported by many applications, well suited for export.
See Also
Other mesh functions:
faces.quad.to.tris(),
read.fs.surface(),
read.fs.surface.asc(),
read.fs.surface.bvsrf(),
read.fs.surface.geo(),
read.fs.surface.gii(),
read.fs.surface.ico(),
read.fs.surface.off(),
read.fs.surface.ply(),
read.fs.surface.vtk(),
read.mesh.brainvoyager(),
read_nisurface(),
read_nisurfacefile(),
write.fs.surface(),
write.fs.surface.asc(),
write.fs.surface.byu(),
write.fs.surface.gii(),
write.fs.surface.mz3(),
write.fs.surface.vtk()
Read Object File Format (OFF) mesh as surface.
Description
This reads meshes from text files in OFF mesh format. This is an ASCII format.
Usage
read.fs.surface.off(filepath)
Arguments
filepath |
string. Full path to the input surface file in OFF mesh format. |
Value
named list. The list has the following named entries: "vertices": nx3 double matrix, where n is the number of vertices. Each row contains the x,y,z coordinates of a single vertex. "faces": nx3 integer matrix. Each row contains the vertex indices of the 3 vertices defining the face. WARNING: The indices are returned starting with index 1 (as used in GNU R). Keep in mind that you need to adjust the index (by substracting 1) to compare with data from other software.
See Also
Other mesh functions:
faces.quad.to.tris(),
read.fs.surface(),
read.fs.surface.asc(),
read.fs.surface.bvsrf(),
read.fs.surface.geo(),
read.fs.surface.gii(),
read.fs.surface.ico(),
read.fs.surface.obj(),
read.fs.surface.ply(),
read.fs.surface.vtk(),
read.mesh.brainvoyager(),
read_nisurface(),
read_nisurfacefile(),
write.fs.surface(),
write.fs.surface.asc(),
write.fs.surface.byu(),
write.fs.surface.gii(),
write.fs.surface.mz3(),
write.fs.surface.vtk()
Read Stanford PLY format mesh as surface.
Description
This reads meshes from text files in PLY format. Note that this does not read arbitrary data from PLY files, i.e., PLY files can store data that is not supported by this function.
Usage
read.fs.surface.ply(filepath)
Arguments
filepath |
string. Full path to the input surface file in Stanford Triangle (PLY) format. |
Value
named list. The list has the following named entries: "vertices": nx3 double matrix, where n is the number of vertices. Each row contains the x,y,z coordinates of a single vertex. "faces": nx3 integer matrix. Each row contains the vertex indices of the 3 vertices defining the face. WARNING: The indices are returned starting with index 1 (as used in GNU R). Keep in mind that you need to adjust the index (by substracting 1) to compare with data from other software.
Note
This is by far not a complete PLY format reader. It can read PLY mesh files which were written by write.fs.surface.ply and Blender. Vertex colors and Blender vertex normals are currently ignored (but files with them are supported in the sense that the mesh data will be read correctly).
See Also
Other mesh functions:
faces.quad.to.tris(),
read.fs.surface(),
read.fs.surface.asc(),
read.fs.surface.bvsrf(),
read.fs.surface.geo(),
read.fs.surface.gii(),
read.fs.surface.ico(),
read.fs.surface.obj(),
read.fs.surface.off(),
read.fs.surface.vtk(),
read.mesh.brainvoyager(),
read_nisurface(),
read_nisurfacefile(),
write.fs.surface(),
write.fs.surface.asc(),
write.fs.surface.byu(),
write.fs.surface.gii(),
write.fs.surface.mz3(),
write.fs.surface.vtk()
Read mesh in STL format, auto-detecting ASCII versus binary format version.
Description
Read mesh in STL format, auto-detecting ASCII versus binary format version.
Usage
read.fs.surface.stl(filepath, digits = 6L, is_ascii = "auto")
Arguments
filepath |
full path to surface mesh file in STL format. |
digits |
the precision (number of digits after decimal separator) to use when determining whether two x,y,z coords define the same vertex. This is used when the polygon soup is turned into an indexed mesh. |
is_ascii |
logical, whether the file is in the ASCII version of the STL format (as opposed to the binary version). Can also be the character string 'auto', in which case the function will try to auto-detect the format. |
Value
an fs.surface instance, the mesh.
Note
The mesh is stored in the file as a polygon soup, which is transformed into an index mesh by this function.
Read surface mesh in STL ASCII format.
Description
The STL format is a mesh format that is often used for 3D printing, it stores geometry information. It is known as stereolithography format. A binary and an ASCII version exist. This function reads the ASCII version.
Usage
read.fs.surface.stl.ascii(filepath, digits = 6L)
Arguments
filepath |
full path to surface mesh file in STL format. |
digits |
the precision (number of digits after decimal separator) to use when determining whether two x,y,z coords define the same vertex. This is used when the polygon soup is turned into an indexed mesh. |
Value
an fs.surface instance. The normals of the faces are available in the 'metadata' property, in the entry 'normals' (a matrix with one row per face). Note that the normal vectors stored in the file are ignored, the returned normals are computed from the geometry, see mesh.face.normals.
Note
The STL format does not use indices into a vertex list to define faces, instead it repeats vertex coords in each face ('polygon soup'). Therefore, the mesh has to be reconstructed, which is what the internal function polygon.soup.to.indexed.mesh does.
References
See https://en.wikipedia.org/wiki/STL_(file_format) for a format description.
Read surface mesh in STL binary format.
Description
The STL format is a mesh format that is often used for 3D printing, it stores geometry information. It is known as stereolithography format. A binary and an ASCII version exist. This function reads the binary version.
Usage
read.fs.surface.stl.bin(filepath, digits = 6L)
Arguments
filepath |
full path to surface mesh file in STL format. |
digits |
the precision (number of digits after decimal separator) to use when determining whether two x,y,z coords define the same vertex. This is used when the polygon soup is turned into an indexed mesh. |
Value
an fs.surface instance. The normals of the faces are available in the 'metadata' property, in the entry 'normals' (a matrix with one row per face). Note that the normal vectors stored in the file are ignored, the returned normals are computed from the geometry, see mesh.face.normals.
Note
The STL format does not use indices into a vertex list to define faces, instead it repeats vertex coords in each face ('polygon soup').
References
See https://en.wikipedia.org/wiki/STL_(file_format) for the format spec.
Read VTK legacy format mesh as surface.
Description
Reads meshes from files in the VTK legacy format. Both the ASCII and the binary encoding are supported, as are the cell array layouts written by VTK 4.2 and older and by VTK 5.1 and newer, see the notes. See https://vtk.org/wp-content/uploads/2015/04/file-formats.pdf for the format specification. Note that this function does not read arbitrary VTK datasets, it supports only the geometry of POLYDATA datasets (meshes and point clouds); attribute data such as normals, texture coordinates or scalars is ignored. Only triangular meshes are supported, files containing other polygons are rejected with an error.
Usage
read.fs.surface.vtk(filepath)
Arguments
filepath |
string. Full path to the input surface file in VTK format. |
Value
named list. The list has the following named entries: "vertices": nx3 double matrix, where n is the number of vertices. Each row contains the x,y,z coordinates of a single vertex. "faces": nx3 integer matrix. Each row contains the vertex indices of the 3 vertices defining the face. WARNING: The indices are returned starting with index 1 (as used in GNU R). Keep in mind that you need to adjust the index (by substracting 1) to compare with data from other software.
Note
This is by far not a complete VTK format reader. Files that store
streamlines instead of a mesh (i.e., that contain a LINES section) are read
with read.fs.tracts.vtk.
See Also
Other mesh functions:
faces.quad.to.tris(),
read.fs.surface(),
read.fs.surface.asc(),
read.fs.surface.bvsrf(),
read.fs.surface.geo(),
read.fs.surface.gii(),
read.fs.surface.ico(),
read.fs.surface.obj(),
read.fs.surface.off(),
read.fs.surface.ply(),
read.mesh.brainvoyager(),
read_nisurface(),
read_nisurfacefile(),
write.fs.surface(),
write.fs.surface.asc(),
write.fs.surface.byu(),
write.fs.surface.gii(),
write.fs.surface.mz3(),
write.fs.surface.vtk()
Examples
surface_file <- system.file("extdata", "cube.vtk", package = "freesurferformats", mustWork = TRUE)
mesh <- read.fs.surface.vtk(surface_file)
cat(sprintf("Read a mesh with %d vertices and %d faces.\n", nrow(mesh$vertices), nrow(mesh$faces)))
Read VTK legacy format streamlines as tracts.
Description
Reads streamline (tractography) data from files in the VTK legacy format, i.e. from POLYDATA datasets that contain a LINES section. Both the ASCII and the binary encoding are supported, as are the cell array layouts written by VTK 4.2 and older and by VTK 5.1 and newer. This is the format that Paraview, TrackVis and DSI Studio export streamlines in. Attribute data such as scalar values per point is ignored.
Usage
read.fs.tracts.vtk(filepath)
Arguments
filepath |
character string, path to the input file in VTK legacy format. |
Value
an fs.tracts instance with the streamlines. Use
tracts[[i]] to get the n x 3 coordinate matrix of a single
streamline, and fs.tracts.lengths for the number of points of
each streamline.
Note
Points that are not part of any streamline are dropped, because the
fs.tracts data structure stores the coordinates of the streamlines
without gaps. A warning is issued if that happens.
Examples
# The example file was written by VTK and contains 3 streamlines.
# It also has a point that is not part of any streamline, which is dropped with a warning.
tracts_file <- system.file("extdata", "tracts_v51_binary.vtk",
package = "freesurferformats", mustWork = TRUE
)
tracts <- suppressWarnings(read.fs.tracts.vtk(tracts_file))
cat(sprintf(
"Read %d streamlines with %d points.\n",
length(tracts), nrow(fs.tracts.coords(tracts))
))
Load transformation matrix from a file.
Description
Load transformation matrix from a file.
Usage
read.fs.transform(filepath, format = "auto")
Arguments
filepath |
character string, the full path to the transform file. |
format |
character string, the file format. 'auto' guesses it from the file extension and the file content, and 'xfm' (for xform format), 'dat' (for tkregister style, e.g. register.dat), 'lta' (for FreeSurfer LTA), 'fslmat' (for an FSL/FLIRT matrix) and 'itk' (for an ITK text transform, e.g. a |
Value
an fs.transform instance, see fs.transform. Its fields include the 'matrix', and the
coordinate spaces the matrix maps between (space_in, space_out and voxel_base). Which of them are
known depends on the format: an xfm file states neither (both sides are RAS), a register.dat file states
both by definition, an FSL matrix maps voxel coordinates (zero-based) to voxel coordinates, and an LTA file
states the spaces in its header.
Note
Currently this function has been tested with linear transformation files only, all others are unsupported.
See Also
Other header coordinate space:
invert.fs.transform(),
is.fs.transform(),
mghheader.is.ras.valid(),
mghheader.ras2vox(),
mghheader.ras2vox.tkreg(),
mghheader.scanner2tkreg(),
mghheader.tkreg2scanner(),
mghheader.vox2ras(),
mghheader.vox2ras.tkreg(),
print.fs.transform(),
read.fs.transform.dat(),
read.fs.transform.fslmat(),
read.fs.transform.itk(),
read.fs.transform.lta(),
read.fs.transform.xfm(),
sm0to1(),
sm1to0(),
summary.fs.transform(),
transform2lps(),
transform2ras(),
transform2voxel(),
transform2world(),
write.fs.transform(),
write.fs.transform.dat(),
write.fs.transform.fslmat(),
write.fs.transform.itk(),
write.fs.transform.lta(),
write.fs.transform.xfm()
Examples
tf_file <- system.file("extdata", "talairach.xfm",
package = "freesurferformats",
mustWork = TRUE
)
transform <- read.fs.transform(tf_file)
transform$matrix
Load transformation matrix from a tkregister dat file.
Description
Load transformation matrix from a tkregister dat file.
Usage
read.fs.transform.dat(filepath)
Arguments
filepath |
character string, the full path to the transform file. |
Value
an fs.transform instance. A tkregister matrix maps the movable volume (the source) to the target
volume, so space_in is 'voxel' and space_out is 'ras'. It produces RAS coordinates in the tkregister
frame of the target volume, which is why dst states frame = 'tkreg', see
mghheader.vox2ras.tkreg. The other entries of the file are kept as the subject,
in_plane_resolution, between_plane_resolution and intensity fields.
See Also
Other header coordinate space:
invert.fs.transform(),
is.fs.transform(),
mghheader.is.ras.valid(),
mghheader.ras2vox(),
mghheader.ras2vox.tkreg(),
mghheader.scanner2tkreg(),
mghheader.tkreg2scanner(),
mghheader.vox2ras(),
mghheader.vox2ras.tkreg(),
print.fs.transform(),
read.fs.transform(),
read.fs.transform.fslmat(),
read.fs.transform.itk(),
read.fs.transform.lta(),
read.fs.transform.xfm(),
sm0to1(),
sm1to0(),
summary.fs.transform(),
transform2lps(),
transform2ras(),
transform2voxel(),
transform2world(),
write.fs.transform(),
write.fs.transform.dat(),
write.fs.transform.fslmat(),
write.fs.transform.itk(),
write.fs.transform.lta(),
write.fs.transform.xfm()
Examples
tf_file <- system.file("extdata", "register.dat",
package = "freesurferformats",
mustWork = TRUE
)
transform <- read.fs.transform.dat(tf_file)
transform$matrix
Read a transformation matrix from an FSL matrix file.
Description
Read the plain text 4x4 matrix that FSL's flirt writes with the -omat option, and that FSL,
MRtrix3 and FreeSurfer read as the registration between two images.
Usage
read.fs.transform.fslmat(filepath)
Arguments
filepath |
character string, the full path to the transform file. |
Value
an fs.transform instance. An FSL matrix maps the voxel coordinates of the image given to flirt -in to those of the image given to flirt -ref. Both are voxel indices, so space_in and space_out are
'voxel' and voxel_base is 0 (FSL voxel indices are zero-based). The two images are not recorded in the
file, so src and dst are NULL and the volumes have to be passed to transform2world
to interpret the matrix in world coordinates.
See Also
Other header coordinate space:
invert.fs.transform(),
is.fs.transform(),
mghheader.is.ras.valid(),
mghheader.ras2vox(),
mghheader.ras2vox.tkreg(),
mghheader.scanner2tkreg(),
mghheader.tkreg2scanner(),
mghheader.vox2ras(),
mghheader.vox2ras.tkreg(),
print.fs.transform(),
read.fs.transform(),
read.fs.transform.dat(),
read.fs.transform.itk(),
read.fs.transform.lta(),
read.fs.transform.xfm(),
sm0to1(),
sm1to0(),
summary.fs.transform(),
transform2lps(),
transform2ras(),
transform2voxel(),
transform2world(),
write.fs.transform(),
write.fs.transform.dat(),
write.fs.transform.fslmat(),
write.fs.transform.itk(),
write.fs.transform.lta(),
write.fs.transform.xfm()
Examples
# Write the example LTA as an FSL matrix and read it back: no FSL installation is needed for that.
lta_file <- system.file("extdata", "talairach.lta", package = "freesurferformats", mustWork = TRUE)
mat_file <- tempfile(fileext = ".mat")
write.fs.transform(read.fs.transform(lta_file), mat_file, format = "fslmat")
read.fs.transform(mat_file)$matrix
unlink(mat_file)
Read a transformation matrix from an ITK text transform file.
Description
Read the plain text file format that ITK and the tools built on it (3D Slicer, ANTs via
ConvertTransformFile, SimpleITK and the workflows of fMRIPrep/QSIPrep that are based on them) use to store
linear transformations, usually with the extension .tfm or .txt.
Usage
read.fs.transform.itk(filepath)
Arguments
filepath |
character string, the full path to the transform file. |
Value
an fs.transform instance. An ITK transform operates on the world coordinates of the images, which in
ITK are left-posterior-superior, so space_in and space_out are 'lps' and voxel_base is NA. This is
not the RAS space that the other formats of this package use, and it is not converted silently: use
transform2ras to get a transformation in RAS coordinates. The volumes are not recorded in
the file, so src and dst are NULL. The ITK class name (e.g. 'AffineTransform_float_3_3') is stored in
the type field, and the values of the FixedParameters entry in the fixed_parameters field.
Note
The format can store many kinds of transforms besides affine ones; this function reads the affine transformations only, i.e. the classes 'AffineTransform_float_3_3', 'AffineTransform_double_3_3', 'MatrixOffsetTransformBase_float_3_3' and 'MatrixOffsetTransformBase_double_3_3'. These are the classes that occur in the output of the pipelines mentioned above, and the only ones for which the interpretation of the parameters could be verified against other implementations. Files that contain several transformations (an ITK 'CompositeTransform') are not supported either, and are reported as such: composing them requires the ordering rules of ITK, which would be a guess without a reference to check against.
The FixedParameters entry is the center of rotation, so the matrix that is returned is
y = A(x - c) + t + c, i.e. it has the center folded in. That is the same thing that the ITK writer of
this package stores, and the transformation is not changed by it.
FreeSurfer reads ITK files as well, but two limitations of its version 7.4.1 are worth knowing when the file
has to be passed to it: it rejects the 'float' variant of the classes ('readITK: Transform type unknown!'),
and its lta_convert --initk ignores the FixedParameters, so it interprets a file with a non-zero center
of rotation differently from ITK itself (which computes offset = translation + center - matrix * center,
see ComputeOffset() in ITK's itkMatrixOffsetTransformBase.hxx) and from this package. Both were verified
by converting files that encode the same transformation, and both are avoided by the files that
write.fs.transform.itk writes.
See Also
Other header coordinate space:
invert.fs.transform(),
is.fs.transform(),
mghheader.is.ras.valid(),
mghheader.ras2vox(),
mghheader.ras2vox.tkreg(),
mghheader.scanner2tkreg(),
mghheader.tkreg2scanner(),
mghheader.vox2ras(),
mghheader.vox2ras.tkreg(),
print.fs.transform(),
read.fs.transform(),
read.fs.transform.dat(),
read.fs.transform.fslmat(),
read.fs.transform.lta(),
read.fs.transform.xfm(),
sm0to1(),
sm1to0(),
summary.fs.transform(),
transform2lps(),
transform2ras(),
transform2voxel(),
transform2world(),
write.fs.transform(),
write.fs.transform.dat(),
write.fs.transform.fslmat(),
write.fs.transform.itk(),
write.fs.transform.lta(),
write.fs.transform.xfm()
Examples
xfm_file <- system.file("extdata", "talairach.xfm", package = "freesurferformats", mustWork = TRUE)
tf <- transform2ras(transform2lps(read.fs.transform(xfm_file)))
summary(tf)$space_in
Load transformation matrix from a FreeSurfer linear transform array (LTA) file.
Description
Load transformation matrix from a FreeSurfer linear transform array (LTA) file.
Usage
read.fs.transform.lta(filepath)
Arguments
filepath |
character string, the full path to the transform file. |
Value
an fs.transform instance. The header of an LTA file states whether the matrix operates on voxel
indices (type 0, LINEAR_VOX_TO_VOX) or on RAS world coordinates (type 1, LINEAR_RAS_TO_RAS), and that is
used to set space_in, space_out and voxel_base. FreeSurfer voxel indices are zero-based. The file also
records both volumes it relates, so src and dst contain the file name, the dimensions, the voxel size
and the voxel-to-RAS matrix of each of them. The parsed header and volume info sections are kept in the
header and volumes fields.
Note
I found no spec for the LTA file format, only example files, so this function should be used with care. If you have a file that is not parsed correctly, please open an issue and attach it.
See Also
Other header coordinate space:
invert.fs.transform(),
is.fs.transform(),
mghheader.is.ras.valid(),
mghheader.ras2vox(),
mghheader.ras2vox.tkreg(),
mghheader.scanner2tkreg(),
mghheader.tkreg2scanner(),
mghheader.vox2ras(),
mghheader.vox2ras.tkreg(),
print.fs.transform(),
read.fs.transform(),
read.fs.transform.dat(),
read.fs.transform.fslmat(),
read.fs.transform.itk(),
read.fs.transform.xfm(),
sm0to1(),
sm1to0(),
summary.fs.transform(),
transform2lps(),
transform2ras(),
transform2voxel(),
transform2world(),
write.fs.transform(),
write.fs.transform.dat(),
write.fs.transform.fslmat(),
write.fs.transform.itk(),
write.fs.transform.lta(),
write.fs.transform.xfm()
Examples
tf_file <- system.file("extdata", "talairach.lta",
package = "freesurferformats", mustWork = TRUE
)
transform <- read.fs.transform.lta(tf_file)
transform$matrix
Load transformation matrix from an XFM file.
Description
Load transformation matrix from an XFM file.
Usage
read.fs.transform.xfm(filepath)
Arguments
filepath |
character string, the full path to the transform file. |
Value
an fs.transform instance. An xfm file stores a linear transformation between two RAS (world)
coordinate spaces, typically the scanner space of a subject and the RAS space of an MNI or Talairach
template, so space_in and space_out are both 'ras' and voxel_base is NA. The volumes that the
transformation relates are not recorded in the file, so src and dst are NULL.
Note
Currently this function has been tested with linear transformation files only, all others are unsupported.
See Also
Other header coordinate space:
invert.fs.transform(),
is.fs.transform(),
mghheader.is.ras.valid(),
mghheader.ras2vox(),
mghheader.ras2vox.tkreg(),
mghheader.scanner2tkreg(),
mghheader.tkreg2scanner(),
mghheader.vox2ras(),
mghheader.vox2ras.tkreg(),
print.fs.transform(),
read.fs.transform(),
read.fs.transform.dat(),
read.fs.transform.fslmat(),
read.fs.transform.itk(),
read.fs.transform.lta(),
sm0to1(),
sm1to0(),
summary.fs.transform(),
transform2lps(),
transform2ras(),
transform2voxel(),
transform2world(),
write.fs.transform(),
write.fs.transform.dat(),
write.fs.transform.fslmat(),
write.fs.transform.itk(),
write.fs.transform.lta(),
write.fs.transform.xfm()
Examples
tf_file <- system.file("extdata", "talairach.xfm",
package = "freesurferformats",
mustWork = TRUE
)
transform <- read.fs.transform.xfm(tf_file)
transform$matrix
Read volume file in MGH, MGZ or NIFTI format
Description
Read multi-dimensional brain imaging data from a file.
Usage
read.fs.volume(
filepath,
format = "auto",
flatten = FALSE,
with_header = FALSE,
drop_empty_dims = FALSE
)
Arguments
filepath |
string. Full path to the input MGZ, MGH or NIFTI file. |
format |
character string, one one of 'auto', 'nii', 'mgh', 'mgz', 'nrrd' or 'analyze'. The format to assume. If set to 'auto' (the default), the format will be derived from the file extension. The value 'analyze' covers the two-file image formats ANALYZE 7.5 and NIFTI v1 pair files, which share the |
flatten |
logical. Whether to flatten the return volume to a 1D vector. Useful if you know that this file contains 1D morphometry data. |
with_header |
logical. Whether to return the header as well. If TRUE, return an instance of class |
drop_empty_dims |
logical, whether to drop empty dimensions of the returned data |
Value
data, multi-dimensional array. The brain imaging data, one value per voxel. The data type and the dimensions depend on the data in the file, they are read from the header. If the parameter flatten is TRUE, a numeric vector is returned instead. Note: The return value changes if the parameter with_header is TRUE, see parameter description.
Note
CIFTI-2 files (which are NIFTI-2 files, see read.cifti) are
refused with an error instead of being read as volumes: their payload is a
matrix whose dimensions the CIFTI XML metadata describes, so the values would
come back as voxels that mean nothing.
See Also
To derive more information from the header, see the mghheader.* functions, like mghheader.vox2ras.tkreg.
Other morphometry functions:
fs.get.morph.file.ext.for.format(),
fs.get.morph.file.format.from.filename(),
read.fs.curv(),
read.fs.mgh(),
read.fs.morph(),
read.fs.morph.gii(),
read.fs.weight(),
write.fs.curv(),
write.fs.label.gii(),
write.fs.mgh(),
write.fs.morph(),
write.fs.morph.asc(),
write.fs.morph.gii(),
write.fs.morph.ni1(),
write.fs.morph.ni2(),
write.fs.morph.smp(),
write.fs.morph.txt(),
write.fs.weight(),
write.fs.weight.asc()
Examples
brain_image <- system.file("extdata", "brain.mgz",
package = "freesurferformats",
mustWork = TRUE
)
vd <- read.fs.volume(brain_image)
cat(sprintf(
"Read voxel data with dimensions %s. Values: min=%d, mean=%f, max=%d.\n",
paste(dim(vd), collapse = " "), min(vd), mean(vd), max(vd)
))
# Read it again with full header data:
vdh <- read.fs.volume(brain_image, with_header = TRUE)
# Use the vox2ras matrix from the header to compute RAS coordinates at CRS voxel (0, 0, 0):
vox2ras_matrix <- mghheader.vox2ras(vdh)
vox2ras_matrix %*% c(0, 0, 0, 1)
Read an ANALYZE 7.5 or NIFTI v1 pair file as an fs.volume.
Description
Read a volume from the two-file image formats ANALYZE 7.5 and NIFTI v1: a 348 byte header
(<base>.hdr) and the voxel data in a separate file (<base>.img). Read
read.analyze.header for the difference between the two variants and for the limitations of the
ANALYZE header.
Usage
read.fs.volume.analyze(
filepath,
flatten = FALSE,
with_header = FALSE,
drop_empty_dims = FALSE,
spm = FALSE
)
Arguments
filepath |
character string, the path to one of the two files of the pair, or to its base name. See
|
flatten |
logical. Whether to flatten the return volume to a 1D vector. Useful if you know that this file contains 1D morphometry data. |
with_header |
logical. Whether to return the header as well. If TRUE, return an instance of class |
drop_empty_dims |
logical, whether to drop empty dimensions of the returned data |
spm |
logical, whether to interpret the ANALYZE header the way SPM, FreeSurfer and the other tools of the
ecosystem do. This concerns the fields that ANALYZE 7.5 leaves undefined but that SPM uses: |
Value
an fs.volume instance, i.e. a named list with the entries data (the voxel data) and header (the
image header), or only the data array if with_header is FALSE. The header is the format specific header (an
ANALYZE 7.5 header as returned by read.analyze.header for ANALYZE files, a NIFTI v1 header as
returned by read.nifti1.header for NIFTI pair files), and not an MGH header. In addition, the
following entries are present:
vox2ras_matrixthe 4x4 voxel-to-RAS transformation matrix, computed from the
sform/qformheader fields for NIFTI v1 pair files. For ANALYZE files this entry is only present ifspmisTRUE, see the note below.vox2ras_sourcecharacter string, a description of where the matrix comes from, one of
'sform','qform'(for NIFTI v1 pair files),'mat sidecar','spm origin'or'analyze convention'(for ANALYZE files, see the geometry section). Only present ifvox2ras_matrixis present.voldimonly present if
flattenisTRUE, exactly as in the other volume readers.filepath,filepath_header,filepath_imagethe paths of the header and data files.
The geometry of ANALYZE 7.5 files
The ANALYZE 7.5 header stores the voxel sizes (pix_dim) but neither the direction of the voxel axes in world
space nor the position of the image in it. This means that the left/right orientation of an ANALYZE image is
not known from the header, and no implementation of the format can know it: the format is famous for exactly
this problem, and the orient field that was added to fix it is set by some tools and ignored by others.
There are two ways to get a transformation matrix for such a file, and this function supports both:
- The MATLAB sidecar file
SPM and FreeSurfer write the transformation matrix into a file named
<base>.matnext to the<base>.imgfile, as a MATLAB v4 file with a variable namedmatorM. This matrix is real information from the file set, not a convention, so it is used whenever such a file is present, and thevox2ras_sourceof the result is'mat sidecar'. TheMvariant does not contain the flip of the first voxel axis that the format's original software applies, so that flip is added (this is also what the reference implementation of the format, nibabel, does). Note that the matrix in the file maps the 1-based voxel indices that MATLAB uses, and that the matrix returned here maps the 0-based indices that R and this package use: the difference is the sum of the rows of the rotation part, i.e. up to several millimeters, and getting it wrong is exactly the kind of silent error that is hard to notice. FreeSurfer writes only theMvariable, nibabel writes both. MATLAB files of version 5 and newer (the.matfiles that recent MATLAB versions write, which are compressed) cannot be read; such a file is reported and ignored, the volume data is still returned.- The SPM convention (
spm = TRUE) If there is no sidecar file, the SPM and FreeSurfer tools derive the geometry from the fields that ANALYZE leaves unused: the
originatorfield holds the voxel coordinates of the image origin, the voxel sizes give the axis lengths, and the axes are assumed to point to the left, the front and the top (diag(-x, y, z), the convention of the format's original software). The samespm = TRUEapplies the scale factor that SPM stores infunused1. Both are heuristics that the file does not state, which is why they are not used by default: a matrix from a convention can be wrong by a mirror image.
Without a sidecar file and with spm = FALSE (the default), no matrix is reported at all: the voxel sizes and
the orientation code are returned as they are stored, and you can build a matrix from them if the convention of
your choice is known to be the right one for your data.
See Also
read.analyze.header, read.analyze.data, read.fs.volume
Examples
hdrfile <- system.file("extdata", "analyze", "tiny_u8.hdr",
package = "freesurferformats", mustWork = TRUE
)
vol <- read.fs.volume.analyze(hdrfile, with_header = TRUE)
dim(vol$data)
vol$header$pix_dim
Read a 3D or 4D NIFTI file into an fs.volume instance with complete header.
Description
This function reads a NIFTI v1 or v2 file, or takes a nifti instance from the oro.nifti
package, and computes the MGH header fields from the NIFTI header data, allowing for proper orientation of
the contained image data (see mghheader.vox2ras and related functions).
Files are read with the NIFTI reader of this package, so the oro.nifti package is only needed if a
nifti instance is passed, or if reorient or extra arguments are used. Currently only few datatypes are
supported, and the orientation can only be derived if the sform or qform header field is present.
Usage
read.fs.volume.nii(
filepath,
flatten = FALSE,
with_header = FALSE,
drop_empty_dims = FALSE,
do_rotate = FALSE,
reorient = FALSE,
...
)
Arguments
filepath |
instance of class |
flatten |
logical. Whether to flatten the return volume to a 1D vector. Useful if you know that this file contains 1D morphometry data. |
with_header |
logical. Whether to return the header as well. If TRUE, return an instance of class |
drop_empty_dims |
logical, whether to drop empty dimensions of the returned data |
do_rotate |
logical, whether to rotate 3D volumes to compensate for storage order. WIP. |
reorient |
logical, whether to let |
... |
extra parameters passed to |
Value
an fs.volume instance. The header fields are computed from the NIFTI header. The data array is returned in the raw NIFTI file storage order (first dimension fastest), which is also the order used by the MGH/MGZ format. For a file, the NIFTI data scaling fields scl_slope/scl_inter of the header are applied to the values while reading (this is what the oro.nifti package does for files as well), for an oro.nifti instance the values are returned as they are stored in the instance. If the NIFTI file contains sform or qform geometry information, the returned header contains a vox2ras_matrix entry in addition to the MGH header fields, just like the header returned by read.fs.mgh.
Note
The data array is not reoriented, because the NIFTI geometry is stored in the sform/qform header fields, and these describe the raw file storage order. Reorientation as performed by oro.nifti::readNIfTI(reorient = TRUE) permutes or flips the data array without updating the sform fields, so the data array would no longer match the header of the returned fs.volume (and thus not the vox2ras_matrix used to map voxel indices to coordinates). Using reorient = TRUE, or passing a nifti instance that was read with reorient = TRUE, is therefore discouraged and results in a warning.
Files are read with the NIFTI reader of this package, which reads both NIFTI v1 and NIFTI v2 files and does not require the oro.nifti package. Two details of the way oro.nifti used to read files are kept, so that the returned values do not change: the NIFTI data scaling fields (scl_slope/scl_inter) are applied to the values while reading (see the return value section), and voxel sizes that are stored as 0 for a used dimension (or that are not finite) are reported as 1.
This is not supposed to be used to read 1D morphometry data from NIFTI files generated by FreeSurfer (e.g., by converting lh.thickness to NIFTI using mri_convert): such files contain a single dimension, and the volume returned for them is degenerate. Use read.fs.morph to read morphometry data.
References
See https://nifti.nimh.nih.gov/nifti-1/ for the NIfTI-1 data format spec.
See Also
oro.nifti::readNIfTI, read.fs.mgh
Examples
## Not run:
base_file <- "~/data/subject1_only/subject1/mri/brain"
# missing file ext.
mgh_file <- paste(base_file, ".mgz", sep = "")
# the standard MGH/MGZ file
nii_file <- paste(base_file, ".nii", sep = "")
# NIFTI file generated with mri_convert
brain_mgh <- read.fs.mgh(mgh_file, with_header = TRUE)
brain_nii <- read.fs.volume.nii(nii_file, with_header = TRUE)
all(brain_nii$data == brain_mgh$data)
# output: TRUE
all(mghheader.vox2ras(brain_nii) == mghheader.vox2ras(brain_mgh)) # output: TRUE
## End(Not run)
Read volume data from a file in NRRD format.
Description
Reads a volume from a file in NRRD format (.nrrd), i.e. the format that 3D Slicer,
ITK/SimpleITK, DTI-TK, DSI Studio and the teem tools use. Detached headers (.nhdr, whose
data are in separate files) and gzip-compressed files (.nrrd.gz) are supported as well, and
the reader is implemented in this package, so no additional R package or external software is
needed. The values are returned in the order in which they are stored in the file, and NRRD
stores the first axis fastest, which is the order that R uses for arrays as well, so the
returned array is shaped exactly like the volume described by the header.
Usage
read.fs.volume.nrrd(
filepath,
flatten = FALSE,
with_header = FALSE,
drop_empty_dims = FALSE
)
Arguments
filepath |
character string, path to the file in NRRD format. |
flatten |
logical, whether to return a numeric vector instead of a multidimensional array. |
with_header |
logical, whether to return an |
drop_empty_dims |
logical, whether to drop dimensions of length 1 from the returned data, e.g. the frame axis of a 3D volume that was stored as a 4D array with one volume. Note that NRRD files state their dimensionality explicitly, so unlike the MGH or NIfTI readers this one only drops dimensions that the file actually has. |
Value
a multidimensional array of the dimensions stated in the file header, a numeric vector
if flatten is TRUE, or an fs.volume instance if with_header is TRUE. The data type
of the array follows the file: integer for the integer types up to 32 bit, double for the
floating point types and for the 64 bit integer types (which have no R equivalent, values
above 2^53 lose precision, and a warning is raised in that case).
Note
The data are returned exactly as they are stored in the file: the reader does not
reorient, rescale or otherwise change them. Use the vox2ras_matrix entry of the header to
map voxel indices to RAS+ coordinates, which is the space in which FreeSurfer, NIfTI and the
rest of this package work. NRRD files that state the LPS space (which is what the ITK tools
write) are handled: the matrix is converted to RAS. For a volume whose file states no space
information at all, no matrix is available (the entry is NULL), since any matrix would be a
guess.
Diffusion MRI data in NRRD format carry their b-value and their gradient directions in
custom header fields (the convention of the teem tools, DTI-TK and 3D Slicer). They are
parsed into the dwi entry of the header by read.nrrd.header. The gradients are
given in the image frame, and the measurement_frame entry of the dwi list is the rotation
that maps them into the frame in which the measurement was performed; a caller that needs the
gradients in that frame has to apply it (multiply the vector by the matrix). The values can be
handed to read.dti.gradients together with one b-value per volume, see the
examples.
Examples
nrrd_file <- system.file("extdata", "nrrd", "vol_u8_raw.nrrd",
package = "freesurferformats", mustWork = TRUE
)
vol <- read.fs.volume.nrrd(nrrd_file)
dim(vol)
# Read the geometry as well:
volh <- read.fs.volume.nrrd(nrrd_file, with_header = TRUE)
volh$header$vox2ras_matrix
## Not run:
# Read a DWI volume and use its gradient table:
hdr <- read.nrrd.header("dwi.nrrd")
gradients <- read.dti.gradients(hdr$dwi$bvec, rep(hdr$dwi$b_value, hdr$dwi$num_gradients))
## End(Not run)
Read file in FreeSurfer weight or w format
Description
Read morphometry data in weight format (aka w files). A weight format file contains morphometry data for a set of vertices, defined by their index in a surface. This can be only a subset of the surface vertices.
Usage
read.fs.weight(filepath, format = "auto")
Arguments
filepath |
string. Full path to the input weight file. Weight files typically have the file extension '.w', but that is not enforced. |
format |
one of 'auto', 'asc', or 'bin'. The format to assume. If set to 'auto' (the default), binary format will be used unless the filepath ends with '.asc'. |
Value
the indices and weight data, as a named list. Entries: "vertex_indices": vector of n vertex indices. They are stored zero-based in the file, but are returned one-based (R-style). "value": double vector of length n, the morphometry data for the vertices. The data can be whatever you want.
See Also
Other morphometry functions:
fs.get.morph.file.ext.for.format(),
fs.get.morph.file.format.from.filename(),
read.fs.curv(),
read.fs.mgh(),
read.fs.morph(),
read.fs.morph.gii(),
read.fs.volume(),
write.fs.curv(),
write.fs.label.gii(),
write.fs.mgh(),
write.fs.morph(),
write.fs.morph.asc(),
write.fs.morph.gii(),
write.fs.morph.ni1(),
write.fs.morph.ni2(),
write.fs.morph.smp(),
write.fs.morph.txt(),
write.fs.weight(),
write.fs.weight.asc()
Read ASCII version of FreeSurfer weight file.
Description
Read ASCII version of FreeSurfer weight file. Called by read.fs.weight if parameter format is set to 'asc'.
Usage
read.fs.weight.asc(filepath)
Arguments
filepath |
string. Full path to the input weight file, must be in ASCII weight format. |
Value
the indices and weight data, as a named list. Entries: "vertex_indices": vector of n vertex indices. They are stored zero-based in the file, but are returned one-based (R-style). "value": double vector of length n, the morphometry data for the vertices. The data can be whatever you want.
Read the matrices of a MATLAB v4 data file.
Description
MATLAB v4 files (the format behind the .mat files that SPM and FreeSurfer write next to an
ANALYZE image, see read.fs.volume.analyze) are the simplest MATLAB data format: a small header
with the type, the dimensions, the imaginary flag and the variable name, followed by the raw values in column
major order. This function reads the matrices of such a file.
Usage
read.matlab.v4.matrix(filepath)
Arguments
filepath |
character string, the path of the file to read. |
Value
named list of matrices, one per variable in the file (a v4 file may contain several variables, which are
stored one after another). The names are the variable names (e.g. 'M' or 'mat'), and the values are
matrices of the stored dimensions. Returns NULL if the file is not a MATLAB v4 file, i.e. if no interpretation
of its content leads to a file whose size matches the declared variables. Other MATLAB file versions (v5 and
newer, which are compressed and have a completely different structure) are reported as NULL as well, instead
of returning data from a wrongly interpreted header.
Note
Only the numeric types of the format are read (double, float, int32, int16, uint16 and uint8, which are the type codes 0, 10, 20, 30, 40 and 50). Text matrices and variables with more than 2 dimensions are not supported, the latter because the v4 format cannot store them.
Read Brainvoyager srf format (.srf) mesh.
Description
Read a mesh and associated data like color and normals from a binary file in BrainVoyager SRF mesh format.
Usage
read.mesh.brainvoyager(filepath)
Arguments
filepath |
string. Full path to the input surface file in SRF mesh format. |
Value
named list of the elements in the file.
References
The srf format spec is at https://support.brainvoyager.com/brainvoyager/automation-development/84-file-formats/344-users-guide-2-3-the-format-of-srf-files.
See Also
Other mesh functions:
faces.quad.to.tris(),
read.fs.surface(),
read.fs.surface.asc(),
read.fs.surface.bvsrf(),
read.fs.surface.geo(),
read.fs.surface.gii(),
read.fs.surface.ico(),
read.fs.surface.obj(),
read.fs.surface.off(),
read.fs.surface.ply(),
read.fs.surface.vtk(),
read_nisurface(),
read_nisurfacefile(),
write.fs.surface(),
write.fs.surface.asc(),
write.fs.surface.byu(),
write.fs.surface.gii(),
write.fs.surface.mz3(),
write.fs.surface.vtk()
Read the ASCII header of an MRtrix TCK/TSF file.
Description
Reads lines up to and including the terminating 'END' line. The number of header lines is not limited, headers of real files contain a variable number of entries (command history, comments, ROI specifications).
Usage
read.mrtrix.header(filepath)
Arguments
filepath |
character string, path to the file. |
Value
named list with entries lines (the raw header lines),
gzipped (logical) and header (the parsed key-value pairs).
Read the data payload of an MRtrix TCK/TSF file.
Description
Reads the payload sequentially in chunks and splits it into
groups of values_per_point finite values, which are the points of the
individual streamlines.
The end of the data is normally marked by a group of Inf values, but that marker is not always present: the TSF test data shipped with this package has none, and the MRtrix reference reader treats the plain end of the file as a normal end of the streamline data as well. Its absence is therefore not an error here, it is only reported as a warning when the header states a larger number of streamlines than were found, i.e., when data really is missing.
Usage
read.mrtrix.stream(
con,
offset,
dsize,
endian,
values_per_point,
max_groups = Inf,
skip_groups = 0L,
bbox = NULL,
chunk_values = 4e+06,
filepath = "",
gzipped = FALSE,
expected_groups = NA_real_
)
Arguments
con |
a connection opened in binary read mode. |
offset |
numeric, byte offset of the payload. |
dsize |
integer, bytes per value (4 for Float32, 8 for Float64). |
endian |
character string, 'little' or 'big'. |
values_per_point |
integer, 3 for TCK (xyz triples) and 1 for TSF. |
max_groups |
numeric, stop after this many groups have been selected.
Use |
skip_groups |
integer, the number of streamlines to skip before selecting any. Skipped streamlines are never held in memory. |
bbox |
numeric vector of length 6 or NULL. If given, only streamlines
that have at least one point inside the box are selected. The box is given
as |
chunk_values |
integer, number of values to read per chunk. |
filepath |
character string, the path of the file, used in messages only. |
gzipped |
logical, whether the connection reads a gzip-compressed file. R cannot seek on gzip connections, so the header bytes are then skipped by reading and discarding them instead. |
expected_groups |
numeric, the number of groups (streamlines) stated in the header, or NA if the header does not contain a usable count. Only used to warn about a possibly truncated file, never to limit reading. |
Value
named list with entries data (matrix with
values_per_point columns holding the concatenated groups),
lengths (integer vector, number of points per group) and
terminator_seen (logical).
Read raw voxel values of a NIFTI v1/v2 or ANALYZE file from a connection.
Description
Read num_values voxel values of the data type described by the datatype and bitpix fields of
a header, in the endianness of the file. This is the shared low level reading code of the NIFTI and ANALYZE
readers.
Usage
read.nifti.values(fh, datatype, bitpix, num_values, endian)
Arguments
fh |
connection to read from, positioned at the first value. |
datatype |
integer, the |
bitpix |
integer, the |
num_values |
integer, the number of values to read. |
endian |
character string, the endianness of the file, 'little' or 'big'. |
Value
numeric or integer vector of length num_values, the raw values as they are stored in the file.
Note
The signedness of the data type is taken from nifti.dtype.info: an unsigned 8 bit value of
200 is returned as 200, not as -56. R's readBin reads integers as signed by default, and it silently ignores
a signed argument for 4 byte integers, so the three unsigned types need special care.
Read raw NIFTI v1 data from file (which may contain the FreeSurfer hack).
Description
Read raw NIFTI v1 data from file (which may contain the FreeSurfer hack).
Usage
read.nifti1.data(filepath, drop_empty_dims = TRUE, header = NULL)
Arguments
filepath |
path to a NIFTI v1 file (single file version), which can contain the FreeSurfer hack. |
drop_empty_dims |
logical, whether to drop empty dimensions in the loaded data array. |
header |
optional nifti header obtained from |
Value
the data in the NIFTI v1 file. Note that the NIFTI v1 header information (scaling, units, etc.) is not applied in any way: the data are returned raw, as read from the file. The information in the header is used to read the data with the proper data type and size.
Note
The FreeSurfer hack is a non-standard way to save long vectors (one dimension greater than 32k entries) in NIFTI v1 files. Files with this hack are produced when converting MGH or MGZ files containing such long vectors with the FreeSurfer 'mri_convert' tool.
Read NIFTI v1 header from file (which may contain the FreeSurfer hack).
Description
Read NIFTI v1 header from file (which may contain the FreeSurfer hack).
Usage
read.nifti1.header(filepath)
Arguments
filepath |
path to a NIFTI v1 file (single file version), which can contain the FreeSurfer hack. |
Value
named list with NIFTI 1 header fields.
Note
The FreeSurfer hack is a non-standard way to save long vectors (one dimension greater than 32767 entries) in NIFTI v1 files. Files with this hack are produced when converting MGH or MGZ files containing such long vectors with the FreeSurfer 'mri_convert' tool.
Read NIFTI v1 header from file (which may contain the FreeSurfer hack).
Description
Read NIFTI v1 header from file (which may contain the FreeSurfer hack).
Usage
read.nifti1.header.internal(filepath, little_endian = TRUE)
Arguments
filepath |
path to a NIFTI v1 file (single file version), which can contain the FreeSurfer hack. |
little_endian |
internal logical, leave this alone. Endianness will be figured out automatically, messing with this parameter only hurts. |
Value
named list with NIFTI 1 header fields.
Read raw data from NIFTI v2 file.
Description
Read raw data from NIFTI v2 file.
Usage
read.nifti2.data(filepath, header = NULL, drop_empty_dims = TRUE)
Arguments
filepath |
path to a NIFTI v2 file. |
header |
optional nifti v2 header obtained from |
drop_empty_dims |
logical, whether to drop empty dimensions in the loaded data array. |
Value
the data in the NIFTI v2 file. Note that the NIFTI v2 header information (scaling, units, etc.) is not applied in any way: the data are returned raw, as read from the file. The information in the header is used to read the data with the proper data type and size.
Read NIFTI v2 header from file.
Description
Read NIFTI v2 header from file.
Usage
read.nifti2.header(filepath)
Arguments
filepath |
path to a NIFTI v2 file. |
Value
named list with NIFTI 2 header fields. The header extensions, if the file has any, are returned in
the field extensions, a list in which each entry is one header extension as created by
nifti2.extension (i.e., a list with the entries 'ecode' and 'content'). CIFTI2 files store
their XML metadata in such an extension, see nifti2.get.extension.
See Also
Read NIFTI v2 header from file.
Description
Read NIFTI v2 header from file.
Usage
read.nifti2.header.internal(filepath, little_endian = TRUE)
Arguments
filepath |
path to a NIFTI v2 file. |
little_endian |
internal logical, leave this alone. Endianness will be figured out automatically, messing with this parameter only hurts. |
Value
named list with NIFTI 2 header fields, including the header extensions (field extensions, see read.nifti2.header).
Note
See https://nifti.nimh.nih.gov/pub/dist/data/nifti2/ for test data. Thanks to Anderson Winkler for his post at https://brainder.org/2015/04/03/the-nifti-2-file-format/.
Read the header of a file in NRRD format.
Description
Reads and parses the ASCII header of a NRRD file without touching the volume data. This is cheap, and it can be used to inspect a file, or to check its geometry, before deciding whether to read the data.
Usage
read.nrrd.header(filepath)
Arguments
filepath |
character string, path to the NRRD file ( |
Value
named list, the parsed header. The fields of the file are available under their
normalized names (e.g. space_directions for the field 'space directions'), and fields that
this function does not interpret are collected in the other_fields entry. The derived
entries are vox2ras_matrix (the 4x4 matrix that maps 0-based voxel indices to RAS+
coordinates, or NULL when the file states no geometry), vox2ras_source (how the matrix was
derived: 'space directions' or 'spacings'), data_files (the resolved paths of the data files
for a detached header, or NULL), data_offset (the byte offset of the data in the header
file), gzipped_file (whether the whole file is gzip-compressed), header_size (the size of
the header in bytes) and dwi (the parsed diffusion metadata, or NULL, see
read.fs.volume.nrrd).
Examples
nrrd_file <- system.file("extdata", "nrrd", "vol_u8_raw.nrrd",
package = "freesurferformats", mustWork = TRUE
)
hdr <- read.nrrd.header(nrrd_file)
hdr$sizes
hdr$vox2ras_matrix
Read Brainvoyager statistical surface results from SMP file.
Description
Read Brainvoyager statistical surface results from SMP file.
Usage
read.smp.brainvoyager(filepath)
Arguments
filepath |
character string, path to file in Brainvoyager SMP file format |
Value
named list of file contents
Note
Currently only SMP file versions 1 to 5 are supported, as these are the only ones for which a spec is available. The version is encoded in the file header.
References
see https://helpdesk.brainvoyager.com/brainvoyager/automation-development/84-file-formats/40-the-format-of-smp-files for the spec
Examples
## Not run:
# Surface mesh, requires BV demo dataset from website:
sf <- read.fs.surface.bvsrf("~/data/BrainTutorData/CG_LHRH_D65534.srf")
# Surface map of cortical thickness. Needs to be created in BV.
smp_file <- "~/data/BrainTutorData/CG_LHRH_D65534_Thickness.smp"
smp <- read.smp.brainvoyager(smp_file)
smp_data <- read.fs.morph.bvsmp(smp)
# could also pass smp_file.
fsbrain::vis.fs.surface(sf, per_vertex_data = smp_data)
## End(Not run)
Read Brainvoyager statistical surface results from v1 or v2 SMP file.
Description
Read Brainvoyager statistical surface results from v1 or v2 SMP file.
Usage
read.smp.brainvoyager.v1or2(filepath, version)
Arguments
filepath |
character string, path to file in Brainvoyager SMP file format |
Value
named list of file contents
Note
Do not call this, call read.smp.brainvoyager instead, which will figure out the version and call the appropriate function.
Read Brainvoyager statistical surface results from v3 SMP file.
Description
Read Brainvoyager statistical surface results from v3 SMP file.
Usage
read.smp.brainvoyager.v3(filepath)
Arguments
filepath |
character string, path to file in Brainvoyager SMP file format |
Value
named list of file contents
Note
Do not call this, call read.smp.brainvoyager instead, which will figure out the version and call the appropriate function.
Read Brainvoyager statistical surface results from v4 or v5 SMP file.
Description
Read Brainvoyager statistical surface results from v4 or v5 SMP file.
Usage
read.smp.brainvoyager.v4or5(filepath, version)
Arguments
filepath |
character string, path to file in Brainvoyager SMP file format |
Value
named list of file contents
Note
Do not call this, call read.smp.brainvoyager instead, which will figure out the version and call the appropriate function.
Read the track records of a TRK file.
Description
Reads track records from the current position of the connection
until the end of the file or until max_tracks records have been
selected. Coordinates and per-point scalars are stored interleaved in the
file, so each record is read with a single readBin call and split
afterwards, instead of reading one point at a time.
Usage
read.trk.records(
fh,
endian,
n_scalars,
n_properties,
max_tracks = Inf,
expected_tracks = NA_real_,
skip_tracks = 0L,
bbox = NULL,
transform = NULL,
gzipped = FALSE,
filepath = ""
)
Arguments
fh |
a connection opened in binary read mode, positioned at the start of the first track record. |
endian |
character string, 'little' or 'big'. |
n_scalars |
integer, number of scalars per point. |
n_properties |
integer, number of properties per track. |
max_tracks |
numeric, maximum number of tracks to select. Use
|
expected_tracks |
numeric, the number of tracks stated in the header, or NA if the header does not contain a usable count. Used to report truncated files, never to limit reading. |
skip_tracks |
integer, the number of tracks to skip before selecting
any, see |
bbox |
numeric vector of length 6 or NULL, a bounding box, see
|
transform |
4x4 numeric matrix or NULL. If given, it is applied to the coordinates of every track as it is read, before the bounding box filter is evaluated and before they are stored. This is used to filter in the target coordinate system without transforming the whole result twice. |
gzipped |
logical, whether the connection reads a gzip-compressed file,
see |
filepath |
character string, the path of the file, used in error messages and for skipping in compressed files. |
Value
named list with entries coords (matrix with 3 columns and one
row per point), lengths (integer vector, points per track),
scalars (matrix or NULL) and properties (matrix or NULL).
Read a VTK legacy file with a POLYDATA dataset.
Description
Reads the geometry (points and the cell arrays VERTICES, LINES and POLYGONS) of a VTK legacy file. Both the ASCII and the binary encoding are supported, as are the old and the new cell array layout, see the comment at the top of the file. Attribute data such as normals, texture coordinates or scalars is ignored.
Usage
read.vtk.legacy.polydata(filepath)
Arguments
filepath |
character string, path to the VTK file. |
Value
named list with the entries 'version' (character, the VTK version from the header), 'encoding' (character, 'ASCII' or 'BINARY'), 'points' (n x 3 double matrix, or NULL), 'verts', 'lines' and 'polys' (each a list of integer vectors with 0-based vertex indices, or NULL if the file does not contain that cell type), and 'ignored_sections' (character vector with the keywords of the sections that were not read, e.g. 'POINT_DATA').
Read a surface, based on the file path without extension.
Description
Tries to read all files which can be constructed from the base path and the given extensions.
Usage
read_nisurface(filepath_noext, extensions = c("", ".asc", ".gii"), ...)
Arguments
filepath_noext |
character string, the full path to the input surface file without file extension. |
extensions |
vector of character strings, the file extensions to try. |
... |
parameters passed on to |
Value
an instance of fs.surface, read from the file. See read.fs.surface for details. If none of the reader methods succeed, an error is raised.
See Also
Other mesh functions:
faces.quad.to.tris(),
read.fs.surface(),
read.fs.surface.asc(),
read.fs.surface.bvsrf(),
read.fs.surface.geo(),
read.fs.surface.gii(),
read.fs.surface.ico(),
read.fs.surface.obj(),
read.fs.surface.off(),
read.fs.surface.ply(),
read.fs.surface.vtk(),
read.mesh.brainvoyager(),
read_nisurfacefile(),
write.fs.surface(),
write.fs.surface.asc(),
write.fs.surface.byu(),
write.fs.surface.gii(),
write.fs.surface.mz3(),
write.fs.surface.vtk()
Examples
## Not run:
surface_filepath_noext <-
paste(get_optional_data_filepath("subjects_dir/subject1/surf/"),
"lh.white",
sep = ""
)
mesh <- read_nisurface(surface_filepath_noext)
mesh
## End(Not run)
S3 method to read a neuroimaging surface file.
Description
Tries to read the file with all implemented surface format reader methods. The file must exist. With the default settings, one can read files in the following surface formats: 1) FreeSurfer binary surface format (e.g., surf/lh.white). 2) FreeSurfer ASCII surface format (e.g., surf/lh.white,asc). 3) GIFTI surface format, only if package gifti is installed. See gifti::read_gifti for details. Feel free to implement additional methods. Hint:keep in mind that they should return one-based indices.
Usage
read_nisurfacefile(filepath, methods = c("fsnative", "fsascii", "gifti"), ...)
Arguments
filepath |
character string, the full path to the input surface file. |
methods |
list of character strings, the formats to try. Each of these must have a function called |
... |
parameters passed on to the individual methods |
Value
an instance of fs.surface, read from the file. See read.fs.surface for details. If none of the reader methods succeed, an error is raised.
See Also
Other mesh functions:
faces.quad.to.tris(),
read.fs.surface(),
read.fs.surface.asc(),
read.fs.surface.bvsrf(),
read.fs.surface.geo(),
read.fs.surface.gii(),
read.fs.surface.ico(),
read.fs.surface.obj(),
read.fs.surface.off(),
read.fs.surface.ply(),
read.fs.surface.vtk(),
read.mesh.brainvoyager(),
read_nisurface(),
write.fs.surface(),
write.fs.surface.asc(),
write.fs.surface.byu(),
write.fs.surface.gii(),
write.fs.surface.mz3(),
write.fs.surface.vtk()
Examples
surface_file <- system.file("extdata", "lh.tinysurface",
package = "freesurferformats", mustWork = TRUE
)
mesh <- read_nisurface(surface_file)
mesh
Read a FreeSurfer ASCII surface file.
Description
Read a FreeSurfer ASCII surface file.
Usage
## S3 method for class 'fsascii'
read_nisurfacefile(filepath, ...)
Arguments
filepath |
character string, the full path to the input surface file. |
... |
parameters passed to |
Value
an instance of fs.surface, read from the file. See read.fs.surface for details. If none of the reader methods succeed, an error is raised.
Read a FreeSurfer ASCII surface file.
Description
Read a FreeSurfer ASCII surface file.
Usage
## S3 method for class 'fsnative'
read_nisurfacefile(filepath, ...)
Arguments
filepath |
character string, the full path to the input surface file. |
... |
parameters passed to |
Value
an instance of fs.surface, read from the file. See read.fs.surface for details. If none of the reader methods succeed, an error is raised.
Read a gifti file as a surface.
Description
Read a gifti file as a surface.
Usage
## S3 method for class 'gifti'
read_nisurfacefile(filepath, ...)
Arguments
filepath |
character string, the full path to the input surface file. |
... |
ignored |
Value
an instance of fs.surface, read from the file. See read.fs.surface for details. If none of the reader methods succeed, an error is raised.
Safe wrapper around readBin that verifies the number of elements read.
Description
Calls readBin and then checks that the
returned vector has the expected length. If the file ends prematurely,
readBin silently returns fewer elements — this wrapper turns that
into an explicit error.
Usage
read_safe_bin(con, what, n, size, endian, ...)
Arguments
con |
a connection object. |
what |
character string or type, passed to |
n |
integer, the number of elements to read. |
size |
integer, the number of bytes per element. |
endian |
character string, |
... |
additional arguments passed to |
Value
the vector of data read from the connection.
Find files with the given base name and extensions that exist.
Description
Note that in the current implementation, the case of the filepath and the extension must match.
Usage
readable.files(
filepath,
precedence = c(".mgh", ".mgz"),
error_if_none = TRUE,
return_all = FALSE
)
Arguments
filepath |
character string, path to a file without extension |
precedence |
vector of character strings, the file extensions to check. Must include the dot (if you expect one). |
error_if_none |
logical, whether to raise an error if none of the files exist |
return_all |
logical, whether to return all readable files instead of just the first one |
Value
character string, the path to the first existing file (or NULL if none of them exists).
Read binary colortable in v2 format.
Description
Read a v2 format colortable from a connection to a binary file.
Usage
readcolortable(fh, ctable_num_entries)
Arguments
fh |
file handle |
ctable_num_entries |
number of entries to read |
Value
named list, the color table. The named entries are: "num_entries": int, number of brain structures. "struct_names": vector of strings, the brain structure names. "table": numeric matrix with num_entries rows and 5 colums. The 5 columns are: 1 = color red channel, 2=color blue channel, 3=color green channel, 4=color alpha channel, 5=unique color code.
Read binary colortable in old format.
Description
Read an oldformat colortable from a connection to a binary file.
Usage
readcolortable_oldformat(fh, ctable_num_entries)
Arguments
fh |
file handle |
ctable_num_entries |
number of entries to read |
Value
named list, the color table. The named entries are: "num_entries": int, number of brain structures. "struct_names": vector of strings, the brain structure names. "table": numeric matrix with num_entries rows and 5 colums. The 5 columns are: 1 = color red channel, 2=color blue channel, 3=color green channel, 4=color alpha channel, 5=unique color code.
Rotate a 2D matrix in 90 degree steps.
Description
Rotate a 2D matrix in 90 degree steps.
Usage
rotate2D(slice, degrees = 90)
Arguments
slice |
a 2D matrix |
degrees |
integer, must be a (positive or negative) multiple of 90 |
Value
2D matrix, the rotated matrix
Rotate a 3D array in 90 degree steps.
Description
Rotate a 3D array in 90 degree steps along an axis. This leads to an array with different dimensions.
Usage
rotate3D(volume, axis = 1L, degrees = 90L)
Arguments
volume |
a 3D image volume |
axis |
positive integer in range 1L..3L or an axis name, the axis to use. |
degrees |
integer, must be a (positive or negative) multiple of 90L. |
Value
a 3D image volume, rotated around the axis. The dimensions may or may not be different from the input image, depending on the rotation angle.
See Also
Other volume math:
flip3D()
Rotate 2D matrix clockwise in 90 degree steps.
Description
Rotate 2D matrix clockwise in 90 degree steps.
Usage
rotate90(mtx, times = 1L, clockwise = TRUE)
Arguments
mtx |
a 2D matrix |
times |
integer, how often to rotate in 90 degree steps. Example: pass |
clockwise |
logical, whether to rotate clockwise. |
Scan a tract file without holding its data in memory.
Description
Streams through the tract file and either counts the tracts, or computes the bounding box of all their points, or both. Nothing but the current chunk is ever held in memory, so this works on files of any size.
Usage
scan.dti.tract.file(filepath, want = c("count", "bbox"), chunk_values = 4e+06)
Arguments
filepath |
character string, path to the |
want |
character vector, any combination of 'count' and 'bbox'. |
chunk_values |
integer, number of payload values to read per chunk. |
Value
named list with the entries that were requested:
count (integer, the number of tracts) and bbox (numeric
vector of length 6, c(xmin, xmax, ymin, ymax, zmin, zmax)), or
NULL for bbox if no point was found.
Scan an MRtrix TCK or TSF file.
Description
Scan an MRtrix TCK or TSF file.
Usage
scan.mrtrix.file(filepath, want, chunk_values = 4e+06)
Arguments
filepath |
character string, path to the file. |
want |
character vector, the values to compute, see
|
chunk_values |
integer, number of payload values to read per chunk. |
Value
named list with entries count and bbox.
Scan a TRK file.
Description
Scan a TRK file.
Usage
scan.trk.file(filepath, want)
Arguments
filepath |
character string, path to the file. |
want |
character vector, the values to compute, see
|
Value
named list with entries count and bbox.
Scan exactly n values from source string.
Description
Scan exactly n values from source string.
Usage
scann(cstring, num = 1L, what = integer(), line_number = NULL)
Arguments
cstring |
the input character string |
num |
integer, the number of expected resulting items. |
line_number |
optional integer, the line number (if the string represents a line from a text file). Will be printed in error message, if any. |
Value
vector of type integer or double
Skip over bytes of a connection, transparently handling gzip.
Description
Skips forward from the current position of the connection. R
cannot seek on a gzfile connection (the underlying gzseek() fails
with 'invalid or incomplete compressed data' and only warns instead of
failing loudly), so compressed connections are skipped by reading and
discarding the bytes instead.
Usage
skip.connection.bytes(con, num_bytes, gzipped, filepath = "")
Arguments
con |
a connection opened in binary read mode. |
num_bytes |
numeric, the number of bytes to skip, relative to the current position of the connection. |
gzipped |
logical, whether the connection is a gzfile connection, as
reported by |
filepath |
character string, used in error messages only. |
Value
TRUE, invisibly.
Adapt spatial transformation matrix for 1-based indices.
Description
Adapt spatial transformation matrix for 1-based indices.
Usage
sm0to1(tf_matrix)
Arguments
tf_matrix |
4x4 numerical matrix, the input spatial transformation matrix, suitable for 0-based indices. Typically this is a vox2ras matrix obtained from functions like |
Value
4x4 numerical matrix, adapted spatial transformation matrix, suitable for 1-based indices.
See Also
sm1to0 for the inverse operation
Other header coordinate space:
invert.fs.transform(),
is.fs.transform(),
mghheader.is.ras.valid(),
mghheader.ras2vox(),
mghheader.ras2vox.tkreg(),
mghheader.scanner2tkreg(),
mghheader.tkreg2scanner(),
mghheader.vox2ras(),
mghheader.vox2ras.tkreg(),
print.fs.transform(),
read.fs.transform(),
read.fs.transform.dat(),
read.fs.transform.fslmat(),
read.fs.transform.itk(),
read.fs.transform.lta(),
read.fs.transform.xfm(),
sm1to0(),
summary.fs.transform(),
transform2lps(),
transform2ras(),
transform2voxel(),
transform2world(),
write.fs.transform(),
write.fs.transform.dat(),
write.fs.transform.fslmat(),
write.fs.transform.itk(),
write.fs.transform.lta(),
write.fs.transform.xfm()
Adapt spatial transformation matrix for 0-based indices.
Description
Adapt spatial transformation matrix for 0-based indices.
Usage
sm1to0(tf_matrix)
Arguments
tf_matrix |
4x4 numerical matrix, the input spatial transformation matrix, suitable for 1-based indices. |
Value
4x4 numerical matrix, adapted spatial transformation matrix, suitable for 0-based indices.
See Also
sm0to1 for the inverse operation
Other header coordinate space:
invert.fs.transform(),
is.fs.transform(),
mghheader.is.ras.valid(),
mghheader.ras2vox(),
mghheader.ras2vox.tkreg(),
mghheader.scanner2tkreg(),
mghheader.tkreg2scanner(),
mghheader.vox2ras(),
mghheader.vox2ras.tkreg(),
print.fs.transform(),
read.fs.transform(),
read.fs.transform.dat(),
read.fs.transform.fslmat(),
read.fs.transform.itk(),
read.fs.transform.lta(),
read.fs.transform.xfm(),
sm0to1(),
summary.fs.transform(),
transform2lps(),
transform2ras(),
transform2voxel(),
transform2world(),
write.fs.transform(),
write.fs.transform.dat(),
write.fs.transform.fslmat(),
write.fs.transform.itk(),
write.fs.transform.lta(),
write.fs.transform.xfm()
Split one chunk of MRtrix payload values into streamlines.
Description
A streamline is a maximal run of finite rows. A run that is not
followed by a separator belongs to the next chunk and is returned as
pending instead. Runs that contain no points at all (two consecutive
separators, which MRtrix writes for empty streamlines) are dropped, which
is what the 'nibabel' reader does as well.
Usage
## S3 method for class 'mrtrix.chunk'
split(mat, pending, finish_pending = FALSE)
Arguments
mat |
numeric matrix with one column per point value, the rows of the chunk, already truncated at the end-of-file marker if the chunk contains one. |
pending |
numeric matrix, the points of the streamline that is still being assembled from the previous chunk. |
finish_pending |
logical, whether the chunk ended in the end-of-file marker. In that case the pending streamline is complete and is returned as a regular streamline, and it must not be dropped. |
Value
named list with entries points (matrix holding the completed
streamlines, concatenated along the rows), lengths (integer vector
with the number of points of each completed streamline) and pending
(matrix, the points of the trailing incomplete streamline).
Guess whether a mesh file in STL format is the ASCII or the binary version.
Description
Guess whether a mesh file in STL format is the ASCII or the binary version.
Usage
stl.format.file.is.ascii(filepath)
Arguments
filepath |
full path to surface mesh file in STL format. |
Extract selected groups from a concatenated matrix.
Description
Extract selected groups from a concatenated matrix.
Usage
## S3 method for class 'groups'
subset(points, lengths, sel)
Arguments
points |
numeric matrix holding the concatenated rows of all groups. |
lengths |
integer vector with the number of rows of each group. |
sel |
integer vector, the indices of the groups to extract. |
Value
named list with entries points (matrix with the rows of the
selected groups) and lengths (their lengths).
Summarize an fs.transform instance.
Description
Compute the properties of a transformation in a machine-readable form, for printing or for further processing.
Usage
## S3 method for class 'fs.transform'
summary(object, ...)
Arguments
object |
an |
... |
ignored, only present for consistency with the generic. |
Value
named list with the entries 'format', 'source', 'space_in', 'space_out', 'voxel_base', 'src', 'dst' (the corresponding fields of the transform), 'translation' (numerical vector of length 3, the last column of the matrix), 'determinant', 'is_affine' (logical, whether the last row of the matrix is '0 0 0 1') and 'is_invertible' (logical).
See Also
Other header coordinate space:
invert.fs.transform(),
is.fs.transform(),
mghheader.is.ras.valid(),
mghheader.ras2vox(),
mghheader.ras2vox.tkreg(),
mghheader.scanner2tkreg(),
mghheader.tkreg2scanner(),
mghheader.vox2ras(),
mghheader.vox2ras.tkreg(),
print.fs.transform(),
read.fs.transform(),
read.fs.transform.dat(),
read.fs.transform.fslmat(),
read.fs.transform.itk(),
read.fs.transform.lta(),
read.fs.transform.xfm(),
sm0to1(),
sm1to0(),
transform2lps(),
transform2ras(),
transform2voxel(),
transform2world(),
write.fs.transform(),
write.fs.transform.dat(),
write.fs.transform.fslmat(),
write.fs.transform.itk(),
write.fs.transform.lta(),
write.fs.transform.xfm()
Examples
tf <- read.fs.transform(system.file("extdata", "register.dat",
package = "freesurferformats", mustWork = TRUE
))
summary(tf)$space_out
Translate surface RAS coordinates, as used in surface vertices and surface labels, to volume RAS.
Description
Translate surface RAS coordinates, as used in surface vertices and surface labels, to volume RAS.
Usage
surfaceras.to.ras(
header_cras,
sras_coords,
first_voxel_RAS = c(1, 1, 1),
invert_transform = FALSE
)
Arguments
header_cras |
an MGH header instance from which to extract the cras (center RAS), or the cras vector, i.e., a numerical vector of length 3 |
sras_coords |
nx3 numerical vector, the input surface RAS coordinates. Could be the vertex coordinates of an 'fs.surface' instance, or the RAS coords from a surface label. Use the orig surfaces. |
first_voxel_RAS |
the RAS of the first voxel, see |
invert_transform |
logical, whether to invert the transform. Do not use this, call |
Value
the RAS coords for the input sras_coords
Note
The RAS can be computed from Surface RAS by adding the center RAS coordinates, i.e., it is nothing but a translation.
Compute Talairach RAS for surface RAS (e.g., vertex coordinates).
Description
Compute Talairach RAS for surface RAS (e.g., vertex coordinates).
Usage
surfaceras.to.talairach(
sras_coords,
talairach,
header_cras,
first_voxel_RAS = c(1, 1, 1)
)
Arguments
sras_coords |
nx3 numerical vector, the input surface RAS coordinates. Could be the vertex coordinates of an 'fs.surface' instance, or the RAS coords from a surface label. Use the orig surfaces. |
talairach |
the 4x4 numerical talairach matrix, or a character string which will be interpreted as the path to an xfm file containing the matrix (typically |
header_cras |
an MGH header instance from which to extract the cras (center RAS), or the cras vector, i.e., a numerical vector of length 3 |
first_voxel_RAS |
the RAS of the first voxel, see |
Value
The Talairach RAS coordinates for the vertices of the orig surfaces (or coords in surface RAS space). Based on linear transform.
Compute MNI talairach coordinates from RAS coords.
Description
Compute MNI talairach coordinates from RAS coords.
Usage
talairachras.to.ras(tal_ras_coords, talairach)
Arguments
tal_ras_coords |
coordinate matrix in Talairach RAS space |
talairach |
the 4x4 numerical talairach matrix, or a character string which will be interpreted as the path to an xfm file containing the matrix (typically |
Value
the Talairach RAS coordinates for the given RAS coordinates. They are based on a linear transform.
Note
You can use this to compute the Talairach coordinate of a voxel, based on its RAS coordinate.
References
see https://en.wikipedia.org/wiki/Talairach_coordinates
Check whether a text line holds a fixed number of numerical values.
Description
Check whether a text line holds a fixed number of numerical values.
Usage
## S3 method for class 'line.is.numeric'
text(line, num)
Arguments
line |
character string, the line to check. |
num |
integer, the number of numerical values expected in the line. |
Value
logical, whether the line contains exactly num numerical values and nothing else.
Compute the affine that maps TrackVis coordinates to RAS+ mm.
Description
Computes the affine that turns the streamlines stored in a TRK
file into RAS+ mm coordinates in which a coordinate of (0,0,0) is the center
of the first voxel, which is the convention used by 'nibabel', DIPY and the
TRX format. The stored streamlines refer to the voxel corners and are in
"voxelmm" space, so this combines the stored matrix with the voxel sizes,
the half-voxel offset, and the orientation stored in the voxel_order
header field.
Usage
trackvis.affine.to.rasmm(header)
Arguments
header |
named list, the header of a TRK file as returned by
|
Value
a 4x4 numeric matrix.
Note
The TrackVis specification assumes that the stored streamlines are in
mm and that the stored matrix maps them to RAS, which means the matrix has
to be corrected whenever the voxels are not 1 mm^3. DSI Studio writes files
that do not need the half-voxel shift, which is what the shift_origin
parameter of read.dti.trk controls.
Transform a bounding box with an affine.
Description
Returns the axis-aligned bounding box of the transformed box. For a linear transformation the extremes of the image of a box are attained at its corners, so transforming the 8 corners gives the exact bounding box of the transformed data.
Usage
## S3 method for class 'bbox'
transform(bbox, affine)
Arguments
bbox |
numeric vector of length 6,
|
affine |
4x4 numeric matrix. |
Value
numeric vector of length 6.
Get the file path recorded in a volume descriptor.
Description
Get the file path recorded in a volume descriptor.
Usage
## S3 method for class 'descriptor.path'
transform(descriptor)
Arguments
descriptor |
|
Value
NULL or character string.
Extract the text of a file for format sniffing.
Description
Read the beginning of a file and return the printable characters it contains, so that the file can be identified by markers in its content without failing on binary data.
Usage
## S3 method for class 'file.sniff.text'
transform(filepath, num_bytes = 256L)
Arguments
filepath |
character string, the path to the file. |
num_bytes |
integer, the number of bytes to inspect. |
Value
character string, the printable characters of the beginning of the file.
Convert a transformation between the LPS and the RAS convention.
Description
Changing the convention of the coordinates that a transformation maps flips the sign of its first two axes on each side of the transformation that changes: the input side by multiplying the matrix from the right and the output side by multiplying it from the left, with a diagonal matrix that negates x and y. That matrix is its own inverse, which is why the conversion in both directions is the same operation.
Usage
## S3 method for class 'flip.handedness'
transform(tf, target)
Arguments
tf |
an |
target |
character string, either 'ras' or 'lps'. |
Value
an fs.transform instance whose matrix is expressed in the requested convention.
Determine the volume geometry of one side of a transformation.
Description
Use the geometry recorded in the transformation itself if it is available, and the volume passed by the caller otherwise.
Usage
## S3 method for class 'geometry.for.side'
transform(tf, side, volume = NULL)
Arguments
tf |
an |
side |
character string, either 'src' or 'dst'. |
volume |
|
Value
NULL or a geometry list as returned by volume.geometry.
Format the rows of a transformation matrix for a text file.
Description
The transformation file formats store the matrix as text, and the values are written with enough significant digits so that reading the file back gives the exact same double values. Fewer digits are not enough: 15 digits, as used by some other tools, lose up to a few units in the last place of a double.
Usage
## S3 method for class 'matrix.row.lines'
transform(matrix)
Arguments
matrix |
numerical matrix, the matrix to format. |
Value
character vector with one entry per row of the matrix.
Format a single numerical value for a transformation text file.
Description
17 significant decimal digits identify a double uniquely, so writing that many of them and
reading them back preserves the value exactly – but only if the decimal conversion of the C library rounds
correctly, and that is not true on every platform: on macOS (ARM64) the round trip of a value like
-1e-7 / 7 loses one unit in the last place, because the value that is written is one digit off. The round
trip is therefore verified here with R's own decimal conversion, and the number of digits is increased
until the value survives it. The output therefore has no more digits than the platform can handle
correctly, and it is guaranteed to be read back exactly by the same platform.
Usage
## S3 method for class 'value.text'
transform(value)
Arguments
value |
single numerical value, the value to format. |
Value
character string, the text representation of the value.
Format numerical values for a transformation text file.
Description
Format numerical values for a transformation text file.
Usage
## S3 method for class 'values.text'
transform(values)
Arguments
values |
numerical vector, the values to format. |
Value
character string, the values separated by single spaces.
Determine the frame of the world space of a transformation.
Description
The world space that a transformation between voxel coordinates refers to depends on the format
it was read from: an FSL matrix uses the FSL convention, see fsl.scaled.voxel.matrix, while the
matrices of the other formats use the RAS space of the volume headers. The frame is taken from the volume
descriptors if they state it and is derived from the format otherwise, so that
transform2world and transform2voxel always agree.
Usage
## S3 method for class 'world.frame'
transform(tf)
Arguments
tf |
an |
Value
character string, either 'fsl' or 'scanner'.
Convert a transformation to LPS world coordinates.
Description
The reverse of transform2ras, for transformations that have to be expressed in
the world coordinates that ITK and the tools built on it use. A transformation that is already in LPS
coordinates is returned unchanged.
Usage
transform2lps(tf)
Arguments
tf |
an |
Value
an fs.transform instance whose matrix operates on LPS coordinates.
See Also
Other header coordinate space:
invert.fs.transform(),
is.fs.transform(),
mghheader.is.ras.valid(),
mghheader.ras2vox(),
mghheader.ras2vox.tkreg(),
mghheader.scanner2tkreg(),
mghheader.tkreg2scanner(),
mghheader.vox2ras(),
mghheader.vox2ras.tkreg(),
print.fs.transform(),
read.fs.transform(),
read.fs.transform.dat(),
read.fs.transform.fslmat(),
read.fs.transform.itk(),
read.fs.transform.lta(),
read.fs.transform.xfm(),
sm0to1(),
sm1to0(),
summary.fs.transform(),
transform2ras(),
transform2voxel(),
transform2world(),
write.fs.transform(),
write.fs.transform.dat(),
write.fs.transform.fslmat(),
write.fs.transform.itk(),
write.fs.transform.lta(),
write.fs.transform.xfm()
Examples
tf <- read.fs.transform(system.file("extdata", "talairach.xfm",
package = "freesurferformats", mustWork = TRUE
))
# The matrix changes, because the sign of the first two axes changes.
max(abs(transform2lps(tf)$matrix - tf$matrix)) > 0
Convert a transformation to RAS world coordinates.
Description
ITK and the tools built on it (3D Slicer, ANTs, SimpleITK and the workflows that use them) work
in world coordinates that are left-posterior-superior (LPS), while the other file formats of this package use
right-anterior-superior (RAS) coordinates. The two conventions differ in the sign of the first two axes only,
so converting a transformation between them neither needs nor uses the geometry of a volume, unlike the
conversion between voxel and world coordinates, see transform2world. A transformation that
is already in RAS coordinates is returned unchanged.
Usage
transform2ras(tf)
Arguments
tf |
an |
Value
an fs.transform instance whose matrix operates on RAS coordinates.
See Also
Other header coordinate space:
invert.fs.transform(),
is.fs.transform(),
mghheader.is.ras.valid(),
mghheader.ras2vox(),
mghheader.ras2vox.tkreg(),
mghheader.scanner2tkreg(),
mghheader.tkreg2scanner(),
mghheader.vox2ras(),
mghheader.vox2ras.tkreg(),
print.fs.transform(),
read.fs.transform(),
read.fs.transform.dat(),
read.fs.transform.fslmat(),
read.fs.transform.itk(),
read.fs.transform.lta(),
read.fs.transform.xfm(),
sm0to1(),
sm1to0(),
summary.fs.transform(),
transform2lps(),
transform2voxel(),
transform2world(),
write.fs.transform(),
write.fs.transform.dat(),
write.fs.transform.fslmat(),
write.fs.transform.itk(),
write.fs.transform.lta(),
write.fs.transform.xfm()
Examples
# An ITK transform operates on LPS coordinates, the FreeSurfer formats on RAS coordinates.
tf <- read.fs.transform(system.file("extdata", "talairach.xfm",
package = "freesurferformats", mustWork = TRUE
))
summary(tf)$space_in
summary(transform2lps(tf))$space_in
summary(transform2ras(transform2lps(tf)))$space_in
Convert a transformation to voxel coordinates.
Description
The inverse operation of transform2world: given a transformation that operates
on world coordinates, compute the matrix that maps voxel indices of one volume to voxel indices of another.
The result can be saved as an FSL matrix, see write.fs.transform.fslmat.
Usage
transform2voxel(tf, src = NULL, dst = NULL)
Arguments
tf |
an |
src |
|
dst |
|
Value
an fs.transform instance whose matrix operates on (zero-based) voxel coordinates.
See Also
Other header coordinate space:
invert.fs.transform(),
is.fs.transform(),
mghheader.is.ras.valid(),
mghheader.ras2vox(),
mghheader.ras2vox.tkreg(),
mghheader.scanner2tkreg(),
mghheader.tkreg2scanner(),
mghheader.vox2ras(),
mghheader.vox2ras.tkreg(),
print.fs.transform(),
read.fs.transform(),
read.fs.transform.dat(),
read.fs.transform.fslmat(),
read.fs.transform.itk(),
read.fs.transform.lta(),
read.fs.transform.xfm(),
sm0to1(),
sm1to0(),
summary.fs.transform(),
transform2lps(),
transform2ras(),
transform2world(),
write.fs.transform(),
write.fs.transform.dat(),
write.fs.transform.fslmat(),
write.fs.transform.itk(),
write.fs.transform.lta(),
write.fs.transform.xfm()
Examples
lta_file <- system.file("extdata", "talairach.lta", package = "freesurferformats", mustWork = TRUE)
tf_world <- transform2world(read.fs.transform(lta_file))
tf_voxel <- transform2voxel(tf_world)
max(abs(tf_voxel$matrix - read.fs.transform(lta_file)$matrix)) # back where we started
Convert a transformation to the world (RAS) coordinate space.
Description
Transformation files often store their matrix in voxel coordinates, which means that the matrix alone cannot be used to transform world coordinates (e.g. the coordinates of a brain surface vertex, or a peak coordinate from another study): the geometry of the volumes the matrix relates is required as well. This function converts such a transformation into one that operates on world coordinates.
The result depends on the format the transformation was read from, because the formats disagree about their world space, which is why this is not a pure matrix operation:
For an FSL matrix ('fslmat'), the world space is the one FSL uses: unit voxel axes with a flipped first axis, see
fsl.scaled.voxel.matrix. Both MRtrix3 and FreeSurfer implement exactly this, and the result is a transformation between FSL world coordinates. Thesrcanddstentries of the result have the frame 'fsl'.For an LTA of type 0 (VOX2VOX), the world space is the RAS space of the two volume geometries: the result is
vox2ras_dst \%*\% matrix \%*\% solve(vox2ras_src). The descriptors have the frame 'scanner'.
Usage
transform2world(tf, src = NULL, dst = NULL)
Arguments
tf |
an |
src |
|
dst |
|
Value
an fs.transform instance whose matrix operates on world coordinates.
See Also
Other header coordinate space:
invert.fs.transform(),
is.fs.transform(),
mghheader.is.ras.valid(),
mghheader.ras2vox(),
mghheader.ras2vox.tkreg(),
mghheader.scanner2tkreg(),
mghheader.tkreg2scanner(),
mghheader.vox2ras(),
mghheader.vox2ras.tkreg(),
print.fs.transform(),
read.fs.transform(),
read.fs.transform.dat(),
read.fs.transform.fslmat(),
read.fs.transform.itk(),
read.fs.transform.lta(),
read.fs.transform.xfm(),
sm0to1(),
sm1to0(),
summary.fs.transform(),
transform2lps(),
transform2ras(),
transform2voxel(),
write.fs.transform(),
write.fs.transform.dat(),
write.fs.transform.fslmat(),
write.fs.transform.itk(),
write.fs.transform.lta(),
write.fs.transform.xfm()
Examples
# Read an LTA file, which records both volumes it relates, and convert it to world coordinates.
lta_file <- system.file("extdata", "talairach.lta", package = "freesurferformats", mustWork = TRUE)
tf <- read.fs.transform(lta_file)
tf_world <- transform2world(tf)
tf_world$space_in
tf_world$matrix
Translate between code and name of MRI data types.
Description
Translate between code and name of MRI data types.
Usage
translate.mri.dtype(dtype)
Arguments
dtype |
character string (one of c('MRI_FLOAT') or integer, one of c(0L, 1L, 3L, 4L). Numeric values will be converted to integer. |
Value
if dtype is a character string, the respective integer code. If it is numeric, the respective character string.
Create an iterator over the tracts of a TRK file.
Description
Create an iterator over the tracts of a TRK file.
Usage
trk.track.iterator(filepath, skip_tracks = 0L, bbox = NULL)
Arguments
filepath |
character string, path to the file. |
skip_tracks |
integer, the number of tracts to skip. |
bbox |
numeric vector of length 6 or NULL, a bounding box, see
|
Value
the iterator environment.
Validate a bounding box argument.
Description
Validate a bounding box argument.
Usage
validate.bbox(bbox)
Arguments
bbox |
numeric vector of length 6 or NULL. |
Value
TRUE, invisibly. Stops if the box is invalid.
Validate and normalize a diffusion MRI gradient table.
Description
Checks that a set of b-vectors and b-values is consistent,
replaces missing values by b=0 volumes, and reports suspicious entries.
This is the validation used by
read.dti.gradients, but it can also be
called directly on gradients from any other source.
Usage
validate.dti.gradients(bvec, bval, n_volumes = NULL)
Arguments
bvec |
character string (path to a b-vectors file), or a numeric matrix with one row per volume (or one column per volume) and 3 columns. |
bval |
character string (path to a b-values file), or a numeric vector
with one value per volume. Can be |
n_volumes |
scalar numeric or integer, the number of volumes in the DWI
image that the gradients belong to, used to check that the table matches
the image. Typically |
Value
a named list with the entries bvec (numeric matrix with n rows
and 3 columns, one row per volume) and bval (numeric vector of length
n).
Note
The rules for missing values match those of MRtrix3: a missing b-value
in a volume with a valid direction, or a missing direction in a volume with
a non-zero b-value, is an error, because such a volume cannot be
interpreted. Everything else is treated as a b=0 volume. The norm of the
gradient vectors is never changed, and a b-value is never rescaled, because
that would silently alter the data.
Check whether an object is a valid fs.transform instance.
Description
This checks the invariants that every fs.transform must fulfill: it is a named list with a
finite 4x4 numerical matrix, a known or unknown coordinate space for both sides, a voxel base that matches
those spaces, and volume descriptors that only contain supported entries. It is called automatically by the
constructor, so that readers, writers and user code can rely on the fields.
Usage
validate.fs.transform(tf)
Arguments
tf |
the object to check. |
Value
TRUE if tf is a valid fs.transform instance, and the function stops with an explanatory error
message otherwise.
Validate that a requested allocation does not exceed the safety limit.
Description
Given dimension sizes and bytes per element, checks that the total allocation size is safe. Catches negative/NA/Inf dimensions, integer overflow (by converting to double), and enforces the max allocation limit.
Note that bytes_per_elem must be the size of an element in memory,
which is not necessarily the size on disk: readBin() into a
numeric() vector allocates 8 bytes per element even when the values
are stored as 4 byte floats.
Usage
validate_allocation_size(
dims,
bytes_per_elem,
max_bytes = get_max_alloc_bytes(),
label = NULL
)
Arguments
dims |
numeric vector of dimension sizes (e.g., |
bytes_per_elem |
single numeric value, the number of bytes per element
as stored in memory (e.g., |
max_bytes |
single numeric value, the maximum allowed allocation in bytes.
Defaults to the result of |
label |
character string or NULL, a human-readable description of what is being allocated. Included in the error message to help the user understand which part of a file the limit was hit on. |
Value
the total number of elements (as double), invisibly. The function stops with an error if the allocation would be unsafe.
Compute Euclidean distance between two vertices v1 and v2.
Description
Compute Euclidean distance between two vertices v1 and v2.
Usage
vertex.euclid.dist(surface, v1, v2)
Arguments
surface |
an fs.surface instance |
v1 |
positive integer, vertex index of v1 |
v2 |
positive integer, vertex index of v2 |
Value
double, the Euclidean distance between v1 and v2
See Also
Other Euclidean distance util functions:
closest.vert.to.point(),
vertexdists.to.point()
Compute Euclidean distance from all mesh vertices to given point.
Description
Compute Euclidean distance from all mesh vertices to given point.
Usage
vertexdists.to.point(surface, point_coords)
Arguments
surface |
an fs.surface instance |
point_coords |
double vector of length 3, the xyz coords of a single point. |
Value
double vector of distances
See Also
Other Euclidean distance util functions:
closest.vert.to.point(),
vertex.euclid.dist()
Describe a volume for an fs.transform.
Description
Transformation files often record the geometry of the volumes they relate, either completely (an
LTA file stores the voxel dimensions, the voxel sizes and the voxel-to-RAS direction vectors of both volumes)
or not at all. This helper turns that information into the src and dst descriptors of an fs.transform.
The frame entry states which RAS coordinates the vox2ras matrix produces: 'scanner' means that the matrix
is used as given (this is what an LTA file records), and 'tkreg' means FreeSurfer tkregister coordinates,
which are RAS coordinates with an identity rotation and the origin at the center of the volume. A descriptor
may be partial, e.g. when only the target is known to be in tkregister space.
Usage
volume.descriptor(
path = NULL,
dim = NULL,
voxelsize = NULL,
xras = NULL,
yras = NULL,
zras = NULL,
cras = NULL,
vox2ras = NULL,
frame = "scanner",
valid = NULL
)
Arguments
path |
|
dim |
|
voxelsize |
|
xras |
|
yras |
|
zras |
|
cras |
|
vox2ras |
|
frame |
character string, either 'scanner', 'tkreg' or 'fsl', see the description. |
valid |
|
Value
NULL if no information was given, a named list describing the volume otherwise.
Get the geometry of a volume.
Description
Transformation matrices of the voxel-to-voxel kind can only be interpreted relative to the volumes they relate, so the conversion functions need the geometry of those volumes: their dimensions, voxel sizes and the matrix that maps voxel indices to RAS coordinates.
The voxel indices are zero-based and the origin of the RAS space is the one used by FreeSurfer for MGH
headers and by NIfTI for the sform, i.e. this is the same convention as mghheader.vox2ras.
Usage
volume.geometry(volume)
Arguments
volume |
an |
Value
named list with the entries 'vox2ras' (4x4 numerical matrix), 'dim' (integer vector of length 3) and 'voxelsize' (numerical vector of length 3).
Convert values that are used as indices to integers.
Description
Convert values that are used as indices to integers.
Usage
vtk.as.indices(values, filepath)
Arguments
values |
numeric vector, the values to convert. |
filepath |
character string, the file the values were read from. |
Value
integer vector.
Determine how the cell array of a section is stored.
Description
The cell arrays of VTK legacy files come in two layouts, see the comment at the top of this file. Both layouts are still written by software in use today, and the version number in the header does not reliably indicate which one a file uses, so the layout is detected from the presence of the OFFSETS keyword: the old layout starts the cell data with the vertex count of the first cell as a raw number, whereas the new layout starts it with the string 'OFFSETS'. For ASCII files that is simply the next line; for binary files the first byte decides, and because a cell vertex count is a small integer, the first byte of an old style cell array is always zero.
Usage
vtk.cell.section.layout(reader)
Arguments
reader |
an environment as returned by |
Value
named list with the entry 'layout' ('old' or 'new') and, for the new layout, the entry 'type' (character, the name of the offsets data type).
Check that all cells of the requested type are triangles.
Description
Check that all cells of the requested type are triangles.
Usage
vtk.check.triangles(cells, filepath)
Arguments
cells |
list of integer vectors, as returned by |
filepath |
character string, the file the cells were read from. |
Value
NULL, invisibly. Stops if a cell is not a triangle.
Get the on-disk properties of a VTK legacy data type.
Description
Every data section of a VTK legacy file names the type of its
values explicitly (e.g. POINTS 8 float). This function translates
such a type name into the number of bytes a single value occupies on disk,
the R storage mode to read it into, and whether the values are integers.
Usage
vtk.data.type.info(type_name, filepath = "")
Arguments
type_name |
character string, the type name as it occurs in the file, e.g. 'float', 'double' or 'vtktypeint64'. |
filepath |
character string, the file the type name was found in. Only used to make error messages more helpful. |
Value
named list with the entries 'size' (integer, bytes per value on disk),
'mode' (character, the storage mode for readBin) and
'integer' (logical, whether the values are integers).
Read the next line of an ASCII VTK legacy file.
Description
Read the next line of an ASCII VTK legacy file.
Usage
vtk.next.line(reader)
Arguments
reader |
an environment as returned by |
Value
character string, or NULL at the end of the file.
Read the next section header line of a VTK legacy file.
Description
Read the next section header line of a VTK legacy file.
Usage
vtk.next.section(reader)
Arguments
reader |
an environment as returned by |
Value
named list with the entries 'keyword' (character, e.g. 'POLYGONS') and
'args' (character vector, the remaining tokens of the line), or NULL
at the end of the file.
Read the cell array of a VTK legacy section.
Description
Read the cell array of a VTK legacy section.
Usage
vtk.parse.cell.section(reader, section)
Arguments
reader |
an environment as returned by |
section |
named list, a section as returned by |
Value
list of integer vectors, one per cell, containing the 0-based vertex indices of the cell.
Read a non-negative integer from a VTK section header.
Description
Read a non-negative integer from a VTK section header.
Usage
vtk.parse.count(value, filepath, what)
Arguments
value |
character string, the token to parse. |
filepath |
character string, the file being read, for error messages. |
what |
character string, a description of the value, for error messages. |
Value
single integer.
Look at the next line of an ASCII VTK legacy file.
Description
Look at the next line of an ASCII VTK legacy file.
Usage
vtk.peek.line(reader)
Arguments
reader |
an environment as returned by |
Value
character string, or NULL at the end of the file. The line is
not consumed, the next call to vtk.next.line returns it.
Read the header of a VTK legacy file and set up the reader.
Description
Read the header of a VTK legacy file and set up the reader.
Usage
vtk.read.header(reader)
Arguments
reader |
an environment as returned by |
Value
named list with the entries 'version' (character), 'encoding' ('ASCII' or 'BINARY') and 'dataset' (character, the dataset type).
Consume bytes from a VTK legacy reader.
Description
Consume bytes from a VTK legacy reader.
Usage
vtk.reader.bytes(reader, num_bytes)
Arguments
reader |
an environment as returned by |
num_bytes |
single non-negative integer, the number of bytes to consume. |
Value
raw vector of length num_bytes.
Close the connection of a VTK legacy reader.
Description
Close the connection of a VTK legacy reader.
Usage
vtk.reader.close(reader)
Arguments
reader |
an environment as returned by |
Value
NULL, invisibly.
Fill the lookahead buffer of a VTK legacy reader.
Description
Fill the lookahead buffer of a VTK legacy reader.
Usage
vtk.reader.fill(reader, num_bytes)
Arguments
reader |
an environment as returned by |
num_bytes |
single non-negative integer, the number of bytes the buffer should hold. |
Value
NULL, invisibly. The buffer may hold fewer bytes than requested
if the file ends.
Create the low-level state used while reading a VTK legacy file.
Description
Opens a connection to the file (transparently handling gzip
compression) and initializes the lookahead buffer. The returned environment
is passed to the other vtk.* functions, which mutate its state while
they consume the file.
Usage
vtk.reader.new(filepath)
Arguments
filepath |
character string, path to the VTK file. |
Value
an environment with the class 'vtk.reader'.
Read numeric values from a binary VTK legacy file.
Description
Read numeric values from a binary VTK legacy file.
Usage
vtk.reader.numbers(reader, num_values, type_info)
Arguments
reader |
an environment as returned by |
num_values |
single non-negative integer, the number of values to read. |
type_info |
named list, the result of |
Value
numeric or integer vector of length num_values.
Note
Legacy VTK binary data is always big endian, the format has no way of expressing a different byte order.
Read bytes from a VTK legacy reader without consuming them.
Description
Read bytes from a VTK legacy reader without consuming them.
Usage
vtk.reader.peek(reader, num_bytes)
Arguments
reader |
an environment as returned by |
num_bytes |
single non-negative integer, the number of bytes to peek at. |
Value
raw vector, possibly shorter than num_bytes at the end of the file.
Read numeric values from a VTK legacy section.
Description
Read numeric values from a VTK legacy section.
Usage
vtk.section.values(reader, num_values, type_info)
Arguments
reader |
an environment as returned by |
num_values |
single non-negative integer, the number of values to read. |
type_info |
named list, the result of |
Value
numeric or integer vector of length num_values.
Read numeric values from an ASCII VTK legacy section.
Description
The ASCII encoding does not guarantee how many values share a line, so values are collected line by line until the expected number of them has been read. A line that contains more values than the section declares is treated as an error, because it means that the section header lied about the size of the section and the file cannot be parsed reliably.
Usage
vtk.section.values.ascii(reader, num_values)
Arguments
reader |
an environment as returned by |
num_values |
single non-negative integer, the number of values to read. |
Value
numeric vector of length num_values.
Split a line of a VTK legacy file into whitespace separated tokens.
Description
Split a line of a VTK legacy file into whitespace separated tokens.
Usage
vtk.split.line(line)
Arguments
line |
character string, the line to split. |
Value
character vector, the tokens of the line.
Write the sections of a triangular mesh in VTK ASCII format.
Description
Write the sections of a triangular mesh in VTK ASCII format.
Usage
vtk.write.surface.ascii(con, vertex_coords, faces, version)
Arguments
con |
a connection opened for writing. |
vertex_coords |
n x 3 matrix of doubles, the vertex coordinates. |
faces |
n x 3 matrix of integers, the vertex indices of the faces, already converted to zero-based indices. |
version |
character string, either '4.2' or '5.1'. |
Value
NULL, invisibly.
Write the sections of a triangular mesh in binary VTK format.
Description
Write the sections of a triangular mesh in binary VTK format.
Usage
vtk.write.surface.binary(con, vertex_coords, faces, version)
Arguments
con |
a connection opened for binary writing. |
vertex_coords |
n x 3 matrix of doubles, the vertex coordinates. |
faces |
n x 3 matrix of integers, the vertex indices of the faces, already converted to zero-based indices. |
version |
character string, either '4.2' or '5.1'. |
Value
NULL, invisibly.
Note
Binary data in the VTK legacy format is always big endian, the format has no way of expressing a different byte order.
Write data to a file in ANALYZE 7.5 format.
Description
Write an array or vector to the two files that make up an ANALYZE 7.5 image: a 348 byte header
(<base>.hdr) and the raw voxel data in a separate file (<base>.img).
Usage
write.analyze(filepath, analyzedata, analyzeheader = NULL, ...)
Arguments
filepath |
character string, the path of the output files. It must end with |
analyzedata |
array of numeric (integer or double) data, can have up to 7 dimensions. See
|
analyzeheader |
optional ANALYZE 7.5 header that is suitable for the passed |
... |
additional parameters passed to |
Value
invisible named list with the entries header (the header that was written) and data (the data that
was written). Use these to check what the function did with your input, they reflect the values that ended up in
the file, e.g. values that had to be converted to the data type stated in the header.
Note
ANALYZE 7.5 cannot store a transformation matrix, and the format does not even define the direction of the
voxel axes in world space. This writer therefore cannot write the geometry of an image: if you have a volume
with a known vox2ras_matrix and you want to keep it, write a NIFTI v1 file with
write.nifti1 instead (either a single file, or a .hdr/.img pair by setting the header magic
to 'ni1', which is what write.fs.volume does for such file names). If you know that the data
will be read by SPM or FreeSurfer, you can store the image origin in the spm_origin field of the header, see
read.analyze.header.
Note that tools differ in how they recognize the format. FreeSurfer's mri_convert, for example, does not
infer the ANALYZE format from the .hdr file extension and reports 'cannot determine file type' unless the
input type is given explicitly: mri_convert -it analyze -ot mgz vol.hdr vol.mgz works, mri_convert -ot mgz vol.hdr vol.mgz does not. The header written by this function is the one FreeSurfer itself writes for
-ot analyze, so this is a limitation of the reader, not of the file.
See Also
read.analyze.header, analyzeheader.for.data
Examples
outfiles <- tempfile()
data <- array(1:24, dim = c(4, 3, 2))
analyzeheader <- analyzeheader.for.data(data)
analyzeheader$pix_dim <- c(1., 1.5, 1.5, 2., 0., 0., 0., 0.)
write.analyze(outfiles, data, analyzeheader)
vol <- read.fs.volume.analyze(outfiles, with_header = TRUE)
vol$header$pix_dim
Write a fixed length character field of an ANALYZE 7.5 header.
Description
Write a fixed length character field of an ANALYZE 7.5 header.
Usage
write.analyze.char.field(fh, field_value, field_length, return_bytes = FALSE)
Arguments
fh |
connection to write to. |
field_value |
character string, the value to write. |
field_length |
integer, the length of the field in bytes. |
return_bytes |
logical, whether to return the raw bytes instead of writing them to the connection. |
Value
invisible NULL (or the raw vector of length field_length if return_bytes is TRUE), called for
the side effect of writing to the connection.
Note
The string is converted to bytes as ISO-8859-1 (latin-1), which is the inverse of the conversion that
analyze.read.char.field applies when reading, so that the content of the field survives a read
and write cycle byte for byte. Characters that latin-1 cannot represent are written as UTF-8 instead.
Write the 348 byte ANALYZE 7.5 header to a connection.
Description
Write the 348 byte ANALYZE 7.5 header to a connection.
Usage
write.analyze.header.internal(fh, analyzeheader)
Arguments
fh |
connection to write to. |
analyzeheader |
named list, a valid ANALYZE 7.5 header. |
Value
invisible NULL, called for the side effect of writing to the connection.
Write a brain atlas to a colortable (LUT) file and a per-vertex label file.
Description
Write a brain atlas (surface annotation) to two text files: a FreeSurfer ASCII colortable lookup table (LUT) file and a per-vertex label file. This is the inverse of atlas.from.lut.and.csv, and is useful for exporting an annotation in the simple text format used e.g. by the Python package 'yabplot' (files like 'aparc_LUT.txt' and 'aparc_conte69.csv'). If the annotation was created by atlas.from.lut.and.csv, the original per-vertex label indices are stored in its metadata and are used for the export, which makes it lossless. Otherwise, the indices are recovered by matching the per-vertex color codes against the colortable, which is ambiguous if several regions share a color code (e.g., the left/right pairs of the Desikan-Killiany 'aparc' atlas).
Usage
write.atlas.to.lut.and.csv(fs.annot, lut_file, csv_file, unknown_index = 0L)
Arguments
fs.annot |
an annotation, as returned by |
lut_file |
string, path to the output colortable file. Will be written in FreeSurfer ASCII LUT format, see |
csv_file |
string, path to the output per-vertex label file. Will contain one integer per line: the struct index (label ID) of the region for that vertex, as defined in the first column of the LUT file. Unlabeled vertices (e.g., the medial wall) are encoded with the struct index given in parameter |
unknown_index |
integer, the struct index to use for unlabeled vertices (i.e., vertices whose label code has no entry in the colortable). Defaults to 0. |
Value
named list with the following entries: 'lut_file' and 'csv_file' (the paths to the files that were written), 'num_vertices' (integer, the number of vertices in the per-vertex label file) and 'num_regions' (integer, the number of regions in the LUT file).
See Also
Other atlas functions:
atlas.from.lut.and.csv(),
colortable.from.annot(),
read.fs.annot(),
read.fs.colortable(),
write.fs.annot(),
write.fs.annot.gii(),
write.fs.colortable()
Examples
## Not run:
annot <- read.fs.annot("lh.aparc.annot")
write.atlas.to.lut.and.csv(annot, "myatlas_LUT.txt", "myatlas_vertices.csv")
# read it back into an annotation:
annot2 <- atlas.from.lut.and.csv("myatlas_LUT.txt", "myatlas_vertices.csv")
## End(Not run)
Write a CIFTI-2 file.
Description
Write a data matrix and its axes to a CIFTI-2 file, i.e. a NIFTI-2 file
with the CIFTI-2 XML in a header extension. The axes describe what the matrix
dimensions contain; they can be given explicitly (see the cifti.axis.*() functions),
taken from a template file (recommended for real data, see
cifti.axis.from.template), or both.
The file type (and thus the NIFTI intent code that identifies it) follows from the
axes: a scalars dimension and a brain model dimension make a .dscalar file, a series
dimension and a brain model dimension a .dtseries file, and so on. If the file name
has one of the standard CIFTI extensions, the axes have to match it: a file named
.pdconn.nii whose dimensions are not (brain models, parcels) is an error, not a
warning, because the file name is the only hint that other software has about the
content.
Usage
write.cifti(filepath, data, axes = NULL, template = NULL, metadata = NULL)
Arguments
filepath |
character string, the path of the file to write. |
data |
numeric or integer matrix or array, the data. The dimensions have to match
the sizes of the axes, and the order is the same as for |
axes |
list of axes, one per matrix dimension, or |
template |
character string (the path of a CIFTI-2 file), an |
metadata |
named character vector or named list, or |
Value
the axes that were written, invisibly. The file is written as a side effect.
Note
The data are written as 32 bit floating point values, which is what the reference implementations write for CIFTI-2 files (including for label files, whose keys are small integers). Values that need more than about 7 significant digits are rounded.
See Also
Other cifti functions:
cifti.axis.brain.models(),
cifti.axis.from.template(),
cifti.axis.labels(),
cifti.axis.parcels(),
cifti.axis.parcels.from.annot(),
cifti.axis.scalars(),
cifti.axis.series(),
cifti.brain.model.surface(),
cifti.brain.model.volume(),
cifti.dim.labels(),
cifti.file.type.for.axes(),
cifti.grayordinates(),
cifti.header.from.axes(),
cifti.label.table(),
cifti.parcel(),
cifti.parcels(),
cifti.series.info(),
cifti.structure.data(),
cifti.structures(),
cifti.volume(),
print.fs.cifti(),
print.fs.cifti.data(),
print.fs.connectome(),
read.cifti(),
read.cifti.header(),
read.cifti.rows(),
read.fs.connectome.cifti(),
write.fs.connectome.cifti(),
write.fs.morph.cifti(),
write.fs.parcellated.cifti(),
write.fs.parcellation.cifti(),
write.fs.series.cifti()
Examples
axis_brain <- cifti.axis.brain.models(list(
cifti.brain.model.surface("lh", 10L),
cifti.brain.model.surface("rh", 12L)))
data_matrix <- matrix(1:22, nrow = 1L)
out_file <- file.path(tempdir(), "tiny_written.dscalar.nii")
write.cifti(out_file, data_matrix, axes = list(cifti.axis.scalars("my data"), axis_brain))
## Not run:
# Write data with the mapping of an existing file (recommended for real data):
template <- "Conte69.MyelinAndCorrThickness.32k_fs_LR.dscalar.nii"
data_matrix <- read.cifti(template)$data
write.cifti("copy.dscalar.nii", data_matrix, template = template)
## End(Not run)
Write b-values to a FSL-style bvals file.
Description
Writes the diffusion weighting of each volume of a diffusion MRI dataset to a plain text file, which is the bvals part of the FSL bvecs/bvals format.
Usage
write.dti.bval(filepath, bval, layout = "components")
Arguments
filepath |
character string, path to the output file. The conventional
extension is |
bval |
numeric vector, the b-value of each volume, in s/mm^2. |
layout |
character string, one of 'components' or 'volumes'.
|
Value
NULL, invisibly. Called for the side effect of writing the file.
See Also
Other dti functions:
read.dti.bval(),
read.dti.bvec(),
read.dti.grad(),
read.dti.gradients(),
write.dti.bvec(),
write.dti.grad()
Write b-vectors to a FSL-style bvecs file.
Description
Writes the diffusion gradient directions of a diffusion MRI dataset to a plain text file, which is the bvecs part of the FSL bvecs/bvals format. Note that these vectors are interpreted relative to the image axes, so the file is only meaningful together with the image it was derived from.
Usage
write.dti.bvec(filepath, bvec, layout = "components")
Arguments
filepath |
character string, path to the output file. The conventional
extension is |
bvec |
numeric matrix with 3 columns (one row per volume) or 3 rows (one column per volume), the gradient direction of each volume. |
layout |
character string, one of 'components' or 'volumes'.
|
Value
NULL, invisibly. Called for the side effect of writing the file.
Note
A square 3x3 input is ambiguous. Since a matrix passed in memory
follows the R convention of one row per volume, the rows are written as the
volumes here; read.dti.bvec assumes the
components for a square file, so reading such a file back yields the
transposed matrix and warns about the ambiguity.
See Also
Other dti functions:
read.dti.bval(),
read.dti.bvec(),
read.dti.grad(),
read.dti.gradients(),
write.dti.bval(),
write.dti.grad()
Write a gradient table in MRtrix3 format.
Description
Writes a diffusion gradient table to a plain text file with one
line per DWI volume, each line holding the four space-separated values
[ x y z b ]. This is the format that the -grad option of the MRtrix3
commands expects, and the format of the dw_scheme entry in the header of
a .mif image.
Usage
write.dti.grad(filepath, bvec, bval = NULL, layout = "volumes")
Arguments
filepath |
character string, path to the output file. Files ending in
|
bvec |
numeric matrix with 3 columns (one row per volume) or 3 rows (one
column per volume), the gradient directions. Alternatively a full gradient
table, i.e. a numeric matrix with 4 columns named or ordered 'x', 'y', 'z'
and 'b', as returned by
|
bval |
numeric vector, the b-value of each volume, in s/mm^2. Ignored if
|
layout |
character string, one of 'volumes' or 'components'. |
Value
NULL, invisibly. Called for the side effect of writing the file.
See Also
Other dti functions:
read.dti.bval(),
read.dti.bvec(),
read.dti.grad(),
read.dti.gradients(),
write.dti.bval(),
write.dti.bvec()
Write tracks to a file in MRtrix TCK format.
Description
Writes streamlines in the TCK format described at
https://mrtrix.readthedocs.io/en/latest/getting_started/image_data.html.
The format stores a triplet of NaN values between streamlines and a triplet
of Inf values at the end. The output is read by MRtrix and by
read.dti.tck.
Usage
write.dti.tck(
tracts,
filepath,
datatype = "Float32LE",
gzip = NULL,
header = list()
)
Arguments
tracts |
the tracks to write, either an |
filepath |
character string, the path of the file to write. |
datatype |
character string, one of 'Float32LE' (the default, and what MRtrix writes), 'Float32BE', 'Float64LE' or 'Float64BE'. |
gzip |
logical or NULL, whether to gzip-compress the output. If
|
header |
named list of additional header entries to store in the file, e.g., the header of the file the tracks were read from. The entries 'id', 'datatype', 'count', 'file' and 'derived' are always computed by the readers and cannot be set. |
Value
the file path, invisibly.
Note
Tracts without any point cannot be represented in the TCK format: they
are written as a bare delimiter, which every reader (including this
package and 'nibabel') drops again, so the file reads back with fewer
tracts than it was written from. Writing such a file raises a warning.
write.dti.trk preserves empty tracts.
Examples
## Not run:
tck <- read.dti.tck("brain.tck", max_tracks = 1000);
write.dti.tck(tck$tracks, "first_1000.tck", header = tck$header);
# Round trip through a compressed file:
write.dti.tck(tck$tracks, "copy.tck.gz");
## End(Not run)
Write tracks to a file in TrackVis TRK format.
Description
Writes streamlines in the TRK format described at
http://trackvis.org/docs/?subsect=fileformat. The output is read by
TrackVis, by DSI Studio and by read.dti.trk.
Usage
write.dti.trk(
tracts,
filepath,
header = NULL,
coords_space = NULL,
endian = "little",
gzip = NULL
)
Arguments
tracts |
the tracks to write, either an |
filepath |
character string, the path of the file to write. |
header |
named list or NULL, the header of the file the tracks were read
from, whose metadata (voxel sizes, dimensions, the voxel-to-RAS matrix, the
voxel order, and the scalars and properties of the file) is reused. If
|
coords_space |
character string or NULL, the coordinate system the
tracks are in, either 'native' (the coordinates are written as they are) or
'ras' (the coordinates are RAS+ mm and are transformed back to the space
used in the file, which is what 'nibabel' does when saving). If |
endian |
character string, 'little' (the default) or 'big'. TrackVis writes little endian files, big endian support is for reading files written on old big endian systems. |
gzip |
logical or NULL, whether to gzip-compress the output. If
|
Value
the file path, invisibly.
Examples
## Not run:
trk <- read.dti.trk("brain.trk");
write.dti.trk(trk$tracks, "copy.trk", header = trk$header);
# Write RAS coordinates back to a file that uses voxelmm space:
trk_ras <- read.dti.trk("brain.trk", coords = "ras");
write.dti.trk(trk_ras$tracks, "copy.trk", header = trk_ras$header, coords_space = "ras");
## End(Not run)
Write per-point track values to a file in MRtrix TSF format.
Description
The TSF format stores one scalar value per point of a streamline, e.g., the fractional anisotropy, the distance along the track or a value sampled from an image at the point coordinates. It is the companion format of the TCK format: a TSF file contains no coordinates and no track boundaries, it is just a stream of values that has to be read together with the tractogram it describes. The number of values per track is therefore required to write the file, and a TSF file without the matching TCK file is meaningless to every reader (MRtrix checks this, see the note below).
Usage
write.dti.tsf(
tracts,
filepath,
lengths = NULL,
datatype = "Float32LE",
gzip = NULL,
header = list()
)
Arguments
tracts |
the values to write. This can be an |
filepath |
character string, the path of the file to write. |
lengths |
integer vector or NULL, the number of values per track. This
is ignored unless |
datatype |
character string, one of 'Float32LE' (the default, and what MRtrix writes), 'Float32BE', 'Float64LE' or 'Float64BE'. |
gzip |
logical or NULL, whether to gzip-compress the output. If
|
header |
named list of additional header entries to store in the file, e.g., the header of the file the tracks were read from. The entries 'id', 'datatype', 'count', 'file' and 'derived' are always computed by the readers and cannot be set. |
Value
the file path, invisibly.
Note
The TSF format stores a NaN value after every track, and unlike the TCK
format it has no Inf terminator: the reader relies on the delimiters to
split the value stream into tracks. A file whose values are not delimited
exactly like the tracks of the tractogram can therefore not be detected as
broken by this package, but MRtrix reports the mismatch of the track counts
when the file is used (e.g., in tcksample or tsfvalidate).
See Also
Examples
# A TSF file stores one value per point. Since the format contains no track
# boundaries, the track lengths have to be provided:
tsff <- tempfile(fileext = ".tsf");
values_by_track <- list(c(0.1, 0.2, 0.3), c(0.4, 0.5));
write.dti.tsf(values_by_track, tsff);
read.dti.tsf(tsff)$scalars$scalar_list;
# The same file can be written from one vector of values and the lengths:
write.dti.tsf(c(0.1, 0.2, 0.3, 0.4, 0.5), tsff, lengths = c(3L, 2L));
## Not run:
# Read the values of a track scalar file, modify them and write them back:
tsf <- read.dti.tsf("brain.tsf");
tsf$scalars$merged <- tsf$scalars$merged * 2;
write.dti.tsf(tsf$scalars, "brain_doubled.tsf");
# Sample an image along the tracks of a tractogram and store the result. The
# values of a TRK file that has one scalar are accepted as they are:
trk <- read.dti.trk("brain.trk");
write.dti.tsf(trk$tracks, "brain.trk.tsf");
## End(Not run)
Write annotation to binary file.
Description
Write an annotation to a FreeSurfer binary format annotation file in the new format (v2). An annotation (or brain parcellation) assigns each vertex to a label (or region). One of the regions is often called 'unknown' or similar and all vertices which are not relevant for the parcellation are assigned this label.
Usage
write.fs.annot(
filepath,
num_vertices = NULL,
colortable = NULL,
labels_as_colorcodes = NULL,
labels_as_indices_into_colortable = NULL,
fs.annot = NULL
)
Arguments
filepath |
string, path to the output file |
num_vertices |
integer, the number of vertices of the surface. Must be given unless parameter |
colortable |
dataframe that contains one region per row. Required columns are: 'struct_name': character string, the region name. 'r': integer in range 0-255, the RGB color value for the red channel. 'g': same for the green channel. 'b': same for the blue channel. 'a': the alpha (transparency) channel value. Optional columns are: 'code': the color code. Will be computed if not set. Note that you can pass the dataframe returned by |
labels_as_colorcodes |
vector of n integers. The first way to specify the labels. Each integer is a colorcode, that has been computed from the RGBA color values of the regions in the colortable as |
labels_as_indices_into_colortable |
vector of n integers, the second way to specify the labels. Each integer is an index into the rows of the colortable. Indices start with 1. This parameter and |
fs.annot |
instance of class |
See Also
Other atlas functions:
atlas.from.lut.and.csv(),
colortable.from.annot(),
read.fs.annot(),
read.fs.colortable(),
write.atlas.to.lut.and.csv(),
write.fs.annot.gii(),
write.fs.colortable()
Examples
## Not run:
# Load annotation
annot_file <- system.file("extdata", "lh.aparc.annot.gz",
package = "freesurferformats",
mustWork = TRUE
)
annot <- read.fs.annot(annot_file)
# New method: write the annotation instance:
write.fs.annot(tempfile(fileext = ".annot"), fs.annot = annot)
# Old method: write it from its parts:
write.fs.annot(tempfile(fileext = ".annot"), length(annot$vertices),
annot$colortable_df,
labels_as_colorcodes = annot$label_codes
)
## End(Not run)
Write annotation to GIFTI file.
Description
Write an annotation to a GIFTI XML file.
Usage
write.fs.annot.gii(filepath, annot)
Arguments
filepath |
string, path to the output file. |
annot |
fs.annot instance, an annotation. |
Note
This function does not write a GIFTI file that is valid according to the specification: it stores extra color data in the Label nodes, and there is more than one Label in the LabelTable node.
See Also
Other atlas functions:
atlas.from.lut.and.csv(),
colortable.from.annot(),
read.fs.annot(),
read.fs.colortable(),
write.atlas.to.lut.and.csv(),
write.fs.annot(),
write.fs.colortable()
Other gifti writers:
write.fs.label.gii(),
write.fs.morph.gii(),
write.fs.surface.gii()
Examples
## Not run:
# Load annotation
annot_file <- system.file("extdata", "lh.aparc.annot.gz",
package = "freesurferformats",
mustWork = TRUE
)
annot <- read.fs.annot(annot_file)
# New method: write the annotation instance:
write.fs.annot.gii(tempfile(fileext = ".annot"), annot)
## End(Not run)
Write colortable file in FreeSurfer ASCII LUT format.
Description
Write the colortable to a text file in FreeSurfer ASCII colortable lookup table (LUT) format. An example file is FREESURFER_HOME/FreeSurferColorLUT.txt.
Usage
write.fs.colortable(filepath, colortable)
Arguments
filepath |
string. Full path to the output colormap file. |
colortable |
data.frame, a colortable as read by |
Value
the written dataframe, invisible. Note that this is will contain a column named 'struct_index', no matter whether the input colortable contained it or not.
See Also
Other atlas functions:
atlas.from.lut.and.csv(),
colortable.from.annot(),
read.fs.annot(),
read.fs.colortable(),
write.atlas.to.lut.and.csv(),
write.fs.annot(),
write.fs.annot.gii()
Other colorLUT functions:
colortable.from.annot(),
read.fs.colortable()
Write a CIFTI-2 connectome file.
Description
Write a connectome matrix to a CIFTI-2 file: a dense connectome
(.dconn), a parcellated connectome (.pconn), or one of the mixed types (.pdconn,
.dpconn) whose two dimensions hold brainordinates and parcels. The file type follows
from the axes (and has to match the file name, see write.cifti), and the
mapping of the two dimensions has to be given: it cannot be derived from the matrix,
and guessing it (e.g. from the size of the matrix) would silently produce a file whose
rows and columns describe the wrong brain regions.
Use template for the normal case, i.e. to write a connectome of the brainordinates or
parcels of an existing file: this is how a .dconn of a subject gets the mapping of
that subject, and how a .pconn gets the parcels of the .ptseries it was computed
from. A template with a single brainordinate dimension (a .dscalar, .dtseries or
.dlabel, i.e. the files that actually exist for a subject) is accepted as well: its
mapping is then used for both dimensions of the connectome, which is what those files
describe. Use axes if the mapping has to be built, e.g. a parcels axis from
annotations (see cifti.axis.parcels.from.annot).
The complete matrix is written: a connectome file stores both halves of the matrix and
its diagonal, so the symmetry of the matrix is not exploited anywhere, and the matrix
of a .dconn can be huge (33 GB for the 91,282 grayordinates of an HCP subject, which
is more than any implementation can hold in memory). Writing such a file is not
supported yet; a connectome of a reduced set of brainordinates can be written.
Usage
write.fs.connectome.cifti(
filepath,
data,
template = NULL,
axes = NULL,
metadata = NULL
)
Arguments
filepath |
character string, the path of the file to write. The name should be one
of |
data |
numeric matrix, the connectome: the first matrix dimension (the rows) is
CIFTI matrix dimension 0, which the axes describe. An |
template |
character string (the path of a CIFTI-2 file), an |
axes |
list of two axes (see |
metadata |
named character vector or named list, or |
Value
the axes that were written, invisibly.
See Also
Other cifti functions:
cifti.axis.brain.models(),
cifti.axis.from.template(),
cifti.axis.labels(),
cifti.axis.parcels(),
cifti.axis.parcels.from.annot(),
cifti.axis.scalars(),
cifti.axis.series(),
cifti.brain.model.surface(),
cifti.brain.model.volume(),
cifti.dim.labels(),
cifti.file.type.for.axes(),
cifti.grayordinates(),
cifti.header.from.axes(),
cifti.label.table(),
cifti.parcel(),
cifti.parcels(),
cifti.series.info(),
cifti.structure.data(),
cifti.structures(),
cifti.volume(),
print.fs.cifti(),
print.fs.cifti.data(),
print.fs.connectome(),
read.cifti(),
read.cifti.header(),
read.cifti.rows(),
read.fs.connectome.cifti(),
write.cifti(),
write.fs.morph.cifti(),
write.fs.parcellated.cifti(),
write.fs.parcellation.cifti(),
write.fs.series.cifti()
Examples
pconn_file <- system.file("extdata", "cifti", "tiny.pconn.nii", package = "freesurferformats")
conn <- read.fs.connectome.cifti(pconn_file)
out_file <- file.path(tempdir(), "written.pconn.nii")
# The values are squared, the mapping is the one of the original file:
write.fs.connectome.cifti(out_file, conn$data^2, template = pconn_file)
read.fs.connectome.cifti(out_file)$data[1:2, 1:2]
## Not run:
# The grayordinates of a subject are the same in all its dense files, so a dtseries
# can define the mapping of the dconn:
write.fs.connectome.cifti("sub-01_dconn.nii", connectivity_matrix,
template = "sub-01_task-rest_dtseries.nii")
## End(Not run)
Write file in FreeSurfer curv format
Description
Write vertex-wise brain surface data to a file in FreeSurfer binary 'curv' format. For a subject (MRI image pre-processed with FreeSurfer) named 'bert', an example file would be 'bert/surf/lh.thickness', which contains n values. Each value represents the cortical thickness at the respective vertex in the brain surface mesh of bert.
Usage
write.fs.curv(filepath, data)
Arguments
filepath |
string. Full path to the output curv file. If it ends with ".gz", the file is written in gzipped format. Note that this is not common, and that other software may not handle this transparently. |
data |
vector of doubles. The brain morphometry data to write, one value per vertex. |
See Also
Other morphometry functions:
fs.get.morph.file.ext.for.format(),
fs.get.morph.file.format.from.filename(),
read.fs.curv(),
read.fs.mgh(),
read.fs.morph(),
read.fs.morph.gii(),
read.fs.volume(),
read.fs.weight(),
write.fs.label.gii(),
write.fs.mgh(),
write.fs.morph(),
write.fs.morph.asc(),
write.fs.morph.gii(),
write.fs.morph.ni1(),
write.fs.morph.ni2(),
write.fs.morph.smp(),
write.fs.morph.txt(),
write.fs.weight(),
write.fs.weight.asc()
Write vertex indices to file in FreeSurfer label format
Description
Write vertex coordinates and vertex indices defining faces to a file in FreeSurfer binary surface format. For a subject (MRI image pre-processed with FreeSurfer) named 'bert', an example file would be 'bert/label/lh.cortex'.
Usage
write.fs.label(
filepath,
vertex_indices,
vertex_coords = NULL,
vertex_data = NULL,
indices_are_one_based = TRUE
)
Arguments
filepath |
string. Full path to the output label file. If it ends with ".gz", the file is written in gzipped format. Note that this is not common, and that other software may not handle this transparently. |
vertex_indices |
instance of class |
vertex_coords |
an n x 3 float matrix of vertex coordinates, where n is the number of 'vertex_indices'. Optional, defaults to NULL, which will write placeholder data. The vertex coordinates are not used by any software I know (you should get them from the surface file). Will be used from |
vertex_data |
a numerical vector of length n, where n is the number of 'vertex_indices'. Optional, defaults to NULL, which will write placeholder data. The vertex data are not used by any software I know (you should get them from a morphometry file). Will be used from |
indices_are_one_based |
logical, whether the given indices are one-based, as is standard in R. Indices are stored zero-based in label files, so if this is TRUE, all indices will be incremented by one before writing them to the file. Defaults to TRUE. If FALSE, it is assumed that they are zero-based and they are written to the file as-is. Will be used from |
Value
dataframe, the dataframe that was written to the file (after the header lines).
See Also
Other label functions:
read.fs.label(),
read.fs.label.gii(),
read.fs.label.native()
Examples
## Not run:
# Write a simple label containing only vertex indices:
label_vertices <- c(1, 2, 3, 4, 5, 1000, 2000, 2323, 34, 34545, 42)
write.fs.label(tempfile(fileext = ".label"), label_vertices)
# Load a full label, write it back to a file:
labelfile <- system.file("extdata", "lh.entorhinal_exvivo.label",
package = "freesurferformats", mustWork = TRUE
)
label <- read.fs.label(labelfile, full = TRUE)
write.fs.label(tempfile(fileext = ".label"), label)
## End(Not run)
Write a binary surface label in GIFTI format.
Description
The data will be written with intent 'NIFTI_INTENT_LABEL' and as datatype 'NIFTI_TYPE_INT32'. The label table will include entries 'positive' (label value 0), and 'negative' (label value 1).
Usage
write.fs.label.gii(filepath, vertex_indices, num_vertices_in_surface)
Arguments
filepath |
string, the full path of the output GIFTI file. |
vertex_indices |
integer vector, the vertex indices which are part of the label (positive). All others not listed, up to num_vertices_in_surface, will be set to be negative. |
num_vertices_in_surface |
integer, the total number of vertices in the surface mesh. A GIFTI label is more like a mask/an annotation, so we need to know the number of vertices. |
Value
format, string. The format that was used to write the data: "gii".
See Also
Other morphometry functions:
fs.get.morph.file.ext.for.format(),
fs.get.morph.file.format.from.filename(),
read.fs.curv(),
read.fs.mgh(),
read.fs.morph(),
read.fs.morph.gii(),
read.fs.volume(),
read.fs.weight(),
write.fs.curv(),
write.fs.mgh(),
write.fs.morph(),
write.fs.morph.asc(),
write.fs.morph.gii(),
write.fs.morph.ni1(),
write.fs.morph.ni2(),
write.fs.morph.smp(),
write.fs.morph.txt(),
write.fs.weight(),
write.fs.weight.asc()
Other gifti writers:
write.fs.annot.gii(),
write.fs.morph.gii(),
write.fs.surface.gii()
Examples
label <- c(1L, 23L, 44L)
# the positive vertex indices
outfile <- tempfile(fileext = ".gii")
write.fs.label.gii(outfile, label, 50L)
Write file in FreeSurfer MGH or MGZ format
Description
Write brain data to a file in FreeSurfer binary MGH or MGZ format.
Usage
write.fs.mgh(
filepath,
data,
vox2ras_matrix = NULL,
mr_params = c(0, 0, 0, 0, 0),
mri_dtype = "auto"
)
Arguments
filepath |
string. Full path to the output curv file. If this ends with ".mgz", the file will be written gzipped (i.e., in MGZ instead of MGH format). |
data |
matrix or array of numerical values. The brain data to write. Must be integers or doubles. (The data type is set automatically to MRI_INT for integers and MRI_FLOAT for doubles in the MGH header). |
vox2ras_matrix |
4x4 matrix. An affine transformation matrix for the RAS transform that maps voxel indices in the volume to coordinates, such that for y(i1,i2,i3) (i.e., a voxel defined by 3 indices in the volume), the xyz coordinates are |
mr_params |
double vector of length four (without fov) or five. The acquisition parameters, in order: tr, flipangle, te, ti, fov. Spelled out: repetition time, flip angle, echo time, inversion time, field-of-view. The unit for the three times is ms, the angle unit is radians. Defaults to c(0., 0., 0., 0., 0.) if omitted. Pass NULL if you do not want to write them at all. |
mri_dtype |
character string representing an MRI data type code or 'auto'. Valid strings are 'MRI_UCHAR' (1 byte unsigned integer), 'MRI_SHORT' (2 byte signed integer), 'MRI_INT' (4 byte signed integer) and 'MRI_FLOAT' (4 byte signed floating point). The default value |
See Also
Other morphometry functions:
fs.get.morph.file.ext.for.format(),
fs.get.morph.file.format.from.filename(),
read.fs.curv(),
read.fs.mgh(),
read.fs.morph(),
read.fs.morph.gii(),
read.fs.volume(),
read.fs.weight(),
write.fs.curv(),
write.fs.label.gii(),
write.fs.morph(),
write.fs.morph.asc(),
write.fs.morph.gii(),
write.fs.morph.ni1(),
write.fs.morph.ni2(),
write.fs.morph.smp(),
write.fs.morph.txt(),
write.fs.weight(),
write.fs.weight.asc()
Write morphometry data in a format derived from the given file name.
Description
Given data and a morphometry file name, derive the proper format from the file extension and write the file.
Usage
write.fs.morph(filepath, data, format = "auto", ...)
Arguments
filepath |
string. The full file name. The format to use will be derived from the last characters, the suffix. Supported suffixes are "mgh" for MGH format, "mgz" for MGZ format, "smp" for Brainvoyager SMP format, "nii" or "nii.gz" for NIFTI v1 format, "gii" or "gii.gz" for GIFTI format, everything else will be treated as curv format. |
data |
numerical vector. The data to write. |
format |
character string, the format to use. One of c("auto", "mgh", "mgz", "curv", "n1", "ni2", "gii"). The default setting "auto" will determine the format from the file extension. |
... |
additional parameters to pass to the respective writer function. |
Value
character string. The format that was used to write the data. One of c("auto", "mgh", "mgz", "curv", "ni1", "ni2", "gii").
Note
A file name that is one of the standard CIFTI-2 names (e.g. .dscalar.nii or
.dlabel.nii) is an error: such a file has to contain the CIFTI XML metadata, and
a NIFTI file with that name is read as a CIFTI file (and refused) by this package
and by other software. Use write.fs.morph.cifti to write morphometry
data to a CIFTI-2 file, or write.cifti for the other CIFTI-2 types.
See Also
Other morphometry functions:
fs.get.morph.file.ext.for.format(),
fs.get.morph.file.format.from.filename(),
read.fs.curv(),
read.fs.mgh(),
read.fs.morph(),
read.fs.morph.gii(),
read.fs.volume(),
read.fs.weight(),
write.fs.curv(),
write.fs.label.gii(),
write.fs.mgh(),
write.fs.morph.asc(),
write.fs.morph.gii(),
write.fs.morph.ni1(),
write.fs.morph.ni2(),
write.fs.morph.smp(),
write.fs.morph.txt(),
write.fs.weight(),
write.fs.weight.asc()
Write file in FreeSurfer ASCII curv format
Description
Write vertex-wise brain surface data to a file in FreeSurfer ascii 'curv' format.
Usage
write.fs.morph.asc(filepath, data, coords = NULL)
Arguments
filepath |
string. Full path to the output curv file. If it ends with ".gz", the file is written in gzipped format. Note that this is not common, and that other software may not handle this transparently. |
data |
vector of doubles. The brain morphometry data to write, one value per vertex. |
coords |
optional, nx3 matrix of x,y,z coordinates, one row per vertex in 'data'. If |
See Also
Other morphometry functions:
fs.get.morph.file.ext.for.format(),
fs.get.morph.file.format.from.filename(),
read.fs.curv(),
read.fs.mgh(),
read.fs.morph(),
read.fs.morph.gii(),
read.fs.volume(),
read.fs.weight(),
write.fs.curv(),
write.fs.label.gii(),
write.fs.mgh(),
write.fs.morph(),
write.fs.morph.gii(),
write.fs.morph.ni1(),
write.fs.morph.ni2(),
write.fs.morph.smp(),
write.fs.morph.txt(),
write.fs.weight(),
write.fs.weight.asc()
Write morphometry data to a CIFTI-2 .dscalar file.
Description
Write a per-vertex data vector (or several of them, as the maps of the
file) to a CIFTI-2 dense scalar file. This is the inverse of
read.fs.morph.cifti: the data are given for the complete surface, and
the vertices that the file contains are selected with the mapping of a template file
(which is what a grayordinates file needs, since it leaves out the medial wall).
Usage
write.fs.morph.cifti(
filepath,
data,
template = NULL,
structure = NULL,
map_names = NULL,
metadata = NULL
)
Arguments
filepath |
character string, the path of the file to write. The name should end
with |
data |
numeric vector or matrix or named list, the per-vertex data:
The vertex order is the order of the surface mesh, which is also the order in which
|
template |
character string (the path of a CIFTI-2 file), an |
structure |
character string or |
map_names |
character vector or |
metadata |
named character vector or |
Value
the axes that were written, invisibly.
See Also
Other cifti functions:
cifti.axis.brain.models(),
cifti.axis.from.template(),
cifti.axis.labels(),
cifti.axis.parcels(),
cifti.axis.parcels.from.annot(),
cifti.axis.scalars(),
cifti.axis.series(),
cifti.brain.model.surface(),
cifti.brain.model.volume(),
cifti.dim.labels(),
cifti.file.type.for.axes(),
cifti.grayordinates(),
cifti.header.from.axes(),
cifti.label.table(),
cifti.parcel(),
cifti.parcels(),
cifti.series.info(),
cifti.structure.data(),
cifti.structures(),
cifti.volume(),
print.fs.cifti(),
print.fs.cifti.data(),
print.fs.connectome(),
read.cifti(),
read.cifti.header(),
read.cifti.rows(),
read.fs.connectome.cifti(),
write.cifti(),
write.fs.connectome.cifti(),
write.fs.parcellated.cifti(),
write.fs.parcellation.cifti(),
write.fs.series.cifti()
Examples
template <- system.file("extdata", "cifti", "tiny.dscalar.nii", package = "freesurferformats")
out_file <- file.path(tempdir(), "written.dscalar.nii")
data <- read.fs.morph.cifti(template, "lh")
data[2] <- 555 # change one value
write.fs.morph.cifti(out_file, data, template = template, structure = "lh")
read.fs.morph.cifti(out_file, "lh")[1:3]
Write morphometry data in GIFTI format.
Description
The data will be written with intent 'NIFTI_INTENT_SHAPE' and as datatype 'NIFTI_TYPE_FLOAT32'.
Usage
write.fs.morph.gii(filepath, data)
Arguments
filepath |
string, the full path of the output GIFTI file. |
data |
numerical vector, the data to write. Will be coerced to double. |
Value
format, string. The format that was used to write the data: "gii".
See Also
Other morphometry functions:
fs.get.morph.file.ext.for.format(),
fs.get.morph.file.format.from.filename(),
read.fs.curv(),
read.fs.mgh(),
read.fs.morph(),
read.fs.morph.gii(),
read.fs.volume(),
read.fs.weight(),
write.fs.curv(),
write.fs.label.gii(),
write.fs.mgh(),
write.fs.morph(),
write.fs.morph.asc(),
write.fs.morph.ni1(),
write.fs.morph.ni2(),
write.fs.morph.smp(),
write.fs.morph.txt(),
write.fs.weight(),
write.fs.weight.asc()
Other gifti writers:
write.fs.annot.gii(),
write.fs.label.gii(),
write.fs.surface.gii()
Write morphometry data in NIFTI v1 format.
Description
Write morphometry data in NIFTI v1 format.
Usage
write.fs.morph.ni1(filepath, data, ...)
Arguments
filepath |
string, the full path of the output NIFTI file. Should end with '.nii' or '.nii.gz'. |
data |
numerical vector, the data to write. Will be coerced to double. |
... |
extra parameters passed to |
Value
format, string. The format that was used to write the data: "ni1".
See Also
Other morphometry functions:
fs.get.morph.file.ext.for.format(),
fs.get.morph.file.format.from.filename(),
read.fs.curv(),
read.fs.mgh(),
read.fs.morph(),
read.fs.morph.gii(),
read.fs.volume(),
read.fs.weight(),
write.fs.curv(),
write.fs.label.gii(),
write.fs.mgh(),
write.fs.morph(),
write.fs.morph.asc(),
write.fs.morph.gii(),
write.fs.morph.ni2(),
write.fs.morph.smp(),
write.fs.morph.txt(),
write.fs.weight(),
write.fs.weight.asc()
Other nifti1 writers:
nii1header.for.mgh(),
write.nifti1()
Write morphometry data in NIFTI v2 format.
Description
Write morphometry data in NIFTI v2 format.
Usage
write.fs.morph.ni2(filepath, data, ...)
Arguments
filepath |
string, the full path of the output NIFTI file. Should end with '.nii' or '.nii.gz'. |
data |
numerical vector, the data to write. Will be coerced to double. |
... |
extra parameters passed to |
Value
format, string. The format that was used to write the data: "ni2".
Note
Not many software packages support NIFTI v2 format. If possible with your data, you may want to use NIFTI v1 instead.
See Also
nifti.file.version can be used to check whether a file is NIFTI v1 or v2 file.
Other morphometry functions:
fs.get.morph.file.ext.for.format(),
fs.get.morph.file.format.from.filename(),
read.fs.curv(),
read.fs.mgh(),
read.fs.morph(),
read.fs.morph.gii(),
read.fs.volume(),
read.fs.weight(),
write.fs.curv(),
write.fs.label.gii(),
write.fs.mgh(),
write.fs.morph(),
write.fs.morph.asc(),
write.fs.morph.gii(),
write.fs.morph.ni1(),
write.fs.morph.smp(),
write.fs.morph.txt(),
write.fs.weight(),
write.fs.weight.asc()
Other nifti2 writers:
write.nifti2()
Write morphometry data in Brainvoyager SMP format.
Description
Write morphometry data in Brainvoyager SMP format.
Usage
write.fs.morph.smp(filepath, data, ...)
Arguments
filepath |
string, the full path of the output SMP file. |
data |
numerical vector, the data to write. Will be coerced to double. |
... |
extra arguments passed to |
Value
format, string. The format that was used to write the data.
See Also
Other morphometry functions:
fs.get.morph.file.ext.for.format(),
fs.get.morph.file.format.from.filename(),
read.fs.curv(),
read.fs.mgh(),
read.fs.morph(),
read.fs.morph.gii(),
read.fs.volume(),
read.fs.weight(),
write.fs.curv(),
write.fs.label.gii(),
write.fs.mgh(),
write.fs.morph(),
write.fs.morph.asc(),
write.fs.morph.gii(),
write.fs.morph.ni1(),
write.fs.morph.ni2(),
write.fs.morph.txt(),
write.fs.weight(),
write.fs.weight.asc()
Write curv data to file in simple text format
Description
Write vertex-wise brain surface data to a file in a simple text format: one value per line.
Usage
write.fs.morph.txt(filepath, data)
Arguments
filepath |
string. Full path to the output curv file. If it ends with ".gz", the file is written in gzipped format. Note that this is not common, and that other software may not handle this transparently. |
data |
vector of doubles. The brain morphometry data to write, one value per vertex. |
See Also
Other morphometry functions:
fs.get.morph.file.ext.for.format(),
fs.get.morph.file.format.from.filename(),
read.fs.curv(),
read.fs.mgh(),
read.fs.morph(),
read.fs.morph.gii(),
read.fs.volume(),
read.fs.weight(),
write.fs.curv(),
write.fs.label.gii(),
write.fs.mgh(),
write.fs.morph(),
write.fs.morph.asc(),
write.fs.morph.gii(),
write.fs.morph.ni1(),
write.fs.morph.ni2(),
write.fs.morph.smp(),
write.fs.weight(),
write.fs.weight.asc()
Write a CIFTI-2 parcellated map or series file.
Description
Write data that has one value (or one time series) per parcel to a
parcellated CIFTI-2 file: a .pscalar (scalar maps, e.g. a mean value per region) or a
.ptseries (a time series per region). The parcellated dimension of these file types
is matrix dimension 1, and the order of the parcels is the order of the parcels axis,
which comes from a template file or from a parcels axis that you build (see
cifti.axis.parcels.from.annot for a parcellation of this package, e.g.
the annotations of a FreeSurfer atlas).
The file type is derived from the file name: a name ending in .pscalar.nii gets a
scalars dimension (the map names come from map_names), one ending in .ptseries.nii
a series dimension (described by start, step and unit). Use
write.cifti directly for the other parcellated types (.pconn, the
mixed connectome types) or for a file with a non-standard name.
Usage
write.fs.parcellated.cifti(
filepath,
data,
template = NULL,
axes = NULL,
map_names = NULL,
start = 0,
step = 1,
unit = "SECOND",
metadata = NULL
)
Arguments
filepath |
character string, the path of the file to write, ending in
|
data |
numeric vector or matrix, the data: a vector with one value per parcel (a
|
template |
character string (the path of a CIFTI-2 file), an |
axes |
list of two axes or a single parcels axis (see
|
map_names |
character vector or |
start |
numeric, the value of the first series point of a |
step |
numeric, the difference between consecutive series points. |
unit |
character string, the unit of the series, one of 'SECOND', 'HERTZ', 'METER' or 'RADIAN'. |
metadata |
named character vector or named list, or |
Value
the axes that were written, invisibly.
See Also
Other cifti functions:
cifti.axis.brain.models(),
cifti.axis.from.template(),
cifti.axis.labels(),
cifti.axis.parcels(),
cifti.axis.parcels.from.annot(),
cifti.axis.scalars(),
cifti.axis.series(),
cifti.brain.model.surface(),
cifti.brain.model.volume(),
cifti.dim.labels(),
cifti.file.type.for.axes(),
cifti.grayordinates(),
cifti.header.from.axes(),
cifti.label.table(),
cifti.parcel(),
cifti.parcels(),
cifti.series.info(),
cifti.structure.data(),
cifti.structures(),
cifti.volume(),
print.fs.cifti(),
print.fs.cifti.data(),
print.fs.connectome(),
read.cifti(),
read.cifti.header(),
read.cifti.rows(),
read.fs.connectome.cifti(),
write.cifti(),
write.fs.connectome.cifti(),
write.fs.morph.cifti(),
write.fs.parcellation.cifti(),
write.fs.series.cifti()
Examples
template <- system.file("extdata", "cifti", "tiny.ptseries.nii", package = "freesurferformats")
data <- matrix(seq_len(3 * 4), nrow = 4L) # 4 series points, 3 parcels
out_file <- file.path(tempdir(), "written.ptseries.nii")
write.fs.parcellated.cifti(out_file, data, template = template, step = 0.5)
dim(read.cifti(out_file)$data)
Write a parcellation to a CIFTI-2 .dlabel file.
Description
Write per-vertex label keys (one per vertex of the complete surface, per
structure) to a CIFTI-2 dense label file. This is the inverse of
read.fs.parcellation.cifti.
Usage
write.fs.parcellation.cifti(
filepath,
data,
template = NULL,
structure = NULL,
label_table = NULL,
map_name = NULL,
metadata = NULL
)
Arguments
filepath |
character string, the path of the file to write. The name should end
with |
data |
integer vector, matrix or named list, the label keys per vertex, see
|
template |
character string (the path of a CIFTI-2 file), an |
structure |
character string or |
label_table |
data.frame or |
map_name |
character string or |
metadata |
named character vector or |
Value
the axes that were written, invisibly.
See Also
Other cifti functions:
cifti.axis.brain.models(),
cifti.axis.from.template(),
cifti.axis.labels(),
cifti.axis.parcels(),
cifti.axis.parcels.from.annot(),
cifti.axis.scalars(),
cifti.axis.series(),
cifti.brain.model.surface(),
cifti.brain.model.volume(),
cifti.dim.labels(),
cifti.file.type.for.axes(),
cifti.grayordinates(),
cifti.header.from.axes(),
cifti.label.table(),
cifti.parcel(),
cifti.parcels(),
cifti.series.info(),
cifti.structure.data(),
cifti.structures(),
cifti.volume(),
print.fs.cifti(),
print.fs.cifti.data(),
print.fs.connectome(),
read.cifti(),
read.cifti.header(),
read.cifti.rows(),
read.fs.connectome.cifti(),
write.cifti(),
write.fs.connectome.cifti(),
write.fs.morph.cifti(),
write.fs.parcellated.cifti(),
write.fs.series.cifti()
Examples
template <- system.file("extdata", "cifti", "tiny.dlabel.nii", package = "freesurferformats")
keys <- read.fs.parcellation.cifti(template, "lh")
label_table <- read.fs.parcellation.cifti(template, "lh", with_label_table = TRUE)$label_table
out_file <- file.path(tempdir(), "written.dlabel.nii")
write.fs.parcellation.cifti(out_file, keys, template = template, structure = "lh",
label_table = label_table)
table(read.fs.parcellation.cifti(out_file, "lh"))
Write a surface patch
Description
Write a surface patch, i.e. a set of vertices and patch border information, to a binary patch file.
Usage
write.fs.patch(filepath, patch)
Arguments
filepath |
string. Full path to the output patch file. If it ends with ".gz", the file is written in gzipped format. Note that this is not common, and that other software may not handle this transparently. |
patch |
an instance of class |
Value
the patch, invisible
See Also
Other patch functions:
fs.patch(),
read.fs.patch(),
read.fs.patch.asc()
Write time series data to a CIFTI-2 .dtseries file.
Description
Write a per-vertex time series (or several structures at once) to a CIFTI-2
dense series file. This is the inverse of read.fs.series.cifti.
Usage
write.fs.series.cifti(
filepath,
data,
template = NULL,
structure = NULL,
start = 0,
step = 1,
unit = "SECOND",
metadata = NULL
)
Arguments
filepath |
character string, the path of the file to write. The name should end
with |
data |
numeric matrix or named list, the data: a matrix with one row per vertex of the complete surface and one column per series point (time point), or a named list of such matrices per structure. |
template |
character string (the path of a CIFTI-2 file), an |
structure |
character string or |
start |
numeric, the value of the first series point, see
|
step |
numeric, the difference between consecutive series points. |
unit |
character string, the unit of the series, one of 'SECOND', 'HERTZ', 'METER' or 'RADIAN'. |
metadata |
named character vector or |
Value
the axes that were written, invisibly.
See Also
Other cifti functions:
cifti.axis.brain.models(),
cifti.axis.from.template(),
cifti.axis.labels(),
cifti.axis.parcels(),
cifti.axis.parcels.from.annot(),
cifti.axis.scalars(),
cifti.axis.series(),
cifti.brain.model.surface(),
cifti.brain.model.volume(),
cifti.dim.labels(),
cifti.file.type.for.axes(),
cifti.grayordinates(),
cifti.header.from.axes(),
cifti.label.table(),
cifti.parcel(),
cifti.parcels(),
cifti.series.info(),
cifti.structure.data(),
cifti.structures(),
cifti.volume(),
print.fs.cifti(),
print.fs.cifti.data(),
print.fs.connectome(),
read.cifti(),
read.cifti.header(),
read.cifti.rows(),
read.fs.connectome.cifti(),
write.cifti(),
write.fs.connectome.cifti(),
write.fs.morph.cifti(),
write.fs.parcellated.cifti(),
write.fs.parcellation.cifti()
Examples
template <- system.file("extdata", "cifti", "tiny.dscalar.nii", package = "freesurferformats")
series <- matrix(seq_len(10 * 3), nrow = 10L) # 10 vertices (lh), 3 time points
out_file <- file.path(tempdir(), "written.dtseries.nii")
write.fs.series.cifti(out_file, series, template = template, structure = "lh", step = 0.72)
dim(read.fs.series.cifti(out_file, "lh"))
Write mesh to file in FreeSurfer binary surface format
Description
Write vertex coordinates and vertex indices defining faces to a file in FreeSurfer binary surface format. For a subject (MRI image pre-processed with FreeSurfer) named 'bert', an example file would be 'bert/surf/lh.white'. This function writes the triangle version of the surface file format.
Usage
write.fs.surface(filepath, vertex_coords, faces, format = "auto")
Arguments
filepath |
string. Full path to the output curv file. If it ends with ".gz", the file is written in gzipped format. Note that this is not common, and that other software may not handle this transparently. |
vertex_coords |
n x 3 matrix of doubles. Each row defined the x,y,z coords for a vertex. |
faces |
n x 3 matrix of integers. Each row defined the 3 vertex indices that make up the face. WARNING: Vertex indices should be given in R-style, i.e., the index of the first vertex is 1. However, they will be written in FreeSurfer style, i.e., all indices will have 1 substracted, so that the index of the first vertex will be zero. |
format |
character string, the format to use. One of 'bin' for FreeSurfer binary surface format, 'asc' for FreeSurfer ASCII format, 'vtk' for VTK ASCII legacy format, 'ply' for Standford PLY format, 'off' for Object File Format, 'obj' for Wavefront object format, 'gii' for GIFTI format, 'mz3' for Surf-Ice MZ3 fomat, 'byu' for Brigham Young University (BYU) mesh format, 'stl' for the stereolithography (STL) format used for 3D printing, or 'auto' to derive the format from the file extension given in parameter 'filepath'. With 'auto', a path ending in '.asc' is interpreted as 'asc', a path ending in '.vtk' as vtk, and so on for the other formats. A path ending in '.stla' is interpreted as the ASCII variant of the STL format and one ending in '.stlb' or '.stl' as the binary variant. Everything not matching any of these is interpreted as 'bin', i.e., FreeSurfer binary surface format. |
Value
character string, the format that was written. One of "tris" or "quads". Currently only triangular meshes are supported, so always 'tris'.
See Also
Other mesh functions:
faces.quad.to.tris(),
read.fs.surface(),
read.fs.surface.asc(),
read.fs.surface.bvsrf(),
read.fs.surface.geo(),
read.fs.surface.gii(),
read.fs.surface.ico(),
read.fs.surface.obj(),
read.fs.surface.off(),
read.fs.surface.ply(),
read.fs.surface.vtk(),
read.mesh.brainvoyager(),
read_nisurface(),
read_nisurfacefile(),
write.fs.surface.asc(),
write.fs.surface.byu(),
write.fs.surface.gii(),
write.fs.surface.mz3(),
write.fs.surface.vtk()
Other mesh export functions:
write.fs.surface.obj(),
write.fs.surface.off(),
write.fs.surface.off.ply2(),
write.fs.surface.ply(),
write.fs.surface.ply2(),
write.fs.surface.stl(),
write.fs.surface.vtk()
Examples
## Not run:
# Read a surface from a file:
surface_file <- system.file("extdata", "lh.tinysurface",
package = "freesurferformats", mustWork = TRUE
)
mesh <- read.fs.surface(surface_file)
# Now save it:
write.fs.surface(tempfile(), mesh$vertices, mesh$faces)
## End(Not run)
Write mesh to file in FreeSurfer ASCII surface format
Description
Write vertex coordinates and vertex indices defining faces to a file in FreeSurfer ASCII surface format. For a subject (MRI image pre-processed with FreeSurfer) named 'bert', an example file would be 'bert/surf/lh.white.asc'.
Usage
write.fs.surface.asc(filepath, vertex_coords, faces)
Arguments
filepath |
string. Full path to the output surface file, should end with '.asc', but that is not enforced. |
vertex_coords |
n x 3 matrix of doubles. Each row defined the x,y,z coords for a vertex. |
faces |
n x 3 matrix of integers. Each row defined the 3 vertex indices that make up the face. WARNING: Vertex indices should be given in R-style, i.e., the index of the first vertex is 1. However, they will be written in FreeSurfer style, i.e., all indices will have 1 substracted, so that the index of the first vertex will be zero. |
Value
string the format that was written. One of "tris" or "quads". Currently only triangular meshes are supported, so always 'tris'.
See Also
Other mesh functions:
faces.quad.to.tris(),
read.fs.surface(),
read.fs.surface.asc(),
read.fs.surface.bvsrf(),
read.fs.surface.geo(),
read.fs.surface.gii(),
read.fs.surface.ico(),
read.fs.surface.obj(),
read.fs.surface.off(),
read.fs.surface.ply(),
read.fs.surface.vtk(),
read.mesh.brainvoyager(),
read_nisurface(),
read_nisurfacefile(),
write.fs.surface(),
write.fs.surface.byu(),
write.fs.surface.gii(),
write.fs.surface.mz3(),
write.fs.surface.vtk()
Examples
## Not run:
# Read a surface from a file:
surface_file <- system.file("extdata", "lh.tinysurface",
package = "freesurferformats", mustWork = TRUE
)
mesh <- read.fs.surface(surface_file)
# Now save it:
write.fs.surface.asc(tempfile(fileext = ".asc"), mesh$vertices, mesh$faces)
## End(Not run)
Write surface to Brainvoyager SRF file.
Description
Write surface to Brainvoyager SRF file.
Usage
write.fs.surface.bvsrf(
filepath,
vertex_coords,
faces,
normals = NULL,
neighborhoods = NULL
)
Arguments
filepath |
string. Full path to the output curv file. If it ends with ".gz", the file is written in gzipped format. Note that this is not common, and that other software may not handle this transparently. |
vertex_coords |
n x 3 matrix of doubles. Each row defined the x,y,z coords for a vertex. |
faces |
n x 3 matrix of integers. Each row defined the 3 vertex indices that make up the face. WARNING: Vertex indices should be given in R-style, i.e., the index of the first vertex is 1. However, they will be written in FreeSurfer style, i.e., all indices will have 1 substracted, so that the index of the first vertex will be zero. |
normals |
matrix of nx3 vertex normals (x,y,z) |
neighborhoods |
list of integer lists, the indices of the nearest neighbors for each vertex (an adjacency list). The sub list at index n contains the indices of the vertices in the 1-neighborhood of vertex n. The vertex indices in the sub lists must be zero-based. |
Note
This function is experimental. Only SRF file format version 4 is supported.
Write mesh to file in BYU ASCII format.
Description
Write mesh to file in BYU ASCII format.
Usage
write.fs.surface.byu(filepath, vertex_coords, faces)
Arguments
filepath |
string. Full path to the output surface file, should end with '.byu', but that is not enforced. |
vertex_coords |
n x 3 matrix of doubles. Each row defined the x,y,z coords for a vertex. |
faces |
n x 3 matrix of integers. Each row defined the 3 vertex indices that make up the face. WARNING: Vertex indices should be given in R-style, i.e., the index of the first vertex is 1. However, they will be written in FreeSurfer style, i.e., all indices will have 1 substracted, so that the index of the first vertex will be zero. |
Value
string the format that was written. One of "tris" or "quads". Currently only triangular meshes are supported, so always 'tris'.
Note
This is a fixed field length ASCII format. Keep in mind that the BYU format expects the coordinates to be in the cube -1 to +1 on all three axes.
See Also
Other mesh functions:
faces.quad.to.tris(),
read.fs.surface(),
read.fs.surface.asc(),
read.fs.surface.bvsrf(),
read.fs.surface.geo(),
read.fs.surface.gii(),
read.fs.surface.ico(),
read.fs.surface.obj(),
read.fs.surface.off(),
read.fs.surface.ply(),
read.fs.surface.vtk(),
read.mesh.brainvoyager(),
read_nisurface(),
read_nisurfacefile(),
write.fs.surface(),
write.fs.surface.asc(),
write.fs.surface.gii(),
write.fs.surface.mz3(),
write.fs.surface.vtk()
Examples
## Not run:
# Read a surface from a file:
surface_file <- system.file("extdata", "lh.tinysurface",
package = "freesurferformats", mustWork = TRUE
)
mesh <- read.fs.surface(surface_file)
# Now save it:
write.fs.surface.byu(tempfile(fileext = ".byu"), mesh$vertices, mesh$faces)
## End(Not run)
Write mesh to file in GIFTI surface format
Description
Write vertex coordinates and vertex indices defining faces to a file in GIFTI surface format. For a subject (MRI image pre-processed with FreeSurfer) named 'bert', an example file would be 'bert/surf/lh.white.asc'.
Usage
write.fs.surface.gii(filepath, vertex_coords, faces)
Arguments
filepath |
string. Full path to the output surface file, should end with '.asc', but that is not enforced. |
vertex_coords |
n x 3 matrix of doubles. Each row defined the x,y,z coords for a vertex. |
faces |
n x 3 matrix of integers. Each row defined the 3 vertex indices that make up the face. WARNING: Vertex indices should be given in R-style, i.e., the index of the first vertex is 1. However, they will be written in FreeSurfer style, i.e., all indices will have 1 substracted, so that the index of the first vertex will be zero. |
Value
string the format that was written. One of "tris" or "quads". Currently only triangular meshes are supported, so always 'tris'.
See Also
Other mesh functions:
faces.quad.to.tris(),
read.fs.surface(),
read.fs.surface.asc(),
read.fs.surface.bvsrf(),
read.fs.surface.geo(),
read.fs.surface.gii(),
read.fs.surface.ico(),
read.fs.surface.obj(),
read.fs.surface.off(),
read.fs.surface.ply(),
read.fs.surface.vtk(),
read.mesh.brainvoyager(),
read_nisurface(),
read_nisurfacefile(),
write.fs.surface(),
write.fs.surface.asc(),
write.fs.surface.byu(),
write.fs.surface.mz3(),
write.fs.surface.vtk()
Other gifti writers:
write.fs.annot.gii(),
write.fs.label.gii(),
write.fs.morph.gii()
Examples
## Not run:
# Read a surface from a file:
surface_file <- system.file("extdata", "lh.tinysurface",
package = "freesurferformats", mustWork = TRUE
)
mesh <- read.fs.surface(surface_file)
# Now save it:
write.fs.surface.gii(tempfile(fileext = ".gii"), mesh$vertices, mesh$faces)
## End(Not run)
Write mesh to file in mz3 binary format.
Description
Write mesh to file in mz3 binary format.
Usage
write.fs.surface.mz3(filepath, vertex_coords, faces, gzipped = TRUE)
Arguments
filepath |
string. Full path to the output surface file, should end with '.mz3', but that is not enforced. |
vertex_coords |
n x 3 matrix of doubles. Each row defined the x,y,z coords for a vertex. |
faces |
n x 3 matrix of integers. Each row defined the 3 vertex indices that make up the face. WARNING: Vertex indices should be given in R-style, i.e., the index of the first vertex is 1. However, they will be written in FreeSurfer style, i.e., all indices will have 1 substracted, so that the index of the first vertex will be zero. |
gzipped |
logical, whether to write a gzip compressed file |
Value
string the format that was written. One of "tris" or "quads". Currently only triangular meshes are supported, so always 'tris'.
Note
This format is used by the surf-ice renderer. The format spec is at https://github.com/neurolabusc/surf-ice/tree/master/mz3.
See Also
Other mesh functions:
faces.quad.to.tris(),
read.fs.surface(),
read.fs.surface.asc(),
read.fs.surface.bvsrf(),
read.fs.surface.geo(),
read.fs.surface.gii(),
read.fs.surface.ico(),
read.fs.surface.obj(),
read.fs.surface.off(),
read.fs.surface.ply(),
read.fs.surface.vtk(),
read.mesh.brainvoyager(),
read_nisurface(),
read_nisurfacefile(),
write.fs.surface(),
write.fs.surface.asc(),
write.fs.surface.byu(),
write.fs.surface.gii(),
write.fs.surface.vtk()
Examples
## Not run:
# Read a surface from a file:
surface_file <- system.file("extdata", "lh.tinysurface",
package = "freesurferformats", mustWork = TRUE
)
mesh <- read.fs.surface(surface_file)
# Now save it:
write.fs.surface.mz3(tempfile(fileext = ".mz3"), mesh$vertices, mesh$faces)
## End(Not run)
Write mesh to file in Wavefront object (.obj) format
Description
The wavefront object format is a simply ASCII format for storing meshes.
Usage
write.fs.surface.obj(filepath, vertex_coords, faces, vertex_colors = NULL)
Arguments
filepath |
string. Full path to the output surface file, should end with '.vtk', but that is not enforced. |
vertex_coords |
n x 3 matrix of doubles. Each row defined the x,y,z coords for a vertex. |
faces |
n x 3 matrix of integers. Each row defined the 3 vertex indices that make up the face. WARNING: Vertex indices should be given in R-style, i.e., the index of the first vertex is 1. However, they will be written in FreeSurfer style, i.e., all indices will have 1 substracted, so that the index of the first vertex will be zero. |
vertex_colors |
vector of vertex colors. Will be written after the x, y, z coords on vertex lines. WARNING: This is NOT part of the official OBJ standard, and may not work with other software and even break some parsers. |
Value
string the format that was written. One of "tris" or "quads". Currently only triangular meshes are supported, so always 'tris'.
Note
Do not confuse the Wavefront object file format (.obj) with the OFF format (.off), they are not identical.
See Also
Other mesh export functions:
write.fs.surface(),
write.fs.surface.off(),
write.fs.surface.off.ply2(),
write.fs.surface.ply(),
write.fs.surface.ply2(),
write.fs.surface.stl(),
write.fs.surface.vtk()
Examples
## Not run:
# Read a surface from a file:
surface_file <- system.file("extdata", "lh.tinysurface",
package = "freesurferformats", mustWork = TRUE
)
mesh <- read.fs.surface(surface_file)
# Now save it:
write.fs.surface.obj(tempfile(fileext = ".obj"), mesh$vertices, mesh$faces)
## End(Not run)
Write mesh to file in Object File Format (.off)
Description
The Object File Format is a simply ASCII format for storing meshes.
Usage
write.fs.surface.off(filepath, vertex_coords, faces)
Arguments
filepath |
string. Full path to the output surface file, should end with '.off', but that is not enforced. |
vertex_coords |
n x 3 matrix of doubles. Each row defined the x,y,z coords for a vertex. |
faces |
n x 3 matrix of integers. Each row defined the 3 vertex indices that make up the face. WARNING: Vertex indices should be given in R-style, i.e., the index of the first vertex is 1. However, they will be written in FreeSurfer style, i.e., all indices will have 1 substracted, so that the index of the first vertex will be zero. |
Value
string the format that was written. One of "tris" or "quads". Currently only triangular meshes are supported, so always 'tris'.
Note
Do not confuse the OFF format (.off) with the Wavefront object file format (.obj), they are not identical.
See Also
Other mesh export functions:
write.fs.surface(),
write.fs.surface.obj(),
write.fs.surface.off.ply2(),
write.fs.surface.ply(),
write.fs.surface.ply2(),
write.fs.surface.stl(),
write.fs.surface.vtk()
Examples
## Not run:
# Read a surface from a file:
surface_file <- system.file("extdata", "lh.tinysurface",
package = "freesurferformats", mustWork = TRUE
)
mesh <- read.fs.surface(surface_file)
# Now save it:
write.fs.surface.off(tempfile(fileext = ".off"), mesh$vertices, mesh$faces)
## End(Not run)
Write mesh to file in Object File Format (.off) or PLY2 format.
Description
The two formats are very similar, they only differ in the header lines. This function can write both.
Usage
write.fs.surface.off.ply2(filepath, vertex_coords, faces, format)
Arguments
filepath |
string. Full path to the output surface file, should end with '.off', but that is not enforced. |
vertex_coords |
n x 3 matrix of doubles. Each row defined the x,y,z coords for a vertex. |
faces |
n x 3 matrix of integers. Each row defined the 3 vertex indices that make up the face. WARNING: Vertex indices should be given in R-style, i.e., the index of the first vertex is 1. However, they will be written in FreeSurfer style, i.e., all indices will have 1 substracted, so that the index of the first vertex will be zero. |
format |
character string, the format to write. One of 'ply2' or 'off'. |
Value
string the format that was written. One of "tris" or "quads". Currently only triangular meshes are supported, so always 'tris'.
Note
Do not confuse the OFF format (.off) with the Wavefront object file format (.obj), they are not identical.
See Also
Other mesh export functions:
write.fs.surface(),
write.fs.surface.obj(),
write.fs.surface.off(),
write.fs.surface.ply(),
write.fs.surface.ply2(),
write.fs.surface.stl(),
write.fs.surface.vtk()
Examples
## Not run:
# Read a surface from a file:
surface_file <- system.file("extdata", "lh.tinysurface",
package = "freesurferformats", mustWork = TRUE
)
mesh <- read.fs.surface(surface_file)
# Now save it:
write.fs.surface.off(tempfile(fileext = ".off"), mesh$vertices, mesh$faces)
## End(Not run)
Write mesh to file in PLY format (.ply)
Description
The PLY format is a versatile ASCII format for storing meshes. Also known as Polygon File Format or Stanford Triangle Format.
Usage
write.fs.surface.ply(filepath, vertex_coords, faces, vertex_colors = NULL)
Arguments
filepath |
string. Full path to the output surface file, should end with '.vtk', but that is not enforced. |
vertex_coords |
n x 3 matrix of doubles. Each row defined the x,y,z coords for a vertex. |
faces |
m x 3 matrix of integers. Each row defined the 3 vertex indices that make up the face. WARNING: Vertex indices should be given in R-style, i.e., the index of the first vertex is 1. However, they will be written in FreeSurfer style, i.e., all indices will have 1 substracted, so that the index of the first vertex will be zero. |
vertex_colors |
optional, matrix of RGBA vertex colors, number of rows must be the same as for vertex_coords. Color values must be integers in range 0-255. Alternatively, a vector of n RGB color strings can be passed. |
Value
string the format that was written. One of "tris" or "quads". Currently only triangular meshes are supported, so always 'tris'.
References
See http://paulbourke.net/dataformats/ply/ for the PLY format spec.
See Also
Other mesh export functions:
write.fs.surface(),
write.fs.surface.obj(),
write.fs.surface.off(),
write.fs.surface.off.ply2(),
write.fs.surface.ply2(),
write.fs.surface.stl(),
write.fs.surface.vtk()
Examples
## Not run:
# Read a surface from a file:
surface_file <- system.file("extdata", "lh.tinysurface",
package = "freesurferformats", mustWork = TRUE
)
mesh <- read.fs.surface(surface_file)
# Now save it:
write.fs.surface.ply(tempfile(fileext = ".ply"), mesh$vertices, mesh$faces)
# save a version with RGBA vertex colors
vertex_colors <- matrix(rep(82L, 5 * 4), ncol = 4)
write.fs.surface.ply(tempfile(fileext = ".ply"), mesh$vertices,
mesh$faces,
vertex_colors = vertex_colors
)
## End(Not run)
Write mesh to file in PLY2 File Format (.ply2)
Description
The PLY2 file format is a simply ASCII format for storing meshes. It is very similar to OFF and by far not as flexible as PLY.
Usage
write.fs.surface.ply2(filepath, vertex_coords, faces)
Arguments
filepath |
string. Full path to the output surface file, should end with '.off', but that is not enforced. |
vertex_coords |
n x 3 matrix of doubles. Each row defined the x,y,z coords for a vertex. |
faces |
n x 3 matrix of integers. Each row defined the 3 vertex indices that make up the face. WARNING: Vertex indices should be given in R-style, i.e., the index of the first vertex is 1. However, they will be written in FreeSurfer style, i.e., all indices will have 1 substracted, so that the index of the first vertex will be zero. |
Value
string the format that was written. One of "tris" or "quads". Currently only triangular meshes are supported, so always 'tris'.
See Also
Other mesh export functions:
write.fs.surface(),
write.fs.surface.obj(),
write.fs.surface.off(),
write.fs.surface.off.ply2(),
write.fs.surface.ply(),
write.fs.surface.stl(),
write.fs.surface.vtk()
Examples
## Not run:
# Read a surface from a file:
surface_file <- system.file("extdata", "lh.tinysurface",
package = "freesurferformats", mustWork = TRUE
)
mesh <- read.fs.surface(surface_file)
# Now save it:
write.fs.surface.ply2(tempfile(fileext = ".ply2"), mesh$vertices, mesh$faces)
## End(Not run)
Write mesh to file in STL format (ASCII or binary).
Description
The STL format (stereolithography, the format used for 3D
printing) stores a triangular mesh as a list of triangles, each with its
vertex coordinates repeated and with a normal vector, instead of storing a
vertex list and indices into it. Both the ASCII and the binary version of
the format are written by this function, the binary one being the default
since it is much smaller and it is what most software uses. The resulting
files can be read back with read.fs.surface.stl and are
accepted by mesh viewers and slicers.
Usage
write.fs.surface.stl(
filepath,
vertex_coords,
faces,
ascii = FALSE,
solid_name = "mesh"
)
Arguments
filepath |
character string, the path of the file to write. |
vertex_coords |
n x 3 matrix of doubles, the vertex coordinates. |
faces |
n x 3 matrix of integers, the vertex indices of the triangles.
The STL format has no support for polygons with more than 3 vertices, so a
quad mesh has to be converted first with |
ascii |
logical, whether to write the ASCII version of the format. The default is the binary version, which is smaller by a factor of about 5 and which is what most mesh processing software writes. Use the ASCII version if the file has to be readable by humans or by software that supports only the ASCII variant. |
solid_name |
character string, the name of the mesh. Only used in the ASCII version, where the format requires the name in the first and the last line of the file. |
Value
character string, the format that was written: 'tris'.
Note
The normals of the triangles are computed from the vertex coordinates (the STL format stores them, but no reader has to trust them). A degenerate triangle, i.e., one whose vertices are collinear or identical, has no normal, so a zero vector is written for it.
An indexed mesh is stored as a polygon soup in an STL file: every
triangle repeats the coordinates of its vertices. Reading such a file back
with read.fs.surface.stl merges the repeated vertices again
(using the digits precision of that function), so a round trip
through an STL file preserves the geometry of the mesh, but not the order or
the count of the vertices in the vertex list.
See Also
Other mesh export functions:
write.fs.surface(),
write.fs.surface.obj(),
write.fs.surface.off(),
write.fs.surface.off.ply2(),
write.fs.surface.ply(),
write.fs.surface.ply2(),
write.fs.surface.vtk()
Examples
## Not run:
# Write a mesh as binary and as ASCII STL:
mesh <- read.fs.surface(system.file("extdata", "cube.stl", package = "freesurferformats"));
write.fs.surface.stl(tempfile(fileext = ".stl"), mesh$vertices, mesh$faces);
write.fs.surface.stl(tempfile(fileext = ".stl"), mesh$vertices, mesh$faces, ascii = TRUE);
# The file format is also chosen by the file name when using the generic
# writer:
write.fs.surface(tempfile(fileext = ".stl"), mesh$vertices, mesh$faces);
## End(Not run)
Write mesh to file in VTK legacy format
Description
The VTK legacy format is the plain text/binary format that is supported by all versions of the VTK library; the XML based VTK format (.vtp) is not the same thing. Two variants of the file layout exist and are both still written by software in use today: the old layout introduced in VTK 4.2, and the layout that VTK produces since version 5.1 (released 2015). The parameter 'version' selects which one to write.
Usage
write.fs.surface.vtk(
filepath,
vertex_coords,
faces,
version = 4.2,
binary = FALSE
)
Arguments
filepath |
string. Full path to the output surface file, should end with '.vtk', but that is not enforced. |
vertex_coords |
n x 3 matrix of doubles. Each row defined the x,y,z coords for a vertex. |
faces |
n x 3 matrix of integers. Each row defined the 3 vertex indices that make up the face. WARNING: Vertex indices should be given in R-style, i.e., the index of the first vertex is 1. However, they will be written in VTK style, i.e., all indices will have 1 substracted, so that the index of the first vertex will be zero. |
version |
double, the VTK version whose file layout to write. Either 4.2 (the default) or 5.1. Version 4.2 writes the cell array layout that every VTK version can read, version 5.1 writes the |
binary |
logical, whether to write the data in binary form instead of the ASCII text form. Binary files are much smaller and much faster to read and write, but they are not human readable. Defaults to FALSE. |
Value
string the format that was written. One of "tris" or "quads". Currently only triangular meshes are supported, so always 'tris'.
Note
Binary data in the VTK legacy format is always big endian, the format has no way of expressing a different byte order. The vertex coordinates are written as single precision (4 byte) floats in both encodings, which is what VTK itself does.
See Also
Other mesh functions:
faces.quad.to.tris(),
read.fs.surface(),
read.fs.surface.asc(),
read.fs.surface.bvsrf(),
read.fs.surface.geo(),
read.fs.surface.gii(),
read.fs.surface.ico(),
read.fs.surface.obj(),
read.fs.surface.off(),
read.fs.surface.ply(),
read.fs.surface.vtk(),
read.mesh.brainvoyager(),
read_nisurface(),
read_nisurfacefile(),
write.fs.surface(),
write.fs.surface.asc(),
write.fs.surface.byu(),
write.fs.surface.gii(),
write.fs.surface.mz3()
Other mesh export functions:
write.fs.surface(),
write.fs.surface.obj(),
write.fs.surface.off(),
write.fs.surface.off.ply2(),
write.fs.surface.ply(),
write.fs.surface.ply2(),
write.fs.surface.stl()
Examples
## Not run:
# Read a surface from a file:
surface_file <- system.file("extdata", "lh.tinysurface",
package = "freesurferformats", mustWork = TRUE
)
mesh <- read.fs.surface(surface_file)
# Now save it:
write.fs.surface.vtk(tempfile(fileext = ".vtk"), mesh$vertices, mesh$faces)
# Or as a binary file using the layout of VTK 5.1:
write.fs.surface.vtk(tempfile(fileext = ".vtk"), mesh$vertices, mesh$faces,
version = 5.1, binary = TRUE
)
## End(Not run)
Write a transformation matrix to a file.
Description
Save an fs.transform instance in one of the supported transformation file formats.
A transformation stores its matrix together with the coordinate spaces it maps between, and the formats
disagree about which spaces they can express. A transformation is only written if the format can represent it
exactly, because a silent conversion would change the meaning of the matrix: FSL matrix files, for example,
store voxel-to-voxel matrices, so a transformation in world coordinates must be converted first with
transform2voxel. A format that cannot express the transformation at all is an error, not a
warning.
Usage
write.fs.transform(tf, filepath, format = "auto")
Arguments
tf |
an |
filepath |
character string, the full path of the file to write. |
format |
character string, the file format, one of 'auto' (guess from the file extension), 'fslmat' (an
FSL/FLIRT matrix file, i.e. a plain text 4x4 matrix as written by FSL's |
Value
the fs.transform instance tf, invisibly.
See Also
Other header coordinate space:
invert.fs.transform(),
is.fs.transform(),
mghheader.is.ras.valid(),
mghheader.ras2vox(),
mghheader.ras2vox.tkreg(),
mghheader.scanner2tkreg(),
mghheader.tkreg2scanner(),
mghheader.vox2ras(),
mghheader.vox2ras.tkreg(),
print.fs.transform(),
read.fs.transform(),
read.fs.transform.dat(),
read.fs.transform.fslmat(),
read.fs.transform.itk(),
read.fs.transform.lta(),
read.fs.transform.xfm(),
sm0to1(),
sm1to0(),
summary.fs.transform(),
transform2lps(),
transform2ras(),
transform2voxel(),
transform2world(),
write.fs.transform.dat(),
write.fs.transform.fslmat(),
write.fs.transform.itk(),
write.fs.transform.lta(),
write.fs.transform.xfm()
Examples
tf <- read.fs.transform(system.file("extdata", "talairach.lta",
package = "freesurferformats", mustWork = TRUE
))
out_file <- tempfile(fileext = ".mat")
# An LTA of type 0 is a voxel-to-voxel transformation, so it can be written as an FSL matrix.
write.fs.transform(tf, out_file, format = "fslmat")
read.fs.transform(out_file)$matrix
unlink(out_file)
# The same transformation can be written in the FreeSurfer formats of the spaces it maps between.
out_file <- tempfile(fileext = ".lta")
write.fs.transform(tf, out_file)
unlink(out_file)
Write a tkregister dat file.
Description
Write a transformation in the FreeSurfer tkregister format (register.dat), the format that
mri_vol2vol --reg, tkregister2 and bbregister use. Such a matrix maps the voxel coordinates of the
movable volume (the source) to RAS coordinates in the tkregister frame of the target volume, see
mghheader.vox2ras.tkreg, so a transformation can only be written if this is what it maps.
Usage
write.fs.transform.dat(
tf,
filepath,
subject = NULL,
in_plane_resolution = NULL
)
Arguments
tf |
an |
filepath |
character string, the full path of the file to write. |
subject |
|
in_plane_resolution |
|
Value
the fs.transform instance tf, invisibly.
See Also
Other header coordinate space:
invert.fs.transform(),
is.fs.transform(),
mghheader.is.ras.valid(),
mghheader.ras2vox(),
mghheader.ras2vox.tkreg(),
mghheader.scanner2tkreg(),
mghheader.tkreg2scanner(),
mghheader.vox2ras(),
mghheader.vox2ras.tkreg(),
print.fs.transform(),
read.fs.transform(),
read.fs.transform.dat(),
read.fs.transform.fslmat(),
read.fs.transform.itk(),
read.fs.transform.lta(),
read.fs.transform.xfm(),
sm0to1(),
sm1to0(),
summary.fs.transform(),
transform2lps(),
transform2ras(),
transform2voxel(),
transform2world(),
write.fs.transform(),
write.fs.transform.fslmat(),
write.fs.transform.itk(),
write.fs.transform.lta(),
write.fs.transform.xfm()
Examples
dat_file <- system.file("extdata", "register.dat", package = "freesurferformats", mustWork = TRUE)
tf <- read.fs.transform(dat_file)
out_file <- tempfile(fileext = ".dat")
write.fs.transform.dat(tf, out_file)
max(abs(read.fs.transform(out_file)$matrix - tf$matrix)) # 0
unlink(out_file)
Write a transformation matrix in FSL format.
Description
Write a 4x4 matrix as an FSL matrix file, i.e. as the plain text file that FSL's flirt writes
with the -omat option and that FSL, MRtrix3 and FreeSurfer read as the registration between two images. The
matrix must map voxel coordinates to voxel coordinates (space_in and space_out are 'voxel'), because that
is what an FSL matrix stores: it relates the voxel grid of the image given to flirt -in to the voxel grid of
the image given to flirt -ref, and it does not record which images those were. Use
transform2voxel to convert a transformation in world coordinates into one that can be
written.
Usage
write.fs.transform.fslmat(tf, filepath)
Arguments
tf |
an |
filepath |
character string, the full path of the file to write. |
Value
the fs.transform instance tf, invisibly.
See Also
Other header coordinate space:
invert.fs.transform(),
is.fs.transform(),
mghheader.is.ras.valid(),
mghheader.ras2vox(),
mghheader.ras2vox.tkreg(),
mghheader.scanner2tkreg(),
mghheader.tkreg2scanner(),
mghheader.vox2ras(),
mghheader.vox2ras.tkreg(),
print.fs.transform(),
read.fs.transform(),
read.fs.transform.dat(),
read.fs.transform.fslmat(),
read.fs.transform.itk(),
read.fs.transform.lta(),
read.fs.transform.xfm(),
sm0to1(),
sm1to0(),
summary.fs.transform(),
transform2lps(),
transform2ras(),
transform2voxel(),
transform2world(),
write.fs.transform(),
write.fs.transform.dat(),
write.fs.transform.itk(),
write.fs.transform.lta(),
write.fs.transform.xfm()
Examples
tf_file <- system.file("extdata", "talairach.lta", package = "freesurferformats", mustWork = TRUE)
out_file <- tempfile(fileext = ".mat")
write.fs.transform.fslmat(read.fs.transform(tf_file), out_file)
readLines(out_file)
unlink(out_file)
Write an ITK text transform file.
Description
Write a transformation in the text file format of ITK, which the tools built on ITK read: 3D
Slicer (which calls it the 'ITK Transform' format), ANTs (via ConvertTransformFile), SimpleITK, and the
workflows that write their transformations with them. The file name extension is usually .tfm or .txt.
An ITK transform operates on the world coordinates of the images, which in ITK are
left-posterior-superior, so only a transformation that maps LPS coordinates can be written. Use
transform2lps to convert a transformation in RAS coordinates.
Usage
write.fs.transform.itk(tf, filepath)
Arguments
tf |
an |
filepath |
character string, the full path of the file to write. |
Value
the fs.transform instance tf, invisibly.
Note
The file that is written uses the class 'AffineTransform_double_3_3', i.e. the parameters are stored in
double precision, and it states a center of rotation of zero, with the center folded into the translation.
This is exactly the form that FreeSurfer's lta_convert --outitk writes, and the form that
lta_convert --initk can read: it rejects the 'float' variant of the classes and ignores a non-zero center
of rotation, see the note in read.fs.transform.itk.
See Also
Other header coordinate space:
invert.fs.transform(),
is.fs.transform(),
mghheader.is.ras.valid(),
mghheader.ras2vox(),
mghheader.ras2vox.tkreg(),
mghheader.scanner2tkreg(),
mghheader.tkreg2scanner(),
mghheader.vox2ras(),
mghheader.vox2ras.tkreg(),
print.fs.transform(),
read.fs.transform(),
read.fs.transform.dat(),
read.fs.transform.fslmat(),
read.fs.transform.itk(),
read.fs.transform.lta(),
read.fs.transform.xfm(),
sm0to1(),
sm1to0(),
summary.fs.transform(),
transform2lps(),
transform2ras(),
transform2voxel(),
transform2world(),
write.fs.transform(),
write.fs.transform.dat(),
write.fs.transform.fslmat(),
write.fs.transform.lta(),
write.fs.transform.xfm()
Examples
xfm_file <- system.file("extdata", "talairach.xfm", package = "freesurferformats", mustWork = TRUE)
out_file <- tempfile(fileext = ".tfm")
write.fs.transform.itk(transform2lps(read.fs.transform(xfm_file)), out_file)
readLines(out_file)
unlink(out_file)
Write a FreeSurfer linear transform array (LTA) file.
Description
Write a transformation in the LTA format, which is the format FreeSurfer uses to exchange linear
transformations and that is read by mri_vol2vol, tkregister2, mri_register and lta_convert.
The file states in its header whether the matrix operates on voxel indices (type 0, LINEAR_VOX_TO_VOX) or on
RAS coordinates (type 1, LINEAR_RAS_TO_RAS), so the spaces of the transformation determine the type that is
written. The geometry of the volumes is written from the src and dst descriptors, which makes the file
self-contained: FreeSurfer can convert it to other spaces without being given the volumes again.
Usage
write.fs.transform.lta(tf, filepath)
Arguments
tf |
an |
filepath |
character string, the full path of the file to write. |
Value
the fs.transform instance tf, invisibly.
Note
The mean and sigma header entries of an LTA file describe the registration that produced the matrix
and are not used to interpret it. They are taken from the header field of tf if it has them, and are
otherwise set to the center of the source volume and to 10000.
See Also
Other header coordinate space:
invert.fs.transform(),
is.fs.transform(),
mghheader.is.ras.valid(),
mghheader.ras2vox(),
mghheader.ras2vox.tkreg(),
mghheader.scanner2tkreg(),
mghheader.tkreg2scanner(),
mghheader.vox2ras(),
mghheader.vox2ras.tkreg(),
print.fs.transform(),
read.fs.transform(),
read.fs.transform.dat(),
read.fs.transform.fslmat(),
read.fs.transform.itk(),
read.fs.transform.lta(),
read.fs.transform.xfm(),
sm0to1(),
sm1to0(),
summary.fs.transform(),
transform2lps(),
transform2ras(),
transform2voxel(),
transform2world(),
write.fs.transform(),
write.fs.transform.dat(),
write.fs.transform.fslmat(),
write.fs.transform.itk(),
write.fs.transform.xfm()
Examples
lta_file <- system.file("extdata", "talairach.lta", package = "freesurferformats", mustWork = TRUE)
tf <- read.fs.transform(lta_file)
out_file <- tempfile(fileext = ".lta")
write.fs.transform.lta(tf, out_file)
max(abs(read.fs.transform(out_file)$matrix - tf$matrix)) # 0, the matrix survives the round trip
unlink(out_file)
Write an MNI transform (xfm) file.
Description
Write a transformation in the FreeSurfer xfm format, the format of talairach.xfm files, which
store the transformation from the RAS space of a subject to the RAS space of an MNI or Talairach template.
Only the first three rows of the matrix are stored, so the transformation must be affine, and it must map RAS
coordinates to RAS coordinates.
Usage
write.fs.transform.xfm(tf, filepath, type = "Linear")
Arguments
tf |
an |
filepath |
character string, the full path of the file to write. |
type |
character string, the value of the |
Value
the fs.transform instance tf, invisibly.
See Also
Other header coordinate space:
invert.fs.transform(),
is.fs.transform(),
mghheader.is.ras.valid(),
mghheader.ras2vox(),
mghheader.ras2vox.tkreg(),
mghheader.scanner2tkreg(),
mghheader.tkreg2scanner(),
mghheader.vox2ras(),
mghheader.vox2ras.tkreg(),
print.fs.transform(),
read.fs.transform(),
read.fs.transform.dat(),
read.fs.transform.fslmat(),
read.fs.transform.itk(),
read.fs.transform.lta(),
read.fs.transform.xfm(),
sm0to1(),
sm1to0(),
summary.fs.transform(),
transform2lps(),
transform2ras(),
transform2voxel(),
transform2world(),
write.fs.transform(),
write.fs.transform.dat(),
write.fs.transform.fslmat(),
write.fs.transform.itk(),
write.fs.transform.lta()
Examples
xfm_file <- system.file("extdata", "talairach.xfm", package = "freesurferformats", mustWork = TRUE)
tf <- read.fs.transform(xfm_file)
out_file <- tempfile(fileext = ".xfm")
write.fs.transform.xfm(tf, out_file)
max(abs(read.fs.transform(out_file)$matrix - tf$matrix)) # 0
unlink(out_file)
Write an fs.volume instance to a file in MGH, MGZ or NIFTI v1 format.
Description
Write brain volume data to a file. The format is determined from the file extension of filepath.
Usage
write.fs.volume(filepath, fs_vol)
Arguments
filepath |
string. Full path to the output file. The file extension determines the format: '.mgh' or '.mgz' for FreeSurfer MGH/MGZ format, '.nii' or '.nii.gz' for NIFTI v1 format, and '.hdr', '.img', '.hdr.gz' or '.img.gz' for a NIFTI v1 pair, i.e. a header file with a separate data file. A pair is written instead of a plain ANALYZE 7.5 file because ANALYZE cannot store the geometry of the volume, see |
fs_vol |
an |
Note
When writing NIFTI files, this function uses nii1header.for.mgh to compute a NIFTI v1 header from the MGH header information.
A file name that is one of the standard CIFTI-2 names (e.g. .dscalar.nii) is an
error: such a file has to contain the CIFTI XML metadata, so a NIFTI file with that
name is refused by this package and misread by other software. Use
write.cifti for CIFTI-2 files.
Examples
## Not run:
mgh_file <- system.file("extdata", "brain.mgz",
package = "freesurferformats",
mustWork = TRUE
)
fs_vol <- read.fs.volume(mgh_file, with_header = TRUE)
write.fs.volume(tempfile(fileext = ".mgz"), fs_vol)
write.fs.volume(tempfile(fileext = ".nii.gz"), fs_vol)
write.fs.volume(tempfile(fileext = ".hdr"), fs_vol)
## End(Not run)
Write file in FreeSurfer weight format
Description
Write vertex-wise brain data for a set of vertices to file in weight format. This format is also known as paint format or simply as w format.
Usage
write.fs.weight(filepath, vertex_indices, values, format = "bin")
Arguments
filepath |
string. Full path to the output weight file. |
vertex_indices |
vector of integers, the vertex indices. Must be one-based (R-style). This function will substract 1, as they need to be stored zero-based in the file. |
values |
vector of floats. The brain morphometry data to write, one value per vertex. |
format |
character string, one of 'bin' or 'asc'. The weight format type, there is a binary version of the format and an ASCII version. |
See Also
Other morphometry functions:
fs.get.morph.file.ext.for.format(),
fs.get.morph.file.format.from.filename(),
read.fs.curv(),
read.fs.mgh(),
read.fs.morph(),
read.fs.morph.gii(),
read.fs.volume(),
read.fs.weight(),
write.fs.curv(),
write.fs.label.gii(),
write.fs.mgh(),
write.fs.morph(),
write.fs.morph.asc(),
write.fs.morph.gii(),
write.fs.morph.ni1(),
write.fs.morph.ni2(),
write.fs.morph.smp(),
write.fs.morph.txt(),
write.fs.weight.asc()
Write file in FreeSurfer weight ASCII format
Description
Write vertex-wise brain data for a set of vertices to an ASCII file in weight format. This format is also known as paint format or simply as w format.
Usage
write.fs.weight.asc(filepath, vertex_indices, values)
Arguments
filepath |
string. Full path to the output ASCII weight file. |
vertex_indices |
vector of integers, the vertex indices. Must be one-based (R-style). This function will substract 1, as they need to be stored zero-based in the file. |
values |
vector of floats. The brain morphometry data to write, one value per vertex. |
See Also
Other morphometry functions:
fs.get.morph.file.ext.for.format(),
fs.get.morph.file.format.from.filename(),
read.fs.curv(),
read.fs.mgh(),
read.fs.morph(),
read.fs.morph.gii(),
read.fs.volume(),
read.fs.weight(),
write.fs.curv(),
write.fs.label.gii(),
write.fs.mgh(),
write.fs.morph(),
write.fs.morph.asc(),
write.fs.morph.gii(),
write.fs.morph.ni1(),
write.fs.morph.ni2(),
write.fs.morph.smp(),
write.fs.morph.txt(),
write.fs.weight()
Write the payload of an MRtrix streamlines file.
Description
Writes the concatenated per-point values of all streamlines, separated by a NaN value after every streamline, as the TCK and TSF formats require. The data are written in chunks of streamlines, so that the extra memory needed does not depend on the size of the tractogram. This is shared by the TCK and the TSF writer, which differ only in the number of values per point and in the terminator they append.
Usage
write.mrtrix.streamlines(
con,
values,
lengths,
dsize,
endian,
terminator = NULL,
chunk_tracks = 10000L
)
Arguments
con |
a connection opened in binary write mode. |
values |
numeric matrix, the concatenated per-point values of all streamlines, with one column per value (3 coordinates for the TCK format, one scalar for the TSF format). |
lengths |
integer vector, the number of points of each streamline. |
dsize |
integer, the number of bytes per value (4 or 8). |
endian |
character string, 'little' or 'big'. |
terminator |
numeric vector or NULL. If given, it is written after the last streamline (the TCK format appends a vector of Inf values, the TSF format has no terminator, so the NaN delimiter of the last streamline already ends the file). |
chunk_tracks |
integer, the number of streamlines that are converted and written at once. |
Value
the number of streamlines written, invisibly.
Write header and data to a file in NIFTI v1 format.
Description
Write header and data to a file in NIFTI v1 format.
Usage
write.nifti1(filepath, niidata, niiheader = NULL, ...)
Arguments
filepath |
the file to write. The extension should be '.nii' or '.nii.gz' for a single file NIFTI image, and
'.hdr', '.img' (optionally followed by '.gz') for a NIFTI v1 pair, i.e. a header file with the voxel data in a
separate '.img' file. Which of the two is written follows from the |
niidata |
array of numeric or integer data, with up to 7 dimensions. Will be written to the file with the datatype and bitpix specified in the 'niiheader' argument. Set to |
niiheader |
an optional NIFTI v1 header that is suitable for the passed 'niidata'. If not given, one will be generated with |
... |
additional parameters passed to |
Value
invisible named list with the entries header (the header that was written) and data (the data that
was written, or NULL if no data was passed).
See Also
Other nifti1 writers:
nii1header.for.mgh(),
write.fs.morph.ni1()
Examples
# A single file NIFTI image (the default):
data <- array(1:24, dim = c(4, 3, 2))
nii_file <- tempfile(fileext = ".nii")
write.nifti1(nii_file, data)
# A NIFTI v1 pair, i.e. a header plus a separate data file. Ask for a pair
# header by passing 'pair = TRUE' (this is passed on to the header generator):
write.nifti1(tempfile(fileext = ".hdr"), data, pair = TRUE)
# The NIFTI v1 pair files can be read back with the volume reader:
hdr_file <- tempfile(fileext = ".hdr")
write.nifti1(hdr_file, data, pair = TRUE)
vol <- read.fs.volume(hdr_file, with_header = TRUE)
print(dim(vol$data))
Write the voxel data of a NIFTI v1 file to a connection.
Description
Write the voxel data of a NIFTI v1 file to a connection.
Usage
write.nifti1.data.internal(fh, niidata, niiheader)
Arguments
fh |
connection to write to. |
niidata |
array of numeric data, or |
niiheader |
named list, a valid NIFTI v1 header that describes the data. |
Value
the data that was written, after conversion to the data type stated in the header, or NULL if niidata
was NULL.
Write the 348 byte NIFTI v1 header (and the padding up to the data offset) to a connection.
Description
Write the 348 byte NIFTI v1 header (and the padding up to the data offset) to a connection.
Usage
write.nifti1.header.internal(fh, niiheader)
Arguments
fh |
connection to write to. |
niiheader |
named list, a valid NIFTI v1 header. |
Value
invisible NULL, called for the side effect of writing to the connection.
Write header and data to a file in NIFTI v2 format.
Description
Write header and data to a file in NIFTI v2 format.
Usage
write.nifti2(filepath, niidata, niiheader = NULL, extensions = NULL)
Arguments
filepath |
the file to write. The extension should be '.nii' or '.nii.gz'. |
niidata |
array of numeric or integer data, with up to 7 dimensions. Will be written to the file with the datatype and bitpix specified in the 'niiheader' argument. |
niiheader |
an optional NIFTI v2 header that is suitable for the passed 'niidata'. If not given, one will be generated with |
extensions |
optional list of NIFTI v2 header extensions to write between the header and the data, each
created with |
See Also
read.nifti2.header, nifti2.get.extension
Other nifti2 writers:
write.fs.morph.ni2()
Write a brainvoyager SMP file.
Description
Write a brainvoyager SMP file, which contains one or more vertex-wise data maps (stats or morphometry data).
Usage
write.smp.brainvoyager(filepath, bvsmp, smp_version = 3L)
Arguments
filepath |
character string, the output file |
bvsmp |
bvsmp instance, a named list as returned by |
smp_version |
integer, the SMP file format version to use when writing. Versions 2 to 5 are supported, but only versions 2 and 3 have been tested properly. Please report any problems you encounter. When converting between file versions (e.g., loading a v2 file and saving the result as a v5 file), some required fields may be missing, and for those without a default value according to the official spec, you will have to manually add the value you want in the bvsmp object before writing. |
See Also
Write a brainvoyager v2 SMP file.
Description
Write a brainvoyager v2 SMP file.
Usage
write.smp.brainvoyager.v2(filepath, bvsmp)
Arguments
filepath |
character string, the output file |
bvsmp |
bvsmp instance, a named list as returned by |
Note
Called by write.smp.brainvoyager.
The map_type and num_lags of the first vertex map will be used for the top header,i.e., for all maps. The v2 format does not support per-map settings for these values. Also min_alg, max_lag and cc_overlay are ignored.
Write a brainvoyager v3, v4 or v5 SMP file.
Description
Write a brainvoyager v3, v4 or v5 SMP file.
Usage
write.smp.brainvoyager.v3or4or5(filepath, bvsmp, smp_version)
Arguments
filepath |
character string, the output file |
bvsmp |
bvsmp instance, a named list as returned by |
smp_version |
integer, the SMP file format version to use when writing. Versions 2 to 5 are supported, but only versions 2 and 3 have been tested properly. Please report any problems you encounter. When converting between file versions (e.g., loading a v2 file and saving the result as a v5 file), some required fields may be missing, and for those without a default value according to the official spec, you will have to manually add the value you want in the bvsmp object before writing. |
Note
Called by write.smp.brainvoyager.
Write the sections of a triangular mesh in ASCII STL format.
Description
Writes the 'solid' block of the ASCII variant of the STL format,
with 7 lines per face ('facet normal', 'outer loop', 3 'vertex' lines,
'endloop', 'endfacet'). This is the layout that
read.fs.surface.stl.ascii and other STL readers expect.
Usage
write.stl.ascii(con, vertex_coords, faces, face_normals, solid_name = "mesh")
Arguments
con |
a connection opened in binary write mode, the file is written as text through it. |
vertex_coords |
n x 3 matrix of doubles, the vertex coordinates. |
faces |
n x 3 matrix of integers, the vertex indices of the triangles. |
face_normals |
n x 3 matrix of doubles, the normals of the faces, see
|
solid_name |
character string, the name of the mesh. |
Value
NULL, invisibly. The data are written to con.
Write the sections of a triangular mesh in binary STL format.
Description
Writes the binary variant of the STL format: an 80 byte header, a 4 byte face count, and then 50 bytes per face (3 float32 values for the face normal, 9 float32 values for the 3 vertex coordinates, and a zero uint16 attribute byte count). All values are little endian, as the format requires. Note that the header must not start with the string 'solid', which is how readers tell the ASCII and the binary variant apart.
Usage
write.stl.binary(con, vertex_coords, faces, face_normals)
Arguments
con |
a connection opened in binary write mode, the file is written as text through it. |
vertex_coords |
n x 3 matrix of doubles, the vertex coordinates. |
faces |
n x 3 matrix of integers, the vertex indices of the triangles. |
face_normals |
n x 3 matrix of doubles, the normals of the faces, see
|
Value
NULL, invisibly. The data are written to con.
Write the 1000 byte header of a TRK file.
Description
Write the 1000 byte header of a TRK file.
Usage
write.trk.header(con, header, num_tracks, endian)
Arguments
con |
a connection opened in binary write mode. |
header |
named list, the header fields to write. Missing fields get defaults. |
num_tracks |
integer, the value for the 'n_count' field. |
endian |
character string, 'little' or 'big'. |
Value
NULL, invisibly. The header is written to con.
Create XML GIFTI metadata node.
Description
Create XML GIFTI metadata node.
Usage
xml_node_gifti_MD(name, value, as_cdata = TRUE)
Arguments
name |
character string, the metadata name |
value |
character string, the metadata value |
as_cdata |
logical, whether to wrap the value in cdata tags |
Value
XML tree from xml2
Note
This creates an MD note, not the outer MetaData node.
Create XML GIFTI CoordinateSystemTransformMatrix node.
Description
Create XML GIFTI CoordinateSystemTransformMatrix node.
Usage
xml_node_gifti_coordtransform(
transform_matrix,
data_space = "NIFTI_XFORM_UNKNOWN",
transformed_space = "NIFTI_XFORM_UNKNOWN",
as_cdata = TRUE
)
Arguments
transform_matrix |
numerical 4x4 matrix, the transformation matrix from 'data_space' to 'transformed_space'. |
data_space |
character string, the space used by the data before transformation. |
transformed_space |
character string, the space reached after application of the transformation matrix. |
as_cdata |
logical, whether to wrap text attributes ('data_space' and 'transformed_space') in cdata tags. |
Value
XML node from xml2
Create XML GIFTI Label node.
Description
Create XML GIFTI Label node.
Usage
xml_node_gifti_label(value, attributes = list(), as_cdata = TRUE)
Arguments
value |
the text contents of the node, usually the region name |
attributes |
named list, the attributes |
as_cdata |
logical, whether to wrap the value in cdata tags |
Value
XML node from xml2
Create XML GIFTI LabelTable node.
Description
Create XML GIFTI LabelTable node.
Usage
xml_node_gifti_label_table(attributes = list())
Value
XML node from xml2
Compute LabelTable node from annotation.
Description
Compute LabelTable node from annotation.
Usage
xml_node_gifti_label_table_from_annot(annot)
Arguments
annot |
an fs.annotation, the included data will be used to compute the LabelTable node |
Value
XML tree from xml2, the LabelTable and its child nodes