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

Setup

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

    qasm_array.append(line_data)

    # Keep adding lines until we see a new line.
    while lines[line_idx] != "\n":
        qasm_array.append(lines[line_idx])
        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 = [
    filename
    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:
            circuit_list.append(qasm_str)

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_name = "desired_backend"

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

Was this useful?

Fire Opal

Optimize your quantum algorithms

Next up

Continue learning about Fire Opal

Performing mid-circuit measurements

Creating a circuit with mid-circuit measurements and executing it with Fire Opal