Q-CTRL logo

Jupyter Get the notebook

How to import OpenQASM from files

Importing OpenQASM from external files to Python

Submitting circuits to Fire Opal requires the circuits to be formatted as OpenQASM strings. This notebook demonstrates how to import OpenQASM strings from external files for use with Fire Opal.

import os
from typing import List, Tuple

from fireopal import validate


In order to read the files, we define a helper function to pull all OpenQASM strings from a file, and specify the directory in which the files are found.

def extract_qasm(lines: List[str], starting_idx: int) -> Tuple[str, int]:
    "Extract the next QASM string from the file."
    qasm_array = []
    line_data = ""
    line_idx = starting_idx

    # Find the starting line.
    while "OPENQASM" not in line_data and line_idx < len(lines):
        line_data = lines[line_idx]
        line_idx += 1

    if line_idx == len(lines):
        return None, line_idx


    # Keep adding lines until we see a new line.
    while lines[line_idx] != "\n":
        line_idx += 1

    return ("".join(qasm_array), line_idx)
circuit_directory = "../relative/path/to/circuits"  # the relative path from this notebook to your file(s)
circuit_filenames = [
    for filename in os.listdir(circuit_directory)
    if filename.endswith((".txt", ".qasm"))

Read OpenQASM strings from file(s)

Next, we create a list of OpenQASM strings from the files specified above.

circuit_list = []
for filename in circuit_filenames:
    with open(circuit_directory + filename, "r") as filehandle:
        lines = filehandle.readlines()

    line_idx = 0
    while line_idx < len(lines):
        qasm_str, line_idx = extract_qasm(lines, line_idx)
        if qasm_str is not None:

Validate imported strings for use with Fire Opal

Finally, we ensure the imported strings are valid OpenQASM strings that can be executed with Fire Opal.

# Enter your IBM token here.
token = "your_IBM_token"

# These are the properties for the publicly available provider for IBM backends.
# If you have access to a private provider and wish to use it, replace these values.
hub = "ibm-q"
group = "open"
project = "main"

credentials = {"token": token, "hub": hub, "group": group, "project": project}

# Enter your desired IBM backend here.
backend = "desired_backend"

validate_results = validate(
    circuits=circuit_list, credentials=credentials, backend=backend
print(f"Number of circuits validated: {len(circuit_list)}")
print(f"Number of circuit errors found: {len(validate_results['results'])}")