Skip to content

Commit 96aca04

Browse files
committed
NF - moved trackvis reader from dipy
1 parent b499f4c commit 96aca04

File tree

5 files changed

+730
-26
lines changed

5 files changed

+730
-26
lines changed

nibabel/__init__.py

Lines changed: 20 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,11 @@
66
# copyright and license terms.
77
#
88
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
9-
"""This package provides read and write access to some common
10-
neuroimaging file formats.
9+
"""This package provides read and write access to some common neuroimaging file
10+
formats.
1111
12-
The various image format classes give full or selective access to header
13-
(meta) information and access to the image data is made available via
14-
NumPy arrays.
12+
The various image format classes give full or selective access to header (meta)
13+
information and access to the image data is made available via NumPy arrays.
1514
1615
============
1716
Quickstart
@@ -44,22 +43,23 @@
4443

4544

4645
# module imports
47-
from nibabel import analyze as ana
48-
from nibabel import spm99analyze as spm99
49-
from nibabel import spm2analyze as spm2
50-
from nibabel import nifti1 as ni1
51-
from nibabel import minc
46+
from . import analyze as ana
47+
from . import spm99analyze as spm99
48+
from . import spm2analyze as spm2
49+
from . import nifti1 as ni1
50+
from . import minc
5251
# object imports
53-
from nibabel.fileholders import FileHolder, FileHolderError
54-
from nibabel.loadsave import load, save
55-
from nibabel.analyze import AnalyzeHeader, AnalyzeImage
56-
from nibabel.spm99analyze import Spm99AnalyzeHeader, Spm99AnalyzeImage
57-
from nibabel.spm2analyze import Spm2AnalyzeHeader, Spm2AnalyzeImage
58-
from nibabel.nifti1 import Nifti1Header, Nifti1Image, Nifti1Pair
59-
from nibabel.minc import MincImage
60-
from nibabel.funcs import (squeeze_image, concat_images, four_to_three,
52+
from .fileholders import FileHolder, FileHolderError
53+
from .loadsave import load, save
54+
from .analyze import AnalyzeHeader, AnalyzeImage
55+
from .spm99analyze import Spm99AnalyzeHeader, Spm99AnalyzeImage
56+
from .spm2analyze import Spm2AnalyzeHeader, Spm2AnalyzeImage
57+
from .nifti1 import Nifti1Header, Nifti1Image, Nifti1Pair
58+
from .minc import MincImage
59+
from .funcs import (squeeze_image, concat_images, four_to_three,
6160
as_closest_canonical)
62-
from nibabel.orientations import (io_orientation, orientation_affine,
61+
from .orientations import (io_orientation, orientation_affine,
6362
flip_axis, OrientationError,
6463
apply_orientation)
65-
from nibabel.imageclasses import class_map, ext_map
64+
from .imageclasses import class_map, ext_map
65+
from . import trackvis

nibabel/tests/test_trackvis.py

Lines changed: 183 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,183 @@
1+
''' Testing trackvis module '''
2+
3+
from StringIO import StringIO
4+
5+
import numpy as np
6+
7+
import nibabel.trackvis as tv
8+
9+
from nose.tools import assert_true, assert_false, assert_equal, assert_raises
10+
11+
from numpy.testing import assert_array_equal, assert_array_almost_equal
12+
13+
from nibabel.testing import parametric
14+
15+
16+
@parametric
17+
def test_write():
18+
streams = []
19+
out_f = StringIO()
20+
tv.write(out_f, [], {})
21+
yield assert_equal(out_f.getvalue(), tv.empty_header().tostring())
22+
out_f.truncate(0)
23+
# Write something not-default
24+
tv.write(out_f, [], {'id_string':'TRACKb'})
25+
# read it back
26+
out_f.seek(0)
27+
streams, hdr = tv.read(out_f)
28+
yield assert_equal(hdr['id_string'], 'TRACKb')
29+
# check that we can pass none for the header
30+
out_f.truncate(0)
31+
tv.write(out_f, [])
32+
out_f.truncate(0)
33+
tv.write(out_f, [], None)
34+
# check that we check input values
35+
out_f.truncate(0)
36+
yield assert_raises(tv.HeaderError,
37+
tv.write, out_f, [],{'id_string':'not OK'})
38+
yield assert_raises(tv.HeaderError,
39+
tv.write, out_f, [],{'version': 3})
40+
yield assert_raises(tv.HeaderError,
41+
tv.write, out_f, [],{'hdr_size': 0})
42+
43+
44+
def streams_equal(stream1, stream2):
45+
if not np.all(stream1[0] == stream1[0]):
46+
return False
47+
if stream1[1] is None:
48+
if not stream2[1] is None:
49+
return false
50+
if stream1[2] is None:
51+
if not stream2[2] is None:
52+
return false
53+
if not np.all(stream1[1] == stream1[1]):
54+
return False
55+
if not np.all(stream1[2] == stream1[2]):
56+
return False
57+
return True
58+
59+
60+
def streamlist_equal(streamlist1, streamlist2):
61+
if len(streamlist1) != len(streamlist2):
62+
return False
63+
for s1, s2 in zip(streamlist1, streamlist2):
64+
if not streams_equal(s1, s2):
65+
return False
66+
return True
67+
68+
69+
def test_round_trip():
70+
out_f = StringIO()
71+
xyz0 = np.tile(np.arange(5).reshape(5,1), (1, 3))
72+
xyz1 = np.tile(np.arange(5).reshape(5,1) + 10, (1, 3))
73+
streams = [(xyz0, None, None), (xyz1, None, None)]
74+
tv.write(out_f, streams, {})
75+
out_f.seek(0)
76+
streams2, hdr = tv.read(out_f)
77+
yield assert_true, streamlist_equal(streams, streams2)
78+
79+
80+
@parametric
81+
def test_empty_header():
82+
for endian in '<>':
83+
for version in (1, 2):
84+
hdr = tv.empty_header(endian, version)
85+
yield assert_equal(hdr['id_string'], 'TRACK')
86+
yield assert_equal(hdr['version'], version)
87+
yield assert_equal(hdr['hdr_size'], 1000)
88+
yield assert_array_equal(
89+
hdr['image_orientation_patient'],
90+
[0,0,0,0,0,0])
91+
hdr = tv.empty_header(version=2)
92+
yield assert_array_equal(hdr['vox_to_ras'], np.zeros((4,4)))
93+
hdr_endian = tv.endian_codes[tv.empty_header().dtype.byteorder]
94+
yield assert_equal(hdr_endian, tv.native_code)
95+
96+
97+
@parametric
98+
def test_get_affine():
99+
hdr = tv.empty_header()
100+
# default header gives useless affine
101+
yield assert_array_equal(tv.aff_from_hdr(hdr),
102+
np.diag([0,0,0,1]))
103+
hdr['voxel_size'] = 1
104+
yield assert_array_equal(tv.aff_from_hdr(hdr),
105+
np.diag([0,0,0,1]))
106+
# DICOM direction cosines
107+
hdr['image_orientation_patient'] = [1,0,0,0,1,0]
108+
yield assert_array_equal(tv.aff_from_hdr(hdr),
109+
np.diag([-1,-1,1,1]))
110+
# RAS direction cosines
111+
hdr['image_orientation_patient'] = [-1,0,0,0,-1,0]
112+
yield assert_array_equal(tv.aff_from_hdr(hdr),
113+
np.eye(4))
114+
# translations
115+
hdr['origin'] = [1,2,3]
116+
exp_aff = np.eye(4)
117+
exp_aff[:3,3] = [-1,-2,3]
118+
yield assert_array_equal(tv.aff_from_hdr(hdr),
119+
exp_aff)
120+
# now use the easier vox_to_ras field
121+
hdr = tv.empty_header()
122+
aff = np.eye(4)
123+
aff[:3,:] = np.arange(12).reshape(3,4)
124+
hdr['vox_to_ras'] = aff
125+
yield assert_array_equal(tv.aff_from_hdr(hdr), aff)
126+
# mappings work too
127+
d = {'version': 1,
128+
'voxel_size': np.array([1,2,3]),
129+
'image_orientation_patient': np.array([1,0,0,0,1,0]),
130+
'origin': np.array([10,11,12])}
131+
aff = tv.aff_from_hdr(d)
132+
133+
134+
@parametric
135+
def test_aff_to_hdr():
136+
for version in (1, 2):
137+
hdr = {'version': version}
138+
affine = np.diag([1,2,3,1])
139+
affine[:3,3] = [10,11,12]
140+
tv.aff_to_hdr(affine, hdr)
141+
yield assert_array_almost_equal(tv.aff_from_hdr(hdr), affine)
142+
# put flip into affine
143+
aff2 = affine.copy()
144+
aff2[:,2] *=-1
145+
tv.aff_to_hdr(aff2, hdr)
146+
yield assert_array_almost_equal(tv.aff_from_hdr(hdr), aff2)
147+
if version == 2:
148+
yield assert_array_almost_equal(hdr['vox_to_ras'], aff2)
149+
150+
151+
@parametric
152+
def test_tv_class():
153+
tvf = tv.TrackvisFile([])
154+
yield assert_equal(tvf.streamlines, [])
155+
yield assert_true(isinstance(tvf.header, np.ndarray))
156+
yield assert_equal(tvf.endianness, tv.native_code)
157+
yield assert_equal(tvf.filename, None)
158+
out_f = StringIO()
159+
tvf.to_file(out_f)
160+
yield assert_equal(out_f.getvalue(), tv.empty_header().tostring())
161+
out_f.truncate(0)
162+
# Write something not-default
163+
tvf = tv.TrackvisFile([], {'id_string':'TRACKb'})
164+
tvf.to_file(out_f)
165+
# read it back
166+
out_f.seek(0)
167+
tvf_back = tv.TrackvisFile.from_file(out_f)
168+
yield assert_equal(tvf_back.header['id_string'], 'TRACKb')
169+
# check that we check input values
170+
out_f.truncate(0)
171+
yield assert_raises(tv.HeaderError,
172+
tv.TrackvisFile,
173+
[],{'id_string':'not OK'})
174+
yield assert_raises(tv.HeaderError,
175+
tv.TrackvisFile,
176+
[],{'version': 3})
177+
yield assert_raises(tv.HeaderError,
178+
tv.TrackvisFile,
179+
[],{'hdr_size':0})
180+
affine = np.diag([1,2,3,1])
181+
affine[:3,3] = [10,11,12]
182+
tvf.set_affine(affine)
183+
yield assert_true(np.all(tvf.get_affine() == affine))

nibabel/tests/test_utils.py

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,8 @@
2121
calculate_scale,
2222
scale_min_max,
2323
can_cast, allopen,
24-
shape_zoom_affine)
24+
shape_zoom_affine,
25+
rec2dict)
2526

2627
from numpy.testing import (assert_array_almost_equal,
2728
assert_array_equal)
@@ -133,10 +134,10 @@ def test_array_to_file():
133134
data_back = write_return(arr, str_io, ndt) # float, thus no effect
134135
yield assert_array_equal(data_back, arr)
135136
# True is the default, but just to show its possible
136-
data_back = write_return(arr, str_io, ndt, nan2zero=True)
137+
data_back = write_return(arr, str_io, ndt, nan2zero=True)
137138
yield assert_array_equal(data_back, arr)
138139
data_back = write_return(arr, str_io,
139-
np.dtype(np.int64), nan2zero=True)
140+
np.dtype(np.int64), nan2zero=True)
140141
yield assert_array_equal(data_back, [[0, 0],[0, 0]])
141142
# otherwise things get a bit weird; tidied here
142143
# How weird? Look at arr.astype(np.int64)
@@ -160,8 +161,8 @@ def test_array_to_file():
160161
array_to_file(arr + np.inf, str_io, np.int32, 0, 0.0, None)
161162
data_back = array_from_file(arr.shape, np.int32, str_io)
162163
yield assert_array_equal(data_back, np.zeros(arr.shape))
163-
164-
164+
165+
165166
def write_return(data, fileobj, out_dtype, *args, **kwargs):
166167
fileobj.truncate(0)
167168
array_to_file(data, fileobj, out_dtype, *args, **kwargs)
@@ -238,7 +239,7 @@ def test_can_cast():
238239
yield assert_equal, def_res, can_cast(intype, outtype)
239240
yield assert_equal, scale_res, can_cast(intype, outtype, False, True)
240241
yield assert_equal, all_res, can_cast(intype, outtype, True, True)
241-
242+
242243

243244
@parametric
244245
def test_allopen():
@@ -282,3 +283,9 @@ def test_shape_zoom_affine():
282283
[ 0., 0., 0., 1.]])
283284
yield assert_array_almost_equal(res, exp)
284285

286+
287+
@parametric
288+
def test_rec2dict():
289+
r = np.zeros((), dtype = [('x', 'i4'), ('s', 'S10')])
290+
d = rec2dict(r)
291+
yield assert_equal(d, {'x': 0, 's': ''})

0 commit comments

Comments
 (0)