Errors in passing quantum matrix operators to QNode object

Hi,

I’m trying to execute the following code:

The below code works fine:
import pennylane as qml
from pennylane import numpy as np

dev = qml.device('default.qubit', wires=2)
@qml.qnode(dev, interface='numpy')
def circuit1(phi, theta):
    qml.RX(phi[0], wires=0)
    qml.RY(phi[1], wires=1)
    qml.CNOT(wires=[0, 1])
    qml.PhaseShift(theta, wires=0)
    qml.T(wires = 1)
    return qml.expval(qml.PauliZ(0)), qml.expval(qml.Hadamard(1))

phi = np.array([0.5, 0.1])
theta = 0.2
print(circuit1(phi, theta))

Now let’s say that I want to turn qml.T into the matrix it represents (https://pennylane.readthedocs.io/en/stable/code/api/pennylane.T.html) and pass that matrix. Doing this I can write:

dev = qml.device('default.qubit', wires=2)
@qml.qnode(dev, interface='numpy')
def circuit1(phi, theta, matrix):
    qml.RX(phi[0], wires=0)
    qml.RY(phi[1], wires=1)
    qml.CNOT(wires=[0, 1])
    qml.PhaseShift(theta, wires=0)
    qml.QubitUnitary(matrix, wires=1)
    return qml.expval(qml.PauliZ(0)), qml.expval(qml.Hadamard(1))

phi = np.array([0.5, 0.1])
theta = 0.2
matrix = np.array([[1, 0], [0, 0.70710678 + 0.70710678*1.j]])
print(circuit1(phi, theta, matrix))

However when I do this I get the following error:

TypeError: RX: Real scalar parameter expected, got <class 'numpy.complex128'>.

Printing out the values for phi I get:

(0.5+0j)
(0.1+0j)

which is very much confusing since I never passed
phi = 0.5 +0j, 0.1+0j
in the 1st place as I only passed phi = 0.5, 0.1!

It appears that by passing a complex array/matrix into Pennylane I contaminate all of the input variables! (I tried commenting out and passing only theta but the same thing happened to theta- it got turned into an imaginary number).

How do I solve this error?

Thanks!

Hi @max,

Internally, PennyLane will eventually have to cast all variables to complex numbers (since the simulation of a quantum state takes places in a complex space). What you’re seeing is a byproduct of that (though unintended).

Internally QubitUnitary decomposes to a particular sequences of gates (so it can run on hardware if possible). It looks like you’ve found a bug in the decomposition. I’ve added an issue on our GitHub page.

I think it’s unrelated, but I need some clarity about how you are “Printing out the values for phi”. I’ve reproduced your code, and though I am seeing the exception, there is no change to the variable phi. Can you provide the exact code which gives the values (0.5+0j) and (0.1+0j)?