I have two circuits that I believe are equivalent. When I say 'equivalent' I mean that they have equivalent unitary representations up to a global phase. How can one check this using Qiskit? How I would show equivalence isn't clear to me.
As it is point out, depends on your notion of equivalence.
Two circuits are equivalent upto global phase if they represent the same state vector. Consider the following two circuits:
from qiskit import QuantumCircuit import numpy as np qc1 = QuantumCircuit(2) qc1.h(0) qc1.cx(0,1) qc2 = QuantumCircuit(2) qc2.u2(0, np.pi, 0) qc2.cx(0,1)
It is possible to check if their state vector is the same with the Qiskit
from qiskit.quantum_info import Statevector Statevector.from_instruction(qc1).equiv(Statevector.from_instruction(qc2)) # True
If you need to consider global phase, in that case you need to compare their unitary matrices via simulation.
In the following case:
qc1 = QuantumCircuit(1) qc1.x(0) qc2 = QuantumCircuit(1) qc2.rx(np.pi, 0)
These circuit has the same state vector, but not the same unitary:
Statevector.from_instruction(qc1).equiv(Statevector.from_instruction(qc2)) # True backend_sim = Aer.get_backend('unitary_simulator') job_sim = execute([qc1, qc2], backend_sim) result_sim = job_sim.result() unitary1 = result_sim.get_unitary(qc1) unitary2 = result_sim.get_unitary(qc2) np.allclose(unitary1, unitary2) # False
If your circuits have measurements, you probably want to consider these to circuits equivalent, since their measured results are equivalent.
qc1 = QuantumCircuit(2,2) qc1.h(0) qc1.measure(0,0) qc1.measure(1,1) qc2 = QuantumCircuit(2,2) qc2.h(0) qc2.swap(0,1) qc2.measure(0,1) qc2.measure(1,0)
In this case, you want to compare their result counts, considering some statistical error:
backend_sim = Aer.get_backend('qasm_simulator') job_sim = execute([qc1, qc2], backend_sim, shots=1000) result_sim = job_sim.result() counts1 = result_sim.get_counts(qc1) counts2 = result_sim.get_counts(qc2) print(counts1, counts2)
Up to Ancillas
You might want to consider these two circuits equivalent:
qc1 = QuantumCircuit(3) qc1.x(0) qc2 = QuantumCircuit(1) qc2.rx(np.pi, 0)
It was suggested to invert one of them, compose them (wiring the ancillas) and check if it is the identity. For example:
from qiskit.quantum_info import Operator composed = qc1.compose(qc2.inverse(), qubits=range(len(qc2.qubits))) Operator(composed).equiv(Operator.from_label('I'*len(qc1.qubits))) # True
A simpler method is to use
equiv method directly from the
Operator class. Basically convert both the circuits to operators and then use
equiv. You can check out the documentation for the Operator class here.
The basic syntax would be something like,
from qiskit import * from qiskit.quantum_info import Operator Op1 = Operator(qc1) Op2 = Operator(qc2) Op1.equiv(Op2)
Where qc1 and qc2 are your two quantum circuits.