If you can afford to symmetry the matrix just before performing the calculations, the following should be fast enough:
def symmetrize(a): return a + aT - numpy.diag(a.diagonal())
This works under reasonable assumptions (for example, not making either a[0, 1] = 42 or the inconsistent a[1, 0] = 123 before running symmetrize ).
If you really need transparent symmetrization, you can consider subclassing numpy.ndarray and simply override __setitem__ :
class SymNDArray(numpy.ndarray): def __setitem__(self, (i, j), value): super(SymNDArray, self).__setitem__((i, j), value) super(SymNDArray, self).__setitem__((j, i), value) def symarray(input_array): """ Returns a symmetrized version of the array-like input_array. Further assignments to the array are automatically symmetrized. """ return symmetrize(numpy.asarray(input_array)).view(SymNDArray)
(or equivalent with matrices instead of arrays, depending on your needs). This approach even handles more complex assignments, such as a[:, 1] = -1 , which sets the elements a[1, :] a[:, 1] = -1 correctly.
Note that Python 3 removed the ability to write def โฆ(โฆ, (i, j),โฆ) , so before starting with Python 3, the code
Eric Lebigot Apr 04 2018-10-10T00: 00-04-04
source share