Skip to content

Commit

Permalink
RF+TST: check/error for bad axcodes codes/labels
Browse files Browse the repository at this point in the history
As Kesshi Jordan pointed out, TRK files can have lower-case axis codes,
and this causes unexpected output from axcodes2ornt.  Extend
axcodes2ornt to

a) Check whether the axis codes do in fact correspond to the labels.
b) Check for duplicate labels.
  • Loading branch information
matthew-brett committed Feb 19, 2018
1 parent 4740545 commit 9ac73d0
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 7 deletions.
9 changes: 7 additions & 2 deletions nibabel/orientations.py
Original file line number Diff line number Diff line change
Expand Up @@ -349,8 +349,13 @@ def axcodes2ornt(axcodes, labels=None):
[ 0., -1.],
[ 2., 1.]])
"""
if labels is None:
labels = list(zip('LPI', 'RAS'))
labels = list(zip('LPI', 'RAS')) if labels is None else labels
allowed_labels = sum([list(L) for L in labels], []) + [None]
if len(allowed_labels) != len(set(allowed_labels)):
raise ValueError('Duplicate labels in {}'.format(allowed_labels))
if not set(axcodes).issubset(allowed_labels):
raise ValueError('Not all axis codes {} in label set {}'
.format(list(axcodes), allowed_labels))
n_axes = len(axcodes)
ornt = np.ones((n_axes, 2), dtype=np.int8) * np.nan
for code_idx, code in enumerate(axcodes):
Expand Down
29 changes: 24 additions & 5 deletions nibabel/tests/test_orientations.py
Original file line number Diff line number Diff line change
Expand Up @@ -300,11 +300,8 @@ def test_axcodes2ornt():
)

# default is RAS output directions
assert_array_equal(axcodes2ornt(('R', 'A', 'S')),
[[0, 1],
[1, 1],
[2, 1]]
)
default = np.c_[range(3), [1] * 3]
assert_array_equal(axcodes2ornt(('R', 'A', 'S')), default)

# dropped axes produce None
assert_array_equal(axcodes2ornt(('R', None, 'S')),
Expand All @@ -313,6 +310,28 @@ def test_axcodes2ornt():
[2, 1]]
)

# Missing axcodes raise an error
assert_array_equal(axcodes2ornt('RAS'), default)
assert_raises(ValueError, axcodes2ornt, 'rAS')
# None is OK as axis code
assert_array_equal(axcodes2ornt(('R', None, 'S')),
[[0, 1],
[np.nan, np.nan],
[2, 1]])
# Bad axis code with None also raises error.
assert_raises(ValueError, axcodes2ornt, ('R', None, 's'))
# Axis codes checked with custom labels
labels = ('SD', 'BF', 'lh')
assert_array_equal(axcodes2ornt('BlD', labels),
[[1, -1],
[2, -1],
[0, 1]])
assert_raises(ValueError, axcodes2ornt, 'blD', labels)

# Duplicate labels
assert_raises(ValueError, axcodes2ornt, 'blD', ('SD', 'BF', 'lD'))
assert_raises(ValueError, axcodes2ornt, 'blD', ('SD', 'SF', 'lD'))


def test_aff2axcodes():
assert_equal(aff2axcodes(np.eye(4)), tuple('RAS'))
Expand Down

0 comments on commit 9ac73d0

Please sign in to comment.