Skip to content

Commit

Permalink
Implement JSON serialization for numpy dtypes (#2456)
Browse files Browse the repository at this point in the history
Fixes #2453
  • Loading branch information
kevinsung authored and CirqBot committed Oct 30, 2019
1 parent dffd4ea commit d3cfe3f
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
9 changes: 8 additions & 1 deletion cirq/protocols/json.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
import json
import numbers
import pathlib
from typing import (
Union,
Expand Down Expand Up @@ -230,7 +231,13 @@ class CirqEncoder(json.JSONEncoder):
def default(self, o):
if hasattr(o, '_json_dict_'):
return o._json_dict_()
if isinstance(o, complex):
if isinstance(o, np.bool_):
return bool(o)
if isinstance(o, numbers.Integral):
return int(o)
if isinstance(o, numbers.Real):
return float(o)
if isinstance(o, numbers.Complex):
return {
'cirq_type': 'complex',
'real': o.real,
Expand Down
21 changes: 21 additions & 0 deletions cirq/protocols/json_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -528,13 +528,34 @@ def _roundtrip_test_classes() -> Iterator[Tuple[str, Type]]:


def test_builtins():
assert_roundtrip(True)
assert_roundtrip(1)
assert_roundtrip(1 + 2j)
assert_roundtrip({
'test': [123, 5.5],
'key2': 'asdf',
'3': None,
'0.0': [],
})


def test_numpy():
x = np.ones(1)[0]

assert_roundtrip(x.astype(np.bool))
assert_roundtrip(x.astype(np.int8))
assert_roundtrip(x.astype(np.int16))
assert_roundtrip(x.astype(np.int32))
assert_roundtrip(x.astype(np.int64))
assert_roundtrip(x.astype(np.uint8))
assert_roundtrip(x.astype(np.uint16))
assert_roundtrip(x.astype(np.uint32))
assert_roundtrip(x.astype(np.uint64))
assert_roundtrip(x.astype(np.float32))
assert_roundtrip(x.astype(np.float64))
assert_roundtrip(x.astype(np.complex64))
assert_roundtrip(x.astype(np.complex128))

assert_roundtrip(np.ones((11, 5)))
assert_roundtrip(np.arange(3))

Expand Down

0 comments on commit d3cfe3f

Please sign in to comment.