How can we compute the symbolic determinant and permanent in SymPy?

382 Views Asked by At

I'm not finding the answer to this simply by googling, so I think it has a place on this site, seeing as all the online symbolic determinant calculators don't seem to work right, and so forget about computing the symbolic permanent. By symbolic, I mean in terms of variable $A_{ij}$'s all $n^2$ of them.

What I would like to do is compute the determinant & the permanent for small test cases i.e. for $n \times n$ matrices of SymPy symbols named either via subscript numbering or using up the Latin / Greek letters, for $n \lt 20$.

I'm using this in my research of elementary approaches to computing the permanent.

I would then like to take the formula and display it either at run-time or via copy / paste in rendered LaTeX, so please keep that in mind, i.e. multiplication should just be juxtaposition.

Do you know how to do this? Thank you.

This is of value to undergraduate researchers who'd like to mess around with computing the permanent.

1

There are 1 best solutions below

0
On

The canonical code for doing the above is this. I've also included how to assign to the individual matrix entries, because to experiment with the permanent, you'll have to be able to do that:

from sympy import *
from itertools import permutations
from functools import reduce
# init_printing()   # Used for outputing LaTeX if needed later

n = 4

A = MatrixSymbol('A', n, n)
A = Matrix(A)

detA = A.det()

pprint(detA)

# permA = A.per()  # Fails with some internal library erorr that 'Integer' object is not iterable

def permanent(A:Matrix):
    n = len(A.row(0))
    assert n == len(A.col(0))
    Sn = permutations(range(n))
    formula = 0
    mul = lambda x,y: x*y
    for sigma in Sn:
        formula += reduce(mul, [A[i, sigma[i]] for i in range(n)])
    return formula

permA = permanent(A)
pprint(permA)

# Example matrix entry assignment:

A[0,0] = -A[0,0]

pprint(A)

It was not as bad as I expected. I made use mainly of the SymPy documentation.