diff --git a/CHANGELOG.md b/CHANGELOG.md index ff068e4..f5ef5cb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,9 +1,11 @@ # News -## v0.3.4 - dev +## v0.3.4 - 2024-07-22 - Added `tr` and `ptrace` functionalities. - New symbolic superoperator representations. +- Added linear algebra operations `exp`, `vec`, `conj`, `transpose`. +- Created a getting-started guide in docs. ## v0.3.3 - 2024-07-12 diff --git a/Project.toml b/Project.toml index fcd3a93..e2e31c9 100644 --- a/Project.toml +++ b/Project.toml @@ -1,7 +1,7 @@ name = "QuantumSymbolics" uuid = "efa7fd63-0460-4890-beb7-be1bbdfbaeae" authors = ["QuantumSymbolics.jl contributors"] -version = "0.3.4-dev" +version = "0.3.4" [deps] Latexify = "23fbe1c1-3f47-55db-b15f-69d7ec21a316" diff --git a/docs/make.jl b/docs/make.jl index 4092076..e37a056 100644 --- a/docs/make.jl +++ b/docs/make.jl @@ -4,8 +4,7 @@ push!(LOAD_PATH,"../src/") using Documenter using DocumenterCitations using QuantumSymbolics -using QuantumOptics -using QuantumClifford +using QuantumInterface DocMeta.setdocmeta!(QuantumSymbolics, :DocTestSetup, :(using QuantumSymbolics, QuantumOptics, QuantumClifford); recursive=true) @@ -25,8 +24,9 @@ function main() authors = "Stefan Krastanov", pages = [ "QuantumSymbolics.jl" => "index.md", - "Qubit Basis Choice" => "qubit_basis.md", + "Getting Started with QuantumSymbolics.jl" => "introduction.md", "Express Functionality" => "express.md", + "Qubit Basis Choice" => "qubit_basis.md", "API" => "API.md", ] ) diff --git a/docs/src/index.md b/docs/src/index.md index 70dcbd2..62c75f6 100644 --- a/docs/src/index.md +++ b/docs/src/index.md @@ -202,4 +202,4 @@ express(MixedState(X1)/2+SProjector(Z1)/2, CliffordRepr()) !!! warning "Stabilizer state expressions" - The state written as $\frac{|Z₁⟩⊗|Z₁⟩+|Z₂⟩⊗|Z₂⟩}{√2}$ is a well known stabilizer state, namely a Bell state. However, automatically expressing it as a stabilizer is a prohibitively expensive computational operation in general. We do not perform that computation automatically. If you want to ensure that states you define can be automatically converted to tableaux for Clifford simulations, avoid using summation of kets. On the other hand, in all of our Clifford Monte-Carlo simulations, `⊗` is fully supported, as well as [`SProjector`](@ref), [`MixedState`](@ref), [`StabilizerState`](@ref), and summation of density matrices. + The state written as $\frac{|Z₁⟩⊗|Z₁⟩+|Z₂⟩⊗|Z₂⟩}{√2}$ is a well known stabilizer state, namely a Bell state. However, automatically expressing it as a stabilizer is a prohibitively expensive computational operation in general. We do not perform that computation automatically. If you want to ensure that states you define can be automatically converted to tableaux for Clifford simulations, avoid using summation of kets. On the other hand, in all of our Clifford Monte-Carlo simulations, `⊗` is fully supported, as well as [`projector`](@ref), [`MixedState`](@ref), [`StabilizerState`](@ref), and summation of density matrices. diff --git a/docs/src/introduction.md b/docs/src/introduction.md new file mode 100644 index 0000000..c85298a --- /dev/null +++ b/docs/src/introduction.md @@ -0,0 +1,251 @@ +# Getting Started with QuantumSymbolics.jl + +```@meta +DocTestSetup = quote + using QuantumSymbolics +end +``` + +QuantumSymbolics is designed for manipulation and numerical translation of symbolic quantum objects. This tutorial introduces basic features of the package. + +## Installation + +QuantumSymbolics.jl can be installed through the Julia package system in the standard way: + +``` +using Pkg +Pkg.add("QuantumSymbolics") +``` + +## Literal Symbolic Quantum Objects + +Basic objects of type [`SBra`](@ref), [`SKet`](@ref), [`SOperator`](@ref), and [`SSuperOperator`](@ref) represent symbolic quantum objects with `name` and `basis` properties. Each type can be generated with a straightforward macro: + +```jldoctest +julia> using QuantumSymbolics + +julia> @bra b # object of type SBra +⟨b| + +julia> @ket k # object of type SKet +|k⟩ + +julia> @op A # object of type SOperator +A + +julia> @superop S # object of type SSuperOperator +S +``` + +By default, each of the above macros defines a symbolic quantum object in the spin-1/2 basis. One can simply choose a different basis, such as the Fock basis or a tensor product of several bases, by passing an object of type `Basis` to the second argument in the macro call: + +```jldoctest +julia> @op B FockBasis(Inf, 0.0) +B + +julia> basis(B) +Fock(cutoff=Inf) + +julia> @op C SpinBasis(1//2)⊗SpinBasis(5//2) +C + +julia> basis(C) +[Spin(1/2) ⊗ Spin(5/2)] +``` +Here, we extracted the basis of the defined symbolic operators using the `basis` function. + +Symbolic quantum objects with additional properties can be defined, such as a Hermitian operator, or the zero ket (i.e., a symbolic ket equivalent to the zero vector $\bm{0}$). + +## Basic Operations + +Expressions containing symbolic quantum objects can be built with a variety of functions. Let us consider the most fundamental operations: multiplication `*`, addition `+`, and the tensor product `⊗`. + +We can multiply, for example, a ket by a scalar value, or apply an operator to a ket: + +```jldoctest +julia> @ket k; @op A; + +julia> 2*k +2|k⟩ + +julia> A*k +A|k⟩ +``` + +Similar scaling procedures can be performed on bras and operators. Addition between symbolic objects is also available, for instance: + +```jldoctest +julia> @op A₁; @op A₂; + +julia> A₁+A₂ +(A₁+A₂) + +julia> @bra b; + +julia> 2*b + 5*b +7⟨b| +``` +Built into the package are straightforward automatic simplification rules, as shown in the last example, where `2⟨b|+5⟨b|` evaluates to `7⟨b|`. + +Tensor products of symbolic objects can be performed, with basis information transferred: + +```jldoctest +julia> @ket k₁; @ket k₂; + +julia> tp = k₁⊗k₂ +|k₁⟩|k₂⟩ + +julia> basis(tp) +[Spin(1/2) ⊗ Spin(1/2)] +``` + +Inner and outer products of bras and kets can be generated: + +```jldoctest +julia> @bra b; @ket k; + +julia> b*k +⟨b||k⟩ + +julia> k*b +|k⟩⟨b| +``` + +More involved combinations of operations can be explored. Here are few other straightforward examples: + +```jldoctest +julia> @bra b; @ket k; @op A; @op B; + +julia> 3*A*B*k +3AB|k⟩ + +julia> A⊗(k*b + B) +(A⊗(B+|k⟩⟨b|)) + +julia> A-A +𝟎 +``` +In the last example, a zero operator, denoted `𝟎`, was returned by subtracting a symbolic operator from itself. Such an object is of the type [`SZeroOperator`](@ref), and similar objects [`SZeroBra`](@ref) and [`SZeroKet`](@ref) correspond to zero bras and zero kets, respectively. + +## Linear Algebra on Bras, Kets, and Operators + +QuantumSymbolics supports a wide variety of linear algebra on symbolic bras, kets, and operators. For instance, the commutator and anticommutator of two operators, can be generated: + +```jldoctest +julia> @op A; @op B; + +julia> commutator(A, B) +[A,B] + +julia> anticommutator(A, B) +{A,B} + +julia> commutator(A, A) +𝟎 +``` +Or, one can take the dagger of a quantum object with the [`dagger`](@ref) function: + +```jldoctest +julia> @ket k; @op A; @op B; + +julia> dagger(A) +A† + +julia> dagger(A*k) +|k⟩†A† + +julia> dagger(A*B) +B†A† +``` +Below, we state all of the supported linear algebra operations on quantum objects: + +- commutator of two operators: [`commutator`](@ref), +- anticommutator of two operators: [`anticommutator`](@ref), +- complex conjugate: [`conj`](@ref), +- transpose: [`transpose`](@ref), +- projection of a ket: [`projector`](@ref), +- adjoint or dagger: [`dagger`](@ref), +- trace: [`tr`](@ref), +- partial trace: [`ptrace`](@ref), +- inverse of an operator: [`inv`](@ref), +- exponential of an operator: [`exp`](@ref), +- vectorization of an operator: [`vec`](@ref). + +## Simplifying Expressions + +For predefined objects such as the Pauli operators [`X`](@ref), [`Y`](@ref), and [`Z`](@ref), additional simplification can be performed with the [`qsimplify`](@ref) function. Take the following example: + +```jldoctest +julia> qsimplify(X*Z) +(0 - 1im)Y +``` + +Here, we have the relation $XZ = -iY$, so calling [`qsimplify`](@ref) on the expression `X*Z` will rewrite the expression as `-im*Y`. + +Note that simplification rewriters used in QuantumSymbolics are built from the interface of [`SymbolicUtils.jl`](https://github.com/JuliaSymbolics/SymbolicUtils.jl). By default, when called on an expression, [`qsimplify`](@ref) will iterate through every defined simplification rule in the QuantumSymbolics package until the expression can no longer be simplified. + +Now, suppose we only want to use a specific subset of rules. For instance, say we wish to simplify commutators, but not anticommutators. Then, we can pass the keyword argument `rewriter=qsimplify_commutator` to [`qsimplify`](@ref), as done in the following example: + +```jldoctest +julia> qsimplify(commutator(X, Y), rewriter=qsimplify_commutator) +(0 + 2im)Z + +julia> qsimplify(anticommutator(X, Y), rewriter=qsimplify_commutator) +{X,Y} +``` +As shown above, we apply [`qsimplify`](@ref) to two expressions: `commutator(X, Y)` and `anticommutator(X, Y)`. We specify that only commutator rules will be applied, thus the first expression is rewritten to `(0 + 2im)Z` while the second expression is simply returned. This feature can greatly reduce the time it takes for an expression to be simplified. + +Below, we state all of the simplification rule subsets that can be passed to [`qsimplify`](@ref): + +- `qsimplify_pauli` for Pauli multiplication, +- `qsimplify_commutator` for commutators of Pauli operators, +- `qsimplify_anticommutator` for anticommutators of Pauli operators. + +## Expanding Expressions + +Symbolic expressions containing quantum objects can be expanded with the [`qexpand`](@ref) function. We demonstrate this capability with the following examples. + +```jldoctest +julia> @op A; @op B; @op C; + +julia> qexpand(A⊗(B+C)) +((A⊗B)+(A⊗C)) + +julia> qexpand((B+C)*A) +(BA+CA) + +julia> @ket k₁; @ket k₂; @ket k₃; + +julia> qexpand(k₁⊗(k₂+k₃)) +(|k₁⟩|k₂⟩+|k₁⟩|k₃⟩) + +julia> qexpand((A*B)*(k₁+k₂)) +(AB|k₁⟩+AB|k₂⟩) +``` + +## Numerical Translation of Symbolic Objects + +Symbolic expressions containing predefined objects can be converted to numerical representations with [`express`](@ref). Numerics packages supported by this translation capability are [`QuantumOptics.jl`](https://github.com/qojulia/QuantumOptics.jl) and [`QuantumClifford.jl`](https://github.com/QuantumSavory/QuantumClifford.jl/). + +By default, [`express`](@ref) converts an object to the quantum optics state vector representation. For instance, we can represent the exponential of the Pauli operator [`X`](@ref) numerically as follows: + +```jldoctest +julia> using QuantumOptics + +julia> express(exp(X)) +Operator(dim=2x2) + basis: Spin(1/2)sparse([1, 2, 1, 2], [1, 1, 2, 2], ComplexF64[1.5430806327160496 + 0.0im, 1.1752011684303352 + 0.0im, 1.1752011684303352 + 0.0im, 1.5430806327160496 + 0.0im], 2, 2) +``` + +To convert to the Clifford representation, an instance of `CliffordRepr` must be passed to [`express`](@ref). For instance, we can represent the projection of the basis state [`X1`](@ref) of the Pauli operator [`X`](@ref) as follows: + +```jldoctest +julia> using QuantumClifford + +julia> express(projector(X1), CliffordRepr()) +𝒟ℯ𝓈𝓉𝒶𝒷 ++ Z +𝒮𝓉𝒶𝒷 ++ X +``` +For more details on using [`express`](@ref), refer to the [express functionality page](@ref express). \ No newline at end of file diff --git a/src/QSymbolicsBase/QSymbolicsBase.jl b/src/QSymbolicsBase/QSymbolicsBase.jl index 10e2f93..57bae11 100644 --- a/src/QSymbolicsBase/QSymbolicsBase.jl +++ b/src/QSymbolicsBase/QSymbolicsBase.jl @@ -6,7 +6,7 @@ using TermInterface import TermInterface: isexpr,head,iscall,children,operation,arguments,metadata,maketerm using LinearAlgebra -import LinearAlgebra: eigvecs,ishermitian,inv +import LinearAlgebra: eigvecs,ishermitian,conj,transpose,inv,exp,vec,tr import QuantumInterface: apply!, @@ -23,7 +23,7 @@ export SymQObj,QObj, apply!, express, tensor,⊗, - dagger,projector,commutator,anticommutator,tr,ptrace, + dagger,projector,commutator,anticommutator,conj,transpose,inv,exp,vec,tr,ptrace, I,X,Y,Z,σˣ,σʸ,σᶻ,Pm,Pp,σ₋,σ₊, H,CNOT,CPHASE,XCX,XCY,XCZ,YCX,YCY,YCZ,ZCX,ZCY,ZCZ, X1,X2,Y1,Y2,Z1,Z2,X₁,X₂,Y₁,Y₂,Z₁,Z₂,L0,L1,Lp,Lm,Lpi,Lmi,L₀,L₁,L₊,L₋,L₊ᵢ,L₋ᵢ, @@ -35,8 +35,8 @@ export SymQObj,QObj, SScaled,SScaledBra,SScaledOperator,SScaledKet, STensorBra,STensorKet,STensorOperator, SZeroBra,SZeroKet,SZeroOperator, + SConjugate,STranspose,SProjector,SDagger,SInvOperator,SExpOperator,SVec,STrace,SPartialTrace, MixedState,IdentityOp, - SProjector,SDagger,STrace,SPartialTrace,SInvOperator, SApplyKet,SApplyBra,SMulOperator,SSuperOpApply,SCommutator,SAnticommutator,SBraKet,SOuterKetBra, HGate,XGate,YGate,ZGate,CPHASEGate,CNOTGate, XBasisState,YBasisState,ZBasisState, diff --git a/src/QSymbolicsBase/basic_ops_homogeneous.jl b/src/QSymbolicsBase/basic_ops_homogeneous.jl index 97322a5..0de8570 100644 --- a/src/QSymbolicsBase/basic_ops_homogeneous.jl +++ b/src/QSymbolicsBase/basic_ops_homogeneous.jl @@ -3,7 +3,7 @@ # that are homogeneous in their arguments. ## -"""Scaling of a quantum object (ket, operator, or bra) by a number +"""Scaling of a quantum object (ket, operator, or bra) by a number. ```jldoctest julia> @ket k @@ -69,7 +69,7 @@ function Base.show(io::IO, x::SScaledBra) end end -"""Addition of quantum objects (kets, operators, or bras) +"""Addition of quantum objects (kets, operators, or bras). ```jldoctest julia> @ket k₁; @ket k₂; @@ -118,7 +118,7 @@ function Base.show(io::IO, x::SAddOperator) print(io, "("*join(ordered_terms,"+")::String*")") # type assert to help inference end -"""Symbolic application of operator on operator +"""Symbolic application of operator on operator. ```jldoctest julia> @op A; @op B; @@ -153,7 +153,7 @@ end Base.show(io::IO, x::SMulOperator) = print(io, join(map(string, arguments(x)),"")) basis(x::SMulOperator) = basis(first(x.terms)) -"""Tensor product of quantum objects (kets, operators, or bras) +"""Tensor product of quantum objects (kets, operators, or bras). ```jldoctest julia> @ket k₁; @ket k₂; @@ -196,72 +196,3 @@ const STensorOperator = STensor{AbstractOperator} Base.show(io::IO, x::STensorOperator) = print(io, "("*join(map(string, arguments(x)),"⊗")*")") const STensorSuperOperator = STensor{AbstractSuperOperator} Base.show(io::IO, x::STensorSuperOperator) = print(io, "("*join(map(string, arguments(x)),"⊗")*")") - -"""Symbolic commutator of two operators - -```jldoctest -julia> @op A; @op B; - -julia> commutator(A, B) -[A,B] - -julia> commutator(A, A) -𝟎 -``` -""" -@withmetadata struct SCommutator <: Symbolic{AbstractOperator} - op1 - op2 -end -isexpr(::SCommutator) = true -iscall(::SCommutator) = true -arguments(x::SCommutator) = [x.op1, x.op2] -operation(x::SCommutator) = commutator -head(x::SCommutator) = :commutator -children(x::SCommutator) = [:commutator, x.op1, x.op2] -function commutator(o1::Symbolic{AbstractOperator}, o2::Symbolic{AbstractOperator}) - if !(samebases(basis(o1),basis(o2))) - throw(IncompatibleBases()) - else - coeff, cleanterms = prefactorscalings([o1 o2]) - cleanterms[1] === cleanterms[2] ? SZeroOperator() : coeff * SCommutator(cleanterms...) - end -end -commutator(o1::SZeroOperator, o2::Symbolic{AbstractOperator}) = SZeroOperator() -commutator(o1::Symbolic{AbstractOperator}, o2::SZeroOperator) = SZeroOperator() -commutator(o1::SZeroOperator, o2::SZeroOperator) = SZeroOperator() -Base.show(io::IO, x::SCommutator) = print(io, "[$(x.op1),$(x.op2)]") -basis(x::SCommutator) = basis(x.op1) - -"""Symbolic anticommutator of two operators - -```jldoctest -julia> @op A; @op B; - -julia> anticommutator(A, B) -{A,B} -``` -""" -@withmetadata struct SAnticommutator <: Symbolic{AbstractOperator} - op1 - op2 -end -isexpr(::SAnticommutator) = true -iscall(::SAnticommutator) = true -arguments(x::SAnticommutator) = [x.op1, x.op2] -operation(x::SAnticommutator) = anticommutator -head(x::SAnticommutator) = :anticommutator -children(x::SAnticommutator) = [:anticommutator, x.op1, x.op2] -function anticommutator(o1::Symbolic{AbstractOperator}, o2::Symbolic{AbstractOperator}) - if !(samebases(basis(o1),basis(o2))) - throw(IncompatibleBases()) - else - coeff, cleanterms = prefactorscalings([o1 o2]) - coeff * SAnticommutator(cleanterms...) - end -end -anticommutator(o1::SZeroOperator, o2::Symbolic{AbstractOperator}) = SZeroOperator() -anticommutator(o1::Symbolic{AbstractOperator}, o2::SZeroOperator) = SZeroOperator() -anticommutator(o1::SZeroOperator, o2::SZeroOperator) = SZeroOperator() -Base.show(io::IO, x::SAnticommutator) = print(io, "{$(x.op1),$(x.op2)}") -basis(x::SAnticommutator) = basis(x.op1) diff --git a/src/QSymbolicsBase/basic_ops_inhomogeneous.jl b/src/QSymbolicsBase/basic_ops_inhomogeneous.jl index 616639d..7cc77f9 100644 --- a/src/QSymbolicsBase/basic_ops_inhomogeneous.jl +++ b/src/QSymbolicsBase/basic_ops_inhomogeneous.jl @@ -2,7 +2,7 @@ # This file defines the symbolic operations for quantum objects (kets, operators, and bras) that are inhomogeneous in their arguments. ## -"""Symbolic application of an operator on a ket (from the left) +"""Symbolic application of an operator on a ket (from the left). ```jldoctest julia> @ket k; @op A; @@ -35,7 +35,7 @@ Base.:(*)(op::SZeroOperator, k::SZeroKet) = SZeroKet() Base.show(io::IO, x::SApplyKet) = begin print(io, x.op); print(io, x.ket) end basis(x::SApplyKet) = basis(x.ket) -"""Symbolic application of an operator on a bra (from the right) +"""Symbolic application of an operator on a bra (from the right). ```jldoctest julia> @bra b; @op A; @@ -68,7 +68,7 @@ Base.:(*)(b::SZeroBra, op::SZeroOperator) = SZeroBra() Base.show(io::IO, x::SApplyBra) = begin print(io, x.bra); print(io, x.op) end basis(x::SApplyBra) = basis(x.bra) -"""Symbolic inner product of a bra and a ket +"""Symbolic inner product of a bra and a ket. ```jldoctest julia> @bra b; @ket k; @@ -103,7 +103,8 @@ Base.hash(x::SBraKet, h::UInt) = hash((head(x), arguments(x)), h) maketerm(::Type{SBraKet}, f, a, t, m) = f(a...) Base.isequal(x::SBraKet, y::SBraKet) = isequal(x.bra, y.bra) && isequal(x.ket, y.ket) -"""Symbolic outer product of a ket and a bra +"""Symbolic outer product of a ket and a bra. + ```jldoctest julia> @bra b; @ket k; diff --git a/src/QSymbolicsBase/basic_superops.jl b/src/QSymbolicsBase/basic_superops.jl index d6f0363..b52792c 100644 --- a/src/QSymbolicsBase/basic_superops.jl +++ b/src/QSymbolicsBase/basic_superops.jl @@ -27,6 +27,8 @@ head(x::KrausRepr) = :kraus children(x::KrausRepr) = [:kraus; x.krausops] kraus(xs::Symbolic{AbstractOperator}...) = KrausRepr(collect(xs)) basis(x::KrausRepr) = basis(first(x.krausops)) +Base.:(*)(sop::KrausRepr, op::Symbolic{AbstractOperator}) = (+)((i*op*dagger(i) for i in sop.krausops)...) +Base.:(*)(sop::KrausRepr, k::Symbolic{AbstractKet}) = (+)((i*SProjector(k)*dagger(i) for i in sop.krausops)...) Base.show(io::IO, x::KrausRepr) = print(io, "𝒦("*join([symbollabel(i) for i in x.krausops], ",")*")") ## @@ -56,7 +58,5 @@ Base.:(*)(sop::Symbolic{AbstractSuperOperator}, op::Symbolic{AbstractOperator}) Base.:(*)(sop::Symbolic{AbstractSuperOperator}, op::SZeroOperator) = SZeroOperator() Base.:(*)(sop::Symbolic{AbstractSuperOperator}, k::Symbolic{AbstractKet}) = SSuperOpApply(sop,SProjector(k)) Base.:(*)(sop::Symbolic{AbstractSuperOperator}, k::SZeroKet) = SZeroOperator() -Base.:(*)(sop::KrausRepr, op::Symbolic{AbstractOperator}) = (+)((i*op*dagger(i) for i in sop.krausops)...) -Base.:(*)(sop::KrausRepr, k::Symbolic{AbstractKet}) = (+)((i*SProjector(k)*dagger(i) for i in sop.krausops)...) Base.show(io::IO, x::SSuperOpApply) = print(io, "$(x.sop)[$(x.op)]") basis(x::SSuperOpApply) = basis(x.op) \ No newline at end of file diff --git a/src/QSymbolicsBase/express.jl b/src/QSymbolicsBase/express.jl index e091591..8fd6466 100644 --- a/src/QSymbolicsBase/express.jl +++ b/src/QSymbolicsBase/express.jl @@ -9,6 +9,8 @@ export express, express_nolookup, consistent_representation import SymbolicUtils: Symbolic """ + express(s, repr::AbstractRepresentation=QuantumOpticsRepr()[, use::AbstractUse]) + The main interface for expressing quantum objects in various representations. ```jldoctest diff --git a/src/QSymbolicsBase/linalg.jl b/src/QSymbolicsBase/linalg.jl index c4cd36e..7b201d3 100644 --- a/src/QSymbolicsBase/linalg.jl +++ b/src/QSymbolicsBase/linalg.jl @@ -2,18 +2,111 @@ # Linear algebra operations on quantum objects. ## -"""Projector for a given ket +@withmetadata struct SCommutator <: Symbolic{AbstractOperator} + op1 + op2 +end +isexpr(::SCommutator) = true +iscall(::SCommutator) = true +arguments(x::SCommutator) = [x.op1, x.op2] +operation(x::SCommutator) = commutator +head(x::SCommutator) = :commutator +children(x::SCommutator) = [:commutator, x.op1, x.op2] + +"""Symbolic commutator of two operators. ```jldoctest -julia> SProjector(X1⊗X2) -𝐏[|X₁⟩|X₂⟩] +julia> @op A; @op B; + +julia> commutator(A, B) +[A,B] + +julia> commutator(A, A) +𝟎 +``` +""" +function commutator(o1::Symbolic{AbstractOperator}, o2::Symbolic{AbstractOperator}) + if !(samebases(basis(o1),basis(o2))) + throw(IncompatibleBases()) + else + coeff, cleanterms = prefactorscalings([o1 o2]) + cleanterms[1] === cleanterms[2] ? SZeroOperator() : coeff * SCommutator(cleanterms...) + end +end +commutator(o1::SZeroOperator, o2::Symbolic{AbstractOperator}) = SZeroOperator() +commutator(o1::Symbolic{AbstractOperator}, o2::SZeroOperator) = SZeroOperator() +commutator(o1::SZeroOperator, o2::SZeroOperator) = SZeroOperator() +Base.show(io::IO, x::SCommutator) = print(io, "[$(x.op1),$(x.op2)]") +basis(x::SCommutator) = basis(x.op1) + + +@withmetadata struct SAnticommutator <: Symbolic{AbstractOperator} + op1 + op2 +end +isexpr(::SAnticommutator) = true +iscall(::SAnticommutator) = true +arguments(x::SAnticommutator) = [x.op1, x.op2] +operation(x::SAnticommutator) = anticommutator +head(x::SAnticommutator) = :anticommutator +children(x::SAnticommutator) = [:anticommutator, x.op1, x.op2] + +"""Symbolic anticommutator of two operators. + +```jldoctest +julia> @op A; @op B; + +julia> anticommutator(A, B) +{A,B} +``` +""" +function anticommutator(o1::Symbolic{AbstractOperator}, o2::Symbolic{AbstractOperator}) + if !(samebases(basis(o1),basis(o2))) + throw(IncompatibleBases()) + else + coeff, cleanterms = prefactorscalings([o1 o2]) + coeff * SAnticommutator(cleanterms...) + end +end +anticommutator(o1::SZeroOperator, o2::Symbolic{AbstractOperator}) = SZeroOperator() +anticommutator(o1::Symbolic{AbstractOperator}, o2::SZeroOperator) = SZeroOperator() +anticommutator(o1::SZeroOperator, o2::SZeroOperator) = SZeroOperator() +Base.show(io::IO, x::SAnticommutator) = print(io, "{$(x.op1),$(x.op2)}") +basis(x::SAnticommutator) = basis(x.op1) + + +@withmetadata struct SConjugate{T<:QObj} <: Symbolic{T} + obj +end +isexpr(::SConjugate) = true +iscall(::SConjugate) = true +arguments(x::SConjugate) = [x.obj] +operation(x::SConjugate) = conj +head(x::SConjugate) = :conj +children(x::SConjugate) = [:conj, x.obj] + +"""Complex conjugate of quantum objects (kets, bras, operators). + +```jldoctest +julia> @op A; @ket k; + +julia> conj(A) +Aˣ + +julia> conj(k) +|k⟩ˣ +``` +""" +conj(x::Symbolic{T}) where {T<:QObj} = SConjugate{T}(x) +conj(x::SZero) = x +conj(x::SConjugate) = x.obj +basis(x::SConjugate) = basis(x.obj) +function Base.show(io::IO, x::SConjugate) + print(io,x.obj) + print(io,"ˣ") +end + -julia> express(SProjector(X2)) -Operator(dim=2x2) - basis: Spin(1/2) - 0.5+0.0im -0.5-0.0im - -0.5+0.0im 0.5+0.0im -```""" @withmetadata struct SProjector <: Symbolic{AbstractOperator} ket::Symbolic{AbstractKet} # TODO parameterize end @@ -23,6 +116,20 @@ arguments(x::SProjector) = [x.ket] operation(x::SProjector) = projector head(x::SProjector) = :projector children(x::SProjector) = [:projector,x.ket] + +"""Projector for a given ket. + +```jldoctest +julia> projector(X1⊗X2) +𝐏[|X₁⟩|X₂⟩] + +julia> express(projector(X2)) +Operator(dim=2x2) + basis: Spin(1/2) + 0.5+0.0im -0.5-0.0im + -0.5+0.0im 0.5+0.0im +``` +""" projector(x::Symbolic{AbstractKet}) = SProjector(x) projector(x::SZeroKet) = SZeroOperator() basis(x::SProjector) = basis(x.ket) @@ -32,7 +139,59 @@ function Base.show(io::IO, x::SProjector) print(io,"]") end -"""Dagger, i.e., adjoint of quantum objects (kets, bras, operators) + +@withmetadata struct STranspose{T<:QObj} <: Symbolic{T} + obj +end +isexpr(::STranspose) = true +iscall(::STranspose) = true +arguments(x::STranspose) = [x.obj] +operation(x::STranspose) = transpose +head(x::STranspose) = :transpose +children(x::STranspose) = [:transpose, x.obj] + +"""Transpose of quantum objects (kets, bras, operators). + +```jldoctest +julia> @op A; @op B; @ket k; + +julia> transpose(A) +Aᵀ + +julia> transpose(A+B) +(Aᵀ+Bᵀ) + +julia> transpose(k) +|k⟩ᵀ +``` +""" +transpose(x::Symbolic{AbstractOperator}) = STranspose{AbstractOperator}(x) +transpose(x::Symbolic{AbstractKet}) = STranspose{AbstractBra}(x) +transpose(x::Symbolic{AbstractBra}) = STranspose{AbstractKet}(x) +transpose(x::SScaled) = x.coeff*transpose(x.obj) +transpose(x::SAdd) = (+)((transpose(i) for i in arguments(x))...) +transpose(x::SMulOperator) = (*)((transpose(i) for i in reverse(x.terms))...) +transpose(x::STensor) = (⊗)((transpose(i) for i in x.terms)...) +transpose(x::SZeroOperator) = x +transpose(x::STranspose) = x.obj +basis(x::STranspose) = basis(x.obj) +function Base.show(io::IO, x::STranspose) + print(io,x.obj) + print(io,"ᵀ") +end + + +@withmetadata struct SDagger{T<:QObj} <: Symbolic{T} + obj +end +isexpr(::SDagger) = true +iscall(::SDagger) = true +arguments(x::SDagger) = [x.obj] +operation(x::SDagger) = dagger +head(x::SDagger) = :dagger +children(x::SDagger) = [:dagger, x.obj] + +"""Dagger, i.e., adjoint of quantum objects (kets, bras, operators). ```jldoctest julia> @ket a; @op A; @@ -50,38 +209,25 @@ julia> ℋ = SHermitianOperator(:ℋ); U = SUnitaryOperator(:U); julia> dagger(ℋ) ℋ -julia> dagger(U) +julia> dagger(U) U⁻¹ ``` """ -@withmetadata struct SDagger{T<:QObj} <: Symbolic{T} - obj -end -isexpr(::SDagger) = true -iscall(::SDagger) = true -arguments(x::SDagger) = [x.obj] -operation(x::SDagger) = dagger -head(x::SDagger) = :dagger -children(x::SDagger) = [:dagger, x.obj] dagger(x::Symbolic{AbstractBra}) = SDagger{AbstractKet}(x) dagger(x::Symbolic{AbstractKet}) = SDagger{AbstractBra}(x) dagger(x::Symbolic{AbstractOperator}) = SDagger{AbstractOperator}(x) -dagger(x::SScaledKet) = SScaledBra(conj(x.coeff), dagger(x.obj)) +dagger(x::SScaled) = conj(x.coeff)*dagger(x.obj) dagger(x::SAdd) = (+)((dagger(i) for i in arguments(x))...) -dagger(x::SScaledBra) = SScaledKet(conj(x.coeff), dagger(x.obj)) +dagger(x::SMulOperator) = (*)((dagger(i) for i in reverse(x.terms))...) +dagger(x::STensor) = (⊗)((dagger(i) for i in x.terms)...) dagger(x::SZeroOperator) = x dagger(x::SHermitianOperator) = x dagger(x::SHermitianUnitaryOperator) = x dagger(x::SUnitaryOperator) = inv(x) -dagger(x::STensorBra) = STensorKet(collect(dagger(i) for i in x.terms)) -dagger(x::STensorKet) = STensorBra(collect(dagger(i) for i in x.terms)) -dagger(x::STensorOperator) = STensorOperator(collect(dagger(i) for i in x.terms)) -dagger(x::SScaledOperator) = SScaledOperator(conj(x.coeff), dagger(x.obj)) dagger(x::SApplyKet) = dagger(x.ket)*dagger(x.op) dagger(x::SApplyBra) = dagger(x.op)*dagger(x.bra) -dagger(x::SMulOperator) = SMulOperator(collect(dagger(i) for i in reverse(x.terms))) -dagger(x::SBraKet) = SBraKet(dagger(x.ket), dagger(x.bra)) -dagger(x::SOuterKetBra) = SOuterKetBra(dagger(x.bra), dagger(x.ket)) +dagger(x::SBraKet) = dagger(x.ket)*dagger(x.bra) +dagger(x::SOuterKetBra) = dagger(x.bra)*dagger(x.ket) dagger(x::SDagger) = x.obj basis(x::SDagger) = basis(x.obj) function Base.show(io::IO, x::SDagger) @@ -89,6 +235,19 @@ function Base.show(io::IO, x::SDagger) print(io,"†") end + +@withmetadata struct STrace <: Symbolic{Complex} + op::Symbolic{AbstractOperator} +end +isexpr(::STrace) = true +iscall(::STrace) = true +arguments(x::STrace) = [x.op] +sorted_arguments(x::STrace) = arguments(x) +operation(x::STrace) = tr +head(x::STrace) = :tr +children(x::STrace) = [:tr, x.op] +Base.show(io::IO, x::STrace) = print(io, "tr($(x.op))") + """Trace of an operator ```jldoctest @@ -106,17 +265,6 @@ julia> tr(k*b) ⟨b||k⟩ ``` """ -@withmetadata struct STrace <: Symbolic{Complex} - op::Symbolic{AbstractOperator} -end -isexpr(::STrace) = true -iscall(::STrace) = true -arguments(x::STrace) = [x.op] -sorted_arguments(x::STrace) = arguments(x) -operation(x::STrace) = tr -head(x::STrace) = :tr -children(x::STrace) = [:tr, x.op] -Base.show(io::IO, x::STrace) = print(io, "tr($(x.op))") tr(x::Symbolic{AbstractOperator}) = STrace(x) tr(x::SScaled{AbstractOperator}) = x.coeff*tr(x.obj) tr(x::SAdd{AbstractOperator}) = (+)((tr(i) for i in arguments(x))...) @@ -126,6 +274,24 @@ tr(x::STensorOperator) = (*)((tr(i) for i in arguments(x))...) Base.hash(x::STrace, h::UInt) = hash((head(x), arguments(x)), h) Base.isequal(x::STrace, y::STrace) = isequal(x.op, y.op) + +@withmetadata struct SPartialTrace <: Symbolic{AbstractOperator} + obj + sys::Int +end +isexpr(::SPartialTrace) = true +iscall(::SPartialTrace) = true +arguments(x::SPartialTrace) = [x.obj, x.sys] +operation(x::SPartialTrace) = ptrace +head(x::SPartialTrace) = :ptrace +children(x::SPartialTrace) = [:ptrace, x.obj, x.sys] +function basis(x::SPartialTrace) + obj_bases = collect(basis(x.obj).bases) + new_bases = deleteat!(copy(obj_bases), x.sys) + tensor(new_bases...) +end +Base.show(io::IO, x::SPartialTrace) = print(io, "tr$(x.sys)($(x.obj))") + """Partial trace over system i of a composite quantum system ```jldoctest @@ -163,22 +329,6 @@ julia> ptrace(mixed_state, 2) ((0 + ⟨b||k⟩)A+(tr(B))|k⟩⟨b|) ``` """ -@withmetadata struct SPartialTrace <: Symbolic{AbstractOperator} - obj - sys::Int -end -isexpr(::SPartialTrace) = true -iscall(::SPartialTrace) = true -arguments(x::SPartialTrace) = [x.obj, x.sys] -operation(x::SPartialTrace) = ptrace -head(x::SPartialTrace) = :ptrace -children(x::SPartialTrace) = [:ptrace, x.obj, x.sys] -function basis(x::SPartialTrace) - obj_bases = collect(basis(x.obj).bases) - new_bases = deleteat!(copy(obj_bases), x.sys) - tensor(new_bases...) -end -Base.show(io::IO, x::SPartialTrace) = print(io, "tr$(x.sys)($(x.obj))") function ptrace(x::Symbolic{AbstractOperator}, s) ex = isexpr(x) ? qexpand(x) : x if isa(ex, typeof(x)) @@ -243,18 +393,7 @@ function ptrace(x::STensorOperator, s) end end -"""Inverse Operator - -```jldoctest -julia> @op A; - -julia> inv(A) -A⁻¹ -julia> inv(A)*A -𝕀 -``` -""" @withmetadata struct SInvOperator <: Symbolic{AbstractOperator} op::Symbolic{AbstractOperator} end @@ -268,4 +407,70 @@ basis(x::SInvOperator) = basis(x.op) Base.show(io::IO, x::SInvOperator) = print(io, "$(x.op)⁻¹") Base.:(*)(invop::SInvOperator, op::SOperator) = isequal(invop.op, op) ? IdentityOp(basis(op)) : SMulOperator(invop, op) Base.:(*)(op::SOperator, invop::SInvOperator) = isequal(op, invop.op) ? IdentityOp(basis(op)) : SMulOperator(op, invop) -inv(x::Symbolic{AbstractOperator}) = SInvOperator(x) \ No newline at end of file + +"""Inverse of an operator. + +```jldoctest +julia> @op A; + +julia> inv(A) +A⁻¹ + +julia> inv(A)*A +𝕀 +``` +""" +inv(x::Symbolic{AbstractOperator}) = SInvOperator(x) + + +@withmetadata struct SExpOperator <: Symbolic{AbstractOperator} + op::Symbolic{AbstractOperator} +end +isexpr(::SExpOperator) = true +iscall(::SExpOperator) = true +arguments(x::SExpOperator) = [x.op] +operation(x::SExpOperator) = exp +head(x::SExpOperator) = :exp +children(x::SExpOperator) = [:exp, x.op] +basis(x::SExpOperator) = basis(x.op) +Base.show(io::IO, x::SExpOperator) = print(io, "exp($(x.op))") + +"""Exponential of a symbolic operator. + +```jldoctest +julia> @op A; @op B; + +julia> exp(A) +exp(A) +``` +""" +exp(x::Symbolic{AbstractOperator}) = SExpOperator(x) + + +@withmetadata struct SVec <: Symbolic{AbstractKet} + op::Symbolic{AbstractOperator} +end +isexpr(::SVec) = true +iscall(::SVec) = true +arguments(x::SVec) = [x.op] +operation(x::SVec) = vec +head(x::SVec) = :vec +children(x::SVec) = [:vec, x.op] +basis(x::SVec) = (⊗)(fill(basis(x.op), length(basis(x.op)))...) +Base.show(io::IO, x::SVec) = print(io, "|$(x.op)⟩⟩") + +"""Vectorization of a symbolic operator. + +```jldoctest +julia> @op A; @op B; + +julia> vec(A) +|A⟩⟩ + +julia> vec(A+B) +(|A⟩⟩+|B⟩⟩) +``` +""" +vec(x::Symbolic{AbstractOperator}) = SVec(x) +vec(x::SScaled{AbstractOperator}) = x.coeff*vec(x.obj) +vec(x::SAdd{AbstractOperator}) = (+)((vec(i) for i in arguments(x))...) \ No newline at end of file diff --git a/src/QSymbolicsBase/literal_objects.jl b/src/QSymbolicsBase/literal_objects.jl index a65c850..a2a4161 100644 --- a/src/QSymbolicsBase/literal_objects.jl +++ b/src/QSymbolicsBase/literal_objects.jl @@ -2,11 +2,26 @@ # This file defines quantum objects (kets, bras, and operators) with various properties ## +"""Symbolic bra""" struct SBra <: Symbolic{AbstractBra} name::Symbol basis::Basis end SBra(name) = SBra(name, qubit_basis) + +""" + @bra(name, basis=SpinBasis(1//2)) + +Define a symbolic bra of type `SBra`. By default, the defined basis is the spin-1/2 basis. + +```jldoctest +julia> @bra b₁ +⟨b₁| + +julia> @bra b₂ FockBasis(2) +⟨b₂| +``` +""" macro bra(name, basis) :($(esc(name)) = SBra($(Expr(:quote, name)), $(basis))) end @@ -14,11 +29,26 @@ macro bra(name) :($(esc(name)) = SBra($(Expr(:quote, name)))) end +"""Symbolic ket""" struct SKet <: Symbolic{AbstractKet} name::Symbol basis::Basis end SKet(name) = SKet(name, qubit_basis) + +""" + @ket(name, basis=SpinBasis(1//2)) + +Define a symbolic ket of type `SKet`. By default, the defined basis is the spin-1/2 basis. + +```jldoctest +julia> @ket k₁ +|k₁⟩ + +julia> @ket k₂ FockBasis(2) +|k₂⟩ +``` +""" macro ket(name, basis) :($(esc(name)) = SKet($(Expr(:quote, name)), $(basis))) end @@ -26,11 +56,26 @@ macro ket(name) :($(esc(name)) = SKet($(Expr(:quote, name)))) end +"""Symbolic operator""" struct SOperator <: Symbolic{AbstractOperator} name::Symbol basis::Basis end SOperator(name) = SOperator(name, qubit_basis) + +""" + @op(name, basis=SpinBasis(1//2)) + +Define a symbolic ket of type `SOperator`. By default, the defined basis is the spin-1/2 basis. + +```jldoctest +julia> @op A +A + +julia> @op B FockBasis(2) +B +``` +""" macro op(name, basis) :($(esc(name)) = SOperator($(Expr(:quote, name)), $(basis))) end @@ -40,6 +85,7 @@ end ishermitian(x::SOperator) = false isunitary(x::SOperator) = false +"""Symbolic Hermitian operator""" struct SHermitianOperator <: Symbolic{AbstractOperator} name::Symbol basis::Basis @@ -49,6 +95,7 @@ SHermitianOperator(name) = SHermitianOperator(name, qubit_basis) ishermitian(::SHermitianOperator) = true isunitary(::SHermitianOperator) = false +"""Symbolic unitary operator""" struct SUnitaryOperator <: Symbolic{AbstractOperator} name::Symbol basis::Basis @@ -58,6 +105,7 @@ SUnitaryOperator(name) = SUnitaryOperator(name, qubit_basis) ishermitian(::SUnitaryOperator) = false isunitary(::SUnitaryOperator) = true +"""Symbolic Hermitian and unitary operator""" struct SHermitianUnitaryOperator <: Symbolic{AbstractOperator} name::Symbol basis::Basis @@ -67,6 +115,7 @@ SHermitianUnitaryOperator(name) = SHermitianUnitaryOperator(name, qubit_basis) ishermitian(::SHermitianUnitaryOperator) = true isunitary(::SHermitianUnitaryOperator) = true +"""Symbolic superoperator""" struct SSuperOperator <: Symbolic{AbstractSuperOperator} name::Symbol basis::Basis @@ -94,10 +143,13 @@ Base.show(io::IO, x::SymQObj) = print(io, symbollabel(x)) # fallback that probab struct SZero{T<:QObj} <: Symbolic{T} end +"""Symbolic zero bra""" const SZeroBra = SZero{AbstractBra} +"""Symbolic zero ket""" const SZeroKet = SZero{AbstractKet} +"""Symbolic zero operator""" const SZeroOperator = SZero{AbstractOperator} isexpr(::SZero) = false diff --git a/src/QSymbolicsBase/rules.jl b/src/QSymbolicsBase/rules.jl index b7d1a79..98b3d4f 100644 --- a/src/QSymbolicsBase/rules.jl +++ b/src/QSymbolicsBase/rules.jl @@ -94,14 +94,21 @@ RULES_SIMPLIFY = [RULES_PAULI; RULES_COMMUTATOR; RULES_ANTICOMMUTATOR] # Simplification rewriters ## -qsimplify_anticommutator = Chain(RULES_ANTICOMMUTATOR) qsimplify_pauli = Chain(RULES_PAULI) qsimplify_commutator = Chain(RULES_COMMUTATOR) +qsimplify_anticommutator = Chain(RULES_ANTICOMMUTATOR) + +""" + qsimplify(s; rewriter=nothing) -"""Manually simplify a symbolic expression of quantum objects. +Manually simplify a symbolic expression of quantum objects. If the keyword `rewriter` is not specified, then `qsimplify` will apply every defined rule to the expression. For performance or single-purpose motivations, the user has the option to define a specific rewriter for `qsimplify` to apply to the expression. +The defined rewriters for simplification are the following objects: + - `qsimplify_pauli` + - `qsimplify_commutator` + - `qsimplify_anticommutator` ```jldoctest julia> qsimplify(σʸ*commutator(σˣ*σᶻ, σᶻ)) @@ -144,7 +151,10 @@ RULES_EXPAND = [ # Expansion rewriter ## -"""Manually expand a symbolic expression of quantum objects. +""" + qexpand(s) + +Manually expand a symbolic expression of quantum objects. ```jldoctest julia> @op A; @op B; @op C; diff --git a/test/runtests.jl b/test/runtests.jl index 5a13c9e..4644d7b 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -37,6 +37,7 @@ println("Starting tests with $(Threads.nthreads()) threads out of `Sys.CPU_THREA @doset "zero_obj" @doset "trace" @doset "expand" +@doset "misc_linalg" @doset "throws" @doset "pauli" diff --git a/test/test_misc_linalg.jl b/test/test_misc_linalg.jl new file mode 100644 index 0000000..4517664 --- /dev/null +++ b/test/test_misc_linalg.jl @@ -0,0 +1,29 @@ +using QuantumSymbolics +using Test + +@op A; @op B; +O = SZeroOperator() + +@testset "Complex Conjugate" begin + @test isequal(conj(O), O) + @test isequal(conj(conj(A)), A) +end + +@testset "Transpose" begin + @test isequal(transpose(2*A), 2*transpose(A)) + @test isequal(transpose(A+B), transpose(A)+transpose(B)) + @test isequal(transpose(A*B), transpose(B)*transpose(A)) + @test isequal(transpose(A⊗B), transpose(A)⊗transpose(B)) + @test isequal(transpose(O), O) + @test isequal(transpose(transpose(A)), A) +end + +@testset "Vectorization" begin + @test isequal(vec(2*A), 2*vec(A)) + @test isequal(vec(A+B), vec(A)+vec(B)) + @test isequal(basis(vec(A)), SpinBasis(1//2)⊗SpinBasis(1//2)) +end + +@testset "Exponential" begin + @test isequal(exp(A), SExpOperator(A)) +end \ No newline at end of file