Skip to content

affine matrix issue while saving trackvis files #704

Open
@daniel-ge

Description

@daniel-ge

I am attempting to write files in Trackvis-Format (trk). So loading a trk-file and saving it without any further changes should work. But unfortunately it fails in the following example:

Failing example

import nibabel.streamlines.trk as nitrk 
from numpy.testing import assert_equal, assert_almost_equal
import numpy as np
from numpy.linalg import inv
import urllib

trkname = "/tmp/myfile.trk"
trkname_clone = "/tmp/myfile_clone.trk"

# please let me know if the link of the example file is expired
url = "https://gigamove.rz.rwth-aachen.de/d/id/4hd7gVeFc4GweS/dd/100"
urllib.URLopener().retrieve(url, trkname)

trk = nitrk.TrkFile.load(trkname) # just loading...
trk.save(trkname_clone) # ... and saving
trk_clone = nitrk.TrkFile.load(trkname_clone) # let's load the content for comparison

# the contents of the files should be equal:
assert_equal(trk.header,trk_clone.header)
for i in range(len(trk.streamlines)):
    assert_almost_equal(trk.streamlines[i],
                        trk_clone.streamlines[i], decimal=4)
"""
AssertionError: 
Arrays are not almost equal to 4 decimals

(mismatch 100.0%)
 x: array([[-111.3645,  160.6524,   40.247 ],
       [-112.3261,  161.0878,   40.6915],
       [-112.4026,  161.1225,   40.7269],...
 y: array([[-4416.592 ,  4464.1333,  4995.547 ],
       [-4387.707 ,  4434.735 ,  4961.6387],
       [-4385.4077,  4432.3945,  4958.94  ],...
"""

Working example

I figured out that this error is related to the creation of the affine transformation in get_affine_rasmm_to_trackvis. After redefinition of this function the saved file contains the same data as the original one.

def f(hdr):
    T = nitrk.get_affine_trackvis_to_rasmm(hdr)
    T2 = np.eye(4)
    T2[:3,:3] = inv(T[:3,:3])
    T3 = np.eye(4)
    T3[:3,3:4] = T[:3,3:4]*-1
    return np.dot(T2,T3)

nitrk.get_affine_rasmm_to_trackvis = f

trk = nitrk.TrkFile.load(trkname)
trk.tractogram.affine_to_rasmm = np.eye(4) # because it was only ROUGHLY eye(4)
trk.save(trkname_clone)
trk_clone = nitrk.TrkFile.load(trkname_clone)

# the contents of the files should be equal:
assert_equal(trk.header,trk_clone.header)
for i in range(len(trk.streamlines)):
    assert_almost_equal(trk.streamlines[i],
                        trk_clone.streamlines[i], decimal=4)

"""
No Error :)
"""

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions