From 05dd11a60d214c74645fac73a775face9d741df2 Mon Sep 17 00:00:00 2001 From: Sebastien Bourdeauducq Date: Sat, 25 Jul 2015 12:28:41 +0800 Subject: [PATCH] protocols/pyon: support numpy scalars (closes #53) --- artiq/protocols/pyon.py | 24 +++++++++++++++++++++++- artiq/test/serialization.py | 3 +++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/artiq/protocols/pyon.py b/artiq/protocols/pyon.py index 3998d8bc8..13161094e 100644 --- a/artiq/protocols/pyon.py +++ b/artiq/protocols/pyon.py @@ -39,6 +39,16 @@ _encode_map = { numpy.ndarray: "nparray" } +_numpy_scalar = { + "int8", "int16", "int32", "int64", "uint8", "uint16", "uint32", "uint64", + "float16", "float32", "float64" +} + + +for _t in _numpy_scalar: + _encode_map[getattr(numpy, _t)] = "npscalar" + + class _Encoder: def __init__(self, pretty): self.pretty = pretty @@ -114,6 +124,13 @@ class _Encoder: r += ")" return r + def encode_npscalar(self, x): + r = "npscalar(" + r += "\"" + type(x).__name__ + "\", " + r += encode(base64.b64encode(x).decode()) + r += ")" + return r + def encode(self, x): return getattr(self, "encode_" + _encode_map[type(x)])(x) @@ -131,6 +148,10 @@ def _nparray(shape, dtype, data): return a.reshape(shape) +def _npscalar(ty, data): + return numpy.frombuffer(base64.b64decode(data), dtype=ty)[0] + + _eval_dict = { "__builtins__": None, @@ -139,7 +160,8 @@ _eval_dict = { "true": True, "Fraction": Fraction, - "nparray": _nparray + "nparray": _nparray, + "npscalar": _npscalar } def decode(s): diff --git a/artiq/test/serialization.py b/artiq/test/serialization.py index 27e08bf30..7bcbed5eb 100644 --- a/artiq/test/serialization.py +++ b/artiq/test/serialization.py @@ -10,6 +10,9 @@ from artiq.protocols import pyon _pyon_test_object = { (1, 2): [(3, 4.2), (2, )], Fraction(3, 4): np.linspace(5, 10, 1), + "a": np.int8(9), "b": np.int16(-98), "c": np.int32(42), "d": np.int64(-5), + "e": np.uint8(8), "f": np.uint16(5), "g": np.uint32(4), "h": np.uint64(9), + "x": np.float16(9.0), "y": np.float32(9.0), "z": np.float64(9.0), }