Skip to content

Commit

Permalink
Convert NumPy arrays when updating _SyncedDict. (#185)
Browse files Browse the repository at this point in the history
* These tests should fail, demonstrating issue 184.

* Convert NumPy types when calling _dfs_convert.

* Update changelog.txt
  • Loading branch information
bdice authored and csadorf committed May 14, 2019
1 parent 39cafbe commit f8a08c3
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 0 deletions.
1 change: 1 addition & 0 deletions changelog.txt
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ next
- Fix: Passing an instance of dict to `H5Store.setdefault()` will return an instance of `H5Group` instead of a dict (#180).
- Improve the representation (return value of `repr()`) of instances of `H5Group`.
- Improve the representation (return value of `repr()`) of instances of `SyncedAttrDict`.
- Fix error with storing numpy arrays and scalars in a synced dictionary (e.g. `job.statepoint`, `job.document`) (#184).


[1.0.0] -- 2019-02-28
Expand Down
10 changes: 10 additions & 0 deletions signac/core/synceddict.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@
else:
from collections.abc import Mapping
from collections.abc import MutableMapping
try:
import numpy
NUMPY = True
except ImportError:
NUMPY = False


logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -107,6 +112,11 @@ def _dfs_convert(self, root):
return ret
elif type(root) is list:
return _SyncedList(root, self)
elif NUMPY:
if isinstance(root, numpy.number):
return root.item()
elif isinstance(root, numpy.ndarray):
return _SyncedList(root.tolist(), self)
return root

@classmethod
Expand Down
3 changes: 3 additions & 0 deletions tests/test_numpy_integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from test_project import BaseProjectTest
try:
import numpy # noqa
import numpy.testing
NUMPY = True
except ImportError:
NUMPY = False
Expand All @@ -19,6 +20,7 @@ def test_store_number_in_sp_and_doc(self):
b = numpy.float64(i) if i % 2 else numpy.float32(i)
job = self.project.open_job(dict(a=a))
job.doc.b = b
numpy.testing.assert_equal(job.doc.b, b)
for i, job in enumerate(sorted(self.project, key=lambda job: job.sp.a)):
self.assertEqual(job.sp.a, i)
self.assertEqual(job.doc.b, i)
Expand All @@ -34,6 +36,7 @@ def test_store_array_in_doc(self):
for i in range(10):
job = self.project.open_job(dict(a=i))
job.doc.array = numpy.ones(3) * i
numpy.testing.assert_equal(job.doc.array, numpy.ones(3) * i)
for i, job in enumerate(sorted(self.project, key=lambda job: job.sp.a)):
self.assertEqual(i, job.sp.a)
self.assertTrue(((numpy.array([i, i, i]) == job.doc.array).all()))
Expand Down

0 comments on commit f8a08c3

Please sign in to comment.