# Swap test to calculate inner product with qiskit for multi-qubit states

Is it possible to perform a controlled swap test with multiple targets with qiskit? I have tried using cswap(ancilla[0],qb1,qb2), where qb1 is an n-qubit register and qb2 is as well

• It should be possible. In this case you would be swapping qb1 and qb2 is ancilla[0] is in the 1 state. Is this what you are expecting? Documentation on the cswap method can be found here: qiskit.org/documentation/api/… Feb 7 '20 at 15:00
• Yes, this is what I want to happen, but I get the following error message: qiskit.circuit.exceptions.CircuitError: "Not sure how to combine these qubit arguments:\n [[Qubit(QuantumRegister(3, 'q4'), 0)], [Qubit(QuantumRegister(3, 'q0'), 0), Qubit(QuantumRegister(3, 'q0'), 1), Qubit(QuantumRegister(3, 'q0'), 2)], [Qubit(QuantumRegister(3, 'q2'), 0), Qubit(QuantumRegister(3, 'q2'), 1), Qubit(QuantumRegister(3, 'q2'), 2)]]\n" Feb 7 '20 at 15:11
• Oh I think the registers need to be the same size. So if ancilla[0], qb1, and qb2 are a different size then you will get this error. You would need to set multiple cswap gates depending on the sizes of qb1 and qb2. For example if qb1 and qb2 are of size 2, you would call cswap(ancilla[0], qb1[0], qb2[0]) and then call cswap(ancilla[0], qb1[1], qb2[1]) Feb 7 '20 at 15:27
• @MatthewStypulkoski could you add this as an answer instead of a comment (do not delete the comment)? Feb 7 '20 at 16:50

It is possible, but when calling cswap, all of the arguments need to be of the same size. In your example, assuming ancilla[0] is 1 qubit, you would need qb1 and qb2 to also be 1 qubit. If qb1 and qb2 are QuantumRegisters of size > 1, then you would need multiple cswap calls. For example, if qb1 and qb2 are of size 2:

circuit.cswap(ancilla[0], qb1[0], qb2[0])
circuit.cswap(ancilla[0], qb1[1], qb2[1])


This way the ancilla[0] qubit is still the control for both calls, and all of the arguments in both calls are of the same size.

If you aren't keeping the states that you performed the swap test on, you don't need to use CSWAPs to perform the swap test. You can instead just pair up the qubits from each system, perform Bell basis measurements on them, and count whether you see the 11 result and odd or even number of times.

This:

Gives the same result statistics as this:

But the latter is much less demanding on the quantum hardware, because the three qubit gates can be done in the classical postprocessing.

• Thanks! Can you explain why the latter works? Also, are the cnots supposed to be before the hadamards? Feb 8 '20 at 7:44
• @QCQCQC You can rewrite the first circuit into the second by taking advantage of the ability to add or remove operations on qubits that will be discarded. Decompose the CSWAPs into CNOT-TOF-CNOT, the right CNOTs are discarded, introduce Hadamards and measurements, propagate left to flip direction of Toffolis. Yes the CNOTs are where they are supposed to be. Feb 8 '20 at 21:14