TRX Python

raw JSON →
0.4.0 verified Fri May 01 auth: no python

A community-oriented Python library for reading and writing the TRX (Tractography) file format, designed for efficient storage of streamline tractography data. Current version 0.4.0, requires Python >=3.11, with an active development cadence on GitHub.

pip install trx-python
error ValueError: Mode not specified. Use 'rb' for reading or 'wb' for writing.
cause Opening TRXFile without mode parameter in 0.4.0.
fix
Add mode='rb' or mode='wb' when creating TRXFile.
error AttributeError: module 'trx' has no attribute 'TRXFile'
cause Incorrect import: trying to import TRXFile from top-level trx instead of trx.file.
fix
Use 'from trx.file import TRXFile'.
error TypeError: write_streamlines() got an unexpected keyword argument 'groups'
cause The 'groups' parameter was removed in 0.4.0. Streamline grouping is now done via the 'data_per_streamline' dictionary.
fix
Pass grouping data as a dict with streamline indices as keys: data_per_streamline={...}.
error OSError: [Errno 22] Invalid argument when reading .trx file
cause Writing with different endianness or corrupt header; trx-python expects little-endian data.
fix
Ensure the file was written with trx-python 0.4.0+ which forces little-endian. Re-create the file.
breaking TRXFile now requires explicit binary mode ('wb' or 'rb') when opening. Omitting mode will raise a ValueError in version 0.4.0.
fix Always specify mode='wb' for writing or mode='rb' for reading.
gotcha Streamline data must be float32 numpy arrays. Passing float64 or other dtypes may cause silent truncation or errors.
fix Convert data to numpy.float32 before writing: np.array(streamline, dtype=np.float32).
deprecated The function 'read_trx' and 'write_trx' from version 0.2 are deprecated and will be removed. Use TRXFile context manager instead.
fix Replace read_trx/write_trx calls with 'with TRXFile(...) as trx: trx.read/write_streamlines(...)'.

Minimal example: create a TRX file with two streamlines and read them back.

# Create a simple TRX file with two streamlines
import numpy as np
from trx.file import TRXFile

# Create two streamlines as arrays of 3D points
streamlines = [
    np.array([[0,0,0], [1,0,0], [2,0,0]], dtype=np.float32),
    np.array([[0,1,0], [1,1,0], [2,1,0]], dtype=np.float32)
]

# Write to file
with TRXFile('example.trx', mode='wb') as trx:
    trx.write_streamlines(streamlines)

# Read back
with TRXFile('example.trx', mode='rb') as trx:
    loaded = list(trx.read_streamlines())
    print(f'Loaded {len(loaded)} streamlines')