quimb.tensor.tensor_builder

Build specific tensor networks, including states and operators.

Attributes

Classes

MatrixProductOperator

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

MatrixProductState

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

LocalHam1D

An simple interacting hamiltonian object used, for instance, in TEBD.

TensorNetwork2D

Mixin class for tensor networks with a square lattice two-dimensional

LocalHam2D

A 2D Hamiltonian represented as local terms. This combines all two site

TensorNetwork3D

Mixin class for tensor networks with a cubic lattice three-dimensional

LocalHam3D

Representation of a local hamiltonian defined on a general graph. This

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

TensorNetwork

A collection of (as yet uncontracted) Tensors.

_TermAdder

Simple class to allow SpinHam1D syntax like

SpinHam1D

Class for easily building custom spin hamiltonians in MPO or LocalHam1D

Functions

ikron(ops, dims, inds[, sparse, stype, coo_build, ...])

Tensor an operator into a larger space by padding with identities.

make_immutable(mat)

Make array read only, in-place.

_gen_mbl_random_factors(n, dh, dh_dim, dh_dist[, ...])

ham_heis(n[, j, b, cyclic, parallel, nthreads, ownership])

Constructs the nearest neighbour 1d heisenberg spin-1/2 hamiltonian.

spin_operator(label[, S])

Generate a general spin-operator.

rand_phase(shape[, scale, dtype])

Generate random complex numbers distributed on the unit sphere.

randn([shape, dtype, scale, loc, num_threads, seed, dist])

Fast multithreaded generation of random normally distributed data.

random_seed_fn(fn)

Modify fn to take a seed argument (so as to seed the random

seed_rand(seed)

See the random number generators, by instantiating a new set of bit

deprecated(fn, old_name, new_name)

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

asarray(array)

Maybe convert data for a tensor to use. If array already has a

sensibly_scale(x)

Take an array and scale it very roughly such that random tensor

array_contract(arrays, inputs[, output, optimize, backend])

eigh_truncated(x[, cutoff, cutoff_mode, max_bond, ...])

gen_2d_bonds(Lx, Ly[, steppers, coo_filter, cyclic])

Convenience function for tiling pairs of bond coordinates on a 2D

gen_2d_plaquettes(Lx, Ly, tiling)

Generate a tiling of plaquettes in a square 2D lattice.

gen_3d_bonds(Lx, Ly, Lz[, steppers, coo_filter, cyclic])

Convenience function for tiling pairs of bond coordinates on a 3D

gen_3d_plaquettes(Lx, Ly, Lz[, tiling])

Generate a tiling of plaquettes in a cubic 3D lattice.

create_lazy_edge_map(tn[, site_tags])

Given a tensor network, where each tensor is in exactly one group or

COPY_tensor(d, inds[, tags, dtype])

Get the tensor representing the COPY operation with dimension size

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_direct_product(T1, T2[, sum_inds, inplace])

Direct product of two Tensors. Any axes included in sum_inds must be

tensor_network_sum(tnA, tnB[, inplace])

Sum of two tensor networks, whose indices should match exactly, using

delta_array(shape[, dtype])

Get the delta symbol AKA COPY-tensor as an ndarray.

get_rand_fill_fn([dist, loc, scale, seed, dtype])

Get a callable with the given random distribution and parameters, that

rand_tensor(shape, inds[, tags, dtype, dist, scale, ...])

Generate a random tensor with specified shape and inds.

rand_phased(shape, inds[, tags, dtype])

Generate a random tensor with specified shape and inds, and randomly

rand_symmetric_array(d, ndim[, dist, loc, scale, ...])

Get a random symmetric array, i.e. one that is invariant under

rand_tensor_symmetric(d, inds[, tags, dist, loc, ...])

Generate a random symmetric tensor with specified local dimension and

TN_from_sites_product_state(site_map[, site_tag_id, ...])

A product state in general tensor network form.

TN_from_sites_computational_state(site_map[, ...])

A computational basis state in general tensor network form.

gen_unique_edges(edges)

compute_string_edge_frequencies(strings)

Compute a dictionary of edge frequencies for a list of strings,

TN_from_edges_and_fill_fn(fill_fn, edges, D[, ...])

Create a tensor network from a sequence of edges defining a graph,

TN_from_edges_empty(edges, D[, phys_dim, site_tag_id, ...])

Create a tensor network from a sequence of edges defining a graph,

TN_from_edges_with_value(value, edges, D[, phys_dim, ...])

Create a tensor network from a sequence of edges defining a graph,

TN_from_edges_rand(edges, D[, phys_dim, seed, dtype, ...])

Create a random tensor network with geometry defined from a sequence

TN_rand_reg(n, reg, D[, phys_dim, seed, dtype, ...])

Create a random regular tensor network.

TN_rand_tree(n, D[, phys_dim, seed, dtype, ...])

Create a random tree tensor network.

TN_from_strings(strings[, fill_fn, line_dim, ...])

HTN_CP_from_inds_and_fill_fn(fill_fn, inds, sizes, D)

reate a CP-decomposition structured hyper tensor network from a

HTN_CP_from_sites_and_fill_fn(fill_fn, sites, D[, ...])

Create a CP-decomposition structured hyper tensor network state from a

HTN_CP_operator_from_products(array_seqs, upper_inds, ...)

Construct a CP form hyper tensor network of the sum of matrix strings:

HTN_dual_from_edges_and_fill_fn(fill_fn, edges, D[, ...])

Create a hyper tensor network with a tensor on each bond and a hyper

convert_to_2d(tn[, Lx, Ly, site_tag_id, x_tag_id, ...])

Convert tn to a TensorNetwork2D,

TN2D_from_fill_fn(fill_fn, Lx, Ly, D[, cyclic, ...])

A scalar 2D lattice tensor network with tensors filled by a function.

TN2D_empty(Lx, Ly, D[, cyclic, site_tag_id, x_tag_id, ...])

A scalar 2D lattice tensor network initialized with empty tensors.

TN2D_with_value(value, Lx, Ly, D[, cyclic, ...])

A scalar 2D lattice tensor network with every element set to value.

TN2D_rand(Lx, Ly, D[, cyclic, site_tag_id, x_tag_id, ...])

A random scalar 2D lattice tensor network.

TN2D_rand_symmetric(Lx, Ly, D[, cyclic, site_tag_id, ...])

Create a random 2D lattice tensor network where every tensor is

TN2D_corner_double_line(Lx, Ly[, line_dim, tiling, ...])

Build a 2D 'corner double line' (CDL) tensor network. Each plaquette

TN2D_rand_hidden_loop(Lx, Ly, *[, cyclic, line_dim, ...])

convert_to_3d(tn[, Lx, Ly, Lz, site_tag_id, x_tag_id, ...])

Convert tn to a TensorNetwork3D,

TN3D_from_fill_fn(fill_fn, Lx, Ly, Lz, D[, cyclic, ...])

A scalar 3D lattice tensor network with tensors filled by a function.

TN3D_empty(Lx, Ly, Lz, D[, cyclic, site_tag_id, ...])

A scalar 3D lattice tensor network initialized with empty tensors.

TN3D_with_value(value, Lx, Ly, Lz, D[, cyclic, ...])

A scalar 2D lattice tensor network with every element set to value.

TN3D_rand(Lx, Ly, Lz, D[, cyclic, site_tag_id, ...])

A random scalar 3D lattice tensor network.

TN3D_corner_double_line(Lx, Ly, Lz[, line_dim, ...])

TN3D_rand_hidden_loop(Lx, Ly, Lz, *[, cyclic, ...])

classical_ising_S_matrix(beta[, j])

The interaction term for the classical ising model.

classical_ising_H_matrix(beta[, h])

The magnetic field term for the classical ising model.

classical_ising_sqrtS_matrix(beta[, j, asymm])

The sqrt factorized interaction term for the classical ising model.

classical_ising_T_matrix(beta[, j, h, directions, ...])

The single effective TN site for the classical ising model.

parse_j_coupling_to_function(j)

Parse the j argument to a function that can be called to get the

HTN2D_classical_ising_partition_function(Lx, Ly, beta)

Hyper tensor network representation of the 2D classical ising model

HTN3D_classical_ising_partition_function(Lx, Ly, Lz, beta)

Hyper tensor network representation of the 3D classical ising model

TN2D_classical_ising_partition_function(Lx, Ly, beta)

The tensor network representation of the 2D classical ising model

TN3D_classical_ising_partition_function(Lx, Ly, Lz, beta)

Tensor network representation of the 3D classical ising model

HTN_classical_partition_function_from_edges(edges, beta)

Build a hyper tensor network representation of a classical ising model

TN_classical_partition_function_from_edges(edges, beta)

Build a regular tensor network representation of a classical ising model

make_couplings_matrix_symmetric(J[, UPLO])

Take a coupling matrix or dict of pairwise strengths in either upper or

TN2D_embedded_classical_ising_partition_function(Jij, beta)

Construct a (triangular) '2D' tensor network representation of the

dimer_data(d[, cover_count, dtype])

TN_dimer_covering_from_edges(edges[, cover_count, ...])

Make a tensor network from sequence of graph edges that counts the

clause_negmask(clause)

Encode a clause as a single integer m.

or_clause_data(ndim[, m, dtype, q])

Get the array representing satisfiability of ndim clauses with

or_clause_tensor(ndim, m, inds[, tags, dtype])

Get the tensor representing satisfiability of ndim clauses with

or_clause_mps_tensors(ndim, m, inds[, tags, dtype])

Get the set of MPS tensors representing satisfiability of ndim

or_clause_parafac_data(ndim, m[, dtype])

Get the set of PARAFAC arrays representing satisfiability of ndim

clause_parafac_tensors(ndim, m, inds[, tags, dtype])

Get the set of PARAFAC tensors representing satisfiability of ndim

HTN_from_clauses(clauses[, weights, mode, dtype, ...])

Given a list of clauses, create a hyper tensor network, with a single

cnf_file_parse(fname)

Parse a DIMACS style 'cnf' file into a list of clauses, and possibly a

HTN_from_cnf(fname[, mode, dtype, clause_tag_id, ...])

Create a hyper tensor network from a '.cnf' or '.wcnf' file - i.e. a

random_ksat_instance(k, num_variables[, num_clauses, ...])

Create a random k-SAT instance.

HTN_random_ksat(k, num_variables[, num_clauses, ...])

Create a random k-SAT instance encoded as a hyper tensor network.

TN_matching(tn, max_bond[, site_tags, fill_fn, dtype])

Create a tensor network with the same outer indices as tn but

MPS_rand_state(L, bond_dim[, phys_dim, normalize, ...])

Generate a random matrix product state.

MPS_product_state(arrays[, cyclic])

Generate a product state in MatrixProductState form, i,e,

MPS_computational_state(binary[, dtype, cyclic])

A computational basis state in Matrix Product State form.

MPS_neel_state(L[, down_first, dtype])

Generate the neel state in Matrix Product State form.

MPS_COPY(L[, phys_dim, dtype])

Build a matrix product state representation of the COPY tensor.

MPS_ghz_state(L[, dtype])

Build the chi=2 OBC MPS representation of the GHZ state.

MPS_w_state(L[, dtype])

Build the chi=2 OBC MPS representation of the W state.

MPS_rand_computational_state(L[, dtype])

Generate a random computation basis state, like '01101001010'.

MPS_zero_state(L[, bond_dim, phys_dim, cyclic, dtype])

The all-zeros MPS state, of given bond-dimension.

MPS_sampler(L[, dtype, squeeze])

A product state for sampling tensor network traces. Seen as a vector it

MPO_identity(L[, sites, phys_dim, dtype, cyclic])

Generate an identity MPO of size L.

MPO_identity_like(mpo, **mpo_opts)

Return an identity matrix operator with the same physical index and

MPO_zeros(L[, phys_dim, dtype, cyclic])

Generate a zeros MPO of size L.

MPO_zeros_like(mpo, **mpo_opts)

Return a zeros matrix product operator with the same physical index and

MPO_product_operator(arrays[, cyclic])

Return an MPO of bond dimension 1 representing the product of raw

MPO_rand(L, bond_dim[, phys_dim, normalize, cyclic, ...])

Generate a random matrix product state.

MPO_rand_herm(L, bond_dim[, phys_dim, normalize, dtype])

Generate a random hermitian matrix product operator.

maybe_make_real(X)

Check if X is real, if so, convert to contiguous array.

spin_ham_mpo_tensor(one_site_terms, two_site_terms[, ...])

Generate tensor(s) for a spin hamiltonian MPO.

_ham_ising([j, bx, S, cyclic])

MPO_ham_ising(L[, j, bx, S, cyclic])

Ising Hamiltonian in MPO form.

ham_1d_ising([L, j, bx, S, cyclic])

Ising Hamiltonian in

_ham_XY([j, bz, S, cyclic])

MPO_ham_XY(L[, j, bz, S, cyclic])

XY-Hamiltonian in MPO form.

ham_1d_XY([L, j, bz, S, cyclic])

XY-Hamiltonian in

_ham_heis([j, bz, S, cyclic])

MPO_ham_heis(L[, j, bz, S, cyclic])

Heisenberg Hamiltonian in MPO form.

ham_1d_heis([L, j, bz, S, cyclic])

Heisenberg Hamiltonian in

MPO_ham_XXZ(L, delta[, jxy, S, cyclic])

XXZ-Hamiltonian in MPO form.

ham_1d_XXZ([L, delta, jxy, S, cyclic])

XXZ-Hamiltonian in

_ham_bilinear_biquadratic(theta, *[, S, cyclic])

MPO_ham_bilinear_biquadratic([L, theta, S, cyclic, ...])

Hamiltonian of one-dimensional bilinear biquadratic chain in MPO form,

ham_1d_bilinear_biquadratic([L, theta, S, cyclic])

Hamiltonian of one-dimensional bilinear biquadratic chain in LocalHam1D

_ham_mbl(L, dh[, j, seed, S, cyclic, dh_dist, dh_dim, ...])

MPO_ham_mbl(L, dh[, j, seed, S, cyclic, dh_dist, ...])

The many-body-localized spin hamiltonian in MPO form.

ham_1d_mbl(L, dh[, j, seed, S, cyclic, dh_dist, ...])

The many-body-localized spin hamiltonian in

ham_2d_ising(Lx, Ly[, j, bx])

Ising Hamiltonian in

ham_2d_heis(Lx, Ly[, j, bz])

Heisenberg Hamiltonian in

ham_2d_j1j2(Lx, Ly[, j1, j2, bz])

Heisenberg Hamiltonian in

ham_3d_heis(Lx, Ly, Lz[, j, bz])

Heisenberg Hamiltonian in

Module Contents

quimb.tensor.tensor_builder.ikron(ops, dims, inds, sparse=None, stype=None, coo_build=False, parallel=False, ownership=None)[source]

Tensor an operator into a larger space by padding with identities.

Automatically placing a large operator over several dimensions is allowed and a list of operators can be given which are then placed cyclically.

Parameters:
  • op (operator or sequence of operators) – Operator(s) to place into the tensor space. If more than one, these are cyclically placed at each of the dims specified by inds.

  • dims (sequence of int or nested sequences of int) – The subsystem dimensions. If treated as an array, should have the same number of dimensions as the system.

  • inds (tuple of int, or sequence of tuple of int) – Indices, or coordinates, of the dimensions to place operator(s) on. Each dimension specified can be smaller than the size of op (as long as it factorizes it).

  • sparse (bool, optional) – Whether to construct the new operator in sparse form.

  • stype (str, optional) – If sparse, which format to use for the output.

  • coo_build (bool, optional) – Whether to build the intermediary matrices using the 'coo' format - can be faster to build sparse in this way, then convert to chosen format, including dense.

  • parallel (bool, optional) – Whether to build the operator in parallel using threads (only good for big (d > 2**16) operators).

  • ownership ((int, int), optional) – If given, only construct the rows in range(*ownership). Such that the final operator is actually X[slice(*ownership), :]. Useful for constructing operators in parallel, e.g. for MPI.

Returns:

Operator such that ops act on dims[inds].

Return type:

qarray or sparse matrix

See also

kron, pkron

Examples

Place an operator between two identities:

>>> IZI = ikron(pauli('z'), [2, 2, 2], 1)
>>> np.allclose(IZI, eye(2) & pauli('z') & eye(2))
True

Overlay a large operator on several sites:

>>> rho_ab = rand_rho(4)
>>> rho_abc = ikron(rho_ab, [5, 2, 2, 7], [1, 2])  # overlay both 2s
>>> rho_abc.shape
(140, 140)

Place an operator at specified sites, regardless of size:

>>> A = rand_herm(5)
>>> ikron(A, [2, -1, 2, -1, 2, -1], [1, 3, 5]).shape
(1000, 1000)

Create a two site interaction (note the coefficient jx we only need to multiply into a single input operator):

>>> Sx = spin_operator('X')
>>> jx = 0.123
>>> jSxSx = ikron([jx * Sx, Sx], [2, 2, 2, 2], [0, 3])
>>> np.allclose(jSxSx, jx * (Sx & eye(2) & eye(2) & Sx))
True
quimb.tensor.tensor_builder.make_immutable(mat)[source]

Make array read only, in-place.

Parameters:

mat (sparse or dense array) – Matrix to make immutable.

quimb.tensor.tensor_builder._gen_mbl_random_factors(n, dh, dh_dim, dh_dist, seed=None, beta=None)[source]
quimb.tensor.tensor_builder.eye[source]

Alias for identity().

quimb.tensor.tensor_builder.ham_heis(n, j=1.0, b=0.0, cyclic=False, parallel=False, nthreads=None, ownership=None)[source]

Constructs the nearest neighbour 1d heisenberg spin-1/2 hamiltonian.

Parameters:
  • n (int) – Number of spins.

  • j (float or tuple(float, float, float), optional) – Coupling constant(s), with convention that positive = antiferromagnetic. Can supply scalar for isotropic coupling or vector (jx, jy, jz).

  • b (float or tuple(float, float, float), optional) – Magnetic field, defaults to z-direction only if tuple not given.

  • cyclic (bool, optional) – Whether to couple the first and last spins.

  • sparse (bool, optional) – Whether to return the hamiltonian in sparse form.

  • stype (str, optional) – What format of sparse operator to return if sparse.

  • parallel (bool, optional) – Whether to build the operator in parallel. By default will do this for n > 16.

  • nthreads (int optional) – How mny threads to use in parallel to build the operator.

  • ownership ((int, int), optional) – If given, which range of rows to generate.

  • kwargs – Supplied to quimbify().

Returns:

H – The Hamiltonian.

Return type:

immutable operator

quimb.tensor.tensor_builder.spin_operator(label, S=1 / 2, **kwargs)[source]

Generate a general spin-operator.

Parameters:
  • label (str) –

    The type of operator, can be one of six options:

    • {'x', 'X'}, x-spin operator.

    • {'y', 'Y'}, y-spin operator.

    • {'z', 'Z'}, z-spin operator.

    • {'+', 'p'}, Raising operator.

    • {'-', 'm'}, Lowering operator.

    • {'i', 'I'}, identity operator.

  • S (float, optional) – The spin of particle to act on, default to spin-1/2.

  • kwargs – Passed to quimbify().

Returns:

S – The spin operator.

Return type:

immutable operator

See also

pauli

Examples

>>> spin_operator('x')
qarray([[0. +0.j, 0.5+0.j],
        [0.5+0.j, 0. +0.j]])
>>> qu.spin_operator('+', S=1)
qarray([[0.        +0.j, 1.41421356+0.j, 0.        +0.j],
        [0.        +0.j, 0.        +0.j, 1.41421356+0.j],
        [0.        +0.j, 0.        +0.j, 0.        +0.j]])
>>> qu.spin_operator('Y', sparse=True)
<2x2 sparse matrix of type '<class 'numpy.complex128'>'
    with 2 stored elements in Compressed Sparse Row format>
quimb.tensor.tensor_builder.choice[source]
quimb.tensor.tensor_builder.rand_phase(shape, scale=1, dtype=complex)[source]

Generate random complex numbers distributed on the unit sphere.

quimb.tensor.tensor_builder.randn(shape=(), dtype=float, scale=1.0, loc=0.0, num_threads=None, seed=None, dist='normal')[source]

Fast multithreaded generation of random normally distributed data.

Parameters:
  • shape (tuple[int]) – The shape of the output random array.

  • dtype ({'complex128', 'float64', 'complex64' 'float32'}, optional) – The data-type of the output array.

  • scale (float, optional) – A multiplicative scale for the random numbers.

  • loc (float, optional) – An additive location for the random numbers.

  • num_threads (int, optional) – How many threads to use. If None, decide automatically.

  • dist ({'normal', 'uniform', 'rademacher', 'exp'}, optional) – Type of random number to generate.

quimb.tensor.tensor_builder.random_seed_fn(fn)[source]

Modify fn to take a seed argument (so as to seed the random generators once-only at beginning of function not every randn call).

quimb.tensor.tensor_builder.seed_rand(seed)[source]

See the random number generators, by instantiating a new set of bit generators with a ‘seed sequence’.

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

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

quimb.tensor.tensor_builder.asarray(array)[source]

Maybe convert data for a tensor to use. If array already has a .shape attribute, i.e. looks like an array, it is left as-is. Else the elements are inspected to see which libraries’ array constructor should be used, defaulting to numpy if everything is builtin or numpy numbers.

quimb.tensor.tensor_builder.sensibly_scale(x)[source]

Take an array and scale it very roughly such that random tensor networks consisting of such arrays do not have gigantic norms.

quimb.tensor.tensor_builder.array_contract(arrays, inputs, output=None, optimize=None, backend=None, **kwargs)[source]
quimb.tensor.tensor_builder.eigh_truncated(x, cutoff=-1.0, cutoff_mode=4, max_bond=-1, absorb=0, renorm=0, backend=None)[source]
class quimb.tensor.tensor_builder.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_builder.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_builder.LocalHam1D(L, H2, H1=None, cyclic=False)[source]

Bases: quimb.tensor.tensor_arbgeom_tebd.LocalHamGen

An simple interacting hamiltonian object used, for instance, in TEBD. Once instantiated, the LocalHam1D hamiltonian stores a single term per pair of sites, cached versions of which can be retrieved like H.get_gate_expm((i, i + 1), -1j * 0.5) etc.

Parameters:
  • L (int) – The size of the hamiltonian.

  • H2 (array_like or dict[tuple[int], array_like]) – The sum of interaction terms. If a dict is given, the keys should be nearest neighbours like (10, 11), apart from any default term which should have the key None, and the values should be the sum of interaction terms for that interaction.

  • H1 (array_like or dict[int, array_like], optional) – The sum of single site terms. If a dict is given, the keys should be integer sites, apart from any default term which should have the key None, and the values should be the sum of single site terms for that site.

  • cyclic (bool, optional) – Whether the hamiltonian has periodic boundary conditions or not.

terms

The terms in the hamiltonian, combined from the inputs such that there is a single term per pair.

Type:

dict[tuple[int], array]

Examples

A simple, translationally invariant, interaction-only LocalHam1D:

>>> XX = pauli('X') & pauli('X')
>>> YY = pauli('Y') & pauli('Y')
>>> ham = LocalHam1D(L=100, H2=XX + YY)

The same, but with a translationally invariant field as well:

>>> Z = pauli('Z')
>>> ham = LocalHam1D(L=100, H2=XX + YY, H1=Z)

Specifying a default interaction and field, with custom values set for some sites:

>>> H2 = {None: XX + YY, (49, 50): (XX + YY) / 2}
>>> H1 = {None: Z, 49: 2 * Z, 50: 2 * Z}
>>> ham = LocalHam1D(L=100, H2=H2, H1=H1)

Specifying the hamiltonian entirely through site specific interactions and fields:

>>> H2 = {(i, i + 1): XX + YY for i in range(99)}
>>> H1 = {i: Z for i in range(100)}
>>> ham = LocalHam1D(L=100, H2=H2, H1=H1)

See also

SpinHam1D

mean_norm()[source]

Computes the average frobenius norm of local terms.

build_mpo_propagator_trotterized(x, site_tag_id='I{}', tags=None, upper_ind_id='k{}', lower_ind_id='b{}', shape='lrud', contract_sites=True, **split_opts)[source]

Build an MPO representation of expm(H * x), i.e. the imaginary or real time propagator of this local 1D hamiltonian, using a first order trotterized decomposition.

Parameters:
  • x (float) – The time to evolve for. Note this does not include the imaginary prefactor of the Schrodinger equation, so real x corresponds to imaginary time evolution, and vice versa.

  • 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))).

  • 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))).

  • 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 if not periodic.

  • contract_sites (bool, optional) – Whether to contract all the decomposed factors at each site to yield a single tensor per site, by default True.

  • split_opts – Supplied to tensor_split().

__repr__()[source]

Return repr(self).

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

Bases: quimb.tensor.tensor_arbgeom.TensorNetworkGen

Mixin class for tensor networks with a square lattice two-dimensional structure, indexed by [{row},{column}] so that:

             'Y{j}'
                v

i=Lx-1 ●──●──●──●──●──●──   ──●
       |  |  |  |  |  |       |
             ...
       |  |  |  |  |  | 'I{i},{j}' = 'I3,5' e.g.
i=3    ●──●──●──●──●──●──
       |  |  |  |  |  |       |
i=2    ●──●──●──●──●──●──   ──●    <== 'X{i}'
       |  |  |  |  |  |  ...  |
i=1    ●──●──●──●──●──●──   ──●
       |  |  |  |  |  |       |
i=0    ●──●──●──●──●──●──   ──●

     j=0, 1, 2, 3, 4, 5    j=Ly-1

This implies the following conventions:

  • the ‘up’ bond is coordinates (i, j), (i + 1, j)

  • the ‘down’ bond is coordinates (i, j), (i - 1, j)

  • the ‘right’ bond is coordinates (i, j), (i, j + 1)

  • the ‘left’ bond is coordinates (i, j), (i, j - 1)

_NDIMS = 2
_EXTRA_PROPS = ('_site_tag_id', '_x_tag_id', '_y_tag_id', '_Lx', '_Ly')
_compatible_2d(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 TensorNetwork2D instance.

Parameters:
  • other (TensorNetwork2D 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:

TensorNetwork2D or TensorNetwork

property Lx
The number of rows.
property Ly
The number of columns.
property nsites
The total number of sites.
site_tag(i, j=None)[source]

The name of the tag specifiying the tensor at site (i, j).

property x_tag_id
The string specifier for tagging each row of this 2D TN.
x_tag(i)[source]
property x_tags
A tuple of all of the ``Lx`` different row tags.
row_tag[source]
row_tags
property y_tag_id
The string specifier for tagging each column of this 2D TN.
y_tag(j)[source]
property y_tags
A tuple of all of the ``Ly`` different column tags.
col_tag[source]
col_tags
maybe_convert_coo(x)[source]

Check if x is a tuple of two ints and convert to the corresponding site tag if so.

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

This is the function that lets coordinates such as (i, j) be used for many ‘tag’ based functions.

gen_site_coos()[source]

Generate coordinates for all the sites in this 2D TN.

gen_bond_coos()[source]

Generate pairs of coordinates for all the bonds in this 2D TN.

gen_horizontal_bond_coos()[source]

Generate all coordinate pairs like (i, j), (i, j + 1).

gen_horizontal_even_bond_coos()[source]

Generate all coordinate pairs like (i, j), (i, j + 1) where j is even, which thus don’t overlap at all.

gen_horizontal_odd_bond_coos()[source]

Generate all coordinate pairs like (i, j), (i, j + 1) where j is odd, which thus don’t overlap at all.

gen_vertical_bond_coos()[source]

Generate all coordinate pairs like (i, j), (i + 1, j).

gen_vertical_even_bond_coos()[source]

Generate all coordinate pairs like (i, j), (i + 1, j) where i is even, which thus don’t overlap at all.

gen_vertical_odd_bond_coos()[source]

Generate all coordinate pairs like (i, j), (i + 1, j) where i is odd, which thus don’t overlap at all.

gen_diagonal_left_bond_coos()[source]

Generate all coordinate pairs like (i, j), (i + 1, j - 1).

gen_diagonal_left_even_bond_coos()[source]

Generate all coordinate pairs like (i, j), (i + 1, j - 1) where j is even, which thus don’t overlap at all.

gen_diagonal_left_odd_bond_coos()[source]

Generate all coordinate pairs like (i, j), (i + 1, j - 1) where j is odd, which thus don’t overlap at all.

gen_diagonal_right_bond_coos()[source]

Generate all coordinate pairs like (i, j), (i + 1, j + 1).

gen_diagonal_right_even_bond_coos()[source]

Generate all coordinate pairs like (i, j), (i + 1, j + 1) where i is even, which thus don’t overlap at all.

gen_diagonal_right_odd_bond_coos()[source]

Generate all coordinate pairs like (i, j), (i + 1, j + 1) where i is odd, which thus don’t overlap at all.

gen_diagonal_bond_coos()[source]

Generate all next nearest neighbor diagonal coordinate pairs.

valid_coo(coo, xrange=None, yrange=None)[source]

Check whether coo is in-bounds.

Parameters:
  • coo ((int, int, int), optional) – The coordinates to check.

  • xrange ((int, int), optional) – The range of allowed values for the x and y coordinates.

  • yrange ((int, int), optional) – The range of allowed values for the x and y coordinates.

Return type:

bool

get_ranges_present()[source]

Return the range of site coordinates present in this TN.

Returns:

xrange, yrange – The minimum and maximum site coordinates present in each direction.

Return type:

tuple[tuple[int, int]]

is_cyclic_x(j=None, imin=None, imax=None)[source]

Check if the x dimension is cyclic (periodic), specifically whether a bond exists between (imin, j) and (imax, j), with default values of imin = 0 and imax = Lx - 1, and j at the center of the lattice. If imin and imax are adjacent then this is considered False, since there is no ‘extra’ connectivity.

is_cyclic_y(i=None, jmin=None, jmax=None)[source]

Check if the y dimension is cyclic (periodic), specifically whether a bond exists between (i, jmin) and (i, jmax), with default values of jmin = 0 and jmax = Ly - 1, and i at the center of the lattice. If jmin and jmax are adjacent then this is considered False, since there is no ‘extra’ connectivity.

__getitem__(key)[source]

Key based tensor selection, checking for integer based shortcut.

show()[source]

Print a unicode schematic of this 2D TN and its bond dimensions.

_repr_info()[source]

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

flatten(fuse_multibonds=True, inplace=False)[source]

Contract all tensors corresponding to each site into one.

flatten_[source]
gen_pairs(xrange=None, yrange=None, xreverse=False, yreverse=False, coordinate_order='xy', xstep=None, ystep=None, stepping_order='xy', step_only=None)[source]

Helper function for generating pairs of cooordinates for all bonds within a certain range, optionally specifying an order.

Parameters:
  • xrange ((int, int), optional) – The range of allowed values for the x and y coordinates.

  • yrange ((int, int), optional) – The range of allowed values for the x and y coordinates.

  • xreverse (bool, optional) – Whether to reverse the order of the x and y sweeps.

  • yreverse (bool, optional) – Whether to reverse the order of the x and y sweeps.

  • coordinate_order (str, optional) – The order in which to sweep the x and y coordinates. Earlier dimensions will change slower. If the corresponding range has size 1 then that dimension doesn’t need to be specified.

  • xstep (int, optional) – When generating a bond, step in this direction to yield the neighboring coordinate. By default, these follow xreverse and yreverse respectively.

  • ystep (int, optional) – When generating a bond, step in this direction to yield the neighboring coordinate. By default, these follow xreverse and yreverse respectively.

  • stepping_order (str, optional) – The order in which to step the x and y coordinates to generate bonds. Does not need to include all dimensions.

  • step_only (int, optional) – Only perform the ith steps in stepping_order, used to interleave canonizing and compressing for example.

Yields:

coo_a, coo_b (((int, int), (int, int)))

canonize_plane(xrange, yrange, equalize_norms=False, canonize_opts=None, **gen_pair_opts)[source]

Canonize every pair of tensors within a subrange, optionally specifying a order to visit those pairs in.

canonize_row(i, sweep, yrange=None, **canonize_opts)[source]

Canonize all or part of a row.

If sweep == 'right' then:

 |  |  |  |  |  |  |         |  |  |  |  |  |  |
─●──●──●──●──●──●──●─       ─●──●──●──●──●──●──●─
 |  |  |  |  |  |  |         |  |  |  |  |  |  |
─●──●──●──●──●──●──●─  ==>  ─●──>──>──>──>──o──●─ row=i
 |  |  |  |  |  |  |         |  |  |  |  |  |  |
─●──●──●──●──●──●──●─       ─●──●──●──●──●──●──●─
 |  |  |  |  |  |  |         |  |  |  |  |  |  |
    .           .               .           .
    jstart      jstop           jstart      jstop

If sweep == 'left' then:

 |  |  |  |  |  |  |         |  |  |  |  |  |  |
─●──●──●──●──●──●──●─       ─●──●──●──●──●──●──●─
 |  |  |  |  |  |  |         |  |  |  |  |  |  |
─●──●──●──●──●──●──●─  ==>  ─●──o──<──<──<──<──●─ row=i
 |  |  |  |  |  |  |         |  |  |  |  |  |  |
─●──●──●──●──●──●──●─       ─●──●──●──●──●──●──●─
 |  |  |  |  |  |  |         |  |  |  |  |  |  |
    .           .               .           .
    jstop       jstart          jstop       jstart

Does not yield an orthogonal form in the same way as in 1D.

Parameters:
  • i (int) – Which row to canonize.

  • sweep ({'right', 'left'}) – Which direction to sweep in.

  • jstart (int or None) – Starting column, defaults to whole row.

  • jstop (int or None) – Stopping column, defaults to whole row.

  • canonize_opts – Supplied to canonize_between.

canonize_column(j, sweep, xrange=None, **canonize_opts)[source]

Canonize all or part of a column.

If sweep='up' then:

 |  |  |         |  |  |
─●──●──●─       ─●──●──●─
 |  |  |         |  |  |
─●──●──●─       ─●──o──●─ istop
 |  |  |   ==>   |  |  |
─●──●──●─       ─●──^──●─
 |  |  |         |  |  |
─●──●──●─       ─●──^──●─ istart
 |  |  |         |  |  |
─●──●──●─       ─●──●──●─
 |  |  |         |  |  |
    .               .
    j               j

If sweep='down' then:

 |  |  |         |  |  |
─●──●──●─       ─●──●──●─
 |  |  |         |  |  |
─●──●──●─       ─●──v──●─ istart
 |  |  |   ==>   |  |  |
─●──●──●─       ─●──v──●─
 |  |  |         |  |  |
─●──●──●─       ─●──o──●─ istop
 |  |  |         |  |  |
─●──●──●─       ─●──●──●─
 |  |  |         |  |  |
    .               .
    j               j

Does not yield an orthogonal form in the same way as in 1D.

Parameters:
  • j (int) – Which column to canonize.

  • sweep ({'up', 'down'}) – Which direction to sweep in.

  • xrange (None or (int, int), optional) – The range of columns to canonize.

  • canonize_opts – Supplied to canonize_between.

canonize_row_around(i, around=(0, 1))[source]
compress_plane(xrange, yrange, max_bond=None, cutoff=1e-10, equalize_norms=False, compress_opts=None, **gen_pair_opts)[source]

Compress every pair of tensors within a subrange, optionally specifying a order to visit those pairs in.

compress_row(i, sweep, yrange=None, max_bond=None, cutoff=1e-10, equalize_norms=False, compress_opts=None)[source]

Compress all or part of a row.

If sweep == 'right' then:

 |  |  |  |  |  |  |         |  |  |  |  |  |  |
━●━━●━━●━━●━━●━━●━━●━       ━●━━●━━●━━●━━●━━●━━●━
 |  |  |  |  |  |  |         |  |  |  |  |  |  |
━●━━●━━●━━●━━●━━●━━●━  ━━>  ━●━━>──>──>──>──o━━●━ row=i
 |  |  |  |  |  |  |         |  |  |  |  |  |  |
━●━━●━━●━━●━━●━━●━━●━       ━●━━●━━●━━●━━●━━●━━●━
 |  |  |  |  |  |  |         |  |  |  |  |  |  |
    .           .               .           .
    jstart      jstop           jstart      jstop

If sweep == 'left' then:

 |  |  |  |  |  |  |         |  |  |  |  |  |  |
━●━━●━━●━━●━━●━━●━━●━       ━●━━●━━●━━●━━●━━●━━●━
 |  |  |  |  |  |  |         |  |  |  |  |  |  |
━●━━●━━●━━●━━●━━●━━●━  ━━>  ━●━━o──<──<──<──<━━●━ row=i
 |  |  |  |  |  |  |         |  |  |  |  |  |  |
━●━━●━━●━━●━━●━━●━━●━       ━●━━●━━●━━●━━●━━●━━●━
 |  |  |  |  |  |  |         |  |  |  |  |  |  |
    .           .               .           .
    jstop       jstart          jstop       jstart

Does not yield an orthogonal form in the same way as in 1D.

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

  • sweep ({'right', 'left'}) – Which direction to sweep in.

  • yrange (tuple[int, int] or None) – The range of columns to compress.

  • max_bond (int, optional) – The maximum boundary dimension, AKA ‘chi’. The default of None means truncation is left purely to cutoff and is not recommended in 2D.

  • cutoff (float, optional) – Cut-off value to used to truncate singular values in the boundary contraction.

  • compress_opts (None or dict, optional) – Supplied to compress_between().

compress_column(j, sweep, xrange=None, max_bond=None, cutoff=1e-10, equalize_norms=False, compress_opts=None)[source]

Compress all or part of a column.

If sweep='up' then:

 ┃  ┃  ┃         ┃  ┃  ┃
─●──●──●─       ─●──●──●─
 ┃  ┃  ┃         ┃  ┃  ┃
─●──●──●─       ─●──o──●─  .
 ┃  ┃  ┃   ==>   ┃  |  ┃   .
─●──●──●─       ─●──^──●─  . xrange
 ┃  ┃  ┃         ┃  |  ┃   .
─●──●──●─       ─●──^──●─  .
 ┃  ┃  ┃         ┃  ┃  ┃
─●──●──●─       ─●──●──●─
 ┃  ┃  ┃         ┃  ┃  ┃
    .               .
    j               j

If sweep='down' then:

 ┃  ┃  ┃         ┃  ┃  ┃
─●──●──●─       ─●──●──●─
 ┃  ┃  ┃         ┃  ┃  ┃
─●──●──●─       ─●──v──●─ .
 ┃  ┃  ┃   ==>   ┃  |  ┃  .
─●──●──●─       ─●──v──●─ . xrange
 ┃  ┃  ┃         ┃  |  ┃  .
─●──●──●─       ─●──o──●─ .
 ┃  ┃  ┃         ┃  ┃  ┃
─●──●──●─       ─●──●──●─
 ┃  ┃  ┃         ┃  ┃  ┃
    .               .
    j               j

Does not yield an orthogonal form in the same way as in 1D.

Parameters:
  • j (int) – Which column to compress.

  • sweep ({'up', 'down'}) – Which direction to sweep in.

  • xrange (None or (int, int), optional) – The range of rows to compress.

  • max_bond (int, optional) – The maximum boundary dimension, AKA ‘chi’. The default of None means truncation is left purely to cutoff and is not recommended in 2D.

  • cutoff (float, optional) – Cut-off value to used to truncate singular values in the boundary contraction.

  • compress_opts (None or dict, optional) – Supplied to compress_between().

_contract_boundary_core_via_1d(xrange, yrange, from_which, max_bond, cutoff=1e-10, method='dm', layer_tags=None, **compress_opts)[source]
_contract_boundary_core(xrange, yrange, from_which, max_bond, cutoff=1e-10, canonize=True, layer_tags=None, compress_late=True, sweep_reverse=False, equalize_norms=False, compress_opts=None, canonize_opts=None)[source]
_contract_boundary_full_bond(xrange, yrange, from_which, max_bond, cutoff=0.0, method='eigh', renorm=False, optimize='auto-hq', opposite_envs=None, equalize_norms=False, contract_boundary_opts=None)[source]

Contract the boundary of this 2D TN using the ‘full bond’ environment information obtained from a boundary contraction in the opposite direction.

Parameters:
  • xrange ((int, int) or None, optional) – The range of rows to contract and compress.

  • yrange ((int, int)) – The range of columns to contract and compress.

  • from_which ({'xmin', 'ymin', 'xmax', 'ymax'}) – Which direction to contract the rectangular patch from.

  • max_bond (int) – The maximum boundary dimension, AKA ‘chi’. By default used for the opposite direction environment contraction as well.

  • cutoff (float, optional) – Cut-off value to used to truncate singular values in the boundary contraction - only for the opposite direction environment contraction.

  • method ({'eigh', 'eig', 'svd', 'biorthog'}, optional) – Which similarity decomposition method to use to compress the full bond environment.

  • renorm (bool, optional) – Whether to renormalize the isometric projection or not.

  • optimize (str or PathOptimize, optimize) – Contraction optimizer to use for the exact contractions.

  • opposite_envs (dict, optional) – If supplied, the opposite environments will be fetched or lazily computed into this dict depending on whether they are missing.

  • contract_boundary_opts – Other options given to the opposite direction environment contraction.

_contract_boundary_projector(xrange, yrange, from_which, max_bond=None, cutoff=1e-10, lazy=False, equalize_norms=False, optimize='auto-hq', compress_opts=None)[source]

Contract the boundary of this 2D tensor network by explicitly computing and inserting explicit local projector tensors, which can optionally be left uncontracted. Multilayer networks are naturally supported.

Parameters:
  • xrange (tuple) – The range of x indices to contract.

  • yrange (tuple) – The range of y indices to contract.

  • from_which ({'xmin', 'xmax', 'ymin', 'ymax'}) – From which boundary to contract.

  • max_bond (int, optional) – The maximum bond dimension to contract to. If None (default), compression is left to cutoff.

  • cutoff (float, optional) – The cutoff to use for boundary compression.

  • lazy (bool, optional) – Whether to leave the boundary tensors uncontracted. If False (the default), the boundary tensors are contracted and the resulting boundary has a single tensor per site.

  • equalize_norms (bool, optional) – Whether to actively absorb the norm of modified tensors into self.exponent.

  • optimize (str or PathOptimizer, optional) – The contract path optimization to use when forming the projector tensors.

  • compress_opts (dict, optional) – Other options to pass to svd_truncated().

contract_boundary_from(xrange, yrange, from_which, max_bond=None, *, cutoff=1e-10, canonize=True, mode='mps', layer_tags=None, sweep_reverse=False, compress_opts=None, inplace=False, **contract_boundary_opts)[source]

Unified entrypoint for contracting any rectangular patch of tensors from any direction, with any boundary method.

contract_boundary_from_[source]
contract_boundary_from_xmin(xrange, yrange=None, max_bond=None, *, cutoff=1e-10, canonize=True, mode='mps', layer_tags=None, sweep_reverse=False, compress_opts=None, inplace=False, **contract_boundary_opts)[source]

Contract a 2D tensor network inwards from the bottom, canonizing and compressing (left to right) along the way. If layer_tags is None this looks like:

a) contract

│  │  │  │  │
●──●──●──●──●       │  │  │  │  │
│  │  │  │  │  -->  ●══●══●══●══●
●──●──●──●──●

b) optionally canonicalize

│  │  │  │  │
●══●══<══<══<

c) compress in opposite direction

│  │  │  │  │  -->  │  │  │  │  │  -->  │  │  │  │  │
>──●══●══●══●  -->  >──>──●══●══●  -->  >──>──>──●══●
.  .           -->     .  .        -->        .  .

If layer_tags is specified, each then each layer is contracted in and compressed separately, resulting generally in a lower memory scaling. For two layer tags this looks like:

a) first flatten the outer boundary only

│ ││ ││ ││ ││ │       │ ││ ││ ││ ││ │
●─○●─○●─○●─○●─○       ●─○●─○●─○●─○●─○
│ ││ ││ ││ ││ │  ==>   ╲│ ╲│ ╲│ ╲│ ╲│
●─○●─○●─○●─○●─○         ●══●══●══●══●

b) contract and compress a single layer only

│ ││ ││ ││ ││ │
│ ○──○──○──○──○
│╱ │╱ │╱ │╱ │╱
●══<══<══<══<

c) contract and compress the next layer

╲│ ╲│ ╲│ ╲│ ╲│
 >══>══>══>══●
Parameters:
  • xrange ((int, int)) – The range of rows to compress (inclusive).

  • yrange ((int, int) or None, optional) – The range of columns to compress (inclusive), sweeping along with canonization and compression. Defaults to all columns.

  • max_bond (int, optional) – The maximum boundary dimension, AKA ‘chi’. The default of None means truncation is left purely to cutoff and is not recommended in 2D.

  • cutoff (float, optional) – Cut-off value to used to truncate singular values in the boundary contraction.

  • canonize (bool, optional) – Whether to sweep one way with canonization before compressing.

  • mode ({'mps', 'full-bond'}, optional) – How to perform the compression on the boundary.

  • layer_tags (None or sequence[str], optional) – If None, all tensors at each coordinate pair [(i, j), (i + 1, j)] will be first contracted. If specified, then the outer tensor at (i, j) will be contracted with the tensor specified by [(i + 1, j), layer_tag], for each layer_tag in layer_tags.

  • sweep_reverse (bool, optional) – Which way to perform the compression sweep, which has an effect on which tensors end up being canonized. Setting this to true sweeps the compression from largest to smallest coordinates.

  • compress_opts (None or dict, optional) – Supplied to compress_between().

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

contract_boundary_from_xmin_[source]
contract_boundary_from_xmax(xrange, yrange=None, max_bond=None, *, cutoff=1e-10, canonize=True, mode='mps', layer_tags=None, inplace=False, sweep_reverse=False, compress_opts=None, **contract_boundary_opts)[source]

Contract a 2D tensor network inwards from the top, canonizing and compressing (right to left) along the way. If layer_tags is None this looks like:

a) contract

●──●──●──●──●
|  |  |  |  |  -->  ●══●══●══●══●
●──●──●──●──●       |  |  |  |  |
|  |  |  |  |

b) optionally canonicalize

●══●══<══<══<
|  |  |  |  |

c) compress in opposite direction

>──●══●══●══●  -->  >──>──●══●══●  -->  >──>──>──●══●
|  |  |  |  |  -->  |  |  |  |  |  -->  |  |  |  |  |
.  .           -->     .  .        -->        .  .

If layer_tags is specified, each then each layer is contracted in and compressed separately, resulting generally in a lower memory scaling. For two layer tags this looks like:

a) first flatten the outer boundary only

●─○●─○●─○●─○●─○         ●══●══●══●══●
│ ││ ││ ││ ││ │  ==>   ╱│ ╱│ ╱│ ╱│ ╱│
●─○●─○●─○●─○●─○       ●─○●─○●─○●─○●─○
│ ││ ││ ││ ││ │       │ ││ ││ ││ ││ │

b) contract and compress a single layer only

●══<══<══<══<
│╲ │╲ │╲ │╲ │╲
│ ○──○──○──○──○
│ ││ ││ ││ ││ │

c) contract and compress the next layer

 ●══●══●══●══●
╱│ ╱│ ╱│ ╱│ ╱│
Parameters:
  • xrange ((int, int)) – The range of rows to compress (inclusive).

  • yrange ((int, int) or None, optional) – The range of columns to compress (inclusive), sweeping along with canonization and compression. Defaults to all columns.

  • max_bond (int, optional) – The maximum boundary dimension, AKA ‘chi’. The default of None means truncation is left purely to cutoff and is not recommended in 2D.

  • cutoff (float, optional) – Cut-off value to used to truncate singular values in the boundary contraction.

  • canonize (bool, optional) – Whether to sweep one way with canonization before compressing.

  • mode ({'mps', 'full-bond'}, optional) – How to perform the compression on the boundary.

  • layer_tags (None or str, optional) – If None, all tensors at each coordinate pair [(i, j), (i - 1, j)] will be first contracted. If specified, then the outer tensor at (i, j) will be contracted with the tensor specified by [(i - 1, j), layer_tag], for each layer_tag in layer_tags.

  • sweep_reverse (bool, optional) – Which way to perform the compression sweep, which has an effect on which tensors end up being canonized. Setting this to true sweeps the compression from largest to smallest coordinates.

  • compress_opts (None or dict, optional) – Supplied to compress_between().

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

contract_boundary_from_xmax_[source]
contract_boundary_from_ymin(yrange, xrange=None, max_bond=None, *, cutoff=1e-10, canonize=True, mode='mps', layer_tags=None, sweep_reverse=False, compress_opts=None, inplace=False, **contract_boundary_opts)[source]

Contract a 2D tensor network inwards from the left, canonizing and compressing (bottom to top) along the way. If layer_tags is None this looks like:

a) contract

●──●──       ●──
│  │         ║
●──●──  ==>  ●──
│  │         ║
●──●──       ●──

b) optionally canonicalize

●──       v──
║         ║
●──  ==>  v──
║         ║
●──       ●──

c) compress in opposite direction

v──       ●──
║         │
v──  ==>  ^──
║         │
●──       ^──

If layer_tags is specified, each then each layer is contracted in and compressed separately, resulting generally in a lower memory scaling. For two layer tags this looks like:

a) first flatten the outer boundary only

○──○──           ●──○──
│╲ │╲            │╲ │╲
●─○──○──         ╰─●──○──
 ╲│╲╲│╲     ==>    │╲╲│╲
  ●─○──○──         ╰─●──○──
   ╲│ ╲│             │ ╲│
    ●──●──           ╰──●──

b) contract and compress a single layer only

   ○──
 ╱╱ ╲
●─── ○──
 ╲ ╱╱ ╲
  ^─── ○──
   ╲ ╱╱
    ^─────

c) contract and compress the next layer

●──
│╲
╰─●──
  │╲
  ╰─●──
    │
    ╰──
Parameters:
  • yrange ((int, int)) – The range of columns to compress (inclusive).

  • xrange ((int, int) or None, optional) – The range of rows to compress (inclusive), sweeping along with canonization and compression. Defaults to all rows.

  • max_bond (int, optional) – The maximum boundary dimension, AKA ‘chi’. The default of None means truncation is left purely to cutoff and is not recommended in 2D.

  • cutoff (float, optional) – Cut-off value to used to truncate singular values in the boundary contraction.

  • canonize (bool, optional) – Whether to sweep one way with canonization before compressing.

  • mode ({'mps', 'full-bond'}, optional) – How to perform the compression on the boundary.

  • layer_tags (None or str, optional) – If None, all tensors at each coordinate pair [(i, j), (i, j + 1)] will be first contracted. If specified, then the outer tensor at (i, j) will be contracted with the tensor specified by [(i + 1, j), layer_tag], for each layer_tag in layer_tags.

  • sweep_reverse (bool, optional) – Which way to perform the compression sweep, which has an effect on which tensors end up being canonized. Setting this to true sweeps the compression from largest to smallest coordinates.

  • compress_opts (None or dict, optional) – Supplied to compress_between().

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

contract_boundary_from_ymin_[source]
contract_boundary_from_ymax(yrange, xrange=None, max_bond=None, *, cutoff=1e-10, canonize=True, mode='mps', layer_tags=None, sweep_reverse=False, compress_opts=None, inplace=False, **contract_boundary_opts)[source]

Contract a 2D tensor network inwards from the left, canonizing and compressing (top to bottom) along the way. If layer_tags is None this looks like:

a) contract

──●──●       ──●
  │  │         ║
──●──●  ==>  ──●
  │  │         ║
──●──●       ──●

b) optionally canonicalize

──●       ──v
  ║         ║
──●  ==>  ──v
  ║         ║
──●       ──●

c) compress in opposite direction

──v       ──●
  ║         │
──v  ==>  ──^
  ║         │
──●       ──^

If layer_tags is specified, each then each layer is contracted in and compressed separately, resulting generally in a lower memory scaling. For two layer tags this looks like:

a) first flatten the outer boundary only

    ──○──○           ──○──●
     ╱│ ╱│            ╱│ ╱│
  ──○──○─●         ──○──●─╯
   ╱│╱╱│╱   ==>     ╱│╱╱│
──○──○─●         ──○──●─╯
  │╱ │╱            │╱ │
──●──●           ──●──╯

b) contract and compress a single layer only

    ──○
     ╱ ╲╲
  ──○────v
   ╱ ╲╲ ╱
──○────v
   ╲╲ ╱
─────●

c) contract and compress the next layer

       ╲
    ────v
     ╲ ╱
  ────v
   ╲ ╱
────●
Parameters:
  • yrange ((int, int)) – The range of columns to compress (inclusive).

  • xrange ((int, int) or None, optional) – The range of rows to compress (inclusive), sweeping along with canonization and compression. Defaults to all rows.

  • max_bond (int, optional) – The maximum boundary dimension, AKA ‘chi’. The default of None means truncation is left purely to cutoff and is not recommended in 2D.

  • cutoff (float, optional) – Cut-off value to used to truncate singular values in the boundary contraction.

  • canonize (bool, optional) – Whether to sweep one way with canonization before compressing.

  • mode ({'mps', 'full-bond'}, optional) – How to perform the compression on the boundary.

  • layer_tags (None or str, optional) – If None, all tensors at each coordinate pair [(i, j), (i, j - 1)] will be first contracted. If specified, then the outer tensor at (i, j) will be contracted with the tensor specified by [(i + 1, j), layer_tag], for each layer_tag in layer_tags.

  • sweep_reverse (bool, optional) – Which way to perform the compression sweep, which has an effect on which tensors end up being canonized. Setting this to true sweeps the compression from largest to smallest coordinates.

  • compress_opts (None or dict, optional) – Supplied to compress_between().

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

contract_boundary_from_ymax_[source]
_contract_interleaved_boundary_sequence(*, contract_boundary_opts=None, sequence=None, xmin=None, xmax=None, ymin=None, ymax=None, max_separation=1, max_unfinished=1, around=None, equalize_norms=False, canonize=False, canonize_opts=None, final_contract=True, final_contract_opts=None, progbar=False, inplace=False)[source]

Unified handler for performing iterleaved contractions in a sequence of inwards boundary directions.

contract_boundary(max_bond=None, *, cutoff=1e-10, canonize=True, mode='mps', layer_tags=None, compress_opts=None, sequence=None, xmin=None, xmax=None, ymin=None, ymax=None, max_separation=1, max_unfinished=1, around=None, equalize_norms=False, final_contract=True, final_contract_opts=None, progbar=None, inplace=False, **contract_boundary_opts)[source]

Contract the boundary of this 2D tensor network inwards:

●──●──●──●       ●──●──●──●       ●──●──●
│  │  │  │       │  │  │  │       ║  │  │
●──●──●──●       ●──●──●──●       ^──●──●       >══>══●       >──v
│  │ij│  │  ==>  │  │ij│  │  ==>  ║ij│  │  ==>  │ij│  │  ==>  │ij║
●──●──●──●       ●══<══<══<       ^──<──<       ^──<──<       ^──<
│  │  │  │
●──●──●──●

Optionally from any or all of the boundary, in multiple layers, and stopping around a region. The default is to contract the boundary from the two shortest opposing sides.

Parameters:
  • around (None or sequence of (int, int), optional) – If given, don’t contract the square of sites bounding these coordinates.

  • max_bond (int, optional) – The maximum boundary dimension, AKA ‘chi’. The default of None means truncation is left purely to cutoff and is not recommended in 2D.

  • cutoff (float, optional) – Cut-off value to used to truncate singular values in the boundary contraction.

  • canonize (bool, optional) – Whether to sweep one way with canonization before compressing.

  • mode ({'mps', 'full-bond'}, optional) – How to perform the compression on the boundary.

  • layer_tags (None or sequence of str, optional) – If given, perform a multilayer contraction, contracting the inner sites in each layer into the boundary individually.

  • compress_opts (None or dict, optional) – Other low level options to pass to compress_between().

  • sequence (sequence of {'xmin', 'xmax', 'ymin', 'ymax'}, optional) – Which directions to cycle throught when performing the inwards contractions, i.e. from that direction. If around is specified you will likely need all of these! Default is to contract from the two shortest opposing sides.

  • xmin (int, optional) – The initial bottom boundary row, defaults to 0.

  • xmax (int, optional) – The initial top boundary row, defaults to Lx - 1.

  • ymin (int, optional) – The initial left boundary column, defaults to 0.

  • ymax (int, optional) – The initial right boundary column, defaults to Ly - 1..

  • max_separation (int, optional) – If around is None, when any two sides become this far apart simply contract the remaining tensor network.

  • max_unfinished (int, optional) – If around is None, when this many sides are still not within max_separation simply contract the remaining tensor network.

  • around – If given, don’t contract the square of sites bounding these coordinates.

  • equalize_norms (bool or float, optional) – Whether to equalize the norms of the boundary tensors after each contraction, gathering the overall scaling coefficient, log10, in tn.exponent.

  • final_contract (bool, optional) – Whether to exactly contract the remaining tensor network after the boundary contraction.

  • final_contract_opts (None or dict, optional) – Options to pass to contract(), optimize defaults to 'auto-hq'.

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

  • inplace (bool, optional) – Whether to perform the contraction in place or not.

  • contract_boundary_opts – Supplied to contract_boundary_from(), including compression and canonization options.

contract_boundary_[source]
contract_mps_sweep(max_bond=None, *, cutoff=1e-10, canonize=True, direction=None, **contract_boundary_opts)[source]

Contract this 2D tensor network by sweeping an MPS across from one side to the other.

Parameters:
  • max_bond (int, optional) – The maximum boundary dimension, AKA ‘chi’. The default of None means truncation is left purely to cutoff and is not recommended in 2D.

  • cutoff (float, optional) – Cut-off value to used to truncate singular values in the boundary contraction.

  • canonize (bool, optional) – Whether to sweep one way with canonization before compressing.

  • direction ({'xmin', 'xmax', 'ymin', 'ymax'}, optional) – Which direction to sweep from. If None (default) then the shortest boundary is chosen.

  • contract_boundary_opts – Supplied to contract_boundary_from(), including compression and canonization options.

contract_mps_sweep_[source]
contract_full_bootstrap(n, *, optimize='auto-hq', **kwargs)[source]
compute_environments(from_which, xrange=None, yrange=None, max_bond=None, *, cutoff=1e-10, canonize=True, mode='mps', layer_tags=None, dense=False, compress_opts=None, envs=None, **contract_boundary_opts)[source]

Compute the 1D boundary tensor networks describing the environments of rows and columns.

Parameters:
  • from_which ({'xmin', 'xmax', 'ymin', 'ymax'}) – Which boundary to compute the environments from.

  • xrange (tuple[int], optional) – The range of rows to compute the environments for.

  • yrange (tuple[int], optional) – The range of columns to compute the environments for.

  • max_bond (int, optional) – The maximum bond dimension of the environments.

  • cutoff (float, optional) – The cutoff for the singular values of the environments.

  • canonize (bool, optional) – Whether to canonicalize along each MPS environment before compressing.

  • mode ({'mps', 'projector', 'full-bond'}, optional) – Which contraction method to use for the environments.

  • layer_tags (str or iterable[str], optional) – If this 2D TN is multi-layered (e.g. a bra and a ket), and mode == 'mps', contract and compress each specified layer separately, for a cheaper contraction.

  • dense (bool, optional) – Whether to use dense tensors for the environments.

  • compress_opts (dict, optional) – Other options to pass to tensor_compress_bond().

  • envs (dict, optional) – An existing dictionary to store the environments in.

  • contract_boundary_opts – Other options to pass to contract_boundary_from().

Returns:

envs – A dictionary of the environments, with keys of the form (from_which, row_or_col_index).

Return type:

dict

compute_xmin_environments[source]

Compute the self.Lx 1D boundary tensor networks describing the lower environments of each row in this 2D tensor network. See compute_x_environments() for full details.

compute_xmax_environments[source]

Compute the self.Lx 1D boundary tensor networks describing the upper environments of each row in this 2D tensor network. See compute_x_environments() for full details.

compute_ymin_environments[source]

Compute the self.Ly 1D boundary tensor networks describing the left environments of each column in this 2D tensor network. See compute_y_environments() for full details.

compute_ymax_environments[source]

Compute the self.Ly 1D boundary tensor networks describing the right environments of each column in this 2D tensor network. See compute_y_environments() for full details.

compute_x_environments(max_bond=None, *, cutoff=1e-10, canonize=True, dense=False, mode='mps', layer_tags=None, compress_opts=None, envs=None, **contract_boundary_opts)[source]

Compute the 2 * self.Lx 1D boundary tensor networks describing the lower and upper environments of each row in this 2D tensor network, assumed to represent the norm.

The top or ‘xmax’ environment for row i will be a contraction of all rows i + 1, i + 2, ... etc:

 ●━━━●━━━●━━━●━━━●━━━●━━━●━━━●━━━●━━━●
╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲

The bottom or ‘xmin’ environment for row i will be a contraction of all rows i - 1, i - 2, ... etc:

╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱
 ●━━━●━━━●━━━●━━━●━━━●━━━●━━━●━━━●━━━●

Such that envs['xmax', i] & self.select(self.x_tag(i)) & envs['xmin', i] would look like:

 ●━━━●━━━●━━━●━━━●━━━●━━━●━━━●━━━●━━━●
╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲
o─o─o─o─o─o─o─o─o─o─o─o─o─o─o─o─o─o─o─o
╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱
 ●━━━●━━━●━━━●━━━●━━━●━━━●━━━●━━━●━━━●

And be (an approximation of) the norm centered around row i

Parameters:
  • max_bond (int, optional) – The maximum boundary dimension, AKA ‘chi’. The default of None means truncation is left purely to cutoff and is not recommended in 2D.

  • cutoff (float, optional) – Cut-off value to used to truncate singular values in the boundary contraction.

  • canonize (bool, optional) – Whether to sweep one way with canonization before compressing.

  • dense (bool, optional) – If true, contract the boundary in as a single dense tensor.

  • mode ({'mps', 'full-bond'}, optional) – How to perform the boundary compression.

  • layer_tags (None or sequence[str], optional) – If None, all tensors at each coordinate pair [(i, j), (i + 1, j)] will be first contracted. If specified, then the outer tensor at (i, j) will be contracted with the tensor specified by [(i + 1, j), layer_tag], for each layer_tag in layer_tags.

  • compress_opts (None or dict, optional) – Supplied to compress_between().

  • envs (dict, optional) – Supply an existing dictionary to store the environments in.

  • contract_boundary_opts – Supplied to contract_boundary_from_xmin() and contract_boundary_from_xmax() .

Returns:

x_envs – The two environment tensor networks of row i will be stored in x_envs['xmin', i] and x_envs['xmax', i].

Return type:

dict[(str, int), TensorNetwork]

compute_y_environments(max_bond=None, *, cutoff=1e-10, canonize=True, dense=False, mode='mps', layer_tags=None, compress_opts=None, envs=None, **contract_boundary_opts)[source]

Compute the 2 * self.Ly 1D boundary tensor networks describing the left (‘ymin’) and right (‘ymax’) environments of each column in this 2D tensor network, assumed to represent the norm.

The left or ‘ymin’ environment for column j will be a contraction of all columns j - 1, j - 2, ... etc:

●<
┃
●<
┃
●<
┃
●<

The right or ‘ymax’ environment for row j will be a contraction of all rows j + 1, j + 2, ... etc:

>●
 ┃
>●
 ┃
>●
 ┃
>●

Such that envs['ymin', j] & self.select(self.y_tag(j)) & envs['ymax', j] would look like:

   ╱o
●< o| >●
┃  |o  ┃
●< o| >●
┃  |o  ┃
●< o| >●
┃  |o  ┃
●< o╱ >●

And be (an approximation of) the norm centered around column j

Parameters:
  • max_bond (int, optional) – The maximum boundary dimension, AKA ‘chi’. The default of None means truncation is left purely to cutoff and is not recommended in 2D.

  • cutoff (float, optional) – Cut-off value to used to truncate singular values in the boundary contraction.

  • canonize (bool, optional) – Whether to sweep one way with canonization before compressing.

  • dense (bool, optional) – If true, contract the boundary in as a single dense tensor.

  • mode ({'mps', 'full-bond'}, optional) – How to perform the boundary compression.

  • layer_tags (None or sequence[str], optional) – If None, all tensors at each coordinate pair [(i, j), (i + 1, j)] will be first contracted. If specified, then the outer tensor at (i, j) will be contracted with the tensor specified by [(i + 1, j), layer_tag], for each layer_tag in layer_tags.

  • compress_opts (None or dict, optional) – Supplied to compress_between().

  • contract_boundary_opts – Supplied to contract_boundary_from_ymin() and contract_boundary_from_ymax() .

Returns:

y_envs – The two environment tensor networks of column j will be stored in y_envs['ymin', j] and y_envs['ymax', j].

Return type:

dict[(str, int), TensorNetwork]

_compute_plaquette_environments_x_first(x_bsz, y_bsz, max_bond=None, cutoff=1e-10, canonize=True, layer_tags=None, second_dense=None, x_envs=None, **compute_environment_opts)[source]
_compute_plaquette_environments_y_first(x_bsz, y_bsz, max_bond=None, cutoff=1e-10, canonize=True, layer_tags=None, second_dense=None, y_envs=None, **compute_environment_opts)[source]
compute_plaquette_environments(x_bsz=2, y_bsz=2, max_bond=None, *, cutoff=1e-10, canonize=True, mode='mps', layer_tags=None, first_contract=None, second_dense=None, compress_opts=None, **compute_environment_opts)[source]

Compute all environments like:

second_dense=False   second_dense=True (& first_contract='columns')

  ●──●                  ╭───●───╮
 ╱│  │╲                 │  ╱ ╲  │
●─.  .─●    ┬           ●─ . . ─●    ┬
│      │    ┊ x_bsz     │       │    ┊ x_bsz
●─.  .─●    ┴           ●─ . . ─●    ┴
 ╲│  │╱                 │  ╲ ╱  │
  ●──●                  ╰───●───╯

  <-->                    <->
 y_bsz                   y_bsz

Use two boundary contractions sweeps.

Parameters:
  • x_bsz (int, optional) – The size of the plaquettes in the x-direction (number of rows).

  • y_bsz (int, optional) – The size of the plaquettes in the y-direction (number of columns).

  • max_bond (int, optional) – The maximum boundary dimension, AKA ‘chi’. The default of None means truncation is left purely to cutoff and is not recommended in 2D.

  • cutoff (float, optional) – Cut-off value to used to truncate singular values in the boundary contraction.

  • canonize (bool, optional) – Whether to sweep one way with canonization before compressing.

  • mode ({'mps', 'full-bond'}, optional) – How to perform the boundary compression.

  • layer_tags (None or sequence[str], optional) – If None, all tensors at each coordinate pair [(i, j), (i + 1, j)] will be first contracted. If specified, then the outer tensor at (i, j) will be contracted with the tensor specified by [(i + 1, j), layer_tag], for each layer_tag in layer_tags.

  • first_contract ({None, 'x', 'y'}, optional) – The environments can either be generated with initial sweeps in the row (‘x’) or column (‘y’) direction. Generally it makes sense to perform this approximate step in whichever is smaller (the default).

  • second_dense (None or bool, optional) – Whether to perform the second set of contraction sweeps (in the rotated direction from whichever first_contract is) using a dense tensor or boundary method. By default this is only turned on if the bsz in the corresponding direction is 1.

  • compress_opts (None or dict, optional) – Supplied to compress_between().

  • compute_environment_opts – Supplied to compute_y_environments() or compute_x_environments() .

Returns:

The plaquette environments. The key is two tuples of ints, the startings coordinate of the plaquette being the first and the size of the plaquette being the second pair.

Return type:

dict[((int, int), (int, int)), TensorNetwork]

coarse_grain_hotrg(direction, max_bond=None, cutoff=1e-10, lazy=False, equalize_norms=False, optimize='auto-hq', compress_opts=None, inplace=False)[source]

Coarse grain this tensor network in direction using HOTRG. This inserts oblique projectors between tensor pairs and then optionally contracts them into new sites for form a lattice half the size.

Parameters:
  • direction ({'x', 'y'}) – The direction to coarse grain in.

  • max_bond (int, optional) – The maximum bond dimension of the projector pairs inserted.

  • cutoff (float, optional) – The cutoff for the singular values of the projector pairs.

  • lazy (bool, optional) – Whether to contract the coarse graining projectors or leave them in the tensor network lazily. Default is to contract them.

  • equalize_norms (bool, optional) – Whether to equalize the norms of the tensors in the coarse grained lattice.

  • optimize (str, optional) – The optimization method to use when contracting the coarse grained lattice, if lazy=False.

  • compress_opts (None or dict, optional) – Supplied to insert_compressor_between_regions().

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

Returns:

The coarse grained tensor network, with size halved in direction.

Return type:

TensorNetwork2D

coarse_grain_hotrg_[source]
contract_hotrg(max_bond=None, *, cutoff=1e-10, canonize=False, canonize_opts=None, sequence=('x', 'y'), max_separation=1, max_unfinished=1, lazy=False, equalize_norms=False, final_contract=True, final_contract_opts=None, progbar=False, inplace=False, **coarse_grain_opts)[source]

Contract this tensor network using the finite version of HOTRG. See https://arxiv.org/abs/1201.1144v4 and https://arxiv.org/abs/1905.02351 for the more optimal computaton of the projectors used here. The TN is contracted sequentially in sequence directions by inserting oblique projectors between plaquettes, and then optionally contracting these new effective sites. The algorithm stops when only one direction has a length larger than 2, and thus exact contraction can be used.

Parameters:
  • max_bond (int, optional) – The maximum bond dimension of the projector pairs inserted.

  • cutoff (float, optional) – The cutoff for the singular values of the projector pairs.

  • canonize (bool, optional) – Whether to canonize all tensors before each contraction, via gauge_all().

  • canonize_opts (None or dict, optional) – Additional options to pass to gauge_all().

  • sequence (tuple of str, optional) – The directions to contract in. Default is to contract in all directions.

  • max_separation (int, optional) – The maximum distance between sides (i.e. length - 1) of the tensor network before that direction is considered finished.

  • max_unfinished (int, optional) – The maximum number of directions that can be unfinished (i.e. are still longer than max_separation + 1) before the coarse graining terminates.

  • lazy (bool, optional) – Whether to contract the coarse graining projectors or leave them in the tensor network lazily. Default is to contract them.

  • equalize_norms (bool or float, optional) – Whether to equalize the norms of all tensors after each contraction, gathering the overall scaling coefficient, log10, in tn.exponent.

  • final_contract (bool, optional) – Whether to exactly contract the remaining tensor network after the coarse graining contractions.

  • final_contract_opts (None or dict, optional) – Options to pass to contract(), optimize defaults to 'auto-hq'.

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

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

  • coarse_grain_opts – Additional options to pass to coarse_grain_hotrg().

Returns:

The contracted tensor network, which will have no more than one direction of length > 2.

Return type:

TensorNetwork2D

contract_hotrg_[source]
contract_ctmrg(max_bond=None, *, cutoff=1e-10, canonize=False, canonize_opts=None, lazy=False, mode='projector', compress_opts=None, sequence=None, xmin=None, xmax=None, ymin=None, ymax=None, max_separation=1, around=None, equalize_norms=False, final_contract=True, final_contract_opts=None, progbar=False, inplace=False, **contract_boundary_opts)[source]

Contract this 2D tensor network using the finite analog of the CTMRG algorithm - https://arxiv.org/abs/cond-mat/9507087. The TN is contracted sequentially in sequence directions by inserting oblique projectors between boundary pairs, and then optionally contracting these new effective sites. The algorithm stops when only one direction has a length larger than 2, and thus exact contraction can be used.

Parameters:
  • max_bond (int, optional) – The maximum bond dimension of the projector pairs inserted.

  • cutoff (float, optional) – The cutoff for the singular values of the projector pairs.

  • canonize (bool, optional) – Whether to canonize the boundary tensors before each contraction, via gauge_all().

  • canonize_opts (None or dict, optional) – Additional options to pass to gauge_all().

  • lazy (bool, optional) – Whether to contract the coarse graining projectors or leave them in the tensor network lazily. Default is to contract them.

  • mode (str, optional) – The method to perform the boundary contraction. Defaults to 'projector'.

  • compress_opts (None or dict, optional) – Other low level options to pass to insert_compressor_between_regions().

  • sequence (sequence of {'xmin', 'xmax', 'ymin', 'ymax'}, optional) – Which directions to cycle throught when performing the inwards contractions, i.e. from that direction. If around is specified you will likely need all of these! Default is to contract in all directions.

  • xmin (int, optional) – The initial bottom boundary row, defaults to 0.

  • xmax (int, optional) – The initial top boundary row, defaults to Lx - 1.

  • ymin (int, optional) – The initial left boundary column, defaults to 0.

  • ymax (int, optional) – The initial right boundary column, defaults to Ly - 1..

  • max_separation (int, optional) – If around is None, when any two sides become this far apart simply contract the remaining tensor network.

  • around (None or sequence of (int, int), optional) – If given, don’t contract the square of sites bounding these coordinates.

  • equalize_norms (bool or float, optional) – Whether to equalize the norms of the boundary tensors after each contraction, gathering the overall scaling coefficient, log10, in tn.exponent.

  • final_contract (bool, optional) – Whether to exactly contract the remaining tensor network after the boundary contraction.

  • final_contract_opts (None or dict, optional) – Options to pass to contract(), optimize defaults to 'auto-hq'.

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

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

  • contract_boundary_opts – Additional options to pass to contract_boundary_from().

Returns:

Either the fully contracted scalar (if final_contract=True and around=None) or the partially contracted tensor network.

Return type:

scalar or TensorNetwork2D

contract_ctmrg_[source]
quimb.tensor.tensor_builder.gen_2d_bonds(Lx, Ly, steppers=None, coo_filter=None, cyclic=False)[source]

Convenience function for tiling pairs of bond coordinates on a 2D lattice given a function like lambda i, j: (i + 1, j + 1).

Parameters:
  • Lx (int) – The number of rows.

  • Ly (int) – The number of columns.

  • steppers (callable or sequence of callable, optional) – Function(s) that take args (i, j) and generate another coordinate, thus defining a bond. Only valid steps are taken. If not given, defaults to nearest neighbor bonds.

  • coo_filter (callable) – Function that takes args (i, j) and only returns True if this is to be a valid starting coordinate.

Yields:

bond (tuple[tuple[int, int], tuple[int, int]]) – A pair of coordinates.

Examples

Generate nearest neighbor bonds:

>>> for bond in gen_2d_bonds(2, 2, [lambda i, j: (i, j + 1),
>>>                                 lambda i, j: (i + 1, j)]):
>>>     print(bond)
((0, 0), (0, 1))
((0, 0), (1, 0))
((0, 1), (1, 1))
((1, 0), (1, 1))

Generate next nearest neighbor digonal bonds:

>>> for bond in gen_2d_bonds(2, 2, [lambda i, j: (i + 1, j + 1),
>>>                                 lambda i, j: (i + 1, j - 1)]):
>>>     print(bond)
((0, 0), (1, 1))
((0, 1), (1, 0))
quimb.tensor.tensor_builder.gen_2d_plaquettes(Lx, Ly, tiling)[source]

Generate a tiling of plaquettes in a square 2D lattice.

Parameters:
  • Lx (int) – The length of the lattice in the x direction.

  • Ly (int) – The length of the lattice in the y direction.

  • tiling ({'1', '2', 'full'}) –

    The tiling to use:

    • ’1’: plaquettes in a checkerboard pattern, such that each edge

      is covered by a maximum of one plaquette.

    • ’2’ or ‘full’: dense tiling of plaquettes. All bulk edges will

      be covered twice.

Yields:

plaquette (tuple[tuple[int]]) – The coordinates of the sites in each plaquette, including the last site which will be the same as the first.

class quimb.tensor.tensor_builder.LocalHam2D(Lx, Ly, H2, H1=None, cyclic=False)[source]

Bases: quimb.tensor.tensor_arbgeom_tebd.LocalHamGen

A 2D Hamiltonian represented as local terms. This combines all two site and one site terms into a single interaction per lattice pair, and caches operations on the terms such as getting their exponential.

Parameters:
  • Lx (int) – The number of rows.

  • Ly (int) – The number of columns.

  • H2 (array_like or dict[tuple[tuple[int]], array_like]) – The two site term(s). If a single array is given, assume to be the default interaction for all nearest neighbours. If a dict is supplied, the keys should represent specific pairs of coordinates like ((ia, ja), (ib, jb)) with the values the array representing the interaction for that pair. A default term for all remaining nearest neighbours interactions can still be supplied with the key None.

  • H1 (array_like or dict[tuple[int], array_like], optional) – The one site term(s). If a single array is given, assume to be the default onsite term for all terms. If a dict is supplied, the keys should represent specific coordinates like (i, j) with the values the array representing the local term for that site. A default term for all remaining sites can still be supplied with the key None.

terms

The total effective local term for each interaction (with single site terms appropriately absorbed). Each key is a pair of coordinates ija, ijb with ija < ijb.

Type:

dict[tuple[tuple[int]], array_like]

property nsites
The number of sites in the system.
__repr__()[source]

Return repr(self).

draw(ordering='sort', show_norm=True, figsize=None, fontsize=8, legend=True, ax=None, **kwargs)[source]

Plot this Hamiltonian as a network.

Parameters:
  • ordering ({'sort', None, 'random'}, optional) – An ordering of the termns, or an argument to be supplied to quimb.tensor.tensor_2d_tebd.LocalHam2D.get_auto_ordering() to generate this automatically.

  • show_norm (bool, optional) – Show the norm of each term as edge labels.

  • figsize (None or tuple[int], optional) – Size of the figure, defaults to size of Hamiltonian.

  • fontsize (int, optional) – Font size for norm labels.

  • legend (bool, optional) – Whether to show the legend of which terms are in which group.

  • ax (None or matplotlib.Axes, optional) – Add to a existing set of axes.

graph[source]
class quimb.tensor.tensor_builder.TensorNetwork3D(ts=(), *, virtual=False, check_collisions=True)[source]

Bases: quimb.tensor.tensor_arbgeom.TensorNetworkGen

Mixin class for tensor networks with a cubic lattice three-dimensional structure.

_NDIMS = 3
_EXTRA_PROPS = ('_site_tag_id', '_x_tag_id', '_y_tag_id', '_z_tag_id', '_Lx', '_Ly', '_Lz')
_compatible_3d(other)[source]

Check whether self and other are compatible 3D tensor networks such that they can remain a 3D 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 TensorNetwork3D instance.

Parameters:
  • other (TensorNetwork3D 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:

TensorNetwork3D or TensorNetwork

property Lx
The number of x-slices.
property Ly
The number of y-slices.
property Lz
The number of z-slices.
property nsites
The total number of sites.
site_tag(i, j=None, k=None)[source]

The name of the tag specifiying the tensor at site (i, j, k).

property x_tag_id
The string specifier for tagging each x-slice of this 3D TN.
x_tag(i)[source]
property x_tags
A tuple of all of the ``Lx`` different x-slice tags.
property y_tag_id
The string specifier for tagging each y-slice of this 3D TN.
y_tag(j)[source]
property y_tags
A tuple of all of the ``Ly`` different y-slice tags.
property z_tag_id
The string specifier for tagging each z-slice of this 3D TN.
z_tag(k)[source]
property z_tags
A tuple of all of the ``Lz`` different z-slice tags.
maybe_convert_coo(coo)[source]

Check if coo is a tuple of three ints and convert to the corresponding site tag if so.

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

This is the function that lets coordinates such as (i, j, k) be used for many ‘tag’ based functions.

gen_site_coos()[source]

Generate coordinates for all the sites in this 3D TN.

gen_bond_coos()[source]

Generate pairs of coordinates for all the bonds in this 3D TN.

valid_coo(coo, xrange=None, yrange=None, zrange=None)[source]

Check whether coo is in-bounds.

Parameters:
  • coo ((int, int, int), optional) – The coordinates to check.

  • xrange ((int, int), optional) – The range of allowed values for the x, y, and z coordinates.

  • yrange ((int, int), optional) – The range of allowed values for the x, y, and z coordinates.

  • zrange ((int, int), optional) – The range of allowed values for the x, y, and z coordinates.

Return type:

bool

get_ranges_present()[source]

Return the range of site coordinates present in this TN.

Returns:

xrange, yrange, zrange – The minimum and maximum site coordinates present in each direction.

Return type:

tuple[tuple[int, int]]

Examples

>>> tn = qtn.TN3D_rand(4, 4, 4, 2)
>>> tn_sub = tn.select_local('I1,2,3', max_distance=1)
>>> tn_sub.get_ranges_present()
((0, 2), (1, 3), (2, 3))
is_cyclic_x(j=None, k=None, imin=None, imax=None)[source]

Check if the x dimension is cyclic (periodic), specifically whether a bond exists between (imin, j, k) and (imax, j, k), with default values of imin = 0 and imax = Lx - 1, and j and k the center of the lattice. If imin and imax are adjacent then this is considered False, since there is no ‘extra’ connectivity.

is_cyclic_y(k=None, i=None, jmin=None, jmax=None)[source]

Check if the y dimension is cyclic (periodic), specifically whether a bond exists between (i, jmin, k) and (i, jmax, k), with default values of jmin = 0 and jmax = Ly - 1, and i and k the center of the lattice. If jmin and jmax are adjacent then this is considered False, since there is no ‘extra’ connectivity.

is_cyclic_z(i=None, j=None, kmin=None, kmax=None)[source]

Check if the z dimension is cyclic (periodic), specifically whether a bond exists between (i, j, kmin) and (i, j, kmax), with default values of kmin = 0 and kmax = Lz - 1, and i and j the center of the lattice. If kmin and kmax are adjacent then this is considered False, since there is no ‘extra’ connectivity.

__getitem__(key)[source]

Key based tensor selection, checking for integer based shortcut.

_repr_info()[source]

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

flatten(fuse_multibonds=True, inplace=False)[source]

Contract all tensors corresponding to each site into one.

flatten_[source]
gen_pairs(xrange=None, yrange=None, zrange=None, xreverse=False, yreverse=False, zreverse=False, coordinate_order='xyz', xstep=None, ystep=None, zstep=None, stepping_order='xyz', step_only=None)[source]

Helper function for generating pairs of cooordinates for all bonds within a certain range, optionally specifying an order.

Parameters:
  • xrange ((int, int), optional) – The range of allowed values for the x, y, and z coordinates.

  • yrange ((int, int), optional) – The range of allowed values for the x, y, and z coordinates.

  • zrange ((int, int), optional) – The range of allowed values for the x, y, and z coordinates.

  • xreverse (bool, optional) – Whether to reverse the order of the x, y, and z sweeps.

  • yreverse (bool, optional) – Whether to reverse the order of the x, y, and z sweeps.

  • zreverse (bool, optional) – Whether to reverse the order of the x, y, and z sweeps.

  • coordinate_order (str, optional) – The order in which to sweep the x, y, and z coordinates. Earlier dimensions will change slower. If the corresponding range has size 1 then that dimension doesn’t need to be specified.

  • xstep (int, optional) – When generating a bond, step in this direction to yield the neighboring coordinate. By default, these follow xreverse, yreverse, and zreverse respectively.

  • ystep (int, optional) – When generating a bond, step in this direction to yield the neighboring coordinate. By default, these follow xreverse, yreverse, and zreverse respectively.

  • zstep (int, optional) – When generating a bond, step in this direction to yield the neighboring coordinate. By default, these follow xreverse, yreverse, and zreverse respectively.

  • stepping_order (str, optional) – The order in which to step the x, y, and z coordinates to generate bonds. Does not need to include all dimensions.

  • step_only (int, optional) – Only perform the ith steps in stepping_order, used to interleave canonizing and compressing for example.

Yields:

coo_a, coo_b (((int, int, int), (int, int, int)))

canonize_plane(xrange, yrange, zrange, equalize_norms=False, canonize_opts=None, **gen_pair_opts)[source]

Canonize every pair of tensors within a subrange, optionally specifying a order to visit those pairs in.

compress_plane(xrange, yrange, zrange, max_bond=None, cutoff=1e-10, equalize_norms=False, compress_opts=None, **gen_pair_opts)[source]

Compress every pair of tensors within a subrange, optionally specifying a order to visit those pairs in.

_contract_boundary_core_via_2d(xrange, yrange, zrange, from_which, max_bond, cutoff=1e-10, method='local-early', layer_tags=None, **compress_opts)[source]
_contract_boundary_core(xrange, yrange, zrange, from_which, max_bond, cutoff=1e-10, canonize=True, canonize_interleave=True, layer_tags=None, compress_late=True, equalize_norms=False, compress_opts=None, canonize_opts=None)[source]
_contract_boundary_projector(xrange, yrange, zrange, from_which, max_bond=None, cutoff=1e-10, canonize=False, layer_tags=None, lazy=False, equalize_norms=False, optimize='auto-hq', compress_opts=None, canonize_opts=None)[source]
contract_boundary_from(xrange, yrange, zrange, from_which, max_bond=None, *, cutoff=1e-10, mode='peps', equalize_norms=False, compress_opts=None, canonize_opts=None, inplace=False, **contract_boundary_opts)[source]

Unified entrypoint for contracting any rectangular patch of tensors from any direction, with any boundary method.

contract_boundary_from_[source]
_contract_interleaved_boundary_sequence(*, contract_boundary_opts=None, sequence=None, xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None, max_separation=1, max_unfinished=1, around=None, equalize_norms=False, canonize=False, canonize_opts=None, final_contract=True, final_contract_opts=None, optimize='auto-hq', progbar=False, inplace=False)[source]

Unified handler for performing iterleaved contractions in a sequence of inwards boundary directions.

contract_boundary(max_bond=None, *, cutoff=1e-10, mode='peps', canonize=True, compress_opts=None, sequence=None, xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None, max_separation=1, max_unfinished=1, around=None, equalize_norms=False, final_contract=True, final_contract_opts=None, optimize='auto-hq', progbar=False, inplace=False, **contract_boundary_opts)[source]
contract_boundary_[source]
contract_ctmrg(max_bond=None, *, cutoff=1e-10, canonize=False, canonize_opts=None, lazy=False, mode='projector', compress_opts=None, sequence=None, xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None, max_separation=1, max_unfinished=1, around=None, equalize_norms=False, final_contract=True, final_contract_opts=None, progbar=False, inplace=False, **contract_boundary_opts)[source]
contract_ctmrg_[source]
_compute_plane_envs(xrange, yrange, zrange, from_which, envs=None, storage_factory=None, **contract_boundary_opts)[source]

Compute all ‘plane’ environments for the cube given by xrange, yrange, zrange, with direction given by from_which.

_maybe_compute_cell_env(key, envs=None, storage_factory=None, boundary_order=None, **contract_boundary_opts)[source]

Recursively compute the necessary 2D, 1D, and 0D environments.

coarse_grain_hotrg(direction, max_bond=None, cutoff=1e-10, lazy=False, equalize_norms=False, optimize='auto-hq', compress_opts=None, inplace=False)[source]

Coarse grain this tensor network in direction using HOTRG. This inserts oblique projectors between tensor pairs and then optionally contracts them into new sites for form a lattice half the size.

Parameters:
  • direction ({'x', 'y', 'z'}) – The direction to coarse grain in.

  • max_bond (int, optional) – The maximum bond dimension of the projector pairs inserted.

  • cutoff (float, optional) – The cutoff for the singular values of the projector pairs.

  • lazy (bool, optional) – Whether to contract the coarse graining projectors or leave them in the tensor network lazily. Default is to contract them.

  • equalize_norms (bool, optional) – Whether to equalize the norms of the tensors in the coarse grained lattice.

  • optimize (str, optional) – The optimization method to use when contracting the coarse grained lattice, if lazy=False.

  • compress_opts (None or dict, optional) – Supplied to insert_compressor_between_regions().

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

Returns:

The coarse grained tensor network, with size halved in direction.

Return type:

TensorNetwork2D

See also

contract_hotrg, insert_compressor_between_regions

coarse_grain_hotrg_[source]
contract_hotrg(max_bond=None, cutoff=1e-10, canonize=False, canonize_opts=None, sequence=('x', 'y', 'z'), max_separation=1, max_unfinished=1, lazy=False, equalize_norms=False, final_contract=True, final_contract_opts=None, progbar=False, inplace=False, **coarse_grain_opts)[source]

Contract this tensor network using the finite version of HOTRG. See https://arxiv.org/abs/1201.1144v4 and https://arxiv.org/abs/1905.02351 for the more optimal computaton of the projectors used here. The TN is contracted sequentially in sequence directions by inserting oblique projectors between tensor pairs, and then optionally contracting these new effective sites. The algorithm stops when only one direction has a length larger than 2, and thus exact contraction can be used.

Parameters:
  • max_bond (int, optional) – The maximum bond dimension of the projector pairs inserted.

  • cutoff (float, optional) – The cutoff for the singular values of the projector pairs.

  • sequence (tuple of str, optional) – The directions to contract in. Default is to contract in all directions.

  • max_separation (int, optional) – The maximum distance between sides (i.e. length - 1) of the tensor network before that direction is considered finished.

  • max_unfinished (int, optional) – The maximum number of directions that can be unfinished (i.e. are still longer than max_separation + 1) before the coarse graining terminates.

  • lazy (bool, optional) – Whether to contract the coarse graining projectors or leave them in the tensor network lazily. Default is to contract them.

  • equalize_norms (bool or float, optional) – Whether to equalize the norms of the tensors in the tensor network after each coarse graining step.

  • final_contract (bool, optional) – Whether to exactly contract the remaining tensor network after the coarse graining contractions.

  • final_contract_opts (None or dict, optional) – Options to pass to contract(), optimize defaults to 'auto-hq'.

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

  • coarse_grain_opts – Additional options to pass to coarse_grain_hotrg().

Returns:

The contracted tensor network, which will have no more than one directino of length > 2.

Return type:

TensorNetwork3D

See also

coarse_grain_hotrg, insert_compressor_between_regions

contract_hotrg_[source]
quimb.tensor.tensor_builder.gen_3d_bonds(Lx, Ly, Lz, steppers=None, coo_filter=None, cyclic=False)[source]

Convenience function for tiling pairs of bond coordinates on a 3D lattice given a function like lambda i, j, k: (i + 1, j + 1, k + 1).

Parameters:
  • Lx (int) – The number of x-slices.

  • Ly (int) – The number of y-slices.

  • Lz (int) – The number of z-slices.

  • steppers (callable or sequence of callable) – Function(s) that take args (i, j, k) and generate another coordinate, thus defining a bond. Only valid steps are taken. If not given, defaults to nearest neighbor bonds.

  • coo_filter (callable) – Function that takes args (i, j, k) and only returns True if this is to be a valid starting coordinate.

Yields:

bond (tuple[tuple[int, int, int], tuple[int, int, int]]) – A pair of coordinates.

Examples

Generate nearest neighbor bonds:

>>> for bond in gen_3d_bonds(2, 2, 2, [lambda i, j, k: (i + 1, j, k),
...                                    lambda i, j, k: (i, j + 1, k),
...                                    lambda i, j, k: (i, j, k + 1)]):
...     print(bond)
((0, 0, 0), (1, 0, 0))
((0, 0, 0), (0, 1, 0))
((0, 0, 0), (0, 0, 1))
((0, 0, 1), (1, 0, 1))
((0, 0, 1), (0, 1, 1))
((0, 1, 0), (1, 1, 0))
((0, 1, 0), (0, 1, 1))
((0, 1, 1), (1, 1, 1))
((1, 0, 0), (1, 1, 0))
((1, 0, 0), (1, 0, 1))
((1, 0, 1), (1, 1, 1))
((1, 1, 0), (1, 1, 1))
quimb.tensor.tensor_builder.gen_3d_plaquettes(Lx, Ly, Lz, tiling='1')[source]

Generate a tiling of plaquettes in a cubic 3D lattice.

Parameters:
  • Lx (int) – The length of the lattice in the x direction.

  • Ly (int) – The length of the lattice in the y direction.

  • Lz (int) – The length of the lattice in the z direction.

  • tiling ({'1', '2', '4', 'full'}) –

    The tiling to use:

    • ’1’: plaquettes in a sparse checkerboard pattern, such that each edge

      is covered by a maximum of one plaquette.

    • ’2’: less sparse checkerboard pattern, such that each edge is

      covered by a maximum of two plaquettes.

    • ’4’ or ‘full’: dense tiling of plaquettes. All bulk edges will

      be covered four times.

Yields:

plaquette (tuple[tuple[int]]) – The coordinates of the sites in each plaquette, including the last site which will be the same as the first.

class quimb.tensor.tensor_builder.LocalHam3D(Lx, Ly, Lz, H2, H1=None, cyclic=False)[source]

Bases: quimb.tensor.tensor_arbgeom_tebd.LocalHamGen

Representation of a local hamiltonian defined on a general graph. This combines all two site and one site terms into a single interaction per lattice pair, and caches operations on the terms such as getting their exponential. The sites (nodes) should be hashable and comparable.

Parameters:
  • H2 (dict[tuple[node], array_like]) – The interaction terms, with each key being an tuple of nodes defining an edge and each value the local hamilotonian term for those two nodes.

  • H1 (array_like or dict[node, array_like], optional) – The one site term(s). If a single array is given, assume to be the default onsite term for all terms. If a dict is supplied, the keys should represent specific coordinates like (i, j) with the values the array representing the local term for that site. A default term for all remaining sites can still be supplied with the key None.

terms

The total effective local term for each interaction (with single site terms appropriately absorbed). Each key is a pair of coordinates site_a, site_b with site_a < site_b.

Type:

dict[tuple, array_like]

property nsites
The number of sites in the system.
__repr__()[source]

Return repr(self).

quimb.tensor.tensor_builder.create_lazy_edge_map(tn, site_tags=None)[source]

Given a tensor network, where each tensor is in exactly one group or ‘site’, compute which sites are connected to each other, without checking each pair.

Parameters:
  • tn (TensorNetwork) – The tensor network to analyze.

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

Returns:

  • edges (dict[tuple[str, str], list[str]]) – Each key is a sorted pair of tags, which are connected, and the value is a list of the indices connecting them.

  • neighbors (dict[str, list[str]]) – For each site tag, the other site tags it is connected to.

class quimb.tensor.tensor_builder.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_builder.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_builder.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

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_builder.COPY_tensor(d, inds, tags=None, dtype=float)[source]

Get the tensor representing the COPY operation with dimension size d and number of dimensions len(inds), with exterior indices inds.

Parameters:
  • d (int) – The size of each dimension.

  • inds (sequence of str) – The exterior index names for each dimension.

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

  • dtype (str, optional) – Data type to create the underlying numpy array with.

Returns:

The tensor describing the MPS, of size d**len(inds).

Return type:

Tensor

class quimb.tensor.tensor_builder.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=())
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).

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

Bases: object

A collection of (as yet uncontracted) Tensors.

Parameters:
  • ts (sequence of Tensor or TensorNetwork) – The objects to combine. The new network will copy these (but not the underlying data) by default. For a view set virtual=True.

  • virtual (bool, optional) – Whether the TensorNetwork should be a view onto the tensors it is given, or a copy of them. E.g. if a virtual TN is constructed, any changes to a Tensor’s indices or tags will propagate to all TNs viewing that Tensor.

  • check_collisions (bool, optional) – If True, the default, then TensorNetwork instances with double indices which match another TensorNetwork instances double indices will have those indices’ names mangled. Can be explicitly turned off when it is known that no collisions will take place – i.e. when not adding any new tensors.

tensor_map

Mapping of unique ids to tensors, like``{tensor_id: tensor, …}``. I.e. this is where the tensors are ‘stored’ by the network.

Type:

dict

tag_map

Mapping of tags to a set of tensor ids which have those tags. I.e. {tag: {tensor_id_1, tensor_id_2, ...}}. Thus to select those tensors could do: map(tensor_map.__getitem__, tag_map[tag]).

Type:

dict

ind_map

Like tag_map but for indices. So ind_map[ind]] returns the tensor ids of those tensors with ind.

Type:

dict

exponent

A scalar prefactor for the tensor network, stored in base 10 like 10**exponent. This is mostly for conditioning purposes and will be 0.0 unless you use use equalize_norms(value) or tn.strip_exponent(tid_or_tensor).

Type:

float

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

Combine this tensor network with another, returning a new tensor network. This can be overriden by subclasses to check for a compatible structured type.

Parameters:
  • other (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:

TensorNetwork

__and__(other)[source]

Combine this tensor network with more tensors, without contracting. Copies the tensors.

__or__(other)[source]

Combine this tensor network with more tensors, without contracting. Views the constituent tensors.

_update_properties(cls, like=None, current=None, **kwargs)[source]
classmethod new(like=None, **kwargs)[source]

Create a new tensor network, without any tensors, of type cls, with all the requisite properties specified by kwargs or inherited from like.

classmethod from_TN(tn, like=None, inplace=False, **kwargs)[source]

Construct a specific tensor network subclass (i.e. one with some promise about structure/geometry and tags/inds such as an MPS) from a generic tensor network which should have that structure already.

Parameters:
  • cls (class) – The TensorNetwork subclass to convert tn to.

  • tn (TensorNetwork) – The TensorNetwork to convert.

  • like (TensorNetwork, optional) – If specified, try and retrieve the neccesary attribute values from this tensor network.

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

  • kwargs – Extra properties of the TN subclass that should be specified.

view_as(cls, inplace=False, **kwargs)[source]

View this tensor network as subclass cls.

view_as_[source]
view_like(like, inplace=False, **kwargs)[source]

View this tensor network as the same subclass cls as like inheriting its extra properties as well.

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

Copy this TensorNetwork. If deep=False, (the default), then everything but the actual numeric data will be copied.

__copy__[source]
get_params()[source]

Get a pytree of the ‘parameters’, i.e. all underlying data arrays.

set_params(params)[source]

Take a pytree of the ‘parameters’, i.e. all underlying data arrays, as returned by get_params and set them.

Link tid to each of tags.

“Unlink tid from each of tags.

Link tid to each of inds.

“Unlink tid from each of inds.

_reset_inner_outer(inds)[source]
_next_tid()[source]
add_tensor(tensor, tid=None, virtual=False)[source]

Add a single tensor to this network - mangle its tid if neccessary.

add_tensor_network(tn, virtual=False, check_collisions=True)[source]
add(t, virtual=False, check_collisions=True)[source]

Add Tensor, TensorNetwork or sequence thereof to self.

make_tids_consecutive(tid0=0)[source]

Reset the tids - node identifies - to be consecutive integers.

__iand__(tensor)[source]

Inplace, but non-virtual, addition of a Tensor or TensorNetwork to this network. It should not have any conflicting indices.

__ior__(tensor)[source]

Inplace, virtual, addition of a Tensor or TensorNetwork to this network. It should not have any conflicting indices.

_modify_tensor_tags(old, new, tid)[source]
_modify_tensor_inds(old, new, tid)[source]
property num_tensors
The total number of tensors in the tensor network.
property num_indices
The total number of indices in the tensor network.
pop_tensor(tid)[source]

Remove tensor with tid from this network, and return it.

remove_all_tensors()[source]

Remove all tensors from this network.

_pop_tensor[source]
delete(tags, which='all')[source]

Delete any tensors which match all or any of tags.

Parameters:
  • tags (str or sequence of str) – The tags to match.

  • which ({'all', 'any'}, optional) – Whether to match all or any of the tags.

check()[source]

Check some basic diagnostics of the tensor network.

add_tag(tag, where=None, which='all')[source]

Add tag to every tensor in this network, or if where is specified, the tensors matching those tags – i.e. adds the tag to all tensors in self.select_tensors(where, which=which).

drop_tags(tags=None)[source]

Remove a tag or tags from this tensor network, defaulting to all. This is an inplace operation.

Parameters:

tags (str or sequence of str or None, optional) – The tag or tags to drop. If None, drop all tags.

retag(tag_map, inplace=False)[source]

Rename tags for all tensors in this network, optionally in-place.

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

  • inplace (bool, optional) – Perform operation inplace or return copy (default).

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

Rename indices for all tensors in this network, optionally in-place.

Parameters:

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

reindex_[source]
mangle_inner_(append=None, which=None)[source]

Generate new index names for internal bonds, meaning that when this tensor network is combined with another, there should be no collisions.

Parameters:
  • append (None or str, optional) – Whether and what to append to the indices to perform the mangling. If None a whole new random UUID will be generated.

  • which (sequence of str, optional) – Which indices to rename, if None (the default), all inner indices.

conj(mangle_inner=False, inplace=False)[source]

Conjugate all the tensors in this network (leaves all indices).

conj_[source]
property H
Conjugate all the tensors in this network (leaves all indices).
item()[source]

Return the scalar value of this tensor network, if it is a scalar.

largest_element()[source]

Return the ‘largest element’, in terms of absolute magnitude, of this tensor network. This is defined as the product of the largest elements of each tensor in the network, which would be the largest single term occuring if the TN was summed explicitly.

norm(**contract_opts)[source]

Frobenius norm of this tensor network. Computed by exactly contracting the TN with its conjugate:

\[\|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.

make_norm(mangle_append='*', layer_tags=('KET', 'BRA'), return_all=False)[source]

Make the norm tensor network of this tensor network tn.H & tn.

Parameters:
  • mangle_append ({str, False or None}, optional) – How to mangle the inner indices of the bra.

  • layer_tags ((str, str), optional) – The tags to identify the top and bottom.

  • return_all (bool, optional) – Return the norm, the ket and the bra.

multiply(x, inplace=False, spread_over=8)