qbraid logo PyQASM

Python toolkit for OpenQASM program analysis and compilation.


Release:

0.0.3

Overview

PyQASM is a Python toolkit that providing advanced utilities for semantic analysis and compilation of OpenQASM 3 programs. Building upon the OpenQASM 3 parser, PyQASM offers additional features such as program validation and unrolling, making it a powerful tool for quantum software developers.

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.

A practical example of PyQASM’s utility is its role in the qasm3 interface of the qBraid-QIR project. Here, PyQASM serves as a core dependency, leveraging its unrolling capabilities to simplify input programs and facilitate their seamless conversion into Quantum Intermediate Representation (QIR).

Installation

PyQASM requires Python 3.10 or greater. The base package can be installed with pip as follows:

pip install pyqasm

Example

import pyqasm

qasm = """
OPENQASM 3;
include "stdgates.inc";

gate hgate q { h q; }
gate xgate q { x q; }

const int[32] N = 4;
qubit[4] q;
qubit ancilla;

def deutsch_jozsa(qubit[N] q_func, qubit[1] ancilla_q) {
   xgate ancilla_q;
   for int i in [0:N-1] { hgate q_func[i]; }
   hgate ancilla_q;
   for int i in [0:N-1] { cx q_func[i], ancilla_q; }
   for int i in [0:N-1] { hgate q_func[i]; }
}

deutsch_jozsa(q, ancilla);

bit[4] result;
result = measure q;
"""

module = pyqasm.load(qasm)
module.unroll()

unrolled_qasm = module.unrolled_qasm

print(unrolled_qasm)
OPENQASM 3;
include "stdgates.inc";
qubit[4] q;
qubit[1] ancilla;
x ancilla[0];
h q[0];
h q[1];
h q[2];
h q[3];
h ancilla[0];
cx q[0], ancilla[0];
cx q[1], ancilla[0];
cx q[2], ancilla[0];
cx q[3], ancilla[0];
h q[0];
h q[1];
h q[2];
h q[3];
bit[4] result;
result[0] = measure q[0];
result[1] = measure q[1];
result[2] = measure q[2];
result[3] = measure q[3];

Resources