tensornetwork.ncon(tensors: Sequence[Union[tensornetwork.tensor.Tensor, Any]], network_structure: Sequence[Sequence[Union[int, str]]], con_order: Optional[Sequence[T_co]] = None, out_order: Optional[Sequence[T_co]] = None, check_network: bool = True, backend: Union[str, tensornetwork.backends.abstract_backend.AbstractBackend, None] = None) → Union[tensornetwork.tensor.Tensor, Any]

Contracts a list of backend-tensors or `Tensor`s according to a tensor network specification.

The network is provided as a list of lists, one for each tensor, specifying the labels for the edges connected to that tensor.

Labels can be any numbers or strings. Negative number-type labels and string-type labels with a prepended hyphen (‘-’) are open labels and remain uncontracted.

Positive number-type labels and string-type labels with no prepended hyphen (‘-’) are closed labels and are contracted.

Any open label appearing more than once is treated as an open batch label. Any closed label appearing more than once is treated as a closed batch label.

Upon finishing the contraction, all open batch labels will have been collapsed into a single dimension, and all closed batch labels will have been summed over.

If out_order = None, output labels are ordered according to descending number ordering and ascending ASCII ordering, with number labels always appearing before string labels. Example: network_structure = [[-1, 1, ‘-rick’, ‘2’,-2], [-2, ‘2’, 1, ‘-morty’]] results in an output order of [-1, -2, ‘-morty’, ‘-rick’].

If out_order is given, the indices of the resulting tensor will be transposed into this order.

If con_order = None, ncon will first contract all number labels in ascending order followed by all string labels in ascending ASCII order. If con_order is given, ncon will contract according to this order.

For example, matrix multiplication:

A = np.array([[1.0, 2.0], [3.0, 4.0]])
B = np.array([[1.0, 1.0], [0.0, 1.0]])
ncon([A,B], [(-1, 1), (1, -2)])

Matrix trace:

A = np.array([[1.0, 2.0], [3.0, 4.0]])
ncon([A], [(1, 1)]) # 5.0


Disallowing 0 as an edge label is legacy behaviour, see original NCON implementation.

  • tensors – List of backend-tensors or `Tensor`s.
  • network_structure – List of lists specifying the tensor network structure.
  • con_order – List of edge labels specifying the contraction order.
  • out_order – List of edge labels specifying the output order.
  • check_network – Boolean flag. If True check the network.
  • backend – String specifying the backend to use. Defaults to tensornetwork.backend_contextmanager.get_default_backend.

  • A backend-tensor: If all elements of tensors are backend-tensors.
  • A Tensor: If all elements of tensors are Tensor objects.

Return type:

The result of the contraction