Given a unitary matrix of a unknown gate, can we write a program in Qiskit to output the name of the corresponding gate if that is a standard gate? So suppose I have $U = \begin{pmatrix} 0 & 1\\ 1 & 0 \end{pmatrix}$, I want Qiskit to output the Pauli $X$ gate name.
1 Answer
I don't think Qiskit itself has some functionality to directly get what you want but you could implement it by yourself using something like the following:
from inspect import getmembers, isclass
import numpy as np
from qiskit.circuit.library import standard_gates
def get_qiskit_gate(u):
for name, gate in getmembers(standard_gates, isclass):
try:
unitary = gate().__array__()
except:
continue
if unitary.shape == u.shape and np.allclose(unitary, u):
return name
However, this will work only for standard gates (defined in the qiskit.circuit.library.standard_gates
module) that implement the __array__
attribute. If the given unitary u
does not correspond to any of these gates, the function will simply returns None
.
Here is an example for the Pauli $X$ gate:
unitary = np.array([[0, 1],
[1, 0]])
print(get_qiskit_gate(u=unitary))
XGate
-
$\begingroup$ Also can you please tell me if I have a standard gate, how can I get its unitary matrix from qiskit $\endgroup$ Commented Feb 8, 2023 at 20:26
-
$\begingroup$ Please open a new question and add some more details about what you need to do $\endgroup$ Commented Feb 8, 2023 at 23:46
-
$\begingroup$ unitary = np.array([[0.707, 0.707], [0.707,- 0.707]]). Why isn't the code outputting hadamard for the above unitary matrix $\endgroup$ Commented Feb 9, 2023 at 4:19
-
$\begingroup$ That happens simply because of the
np.allclose
finite precision when comparing the arrayunitary
with the arrayu
. If you put 0.7071, it works fine;unitary = np.array([[1, 1], [1, -1]]) / np.sqrt(2)
would be even better $\endgroup$ Commented Feb 9, 2023 at 8:58