Skip to content

Commit 9ac73d0

Browse files
committed
RF+TST: check/error for bad axcodes codes/labels
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.
1 parent 4740545 commit 9ac73d0

File tree

2 files changed

+31
-7
lines changed

2 files changed

+31
-7
lines changed

nibabel/orientations.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -349,8 +349,13 @@ def axcodes2ornt(axcodes, labels=None):
349349
[ 0., -1.],
350350
[ 2., 1.]])
351351
"""
352-
if labels is None:
353-
labels = list(zip('LPI', 'RAS'))
352+
labels = list(zip('LPI', 'RAS')) if labels is None else labels
353+
allowed_labels = sum([list(L) for L in labels], []) + [None]
354+
if len(allowed_labels) != len(set(allowed_labels)):
355+
raise ValueError('Duplicate labels in {}'.format(allowed_labels))
356+
if not set(axcodes).issubset(allowed_labels):
357+
raise ValueError('Not all axis codes {} in label set {}'
358+
.format(list(axcodes), allowed_labels))
354359
n_axes = len(axcodes)
355360
ornt = np.ones((n_axes, 2), dtype=np.int8) * np.nan
356361
for code_idx, code in enumerate(axcodes):

nibabel/tests/test_orientations.py

Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -300,11 +300,8 @@ def test_axcodes2ornt():
300300
)
301301

302302
# default is RAS output directions
303-
assert_array_equal(axcodes2ornt(('R', 'A', 'S')),
304-
[[0, 1],
305-
[1, 1],
306-
[2, 1]]
307-
)
303+
default = np.c_[range(3), [1] * 3]
304+
assert_array_equal(axcodes2ornt(('R', 'A', 'S')), default)
308305

309306
# dropped axes produce None
310307
assert_array_equal(axcodes2ornt(('R', None, 'S')),
@@ -313,6 +310,28 @@ def test_axcodes2ornt():
313310
[2, 1]]
314311
)
315312

313+
# Missing axcodes raise an error
314+
assert_array_equal(axcodes2ornt('RAS'), default)
315+
assert_raises(ValueError, axcodes2ornt, 'rAS')
316+
# None is OK as axis code
317+
assert_array_equal(axcodes2ornt(('R', None, 'S')),
318+
[[0, 1],
319+
[np.nan, np.nan],
320+
[2, 1]])
321+
# Bad axis code with None also raises error.
322+
assert_raises(ValueError, axcodes2ornt, ('R', None, 's'))
323+
# Axis codes checked with custom labels
324+
labels = ('SD', 'BF', 'lh')
325+
assert_array_equal(axcodes2ornt('BlD', labels),
326+
[[1, -1],
327+
[2, -1],
328+
[0, 1]])
329+
assert_raises(ValueError, axcodes2ornt, 'blD', labels)
330+
331+
# Duplicate labels
332+
assert_raises(ValueError, axcodes2ornt, 'blD', ('SD', 'BF', 'lD'))
333+
assert_raises(ValueError, axcodes2ornt, 'blD', ('SD', 'SF', 'lD'))
334+
316335

317336
def test_aff2axcodes():
318337
assert_equal(aff2axcodes(np.eye(4)), tuple('RAS'))

0 commit comments

Comments
 (0)