Track Analysis


This tutorial provides an overview of how to perform popular analysis methods and visualizations commonly applied to tracking data. Examples range from the simple analysis of speed or other measures on single tracks, to the application of step-based or staggered metrics, to the generation of autocorrelation plots and performing angle analyses.


First load the package:

library( celltrackR )
library( ggplot2 )
# Save current par() settings
oldpar <- par( no.readonly =TRUE )

The package contains a dataset of T cells imaged in a mouse peripheral lymph node using two photon microscopy. We will here use this dataset as an example of how to perform quality control.

The dataset consists of 21 tracks of individual cells in a tracks object:

str( TCells, list.len = 3 )

Each element in this list is a track from a single cell, consisting of a matrix with $(x,y,z)$ coordinates and the corresponding measurement timepoints:

head( TCells[[1]] )

Similarly, we will also use the BCells and Neutrophils data:

str( BCells, list.len = 3 )
str( Neutrophils, list.len = 3 )

1 Simple track visualization

1.1 2D and 3D plotting

The standard plotting method for tracks plots the projection of 3D tracks on the $(x,y)$ plane:

par( mfrow = c(2,2) )
plot( TCells, main = "T cells" )
plot( BCells, main = "B cells" )
plot( Neutrophils, main = "Neutrophils" )

We can also plot 3D tracks using the function plot3d() (which requires the package scatterplot3d):

par( mfrow = c(2,2) )
plot3d( TCells, main = "T cells" )
plot3d( BCells, main = "B cells" )
plot3d( Neutrophils, main = "Neutrophils" )

1.2 Star plots

Finally, we can overlay the track starting points using normalizeTracks() -- which is useful to detect directionality:

par( mfrow = c(2,2) )
plot( normalizeTracks(TCells), main = "T cells" )
plot( normalizeTracks(BCells), main = "B cells" )
plot( normalizeTracks(Neutrophils), main = "Neutrophils" )

2 Quantification of measures on tracks

The package contains several measures that can be computed on single tracks (see ?TrackMeasures for an overview). The following sections will give examples on how to compute these metrics in different ways, using the speed() function as an example.

2.1 Cell-based analyses

To compute a metric for each track in a dataset, use R's sapply() function directly on the tracks object:

# Obtain mean speeds for each track using sapply
Tcell.speeds <- sapply( TCells, speed )
str( Tcell.speeds )
summary( Tcell.speeds )

This returns a mean speed for each of the 22 tracks in the TCell dataset. Visualize the distribution:

hist( Tcell.speeds )

Now let's repeat for the other two celltypes and plot them next to each other for comparison

Bcell.speeds <- sapply( BCells, speed )
Nphil.speeds <- sapply( Neutrophils, speed )

# Create a dataframe of all data
dT <- data.frame( cells = "T cells", speed = Tcell.speeds )
dB <- data.frame( cells = "B cells", speed = Bcell.speeds )
dN <- data.frame( cells = "Neutrophils", speed = Nphil.speeds )
d <- rbind( dT, dB, dN )

# Compare:
ggplot( d, aes( x = cells, y = speed ) ) +
  ggbeeswarm::geom_quasirandom() +
  scale_y_continuous( limits = c(0,NA) ) +

2.2 Step-based analyses

It has been suggested that cell-based analyses introduce biases, and that analyses should be performed on individual "steps" from all tracks combined instead (Beltman et al (2009)).

We can extract such steps using the subtracks() function (where i is the subtrack length, which is 1 for a single step):

Tcell.steps <- subtracks( TCells, i = 1 )

We can then proceed as before to obtain speeds for each step and further summary statistics:

# Obtain instantaneous speeds for each step using sapply
Tcell.step.speeds <- sapply( Tcell.steps, speed )
str( Tcell.step.speeds )
summary( Tcell.step.speeds )

Visualize the distribution:

hist( Tcell.step.speeds )

Compare cell-based versus step-based:

d.step <- data.frame( method = "step-based", speed = Tcell.step.speeds )
d.cell <- data.frame( method = "cell-based", speed = Tcell.speeds )
d.method <- rbind( d.step, d.cell )

ggplot( d.method, aes( x = method, y = speed ) ) +
  ggbeeswarm::geom_quasirandom( size = 0.3 ) +
  scale_y_continuous( limits = c(0,NA) ) +

And again compare between the different celltypes:

Bcell.step.speeds <- sapply( subtracks(BCells,1), speed )
Nphil.step.speeds <- sapply( subtracks(Neutrophils,1), speed )

# Create a dataframe of all data
dT <- data.frame( cells = "T cells", speed = Tcell.step.speeds )
dB <- data.frame( cells = "B cells", speed = Bcell.step.speeds )
dN <- data.frame( cells = "Neutrophils", speed = Nphil.step.speeds )
dstep <- rbind( dT, dB, dN )

# Compare:
ggplot( dstep, aes( x = cells, y = speed ) ) +
  ggbeeswarm::geom_quasirandom( size = 0.3 ) +
  scale_y_continuous( limits = c(0,NA) ) +

Note that we can do something similar for turning angles, but we need at least two steps to compute a turning angle. Therefore, use subtracks() with i=2 in combination with the overallAngle() method:

Tcell.step.angle <- sapply( subtracks(TCells,2), overallAngle )
Bcell.step.angle <- sapply( subtracks(BCells,2), overallAngle )
Nphil.step.angle <- sapply( subtracks(Neutrophils,2), overallAngle )

# Create a dataframe of all data
dT <- data.frame( cells = "T cells", turn.angle = Tcell.step.angle )
dB <- data.frame( cells = "B cells", turn.angle = Bcell.step.angle )
dN <- data.frame( cells = "Neutrophils", turn.angle = Nphil.step.angle )
dangle <- rbind( dT, dB, dN )

# convert radians to degrees
dangle$turn.angle <- pracma::rad2deg( dangle$turn.angle )

# Compare:
ggplot( dangle, aes( x = cells, y = turn.angle ) ) +
  ggbeeswarm::geom_quasirandom( size = 0.3 ) +
  scale_y_continuous( limits = c(0,NA) ) +

2.3 Staggered analyses

Another approach is to compute metrics not only on "steps" (subtracks of length one), but on all possible subtracks in a track. This is called a "staggered" analysis (Mohktari et al (2013)).

To see how this works on a single track, use applyStaggered with matrix=TRUE. For example, consider track number 8 in the TCells data, which has 8 coordinates (7 steps):

x <- TCells[[8]]

If we compute the speed on all staggered subtracks, we get the following matrix:

stag <- applyStaggered( x, speed, matrix = TRUE )

Where point $(i,j)$ contains the mean speed in the subtrack from the $i^{th}$ to the $j^{th}$ coordinate (thus, the diagonal contains subtracks from a coordinate to itself -- which is no subtrack at all but a single coordinate, and therefore has no speed). Visualize this using the image() or filled.contour() functions:

image( stag )
filled.contour( stag )

Now do it again for a longer track:

filled.contour( applyStaggered( TCells[[3]], speed, matrix = TRUE ) )

This nicely illustrates fluctuations in speed at different points in the track.

If we leave out the matrix=TRUE, the function simply returns the mean of all non-NA entries in the matrix:

# These are the same:
applyStaggered( TCells[[8]], speed )
mean( stag, na.rm = TRUE )

applyStaggered only works on a single track, not a tracks object. To directly get the staggered means for all tracks in the object, use the staggered option:

# Compare the three different methods
Tcell.stag.speed <- sapply( TCells, staggered( speed ) )
d.staggered <- data.frame( method = "staggered", speed = Tcell.speeds )
d.method <- rbind( d.step, d.cell, d.staggered )

ggplot( d.method, aes( x = method, y = speed ) ) +
  ggbeeswarm::geom_quasirandom( size = 0.3 ) +
  scale_y_continuous( limits = c(0,NA) ) +

# cell-based and staggered cell-based are slightly different:
hist( Tcell.speeds - Tcell.stag.speed )

3 Mean square displacement plots

A common analysis on migration data is generating mean square displacement (MSD) plots. For a range of time interval $\Delta t$, we compute the average squared displacement of all subtracks with that duration. Like with step-based approaches, we compute the metric on subtracks pooled from all individual cells -- but now we also do this for subtracks of more than one step.

We can use the subtracks() function with varying i argument to obtain subtracks of different lengths, and then use sapply() to find a mean metric for each of these datasets. However, the package also contains a convenience function that does this automatically: aggregate(). For example, use this function to directly get the mean square displacement of all single steps:

aggregate( TCells, squareDisplacement, subtrack.length = 1 )

where "i" is the subtrack length in number of steps, and "value" is the average value of the applied metric (in this case, square displacement) for all subtracks of that length in the data.

We can also report different summary statistics by changing the FUN argument (see ?aggregate.tracks):

aggregate( TCells, squareDisplacement, subtrack.length = 1, FUN = "" )

This gives us not only the mean, but also the standard error.

Now, if we leave out the subtrack.length, aggregate() automatically computes the metric for subtracks of all possible lengths in the dataset and returns those in a dataframe: <- aggregate( TCells, squareDisplacement, FUN = "" )
str( )

We can then use this for plotting:

ggplot(, aes( x = i, y = mean ) ) +
  geom_ribbon( aes( ymin = lower, ymax = upper) , alpha = 0.2 ,color=NA ) +
  geom_line( ) +
  labs( x = expression( paste(Delta,"t (steps)") ),
        y = "mean square displacement") +

Plotting the standard error is useful because, as $\Delta t$ increases, the number of subtracks with that length decreases rapidly. MSD values at the high end of the plot therefore tend to be less reliable as they are based on very few observations.

Compare for example the number of subtracks of length 10 to the number of length 35:

num10 <- length( subtracks( TCells, 10 ) )
num35 <- length( subtracks( TCells, 35 ) )
c( "10" = num10, "35" = num35 )

Now, let's compare the MSD plot for the three different types of cells:

# Combine into a single dataframe with one column indicating the celltype
# To truly compare them, report subtrack length not in number of steps but
# in their duration (which may differ between different datasets)$cells <- "T cells"$dt <-$i * timeStep( TCells ) <- aggregate( BCells, squareDisplacement, FUN = "" )$cells <- "B cells"$dt <-$i * timeStep( BCells ) <- aggregate( Neutrophils, squareDisplacement, FUN = "" )$cells <- "Neutrophils"$dt <-$i * timeStep( Neutrophils )
msddata <- rbind(,, )

# Plot
p1 <- ggplot( msddata, aes( x = dt , y = mean, color = cells, fill = cells ) ) +
  geom_ribbon( aes( ymin = lower, ymax = upper) , alpha = 0.2 ,color=NA ) +
  geom_line( ) +
  labs( x = expression( paste(Delta,"t (seconds)") ),
        y = "mean square displacement") +
# Also make a zoomed version to look only at first part of the plot
pzoom <- p1 + coord_cartesian( xlim = c(0,500), ylim = c(0,5000) ) 
gridExtra::grid.arrange( p1, pzoom, ncol = 2 ) 

Note that aggregate() can also make MSD plots from non-overlapping subtracks or from subtracks starting at the first position of each track; see ?aggregate.tracks for details.

4 Analyzing persistence

The downside of the MSD plot is that it is strongly affected by both speed and directionality of cells: faster cells displace more, as do cells that move straighter. It can therefore be worthwile to study cell speed and straightness or "persistence" independently.

4.1 Straightness metrics

The package implements several metrics that provide a measure of track straightness or directionality (see Mohktari et al (2013) for details): displacementRatio(), outreachRatio, straightness(), and asphericity(). These metrics can be applied to the data in the same way as was done for speed() in section 2 of this tutorial. See also ?TrackMeasures for more information.

4.2 Autocorrelation plots

To analyze cell persistence, another good analysis is the autocorrelation plot: taking steps with $\Delta t$ time in between, how much do their directions of movement still correlate?

Officially, the autocorrelation plot is a plot of $\cos \alpha$ of two steps, $\vec{s_1}$ and $\vec{s_2}$, whose starting points are $\Delta t$ apart. This is equal to the dot product between $\vec{s_1}$ and $\vec{s_2}$ after normalizing both vectors to unit length. We can compute this again using aggregate() (see also the previous section):

Tcell.acor <- aggregate( TCells, overallNormDot, FUN = ""  )
Tcell.acor$dt <- Tcell.acor$i * timeStep(TCells)
Tcell.acor$cells <- "T cells"

ggplot( Tcell.acor, aes( x = dt , y = mean, color = cells, fill = cells ) ) +
  geom_hline( yintercept = 0 ) +
  geom_ribbon( aes( ymin = lower, ymax = upper) , alpha = 0.2 ,color=NA ) +
  geom_line( ) +
  labs( x = expression( paste(Delta,"t (seconds)") ),
        y = expression(cos(alpha))) +
  theme_classic() + 
  theme( axis.line.x = element_blank() )

Note, however, that steps in which the cell barely moves can add a lot of noise to the analysis of angles. Since it makes no sense anyway to speak of persistent movement when a cell is not moving, we can avoid this by filtering for pairs of steps $\vec{s_1}$ and $\vec{s_2}$ that have at least some minimum displacement. To do this, we give aggregate() a function in the filter.subtracks argument:

# Returns TRUE if first and last step of a track are of the minimum length of 1 micron
check <- function(x){ 
  all( sapply( list(head(x,2),tail(x,2)), trackLength ) >= 1.0 )
# repeat analysis
Tcell.acor2 <- aggregate( TCells, overallNormDot, 
                     FUN = "", filter.subtracks = check )
Tcell.acor2$dt <- Tcell.acor2$i * timeStep(TCells)
Tcell.acor2$cells <- "T cells (filtered)"

d <- rbind( Tcell.acor, Tcell.acor2 )

# compare
ggplot( d, aes( x = dt , y = mean, color = cells, fill = cells ) ) +
  geom_hline( yintercept = 0 ) +
  geom_line( ) +
  labs( x = expression( paste(Delta,"t (seconds)") ),
        y = expression(cos(alpha))) +
  theme_classic() + 
  theme( axis.line.x = element_blank() )

The drop in autocorrelation is now slightly less steep, because the lack of correlation between steps where the cell does not move is not taken into account.

Another solution is to make the autocovariance plot instead of the autocorrelation plot, where we plot the dot product between the original unnormalized vectors $\vec{s_1} \bullet \vec{s_2}$ instead of normalizing them fist. The dot product is less sensitive to noise from very short steps and is therefore recommended:

# autocovariance
Tcell.acov <- aggregate( TCells, overallDot, 
                     FUN = "" )
Tcell.acov$dt <- Tcell.acov$i * timeStep(TCells)
Tcell.acov$cells <- "T cells"

# compare
ggplot( Tcell.acov, aes( x = dt , y = mean, color = cells, fill = cells ) ) +
  geom_hline( yintercept = 0 ) +
  geom_line( ) +
  labs( x = expression( paste(Delta,"t (seconds)") ),
        y = "autocovariance" ) +
  theme_classic() + 
  theme( axis.line.x = element_blank() )

However, the autocovariance is no longer a number between 0 and 1, which is somewhat less convenient when comparing cell types moving at different speeds. We therefore divide all values by the maximum autocovariance at $\Delta t = 0$, and compare with the other celltypes:

# Normalized autocovariance
Tcell.acov[,2:4] <- Tcell.acov[,2:4] / Tcell.acov$mean[1]

# Other cells
Bcell.acov <- aggregate( BCells, overallDot, FUN = "" )
Bcell.acov$cells <- "B cells"
Bcell.acov$dt <- Bcell.acov$i * timeStep( BCells )
Bcell.acov[,2:4] <- Bcell.acov[,2:4] / Bcell.acov$mean[1]

Nphil.acov <- aggregate( Neutrophils, overallDot, FUN = "" )
Nphil.acov$cells <- "Neutrophils"
Nphil.acov$dt <- Nphil.acov$i * timeStep( Neutrophils )
Nphil.acov[,2:4] <- Nphil.acov[,2:4] / Nphil.acov$mean[1]

acovdata <- rbind( Tcell.acov, Bcell.acov, Nphil.acov )

# compare
p1 <- ggplot( acovdata, aes( x = dt , y = mean, color = cells, fill = cells ) ) +
  geom_hline( yintercept = 0 ) +
  geom_ribbon( aes( ymin = lower, ymax = upper) , alpha = 0.2 ,color=NA ) +
  geom_line( ) +
  labs( x = expression( paste(Delta,"t (seconds)") ),
        y = "autocovariance" ) +
  theme_classic() + 
  theme( axis.line.x = element_blank() )

pzoom <- p1 + coord_cartesian( xlim = c(0,500) )
gridExtra::grid.arrange( p1, pzoom, ncol = 2 )

B cells lose their autocovariance most rapidly, making them the least persistent. Neutrophils maintain directional persistence over longer timescales.

5 Analyzing directionality

Aside from directionality within a track segment (because of directional persistence), there can also be global directionality between different tracks: for example, when cells are moving in the direction of some target. The package supports several types of analyses to detect such directionality in a dataset.

5.1 Hotelling's test

An unbiased method for detecting global directionality is Hotelling's T-square test (see Textor et al (2011)), which tests if the mean step displacement vector is significantly different from the null vector. This method is powerful for detecting global movement biases when the direction is not known in advance.

For example, applying Hotelling's test to the Neutrophil data:

par( mfrow=c(1,2) )
plot( Neutrophils )
hotellingsTest( Neutrophils, plot = TRUE, step.spacing = 3 )

This shows there is a bias towards movement in the positive $y$ direction. See the discussion of tissue drift in the vignette on quality control for a more extensive discussion on how to use Hotelling's test to detect a global directional bias.

5.2 Angle analyses

5.2.1 Overview: Angles and distances of steps to a fixed reference (point, plane, or direction)

The following functions support the computation of angles and distances of steps compared to a fixed reference:

These functions take each track in tracks object x, extract the single steps starting at index from (by default, this is the first step in the track), and compute the angle of this step towards the reference. The distance functions compute the distance of the step starting point to the reference.

5.2.2 Angles and distances to planes: detecting tracking artefacts

Angles and distances in reference to a plane are useful to detect tracking artefacts, see the vignette on quality control for a detailed example.

5.2.3 Angle to a reference direction: powerful directionality tests when direction is known

While Hotelling's test may be used to test for directionality in an unknown direction, we can increase the power of testing when the direction is known (for example, in an experiment with an artificial chemotactic gradient in a known direction).

As an example, let's make an artificial dataset with additional movement in the direction $(1,1,1)$:

# Directional movement is 0.05 micron/sec in each dimension
directional.speed <- c( 0.05, 0.05, 0.05 )
add.dir <- function( x, speed.vector )
  # separate timepoints and coordinates
  tvec <- x[,1]
  coords <- x[,-1]

  # compute movement due to drift.
  speed.matrix <- matrix( rep( speed.vector, nrow(coords) ),
                          ncol = ncol(coords), byrow= TRUE )
  speed.matrix <- speed.matrix * tvec

  # Add drift to coordinates
  x[,-1] <- coords + speed.matrix

# Create data with directionality
TCells.dir <- as.tracks( lapply( TCells, add.dir, directional.speed ) )

# Plot both for comparison
par(mfrow=c(1,2) )
plot(TCells, main = "original data" )
plot(TCells.dir, main = "with directional bias" )

Now, let's view the distribution of step angles with the reference direction, and compare this to the original data:

step.angles <- sapply( subtracks( TCells.dir, 1), angleToDir, dvec = c(1,1,1) )
step.angles.original <- sapply( subtracks( TCells, 1 ), angleToDir, dvec = c(1,1,1) )
par(mfrow=c(1,2) )
hist( step.angles.original, main = "original data" )
hist( step.angles, main = "with directional bias" )

In the original dataset, angles to the reference direction form a sine distribution with a mean of 90 degrees -- which is what we expect for 3D angles with a reference when there is no directional bias. But in the artificial dataset, there is an enrichment for angles below 90 degrees, indicative of a directional bias.

5.2.4 Angles and distances to reference point: detecting movement towards a single point

Sometimes a directional bias is not in a fixed direction, but towards a fixed point. The direction of the bias then depends on the location a cell is in.

As an extreme example, let's make an artificial dataset by normalizing all T cell tracks so that they end at the same endpoint:

# Normalize the endpoint by subtracting its coordinates from all other coordinates:
normalize.endpoint <- function( x ){
  coords <- x[,-1]
  coords.norm <- t( apply( coords, 1, function(a) a - coords[nrow(coords),] ) )
  x[,-1] <- coords.norm
TCells.point <- as.tracks( lapply( TCells, normalize.endpoint ) )

# Plot for comparison:
par( mfrow = c(1,2) )
plot( TCells, main = "original data" )
plot( TCells.point, main = "with point attraction" )

Hotelling's test cannot detect this bias, because the direction of the bias depends on where the track started:

hotellingsTest( TCells.point, plot = TRUE, step.spacing = 3 )

Now, given that we know in which direction we expect the cells to move (towards point $(0,0,0)$), we can again use angle analysis to compute the step angles towards the central point:

step.angles <- sapply( subtracks( TCells.point, 1), angleToPoint, p = c(1,1,1) )
step.angles.original <- sapply( subtracks( TCells, 1 ), angleToPoint, p = c(1,1,1) )
par(mfrow=c(1,2) )
hist( step.angles.original, main = "original data" )
hist( step.angles, main = "with point attraction" )

Once again, there is an significant enrichment for small angles.

We can also plot the angle versus the distance to the point:

step.distances <- sapply( subtracks( TCells.point, 1), distanceToPoint, p = c(1,1,1) )

df <- data.frame( dist = step.distances,
                  angles = step.angles )
ggplot( df, aes( x = dist, y = angles ) ) +
  geom_point() +
  geom_hline( yintercept = 90, color = "red" ) +
  stat_smooth( color = "black", method = "loess" ) +
  labs( x = "distance to reference point",
        y = "angle to reference point" ) +

In our artificial dataset, the average angle is below 90 degrees for any distance. But in case of true attraction towards a given point, we might expect the attraction to decrease as the distance to the point increases (for example, because cells at large distances do not feel the chemotactic gradient as much).

5.2.5 Angles and distances between pairs of cells or individual steps

Analyze angles and distances between pairs of cells:

df.cells <- analyzeCellPairs( TCells )

# Plot
ggplot( df.cells, aes( x = dist, y = angle ) ) +
  geom_point( color = "gray40" ) +
  stat_smooth( span = 1, color = "black" )+
  labs( x = "distance between cell pairs",
        y = "angle between cell pairs" ) +
  geom_hline( yintercept = 90, color = "red" ) +

We expect angles between cell pairs to be on average 90 degrees. A lower average angle for cell pairs at low distances may indicate the formation of cell streams and collective migration. A systematic deviation from the 90 degree mean may indicate global directionality in the data.

We can do something similar on the level of single steps (where we take into account only pairs of steps that occur at the same time point, and we filter for steps that displace at least two micron):

df.steps <- analyzeStepPairs( TCells, filter.steps = function(x) displacement(x)>2  )

# Plot
ggplot( df.steps, aes( x = dist, y = angle ) ) +
  geom_point( color = "gray40", size = 0.5 ) +
  stat_smooth( color = "black" )+
  labs( x = "distance between step pairs",
        y = "angle between step pairs") +
  geom_hline( yintercept = 90, color = "red" ) +

Again, we expect to see an average angle of 90 degrees for all distances. See also the vignette on quality control.

# Reset par() settings

Try the celltrackR package in your browser

Any scripts or data that you put into this service are public.

celltrackR documentation built on April 14, 2020, 6:42 p.m.