Skip to content

Commit

Permalink
Add example of qasm2.CustomInstruction (#13167) (#13175)
Browse files Browse the repository at this point in the history
We didn't have an explicit usage example of this in the documentation
before, and several people seem to have been confused by it.

(cherry picked from commit f091cf2)

Co-authored-by: Jake Lishman <[email protected]>
  • Loading branch information
mergify[bot] and jakelishman authored Sep 18, 2024
1 parent fd7560b commit 95921da
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions qiskit/qasm2/parse.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 95921da

Please sign in to comment.