Title: | Animal Trajectory Analysis |
---|---|
Description: | A toolbox to assist with statistical analysis of animal trajectories. It provides simple access to algorithms for calculating and assessing a variety of characteristics such as speed and acceleration, as well as multiple measures of straightness or tortuosity. Some support is provided for 3-dimensional trajectories. McLean & Skowron Volponi (2018) <doi:10.1111/eth.12739>. |
Authors: | Jim McLean [aut, cre] |
Maintainer: | Jim McLean <[email protected]> |
License: | MIT + file LICENSE |
Version: | 1.5.1.9000 |
Built: | 2025-02-26 05:17:22 UTC |
Source: | https://github.com/jimmcl/trajr |
The lines
method for Trajectory objects.
## S3 method for class 'Trajectory' lines( x, draw.start.pt = TRUE, start.pt.cex = 0.8, start.pt.pch = 16, start.pt.col = "black", turning.angles = NULL, ... )
## S3 method for class 'Trajectory' lines( x, draw.start.pt = TRUE, start.pt.cex = 0.8, start.pt.pch = 16, start.pt.col = "black", turning.angles = NULL, ... )
x |
An object of class "Trajectory", the trajectory to be plotted. |
draw.start.pt |
If TRUE, draws a dot at the start point of the trajectory. |
start.pt.cex |
Scale to apply when drawing the start point dot. |
start.pt.pch |
Pch (i.e. plot character, symbol or shape) to apply when drawing the start point dot. |
start.pt.col |
Colour to apply when drawing the start point dot. |
turning.angles |
If |
... |
Additional arguments are passed to |
The plot
method for TrajDirectionAutocorrelations
objects.
Plots the direction autocorrelation function as returned by a call to
TrajDirectionAutocorrelations
, with a optional dot at the first
local minimum.
## S3 method for class 'TrajDirectionAutocorrelations' plot( x, firstMinWindowSize = 10, type = "l", ylab = expression("C(" * Delta * s * ")"), xlab = expression(Delta * s), ... )
## S3 method for class 'TrajDirectionAutocorrelations' plot( x, firstMinWindowSize = 10, type = "l", ylab = expression("C(" * Delta * s * ")"), xlab = expression(Delta * s), ... )
x |
Trajectory to be plotted. |
firstMinWindowSize |
If not NULL, specifies a window size used to calculate the first local minimum, which is then plotted as a point. |
type , xlab , ylab
|
Defaults for plotting. |
... |
Additional arguments passed to |
The plot
method for Trajectory objects.
## S3 method for class 'Trajectory' plot( x, add = FALSE, draw.start.pt = TRUE, start.pt.cex = 0.8, start.pt.pch = 16, start.pt.col = "black", turning.angles = NULL, xlim = grDevices::extendrange(x$x), ylim = grDevices::extendrange(x$y), xlab = ifelse(is.null(TrajGetUnits(x)), "x", sprintf("x (%s)", TrajGetUnits(x))), ylab = ifelse(is.null(TrajGetUnits(x)), "y", sprintf("y (%s)", TrajGetUnits(x))), ann = graphics::par("ann"), axes = TRUE, frame.plot = axes, asp = 1, ... )
## S3 method for class 'Trajectory' plot( x, add = FALSE, draw.start.pt = TRUE, start.pt.cex = 0.8, start.pt.pch = 16, start.pt.col = "black", turning.angles = NULL, xlim = grDevices::extendrange(x$x), ylim = grDevices::extendrange(x$y), xlab = ifelse(is.null(TrajGetUnits(x)), "x", sprintf("x (%s)", TrajGetUnits(x))), ylab = ifelse(is.null(TrajGetUnits(x)), "y", sprintf("y (%s)", TrajGetUnits(x))), ann = graphics::par("ann"), axes = TRUE, frame.plot = axes, asp = 1, ... )
x |
An object of class "Trajectory", the trajectory to be plotted. |
add |
If TRUE, the trajectory is added to the current plot. |
draw.start.pt |
If TRUE, draws a dot at the start point of the trajectory. |
start.pt.cex |
Scale to apply when drawing the start point dot. |
start.pt.pch |
Pch (i.e. plot character, symbol or shape) to apply when drawing the start point dot. |
start.pt.col |
Colour to apply when drawing the start point dot. |
turning.angles |
If |
xlim , ylim , xlab , ylab , asp , ann , axes , frame.plot
|
plotting parameters with useful defaults. |
... |
set.seed(42) trj <- TrajGenerate(angularErrorSd = 1.3) plot(trj)
set.seed(42) trj <- TrajGenerate(angularErrorSd = 1.3) plot(trj)
Plots speed over time, with intervals of fast and/or slow speed highlighted.
## S3 method for class 'TrajSpeedIntervals' plot( x, slowerThanColour = "red", fasterThanColour = "green", highlightColor = "#0000FF1E", xlab = sprintf("Time (%s)", TrajGetTimeUnits(attr(x, "trajectory"))), ylab = sprintf("Speed (%s/%s)", TrajGetUnits(attr(x, "trajectory")), TrajGetTimeUnits(attr(x, "trajectory"))), type = "l", ... )
## S3 method for class 'TrajSpeedIntervals' plot( x, slowerThanColour = "red", fasterThanColour = "green", highlightColor = "#0000FF1E", xlab = sprintf("Time (%s)", TrajGetTimeUnits(attr(x, "trajectory"))), ylab = sprintf("Speed (%s/%s)", TrajGetUnits(attr(x, "trajectory")), TrajGetTimeUnits(attr(x, "trajectory"))), type = "l", ... )
x |
An object of class "SpeedIntervals", as created by
|
slowerThanColour , fasterThanColour
|
The colour of the horizontal line
plotted at the "slower than" or "faster than" speed. Specify |
highlightColor |
Colour of the highlight rectangles. |
xlab , ylab , type
|
Plotting parameters with useful defaults. |
... |
Additional arguments are passed to |
# Display speed intervals with custom x-axis labels # Generate and smooth a trajectory set.seed(3) trj <- TrajSmoothSG(TrajGenerate(120, fps = 0.5)) # Get speed intervals to be plotted si <- TrajSpeedIntervals(trj, slowerThan = 0.9, diff = "central") # Plot, but don't label x axis plot(si, xlab = "Time (min:sec)", xaxt = "n") # Work out where x-axis tick marks should be speeds <- attr(si, "speed") # data frame containing speed over time p <- pretty(speeds$time) # Draw x-sxis ticks and labels with custom formatting axis(1, p, sprintf("%d:%02d", p %/% 60, p %% 60))
# Display speed intervals with custom x-axis labels # Generate and smooth a trajectory set.seed(3) trj <- TrajSmoothSG(TrajGenerate(120, fps = 0.5)) # Get speed intervals to be plotted si <- TrajSpeedIntervals(trj, slowerThan = 0.9, diff = "central") # Plot, but don't label x axis plot(si, xlab = "Time (min:sec)", xaxt = "n") # Work out where x-axis tick marks should be speeds <- attr(si, "speed") # data frame containing speed over time p <- pretty(speeds$time) # Draw x-sxis ticks and labels with custom formatting axis(1, p, sprintf("%d:%02d", p %/% 60, p %% 60))
The points
method for Trajectory objects.
## S3 method for class 'Trajectory' points(x, draw.start.pt = TRUE, turning.angles = NULL, ...)
## S3 method for class 'Trajectory' points(x, draw.start.pt = TRUE, turning.angles = NULL, ...)
x |
An object of class "Trajectory", the trajectory to be plotted. |
draw.start.pt |
If TRUE, draws a dot at the start point of the trajectory. |
turning.angles |
If |
... |
Additional arguments are passed to |
Returns an approximation of the acceleration of a trajectory at each point using the second-order central finite differences.
Traj3DAcceleration(trj3d)
Traj3DAcceleration(trj3d)
trj3d |
3-dimensional trajectory whose acceleration is to be calculated. |
trajr
trajectories, which consist of straight line displacements
between sampled locations, do not contain enough information to correctly
derive velocity or acceleration. Since we have to assume a constant velocity
at each step, the first derivative is discontinuous. Acceleration, therefore,
is zero during each step and infinite at each change of velocity. The
approximation implemented by this function assumes that acceleration occurs
over a period of time: half the duration of the previous step plus half the
duration of the next step.
The function Traj3DSpeed
, despite its name, can be used to
calculate the magnitude of the acceleration vectors returned by this function.
Numeric matrix of 3D acceleration vectors. Each row represents the
acceleration at a point in the trajectory. Columns are named "'x'", "'y'"
and "'z'". The vector has an attribute, trj
, with the trajectory as
its value. The first and last values will always be NA
, since
acceleration cannot be estimated for those points.
Traj3DVelocity
for calculating velocity,
Traj3DResampleTime
and Traj3DRediscretize
to
resample a trajectory to fixed time or length steps.
## Not run: library(rgl) # Plot a trajectory and its acceleration in 3D, using the rgl package # Function to add acceleration vectors as arrows to a 3D trajectory plot Acc3DArrows <- function(acc, scale = 0.0001, trj3d = attr(acc, "trj3d"), ...) { cols <- c("x", "y", "z") sapply(seq_len(nrow(t3) - 2) + 1, function(r) { arrow3d(t3[r, cols], t3[r, cols] + acc[r, ] * scale, type = "extrusion", ...) }) } plot3d(trj3d$x, trj3d$y, trj3d$z, type = 'l') Acc3DArrows(Traj3DAcceleration(trj3d), col = 2) ## End(Not run)
## Not run: library(rgl) # Plot a trajectory and its acceleration in 3D, using the rgl package # Function to add acceleration vectors as arrows to a 3D trajectory plot Acc3DArrows <- function(acc, scale = 0.0001, trj3d = attr(acc, "trj3d"), ...) { cols <- c("x", "y", "z") sapply(seq_len(nrow(t3) - 2) + 1, function(r) { arrow3d(t3[r, cols], t3[r, cols] + acc[r, ] * scale, type = "extrusion", ...) }) } plot3d(trj3d$x, trj3d$y, trj3d$z, type = 'l') Acc3DArrows(Traj3DAcceleration(trj3d), col = 2) ## End(Not run)
Calculates the distance between the start and end of a 3-dimensional trajectory (or a portion of a trajectory). Also called the diffusion distance, net distance, displacement, or bee-line from start to finish.
Traj3DDistance(trj3d, startIndex = 1, endIndex = nrow(trj3d))
Traj3DDistance(trj3d, startIndex = 1, endIndex = nrow(trj3d))
trj3d |
3-dimensional trajectory whose distance is to be calculated. |
startIndex |
Index of the starting point. |
endIndex |
Index of the ending point. |
Numeric distance from the start to the end of the trajectory.
Traj3DFromCoords
creates a new 3-dimensional trajectory object from a
set of 3-dimensional cartesian coordinates, times and some metadata. A 3D
trajectory is a 2D trajectory (see TrajFromCoords
) with the
addition of a z
coordinate. trajr
functions that expect a 2D
trajectory will work on a 3D trajectory by simply ignoring the z
dimension, so should only be used with care. A small number of functions
operate on 3D trajectories, and are prefixed by Traj3D
. Existing
trajr
functions that that do not deal with spatial data (e.g.
TrajDuration
, TrajGetNCoords
etc.) can safely be
used.
Traj3DFromCoords( track, xCol = 1, yCol = 2, zCol = 3, timeCol = NULL, fps = 50, spatialUnits = "m", timeUnits = "s" )
Traj3DFromCoords( track, xCol = 1, yCol = 2, zCol = 3, timeCol = NULL, fps = 50, spatialUnits = "m", timeUnits = "s" )
track |
data frame containing cartesian coordinates and optionally times for the points in the trajectory. |
xCol |
Name or index of the |
yCol |
Name or index of the |
zCol |
Name or index of the |
timeCol |
optional name or index of the column which contains coordinate times. |
fps |
Frames per second - used to calculate relative coordinate times if
|
spatialUnits |
Abbreviation for the x, y and z units. |
timeUnits |
Abbreviation for the units that time is recorded in. |
The coordinates are sometimes referred to as "relocations". Rows containing
NA
coordinate or time values at the start or end of the trajectory are
discarded. NA
coordinates or times in the middle of the trajectory
generate an error.
If timeCol
is specified, track[,timeCol]
is expected to contain
the time (in some numeric units) of each coordinate. Otherwise, times are
calculated for each point as (coord - 1) / fps
where coord
is
the index of the point; in other words, sampling at constant time intervals
is assumed. Time values require conversion if they are not numeric. It may be
possible to use 'strptime' for this purpose, or TrajConvertTime
can be used to convert multiple field time values.
x
and y
must be square units. Longitude and latitude are not
suitable for use as x
and y
values, since in general, 1°
lat != 1° lon
. To create a trajectory from positions in latitude and
longitude, it is first necessary to transform the positions to a suitable
spatial projection such as UTM (possibly by using spTransform
from the
rgdal
package).
Leading and trailing rows with NA
coordinate values are discarded.
NA
coordinate values within a trajectory generate an error.
An object with class "Trajectory3D
", which is a data.frame
with the following components:
x |
X coordinates of trajectory points. |
y |
Y coordinates of trajectory points. |
time |
Time (in
|
displacementTime |
Relative frame/observation times, with
frame/observation 1 at time |
polar |
X and y coordinates represented as complex numbers, to simplify working with 2D segment angles. Note that the z dimension is not represented. |
displacement |
2-dimensional displacement vectors (represented as complex numbers) between each pair of consecutive points. Note that the z dimension is not represented. |
Traj3DLength
, Traj3DStepLengths
,
Traj3DDistance
, Traj3DStraightness
,
Traj3DSmoothSG
, Traj3DResampleTime
,
Traj3DRediscretize
, TrajFromCoords
for creating
2-dimensional trajectories
Calculates the cumulative length of a 3-dimensional trajectory, or a portion of a trajectory. The length is the total distance travelled along the trajectory.
Traj3DLength(trj3d, startIndex = 1, endIndex = nrow(trj3d))
Traj3DLength(trj3d, startIndex = 1, endIndex = nrow(trj3d))
trj3d |
3D trajectory whose length is to be calculated. |
startIndex |
Index of the starting point. |
endIndex |
Index of the ending point. |
Numeric length of the trajectory.
Traj3DFromCoords
, Traj3DStepLengths
, TrajLength
Constructs a new 3-dimensional trajectory by resampling the input
3-dimensional trajectory to a fixed step (or segment) length. By
default, timing of frames is lost, so speed and acceleration cannot
be calculated on a rediscretized trajectory. However, a constant
speed may be applied to the rediscretized trajectory
(simConstantSpeed = TRUE
), in which case the returned
trajectory will have (almost) constant speed, with average speed
approximately equal to the average speed of trj3d
.
Traj3DRediscretize(trj3d, R, simConstantSpeed = FALSE)
Traj3DRediscretize(trj3d, R, simConstantSpeed = FALSE)
trj3d |
The 3-dimensional trajectory to be resampled. |
R |
rediscretization step length, in the spatial units of |
simConstantSpeed |
If TRUE, speeds are interpolated along the new
trajectory so that average speed is approximately the same as that of
|
Unfortunately this operation is slow for large trajectories.
Based on the appendix in Bovet and Benhamou, (1988), extended to 3 dimensions.
A new 3-dimensional trajectory with a constant segment length which
follows trj3d
.
Bovet, P., & Benhamou, S. (1988). Spatial analysis of animals' movements using a correlated random walk model. Journal of Theoretical Biology, 131(4), 419-433. doi:10.1016/S0022-5193(88)80038-9
Traj3DFromCoords
, TrajRediscretize
Constructs a new 3-dimensional trajectory by resampling the input trajectory to a fixed time interval. Points are linearly interpolated along the trajectory. Spatial and time units are preserved.
Traj3DResampleTime(trj3d, stepTime, newFps = NULL)
Traj3DResampleTime(trj3d, stepTime, newFps = NULL)
trj3d |
The 3-dimensional trajectory to be resampled. |
stepTime |
The resampled trajectory step time. Each step in the new trajectory will have this duration. |
newFps |
Value to be stored as the FPS value in the new trajectory (see
|
A new 3-dimensional trajectory with a constant time interval for each
step. Points in the new trajectory are calculated by linearly interpolating
along trj3d
.
Traj3DFromCoords
, TrajResampleTime
Smooths a 3-dimensional trajectory using a Savitzky-Golay smoothing filter.
Traj3DSmoothSG(trj3d, p = 3, n = p + 3 - p%%2, ...)
Traj3DSmoothSG(trj3d, p = 3, n = p + 3 - p%%2, ...)
trj3d |
The 3=dimensional trajectory to be smoothed. |
p |
polynomial order (passed to |
n |
Filter length (or window size), must be an odd number. Passed to
|
... |
Additional arguments are passed to
|
Consider carefully the effects of smoothing a trajectory with temporal gaps
in the data. If the smoothed trajectory is used to derive speed and/or
acceleration, it may be advisable to fill in the gaps before smoothing,
possibly by calling Traj3DResampleTime
.
A new trajectory which is a smoothed version of the input trajectory.
Traj3DFromCoords
, sgolayfilt
, TrajSmoothSG
Speed is calculated as the magnitude of velocity. The returned speed will contain leading and/or trailing 'NA' values, depending on the type of differences used to calculate velocity.
Traj3DSpeed(vel)
Traj3DSpeed(vel)
vel |
Velocity of a 3-dimensional trajectory, as returned by
|
If the trajectory has constant time steps, then the average speed of the
trajectory is 'mean(Traj3DSpeed(Traj3DVelocity(trj)), na.rm = TRUE)'. A
trajectory can be resampled by Traj3DResampleTime
so that it
has constant time steps.
This function is implemented to simply interpret each row of a matrix as a 3D
vector, and return their lengths. Accordingly, this function can also be used
to calculate the magnitude of acceleration as returned by
Traj3DAcceleration
.
Numeric vector with speed at each point along the trajectory.
Traj3DVelocity
to calculate the 3D velocity,
Traj3DAcceleration
to calculate the 3D acceleration,
Traj3DLength
, TrajDuration
,
Traj3DResampleTime
## Not run: # Get the velocity along the trajectory speed <- Traj3DSpeed(Traj3DVelocity(trj3d)) # Alternative method to calculate mean speed of a portion of a trajectory si <- 10 ei <- 400 # Mean speed is displacement divided by time speedMean <- Traj3DLength(trj3d, startIndex = si, endIndex = ei) / TrajDuration(trj3d, startIndex = si, endIndex = ei) ## End(Not run)
## Not run: # Get the velocity along the trajectory speed <- Traj3DSpeed(Traj3DVelocity(trj3d)) # Alternative method to calculate mean speed of a portion of a trajectory si <- 10 ei <- 400 # Mean speed is displacement divided by time speedMean <- Traj3DLength(trj3d, startIndex = si, endIndex = ei) / TrajDuration(trj3d, startIndex = si, endIndex = ei) ## End(Not run)
Returns the lengths of each step in a 3-dimensional trajectory (or part of a trajectory).
Traj3DStepLengths(trj3d, startIndex = 1, endIndex = nrow(trj3d))
Traj3DStepLengths(trj3d, startIndex = 1, endIndex = nrow(trj3d))
trj3d |
Trajectory to query. |
startIndex |
Index of the starting point. |
endIndex |
Index of the ending point. |
Vector of step lengths. The vector will have length 1 - TrajGetNCoords(trj3d)
.
Traj3DFromCoords
, Traj3DLength
, TrajStepLengths
Calculates the straightness index of a 3-dimensional trajectory, ,
where
D
is the beeline distance between the first and last points in
the trajectory,and L
is the path length travelled (Batschelet, 1981).
Benhamou (2004) considers the straightness index to be a reliable measure of
the efficiency of a directed walk, but inapplicable to random trajectories.
The straightness index of a random walk tends towards zero as the number of
steps increases, hence should only be used to compare the tortuosity of
random walks consisting of a similar number of steps.
Traj3DStraightness(trj3d)
Traj3DStraightness(trj3d)
trj3d |
3-dimensional trajectory to calculate straightness of. |
The straightness index is also known as the net-to-gross displacement ratio.
According to Batschelet (1981), this value (termed d) is an
approximation of r, which is the length of the mean vector of turning
angles of a constant step-length trajectory (see
TrajMeanVectorOfTurningAngles
and
TrajRediscretize
for creating a constant step-length
trajectory).
The straightness index of trj
, which is a value between 0
(infinitely tortuous) to 1 (a straight line).
Batschelet, E. (1981). Circular statistics in biology. ACADEMIC PRESS, 111 FIFTH AVE., NEW YORK, NY 10003, 1981, 388.
Benhamou, S. (2004). How to reliably estimate the tortuosity of an animal's path. Journal of Theoretical Biology, 229(2), 209-220. doi:10.1016/j.jtbi.2004.03.016
Traj3DFromCoords
, Traj3DDistance
for
trajectory distance (or displacement), and Traj3DLength
for
trajectory path length, Traj3DStraightness
for the
straightness of a 2D trajectory.
The velocity, as a 3-dimensional vector, is approximated at each point of the trajectory using first-order finite differences. Central, forward or backward differences can be used. Central differences yield a more accurate approximation if the velocity is smooth. As a practical guide, if velocity doesn't change much between steps, use central differences. If it changes substantially (and not just as an artifact of recording noise), then use either forward or backward differences.
Traj3DVelocity(trj3d, diff = c("central", "forward", "backward"))
Traj3DVelocity(trj3d, diff = c("central", "forward", "backward"))
trj3d |
3-dimensional trajectory whose velocity is to be calculated. |
diff |
Type of difference to be calculated, one of "central" (the default), "forward" or "backward". |
Intuitively, think of the central difference velocity at a point as the mean of the velocities of the two adjacent steps. Forward difference velocity is the velocity of the step starting at the point. Backward difference is the velocity of the step ending at the point.
Speed (i.e. the magnitude of the velocity) can be derived from velocity by
calling Traj3DSpeed
.
A numeric matrix. Each row represents the 3D velocity vector at each
point along the trajectory, with 'x', 'y' and 'z' columns. If diff
is "central"
, the first and last velocity values will be NA
since velocity cannot be calculated for them. If diff
is
"forward"
, the last value will be NA, and if diff
is
"backward"
, the first value will be NA.
Traj3DSpeed
for calculating scalar speed, which is the
magnitude of the velocity vector at each step;
Traj3DResampleTime
and Traj3DRediscretize
to
resample a trajectory to fixed time or length steps; Finite differences on
Wikipedia.
Returns an approximation of the acceleration of a trajectory at each point using the second-order central finite differences.
TrajAcceleration(trj)
TrajAcceleration(trj)
trj |
Trajectory whose acceleration is to be calculated. |
trajr
trajectories, which consist of straight line displacements between
sampled locations, do not contain enough information to correctly derive
velocity or acceleration. Since we have to assume a constant velocity at each
step, the first derivative is discontinuous. Acceleration, therefore, is zero
during each step and infinite at each change of velocity. The approximation
implemented by this function assumes that acceleration occurs over a period
of time: half the duration of the previous step plus half the duration of the
next step.
Vector of complex numbers. The modulus (Mod(a)
) is the
magnitude of the acceleration at each point, and the argument
(Arg(a)
) is the direction of the acceleration. The vector has an
attribute, trj
, with the trajectory as its value. The first and last
values will always be NA
, since acceleration cannot be estimated for
those points.
TrajVelocity
for calculating velocity,
TrajResampleTime
and TrajRediscretize
to
resample a trajectory to fixed time or length steps.
# A function to plot acceleration as arrows (scaled in length) AccArrows <- function(acc, scale = .001, trj = attr(acc, "trj"), ...) { graphics::arrows(trj$x, trj$y, trj$x + Re(acc) * scale, trj$y + Im(acc) * scale, ...) } # Generate and plot a random trajectory set.seed(101) trj <- TrajGenerate(30) plot(trj) # Calculate acceleration acc <- TrajAcceleration(trj) # Plot acceleration as red arrows at each point. They need to be scaled down to # fit in the plot, and the arrowhead lengths need to be shortened to look good AccArrows(acc, scale = .001, col = "red", length = .1)
# A function to plot acceleration as arrows (scaled in length) AccArrows <- function(acc, scale = .001, trj = attr(acc, "trj"), ...) { graphics::arrows(trj$x, trj$y, trj$x + Re(acc) * scale, trj$y + Im(acc) * scale, ...) } # Generate and plot a random trajectory set.seed(101) trj <- TrajGenerate(30) plot(trj) # Calculate acceleration acc <- TrajAcceleration(trj) # Plot acceleration as red arrows at each point. They need to be scaled down to # fit in the plot, and the arrowhead lengths need to be shortened to look good AccArrows(acc, scale = .001, col = "red", length = .1)
Calculates the step angles (in radians) of each segment, either relative to the previous segment or relative to the specified compass direction.
TrajAngles(trj, lag = 1, compass.direction = NULL)
TrajAngles(trj, lag = 1, compass.direction = NULL)
trj |
the trajectory whose angles are to be calculated. |
lag |
Angles between every lag'th segment are calculated. Only applies
to non-directed walks, i.e. |
compass.direction |
If not |
Note that since turning angles are circular quantities, i.e. 360° == 0°, it is incorrect to treat them as linear quantities. In particular, do not calculate arithmetic means or standard deviations of turning angles. See Batschelet, (1981) for a detailed explanation and techniques for dealing with circular quantities.
The turning angle before and after every zero-length segment will be
NA
, since the angle of a zero-length segment is undefined. This
behaviour began in trajr
version 1.5.0 (or development version
1.4.0.9000). Prior to this fix, the angle of a zero-length segment was
assumed to be 0, which led to incorrect turning angles being returned. One
approach to dealing with zero-length segments is to simply remove them from
the trajectory. See TrajFromTrjPoints
for a means to achieve this.
Step angles in radians, normalised so that -pi < angle <= pi
.
If compass.direction
is NULL
(the default), the returned
vector will have length nrow(trj) - 2
, i.e. one angle for every pair
of adjacent segments. If compass.direction
is not NULL
, the
returned vector will have length nrow(trj) - 1
, i.e. one angle for
every segment.
Batschelet, E. (1981). Circular statistics in biology. ACADEMIC PRESS, 111 FIFTH AVE., NEW YORK, NY 10003, 1981, 388.
TrajStepLengths
,
TrajMeanVectorOfTurningAngles
,
TrajFromTrjPoints
Time values may be imported in a format which is not immediately usable by 'trajr'. This function converts times that are specified as a number of delimited fields to a single numeric value. The default parameter values handle a value with 4 colon-separated values, which are hours, minutes, seconds and milliseconds, eg: "0:01:04:108" represents 1 minute, 4 seconds and 108 milliseconds, or 64.108 seconds.
TrajConvertTime(time, sep = ":", factors = c(60 * 60, 60, 1, 0.001))
TrajConvertTime(time, sep = ":", factors = c(60 * 60, 60, 1, 0.001))
time |
A character string containing the time value to be converted. |
sep |
Field separator. |
factors |
Vector of numeric factors to be applied to each field, in the order they occur within 'time'. The default assumes 4 fields containing numeric hours, minutes, seconds and milliseconds. |
Note that the base R strptime can be used to convert time values in more complex date/time formats, but it does not handle millisecond fields.
'time' converted to a numeric value.
time <- c("0:00:00:029", "0:01:00:216", "0:02:01:062", "1:00:02:195", "1:06:03:949", "1:42:04:087") seconds <- TrajConvertTime(time)
time <- c("0:00:00:029", "0:01:00:216", "0:02:01:062", "1:00:02:195", "1:06:03:949", "1:42:04:087") seconds <- TrajConvertTime(time)
Determines the coordinates of the first local minimum/maximum of C
in
the direction autocorrelation function of a trajectory as returned by
TrajDirectionAutocorrelations
. The end point is excluded from
consideration as a minimum, similarly the start point will not be returned as
a maximum. If the trajectory does not oscillate in direction, there will not
be a local minimum/maximum, and NULL
is returned.
TrajDAFindFirstMinimum(corr, windowSize = 10) TrajDAFindFirstMaximum(corr, windowSize = 10)
TrajDAFindFirstMinimum(corr, windowSize = 10) TrajDAFindFirstMaximum(corr, windowSize = 10)
corr |
A |
windowSize |
Size of window used to define what constitutes a local mimimum/maximum. |
Numeric vector with 2 values, deltaS
and C
, or NULL if
there is no local minimum/maximum.
set.seed(42) trj <- TrajGenerate(600, angularErrorSd = 1) smoothed <- TrajSmoothSG(trj, 3, 11) # Resample to fixed path length resampled <- TrajRediscretize(smoothed, 1) # Calculate direction autocorrelation for resampled trajectory corr <- TrajDirectionAutocorrelations(resampled, 100) # Extract first local minimum from autocorrelation minPt <- TrajDAFindFirstMinimum(corr, 20) # Plot the autocorrelation function plot(corr, type ='l') # Plot a red dot with a black outline at the first minimum points(minPt["deltaS"], minPt["C"], pch = 16, col = "red", lwd = 2) points(minPt["deltaS"], minPt["C"], col = "black", lwd = 2)
set.seed(42) trj <- TrajGenerate(600, angularErrorSd = 1) smoothed <- TrajSmoothSG(trj, 3, 11) # Resample to fixed path length resampled <- TrajRediscretize(smoothed, 1) # Calculate direction autocorrelation for resampled trajectory corr <- TrajDirectionAutocorrelations(resampled, 100) # Extract first local minimum from autocorrelation minPt <- TrajDAFindFirstMinimum(corr, 20) # Plot the autocorrelation function plot(corr, type ='l') # Plot a red dot with a black outline at the first minimum points(minPt["deltaS"], minPt["C"], pch = 16, col = "red", lwd = 2) points(minPt["deltaS"], minPt["C"], col = "black", lwd = 2)
Calculates speed and change of speed along a trajectory over time. These are the first and second order derivatives of distance travelled over time. Noisy trajectories should be smoothed before being passed to this function, as noise is effectively amplified when taking derivatives.
TrajDerivatives(trj)
TrajDerivatives(trj)
trj |
Trajectory whose speed and change in speed is to be calculated. |
The value returned as acceleration
is not technically
acceleration. In mechanics, acceleration is a vector. The returned value is a
scalar quantity: change of speed, which is sometimes known informally as
acceleration. This value corresponds to the acceleration in a 1-dimensional
trajectory, with the sign indicating the direction of acceleration relative
to the current direction of velocity. See TrajAcceleration
for
an approximation of (vector) acceleration, and TrajVelocity
for
an approximation of velocity.
A list with components:
speed |
numeric vector, speed between each pair of trajectory points, i.e. the speed of each step. |
speedTimes |
numeric vector, times corresponding to values in
|
acceleration |
numeric vector, change in speed between steps. Despite the name, this is not acceleration as defined by mechanics. |
accelerationTimes |
numeric vector, time from the start of the trajectory to the end of the second step in each pair. |
TrajSpeedIntervals
for analysing intervals of low or
high speed within the trajectory. TrajSmoothSG
for smoothing
a trajectory. TrajAcceleration
for calculating acceleration,
and TrajVelocity
for calculating velocity.
Calculates the time variation of directional change (DC) of a trajectory sensu Kitamura & Imafuku (2015). Directional change is defined as the angular change (in degrees) between two steps in the trajectory, divided by the time difference between the two steps.
TrajDirectionalChange(trj, nFrames = 1)
TrajDirectionalChange(trj, nFrames = 1)
trj |
Track to calculate DC for. |
nFrames |
Frame delta to process: if 1, every frame is processed, if 2, every 2nd frame is processed, and so on. Default is 1. |
This function returns the DC for each pair of consecutive steps. Kitamura & Imafuku (2015) used the mean and the standard deviation of DC for portions of trajectories as index values of nonlinearity and irregularity respectively.
The directional change (DC) in degrees between every pair of
consecutive segments in the trajectory, i.e. if nFrames
is 1, the
returned vector will have length nrow(trj) - 2
.
Kitamura, T., & Imafuku, M. (2015). Behavioural mimicry in flight path of Batesian intraspecific polymorphic butterfly Papilio polytes. Proceedings of the Royal Society B: Biological Sciences, 282(1809). doi:10.1098/rspb.2015.0483
set.seed(42) trj <- TrajGenerate() SD = mean(TrajDirectionalChange(trj)) SDDC = sd(TrajDirectionalChange(trj))
set.seed(42) trj <- TrajGenerate() SD = mean(TrajDirectionalChange(trj)) SDDC = sd(TrajDirectionalChange(trj))
Calculates the autocorrelation of the track for s ranging from 1
to
deltaSMax
, based on Shamble et al. (2017). trj
must have a
constant step length (see TrajRediscretize
) i.e. all segments
in the trajectory must be the same length. deltaS is specified in number of
segments. Call TrajDAFindFirstMinimum
to locate the first local
minimum which may be used to characterise directional periodicity in a
trajectory (note that the first local minimum may not exist).
TrajDirectionAutocorrelations(trj, deltaSMax = round(nrow(trj)/4))
TrajDirectionAutocorrelations(trj, deltaSMax = round(nrow(trj)/4))
trj |
The trajectory to calculate the directional autocorrelations for. |
deltaSMax |
Maximum delta s to calculate, default is |
A data frame with class TrajDirectionAutocorrelations
and 2
columns, deltaS
and C
. Plotting this object displays a graph
of the direction autocorrelation function, optionally with the location of
the first local minimum marked
Shamble, P. S., Hoy, R. R., Cohen, I., & Beatus, T. (2017). Walking like an ant: a quantitative and experimental approach to understanding locomotor mimicry in the jumping spider Myrmarachne formicaria. Proceedings of the Royal Society B: Biological Sciences, 284(1858). doi:10.1098/rspb.2017.0308
TrajDAFindFirstMinimum
,
plot.TrajDirectionAutocorrelations
Calculates the distance between the start and end of a trajectory (or a portion of a trajectory). Also called the diffusion distance, net distance, displacement, or bee-line from start to finish.
TrajDistance(trj, startIndex = 1, endIndex = nrow(trj))
TrajDistance(trj, startIndex = 1, endIndex = nrow(trj))
trj |
Trajectory whose distance is to be calculated. |
startIndex |
Index of the starting point. |
endIndex |
Index of the ending point. |
Numeric distance from the start to the end of the trajectory.
Calculates the temporal duration of a trajectory (or a portion of a trajectory).
TrajDuration(trj, startIndex = 1, endIndex = nrow(trj))
TrajDuration(trj, startIndex = 1, endIndex = nrow(trj))
trj |
Trajectory whose duration is to be calculated. |
startIndex |
Index of the starting point. |
endIndex |
Index of the ending point. |
Numeric duration of the trajectory, in time units.
Emax, the maximum expected displacement, is a single-valued measure of
straightness defined by (Cheung, Zhang, Stricker, & Srinivasan, 2007). Emax-a
is a dimensionless, scale-independent measure of the maximum possible
expected displacement. Emax-b is Emax-a * mean step length
, and gives
the maximum possible expected displacement in spatial units. Values closer to
0 are more sinuous, while larger values (approaching infinity) are
straighter.
TrajEmax(trj, eMaxB = FALSE, compass.direction = NULL)
TrajEmax(trj, eMaxB = FALSE, compass.direction = NULL)
trj |
Trajectory to be analysed. |
eMaxB |
If TRUE, calculates and returns Emax-b, otherwise returns Emax-a. |
compass.direction |
if not |
Emax (-a or -b) for trj
.
Cheung, A., Zhang, S., Stricker, C., & Srinivasan, M. V. (2007). Animal navigation: the difficulty of moving in a straight line. Biological Cybernetics, 97(1), 47-61. doi:10.1007/s00422-007-0158-0
Calculates the expected square displacement for a trajectory assuming it is a correlated random walk, using the formula in Kareiva & Shigesada, (1983).
TrajExpectedSquareDisplacement( trj, n = nrow(trj), eqn1 = TRUE, compass.direction = NULL )
TrajExpectedSquareDisplacement( trj, n = nrow(trj), eqn1 = TRUE, compass.direction = NULL )
trj |
A Trajectory. |
n |
Number of steps to calculate. |
eqn1 |
If |
compass.direction |
If not |
Note that Cheung, Zhang, Stricker, and Srinivasan (2007) define an
alternative formulation for expected maximum displacement, Emax (see
TrajEmax
).
Cheung, A., Zhang, S., Stricker, C., & Srinivasan, M. V. (2007). Animal navigation: the difficulty of moving in a straight line. Biological Cybernetics, 97(1), 47-61. doi:10.1007/s00422-007-0158-0
Kareiva, P. M., & Shigesada, N. (1983). Analyzing insect movement as a correlated random walk. Oecologia, 56(2), 234-238. doi:10.1007/bf00379695
set.seed(1) # A random walk trj <- TrajGenerate(200) smoothed <- TrajSmoothSG(trj) # Calculate actual squared displacement at all points along the trajectory sd2 <- sapply(2:nrow(smoothed), function(n) TrajDistance(smoothed, 1, n) ^ 2) # Calculate expected squared displacement ed2_1 <- sapply(2:nrow(smoothed), function(n) TrajExpectedSquareDisplacement(smoothed, n, TRUE)) ed2_2 <- sapply(2:nrow(smoothed), function(n) TrajExpectedSquareDisplacement(smoothed, n, FALSE)) # Plot expected against actual. According to Kareiva & Shigesada, (1983), if actual # (approximately) matches expected, the trajectory is probably a correlated random walk par(mar = c(5, 5, 0.1, 0.1) + .1) plot(2:nrow(smoothed), sd2, type = 'l', pch = 16, cex = .2, lwd = 2, xlab = 'Number of consecutive moves', ylab = expression('Squared displacement, ' * R[n]^2)) lines(2:nrow(smoothed), ed2_1, col = "grey", lwd = 2) lines(2:nrow(smoothed), ed2_2, col = "pink", lwd = 2) legend("bottomright", c(expression("Actual displacement"^2), expression("Expected displacement"^2 * " (eqn 1)"), expression("Expected displacement"^2 * " (eqn 2)")), col = c('black', 'grey', 'pink'), lwd = 2, inset = c(0.01, 0.02))
set.seed(1) # A random walk trj <- TrajGenerate(200) smoothed <- TrajSmoothSG(trj) # Calculate actual squared displacement at all points along the trajectory sd2 <- sapply(2:nrow(smoothed), function(n) TrajDistance(smoothed, 1, n) ^ 2) # Calculate expected squared displacement ed2_1 <- sapply(2:nrow(smoothed), function(n) TrajExpectedSquareDisplacement(smoothed, n, TRUE)) ed2_2 <- sapply(2:nrow(smoothed), function(n) TrajExpectedSquareDisplacement(smoothed, n, FALSE)) # Plot expected against actual. According to Kareiva & Shigesada, (1983), if actual # (approximately) matches expected, the trajectory is probably a correlated random walk par(mar = c(5, 5, 0.1, 0.1) + .1) plot(2:nrow(smoothed), sd2, type = 'l', pch = 16, cex = .2, lwd = 2, xlab = 'Number of consecutive moves', ylab = expression('Squared displacement, ' * R[n]^2)) lines(2:nrow(smoothed), ed2_1, col = "grey", lwd = 2) lines(2:nrow(smoothed), ed2_2, col = "pink", lwd = 2) legend("bottomright", c(expression("Actual displacement"^2), expression("Expected displacement"^2 * " (eqn 1)"), expression("Expected displacement"^2 * " (eqn 2)")), col = c('black', 'grey', 'pink'), lwd = 2, inset = c(0.01, 0.02))
Calculates the fractal dimension (D
) of a trajectory using the
'dividers' method (Sugihara & May, 1990). By default, overestimation of
D
is compensated for as recommended by Nams (2006), by walking the
dividers backwards and forwards, and by estimating the remaining path length
at the end of the last step.
TrajFractalDimension(trj, stepSizes, adjustD = TRUE, dMean = TRUE)
TrajFractalDimension(trj, stepSizes, adjustD = TRUE, dMean = TRUE)
trj |
Trajectory to calculate fractal dimension for. |
stepSizes |
Vector of step sizes (aka divider sizes) used to calculate path lengths. |
adjustD |
If |
dMean |
If |
Fractal dimension may be meaningless for animal trajectories as they may not be true fractal curves - see Benhamou (2004) and Turchin (1996), although it may be useful for studies involving differences in behaviour at different spatial scales (Nams, 2006).
You can test whether a trajectory is a fractal curve for a range of step
sizes using the TrajFractalDimensionValues
function. The
example code in its documentation demonstrates how to plot path length for a
range of step sizes. If the plotted points lie along straight line, then the
trajectory is a fractal curve for that range of step sizes. However, typical
trajectories result in a curve rather than a straight line.
If you decide to use fractal dimension despite the warnings of Benhamou (2004) and Turchin (1996), try to select a biologically meaningful range of step sizes (and be prepared to justify your choice). If comparing fractal dimensions across trajectories, be consistent in your choice of step sizes.
The fractal dimension of the trajectory for the given step sizes.
Benhamou, S. (2004). How to reliably estimate the tortuosity of an animal's path. Journal of Theoretical Biology, 229(2), 209-220. doi:10.1016/j.jtbi.2004.03.016
Nams, V. O. (2006). Improving Accuracy and Precision in Estimating Fractal Dimension of Animal movement paths. Acta Biotheoretica, 54(1), 1-11. doi:10.1007/s10441-006-5954-8
Sugihara, G., & M. May, R. (1990). Applications of fractals in ecology. Trends in Ecology & Evolution, 5(3), 79-86. doi:10.1016/0169-5347(90)90235-6
Turchin, P. (1996). Fractal Analyses of Animal Movement: A Critique. Ecology, 77(7), 2086-2090. doi:10.2307/2265702
TrajLogSequence
to create a logarithmically spaced
sequence, TrajFractalDimensionValues
for the function used
internally to calculate a range of path lengths for different step sizes,
TrajEmax
and TrajSinuosity2
for some alternate
measures of trajectory tortuosity.
Calculates path length () for a range of step sizes
(
). For a fractal (i.e. scale independent) curve,
grows linearly as
grows smaller. In
other words, if the points returned by this function lie on a straight line
in a log-log plot,
trj
is a fractal curve.
TrajFractalDimensionValues(trj, stepSizes, adjustD = TRUE)
TrajFractalDimensionValues(trj, stepSizes, adjustD = TRUE)
trj |
Trajectory to calculate fractal dimension for. |
stepSizes |
Vector of step sizes used to calculate path lengths. |
adjustD |
If TRUE, path length is adjusted to reduce truncation error (Nams, 2006). |
Data frame with columns stepsize
() and
pathlength
(().
Nams, V. O. (2006). Improving Accuracy and Precision in Estimating Fractal Dimension of Animal movement paths. Acta Biotheoretica, 54(1), 1-11. doi:10.1007/s10441-006-5954-8
TrajFractalDimension
for fractal dimension
calculation.
set.seed(42) trj <- TrajGenerate() muL <- mean(TrajStepLengths(trj)) # Use 20 step sizes from 1/2 mean step length to 5 * mean step length. # For real use, biologically meaningful step sizes should be used. stepSizes <- TrajLogSequence(0.5 * muL, 5 * muL, 20) plot(TrajFractalDimensionValues(trj, stepSizes), log = "xy", pch = 16, cex = .5)
set.seed(42) trj <- TrajGenerate() muL <- mean(TrajStepLengths(trj)) # Use 20 step sizes from 1/2 mean step length to 5 * mean step length. # For real use, biologically meaningful step sizes should be used. stepSizes <- TrajLogSequence(0.5 * muL, 5 * muL, 20) plot(TrajFractalDimensionValues(trj, stepSizes), log = "xy", pch = 16, cex = .5)
TrajFromCoords
creates a new trajectory object from a set of
2-dimensional cartesian coordinates, times and some metadata. The coordinates
are sometimes referred to as "relocations". Rows containing NA
coordinate or time values at the start or end of the trajectory are
discarded. NA
coordinates or times in the middle of the trajectory
generate an error.
TrajFromCoords( track, xCol = 1, yCol = 2, timeCol = NULL, fps = 50, spatialUnits = "m", timeUnits = "s" )
TrajFromCoords( track, xCol = 1, yCol = 2, timeCol = NULL, fps = 50, spatialUnits = "m", timeUnits = "s" )
track |
data frame containing cartesian coordinates and optionally times for the points in the trajectory. |
xCol |
Name or index of the |
yCol |
Name or index of the |
timeCol |
optional name or index of the column which contains coordinate times. |
fps |
Frames per second - used to calculate relative coordinate times if
|
spatialUnits |
Abbreviation for the x and y units. |
timeUnits |
Abbreviation for the units that time is recorded in. |
If timeCol
is specified, track[,timeCol]
is expected to contain
the time (in some numeric units) of each coordinate. Otherwise, times are
calculated for each point as (coord - 1) / fps
where coord
is
the index of the point; in other words, sampling at constant time intervals
is assumed. Time values require conversion if they are not numeric. It may be
possible to use 'strptime' for this purpose, or TrajConvertTime
can be used to convert multiple field time values.
x
and y
must be square units. Longitude and latitude are not
suitable for use as x
and y
values, since in general, 1°
lat != 1° lon
. To create a trajectory from positions in latitude and
longitude, it is first necessary to transform the positions to a suitable
spatial projection such as UTM (possibly by using spTransform
from the
rgdal
package).
Leading and trailing rows with NA
coordinate values are discarded.
NA
coordinate values within a trajectory generate an error.
Since columns in coords
are preserved in the returned trajectory, if
coords
contains an x
or y
column which is not identified
by xCol
or yCal
respectively, an error will occur. This is to
prevent columns being inadvertently overwritten.
An object with class "Trajectory
", which is a data.frame with
the following components:
x |
X coordinates of trajectory points. |
y |
Y coordinates of trajectory points. |
time |
Time (in
|
displacementTime |
Relative frame/observation times, with
frame/observation 1 at time |
polar |
Coordinates represented
as complex numbers, to simplify working with segment angles. Beware when
using complex numbers in R; |
displacement |
Displacement vectors (represented as complex numbers) between each pair of consecutive points. |
In addition, any other columns coords
are include in the data frame.
coords <- data.frame(x = c(1, 1.5, 2, 2.5, 3, 4), y = c(0, 0, 1, 1, 2, 1), times = c(0, 1, 2, 3, 4, 5)) trj <- TrajFromCoords(coords, timeCol = "times") par(mar = c(4, 4, 0.5, 0.5) + 0.1) plot(trj)
coords <- data.frame(x = c(1, 1.5, 2, 2.5, 3, 4), y = c(0, 0, 1, 1, 2, 1), times = c(0, 1, 2, 3, 4, 5)) trj <- TrajFromCoords(coords, timeCol = "times") par(mar = c(4, 4, 0.5, 0.5) + 0.1) plot(trj)
Creates a trajectory from a subset of the points in another trajectory, preserving metadata and all columns in the original trajectory.
TrajFromTrjPoints(trj, idx)
TrajFromTrjPoints(trj, idx)
trj |
Trajectory to extract points and metadata from. |
idx |
Indices of the points in |
Note that removing points from a trajectory that does not contain a time column will change the timing of the points, and hence change velocity etc.
A new trajectory which is the same as trj
except with a subset
of points.
## Not run: # Create a trajectory (trj2) by removing all zero-length # segments from another trajectory (trj). Keep all points # that are different from their preceding point, and also # keep the start point trj2 <- TrajFromTrjPoints(trj, c(1, which(Mod(trj$displacement) != 0))) ## End(Not run)
## Not run: # Create a trajectory (trj2) by removing all zero-length # segments from another trajectory (trj). Keep all points # that are different from their preceding point, and also # keep the start point trj2 <- TrajFromTrjPoints(trj, c(1, which(Mod(trj$displacement) != 0))) ## End(Not run)
Generates a trajectory. If random
is TRUE
, the trajectory will
be a correllated random walk/idiothetic directed walk (Kareiva & Shigesada,
1983), corresponding to an animal navigating without a compass (Cheung,
Zhang, Stricker, & Srinivasan, 2008). If random
is FALSE
, it
will be a directed walk/allothetic directed walk/oriented path, corresponding
to an animal navigating with a compass (Cheung, Zhang, Stricker, &
Srinivasan, 2007, 2008).
TrajGenerate( n = 1000, random = TRUE, stepLength = 2, angularErrorSd = 0.5, angularErrorDist = function(n) stats::rnorm(n, sd = angularErrorSd), linearErrorSd = 0.2, linearErrorDist = function(n) stats::rnorm(n, sd = linearErrorSd), fps = 50, ... )
TrajGenerate( n = 1000, random = TRUE, stepLength = 2, angularErrorSd = 0.5, angularErrorDist = function(n) stats::rnorm(n, sd = angularErrorSd), linearErrorSd = 0.2, linearErrorDist = function(n) stats::rnorm(n, sd = linearErrorSd), fps = 50, ... )
n |
Number of steps in the trajectory. |
random |
If TRUE, a random search trajectory is returned, otherwise a directed trajectory (with direction = 0 radians) is returned. |
stepLength |
Mean length of each step in the trajectory, in arbitrary length units. |
angularErrorSd |
Standard deviation of angular errors in radians. |
angularErrorDist |
Function which accepts a single argument - the number
of values to return, and generates random deviates according to some
distribution. The returned values are added to the previous step angle
(when |
linearErrorSd |
Standard deviation of linear step length errors. |
linearErrorDist |
Function which accepts a single argument - the number
of values to return, and generates random deviates according to some
distribution. The returned values are added to |
fps |
Simulated frames-per-second - used to generate times for each point in the trajectory. |
... |
Additional arguments are passed to |
By default, for both random and directed walks, errors are normally
distributed, unbiased, and independent of each other, so are simple
directed walks in the terminology of Cheung, Zhang, Stricker, & Srinivasan,
(2008). This behaviour may be modified by specifying alternative values for
the angularErrorDist
and/or linearErrorDist
parameters.
The initial angle (for a random walk) or the intended direction (for a
directed walk) is 0
radians. To change the initial angle or intended
direction, call TrajRotate
on the new trajectory. The starting
position is (0, 0)
. To change the starting position, call
TrajTranslate
on the new trajectory.
A new Trajectory with n
segments and n + 1
coordinate
pairs.
Kareiva, P. M., & Shigesada, N. (1983). Analyzing insect movement as a correlated random walk. Oecologia, 56(2), 234-238. doi:10.1007/bf00379695
Cheung, A., Zhang, S., Stricker, C., & Srinivasan, M. V. (2007). Animal navigation: the difficulty of moving in a straight line. Biological Cybernetics, 97(1), 47-61. doi:10.1007/s00422-007-0158-0
Cheung, A., Zhang, S., Stricker, C., & Srinivasan, M. V. (2008). Animal navigation: general properties of directed walks. Biological Cybernetics, 99(3), 197-217. doi:10.1007/s00422-008-0251-z
# Generate a 1000 step correlated random walk trj <- TrajGenerate() plot(trj, main = "Correlated walk") # Generate a 1000 step levy flight - paths lengths follow a cauchy distribution trj <- TrajGenerate(linearErrorDist = rcauchy) plot(trj, main = "Levy flight") # Generate a short directed trajectory trj <- TrajGenerate(n = 20, random = FALSE) plot(trj, main = "Directed walk") # Generate an uncorrelated random walk trj <- TrajGenerate(500, angularErrorDist = function(n) runif(n, -pi, pi)) plot(trj, main = "Uncorrelated walk") # Generate a walk directed northwards, starting from (200, 300), # with a mean step length of 200. The initially generated trajectory # is directed to angle 0, with starting point (0, 0) trj <- TrajGenerate(n = 20, stepLength = 200, random = FALSE) # Rotate 90 degrees about (0, 0) (i.e. from east to north) trj <- TrajRotate(trj, pi / 2, relative = FALSE) # Translate to desired starting point trj <- TrajTranslate(trj, 200, 300)
# Generate a 1000 step correlated random walk trj <- TrajGenerate() plot(trj, main = "Correlated walk") # Generate a 1000 step levy flight - paths lengths follow a cauchy distribution trj <- TrajGenerate(linearErrorDist = rcauchy) plot(trj, main = "Levy flight") # Generate a short directed trajectory trj <- TrajGenerate(n = 20, random = FALSE) plot(trj, main = "Directed walk") # Generate an uncorrelated random walk trj <- TrajGenerate(500, angularErrorDist = function(n) runif(n, -pi, pi)) plot(trj, main = "Uncorrelated walk") # Generate a walk directed northwards, starting from (200, 300), # with a mean step length of 200. The initially generated trajectory # is directed to angle 0, with starting point (0, 0) trj <- TrajGenerate(n = 20, stepLength = 200, random = FALSE) # Rotate 90 degrees about (0, 0) (i.e. from east to north) trj <- TrajRotate(trj, pi / 2, relative = FALSE) # Translate to desired starting point trj <- TrajTranslate(trj, 200, 300)
Returns the frames-per-second recorded for this trajectory.
TrajGetFPS(trj)
TrajGetFPS(trj)
trj |
Trajectory to query |
Returns the number of coordinates recorded for this trajectory, i.e. 1 more than the number of steps.
TrajGetNCoords(trj)
TrajGetNCoords(trj)
trj |
Trajectory to query |
Returns the temporal units specified for a scaled trajectory.
TrajGetTimeUnits(trj)
TrajGetTimeUnits(trj)
trj |
Trajectory to query |
Returns the spatial units specified for a scaled trajectory.
TrajGetUnits(trj)
TrajGetUnits(trj)
trj |
Trajectory to query |
Simply a wrapper around point.in.polygon
. The sp
package must be installed for this function to be called. sp
is not
automatically installed as a dependency of trajr.
TrajInPolygon(trj, boundary)
TrajInPolygon(trj, boundary)
trj |
Trajectory to test |
boundary |
A polygon defining the region to be tested against. Can be
any structure that |
Integer array with a value for each point in the trajectory. Values are: 0: point is strictly exterior to boundary; 1: point is strictly interior to boundary; 2: point lies on the relative interior of an edge of boundary; 3: point is a vertex of boundary
# Square arena boundary <- data.frame(x = c(-10, 10, 10, -10), y = c(-10, -10, 10, 10)) # Generate a random trajectory set.seed(1) trj <- TrajGenerate(n = 10, stepLength = 2, angularErrorSd = .15) # Test which points lie inside the boundary print(TrajInPolygon(trj, boundary)) ## [1] 1 1 1 1 1 1 0 0 0 0 0
# Square arena boundary <- data.frame(x = c(-10, 10, 10, -10), y = c(-10, -10, 10, 10)) # Generate a random trajectory set.seed(1) trj <- TrajGenerate(n = 10, stepLength = 2, angularErrorSd = .15) # Test which points lie inside the boundary print(TrajInPolygon(trj, boundary)) ## [1] 1 1 1 1 1 1 0 0 0 0 0
Calculates the cumulative length of a trajectory (or a portion of a trajectory), which is the total distance travelled along the trajectory.
TrajLength(trj, startIndex = 1, endIndex = nrow(trj))
TrajLength(trj, startIndex = 1, endIndex = nrow(trj))
trj |
Trajectory whose length is to be calculated. |
startIndex |
Index of the starting point. |
endIndex |
Index of the ending point. |
Numeric length of the trajectory.
Convenience function to return a sequence of points which are regularly spaced when plotted on a logarithmic axis.
TrajLogSequence(from, to, length.out)
TrajLogSequence(from, to, length.out)
from |
Starting value of the sequence. |
to |
End (maximal) value of the sequence. |
length.out |
Desired length of the sequence (non-negative). Rounded up if fractional. |
Returns the mean vector of the turning angles, as defined by Batschelet, (1981). A unit vector is created for each turning angle in the trajectory, and the centre-of-mass/mean vector is returned.
TrajMeanVectorOfTurningAngles(trj, compass.direction = NULL)
TrajMeanVectorOfTurningAngles(trj, compass.direction = NULL)
trj |
Trajectory object. |
compass.direction |
If not |
According to Batschelet (1981), r
may serve as a straightness index
ranging from 0 to 1, where r
is the length of the mean vector of
turning angles of a trajectory with constant step length. Values of r
near 1 indicating straighter paths. Hence, r =
Mod(TrajMeanVectorOfTurningAngles(trj))
, assuming that trj
has a
constant step length (e.g. has been rediscretized).
A complex number r
which represents the mean vector,
Mod(r)
is the length of the mean vector which varies between 0 and
1, Arg(r)
is the angle.
Batschelet, E. (1981). Circular statistics in biology. ACADEMIC PRESS, 111 FIFTH AVE., NEW YORK, NY 10003, 1981, 388.
TrajStraightness
, TrajAngles
,
TrajRediscretize
for resampling a trajectory to a constant
step length, TrajResampleTime
for resampling a trajectory to
a constant step time.
Calculates the mean or net velocity of a trajectory (or a portion of a trajectory). This is the velocity from the start point to the end point, ignoring the path that was taken.
TrajMeanVelocity(trj, startIndex = 1, endIndex = nrow(trj))
TrajMeanVelocity(trj, startIndex = 1, endIndex = nrow(trj))
trj |
Trajectory whose duration is to be calculated. |
startIndex |
Index of the starting point. |
endIndex |
Index of the ending point. |
Numeric duration of the trajectory, in time units.
This is the inverse of TrajSplit
.
TrajMerge(parts)
TrajMerge(parts)
parts |
A list containing one or more trajectories. The trajectories are concatenated together in order. |
A single trajectory.
trj <- TrajGenerate(n = 20) ntrj <- TrajMerge(TrajSplit(trj, c(3, 9, 20))) print(all(trj == ntrj)) ## [1] TRUE
trj <- TrajGenerate(n = 20) ntrj <- TrajMerge(TrajSplit(trj, c(3, 9, 20))) print(all(trj == ntrj)) ## [1] TRUE
Constructs a new trajectory by resampling the input trajectory to a
fixed step (or segment) length. By default, timing of frames is
lost, so speed and acceleration cannot be calculated on a
rediscretized trajectory. However, a constant speed may be applied
to the rediscretized trajectory (simConstantSpeed = TRUE
),
in which case the returned trajectory will have (almost) constant
speed, with average speed approximately equal to the average speed
of trj
.
TrajRediscretize(trj, R, simConstantSpeed = FALSE)
TrajRediscretize(trj, R, simConstantSpeed = FALSE)
trj |
The trajectory to be resampled. |
R |
rediscretization step length, in the spatial units of |
simConstantSpeed |
If TRUE, speeds are interpolated along the new
trajectory so that average speed is approximately the same as that of
|
Based on the appendix in Bovet and Benhamou, (1988).
A new trajectory with a constant segment length which follows
trj
.
Bovet, P., & Benhamou, S. (1988). Spatial analysis of animals' movements using a correlated random walk model. Journal of Theoretical Biology, 131(4), 419-433. doi:10.1016/S0022-5193(88)80038-9
Constructs a new trajectory by resampling the input trajectory to a fixed time interval. Points are linearly interpolated along the trajectory. Spatial and time units are preserved.
TrajResampleTime(trj, stepTime, newFps = NULL)
TrajResampleTime(trj, stepTime, newFps = NULL)
trj |
The trajectory to be resampled. |
stepTime |
The resampled trajectory step time. Each step in the new trajectory will have this duration. |
newFps |
Value to be stored as the FPS value in the new trajectory (see
|
Resampling with the original step time (i.e., 1/fps) can be used to fill in missing frames in a trajectory.
A new trajectory with a constant time interval for each step. Points
in the new trajectory are calculated by linearly interpolating along
trj
.
# Simulate a trajectory with steps every 5 hours set.seed(46) trj <- TrajGenerate(10, stepLength = 5, fps = 1/5, timeUnits = "hours", linearErrorSd = .8) # Resample to 1 hour steps resampled <- TrajResampleTime(trj, 1) par(mar = c(5, 4, .5, .5)) plot(trj, lwd = 2) points(trj, pch = 16) points(resampled, col = "red", draw.start.pt = FALSE)
# Simulate a trajectory with steps every 5 hours set.seed(46) trj <- TrajGenerate(10, stepLength = 5, fps = 1/5, timeUnits = "hours", linearErrorSd = .8) # Resample to 1 hour steps resampled <- TrajResampleTime(trj, 1) par(mar = c(5, 4, .5, .5)) plot(trj, lwd = 2) points(trj, pch = 16) points(resampled, col = "red", draw.start.pt = FALSE)
Reverses the direction of a trajectory, so that the starting point becomes the last point and vice versa.
TrajReverse(trj)
TrajReverse(trj)
trj |
The Trajectory to be reversed. |
A copy of trj
with direction reversed.
Rotates a trajectory by angle
(when relative
is FALSE
),
or so that angle(finish - start) == angle
(when relative
is
TRUE
).
TrajRotate(trj, angle = 0, origin = c(0, 0), relative = TRUE)
TrajRotate(trj, angle = 0, origin = c(0, 0), relative = TRUE)
trj |
The trajectory to be rotated. |
angle |
The angle of rotation in radians. Either the first and last
points in the rotated trajectory (when |
origin |
Trajectory is rotated about this point. |
relative |
If TRUE, |
A new trajectory which is a rotated version of the input trajectory.
Reads multiple trajectories from files, performs some basic sanity checks on them, and optionally smooths and scales them. Attempts to collect and report errors for multiple trajectories in a single call.
TrajsBuild( fileNames, fps = NULL, scale = NULL, spatialUnits = NULL, timeUnits = NULL, csvStruct = list(x = 1, y = 2, time = NULL), smoothP = 3, smoothN = 41, translateToOrigin = FALSE, rootDir = NULL, csvReadFn = function(filename, ...) utils::read.csv(filename, stringsAsFactors = FALSE, ...), ... )
TrajsBuild( fileNames, fps = NULL, scale = NULL, spatialUnits = NULL, timeUnits = NULL, csvStruct = list(x = 1, y = 2, time = NULL), smoothP = 3, smoothN = 41, translateToOrigin = FALSE, rootDir = NULL, csvReadFn = function(filename, ...) utils::read.csv(filename, stringsAsFactors = FALSE, ...), ... )
fileNames |
Vector of the names of CSV files containing trajectory
coordinates. All of the files must have the same columns. All file names
must be unique. If |
fps |
Vector of frames-per-second values corresponding to the
trajectories in |
scale |
Vector of scale values corresponding to the trajectories in
|
spatialUnits |
Abbreviated name of spatial coordinate units after scaling, e.g. "m". |
timeUnits |
Abbreviated name of temporal units, e.g. "s". |
csvStruct |
A list which identifies the columns in each CSV file which contain x-, y-, and optionally time-values. |
smoothP |
Filter order to be used for Savitzky-Golay smoothing (see
|
smoothN |
Filter length to be used for Savitzky-Golay smoothing (must be
odd, see |
translateToOrigin |
If TRUE, each trajectory is translated so that its starting point is at (0, 0). |
rootDir |
Optional name of a top level directory which contains the CSV
files. If |
csvReadFn |
Function used to read the CSV files. Required to accept
arguments |
... |
Additional arguments passed to |
If rootDir
is not null, it should be the name of a directory which is
searched for the files in fileNames
. The found files are then used as
the list of files to be read in. This may be useful when the names of the
files are known, but their exact location within a directory structure is not
known.
For each file name in fileNames
, reads the file by calling
csvReadFn
to obtain a set of coordinates and optionally times. A
Trajectory is then constructed by passing the coordinates to
TrajFromCoords
, passing in the appropriate fps
value,
and x, y and time column names/indices from csvStruct
. If scale
is not NULL
, the trajectory is scaled by calling
TrajScale
. If smoothP
and smoothN
are not
NULL
, the trajectory is smoothed by calling
TrajSmoothSG
.
A list of trajectories.
read.csv
, TrajFromCoords
,
TrajScale
, TrajSmoothSG
,
TrajTranslate
## Not run: # Names of CSV files containing trajectory coordinates fileNames <- c('xy001.csv', 'xy003.csv', 'xy004.csv') # The files are all located somewhere under this directory rootDir <- '.' # Scale for these files is 1 / pixels per metre scale <- c('1/1200', '1/1350', '1/1300') # Files have columns y, x csvStruct <- list(x = 2, y = 1) # Apply default smoothing, and the files are formatted as conventional CSV, # so there's no need to specify csvReadFn trjs <- TrajsBuild(fileNames, fps = 50, scale = scale, units = "m", csvStruct = csvStruct, rootDir = rootDir) ## End(Not run)
## Not run: # Names of CSV files containing trajectory coordinates fileNames <- c('xy001.csv', 'xy003.csv', 'xy004.csv') # The files are all located somewhere under this directory rootDir <- '.' # Scale for these files is 1 / pixels per metre scale <- c('1/1200', '1/1350', '1/1300') # Files have columns y, x csvStruct <- list(x = 2, y = 1) # Apply default smoothing, and the files are formatted as conventional CSV, # so there's no need to specify csvReadFn trjs <- TrajsBuild(fileNames, fps = 50, scale = scale, units = "m", csvStruct = csvStruct, rootDir = rootDir) ## End(Not run)
Scales the cartesian coordinates in a trajectory, for example, to convert units from pixels to metres.
TrajScale(trj, scale, units, yScale = scale)
TrajScale(trj, scale, units, yScale = scale)
trj |
The trajectory to be scaled. |
scale |
Scaling factor to be applied to the trajectory coordinates. |
units |
Character specifying the spatial units after scaling, e.g. "m" or "metres" |
yScale |
Optional scaling factor to be applied to the y-axis, which may
be specified if the original coordinates are not square. Defaults to
|
new scaled trajectory.
set.seed(42) trj <- TrajGenerate() # original trajectory units are pixels, measured as having # 47 pixels in 10 mm, so to convert to metres, scale the # trajectory by the approriate factor, i.e. (size in metres) / (size in pixels). scale <- .01 / 47 scaled <- TrajScale(trj, scale, "m")
set.seed(42) trj <- TrajGenerate() # original trajectory units are pixels, measured as having # 47 pixels in 10 mm, so to convert to metres, scale the # trajectory by the approriate factor, i.e. (size in metres) / (size in pixels). scale <- .01 / 47 scaled <- TrajScale(trj, scale, "m")
Calculates the sinuosity of a (constant step length) trajectory as defined by
Bovet & Benhamou (1988), eqn 2, which is: where
is the standard deviation of the step turning angles and
is the mean step length. A corrected sinuosity index is available as the
function
TrajSinuosity2
which handles a wider range of
variations in step angles.
TrajSinuosity(trj, compass.direction = NULL)
TrajSinuosity(trj, compass.direction = NULL)
trj |
Trajectory to calculate sinuosity of. |
compass.direction |
if not |
If your trajectory does not have a constant step length, it should be
_rediscretized_ by calling TrajRediscretize
before calling this
function.
The sinuosity of trj
.
Bovet, P., & Benhamou, S. (1988). Spatial analysis of animals' movements using a correlated random walk model. Journal of Theoretical Biology, 131(4), 419-433. doi:10.1016/S0022-5193(88)80038-9
TrajSinuosity2
for a corrected version of sinuosity,
TrajAngles
for the turning angles in a trajectory,
TrajStepLengths
for the step lengths, and
TrajRediscretize
for resampling to a constant step length.
Calculates the sinuosity of a trajectory as defined by Benhamou (2004), equation 8. This is a corrected version of the sinuosity index defined in Bovet & Benhamou (1988), which is suitable for a wider range of turning angle distributions, and does not require a constant step length.
TrajSinuosity2(trj, compass.direction = NULL)
TrajSinuosity2(trj, compass.direction = NULL)
trj |
A Trajectory object. |
compass.direction |
if not |
This function implements equation 8 from Benhamou (2004):
where is the mean step length,
is the mean
cosine of turning angles, and
is the coefficient of variation of
the step length.
Benhamou, S. (2004). How to reliably estimate the tortuosity of an animal's path. Journal of Theoretical Biology, 229(2), 209-220. doi:10.1016/j.jtbi.2004.03.016
TrajSinuosity
for the uncorrected sinuosity index.
Builds a data frame by combining rows of statistical values for multiple trajectories. The statistics for each trajectory are defined by the caller in a user defined function - see the example for one way to achieve this.
TrajsMergeStats( trjs, statsFn, progressBar = c("none", "text", "win", "tk"), check.names = TRUE, ... )
TrajsMergeStats( trjs, statsFn, progressBar = c("none", "text", "win", "tk"), check.names = TRUE, ... )
trjs |
List of trajectories to be characterised. |
statsFn |
Function to calculate statistics of interest for a single trajectory. |
progressBar |
Displays an optional progressbar, which may be helpful if
processing is very slow. The progressbar is displayed by printing to the
console, by using |
check.names |
Passed to |
... |
Additional arguments passed to |
Any NULL valued statistics are converted to NAs.
## Not run: # Define a function which calculates some statistics # of interest for a single trajectory characteriseTrajectory <- function(trj) { # Measures of speed derivs <- TrajDerivatives(trj) mean_speed <- mean(derivs$speed) sd_speed <- sd(derivs$speed) # Resample to constant step length. # Step length must be appropriate for the trajectory resampled <- TrajRediscretize(trj, 2) # Measures of straightness sinuosity <- TrajSinuosity2(resampled) Emax <- TrajEmax(resampled) # Periodicity resampled <- TrajRediscretize(trj, .001) corr <- TrajDirectionAutocorrelations(resampled, round(nrow(resampled) / 4)) first_min <- TrajDAFindFirstMinimum(corr) # Return a list with all of the statistics for this trajectory list(mean_speed = mean_speed, sd_speed = sd_speed, sinuosity = sinuosity, Emax = Emax, first_min_deltaS = first_min[1], first_min_C = first_min[2]) } trjs <- TrajsBuild(filenames) stats <- TrajsMergeStats(trjs, characteriseTrajectory) ## End(Not run)
## Not run: # Define a function which calculates some statistics # of interest for a single trajectory characteriseTrajectory <- function(trj) { # Measures of speed derivs <- TrajDerivatives(trj) mean_speed <- mean(derivs$speed) sd_speed <- sd(derivs$speed) # Resample to constant step length. # Step length must be appropriate for the trajectory resampled <- TrajRediscretize(trj, 2) # Measures of straightness sinuosity <- TrajSinuosity2(resampled) Emax <- TrajEmax(resampled) # Periodicity resampled <- TrajRediscretize(trj, .001) corr <- TrajDirectionAutocorrelations(resampled, round(nrow(resampled) / 4)) first_min <- TrajDAFindFirstMinimum(corr) # Return a list with all of the statistics for this trajectory list(mean_speed = mean_speed, sd_speed = sd_speed, sinuosity = sinuosity, Emax = Emax, first_min_deltaS = first_min[1], first_min_C = first_min[2]) } trjs <- TrajsBuild(filenames) stats <- TrajsMergeStats(trjs, characteriseTrajectory) ## End(Not run)
Smooths a trajectory using a Savitzky-Golay smoothing filter.
TrajSmoothSG(trj, p = 3, n = p + 3 - p%%2, ...)
TrajSmoothSG(trj, p = 3, n = p + 3 - p%%2, ...)
trj |
The trajectory to be smoothed. |
p |
polynomial order (passed to |
n |
Filter length (or window size), must be an odd number. Passed to
|
... |
Additional arguments are passed to
|
Consider carefully the effects of smoothing a trajectory with temporal gaps
in the data. If the smoothed trajectory is used to derive speed and/or
acceleration, it may be advisable to fill in the gaps before smoothing,
possibly by calling TrajResampleTime
.
A new trajectory which is a smoothed version of the input trajectory.
set.seed(3) trj <- TrajGenerate(500, random = TRUE, angularErrorSd = .25) smoothed <- TrajSmoothSG(trj, 3, 31) plot(trj) plot(smoothed, col = "red", add = TRUE)
set.seed(3) trj <- TrajGenerate(500, random = TRUE, angularErrorSd = .25) smoothed <- TrajSmoothSG(trj, 3, 31) plot(trj) plot(smoothed, col = "red", add = TRUE)
Calculates and returns a list of time intervals during which speed is slower
and/or faster than specified values. Speed is calculated by taking the
modulus of velocity (TrajVelocity
).
TrajSpeedIntervals( trj, fasterThan = NULL, slowerThan = NULL, interpolateTimes = TRUE, diff = c("backward", "central", "forward") )
TrajSpeedIntervals( trj, fasterThan = NULL, slowerThan = NULL, interpolateTimes = TRUE, diff = c("backward", "central", "forward") )
trj |
Trajectory to be analysed. |
fasterThan , slowerThan
|
If not |
interpolateTimes |
If |
diff |
Method used to calculate speed, see |
A data frame of class "TrajSpeedIntervals", each row is an interval, columns are:
startFrame |
Indices of frames at the start of each interval. |
stopFrame |
Indices of frames at the end of each interval. |
startTime |
Time since start of trajectory at the start of each interval. |
stopTime |
Time since start of trajectory at the end of each interval |
duration |
Duration of each interval. |
The data frame will also have non-standard attributes:
trajectory |
Value of the |
slowerThan |
Value of the |
fasterThan |
Value of the |
speed |
Data frame with columns |
derivs |
Value returned by calling |
TrajVelocity
for calculating trajectory velocity,
plot.TrajSpeedIntervals
for plotting speed over time with
intervals highlighted.
# Plot speed, highlighting intervals where speed drops below 50 units/sec set.seed(4) trj <- TrajGenerate(200, random = TRUE) smoothed <- TrajSmoothSG(trj, 3, 101) intervals <- TrajSpeedIntervals(smoothed, diff = "central", slowerThan = 50, fasterThan = NULL) plot(intervals) # Report the duration of the longest period of low speed cat(sprintf("Duration of the longest low-speed interval was %g secs\n", max(intervals$duration)))
# Plot speed, highlighting intervals where speed drops below 50 units/sec set.seed(4) trj <- TrajGenerate(200, random = TRUE) smoothed <- TrajSmoothSG(trj, 3, 101) intervals <- TrajSpeedIntervals(smoothed, diff = "central", slowerThan = 50, fasterThan = NULL) plot(intervals) # Report the duration of the longest period of low speed cat(sprintf("Duration of the longest low-speed interval was %g secs\n", max(intervals$duration)))
Every point in trj
will belong to exactly one of the returned
sections. Note that this function will happily create single point
trajectories.
TrajSplit(trj, idx)
TrajSplit(trj, idx)
trj |
The trajectory to be split |
idx |
Indices of splits. Each new section starts at one of these indices. |
A list containing one or more trajectories. The first trajectory in
the list contains the first points from trj
. Remaining trajectories
contain the points starting from each of the idx
values, in
ascending order.
TrajMerge
, TrajSplitAtFirstCrossing
This is basically a wrapper around TrajInPolygon
and
TrajSplit
.
TrajSplitAtFirstCrossing(trj, boundary)
TrajSplitAtFirstCrossing(trj, boundary)
trj |
The trajectory to split. |
boundary |
A polygon defining the boundary. Can be any structure that
|
A list with 1 or 2 elements. If trj
lies entirely inside or
outside boundary
, then the list simply contains trj
. If
trj
crosses the boundary, then the list contains 2 trajectories. The
first is the longest part of trj
that lies entirely inside or
outside boundary
, and the second is the remainder of trj
.
# Square arena boundary <- data.frame(x = c(-10, 10, 10, -10), y = c(-10, -10, 10, 10)) # Generate a random trajectory set.seed(1) trj <- TrajGenerate(n = 8, stepLength = 3, angularErrorSd = .4) # Split the trajectory where it crosses the boundary l <- TrajSplitAtFirstCrossing(trj, boundary) # Plot the boundary and the two trajectories plot(NULL, xlim = range(c(boundary$x, trj$x)), ylim = range(c(boundary$y, trj$y)), asp = 1) polygon(boundary, border = "brown", lwd = 2) lines(l[[1]], col = "#2040ff80", lwd = 3) lines(l[[2]], col = "#ff204080", lwd = 3)
# Square arena boundary <- data.frame(x = c(-10, 10, 10, -10), y = c(-10, -10, 10, 10)) # Generate a random trajectory set.seed(1) trj <- TrajGenerate(n = 8, stepLength = 3, angularErrorSd = .4) # Split the trajectory where it crosses the boundary l <- TrajSplitAtFirstCrossing(trj, boundary) # Plot the boundary and the two trajectories plot(NULL, xlim = range(c(boundary$x, trj$x)), ylim = range(c(boundary$y, trj$y)), asp = 1) polygon(boundary, border = "brown", lwd = 2) lines(l[[1]], col = "#2040ff80", lwd = 3) lines(l[[2]], col = "#ff204080", lwd = 3)
Replaces NAs in a single column of a data frame with an imputed uninformative
numeric replacement value, so that a principal component analysis can be
applied without discarding data. Optionally adds a new "flag" column which
contains 1
for each row which originally contained NA, otherwise
0
.
TrajsStatsReplaceNAs( df, column, replacementValue = mean(df[, column], na.rm = TRUE), flagColumn = NULL )
TrajsStatsReplaceNAs( df, column, replacementValue = mean(df[, column], na.rm = TRUE), flagColumn = NULL )
df |
Data frame to be adjusted. |
column |
Name or index of the column to be adjusted. |
replacementValue |
Numeric value to use instead of NA. |
flagColumn |
If not NULL, specifies the name of a new column to be added to the data frame, with value 0 for non-NA rows, 1 for NA rows. The column is added regardless of whether there are any NAs in the data. |
A copy of df
with NAs replaced in column
.
df <- data.frame(x = c(1, 2, 3), y = c(NA, 5, 6), z = c(NA, NA, 9)) # Eliminate NAs in y, add a flag column, ignore other NAs df <- TrajsStatsReplaceNAs(df, "y", flagColumn = "y.was.NA") print(df)
df <- data.frame(x = c(1, 2, 3), y = c(NA, 5, 6), z = c(NA, NA, 9)) # Eliminate NAs in y, add a flag column, ignore other NAs df <- TrajsStatsReplaceNAs(df, "y", flagColumn = "y.was.NA") print(df)
Returns the lengths of all of the steps in a list of trajectories
TrajsStepLengths(trjs)
TrajsStepLengths(trjs)
trjs |
A list of |
A numeric vector containing the lengths of every step in every trajectory.
## Not run: trjs <- TrajsBuild(fileNames, scale = scale, units = "m") # Print a summary about the step sizes across all trajectories print(summary(TrajsStepLengths(trjs))) ## End(Not run)
## Not run: trjs <- TrajsBuild(fileNames, scale = scale, units = "m") # Print a summary about the step sizes across all trajectories print(summary(TrajsStepLengths(trjs))) ## End(Not run)
Returns the lengths of each step in a trajectory.
TrajStepLengths(trj)
TrajStepLengths(trj)
trj |
Trajectory to query. |
Calculates the straightness index of a trajectory, , where
D
is the beeline distance between the first and last points in the
trajectory,and L
is the path length travelled (Batschelet, 1981).
Benhamou (2004) considers the straightness index to be a reliable measure of
the efficiency of a directed walk, but inapplicable to random trajectories.
The straightness index of a random walk tends towards zero as the number of
steps increases, hence should only be used to compare the tortuosity of
random walks consisting of a similar number of steps.
TrajStraightness(trj)
TrajStraightness(trj)
trj |
Trajectory to calculate straightness of. |
The straightness index is also known as the net-to-gross displacement ratio.
According to Batschelet (1981), this value (termed d) is an
approximation of r, which is the length of the mean vector of turning
angles of a constant step-length trajectory (see
TrajMeanVectorOfTurningAngles
and
TrajRediscretize
for creating a constant step-length
trajectory).
The straightness index of trj
, which is a value between 0
(infinitely tortuous) to 1 (a straight line).
Batschelet, E. (1981). Circular statistics in biology. ACADEMIC PRESS, 111 FIFTH AVE., NEW YORK, NY 10003, 1981, 388.
Benhamou, S. (2004). How to reliably estimate the tortuosity of an animal's path. Journal of Theoretical Biology, 229(2), 209-220. doi:10.1016/j.jtbi.2004.03.016
TrajDistance
for trajectory distance (or
displacement), and TrajLength
for trajectory path length.
Shifts an entire trajectory by the specified delta x and y.
TrajTranslate(trj, dx, dy, dt = 0)
TrajTranslate(trj, dx, dy, dt = 0)
trj |
The Trajectory to be translated. |
dx |
Delta x. |
dy |
Delta y. |
dt |
Delta time. |
A new trajectory which is a translated version of the input trajectory.
# Shift a trajectory so that its origin is (10, 15). # Note that trajectories created by TrajGenerate always start at (0, 0) set.seed(42) trj <- TrajGenerate() trj <- TrajTranslate(trj, 10, 15) # Translate a trajectory so its origin (0, 0) and it starts at time 0 trj <- TrajTranslate(trj, -trj$x[1], -trj$y[1], -trj$time[1])
# Shift a trajectory so that its origin is (10, 15). # Note that trajectories created by TrajGenerate always start at (0, 0) set.seed(42) trj <- TrajGenerate() trj <- TrajTranslate(trj, 10, 15) # Translate a trajectory so its origin (0, 0) and it starts at time 0 trj <- TrajTranslate(trj, -trj$x[1], -trj$y[1], -trj$time[1])
The velocity is approximated at each point of the trajectory using first-order finite differences. Central, forward or backward differences can be used. Central differences yield a more accurate approximation if the velocity is smooth. As a practical guide, if velocity doesn't change much between steps, use central differences. If it changes substantially (and not just as an artifact of recording noise), then use either forward or backward differences.
TrajVelocity(trj, diff = c("central", "forward", "backward"))
TrajVelocity(trj, diff = c("central", "forward", "backward"))
trj |
Trajectory whose velocity is to be calculated. |
diff |
Type of difference to be calculated, one of "central" (the default), "forward" or "backward". |
Intuitively, think of the central difference velocity at a point as the mean of the velocities of the two adjacent steps. Forward difference velocity is the velocity of the step starting at the point. Backward difference is the velocity of the step ending at the point.
A vector of complex numbers representing the velocity at each point
along the trajectory. The modulus (Mod(v)
) is the magnitude of the
velocity, i.e. the speed; the argument (Arg(v)
) is the direction of
the velocity; the real part (Re(v)
) is velocity in the X direction;
and the imaginary part (Im(v)
) is velocity in the Y direction. The
vector has an attribute, trj
, with the trajectory as its value. If
diff
is "central"
, the first and last velocity values are
NA
since velocity cannot be calculated for them. If diff
is
"forward"
, the last value will be NA, and if diff
is
"backward"
, the first value will be NA.
TrajAcceleration
for calculating acceleration;
TrajResampleTime
and TrajRediscretize
to resample
a trajectory to fixed time or length steps; TrajSpeedIntervals
for calculating when speed crosses some threshold; Finite differences on
Wikipedia.
set.seed(11) trj <- TrajGenerate(100) # calculate velocity vel <- TrajVelocity(trj) # Obtain speed over time, with NAs removed speed <- na.omit(data.frame(speed = Mod(vel), time = trj$time)) plot(speed ~ time, speed, type = 'l')
set.seed(11) trj <- TrajGenerate(100) # calculate velocity vel <- TrajVelocity(trj) # Obtain speed over time, with NAs removed speed <- na.omit(data.frame(speed = Mod(vel), time = trj$time)) plot(speed ~ time, speed, type = 'l')