Skip to content

Commit

Permalink
Fix code examples (#13178)
Browse files Browse the repository at this point in the history
* Fix code examples

* Incorporate feedback

Co-authored-by: Jake Lishman <jake.lishman@ibm.com>

---------

Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
  • Loading branch information
frankharkins and jakelishman authored Sep 18, 2024
1 parent f091cf2 commit cc1f30f
Show file tree
Hide file tree
Showing 14 changed files with 68 additions and 36 deletions.
1 change: 1 addition & 0 deletions qiskit/circuit/library/pauli_evolution.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ class PauliEvolutionGate(Gate):
X = SparsePauliOp("X")
Z = SparsePauliOp("Z")
I = SparsePauliOp("I")
# build the evolution gate
operator = (Z ^ Z) - 0.1 * (X ^ I)
Expand Down
4 changes: 2 additions & 2 deletions qiskit/primitives/base/base_estimator.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ class BaseEstimatorV1(BasePrimitive, Generic[T]):
# calculate [ <psi1(theta1)|H1|psi1(theta1)> ]
job = estimator.run([psi1], [H1], [theta1])
job_result = job.result() # It will block until the job finishes.
print(f"The primitive-job finished with result {job_result}"))
print(f"The primitive-job finished with result {job_result}")
# calculate [ <psi1(theta1)|H1|psi1(theta1)>,
# <psi2(theta2)|H2|psi2(theta2)>,
Expand Down Expand Up @@ -144,7 +144,7 @@ def run(
.. code-block:: python
values = parameter_values[i].
values = parameter_values[i]
Args:
circuits: one or more circuit objects.
Expand Down
10 changes: 9 additions & 1 deletion qiskit/primitives/containers/data_bin.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,14 +34,22 @@ class DataBin(ShapedMixin):
.. code-block:: python
import numpy as np
from qiskit.primitives import DataBin, BitArray
data = DataBin(
alpha=BitArray.from_bitstrings(["0010"]),
alpha=BitArray.from_samples(["0010"]),
beta=np.array([1.2])
)
print("alpha data:", data.alpha)
print("beta data:", data.beta)
.. code-block::
alpha data: BitArray(<shape=(), num_shots=1, num_bits=2>)
beta data: [1.2]
"""

__slots__ = ("_data", "_shape")
Expand Down
23 changes: 16 additions & 7 deletions qiskit/pulse/builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,6 @@
from qiskit.compiler import schedule
from qiskit import pulse, QuantumCircuit
from qiskit.pulse import library
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
Expand All @@ -147,7 +146,7 @@
with pulse.build(backend) as pulse_prog:
# Create a pulse.
gaussian_pulse = library.gaussian(10, 1.0, 2)
gaussian_pulse = pulse.Gaussian(10, 1.0, 2)
# Get the qubit's corresponding drive channel from the backend.
d0 = pulse.drive_channel(0)
d1 = pulse.drive_channel(1)
Expand Down Expand Up @@ -285,16 +284,16 @@
d0 = pulse.drive_channel(0)
a0 = pulse.acquire_channel(0)
pulse.play(pulse.library.Constant(10, 1.0), d0)
pulse.play(pulse.Constant(10, 1.0), d0)
pulse.delay(20, d0)
pulse.shift_phase(3.14/2, d0)
pulse.set_phase(3.14, d0)
pulse.shift_frequency(1e7, d0)
pulse.set_frequency(5e9, d0)
with pulse.build() as temp_sched:
pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), d0)
pulse.play(pulse.library.Gaussian(20, -1.0, 3.0), d0)
pulse.play(pulse.Gaussian(20, 1.0, 3.0), d0)
pulse.play(pulse.Gaussian(20, -1.0, 3.0), d0)
pulse.call(temp_sched)
pulse.acquire(30, a0, pulse.MemorySlot(0))
Expand Down Expand Up @@ -1327,7 +1326,9 @@ def frequency_offset(
:emphasize-lines: 7, 16
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
d0 = pulse.DriveChannel(0)
with pulse.build(backend) as pulse_prog:
Expand Down Expand Up @@ -1969,19 +1970,23 @@ def barrier(*channels_or_qubits: chans.Channel | int, name: str | None = None):
.. code-block::
import math
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
d0 = pulse.DriveChannel(0)
with pulse.build(backend) as pulse_prog:
with pulse.align_right():
pulse.call(backend.defaults.instruction_schedule_map.get('x', (1,)))
pulse.call(backend.defaults().instruction_schedule_map.get('u1', (1,)))
# Barrier qubit 1 and d0.
pulse.barrier(1, d0)
# Due to barrier this will play before the gate on qubit 1.
pulse.play(pulse.Constant(10, 1.0), d0)
# This will end at the same time as the pulse above due to
# the barrier.
pulse.call(backend.defaults.instruction_schedule_map.get('x', (1,)))
pulse.call(backend.defaults().instruction_schedule_map.get('u1', (1,)))
.. note:: Requires the active builder context to have a backend set if
qubits are barriered on.
Expand Down Expand Up @@ -2012,6 +2017,7 @@ def macro(func: Callable):
:include-source:
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
@pulse.macro
def measure(qubit: int):
Expand All @@ -2021,6 +2027,9 @@ def measure(qubit: int):
return mem_slot
backend = FakeOpenPulse2Q()
with pulse.build(backend=backend) as sched:
mem_slot = measure(0)
print(f"Qubit measured into {mem_slot}")
Expand Down
5 changes: 5 additions & 0 deletions qiskit/pulse/instructions/directives.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,13 +72,18 @@ class TimeBlockade(Directive):
.. code-block:: python
from qiskit.pulse import Schedule, Play, Constant, DriveChannel
schedule = Schedule()
schedule.insert(120, Play(Constant(10, 0.1), DriveChannel(0)))
This schedule block is expected to be identical to above at a time of execution.
.. code-block:: python
from qiskit.pulse import ScheduleBlock, Play, Constant, DriveChannel
from qiskit.pulse.instructions import TimeBlockade
block = ScheduleBlock()
block.append(TimeBlockade(120, DriveChannel(0)))
block.append(Play(Constant(10, 0.1), DriveChannel(0)))
Expand Down
14 changes: 5 additions & 9 deletions qiskit/pulse/schedule.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ class Schedule:
.. code-block:: python
from qiskit.pulse import Schedule, Gaussian, DriveChannel, Play
sched = Schedule()
sched += Play(Gaussian(160, 0.1, 40), DriveChannel(0))
Expand Down Expand Up @@ -653,8 +654,6 @@ def replace(
sched += pulse.Schedule(old)
sched = sched.flatten()
sched = sched.replace(old, new)
assert sched == pulse.Schedule(new)
Expand Down Expand Up @@ -899,11 +898,8 @@ class ScheduleBlock:
pulse.reference("grand_child")
pulse.play(pulse.Constant(200, amp2), pulse.DriveChannel(0))
Now you assign the inner pulse program to this reference.
.. code-block::
sched_outer.assign_references({("grand_child", ): sched_inner})
# Now assign the inner pulse program to this reference
sched_outer.assign_references({("grand_child",): sched_inner})
print(sched_outer.parameters)
.. parsed-literal::
Expand Down Expand Up @@ -1459,7 +1455,7 @@ def assign_references(
from qiskit import pulse
with pulse.build() as subroutine:
with pulse.build() as nested_prog:
pulse.delay(10, pulse.DriveChannel(0))
with pulse.build() as sub_prog:
Expand Down Expand Up @@ -1490,7 +1486,7 @@ def assign_references(
.. code-block:: python
main_prog.assign_references({("B", ): sub_prog}, inplace=True)
main_prog.references[("B", )].assign_references({"A": nested_prog}, inplace=True)
main_prog.references[("B", )].assign_references({("A", ): nested_prog}, inplace=True)
Here :attr:`.references` returns a dict-like object, and you can
mutably update the nested reference of the particular subroutine.
Expand Down
4 changes: 3 additions & 1 deletion qiskit/pulse/transforms/alignments.py
Original file line number Diff line number Diff line change
Expand Up @@ -338,8 +338,10 @@ class AlignFunc(AlignmentKind):
.. code-block:: python
import numpy as np
def udd10_pos(j):
return np.sin(np.pi*j/(2*10 + 2))**2
return np.sin(np.pi*j/(2*10 + 2))**2
.. note::
Expand Down
7 changes: 7 additions & 0 deletions qiskit/pulse/transforms/dag.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,11 @@ def block_to_dag(block: ScheduleBlock) -> rx.PyDAG:
.. code-block:: python
from qiskit import pulse
my_gaussian0 = pulse.Gaussian(100, 0.5, 20)
my_gaussian1 = pulse.Gaussian(100, 0.3, 10)
with pulse.build() as sched1:
with pulse.align_left():
pulse.play(my_gaussian0, pulse.DriveChannel(0))
Expand All @@ -51,6 +56,8 @@ def block_to_dag(block: ScheduleBlock) -> rx.PyDAG:
.. code-block:: python
from qiskit import pulse
with pulse.build() as sched:
with pulse.align_left():
pulse.shift_phase(1.57, pulse.DriveChannel(1))
Expand Down
2 changes: 2 additions & 0 deletions qiskit/quantum_info/operators/symplectic/pauli.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,8 @@ class initialization (``Pauli('-iXYZ')``). A ``Pauli`` object can be
.. code-block:: python
from qiskit.quantum_info import Pauli
P = Pauli('-iXYZ')
print('P[0] =', repr(P[0]))
Expand Down
5 changes: 5 additions & 0 deletions qiskit/quantum_info/operators/symplectic/sparse_pauli_op.py
Original file line number Diff line number Diff line change
Expand Up @@ -794,6 +794,8 @@ def from_list(
.. code-block:: python
from qiskit.quantum_info import SparsePauliOp
# via tuples and the full Pauli string
op = SparsePauliOp.from_list([("XIIZI", 1), ("IYIIY", 2)])
Expand Down Expand Up @@ -858,6 +860,8 @@ def from_sparse_list(
.. code-block:: python
from qiskit.quantum_info import SparsePauliOp
# via triples and local Paulis with indices
op = SparsePauliOp.from_sparse_list([("ZX", [1, 4], 1), ("YY", [0, 3], 2)], num_qubits=5)
Expand Down Expand Up @@ -1053,6 +1057,7 @@ def group_commuting(self, qubit_wise: bool = False) -> list[SparsePauliOp]:
.. code-block:: python
>>> from qiskit.quantum_info import SparsePauliOp
>>> op = SparsePauliOp.from_list([("XX", 2), ("YY", 1), ("IZ",2j), ("ZZ",1j)])
>>> op.group_commuting()
[SparsePauliOp(["IZ", "ZZ"], coeffs=[0.+2.j, 0.+1j]),
Expand Down
7 changes: 6 additions & 1 deletion qiskit/transpiler/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,15 +106,17 @@
.. code-block:: python
import numpy as np
from qiskit.providers.fake_provider import GenericBackendV2
from qiskit.circuit.library import HGate, PhaseGate, RXGate, TdgGate, TGate, XGate
from qiskit.transpiler import PassManager
from qiskit.transpiler import PassManager, generate_preset_pass_manager
from qiskit.transpiler.passes import (
ALAPScheduleAnalysis,
CXCancellation,
InverseCancellation,
PadDynamicalDecoupling,
)
backend = GenericBackendV2(num_qubits=5)
dd_sequence = [XGate(), XGate()]
scheduling_pm = PassManager(
[
Expand All @@ -135,6 +137,9 @@
]
)
pass_manager = generate_preset_pass_manager(
optimization_level=0
)
# Add pre-layout stage to run extra logical optimization
pass_manager.pre_layout = logical_opt
Expand Down
2 changes: 1 addition & 1 deletion qiskit/transpiler/passes/calibration/rx_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ class RXCalibrationBuilder(CalibrationBuilder):
from qiskit.circuit.library import QuantumVolume
from qiskit.circuit.library.standard_gates import RXGate
from calibration.rx_builder import RXCalibrationBuilder
from qiskit.transpiler.passes import RXCalibrationBuilder
qv = QuantumVolume(4, 4, seed=1004)
Expand Down
3 changes: 3 additions & 0 deletions qiskit/transpiler/passes/scheduling/padding/pad_delay.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@ class PadDelay(BasePadding):
.. code-block:: python
from qiskit import QuantumCircuit
from qiskit.transpiler import InstructionDurations
durations = InstructionDurations([("x", None, 160), ("cx", None, 800)])
qc = QuantumCircuit(2)
Expand Down
17 changes: 3 additions & 14 deletions qiskit/visualization/pass_manager_visualization.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,23 +58,12 @@ def pass_manager_drawer(pass_manager, filename=None, style=None, raw=False):
Example:
.. code-block::
%matplotlib inline
from qiskit import QuantumCircuit
from qiskit.compiler import transpile
from qiskit.transpiler import PassManager
from qiskit.transpiler import generate_preset_pass_manager
from qiskit.visualization import pass_manager_drawer
from qiskit.transpiler.passes import Unroller
circ = QuantumCircuit(3)
circ.ccx(0, 1, 2)
circ.draw()
pass_ = Unroller(['u1', 'u2', 'u3', 'cx'])
pm = PassManager(pass_)
new_circ = pm.run(circ)
new_circ.draw(output='mpl')
pass_manager_drawer(pm, "passmanager.jpg")
pm = generate_preset_pass_manager(optimization_level=0)
pass_manager_drawer(pm)
"""
import pydot

Expand Down

0 comments on commit cc1f30f

Please sign in to comment.