OpenQASM 3
qiskit.qasm3
Qiskit provides some tools for converting between OpenQASM 3 representations of quantum programs, and the QuantumCircuit
class. These will continue to evolve as Qiskit’s support for the dynamic-circuit capabilities expressed by OpenQASM 3 increases.
Exporting to OpenQASM 3
The high-level functions are simply dump()
and dumps()
, which respectively export to a file (given as a filename) and to a Python string.
dump
qiskit.qasm3.dump(circuit, stream, **kwargs)
Serialize a QuantumCircuit
object as an OpenQASM 3 stream to file-like object.
Parameters
- circuit (QuantumCircuit) – Circuit to serialize.
- stream (TextIOBase) – stream-like object to dump the OpenQASM 3 serialization
- **kwargs – Arguments for the
Exporter
constructor.
dumps
qiskit.qasm3.dumps(circuit, **kwargs)
Serialize a QuantumCircuit
object in an OpenQASM 3 string.
Parameters
- circuit (QuantumCircuit) – Circuit to serialize.
- **kwargs – Arguments for the
Exporter
constructor.
Returns
The OpenQASM 3 serialization
Return type
Both of these exporter functions are single-use wrappers around the main Exporter
class. For more complex exporting needs, including dumping multiple circuits in a single session, it may be more convenient or faster to use the complete interface.
Exporter
class qiskit.qasm3.Exporter(includes=('stdgates.inc', ), basis_gates=('U', ), disable_constants=False, alias_classical_registers=None, allow_aliasing=None, indent=' ', experimental=ExperimentalFeatures.None)
QASM3 exporter main class.
Parameters
-
includes (Sequence[str]) – the filenames that should be emitted as includes. These files will be parsed for gates, and any objects dumped from this exporter will use those definitions where possible.
-
basis_gates (Sequence[str]) – the basic defined gate set of the backend.
-
disable_constants (bool) – if
True
, always emit floating-point constants for numeric parameter values. IfFalse
(the default), then values close to multiples of OpenQASM 3 constants (pi
,euler
, andtau
) will be emitted in terms of those constants instead, potentially improving accuracy in the output. -
alias_classical_registers (bool) –
If
True
, then bits may be contained in more than one register. If so, the registers will be emitted using “alias” definitions, which might not be well supported by consumers of OpenQASM 3.See alsoParameter
allow_aliasing
A value for
allow_aliasing
overrides any value given here, and supersedes this parameter. -
allow_aliasing (bool) –
If
True
, then bits may be contained in more than one register. If so, the registers will be emitted using “alias” definitions, which might not be well supported by consumers of OpenQASM 3. Defaults toFalse
or the value ofalias_classical_registers
.New in version 0.25.0.
-
indent (str) – the indentation string to use for each level within an indented block. Can be set to the empty string to disable indentation.
-
experimental (ExperimentalFeatures) – any experimental features to enable during the export. See
ExperimentalFeatures
for more details.
dump
dump(circuit, stream)
Convert the circuit to OpenQASM 3, dumping the result to a file or text stream.
dumps
dumps(circuit)
Convert the circuit to OpenQASM 3, returning the result as a string.
All of these interfaces will raise QASM3ExporterError
on failure.
QASM3ExporterError
exception qiskit.qasm3.QASM3ExporterError(*message)
An error raised during running the OpenQASM 3 exporter.
Set the error message.
Experimental features
The OpenQASM 3 language is still evolving as hardware capabilities improve, so there is no final syntax that Qiskit can reliably target. In order to represent the evolving language, we will sometimes release features before formal standardization, which may need to change as the review process in the OpenQASM 3 design committees progresses. By default, the exporters will only support standardised features of the language. To enable these early-release features, use the experimental
keyword argument of dump()
and dumps()
. The available feature flags are:
ExperimentalFeatures
class qiskit.qasm3.ExperimentalFeatures(value)
Flags for experimental features that the OpenQASM 3 exporter supports.
These are experimental and are more liable to change, because the OpenQASM 3 specification has not formally accepted them yet, so the syntax may not be finalized.
SWITCH_CASE_V1
Default value: 1
Support exporting switch-case statements as proposed by https://github.com/openqasm/openqasm/pull/463 at commit bfa787aa3078.
If you want to enable multiple experimental features, you should combine the flags using the |
operator, such as flag1 | flag2
.
For example, to perform an export using the early semantics of switch
support:
from qiskit import qasm3, QuantumCircuit, QuantumRegister, ClassicalRegister
# Build the circuit
qreg = QuantumRegister(3)
creg = ClassicalRegister(3)
qc = QuantumCircuit(qreg, creg)
with qc.switch(creg) as case:
with case(0):
qc.x(0)
with case(1, 2):
qc.x(1)
with case(case.DEFAULT):
qc.x(2)
# Export to an OpenQASM 3 string.
qasm_string = qasm3.dumps(qc, experimental=qasm3.ExperimentalFeatures.SWITCH_CASE_V1)
All features enabled by the experimental flags are naturally transient. If it becomes necessary to remove flags, they will be subject to the standard Qiskit deprecation policy. We will leave these experimental flags in place for as long as is reasonable.
However, we cannot guarantee any support windows for consumers of OpenQASM 3 code generated using these experimental flags, if the OpenQASM 3 language specification changes the proposal that the flag is based on. It is possible that any tool you are using to consume OpenQASM 3 code created using these flags may update or remove their support while Qiskit continues to offer the flag. You should not rely on the resultant experimental OpenQASM 3 code for long-term storage of programs.
Importing from OpenQASM 3
Currently only two high-level functions are offered, as Qiskit support for importing from OpenQASM 3 is in its infancy, and the implementation is expected to change significantly. The two functions are load()
and loads()
, which are direct counterparts of dump()
and dumps()
, respectively loading a program indirectly from a named file and directly from a given string.
While we are still in the exploratory release period, to use either function, the package qiskit_qasm3_import
must be installed. This can be done by installing Qiskit Terra with the qasm3-import
extra, such as by:
pip install qiskit-terra[qasm3-import]
We expect that this functionality will eventually be merged into core Terra, and no longer require an optional import, but we do not yet have a timeline for this.
load
qiskit.qasm3.load(filename)
Load an OpenQASM 3 program from the file filename
.
Parameters
filename (str) – the filename to load the program from.
Returns
a circuit representation of the OpenQASM 3 program.
Return type
Raises
QASM3ImporterError – if the OpenQASM 3 file is invalid, or cannot be represented by a QuantumCircuit
.
loads
qiskit.qasm3.loads(program)
Load an OpenQASM 3 program from the given string.
Parameters
program (str) – the OpenQASM 3 program.
Returns
a circuit representation of the OpenQASM 3 program.
Return type
Raises
QASM3ImporterError – if the OpenQASM 3 file is invalid, or cannot be represented by a QuantumCircuit
.
Both of these two functions raise QASM3ImporterError
on failure.
QASM3ImporterError
exception qiskit.qasm3.QASM3ImporterError(*message)
An error raised during the OpenQASM 3 importer.
Set the error message.
For example, we can define a quantum program using OpenQASM 3, and use loads()
to directly convert it into a QuantumCircuit
:
import qiskit.qasm3
program = """
OPENQASM 3.0;
include "stdgates.inc";
input float[64] a;
qubit[3] q;
bit[2] mid;
bit[3] out;
let aliased = q[0:1];
gate my_gate(a) c, t {
gphase(a / 2);
ry(a) c;
cx c, t;
}
gate my_phase(a) c {
ctrl @ inv @ gphase(a) c;
}
my_gate(a * 2) aliased[0], q[{1, 2}][0];
measure q[0] -> mid[0];
measure q[1] -> mid[1];
while (mid == "00") {
reset q[0];
reset q[1];
my_gate(a) q[0], q[1];
my_phase(a - pi/2) q[1];
mid[0] = measure q[0];
mid[1] = measure q[1];
}
if (mid[0]) {
let inner_alias = q[{0, 1}];
reset inner_alias;
}
out = measure q;
"""
circuit = qiskit.qasm3.loads(program)
circuit.draw("mpl")