Hello! If we have two vectors with 4 dimensionality, i.e., x_1 = [1, 2, 3, 4 ] and x_2 = [5, 6, 7, 8],How can we contribute a “SWAP TEST” quantum circuit for evaluate these vectors’ similarity?
Thanks a lot!
Hello! If we have two vectors with 4 dimensionality, i.e., x_1 = [1, 2, 3, 4 ] and x_2 = [5, 6, 7, 8],How can we contribute a “SWAP TEST” quantum circuit for evaluate these vectors’ similarity?
Thanks a lot!
Hey @zj-lucky,
Sounds like you’re trying to do the swap test with two 2-qubit states? Is that right?
Each vector x_i can be represented by a two-qubit state; there are two such vectors.
Ah! Okay. Then this should be straightforward enough I think. Here’s what it looks like to swap two two-qubit states:
import pennylane as qml
from pennylane import numpy as np
dev = qml.device('default.qubit')
@qml.qnode(dev)
def four_qubit_SWAP(state):
qml.AmplitudeEmbedding(state, wires=range(4), normalize=True)
qml.SWAP(wires=[1, 3])
qml.SWAP(wires=[0, 2])
return qml.state()
state1 = np.array([0.5, -0.5, -0.5, 0.5])
state2 = np.array([-0.5, 0.5, 0.5, -0.5])
state = np.kron(state1, state2)
# swap state1 with state2
print(state)
print(four_qubit_SWAP(state))
print(qml.draw(four_qubit_SWAP)(state))
[-0.25 0.25 0.25 -0.25 0.25 -0.25 -0.25 0.25 0.25 -0.25 -0.25 0.25
-0.25 0.25 0.25 -0.25]
[-0.25+0.j 0.25+0.j 0.25+0.j -0.25+0.j 0.25+0.j -0.25+0.j -0.25+0.j
0.25+0.j 0.25+0.j -0.25+0.j -0.25+0.j 0.25+0.j -0.25+0.j 0.25+0.j
0.25+0.j -0.25+0.j]
0: ─╭|Ψ⟩───────╭SWAP─┤ State
1: ─├|Ψ⟩─╭SWAP─│─────┤ State
2: ─├|Ψ⟩─│─────╰SWAP─┤ State
3: ─╰|Ψ⟩─╰SWAP───────┤ State
It’s just a combination of two different SWAP gates . Then, to do a SWAP test here, you just need to make a larger controlled operator out of two swap gates.
@qml.qnode(dev)
def double_swap_test():
qml.Hadamard(0)
qml.ctrl(qml.SWAP(wires=[2, 4]) @ qml.SWAP(wires=[1, 3]), control=0)
qml.Hadamard(0)
return qml.state()
print(qml.draw(double_swap_test)())
0: ──H─╭●──────────H─┤ State
2: ────├SWAP@SWAP────┤ State
4: ────├SWAP@SWAP────┤ State
1: ────├SWAP@SWAP────┤ State
3: ────╰SWAP@SWAP────┤ State