--- title: "Getting started with fiber" description: | A practical introduction to the fiber package: the streamline, bundle, and bundle_set classes, shape descriptors, reparametrization, and the Hausdorff distance. vignette: > %\VignetteIndexEntry{Getting started with fiber} %\VignetteEngine{quarto::html} %\VignetteEncoding{UTF-8} knitr: opts_chunk: collapse: true comment: '#>' --- ```{r} #| label: setup #| include: false if (!requireNamespace("fiber", quietly = TRUE)) { # R CMD check re-builds vignette outputs in a fresh R process where the # just-installed package is not always on the library path (seen on Windows). # Skip the executable chunks rather than fail the build in that case. knitr::opts_chunk$set(eval = FALSE) } else { library(fiber) } # The dti package (a Suggests) pulls in rgl on load; in headless environments # rgl cannot open a display and emits a warning ('rgl.init' failed / X11 error). # That warning concerns rgl's graphics, not fiber, so we route rgl to its null # device to keep the coercion example below clean. Sys.setenv(RGL_USE_NULL = "true") ``` The **fiber** package provides three [S7](https://rconsortium.github.io/S7/) classes for representing diffusion MRI tractography data in R: | Class | Represents | |--------------|-------------------------------------------------------| | `streamline` | A single fibre tract (a polyline of 3-D points). | | `bundle` | A collection of streamlines (a tractogram / bundle). | | `bundle_set` | A collection of bundles (white-matter bundles of a subject, or across subjects / sessions). | Together they let you store geometry, per-point and per-streamline attributes (e.g. fractional anisotropy), and per-bundle or per-set metadata, and they come with a concise set of tools for computing shape descriptors, resampling onto uniform grids, computing the Hausdorff distance, and coercing to and from the `dwiFiber` S4 class of the [dti](https://cran.r-project.org/package=dti) package. This vignette walks through the core workflow. A companion, technical [vignette](fiber-api.qmd) (`fiber-api`) describes the complete API in detail. ## Building a streamline A `streamline` stores a `$P \times 3$` matrix of coordinates. The columns must be named `"X"`, `"Y"`, and `"Z"`. ```{r} # A helix in 3-D, sampled at 50 points t <- seq(0, 2 * pi, length.out = 50) sl <- streamline( points = cbind(X = cos(t), Y = sin(t), Z = t / (2 * pi)) ) sl ``` You can attach per-point attributes (e.g. fractional anisotropy) via `point_data` and per-streamline scalars (e.g. a mean FA or a label) via `streamline_data`: ```{r} sl <- streamline( points = cbind(X = cos(t), Y = sin(t), Z = t / (2 * pi)), point_data = list(FA = runif(50)), streamline_data = list(mean_FA = mean(runif(50)), label = "helix") ) sl@n_points # 50 sl@point_attributes # "FA" sl@streamline_attributes # c("mean_FA", "label") ``` ## Shape descriptors Functions like `get_curvilinear_length()`, `get_sinuosity()`, and `get_euclidean_length()` compute scalar shape descriptors from the geometry: ```{r} get_curvilinear_length(sl) get_sinuosity(sl) ``` `get_curvature()` and `get_torsion()` return a per-point profile along the arc-length abscissa: ```{r} head(get_curvature(sl)) ``` `add_shape_descriptors()` attaches several descriptors to an object at once. Scalar descriptors land in `@streamline_data`; per-point ones (`curvature`, `torsion`) land in `@point_data`: ```{r} sl2 <- add_shape_descriptors(sl) sl2@streamline_data$euclidean_length head(sl2@point_data$curvature) ``` ## Bundling streamlines Wrap a list of `streamline`s in a `bundle`. Any `@streamline_data` keys common to **all** streamlines are lifted automatically into `bundle@streamline_data` as length-`S` vectors: ```{r} sl_a <- streamline(points = cbind(X = cos(t), Y = sin(t), Z = t / (2 * pi))) sl_b <- streamline( points = cbind(X = 1.1 * cos(t), Y = 1.1 * sin(t), Z = t / (2 * pi)) ) b <- bundle(streamlines = list(sl_a, sl_b)) b b@n_streamlines # 2 b@streamline_data$mean_FA # lifted automatically, if present ``` You can mix streamlines and bundles with `bind_bundles()`: ```{r} b2 <- bind_bundles(sl_a, b) b2@n_streamlines # 3 ``` ## Reparametrisation `reparametrize()` resamples streamlines onto a uniform arc-length grid using linear interpolation. A single streamline can be resampled to any number of points; by default a `bundle` is resampled to the rounded mean number of points across its streamlines: ```{r} sl_20 <- reparametrize(sl_a, n_points = 20L) sl_20@n_points # 20 b_20 <- reparametrize(b, n_points = 20L) b_20[[1]]@n_points # 20 b_20[[2]]@n_points # 20 ``` ## Hausdorff distance `compute_hausdorff_distance()` computes the symmetric Hausdorff distance between streamlines. Depending on the inputs, it returns a scalar, a vector, or a `dist` object: ```{r} # streamlines -> scalar compute_hausdorff_distance(sl_a, sl_b) # bundle (with no second argument) -> pairwise dist object d <- compute_hausdorff_distance(b) as.matrix(d) # bundle vs streamline -> vector compute_hausdorff_distance(b, sl_a) ``` The core pairwise computation runs in C++ (via cpp11) for speed. ## Bundle sets A `bundle_set` collects `bundle` objects. Two use cases are equally well supported: grouping the multiple white-matter bundles of a single subject, or grouping bundles across subjects / sessions. Names of the input list (like `"callosum"` or `"sub-01"`) are transferred into `bundle_set@bundle_data` as the `id_from_input_names` attribute: ```{r} # Single subject: several white-matter bundles of one subject bs_single <- bundle_set(list( callosum = bundle(list(sl_a)), arcuate = bundle(list(sl_b)) )) bs_single bs_single@n_bundles # 2 bs_single[["callosum"]] # extract one bundle (push-down) # Multi-subject: the same bundle across two subjects / sessions b_sub01 <- bundle( streamlines = list(sl_a), bundle_data = list(subject = "sub-01") ) b_sub02 <- bundle( streamlines = list(sl_b), bundle_data = list(subject = "sub-02") ) bs <- bundle_set(list("sub-01" = b_sub01, "sub-02" = b_sub02)) bs bs@bundle_data$subject # c("sub-01", "sub-02") bs[["sub-01"]] # extract one subject (push-down) ``` `bundle_set` objects also support `reparametrize()` and `add_shape_descriptors()`, which operate per bundle and preserve `@bundle_data` / `@bundle_set_data`. ## A real corpus callosum tractogram The package ships a real tractogram from the corpus callosum (`inst/extdata/CC_SingleTensor.csv`): 100 streamlines, each a sequence of 3-D points with a per-point fractional anisotropy (`FA`) value. The file reads straight into a `bundle`, grouping points by `StreamlineId` and keeping `FA` as a per-point attribute: ```{r} cc <- read.csv( system.file("extdata", "CC_SingleTensor.csv", package = "fiber"), header = TRUE ) make_streamline <- function(d) { d <- d[order(d$PointId), ] streamline( points = as.matrix(d[c("X", "Y", "Z")]), point_data = list(FA = d$FA) ) } cc_bundle <- bundle( streamlines = lapply(split(cc, cc$StreamlineId), make_streamline) ) cc_bundle@n_streamlines # 100 cc_bundle[[1]]@n_points # 150 cc_bundle[[1]]@point_attributes # "FA" range(cc_bundle[[1]]@point_data$FA) # per-point FA on the first stream ``` The `FA` per-point attribute is present on every streamline, so `FA` is a shared point attribute across the whole tractogram: `cc_bundle[[1]]@point_attributes` returns `"FA"` for each of the 100 streamlines. To summarise anisotropy per streamline, lift a scalar (e.g. per-streamline mean `FA`) into `@streamline_data`; the constructor then carries it automatically: ```{r} cc_bundle2 <- bundle( streamlines = lapply( split(cc, cc$StreamlineId), function(d) { d <- d[order(d$PointId), ] streamline( points = as.matrix(d[c("X", "Y", "Z")]), point_data = list(FA = d$FA), streamline_data = list(mean_FA = mean(d$FA)) ) } ) ) cc_bundle2@streamline_data$mean_FA mean(cc_bundle2@streamline_data$mean_FA) # mean across the 100 streamlines ``` ## Interoperability with the dti package If the [dti](https://cran.r-project.org/package=dti) package is installed, you can coerce fiber objects to and from its `dwiFiber` S4 class: ```{r} if (requireNamespace("dti", quietly = TRUE)) { dfi <- as_dwifiber(b) class(dfi) # "dwiFiber" b_back <- as_bundle(dfi) b_back@n_streamlines } ``` `as_dwifiber()` uses per-point directions stored in `@point_data` (`direction_x`, `direction_y`, `direction_z`) when present, otherwise it estimates them from the coordinates via finite differences. If dti emits an rgl warning (`'rgl.init' failed`, `X11 error`, ...) when you run the coercion above, that comes from dti loading the `rgl` package and failing to open a graphics display in your environment. It is unrelated to the fiber package — the conversion itself is unaffected. ## Further reading - The [fiber API reference](fiber-api.qmd) vignette documents every function and class in detail. - Browse the online reference at .