quimb.tensor

Tensor and tensor network functionality.

Submodules

Package Contents

Classes

Circuit

Class for simulating quantum circuits using tensor networks.

CircuitDense

Quantum circuit simulation keeping the state in full dense form.

CircuitMPS

Quantum circuit simulation keeping the state always in a MPS form. If

TNOptimizer

Globally optimize tensors within a tensor network with respect to any

Dense1D

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

MatrixProductOperator

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

MatrixProductState

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

SuperOperator1D

A 1D tensor network super-operator class:

TensorNetwork1D

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

TNLinearOperator1D

A 1D tensor network linear operator like:

TEBD

Class implementing Time Evolving Block Decimation (TEBD) [1].

LocalHam1D

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

PEPO

Projected Entangled Pair Operator object:

PEPS

Projected Entangled Pair States object (2D):

TensorNetwork2D

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

TEBD2D

Generic class for performing two dimensional time evolving block

FullUpdate

Implements the 'Full Update' version of 2D imaginary time evolution,

LocalHam2D

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

SimpleUpdate

A simple subclass of TEBD2D that overrides two key methods in

PEPS3D

Projected Entangled Pair States object (3D).

TensorNetwork3D

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

LocalHam3D

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

LocalHamGen

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

SimpleUpdateGen

Simple update for arbitrary geometry hamiltonians.

TEBDGen

Generic class for performing time evolving block decimation on an

SpinHam1D

Class for easily building custom spin hamiltonians in MPO or LocalHam1D

IsoTensor

A Tensor subclass which keeps its left_inds by default even

PTensor

A tensor whose data array is lazily generated from a set of parameters

Tensor

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

TensorNetwork

A collection of (as yet uncontracted) Tensors.

oset

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

DMRG

Density Matrix Renormalization Group variational groundstate search.

DMRG1

Simple alias of one site DMRG.

DMRG2

Simple alias of two site DMRG.

DMRGX

Class implmenting DMRG-X [1], whereby local effective energy eigenstates

MovingEnvironment

Helper class for efficiently moving the effective 'environment' of a

MERA

The Multi-scale Entanglement Renormalization Ansatz (MERA) state:

Functions

circ_ansatz_1D_brickwork(n, depth[, cyclic, gate2, seed])

A 1D circuit ansatz with odd and even layers of entangling

circ_ansatz_1D_rand(n, depth[, seed, cyclic, gate2, ...])

A 1D circuit ansatz with randomly place entangling gates interleaved

circ_ansatz_1D_zigzag(n, depth[, gate2, seed])

A 1D circuit ansatz with forward and backward layers of entangling

circ_qaoa(terms, depth, gammas, betas, **circuit_opts)

Generate the QAOA circuit for weighted graph described by terms.

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

contract_backend(backend[, set_globally])

A context manager to temporarily set the default backend used for tensor

contract_strategy(strategy[, set_globally])

A context manager to temporarily set the default contraction strategy

get_contract_backend()

Get the default backend used for tensor contractions, via 'cotengra'.

get_contract_strategy()

Get the default contraction strategy - the option supplied as

get_tensor_linop_backend()

Get the default backend used for tensor network linear operators, via

inds_to_eq(inputs[, output])

Turn input and output indices of any sort into a single 'equation'

set_contract_backend(backend)

Set the default backend used for tensor contractions, via 'cotengra'.

set_contract_strategy(strategy)

Get the default contraction strategy - the option supplied as

set_tensor_linop_backend(backend)

Set the default backend used for tensor network linear operators, via

tensor_linop_backend(backend[, set_globally])

A context manager to temporarily set the default backend used for tensor

edges_2d_hexagonal(Lx, Ly[, cyclic, cells])

Return the graph edges of a finite 2D hexagonal lattice. There are two

edges_2d_kagome(Lx, Ly[, cyclic, cells])

Return the graph edges of a finite 2D kagome lattice. There are

edges_2d_square(Lx, Ly[, cyclic, cells])

Return the graph edges of a finite 2D square lattice. The nodes

edges_2d_triangular(Lx, Ly[, cyclic, cells])

Return the graph edges of a finite 2D triangular lattice. There is a

edges_2d_triangular_rectangular(Lx, Ly[, cyclic, cells])

Return the graph edges of a finite 2D triangular lattice tiled in a

edges_3d_cubic(Lx, Ly, Lz[, cyclic, cells])

Return the graph edges of a finite 3D cubic lattice. The nodes

edges_3d_diamond(Lx, Ly, Lz[, cyclic, cells])

Return the graph edges of a finite 3D diamond lattice. There are

edges_3d_diamond_cubic(Lx, Ly, Lz[, cyclic, cells])

Return the graph edges of a finite 3D diamond lattice tiled in a cubic

edges_3d_pyrochlore(Lx, Ly, Lz[, cyclic, cells])

Return the graph edges of a finite 3D pyorchlore lattice. There are

edges_tree_rand(n[, max_degree, seed])

Return a random tree with n nodes. This a convenience function for

jax_register_pytree()

pack(obj)

Take a tensor or tensor network like object and return a skeleton needed

unpack(params, skeleton)

Take a skeleton of a tensor or tensor network like object and a pytree

expec_TN_1D(*tns[, compress, eps])

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

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

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

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

Take a tensor network superoperator and act with it on a

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

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

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

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

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

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

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

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

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

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

MPS_COPY(L[, phys_dim, dtype])

Build a matrix product state representation of the COPY tensor.

HTN2D_classical_ising_partition_function(Lx, Ly, beta)

Hyper tensor network representation of the 2D classical ising model

HTN3D_classical_ising_partition_function(Lx, Ly, Lz, beta)

Hyper tensor network representation of the 3D classical ising model

HTN_classical_partition_function_from_edges(edges, beta)

Build a hyper tensor network representation of a classical ising model

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

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

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

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

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

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

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

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

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

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

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

Heisenberg Hamiltonian in MPO form.

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

Ising Hamiltonian in MPO form.

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

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

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

XY-Hamiltonian in MPO form.

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

Generate an identity MPO of size L.

MPO_identity_like(mpo, **mpo_opts)

Return an identity matrix operator with the same physical index and

MPO_product_operator(arrays[, cyclic])

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

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

Generate a random matrix product state.

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

Generate a random hermitian matrix product operator.

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

Generate a zeros MPO of size L.

MPO_zeros_like(mpo, **mpo_opts)

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

MPS_computational_state(binary[, dtype, cyclic])

A computational basis state in Matrix Product State form.

MPS_ghz_state(L[, dtype])

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

MPS_neel_state(L[, down_first, dtype])

Generate the neel state in Matrix Product State form.

MPS_product_state(arrays[, cyclic])

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

MPS_rand_computational_state(L[, dtype])

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

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

Generate a random matrix product state.

MPS_sampler(L[, dtype, squeeze])

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

MPS_w_state(L[, dtype])

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

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

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

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

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

TN2D_classical_ising_partition_function(Lx, Ly, beta)

The tensor network representation of the 2D classical ising model

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

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

TN2D_embedded_classical_ising_partition_function(Jij, beta)

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

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

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

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

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

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

A random scalar 2D lattice tensor network.

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

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

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

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

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

TN3D_classical_ising_partition_function(Lx, Ly, Lz, beta)

Tensor network representation of the 3D classical ising model

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

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

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

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

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

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

A random scalar 3D lattice tensor network.

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

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

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

TN_classical_partition_function_from_edges(edges, beta)

Build a regular tensor network representation of a classical ising model

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

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

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

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

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

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

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

Create a random tensor network with geometry defined from a sequence

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

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

TN_from_sites_computational_state(site_map[, ...])

A computational basis state in general tensor network form.

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

A product state in general tensor network form.

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

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

Create a random regular tensor network.

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

Create a random tree tensor network.

cnf_file_parse(fname)

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

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

Convert tn to a TensorNetwork2D,

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

Convert tn to a TensorNetwork3D,

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

Heisenberg Hamiltonian in

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

Ising Hamiltonian in

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

The many-body-localized spin hamiltonian in

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

XY-Hamiltonian in

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

Heisenberg Hamiltonian in

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

Ising Hamiltonian in

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

Heisenberg Hamiltonian in

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

Heisenberg Hamiltonian in

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

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

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

Generate a random tensor with specified shape and inds.

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

Create a random k-SAT instance.

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

Get the tensor representing the COPY operation with dimension size

bonds(t1, t2)

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

bonds_size(t1, t2)

Get the size of the bonds linking tensors or tensor networks t1 and

connect(t1, t2, ax1, ax2)

Connect two tensors by setting a shared index for the specified

group_inds(t1, t2)

Group bonds into left only, shared, and right only. If t1 or t2

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

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

rand_uuid([base])

Return a guaranteed unique, shortish identifier, optional appended

tensor_balance_bond(t1, t2[, smudge])

Gauge the bond between two tensors such that the norm of the 'columns'

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

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

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

Inplace compress between the two single tensors. It follows the

tensor_contract(*tensors[, output_inds, optimize, ...])

Contract a collection of tensors into a scalar or tensor, automatically

tensor_direct_product(T1, T2[, sum_inds, inplace])

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

tensor_fuse_squeeze(t1, t2[, squeeze, gauges])

If t1 and t2 share more than one bond fuse it, and if the size

tensor_network_distance(tnA, tnB[, xAA, xAB, xBB, ...])

Compute the Frobenius norm distance between two tensor networks:

tensor_network_fit_als(tn, tn_target[, tags, steps, ...])

Optimize the fit of tn with respect to tn_target using

tensor_network_fit_autodiff(tn, tn_target[, steps, ...])

Optimize the fit of tn with respect to tn_target using

tensor_network_gate_inds(self, G, inds[, contract, ...])

Apply the 'gate' G to indices inds, propagating them to the

tensor_network_sum(tnA, tnB[, inplace])

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

tensor_split(T, left_inds[, method, get, absorb, ...])

Decompose this tensor into two tensors.

Attributes

class quimb.tensor.Circuit(N=None, psi0=None, gate_opts=None, gate_contract='auto-split-gate', gate_propagate_tags='register', tags=None, psi0_dtype='complex128', psi0_tag='PSI0', bra_site_ind_id='b{}')[source]

Class for simulating quantum circuits using tensor networks.

Parameters:
  • N (int, optional) – The number of qubits.

  • psi0 (TensorNetwork1DVector, optional) – The initial state, assumed to be |00000....0> if not given. The state is always copied and the tag PSI0 added.

  • gate_opts (dict_like, optional) – Default keyword arguments to supply to each gate_TN_1D() call during the circuit.

  • tags (str or sequence of str, optional) – Tag(s) to add to the initial wavefunction tensors (whether these are propagated to the rest of the circuit’s tensors depends on gate_opts).

  • psi0_dtype (str, optional) – Ensure the initial state has this dtype.

  • psi0_tag (str, optional) – Ensure the initial state has this tag.

  • bra_site_ind_id (str, optional) – Use this to label ‘bra’ site indices when creating certain (mostly internal) intermediate tensor networks.

psi

The current wavefunction.

Type:

TensorNetwork1DVector

Examples

Create 3-qubit GHZ-state:

>>> qc = qtn.Circuit(3)
>>> gates = [
        ('H', 0),
        ('H', 1),
        ('CNOT', 1, 2),
        ('CNOT', 0, 2),
        ('H', 0),
        ('H', 1),
        ('H', 2),
    ]
>>> qc.apply_gates(gates)
>>> qc.psi
<TensorNetwork1DVector(tensors=12, indices=14, L=3, max_bond=2)>
>>> qc.psi.to_dense().round(4)
qarray([[ 0.7071+0.j],
        [ 0.    +0.j],
        [ 0.    +0.j],
        [-0.    +0.j],
        [-0.    +0.j],
        [ 0.    +0.j],
        [ 0.    +0.j],
        [ 0.7071+0.j]])
>>> for b in qc.sample(10):
...     print(b)
000
000
111
000
111
111
000
111
000
000
property psi

Tensor network representation of the wavefunction.

property uni
property num_gates
from_qasm[source]
from_qasm_file[source]
from_qasm_url[source]
amplitude_tn[source]
partial_trace_rehearse[source]
partial_trace_tn[source]
local_expectation_rehearse[source]
local_expectation_tn[source]
compute_marginal_rehearse[source]
compute_marginal_tn[source]
sample_tns[source]
sample_chaotic_tn[source]
to_dense_rehearse[source]
to_dense_tn[source]
classmethod from_qsim_str(contents, **circuit_opts)[source]

Generate a Circuit instance from a ‘qsim’ string.

classmethod from_qsim_file(fname, **circuit_opts)[source]

Generate a Circuit instance from a ‘qsim’ file.

The qsim file format is described here: https://quantumai.google/qsim/input_format.

classmethod from_qsim_url(url, **circuit_opts)[source]

Generate a Circuit instance from a ‘qsim’ url.

classmethod from_openqasm2_str(contents, **circuit_opts)[source]

Generate a Circuit instance from an OpenQASM 2.0 string.

classmethod from_openqasm2_file(fname, **circuit_opts)[source]

Generate a Circuit instance from an OpenQASM 2.0 file.

classmethod from_openqasm2_url(url, **circuit_opts)[source]

Generate a Circuit instance from an OpenQASM 2.0 url.

_init_state(N, dtype='complex128')[source]
_apply_gate(gate, tags=None, **gate_opts)[source]

Apply a Gate to this Circuit.

apply_gate(gate_id, *gate_args, params=None, qubits=None, controls=None, gate_round=None, parametrize=False, **gate_opts)[source]

Apply a single gate to this tensor network quantum circuit. If gate_round is supplied the tensor(s) added will be tagged with 'ROUND_{gate_round}'. Alternatively, putting an integer first like so:

circuit.apply_gate(10, 'H', 7)

Is automatically translated to:

circuit.apply_gate('H', 7, gate_round=10)
Parameters:
  • gate_id (Gate, str, or array_like) –

    Which gate to apply. This can be:

    • A Gate instance, i.e. with parameters and qubits already specified.

    • A string, e.g. 'H', 'U3', etc. in which case gate_args should be supplied with (*params, *qubits).

    • A raw array, in which case gate_args should be supplied with (*qubits,).

  • gate_args (list[str]) – The arguments to supply to it.

  • gate_round (int, optional) – The gate round. If gate_id is integer-like, will also be taken from here, with then gate_id, gate_args = gate_args[0], gate_args[1:].

  • gate_opts – Supplied to the gate function, options here will override the default gate_opts.

apply_gate_raw(U, where, gate_round=None, **gate_opts)[source]

Apply the raw array U as a gate on qubits in where. It will be assumed to be unitary for the sake of computing reverse lightcones.

apply_gates(gates, **gate_opts)[source]

Apply a sequence of gates to this tensor network quantum circuit.

Parameters:
h(i, gate_round=None, **kwargs)[source]
x(i, gate_round=None, **kwargs)[source]
y(i, gate_round=None, **kwargs)[source]
z(i, gate_round=None, **kwargs)[source]
s(i, gate_round=None, **kwargs)[source]
sdg(i, gate_round=None, **kwargs)[source]
t(i, gate_round=None, **kwargs)[source]
tdg(i, gate_round=None, **kwargs)[source]
x_1_2(i, gate_round=None, **kwargs)[source]
y_1_2(i, gate_round=None, **kwargs)[source]
z_1_2(i, gate_round=None, **kwargs)[source]
w_1_2(i, gate_round=None, **kwargs)[source]
hz_1_2(i, gate_round=None, **kwargs)[source]
cnot(i, j, gate_round=None, **kwargs)[source]
cx(i, j, gate_round=None, **kwargs)[source]
cy(i, j, gate_round=None, **kwargs)[source]
cz(i, j, gate_round=None, **kwargs)[source]
iswap(i, j, gate_round=None, **kwargs)[source]
iden(i, gate_round=None)[source]
swap(i, j, gate_round=None, **kwargs)[source]
rx(theta, i, gate_round=None, parametrize=False, **kwargs)[source]
ry(theta, i, gate_round=None, parametrize=False, **kwargs)[source]
rz(theta, i, gate_round=None, parametrize=False, **kwargs)[source]
u3(theta, phi, lamda, i, gate_round=None, parametrize=False, **kwargs)[source]
u2(phi, lamda, i, gate_round=None, parametrize=False, **kwargs)[source]
u1(lamda, i, gate_round=None, parametrize=False, **kwargs)[source]
cu3(theta, phi, lamda, i, j, gate_round=None, parametrize=False, **kwargs)[source]
cu2(phi, lamda, i, j, gate_round=None, parametrize=False, **kwargs)[source]
cu1(lamda, i, j, gate_round=None, parametrize=False, **kwargs)[source]
fsim(theta, phi, i, j, gate_round=None, parametrize=False, **kwargs)[source]
fsimg(theta, zeta, chi, gamma, phi, i, j, gate_round=None, parametrize=False, **kwargs)[source]
givens(theta, i, j, gate_round=None, parametrize=False, **kwargs)[source]
rxx(theta, i, j, gate_round=None, parametrize=False, **kwargs)[source]
ryy(theta, i, j, gate_round=None, parametrize=False, **kwargs)[source]
rzz(theta, i, j, gate_round=None, parametrize=False, **kwargs)[source]
crx(theta, i, j, gate_round=None, parametrize=False, **kwargs)[source]
cry(theta, i, j, gate_round=None, parametrize=False, **kwargs)[source]
crz(theta, i, j, gate_round=None, parametrize=False, **kwargs)[source]
su4(theta1, phi1, lamda1, theta2, phi2, lamda2, theta3, phi3, lamda3, theta4, phi4, lamda4, t1, t2, t3, i, j, gate_round=None, parametrize=False, **kwargs)[source]
ccx(i, j, k, gate_round=None, **kwargs)[source]
ccnot(i, j, k, gate_round=None, **kwargs)[source]
toffoli(i, j, k, gate_round=None, **kwargs)[source]
ccy(i, j, k, gate_round=None, **kwargs)[source]
ccz(i, j, k, gate_round=None, **kwargs)[source]
cswap(i, j, k, gate_round=None, **kwargs)[source]
fredkin(i, j, k, gate_round=None, **kwargs)[source]
get_uni(transposed=False)[source]

Tensor network representation of the unitary operator (i.e. with the initial state removed).

get_reverse_lightcone_tags(where)[source]

Get the tags of gates in this circuit corresponding to the ‘reverse’ lightcone propagating backwards from registers in where.

Parameters:

where (int or sequence of int) – The register or register to get the reverse lightcone of.

Returns:

The sequence of gate tags (GATE_{i}, …) corresponding to the lightcone.

Return type:

tuple[str]

get_psi_reverse_lightcone(where, keep_psi0=False)[source]

Get just the bit of the wavefunction in the reverse lightcone of sites in where - i.e. causally linked.

Parameters:
  • where (int, or sequence of int) – The sites to propagate the the lightcone back from, supplied to get_reverse_lightcone_tags().

  • keep_psi0 (bool, optional) – Keep the tensors corresponding to the initial wavefunction regardless of whether they are outside of the lightcone.

Returns:

psi_lc

Return type:

TensorNetwork1DVector

_maybe_init_storage()[source]
get_psi_simplified(seq='ADCRS', atol=1e-12, equalize_norms=False)[source]

Get the full wavefunction post local tensor network simplification.

Parameters:
  • seq (str, optional) – Which local tensor network simplifications to perform and in which order, see full_simplify().

  • atol (float, optional) – The tolerance with which to compare to zero when applying full_simplify().

  • equalize_norms (bool, optional) – Actively renormalize tensor norms during simplification.

Returns:

psi

Return type:

TensorNetwork1DVector

get_rdm_lightcone_simplified(where, seq='ADCRS', atol=1e-12, equalize_norms=False)[source]

Get a simplified TN of the norm of the wavefunction, with gates outside reverse lightcone of where cancelled, and physical indices within where preserved so that they can be fixed (sliced) or used as output indices.

Parameters:
  • where (int or sequence of int) – The region assumed to be the target density matrix essentially. Supplied to get_reverse_lightcone_tags().

  • seq (str, optional) – Which local tensor network simplifications to perform and in which order, see full_simplify().

  • atol (float, optional) – The tolerance with which to compare to zero when applying full_simplify().

  • equalize_norms (bool, optional) – Actively renormalize tensor norms during simplification.

Return type:

TensorNetwork

amplitude(b, optimize='auto-hq', simplify_sequence='ADCRS', simplify_atol=1e-12, simplify_equalize_norms=False, backend=None, dtype='complex128', rehearse=False)[source]

Get the amplitude coefficient of bitstring b.

\[c_b = \langle b | \psi \rangle\]
Parameters:
  • b (str or sequence of int) – The bitstring to compute the transition amplitude for.

  • optimize (str, optional) – Contraction path optimizer to use for the amplitude, can be a non-reusable path optimizer as only called once (though path won’t be cached for later use in that case).

  • simplify_sequence (str, optional) – Which local tensor network simplifications to perform and in which order, see full_simplify().

  • simplify_atol (float, optional) – The tolerance with which to compare to zero when applying full_simplify().

  • simplify_equalize_norms (bool, optional) – Actively renormalize tensor norms during simplification.

  • backend (str, optional) – Backend to perform the contraction with, e.g. 'numpy', 'cupy' or 'jax'. Passed to cotengra.

  • dtype (str, optional) – Data type to cast the TN to before contraction.

  • rehearse (bool or "tn", optional) – If True, generate and cache the simplified tensor network and contraction tree but don’t actually perform the contraction. Returns a dict with keys "tn" and 'tree' with the tensor network that will be contracted and the corresponding contraction tree if so.

amplitude_rehearse(b='random', simplify_sequence='ADCRS', simplify_atol=1e-12, simplify_equalize_norms=False, optimize='auto-hq', dtype='complex128', rehearse=True)[source]

Perform just the tensor network simplifications and contraction tree finding associated with computing a single amplitude (caching the results) but don’t perform the actual contraction.

Parameters:
  • b ('random', str or sequence of int) – The bitstring to rehearse computing the transition amplitude for, if 'random' (the default) a random bitstring will be used.

  • optimize (str, optional) – Contraction path optimizer to use for the marginal, can be a non-reusable path optimizer as only called once (though path won’t be cached for later use in that case).

  • simplify_sequence (str, optional) – Which local tensor network simplifications to perform and in which order, see full_simplify().

  • simplify_atol (float, optional) – The tolerance with which to compare to zero when applying full_simplify().

  • simplify_equalize_norms (bool, optional) – Actively renormalize tensor norms during simplification.

  • backend (str, optional) – Backend to perform the marginal contraction with, e.g. 'numpy', 'cupy' or 'jax'. Passed to cotengra.

  • dtype (str, optional) – Data type to cast the TN to before contraction.

Return type:

dict

partial_trace(keep, optimize='auto-hq', simplify_sequence='ADCRS', simplify_atol=1e-12, simplify_equalize_norms=False, backend=None, dtype='complex128', rehearse=False)[source]

Perform the partial trace on the circuit wavefunction, retaining only qubits in keep, and making use of reverse lightcone cancellation:

\[\rho_{\bar{q}} = Tr_{\bar{p}} |\psi_{\bar{q}} \rangle \langle \psi_{\bar{q}}|\]

Where \(\bar{q}\) is the set of qubits to keep, \(\psi_{\bar{q}}\) is the circuit wavefunction only with gates in the causal cone of this set, and \(\bar{p}\) is the remaining qubits.

Parameters:
  • keep (int or sequence of int) – The qubit(s) to keep as we trace out the rest.

  • optimize (str, optional) – Contraction path optimizer to use for the reduced density matrix, can be a non-reusable path optimizer as only called once (though path won’t be cached for later use in that case).

  • simplify_sequence (str, optional) – Which local tensor network simplifications to perform and in which order, see full_simplify().

  • simplify_atol (float, optional) – The tolerance with which to compare to zero when applying full_simplify().

  • simplify_equalize_norms (bool, optional) – Actively renormalize tensor norms during simplification.

  • backend (str, optional) – Backend to perform the marginal contraction with, e.g. 'numpy', 'cupy' or 'jax'. Passed to cotengra.

  • dtype (str, optional) – Data type to cast the TN to before contraction.

  • rehearse (bool or "tn", optional) – If True, generate and cache the simplified tensor network and contraction tree but don’t actually perform the contraction. Returns a dict with keys "tn" and 'tree' with the tensor network that will be contracted and the corresponding contraction tree if so.

Return type:

array or dict

local_expectation(G, where, optimize='auto-hq', simplify_sequence='ADCRS', simplify_atol=1e-12, simplify_equalize_norms=False, backend=None, dtype='complex128', rehearse=False)[source]

Compute the a single expectation value of operator G, acting on sites where, making use of reverse lightcone cancellation.

\[\langle \psi_{\bar{q}} | G_{\bar{q}} | \psi_{\bar{q}} \rangle\]

where \(\bar{q}\) is the set of qubits \(G\) acts one and \(\psi_{\bar{q}}\) is the circuit wavefunction only with gates in the causal cone of this set. If you supply a tuple or list of gates then the expectations will be computed simultaneously.

Parameters:
  • G (array or sequence[array]) – The raw operator(s) to find the expectation of.

  • where (int or sequence of int) – Which qubits the operator acts on.

  • optimize (str, optional) – Contraction path optimizer to use for the local expectation, can be a non-reusable path optimizer as only called once (though path won’t be cached for later use in that case).

  • simplify_sequence (str, optional) – Which local tensor network simplifications to perform and in which order, see full_simplify().

  • simplify_atol (float, optional) – The tolerance with which to compare to zero when applying full_simplify().

  • simplify_equalize_norms (bool, optional) – Actively renormalize tensor norms during simplification.

  • backend (str, optional) – Backend to perform the marginal contraction with, e.g. 'numpy', 'cupy' or 'jax'. Passed to cotengra.

  • dtype (str, optional) – Data type to cast the TN to before contraction.

  • gate_opts (None or dict_like) – Options to use when applying G to the wavefunction.

  • rehearse (bool or "tn", optional) – If True, generate and cache the simplified tensor network and contraction tree but don’t actually perform the contraction. Returns a dict with keys 'tn' and 'tree' with the tensor network that will be contracted and the corresponding contraction tree if so.

Return type:

scalar, tuple[scalar] or dict

compute_marginal(where, fix=None, optimize='auto-hq', backend=None, dtype='complex64', simplify_sequence='ADCRS', simplify_atol=1e-06, simplify_equalize_norms=True, rehearse=False)[source]

Compute the probability tensor of qubits in where, given possibly fixed qubits in fix and tracing everything else having removed redundant unitary gates.

Parameters:
  • where (sequence of int) – The qubits to compute the marginal probability distribution of.

  • fix (None or dict[int, str], optional) – Measurement results on other qubits to fix.

  • optimize (str, optional) – Contraction path optimizer to use for the marginal, can be a non-reusable path optimizer as only called once (though path won’t be cached for later use in that case).

  • backend (str, optional) – Backend to perform the marginal contraction with, e.g. 'numpy', 'cupy' or 'jax'. Passed to cotengra.

  • dtype (str, optional) – Data type to cast the TN to before contraction.

  • simplify_sequence (str, optional) – Which local tensor network simplifications to perform and in which order, see full_simplify().

  • simplify_atol (float, optional) – The tolerance with which to compare to zero when applying full_simplify().

  • simplify_equalize_norms (bool, optional) – Actively renormalize tensor norms during simplification.

  • rehearse (bool or "tn", optional) – Whether to perform the marginal contraction or just return the associated TN and contraction tree.

calc_qubit_ordering(qubits=None, method='greedy-lightcone')[source]

Get a order to measure qubits in, by greedily choosing whichever has the smallest reverse lightcone followed by whichever expands this lightcone least.

Parameters:

qubits (None or sequence of int) – The qubits to generate a lightcone ordering for, if None, assume all qubits.

Returns:

The order to ‘measure’ qubits in.

Return type:

tuple[int]

_parse_qubits_order(qubits=None, order=None)[source]

Simply initializes the default of measuring all qubits, and the default order, or checks that order is a permutation of qubits.

_group_order(order, group_size=1)[source]

Take the qubit ordering order and batch it in groups of size group_size, sorting the qubits (for caching reasons) within each group.

sample(C, qubits=None, order=None, group_size=1, max_marginal_storage=2**20, seed=None, optimize='auto-hq', backend=None, dtype='complex64', simplify_sequence='ADCRS', simplify_atol=1e-06, simplify_equalize_norms=False)[source]

Sample the circuit given by gates, C times, using lightcone cancelling and caching marginal distribution results. This is a generator. This proceeds as a chain of marginal computations.

Assuming we have group_size=1, and some ordering of the qubits, \(\{q_0, q_1, q_2, q_3, \ldots\}\) we first compute:

\[p(q_0) = \mathrm{diag} \mathrm{Tr}_{1, 2, 3,\ldots} | \psi_{0} \rangle \langle \psi_{0} |\]

I.e. simply the probability distribution on a single qubit, conditioned on nothing. The subscript on \(\psi\) refers to the fact that we only need gates from the causal cone of qubit 0. From this we can sample an outcome, either 0 or 1, if we call this \(r_0\) we can then move on to the next marginal:

\[p(q_1 | r_0) = \mathrm{diag} \mathrm{Tr}_{2, 3,\ldots} \langle r_0 | \psi_{0, 1} \rangle \langle \psi_{0, 1} | r_0 \rangle\]

I.e. the probability distribution of the next qubit, given our prior result. We can sample from this to get \(r_1\). Then we compute:

\[p(q_2 | r_0 r_1) = \mathrm{diag} \mathrm{Tr}_{3,\ldots} \langle r_0 r_1 | \psi_{0, 1, 2} \rangle \langle \psi_{0, 1, 2} | r_0 r_1 \rangle\]

Eventually we will reach the ‘final marginal’, which we can compute as

\[|\langle r_0 r_1 r_2 r_3 \ldots | \psi \rangle|^2\]

since there is nothing left to trace out.

Parameters:
  • C (int) – The number of times to sample.

  • qubits (None or sequence of int, optional) – Which qubits to measure, defaults (None) to all qubits.

  • order (None or sequence of int, optional) – Which order to measure the qubits in, defaults (None) to an order based on greedily expanding the smallest reverse lightcone. If specified it should be a permutation of qubits.

  • group_size (int, optional) – How many qubits to group together into marginals, the larger this is the fewer marginals need to be computed, which can be faster at the cost of higher memory. The marginal themselves will each be of size 2**group_size.

  • max_marginal_storage (int, optional) – The total cumulative number of marginal probabilites to cache, once this is exceeded caching will be turned off.

  • seed (None or int, optional) – A random seed, passed to numpy.random.seed if given.

  • optimize (str, optional) – Contraction path optimizer to use for the marginals, shouldn’t be a non-reusable path optimizer as called on many different TNs. Passed to cotengra.array_contract_tree().

  • backend (str, optional) – Backend to perform the marginal contraction with, e.g. 'numpy', 'cupy' or 'jax'. Passed to cotengra.

  • dtype (str, optional) – Data type to cast the TN to before contraction.

  • simplify_sequence (str, optional) – Which local tensor network simplifications to perform and in which order, see full_simplify().

  • simplify_atol (float, optional) – The tolerance with which to compare to zero when applying full_simplify().

  • simplify_equalize_norms (bool, optional) – Actively renormalize tensor norms during simplification.

Yields:

bitstrings (sequence of str)

sample_rehearse(qubits=None, order=None, group_size=1, result=None, optimize='auto-hq', simplify_sequence='ADCRS', simplify_atol=1e-06, simplify_equalize_norms=False, rehearse=True, progbar=False)[source]

Perform the preparations and contraction tree findings for sample(), caching various intermedidate objects, but don’t perform the main contractions.

Parameters:
  • qubits (None or sequence of int, optional) – Which qubits to measure, defaults (None) to all qubits.

  • order (None or sequence of int, optional) – Which order to measure the qubits in, defaults (None) to an order based on greedily expanding the smallest reverse lightcone.

  • group_size (int, optional) – How many qubits to group together into marginals, the larger this is the fewer marginals need to be computed, which can be faster at the cost of higher memory. The marginal’s size itself is exponential in group_size.

  • result (None or dict[int, str], optional) – Explicitly check the computational cost of this result, assumed to be all zeros if not given.

  • optimize (str, optional) – Contraction path optimizer to use for the marginals, shouldn’t be a non-reusable path optimizer as called on many different TNs. Passed to cotengra.array_contract_tree().

  • simplify_sequence (str, optional) – Which local tensor network simplifications to perform and in which order, see full_simplify().

  • simplify_atol (float, optional) – The tolerance with which to compare to zero when applying full_simplify().

  • simplify_equalize_norms (bool, optional) – Actively renormalize tensor norms during simplification.

  • progbar (bool, optional) – Whether to show the progress of finding each contraction tree.

Returns:

One contraction tree object per grouped marginal computation. The keys of the dict are the qubits the marginal is computed for, the values are a dict containing a representative simplified tensor network (key: ‘tn’) and the main contraction tree (key: ‘tree’).

Return type:

dict[tuple[int], dict]

sample_chaotic(C, marginal_qubits, max_marginal_storage=2**20, seed=None, optimize='auto-hq', backend=None, dtype='complex64', simplify_sequence='ADCRS', simplify_atol=1e-06, simplify_equalize_norms=False)[source]

Sample from this circuit, assuming it to be chaotic. Which is to say, only compute and sample correctly from the final marginal, assuming that the distribution on the other qubits is uniform. Given marginal_qubits=5 for instance, for each sample a random bit-string \(r_0 r_1 r_2 \ldots r_{N - 6}\) for the remaining \(N - 5\) qubits will be chosen, then the final marginal will be computed as

\[p(q_{N-5}q_{N-4}q_{N-3}q_{N-2}q_{N-1} | r_0 r_1 r_2 \ldots r_{N-6}) = |\langle r_0 r_1 r_2 \ldots r_{N - 6} | \psi \rangle|^2\]

and then sampled from. Note the expression on the right hand side has 5 open indices here and so is a tensor, however if marginal_qubits is not too big then the cost of contracting this is very similar to a single amplitude.

Note

This method assumes the circuit is chaotic, if its not, then the samples produced will not be an accurate representation of the probability distribution.

Parameters:
  • C (int) – The number of times to sample.

  • marginal_qubits (int or sequence of int) – The number of qubits to treat as marginal, or the actual qubits. If an int is given then the qubits treated as marginal will be circuit.calc_qubit_ordering()[:marginal_qubits].

  • seed (None or int, optional) – A random seed, passed to numpy.random.seed if given.

  • optimize (str, optional) – Contraction path optimizer to use for the marginal, can be a non-reusable path optimizer as only called once (though path won’t be cached for later use in that case).

  • backend (str, optional) – Backend to perform the marginal contraction with, e.g. 'numpy', 'cupy' or 'jax'. Passed to cotengra.

  • dtype (str, optional) – Data type to cast the TN to before contraction.

  • simplify_sequence (str, optional) – Which local tensor network simplifications to perform and in which order, see full_simplify().

  • simplify_atol (float, optional) – The tolerance with which to compare to zero when applying full_simplify().

  • simplify_equalize_norms (bool, optional) – Actively renormalize tensor norms during simplification.

Yields:

str

sample_chaotic_rehearse(marginal_qubits, result=None, optimize='auto-hq', simplify_sequence='ADCRS', simplify_atol=1e-06, simplify_equalize_norms=False, dtype='complex64', rehearse=True)[source]

Rehearse chaotic sampling (perform just the TN simplifications and contraction tree finding).

Parameters:
  • marginal_qubits (int or sequence of int) – The number of qubits to treat as marginal, or the actual qubits. If an int is given then the qubits treated as marginal will be circuit.calc_qubit_ordering()[:marginal_qubits].

  • result (None or dict[int, str], optional) – Explicitly check the computational cost of this result, assumed to be all zeros if not given.

  • optimize (str, optional) – Contraction path optimizer to use for the marginal, can be a non-reusable path optimizer as only called once (though path won’t be cached for later use in that case).

  • simplify_sequence (str, optional) – Which local tensor network simplifications to perform and in which order, see full_simplify().

  • simplify_atol (float, optional) – The tolerance with which to compare to zero when applying full_simplify().

  • simplify_equalize_norms (bool, optional) – Actively renormalize tensor norms during simplification.

  • dtype (str, optional) – Data type to cast the TN to before contraction.

Returns:

The contraction path information for the main computation, the key is the qubits that formed the final marginal. The value is itself a dict with keys 'tn' - a representative tensor network - and 'tree' - the contraction tree.

Return type:

dict[tuple[int], dict]

to_dense(reverse=False, optimize='auto-hq', simplify_sequence='R', simplify_atol=1e-12, simplify_equalize_norms=False, backend=None, dtype=None, rehearse=False)[source]

Generate the dense representation of the final wavefunction.

Parameters:
  • reverse (bool, optional) – Whether to reverse the order of the subsystems, to match the convention of qiskit for example.

  • optimize (str, optional) – Contraction path optimizer to use for the contraction, can be a non-reusable path optimizer as only called once (though path won’t be cached for later use in that case).

  • dtype (str, optional) – If given, convert the tensors to this dtype prior to contraction.

  • simplify_sequence (str, optional) – Which local tensor network simplifications to perform and in which order, see full_simplify().

  • simplify_atol (float, optional) – The tolerance with which to compare to zero when applying full_simplify().

  • simplify_equalize_norms (bool, optional) – Actively renormalize tensor norms during simplification.

  • backend (str, optional) – Backend to perform the contraction with, e.g. 'numpy', 'cupy' or 'jax'. Passed to cotengra.

  • dtype – Data type to cast the TN to before contraction.

  • rehearse (bool, optional) – If True, generate and cache the simplified tensor network and contraction tree but don’t actually perform the contraction. Returns a dict with keys 'tn' and 'tree' with the tensor network that will be contracted and the corresponding contraction tree if so.

Returns:

psi – The densely represented wavefunction with dtype data.

Return type:

qarray

simulate_counts(C, seed=None, reverse=False, **to_dense_opts)[source]

Simulate measuring all qubits in the computational basis many times. Unlike sample(), this generates all the samples simultaneously using the full wavefunction constructed from to_dense(), then calling simulate_counts().

Warning

Because this constructs the full wavefunction it always requires exponential memory in the number of qubits, regardless of circuit depth and structure.

Parameters:
  • C (int) – The number of ‘experimental runs’, i.e. total counts.

  • seed (int, optional) – A seed for reproducibility.

  • reverse (bool, optional) – Whether to reverse the order of the subsystems, to match the convention of qiskit for example.

  • to_dense_opts – Suppled to to_dense().

Returns:

results – The number of recorded counts for each

Return type:

dict[str, int]

schrodinger_contract(*args, **contract_opts)[source]
xeb(samples_or_counts, cache=None, cache_maxsize=2**20, progbar=False, **amplitude_opts)[source]

Compute the linear cross entropy benchmark (XEB) for samples or counts, amplitude per amplitude.

Parameters:
  • samples_or_counts (Iterable[str] or Dict[str, int]) – Either the raw bitstring samples or a dict mapping bitstrings to the number of counts observed.

  • cache (dict, optional) – A dictionary to store the probabilities in, if not supplied quimb.utils.LRU(cache_maxsize) will be used.

  • cache_maxsize – The maximum size of the cache to be used.

  • optional – The maximum size of the cache to be used.

  • progbar – Whether to show progress as the bitstrings are iterated over.

  • optional – Whether to show progress as the bitstrings are iterated over.

  • amplitude_opts – Supplied to amplitude().

xeb_ex(optimize='auto-hq', simplify_sequence='R', simplify_atol=1e-12, simplify_equalize_norms=False, dtype=None, backend=None, autojit=False, progbar=False, **contract_opts)[source]

Compute the exactly expected XEB for this circuit. The main feature here is that if you supply a cotengra optimizer that searches for sliced indices then the XEB will be computed without constructing the full wavefunction.

Parameters:
  • optimize (str or PathOptimizer, optional) – Contraction path optimizer.

  • simplify_sequence (str, optional) – Simplifications to apply to tensor network prior to contraction.

  • simplify_sequence – Which local tensor network simplifications to perform and in which order, see full_simplify().

  • simplify_atol (float, optional) – The tolerance with which to compare to zero when applying full_simplify().

  • dtype (str, optional) – Data type to cast the TN to before contraction.

  • backend (str, optional) – Convert tensors to, and then use contractions from, this library.

  • autojit (bool, optional) – Apply autoray.autojit to the contraciton and map-reduce.

  • progbar (bool, optional) – Show progress in terms of number of wavefunction chunks processed.

update_params_from(tn)[source]

Assuming tn is a tensor network with tensors tagged GATE_{i} corresponding to this circuit (e.g. from circ.psi or circ.uni) but with updated parameters, update the current circuit parameters and tensors with those values.

This is an inplace modification of the Circuit.

Parameters:

tn (TensorNetwork) – The tensor network to find the updated parameters from.

__repr__()[source]

Return repr(self).

class quimb.tensor.CircuitDense(N=None, psi0=None, gate_opts=None, gate_contract=True, tags=None)[source]

Bases: Circuit

Quantum circuit simulation keeping the state in full dense form.

property psi

Tensor network representation of the wavefunction.

property uni
calc_qubit_ordering(qubits=None)[source]

Qubit ordering doesn’t matter for a dense wavefunction.

get_psi_reverse_lightcone(where, keep_psi0=False)[source]

Override get_psi_reverse_lightcone as for a dense wavefunction the lightcone is not meaningful.

class quimb.tensor.CircuitMPS(N=None, psi0=None, gate_opts=None, gate_contract='swap+split', **circuit_opts)[source]

Bases: Circuit

Quantum circuit simulation keeping the state always in a MPS form. If you think the circuit will not build up much entanglement, or you just want to keep a rigorous handle on how much entanglement is present, this can be useful.

property psi

Tensor network representation of the wavefunction.

property uni
_init_state(N, dtype='complex128')[source]
calc_qubit_ordering(qubits=None)[source]

MPS already has a natural ordering.

get_psi_reverse_lightcone(where, keep_psi0=False)[source]

Override get_psi_reverse_lightcone as for an MPS the lightcone is not meaningful.

quimb.tensor.circ_ansatz_1D_brickwork(n, depth, cyclic=False, gate2='cz', seed=None, **circuit_opts)[source]

A 1D circuit ansatz with odd and even layers of entangling gates interleaved with U3 single qubit unitaries:

|  |  |  |  |
|  u  u  u  u
u  o++o  o++o
|  u  u  u  |
o++o  o++o  u
|  u  u  u  |
u  o++o  o++o
|  u  u  u  |
o++o  o++o  u
|  u  u  u  u
u  o++o  o++o
|  u  u  u  |
o++o  o++o  u
u  u  u  u  |
|  |  |  |  |
Parameters:
  • n (int) – The number of qubits.

  • depth (int) – The number of entangling gates per pair.

  • cyclic (bool, optional) – Whether to add entangling gates between qubits 0 and n - 1.

  • gate2 ({'cx', 'cy', 'cz', 'iswap', ..., str}, optional) – The gate to use for the entanling pairs.

  • seed (int, optional) – Random seed for parameters.

  • opts – Supplied to gates_to_param_circuit().

Return type:

Circuit

quimb.tensor.circ_ansatz_1D_rand(n, depth, seed=None, cyclic=False, gate2='cz', avoid_doubling=True, **circuit_opts)[source]

A 1D circuit ansatz with randomly place entangling gates interleaved with U3 single qubit unitaries.

Parameters:
  • n (int) – The number of qubits.

  • depth (int) – The number of entangling gates per pair.

  • seed (int, optional) – Random seed.

  • cyclic (bool, optional) – Whether to add entangling gates between qubits 0 and n - 1.

  • gate2 ({'cx', 'cy', 'cz', 'iswap', ..., str}, optional) – The gate to use for the entanling pairs.

  • avoid_doubling (bool, optional) – Whether to avoid placing an entangling gate directly above the same entangling gate (there will still be single qubit gates interleaved).

  • opts – Supplied to gates_to_param_circuit().

Return type:

Circuit

quimb.tensor.circ_ansatz_1D_zigzag(n, depth, gate2='cz', seed=None, **circuit_opts)[source]

A 1D circuit ansatz with forward and backward layers of entangling gates interleaved with U3 single qubit unitaries:

|  |  |  |
u  u  |  |
o++o  u  |
|  |  |  u
|  o++o  |
|  |  u  |
|  |  o++o
u  u  u  u
|  |  o++o
|  |  u  |
|  o++o  |
|  u  |  u
o++o  u  |
u  u  |  |
|  |  |  |
Parameters:
  • n (int) – The number of qubits.

  • depth (int) – The number of entangling gates per pair.

  • gate2 ({'cx', 'cy', 'cz', 'iswap', ..., str}, optional) – The gate to use for the entanling pairs.

  • seed (int, optional) – Random seed for parameters.

  • opts – Supplied to gates_to_param_circuit().

Return type:

Circuit

quimb.tensor.circ_qaoa(terms, depth, gammas, betas, **circuit_opts)[source]

Generate the QAOA circuit for weighted graph described by terms.

\[|{\bar{\gamma}, \bar{\beta}}\rangle = U_B (\beta _p) U_C (\gamma _p) \cdots U_B (\beta _1) U_C (\gamma _1) |{+}\rangle\]

with

\[U_C (\gamma) = e^{-i \gamma \mathcal{C}} = \prod \limits_{i, j \in E(G)} e^{-i \gamma w_{i j} Z_i Z_j}\]

and

\[U_B (\beta) = \prod \limits_{i \in G} e^{-i \beta X_i}\]
Parameters:
  • terms (dict[tuple[int], float]) – The mapping of integer pair keys (i, j) to the edge weight values, wij. The integers should be a contiguous range enumerated from zero, with the total number of qubits being inferred from this.

  • depth (int) – The number of layers of gates to apply, p above.

  • gammas (iterable of float) – The interaction angles for each layer.

  • betas (iterable of float) – The rotation angles for each layer.

  • circuit_opts – Supplied to Circuit. Note gate_opts={'contract': False} is set by default (it can be overridden) since the RZZ gate, even though it has a rank-2 decomposition, is also diagonal.

quimb.tensor.array_contract(arrays, inputs, output=None, optimize=None, backend=None, **kwargs)[source]
quimb.tensor.contract_backend(backend, set_globally=False)[source]

A context manager to temporarily set the default backend used for tensor contractions, via ‘cotengra’. By default, this only sets the contract backend for the current thread.

Parameters:

set_globally (bool, optimize) – Whether to set the backend just for this thread, or for all threads. If you are entering the context, then using multithreading, you might want True.

quimb.tensor.contract_strategy(strategy, set_globally=False)[source]

A context manager to temporarily set the default contraction strategy supplied as optimize to cotengra. By default, this only sets the contract strategy for the current thread.

Parameters:

set_globally (bool, optimize) – Whether to set the strategy just for this thread, or for all threads. If you are entering the context, then using multithreading, you might want True.

quimb.tensor.get_contract_backend()[source]

Get the default backend used for tensor contractions, via ‘cotengra’.

quimb.tensor.get_contract_strategy()[source]

Get the default contraction strategy - the option supplied as optimize to cotengra.

quimb.tensor.get_symbol[source]
quimb.tensor.get_tensor_linop_backend()[source]

Get the default backend used for tensor network linear operators, via ‘cotengra’. This is different from the default contraction backend as the contractions are likely repeatedly called many times.

quimb.tensor.inds_to_eq(inputs, output=None)[source]

Turn input and output indices of any sort into a single ‘equation’ string where each index is a single ‘symbol’ (unicode character).

Parameters:
  • inputs (sequence of sequence of hashable) – The input indices per tensor.

  • output (sequence of hashable) – The output indices.

Returns:

eq – The string to feed to einsum/contract.

Return type:

str

quimb.tensor.set_contract_backend(backend)[source]

Set the default backend used for tensor contractions, via ‘cotengra’.

quimb.tensor.set_contract_strategy(strategy)[source]

Get the default contraction strategy - the option supplied as optimize to cotengra.

quimb.tensor.set_tensor_linop_backend(backend)[source]

Set the default backend used for tensor network linear operators, via ‘cotengra’. This is different from the default contraction backend as the contractions are likely repeatedly called many times.

quimb.tensor.tensor_linop_backend(backend, set_globally=False)[source]

A context manager to temporarily set the default backend used for tensor network linear operators, via ‘cotengra’. By default, this only sets the contract backend for the current thread.

Parameters:

set_globally (bool, optimize) – Whether to set the backend just for this thread, or for all threads. If you are entering the context, then using multithreading, you might want True.

quimb.tensor.edges_2d_hexagonal(Lx, Ly, cyclic=False, cells=None)[source]

Return the graph edges of a finite 2D hexagonal lattice. There are two sites per cell, and note the cells do not form a square tiling. The nodes (sites) are labelled like (i, j, s) for s in 'AB'.

Parameters:
  • Lx (int) – The number of cells along the x-direction.

  • Ly (int) – The number of cells along the y-direction.

  • cyclic (bool, optional) – Whether to use periodic boundary conditions.

  • cells (list, optional) – A list of cells to use. If not given the cells used are itertools.product(range(Lx), range(Ly)).

Returns:

edges

Return type:

list[((int, int, str), (int, int, str))]

quimb.tensor.edges_2d_kagome(Lx, Ly, cyclic=False, cells=None)[source]

Return the graph edges of a finite 2D kagome lattice. There are three sites per cell, and note the cells do not form a square tiling. The nodes (sites) are labelled like (i, j, s) for s in 'ABC'.

Parameters:
  • Lx (int) – The number of cells along the x-direction.

  • Ly (int) – The number of cells along the y-direction.

  • cyclic (bool, optional) – Whether to use periodic boundary conditions.

  • cells (list, optional) – A list of cells to use. If not given the cells used are itertools.product(range(Lx), range(Ly)).

Returns:

edges

Return type:

list[((int, int, str), (int, int, str))]

quimb.tensor.edges_2d_square(Lx, Ly, cyclic=False, cells=None)[source]

Return the graph edges of a finite 2D square lattice. The nodes (sites) are labelled like (i, j).

Parameters:
  • Lx (int) – The number of cells along the x-direction.

  • Ly (int) – The number of cells along the y-direction.

  • cyclic (bool, optional) – Whether to use periodic boundary conditions.

  • cells (list, optional) – A list of cells to use. If not given the cells used are itertools.product(range(Lx), range(Ly)).

Returns:

edges

Return type:

list[((int, int), (int, int))]

quimb.tensor.edges_2d_triangular(Lx, Ly, cyclic=False, cells=None)[source]

Return the graph edges of a finite 2D triangular lattice. There is a single site per cell, and note the cells do not form a square tiling. The nodes (sites) are labelled like (i, j).

Parameters:
  • Lx (int) – The number of cells along the x-direction.

  • Ly (int) – The number of cells along the y-direction.

  • cyclic (bool, optional) – Whether to use periodic boundary conditions.

  • cells (list, optional) – A list of cells to use. If not given the cells used are itertools.product(range(Lx), range(Ly)).

Returns:

edges

Return type:

list[((int, int), (int, int))]

quimb.tensor.edges_2d_triangular_rectangular(Lx, Ly, cyclic=False, cells=None)[source]

Return the graph edges of a finite 2D triangular lattice tiled in a rectangular geometry. There are two sites per rectangular cell. The nodes (sites) are labelled like (i, j, s) for s in 'AB'.

Parameters:
  • Lx (int) – The number of cells along the x-direction.

  • Ly (int) – The number of cells along the y-direction.

  • cyclic (bool, optional) – Whether to use periodic boundary conditions.

  • cells (list, optional) – A list of cells to use. If not given the cells used are itertools.product(range(Lx), range(Ly)).

Returns:

edges

Return type:

list[((int, int, s), (int, int, s))]

quimb.tensor.edges_3d_cubic(Lx, Ly, Lz, cyclic=False, cells=None)[source]

Return the graph edges of a finite 3D cubic lattice. The nodes (sites) are labelled like (i, j, k).

Parameters:
  • Lx (int) – The number of cells along the x-direction.

  • Ly (int) – The number of cells along the y-direction.

  • Lz (int) – The number of cells along the z-direction.

  • cyclic (bool, optional) – Whether to use periodic boundary conditions.

  • cells (list, optional) – A list of cells to use. If not given the cells used are itertools.product(range(Lx), range(Ly), range(Lz)).

Returns:

edges

Return type:

list[((int, int, int), (int, int, int))]

quimb.tensor.edges_3d_diamond(Lx, Ly, Lz, cyclic=False, cells=None)[source]

Return the graph edges of a finite 3D diamond lattice. There are two sites per cell, and note the cells do not form a cubic tiling. The nodes (sites) are labelled like (i, j, k, s) for s in 'AB'.

Parameters:
  • Lx (int) – The number of cells along the x-direction.

  • Ly (int) – The number of cells along the y-direction.

  • Lz (int) – The number of cells along the z-direction.

  • cyclic (bool, optional) – Whether to use periodic boundary conditions.

  • cells (list, optional) – A list of cells to use. If not given the cells used are itertools.product(range(Lx), range(Ly), range(Lz)).

Returns:

edges

Return type:

list[((int, int, int, str), (int, int, int, str))]

quimb.tensor.edges_3d_diamond_cubic(Lx, Ly, Lz, cyclic=False, cells=None)[source]

Return the graph edges of a finite 3D diamond lattice tiled in a cubic geometry. There are eight sites per cubic cell. The nodes (sites) are labelled like (i, j, k, s) for s in 'ABCDEFGH'.

Parameters:
  • Lx (int) – The number of cells along the x-direction.

  • Ly (int) – The number of cells along the y-direction.

  • Lz (int) – The number of cells along the z-direction.

  • cyclic (bool, optional) – Whether to use periodic boundary conditions.

  • cells (list, optional) – A list of cells to use. If not given the cells used are itertools.product(range(Lx), range(Ly), range(Lz)).

Returns:

edges

Return type:

list[((int, int, int, str), (int, int, int, str))]

quimb.tensor.edges_3d_pyrochlore(Lx, Ly, Lz, cyclic=False, cells=None)[source]

Return the graph edges of a finite 3D pyorchlore lattice. There are four sites per cell, and note the cells do not form a cubic tiling. The nodes (sites) are labelled like (i, j, k, s) for s in 'ABCD'.

Parameters:
  • Lx (int) – The number of cells along the x-direction.

  • Ly (int) – The number of cells along the y-direction.

  • Lz (int) – The number of cells along the z-direction.

  • cyclic (bool, optional) – Whether to use periodic boundary conditions.

  • cells (list, optional) – A list of cells to use. If not given the cells used are itertools.product(range(Lx), range(Ly), range(Lz)).

Returns:

edges

Return type:

list[((int, int, int, str), (int, int, int, str))]

quimb.tensor.edges_tree_rand(n, max_degree=None, seed=None)[source]

Return a random tree with n nodes. This a convenience function for testing purposes and the trees generated are not guaranteed to be uniformly random (for that see networkx.random_tree).

Parameters:
  • n (int) – The number of nodes.

  • max_degree (int, optional) – The maximum degree of the nodes. For example max_degree=3 means generate a binary tree.

  • seed (int, optional) – The random seed.

Returns:

edges

Return type:

list[(int, int)]

quimb.tensor.jax_register_pytree()[source]
quimb.tensor.pack(obj)[source]

Take a tensor or tensor network like object and return a skeleton needed to reconstruct it, and a pytree of raw parameters.

Parameters:

obj (Tensor, TensorNetwork, or similar) – Something that has copy, set_params, and get_params methods.

Returns:

  • params (pytree) – A pytree of raw parameter arrays.

  • skeleton (Tensor, TensorNetwork, or similar) – A copy of obj with all references to the original data removed.

quimb.tensor.unpack(params, skeleton)[source]

Take a skeleton of a tensor or tensor network like object and a pytree of raw parameters and return a new reconstructed object with those parameters inserted.

Parameters:
  • params (pytree) – A pytree of raw parameter arrays, with the same structure as the output of skeleton.get_params().

  • skeleton (Tensor, TensorNetwork, or similar) – Something that has copy, set_params, and get_params methods.

Returns:

obj – A copy of skeleton with parameters inserted.

Return type:

Tensor, TensorNetwork, or similar

class quimb.tensor.TNOptimizer(tn, loss_fn, norm_fn=None, loss_constants=None, loss_kwargs=None, tags=None, shared_tags=None, constant_tags=None, loss_target=None, optimizer='L-BFGS-B', progbar=True, bounds=None, autodiff_backend='AUTO', executor=None, callback=None, **backend_opts)[source]

Globally optimize tensors within a tensor network with respect to any loss function via automatic differentiation. If parametrized tensors are used, optimize the parameters rather than the raw arrays.

Parameters:
  • tn (TensorNetwork) – The core tensor network structure within which to optimize tensors.

  • loss_fn (callable or sequence of callable) – The function that takes tn (as well as loss_constants and loss_kwargs) and returns a single real ‘loss’ to be minimized. For Hamiltonians which can be represented as a sum over terms, an iterable collection of terms (e.g. list) can be given instead. In that case each term is evaluated independently and the sum taken as loss_fn. This can reduce the total memory requirements or allow for parallelization (see executor).

  • norm_fn (callable, optional) – A function to call before loss_fn that prepares or ‘normalizes’ the raw tensor network in some way.

  • loss_constants (dict, optional) – Extra tensor networks, tensors, dicts/list/tuples of arrays, or arrays which will be supplied to loss_fn but also converted to the correct backend array type.

  • loss_kwargs (dict, optional) – Extra options to supply to loss_fn (unlike loss_constants these are assumed to be simple options that don’t need conversion).

  • tags (str, or sequence of str, optional) – If supplied, only optimize tensors with any of these tags.

  • shared_tags (str, or sequence of str, optional) – If supplied, each tag in shared_tags corresponds to a group of tensors to be optimized together.

  • constant_tags (str, or sequence of str, optional) – If supplied, skip optimizing tensors with any of these tags. This ‘opt-out’ mode is overridden if either tags or shared_tags is supplied.

  • loss_target (float, optional) – Stop optimizing once this loss value is reached.

  • optimizer (str, optional) – Which scipy.optimize.minimize optimizer to use (the 'method' kwarg of that function). In addition, quimb implements a few custom optimizers compatible with this interface that you can reference by name - {'adam', 'nadam', 'rmsprop', 'sgd'}.

  • executor (None or Executor, optional) – To be used with term-by-term Hamiltonians. If supplied, this executor is used to parallelize the evaluation. Otherwise each term is evaluated in sequence. It should implement the basic concurrent.futures (PEP 3148) interface.

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

  • bounds (None or (float, float), optional) – Constrain the optimized tensor entries within this range (if the scipy optimizer supports it).

  • autodiff_backend ({'jax', 'autograd', 'tensorflow', 'torch'}, optional) – Which backend library to use to perform the automatic differentation (and computation).

  • callback (callable, optional) –

    A function to call after each optimization step. It should take the current TNOptimizer instance as its only argument. Information such as the current loss and number of evaluations can then be accessed:

    def callback(tnopt):
        print(tnopt.nevals, tnopt.loss)
    

  • backend_opts – Supplied to the backend function compiler and array handler. For example jit_fn=True or device='cpu' .

property d
property nevals

The number of gradient evaluations.

property optimizer

The underlying optimizer that works with the vectorized functions.

property bounds
_set_tn(tn)[source]
_reset_tracking_info(loss_target=None)[source]
reset(tn=None, clear_info=True, loss_target=None)[source]

Reset this optimizer without losing the compiled loss and gradient functions.

Parameters:
  • tn (TensorNetwork, optional) – Set this tensor network as the current state of the optimizer, it must exactly match the original tensor network.

  • clear_info (bool, optional) – Clear the tracked losses and iterations.

_maybe_init_pbar(n)[source]
_maybe_update_pbar()[source]
_maybe_close_pbar()[source]
_check_loss_target()[source]
_maybe_call_callback()[source]
vectorized_value(x)[source]

The value of the loss function at vector x.

vectorized_value_and_grad(x)[source]

The value and gradient of the loss function at vector x.

vectorized_hessp(x, p)[source]

The action of the hessian at point x on vector p.

__repr__()[source]

Return repr(self).

get_tn_opt()[source]

Extract the optimized tensor network, this is a three part process:

  1. inject the current optimized vector into the target tensor network,

  2. run it through norm_fn,

  3. drop any tags used to identify variables.

Returns:

tn_opt

Return type:

TensorNetwork

optimize(n, tol=None, jac=True, hessp=False, optlib='scipy', **options)[source]

Run the optimizer for n function evaluations, using by default scipy.optimize.minimize() as the driver for the vectorized computation. Supplying the gradient and hessian vector product is controlled by the jac and hessp options respectively.

Parameters:
  • n (int) – Notionally the maximum number of iterations for the optimizer, note that depending on the optimizer being used, this may correspond to number of function evaluations rather than just iterations.

  • tol (None or float, optional) – Tolerance for convergence, note that various more specific tolerances can usually be supplied to options, depending on the optimizer being used.

  • jac (bool, optional) – Whether to supply the jacobian, i.e. gradient, of the loss function.

  • hessp (bool, optional) – Whether to supply the hessian vector product of the loss function.

  • optlib ({'scipy', 'nlopt'}, optional) – Which optimization library to use.

  • options – Supplied to scipy.optimize.minimize() or whichever optimizer is being used.

Returns:

tn_opt

Return type:

TensorNetwork

optimize_scipy(n, tol=None, jac=True, hessp=False, **options)[source]

Scipy based optimization, see optimize() for details.

optimize_basinhopping(n, nhop, temperature=1.0, jac=True, hessp=False, **options)[source]

Run the optimizer for using scipy.optimize.basinhopping() as the driver for the vectorized computation. This performs nhop local optimization each with n iterations.

Parameters:
  • n (int) – Number of iterations per local optimization.

  • nhop (int) – Number of local optimizations to hop between.

  • temperature (float, optional) – H

  • options – Supplied to the inner scipy.optimize.minimize() call.

Returns:

tn_opt

Return type:

TensorNetwork

optimize_nlopt(n, tol=None, jac=True, hessp=False, ftol_rel=None, ftol_abs=None, xtol_rel=None, xtol_abs=None)[source]

Run the optimizer for n function evaluations, using nlopt as the backend library to run the optimization. Whether the gradient is computed depends on which optimizer is selected, see valid options at https://nlopt.readthedocs.io/en/latest/NLopt_Algorithms/.

The following scipy optimizer options are automatically translated to the corresponding nlopt algorithms: {“l-bfgs-b”, “slsqp”, “tnc”, “cobyla”}.

Parameters:
  • n (int) – The maximum number of iterations for the optimizer.

  • tol (None or float, optional) – Tolerance for convergence, here this is taken to be the relative tolerance for the loss (ftol_rel below overrides this).

  • jac (bool, optional) – Whether to supply the jacobian, i.e. gradient, of the loss function.

  • hessp (bool, optional) – Whether to supply the hessian vector product of the loss function.

  • ftol_rel (float, optional) – Set relative tolerance on function value.

  • ftol_abs (float, optional) – Set absolute tolerance on function value.

  • xtol_rel (float, optional) – Set relative tolerance on optimization parameters.

  • xtol_abs (float, optional) – Set absolute tolerances on optimization parameters.

Returns:

tn_opt

Return type:

TensorNetwork

optimize_ipopt(n, tol=None, **options)[source]

Run the optimizer for n function evaluations, using ipopt as the backend library to run the optimization via the python package cyipopt.

Parameters:

n (int) – The maximum number of iterations for the optimizer.

Returns:

tn_opt

Return type:

TensorNetwork

optimize_nevergrad(n)[source]

Run the optimizer for n function evaluations, using nevergrad as the backend library to run the optimization. As the name suggests, the gradient is not required for this method.

Parameters:

n (int) – The maximum number of iterations for the optimizer.

Returns:

tn_opt

Return type:

TensorNetwork

plot(xscale='symlog', xscale_linthresh=20, zoom='auto', hlines=())[source]

Plot the loss function as a function of the number of iterations.

Parameters:
  • xscale (str, optional) – The scale of the x-axis. Default is "symlog", i.e. linear for the first part of the plot, and logarithmic for the rest, changing at xscale_linthresh.

  • xscale_linthresh (int, optional) – The threshold for the change from linear to logarithmic scale, if xscale is "symlog". Default is 20.

  • zoom (None or int, optional) – If not None, show an inset plot of the last zoom iterations.

  • hlines (dict, optional) – A dictionary of horizontal lines to plot. The keys are the labels of the lines, and the values are the y-values of the lines.

Returns:

  • fig (matplotlib.figure.Figure) – The figure object.

  • ax (matplotlib.axes.Axes) – The axes object.

class quimb.tensor.Dense1D(array, phys_dim=2, tags=None, site_ind_id='k{}', site_tag_id='I{}', **tn_opts)[source]

Bases: TensorNetwork1DVector

Mimics other 1D tensor network structures, but really just keeps the full state in a single tensor. This allows e.g. applying gates in the same way for quantum circuit simulation as lazily represented hilbert spaces.

Parameters:
  • array (array_like) – The full hilbert space vector - assumed to be made of equal hilbert spaces each of size phys_dim and will be reshaped as such.

  • phys_dim (int, optional) – The hilbert space size of each site, default: 2.

  • tags (sequence of str, optional) – Extra tags to add to the tensor network.

  • site_ind_id (str, optional) – String formatter describing how to label the site indices.

  • site_tag_id (str, optional) – String formatter describing how to label the site tags.

  • tn_opts – Supplied to TensorNetwork.

_EXTRA_PROPS = ('_site_ind_id', '_site_tag_id', '_L')
classmethod rand(n, phys_dim=2, dtype=float, **dense1d_opts)[source]

Create a random dense vector ‘tensor network’.

class quimb.tensor.MatrixProductOperator(arrays, shape='lrud', site_tag_id='I{}', tags=None, upper_ind_id='k{}', lower_ind_id='b{}', bond_name='', **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.

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

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

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

  • bond_name (str, optional) – The base name of the bond indices, onto which uuids will be added.

_EXTRA_PROPS = ('_site_tag_id', '_upper_ind_id', '_lower_ind_id', 'cyclic', '_L')
fill_empty_sites_with_identities_[source]
add_MPO_[source]
dot[source]
classmethod from_fill_fn(fill_fn, L, bond_dim, phys_dim=2, cyclic=False, shape='lrud', site_tag_id='I{}', tags=None, upper_ind_id='k{}', lower_ind_id='b{}')[source]
classmethod from_dense(A, dims=2, sites=None, L=None, tags=None, site_tag_id='I{}', upper_ind_id='k{}', lower_ind_id='b{}', **split_opts)[source]

Build an MPO from a raw dense matrix.

Parameters:
  • A (array) – The dense operator, it should be reshapeable to (*dims, *dims).

  • dims (int, sequence of int, optional) – The physical subdimensions of the operator. If any integer, assume all sites have the same dimension. If a sequence, the dimension of each site. Default is 2.

  • sites (sequence of int, optional) – The sites to place the operator on. If None, will place it on first len(dims) sites.

  • L (int, optional) – The total number of sites in the MPO, if the operator represents only a subset.

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

  • site_tag_id (str, optional) – The string to use to label the site tags.

  • upper_ind_id (str, optional) – The string to use to label the upper physical indices.

  • lower_ind_id (str, optional) – The string to use to label the lower physical indices.

  • split_opts – Supplied to tensor_split().

Return type:

MatrixProductOperator

fill_empty_sites_with_identities(mode='full', phys_dim=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.

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

Returns:

The modified MPO.

Return type:

MatrixProductOperator

add_MPO(other, inplace=False, **kwargs)[source]
_apply_mps(other, compress=False, contract=True, **compress_opts)[source]
_apply_mpo(other, compress=False, contract=True, **compress_opts)[source]
apply(other, compress=False, **compress_opts)[source]

Act with this MPO on another MPO or MPS, such that the resulting object has the same tensor network structure/indices as other.

For an MPS:

       | | | | | | | | | | | | | | | | | |
 self: A-A-A-A-A-A-A-A-A-A-A-A-A-A-A-A-A-A
       | | | | | | | | | | | | | | | | | |
other: x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x

                       -->

       | | | | | | | | | | | | | | | | | |   <- other.site_ind_id
  out: y=y=y=y=y=y=y=y=y=y=y=y=y=y=y=y=y=y

For an MPO:

       | | | | | | | | | | | | | | | | | |
 self: A-A-A-A-A-A-A-A-A-A-A-A-A-A-A-A-A-A
       | | | | | | | | | | | | | | | | | |
other: B-B-B-B-B-B-B-B-B-B-B-B-B-B-B-B-B-B
       | | | | | | | | | | | | | | | | | |

                       -->

       | | | | | | | | | | | | | | | | | |   <- other.upper_ind_id
  out: C=C=C=C=C=C=C=C=C=C=C=C=C=C=C=C=C=C
       | | | | | | | | | | | | | | | | | |   <- other.lower_ind_id

The resulting TN will have the same structure/indices as other, but probably with larger bonds (depending on compression).

Parameters:
Return type:

MatrixProductOperator or MatrixProductState

permute_arrays(shape='lrud')[source]

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

Parameters:

shape (str, optional) – A permutation of 'lrud' specifying the desired order of the left, right, upper and lower (down) indices respectively.

trace(left_inds=None, right_inds=None)[source]

Take the trace of this MPO.

partial_transpose(sysa, inplace=False)[source]

Perform the partial transpose on this MPO by swapping the bra and ket indices on sites in sysa.

Parameters:
  • sysa (sequence of int or int) – The sites to transpose indices on.

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

Return type:

MatrixProductOperator

rand_state(bond_dim, **mps_opts)[source]

Get a random vector matching this MPO.

identity(**mpo_opts)[source]

Get a identity matching this MPO.

show(max_width=None)[source]
class quimb.tensor.MatrixProductState(arrays, *, shape='lrp', tags=None, bond_name='', 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.

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

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

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

  • bond_name (str, optional) – The base name of the bond indices, onto which uuids will be added.

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

Create a random MPS by supplying a 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.

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

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

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

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

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

Return type:

MatrixProductState

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

Create a MatrixProductState directly from a dense vector

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

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

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

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

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

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

Return type:

MatrixProductState

Examples

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

Add another MatrixProductState to this one.

permute_arrays(shape='lrp')[source]

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

Parameters:

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

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

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

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

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

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

Returns:

old_norm – The old norm self.H @ self.

Return type:

float

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

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

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

As might be found in TEBD.

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

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

  • compress_opts – Supplied to tensor_split().

See also

gate, gate_with_auto_swap

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

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

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

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

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

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

  • compress_opts – Supplied to tensor_split().

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

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

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

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

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

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

  • compress_opts – Supplied to tensor_split().

gate_with_auto_swap(G, where, inplace=False, cur_orthog=None, **compress_opts)[source]

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

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

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

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

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

  • compress_opts – Supplied to tensor_split().

See also

gate, gate_split

flip(inplace=False)[source]

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

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

Compute the magnetization at site i.

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

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

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

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

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

  • cur_orthog (int) – If given, the known current orthogonality center, to speed up the mixed canonization.

Returns:

S – The schmidt values.

Return type:

1d-array

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

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

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

  • cur_orthog (int) – If given, the known current orthogonality center, to speed up the mixed canonization.

Return type:

float

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

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

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

  • cur_orthog (int) – If given, the known current orthogonality center, to speed up the mixed canonization.

Return type:

float

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

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

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

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

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

Returns:

rho – The density operator in MPO form.

Return type:

MatrixProductOperator

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

Alias of partial_trace().

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

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

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

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

    Get the:

    • ’ket’: vector form as tensor.

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

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

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

  • cur_orthog (int, optional) – If given, take as the current orthogonality center so as to efficienctly move it a minimal distance.

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

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

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

                          ==> form inner product

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

                          ==> lateral SVD on each section

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

                          ==> vertical SVD and unfold on A & B

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

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

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

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

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

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

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

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

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

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

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

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

Returns:

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

Return type:

TensorNetwork

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

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

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

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

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

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

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

  • approx_spectral_opts – Supplied to approx_spectral_function().

Returns:

ln – The logarithmic negativity.

Return type:

float

See also

MatrixProductState.partial_trace_compress, approx_spectral_function

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

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

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

  • remove (bool, optional) –

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

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

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

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

  • cur_orthog (None or int, optional) – If you already know the orthogonality center, you can supply it here for efficiencies sake.

  • 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.SuperOperator1D(arrays, shape='lrkud', site_tag_id='I{}', outer_upper_ind_id='kn{}', inner_upper_ind_id='k{}', inner_lower_ind_id='b{}', outer_lower_ind_id='bn{}', tags=None, tags_upper=None, tags_lower=None, **tn_opts)[source]

Bases: TensorNetwork1D

A 1D tensor network super-operator class:

0   1   2       n-1
|   |   |        |     <-- outer_upper_ind_id
O===O===O==     =O
|\  |\  |\       |\     <-- inner_upper_ind_id
  )   )   ) ...    )   <-- K (size of local Kraus sum)
|/  |/  |/       |/     <-- inner_lower_ind_id
O===O===O==     =O
|   | : |        |     <-- outer_lower_ind_id
      :
     chi (size of entangling bond dim)
Parameters:

arrays (sequence of arrays) – The data arrays defining the superoperator, this should be a sequence of 2n arrays, such that the first two correspond to the upper and lower operators acting on site 0 etc. The arrays should be 5 dimensional unless OBC conditions are desired, in which case the first two and last two should be 4-dimensional. The dimensions of array can be should match the shape option.

property outer_upper_ind_id
property inner_upper_ind_id
property inner_lower_ind_id
property outer_lower_ind_id
_EXTRA_PROPS = ('_site_tag_id', '_outer_upper_ind_id', '_inner_upper_ind_id', '_inner_lower_ind_id',...
classmethod rand(n, K, chi, phys_dim=2, herm=True, cyclic=False, dtype=complex, **superop_opts)[source]
class quimb.tensor.TensorNetwork1D(ts=(), *, virtual=False, check_collisions=True)[source]

Bases: quimb.tensor.tensor_arbgeom.TensorNetworkGen

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

property L

The number of sites, i.e. length.

property nsites

The number of sites.

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

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

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

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

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

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

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

Return type:

TensorNetwork1D or TensorNetwork

gen_site_coos()[source]

Generate the coordinates of all possible sites.

site_tag(i)[source]

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

slice2sites(tag_slice)[source]

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

Examples

Normal slicing:

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

Slicing from end backwards:

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

Slicing round the end:

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

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

maybe_convert_coo(x)[source]

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

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

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

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

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

Returns:

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

Return type:

TensorNetwork, Tensor or scalar

See also

contract, contract_tags, contract_cumulative

_repr_info()[source]

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

class quimb.tensor.TNLinearOperator1D(tn, left_inds, right_inds, start, stop, ldims=None, rdims=None, is_conj=False, is_trans=False)[source]

Bases: scipy.sparse.linalg.LinearOperator

A 1D tensor network linear operator like:

         start                 stop - 1
           .                     .
         :-O-O-O-O-O-O-O-O-O-O-O-O-:                 --+
         : | | | | | | | | | | | | :                   |
         :-H-H-H-H-H-H-H-H-H-H-H-H-:    acting on    --V
         : | | | | | | | | | | | | :                   |
         :-O-O-O-O-O-O-O-O-O-O-O-O-:                 --+
left_inds^                         ^right_inds

Like TNLinearOperator, but performs a structured contract from one end to the other than can handle very long chains possibly more efficiently by contracting in blocks from one end.

Parameters:
  • tn (TensorNetwork) – The tensor network to turn into a LinearOperator.

  • left_inds (sequence of str) – The left indicies.

  • right_inds (sequence of str) – The right indicies.

  • start (int) – Index of starting site.

  • stop (int) – Index of stopping site (does not include this site).

  • ldims (tuple of int, optional) – If known, the dimensions corresponding to left_inds.

  • rdims (tuple of int, optional) – If known, the dimensions corresponding to right_inds.

See also

TNLinearOperator

property A
_matvec(vec)[source]

Default matrix-vector multiplication handler.

If self is a linear operator of shape (M, N), then this method will be called on a shape (N,) or (N, 1) ndarray, and should return a shape (M,) or (M, 1) ndarray.

This default implementation falls back on _matmat, so defining that will define matrix-vector multiplication as well.

_matmat(mat)[source]

Default matrix-matrix multiplication handler.

Falls back on the user-defined _matvec method, so defining that will define matrix multiplication (though in a very suboptimal way).

copy(conj=False, transpose=False)[source]
conj()[source]
_transpose()[source]

Default implementation of _transpose; defers to rmatvec + conj

_adjoint()[source]

Hermitian conjugate of this TNLO.

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

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

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

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

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

Returns:

x – The expectation value.

Return type:

float

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

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

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


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

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

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

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

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

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

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

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

    • False: leave the gate uncontracted, the default

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

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

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

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

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

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

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

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

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

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

    • If False, propagate nothing.

    • If True, propagate all tags.

  • inplace – Perform the gate in place.

  • bool – Perform the gate in place.

  • optional – Perform the gate in place.

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

Return type:

TensorNetwork1DVector

Examples

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

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

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

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

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

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

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

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

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

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

Returns:

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

Return type:

TensorNetwork

quimb.tensor.NNI[source]
class quimb.tensor.TEBD(p0, H, dt=None, tol=None, t0=0.0, split_opts=None, progbar=True, imag=False)[source]

Class implementing Time Evolving Block Decimation (TEBD) [1].

[1] Guifré Vidal, Efficient Classical Simulation of Slightly Entangled Quantum Computations, PRL 91, 147902 (2003)

Parameters:
  • p0 (MatrixProductState) – Initial state.

  • H (LocalHam1D or array_like) – Dense hamiltonian representing the two body interaction. Should have shape (d * d, d * d), where d is the physical dimension of p0.

  • dt (float, optional) – Default time step, cannot be set as well as tol.

  • tol (float, optional) – Default target error for each evolution, cannot be set as well as dt, which will instead be calculated from the trotter orderm length of time, and hamiltonian norm.

  • t0 (float, optional) – Initial time. Defaults to 0.0.

  • split_opts (dict, optional) – Compression options applied for splitting after gate application, see tensor_split().

  • imag (bool, optional) – Enable imaginary time evolution. Defaults to false.

See also

quimb.Evolution

property pt

The MPS state of the system at the current time.

property err
TARGET_TOL = 1e-13
choose_time_step(tol, T, order)[source]

Trotter error is ~ (T / dt) * dt^(order + 1). Invert to find desired time step, and scale by norm of interaction term.

_get_gate_from_ham(dt_frac, sites)[source]

Get the unitary (exponentiated) gate for fraction of timestep dt_frac and sites sites, cached.

sweep(direction, dt_frac, dt=None, queue=False)[source]

Perform a single sweep of gates and compression. This shifts the orthonognality centre along with the gates as they are applied and split.

Parameters:
  • direction ({'right', 'left'}) – Which direction to sweep. Right is even bonds, left is odd.

  • dt_frac (float) – What fraction of dt substep to take.

  • dt (float, optional) – Overide the current dt with a custom value.

_step_order2(tau=1, **sweep_opts)[source]

Perform a single, second order step.

_step_order4(**sweep_opts)[source]

Perform a single, fourth order step.

step(order=2, dt=None, progbar=None, **sweep_opts)[source]

Perform a single step of time self.dt.

_compute_sweep_dt_tol(T, dt, tol, order)[source]
update_to(T, dt=None, tol=None, order=4, progbar=None)[source]

Update the state to time T.

Parameters:
  • T (float) – The time to evolve to.

  • dt (float, optional) – Time step to use. Can’t be set as well as tol.

  • tol (float, optional) – Tolerance for whole evolution. Can’t be set as well as dt.

  • order (int, optional) – Trotter order to use.

  • progbar (bool, optional) – Manually turn the progress bar off.

_set_progbar_desc(progbar)[source]
at_times(ts, dt=None, tol=None, order=4, progbar=None)[source]

Generate the time evolved state at each time in ts.

Parameters:
  • ts (sequence of float) – The times to evolve to and yield the state at.

  • dt (float, optional) – Time step to use. Can’t be set as well as tol.

  • tol (float, optional) – Tolerance for whole evolution. Can’t be set as well as dt.

  • order (int, optional) – Trotter order to use.

  • progbar (bool, optional) – Manually turn the progress bar off.

Yields:

pt (MatrixProductState) – The state at each of the times in ts. This is a copy of internal state used, so inplace changes can be made to it.

class quimb.tensor.LocalHam1D(L, H2, H1=None, cyclic=False)[source]

Bases: quimb.tensor.tensor_arbgeom_tebd.LocalHamGen

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

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

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

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

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

terms

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

Type:

dict[tuple[int], array]

Examples

A simple, translationally invariant, interaction-only LocalHam1D:

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

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

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

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

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

Specifying the hamiltonian entirely through site specific interactions and fields:

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

See also

SpinHam1D

mean_norm()[source]

Computes the average frobenius norm of local terms.

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

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

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

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

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

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

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

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

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

  • split_opts – Supplied to tensor_split().

__repr__()[source]

Return repr(self).

class quimb.tensor.PEPO(arrays, *, shape='urdlbk', tags=None, upper_ind_id='k{},{}', lower_ind_id='b{},{}', site_tag_id='I{},{}', x_tag_id='X{}', y_tag_id='Y{}', **tn_opts)[source]

Bases: TensorNetwork2DOperator, TensorNetwork2DFlat

Projected Entangled Pair Operator object:

             ...
 │╱   │╱   │╱   │╱   │╱   │╱
 ●────●────●────●────●────●──
╱│   ╱│   ╱│   ╱│   ╱│   ╱│
 │╱   │╱   │╱   │╱   │╱   │╱
 ●────●────●────●────●────●──
╱│   ╱│   ╱│   ╱│   ╱│   ╱│
 │╱   │╱   │╱   │╱   │╱   │╱   ...
 ●────●────●────●────●────●──
╱│   ╱│   ╱│   ╱│   ╱│   ╱│
 │╱   │╱   │╱   │╱   │╱   │╱
 ●────●────●────●────●────●──
╱    ╱    ╱    ╱    ╱    ╱
Parameters:
  • arrays (sequence of sequence of array) – The core tensor data arrays.

  • shape (str, optional) – Which order the dimensions of the arrays are stored in, the default 'urdlbk' stands for (‘up’, ‘right’, ‘down’, ‘left’, ‘bra’, ‘ket’). Arrays on the edge of lattice are assumed to be missing the corresponding dimension.

  • tags (set[str], optional) – Extra global tags to add to the tensor network.

  • upper_ind_id (str, optional) – String specifier for naming convention of upper site indices.

  • lower_ind_id (str, optional) – String specifier for naming convention of lower site indices.

  • site_tag_id (str, optional) – String specifier for naming convention of site tags.

  • x_tag_id (str, optional) – String specifier for naming convention of row (‘x’) tags.

  • y_tag_id (str, optional) – String specifier for naming convention of column (‘y’) tags.

_EXTRA_PROPS = ('_site_tag_id', '_x_tag_id', '_y_tag_id', '_Lx', '_Ly', '_upper_ind_id', '_lower_ind_id')
rand_herm
add_PEPO_[source]
classmethod from_fill_fn(fill_fn, Lx, Ly, bond_dim, phys_dim=2, cyclic=False, shape='urdlbk', **pepo_opts)[source]

Create a PEPO and fill the tensor entries with a supplied function matching signature fill_fn(shape) -> array.

Parameters:
  • fill_fn (callable) – A function that takes a shape tuple and returns a data array.

  • Lx (int) – The number of rows.

  • Ly (int) – The number of columns.

  • bond_dim (int) – The bond dimension.

  • phys_dim (int, optional) – The physical indices dimension.

  • cyclic (bool or tuple[bool, bool], optional) – Whether the lattice is cyclic in the x and y directions.

  • shape (str, optional) – How to layout the indices of the tensors, the default is (up, right, down, left bra, ket) == 'urdlbk'.

  • pepo_opts – Supplied to PEPO.

classmethod rand(Lx, Ly, bond_dim, phys_dim=2, herm=False, dist='normal', loc=0.0, dtype='float64', seed=None, **pepo_opts)[source]

Create a random PEPO.

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

  • Ly (int) – The number of columns.

  • bond_dim (int) – The bond dimension.

  • physical (int, optional) – The physical index dimension.

  • herm (bool, optional) – Whether to symmetrize the tensors across the physical bonds to make the overall operator hermitian.

  • dtype (dtype, optional) – The dtype to create the arrays with, default is real double.

  • seed (int, optional) – A random seed.

  • pepo_opts – Supplied to PEPO.

Returns:

X

Return type:

PEPO

classmethod zeros(Lx, Ly, bond_dim, phys_dim=2, dtype='float64', backend='numpy', **pepo_opts)[source]

Create a PEPO with all zero entries.

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

  • Ly (int) – The number of columns.

  • bond_dim (int) – The bond dimension.

  • physical (int, optional) – The physical index dimension.

  • dtype (dtype, optional) – The dtype to create the arrays with, default is real double.

  • backend (str, optional) – Which backend to use, default is 'numpy'.

  • pepo_opts – Supplied to PEPO.

add_PEPO(other, inplace=False)[source]
_apply_peps(other, compress=False, contract=True, **compress_opts)[source]
apply(other, compress=False, **compress_opts)[source]

Act with this PEPO on other, returning a new TN like other with the same outer indices.

Parameters:
  • other (PEPS) – The TN to act on.

  • compress (bool, optional) – Whether to compress the resulting TN.

  • compress_opts – Supplied to compress().

Return type:

TensorNetwork2DFlat

show()[source]

Print a unicode schematic of this PEPO and its bond dimensions.

class quimb.tensor.PEPS(arrays, *, shape='urdlp', tags=None, site_ind_id='k{},{}', site_tag_id='I{},{}', x_tag_id='X{}', y_tag_id='Y{}', **tn_opts)[source]

Bases: TensorNetwork2DVector, TensorNetwork2DFlat

Projected Entangled Pair States object (2D):

             ...
 │    │    │    │    │    │
 ●────●────●────●────●────●──
╱│   ╱│   ╱│   ╱│   ╱│   ╱│
 │    │    │    │    │    │
 ●────●────●────●────●────●──
╱│   ╱│   ╱│   ╱│   ╱│   ╱│
 │    │    │    │    │    │   ...
 ●────●────●────●────●────●──
╱│   ╱│   ╱│   ╱│   ╱│   ╱│
 │    │    │    │    │    │
 ●────●────●────●────●────●──
╱    ╱    ╱    ╱    ╱    ╱
Parameters:
  • arrays (sequence of sequence of array_like) – The core tensor data arrays.

  • shape (str, optional) – Which order the dimensions of the arrays are stored in, the default 'urdlp' stands for (‘up’, ‘right’, ‘down’, ‘left’, ‘physical’). Arrays on the edge of lattice are assumed to be missing the corresponding dimension.

  • tags (set[str], optional) – Extra global tags to add to the tensor network.

  • site_ind_id (str, optional) – String specifier for naming convention of site indices.

  • site_tag_id (str, optional) – String specifier for naming convention of site tags.

  • x_tag_id (str, optional) – String specifier for naming convention of row (‘x’) tags.

  • y_tag_id (str, optional) – String specifier for naming convention of column (‘y’) tags.

_EXTRA_PROPS = ('_site_tag_id', '_x_tag_id', '_y_tag_id', '_Lx', '_Ly', '_site_ind_id')
add_PEPS_[source]
classmethod from_fill_fn(fill_fn, Lx, Ly, bond_dim, phys_dim=2, cyclic=False, shape='urdlp', **peps_opts)[source]

Create a 2D PEPS from a filling function with signature fill_fn(shape).

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

  • Ly (int) – The number of columns.

  • bond_dim (int) – The bond dimension.

  • phys_dim (int, optional) – The physical index dimension.

  • cyclic (bool or tuple[bool, bool], optional) – Whether the lattice is cyclic in the x and y directions.

  • shape (str, optional) – How to layout the indices of the tensors, the default is (up, right, down, left, phys) == 'urdlbk'. This is the order of the shape supplied to the filling function.

  • peps_opts – Supplied to PEPS.

Returns:

psi

Return type:

PEPS

classmethod empty(Lx, Ly, bond_dim, phys_dim=2, like='numpy', **peps_opts)[source]

Create an empty 2D PEPS.

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

  • Ly (int) – The number of columns.

  • bond_dim (int) – The bond dimension.

  • physical (int, optional) – The physical index dimension.

  • peps_opts – Supplied to PEPS.

Returns:

psi

Return type:

PEPS

classmethod ones(Lx, Ly, bond_dim, phys_dim=2, like='numpy', **peps_opts)[source]

Create a 2D PEPS whose tensors are filled with ones.

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

  • Ly (int) – The number of columns.

  • bond_dim (int) – The bond dimension.

  • physical (int, optional) – The physical index dimension.

  • peps_opts – Supplied to PEPS.

Returns:

psi

Return type:

PEPS

classmethod rand(Lx, Ly, bond_dim, phys_dim=2, dist='normal', loc=0.0, dtype='float64', seed=None, **peps_opts)[source]

Create a random (un-normalized) PEPS.

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

  • Ly (int) – The number of columns.

  • bond_dim (int) – The bond dimension.

  • physical (int, optional) – The physical index dimension.

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

  • loc (float, optional) – An additive offset to add to the random numbers.

  • dtype (dtype, optional) – The dtype to create the arrays with, default is real double.

  • seed (int, optional) – A random seed.

  • peps_opts – Supplied to PEPS.

Returns:

psi

Return type:

PEPS

add_PEPS(other, inplace=False)[source]
show()[source]

Print a unicode schematic of this PEPS and its bond dimensions.

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

Bases: quimb.tensor.tensor_arbgeom.TensorNetworkGen

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

             'Y{j}'
                v

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

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

This implies the following conventions:

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

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

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

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

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.

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.

_NDIMS = 2
_EXTRA_PROPS = ('_site_tag_id', '_x_tag_id', '_y_tag_id', '_Lx', '_Ly')
row_tag[source]
row_tags
col_tag[source]
col_tags
flatten_[source]
contract_boundary_from_[source]
contract_boundary_from_xmin_[source]
contract_boundary_from_xmax_[source]
contract_boundary_from_ymin_[source]
contract_boundary_from_ymax_[source]
contract_boundary_[source]
contract_mps_sweep_[source]
compute_xmin_environments[source]

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

compute_xmax_environments[source]

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

compute_ymin_environments[source]

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

compute_ymax_environments[source]

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

coarse_grain_hotrg_[source]
contract_hotrg_[source]
contract_ctmrg_[source]
_compatible_2d(other)[source]

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

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

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

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

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

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

Return type:

TensorNetwork2D or TensorNetwork

site_tag(i, j=None)[source]

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

x_tag(i)[source]
y_tag(j)[source]
maybe_convert_coo(x)[source]

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

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

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

gen_site_coos()[source]

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

gen_bond_coos()[source]

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

gen_horizontal_bond_coos()[source]

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

gen_horizontal_even_bond_coos()[source]

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

gen_horizontal_odd_bond_coos()[source]

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

gen_vertical_bond_coos()[source]

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

gen_vertical_even_bond_coos()[source]

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

gen_vertical_odd_bond_coos()[source]

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

gen_diagonal_left_bond_coos()[source]

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

gen_diagonal_left_even_bond_coos()[source]

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

gen_diagonal_left_odd_bond_coos()[source]

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

gen_diagonal_right_bond_coos()[source]

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

gen_diagonal_right_even_bond_coos()[source]

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

gen_diagonal_right_odd_bond_coos()[source]

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

gen_diagonal_bond_coos()[source]

Generate all next nearest neighbor diagonal coordinate pairs.

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

Check whether coo is in-bounds.

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

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

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

Return type:

bool

get_ranges_present()[source]

Return the range of site coordinates present in this TN.

Returns:

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

Return type:

tuple[tuple[int, int]]

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

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

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

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

__getitem__(key)[source]

Key based tensor selection, checking for integer based shortcut.

show()[source]

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

_repr_info()[source]

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

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

Contract all tensors corresponding to each site into one.

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

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

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

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

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

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

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

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

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

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

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

Yields:

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

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

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

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

Canonize all or part of a row.

If sweep == 'right' then:

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

If sweep == 'left' then:

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

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

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

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

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

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

  • canonize_opts – Supplied to canonize_between.

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

Canonize all or part of a column.

If sweep='up' then:

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

If sweep='down' then:

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

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

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

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

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

  • canonize_opts – Supplied to canonize_between.

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

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

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

Compress all or part of a row.

If sweep == 'right' then:

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

If sweep == 'left' then:

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

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

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

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

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

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

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

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

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

Compress all or part of a column.

If sweep='up' then:

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

If sweep='down' then:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

a) contract

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

b) optionally canonicalize

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

c) compress in opposite direction

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

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

a) first flatten the outer boundary only

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

b) contract and compress a single layer only

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

c) contract and compress the next layer

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

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

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

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

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

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

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

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

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

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

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

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

a) contract

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

b) optionally canonicalize

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

c) compress in opposite direction

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

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

a) first flatten the outer boundary only

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

b) contract and compress a single layer only

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

c) contract and compress the next layer

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

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

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

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

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

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

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

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

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

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

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

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

a) contract

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

b) optionally canonicalize

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

c) compress in opposite direction

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

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

a) first flatten the outer boundary only

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

b) contract and compress a single layer only

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

c) contract and compress the next layer

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

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

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

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

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

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

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

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

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

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

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

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

a) contract

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

b) optionally canonicalize

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

c) compress in opposite direction

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

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

a) first flatten the outer boundary only

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

b) contract and compress a single layer only

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

c) contract and compress the next layer

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

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

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

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

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

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

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

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

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

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

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

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

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

Contract the boundary of this 2D tensor network inwards:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Returns:

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

Return type:

dict

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Returns:

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

Return type:

dict[(str, int), TensorNetwork]

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

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

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

●<
┃
●<
┃
●<
┃
●<

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

>●
 ┃
>●
 ┃
>●
 ┃
>●

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

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

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

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

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

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

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

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

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

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

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

Returns:

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

Return type:

dict[(str, int), TensorNetwork]

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

Compute all environments like:

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

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

  <-->                    <->
 y_bsz                   y_bsz

Use two boundary contractions sweeps.

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

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

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

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

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

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

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

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

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

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

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

Returns:

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

Return type:

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

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

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

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

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

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

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

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

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

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

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

Returns:

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

Return type:

TensorNetwork2D

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Returns:

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

Return type:

TensorNetwork2D

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Returns:

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

Return type:

scalar or TensorNetwork2D

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

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

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

  • Ly (int) – The number of columns.

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

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

Yields:

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

Examples

Generate nearest neighbor bonds:

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

Generate next nearest neighbor digonal bonds:

>>> for bond in gen_2d_bonds(2, 2, [lambda i, j: (i + 1, j + 1),
>>>                                 lambda i, j: (i + 1, j - 1)]):
>>>     print(bond)
((0, 0), (1, 1))
((0, 1), (1, 0))
class quimb.tensor.TEBD2D(psi0, ham, tau=0.01, D=None, chi=None, imag=True, gate_opts=None, ordering=None, second_order_reflect=False, compute_energy_every=None, compute_energy_final=True, compute_energy_opts=None, compute_energy_fn=None, compute_energy_per_site=False, callback=None, keep_best=False, progbar=True)[source]

Bases: quimb.tensor.tensor_arbgeom_tebd.TEBDGen

Generic class for performing two dimensional time evolving block decimation, i.e. applying the exponential of a Hamiltonian using a product formula that involves applying local exponentiated gates only.

Parameters:
  • psi0 (TensorNetwork2DVector) – The initial state.

  • ham (LocalHam2D) – The Hamtiltonian consisting of local terms.

  • tau (float, optional) – The default local exponent, if considered as time real values here imply imaginary time.

  • max_bond ({'psi0', int, None}, optional) – The maximum bond dimension to keep when applying each gate.

  • gate_opts (dict, optional) – Supplied to quimb.tensor.tensor_2d.TensorNetwork2DVector.gate(), in addition to max_bond. By default contract is set to ‘reduce-split’ and cutoff is set to 0.0.

  • ordering (str, tuple[tuple[int]], callable, optional) – How to order the terms, if a string is given then use this as the strategy given to get_auto_ordering(). An explicit list of coordinate pairs can also be given. The default is to greedily form an ‘edge coloring’ based on the sorted list of Hamiltonian pair coordinates. If a callable is supplied it will be used to generate the ordering before each sweep.

  • second_order_reflect (bool, optional) – If True, then apply each layer of gates in ordering forward with half the time step, then the same with reverse order.

  • compute_energy_every (None or int, optional) – How often to compute and record the energy. If a positive integer ‘n’, the energy is computed before every nth sweep (i.e. including before the zeroth).

  • compute_energy_final (bool, optional) – Whether to compute and record the energy at the end of the sweeps regardless of the value of compute_energy_every. If you start sweeping again then this final energy is the same as the zeroth of the next set of sweeps and won’t be recomputed.

  • compute_energy_opts (dict, optional) – Supplied to compute_local_expectation(). By default max_bond is set to max(8, D**2) where D is the maximum bond to use for applying the gate, cutoff is set to 0.0 and normalized is set to True.

  • compute_energy_fn (callable, optional) – Supply your own function to compute the energy, it should take the TEBD2D object as its only argument.

  • callback (callable, optional) – A custom callback to run after every sweep, it should take the TEBD2D object as its only argument. If it returns any value that boolean evaluates to True then terminal the evolution.

  • progbar (boolean, optional) – Whether to show a live progress bar during the evolution.

  • kwargs – Extra options for the specific TEBD2D subclass.

state

The current state.

Type:

TensorNetwork2DVector

ham

The Hamiltonian being used to evolve.

Type:

LocalHam2D

energy

The current of the current state, this will trigger a computation if the energy at this iteration hasn’t been computed yet.

Type:

float

energies

The energies that have been computed, if any.

Type:

list[float]

its

The corresponding sequence of iteration numbers that energies have been computed at.

Type:

list[int]

taus

The corresponding sequence of time steps that energies have been computed at.

Type:

list[float]

best

If keep_best was set then the best recorded energy and the corresponding state that was computed - keys 'energy' and 'state' respectively.

Type:

dict

property chi
compute_energy()[source]

Compute and return the energy of the current state.

__repr__()[source]

Return repr(self).

class quimb.tensor.FullUpdate(psi0, ham, tau=0.01, D=None, chi=None, fit_strategy='als', fit_opts=None, compute_envs_every=1, pre_normalize=True, condition_tensors=True, condition_balance_bonds=True, contract_optimize='auto-hq', imag=True, gate_opts=None, ordering=None, second_order_reflect=False, compute_energy_every=None, compute_energy_final=True, compute_energy_opts=None, compute_energy_fn=None, compute_energy_per_site=False, callback=None, keep_best=False, progbar=True)[source]

Bases: TEBD2D

Implements the ‘Full Update’ version of 2D imaginary time evolution, where each application of a gate is fitted to the current tensors using a boundary contracted environment.

Parameters:
  • psi0 (TensorNetwork2DVector) – The initial state.

  • ham (LocalHam2D) – The Hamtiltonian consisting of local terms.

  • tau (float, optional) – The default local exponent, if considered as time real values here imply imaginary time.

  • max_bond ({'psi0', int, None}, optional) – The maximum bond dimension to keep when applying each gate.

  • gate_opts (dict, optional) – Supplied to quimb.tensor.tensor_2d.TensorNetwork2DVector.gate(), in addition to max_bond. By default contract is set to ‘reduce-split’ and cutoff is set to 0.0.

  • ordering (str, tuple[tuple[int]], callable, optional) – How to order the terms, if a string is given then use this as the strategy given to get_auto_ordering(). An explicit list of coordinate pairs can also be given. The default is to greedily form an ‘edge coloring’ based on the sorted list of Hamiltonian pair coordinates. If a callable is supplied it will be used to generate the ordering before each sweep.

  • second_order_reflect (bool, optional) – If True, then apply each layer of gates in ordering forward with half the time step, then the same with reverse order.

  • compute_energy_every (None or int, optional) – How often to compute and record the energy. If a positive integer ‘n’, the energy is computed before every nth sweep (i.e. including before the zeroth).

  • compute_energy_final (bool, optional) – Whether to compute and record the energy at the end of the sweeps regardless of the value of compute_energy_every. If you start sweeping again then this final energy is the same as the zeroth of the next set of sweeps and won’t be recomputed.

  • compute_energy_opts (dict, optional) – Supplied to compute_local_expectation(). By default max_bond is set to max(8, D**2) where D is the maximum bond to use for applying the gate, cutoff is set to 0.0 and normalized is set to True.

  • compute_energy_fn (callable, optional) – Supply your own function to compute the energy, it should take the TEBD2D object as its only argument.

  • callback (callable, optional) – A custom callback to run after every sweep, it should take the TEBD2D object as its only argument. If it returns any value that boolean evaluates to True then terminal the evolution.

  • progbar (boolean, optional) – Whether to show a live progress bar during the evolution.

  • fit_strategy ({'als', 'autodiff-fidelity'}, optional) –

    Core method used to fit the gate application.

    • 'als': alternating least squares

    • 'autodiff-fidelity': local fidelity using autodiff

  • fit_opts (dict, optional) – Advanced options for the gate application fitting functions. Defaults are inserted and can be accessed via the .fit_opts attribute.

  • compute_envs_every ({'term', 'group', 'sweep', int}, optional) –

    How often to recompute the environments used to the fit the gate application:

    • 'term': every gate

    • 'group': every set of commuting gates (the default)

    • 'sweep': every total sweep

    • int: every x number of total sweeps

  • pre_normalize (bool, optional) – Actively renormalize the state using the computed environments.

  • condition_tensors (bool, optional) – Whether to actively equalize tensor norms for numerical stability.

  • condition_balance_bonds (bool, optional) – If and when equalizing tensor norms, whether to also balance bonds as an additional conditioning.

  • contract_optimize (str, optional) – Contraction path optimizer to use for gate + env + sites contractions.

state

The current state.

Type:

TensorNetwork2DVector

ham

The Hamiltonian being used to evolve.

Type:

LocalHam2D

energy

The current of the current state, this will trigger a computation if the energy at this iteration hasn’t been computed yet.

Type:

float

energies

The energies that have been computed, if any.

Type:

list[float]

its

The corresponding sequence of iteration numbers that energies have been computed at.

Type:

list[int]

taus

The corresponding sequence of time steps that energies have been computed at.

Type:

list[float]

best

If keep_best was set then the best recorded energy and the corresponding state that was computed - keys 'energy' and 'state' respectively.

Type:

dict

fit_opts

Detailed options for fitting the applied gate.

Type:

dict

property fit_strategy
property compute_envs_every
set_state(psi)[source]

The default method for setting the current state - simply a copy. Subclasses can override this to perform additional transformations.

_maybe_compute_plaquette_envs(force=False)[source]

Compute and store the plaquette environments for all local terms.

presweep(i)[source]

Full update presweep - compute envs and inject gate options.

compute_energy()[source]

Full update compute energy - use the (likely) already calculated plaquette environments.

gate(G, where)[source]

Apply the gate G at sites where, using a fitting method that takes into account the current environment.

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

Bases: quimb.tensor.tensor_arbgeom_tebd.LocalHamGen

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

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

  • Ly (int) – The number of columns.

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

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

terms

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

Type:

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

property nsites

The number of sites in the system.

graph[source]
__repr__()[source]

Return repr(self).

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

Plot this Hamiltonian as a network.

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

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

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

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

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

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

class quimb.tensor.SimpleUpdate(psi0, ham, tau=0.01, D=None, chi=None, gauge_renorm=True, gauge_smudge=1e-06, condition_tensors=True, condition_balance_bonds=True, long_range_use_swaps=False, long_range_path_sequence='random', imag=True, gate_opts=None, ordering=None, second_order_reflect=False, compute_energy_every=None, compute_energy_final=True, compute_energy_opts=None, compute_energy_fn=None, compute_energy_per_site=False, callback=None, keep_best=False, progbar=True)[source]

Bases: TEBD2D

A simple subclass of TEBD2D that overrides two key methods in order to keep ‘diagonal gauges’ living on the bonds of a PEPS. The gauges are stored separately from the main PEPS in the gauges attribute. Before and after a gate is applied they are absorbed and then extracted. When accessing the state attribute they are automatically inserted or you can call get_state(absorb_gauges=False) to lazily add them as hyperedge weights only. Reference: https://arxiv.org/abs/0806.3719.

Parameters:
  • psi0 (TensorNetwork2DVector) – The initial state.

  • ham (LocalHam2D) – The Hamtiltonian consisting of local terms.

  • tau (float, optional) – The default local exponent, if considered as time real values here imply imaginary time.

  • max_bond ({'psi0', int, None}, optional) – The maximum bond dimension to keep when applying each gate.

  • gate_opts (dict, optional) – Supplied to quimb.tensor.tensor_2d.TensorNetwork2DVector.gate(), in addition to max_bond. By default contract is set to ‘reduce-split’ and cutoff is set to 0.0.

  • ordering (str, tuple[tuple[int]], callable, optional) – How to order the terms, if a string is given then use this as the strategy given to get_auto_ordering(). An explicit list of coordinate pairs can also be given. The default is to greedily form an ‘edge coloring’ based on the sorted list of Hamiltonian pair coordinates. If a callable is supplied it will be used to generate the ordering before each sweep.

  • second_order_reflect (bool, optional) – If True, then apply each layer of gates in ordering forward with half the time step, then the same with reverse order.

  • compute_energy_every (None or int, optional) – How often to compute and record the energy. If a positive integer ‘n’, the energy is computed before every nth sweep (i.e. including before the zeroth).

  • compute_energy_final (bool, optional) – Whether to compute and record the energy at the end of the sweeps regardless of the value of compute_energy_every. If you start sweeping again then this final energy is the same as the zeroth of the next set of sweeps and won’t be recomputed.

  • compute_energy_opts (dict, optional) – Supplied to compute_local_expectation(). By default max_bond is set to max(8, D**2) where D is the maximum bond to use for applying the gate, cutoff is set to 0.0 and normalized is set to True.

  • compute_energy_fn (callable, optional) – Supply your own function to compute the energy, it should take the TEBD2D object as its only argument.

  • callback (callable, optional) – A custom callback to run after every sweep, it should take the TEBD2D object as its only argument. If it returns any value that boolean evaluates to True then terminal the evolution.

  • progbar (boolean, optional) – Whether to show a live progress bar during the evolution.

  • gauge_renorm (bool, optional) – Whether to actively renormalize the singular value gauges.

  • gauge_smudge (float, optional) – A small offset to use when applying the guage and its inverse to avoid numerical problems.

  • condition_tensors (bool, optional) – Whether to actively equalize tensor norms for numerical stability.

  • condition_balance_bonds (bool, optional) – If and when equalizing tensor norms, whether to also balance bonds as an additional conditioning.

  • long_range_use_swaps (bool, optional) – If there are long range terms, whether to use swap gates to apply the terms. If False, a long range blob tensor (which won’t scale well for long distances) is formed instead.

  • long_range_path_sequence (str or callable, optional) – If there are long range terms how to generate the path between the two coordinates. If callable, should take the two coordinates and return a sequence of coordinates that links them, else passed to gen_long_range_swap_path.

state

The current state.

Type:

TensorNetwork2DVector

ham

The Hamiltonian being used to evolve.

Type:

LocalHam2D

energy

The current of the current state, this will trigger a computation if the energy at this iteration hasn’t been computed yet.

Type:

float

energies

The energies that have been computed, if any.

Type:

list[float]

its

The corresponding sequence of iteration numbers that energies have been computed at.

Type:

list[int]

taus

The corresponding sequence of time steps that energies have been computed at.

Type:

list[float]

best

If keep_best was set then the best recorded energy and the corresponding state that was computed - keys 'energy' and 'state' respectively.

Type:

dict

property gauges

The dictionary of bond pair coordinates to Tensors describing the weights (t = gauges[pair]; t.data) and index (t = gauges[pair]; t.inds[0]) of all the gauges.

property long_range_use_swaps
_initialize_gauges()[source]

Create unit singular values, stored as tensors.

gate(U, where)[source]

Like TEBD2D.gate but absorb and extract the relevant gauges before and after each gate application.

get_state(absorb_gauges=True)[source]

Return the state, with the diagonal bond gauges either absorbed equally into the tensors on either side of them (absorb_gauges=True, the default), or left lazily represented in the tensor network with hyperedges (absorb_gauges=False).

set_state(psi)[source]

Set the wavefunction state, this resets the environment gauges to unity.

class quimb.tensor.PEPS3D(arrays, *, shape='urfdlbp', tags=None, site_ind_id='k{},{},{}', site_tag_id='I{},{},{}', x_tag_id='X{}', y_tag_id='Y{}', z_tag_id='Z{}', **tn_opts)[source]

Bases: TensorNetwork3DVector, TensorNetwork3DFlat

Projected Entangled Pair States object (3D).

Parameters:
  • arrays (sequence of sequence of sequence of array) – The core tensor data arrays.

  • shape (str, optional) – Which order the dimensions of the arrays are stored in, the default 'urfdlbp' stands for (‘up’, ‘right’, ‘front’, down’, ‘left’, ‘behind’, ‘physical’) meaning (x+, y+, z+, x-, y-, z-, physical) respectively. Arrays on the edge of lattice are assumed to be missing the corresponding dimension.

  • tags (set[str], optional) – Extra global tags to add to the tensor network.

  • site_ind_id (str, optional) – String specifier for naming convention of site indices.

  • site_tag_id (str, optional) – String specifier for naming convention of site tags.

  • x_tag_id (str, optional) – String specifier for naming convention of x-slice tags.

  • y_tag_id (str, optional) – String specifier for naming convention of y-slice tags.

  • z_tag_id (str, optional) – String specifier for naming convention of z-slice tags.

_EXTRA_PROPS = ('_site_tag_id', '_x_tag_id', '_y_tag_id', '_z_tag_id', '_Lx', '_Ly', '_Lz', '_site_ind_id')
permute_arrays(shape='urfdlbp')[source]

Permute the indices of each tensor in this PEPS3D 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.

classmethod from_fill_fn(fill_fn, Lx, Ly, Lz, bond_dim, phys_dim=2, cyclic=False, shape='urfdlbp', **peps3d_opts)[source]

Create a 3D PEPS from a filling function with signature fill_fn(shape).

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

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

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

  • bond_dim (int) – The bond dimension.

  • phys_dim (int, optional) – The physical index dimension.

  • shape (str, optional) – How to layout the indices of the tensors, the default is (up, right, front, down, left, back, phys) == 'urfdlbp'. This is the order of the shape supplied to the filling function.

  • peps_opts – Supplied to PEPS3D.

Returns:

psi

Return type:

PEPS3D

classmethod empty(Lx, Ly, Lz, bond_dim, phys_dim=2, like='numpy', **peps3d_opts)[source]

Create an empty 3D PEPS.

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

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

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

  • bond_dim (int) – The bond dimension.

  • physical (int, optional) – The physical index dimension.

  • peps3d_opts – Supplied to PEPS3D.

Returns:

psi

Return type:

PEPS3D

classmethod ones(Lx, Ly, Lz, bond_dim, phys_dim=2, like='numpy', **peps3d_opts)[source]

Create a 3D PEPS whose tensors are filled with ones.

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

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

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

  • bond_dim (int) – The bond dimension.

  • physical (int, optional) – The physical index dimension.

  • peps3d_opts – Supplied to PEPS3D.

Returns:

psi

Return type:

PEPS3D

classmethod rand(Lx, Ly, Lz, bond_dim, phys_dim=2, dist='normal', loc=0.0, dtype='float64', seed=None, **peps3d_opts)[source]

Create a random (un-normalized) 3D PEPS.

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

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

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

  • bond_dim (int) – The bond dimension.

  • physical (int, optional) – The physical index dimension.

  • dtype (dtype, optional) – The dtype to create the arrays with, default is real double.

  • seed (int, optional) – A random seed.

  • peps_opts – Supplied to PEPS3D.

Returns:

psi

Return type:

PEPS3D

partial_trace_cluster(keep, max_bond=None, *, cutoff=1e-10, max_distance=0, fillin=0, gauges=False, flatten=False, normalized=True, symmetrized='auto', get=None, **contract_boundary_opts)[source]
partial_trace(keep, max_bond=None, *, cutoff=1e-10, canonize=True, flatten=False, normalized=True, symmetrized='auto', envs=None, storage_factory=None, boundary_order=None, contract_cell_optimize='auto-hq', contract_cell_method='boundary', contract_cell_opts=None, get=None, **contract_boundary_opts)[source]

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

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

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

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

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

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

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

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

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

    Whether to perform the computation or not:

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

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

Returns:

rho – The reduce density matrix of sites in keep.

Return type:

array_like

compute_local_expectation(terms, max_bond=None, *, cutoff=1e-10, canonize=True, flatten=False, normalized=True, symmetrized='auto', return_all=False, envs=None, storage_factory=None, progbar=False, **contract_boundary_opts)[source]

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

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

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

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

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

    The method to use to compute the expectation value.

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

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

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

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

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

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

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

    Whether to perform the computations or not:

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

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

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

  • contract_compressed_opts – Supplied to contract_compressed().

Returns:

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

Return type:

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

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

Bases: quimb.tensor.tensor_arbgeom.TensorNetworkGen

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

property Lx

The number of x-slices.

property Ly

The number of y-slices.

property Lz

The number of z-slices.

property nsites

The total number of sites.

property x_tag_id

The string specifier for tagging each x-slice of this 3D TN.

property x_tags

A tuple of all of the Lx different x-slice tags.

property y_tag_id

The string specifier for tagging each y-slice of this 3D TN.

property y_tags

A tuple of all of the Ly different y-slice tags.

property z_tag_id

The string specifier for tagging each z-slice of this 3D TN.

property z_tags

A tuple of all of the Lz different z-slice tags.

_NDIMS = 3
_EXTRA_PROPS = ('_site_tag_id', '_x_tag_id', '_y_tag_id', '_z_tag_id', '_Lx', '_Ly', '_Lz')
flatten_[source]
contract_boundary_from_[source]
contract_boundary_[source]
contract_ctmrg_[source]
coarse_grain_hotrg_[source]
contract_hotrg_[source]
_compatible_3d(other)[source]

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

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

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

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

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

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

Return type:

TensorNetwork3D or TensorNetwork

site_tag(i, j=None, k=None)[source]

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

x_tag(i)[source]
y_tag(j)[source]
z_tag(k)[source]
maybe_convert_coo(coo)[source]

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

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

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

gen_site_coos()[source]

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

gen_bond_coos()[source]

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

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

Check whether coo is in-bounds.

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

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

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

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

Return type:

bool

get_ranges_present()[source]

Return the range of site coordinates present in this TN.

Returns:

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

Return type:

tuple[tuple[int, int]]

Examples

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

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

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

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

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

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

__getitem__(key)[source]

Key based tensor selection, checking for integer based shortcut.

_repr_info()[source]

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

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

Contract all tensors corresponding to each site into one.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Yields:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Returns:

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

Return type:

TensorNetwork2D

See also

contract_hotrg, insert_compressor_between_regions

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

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

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

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

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

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

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

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

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

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

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

  • inplace (bool, optional) – Whether to perform the coarse graining in place.

  • coarse_grain_opts – Additional options to pass to coarse_grain_hotrg().

Returns:

The contracted tensor network, which will have no more than one directino of length > 2.

Return type:

TensorNetwork3D

See also

coarse_grain_hotrg, insert_compressor_between_regions

quimb.tensor.gen_3d_bonds(Lx, Ly, Lz, steppers=None, coo_filter=None, cyclic=False)[source]

Convenience function for tiling pairs of bond coordinates on a 3D lattice given a function like lambda i, j, k: (i + 1, j + 1, k + 1).

Parameters:
  • Lx (int) – The number of x-slices.

  • Ly (int) – The number of y-slices.

  • Lz (int) – The number of z-slices.

  • steppers (callable or sequence of callable) – Function(s) that take args (i, j, k) and generate another coordinate, thus defining a bond. Only valid steps are taken. If not given, defaults to nearest neighbor bonds.

  • coo_filter (callable) – Function that takes args (i, j, k) and only returns True if this is to be a valid starting coordinate.

Yields:

bond (tuple[tuple[int, int, int], tuple[int, int, int]]) – A pair of coordinates.

Examples

Generate nearest neighbor bonds:

>>> for bond in gen_3d_bonds(2, 2, 2, [lambda i, j, k: (i + 1, j, k),
...                                    lambda i, j, k: (i, j + 1, k),
...                                    lambda i, j, k: (i, j, k + 1)]):
...     print(bond)
((0, 0, 0), (1, 0, 0))
((0, 0, 0), (0, 1, 0))
((0, 0, 0), (0, 0, 1))
((0, 0, 1), (1, 0, 1))
((0, 0, 1), (0, 1, 1))
((0, 1, 0), (1, 1, 0))
((0, 1, 0), (0, 1, 1))
((0, 1, 1), (1, 1, 1))
((1, 0, 0), (1, 1, 0))
((1, 0, 0), (1, 0, 1))
((1, 0, 1), (1, 1, 1))
((1, 1, 0), (1, 1, 1))
class quimb.tensor.LocalHam3D(Lx, Ly, Lz, H2, H1=None, cyclic=False)[source]

Bases: quimb.tensor.tensor_arbgeom_tebd.LocalHamGen

Representation of a local hamiltonian defined on a general graph. This combines all two site and one site terms into a single interaction per lattice pair, and caches operations on the terms such as getting their exponential. The sites (nodes) should be hashable and comparable.

Parameters:
  • H2 (dict[tuple[node], array_like]) – The interaction terms, with each key being an tuple of nodes defining an edge and each value the local hamilotonian term for those two nodes.

  • H1 (array_like or dict[node, array_like], optional) – The one site term(s). If a single array is given, assume to be the default onsite term for all terms. If a dict is supplied, the keys should represent specific coordinates like (i, j) with the values the array representing the local term for that site. A default term for all remaining sites can still be supplied with the key None.

terms

The total effective local term for each interaction (with single site terms appropriately absorbed). Each key is a pair of coordinates site_a, site_b with site_a < site_b.

Type:

dict[tuple, array_like]

property nsites

The number of sites in the system.

__repr__()[source]

Return repr(self).

quimb.tensor.tensor_network_align(*tns, ind_ids=None, trace=False, inplace=False)[source]

Align an arbitrary number of tensor networks in a stack-like geometry:

a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a
| | | | | | | | | | | | | | | | | | <- ind_ids[0] (defaults to 1st id)
b-b-b-b-b-b-b-b-b-b-b-b-b-b-b-b-b-b
| | | | | | | | | | | | | | | | | | <- ind_ids[1]
               ...
| | | | | | | | | | | | | | | | | | <- ind_ids[-2]
y-y-y-y-y-y-y-y-y-y-y-y-y-y-y-y-y-y
| | | | | | | | | | | | | | | | | | <- ind_ids[-1]
z-z-z-z-z-z-z-z-z-z-z-z-z-z-z-z-z-z
Parameters:
  • tns (sequence of TensorNetwork) – The TNs to align, should be structured and either effective ‘vectors’ (have a site_ind_id) or ‘operators’ (have a up_ind_id and lower_ind_id).

  • ind_ids (None, or sequence of str) – String with format specifiers to id each level of sites with. Will be automatically generated like (tns[0].site_ind_id, "__ind_a{}__", "__ind_b{}__", ...) if not given.

  • inplace (bool) – Whether to modify the input tensor networks inplace.

Returns:

tns_aligned

Return type:

sequence of TensorNetwork

quimb.tensor.tensor_network_apply_op_vec(A, x, which_A='lower', contract=False, fuse_multibonds=True, compress=False, inplace=False, inplace_A=False, **compress_opts)[source]

Apply a general a general tensor network representing an operator (has upper_ind_id and lower_ind_id) to a tensor network representing a vector (has site_ind_id), by contracting each pair of tensors at each site then compressing the resulting tensor network. How the compression takes place is determined by the type of tensor network passed in. The returned tensor network has the same site indices as x, and it is the lower_ind_id of A that is contracted.

This is like performing A.to_dense() @ x.to_dense(), or the transpose thereof, depending on the value of which_A.

Parameters:
  • A (TensorNetworkGenOperator) – The tensor network representing the operator.

  • x (TensorNetworkGenVector) – The tensor network representing the vector.

  • which_A ({"lower", "upper"}, optional) – Whether to contract the lower or upper indices of A with the site indices of x.

  • contract (bool) – Whether to contract the tensors at each site after applying the operator, yielding a single tensor at each site.

  • fuse_multibonds (bool) – If contract=True, whether to fuse any multibonds after contracting the tensors at each site.

  • compress (bool) – Whether to compress the resulting tensor network.

  • inplace (bool) – Whether to modify x, the input vector tensor network inplace.

  • inplace_A (bool) – Whether to modify A, the operator tensor network inplace.

  • compress_opts – Options to pass to tn.compress, where tn is the resulting tensor network, if compress=True.

Returns:

The same type as x.

Return type:

TensorNetworkGenVector

quimb.tensor.tensor_network_apply_op_op(A, B, which_A='lower', which_B='upper', contract=False, fuse_multibonds=True, compress=False, inplace=False, inplace_A=False, **compress_opts)[source]

Apply the operator (has upper and lower site inds) represented by tensor network A to the operator represented by tensor network B. The resulting tensor network has the same upper and lower indices as B. Optionally contract the tensors at each site, fuse any multibonds, and compress the resulting tensor network.

This is like performing A.to_dense() @ B.to_dense(), or various combinations of tranposes thereof, depending on the values of which_A and which_B.

Parameters:
  • A (TensorNetworkGenOperator) – The tensor network representing the operator to apply.

  • B (TensorNetworkGenOperator) – The tensor network representing the target operator.

  • which_A ({"lower", "upper"}, optional) – Whether to contract the lower or upper indices of A.

  • which_B ({"lower", "upper"}, optional) – Whether to contract the lower or upper indices of B.

  • contract (bool) – Whether to contract the tensors at each site after applying the operator, yielding a single tensor at each site.

  • fuse_multibonds (bool) – If contract=True, whether to fuse any multibonds after contracting the tensors at each site.

  • compress (bool) – Whether to compress the resulting tensor network.

  • inplace (bool) – Whether to modify B, the target tensor network inplace.

  • inplace_A (bool) – Whether to modify A, the applied operator tensor network inplace.

  • compress_opts – Options to pass to tn.compress, where tn is the resulting tensor network, if compress=True.

Returns:

The same type as B.

Return type:

TensorNetworkGenOperator

class quimb.tensor.LocalHamGen(H2, H1=None)[source]

Representation of a local hamiltonian defined on a general graph. This combines all two site and one site terms into a single interaction per lattice pair, and caches operations on the terms such as getting their exponential. The sites (nodes) should be hashable and comparable.

Parameters:
  • H2 (dict[tuple[node], array_like]) – The interaction terms, with each key being an tuple of nodes defining an edge and each value the local hamilotonian term for those two nodes.

  • H1 (array_like or dict[node, array_like], optional) – The one site term(s). If a single array is given, assume to be the default onsite term for all terms. If a dict is supplied, the keys should represent specific coordinates like (i, j) with the values the array representing the local term for that site. A default term for all remaining sites can still be supplied with the key None.

terms

The total effective local term for each interaction (with single site terms appropriately absorbed). Each key is a pair of coordinates site_a, site_b with site_a < site_b.

Type:

dict[tuple, array_like]

property nsites

The number of sites in the system.

graph[source]
items()[source]

Iterate over all terms in the hamiltonian. This is mostly for convenient compatibility with compute_local_expectation.

_convert_from_qarray_cached(x)[source]
_flip_cached(x)[source]
_add_cached(x, y)[source]
_div_cached(x, y)[source]
_op_id_cached(x)[source]
_id_op_cached(x)[source]
_expm_cached(x, y)[source]
get_gate(where)[source]

Get the local term for pair where, cached.

get_gate_expm(where, x)[source]

Get the local term for pair where, matrix exponentiated by x, and cached.

apply_to_arrays(fn)[source]

Apply the function fn to all the arrays representing terms.

_nx_color_ordering(strategy='smallest_first', interchange=True)[source]

Generate a term ordering based on a coloring on the line graph.

get_auto_ordering(order='sort', **kwargs)[source]

Get an ordering of the terms to use with TEBD, for example. The default is to sort the coordinates then greedily group them into commuting sets.

Parameters:

order ({'sort', None, 'random', str}) –

How to order the terms before greedily grouping them into commuting (non-coordinate overlapping) sets:

  • 'sort' will sort the coordinate pairs first.

  • None will use the current order of terms which should match the order they were supplied to this LocalHam2D instance.

  • 'random' will randomly shuffle the coordinate pairs before grouping them - not the same as returning a completely random order.

  • 'random-ungrouped' will randomly shuffle the coordinate pairs but not group them at all with respect to commutation.

Any other option will be passed as a strategy to networkx.coloring.greedy_color to generate the ordering.

Returns:

Sequence of coordinate pairs.

Return type:

list[tuple[node]]

__repr__()[source]

Return repr(self).

draw(ordering='sort', show_norm=True, figsize=None, fontsize=8, legend=True, ax=None, **kwargs)[source]

Plot this Hamiltonian as a network.

Parameters:
  • ordering ({'sort', None, 'random'}, optional) – An ordering of the termns, or an argument to be supplied to quimb.tensor.tensor_arbgeom_tebd.LocalHamGen.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.SimpleUpdateGen(psi0, ham, tau=0.01, D=None, imag=True, gate_opts=None, ordering=None, second_order_reflect=False, compute_energy_every=None, compute_energy_final=True, compute_energy_opts=None, compute_energy_fn=None, compute_energy_per_site=False, callback=None, keep_best=False, progbar=True)[source]

Bases: TEBDGen

Simple update for arbitrary geometry hamiltonians.

gate(U, where)[source]

Perform single gate U at coordinate pair where. This is the the most common method to override.

compute_energy()[source]

Compute and return the energy of the current state. Subclasses can override this with a custom method to compute the energy.

get_state(absorb_gauges=True)[source]

The default method for retrieving the current state - simply a copy. Subclasses can override this to perform additional transformations.

set_state(psi, gauges=None)[source]

The default method for setting the current state - simply a copy. Subclasses can override this to perform additional transformations.

class quimb.tensor.TEBDGen(psi0, ham, tau=0.01, D=None, imag=True, gate_opts=None, ordering=None, second_order_reflect=False, compute_energy_every=None, compute_energy_final=True, compute_energy_opts=None, compute_energy_fn=None, compute_energy_per_site=False, callback=None, keep_best=False, progbar=True)[source]

Generic class for performing time evolving block decimation on an arbitrary graph, i.e. applying the exponential of a Hamiltonian using a product formula that involves applying local exponentiated gates only.

property state

Return a copy of the current state.

property n

The number of sweeps performed.

property D

The maximum bond dimension.

property energy

Return the energy of current state, computing it only if necessary.

sweep(tau)[source]

Perform a full sweep of gates at every pair.

\[\psi \rightarrow \prod_{\{ij\}} \exp(-\tau H_{ij}) \psi\]
_update_progbar(pbar)[source]
evolve(steps, tau=None, progbar=None)[source]

Evolve the state with the local Hamiltonian for steps steps with time step tau.

_check_energy()[source]

Logic for maybe computing the energy if needed.

get_state()[source]

The default method for retrieving the current state - simply a copy. Subclasses can override this to perform additional transformations.

set_state(psi)[source]

The default method for setting the current state - simply a copy. Subclasses can override this to perform additional transformations.

presweep(i)[source]

Perform any computations required before the sweep (and energy computation). For the basic TEBD this is nothing.

gate(U, where)[source]

Perform single gate U at coordinate pair where. This is the the most common method to override.

compute_energy()[source]

Compute and return the energy of the current state. Subclasses can override this with a custom method to compute the energy.

__repr__()[source]

Return repr(self).

quimb.tensor.MPS_COPY(L, phys_dim=2, dtype='float64', **mps_opts)[source]

Build a matrix product state representation of the COPY tensor.

Parameters:
  • L (int) – The number of sites.

  • phys_dim (int, optional) – The physical (site) dimensions, defaults to 2.

  • dtype (str or dtype, optional) – The data type of the tensor network, defaults to ‘float64’.

Return type:

MatrixProductState

quimb.tensor.HTN2D_classical_ising_partition_function(Lx, Ly, beta, h=0.0, j=1.0, ind_id='s{},{}', cyclic=False)[source]

Hyper tensor network representation of the 2D classical ising model partition function. The indices will be shared by 4 or 5 tensors depending on whether h is non-zero. As opposed to the ‘normal’ tensor network, here each classical spin is still a single index, which is easier to contract exactly.

Parameters:
  • Lx (int) – Length of side x.

  • Ly (int) – Length of side y.

  • beta (float) – The inverse temperature.

  • h (float, optional) – The magnetic field strength.

  • j (float, dict, or callable, optional) – The interaction strength, positive being ferromagnetic. If a dict should contain entries for each edge, keyed by the edge. If a callable should have the signature j(node_a, node_b) and return a float.

  • cyclic (bool or (bool, bool), optional) – Whether to use periodic boundary conditions. X and Y can be specified separately using a tuple.

  • ind_id (str, optional) – How to label the indices i.e. ind_id.format(i, j), each of which corresponds to a single classical spin.

Return type:

TensorNetwork

quimb.tensor.HTN3D_classical_ising_partition_function(Lx, Ly, Lz, beta, j=1.0, h=0.0, cyclic=False, ind_id='s{},{},{}')[source]

Hyper tensor network representation of the 3D classical ising model partition function. The indices will be shared by 6 or 7 tensors depending on whether h is non-zero. As opposed to the ‘normal’ tensor network, here each classical spin is still a single index, which is easier to contract exactly.

Parameters:
  • Lx (int) – Length of side x.

  • Ly (int) – Length of side y.

  • Lz (int) – Length of side z.

  • beta (float) – The inverse temperature.

  • j (float, dict, or callable, optional) – The interaction strength, positive being ferromagnetic. If a dict should contain entries for each edge, keyed by the edge. If a callable should have the signature j(node_a, node_b) and return a float.

  • h (float, optional) – The magnetic field strength.

  • cyclic (bool or (bool, bool, bool), optional) – Whether to use periodic boundary conditions. X, Y and Z can be specified separately using a tuple.

  • ind_id (str, optional) – How to label the indices i.e. ind_id.format(i, j, k), each of which corresponds to a single classical spin.

Return type:

TensorNetwork

quimb.tensor.HTN_classical_partition_function_from_edges(edges, beta, j=1.0, h=0.0, site_ind_id='s{}', site_tag_id='I{}', bond_tag_id='B{},{}')[source]

Build a hyper tensor network representation of a classical ising model partition function by specifying graph edges. There will be a single tensor per interaction rather than per site, as well as a single tensor for each site, if h != 0.0.

Parameters:
  • edges (sequence of tuple[hashable, hashable]) – The graph edges, as a sequence of pairs of hashable objects, for example integers, representing the nodes. You can redundantly specify (u, v) and (v, u) and only one edge will be added.

  • beta (float, optional) – The inverse temperature.

  • j (float, dict, or callable, optional) – The interaction strength, positive being ferromagnetic. If a dict should contain entries for each edge, keyed by the edge. If a callable should have the signature j(node_a, node_b) and return a float.

  • h (float, or callable, optional) – The magnetic field strength. If a callable should have the signature h(node) and return a float.

  • site_ind_id (str, optional) – A string formatter for naming tensor indices like site_ind_id.format(node).

  • site_tag_id (str, optional) – A string formatter for naming tensor tags like site_tag_id.format(node).

  • bond_tag_id (str, optional) – A string formatter for naming tensor tags like bond_tag_id.format(node_a, node_b).

Return type:

TensorNetwork

quimb.tensor.HTN_CP_from_sites_and_fill_fn(fill_fn, sites, D, phys_dim=2, site_tag_id='I{}', site_ind_id='k{}', bond_ind=None)[source]

Create a CP-decomposition structured hyper tensor network state from a sequence of sites and a fill function.

Parameters:
  • fill_fn (callable) – A function that takes a shape and returns an array.

  • sites (sequence of hashable) – The sites of the tensor network.

  • D (int) – The hyper bond dimension connecting tensors.

  • phys_dim (int, optional) – The size of the outer, physical indices.

  • site_tag_id (str, optional) – String with formatter to tag sites.

  • site_ind_id (str, optional) – String with formatter to tag indices (if phys_dim specified).

Return type:

TensorNetworkGenVector

quimb.tensor.HTN_dual_from_edges_and_fill_fn(fill_fn, edges, D, phys_dim=None, site_tag_id='I{}', site_ind_id='k{}')[source]

Create a hyper tensor network with a tensor on each bond and a hyper index on each node.

quimb.tensor.HTN_from_clauses(clauses, weights=None, mode='parafac', dtype='float64', clause_tag_id='CLAUSE{}', var_ind_id='var{}', weight_tag_id='WEIGHT{}')[source]

Given a list of clauses, create a hyper tensor network, with a single hyper index for each variable, and single tensor or tensor decomposition for each clause. If weights are given, there will also be a single tensor for each non-trivially weighted variable.

Parameters:
  • clauses (sequence of tuple[int]) – The clauses as a sequence of tuples of integers. Each integer represents a variable, and the sign indicates whether it is negated. The variables thus must be non-zero integers.

  • weights (dict[int, float], optional) – The weights for each variable. Each key should be a signed variable integer, such that relative weights for a variable v are (weights[-v], weights[v]). If only one is given of this pair, the other is assumed to sum to 1. If a variable is not supplied, or weights=None, then both weights are assumed to be 1 and no tensor is created for the variable.

  • mode ({'parafac', 'mps', 'dense', int}, optional) –

    How to represent the clauses:

    • ’parafac’ - N rank-2 tensors connected by a single hyper index. You could further call hyperinds_resolve() for more options to convert the hyper index into a (decomposed) COPY-tensor.

    • ’mps’ - N rank-3 tensors connected along a 1D line.

    • ’dense’ - contract the hyper index.

    • int - use the ‘parafac’ mode, but only if the length of a clause is larger than this threshold.

    Note that variables are always represented by a single (hyper) index, which is like an implicit PARAFAC decomposition.

  • dtype (str) – The data type of the tensors.

  • clause_tag_id (str) – The tag to use for the clause tensors. The tag will be formatted with the clause index.

  • var_ind_id (str) – The index to use for the variable tensors. The index will be formatted with the variable index.

  • weight_tag_id (str) – The tag to use for the weight tensors. The tag will be formatted with the variable index.

Returns:

htn

Return type:

TensorNetwork

quimb.tensor.HTN_from_cnf(fname, mode='parafac', dtype='float64', clause_tag_id='CLAUSE{}', var_ind_id='var{}', weight_tag_id='WEIGHT{}', **kwargs)[source]

Create a hyper tensor network from a ‘.cnf’ or ‘.wcnf’ file - i.e. a model counting or weighted model counting instance specification.

Parameters:
  • fname (str) – Path to a ‘.cnf’ or ‘.wcnf’ file.

  • mode ({'parafac', 'mps', 'dense', int}, optional) –

    How to represent the clauses:

    • ’parafac’ - N rank-2 tensors connected by a single hyper index. You could further call hyperinds_resolve() for more options to convert the hyper index into a (decomposed) COPY-tensor.

    • ’mps’ - N rank-3 tensors connected along a 1D line.

    • ’dense’ - contract the hyper index.

    • int - use the ‘parafac’ mode, but only if the length of a clause is larger than this threshold.

  • dtype (str or dtype, optional) – Data type of the tensors.

  • clause_tag_id (str, optional) – Format string for clause tags.

  • var_ind_id (str, optional) – Format string for variable indices.

  • weight_tag_id (str, optional) – Format string for weight tags.

  • kwargs – Additional keyword arguments passed to HTN_from_clauses().

Returns:

htn

Return type:

TensorNetwork

quimb.tensor.HTN_random_ksat(k, num_variables, num_clauses=None, alpha=None, seed=None, allow_repeat_variables=False, mode='parafac', dtype='float64', clause_tag_id='CLAUSE{}', variable_ind_id='var{}')[source]

Create a random k-SAT instance encoded as a hyper tensor network.

Parameters:
  • k (int) – Number of variables per clause.

  • num_variables (int) – Number of variables in the instance.

  • num_clauses (int, optional) – Number of clauses in the instance. If not specified, will be determined from alpha.

  • alpha (float, optional) – If num_clauses is not directly specified then the average number of clauses per variable. Taken as a Poisson parameter. Either this or num_clauses must be specified.

  • seed (int, optional) – Random seed.

  • allow_repeat_variables (bool, optional) – Whether to allow the same variable to appear multiple times in a single clause.

  • mode ({'parafac', 'mps', 'dense', int}, optional) –

    How to represent the clauses:

    • ’parafac’ - N rank-2 tensors connected by a single hyper index. You could further call hyperinds_resolve() for more options to convert the hyper index into a (decomposed) COPY-tensor.

    • ’mps’ - N rank-3 tensors connected along a 1D line.

    • ’dense’ - contract the hyper index.

    • int - use the ‘parafac’ mode, but only if the length of a clause is larger than this threshold.

    Note that variables are always represented by a single (hyper) index, which is like an implicit PARAFAC decomposition.

  • dtype (str, optional) – Data type of the tensors.

  • clause_tag_id (str, optional) – Format string for clause tags. Should contain a single {} which will be replaced by the clause number.

  • variable_ind_id (str, optional) – Format string for variable indices. Should contain a single {} which will be replaced by the variable number.

Return type:

TensorNetwork

quimb.tensor.MPO_ham_heis(L, j=1.0, bz=0.0, *, S=1 / 2, cyclic=False, **mpo_opts)[source]

Heisenberg Hamiltonian in MPO form.

\[H_\mathrm{Heis} = \sum_{i} ( J_X S^X_i S^X_{i + 1} + J_Y S^Y_i S^Y_{i + 1} + J_Z S^Z_i S^Z_{i + 1} ) - B_Z \sum_{i} S^Z_i\]

Note the default convention of antiferromagnetic interactions and spin operators not Pauli matrices.

Parameters:
  • L (int) – The number of sites.

  • j (float or (float, float, float), optional) – The XX, YY and ZZ interaction strength. Positive is antiferromagnetic.

  • bz (float, optional) – The Z-magnetic field strength.

  • S ({1/2, 1, 3/2, ...}, optional) – The underlying spin of the system, defaults to 1/2.

  • cyclic (bool, optional) – Generate a MPO with periodic boundary conditions or not, default is open boundary conditions.

  • mpo_opts – Supplied to MatrixProductOperator.

Return type:

MatrixProductOperator

quimb.tensor.MPO_ham_ising(L, j=1.0, bx=0.0, *, S=1 / 2, cyclic=False, **mpo_opts)[source]

Ising Hamiltonian in MPO form.

\[H_\mathrm{Ising} = J \sum_{i} S^Z_i S^Z_{i + 1} - B_x \sum_{i} S^X_i\]

Note the default convention of antiferromagnetic interactions and spin operators not Pauli matrices.

Parameters:
  • L (int) – The number of sites.

  • j (float, optional) – The ZZ interaction strength. Positive is antiferromagnetic.

  • bx (float, optional) – The X-magnetic field strength.

  • S ({1/2, 1, 3/2, ...}, optional) – The underlying spin of the system, defaults to 1/2.

  • cyclic (bool, optional) – Generate a MPO with periodic boundary conditions or not, default is open boundary conditions.

  • local_ham_1d_opts (mpo_opts or) – Supplied to MatrixProductOperator.

Return type:

MatrixProductOperator

quimb.tensor.MPO_ham_mbl(L, dh, j=1.0, seed=None, S=1 / 2, *, cyclic=False, dh_dist='s', dh_dim=1, beta=None, **mpo_opts)[source]

The many-body-localized spin hamiltonian in MPO form.

\[H_\mathrm{MBL} = \sum_{i} ( J_X S^X_i S^X_{i + 1} + J_Y S^Y_i S^Y_{i + 1} + J_Z S^Z_i S^Z_{i + 1} ) - \sum_{i} h_i S^Z_i\]

Note the default convention of antiferromagnetic interactions and spin operators not Pauli matrices.

Parameters:
  • L (int) – Number of spins.

  • dh (float) – Random noise strength.

  • j (float, or (float, float, float), optional) – Interaction strength(s) e.g. 1 or (1., 1., 0.5). Positive is antiferromagnetic.

  • seed (int, optional) – Random number to seed the noise with.

  • S ({1/2, 1, 3/2, ...}, optional) – The underlying spin of the system, defaults to 1/2.

  • cyclic (bool, optional) – Whether to use periodic boundary conditions - default is False.

  • dh_dist ({'s', 'g', 'qp'}, optional) – Whether to use sqaure, guassian or quasiperiodic noise.

  • beta (float, optional) – Frequency of the quasirandom noise, only if dh_dist='qr'.

  • mpo_opts – Supplied to MatrixProductOperator.

Return type:

MatrixProductOperator

quimb.tensor.MPO_ham_XY(L, j=1.0, bz=0.0, *, S=1 / 2, cyclic=False, **mpo_opts)[source]

XY-Hamiltonian in MPO form.

\[H_\mathrm{XY} = \sum_{i} ( J_X S^X_i S^X_{i + 1} + J_Y S^Y_i S^Y_{i + 1} ) - B_x \sum_{i} S^Z_i\]

Note the default convention of antiferromagnetic interactions and spin operators not Pauli matrices.

Parameters:
  • L (int) – The number of sites.

  • j (float or (float, float), optional) – The XX and YY interaction strength. Positive is antiferromagnetic.

  • bz (float, optional) – The Z-magnetic field strength.

  • S ({1/2, 1, 3/2, ...}, optional) – The underlying spin of the system, defaults to 1/2.

  • cyclic (bool, optional) – Generate a MPO with periodic boundary conditions or not, default is open boundary conditions.

  • local_ham_1d_opts (mpo_opts or) – Supplied to MatrixProductOperator.

Return type:

MatrixProductOperator

quimb.tensor.MPO_identity(L, phys_dim=2, dtype='float64', cyclic=False, **mpo_opts)[source]

Generate an identity MPO of size L.

Parameters:
  • L (int) – The number of sites.

  • phys_dim (int, optional) – The physical (site) dimensions, defaults to 2.

  • dtype ({float, complex} or numpy dtype, optional) – Data type of the tensor network.

  • cyclic (bool, optional) – Generate a MPO with periodic boundary conditions or not, default is open boundary conditions.

  • mpo_opts – Supplied to MatrixProductOperator.

quimb.tensor.MPO_identity_like(mpo, **mpo_opts)[source]

Return an identity matrix operator with the same physical index and inds/tags as mpo.

quimb.tensor.MPO_product_operator(arrays, cyclic=False, **mpo_opts)[source]

Return an MPO of bond dimension 1 representing the product of raw operators given in arrays.

Parameters:
  • arrays (sequence of 2D array_like) – The operators to form a tensor product of.

  • cyclic (bool, optional) – Whether to generate a cyclic MPO or not.

  • mpo_opts – Supplied to MatrixProductOperator.

Return type:

MatrixProductOperator

quimb.tensor.MPO_rand(L, bond_dim, phys_dim=2, normalize=True, cyclic=False, herm=False, dtype='float64', dist='normal', loc=0.0, scale=1.0, **mpo_opts)[source]

Generate a random matrix product state.

Parameters:
  • L (int) – The number of sites.

  • bond_dim (int) – The bond dimension.

  • phys_dim (int, optional) – The physical (site) dimensions, defaults to 2.

  • normalize (bool, optional) – Whether to normalize the operator such that trace(A.H @ A) == 1.

  • cyclic (bool, optional) – Generate a MPO with periodic boundary conditions or not, default is open boundary conditions.

  • dtype ({float, complex} or numpy dtype, optional) – Data type of the tensor network.

  • dist ({'normal', 'uniform', 'rademacher', 'exp'}, optional) – Type of random number to generate, defaults to ‘normal’.

  • loc (float, optional) – An additive offset to add to the random numbers.

  • scale (float, optional) – A multiplicative factor to scale the random numbers by.

  • herm (bool, optional) – Whether to make the matrix hermitian (or symmetric if real) or not.

  • mpo_opts – Supplied to MatrixProductOperator.

quimb.tensor.MPO_rand_herm(L, bond_dim, phys_dim=2, normalize=True, dtype='float64', **mpo_opts)[source]

Generate a random hermitian matrix product operator. See MPO_rand.

quimb.tensor.MPO_zeros(L, phys_dim=2, dtype='float64', cyclic=False, **mpo_opts)[source]

Generate a zeros MPO of size L.

Parameters:
  • L (int) – The number of sites.

  • phys_dim (int, optional) – The physical (site) dimensions, defaults to 2.

  • dtype ({float, complex} or numpy dtype, optional) – Data type of the tensor network.

  • cyclic (bool, optional) – Generate a MPO with periodic boundary conditions or not, default is open boundary conditions.

  • mpo_opts – Supplied to MatrixProductOperator.

Return type:

MatrixProductOperator

quimb.tensor.MPO_zeros_like(mpo, **mpo_opts)[source]

Return a zeros matrix product operator with the same physical index and inds/tags as mpo.

Parameters:

mpo (MatrixProductOperator) – The MPO to copy the shape of.

Return type:

MatrixProductOperator

quimb.tensor.MPS_computational_state(binary, dtype='float64', cyclic=False, **mps_opts)[source]

A computational basis state in Matrix Product State form.

Parameters:
  • binary (str or sequence of int) – String specifying the state, e.g. '00101010111' or [0, 0, 1].

  • dtype ({'float64', 'complex128', 'float32', 'complex64'}, optional) – The data type to use for the array representation.

  • cyclic (bool, optional) – Generate a MPS with periodic boundary conditions or not, default open boundary conditions.

  • mps_opts – Supplied to MatrixProductState constructor.

quimb.tensor.MPS_ghz_state(L, dtype='float64', **mps_opts)[source]

Build the chi=2 OBC MPS representation of the GHZ state.

Parameters:
  • L (int) – Number of qubits.

  • dtype ({'float64', 'complex128', 'float32', 'complex64'}, optional) – The underlying data type.

  • mps_opts – Supplied to MatrixProductState.

quimb.tensor.MPS_neel_state(L, down_first=False, dtype='float64', **mps_opts)[source]

Generate the neel state in Matrix Product State form.

Parameters:
  • L (int) – The number of spins.

  • down_first (bool, optional) – Whether to start with ‘1’ (down) or ‘0’ (up) first.

  • mps_opts – Supplied to MatrixProductState constructor.

quimb.tensor.MPS_product_state(arrays, cyclic=False, **mps_opts)[source]

Generate a product state in MatrixProductState form, i,e, with bond dimension 1, from single site vectors described by arrays.

quimb.tensor.MPS_rand_computational_state(L, dtype='float64', **mps_opts)[source]

Generate a random computation basis state, like ‘01101001010’.

Parameters:
  • L (int) – The number of qubits.

  • seed (int, optional) – The seed to use.

  • dtype ({float, complex} or numpy dtype, optional) – Data type of the tensor network.

  • mps_opts – Supplied to MatrixProductState.

quimb.tensor.MPS_rand_state(L, bond_dim, phys_dim=2, normalize=True, cyclic=False, dist='normal', loc=0.0, scale=1.0, dtype='float64', trans_invar=False, **mps_opts)[source]

Generate a random matrix product state.

Parameters:
  • L (int) – The number of sites.

  • bond_dim (int) – The bond dimension.

  • phys_dim (int, optional) – The physical (site) dimensions, defaults to 2.

  • normalize (bool, optional) – Whether to normalize the state.

  • cyclic (bool, optional) – Generate a MPS with periodic boundary conditions or not, default is open boundary conditions.

  • dist ({'normal', 'uniform', 'rademacher', 'exp'}, optional) – Type of random number to generate, defaults to ‘normal’.

  • loc (float, optional) – An additive offset to add to the random numbers.

  • scale (float, optional) – A multiplicative factor to scale the random numbers by.

  • dtype ({float, complex} or numpy dtype, optional) – Data type of the tensor network.

  • trans_invar (bool (optional)) – Whether to generate a translationally invariant state, requires cyclic=True.

  • mps_opts – Supplied to MatrixProductState.

quimb.tensor.MPS_sampler(L, dtype=complex, squeeze=True, **mps_opts)[source]

A product state for sampling tensor network traces. Seen as a vector it has the required property that psi.H @ psi == d always for hilbert space size d.

quimb.tensor.MPS_w_state(L, dtype='float64', **mps_opts)[source]

Build the chi=2 OBC MPS representation of the W state.

Parameters:
  • L (int) – Number of qubits.

  • dtype ({'float64', 'complex128', 'float32', 'complex64'}, optional) – The underlying data type.

  • mps_opts – Supplied to MatrixProductState.

quimb.tensor.MPS_zero_state(L, bond_dim=1, phys_dim=2, cyclic=False, dtype='float64', **mps_opts)[source]

The all-zeros MPS state, of given bond-dimension.

Parameters:
  • L (int) – The number of sites.

  • bond_dim (int, optional) – The bond dimension, defaults to 1.

  • phys_dim (int, optional) – The physical (site) dimensions, defaults to 2.

  • cyclic (bool, optional) – Generate a MPS with periodic boundary conditions or not, default is open boundary conditions.

  • dtype ({float, complex} or numpy dtype, optional) – Data type of the tensor network.

  • mps_opts – Supplied to MatrixProductState.

quimb.tensor.NNI_ham_heis[source]
quimb.tensor.NNI_ham_ising[source]
quimb.tensor.NNI_ham_mbl[source]
quimb.tensor.NNI_ham_XY[source]
quimb.tensor.SpinHam[source]
class quimb.tensor.SpinHam1D(S=1 / 2, cyclic=False)[source]

Class for easily building custom spin hamiltonians in MPO or LocalHam1D form. Currently limited to nearest neighbour interactions (and single site terms). It is possible to set ‘default’ translationally invariant terms, but also terms acting on specific sites only (which take precedence). It is also possible to build a sparse matrix version of the hamiltonian (obviously for small sizes only).

Parameters:
  • S (float, optional) – The type of spin, defaults to 1/2.

  • cyclic (bool, optional) – Whether to use periodic boundary conditions - default is False.

Examples

Initialize the spin hamiltonian builder:

>>> builder = SpinHam1D(S=3 / 2)

Add some two-site terms:

>>> builder += 0.5, '+', '-'
>>> builder += 0.5, '-', '+'
>>> builder += 1.0, 'Z', 'Z'

Add a single site term:

>>> builder -= 0.3, 'Z'

Build a MPO version of the hamiltonian for use with DMRG:

>>> mpo_ham = builder.build_mpo(100)
>>> mpo_ham
<MatrixProductOperator(tensors=100, L=100, max_bond=5)>

Build a LocalHam1D version of the hamiltonian for use with TEBD:

>>> builder.build_local_ham(100)
<LocalHam1D(L=100, cyclic=False)>

You can also set terms for specific sites (this overides any of the ‘default’, translationally invariant terms set as above):

>>> builder[10, 11] += 0.75, '+', '-'
>>> builder[10, 11] += 0.75, '-', '+'
>>> builder[10, 11] += 1.5, 'Z', 'Z'

Or specific one-site terms (which again overides any default single site terms set above):

>>> builder[10] += 3.7, 'Z'
>>> builder[11] += 0.0, 'I' # '0' term turns off field
add_term(factor, *operators)[source]

Add another term to the expression to be built.

Parameters:
  • factor (scalar) – Scalar factor to multiply this term by.

  • *operators (str or array) – The operators to use. Can specify one or two for single or two site terms respectively. Can use strings, which are supplied to spin_operator(), or actual arrays as long as they have the correct dimension.

sub_term(factor, *operators)[source]

Subtract a term - simple alias that flips sign of factor.

__iadd__(term)[source]
__isub__(term)[source]
__getitem__(sites)[source]

Part of the machinery that allows terms to be added to specific sites like:

>>> builder[i] += 1/2, 'X'
>>> builder[45, 46] += 1/2, 'Z', 'Z'
__setitem__(sites, value)[source]

Part of the machinery that allows terms to be added to specific sites like:

>>> builder[i] += 1/2, 'X'
>>> builder[45, 46] += 1/2, 'Z', 'Z'

Could also be called directly with a list of terms like:

>>> builder[13, 14] = [(1, 'Z', 'Z'), (0.5, 'X', 'Y')]

Which would overide any terms set so far.

build_mpo(L, upper_ind_id='k{}', lower_ind_id='b{}', site_tag_id='I{}', tags=None, bond_name='')[source]

Build an MPO instance of this spin hamiltonian of size L. See also MatrixProductOperator.

build_sparse(L, **ikron_opts)[source]

Build a sparse matrix representation of this Hamiltonian.

Parameters:
  • L (int, optional) – The number of spins to build the matrix for.

  • ikron_opts – Supplied to ikron().

Returns:

H

Return type:

matrix

_get_spin_op(factor, *ss)[source]
_sum_spin_ops(terms)[source]
build_local_ham(L=None, **local_ham_1d_opts)[source]

Build a nearest neighbour interactor instance of this spin hamiltonian of size L. See also LocalHam1D.

Parameters:

L (int, optional) – The number of spins, if the hamiltonian only has two-site terms this is optional.

Return type:

LocalHam1D

quimb.tensor.TN_matching(tn, max_bond, site_tags=None, fill_fn=None, dtype=None, **randn_opts)[source]

Create a tensor network with the same outer indices as tn but with a single tensor per site with bond dimension max_bond between each connected site. Generally to be used as an initial guess for fitting.

Parameters:
  • tn (TensorNetwork) – The tensor network to match, it can have arbitrary local structure and output indices, as long as site_tags effectively partitions it.

  • max_bond (int) – The bond dimension to use between each site.

  • site_tags (sequence of str, optional) – The tags to use to select the tensors from tn. If not given, uses tn.site_tags. The tensor network built will have one tensor per site, in the order given by site_tags.

  • dtype (dtype, optional) – The data type to use for the new tensors, if not given uses the same as the original tensors.

  • randn_opts – Supplied to randn().

Return type:

TensorNetwork

quimb.tensor.TN2D_classical_ising_partition_function(Lx, Ly, beta, j=1.0, h=0.0, cyclic=False, site_tag_id='I{},{}', x_tag_id='X{}', y_tag_id='Y{}', outputs=(), ind_id='s{},{}')[source]

The tensor network representation of the 2D classical ising model partition function.

Parameters:
  • Lx (int) – Length of side x.

  • Ly (int) – Length of side y.

  • beta (float) – The inverse temperature.

  • j (float, dict, or callable, optional) – The interaction strength, positive being ferromagnetic. If a dict should contain entries for each edge, keyed by the edge. If a callable should have the signature j(node_a, node_b) and return a float.

  • h (float, optional) – The magnetic field strength.

  • cyclic (bool or (bool, bool), optional) – Whether to use periodic boundary conditions. X and Y can be specified separately using a tuple.

  • site_tag_id (str, optional) – String specifier for naming convention of site tags.

  • x_tag_id (str, optional) – String specifier for naming convention of row tags.

  • y_tag_id (str, optional) – String specifier for naming convention of column tags.

  • outputs (sequence of tuple[int, int], optional) – Which sites to generate output indices (i.e. dangling legs) for. The index is named according to ind_id.

  • ind_id (str, optional) – How to label the indices i.e. ind_id.format(i, j), each of which corresponds to a single classical spin in outputs.

Return type:

TensorNetwork2D

quimb.tensor.TN2D_corner_double_line(Lx, Ly, line_dim=2, tiling=2, fill_missing_edges=True, site_tag_id='I{},{}', x_tag_id='X{}', y_tag_id='Y{}', **kwargs)[source]

Build a 2D ‘corner double line’ (CDL) tensor network. Each plaquette contributes a matrix (by default the identity) at each corner, connected in a loop. The corners for each site are then grouped and optionally contracted. Such a tensor network has strong local correlations. See https://arxiv.org/abs/1412.0732. If the sites are not contracted, the resulting network is a product of loops that can be easily and exactly contracted.

Note that if identity matrices are used, the contracted value of the tensor network is line_dim**num_plaquettes.

Parameters:
  • Lx (int) – Length of side x.

  • Ly (int) – Length of side y.

  • line_dim (int, optional) – The dimension of the matrices at each corner. If contract is True, then the resulting bonds with have dimension line_dim**tiling.

  • tiling ({1, 2}, optional) – How to tile the plaquettes. If 1, the plaquettes are tiled in a checkerboard pattern resulting in a single line per edge. If 2, the plaquettes are tiled in a dense pattern resulting in two lines per edge.

  • fill_missing_edges (bool, optional) – Whether to fill in the missing edges around the border with open strings, ensuring every bond exists and has the same dimension.

  • site_tag_id (str, optional) – String specifier for naming convention of site tags.

  • x_tag_id (str, optional) – String specifier for naming convention of row tags.

  • y_tag_id (str, optional) – String specifier for naming convention of column tags.

  • kwargs – Additional keyword arguments are passed to TN_from_strings().

Return type:

TensorNetwork2D

See also

TN_from_strings

quimb.tensor.TN2D_embedded_classical_ising_partition_function(Jij, beta, outputs=(), ordering=None, sites_location='side', UPLO='auto', contract_sites=True, site_tag_id='I{},{}', x_tag_id='X{}', y_tag_id='Y{}', ind_id='s{}')[source]

Construct a (triangular) ‘2D’ tensor network representation of the classical ising model partition function with all-to-all interactions, by embedding it in a 2D lattice. For N spins this will have N(N-1)/2 tensors, present at sites (i, j) where i > j. If outputs is supplied, then dangling indices will be added for each output, to give a ‘standard’ TN representation of the unnormalized marginal distribution over those outputs. Since each spin is effectively “delocalized” into a COPY-tensor MPS spanning the lattice, there is a choice of where to put the outputs, specified by sites_location.

sites_location="side":

...   .  .  .  ╭──
               │
j=2   .  .  ╭──O──...
            │  │
j=1   .  ╭──O──O──...
         │  │  │
j=0   ╭──O──O──O──...
      │  │  │  │
      s0 s1 s2 s3  <- site indices

    i=0, 1, 2, 3, ...

sites_location="diag":

...   .  .  s3 ╭──
              ╲│
j=2   .  s2 ╭──O──...
           ╲│  │
j=1   s1 ╭──O──O──...
        ╲│  │  │
j=0  s0──O──O──O──...

    i=0, 1, 2, 3, ...
Parameters:
  • Jij (array_like or dict[(int, int), float]) – The couplings, as a square matrix or explicit dict. If a matrix, the upper or lower triangle (corresponding to UPLO) should the pairwise interaction strengths. If a dict, then each non-zero interaction can be specified explicitly.

  • beta (float) – The inverse temperature.

  • outputs (sequence of int, optional) – Which sites to generate output indices (i.e. dangling legs) for. The index is named according to ind_id. The location of the output depends on sites_location.

  • ordering (sequence of int, optional) – If supplied, the ordering of the embedded spins into the lattice.

  • sites_location ({"side", "diag"}, optional) – Whether to place the output indices on the side or diagonally. If "side" then the output indices will be placed along the ‘y-min’ border, i.e. [(j, 0) for j in range(1, N)], with two on the first tensor. If "diag" then the output indices will be placed along the central diagonal fold of the lattice, i.e. [(j + 1, j) for j in range(1, N)], with two on the first tensor.

  • UPLO ({"auto", "L", "U"}, optional) – Whether to read the couplings in from J in lower (‘L’: i >= j) or upper (‘U’: i <= j) form. If J is a dict then this only matters if both are present and in that case acts as a preference. If "auto" then either the lower or upper, or symmetric distances can be supplied, but an error is raised if both are.

  • contract_sites (bool, optional) – Whether to contract the sites of the TN, which after initial construction will have one horizontol spin-rail, one vertical spin-rail and one interaction tensor per site.

  • site_tag_id (str, optional) – String formatter specifying how to label each site.

  • x_tag_id (str, optional) – String formatter specifying how to label each x-plane.

  • y_tag_id (str, optional) – String formatter specifying how to label each y-plane.

  • ind_id (str, optional) – How to label the indices i.e. ind_id.format(i), each of which corresponds to a single classical spin in outputs.

Return type:

TensorNetwork2D

quimb.tensor.TN2D_empty(Lx, Ly, D, cyclic=False, site_tag_id='I{},{}', x_tag_id='X{}', y_tag_id='Y{}', dtype='float64')[source]

A scalar 2D lattice tensor network initialized with empty tensors.

Parameters:
  • Lx (int) – Length of side x.

  • Ly (int) – Length of side y.

  • D (int) – The bond dimension connecting sites.

  • cyclic (bool or (bool, bool), optional) – Whether to use periodic boundary conditions. X and Y can be specified separately using a tuple.

  • site_tag_id (str, optional) – String specifier for naming convention of site tags.

  • x_tag_id (str, optional) – String specifier for naming convention of row tags.

  • y_tag_id (str, optional) – String specifier for naming convention of column tags.

  • dtype (str, optional) – The data type of the tensors.

Return type:

TensorNetwork2D

quimb.tensor.TN2D_from_fill_fn(fill_fn, Lx, Ly, D, cyclic=False, site_tag_id='I{},{}', x_tag_id='X{}', y_tag_id='Y{}')[source]

A scalar 2D lattice tensor network with tensors filled by a function.

Parameters:
  • fill_fn (callable) – A function with signature fill_fn(shape) -> array, used to fill each tensor.

  • Lx (int) – Length of side x.

  • Ly (int) – Length of side y.

  • D (int) – The bond dimension connecting sites.

  • cyclic (bool or (bool, bool), optional) – Whether to use periodic boundary conditions. X and Y can be specified separately using a tuple.

  • site_tag_id (str, optional) – String specifier for naming convention of site tags.

  • x_tag_id (str, optional) – String specifier for naming convention of row tags.

  • y_tag_id (str, optional) – String specifier for naming convention of column tags.

Return type:

TensorNetwork2D

quimb.tensor.TN2D_rand(Lx, Ly, D, cyclic=False, site_tag_id='I{},{}', x_tag_id='X{}', y_tag_id='Y{}', dist='normal', loc=0, scale=1, seed=None, dtype='float64')[source]

A random scalar 2D lattice tensor network.

Parameters:
  • Lx (int) – Length of side x.

  • Ly (int) – Length of side y.

  • D (int) – The bond dimension connecting sites.

  • cyclic (bool or (bool, bool), optional) – Whether to use periodic boundary conditions. X and Y can be specified separately using a tuple.

  • site_tag_id (str, optional) – String specifier for naming convention of site tags.

  • x_tag_id (str, optional) – String specifier for naming convention of row tags.

  • y_tag_id (str, optional) – String specifier for naming convention of column tags.

  • dist ({'normal', 'uniform', 'rademacher', 'exp'}, optional) – Type of random number to generate, defaults to ‘normal’.

  • loc (float, optional) – An additive offset to add to the random numbers.

  • scale (float, optional) – A multiplicative factor to scale the random numbers by.

  • seed (int, optional) – A random seed.

  • dtype (dtype, optional) – Data type of the random arrays.

Return type:

TensorNetwork2D

quimb.tensor.TN2D_rand_symmetric(Lx, Ly, D, cyclic=False, site_tag_id='I{},{}', x_tag_id='X{}', y_tag_id='Y{}', dist='normal', loc=0, scale=1, seed=None, dtype='float64')[source]

Create a random 2D lattice tensor network where every tensor is symmetric up to index permutations.

Parameters:
  • Lx (int) – Length of side x.

  • Ly (int) – Length of side y.

  • D (int) – The bond dimension connecting sites.

  • cyclic (bool or (bool, bool), optional) – Whether to use periodic boundary conditions. X and Y can be specified separately using a tuple.

  • site_tag_id (str, optional) – String specifier for naming convention of site tags.

  • x_tag_id (str, optional) – String specifier for naming convention of row tags.

  • y_tag_id (str, optional) – String specifier for naming convention of column tags.

  • dist ({'normal', 'uniform', 'rademacher', 'exp'}, optional) – Type of random number to generate, defaults to ‘normal’.

  • loc (float, optional) – An additive offset to add to the random numbers.

  • scale (float, optional) – A multiplicative factor to scale the random numbers by.

  • seed (int, optional) – A random seed.

  • dtype (dtype, optional) – Data type of the random arrays.

Return type:

TensorNetwork2D

quimb.tensor.TN2D_rand_hidden_loop(Lx, Ly, *, cyclic=False, line_dim=2, line_density=2, seed=None, dist='normal', dtype='float64', loc=0.0, scale=1.0, gauge_random=True, site_tag_id='I{},{}', x_tag_id='X{}', y_tag_id='Y{}', **kwargs)[source]
quimb.tensor.TN2D_with_value(value, Lx, Ly, D, cyclic=False, site_tag_id='I{},{}', x_tag_id='X{}', y_tag_id='Y{}', dtype=None)[source]

A scalar 2D lattice tensor network with every element set to value. This uses numpy.broadcast_to and therefore essentially no memory.

Parameters:
  • value (scalar) – The value to fill the tensors with.

  • Lx (int) – Length of side x.

  • Ly (int) – Length of side y.

  • D (int) – The bond dimension connecting sites.

  • cyclic (bool or (bool, bool), optional) – Whether to use periodic boundary conditions. X and Y can be specified separately using a tuple.

  • site_tag_id (str, optional) – String specifier for naming convention of site tags.

  • x_tag_id (str, optional) – String specifier for naming convention of row tags.

  • y_tag_id (str, optional) – String specifier for naming convention of column tags.

  • dtype (str, optional) – The data type of the tensors.

Return type:

TensorNetwork2D

quimb.tensor.TN3D_classical_ising_partition_function(Lx, Ly, Lz, beta, j=1.0, h=0.0, cyclic=False, site_tag_id='I{},{},{}', x_tag_id='X{}', y_tag_id='Y{}', z_tag_id='Z{}', outputs=(), ind_id='s{},{},{}')[source]

Tensor network representation of the 3D classical ising model partition function.

Parameters:
  • Lx (int) – Length of side x.

  • Ly (int) – Length of side y.

  • Lz (int) – Length of side z.

  • beta (float) – The inverse temperature.

  • j (float, dict, or callable, optional) – The interaction strength, positive being ferromagnetic. If a dict should contain entries for each edge, keyed by the edge. If a callable should have the signature j(node_a, node_b) and return a float.

  • h (float, optional) – The magnetic field strength.

  • cyclic (bool or (bool, bool, bool), optional) – Whether to use periodic boundary conditions. X, Y and Z can be specified separately using a tuple.

  • site_tag_id (str, optional) – String formatter specifying how to label each site.

  • x_tag_id (str, optional) – String formatter specifying how to label each x-plane.

  • y_tag_id (str, optional) – String formatter specifying how to label each y-plane.

  • z_tag_id (str, optional) – String formatter specifying how to label each z-plane.

  • outputs (sequence of tuple[int, int, int], optional) – Which sites to generate output indices (i.e. dangling legs) for. The index is named according to ind_id.

  • ind_id (str, optional) – How to label the indices i.e. ind_id.format(i, j, k), each of which corresponds to a single classical spin in outputs.

Return type:

TensorNetwork

quimb.tensor.TN3D_corner_double_line(Lx, Ly, Lz, line_dim=2, tiling=2, fill_missing_edges=True, site_tag_id='I{},{},{}', x_tag_id='X{}', y_tag_id='Y{}', z_tag_id='Z{}', **kwargs)[source]
quimb.tensor.TN3D_empty(Lx, Ly, Lz, D, cyclic=False, site_tag_id='I{},{},{}', x_tag_id='X{}', y_tag_id='Y{}', z_tag_id='Z{}', dtype='float64')[source]

A scalar 3D lattice tensor network initialized with empty tensors.

Parameters:
  • Lx (int) – Length of side x.

  • Ly (int) – Length of side y.

  • Lz (int) – Length of side z.

  • D (int) – The bond dimension connecting sites.

  • cyclic (bool or (bool, bool, bool), optional) – Whether to use periodic boundary conditions. X, Y and Z can be specified separately using a tuple.

  • site_tag_id (str, optional) – String formatter specifying how to label each site.

  • dtype (dtype, optional) – Data type of the random arrays.

  • seed (int, optional) – Random seed.

Return type:

TensorNetwork3D

quimb.tensor.TN3D_from_fill_fn(fill_fn, Lx, Ly, Lz, D, cyclic=False, site_tag_id='I{},{},{}', x_tag_id='X{}', y_tag_id='Y{}', z_tag_id='Z{}')[source]

A scalar 3D lattice tensor network with tensors filled by a function.

Parameters:
  • fill_fn (callable) – A function with signature fill_fn(shape) -> array, used to fill each tensor.

  • Lx (int) – Length of side x.

  • Ly (int) – Length of side y.

  • Lz (int) – Length of side z.

  • D (int) – The bond dimension connecting sites.

  • cyclic (bool or (bool, bool, bool), optional) – Whether to use periodic boundary conditions. X, Y and Z can be specified separately using a tuple.

  • site_tag_id (str, optional) – String formatter specifying how to label each site.

  • dtype (dtype, optional) – Data type of the random arrays.

Return type:

TensorNetwork3D

quimb.tensor.TN3D_rand(Lx, Ly, Lz, D, cyclic=False, site_tag_id='I{},{},{}', x_tag_id='X{}', y_tag_id='Y{}', z_tag_id='Z{}', dist='normal', loc=0.0, scale=1.0, seed=None, dtype='float64')[source]

A random scalar 3D lattice tensor network.

Parameters:
  • Lx (int) – Length of side x.

  • Ly (int) – Length of side y.

  • Lz (int) – Length of side z.

  • D (int) – The bond dimension connecting sites.

  • cyclic (bool or (bool, bool, bool), optional) – Whether to use periodic boundary conditions. X, Y and Z can be specified separately using a tuple.

  • site_tag_id (str, optional) – String formatter specifying how to label each site.

  • dtype (dtype, optional) – Data type of the random arrays.

  • seed (int, optional) – Random seed.

Return type:

TensorNetwork

quimb.tensor.TN3D_rand_hidden_loop(Lx, Ly, Lz, *, cyclic=False, line_dim=2, line_density=2, seed=None, dist='normal', dtype='float64', loc=0.0, scale=1.0, gauge_random=True, site_tag_id='I{},{},{}', x_tag_id='X{}', y_tag_id='Y{}', z_tag_id='Z{}', **kwargs)[source]
quimb.tensor.TN3D_with_value(value, Lx, Ly, Lz, D, cyclic=False, site_tag_id='I{},{},{}', x_tag_id='X{}', y_tag_id='Y{}', z_tag_id='Z{}', dtype=None)[source]

A scalar 2D lattice tensor network with every element set to value. This uses numpy.broadcast_to and therefore essentially no memory.

Parameters:
  • value (scalar) – The value to fill the tensors with.

  • Lx (int) – Length of side x.

  • Ly (int) – Length of side y.

  • Lz (int) – Length of side z.

  • D (int) – The bond dimension connecting sites.

  • cyclic (bool or (bool, bool, bool), optional) – Whether to use periodic boundary conditions. X, Y and Z can be specified separately using a tuple.

  • site_tag_id (str, optional) – String formatter specifying how to label each site.

  • dtype (dtype, optional) – Data type of the random arrays.

  • seed (int, optional) – Random seed.

Return type:

TensorNetwork3D

quimb.tensor.TN_classical_partition_function_from_edges(edges, beta, j=1.0, h=0.0, site_tag_id='I{}', bond_ind_id='b{},{}', outputs=(), ind_id='s{}')[source]

Build a regular tensor network representation of a classical ising model partition function by specifying graph edges. There will be a single tensor per site.

Parameters:
  • edges (sequence of tuple[hashable, hashable]) – The graph edges, as a sequence of pairs of hashable objects, for example integers, representing the nodes. You can redundantly specify (u, v) and (v, u) and only one edge will be added.

  • beta (float, optional) – The inverse temperature.

  • j (float, dict, or callable, optional) – The interaction strength, positive being ferromagnetic. If a dict should contain entries for each edge, keyed by the edge. If a callable should have the signature j(node_a, node_b) and return a float.

  • h (float, or callable, optional) – The magnetic field strength. If a callable should have the signature h(node) and return a float.

  • site_tag_id (str, optional) – A string formatter for naming tensor tags like site_ind_id.format(node).

  • bond_ind_id (str, optional) – A string formatter for naming the indices bewteen tensors like bond_ind_id.format(node_a, node_b).

Return type:

TensorNetwork

quimb.tensor.TN_dimer_covering_from_edges(edges, cover_count=1, site_tag_id='I{}', bond_ind_id='b{},{}', dtype=float)[source]

Make a tensor network from sequence of graph edges that counts the number of ways to cover the graph exactly with dimers. See https://arxiv.org/abs/1805.10598 for the construction.

Parameters:
  • edges (sequence of tuple) – The edges, each item should be a pair of hashable objects describing nodes linked.

  • cover_count (int, optional) – The exact number of times each node must be ‘covered’. For example 1 for a standard dimer covering or 2 for ‘ice rules’.

  • site_tag_id (str, optional) – A string formatter for naming tensor tags like site_ind_id.format(node).

  • bond_ind_id (str, optional) – A string formatter for naming the indices bewteen tensors like bond_ind_id.format(node_a, node_b).

Return type:

TensorNetwork

quimb.tensor.TN_from_edges_and_fill_fn(fill_fn, edges, D, phys_dim=None, site_tag_id='I{}', site_ind_id='k{}')[source]

Create a tensor network from a sequence of edges defining a graph, and a ‘fill’ function that maps shapes to data.

Parameters:
  • fill_fn (callable) – A function with signature fill_fn(shape) -> array, used to fill each tensor.

  • edges (sequence of tuple[hashable, hashable]) – The graph edges, as a sequence of pairs of hashable objects, for example integers, representing the nodes. You can redundantly specify (u, v) and (v, u) and only one edge will be added.

  • D (int) – The bond dimension connecting tensors.

  • phys_dim (int, optional) – If not None, give each tensor a ‘physical’, free index of this size at each node.

  • site_tag_id (str, optional) – String with formatter to tag sites.

  • site_ind_id (str or (str, str), optional) – String with formatter to tag indices (if phys_dim specified). If a single str is supplied, the tensor network will have a single index at each site, representing a vector. If a pair of strings is supplied, the tensor network will have two indices at each site, representing an operator with upper and lower indices.

Return type:

TensorNetworkGen, TensorNetworkGenVector or TensorNetworkGenOperator

quimb.tensor.TN_from_edges_empty(edges, D, phys_dim=None, site_tag_id='I{}', site_ind_id='k{}', dtype='float64')[source]

Create a tensor network from a sequence of edges defining a graph, initialized with empty tensors.

Parameters:
  • edges (sequence of tuple[hashable, hashable]) – The graph edges, as a sequence of pairs of hashable objects, for example integers, representing the nodes. You can redundantly specify (u, v) and (v, u) and only one edge will be added.

  • D (int) – The bond dimension connecting tensors.

  • phys_dim (int, optional) – If not None, give each tensor a ‘physical’, free index of this size at each node.

  • site_tag_id (str, optional) – String with formatter to tag sites.

  • site_ind_id (str, optional) – String with formatter to tag indices (if phys_dim specified).

  • dtype (str, optional) – The data type of the tensors.

Return type:

TensorNetworkGen, TensorNetworkGenVector or TensorNetworkGenOperator

quimb.tensor.TN_from_edges_rand(edges, D, phys_dim=None, seed=None, dtype='float64', site_tag_id='I{}', site_ind_id='k{}', **randn_opts)[source]

Create a random tensor network with geometry defined from a sequence of edges defining a graph.

Parameters:
  • G (sequence of tuple[node, node]) – The edges defining a graph, each element should be a pair of nodes described by hashable objects.

  • D (int) – The bond dimension connecting tensors.

  • phys_dim (int, optional) – If not None, give each tensor a ‘physical’, free index of this size to mimic a wavefunction of len(G) sites.

  • seed (int, optional) – A random seed.

  • dtype (str, optional) – The data type of the tensors.

  • site_tag_id (str, optional) – String with formatter to tag sites.

  • site_ind_id (str, optional) – String with formatter to tag indices (if phys_dim specified).

  • randn_opts – Supplied to randn().

Return type:

TensorNetworkGen, TensorNetworkGenVector or TensorNetworkGenOperator

quimb.tensor.TN_from_edges_with_value(value, edges, D, phys_dim=None, site_tag_id='I{}', site_ind_id='k{}', dtype=None)[source]

Create a tensor network from a sequence of edges defining a graph, initialized with a constant value. This uses numpy.broadcast_to and therefore essentially no memory.

Parameters:
  • value (scalar) – The value to fill the tensors with.

  • edges (sequence of tuple[hashable, hashable]) – The graph edges, as a sequence of pairs of hashable objects, for example integers, representing the nodes. You can redundantly specify (u, v) and (v, u) and only one edge will be added.

  • D (int) – The bond dimension connecting tensors.

  • phys_dim (int, optional) – If not None, give each tensor a ‘physical’, free index of this size at each node.

  • site_tag_id (str, optional) – String with formatter to tag sites.

  • site_ind_id (str, optional) – String with formatter to tag indices (if phys_dim specified).

  • dtype (str, optional) – The data type of the tensors.

Return type:

TensorNetworkGen, TensorNetworkGenVector or TensorNetworkGenOperator

quimb.tensor.TN_from_sites_computational_state(site_map, site_tag_id='I{}', site_ind_id='k{}', dtype='float64')[source]

A computational basis state in general tensor network form.

Parameters:
  • site_map (dict[hashable, str]) – Mapping of site to computational state, which should be one of ('0', '1', '+', '-').

  • site_tag_id (str, optional) – Format string for site tag labels.

  • site_ind_id (str, optional) – Format string for site index labels.

  • dtype ({'float64', 'complex128', 'float32', 'complex64'}, optional) – The data type to use for the array representation.

Return type:

TensorNetworkGenVector

quimb.tensor.TN_from_sites_product_state(site_map, site_tag_id='I{}', site_ind_id='k{}')[source]

A product state in general tensor network form.

Parameters:
  • site_map (dict[hashable, array_like]) – Mapping of site to local state.

  • site_tag_id (str, optional) – Format string for site tag labels.

  • site_ind_id (str, optional) – Format string for site index labels.

Return type:

TensorNetworkGenVector

quimb.tensor.TN_from_strings(strings, fill_fn=None, line_dim=2, allow_plaquettes=True, site_tag_id='I{}', random_rewire=False, random_rewire_seed=None, join=False, join_avoid_self_loops=True, normalize=False, contract_sites=True, fuse_multibonds=True, **contract_opts)[source]
quimb.tensor.TN_rand_from_edges[source]
quimb.tensor.TN_rand_reg(n, reg, D, phys_dim=None, seed=None, dtype='float64', site_tag_id='I{}', site_ind_id='k{}', **randn_opts)[source]

Create a random regular tensor network.

Parameters:
  • n (int) – The number of tensors.

  • reg (int) – The degree of the tensor network (how many tensors each tensor connects to).

  • D (int) – The bond dimension connecting tensors.

  • phys_dim (int, optional) – If not None, give each tensor a ‘physical’, free index of this size to mimic a wavefunction of n sites.

  • seed (int, optional) – A random seed.

  • site_tag_id (str, optional) – String with formatter to tag sites.

  • site_ind_id (str, optional) – String with formatter to tag indices (if phys_dim specified).

Return type:

TensorNetworkGen, TensorNetworkGenVector or TensorNetworkGenOperator

quimb.tensor.TN_rand_tree(n, D, phys_dim=None, seed=None, dtype='float64', site_tag_id='I{}', site_ind_id='k{}', **randn_opts)[source]

Create a random tree tensor network.

Parameters:
  • n (int) – The number of tensors.

  • D (int) – The bond dimension connecting tensors.

  • phys_dim (int, optional) – If not None, give each tensor a ‘physical’, free index of this size to mimic a wavefunction of n sites.

  • seed (int, optional) – A random seed.

  • site_tag_id (str, optional) – String with formatter to tag sites.

  • site_ind_id (str, optional) – String with formatter to tag indices (if phys_dim specified).

Return type:

TensorNetworkGen, TensorNetworkGenVector or TensorNetworkGenOperator

quimb.tensor.cnf_file_parse(fname)[source]

Parse a DIMACS style ‘cnf’ file into a list of clauses, and possibly a dictionary of weights. The weights, if present, can be specified either as:

  • (CACHET format): a line per weight like w {signed_var} {weight}, where signed_var is an integer whose sign specifies the sign of the weight being set.

  • (MC2021 competition format): the same as above, but with each line specified as c p weight {signed_var} {weight}.

  • (MINIC2D format): a single line of the form c weights {wp_1} {wm_1} {wp_2} {wm_2}... ``,   where ``wp_i and wn_i are the positive and negative weights for variable i. Weights specified this way are overriden by the previous two formats.

Parameters:

fname (str) – Path to a ‘.cnf’ or ‘.wcnf’ file.

Returns:

instance

Return type:

dict

quimb.tensor.convert_to_2d(tn, Lx=None, Ly=None, site_tag_id='I{},{}', x_tag_id='X{}', y_tag_id='Y{}', inplace=False)[source]

Convert tn to a TensorNetwork2D, assuming that is has a generic geometry with sites labelled by (i, j) coordinates already. Useful for constructing 2D tensor networks from functions that only require a list of edges etc.

quimb.tensor.convert_to_3d(tn, Lx=None, Ly=None, Lz=None, site_tag_id='I{},{},{}', x_tag_id='X{}', y_tag_id='Y{}', z_tag_id='Z{}', inplace=False)[source]

Convert tn to a TensorNetwork3D, assuming that is has a generic geometry with sites labelled by (i, j, k) coordinates already. Useful for constructing 3D tensor networks from functions that only require a list of edges etc.

quimb.tensor.ham_1d_heis(L=None, j=1.0, bz=0.0, *, S=1 / 2, cyclic=False, **local_ham_1d_opts)[source]

Heisenberg Hamiltonian in LocalHam1D form.

\[H_\mathrm{Heis} = \sum_{i} ( J_X S^X_i S^X_{i + 1} + J_Y S^Y_i S^Y_{i + 1} + J_Z S^Z_i S^Z_{i + 1} ) - B_Z \sum_{i} S^Z_i\]

Note the default convention of antiferromagnetic interactions and spin operators not Pauli matrices.

Parameters:
  • L (int) – The number of sites.

  • j (float or (float, float, float), optional) – The XX, YY and ZZ interaction strength. Positive is antiferromagnetic.

  • bz (float, optional) – The Z-magnetic field strength.

  • S ({1/2, 1, 3/2, ...}, optional) – The underlying spin of the system, defaults to 1/2.

  • cyclic (bool, optional) – Generate a hamiltonian with periodic boundary conditions or not, default is open boundary conditions.

  • local_ham_1d_opts – Supplied to LocalHam1D.

Return type:

LocalHam1D

quimb.tensor.ham_1d_ising(L=None, j=1.0, bx=0.0, *, S=1 / 2, cyclic=False, **local_ham_1d_opts)[source]

Ising Hamiltonian in LocalHam1D form.

\[H_\mathrm{Ising} = J \sum_{i} S^Z_i S^Z_{i + 1} - B_x \sum_{i} S^X_i\]

Note the default convention of antiferromagnetic interactions and spin operators not Pauli matrices.

Parameters:
  • L (int) – The number of sites.

  • j (float, optional) – The ZZ interaction strength. Positive is antiferromagnetic.

  • bx (float, optional) – The X-magnetic field strength.

  • S ({1/2, 1, 3/2, ...}, optional) – The underlying spin of the system, defaults to 1/2.

  • cyclic (bool, optional) – Generate a hamiltonian with periodic boundary conditions or not, default is open boundary conditions.

  • local_ham_1d_opts (mpo_opts or) – Supplied to LocalHam1D.

Return type:

LocalHam1D

quimb.tensor.ham_1d_mbl(L, dh, j=1.0, seed=None, S=1 / 2, *, cyclic=False, dh_dist='s', dh_dim=1, beta=None, **local_ham_1d_opts)[source]

The many-body-localized spin hamiltonian in LocalHam1D form.

\[H_\mathrm{MBL} = \sum_{i} ( J_X S^X_i S^X_{i + 1} + J_Y S^Y_i S^Y_{i + 1} + J_Z S^Z_i S^Z_{i + 1} ) - \sum_{i} h_i S^Z_i\]

Note the default convention of antiferromagnetic interactions and spin operators not Pauli matrices.

Parameters:
  • L (int) – Number of spins.

  • dh (float) – Random noise strength.

  • j (float, or (float, float, float), optional) – Interaction strength(s) e.g. 1 or (1., 1., 0.5). Positive is antiferromagnetic.

  • seed (int, optional) – Random number to seed the noise with.

  • S ({1/2, 1, 3/2, ...}, optional) – The underlying spin of the system, defaults to 1/2.

  • cyclic (bool, optional) – Whether to use periodic boundary conditions - default is False.

  • dh_dist ({'s', 'g', 'qp'}, optional) – Whether to use sqaure, guassian or quasiperiodic noise.

  • beta (float, optional) – Frequency of the quasirandom noise, only if dh_dist='qr'.

  • local_ham_1d_opts – Supplied to LocalHam1D.

Return type:

LocalHam1D

quimb.tensor.ham_1d_XY(L=None, j=1.0, bz=0.0, *, S=1 / 2, cyclic=False, **local_ham_1d_opts)[source]

XY-Hamiltonian in LocalHam1D form.

\[H_\mathrm{XY} = \sum_{i} ( J_X S^X_i S^X_{i + 1} + J_Y S^Y_i S^Y_{i + 1} ) - B_Z \sum_{i} S^Z_i\]

Note the default convention of antiferromagnetic interactions and spin operators not Pauli matrices.

Parameters:
  • L (int) – The number of sites.

  • j (float or (float, float), optional) – The XX and YY interaction strength. Positive is antiferromagnetic.

  • bz (float, optional) – The Z-magnetic field strength.

  • S ({1/2, 1, 3/2, ...}, optional) – The underlying spin of the system, defaults to 1/2.

  • cyclic (bool, optional) – Generate a hamiltonian with periodic boundary conditions or not, default is open boundary conditions.

  • local_ham_1d_opts – Supplied to LocalHam1D.

Return type:

LocalHam1D

quimb.tensor.ham_2d_heis(Lx, Ly, j=1.0, bz=0.0, **local_ham_2d_opts)[source]

Heisenberg Hamiltonian in LocalHam2D. form.

\[H_\mathrm{Heis} = \sum_{<ij>} ( J_X S^X_i S^X_{j} + J_Y S^Y_i S^Y_{j} + J_Z S^Z_i S^Z_{j} ) - B_Z \sum_{i} S^Z_{i}\]

for nearest neighbors \(<ij>\). Note the default convention of antiferromagnetic interactions and spin operators not Pauli matrices.

Parameters:
  • Lx (int) – The number of rows.

  • Ly (int) – The number of columns.

  • j (float or (float, float, float), optional) – The XX, YY and ZZ interaction strength. Positive is antiferromagnetic.

  • bz (float, optional) – The Z-magnetic field strength.

  • local_ham_2d_opts – Supplied to LocalHam2D.

Return type:

LocalHam2D

quimb.tensor.ham_2d_ising(Lx, Ly, j=1.0, bx=0.0, **local_ham_2d_opts)[source]

Ising Hamiltonian in LocalHam2D form.

\[H_\mathrm{Ising} = J \sum_{<ij>} S^Z_i S^Z_{j} - B_x \sum_{i} S^X_i\]

for nearest neighbors \(<ij>\). Note the default convention of antiferromagnetic interactions and spin operators not Pauli matrices.

Parameters:
  • Lx (int) – The number of rows.

  • Ly (int) – The number of columns.

  • j (float, optional) – The ZZ interaction strength. Positive is antiferromagnetic.

  • bx (float, optional) – The X-magnetic field strength.

  • local_ham_2d_opts – Supplied to LocalHam2D.

Return type:

LocalHam2D

quimb.tensor.ham_2d_j1j2(Lx, Ly, j1=1.0, j2=0.5, bz=0.0, **local_ham_2d_opts)[source]

Heisenberg Hamiltonian in LocalHam2D. form.

\[H_\mathrm{Heis} = \sum_{<ij>} ( J_{1,X} S^X_i S^X_{j} + J_{1,Y} S^Y_i S^Y_{j} + J_{1,Z} S^Z_i S^Z_{j} ) + \sum_{<<ij>>} ( J_{2,X} S^X_i S^X_{j} + J_{2,Y} S^Y_i S^Y_{j} + J_{2,Z} S^Z_i S^Z_{j} ) - B_Z \sum_{i} S^Z_{i}\]

for nearest neighbors \(<ij>\) and diagonal next nearest neighbors \(<<ij>>\). Note the default convention of antiferromagnetic interactions and spin operators not Pauli matrices.

Parameters:
  • Lx (int) – The number of rows.

  • Ly (int) – The number of columns.

  • j2 (float or (float, float, float), optional) – The nearest neighbor XX, YY and ZZ interaction strength. Positive is antiferromagnetic.

  • j2 – The diagonal next nearest nearest XX, YY and ZZ interaction strength. Positive is antiferromagnetic.

  • bz (float, optional) – The Z-magnetic field strength.

  • local_ham_2d_opts – Supplied to LocalHam2D.

Return type:

LocalHam2D

quimb.tensor.ham_3d_heis(Lx, Ly, Lz, j=1.0, bz=0.0, **local_ham_3d_opts)[source]

Heisenberg Hamiltonian in LocalHam3D. form.

\[H_\mathrm{Heis} = \sum_{<ij>} ( J_X S^X_i S^X_{j} + J_Y S^Y_i S^Y_{j} + J_Z S^Z_i S^Z_{j} ) - B_Z \sum_{i} S^Z_{i}\]

for nearest neighbors \(<ij>\). Note the default convention of antiferromagnetic interactions and spin operators not Pauli matrices.

Parameters:
  • Lx (int) – The number of x-planes.

  • Ly (int) – The number of y-planes.

  • Ly – The number of z-planes.

  • j (float or (float, float, float), optional) – The XX, YY and ZZ interaction strength. Positive is antiferromagnetic.

  • bz (float, optional) – The Z-magnetic field strength.

  • local_ham_3d_opts – Supplied to LocalHam3D.

Return type:

LocalHam3D

quimb.tensor.rand_phased(shape, inds, tags=None, dtype=complex)[source]

Generate a random tensor with specified shape and inds, and randomly ‘phased’ (distributed on the unit circle) data, such that T.H @ T == T.norm()**2 == T.size.

Parameters:
  • shape (sequence of int) – Size of each dimension.

  • inds (sequence of str) – Names of each dimension.

  • tags (sequence of str) – Labels to tag this tensor with.

  • dtype ({'complex128', 'complex64'}, optional) – The underlying data type - can only be complex.

Return type:

Tensor

quimb.tensor.rand_tensor(shape, inds, tags=None, dtype='float64', dist='normal', scale=1.0, loc=0.0, left_inds=None, **randn_opts)[source]

Generate a random tensor with specified shape and inds.

Parameters:
  • shape (sequence of int) – Size of each dimension.

  • inds (sequence of str) – Names of each dimension.

  • tags (sequence of str) – Labels to tag this tensor with.

  • dtype ({'float64', 'complex128', 'float32', 'complex64'}, optional) – The underlying data type.

  • dist ({'normal', 'uniform', 'rademacher', 'exp'}, optional) – Type of random number to generate, defaults to ‘normal’.

  • scale (float, optional) – A multiplicative factor to scale the random numbers by.

  • loc (float, optional) – An additive offset to add to the random numbers.

  • 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.

Return type:

Tensor

quimb.tensor.random_ksat_instance(k, num_variables, num_clauses=None, alpha=None, seed=None, allow_repeat_variables=False)[source]

Create a random k-SAT instance.

Parameters:
  • k (int) – Number of variables per clause.

  • num_variables (int) – Number of variables in the instance.

  • num_clauses (int, optional) – Number of clauses in the instance. If not specified, will be determined from alpha.

  • alpha (float, optional) – If num_clauses is not directly specified then the average number of clauses per variable. Taken as a Poisson parameter. Either this or num_clauses must be specified.

  • seed (int, optional) – Random seed.

  • allow_repeat_variables (bool, optional) – Whether to allow the same variable to appear multiple times in a single clause.

Returns:

instance – Dictionary with keys ‘num_variables’, ‘num_clauses’, ‘clauses’. The ‘clauses’ key contains a list of tuples, each tuple representing a clause. Within each tuple, each element is an integer representing a variable, with the sign of the integer representing the sign of the variable in the clause.

Return type:

dict

quimb.tensor.COPY_tensor(d, inds, tags=None, dtype=float)[source]

Get the tensor representing the COPY operation with dimension size d and number of dimensions len(inds), with exterior indices inds.

Parameters:
  • d (int) – The size of each dimension.

  • inds (sequence of str) – The exterior index names for each dimension.

  • tags (None or sequence of str, optional) – Tag the tensor with these.

  • dtype (str, optional) – Data type to create the underlying numpy array with.

Returns:

The tensor describing the MPS, of size d**len(inds).

Return type:

Tensor

class quimb.tensor.IsoTensor(data=1.0, inds=(), tags=None, left_inds=None)[source]

Bases: Tensor

A Tensor subclass which keeps its left_inds by default even when its data is changed.

__slots__ = ('_data', '_inds', '_tags', '_left_inds', '_owners')
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’.

fuse(*args, inplace=False, **kwargs)[source]

Combine groups of indices into single indices.

Parameters:

fuse_map (dict_like or sequence of tuples.) – Mapping like: {new_ind: sequence of existing inds, ...} or an ordered mapping like [(new_ind_1, old_inds_1), ...] in which case the output tensor’s fused inds will be ordered. In both cases the new indices are created at the minimum axis of any of the indices that will be fused.

Returns:

The transposed, reshaped and re-labeled tensor.

Return type:

Tensor

class quimb.tensor.PTensor(fn, params, inds=(), tags=None, left_inds=None)[source]

Bases: Tensor

A tensor whose data array is lazily generated from a set of parameters and a function.

Parameters:
  • fn (callable) – The function that generates the tensor data from params.

  • params (sequence of numbers) – The initial parameters supplied to the generating function like fn(params).

  • inds (optional) – Should match the shape of fn(params), see Tensor.

  • tags (optional) – See Tensor.

  • left_inds (optional) – See Tensor.

See also

PTensor

property data
property fn
property params
property shape

The size of each dimension.

property backend

The backend inferred from the data.

__slots__ = ('_data', '_inds', '_tags', '_left_inds', '_owners')
conj_[source]
classmethod from_parray(parray, inds=(), tags=None, left_inds=None)[source]
copy()[source]

Copy this parametrized tensor.

_set_data(x)[source]
get_params()[source]

Get the parameters of this PTensor.

set_params(params)[source]

Set the parameters of this PTensor.

_apply_function(fn)[source]

Apply fn to the data array of this PTensor (lazily), by composing it with the current parametrized array function.

conj(inplace=False)[source]

Conjugate this parametrized tensor - done lazily whenever the .data attribute is accessed.

unparametrize()[source]

Turn this PTensor into a normal Tensor.

__getstate__()[source]

Helper for pickle.

__setstate__(state)[source]
class quimb.tensor.Tensor(data=1.0, inds=(), tags=None, left_inds=None)[source]

A labelled, tagged n-dimensional array. The index labels are used instead of axis numbers to identify dimensions, and are preserved through operations. The tags are used to identify the tensor within networks, and are combined when tensors are contracted together.

Parameters:
  • data (numpy.ndarray) – The n-dimensional data.

  • inds (sequence of str) – The index labels for each dimension. Must match the number of dimensions of data.

  • tags (sequence of str, optional) – Tags with which to identify and group this tensor. These will be converted into a oset.

  • left_inds (sequence of str, optional) – Which, if any, indices to group as ‘left’ indices of an effective matrix. This can be useful, for example, when automatically applying unitary constraints to impose a certain flow on a tensor network but at the atomistic (Tensor) level.

Examples

Basic construction:

>>> from quimb import randn
>>> from quimb.tensor import Tensor
>>> X = Tensor(randn((2, 3, 4)), inds=['a', 'b', 'c'], tags={'X'})
>>> Y = Tensor(randn((3, 4, 5)), inds=['b', 'c', 'd'], tags={'Y'})

Indices are automatically aligned, and tags combined, when contracting:

>>> X @ Y
Tensor(shape=(2, 5), inds=('a', 'd'), tags={'Y', 'X'})
property data
property inds
property tags
property left_inds
property owners
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.

__slots__ = ('_data', '_inds', '_tags', '_left_inds', '_owners')
__copy__[source]
isel_[source]
new_bond[source]
new_ind_pair_with_identity_[source]
conj_[source]
astype_[source]
transpose_[source]
transpose_like_[source]
moveindex_[source]
sum_reduce_[source]
vector_reduce_[source]
collapse_repeated_[source]
direct_product_[source]
distance_normalized[source]
gate_[source]
retag_[source]
reindex_[source]
fuse_[source]
unfuse_[source]
to_qarray[source]
squeeze_[source]
normalize_[source]
symmetrize_[source]
isometrize_[source]
unitize[source]
unitize_
randomize_[source]
flip_[source]
multiply_index_diagonal_[source]
negate_[source]
graph[source]
visualize[source]
_set_data(data)[source]
_set_inds(inds)[source]
_set_tags(tags)[source]
_set_left_inds(left_inds)[source]
get_params()[source]

A simple function that returns the ‘parameters’ of the underlying data array. This is mainly for providing an interface for ‘structured’ arrays e.g. with block sparsity to interact with optimization.

set_params(params)[source]

A simple function that sets the ‘parameters’ of the underlying data array. This is mainly for providing an interface for ‘structured’ arrays e.g. with block sparsity to interact with optimization.

copy(deep=False, virtual=False)[source]

Copy this tensor.

Note

By default (deep=False), the underlying array will not be copied.

Parameters:
  • deep (bool, optional) – Whether to copy the underlying data as well.

  • virtual (bool, optional) – To conveniently mimic the behaviour of taking a virtual copy of tensor network, this simply returns self.

check()[source]

Do some basic diagnostics on this tensor, raising errors if something is wrong.

add_owner(tn, tid)[source]

Add tn as owner of this Tensor - it’s tag and ind maps will be updated whenever this tensor is retagged or reindexed.

remove_owner(tn)[source]

Remove TensorNetwork tn as an owner of this Tensor.

check_owners()[source]

Check if this tensor is ‘owned’ by any alive TensorNetworks. Also trim any weakrefs to dead TensorNetworks.

_apply_function(fn)[source]
modify(**kwargs)[source]

Overwrite the data of this tensor in place.

Parameters:
  • data (array, optional) – New data.

  • apply (callable, optional) – A function to apply to the current data. If data is also given this is applied subsequently.

  • inds (sequence of str, optional) – New tuple of indices.

  • tags (sequence of str, optional) – New tags.

  • left_inds (sequence of str, optional) – New grouping of indices to be ‘on the left’.

apply_to_arrays(fn)[source]

Apply the function fn to the underlying data array(s). This is meant for changing how the raw arrays are backed (e.g. converting between dtypes or libraries) but not their ‘numerical meaning’.

isel(selectors, inplace=False)[source]

Select specific values for some dimensions/indices of this tensor, thereby removing them. Analogous to X[:, :, 3, :, :] with arrays. The indices to select from can be specified either by integer, in which case the correspoding index is removed, or by a slice.

Parameters:
  • selectors (dict[str, int], dict[str, slice]) – Mapping of index(es) to which value to take.

  • inplace (bool, optional) – Whether to select inplace or not.

Return type:

Tensor

Examples

>>> T = rand_tensor((2, 3, 4), inds=('a', 'b', 'c'))
>>> T.isel({'b': -1})
Tensor(shape=(2, 4), inds=('a', 'c'), tags=())
add_tag(tag)[source]

Add a tag or multiple tags to this tensor. Unlike self.tags.add this also updates any TensorNetwork objects viewing this Tensor.

expand_ind(ind, size, mode=None, rand_strength=None, rand_dist='normal')[source]

Inplace increase the size of the dimension of ind, the new array entries will be filled with zeros by default.

Parameters:
  • name (str) – Name of the index to expand.

  • size (int, optional) – Size of the expanded index.

  • mode ({None, 'zeros', 'repeat', 'random'}, optional) – How to fill any new array entries. If 'zeros' then fill with zeros, if 'repeat' then repeatedly tile the existing entries. If 'random' then fill with random entries drawn from rand_dist, multiplied by rand_strength. If None then select from zeros or random depening on non-zero rand_strength.

  • rand_strength (float, optional) – If mode='random', a multiplicative scale for the random entries, defaulting to 1.0. If mode is None then supplying a non-zero value here triggers mode='random'.

  • rand_dist ({'normal', 'uniform', 'exp'}, optional) – If mode='random', the distribution to draw the random entries from.

new_ind(name, size=1, axis=0, mode=None, rand_strength=None, rand_dist='normal')[source]

Inplace add a new index - a named dimension. If size is specified to be greater than one then the new array entries will be filled with zeros.

Parameters:
  • name (str) – Name of the new index.

  • size (int, optional) – Size of the new index.

  • axis (int, optional) – Position of the new index.

  • mode ({None, 'zeros', 'repeat', 'random'}, optional) – How to fill any new array entries. If 'zeros' then fill with zeros, if 'repeat' then repeatedly tile the existing entries. If 'random' then fill with random entries drawn from rand_dist, multiplied by rand_strength. If None then select from zeros or random depening on non-zero rand_strength.

  • rand_strength (float, optional) – If mode='random', a multiplicative scale for the random entries, defaulting to 1.0. If mode is None then supplying a non-zero value here triggers mode='random'.

  • rand_dist ({'normal', 'uniform', 'exp'}, optional) – If mode='random', the distribution to draw the random entries from.

new_ind_with_identity(name, left_inds, right_inds, axis=0)[source]

Inplace add a new index, where the newly stacked array entries form the identity from left_inds to right_inds. Selecting 0 or 1 for the new index name thus is like ‘turning off’ this tensor if viewed as an operator.

Parameters:
  • name (str) – Name of the new index.

  • left_inds (tuple[str]) – Names of the indices forming the left hand side of the operator.

  • right_inds (tuple[str]) – Names of the indices forming the right hand side of the operator. The dimensions of these must match those of left_inds.

  • axis (int, optional) – Position of the new index.

new_ind_pair_with_identity(new_left_ind, new_right_ind, d, inplace=False)[source]

Expand this tensor with two new indices of size d, by taking an (outer) tensor product with the identity operator. The two new indices are added as axes at the start of the tensor.

Parameters:
  • new_left_ind (str) – Name of the new left index.

  • new_right_ind (str) – Name of the new right index.

  • d (int) – Size of the new indices.

  • inplace (bool, optional) – Whether to perform the expansion inplace.

Return type:

Tensor

conj(inplace=False)[source]

Conjugate this tensors data (does nothing to indices).

iscomplex()[source]
astype(dtype, inplace=False)[source]

Change the type of this tensor to dtype.

max_dim()[source]

Return the maximum size of any dimension, or 1 if scalar.

ind_size(ind)[source]

Return the size of dimension corresponding to ind.

inds_size(inds)[source]

Return the total size of dimensions corresponding to inds.

shared_bond_size(other)[source]

Get the total size of the shared index(es) with other.

inner_inds()[source]

Get all indices that appear on two or more tensors.

transpose(*output_inds, inplace=False)[source]

Transpose this tensor - permuting the order of both the data and the indices. This operation is mainly for ensuring a certain data layout since for most operations the specific order of indices doesn’t matter.

Note to compute the tranditional ‘transpose’ of an operator within a contraction for example, you would just use reindexing not this.

Parameters:
  • output_inds (sequence of str) – The desired output sequence of indices.

  • inplace (bool, optional) – Perform the tranposition inplace.

Returns:

tt – The transposed tensor.

Return type:

Tensor

transpose_like(other, inplace=False)[source]

Transpose this tensor to match the indices of other, allowing for one index to be different. E.g. if self.inds = ('a', 'b', 'c', 'x') and other.inds = ('b', 'a', 'd', 'c') then ‘x’ will be aligned with ‘d’ and the output inds will be ('b', 'a', 'x', 'c')

Parameters:
  • other (Tensor) – The tensor to match.

  • inplace (bool, optional) – Perform the tranposition inplace.

Returns:

tt – The transposed tensor.

Return type:

Tensor

See also

transpose

moveindex(ind, axis, inplace=False)[source]

Move the index ind to position axis. Like transpose, this permutes the order of both the data and the indices and is mainly for ensuring a certain data layout since for most operations the specific order of indices doesn’t matter.

Parameters:
  • ind (str) – The index to move.

  • axis (int) – The new position to move ind to. Can be negative.

  • inplace (bool, optional) – Whether to perform the move inplace or not.

Return type:

Tensor

item()[source]

Return the scalar value of this tensor, if it has a single element.

trace(left_inds, right_inds, preserve_tensor=False, inplace=False)[source]

Trace index or indices left_inds with right_inds, removing them.

Parameters:
  • left_inds (str or sequence of str) – The left indices to trace, order matching right_inds.

  • right_inds (str or sequence of str) – The right indices to trace, order matching left_inds.

  • preserve_tensor (bool, optional) – If True, a tensor will be returned even if no indices remain.

  • inplace (bool, optional) – Perform the trace inplace.

Returns:

z

Return type:

Tensor or scalar

sum_reduce(ind, inplace=False)[source]

Sum over index ind, removing it from this tensor.

Parameters:
  • ind (str) – The index to sum over.

  • inplace (bool, optional) – Whether to perform the reduction inplace.

Return type:

Tensor

vector_reduce(ind, v, inplace=False)[source]

Contract the vector v with the index ind of this tensor, removing it.

Parameters:
  • ind (str) – The index to contract.

  • v (array_like) – The vector to contract with.

  • inplace (bool, optional) – Whether to perform the reduction inplace.

Return type:

Tensor

collapse_repeated(inplace=False)[source]

Take the diagonals of any repeated indices, such that each index only appears once.

contract(*others, output_inds=None, **opts)[source]
direct_product(other, sum_inds=(), inplace=False)[source]
split(*args, **kwargs)[source]
compute_reduced_factor(side, left_inds, right_inds, **split_opts)[source]
distance(other, **contract_opts)[source]
gate(G, ind, preserve_inds=True, inplace=False)[source]

Gate this tensor - contract a matrix into one of its indices without changing its indices. Unlike contract, G is a raw array and the tensor remains with the same set of indices.

Parameters:
  • G (2D array_like) – The matrix to gate the tensor index with.

  • ind (str) – Which index to apply the gate to.

Return type:

Tensor

Examples

Create a random tensor of 4 qubits:

>>> t = qtn.rand_tensor(
...    shape=[2, 2, 2, 2],
...    inds=['k0', 'k1', 'k2', 'k3'],
... )

Create another tensor with an X gate applied to qubit 2:

>>> Gt = t.gate(qu.pauli('X'), 'k2')

The contraction of these two tensors is now the expectation of that operator:

>>> t.H @ Gt
-4.108910576149794
singular_values(left_inds, method='svd')[source]

Return the singular values associated with splitting this tensor according to left_inds.

Parameters:
  • left_inds (sequence of str) – A subset of this tensors indices that defines ‘left’.

  • method ({'svd', 'eig'}) – Whether to use the SVD or eigenvalue decomposition to get the singular values.

Returns:

The singular values.

Return type:

1d-array

entropy(left_inds, method='svd')[source]

Return the entropy associated with splitting this tensor according to left_inds.

Parameters:
  • left_inds (sequence of str) – A subset of this tensors indices that defines ‘left’.

  • method ({'svd', 'eig'}) – Whether to use the SVD or eigenvalue decomposition to get the singular values.

Return type:

float

retag(retag_map, inplace=False)[source]

Rename the tags of this tensor, optionally, in-place.

Parameters:
  • retag_map (dict-like) – Mapping of pairs {old_tag: new_tag, ...}.

  • inplace (bool, optional) – If False (the default), a copy of this tensor with the changed tags will be returned.

reindex(index_map, inplace=False)[source]

Rename the indices of this tensor, optionally in-place.

Parameters:
  • index_map (dict-like) – Mapping of pairs {old_ind: new_ind, ...}.

  • inplace (bool, optional) – If False (the default), a copy of this tensor with the changed inds will be returned.

fuse(fuse_map, inplace=False)[source]

Combine groups of indices into single indices.

Parameters:

fuse_map (dict_like or sequence of tuples.) – Mapping like: {new_ind: sequence of existing inds, ...} or an ordered mapping like [(new_ind_1, old_inds_1), ...] in which case the output tensor’s fused inds will be ordered. In both cases the new indices are created at the minimum axis of any of the indices that will be fused.

Returns:

The transposed, reshaped and re-labeled tensor.

Return type:

Tensor

unfuse(unfuse_map, shape_map, inplace=False)[source]

Reshape single indices into groups of multiple indices

Parameters:
  • unfuse_map (dict_like or sequence of tuples.) – Mapping like: {existing_ind: sequence of new inds, ...} or an ordered mapping like [(old_ind_1, new_inds_1), ...] in which case the output tensor’s new inds will be ordered. In both cases the new indices are created at the old index’s position of the tensor’s shape

  • shape_map (dict_like or sequence of tuples) – Mapping like: {old_ind: new_ind_sizes, ...} or an ordered mapping like [(old_ind_1, new_ind_sizes_1), ...].

Returns:

The transposed, reshaped and re-labeled tensor

Return type:

Tensor

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:

Tensor

largest_element()[source]

Return the largest element, in terms of absolute magnitude, of this tensor.

idxmin(f=None)[source]

Get the index configuration of the minimum element of this tensor, optionally applying f first.

Parameters:

f (callable or str, optional) – If a callable, apply this function to the tensor data before finding the minimum element. If a string, apply autoray.do(f, data).

Returns:

Mapping of index names to their values at the minimum element.

Return type:

dict[str, int]

idxmax(f=None)[source]

Get the index configuration of the maximum element of this tensor, optionally applying f first.

Parameters:

f (callable or str, optional) – If a callable, apply this function to the tensor data before finding the maximum element. If a string, apply autoray.do(f, data).

Returns:

Mapping of index names to their values at the maximum element.

Return type:

dict[str, int]

norm()[source]

Frobenius norm of this tensor:

\[\|t\|_F = \sqrt{\mathrm{Tr} \left(t^{\dagger} t\right)}\]

where the trace is taken over all indices. Equivalent to the square root of the sum of squared singular values across any partition.

normalize(inplace=False)[source]
symmetrize(ind1, ind2, inplace=False)[source]

Hermitian symmetrize this tensor for indices ind1 and ind2. I.e. T = (T + T.conj().T) / 2, where the transpose is taken only over the specified indices.

isometrize(left_inds=None, method='qr', inplace=False)[source]

Make this tensor unitary (or isometric) with respect to left_inds. The underlying method is set by method.

Parameters:
  • left_inds (sequence of str) – The indices to group together and treat as the left hand side of a matrix.

  • method (str, optional) –

    The method used to generate the isometry. The options are:

    • ”qr”: use the Q factor of the QR decomposition of x with the constraint that the diagonal of R is positive.

    • ”svd”: uses U @ VH of the SVD decomposition of x. This is useful for finding the ‘closest’ isometric matrix to x, such as when it has been expanded with noise etc. But is less stable for differentiation / optimization.

    • ”exp”: use the matrix exponential of x - dag(x), first completing x with zeros if it is rectangular. This is a good parametrization for optimization, but more expensive for non-square x.

    • ”cayley”: use the Cayley transform of x - dag(x), first completing x with zeros if it is rectangular. This is a good parametrization for optimization (one the few compatible with HIPS/autograd e.g.), but more expensive for non-square x.

    • ”householder”: use the Householder reflection method directly. This requires that the backend implements “linalg.householder_product”.

    • ”torch_householder”: use the Householder reflection method directly, using the torch_householder package. This requires that the package is installed and that the backend is "torch". This is generally the best parametrizing method for “torch” if available.

    • ”mgs”: use a python implementation of the modified Gram Schmidt method directly. This is slow if not compiled but a useful reference.

    Not all backends support all methods or differentiating through all methods.

  • inplace (bool, optional) – Whether to perform the unitization inplace.

Return type:

Tensor

randomize(dtype=None, inplace=False, **randn_opts)[source]

Randomize the entries of this tensor.

Parameters:
  • dtype ({None, str}, optional) – The data type of the random entries. If left as the default None, then the data type of the current array will be used.

  • inplace (bool, optional) – Whether to perform the randomization inplace, by default False.

  • randn_opts – Supplied to randn().

Return type:

Tensor

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 index ind.

almost_equals(other, **kwargs)[source]

Check if this tensor is almost the same as another.

drop_tags(tags=None)[source]

Drop certain tags, defaulting to all, from this tensor.

bonds(other)[source]

Return a tuple of the shared indices between this tensor and other.

filter_bonds(other)[source]

Sort this tensor’s indices into a list of those that it shares and doesn’t share with another tensor.

Parameters:

other (Tensor) – The other tensor.

Returns:

shared, unshared – The shared and unshared indices.

Return type:

(tuple[str], tuple[str])

__imul__(other)[source]
__itruediv__(other)[source]
__and__(other)[source]

Combine with another Tensor or TensorNetwork into a new TensorNetwork.

__or__(other)[source]

Combine virtually (no copies made) with another Tensor or TensorNetwork into a new TensorNetwork.

__matmul__(other)[source]

Explicitly contract with another tensor. Avoids some slight overhead of calling the full tensor_contract().

negate(inplace=False)[source]

Negate this tensor.

__neg__()[source]

Negate this tensor.

as_network(virtual=True)[source]

Return a TensorNetwork with only this tensor.

draw(*args, **kwargs)[source]

Plot a graph of this tensor and its indices.

__getstate__()[source]

Helper for pickle.

__setstate__(state)[source]
_repr_info()[source]

General info to show in various reprs. Sublasses can add more relevant info to this dict.

_repr_info_extra()[source]

General detailed info to show in various reprs. Sublasses can add more relevant info to this dict.

_repr_info_str(normal=True, extra=False)[source]

Render the general info as a string.

_repr_html_()[source]

Render this Tensor as HTML, for Jupyter notebooks.

__str__()[source]

Return str(self).

__repr__()[source]

Return repr(self).

class quimb.tensor.TensorNetwork(ts=(), *, virtual=False, check_collisions=True)[source]

Bases: object

A collection of (as yet uncontracted) Tensors.

Parameters:
  • ts (sequence of Tensor or TensorNetwork) – The objects to combine. The new network will copy these (but not the underlying data) by default. For a view set virtual=True.

  • virtual (bool, optional) – Whether the TensorNetwork should be a view onto the tensors it is given, or a copy of them. E.g. if a virtual TN is constructed, any changes to a Tensor’s indices or tags will propagate to all TNs viewing that Tensor.

  • check_collisions (bool, optional) – If True, the default, then TensorNetwork instances with double indices which match another TensorNetwork instances double indices will have those indices’ names mangled. Can be explicitly turned off when it is known that no collisions will take place – i.e. when not adding any new tensors.

tensor_map

Mapping of unique ids to tensors, like``{tensor_id: tensor, …}``. I.e. this is where the tensors are ‘stored’ by the network.

Type:

dict

tag_map

Mapping of tags to a set of tensor ids which have those tags. I.e. {tag: {tensor_id_1, tensor_id_2, ...}}. Thus to select those tensors could do: map(tensor_map.__getitem__, tag_map[tag]).

Type:

dict

ind_map

Like tag_map but for indices. So ind_map[ind]] returns the tensor ids of those tensors with ind.

Type:

dict

exponent

A scalar prefactor for the tensor network, stored in base 10 like 10**exponent. This is mostly for conditioning purposes and will be 0.0 unless you use use equalize_norms(value) or tn.strip_exponent(tid_or_tensor).

Type:

float

property num_tensors

The total number of tensors in the tensor network.

property num_indices

The total number of indices in the tensor network.

property H

Conjugate all the tensors in this network (leaves all indices).

property tensors

Get the tuple of tensors in this tensor network.

property arrays

Get the tuple of raw arrays containing all the tensor network data.

property tags
property shape

Actual, i.e. exterior, shape of this TensorNetwork.

property dtype

The dtype of this TensorNetwork, this is the minimal common type of all the tensors data.

_EXTRA_PROPS = ()
_CONTRACT_STRUCTURED = False
view_as_[source]
view_like_[source]
__copy__[source]
_pop_tensor[source]
retag_[source]
reindex_[source]
conj_[source]
multiply_[source]
multiply_each_[source]
negate_[source]
select_any[source]
select_all[source]
replace_with_svd_[source]
gate_inds[source]
gate_inds_[source]
gate_inds_with_tn_[source]
compress_all_[source]
compress_all_tree_[source]
compress_all_1d_[source]
compress_all_simple_[source]
graph_tree_span[source]
canonize_around_[source]
gauge_all_canonize_[source]
gauge_all_simple_[source]
gauge_all_random_[source]
gauge_all_[source]
gauge_local_[source]
contract_around_[source]
contract_compressed_[source]
drape_bond_between_[source]
isel_[source]
sum_reduce_[source]
vector_reduce_[source]
insert_operator_[source]
contract_tags_[source]
contract_[source]
to_qarray[source]
insert_compressor_between_regions_[source]
distance_normalized[source]
fit_[source]
squeeze_[source]
isometrize_[source]
unitize[source]
unitize_
randomize_[source]
equalize_norms_[source]
balance_bonds_[source]
fuse_multibonds_[source]
expand_bond_dimension_[source]
flip_[source]
rank_simplify_[source]
diagonal_reduce_[source]
antidiag_gauge_[source]
column_reduce_[source]
split_simplify_[source]
pair_simplify_[source]
loop_simplify_[source]
full_simplify_[source]
hyperinds_resolve_[source]
compress_simplify_[source]
astype_[source]
draw[source]
draw_3d[source]
draw_interactive[source]
draw_3d_interactive[source]
graph[source]
visualize_tensors[source]
combine(other, *, virtual=False, check_collisions=True)[source]

Combine this tensor network with another, returning a new tensor network.

Parameters:
  • other (TensorNetwork) – The other tensor network to combine with.

  • virtual (bool, optional) – Whether the new tensor network should copy all the incoming tensors (False, the default), or view them as virtual (True).

  • check_collisions (bool, optional) – Whether to check for index collisions between the two tensor networks before combining them. If True (the default), any inner indices that clash will be mangled.

Return type:

TensorNetwork

__and__(other)[source]

Combine this tensor network with more tensors, without contracting. Copies the tensors.

__or__(other)[source]

Combine this tensor network with more tensors, without contracting. Views the constituent tensors.

_update_properties(cls, like=None, current=None, **kwargs)[source]
classmethod new(like=None, **kwargs)[source]

Create a new tensor network, without any tensors, of type cls, with all the requisite properties specified by kwargs or inherited from like.

classmethod from_TN(tn, like=None, inplace=False, **kwargs)[source]

Construct a specific tensor network subclass (i.e. one with some promise about structure/geometry and tags/inds such as an MPS) from a generic tensor network which should have that structure already.

Parameters:
  • cls (class) – The TensorNetwork subclass to convert tn to.

  • tn (TensorNetwork) – The TensorNetwork to convert.

  • like (TensorNetwork, optional) – If specified, try and retrieve the neccesary attribute values from this tensor network.

  • inplace (bool, optional) – Whether to perform the conversion inplace or not.

  • kwargs – Extra properties of the TN subclass that should be specified.

view_as(cls, inplace=False, **kwargs)[source]

View this tensor network as subclass cls.

view_like(like, inplace=False, **kwargs)[source]

View this tensor network as the same subclass cls as like inheriting its extra properties as well.

copy(virtual=False, deep=False)[source]

Copy this TensorNetwork. If deep=False, (the default), then everything but the actual numeric data will be copied.

get_params()[source]

Get a pytree of the ‘parameters’, i.e. all underlying data arrays.

set_params(params)[source]

Take a pytree of the ‘parameters’, i.e. all underlying data arrays, as returned by get_params and set them.

Link tid to each of tags.

“Unlink tid from each of tags.

Link tid to each of inds.

“Unlink tid from each of inds.

_reset_inner_outer(inds)[source]
_next_tid()[source]
add_tensor(tensor, tid=None, virtual=False)[source]

Add a single tensor to this network - mangle its tid if neccessary.

add_tensor_network(tn, virtual=False, check_collisions=True)[source]
add(t, virtual=False, check_collisions=True)[source]

Add Tensor, TensorNetwork or sequence thereof to self.

make_tids_consecutive(tid0=0)[source]

Reset the tids - node identifies - to be consecutive integers.

__iand__(tensor)[source]

Inplace, but non-virtual, addition of a Tensor or TensorNetwork to this network. It should not have any conflicting indices.

__ior__(tensor)[source]

Inplace, virtual, addition of a Tensor or TensorNetwork to this network. It should not have any conflicting indices.

_modify_tensor_tags(old, new, tid)[source]
_modify_tensor_inds(old, new, tid)[source]
pop_tensor(tid)[source]

Remove tensor with tid from this network, and return it.

remove_all_tensors()[source]

Remove all tensors from this network.

delete(tags, which='all')[source]

Delete any tensors which match all or any of tags.

Parameters:
  • tags (str or sequence of str) – The tags to match.

  • which ({'all', 'any'}, optional) – Whether to match all or any of the tags.

check()[source]

Check some basic diagnostics of the tensor network.

add_tag(tag, where=None, which='all')[source]

Add tag to every tensor in this network, or if where is specified, the tensors matching those tags – i.e. adds the tag to all tensors in self.select_tensors(where, which=which).

drop_tags(tags=None)[source]

Remove a tag or tags from this tensor network, defaulting to all. This is an inplace operation.

Parameters:

tags (str or sequence of str or None, optional) – The tag or tags to drop. If None, drop all tags.

retag(tag_map, inplace=False)[source]

Rename tags for all tensors in this network, optionally in-place.

Parameters:
  • tag_map (dict-like) – Mapping of pairs {old_tag: new_tag, ...}.

  • inplace (bool, optional) – Perform operation inplace or return copy (default).

reindex(index_map, inplace=False)[source]

Rename indices for all tensors in this network, optionally in-place.

Parameters:

index_map (dict-like) – Mapping of pairs {old_ind: new_ind, ...}.

mangle_inner_(append=None, which=None)[source]

Generate new index names for internal bonds, meaning that when this tensor network is combined with another, there should be no collisions.

Parameters:
  • append (None or str, optional) – Whether and what to append to the indices to perform the mangling. If None a whole new random UUID will be generated.

  • which (sequence of str, optional) – Which indices to rename, if None (the default), all inner indices.

conj(mangle_inner=False, inplace=False)[source]

Conjugate all the tensors in this network (leaves all indices).

item()[source]

Return the scalar value of this tensor network, if it is a scalar.

largest_element()[source]

Return the ‘largest element’, in terms of absolute magnitude, of this tensor network. This is defined as the product of the largest elements of each tensor in the network, which would be the largest single term occuring if the TN was summed explicitly.

norm(**contract_opts)[source]

Frobenius norm of this tensor network. Computed by exactly contracting the TN with its conjugate:

\[\|T\|_F = \sqrt{\mathrm{Tr} \left(T^{\dagger} T\right)}\]

where the trace is taken over all indices. Equivalent to the square root of the sum of squared singular values across any partition.

make_norm(mangle_append='*', layer_tags=('KET', 'BRA'), return_all=False)[source]

Make the norm tensor network of this tensor network tn.H & tn.

Parameters:
  • mangle_append ({str, False or None}, optional) – How to mangle the inner indices of the bra.

  • layer_tags ((str, str), optional) – The tags to identify the top and bottom.

  • return_all (bool, optional) – Return the norm, the ket and the bra.

multiply(x, inplace=False, spread_over=8)[source]

Scalar multiplication of this tensor network with x.

Parameters:
  • x (scalar) – The number to multiply this tensor network by.

  • inplace (bool, optional) – Whether to perform the multiplication inplace.

  • spread_over (int, optional) – How many tensors to try and spread the multiplication over, in order that the effect of multiplying by a very large or small scalar is not concentrated.

multiply_each(x, inplace=False)[source]

Scalar multiplication of each tensor in this tensor network with x. If trying to spread a multiplicative factor fac uniformly over all tensors in the network and the number of tensors is large, then calling multiply(fac) can be inaccurate due to precision loss. If one has a routine that can precisely compute the x to be applied to each tensor, then this function avoids the potential inaccuracies in multiply().

Parameters:
  • x (scalar) – The number that multiplies each tensor in the network

  • inplace (bool, optional) – Whether to perform the multiplication inplace.

negate(inplace=False)[source]

Negate this tensor network.

__mul__(other)[source]

Scalar multiplication.

__rmul__(other)[source]

Right side scalar multiplication.

__imul__(other)[source]

Inplace scalar multiplication.

__truediv__(other)[source]

Scalar division.

__itruediv__(other)[source]

Inplace scalar division.

__neg__()[source]

Negate this tensor network.

__iter__()[source]
get_symbol_map()[source]

Get the mapping of the current indices to einsum style single unicode characters. The symbols are generated in the order they appear on the tensors.

get_equation(output_inds=None)[source]

Get the ‘equation’ describing this tensor network, in einsum style with a single unicode letter per index. The symbols are generated in the order they appear on the tensors.

Parameters:

output_inds (None or sequence of str, optional) – Manually specify which are the output indices.

Returns:

eq

Return type:

str

Examples

>>> tn = qtn.TN_rand_reg(10, 3, 2)
>>> tn.get_equation()
'abc,dec,fgb,hia,jke,lfk,mnj,ing,omd,ohl->'
get_inputs_output_size_dict(output_inds=None)[source]

Get a tuple of inputs, output and size_dict suitable for e.g. passing to path optimizers. The symbols are generated in the order they appear on the tensors.

Parameters:

output_inds (None or sequence of str, optional) – Manually specify which are the output indices.

Returns:

  • inputs (tuple[str])

  • output (str)

  • size_dict (dict[str, ix])

geometry_hash(output_inds=None, strict_index_order=False)[source]

A hash of this tensor network’s shapes & geometry. A useful check for determinism. Moreover, if this matches for two tensor networks then they can be contracted using the same tree for the same cost. Order of tensors matters for this - two isomorphic tensor networks with shuffled tensor order will not have the same hash value. Permuting the indices of individual of tensors or the output does not matter unless you set strict_index_order=True.

Parameters:
  • output_inds (None or sequence of str, optional) – Manually specify which indices are output indices and their order, otherwise assumed to be all indices that appear once.

  • strict_index_order (bool, optional) – If False, then the permutation of the indices of each tensor and the output does not matter.

Return type:

str

Examples

If we transpose some indices, then only the strict hash changes:

>>> tn = qtn.TN_rand_reg(100, 3, 2, seed=0)
>>> tn.geometry_hash()
'18c702b2d026dccb1a69d640b79d22f3e706b6ad'
>>> tn.geometry_hash(strict_index_order=True)
'c109fdb43c5c788c0aef7b8df7bb83853cf67ca1'
>>> t = tn['I0']
>>> t.transpose_(t.inds[2], t.inds[1], t.inds[0])
>>> tn.geometry_hash()
'18c702b2d026dccb1a69d640b79d22f3e706b6ad'
>>> tn.geometry_hash(strict_index_order=True)
'52c32c1d4f349373f02d512f536b1651dfe25893'
tensors_sorted()[source]

Return a tuple of tensors sorted by their respective tags, such that the tensors of two networks with the same tag structure can be iterated over pairwise.

apply_to_arrays(fn)[source]

Modify every tensor’s array inplace by applying fn to it. This is meant for changing how the raw arrays are backed (e.g. converting between dtypes or libraries) but not their ‘numerical meaning’.

_get_tids_from(xmap, xs, which)[source]
_get_tids_from_tags(tags, which='all')[source]

Return the set of tensor ids that match tags.

Parameters:
  • tags (seq or str, str, None, ..., int, slice) – Tag specifier(s).

  • which ({'all', 'any', '!all', '!any'}) –

    How to select based on the tags, if:

    • ’all’: get ids of tensors matching all tags

    • ’any’: get ids of tensors matching any tags

    • ’!all’: get ids of tensors not matching all tags

    • ’!any’: get ids of tensors not matching any tags

Return type:

set[str]

_get_tids_from_inds(inds, which='all')[source]

Like _get_tids_from_tags but specify inds instead.

_tids_get(*tids)[source]

Convenience function that generates unique tensors from tids.

_inds_get(*inds)[source]

Convenience function that generates unique tensors from inds.

_tags_get(*tags)[source]

Convenience function that generates unique tensors from tags.

select_tensors(tags, which='all')[source]

Return the sequence of tensors that match tags. If which='all', each tensor must contain every tag. If which='any', each tensor can contain any of the tags.

Parameters:
  • tags (str or sequence of str) – The tag or tag sequence.

  • which ({'all', 'any'}) – Whether to require matching all or any of the tags.

Returns:

tagged_tensors – The tagged tensors.

Return type:

tuple of Tensor

_select_tids(tids, virtual=True)[source]

Get a copy or a virtual copy (doesn’t copy the tensors) of this TensorNetwork, only with the tensors corresponding to tids.

_select_without_tids(tids, virtual=True)[source]

Get a copy or a virtual copy (doesn’t copy the tensors) of this TensorNetwork, without the tensors corresponding to tids.

select(tags, which='all', virtual=True)[source]

Get a TensorNetwork comprising tensors that match all or any of tags, inherit the network properties/structure from self. This returns a view of the tensors not a copy.

Parameters:
  • tags (str or sequence of str) – The tag or tag sequence.

  • which ({'all', 'any'}) – Whether to require matching all or any of the tags.

  • virtual (bool, optional) – Whether the returned tensor network views the same tensors (the default) or takes copies (virtual=False) from self.

Returns:

tagged_tn – A tensor network containing the tagged tensors.

Return type:

TensorNetwork

select_neighbors(tags, which='any')[source]

Select any neighbouring tensors to those specified by tags.self

Parameters:
  • tags (sequence of str, int) – Tags specifying tensors.

  • which ({'any', 'all'}, optional) – How to select tensors based on tags.

Returns:

The neighbouring tensors.

Return type:

tuple[Tensor]

_select_local_tids(tids, max_distance=1, fillin=False, reduce_outer=None, inwards=False, virtual=True, include=None, exclude=None)[source]
select_local(tags, which='all', max_distance=1, fillin=False, reduce_outer=None, virtual=True, include=None, exclude=None)[source]

Select a local region of tensors, based on graph distance max_distance to any tagged tensors.

Parameters:
  • tags (str or sequence of str) – The tag or tag sequence defining the initial region.

  • which ({'all', 'any', '!all', '!any'}, optional) – Whether to require matching all or any of the tags.

  • max_distance (int, optional) – The maximum distance to the initial tagged region.

  • fillin (bool or int, optional) –

    Once the local region has been selected based on graph distance, whether and how many times to ‘fill-in’ corners by adding tensors connected multiple times. For example, if R is an initially tagged tensor and x are locally selected tensors:

      fillin=0       fillin=1       fillin=2
    
     | | | | |      | | | | |      | | | | |
    -o-o-x-o-o-    -o-x-x-x-o-    -x-x-x-x-x-
     | | | | |      | | | | |      | | | | |
    -o-x-x-x-o-    -x-x-x-x-x-    -x-x-x-x-x-
     | | | | |      | | | | |      | | | | |
    -x-x-R-x-x-    -x-x-R-x-x-    -x-x-R-x-x-
    

  • reduce_outer ({'sum', 'svd', 'svd-sum', 'reflect'}, optional) – Whether and how to reduce any outer indices of the selected region.

  • virtual (bool, optional) – Whether the returned tensor network should be a view of the tensors or a copy (virtual=False).

  • include (sequence of int, optional) – Only include tensor with these tids.

  • exclude (sequence of int, optional) – Only include tensor without these tids.

Return type:

TensorNetwork

__getitem__(tags)[source]

Get the tensor(s) associated with tags.

Parameters:

tags (str or sequence of str) – The tags used to select the tensor(s).

Return type:

Tensor or sequence of Tensors

__setitem__(tags, tensor)[source]

Set the single tensor uniquely associated with tags.

__delitem__(tags)[source]

Delete any tensors which have all of tags.

partition_tensors(tags, inplace=False, which='any')[source]

Split this TN into a list of tensors containing any or all of tags and a TensorNetwork of the the rest.

Parameters:
  • tags (sequence of str) – The list of tags to filter the tensors by. Use ... (Ellipsis) to filter all.

  • inplace (bool, optional) – If true, remove tagged tensors from self, else create a new network with the tensors removed.

  • which ({'all', 'any'}) – Whether to require matching all or any of the tags.

Returns:

(u_tn, t_ts) – The untagged tensor network, and the sequence of tagged Tensors.

Return type:

(TensorNetwork, tuple of Tensors)

partition(tags, which='any', inplace=False)[source]

Split this TN into two, based on which tensors have any or all of tags. Unlike partition_tensors, both results are TNs which inherit the structure of the initial TN.

Parameters:
  • tags (sequence of str) – The tags to split the network with.

  • which ({'any', 'all'}) – Whether to split based on matching any or all of the tags.

  • inplace (bool) – If True, actually remove the tagged tensors from self.

Returns:

untagged_tn, tagged_tn – The untagged and tagged tensor networs.

Return type:

(TensorNetwork, TensorNetwork)

_split_tensor_tid(tid, left_inds, **split_opts)[source]
split_tensor(tags, left_inds, **split_opts)[source]

Split the single tensor uniquely identified by tags, adding the resulting tensors from the decomposition back into the network. Inplace operation.

replace_with_identity(where, which='any', inplace=False)[source]

Replace all tensors marked by where with an identity. E.g. if X denote where tensors:

---1  X--X--2---         ---1---2---
   |  |  |  |      ==>          |
   X--X--X  |                   |
Parameters:
  • where (tag or seq of tags) – Tags specifying the tensors to replace.

  • which ({'any', 'all'}) – Whether to replace tensors matching any or all the tags where.

  • inplace (bool) – Perform operation in place.

Returns:

The TN, with section replaced with identity.

Return type:

TensorNetwork

See also

replace_with_svd

replace_with_svd(where, left_inds, eps, *, which='any', right_inds=None, method='isvd', max_bond=None, absorb='both', cutoff_mode='rel', renorm=None, ltags=None, rtags=None, keep_tags=True, start=None, stop=None, inplace=False)[source]

Replace all tensors marked by where with an iteratively constructed SVD. E.g. if X denote where tensors:

                        :__       ___:
---X  X--X  X---        :  \     /   :
   |  |  |  |      ==>  :   U~s~VH---:
---X--X--X--X---        :__/     \   :
      |     +---        :         \__:
      X              left_inds       :
                                 right_inds
Parameters:
  • where (tag or seq of tags) – Tags specifying the tensors to replace.

  • left_inds (ind or sequence of inds) – The indices defining the left hand side of the SVD.

  • eps (float) – The tolerance to perform the SVD with, affects the number of singular values kept. See quimb.linalg.rand_linalg.estimate_rank().

  • which ({'any', 'all', '!any', '!all'}, optional) – Whether to replace tensors matching any or all the tags where, prefix with ‘!’ to invert the selection.

  • right_inds (ind or sequence of inds, optional) – The indices defining the right hand side of the SVD, these can be automatically worked out, but for hermitian decompositions the order is important and thus can be given here explicitly.

  • method (str, optional) – How to perform the decomposition, if not an iterative method the subnetwork dense tensor will be formed first, see tensor_split() for options.

  • max_bond (int, optional) – The maximum bond to keep, defaults to no maximum (-1).

  • ltags (sequence of str, optional) – Tags to add to the left tensor.

  • rtags (sequence of str, optional) – Tags to add to the right tensor.

  • keep_tags (bool, optional) – Whether to propagate tags found in the subnetwork to both new tensors or drop them, defaults to True.

  • start (int, optional) – If given, assume can use TNLinearOperator1D.

  • stop (int, optional) – If given, assume can use TNLinearOperator1D.

  • inplace (bool, optional) – Perform operation in place.

Return type:

TensorNetwork

replace_section_with_svd(start, stop, eps, **replace_with_svd_opts)[source]

Take a 1D tensor network, and replace a section with a SVD. See replace_with_svd().

Parameters:
  • start (int) – Section start index.

  • stop (int) – Section stop index, not included itself.

  • eps (float) – Precision of SVD.

  • replace_with_svd_opts – Supplied to replace_with_svd().

Return type:

TensorNetwork

convert_to_zero()[source]

Inplace conversion of this network to an all zero tensor network.

_contract_between_tids(tid1, tid2, equalize_norms=False, gauges=None, output_inds=None, **contract_opts)[source]
contract_between(tags1, tags2, **contract_opts)[source]

Contract the two tensors specified by tags1 and tags2 respectively. This is an inplace operation. No-op if the tensor specified by tags1 and tags2 is the same tensor.

Parameters:
  • tags1 – Tags uniquely identifying the first tensor.

  • tags2 (str or sequence of str) – Tags uniquely identifying the second tensor.

  • contract_opts – Supplied to tensor_contract().

contract_ind(ind, output_inds=None, **contract_opts)[source]

Contract tensors connected by ind.

gate_inds_with_tn(inds, gate, gate_inds_inner, gate_inds_outer, inplace=False)[source]

Gate some indices of this tensor network with another tensor network. That is, rewire and then combine them such that the new tensor network has the same outer indices as before, but now includes gate:

gate_inds_outer
 :
 :         gate_inds_inner
 :         :
 :         :   inds               inds
 :  ┌────┐ :   : ┌────┬───        : ┌───────┬───
 ───┤    ├──  a──┤    │          a──┤       │
    │    │       │    ├───          │       ├───
 ───┤gate├──  b──┤self│     -->  b──┤  new  │
    │    │       │    ├───          │       ├───
 ───┤    ├──  c──┤    │          c──┤       │
    └────┘       └────┴───          └───────┴───

Where there can be arbitrary structure of tensors within both self and gate.

The case where some of target inds are not present is handled as so (here ‘c’ is missing so ‘x’ and ‘y’ are kept):

gate_inds_outer
 :
 :         gate_inds_inner
 :         :
 :         :   inds               inds
 :  ┌────┐ :   : ┌────┬───        : ┌───────┬───
 ───┤    ├──  a──┤    │          a──┤       │
    │    │       │    ├───          │       ├───
 ───┤gate├──  b──┤self│     -->  b──┤  new  │
    │    │       │    ├───          │       ├───
x───┤    ├──y    └────┘          x──┤    ┌──┘
    └────┘                          └────┴───y

Which enables convinient construction of various tensor networks, for example propagators, from scratch.

Parameters:
  • inds (str or sequence of str) – The current indices to gate. If an index is not present on the target tensor network, it is ignored and instead the resulting tensor network will have both the corresponding inner and outer index of the gate tensor network.

  • gate (Tensor or TensorNetwork) – The tensor network to gate with.

  • gate_inds_inner (sequence of str) – The indices of gate to join to the old inds, must be the same length as inds.

  • gate_inds_outer (sequence of str) – The indices of gate to make the new outer inds, must be the same length as inds.

Returns:

tn_gated

Return type:

TensorNetwork

_compute_tree_gauges(tree, outputs)[source]

Given a tree of connected tensors, absorb the gauges from outside inwards, finally outputing the gauges associated with the outputs.

Parameters:
  • tree (sequence of (tid_outer, tid_inner, distance)) – The tree of connected tensors, see get_tree_span().

  • outputs (sequence of (tid, ind)) – Each output is specified by a tensor id and an index, such that having absorbed all gauges in the tree, the effective reduced factor of the tensor with respect to the index is returned.

Returns:

Gouts – The effective reduced factors of the tensor index pairs specified in outputs, each a matrix.

Return type:

sequence of array

_compress_between_virtual_tree_tids(tidl, tidr, max_bond, cutoff, r, absorb='both', include=None, exclude=None, span_opts=None, **compress_opts)[source]
_compute_bond_env(tid1, tid2, select_local_distance=None, select_local_opts=None, max_bond=None, cutoff=None, method='contract_around', contract_around_opts=None, contract_compressed_opts=None, optimize='auto-hq', include=None, exclude=None)[source]

Compute the local tensor environment of the bond(s), if cut, between two tensors.

_compress_between_full_bond_tids(tid1, tid2, max_bond, cutoff=0.0, absorb='both', renorm=False, method='eigh', select_local_distance=None, select_local_opts=None, env_max_bond='max_bond', env_cutoff='cutoff', env_method='contract_around', contract_around_opts=None, contract_compressed_opts=None, env_optimize='auto-hq', include=None, exclude=None)[source]
_compress_between_local_fit(tid1, tid2, max_bond, cutoff=0.0, absorb='both', method='als', select_local_distance=1, select_local_opts=None, include=None, exclude=None, **fit_opts)[source]
_compress_between_tids(tid1, tid2, max_bond=None, cutoff=1e-10, absorb='both', canonize_distance=None, canonize_opts=None, canonize_after_distance=None, canonize_after_opts=None, mode='basic', equalize_norms=False, gauges=None, gauge_smudge=1e-06, callback=None, **compress_opts)[source]
compress_between(tags1, tags2, max_bond=None, cutoff=1e-10, absorb='both', canonize_distance=0, canonize_opts=None, equalize_norms=False, **compress_opts)[source]

Compress the bond between the two single tensors in this network specified by tags1 and tags2 using tensor_compress_bond():

  |    |    |    |           |    |    |    |
==●====●====●====●==       ==●====●====●====●==
 /|   /|   /|   /|          /|   /|   /|   /|
  |    |    |    |           |    |    |    |
==●====1====2====●==  ==>  ==●====L----R====●==
 /|   /|   /|   /|          /|   /|   /|   /|
  |    |    |    |           |    |    |    |
==●====●====●====●==       ==●====●====●====●==
 /|   /|   /|   /|          /|   /|   /|   /|

This is an inplace operation. The compression is unlikely to be optimal with respect to the frobenius norm, unless the TN is already canonicalized at the two tensors. The absorb kwarg can be specified to yield an isometry on either the left or right resulting tensors.

Parameters:
  • tags1 – Tags uniquely identifying the first (‘left’) tensor.

  • tags2 (str or sequence of str) – Tags uniquely identifying the second (‘right’) tensor.

  • max_bond (int or None, optional) – The maxmimum bond dimension.

  • cutoff (float, optional) – The singular value cutoff to use.

  • canonize_distance (int, optional) – How far to locally canonize around the target tensors first.

  • canonize_opts (None or dict, optional) – Other options for the local canonization.

  • equalize_norms (bool or float, optional) – If set, rescale the norms of all tensors modified to this value, stripping the rescaling factor into the exponent attribute.

  • compress_opts – Supplied to tensor_compress_bond().

See also

canonize_between

compress_all(max_bond=None, cutoff=1e-10, canonize=True, tree_gauge_distance=None, canonize_distance=None, canonize_after_distance=None, mode='auto', inplace=False, **compress_opts)[source]

Compress all bonds one by one in this network.

Parameters:
  • max_bond (int or None, optional) – The maxmimum bond dimension to compress to.

  • cutoff (float, optional) – The singular value cutoff to use.

  • tree_gauge_distance (int, optional) – How far to include local tree gauge information when compressing. If the local geometry is a tree, then each compression will be locally optimal up to this distance.

  • canonize_distance (int, optional) – How far to locally canonize around the target tensors first, this is set automatically by tree_gauge_distance if not specified.

  • canonize_after_distance (int, optional) – How far to locally canonize around the target tensors after, this is set automatically by tree_gauge_distance, depending on mode if not specified.

  • mode ({'auto', 'basic', 'virtual-tree'}, optional) – The mode to use for compressing the bonds. If ‘auto’, will use ‘basic’ if tree_gauge_distance == 0 else ‘virtual-tree’.

  • inplace (bool, optional) – Whether to perform the compression inplace.

  • compress_opts – Supplied to compress_between().

Return type:

TensorNetwork

See also

compress_between, canonize_all

compress_all_tree(inplace=False, **compress_opts)[source]

Canonically compress this tensor network, assuming it to be a tree. This generates a tree spanning out from the most central tensor, then compresses all bonds inwards in a depth-first manner, using an infinite canonize_distance to shift the orthogonality center.

compress_all_1d(max_bond=None, cutoff=1e-10, canonize=True, inplace=False, **compress_opts)[source]

Compress a tensor network that you know has a 1D topology, this proceeds by generating a spanning ‘tree’ from around the least central tensor, then optionally canonicalizing all bonds outwards and compressing inwards.

Parameters:
  • max_bond (int, optional) – The maximum bond dimension to compress to.

  • cutoff (float, optional) – The singular value cutoff to use.

  • canonize (bool, optional) – Whether to canonize all bonds outwards first.

  • inplace (bool, optional) – Whether to perform the compression inplace.

  • compress_opts – Supplied to tensor_compress_bond().

Return type:

TensorNetwork

compress_all_simple(max_bond=None, cutoff=1e-10, gauges=None, max_iterations=5, tol=0.0, smudge=1e-12, power=1.0, inplace=False, **gauge_simple_opts)[source]
_canonize_between_tids(tid1, tid2, absorb='right', gauges=None, gauge_smudge=1e-06, equalize_norms=False, **canonize_opts)[source]
canonize_between(tags1, tags2, absorb='right', **canonize_opts)[source]

‘Canonize’ the bond between the two single tensors in this network specified by tags1 and tags2 using tensor_canonize_bond:

  |    |    |    |           |    |    |    |
--●----●----●----●--       --●----●----●----●--
 /|   /|   /|   /|          /|   /|   /|   /|
  |    |    |    |           |    |    |    |
--●----1----2----●--  ==>  --●---->~~~~R----●--
 /|   /|   /|   /|          /|   /|   /|   /|
  |    |    |    |           |    |    |    |
--●----●----●----●--       --●----●----●----●--
 /|   /|   /|   /|          /|   /|   /|   /|

This is an inplace operation. This can only be used to put a TN into truly canonical form if the geometry is a tree, such as an MPS.

Parameters:
  • tags1 – Tags uniquely identifying the first (‘left’) tensor, which will become an isometry.

  • tags2 (str or sequence of str) – Tags uniquely identifying the second (‘right’) tensor.

  • absorb ({'left', 'both', 'right'}, optional) – Which side of the bond to absorb the non-isometric operator.

  • canonize_opts – Supplied to tensor_canonize_bond().

See also

compress_between

reduce_inds_onto_bond(inda, indb, tags=None, drop_tags=False, combine=True, ndim_cutoff=3)[source]

Use QR factorization to ‘pull’ the indices inda and indb off of their respective tensors and onto the bond between them. This is an inplace operation.

_get_neighbor_tids(tids, exclude_inds=())[source]

Get the tids of tensors connected to the tensor(s) at tids.

Parameters:
  • tids (int or sequence of int) – The tensor identifier(s) to get the neighbors of.

  • exclude_inds (sequence of str, optional) – Exclude these indices from being considered as connections.

Return type:

oset[int]

_get_subgraph_tids(tids)[source]

Get the tids of tensors connected, by any distance, to the tensor or region of tensors tids.

_ind_to_subgraph_tids(ind)[source]

Get the tids of tensors connected, by any distance, to the index ind.

istree()[source]

Check if this tensor network has a tree structure, (treating multibonds as a single edge).

Examples

>>> MPS_rand_state(10, 7).istree()
True
>>> MPS_rand_state(10, 7, cyclic=True).istree()
False
isconnected()[source]

Check whether this tensor network is connected, i.e. whether there is a path between any two tensors, (including size 1 indices).

subgraphs(virtual=False)[source]

Split this tensor network into disconneceted subgraphs.

Parameters:

virtual (bool, optional) – Whether the tensor networks should view the original tensors or not - by default take copies.

Return type:

list[TensorNetwork]

get_tree_span(tids, min_distance=0, max_distance=None, include=None, exclude=None, ndim_sort='max', distance_sort='min', sorter=None, weight_bonds=True, inwards=True)[source]

Generate a tree on the tensor network graph, fanning out from the tensors identified by tids, up to a maximum of max_distance away. The tree can be visualized with draw_tree_span().

Parameters:
  • tids (sequence of str) – The nodes that define the region to span out of.

  • min_distance (int, optional) – Don’t add edges to the tree until this far from the region. For example, 1 will not include the last merges from neighboring tensors in the region defined by tids.

  • max_distance (None or int, optional) – Terminate branches once they reach this far away. If None there is no limit,

  • include (sequence of str, optional) – If specified, only tids specified here can be part of the tree.

  • exclude (sequence of str, optional) – If specified, tids specified here cannot be part of the tree.

  • ndim_sort ({'min', 'max', 'none'}, optional) – When expanding the tree, how to choose what nodes to expand to next, once connectivity to the current surface has been taken into account.

  • distance_sort ({'min', 'max', 'none'}, optional) – When expanding the tree, how to choose what nodes to expand to next, once connectivity to the current surface has been taken into account.

  • weight_bonds (bool, optional) – Whether to weight the ‘connection’ of a candidate tensor to expand out to using bond size as well as number of bonds.

Returns:

The ordered list of merges, each given as tuple (tid1, tid2, d) indicating merge tid1 -> tid2 at distance d.

Return type:

list[(str, str, int)]

See also

draw_tree_span

_draw_tree_span_tids(tids, span=None, min_distance=0, max_distance=None, include=None, exclude=None, ndim_sort='max', distance_sort='min', sorter=None, weight_bonds=True, color='order', colormap='Spectral', **draw_opts)[source]
draw_tree_span(tags, which='all', min_distance=0, max_distance=None, include=None, exclude=None, ndim_sort='max', distance_sort='min', weight_bonds=True, color='order', colormap='Spectral', **draw_opts)[source]

Visualize a generated tree span out of the tensors tagged by tags.

Parameters:
  • tags (str or sequence of str) – Tags specifiying a region of tensors to span out of.

  • which ({'all', 'any': '!all', '!any'}, optional) – How to select tensors based on the tags.

  • min_distance (int, optional) – See get_tree_span().

  • max_distance (None or int, optional) – See get_tree_span().

  • include (sequence of str, optional) – See get_tree_span().

  • exclude (sequence of str, optional) – See get_tree_span().

  • distance_sort ({'min', 'max'}, optional) – See get_tree_span().

  • color ({'order', 'distance'}, optional) – Whether to color nodes based on the order of the contraction or the graph distance from the specified region.

  • colormap (str) – The name of a matplotlib colormap to use.

See also

get_tree_span

_canonize_around_tids(tids, min_distance=0, max_distance=None, include=None, exclude=None, span_opts=None, absorb='right', gauge_links=False, link_absorb='both', inwards=True, gauges=None, gauge_smudge=1e-06, **canonize_opts)[source]
canonize_around(tags, which='all', min_distance=0, max_distance=None, include=None, exclude=None, span_opts=None, absorb='right', gauge_links=False, link_absorb='both', equalize_norms=False, inplace=False, **canonize_opts)[source]

Expand a locally canonical region around tags:

          --●---●--
        |   |   |   |
      --●---v---v---●--
    |   |   |   |   |   |
  --●--->---v---v---<---●--
|   |   |   |   |   |   |   |
●--->--->---O---O---<---<---●
|   |   |   |   |   |   |   |
  --●--->---^---^---^---●--
    |   |   |   |   |   |
      --●---^---^---●--
        |   |   |   |
          --●---●--

                 <=====>
                 max_distance = 2 e.g.

Shown on a grid here but applicable to arbitrary geometry. This is a way of gauging a tensor network that results in a canonical form if the geometry is described by a tree (e.g. an MPS or TTN). The canonizations proceed inwards via QR decompositions.

The sequence generated by round-robin expanding the boundary of the originally specified tensors - it will only be unique for trees.

Parameters:
  • tags (str, or sequence or str) – Tags defining which set of tensors to locally canonize around.

  • which ({'all', 'any', '!all', '!any'}, optional) – How select the tensors based on tags.

  • min_distance (int, optional) – How close, in terms of graph distance, to canonize tensors away. See get_tree_span().

  • max_distance (None or int, optional) – How far, in terms of graph distance, to canonize tensors away. See get_tree_span().

  • include (sequence of str, optional) – How to build the spanning tree to canonize along. See get_tree_span().

  • exclude (sequence of str, optional) – How to build the spanning tree to canonize along. See get_tree_span().

  • {'min' (distance_sort) – How to build the spanning tree to canonize along. See get_tree_span().

  • 'max'} – How to build the spanning tree to canonize along. See get_tree_span().

  • optional – How to build the spanning tree to canonize along. See get_tree_span().

  • absorb ({'right', 'left', 'both'}, optional) – As we canonize inwards from tensor A to tensor B which to absorb the singular values into.

  • gauge_links (bool, optional) – Whether to gauge the links between branches of the spanning tree generated (in a Simple Update like fashion).

  • link_absorb ({'both', 'right', 'left'}, optional) – If performing the link gauging, how to absorb the singular values.

  • equalize_norms (bool or float, optional) – Scale the norms of tensors acted on to this value, accumulating the log10 scaled factors in self.exponent.

  • inplace (bool, optional) – Whether to perform the canonization inplace.

Return type:

TensorNetwork

See also

get_tree_span

gauge_all_canonize(max_iterations=5, absorb='both', gauges=None, gauge_smudge=1e-06, equalize_norms=False, inplace=False, **canonize_opts)[source]

Iterative gauge all the bonds in this tensor network with a basic ‘canonization’ strategy.

gauge_all_simple(max_iterations=5, tol=0.0, smudge=1e-12, power=1.0, gauges=None, equalize_norms=False, progbar=False, inplace=False)[source]

Iterative gauge all the bonds in this tensor network with a ‘simple update’ like strategy.

gauge_all_random(max_iterations=1, unitary=True, seed=None, inplace=False)[source]

Gauge all the bonds in this network randomly. This is largely for testing purposes.

gauge_all(method='canonize', **gauge_opts)[source]

Gauge all bonds in this network using one of several strategies.

Parameters:
  • method (str, optional) – The method to use for gauging. One of “canonize”, “simple”, or “random”. Default is “canonize”.

  • gauge_opts (dict, optional) – Additional keyword arguments to pass to the chosen method.

_gauge_local_tids(tids, max_distance=1, max_iterations='max_distance', method='canonize', inwards=False, include=None, exclude=None, **gauge_local_opts)[source]

Iteratively gauge all bonds in the local tensor network defined by tids according to one of several strategies.

gauge_local(tags, which='all', max_distance=1, max_iterations='max_distance', method='canonize', inplace=False, **gauge_local_opts)[source]

Iteratively gauge all bonds in the tagged sub tensor network according to one of several strategies.

gauge_simple_insert(gauges, remove=False, smudge=0.0, power=1.0)[source]

Insert the simple update style bond gauges found in gauges if they are present in this tensor network. The gauges inserted are also returned so that they can be removed later.

Parameters:
  • gauges (dict[str, array_like]) – The store of bond gauges, the keys being indices and the values being the vectors. Only bonds present in this dictionary will be gauged.

  • remove (bool, optional) – Whether to remove the gauges from the store after inserting them.

  • smudge (float, optional) – A small value to add to the gauge vectors to avoid singularities.

Returns:

  • outer (list[(Tensor, str, array_like)]) – The sequence of gauges applied to outer indices, each a tuple of the tensor, the index and the gauge vector.

  • inner (list[((Tensor, Tensor), str, array_like)]) – The sequence of gauges applied to inner indices, each a tuple of the two inner tensors, the inner bond and the gauge vector applied.

static gauge_simple_remove(outer=None, inner=None)[source]

Remove the simple update style bond gauges inserted by gauge_simple_insert.

gauge_simple_temp(gauges, smudge=1e-12, ungauge_outer=True, ungauge_inner=True)[source]

Context manager that temporarily inserts simple update style bond gauges into this tensor network, before optionally ungauging them.

Parameters:
  • self (TensorNetwork) – The TensorNetwork to be gauge-bonded.

  • 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 gauged.

  • ungauge_outer (bool, optional) – Whether to ungauge the outer bonds.

  • ungauge_inner (bool, optional) – Whether to ungauge the inner bonds.

Yields:
  • outer (list[(Tensor, int, array_like)]) – The tensors, indices and gauges that were performed on outer indices.

  • inner (list[((Tensor, Tensor), int, array_like)]) – The tensors, indices and gauges that were performed on inner bonds.

Examples

>>> tn = TN_rand_reg(10, 4, 3)
>>> tn ^ all
-51371.66630218866
>>> gauges = {}
>>> tn.gauge_all_simple_(gauges=gauges)
>>> len(gauges)
20
>>> tn ^ all
28702551.673767876
>>> with gauged_bonds(tn, gauges):
...     # temporarily insert gauges
...     print(tn ^ all)
-51371.66630218887
>>> tn ^ all
28702551.67376789
_contract_compressed_tid_sequence(seq, max_bond=None, cutoff=1e-10, output_inds=None, tree_gauge_distance=1, canonize_distance=None, canonize_opts=None, canonize_after_distance=None, canonize_after_opts=None, gauge_boundary_only=True, compress_opts=None, compress_late=True, compress_mode='auto', compress_min_size=None, compress_span=False, compress_matrices=True, compress_exclude=None, equalize_norms=False, gauges=None, gauge_smudge=1e-06, callback_pre_contract=None, callback_post_contract=None, callback_pre_compress=None, callback_post_compress=None, callback=None, preserve_tensor=False, progbar=False, inplace=False)[source]
_contract_around_tids(tids, seq=None, min_distance=0, max_distance=None, span_opts=None, max_bond=None, cutoff=1e-10, canonize_opts=None, **kwargs)[source]

Contract around tids, by following a greedily generated spanning tree, and compressing whenever two tensors in the outer ‘boundary’ share more than one index.

compute_centralities()[source]
most_central_tid()[source]
least_central_tid()[source]
contract_around_center(**opts)[source]
contract_around_corner(**opts)[source]
contract_around(tags, which='all', min_distance=0, max_distance=None, span_opts=None, max_bond=None, cutoff=1e-10, tree_gauge_distance=1, canonize_distance=None, canonize_opts=None, canonize_after_distance=None, canonize_after_opts=None, gauge_boundary_only=True, compress_late=True, compress_min_size=None, compress_opts=None, compress_span=False, compress_matrices=True, equalize_norms=False, gauges=None, gauge_smudge=1e-06, callback_pre_contract=None, callback_post_contract=None, callback_pre_compress=None, callback_post_compress=None, callback=None, inplace=False, **kwargs)[source]

Perform a compressed contraction inwards towards the tensors identified by tags.

contract_compressed(optimize, output_inds=None, max_bond=None, cutoff=1e-10, tree_gauge_distance=1, canonize_distance=None, canonize_opts=None, canonize_after_distance=None, canonize_after_opts=None, gauge_boundary_only=True, compress_late=True, compress_min_size=None, compress_opts=None, compress_span=True, compress_matrices=True, compress_exclude=None, equalize_norms=False, gauges=None, gauge_smudge=1e-06, callback_pre_contract=None, callback_post_contract=None, callback_pre_compress=None, callback_post_compress=None, callback=None, progbar=False, **kwargs)[source]
new_bond(tags1, tags2, **opts)[source]

Inplace addition of a dummmy (size 1) bond between the single tensors specified by by tags1 and tags2.

Parameters:
  • tags1 (sequence of str) – Tags identifying the first tensor.

  • tags2 (sequence of str) – Tags identifying the second tensor.

  • opts – Supplied to new_bond().

See also

new_bond

_cut_between_tids(tid1, tid2, left_ind, right_ind)[source]
cut_between(left_tags, right_tags, left_ind, right_ind)[source]

Cut the bond between the tensors specified by left_tags and right_tags, giving them the new inds left_ind and right_ind respectively.

cut_bond(bond, new_left_ind=None, new_right_ind=None)[source]

Cut the bond index specified by bond between the tensors it connects. Use cut_between for control over which tensor gets which new index new_left_ind or new_right_ind. The index must connect exactly two tensors.

Parameters:
  • bond (str) – The index to cut.

  • new_left_ind (str, optional) – The new index to give to the left tensor (lowest tid value).

  • new_right_ind (str, optional) – The new index to give to the right tensor (highest tid value).

drape_bond_between(tagsa, tagsb, tags_target, left_ind=None, right_ind=None, inplace=False)[source]

Take the bond(s) connecting the tensors tagged at tagsa and tagsb, and ‘drape’ it through the tensor tagged at tags_target, effectively adding an identity tensor between the two and contracting it with the third:

 ┌─┐    ┌─┐      ┌─┐     ┌─┐
─┤A├─Id─┤B├─    ─┤A├─┐ ┌─┤B├─
 └─┘    └─┘      └─┘ │ │ └─┘
             left_ind│ │right_ind
     ┌─┐     -->     ├─┤
    ─┤C├─           ─┤D├─
     └┬┘             └┬┘     where D = C ⊗ Id
      │               │

This increases the size of the target tensor by d**2, and disconnects the tensors at tagsa and tagsb.

Parameters:
  • tagsa (str or sequence of str) – The tag(s) identifying the first tensor.

  • tagsb (str or sequence of str) – The tag(s) identifying the second tensor.

  • tags_target (str or sequence of str) – The tag(s) identifying the target tensor.

  • left_ind (str, optional) – The new index to give to the left tensor.

  • right_ind (str, optional) – The new index to give to the right tensor.

  • inplace (bool, optional) – Whether to perform the draping inplace.

Return type:

TensorNetwork

isel(selectors, inplace=False)[source]

Select specific values for some dimensions/indices of this tensor network, thereby removing them.

Parameters:
  • selectors (dict[str, int]) – Mapping of index(es) to which value to take.

  • inplace (bool, optional) – Whether to select inplace or not.

Return type:

TensorNetwork

See also

Tensor.isel

sum_reduce(ind, inplace=False)[source]

Sum over the index ind of this tensor network, removing it. This is like contracting a vector of ones in, or marginalizing a classical probability distribution.

Parameters:
  • ind (str) – The index to sum over.

  • inplace (bool, optional) – Whether to perform the reduction inplace.

vector_reduce(ind, v, inplace=False)[source]

Contract the vector v with the index ind of this tensor network, removing it.

Parameters:
  • ind (str) – The index to contract.

  • v (array_like) – The vector to contract with.

  • inplace (bool, optional) – Whether to perform the reduction inplace.

Return type:

TensorNetwork

cut_iter(*inds)[source]

Cut and iterate over one or more indices in this tensor network. Each network yielded will have that index removed, and the sum of all networks will equal the original network. This works by iterating over the product of all combinations of each bond supplied to isel. As such, the number of networks produced is exponential in the number of bonds cut.

Parameters:

inds (sequence of str) – The bonds to cut.

Yields:

TensorNetwork

Examples

Here we’ll cut the two extra bonds of a cyclic MPS and sum the contraction of the resulting 49 OBC MPS norms:

>>> psi = MPS_rand_state(10, bond_dim=7, cyclic=True)
>>> norm = psi.H & psi
>>> bnds = bonds(norm[0], norm[-1])
>>> sum(tn ^ all for tn in norm.cut_iter(*bnds))
1.0
insert_operator(A, where1, where2, tags=None, inplace=False)[source]

Insert an operator on the bond between the specified tensors, e.g.:

  |   |              |   |
--1---2--    ->    --1-A-2--
  |                  |
Parameters:
  • A (array) – The operator to insert.

  • where1 (str, sequence of str, or int) – The tags defining the ‘left’ tensor.

  • where2 (str, sequence of str, or int) – The tags defining the ‘right’ tensor.

  • tags (str or sequence of str) – Tags to add to the new operator’s tensor.

  • inplace (bool, optional) – Whether to perform the insertion inplace.

_insert_gauge_tids(U, tid1, tid2, Uinv=None, tol=1e-10, bond=None)[source]
insert_gauge(U, where1, where2, Uinv=None, tol=1e-10)[source]

Insert the gauge transformation U^-1 @ U into the bond between the tensors, T1 and T2, defined by where1 and where2. The resulting tensors at those locations will be T1 @ U^-1 and U @ T2.

Parameters:
  • U (array) – The gauge to insert.

  • where1 (str, sequence of str, or int) – Tags defining the location of the ‘left’ tensor.

  • where2 (str, sequence of str, or int) – Tags defining the location of the ‘right’ tensor.

  • Uinv (array) – The inverse gauge, U @ Uinv == Uinv @ U == eye, to insert. If not given will be calculated using numpy.linalg.inv().

contract_tags(tags, which='any', output_inds=None, optimize=None, get=None, backend=None, preserve_tensor=False, inplace=False, **contract_opts)[source]

Contract the tensors that match any or all of tags.

Parameters:
  • tags (sequence of str) – The list of tags to filter the tensors by. Use all or ... (Ellipsis) to contract all tensors.

  • which ({'all', 'any'}) – Whether to require matching all or any of the tags.

  • output_inds (sequence of str, optional) – The indices to specify as outputs of the contraction. If not given, and the tensor network has no hyper-indices, these are computed automatically as every index appearing once.

  • optimize ({None, str, path_like, PathOptimizer}, optional) –

    The contraction path optimization strategy to use.

    • None: use the default strategy,

    • str: use the preset strategy with the given name,

    • path_like: use this exact path,

    • cotengra.HyperOptimizer: find the contraction using this optimizer, supports slicing,

    • cotengra.ContractionTree: use this exact tree, supports

    slicing, - opt_einsum.PathOptimizer: find the path using this

    optimizer.

    Contraction with cotengra might be a bit more efficient but the main reason would be to handle sliced contraction automatically.

  • get (str, optional) –

    What to return. If:

    • None (the default) - return the resulting scalar or Tensor.

    • 'expression' - return a callbable expression that performs the contraction and operates on the raw arrays.

    • 'tree' - return the cotengra.ContractionTree describing the contraction.

    • 'path' - return the raw ‘path’ as a list of tuples.

    • 'symbol-map' - return the dict mapping indices to ‘symbols’ (single unicode letters) used internally by cotengra

    • 'path-info' - return the opt_einsum.PathInfo path object with detailed information such as flop cost. The symbol-map is also added to the quimb_symbol_map attribute.

  • backend ({'auto', 'numpy', 'jax', 'cupy', 'tensorflow', ...}, optional) – Which backend to use to perform the contraction. Supplied to cotengra.

  • preserve_tensor (bool, optional) – Whether to return a tensor regardless of whether the output object is a scalar (has no indices) or not.

  • inplace (bool, optional) – Whether to perform the contraction inplace.

  • contract_opts – Passed to tensor_contract().

Returns:

The result of the contraction, still a TensorNetwork if the contraction was only partial.

Return type:

TensorNetwork, Tensor or scalar

contract(tags=..., output_inds=None, optimize=None, get=None, backend=None, preserve_tensor=False, max_bond=None, inplace=False, **opts)[source]

Contract some, or all, of the tensors in this network. This method dispatches to contract_tags, contract_structured, or contract_compressed based on the various arguments.

Parameters:
  • tags (sequence of str, all, or Ellipsis, optional) – Any tensors with any of these tags with be contracted. Use all or ... (Ellipsis) to contract all tensors. ... will try and use a ‘structured’ contract method if possible.

  • output_inds (sequence of str, optional) – The indices to specify as outputs of the contraction. If not given, and the tensor network has no hyper-indices, these are computed automatically as every index appearing once.

  • optimize ({None, str, path_like, PathOptimizer}, optional) –

    The contraction path optimization strategy to use.

    • None: use the default strategy,

    • str: use the preset strategy with the given name,

    • path_like: use this exact path,

    • cotengra.HyperOptimizer: find the contraction using this optimizer, supports slicing,

    • cotengra.ContractionTree: use this exact tree, supports slicing,

    • opt_einsum.PathOptimizer: find the path using this optimizer.

    Contraction with cotengra might be a bit more efficient but the main reason would be to handle sliced contraction automatically.

  • get (str, optional) –

    What to return. If:

    • None (the default) - return the resulting scalar or Tensor.

    • 'expression' - return a callbable expression that performs the contraction and operates on the raw arrays.

    • 'tree' - return the cotengra.ContractionTree describing the contraction.

    • 'path' - return the raw ‘path’ as a list of tuples.

    • 'symbol-map' - return the dict mapping indices to ‘symbols’ (single unicode letters) used internally by cotengra

    • 'path-info' - return the opt_einsum.PathInfo path object with detailed information such as flop cost. The symbol-map is also added to the quimb_symbol_map attribute.

  • backend ({'auto', 'numpy', 'jax', 'cupy', 'tensorflow', ...}, optional) – Which backend to use to perform the contraction. Supplied to cotengra.

  • preserve_tensor (bool, optional) – Whether to return a tensor regardless of whether the output object is a scalar (has no indices) or not.

  • inplace (bool, optional) – Whether to perform the contraction inplace. This is only valid if not all tensors are contracted (which doesn’t produce a TN).

  • opts – Passed to tensor_contract(), contract_compressed() .

Returns:

The result of the contraction, still a TensorNetwork if the contraction was only partial.

Return type:

TensorNetwork, Tensor or scalar

contract_cumulative(tags_seq, output_inds=None, preserve_tensor=False, equalize_norms=False, inplace=False, **opts)[source]

Cumulative contraction of tensor network. Contract the first set of tags, then that set with the next set, then both of those with the next and so forth. Could also be described as an manually ordered contraction of all tags in tags_seq.

Parameters:
  • tags_seq (sequence of sequence of str) – The list of tag-groups to cumulatively contract.

  • output_inds (sequence of str, optional) – The indices to specify as outputs of the contraction. If not given, and the tensor network has no hyper-indices, these are computed automatically as every index appearing once.

  • preserve_tensor (bool, optional) – Whether to return a tensor regardless of whether the output object is a scalar (has no indices) or not.

  • inplace (bool, optional) – Whether to perform the contraction inplace.

  • opts – Passed to tensor_contract().

Returns:

The result of the contraction, still a TensorNetwork if the contraction was only partial.

Return type:

TensorNetwork, Tensor or scalar

contraction_path(optimize=None, **contract_opts)[source]

Compute the contraction path, a sequence of (int, int), for the contraction of this entire tensor network using path optimizer optimize.

contraction_info(optimize=None, **contract_opts)[source]

Compute the opt_einsum.PathInfo object decsribing the contraction of this entire tensor network using path optimizer optimize.

contraction_tree(optimize=None, output_inds=None, **kwargs)[source]

Return the cotengra.ContractionTree corresponding to contracting this entire tensor network with path finder optimize.

contraction_width(optimize=None, **contract_opts)[source]

Compute the ‘contraction width’ of this tensor network. This is defined as log2 of the maximum tensor size produced during the contraction sequence. If every index in the network has dimension 2 this corresponds to the maximum rank tensor produced.

contraction_cost(optimize=None, **contract_opts)[source]

Compute the ‘contraction cost’ of this tensor network. This is defined as log10 of the total number of scalar operations during the contraction sequence.

__rshift__(tags_seq)[source]

Overload of ‘>>’ for TensorNetwork.contract_cumulative.

__irshift__(tags_seq)[source]

Overload of ‘>>=’ for inplace TensorNetwork.contract_cumulative.

__xor__(tags)[source]

Overload of ‘^’ for TensorNetwork.contract.

__ixor__(tags)[source]

Overload of ‘^=’ for inplace TensorNetwork.contract.

__matmul__(other)[source]

Overload “@” to mean full contraction with another network.

as_network(virtual=True)[source]

Matching method (for ensuring object is a tensor network) to as_network(), which simply returns self if virtual=True.

aslinearoperator(left_inds, right_inds, ldims=None, rdims=None, backend=None, optimize=None)[source]

View this TensorNetwork as a TNLinearOperator.

split(left_inds, right_inds=None, **split_opts)[source]

Decompose this tensor network across a bipartition of outer indices.

This method matches Tensor.split by converting to a TNLinearOperator first. Note unless an iterative method is passed to method, the full dense tensor will be contracted.

trace(left_inds, right_inds, **contract_opts)[source]

Trace over left_inds joined with right_inds

to_dense(*inds_seq, to_qarray=False, **contract_opts)[source]

Convert this network 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: TN.to_dense(('k0', 'k1'), ('b0', 'b1')).

compute_reduced_factor(side, left_inds, right_inds, optimize='auto-hq', **contract_opts)[source]

Compute either the left or right ‘reduced factor’ of this tensor network. I.e., view as an operator, X, mapping left_inds to right_inds and compute L or R such that X = U_R @ R or X = L @ U_L, with U_R and U_L unitary operators that are not computed. Only dag(X) @ X or X @ dag(X) is contracted, which is generally cheaper than contracting X itself.

Parameters:
  • self (TensorNetwork) – The tensor network to compute the reduced factor of.

  • side ({'left', 'right'}) – Whether to compute the left or right reduced factor. If ‘right’ then dag(X) @ X is contracted, otherwise X @ dag(X).

  • left_inds (sequence of str) – The indices forming the left side of the operator.

  • right_inds (sequence of str) – The indices forming the right side of the operator.

  • contract_opts (dict, optional) – Options to pass to to_dense().

Return type:

array_like

insert_compressor_between_regions(ltags, rtags, max_bond=None, cutoff=1e-10, select_which='any', insert_into=None, new_tags=None, new_ltags=None, new_rtags=None, bond_ind=None, optimize='auto-hq', inplace=False, **compress_opts)[source]

Compute and insert a pair of ‘oblique’ projection tensors (see for example https://arxiv.org/abs/1905.02351) that effectively compresses between two regions of the tensor network. Useful for various approximate contraction methods such as HOTRG and CTMRG.

Parameters:
  • ltags (sequence of str) – The tags of the tensors in the left region.

  • rtags (sequence of str) – The tags of the tensors in the right region.

  • max_bond (int or None, optional) – The maximum bond dimension to use for the compression (i.e. shared by the two projection tensors). If None then the maximum is controlled by cutoff.

  • cutoff (float, optional) – The cutoff to use for the compression.

  • select_which ({'any', 'all', 'none'}, optional) – How to select the regions based on the tags, see select().

  • insert_into (TensorNetwork, optional) – If given, insert the new tensors into this tensor network, assumed to have the same relevant indices as self.

  • new_tags (str or sequence of str, optional) – The tag(s) to add to both the new tensors.

  • new_ltags (str or sequence of str, optional) – The tag(s) to add to the new left projection tensor.

  • new_rtags (str or sequence of str, optional) – The tag(s) to add to the new right projection tensor.

  • optimize (str or PathOptimizer, optional) – How to optimize the contraction of the projection tensors.

  • inplace (bool, optional) – Whether perform the insertion in-place. If insert_into is supplied then this doesn’t matter, and that tensor network will be modified and returned.

Return type:

TensorNetwork

distance(*args, **kwargs)[source]
fit(tn_target, method='als', tol=1e-09, inplace=False, progbar=False, **fitting_opts)[source]

Optimize the entries of this tensor network with respect to a least squares fit of tn_target which should have the same outer indices. Depending on method this calls tensor_network_fit_als() or tensor_network_fit_autodiff(). The quantity minimized is:

\[D(A, B) = | A - B |_{\mathrm{fro}} = \mathrm{Tr} [(A - B)^{\dagger}(A - B)]^{1/2} = ( \langle A | A \rangle - 2 \mathrm{Re} \langle A | B \rangle| + \langle B | B \rangle ) ^{1/2}\]
Parameters:
  • tn_target (TensorNetwork) – The target tensor network to try and fit the current one to.

  • method ({'als', 'autodiff'}, optional) – Whether to use alternating least squares (ALS) or automatic differentiation to perform the optimization. Generally ALS is better for simple geometries, autodiff better for complex ones.

  • tol (float, optional) – The target norm distance.

  • inplace (bool, optional) – Update the current tensor network in place.

  • progbar (bool, optional) – Show a live progress bar of the fitting process.

  • fitting_opts – Supplied to either tensor_network_fit_als() or tensor_network_fit_autodiff().

Returns:

tn_opt – The optimized tensor network.

Return type:

TensorNetwork

all_inds()[source]

Return a tuple of all indices in this network.

ind_size(ind)[source]

Find the size of ind.

inds_size(inds)[source]

Return the total size of dimensions corresponding to inds.

ind_sizes()[source]

Get dict of each index mapped to its size.

inner_inds()[source]

Tuple of interior indices, assumed to be any indices that appear twice or more (this only holds generally for non-hyper tensor networks).

outer_inds()[source]

Tuple of exterior indices, assumed to be any lone indices (this only holds generally for non-hyper tensor networks).

outer_dims_inds()[source]

Get the ‘outer’ pairs of dimension and indices, i.e. as if this tensor network was fully contracted.

outer_size()[source]

Get the total size of the ‘outer’ indices, i.e. as if this tensor network was fully contracted.

get_multibonds(include=None, exclude=None)[source]

Get a dict of ‘multibonds’ in this tensor network, i.e. groups of two or more indices that appear on exactly the same tensors and thus could be fused, for example.

Parameters:
  • include (sequence of str, optional) – Only consider these indices, by default all indices.

  • exclude (sequence of str, optional) – Ignore these indices, by default the outer indices of this TN.

Returns:

A dict mapping the tuple of indices that could be fused to the tuple of tensor ids they appear on.

Return type:

dict[tuple[str], tuple[int]]

get_hyperinds(output_inds=None)[source]

Get a tuple of all ‘hyperinds’, defined as those indices which don’t appear exactly twice on either the tensors or in the ‘outer’ (i.e. output) indices.

Note the default set of ‘outer’ indices is calculated as only those indices that appear once on the tensors, so these likely need to be manually specified, otherwise, for example, an index that appears on two tensors and the output will incorrectly be identified as non-hyper.

Parameters:

output_inds (None, str or sequence of str, optional) – The outer or output index or indices. If not specified then taken as every index that appears only once on the tensors (and thus non-hyper).

Returns:

The tensor network hyperinds.

Return type:

tuple[str]

compute_contracted_inds(*tids, output_inds=None)[source]

Get the indices describing the tensor contraction of tensors corresponding to tids.

squeeze(fuse=False, include=None, exclude=None, inplace=False)[source]

Drop singlet bonds and dimensions from this tensor network. If fuse=True also fuse all multibonds between tensors.

Parameters:
  • fuse (bool, optional) – Whether to fuse multibonds between tensors as well as squeezing.

  • include (sequence of str, optional) – Only squeeze these indices, by default all indices.

  • exclude (sequence of str, optional) – Ignore these indices, by default the outer indices of this TN.

  • inplace (bool, optional) – Whether to perform the squeeze and optional fuse inplace.

Return type:

TensorNetwork

isometrize(method='qr', allow_no_left_inds=False, inplace=False)[source]

Project every tensor in this network into an isometric form, assuming they have left_inds marked.

Parameters:
  • method (str, optional) –

    The method used to generate the isometry. The options are:

    • ”qr”: use the Q factor of the QR decomposition of x with the constraint that the diagonal of R is positive.

    • ”svd”: uses U @ VH of the SVD decomposition of x. This is useful for finding the ‘closest’ isometric matrix to x, such as when it has been expanded with noise etc. But is less stable for differentiation / optimization.

    • ”exp”: use the matrix exponential of x - dag(x), first completing x with zeros if it is rectangular. This is a good parametrization for optimization, but more expensive for non-square x.

    • ”cayley”: use the Cayley transform of x - dag(x), first completing x with zeros if it is rectangular. This is a good parametrization for optimization (one the few compatible with HIPS/autograd e.g.), but more expensive for non-square x.

    • ”householder”: use the Householder reflection method directly. This requires that the backend implements “linalg.householder_product”.

    • ”torch_householder”: use the Householder reflection method directly, using the torch_householder package. This requires that the package is installed and that the backend is "torch". This is generally the best parametrizing method for “torch” if available.

    • ”mgs”: use a python implementation of the modified Gram Schmidt method directly. This is slow if not compiled but a useful reference.

    Not all backends support all methods or differentiating through all methods.

  • allow_no_left_inds (bool, optional) – If True then allow tensors with no left_inds to be left alone, rather than raising an error.

  • inplace (bool, optional) – If True then perform the operation in-place.

Return type:

TensorNetwork

randomize(dtype=None, seed=None, inplace=False, **randn_opts)[source]

Randomize every tensor in this TN - see quimb.tensor.tensor_core.Tensor.randomize().

Parameters:
  • dtype ({None, str}, optional) – The data type of the random entries. If left as the default None, then the data type of the current array will be used.

  • seed (None or int, optional) – Seed for the random number generator.

  • inplace (bool, optional) – Whether to perform the randomization inplace, by default False.

  • randn_opts – Supplied to randn().

Return type:

TensorNetwork

strip_exponent(tid_or_tensor, value=None)[source]

Scale the elements of tensor corresponding to tid so that the norm of the array is some value, which defaults to 1. The log of the scaling factor, base 10, is then accumulated in the exponent attribute.

Parameters:
  • tid (str or Tensor) – The tensor identifier or actual tensor.

  • value (None or float, optional) – The value to scale the norm of the tensor to.

distribute_exponent()[source]

Distribute the exponent p of this tensor network (i.e. corresponding to tn * 10**p) equally among all tensors.

equalize_norms(value=None, inplace=False)[source]

Make the Frobenius norm of every tensor in this TN equal without changing the overall value if value=None, or set the norm of every tensor to value by scalar multiplication only.

Parameters:
  • value (None or float, optional) – Set the norm of each tensor to this value specifically. If supplied the change in overall scaling will be accumulated in tn.exponent in the form of a base 10 power.

  • inplace (bool, optional) – Whether to perform the norm equalization inplace or not.

Return type:

TensorNetwork

balance_bonds(inplace=False)[source]

Apply tensor_balance_bond() to all bonds in this tensor network.

Parameters:

inplace (bool, optional) – Whether to perform the bond balancing inplace or not.

Return type:

TensorNetwork

fuse_multibonds(gauges=None, include=None, exclude=None, inplace=False)[source]

Fuse any multi-bonds (more than one index shared by the same pair of tensors) into a single bond.

Parameters:
  • gauges (None or dict[str, array_like], optional) – If supplied, also fuse the gauges contained in this dict.

  • include (sequence of str, optional) – Only consider these indices, by default all indices.

  • exclude (sequence of str, optional) – Ignore these indices, by default the outer indices of this TN.

expand_bond_dimension(new_bond_dim, mode=None, rand_strength=None, rand_dist='normal', inds_to_expand=None, inplace=False)[source]

Increase the dimension of all or some of the bonds in this tensor network to at least new_bond_dim, optinally adding some random noise to the new entries.

Parameters:
  • new_bond_dim (int) – The minimum bond dimension to expand to, if the bond dimension is already larger than this it will be left unchanged.

  • rand_strength (float, optional) – The strength of random noise to add to the new array entries, if any. The noise is drawn from a normal distribution with standard deviation rand_strength.

  • inds_to_expand (sequence of str, optional) – The indices to expand, if not all.

  • inplace (bool, optional) – Whether to expand this tensor network in place, or return a new one.

Return type:

TensorNetwork

flip(inds, inplace=False)[source]

Flip the dimension corresponding to indices inds on all tensors that share it.

rank_simplify(output_inds=None, equalize_norms=False, cache=None, max_combinations=500, inplace=False)[source]

Simplify this tensor network by performing contractions that don’t increase the rank of any tensors.

Parameters:
  • output_inds (sequence of str, optional) – Explicitly set which indices of the tensor network are output indices and thus should not be modified.

  • equalize_norms (bool or float) – Actively renormalize the tensors during the simplification process. Useful for very large TNs. The scaling factor will be stored as an exponent in tn.exponent.

  • cache (None or set) – Persistent cache used to mark already checked tensors.

  • inplace (bool, optional) – Whether to perform the rand reduction inplace.

Return type:

TensorNetwork

diagonal_reduce(output_inds=None, atol=1e-12, cache=None, inplace=False)[source]

Find tensors with diagonal structure and collapse those axes. This will create a tensor ‘hyper’ network with indices repeated 2+ times, as such, output indices should be explicitly supplied when contracting, as they can no longer be automatically inferred. For example:

>>> tn_diag = tn.diagonal_reduce()
>>> tn_diag.contract(all, output_inds=[])
Parameters:
  • output_inds (sequence of str, optional) – Which indices to explicitly consider as outer legs of the tensor network and thus not replace. If not given, these will be taken as all the indices that appear once.

  • atol (float, optional) – When identifying diagonal tensors, the absolute tolerance with which to compare to zero with.

  • cache (None or set) – Persistent cache used to mark already checked tensors.

  • inplace – Whether to perform the diagonal reduction inplace.

  • bool – Whether to perform the diagonal reduction inplace.

  • optional – Whether to perform the diagonal reduction inplace.

Return type:

TensorNetwork

antidiag_gauge(output_inds=None, atol=1e-12, cache=None, inplace=False)[source]

Flip the order of any bonds connected to antidiagonal tensors. Whilst this is just a gauge fixing (with the gauge being the flipped identity) it then allows diagonal_reduce to then simplify those indices.

Parameters:
  • output_inds (sequence of str, optional) – Which indices to explicitly consider as outer legs of the tensor network and thus not flip. If not given, these will be taken as all the indices that appear once.

  • atol (float, optional) – When identifying antidiagonal tensors, the absolute tolerance with which to compare to zero with.

  • cache (None or set) – Persistent cache used to mark already checked tensors.

  • inplace – Whether to perform the antidiagonal gauging inplace.

  • bool – Whether to perform the antidiagonal gauging inplace.

  • optional – Whether to perform the antidiagonal gauging inplace.

Return type:

TensorNetwork

column_reduce(output_inds=None, atol=1e-12, cache=None, inplace=False)[source]

Find bonds on this tensor network which have tensors where all but one column (of the respective index) is non-zero, allowing the ‘cutting’ of that bond.

Parameters:
  • output_inds (sequence of str, optional) – Which indices to explicitly consider as outer legs of the tensor network and thus not slice. If not given, these will be taken as all the indices that appear once.

  • atol (float, optional) – When identifying singlet column tensors, the absolute tolerance with which to compare to zero with.

  • cache (None or set) – Persistent cache used to mark already checked tensors.

  • inplace – Whether to perform the column reductions inplace.

  • bool – Whether to perform the column reductions inplace.

  • optional – Whether to perform the column reductions inplace.

Return type:

TensorNetwork

split_simplify(atol=1e-12, equalize_norms=False, cache=None, inplace=False, **split_opts)[source]

Find tensors which have low rank SVD decompositions across any combination of bonds and perform them.

Parameters:
  • atol (float, optional) – Cutoff used when attempting low rank decompositions.

  • equalize_norms (bool or float) – Actively renormalize the tensors during the simplification process. Useful for very large TNs. The scaling factor will be stored as an exponent in tn.exponent.

  • cache (None or set) – Persistent cache used to mark already checked tensors.

  • inplace – Whether to perform the split simplification inplace.

  • bool – Whether to perform the split simplification inplace.

  • optional – Whether to perform the split simplification inplace.

gen_loops(max_loop_length=None)[source]

Generate sequences of tids that represent loops in the TN.

Parameters:

max_loop_length (None or int) – Set the maximum number of tensors that can appear in a loop. If None, wait until any loop is found and set that as the maximum length.

Yields:

tuple[int]

_get_string_between_tids(tida, tidb)[source]
tids_are_connected(tids)[source]

Check whether nodes tids are connected.

Parameters:

tids (sequence of int) – Nodes to check.

Return type:

bool

compute_shortest_distances(tids=None, exclude_inds=())[source]

Compute the minimum graph distances between all or some nodes tids.

compute_hierarchical_linkage(tids=None, method='weighted', optimal_ordering=True, exclude_inds=())[source]
compute_hierarchical_ssa_path(tids=None, method='weighted', optimal_ordering=True, exclude_inds=(), are_sorted=False, linkage=None)[source]

Compute a hierarchical grouping of tids, as a ssa_path.

compute_hierarchical_ordering(tids=None, method='weighted', optimal_ordering=True, exclude_inds=(), linkage=None)[source]
compute_hierarchical_grouping(max_group_size, tids=None, method='weighted', optimal_ordering=True, exclude_inds=(), linkage=None)[source]

Group tids (by default, all tensors) into groups of size max_group_size or less, using a hierarchical clustering.

pair_simplify(cutoff=1e-12, output_inds=None, max_inds=10, cache=None, equalize_norms=False, max_combinations=500, inplace=False, **split_opts)[source]
loop_simplify(output_inds=None, max_loop_length=None, max_inds=10, cutoff=1e-12, loops=None, cache=None, equalize_norms=False, inplace=False, **split_opts)[source]

Try and simplify this tensor network by identifying loops and checking for low-rank decompositions across groupings of the loops outer indices.

Parameters:
  • max_loop_length (None or int, optional) – Largest length of loop to search for, if not set, the size will be set to the length of the first (and shortest) loop found.

  • cutoff (float, optional) – Cutoff to use for the operator decomposition.

  • loops (None, sequence or callable) – Loops to check, or a function that generates them.

  • cache (set, optional) – For performance reasons can supply a cache for already checked loops.

  • inplace (bool, optional) – Whether to replace the loops inplace.

  • split_opts – Supplied to tensor_split().

Return type:

TensorNetwork

full_simplify(seq='ADCR', output_inds=None, atol=1e-12, equalize_norms=False, cache=None, inplace=False, progbar=False, rank_simplify_opts=None, loop_simplify_opts=None, split_simplify_opts=None, custom_methods=(), split_method='svd')[source]

Perform a series of tensor network ‘simplifications’ in a loop until there is no more reduction in the number of tensors or indices. Note that apart from rank-reduction, the simplification methods make use of the non-zero structure of the tensors, and thus changes to this will potentially produce different simplifications.

Parameters:
  • seq (str, optional) –

    Which simplifications and which order to perform them in.

    • 'A' : stands for antidiag_gauge

    • 'D' : stands for diagonal_reduce

    • 'C' : stands for column_reduce

    • 'R' : stands for rank_simplify

    • 'S' : stands for split_simplify

    • 'L' : stands for loop_simplify

    If you want to keep the tensor network ‘simple’, i.e. with no hyperedges, then don’t use 'D' (moreover 'A' is redundant).

  • output_inds (sequence of str, optional) – Explicitly set which indices of the tensor network are output indices and thus should not be modified. If not specified the tensor network is assumed to be a ‘standard’ one where indices that only appear once are the output indices.

  • atol (float, optional) – The absolute tolerance when indentifying zero entries of tensors and performing low-rank decompositions.

  • equalize_norms (bool or float) – Actively renormalize the tensors during the simplification process. Useful for very large TNs. If True, the norms, in the formed of stripped exponents, will be redistributed at the end. If an actual number, the final tensors will all have this norm, and the scaling factor will be stored as a base-10 exponent in tn.exponent.

  • cache (None or set) – A persistent cache for each simplification process to mark already processed tensors.

  • progbar (bool, optional) – Show a live progress bar of the simplification process.

  • inplace (bool, optional) – Whether to perform the simplification inplace.

Return type:

TensorNetwork

hyperinds_resolve(mode='dense', sorter=None, output_inds=None, inplace=False)[source]

Convert this into a regular tensor network, where all indices appear at most twice, by inserting COPY tensor or tensor networks for each hyper index.

Parameters:
  • mode ({'dense', 'mps', 'tree'}, optional) – What type of COPY tensor(s) to insert.

  • sorter (None or callable, optional) – If given, a function to sort the indices that a single hyperindex will be turned into. Th function is called like tids.sort(key=sorter).

  • inplace (bool, optional) – Whether to insert the COPY tensors inplace.

Return type:

TensorNetwork

compress_simplify(output_inds=None, atol=1e-06, simplify_sequence_a='ADCRS', simplify_sequence_b='RPL', hyperind_resolve_mode='tree', hyperind_resolve_sort='clustering', final_resolve=False, split_method='svd', max_simplification_iterations=100, converged_tol=0.01, equalize_norms=True, progbar=False, inplace=False, **full_simplify_opts)[source]
max_bond()[source]

Return the size of the largest bond in this network.

iscomplex()[source]
astype(dtype, inplace=False)[source]

Convert the type of all tensors in this network to dtype.

__getstate__()[source]

Helper for pickle.

__setstate__(state)[source]
_repr_info()[source]

General info to show in various reprs. Sublasses can add more relevant info to this dict.

_repr_info_str()[source]

Render the general info as a string.

_repr_html_()[source]

Render this TensorNetwork as HTML, for Jupyter notebooks.

__str__()[source]

Return str(self).

__repr__()[source]

Return repr(self).

quimb.tensor.bonds(t1, t2)[source]

Getting any indices connecting the Tensor(s) or TensorNetwork(s) t1 and t2.

quimb.tensor.bonds_size(t1, t2)[source]

Get the size of the bonds linking tensors or tensor networks t1 and t2.

quimb.tensor.connect(t1, t2, ax1, ax2)[source]

Connect two tensors by setting a shared index for the specified dimensions. This is an inplace operation that will also affect any tensor networks viewing these tensors.

Parameters:
  • t1 (Tensor) – The first tensor.

  • t2 – The second tensor.

  • ax1 (int) – The dimension (axis) to connect on the first tensor.

  • ax2 (int) – The dimension (axis) to connect on the second tensor.

Examples

>>> X = rand_tensor([2, 3], inds=['a', 'b'])
>>> Y = rand_tensor([3, 4], inds=['c', 'd'])
>>> tn = (X | Y)  # is *view* of tensors (``&`` would copy them)
>>> print(tn)
TensorNetwork([
    Tensor(shape=(2, 3), inds=('a', 'b'), tags=()),
    Tensor(shape=(3, 4), inds=('c', 'd'), tags=()),
])
>>> connect(X, Y, 1, 0)  # modifies tensors *and* viewing TN
>>> print(tn)
TensorNetwork([
    Tensor(shape=(2, 3), inds=('a', '_e9021e0000002'), tags=()),
    Tensor(shape=(3, 4), inds=('_e9021e0000002', 'd'), tags=()),
])
>>>  tn ^ all
Tensor(shape=(2, 4), inds=('a', 'd'), tags=())
quimb.tensor.group_inds(t1, t2)[source]

Group bonds into left only, shared, and right only. If t1 or t2 are TensorNetwork objects, then only outer indices are considered.

Parameters:
Returns:

  • left_inds (list[str]) – Indices only in t1.

  • shared_inds (list[str]) – Indices in both t1 and t2.

  • right_inds (list[str]) – Indices only in t2.

quimb.tensor.new_bond(T1, T2, size=1, name=None, axis1=0, axis2=0)[source]

Inplace addition of a new bond between tensors T1 and T2. The size of the new bond can be specified, in which case the new array parts will be filled with zeros.

Parameters:
  • T1 (Tensor) – First tensor to modify.

  • T2 (Tensor) – Second tensor to modify.

  • size (int, optional) – Size of the new dimension.

  • name (str, optional) – Name for the new index.

  • axis1 (int, optional) – Position on the first tensor for the new dimension.

  • axis2 (int, optional) – Position on the second tensor for the new dimension.

class quimb.tensor.oset(it=())[source]

An ordered set which stores elements as the keys of dict (ordered as of python 3.6). ‘A few times’ slower than using a set directly for small sizes, but makes everything deterministic.

__slots__ = ('_d',)
pop[source]
classmethod _from_dict(d)[source]
classmethod from_dict(d)[source]

Public method makes sure to copy incoming dictionary.

copy()[source]
__deepcopy__(memo)[source]
add(k)[source]
discard(k)[source]
remove(k)[source]
clear()[source]
update(*others)[source]
union(*others)[source]
intersection_update(*others)[source]
intersection(*others)[source]
difference_update(*others)[source]
difference(*others)[source]
popleft()[source]
popright()[source]
__eq__(other)[source]

Return self==value.

__or__(other)[source]
__ior__(other)[source]
__and__(other)[source]
__iand__(other)[source]
__sub__(other)[source]
__isub__(other)[source]
__len__()[source]
__iter__()[source]
__contains__(x)[source]
__repr__()[source]

Return repr(self).

quimb.tensor.rand_uuid(base='')[source]

Return a guaranteed unique, shortish identifier, optional appended to base.

Examples

>>> rand_uuid()
'_2e1dae1b'
>>> rand_uuid('virt-bond')
'virt-bond_bf342e68'
quimb.tensor.tensor_balance_bond(t1, t2, smudge=1e-06)[source]

Gauge the bond between two tensors such that the norm of the ‘columns’ of the tensors on each side is the same for each index of the bond.

Parameters:
  • t1 (Tensor) – The first tensor, should share a single index with t2.

  • t2 (Tensor) – The second tensor, should share a single index with t1.

  • smudge (float, optional) – Avoid numerical issues by ‘smudging’ the correctional factor by this much - the gauging introduced is still exact.

quimb.tensor.tensor_canonize_bond(T1, T2, absorb='right', gauges=None, gauge_smudge=1e-06, **split_opts)[source]

Inplace ‘canonization’ of two tensors. This gauges the bond between the two such that T1 is isometric:

  |   |          |   |          |   |
--1---2--  =>  -->~R-2--  =>  -->~~~O--
  |   |          |   |          |   |
  .                ...
 <QR>              contract
Parameters:
  • T1 (Tensor) – The tensor to be isometrized.

  • T2 (Tensor) – The tensor to absorb the R-factor into.

  • absorb ({'right', 'left', 'both', None}, optional) – Which tensor to effectively absorb the singular values into.

  • split_opts – Supplied to tensor_split(), with modified defaults of method=='qr' and absorb='right'.

quimb.tensor.tensor_compress_bond(T1, T2, reduced=True, absorb='both', gauges=None, gauge_smudge=1e-06, info=None, **compress_opts)[source]

Inplace compress between the two single tensors. It follows the following steps (by default) to minimize the size of SVD performed:

a)│   │        b)│        │        c)│       │
━━●━━━●━━  ->  ━━>━━○━━○━━<━━  ->  ━━>━━━M━━━<━━
  │   │          │  ....  │          │       │
 <*> <*>          contract              <*>
 QR   LQ            -><-                SVD

          d)│            │        e)│   │
      ->  ━━>━━━ML──MR━━━<━━  ->  ━━●───●━━
            │....    ....│          │   │
          contract  contract          ^compressed bond
            -><-      -><-
Parameters:
  • T1 (Tensor) – The left tensor.

  • T2 (Tensor) – The right tensor.

  • max_bond (int or None, optional) – The maxmimum bond dimension.

  • cutoff (float, optional) – The singular value cutoff to use.

  • reduced ({True, False, "left", "right"}, optional) – Whether to perform the QR reduction as above or not. If False, contract both tensors together and perform a single SVD. If ‘left’ or ‘right’ then just perform the svd on the left or right tensor respectively. This can still be optimal if the other tensor is already isometric, i.e. the pair are right or left canonical respectively.

  • absorb ({'both', 'left', 'right', None}, optional) – Where to absorb the singular values after decomposition.

  • info (None or dict, optional) – A dict for returning extra information such as the singular values.

  • compress_opts – Supplied to tensor_split().

quimb.tensor.tensor_contract(*tensors, output_inds=None, optimize=None, get=None, backend=None, preserve_tensor=False, drop_tags=False, **contract_opts)[source]

Contract a collection of tensors into a scalar or tensor, automatically aligning their indices and computing an optimized contraction path. The output tensor will have the union of tags from the input tensors.

Parameters:
  • tensors (sequence of Tensor) – The tensors to contract.

  • output_inds (sequence of str) – The output indices. These can be inferred if the contraction has no ‘hyper’ indices, in which case the output indices are those that appear only once in the input indices, and ordered as they appear in the inputs. For hyper indices or a specific ordering, these must be supplied.

  • optimize ({None, str, path_like, PathOptimizer}, optional) –

    The contraction path optimization strategy to use.

    • None: use the default strategy,

    • str: use the preset strategy with the given name,

    • path_like: use this exact path,

    • cotengra.HyperOptimizer: find the contraction using this optimizer, supports slicing,

    • cotengra.ContractionTree: use this exact tree, supports slicing,

    • opt_einsum.PathOptimizer: find the path using this optimizer.

    Contraction with cotengra might be a bit more efficient but the main reason would be to handle sliced contraction automatically, as well as the fact that it uses autoray internally.

  • get (str, optional) –

    What to return. If:

    • None (the default) - return the resulting scalar or Tensor.

    • 'expression' - return a callbable expression that performs the contraction and operates on the raw arrays.

    • 'tree' - return the cotengra.ContractionTree describing the contraction.

    • 'path' - return the raw ‘path’ as a list of tuples.

    • 'symbol-map' - return the dict mapping indices to ‘symbols’ (single unicode letters) used internally by cotengra

    • 'path-info' - return the opt_einsum.PathInfo path object with detailed information such as flop cost. The symbol-map is also added to the quimb_symbol_map attribute.

  • backend ({'auto', 'numpy', 'jax', 'cupy', 'tensorflow', ...}, optional) – Which backend to use to perform the contraction. Supplied to cotengra.

  • preserve_tensor (bool, optional) – Whether to return a tensor regardless of whether the output object is a scalar (has no indices) or not.

  • drop_tags (bool, optional) – Whether to drop all tags from the output tensor. By default the output tensor will keep the union of all tags from the input tensors.

  • contract_opts – Passed to cotengra.array_contract.

Return type:

scalar or Tensor

quimb.tensor.tensor_direct_product(T1, T2, sum_inds=(), inplace=False)[source]

Direct product of two Tensors. Any axes included in sum_inds must be the same size and will be summed over rather than concatenated. Summing over contractions of TensorNetworks equates to contracting a TensorNetwork made of direct products of each set of tensors. I.e. (a1 @ b1) + (a2 @ b2) == (a1 (+) a2) @ (b1 (+) b2).

Parameters:
  • T1 (Tensor) – The first tensor.

  • T2 (Tensor) – The second tensor, with matching indices and dimensions to T1.

  • sum_inds (sequence of str, optional) – Axes to sum over rather than combine, e.g. physical indices when adding tensor networks.

  • inplace (bool, optional) – Whether to modify T1 inplace.

Returns:

Like T1, but with each dimension doubled in size if not in sum_inds.

Return type:

Tensor

quimb.tensor.tensor_fuse_squeeze(t1, t2, squeeze=True, gauges=None)[source]

If t1 and t2 share more than one bond fuse it, and if the size of the shared dimenion(s) is 1, squeeze it. Inplace operation.

quimb.tensor.tensor_network_distance(tnA, tnB, xAA=None, xAB=None, xBB=None, method='auto', normalized=False, **contract_opts)[source]

Compute the Frobenius norm distance between two tensor networks:

\[D(A, B) = | A - B |_{\mathrm{fro}} = \mathrm{Tr} [(A - B)^{\dagger}(A - B)]^{1/2} = ( \langle A | A \rangle - 2 \mathrm{Re} \langle A | B \rangle| + \langle B | B \rangle ) ^{1/2}\]

which should have matching outer indices. Note the default approach to computing the norm is precision limited to about eps**0.5 where eps is the precision of the data type, e.g. 1e-8 for float64. This is due to the subtraction in the above expression.

Parameters:
  • tnA (TensorNetwork or Tensor) – The first tensor network operator.

  • tnB (TensorNetwork or Tensor) – The second tensor network operator.

  • xAA (None or scalar) – The value of A.H @ A if you already know it (or it doesn’t matter).

  • xAB (None or scalar) – The value of A.H @ B if you already know it (or it doesn’t matter).

  • xBB (None or scalar) – The value of B.H @ B if you already know it (or it doesn’t matter).

  • method ({'auto', 'overlap', 'dense'}, optional) – How to compute the distance. If 'overlap', the default, the distance will be computed as the sum of overlaps, without explicitly forming the dense operators. If 'dense', the operators will be directly formed and the norm computed, which can be quicker when the exterior dimensions are small. If 'auto', the dense method will be used if the total operator (outer) size is <= 2**16.

  • normalized (bool, optional) – If True, then normalize the distance by the norm of the two operators, i.e. 2 * D(A, B) / (|A| + |B|). The resulting distance lies between 0 and 2 and is more useful for assessing convergence.

  • contract_opts – Supplied to contract().

Returns:

D

Return type:

float

quimb.tensor.tensor_network_fit_als(tn, tn_target, tags=None, steps=100, tol=1e-09, solver='solve', enforce_pos=False, pos_smudge=None, tnAA=None, tnAB=None, xBB=None, contract_optimize='greedy', inplace=False, progbar=False)[source]

Optimize the fit of tn with respect to tn_target using alternating least squares (ALS). This minimizes the norm of the difference between the two tensor networks, which must have matching outer indices, using overlaps.

Parameters:
  • tn (TensorNetwork) – The tensor network to fit.

  • tn_target (TensorNetwork) – The target tensor network to fit tn to.

  • tags (sequence of str, optional) – If supplied, only optimize tensors matching any of given tags.

  • steps (int, optional) – The maximum number of ALS steps.

  • tol (float, optional) – The target norm distance.

  • solver ({'solve', 'lstsq', ...}, optional) – The underlying driver function used to solve the local minimization, e.g. numpy.linalg.solve for 'solve' with numpy backend.

  • enforce_pos (bool, optional) – Whether to enforce positivity of the locally formed environments, which can be more stable.

  • pos_smudge (float, optional) – If enforcing positivity, the level below which to clip eigenvalues for make the local environment positive definite.

  • tnAA (TensorNetwork, optional) – If you have already formed the overlap tn.H & tn, maybe approximately, you can supply it here. The unconjugated layer should have tag '__KET__' and the conjugated layer '__BRA__'. Each tensor being optimized should have tag '__VAR{i}__'.

  • tnAB (TensorNetwork, optional) – If you have already formed the overlap tn_target.H & tn, maybe approximately, you can supply it here. Each tensor being optimized should have tag '__VAR{i}__'.

  • xBB (float, optional) – If you have already know, have computed tn_target.H @ tn_target, or it doesn’t matter, you can supply the value here.

  • contract_optimize (str, optional) – The contraction path optimized used to contract the local environments. Note 'greedy' is the default in order to maximize shared work.

  • inplace (bool, optional) – Update tn in place.

  • progbar (bool, optional) – Show a live progress bar of the fitting process.

Return type:

TensorNetwork

quimb.tensor.tensor_network_fit_autodiff(tn, tn_target, steps=1000, tol=1e-09, autodiff_backend='autograd', contract_optimize='auto-hq', distance_method='auto', inplace=False, progbar=False, **kwargs)[source]

Optimize the fit of tn with respect to tn_target using automatic differentation. This minimizes the norm of the difference between the two tensor networks, which must have matching outer indices, using overlaps.

Parameters:
  • tn (TensorNetwork) – The tensor network to fit.

  • tn_target (TensorNetwork) – The target tensor network to fit tn to.

  • steps (int, optional) – The maximum number of autodiff steps.

  • tol (float, optional) – The target norm distance.

  • autodiff_backend (str, optional) – Which backend library to use to perform the gradient computation.

  • contract_optimize (str, optional) – The contraction path optimized used to contract the overlaps.

  • distance_method ({'auto', 'dense', 'overlap'}, optional) – Supplied to tensor_network_distance(), controls how the distance is computed.

  • inplace (bool, optional) – Update tn in place.

  • progbar (bool, optional) – Show a live progress bar of the fitting process.

  • kwargs – Passed to TNOptimizer.

quimb.tensor.tensor_network_gate_inds(self, G, inds, contract=False, tags=None, info=None, inplace=False, **compress_opts)[source]

Apply the ‘gate’ G to indices inds, propagating them to the outside, as if applying G @ x.

Parameters:
  • G (array_ike) – The gate array to apply, should match or be factorable into the shape (*phys_dims, *phys_dims).

  • inds (str or sequence or str,) – The index or indices to apply the gate to.

  • contract ({False, True, 'split', 'reduce-split', 'split-gate',) –

    ‘swap-split-gate’, ‘auto-split-gate’}, optional How to apply the gate:

    • False: gate is added to network lazily and nothing is contracted, tensor network structure is thus not maintained.

    • True: gate is contracted eagerly with all tensors involved, tensor network structure is thus only maintained if gate acts on a single site only.

    • ’split’: contract all involved tensors then split the result back into two.

    • ’reduce-split’: factor the two physical indices into ‘R-factors’ using QR decompositions on the original site tensors, then contract the gate, split it and reabsorb each side. Much cheaper than 'split'.

    • ’split-gate’: lazily add the gate as with False, but split the gate tensor spatially.

    • ’swap-split-gate’: lazily add the gate as with False, but split the gate as if an extra SWAP has been applied.

    • ’auto-split-gate’: lazily add the gate as with False, but maybe apply one of the above options depending on whether they result in a rank reduction.

    The named methods are relevant for two site gates only, for single site gates they use the contract=True option which also maintains the structure of the TN. See below for a pictorial description of each method.

  • tags (str or sequence of str, optional) – Tags to add to the new gate tensor.

  • info (None or dict, optional) – Used to store extra optional information such as the singular values if not absorbed.

  • inplace (bool, optional) – Whether to perform the gate operation inplace on the tensor network or not.

  • compress_opts – Supplied to tensor_split() for any contract methods that involve splitting. Ignored otherwise.

Returns:

G_tn

Return type:

TensorNetwork

Notes

The contract options look like the following (for two site gates).

contract=False:

  .   .  <- inds
  │   │
  GGGGG
  │╱  │╱
──●───●──
 ╱   ╱

contract=True:

  │╱  │╱
──GGGGG──
 ╱   ╱

contract='split':

  │╱  │╱          │╱  │╱
──GGGGG──  ==>  ──G┄┄┄G──
 ╱   ╱           ╱   ╱
  <SVD>

contract='reduce-split':

  │   │             │ │
  GGGGG             GGG               │ │
  │╱  │╱   ==>     ╱│ │  ╱   ==>     ╱│ │  ╱          │╱  │╱
──●───●──       ──>─●─●─<──       ──>─GGG─<──  ==>  ──G┄┄┄G──
 ╱   ╱           ╱     ╱           ╱     ╱           ╱   ╱
<QR> <LQ>                            <SVD>

For one site gates when one of these ‘split’ methods is supplied contract=True is assumed.

contract='split-gate':

  │   │ <SVD>
  G~~~G
  │╱  │╱
──●───●──
 ╱   ╱

contract='swap-split-gate':

   ╲ ╱
    ╳
   ╱ ╲ <SVD>
  G~~~G
  │╱  │╱
──●───●──
 ╱   ╱

contract='auto-split-gate' chooses between the above two and False, depending on whether either results in a lower rank.

quimb.tensor.tensor_network_sum(tnA, tnB, inplace=False)[source]

Sum of two tensor networks, whose indices should match exactly, using direct products.

Parameters:
Returns:

The sum of tnA and tnB, with increased bond dimensions.

Return type:

TensorNetwork

quimb.tensor.tensor_split(T, left_inds, method='svd', get=None, absorb='both', max_bond=None, cutoff=1e-10, cutoff_mode='rel', renorm=None, ltags=None, rtags=None, stags=None, bond_ind=None, right_inds=None)[source]

Decompose this tensor into two tensors.

Parameters:
  • T (Tensor or TNLinearOperator) – The tensor (network) to split.

  • left_inds (str or sequence of str) – The index or sequence of inds, which T should already have, to split to the ‘left’. You can supply None here if you supply right_inds instead.

  • method (str, optional) –

    How to split the tensor, only some methods allow bond truncation:

    • 'svd': full SVD, allows truncation.

    • 'eig': full SVD via eigendecomp, allows truncation.

    • 'lu': full LU decomposition, allows truncation. This method favors tensor sparsity but is not rank optimal.

    • 'svds': iterative svd, allows truncation.

    • 'isvd': iterative svd using interpolative methods, allows truncation.

    • 'rsvd' : randomized iterative svd with truncation.

    • 'eigh': full eigen-decomposition, tensor must he hermitian.

    • 'eigsh': iterative eigen-decomposition, tensor must be hermitian.

    • 'qr': full QR decomposition.

    • 'lq': full LR decomposition.

    • 'polar_right': full polar decomposition as A = UP.

    • 'polar_left': full polar decomposition as A = PU.

    • 'cholesky': full cholesky decomposition, tensor must be positive.

  • get ({None, 'arrays', 'tensors', 'values'}) –

    If given, what to return instead of a TN describing the split:

    • None: a tensor network of the two (or three) tensors.

    • 'arrays': the raw data arrays as a tuple (l, r) or (l, s, r) depending on absorb.

    • 'tensors ': the new tensors as a tuple (Tl, Tr) or (Tl, Ts, Tr) depending on absorb.

    • 'values': only compute and return the singular values s.

  • absorb ({'both', 'left', 'right', None}, optional) – Whether to absorb the singular values into both, the left, or the right unitary matrix respectively, or neither. If neither (absorb=None) then the singular values will be returned separately in their own 1D tensor or array. In that case if get=None the tensor network returned will have a hyperedge corresponding to the new bond index connecting three tensors. If get='tensors' or get='arrays' then a tuple like (left, s, right) is returned.

  • max_bond (None or int) – If integer, the maximum number of singular values to keep, regardless of cutoff.

  • cutoff (float, optional) – The threshold below which to discard singular values, only applies to rank revealing methods (not QR, LQ, or cholesky).

  • cutoff_mode ({'sum2', 'rel', 'abs', 'rsum2'}) –

    Method with which to apply the cutoff threshold:

    • 'rel': values less than cutoff * s[0] discarded.

    • 'abs': values less than cutoff discarded.

    • 'sum2': sum squared of values discarded must be < cutoff.

    • 'rsum2': sum squared of values discarded must be less than cutoff times the total sum of squared values.

    • 'sum1': sum values discarded must be < cutoff.

    • 'rsum1': sum of values discarded must be less than cutoff times the total sum of values.

  • renorm ({None, bool, or int}, optional) – Whether to renormalize the kept singular values, assuming the bond has a canonical environment, corresponding to maintaining the frobenius or nuclear norm. If None (the default) then this is automatically turned on only for cutoff_method in {'sum2', 'rsum2', 'sum1', 'rsum1'} with method in {'svd', 'eig', 'eigh'}.

  • ltags (sequence of str, optional) – Add these new tags to the left tensor.

  • rtags (sequence of str, optional) – Add these new tags to the right tensor.

  • stags (sequence of str, optional) – Add these new tags to the singular value tensor.

  • bond_ind (str, optional) – Explicitly name the new bond, else a random one will be generated.

  • right_inds (sequence of str, optional) – Explicitly give the right indices, otherwise they will be worked out. This is a minor performance feature.

Returns:

Depending on if get is None, 'tensors', 'arrays', or 'values'. In the first three cases, if absorb is set, then the returned objects correspond to (left, right) whereas if absorb=None the returned objects correspond to (left, singular_values, right).

Return type:

TensorNetwork or tuple[Tensor] or tuple[array] or 1D-array

class quimb.tensor.DMRG(ham, bond_dims, cutoffs=1e-09, bsz=2, which='SA', p0=None)[source]

Density Matrix Renormalization Group variational groundstate search. Some initialising arguments act as defaults, but can be overidden with each solve or sweep. See get_default_opts() for the list of advanced options initialized in the opts attribute.

Parameters:
  • ham (MatrixProductOperator) – The hamiltonian in MPO form.

  • bond_dims (int or sequence of ints.) – The bond-dimension of the MPS to optimize. If bsz > 1, then this corresponds to the maximum bond dimension when splitting the effective local groundstate. If a sequence is supplied then successive sweeps iterate through, then repeate the final value. E.g. [16, 32, 64] -> (16, 32, 64, 64, 64, ...).

  • cutoffs (dict-like) – The cutoff threshold(s) to use when compressing. If a sequence is supplied then successive sweeps iterate through, then repeate the final value. E.g. [1e-5, 1e-7, 1e-9] -> (1e-5, 1e-7, 1e-9, 1e-9, ...).

  • bsz ({1, 2}) – Number of sites to optimize for locally i.e. DMRG1 or DMRG2.

  • which ({'SA', 'LA'}, optional) – Whether to search for smallest or largest real part eigenvectors.

  • p0 (MatrixProductState, optional) – If given, use as the initial state.

state

The current, optimized state.

Type:

MatrixProductState

energy

The current most optimized energy.

Type:

float

energies

The total energy after each sweep.

Type:

list of float

local_energies

The local energies per sweep: local_energies[i, j] contains the local energy found at the jth step of the (i+1)th sweep.

Type:

list of list of float

total_energies

The total energies per sweep: local_energies[i, j] contains the total energy after the jth step of the (i+1)th sweep.

Type:

list of list of float

opts

Advanced options e.g. relating to the inner eigensolve or compression, see get_default_opts().

Type:

dict

(bond_sizes_ham)

If cyclic, the sizes of the energy environement transfer matrix bonds, per segment, per sweep.

Type:

list[list[int]]

(bond_sizes_norm)

If cyclic, the sizes of the norm environement transfer matrix bonds, per segment, per sweep.

Type:

list[list[int]]

property energy
property state
_set_bond_dim_seq(bond_dims)[source]
_set_cutoff_seq(cutoffs)[source]
_canonize_after_1site_update(direction, i)[source]

Compress a site having updated it. Also serves to move the orthogonality center along.

_eigs(A, B=None, v0=None)[source]

Find single eigenpair, using all the internal settings.

print_energy_info(Heff=None, loc_gs=None)[source]
print_norm_info(i=None)[source]
form_local_ops(i, dims, lix, uix)[source]

Construct the effective Hamiltonian, and if needed, norm.

post_check(i, Neff, loc_gs, loc_en, loc_gs_old)[source]

Perform some checks on the output of the local eigensolve.

_update_local_state_1site(i, direction, **compress_opts)[source]

Find the single site effective tensor groundstate of:

>->->->->-/|\-<-<-<-<-<-<-<-<          /|\       <-- uix
| | | | |  |  | | | | | | | |         / | \
H-H-H-H-H--H--H-H-H-H-H-H-H-H   =    L--H--R
| | | | | i|  | | | | | | | |         \i| /
>->->->->-\|/-<-<-<-<-<-<-<-<          \|/       <-- lix

And insert it back into the states k and b, and thus TN_energy.

_update_local_state_2site(i, direction, **compress_opts)[source]

Find the 2-site effective tensor groundstate of:

>->->->->-/| |\-<-<-<-<-<-<-<-<          /| |\
| | | | |  | |  | | | | | | | |         / | | \
H-H-H-H-H--H-H--H-H-H-H-H-H-H-H   =    L--H-H--R
| | | | |  i i+1| | | | | | | |         \ | | /
>->->->->-\| |/-<-<-<-<-<-<-<-<          \| |/
                                     i i+1

And insert it back into the states k and b, and thus TN_energy.

_update_local_state(i, **update_opts)[source]

Move envs to site i and dispatch to the correct local updater.

sweep(direction, canonize=True, verbosity=0, **update_opts)[source]

Perform a sweep of optimizations, either rightwards:

  optimize -->
    ...
>->-o-<-<-<-<-<-<-<-<-<-<-<-<-<
| | | | | | | | | | | | | | | |
H-H-H-H-H-H-H-H-H-H-H-H-H-H-H-H
| | | | | | | | | | | | | | | |
>->-o-<-<-<-<-<-<-<-<-<-<-<-<-<

or leftwards (direction=’L’):

                <-- optimize
                          ...
>->->->->->->->->->->->->-o-<-<
| | | | | | | | | | | | | | | |
H-H-H-H-H-H-H-H-H-H-H-H-H-H-H-H
| | | | | | | | | | | | | | | |
>->->->->->->->->->->->->-o-<-<

After the sweep the state is left or right canonized respectively.

Parameters:
  • direction ({'R', 'L'}) – Sweep from left to right (->) or right to left (<-) respectively.

  • canonize (bool, optional) – Canonize the state first, not needed if doing alternate sweeps.

  • verbosity ({0, 1, 2}, optional) – Show a progress bar for the sweep.

  • update_opts – Supplied to self._update_local_state.

sweep_right(canonize=True, verbosity=0, **update_opts)[source]
sweep_left(canonize=True, verbosity=0, **update_opts)[source]
_print_pre_sweep(i, direction, max_bond, cutoff, verbosity=0)[source]

Print this before each sweep.

_compute_post_sweep()[source]

Compute this after each sweep.

_print_post_sweep(converged, verbosity=0)[source]

Print this after each sweep.

_check_convergence(tol)[source]

By default check the absolute change in energy.

solve(tol=0.0001, bond_dims=None, cutoffs=None, sweep_sequence=None, max_sweeps=10, verbosity=0, suppress_warnings=True)[source]

Solve the system with a sequence of sweeps, up to a certain absolute tolerance in the energy or maximum number of sweeps.

Parameters:
  • tol (float, optional) – The absolute tolerance to converge energy to.

  • bond_dims (int or sequence of int) – Overide the initial/current bond_dim sequence.

  • cutoffs (float of sequence of float) – Overide the initial/current cutoff sequence.

  • sweep_sequence (str, optional) – String made of ‘L’ and ‘R’ defining the sweep sequence, e.g ‘RRL’. The sequence will be repeated until max_sweeps is reached.

  • max_sweeps (int, optional) – The maximum number of sweeps to perform.

  • verbosity ({0, 1, 2}, optional) – How much information to print about progress.

  • suppress_warnings (bool, optional) – Whether to suppress warnings about non-convergence, usually due to the intentional low accuracy of the inner eigensolve.

Returns:

converged – Whether the algorithm has converged to tol yet.

Return type:

bool

class quimb.tensor.DMRG1(ham, which='SA', bond_dims=None, cutoffs=1e-08, p0=None)[source]

Bases: DMRG

Simple alias of one site DMRG.

class quimb.tensor.DMRG2(ham, which='SA', bond_dims=None, cutoffs=1e-08, p0=None)[source]

Bases: DMRG

Simple alias of two site DMRG.

class quimb.tensor.DMRGX(ham, p0, bond_dims, cutoffs=1e-08, bsz=1)[source]

Bases: DMRG

Class implmenting DMRG-X [1], whereby local effective energy eigenstates are chosen to maximise overlap with the previous step’s state, leading to convergence on an mid-spectrum eigenstate of the full hamiltonian, as long as it is perturbatively close to the original state.

[1] Khemani, V., Pollmann, F. & Sondhi, S. L. Obtaining Highly Excited Eigenstates of Many-Body Localized Hamiltonians by the Density Matrix Renormalization Group Approach. Phys. Rev. Lett. 116, 247204 (2016).

Parameters:
k

The current, optimized state.

Type:

MatrixProductState

energies

The list of energies after each sweep.

Type:

list of float

property variance
form_local_ops(i, dims, lix, uix)[source]

Construct the effective Hamiltonian, and if needed, norm.

_update_local_state_1site_dmrgx(i, direction, **compress_opts)[source]

Like _update_local_state, but re-insert all eigenvectors, then choose the one with best overlap with eff_ovlp.

_update_local_state(i, **update_opts)[source]

Move envs to site i and dispatch to the correct local updater.

sweep(direction, canonize=True, verbosity=0, **update_opts)[source]

Perform a sweep of the algorithm.

Parameters:
  • direction ({'R', 'L'}) – Sweep from left to right (->) or right to left (<-) respectively.

  • canonize (bool, optional) – Canonize the state first, not needed if doing alternate sweeps.

  • verbosity ({0, 1, 2}, optional) – Show a progress bar for the sweep.

  • update_opts – Supplied to self._update_local_state.

_compute_post_sweep()[source]

Compute this after each sweep.

_print_post_sweep(converged, verbosity=0)[source]

Print this after each sweep.

_check_convergence(tol)[source]

By default check the absolute change in energy.

class quimb.tensor.MovingEnvironment(tn, begin, bsz, *, cyclic=False, segment_callbacks=None, ssz=0.5, eps=1e-08, method='isvd', max_bond=-1, norm=False)[source]

Helper class for efficiently moving the effective ‘environment’ of a few sites in a 1D tensor network. E.g. for begin='left', bsz=2, this initializes the right environments like so:

n - 1: ●─●─●─     ─●─●─●
       │ │ │       │ │ │
       H─H─H─ ... ─H─H─H
       │ │ │       │ │ │
       ●─●─●─     ─●─●─●

n - 2: ●─●─●─     ─●─●─╮
       │ │ │       │ │ ●
       H─H─H─ ... ─H─H─H
       │ │ │       │ │ ●
       ●─●─●─     ─●─●─╯

n - 3: ●─●─●─     ─●─╮
       │ │ │       │ ●●
       H─H─H─ ... ─H─HH
       │ │ │       │ ●●
       ●─●─●─     ─●─╯

...

0    : ●─●─╮
       │ │ ●●   ●●●
       H─H─HH...HHH
       │ │ ●●   ●●●
       ●─●─╯

which can then be used to efficiently generate the left environments as each site is updated. For example if bsz=2 and the environements have been shifted many sites into the middle, then MovingEnvironment() returns something like:

     <---> bsz sites
    ╭─●─●─╮
●●●●● │ │ ●●●●●●●
HHHHH─H─H─HHHHHHH
●●●●● │ │ ●●●●●●●
    ╰─●─●─╯
0 ... i i+1 ... n-1

For periodic systems MovingEnvironment approximates the ‘long way round’ transfer matrices. E.g consider replacing segment B (to arbitrary precision) with an SVD:

╭───────────────────────────────────────────────╮
╰─A─A─A─A─A─A─A─A─A─A─A─A─B─B─B─B─B─B─B─B─B─B─B─╯
  │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │           ==>
╭─A─A─A─A─A─A─A─A─A─A─A─A─B─B─B─B─B─B─B─B─B─B─B─╮
╰───────────────────────────────────────────────╯

╭┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄╮
┊   ╭─A─A─A─A─A─A─A─A─A─A─A─A─╮   ┊                       ==>
╰┄<BL │ │ │ │ │ │ │ │ │ │ │ │ BR>┄╯
    ╰─A─A─A─A─A─A─A─A─A─A─A─A─╯
      ^                     ^
segment_start          segment_stop - 1

╭┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄╮
┊   ╭─A─A─╮                        ┊                      ==>
╰┄<BL │ │ AAAAAAAAAAAAAAAAAAAAABR>┄╯
    ╰─A─A─╯
      ...
    <-bsz->

╭┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄╮
┊               ╭─A─A─╮           ┊                       ==>
╰~<BLAAAAAAAAAAA  │ │ AAAAAAAABR>~╯
                ╰─A─A─╯
                  i i+1
     -----sweep--------->

Can then contract and store left and right environments for efficient sweeping just as in non-periodic case. If the segment is long enough (50+) sites, often only 1 singular value is needed, and thus the efficiency is the same as for OBC.

Parameters:
  • tn (TensorNetwork) – The 1D tensor network, should be closed, i.e. an overlap of some sort.

  • begin ({'left', 'right'}) – Which side to start at and sweep from.

  • bsz (int) – The number of sites that form the the ‘non-environment’, e.g. 2 for DMRG2.

  • ssz (float or int, optional) – The size of the segment to use, if float, the proportion. Default: 1/2.

  • eps (float, optional) – The tolerance to approximate the transfer matrix with. See replace_with_svd().

  • cyclic (bool, optional) – Whether this is a periodic MovingEnvironment.

  • segment_callbacks (sequence of callable, optional) – Functions with signature callback(start, stop, self.begin), to be called every time a new segment is initialized.

  • method ({'isvd', 'svds', ...}, optional) – How to perform the transfer matrix compression if PBC. See replace_with_svd().

  • max_bond (, optional) – If > 0, the maximum bond of the compressed transfer matrix.

  • norm (bool, optional) – If True, treat this MovingEnvironment as the state overlap, which enables a few extra checks.

Notes

Does not necessarily need to be an operator overlap tensor network. Useful for any kind of sweep where only local tensor updates are being made. Note that only the current site is completely up-to-date and can be modified with changes meant to propagate.

site_tag(i)[source]
init_segment(begin, start, stop)[source]

Initialize the environments in range(start, stop) so that one can start sweeping from the side defined by begin.

init_non_segment(start, stop)[source]

Compress and label the effective env not in range(start, stop) if cyclic, else just add some dummy left and right end pieces.

move_right()[source]
move_left()[source]
move_to(i)[source]

Move this effective environment to site i.

__call__()[source]

Get the current environment.

class quimb.tensor.MERA(L, uni=None, iso=None, phys_dim=2, dangle=False, site_ind_id='k{}', site_tag_id='I{}', **tn_opts)[source]

Bases: quimb.tensor.tensor_1d.TensorNetwork1DVector, quimb.tensor.tensor_1d.TensorNetwork1D, quimb.tensor.tensor_core.TensorNetwork

The Multi-scale Entanglement Renormalization Ansatz (MERA) state:

    ...     ...     ...     ...     ...     ...
 |       |       |       |       |       |       |
ISO     ISO     ISO     ISO     ISO     ISO     ISO   :
   \   /   \   /   \   /   \   /   \   /   \   /      : '_LAYER1'
    UNI     UNI     UNI     UNI     UNI     UNI       :
   /   \   /   \   /   \   /   \   /   \   /   \
O ISO ISO ISO ISO ISO ISO ISO ISO ISO ISO ISO ISO I   :
| | | | | | | | | | | | | | | | | | | | | | | | | |   : '_LAYER0'
UNI UNI UNI UNI UNI UNI UNI UNI UNI UNI UNI UNI UNI   :
| | | | | | | | | | | | | | | | | | | | | | | | | |  <-- phys_dim
0 1 2 3 4 ....                            ... L-2 L-1
Parameters:
  • L (int) – The number of phyiscal sites. Shoule be a power of 2.

  • uni (array or sequence of arrays of shape (d, d, d, d).) – The unitary operator(s). These will be cycled over and placed from bottom left to top right in diagram above.

  • iso (array or sequence of arrays of shape (d, d, d)) – The isometry operator(s). These will be cycled over and placed from bottom left to top right in diagram above.

  • phys_dim (int, optional) – The dimension of the local hilbert space.

  • dangle (bool, optional) – Whether to leave a dangling index on the final isometry, in order to maintain perfect scale invariance, else join the final unitaries just with an indentity.

_EXTRA_PROPS = ('_site_ind_id', '_site_tag_id', 'cyclic', '_L')
_CONTRACT_STRUCTURED = False
classmethod rand(L, max_bond=None, phys_dim=2, dtype=float, **mera_opts)[source]
classmethod rand_invar(L, phys_dim=2, dtype=float, **mera_opts)[source]

Generate a random translational and scale invariant MERA.