# How can I simplify expressions with custom-symmetric tensors? [duplicate]

I am looking to simplify an output that I have from previous calculations in Mathematica:

-2 Sin[θ/2]^2
((-1 + Cos[θ]) g[P,P,T,U] - (1 + Cos[θ]) g[Q, Q, T, U] -
(g[P, Q, T, U] + g[Q, P, T, U]) Sin[θ])


However, in this specific problem, I know that g[Q, P, T, U] == g[P, Q, T, U], in the sense that g can be looked at as a tensor with the custom symmetries g[P, Q, R, S] == g[P, Q, S, R] == g[Q, P, R, S] == g[Q, P, S, R] == g[R, S, P, Q] == g[R, S, Q, P] == g[S, R, P, Q] == g[S, R, Q, P]. (They are the two-electron integrals occurring in quantum chemistry.)

I know that I could use the replacement rule /.{g[Q, P, T, U] -> g[P, Q, T, U]}, but I have many similar terms, for example I have

-2 Sin[θ/2]^2
((-1 + Cos[θ]) g[R, S, P, P] - (1 + Cos[θ]) g[R, S, Q, Q] -
(g[R, S, P, Q] + g[R, S, Q, P]) Sin[θ])


as well, so I would need to use the replacement rule {g[R, S, Q, P} -> g[R, S, P, Q]} as well.

This list of different and similar terms is huge, so my question is if there is there a way to tell Mathematica that the given symmetry of the arguments of g exists, in order to simplify the above expression.

Ultimately, I would like to simplify the expressions of the type

2 Sin[θ/2]^4 (8 Cos[θ/2]^4 g[Q,P,P,Q]+8 g[P,Q,Q,P] Sin[θ/2]^4+2 Sin[θ] ((1+Cos[θ]) g[P,P,P,Q]+(-1+Cos[θ]) g[P,P,Q,P]-g[P,Q,P,P]+Cos[θ] g[P,Q,P,P]+g[P,Q,Q,Q]-Cos[θ] g[P,Q,Q,Q]+g[Q,P,P,P]+Cos[θ] g[Q,P,P,P]-g[Q,P,Q,Q]-Cos[θ] g[Q,P,Q,Q]-g[Q,Q,P,Q]-Cos[θ] g[Q,Q,P,Q]+g[Q,Q,Q,P]-Cos[θ] g[Q,Q,Q,P]+g[P,P,P,P] Sin[θ]-g[P,P,Q,Q] Sin[θ]-g[P,Q,P,Q] Sin[θ]-g[Q,P,Q,P] Sin[θ]-g[Q,Q,P,P] Sin[θ]+g[Q,Q,Q,Q] Sin[θ]))


## marked as duplicate by Carl Woll, Community♦Dec 18 '17 at 21:33

This code will canonically sort the arguments of g according to its symmetries:

g[args__] :=
With[{canonical =
First[Sort[Permute[{args},
PermutationGroup[{Cycles[{{3, 4}}], Cycles[{{1, 2}}],
Cycles[{{1, 3}, {2, 4}}]}]]]]},
g @@ canonical /; {args} =!= canonical
]