Creating symmetric YASTN tensors#

Initializing symmetric tensors from scratch#

Symmetric tensor can be initialized as blank or, more precisely, empty. In this case only its rank (specified through tuple of signatures) and symmetry needs to be known when initializing such empty symmetric tensors. The data, in a form of non-zero blocks, can be added at later time.

See examples at Create empty tensor and fill it block by block.

class yastn.Tensor(config=None, s=(), n=None, isdiag=False, **kwargs)[source]#

Initialize empty (without any blocks allocated) YASTN tensor.

Parameters:
  • config (module | _config(NamedTuple)) – YASTN configuration

  • s (Sequence[int]) – a signature of tensor. Also determines the number of legs.

  • n (int | Sequence[int]) – total charge of the tensor. In case of direct product of several abelian symmetries, n is a tuple with total charge for each individual symmetry.

  • isdiag (bool) – distinguish diagonal tensor as a special case of a tensor.

Tensor.set_block(ts=(), Ds=None, val='zeros')#

Add new block to tensor or change the existing one.

This is the intended way to add new blocks by hand. Checks if bond dimensions of the new block are consistent with the existing ones and updates the legs of the tensors accordingly.

Parameters:
  • ts (Sequence[int] | Sequence[Sequence[int]]) – Charges identifing the block. Ignored if tensor has no symmetry.

  • Ds (Sequence[int]) – Dimensions of the block. If None, tries to infer dimensions from legs of the tensor.

  • val (tensor-like | str | tuple[str, tuple]) – recognized string values are 'ones', 'zeros', 'normal', 'rand', or a tuple ('rand', distribution), for uniform distribution in range given by tuple lim. Otherwise any tensor-like format such as nested list, numpy.ndarray, etc., can be used provided it is supported by tensor’s backend.

Basic creation operations#

See examples at Create tensors from scratch.

Basic creation operations includes operations such as creating random tensors, tensors filled with zeros, or diagonal identity tensors.

The symmetry structure of the tensor can be given either by directly listing all charge sectors for each leg and dimensions of these sectors or by passing a list of legs.

yastn.eye(config=None, legs=(), isdiag=True, **kwargs) Tensor[source]

Initialize diagonal tensor of identity matrix. In presence of symmetries, such matrix is block-diagonal with all allowed blocks filled with identity matrices.

Note

Currently supports either one or two legs as input. In case of a single leg, an identity matrix with Leg and its conjugate yastn.Leg.conj() is returned.

Parameters:
  • config (module | _config(NamedTuple)) – YASTN configuration

  • legs (Sequence[yastn.Leg]) – Specify legs of the tensor passing a list of yastn.Leg.

  • isdiag (bool) – Specify by bool whether to return explicitly diagonal tensor. If True, the signatures of the legs have to be opposite, and fused legs are not supported. If False, it supports having fused legs and any combination of signatures.

  • device (str) – Device on which the tensor should be initialized. Overrides attribute default_device specified in configuration.

  • s (Optional[Sequence[int]]) – (alternative) Tensor signature; should be (1, -1) or (-1, 1). The default is s=(1, -1).

  • t (Optional[Sequence[Sequence[int | Sequence[int]]]]) – (alternative) List of charges for each leg. The default is t=().

  • D (Optional[list]) – (alternative) List of corresponding bond dimensions. The default is D=().

Note

If any of s, t, or D are specified, legs are overriden and only t, D, and s are used.

yastn.ones(config=None, legs=(), n=None, isdiag=False, **kwargs) Tensor[source]

Initialize tensor with all allowed blocks filled with ones.

Parameters:
  • config (module | _config(NamedTuple)) – YASTN configuration

  • legs (Sequence[yastn.Leg]) – Specify legs of the tensor passing a list of yastn.Leg.

  • n (int | Sequence[int]) – total charge of the tensor.

  • isdiag (bool) – whether or not to make tensor diagonal.

  • dtype (str) – Desired datatype, overrides default_dtype specified in configuration.

  • device (str) – Device on which the tensor should be initialized. Overrides attribute default_device specified in configuration.

  • s (Optional[Sequence[int]]) – (alternative) Tensor signature. Also determines the number of legs. The default is s=().

  • t (Optional[Sequence[Sequence[int | Sequence[int]]]]) – (alternative) List of charges for each leg. The default is t=().

  • D (Optional[Sequence[Sequence[int]]]) – (alternative) List of corresponding bond dimensions. The default is D=().

Note

If any of s, t, or D are specified, legs are overriden and only t, D, and s are used.

yastn.rand(config=None, distribution=(-1, 1), legs=(), n=None, isdiag=False, **kwargs) Tensor[source]

Initialize tensor with all allowed blocks filled with random numbers.

Draws from a uniform distribution in the range specify by lim, or lim in real and imaginary part, depending on desired dtype. distribution='normal' invokes normal distribution with zero mean and standard deviation one. The default is distribution=(-1, 1).

Parameters:
  • config (module | _config(NamedTuple)) – YASTN configuration

  • distribution (tuple[int, int] | str) – The range from which the numbers are drawn from a uniform distribution. For distribution='normal' normal distribution is used.

  • legs (Sequence[yastn.Leg]) – Specify legs of the tensor passing a list of yastn.Leg.

  • n (int | Sequence[int]) – Total charge of the tensor.

  • isdiag (bool) – whether or not to make tensor diagonal.

  • dtype (str) – Desired datatype, overrides default_dtype specified in configuration.

  • device (str) – Device on which the tensor should be initialized. Overrides attribute default_device specified in configuration.

  • s (Optional[Sequence[int]]) – (alternative) Tensor signature. Also determines the number of legs. The default is s=().

  • t (Optional[Sequence[Sequence[int | Sequence[int]]]]) – (alternative) List of charges for each leg. The default is t=().

  • D (Optional[Sequence[Sequence[int]]]) – (alternative) List of corresponding bond dimensions. The default is D=().

Note

If any of s, t, or D are specified, legs are overriden and only t, D, and s are used.

yastn.randC(config=None, distribution=(-1, 1), legs=(), n=None, isdiag=False, **kwargs) Tensor[source]

Initialize tensor with all allowed blocks filled with complex random numbers, see yastn.rand().

yastn.randR(config=None, distribution=(-1, 1), legs=(), n=None, isdiag=False, **kwargs) Tensor[source]

Initialize tensor with all allowed blocks filled with real random numbers, see yastn.rand().

yastn.zeros(config=None, legs=(), n=None, isdiag=False, **kwargs) Tensor[source]

Initialize tensor with all allowed blocks filled with zeros.

Parameters:
  • config (module | _config(NamedTuple)) – YASTN configuration

  • legs (Sequence[yastn.Leg]) – Specify legs of the tensor passing a list of yastn.Leg.

  • n (int | Sequence[int]) – total charge of the tensor.

  • isdiag (bool) – whether or not to make tensor diagonal

  • dtype (str) – Desired datatype, overrides default_dtype specified in configuration.

  • device (str) – Device on which the tensor should be initialized. Overrides attribute default_device specified in configuration.

  • s (Optional[Sequence[int]]) – (alternative) Tensor signature. Also determines the number of legs. The default is s=().

  • t (Optional[Sequence[Sequence[int | Sequence[int]]]]) – (alternative) List of charges for each leg. The default is t=().

  • D (Optional[Sequence[Sequence[int]]]) – (alternative) List of corresponding bond dimensions. The default is D=().

Note

If any of s, t, or D are specified, legs are overriden and only t, D, and s are used.

Copying and cloning with autograd#

See examples at Clone, detach or copy tensors.

YASTN follows the semantics of PyTorch with regards to creating differentiable clones or non-differentiable copies of symmetric tensors. See clone and detach for PyTorch.

Tensor.copy() Tensor#

Return a copy of the tensor. Data of the resulting tensor is independent from the original.

Warning

This operation does not preserve autograd on returned yastn.Tensor.

Return type:

yastn.Tensor

Tensor.clone() Tensor#

Return a clone of the tensor preserving the autograd - resulting clone is a part of the computational graph. Data of the resulting tensor is indepedent from the original.

Tensor.detach() Tensor#

Detach tensor from the computational graph returning a view.

Data of the resulting tensor is a view of the original data. In case of NumPy backend, returns self.

Warning

This operation does not preserve autograd on returned yastn.Tensor.

Changing tensor’s device or dtype#

Support for different compute devices, i.e. CPU, GPU, or others, depends on the selected backend. For example

  • NumPy backend supports only CPU,

  • PyTorch backend supports also GPU (and other devices).

Tensors can be moved between devices and/or their dtype may be changed

Tensor.to(device=None, dtype=None, **kwargs) Tensor#

Move tensor to device and cast to given datatype.

Returns a clone of the tensor residing on device in desired datatype dtype. If tensor already resides on device, returns self. This operation preserves autograd. If no change is needed, makes only a shallow copy of the tensor data.

Parameters:
  • device (str) – device identifier

  • dtype (str) – desired dtype

Import/Export of YASTN tensors from/to different formats#

See examples at Serialization of symmetric tensors.

These utility operations can export and then import tensors from different formats. For example, exporting and importing tensor or MPS to and from a file.

yastn.Tensor.to_dict(a, level=2, meta=None) dict[source]#

Serialize YASTN tensor to a dictionary containing all the information needed to recreate the tensor. Complementary function is yastn.Tensor.from_dict() or a general yastn.from_dict().

Using argument level == 2 allows robust saving with numpy.save method.

Parameters:
  • a (yastn.Tensor) – tensor to serialize.

  • level (int) – Controls how much internal Tensor data and meta sub-classes are turned into basic python data structures. For level == 0, nothing is converted. For level >= 1, converts information about config and tensor block structure into python dictionaries. For level >= 2, turns tensor data into numpy array. Level == 2 (or == 1 for numpy backend) allows saving with numpy.save, which is the default.

  • meta (dict) – There is an option to provide meta-data obtained from earlier application of yastn.Tensor.to_dict(). Extra zero blocks (missing in tensor) are then included in the returned 1D array to make it consistent with structure given in meta. Raises error if tensor has some blocks which are not included in meta or otherwise meta does not match the tensor.

  • .. note::yastn.Tensor.to_dict() and yastn.Tensor.from_dict(), together with yastn.split_data_and_meta() and yastn.combine_data_and_meta() provide mechanism that allows using external matrix-free methods, such as eigs() implemented in SciPy. See example at Combining with scipy.sparse.linalg.eigs.

yastn.from_dict(d, config=None)[source]#

De-serializes an object from the dictionary d. Object type is read from d.

Parameters:
  • d (dict) – Object stored in form of a dictionary created with to_dict method.

  • config (Optional[module | _config(NamedTuple)]) – YASTN configuration If provided, overrides configuration stored in d.

yastn.Tensor.from_dict(d: dict, config: None | _config = None) Tensor#

De-serializes tensor from the dictionary d.

Parameters:
  • d (dict) – Tensor stored in form of a dictionary. Typically provided by an output of yastn.Tensor.to_dict().

  • config (Optional[module | _config(NamedTuple)]) – YASTN configuration If provided, overrides configuration stored in d.

yastn.Tensor.save_to_hdf5(a, file, path) None[source]#

Export tensor into hdf5 type file.

Complementary function is yastn.load_from_hdf5().

Parameters:

a (yastn.Tensor) – tensor to export.

yastn.load_from_hdf5(config, file, path) Tensor[source]#

Create tensor from hdf5 file.

Parameters:
  • config (module | _config(NamedTuple)) – YASTN configuration

  • file – pointer to opened HDF5 file.

  • path – path inside the file which contains the state.

yastn.Tensor.save_to_dict(a) dict[source]#

Export YASTN tensor to dictionary containing all the information needed to recreate the tensor.

Allows saving the tensor, e.g., with numpy.save().

Complementary function is yastn.load_from_dict().

!!! This method is deprecated; use to_dict(). !!!

Parameters:

a (yastn.Tensor) – tensor to export.

yastn.load_from_dict(config=None, d=None) Tensor[source]#

Create tensor from the dictionary d.

!!! This method is deprecated; use to_dict(). !!!

Parameters:

Dictionaries generated ny to_dict methods can be further split into tuple of data arrays and remaining metadata identifying the tensor structure (or structure of more complex objects, e.g., Mps or Peps) using yastn.split_data_and_meta() and later combined back with yastn.combine_data_and_meta().

yastn.split_data_and_meta(d: dict, squeeze=False) tuple[tuple['numpy.array' | 'torch.tensor'], dict][source]#

Split a dictionary generated by to_dict methods into a tuple containing data array, and a dictionary meta with remaining information. Meta is a copy of d, where data arrays are replaced with their position in the data tuple.

Parameters:
  • d (dict) – A result of to_dict method

  • squeeze (bool) – If True, and there is a single data tensor, it is unpacked from the tuple

  • Return

  • data, meta

yastn.combine_data_and_meta(data: tuple['numpy.array' | 'torch.tensor'], meta: dict) dict[source]#

Reverse yastn.split_data_and_meta().