Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/opt_einsum/backends/object_arrays.py: 17%
24 statements
« prev ^ index » next coverage.py v7.3.1, created at 2023-09-25 06:41 +0000
« prev ^ index » next coverage.py v7.3.1, created at 2023-09-25 06:41 +0000
1"""
2Functions for performing contractions with array elements which are objects.
3"""
5import functools
6import operator
8import numpy as np
11def object_einsum(eq, *arrays):
12 """A ``einsum`` implementation for ``numpy`` arrays with object dtype.
13 The loop is performed in python, meaning the objects themselves need
14 only to implement ``__mul__`` and ``__add__`` for the contraction to be
15 computed. This may be useful when, for example, computing expressions of
16 tensors with symbolic elements, but note it will be very slow when compared
17 to ``numpy.einsum`` and numeric data types!
19 Parameters
20 ----------
21 eq : str
22 The contraction string, should specify output.
23 arrays : sequence of arrays
24 These can be any indexable arrays as long as addition and
25 multiplication is defined on the elements.
27 Returns
28 -------
29 out : numpy.ndarray
30 The output tensor, with ``dtype=object``.
31 """
33 # when called by ``opt_einsum`` we will always be given a full eq
34 lhs, output = eq.split("->")
35 inputs = lhs.split(",")
37 sizes = {}
38 for term, array in zip(inputs, arrays):
39 for k, d in zip(term, array.shape):
40 sizes[k] = d
42 out_size = tuple(sizes[k] for k in output)
43 out = np.empty(out_size, dtype=object)
45 inner = tuple(k for k in sizes if k not in output)
46 inner_size = tuple(sizes[k] for k in inner)
48 for coo_o in np.ndindex(*out_size):
50 coord = dict(zip(output, coo_o))
52 def gen_inner_sum():
53 for coo_i in np.ndindex(*inner_size):
54 coord.update(dict(zip(inner, coo_i)))
55 locs = (tuple(coord[k] for k in term) for term in inputs)
56 elements = (array[loc] for array, loc in zip(arrays, locs))
57 yield functools.reduce(operator.mul, elements)
59 out[coo_o] = functools.reduce(operator.add, gen_inner_sum())
61 return out