opt_einsum.paths.optimal(inputs, output, size_dict, memory_limit=None)[source]

Computes all possible pair contractions in a depth-first recursive manner, sieving results based on memory_limit and the best path found so far. Returns the lowest cost path. This algorithm scales factoriallly with respect to the elements in the list input_sets.

  • inputs (list) – List of sets that represent the lhs side of the einsum subscript.

  • output (set) – Set that represents the rhs side of the overall einsum subscript.

  • size_dict (dictionary) – Dictionary of index sizes.

  • memory_limit (int) – The maximum number of elements in a temporary array.


path – The optimal contraction order within the memory limit constraint.

Return type



>>> isets = [set('abd'), set('ac'), set('bdc')]
>>> oset = set('')
>>> idx_sizes = {'a': 1, 'b':2, 'c':3, 'd':4}
>>> optimal(isets, oset, idx_sizes, 5000)
[(0, 2), (0, 1)]