| Title: | An R package for reading and writing movement data |
|---|---|
| Description: | An R package for reading and writing movement data. |
| Authors: | Mikkel Roald-Arbøl [aut, cre] (ORCID: <https://orcid.org/0000-0002-9998-0058>) |
| Maintainer: | Mikkel Roald-Arbøl <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 0.4.1 |
| Built: | 2026-06-06 05:54:07 UTC |
| Source: | https://github.com/animovement/aniread |
Reads a calibration recording and computes calibration values. Spin the ball a known number of times in one direction while recording.
calibrate_trackball( path, ball_diameter, ball_rotations, col_dx = "x", col_dy = "y" )calibrate_trackball( path, ball_diameter, ball_rotations, col_dx = "x", col_dy = "y" )
path |
Path to calibration CSV file. |
ball_diameter |
Diameter of the trackball in desired output units (e.g., mm or cm). |
ball_rotations |
Number of complete rotations performed. |
col_dx |
Column name for x-axis values. |
col_dy |
Column name for y-axis values. |
A list with two elements:
counts_per_rotation: Sensor counts per full rotation (for ball_calibration in read_trackball).
calibration_factor: Distance per sensor count (for set_unit_space).
Downloads sample data for different animal tracking software and returns the path to the downloaded file. The function caches the data to avoid repeated downloads.
get_sample_data( source, dataset = NULL, cache_dir = tempdir(), quiet = FALSE, list_datasets = FALSE )get_sample_data( source, dataset = NULL, cache_dir = tempdir(), quiet = FALSE, list_datasets = FALSE )
source |
Character string specifying either a tracking software name or a URL. Currently supported software names:
Alternatively, provide a URL string (starting with "http://" or "https://") to download a file from a custom location. |
dataset |
Character string specifying which dataset to download for sources
that have multiple options. If NULL (default), the first listed dataset is used.
Call |
cache_dir |
Character string specifying the directory where to cache the downloaded
files. Defaults to a temporary directory using |
quiet |
TRUE/FALSE. TRUE suppresses inform messages. |
list_datasets |
TRUE/FALSE. If TRUE, prints available sources and datasets. Can be called with or without specifying a source. |
The function downloads sample data and caches it locally. If the file already exists in the cache directory, it will use the cached version instead of downloading again.
Some sources have multiple datasets available. The first dataset listed for each
source is used by default when dataset = NULL.
Special handling for TRex datasets: TRex datasets are distributed as zip files containing multiple individual tracking files (one per animal). The function automatically extracts these and returns a vector of paths to the individual files.
The predefined data sources are hosted at:
https://gin.g-node.org/neuroinformatics/movement-test-data
https://github.com/animovement/movement-data
Character string (or vector) with the path(s) to the downloaded file(s).
For TRex datasets, returns a character vector of paths to the individual tracking
files. For all other sources, returns a single file path. Returns NULL invisibly
if list_datasets = TRUE.
## Not run: # See all available sources and datasets get_sample_data(list_datasets = TRUE) # See datasets for a specific source get_sample_data("sleap", list_datasets = TRUE) # Get default dataset for SLEAP path <- get_sample_data("sleap") # Get a specific SLEAP dataset path <- get_sample_data("sleap", dataset = "zebras_drone") # Get TRex data (returns vector of paths to individual files) paths <- get_sample_data("trex") # Download from a custom URL path <- get_sample_data("https://example.com/data/tracking.csv") ## End(Not run)## Not run: # See all available sources and datasets get_sample_data(list_datasets = TRUE) # See datasets for a specific source get_sample_data("sleap", list_datasets = TRUE) # Get default dataset for SLEAP path <- get_sample_data("sleap") # Get a specific SLEAP dataset path <- get_sample_data("sleap", dataset = "zebras_drone") # Get TRex data (returns vector of paths to individual files) paths <- get_sample_data("trex") # Download from a custom URL path <- get_sample_data("https://example.com/data/tracking.csv") ## End(Not run)
Reads movement data from a Parquet file and returns an aniframe object. Parquet files are required as they preserve the metadata necessary for aniframe objects.
read_aniframe(path)read_aniframe(path)
path |
Path to a Parquet file. |
An aniframe object.
## Not run: data <- read_aniframe("movement_data.parquet") ## End(Not run)## Not run: data <- read_aniframe("movement_data.parquet") ## End(Not run)
Read a data frame from AnimalTA. AnimalTA exports tracking
data in image (top-left) coordinates; the reader reflects y so the
returned aniframe is in the conventional bottom_left origin.
read_animalta(path, detailed = FALSE, video_height = NULL)read_animalta(path, detailed = FALSE, video_height = NULL)
path |
An AnimalTA data frame |
detailed |
Animal export either raw (default) or detailed data files. We only have limited support for detailed data. |
video_height |
Optional numeric height of the source video frame in
pixels. AnimalTA does not record this in the export, so when not
supplied the maximum observed |
a movement dataframe
Chiara, V., & Kim, S.-Y. (2023). AnimalTA: A highly flexible and easy-to-use program for tracking and analysing animal movement in different environments. Methods in Ecology and Evolution, 14, 1699–1707. doi:0.1111/2041-210X.14115.
Reads CSV files output by Anipose's 3D triangulation pipeline and converts them into aniframe format. The function handles the pivot from wide format (one column per keypoint-coordinate combination) to long format with separate rows for each keypoint at each time point.
read_anipose(path, unit_space = "mm")read_anipose(path, unit_space = "mm")
path |
Character string specifying the path to an Anipose CSV file.
Typically these are found in the |
unit_space |
Character string specifying the spatial units of the coordinates. This should match the units you used for your calibration board dimensions (e.g., "mm", "cm", "m"). Default is "mm". |
An aniframe (tibble) with the following columns:
time: Frame number
keypoint: Name of the tracked body part
x, y, z: 3D coordinates in the specified units
confidence: Mean detection confidence across cameras (0-1 scale)
The aniframe includes metadata about the data source, filename, spatial units, and coordinate system.
Anipose outputs CSV files with columns like bodypart_x, bodypart_y,
bodypart_z, bodypart_error, bodypart_ncams, and bodypart_score for
each tracked keypoint. The coordinates are in whatever units you specified
for your calibration board dimensions.
## Not run: # Read anipose data with default millimeter units pose_data <- read_anipose("path/to/pose-3d/trial001.csv") # Read with centimeter units pose_data <- read_anipose("path/to/pose-3d/trial001.csv", unit_space = "cm") ## End(Not run)## Not run: # Read anipose data with default millimeter units pose_data <- read_anipose("path/to/pose-3d/trial001.csv") # Read with centimeter units pose_data <- read_anipose("path/to/pose-3d/trial001.csv", unit_space = "cm") ## End(Not run)
Read a Bonsai data frame. Bonsai centroid coordinates
come from camera/video pipelines that use image (top-left) origin;
the reader reflects y so the returned aniframe is in the
conventional bottom_left origin. Bonsai workflows are
user-defined and the output CSV does not record video resolution,
so pass video_height to get an accurate flip — otherwise max(y)
is used as a fallback.
read_bonsai(path, video_height = NULL)read_bonsai(path, video_height = NULL)
path |
Path to a Bonsai data file |
video_height |
Optional numeric height of the source video frame in pixels. |
a movement dataframe
Reads a C3D file and returns the data as an aniframe with associated metadata including source software, units, and sampling rate.
read_c3d(path)read_c3d(path)
path |
Path to a |
An aniframe with columns time, keypoint, x, y, and z.
Metadata includes source software, filename, time/space units, and
sampling rate. Time is 0-indexed (in frames).
c3dr::c3d_read() for lower-level C3D access.
Reads a file and selects/renames specified columns to create an aniframe.
read_custom( path, cols, variables_what = NULL, variables_when = NULL, variables_where = NULL, metadata = list() )read_custom( path, cols, variables_what = NULL, variables_when = NULL, variables_where = NULL, metadata = list() )
path |
Character string specifying the path to the file to read. |
cols |
A named vector specifying which columns to keep and how to rename
them, e.g. |
variables_what |
Character vector of identity columns that together define a unique entity. Uses aniframe defaults if NULL. |
variables_when |
Character vector of temporal columns that together define a unique timepoint. Uses aniframe defaults if NULL. |
variables_where |
Character vector of spatial columns that together define position. If NULL, detected from data. |
metadata |
A list of metadata to attach to the resulting aniframe. Default is an empty list. |
An aniframe with the selected and renamed columns, and attached metadata.
## Not run: # Simple case: rename columns to standard names, use defaults read_custom("data.csv", cols = c(time = "frame", x = "pos_x", y = "pos_y")) # With identity variable read_custom( "data.csv", cols = c(track = "track_id", time = "frame", x = "pos_x", y = "pos_y"), variables_what = "track" ) # Full specification with trials read_custom( "data.csv", cols = c( id = "animal_id", trial = "trial_num", frame = "frame_idx", x = "x_coord", y = "y_coord" ), variables_what = "id", variables_when = c("trial", "frame") ) # Using column positions read_custom("data.csv", cols = c(time = 1, x = 2, y = 3)) ## End(Not run)## Not run: # Simple case: rename columns to standard names, use defaults read_custom("data.csv", cols = c(time = "frame", x = "pos_x", y = "pos_y")) # With identity variable read_custom( "data.csv", cols = c(track = "track_id", time = "frame", x = "pos_x", y = "pos_y"), variables_what = "track" ) # Full specification with trials read_custom( "data.csv", cols = c( id = "animal_id", trial = "trial_num", frame = "frame_idx", x = "x_coord", y = "y_coord" ), variables_what = "id", variables_when = c("trial", "frame") ) # Using column positions read_custom("data.csv", cols = c(time = 1, x = 2, y = 3)) ## End(Not run)
Read files from DeepLabCut (DLC) in either csv or h5 format.
DeepLabCut stores predictions in image (top-left) coordinates; the
reader reflects y so the returned aniframe is in the conventional
bottom_left origin. DLC's csv/h5 exports do not contain the source
video resolution (it lives in the project's config.yaml), so pass
video_height to get an accurate flip — otherwise max(y) is used
as a fallback.
read_deeplabcut(path, video_height = NULL)read_deeplabcut(path, video_height = NULL)
path |
Path to a DeepLabCut data file |
video_height |
Optional numeric height of the source video frame in pixels. |
an aniframe
Reads a FastTrack tracking result file (.txt format) and returns an
aniframe with keypoints for head, body, and tail positions.
FastTrack stores positions in image (top-left) coordinates; the
reader reflects y so the returned aniframe is in the conventional
bottom_left origin. The tracking file does not record the source
video resolution, so pass video_height to get an accurate flip —
otherwise max(y) is used as a fallback.
read_fasttrack(path, video_height = NULL)read_fasttrack(path, video_height = NULL)
path |
Path to a FastTrack tracking.txt file. |
video_height |
Optional numeric height of the source video frame in pixels. |
An aniframe
This helper loads a FicTrac *.dat file, keeps only the timestamp and
2‑D position columns, converts the timestamps to seconds, and returns the
result as an aniframe object. If the physical ball radius is supplied,
the positions are scaled accordingly and the spatial unit metadata is set.
read_fictrac(path, ball_radius = NULL, unit_ball_radius = "cm")read_fictrac(path, ball_radius = NULL, unit_ball_radius = "cm")
path |
Character. Path to the FicTrac |
ball_radius |
Numeric (optional). Physical radius of the tracking ball.
When supplied the |
unit_ball_radius |
Character. Unit of |
An aniframe object with columns time, x, and y. Metadata
includes the source ("fictrac"), original filename, sampling rate,
time unit ("s"), space unit (either "none" or the value of
unit_ball_radius), and a Cartesian 2‑D coordinate system.
## Not run: # Assuming you have a FicTrac file called "fly1.dat" traj <- read_fictrac("fly1.dat", ball_radius = 0.5, unit_ball_radius = "cm") head(traj) ## End(Not run)## Not run: # Assuming you have a FicTrac file called "fly1.dat" traj <- read_fictrac("fly1.dat", ball_radius = 0.5, unit_ball_radius = "cm") head(traj) ## End(Not run)
Imports FreeMoCap motion capture data from a CSV file and converts it to an aniframe format. The function expects data in tidy format (typically files ending in 'by_frame.csv') and will error if other formats are detected.
read_freemocap(path)read_freemocap(path)
path |
Character string specifying the path to the FreeMoCap CSV file. Should be a file ending in 'by_frame.csv'. |
An aniframe object with the following characteristics:
Metadata indicating source as "freemocap"
Spatial units in millimeters (mm)
3D Cartesian coordinate system
Time units in seconds (if timestamps available) or frames (if not)
Start datetime in metadata (if timestamps available)
## Not run: # Read FreeMoCap data mocap_data <- read_freemocap("path/to/data_by_frame.csv") # Check metadata aniframe::get_metadata(mocap_data) ## End(Not run)## Not run: # Read FreeMoCap data mocap_data <- read_freemocap("path/to/data_by_frame.csv") # Check metadata aniframe::get_metadata(mocap_data) ## End(Not run)
idtracker.ai stores trajectories in image (top-left) coordinates; the
reader reflects y so the returned aniframe is in the conventional
bottom_left origin. For h5 files the frame height is read directly
from the /height dataset. CSV exports do not include the frame
height, so pass video_height explicitly to get an accurate flip
(otherwise max(y) is used as a fallback).
read_idtracker( path, path_probabilities = NULL, version = 6, video_height = NULL )read_idtracker( path, path_probabilities = NULL, version = 6, video_height = NULL )
path |
Path to an idtracker.ai data frame |
path_probabilities |
Path to a csv file with probabilities. Only needed if you are reading csv files as they are included in h5 files. |
version |
idtracker.ai version. Currently only v6 output is implemented |
video_height |
Optional numeric height of the source video frame in pixels. Overrides the value read from the h5 file when both are available. |
a movement dataframe
Read csv files from LightningPose (LP). Like DeepLabCut, the source
is in image (top-left) coordinates and the reader reflects y to
bottom_left.
read_lightningpose(path, video_height = NULL)read_lightningpose(path, video_height = NULL)
path |
Path to a LightningPose data file |
video_height |
Optional numeric height of the source video frame
in pixels. Falls back to |
an aniframe
Imports pose estimation data from netCDF/HDF5 files created by the movement Python package.
read_movement(path, video_height = NULL)read_movement(path, video_height = NULL)
path |
Path to an HDF5 file ( |
video_height |
Optional numeric height of the source video frame
in pixels. movement does not currently store this in the netCDF
attributes, so without it |
The movement package stores pose estimation data in a specific netCDF/HDF5 structure
with datasets for individuals, keypoints, position coordinates, confidence
scores, and time. This function reads that structure and reshapes it into
a tidy aniframe format. The underlying tracking software outputs
image (top-left) coordinates, so the reader reflects y to
bottom_left before returning.
An aniframe
Reads CSV files exported from Octron video segmentation software.
The function parses the metadata header and returns tracking data
as an aniframe with centroid positions, bounding box corners, and
shape descriptors. Octron stores positions in image (top-left)
coordinates; the reader reflects y so the returned aniframe is in
the conventional bottom_left origin. The frame height is read
from the CSV header (video_height:) by default.
read_octron( path, keep_bbox = FALSE, video_height = NULL, method = c("weighted", "largest", "segments"), properties = "all" )read_octron( path, keep_bbox = FALSE, video_height = NULL, method = c("weighted", "largest", "segments"), properties = "all" )
path |
Path to the Octron CSV file. |
keep_bbox |
Keep bounding box coordinates? Default FALSE. |
video_height |
Optional numeric height of the source video frame in pixels. Overrides the value parsed from the CSV header when both are available. |
method |
Strategy for resolving frames where Octron emitted multiple mask segments per track. One of:
When the source CSV contains no tuple-valued rows, all three methods produce identical numeric output. |
properties |
Which scikit-image / Octron region-property columns to read. Newer Octron exports include dozens of per-segment shape, intensity and moment descriptors that can dominate read time on tuple-heavy files. One of:
When |
Newer Octron exports (>= the multi-blob handling in
OCTRON-GUI #63)
may emit per-segment columns as tuple-strings, e.g. "(120.5, 85.3)",
when YOLO detects multiple disconnected mask segments belonging to
the same track in a single frame. The method argument controls
how those rows are reduced to scalar values, or whether they are
expanded into one row per segment.
An aniframe
SLEAP stores predictions in image (top-left) coordinates; the reader
reflects y so the returned aniframe is in the conventional
bottom_left origin. SLEAP's analysis h5 export does not include
the source video resolution, so pass video_height to get an
accurate flip — otherwise max(y) is used as a fallback.
read_sleap(path, video_height = NULL)read_sleap(path, video_height = NULL)
path |
A SLEAP analysis data frame in HDF5 (.h5) format |
video_height |
Optional numeric height of the source video frame in pixels. |
a movement dataframe
Read trackball data from a variety of setups and configurations.
read_trackball( paths, setup = c("of_free", "of_fixed"), sampling_rate, col_time = "time", col_dx = "x", col_dy = "y", counts_per_rotation = NULL, ball_diameter = NULL, dots_per_cm = NULL, quiet = TRUE )read_trackball( paths, setup = c("of_free", "of_fixed"), sampling_rate, col_time = "time", col_dx = "x", col_dy = "y", counts_per_rotation = NULL, ball_diameter = NULL, dots_per_cm = NULL, quiet = TRUE )
paths |
Two file paths, one for each sensor (although one is allowed for a fixed setup, |
setup |
Which type of experimental setup was used. Expects either |
sampling_rate |
Sampling rate tells the function how long time it should integrate over. A sampling rate of 60(Hz) will mean windows of 1/60 sec are used to integrate over. |
col_time |
Which column contains the information about time. Can be specified either by the column number (numeric) or the name of the column if it has one (character). Should either be a datetime (POSIXt) or seconds (numeric). |
col_dx |
Column name for x-axis values |
col_dy |
Column name for y-axis values |
counts_per_rotation |
For |
ball_diameter |
For |
dots_per_cm |
For |
quiet |
If |
a movement dataframe
Parses a TrackMate XML file and returns spot data from filtered tracks
as an aniframe. TrackMate stores spot coordinates in image (top-left)
coordinates; the reader reflects y so the returned aniframe is in the
conventional bottom_left origin. The frame height is read from
Settings/ImageData/@height in the XML by default.
read_trackmate(path, slim = TRUE, video_height = NULL)read_trackmate(path, slim = TRUE, video_height = NULL)
path |
Path to the TrackMate XML file. |
slim |
If TRUE, return only essential columns (default TRUE). |
video_height |
Optional numeric height of the source frame in the
units reported by the XML. Overrides the value parsed from
|
An aniframe with columns including time, x, y, z, frame, and track_id.
Reads and formats movement tracking data exported from TRex (Walter & Couzin, 2021). TRex is a software for tracking animal movement in videos, which exports coordinate data in CSV format. This function processes these files into a standardized movement data format.
read_trex(path, video_height = NULL)read_trex(path, video_height = NULL)
path |
Character string specifying the path to a TRex CSV file. The file should contain columns for:
|
video_height |
Optional numeric height of the source video frame
in the same spatial units as the tracking output (TRex defaults to
centimetres). TRex's CSV export does not record this, so without it
|
The function performs several processing steps:
Validates the input file format (must be CSV)
Reads the data using vroom for efficient processing
Cleans column names to a consistent format
Restructures the data from wide to long format
Initializes metadata fields required for movement data
A data frame containing movement data with the following columns:
time: Time values from the tracking
individual: Factor (set to NA, as TRex tracks one individual)
keypoint: Factor identifying tracked points (e.g., "head", "centroid")
x: x-coordinates in centimeters
y: y-coordinates in centimeters
confidence: Numeric confidence values (set to NA as TRex doesn't provide these)
Walter, T., & Couzin, I. D. (2021). TRex, a fast multi-animal tracking system with markerless identification, and 2D estimation of posture and visual fields. eLife, 10, e64000.
TRex software: https://trex.run
## Not run: # Read a TRex CSV file data <- read_trex("path/to/trex_export.csv") ## End(Not run)## Not run: # Read a TRex CSV file data <- read_trex("path/to/trex_export.csv") ## End(Not run)
This high‑level wrapper writes an aniframe object to a file in one of the
supported formats (parquet, csv, or tsv). We highly recommend using parquet
as neither csv or tsv can preserve the metadata.
write_aniframe(data, filename, ...)write_aniframe(data, filename, ...)
data |
An aniframe object (see |
filename |
Character string specifying the output file name. The file extension determines which writer is used. |
... |
Additional arguments passed to the format‑specific writer
( |
Supported extensions are "parquet", "csv" and "tsv". We highly recommend using parquet
as neither csv or tsv can preserve the metadata.
CSV/TSV files are written with the vroom for fast I/O.
Parquet files are written with the arrow package is installed (install‑on‑demand if missing).
The original data object (invisibly), enabling pipe‑friendly usage.
## Not run: ## Create a small aniframe for demonstration df <- aniframe::example_aniframe() ## Write the aniframe as CSV write_aniframe(df, "demo.csv") ## Write the same aniframe as Parquet write_aniframe(df, "demo.parquet") ## End(Not run)## Not run: ## Create a small aniframe for demonstration df <- aniframe::example_aniframe() ## Write the aniframe as CSV write_aniframe(df, "demo.csv") ## Write the same aniframe as Parquet write_aniframe(df, "demo.parquet") ## End(Not run)
Converts an aniframe to the CSV format required by inTRACKtive for browser-based interactive visualization of tracking data. The function creates unique integer track identifiers from combinations of grouping columns present in the data.
write_intracktive(data, filename, quiet = FALSE)write_intracktive(data, filename, quiet = FALSE)
data |
An aniframe containing tracking data with required columns
|
filename |
File path to write the CSV. |
quiet |
Suppress messages. TRUE/FALSE. Defaults to FALSE. |
inTRACKtive requires tracking data with a unique integer track_id for each
tracked object. This function automatically generates track IDs from any
combination of aniframe grouping columns that are present in the data.
The output format includes:
track_id: Integer identifier for each unique track
t: Time values (renamed from time)
x, y: Spatial coordinates
z: Optional third dimension if present
The resulting CSV can be converted to inTRACKtive's Zarr format using their command-line tools or Python package.
Returns the input data unchanged.
Huijben, T.A.P.M., Anderson, A.G., Sweet, A. et al. (2025). inTRACKtive: a web-based tool for interactive cell tracking visualization. Nature Methods.
## Not run: # Write aniframe to inTRACKtive CSV write_intracktive(my_data, "tracks.csv") # Get formatted data without writing formatted <- write_intracktive(my_data) ## End(Not run)## Not run: # Write aniframe to inTRACKtive CSV write_intracktive(my_data, "tracks.csv") # Get formatted data without writing formatted <- write_intracktive(my_data) ## End(Not run)