def coerce_type(cls, obj, typedef=None, key_order=None, **kwargs):
        r"""Coerce objects of specific types to match the data type.

        Args:
            obj (object): Object to be coerced.
            typedef (dict, optional): Type defintion that object should be
                coerced to. Defaults to None.
            key_order (list, optional): Order or keys correpsonding to elements in
                a provided list or tuple. Defaults to None.
            **kwargs: Additional keyword arguments are metadata entries that may
                aid in coercing the type.

        Returns:
            object: Coerced object.

        Raises:
            RuntimeError: If obj is a list or tuple, but key_order is not provided.

        """
        from yggdrasil.serialize import pandas2dict, numpy2dict, list2dict
        if isinstance(obj, pd.DataFrame):
            obj = pandas2dict(obj)
        elif isinstance(obj, np.ndarray) and (len(obj.dtype) > 0):
            obj = numpy2dict(obj)
        elif isinstance(obj, (list, tuple)) and (key_order is not None):
            obj = list2dict(obj, names=key_order)
        return obj
Ejemplo n.º 2
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)
Ejemplo n.º 4
0
    def object2dict(cls, obj, as_array=False, field_names=None, **kwargs):
        r"""Convert a message object into a dictionary.

        Args:
            obj (object): Object that would be serialized by this class and
                should be returned in a dictionary 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:
            dict: Dictionary version of the provided object.

        """
        if field_names is None:
            assert (not as_array)
            return super(DefaultSerialize, cls).object2dict(obj, **kwargs)
        else:
            out = serialize.list2dict(obj, names=field_names)
        return out