[BUG] Unexpected behaviour when using tape.to_openqasm()
See original GitHub issueExpected behavior
Consider the tape
import pennylane as qml
with qml.tape.QuantumTape() as tape:
qml.PauliX(wires=1)
qml.PauliY(wires=0)
Note that the first gate is applied to wire 1 and tape.wires = <Wires = [1, 0]>.
We know convert to QASM:
>>> print(tape.to_openqasm())
OPENQASM 2.0;
include "qelib1.inc";
qreg q[2];
creg c[2];
x q[0];
y q[1];
measure q[0] -> c[0];
measure q[1] -> c[1];
We see that the wires have been permuted, i.e., with X being applied to wire 0 and Y being applied to wire 1.
This can be fixed by specifying a wire ordering in to_openqasm():
>>> print(tape.to_openqasm(wires=sorted(tape.wires)))
OPENQASM 2.0;
include "qelib1.inc";
qreg q[2];
creg c[2];
x q[1];
y q[0];
measure q[0] -> c[0];
measure q[1] -> c[1];
Actual behavior
The permuted wire ordering is unexpected behaviour and seems to arise from the tape wires not being ordered, i.e., tape.wires = <Wires = [1, 0]>. Another side-effect of non-ordered tape wires is that tape.draw() can potentially be surprising:
>>> tape.draw()
1: ──X──┤
0: ──Y──┤
(again, fixable by specifying a wire ordering)
On the other hand, do we not sort tape wires by default because we can have custom wire labels like strings?
Additional information
This behaviour was highlighted in this PR: https://github.com/unitaryfund/mitiq/pull/836
Source code
import pennylane as qml
with qml.tape.QuantumTape() as tape:
qml.PauliX(wires=1)
qml.PauliY(wires=0)
print("Default wire ordering:\n")
print(tape.to_openqasm())
print("\nCorrected wire ordering:\n")
print(tape.to_openqasm(wires=sorted(tape.wires)))
Tracebacks
No response
System information
Dev PL
- I have searched exisisting GitHub issues to make sure the issue does not already exist.
Issue Analytics
- State:
- Created 2 years ago
- Comments:5 (4 by maintainers)

Top Related StackOverflow Question
@rmlarose that is a good point! We can definitely alter this behaviour. I’m not 100% sure why all qubits are currently measured; it could be one of two things:
For me this links to a more general question of wires being maybe too flexible (e.g., functions, floats) such that we can’t sort them. If that were solved, it’d be easy to fix this issue.
In terms of closing this, I think it’s still a valid issue in the sense that it’s doing something weird even if its what we expect at this point. Maybe we need a “known issues” category of stuff we’re not going to worry about, but still keep track of. Otherwise, if you find this is unnecessary noise in the list of issues, then it’s also ok to close.