Tutorial: Custom Pulse Annotations and OpenQASM 3 Export¶
This tutorial covers:
Creating custom
PulseEnvelopeAnnotationfor specific gatesAttaching annotations to
BoxOpblocksOverriding default pulse shapes (DRAG, GaussianSquare parameters)
Exporting to OpenQASM 3 with serialized pulse pragmas
Round-trip serialization via QPY
[1]:
import io
import numpy as np
import qiskit.qpy as qpy
from qiskit import QuantumCircuit, qasm3
from qiskit.providers.fake_provider import GenericBackendV2
from qiskit.transpiler import generate_preset_pass_manager
from qiskit_waveform_sim import (
PulseAnnotationSerializer,
PulseEnvelopeAnnotation,
TargetWaveformSimulator,
)
1. Understanding PulseEnvelopeAnnotation¶
[2]:
# Create annotations with different pulse shapes
# Default DRAG (used for sx, x, rx)
drag_default = PulseEnvelopeAnnotation()
print(f"Default DRAG: {drag_default}")
# Custom high-beta DRAG for leakage suppression
drag_high_beta = PulseEnvelopeAnnotation(
shape="drag",
amp=0.55, # Peak amplitude
beta=0.25, # DRAG beta (leakage suppression)
sigma_ratio=0.2, # σ as fraction of duration
risefall_dt=16, # Not used for DRAG
)
print(f"High-beta DRAG: {drag_high_beta}")
# GaussianSquare for flat-top pulses (CR, measure)
gs_custom = PulseEnvelopeAnnotation(
shape="gaussian_square",
amp=0.7,
beta=0.0, # Not used for GS
sigma_ratio=0.0, # Not used for GS
risefall_dt=24, # Rise/fall in dt
)
print(f"GaussianSquare: {gs_custom}")
Default DRAG: PulseEnvelopeAnnotation(shape='drag', amp=0.5, beta=0.08, sigma_ratio=0.25, risefall_dt=16)
High-beta DRAG: PulseEnvelopeAnnotation(shape='drag', amp=0.55, beta=0.25, sigma_ratio=0.2, risefall_dt=16)
GaussianSquare: PulseEnvelopeAnnotation(shape='gaussian_square', amp=0.7, beta=0.0, sigma_ratio=0.0, risefall_dt=24)
2. Attaching Annotations to BoxOp¶
[3]:
backend = GenericBackendV2(num_qubits=2, seed=42)
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.cx(0, 1)
# Override the SX gate inside this box with a custom pulse
with qc.box(duration=160, unit="dt", annotations=[drag_high_beta]):
qc.sx(0)
qc.measure([0, 1], [0, 1])
# Verify the annotation is attached (instruction 2 is the box: h, cx, box)
box_op = qc.data[2].operation
print(f"BoxOp annotations: {box_op.annotations}")
print(f"BoxOp duration: {box_op.duration} {box_op.unit}")
BoxOp annotations: [PulseEnvelopeAnnotation(shape='drag', amp=0.55, beta=0.25, sigma_ratio=0.2, risefall_dt=16)]
BoxOp duration: 160 dt
3. Simulate the Custom Pulse¶
Qiskit’s preset scheduling passes reject circuits that contain boxes, so a boxed circuit cannot go through generate_preset_pass_manager(..., scheduling_method="alap"). TargetWaveformSimulator.compile() only needs start times, though: for a small example we can pass them by hand with compile(..., start_times=[...]): one non-negative integer start time (in dt) per top-level instruction, in circuit order.
A box with a fixed duration around a single gate sets that gate’s pulse duration, so σ = 160 dt × 0.2 = 32 dt.
[4]:
demo = QuantumCircuit(1)
with demo.box(duration=160, unit="dt", annotations=[drag_high_beta]):
demo.sx(0)
# hand-scheduled: the box starts at t = 0
sim = TargetWaveformSimulator(backend.target).compile(demo, start_times=[0])
for e in sim.events_by_channel["d0"]:
print(
f"{e.op_name}: start={e.start_dt} dt, duration={e.duration_dt} dt, "
f"amp={abs(e.amp):.3f}, beta={e.beta:.3f}, sigma={e.sigma_dt:.1f} dt"
)
sx: start=0 dt, duration=160 dt, amp=0.550, beta=0.250, sigma=32.0 dt
4. Multiple Annotations and Fractional Gates¶
[5]:
# You can attach different annotations to different boxes
qc2 = QuantumCircuit(2, 2)
qc2.h(0)
# Box 1: custom DRAG for RX(pi/4)
with qc2.box(
duration=120,
unit="dt",
annotations=[PulseEnvelopeAnnotation(shape="drag", amp=0.4, beta=0.15, sigma_ratio=0.25)],
):
qc2.rx(np.pi / 4, 0)
# Box 2: custom GaussianSquare for the RZZ cross-resonance pulses
with qc2.box(
duration=300,
unit="dt",
annotations=[PulseEnvelopeAnnotation(shape="gaussian_square", amp=0.8, risefall_dt=30)],
):
qc2.rzz(np.pi / 2, 0, 1)
qc2.measure([0, 1], [0, 1])
for inst in qc2.data:
annotations = getattr(inst.operation, "annotations", None)
if annotations:
print(f"{inst.operation.name} on {[qc2.find_bit(q).index for q in inst.qubits]}: {annotations[0]}")
box on [0]: PulseEnvelopeAnnotation(shape='drag', amp=0.4, beta=0.15, sigma_ratio=0.25, risefall_dt=16)
box on [0, 1]: PulseEnvelopeAnnotation(shape='gaussian_square', amp=0.8, beta=0.08, sigma_ratio=0.25, risefall_dt=30)
5. Export to OpenQASM 3 with Pulse Pragmas¶
[6]:
# Export with custom annotation serializer
qasm3_str = qasm3.dumps(
qc2,
annotation_handlers={"pulse_sim.envelope": PulseAnnotationSerializer()}
)
print(qasm3_str[:2000])
OPENQASM 3.0;
include "stdgates.inc";
gate rzz(p0) _gate_q_0, _gate_q_1 {
cx _gate_q_0, _gate_q_1;
rz(p0) _gate_q_1;
cx _gate_q_0, _gate_q_1;
}
bit[2] c;
qubit[2] q;
h q[0];
@pulse_sim.envelope {'shape': 'drag', 'amp': 0.4, 'beta': 0.15, 'sigma_ratio': 0.25, 'risefall_dt': 16}
box[120dt] {
rx(pi/4) q[0];
}
@pulse_sim.envelope {'shape': 'gaussian_square', 'amp': 0.8, 'beta': 0.08, 'sigma_ratio': 0.25, 'risefall_dt': 30}
box[300dt] {
rzz(pi/2) q[0], q[1];
}
c[0] = measure q[0];
c[1] = measure q[1];
6. QPY Round-trip Serialization¶
[7]:
# Serialize to QPY binary format
buf = io.BytesIO()
qpy.dump(qc2, buf, annotation_factories={"pulse_sim.envelope": PulseAnnotationSerializer().as_qpy()})
# Deserialize
buf.seek(0)
loaded_qc = qpy.load(buf, annotation_factories={"pulse_sim.envelope": PulseAnnotationSerializer().as_qpy()})[0]
# Verify annotations survived round-trip
for inst in loaded_qc.data:
op = inst.operation
if hasattr(op, 'annotations') and op.annotations:
for ann in op.annotations:
if isinstance(ann, PulseEnvelopeAnnotation):
print(f"Restored annotation: {ann}")
Restored annotation: PulseEnvelopeAnnotation(shape='drag', amp=0.4, beta=0.15, sigma_ratio=0.25, risefall_dt=16)
Restored annotation: PulseEnvelopeAnnotation(shape='gaussian_square', amp=0.8, beta=0.08, sigma_ratio=0.25, risefall_dt=30)
7. Export to Hardware Formats (LabOne Q, RFSoC/QICK)¶
[ ]:
# Extract waveforms for hardware upload
# This is a simplified example - real hardware needs specific formats
# Get full circuit duration
total_dt = sim.total_duration_dt
# Extract all channels (ideal=True: uploads must never contain simulated impairments)
waveforms = {}
for ch in sim.get_channels():
snip = sim.get_snippet(ch, start_dt=0, length_dt=total_dt, ideal=True)
waveforms[ch] = {
"time_ns": snip.time_ns,
"I": snip.wave.real,
"Q": snip.wave.imag,
"phase": snip.phase_rad,
"dt": snip.dt_sec,
}
print(f"{ch}: {len(snip.wave)} samples")
# For LabOne Q: convert to their waveform format
# For RFSoC/QICK: convert to their DAC format (int16, etc.)
# See the hardware_export tutorial for complete examples
Summary¶
Custom pulses: override a gate’s pulse shape via
BoxOp+PulseEnvelopeAnnotationParametric control: amplitude, beta, sigma and rise/fall are configurable and validated
OpenQASM 3 export: annotations serialize as
@pulse_sim.envelope {...}pragmasQPY support: binary round-trip with annotations preserved
Simulation: applied by
compile()when you passstart_times=[...](Qiskit’s preset scheduler does not yet accept boxes)
Next: see the hardware_export tutorial for exporting waveforms.