QuantumBFS / ZXCalculus.jl

An implementation of ZX-calculus in Julia
http://yaoquantum.org/ZXCalculus.jl/dev/
MIT License
48 stars 7 forks source link

convert ZXDiagram to tensor network #16

Closed Roger-luo closed 1 year ago

GiggleLiu commented 4 years ago

Might be useful in the future.

function ztensor(nleg::Int, α::T) where T<:Number
    shape = (fill(2, nleg)...,)
    factor = exp(im*α)
    out = zeros(typeof(factor), shape...)
    out[1] = one(typeof(factor))
    out[fill(2, nleg)...] = factor
    out
end

function xtensor(nleg::Int, α::T) where T<:Number
    pos = [1, 1]/sqrt(2)
    neg = [1, -1]/sqrt(2)
    shape = (fill(2, nleg)...,)
    reshape(reduce(kron, fill(pos, nleg)) + exp(im*α)*reduce(kron, fill(neg, nleg)), shape)
end

function htensor(nleg::Int, α::T) where T<:Number
    shape = (fill(2, nleg)...,)
    factor = exp(im*α)
    out = fill(one(typeof(factor)), shape)
    out[fill(2, nleg)...] = factor
    return out
end
GiggleLiu commented 4 years ago

The correspondence with Yao.jl

θ = 0.5
@test mat(Rz(θ) * phase(θ/2)) ≈ ztensor(2, θ)
@test mat(Rx(θ) * phase(θ/2)) ≈ xtensor(2, θ)
@test mat(H) .* sqrt(2) ≈ htensor(2, π)
@test mat(shift(θ)) ≈ ztensor(2, θ)

Some identities

θ = 0.5
@test mat(Rz(θ) * Yao.phase(θ/2)) ≈ ztensor(2, θ)
@test mat(shift(θ)) ≈ ztensor(2, θ)
@test mat(Rx(θ) * Yao.phase(θ/2)) ≈ xtensor(2, θ)
@test mat(H) .* sqrt(2) ≈ htensor(2, π)
@test mat(T) ≈ ztensor(2, π/4)
@test mat(ConstGate.S) ≈ ztensor(2, π/2)
@test mat(chain(ConstGate.Sdag, X, ConstGate.S)) ≈ mat(Y)
@test mat(T) ≈ mat(Rz(π/4) * Yao.phase(π/8))
@test mat(ConstGate.S) ≈ mat(Rz(π/2) * Yao.phase(π/4))

For more, see https://github.com/QuantumBFS/YaoZX.jl

exAClior commented 1 year ago

This is implemented in #93 albeit for zxw diagram. I will close this for now.