quimb.tensor.tensor_builder¶
Build specific tensor networks, including states and operators.
Attributes¶
Alias for 

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

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

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

Mixin class for tensor networks with a square lattice twodimensional 

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

Mixin class for tensor networks with a cubic lattice threedimensional 

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

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

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

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

A labelled, tagged ndimensional array. The index labels are used 

A collection of (as yet uncontracted) Tensors. 

Simple class to allow 

Class for easily building custom spin hamiltonians in MPO or LocalHam1D 
Functions¶

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

Make array read only, inplace. 



Constructs the nearest neighbour 1d heisenberg spin1/2 hamiltonian. 

Generate a general spinoperator. 

Generate random complex numbers distributed on the unit sphere. 

Fast multithreaded generation of random normally distributed data. 

Modify 

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

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

Maybe convert data for a tensor to use. If 
Take an array and scale it very roughly such that random tensor 






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

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

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

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

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

Get the tensor representing the COPY operation with dimension size 

Inplace addition of a new bond between tensors 

Return a guaranteed unique, shortish identifier, optional appended 

Parse a 

Direct product of two Tensors. Any axes included in 

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

Get the delta symbol AKA COPYtensor as an ndarray. 

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

Generate a random tensor with specified shape and inds. 

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

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

Generate a random symmetric tensor with specified local dimension and 

A product state in general tensor network form. 

A computational basis state in general tensor network form. 



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

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

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

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

Create a random tensor network with geometry defined from a sequence 

Create a random regular tensor network. 

Create a random tree tensor network. 



reate a CPdecomposition structured hyper tensor network from a 

Create a CPdecomposition structured hyper tensor network state from a 

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

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

Convert 

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

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

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

A random scalar 2D lattice tensor network. 

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

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



Convert 

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

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

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

A random scalar 3D lattice tensor network. 





The interaction term for the classical ising model. 

The magnetic field term for the classical ising model. 

The sqrt factorized interaction term for the classical ising model. 

The single effective TN site for the classical ising model. 
Parse the 


Hyper tensor network representation of the 2D classical ising model 

Hyper tensor network representation of the 3D classical ising model 

The tensor network representation of the 2D classical ising model 

Tensor network representation of the 3D classical ising model 

Build a hyper tensor network representation of a classical ising model 

Build a regular tensor network representation of a classical ising model 

Take a coupling matrix or dict of pairwise strengths in either upper or 
Construct a (triangular) '2D' tensor network representation of the 




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

Encode a clause as a single integer 

Get the array representing satisfiability of 

Get the tensor representing satisfiability of 

Get the set of MPS tensors representing satisfiability of 

Get the set of PARAFAC arrays representing satisfiability of 

Get the set of PARAFAC tensors representing satisfiability of 

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

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

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

Create a random kSAT instance. 

Create a random kSAT instance encoded as a hyper tensor network. 

Create a tensor network with the same outer indices as 

Generate a random matrix product state. 

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

A computational basis state in Matrix Product State form. 

Generate the neel state in Matrix Product State form. 

Build a matrix product state representation of the COPY tensor. 

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

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

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

The allzeros MPS state, of given bonddimension. 

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

Generate an identity MPO of size 

Return an identity matrix operator with the same physical index and 

Generate a zeros MPO of size 

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

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

Generate a random matrix product state. 

Generate a random hermitian matrix product operator. 
Check if 


Generate tensor(s) for a spin hamiltonian MPO. 



Ising Hamiltonian in MPO form. 

Ising Hamiltonian in 



XYHamiltonian in MPO form. 

XYHamiltonian in 



Heisenberg Hamiltonian in MPO form. 

Heisenberg Hamiltonian in 

XXZHamiltonian in MPO form. 

XXZHamiltonian in 



Hamiltonian of onedimensional bilinear biquadratic chain in MPO form, 

Hamiltonian of onedimensional bilinear biquadratic chain in LocalHam1D 



The manybodylocalized spin hamiltonian in MPO form. 

The manybodylocalized spin hamiltonian in 

Ising Hamiltonian in 

Heisenberg Hamiltonian in 

Heisenberg Hamiltonian in 

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 byinds
.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 actuallyX[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, inplace.
 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.ham_heis(n, j=1.0, b=0.0, cyclic=False, parallel=False, nthreads=None, ownership=None)[source]¶
Constructs the nearest neighbour 1d heisenberg spin1/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 zdirection 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 spinoperator.
 Parameters:
label (str) –
The type of operator, can be one of six options:
{'x', 'X'}
, xspin operator.{'y', 'Y'}
, yspin operator.{'z', 'Z'}
, zspin operator.{'+', 'p'}
, Raising operator.{'', 'm'}
, Lowering operator.{'i', 'I'}
, identity operator.
S (float, optional) – The spin of particle to act on, default to spin1/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.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:
dtype ({'complex128', 'float64', 'complex64' 'float32'}, optional) – The datatype 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 aseed
argument (so as to seed the random generators onceonly at beginning of function not everyrandn
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 asis. Else the elements are inspected to see which libraries’ array constructor should be used, defaulting tonumpy
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 ifsites
is not given).shape (str, optional) – String specifying layout of the tensors. E.g. ‘lrud’ (the default) indicates the shape corresponds leftbond, rightbond, ‘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 leftbond, rightbond, ‘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:
 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:
 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:
 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: AAAAAAAAAAAAAAAAAA                   other: xxxxxxxxxxxxxxxxxx >                   < 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: AAAAAAAAAAAAAAAAAA                   other: BBBBBBBBBBBBBBBBBB                   >                   < 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:
other (MatrixProductOperator or MatrixProductState) – The object to act on.
compress (bool, optional) – Whether to compress the resulting object.
compress_opts – Supplied to
TensorNetwork1DFlat.compress()
.
 Return type:
 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.
 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 ifsites
is not given).shape (str, optional) – String specifying layout of the tensors. E.g. ‘lrp’ (the default) indicates the shape corresponds leftbond, rightbond, 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:
 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:
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 oooooo      
 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=1e15, insert=None)[source]¶
Normalize this MPS, optional with covector
bra
. For periodic MPS this uses transfer matrix SVD approximation with precisioneps
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: 1e14.
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:
 gate_split(G, where, inplace=False, **compress_opts)[source]¶
Apply a twosite gate and then split resulting tensor to retrieve a MPS form:
ooABoo       ooGGGoo ooX~Yoo   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 dimensiond
.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
 swap_sites_with_compress(i, j, info=None, inplace=False, **compress_opts)[source]¶
Swap sites
i
andj
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_site_to(i, f, info=None, inplace=False, **compress_opts)[source]¶
Swap site
i
to sitef
, 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 oooxoooooo >>>>>>>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()
.
 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 dimensiond
.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 sitej
will remain swapped toi + 1
, and sites betweeni + 1
andj
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_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', 'zipupfirst', '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:
 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', 'zipupfirst', '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:
 gate_nonlocal(G, where, dims=None, method='direct', info=None, inplace=False, **compress_opts)[source]¶
Apply a potentially nonlocal 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', 'zipupfirst', '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:
 flip(inplace=False)[source]¶
Reverse the order of the sites in the MPS, such that site
i
is now at siteL  i  1
.
 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 oooooSooooooooooo                 i1 ..........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.
 entropy(i, info=None, method='svd')[source]¶
The entropy of bipartition between the left block of
i
sites and the rest.
 schmidt_gap(i, info=None, method='svd')[source]¶
The schmidt gap of bipartition between the left block of
i
sites and the rest.
 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:
 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', 'ketdense', 'rhodense'}, optional) –
Get the:
’ket’: vector form as tensor.
’rho’: density operator form, i.e. vector outer product
’ketdense’: like ‘ket’ but return
qarray
.’rhodense’: 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=1e08, 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.... ooooAAAAAAAAooBBBBBBooooooooo                              ==> form inner product ............... ........... ooooAAAAAAAAooBBBBBBooooooooo                              ooooAAAAAAAAooBBBBBBooooooooo ==> 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. Seetensor_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:
 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 ......... ..... ... ooooooAAAAAoooBBBooooooo ...                        
 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. Seetensor_split
.approx_spectral_opts – Supplied to
approx_spectral_function()
.
 Returns:
ln – The logarithmic negativity.
 Return type:
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 ismin(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 thansite
will be retagged and reindex one down, and the MPS will have one less site. E.g:0123456 / / /  measure and remove site 3 012456  reindex sites (4, 5, 6) to (3, 4, 5) 012345
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'
.
 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 likeH.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 keyNone
, 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.
Examples
A simple, translationally invariant, interactiononly
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
 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 leftbond, rightbond, ‘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()
.
 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 twodimensional structure, indexed by
[{row},{column}]
so that:'Y{j}' v i=Lx1 ●──●──●──●──●──●── ──●        ...       '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=Ly1
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
andother
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:
 property Lx¶
 The number of rows.
 property Ly¶
 The number of columns.
 property nsites¶
 The total number of sites.
 property x_tag_id¶
 The string specifier for tagging each row of this 2D TN.
 property x_tags¶
 A tuple of all of the ``Lx`` different row tags.
 row_tags¶
 property y_tag_id¶
 The string specifier for tagging each column of this 2D TN.
 property y_tags¶
 A tuple of all of the ``Ly`` different column tags.
 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_horizontal_even_bond_coos()[source]¶
Generate all coordinate pairs like
(i, j), (i, j + 1)
wherej
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)
wherej
is odd, which thus don’t overlap at all.
 gen_vertical_even_bond_coos()[source]¶
Generate all coordinate pairs like
(i, j), (i + 1, j)
wherei
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)
wherei
is odd, which thus don’t overlap at all.
 gen_diagonal_left_even_bond_coos()[source]¶
Generate all coordinate pairs like
(i, j), (i + 1, j  1)
wherej
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)
wherej
is odd, which thus don’t overlap at all.
 gen_diagonal_right_even_bond_coos()[source]¶
Generate all coordinate pairs like
(i, j), (i + 1, j + 1)
wherei
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)
wherei
is odd, which thus don’t overlap at all.
 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 ofimin = 0
andimax = Lx  1
, andj
at the center of the lattice. Ifimin
andimax
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 ofjmin = 0
andjmax = Ly  1
, andi
at the center of the lattice. Ifjmin
andjmax
are adjacent then this is considered False, since there is no ‘extra’ connectivity.
 _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.
 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
andyreverse
respectively.ystep (int, optional) – When generating a bond, step in this direction to yield the neighboring coordinate. By default, these follow
xreverse
andyreverse
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.
 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.
 compress_plane(xrange, yrange, max_bond=None, cutoff=1e10, 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=1e10, 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 tocutoff
and is not recommended in 2D.cutoff (float, optional) – Cutoff 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=1e10, 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 tocutoff
and is not recommended in 2D.cutoff (float, optional) – Cutoff 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=1e10, method='dm', layer_tags=None, **compress_opts)[source]¶
 _contract_boundary_core(xrange, yrange, from_which, max_bond, cutoff=1e10, 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='autohq', 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) – Cutoff 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=1e10, lazy=False, equalize_norms=False, optimize='autohq', 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 tocutoff
.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=1e10, 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_xmin(xrange, yrange=None, max_bond=None, *, cutoff=1e10, 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 tocutoff
and is not recommended in 2D.cutoff (float, optional) – Cutoff 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', 'fullbond'}, 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 eachlayer_tag
inlayer_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(xrange, yrange=None, max_bond=None, *, cutoff=1e10, 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 tocutoff
and is not recommended in 2D.cutoff (float, optional) – Cutoff 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', 'fullbond'}, 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 eachlayer_tag
inlayer_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(yrange, xrange=None, max_bond=None, *, cutoff=1e10, 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 tocutoff
and is not recommended in 2D.cutoff (float, optional) – Cutoff 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', 'fullbond'}, 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 eachlayer_tag
inlayer_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(yrange, xrange=None, max_bond=None, *, cutoff=1e10, 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 tocutoff
and is not recommended in 2D.cutoff (float, optional) – Cutoff 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', 'fullbond'}, 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 eachlayer_tag
inlayer_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_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=1e10, 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 tocutoff
and is not recommended in 2D.cutoff (float, optional) – Cutoff 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', 'fullbond'}, 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 withinmax_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'autohq'
.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_mps_sweep(max_bond=None, *, cutoff=1e10, 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 tocutoff
and is not recommended in 2D.cutoff (float, optional) – Cutoff 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.
 compute_environments(from_which, xrange=None, yrange=None, max_bond=None, *, cutoff=1e10, 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', 'fullbond'}, optional) – Which contraction method to use for the environments.
layer_tags (str or iterable[str], optional) – If this 2D TN is multilayered (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:
 compute_xmin_environments[source]¶
Compute the
self.Lx
1D boundary tensor networks describing the lower environments of each row in this 2D tensor network. Seecompute_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. Seecompute_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. Seecompute_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. Seecompute_y_environments()
for full details.
 compute_x_environments(max_bond=None, *, cutoff=1e10, 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 rowsi + 1, i + 2, ...
etc:●━━━●━━━●━━━●━━━●━━━●━━━●━━━●━━━●━━━● ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲
The bottom or ‘xmin’ environment for row
i
will be a contraction of all rowsi  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 tocutoff
and is not recommended in 2D.cutoff (float, optional) – Cutoff 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', 'fullbond'}, 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 eachlayer_tag
inlayer_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()
andcontract_boundary_from_xmax()
.
 Returns:
x_envs – The two environment tensor networks of row
i
will be stored inx_envs['xmin', i]
andx_envs['xmax', i]
. Return type:
dict[(str, int), TensorNetwork]
 compute_y_environments(max_bond=None, *, cutoff=1e10, 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 columnsj  1, j  2, ...
etc:●< ┃ ●< ┃ ●< ┃ ●<
The right or ‘ymax’ environment for row
j
will be a contraction of all rowsj + 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 tocutoff
and is not recommended in 2D.cutoff (float, optional) – Cutoff 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', 'fullbond'}, 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 eachlayer_tag
inlayer_tags
.compress_opts (None or dict, optional) – Supplied to
compress_between()
.contract_boundary_opts – Supplied to
contract_boundary_from_ymin()
andcontract_boundary_from_ymax()
.
 Returns:
y_envs – The two environment tensor networks of column
j
will be stored iny_envs['ymin', j]
andy_envs['ymax', j]
. Return type:
dict[(str, int), TensorNetwork]
 _compute_plaquette_environments_x_first(x_bsz, y_bsz, max_bond=None, cutoff=1e10, 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=1e10, 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=1e10, 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 xdirection (number of rows).
y_bsz (int, optional) – The size of the plaquettes in the ydirection (number of columns).
max_bond (int, optional) – The maximum boundary dimension, AKA ‘chi’. The default of
None
means truncation is left purely tocutoff
and is not recommended in 2D.cutoff (float, optional) – Cutoff 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', 'fullbond'}, 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 eachlayer_tag
inlayer_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 thebsz
in the corresponding direction is 1.compress_opts (None or dict, optional) – Supplied to
compress_between()
.compute_environment_opts – Supplied to
compute_y_environments()
orcompute_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:
 coarse_grain_hotrg(direction, max_bond=None, cutoff=1e10, lazy=False, equalize_norms=False, optimize='autohq', 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:
 contract_hotrg(max_bond=None, *, cutoff=1e10, 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'autohq'
.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:
 contract_ctmrg(max_bond=None, *, cutoff=1e10, 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/condmat/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'autohq'
.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
andaround=None
) or the partially contracted tensor network. Return type:
scalar or TensorNetwork2D
 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 returnsTrue
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 keyNone
.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 keyNone
.
 terms¶
The total effective local term for each interaction (with single site terms appropriately absorbed). Each key is a pair of coordinates
ija, ijb
withija < ijb
.
 property nsites¶
 The number of sites in the system.
 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.
 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 threedimensional 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
andother
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:
 property Lx¶
 The number of xslices.
 property Ly¶
 The number of yslices.
 property Lz¶
 The number of zslices.
 property nsites¶
 The total number of sites.
 property x_tag_id¶
 The string specifier for tagging each xslice of this 3D TN.
 property x_tags¶
 A tuple of all of the ``Lx`` different xslice tags.
 property y_tag_id¶
 The string specifier for tagging each yslice of this 3D TN.
 property y_tags¶
 A tuple of all of the ``Ly`` different yslice tags.
 property z_tag_id¶
 The string specifier for tagging each zslice of this 3D TN.
 property z_tags¶
 A tuple of all of the ``Lz`` different zslice 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.
 valid_coo(coo, xrange=None, yrange=None, zrange=None)[source]¶
Check whether
coo
is inbounds. Parameters:
 Return type:
 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:
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 ofimin = 0
andimax = Lx  1
, andj
andk
the center of the lattice. Ifimin
andimax
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 ofjmin = 0
andjmax = Ly  1
, andi
andk
the center of the lattice. Ifjmin
andjmax
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 ofkmin = 0
andkmax = Lz  1
, andi
andj
the center of the lattice. Ifkmin
andkmax
are adjacent then this is considered False, since there is no ‘extra’ connectivity.
 _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.
 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
, andzreverse
respectively.ystep (int, optional) – When generating a bond, step in this direction to yield the neighboring coordinate. By default, these follow
xreverse
,yreverse
, andzreverse
respectively.zstep (int, optional) – When generating a bond, step in this direction to yield the neighboring coordinate. By default, these follow
xreverse
,yreverse
, andzreverse
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=1e10, 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=1e10, method='localearly', layer_tags=None, **compress_opts)[source]¶
 _contract_boundary_core(xrange, yrange, zrange, from_which, max_bond, cutoff=1e10, 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=1e10, canonize=False, layer_tags=None, lazy=False, equalize_norms=False, optimize='autohq', compress_opts=None, canonize_opts=None)[source]¶
 contract_boundary_from(xrange, yrange, zrange, from_which, max_bond=None, *, cutoff=1e10, 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_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='autohq', progbar=False, inplace=False)[source]¶
Unified handler for performing iterleaved contractions in a sequence of inwards boundary directions.
 contract_boundary(max_bond=None, *, cutoff=1e10, 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='autohq', progbar=False, inplace=False, **contract_boundary_opts)[source]¶
 contract_ctmrg(max_bond=None, *, cutoff=1e10, 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]¶
 _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 byfrom_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=1e10, lazy=False, equalize_norms=False, optimize='autohq', 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:
See also
contract_hotrg
,insert_compressor_between_regions
 contract_hotrg(max_bond=None, cutoff=1e10, 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'autohq'
.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:
See also
coarse_grain_hotrg
,insert_compressor_between_regions
 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 xslices.
Ly (int) – The number of yslices.
Lz (int) – The number of zslices.
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 returnsTrue
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 keyNone
.
 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
withsite_a < site_b
.
 property nsites¶
 The number of sites in the system.
 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
andother
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:
 property nsites¶
 The total number of sites.
 property sites¶
 Tuple of the possible sites in this tensor network.
 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.
 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
).
 property site_tags¶
 All of the site tags.
 property site_tags_present¶
 All of the site tags still present in this tensor network.
 maybe_convert_coo(x)[source]¶
Check if
x
is a valid site and convert to the corresponding site tag if so, else returnx
.
 _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.
 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.
 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
).
 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.
 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
).
 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
 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
), likeA @ 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 ofB
. IfFalse
(the default), the lower indices ofA
will be contracted with the upper indices ofB
, ifTrue
the upper indices ofA
will be contracted with the upper indices ofB
, which is like applying the transpose first.inplace (bool, optional) – Whether to perform the gate operation inplace on this tensor network.
 Return type:
 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
), likeB @ 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. IfFalse
(the default), the upper indices ofA
will be contracted with the lower indices ofB
, ifTrue
the lower indices ofA
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:
 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:
 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.
 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
).
 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). IfNone
(default), do this only if theinds_seq
is not supplied.contract_opts – Options to pass to
contract()
.
 Return type:
array
 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, likeA @ 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 ofx
. IfFalse
(the default), the lower indices ofA
will be contracted with the site indices ofx
, ifTrue
the upper indices ofA
will be contracted with the site indices ofx
, which is like applyingA.T @ x
.inplace (bool, optional) – Whether to perform the gate operation inplace on this tensor network.
 Return type:
 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 aroundgate_inds()
apart fromwhere
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', 'reducesplit', 'splitgate',) – ‘swapsplitgate’, ‘autosplitgate’}, 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 anycontract
methods that involve splitting. Ignored otherwise.
 Return type:
See also
 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 ingauges
. The new singular values for the bond are reinserted intogauges
. 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
.
 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 siteswhere
, either treating the environment beyondmax_distance
as the identity, or using simple update style bond gauges as supplied ingauges
.This selects a local neighbourhood of tensors up to distance
max_distance
away fromwhere
, 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 siteswhere
are used.fillin (bool or int, optional) – When selecting the local tensors, whether and how many times to ‘fillin’ 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:
 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 ingauges
.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 ‘fillin’ 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:
 local_expectation_exact(G, where, optimize='autohq', 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='autohq', *, 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:
 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 inkeep
.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 toTrue
.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', 'rhoreduced'}, 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 toTrue
.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:
 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', 'rhoreduced'}, optional) –
The method to use to compute the expectation value.
’rho’: compute the expectation value via the reduced density matrix.
’rhoreduced’: 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 toTrue
.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:
 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 dimensionslen(inds)
, with exterior indicesinds
. Parameters:
 Returns:
The tensor describing the MPS, of size
d**len(inds)
. Return type:
 class quimb.tensor.tensor_builder.Tensor(data=1.0, inds=(), tags=None, left_inds=None)[source]¶
A labelled, tagged ndimensional 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 ndimensional 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')¶
 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.
 property data¶
 property inds¶
 property tags¶
 property left_inds¶
 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.
 check_owners()[source]¶
Check if this tensor is ‘owned’ by any alive TensorNetworks. Also trim any weakrefs to dead TensorNetworks.
 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:
 Return type:
Examples
>>> T = rand_tensor((2, 3, 4), inds=('a', 'b', 'c')) >>> T.isel({'b': 1}) Tensor(shape=(2, 4), inds=('a', 'c'), tags=())
See also
 add_tag(tag)[source]¶
Add a tag or multiple tags to this tensor. Unlike
self.tags.add
this also updates anyTensorNetwork
objects viewing thisTensor
.
 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 fromrand_dist
, multiplied byrand_strength
. IfNone
then select from zeros or random depening on nonzerorand_strength
.rand_strength (float, optional) – If
mode='random'
, a multiplicative scale for the random entries, defaulting to 1.0. Ifmode is None
then supplying a nonzero value here triggersmode='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 fromrand_dist
, multiplied byrand_strength
. IfNone
then select from zeros or random depening on nonzerorand_strength
.rand_strength (float, optional) – If
mode='random'
, a multiplicative scale for the random entries, defaulting to 1.0. Ifmode is None
then supplying a nonzero value here triggersmode='random'
.rand_dist ({'normal', 'uniform', 'exp'}, optional) – If
mode='random'
, the distribution to draw the random entries from.
See also
 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
toright_inds
. Selecting 0 or 1 for the new indexname
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.
 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.
Get the total size of the shared index(es) with
other
.
 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:
 Returns:
tt – The transposed tensor.
 Return type:
See also
 transpose_like(other, inplace=False)[source]¶
Transpose this tensor to match the indices of
other
, allowing for one index to be different. E.g. ifself.inds = ('a', 'b', 'c', 'x')
andother.inds = ('b', 'a', 'd', 'c')
then ‘x’ will be aligned with ‘d’ and the output inds will be('b', 'a', 'x', 'c')
 Parameters:
 Returns:
tt – The transposed tensor.
 Return type:
See also
 moveindex(ind, axis, inplace=False)[source]¶
Move the index
ind
to positionaxis
. Liketranspose
, 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.
 trace(left_inds, right_inds, preserve_tensor=False, inplace=False)[source]¶
Trace index or indices
left_inds
withright_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
 vector_reduce(ind, v, inplace=False)[source]¶
Contract the vector
v
with the indexind
of this tensor, removing it.
 collapse_repeated(inplace=False)[source]¶
Take the diagonals of any repeated indices, such that each index only appears once.
 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:
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
 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:
1darray
 entropy(left_inds, method='svd')[source]¶
Return the entropy associated with splitting this tensor according to
left_inds
.
 retag(retag_map, inplace=False)[source]¶
Rename the tags of this tensor, optionally, inplace.
 Parameters:
retag_map (dictlike) – 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.
 reindex(index_map, inplace=False)[source]¶
Rename the indices of this tensor, optionally inplace.
 Parameters:
index_map (dictlike) – 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.
 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 relabeled tensor.
 Return type:
 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 shapeshape_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 relabeled tensor
 Return type:
 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'))
.
 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:
 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.
 idxmax(f=None)[source]¶
Get the index configuration of the maximum element of this tensor, optionally applying
f
first.
 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.
 symmetrize(ind1, ind2, inplace=False)[source]¶
Hermitian symmetrize this tensor for indices
ind1
andind2
. I.e.T = (T + T.conj().T) / 2
, where the transpose is taken only over the specified indices.
 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 bymethod
. 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 ofR
is positive.”svd”: uses
U @ VH
of the SVD decomposition ofx
. This is useful for finding the ‘closest’ isometric matrix tox
, 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 completingx
with zeros if it is rectangular. This is a good parametrization for optimization, but more expensive for nonsquarex
.”cayley”: use the Cayley transform of
x  dag(x)
, first completingx
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 nonsquarex
.”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:
 unitize_¶
 randomize(dtype=None, inplace=False, **randn_opts)[source]¶
Randomize the entries of this tensor.
 Parameters:
 Return type:
 flip(ind, inplace=False)[source]¶
Reverse the axis on this tensor corresponding to
ind
. Like performing e.g.X[:, :, ::1, :]
.
 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 indexind
.
 filter_bonds(other)[source]¶
Sort this tensor’s indices into a list of those that it shares and doesn’t share with another tensor.
 __or__(other)[source]¶
Combine virtually (no copies made) with another
Tensor
orTensorNetwork
into a newTensorNetwork
.
 __matmul__(other)[source]¶
Explicitly contract with another tensor. Avoids some slight overhead of calling the full
tensor_contract()
.
 _repr_info()[source]¶
General info to show in various reprs. Sublasses can add more relevant info to this dict.
 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 anotherTensorNetwork
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:
 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:
 ind_map¶
Like
tag_map
but for indices. Soind_map[ind]]
returns the tensor ids of those tensors withind
. Type:
 exponent¶
A scalar prefactor for the tensor network, stored in base 10 like
10**exponent
. This is mostly for conditioning purposes and will be0.0
unless you use useequalize_norms(value)
ortn.strip_exponent(tid_or_tensor)
. Type:
 _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:
 __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.
 classmethod new(like=None, **kwargs)[source]¶
Create a new tensor network, without any tensors, of type
cls
, with all the requisite properties specified bykwargs
or inherited fromlike
.
 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_like(like, inplace=False, **kwargs)[source]¶
View this tensor network as the same subclass
cls
aslike
inheriting its extra properties as well.
 copy(virtual=False, deep=False)[source]¶
Copy this
TensorNetwork
. Ifdeep=False
, (the default), then everything but the actual numeric data will be copied.
 set_params(params)[source]¶
Take a pytree of the ‘parameters’, i.e. all underlying data arrays, as returned by
get_params
and set them.
 add_tensor(tensor, tid=None, virtual=False)[source]¶
Add a single tensor to this network  mangle its tid if neccessary.
 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 nonvirtual, 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.
 property num_tensors¶
 The total number of tensors in the tensor network.
 property num_indices¶
 The total number of indices in 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 inself.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.
 retag(tag_map, inplace=False)[source]¶
Rename tags for all tensors in this network, optionally inplace.
 Parameters:
tag_map (dictlike) – Mapping of pairs
{old_tag: new_tag, ...}
.inplace (bool, optional) – Perform operation inplace or return copy (default).
 reindex(index_map, inplace=False)[source]¶
Rename indices for all tensors in this network, optionally inplace.
 Parameters:
index_map (dictlike) – Mapping of pairs
{old_ind: new_ind, ...}
.
 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.
 conj(mangle_inner=False, inplace=False)[source]¶
Conjugate all the tensors in this network (leaves all indices).
 property H¶
 Conjugate all the tensors in this network (leaves all indices).
 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.