NonCommutativeProducts.jl is a Julia package for sorting non-commuting objects, such as operators in quantum mechanics. Users must specify custom commutation relations and sorting orders, as there are no inbuilt ones in this package. With a list of types Ts that represents your non-commuting objects, call @nc Ts... to define addition and multiplication for these types, and define mul_effect(a, b) for each pair of types to say what a*b is replaced by. Products are sorted as they are formed; use with_autosort(false) to leave them unsorted.
Requires Julia 1.12+.
using Pkg
Pkg.add("NonCommutativeProducts")Fermions sorted in normal order, with all creation operators before annihilation operators:
struct Fermion
label::Int
dagger::Bool
end
Base.adjoint(x::Fermion) = Fermion(x.label, !x.dagger)
Fermion(k) = Fermion(k, false)
Base.show(io::IO, x::Fermion) = print(io, "c", x.dagger ? "†" : "", "[", x.label, "]")
using NonCommutativeProducts
import NonCommutativeProducts: @nc, mul_effect
@nc Fermion
function mul_effect(a::Fermion, b::Fermion)
# If the fermion is multiplied with itself, replace it by zero.
(a.dagger, a.label) == (b.dagger, b.label) && return 0
# If already sorted, return nothing
(!a.dagger, a.label) < (!b.dagger, b.label) && return nothing
# Non-trivial anti-commutation relation
(!a.dagger, a.label) == (b.dagger, b.label) && return -b*a + 1
# Trivial anti-commutation relation
return -b*a
end
Fermion(1)'*Fermion(1)
#c†[1]*c[1]
Fermion(1)*Fermion(1)'
#1I - c†[1]*c[1]See the stable or development documentation for multiple types, traversing expressions, linear algebra, gradings, performance tips and the API reference.