Beispiel #1
0
def b2o(obj: Any, b: bytes) -> Any:
    if isinstance(obj, (int, float, bool, str, type(None))):
        return obj

    if isinstance(obj, list):
        return [b2o(value, b) for value in obj]

    assert isinstance(obj, dict)

    x = obj.get('__complex__')
    if x is not None:
        return complex(*x)

    x = obj.get('__ndarray__')
    if x is not None:
        shape, name, offset = x
        dtype = np.dtype(name)
        size = dtype.itemsize * np.prod(shape).astype(int)
        a = np.frombuffer(b[offset:offset + size], dtype)
        a.shape = shape
        if not np.little_endian:
            a = a.byteswap()
        return a

    dct = {key: b2o(value, b) for key, value in obj.items()}
    objtype = dct.pop('__ase_objtype__', None)
    if objtype is None:
        return dct
    return create_ase_object(objtype, dct)
Beispiel #2
0
def insert_ase_objects(obj):
    if isinstance(obj, dict):
        objtype = obj.pop('__ase_objtype__', None)
        if objtype is None:
            return {
                key: insert_ase_objects(value)
                for key, value in obj.items()
            }
        return create_ase_object(objtype, obj)
    if isinstance(obj, list):
        return [insert_ase_objects(value) for value in obj]
    return obj
Beispiel #3
0
def insert_ase_and_ndarray_objects(obj):
    if isinstance(obj, dict):
        objtype = obj.pop('__ase_objtype__', None)
        if objtype is not None:
            return create_ase_object(objtype, obj)
        data = obj.get('__ndarray__')
        if data is not None:
            return create_ndarray(*data)
        return {key: insert_ase_and_ndarray_objects(value)
                for key, value in obj.items()}
    if isinstance(obj, list):
        return [insert_ase_and_ndarray_objects(value) for value in obj]
    return obj