Compilation

Inlining & Unrolling

This example demonstrates the capabilities of the PyQASM tool by unrolling a complex OpenQASM program into a simplified form.

In PyQASM, “unrolling” refers to the process of simplifying a quantum program by expanding custom gate definitions and flattening complex language constructs like subroutines, loops, and conditional statements into basic operations. This technique, also known as program flattening or inlining, transforms nested and recursive structures into a linear sequence of operations consisting solely of qubit and classical bit declarations, gate operations, and measurement operations. By converting the program into this simplified format, it becomes easier to perform subsequent transpilation or compilation steps before executing the program on a quantum device.

example.qasm
OPENQASM 3.0;
include "stdgates.inc";

// Define custom gates
gate hgate q {
    h q;
}
gate xgate q {
    x q;
}
gate cxgate q1, q2 {
    cx q1, q2;
}

// Define a subroutine for creating a Bell state
def create_bell_state(qubit[2] q) {
    hgate q[0];
    cxgate q[0], q[1];
    return;
}

// Define a subroutine for a generic quantum operation
def generic_operation(qubit[N] q) {
    for int i in [0:N-1] {
        hgate q[i];
        xgate q[i];
        y q[i];
        rx(pi) q[i];
    }
    return;
}

// Main program
const int[32] N = 4;
qubit[N] q;
bit[N] c;

// Create a Bell state using the alias
create_bell_state(q[0:2]);

measure q[0:1] -> c[0:1];

// Perform a generic operation on all qubits
generic_operation(q);

// Classical control flow
if (c[0]) {
    hgate q[0];
} else {
    xgate q[0];
}

// Define an array of angles for parameterized gates
array[float[64], N] angles = {pi/2, pi/4, pi/8, pi/16};

// Apply parameterized rotations
for int i in [0:N-1] {
    rx(angles[i]) q[i];
}

// Measure the qubits
c = measure q;

For complete details about the supported operations, see PyQASM Supported Operations.

Analysis

num_qubits, num_clbits, and depth

This example demonstrates how to use the num_qubits, num_clbits, and depth methods.

Transformations

has_measurements and remove_measurements

This example demonstrates how to check for measurements and remove them.

Very similar to the previous example, we also have has_barriers and remove_barriers methods to check for barriers and remove them, respectively.

populate_idle_qubits

This example demonstrates how to populate idle qubits with identity gates -

remove_idle_qubits

This example demonstrates how to remove idle qubits from the module and shows the qubit count before and after.

reverse_qubit_order

This example demonstrates how to reverse the order of qubits in the module with a more involved program.

Refer to the PyQASM API Documentation for more details on the available methods and their usage.