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