quimb.tensor.tensor_1d

Classes and algorithms related to 1D tensor networks.

Attributes

Classes

TensorNetworkGen

A tensor network which notionally has a single tensor per 'site',

TensorNetworkGenOperator

A tensor network which notionally has a single tensor and two outer

TensorNetworkGenVector

A tensor network which notionally has a single tensor and outer index

Tensor

A labelled, tagged n-dimensional array. The index labels are used

oset

An ordered set which stores elements as the keys of dict (ordered as of

TensorNetwork1D

Base class for tensor networks with a one-dimensional structure.

TensorNetwork1DVector

1D Tensor network which overall is like a vector with a single type of

TensorNetwork1DOperator

Base class for tensor networks with a one-dimensional structure.

TensorNetwork1DFlat

1D Tensor network which has a flat structure.

MatrixProductState

Initialise a matrix product state, with auto labelling and tagging.

MatrixProductOperator

Initialise a matrix product operator, with auto labelling and tagging.

Dense1D

Mimics other 1D tensor network structures, but really just keeps the

SuperOperator1D

A 1D tensor network super-operator class:

TNLinearOperator1D

A 1D tensor network linear operator like:

Functions

norm_trace_dense(A[, isherm])

Returns the trace norm of operator A, that is,

deprecated(fn, old_name, new_name)

Mark a function as deprecated, and indicate the new name.

ensure_dict(x)

Make sure x is a dict, creating an empty one if x is None.

pairwise(iterable)

Iterate over each pair of neighbours in iterable.

print_multi_line(*lines[, max_width])

Print multiple lines, with a maximum width.

tensor_network_ag_sum(tna, tnb[, site_tags, negate, ...])

Add two tensor networks with arbitrary, but matching, geometries. They

tensor_network_align(*tns[, ind_ids, trace, inplace])

Align an arbitrary number of tensor networks in a stack-like geometry:

tensor_network_apply_op_op(A, B[, which_A, which_B, ...])

Apply the operator (has upper and lower site inds) represented by tensor

tensor_network_apply_op_vec(A, x[, which_A, contract, ...])

Apply a general a general tensor network representing an operator (has

bonds(t1, t2)

Getting any indices connecting the Tensor(s) or TensorNetwork(s) t1

new_bond(T1, T2[, size, name, axis1, axis2])

Inplace addition of a new bond between tensors T1 and T2. The

rand_uuid([base])

Return a guaranteed unique, shortish identifier, optional appended

tags_to_oset(tags)

Parse a tags argument into an ordered set.

tensor_canonize_bond(T1, T2[, absorb, gauges, ...])

Inplace 'canonization' of two tensors. This gauges the bond between

tensor_compress_bond(T1, T2[, reduced, absorb, ...])

Inplace compress between the two single tensors. It follows the

expec_TN_1D(*tns[, compress, eps])

Compute the expectation of several 1D TNs, using transfer matrix

maybe_factor_gate_into_tensor(G, phys_dim, nsites, where)

gate_TN_1D(tn, G, where[, contract, tags, ...])

Act with the gate G on sites where, maintaining the outer

superop_TN_1D(tn_super, tn_op[, upper_ind_id, ...])

Take a tensor network superoperator and act with it on a

parse_cur_orthog([cur_orthog, info])

convert_cur_orthog(fn)

set_default_compress_mode(opts[, cyclic])

Module Contents

quimb.tensor.tensor_1d.norm_trace_dense(A, isherm=False)[source]

Returns the trace norm of operator A, that is, the sum of the absolute eigenvalues.

quimb.tensor.tensor_1d.deprecated(fn, old_name, new_name)[source]

Mark a function as deprecated, and indicate the new name.

quimb.tensor.tensor_1d.ensure_dict(x)[source]

Make sure x is a dict, creating an empty one if x is None.

quimb.tensor.tensor_1d.pairwise(iterable)[source]

Iterate over each pair of neighbours in iterable.

quimb.tensor.tensor_1d.print_multi_line(*lines, max_width=None)[source]

Print multiple lines, with a maximum width.

class quimb.tensor.tensor_1d.TensorNetworkGen(ts=(), *, virtual=False, check_collisions=True)[source]

Bases: quimb.tensor.tensor_core.TensorNetwork

A tensor network which notionally has a single tensor per ‘site’, though these could be labelled arbitrarily could also be linked in an arbitrary geometry by bonds.

_NDIMS = 1
_EXTRA_PROPS = ('_sites', '_site_tag_id')
_compatible_arbgeom(other)[source]

Check whether self and other represent the same set of sites and are tagged equivalently.

combine(other, *, virtual=False, check_collisions=True)[source]

Combine this tensor network with another, returning a new tensor network. If the two are compatible, cast the resulting tensor network to a TensorNetworkGen instance.

Parameters:
  • other (TensorNetworkGen or TensorNetwork) – The other tensor network to combine with.

  • virtual (bool, optional) – Whether the new tensor network should copy all the incoming tensors (False, the default), or view them as virtual (True).

  • check_collisions (bool, optional) – Whether to check for index collisions between the two tensor networks before combining them. If True (the default), any inner indices that clash will be mangled.

Return type:

TensorNetworkGen or TensorNetwork

property nsites
The total number of sites.
gen_site_coos()[source]

Generate the coordinates of all sites, same as self.sites.

property sites
Tuple of the possible sites in this tensor network.
_get_site_set()[source]

The set of all sites.

gen_sites_present()[source]

Generate the sites which are currently present (e.g. if a local view of a larger tensor network), based on whether their tags are present.

Examples

>>> tn = qtn.TN3D_rand(4, 4, 4, 2)
>>> tn_sub = tn.select_local('I1,2,3', max_distance=1)
>>> list(tn_sub.gen_sites_present())
[(0, 2, 3), (1, 1, 3), (1, 2, 2), (1, 2, 3), (1, 3, 3), (2, 2, 3)]
property site_tag_id
The string specifier for tagging each site of this tensor network.
site_tag(site)[source]

The name of the tag specifiying the tensor at site.

retag_sites(new_id, where=None, inplace=False)[source]

Modify the site tags for all or some tensors in this tensor network (without changing the site_tag_id).

Parameters:
  • new_id (str) – A string with a format placeholder to accept a site, e.g. “S{}”.

  • where (None or sequence) – Which sites to update the index labels on. If None (default) all sites.

  • inplace (bool) – Whether to retag in place.

property site_tags
All of the site tags.
property site_tags_present
All of the site tags still present in this tensor network.
retag_all(new_id, inplace=False)[source]

Retag all sites and change the site_tag_id.

retag_all_[source]
_get_site_tag_set()[source]

The oset of all site tags.

filter_valid_site_tags(tags)[source]

Get the valid site tags from tags.

maybe_convert_coo(x)[source]

Check if x is a valid site and convert to the corresponding site tag if so, else return x.

gen_tags_from_coos(coos)[source]

Generate the site tags corresponding to the given coordinates.

_get_tids_from_tags(tags, which='all')[source]

This is the function that lets coordinates such as site be used for many ‘tag’ based functions.

reset_cached_properties()[source]

Reset any cached properties, one should call this when changing the actual geometry of a TN inplace, for example.

align(*args, inplace=False, **kwargs)[source]
align_[source]
__add__(other)[source]
__sub__(other)[source]
__iadd__(other)[source]
__isub__(other)[source]
class quimb.tensor.tensor_1d.TensorNetworkGenOperator(ts=(), *, virtual=False, check_collisions=True)[source]

Bases: TensorNetworkGen

A tensor network which notionally has a single tensor and two outer indices per ‘site’, though these could be labelled arbitrarily and could also be linked in an arbitrary geometry by bonds. By convention, if converted to a dense matrix, the ‘upper’ indices would be on the left and the ‘lower’ indices on the right.

_EXTRA_PROPS = ('_sites', '_site_tag_id', '_upper_ind_id', '_lower_ind_id')
property upper_ind_id
The string specifier for the upper phyiscal indices.
upper_ind(site)[source]

Get the upper physical index name of site.

reindex_upper_sites(new_id, where=None, inplace=False)[source]

Modify the upper site indices for all or some tensors in this operator tensor network (without changing the upper_ind_id).

Parameters:
  • new_id (str) – A string with a format placeholder to accept a site, e.g. “up{}”.

  • where (None or sequence) – Which sites to update the index labels on. If None (default) all sites.

  • inplace (bool) – Whether to reindex in place.

reindex_upper_sites_[source]
property upper_inds
Return a tuple of all upper indices.
property upper_inds_present
Return a tuple of all upper indices still present in the tensor
network.
property lower_ind_id
The string specifier for the lower phyiscal indices.
lower_ind(site)[source]

Get the lower physical index name of site.

reindex_lower_sites(new_id, where=None, inplace=False)[source]

Modify the lower site indices for all or some tensors in this operator tensor network (without changing the lower_ind_id).

Parameters:
  • new_id (str) – A string with a format placeholder to accept a site, e.g. “up{}”.

  • where (None or sequence) – Which sites to update the index labels on. If None (default) all sites.

  • inplace (bool) – Whether to reindex in place.

reindex_lower_sites_[source]
property lower_inds
Return a tuple of all lower indices.
property lower_inds_present
Return a tuple of all lower indices still present in the tensor
network.
to_dense(*inds_seq, to_qarray=False, **contract_opts)[source]

Contract this tensor network ‘operator’ into a dense array.

Parameters:
  • inds_seq (sequence of sequences of str) – How to group the site indices into the dense array. By default, use a single group ordered like sites, but only containing those sites which are still present.

  • to_qarray (bool) – Whether to turn the dense array into a qarray, if the backend would otherwise be 'numpy'.

  • contract_opts – Options to pass to contract().

Return type:

array

to_qarray[source]
phys_dim(site=None, which='upper')[source]

Get the physical dimension of site.

gate_upper_with_op_lazy(A, transpose=False, inplace=False)[source]

Act lazily with the operator tensor network A, which should have matching structure, on this operator tensor network (B), like A @ B. The returned tensor network will have the same structure as this one, but with the operator gated in lazily, i.e. uncontracted.

\[B \rightarrow A B\]

or (if transpose=True):

\[B \rightarrow A^T B\]
Parameters:
  • A (TensorNetworkGenOperator) – The operator tensor network to gate with, or apply to this tensor network.

  • transpose (bool, optional) – Whether to contract the lower or upper indices of A with the upper indices of B. If False (the default), the lower indices of A will be contracted with the upper indices of B, if True the upper indices of A will be contracted with the upper indices of B, which is like applying the transpose first.

  • inplace (bool, optional) – Whether to perform the gate operation inplace on this tensor network.

Return type:

TensorNetworkGenOperator

gate_upper_with_op_lazy_[source]
gate_lower_with_op_lazy(A, transpose=False, inplace=False)[source]

Act lazily ‘from the right’ with the operator tensor network A, which should have matching structure, on this operator tensor network (B), like B @ A. The returned tensor network will have the same structure as this one, but with the operator gated in lazily, i.e. uncontracted.

\[B \rightarrow B A\]

or (if transpose=True):

\[B \rightarrow B A^T\]
Parameters:
  • A (TensorNetworkGenOperator) – The operator tensor network to gate with, or apply to this tensor network.

  • transpose (bool, optional) – Whether to contract the upper or lower indices of A with the lower indices of this TN. If False (the default), the upper indices of A will be contracted with the lower indices of B, if True the lower indices of A will be contracted with the lower indices of this TN, which is like applying the transpose first.

  • inplace (bool, optional) – Whether to perform the gate operation inplace on this tensor network.

Return type:

TensorNetworkGenOperator

gate_lower_with_op_lazy_[source]
gate_sandwich_with_op_lazy(A, inplace=False)[source]

Act lazily with the operator tensor network A, which should have matching structure, on this operator tensor network (B), like \(B \rightarrow A B A^\dagger\). The returned tensor network will have the same structure as this one, but with the operator gated in lazily, i.e. uncontracted.

Parameters:
  • A (TensorNetworkGenOperator) – The operator tensor network to gate with, or apply to this tensor network.

  • inplace (bool, optional) – Whether to perform the gate operation inplace on this tensor

Return type:

TensorNetworkGenOperator

gate_sandwich_with_op_lazy_[source]
class quimb.tensor.tensor_1d.TensorNetworkGenVector(ts=(), *, virtual=False, check_collisions=True)[source]

Bases: TensorNetworkGen

A tensor network which notionally has a single tensor and outer index per ‘site’, though these could be labelled arbitrarily and could also be linked in an arbitrary geometry by bonds.

_EXTRA_PROPS = ('_sites', '_site_tag_id', '_site_ind_id')
property site_ind_id
The string specifier for the physical indices.
site_ind(site)[source]
property site_inds
Return a tuple of all site indices.
property site_inds_present
All of the site inds still present in this tensor network.
reset_cached_properties()[source]

Reset any cached properties, one should call this when changing the actual geometry of a TN inplace, for example.

reindex_sites(new_id, where=None, inplace=False)[source]

Modify the site indices for all or some tensors in this vector tensor network (without changing the site_ind_id).

Parameters:
  • new_id (str) – A string with a format placeholder to accept a site, e.g. “ket{}”.

  • where (None or sequence) – Which sites to update the index labels on. If None (default) all sites.

  • inplace (bool) – Whether to reindex in place.

reindex_sites_[source]
reindex_all(new_id, inplace=False)[source]

Reindex all physical sites and change the site_ind_id.

reindex_all_[source]
gen_inds_from_coos(coos)[source]

Generate the site inds corresponding to the given coordinates.

phys_dim(site=None)[source]

Get the physical dimension of site, defaulting to the first site if not specified.

to_dense(*inds_seq, to_qarray=False, to_ket=None, **contract_opts)[source]

Contract this tensor network ‘vector’ into a dense array. By default, turn into a ‘ket’ qarray, i.e. column vector of shape (d, 1).

Parameters:
  • inds_seq (sequence of sequences of str) – How to group the site indices into the dense array. By default, use a single group ordered like sites, but only containing those sites which are still present.

  • to_qarray (bool) – Whether to turn the dense array into a qarray, if the backend would otherwise be 'numpy'.

  • to_ket (None or str) – Whether to reshape the dense array into a ket (shape (d, 1) array). If None (default), do this only if the inds_seq is not supplied.

  • contract_opts – Options to pass to contract().

Return type:

array

to_qarray[source]
gate_with_op_lazy(A, transpose=False, inplace=False, **kwargs)[source]

Act lazily with the operator tensor network A, which should have matching structure, on this vector/state tensor network, like A @ x. The returned tensor network will have the same structure as this one, but with the operator gated in lazily, i.e. uncontracted.

\[| x \rangle \rightarrow A | x \rangle\]

or (if transpose=True):

\[| x \rangle \rightarrow A^T | x \rangle\]
Parameters:
  • A (TensorNetworkGenOperator) – The operator tensor network to gate with, or apply to this tensor network.

  • transpose (bool, optional) – Whether to contract the lower or upper indices of A with the site indices of x. If False (the default), the lower indices of A will be contracted with the site indices of x, if True the upper indices of A will be contracted with the site indices of x, which is like applying A.T @ x.

  • inplace (bool, optional) – Whether to perform the gate operation inplace on this tensor network.

Return type:

TensorNetworkGenVector

gate_with_op_lazy_[source]
gate(G, where, contract=False, tags=None, propagate_tags=False, info=None, inplace=False, **compress_opts)[source]

Apply a gate to this vector tensor network at sites where. This is essentially a wrapper around gate_inds() apart from where can be specified as a list of sites, and tags can be optionally, intelligently propagated to the new gate tensor.

\[| \psi \rangle \rightarrow G_\mathrm{where} | \psi \rangle\]
Parameters:
  • G (array_ike) – The gate array to apply, should match or be factorable into the shape (*phys_dims, *phys_dims).

  • where (node or sequence[node]) – The sites to apply the gate to.

  • contract ({False, True, 'split', 'reduce-split', 'split-gate',) – ‘swap-split-gate’, ‘auto-split-gate’}, optional How to apply the gate, see gate_inds().

  • tags (str or sequence of str, optional) – Tags to add to the new gate tensor.

  • propagate_tags ({False, True, 'register', 'sites'}, optional) –

    Whether to propagate tags to the new gate tensor:

    - False: no tags are propagated
    - True: all tags are propagated
    - 'register': only site tags corresponding to ``where`` are
      added.
    - 'sites': all site tags on the current sites are propgated,
      resulting in a lightcone like tagging.
    

  • info (None or dict, optional) – Used to store extra optional information such as the singular values if not absorbed.

  • inplace (bool, optional) – Whether to perform the gate operation inplace on the tensor network or not.

  • compress_opts – Supplied to tensor_split() for any contract methods that involve splitting. Ignored otherwise.

Return type:

TensorNetworkGenVector

See also

TensorNetwork.gate_inds

gate_[source]
gate_simple_(G, where, gauges, renorm=True, **gate_opts)[source]

Apply a gate to this vector tensor network at sites where, using simple update style gauging of the tensors first, as supplied in gauges. The new singular values for the bond are reinserted into gauges.

Parameters:
  • G (array_like) – The gate to be applied.

  • where (node or sequence[node]) – The sites to apply the gate to.

  • gauges (dict[str, array_like]) – The store of gauge bonds, the keys being indices and the values being the vectors. Only bonds present in this dictionary will be used.

  • renorm (bool, optional) – Whether to renormalise the singular after the gate is applied, before reinserting them into gauges.

gate_fit_local_(G, where, max_distance=0, fillin=0, gauges=None, **fit_opts)[source]
local_expectation_cluster(G, where, normalized=True, max_distance=0, fillin=False, gauges=None, optimize='auto', max_bond=None, rehearse=False, **contract_opts)[source]

Approximately compute a single local expectation value of the gate G at sites where, either treating the environment beyond max_distance as the identity, or using simple update style bond gauges as supplied in gauges.

This selects a local neighbourhood of tensors up to distance max_distance away from where, then traces over dangling bonds after potentially inserting the bond gauges, to form an approximate version of the reduced density matrix.

\[\langle \psi | G | \psi \rangle \approx \frac{ \mathrm{Tr} [ G \tilde{\rho}_\mathrm{where} ] }{ \mathrm{Tr} [ \tilde{\rho}_\mathrm{where} ] }\]

assuming normalized==True.

Parameters:
  • G (array_like) – The gate to compute the expecation of.

  • where (node or sequence[node]) – The sites to compute the expectation at.

  • normalized (bool, optional) – Whether to locally normalize the result, i.e. divide by the expectation value of the identity.

  • max_distance (int, optional) – The maximum graph distance to include tensors neighboring where when computing the expectation. The default 0 means only the tensors at sites where are used.

  • fillin (bool or int, optional) – When selecting the local tensors, whether and how many times to ‘fill-in’ corner tensors attached multiple times to the local region. On a lattice this fills in the corners. See select_local().

  • gauges (dict[str, array_like], optional) – The store of gauge bonds, the keys being indices and the values being the vectors. Only bonds present in this dictionary will be used.

  • optimize (str or PathOptimizer, optional) – The contraction path optimizer to use, when exactly contracting the local tensors.

  • max_bond (None or int, optional) – If specified, use compressed contraction.

  • rehearse ({False, 'tn', 'tree', True}, optional) –

    Whether to perform the computations or not:

    - False: perform the computation.
    - 'tn': return the tensor networks of each local expectation,
      without running the path optimizer.
    - 'tree': run the path optimizer and return the
      ``cotengra.ContractonTree`` for each local expectation.
    - True: run the path optimizer and return the ``PathInfo`` for
      each local expectation.
    

Returns:

expectation

Return type:

float

local_expectation_simple[source]
compute_local_expectation_cluster(terms, *, max_distance=0, fillin=False, normalized=True, gauges=None, optimize='auto', max_bond=None, return_all=False, rehearse=False, executor=None, progbar=False, **contract_opts)[source]

Compute all local expectations of the given terms, either treating the environment beyond max_distance as the identity, or using simple update style bond gauges as supplied in gauges.

This selects a local neighbourhood of tensors up to distance max_distance away from each term’s sites, then traces over dangling bonds after potentially inserting the bond gauges, to form an approximate version of the reduced density matrix.

\[\sum_\mathrm{i} \langle \psi | G_\mathrm{i} | \psi \rangle \approx \sum_\mathrm{i} \frac{ \mathrm{Tr} [ G_\mathrm{i} \tilde{\rho}_\mathrm{i} ] }{ \mathrm{Tr} [ \tilde{\rho}_\mathrm{i} ] }\]

assuming normalized==True.

Parameters:
  • terms (dict[node or (node, node), array_like]) – The terms to compute the expectation of, with keys being the sites and values being the local operators.

  • max_distance (int, optional) – The maximum graph distance to include tensors neighboring each term’s sites when computing the expectation. The default 0 means only the tensors at sites of each term are used.

  • fillin (bool or int, optional) – When selecting the local tensors, whether and how many times to ‘fill-in’ corner tensors attached multiple times to the local region. On a lattice this fills in the corners. See select_local().

  • normalized (bool, optional) – Whether to locally normalize the result, i.e. divide by the expectation value of the identity. This implies that a different normalization factor is used for each term.

  • gauges (dict[str, array_like], optional) – The store of gauge bonds, the keys being indices and the values being the vectors. Only bonds present in this dictionary will be used.

  • optimize (str or PathOptimizer, optional) – The contraction path optimizer to use, when exactly contracting the local tensors.

  • max_bond (None or int, optional) – If specified, use compressed contraction.

  • return_all (bool, optional) – Whether to return all results, or just the summed expectation.

  • rehearse ({False, 'tn', 'tree', True}, optional) –

    Whether to perform the computations or not:

    - False: perform the computation.
    - 'tn': return the tensor networks of each local expectation,
      without running the path optimizer.
    - 'tree': run the path optimizer and return the
      ``cotengra.ContractonTree`` for each local expectation.
    - True: run the path optimizer and return the ``PathInfo`` for
      each local expectation.
    

  • executor (Executor, optional) – If supplied compute the terms in parallel using this executor.

  • progbar (bool, optional) – Whether to show a progress bar.

  • contract_opts – Supplied to contract().

Returns:

expecs – If return_all==False, return the summed expectation value of the given terms. Otherwise, return a dictionary mapping each term’s location to the expectation value.

Return type:

float or dict[node or (node, node), float]

compute_local_expectation_simple[source]
local_expectation_exact(G, where, optimize='auto-hq', normalized=True, rehearse=False, **contract_opts)[source]

Compute the local expectation of operator G at site(s) where by exactly contracting the full overlap tensor network.

compute_local_expectation_exact(terms, optimize='auto-hq', *, normalized=True, return_all=False, rehearse=False, executor=None, progbar=False, **contract_opts)[source]

Compute the local expectations of many operators, by exactly contracting the full overlap tensor network.

Parameters:
  • terms (dict[node or (node, node), array_like]) – The terms to compute the expectation of, with keys being the sites and values being the local operators.

  • optimize (str or PathOptimizer, optional) – The contraction path optimizer to use, when exactly contracting the full tensor network.

  • normalized (bool, optional) – Whether to normalize the result.

  • return_all (bool, optional) – Whether to return all results, or just the summed expectation.

  • rehearse ({False, 'tn', 'tree', True}, optional) –

    Whether to perform the computations or not:

    - False: perform the computation.
    - 'tn': return the tensor networks of each local expectation,
      without running the path optimizer.
    - 'tree': run the path optimizer and return the
      ``cotengra.ContractonTree`` for each local expectation.
    - True: run the path optimizer and return the ``PathInfo`` for
      each local expectation.
    

  • executor (Executor, optional) – If supplied compute the terms in parallel using this executor.

  • progbar (bool, optional) – Whether to show a progress bar.

  • contract_opts – Supplied to contract().

Returns:

expecs – If return_all==False, return the summed expectation value of the given terms. Otherwise, return a dictionary mapping each term’s location to the expectation value.

Return type:

float or dict[node or (node, node), float]

partial_trace(keep, max_bond, optimize, flatten=True, reduce=False, normalized=True, symmetrized='auto', rehearse=False, method='contract_compressed', **contract_compressed_opts)[source]

Partially trace this tensor network state, keeping only the sites in keep, using compressed contraction.

Parameters:
  • keep (iterable of hashable) – The sites to keep.

  • max_bond (int) – The maximum bond dimensions to use while compressed contracting.

  • optimize (str or PathOptimizer, optional) – The contraction path optimizer to use, should specifically generate contractions paths designed for compressed contraction.

  • flatten ({False, True, 'all'}, optional) – Whether to force ‘flattening’ (contracting all physical indices) of the tensor network before contraction, whilst this makes the TN generally more complex to contract, the accuracy is usually improved. If 'all' also flatten the tensors in keep.

  • reduce (bool, optional) – Whether to first ‘pull’ the physical indices off their respective tensors using QR reduction. Experimental.

  • normalized (bool, optional) – Whether to normalize the reduced density matrix at the end.

  • symmetrized ({'auto', True, False}, optional) – Whether to symmetrize the reduced density matrix at the end. This should be unecessary if flatten is set to True.

  • rehearse ({False, 'tn', 'tree', True}, optional) –

    Whether to perform the computation or not:

    - False: perform the computation.
    - 'tn': return the tensor network without running the path
      optimizer.
    - 'tree': run the path optimizer and return the
      ``cotengra.ContractonTree``..
    - True: run the path optimizer and return the ``PathInfo``.
    

  • contract_compressed_opts (dict, optional) – Additional keyword arguments to pass to contract_compressed().

Returns:

rho – The reduce density matrix of sites in keep.

Return type:

array_like

local_expectation(G, where, max_bond, optimize, flatten=True, normalized=True, symmetrized='auto', reduce=False, rehearse=False, **contract_compressed_opts)[source]

Compute the local expectation of operator G at site(s) where by approximately contracting the full overlap tensor network.

Parameters:
  • G (array_like) – The local operator to compute the expectation of.

  • where (node or sequence of nodes) – The sites to compute the expectation for.

  • max_bond (int) – The maximum bond dimensions to use while compressed contracting.

  • optimize (str or PathOptimizer, optional) – The contraction path optimizer to use, should specifically generate contractions paths designed for compressed contraction.

  • method ({'rho', 'rho-reduced'}, optional) – The method to use to compute the expectation value.

  • flatten (bool, optional) – Whether to force ‘flattening’ (contracting all physical indices) of the tensor network before contraction, whilst this makes the TN generally more complex to contract, the accuracy is usually much improved.

  • normalized (bool, optional) – If computing via partial_trace, whether to normalize the reduced density matrix at the end.

  • symmetrized ({'auto', True, False}, optional) – If computing via partial_trace, whether to symmetrize the reduced density matrix at the end. This should be unecessary if flatten is set to True.

  • rehearse ({False, 'tn', 'tree', True}, optional) –

    Whether to perform the computation or not:

    - False: perform the computation.
    - 'tn': return the tensor network without running the path
      optimizer.
    - 'tree': run the path optimizer and return the
      ``cotengra.ContractonTree``..
    - True: run the path optimizer and return the ``PathInfo``.
    

  • contract_compressed_opts (dict, optional) – Additional keyword arguments to pass to contract_compressed().

Returns:

expec

Return type:

float

compute_local_expectation(terms, max_bond, optimize, *, flatten=True, normalized=True, symmetrized='auto', reduce=False, return_all=False, rehearse=False, executor=None, progbar=False, **contract_compressed_opts)[source]

Compute the local expectations of many local operators, by approximately contracting the full overlap tensor network.

Parameters:
  • terms (dict[node or (node, node), array_like]) – The terms to compute the expectation of, with keys being the sites and values being the local operators.

  • max_bond (int) – The maximum bond dimension to use during contraction.

  • optimize (str or PathOptimizer) – The compressed contraction path optimizer to use.

  • method ({'rho', 'rho-reduced'}, optional) –

    The method to use to compute the expectation value.

    • ’rho’: compute the expectation value via the reduced density matrix.

    • ’rho-reduced’: compute the expectation value via the reduced density matrix, having reduced the physical indices onto the bonds first.

  • flatten (bool, optional) – Whether to force ‘flattening’ (contracting all physical indices) of the tensor network before contraction, whilst this makes the TN generally more complex to contract, the accuracy can often be much improved.

  • normalized (bool, optional) – Whether to locally normalize the result.

  • symmetrized ({'auto', True, False}, optional) – Whether to symmetrize the reduced density matrix at the end. This should be unecessary if flatten is set to True.

  • return_all (bool, optional) – Whether to return all results, or just the summed expectation. If rehease is not False, this is ignored and a dict is always returned.

  • rehearse ({False, 'tn', 'tree', True}, optional) –

    Whether to perform the computations or not:

    - False: perform the computation.
    - 'tn': return the tensor networks of each local expectation,
      without running the path optimizer.
    - 'tree': run the path optimizer and return the
      ``cotengra.ContractonTree`` for each local expectation.
    - True: run the path optimizer and return the ``PathInfo`` for
      each local expectation.
    

  • executor (Executor, optional) – If supplied compute the terms in parallel using this executor.

  • progbar (bool, optional) – Whether to show a progress bar.

  • contract_compressed_opts – Supplied to contract_compressed().

Returns:

expecs – If return_all==False, return the summed expectation value of the given terms. Otherwise, return a dictionary mapping each term’s location to the expectation value.

Return type:

float or dict[node or (node, node), float]

compute_local_expectation_rehearse[source]
compute_local_expectation_tn[source]
quimb.tensor.tensor_1d.tensor_network_ag_sum(tna, tnb, site_tags=None, negate=False, compress=False, inplace=False, **compress_opts)[source]

Add two tensor networks with arbitrary, but matching, geometries. They should have the same site tags, with a single tensor per site and sites connected by a single index only (but the name of this index can differ in the two TNs).

Parameters:
  • tna (TensorNetworkGen) – The first tensor network to add.

  • tnb (TensorNetworkGen) – The second tensor network to add.

  • site_tags (None or sequence of str, optional) – Which tags to consider as ‘sites’, by default uses tna.site_tags.

  • negate (bool, optional) – Whether to negate the second tensor network before adding.

  • compress (bool, optional) – Whether to compress the resulting tensor network, by calling the compress method with the given options.

  • inplace (bool, optional) – Whether to modify the first tensor network inplace.

Returns:

The resulting tensor network.

Return type:

TensorNetworkGen

quimb.tensor.tensor_1d.tensor_network_align(*tns, ind_ids=None, trace=False, inplace=False)[source]

Align an arbitrary number of tensor networks in a stack-like geometry:

a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a
| | | | | | | | | | | | | | | | | | <- ind_ids[0] (defaults to 1st id)
b-b-b-b-b-b-b-b-b-b-b-b-b-b-b-b-b-b
| | | | | | | | | | | | | | | | | | <- ind_ids[1]
               ...
| | | | | | | | | | | | | | | | | | <- ind_ids[-2]
y-y-y-y-y-y-y-y-y-y-y-y-y-y-y-y-y-y
| | | | | | | | | | | | | | | | | | <- ind_ids[-1]
z-z-z-z-z-z-z-z-z-z-z-z-z-z-z-z-z-z
Parameters:
  • tns (sequence of TensorNetwork) – The TNs to align, should be structured and either effective ‘vectors’ (have a site_ind_id) or ‘operators’ (have a up_ind_id and lower_ind_id).

  • ind_ids (None, or sequence of str) – String with format specifiers to id each level of sites with. Will be automatically generated like (tns[0].site_ind_id, "__ind_a{}__", "__ind_b{}__", ...) if not given.

  • inplace (bool) – Whether to modify the input tensor networks inplace.

Returns:

tns_aligned

Return type:

sequence of TensorNetwork

quimb.tensor.tensor_1d.tensor_network_apply_op_op(A, B, which_A='lower', which_B='upper', contract=False, fuse_multibonds=True, compress=False, inplace=False, inplace_A=False, **compress_opts)[source]

Apply the operator (has upper and lower site inds) represented by tensor network A to the operator represented by tensor network B. The resulting tensor network has the same upper and lower indices as B. Optionally contract the tensors at each site, fuse any multibonds, and compress the resulting tensor network.

This is like performing A.to_dense() @ B.to_dense(), or various combinations of tranposes thereof, depending on the values of which_A and which_B.

Parameters:
  • A (TensorNetworkGenOperator) – The tensor network representing the operator to apply.

  • B (TensorNetworkGenOperator) – The tensor network representing the target operator.

  • which_A ({"lower", "upper"}, optional) – Whether to contract the lower or upper indices of A.

  • which_B ({"lower", "upper"}, optional) – Whether to contract the lower or upper indices of B.

  • contract (bool) – Whether to contract the tensors at each site after applying the operator, yielding a single tensor at each site.

  • fuse_multibonds (bool) – If contract=True, whether to fuse any multibonds after contracting the tensors at each site.

  • compress (bool) – Whether to compress the resulting tensor network.

  • inplace (bool) – Whether to modify B, the target tensor network inplace.

  • inplace_A (bool) – Whether to modify A, the applied operator tensor network inplace.

  • compress_opts – Options to pass to tn.compress, where tn is the resulting tensor network, if compress=True.

Returns:

The same type as B.

Return type:

TensorNetworkGenOperator

quimb.tensor.tensor_1d.tensor_network_apply_op_vec(A, x, which_A='lower', contract=False, fuse_multibonds=True, compress=False, inplace=False, inplace_A=False, **compress_opts)[source]

Apply a general a general tensor network representing an operator (has upper_ind_id and lower_ind_id) to a tensor network representing a vector (has site_ind_id), by contracting each pair of tensors at each site then compressing the resulting tensor network. How the compression takes place is determined by the type of tensor network passed in. The returned tensor network has the same site indices as x, and it is the lower_ind_id of A that is contracted.

This is like performing A.to_dense() @ x.to_dense(), or the transpose thereof, depending on the value of which_A.

Parameters:
  • A (TensorNetworkGenOperator) – The tensor network representing the operator.

  • x (TensorNetworkGenVector) – The tensor network representing the vector.

  • which_A ({"lower", "upper"}, optional) – Whether to contract the lower or upper indices of A with the site indices of x.

  • contract (bool) – Whether to contract the tensors at each site after applying the operator, yielding a single tensor at each site.

  • fuse_multibonds (bool) – If contract=True, whether to fuse any multibonds after contracting the tensors at each site.

  • compress (bool) – Whether to compress the resulting tensor network.

  • inplace (bool) – Whether to modify x, the input vector tensor network inplace.

  • inplace_A (bool) – Whether to modify A, the operator tensor network inplace.

  • compress_opts – Options to pass to tn.compress, where tn is the resulting tensor network, if compress=True.

Returns:

The same type as x.

Return type:

TensorNetworkGenVector

class quimb.tensor.tensor_1d.Tensor(data=1.0, inds=(), tags=None, left_inds=None)[source]

A labelled, tagged n-dimensional array. The index labels are used instead of axis numbers to identify dimensions, and are preserved through operations. The tags are used to identify the tensor within networks, and are combined when tensors are contracted together.

Parameters:
  • data (numpy.ndarray) – The n-dimensional data.

  • inds (sequence of str) – The index labels for each dimension. Must match the number of dimensions of data.

  • tags (sequence of str, optional) – Tags with which to identify and group this tensor. These will be converted into a oset.

  • left_inds (sequence of str, optional) – Which, if any, indices to group as ‘left’ indices of an effective matrix. This can be useful, for example, when automatically applying unitary constraints to impose a certain flow on a tensor network but at the atomistic (Tensor) level.

Examples

Basic construction:

>>> from quimb import randn
>>> from quimb.tensor import Tensor
>>> X = Tensor(randn((2, 3, 4)), inds=['a', 'b', 'c'], tags={'X'})
>>> Y = Tensor(randn((3, 4, 5)), inds=['b', 'c', 'd'], tags={'Y'})

Indices are automatically aligned, and tags combined, when contracting:

>>> X @ Y
Tensor(shape=(2, 5), inds=('a', 'd'), tags={'Y', 'X'})
__slots__ = ('_data', '_inds', '_tags', '_left_inds', '_owners')
_set_data(data)[source]
_set_inds(inds)[source]
_set_tags(tags)[source]
_set_left_inds(left_inds)[source]
get_params()[source]

A simple function that returns the ‘parameters’ of the underlying data array. This is mainly for providing an interface for ‘structured’ arrays e.g. with block sparsity to interact with optimization.

set_params(params)[source]

A simple function that sets the ‘parameters’ of the underlying data array. This is mainly for providing an interface for ‘structured’ arrays e.g. with block sparsity to interact with optimization.

copy(deep=False, virtual=False)[source]

Copy this tensor.

Note

By default (deep=False), the underlying array will not be copied.

Parameters:
  • deep (bool, optional) – Whether to copy the underlying data as well.

  • virtual (bool, optional) – To conveniently mimic the behaviour of taking a virtual copy of tensor network, this simply returns self.

__copy__[source]
property data
property inds
property tags
property left_inds
check()[source]

Do some basic diagnostics on this tensor, raising errors if something is wrong.

property owners
add_owner(tn, tid)[source]

Add tn as owner of this Tensor - it’s tag and ind maps will be updated whenever this tensor is retagged or reindexed.

remove_owner(tn)[source]

Remove TensorNetwork tn as an owner of this Tensor.

check_owners()[source]

Check if this tensor is ‘owned’ by any alive TensorNetworks. Also trim any weakrefs to dead TensorNetworks.

_apply_function(fn)[source]
modify(**kwargs)[source]

Overwrite the data of this tensor in place.

Parameters:
  • data (array, optional) – New data.

  • apply (callable, optional) – A function to apply to the current data. If data is also given this is applied subsequently.

  • inds (sequence of str, optional) – New tuple of indices.

  • tags (sequence of str, optional) – New tags.

  • left_inds (sequence of str, optional) – New grouping of indices to be ‘on the left’.

apply_to_arrays(fn)[source]

Apply the function fn to the underlying data array(s). This is meant for changing how the raw arrays are backed (e.g. converting between dtypes or libraries) but not their ‘numerical meaning’.

isel(selectors, inplace=False)[source]

Select specific values for some dimensions/indices of this tensor, thereby removing them. Analogous to X[:, :, 3, :, :] with arrays. The indices to select from can be specified either by integer, in which case the correspoding index is removed, or by a slice.

Parameters:
  • selectors (dict[str, int], dict[str, slice]) – Mapping of index(es) to which value to take.

  • inplace (bool, optional) – Whether to select inplace or not.

Return type:

Tensor

Examples

>>> T = rand_tensor((2, 3, 4), inds=('a', 'b', 'c'))
>>> T.isel({'b': -1})
Tensor(shape=(2, 4), inds=('a', 'c'), tags=())

See also

TensorNetwork.isel

isel_[source]
add_tag(tag)[source]

Add a tag or multiple tags to this tensor. Unlike self.tags.add this also updates any TensorNetwork objects viewing this Tensor.

expand_ind(ind, size, mode=None, rand_strength=None, rand_dist='normal')[source]

Inplace increase the size of the dimension of ind, the new array entries will be filled with zeros by default.

Parameters:
  • name (str) – Name of the index to expand.

  • size (int, optional) – Size of the expanded index.

  • mode ({None, 'zeros', 'repeat', 'random'}, optional) – How to fill any new array entries. If 'zeros' then fill with zeros, if 'repeat' then repeatedly tile the existing entries. If 'random' then fill with random entries drawn from rand_dist, multiplied by rand_strength. If None then select from zeros or random depening on non-zero rand_strength.

  • rand_strength (float, optional) – If mode='random', a multiplicative scale for the random entries, defaulting to 1.0. If mode is None then supplying a non-zero value here triggers mode='random'.

  • rand_dist ({'normal', 'uniform', 'exp'}, optional) – If mode='random', the distribution to draw the random entries from.

new_ind(name, size=1, axis=0, mode=None, rand_strength=None, rand_dist='normal')[source]

Inplace add a new index - a named dimension. If size is specified to be greater than one then the new array entries will be filled with zeros.

Parameters:
  • name (str) – Name of the new index.

  • size (int, optional) – Size of the new index.

  • axis (int, optional) – Position of the new index.

  • mode ({None, 'zeros', 'repeat', 'random'}, optional) – How to fill any new array entries. If 'zeros' then fill with zeros, if 'repeat' then repeatedly tile the existing entries. If 'random' then fill with random entries drawn from rand_dist, multiplied by rand_strength. If None then select from zeros or random depening on non-zero rand_strength.

  • rand_strength (float, optional) – If mode='random', a multiplicative scale for the random entries, defaulting to 1.0. If mode is None then supplying a non-zero value here triggers mode='random'.

  • rand_dist ({'normal', 'uniform', 'exp'}, optional) – If mode='random', the distribution to draw the random entries from.

new_bond[source]
new_ind_with_identity(name, left_inds, right_inds, axis=0)[source]

Inplace add a new index, where the newly stacked array entries form the identity from left_inds to right_inds. Selecting 0 or 1 for the new index name thus is like ‘turning off’ this tensor if viewed as an operator.

Parameters:
  • name (str) – Name of the new index.

  • left_inds (tuple[str]) – Names of the indices forming the left hand side of the operator.

  • right_inds (tuple[str]) – Names of the indices forming the right hand side of the operator. The dimensions of these must match those of left_inds.

  • axis (int, optional) – Position of the new index.

new_ind_pair_with_identity(new_left_ind, new_right_ind, d, inplace=False)[source]

Expand this tensor with two new indices of size d, by taking an (outer) tensor product with the identity operator. The two new indices are added as axes at the start of the tensor.

Parameters:
  • new_left_ind (str) – Name of the new left index.

  • new_right_ind (str) – Name of the new right index.

  • d (int) – Size of the new indices.

  • inplace (bool, optional) – Whether to perform the expansion inplace.

Return type:

Tensor

new_ind_pair_with_identity_[source]
conj(inplace=False)[source]

Conjugate this tensors data (does nothing to indices).

conj_[source]
property H
Conjugate this tensors data (does nothing to indices).
property shape
The size of each dimension.
property ndim
The number of dimensions.
property size
The total number of array elements.
property dtype
The data type of the array elements.
property backend
The backend inferred from the data.
iscomplex()[source]
astype(dtype, inplace=False)[source]

Change the type of this tensor to dtype.

astype_[source]
max_dim()[source]

Return the maximum size of any dimension, or 1 if scalar.

ind_size(ind)[source]

Return the size of dimension corresponding to ind.

inds_size(inds)[source]

Return the total size of dimensions corresponding to inds.

shared_bond_size(other)[source]

Get the total size of the shared index(es) with other.

inner_inds()[source]

Get all indices that appear on two or more tensors.

transpose(*output_inds, inplace=False)[source]

Transpose this tensor - permuting the order of both the data and the indices. This operation is mainly for ensuring a certain data layout since for most operations the specific order of indices doesn’t matter.

Note to compute the tranditional ‘transpose’ of an operator within a contraction for example, you would just use reindexing not this.

Parameters:
  • output_inds (sequence of str) – The desired output sequence of indices.

  • inplace (bool, optional) – Perform the tranposition inplace.

Returns:

tt – The transposed tensor.

Return type:

Tensor

transpose_[source]
transpose_like(other, inplace=False)[source]

Transpose this tensor to match the indices of other, allowing for one index to be different. E.g. if self.inds = ('a', 'b', 'c', 'x') and other.inds = ('b', 'a', 'd', 'c') then ‘x’ will be aligned with ‘d’ and the output inds will be ('b', 'a', 'x', 'c')

Parameters:
  • other (Tensor) – The tensor to match.

  • inplace (bool, optional) – Perform the tranposition inplace.

Returns:

tt – The transposed tensor.

Return type:

Tensor

See also

transpose

transpose_like_[source]
moveindex(ind, axis, inplace=False)[source]

Move the index ind to position axis. Like transpose, this permutes the order of both the data and the indices and is mainly for ensuring a certain data layout since for most operations the specific order of indices doesn’t matter.

Parameters:
  • ind (str) – The index to move.

  • axis (int) – The new position to move ind to. Can be negative.

  • inplace (bool, optional) – Whether to perform the move inplace or not.

Return type:

Tensor

moveindex_[source]
item()[source]

Return the scalar value of this tensor, if it has a single element.

trace(left_inds, right_inds, preserve_tensor=False, inplace=False)[source]

Trace index or indices left_inds with right_inds, removing them.

Parameters:
  • left_inds (str or sequence of str) – The left indices to trace, order matching right_inds.

  • right_inds (str or sequence of str) – The right indices to trace, order matching left_inds.

  • preserve_tensor (bool, optional) – If True, a tensor will be returned even if no indices remain.

  • inplace (bool, optional) – Perform the trace inplace.

Returns:

z

Return type:

Tensor or scalar

sum_reduce(ind, inplace=False)[source]

Sum over index ind, removing it from this tensor.

Parameters:
  • ind (str) – The index to sum over.

  • inplace (bool, optional) – Whether to perform the reduction inplace.

Return type:

Tensor

sum_reduce_[source]
vector_reduce(ind, v, inplace=False)[source]

Contract the vector v with the index ind of this tensor, removing it.

Parameters:
  • ind (str) – The index to contract.

  • v (array_like) – The vector to contract with.

  • inplace (bool, optional) – Whether to perform the reduction inplace.

Return type:

Tensor

vector_reduce_[source]
collapse_repeated(inplace=False)[source]

Take the diagonals of any repeated indices, such that each index only appears once.

collapse_repeated_[source]
contract(*others, output_inds=None, **opts)[source]
direct_product(other, sum_inds=(), inplace=False)[source]
direct_product_[source]
split(*args, **kwargs)[source]
compute_reduced_factor(side, left_inds, right_inds, **split_opts)[source]
distance(other, **contract_opts)[source]
distance_normalized[source]
gate(G, ind, preserve_inds=True, inplace=False)[source]

Gate this tensor - contract a matrix into one of its indices without changing its indices. Unlike contract, G is a raw array and the tensor remains with the same set of indices.

Parameters:
  • G (2D array_like) – The matrix to gate the tensor index with.

  • ind (str) – Which index to apply the gate to.

Return type:

Tensor

Examples

Create a random tensor of 4 qubits:

>>> t = qtn.rand_tensor(
...    shape=[2, 2, 2, 2],
...    inds=['k0', 'k1', 'k2', 'k3'],
... )

Create another tensor with an X gate applied to qubit 2:

>>> Gt = t.gate(qu.pauli('X'), 'k2')

The contraction of these two tensors is now the expectation of that operator:

>>> t.H @ Gt
-4.108910576149794
gate_[source]
singular_values(left_inds, method='svd')[source]

Return the singular values associated with splitting this tensor according to left_inds.

Parameters:
  • left_inds (sequence of str) – A subset of this tensors indices that defines ‘left’.

  • method ({'svd', 'eig'}) – Whether to use the SVD or eigenvalue decomposition to get the singular values.

Returns:

The singular values.

Return type:

1d-array

entropy(left_inds, method='svd')[source]

Return the entropy associated with splitting this tensor according to left_inds.

Parameters:
  • left_inds (sequence of str) – A subset of this tensors indices that defines ‘left’.

  • method ({'svd', 'eig'}) – Whether to use the SVD or eigenvalue decomposition to get the singular values.

Return type:

float

retag(retag_map, inplace=False)[source]

Rename the tags of this tensor, optionally, in-place.

Parameters:
  • retag_map (dict-like) – Mapping of pairs {old_tag: new_tag, ...}.

  • inplace (bool, optional) – If False (the default), a copy of this tensor with the changed tags will be returned.

retag_[source]
reindex(index_map, inplace=False)[source]

Rename the indices of this tensor, optionally in-place.

Parameters:
  • index_map (dict-like) – Mapping of pairs {old_ind: new_ind, ...}.

  • inplace (bool, optional) – If False (the default), a copy of this tensor with the changed inds will be returned.

reindex_[source]
fuse(fuse_map, inplace=False)[source]

Combine groups of indices into single indices.

Parameters:

fuse_map (dict_like or sequence of tuples.) – Mapping like: {new_ind: sequence of existing inds, ...} or an ordered mapping like [(new_ind_1, old_inds_1), ...] in which case the output tensor’s fused inds will be ordered. In both cases the new indices are created at the minimum axis of any of the indices that will be fused.

Returns:

The transposed, reshaped and re-labeled tensor.

Return type:

Tensor

fuse_[source]
unfuse(unfuse_map, shape_map, inplace=False)[source]

Reshape single indices into groups of multiple indices

Parameters:
  • unfuse_map (dict_like or sequence of tuples.) – Mapping like: {existing_ind: sequence of new inds, ...} or an ordered mapping like [(old_ind_1, new_inds_1), ...] in which case the output tensor’s new inds will be ordered. In both cases the new indices are created at the old index’s position of the tensor’s shape

  • shape_map (dict_like or sequence of tuples) – Mapping like: {old_ind: new_ind_sizes, ...} or an ordered mapping like [(old_ind_1, new_ind_sizes_1), ...].

Returns:

The transposed, reshaped and re-labeled tensor

Return type:

Tensor

unfuse_[source]
to_dense(*inds_seq, to_qarray=False)[source]

Convert this Tensor into an dense array, with a single dimension for each of inds in inds_seqs. E.g. to convert several sites into a density matrix: T.to_dense(('k0', 'k1'), ('b0', 'b1')).

to_qarray[source]
squeeze(include=None, exclude=None, inplace=False)[source]

Drop any singlet dimensions from this tensor.

Parameters:
  • inplace (bool, optional) – Whether modify the original or return a new tensor.

  • include (sequence of str, optional) – Only squeeze dimensions with indices in this list.

  • exclude (sequence of str, optional) – Squeeze all dimensions except those with indices in this list.

  • inplace – Whether to perform the squeeze inplace or not.

Return type:

Tensor

squeeze_[source]
largest_element()[source]

Return the largest element, in terms of absolute magnitude, of this tensor.

idxmin(f=None)[source]

Get the index configuration of the minimum element of this tensor, optionally applying f first.

Parameters:

f (callable or str, optional) – If a callable, apply this function to the tensor data before finding the minimum element. If a string, apply autoray.do(f, data).

Returns:

Mapping of index names to their values at the minimum element.

Return type:

dict[str, int]

idxmax(f=None)[source]

Get the index configuration of the maximum element of this tensor, optionally applying f first.

Parameters:

f (callable or str, optional) – If a callable, apply this function to the tensor data before finding the maximum element. If a string, apply autoray.do(f, data).

Returns:

Mapping of index names to their values at the maximum element.

Return type:

dict[str, int]

norm()[source]

Frobenius norm of this tensor:

\[\|t\|_F = \sqrt{\mathrm{Tr} \left(t^{\dagger} t\right)}\]

where the trace is taken over all indices. Equivalent to the square root of the sum of squared singular values across any partition.

normalize(inplace=False)[source]
normalize_[source]
symmetrize(ind1, ind2, inplace=False)[source]

Hermitian symmetrize this tensor for indices ind1 and ind2. I.e. T = (T + T.conj().T) / 2, where the transpose is taken only over the specified indices.

symmetrize_[source]
isometrize(left_inds=None, method='qr', inplace=False)[source]

Make this tensor unitary (or isometric) with respect to left_inds. The underlying method is set by method.

Parameters:
  • left_inds (sequence of str) – The indices to group together and treat as the left hand side of a matrix.

  • method (str, optional) –

    The method used to generate the isometry. The options are:

    • ”qr”: use the Q factor of the QR decomposition of x with the constraint that the diagonal of R is positive.

    • ”svd”: uses U @ VH of the SVD decomposition of x. This is useful for finding the ‘closest’ isometric matrix to x, such as when it has been expanded with noise etc. But is less stable for differentiation / optimization.

    • ”exp”: use the matrix exponential of x - dag(x), first completing x with zeros if it is rectangular. This is a good parametrization for optimization, but more expensive for non-square x.

    • ”cayley”: use the Cayley transform of x - dag(x), first completing x with zeros if it is rectangular. This is a good parametrization for optimization (one the few compatible with HIPS/autograd e.g.), but more expensive for non-square x.

    • ”householder”: use the Householder reflection method directly. This requires that the backend implements “linalg.householder_product”.

    • ”torch_householder”: use the Householder reflection method directly, using the torch_householder package. This requires that the package is installed and that the backend is "torch". This is generally the best parametrizing method for “torch” if available.

    • ”mgs”: use a python implementation of the modified Gram Schmidt method directly. This is slow if not compiled but a useful reference.

    Not all backends support all methods or differentiating through all methods.

  • inplace (bool, optional) – Whether to perform the unitization inplace.

Return type:

Tensor

isometrize_[source]
unitize[source]
unitize_
randomize(dtype=None, inplace=False, **randn_opts)[source]

Randomize the entries of this tensor.

Parameters:
  • dtype ({None, str}, optional) – The data type of the random entries. If left as the default None, then the data type of the current array will be used.

  • inplace (bool, optional) – Whether to perform the randomization inplace, by default False.

  • randn_opts – Supplied to randn().

Return type:

Tensor

randomize_[source]
flip(ind, inplace=False)[source]

Reverse the axis on this tensor corresponding to ind. Like performing e.g. X[:, :, ::-1, :].

flip_[source]
multiply_index_diagonal(ind, x, inplace=False)[source]

Multiply this tensor by 1D array x as if it were a diagonal tensor being contracted into index ind.

multiply_index_diagonal_[source]
almost_equals(other, **kwargs)[source]

Check if this tensor is almost the same as another.

drop_tags(tags=None)[source]

Drop certain tags, defaulting to all, from this tensor.

bonds(other)[source]

Return a tuple of the shared indices between this tensor and other.

filter_bonds(other)[source]

Sort this tensor’s indices into a list of those that it shares and doesn’t share with another tensor.

Parameters:

other (Tensor) – The other tensor.

Returns:

shared, unshared – The shared and unshared indices.

Return type:

(tuple[str], tuple[str])

__imul__(other)[source]
__itruediv__(other)[source]
__and__(other)[source]

Combine with another Tensor or TensorNetwork into a new TensorNetwork.

__or__(other)[source]

Combine virtually (no copies made) with another Tensor or TensorNetwork into a new TensorNetwork.

__matmul__(other)[source]

Explicitly contract with another tensor. Avoids some slight overhead of calling the full tensor_contract().

negate(inplace=False)[source]

Negate this tensor.

negate_[source]
__neg__()[source]

Negate this tensor.

as_network(virtual=True)[source]

Return a TensorNetwork with only this tensor.

draw(*args, **kwargs)[source]

Plot a graph of this tensor and its indices.

graph[source]
visualize[source]
__getstate__()[source]

Helper for pickle.

__setstate__(state)[source]
_repr_info()[source]

General info to show in various reprs. Sublasses can add more relevant info to this dict.

_repr_info_extra()[source]

General detailed info to show in various reprs. Sublasses can add more relevant info to this dict.

_repr_info_str(normal=True, extra=False)[source]

Render the general info as a string.

_repr_html_()[source]

Render this Tensor as HTML, for Jupyter notebooks.

__str__()[source]

Return str(self).

__repr__()[source]

Return repr(self).

quimb.tensor.tensor_1d.bonds(t1, t2)[source]

Getting any indices connecting the Tensor(s) or TensorNetwork(s) t1 and t2.

quimb.tensor.tensor_1d.new_bond(T1, T2, size=1, name=None, axis1=0, axis2=0)[source]

Inplace addition of a new bond between tensors T1 and T2. The size of the new bond can be specified, in which case the new array parts will be filled with zeros.

Parameters:
  • T1 (Tensor) – First tensor to modify.

  • T2 (Tensor) – Second tensor to modify.

  • size (int, optional) – Size of the new dimension.

  • name (str, optional) – Name for the new index.

  • axis1 (int, optional) – Position on the first tensor for the new dimension.

  • axis2 (int, optional) – Position on the second tensor for the new dimension.

class quimb.tensor.tensor_1d.oset(it=())[source]

An ordered set which stores elements as the keys of dict (ordered as of python 3.6). ‘A few times’ slower than using a set directly for small sizes, but makes everything deterministic.

__slots__ = ('_d',)
classmethod _from_dict(d)[source]
classmethod from_dict(d)[source]

Public method makes sure to copy incoming dictionary.

copy()[source]
__deepcopy__(memo)[source]
add(k)[source]
discard(k)[source]
remove(k)[source]
clear()[source]
update(*others)[source]
union(*others)[source]
intersection_update(*others)[source]
intersection(*others)[source]
difference_update(*others)[source]
difference(*others)[source]
popleft()[source]
popright()[source]
pop[source]
__eq__(other)[source]

Return self==value.

__or__(other)[source]
__ior__(other)[source]
__and__(other)[source]
__iand__(other)[source]
__sub__(other)[source]
__isub__(other)[source]
__len__()[source]
__iter__()[source]
__contains__(x)[source]
__repr__()[source]

Return repr(self).

quimb.tensor.tensor_1d.rand_uuid(base='')[source]

Return a guaranteed unique, shortish identifier, optional appended to base.

Examples

>>> rand_uuid()
'_2e1dae1b'
>>> rand_uuid('virt-bond')
'virt-bond_bf342e68'
quimb.tensor.tensor_1d.tags_to_oset(tags)[source]

Parse a tags argument into an ordered set.

quimb.tensor.tensor_1d.tensor_canonize_bond(T1, T2, absorb='right', gauges=None, gauge_smudge=1e-06, **split_opts)[source]

Inplace ‘canonization’ of two tensors. This gauges the bond between the two such that T1 is isometric:

  |   |          |   |          |   |
--1---2--  =>  -->~R-2--  =>  -->~~~O--
  |   |          |   |          |   |
  .                ...
 <QR>              contract
Parameters:
  • T1 (Tensor) – The tensor to be isometrized.

  • T2 (Tensor) – The tensor to absorb the R-factor into.

  • absorb ({'right', 'left', 'both', None}, optional) – Which tensor to effectively absorb the singular values into.

  • split_opts – Supplied to tensor_split(), with modified defaults of method=='qr' and absorb='right'.

quimb.tensor.tensor_1d.tensor_compress_bond(T1, T2, reduced=True, absorb='both', gauges=None, gauge_smudge=1e-06, info=None, **compress_opts)[source]

Inplace compress between the two single tensors. It follows the following steps (by default) to minimize the size of SVD performed:

a)│   │        b)│        │        c)│       │
━━●━━━●━━  ->  ━━>━━○━━○━━<━━  ->  ━━>━━━M━━━<━━
  │   │          │  ....  │          │       │
 <*> <*>          contract              <*>
 QR   LQ            -><-                SVD

          d)│            │        e)│   │
      ->  ━━>━━━ML──MR━━━<━━  ->  ━━●───●━━
            │....    ....│          │   │
          contract  contract          ^compressed bond
            -><-      -><-
Parameters:
  • T1 (Tensor) – The left tensor.

  • T2 (Tensor) – The right tensor.

  • max_bond (int or None, optional) – The maxmimum bond dimension.

  • cutoff (float, optional) – The singular value cutoff to use.

  • reduced ({True, False, "left", "right"}, optional) – Whether to perform the QR reduction as above or not. If False, contract both tensors together and perform a single SVD. If ‘left’ or ‘right’ then just perform the svd on the left or right tensor respectively. This can still be optimal if the other tensor is already isometric, i.e. the pair are right or left canonical respectively.

  • absorb ({'both', 'left', 'right', None}, optional) – Where to absorb the singular values after decomposition.

  • info (None or dict, optional) – A dict for returning extra information such as the singular values.

  • compress_opts – Supplied to tensor_split().

quimb.tensor.tensor_1d.align_TN_1D[source]
quimb.tensor.tensor_1d.expec_TN_1D(*tns, compress=None, eps=1e-15)[source]

Compute the expectation of several 1D TNs, using transfer matrix compression if any are periodic.

Parameters:
  • tns (sequence of TensorNetwork1D) – The MPS and MPO to find expectation of. Should start and begin with an MPS e.g. (MPS, MPO, ...,  MPS).

  • compress ({None, False, True}, optional) – Whether to perform transfer matrix compression on cyclic systems. If set to None (the default), decide heuristically.

  • eps (float, optional) – The accuracy of the transfer matrix compression.

Returns:

x – The expectation value.

Return type:

float

quimb.tensor.tensor_1d.maybe_factor_gate_into_tensor(G, phys_dim, nsites, where)[source]
quimb.tensor.tensor_1d.gate_TN_1D(tn, G, where, contract=False, tags=None, propagate_tags='sites', info=None, inplace=False, cur_orthog=None, **compress_opts)[source]

Act with the gate G on sites where, maintaining the outer indices of the 1D tensor network:

contract=False       contract=True
    . .                    . .             <- where
o-o-o-o-o-o-o        o-o-o-GGG-o-o-o
| | | | | | |        | | | / \ | | |
    GGG
    | |


contract='split-gate'        contract='swap-split-gate'
      . .                          . .                      <- where
  o-o-o-o-o-o-o                o-o-o-o-o-o-o
  | | | | | | |                | | | | | | |
      G~G                          G~G
      | |                          \ /
                                    X
                                   / \

contract='swap+split'
        . .            <- where
  o-o-o-G=G-o-o-o
  | | | | | | | |

Note that the sites in where do not have to be contiguous. By default, site tags will be propagated to the gate tensors, identifying a ‘light cone’.

Parameters:
  • tn (TensorNetwork1DVector) – The 1D vector-like tensor network, for example, and MPS.

  • G (array) – A square array to act with on sites where. It should have twice the number of dimensions as the number of sites. The second half of these will be contracted with the MPS, and the first half indexed with the correct site_ind_id. Sites are read left to right from the shape. A two-dimensional array is permissible if each dimension factorizes correctly.

  • where (int or sequence of int) – Where the gate should act.

  • contract ({False, 'split-gate', 'swap-split-gate',) –

    ‘auto-split-gate’, True, ‘swap+split’}, optional Whether to contract the gate into the 1D tensor network. If,

    • False: leave the gate uncontracted, the default

    • ’split-gate’: like False, but split the gate if it is two-site.

    • ’swap-split-gate’: like ‘split-gate’, but decompose the gate as if a swap had first been applied

    • ’auto-split-gate’: automatically select between the above three options, based on the rank of the gate.

    • True: contract the gate into the tensor network, if the gate acts on more than one site, this will produce an ever larger tensor.

    • ’swap+split’: Swap sites until they are adjacent, then contract the gate and split the resulting tensor, then swap the sites back to their original position. In this way an MPS structure can be explicitly maintained at the cost of rising bond-dimension.

  • tags (str or sequence of str, optional) – Tag the new gate tensor with these tags.

  • propagate_tags ({'sites', 'register', False, True}, optional) –

    Add any tags from the sites to the new gate tensor (only matters if contract=False else tags are merged anyway):

    • If 'sites', then only propagate tags matching e.g. ‘I{}’ and ignore all others. I.e. just propagate the lightcone.

    • If 'register', then only propagate tags matching the sites of where this gate was actually applied. I.e. ignore the lightcone, just keep track of which ‘registers’ the gate was applied to.

    • If False, propagate nothing.

    • If True, propagate all tags.

  • inplace – Perform the gate in place.

  • bool – Perform the gate in place.

  • optional – Perform the gate in place.

  • compress_opts – Supplied to split() if contract='swap+split' or gate_with_auto_swap() if contract='swap+split'.

Return type:

TensorNetwork1DVector

Examples

>>> p = MPS_rand_state(3, 7)
>>> p.gate_(spin_operator('X'), where=1, tags=['GX'])
>>> p
<MatrixProductState(tensors=4, L=3, max_bond=7)>
>>> p.outer_inds()
('k0', 'k1', 'k2')
quimb.tensor.tensor_1d.superop_TN_1D(tn_super, tn_op, upper_ind_id='k{}', lower_ind_id='b{}', so_outer_upper_ind_id=None, so_inner_upper_ind_id=None, so_inner_lower_ind_id=None, so_outer_lower_ind_id=None)[source]

Take a tensor network superoperator and act with it on a tensor network operator, maintaining the original upper and lower indices of the operator:

outer_upper_ind_id                           upper_ind_id
   | | | ... |                               | | | ... |
   +----------+                              +----------+
   | tn_super +---+                          | tn_super +---+
   +----------+   |     upper_ind_id         +----------+   |
   | | | ... |    |      | | | ... |         | | | ... |    |
inner_upper_ind_id|     +-----------+       +-----------+   |
                  |  +  |   tn_op   |   =   |   tn_op   |   |
inner_lower_ind_id|     +-----------+       +-----------+   |
   | | | ... |    |      | | | ... |         | | | ... |    |
   +----------+   |      lower_ind_id        +----------+   |
   | tn_super +---+                          | tn_super +---+
   +----------+                              +----------+
   | | | ... | <--                           | | | ... |
outer_lower_ind_id                           lower_ind_id
Parameters:
  • tn_super (TensorNetwork) – The superoperator in the form of a 1D-like tensor network.

  • tn_op (TensorNetwork) – The operator to be acted on in the form of a 1D-like tensor network.

  • upper_ind_id (str, optional) – Current id of the upper operator indices, e.g. usually 'k{}'.

  • lower_ind_id (str, optional) – Current id of the lower operator indices, e.g. usually 'b{}'.

  • so_outer_upper_ind_id (str, optional) – Current id of the superoperator’s upper outer indices, these will be reindexed to form the new effective operators upper indices.

  • so_inner_upper_ind_id (str, optional) – Current id of the superoperator’s upper inner indices, these will be joined with those described by upper_ind_id.

  • so_inner_lower_ind_id (str, optional) – Current id of the superoperator’s lower inner indices, these will be joined with those described by lower_ind_id.

  • so_outer_lower_ind_id (str, optional) – Current id of the superoperator’s lower outer indices, these will be reindexed to form the new effective operators lower indices.

Returns:

KAK – The tensornetwork of the superoperator acting on the operator.

Return type:

TensorNetwork

quimb.tensor.tensor_1d.parse_cur_orthog(cur_orthog='calc', info=None)[source]
quimb.tensor.tensor_1d.convert_cur_orthog(fn)[source]
class quimb.tensor.tensor_1d.TensorNetwork1D(ts=(), *, virtual=False, check_collisions=True)[source]

Bases: quimb.tensor.tensor_arbgeom.TensorNetworkGen

Base class for tensor networks with a one-dimensional structure.

_NDIMS = 1
_EXTRA_PROPS = ('_site_tag_id', '_L')
_CONTRACT_STRUCTURED = True
_compatible_1d(other)[source]

Check whether self and other are compatible 2D tensor networks such that they can remain a 2D tensor network when combined.

combine(other, *, virtual=False, check_collisions=True)[source]

Combine this tensor network with another, returning a new tensor network. If the two are compatible, cast the resulting tensor network to a TensorNetwork1D instance.

Parameters:
  • other (TensorNetwork1D or TensorNetwork) – The other tensor network to combine with.

  • virtual (bool, optional) – Whether the new tensor network should copy all the incoming tensors (False, the default), or view them as virtual (True).

  • check_collisions (bool, optional) – Whether to check for index collisions between the two tensor networks before combining them. If True (the default), any inner indices that clash will be mangled.

Return type:

TensorNetwork1D or TensorNetwork

property L
The number of sites, i.e. length.
property nsites
The number of sites.
gen_site_coos()[source]

Generate the coordinates of all possible sites.

site_tag(i)[source]

The name of the tag specifiying the tensor at site i.

slice2sites(tag_slice)[source]

Take a slice object, and work out its implied start, stop and step, taking into account cyclic boundary conditions.

Examples

Normal slicing:

>>> p = MPS_rand_state(10, bond_dim=7)
>>> p.slice2sites(slice(5))
(0, 1, 2, 3, 4)
>>> p.slice2sites(slice(4, 8))
(4, 5, 6, 7)

Slicing from end backwards:

>>> p.slice2sites(slice(..., -3, -1))
(9, 8)

Slicing round the end:

>>> p.slice2sites(slice(7, 12))
(7, 8, 9, 0, 1)
>>> p.slice2sites(slice(-3, 2))
(7, 8, 9, 0, 1)

If the start point is > end point (before modulo n), then step needs to be negative to return anything.

maybe_convert_coo(x)[source]

Check if x is an integer and convert to the corresponding site tag if so.

contract_structured(tag_slice, structure_bsz=5, inplace=False, **opts)[source]

Perform a structured contraction, translating tag_slice from a slice or to a cumulative sequence of tags.

Parameters:
  • tag_slice (slice or ...) – The range of sites, or for all.

  • inplace (bool, optional) – Whether to perform the contraction inplace.

Returns:

The result of the contraction, still a TensorNetwork if the contraction was only partial.

Return type:

TensorNetwork, Tensor or scalar

See also

contract, contract_tags, contract_cumulative

_repr_info()[source]

General info to show in various reprs. Sublasses can add more relevant info to this dict.

class quimb.tensor.tensor_1d.TensorNetwork1DVector(ts=(), *, virtual=False, check_collisions=True)[source]

Bases: TensorNetwork1D, quimb.tensor.tensor_arbgeom.TensorNetworkGenVector

1D Tensor network which overall is like a vector with a single type of site ind.

_EXTRA_PROPS = ('_site_tag_id', '_site_ind_id', '_L')
reindex_sites(new_id, where=None, inplace=False)[source]

Update the physical site index labels to a new string specifier. Note that this doesn’t change the stored id string with the TN.

Parameters:
  • new_id (str) – A string with a format placeholder to accept an int, e.g. “ket{}”.

  • where (None or slice) – Which sites to update the index labels on. If None (default) all sites.

  • inplace (bool) – Whether to reindex in place.

reindex_sites_[source]
site_ind(i)[source]

Get the physical index name of site i.

gate(*args, inplace=False, **kwargs)[source]

Apply a gate to this vector tensor network at sites where. This is essentially a wrapper around gate_inds() apart from where can be specified as a list of sites, and tags can be optionally, intelligently propagated to the new gate tensor.

\[| \psi \rangle \rightarrow G_\mathrm{where} | \psi \rangle\]
Parameters:
  • G (array_ike) – The gate array to apply, should match or be factorable into the shape (*phys_dims, *phys_dims).

  • where (node or sequence[node]) – The sites to apply the gate to.

  • contract ({False, True, 'split', 'reduce-split', 'split-gate',) – ‘swap-split-gate’, ‘auto-split-gate’}, optional How to apply the gate, see gate_inds().

  • tags (str or sequence of str, optional) – Tags to add to the new gate tensor.

  • propagate_tags ({False, True, 'register', 'sites'}, optional) –

    Whether to propagate tags to the new gate tensor:

    - False: no tags are propagated
    - True: all tags are propagated
    - 'register': only site tags corresponding to ``where`` are
      added.
    - 'sites': all site tags on the current sites are propgated,
      resulting in a lightcone like tagging.
    

  • info (None or dict, optional) – Used to store extra optional information such as the singular values if not absorbed.

  • inplace (bool, optional) – Whether to perform the gate operation inplace on the tensor network or not.

  • compress_opts – Supplied to tensor_split() for any contract methods that involve splitting. Ignored otherwise.

Return type:

TensorNetworkGenVector

See also

TensorNetwork.gate_inds

gate_[source]
expec(*args, **kwargs)[source]
correlation(A, i, j, B=None, **expec_opts)[source]

Correlation of operator A between i and j.

Parameters:
  • A (array) – The operator to act with, can be multi site.

  • i (int or sequence of int) – The first site(s).

  • j (int or sequence of int) – The second site(s).

  • expec_opts – Supplied to expec_TN_1D().

Returns:

C – The correlation <A(i)> + <A(j)> - <A(ij)>.

Return type:

float

Examples

>>> ghz = (MPS_computational_state('0000') +
...        MPS_computational_state('1111')) / 2**0.5
>>> ghz.correlation(pauli('Z'), 0, 1)
1.0
>>> ghz.correlation(pauli('Z'), 0, 1, B=pauli('X'))
0.0
class quimb.tensor.tensor_1d.TensorNetwork1DOperator(ts=(), *, virtual=False, check_collisions=True)[source]

Bases: TensorNetwork1D, quimb.tensor.tensor_arbgeom.TensorNetworkGenOperator

Base class for tensor networks with a one-dimensional structure.

_EXTRA_PROPS = ('_site_tag_id', '_upper_ind_id', '_lower_ind_id', '_L')
reindex_lower_sites(new_id, where=None, inplace=False)[source]

Update the lower site index labels to a new string specifier.

Parameters:
  • new_id (str) – A string with a format placeholder to accept an int, e.g. "ket{}".

  • where (None or slice) – Which sites to update the index labels on. If None (default) all sites.

  • inplace (bool) – Whether to reindex in place.

reindex_lower_sites_[source]
reindex_upper_sites(new_id, where=None, inplace=False)[source]

Update the upper site index labels to a new string specifier.

Parameters:
  • new_id (str) – A string with a format placeholder to accept an int, e.g. “ket{}”.

  • where (None or slice) – Which sites to update the index labels on. If None (default) all sites.

  • inplace (bool) – Whether to reindex in place.

reindex_upper_sites_[source]
quimb.tensor.tensor_1d.set_default_compress_mode(opts, cyclic=False)[source]
class quimb.tensor.tensor_1d.TensorNetwork1DFlat(ts=(), *, virtual=False, check_collisions=True)[source]

Bases: TensorNetwork1D

1D Tensor network which has a flat structure.

_EXTRA_PROPS = ('_site_tag_id', '_L')
left_canonize_site(i, bra=None)[source]

Left canonize this TN’s ith site, inplace:

    i                i
   -o-o-            ->-s-
... | | ...  ==> ... | | ...
Parameters:
  • i (int) – Which site to canonize. The site at i + 1 also absorbs the non-isometric part of the decomposition of site i.

  • bra (None or matching TensorNetwork to self, optional) – If set, also update this TN’s data with the conjugate canonization.

right_canonize_site(i, bra=None)[source]

Right canonize this TN’s ith site, inplace:

      i                i
   -o-o-            -s-<-
... | | ...  ==> ... | | ...
Parameters:

i (int) –

Which site to canonize. The site at i - 1 also absorbs the

non-isometric part of the decomposition of site i.

braNone or matching TensorNetwork to self, optional

If set, also update this TN’s data with the conjugate canonization.

left_canonicalize(stop=None, start=None, normalize=False, bra=None, inplace=False)[source]

Left canonicalize all or a portion of this TN (i.e. sweep the orthogonality center to the right). If this is a MPS, this implies that:

              i              i
>->->->->->->-o-o-         +-o-o-
| | | | | | | | | ...  =>  | | | ...
>->->->->->->-o-o-         +-o-o-
Parameters:
  • start (int, optional) – If given, the site to start left canonicalizing at.

  • stop (int, optional) – If given, the site to stop left canonicalizing at.

  • normalize (bool, optional) – Whether to normalize the state, only works for OBC.

  • bra (MatrixProductState, optional) – If supplied, simultaneously left canonicalize this MPS too, assuming it to be the conjugate state.

  • inplace (bool, optional) – Whether to perform the operation inplace. If bra is supplied then it is always modifed inplace.

Return type:

TensorNetwork1DFlat

left_canonicalize_[source]
left_canonize[source]
right_canonicalize(stop=None, start=None, normalize=False, bra=None, inplace=False)[source]

Right canonicalize all or a portion of this TN (i.e. sweep the orthogonality center to the left). If this is a MPS,

i i

-o-o-<-<-<-<-<-<-< -o-o-+

… | | | | | | | | | -> … | | |

-o-o-<-<-<-<-<-<-< -o-o-+

Parameters:
  • start (int, optional) – If given, the site to start right canonizing at.

  • stop (int, optional) – If given, the site to stop right canonizing at.

  • normalize (bool, optional) – Whether to normalize the state.

  • bra (MatrixProductState, optional) – If supplied, simultaneously right canonicalize this MPS too, assuming it to be the conjugate state.

  • inplace (bool, optional) – Whether to perform the operation inplace. If bra is supplied then it is always modifed inplace.

Return type:

TensorNetwork1DFlat

right_canonicalize_[source]
right_canonize[source]
canonize_cyclic(i, bra=None, method='isvd', inv_tol=1e-10)[source]

Bring this MatrixProductState into (possibly only approximate) canonical form at site(s) i.

Parameters:
  • i (int or slice) – The site or range of sites to make canonical.

  • bra (MatrixProductState, optional) – Simultaneously canonize this state as well, assuming it to be the co-vector.

  • method ({'isvd', 'svds', ...}, optional) – How to perform the lateral compression.

  • inv_tol (float, optional) – Tolerance with which to invert the gauge.

shift_orthogonality_center(current, new, bra=None)[source]

Move the orthogonality center of this MPS.

Parameters:
  • current (int) – The current orthogonality center.

  • new (int) – The target orthogonality center.

  • bra (MatrixProductState, optional) – If supplied, simultaneously move the orthogonality center of this MPS too, assuming it to be the conjugate state.

canonicalize(where, cur_orthog='calc', info=None, bra=None, inplace=False)[source]

Gauge this MPS into mixed canonical form, implying:

              i                      i
>->->->->- ->-o-<- -<-<-<-<-<      +-o-+
| | | | |...| | |...| | | | |  ->  | | |
>->->->->- ->-o-<- -<-<-<-<-<      +-o-+

You can also supply a min/max of sites to orthogonalize around, and a current location of the orthogonality center for efficiency:

      current                              where
      .......                              .....
>->->-c-c-c-c-<-<-<-<-<-<      >->->->->->-w-<-<-<-<-<-<
| | | | | | | | | | | | |  ->  | | | | | | | | | | | | |
>->->-c-c-c-c-<-<-<-<-<-<      >->->->->->-w-<-<-<-<-<-<
   cmin     cmax                           i   j

This would only move cmin to i and cmax to j if necessary.

Parameters:
  • where (int or sequence of int) – Which site(s) to orthogonalize around. If a sequence of int then make sure that section from min(where) to max(where) is orthog.

  • info (dict, optional) – If supplied, will be used to infer and store various extra information. Currently, the key “cur_orthog” is used to store the current orthogonality center. Its input value can be "calc", a single site, or a pair of sites representing the min/max range, inclusive. It will be updated to the actual range after.

  • bra (MatrixProductState, optional) – If supplied, simultaneously mixed canonicalize this MPS too, assuming it to be the conjugate state.

  • inplace (bool, optional) – Whether to perform the operation inplace. If bra is supplied then it is always modifed inplace.

Returns:

The mixed canonical form MPS.

Return type:

MatrixProductState

canonicalize_[source]
canonize[source]
left_compress_site(i, bra=None, **compress_opts)[source]

Left compress this 1D TN’s ith site, such that the site is then left unitary with its right bond (possibly) reduced in dimension.

Parameters:
  • i (int) – Which site to compress.

  • bra (None or matching TensorNetwork to self, optional) – If set, also update this TN’s data with the conjugate compression.

  • compress_opts – Supplied to Tensor.split().

right_compress_site(i, bra=None, **compress_opts)[source]

Right compress this 1D TN’s ith site, such that the site is then right unitary with its left bond (possibly) reduced in dimension.

Parameters:
  • i (int) – Which site to compress.

  • bra (None or matching TensorNetwork to self, optional) – If set, update this TN’s data with the conjugate compression.

  • compress_opts – Supplied to Tensor.split().

left_compress(start=None, stop=None, bra=None, **compress_opts)[source]

Compress this 1D TN, from left to right, such that it becomes left-canonical (unless absorb != 'right').

Parameters:
  • start (int, optional) – Site to begin compressing on.

  • stop (int, optional) – Site to stop compressing at (won’t itself be an isometry).

  • bra (None or TensorNetwork like this one, optional) – If given, update this TN as well, assuming it to be the conjugate.

  • compress_opts – Supplied to Tensor.split().

right_compress(start=None, stop=None, bra=None, **compress_opts)[source]

Compress this 1D TN, from right to left, such that it becomes right-canonical (unless absorb != 'left').

Parameters:
  • start (int, optional) – Site to begin compressing on.

  • stop (int, optional) – Site to stop compressing at (won’t itself be an isometry).

  • bra (None or TensorNetwork like this one, optional) – If given, update this TN as well, assuming it to be the conjugate.

  • compress_opts – Supplied to Tensor.split().

compress(form=None, **compress_opts)[source]

Compress this 1D Tensor Network, possibly into canonical form.

Parameters:
  • form ({None, 'flat', 'left', 'right'} or int) – Output form of the TN. None left canonizes the state first for stability reasons, then right_compresses (default). 'flat' tries to distribute the singular values evenly – state will not be canonical. 'left' and 'right' put the state into left and right canonical form respectively with a prior opposite sweep, or an int will put the state into mixed canonical form at that site.

  • compress_opts – Supplied to Tensor.split().

compress_site(i, canonize=True, info=None, bra=None, **compress_opts)[source]

Compress the bonds adjacent to site i, by default first setting the orthogonality center to that site:

     i                     i
-o-o-o-o-o-    -->    ->->~o~<-<-
 | | | | |             | | | | |
Parameters:
  • i (int) – Which site to compress around

  • canonize (bool, optional) – Whether to first set the orthogonality center to site i.

  • info (dict, optional) – If supplied, will be used to infer and store various extra information. Currently, the key “cur_orthog” is used to store the current orthogonality center. Its input value can be "calc", a single site, or a pair of sites representing the min/max range, inclusive. It will be updated to the actual range after.

  • bra (MatrixProductState, optional) – The conjugate state to also apply the compression to.

  • compress_opts – Supplied to tensor_split().

bond(i, j)[source]

Get the name of the index defining the bond between sites i and j.

bond_size(i, j)[source]

Return the size of the bond between site i and j.

bond_sizes()[source]
amplitude(b)[source]

Compute the amplitude of configuration b.

Parameters:

b (sequence of int) – The configuration to compute the amplitude of.

Returns:

c_b

Return type:

scalar

singular_values(i, info=None, method='svd')[source]

Find the singular values associated with the ith bond:

....L....   i
o-o-o-o-o-l-o-o-o-o-o-o-o-o-o-o-o
| | | | |   | | | | | | | | | | |
       i-1  ..........R..........

Leaves the 1D TN in mixed canoncial form at bond i.

Parameters:
  • i (int) – Which bond, or equivalently, the number of sites in the left partition.

  • info (dict, optional) – If supplied, will be used to infer and store various extra information. Currently, the key “cur_orthog” is used to store the current orthogonality center. Its input value can be "calc", a single site, or a pair of sites representing the min/max range, inclusive. It will be updated to the actual range after.

Returns:

svals – The singular values.

Return type:

1d-array

expand_bond_dimension(new_bond_dim, rand_strength=0.0, bra=None, inplace=True)[source]

Expand the bond dimensions of this 1D tensor network to at least new_bond_dim.

Parameters:
  • new_bond_dim (int) – Minimum bond dimension to expand to.

  • inplace (bool, optional) – Whether to perform the expansion in place.

  • bra (MatrixProductState, optional) – Mirror the changes to bra inplace, treating it as the conjugate state.

  • rand_strength (float, optional) – If rand_strength > 0, fill the new tensor entries with gaussian noise of strength rand_strength.

Return type:

MatrixProductState

count_canonized()[source]
calc_current_orthog_center()[source]

Calculate the site(s) of the current orthogonality center.

Returns:

The min/max of sites around which the TN is currently orthogonal.

Return type:

(int, int)

as_cyclic(inplace=False)[source]

Convert this flat, 1D, TN into cyclic form by adding a dummy bond between the first and last sites.

show(max_width=None)[source]
class quimb.tensor.tensor_1d.MatrixProductState(arrays, *, sites=None, L=None, shape='lrp', tags=None, site_ind_id='k{}', site_tag_id='I{}', **tn_opts)[source]

Bases: TensorNetwork1DVector, TensorNetwork1DFlat

Initialise a matrix product state, with auto labelling and tagging.

Parameters:
  • arrays (sequence of arrays) – The tensor arrays to form into a MPS.

  • sites (sequence of int, optional) – Construct the MPO on these sites only. If not given, enumerate from zero. Should be monotonically increasing and match arrays.

  • L (int, optional) – The number of sites the MPO should be defined on. If not given, this is taken as the max sites value plus one (i.e.g the number of arrays if sites is not given).

  • shape (str, optional) – String specifying layout of the tensors. E.g. ‘lrp’ (the default) indicates the shape corresponds left-bond, right-bond, physical index. End tensors have either ‘l’ or ‘r’ dropped from the string.

  • tags (str or sequence of str, optional) – Global tags to attach to all tensors.

  • site_ind_id (str) – A string specifiying how to label the physical site indices. Should contain a '{}' placeholder. It is used to generate the actual indices like: map(site_ind_id.format, range(len(arrays))).

  • site_tag_id (str) – A string specifiying how to tag the tensors at each site. Should contain a '{}' placeholder. It is used to generate the actual tags like: map(site_tag_id.format, range(len(arrays))).

_EXTRA_PROPS = ('_site_tag_id', '_site_ind_id', 'cyclic', '_L')
classmethod from_fill_fn(fill_fn, L, bond_dim, phys_dim=2, sites=None, cyclic=False, shape='lrp', site_ind_id='k{}', site_tag_id='I{}', tags=None)[source]

Create an MPS by supplying a ‘filling’ function to generate the data for each site.

Parameters:
  • fill_fn (callable) – A function with signature fill_fn(shape : tuple[int]) -> array_like.

  • L (int) – The number of sites.

  • bond_dim (int) – The bond dimension.

  • phys_dim (int or Sequence[int], optional) – The physical dimension(s) of each site, if a sequence it will be cycled over.

  • sites (None or sequence of int, optional) – Construct the MPS on these sites only. If not given, enumerate from zero.

  • cyclic (bool, optional) – Whether the MPS should be cyclic (periodic).

  • shape (str, optional) – What specific order to layout the indices in, should be a sequence of 'l', 'r', and 'p', corresponding to left, right, and physical indices respectively.

  • site_ind_id (str, optional) – How to label the physical site indices.

  • site_tag_id (str, optional) – How to tag the physical sites.

  • tags (str or sequence of str, optional) – Global tags to attach to all tensors.

Return type:

MatrixProductState

classmethod from_dense(psi, dims=2, tags=None, site_ind_id='k{}', site_tag_id='I{}', **split_opts)[source]

Create a MatrixProductState directly from a dense vector

Parameters:
  • psi (array_like) – The dense state to convert to MPS from.

  • dims (int or sequence of int) – Physical subsystem dimensions of each site. If a single int, all sites have this same dimension, by default, 2.

  • tags (str or sequence of str, optional) – Global tags to attach to all tensors.

  • site_ind_id (str, optional) – How to index the physical sites, see MatrixProductState.

  • site_tag_id (str, optional) – How to tag the physical sites, see MatrixProductState.

  • split_opts – Supplied to tensor_split() to in order to partition the dense vector into tensors. absorb='left' is set by default, to ensure the compression is canonical / optimal.

Return type:

MatrixProductState

Examples

>>> dims = [2, 2, 2, 2, 2, 2]
>>> psi = rand_ket(prod(dims))
>>> mps = MatrixProductState.from_dense(psi, dims)
>>> mps.show()
 2 4 8 4 2
o-o-o-o-o-o
| | | | | |
add_MPS(other, inplace=False, **kwargs)[source]

Add another MatrixProductState to this one.

add_MPS_[source]
permute_arrays(shape='lrp')[source]

Permute the indices of each tensor in this MPS to match shape. This doesn’t change how the overall object interacts with other tensor networks but may be useful for extracting the underlying arrays consistently. This is an inplace operation.

Parameters:

shape (str, optional) – A permutation of 'lrp' specifying the desired order of the left, right, and physical indices respectively.

normalize(bra=None, eps=1e-15, insert=None)[source]

Normalize this MPS, optional with co-vector bra. For periodic MPS this uses transfer matrix SVD approximation with precision eps in order to be efficient. Inplace.

Parameters:
  • bra (MatrixProductState, optional) – If given, normalize this MPS with the same factor.

  • eps (float, optional) – If cyclic, precision to approximation transfer matrix with. Default: 1e-14.

  • insert (int, optional) – Insert the corrective normalization on this site, random if not given.

Returns:

old_norm – The old norm self.H @ self.

Return type:

float

gate_split(G, where, inplace=False, **compress_opts)[source]

Apply a two-site gate and then split resulting tensor to retrieve a MPS form:

-o-o-A-B-o-o-
 | | | | | |            -o-o-GGG-o-o-           -o-o-X~Y-o-o-
 | | GGG | |     ==>     | | | | | |     ==>     | | | | | |
 | | | | | |                 i j                     i j
     i j

As might be found in TEBD.

Parameters:
  • G (array) – The gate, with shape (d**2, d**2) for physical dimension d.

  • where ((int, int)) – Indices of the sites to apply the gate to.

  • compress_opts – Supplied to tensor_split().

See also

gate, gate_with_auto_swap

gate_split_[source]
swap_sites_with_compress(i, j, info=None, inplace=False, **compress_opts)[source]

Swap sites i and j by contracting, then splitting with the physical indices swapped. If the sites are not adjacent, this will happen multiple times.

Parameters:
  • i (int) – The first site to swap.

  • j (int) – The second site to swap.

  • cur_orthog (int, sequence of int, or 'calc') – If known, the current orthogonality center.

  • info (dict, optional) – If supplied, will be used to infer and store various extra information. Currently, the key “cur_orthog” is used to store the current orthogonality center. Its input value can be "calc", a single site, or a pair of sites representing the min/max range, inclusive. It will be updated to the actual range after.

  • inplace (bond, optional) – Perform the swaps inplace.

  • compress_opts – Supplied to tensor_split().

swap_sites_with_compress_[source]
swap_site_to(i, f, info=None, inplace=False, **compress_opts)[source]

Swap site i to site f, compressing the bond after each swap:

      i       f
0 1 2 3 4 5 6 7 8 9      0 1 2 4 5 6 7 3 8 9
o-o-o-x-o-o-o-o-o-o      >->->->->->->-x-<-<
| | | | | | | | | |  ->  | | | | | | | | | |
Parameters:
  • i (int) – The site to move.

  • f (int) – The new location for site i.

  • info (dict, optional) – If supplied, will be used to infer and store various extra information. Currently, the key “cur_orthog” is used to store the current orthogonality center. Its input value can be "calc", a single site, or a pair of sites representing the min/max range, inclusive. It will be updated to the actual range after.

  • inplace (bond, optional) – Perform the swaps inplace.

  • compress_opts – Supplied to tensor_split().

swap_site_to_[source]
gate_with_auto_swap(G, where, info=None, swap_back=True, inplace=False, **compress_opts)[source]

Perform a two site gate on this MPS by, if necessary, swapping and compressing the sites until they are adjacent, using gate_split, then unswapping the sites back to their original position.

Parameters:
  • G (array) – The gate, with shape (d**2, d**2) for physical dimension d.

  • where ((int, int)) – Indices of the sites to apply the gate to.

  • info (dict, optional) – If supplied, will be used to infer and store various extra information. Currently, the key “cur_orthog” is used to store the current orthogonality center. Its input value can be "calc", a single site, or a pair of sites representing the min/max range, inclusive. It will be updated to the actual range after.

  • swap_back (bool, optional) – Whether to swap the sites back to their original position after applying the gate. If not, for sites i < j, the site j will remain swapped to i + 1, and sites between i + 1 and j will be shifted one place up.

  • inplace (bond, optional) – Perform the swaps inplace.

  • compress_opts – Supplied to tensor_split().

See also

gate, gate_split

gate_with_auto_swap_[source]
gate_with_submpo(submpo, where=None, method='direct', transpose=False, info=None, inplace=False, inplace_mpo=False, **compress_opts)[source]

Apply an MPO, which only acts on a subset of sites, to this MPS, compressing the MPS with the MPO only on the minimal set of sites covering where, keeping the MPS form:

    │   │ │
    A───A─A
    │   │ │         ->    │ │ │ │ │ │ │ │
                          >─>─O━O━O━O─<─<
│ │ │ │ │ │ │ │
o─o─o─o─o─o─o─o
Parameters:
  • submpo (MatrixProductOperator) – The MPO to apply.

  • where (sequence of int, optional) – The range of sites the MPO acts on, will be inferred from the support of the MPO if not given.

  • method ({'direct", 'dm', 'zipup', 'zipup-first', 'fit'}, optional) – The compression method to use.

  • transpose (bool, optional) – Whether to transpose the MPO before applying it. By default the lower inds of the MPO are contracted with the MPS, if transposed the upper inds are contracted.

  • info (dict, optional) – If supplied, will be used to infer and store various extra information. Currently, the key “cur_orthog” is used to store the current orthogonality center. Its input value can be "calc", a single site, or a pair of sites representing the min/max range, inclusive. It will be updated to the actual range after.

  • inplace (bool, optional) – Whether to perform the application and compression inplace.

  • compress_opts – Supplied to tensor_network_1d_compress().

Return type:

MatrixProductState

gate_with_submpo_[source]
gate_with_mpo(mpo, method='direct', transpose=False, inplace=False, inplace_mpo=False, **compress_opts)[source]

Gate this MPS with an MPO and compress the result with one of various methods back to MPS form:

│ │ │ │ │ │ │ │
A─A─A─A─A─A─A─A
│ │ │ │ │ │ │ │     ->    │ │ │ │ │ │ │ │
                          O━O━O━O━O━O━O━O
│ │ │ │ │ │ │ │
o─o─o─o─o─o─o─o
Parameters:
  • mpo (MatrixProductOperator) – The MPO to apply.

  • max_bond (int, optional) – A maximum bond dimension to keep when compressing.

  • cutoff (float, optional) – A singular value cutoff to use when compressing.

  • method ({'direct", 'dm', 'zipup', 'zipup-first', 'fit', ...}, optional) – The compression method to use.

  • transpose (bool, optional) – Whether to transpose the MPO before applying it. By default the lower inds of the MPO are contracted with the MPS, if transposed the upper inds are contracted.

  • inplace (bool, optional) – Whether to perform the compression inplace.

  • inplace_mpo (bool, optional) – Whether the modify the MPO in place, a minor performance gain.

  • compress_opts – Other options supplied to tensor_network_1d_compress().

Return type:

MatrixProductState

gate_with_mpo_[source]
gate_nonlocal(G, where, dims=None, method='direct', info=None, inplace=False, **compress_opts)[source]

Apply a potentially non-local gate to this MPS by first decomposing it into an MPO, then compressing the MPS with MPO only on the minimal set of sites covering where.

Parameters:
  • G (array_like) – The gate to apply.

  • where (sequence of int) – The sites to apply the gate to.

  • max_bond (int, optional) – A maximum bond dimension to keep when compressing.

  • cutoff (float, optional) – A singular value cutoff to use when compressing.

  • dims (sequence of int, optional) – The factorized dimensions of the gate G, which should match the physical dimensions of the sites it acts on. Calculated if not supplied. If a single int, all sites are assumed to have this same dimension.

  • method ({'direct", 'dm', 'zipup', 'zipup-first', 'fit', ...}, optional) – The compression method to use.

  • info (dict, optional) – If supplied, will be used to infer and store various extra information. Currently, the key “cur_orthog” is used to store the current orthogonality center. Its input value can be "calc", a single site, or a pair of sites representing the min/max range, inclusive. It will be updated to the actual range after.

  • inplace (bool, optional) – Whether to perform the compression inplace.

  • compress_opts – Supplied to tensor_network_1d_compress().

Return type:

MatrixProductState

gate_nonlocal_[source]
flip(inplace=False)[source]

Reverse the order of the sites in the MPS, such that site i is now at site L - i - 1.

magnetization(i, direction='Z', info=None)[source]

Compute the magnetization at site i.

schmidt_values(i, info=None, method='svd')[source]

Find the schmidt values associated with the bipartition of this MPS between sites on either site of i. In other words, i is the number of sites in the left hand partition:

....L....   i
o-o-o-o-o-S-o-o-o-o-o-o-o-o-o-o-o
| | | | |   | | | | | | | | | | |
       i-1  ..........R..........

The schmidt values, S, are the singular values associated with the (i - 1, i) bond, squared, provided the MPS is mixed canonized at one of those sites.

Parameters:
  • i (int) – The number of sites in the left partition.

  • info (dict, optional) – If given, will be used to infer and store various extra information. Currently the key “cur_orthog” is used to store the current orthogonality center.

Returns:

S – The schmidt values.

Return type:

1d-array

entropy(i, info=None, method='svd')[source]

The entropy of bipartition between the left block of i sites and the rest.

Parameters:
  • i (int) – The number of sites in the left partition.

  • info (dict, optional) – If given, will be used to infer and store various extra information. Currently the key “cur_orthog” is used to store the current orthogonality center.

Return type:

float

schmidt_gap(i, info=None, method='svd')[source]

The schmidt gap of bipartition between the left block of i sites and the rest.

Parameters:
  • i (int) – The number of sites in the left partition.

  • info (dict, optional) – If given, will be used to infer and store various extra information. Currently the key “cur_orthog” is used to store the current orthogonality center.

Return type:

float

partial_trace(keep, upper_ind_id='b{}', rescale_sites=True)[source]

Partially trace this matrix product state, producing a matrix product operator.

Parameters:
  • keep (sequence of int or slice) – Indicies of the sites to keep.

  • upper_ind_id (str, optional) – The ind id of the (new) ‘upper’ inds, i.e. the ‘bra’ inds.

  • rescale_sites (bool, optional) – If True (the default), then the kept sites will be rescaled to (0, 1, 2, ...) etc. rather than keeping their original site numbers.

Returns:

rho – The density operator in MPO form.

Return type:

MatrixProductOperator

ptr(keep, upper_ind_id='b{}', rescale_sites=True)[source]

Alias of partial_trace().

bipartite_schmidt_state(sz_a, get='ket', info=None)[source]

Compute the reduced state for a bipartition of an OBC MPS, in terms of the minimal left/right schmidt basis:

     A            B
 .........     ...........
 >->->->->--s--<-<-<-<-<-<    ->   +-s-+
 | | | | |     | | | | | |         |   |
k0 k1...                          kA   kB
Parameters:
  • sz_a (int) – The number of sites in subsystem A, must be 0 < sz_a < N.

  • get ({'ket', 'rho', 'ket-dense', 'rho-dense'}, optional) –

    Get the:

    • ’ket’: vector form as tensor.

    • ’rho’: density operator form, i.e. vector outer product

    • ’ket-dense’: like ‘ket’ but return qarray.

    • ’rho-dense’: like ‘rho’ but return qarray.

  • info (dict, optional) – If given, will be used to infer and store various extra information. Currently the key “cur_orthog” is used to store the current orthogonality center.

static _do_lateral_compress(mps, kb, section, leave_short, ul, ll, heps, hmethod, hmax_bond, verbosity, compressed, **compress_opts)[source]
static _do_vertical_decomp(mps, kb, section, sysa, sysb, compressed, ul, ur, ll, lr, vmethod, vmax_bond, veps, verbosity, **compress_opts)[source]
partial_trace_compress(sysa, sysb, eps=1e-08, method=('isvd', None), max_bond=(None, 1024), leave_short=True, renorm=True, lower_ind_id='b{}', verbosity=0, **compress_opts)[source]

Perform a compressed partial trace using singular value lateral then vertical decompositions of transfer matrix products:

        .....sysa......     ...sysb....
o-o-o-o-A-A-A-A-A-A-A-A-o-o-B-B-B-B-B-B-o-o-o-o-o-o-o-o-o
| | | | | | | | | | | | | | | | | | | | | | | | | | | | |

                          ==> form inner product

        ...............     ...........
o-o-o-o-A-A-A-A-A-A-A-A-o-o-B-B-B-B-B-B-o-o-o-o-o-o-o-o-o
| | | | | | | | | | | | | | | | | | | | | | | | | | | | |
o-o-o-o-A-A-A-A-A-A-A-A-o-o-B-B-B-B-B-B-o-o-o-o-o-o-o-o-o

                          ==> lateral SVD on each section

          .....sysa......     ...sysb....
          /\             /\   /\         /\
  ... ~~~E  A~~~~~~~~~~~A  E~E  B~~~~~~~B  E~~~ ...
          \/             \/   \/         \/

                          ==> vertical SVD and unfold on A & B

                  |                 |
          /-------A-------\   /-----B-----\
  ... ~~~E                 E~E             E~~~ ...
          \-------A-------/   \-----B-----/
                  |                 |

With various special cases including OBC or end spins included in subsytems.

Parameters:
  • sysa (sequence of int) – The sites, which should be contiguous, defining subsystem A.

  • sysb (sequence of int) – The sites, which should be contiguous, defining subsystem B.

  • eps (float or (float, float), optional) – Tolerance(s) to use when compressing the subsystem transfer matrices and vertically decomposing.

  • method (str or (str, str), optional) – Method(s) to use for laterally compressing the state then vertially compressing subsytems.

  • max_bond (int or (int, int), optional) – The maximum bond to keep for laterally compressing the state then vertially compressing subsytems.

  • leave_short (bool, optional) – If True (the default), don’t try to compress short sections.

  • renorm (bool, optional) – If True (the default), renomalize the state so that tr(rho)==1.

  • lower_ind_id (str, optional) – The index id to create for the new density matrix, the upper_ind_id is automatically taken as the current site_ind_id.

  • compress_opts (dict, optional) – If given, supplied to partial_trace_compress to govern how singular values are treated. See tensor_split.

  • verbosity ({0, 1}, optional) – How much information to print while performing the compressed partial trace.

Returns:

rho_ab – Density matrix tensor network with outer_inds = ('k0', 'k1', 'b0', 'b1') for example.

Return type:

TensorNetwork

logneg_subsys(sysa, sysb, compress_opts=None, approx_spectral_opts=None, verbosity=0, approx_thresh=2**12)[source]

Compute the logarithmic negativity between subsytem blocks, e.g.:

                   sysa         sysb
                 .........       .....
... -o-o-o-o-o-o-A-A-A-A-A-o-o-o-B-B-B-o-o-o-o-o-o-o- ...
     | | | | | | | | | | | | | | | | | | | | | | | |
Parameters:
  • sysa (sequence of int) – The sites, which should be contiguous, defining subsystem A.

  • sysb (sequence of int) – The sites, which should be contiguous, defining subsystem B.

  • eps (float, optional) – Tolerance to use when compressing the subsystem transfer matrices.

  • method (str or (str, str), optional) – Method(s) to use for laterally compressing the state then vertially compressing subsytems.

  • compress_opts (dict, optional) – If given, supplied to partial_trace_compress to govern how singular values are treated. See tensor_split.

  • approx_spectral_opts – Supplied to approx_spectral_function().

Returns:

ln – The logarithmic negativity.

Return type:

float

See also

MatrixProductState.partial_trace_compress, approx_spectral_function

measure(site, remove=False, outcome=None, renorm=True, info=None, get=None, inplace=False)[source]

Measure this MPS at site, including projecting the state. Optionally remove the site afterwards, yielding an MPS with one less site. In either case the orthogonality center of the returned MPS is min(site, new_L - 1).

Parameters:
  • site (int) – The site to measure.

  • remove (bool, optional) –

    Whether to remove the site completely after projecting the measurement. If True, sites greater than site will be retagged and reindex one down, and the MPS will have one less site. E.g:

    0-1-2-3-4-5-6
           / / /  - measure and remove site 3
    0-1-2-4-5-6
                  - reindex sites (4, 5, 6) to (3, 4, 5)
    0-1-2-3-4-5
    

  • outcome (None or int, optional) – Specify the desired outcome of the measurement. If None, it will be randomly sampled according to the local density matrix.

  • renorm (bool, optional) – Whether to renormalize the state post measurement.

  • info (dict, optional) – If given, will be used to infer and store various extra information. Currently the key “cur_orthog” is used to store the current orthogonality center.

  • get ({None, 'outcome'}, optional) – If 'outcome', simply return the outcome, and don’t perform any projection.

  • inplace (bool, optional) – Whether to perform the measurement in place or not.

Returns:

  • outcome (int) – The measurement outcome, drawn from range(phys_dim).

  • psi (MatrixProductState) – The measured state, if get != 'outcome'.

measure_[source]
class quimb.tensor.tensor_1d.MatrixProductOperator(arrays, *, sites=None, L=None, shape='lrud', tags=None, upper_ind_id='k{}', lower_ind_id='b{}', site_tag_id='I{}', **tn_opts)[source]

Bases: TensorNetwork1DOperator, TensorNetwork1DFlat

Initialise a matrix product operator, with auto labelling and tagging.

Parameters:
  • arrays (sequence of arrays) – The tensor arrays to form into a MPO.

  • sites (sequence of int, optional) – Construct the MPO on these sites only. If not given, enumerate from zero. Should be monotonically increasing and match arrays.

  • L (int, optional) – The number of sites the MPO should be defined on. If not given, this is taken as the max sites value plus one (i.e.g the number of arrays if sites is not given).

  • shape (str, optional) – String specifying layout of the tensors. E.g. ‘lrud’ (the default) indicates the shape corresponds left-bond, right-bond, ‘up’ physical index, ‘down’ physical index. End tensors have either ‘l’ or ‘r’ dropped from the string.

  • tags (str or sequence of str, optional) – Global tags to attach to all tensors.

  • upper_ind_id (str) – A string specifiying how to label the upper physical site indices. Should contain a '{}' placeholder. It is used to generate the actual indices like: map(upper_ind_id.format, range(len(arrays))).

  • lower_ind_id (str) – A string specifiying how to label the lower physical site indices. Should contain a '{}' placeholder. It is used to generate the actual indices like: map(lower_ind_id.format, range(len(arrays))).

  • site_tag_id (str) – A string specifiying how to tag the tensors at each site. Should contain a '{}' placeholder. It is used to generate the actual tags like: map(site_tag_id.format, range(len(arrays))).

_EXTRA_PROPS = ('_site_tag_id', '_upper_ind_id', '_lower_ind_id', 'cyclic', '_L')
classmethod from_fill_fn(fill_fn, L, bond_dim, phys_dim=2, sites=None, cyclic=False, shape='lrud', tags=None, upper_ind_id='k{}', lower_ind_id='b{}', site_tag_id='I{}')[source]

Create an MPO by supplying a ‘filling’ function to generate the data for each site.

Parameters:
  • fill_fn (callable) – A function with signature fill_fn(shape : tuple[int]) -> array_like.

  • L (int) – The number of sites.

  • bond_dim (int) – The bond dimension.

  • phys_dim (int or Sequence[int], optional) – The physical dimension(s) of each site, if a sequence it will be cycled over.

  • sites (None or sequence of int, optional) – Construct the MPO on these sites only. If not given, enumerate from zero.

  • cyclic (bool, optional) – Whether the MPO should be cyclic (periodic).

  • shape (str, optional) – String specifying layout of the tensors. E.g. ‘lrud’ (the default) indicates the shape corresponds left-bond, right-bond, ‘up’ physical index, ‘down’ physical index. End tensors have either ‘l’ or ‘r’ dropped from the string.

  • tags (str or sequence of str, optional) – Global tags to attach to all tensors.

  • upper_ind_id (str) – A string specifiying how to label the upper physical site indices. Should contain a '{}' placeholder.

  • lower_ind_id (str) – A string specifiying how to label the lower physical site indices. Should contain a '{}' placeholder.

  • site_tag_id (str, optional) – How to tag the physical sites. Should contain a '{}' placeholder.

Return type:

MatrixProductState

classmethod from_dense(A, dims=2, sites=None, L=None, tags=None, site_tag_id='I{}', upper_ind_id='k{}', lower_ind_id='b{}', **split_opts)[source]

Build an MPO from a raw dense matrix.

Parameters:
  • A (array) – The dense operator, it should be reshapeable to (*dims, *dims).

  • dims (int, sequence of int, optional) – The physical subdimensions of the operator. If any integer, assume all sites have the same dimension. If a sequence, the dimension of each site. Default is 2.

  • sites (sequence of int, optional) – The sites to place the operator on. If None, will place it on first len(dims) sites.

  • L (int, optional) – The total number of sites in the MPO, if the operator represents only a subset.

  • tags (str or sequence of str, optional) – Global tags to attach to all tensors.

  • site_tag_id (str, optional) – The string to use to label the site tags.

  • upper_ind_id (str, optional) – The string to use to label the upper physical indices.

  • lower_ind_id (str, optional) – The string to use to label the lower physical indices.

  • split_opts – Supplied to tensor_split().

Return type:

MatrixProductOperator

fill_empty_sites(mode='full', phys_dim=None, fill_array=None, inplace=False)[source]

Fill any empty sites of this MPO with identity tensors, adding size 1 bonds or draping existing bonds where necessary such that the resulting tensor has nearest neighbor bonds only.

Parameters:
  • mode ({'full', 'minimal'}, optional) – Whether to fill in all sites, including at either end, or simply the minimal range covering the min to max current sites present.

  • phys_dim (int, optional) – The physical dimension of the identity tensors to add. If not specified, will use the upper physical dimension of the first present site.

  • fill_array (array, optional) – The array to use for the identity tensors. If not specified, will use the identity array of the same dtype as the first present site.

  • inplace (bool, optional) – Whether to perform the operation inplace.

Returns:

The modified MPO.

Return type:

MatrixProductOperator

fill_empty_sites_[source]
add_MPO(other, inplace=False, **kwargs)[source]
add_MPO_[source]
_apply_mps(other, compress=False, contract=True, **compress_opts)[source]
_apply_mpo(other, compress=False, contract=True, **compress_opts)[source]
apply(other, compress=False, **compress_opts)[source]

Act with this MPO on another MPO or MPS, such that the resulting object has the same tensor network structure/indices as other.

For an MPS:

       | | | | | | | | | | | | | | | | | |
 self: A-A-A-A-A-A-A-A-A-A-A-A-A-A-A-A-A-A
       | | | | | | | | | | | | | | | | | |
other: x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x

                       -->

       | | | | | | | | | | | | | | | | | |   <- other.site_ind_id
  out: y=y=y=y=y=y=y=y=y=y=y=y=y=y=y=y=y=y

For an MPO:

       | | | | | | | | | | | | | | | | | |
 self: A-A-A-A-A-A-A-A-A-A-A-A-A-A-A-A-A-A
       | | | | | | | | | | | | | | | | | |
other: B-B-B-B-B-B-B-B-B-B-B-B-B-B-B-B-B-B
       | | | | | | | | | | | | | | | | | |

                       -->

       | | | | | | | | | | | | | | | | | |   <- other.upper_ind_id
  out: C=C=C=C=C=C=C=C=C=C=C=C=C=C=C=C=C=C
       | | | | | | | | | | | | | | | | | |   <- other.lower_ind_id

The resulting TN will have the same structure/indices as other, but probably with larger bonds (depending on compression).

Parameters:
Return type:

MatrixProductOperator or MatrixProductState

dot[source]
permute_arrays(shape='lrud')[source]

Permute the indices of each tensor in this MPO to match shape. This doesn’t change how the overall object interacts with other tensor networks but may be useful for extracting the underlying arrays consistently. This is an inplace operation.

Parameters:

shape (str, optional) – A permutation of 'lrud' specifying the desired order of the left, right, upper and lower (down) indices respectively.

trace(left_inds=None, right_inds=None)[source]

Take the trace of this MPO.

partial_transpose(sysa, inplace=False)[source]

Perform the partial transpose on this MPO by swapping the bra and ket indices on sites in sysa.

Parameters:
  • sysa (sequence of int or int) – The sites to transpose indices on.

  • inplace (bool, optional) – Whether to perform the partial transposition inplace.

Return type:

MatrixProductOperator

rand_state(bond_dim, **mps_opts)[source]

Get a random vector matching this MPO.

identity(**mpo_opts)[source]

Get a identity matching this MPO.

show(max_width=None)[source]
class quimb.tensor.tensor_1d.Dense1D(array, phys_dim=2, tags=None, site_ind_id='k{}', site_tag_id='I{}', **tn_opts)[source]

Bases: TensorNetwork1DVector

Mimics other 1D tensor network structures, but really just keeps the full state in a single tensor. This allows e.g. applying gates in the same way for quantum circuit simulation as lazily represented hilbert spaces.

Parameters:
  • array (array_like) – The full hilbert space vector - assumed to be made of equal hilbert spaces each of size phys_dim and will be reshaped as such.

  • phys_dim (int, optional) – The hilbert space size of each site, default: 2.

  • tags (sequence of str, optional) – Extra tags to add to the tensor network.

  • site_ind_id (str, optional) – String formatter describing how to label the site indices.

  • site_tag_id (str, optional) – String formatter describing how to label the site tags.

  • tn_opts – Supplied to TensorNetwork.

_EXTRA_PROPS = ('_site_ind_id', '_site_tag_id', '_L')
classmethod rand(n, phys_dim=2, dtype=float, **dense1d_opts)[source]

Create a random dense vector ‘tensor network’.

class quimb.tensor.tensor_1d.SuperOperator1D(arrays, shape='lrkud', site_tag_id='I{}', outer_upper_ind_id='kn{}', inner_upper_ind_id='k{}', inner_lower_ind_id='b{}', outer_lower_ind_id='bn{}', tags=None, tags_upper=None, tags_lower=None, **tn_opts)[source]

Bases: TensorNetwork1D

A 1D tensor network super-operator class:

0   1   2       n-1
|   |   |        |     <-- outer_upper_ind_id
O===O===O==     =O
|\  |\  |\       |\     <-- inner_upper_ind_id
  )   )   ) ...    )   <-- K (size of local Kraus sum)
|/  |/  |/       |/     <-- inner_lower_ind_id
O===O===O==     =O
|   | : |        |     <-- outer_lower_ind_id
      :
     chi (size of entangling bond dim)
Parameters:

arrays (sequence of arrays) – The data arrays defining the superoperator, this should be a sequence of 2n arrays, such that the first two correspond to the upper and lower operators acting on site 0 etc. The arrays should be 5 dimensional unless OBC conditions are desired, in which case the first two and last two should be 4-dimensional. The dimensions of array can be should match the shape option.

_EXTRA_PROPS = ('_site_tag_id', '_outer_upper_ind_id', '_inner_upper_ind_id', '_inner_lower_ind_id',...
classmethod rand(n, K, chi, phys_dim=2, herm=True, cyclic=False, dtype=complex, **superop_opts)[source]
property outer_upper_ind_id
property inner_upper_ind_id
property inner_lower_ind_id
property outer_lower_ind_id
class quimb.tensor.tensor_1d.TNLinearOperator1D(tn, left_inds, right_inds, start, stop, ldims=None, rdims=None, is_conj=False, is_trans=False)[source]

Bases: scipy.sparse.linalg.LinearOperator

A 1D tensor network linear operator like:

         start                 stop - 1
           .                     .
         :-O-O-O-O-O-O-O-O-O-O-O-O-:                 --+
         : | | | | | | | | | | | | :                   |
         :-H-H-H-H-H-H-H-H-H-H-H-H-:    acting on    --V
         : | | | | | | | | | | | | :                   |
         :-O-O-O-O-O-O-O-O-O-O-O-O-:                 --+
left_inds^                         ^right_inds

Like TNLinearOperator, but performs a structured contract from one end to the other than can handle very long chains possibly more efficiently by contracting in blocks from one end.

Parameters:
  • tn (TensorNetwork) – The tensor network to turn into a LinearOperator.

  • left_inds (sequence of str) – The left indicies.

  • right_inds (sequence of str) – The right indicies.

  • start (int) – Index of starting site.

  • stop (int) – Index of stopping site (does not include this site).

  • ldims (tuple of int, optional) – If known, the dimensions corresponding to left_inds.

  • rdims (tuple of int, optional) – If known, the dimensions corresponding to right_inds.

See also

TNLinearOperator

_matvec(vec)[source]

Default matrix-vector multiplication handler.

If self is a linear operator of shape (M, N), then this method will be called on a shape (N,) or (N, 1) ndarray, and should return a shape (M,) or (M, 1) ndarray.

This default implementation falls back on _matmat, so defining that will define matrix-vector multiplication as well.

_matmat(mat)[source]

Default matrix-matrix multiplication handler.

Falls back on the user-defined _matvec method, so defining that will define matrix multiplication (though in a very suboptimal way).

copy(conj=False, transpose=False)[source]
conj()[source]
_transpose()[source]

Default implementation of _transpose; defers to rmatvec + conj

_adjoint()[source]

Hermitian conjugate of this TNLO.

to_dense()[source]
property A