Given a unitary matrix, output the gate name using Qiskit

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.

• Using Simone's methodology, you could also search for specific multiples, fractions, or powers of gates, including the square roots. Feb 7, 2023 at 22:27

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

• Also can you please tell me if I have a standard gate, how can I get its unitary matrix from qiskit Feb 8, 2023 at 20:26
• Please open a new question and add some more details about what you need to do Feb 8, 2023 at 23:46
• unitary = np.array([[0.707, 0.707], [0.707,- 0.707]]). Why isn't the code outputting hadamard for the above unitary matrix Feb 9, 2023 at 4:19
• That happens simply because of the np.allclose finite precision when comparing the array unitary with the array u. If you put 0.7071, it works fine; unitary = np.array([[1, 1], [1, -1]]) / np.sqrt(2) would be even better Feb 9, 2023 at 8:58