qiskit-community / qiskit-hackathon-korea-21

A repository for Qiskit Hackathon Korea (February 16-19, 2021)
33 stars 11 forks source link

Generate OpenQASM3 from Qiskit code by parsing qiskit code with python ast #23

Closed hhorii closed 3 years ago

hhorii commented 3 years ago

Abstract

OpenQASM3 is under development in https://github.com/Qiskit/openqasm. OpenQASM3 supports classical statements in addition to quantum statements. In this project, a OpenQASM3 file is generated by analyzing python code that uses qiskit.

Description

OpenQASM3 supports classical instructions which include loop, branch, and unary/binary operations. However, it is difficult to write large OpenQASM3 file without help of tools.

In this project, we define DSL (domain specific language) which is a subset of python 3 and generate a OpenQASM3 file from a function written in the DSL.

The DSL uses Qiskit to write quantum instructions and use python expressions to write classical instructions. For example, following qft function can be supported in the DSL.

def qft(circuit):
    n = 5
    qr = QuantumRegister(n)
    circuit.add_register(qr)
    cr = ClassicalRegister(n)
    circuit.add_register(cr)

    for i in range(n):
        circuit.h(qr[i])

    for i in range(n):
        for j in range(i):
            l = math.pi / float(2 ** (i - j))
            circuit.p(l / 2, qr[i])
            circuit.cx(qr[i], qr[j])
            circuit.p(-l / 2, qr[j])
            circuit.cx(qr[i], qr[j])
            circuit.p(l / 2, qr[j])
        circuit.h(qr[i])

    circuit.barrier(qr)
    circuit.measure(qr, cr)

This function will be converted to a OpenQASM3 file as follows:

OPENQASM 3;
include "stdgates.inc";

const n = 10;

qubit qr[n];
bit cr[n];

float[64] l;
int[64] i, j;

for i in [0:n-1:1]
    h(qr[i);

for i in [0:n-1:1] {
    for j in [0:i-1:1] {
        l = pi / 2.0 ** (i - j);
        p(l / 2, qr[i]);
        cx(qr[i], qr[j];
        p(-l / 2, qr[j]);
        cx(qr[i], qr[j]);
        p(l / 2, qr[j]);
    }
}
cr = measure(qr);

In this project, we parse a specific function of python (with many assumptions) and generate a OpenQASM3 file. In general, Python code is analyzed by using pytyon.ast. Python.ast tree can be generated with this code:

import ast
import astpretty

with open(filename, 'r') as f:
     source = f.read()

tree = ast.parse(source)

for stmt in tree.body:
    astpretty.pprint(stmt)

We can validate generated OpenQASM3 file with antlr g4 file of OpenQASM3.

Maybe work items will be

Because Qiskit and OpenQASM3 cover huge, we start a very limited scope of them. Maybe we can show strategy to implement remaining part of OpenQASM3.

One of example to use python ast is classicalfunction which generate oracle with an annotation @classical_function.

Members

Deliverable

Python utility tool to generate a OpenQASM file from a Qiskit code.

GitHub repo