Source code for metatensor.io._tensor

from __future__ import annotations

import ctypes
import io
import json
import pathlib
import warnings
import zipfile
from typing import BinaryIO, Optional, Union

import numpy as np

from .._c_api import mts_create_array_callback_t
from .._c_lib import _get_library
from .._data import ArrayBackend
from .._status import check_pointer
from .._tensor import TensorMap
from ._block import (
    CreateArrayCallback,
    block_to_dict,
    single_block_from_mts,
)
from ._labels import labels_from_mts, labels_to_mts
from ._utils import (
    array_backend_for_create_array,
    create_array_for_array_backend,
    save_buffer_raw,
)


[docs] def load( file: Union[str, pathlib.Path, BinaryIO], use_numpy=False, *, array_backend: ArrayBackend = "numpy", ) -> TensorMap: """ Load a previously saved :py:class:`TensorMap` from the given file. :py:class:`TensorMap` are serialized using numpy's NPZ format, i.e. a ZIP file without compression (storage method is ``STORED``), where each file is stored as a ``.npy`` array. See the C API documentation for more information on the format. :param file: file to load: this can be a string, a :py:class:`pathlib.Path` containing the path to the file to load, or a file-like object that should be opened in binary mode. :param use_numpy: should we use numpy or the native implementation? Numpy should be able to process more dtypes than the native implementation, which is limited to float64, but the native implementation is usually faster than going through numpy. :param array_backend: array backend to use for all data in the :py:class:`TensorMap`. See :ref:`python-api-array-backend` for more information. """ if use_numpy: if array_backend != "numpy": raise ValueError("`array_backend` must be 'numpy' when `use_numpy` is True") return _tensor_from_mts(file) else: create_array = create_array_for_array_backend(array_backend) if isinstance(file, (str, pathlib.Path)): return load_custom_array(file, create_array) else: # assume we have a file-like object buffer = file.read() assert isinstance(buffer, bytes) return load_buffer_custom_array(buffer, create_array)
[docs] def load_buffer( buffer: Union[bytes, bytearray, memoryview], use_numpy=False, *, array_backend: ArrayBackend = "numpy", ) -> TensorMap: """ Load a previously saved :py:class:`TensorMap` from an in-memory buffer. :param buffer: In-memory buffer containing a serialized ``TensorMap`` :param use_numpy: should we use numpy or the native implementation? :param array_backend: array backend to use for all data in the :py:class:`TensorMap`. See :ref:`python-api-array-backend` for more information. """ if use_numpy: if array_backend != "numpy": raise ValueError("`array_backend` must be 'numpy' when `use_numpy` is True") return _tensor_from_mts(io.BytesIO(buffer)) else: create_array = create_array_for_array_backend(array_backend) return load_buffer_custom_array(buffer, create_array)
[docs] def load_custom_array( path: Union[str, pathlib.Path], create_array: CreateArrayCallback, *, array_backend: Optional[ArrayBackend] = None, ) -> TensorMap: """ Load a previously saved :py:class:`TensorMap` from the given path using a custom array creation callback. This advanced functionality should not be needed by most users. :py:func:`metatensor.io.create_numpy_array` and :py:func:`metatensor.io.create_torch_array` can be used as callbacks to load data into numpy and torch arrays respectively. :param path: path of the file to load :param create_array: callback used to create arrays as needed :param array_backend: array backend to use for all data in the :py:class:`TensorMap`. This is required for custom ``create_array`` callbacks, and guessed if the callback is one of :py:func:`metatensor.io.create_numpy_array` or :py:func:`metatensor.io.create_torch_array`. See :ref:`python-api-array-backend` for more information. """ lib = _get_library() if isinstance(path, str): path = path.encode("utf8") elif isinstance(path, pathlib.Path): path = bytes(path) ptr = lib.mts_tensormap_load(path, mts_create_array_callback_t(create_array)) check_pointer(ptr) return TensorMap.unsafe_from_ptr( ptr, array_backend=array_backend_for_create_array(create_array, array_backend) )
[docs] def load_buffer_custom_array( buffer: Union[bytes, bytearray, memoryview], create_array: CreateArrayCallback, *, array_backend: Optional[ArrayBackend] = None, ) -> TensorMap: """ Load a previously saved :py:class:`TensorMap` from the given buffer using a custom array creation callback. This advanced functionality should not be needed by most users. :py:func:`metatensor.io.create_numpy_array` and :py:func:`metatensor.io.create_torch_array` can be used as callbacks to load data into numpy and torch arrays respectively. :param buffer: in-memory buffer containing a saved :py:class:`TensorMap` :param create_array: callback used to create arrays as needed :param array_backend: array backend to use for all data in the :py:class:`TensorMap`. This is required for custom ``create_array`` callbacks, and guessed if the callback is one of :py:func:`metatensor.io.create_numpy_array` or :py:func:`metatensor.io.create_torch_array`. See :ref:`python-api-array-backend` for more information. """ lib = _get_library() array = np.frombuffer(buffer, dtype=np.uint8) ptr = lib.mts_tensormap_load_buffer( array.ctypes.data_as(ctypes.c_char_p), array.nbytes, mts_create_array_callback_t(create_array), ) check_pointer(ptr) return TensorMap.unsafe_from_ptr( ptr, array_backend=array_backend_for_create_array(create_array, array_backend) )
def save_tensor( file: Union[str, pathlib.Path, BinaryIO], tensor: TensorMap, use_numpy=False, ): assert isinstance(tensor, TensorMap) if use_numpy: all_entries = _tensor_to_dict(tensor) if not hasattr(file, "write"): # prevent numpy from adding a .npz extension by opening the file ourself with open(file, "wb") as fd: np.savez(fd, **all_entries) else: np.savez(file, **all_entries) info = tensor.info() if len(info) > 0: with zipfile.ZipFile(file, mode="a") as zf: with zf.open("info.json", mode="w", force_zip64=True) as info_file: info_str = json.dumps(info, indent=2) info_file.write(info_str.encode("utf8")) else: lib = _get_library() if isinstance(file, str): if not file.endswith(".mts"): file += ".mts" warnings.warn( message="adding '.mts' extension," f" the file will be saved at '{file}'", stacklevel=1, ) path = file.encode("utf8") lib.mts_tensormap_save(path, tensor._ptr) elif isinstance(file, pathlib.Path): if not file.name.endswith(".mts"): file = file.with_name(file.name + ".mts") warnings.warn( message="adding '.mts' extension," f" the file will be saved at '{file.name}'", stacklevel=1, ) path = bytes(file) lib.mts_tensormap_save(path, tensor._ptr) else: # assume we have a file-like object buffer = save_tensor_buffer_raw(tensor) file.write(buffer.raw) def save_tensor_buffer_raw(tensor: TensorMap) -> ctypes.Array: """ Save a TensorMap to an in-memory buffer, returning the data as a ctypes array of ``ctypes.c_char``. """ lib = _get_library() return save_buffer_raw(lib.mts_tensormap_save_buffer, tensor._ptr) def _tensor_to_dict(tensor_map): result = { "keys": labels_to_mts(tensor_map.keys), } for block_i, block in enumerate(tensor_map.blocks()): prefix = f"blocks/{block_i}/" result.update(block_to_dict(block, prefix, is_gradient=False)) return result def _tensor_from_mts(file): dictionary = np.load(file) keys = labels_from_mts(dictionary["keys"]) blocks = [] for block_i in range(len(keys)): prefix = f"blocks/{block_i}/" properties = labels_from_mts(dictionary[f"{prefix}properties"]) block = single_block_from_mts(prefix, dictionary, properties) blocks.append(block) tensor = TensorMap(keys, blocks) if "info.json" in dictionary: info_json = dictionary["info.json"].decode("utf8") for name, value in json.loads(info_json).items(): tensor.set_info(str(name), str(value)) return tensor