Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
119 changes: 83 additions & 36 deletions src/ndi/fun/data/read_ngrid.py
Original file line number Diff line number Diff line change
@@ -1,51 +1,98 @@
import numpy as np
import os
import warnings

# MATLAB's writengrid writes little-endian ('ieee-le'); read the same way on
# every platform rather than in the machine's native byte order.
_DTYPE_MAP = {
'double': '<f8',
'single': '<f4',
'int8': 'i1',
'uint8': 'u1',
'int16': '<i2',
'uint16': '<u2',
'int32': '<i4',
'uint32': '<u4',
'int64': '<i8',
'uint64': '<u8',
'char': 'u1', # MATLAB fread 'char' reads 8-bit characters
'logical': '?',
}


def read_ngrid(filename_or_fileobj, data_size, data_type='double'):
"""
Read an n-dimensional matrix from a binary file.

Args:
filename_or_fileobj (str or fileobj): Path to file or file object.
data_size (list of int): Dimensions of matrix.
filename_or_fileobj (str, os.PathLike, or file object): Path to the
file, or an object to read from. Accepted objects are:
* DID-python file objects (did.file.Fileobj, ReadOnlyFileobj,
and the binary document objects returned by
database_openbinarydoc), which expose ``fread``; an object
that is not open (``fid is None``) is opened read-only here
and closed again after reading, and one that is already open
is read from its current position and left open for its owner
to close;
* any binary file-like object with ``read`` (an open file,
io.BytesIO, ...), which is read and left open.
data_size (list of int): Dimensions of the matrix.
data_type (str): 'double', 'single', 'int8', 'uint8', etc.

Returns:
np.ndarray: N-dimensional matrix.
np.ndarray: N-dimensional matrix of shape ``data_size``.

The file holds the elements in MATLAB (column-major, little-endian)
order, as written by MATLAB's writengrid or ndi.fun.data.write_ngrid.
"""
dtype_map = {
'double': np.float64,
'single': np.float32,
'int8': np.int8,
'uint8': np.uint8,
'int16': np.int16,
'uint16': np.uint16,
'int32': np.int32,
'uint32': np.uint32,
'int64': np.int64,
'uint64': np.uint64,
'char': np.char, # ?
'logical': np.bool_
}

np_dtype = dtype_map.get(data_type, np.float64)

if isinstance(filename_or_fileobj, str):
if data_type not in _DTYPE_MAP:
# As before (and as MATLAB's readngrid warns), fall back to double.
warnings.warn(f"Unknown data_type '{data_type}'; reading as 'double'.")
data_type = 'double'
np_dtype = np.dtype(_DTYPE_MAP[data_type])
data_size = [int(d) for d in np.atleast_1d(data_size)]
count = int(np.prod(data_size))
nbytes = count * np_dtype.itemsize

if isinstance(filename_or_fileobj, (str, os.PathLike)):
if not os.path.isfile(filename_or_fileobj):
raise FileNotFoundError(f"File not found: {filename_or_fileobj}")

with open(filename_or_fileobj, 'rb') as f:
# Numpy reads in C-order by default, but Matlab writes in F-order (column-major)
# data_size is (rows, cols, depth...)
# We should read as flat then reshape in 'F' order
count = np.prod(data_size)
x = np.fromfile(f, dtype=np_dtype, count=count)
x = x.reshape(data_size, order='F')

else: # file object
# Assuming read method
count = np.prod(data_size)
x = np.fromfile(filename_or_fileobj, dtype=np_dtype, count=count)
x = x.reshape(data_size, order='F')

return x
raw = f.read(nbytes)
else:
raw = _read_from_object(filename_or_fileobj, nbytes)

if raw is None:
raw = b''
if len(raw) != nbytes:
raise ValueError(
f"Read {len(raw) // np_dtype.itemsize} elements; expected {count} "
f"for data_size {data_size}. Check data_size and data_type.")

x = np.frombuffer(raw, dtype=np_dtype, count=count)
# Elements are stored in column-major (MATLAB) order.
return x.reshape(data_size, order='F').astype(np_dtype.newbyteorder('='))


def _read_from_object(obj, nbytes):
"""Read NBYTES raw bytes from a DID file object or a file-like object."""
if hasattr(obj, 'fread'):
# DID-python file object. Open it here only if it is not open, and in
# that case close it again; an open object belongs to the caller.
opened_here = False
if getattr(obj, 'fid', None) is None and hasattr(obj, 'fopen'):
obj.fopen()
if getattr(obj, 'fid', None) is None:
name = getattr(obj, 'fullpathfilename', '')
raise FileNotFoundError(f"Could not open file: {name}")
opened_here = True
try:
return obj.fread(nbytes)
finally:
if opened_here:
obj.fclose()
if hasattr(obj, 'read'):
return obj.read(nbytes)
raise TypeError(
"filename_or_fileobj must be a path, a DID file object, or a binary "
"file-like object with a read() method.")
109 changes: 109 additions & 0 deletions tests/ndi/unittest/fun/test_read_ngrid.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
import io
import os
import pathlib
import shutil
import tempfile
import unittest

import numpy as np

from ndi.fun.data import read_ngrid, write_ngrid

try:
from did.file import Fileobj, ReadOnlyFileobj
HAVE_DID = True
except ImportError: # pragma: no cover - did is a declared dependency
HAVE_DID = False


class TestReadNgrid(unittest.TestCase):
"""read_ngrid reads what write_ngrid (or MATLAB's writengrid) wrote, from
a path or from a file object, including DID file objects such as those
database_openbinarydoc returns."""

def setUp(self):
self.root = tempfile.mkdtemp()

def tearDown(self):
shutil.rmtree(self.root)

def _write(self, x, name, data_type='double'):
fname = os.path.join(self.root, name)
write_ngrid(x, fname, data_type)
return fname

def test_path_round_trip_2d(self):
x = np.random.rand(4, 3)
fname = self._write(x, 'a.ngrid')
np.testing.assert_array_equal(read_ngrid(fname, [4, 3]), x)

def test_path_round_trip_3d_and_pathlike(self):
x = np.random.rand(3, 4, 2)
fname = self._write(x, 'b.ngrid')
y = read_ngrid(pathlib.Path(fname), list(x.shape))
self.assertEqual(y.shape, x.shape)
np.testing.assert_array_equal(y, x)

def test_column_major_little_endian_layout(self):
# MATLAB writes column-major, little-endian; build such a file by hand.
x = np.arange(6, dtype=float).reshape(2, 3)
fname = os.path.join(self.root, 'c.ngrid')
with open(fname, 'wb') as f:
f.write(x.flatten(order='F').astype('<f8').tobytes())
np.testing.assert_array_equal(read_ngrid(fname, [2, 3]), x)

def test_integer_type(self):
x = np.arange(12, dtype=np.int16).reshape(3, 4)
fname = self._write(x, 'd.ngrid', 'int16')
y = read_ngrid(fname, [3, 4], 'int16')
self.assertEqual(y.dtype, np.int16)
np.testing.assert_array_equal(y, x)

def test_file_like_object_is_read_and_left_open(self):
x = np.random.rand(2, 5)
buf = io.BytesIO(x.flatten(order='F').astype('<f8').tobytes())
np.testing.assert_array_equal(read_ngrid(buf, [2, 5]), x)
self.assertFalse(buf.closed)

@unittest.skipUnless(HAVE_DID, 'did is not installed')
def test_unopened_did_fileobj_is_opened_and_closed(self):
x = np.random.rand(5, 2)
fname = self._write(x, 'e.ngrid')
fo = ReadOnlyFileobj(fullpathfilename=fname)
self.assertIsNone(fo.fid)
np.testing.assert_array_equal(read_ngrid(fo, [5, 2]), x)
self.assertIsNone(fo.fid, 'an object read_ngrid opened should be closed again')

@unittest.skipUnless(HAVE_DID, 'did is not installed')
def test_open_did_fileobj_is_read_and_left_open(self):
# The case database_openbinarydoc produces: an already-open object.
x = np.random.rand(2, 3, 2)
fname = self._write(x, 'f.ngrid')
fo = ReadOnlyFileobj(fullpathfilename=fname)
fo.fopen()
try:
self.assertIsNotNone(fo.fid)
np.testing.assert_array_equal(read_ngrid(fo, [2, 3, 2]), x)
self.assertIsNotNone(fo.fid, 'an object open on entry should be left open')
finally:
fo.fclose()

def test_wrong_size_raises(self):
fname = self._write(np.random.rand(2, 2), 'g.ngrid')
with self.assertRaises(ValueError):
read_ngrid(fname, [3, 3])

def test_missing_file_raises(self):
with self.assertRaises(FileNotFoundError):
read_ngrid(os.path.join(self.root, 'missing.ngrid'), [2, 2])

def test_unknown_type_warns_and_reads_double(self):
x = np.random.rand(2, 2)
fname = self._write(x, 'h.ngrid')
with self.assertWarns(UserWarning):
y = read_ngrid(fname, [2, 2], 'notatype')
np.testing.assert_array_equal(y, x)


if __name__ == '__main__':
unittest.main()
109 changes: 109 additions & 0 deletions tests/nditests/unittest/fun/test_read_ngrid.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
import io
import os
import pathlib
import shutil
import tempfile
import unittest

import numpy as np

from ndi.fun.data import read_ngrid, write_ngrid

try:
from did.file import Fileobj, ReadOnlyFileobj
HAVE_DID = True
except ImportError: # pragma: no cover - did is a declared dependency
HAVE_DID = False


class TestReadNgrid(unittest.TestCase):
"""read_ngrid reads what write_ngrid (or MATLAB's writengrid) wrote, from
a path or from a file object, including DID file objects such as those
database_openbinarydoc returns."""

def setUp(self):
self.root = tempfile.mkdtemp()

def tearDown(self):
shutil.rmtree(self.root)

def _write(self, x, name, data_type='double'):
fname = os.path.join(self.root, name)
write_ngrid(x, fname, data_type)
return fname

def test_path_round_trip_2d(self):
x = np.random.rand(4, 3)
fname = self._write(x, 'a.ngrid')
np.testing.assert_array_equal(read_ngrid(fname, [4, 3]), x)

def test_path_round_trip_3d_and_pathlike(self):
x = np.random.rand(3, 4, 2)
fname = self._write(x, 'b.ngrid')
y = read_ngrid(pathlib.Path(fname), list(x.shape))
self.assertEqual(y.shape, x.shape)
np.testing.assert_array_equal(y, x)

def test_column_major_little_endian_layout(self):
# MATLAB writes column-major, little-endian; build such a file by hand.
x = np.arange(6, dtype=float).reshape(2, 3)
fname = os.path.join(self.root, 'c.ngrid')
with open(fname, 'wb') as f:
f.write(x.flatten(order='F').astype('<f8').tobytes())
np.testing.assert_array_equal(read_ngrid(fname, [2, 3]), x)

def test_integer_type(self):
x = np.arange(12, dtype=np.int16).reshape(3, 4)
fname = self._write(x, 'd.ngrid', 'int16')
y = read_ngrid(fname, [3, 4], 'int16')
self.assertEqual(y.dtype, np.int16)
np.testing.assert_array_equal(y, x)

def test_file_like_object_is_read_and_left_open(self):
x = np.random.rand(2, 5)
buf = io.BytesIO(x.flatten(order='F').astype('<f8').tobytes())
np.testing.assert_array_equal(read_ngrid(buf, [2, 5]), x)
self.assertFalse(buf.closed)

@unittest.skipUnless(HAVE_DID, 'did is not installed')
def test_unopened_did_fileobj_is_opened_and_closed(self):
x = np.random.rand(5, 2)
fname = self._write(x, 'e.ngrid')
fo = ReadOnlyFileobj(fullpathfilename=fname)
self.assertIsNone(fo.fid)
np.testing.assert_array_equal(read_ngrid(fo, [5, 2]), x)
self.assertIsNone(fo.fid, 'an object read_ngrid opened should be closed again')

@unittest.skipUnless(HAVE_DID, 'did is not installed')
def test_open_did_fileobj_is_read_and_left_open(self):
# The case database_openbinarydoc produces: an already-open object.
x = np.random.rand(2, 3, 2)
fname = self._write(x, 'f.ngrid')
fo = ReadOnlyFileobj(fullpathfilename=fname)
fo.fopen()
try:
self.assertIsNotNone(fo.fid)
np.testing.assert_array_equal(read_ngrid(fo, [2, 3, 2]), x)
self.assertIsNotNone(fo.fid, 'an object open on entry should be left open')
finally:
fo.fclose()

def test_wrong_size_raises(self):
fname = self._write(np.random.rand(2, 2), 'g.ngrid')
with self.assertRaises(ValueError):
read_ngrid(fname, [3, 3])

def test_missing_file_raises(self):
with self.assertRaises(FileNotFoundError):
read_ngrid(os.path.join(self.root, 'missing.ngrid'), [2, 2])

def test_unknown_type_warns_and_reads_double(self):
x = np.random.rand(2, 2)
fname = self._write(x, 'h.ngrid')
with self.assertWarns(UserWarning):
y = read_ngrid(fname, [2, 2], 'notatype')
np.testing.assert_array_equal(y, x)


if __name__ == '__main__':
unittest.main()
Loading