quimb.tensor¶
Tensor and tensor network functionality.
Submodules¶
- quimb.tensor.array_ops
- quimb.tensor.belief_propagation
- quimb.tensor.circuit
- quimb.tensor.circuit_gen
- quimb.tensor.contraction
- quimb.tensor.decomp
- quimb.tensor.drawing
- quimb.tensor.fitting
- quimb.tensor.geometry
- quimb.tensor.interface
- quimb.tensor.networking
- quimb.tensor.optimize
- quimb.tensor.tensor_1d
- quimb.tensor.tensor_1d_compress
- quimb.tensor.tensor_1d_tebd
- quimb.tensor.tensor_2d
- quimb.tensor.tensor_2d_compress
- quimb.tensor.tensor_2d_tebd
- quimb.tensor.tensor_3d
- quimb.tensor.tensor_3d_tebd
- quimb.tensor.tensor_approx_spectral
- quimb.tensor.tensor_arbgeom
- quimb.tensor.tensor_arbgeom_compress
- quimb.tensor.tensor_arbgeom_tebd
- quimb.tensor.tensor_builder
- quimb.tensor.tensor_core
- quimb.tensor.tensor_dmrg
- quimb.tensor.tensor_mera
Attributes¶
Classes¶
Class for simulating quantum circuits using tensor networks. The class |
|
Quantum circuit simulation keeping the state in full dense form. |
|
Quantum circuit simulation keeping the state always in a MPS form. If |
|
Quantum circuit simulation keeping the state always in an MPS form, but |
|
A simple class for storing the details of a quantum circuit gate. |
|
Globally optimize tensors within a tensor network with respect to any |
|
Mimics other 1D tensor network structures, but really just keeps the |
|
Initialise a matrix product operator, with auto labelling and tagging. |
|
Initialise a matrix product state, with auto labelling and tagging. |
|
A 1D tensor network super-operator class: |
|
Base class for tensor networks with a one-dimensional structure. |
|
A 1D tensor network linear operator like: |
|
Class implementing Time Evolving Block Decimation (TEBD) [1]. |
|
An simple interacting hamiltonian object used, for instance, in TEBD. |
|
Projected Entangled Pair Operator object: |
|
Projected Entangled Pair States object (2D): |
|
Mixin class for tensor networks with a square lattice two-dimensional |
|
Generic class for performing two dimensional time evolving block |
|
Implements the 'Full Update' version of 2D imaginary time evolution, |
|
A 2D Hamiltonian represented as local terms. This combines all two site |
|
A simple subclass of |
|
Projected Entangled Pair States object (3D). |
|
Mixin class for tensor networks with a cubic lattice three-dimensional |
|
Representation of a local hamiltonian defined on a general graph. This |
|
Representation of a local hamiltonian defined on a general graph. This |
|
Simple update for arbitrary geometry hamiltonians. |
|
Generic class for performing time evolving block decimation on an |
|
Class for easily building custom spin hamiltonians in MPO or LocalHam1D |
|
A |
|
A tensor whose data array is lazily generated from a set of parameters |
|
A labelled, tagged n-dimensional array. The index labels are used |
|
A collection of (as yet uncontracted) Tensors. |
|
An ordered set which stores elements as the keys of dict (ordered as of |
|
Density Matrix Renormalization Group variational groundstate search. |
|
Simple alias of one site |
|
Simple alias of two site |
|
Class implmenting DMRG-X [1], whereby local effective energy eigenstates |
|
Helper class for efficiently moving the effective 'environment' of a |
|
The Multi-scale Entanglement Renormalization Ansatz (MERA) state: |
Functions¶
|
Generate a random all-to-all quantum circuit. |
|
A 1D circuit ansatz with odd and even layers of entangling |
|
A 1D circuit ansatz with randomly place entangling gates interleaved |
|
A 1D circuit ansatz with forward and backward layers of entangling |
|
Generate the QAOA circuit for weighted graph described by |
|
|
|
A context manager to temporarily set the default backend used for tensor |
|
A context manager to temporarily set the default contraction strategy |
Get the default backend used for tensor contractions, via 'cotengra'. |
|
Get the default contraction strategy - the option supplied as |
|
Get the default backend used for tensor network linear operators, via |
|
|
Turn input and output indices of any sort into a single 'equation' |
|
Set the default backend used for tensor contractions, via 'cotengra'. |
|
Get the default contraction strategy - the option supplied as |
|
Set the default backend used for tensor network linear operators, via |
|
A context manager to temporarily set the default backend used for tensor |
|
Return the graph edges of a finite 1D chain lattice. |
|
Return the graph edges of a finite 2D hexagonal lattice. There are two |
|
Return the graph edges of a finite 2D kagome lattice. There are |
|
Return the graph edges of a finite 2D square lattice. The nodes |
|
Return the graph edges of a finite 2D triangular lattice. There is a |
|
Return the graph edges of a finite 2D triangular lattice tiled in a |
|
Return the graph edges of a finite 3D cubic lattice. The nodes |
|
Return the graph edges of a finite 3D diamond lattice. There are |
|
Return the graph edges of a finite 3D diamond lattice tiled in a cubic |
|
Return the graph edges of a finite 3D pyorchlore lattice. There are |
|
Return a random tree with |
|
Take a tensor or tensor network like object and return a skeleton needed |
|
Take a skeleton of a tensor or tensor network like object and a pytree |
|
Compute the expectation of several 1D TNs, using transfer matrix |
|
Act with the gate |
|
Take a tensor network superoperator and act with it on a |
|
Check that |
|
Compress a 1D-like tensor network using the specified method. |
|
Convenience function for tiling pairs of bond coordinates on a 2D |
|
Convenience function for tiling pairs of bond coordinates on a 3D |
|
Align an arbitrary number of tensor networks in a stack-like geometry: |
|
Apply the operator (has upper and lower site inds) represented by tensor |
|
Apply a general a general tensor network representing an operator (has |
|
Generate an edge coloring for the graph given by |
|
Build a matrix product state representation of the COPY tensor. |
|
Hyper tensor network representation of the 2D classical ising model |
|
Hyper tensor network representation of the 3D classical ising model |
|
Build a hyper tensor network representation of a classical ising model |
|
Create a CP-decomposition structured hyper tensor network state from a |
|
Create a hyper tensor network with a tensor on each bond and a hyper |
|
Given a list of clauses, create a hyper tensor network, with a single |
|
Create a hyper tensor network from a '.cnf' or '.wcnf' file - i.e. a |
|
Create a random, possibly hyper, tensor network, with a mix of normal |
|
Create a random k-SAT instance encoded as a hyper tensor network. |
|
Heisenberg Hamiltonian in MPO form. |
|
Ising Hamiltonian in MPO form. |
|
The many-body-localized spin hamiltonian in MPO form. |
|
XY-Hamiltonian in MPO form. |
|
Generate an identity MPO of size |
|
Return an identity matrix operator with the same physical index and |
|
Return an MPO of bond dimension 1 representing the product of raw |
|
Generate a random matrix product state. |
|
Generate a random hermitian matrix product operator. |
|
Generate a zeros MPO of size |
|
Return a zeros matrix product operator with the same physical index and |
|
A computational basis state in Matrix Product State form. |
|
Build the chi=2 OBC MPS representation of the GHZ state. |
|
Generate the neel state in Matrix Product State form. |
|
Generate a product state in MatrixProductState form, i,e, |
|
Generate a random computation basis state, like '01101001010'. |
|
Generate a random matrix product state. |
|
A product state for sampling tensor network traces. Seen as a vector it |
|
Build the chi=2 OBC MPS representation of the W state. |
|
The all-zeros MPS state, of given bond-dimension. |
|
The tensor network representation of the 2D classical ising model |
|
Build a 2D 'corner double line' (CDL) tensor network. Each plaquette |
Construct a (triangular) '2D' tensor network representation of the |
|
|
A scalar 2D lattice tensor network initialized with empty tensors. |
|
A scalar 2D lattice tensor network with tensors filled by a function. |
|
A random scalar 2D lattice tensor network. |
|
|
|
Create a random 2D lattice tensor network where every tensor is |
|
A scalar 2D lattice tensor network with every element set to |
|
Tensor network representation of the 3D classical ising model |
|
|
|
A scalar 3D lattice tensor network initialized with empty tensors. |
|
A scalar 3D lattice tensor network with tensors filled by a function. |
|
A random scalar 3D lattice tensor network. |
|
|
|
A scalar 2D lattice tensor network with every element set to |
|
Build a regular tensor network representation of a classical ising model |
|
Make a tensor network from sequence of graph edges that counts the |
|
Create a tensor network from a sequence of edges defining a graph, |
|
Create a tensor network from a sequence of edges defining a graph, |
|
Create a random tensor network with geometry defined from a sequence |
|
Create a tensor network from a sequence of edges defining a graph, |
|
A computational basis state in general tensor network form. |
|
A product state in general tensor network form. |
|
|
|
Create a tensor network with the same outer indices as |
|
Create a random regular tensor network. |
|
Create a random tree tensor network. |
|
Parse a DIMACS style 'cnf' file into a list of clauses, and possibly a |
|
Convert |
|
Convert |
|
Heisenberg Hamiltonian in |
|
Ising Hamiltonian in |
|
The many-body-localized spin hamiltonian in |
|
XY-Hamiltonian in |
|
Heisenberg Hamiltonian in |
|
Ising Hamiltonian in |
|
Heisenberg Hamiltonian in |
|
Heisenberg Hamiltonian in |
|
Generate a random tensor with specified shape and inds, and randomly |
|
Generate a random tensor with specified shape and inds. |
|
Create a random k-SAT instance. |
|
Get the tensor representing the COPY operation with dimension size |
|
Getting any indices connecting the Tensor(s) or TensorNetwork(s) |
|
Get the size of the bonds linking tensors or tensor networks |
|
Connect two tensors by setting a shared index for the specified |
|
Group bonds into left only, shared, and right only. If |
|
Inplace addition of a new bond between tensors |
|
Return a guaranteed unique, shortish identifier, optional appended |
|
Gauge the bond between two tensors such that the norm of the 'columns' |
|
Inplace 'canonization' of two tensors. This gauges the bond between |
|
Inplace compress between the two single tensors. It follows the |
|
Contract a collection of tensors into a scalar or tensor, automatically |
|
Direct product of two Tensors. Any axes included in |
|
If |
|
Compute the Frobenius norm distance between two tensor networks: |
|
Optimize the fit of |
|
Optimize the fit of |
|
Apply the 'gate' |
|
Sum of two tensor networks, whose indices should match exactly, using |
|
Decompose this tensor into two tensors. |
Package Contents¶
- 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', tag_gate_numbers=True, gate_tag_id='GATE_{}', tag_gate_rounds=True, round_tag_id='ROUND_{}', tag_gate_labels=True, bra_site_ind_id='b{}', dtype=None, to_backend=None, convert_eager=False)[source]¶
Class for simulating quantum circuits using tensor networks. The class keeps a list of
Gate
objects in sync with a tensor network representing the current state of the circuit.- 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 tagPSI0
added.gate_opts (dict_like, optional) – Default keyword arguments to supply to each
gate_TN_1D()
call during the circuit.gate_contract (str, optional) – Shortcut for setting the default ‘contract’ option in gate_opts.
gate_propagate_tags (str, optional) – Shortcut for setting the default ‘propagate_tags’ option in gate_opts.
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.
tag_gate_numbers (bool, optional) – Whether to tag each gate tensor with its number in the circuit, like
"GATE_{g}"
. This is required for updating the circuit parameters.gate_tag_id (str, optional) – The format string for tagging each gate tensor, by default e.g.
"GATE_{g}"
.tag_gate_rounds (bool, optional) – Whether to tag each gate tensor with its number in the circuit, like
"ROUND_{r}"
.round_tag_id (str, optional) – The format string for tagging each round of gates, by default e.g.
"ROUND_{r}"
.tag_gate_labels (bool, optional) – Whether to tag each gate tensor with its gate type label, e.g.
{"X_1/2", "ISWAP", "CCX", ...}
..bra_site_ind_id (str, optional) – Use this to label ‘bra’ site indices when creating certain (mostly internal) intermediate tensor networks.
dtype (str, optional) – A default dtype to perform calculations in. Depending on convert_eager, this is enforced after circuit construction and simplification (the default for exact simulation), or eagerly to the initial state and as gates are applied (the default for MPS simulation).
to_backend (callable, optional) – If given, apply this function to both the initial state arrays and to every gate as it is applied.
convert_eager (bool, optional) – Whether to eagerly perform dtype casting and application of to_backend as gates are supplied, or wait until after the necessary TNs for a particular task such as sampling are formed and simplified. Deferred conversion (convert_eager=False) is the default mode for full contraction.
- psi¶
The current circuit wavefunction as a tensor network.
- Type:
- uni¶
The current circuit unitary operator as a tensor network.
- Type:
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
See also
- tag_gate_numbers = True¶
- tag_gate_rounds = True¶
- tag_gate_labels = True¶
- dtype = None¶
- to_backend = None¶
- convert_eager = False¶
- _backend_gate_cache¶
- gate_opts¶
- _gates = []¶
- _ket_site_ind_id¶
- _bra_site_ind_id = 'b{}'¶
- _gate_tag_id = 'GATE_{}'¶
- _round_tag_id = 'ROUND_{}'¶
- _sample_n_gates = -1¶
- _storage¶
- _sampled_conditionals¶
- set_params(params)[source]¶
Set the parameters of the circuit.
- Parameters:
params (dict`) – A dictionary mapping gate numbers to the new parameters.
- classmethod from_qsim_str(contents, progbar=False, **circuit_opts)[source]¶
Generate a
Circuit
instance from a ‘qsim’ string.
- classmethod from_qsim_file(fname, progbar=False, **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, progbar=False, **circuit_opts)[source]¶
Generate a
Circuit
instance from a ‘qsim’ url.
- classmethod from_openqasm2_str(contents, progbar=False, **circuit_opts)[source]¶
Generate a
Circuit
instance from an OpenQASM 2.0 string.
- classmethod from_openqasm2_file(fname, progbar=False, **circuit_opts)[source]¶
Generate a
Circuit
instance from an OpenQASM 2.0 file.
- classmethod from_openqasm2_url(url, progbar=False, **circuit_opts)[source]¶
Generate a
Circuit
instance from an OpenQASM 2.0 url.
- classmethod from_gates(gates, N=None, progbar=False, **kwargs)[source]¶
Generate a
Circuit
instance from a sequence of gates.
- property gates¶
- property num_gates¶
- _apply_gate(gate, tags=None, **gate_opts)[source]¶
Apply a
Gate
to thisCircuit
. This is the main method that all calls to apply a gate should go through.
- apply_gate(gate_id, *gate_args, params=None, qubits=None, controls=None, gate_round=None, parametrize=None, **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 casegate_args
should be supplied with(*params, *qubits)
.A raw array, in which case
gate_args
should be supplied with(*qubits,)
.
gate_round (int, optional) – The gate round. If
gate_id
is integer-like, will also be taken from here, with thengate_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, controls=None, gate_round=None, **gate_opts)[source]¶
Apply the raw array
U
as a gate on qubits inwhere
. It will be assumed to be unitary for the sake of computing reverse lightcones.
- apply_gates(gates, progbar=False, **gate_opts)[source]¶
Apply a sequence of gates to this tensor network quantum circuit.
- Parameters:
gates (Sequence[Gate] or Sequence[Tuple]) – The sequence of gates to apply.
gate_opts – Supplied to
apply_gate()
.
- 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]¶
- property psi¶
Tensor network representation of the wavefunction.
- get_uni(transposed=False)[source]¶
Tensor network representation of the unitary operator (i.e. with the initial state removed).
- property uni¶
- 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
.
- 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:
- 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:
- 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 withinwhere
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:
- amplitude(b, optimize='auto-hq', simplify_sequence='ADCRS', simplify_atol=1e-12, simplify_equalize_norms=True, backend=None, dtype=None, 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 tocotengra
.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=True, optimize='auto-hq', dtype=None, 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 tocotengra
.dtype (str, optional) – Data type to cast the TN to before contraction.
- Return type:
- partial_trace(keep, optimize='auto-hq', simplify_sequence='ADCRS', simplify_atol=1e-12, simplify_equalize_norms=True, backend=None, dtype=None, 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 tocotengra
.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=True, backend=None, dtype=None, rehearse=False)[source]¶
Compute the a single expectation value of operator
G
, acting on siteswhere
, 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 tocotengra
.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:
- 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 infix
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 tocotengra
.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.
- _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 ofqubits
.
- _group_order(order, group_size=1)[source]¶
Take the qubit ordering
order
and batch it in groups of sizegroup_size
, sorting the qubits (for caching reasons) within each group.
- get_qubit_distances(method='dijkstra', alpha=2)[source]¶
Get a nested dictionary of qubit distances. This is computed from a graph representing qubit interactions. The graph has an edge between qubits if they are acted on by the same gate, and the distance-weight of the edge is exponentially small in the number of gates between them.
- Parameters:
method ({'dijkstra', 'resistance'}, optional) – The method to use to compute the qubit distances. See
networkx.all_pairs_dijkstra_path_length()
andnetworkx.resistance_distance()
.alpha (float, optional) – The distance weight between qubits is
alpha**(num_gates - 1 )
.
- Returns:
The distance between each pair of qubits, accessed like
distances[q1][q2]
. If two qubits are not connected, the distance is missing.- Return type:
- reordered_gates_dfs_clustered()[source]¶
Get the gates reordered by a depth first search traversal of the multi-qubit gate graph that greedily selects successive gates which are ‘close’ in graph distance, and shifts single qubit gates to be adjacent to multi-qubit gates where possible.
- sample(C, qubits=None, order=None, group_size=10, max_marginal_storage=2**20, seed=None, optimize='auto-hq', backend=None, dtype='complex64', simplify_sequence='ADCRS', simplify_atol=1e-06, simplify_equalize_norms=True)[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 ofqubits
.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 tocotengra
.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=10, result=None, optimize='auto-hq', simplify_sequence='ADCRS', simplify_atol=1e-06, simplify_equalize_norms=True, 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:
- sample_chaotic(C, marginal_qubits, fix=None, max_marginal_storage=2**20, seed=None, optimize='auto-hq', backend=None, dtype='complex64', simplify_sequence='ADCRS', simplify_atol=1e-06, simplify_equalize_norms=True)[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]
.fix (None or dict[int, str], optional) – Measurement results on other qubits to fix. These will be randomly sampled if
fix
is not given or a qubit is missing.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 tocotengra
.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=True, 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:
- get_gate_by_gate_circuits(group_size=10)[source]¶
Get a sequence of circuits by partitioning the gates into groups such circuit i + 1 acts on at most
group_size
new qubits compared to circuit i.- Parameters:
group_size (int, optional) – The maximum number of new qubits that can be acted on by a circuit compared to its predecessor.
- Returns:
A sequence of dicts, each with keys
'circuit'
and'where'
, where the former is aCircuit
and the latter the tuple of new qubits that it acts on comparaed to the previous circuit.- Return type:
Sequence[dict]
- sample_gate_by_gate(C, group_size=10, seed=None, max_marginal_storage=2**20, optimize='auto-hq', backend=None, dtype='complex64', simplify_sequence='ADCRS', simplify_atol=1e-06, simplify_equalize_norms=True)[source]¶
Sample this circuit using the gate-by-gate method, where we ‘evolve’ a result bitstring by sequentially including more and more gates, at each step updating the result by computing a full conditional marginal. See “How to simulate quantum measurement without computing marginals” by Sergey Bravyi, David Gosset, Yinchen Liu (https://arxiv.org/abs/2112.08499). The overall complexity of this is guaranteed to be similar to that of computing a single amplitude which can be much better than the naive “qubit-by-qubit” (.sample) method. However, it requires evaluting a number of tensor networks that scales linearly with the number of gates which can offset any practical advantages for shallow circuits for example.
- Parameters:
C (int) – The number of samples to generate.
group_size (int, optional) – The maximum number of qubits that can be acted on by a circuit compared to its predecessor. This will be the dimension of the marginal computed at each step.
seed (None or int, optional) – A random seed, passed to
numpy.random.seed
if given.max_marginal_storage (int, optional) – The total cumulative number of marginal probabilites to cache, once this is exceeded caching will be turned off.
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 tocotengra
.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, 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.
- Yields:
str
- sample_gate_by_gate_rehearse(group_size=10, optimize='auto-hq', dtype='complex64', simplify_sequence='ADCRS', simplify_atol=1e-06, simplify_equalize_norms=True, rehearse=True, progbar=False)[source]¶
Perform the preparations and contraction tree findings for
sample_gate_by_gate()
, caching various intermedidate objects, but don’t perform the main contractions.- Parameters:
group_size (int, optional) – The maximum number of qubits that can be acted on by a circuit compared to its predecessor. This will be the dimension of the marginal computed at each step.
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()
.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 (True or "tn", optional) – If
True
, generate and cache the simplified tensor network and contraction tree but don’t actually perform the contraction. If “tn”, only generate the simplified tensor networks.
- Return type:
Sequence[dict] or Sequence[TensorNetwork]
- to_dense(reverse=False, optimize='auto-hq', simplify_sequence='R', simplify_atol=1e-12, simplify_equalize_norms=True, 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 tocotengra
.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:
- 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 fromto_dense()
, then callingsimulate_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:
- 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=True, 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 taggedGATE_{i}
corresponding to this circuit (e.g. fromcirc.psi
orcirc.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.
- class quimb.tensor.CircuitDense(N=None, psi0=None, gate_opts=None, gate_contract=True, tags=None, convert_eager=True, **circuit_opts)[source]¶
Bases:
Circuit
Quantum circuit simulation keeping the state in full dense form.
- property psi¶
Tensor network representation of the wavefunction.
- property uni¶
- class quimb.tensor.CircuitMPS(N=None, *, psi0=None, max_bond=None, cutoff=1e-10, gate_opts=None, gate_contract='auto-mps', dtype=None, to_backend=None, convert_eager=True, **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.
- Parameters:
N (int, optional) – The number of qubits in the circuit.
psi0 (TensorNetwork1DVector, optional) – The initial state, assumed to be
|00000....0>
if not given. The state is always copied and the tagPSI0
added.max_bond (int, optional) – The maximum bond dimension to truncate to when applying gates, if any. This is simply a shortcut for setting
gate_opts['max_bond']
.cutoff (float, optional) – The singular value cutoff to use when truncating the state. This is simply a shortcut for setting
gate_opts['cutoff']
.gate_opts (dict, optional) – Default options to pass to each gate, for example, “max_bond” and “cutoff” etc.
gate_contract (str, optional) –
The default method for applying gates. Relevant MPS options are:
'auto-mps'
: automatically choose a method that maintains the MPS form (default). This uses'swap+split'
for 2-qubit gates and'nonlocal'
for 3+ qubit gates.'swap+split'
: swap nonlocal qubits to be next to each other, before applying the gate, then swapping them back'nonlocal'
: turn the gate into a potentially nonlocal (sub) MPO and apply it directly. Seetensor_network_1d_compress()
.
dtype (str, optional) – The data type to use for the state tensor.
to_backend (callable, optional) – A function to convert tensor data to a particular backend.
convert_eager (bool, optional) – Whether to eagerly perform dtype casting and application of to_backend as gates are supplied, or wait until after the necessary TNs for a particular task such as sampling are formed and simplified. Eager conversion (convert_eager=True) is the default mode for MPS simulation, unlike full contraction.
circuit_opts – Supplied to
Circuit
.
- psi¶
The current state of the circuit, always in MPS form.
- Type:
Examples
Create a circuit object that always uses the “nonlocal” method for contracting in gates, and the “dm” compression method within that, using a large cutoff and maximum bond dimension:
circ = qtn.CircuitMPS( N=56, gate_opts=dict( contract="nonlocal", method="dm", max_bond=1024, cutoff=1e-3, ) )
- apply_gates(gates, progbar=False, **gate_opts)[source]¶
Apply a sequence of gates to this tensor network quantum circuit.
- Parameters:
gates (Sequence[Gate] or Sequence[Tuple]) – The sequence of gates to apply.
gate_opts – Supplied to
apply_gate()
.
- property psi¶
Tensor network representation of the wavefunction.
- property uni¶
- get_psi_reverse_lightcone(where, keep_psi0=False)[source]¶
Override
get_psi_reverse_lightcone
as for an MPS the lightcone is not meaningful.
- sample(C, seed=None, dtype=None, *, qubits=None, order=None, group_size=None, max_marginal_storage=None, optimize=None, backend=None, simplify_sequence=None, simplify_atol=None, simplify_equalize_norms=None)[source]¶
Sample the MPS circuit
C
times.
- fidelity_estimate()[source]¶
Estimate the fidelity of the current state based on its norm, which tracks how much the state has been truncated:
\[\tilde{F} = \left| \langle \psi | \psi \rangle \right|^2 \approx \left|\langle \psi_\mathrm{ideal} | \psi \rangle\right|^2\]See also
- error_estimate()[source]¶
Estimate the error in the current state based on the norm of the discarded part of the state:
\[\epsilon = 1 - \tilde{F}\]See also
- local_expectation(G, where, normalized=False, dtype=None, *, simplify_sequence=None, simplify_atol=None, simplify_equalize_norms=None, backend=None, rehearse=None, **contract_opts)[source]¶
Compute the local expectation value of a local operator at
where
(via forming the reduced density matrix). Note this moves the orthogonality around inplace, and records it in info.- Parameters:
- Return type:
- class quimb.tensor.CircuitPermMPS(N=None, psi0=None, gate_opts=None, gate_contract='swap+split', **circuit_opts)[source]¶
Bases:
CircuitMPS
Quantum circuit simulation keeping the state always in an MPS form, but lazily tracking the qubit ordering rather than ‘swapping back’ qubits after applying non-local gates. This can be useful for circuits with no expectation of locality. The qubit ordering is always tracked in the attribute
qubits
. Thepsi
attribute returns the TN with the sites reindexed and retagged according to the current qubit ordering, meaning it is no longer an MPS. Use circ.get_psi_unordered() to get the unpermuted MPS and use circ.qubits to get the current qubit ordering if you prefer.- qubits¶
- _apply_gate(gate, tags=None, **gate_opts)[source]¶
Apply a
Gate
to thisCircuit
. This is the main method that all calls to apply a gate should go through.
- get_psi_unordered()[source]¶
Return the MPS representing the state but without reordering the sites.
- property psi¶
Tensor network representation of the wavefunction.
- class quimb.tensor.Gate(label, params, qubits=None, controls=None, round=None, parametrize=False)[source]¶
A simple class for storing the details of a quantum circuit gate.
- Parameters:
label (str) – The name or ‘identifier’ of the gate.
params (Iterable[float]) – The parameters of the gate.
qubits (Iterable[int], optional) – Which qubits the gate acts on.
controls (Iterable[int], optional) – Which qubits are the controls.
round (int, optional) – If given, which round or layer the gate is part of.
parametrize (bool, optional) – Whether the gate will correspond to a parametrized tensor.
- __slots__ = ('_label', '_params', '_qubits', '_controls', '_round', '_parametrize', '_tag', '_special',...¶
- _label¶
- _params¶
- _round = 0¶
- _parametrize = False¶
- _tag¶
- _special¶
- _constant¶
- _array = None¶
- property label¶
- property params¶
- property qubits¶
- property total_qubit_count¶
- property controls¶
- property round¶
- property special¶
- property parametrize¶
- property tag¶
- build_array()[source]¶
Build the array representation of the gate. For controlled gates this excludes the control qubits.
- property array¶
- quimb.tensor.circ_a2a_rand(n, depth, seed=None, gate2='cz', **circuit_opts)[source]¶
Generate a random all-to-all quantum circuit.
- Parameters:
- Return type:
- 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:
See also
- 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:
- 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:
See also
- 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
. Notegate_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
tocotengra
. 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
tocotengra
.
- 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.
See also
set_tensor_linop_backend
,set_contract_backend
,get_contract_backend
,TNLinearOperator
- 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:
- 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
tocotengra
.
- 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.
See also
get_tensor_linop_backend
,set_contract_backend
,get_contract_backend
,TNLinearOperator
- 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_1d_chain(L, cyclic=False)[source]¶
Return the graph edges of a finite 1D chain lattice.
- 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)
fors
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:
- 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)
fors
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:
- 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:
- 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:
- 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)
fors
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:
- 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:
- 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)
fors
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:
- 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)
fors
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:
- 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)
fors
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:
- 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 seenetworkx.random_labeled_tree
).
- 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
, andget_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
, andget_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 asloss_constants
andloss_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 (seeexecutor
).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
(unlikeloss_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
orshared_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
ordevice='cpu'
.
- progbar = True¶
- tags = None¶
- constant_tags = None¶
- _autodiff_backend = 'AUTO'¶
- _multiloss¶
- norm_fn = None¶
- loss_constants¶
- loss_kwargs¶
- property bounds¶
- property optimizer¶
The underlying optimizer that works with the vectorized functions.
- callback = None¶
- 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.
- property d¶
- property nevals¶
The number of gradient evaluations.
- get_tn_opt()[source]¶
Extract the optimized tensor network, this is a three part process:
inject the current optimized vector into the target tensor network or pytree,
run it through
norm_fn
,drop any tags used to identify variables.
- Returns:
tn_opt
- Return type:
- optimize(n, tol=None, jac=True, hessp=False, optlib='scipy', **options)[source]¶
Run the optimizer for
n
function evaluations, using by defaultscipy.optimize.minimize()
as the driver for the vectorized computation. Supplying the gradient and hessian vector product is controlled by thejac
andhessp
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:
- 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 performsnhop
local optimization each withn
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:
- 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, usingnlopt
as the backend library to run the optimization. Whether the gradient is computed depends on whichoptimizer
is selected, see valid options at https://nlopt.readthedocs.io/en/latest/NLopt_Algorithms/.The following scipy
optimizer
options are automatically translated to the correspondingnlopt
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:
- optimize_ipopt(n, tol=None, **options)[source]¶
Run the optimizer for
n
function evaluations, usingipopt
as the backend library to run the optimization via the python packagecyipopt
.- Parameters:
n (int) – The maximum number of iterations for the optimizer.
- Returns:
tn_opt
- Return type:
- optimize_nevergrad(n)[source]¶
Run the optimizer for
n
function evaluations, usingnevergrad
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:
- 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 atxscale_linthresh
.xscale_linthresh (int, optional) – The threshold for the change from linear to logarithmic scale, if
xscale
is"symlog"
. Default is20
.zoom (None or int, optional) – If not
None
, show an inset plot of the lastzoom
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')¶
- _L¶
- _site_ind_id = 'k{}'¶
- _site_tag_id = 'I{}'¶
- class quimb.tensor.MatrixProductOperator(arrays, *, sites=None, L=None, shape='lrud', tags=None, upper_ind_id='k{}', lower_ind_id='b{}', site_tag_id='I{}', **tn_opts)[source]¶
Bases:
TensorNetwork1DOperator
,TensorNetwork1DFlat
Initialise a matrix product operator, with auto labelling and tagging.
- Parameters:
arrays (sequence of arrays) – The tensor arrays to form into a MPO.
sites (sequence of int, optional) – Construct the MPO on these sites only. If not given, enumerate from zero. Should be monotonically increasing and match
arrays
.L (int, optional) – The number of sites the MPO should be defined on. If not given, this is taken as the max
sites
value plus one (i.e.g the number of arrays ifsites
is not given).shape (str, optional) – String specifying layout of the tensors. E.g. ‘lrud’ (the default) indicates the shape corresponds left-bond, right-bond, ‘up’ physical index, ‘down’ physical index. End tensors have either ‘l’ or ‘r’ dropped from the string.
tags (str or sequence of str, optional) – Global tags to attach to all tensors.
upper_ind_id (str) – A string specifiying how to label the upper physical site indices. Should contain a
'{}'
placeholder. It is used to generate the actual indices like:map(upper_ind_id.format, range(len(arrays)))
.lower_ind_id (str) – A string specifiying how to label the lower physical site indices. Should contain a
'{}'
placeholder. It is used to generate the actual indices like:map(lower_ind_id.format, range(len(arrays)))
.site_tag_id (str) – A string specifiying how to tag the tensors at each site. Should contain a
'{}'
placeholder. It is used to generate the actual tags like:map(site_tag_id.format, range(len(arrays)))
.
- _EXTRA_PROPS = ('_site_tag_id', '_upper_ind_id', '_lower_ind_id', 'cyclic', '_L')¶
- _L = None¶
- _upper_ind_id = 'k{}'¶
- _lower_ind_id = 'b{}'¶
- _site_tag_id = 'I{}'¶
- cyclic¶
- classmethod from_fill_fn(fill_fn, L, bond_dim, phys_dim=2, sites=None, cyclic=False, shape='lrud', tags=None, upper_ind_id='k{}', lower_ind_id='b{}', site_tag_id='I{}')[source]¶
Create an MPO by supplying a ‘filling’ function to generate the data for each site.
- Parameters:
fill_fn (callable) – A function with signature
fill_fn(shape : tuple[int]) -> array_like
.L (int) – The number of sites.
bond_dim (int) – The bond dimension.
phys_dim (int or Sequence[int], optional) – The physical dimension(s) of each site, if a sequence it will be cycled over.
sites (None or sequence of int, optional) – Construct the MPO on these sites only. If not given, enumerate from zero.
cyclic (bool, optional) – Whether the MPO should be cyclic (periodic).
shape (str, optional) – String specifying layout of the tensors. E.g. ‘lrud’ (the default) indicates the shape corresponds left-bond, right-bond, ‘up’ physical index, ‘down’ physical index. End tensors have either ‘l’ or ‘r’ dropped from the string.
tags (str or sequence of str, optional) – Global tags to attach to all tensors.
upper_ind_id (str) – A string specifiying how to label the upper physical site indices. Should contain a
'{}'
placeholder.lower_ind_id (str) – A string specifiying how to label the lower physical site indices. Should contain a
'{}'
placeholder.site_tag_id (str, optional) – How to tag the physical sites. Should contain a
'{}'
placeholder.
- Return type:
- classmethod from_dense(A, dims=2, sites=None, L=None, tags=None, site_tag_id='I{}', upper_ind_id='k{}', lower_ind_id='b{}', **split_opts)[source]¶
Build an MPO from a raw dense matrix.
- Parameters:
A (array) – The dense operator, it should be reshapeable to
(*dims, *dims)
.dims (int, sequence of int, optional) – The physical subdimensions of the operator. If any integer, assume all sites have the same dimension. If a sequence, the dimension of each site. Default is 2.
sites (sequence of int, optional) – The sites to place the operator on. If None, will place it on first len(dims) sites.
L (int, optional) – The total number of sites in the MPO, if the operator represents only a subset.
tags (str or sequence of str, optional) – Global tags to attach to all tensors.
site_tag_id (str, optional) – The string to use to label the site tags.
upper_ind_id (str, optional) – The string to use to label the upper physical indices.
lower_ind_id (str, optional) – The string to use to label the lower physical indices.
split_opts – Supplied to
tensor_split()
.
- Return type:
- fill_empty_sites(mode='full', phys_dim=None, fill_array=None, inplace=False)[source]¶
Fill any empty sites of this MPO with identity tensors, adding size 1 bonds or draping existing bonds where necessary such that the resulting tensor has nearest neighbor bonds only.
- Parameters:
mode ({'full', 'minimal'}, optional) – Whether to fill in all sites, including at either end, or simply the minimal range covering the min to max current sites present.
phys_dim (int, optional) – The physical dimension of the identity tensors to add. If not specified, will use the upper physical dimension of the first present site.
fill_array (array, optional) – The array to use for the identity tensors. If not specified, will use the identity array of the same dtype as the first present site.
inplace (bool, optional) – Whether to perform the operation inplace.
- Returns:
The modified MPO.
- Return type:
- apply(other, compress=False, **compress_opts)[source]¶
Act with this MPO on another MPO or MPS, such that the resulting object has the same tensor network structure/indices as
other
.For an MPS:
| | | | | | | | | | | | | | | | | | self: 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:
other (MatrixProductOperator or MatrixProductState) – The object to act on.
compress (bool, optional) – Whether to compress the resulting object.
compress_opts – Supplied to
TensorNetwork1DFlat.compress()
.
- Return type:
- permute_arrays(shape='lrud')[source]¶
Permute the indices of each tensor in this MPO to match
shape
. This doesn’t change how the overall object interacts with other tensor networks but may be useful for extracting the underlying arrays consistently. This is an inplace operation.- Parameters:
shape (str, optional) – A permutation of
'lrud'
specifying the desired order of the left, right, upper and lower (down) indices respectively.
- class quimb.tensor.MatrixProductState(arrays, *, sites=None, L=None, shape='lrp', tags=None, site_ind_id='k{}', site_tag_id='I{}', **tn_opts)[source]¶
Bases:
TensorNetwork1DVector
,TensorNetwork1DFlat
Initialise a matrix product state, with auto labelling and tagging.
- Parameters:
arrays (sequence of arrays) – The tensor arrays to form into a MPS.
sites (sequence of int, optional) – Construct the MPO on these sites only. If not given, enumerate from zero. Should be monotonically increasing and match
arrays
.L (int, optional) – The number of sites the MPO should be defined on. If not given, this is taken as the max
sites
value plus one (i.e.g the number of arrays ifsites
is not given).shape (str, optional) – String specifying layout of the tensors. E.g. ‘lrp’ (the default) indicates the shape corresponds left-bond, right-bond, physical index. End tensors have either ‘l’ or ‘r’ dropped from the string.
tags (str or sequence of str, optional) – Global tags to attach to all tensors.
site_ind_id (str) – A string specifiying how to label the physical site indices. Should contain a
'{}'
placeholder. It is used to generate the actual indices like:map(site_ind_id.format, range(len(arrays)))
.site_tag_id (str) – A string specifiying how to tag the tensors at each site. Should contain a
'{}'
placeholder. It is used to generate the actual tags like:map(site_tag_id.format, range(len(arrays)))
.
- _EXTRA_PROPS = ('_site_tag_id', '_site_ind_id', 'cyclic', '_L')¶
- _L¶
- _site_ind_id = 'k{}'¶
- _site_tag_id = 'I{}'¶
- cyclic¶
- classmethod from_fill_fn(fill_fn, L, bond_dim, phys_dim=2, sites=None, cyclic=False, shape='lrp', site_ind_id='k{}', site_tag_id='I{}', tags=None)[source]¶
Create an MPS by supplying a ‘filling’ function to generate the data for each site.
- Parameters:
fill_fn (callable) – A function with signature
fill_fn(shape : tuple[int]) -> array_like
.L (int) – The number of sites.
bond_dim (int) – The bond dimension.
phys_dim (int or Sequence[int], optional) – The physical dimension(s) of each site, if a sequence it will be cycled over.
sites (None or sequence of int, optional) – Construct the MPS on these sites only. If not given, enumerate from zero.
cyclic (bool, optional) – Whether the MPS should be cyclic (periodic).
shape (str, optional) – What specific order to layout the indices in, should be a sequence of
'l'
,'r'
, and'p'
, corresponding to left, right, and physical indices respectively.site_ind_id (str, optional) – How to label the physical site indices.
site_tag_id (str, optional) – How to tag the physical sites.
tags (str or sequence of str, optional) – Global tags to attach to all tensors.
- Return type:
- classmethod from_dense(psi, dims=2, tags=None, site_ind_id='k{}', site_tag_id='I{}', **split_opts)[source]¶
Create a
MatrixProductState
directly from a dense vector- Parameters:
psi (array_like) – The dense state to convert to MPS from.
dims (int or sequence of int) – Physical subsystem dimensions of each site. If a single int, all sites have this same dimension, by default, 2.
tags (str or sequence of str, optional) – Global tags to attach to all tensors.
site_ind_id (str, optional) – How to index the physical sites, see
MatrixProductState
.site_tag_id (str, optional) – How to tag the physical sites, see
MatrixProductState
.split_opts – Supplied to
tensor_split()
to in order to partition the dense vector into tensors.absorb='left'
is set by default, to ensure the compression is canonical / optimal.
- Return type:
Examples
>>> dims = [2, 2, 2, 2, 2, 2] >>> psi = rand_ket(prod(dims)) >>> mps = MatrixProductState.from_dense(psi, dims) >>> mps.show() 2 4 8 4 2 o-o-o-o-o-o | | | | | |
- 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 precisioneps
in order to be efficient. Inplace.- Parameters:
bra (MatrixProductState, optional) – If given, normalize this MPS with the same factor.
eps (float, optional) – If cyclic, precision to approximation transfer matrix with. Default: 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:
- 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 dimensiond
.where ((int, int)) – Indices of the sites to apply the gate to.
compress_opts – Supplied to
tensor_split()
.
See also
gate
,gate_with_auto_swap
- swap_sites_with_compress(i, j, info=None, inplace=False, **compress_opts)[source]¶
Swap sites
i
andj
by contracting, then splitting with the physical indices swapped. If the sites are not adjacent, this will happen multiple times.- Parameters:
i (int) – The first site to swap.
j (int) – The second site to swap.
cur_orthog (int, sequence of int, or 'calc') – If known, the current orthogonality center.
info (dict, optional) – If supplied, will be used to infer and store various extra information. Currently, the key “cur_orthog” is used to store the current orthogonality center. Its input value can be
"calc"
, a single site, or a pair of sites representing the min/max range, inclusive. It will be updated to the actual range after.inplace (bond, optional) – Perform the swaps inplace.
compress_opts – Supplied to
tensor_split()
.
- swap_site_to(i, f, info=None, inplace=False, **compress_opts)[source]¶
Swap site
i
to sitef
, compressing the bond after each swap:i f 0 1 2 3 4 5 6 7 8 9 0 1 2 4 5 6 7 3 8 9 o-o-o-x-o-o-o-o-o-o >->->->->->->-x-<-< | | | | | | | | | | -> | | | | | | | | | |
- Parameters:
i (int) – The site to move.
f (int) – The new location for site
i
.info (dict, optional) – If supplied, will be used to infer and store various extra information. Currently, the key “cur_orthog” is used to store the current orthogonality center. Its input value can be
"calc"
, a single site, or a pair of sites representing the min/max range, inclusive. It will be updated to the actual range after.inplace (bond, optional) – Perform the swaps inplace.
compress_opts – Supplied to
tensor_split()
.
- gate_with_auto_swap(G, where, info=None, swap_back=True, inplace=False, **compress_opts)[source]¶
Perform a two site gate on this MPS by, if necessary, swapping and compressing the sites until they are adjacent, using
gate_split
, then unswapping the sites back to their original position.- Parameters:
G (array) – The gate, with shape
(d**2, d**2)
for physical dimensiond
.where ((int, int)) – Indices of the sites to apply the gate to.
info (dict, optional) – If supplied, will be used to infer and store various extra information. Currently, the key “cur_orthog” is used to store the current orthogonality center. Its input value can be
"calc"
, a single site, or a pair of sites representing the min/max range, inclusive. It will be updated to the actual range after.swap_back (bool, optional) – Whether to swap the sites back to their original position after applying the gate. If not, for sites
i < j
, the sitej
will remain swapped toi + 1
, and sites betweeni + 1
andj
will be shifted one place up.inplace (bond, optional) – Perform the swaps inplace.
compress_opts – Supplied to
tensor_split()
.
See also
gate
,gate_split
- gate_with_submpo(submpo, where=None, method='direct', transpose=False, info=None, inplace=False, inplace_mpo=False, **compress_opts)[source]¶
Apply an MPO, which only acts on a subset of sites, to this MPS, compressing the MPS with the MPO only on the minimal set of sites covering where, keeping the MPS form:
│ │ │ A───A─A │ │ │ -> │ │ │ │ │ │ │ │ >─>─O━O━O━O─<─< │ │ │ │ │ │ │ │ o─o─o─o─o─o─o─o
- Parameters:
submpo (MatrixProductOperator) – The MPO to apply.
where (sequence of int, optional) – The range of sites the MPO acts on, will be inferred from the support of the MPO if not given.
method ({'direct", 'dm', 'zipup', 'zipup-first', 'fit'}, optional) – The compression method to use.
transpose (bool, optional) – Whether to transpose the MPO before applying it. By default the lower inds of the MPO are contracted with the MPS, if transposed the upper inds are contracted.
info (dict, optional) – If supplied, will be used to infer and store various extra information. Currently, the key “cur_orthog” is used to store the current orthogonality center. Its input value can be
"calc"
, a single site, or a pair of sites representing the min/max range, inclusive. It will be updated to the actual range after.inplace (bool, optional) – Whether to perform the application and compression inplace.
compress_opts – Supplied to
tensor_network_1d_compress()
.
- Return type:
- gate_with_mpo(mpo, method='direct', transpose=False, inplace=False, inplace_mpo=False, **compress_opts)[source]¶
Gate this MPS with an MPO and compress the result with one of various methods back to MPS form:
│ │ │ │ │ │ │ │ A─A─A─A─A─A─A─A │ │ │ │ │ │ │ │ -> │ │ │ │ │ │ │ │ O━O━O━O━O━O━O━O │ │ │ │ │ │ │ │ o─o─o─o─o─o─o─o
- Parameters:
mpo (MatrixProductOperator) – The MPO to apply.
max_bond (int, optional) – A maximum bond dimension to keep when compressing.
cutoff (float, optional) – A singular value cutoff to use when compressing.
method ({'direct", 'dm', 'zipup', 'zipup-first', 'fit', ...}, optional) – The compression method to use.
transpose (bool, optional) – Whether to transpose the MPO before applying it. By default the lower inds of the MPO are contracted with the MPS, if transposed the upper inds are contracted.
inplace (bool, optional) – Whether to perform the compression inplace.
inplace_mpo (bool, optional) – Whether the modify the MPO in place, a minor performance gain.
compress_opts – Other options supplied to
tensor_network_1d_compress()
.
- Return type:
- gate_nonlocal(G, where, dims=None, method='direct', info=None, inplace=False, **compress_opts)[source]¶
Apply a potentially non-local gate to this MPS by first decomposing it into an MPO, then compressing the MPS with MPO only on the minimal set of sites covering where.
- Parameters:
G (array_like) – The gate to apply.
where (sequence of int) – The sites to apply the gate to.
max_bond (int, optional) – A maximum bond dimension to keep when compressing.
cutoff (float, optional) – A singular value cutoff to use when compressing.
dims (sequence of int, optional) – The factorized dimensions of the gate
G
, which should match the physical dimensions of the sites it acts on. Calculated if not supplied. If a single int, all sites are assumed to have this same dimension.method ({'direct", 'dm', 'zipup', 'zipup-first', 'fit', ...}, optional) – The compression method to use.
info (dict, optional) – If supplied, will be used to infer and store various extra information. Currently, the key “cur_orthog” is used to store the current orthogonality center. Its input value can be
"calc"
, a single site, or a pair of sites representing the min/max range, inclusive. It will be updated to the actual range after.inplace (bool, optional) – Whether to perform the compression inplace.
compress_opts – Supplied to
tensor_network_1d_compress()
.
- Return type:
- flip(inplace=False)[source]¶
Reverse the order of the sites in the MPS, such that site
i
is now at siteL - i - 1
.
- schmidt_values(i, info=None, method='svd')[source]¶
Find the schmidt values associated with the bipartition of this MPS between sites on either site of
i
. In other words,i
is the number of sites in the left hand partition:....L.... i 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.
- entropy(i, info=None, method='svd')[source]¶
The entropy of bipartition between the left block of
i
sites and the rest.
- schmidt_gap(i, info=None, method='svd')[source]¶
The schmidt gap of bipartition between the left block of
i
sites and the rest.
- partial_trace_to_mpo(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:
- partial_trace(*_, **__)[source]¶
Partially trace this tensor network state, keeping only the sites in
keep
, using compressed contraction.- Parameters:
keep (iterable of hashable) – The sites to keep.
max_bond (int) – The maximum bond dimensions to use while compressed contracting.
optimize (str or PathOptimizer, optional) – The contraction path optimizer to use, should specifically generate contractions paths designed for compressed contraction.
flatten ({False, True, 'all'}, optional) – Whether to force ‘flattening’ (contracting all physical indices) of the tensor network before contraction, whilst this makes the TN generally more complex to contract, the accuracy is usually improved. If
'all'
also flatten the tensors inkeep
.reduce (bool, optional) – Whether to first ‘pull’ the physical indices off their respective tensors using QR reduction. Experimental.
normalized (bool, optional) – Whether to normalize the reduced density matrix at the end.
symmetrized ({'auto', True, False}, optional) – Whether to symmetrize the reduced density matrix at the end. This should be unecessary if
flatten
is set toTrue
.rehearse ({False, 'tn', 'tree', True}, optional) –
Whether to perform the computation or not:
- False: perform the computation. - 'tn': return the tensor network without running the path optimizer. - 'tree': run the path optimizer and return the ``cotengra.ContractonTree``.. - True: run the path optimizer and return the ``PathInfo``.
contract_compressed_opts (dict, optional) – Additional keyword arguments to pass to
contract_compressed()
.
- Returns:
rho – The reduce density matrix of sites in
keep
.- Return type:
array_like
- partial_trace_to_dense_canonical(where, normalized=True, info=None, **contract_opts)[source]¶
Compute the dense local reduced density matrix by canonicalizing around the target sites and then contracting the local tensors. Note this moves the orthogonality around inplace, and records it in info.
- Parameters:
where (int or tuple[int]) – The site or sites to compute the reduced density matrix for.
normalized (bool, optional) – Explicitly normalize the local reduced density matrix.
info (dict, optional) – If supplied, will be used to infer and store various extra information. Currently the key “cur_orthog” is used to store the current orthogonality center. Its input value can be
"calc"
, a single site, or a pair of sites representing the min/max range, inclusive. It will be updated to the actual range after.contract_opts – Passed to tensor_contract when computing the reduced local density matrix.
- Return type:
array_like
- local_expectation_canonical(G, where, normalized=True, info=None, **contract_opts)[source]¶
Compute a local expectation value (via forming the reduced density matrix). Note this moves the orthogonality around inplace, and records it in info.
- Parameters:
G (array_like) – The local operator to compute the expectation of.
where (int or tuple[int]) – The site or sites to compute the expectation at.
normalized (bool, optional) – Explicitly normalize the local reduced density matrix.
info (dict, optional) – If supplied, will be used to infer and store various extra information. Currently the key “cur_orthog” is used to store the current orthogonality center. Its input value can be
"calc"
, a single site, or a pair of sites representing the min/max range, inclusive. It will be updated to the actual range after.contract_opts – Passed to tensor_contract when computing the reduced local density matrix.
- Return type:
- compute_local_expectation_canonical(terms, normalized=True, return_all=False, info=None, inplace=False, **contract_opts)[source]¶
Compute many local expectations at once, via forming the relevant reduced density matrices via canonicalization. This moves the orthogonality around inplace, and records it in info.
- Parameters:
terms (dict[int or tuple[int], array_like]) – The local terms to compute values for.
normalized (bool, optional) – Explicitly normalize each local reduced density matrix.
return_all (bool, optional) – Whether to return each expectation in terms separately or sum them all together (the default).
info (dict, optional) – If supplied, will be used to infer and store various extra information. Currently, the key “cur_orthog” is used to store the current orthogonality center. Its input value can be
"calc"
, a single site, or a pair of sites representing the min/max range, inclusive. It will be updated to the actual range after.inplace (bool, optional) – Whether to perform the required canonicalizations inplace.
contract_opts – Supplied to
contract()
when contracting the local density matrices.
- Returns:
The expecetation value(s), either summed or for each term if return_all=True.
- Return type:
- compute_local_expectation_via_envs(terms, normalized=True, return_all=False, **contract_opts)[source]¶
Compute many local expectations at once, via forming the relevant local overlaps using left and right environments formed via contraction. This does not require any canonicalization and can be quicker if the canonical center is not already aligned.
- Parameters:
terms (dict[int or tuple[int], array_like]) – The local terms to compute values for.
normalized (bool, optional) – Explicitly normalize each local reduced density matrix.
return_all (bool, optional) – Whether to return each expectation in terms separately or sum them all together (the default).
contract_opts – Supplied to
contract()
when contracting the local overlaps.
- Returns:
The expecetation value(s), either summed or for each term if return_all=True.
- Return type:
See also
compute_local_expectation_canonical
,compute_left_environments
,compute_right_environments
- compute_local_expectation(terms, normalized=True, return_all=False, method='canonical', info=None, inplace=False, **contract_opts)[source]¶
Compute many local expectations at once.
- Parameters:
terms (dict[int or tuple[int], array_like]) – The local terms to compute values for.
normalized (bool, optional) – Explicitly normalize each local term.
return_all (bool, optional) – Whether to return each expectation in terms separately or sum them all together (the default).
method ({'canonical', 'envs'}, optional) –
The method to use to compute the local expectations.
’canonical’: canonicalize around the sites of interest and contract the local reduced density matrices, moving the canonical center around as needed.
’envs’: form the local overlaps using left and right environments and contract these directly. This can be quicker if the canonical center is not already aligned.
info (dict, optional) – If supplied, and method==”canonical”, will be used to infer and store various extra information. Currently the key “cur_orthog” is used to store the current orthogonality center. Its input value can be
"calc"
, a single site, or a pair of sites representing the min/max range, inclusive. It will be updated to the actual range after.inplace (bool, optional) – If method==”canonical”, whether to perform the required canonicalizations inplace or on a copy of the state.
contract_opts – Supplied to
contract()
when contracting the local overlaps or density matrices.
- Returns:
The expecetation value(s), either summed or for each term if return_all=True.
- Return type:
- bipartite_schmidt_state(sz_a, get='ket', info=None)[source]¶
Compute the reduced state for a bipartition of an OBC MPS, in terms of the minimal left/right schmidt basis:
A B ......... ........... >->->->->--s--<-<-<-<-<-< -> +-s-+ | | | | | | | | | | | | | k0 k1... kA kB
- Parameters:
sz_a (int) – The number of sites in subsystem A, must be
0 < sz_a < N
.get ({'ket', 'rho', 'ket-dense', 'rho-dense'}, optional) –
Get the:
’ket’: vector form as tensor.
’rho’: density operator form, i.e. vector outer product
’ket-dense’: like ‘ket’ but return
qarray
.’rho-dense’: like ‘rho’ but return
qarray
.
info (dict, optional) – If given, will be used to infer and store various extra information. Currently the key “cur_orthog” is used to store the current orthogonality center.
- static _do_lateral_compress(mps, kb, section, leave_short, ul, ll, heps, hmethod, hmax_bond, verbosity, compressed, **compress_opts)[source]¶
- static _do_vertical_decomp(mps, kb, section, sysa, sysb, compressed, ul, ur, ll, lr, vmethod, vmax_bond, veps, verbosity, **compress_opts)[source]¶
- partial_trace_compress(sysa, sysb, eps=1e-08, method=('isvd', None), max_bond=(None, 1024), leave_short=True, renorm=True, lower_ind_id='b{}', verbosity=0, **compress_opts)[source]¶
Perform a compressed partial trace using singular value lateral then vertical decompositions of transfer matrix products:
.....sysa...... ...sysb.... o-o-o-o-A-A-A-A-A-A-A-A-o-o-B-B-B-B-B-B-o-o-o-o-o-o-o-o-o | | | | | | | | | | | | | | | | | | | | | | | | | | | | | ==> form inner product ............... ........... o-o-o-o-A-A-A-A-A-A-A-A-o-o-B-B-B-B-B-B-o-o-o-o-o-o-o-o-o | | | | | | | | | | | | | | | | | | | | | | | | | | | | | o-o-o-o-A-A-A-A-A-A-A-A-o-o-B-B-B-B-B-B-o-o-o-o-o-o-o-o-o ==> lateral SVD on each section .....sysa...... ...sysb.... /\ /\ /\ /\ ... ~~~E A~~~~~~~~~~~A E~E B~~~~~~~B E~~~ ... \/ \/ \/ \/ ==> vertical SVD and unfold on A & B | | /-------A-------\ /-----B-----\ ... ~~~E E~E E~~~ ... \-------A-------/ \-----B-----/ | |
With various special cases including OBC or end spins included in subsytems.
- Parameters:
sysa (sequence of int) – The sites, which should be contiguous, defining subsystem A.
sysb (sequence of int) – The sites, which should be contiguous, defining subsystem B.
eps (float or (float, float), optional) – Tolerance(s) to use when compressing the subsystem transfer matrices and vertically decomposing.
method (str or (str, str), optional) – Method(s) to use for laterally compressing the state then vertially compressing subsytems.
max_bond (int or (int, int), optional) – The maximum bond to keep for laterally compressing the state then vertially compressing subsytems.
leave_short (bool, optional) – If True (the default), don’t try to compress short sections.
renorm (bool, optional) – If True (the default), renomalize the state so that
tr(rho)==1
.lower_ind_id (str, optional) – The index id to create for the new density matrix, the upper_ind_id is automatically taken as the current site_ind_id.
compress_opts (dict, optional) – If given, supplied to
partial_trace_compress
to govern how singular values are treated. Seetensor_split
.verbosity ({0, 1}, optional) – How much information to print while performing the compressed partial trace.
- Returns:
rho_ab – Density matrix tensor network with
outer_inds = ('k0', 'k1', 'b0', 'b1')
for example.- Return type:
- logneg_subsys(sysa, sysb, compress_opts=None, approx_spectral_opts=None, verbosity=0, approx_thresh=2**12)[source]¶
Compute the logarithmic negativity between subsytem blocks, e.g.:
sysa sysb ......... ..... ... -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. Seetensor_split
.approx_spectral_opts – Supplied to
approx_spectral_function()
.
- Returns:
ln – The logarithmic negativity.
- Return type:
See also
MatrixProductState.partial_trace_compress
,approx_spectral_function
- measure(site, remove=False, outcome=None, renorm=True, info=None, get=None, seed=None, inplace=False)[source]¶
Measure this MPS at
site
, including projecting the state. Optionally remove the site afterwards, yielding an MPS with one less site. In either case the orthogonality center of the returned MPS ismin(site, new_L - 1)
.- Parameters:
site (int) – The site to measure.
remove (bool, optional) –
Whether to remove the site completely after projecting the measurement. If
True
, sites greater thansite
will be retagged and reindex one down, and the MPS will have one less site. E.g:0-1-2-3-4-5-6 / / / - measure and remove site 3 0-1-2-4-5-6 - reindex sites (4, 5, 6) to (3, 4, 5) 0-1-2-3-4-5
outcome (None or int, optional) – Specify the desired outcome of the measurement. If
None
, it will be randomly sampled according to the local density matrix.renorm (bool, optional) – Whether to renormalize the state post measurement.
info (dict, optional) – If given, will be used to infer and store various extra information. Currently the key “cur_orthog” is used to store the current orthogonality center.
get ({None, 'outcome'}, optional) – If
'outcome'
, simply return the outcome, and don’t perform any projection.seed (None, int, or np.random.Generator, optional) – A random seed or generator to use.
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'
.
- sample(C, seed=None, info=None)[source]¶
Generate
C
samples rom this MPS, along with their probabilities.- Parameters:
C (int) – The number of samples to generate.
seed (None, int, or np.random.Generator, optional) – A random seed or generator to use.
info (dict, optional) – If given, will be used to infer and store various extra information. Currently the key “cur_orthog” is used to store the current orthogonality center.
- Yields:
config (sequence of int) – The sample configuration.
omega (float) – The probability of this configuration.
- 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.
- _EXTRA_PROPS = ('_site_tag_id', '_outer_upper_ind_id', '_inner_upper_ind_id', '_inner_lower_ind_id',...¶
- _L¶
- _outer_upper_ind_id = 'kn{}'¶
- _inner_upper_ind_id = 'k{}'¶
- _inner_lower_ind_id = 'b{}'¶
- _outer_lower_ind_id = 'bn{}'¶
- _site_tag_id = 'I{}'¶
- cyclic¶
- classmethod rand(n, K, chi, phys_dim=2, herm=True, cyclic=False, dtype=complex, **superop_opts)[source]¶
- property outer_upper_ind_id¶
- property inner_upper_ind_id¶
- property inner_lower_ind_id¶
- property outer_lower_ind_id¶
- class quimb.tensor.TensorNetwork1D(ts=(), *, virtual=False, check_collisions=True)[source]¶
Bases:
quimb.tensor.tensor_arbgeom.TensorNetworkGen
Base class for tensor networks with a one-dimensional structure.
- _NDIMS = 1¶
- _EXTRA_PROPS = ('_site_tag_id', '_L')¶
- _CONTRACT_STRUCTURED = True¶
- _compatible_1d(other)[source]¶
Check whether
self
andother
are compatible 2D tensor networks such that they can remain a 2D tensor network when combined.
- combine(other, *, virtual=False, check_collisions=True)[source]¶
Combine this tensor network with another, returning a new tensor network. If the two are compatible, cast the resulting tensor network to a
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:
- property L¶
The number of sites, i.e. length.
- property nsites¶
The number of sites.
- 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 aslice
or … to a cumulative sequence of tags.- Parameters:
- 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
- compute_left_environments(**contract_opts)[source]¶
Compute the left environments of this 1D tensor network.
- Parameters:
contract_opts – Supplied to
contract()
.- Returns:
Environments indexed by the site they are to the left of, so keys run from (1, … L - 1).
- Return type:
- compute_right_environments(**contract_opts)[source]¶
Compute the right environments of this 1D tensor network.
- Parameters:
contract_opts – Supplied to
contract()
.- Returns:
Environments indexed by the site they are to the right of, so keys run from (0, … L - 2).
- Return type:
- 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
- tn¶
- tags¶
- is_conj = False¶
- is_trans = False¶
- _conj_linop = None¶
- _adjoint_linop = None¶
- _transpose_linop = None¶
- _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).
- property A¶
- 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:
- 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 siteswhere
, 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 correctsite_ind_id
. Sites are read left to right from the shape. A two-dimensional array is permissible if each dimension factorizes correctly.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()
ifcontract='swap+split'
orgate_with_auto_swap()
ifcontract='swap+split'
.
- Return type:
See also
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:
- quimb.tensor.enforce_1d_like(tn, site_tags=None, fix_bonds=True, inplace=False)[source]¶
Check that
tn
is 1D-like with OBC, i.e. 1) that each tensor has exactly one of the givensite_tags
. If not, raise a ValueError. 2) That there are no hyper indices. And 3) that there are only bonds within sites or between nearest neighbor sites. This issue can be optionally automatically fixed by inserting a string of identity tensors.- Parameters:
tn (TensorNetwork) – The tensor network to check.
site_tags (sequence of str, optional) – The tags to use to group and order the tensors from
tn
. If not given, usestn.site_tags
.fix_bonds (bool, optional) – Whether to fix the bond structure by inserting identity tensors.
inplace (bool, optional) – Whether to perform the fix inplace or not.
- Raises:
ValueError – If the tensor network is not 1D-like.
- quimb.tensor.tensor_network_1d_compress(tn, max_bond=None, cutoff=1e-10, method='dm', site_tags=None, canonize=True, permute_arrays=True, optimize='auto-hq', sweep_reverse=False, equalize_norms=False, compress_opts=None, inplace=False, **kwargs)[source]¶
Compress a 1D-like tensor network using the specified method.
- Parameters:
tn (TensorNetwork) – The tensor network to compress. Every tensor should have exactly one of the site tags. Each site can have multiple tensors and output indices.
max_bond (int) – The maximum bond dimension to compress to.
cutoff (float, optional) – A dynamic threshold for discarding singular values when compressing.
method ({"direct", "dm", "zipup", "zipup-first", "fit", "projector", ...}) – The compression method to use.
site_tags (sequence of str, optional) – The tags to use to group and order the tensors from
tn
. If not given, usestn.site_tags
. The tensor network built will have one tensor per site, in the order given bysite_tags
.canonize (bool, optional) – Whether to perform canonicalization, pseudo or otherwise depending on the method, before compressing. Ignored for
method='dm'
andmethod='fit'
.permute_arrays (bool or str, optional) – Whether to permute the array indices of the final tensor network into canonical order. If
True
will use the default order, otherwise if a string this specifies a custom order.optimize (str, optional) – The contraction path optimizer to use.
sweep_reverse (bool, optional) – Whether to sweep in the reverse direction, resulting in a left canonical form instead of right canonical (for the fit method, this also depends on the last sweep direction).
equalize_norms (bool or float, optional) – Whether to equalize the norms of the tensors after compression. If an explicit value is give, then the norms will be set to that value, and the overall scaling factor will be accumulated into .exponent.
inplace (bool, optional) – Whether to perform the compression inplace.
kwargs – Supplied to the chosen compression method.
- Return type:
- 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)
, whered
is the physical dimension ofp0
.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
- _pt¶
- L¶
- H¶
- cyclic¶
- _ham_norm¶
- _err = 0.0¶
- tol = None¶
- imag = False¶
- progbar = True¶
- split_opts¶
- property pt¶
The MPS state of the system at the current time.
- property err¶
- 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 sitessites
, 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.
- TARGET_TOL = 1e-13¶
- update_to(T, dt=None, tol=None, order=4, progbar=None)[source]¶
Update the state to time
T
.- Parameters:
- 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 likeH.get_gate_expm((i, i + 1), -1j * 0.5)
etc.- Parameters:
L (int) – The size of the hamiltonian.
H2 (array_like or dict[tuple[int], array_like]) – The sum of interaction terms. If a dict is given, the keys should be nearest neighbours like
(10, 11)
, apart from any default term which should have the keyNone
, and the values should be the sum of interaction terms for that interaction.H1 (array_like or dict[int, array_like], optional) – The sum of single site terms. If a dict is given, the keys should be integer sites, apart from any default term which should have the key
None
, and the values should be the sum of single site terms for that site.cyclic (bool, optional) – Whether the hamiltonian has periodic boundary conditions or not.
- terms¶
The terms in the hamiltonian, combined from the inputs such that there is a single term per pair.
Examples
A simple, translationally invariant, 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
- L¶
- cyclic = False¶
- 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()
.
- 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')¶
- _upper_ind_id = 'k{},{}'¶
- _lower_ind_id = 'b{},{}'¶
- _site_tag_id = 'I{},{}'¶
- _x_tag_id = 'X{}'¶
- _y_tag_id = 'Y{}'¶
- _Lx¶
- _Ly¶
- 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, scale=1.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:
- rand_herm¶
- 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
.
- apply(other, compress=False, **compress_opts)[source]¶
Act with this PEPO on
other
, returning a new TN likeother
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:
- 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')¶
- _site_ind_id = 'k{},{}'¶
- _site_tag_id = 'I{},{}'¶
- _x_tag_id = 'X{}'¶
- _y_tag_id = 'Y{}'¶
- _Lx¶
- _Ly¶
- 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:
- classmethod empty(Lx, Ly, bond_dim, phys_dim=2, like='numpy', **peps_opts)[source]¶
Create an empty 2D PEPS.
- Parameters:
- Returns:
psi
- Return type:
See also
- 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:
- Returns:
psi
- Return type:
See also
- classmethod zeros(Lx, Ly, bond_dim, phys_dim=2, like='numpy', **peps_opts)[source]¶
Create a 2D PEPS whose tensors are filled with zeros.
- Parameters:
- Returns:
psi
- Return type:
See also
- classmethod rand(Lx, Ly, bond_dim, phys_dim=2, dist='normal', loc=0.0, scale=1.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:
See also
- classmethod product_state(site_map, cyclic=False, **peps_opts)[source]¶
Create a PEPS representing a product state, with explicit bonds of dimension 1 between sites.
- Parameters:
site_map (dict[tuple[int, int], array] or Sequence[Sequence[array]]) – A mapping of site coordinates to physical vectors, or a 2D array of physical vectors. Each vector being a single site state.
cyclic (bool or tuple[bool, bool], optional) – Whether the lattice is cyclic in the x and y directions.
peps_opts – Supplied to
PEPS
.
- Return type:
- 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)
- _NDIMS = 2¶
- _EXTRA_PROPS = ('_site_tag_id', '_x_tag_id', '_y_tag_id', '_Lx', '_Ly')¶
- _compatible_2d(other)[source]¶
Check whether
self
andother
are compatible 2D tensor networks such that they can remain a 2D tensor network when combined.
- combine(other, *, virtual=False, check_collisions=True)[source]¶
Combine this tensor network with another, returning a new tensor network. If the two are compatible, cast the resulting tensor network to a
TensorNetwork2D
instance.- Parameters:
other (TensorNetwork2D or TensorNetwork) – The other tensor network to combine with.
virtual (bool, optional) – Whether the new tensor network should copy all the incoming tensors (
False
, the default), or view them as virtual (True
).check_collisions (bool, optional) – Whether to check for index collisions between the two tensor networks before combining them. If
True
(the default), any inner indices that clash will be mangled.
- Return type:
- property Lx¶
The number of rows.
- property Ly¶
The number of columns.
- property nsites¶
The total number of sites.
- property x_tag_id¶
The string specifier for tagging each row of this 2D TN.
- property x_tags¶
A tuple of all of the
Lx
different row tags.
- row_tags¶
- property y_tag_id¶
The string specifier for tagging each column of this 2D TN.
- property y_tags¶
A tuple of all of the
Ly
different column tags.
- col_tags¶
- maybe_convert_coo(x)[source]¶
Check if
x
is a tuple of two ints and convert to the corresponding site tag if so.
- _get_tids_from_tags(tags, which='all')[source]¶
This is the function that lets coordinates such as
(i, j)
be used for many ‘tag’ based functions.
- gen_horizontal_even_bond_coos()[source]¶
Generate all coordinate pairs like
(i, j), (i, j + 1)
wherej
is even, which thus don’t overlap at all.
- gen_horizontal_odd_bond_coos()[source]¶
Generate all coordinate pairs like
(i, j), (i, j + 1)
wherej
is odd, which thus don’t overlap at all.
- gen_vertical_even_bond_coos()[source]¶
Generate all coordinate pairs like
(i, j), (i + 1, j)
wherei
is even, which thus don’t overlap at all.
- gen_vertical_odd_bond_coos()[source]¶
Generate all coordinate pairs like
(i, j), (i + 1, j)
wherei
is odd, which thus don’t overlap at all.
- gen_diagonal_left_even_bond_coos()[source]¶
Generate all coordinate pairs like
(i, j), (i + 1, j - 1)
wherej
is even, which thus don’t overlap at all.
- gen_diagonal_left_odd_bond_coos()[source]¶
Generate all coordinate pairs like
(i, j), (i + 1, j - 1)
wherej
is odd, which thus don’t overlap at all.
- gen_diagonal_right_even_bond_coos()[source]¶
Generate all coordinate pairs like
(i, j), (i + 1, j + 1)
wherei
is even, which thus don’t overlap at all.
- gen_diagonal_right_odd_bond_coos()[source]¶
Generate all coordinate pairs like
(i, j), (i + 1, j + 1)
wherei
is odd, which thus don’t overlap at all.
- is_cyclic_x(j=None, imin=None, imax=None)[source]¶
Check if the x dimension is cyclic (periodic), specifically whether a bond exists between
(imin, j)
and(imax, j)
, with default values ofimin = 0
andimax = Lx - 1
, andj
at the center of the lattice. Ifimin
andimax
are adjacent then this is considered False, since there is no ‘extra’ connectivity.
- is_cyclic_y(i=None, jmin=None, jmax=None)[source]¶
Check if the y dimension is cyclic (periodic), specifically whether a bond exists between
(i, jmin)
and(i, jmax)
, with default values ofjmin = 0
andjmax = Ly - 1
, andi
at the center of the lattice. Ifjmin
andjmax
are adjacent then this is considered False, since there is no ‘extra’ connectivity.
- _repr_info()[source]¶
General info to show in various reprs. Sublasses can add more relevant info to this dict.
- flatten(fuse_multibonds=True, inplace=False)[source]¶
Contract all tensors corresponding to each site into one.
- gen_pairs(xrange=None, yrange=None, xreverse=False, yreverse=False, coordinate_order='xy', xstep=None, ystep=None, stepping_order='xy', step_only=None)[source]¶
Helper function for generating pairs of cooordinates for all bonds within a certain range, optionally specifying an order.
- Parameters:
xrange ((int, int), optional) – The range of allowed values for the x and y coordinates.
yrange ((int, int), optional) – The range of allowed values for the x and y coordinates.
xreverse (bool, optional) – Whether to reverse the order of the x and y sweeps.
yreverse (bool, optional) – Whether to reverse the order of the x and y sweeps.
coordinate_order (str, optional) – The order in which to sweep the x and y coordinates. Earlier dimensions will change slower. If the corresponding range has size 1 then that dimension doesn’t need to be specified.
xstep (int, optional) – When generating a bond, step in this direction to yield the neighboring coordinate. By default, these follow
xreverse
andyreverse
respectively.ystep (int, optional) – When generating a bond, step in this direction to yield the neighboring coordinate. By default, these follow
xreverse
andyreverse
respectively.stepping_order (str, optional) – The order in which to step the x and y coordinates to generate bonds. Does not need to include all dimensions.
step_only (int, optional) – Only perform the ith steps in
stepping_order
, used to interleave canonizing and compressing for example.
- Yields:
coo_a, coo_b (((int, int), (int, int)))
- canonize_plane(xrange, yrange, equalize_norms=False, canonize_opts=None, **gen_pair_opts)[source]¶
Canonize every pair of tensors within a subrange, optionally specifying a order to visit those pairs in.
- canonize_row(i, sweep, yrange=None, **canonize_opts)[source]¶
Canonize all or part of a row.
If
sweep == 'right'
then:| | | | | | | | | | | | | | ─●──●──●──●──●──●──●─ ─●──●──●──●──●──●──●─ | | | | | | | | | | | | | | ─●──●──●──●──●──●──●─ ==> ─●──>──>──>──>──o──●─ row=i | | | | | | | | | | | | | | ─●──●──●──●──●──●──●─ ─●──●──●──●──●──●──●─ | | | | | | | | | | | | | | . . . . jstart jstop jstart jstop
If
sweep == 'left'
then:| | | | | | | | | | | | | | ─●──●──●──●──●──●──●─ ─●──●──●──●──●──●──●─ | | | | | | | | | | | | | | ─●──●──●──●──●──●──●─ ==> ─●──o──<──<──<──<──●─ row=i | | | | | | | | | | | | | | ─●──●──●──●──●──●──●─ ─●──●──●──●──●──●──●─ | | | | | | | | | | | | | | . . . . jstop jstart jstop jstart
Does not yield an orthogonal form in the same way as in 1D.
- canonize_column(j, sweep, xrange=None, **canonize_opts)[source]¶
Canonize all or part of a column.
If
sweep='up'
then:| | | | | | ─●──●──●─ ─●──●──●─ | | | | | | ─●──●──●─ ─●──o──●─ istop | | | ==> | | | ─●──●──●─ ─●──^──●─ | | | | | | ─●──●──●─ ─●──^──●─ istart | | | | | | ─●──●──●─ ─●──●──●─ | | | | | | . . j j
If
sweep='down'
then:| | | | | | ─●──●──●─ ─●──●──●─ | | | | | | ─●──●──●─ ─●──v──●─ istart | | | ==> | | | ─●──●──●─ ─●──v──●─ | | | | | | ─●──●──●─ ─●──o──●─ istop | | | | | | ─●──●──●─ ─●──●──●─ | | | | | | . . j j
Does not yield an orthogonal form in the same way as in 1D.
- compress_plane(xrange, yrange, max_bond=None, cutoff=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 tocutoff
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 tocutoff
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 tocutoff
.cutoff (float, optional) – The cutoff to use for boundary compression.
lazy (bool, optional) – Whether to leave the boundary tensors uncontracted. If
False
(the default), the boundary tensors are contracted and the resulting boundary has a single tensor per site.equalize_norms (bool, optional) – Whether to actively absorb the norm of modified tensors into
self.exponent
.optimize (str or PathOptimizer, optional) – The contract path optimization to use when forming the projector tensors.
compress_opts (dict, optional) – Other options to pass to
svd_truncated()
.
- contract_boundary_from(xrange, yrange, from_which, max_bond=None, *, cutoff=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 tocutoff
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 eachlayer_tag
inlayer_tags
.sweep_reverse (bool, optional) – Which way to perform the compression sweep, which has an effect on which tensors end up being canonized. Setting this to true sweeps the compression from largest to smallest coordinates.
compress_opts (None or dict, optional) – Supplied to
compress_between()
.inplace (bool, optional) – Whether to perform the contraction inplace or not.
- contract_boundary_from_xmax(xrange, yrange=None, max_bond=None, *, cutoff=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 tocutoff
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 eachlayer_tag
inlayer_tags
.sweep_reverse (bool, optional) – Which way to perform the compression sweep, which has an effect on which tensors end up being canonized. Setting this to true sweeps the compression from largest to smallest coordinates.
compress_opts (None or dict, optional) – Supplied to
compress_between()
.inplace (bool, optional) – Whether to perform the contraction inplace or not.
- contract_boundary_from_ymin(yrange, xrange=None, max_bond=None, *, cutoff=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 tocutoff
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 eachlayer_tag
inlayer_tags
.sweep_reverse (bool, optional) – Which way to perform the compression sweep, which has an effect on which tensors end up being canonized. Setting this to true sweeps the compression from largest to smallest coordinates.
compress_opts (None or dict, optional) – Supplied to
compress_between()
.inplace (bool, optional) – Whether to perform the contraction inplace or not.
- contract_boundary_from_ymax(yrange, xrange=None, max_bond=None, *, cutoff=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 tocutoff
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 eachlayer_tag
inlayer_tags
.sweep_reverse (bool, optional) – Which way to perform the compression sweep, which has an effect on which tensors end up being canonized. Setting this to true sweeps the compression from largest to smallest coordinates.
compress_opts (None or dict, optional) – Supplied to
compress_between()
.inplace (bool, optional) – Whether to perform the contraction inplace or not.
- _contract_interleaved_boundary_sequence(*, contract_boundary_opts=None, sequence=None, xmin=None, xmax=None, ymin=None, ymax=None, max_separation=1, max_unfinished=1, around=None, equalize_norms=False, canonize=False, canonize_opts=None, final_contract=True, final_contract_opts=None, progbar=False, inplace=False)[source]¶
Unified handler for performing iterleaved contractions in a sequence of inwards boundary directions.
- contract_boundary(max_bond=None, *, cutoff=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 tocutoff
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, can also be any of the generic 1D or arbgeom methods.
layer_tags (None or sequence of str, optional) – If given, perform a multilayer contraction, contracting the inner sites in each layer into the boundary individually.
compress_opts (None or dict, optional) – Other low level options to pass to
compress_between()
.sequence (sequence of {'xmin', 'xmax', 'ymin', 'ymax'}, optional) – Which directions to cycle throught when performing the inwards contractions, i.e. from that direction. If
around
is specified you will likely need all of these! Default is to contract from the two shortest opposing sides.xmin (int, optional) – The initial bottom boundary row, defaults to 0.
xmax (int, optional) – The initial top boundary row, defaults to
Lx - 1
.ymin (int, optional) – The initial left boundary column, defaults to 0.
ymax (int, optional) – The initial right boundary column, defaults to
Ly - 1
..max_separation (int, optional) – If
around is None
, when any two sides become this far apart simply contract the remaining tensor network.max_unfinished (int, optional) – If
around is None
, when this many sides are still not withinmax_separation
simply contract the remaining tensor network.around – If given, don’t contract the square of sites bounding these coordinates.
equalize_norms (bool or float, optional) – Whether to equalize the norms of the boundary tensors after each contraction, gathering the overall scaling coefficient, log10, in
tn.exponent
.final_contract (bool, optional) – Whether to exactly contract the remaining tensor network after the boundary contraction.
final_contract_opts (None or dict, optional) – Options to pass to
contract()
,optimize
defaults to'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 tocutoff
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.
- 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:
- compute_xmin_environments[source]¶
Compute the
self.Lx
1D boundary tensor networks describing the lower environments of each row in this 2D tensor network. Seecompute_x_environments()
for full details.
- compute_xmax_environments[source]¶
Compute the
self.Lx
1D boundary tensor networks describing the upper environments of each row in this 2D tensor network. Seecompute_x_environments()
for full details.
- compute_ymin_environments[source]¶
Compute the
self.Ly
1D boundary tensor networks describing the left environments of each column in this 2D tensor network. Seecompute_y_environments()
for full details.
- compute_ymax_environments[source]¶
Compute the
self.Ly
1D boundary tensor networks describing the right environments of each column in this 2D tensor network. Seecompute_y_environments()
for full details.
- compute_x_environments(max_bond=None, *, cutoff=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 rowsi + 1, i + 2, ...
etc:●━━━●━━━●━━━●━━━●━━━●━━━●━━━●━━━●━━━● ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲
The bottom or ‘xmin’ environment for row
i
will be a contraction of all rowsi - 1, i - 2, ...
etc:╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ●━━━●━━━●━━━●━━━●━━━●━━━●━━━●━━━●━━━●
Such that
envs['xmax', i] & self.select(self.x_tag(i)) & envs['xmin', i]
would look like:●━━━●━━━●━━━●━━━●━━━●━━━●━━━●━━━●━━━● ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ o─o─o─o─o─o─o─o─o─o─o─o─o─o─o─o─o─o─o─o ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ●━━━●━━━●━━━●━━━●━━━●━━━●━━━●━━━●━━━●
And be (an approximation of) the norm centered around row
i
- Parameters:
max_bond (int, optional) – The maximum boundary dimension, AKA ‘chi’. The default of
None
means truncation is left purely tocutoff
and is not recommended in 2D.cutoff (float, optional) – 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 eachlayer_tag
inlayer_tags
.compress_opts (None or dict, optional) – Supplied to
compress_between()
.envs (dict, optional) – Supply an existing dictionary to store the environments in.
contract_boundary_opts – Supplied to
contract_boundary_from_xmin()
andcontract_boundary_from_xmax()
.
- Returns:
x_envs – The two environment tensor networks of row
i
will be stored inx_envs['xmin', i]
andx_envs['xmax', i]
.- Return type:
dict[(str, int), TensorNetwork]
- compute_y_environments(max_bond=None, *, cutoff=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 columnsj - 1, j - 2, ...
etc:●< ┃ ●< ┃ ●< ┃ ●<
The right or ‘ymax’ environment for row
j
will be a contraction of all rowsj + 1, j + 2, ...
etc:>● ┃ >● ┃ >● ┃ >●
Such that
envs['ymin', j] & self.select(self.y_tag(j)) & envs['ymax', j]
would look like:╱o ●< o| >● ┃ |o ┃ ●< o| >● ┃ |o ┃ ●< o| >● ┃ |o ┃ ●< o╱ >●
And be (an approximation of) the norm centered around column
j
- Parameters:
max_bond (int, optional) – The maximum boundary dimension, AKA ‘chi’. The default of
None
means truncation is left purely tocutoff
and is not recommended in 2D.cutoff (float, optional) – 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 eachlayer_tag
inlayer_tags
.compress_opts (None or dict, optional) – Supplied to
compress_between()
.contract_boundary_opts – Supplied to
contract_boundary_from_ymin()
andcontract_boundary_from_ymax()
.
- Returns:
y_envs – The two environment tensor networks of column
j
will be stored iny_envs['ymin', j]
andy_envs['ymax', j]
.- Return type:
dict[(str, int), TensorNetwork]
- _compute_plaquette_environments_x_first(x_bsz, y_bsz, max_bond=None, cutoff=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 tocutoff
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 eachlayer_tag
inlayer_tags
.first_contract ({None, 'x', 'y'}, optional) – The environments can either be generated with initial sweeps in the row (‘x’) or column (‘y’) direction. Generally it makes sense to perform this approximate step in whichever is smaller (the default).
second_dense (None or bool, optional) – Whether to perform the second set of contraction sweeps (in the rotated direction from whichever
first_contract
is) using a dense tensor or boundary method. By default this is only turned on if thebsz
in the corresponding direction is 1.compress_opts (None or dict, optional) – Supplied to
compress_between()
.compute_environment_opts – Supplied to
compute_y_environments()
orcompute_x_environments()
.
- Returns:
The plaquette environments. The key is two tuples of ints, the startings coordinate of the plaquette being the first and the size of the plaquette being the second pair.
- Return type:
- coarse_grain_hotrg(direction, max_bond=None, cutoff=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:
- 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:
- 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
andaround=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 returnsTrue
if this is to be a valid starting coordinate.
- Yields:
bond (tuple[tuple[int, int], tuple[int, int]]) – A pair of coordinates.
Examples
Generate nearest neighbor bonds:
>>> for bond in gen_2d_bonds(2, 2, [lambda i, j: (i, j + 1), >>> lambda i, j: (i + 1, j)]): >>> print(bond) ((0, 0), (0, 1)) ((0, 0), (1, 0)) ((0, 1), (1, 1)) ((1, 0), (1, 1))
Generate next nearest neighbor digonal bonds:
>>> for bond in gen_2d_bonds(2, 2, [lambda i, j: (i + 1, j + 1), >>> lambda i, j: (i + 1, j - 1)]): >>> print(bond) ((0, 0), (1, 1)) ((0, 1), (1, 0))
- 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 tomax_bond
. By defaultcontract
is set to ‘reduce-split’ andcutoff
is set to0.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 inordering
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 defaultmax_bond
is set tomax(8, D**2)
whereD
is the maximum bond to use for applying the gate,cutoff
is set to0.0
andnormalized
is set toTrue
.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 toTrue
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:
- ham¶
The Hamiltonian being used to evolve.
- Type:
- energy¶
The current of the current state, this will trigger a computation if the energy at this iteration hasn’t been computed yet.
- Type:
- its¶
The corresponding sequence of iteration numbers that energies have been computed at.
- taus¶
The corresponding sequence of time steps that energies have been computed at.
- best¶
If
keep_best
was set then the best recorded energy and the corresponding state that was computed - keys'energy'
and'state'
respectively.- Type:
- property chi¶
- 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 tomax_bond
. By defaultcontract
is set to ‘reduce-split’ andcutoff
is set to0.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 inordering
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 defaultmax_bond
is set tomax(8, D**2)
whereD
is the maximum bond to use for applying the gate,cutoff
is set to0.0
andnormalized
is set toTrue
.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 toTrue
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 sweepint: 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:
- ham¶
The Hamiltonian being used to evolve.
- Type:
- energy¶
The current of the current state, this will trigger a computation if the energy at this iteration hasn’t been computed yet.
- Type:
- its¶
The corresponding sequence of iteration numbers that energies have been computed at.
- taus¶
The corresponding sequence of time steps that energies have been computed at.
- best¶
If
keep_best
was set then the best recorded energy and the corresponding state that was computed - keys'energy'
and'state'
respectively.- Type:
- property fit_strategy¶
- fit_opts¶
- pre_normalize = True¶
- contract_optimize = ''¶
- condition_tensors = True¶
- condition_balance_bonds = True¶
- 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.
- 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 keyNone
.H1 (array_like or dict[tuple[int], array_like], optional) – The one site term(s). If a single array is given, assume to be the default onsite term for all terms. If a dict is supplied, the keys should represent specific coordinates like
(i, j)
with the values the array representing the local term for that site. A default term for all remaining sites can still be supplied with the keyNone
.
- terms¶
The total effective local term for each interaction (with single site terms appropriately absorbed). Each key is a pair of coordinates
ija, ijb
withija < ijb
.
- Lx¶
- Ly¶
- property nsites¶
The number of sites in the system.
- draw(ordering='sort', show_norm=True, figsize=None, fontsize=8, legend=True, ax=None, **kwargs)[source]¶
Plot this Hamiltonian as a network.
- Parameters:
ordering ({'sort', None, 'random'}, optional) – An ordering of the termns, or an argument to be supplied to
quimb.tensor.tensor_2d_tebd.LocalHam2D.get_auto_ordering()
to generate this automatically.show_norm (bool, optional) – Show the norm of each term as edge labels.
figsize (None or tuple[int], optional) – Size of the figure, defaults to size of Hamiltonian.
fontsize (int, optional) – Font size for norm labels.
legend (bool, optional) – Whether to show the legend of which terms are in which group.
ax (None or matplotlib.Axes, optional) – Add to a existing set of axes.
- class quimb.tensor.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 thegauges
attribute. Before and after a gate is applied they are absorbed and then extracted. When accessing thestate
attribute they are automatically inserted or you can callget_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 tomax_bond
. By defaultcontract
is set to ‘reduce-split’ andcutoff
is set to0.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 inordering
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 defaultmax_bond
is set tomax(8, D**2)
whereD
is the maximum bond to use for applying the gate,cutoff
is set to0.0
andnormalized
is set toTrue
.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 toTrue
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:
- ham¶
The Hamiltonian being used to evolve.
- Type:
- energy¶
The current of the current state, this will trigger a computation if the energy at this iteration hasn’t been computed yet.
- Type:
- its¶
The corresponding sequence of iteration numbers that energies have been computed at.
- taus¶
The corresponding sequence of time steps that energies have been computed at.
- best¶
If
keep_best
was set then the best recorded energy and the corresponding state that was computed - keys'energy'
and'state'
respectively.- Type:
- gauge_renorm = True¶
- gauge_smudge = 1e-06¶
- condition_tensors = True¶
- condition_balance_bonds = True¶
- long_range_path_sequence = 'random'¶
- 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¶
- gate(U, where)[source]¶
Like
TEBD2D.gate
but absorb and extract the relevant gauges before and after each gate application.
- 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')¶
- _site_ind_id = 'k{},{},{}'¶
- _site_tag_id = 'I{},{},{}'¶
- _x_tag_id = 'X{}'¶
- _y_tag_id = 'Y{}'¶
- _z_tag_id = 'Z{}'¶
- _Lx¶
- _Ly¶
- _Lz¶
- 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:
- classmethod empty(Lx, Ly, Lz, bond_dim, phys_dim=2, like='numpy', **peps3d_opts)[source]¶
Create an empty 3D PEPS.
- Parameters:
- Returns:
psi
- Return type:
See also
- 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:
- Returns:
psi
- Return type:
See also
- 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:
See also
- 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]¶
Compute the approximate reduced density matrix at sites
where
by contracting a local cluster of tensors, potentially gauging the region with the simple update style bond gauges ingauges
.- Parameters:
where (sequence[node]) – The sites to keep.
gauges (dict[str, array_like], optional) – The store of gauge bonds, the keys being indices and the values being the vectors. Only bonds present in this dictionary will be used.
optimize (str or PathOptimizer, optional) – The contraction path optimizer to use, when exactly contracting the local tensors.
normalized (bool or "return", optional) – Whether to normalize the result. If “return”, return the norm separately.
max_distance (int, optional) – The maximum graph distance to include tensors neighboring
where
when computing the expectation. The default 0 means only the tensors at siteswhere
are used, 1 includes there direct neighbors, etc.mode ({'graphdistance', 'loopunion'}, optional) – How to select the local tensors, either by graph distance or by selecting the union of all loopy regions containing
where
, of size up tomax_distance
, ensuring no dangling tensors.fillin (bool or int, optional) – When selecting the local tensors, whether and how many times to ‘fill-in’ corner tensors attached multiple times to the local region. On a lattice this fills in the corners. See
select_local()
.grow_from ({"all", "any"}, optional) – If mode is ‘loopunion’, whether each loop should contain all of the initial tagged tensors, or just any of them (generating a larger region).
smudge (float, optional) – A small value to add to the gauges before multiplying them in and inverting them to avoid numerical issues.
power (float, optional) – The power to raise the singular values to before multiplying them in and inverting them.
get ({'matrix', 'array', 'tensor'}, optional) – Whether to return the result as a fused matrix (i.e. always 2D), unfused array, or still labeled Tensor.
rehearse (bool, optional) – Whether to perform the computation or not, if
True
return a rehearsal info dict.contract_opts – Supplied to
contract()
.
- 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 inkeep
.reduce (bool, optional) – Whether to first ‘pull’ the physical indices off their respective tensors using QR reduction. Experimental.
normalized (bool, optional) – Whether to normalize the reduced density matrix at the end.
symmetrized ({'auto', True, False}, optional) – Whether to symmetrize the reduced density matrix at the end. This should be unecessary if
flatten
is set toTrue
.rehearse ({False, 'tn', 'tree', True}, optional) –
Whether to perform the computation or not:
- False: perform the computation. - 'tn': return the tensor network without running the path optimizer. - 'tree': run the path optimizer and return the ``cotengra.ContractonTree``.. - True: run the path optimizer and return the ``PathInfo``.
contract_compressed_opts (dict, optional) – Additional keyword arguments to pass to
contract_compressed()
.
- Returns:
rho – The reduce density matrix of sites in
keep
.- Return type:
array_like
- 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 toTrue
.return_all (bool, optional) – Whether to return all results, or just the summed expectation. If
rehease is not False
, this is ignored and a dict is always returned.rehearse ({False, 'tn', 'tree', True}, optional) –
Whether to perform the computations or not:
- False: perform the computation. - 'tn': return the tensor networks of each local expectation, without running the path optimizer. - 'tree': run the path optimizer and return the ``cotengra.ContractonTree`` for each local expectation. - True: run the path optimizer and return the ``PathInfo`` for each local expectation.
executor (Executor, optional) – If supplied compute the terms in parallel using this executor.
progbar (bool, optional) – Whether to show a progress bar.
contract_compressed_opts – Supplied to
contract_compressed()
.
- Returns:
expecs – If
return_all==False
, return the summed expectation value of the given terms. Otherwise, return a dictionary mapping each term’s location to the expectation value.- Return type:
- 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.
- _NDIMS = 3¶
- _EXTRA_PROPS = ('_site_tag_id', '_x_tag_id', '_y_tag_id', '_z_tag_id', '_Lx', '_Ly', '_Lz')¶
- _compatible_3d(other)[source]¶
Check whether
self
andother
are compatible 3D tensor networks such that they can remain a 3D tensor network when combined.
- combine(other, *, virtual=False, check_collisions=True)[source]¶
Combine this tensor network with another, returning a new tensor network. If the two are compatible, cast the resulting tensor network to a
TensorNetwork3D
instance.- Parameters:
other (TensorNetwork3D or TensorNetwork) – The other tensor network to combine with.
virtual (bool, optional) – Whether the new tensor network should copy all the incoming tensors (
False
, the default), or view them as virtual (True
).check_collisions (bool, optional) – Whether to check for index collisions between the two tensor networks before combining them. If
True
(the default), any inner indices that clash will be mangled.
- Return type:
- property Lx¶
The number of 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.
- maybe_convert_coo(coo)[source]¶
Check if
coo
is a tuple of three ints and convert to the corresponding site tag if so.
- _get_tids_from_tags(tags, which='all')[source]¶
This is the function that lets coordinates such as
(i, j, k)
be used for many ‘tag’ based functions.
- valid_coo(coo, xrange=None, yrange=None, zrange=None)[source]¶
Check whether
coo
is in-bounds.- Parameters:
- Return type:
- get_ranges_present()[source]¶
Return the range of site coordinates present in this TN.
- Returns:
xrange, yrange, zrange – The minimum and maximum site coordinates present in each direction.
- Return type:
Examples
>>> tn = qtn.TN3D_rand(4, 4, 4, 2) >>> tn_sub = tn.select_local('I1,2,3', max_distance=1) >>> tn_sub.get_ranges_present() ((0, 2), (1, 3), (2, 3))
- is_cyclic_x(j=None, k=None, imin=None, imax=None)[source]¶
Check if the x dimension is cyclic (periodic), specifically whether a bond exists between
(imin, j, k)
and(imax, j, k)
, with default values ofimin = 0
andimax = Lx - 1
, andj
andk
the center of the lattice. Ifimin
andimax
are adjacent then this is considered False, since there is no ‘extra’ connectivity.
- is_cyclic_y(k=None, i=None, jmin=None, jmax=None)[source]¶
Check if the y dimension is cyclic (periodic), specifically whether a bond exists between
(i, jmin, k)
and(i, jmax, k)
, with default values ofjmin = 0
andjmax = Ly - 1
, andi
andk
the center of the lattice. Ifjmin
andjmax
are adjacent then this is considered False, since there is no ‘extra’ connectivity.
- is_cyclic_z(i=None, j=None, kmin=None, kmax=None)[source]¶
Check if the z dimension is cyclic (periodic), specifically whether a bond exists between
(i, j, kmin)
and(i, j, kmax)
, with default values ofkmin = 0
andkmax = Lz - 1
, andi
andj
the center of the lattice. Ifkmin
andkmax
are adjacent then this is considered False, since there is no ‘extra’ connectivity.
- _repr_info()[source]¶
General info to show in various reprs. Sublasses can add more relevant info to this dict.
- flatten(fuse_multibonds=True, inplace=False)[source]¶
Contract all tensors corresponding to each site into one.
- gen_pairs(xrange=None, yrange=None, zrange=None, xreverse=False, yreverse=False, zreverse=False, coordinate_order='xyz', xstep=None, ystep=None, zstep=None, stepping_order='xyz', step_only=None)[source]¶
Helper function for generating pairs of cooordinates for all bonds within a certain range, optionally specifying an order.
- Parameters:
xrange ((int, int), optional) – The range of allowed values for the x, y, and z coordinates.
yrange ((int, int), optional) – The range of allowed values for the x, y, and z coordinates.
zrange ((int, int), optional) – The range of allowed values for the x, y, and z coordinates.
xreverse (bool, optional) – Whether to reverse the order of the x, y, and z sweeps.
yreverse (bool, optional) – Whether to reverse the order of the x, y, and z sweeps.
zreverse (bool, optional) – Whether to reverse the order of the x, y, and z sweeps.
coordinate_order (str, optional) – The order in which to sweep the x, y, and z coordinates. Earlier dimensions will change slower. If the corresponding range has size 1 then that dimension doesn’t need to be specified.
xstep (int, optional) – When generating a bond, step in this direction to yield the neighboring coordinate. By default, these follow
xreverse
,yreverse
, andzreverse
respectively.ystep (int, optional) – When generating a bond, step in this direction to yield the neighboring coordinate. By default, these follow
xreverse
,yreverse
, andzreverse
respectively.zstep (int, optional) – When generating a bond, step in this direction to yield the neighboring coordinate. By default, these follow
xreverse
,yreverse
, andzreverse
respectively.stepping_order (str, optional) – The order in which to step the x, y, and z coordinates to generate bonds. Does not need to include all dimensions.
step_only (int, optional) – Only perform the ith steps in
stepping_order
, used to interleave canonizing and compressing for example.
- Yields:
coo_a, coo_b (((int, int, int), (int, int, int)))
- canonize_plane(xrange, yrange, zrange, equalize_norms=False, canonize_opts=None, **gen_pair_opts)[source]¶
Canonize every pair of tensors within a subrange, optionally specifying a order to visit those pairs in.
- compress_plane(xrange, yrange, zrange, max_bond=None, cutoff=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 byfrom_which
.
- _maybe_compute_cell_env(key, envs=None, storage_factory=None, boundary_order=None, **contract_boundary_opts)[source]¶
Recursively compute the necessary 2D, 1D, and 0D environments.
- coarse_grain_hotrg(direction, max_bond=None, cutoff=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:
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:
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 returnsTrue
if this is to be a valid starting coordinate.
- Yields:
bond (tuple[tuple[int, int, int], tuple[int, int, int]]) – A pair of coordinates.
Examples
Generate nearest neighbor bonds:
>>> for bond in gen_3d_bonds(2, 2, 2, [lambda i, j, k: (i + 1, j, k), ... lambda i, j, k: (i, j + 1, k), ... lambda i, j, k: (i, j, k + 1)]): ... print(bond) ((0, 0, 0), (1, 0, 0)) ((0, 0, 0), (0, 1, 0)) ((0, 0, 0), (0, 0, 1)) ((0, 0, 1), (1, 0, 1)) ((0, 0, 1), (0, 1, 1)) ((0, 1, 0), (1, 1, 0)) ((0, 1, 0), (0, 1, 1)) ((0, 1, 1), (1, 1, 1)) ((1, 0, 0), (1, 1, 0)) ((1, 0, 0), (1, 0, 1)) ((1, 0, 1), (1, 1, 1)) ((1, 1, 0), (1, 1, 1))
- 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 keyNone
.
- terms¶
The total effective local term for each interaction (with single site terms appropriately absorbed). Each key is a pair of coordinates
site_a, site_b
withsite_a < site_b
.
- Lx¶
- Ly¶
- Lz¶
- property nsites¶
The number of sites in the system.
- quimb.tensor.tensor_network_align(*tns: TensorNetworkGen, 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 aup_ind_id
andlower_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_op(A: TensorNetworkGenOperator, B: TensorNetworkGenOperator, 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 networkB
. The resulting tensor network has the same upper and lower indices asB
. 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 ofwhich_A
andwhich_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
, wheretn
is the resulting tensor network, ifcompress=True
.
- Returns:
The same type as
B
.- Return type:
- quimb.tensor.tensor_network_apply_op_vec(A: TensorNetworkGenOperator, x: TensorNetworkGenVector, 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
andlower_ind_id
) to a tensor network representing a vector (hassite_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 asx
, and it is thelower_ind_id
ofA
that is contracted.This is like performing
A.to_dense() @ x.to_dense()
, or the transpose thereof, depending on the value ofwhich_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 ofx
.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
, wheretn
is the resulting tensor network, ifcompress=True
.
- Returns:
The same type as
x
.- Return type:
- 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 keyNone
.
- terms¶
The total effective local term for each interaction (with single site terms appropriately absorbed). Each key is a pair of coordinates
site_a, site_b
withsite_a < site_b
.
- _op_cache¶
- terms¶
- sites¶
- _sites_to_covering_terms¶
- property nsites¶
The number of sites in the system.
- items()[source]¶
Iterate over all terms in the hamiltonian. This is mostly for convenient compatibility with
compute_local_expectation
.
- get_gate_expm(where, x)[source]¶
Get the local term for pair
where
, matrix exponentiated byx
, and cached.
- 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 thisLocalHam2D
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:
- 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, cutoff=1e-10, 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, tol=None, equilibrate_every=0, equilibrate_start=True, equilibrate_opts=None, callback=None, keep_best=False, progbar=True)[source]¶
Bases:
TEBDGen
Simple update for arbitrary geometry hamiltonians.
- Parameters:
psi0 (TensorNetworkGenVector) – The initial state.
ham (LocalHamGen) – The local hamiltonian.
tau (float, optional) – The default time step to use.
D (int, optional) – The maximum bond dimension, by default the current maximum bond of
psi0
.cutoff (float, optional) – The singular value cutoff to use when applying gates.
imag (bool, optional) – Whether to evolve in imaginary time (default) or real time.
gate_opts (dict, optional) – Other options to supply to the gate application method,
quimb.tensor.tensor_arbgeom.TensorNetworkGenVector.gate_simple_()
.ordering (None, str or callable, optional) – The ordering of the terms to apply, by default this will be determined automatically.
second_order_reflect (bool, optional) – Whether to use a second order Trotter decomposition by reflecting the ordering.
compute_energy_every (int, optional) – Compute the energy every this many steps.
compute_energy_final (bool, optional) – Whether to compute the energy at the end.
compute_energy_opts (dict, optional) – Options to supply to the energy computation method,
quimb.tensor.tensor_arbgeom.TensorNetworkGenVector.compute_local_expectation_cluster()
.compute_energy_fn (callable, optional) – A custom function to compute the energy, with signature
fn(su)
, wheresu
is this instance.compute_energy_per_site (bool, optional) – Whether to compute the energy per site.
tol (float, optional) – If not
None
, stop when either energy difference falls below this value, or maximum singluar value changes fall below this value.equilibrate_every (int, optional) – Equilibrate the gauges every this many steps.
equilibrate_start (bool, optional) – Whether to equilibrate the gauges at the start, regardless of
equilibrate_every
.equilibrate_opts (dict, optional) – Default options to supply to the gauge equilibration method, see
quimb.tensor.tensor_core.TensorNetwork.gauge_all_simple()
. By default max_iterations is set to 100 and tol to 1e-3.callback (callable, optional) – A function to call after each step, with signature
fn(su)
.keep_best (bool, optional) – Whether to keep track of the best state and energy.
progbar (bool, optional) – Whether to show a progress bar during evolution.
- equilibrate_every = 0¶
- equilibrate_start = True¶
- equilibrate_opts¶
- gauges_prev = None¶
- gauge_diffs = []¶
- equilibrate(**kwargs)[source]¶
Equilibrate the gauges with the current state (like evolving with tau=0).
- get_state(absorb_gauges=True)[source]¶
Return the current state, possibly absorbing the gauges.
- Parameters:
absorb_gauges (bool or "return", optional) – Whether to absorb the gauges into the state or not. If True, a standard PEPS is returned with the gauges absorbed. If False`, the gauges are added to the tensor network but uncontracted. If “return”, the gauges are returned separately.
- Returns:
psi (TensorNetwork) – The current state.
gauges (dict) – The current gauges, if
absorb_gauges == "return"
.
- class quimb.tensor.TEBDGen(psi0, ham, tau=0.01, D=None, cutoff=1e-10, 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, tol=None, 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.
- imag = True¶
- property state¶
Return a copy of the current state.
- ham¶
- progbar = True¶
- callback = None¶
- tau = 0.01¶
- last_tau = 0.0¶
- gate_opts¶
- compute_energy_opts¶
- compute_energy_every = None¶
- compute_energy_final = True¶
- compute_energy_fn = None¶
- compute_energy_per_site = False¶
- tol = None¶
- second_order_reflect = False¶
- _n = 0¶
- its = []¶
- taus = []¶
- energies = []¶
- energy_diffs = []¶
- egrdm¶
- keep_best = False¶
- best¶
- stop = False¶
- sweep(tau)[source]¶
Perform a full sweep of gates at every pair.
\[\psi \rightarrow \prod_{\{ij\}} \exp(-\tau H_{ij}) \psi\]
- evolve(steps, tau=None, progbar=None)[source]¶
Evolve the state with the local Hamiltonian for
steps
steps with time steptau
.
- 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.
- 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 update is nothing.
- postlayer()[source]¶
Perform any computations required after each layer of commuting gates. For the basic update this is nothing.
- postsweep(i)[source]¶
Perform any computations required after the sweep (but before the energy computation). For the basic update this is nothing.
- gate(U, where)[source]¶
Perform single gate
U
at coordinate pairwhere
. 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.
- plot(zoom='auto', xscale='symlog', xscale_linthresh=20, color_energy=(0.0, 0.5, 1.0), color_gauge_diff=(1.0, 0.5, 0.0), hlines=(), figsize=(8, 4))[source]¶
Plot an overview of the evolution of the energy and gauge diffs.
- Parameters:
zoom (int or 'auto', optional) – The number of iterations to zoom in on, or ‘auto’ to automatically choose a reasonable zoom level.
xscale ({'linear', 'log', 'symlog'}, optional) – The x-axis scale, for the upper plot of the entire evolution.
xscale_linthresh (float, optional) – The linear threshold for the upper symlog scale.
color_energy (str or tuple, optional) – The color to use for the energy plot.
color_gauge_diff (str or tuple, optional) – The color to use for the gauge diff plot.
hlines (dict, optional) – Add horizontal lines to the plot, with keys as labels and values as the y-values.
figsize (tuple, optional) – The size of the figure.
- Returns:
fig, axs
- Return type:
matplotlib.Figure, tuple[matplotlib.Axes]
- quimb.tensor.edge_coloring(edges, strategy='smallest_last', interchange=True, group=True)[source]¶
Generate an edge coloring for the graph given by
edges
, usingnetworkx.coloring.greedy_color
.- Parameters:
edges (sequence[tuple[hashable, hashable]]) – The edges of the graph.
strategy (str or callable, optional) –
The strategy to use for coloring the edges. Can be:
’largest_first’
’smallest_last’
’random_sequential’
…
interchange (bool, optional) – Whether to use the interchange heuristic. Usually generates better colorings but can be slower.
group (bool, optional) – Whether to group the edges by color or return a flat list.
- quimb.tensor.MPS_COPY(L, phys_dim=2, dtype='float64', **mps_opts)[source]¶
Build a matrix product state representation of the COPY tensor.
- Parameters:
- Return type:
- quimb.tensor.HTN2D_classical_ising_partition_function(Lx, Ly, beta, h=0.0, j=1.0, cyclic=False, ind_id='s{},{}', site_tag_id='I{},{}')[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.site_tag_id (str, optional) – How to label the site tags, note that in the hyper tensor network representation each tensor will have two site tags for the two sites it connects.
- Return type:
- quimb.tensor.HTN3D_classical_ising_partition_function(Lx, Ly, Lz, beta, j=1.0, h=0.0, cyclic=False, ind_id='s{},{},{}', site_tag_id='I{},{},{}')[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.site_tag_id (str, optional) – How to label the site tags, note that in the hyper tensor network representation each tensor will have two site tags for the two sites it connects.
- Return type:
- 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:
- 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:
- 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, orweights=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:
- 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:
- quimb.tensor.HTN_rand(n, reg, n_out=0, n_hyper_in=0, n_hyper_out=0, d_min=2, d_max=3, seed=None, dtype='float64', dist='normal', scale=1.0, loc=0.0, site_ind_id='k{}')[source]¶
Create a random, possibly hyper, tensor network, with a mix of normal and hyper inner and outer indices. Useful for testing edges cases.
- Parameters:
n (int) – The number of tensors.
reg (int) – The average degree (number of dimensions per tensor) of the tensor network (prior to placing extra indices).
n_out (int, optional) – The number of normal outer indices to add (i.e. appear exactly once).
n_hyper_in (int, optional) – The number of hyper inner indices to add (i.e. appear on three or more tensors).
n_hyper_out (int, optional) – The number of hyper outer indices to add (i.e. appear in output and two or more tensors).
d_min (int, optional) – The minimum size of any dimension.
d_max (int, optional) – The maximum size of any dimension.
seed (int, optional) – A random seed.
- Return type:
- 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:
- 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:
- 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:
- 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:
- 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:
- quimb.tensor.MPO_identity(L, sites=None, 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:
- 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:
- 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:
- 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.
- 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 sized
.
- 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
.
- 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:
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
- S = 0.5¶
- one_site_terms = []¶
- two_site_terms = []¶
- cyclic = False¶
- var_one_site_terms¶
- var_two_site_terms¶
- 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.
- __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)[source]¶
Build an MPO instance of this spin hamiltonian of size
L
. See alsoMatrixProductOperator
.
- build_local_ham(L=None, **local_ham_1d_opts)[source]¶
Build a nearest neighbour interactor instance of this spin hamiltonian of size
L
. See alsoLocalHam1D
.- Parameters:
L (int, optional) – The number of spins, if the hamiltonian only has two-site terms this is optional.
- Return type:
- 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 inoutputs
.
- Return type:
- 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. If2
, 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:
See also
- 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 onsites_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. IfJ
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 inoutputs
.
- Return type:
- 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:
- 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:
- 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:
- 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:
- 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 usesnumpy.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:
- 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 inoutputs
.
- Return type:
- 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:
- 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:
- 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:
- 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 usesnumpy.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:
- 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:
- 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:
- 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 oflen(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:
- 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:
- Return type:
- 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_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 dimensionmax_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, usestn.site_tags
. The tensor network built will have one tensor per site, in the order given bysite_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:
- 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 ofn
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, max_degree=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 ofn
sites.max_degree (int, optional) – The maximum degree of any node in the tree, for example 3 means that each tensor can connect to at most 3 other tensors - creating a binary tree (1 parent and two children).
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}
, wheresigned_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
andwn_i
are the positive and negative weights for variablei
. Weights specified this way are overriden by the previous two formats.
- 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 aTensorNetwork2D
, 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 aTensorNetwork3D
, 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:
- 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:
- 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:
- 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:
- 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:
- Return type:
- 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:
- Return type:
- 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:
- 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:
- 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
.
- 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:
- 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:
- 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 dimensionslen(inds)
, with exterior indicesinds
.- Parameters:
- Returns:
The tensor describing the MPS, of size
d**len(inds)
.- Return type:
- class quimb.tensor.IsoTensor(data=1.0, inds=(), tags=None, left_inds=None)[source]¶
Bases:
Tensor
A
Tensor
subclass which keeps itsleft_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:
- 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)
, seeTensor
.tags (optional) – See
Tensor
.left_inds (optional) – See
Tensor
.
See also
- __slots__ = ('_data', '_inds', '_tags', '_left_inds', '_owners')¶
- property data¶
- property fn¶
- property params¶
- property shape¶
The size of each dimension.
- property backend¶
The backend inferred from the data.
- _apply_function(fn)[source]¶
Apply
fn
to the data array of thisPTensor
(lazily), by composing it with the current parametrized array function.
- 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'})
- __slots__ = ('_data', '_inds', '_tags', '_left_inds', '_owners')¶
- _owners¶
- get_params()[source]¶
A simple function that returns the ‘parameters’ of the underlying data array. This is mainly for providing an interface for ‘structured’ arrays e.g. with block sparsity to interact with optimization.
- set_params(params)[source]¶
A simple function that sets the ‘parameters’ of the underlying data array. This is mainly for providing an interface for ‘structured’ arrays e.g. with block sparsity to interact with optimization.
- copy(deep=False, virtual=False)[source]¶
Copy this tensor.
Note
By default (
deep=False
), the underlying array will not be copied.
- property data¶
- property inds¶
- property tags¶
- property left_inds¶
- property owners¶
- add_owner(tn, tid)[source]¶
Add
tn
as owner of this Tensor - it’s tag and ind maps will be updated whenever this tensor is retagged or reindexed.
- check_owners()[source]¶
Check if this tensor is ‘owned’ by any alive TensorNetworks. Also trim any weakrefs to dead TensorNetworks.
- modify(**kwargs)[source]¶
Overwrite the data of this tensor in place.
- Parameters:
data (array, optional) – New data.
apply (callable, optional) – A function to apply to the current data. If data is also given this is applied subsequently.
inds (sequence of str, optional) – New tuple of indices.
tags (sequence of str, optional) – New tags.
left_inds (sequence of str, optional) – New grouping of indices to be ‘on the left’.
- apply_to_arrays(fn)[source]¶
Apply the function
fn
to the underlying data array(s). This is meant for changing how the raw arrays are backed (e.g. converting between dtypes or libraries) but not their ‘numerical meaning’.
- isel(selectors, inplace=False)[source]¶
Select specific values for some dimensions/indices of this tensor, thereby removing them. Analogous to
X[:, :, 3, :, :]
with arrays. The indices to select from can be specified either by integer, in which case the correspoding index is removed, or by a slice.- Parameters:
selectors (dict[str, int or slice or "r"]) –
Mapping of index(es) to which value to take. The values can be:
int: select a specific value for that index.
slice: select a range of values for that index.
”r”: contract a random vector in.
The mapping can contain indices that don’t appear on this tensor, in which case they are ignored.
inplace (bool, optional) – Whether to select inplace or not.
- Return type:
Examples
>>> T = rand_tensor((2, 3, 4), inds=('a', 'b', 'c')) >>> T.isel({'b': -1}) Tensor(shape=(2, 4), inds=('a', 'c'), tags=())
See also
- add_tag(tag)[source]¶
Add a tag or multiple tags to this tensor. Unlike
self.tags.add
this also updates anyTensorNetwork
objects viewing thisTensor
.
- expand_ind(ind, size, mode=None, rand_strength=None, rand_dist='normal')[source]¶
Inplace increase the size of the dimension of
ind
, the new array entries will be filled with zeros by default.- Parameters:
name (str) – Name of the index to expand.
size (int, optional) – Size of the expanded index.
mode ({None, 'zeros', 'repeat', 'random'}, optional) – How to fill any new array entries. If
'zeros'
then fill with zeros, if'repeat'
then repeatedly tile the existing entries. If'random'
then fill with random entries drawn fromrand_dist
, multiplied byrand_strength
. IfNone
then select from zeros or random depening on non-zerorand_strength
.rand_strength (float, optional) – If
mode='random'
, a multiplicative scale for the random entries, defaulting to 1.0. Ifmode is None
then supplying a non-zero value here triggersmode='random'
.rand_dist ({'normal', 'uniform', 'exp'}, optional) – If
mode='random'
, the distribution to draw the random entries from.
- new_ind(name, size=1, axis=0, mode=None, rand_strength=None, rand_dist='normal')[source]¶
Inplace add a new index - a named dimension. If
size
is specified to be greater than one then the new array entries will be filled with zeros.- Parameters:
name (str) – Name of the new index.
size (int, optional) – Size of the new index.
axis (int, optional) – Position of the new index.
mode ({None, 'zeros', 'repeat', 'random'}, optional) – How to fill any new array entries. If
'zeros'
then fill with zeros, if'repeat'
then repeatedly tile the existing entries. If'random'
then fill with random entries drawn fromrand_dist
, multiplied byrand_strength
. IfNone
then select from zeros or random depening on non-zerorand_strength
.rand_strength (float, optional) – If
mode='random'
, a multiplicative scale for the random entries, defaulting to 1.0. Ifmode is None
then supplying a non-zero value here triggersmode='random'
.rand_dist ({'normal', 'uniform', 'exp'}, optional) – If
mode='random'
, the distribution to draw the random entries from.
See also
- new_ind_with_identity(name, left_inds, right_inds, axis=0)[source]¶
Inplace add a new index, where the newly stacked array entries form the identity from
left_inds
toright_inds
. Selecting 0 or 1 for the new indexname
thus is like ‘turning off’ this tensor if viewed as an operator.- Parameters:
name (str) – Name of the new index.
left_inds (tuple[str]) – Names of the indices forming the left hand side of the operator.
right_inds (tuple[str]) – Names of the indices forming the right hand side of the operator. The dimensions of these must match those of
left_inds
.axis (int, optional) – Position of the new index.
- new_ind_pair_with_identity(new_left_ind, new_right_ind, d, inplace=False)[source]¶
Expand this tensor with two new indices of size
d
, by taking an (outer) tensor product with the identity operator. The two new indices are added as axes at the start of the tensor.
- property H¶
Conjugate this tensors data (does nothing to indices).
- property shape¶
The size of each dimension.
- property ndim¶
The number of dimensions.
- property size¶
The total number of array elements.
- property dtype¶
The data type of the array elements.
- property dtype_name¶
The name of the data type of the array elements.
- property backend¶
The backend inferred from the data.
Get the total size of the shared index(es) with
other
.
- transpose(*output_inds, inplace=False)[source]¶
Transpose this tensor - permuting the order of both the data and the indices. This operation is mainly for ensuring a certain data layout since for most operations the specific order of indices doesn’t matter.
Note to compute the tranditional ‘transpose’ of an operator within a contraction for example, you would just use reindexing not this.
- Parameters:
- Returns:
tt – The transposed tensor.
- Return type:
See also
- transpose_like(other, inplace=False)[source]¶
Transpose this tensor to match the indices of
other
, allowing for one index to be different. E.g. ifself.inds = ('a', 'b', 'c', 'x')
andother.inds = ('b', 'a', 'd', 'c')
then ‘x’ will be aligned with ‘d’ and the output inds will be('b', 'a', 'x', 'c')
- Parameters:
- Returns:
tt – The transposed tensor.
- Return type:
See also
- moveindex(ind, axis, inplace=False)[source]¶
Move the index
ind
to positionaxis
. Liketranspose
, this permutes the order of both the data and the indices and is mainly for ensuring a certain data layout since for most operations the specific order of indices doesn’t matter.
- trace(left_inds, right_inds, preserve_tensor=False, inplace=False)[source]¶
Trace index or indices
left_inds
withright_inds
, removing them.- Parameters:
left_inds (str or sequence of str) – The left indices to trace, order matching
right_inds
.right_inds (str or sequence of str) – The right indices to trace, order matching
left_inds
.preserve_tensor (bool, optional) – If
True
, a tensor will be returned even if no indices remain.inplace (bool, optional) – Perform the trace inplace.
- Returns:
z
- Return type:
Tensor or scalar
- vector_reduce(ind, v, inplace=False)[source]¶
Contract the vector
v
with the indexind
of this tensor, removing it.
- rand_reduce(ind, dtype=None, inplace=False, **kwargs)[source]¶
Contract the index
ind
of this tensor with a random vector, removing it.
- collapse_repeated(inplace=False)[source]¶
Take the diagonals of any repeated indices, such that each index only appears once.
- gate(G, ind, preserve_inds=True, transposed=False, 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. This is like applying:\[x \leftarrow G x\]or if
transposed=True
:\[x \leftarrow x G\]- Parameters:
G (2D array_like) – The matrix to gate the tensor index with.
ind (str) – Which index to apply the gate to.
preserve_inds (bool, optional) – If
True
, the order of the indices is preserved, otherwise the gated index will be left at the first axis, avoiding a transpose.transposed (bool, optional) – If
True
, the gate is effectively transpose and applied, or equivalently, contracted to its left rather than right.
- Return type:
Examples
Create a random tensor of 4 qubits:
>>> t = qtn.rand_tensor( ... shape=[2, 2, 2, 2], ... inds=['k0', 'k1', 'k2', 'k3'], ... )
Create another tensor with an X gate applied to qubit 2:
>>> Gt = t.gate(qu.pauli('X'), 'k2')
The contraction of these two tensors is now the expectation of that operator:
>>> t.H @ Gt -4.108910576149794
- singular_values(left_inds, method='svd')[source]¶
Return the singular values associated with splitting this tensor according to
left_inds
.- Parameters:
left_inds (sequence of str) – A subset of this tensors indices that defines ‘left’.
method ({'svd', 'eig'}) – Whether to use the SVD or eigenvalue decomposition to get the singular values.
- Returns:
The singular values.
- Return type:
1d-array
- entropy(left_inds, method='svd')[source]¶
Return the entropy associated with splitting this tensor according to
left_inds
.
- retag(retag_map, inplace=False)[source]¶
Rename the tags of this tensor, optionally, 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:
- unfuse(unfuse_map, shape_map, inplace=False)[source]¶
Reshape single indices into groups of multiple indices
- Parameters:
unfuse_map (dict_like or sequence of tuples.) – Mapping like:
{existing_ind: sequence of new inds, ...}
or an ordered mapping like[(old_ind_1, new_inds_1), ...]
in which case the output tensor’s new inds will be ordered. In both cases the new indices are created at the old index’s position of the tensor’s shapeshape_map (dict_like or sequence of tuples) – Mapping like:
{old_ind: new_ind_sizes, ...}
or an ordered mapping like[(old_ind_1, new_ind_sizes_1), ...]
.
- Returns:
The transposed, reshaped and re-labeled tensor
- Return type:
- to_dense(*inds_seq, to_qarray=False)[source]¶
Convert this Tensor into an dense array, with a single dimension for each of inds in
inds_seqs
. E.g. to convert several sites into a density matrix:T.to_dense(('k0', 'k1'), ('b0', 'b1'))
.
- squeeze(include=None, exclude=None, inplace=False)[source]¶
Drop any singlet dimensions from this tensor.
- Parameters:
inplace (bool, optional) – Whether modify the original or return a new tensor.
include (sequence of str, optional) – Only squeeze dimensions with indices in this list.
exclude (sequence of str, optional) – Squeeze all dimensions except those with indices in this list.
inplace – Whether to perform the squeeze inplace or not.
- Return type:
- largest_element()[source]¶
Return the largest element, in terms of absolute magnitude, of this tensor.
- idxmin(f=None)[source]¶
Get the index configuration of the minimum element of this tensor, optionally applying
f
first.
- idxmax(f=None)[source]¶
Get the index configuration of the maximum element of this tensor, optionally applying
f
first.
- norm(squared=False, **contract_opts)[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.
- overlap(other, **contract_opts)[source]¶
Overlap of this tensor with another tensor:
\[\langle o | t \rangle = \mathrm{Tr} \left(o^{\dagger} t\right)\]where the trace is taken over all indices.
- Parameters:
other (Tensor or TensorNetwork) – The other tensor or network to overlap with. This tensor will be conjugated.
- Return type:
scalar
- symmetrize(ind1, ind2, inplace=False)[source]¶
Hermitian symmetrize this tensor for indices
ind1
andind2
. I.e.T = (T + T.conj().T) / 2
, where the transpose is taken only over the specified indices.
- isometrize(left_inds=None, method='qr', inplace=False)[source]¶
Make this tensor unitary (or isometric) with respect to
left_inds
. The underlying method is set bymethod
.- Parameters:
left_inds (sequence of str) – The indices to group together and treat as the left hand side of a matrix.
method (str, optional) –
The method used to generate the isometry. The options are:
”qr”: use the Q factor of the QR decomposition of
x
with the constraint that the diagonal ofR
is positive.”svd”: uses
U @ VH
of the SVD decomposition ofx
. This is useful for finding the ‘closest’ isometric matrix tox
, such as when it has been expanded with noise etc. But is less stable for differentiation / optimization.”exp”: use the matrix exponential of
x - dag(x)
, first completingx
with zeros if it is rectangular. This is a good parametrization for optimization, but more expensive for non-squarex
.”cayley”: use the Cayley transform of
x - dag(x)
, first completingx
with zeros if it is rectangular. This is a good parametrization for optimization (one the few compatible with HIPS/autograd e.g.), but more expensive for non-squarex
.”householder”: use the Householder reflection method directly. This requires that the backend implements “linalg.householder_product”.
”torch_householder”: use the Householder reflection method directly, using the
torch_householder
package. This requires that the package is installed and that the backend is"torch"
. This is generally the best parametrizing method for “torch” if available.”mgs”: use a python implementation of the modified Gram Schmidt method directly. This is slow if not compiled but a useful reference.
Not all backends support all methods or differentiating through all methods.
inplace (bool, optional) – Whether to perform the unitization inplace.
- Return type:
- unitize_¶
- randomize(dtype=None, inplace=False, **randn_opts)[source]¶
Randomize the entries of this tensor.
- Parameters:
- Return type:
- flip(ind, inplace=False)[source]¶
Reverse the axis on this tensor corresponding to
ind
. Like performing e.g.X[:, :, ::-1, :]
.
- multiply_index_diagonal(ind, x, inplace=False)[source]¶
Multiply this tensor by 1D array
x
as if it were a diagonal tensor being contracted into indexind
.
- filter_bonds(other)[source]¶
Sort this tensor’s indices into a list of those that it shares and doesn’t share with another tensor.
- __or__(other)[source]¶
Combine virtually (no copies made) with another
Tensor
orTensorNetwork
into a newTensorNetwork
.
- __matmul__(other)[source]¶
Explicitly contract with another tensor. Avoids some slight overhead of calling the full
tensor_contract()
.
- _repr_info()[source]¶
General info to show in various reprs. Sublasses can add more relevant info to this dict.
- class quimb.tensor.TensorNetwork(ts=(), *, virtual=False, check_collisions=True)[source]¶
Bases:
object
A collection of (as yet uncontracted) Tensors.
- Parameters:
ts (sequence of Tensor or TensorNetwork) – The objects to combine. The new network will copy these (but not the underlying data) by default. For a view set
virtual=True
.virtual (bool, optional) – Whether the TensorNetwork should be a view onto the tensors it is given, or a copy of them. E.g. if a virtual TN is constructed, any changes to a Tensor’s indices or tags will propagate to all TNs viewing that Tensor.
check_collisions (bool, optional) – If True, the default, then
TensorNetwork
instances with double indices which match anotherTensorNetwork
instances double indices will have those indices’ names mangled. Can be explicitly turned off when it is known that no collisions will take place – i.e. when not adding any new tensors.
- tensor_map¶
Mapping of unique ids to tensors, like``{tensor_id: tensor, …}``. I.e. this is where the tensors are ‘stored’ by the network.
- Type:
- tag_map¶
Mapping of tags to a set of tensor ids which have those tags. I.e.
{tag: {tensor_id_1, tensor_id_2, ...}}
. Thus to select those tensors could do:map(tensor_map.__getitem__, tag_map[tag])
.- Type:
- ind_map¶
Like
tag_map
but for indices. Soind_map[ind]]
returns the tensor ids of those tensors withind
.- Type:
- exponent¶
A scalar prefactor for the tensor network, stored in base 10 like
10**exponent
. This is mostly for conditioning purposes and will be0.0
unless you use useequalize_norms(value)
ortn.strip_exponent(tid_or_tensor)
.- Type:
- _EXTRA_PROPS = ()¶
- _CONTRACT_STRUCTURED = False¶
- _tid_counter = 0¶
- tensor_map¶
- tag_map¶
- ind_map¶
- _inner_inds¶
- _outer_inds¶
- exponent = 0.0¶
- combine(other, *, virtual=False, check_collisions=True)[source]¶
Combine this tensor network with another, returning a new tensor network. This can be overriden by subclasses to check for a compatible structured type.
- Parameters:
other (TensorNetwork) – The other tensor network to combine with.
virtual (bool, optional) – Whether the new tensor network should copy all the incoming tensors (
False
, the default), or view them as virtual (True
).check_collisions (bool, optional) – Whether to check for index collisions between the two tensor networks before combining them. If
True
(the default), any inner indices that clash will be mangled.
- Return type:
- __and__(other)[source]¶
Combine this tensor network with more tensors, without contracting. Copies the tensors.
- __or__(other)[source]¶
Combine this tensor network with more tensors, without contracting. Views the constituent tensors.
- classmethod new(like=None, **kwargs)[source]¶
Create a new tensor network, without any tensors, of type
cls
, with all the requisite properties specified bykwargs
or inherited fromlike
.
- classmethod from_TN(tn, like=None, inplace=False, **kwargs)[source]¶
Construct a specific tensor network subclass (i.e. one with some promise about structure/geometry and tags/inds such as an MPS) from a generic tensor network which should have that structure already.
- Parameters:
cls (class) – The TensorNetwork subclass to convert
tn
to.tn (TensorNetwork) – The TensorNetwork to convert.
like (TensorNetwork, optional) – If specified, try and retrieve the neccesary attribute values from this tensor network.
inplace (bool, optional) – Whether to perform the conversion inplace or not.
kwargs – Extra properties of the TN subclass that should be specified.
- view_like(like, inplace=False, **kwargs)[source]¶
View this tensor network as the same subclass
cls
aslike
inheriting its extra properties as well.
- copy(virtual=False, deep=False)[source]¶
Copy this
TensorNetwork
. Ifdeep=False
, (the default), then everything but the actual numeric data will be copied.
- set_params(params)[source]¶
Take a pytree of the ‘parameters’, i.e. all underlying data arrays, as returned by
get_params
and set them.
- add_tensor(tensor, tid=None, virtual=False)[source]¶
Add a single tensor to this network - mangle its tid if neccessary.
- add(t, virtual=False, check_collisions=True)[source]¶
Add Tensor, TensorNetwork or sequence thereof to self.
- make_tids_consecutive(tid0=0)[source]¶
Reset the tids - node identifies - to be consecutive integers.
- __iand__(tensor)[source]¶
Inplace, but 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.
- property num_tensors¶
The total number of tensors in the tensor network.
- property num_indices¶
The total number of indices in the tensor network.
- add_tag(tag, where=None, which='all')[source]¶
Add tag to every tensor in this network, or if
where
is specified, the tensors matching those tags – i.e. adds the tag to all tensors inself.select_tensors(where, which=which)
.
- drop_tags(tags=None)[source]¶
Remove a tag or tags from this tensor network, defaulting to all. This is an inplace operation.
- retag(tag_map, inplace=False)[source]¶
Rename tags for all tensors in this network, optionally 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.
- conj(mangle_inner=False, output_inds=None, inplace=False)[source]¶
Conjugate all the tensors in this network (leave all outer indices).
- Parameters:
mangle_inner ({bool, str, None}, optional) – Whether to mangle the inner indices of the network. If a string is given, it will be appended to the index names.
output_inds (sequence of str, optional) – If given, the indices to mangle will be restricted to those not in this list. This is only needed for (hyper) tensor networks where output indices are not given simply by those that appear once.
inplace (bool, optional) – Whether to perform the conjugation inplace or not.
- Return type:
- property H¶
Conjugate all the tensors in this network (leaves all indices).
- largest_element()[source]¶
Return the ‘largest element’, in terms of absolute magnitude, of this tensor network. This is defined as the product of the largest elements of each tensor in the network, which would be the largest single term occuring if the TN was summed explicitly.
- make_norm(mangle_append='*', layer_tags=('KET', 'BRA'), output_inds=None, return_all=False)[source]¶
Make the norm (squared) tensor network of this tensor network
tn.H & tn
. This deterministally mangles the inner indices of the bra to avoid clashes with the ket, and also adds tags to the top and bottom layers. If the tensor network has hyper outer indices, you may need to specify the output indices. This allows ‘hyper’ norms.- 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.
output_inds (sequence of str, optional) – If given, the indices to mangle will be restricted to those not in this list. This is only needed for (hyper) tensor networks where output indices are not given simply by those that appear once.
return_all (bool, optional) – Return the norm, the ket and the bra. These are virtual, i.e. are views of the same tensors.
- Returns:
tn_norm
- Return type:
- norm(output_inds=None, squared=False, **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_overlap(other, layer_tags=('KET', 'BRA'), output_inds=None, return_all=False)[source]¶
Make the overlap tensor network of this tensor network with another tensor network other.H & self. This deterministally mangles the inner indices of the bra to avoid clashes with the ket, and also adds tags to the top and bottom layers. If the tensor network has hyper outer indices, you may need to specify the output indices. This allows ‘hyper’ overlaps.
- Parameters:
other (TensorNetwork) – The other tensor network to overlap with, it should have the same outer indices as this tensor network, all other indices will be explicitly mangled in the copy taken, allowing ‘hyper’ overlaps. This tensor network will be conjugated in the overlap.
layer_tags ((str, str), optional) – The tags to identify the top and bottom.
output_inds (sequence of str, optional) – If given, the indices to mangle will be restricted to those not in this list. This is only needed for (hyper) tensor networks where output indices are not given simply by those that appear once.
return_all (bool, optional) – Return the overlap, the ket and the bra. These are virtual, i.e. are views of the same tensors.
- Returns:
tn_overlap
- Return type:
- overlap(other, output_inds=None, **contract_opts)[source]¶
Overlap of this tensor network with another tensor network. Computed by exactly contracting the TN with the conjugate of the other TN:
\[\langle O, T \rangle = \mathrm{Tr} \left(O^{\dagger} T\right)\]where the trace is taken over all indices. This supports ‘hyper’ tensor networks, where the output indices are not simply those that appear once.
- Parameters:
other (TensorNetwork) – The other tensor network to overlap with, it should have the same outer indices as this tensor network, all other indices will be explicitly mangled in the copy taken, allowing ‘hyper’ overlaps. This tensor network will be conjugated in the overlap.
output_inds (sequence of str, optional) – If given, the indices to mangle will be restricted to those not in this list. This is only needed for (hyper) tensor networks where output indices are not given simply by those that appear once.
contract_opts – Supplied to
tensor_contract()
for the contraction.
- Return type:
scalar
- 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 factorfac
uniformly over all tensors in the network and the number of tensors is large, then callingmultiply(fac)
can be inaccurate due to precision loss. If one has a routine that can precisely compute thex
to be applied to each tensor, then this function avoids the potential inaccuracies inmultiply()
.- Parameters:
x (scalar) – The number that multiplies each tensor in the network
inplace (bool, optional) – Whether to perform the multiplication inplace.
- 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.
- 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.See also
- 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:
Examples
>>> tn = qtn.TN_rand_reg(10, 3, 2) >>> tn.get_equation() 'abc,dec,fgb,hia,jke,lfk,mnj,ing,omd,ohl->'
See also
- get_inputs_output_size_dict(output_inds=None)[source]¶
Get a tuple of
inputs
,output
andsize_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])
See also
- 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:
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_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:
- select_tensors(tags, which='all')[source]¶
Return the sequence of tensors that match
tags
. Ifwhich='all'
, each tensor must contain every tag. Ifwhich='any'
, each tensor can contain any of the tags.- Parameters:
- Returns:
tagged_tensors – The tagged tensors.
- Return type:
See also
- _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 totids
.
- _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 totids
.
- select(tags, which='all', virtual=True)[source]¶
Get a TensorNetwork comprising tensors that match all or any of
tags
, inherit the network properties/structure fromself
. This returns a view of the tensors not a copy.- Parameters:
- Returns:
tagged_tn – A tensor network containing the tagged tensors.
- Return type:
See also
select_tensors
,select_neighbors
,partition
,partition_tensors
- select_neighbors(tags, which='any')[source]¶
Select any neighbouring tensors to those specified by
tags
.self- Parameters:
- Returns:
The neighbouring tensors.
- Return type:
See also
- _select_local_tids(tids, max_distance=1, mode='graphdistance', fillin=False, grow_from='all', reduce_outer=None, virtual=True, include=None, exclude=None)[source]¶
Select a local region of tensors, based on graph distance or union of loops, from an initial set of tensor ids.
- Parameters:
tids (sequence of str) – The initial tensor ids.
max_distance (int, optional) – The maximum distance to the initial tagged region, or if using ‘loopunion’ mode, the maximum size of any loop.
mode ({'graphdistance', 'loopunion'}, optional) – How to select the local tensors, either by graph distance or by selecting the union of all loopy regions containing
tids
.fillin (bool or int, optional) – Whether to fill in the local patch with additional tensors, or not. fillin tensors are those connected by two or more bonds to the original local patch, the process is repeated int(fillin) times.
grow_from ({"all", "any"}, optional) – If mode is ‘loopunion’, whether each loop should contain all of the initial tids, or just any of them (generating a larger region).
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.
include (None or sequence of int, optional) – If given, only include tensor from this set of tids.
exclude (None or sequence of int, optional) – If given, always exclude tensors from this set of tids.
- Return type:
- select_local(tags, which='all', max_distance=1, mode='graphdistance', fillin=False, grow_from='all', 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, or if using ‘loopunion’ mode, the maximum size of any loop.
mode ({'graphdistance', 'loopunion'}, optional) – How to select the local tensors, either by graph distance or by selecting the union of all loopy regions containing
where
, of size up tomax_distance
, ensuring no dangling tensors.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 andx
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-
grow_from ({"all", "any"}, optional) – If mode is ‘loopunion’, whether each loop should contain all of the initial tagged tensors, or just any of them (generating a larger region).
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:
- select_path(loop, gauges=None)[source]¶
Select a sub tensor network corresponding to a single (possibly closed AKA loop like) path. Indices that are not part of the loop but do connect tids within it are cut, making this different to other select methods.
- Parameters:
loop (NetworkPath or sequence of str or int) – A collection of tids and inds to select.
gauges (dict[str, array_like], optional) – A dictionary of gauge tensors to insert at dangling (including cut) indices.
- Return type:
- partition_tensors(tags, inplace=False, which='any')[source]¶
Split this TN into a list of tensors containing any or all of
tags
and aTensorNetwork
of the the rest.- Parameters:
- Returns:
(u_tn, t_ts) – The untagged tensor network, and the sequence of tagged Tensors.
- Return type:
(TensorNetwork, tuple of Tensors)
See also
- partition(tags, which='any', inplace=False)[source]¶
Split this TN into two, based on which tensors have any or all of
tags
. Unlikepartition_tensors
, both results are TNs which inherit the structure of the initial TN.- Parameters:
- Returns:
untagged_tn, tagged_tn – The untagged and tagged tensor networs.
- Return type:
See also
- 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. ifX
denotewhere
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:
See also
- 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. ifX
denotewhere
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:
See also
- 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:
- _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
andtags2
respectively. This is an inplace operation. No-op if the tensor specified bytags1
andtags2
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()
.
- 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
andgate
.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 oldinds
, must be the same length asinds
.gate_inds_outer (sequence of str) – The indices of
gate
to make the new outerinds
, must be the same length asinds
.
- Returns:
tn_gated
- Return type:
See also
- _compute_tree_gauges(tree, outputs)[source]¶
Given a
tree
of connected tensors, absorb the gauges from outside inwards, finally outputing the gauges associated with theoutputs
.- 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
andtags2
usingtensor_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
- 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 onmode
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:
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:
- 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
andtags2
usingtensor_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
- 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
andindb
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
.
- _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
.
- _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
- _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:
See also
- 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, damping=0.0, gauges=None, equalize_norms=False, touched_tids=None, info=None, progbar=False, inplace=False)[source]¶
Iterative gauge all the bonds in this tensor network with a ‘simple update’ like strategy. If gauges are not supplied they are initialized and then reabsorbed at the end, in which case this method acts as a kind of conditioning. More usefully, if you supply gauges then they will be updated inplace and not absorbed back into the tensor network, with the assumption that you are using/tracking them externally.
- Parameters:
max_iterations (int, optional) – The maximum number of iterations to perform.
tol (float, optional) – The convergence tolerance for the singular values.
smudge (float, optional) – A small value to add to the singular values when gauging.
power (float, optional) – A power to raise the singular values to when gauging.
damping (float, optional) – The damping factor to apply to the gauging updates.
gauges (dict, optional) – Supply the initial gauges to use.
equalize_norms (bool, optional) – Whether to equalize the norms of the tensors after each update.
touched_tids (sequence of int, optional) – The tensor identifiers to start the gauge sweep from.
info (dict, optional) –
Store extra information about the gauging process in this dict. If supplied, the following keys are filled:
’iterations’: the number of iterations performed.
’max_sdiff’: the maximum singular value difference.
progbar (bool, optional) – Whether to show a progress bar.
inplace (bool, optional) – Whether to perform the gauging inplace.
- Return type:
- 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:
See also
- _gauge_local_tids(tids, max_distance=1, mode='graphdistance', max_iterations='max_distance', method='canonize', 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 when inserting.
power (float, optional) – A power to raise the gauge vectors to when inserting.
- 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, power=1.0, 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.
smudge (float, optional) – A small value to add to the gauge vectors to avoid singularities.
power (float, optional) – A power to raise the gauge vectors to when inserting.
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, *, 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_mode='auto', compress_min_size=None, compress_span=False, compress_matrices=True, compress_exclude=None, compress_opts=None, strip_exponent=False, equalize_norms='auto', 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]¶
Core routine for performing compressed contraction.
- _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.
- 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='auto', 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=None, compress_mode='auto', compress_min_size=None, compress_span=True, compress_matrices=True, compress_exclude=None, compress_opts=None, strip_exponent=False, equalize_norms='auto', 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, **kwargs)[source]¶
Contract this tensor network using the hyperoptimized approximate contraction method introduced in https://arxiv.org/abs/2206.07044.
Only supports non-hyper tensor networks.
- Parameters:
optimize (str, sequence, HyperCompressedOptimizer, ContractionTreeCompressed) –
The contraction strategy to use. The options are:
str: use the preset strategy with the given name,
path_like: use this exact path,
cotengra.HyperCompressedOptimizer
: find the contraction using this optimizercotengra.ContractionTreeCompressed
: use this exact tree
Note that the strategy should be one that specifically targets compressed contraction, paths for exact contraction will likely perform badly. See the cotengra documentation for more details. Values for
max_bond
andcompress_late
are inherited from the optimizer if possible (and not specified).output_inds (sequence of str, optional) – Output indices. Note that hyper indices are not supported and this is just for specifying the output order.
max_bond ("auto", int or None, optional) –
The maximum bond dimension to allow during compression.
"auto"
: try and inherit value from the optimizer, or use the current maximum bond dimension squared if not available.int: a specific maximum bond dimension to use.
None
: no maximum bond dimension (compression still possible via cutoff) - not recommended.
cutoff (float, optional) – The singular value cutoff to use during compression.
tree_gauge_distance (int, optional) – The distance to ‘tree gauge’ around a pair of tensors before compressing. Depending on if compress_mode=”basic” this sets canonize_distance and canonize_after_distance.
canonize_distance (int, optional) – The distance to canonize around a pair of tensors before compressing.
canonize_opts (dict, optional) – Additional keyword arguments to pass to the canonize routine.
canonize_after_distance (int, optional) – The distance to canonize around a pair of tensors after compressing.
canonize_after_opts (dict, optional) – Additional keyword arguments to pass to the canonize routine after compressing.
gauge_boundary_only (bool, optional) – Whether to only gauge the ‘boundary’ tensors, that is, intermediate tensors.
compress_late (None or bool, optional) – Whether to compress just before contracting the tensors involved or immediately after. Early compression is cheaper and a better default especially for contractions beyond planar. Late compression leaves more information in the tensors for possibly better quality gauging and compression. Whilst the largest tensor (‘contraction width’) is typically unchanged, the total memory and cost can be quite a lot higher. By default, this is None, which will try and inherit the value from the optimizer, else default to False.
compress_mode ({'auto', 'basic', 'virtual-tree', ...}, optional) – How to compress a pair of tensors. If ‘auto’, then ‘basic’ is used if tree_gauge_distance=0 or gauges are supplied, otherwise ‘virtual-tree’ is used. See _compress_between_tids for other valid options.
compress_min_size (int, optional) – Skip compressing a pair of tensors if their contraction would yield a tensor smaller than this size.
compress_opts (dict, optional) – Additional keyword arguments to pass to the core pariwise compression routine.
compress_span (bool or int, optional) – Whether to compress between tensors that are going to be contracted. If an int, this specifies that if two tensors will be contracted in the next compress_span contractions, then their bonds should be compressed.
compress_matrices (bool, optional) – Whether to compress pairs of tensors that are effectively matrices.
compress_exclude (set[int], optional) – An explicit set of tensor ids to exclude from compression.
strip_exponent (bool, optional) – Whether the strip an overall exponent, log10, from the final contraction. If a TensorNetwork is returned, this exponent is accumulated in the exponent attribute. If a Tensor or scalar is returned, the exponent is returned separately.
equalize_norms (bool or "auto", optional) – Whether to equalize the norms of the tensors during the contraction. By default (“auto”) this follows strip_exponent. The overall scaling is accumulated, log10, into tn.exponent. If True, at the end this exponent is redistributed. If a float, this is the target norm to equalize tensors to, e.g. 1.0, and the exponent is not redistributed, which is useful in the case that the non-log value is beyond standard precision.
gauges (dict[str, array_like], optional) – If supplied, use simple update style gauges during the contraction. The keys should be indices and the values singular value vectors. Only bonds present in this dictionary will be gauged.
gauge_smudge (float, optional) – If using simple update style gauging, add a small value to the singular values to avoid singularities.
callback_pre_contract (callable, optional) – A function to call before contracting a pair of tensors. It should have signature fn(tn, (tid1, tid2)).
callback_post_contract (callable, optional) – A function to call after contracting a pair of tensors. It should have signature fn(tn, tid).
callback_pre_compress (callable, optional) – A function to call before compressing a pair of tensors. It should have signature fn(tn, (tid1, tid2)).
callback_post_compress (callable, optional) – A function to call after compressing a pair of tensors. It should have signature fn(tn, (tid1, tid2)).
callback (callable, optional) – A function to call after each full step of contraction and compressions. It should have signature fn(tn, tid).
preserve_tensor (bool, optional) – If True, return a Tensor object even if it represents a scalar. Ignore if inplace=True, in which case a TensorNetwork is always returned.
progbar (bool, optional) – Whether to show a progress bar.
inplace (bool, optional) – Whether to perform the contraction inplace.
kwargs (dict, optional) – Additional keyword passed to _contract_compressed_tid_sequence.
- new_bond(tags1, tags2, **opts)[source]¶
Inplace addition of a dummmy (size 1) bond between the single tensors specified by by
tags1
andtags2
.- 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
- cut_between(left_tags, right_tags, left_ind, right_ind)[source]¶
Cut the bond between the tensors specified by
left_tags
andright_tags
, giving them the new indsleft_ind
andright_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. Usecut_between
for control over which tensor gets which new indexnew_left_ind
ornew_right_ind
. The index must connect exactly two tensors.
- 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
andtagsb
, and ‘drape’ it through the tensor tagged attags_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 attagsa
andtagsb
.- 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:
- isel(selectors, inplace=False)[source]¶
Select specific values for some dimensions/indices of this tensor network, thereby removing them.
- Parameters:
- Return type:
See also
- 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.
- vector_reduce(ind, v, inplace=False)[source]¶
Contract the vector
v
with the indexind
of this tensor network, removing it.- Parameters:
- Return type:
- 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
See also
- 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(U, where1, where2, Uinv=None, tol=1e-10)[source]¶
Insert the gauge transformation
U^-1 @ U
into the bond between the tensors,T1
andT2
, defined bywhere1
andwhere2
. The resulting tensors at those locations will beT1 @ U^-1
andU @ 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 usingnumpy.linalg.inv()
.
- contract_tags(tags, which='any', output_inds=None, optimize=None, get=None, backend=None, strip_exponent=False, equalize_norms='auto', 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 (str, PathOptimizer, ContractionTree or path_like, optional) –
The contraction path optimization strategy to use.
None
: use the default strategy,str
: use the preset strategy with the given name,cotengra.HyperOptimizer
: find the contraction using this optimizer, supports slicing,opt_einsum.PathOptimizer
: find the path using this optimizer.cotengra.ContractionTree
: use this exact tree, supports slicing,path_like
: use this exact path.
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 thecotengra.ContractionTree
describing the contraction in detail.'path'
- return the raw ‘path’ as a list of tuples.'symbol-map'
- return the dict mapping indices to ‘symbols’ (single unicode letters) used internally bycotengra
'path-info'
- return theopt_einsum.PathInfo
path object with detailed information such as flop cost. The symbol-map is also added to thequimb_symbol_map
attribute.
backend ({'auto', 'numpy', 'jax', 'cupy', 'tensorflow', ...}, optional) – Which backend to use to perform the contraction. Supplied to cotengra.
strip_exponent (bool, optional) – Whether the strip an overall exponent, log10, from the final contraction. If a TensorNetwork is returned, this exponent is accumulated in the exponent attribute. If a Tensor or scalar is returned, the exponent is returned separately.
equalize_norms (bool or "auto", optional) – Whether to equalize the norms of the tensors during the contraction. By default (“auto”) this follows strip_exponent.
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
See also
- contract(tags=..., output_inds=None, optimize=None, get=None, max_bond=None, strip_exponent=False, preserve_tensor=False, backend=None, inplace=False, **kwargs)[source]¶
Contract some, or all, of the tensors in this network. This method dispatches to
contract_tags
,contract_structured
, orcontract_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 (str, PathOptimizer, ContractionTree or path_like, optional) –
The contraction path optimization strategy to use.
None
: use the default strategy,str
: use the preset strategy with the given name,cotengra.HyperOptimizer
: find the contraction using this optimizer, supports slicing,opt_einsum.PathOptimizer
: find the path using this optimizer.cotengra.ContractionTree
: use this exact tree, supports slicing,path_like
: use this exact path.
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 thecotengra.ContractionTree
describing the contraction in detail.'path'
- return the raw ‘path’ as a list of tuples.'symbol-map'
- return the dict mapping indices to ‘symbols’ (single unicode letters) used internally bycotengra
'path-info'
- return theopt_einsum.PathInfo
path object with detailed information such as flop cost. The symbol-map is also added to thequimb_symbol_map
attribute.
strip_exponent (bool, optional) – Whether the strip an overall exponent, log10, from the final contraction. If a TensorNetwork is returned, this exponent is accumulated in the exponent attribute. If a Tensor or scalar is returned, the exponent is returned separately.
preserve_tensor (bool, optional) – Whether to return a tensor regardless of whether the output object is a scalar (has no indices) or not.
backend ({'auto', 'numpy', 'jax', 'cupy', 'tensorflow', ...}, optional) – Which backend to use to perform the contraction. Supplied to cotengra.
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).
kwargs – 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
See also
- contract_cumulative(tags_seq, output_inds=None, strip_exponent=False, equalize_norms='auto', preserve_tensor=False, inplace=False, **contract_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.
strip_exponent (bool, optional) – Whether the strip an overall exponent, log10, from the final contraction. If a TensorNetwork is returned, this exponent is accumulated in the exponent attribute. If a Tensor or scalar is returned, the exponent is returned separately.
equalize_norms (bool or "auto", optional) – Whether to equalize the norms of the tensors during the contraction. By default (“auto”) this follows strip_exponent.
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
See also
- contraction_path(optimize=None, output_inds=None, **kwargs)[source]¶
Compute the contraction path, a sequence of (int, int), for the contraction of this entire tensor network using strategy
optimize
.- Parameters:
optimize (str, PathOptimizer, ContractionTree or path_like, optional) –
The contraction path optimization strategy to use.
None
: use the default strategy,str
: use the preset strategy with the given name,cotengra.HyperOptimizer
: find the contraction using this optimizer, supports slicing,opt_einsum.PathOptimizer
: find the path using this optimizer.cotengra.ContractionTree
: use this exact tree, supports slicing,path_like
: use this exact path.
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.
kwargs (dict, optional) – Passed to
cotengra.array_contract_path()
.
- Return type:
- contraction_info(optimize=None, output_inds=None, **kwargs)[source]¶
Compute the
opt_einsum.PathInfo
object describing the contraction of this entire tensor network using strategyoptimize
. Note any sliced indices will be ignored.- Parameters:
optimize (str, PathOptimizer, ContractionTree or path_like, optional) –
The contraction path optimization strategy to use.
None
: use the default strategy,str
: use the preset strategy with the given name,cotengra.HyperOptimizer
: find the contraction using this optimizer, supports slicing,opt_einsum.PathOptimizer
: find the path using this optimizer.cotengra.ContractionTree
: use this exact tree, supports slicing,path_like
: use this exact path.
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.
kwargs (dict, optional) – Passed to
cotengra.array_contract_tree()
.
- Return type:
opt_einsum.PathInfo
- contraction_tree(optimize=None, output_inds=None, **kwargs)[source]¶
Return the
cotengra.ContractionTree
corresponding to contracting this entire tensor network with strategyoptimize
.- Parameters:
optimize (str, PathOptimizer, ContractionTree or path_like, optional) –
The contraction path optimization strategy to use.
None
: use the default strategy,str
: use the preset strategy with the given name,cotengra.HyperOptimizer
: find the contraction using this optimizer, supports slicing,opt_einsum.PathOptimizer
: find the path using this optimizer.cotengra.ContractionTree
: use this exact tree, supports slicing,path_like
: use this exact path.
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.
kwargs (dict, optional) – Passed to
cotengra.array_contract_tree()
.
- Return type:
- 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.
- as_network(virtual=True)[source]¶
Matching method (for ensuring object is a tensor network) to
as_network()
, which simply returnsself
ifvirtual=True
.
- aslinearoperator(left_inds, right_inds, ldims=None, rdims=None, backend=None, optimize=None)[source]¶
View this
TensorNetwork
as aTNLinearOperator
.
- 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 aTNLinearOperator
first. Note unless an iterative method is passed tomethod
, the full dense tensor will be contracted.
- 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
, mappingleft_inds
toright_inds
and computeL
orR
such thatX = U_R @ R
orX = L @ U_L
, withU_R
andU_L
unitary operators that are not computed. Onlydag(X) @ X
orX @ dag(X)
is contracted, which is generally cheaper than contractingX
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, otherwiseX @ 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 bycutoff
.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:
See also
- 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 onmethod
this callstensor_network_fit_als()
ortensor_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', 'tree'}, optional) –
How to perform the fitting. The options are:
’als’: alternating least squares (ALS) optimization,
’autodiff’: automatic differentiation optimization,
’tree’: ALS where the fitted tensor network has a tree structure and thus a canonical form can be utilized for much greater efficiency and stability.
Generally ALS is better for simple geometries, autodiff better for complex ones. Tree best if the tensor network has a tree structure.
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()
,tensor_network_fit_autodiff()
, ortensor_network_fit_tree()
.
- Returns:
tn_opt – The optimized tensor network.
- Return type:
See also
tensor_network_fit_als
,tensor_network_fit_autodiff
,tensor_network_fit_tree
,tensor_network_distance
,tensor_network_1d_compress
- property tags¶
- 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:
- Returns:
A dict mapping the tuple of indices that could be fused to the tuple of tensor ids they appear on.
- Return type:
- 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.
- 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:
- 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 ofR
is positive.”svd”: uses
U @ VH
of the SVD decomposition ofx
. This is useful for finding the ‘closest’ isometric matrix tox
, such as when it has been expanded with noise etc. But is less stable for differentiation / optimization.”exp”: use the matrix exponential of
x - dag(x)
, first completingx
with zeros if it is rectangular. This is a good parametrization for optimization, but more expensive for non-squarex
.”cayley”: use the Cayley transform of
x - dag(x)
, first completingx
with zeros if it is rectangular. This is a good parametrization for optimization (one the few compatible with HIPS/autograd e.g.), but more expensive for non-squarex
.”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 noleft_inds
to be left alone, rather than raising an error.inplace (bool, optional) – If
True
then perform the operation in-place.
- Return type:
- unitize_¶
- 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:
- strip_exponent(tid_or_tensor, value=None, check_zero=False)[source]¶
Scale the elements of tensor corresponding to
tid
so that the norm of the array is some value, which defaults to1
. The log of the scaling factor, base 10, is then accumulated in theexponent
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.
check_zero (bool, optional) – Whether to check if the tensor has zero norm and in that case do nothing, since the exponent would be -inf. Off by default to avoid data dependent computational graphs when tracing and computing gradients etc.
- distribute_exponent()[source]¶
Distribute the exponent
p
of this tensor network (i.e. corresponding totn * 10**p
) equally among all tensors.
- equalize_norms(value=None, check_zero=False, 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 tovalue
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.check_zero (bool, optional) – Whether, if and when equalizing norms, to check if tensors have zero norm and in that case do nothing, since the exponent would be -inf. Off by default to avoid data dependent computational graphs when tracing and computing gradients etc.
inplace (bool, optional) – Whether to perform the norm equalization inplace or not.
- Return type:
- 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:
- 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:
- 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, check_zero=False, 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.
check_zero (bool, optional) – Whether, if and when equalizing norms, to check if tensors have zero norm and in that case do nothing, since the exponent would be -inf. Off by default to avoid data dependent computational graphs when tracing and computing gradients etc.
inplace (bool, optional) – Whether to perform the rand reduction inplace.
- Return type:
See also
- 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:
See also
- 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:
See also
full_simplify
,rank_simplify
,diagonal_reduce
,column_reduce
- 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:
See also
full_simplify
,rank_simplify
,diagonal_reduce
,antidiag_gauge
- split_simplify(atol=1e-12, equalize_norms=False, cache=None, check_zero=False, 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.
check_zero (bool, optional) – Whether, if and when equalizing norms, to check if tensors have zero norm and in that case do nothing, since the exponent would be -inf. Off by default to avoid data dependent computational graphs when tracing and computing gradients etc.
inplace – Whether to perform the split simplification inplace.
bool – Whether to perform the split simplification inplace.
optional – Whether to perform the split simplification inplace.
- pair_simplify(cutoff=1e-12, output_inds=None, max_inds=10, cache=None, equalize_norms=False, max_combinations=500, check_zero=False, 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, check_zero=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.
check_zero (bool, optional) – Whether, if and when equalizing norms, to check if tensors have zero norm and in that case do nothing, since the exponent would be -inf. Off by default to avoid data dependent computational graphs when tracing and computing gradients etc.
inplace (bool, optional) – Whether to replace the loops inplace.
split_opts – Supplied to
tensor_split()
.
- Return type:
- full_simplify(seq='ADCR', output_inds=None, atol=1e-12, equalize_norms=False, cache=None, rank_simplify_opts=None, loop_simplify_opts=None, split_simplify_opts=None, custom_methods=(), split_method='svd', check_zero='auto', inplace=False, progbar=False)[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 forantidiag_gauge
'D'
: stands fordiagonal_reduce
'C'
: stands forcolumn_reduce
'R'
: stands forrank_simplify
'S'
: stands forsplit_simplify
'L'
: stands forloop_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.
check_zero (bool, optional) – Whether to check if tensors have zero norm and in that case do nothing if and when equalizing norms, rather than generating a NaN. If ‘auto’ this will only be turned on if other methods that explicitly check data entries (“A”, “D”, “C”, “S”, “L”) are being used (the default).
progbar (bool, optional) – Show a live progress bar of the simplification process.
inplace (bool, optional) – Whether to perform the simplification inplace.
- Return type:
- 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:
- 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, check_zero=True, progbar=False, inplace=False, **full_simplify_opts)[source]¶
- max_bond()[source]¶
Return the size of the largest bond (i.e. index connecting 2+ tensors) in this network.
- property shape¶
Effective, i.e. outer, shape of this TensorNetwork.
- property dtype¶
The dtype of this TensorNetwork, this is the minimal common type of all the tensors data.
- property dtype_name¶
The name of the data type of the array elements.
- property backend¶
Get the backend of any tensor in this network, asssuming it to be the same for all tensors.
- quimb.tensor.bonds(t1: Tensor, t2: Tensor)[source]¶
Getting any indices connecting the Tensor(s) or TensorNetwork(s)
t1
andt2
.
- quimb.tensor.bonds_size(t1: Tensor, t2: Tensor)[source]¶
Get the size of the bonds linking tensors or tensor networks
t1
andt2
.
- quimb.tensor.connect(t1: Tensor, t2: Tensor, 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:
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: Tensor, t2: Tensor)[source]¶
Group bonds into left only, shared, and right only. If
t1
ort2
areTensorNetwork
objects, then only outer indices are considered.- Parameters:
t1 (Tensor or TensorNetwork) – The first tensor or tensor network.
t2 (Tensor or TensorNetwork) – The second tensor or tensor network.
- Returns:
left_inds (list[str]) – Indices only in
t1
.shared_inds (list[str]) – Indices in both
t1
andt2
.right_inds (list[str]) – Indices only in
t2
.
- quimb.tensor.new_bond(T1: Tensor, T2: Tensor, size=1, name=None, axis1=0, axis2=0)[source]¶
Inplace addition of a new bond between tensors
T1
andT2
. 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',)¶
- _d¶
- 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: Tensor, t2: Tensor, 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.
- quimb.tensor.tensor_canonize_bond(T1: Tensor, T2: Tensor, 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 ofmethod=='qr'
andabsorb='right'
.
- quimb.tensor.tensor_compress_bond(T1: Tensor, T2: Tensor, 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: Tensor, output_inds=None, optimize=None, get=None, backend=None, preserve_tensor=False, drop_tags=False, strip_exponent=False, exponent=None, **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 (str, PathOptimizer, ContractionTree or path_like, optional) –
The contraction path optimization strategy to use.
None
: use the default strategy,str
: use the preset strategy with the given name,cotengra.HyperOptimizer
: find the contraction using this optimizer, supports slicing,opt_einsum.PathOptimizer
: find the path using this optimizer.cotengra.ContractionTree
: use this exact tree, supports slicing,path_like
: use this exact path.
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 usesautoray
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 thecotengra.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 bycotengra
'path-info'
- return theopt_einsum.PathInfo
path object with detailed information such as flop cost. The symbol-map is also added to thequimb_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.
strip_exponent (bool, optional) – If True, return the exponent of the result, log10, as well as the rescaled ‘mantissa’. Useful for very large or small values.
exponent (float, optional) – If supplied, an overall base exponent to scale the result by.
contract_opts – Passed to
cotengra.array_contract
.
- Return type:
scalar or Tensor
- quimb.tensor.tensor_direct_product(T1: Tensor, T2: Tensor, 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:
- Returns:
Like
T1
, but with each dimension doubled in size if not insum_inds
.- Return type:
- quimb.tensor.tensor_fuse_squeeze(t1: Tensor, t2: Tensor, squeeze=True, gauges=None)[source]¶
If
t1
andt2
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, output_inds=None, **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
whereeps
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 or str, optional) – If
True
, then normalize the distance by the norm of the two operators, i.e.D(A, B) * 2 / (|A| + |B|)
. The resulting distance lies between 0 and 2 and is more useful for assessing convergence. If'infidelity'
, compute the normalized infidelity1 - |<A|B>|^2 / (|A| |B|)
, which can be faster to optimize e.g., but does not take into account normalization.output_inds (sequence of str, optional) – Specify the output indices of tnA and tnB to contract over. This can be necessary if either network has hyper indices.
contract_opts – Supplied to
contract()
.
- Returns:
D
- Return type:
- quimb.tensor.tensor_network_fit_als(tn, tn_target, tags=None, steps=100, tol=1e-09, dense_solve='auto', solver='auto', solver_maxiter=4, solver_dense='auto', enforce_pos=False, pos_smudge=None, tnAA=None, tnAB=None, xBB=None, output_inds=None, contract_optimize='auto-hq', inplace=False, progbar=False, **kwargs)[source]¶
Optimize the fit of
tn
with respect totn_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.
dense_solve ({'auto', True, False}, optional) – Whether to solve the local minimization problem in dense form. If
'auto'
, will only use dense form for small tensors.solver ({"auto", None, "cg", ...}, optional) – What solver to use for the iterative (but not dense) local minimization. If
None
will use a built in conjugate gradient solver. If a string, will use the corresponding solver fromscipy.sparse.linalg
.solver_maxiter (int, optional) – The maximum number of iterations for the iterative solver.
solver_dense ({"auto", None, 'solve', 'eigh', 'lstsq', ...}, optional) – The underlying driver function used to solve the local minimization, e.g.
numpy.linalg.solve
for'solve'
withnumpy
backend, if solving the local problem in dense form.enforce_pos (bool, optional) – Whether to enforce positivity of the locally formed environments, which can be more stable, only for dense solves. This sets
solver_dense='eigh'
.pos_smudge (float, optional) – If enforcing positivity, the level below which to clip eigenvalues for make the local environment positive definit, only for dense solves.
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:
- quimb.tensor.tensor_network_fit_autodiff(tn, tn_target, steps=1000, tol=1e-09, autodiff_backend='autograd', contract_optimize='auto-hq', distance_method='auto', normalized='squared', output_inds=None, xBB=None, inplace=False, progbar=False, **kwargs)[source]¶
Optimize the fit of
tn
with respect totn_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.normalized (bool or str, optional) – If
True
, then normalize the distance by the norm of the two operators, i.e.D(A, B) * 2 / (|A| + |B|)
. The resulting distance lies between 0 and 2 and is more useful for assessing convergence. If'infidelity'
, compute the normalized infidelity1 - |<A|B>|^2 / (|A| |B|)
, which can be faster to optimize e.g., but does not take into account normalization.output_inds (sequence of str, optional) – Specify the output indices of tnA and tnB to contract over. This can be necessary if either network has hyper indices.
xBB (float, optional) – If you already know, have computed
tn_target.H @ tn_target
, or don’t care about the overall scale of the norm distance, you can supply a value here.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: TensorNetwork, G, inds, contract=False, tags=None, info=None, inplace=False, **compress_opts)[source]¶
Apply the ‘gate’
G
to indicesinds
, propagating them to the outside, as if applyingG @ 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 anycontract
methods that involve splitting. Ignored otherwise.
- Returns:
G_tn
- Return type:
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 andFalse
, depending on whether either results in a lower rank.
- quimb.tensor.tensor_network_sum(tnA: TensorNetwork, tnB: TensorNetwork, inplace=False)[source]¶
Sum of two tensor networks, whose indices should match exactly, using direct products.
- Parameters:
tnA (TensorNetwork) – The first tensor network.
tnB (TensorNetwork) – The second tensor network.
- Returns:
The sum of
tnA
andtnB
, with increased bond dimensions.- Return type:
- quimb.tensor.tensor_split(T: Tensor, 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 supplyNone
here if you supplyright_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 asA = UP
.'polar_left'
: full polar decomposition asA = 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 onabsorb
.'tensors '
: the new tensors as a tuple(Tl, Tr)
or(Tl, Ts, Tr)
depending onabsorb
.'values'
: only compute and return the singular valuess
.
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 ifget=None
the tensor network returned will have a hyperedge corresponding to the new bond index connecting three tensors. Ifget='tensors'
orget='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 thancutoff * s[0]
discarded.'abs'
: values less thancutoff
discarded.'sum2'
: sum squared of values discarded must be< cutoff
.'rsum2'
: sum squared of values discarded must be less thancutoff
times the total sum of squared values.'sum1'
: sum values discarded must be< cutoff
.'rsum1'
: sum of values discarded must be less thancutoff
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 forcutoff_method in {'sum2', 'rsum2', 'sum1', 'rsum1'}
withmethod 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
isNone
,'tensors'
,'arrays'
, or'values'
. In the first three cases, ifabsorb
is set, then the returned objects correspond to(left, right)
whereas ifabsorb=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 theopts
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:
- 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.
- 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.
- opts¶
Advanced options e.g. relating to the inner eigensolve or compression, see
get_default_opts()
.- Type:
- (bond_sizes_ham)
If cyclic, the sizes of the energy environement transfer matrix bonds, per segment, per sweep.
- (bond_sizes_norm)
If cyclic, the sizes of the norm environement transfer matrix bonds, per segment, per sweep.
- L¶
- phys_dim¶
- bsz = 2¶
- which = 'SA'¶
- cyclic¶
- _b¶
- ham¶
- TN_energy¶
- energies = []¶
- local_energies = []¶
- total_energies = []¶
- opts¶
- property energy¶
- property state¶
- _canonize_after_1site_update(direction, i)[source]¶
Compress a site having updated it. Also serves to move the orthogonality center along.
- 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
andb
, and thusTN_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
andb
, and thusTN_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
.
- _print_pre_sweep(i, direction, max_bond, cutoff, verbosity=0)[source]¶
Print this before each sweep.
- 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:
- 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:
ham (MatrixProductOperator) – The hamiltonian in MPO form, should have ~area-law eigenstates.
p0 (MatrixProductState) – The initial MPS guess, e.g. a computation basis state.
- k¶
The current, optimized state.
- Type:
- TN_energy2¶
- variances¶
- _target_energy¶
- opts¶
- 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 witheff_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
.
- 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, thenMovingEnvironment()
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.
- tn¶
- begin¶
- bsz¶
- cyclic = False¶
- L¶
- _site_tag_id¶
- init_segment(begin, start, stop)[source]¶
Initialize the environments in
range(start, stop)
so that one can start sweeping from the side defined bybegin
.
- 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¶
- _site_ind_id = 'k{}'¶
- _site_tag_id = 'I{}'¶
- cyclic = True¶
- _L¶