block_from_array¶
- metatensor.block_from_array(array, sample_names: List[str] | None = None, component_names: List[str] | None = None, property_names: List[str] | None = None) TensorBlock[source]¶
Creates a simple TensorBlock from an array.
The metadata in the resulting
TensorBlockis filled with ranges of integers. This function should be seen as a quick way of creating aTensorBlockfrom arbitrary data. However, the metadata generated in this way has little meaning.- Parameters:
array – An array with two or more dimensions. This can either be a
numpy.ndarrayor atorch.Tensor.sample_names (List[str] | None) – A list containing
d_samplesnames for the sample dimensions. The firstd_samplesdimensions in the array will be interpreted as enumerating samples.Noneimplies a single dimension named"sample".property_names (List[str] | None) – A list containing
d_propertiesnames for the property dimensions. The lastd_propertiesdimensions in the array will be interpreted as enumerating properties.Noneimplies a single dimension named"property".component_names (List[str] | None) – A list containing
n_componentnames for the component dimensions. The middled_componentsdimensions in the array will be interpreted as enumerating components.Noneimplies that all the middle dimensions (after removing any sample and property dimensions) will be considered components, named"component_xxx".
- Returns:
A
TensorBlockwhose values correspond to the providedarray. If no name options are provided, the metadata names are set to"sample"for samples;"component_1","component_2", … for components; andpropertyfor properties. The number ofcomponentlabels is adapted to the dimensionality of the input array. If axes names are given, as indicated in the parameter list, the dimensions of the array will be interpreted accordingly, and indices also generated in a similar way. The metadata associated with each axis is a range of integers going from 0 to the size of the corresponding axis. The returnedTensorBlockhas no gradients.- Return type:
>>> import numpy as np >>> import metatensor as mts >>> # Construct a simple 4D array: >>> array = np.linspace(0, 10, 42).reshape((7, 3, 1, 2)) >>> # Transform it into a TensorBlock: >>> tensor_block = mts.block_from_array(array) >>> print(tensor_block) TensorBlock samples (7): ['sample'] components (3, 1): ['component_1', 'component_2'] properties (2): ['property'] gradients: None >>> # The data inside the TensorBlock will correspond to the provided array: >>> print(np.all(array == tensor_block.values)) True >>> # High-dimensional tensor >>> array = np.linspace(0, 10, 60).reshape((2, 3, 5, 1, 2)) >>> # Specify axes names: >>> tensor_block = mts.block_from_array( ... array, sample_names=["a", "b"], property_names=["y"] ... ) >>> print(tensor_block) TensorBlock samples (6): ['a', 'b'] components (5, 1): ['component_1', 'component_2'] properties (2): ['y'] gradients: None