qml.transforms.get_unitary_matrix¶

get_unitary_matrix(circuit, wire_order=None)[source]

Construct the matrix representation of a quantum circuit.

Parameters
• circuit (pennylane.QNode, QuantumTape, or Callable) – A quantum node, tape, or function that applies quantum operations.

• wire_order (Sequence[Any], optional) – Order of the wires in the quantum circuit. Defaults to the order in which the wires appear in the quantum function.

Returns

Function which accepts the same arguments as the QNode or quantum function. When called, this function will return the unitary matrix in the appropriate autodiff framework (Autograd, TensorFlow, PyTorch, JAX) given its parameters.

Return type

function

Example

Consider the following function (the same applies for a QNode or tape):

def circuit(theta):
qml.RX(theta, wires=1)
qml.PauliZ(wires=0)

We can use get_unitary_matrix to generate a new function that returns the unitary matrix corresponding to the function circuit:

>>> get_matrix = get_unitary_matrix(circuit)
>>> theta = np.pi / 4
>>> get_matrix(theta)
array([[ 0.92387953+0.j,  0.+0.j ,  0.-0.38268343j,  0.+0.j],
[ 0.+0.j,  -0.92387953+0.j,  0.+0.j,  0. +0.38268343j],
[ 0. -0.38268343j,  0.+0.j,  0.92387953+0.j,  0.+0.j],
[ 0.+0.j,  0.+0.38268343j,  0.+0.j,  -0.92387953+0.j]])

Note that since wire_order was not specified, the default order [1, 0] for circuit was used, and the unitary matrix corresponds to the operation $$Z\otimes R_X(\theta)$$. To obtain the matrix for $$R_X(\theta)\otimes Z$$, specify wire_order=[0, 1] in the function call:

>>> get_matrix = get_unitary_matrix(circuit, wire_order=[0, 1])

You can also get the unitary matrix for operations on a subspace of a larger Hilbert space. For example, with the same function circuit and wire_order=["a", 0, "b", 1] you obtain the $$16\times 16$$ matrix for the operation $$I\otimes Z\otimes I\otimes R_X(\theta)$$.

This unitary matrix can also be used in differentiable calculations. For example, consider the following cost function:

def circuit(theta):
qml.RX(theta, wires=1)
qml.PauliZ(wires=0)
qml.CNOT(wires=[0, 1])

def cost(theta):
matrix = get_unitary_matrix(circuit)(theta)
return np.real(np.trace(matrix))

Since this cost function returns a real scalar as a function of theta, we can differentiate it: