示例#1
0
def test_coerce(nested_approx):
    r"""Test serialization of coerced types."""
    from yggdrasil import serialize
    from yggdrasil.metaschema.datatypes.JSONArrayMetaschemaType import (
        JSONArrayMetaschemaType)
    typedef = {'type': 'array', 'items': [{'type': '1darray',
                                           'subtype': 'float',
                                           'title': 'a',
                                           'precision': 64}]}
    x = JSONArrayMetaschemaType(**typedef)
    key_order = ['a']
    msg_recv = [np.zeros(3, 'float64')]
    msg_send_list = [msg_recv[0],
                     np.zeros(3, 'float32'),
                     serialize.list2numpy(msg_recv, names=key_order),
                     serialize.list2pandas(msg_recv, names=key_order),
                     serialize.list2dict(msg_recv, names=key_order)]

    def do_send_recv(msg_send):
        msg_seri = x.serialize(msg_send, tyepdef=typedef, key_order=key_order)
        assert(x.deserialize(msg_seri)[0] == nested_approx(msg_recv))

    for y in msg_send_list:
        do_send_recv(y)
    assert(JSONArrayMetaschemaType.coerce_type({'a': 'hello', 'b': 'world'})
           == [{'a': 'hello', 'b': 'world'}])
def test_coerce():
    r"""Test serialization of coerced types."""
    typedef = {
        'type':
        'array',
        'items': [{
            'type': '1darray',
            'subtype': 'float',
            'title': 'a',
            'precision': 64
        }]
    }
    x = JSONArrayMetaschemaType(**typedef)
    key_order = ['a']
    msg_recv = [np.zeros(3, 'float64')]
    msg_send_list = [
        msg_recv[0],
        serialize.list2numpy(msg_recv, names=key_order),
        serialize.list2pandas(msg_recv, names=key_order),
        serialize.list2dict(msg_recv, names=key_order)
    ]

    def do_send_recv(msg_send):
        msg_seri = x.serialize(msg_send, tyepdef=typedef, key_order=key_order)
        assert_equal(x.deserialize(msg_seri)[0], msg_recv)

    for y in msg_send_list:
        do_send_recv(y)
示例#3
0
def test_numpy2list():
    r"""Test conversion of a numpy array to a list and back."""
    with pytest.raises(TypeError):
        serialize.numpy2list(None)
    with pytest.raises(TypeError):
        serialize.list2numpy(None)
    nele = 5
    names = ["complex", "name", "number", "value"]
    dtypes = ['c16', 'S5', 'i8', 'f8']
    dtype = np.dtype([(n, f) for n, f in zip(names, dtypes)])
    arr_mix = np.zeros(nele, dtype)
    arr_mix['name'][0] = 'hello'
    test_arrs = [arr_mix]
    for ans in test_arrs:
        d = serialize.numpy2list(ans)
        # Name provided
        res = serialize.list2numpy(d, names=names)
        np.testing.assert_array_equal(ans, res)
示例#4
0
    def object2array(cls, obj, as_array=False, field_names=None, **kwargs):
        r"""Convert a message object into an array.

        Args:
            obj (object): Object that would be serialized by this class and
                should be returned in an array form.
            as_array (bool, optional): If True, the objects in the list
                are complete columns in a table and as_format is set to True.
                Defaults to False.
            field_names (list, optional): The field names associated with a
                table-like data type. Defaults to None. This keyword must be
                provided if as_array is True.
            **kwargs: Additional keyword arguments are ignored.

        Returns:
            np.array: Array version of the provided object.

        """
        if as_array:
            assert (field_names is not None)
            out = serialize.list2numpy(obj, names=field_names)
        else:
            out = super(DefaultSerialize, cls).object2array(obj, **kwargs)
        return out
示例#5
0
    def get_testing_options(cls, as_array=False, **kwargs):
        r"""Method to return a dictionary of testing options for this class.

        Returns:
            dict: Dictionary of variables to use for testing. Key/value pairs:
                kwargs (dict): Keyword arguments for comms tested with the
                    provided content.
                send (list): List of objects to send to test file.
                recv (list): List of objects that will be received from a test
                    file that was sent the messages in 'send'.
                contents (bytes): Bytes contents of test file created by sending
                    the messages in 'send'.

        """
        out = super(AsciiFileComm, cls).get_testing_options(as_array=as_array,
                                                            **kwargs)
        field_names = [
            backwards.as_str(x) for x in out['kwargs']['field_names']
        ]
        field_units = [
            backwards.as_str(x) for x in out['kwargs']['field_units']
        ]
        if as_array:
            lst = out['send'][0]
            out['recv'] = [[
                units.add_units(np.hstack([x[i] for x in out['send']]), u)
                for i, (n, u) in enumerate(zip(field_names, field_units))
            ]]
            out['dict'] = {k: l for k, l in zip(field_names, lst)}
            out['msg_array'] = serialize.list2numpy(lst, names=field_names)
        else:
            out['recv'] = out['send']
            out['dict'] = {k: v for k, v in zip(field_names, out['send'][0])}
        out['field_names'] = field_names
        out['field_units'] = field_units
        return out