Exemple #1
0
    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 that keys from a dictionary should
                be used to compose an array. 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 dictionary, but key_order is not provided.

        """
        from yggdrasil.serialize import pandas2list, numpy2list, dict2list
        if isinstance(obj, pd.DataFrame):
            obj = pandas2list(obj)
        elif isinstance(obj, np.ndarray) and (len(obj.dtype) > 0):
            obj = numpy2list(obj)
        elif isinstance(obj, dict):
            if (key_order is not None) or (len(obj) == 1):
                obj = dict2list(obj, order=key_order)
            else:
                obj = [obj]
        elif isinstance(typedef, dict) and (len(typedef.get('items', [])) == 1):
            typedef_validated = kwargs.get('typedef_validated', False)
            if cls.check_decoded([obj], typedef,
                                 typedef_validated=typedef_validated):
                obj = [obj]
        return obj
Exemple #2
0
    def coerce_type(cls,
                    obj,
                    typedef=None,
                    key_order=None,
                    dont_wrap_single=False,
                    **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 that keys from a dictionary should
                be used to compose an array. Defaults to None.
            dont_wrap_single (bool, optional): If True, single element
                data types will not attempt to wrap input object in
                additional list. Defaults to False.
            **kwargs: Additional keyword arguments are metadata entries that may
                aid in coercing the type.

        Returns:
            object: Coerced object.

        Raises:
            RuntimeError: If obj is a dictionary, but key_order is not provided.

        """
        from yggdrasil.serialize import pandas2list, numpy2list, dict2list
        if isinstance(obj, pd.DataFrame):
            obj = pandas2list(obj)
        elif isinstance(obj, np.ndarray) and (len(obj.dtype) == 0):
            obj = [obj]
        elif isinstance(obj, np.ndarray) and (len(obj.dtype) > 0):
            obj = numpy2list(obj)
        elif isinstance(obj, dict):
            if (key_order is not None) or (len(obj) == 1):
                obj = dict2list(obj, order=key_order)
            elif (isinstance(typedef, dict)
                  and isinstance(typedef.get('items', None), list)
                  and all([('title' in x) for x in typedef['items']])):
                key_order = [x['title'] for x in typedef['items']]
                obj = dict2list(obj, order=key_order)
            else:
                obj = [obj]
        elif ((isinstance(typedef, dict) and (not dont_wrap_single)
               and (len(typedef.get('items', [])) == 1))):
            typedef_validated = kwargs.get('typedef_validated', False)
            try_obj = cls.coerce_type([obj],
                                      typedef=typedef,
                                      key_order=key_order,
                                      dont_wrap_single=True,
                                      **kwargs)
            if cls.check_decoded(try_obj,
                                 typedef,
                                 typedef_validated=typedef_validated):
                obj = try_obj
        return super(JSONArrayMetaschemaType, cls).coerce_type(obj,
                                                               typedef=typedef,
                                                               **kwargs)
Exemple #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)