API reference
No names are exported, so access them as NonCommutativeProducts.name or import them explicitly, e.g. using NonCommutativeProducts: @nc, terms.
NonCommutativeProducts.NonCommutativeProducts — Module
NonCommutativeProductsSymbolic arithmetic with atoms that do not commute. Atoms are registered with @nc. Products are NCMul values and sums are NCAdd values. The order of factors is set by defining mul_effect for the atom types. Products are sorted as they are formed, unless inside with_autosort(false).
Setting up types
NonCommutativeProducts.@nc — Macro
@nc T1 T2 ...Define addition and multiplication for the given types, both within each type and between them, and make them implement the VectorInterface.jl API. Products are sorted as they are formed, so also define mul_effect for the types, or form products inside with_autosort(false). Number types are rejected, since Base defines their arithmetic. Atoms must compare by value; a custom == needs a matching hash.
NonCommutativeProducts.@commutative — Macro
@commutative T1 T2 ...Define mixed arithmetic for types that commute with each other, and order them as listed: for x::Ti and y::Tj, x*y stays if i < j and becomes y*x if i > j. The types must already be registered with @nc, must not overlap, and must not be listed later in the opposite order. Reversing a pair throws, except that using a supertype of an earlier type goes undetected.
NonCommutativeProducts.mul_effect — Function
mul_effect(a, b)When sorting a non-commutative expression, mul_effect(a, b) gives the replacement for a*b. Sorting continues until each neighbouring pair returns nothing.
This package defines no methods for mul_effect, so define them for your types. Products are sorted as they are formed, so a product of types without a method throws a MethodError, unless it is inside with_autosort(false). Products formed inside mul_effect are not sorted when the package calls it.
The return value can be nothing, a number, an object, a sum or product of these, or one of the helper types Swap(λ) (replace a*b by λ*b*a) and AddTerms(terms) (replace a*b by a sum of terms).
Example
# Anticommuting Grassmann numbersstruct θ id::Int endNonCommutativeProducts.@nc θNonCommutativeProducts.mul_effect(a::θ, b::θ) = a.id < b.id ? nothing : -b * a * (a.id==b.id ? 0 : 1)θ(2)*θ(1) # = -θ(1)*θ(2)θ(1)*θ(1) # = 0NonCommutativeProducts.Swap — Type
Swap(λ)Return value for mul_effect that replaces a*b by λ*b*a.
NonCommutativeProducts.AddTerms — Type
AddTerms(terms)Return value for mul_effect that replaces a*b by the sum of terms. terms is an iterable such as a vector or a tuple, and its elements can be any other allowed return value of mul_effect except nothing, including sums and nested AddTerms.
NonCommutativeProducts.contraction_key — Function
contraction_key(atom)Return a key that lets inner(x, y) skip orthogonal pairs of terms, or nothing (the default).
Terms that first differ at kets of one subsystem are orthogonal; otherwise inner computes the full product, so any order is correct and one order is fastest. Keys must differ between subsystems.
For atoms k, l with keys and any atom u:
mul_effect(k', l)must be defined. Being aNumberasserts thatkandlare in one subsystem, so it must not be one for different subsystems, not even 0, orinnercan silently miss terms.mul_effect(k', l)must be aNumberwhen the keys are equal.mul_effect(u, k')must benothingor aSwap.
Kets of an orthonormal basis can have keys; bras can't. See Fast inner products.
NonCommutativeProducts.mul_terms!! — Function
mul_terms!!(c, x, b)Return the sum c plus the sorted product of the term or sum x and the product or sum b, reusing the storage of c when possible. mul!! calls it with the whole left factor, and so does * when either factor is a sum, except inside with_autosort(false). For a sum x, the default calls mul_terms!!(c, t, b) for each term t of x.
Define methods for your own atom types to compute these products directly, e.g. to apply an operator to every ket in a sum with one precomputation, or, with a sum x, to compute the whole product at once. Autosort is disabled during the call, so a method must add terms that are already sorted, with add!!.
Gradings
NonCommutativeProducts.grade — Function
grade(atom)The grade of atom. Define it for your types to make them graded; the default for types declared with @nc is nothing, the identity grade. For other objects it throws an ArgumentError. Every term of mul_effect(a, b) must have the product of the grades of a and b, see check_grading. Within one grading, this is mul_grade(grade(a), grade(b)). Grades of different types are combined according to their grading.
For other expressions, grade(x) == only(grades(x)), and it throws an ArgumentError if there are several grades or none.
Example
# Fermions with charge as the gradeNonCommutativeProducts.grade(f::Fermion) = f.dagger ? 1 : -1NonCommutativeProducts.mul_grade(g::Int, h::Int) = iszero(g + h) ? nothing : g + hNonCommutativeProducts.adjoint_grade(g::Int) = -gNonCommutativeProducts.mul_grade — Function
mul_grade(g, h)The product of the grades g and h of one grading, neither of which is nothing. It must be associative, and return nothing for the identity grade or else a grade of the same grading.
It is only called for grades of one grading: grades of the same type, or of different types with the same grading. So a family of types sharing a key needs mul_grade methods between its member types. Grades of different gradings are combined into a ProductGrade instead.
NonCommutativeProducts.adjoint_grade — Function
adjoint_grade(g)The grade of the adjoint of an expression of grade g (not nothing). It must return nothing or a grade of the same grading. Only needed for adjoints of zero sums.
NonCommutativeProducts.grading — Function
grading(G::Type)The key of the grading that grades of type G belong to, or nothing if it is undeclared (the default). Keys are compared with isequal, and should be types or symbols.
Grades of the same type are multiplied with mul_grade, and need no declaration. Grades of different types are combined by their keys:
- equal keys: one grading, multiplied with
mul_grade, which must be defined between the types; - different keys: independent gradings, combined into a
ProductGrade; - an undeclared key: an
ArgumentError.
Example
NonCommutativeProducts.grading(::Type{Charge}) = ChargeNonCommutativeProducts.grading(::Type{<:U1}) = U1 # one grading spread over the types U1{T}NonCommutativeProducts.ProductGrade — Type
ProductGrade(g1, g2, ...)A grade in the direct product of independent gradings, with one component per grading. It is the product of grades with different declared gradings, so that e.g. fermions graded by Charge and kets graded by Bicyclic can be multiplied without defining mul_grade(::Charge, ::Bicyclic), once both types declare their grading.
Products involving a ProductGrade are computed componentwise:
- components of the same grading are multiplied with
mul_grade, in order, so the product is associative; - components that become
nothingare dropped, and a single remaining component is returned unwrapped, so the product of the gradesCharge(1),Bicyclic(1, 0)andCharge(-1)isBicyclic(1, 0).
Components are matched by grading regardless of their order, so f * k and k * f have the same grade. adjoint_grade acts componentwise. mul_grade and adjoint_grade within one grading must return a grade of that grading or nothing, which is checked when combining with a ProductGrade. Construct a ProductGrade with at least two components, in any order, with distinct declared gradings, none of them nothing or a ProductGrade.
Example
# Fermions with spin, graded by charge and by spinstruct Spin s::Intendspin(s) = iszero(s) ? nothing : Spin(s)NonCommutativeProducts.grading(::Type{Spin}) = Spin # and likewise for ChargeNonCommutativeProducts.mul_grade(a::Spin, b::Spin) = spin(a.s + b.s)NonCommutativeProducts.adjoint_grade(a::Spin) = spin(-a.s)NonCommutativeProducts.grade(f::SpinfulFermion) = ProductGrade(Charge(f.dagger ? 1 : -1), Spin(f.up == f.dagger ? 1 : -1))NonCommutativeProducts.grades — Function
grades(x)The set of grades of x. Grades never affect ==, hash or any other property of the value.
For a nonzero x, these are the grades of its terms, plus nothing if it has a nonzero scalar part. A zero has the grades of how it was computed, from the grades Γ(a), Γ(b) of the operands:
| operation | grades of a zero result |
|---|---|
a * b, a^n | Γ(a) ⊗ Γ(b) = {g ⋅ h : g ∈ Γ(a), h ∈ Γ(b)} |
a + b, a - b | Γ(a) ∪ Γ(b) |
a' | {adjoint_grade(g) : g ∈ Γ(a)} |
α * a, zero(a), zerovector(a), copy, convert, sort | Γ(a) |
mul!!(c, a, b) | Γ(c) ∪ Γ(a) ⊗ Γ(b) |
add!!(a, b, α, β), VectorInterface.add(!) | Γ(a) ∪ Γ(b), or Γ(b) if β isa VectorInterface.Zero |
Here g ⋅ h is the product of grades, mul_grade within one grading (see grading).
A zero without such a history (the number 0, zero(typeof(a)), or a zero sum built from a Dict or by ncmap) has no grades. The empty set is the unit of both ⊗ and ∪.
A product without factors behaves like its prefactor, a number, so a zero one has no grades: grades(2 * one(f)) is Set([nothing]), but grades(0 * one(f)) is empty. The table applies to products with factors and to sums.
Example
f = Fermion(1) # with the charge grading in the example of `grade`grades(f' * f + 1) == Set([nothing])grades(f * f) == Set([-2]) # f * f == 0grades(0 * (f' + f)) == Set([1, -1])NonCommutativeProducts.grade_part — Function
grade_part(x, g)The part of x with grade g, where the scalar part has grade nothing. x is the sum of grade_part(x, g) over g in grades(x).
Example
f = Fermion(1) # with the charge grading in the example of `grade`grade_part(f' * f + f + 1, nothing) == f' * f + 1grade_part(f' * f + f + 1, -1) == fNonCommutativeProducts.check_grading — Function
check_grading(a, b)Check that every term of mul_effect(a, b) has the product of the grades of a and b (see grade). Zero terms are always allowed. Meant to be used in tests.
Example
f = Fermion(1)check_grading(f, f') # trueGroups and segments
NonCommutativeProducts.atom_group — Function
atom_group(atom)The group that atom belongs to, used to split products into segments with foreach_segment, split_by_group and segment_ranges. Two factors are in the same group if their groups are isequal. Defaults to typeof(atom), so parametric variants of one type are different groups, e.g. Fermion{Int} and Fermion{Int32}.
Define methods for your types to group atoms by value, e.g. by the Hilbert space they act on, or to put several types in one group. The group can also encode a kind, e.g. (space_id, :ket) and (space_id, :op), to keep kets and operators of the same subsystem in separate segments. Groups do not change how products are sorted: the order of factors is set by mul_effect alone.
Example
NonCommutativeProducts.atom_group(f::Fermion) = f.site # fermions on the same site form one groupNonCommutativeProducts.foreach_segment — Function
foreach_segment(f, x)Call f(g, seg) for each segment of the product x, from left to right. A segment is a maximal run of consecutive factors whose atom_groups are isequal, g is that group and seg is an AbstractVector of the factors. x is a product or an atom; the coefficient of a product is ignored, and a product without factors has no segments. A sum with one term counts as that term; any other sum, including zero, throws an ArgumentError, so apply it to each of its terms.
seg has a concrete element type when its factors share one. It may alias the factors of x, so do not mutate it.
Example
foreach_segment((g, seg) -> println(g, " => ", seg), NCMul(2, [a1, a2, b, a3]))# prints the group of `a` with [a1, a2], the group of `b` with [b], and the group of `a` with [a3]NonCommutativeProducts.split_by_group — Function
split_by_group(x)The segments of x (see foreach_segment) as a Vector of pairs g => part, from left to right, where g is the atom_group of the segment and part a product of its factors. The first part has the coefficient of x, the others one, so the unsorted product of the parts equals x, except that a product without factors or a scalar-only sum gives an empty Vector. A sum with several terms, or a zero sum, throws an ArgumentError.
Segments are runs, not groups: interleaved factors give several parts with the same g. A part may share its factors with x, so do not mutate it. For factors of an abstract element type, prefer segment_ranges or foreach_segment in hot paths.
Example
split_by_group(2 * a1 * a2 * b) # [A => 2 * a1 * a2, B => 1 * b], with A the group of `a` and B that of `b`NonCommutativeProducts.segment_ranges — Function
segment_ranges(x)A lazy iterator over the segments of x (see foreach_segment), from left to right. It gives pairs g => range, where g is the atom_group of the segment and range the indices of its factors in factors(x).
Example
collect(segment_ranges(NCMul(2, [a1, a2, b, a3]))) # [A => 1:2, B => 3:3, A => 4:4], with A the group of `a` and B that of `b`# Whether a product with factors has them all in one group, and whichg, r = first(segment_ranges(x))length(r) == length(factors(x))Sorting
Base.sort — Method
sort(x::Union{NCMul,NCAdd})Sort x by repeatedly applying mul_effect to neighbouring factors. The result is always an NCAdd, also when x is a product that sorts to a single term.
NonCommutativeProducts.autosort — Function
autosort()Whether products are sorted with mul_effect as they are formed. True unless overridden with with_autosort.
NonCommutativeProducts.with_autosort — Function
with_autosort(f, enabled::Bool=true)Call f() with autosorting set to enabled and return its value. Works with a do block:
with_autosort(false) do a * bendExpressions
NonCommutativeProducts.NCMul — Type
NCMulA product: a coefficient times an ordered list of factors. Create products by multiplying atoms registered with @nc, e.g. 2 * a * b. Use coefficient(x) and factors(x) to read the parts of a product.
NonCommutativeProducts.NCAdd — Type
NCAddA sum of products (NCMul) with a scalar term. Create sums by adding atoms and products, e.g. a*b + 2*c + 1. Use terms(x) to iterate over the terms of a sum.
The constructors of NCAdd are internal. They may take ownership of the dictionary passed to them and mutate it.
NonCommutativeProducts.terms — Function
terms(x)An iterator over the terms of x, each an NCMul that includes its coefficient. A nonzero scalar part of a sum appears as a product without factors, so sum(terms(x)) == x. Zero has no terms: terms(0), the terms of a zero sum and the terms of a zero product are empty, and sum of an empty iterator throws.
Works for sums, products, numbers and atoms registered with @nc.
Example
collect(terms(2 * a * b + 3 * c + 1)) # the products 2*a*b, 3*c and 1, in no particular orderterms(2 * a) # the single product 2*aNonCommutativeProducts.nterms — Function
nterms(x)The number of terms of x, length(collect(terms(x))), computed in constant time.
Example
nterms(2 * a * b + 3 * c + 1) == 3nterms(2 * a) == 1nterms(0) == 0NonCommutativeProducts.termpairs — Function
termpairs(x)An iterator over the terms of x, as in terms(x), as pairs factors => coefficient without creating a product for each term. The factors may be the internal storage of x, so they must not be mutated.
Example
Dict(termpairs(2 * a * b + 3 * c + 1)) == Dict([a, b] => 2, [c] => 3, [] => 1)collect(termpairs(2 * a)) == [[a] => 2]NonCommutativeProducts.map_coefficients — Function
map_coefficients(f, x)x with the coefficient c of each term in termpairs(x) replaced by f(factors, c). Terms that become zero are dropped, and a zero result keeps the grades of x. The factors must not be mutated.
Example
map_coefficients((fs, c) -> length(fs) * c, 2 * a * b + 3 * c + 1) == 4 * a * b + 3 * cmap_coefficients((fs, c) -> 2c, 3 * a) == 6 * aNonCommutativeProducts.factors — Function
factors(x)The factors of x as an AbstractVector, in order and without the coefficient. Works for products, numbers and atoms registered with @nc: a number has no factors, and an atom is its own single factor. A sum with exactly one term has the factors of that term. Any other sum, including zero, throws an ArgumentError; use terms to get its products. The result is a copy, so modifying it does not change x.
Example
factors(2 * a * b) == [a, b]factors(2) == []factors(a) == [a]NonCommutativeProducts.coefficient — Function
coefficient(x)The scalar coefficient of x. Works for products, numbers and atoms registered with @nc: a number is its own coefficient, and an atom has coefficient 1. A sum with exactly one term has the coefficient of that term. Any other sum, including zero, throws an ArgumentError; use terms to get its products.
Example
coefficient(2 * a * b) == 2coefficient(2) == 2coefficient(a) == 1NonCommutativeProducts.scalar — Function
scalar(x)The number that x equals if x is a scalar, i.e. a number or a product or sum without factors. Throws an ArgumentError for other products and sums.
NonCommutativeProducts.add!! — Function
add!!(a, b)
add!!(a, b, α)
add!!(a, b, α, β)Compute a + b, or β * a + α * b, reusing the storage of a when possible. Use the returned value, since a may be left unchanged or modified. This is not VectorInterface.add!!.
NonCommutativeProducts.ncmap — Function
ncmap(f, expr; scalarmap=identity)Map f over the noncommutative factors in expr, keeping the sums and products of expr. scalarmap is applied to the scalar coefficients: the prefactor of each term and the additive constant. Equivalent to ncmapreduce(f, (+, *), expr; scalarmap).
Example
If a and b are of types registered with @nc then
ncmap(f, 2*a*b + 1) == 2*f(a)*f(b) + 1See ncmapreduce for more general mapping and reduction.
NonCommutativeProducts.ncmapreduce — Function
ncmapreduce(f, ops, expr; scalarmap=identity)Map f over the noncommutative factors of expr, then reduce them with the binary operations ops = (add, mul). mul combines the factors of each term, starting from the term's prefactor. add combines the terms, starting from the additive constant. Each reduction is a left fold. scalarmap is applied to each prefactor, to the additive constant, and to a bare number expr. A bare atom acts as 1 * atom.
Example
(using infix notation for add and mul)
ncmapreduce(f, (add, mul), 2*a*b + 1; scalarmap=g) == g(1) add ((g(2) mul f(a)) mul f(b))Truncation
NonCommutativeProducts.truncate_terms — Function
truncate_terms(x; atol=0, rtol=0)Drop small terms of x. Returns (; expr, err), the truncated expression and a bound on the error. Up to rounding,
opnorm(x - expr) ≤ err ≤ max(atol, rtol * B)in every representation where opnorm_bound holds. A term c * P has the weight |c| times the bound on P, and B is the total weight of the terms that can be dropped. Terms are dropped from the smallest weight up, while their total fits the budget, and terms of equal weight are dropped together or not at all. Terms with an unknown or infinite weight are always kept, such as those containing an atom without a bound.
Example
NonCommutativeProducts.opnorm_bound(::Fermion) = 1expr, err = truncate_terms(c[1]' * c[2] + 0.01 * c[1] + 0.001 * c[2]; atol=0.005)# expr == c[1]' * c[2] + 0.01 * c[1] and err == 0.001NonCommutativeProducts.opnorm_bound — Function
opnorm_bound(x)An upper bound on the operator norm of x, or nothing if no bound is known. Define it for your atom types, with a bound that holds in every representation you use, so that truncate_terms can drop terms containing them. Products and sums get their bound from their atoms and coefficients.
Example
NonCommutativeProducts.opnorm_bound(::Fermion) = 1Index
NonCommutativeProducts.NonCommutativeProductsNonCommutativeProducts.AddTermsNonCommutativeProducts.NCAddNonCommutativeProducts.NCMulNonCommutativeProducts.ProductGradeNonCommutativeProducts.SwapBase.sortNonCommutativeProducts.add!!NonCommutativeProducts.adjoint_gradeNonCommutativeProducts.atom_groupNonCommutativeProducts.autosortNonCommutativeProducts.check_gradingNonCommutativeProducts.coefficientNonCommutativeProducts.contraction_keyNonCommutativeProducts.factorsNonCommutativeProducts.foreach_segmentNonCommutativeProducts.gradeNonCommutativeProducts.grade_partNonCommutativeProducts.gradesNonCommutativeProducts.gradingNonCommutativeProducts.map_coefficientsNonCommutativeProducts.mul_effectNonCommutativeProducts.mul_gradeNonCommutativeProducts.mul_terms!!NonCommutativeProducts.ncmapNonCommutativeProducts.ncmapreduceNonCommutativeProducts.ntermsNonCommutativeProducts.opnorm_boundNonCommutativeProducts.scalarNonCommutativeProducts.segment_rangesNonCommutativeProducts.split_by_groupNonCommutativeProducts.termpairsNonCommutativeProducts.termsNonCommutativeProducts.truncate_termsNonCommutativeProducts.with_autosortNonCommutativeProducts.@commutativeNonCommutativeProducts.@nc