Skip to content

QASM Conversion ​

API reference for functions that convert between quantum programs (QProg) and the OpenQASM 2.0 intermediate representation format.

convert_qasm_string_to_qprog ​

Parses an OpenQASM 2.0 instruction-set string and returns the corresponding quantum program.

Signature ​

python
convert_qasm_string_to_qprog(
    qasm_str: str,
) -> QProg

Parameters ​

ParameterTypeDescription
qasm_strstrAn OpenQASM 2.0 instruction-set string to be converted.

Returns ​

The converted QProg quantum program.

Raises ​

ExceptionDescription
RuntimeErrorIf the QASM string contains syntax errors or references undefined gates or qubits.

Examples ​

python
from pyqpanda3.intermediate_compiler import convert_qasm_string_to_qprog

qasm_str = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[2];
creg c[2];
h q[0];
cx q[0],q[1];
measure q[0] -> c[0];
measure q[1] -> c[1];
"""
prog = convert_qasm_string_to_qprog(qasm_str)

convert_qasm_file_to_qprog ​

Reads an OpenQASM 2.0 file and returns the corresponding quantum program.

Signature ​

python
convert_qasm_file_to_qprog(
    qasm_filepath: str,
) -> QProg

Parameters ​

ParameterTypeDescription
qasm_filepathstrPath to a file containing OpenQASM 2.0 instruction-set text.

Returns ​

The converted QProg quantum program.

Raises ​

ExceptionDescription
RuntimeErrorIf the file cannot be read or contains syntax errors.
FileNotFoundErrorIf the specified file path does not exist.

Examples ​

python
import tempfile
from pyqpanda3.intermediate_compiler import convert_qasm_file_to_qprog

qasm = '''OPENQASM 2.0;
include "qelib1.inc";
qreg q[2];
creg c[2];
h q[0];
cx q[0],q[1];
measure q[0] -> c[0];
measure q[1] -> c[1];
'''

with tempfile.NamedTemporaryFile(mode='w', suffix='.qasm', delete=False) as f:
    f.write(qasm)
    path = f.name

prog = convert_qasm_file_to_qprog(path)  # a missing or unreadable file raises RuntimeError

convert_qprog_to_qasm ​

Converts a quantum program to an OpenQASM 2.0 string representation.

Signature ​

python
convert_qprog_to_qasm(
    prog: QProg,
    precision: int = 8,
) -> str

Parameters ​

ParameterTypeDescription
progQProgThe quantum program to convert.
precisionintNumber of decimal places for floating-point gate parameters. Must be a non-negative integer. Defaults to 8.

Returns ​

The OpenQASM 2.0 instruction-set string representing the quantum program.

Examples ​

python
from pyqpanda3.intermediate_compiler import convert_qprog_to_qasm
from pyqpanda3.core import QProg, H, CNOT

prog = QProg() << H(0) << CNOT(0, 1)
qasm_str = convert_qprog_to_qasm(prog, precision=6)
print(qasm_str)

运行结果:

OPENQASM 2.0;
include "qelib1.inc";
qreg q[2];
creg c[0];
h q[0];
cx q[0],q[1];

See Also ​

Released under the MIT License.