Here is an example of writing an OpenQASM 2.0 program from a quantum score. I have broken it down into columns from top to bottom of the score for clarity, and annotated these in the diagram by indicating column numbers in orange.
We saw the following circuit in a previous chapter where it illustrated the reversibility of quantum computations:
Let's dissect the OpenQASM that generates this circuit.
The first lines are, as usual, the headers, indicating the code is OpenQASM and that we will be using the standard IBM QX header:
OPENQASM 2.0;
include "qelib1.inc";
The next lines declare a quantum register named q of 5 qubits initialized to |"00000"> and a classical register name c of 5 bits initialized to 00000:
// declare the quantum and classical registers we will use
qreg q[5];
creg c[5];
The next lines will go column by column in the circuit diagram, creating the code for each column in order.
We will start with the first column:
The first column we can see only contains a CNOT gate, with its control qubit being the third qubit in the q quantum register, q[2] and the target qubit being the second qubit in the q quantum register, q[1]. Looking up the OpenQASM syntax for the CNOT gate in the table in the previous section, we see that it is cnot control, target; , which means that the first column will be coded as:
//column 1
cx q[2],q[1];
Next we will move to the second column, which has a number of gates specified. The code for the second column is:
//column2
x q[1];
h q[2];
s q[3];
y q[4];
Each successive column should now be straightforward to encode from looking at the quantum score in OpenQASM. The full program is as follows:
OPENQASM 2.0;
include "qelib1.inc";
// declare the quantum and classical registers we will use
qreg q[5];
creg c[5];
//column 1
cx q[2],q[1];
//column2
x q[1];
h q[2];
s q[3];
y q[4];
//column 3
t q[2];
z q[3];
//column 4
tdg q[2];
z q[3];
//column 5
x q[1];
h q[2];
sdg q[3];
y q[4];
// column 6
cx q[2],q[1];
// column 7
measure q[0] -> c[0];
// column 8
measure q[1] -> c[1];
// column 9
measure q[2] -> c[2];
// column 10
measure q[3] -> c[3];
// column 11
measure q[4] -> c[4];
The previous code exactly reproduced the quantum score as depicted, but we could make several quantum scores, which are equivalent (and thus several variations on the OpenQASM program that are equivalent), as we saw in previous sections. Here are a couple of things to keep in mind:
- Each column could be in any order, for example column 3 could be:
t q[2];
z q[3];
- Or it could be:
z q[3];
tdg q[2];
In addition, any gate operating on a qubit in any column where there is no gate in the previous column on the qubit can be moved to the previous column, without affecting the computation.