# Recognizing Summation Indices in Mathematica

Consider some complicated expression like the following: $$Q[a,b]Q[a,c]M[a,c]M[a,b]$$ Where the lower case letters are matrix indices. I am looking for a way to make mathematica recognize all the existing indices automatically and just turn this expression into the sum: $$\sum_a \sum_b \sum_c Q[a,b]Q[a,c]M[a,c]M[a,b]$$ Notice that this is not Einstein summation convention because I don't care how many times the indices are repeated.

Any ideas or references would be highly appreciated.

ClearAll[heads, indices, sum]
Cases[#, a_[__] /; Context[a] =!= "System" :> a, Infinity]] &;
indices = DeleteDuplicates[Cases[#, heads[#][a__] :> a, Infinity]] &;
sum = Function[{e}, Sum[e, ##] & @@ indices[e]];


Examples:

sum[Q[a, b] Q[a, c] M[a, c] M[a, b]] // TeXForm


$\sum _a\sum _b\sum _c M (a, b) Q (a, b) M (a, c) Q (a, c)$

If you want to keep the order of terms, wrap the input expression with HoldForm:

sum[HoldForm[Q[a, b] Q[a, c] M[a, c] M[a, b]]] // TeXForm
`

$\sum _a\sum _b\sum _c Q (a, b) Q (a, c) M (a, c) M (a, b)$