Skip to main content

Traja is a trajectory analysis and visualization tool

Project description

Colab

Traja is a Python library for trajectory analysis. It extends the capability of pandas DataFrame specific for animal trajectory analysis in 2D, and provides convenient interfaces to other geometric analysis packages (eg, R and shapely).

Introduction

The traja Python package is a toolkit for the numerical characterization and analysis of the trajectories of moving animals. Trajectory analysis is applicable in fields as diverse as optimal foraging theory, migration, and behavioral mimicry (e.g. for verifying similarities in locomotion). A trajectory is simply a record of the path followed by a moving animal. Traja operates on trajectories in the form of a series of locations (as x, y coordinates) with times. Trajectories may be obtained by any method which provides this information, including manual tracking, radio telemetry, GPS tracking, and motion tracking from videos.

The goal of this package (and this document) is to aid biological researchers, who may not have extensive experience with Python, to analyze trajectories without being restricted by a limited knowledge of Python or programming. However, a basic understanding of Python is useful.

If you use traja in your publications, please cite the repo

@software{justin_shenk_2019_3237827,
  author       = {Justin Shenk and
                  the Traja development team},
  title        = {justinshenk/traja},
  month        = jun,
  year         = 2019,
  publisher    = {Zenodo},
  version      = {latest},
  doi          = {10.5281/zenodo.3237827},
  url          = {https://doi.org/10.5281/zenodo.3237827}
}

Installation and setup

To install traja with conda, run

conda install -c conda-forge traja

or with pip

pip install traja.

Import traja into your Python script or via the Python command-line with import traja.

Trajectories with traja

Traja stores trajectories in pandas DataFrames, allowing any pandas functions to be used.

Load trajectory with x, y and time coordinates:

import traja

df = traja.read_file('coords.csv')

Once a DataFrame is loaded, use the .traja accessor to access the visualization and analysis methods:

df.traja.plot(title='Cage trajectory')

Analyze Trajectory

The following functions are available via traja.trajectory.[method]

Function

Description

calc_derivatives

Calculate derivatives of x, y values

calc_turn_angles

Calculate turn angles with regard to x-axis

transitions

Calculate first-order Markov model for transitions between grid bins

generate

Generate random walk

resample_time

Resample to consistent step_time intervals

rediscretize_points

Rediscretize points to given step length

For up-to-date documentation, see https://traja.readthedocs.io.

Deep Learning Integration

Traja provides production-ready features for training neural networks on trajectory data:

Data Augmentation - Create training variations for robust models:

# Rotation, noise, scaling, reversal, subsampling
rotated = df.traja.augment_rotate(angle=45)
noisy = df.traja.augment_noise(sigma=0.1)
scaled = df.traja.augment_scale(factor=1.5)

Sequence Processing - Standardize trajectory lengths for batching:

# Pad or truncate to fixed length
padded = df.traja.pad_trajectory(target_length=200, mode='edge')
truncated = df.traja.truncate_trajectory(target_length=100, mode='random')
normalized = df.traja.normalize_trajectory()

Feature Extraction - Generate ML-ready features:

# Extract displacement, speed, turn_angle, heading, acceleration
features = df.traja.extract_features()

PyTorch Integration - Seamless tensor conversion:

tensor = df.traja.to_tensor()  # Convert to PyTorch tensor

Dataset Utilities - Train/val/test splitting:

trajectories = [traja.generate(n=100) for _ in range(50)]
train, val, test = traja.trajectory.train_test_split(
    trajectories, train_size=0.7, val_size=0.15, test_size=0.15
)

3D Support - All features work with x, y, z coordinates:

df_3d = traja.TrajaDataFrame({'x': x, 'y': y, 'z': z})
tensor_3d = df_3d.traja.to_tensor()  # Shape: (n_points, 3)

GPS/Lat-Long Support - Work with GPS coordinates:

traj = traja.from_latlon(lat, lon)  # Convert GPS to local x,y

Visualization Enhancements - Better trajectory analysis and exploration:

# Interactive plots with plotly
fig = df.traja.plot_interactive()  # Zoom, pan, rotate

# Heatmap showing time spent in locations
df.traja.plot_heatmap(bins=50)

# Speed and acceleration profiles
df.traja.plot_speed()
df.traja.plot_acceleration()

# Comprehensive 4-panel analysis
df.traja.plot_trajectory_components()

Performance Optimization - Fast parallel processing:

# Process 100 trajectories in parallel
trajectories = [traja.generate(n=1000) for _ in range(100)]
results = traja.trajectory.batch_process(
    trajectories,
    lambda t: t.traja.normalize_trajectory(),
    n_jobs=-1  # Use all CPUs
)

See the Deep Learning documentation and examples/deep_learning_demo.ipynb for complete examples.

Random walk

Generate random walks with

df = traja.generate(n=1000, step_length=2)
df.traja.plot()
walk\_screenshot.png

Resample time

traja.trajectory.resample_time allows resampling trajectories by a step_time.

Flow Plotting

df = traja.generate()
traja.plot_surface(df)
3D plot
traja.plot_quiver(df, bins=32)
quiver plot
traja.plot_contour(df, filled=False, quiver=False, bins=32)
contour plot
traja.plot_contour(df, filled=False, quiver=False, bins=32)
contour plot filled
traja.plot_contour(df, bins=32, contourfplot_kws={'cmap':'coolwarm'})
streamplot

Acknowledgements

traja code implementation and analytical methods (particularly rediscretize_points) are heavily inspired by Jim McLean’s R package trajr. Many thanks to Jim for his feedback.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

traja-25.0.1.tar.gz (6.6 MB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

traja-25.0.1-py3-none-any.whl (102.1 kB view details)

Uploaded Python 3

File details

Details for the file traja-25.0.1.tar.gz.

File metadata

  • Download URL: traja-25.0.1.tar.gz
  • Upload date:
  • Size: 6.6 MB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.4

File hashes

Hashes for traja-25.0.1.tar.gz
Algorithm Hash digest
SHA256 8016c09d6b9e7d1cd040647a4d656967188d7186cc8171734bd28bbafad1286d
MD5 c5b983e34a069e2cf6ddb4c56cb2e70b
BLAKE2b-256 ab0ed14f1ecd716ce9052a41ab677f98070d89d3e50474fb5af5ac504039d5ed

See more details on using hashes here.

File details

Details for the file traja-25.0.1-py3-none-any.whl.

File metadata

  • Download URL: traja-25.0.1-py3-none-any.whl
  • Upload date:
  • Size: 102.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.4

File hashes

Hashes for traja-25.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 1caa653bb50283cc05da537e8f8afd1a040a53d8563f98f981199a6415685a15
MD5 b98ca13d8d944a11bd21848b99c36ab9
BLAKE2b-256 73f46409319f0bd084dbcb5e9fefb2400c77d8b3246dc9fe4acd98fab4a597d3

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page