Correct wire ordering for operations on 3+ wires

Hi there,

I have been building circuits using qml.QubitUnitary and am getting confused by the wiring convention in Pennylane when using more than 2 wires in a single operation.

Consider the following example

import pennylane as qml

dev2 = qml.device('default.qubit', wires=2)

def circuit2():
    return qml.probs(wires=[0,1])

Executing circuit2() returns

array([0.5, 0. , 0.5, 0. ])

This corresponds to the superposition |00> + |10>, so I deduce that the wire numbers passed as argument to qml.probs are ordered from most significant to least significant qubit.

Expanding this example to three qubits,

dev3 = qml.device('default.qubit', wires=3)

def circuit3():
    return qml.probs(wires=[0,1,2])

and executing circuit3(), we obtain as expected

array([0.5, 0. , 0. , 0. , 0.5, 0. , 0. , 0. ])

By reordering the wires to [1,2,0], I would now expect to obtain

array([0.5 , 0.5, 0. , 0. , 0. , 0. , 0., 0. ])

but instead I get

>>> @qml.qnode(dev3)
... def circuit3b():
...     qml.Hadamard(wires=0)
...     return qml.probs(wires=[1,2,0])
>>> circuit3b()
array([0.5, 0. , 0.5, 0. , 0. , 0. , 0. , 0. ])

The same ordering seems to be used for qml.QubitUnitary. What is wrong in my reasoning?

Hi @Oe2tam, and welcome! :slight_smile:

As you have deduced, PennyLane states are ordered with wire 0 always corresponding to the leftmost index, i.e., in the flattened array of a 3-qubit state, you have elements (in order) 000, 001, 010, 011, 100, 101, 110, 111 and the indices correspond to [wire 0][wire 1][wire 2] .

The example you provide smells like a possible bug to me. I don’t think we give any hard guarantees that permuted wire ordering will work. In the short term, I recommend you stick to “ordered” wire lists, and permute the resulting arrays afterwards if you need to.

Note that we are refactoring the way PennyLane handles wires at the moment ([WIP] Introduce wire class by mariaschuld · Pull Request #615 · PennyLaneAI/pennylane · GitHub). This won’t change the convention for indexing, but should help reduce possible edge-case bugs.

Hi @nathan!

Thank you so much for the reply. I’m indeed new to Pennylane! But you will here from me in the future :slight_smile:

That makes sense. I was working with arrays to store the wire numbering and never paid attention to the actual ordering of the wires. That probably explains my problems!

Thanks too for pointing out the upcoming changes. I will keep an eye on it. Being able to reorder wires would come in handy when working with qml.QubitUnitary.