OpenQASM 2

Overview

QuantumRingsLib can compose a QuantumCircuit from OpenQASM 2.x content.

There are two supported entry points:

  • QuantumCircuit.from_qasm_file(path) — compose a circuit from an OpenQASM 2 file.

  • QuantumCircuit.from_qasm_str(qasm_str) — compose a circuit from an OpenQASM 2 string.

For the recommended end-to-end workflow (provider → backend → circuit → run), see Circuits.

QuantumRingsLib also provides a qasm2 helper class for importing qasm2-compliant files/strings into a quantum circuit. The qasm2.load(...) and qasm2.loads(...) methods accept additional parameters (for example, an include path and a strict flag). See the API reference for details.

Existing OpenQASM 2 files can also be submitted directly to BackendV2.run without first composing a QuantumCircuit.

Import from a file

Use QuantumCircuit.from_qasm_file(...) to compose a circuit from an OpenQASM 2 file:

from QuantumRingsLib import QuantumCircuit

circuit_name = r"C:\\path\\to\\circuit.qasm"
qc = QuantumCircuit.from_qasm_file(circuit_name)

Or using the qasm2 helper class:

from QuantumRingsLib import qasm2

circuit_name = r"C:\\path\\to\\circuit.qasm"

qa = qasm2()
qc = qa.load(circuit_name)

Import from a string

Use QuantumCircuit.from_qasm_str(...) to compose a circuit from an OpenQASM 2 string:

from QuantumRingsLib import QuantumCircuit

# qasm_str should contain OpenQASM 2 instructions
qasm_str = open("circuit.qasm", "r", encoding="utf-8").read()
qc = QuantumCircuit.from_qasm_str(qasm_str)

Or using the qasm2 helper class:

from QuantumRingsLib import qasm2

qasm_str = open("circuit.qasm", "r", encoding="utf-8").read()

qa = qasm2()
qc = qa.loads(qasm_str)

After importing

After the circuit is composed, you can further modify it before execution. For example, the legacy Sycamore workflow imports a circuit and then adds measurement:

qc.measure_all()

For execution, see Circuits and Run Settings.

Direct execution

Pass the file path as the first argument:

from QuantumRingsLib import QuantumRingsProvider, job_monitor

provider = QuantumRingsProvider(token=my_token, name=my_name)
backend = provider.get_backend(backend="amber_quantum_rings")

circuit_name = r"C:\\path\\to\\circuit.qasm"
job = backend.run(circuit_name, mode="sync", shots=1000)
job_monitor(job, quiet=True)
result = job.result()
counts = result.get_counts()
print(counts)

Note

BackendV2.run does not return a QuantumCircuit object. If you need to inspect or modify the circuit before execution, use the import path instead.

Exporting OpenQASM 2

You can generate equivalent OpenQASM 2 code from a QuantumCircuit using qc.qasm(...). This method can print formatted output and/or save it to a file.

Common errors

  • RuntimeError can be raised if there is a problem with the instructions contained in the OpenQASM 2 file or string.

See also