quimb.tensor.tensor_core

Core tensor network tools.

Attributes

Classes

qarray

Thin subclass of numpy.ndarray with some convenient quantum

oset

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

PArray

Simple array-like object that lazily generates the actual array by

Tensor

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

TensorNetwork

A collection of (as yet uncontracted) Tensors.

TNLinearOperator

Get a linear operator - something that replicates the matrix-vector

PTensor

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

IsoTensor

A Tensor subclass which keeps its left_inds by default even

Functions

make_immutable(mat)

Make array read only, in-place.

prod(iterable)

realify_scalar(x[, imag_tol])

vdot(a, b)

Accelerated 'Hermitian' inner product of two arrays. In other words,

rand_matrix(d[, scaled, sparse, stype, density, ...])

Generate a random matrix of order d with normally distributed

rand_uni(d[, dtype])

Generate a random unitary operator of size d, distributed according to

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

Fast multithreaded generation of random normally distributed data.

seed_rand(seed)

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

check_opt(name, value, valid)

Check whether value takes one of valid options, and raise an

deprecated(fn, old_name, new_name)

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

ensure_dict(x)

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

gen_bipartitions(it)

Generate all unique bipartitions of it. Unique meaning

tree_map(f, tree[, is_leaf])

Map f over all leaves in tree, returning a new pytree.

asarray(array)

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

find_antidiag_axes(x[, atol])

Try and find a pair of axes of x in which it is anti-diagonal.

find_columns(x[, atol])

Try and find columns of axes which are zero apart from a single index.

find_diag_axes(x[, atol])

Try and find a pair of axes of x in which it is diagonal.

iscomplex(x)

Does x have a complex dtype?

ndim(array)

The number of dimensions of an array.

norm_fro(x)

The frobenius norm of an array.

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

array_contract_expression(*args[, optimize])

array_contract_path(*args[, optimize])

array_contract_pathinfo(*args, **kwargs)

array_contract_tree(*args[, optimize])

get_contract_backend()

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

get_contract_strategy()

Get the default contraction strategy - the option supplied as

get_tensor_linop_backend()

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

inds_to_eq(inputs[, output])

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

inds_to_symbols(inputs)

Map a sequence of inputs terms, containing any hashable indices, to

auto_color_html(s)

Automatically hash and color a string for HTML display.

draw_tn(tn[, color, show_inds, show_tags, ...])

Plot this tensor network as a networkx graph using matplotlib,

visualize_tensor(tensor, **kwargs)

Visualize all entries of a tensor, with indices mapped into the plane

visualize_tensors(tn[, mode, r, r_scale, figsize])

Visualize all the entries of every tensor in this network.

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

Compute the Frobenius norm distance between two tensor networks:

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

Optimize the fit of tn with respect to tn_target using

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

Optimize the fit of tn with respect to tn_target using

oset_union(xs)

Non-variadic ordered set union taking any sequence of iterables.

oset_intersection(xs)

tags_to_oset(tags)

Parse a tags argument into an ordered set.

sortedtuple(x)

_gen_output_inds(all_inds)

Generate the output, i.e. unique, indices from the set inds. Raise

_tensor_contract_get_other(arrays, inds, inds_out, ...)

maybe_realify_scalar(data)

If data is a numpy array, check if its complex with small imaginary

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

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

rand_uuid([base])

Return a guaranteed unique, shortish identifier, optional appended

_parse_split_opts(method, cutoff, absorb, max_bond, ...)

_check_left_right_isom(method, absorb)

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

Decompose this tensor into two tensors.

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

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

choose_local_compress_gauge_settings([canonize, ...])

Choose default gauge settings for arbitrary geometry local compression.

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

Inplace compress between the two single tensors. It follows the

tensor_balance_bond(t1, t2[, smudge])

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

tensor_multifuse(ts, inds[, gauges])

For tensors ts which should all have indices inds, fuse the

tensor_make_single_bond(t1, t2[, gauges])

If two tensors share multibonds, fuse them together and return the left

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

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

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

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

rand_padder(vector, pad_width, iaxis, kwargs)

Helper function for padding tensor with random entries.

array_direct_product(X, Y[, sum_axes])

Direct product of two arrays.

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

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

tensor_network_sum(tnA, tnB[, inplace])

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

bonds(t1, t2)

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

bonds_size(t1, t2)

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

group_inds(t1, t2)

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

connect(t1, t2, ax1, ax2)

Connect two tensors by setting a shared index for the specified

get_tags(ts)

Return all the tags in found in ts.

maybe_unwrap(t[, preserve_tensor_network, ...])

Maybe unwrap a TensorNetwork or Tensor into a Tensor or

_make_copy_ndarray(d, ndim[, dtype])

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

Get the tensor representing the COPY operation with dimension size

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

Get the set of MPS tensors representing the COPY tensor with dimension

COPY_tree_tensors(d, inds[, tags, dtype, ssa_path])

Get the set of tree tensors representing the COPY tensor with dimension

_make_promote_array_func(op, meth_name)

_make_rhand_array_promote_func(op, meth_name)

_tensor_network_gate_inds_basic(tn, G, inds, ng, tags, ...)

_tensor_network_gate_inds_lazy_split(tn, G, inds, ng, ...)

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

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

tnlo_implements(np_function)

Register an __array_function__ implementation for TNLinearOperator

_tnlo_trace(x)

Module Contents

quimb.tensor.tensor_core.make_immutable(mat)[source]

Make array read only, in-place.

Parameters:

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

quimb.tensor.tensor_core.prod(iterable)
class quimb.tensor.tensor_core.qarray(shape, dtype=float, buffer=None, offset=0, strides=None, order=None)[source]

Bases: numpy.ndarray

Thin subclass of numpy.ndarray with some convenient quantum linear algebra related methods and attributes (.H, &, etc.), and matrix-like preservation of at least 2-dimensions so as to distiguish kets and bras.

property H
property A
__array__()[source]
__and__(other)[source]
normalize(inplace=True)[source]
nmlz(inplace=True)[source]
chop(inplace=True)[source]
tr()[source]
partial_trace(dims, keep)[source]
ptr(dims, keep)[source]
__str__()[source]

Return str(self).

__repr__()[source]

Return repr(self).

quimb.tensor.tensor_core.realify_scalar(x, imag_tol=1e-12)[source]
quimb.tensor.tensor_core.vdot(a, b)[source]

Accelerated ‘Hermitian’ inner product of two arrays. In other words, b here will be conjugated by the function.

quimb.tensor.tensor_core.rand_matrix(d, scaled=True, sparse=False, stype='csr', density=None, dtype=complex, seed=None)[source]

Generate a random matrix of order d with normally distributed entries. If scaled is True, then in the limit of large d the eigenvalues will be distributed on the unit complex disk.

Parameters:
  • d (int) – Matrix dimension.

  • scaled (bool, optional) – Whether to scale the matrices values such that its spectrum approximately lies on the unit disk (for dense matrices).

  • sparse (bool, optional) – Whether to produce a sparse matrix.

  • stype ({'csr', 'csc', 'coo', ...}, optional) – The type of sparse matrix if sparse=True.

  • density (float, optional) – Target density of non-zero elements for the sparse matrix. By default aims for about 10 entries per row.

  • dtype ({complex, float}, optional) – The data type of the matrix elements.

Returns:

mat – Random matrix.

Return type:

qarray or sparse matrix

quimb.tensor.tensor_core.rand_uni(d, dtype=complex)[source]

Generate a random unitary operator of size d, distributed according to the Haar measure.

See also

rand_matrix, rand_herm, rand_pos, rand_rho

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

Fast multithreaded generation of random normally distributed data.

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

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

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

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

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

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

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

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

quimb.tensor.tensor_core.check_opt(name, value, valid)[source]

Check whether value takes one of valid options, and raise an informative error if not.

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

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

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

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

quimb.tensor.tensor_core.gen_bipartitions(it)[source]

Generate all unique bipartitions of it. Unique meaning (1, 2), (3, 4) is considered the same as (3, 4), (1, 2).

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

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

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

Public method makes sure to copy incoming dictionary.

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

Return self==value.

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

Return repr(self).

quimb.tensor.tensor_core.tree_map(f, tree, is_leaf=is_not_container)[source]

Map f over all leaves in tree, returning a new pytree.

Parameters:
  • f (callable) – A function to apply to all leaves in tree.

  • tree (pytree) – A nested sequence of tuples, lists, dicts and other objects.

  • is_leaf (callable) – A function to determine if an object is a leaf, f is only applied to objects for which is_leaf(x) returns True.

Return type:

pytree

class quimb.tensor.tensor_core.PArray(fn, params, shape=None)[source]

Simple array-like object that lazily generates the actual array by calling a function with a set of parameters.

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

See also

PTensor

__slots__ = ('_fn', '_params', '_data', '_shape', '_shape_fn_id')
copy()[source]
property fn
property params
property data
property shape
property ndim
add_function(g)[source]

Chain the new function g on top of current function f like g(f(params)).

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

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

quimb.tensor.tensor_core.find_antidiag_axes(x, atol=1e-12)[source]

Try and find a pair of axes of x in which it is anti-diagonal.

Parameters:
  • x (array-like) – The array to search.

  • atol (float, optional) – Tolerance with which to compare to zero.

Returns:

The two axes if found else None.

Return type:

tuple[int] or None

Examples

>>> x = np.array([[[0, 1], [0, 2]],
...               [[3, 0], [4, 0]]])
>>> find_antidiag_axes(x)
(0, 2)

Which means we can reduce x without loss of information to:

>>> np.einsum('aba->ab', x[::-1, :, :])
array([[3, 4],
       [1, 2]])

as long as we flip the order of dimensions on other tensors corresponding to the the same index.

quimb.tensor.tensor_core.find_columns(x, atol=1e-12)[source]

Try and find columns of axes which are zero apart from a single index.

Parameters:
  • x (array-like) – The array to search.

  • atol (float, optional) – Tolerance with which to compare to zero.

Returns:

If found, the first integer is which axis, and the second is which column of that axis, else None.

Return type:

tuple[int] or None

Examples

>>> x = np.array([[[0, 1], [0, 2]],
...               [[0, 3], [0, 4]]])
>>> find_columns(x)
(2, 1)

Which means we can happily slice x without loss of information to:

>>> x[:, :, 1]
array([[1, 2],
       [3, 4]])
quimb.tensor.tensor_core.find_diag_axes(x, atol=1e-12)[source]

Try and find a pair of axes of x in which it is diagonal.

Parameters:
  • x (array-like) – The array to search.

  • atol (float, optional) – Tolerance with which to compare to zero.

Returns:

The two axes if found else None.

Return type:

tuple[int] or None

Examples

>>> x = np.array([[[1, 0], [0, 2]],
...               [[3, 0], [0, 4]]])
>>> find_diag_axes(x)
(1, 2)

Which means we can reduce x without loss of information to:

>>> np.einsum('abb->ab', x)
array([[1, 2],
       [3, 4]])
quimb.tensor.tensor_core.iscomplex(x)[source]

Does x have a complex dtype?

quimb.tensor.tensor_core.ndim(array)[source]

The number of dimensions of an array.

quimb.tensor.tensor_core.norm_fro(x)[source]

The frobenius norm of an array.

quimb.tensor.tensor_core.array_contract(arrays, inputs, output=None, optimize=None, backend=None, **kwargs)[source]
quimb.tensor.tensor_core.array_contract_expression(*args, optimize=None, **kwargs)[source]
quimb.tensor.tensor_core.array_contract_path(*args, optimize=None, **kwargs)[source]
quimb.tensor.tensor_core.array_contract_pathinfo(*args, **kwargs)[source]
quimb.tensor.tensor_core.array_contract_tree(*args, optimize=None, **kwargs)[source]
quimb.tensor.tensor_core.get_contract_backend()[source]

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

See also

set_contract_backend, get_tensor_linop_backend, set_tensor_linop_backend, tensor_contract

quimb.tensor.tensor_core.get_contract_strategy()[source]

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

quimb.tensor.tensor_core.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.tensor_core.inds_to_eq(inputs, output=None)[source]

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

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

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

Returns:

eq – The string to feed to einsum/contract.

Return type:

str

quimb.tensor.tensor_core.inds_to_symbols(inputs)[source]

Map a sequence of inputs terms, containing any hashable indices, to single unicode letters, appropriate for einsum.

Parameters:

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

Returns:

symbols – The mapping from index to symbol.

Return type:

dict[hashable, str]

quimb.tensor.tensor_core.auto_color_html(s)[source]

Automatically hash and color a string for HTML display.

quimb.tensor.tensor_core.draw_tn(tn, color=None, *, show_inds=None, show_tags=None, output_inds=None, highlight_inds=(), highlight_tids=(), highlight_inds_color=(1.0, 0.2, 0.2), highlight_tids_color=(1.0, 0.2, 0.2), custom_colors=None, legend='auto', dim=2, fix=None, layout='auto', initial_layout='auto', refine_layout='auto', iterations='auto', k=None, pos=None, node_color=None, node_scale=1.0, node_size=None, node_alpha=1.0, node_shape='o', node_outline_size=None, node_outline_darkness=0.9, node_hatch='', edge_color=None, edge_scale=1.0, edge_alpha=1 / 2, multi_edge_spread=0.1, multi_tag_style='auto', show_left_inds=True, arrow_opts=None, label_color=None, font_size=10, font_size_inner=7, font_family='monospace', isdark=None, title=None, backend='matplotlib', figsize=(6, 6), margin=None, xlims=None, ylims=None, get=None, return_fig=False, ax=None)[source]

Plot this tensor network as a networkx graph using matplotlib, with edge width corresponding to bond dimension.

Parameters:
  • color (sequence of tags, optional) – If given, uniquely color any tensors which have each of the tags. If some tensors have more than of the tags, only one color will show.

  • output_inds (sequence of str, optional) – For hyper tensor networks explicitly specify which indices should be drawn as outer indices. If not set, the outer indices are assumed to be those that only appear on a single tensor.

  • highlight_inds (iterable, optional) – Highlight these edges.

  • highlight_tids (iterable, optional) – Highlight these nodes.

  • highlight_inds_color – What color to use for highlight_inds nodes.

  • highlight_tids_color (tuple[float], optional) – What color to use for highlight_tids nodes.

  • show_inds ({None, False, True, 'all', 'bond-size'}, optional) – Explicitly turn on labels for each tensors indices.

  • show_tags ({None, False, True}, optional) – Explicitly turn on labels for each tensors tags.

  • custom_colors (sequence of colors, optional) – Supply a custom sequence of colors to match the tags given in color.

  • title (str, optional) – Set a title for the axis.

  • legend ("auto" or bool, optional) – Whether to draw a legend for the colored tags. If "auto" then only draw a legend if there are less than 20 tags.

  • dim ({2, 2.5, 3}, optional) – What dimension to position the graph nodes in. 2.5 positions the nodes in 3D but then projects then down to 2D.

  • fix (dict[tags_ind_or_tid], (float, float)], optional) – Used to specify actual relative positions for each tensor node. Each key should be a sequence of tags that uniquely identifies a tensor, a tid, or a ind, and each value should be a (x, y) coordinate tuple.

  • layout (str, optional) –

    How to layout the graph. Can be any of the following:

    • 'auto': layout the graph using a networkx method then relax the layout using a force-directed algorithm.

    • a networkx layout method name, e.g. 'kamada_kawai': just layout the graph using a networkx method, with no relaxation.

    • a graphviz method such as 'dot', 'neato' or 'sfdp': layout the graph using pygraphviz.

  • initial_layout ({'auto', 'spectral', 'kamada_kawai', 'circular', ) – ‘planar’, ‘random’, ‘shell’, ‘bipartite’, …}, optional If layout == 'auto' The name of a networkx layout to use before iterating with the spring layout. Set layout directly or iterations=0 if you don’t want any spring relaxation.

  • iterations (int, optional) – How many iterations to perform when when finding the best layout using node repulsion. Ramp this up if the graph is drawing messily.

  • k (float, optional) – The optimal distance between nodes.

  • pos (dict, optional) – Pre-computed positions for the nodes. If given, this will override layout. The nodes shouuld be exactly the same as the nodes in the graph returned by draw(get='graph').

  • node_color (tuple[float], optional) – Default color of nodes.

  • node_scale (float, optional) – Scale the node sizes by this factor, in addition to the automatic scaling based on the number of tensors.

  • node_size (None, float or dict, optional) – How big to draw the tensors. Can be a global single value, or a dict containing values for specific tags or tids. This is in absolute figure units. See node_scale simply scale the node sizes up or down.

  • node_alpha (float, optional) – Transparency of the nodes.

  • node_shape (None, str or dict, optional) – What shape to draw the tensors. Should correspond to a matplotlib scatter marker. Can be a global single value, or a dict containing values for specific tags or tids.

  • node_outline_size (None, float or dict, optional) – The width of the border of each node. Can be a global single value, or a dict containing values for specific tags or tids.

  • node_outline_darkness (float, optional) – Darkening of nodes outlines.

  • edge_color (tuple[float], optional) – Default color of edges.

  • edge_scale (float, optional) – How much to scale the width of the edges.

  • edge_alpha (float, optional) – Set the alpha (opacity) of the drawn edges.

  • multi_edge_spread (float, optional) – How much to spread the lines of multi-edges.

  • show_left_inds (bool, optional) – Whether to show tensor.left_inds as incoming arrows.

  • arrow_closeness (float, optional) – How close to draw the arrow to its target.

  • arrow_length (float, optional) – The size of the arrow with respect to the edge.

  • arrow_overhang (float, optional) – Varies the arrowhead between a triangle (0.0) and ‘V’ (1.0).

  • arrow_linewidth (float, optional) – The width of the arrow line itself.

  • label_color (tuple[float], optional) – Color to draw labels with.

  • font_size (int, optional) – Font size for drawing tags and outer indices.

  • font_size_inner (int, optional) – Font size for drawing inner indices.

  • font_family (str, optional) – Font family to use for all labels.

  • isdark (bool, optional) – Explicitly specify that the background is dark, and use slightly different default drawing colors. If not specified detects automatically from matplotlib.rcParams.

  • figsize (tuple of int, optional) – The size of the drawing.

  • margin (None or float, optional) – Specify an argument for ax.margin, else the plot limits will try and be computed based on the node positions and node sizes.

  • xlims (None or tuple, optional) – Explicitly set the x plot range.

  • xlims – Explicitly set the y plot range.

  • get ({None, 'pos', 'graph'}, optional) –

    If None then plot as normal, else if:

    • 'pos', return the plotting positions of each tid and ind drawn as a node, this can supplied to subsequent calls as fix=pos to maintain positions, even as the graph structure changes.

    • 'graph', return the networkx.Graph object. Note that this will potentially have extra nodes representing output and hyper indices.

  • return_fig (bool, optional) – If True and ax is None then return the figure created rather than executing pyplot.show().

  • ax (matplotlib.Axis, optional) – Draw the graph on this axis rather than creating a new figure.

quimb.tensor.tensor_core.visualize_tensor(tensor, **kwargs)[source]

Visualize all entries of a tensor, with indices mapped into the plane and values mapped into a color wheel.

Parameters:
  • tensor (Tensor) – The tensor to visualize.

  • skew_factor (float, optional) – When there are more than two dimensions, a factor to scale the rotations by to avoid overlapping data points.

  • size_map (bool, optional) – Whether to map the tensor value magnitudes to marker size.

  • size_scale (float, optional) – An overall factor to scale the marker size by.

  • alpha_map (bool, optional) – Whether to map the tensor value magnitudes to marker alpha.

  • alpha_pow (float, optional) – The power to raise the magnitude to when mapping to alpha.

  • alpha (float, optional) – The overall alpha to use for all markers if not alpha_map.

  • show_lattice (bool, optional) – Show a small grey dot for every ‘lattice’ point regardless of value.

  • lattice_opts (dict, optional) – Options to pass to maplotlib.Axis.scatter for the lattice points.

  • linewidths (float, optional) – The linewidth to use for the markers.

  • marker (str, optional) – The marker to use for the markers.

  • figsize (tuple, optional) – The size of the figure to create, if ax is not provided.

  • ax (matplotlib.Axis, optional) – The axis to draw to. If not provided, a new figure will be created.

Returns:

  • fig (matplotlib.Figure) – The figure containing the plot, or None if ax was provided.

  • ax (matplotlib.Axis) – The axis containing the plot.

quimb.tensor.tensor_core.visualize_tensors(tn, mode='network', r=None, r_scale=1.0, figsize=None, **visualize_opts)[source]

Visualize all the entries of every tensor in this network.

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

  • mode ({'network', 'grid', 'row', 'col'}, optional) –

    How to arrange each tensor’s visualization.

    • 'network': arrange each tensor’s visualization according to the

      automatic layout given by draw.

    • 'grid': arrange each tensor’s visualization in a grid.

    • 'row': arrange each tensor’s visualization horizontally.

    • 'col': arrange each tensor’s visualization vertically.

  • r (float, optional) – The absolute radius of each tensor’s visualization, when mode='network'.

  • r_scale (float, optional) – A relative scaling factor for the radius of each tensor’s visualization, when mode='network'.

  • figsize (tuple, optional) – The size of the figure to create, if ax is not provided.

  • visualize_opts – Supplied to visualize_tensor.

quimb.tensor.tensor_core.tensor_network_distance(tnA, tnB, xAA=None, xAB=None, xBB=None, method='auto', normalized=False, **contract_opts)[source]

Compute the Frobenius norm distance between two tensor networks:

\[D(A, B) = | A - B |_{\mathrm{fro}} = \mathrm{Tr} [(A - B)^{\dagger}(A - B)]^{1/2} = ( \langle A | A \rangle - 2 \mathrm{Re} \langle A | B \rangle| + \langle B | B \rangle ) ^{1/2}\]

which should have matching outer indices. Note the default approach to computing the norm is precision limited to about eps**0.5 where eps is the precision of the data type, e.g. 1e-8 for float64. This is due to the subtraction in the above expression.

Parameters:
  • tnA (TensorNetwork or Tensor) – The first tensor network operator.

  • tnB (TensorNetwork or Tensor) – The second tensor network operator.

  • xAA (None or scalar) – The value of A.H @ A if you already know it (or it doesn’t matter).

  • xAB (None or scalar) – The value of A.H @ B if you already know it (or it doesn’t matter).

  • xBB (None or scalar) – The value of B.H @ B if you already know it (or it doesn’t matter).

  • method ({'auto', 'overlap', 'dense'}, optional) – How to compute the distance. If 'overlap', the default, the distance will be computed as the sum of overlaps, without explicitly forming the dense operators. If 'dense', the operators will be directly formed and the norm computed, which can be quicker when the exterior dimensions are small. If 'auto', the dense method will be used if the total operator (outer) size is <= 2**16.

  • normalized (bool, optional) – If True, then normalize the distance by the norm of the two operators, i.e. 2 * D(A, B) / (|A| + |B|). The resulting distance lies between 0 and 2 and is more useful for assessing convergence.

  • contract_opts – Supplied to contract().

Returns:

D

Return type:

float

quimb.tensor.tensor_core.tensor_network_fit_als(tn, tn_target, tags=None, steps=100, tol=1e-09, solver='solve', enforce_pos=False, pos_smudge=None, tnAA=None, tnAB=None, xBB=None, contract_optimize='greedy', inplace=False, progbar=False)[source]

Optimize the fit of tn with respect to tn_target using alternating least squares (ALS). This minimizes the norm of the difference between the two tensor networks, which must have matching outer indices, using overlaps.

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

  • tn_target (TensorNetwork) – The target tensor network to fit tn to.

  • tags (sequence of str, optional) – If supplied, only optimize tensors matching any of given tags.

  • steps (int, optional) – The maximum number of ALS steps.

  • tol (float, optional) – The target norm distance.

  • solver ({'solve', 'lstsq', ...}, optional) – The underlying driver function used to solve the local minimization, e.g. numpy.linalg.solve for 'solve' with numpy backend.

  • enforce_pos (bool, optional) – Whether to enforce positivity of the locally formed environments, which can be more stable.

  • pos_smudge (float, optional) – If enforcing positivity, the level below which to clip eigenvalues for make the local environment positive definite.

  • tnAA (TensorNetwork, optional) – If you have already formed the overlap tn.H & tn, maybe approximately, you can supply it here. The unconjugated layer should have tag '__KET__' and the conjugated layer '__BRA__'. Each tensor being optimized should have tag '__VAR{i}__'.

  • tnAB (TensorNetwork, optional) – If you have already formed the overlap tn_target.H & tn, maybe approximately, you can supply it here. Each tensor being optimized should have tag '__VAR{i}__'.

  • xBB (float, optional) – If you have already know, have computed tn_target.H @ tn_target, or it doesn’t matter, you can supply the value here.

  • contract_optimize (str, optional) – The contraction path optimized used to contract the local environments. Note 'greedy' is the default in order to maximize shared work.

  • inplace (bool, optional) – Update tn in place.

  • progbar (bool, optional) – Show a live progress bar of the fitting process.

Return type:

TensorNetwork

quimb.tensor.tensor_core.tensor_network_fit_autodiff(tn, tn_target, steps=1000, tol=1e-09, autodiff_backend='autograd', contract_optimize='auto-hq', distance_method='auto', inplace=False, progbar=False, **kwargs)[source]

Optimize the fit of tn with respect to tn_target using automatic differentation. This minimizes the norm of the difference between the two tensor networks, which must have matching outer indices, using overlaps.

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

  • tn_target (TensorNetwork) – The target tensor network to fit tn to.

  • steps (int, optional) – The maximum number of autodiff steps.

  • tol (float, optional) – The target norm distance.

  • autodiff_backend (str, optional) – Which backend library to use to perform the gradient computation.

  • contract_optimize (str, optional) – The contraction path optimized used to contract the overlaps.

  • distance_method ({'auto', 'dense', 'overlap'}, optional) – Supplied to tensor_network_distance(), controls how the distance is computed.

  • inplace (bool, optional) – Update tn in place.

  • progbar (bool, optional) – Show a live progress bar of the fitting process.

  • kwargs – Passed to TNOptimizer.

quimb.tensor.tensor_core._inds_to_eq[source]
quimb.tensor.tensor_core.get_symbol[source]
quimb.tensor.tensor_core.oset_union(xs)[source]

Non-variadic ordered set union taking any sequence of iterables.

quimb.tensor.tensor_core.oset_intersection(xs)[source]
quimb.tensor.tensor_core.tags_to_oset(tags)[source]

Parse a tags argument into an ordered set.

quimb.tensor.tensor_core.sortedtuple(x)[source]
quimb.tensor.tensor_core._gen_output_inds(all_inds)[source]

Generate the output, i.e. unique, indices from the set inds. Raise if any index found more than twice.

quimb.tensor.tensor_core._VALID_CONTRACT_GET
quimb.tensor.tensor_core._tensor_contract_get_other(arrays, inds, inds_out, shapes, get, **contract_opts)[source]
quimb.tensor.tensor_core.maybe_realify_scalar(data)[source]

If data is a numpy array, check if its complex with small imaginary part, and if so return only the real part, otherwise do nothing.

quimb.tensor.tensor_core.tensor_contract(*tensors, output_inds=None, optimize=None, get=None, backend=None, preserve_tensor=False, drop_tags=False, **contract_opts)[source]

Contract a collection of tensors into a scalar or tensor, automatically aligning their indices and computing an optimized contraction path. The output tensor will have the union of tags from the input tensors.

Parameters:
  • tensors (sequence of Tensor) – The tensors to contract.

  • output_inds (sequence of str) – The output indices. These can be inferred if the contraction has no ‘hyper’ indices, in which case the output indices are those that appear only once in the input indices, and ordered as they appear in the inputs. For hyper indices or a specific ordering, these must be supplied.

  • optimize ({None, str, path_like, PathOptimizer}, optional) –

    The contraction path optimization strategy to use.

    • None: use the default strategy,

    • str: use the preset strategy with the given name,

    • path_like: use this exact path,

    • cotengra.HyperOptimizer: find the contraction using this optimizer, supports slicing,

    • cotengra.ContractionTree: use this exact tree, supports slicing,

    • opt_einsum.PathOptimizer: find the path using this optimizer.

    Contraction with cotengra might be a bit more efficient but the main reason would be to handle sliced contraction automatically, as well as the fact that it uses autoray internally.

  • get (str, optional) –

    What to return. If:

    • None (the default) - return the resulting scalar or Tensor.

    • 'expression' - return a callbable expression that performs the contraction and operates on the raw arrays.

    • 'tree' - return the cotengra.ContractionTree describing the contraction.

    • 'path' - return the raw ‘path’ as a list of tuples.

    • 'symbol-map' - return the dict mapping indices to ‘symbols’ (single unicode letters) used internally by cotengra

    • 'path-info' - return the opt_einsum.PathInfo path object with detailed information such as flop cost. The symbol-map is also added to the quimb_symbol_map attribute.

  • backend ({'auto', 'numpy', 'jax', 'cupy', 'tensorflow', ...}, optional) – Which backend to use to perform the contraction. Supplied to cotengra.

  • preserve_tensor (bool, optional) – Whether to return a tensor regardless of whether the output object is a scalar (has no indices) or not.

  • drop_tags (bool, optional) – Whether to drop all tags from the output tensor. By default the output tensor will keep the union of all tags from the input tensors.

  • contract_opts – Passed to cotengra.array_contract.

Return type:

scalar or Tensor

quimb.tensor.tensor_core._RAND_PREFIX
quimb.tensor.tensor_core._RAND_ALPHABET
quimb.tensor.tensor_core.RAND_UUIDS
quimb.tensor.tensor_core.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_core._VALID_SPLIT_GET
quimb.tensor.tensor_core._SPLIT_FNS
quimb.tensor.tensor_core._SPLIT_VALUES_FNS
quimb.tensor.tensor_core._FULL_SPLIT_METHODS
quimb.tensor.tensor_core._RANK_HIDDEN_METHODS
quimb.tensor.tensor_core._DENSE_ONLY_METHODS
quimb.tensor.tensor_core._LEFT_ISOM_METHODS
quimb.tensor.tensor_core._RIGHT_ISOM_METHODS
quimb.tensor.tensor_core._ISOM_METHODS
quimb.tensor.tensor_core._CUTOFF_LOOKUP
quimb.tensor.tensor_core._ABSORB_LOOKUP
quimb.tensor.tensor_core._MAX_BOND_LOOKUP
quimb.tensor.tensor_core._CUTOFF_MODES
quimb.tensor.tensor_core._RENORM_LOOKUP
quimb.tensor.tensor_core._parse_split_opts(method, cutoff, absorb, max_bond, cutoff_mode, renorm)[source]
quimb.tensor.tensor_core._check_left_right_isom(method, absorb)[source]
quimb.tensor.tensor_core.tensor_split(T, left_inds, method='svd', get=None, absorb='both', max_bond=None, cutoff=1e-10, cutoff_mode='rel', renorm=None, ltags=None, rtags=None, stags=None, bond_ind=None, right_inds=None)[source]

Decompose this tensor into two tensors.

Parameters:
  • T (Tensor or TNLinearOperator) – The tensor (network) to split.

  • left_inds (str or sequence of str) – The index or sequence of inds, which T should already have, to split to the ‘left’. You can supply None here if you supply right_inds instead.

  • method (str, optional) –

    How to split the tensor, only some methods allow bond truncation:

    • 'svd': full SVD, allows truncation.

    • 'eig': full SVD via eigendecomp, allows truncation.

    • 'lu': full LU decomposition, allows truncation. This method favors tensor sparsity but is not rank optimal.

    • 'svds': iterative svd, allows truncation.

    • 'isvd': iterative svd using interpolative methods, allows truncation.

    • 'rsvd' : randomized iterative svd with truncation.

    • 'eigh': full eigen-decomposition, tensor must he hermitian.

    • 'eigsh': iterative eigen-decomposition, tensor must be hermitian.

    • 'qr': full QR decomposition.

    • 'lq': full LR decomposition.

    • 'polar_right': full polar decomposition as A = UP.

    • 'polar_left': full polar decomposition as A = PU.

    • 'cholesky': full cholesky decomposition, tensor must be positive.

  • get ({None, 'arrays', 'tensors', 'values'}) –

    If given, what to return instead of a TN describing the split:

    • None: a tensor network of the two (or three) tensors.

    • 'arrays': the raw data arrays as a tuple (l, r) or (l, s, r) depending on absorb.

    • 'tensors ': the new tensors as a tuple (Tl, Tr) or (Tl, Ts, Tr) depending on absorb.

    • 'values': only compute and return the singular values s.

  • absorb ({'both', 'left', 'right', None}, optional) – Whether to absorb the singular values into both, the left, or the right unitary matrix respectively, or neither. If neither (absorb=None) then the singular values will be returned separately in their own 1D tensor or array. In that case if get=None the tensor network returned will have a hyperedge corresponding to the new bond index connecting three tensors. If get='tensors' or get='arrays' then a tuple like (left, s, right) is returned.

  • max_bond (None or int) – If integer, the maximum number of singular values to keep, regardless of cutoff.

  • cutoff (float, optional) – The threshold below which to discard singular values, only applies to rank revealing methods (not QR, LQ, or cholesky).

  • cutoff_mode ({'sum2', 'rel', 'abs', 'rsum2'}) –

    Method with which to apply the cutoff threshold:

    • 'rel': values less than cutoff * s[0] discarded.

    • 'abs': values less than cutoff discarded.

    • 'sum2': sum squared of values discarded must be < cutoff.

    • 'rsum2': sum squared of values discarded must be less than cutoff times the total sum of squared values.

    • 'sum1': sum values discarded must be < cutoff.

    • 'rsum1': sum of values discarded must be less than cutoff times the total sum of values.

  • renorm ({None, bool, or int}, optional) – Whether to renormalize the kept singular values, assuming the bond has a canonical environment, corresponding to maintaining the frobenius or nuclear norm. If None (the default) then this is automatically turned on only for cutoff_method in {'sum2', 'rsum2', 'sum1', 'rsum1'} with method in {'svd', 'eig', 'eigh'}.

  • ltags (sequence of str, optional) – Add these new tags to the left tensor.

  • rtags (sequence of str, optional) – Add these new tags to the right tensor.

  • stags (sequence of str, optional) – Add these new tags to the singular value tensor.

  • bond_ind (str, optional) – Explicitly name the new bond, else a random one will be generated.

  • right_inds (sequence of str, optional) – Explicitly give the right indices, otherwise they will be worked out. This is a minor performance feature.

Returns:

Depending on if get is None, 'tensors', 'arrays', or 'values'. In the first three cases, if absorb is set, then the returned objects correspond to (left, right) whereas if absorb=None the returned objects correspond to (left, singular_values, right).

Return type:

TensorNetwork or tuple[Tensor] or tuple[array] or 1D-array

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

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

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

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

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

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

quimb.tensor.tensor_core.choose_local_compress_gauge_settings(canonize=True, tree_gauge_distance=None, canonize_distance=None, canonize_after_distance=None, mode='auto')[source]

Choose default gauge settings for arbitrary geometry local compression.

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

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

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

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

  • T2 (Tensor) – The right tensor.

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

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

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

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

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

  • compress_opts – Supplied to tensor_split().

quimb.tensor.tensor_core.tensor_balance_bond(t1, t2, smudge=1e-06)[source]

Gauge the bond between two tensors such that the norm of the ‘columns’ of the tensors on each side is the same for each index of the bond.

Parameters:
  • t1 (Tensor) – The first tensor, should share a single index with t2.

  • t2 (Tensor) – The second tensor, should share a single index with t1.

  • smudge (float, optional) – Avoid numerical issues by ‘smudging’ the correctional factor by this much - the gauging introduced is still exact.

quimb.tensor.tensor_core.tensor_multifuse(ts, inds, gauges=None)[source]

For tensors ts which should all have indices inds, fuse the those bonds together, optionally updating gauges if present. Inplace operation.

quimb.tensor.tensor_core.tensor_make_single_bond(t1, t2, gauges=None)[source]

If two tensors share multibonds, fuse them together and return the left indices, bond if it exists, and right indices. Handles simple gauges. Inplace operation.

quimb.tensor.tensor_core.tensor_fuse_squeeze(t1, t2, squeeze=True, gauges=None)[source]

If t1 and t2 share more than one bond fuse it, and if the size of the shared dimenion(s) is 1, squeeze it. Inplace operation.

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

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

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

  • T2 (Tensor) – Second tensor to modify.

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

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

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

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

quimb.tensor.tensor_core.rand_padder(vector, pad_width, iaxis, kwargs)[source]

Helper function for padding tensor with random entries.

quimb.tensor.tensor_core.array_direct_product(X, Y, sum_axes=())[source]

Direct product of two arrays.

Parameters:
  • X (numpy.ndarray) – First tensor.

  • Y (numpy.ndarray) – Second tensor, same shape as X.

  • sum_axes (sequence of int) – Axes to sum over rather than direct product, e.g. physical indices when adding tensor networks.

Returns:

Z – Same shape as X and Y, but with every dimension the sum of the two respective dimensions, unless it is included in sum_axes.

Return type:

numpy.ndarray

quimb.tensor.tensor_core.tensor_direct_product(T1, T2, sum_inds=(), inplace=False)[source]

Direct product of two Tensors. Any axes included in sum_inds must be the same size and will be summed over rather than concatenated. Summing over contractions of TensorNetworks equates to contracting a TensorNetwork made of direct products of each set of tensors. I.e. (a1 @ b1) + (a2 @ b2) == (a1 (+) a2) @ (b1 (+) b2).

Parameters:
  • T1 (Tensor) – The first tensor.

  • T2 (Tensor) – The second tensor, with matching indices and dimensions to T1.

  • sum_inds (sequence of str, optional) – Axes to sum over rather than combine, e.g. physical indices when adding tensor networks.

  • inplace (bool, optional) – Whether to modify T1 inplace.

Returns:

Like T1, but with each dimension doubled in size if not in sum_inds.

Return type:

Tensor

quimb.tensor.tensor_core.tensor_network_sum(tnA, tnB, inplace=False)[source]

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

Parameters:
Returns:

The sum of tnA and tnB, with increased bond dimensions.

Return type:

TensorNetwork

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

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

quimb.tensor.tensor_core.bonds_size(t1, t2)[source]

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

quimb.tensor.tensor_core.group_inds(t1, t2)[source]

Group bonds into left only, shared, and right only. If t1 or t2 are TensorNetwork objects, then only outer indices are considered.

Parameters:
Returns:

  • left_inds (list[str]) – Indices only in t1.

  • shared_inds (list[str]) – Indices in both t1 and t2.

  • right_inds (list[str]) – Indices only in t2.

quimb.tensor.tensor_core.connect(t1, t2, ax1, ax2)[source]

Connect two tensors by setting a shared index for the specified dimensions. This is an inplace operation that will also affect any tensor networks viewing these tensors.

Parameters:
  • t1 (Tensor) – The first tensor.

  • t2 – The second tensor.

  • ax1 (int) – The dimension (axis) to connect on the first tensor.

  • ax2 (int) – The dimension (axis) to connect on the second tensor.

Examples

>>> X = rand_tensor([2, 3], inds=['a', 'b'])
>>> Y = rand_tensor([3, 4], inds=['c', 'd'])
>>> tn = (X | Y)  # is *view* of tensors (``&`` would copy them)
>>> print(tn)
TensorNetwork([
    Tensor(shape=(2, 3), inds=('a', 'b'), tags=()),
    Tensor(shape=(3, 4), inds=('c', 'd'), tags=()),
])
>>> connect(X, Y, 1, 0)  # modifies tensors *and* viewing TN
>>> print(tn)
TensorNetwork([
    Tensor(shape=(2, 3), inds=('a', '_e9021e0000002'), tags=()),
    Tensor(shape=(3, 4), inds=('_e9021e0000002', 'd'), tags=()),
])
>>>  tn ^ all
Tensor(shape=(2, 4), inds=('a', 'd'), tags=())
quimb.tensor.tensor_core.get_tags(ts)[source]

Return all the tags in found in ts.

Parameters:

ts (Tensor, TensorNetwork or sequence of either) – The objects to combine tags from.

quimb.tensor.tensor_core.maybe_unwrap(t, preserve_tensor_network=False, preserve_tensor=False, equalize_norms=False, output_inds=None)[source]

Maybe unwrap a TensorNetwork or Tensor into a Tensor or scalar, depending on how many tensors and indices it has, optionally handling accrued exponent normalization and output index ordering (if a tensor).

Parameters:
  • t (Tensor or TensorNetwork) – The tensor or tensor network to unwrap.

  • preserve_tensor_network (bool, optional) – If True, then don’t unwrap a TensorNetwork to a Tensor even if it has only one tensor.

  • preserve_tensor (bool, optional) – If True, then don’t unwrap a Tensor to a scalar even if it has no indices.

  • equalize_norms (bool, optional) – If True, then equalize the norms of all tensors in the tensor network before unwrapping.

  • output_inds (sequence of str, optional) – If unwrapping a tensor, then transpose it to the specified indices.

Return type:

TensorNetwork, Tensor or Number

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

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

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

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

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

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

Examples

Basic construction:

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

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

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

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

set_params(params)[source]

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

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

Copy this tensor.

Note

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

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

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

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

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

property owners
add_owner(tn, tid)[source]

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

remove_owner(tn)[source]

Remove TensorNetwork tn as an owner of this Tensor.

check_owners()[source]

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

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

Overwrite the data of this tensor in place.

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

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

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

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

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

apply_to_arrays(fn)[source]

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

isel(selectors, inplace=False)[source]

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

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

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

Return type:

Tensor

Examples

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Return type:

Tensor

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

Conjugate this tensors data (does nothing to indices).

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

Change the type of this tensor to dtype.

astype_[source]
max_dim()[source]

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

ind_size(ind)[source]

Return the size of dimension corresponding to ind.

inds_size(inds)[source]

Return the total size of dimensions corresponding to inds.

shared_bond_size(other)[source]

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

inner_inds()[source]

Get all indices that appear on two or more tensors.

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

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

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

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

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

Returns:

tt – The transposed tensor.

Return type:

Tensor

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

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

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

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

Returns:

tt – The transposed tensor.

Return type:

Tensor

See also

transpose

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

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

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

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

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

Return type:

Tensor

moveindex_[source]
item()[source]

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

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

Trace index or indices left_inds with right_inds, removing them.

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

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

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

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

Returns:

z

Return type:

Tensor or scalar

sum_reduce(ind, inplace=False)[source]

Sum over index ind, removing it from this tensor.

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

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

Return type:

Tensor

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

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

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

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

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

Return type:

Tensor

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

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

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

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

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

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

Return type:

Tensor

Examples

Create a random tensor of 4 qubits:

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

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

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

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

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

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

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

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

Returns:

The singular values.

Return type:

1d-array

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

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

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

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

Return type:

float

retag(retag_map, inplace=False)[source]

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

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

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

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

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

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

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

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

Combine groups of indices into single indices.

Parameters:

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

Returns:

The transposed, reshaped and re-labeled tensor.

Return type:

Tensor

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

Reshape single indices into groups of multiple indices

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

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

Returns:

The transposed, reshaped and re-labeled tensor

Return type:

Tensor

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

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

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

Drop any singlet dimensions from this tensor.

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

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

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

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

Return type:

Tensor

squeeze_[source]
largest_element()[source]

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

idxmin(f=None)[source]

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

Parameters:

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

Returns:

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

Return type:

dict[str, int]

idxmax(f=None)[source]

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

Parameters:

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

Returns:

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

Return type:

dict[str, int]

norm()[source]

Frobenius norm of this tensor:

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

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

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

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

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

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

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

  • method (str, optional) –

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

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

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

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

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

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

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

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

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

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

Return type:

Tensor

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

Randomize the entries of this tensor.

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

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

  • randn_opts – Supplied to randn().

Return type:

Tensor

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

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

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

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

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

Check if this tensor is almost the same as another.

drop_tags(tags=None)[source]

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

bonds(other)[source]

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

filter_bonds(other)[source]

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

Parameters:

other (Tensor) – The other tensor.

Returns:

shared, unshared – The shared and unshared indices.

Return type:

(tuple[str], tuple[str])

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

Combine with another Tensor or TensorNetwork into a new TensorNetwork.

__or__(other)[source]

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

__matmul__(other)[source]

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

negate(inplace=False)[source]

Negate this tensor.

negate_[source]
__neg__()[source]

Negate this tensor.

as_network(virtual=True)[source]

Return a TensorNetwork with only this tensor.

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

Plot a graph of this tensor and its indices.

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

Helper for pickle.

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

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

_repr_info_extra()[source]

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

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

Render the general info as a string.

_repr_html_()[source]

Render this Tensor as HTML, for Jupyter notebooks.

__str__()[source]

Return str(self).

__repr__()[source]

Return repr(self).

quimb.tensor.tensor_core._make_copy_ndarray(d, ndim, dtype=float)[source]
quimb.tensor.tensor_core.COPY_tensor(d, inds, tags=None, dtype=float)[source]

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

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

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

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

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

Returns:

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

Return type:

Tensor

quimb.tensor.tensor_core.COPY_mps_tensors(d, inds, tags=None, dtype=float)[source]

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

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

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

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

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

Returns:

The len(inds) tensors describing the MPS, with physical legs ordered as supplied in inds.

Return type:

List[Tensor]

quimb.tensor.tensor_core.COPY_tree_tensors(d, inds, tags=None, dtype=float, ssa_path=None)[source]

Get the set of tree tensors representing the COPY tensor with dimension size d and number of dimensions len(inds), with exterior indices inds. The tree is generated by cycling through pairs.

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

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

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

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

Returns:

The len(inds) - 2 tensors describing the TTN, with physical legs ordered as supplied in inds.

Return type:

List[Tensor]

quimb.tensor.tensor_core._make_promote_array_func(op, meth_name)[source]
quimb.tensor.tensor_core._make_rhand_array_promote_func(op, meth_name)[source]
quimb.tensor.tensor_core._tensor_network_gate_inds_basic(tn, G, inds, ng, tags, contract, isparam, info, **compress_opts)[source]
quimb.tensor.tensor_core._tensor_network_gate_inds_lazy_split(tn, G, inds, ng, tags, contract, dims, **compress_opts)[source]
quimb.tensor.tensor_core._BASIC_GATE_CONTRACT
quimb.tensor.tensor_core._SPLIT_GATE_CONTRACT
quimb.tensor.tensor_core._VALID_GATE_CONTRACT
quimb.tensor.tensor_core.tensor_network_gate_inds(self, G, inds, contract=False, tags=None, info=None, inplace=False, **compress_opts)[source]

Apply the ‘gate’ G to indices inds, propagating them to the outside, as if applying G @ x.

Parameters:
  • G (array_ike) – The gate array to apply, should match or be factorable into the shape (*phys_dims, *phys_dims).

  • inds (str or sequence or str,) – The index or indices to apply the gate to.

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

    ‘swap-split-gate’, ‘auto-split-gate’}, optional How to apply the gate:

    • False: gate is added to network lazily and nothing is contracted, tensor network structure is thus not maintained.

    • True: gate is contracted eagerly with all tensors involved, tensor network structure is thus only maintained if gate acts on a single site only.

    • ’split’: contract all involved tensors then split the result back into two.

    • ’reduce-split’: factor the two physical indices into ‘R-factors’ using QR decompositions on the original site tensors, then contract the gate, split it and reabsorb each side. Much cheaper than 'split'.

    • ’split-gate’: lazily add the gate as with False, but split the gate tensor spatially.

    • ’swap-split-gate’: lazily add the gate as with False, but split the gate as if an extra SWAP has been applied.

    • ’auto-split-gate’: lazily add the gate as with False, but maybe apply one of the above options depending on whether they result in a rank reduction.

    The named methods are relevant for two site gates only, for single site gates they use the contract=True option which also maintains the structure of the TN. See below for a pictorial description of each method.

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

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

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

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

Returns:

G_tn

Return type:

TensorNetwork

Notes

The contract options look like the following (for two site gates).

contract=False:

  .   .  <- inds
  │   │
  GGGGG
  │╱  │╱
──●───●──
 ╱   ╱

contract=True:

  │╱  │╱
──GGGGG──
 ╱   ╱

contract='split':

  │╱  │╱          │╱  │╱
──GGGGG──  ==>  ──G┄┄┄G──
 ╱   ╱           ╱   ╱
  <SVD>

contract='reduce-split':

  │   │             │ │
  GGGGG             GGG               │ │
  │╱  │╱   ==>     ╱│ │  ╱   ==>     ╱│ │  ╱          │╱  │╱
──●───●──       ──>─●─●─<──       ──>─GGG─<──  ==>  ──G┄┄┄G──
 ╱   ╱           ╱     ╱           ╱     ╱           ╱   ╱
<QR> <LQ>                            <SVD>

For one site gates when one of these ‘split’ methods is supplied contract=True is assumed.

contract='split-gate':

  │   │ <SVD>
  G~~~G
  │╱  │╱
──●───●──
 ╱   ╱

contract='swap-split-gate':

   ╲ ╱
    ╳
   ╱ ╲ <SVD>
  G~~~G
  │╱  │╱
──●───●──
 ╱   ╱

contract='auto-split-gate' chooses between the above two and False, depending on whether either results in a lower rank.

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

Bases: object

A collection of (as yet uncontracted) Tensors.

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

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

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

tensor_map

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

Type:

dict

tag_map

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

Type:

dict

ind_map

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

Type:

dict

exponent

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

Type:

float

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

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

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

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

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

Return type:

TensorNetwork

__and__(other)[source]

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

__or__(other)[source]

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

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

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

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

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

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

  • tn (TensorNetwork) – The TensorNetwork to convert.

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

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

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

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

View this tensor network as subclass cls.

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

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

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

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

__copy__[source]
get_params()[source]

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

set_params(params)[source]

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

Link tid to each of tags.

“Unlink tid from each of tags.

Link tid to each of inds.

“Unlink tid from each of inds.

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

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

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

Add Tensor, TensorNetwork or sequence thereof to self.

make_tids_consecutive(tid0=0)[source]

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

__iand__(tensor)[source]

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

__ior__(tensor)[source]

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

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

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

remove_all_tensors()[source]

Remove all tensors from this network.

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

Delete any tensors which match all or any of tags.

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

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

check()[source]

Check some basic diagnostics of the tensor network.

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

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

drop_tags(tags=None)[source]

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

Parameters:

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

retag(tag_map, inplace=False)[source]

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

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

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

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

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

Parameters:

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

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

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

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

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

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

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

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

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

largest_element()[source]

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

norm(**contract_opts)[source]

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

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

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

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

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

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

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

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

multiply(x, inplace=False, spread_over=8)[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_[source]
multiply_each(x, inplace=False)[source]

Scalar multiplication of each tensor in this tensor network with x. If trying to spread a multiplicative factor fac uniformly over all tensors in the network and the number of tensors is large, then calling multiply(fac) can be inaccurate due to precision loss. If one has a routine that can precisely compute the x to be applied to each tensor, then this function avoids the potential inaccuracies in multiply().

Parameters:
  • x (scalar) – The number that multiplies each tensor in the network

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

multiply_each_[source]
negate(inplace=False)[source]

Negate this tensor network.

negate_[source]
__mul__(other)[source]

Scalar multiplication.

__rmul__(other)[source]

Right side scalar multiplication.

__imul__(other)[source]

Inplace scalar multiplication.

__truediv__(other)[source]

Scalar division.

__itruediv__(other)[source]

Inplace scalar division.

__neg__()[source]

Negate this tensor network.

__iter__()[source]
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.

get_equation(output_inds=None)[source]

Get the ‘equation’ describing this tensor network, in einsum style with a single unicode letter per index. The symbols are generated in the order they appear on the tensors.

Parameters:

output_inds (None or sequence of str, optional) – Manually specify which are the output indices.

Returns:

eq

Return type:

str

Examples

>>> tn = qtn.TN_rand_reg(10, 3, 2)
>>> tn.get_equation()
'abc,dec,fgb,hia,jke,lfk,mnj,ing,omd,ohl->'
get_inputs_output_size_dict(output_inds=None)[source]

Get a tuple of inputs, output and size_dict suitable for e.g. passing to path optimizers. The symbols are generated in the order they appear on the tensors.

Parameters:

output_inds (None or sequence of str, optional) – Manually specify which are the output indices.

Returns:

  • inputs (tuple[str])

  • output (str)

  • size_dict (dict[str, ix])

geometry_hash(output_inds=None, strict_index_order=False)[source]

A hash of this tensor network’s shapes & geometry. A useful check for determinism. Moreover, if this matches for two tensor networks then they can be contracted using the same tree for the same cost. Order of tensors matters for this - two isomorphic tensor networks with shuffled tensor order will not have the same hash value. Permuting the indices of individual of tensors or the output does not matter unless you set strict_index_order=True.

Parameters:
  • output_inds (None or sequence of str, optional) – Manually specify which indices are output indices and their order, otherwise assumed to be all indices that appear once.

  • strict_index_order (bool, optional) – If False, then the permutation of the indices of each tensor and the output does not matter.

Return type:

str

Examples

If we transpose some indices, then only the strict hash changes:

>>> tn = qtn.TN_rand_reg(100, 3, 2, seed=0)
>>> tn.geometry_hash()
'18c702b2d026dccb1a69d640b79d22f3e706b6ad'
>>> tn.geometry_hash(strict_index_order=True)
'c109fdb43c5c788c0aef7b8df7bb83853cf67ca1'
>>> t = tn['I0']
>>> t.transpose_(t.inds[2], t.inds[1], t.inds[0])
>>> tn.geometry_hash()
'18c702b2d026dccb1a69d640b79d22f3e706b6ad'
>>> tn.geometry_hash(strict_index_order=True)
'52c32c1d4f349373f02d512f536b1651dfe25893'
tensors_sorted()[source]

Return a tuple of tensors sorted by their respective tags, such that the tensors of two networks with the same tag structure can be iterated over pairwise.

apply_to_arrays(fn)[source]

Modify every tensor’s array inplace by applying fn to it. This is meant for changing how the raw arrays are backed (e.g. converting between dtypes or libraries) but not their ‘numerical meaning’.

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

Return the set of tensor ids that match tags.

Parameters:
  • tags (seq or str, str, None, ..., int, slice) – Tag specifier(s).

  • which ({'all', 'any', '!all', '!any'}) –

    How to select based on the tags, if:

    • ’all’: get ids of tensors matching all tags

    • ’any’: get ids of tensors matching any tags

    • ’!all’: get ids of tensors not matching all tags

    • ’!any’: get ids of tensors not matching any tags

Return type:

set[str]

_get_tids_from_inds(inds, which='all')[source]

Like _get_tids_from_tags but specify inds instead.

_tids_get(*tids)[source]

Convenience function that generates unique tensors from tids.

_inds_get(*inds)[source]

Convenience function that generates unique tensors from inds.

_tags_get(*tags)[source]

Convenience function that generates unique tensors from tags.

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

Return the sequence of tensors that match tags. If which='all', each tensor must contain every tag. If which='any', each tensor can contain any of the tags.

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

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

Returns:

tagged_tensors – The tagged tensors.

Return type:

tuple of Tensor

_select_tids(tids, virtual=True)[source]

Get a copy or a virtual copy (doesn’t copy the tensors) of this TensorNetwork, only with the tensors corresponding to tids.

_select_without_tids(tids, virtual=True)[source]

Get a copy or a virtual copy (doesn’t copy the tensors) of this TensorNetwork, without the tensors corresponding to tids.

select(tags, which='all', virtual=True)[source]

Get a TensorNetwork comprising tensors that match all or any of tags, inherit the network properties/structure from self. This returns a view of the tensors not a copy.

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

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

  • virtual (bool, optional) – Whether the returned tensor network views the same tensors (the default) or takes copies (virtual=False) from self.

Returns:

tagged_tn – A tensor network containing the tagged tensors.

Return type:

TensorNetwork

select_any[source]
select_all[source]
select_neighbors(tags, which='any')[source]

Select any neighbouring tensors to those specified by tags.self

Parameters:
  • tags (sequence of str, int) – Tags specifying tensors.

  • which ({'any', 'all'}, optional) – How to select tensors based on tags.

Returns:

The neighbouring tensors.

Return type:

tuple[Tensor]

_select_local_tids(tids, max_distance=1, fillin=False, reduce_outer=None, inwards=False, virtual=True, include=None, exclude=None)[source]
select_local(tags, which='all', max_distance=1, fillin=False, reduce_outer=None, virtual=True, include=None, exclude=None)[source]

Select a local region of tensors, based on graph distance max_distance to any tagged tensors.

Parameters:
  • tags (str or sequence of str) – The tag or tag sequence defining the initial region.

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

  • max_distance (int, optional) – The maximum distance to the initial tagged region.

  • fillin (bool or int, optional) –

    Once the local region has been selected based on graph distance, whether and how many times to ‘fill-in’ corners by adding tensors connected multiple times. For example, if R is an initially tagged tensor and x are locally selected tensors:

      fillin=0       fillin=1       fillin=2
    
     | | | | |      | | | | |      | | | | |
    -o-o-x-o-o-    -o-x-x-x-o-    -x-x-x-x-x-
     | | | | |      | | | | |      | | | | |
    -o-x-x-x-o-    -x-x-x-x-x-    -x-x-x-x-x-
     | | | | |      | | | | |      | | | | |
    -x-x-R-x-x-    -x-x-R-x-x-    -x-x-R-x-x-
    

  • reduce_outer ({'sum', 'svd', 'svd-sum', 'reflect'}, optional) – Whether and how to reduce any outer indices of the selected region.

  • virtual (bool, optional) – Whether the returned tensor network should be a view of the tensors or a copy (virtual=False).

  • include (sequence of int, optional) – Only include tensor with these tids.

  • exclude (sequence of int, optional) – Only include tensor without these tids.

Return type:

TensorNetwork

__getitem__(tags)[source]

Get the tensor(s) associated with tags.

Parameters:

tags (str or sequence of str) – The tags used to select the tensor(s).

Return type:

Tensor or sequence of Tensors

__setitem__(tags, tensor)[source]

Set the single tensor uniquely associated with tags.

__delitem__(tags)[source]

Delete any tensors which have all of tags.

partition_tensors(tags, inplace=False, which='any')[source]

Split this TN into a list of tensors containing any or all of tags and a TensorNetwork of the the rest.

Parameters:
  • tags (sequence of str) – The list of tags to filter the tensors by. Use ... (Ellipsis) to filter all.

  • inplace (bool, optional) – If true, remove tagged tensors from self, else create a new network with the tensors removed.

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

Returns:

(u_tn, t_ts) – The untagged tensor network, and the sequence of tagged Tensors.

Return type:

(TensorNetwork, tuple of Tensors)

partition(tags, which='any', inplace=False)[source]

Split this TN into two, based on which tensors have any or all of tags. Unlike partition_tensors, both results are TNs which inherit the structure of the initial TN.

Parameters:
  • tags (sequence of str) – The tags to split the network with.

  • which ({'any', 'all'}) – Whether to split based on matching any or all of the tags.

  • inplace (bool) – If True, actually remove the tagged tensors from self.

Returns:

untagged_tn, tagged_tn – The untagged and tagged tensor networs.

Return type:

(TensorNetwork, TensorNetwork)

_split_tensor_tid(tid, left_inds, **split_opts)[source]
split_tensor(tags, left_inds, **split_opts)[source]

Split the single tensor uniquely identified by tags, adding the resulting tensors from the decomposition back into the network. Inplace operation.

replace_with_identity(where, which='any', inplace=False)[source]

Replace all tensors marked by where with an identity. E.g. if X denote where tensors:

---1  X--X--2---         ---1---2---
   |  |  |  |      ==>          |
   X--X--X  |                   |
Parameters:
  • where (tag or seq of tags) – Tags specifying the tensors to replace.

  • which ({'any', 'all'}) – Whether to replace tensors matching any or all the tags where.

  • inplace (bool) – Perform operation in place.

Returns:

The TN, with section replaced with identity.

Return type:

TensorNetwork

See also

replace_with_svd

replace_with_svd(where, left_inds, eps, *, which='any', right_inds=None, method='isvd', max_bond=None, absorb='both', cutoff_mode='rel', renorm=None, ltags=None, rtags=None, keep_tags=True, start=None, stop=None, inplace=False)[source]

Replace all tensors marked by where with an iteratively constructed SVD. E.g. if X denote where tensors:

                        :__       ___:
---X  X--X  X---        :  \     /   :
   |  |  |  |      ==>  :   U~s~VH---:
---X--X--X--X---        :__/     \   :
      |     +---        :         \__:
      X              left_inds       :
                                 right_inds
Parameters:
  • where (tag or seq of tags) – Tags specifying the tensors to replace.

  • left_inds (ind or sequence of inds) – The indices defining the left hand side of the SVD.

  • eps (float) – The tolerance to perform the SVD with, affects the number of singular values kept. See quimb.linalg.rand_linalg.estimate_rank().

  • which ({'any', 'all', '!any', '!all'}, optional) – Whether to replace tensors matching any or all the tags where, prefix with ‘!’ to invert the selection.

  • right_inds (ind or sequence of inds, optional) – The indices defining the right hand side of the SVD, these can be automatically worked out, but for hermitian decompositions the order is important and thus can be given here explicitly.

  • method (str, optional) – How to perform the decomposition, if not an iterative method the subnetwork dense tensor will be formed first, see tensor_split() for options.

  • max_bond (int, optional) – The maximum bond to keep, defaults to no maximum (-1).

  • ltags (sequence of str, optional) – Tags to add to the left tensor.

  • rtags (sequence of str, optional) – Tags to add to the right tensor.

  • keep_tags (bool, optional) – Whether to propagate tags found in the subnetwork to both new tensors or drop them, defaults to True.

  • start (int, optional) – If given, assume can use TNLinearOperator1D.

  • stop (int, optional) – If given, assume can use TNLinearOperator1D.

  • inplace (bool, optional) – Perform operation in place.

Return type:

TensorNetwork

replace_with_svd_[source]
replace_section_with_svd(start, stop, eps, **replace_with_svd_opts)[source]

Take a 1D tensor network, and replace a section with a SVD. See replace_with_svd().

Parameters:
  • start (int) – Section start index.

  • stop (int) – Section stop index, not included itself.

  • eps (float) – Precision of SVD.

  • replace_with_svd_opts – Supplied to replace_with_svd().

Return type:

TensorNetwork

convert_to_zero()[source]

Inplace conversion of this network to an all zero tensor network.

_contract_between_tids(tid1, tid2, equalize_norms=False, gauges=None, output_inds=None, **contract_opts)[source]
contract_between(tags1, tags2, **contract_opts)[source]

Contract the two tensors specified by tags1 and tags2 respectively. This is an inplace operation. No-op if the tensor specified by tags1 and tags2 is the same tensor.

Parameters:
  • tags1 – Tags uniquely identifying the first tensor.

  • tags2 (str or sequence of str) – Tags uniquely identifying the second tensor.

  • contract_opts – Supplied to tensor_contract().

contract_ind(ind, output_inds=None, **contract_opts)[source]

Contract tensors connected by ind.

gate_inds[source]
gate_inds_[source]
gate_inds_with_tn(inds, gate, gate_inds_inner, gate_inds_outer, inplace=False)[source]

Gate some indices of this tensor network with another tensor network. That is, rewire and then combine them such that the new tensor network has the same outer indices as before, but now includes gate:

gate_inds_outer
 :
 :         gate_inds_inner
 :         :
 :         :   inds               inds
 :  ┌────┐ :   : ┌────┬───        : ┌───────┬───
 ───┤    ├──  a──┤    │          a──┤       │
    │    │       │    ├───          │       ├───
 ───┤gate├──  b──┤self│     -->  b──┤  new  │
    │    │       │    ├───          │       ├───
 ───┤    ├──  c──┤    │          c──┤       │
    └────┘       └────┴───          └───────┴───

Where there can be arbitrary structure of tensors within both self and gate.

The case where some of target inds are not present is handled as so (here ‘c’ is missing so ‘x’ and ‘y’ are kept):

gate_inds_outer
 :
 :         gate_inds_inner
 :         :
 :         :   inds               inds
 :  ┌────┐ :   : ┌────┬───        : ┌───────┬───
 ───┤    ├──  a──┤    │          a──┤       │
    │    │       │    ├───          │       ├───
 ───┤gate├──  b──┤self│     -->  b──┤  new  │
    │    │       │    ├───          │       ├───
x───┤    ├──y    └────┘          x──┤    ┌──┘
    └────┘                          └────┴───y

Which enables convinient construction of various tensor networks, for example propagators, from scratch.

Parameters:
  • inds (str or sequence of str) – The current indices to gate. If an index is not present on the target tensor network, it is ignored and instead the resulting tensor network will have both the corresponding inner and outer index of the gate tensor network.

  • gate (Tensor or TensorNetwork) – The tensor network to gate with.

  • gate_inds_inner (sequence of str) – The indices of gate to join to the old inds, must be the same length as inds.

  • gate_inds_outer (sequence of str) – The indices of gate to make the new outer inds, must be the same length as inds.

Returns:

tn_gated

Return type:

TensorNetwork

gate_inds_with_tn_[source]
_compute_tree_gauges(tree, outputs)[source]

Given a tree of connected tensors, absorb the gauges from outside inwards, finally outputing the gauges associated with the outputs.

Parameters:
  • tree (sequence of (tid_outer, tid_inner, distance)) – The tree of connected tensors, see get_tree_span().

  • outputs (sequence of (tid, ind)) – Each output is specified by a tensor id and an index, such that having absorbed all gauges in the tree, the effective reduced factor of the tensor with respect to the index is returned.

Returns:

Gouts – The effective reduced factors of the tensor index pairs specified in outputs, each a matrix.

Return type:

sequence of array

_compress_between_virtual_tree_tids(tidl, tidr, max_bond, cutoff, r, absorb='both', include=None, exclude=None, span_opts=None, **compress_opts)[source]
_compute_bond_env(tid1, tid2, select_local_distance=None, select_local_opts=None, max_bond=None, cutoff=None, method='contract_around', contract_around_opts=None, contract_compressed_opts=None, optimize='auto-hq', include=None, exclude=None)[source]

Compute the local tensor environment of the bond(s), if cut, between two tensors.

_compress_between_full_bond_tids(tid1, tid2, max_bond, cutoff=0.0, absorb='both', renorm=False, method='eigh', select_local_distance=None, select_local_opts=None, env_max_bond='max_bond', env_cutoff='cutoff', env_method='contract_around', contract_around_opts=None, contract_compressed_opts=None, env_optimize='auto-hq', include=None, exclude=None)[source]
_compress_between_local_fit(tid1, tid2, max_bond, cutoff=0.0, absorb='both', method='als', select_local_distance=1, select_local_opts=None, include=None, exclude=None, **fit_opts)[source]
_compress_between_tids(tid1, tid2, max_bond=None, cutoff=1e-10, absorb='both', canonize_distance=None, canonize_opts=None, canonize_after_distance=None, canonize_after_opts=None, mode='basic', equalize_norms=False, gauges=None, gauge_smudge=1e-06, callback=None, **compress_opts)[source]
compress_between(tags1, tags2, max_bond=None, cutoff=1e-10, absorb='both', canonize_distance=0, canonize_opts=None, equalize_norms=False, **compress_opts)[source]

Compress the bond between the two single tensors in this network specified by tags1 and tags2 using tensor_compress_bond():

  |    |    |    |           |    |    |    |
==●====●====●====●==       ==●====●====●====●==
 /|   /|   /|   /|          /|   /|   /|   /|
  |    |    |    |           |    |    |    |
==●====1====2====●==  ==>  ==●====L----R====●==
 /|   /|   /|   /|          /|   /|   /|   /|
  |    |    |    |           |    |    |    |
==●====●====●====●==       ==●====●====●====●==
 /|   /|   /|   /|          /|   /|   /|   /|

This is an inplace operation. The compression is unlikely to be optimal with respect to the frobenius norm, unless the TN is already canonicalized at the two tensors. The absorb kwarg can be specified to yield an isometry on either the left or right resulting tensors.

Parameters:
  • tags1 – Tags uniquely identifying the first (‘left’) tensor.

  • tags2 (str or sequence of str) – Tags uniquely identifying the second (‘right’) tensor.

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

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

  • canonize_distance (int, optional) – How far to locally canonize around the target tensors first.

  • canonize_opts (None or dict, optional) – Other options for the local canonization.

  • equalize_norms (bool or float, optional) – If set, rescale the norms of all tensors modified to this value, stripping the rescaling factor into the exponent attribute.

  • compress_opts – Supplied to tensor_compress_bond().

See also

canonize_between

compress_all(max_bond=None, cutoff=1e-10, canonize=True, tree_gauge_distance=None, canonize_distance=None, canonize_after_distance=None, mode='auto', inplace=False, **compress_opts)[source]

Compress all bonds one by one in this network.

Parameters:
  • max_bond (int or None, optional) – The maxmimum bond dimension to compress to.

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

  • tree_gauge_distance (int, optional) – How far to include local tree gauge information when compressing. If the local geometry is a tree, then each compression will be locally optimal up to this distance.

  • canonize_distance (int, optional) – How far to locally canonize around the target tensors first, this is set automatically by tree_gauge_distance if not specified.

  • canonize_after_distance (int, optional) – How far to locally canonize around the target tensors after, this is set automatically by tree_gauge_distance, depending on mode if not specified.

  • mode ({'auto', 'basic', 'virtual-tree'}, optional) – The mode to use for compressing the bonds. If ‘auto’, will use ‘basic’ if tree_gauge_distance == 0 else ‘virtual-tree’.

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

  • compress_opts – Supplied to compress_between().

Return type:

TensorNetwork

See also

compress_between, canonize_all

compress_all_[source]
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_tree_[source]
compress_all_1d(max_bond=None, cutoff=1e-10, canonize=True, inplace=False, **compress_opts)[source]

Compress a tensor network that you know has a 1D topology, this proceeds by generating a spanning ‘tree’ from around the least central tensor, then optionally canonicalizing all bonds outwards and compressing inwards.

Parameters:
  • max_bond (int, optional) – The maximum bond dimension to compress to.

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

  • canonize (bool, optional) – Whether to canonize all bonds outwards first.

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

  • compress_opts – Supplied to tensor_compress_bond().

Return type:

TensorNetwork

compress_all_1d_[source]
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]
compress_all_simple_[source]
_canonize_between_tids(tid1, tid2, absorb='right', gauges=None, gauge_smudge=1e-06, equalize_norms=False, **canonize_opts)[source]
canonize_between(tags1, tags2, absorb='right', **canonize_opts)[source]

‘Canonize’ the bond between the two single tensors in this network specified by tags1 and tags2 using tensor_canonize_bond:

  |    |    |    |           |    |    |    |
--●----●----●----●--       --●----●----●----●--
 /|   /|   /|   /|          /|   /|   /|   /|
  |    |    |    |           |    |    |    |
--●----1----2----●--  ==>  --●---->~~~~R----●--
 /|   /|   /|   /|          /|   /|   /|   /|
  |    |    |    |           |    |    |    |
--●----●----●----●--       --●----●----●----●--
 /|   /|   /|   /|          /|   /|   /|   /|

This is an inplace operation. This can only be used to put a TN into truly canonical form if the geometry is a tree, such as an MPS.

Parameters:
  • tags1 – Tags uniquely identifying the first (‘left’) tensor, which will become an isometry.

  • tags2 (str or sequence of str) – Tags uniquely identifying the second (‘right’) tensor.

  • absorb ({'left', 'both', 'right'}, optional) – Which side of the bond to absorb the non-isometric operator.

  • canonize_opts – Supplied to tensor_canonize_bond().

See also

compress_between

reduce_inds_onto_bond(inda, indb, tags=None, drop_tags=False, combine=True, ndim_cutoff=3)[source]

Use QR factorization to ‘pull’ the indices inda and indb off of their respective tensors and onto the bond between them. This is an inplace operation.

_get_neighbor_tids(tids, exclude_inds=())[source]

Get the tids of tensors connected to the tensor(s) at tids.

Parameters:
  • tids (int or sequence of int) – The tensor identifier(s) to get the neighbors of.

  • exclude_inds (sequence of str, optional) – Exclude these indices from being considered as connections.

Return type:

oset[int]

_get_neighbor_inds(inds)[source]

Get the indices connected to the index(es) at inds.

Parameters:

inds (str or sequence of str) – The index(es) to get the neighbors of.

Return type:

oset[str]

_get_subgraph_tids(tids)[source]

Get the tids of tensors connected, by any distance, to the tensor or region of tensors tids.

_ind_to_subgraph_tids(ind)[source]

Get the tids of tensors connected, by any distance, to the index ind.

istree()[source]

Check if this tensor network has a tree structure, (treating multibonds as a single edge).

Examples

>>> MPS_rand_state(10, 7).istree()
True
>>> MPS_rand_state(10, 7, cyclic=True).istree()
False
isconnected()[source]

Check whether this tensor network is connected, i.e. whether there is a path between any two tensors, (including size 1 indices).

subgraphs(virtual=False)[source]

Split this tensor network into disconneceted subgraphs.

Parameters:

virtual (bool, optional) – Whether the tensor networks should view the original tensors or not - by default take copies.

Return type:

list[TensorNetwork]

get_tree_span(tids, min_distance=0, max_distance=None, include=None, exclude=None, ndim_sort='max', distance_sort='min', sorter=None, weight_bonds=True, inwards=True)[source]

Generate a tree on the tensor network graph, fanning out from the tensors identified by tids, up to a maximum of max_distance away. The tree can be visualized with draw_tree_span().

Parameters:
  • tids (sequence of str) – The nodes that define the region to span out of.

  • min_distance (int, optional) – Don’t add edges to the tree until this far from the region. For example, 1 will not include the last merges from neighboring tensors in the region defined by tids.

  • max_distance (None or int, optional) – Terminate branches once they reach this far away. If None there is no limit,

  • include (sequence of str, optional) – If specified, only tids specified here can be part of the tree.

  • exclude (sequence of str, optional) – If specified, tids specified here cannot be part of the tree.

  • ndim_sort ({'min', 'max', 'none'}, optional) – When expanding the tree, how to choose what nodes to expand to next, once connectivity to the current surface has been taken into account.

  • distance_sort ({'min', 'max', 'none'}, optional) – When expanding the tree, how to choose what nodes to expand to next, once connectivity to the current surface has been taken into account.

  • weight_bonds (bool, optional) – Whether to weight the ‘connection’ of a candidate tensor to expand out to using bond size as well as number of bonds.

Returns:

The ordered list of merges, each given as tuple (tid1, tid2, d) indicating merge tid1 -> tid2 at distance d.

Return type:

list[(str, str, int)]

See also

draw_tree_span

_draw_tree_span_tids(tids, span=None, min_distance=0, max_distance=None, include=None, exclude=None, ndim_sort='max', distance_sort='min', sorter=None, weight_bonds=True, color='order', colormap='Spectral', **draw_opts)[source]
draw_tree_span(tags, which='all', min_distance=0, max_distance=None, include=None, exclude=None, ndim_sort='max', distance_sort='min', weight_bonds=True, color='order', colormap='Spectral', **draw_opts)[source]

Visualize a generated tree span out of the tensors tagged by tags.

Parameters:
  • tags (str or sequence of str) – Tags specifiying a region of tensors to span out of.

  • which ({'all', 'any': '!all', '!any'}, optional) – How to select tensors based on the tags.

  • min_distance (int, optional) – See get_tree_span().

  • max_distance (None or int, optional) – See get_tree_span().

  • include (sequence of str, optional) – See get_tree_span().

  • exclude (sequence of str, optional) – See get_tree_span().

  • distance_sort ({'min', 'max'}, optional) – See get_tree_span().

  • color ({'order', 'distance'}, optional) – Whether to color nodes based on the order of the contraction or the graph distance from the specified region.

  • colormap (str) – The name of a matplotlib colormap to use.

See also

get_tree_span

graph_tree_span[source]
_canonize_around_tids(tids, min_distance=0, max_distance=None, include=None, exclude=None, span_opts=None, absorb='right', gauge_links=False, link_absorb='both', inwards=True, gauges=None, gauge_smudge=1e-06, **canonize_opts)[source]
canonize_around(tags, which='all', min_distance=0, max_distance=None, include=None, exclude=None, span_opts=None, absorb='right', gauge_links=False, link_absorb='both', equalize_norms=False, inplace=False, **canonize_opts)[source]

Expand a locally canonical region around tags:

          --●---●--
        |   |   |   |
      --●---v---v---●--
    |   |   |   |   |   |
  --●--->---v---v---<---●--
|   |   |   |   |   |   |   |
●--->--->---O---O---<---<---●
|   |   |   |   |   |   |   |
  --●--->---^---^---^---●--
    |   |   |   |   |   |
      --●---^---^---●--
        |   |   |   |
          --●---●--

                 <=====>
                 max_distance = 2 e.g.

Shown on a grid here but applicable to arbitrary geometry. This is a way of gauging a tensor network that results in a canonical form if the geometry is described by a tree (e.g. an MPS or TTN). The canonizations proceed inwards via QR decompositions.

The sequence generated by round-robin expanding the boundary of the originally specified tensors - it will only be unique for trees.

Parameters:
  • tags (str, or sequence or str) – Tags defining which set of tensors to locally canonize around.

  • which ({'all', 'any', '!all', '!any'}, optional) – How select the tensors based on tags.

  • min_distance (int, optional) – How close, in terms of graph distance, to canonize tensors away. See get_tree_span().

  • max_distance (None or int, optional) – How far, in terms of graph distance, to canonize tensors away. See get_tree_span().

  • include (sequence of str, optional) – How to build the spanning tree to canonize along. See get_tree_span().

  • exclude (sequence of str, optional) – How to build the spanning tree to canonize along. See get_tree_span().

  • {'min' (distance_sort) – How to build the spanning tree to canonize along. See get_tree_span().

  • 'max'} – How to build the spanning tree to canonize along. See get_tree_span().

  • optional – How to build the spanning tree to canonize along. See get_tree_span().

  • absorb ({'right', 'left', 'both'}, optional) – As we canonize inwards from tensor A to tensor B which to absorb the singular values into.

  • gauge_links (bool, optional) – Whether to gauge the links between branches of the spanning tree generated (in a Simple Update like fashion).

  • link_absorb ({'both', 'right', 'left'}, optional) – If performing the link gauging, how to absorb the singular values.

  • equalize_norms (bool or float, optional) – Scale the norms of tensors acted on to this value, accumulating the log10 scaled factors in self.exponent.

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

Return type:

TensorNetwork

See also

get_tree_span

canonize_around_[source]
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_canonize_[source]
gauge_all_simple(max_iterations=5, tol=0.0, smudge=1e-12, power=1.0, gauges=None, equalize_norms=False, progbar=False, inplace=False)[source]

Iterative gauge all the bonds in this tensor network with a ‘simple update’ like strategy.

gauge_all_simple_[source]
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_random_[source]
gauge_all(method='canonize', **gauge_opts)[source]

Gauge all bonds in this network using one of several strategies.

Parameters:
  • method (str, optional) – The method to use for gauging. One of “canonize”, “simple”, or “random”. Default is “canonize”.

  • gauge_opts (dict, optional) – Additional keyword arguments to pass to the chosen method.

gauge_all_[source]
_gauge_local_tids(tids, max_distance=1, max_iterations='max_distance', method='canonize', inwards=False, include=None, exclude=None, **gauge_local_opts)[source]

Iteratively gauge all bonds in the local tensor network defined by tids according to one of several strategies.

gauge_local(tags, which='all', max_distance=1, max_iterations='max_distance', method='canonize', inplace=False, **gauge_local_opts)[source]

Iteratively gauge all bonds in the tagged sub tensor network according to one of several strategies.

gauge_local_[source]
gauge_simple_insert(gauges, remove=False, smudge=0.0, power=1.0)[source]

Insert the simple update style bond gauges found in gauges if they are present in this tensor network. The gauges inserted are also returned so that they can be removed later.

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

  • remove (bool, optional) – Whether to remove the gauges from the store after inserting them.

  • smudge (float, optional) – A small value to add to the gauge vectors to avoid singularities.

Returns:

  • outer (list[(Tensor, str, array_like)]) – The sequence of gauges applied to outer indices, each a tuple of the tensor, the index and the gauge vector.

  • inner (list[((Tensor, Tensor), str, array_like)]) – The sequence of gauges applied to inner indices, each a tuple of the two inner tensors, the inner bond and the gauge vector applied.

static gauge_simple_remove(outer=None, inner=None)[source]

Remove the simple update style bond gauges inserted by gauge_simple_insert.

gauge_simple_temp(gauges, smudge=1e-12, ungauge_outer=True, ungauge_inner=True)[source]

Context manager that temporarily inserts simple update style bond gauges into this tensor network, before optionally ungauging them.

Parameters:
  • self (TensorNetwork) – The TensorNetwork to be gauge-bonded.

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

  • ungauge_outer (bool, optional) – Whether to ungauge the outer bonds.

  • ungauge_inner (bool, optional) – Whether to ungauge the inner bonds.

Yields:
  • outer (list[(Tensor, int, array_like)]) – The tensors, indices and gauges that were performed on outer indices.

  • inner (list[((Tensor, Tensor), int, array_like)]) – The tensors, indices and gauges that were performed on inner bonds.

Examples

>>> tn = TN_rand_reg(10, 4, 3)
>>> tn ^ all
-51371.66630218866
>>> gauges = {}
>>> tn.gauge_all_simple_(gauges=gauges)
>>> len(gauges)
20
>>> tn ^ all
28702551.673767876
>>> with gauged_bonds(tn, gauges):
...     # temporarily insert gauges
...     print(tn ^ all)
-51371.66630218887
>>> tn ^ all
28702551.67376789
_contract_compressed_tid_sequence(seq, max_bond=None, cutoff=1e-10, output_inds=None, tree_gauge_distance=1, canonize_distance=None, canonize_opts=None, canonize_after_distance=None, canonize_after_opts=None, gauge_boundary_only=True, compress_opts=None, compress_late=True, compress_mode='auto', compress_min_size=None, compress_span=False, compress_matrices=True, compress_exclude=None, equalize_norms=False, gauges=None, gauge_smudge=1e-06, callback_pre_contract=None, callback_post_contract=None, callback_pre_compress=None, callback_post_compress=None, callback=None, preserve_tensor=False, progbar=False, inplace=False)[source]
_contract_around_tids(tids, seq=None, min_distance=0, max_distance=None, span_opts=None, max_bond=None, cutoff=1e-10, canonize_opts=None, **kwargs)[source]

Contract around tids, by following a greedily generated spanning tree, and compressing whenever two tensors in the outer ‘boundary’ share more than one index.

compute_centralities()[source]
most_central_tid()[source]
least_central_tid()[source]
contract_around_center(**opts)[source]
contract_around_corner(**opts)[source]
contract_around(tags, which='all', min_distance=0, max_distance=None, span_opts=None, max_bond=None, cutoff=1e-10, tree_gauge_distance=1, canonize_distance=None, canonize_opts=None, canonize_after_distance=None, canonize_after_opts=None, gauge_boundary_only=True, compress_late=True, compress_min_size=None, compress_opts=None, compress_span=False, compress_matrices=True, equalize_norms=False, gauges=None, gauge_smudge=1e-06, callback_pre_contract=None, callback_post_contract=None, callback_pre_compress=None, callback_post_compress=None, callback=None, inplace=False, **kwargs)[source]

Perform a compressed contraction inwards towards the tensors identified by tags.

contract_around_[source]
contract_compressed(optimize, output_inds=None, max_bond=None, cutoff=1e-10, tree_gauge_distance=1, canonize_distance=None, canonize_opts=None, canonize_after_distance=None, canonize_after_opts=None, gauge_boundary_only=True, compress_late=True, compress_min_size=None, compress_opts=None, compress_span=True, compress_matrices=True, compress_exclude=None, equalize_norms=False, gauges=None, gauge_smudge=1e-06, callback_pre_contract=None, callback_post_contract=None, callback_pre_compress=None, callback_post_compress=None, callback=None, progbar=False, **kwargs)[source]
contract_compressed_[source]
new_bond(tags1, tags2, **opts)[source]

Inplace addition of a dummmy (size 1) bond between the single tensors specified by by tags1 and tags2.

Parameters:
  • tags1 (sequence of str) – Tags identifying the first tensor.

  • tags2 (sequence of str) – Tags identifying the second tensor.

  • opts – Supplied to new_bond().

See also

new_bond

_cut_between_tids(tid1, tid2, left_ind, right_ind)[source]
cut_between(left_tags, right_tags, left_ind, right_ind)[source]

Cut the bond between the tensors specified by left_tags and right_tags, giving them the new inds left_ind and right_ind respectively.

cut_bond(bond, new_left_ind=None, new_right_ind=None)[source]

Cut the bond index specified by bond between the tensors it connects. Use cut_between for control over which tensor gets which new index new_left_ind or new_right_ind. The index must connect exactly two tensors.

Parameters:
  • bond (str) – The index to cut.

  • new_left_ind (str, optional) – The new index to give to the left tensor (lowest tid value).

  • new_right_ind (str, optional) – The new index to give to the right tensor (highest tid value).

drape_bond_between(tagsa, tagsb, tags_target, left_ind=None, right_ind=None, inplace=False)[source]

Take the bond(s) connecting the tensors tagged at tagsa and tagsb, and ‘drape’ it through the tensor tagged at tags_target, effectively adding an identity tensor between the two and contracting it with the third:

 ┌─┐    ┌─┐      ┌─┐     ┌─┐
─┤A├─Id─┤B├─    ─┤A├─┐ ┌─┤B├─
 └─┘    └─┘      └─┘ │ │ └─┘
             left_ind│ │right_ind
     ┌─┐     -->     ├─┤
    ─┤C├─           ─┤D├─
     └┬┘             └┬┘     where D = C ⊗ Id
      │               │

This increases the size of the target tensor by d**2, and disconnects the tensors at tagsa and tagsb.

Parameters:
  • tagsa (str or sequence of str) – The tag(s) identifying the first tensor.

  • tagsb (str or sequence of str) – The tag(s) identifying the second tensor.

  • tags_target (str or sequence of str) – The tag(s) identifying the target tensor.

  • left_ind (str, optional) – The new index to give to the left tensor.

  • right_ind (str, optional) – The new index to give to the right tensor.

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

Return type:

TensorNetwork

drape_bond_between_[source]
isel(selectors, inplace=False)[source]

Select specific values for some dimensions/indices of this tensor network, thereby removing them.

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

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

Return type:

TensorNetwork

See also

Tensor.isel

isel_[source]
sum_reduce(ind, inplace=False)[source]

Sum over the index ind of this tensor network, removing it. This is like contracting a vector of ones in, or marginalizing a classical probability distribution.

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

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

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

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

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

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

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

Return type:

TensorNetwork

vector_reduce_[source]
cut_iter(*inds)[source]

Cut and iterate over one or more indices in this tensor network. Each network yielded will have that index removed, and the sum of all networks will equal the original network. This works by iterating over the product of all combinations of each bond supplied to isel. As such, the number of networks produced is exponential in the number of bonds cut.

Parameters:

inds (sequence of str) – The bonds to cut.

Yields:

TensorNetwork

Examples

Here we’ll cut the two extra bonds of a cyclic MPS and sum the contraction of the resulting 49 OBC MPS norms:

>>> psi = MPS_rand_state(10, bond_dim=7, cyclic=True)
>>> norm = psi.H & psi
>>> bnds = bonds(norm[0], norm[-1])
>>> sum(tn ^ all for tn in norm.cut_iter(*bnds))
1.0
insert_operator(A, where1, where2, tags=None, inplace=False)[source]

Insert an operator on the bond between the specified tensors, e.g.:

  |   |              |   |
--1---2--    ->    --1-A-2--
  |                  |
Parameters:
  • A (array) – The operator to insert.

  • where1 (str, sequence of str, or int) – The tags defining the ‘left’ tensor.

  • where2 (str, sequence of str, or int) – The tags defining the ‘right’ tensor.

  • tags (str or sequence of str) – Tags to add to the new operator’s tensor.

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

insert_operator_[source]
_insert_gauge_tids(U, tid1, tid2, Uinv=None, tol=1e-10, bond=None)[source]
insert_gauge(U, where1, where2, Uinv=None, tol=1e-10)[source]

Insert the gauge transformation U^-1 @ U into the bond between the tensors, T1 and T2, defined by where1 and where2. The resulting tensors at those locations will be T1 @ U^-1 and U @ T2.

Parameters:
  • U (array) – The gauge to insert.

  • where1 (str, sequence of str, or int) – Tags defining the location of the ‘left’ tensor.

  • where2 (str, sequence of str, or int) – Tags defining the location of the ‘right’ tensor.

  • Uinv (array) – The inverse gauge, U @ Uinv == Uinv @ U == eye, to insert. If not given will be calculated using numpy.linalg.inv().

contract_tags(tags, which='any', output_inds=None, optimize=None, get=None, backend=None, preserve_tensor=False, inplace=False, **contract_opts)[source]

Contract the tensors that match any or all of tags.

Parameters:
  • tags (sequence of str) – The list of tags to filter the tensors by. Use all or ... (Ellipsis) to contract all tensors.

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

  • output_inds (sequence of str, optional) – The indices to specify as outputs of the contraction. If not given, and the tensor network has no hyper-indices, these are computed automatically as every index appearing once.

  • optimize ({None, str, path_like, PathOptimizer}, optional) –

    The contraction path optimization strategy to use.

    • None: use the default strategy,

    • str: use the preset strategy with the given name,

    • path_like: use this exact path,

    • cotengra.HyperOptimizer: find the contraction using this optimizer, supports slicing,

    • cotengra.ContractionTree: use this exact tree, supports

    slicing, - opt_einsum.PathOptimizer: find the path using this

    optimizer.

    Contraction with cotengra might be a bit more efficient but the main reason would be to handle sliced contraction automatically.

  • get (str, optional) –

    What to return. If:

    • None (the default) - return the resulting scalar or Tensor.

    • 'expression' - return a callbable expression that performs the contraction and operates on the raw arrays.

    • 'tree' - return the cotengra.ContractionTree describing the contraction.

    • 'path' - return the raw ‘path’ as a list of tuples.

    • 'symbol-map' - return the dict mapping indices to ‘symbols’ (single unicode letters) used internally by cotengra

    • 'path-info' - return the opt_einsum.PathInfo path object with detailed information such as flop cost. The symbol-map is also added to the quimb_symbol_map attribute.

  • backend ({'auto', 'numpy', 'jax', 'cupy', 'tensorflow', ...}, optional) – Which backend to use to perform the contraction. Supplied to cotengra.

  • preserve_tensor (bool, optional) – Whether to return a tensor regardless of whether the output object is a scalar (has no indices) or not.

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

  • contract_opts – Passed to tensor_contract().

Returns:

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

Return type:

TensorNetwork, Tensor or scalar

contract_tags_[source]
contract(tags=..., output_inds=None, optimize=None, get=None, backend=None, preserve_tensor=False, max_bond=None, inplace=False, **opts)[source]

Contract some, or all, of the tensors in this network. This method dispatches to contract_tags, contract_structured, or contract_compressed based on the various arguments.

Parameters:
  • tags (sequence of str, all, or Ellipsis, optional) – Any tensors with any of these tags with be contracted. Use all or ... (Ellipsis) to contract all tensors. ... will try and use a ‘structured’ contract method if possible.

  • output_inds (sequence of str, optional) – The indices to specify as outputs of the contraction. If not given, and the tensor network has no hyper-indices, these are computed automatically as every index appearing once.

  • optimize ({None, str, path_like, PathOptimizer}, optional) –

    The contraction path optimization strategy to use.

    • None: use the default strategy,

    • str: use the preset strategy with the given name,

    • path_like: use this exact path,

    • cotengra.HyperOptimizer: find the contraction using this optimizer, supports slicing,

    • cotengra.ContractionTree: use this exact tree, supports slicing,

    • opt_einsum.PathOptimizer: find the path using this optimizer.

    Contraction with cotengra might be a bit more efficient but the main reason would be to handle sliced contraction automatically.

  • get (str, optional) –

    What to return. If:

    • None (the default) - return the resulting scalar or Tensor.

    • 'expression' - return a callbable expression that performs the contraction and operates on the raw arrays.

    • 'tree' - return the cotengra.ContractionTree describing the contraction.

    • 'path' - return the raw ‘path’ as a list of tuples.

    • 'symbol-map' - return the dict mapping indices to ‘symbols’ (single unicode letters) used internally by cotengra

    • 'path-info' - return the opt_einsum.PathInfo path object with detailed information such as flop cost. The symbol-map is also added to the quimb_symbol_map attribute.

  • backend ({'auto', 'numpy', 'jax', 'cupy', 'tensorflow', ...}, optional) – Which backend to use to perform the contraction. Supplied to cotengra.

  • preserve_tensor (bool, optional) – Whether to return a tensor regardless of whether the output object is a scalar (has no indices) or not.

  • inplace (bool, optional) – Whether to perform the contraction inplace. This is only valid if not all tensors are contracted (which doesn’t produce a TN).

  • opts – Passed to tensor_contract(), contract_compressed() .

Returns:

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

Return type:

TensorNetwork, Tensor or scalar

contract_[source]
contract_cumulative(tags_seq, output_inds=None, preserve_tensor=False, equalize_norms=False, inplace=False, **opts)[source]

Cumulative contraction of tensor network. Contract the first set of tags, then that set with the next set, then both of those with the next and so forth. Could also be described as an manually ordered contraction of all tags in tags_seq.

Parameters:
  • tags_seq (sequence of sequence of str) – The list of tag-groups to cumulatively contract.

  • output_inds (sequence of str, optional) – The indices to specify as outputs of the contraction. If not given, and the tensor network has no hyper-indices, these are computed automatically as every index appearing once.

  • preserve_tensor (bool, optional) – Whether to return a tensor regardless of whether the output object is a scalar (has no indices) or not.

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

  • opts – Passed to tensor_contract().

Returns:

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

Return type:

TensorNetwork, Tensor or scalar

contraction_path(optimize=None, **contract_opts)[source]

Compute the contraction path, a sequence of (int, int), for the contraction of this entire tensor network using path optimizer optimize.

contraction_info(optimize=None, **contract_opts)[source]

Compute the opt_einsum.PathInfo object decsribing the contraction of this entire tensor network using path optimizer optimize.

contraction_tree(optimize=None, output_inds=None, **kwargs)[source]

Return the cotengra.ContractionTree corresponding to contracting this entire tensor network with path finder optimize.

contraction_width(optimize=None, **contract_opts)[source]

Compute the ‘contraction width’ of this tensor network. This is defined as log2 of the maximum tensor size produced during the contraction sequence. If every index in the network has dimension 2 this corresponds to the maximum rank tensor produced.

contraction_cost(optimize=None, **contract_opts)[source]

Compute the ‘contraction cost’ of this tensor network. This is defined as log10 of the total number of scalar operations during the contraction sequence.

__rshift__(tags_seq)[source]

Overload of ‘>>’ for TensorNetwork.contract_cumulative.

__irshift__(tags_seq)[source]

Overload of ‘>>=’ for inplace TensorNetwork.contract_cumulative.

__xor__(tags)[source]

Overload of ‘^’ for TensorNetwork.contract.

__ixor__(tags)[source]

Overload of ‘^=’ for inplace TensorNetwork.contract.

__matmul__(other)[source]

Overload “@” to mean full contraction with another network.

as_network(virtual=True)[source]

Matching method (for ensuring object is a tensor network) to as_network(), which simply returns self if virtual=True.

aslinearoperator(left_inds, right_inds, ldims=None, rdims=None, backend=None, optimize=None)[source]

View this TensorNetwork as a TNLinearOperator.

split(left_inds, right_inds=None, **split_opts)[source]

Decompose this tensor network across a bipartition of outer indices.

This method matches Tensor.split by converting to a TNLinearOperator first. Note unless an iterative method is passed to method, the full dense tensor will be contracted.

trace(left_inds, right_inds, **contract_opts)[source]

Trace over left_inds joined with right_inds

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

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

to_qarray[source]
compute_reduced_factor(side, left_inds, right_inds, optimize='auto-hq', **contract_opts)[source]

Compute either the left or right ‘reduced factor’ of this tensor network. I.e., view as an operator, X, mapping left_inds to right_inds and compute L or R such that X = U_R @ R or X = L @ U_L, with U_R and U_L unitary operators that are not computed. Only dag(X) @ X or X @ dag(X) is contracted, which is generally cheaper than contracting X itself.

Parameters:
  • self (TensorNetwork) – The tensor network to compute the reduced factor of.

  • side ({'left', 'right'}) – Whether to compute the left or right reduced factor. If ‘right’ then dag(X) @ X is contracted, otherwise X @ dag(X).

  • left_inds (sequence of str) – The indices forming the left side of the operator.

  • right_inds (sequence of str) – The indices forming the right side of the operator.

  • contract_opts (dict, optional) – Options to pass to to_dense().

Return type:

array_like

insert_compressor_between_regions(ltags, rtags, max_bond=None, cutoff=1e-10, select_which='any', insert_into=None, new_tags=None, new_ltags=None, new_rtags=None, bond_ind=None, optimize='auto-hq', inplace=False, **compress_opts)[source]

Compute and insert a pair of ‘oblique’ projection tensors (see for example https://arxiv.org/abs/1905.02351) that effectively compresses between two regions of the tensor network. Useful for various approximate contraction methods such as HOTRG and CTMRG.

Parameters:
  • ltags (sequence of str) – The tags of the tensors in the left region.

  • rtags (sequence of str) – The tags of the tensors in the right region.

  • max_bond (int or None, optional) – The maximum bond dimension to use for the compression (i.e. shared by the two projection tensors). If None then the maximum is controlled by cutoff.

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

  • select_which ({'any', 'all', 'none'}, optional) – How to select the regions based on the tags, see select().

  • insert_into (TensorNetwork, optional) – If given, insert the new tensors into this tensor network, assumed to have the same relevant indices as self.

  • new_tags (str or sequence of str, optional) – The tag(s) to add to both the new tensors.

  • new_ltags (str or sequence of str, optional) – The tag(s) to add to the new left projection tensor.

  • new_rtags (str or sequence of str, optional) – The tag(s) to add to the new right projection tensor.

  • optimize (str or PathOptimizer, optional) – How to optimize the contraction of the projection tensors.

  • inplace (bool, optional) – Whether perform the insertion in-place. If insert_into is supplied then this doesn’t matter, and that tensor network will be modified and returned.

Return type:

TensorNetwork

insert_compressor_between_regions_[source]
distance(*args, **kwargs)[source]
distance_normalized[source]
fit(tn_target, method='als', tol=1e-09, inplace=False, progbar=False, **fitting_opts)[source]

Optimize the entries of this tensor network with respect to a least squares fit of tn_target which should have the same outer indices. Depending on method this calls tensor_network_fit_als() or tensor_network_fit_autodiff(). The quantity minimized is:

\[D(A, B) = | A - B |_{\mathrm{fro}} = \mathrm{Tr} [(A - B)^{\dagger}(A - B)]^{1/2} = ( \langle A | A \rangle - 2 \mathrm{Re} \langle A | B \rangle| + \langle B | B \rangle ) ^{1/2}\]
Parameters:
  • tn_target (TensorNetwork) – The target tensor network to try and fit the current one to.

  • method ({'als', 'autodiff'}, optional) – Whether to use alternating least squares (ALS) or automatic differentiation to perform the optimization. Generally ALS is better for simple geometries, autodiff better for complex ones.

  • tol (float, optional) – The target norm distance.

  • inplace (bool, optional) – Update the current tensor network in place.

  • progbar (bool, optional) – Show a live progress bar of the fitting process.

  • fitting_opts – Supplied to either tensor_network_fit_als() or tensor_network_fit_autodiff().

Returns:

tn_opt – The optimized tensor network.

Return type:

TensorNetwork

fit_[source]
property tags
all_inds()[source]

Return a tuple of all indices in this network.

ind_size(ind)[source]

Find the size of ind.

inds_size(inds)[source]

Return the total size of dimensions corresponding to inds.

ind_sizes()[source]

Get dict of each index mapped to its size.

inner_inds()[source]

Tuple of interior indices, assumed to be any indices that appear twice or more (this only holds generally for non-hyper tensor networks).

outer_inds()[source]

Tuple of exterior indices, assumed to be any lone indices (this only holds generally for non-hyper tensor networks).

outer_dims_inds()[source]

Get the ‘outer’ pairs of dimension and indices, i.e. as if this tensor network was fully contracted.

outer_size()[source]

Get the total size of the ‘outer’ indices, i.e. as if this tensor network was fully contracted.

get_multibonds(include=None, exclude=None)[source]

Get a dict of ‘multibonds’ in this tensor network, i.e. groups of two or more indices that appear on exactly the same tensors and thus could be fused, for example.

Parameters:
  • include (sequence of str, optional) – Only consider these indices, by default all indices.

  • exclude (sequence of str, optional) – Ignore these indices, by default the outer indices of this TN.

Returns:

A dict mapping the tuple of indices that could be fused to the tuple of tensor ids they appear on.

Return type:

dict[tuple[str], tuple[int]]

get_hyperinds(output_inds=None)[source]

Get a tuple of all ‘hyperinds’, defined as those indices which don’t appear exactly twice on either the tensors or in the ‘outer’ (i.e. output) indices.

Note the default set of ‘outer’ indices is calculated as only those indices that appear once on the tensors, so these likely need to be manually specified, otherwise, for example, an index that appears on two tensors and the output will incorrectly be identified as non-hyper.

Parameters:

output_inds (None, str or sequence of str, optional) – The outer or output index or indices. If not specified then taken as every index that appears only once on the tensors (and thus non-hyper).

Returns:

The tensor network hyperinds.

Return type:

tuple[str]

compute_contracted_inds(*tids, output_inds=None)[source]

Get the indices describing the tensor contraction of tensors corresponding to tids.

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

Drop singlet bonds and dimensions from this tensor network. If fuse=True also fuse all multibonds between tensors.

Parameters:
  • fuse (bool, optional) – Whether to fuse multibonds between tensors as well as squeezing.

  • include (sequence of str, optional) – Only squeeze these indices, by default all indices.

  • exclude (sequence of str, optional) – Ignore these indices, by default the outer indices of this TN.

  • inplace (bool, optional) – Whether to perform the squeeze and optional fuse inplace.

Return type:

TensorNetwork

squeeze_[source]
isometrize(method='qr', allow_no_left_inds=False, inplace=False)[source]

Project every tensor in this network into an isometric form, assuming they have left_inds marked.

Parameters:
  • method (str, optional) –

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

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

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

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

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

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

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

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

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

  • allow_no_left_inds (bool, optional) – If True then allow tensors with no left_inds to be left alone, rather than raising an error.

  • inplace (bool, optional) – If True then perform the operation in-place.

Return type:

TensorNetwork

isometrize_[source]
unitize[source]
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:

TensorNetwork

randomize_[source]
strip_exponent(tid_or_tensor, value=None)[source]

Scale the elements of tensor corresponding to tid so that the norm of the array is some value, which defaults to 1. The log of the scaling factor, base 10, is then accumulated in the exponent attribute.

Parameters:
  • tid (str or Tensor) – The tensor identifier or actual tensor.

  • value (None or float, optional) – The value to scale the norm of the tensor to.

distribute_exponent()[source]

Distribute the exponent p of this tensor network (i.e. corresponding to tn * 10**p) equally among all tensors.

equalize_norms(value=None, inplace=False)[source]

Make the Frobenius norm of every tensor in this TN equal without changing the overall value if value=None, or set the norm of every tensor to value by scalar multiplication only.

Parameters:
  • value (None or float, optional) – Set the norm of each tensor to this value specifically. If supplied the change in overall scaling will be accumulated in tn.exponent in the form of a base 10 power.

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

Return type:

TensorNetwork

equalize_norms_[source]
balance_bonds(inplace=False)[source]

Apply tensor_balance_bond() to all bonds in this tensor network.

Parameters:

inplace (bool, optional) – Whether to perform the bond balancing inplace or not.

Return type:

TensorNetwork

balance_bonds_[source]
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.

fuse_multibonds_[source]
expand_bond_dimension(new_bond_dim, mode=None, rand_strength=None, rand_dist='normal', inds_to_expand=None, inplace=False)[source]

Increase the dimension of all or some of the bonds in this tensor network to at least new_bond_dim, optinally adding some random noise to the new entries.

Parameters:
  • new_bond_dim (int) – The minimum bond dimension to expand to, if the bond dimension is already larger than this it will be left unchanged.

  • rand_strength (float, optional) – The strength of random noise to add to the new array entries, if any. The noise is drawn from a normal distribution with standard deviation rand_strength.

  • inds_to_expand (sequence of str, optional) – The indices to expand, if not all.

  • inplace (bool, optional) – Whether to expand this tensor network in place, or return a new one.

Return type:

TensorNetwork

expand_bond_dimension_[source]
flip(inds, inplace=False)[source]

Flip the dimension corresponding to indices inds on all tensors that share it.

flip_[source]
rank_simplify(output_inds=None, equalize_norms=False, cache=None, max_combinations=500, inplace=False)[source]

Simplify this tensor network by performing contractions that don’t increase the rank of any tensors.

Parameters:
  • output_inds (sequence of str, optional) – Explicitly set which indices of the tensor network are output indices and thus should not be modified.

  • equalize_norms (bool or float) – Actively renormalize the tensors during the simplification process. Useful for very large TNs. The scaling factor will be stored as an exponent in tn.exponent.

  • cache (None or set) – Persistent cache used to mark already checked tensors.

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

Return type:

TensorNetwork

rank_simplify_[source]
diagonal_reduce(output_inds=None, atol=1e-12, cache=None, inplace=False)[source]

Find tensors with diagonal structure and collapse those axes. This will create a tensor ‘hyper’ network with indices repeated 2+ times, as such, output indices should be explicitly supplied when contracting, as they can no longer be automatically inferred. For example:

>>> tn_diag = tn.diagonal_reduce()
>>> tn_diag.contract(all, output_inds=[])
Parameters:
  • output_inds (sequence of str, optional) – Which indices to explicitly consider as outer legs of the tensor network and thus not replace. If not given, these will be taken as all the indices that appear once.

  • atol (float, optional) – When identifying diagonal tensors, the absolute tolerance with which to compare to zero with.

  • cache (None or set) – Persistent cache used to mark already checked tensors.

  • inplace – Whether to perform the diagonal reduction inplace.

  • bool – Whether to perform the diagonal reduction inplace.

  • optional – Whether to perform the diagonal reduction inplace.

Return type:

TensorNetwork

diagonal_reduce_[source]
antidiag_gauge(output_inds=None, atol=1e-12, cache=None, inplace=False)[source]

Flip the order of any bonds connected to antidiagonal tensors. Whilst this is just a gauge fixing (with the gauge being the flipped identity) it then allows diagonal_reduce to then simplify those indices.

Parameters:
  • output_inds (sequence of str, optional) – Which indices to explicitly consider as outer legs of the tensor network and thus not flip. If not given, these will be taken as all the indices that appear once.

  • atol (float, optional) – When identifying antidiagonal tensors, the absolute tolerance with which to compare to zero with.

  • cache (None or set) – Persistent cache used to mark already checked tensors.

  • inplace – Whether to perform the antidiagonal gauging inplace.

  • bool – Whether to perform the antidiagonal gauging inplace.

  • optional – Whether to perform the antidiagonal gauging inplace.

Return type:

TensorNetwork

antidiag_gauge_[source]
column_reduce(output_inds=None, atol=1e-12, cache=None, inplace=False)[source]

Find bonds on this tensor network which have tensors where all but one column (of the respective index) is non-zero, allowing the ‘cutting’ of that bond.

Parameters:
  • output_inds (sequence of str, optional) – Which indices to explicitly consider as outer legs of the tensor network and thus not slice. If not given, these will be taken as all the indices that appear once.

  • atol (float, optional) – When identifying singlet column tensors, the absolute tolerance with which to compare to zero with.

  • cache (None or set) – Persistent cache used to mark already checked tensors.

  • inplace – Whether to perform the column reductions inplace.

  • bool – Whether to perform the column reductions inplace.

  • optional – Whether to perform the column reductions inplace.

Return type:

TensorNetwork

column_reduce_[source]
split_simplify(atol=1e-12, equalize_norms=False, cache=None, inplace=False, **split_opts)[source]

Find tensors which have low rank SVD decompositions across any combination of bonds and perform them.

Parameters:
  • atol (float, optional) – Cutoff used when attempting low rank decompositions.

  • equalize_norms (bool or float) – Actively renormalize the tensors during the simplification process. Useful for very large TNs. The scaling factor will be stored as an exponent in tn.exponent.

  • cache (None or set) – Persistent cache used to mark already checked tensors.

  • inplace – Whether to perform the split simplification inplace.

  • bool – Whether to perform the split simplification inplace.

  • optional – Whether to perform the split simplification inplace.

split_simplify_[source]
gen_loops(max_loop_length=None)[source]

Generate sequences of tids that represent loops in the TN.

Parameters:

max_loop_length (None or int) – Set the maximum number of tensors that can appear in a loop. If None, wait until any loop is found and set that as the maximum length.

Yields:

tuple[int]

See also

gen_inds_loops

gen_inds_loops(max_loop_length=None)[source]

Generate all sequences of indices, up to a specified length, that represent loops in this tensor network. Unlike gen_loops this function will return the indices of the tensors in the loop rather than the tensor ids, allowing one to differentiate between e.g. a double loop and a ‘figure of eight’ loop.

Parameters:

max_loop_length (None or int) – Set the maximum number of indices that can appear in a loop. If None, wait until any loop is found and set that as the maximum length.

Yields:

tuple[str]

gen_inds_connected(max_length)[source]

Generate all index ‘patches’ of size up to max_length.

Parameters:

max_length (int) – The maximum number of indices in the patch.

Yields:

tuple[str]

See also

gen_inds_loops

_get_string_between_tids(tida, tidb)[source]
tids_are_connected(tids)[source]

Check whether nodes tids are connected.

Parameters:

tids (sequence of int) – Nodes to check.

Return type:

bool

compute_shortest_distances(tids=None, exclude_inds=())[source]

Compute the minimum graph distances between all or some nodes tids.

compute_hierarchical_linkage(tids=None, method='weighted', optimal_ordering=True, exclude_inds=())[source]
compute_hierarchical_ssa_path(tids=None, method='weighted', optimal_ordering=True, exclude_inds=(), are_sorted=False, linkage=None)[source]

Compute a hierarchical grouping of tids, as a ssa_path.

compute_hierarchical_ordering(tids=None, method='weighted', optimal_ordering=True, exclude_inds=(), linkage=None)[source]
compute_hierarchical_grouping(max_group_size, tids=None, method='weighted', optimal_ordering=True, exclude_inds=(), linkage=None)[source]

Group tids (by default, all tensors) into groups of size max_group_size or less, using a hierarchical clustering.

pair_simplify(cutoff=1e-12, output_inds=None, max_inds=10, cache=None, equalize_norms=False, max_combinations=500, inplace=False, **split_opts)[source]
pair_simplify_[source]
loop_simplify(output_inds=None, max_loop_length=None, max_inds=10, cutoff=1e-12, loops=None, cache=None, equalize_norms=False, inplace=False, **split_opts)[source]

Try and simplify this tensor network by identifying loops and checking for low-rank decompositions across groupings of the loops outer indices.

Parameters:
  • max_loop_length (None or int, optional) – Largest length of loop to search for, if not set, the size will be set to the length of the first (and shortest) loop found.

  • cutoff (float, optional) – Cutoff to use for the operator decomposition.

  • loops (None, sequence or callable) – Loops to check, or a function that generates them.

  • cache (set, optional) – For performance reasons can supply a cache for already checked loops.

  • inplace (bool, optional) – Whether to replace the loops inplace.

  • split_opts – Supplied to tensor_split().

Return type:

TensorNetwork

loop_simplify_[source]
full_simplify(seq='ADCR', output_inds=None, atol=1e-12, equalize_norms=False, cache=None, inplace=False, progbar=False, rank_simplify_opts=None, loop_simplify_opts=None, split_simplify_opts=None, custom_methods=(), split_method='svd')[source]

Perform a series of tensor network ‘simplifications’ in a loop until there is no more reduction in the number of tensors or indices. Note that apart from rank-reduction, the simplification methods make use of the non-zero structure of the tensors, and thus changes to this will potentially produce different simplifications.

Parameters:
  • seq (str, optional) –

    Which simplifications and which order to perform them in.

    • 'A' : stands for antidiag_gauge

    • 'D' : stands for diagonal_reduce

    • 'C' : stands for column_reduce

    • 'R' : stands for rank_simplify

    • 'S' : stands for split_simplify

    • 'L' : stands for loop_simplify

    If you want to keep the tensor network ‘simple’, i.e. with no hyperedges, then don’t use 'D' (moreover 'A' is redundant).

  • output_inds (sequence of str, optional) – Explicitly set which indices of the tensor network are output indices and thus should not be modified. If not specified the tensor network is assumed to be a ‘standard’ one where indices that only appear once are the output indices.

  • atol (float, optional) – The absolute tolerance when indentifying zero entries of tensors and performing low-rank decompositions.

  • equalize_norms (bool or float) – Actively renormalize the tensors during the simplification process. Useful for very large TNs. If True, the norms, in the formed of stripped exponents, will be redistributed at the end. If an actual number, the final tensors will all have this norm, and the scaling factor will be stored as a base-10 exponent in tn.exponent.

  • cache (None or set) – A persistent cache for each simplification process to mark already processed tensors.

  • progbar (bool, optional) – Show a live progress bar of the simplification process.

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

Return type:

TensorNetwork

full_simplify_[source]
hyperinds_resolve(mode='dense', sorter=None, output_inds=None, inplace=False)[source]

Convert this into a regular tensor network, where all indices appear at most twice, by inserting COPY tensor or tensor networks for each hyper index.

Parameters:
  • mode ({'dense', 'mps', 'tree'}, optional) – What type of COPY tensor(s) to insert.

  • sorter (None or callable, optional) – If given, a function to sort the indices that a single hyperindex will be turned into. Th function is called like tids.sort(key=sorter).

  • inplace (bool, optional) – Whether to insert the COPY tensors inplace.

Return type:

TensorNetwork

hyperinds_resolve_[source]
compress_simplify(output_inds=None, atol=1e-06, simplify_sequence_a='ADCRS', simplify_sequence_b='RPL', hyperind_resolve_mode='tree', hyperind_resolve_sort='clustering', final_resolve=False, split_method='svd', max_simplification_iterations=100, converged_tol=0.01, equalize_norms=True, progbar=False, inplace=False, **full_simplify_opts)[source]
compress_simplify_[source]
max_bond()[source]

Return the size of the largest bond in this network.

property shape
Actual, i.e. exterior, shape of this TensorNetwork.
property dtype
The dtype of this TensorNetwork, this is the minimal common type
of all the tensors data.
iscomplex()[source]
astype(dtype, inplace=False)[source]

Convert the type of all tensors in this network to dtype.

astype_[source]
__getstate__()[source]

Helper for pickle.

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

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

_repr_info_str()[source]

Render the general info as a string.

_repr_html_()[source]

Render this TensorNetwork as HTML, for Jupyter notebooks.

__str__()[source]

Return str(self).

__repr__()[source]

Return repr(self).

draw[source]
draw_3d[source]
draw_interactive[source]
draw_3d_interactive[source]
graph[source]
visualize_tensors[source]
quimb.tensor.tensor_core.TNLO_HANDLED_FUNCTIONS
class quimb.tensor.tensor_core.TNLinearOperator(tns, left_inds, right_inds, ldims=None, rdims=None, optimize=None, backend=None, is_conj=False)[source]

Bases: scipy.sparse.linalg.LinearOperator

Get a linear operator - something that replicates the matrix-vector operation - for an arbitrary uncontracted TensorNetwork, e.g:

         : --O--O--+ +-- :                 --+
         :   |     | |   :                   |
         : --O--O--O-O-- :    acting on    --V
         :   |     |     :                   |
         : --+     +---- :                 --+
left_inds^               ^right_inds

This can then be supplied to scipy’s sparse linear algebra routines. The left_inds / right_inds convention is that the linear operator will have shape matching (*left_inds, *right_inds), so that the right_inds are those that will be contracted in a normal matvec / matmat operation:

_matvec =    --0--v    , _rmatvec =     v--0--
Parameters:
  • tns (sequence of Tensors or TensorNetwork) – A representation of the hamiltonian

  • left_inds (sequence of str) – The ‘left’ inds of the effective hamiltonian network.

  • right_inds (sequence of str) – The ‘right’ inds of the effective hamiltonian network. These should be ordered the same way as left_inds.

  • ldims (tuple of int, or None) – The dimensions corresponding to left_inds. Will figure out if None.

  • rdims (tuple of int, or None) – The dimensions corresponding to right_inds. Will figure out if None.

  • optimize (str, optional) – The path optimizer to use for the ‘matrix-vector’ contraction.

  • backend (str, optional) – The array backend to use for the ‘matrix-vector’ contraction.

  • is_conj (bool, optional) – Whether this object should represent the adjoint operator.

See also

TNLinearOperator1D

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

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

Default implementation of _transpose; defers to rmatvec + conj

_adjoint()[source]

Hermitian conjugate of this TNLO.

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

Convert this TNLinearOperator into a dense array, defaulting to grouping the left and right indices respectively.

to_qarray[source]
split(**split_opts)[source]
property A
astype(dtype)[source]

Convert this TNLinearOperator to type dtype.

__array_function__(func, types, args, kwargs)[source]
quimb.tensor.tensor_core.tnlo_implements(np_function)[source]

Register an __array_function__ implementation for TNLinearOperator objects.

quimb.tensor.tensor_core._tnlo_trace(x)[source]
class quimb.tensor.tensor_core.PTensor(fn, params, inds=(), tags=None, left_inds=None)[source]

Bases: Tensor

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

Parameters:
  • fn (callable) – The function that generates the tensor data from params.

  • params (sequence of numbers) – The initial parameters supplied to the generating function like fn(params).

  • inds (optional) – Should match the shape of fn(params), see Tensor.

  • tags (optional) – See Tensor.

  • left_inds (optional) – See Tensor.

See also

PTensor

__slots__ = ('_data', '_inds', '_tags', '_left_inds', '_owners')
classmethod from_parray(parray, inds=(), tags=None, left_inds=None)[source]
copy()[source]

Copy this parametrized tensor.

_set_data(x)[source]
property data
property fn
get_params()[source]

Get the parameters of this PTensor.

set_params(params)[source]

Set the parameters of this PTensor.

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 this PTensor (lazily), by composing it with the current parametrized array function.

conj(inplace=False)[source]

Conjugate this parametrized tensor - done lazily whenever the .data attribute is accessed.

conj_[source]
unparametrize()[source]

Turn this PTensor into a normal Tensor.

__getstate__()[source]

Helper for pickle.

__setstate__(state)[source]
class quimb.tensor.tensor_core.IsoTensor(data=1.0, inds=(), tags=None, left_inds=None)[source]

Bases: Tensor

A Tensor subclass which keeps its left_inds by default even when its data is changed.

__slots__ = ('_data', '_inds', '_tags', '_left_inds', '_owners')
modify(**kwargs)[source]

Overwrite the data of this tensor in place.

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

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

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

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

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

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

Combine groups of indices into single indices.

Parameters:

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

Returns:

The transposed, reshaped and re-labeled tensor.

Return type:

Tensor