Package 'aniread'

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

Help Index


Get calibration values for trackball data

Description

Reads a calibration recording and computes calibration values. Spin the ball a known number of times in one direction while recording.

Usage

calibrate_trackball(
  path,
  ball_diameter,
  ball_rotations,
  col_dx = "x",
  col_dy = "y"
)

Arguments

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.

Value

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).


Download sample tracking data

Description

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.

Usage

get_sample_data(
  source,
  dataset = NULL,
  cache_dir = tempdir(),
  quiet = FALSE,
  list_datasets = FALSE
)

Arguments

source

Character string specifying either a tracking software name or a URL. Currently supported software names:

  • "animalta": Data from AnimalTA

  • "anipose": Mouse paw tracking data

  • "bonsai": Tracking data from Bonsai

  • "deeplabcut": Mouse/animal tracking from DeepLabCut (3 datasets)

  • "fictrac": Fictrac sample data

  • "freemocap": FreeMoCap motion capture test data

  • "idtracker": Trajectories from idtracker.ai

  • "lightningpose": Mouse tracking from LightningPose (2 datasets)

  • "movement": Movement package native format (2 datasets)

  • "sleap": Animal tracking from SLEAP (3 datasets)

  • "trex": Multi-animal tracking from TRex (returns vector of individual files)

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 get_sample_data(list_datasets = TRUE) to see all available options.

cache_dir

Character string specifying the directory where to cache the downloaded files. Defaults to a temporary directory using tempdir(). Set to a permanent location to persist data across R sessions.

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.

Details

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

Value

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.

Examples

## 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)

Read an aniframe from a Parquet file

Description

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.

Usage

read_aniframe(path)

Arguments

path

Path to a Parquet file.

Value

An aniframe object.

Examples

## Not run: 
data <- read_aniframe("movement_data.parquet")

## End(Not run)

Read AnimalTA data

Description

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.

Usage

read_animalta(path, detailed = FALSE, video_height = NULL)

Arguments

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 y is used as a fallback.

Value

a movement dataframe

References

  • 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.


Read Anipose 3D pose estimation data

Description

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.

Usage

read_anipose(path, unit_space = "mm")

Arguments

path

Character string specifying the path to an Anipose CSV file. Typically these are found in the ⁠pose-3d⁠ directory of your Anipose output.

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".

Value

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 Data Structure

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.

Examples

## 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 centroid tracking data from Bonsai

Description

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.

Usage

read_bonsai(path, video_height = NULL)

Arguments

path

Path to a Bonsai data file

video_height

Optional numeric height of the source video frame in pixels.

Value

a movement dataframe


Read a C3D motion capture file

Description

Reads a C3D file and returns the data as an aniframe with associated metadata including source software, units, and sampling rate.

Usage

read_c3d(path)

Arguments

path

Path to a .c3d file.

Value

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).

See Also

c3dr::c3d_read() for lower-level C3D access.


Read a custom file format

Description

Reads a file and selects/renames specified columns to create an aniframe.

Usage

read_custom(
  path,
  cols,
  variables_what = NULL,
  variables_when = NULL,
  variables_where = NULL,
  metadata = list()
)

Arguments

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. c(time = "time", x = "x", y = "y"). Names should be the desired output column names, and values can be either the original column names (as characters) or column positions (as integers, e.g. c(time = 1, x = 2, y = 3)).

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.

Value

An aniframe with the selected and renamed columns, and attached metadata.

Examples

## 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 DeepLabCut data

Description

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.

Usage

read_deeplabcut(path, video_height = NULL)

Arguments

path

Path to a DeepLabCut data file

video_height

Optional numeric height of the source video frame in pixels.

Value

an aniframe


Read FastTrack tracking data

Description

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.

Usage

read_fasttrack(path, video_height = NULL)

Arguments

path

Path to a FastTrack tracking.txt file.

video_height

Optional numeric height of the source video frame in pixels.

Value

An aniframe


Read projected FicTrac data

Description

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.

Usage

read_fictrac(path, ball_radius = NULL, unit_ball_radius = "cm")

Arguments

path

Character. Path to the FicTrac ⁠*.dat⁠ file.

ball_radius

Numeric (optional). Physical radius of the tracking ball. When supplied the x and y coordinates are multiplied by this value.

unit_ball_radius

Character. Unit of ball_radius (e.g., "cm" or "mm"). Defaults to "cm". Ignored when ball_radius is NULL.

Value

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.

Examples

## 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)

Read FreeMoCap motion capture data

Description

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.

Usage

read_freemocap(path)

Arguments

path

Character string specifying the path to the FreeMoCap CSV file. Should be a file ending in 'by_frame.csv'.

Value

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)

Examples

## 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)

Read idtracker.ai data

Description

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).

Usage

read_idtracker(
  path,
  path_probabilities = NULL,
  version = 6,
  video_height = NULL
)

Arguments

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.

Value

a movement dataframe


Read LightningPose data

Description

Read csv files from LightningPose (LP). Like DeepLabCut, the source is in image (top-left) coordinates and the reader reflects y to bottom_left.

Usage

read_lightningpose(path, video_height = NULL)

Arguments

path

Path to a LightningPose data file

video_height

Optional numeric height of the source video frame in pixels. Falls back to max(y) when not supplied.

Value

an aniframe


Read data exported from the movement Python package

Description

Imports pose estimation data from netCDF/HDF5 files created by the movement Python package.

Usage

read_movement(path, video_height = NULL)

Arguments

path

Path to an HDF5 file (.nc or .h5) exported from movement.

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 max(y) is used as a fallback when reflecting to bottom_left.

Details

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.

Value

An aniframe


Read Octron Segmentation Data

Description

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.

Usage

read_octron(
  path,
  keep_bbox = FALSE,
  video_height = NULL,
  method = c("weighted", "largest", "segments"),
  properties = "all"
)

Arguments

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:

  • "weighted" (default): area-weighted mean across all segments per row. area becomes the sum of segment areas; orientation falls back to "largest" (circular quantity, weighted mean is undefined).

  • "largest": take values from the single largest segment per row.

  • "segments": expand each multi-segment row into one row per segment, adding a segment identity variable. Segments are not matched across frames, so filtering on segment is generally not meaningful.

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:

  • "all" (default): read every property column found in the file. Backwards-compatible with prior read_octron() behaviour.

  • a character vector of column names, e.g. c("area", "orientation"): read only the listed properties. Unknown names are warned about and ignored.

  • NULL or character(0): skip all property columns; the result contains only id columns and the centroid (and bbox when keep_bbox = TRUE).

When method = "weighted" and area exists in the file but is absent from this argument, it is added automatically (the area-weighted mean has no meaning otherwise) and an info message is emitted.

Details

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.

Value

An aniframe


Read SLEAP data

Description

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.

Usage

read_sleap(path, video_height = NULL)

Arguments

path

A SLEAP analysis data frame in HDF5 (.h5) format

video_height

Optional numeric height of the source video frame in pixels.

Value

a movement dataframe


Read trackball data

Description

Read trackball data from a variety of setups and configurations.

Usage

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
)

Arguments

paths

Two file paths, one for each sensor (although one is allowed for a fixed setup, of_fixed).

setup

Which type of experimental setup was used. Expects either of_free or of_fixed.

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 of_fixed setup: the sensor count for a full 360 degree rotation. Can be obtained using calibrate_trackball().

ball_diameter

For of_fixed setup: the ball diameter (in same units as desired output). Required if using dots_per_cm instead of counts_per_rotation.

dots_per_cm

For of_fixed setup: sensor dots-per-cm. Use with ball_diameter as an alternative to counts_per_rotation.

quiet

If TRUE (default), suppresses most warning messages.

Value

a movement dataframe


Read TrackMate XML into an aniframe

Description

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.

Usage

read_trackmate(path, slim = TRUE, video_height = NULL)

Arguments

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 ⁠Settings/ImageData/@height⁠ when both are available.

Value

An aniframe with columns including time, x, y, z, frame, and track_id.


Read TRex Movement Tracking Data

Description

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.

Usage

read_trex(path, video_height = NULL)

Arguments

path

Character string specifying the path to a TRex CSV file. The file should contain columns for:

  • time

  • x and y coordinates for tracked points (e.g., x_head, y_head)

  • x and y coordinates for centroid (x_number_wcentroid_cm, y_number_wcentroid_cm)

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 max(y) is used as a fallback when reflecting to bottom_left.

Details

The function performs several processing steps:

  1. Validates the input file format (must be CSV)

  2. Reads the data using vroom for efficient processing

  3. Cleans column names to a consistent format

  4. Restructures the data from wide to long format

  5. Initializes metadata fields required for movement data

Value

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)

References

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.

See Also

  • TRex software: https://trex.run

Examples

## Not run: 
# Read a TRex CSV file
data <- read_trex("path/to/trex_export.csv")

## End(Not run)

Write an aniframe to disk

Description

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.

Usage

write_aniframe(data, filename, ...)

Arguments

data

An aniframe object (see aniframe::is_aniframe()).

filename

Character string specifying the output file name. The file extension determines which writer is used.

...

Additional arguments passed to the format‑specific writer (write_aniframe_csv() or write_aniframe_parquet()). Typical arguments include delim, col_names, compression, etc., depending on the backend.

Details

  • 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).

Value

The original data object (invisibly), enabling pipe‑friendly usage.

Examples

## 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)

Write aniframe data to inTRACKtive CSV format

Description

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.

Usage

write_intracktive(data, filename, quiet = FALSE)

Arguments

data

An aniframe containing tracking data with required columns time, x, and y. Optional columns include z for 3D data and grouping columns (session, trial, model, individual, keypoint).

filename

File path to write the CSV.

quiet

Suppress messages. TRUE/FALSE. Defaults to FALSE.

Details

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.

Value

Returns the input data unchanged.

References

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.

Examples

## 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)