Skip to content

Commit

Permalink
BF - add missing files for byteswapping
Browse files Browse the repository at this point in the history
  • Loading branch information
matthew-brett committed Feb 10, 2011
1 parent 0f5d89a commit 81c056e
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
30 changes: 30 additions & 0 deletions dipy/utils/arrfuncs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
""" Utilities to manipulate numpy arrays """

import sys

import numpy as np

from nibabel.volumeutils import endian_codes, native_code, swapped_code


def as_native_array(arr):
""" Return `arr` as native byteordered array
If arr is already native byte ordered, return unchanged. If it is opposite
endian, then make a native byte ordered copy and return that
Parameters
----------
arr : ndarray
Returns
-------
native_arr : ndarray
If `arr` was native order, this is just `arr`. Otherwise it's a new
array such that ``np.all(native_arr == arr)``, with native byte
ordering.
"""
if endian_codes[arr.dtype.byteorder] == native_code:
return arr
return arr.byteswap().newbyteorder()

30 changes: 30 additions & 0 deletions dipy/utils/tests/test_arrfuncs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
""" Testing array utilities
"""

import sys

import numpy as np

from ..arrfuncs import as_native_array

from numpy.testing import (assert_array_almost_equal,
assert_array_equal)

from nose.tools import assert_true, assert_false, assert_equal, assert_raises

NATIVE_ORDER = '<' if sys.byteorder == 'little' else '>'
SWAPPED_ORDER = '>' if sys.byteorder == 'little' else '<'

def test_as_native():
arr = np.arange(5) # native
assert_equal(arr.dtype.byteorder, '=')
narr = as_native_array(arr)
assert_true(arr is narr)
sdt = arr.dtype.newbyteorder('s')
barr = arr.astype(sdt)
assert_equal(barr.dtype.byteorder, SWAPPED_ORDER)
narr = as_native_array(barr)
assert_false(barr is narr)
assert_array_equal(barr, narr)
assert_equal(narr.dtype.byteorder, NATIVE_ORDER)

0 comments on commit 81c056e

Please sign in to comment.