Building on the package

Packages such as QuantumCumulants.jl derive equations from the expressions of this package, and others add numeric backends. Both work through the public API: an expression is read term by term, and a backend implements a fixed set of conversion hooks.

Reading expressions

An operator expression is a QAdd, and iterating it gives its terms as QTerm => coefficient pairs. A term holds its operators in canonical order in ops, and the pairs of indices it requires to differ in ne. A coefficient becomes a Symbolics expression with to_num.

using SecondQuantizedAlgebrausing SecondQuantizedAlgebra: to_numh = FockSpace(:cavity) ⊗ NLevelSpace(:atom, 2)a = Destroy(h, :a, 1)σ(i, j) = Transition(h, :σ, i, j, 2)@variables Δ g κ γH = Δ * a' * a + g * (a' * σ(1, 2) + a * σ(2, 1))[(term.ops, to_num(c)) for (term, c) in H]
3-element Vector{Tuple{Vector{Op}, Complex{Symbolics.Num}}}:
 ([a', σ₁₂], g)
 ([a, σ₂₁], g)
 ([a', a], Δ)

Every operator is an Op, whatever its kind, so its name, its subsystems and its kind are read with functions.

using SecondQuantizedAlgebra: optypeoperator_name(σ(1, 2)), acts_on(σ(1, 2)), optype(σ(1, 2))
(:σ, [2], SecondQuantizedAlgebra.OP_TRANSITION)

Equations of motion often contain an expression and its adjoint as one unknown, $\langle X \rangle$ and $\langle X^\dagger \rangle = \langle X \rangle^*$. Keeping one of the two needs a choice that is the same in every session, which canonical_isless makes.

using SecondQuantizedAlgebra: canonical_islessx = a' * σ(1, 2)canonical_isless(x, x') ? x : x'

\[a{\sigma}^{{21}}\]

Indexed sums carry their summation indices, and the average of a sum its summand and excluded sites, read with the accessors shown under Many emitters.

Reading maps

A Lindbladian splits into its hamiltonian and its channels with their rates. A channel $\sum \mathcal{D}[J, K]$ is read with jump, partner and scope.

using SecondQuantizedAlgebra: hamiltonian, channels, jump, partnerL = hamiltonian_action(H) + κ * dissipator(a) + γ * dissipator(σ(1, 2))[(jump(ch), partner(ch), rate) for (ch, rate) in channels(L)]
2-element Vector{Tuple{SecondQuantizedAlgebra.QAdd, SecondQuantizedAlgebra.QAdd, SecondQuantizedAlgebra.Coeff}}:
 (a, a, κ)
 (σ₁₂, σ₁₂, γ)

Any SuperOperator iterates as sandwiches with their coefficients, and the two sides of a sandwich are read with left_operator and right_operator.

using SecondQuantizedAlgebra: SuperOperator, left_operator, right_operator[(left_operator(t), right_operator(t), c) for (t, c) in SuperOperator(dissipator(a))]
3-element Vector{Tuple{SecondQuantizedAlgebra.QAdd, SecondQuantizedAlgebra.QAdd, SecondQuantizedAlgebra.Coeff}}:
 (1, a' * a, (-1//2))
 (a' * a, 1, (-1//2))
 (a, a', 1)

Adding a numeric backend

The numeric core in src/numeric/ converts an expression into a list of terms, each a ComplexF64 coefficient with a list of operator factors, and hands them to a backend. A backend is a singleton subtype of NumericBackend with methods for the following functions:

FunctionResponsibility
numeric_basis(be, h, dims)build the full basis from a Hilbert space and truncations
numeric_num_subsystems(be, basis)number of tensor factors
numeric_subbasis(be, basis, slot)one tensor factor
numeric_operator(be, op, subbasis)the matrix of one operator
numeric_embed(be, basis, slot, leaf)a factor placed in the full space
numeric_identity(be, basis)the identity on the full space
numeric_assemble(be, basis, terms)the sum of the terms, possibly lazy
numeric_materialize(be, assembled, op_type)the representation returned to the user

numeric_materialize gives op_type a fixed meaning: EagerOperator() returns the backend's ordinary operator, identity returns the assembled object unchanged, and any other function is applied to it. Materialization happens once, after assembly, so a single operator, a product and a sum come out in the same representation.

A minimal backend:

import SecondQuantizedAlgebra as SQAstruct MyBackend <: SQA.NumericBackend endSQA.numeric_basis(::MyBackend, h::SQA.HilbertSpace, dims) = error("build the basis")SQA.numeric_num_subsystems(::MyBackend, basis) = error("count subsystems")SQA.numeric_subbasis(::MyBackend, basis, slot::Int) = error("select a subsystem")SQA.numeric_operator(::MyBackend, op::SQA.Op, subbasis) = error("construct a leaf")SQA.numeric_embed(::MyBackend, basis, slot::Int, leaf) = error("embed a leaf")SQA.numeric_identity(::MyBackend, basis) = error("construct the identity")SQA.numeric_assemble(::MyBackend, basis, terms) = error("assemble terms")SQA.numeric_materialize(::MyBackend, assembled, ::SQA.EagerOperator) =    error("make an eager operator")SQA.numeric_materialize(::MyBackend, assembled, ::typeof(identity)) = assembled

It is used as to_numeric(H, h, dims; backend = MyBackend()); only the two bundled backends are found automatically. Further features need further methods:

FeatureAdditional methods
time-dependent parametersnumeric_assemble_td
eager indexed sumsnumeric_zero, numeric_add_term! (fresh storage and in-place scaled accumulation)
static formal operator functionsnumeric_function, with an expim specialization for exp(im * op)
conversion with a state in place of a basisnumeric_backend(state), numeric_basis(state)
numeric_average and expectthe state methods and numeric_expect
superoperators and to_numeric_masternumeric_superoperator, numeric_matrix, and numeric_scaled_td for time-dependent collapse operators

The type of the assembled object must not depend on the number of terms, so a vector-backed lazy sum is used rather than a tuple. And a time-dependent coefficient that reads the solver parameters is a two-argument function (p, t) -> value, recognized by its arity rather than by a wrapper type. The two bundled extensions under ext/ are complete examples.

SecondQuantizedAlgebra.numeric_basis — Function
numeric_basis(be, h::HilbertSpace, dims)

Build the full numeric basis for Hilbert space h with user dimensions dims (Fock cutoff / spin number; ignored for spaces that carry their own level count). Returns a Basis (QuantumOptics) or integer dims (QuantumToolbox).

source
SecondQuantizedAlgebra.numeric_num_subsystems — Function
numeric_num_subsystems(be, basis) -> Int

Number of tensor-product subsystems represented by basis. Backends use this hook to validate indexed-site layouts before emitting any numeric operators.

source
SecondQuantizedAlgebra.numeric_operator — Function
numeric_operator(be, op::Op, subbasis)

Map a single-site operator op to its numeric matrix on subbasis (the subsystem basis for op's slot). Backends implement it as a closed k === OP_* value-branch on op.kind.

source
SecondQuantizedAlgebra.numeric_embed — Function
numeric_embed(be, basis, slot::Int, leaf)

Place the single-site numeric operator leaf at slot of basis, returning an operator on the full space (the leaf unchanged for a simple basis, a lazy/concrete tensor for a composite one).

source
SecondQuantizedAlgebra.numeric_assemble — Function
numeric_assemble(be, basis, terms)

Assemble a static lazy operator from a backend-neutral terms list. Each entry is (c::ComplexF64, factors::Vector{<leaf>}) with factors already embedded at their slots. The result uses the backend's native lazy representation.

source
SecondQuantizedAlgebra.numeric_assemble_td — Function
numeric_assemble_td(be, basis, td_terms)

Time-dependent counterpart of numeric_assemble.

Each coefficient is Union{ComplexF64, Function}: a constant, a t -> ComplexF64, or a solver-parameter-aware (p, t) -> ComplexF64. The result is the backend's native time-dependent operator.

source
SecondQuantizedAlgebra.numeric_materialize — Function
numeric_materialize(be, op, op_type)

Materialize a static lazily assembled operator op according to op_type, applied exactly once at the public boundary. Implementations must treat EagerOperator as a request for their ordinary eager operator and identity as a request for op unchanged. Other callables are backend-defined. The eager representation need not be sparse, although both bundled backends choose sparse storage.

This hook is not used by numeric_average, which consumes the lazy assembly, or by time-dependent conversion, which returns the backend's native time-dependent operator.

source
SecondQuantizedAlgebra.numeric_function — Function
numeric_function(backend, f, op)

Apply the matrix function f to the complete materialized operator op. The function tokens are sin, cos, and expim; the last means exp(im * op). Hermitian exponential arguments can use eigendecomposition; numeric replacements that break Hermiticity must retain their general matrix-exponential semantics. Return a backend operator preserving its basis/dimensions and supporting ordered arithmetic.

source
SecondQuantizedAlgebra.numeric_superoperator — Function
numeric_superoperator(be, basis, terms::Vector{<:Tuple{ComplexF64, Any, Any}})

Build the backend's eager superoperator Σ c * sprepost(L, R) on basis from the terms (c, L, R). Both sides are already matrices, as returned by numeric_matrix, so the backend only combines and wraps them.

source
SecondQuantizedAlgebra.numeric_scaled_td — Function
numeric_scaled_td(be, op, f)

Wrap the static backend operator op with the time-dependent scalar coefficient f, a t -> value or (p, t) -> value closure. Only backends with time-dependent collapse operators implement it.

source

Eager indexed sums call numeric_zero(backend, basis) once, then numeric_add_term!(accumulator, coefficient, operators, context) for each allowed index assignment. The accumulator must own its storage. Add the scaled product in place without mutating supplied replacements or retaining a cache of full-space operators across summands. Multiple bound indices are enumerated jointly, including their inequality constraints. Lazy and time-dependent representations may retain multiple operators; the eager streaming memory contract does not apply to them.