From 87b2872b6d4320022f7addd738ed16dcb5829b34 Mon Sep 17 00:00:00 2001 From: Jake Lishman Date: Tue, 17 Sep 2024 15:04:59 +0100 Subject: [PATCH] Add example of `qasm2.CustomInstruction` We didn't have an explicit usage example of this in the documentation before, and several people seem to have been confused by it. --- qiskit/qasm2/parse.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/qiskit/qasm2/parse.py b/qiskit/qasm2/parse.py index a40270a99b8c..6cdb0f70bba0 100644 --- a/qiskit/qasm2/parse.py +++ b/qiskit/qasm2/parse.py @@ -89,6 +89,35 @@ class CustomInstruction: There is a final ``builtin`` field. This is optional, and if set true will cause the instruction to be defined and available within the parsing, even if there is no definition in any included OpenQASM 2 file. + + Examples: + + Instruct the importer to use Qiskit's :class:`.ECRGate` and :class:`.RZXGate` objects to + interpret ``gate`` statements that are known to have been created from those same objects + during OpenQASM 2 export:: + + from qiskit import qasm2 + from qiskit.circuit import QuantumCircuit, library + + qc = QuantumCircuit(2) + qc.ecr(0, 1) + qc.rzx(0.3, 0, 1) + qc.rzx(0.7, 1, 0) + qc.rzx(1.5, 0, 1) + qc.ecr(1, 0) + + # This output string includes `gate ecr q0, q1 { ... }` and `gate rzx(p) q0, q1 { ... }` + # statements, since `ecr` and `rzx` are neither built-in gates nor in ``qelib1.inc``. + dumped = qasm2.dumps(qc) + + # Tell the importer how to interpret the `gate` statements, which we know are safe + # because we controlled the input OpenQASM 2 source. + custom = [ + qasm2.CustomInstruction("ecr", 0, 2, library.ECRGate), + qasm2.CustomInstruction("rzx", 1, 2, library.RZXGate), + ] + + loaded = qasm2.loads(dumped, custom_instructions=custom) """ name: str