-
Notifications
You must be signed in to change notification settings - Fork 258
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
NF: add utils module for code support functions
Add to_scalar function with tests.
- Loading branch information
1 parent
314f0dd
commit 1d32fed
Showing
2 changed files
with
43 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
""" Test for utils module | ||
""" | ||
|
||
import numpy as np | ||
|
||
from nibabel.utils import to_scalar | ||
|
||
from nose.tools import assert_equal, assert_true, assert_false, assert_raises | ||
|
||
|
||
def test_to_scalar(): | ||
for pass_thru in (2, 2.3, 'foo', b'foo', [], (), [2], (2,), object()): | ||
assert_true(to_scalar(pass_thru) is pass_thru) | ||
for arr_contents in (2, 2.3, 'foo', b'foo'): | ||
arr = np.array(arr_contents) | ||
out = to_scalar(arr) | ||
assert_false(to_scalar(arr) is arr) | ||
assert_equal(out, arr_contents) | ||
# Promote to 1 and 2D and check contents | ||
assert_equal(to_scalar(np.atleast_1d(arr)), arr_contents) | ||
assert_equal(to_scalar(np.atleast_2d(arr)), arr_contents) | ||
assert_raises(ValueError, to_scalar, np.array([1, 2])) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
""" Code support routines, not otherwise classified | ||
""" | ||
|
||
|
||
def to_scalar(val): | ||
""" Return scalar representation of `val` | ||
Return scalar value from numpy array, or pass through value if not numpy | ||
array. | ||
Parameters | ||
---------- | ||
val : object | ||
numpy array or other object. | ||
Returns | ||
------- | ||
out : object | ||
Result of ``val.item()`` if `val` has an ``item`` method, else `val`. | ||
""" | ||
return val.item() if hasattr(val, 'item') else val |