I am trying to write a sorting function which will sort expressions involving products of bosonic objects which do not commute. For example, I can have objects like $a,\ a^\dagger,\ b,\ b^\dagger$ where $[a,a^\dagger] = 1$, $[b,b^\dagger] = 1$ and all other commutators vanish. So the sorting function should for example sort a term like $a a^\dagger b a b^\dagger$ to $a + a^\dagger a^2 + ab^\dagger b+a^\dagger a^2 b^\dagger b$. So I want to sort them first lexicographically and then such that dagger objects will be to the left.
I have been using a function from the notebook provided by Simon Tyler at arXiv. So I have created a bosonic object using
Clear[Boson, BosonC, BosonA]
Boson /: MakeBoxes[
Boson[cr : (True | False), sym_], fmt_] :=
With[{sbox = If[StringQ[sym], sym, ToBoxes[sym]]},
With[{abox = If[cr, SuperscriptBox[#, FormBox["\[Dagger]", Bold]], #] &@sbox},
InterpretationBox[abox, Boson[cr, sym]]
]
]
BosonA[sym_:"a"] := Boson[False, sym]
BosonC[sym_:"a"] := Boson[True, sym]
Next following the code, I want to turn the atomic expressions into lists and use Mathematica's ordering after that. So I have functions like
NCOrder[Boson[cr : True | False, sym_]] :=
NCOrder[Boson[cr, sym]] = {{sym, Boole[cr]}}
NCSort[expr_] := Module[{temp, NCM},
temp = expr /. NonCommutativeMultiply -> NCM;
temp = temp /. (NCM[a : _Boson ..] :> (NCM[a][[Ordering[#]]] &[NCOrder /@ {a}]));
temp = temp /. NCM[singleArg_] :> singleArg;
temp = temp /. NCM -> NonCommutativeMultiply
]
This NCSort function right now is just ordering it lexicographically. I want to modify it so that it would sort and order the expressions as I explained above.