diff --git a/docs/conf.py b/docs/conf.py index 8306d9cb8a5f..c794ec284a67 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -34,10 +34,10 @@ "sphinx.ext.viewcode", "sphinx.ext.extlinks", "sphinx.ext.intersphinx", - "jupyter_sphinx", "sphinx_autodoc_typehints", "reno.sphinxext", "sphinx_design", + "matplotlib.sphinxext.plot_directive", ] templates_path = ["_templates"] diff --git a/qiskit/algorithms/evolvers/trotterization/trotter_qrte.py b/qiskit/algorithms/evolvers/trotterization/trotter_qrte.py index e91793570d51..323305b4b8c1 100644 --- a/qiskit/algorithms/evolvers/trotterization/trotter_qrte.py +++ b/qiskit/algorithms/evolvers/trotterization/trotter_qrte.py @@ -46,9 +46,7 @@ class TrotterQRTE(RealEvolver): Type of Trotterization is defined by a ProductFormula provided. - Examples: - - .. jupyter-execute:: + Examples:: from qiskit.opflow import X, Z, Zero from qiskit.algorithms import EvolutionProblem, TrotterQRTE diff --git a/qiskit/algorithms/linear_solvers/hhl.py b/qiskit/algorithms/linear_solvers/hhl.py index 131e2bfcbdbc..92ddda7f8459 100644 --- a/qiskit/algorithms/linear_solvers/hhl.py +++ b/qiskit/algorithms/linear_solvers/hhl.py @@ -67,9 +67,7 @@ class HHL(LinearSolver): It is replaced by the tutorial at `HHL `_ - Examples: - - .. jupyter-execute:: + Examples:: import warnings import numpy as np diff --git a/qiskit/algorithms/linear_solvers/matrices/numpy_matrix.py b/qiskit/algorithms/linear_solvers/matrices/numpy_matrix.py index fdf30017c925..2ffdc54c09e5 100644 --- a/qiskit/algorithms/linear_solvers/matrices/numpy_matrix.py +++ b/qiskit/algorithms/linear_solvers/matrices/numpy_matrix.py @@ -25,9 +25,7 @@ class NumPyMatrix(LinearSystemMatrix): """The deprecated class of matrices given as a numpy array. - Examples: - - .. jupyter-execute:: + Examples:: import warnings import numpy as np diff --git a/qiskit/algorithms/linear_solvers/matrices/tridiagonal_toeplitz.py b/qiskit/algorithms/linear_solvers/matrices/tridiagonal_toeplitz.py index 6dda2716b680..325554c8fb60 100644 --- a/qiskit/algorithms/linear_solvers/matrices/tridiagonal_toeplitz.py +++ b/qiskit/algorithms/linear_solvers/matrices/tridiagonal_toeplitz.py @@ -38,9 +38,7 @@ class TridiagonalToeplitz(LinearSystemMatrix): 0 & 0 & b & a \end{pmatrix}. - Examples: - - .. jupyter-execute:: + Examples:: import warnings import numpy as np diff --git a/qiskit/algorithms/linear_solvers/numpy_linear_solver.py b/qiskit/algorithms/linear_solvers/numpy_linear_solver.py index 0a3cbbd57191..d85c0920baf5 100644 --- a/qiskit/algorithms/linear_solvers/numpy_linear_solver.py +++ b/qiskit/algorithms/linear_solvers/numpy_linear_solver.py @@ -29,9 +29,7 @@ class NumPyLinearSolver(LinearSolver): This linear system solver computes the exact value of the given observable(s) or the full solution vector if no observable is specified. - Examples: - - .. jupyter-execute:: + Examples:: import warnings import numpy as np diff --git a/qiskit/algorithms/linear_solvers/observables/absolute_average.py b/qiskit/algorithms/linear_solvers/observables/absolute_average.py index 300c31edaed9..ae0b930d944a 100644 --- a/qiskit/algorithms/linear_solvers/observables/absolute_average.py +++ b/qiskit/algorithms/linear_solvers/observables/absolute_average.py @@ -29,9 +29,7 @@ class AbsoluteAverage(LinearSystemObservable): For a vector :math:`x=(x_1,...,x_N)`, the absolute average is defined as :math:`\abs{\frac{1}{N}\sum_{i=1}^{N}x_i}`. - Examples: - - .. jupyter-execute:: + Examples:: import warnings import numpy as np diff --git a/qiskit/algorithms/linear_solvers/observables/matrix_functional.py b/qiskit/algorithms/linear_solvers/observables/matrix_functional.py index ca0cfecf16bc..0b584ba3b4af 100644 --- a/qiskit/algorithms/linear_solvers/observables/matrix_functional.py +++ b/qiskit/algorithms/linear_solvers/observables/matrix_functional.py @@ -28,9 +28,7 @@ class MatrixFunctional(LinearSystemObservable): """The deprecated class for the matrix functional of the vector solution to the linear systems. - Examples: - - .. jupyter-execute:: + Examples:: import warnings import numpy as np diff --git a/qiskit/circuit/__init__.py b/qiskit/circuit/__init__.py index dccdcf5b4572..7da3bf2d41e6 100644 --- a/qiskit/circuit/__init__.py +++ b/qiskit/circuit/__init__.py @@ -38,7 +38,8 @@ |\\psi\\rangle = \\left(|000\\rangle+|111\\rangle\\right)/\\sqrt{2} -.. jupyter-execute:: +.. plot:: + :include-source: from qiskit import QuantumCircuit # Create a circuit with a register of three qubits @@ -50,7 +51,7 @@ # CX (CNOT) gate on control qubit 0 and target qubit 2 resulting in a GHZ state. circ.cx(0, 2) # Draw the circuit - circ.draw() + circ.draw('mpl') Supplementary Information @@ -67,9 +68,10 @@ (:class:`~.HGate`), in which we expect to get :math:`|0\\rangle` and :math:`|1\\rangle` with equal probability. - .. jupyter-execute:: + .. plot:: + :include-source: - from qiskit import BasicAer, transpile, QuantumRegister, ClassicalRegister + from qiskit import BasicAer, transpile, QuantumRegister, ClassicalRegister, QuantumCircuit qr = QuantumRegister(1) cr = ClassicalRegister(1) @@ -78,7 +80,7 @@ qc.measure(0, 0) qc.draw('mpl') - .. jupyter-execute:: + .. code-block:: backend = BasicAer.get_backend('qasm_simulator') tqc = transpile(qc, backend) @@ -86,25 +88,42 @@ print(counts) + .. parsed-literal:: + + {'0': 524, '1': 500} + Now, we add an :class:`~.XGate` only if the value of the :class:`~.ClassicalRegister` is 0. That way, if the state is :math:`|0\\rangle`, it will be changed to :math:`|1\\rangle` and if the state is :math:`|1\\rangle`, it will not be changed at all, so the final state will always be :math:`|1\\rangle`. - .. jupyter-execute:: + .. plot:: + :include-source: + + from qiskit import BasicAer, transpile, QuantumRegister, ClassicalRegister, QuantumCircuit + + qr = QuantumRegister(1) + cr = ClassicalRegister(1) + qc = QuantumCircuit(qr, cr) + qc.h(0) + qc.measure(0, 0) qc.x(0).c_if(cr, 0) qc.measure(0, 0) qc.draw('mpl') - .. jupyter-execute:: + .. code-block:: + backend = BasicAer.get_backend('qasm_simulator') tqc = transpile(qc, backend) counts = backend.run(tqc).result().get_counts() print(counts) + .. parsed-literal:: + + {'1': 1024} .. dropdown:: Quantum Circuit Properties :animate: fade-in-slide-down @@ -118,7 +137,8 @@ Consider the following circuit: - .. jupyter-execute:: + .. plot:: + :include-source: from qiskit import QuantumCircuit qc = QuantumCircuit(12) @@ -135,24 +155,30 @@ qc.swap(6, 9) qc.swap(6, 10) qc.x(6) - qc.draw() + qc.draw('mpl') From the plot, it is easy to see that this circuit has 12 qubits, and a collection of Hadamard, CNOT, X, and SWAP gates. But how to quantify this programmatically? Because we can do single-qubit gates on all the qubits simultaneously, the number of qubits in this circuit is equal to the **width** of the circuit: - .. jupyter-execute:: + .. code-block:: qc.width() + .. parsed-literal:: + + 12 We can also just get the number of qubits directly: - .. jupyter-execute:: + .. code-block:: qc.num_qubits + .. parsed-literal:: + + 12 .. important:: @@ -166,18 +192,24 @@ It is also straightforward to get the number and type of the gates in a circuit using :meth:`QuantumCircuit.count_ops`: - .. jupyter-execute:: + .. code-block:: qc.count_ops() + .. parsed-literal:: + + OrderedDict([('cx', 8), ('h', 5), ('x', 3), ('swap', 3)]) We can also get just the raw count of operations by computing the circuits :meth:`QuantumCircuit.size`: - .. jupyter-execute:: + .. code-block:: qc.size() + .. parsed-literal:: + + 19 A particularly important circuit property is known as the circuit **depth**. The depth of a quantum circuit is a measure of how many "layers" of quantum gates, executed in @@ -202,10 +234,13 @@ We can verify our graphical result using :meth:`QuantumCircuit.depth`: - .. jupyter-execute:: + .. code-block:: qc.depth() + .. parsed-literal:: + + 9 .. raw:: html diff --git a/qiskit/circuit/classicalfunction/__init__.py b/qiskit/circuit/classicalfunction/__init__.py index 04a8a7ffe16d..4a42d8fe3fc5 100644 --- a/qiskit/circuit/classicalfunction/__init__.py +++ b/qiskit/circuit/classicalfunction/__init__.py @@ -25,7 +25,7 @@ how to synthesize a simple boolean function defined using Python into a QuantumCircuit: - .. jupyter-execute:: + .. code-block:: from qiskit.circuit.classicalfunction import classical_function from qiskit.circuit.classicalfunction.types import Int1 @@ -35,7 +35,6 @@ def grover_oracle(a: Int1, b: Int1, c: Int1, d: Int1) -> Int1: return (not a and b and not c and d) quantum_circuit = grover_oracle.synth() - quantum_circuit.draw() Following Qiskit's little-endian bit ordering convention, the left-most bit (`a`) is the most significant bit and the right-most bit (`d`) is the least significant bit. The resulting diff --git a/qiskit/circuit/controlledgate.py b/qiskit/circuit/controlledgate.py index 706d27403898..273c046c5a7c 100644 --- a/qiskit/circuit/controlledgate.py +++ b/qiskit/circuit/controlledgate.py @@ -64,7 +64,8 @@ def __init__( Create a controlled standard gate and apply it to a circuit. - .. jupyter-execute:: + .. plot:: + :include-source: from qiskit import QuantumCircuit, QuantumRegister from qiskit.circuit.library.standard_gates import HGate @@ -73,11 +74,12 @@ def __init__( qc = QuantumCircuit(qr) c3h_gate = HGate().control(2) qc.append(c3h_gate, qr) - qc.draw() + qc.draw('mpl') Create a controlled custom gate and apply it to a circuit. - .. jupyter-execute:: + .. plot:: + :include-source: from qiskit import QuantumCircuit, QuantumRegister from qiskit.circuit.library.standard_gates import HGate @@ -89,7 +91,7 @@ def __init__( qc2 = QuantumCircuit(4) qc2.append(custom, [0, 3, 1, 2]) - qc2.draw() + qc2.draw('mpl') """ self.base_gate = None if base_gate is None else base_gate.copy() super().__init__(name, num_qubits, params, label=label) diff --git a/qiskit/circuit/instructionset.py b/qiskit/circuit/instructionset.py index 851a7034e1ab..10155460030d 100644 --- a/qiskit/circuit/instructionset.py +++ b/qiskit/circuit/instructionset.py @@ -188,23 +188,24 @@ def c_if(self, classical: Union[Clbit, ClassicalRegister, int], val: int) -> "In to a concrete resource that these instructions are permitted to access. Example: - .. jupyter-execute:: + .. plot:: + :include-source: - from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit + from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit - qr = QuantumRegister(2) - cr = ClassicalRegister(2) - qc = QuantumCircuit(qr, cr) - qc.h(range(2)) - qc.measure(range(2), range(2)) + qr = QuantumRegister(2) + cr = ClassicalRegister(2) + qc = QuantumCircuit(qr, cr) + qc.h(range(2)) + qc.measure(range(2), range(2)) - # apply x gate if the classical register has the value 2 (10 in binary) - qc.x(0).c_if(cr, 2) + # apply x gate if the classical register has the value 2 (10 in binary) + qc.x(0).c_if(cr, 2) - # apply y gate if bit 0 is set to 1 - qc.y(1).c_if(0, 1) + # apply y gate if bit 0 is set to 1 + qc.y(1).c_if(0, 1) - qc.draw() + qc.draw('mpl') """ if self._requester is None and not isinstance(classical, (Clbit, ClassicalRegister)): diff --git a/qiskit/circuit/library/__init__.py b/qiskit/circuit/library/__init__.py index bffe75968e1e..08d7cfea098a 100644 --- a/qiskit/circuit/library/__init__.py +++ b/qiskit/circuit/library/__init__.py @@ -25,15 +25,16 @@ method and so the circuit library allows users to program at higher levels of abstraction. For example, to append a multi-controlled CNOT: -.. jupyter-execute:: +.. plot:: + :include-source: - from qiskit.circuit.library import MCXGate - gate = MCXGate(4) + from qiskit.circuit.library import MCXGate + gate = MCXGate(4) - from qiskit import QuantumCircuit - circuit = QuantumCircuit(5) - circuit.append(gate, [0, 1, 4, 2, 3]) - circuit.draw('mpl') + from qiskit import QuantumCircuit + circuit = QuantumCircuit(5) + circuit.append(gate, [0, 1, 4, 2, 3]) + circuit.draw('mpl') The library is organized in several sections. @@ -47,7 +48,7 @@ For example: -.. jupyter-execute:: +.. code-block:: from qiskit.circuit.library import XGate gate = XGate() @@ -55,6 +56,16 @@ print(gate.power(1/2).to_matrix()) # √X gate print(gate.control(1).to_matrix()) # CX (controlled X) gate +.. parsed-literal:: + + [[0.+0.j 1.+0.j] + [1.+0.j 0.+0.j]] + [[0.5+0.5j 0.5-0.5j] + [0.5-0.5j 0.5+0.5j]] + [[1.+0.j 0.+0.j 0.+0.j 0.+0.j] + [0.+0.j 0.+0.j 0.+0.j 1.+0.j] + [0.+0.j 0.+0.j 1.+0.j 0.+0.j] + [0.+0.j 1.+0.j 0.+0.j 0.+0.j]] .. autosummary:: :toctree: ../stubs/ @@ -145,7 +156,7 @@ set the amount of qubits involved at instantiation time. -.. jupyter-execute:: +.. code-block:: from qiskit.circuit.library import Diagonal @@ -155,6 +166,11 @@ diagonal = Diagonal([1, 1, 1, 1]) print(diagonal.num_qubits) +.. parsed-literal:: + + 1 + 2 + .. autosummary:: :toctree: ../stubs/ @@ -349,7 +365,7 @@ In this example, the identity constant in a template is checked: -.. jupyter-execute:: +.. code-block:: from qiskit.circuit.library.templates import template_nct_4b_1 from qiskit.quantum_info import Operator diff --git a/qiskit/circuit/library/arithmetic/piecewise_chebyshev.py b/qiskit/circuit/library/arithmetic/piecewise_chebyshev.py index 9c3e57b19a32..67f808278f2d 100644 --- a/qiskit/circuit/library/arithmetic/piecewise_chebyshev.py +++ b/qiskit/circuit/library/arithmetic/piecewise_chebyshev.py @@ -34,7 +34,8 @@ class PiecewiseChebyshev(BlueprintCircuit): Examples: - .. jupyter-execute:: + .. plot:: + :include-source: import numpy as np from qiskit import QuantumCircuit diff --git a/qiskit/circuit/library/basis_change/qft.py b/qiskit/circuit/library/basis_change/qft.py index c937cf126d6d..7e9262d81943 100644 --- a/qiskit/circuit/library/basis_change/qft.py +++ b/qiskit/circuit/library/basis_change/qft.py @@ -38,24 +38,22 @@ class QFT(BlueprintCircuit): For 4 qubits, the circuit that implements this transformation is: - .. jupyter-execute:: - :hide-code: + .. plot:: - from qiskit.circuit.library import QFT - import qiskit.tools.jupyter - circuit = QFT(4) - %circuit_library_info circuit + from qiskit.circuit.library import QFT + from qiskit.tools.jupyter.library import _generate_circuit_library_visualization + circuit = QFT(4) + _generate_circuit_library_visualization(circuit) The inverse QFT can be obtained by calling the ``inverse`` method on this class. The respective circuit diagram is: - .. jupyter-execute:: - :hide-code: + .. plot:: - from qiskit.circuit.library import QFT - import qiskit.tools.jupyter - circuit = QFT(4).inverse() - %circuit_library_info circuit + from qiskit.circuit.library import QFT + from qiskit.tools.jupyter.library import _generate_circuit_library_visualization + circuit = QFT(4).inverse() + _generate_circuit_library_visualization(circuit) One method to reduce circuit depth is to implement the QFT approximately by ignoring controlled-phase rotations where the angle is beneath a threshold. This is discussed @@ -66,13 +64,12 @@ class QFT(BlueprintCircuit): ``approximation_degree`` rotation angles are dropped from the QFT. For instance, a QFT on 5 qubits with approximation degree 2 yields (the barriers are dropped in this example): - .. jupyter-execute:: - :hide-code: + .. plot:: - from qiskit.circuit.library import QFT - import qiskit.tools.jupyter - circuit = QFT(5, approximation_degree=2) - %circuit_library_info circuit + from qiskit.circuit.library import QFT + from qiskit.tools.jupyter.library import _generate_circuit_library_visualization + circuit = QFT(5, approximation_degree=2) + _generate_circuit_library_visualization(circuit) """ diff --git a/qiskit/circuit/library/boolean_logic/inner_product.py b/qiskit/circuit/library/boolean_logic/inner_product.py index 3f3c29aef50c..08524f51048a 100644 --- a/qiskit/circuit/library/boolean_logic/inner_product.py +++ b/qiskit/circuit/library/boolean_logic/inner_product.py @@ -53,13 +53,12 @@ class InnerProduct(QuantumCircuit): Reference Circuit: - .. jupyter-execute:: - :hide-code: + .. plot:: - from qiskit.circuit.library import InnerProduct - import qiskit.tools.jupyter - circuit = InnerProduct(4) - %circuit_library_info circuit + from qiskit.circuit.library import InnerProduct + from qiskit.tools.jupyter.library import _generate_circuit_library_visualization + circuit = InnerProduct(4) + _generate_circuit_library_visualization(circuit) """ def __init__(self, num_qubits: int) -> None: diff --git a/qiskit/circuit/library/boolean_logic/quantum_and.py b/qiskit/circuit/library/boolean_logic/quantum_and.py index da0962b27c49..7b598c4ad7c8 100644 --- a/qiskit/circuit/library/boolean_logic/quantum_and.py +++ b/qiskit/circuit/library/boolean_logic/quantum_and.py @@ -30,25 +30,23 @@ class AND(QuantumCircuit): The AND gate without special flags equals the multi-controlled-X gate: - .. jupyter-execute:: - :hide-code: + .. plot:: - from qiskit.circuit.library import AND - import qiskit.tools.jupyter - circuit = AND(5) - %circuit_library_info circuit + from qiskit.circuit.library import AND + from qiskit.tools.jupyter.library import _generate_circuit_library_visualization + circuit = AND(5) + _generate_circuit_library_visualization(circuit) Using flags we can negate qubits or skip them. For instance, if we have 5 qubits and want to return ``True`` if the first qubit is ``False`` and the last two are ``True`` we use the flags ``[-1, 0, 0, 1, 1]``. - .. jupyter-execute:: - :hide-code: + .. plot:: - from qiskit.circuit.library import AND - import qiskit.tools.jupyter - circuit = AND(5, flags=[-1, 0, 0, 1, 1]) - %circuit_library_info circuit + from qiskit.circuit.library import AND + from qiskit.tools.jupyter.library import _generate_circuit_library_visualization + circuit = AND(5, flags=[-1, 0, 0, 1, 1]) + _generate_circuit_library_visualization(circuit) """ diff --git a/qiskit/circuit/library/boolean_logic/quantum_or.py b/qiskit/circuit/library/boolean_logic/quantum_or.py index 3fbea2e17e06..4e885c23b44e 100644 --- a/qiskit/circuit/library/boolean_logic/quantum_or.py +++ b/qiskit/circuit/library/boolean_logic/quantum_or.py @@ -30,25 +30,23 @@ class OR(QuantumCircuit): The OR gate without special flags: - .. jupyter-execute:: - :hide-code: + .. plot:: - from qiskit.circuit.library import OR - import qiskit.tools.jupyter - circuit = OR(5) - %circuit_library_info circuit + from qiskit.circuit.library import OR + from qiskit.tools.jupyter.library import _generate_circuit_library_visualization + circuit = OR(5) + _generate_circuit_library_visualization(circuit) Using flags we can negate qubits or skip them. For instance, if we have 5 qubits and want to return ``True`` if the first qubit is ``False`` or one of the last two are ``True`` we use the flags ``[-1, 0, 0, 1, 1]``. - .. jupyter-execute:: - :hide-code: + .. plot:: - from qiskit.circuit.library import OR - import qiskit.tools.jupyter - circuit = OR(5, flags=[-1, 0, 0, 1, 1]) - %circuit_library_info circuit + from qiskit.circuit.library import OR + from qiskit.tools.jupyter.library import _generate_circuit_library_visualization + circuit = OR(5, flags=[-1, 0, 0, 1, 1]) + _generate_circuit_library_visualization(circuit) """ diff --git a/qiskit/circuit/library/boolean_logic/quantum_xor.py b/qiskit/circuit/library/boolean_logic/quantum_xor.py index 3d5118afd861..08b0055248fa 100644 --- a/qiskit/circuit/library/boolean_logic/quantum_xor.py +++ b/qiskit/circuit/library/boolean_logic/quantum_xor.py @@ -45,13 +45,12 @@ def __init__( CircuitError: if the xor bitstring exceeds available qubits. Reference Circuit: - .. jupyter-execute:: - :hide-code: + .. plot:: - from qiskit.circuit.library import XOR - import qiskit.tools.jupyter - circuit = XOR(5, seed=42) - %circuit_library_info circuit + from qiskit.circuit.library import XOR + from qiskit.tools.jupyter.library import _generate_circuit_library_visualization + circuit = XOR(5, seed=42) + _generate_circuit_library_visualization(circuit) """ circuit = QuantumCircuit(num_qubits, name="xor") diff --git a/qiskit/circuit/library/data_preparation/state_preparation.py b/qiskit/circuit/library/data_preparation/state_preparation.py index 943e74f445b5..65b1c9162990 100644 --- a/qiskit/circuit/library/data_preparation/state_preparation.py +++ b/qiskit/circuit/library/data_preparation/state_preparation.py @@ -440,14 +440,14 @@ def prepare_state(self, state, qubits=None, label=None): Examples: Prepare a qubit in the state :math:`(|0\rangle - |1\rangle) / \sqrt{2}`. - .. jupyter-execute:: + .. code-block:: - import numpy as np - from qiskit import QuantumCircuit + import numpy as np + from qiskit import QuantumCircuit - circuit = QuantumCircuit(1) - circuit.prepare_state([1/np.sqrt(2), -1/np.sqrt(2)], 0) - circuit.draw() + circuit = QuantumCircuit(1) + circuit.prepare_state([1/np.sqrt(2), -1/np.sqrt(2)], 0) + circuit.draw() output: @@ -463,7 +463,7 @@ def prepare_state(self, state, qubits=None, label=None): More information about labels for basis states are in :meth:`.Statevector.from_label`. - .. jupyter-execute:: + .. code-block:: import numpy as np from qiskit import QuantumCircuit @@ -484,7 +484,7 @@ def prepare_state(self, state, qubits=None, label=None): Initialize two qubits from an array of complex amplitudes - .. jupyter-execute:: + .. code-block:: import numpy as np from qiskit import QuantumCircuit diff --git a/qiskit/circuit/library/fourier_checking.py b/qiskit/circuit/library/fourier_checking.py index 8491ef1e0c99..696d94ba654c 100644 --- a/qiskit/circuit/library/fourier_checking.py +++ b/qiskit/circuit/library/fourier_checking.py @@ -61,15 +61,14 @@ def __init__(self, f: List[int], g: List[int]) -> None: CircuitError: if the inputs f and g are not valid. Reference Circuit: - .. jupyter-execute:: - :hide-code: - - from qiskit.circuit.library import FourierChecking - import qiskit.tools.jupyter - f = [1, -1, -1, -1] - g = [1, 1, -1, -1] - circuit = FourierChecking(f, g) - %circuit_library_info circuit + .. plot:: + + from qiskit.circuit.library import FourierChecking + from qiskit.tools.jupyter.library import _generate_circuit_library_visualization + f = [1, -1, -1, -1] + g = [1, 1, -1, -1] + circuit = FourierChecking(f, g) + _generate_circuit_library_visualization(circuit) """ num_qubits = math.log2(len(f)) diff --git a/qiskit/circuit/library/generalized_gates/gms.py b/qiskit/circuit/library/generalized_gates/gms.py index 2b577161e4d2..46b28cac60af 100644 --- a/qiskit/circuit/library/generalized_gates/gms.py +++ b/qiskit/circuit/library/generalized_gates/gms.py @@ -41,16 +41,15 @@ class GMS(QuantumCircuit): **Expanded Circuit:** - .. jupyter-execute:: - :hide-code: - - from qiskit.circuit.library import GMS - import qiskit.tools.jupyter - import numpy as np - circuit = GMS(num_qubits=3, theta=[[0, np.pi/4, np.pi/8], - [0, 0, np.pi/2], - [0, 0, 0]]) - %circuit_library_info circuit.decompose() + .. plot:: + + from qiskit.circuit.library import GMS + from qiskit.tools.jupyter.library import _generate_circuit_library_visualization + import numpy as np + circuit = GMS(num_qubits=3, theta=[[0, np.pi/4, np.pi/8], + [0, 0, np.pi/2], + [0, 0, 0]]) + _generate_circuit_library_visualization(circuit.decompose()) The Mølmer–Sørensen gate is native to ion-trap systems. The global MS can be applied to multiple ions to entangle multiple qubits simultaneously [1]. diff --git a/qiskit/circuit/library/generalized_gates/gr.py b/qiskit/circuit/library/generalized_gates/gr.py index 171d05960c67..acb83909cce0 100644 --- a/qiskit/circuit/library/generalized_gates/gr.py +++ b/qiskit/circuit/library/generalized_gates/gr.py @@ -44,14 +44,13 @@ class GR(QuantumCircuit): **Expanded Circuit:** - .. jupyter-execute:: - :hide-code: + .. plot:: - from qiskit.circuit.library import GR - import qiskit.tools.jupyter - import numpy as np - circuit = GR(num_qubits=3, theta=np.pi/4, phi=np.pi/2) - %circuit_library_info circuit + from qiskit.circuit.library import GR + from qiskit.tools.jupyter.library import _generate_circuit_library_visualization + import numpy as np + circuit = GR(num_qubits=3, theta=np.pi/4, phi=np.pi/2) + _generate_circuit_library_visualization(circuit) """ @@ -99,14 +98,13 @@ class GRX(GR): **Expanded Circuit:** - .. jupyter-execute:: - :hide-code: + .. plot:: from qiskit.circuit.library import GRX - import qiskit.tools.jupyter + from qiskit.tools.jupyter.library import _generate_circuit_library_visualization import numpy as np circuit = GRX(num_qubits=3, theta=np.pi/4) - %circuit_library_info circuit + _generate_circuit_library_visualization(circuit) """ @@ -148,14 +146,13 @@ class GRY(GR): **Expanded Circuit:** - .. jupyter-execute:: - :hide-code: + .. plot:: - from qiskit.circuit.library import GRY - import qiskit.tools.jupyter - import numpy as np - circuit = GRY(num_qubits=3, theta=np.pi/4) - %circuit_library_info circuit + from qiskit.circuit.library import GRY + from qiskit.tools.jupyter.library import _generate_circuit_library_visualization + import numpy as np + circuit = GRY(num_qubits=3, theta=np.pi/4) + _generate_circuit_library_visualization(circuit) """ @@ -197,14 +194,13 @@ class GRZ(QuantumCircuit): **Expanded Circuit:** - .. jupyter-execute:: - :hide-code: + .. plot:: - from qiskit.circuit.library import GRZ - import qiskit.tools.jupyter - import numpy as np - circuit = GRZ(num_qubits=3, phi=np.pi/2) - %circuit_library_info circuit + from qiskit.circuit.library import GRZ + from qiskit.tools.jupyter.library import _generate_circuit_library_visualization + import numpy as np + circuit = GRZ(num_qubits=3, phi=np.pi/2) + _generate_circuit_library_visualization(circuit) """ diff --git a/qiskit/circuit/library/generalized_gates/mcmt.py b/qiskit/circuit/library/generalized_gates/mcmt.py index 6907ac31c521..fec304b4b912 100644 --- a/qiskit/circuit/library/generalized_gates/mcmt.py +++ b/qiskit/circuit/library/generalized_gates/mcmt.py @@ -208,13 +208,12 @@ class MCMTVChain(MCMT): **Expanded Circuit:** - .. jupyter-execute:: - :hide-code: + .. plot:: - from qiskit.circuit.library import MCMTVChain, ZGate - import qiskit.tools.jupyter - circuit = MCMTVChain(ZGate(), 2, 2) - %circuit_library_info circuit.decompose() + from qiskit.circuit.library import MCMTVChain, ZGate + from qiskit.tools.jupyter.library import _generate_circuit_library_visualization + circuit = MCMTVChain(ZGate(), 2, 2) + _generate_circuit_library_visualization(circuit.decompose()) **Examples:** diff --git a/qiskit/circuit/library/generalized_gates/permutation.py b/qiskit/circuit/library/generalized_gates/permutation.py index 749f7cceba06..c415d5704e06 100644 --- a/qiskit/circuit/library/generalized_gates/permutation.py +++ b/qiskit/circuit/library/generalized_gates/permutation.py @@ -47,24 +47,21 @@ def __init__( CircuitError: if permutation pattern is malformed. Reference Circuit: - .. jupyter-execute:: - :hide-code: + .. plot:: - from qiskit.circuit.library import Permutation - import qiskit.tools.jupyter - A = [2,4,3,0,1] - circuit = Permutation(5, A) - circuit.draw('mpl') + from qiskit.circuit.library import Permutation + A = [2,4,3,0,1] + circuit = Permutation(5, A) + circuit.draw('mpl') Expanded Circuit: - .. jupyter-execute:: - :hide-code: - - from qiskit.circuit.library import Permutation - import qiskit.tools.jupyter - A = [2,4,3,0,1] - circuit = Permutation(5, A) - %circuit_library_info circuit.decompose() + .. plot:: + + from qiskit.circuit.library import Permutation + from qiskit.tools.jupyter.library import _generate_circuit_library_visualization + A = [2,4,3,0,1] + circuit = Permutation(5, A) + _generate_circuit_library_visualization(circuit.decompose()) """ if pattern is not None: if sorted(pattern) != list(range(num_qubits)): diff --git a/qiskit/circuit/library/graph_state.py b/qiskit/circuit/library/graph_state.py index aeb2e8cb5499..3c6705206b1d 100644 --- a/qiskit/circuit/library/graph_state.py +++ b/qiskit/circuit/library/graph_state.py @@ -39,15 +39,14 @@ class GraphState(QuantumCircuit): **Reference Circuit:** - .. jupyter-execute:: - :hide-code: - - from qiskit.circuit.library import GraphState - import qiskit.tools.jupyter - import rustworkx as rx - G = rx.generators.cycle_graph(5) - circuit = GraphState(rx.adjacency_matrix(G)) - %circuit_library_info circuit + .. plot:: + + from qiskit.circuit.library import GraphState + from qiskit.tools.jupyter.library import _generate_circuit_library_visualization + import rustworkx as rx + G = rx.generators.cycle_graph(5) + circuit = GraphState(rx.adjacency_matrix(G)) + _generate_circuit_library_visualization(circuit) **References:** diff --git a/qiskit/circuit/library/hidden_linear_function.py b/qiskit/circuit/library/hidden_linear_function.py index df69021795a9..4742145ab51f 100644 --- a/qiskit/circuit/library/hidden_linear_function.py +++ b/qiskit/circuit/library/hidden_linear_function.py @@ -53,15 +53,13 @@ class HiddenLinearFunction(QuantumCircuit): **Reference Circuit:** - .. jupyter-execute:: - :hide-code: - - from qiskit.circuit.library import HiddenLinearFunction - import qiskit.tools.jupyter - A = [[1, 1, 0], [1, 0, 1], [0, 1, 1]] - circuit = HiddenLinearFunction(A) - %circuit_library_info circuit + .. plot:: + from qiskit.circuit.library import HiddenLinearFunction + from qiskit.tools.jupyter.library import _generate_circuit_library_visualization + A = [[1, 1, 0], [1, 0, 1], [0, 1, 1]] + circuit = HiddenLinearFunction(A) + _generate_circuit_library_visualization(circuit) **Reference:** diff --git a/qiskit/circuit/library/iqp.py b/qiskit/circuit/library/iqp.py index 95215c613dfa..0b55d7c0720b 100644 --- a/qiskit/circuit/library/iqp.py +++ b/qiskit/circuit/library/iqp.py @@ -35,25 +35,22 @@ class IQP(QuantumCircuit): **Reference Circuit:** - .. jupyter-execute:: - :hide-code: + .. plot:: - from qiskit.circuit.library import IQP - import qiskit.tools.jupyter - A = [[6, 5, 3], [5, 4, 5], [3, 5, 1]] - circuit = IQP(A) - circuit.draw('mpl') + from qiskit.circuit.library import IQP + A = [[6, 5, 3], [5, 4, 5], [3, 5, 1]] + circuit = IQP(A) + circuit.draw('mpl') **Expanded Circuit:** - .. jupyter-execute:: - :hide-code: + .. plot:: - from qiskit.circuit.library import IQP - import qiskit.tools.jupyter - A = [[6, 5, 3], [5, 4, 5], [3, 5, 1]] - circuit = IQP(A) - %circuit_library_info circuit.decompose() + from qiskit.circuit.library import IQP + from qiskit.tools.jupyter.library import _generate_circuit_library_visualization + A = [[6, 5, 3], [5, 4, 5], [3, 5, 1]] + circuit = IQP(A) + _generate_circuit_library_visualization(circuit.decompose()) **References:** diff --git a/qiskit/circuit/library/n_local/pauli_two_design.py b/qiskit/circuit/library/n_local/pauli_two_design.py index 77bb94916fd9..a8dc91e273b3 100644 --- a/qiskit/circuit/library/n_local/pauli_two_design.py +++ b/qiskit/circuit/library/n_local/pauli_two_design.py @@ -51,11 +51,12 @@ class PauliTwoDesign(TwoLocal): Examples: - .. jupyter-execute: + .. plot:: + :include-source: - from qiskit.circuit.library import PauliTwoDesign - circuit = PauliTwoDesign(4, reps=2, seed=5, insert_barriers=True) - print(circuit.draw()) + from qiskit.circuit.library import PauliTwoDesign + circuit = PauliTwoDesign(4, reps=2, seed=5, insert_barriers=True) + circuit.draw('mpl') References: diff --git a/qiskit/circuit/library/phase_estimation.py b/qiskit/circuit/library/phase_estimation.py index 314d3999b47d..b131e320486a 100644 --- a/qiskit/circuit/library/phase_estimation.py +++ b/qiskit/circuit/library/phase_estimation.py @@ -69,17 +69,16 @@ def __init__( The inverse QFT should not include a swap of the qubit order. Reference Circuit: - .. jupyter-execute:: - :hide-code: - - from qiskit.circuit import QuantumCircuit - from qiskit.circuit.library import PhaseEstimation - import qiskit.tools.jupyter - unitary = QuantumCircuit(2) - unitary.x(0) - unitary.y(1) - circuit = PhaseEstimation(3, unitary) - %circuit_library_info circuit + .. plot:: + + from qiskit.circuit import QuantumCircuit + from qiskit.circuit.library import PhaseEstimation + from qiskit.tools.jupyter.library import _generate_circuit_library_visualization + unitary = QuantumCircuit(2) + unitary.x(0) + unitary.y(1) + circuit = PhaseEstimation(3, unitary) + _generate_circuit_library_visualization(circuit) """ qr_eval = QuantumRegister(num_evaluation_qubits, "eval") qr_state = QuantumRegister(unitary.num_qubits, "q") diff --git a/qiskit/circuit/library/quantum_volume.py b/qiskit/circuit/library/quantum_volume.py index b763a38f17e8..43340dfff3ce 100644 --- a/qiskit/circuit/library/quantum_volume.py +++ b/qiskit/circuit/library/quantum_volume.py @@ -32,23 +32,20 @@ class QuantumVolume(QuantumCircuit): **Reference Circuit:** - .. jupyter-execute:: - :hide-code: + .. plot:: - from qiskit.circuit.library import QuantumVolume - import qiskit.tools.jupyter - circuit = QuantumVolume(5, 6, seed=10) - circuit.draw('mpl') + from qiskit.circuit.library import QuantumVolume + circuit = QuantumVolume(5, 6, seed=10) + circuit.draw('mpl') **Expanded Circuit:** - .. jupyter-execute:: - :hide-code: + .. plot:: - from qiskit.circuit.library import QuantumVolume - import qiskit.tools.jupyter - circuit = QuantumVolume(5, 6, seed=10, classical_permutation=False) - %circuit_library_info circuit.decompose() + from qiskit.circuit.library import QuantumVolume + from qiskit.tools.jupyter.library import _generate_circuit_library_visualization + circuit = QuantumVolume(5, 6, seed=10, classical_permutation=False) + _generate_circuit_library_visualization(circuit.decompose()) **References:** diff --git a/qiskit/circuit/operation.py b/qiskit/circuit/operation.py index f2e898c069f9..d4d2a719a9b8 100644 --- a/qiskit/circuit/operation.py +++ b/qiskit/circuit/operation.py @@ -28,16 +28,17 @@ class Operation(ABC): Add a Clifford and a Toffoli gate to a QuantumCircuit. - .. jupyter-execute:: + .. plot:: + :include-source: - from qiskit import QuantumCircuit - from qiskit.quantum_info import Clifford, random_clifford + from qiskit import QuantumCircuit + from qiskit.quantum_info import Clifford, random_clifford - qc = QuantumCircuit(3) - cliff = random_clifford(2) - qc.append(cliff, [0, 1]) - qc.ccx(0, 1, 2) - qc.draw() + qc = QuantumCircuit(3) + cliff = random_clifford(2) + qc.append(cliff, [0, 1]) + qc.ccx(0, 1, 2) + qc.draw('mpl') """ __slots__ = () diff --git a/qiskit/circuit/parameter.py b/qiskit/circuit/parameter.py index 558853f11a9b..7ece72cae6a0 100644 --- a/qiskit/circuit/parameter.py +++ b/qiskit/circuit/parameter.py @@ -29,22 +29,23 @@ class Parameter(ParameterExpression): Construct a variable-rotation X gate using circuit parameters. - .. jupyter-execute:: + .. plot:: + :include-source: - from qiskit.circuit import QuantumCircuit, Parameter + from qiskit.circuit import QuantumCircuit, Parameter - # create the parameter - phi = Parameter('phi') - qc = QuantumCircuit(1) + # create the parameter + phi = Parameter('phi') + qc = QuantumCircuit(1) - # parameterize the rotation - qc.rx(phi, 0) - qc.draw() + # parameterize the rotation + qc.rx(phi, 0) + qc.draw('mpl') - # bind the parameters after circuit to create a bound circuit - bc = qc.bind_parameters({phi: 3.14}) - bc.measure_all() - bc.draw() + # bind the parameters after circuit to create a bound circuit + bc = qc.bind_parameters({phi: 3.14}) + bc.measure_all() + bc.draw('mpl') """ def __new__(cls, name, uuid=None): # pylint: disable=unused-argument diff --git a/qiskit/circuit/quantumcircuit.py b/qiskit/circuit/quantumcircuit.py index 4348cc8ae2b9..d1327699ea12 100644 --- a/qiskit/circuit/quantumcircuit.py +++ b/qiskit/circuit/quantumcircuit.py @@ -155,47 +155,49 @@ class QuantumCircuit: Construct a simple Bell state circuit. - .. jupyter-execute:: + .. plot:: + :include-source: - from qiskit import QuantumCircuit + from qiskit import QuantumCircuit - qc = QuantumCircuit(2, 2) - qc.h(0) - qc.cx(0, 1) - qc.measure([0, 1], [0, 1]) - qc.draw() + qc = QuantumCircuit(2, 2) + qc.h(0) + qc.cx(0, 1) + qc.measure([0, 1], [0, 1]) + qc.draw('mpl') Construct a 5-qubit GHZ circuit. - .. jupyter-execute:: + .. code-block:: - from qiskit import QuantumCircuit + from qiskit import QuantumCircuit - qc = QuantumCircuit(5) - qc.h(0) - qc.cx(0, range(1, 5)) - qc.measure_all() + qc = QuantumCircuit(5) + qc.h(0) + qc.cx(0, range(1, 5)) + qc.measure_all() Construct a 4-qubit Bernstein-Vazirani circuit using registers. - .. jupyter-execute:: + .. plot:: + :include-source: - from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit + from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit - qr = QuantumRegister(3, 'q') - anc = QuantumRegister(1, 'ancilla') - cr = ClassicalRegister(3, 'c') - qc = QuantumCircuit(qr, anc, cr) + qr = QuantumRegister(3, 'q') + anc = QuantumRegister(1, 'ancilla') + cr = ClassicalRegister(3, 'c') + qc = QuantumCircuit(qr, anc, cr) - qc.x(anc[0]) - qc.h(anc[0]) - qc.h(qr[0:3]) - qc.cx(qr[0:3], anc[0]) - qc.h(qr[0:3]) - qc.barrier(qr) - qc.measure(qr, cr) + qc.x(anc[0]) + qc.h(anc[0]) + qc.h(qr[0:3]) + qc.cx(qr[0:3], anc[0]) + qc.h(qr[0:3]) + qc.barrier(qr) + qc.measure(qr, cr) - qc.draw() + qc.draw('mpl') """ instances = 0 @@ -968,15 +970,16 @@ def tensor(self, other: "QuantumCircuit", inplace: bool = False) -> Optional["Qu Examples: - .. jupyter-execute:: + .. plot:: + :include-source: - from qiskit import QuantumCircuit - top = QuantumCircuit(1) - top.x(0); - bottom = QuantumCircuit(2) - bottom.cry(0.2, 0, 1); - tensored = bottom.tensor(top) - print(tensored.draw()) + from qiskit import QuantumCircuit + top = QuantumCircuit(1) + top.x(0); + bottom = QuantumCircuit(2) + bottom.cry(0.2, 0, 1); + tensored = bottom.tensor(top) + tensored.draw('mpl') Returns: QuantumCircuit: The tensored circuit (returns None if inplace==True). @@ -1860,16 +1863,16 @@ def draw( ImportError: when the output methods requires non-installed libraries. Example: - .. jupyter-execute:: + .. plot:: + :include-source: - from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit - from qiskit.tools.visualization import circuit_drawer - q = QuantumRegister(1) - c = ClassicalRegister(1) - qc = QuantumCircuit(q, c) - qc.h(q) - qc.measure(q, c) - qc.draw(output='mpl', style={'backgroundcolor': '#EEEEEE'}) + from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit + q = QuantumRegister(1) + c = ClassicalRegister(1) + qc = QuantumCircuit(q, c) + qc.h(q) + qc.measure(q, c) + qc.draw(output='mpl', style={'backgroundcolor': '#EEEEEE'}) """ # pylint: disable=cyclic-import @@ -2557,40 +2560,35 @@ def assign_parameters( Create a parameterized circuit and assign the parameters in-place. - .. jupyter-execute:: - - from qiskit.circuit import QuantumCircuit, Parameter - - circuit = QuantumCircuit(2) - params = [Parameter('A'), Parameter('B'), Parameter('C')] - circuit.ry(params[0], 0) - circuit.crx(params[1], 0, 1) - - print('Original circuit:') - print(circuit.draw()) + .. plot:: + :include-source: - circuit.assign_parameters({params[0]: params[2]}, inplace=True) + from qiskit.circuit import QuantumCircuit, Parameter - print('Assigned in-place:') - print(circuit.draw()) + circuit = QuantumCircuit(2) + params = [Parameter('A'), Parameter('B'), Parameter('C')] + circuit.ry(params[0], 0) + circuit.crx(params[1], 0, 1) + circuit.draw('mpl') + circuit.assign_parameters({params[0]: params[2]}, inplace=True) + circuit.draw('mpl') Bind the values out-of-place by list and get a copy of the original circuit. - .. jupyter-execute:: + .. plot:: + :include-source: - from qiskit.circuit import QuantumCircuit, ParameterVector + from qiskit.circuit import QuantumCircuit, ParameterVector - circuit = QuantumCircuit(2) - params = ParameterVector('P', 2) - circuit.ry(params[0], 0) - circuit.crx(params[1], 0, 1) + circuit = QuantumCircuit(2) + params = ParameterVector('P', 2) + circuit.ry(params[0], 0) + circuit.crx(params[1], 0, 1) - bound_circuit = circuit.assign_parameters([1, 2]) - print('Bound circuit:') - print(bound_circuit.draw()) + bound_circuit = circuit.assign_parameters([1, 2]) + bound_circuit.draw('mpl') - print('The original circuit is unchanged:') - print(circuit.draw()) + circuit.draw('mpl') """ # replace in self or in a copy depending on the value of in_place diff --git a/qiskit/circuit/random/utils.py b/qiskit/circuit/random/utils.py index b63f04c746a8..2b8911252d34 100644 --- a/qiskit/circuit/random/utils.py +++ b/qiskit/circuit/random/utils.py @@ -28,12 +28,13 @@ def random_circuit( This function will generate a random circuit by randomly selecting gates from the set of standard gates in :mod:`qiskit.extensions`. For example: - .. jupyter-execute:: + .. plot:: + :include-source: - from qiskit.circuit.random import random_circuit + from qiskit.circuit.random import random_circuit - circ = random_circuit(2, 2, measure=True) - circ.draw(output='mpl') + circ = random_circuit(2, 2, measure=True) + circ.draw(output='mpl') Args: num_qubits (int): number of quantum wires diff --git a/qiskit/converters/ast_to_dag.py b/qiskit/converters/ast_to_dag.py index b8d99603378e..3883f7c5668c 100644 --- a/qiskit/converters/ast_to_dag.py +++ b/qiskit/converters/ast_to_dag.py @@ -76,12 +76,10 @@ def ast_to_dag(ast): QiskitError: if the AST is malformed. Example: - .. jupyter-execute:: + .. code-block:: from qiskit.converters import ast_to_dag from qiskit import qasm, QuantumCircuit, ClassicalRegister, QuantumRegister - from qiskit.visualization import dag_drawer - %matplotlib inline q = QuantumRegister(3, 'q') c = ClassicalRegister(3, 'c') @@ -93,7 +91,6 @@ def ast_to_dag(ast): qasm_str = circ.qasm() ast = qasm.Qasm(data=qasm_str).parse() dag = ast_to_dag(ast) - dag_drawer(dag) """ dag = DAGCircuit() AstInterpreter(dag)._process_node(ast) diff --git a/qiskit/converters/circuit_to_dag.py b/qiskit/converters/circuit_to_dag.py index 649c48fc770f..22cc81f1a89f 100644 --- a/qiskit/converters/circuit_to_dag.py +++ b/qiskit/converters/circuit_to_dag.py @@ -26,13 +26,11 @@ def circuit_to_dag(circuit): DAGCircuit: the DAG representing the input circuit. Example: - .. jupyter-execute:: + .. code-block:: from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.dagcircuit import DAGCircuit from qiskit.converters import circuit_to_dag - from qiskit.visualization import dag_drawer - %matplotlib inline q = QuantumRegister(3, 'q') c = ClassicalRegister(3, 'c') @@ -42,7 +40,6 @@ def circuit_to_dag(circuit): circ.measure(q[0], c[0]) circ.rz(0.5, q[1]).c_if(c, 2) dag = circuit_to_dag(circ) - dag_drawer(dag) """ dagcircuit = DAGCircuit() dagcircuit.name = circuit.name diff --git a/qiskit/converters/circuit_to_instruction.py b/qiskit/converters/circuit_to_instruction.py index a655c5141b3d..7965e3a474bc 100644 --- a/qiskit/converters/circuit_to_instruction.py +++ b/qiskit/converters/circuit_to_instruction.py @@ -44,7 +44,7 @@ def circuit_to_instruction(circuit, parameter_map=None, equivalence_library=None yield the components comprising the original circuit. Example: - .. jupyter-execute:: + .. code-block:: from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.converters import circuit_to_instruction diff --git a/qiskit/converters/dag_to_circuit.py b/qiskit/converters/dag_to_circuit.py index dcc2cb3896fa..63e25fbb21ad 100644 --- a/qiskit/converters/dag_to_circuit.py +++ b/qiskit/converters/dag_to_circuit.py @@ -26,25 +26,25 @@ def dag_to_circuit(dag): QuantumCircuit: the circuit representing the input dag. Example: - .. jupyter-execute:: + .. plot:: + :include-source: - from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit - from qiskit.dagcircuit import DAGCircuit - from qiskit.converters import circuit_to_dag - from qiskit.circuit.library.standard_gates import CHGate, U2Gate, CXGate - from qiskit.converters import dag_to_circuit - %matplotlib inline + from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit + from qiskit.dagcircuit import DAGCircuit + from qiskit.converters import circuit_to_dag + from qiskit.circuit.library.standard_gates import CHGate, U2Gate, CXGate + from qiskit.converters import dag_to_circuit - q = QuantumRegister(3, 'q') - c = ClassicalRegister(3, 'c') - circ = QuantumCircuit(q, c) - circ.h(q[0]) - circ.cx(q[0], q[1]) - circ.measure(q[0], c[0]) - circ.rz(0.5, q[1]).c_if(c, 2) - dag = circuit_to_dag(circ) - circuit = dag_to_circuit(dag) - circuit.draw() + q = QuantumRegister(3, 'q') + c = ClassicalRegister(3, 'c') + circ = QuantumCircuit(q, c) + circ.h(q[0]) + circ.cx(q[0], q[1]) + circ.measure(q[0], c[0]) + circ.rz(0.5, q[1]).c_if(c, 2) + dag = circuit_to_dag(circ) + circuit = dag_to_circuit(dag) + circuit.draw('mpl') """ name = dag.name or None diff --git a/qiskit/execute_function.py b/qiskit/execute_function.py index bfc188655af6..eec22f05a15b 100644 --- a/qiskit/execute_function.py +++ b/qiskit/execute_function.py @@ -264,7 +264,7 @@ def execute( Example: Construct a 5-qubit GHZ circuit and execute 4321 shots on a backend. - .. jupyter-execute:: + .. code-block:: from qiskit import QuantumCircuit, execute, BasicAer diff --git a/qiskit/extensions/quantum_initializer/initializer.py b/qiskit/extensions/quantum_initializer/initializer.py index 7d6c658174ad..ea0349cd51e8 100644 --- a/qiskit/extensions/quantum_initializer/initializer.py +++ b/qiskit/extensions/quantum_initializer/initializer.py @@ -119,7 +119,7 @@ class to prepare the qubits in a specified state. Examples: Prepare a qubit in the state :math:`(|0\rangle - |1\rangle) / \sqrt{2}`. - .. jupyter-execute:: + .. code-block:: import numpy as np from qiskit import QuantumCircuit @@ -142,7 +142,7 @@ class to prepare the qubits in a specified state. More information about labels for basis states are in :meth:`.Statevector.from_label`. - .. jupyter-execute:: + .. code-block:: import numpy as np from qiskit import QuantumCircuit @@ -163,7 +163,7 @@ class to prepare the qubits in a specified state. Initialize two qubits from an array of complex amplitudes. - .. jupyter-execute:: + .. code-block:: import numpy as np from qiskit import QuantumCircuit diff --git a/qiskit/providers/basicaer/__init__.py b/qiskit/providers/basicaer/__init__.py index 242e11866328..d2ae5638e19f 100644 --- a/qiskit/providers/basicaer/__init__.py +++ b/qiskit/providers/basicaer/__init__.py @@ -20,11 +20,11 @@ A module of Python-based quantum simulators. Simulators are accessed via the `BasicAer` provider, e.g.: -.. jupyter-execute:: +.. code-block:: - from qiskit import BasicAer + from qiskit import BasicAer - backend = BasicAer.get_backend('qasm_simulator') + backend = BasicAer.get_backend('qasm_simulator') Simulators diff --git a/qiskit/providers/fake_provider/__init__.py b/qiskit/providers/fake_provider/__init__.py index 6885a958f609..efd9ad395dd2 100644 --- a/qiskit/providers/fake_provider/__init__.py +++ b/qiskit/providers/fake_provider/__init__.py @@ -31,38 +31,34 @@ Here is an example of using a fake backend for transpilation and simulation. -.. jupyter-execute:: - - from qiskit import QuantumCircuit - from qiskit.providers.fake_provider import FakeManilaV2 - - # Get a fake backend from the fake provider - backend = FakeManilaV2() - - # Create a simple circuit - circuit = QuantumCircuit(3) - circuit.h(0) - circuit.cx(0,1) - circuit.cx(0,2) - circuit.measure_all() - circuit.draw() - -.. jupyter-execute:: - - from qiskit import transpile - - # Transpile the ideal circuit to a circuit that can be directly executed by the backend - transpiled_circuit = transpile(circuit, backend) - transpiled_circuit.draw() - -.. jupyter-execute:: - - from qiskit.tools.visualization import plot_histogram - - # Run the transpiled circuit using the simulated fake backend - job = backend.run(transpiled_circuit) - counts = job.result().get_counts() - plot_histogram(counts) +.. plot:: + :include-source: + + from qiskit import QuantumCircuit + from qiskit.providers.fake_provider import FakeManilaV2 + from qiskit import transpile + from qiskit.tools.visualization import plot_histogram + + + # Get a fake backend from the fake provider + backend = FakeManilaV2() + + # Create a simple circuit + circuit = QuantumCircuit(3) + circuit.h(0) + circuit.cx(0,1) + circuit.cx(0,2) + circuit.measure_all() + circuit.draw('mpl') + + # Transpile the ideal circuit to a circuit that can be directly executed by the backend + transpiled_circuit = transpile(circuit, backend) + transpiled_circuit.draw('mpl') + + # Run the transpiled circuit using the simulated fake backend + job = backend.run(transpiled_circuit) + counts = job.result().get_counts() + plot_histogram(counts) .. important:: diff --git a/qiskit/pulse/builder.py b/qiskit/pulse/builder.py index 4656c442dc64..73ac8eb9f8fc 100644 --- a/qiskit/pulse/builder.py +++ b/qiskit/pulse/builder.py @@ -38,38 +38,39 @@ execution. For example, to play a series of pulses on channels is as simple as: -.. jupyter-execute:: +.. plot:: + :include-source: - from qiskit import pulse - - dc = pulse.DriveChannel - d0, d1, d2, d3, d4 = dc(0), dc(1), dc(2), dc(3), dc(4) + from qiskit import pulse - with pulse.build(name='pulse_programming_in') as pulse_prog: - pulse.play([1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1], d0) - pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0], d1) - pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0], d2) - pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0], d3) - pulse.play([1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0], d4) + dc = pulse.DriveChannel + d0, d1, d2, d3, d4 = dc(0), dc(1), dc(2), dc(3), dc(4) - pulse_prog.draw() + with pulse.build(name='pulse_programming_in') as pulse_prog: + pulse.play([1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1], d0) + pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0], d1) + pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0], d2) + pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0], d3) + pulse.play([1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0], d4) + pulse_prog.draw() To begin pulse programming we must first initialize our program builder context with :func:`build`, after which we can begin adding program statements. For example, below we write a simple program that :func:`play`\s a pulse: -.. jupyter-execute:: +.. plot:: + :include-source: - from qiskit import execute, pulse + from qiskit import execute, pulse - d0 = pulse.DriveChannel(0) + d0 = pulse.DriveChannel(0) - with pulse.build() as pulse_prog: - pulse.play(pulse.Constant(100, 1.0), d0) + with pulse.build() as pulse_prog: + pulse.play(pulse.Constant(100, 1.0), d0) - pulse_prog.draw() + pulse_prog.draw() The builder initializes a :class:`.pulse.Schedule`, ``pulse_prog`` and then begins to construct the program within the context. The output pulse @@ -88,31 +89,32 @@ state we prepared. This program which mixes circuits and pulses will be automatically lowered to be run as a pulse program: -.. jupyter-execute:: +.. plot:: + :include-source: - import math + import math - from qiskit import pulse - from qiskit.providers.fake_provider import FakeOpenPulse3Q + from qiskit import pulse + from qiskit.providers.fake_provider import FakeOpenPulse3Q - # TODO: This example should use a real mock backend. - backend = FakeOpenPulse3Q() + # TODO: This example should use a real mock backend. + backend = FakeOpenPulse3Q() - d2 = pulse.DriveChannel(2) + d2 = pulse.DriveChannel(2) - with pulse.build(backend) as bell_prep: - pulse.u2(0, math.pi, 0) - pulse.cx(0, 1) + with pulse.build(backend) as bell_prep: + pulse.u2(0, math.pi, 0) + pulse.cx(0, 1) - with pulse.build(backend) as decoupled_bell_prep_and_measure: - # We call our bell state preparation schedule constructed above. - with pulse.align_right(): - pulse.call(bell_prep) - pulse.play(pulse.Constant(bell_prep.duration, 0.02), d2) - pulse.barrier(0, 1, 2) - registers = pulse.measure_all() + with pulse.build(backend) as decoupled_bell_prep_and_measure: + # We call our bell state preparation schedule constructed above. + with pulse.align_right(): + pulse.call(bell_prep) + pulse.play(pulse.Constant(bell_prep.duration, 0.02), d2) + pulse.barrier(0, 1, 2) + registers = pulse.measure_all() - decoupled_bell_prep_and_measure.draw() + decoupled_bell_prep_and_measure.draw() With the pulse builder we are able to blend programming on qubits and channels. While the pulse schedule is based on instructions that operate on @@ -121,110 +123,110 @@ In the example below we demonstrate some more features of the pulse builder: -.. jupyter-execute:: - - import math - - from qiskit import pulse, QuantumCircuit - from qiskit.pulse import library - from qiskit.providers.fake_provider import FakeOpenPulse2Q - - backend = FakeOpenPulse2Q() - - with pulse.build(backend) as pulse_prog: - # Create a pulse. - gaussian_pulse = library.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) - # Play a pulse at t=0. - pulse.play(gaussian_pulse, d0) - # Play another pulse directly after the previous pulse at t=10. - pulse.play(gaussian_pulse, d0) - # The default scheduling behavior is to schedule pulses in parallel - # across channels. For example, the statement below - # plays the same pulse on a different channel at t=0. - pulse.play(gaussian_pulse, d1) - - # We also provide pulse scheduling alignment contexts. - # The default alignment context is align_left. - - # The sequential context schedules pulse instructions sequentially in time. - # This context starts at t=10 due to earlier pulses above. - with pulse.align_sequential(): - pulse.play(gaussian_pulse, d0) - # Play another pulse after at t=20. - pulse.play(gaussian_pulse, d1) - - # We can also nest contexts as each instruction is - # contained in its local scheduling context. - # The output of a child context is a context-schedule - # with the internal instructions timing fixed relative to - # one another. This is schedule is then called in the parent context. - - # Context starts at t=30. - with pulse.align_left(): - # Start at t=30. - pulse.play(gaussian_pulse, d0) - # Start at t=30. - pulse.play(gaussian_pulse, d1) - # Context ends at t=40. - - # Alignment context where all pulse instructions are - # aligned to the right, ie., as late as possible. - with pulse.align_right(): - # Shift the phase of a pulse channel. - pulse.shift_phase(math.pi, d1) - # Starts at t=40. - pulse.delay(100, d0) - # Ends at t=140. - - # Starts at t=130. - pulse.play(gaussian_pulse, d1) - # Ends at t=140. - - # Acquire data for a qubit and store in a memory slot. - pulse.acquire(100, 0, pulse.MemorySlot(0)) - - # We also support a variety of macros for common operations. - - # Measure all qubits. - pulse.measure_all() - - # Delay on some qubits. - # This requires knowledge of which channels belong to which qubits. - # delay for 100 cycles on qubits 0 and 1. - pulse.delay_qubits(100, 0, 1) - - # Call a quantum circuit. The pulse builder lazily constructs a quantum - # circuit which is then transpiled and scheduled before inserting into - # a pulse schedule. - # NOTE: Quantum register indices correspond to physical qubit indices. - qc = QuantumCircuit(2, 2) - qc.cx(0, 1) - pulse.call(qc) - # Calling a small set of standard gates and decomposing to pulses is - # also supported with more natural syntax. - pulse.u3(0, math.pi, 0, 0) - pulse.cx(0, 1) - - - # It is also be possible to call a preexisting schedule - tmp_sched = pulse.Schedule() - tmp_sched += pulse.Play(gaussian_pulse, d0) - pulse.call(tmp_sched) - - # We also support: - - # frequency instructions - pulse.set_frequency(5.0e9, d0) - - # phase instructions - pulse.shift_phase(0.1, d0) - - # offset contexts - with pulse.phase_offset(math.pi, d0): - pulse.play(gaussian_pulse, d0) +.. code-block:: + + import math + + from qiskit import pulse, QuantumCircuit + from qiskit.pulse import library + from qiskit.providers.fake_provider import FakeOpenPulse2Q + + backend = FakeOpenPulse2Q() + + with pulse.build(backend) as pulse_prog: + # Create a pulse. + gaussian_pulse = library.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) + # Play a pulse at t=0. + pulse.play(gaussian_pulse, d0) + # Play another pulse directly after the previous pulse at t=10. + pulse.play(gaussian_pulse, d0) + # The default scheduling behavior is to schedule pulses in parallel + # across channels. For example, the statement below + # plays the same pulse on a different channel at t=0. + pulse.play(gaussian_pulse, d1) + + # We also provide pulse scheduling alignment contexts. + # The default alignment context is align_left. + + # The sequential context schedules pulse instructions sequentially in time. + # This context starts at t=10 due to earlier pulses above. + with pulse.align_sequential(): + pulse.play(gaussian_pulse, d0) + # Play another pulse after at t=20. + pulse.play(gaussian_pulse, d1) + + # We can also nest contexts as each instruction is + # contained in its local scheduling context. + # The output of a child context is a context-schedule + # with the internal instructions timing fixed relative to + # one another. This is schedule is then called in the parent context. + + # Context starts at t=30. + with pulse.align_left(): + # Start at t=30. + pulse.play(gaussian_pulse, d0) + # Start at t=30. + pulse.play(gaussian_pulse, d1) + # Context ends at t=40. + + # Alignment context where all pulse instructions are + # aligned to the right, ie., as late as possible. + with pulse.align_right(): + # Shift the phase of a pulse channel. + pulse.shift_phase(math.pi, d1) + # Starts at t=40. + pulse.delay(100, d0) + # Ends at t=140. + + # Starts at t=130. + pulse.play(gaussian_pulse, d1) + # Ends at t=140. + + # Acquire data for a qubit and store in a memory slot. + pulse.acquire(100, 0, pulse.MemorySlot(0)) + + # We also support a variety of macros for common operations. + + # Measure all qubits. + pulse.measure_all() + + # Delay on some qubits. + # This requires knowledge of which channels belong to which qubits. + # delay for 100 cycles on qubits 0 and 1. + pulse.delay_qubits(100, 0, 1) + + # Call a quantum circuit. The pulse builder lazily constructs a quantum + # circuit which is then transpiled and scheduled before inserting into + # a pulse schedule. + # NOTE: Quantum register indices correspond to physical qubit indices. + qc = QuantumCircuit(2, 2) + qc.cx(0, 1) + pulse.call(qc) + # Calling a small set of standard gates and decomposing to pulses is + # also supported with more natural syntax. + pulse.u3(0, math.pi, 0, 0) + pulse.cx(0, 1) + + + # It is also be possible to call a preexisting schedule + tmp_sched = pulse.Schedule() + tmp_sched += pulse.Play(gaussian_pulse, d0) + pulse.call(tmp_sched) + + # We also support: + + # frequency instructions + pulse.set_frequency(5.0e9, d0) + + # phase instructions + pulse.shift_phase(0.1, d0) + + # offset contexts + with pulse.phase_offset(math.pi, d0): + pulse.play(gaussian_pulse, d0) The above is just a small taste of what is possible with the builder. See the rest of the module documentation for more information on its capabilities. @@ -240,7 +242,7 @@ Methods to return the correct channels for the respective qubit indices. -.. jupyter-execute:: +.. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeArmonk @@ -251,6 +253,9 @@ d0 = pulse.drive_channel(0) print(d0) +.. parsed-literal:: + + DriveChannel(0) .. autosummary:: :toctree: ../stubs/ @@ -266,7 +271,8 @@ Pulse instructions are available within the builder interface. Here's an example: -.. jupyter-execute:: +.. plot:: + :include-source: from qiskit import pulse from qiskit.providers.fake_provider import FakeArmonk @@ -317,21 +323,22 @@ example an alignment context like :func:`align_right` may be used to align all pulses as late as possible in a pulse program. -.. jupyter-execute:: +.. plot:: + :include-source: - from qiskit import pulse + from qiskit import pulse - d0 = pulse.DriveChannel(0) - d1 = pulse.DriveChannel(1) + d0 = pulse.DriveChannel(0) + d1 = pulse.DriveChannel(1) - with pulse.build() as pulse_prog: - with pulse.align_right(): - # this pulse will start at t=0 - pulse.play(pulse.Constant(100, 1.0), d0) - # this pulse will start at t=80 - pulse.play(pulse.Constant(20, 1.0), d1) + with pulse.build() as pulse_prog: + with pulse.align_right(): + # this pulse will start at t=0 + pulse.play(pulse.Constant(100, 1.0), d0) + # this pulse will start at t=80 + pulse.play(pulse.Constant(20, 1.0), d1) - pulse_prog.draw() + pulse_prog.draw() .. autosummary:: :toctree: ../stubs/ @@ -352,7 +359,7 @@ Macros help you add more complex functionality to your pulse program. -.. jupyter-execute:: +.. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeArmonk @@ -363,6 +370,10 @@ mem_slot = pulse.measure(0) print(mem_slot) +.. parsed-literal:: + + MemorySlot(0) + .. autosummary:: :toctree: ../stubs/ @@ -382,7 +393,7 @@ builder interface in which it will be possible to calibrate a gate in terms of pulses and use that gate in a circuit. -.. jupyter-execute:: +.. code-block:: import math @@ -410,7 +421,7 @@ The utility functions can be used to gather attributes about the backend and modify how the program is built. -.. jupyter-execute:: +.. code-block:: from qiskit import pulse @@ -429,6 +440,12 @@ print('There are {} seconds in {} samples.'.format( seconds, pulse.seconds_to_samples(1e-6))) +.. parsed-literal:: + + Number of qubits in backend: 1 + There are 160 samples in 3.5555555555555554e-08 seconds + There are 1e-06 seconds in 4500 samples. + .. autosummary:: :toctree: ../stubs/ @@ -954,7 +971,7 @@ def build( To enter a building context and starting building a pulse program: - .. jupyter-execute:: + .. code-block:: from qiskit import execute, pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q @@ -1054,7 +1071,7 @@ def append_instruction(instruction: instructions.Instruction): Examples: - .. jupyter-execute:: + .. code-block:: from qiskit import pulse @@ -1064,6 +1081,10 @@ def append_instruction(instruction: instructions.Instruction): pulse.builder.append_instruction(pulse.Delay(10, d0)) print(pulse_prog.instructions) + + .. parsed-literal:: + + ((0, Delay(10, DriveChannel(0))),) """ _active_builder().append_instruction(instruction) @@ -1073,7 +1094,7 @@ def num_qubits() -> int: Examples: - .. jupyter-execute:: + .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q @@ -1083,6 +1104,10 @@ def num_qubits() -> int: with pulse.build(backend): print(pulse.num_qubits()) + .. parsed-literal:: + + 2 + .. note:: Requires the active builder context to have a backend set. """ return active_backend().configuration().n_qubits @@ -1123,7 +1148,7 @@ def qubit_channels(qubit: int) -> Set[chans.Channel]: Examples: - .. jupyter-execute:: + .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q @@ -1133,6 +1158,10 @@ def qubit_channels(qubit: int) -> Set[chans.Channel]: with pulse.build(backend): print(pulse.qubit_channels(0)) + .. parsed-literal:: + + {MeasureChannel(0), ControlChannel(0), DriveChannel(0), AcquireChannel(0), ControlChannel(1)} + .. note:: Requires the active builder context to have a backend set. .. note:: A channel may still be associated with another qubit in this list @@ -1162,7 +1191,7 @@ def active_transpiler_settings() -> Dict[str, Any]: Examples: - .. jupyter-execute:: + .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q @@ -1175,6 +1204,10 @@ def active_transpiler_settings() -> Dict[str, Any]: default_transpiler_settings=transpiler_settings): print(pulse.active_transpiler_settings()) + .. parsed-literal:: + + {'optimization_level': 3} + """ return dict(_active_builder().transpiler_settings) @@ -1184,7 +1217,7 @@ def active_circuit_scheduler_settings() -> Dict[str, Any]: # pylint: disable=in Examples: - .. jupyter-execute:: + .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q @@ -1198,6 +1231,10 @@ def active_circuit_scheduler_settings() -> Dict[str, Any]: # pylint: disable=in default_circuit_scheduler_settings=circuit_scheduler_settings): print(pulse.active_circuit_scheduler_settings()) + .. parsed-literal:: + + {'method': 'alap'} + """ return dict(_active_builder().circuit_scheduler_settings) @@ -1214,7 +1251,7 @@ def align_left() -> ContextManager[None]: Examples: - .. jupyter-execute:: + .. code-block:: from qiskit import pulse @@ -1252,7 +1289,7 @@ def align_right() -> AlignmentKind: Examples: - .. jupyter-execute:: + .. code-block:: from qiskit import pulse @@ -1290,7 +1327,7 @@ def align_sequential() -> AlignmentKind: Examples: - .. jupyter-execute:: + .. code-block:: from qiskit import pulse @@ -1334,7 +1371,8 @@ def align_equispaced(duration: Union[int, ParameterExpression]) -> AlignmentKind Examples: - .. jupyter-execute:: + .. plot:: + :include-source: from qiskit import pulse @@ -1386,7 +1424,8 @@ def align_func( Examples: - .. jupyter-execute:: + .. plot:: + :include-source: import numpy as np from qiskit import pulse @@ -1463,7 +1502,7 @@ def transpiler_settings(**settings) -> ContextManager[None]: Examples: - .. jupyter-execute:: + .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q @@ -1474,6 +1513,11 @@ def transpiler_settings(**settings) -> ContextManager[None]: print(pulse.active_transpiler_settings()) with pulse.transpiler_settings(optimization_level=3): print(pulse.active_transpiler_settings()) + + .. parsed-literal:: + + {} + {'optimization_level': 3} """ builder = _active_builder() curr_transpiler_settings = builder.transpiler_settings @@ -1490,7 +1534,7 @@ def circuit_scheduler_settings(**settings) -> ContextManager[None]: Examples: - .. jupyter-execute:: + .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q @@ -1501,6 +1545,12 @@ def circuit_scheduler_settings(**settings) -> ContextManager[None]: print(pulse.active_circuit_scheduler_settings()) with pulse.circuit_scheduler_settings(method='alap'): print(pulse.active_circuit_scheduler_settings()) + + .. parsed-literal:: + + {} + {'method': 'alap'} + """ builder = _active_builder() curr_circuit_scheduler_settings = builder.circuit_scheduler_settings @@ -1519,7 +1569,7 @@ def phase_offset(phase: float, *channels: chans.PulseChannel) -> ContextManager[ Examples: - .. jupyter-execute:: + .. code-block:: import math @@ -1618,7 +1668,7 @@ def drive_channel(qubit: int) -> chans.DriveChannel: Examples: - .. jupyter-execute:: + .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q @@ -1638,7 +1688,7 @@ def measure_channel(qubit: int) -> chans.MeasureChannel: Examples: - .. jupyter-execute:: + .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q @@ -1658,7 +1708,7 @@ def acquire_channel(qubit: int) -> chans.AcquireChannel: Examples: - .. jupyter-execute:: + .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q @@ -1681,7 +1731,7 @@ def control_channels(*qubits: Iterable[int]) -> List[chans.ControlChannel]: Examples: - .. jupyter-execute:: + .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q @@ -1709,7 +1759,7 @@ def delay(duration: int, channel: chans.Channel, name: Optional[str] = None): Examples: - .. jupyter-execute:: + .. code-block:: from qiskit import pulse @@ -1733,7 +1783,7 @@ def play( Examples: - .. jupyter-execute:: + .. code-block:: from qiskit import pulse @@ -1764,7 +1814,7 @@ def acquire( Examples: - .. jupyter-execute:: + .. code-block:: from qiskit import pulse @@ -1811,7 +1861,7 @@ def set_frequency(frequency: float, channel: chans.PulseChannel, name: Optional[ Examples: - .. jupyter-execute:: + .. code-block:: from qiskit import pulse @@ -1881,7 +1931,7 @@ def shift_phase(phase: float, channel: chans.PulseChannel, name: Optional[str] = Examples: - .. jupyter-execute:: + .. code-block:: import math @@ -1905,7 +1955,7 @@ def snapshot(label: str, snapshot_type: str = "statevector"): Examples: - .. jupyter-execute:: + .. code-block:: from qiskit import pulse @@ -1943,7 +1993,7 @@ def call( 1. Calling a schedule block (recommended) - .. jupyter-execute:: + .. code-block:: from qiskit import circuit, pulse from qiskit.providers.fake_provider import FakeBogotaV2 @@ -1958,15 +2008,35 @@ def call( print(pulse_prog) + .. parsed-literal:: + + ScheduleBlock( + ScheduleBlock( + Play( + Gaussian(duration=160, amp=(0.1+0j), sigma=40), + DriveChannel(0) + ), + name="block0", + transform=AlignLeft() + ), + name="block1", + transform=AlignLeft() + ) + The actual program is stored in the reference table attached to the schedule. - .. jupyter-execute:: + .. code-block:: print(pulse_prog.references) + .. parsed-literal:: + + ReferenceManager: + - ('block0', '634b3b50bd684e26a673af1fbd2d6c81'): ScheduleBlock(Play(Gaussian(... + In addition, you can call a parameterized target program with parameter assignment. - .. jupyter-execute:: + .. code-block:: amp = circuit.Parameter("amp") @@ -1979,10 +2049,33 @@ def call( print(pulse_prog) + .. parsed-literal:: + + ScheduleBlock( + ScheduleBlock( + Play( + Gaussian(duration=160, amp=(0.1+0j), sigma=40), + DriveChannel(0) + ), + name="block2", + transform=AlignLeft() + ), + ScheduleBlock( + Play( + Gaussian(duration=160, amp=(0.3+0j), sigma=40), + DriveChannel(0) + ), + name="block2", + transform=AlignLeft() + ), + name="block3", + transform=AlignLeft() + ) + If there is a name collision between parameters, you can distinguish them by specifying each parameter object in a python dictionary. For example, - .. jupyter-execute:: + .. code-block:: amp1 = circuit.Parameter('amp') amp2 = circuit.Parameter('amp') @@ -1996,9 +2089,22 @@ def call( print(pulse_prog) + .. parsed-literal:: + + ScheduleBlock( + ScheduleBlock( + Play(Gaussian(duration=160, amp=(0.1+0j), sigma=40), DriveChannel(0)), + Play(Gaussian(duration=160, amp=(0.3+0j), sigma=40), DriveChannel(1)), + name="block4", + transform=AlignLeft() + ), + name="block5", + transform=AlignLeft() + ) + 2. Calling a schedule - .. jupyter-execute:: + .. code-block:: x_sched = backend.instruction_schedule_map.get("x", (0,)) @@ -2007,13 +2113,40 @@ def call( print(pulse_prog) + .. parsed-literal:: + + ScheduleBlock( + Call( + Schedule( + ( + 0, + Play( + Drag( + duration=160, + amp=(0.18989731546729305+0j), + sigma=40, + beta=-1.201258305015517, + name='drag_86a8' + ), + DriveChannel(0), + name='drag_86a8' + ) + ), + name="x" + ), + name='x' + ), + name="block6", + transform=AlignLeft() + ) + Currently, the backend calibrated gates are provided in the form of :class:`~.Schedule`. The parameter assignment mechanism is available also for schedules. However, the called schedule is not treated as a reference. 3. Calling a quantum circuit - .. jupyter-execute:: + .. code-block:: backend = FakeBogotaV2() @@ -2025,6 +2158,33 @@ def call( print(pulse_prog) + .. parsed-literal:: + + ScheduleBlock( + Call( + Schedule( + ( + 0, + Play( + Drag( + duration=160, + amp=(0.18989731546729305+0j), + sigma=40, + beta=-1.201258305015517, + name='drag_86a8' + ), + DriveChannel(0), + name='drag_86a8' + ) + ), + name="circuit-87" + ), + name='circuit-87' + ), + name="block7", + transform=AlignLeft() + ) + .. warning:: Calling a circuit from a schedule is not encouraged. Currently, the Qiskit execution model @@ -2082,10 +2242,7 @@ def barrier(*channels_or_qubits: Union[chans.Channel, int], name: Optional[str] the barrier. Consider the case where we want to enforce that one pulse happens after another on separate channels, this can be done with: - .. jupyter-kernel:: python3 - :id: barrier - - .. jupyter-execute:: + .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q @@ -2102,7 +2259,7 @@ def barrier(*channels_or_qubits: Union[chans.Channel, int], name: Optional[str] Of course this could have been accomplished with: - .. jupyter-execute:: + .. code-block:: from qiskit.pulse import transforms @@ -2121,7 +2278,7 @@ def barrier(*channels_or_qubits: Union[chans.Channel, int], name: Optional[str] in the case where we are calling an outside circuit or schedule and want to align a pulse at the end of one call: - .. jupyter-execute:: + .. code-block:: import math @@ -2163,7 +2320,8 @@ def macro(func: Callable): Examples: - .. jupyter-execute:: + .. plot:: + :include-source: from qiskit import pulse @@ -2221,10 +2379,7 @@ def measure( To use the measurement it is as simple as specifying the qubit you wish to measure: - .. jupyter-kernel:: python3 - :id: measure - - .. jupyter-execute:: + .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q @@ -2244,7 +2399,7 @@ def measure( future we will support using this handle to a result register to build up ones program. It is also possible to supply this register: - .. jupyter-execute:: + .. code-block:: with pulse.build(backend) as pulse_prog: pulse.play(pulse.Constant(100, 1.0), qubit_drive_chan) @@ -2308,7 +2463,7 @@ def measure_all() -> List[chans.MemorySlot]: Examples: - .. jupyter-execute:: + .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q @@ -2348,7 +2503,7 @@ def delay_qubits(duration: int, *qubits: Union[int, Iterable[int]]): Examples: - .. jupyter-execute:: + .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse3Q @@ -2382,12 +2537,9 @@ def call_gate(gate: circuit.Gate, qubits: Tuple[int, ...], lazy: bool = True): deprecated in the future in favor of tight integration with a circuit builder interface which is under development. - .. jupyter-kernel:: python3 - :id: call_gate - Examples: - .. jupyter-execute:: + .. code-block:: from qiskit import pulse from qiskit.pulse import builder @@ -2402,7 +2554,7 @@ def call_gate(gate: circuit.Gate, qubits: Tuple[int, ...], lazy: bool = True): We can see the role of the transpiler in scheduling gates by optimizing away two consecutive CNOT gates: - .. jupyter-execute:: + .. code-block:: with pulse.build(backend) as pulse_prog: with pulse.transpiler_settings(optimization_level=3): @@ -2440,7 +2592,7 @@ def cx(control: int, target: int): # pylint: disable=invalid-name Examples: - .. jupyter-execute:: + .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q @@ -2465,7 +2617,7 @@ def u1(theta: float, qubit: int): # pylint: disable=invalid-name Examples: - .. jupyter-execute:: + .. code-block:: import math @@ -2492,7 +2644,7 @@ def u2(phi: float, lam: float, qubit: int): # pylint: disable=invalid-name Examples: - .. jupyter-execute:: + .. code-block:: import math @@ -2519,7 +2671,7 @@ def u3(theta: float, phi: float, lam: float, qubit: int): # pylint: disable=inv Examples: - .. jupyter-execute:: + .. code-block:: import math @@ -2546,7 +2698,7 @@ def x(qubit: int): Examples: - .. jupyter-execute:: + .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q diff --git a/qiskit/pulse/library/discrete.py b/qiskit/pulse/library/discrete.py index 4d14d0799a65..5195cbaa17c6 100644 --- a/qiskit/pulse/library/discrete.py +++ b/qiskit/pulse/library/discrete.py @@ -121,17 +121,19 @@ def sawtooth( name: Name of pulse. Example: - .. jupyter-execute:: - - import matplotlib.pyplot as plt - from qiskit.pulse.library import sawtooth - import numpy as np - - duration = 100 - amp = 1 - freq = 1 / duration - sawtooth_wave = np.real(sawtooth(duration, amp, freq).samples) - plt.plot(range(duration), sawtooth_wave) + .. plot:: + :include-source: + + import matplotlib.pyplot as plt + from qiskit.pulse.library import sawtooth + import numpy as np + + duration = 100 + amp = 1 + freq = 1 / duration + sawtooth_wave = np.real(sawtooth(duration, amp, freq).samples) + plt.plot(range(duration), sawtooth_wave) + plt.show() """ if freq is None: freq = 1.0 / duration @@ -165,17 +167,19 @@ def triangle( name: Name of pulse. Example: - .. jupyter-execute:: - - import matplotlib.pyplot as plt - from qiskit.pulse.library import triangle - import numpy as np - - duration = 100 - amp = 1 - freq = 1 / duration - triangle_wave = np.real(triangle(duration, amp, freq).samples) - plt.plot(range(duration), triangle_wave) + .. plot:: + :include-source: + + import matplotlib.pyplot as plt + from qiskit.pulse.library import triangle + import numpy as np + + duration = 100 + amp = 1 + freq = 1 / duration + triangle_wave = np.real(triangle(duration, amp, freq).samples) + plt.plot(range(duration), triangle_wave) + plt.show() """ if freq is None: freq = 1.0 / duration diff --git a/qiskit/pulse/library/symbolic_pulses.py b/qiskit/pulse/library/symbolic_pulses.py index 713265c47a46..f66ef55310ff 100644 --- a/qiskit/pulse/library/symbolic_pulses.py +++ b/qiskit/pulse/library/symbolic_pulses.py @@ -304,7 +304,7 @@ class SymbolicPulse(Pulse): This is how a user can instantiate a symbolic pulse instance. In this example, we instantiate a custom `Sawtooth` envelope. - .. jupyter-execute:: + .. code-block:: from qiskit.pulse.library import SymbolicPulse @@ -319,9 +319,11 @@ class SymbolicPulse(Pulse): the envelope and constraints. However, this instance cannot generate waveforms without knowing the envelope definition. Now you need to provide the envelope. - .. jupyter-execute:: + .. plot:: + :include-source: import sympy + from qiskit.pulse.library import SymbolicPulse t, amp, freq = sympy.symbols("t, amp, freq") envelope = 2 * amp * (freq * t - sympy.floor(1 / 2 + freq * t)) diff --git a/qiskit/pulse/schedule.py b/qiskit/pulse/schedule.py index 7d2fc115bc85..c501b9a8a04b 100644 --- a/qiskit/pulse/schedule.py +++ b/qiskit/pulse/schedule.py @@ -633,10 +633,7 @@ def replace( The replacement matching is based on an instruction equality check. - .. jupyter-kernel:: python3 - :id: replace - - .. jupyter-execute:: + .. code-block:: from qiskit import pulse @@ -657,7 +654,7 @@ def replace( perform this replacement over all instructions in the schedule tree. Flatten the schedule prior to running:: - .. jupyter-execute:: + .. code-block:: sched = pulse.Schedule() @@ -888,7 +885,7 @@ class ScheduleBlock: can be a hard task. Schedule block offers a convenient feature to help with this by automatically scoping the parameters and subroutines. - .. jupyter-execute:: + .. code-block:: from qiskit import pulse from qiskit.circuit.parameter import Parameter @@ -900,6 +897,10 @@ class ScheduleBlock: print(sched1.scoped_parameters()) + .. parsed-literal:: + + (Parameter(root::amp),) + The :meth:`~ScheduleBlock.scoped_parameters` method returns all :class:`~.Parameter` objects defined in the schedule block. The parameter name is updated to reflect its scope information, i.e. where it is defined. @@ -914,7 +915,7 @@ class ScheduleBlock: You can call a subroutine without specifying a substantial program (like ``sched1`` above which we will assign later). - .. jupyter-execute:: + .. code-block:: amp2 = Parameter("amp") @@ -925,28 +926,41 @@ class ScheduleBlock: print(sched2.scoped_parameters()) + .. parsed-literal:: + + (Parameter(root::amp),) + This only returns "root::amp" because the "grand_child" reference is unknown. Now you assign the actual pulse program to this reference. - .. jupyter-execute:: + .. code-block:: sched2.assign_references({("grand_child", ): sched1}) print(sched2.scoped_parameters()) + .. parsed-literal:: + + (Parameter(root::amp), Parameter(root::grand_child::amp)) + Now you get two parameters "root::amp" and "root::grand_child::amp". The second parameter name indicates it is defined within the referred program "grand_child". The program calling the "grand_child" has a reference program description which is accessed through :attr:`ScheduleBlock.references`. - .. jupyter-execute:: + .. code-block:: print(sched2.references) + .. parsed-literal:: + + ReferenceManager: + - ('grand_child',): ScheduleBlock(Play(Constant(duration=100, amp=amp,... + Finally, you may want to call this program from another program. Here we try a different approach to define subroutine. Namely, we call a subroutine from the root program with the actual program ``sched2``. - .. jupyter-execute:: + .. code-block:: amp3 = Parameter("amp") @@ -956,6 +970,10 @@ class ScheduleBlock: print(main.scoped_parameters()) + .. parsed-literal:: + + (Parameter(root::amp), Parameter(root::child::amp), Parameter(root::child::grand_child::amp)) + This implicitly creates a reference named "child" within the root program and assigns ``sched2`` to it. You get three parameters "root::amp", "root::child::amp", and "root::child::grand_child::amp". @@ -963,7 +981,7 @@ class ScheduleBlock: If you know the scope of a parameter, you can directly get the parameter object using :meth:`ScheduleBlock.search_parameters` as follows. - .. jupyter-execute:: + .. code-block:: main.search_parameters("root::child::grand_child::amp") @@ -972,22 +990,27 @@ class ScheduleBlock: regardless of its parent scope. This is sometimes convenient if you want to extract parameters from a deeply nested program. - .. jupyter-execute:: + .. code-block:: main.search_parameters("\\S::grand_child::amp") Note that the root program is only aware of its direct references. - .. jupyter-execute:: + .. code-block:: print(main.references) + .. parsed-literal:: + + ReferenceManager: + - ('child',): ScheduleBlock(ScheduleBlock(ScheduleBlock(Play(Con... + As you can see the main program cannot directly assign a subroutine to the "grand_child" because this subroutine is not called within the root program, i.e. it is indirectly called by "child". However, the returned :class:`.ReferenceManager` is a dict-like object, and you can still reach to "grand_child" via the "child" program with the following chained dict access. - .. jupyter-execute:: + .. code-block:: main.references[("child", )].references[("grand_child", )] diff --git a/qiskit/pulse/transforms/canonicalization.py b/qiskit/pulse/transforms/canonicalization.py index 7cb7236b5910..ba9fc4d0f12d 100644 --- a/qiskit/pulse/transforms/canonicalization.py +++ b/qiskit/pulse/transforms/canonicalization.py @@ -264,10 +264,7 @@ def align_measures( correspond to the same qubit and the acquire/play instructions should be shifted together on these channels. - .. jupyter-kernel:: python3 - :id: align_measures - - .. jupyter-execute:: + .. code-block:: from qiskit import pulse from qiskit.pulse import transforms @@ -291,7 +288,7 @@ def align_measures( If it is desired to only shift acquisition and measurement stimulus instructions set the flag ``align_all=False``: - .. jupyter-execute:: + .. code-block:: aligned_sched, aligned_sched_shifted = transforms.align_measures( [sched, sched_shifted], diff --git a/qiskit/quantum_info/analysis/distance.py b/qiskit/quantum_info/analysis/distance.py index b37b06b48c0b..65f8e6e05f68 100644 --- a/qiskit/quantum_info/analysis/distance.py +++ b/qiskit/quantum_info/analysis/distance.py @@ -73,7 +73,7 @@ def hellinger_fidelity(dist_p, dist_q): Example: - .. jupyter-execute:: + .. code-block:: from qiskit import QuantumCircuit, execute, BasicAer from qiskit.quantum_info.analysis import hellinger_fidelity diff --git a/qiskit/quantum_info/operators/dihedral/dihedral.py b/qiskit/quantum_info/operators/dihedral/dihedral.py index 032deae55f66..af98e7b71163 100644 --- a/qiskit/quantum_info/operators/dihedral/dihedral.py +++ b/qiskit/quantum_info/operators/dihedral/dihedral.py @@ -45,7 +45,7 @@ class CNOTDihedral(BaseOperator, AdjointMixin): The phase polynomial is a polynomial of degree at most 3, in :math:`N` variables, whose coefficients are in the ring Z_8 with 8 elements. - .. jupyter-execute:: + .. code-block:: from qiskit import QuantumCircuit from qiskit.quantum_info import CNOTDihedral @@ -61,6 +61,14 @@ class CNOTDihedral(BaseOperator, AdjointMixin): # Print the CNOTDihedral element print(elem) + .. parsed-literal:: + + phase polynomial = + 0 + 3*x_0 + 3*x_1 + 2*x_0*x_1 + affine function = + (x_0,x_0 + x_1,x_2 + 1) + + **Circuit Conversion** CNOTDihedral operators can be initialized from circuits containing *only* the diff --git a/qiskit/quantum_info/operators/symplectic/clifford.py b/qiskit/quantum_info/operators/symplectic/clifford.py index 5342e5e916d4..e7c3e3590438 100644 --- a/qiskit/quantum_info/operators/symplectic/clifford.py +++ b/qiskit/quantum_info/operators/symplectic/clifford.py @@ -51,7 +51,7 @@ class Clifford(BaseOperator, AdjointMixin, Operation): be obtained by calling the :meth:`to_dict` method. This representation is also used if a Clifford object is printed as in the following example - .. jupyter-execute:: + .. code-block:: from qiskit import QuantumCircuit from qiskit.quantum_info import Clifford @@ -71,6 +71,12 @@ class Clifford(BaseOperator, AdjointMixin, Operation): # Print the Clifford stabilizer rows print(cliff.to_labels(mode="S")) + .. parsed-literal:: + + Clifford: Stabilizer = ['+XX', '+ZZ'], Destabilizer = ['+IZ', '+XI'] + ['+IZ', '+XI'] + ['+XX', '+ZZ'] + **Circuit Conversion** Clifford operators can be initialized from circuits containing *only* the diff --git a/qiskit/quantum_info/operators/symplectic/pauli_list.py b/qiskit/quantum_info/operators/symplectic/pauli_list.py index 3cf7f0399ecd..4d566110b7f0 100644 --- a/qiskit/quantum_info/operators/symplectic/pauli_list.py +++ b/qiskit/quantum_info/operators/symplectic/pauli_list.py @@ -51,7 +51,7 @@ class PauliList(BasePauli, LinearMixin, GroupMixin): For example, - .. jupyter-execute:: + .. code-block:: import numpy as np @@ -77,19 +77,32 @@ class PauliList(BasePauli, LinearMixin, GroupMixin): pauli_list = PauliList.from_symplectic(z, x, phase) print("4. ", pauli_list) + .. parsed-literal:: + + 1. ['II', 'ZI', '-iYY'] + 2. ['iXI'] + 3. ['iXI', 'iZZ'] + 4. ['YZ', '-iIX'] + **Data Access** The individual Paulis can be accessed and updated using the ``[]`` operator which accepts integer, lists, or slices for selecting subsets of PauliList. If integer is given, it returns Pauli not PauliList. - .. jupyter-execute:: + .. code-block:: pauli_list = PauliList(["XX", "ZZ", "IZ"]) print("Integer: ", repr(pauli_list[1])) print("List: ", repr(pauli_list[[0, 2]])) print("Slice: ", repr(pauli_list[0:2])) + .. parsed-literal:: + + Integer: Pauli('ZZ') + List: PauliList(['XX', 'IZ']) + Slice: PauliList(['XX', 'ZZ']) + **Iteration** Rows in the Pauli table can be iterated over like a list. Iteration can @@ -521,7 +534,7 @@ def sort(self, weight=False, phase=False): Consider sorting all a random ordering of all 2-qubit Paulis - .. jupyter-execute:: + .. code-block:: from numpy.random import shuffle from qiskit.quantum_info.operators import PauliList @@ -545,6 +558,18 @@ def sort(self, weight=False, phase=False): print('Weight sorted') print(srt) + .. parsed-literal:: + + Initial Ordering + ['YX', 'ZZ', 'XZ', 'YI', 'YZ', 'II', 'XX', 'XI', 'XY', 'YY', 'IX', 'IZ', + 'ZY', 'ZI', 'ZX', 'IY'] + Lexicographically sorted + ['II', 'IX', 'IY', 'IZ', 'XI', 'XX', 'XY', 'XZ', 'YI', 'YX', 'YY', 'YZ', + 'ZI', 'ZX', 'ZY', 'ZZ'] + Weight sorted + ['II', 'IX', 'IY', 'IZ', 'XI', 'YI', 'ZI', 'XX', 'XY', 'XZ', 'YX', 'YY', + 'YZ', 'ZX', 'ZY', 'ZZ'] + Args: weight (bool): optionally sort by weight if True (Default: False). phase (bool): Optionally sort by phase before weight or order @@ -560,7 +585,7 @@ def unique(self, return_index=False, return_counts=False): **Example** - .. jupyter-execute:: + .. code-block:: from qiskit.quantum_info.operators import PauliList @@ -568,6 +593,10 @@ def unique(self, return_index=False, return_counts=False): unique = pt.unique() print(unique) + .. parsed-literal:: + + ['X', 'Y', '-X', 'I', 'Z', 'iZ'] + Args: return_index (bool): If True, also return the indices that result in the unique array. diff --git a/qiskit/quantum_info/operators/symplectic/pauli_table.py b/qiskit/quantum_info/operators/symplectic/pauli_table.py index 52375cea385c..fc280410b999 100644 --- a/qiskit/quantum_info/operators/symplectic/pauli_table.py +++ b/qiskit/quantum_info/operators/symplectic/pauli_table.py @@ -426,7 +426,7 @@ def sort(self, weight=False): Consider sorting all a random ordering of all 2-qubit Paulis - .. jupyter-execute:: + .. code-block:: from numpy.random import shuffle from qiskit.quantum_info.operators import PauliTable @@ -450,6 +450,25 @@ def sort(self, weight=False): print('Weight sorted') print(srt) + + .. parsed-literal:: + + Initial Ordering + PauliTable: [ + 'IZ', 'XZ', 'ZY', 'YI', 'YZ', 'IX', 'II', 'ZI', 'IY', 'XY', 'XI', 'YY', 'ZX', + 'XX', 'ZZ', 'YX' + ] + Lexicographically sorted + PauliTable: [ + 'II', 'IX', 'IY', 'IZ', 'XI', 'XX', 'XY', 'XZ', 'YI', 'YX', 'YY', 'YZ', 'ZI', + 'ZX', 'ZY', 'ZZ' + ] + Weight sorted + PauliTable: [ + 'II', 'IX', 'IY', 'IZ', 'XI', 'YI', 'ZI', 'XX', 'XY', 'XZ', 'YX', 'YY', 'YZ', + 'ZX', 'ZY', 'ZZ' + ] + Args: weight (bool): optionally sort by weight if True (Default: False). @@ -463,7 +482,7 @@ def unique(self, return_index=False, return_counts=False): **Example** - .. jupyter-execute:: + .. code-block:: from qiskit.quantum_info.operators import PauliTable @@ -471,6 +490,10 @@ def unique(self, return_index=False, return_counts=False): unique = pt.unique() print(unique) + .. parsed-literal:: + + PauliTable: ['X', 'Y', 'I', 'Z'] + Args: return_index (bool): If True, also return the indices that result in the unique array. @@ -522,7 +545,7 @@ def tensor(self, other): **Example** - .. jupyter-execute:: + .. code-block:: from qiskit.quantum_info.operators import PauliTable @@ -530,6 +553,10 @@ def tensor(self, other): other = PauliTable.from_labels(['Y', 'Z']) print(current.tensor(other)) + .. parsed-literal:: + + PauliTable: ['IY', 'IZ', 'XY', 'XZ'] + Args: other (PauliTable): another PauliTable. @@ -553,7 +580,7 @@ def expand(self, other): **Example** - .. jupyter-execute:: + .. code-block:: from qiskit.quantum_info.operators import PauliTable @@ -561,6 +588,10 @@ def expand(self, other): other = PauliTable.from_labels(['Y', 'Z']) print(current.expand(other)) + .. parsed-literal:: + + PauliTable: ['YI', 'YX', 'ZI', 'ZX'] + Args: other (PauliTable): another PauliTable. @@ -585,7 +616,7 @@ def compose(self, other, qargs=None, front=True): **Example** - .. jupyter-execute:: + .. code-block:: from qiskit.quantum_info.operators import PauliTable @@ -593,6 +624,10 @@ def compose(self, other, qargs=None, front=True): other = PauliTable.from_labels(['Y', 'Z']) print(current.compose(other)) + .. parsed-literal:: + + PauliTable: ['Y', 'Z', 'Z', 'Y'] + Args: other (PauliTable): another PauliTable. qargs (None or list): qubits to apply dot product on (Default: None). @@ -638,7 +673,7 @@ def dot(self, other, qargs=None): **Example** - .. jupyter-execute:: + .. code-block:: from qiskit.quantum_info.operators import PauliTable @@ -646,6 +681,10 @@ def dot(self, other, qargs=None): other = PauliTable.from_labels(['Y', 'Z']) print(current.dot(other)) + .. parsed-literal:: + + PauliTable: ['Y', 'Z', 'Z', 'Y'] + Args: other (PauliTable): another PauliTable. qargs (None or list): qubits to apply dot product on (Default: None). diff --git a/qiskit/quantum_info/operators/symplectic/sparse_pauli_op.py b/qiskit/quantum_info/operators/symplectic/sparse_pauli_op.py index ba46174653e8..538de22380f4 100644 --- a/qiskit/quantum_info/operators/symplectic/sparse_pauli_op.py +++ b/qiskit/quantum_info/operators/symplectic/sparse_pauli_op.py @@ -482,7 +482,7 @@ def argsort(self, weight=False): Here is an example of how to use SparsePauliOp argsort. - .. jupyter-execute:: + .. code-block:: import numpy as np from qiskit.quantum_info import SparsePauliOp @@ -512,6 +512,18 @@ def argsort(self, weight=False): print('Weight sorted') print(srt) + .. parsed-literal:: + + Initial Ordering + SparsePauliOp(['XX', 'XX', 'XX', 'YI', 'II', 'XZ', 'XY', 'XI'], + coeffs=[2.+1.j, 2.+2.j, 3.+0.j, 3.+0.j, 4.+0.j, 5.+0.j, 6.+0.j, 7.+0.j]) + Lexicographically sorted + [4 7 0 1 2 6 5 3] + Lexicographically sorted + [4 7 0 1 2 6 5 3] + Weight sorted + [4 7 3 0 1 2 6 5] + Args: weight (bool): optionally sort by weight if True (Default: False). By using the weight kwarg the output can additionally be sorted @@ -539,7 +551,7 @@ def sort(self, weight=False): Here is an example of how to use SparsePauliOp sort. - .. jupyter-execute:: + .. code-block:: import numpy as np from qiskit.quantum_info import SparsePauliOp @@ -569,6 +581,21 @@ def sort(self, weight=False): print('Weight sorted') print(srt) + .. parsed-literal:: + + Initial Ordering + SparsePauliOp(['XX', 'XX', 'XX', 'YI', 'II', 'XZ', 'XY', 'XI'], + coeffs=[2.+1.j, 2.+2.j, 3.+0.j, 3.+0.j, 4.+0.j, 5.+0.j, 6.+0.j, 7.+0.j]) + Lexicographically sorted + SparsePauliOp(['II', 'XI', 'XX', 'XX', 'XX', 'XY', 'XZ', 'YI'], + coeffs=[4.+0.j, 7.+0.j, 2.+1.j, 2.+2.j, 3.+0.j, 6.+0.j, 5.+0.j, 3.+0.j]) + Lexicographically sorted + SparsePauliOp(['II', 'XI', 'XX', 'XX', 'XX', 'XY', 'XZ', 'YI'], + coeffs=[4.+0.j, 7.+0.j, 2.+1.j, 2.+2.j, 3.+0.j, 6.+0.j, 5.+0.j, 3.+0.j]) + Weight sorted + SparsePauliOp(['II', 'XI', 'YI', 'XX', 'XX', 'XX', 'XY', 'XZ'], + coeffs=[4.+0.j, 7.+0.j, 3.+0.j, 2.+1.j, 2.+2.j, 3.+0.j, 6.+0.j, 5.+0.j]) + Args: weight (bool): optionally sort by weight if True (Default: False). By using the weight kwarg the output can additionally be sorted diff --git a/qiskit/quantum_info/operators/symplectic/stabilizer_table.py b/qiskit/quantum_info/operators/symplectic/stabilizer_table.py index 4aa708c9941a..8b0f62b471ab 100644 --- a/qiskit/quantum_info/operators/symplectic/stabilizer_table.py +++ b/qiskit/quantum_info/operators/symplectic/stabilizer_table.py @@ -376,7 +376,7 @@ def sort(self, weight=False): Consider sorting all a random ordering of all 2-qubit Paulis - .. jupyter-execute:: + .. code-block:: from numpy.random import shuffle from qiskit.quantum_info.operators import StabilizerTable @@ -402,6 +402,27 @@ def sort(self, weight=False): print('Weight sorted') print(srt) + .. parsed-literal:: + + Initial Ordering + StabilizerTable: [ + '-YZ', '+IX', '-ZI', '+II', '-IY', '-II', '-XI', '-IX', '-ZX', '-ZZ', '+XY', '+XZ', + '-YX', '-YI', '+ZI', '+ZX', '+ZY', '+IZ', '-ZY', '+YZ', '-IZ', '-XX', '+XI', '+YI', + '+XX', '+IY', '+ZZ', '-XY', '-YY', '+YX', '+YY', '-XZ' + ] + Lexicographically sorted + StabilizerTable: [ + '+II', '-II', '+IX', '-IX', '-IY', '+IY', '+IZ', '-IZ', '-XI', '+XI', '-XX', '+XX', + '+XY', '-XY', '+XZ', '-XZ', '-YI', '+YI', '-YX', '+YX', '-YY', '+YY', '-YZ', '+YZ', + '-ZI', '+ZI', '-ZX', '+ZX', '+ZY', '-ZY', '-ZZ', '+ZZ' + ] + Weight sorted + StabilizerTable: [ + '+II', '-II', '+IX', '-IX', '-IY', '+IY', '+IZ', '-IZ', '-XI', '+XI', '-YI', '+YI', + '-ZI', '+ZI', '-XX', '+XX', '+XY', '-XY', '+XZ', '-XZ', '-YX', '+YX', '-YY', '+YY', + '-YZ', '+YZ', '-ZX', '+ZX', '+ZY', '-ZY', '-ZZ', '+ZZ' + ] + Args: weight (bool): optionally sort by weight if True (Default: False). @@ -415,7 +436,7 @@ def unique(self, return_index=False, return_counts=False): **Example** - .. jupyter-execute:: + .. code-block:: from qiskit.quantum_info.operators import StabilizerTable @@ -423,6 +444,10 @@ def unique(self, return_index=False, return_counts=False): unique = st.unique() print(unique) + .. parsed-literal:: + + StabilizerTable: ['+X', '+I', '-I', '-X'] + Args: return_index (bool): If True, also return the indices that result in the unique array. @@ -477,7 +502,7 @@ def tensor(self, other): **Example** - .. jupyter-execute:: + .. code-block:: from qiskit.quantum_info.operators import StabilizerTable @@ -485,6 +510,10 @@ def tensor(self, other): other = StabilizerTable.from_labels(['-Y', '+Z']) print(current.tensor(other)) + .. parsed-literal:: + + StabilizerTable: ['-IY', '+IZ', '+XY', '-XZ'] + Args: other (StabilizerTable): another StabilizerTable. @@ -509,7 +538,7 @@ def expand(self, other): **Example** - .. jupyter-execute:: + .. code-block:: from qiskit.quantum_info.operators import StabilizerTable @@ -517,6 +546,10 @@ def expand(self, other): other = StabilizerTable.from_labels(['-Y', '+Z']) print(current.expand(other)) + .. parsed-literal:: + + StabilizerTable: ['-YI', '+YX', '+ZI', '-ZX'] + Args: other (StabilizerTable): another StabilizerTable. @@ -556,7 +589,7 @@ def compose(self, other, qargs=None, front=False): **Example** - .. jupyter-execute:: + .. code-block:: from qiskit.quantum_info.operators import StabilizerTable @@ -564,6 +597,10 @@ def compose(self, other, qargs=None, front=False): other = StabilizerTable.from_labels(['+X', '-Z']) print(current.compose(other)) + .. parsed-literal:: + + StabilizerTable: ['+X', '-Z', '-I', '-Y'] + Args: other (StabilizerTable): another StabilizerTable. qargs (None or list): qubits to apply compose product on @@ -634,7 +671,7 @@ def dot(self, other, qargs=None): **Example** - .. jupyter-execute:: + .. code-block:: from qiskit.quantum_info.operators import StabilizerTable @@ -642,6 +679,10 @@ def dot(self, other, qargs=None): other = StabilizerTable.from_labels(['+X', '-Z']) print(current.dot(other)) + .. parsed-literal:: + + StabilizerTable: ['+X', '-Z', '-I', '+Y'] + Args: other (StabilizerTable): another StabilizerTable. qargs (None or list): qubits to apply dot product on diff --git a/qiskit/quantum_info/states/densitymatrix.py b/qiskit/quantum_info/states/densitymatrix.py index 3231bd4709d8..435c02e535cf 100644 --- a/qiskit/quantum_info/states/densitymatrix.py +++ b/qiskit/quantum_info/states/densitymatrix.py @@ -430,7 +430,7 @@ def probabilities(self, qargs=None, decimals=None): with :math:`\\rho_1=|+\\rangle\\!\\langle+|`, :math:`\\rho_0=|0\\rangle\\!\\langle0|`. - .. jupyter-execute:: + .. code-block:: from qiskit.quantum_info import DensityMatrix @@ -448,10 +448,16 @@ def probabilities(self, qargs=None, decimals=None): probs_qubit_1 = rho.probabilities([1]) print('Qubit-1 probs: {}'.format(probs_qubit_1)) + .. parsed-literal:: + + probs: [0.5 0. 0.5 0. ] + Qubit-0 probs: [1. 0.] + Qubit-1 probs: [0.5 0.5] + We can also permute the order of qubits in the ``qargs`` list to change the qubit position in the probabilities output - .. jupyter-execute:: + .. code-block:: from qiskit.quantum_info import DensityMatrix @@ -465,6 +471,11 @@ def probabilities(self, qargs=None, decimals=None): # but swapping qubits 0 and 1 in output probs_swapped = rho.probabilities([1, 0]) print('Swapped probs: {}'.format(probs_swapped)) + + .. parsed-literal:: + + probs: [0.5 0. 0.5 0. ] + Swapped probs: [0.5 0.5 0. 0. ] """ probs = self._subsystem_probabilities( np.abs(self.data.diagonal()), self._op_shape.dims_l(), qargs=qargs @@ -619,17 +630,26 @@ def to_dict(self, decimals=None): The ket-form of a 2-qubit density matrix :math:`rho = |-\rangle\!\langle -|\otimes |0\rangle\!\langle 0|` - .. jupyter-execute:: + .. code-block:: from qiskit.quantum_info import DensityMatrix rho = DensityMatrix.from_label('-0') print(rho.to_dict()) + .. parsed-literal:: + + { + '00|00': (0.4999999999999999+0j), + '10|00': (-0.4999999999999999-0j), + '00|10': (-0.4999999999999999+0j), + '10|10': (0.4999999999999999+0j) + } + For non-qubit subsystems the integer range can go from 0 to 9. For example in a qutrit system - .. jupyter-execute:: + .. code-block:: import numpy as np from qiskit.quantum_info import DensityMatrix @@ -642,11 +662,15 @@ def to_dict(self, decimals=None): rho = DensityMatrix(mat, dims=(3, 3)) print(rho.to_dict()) + .. parsed-literal:: + + {'00|00': (0.25+0j), '10|10': (0.25+0j), '20|20': (0.25+0j), '22|22': (0.25+0j)} + For large subsystem dimensions delimiters are required. The following example is for a 20-dimensional system consisting of a qubit and 10-dimensional qudit. - .. jupyter-execute:: + .. code-block:: import numpy as np from qiskit.quantum_info import DensityMatrix @@ -656,6 +680,10 @@ def to_dict(self, decimals=None): mat[-1, -1] = 0.5 rho = DensityMatrix(mat, dims=(2, 10)) print(rho.to_dict()) + + .. parsed-literal:: + + {'00|00': (0.5+0j), '91|91': (0.5+0j)} """ return self._matrix_to_dict( self.data, self._op_shape.dims_l(), decimals=decimals, string_labels=True diff --git a/qiskit/quantum_info/states/stabilizerstate.py b/qiskit/quantum_info/states/stabilizerstate.py index f9394669d460..0fc62d6b3565 100644 --- a/qiskit/quantum_info/states/stabilizerstate.py +++ b/qiskit/quantum_info/states/stabilizerstate.py @@ -28,7 +28,7 @@ class StabilizerState(QuantumState): Stabilizer simulator using the convention from reference [1]. Based on the internal class :class:`~qiskit.quantum_info.Clifford`. - .. jupyter-execute:: + .. code-block:: from qiskit import QuantumCircuit from qiskit.quantum_info import StabilizerState, Pauli @@ -48,6 +48,12 @@ class StabilizerState(QuantumState): # Calculate expectation value of the StabilizerState print (stab.expectation_value(Pauli('ZZ'))) + .. parsed-literal:: + + StabilizerState(StabilizerTable: ['+XX', '+ZZ']) + {'00': 0.5, '11': 0.5} + 1 + References: 1. S. Aaronson, D. Gottesman, *Improved Simulation of Stabilizer Circuits*, Phys. Rev. A 70, 052328 (2004). diff --git a/qiskit/quantum_info/states/statevector.py b/qiskit/quantum_info/states/statevector.py index e3c03fa55d63..ec1cad44421f 100644 --- a/qiskit/quantum_info/states/statevector.py +++ b/qiskit/quantum_info/states/statevector.py @@ -170,12 +170,13 @@ def draw(self, output=None, **drawer_args): Plot one of the Bell states - .. jupyter-execute:: + .. plot:: + :include-source: from numpy import sqrt from qiskit.quantum_info import Statevector sv=Statevector([1/sqrt(2), 0, 0, -1/sqrt(2)]) - sv.draw(output='latex') + sv.draw(output='hinton') """ # pylint: disable=cyclic-import @@ -524,7 +525,7 @@ def probabilities(self, qargs=None, decimals=None): Consider a 2-qubit product state :math:`|\\psi\\rangle=|+\\rangle\\otimes|0\\rangle`. - .. jupyter-execute:: + .. code-block:: from qiskit.quantum_info import Statevector @@ -542,10 +543,16 @@ def probabilities(self, qargs=None, decimals=None): probs_qubit_1 = psi.probabilities([1]) print('Qubit-1 probs: {}'.format(probs_qubit_1)) + .. parsed-literal:: + + probs: [0.5 0. 0.5 0. ] + Qubit-0 probs: [1. 0.] + Qubit-1 probs: [0.5 0.5] + We can also permute the order of qubits in the ``qargs`` list to change the qubit position in the probabilities output - .. jupyter-execute:: + .. code-block:: from qiskit.quantum_info import Statevector @@ -559,6 +566,12 @@ def probabilities(self, qargs=None, decimals=None): # but swapping qubits 0 and 1 in output probs_swapped = psi.probabilities([1, 0]) print('Swapped probs: {}'.format(probs_swapped)) + + .. parsed-literal:: + + probs: [0.5 0. 0.5 0. ] + Swapped probs: [0.5 0.5 0. 0. ] + """ probs = self._subsystem_probabilities( np.abs(self.data) ** 2, self._op_shape.dims_l(), qargs=qargs @@ -758,17 +771,21 @@ def to_dict(self, decimals=None): The ket-form of a 2-qubit statevector :math:`|\psi\rangle = |-\rangle\otimes |0\rangle` - .. jupyter-execute:: + .. code-block:: from qiskit.quantum_info import Statevector psi = Statevector.from_label('-0') print(psi.to_dict()) + .. parsed-literal:: + + {'00': (0.7071067811865475+0j), '10': (-0.7071067811865475+0j)} + For non-qubit subsystems the integer range can go from 0 to 9. For example in a qutrit system - .. jupyter-execute:: + .. code-block:: import numpy as np from qiskit.quantum_info import Statevector @@ -779,11 +796,15 @@ def to_dict(self, decimals=None): psi = Statevector(vec, dims=(3, 3)) print(psi.to_dict()) + .. parsed-literal:: + + {'00': (0.7071067811865475+0j), '22': (0.7071067811865475+0j)} + For large subsystem dimensions delimiters are required. The following example is for a 20-dimensional system consisting of a qubit and 10-dimensional qudit. - .. jupyter-execute:: + .. code-block:: import numpy as np from qiskit.quantum_info import Statevector @@ -793,6 +814,11 @@ def to_dict(self, decimals=None): vec[-1] = 1 / np.sqrt(2) psi = Statevector(vec, dims=(2, 10)) print(psi.to_dict()) + + .. parsed-literal:: + + {'00': (0.7071067811865475+0j), '91': (0.7071067811865475+0j)} + """ return self._vector_to_dict( self.data, self._op_shape.dims_l(), decimals=decimals, string_labels=True diff --git a/qiskit/synthesis/discrete_basis/__init__.py b/qiskit/synthesis/discrete_basis/__init__.py index 6f5e21bf22e2..606c40b414b3 100644 --- a/qiskit/synthesis/discrete_basis/__init__.py +++ b/qiskit/synthesis/discrete_basis/__init__.py @@ -50,7 +50,7 @@ Examples: - .. jupyter-execute:: + .. code-block:: import numpy as np from qiskit.circuit import QuantumCircuit @@ -76,6 +76,18 @@ print('Error:', np.linalg.norm(Operator(circuit).data - Operator(discretized).data)) + .. parsed-literal:: + + Original circuit: + ┌─────────┐ + q: ┤ Rx(0.8) ├ + └─────────┘ + Discretized circuit: + global phase: 7π/8 + ┌───┐┌───┐┌───┐ + q: ┤ H ├┤ T ├┤ H ├ + └───┘└───┘└───┘ + Error: 2.828408279166474 References: diff --git a/qiskit/tools/jupyter/__init__.py b/qiskit/tools/jupyter/__init__.py index 4348fb11ddd4..9e5bc9d9f73f 100644 --- a/qiskit/tools/jupyter/__init__.py +++ b/qiskit/tools/jupyter/__init__.py @@ -61,7 +61,7 @@ HTMLProgressBar =============== -.. jupyter-execute:: +.. code-block:: import numpy as np from qiskit.tools.parallel import parallel_map @@ -74,7 +74,7 @@ Qiskit version table ==================== -.. jupyter-execute:: +.. code-block:: import qiskit.tools.jupyter %qiskit_version_table @@ -83,7 +83,7 @@ Qiskit copyright ================ -.. jupyter-execute:: +.. code-block:: import qiskit.tools.jupyter %qiskit_copyright @@ -91,7 +91,7 @@ Monospaced output ================= -.. jupyter-execute:: +.. code-block:: import qiskit.tools.jupyter %monospaced_output diff --git a/qiskit/tools/jupyter/library.py b/qiskit/tools/jupyter/library.py index 7d986a8ad119..42eb4ded7a51 100644 --- a/qiskit/tools/jupyter/library.py +++ b/qiskit/tools/jupyter/library.py @@ -18,6 +18,7 @@ from IPython.display import display from qiskit import QuantumCircuit from qiskit.exceptions import MissingOptionalLibraryError +from qiskit.utils import optionals as _optionals try: import pygments @@ -29,6 +30,25 @@ HAS_PYGMENTS = False +@_optionals.HAS_MATPLOTLIB.require_in_call +def _generate_circuit_library_visualization(circuit: QuantumCircuit): + import matplotlib.pyplot as plt + + circuit = circuit.decompose() + ops = circuit.count_ops() + num_nl = circuit.num_nonlocal_gates() + _fig, (ax0, ax1) = plt.subplots(2, 1) + circuit.draw("mpl", ax=ax0) + ax1.axis("off") + ax1.grid(visible=None) + ax1.table( + [[circuit.name], [circuit.width()], [circuit.depth()], [sum(ops.values())], [num_nl]], + rowLabels=["Circuit Name", "Width", "Depth", "Total Gates", "Non-local Gates"], + ) + plt.tight_layout() + plt.show() + + def circuit_data_table(circuit: QuantumCircuit) -> wid.HTML: """Create a HTML table widget for a given quantum circuit. diff --git a/qiskit/transpiler/__init__.py b/qiskit/transpiler/__init__.py index df827dc5c513..42cdb5535568 100644 --- a/qiskit/transpiler/__init__.py +++ b/qiskit/transpiler/__init__.py @@ -60,22 +60,22 @@ operations. In the present case of IBM Q devices, the native gate set can be found by querying the devices themselves, and looking for the corresponding attribute in their configuration: - .. jupyter-execute:: - :hide-code: - :hide-output: + .. code-block:: - from qiskit.providers.fake_provider import FakeVigo - backend = FakeVigo() + from qiskit.providers.fake_provider import FakeVigoV2 + backend = FakeVigoV2() - .. jupyter-execute:: + print(backend.operation_names) - backend.configuration().basis_gates + .. parsed-literal:: + ['id', 'rz', 'sx', 'x', 'cx', 'measure', 'delay'] Every quantum circuit run on an IBM Q device must be expressed using only these basis gates. For example, suppose one wants to run a simple phase estimation circuit: - .. jupyter-execute:: + .. plot:: + :include-source: import numpy as np from qiskit import QuantumCircuit @@ -94,9 +94,24 @@ decompose the circuit to show what it would look like in the native gate set of the IBM Quantum devices: - .. jupyter-execute:: + .. plot:: + :include-source: + import numpy as np + from qiskit import QuantumCircuit from qiskit import transpile + from qiskit.providers.fake_provider import FakeVigoV2 + + qc = QuantumCircuit(2, 1) + + qc.h(0) + qc.x(1) + qc.cp(np.pi/4, 0, 1) + qc.h(0) + qc.measure([0], [0]) + qc.draw(output='mpl') + + backend = FakeVigoV2() qc_basis = transpile(qc, backend) qc_basis.draw(output='mpl') @@ -105,10 +120,14 @@ A few things to highlight. First, the circuit has gotten longer with respect to the initial one. This can be verified by checking the depth of the circuits: - .. jupyter-execute:: + .. code-block:: print('Original depth:', qc.depth(), 'Decomposed Depth:', qc_basis.depth()) + .. parsed-literal:: + + Original depth: 4 Decomposed Depth: 10 + Second, although we had a single controlled gate, the fact that it was not in the basis set means that, when expanded, it requires more than a single `cx` gate to implement. All said, unrolling to the basis set of gates leads to an increase in the depth of a @@ -119,7 +138,10 @@ 1. A SWAP gate is not a native gate on the IBM Q devices, and must be decomposed into three CNOT gates: - .. jupyter-execute:: + .. plot:: + :include-source: + + from qiskit import QuantumCircuit swap_circ = QuantumCircuit(2) swap_circ.swap(0, 1) @@ -136,7 +158,10 @@ that our basis gate set includes only single- and two-qubit gates, it is obvious that this gate must be decomposed. This decomposition is quite costly: - .. jupyter-execute:: + .. plot:: + :include-source: + + from qiskit import QuantumCircuit ccx_circ = QuantumCircuit(3) ccx_circ.ccx(0, 1, 2) @@ -194,12 +219,13 @@ in them, and we can view this layout selection graphically using :func:`qiskit.visualization.plot_circuit_layout`: - .. jupyter-execute:: + .. plot:: + :include-source: from qiskit import QuantumCircuit, transpile from qiskit.visualization import plot_circuit_layout - from qiskit.providers.fake_provider import FakeVigo - backend = FakeVigo() + from qiskit.providers.fake_provider import FakeVigoV2 + backend = FakeVigoV2() ghz = QuantumCircuit(3, 3) ghz.h(0) @@ -211,26 +237,63 @@ - **Layout Using Optimization Level 0** - .. jupyter-execute:: + .. plot:: + :include-source: - new_circ_lv0 = transpile(ghz, backend=backend, optimization_level=0) - plot_circuit_layout(new_circ_lv0, backend) + from qiskit import QuantumCircuit, transpile + from qiskit.visualization import plot_circuit_layout + from qiskit.providers.fake_provider import FakeVigoV2 + backend = FakeVigoV2() + ghz = QuantumCircuit(3, 3) + ghz.h(0) + ghz.cx(0,range(1,3)) + ghz.barrier() + ghz.measure(range(3), range(3)) + ghz.draw(output='mpl') + + new_circ_lv0 = transpile(ghz, backend=backend, optimization_level=0) + plot_circuit_layout(new_circ_lv0, backend) - **Layout Using Optimization Level 3** - .. jupyter-execute:: + .. plot:: + :include-source: + + from qiskit import QuantumCircuit, transpile + from qiskit.visualization import plot_circuit_layout + from qiskit.providers.fake_provider import FakeVigoV2 + backend = FakeVigoV2() - new_circ_lv3 = transpile(ghz, backend=backend, optimization_level=3) - plot_circuit_layout(new_circ_lv3, backend) + ghz = QuantumCircuit(3, 3) + ghz.h(0) + ghz.cx(0,range(1,3)) + ghz.barrier() + ghz.measure(range(3), range(3)) + ghz.draw(output='mpl') + new_circ_lv3 = transpile(ghz, backend=backend, optimization_level=3) + plot_circuit_layout(new_circ_lv3, backend) It is completely possible to specify your own initial layout. To do so we can pass a list of integers to :func:`qiskit.compiler.transpile` via the `initial_layout` keyword argument, where the index labels the virtual qubit in the circuit and the corresponding value is the label for the physical qubit to map onto: - .. jupyter-execute:: + .. plot:: + :include-source: + + from qiskit import QuantumCircuit, transpile + from qiskit.visualization import plot_circuit_layout + from qiskit.providers.fake_provider import FakeVigoV2 + backend = FakeVigoV2() + + ghz = QuantumCircuit(3, 3) + ghz.h(0) + ghz.cx(0,range(1,3)) + ghz.barrier() + ghz.measure(range(3), range(3)) + ghz.draw(output='mpl') # Virtual -> physical # 0 -> 3 @@ -270,7 +333,8 @@ In order to highlight this, we run a GHZ circuit 100 times, using a "bad" (disconnected) `initial_layout`: - .. jupyter-execute:: + .. plot:: + :include-source: import matplotlib.pyplot as plt from qiskit import QuantumCircuit, transpile @@ -282,9 +346,6 @@ ghz.cx(0,range(1,5)) ghz.draw(output='mpl') - - .. jupyter-execute:: - depths = [] for _ in range(100): depths.append(transpile(ghz, @@ -331,7 +392,8 @@ So the numbers below will likely change each time you run the code. - .. jupyter-execute:: + .. plot:: + :include-source: import matplotlib.pyplot as plt from qiskit import QuantumCircuit, transpile @@ -344,7 +406,7 @@ ghz.draw(output='mpl') - .. jupyter-execute:: + .. code-block:: for kk in range(4): circ = transpile(ghz, backend, optimization_level=kk) @@ -353,6 +415,23 @@ print('Gate counts:', circ.count_ops()) print() + .. parsed-literal:: + + Optimization Level 0 + Depth: 14 + Gate counts: OrderedDict([('cx', 19), ('u2', 1)]) + + Optimization Level 1 + Depth: 8 + Gate counts: OrderedDict([('cx', 7), ('u2', 1)]) + + Optimization Level 2 + Depth: 8 + Gate counts: OrderedDict([('cx', 7), ('u2', 1)]) + + Optimization Level 3 + Depth: 7 + Gate counts: OrderedDict([('cx', 7), ('u2', 1)]) .. raw:: html @@ -365,9 +444,11 @@ a scheduling phase can be applied to optionally account for all the idle time in the circuit. At a high level the scheduling can be thought of as inserting delays into the circuit to account for idle time on the qubits between the execution of instructions. For example, if we start with a - circuit such as: + circuit such as a GHZ circuit and then call :func:`~.transpile` on it with ``scheduling_method`` + set: - .. jupyter-execute:: + .. plot:: + :include-source: from qiskit import QuantumCircuit, transpile from qiskit.providers.fake_provider import FakeBoeblingen @@ -376,11 +457,6 @@ ghz = QuantumCircuit(5) ghz.h(0) ghz.cx(0,range(1,5)) - ghz.draw(output='mpl') - - we can then call :func:`~.transpile` on it with ``scheduling_method`` set: - - .. jupyter-execute:: circ = transpile(ghz, backend, scheduling_method="asap") circ.draw(output='mpl') @@ -389,10 +465,19 @@ account for idle time on each qubit. To get a better idea of the timing of the circuit we can also look at it with the :func:`.timeline.draw` function: - .. jupyter-execute:: + .. plot:: + :include-source: from qiskit.visualization.timeline import draw as timeline_draw + from qiskit import QuantumCircuit, transpile + from qiskit.providers.fake_provider import FakeBoeblingen + backend = FakeBoeblingen() + + ghz = QuantumCircuit(5) + ghz.h(0) + ghz.cx(0,range(1,5)) + circ = transpile(ghz, backend, scheduling_method="asap") timeline_draw(circ) The scheduling of a circuit involves two parts, analysis and constraint mapping followed by a diff --git a/qiskit/transpiler/passes/scheduling/dynamical_decoupling.py b/qiskit/transpiler/passes/scheduling/dynamical_decoupling.py index 39c9bcb0613f..7495528f4907 100644 --- a/qiskit/transpiler/passes/scheduling/dynamical_decoupling.py +++ b/qiskit/transpiler/passes/scheduling/dynamical_decoupling.py @@ -45,7 +45,8 @@ class DynamicalDecoupling(TransformationPass): This pass ensures that the inserted sequence preserves the circuit exactly (including global phase). - .. jupyter-execute:: + .. plot:: + :include-source: import numpy as np from qiskit.circuit import QuantumCircuit @@ -64,9 +65,6 @@ class DynamicalDecoupling(TransformationPass): ("cx", [1, 2], 200), ("cx", [2, 3], 300), ("x", None, 50), ("measure", None, 1000)] ) - - .. jupyter-execute:: - # balanced X-X sequence on all qubits dd_sequence = [XGate(), XGate()] pm = PassManager([ALAPSchedule(durations), @@ -74,8 +72,6 @@ class DynamicalDecoupling(TransformationPass): circ_dd = pm.run(circ) timeline_drawer(circ_dd) - .. jupyter-execute:: - # Uhrig sequence on qubit 0 n = 8 dd_sequence = [XGate()] * n diff --git a/qiskit/transpiler/passes/scheduling/padding/dynamical_decoupling.py b/qiskit/transpiler/passes/scheduling/padding/dynamical_decoupling.py index 308fe8f871ad..7cde1c17f0ba 100644 --- a/qiskit/transpiler/passes/scheduling/padding/dynamical_decoupling.py +++ b/qiskit/transpiler/passes/scheduling/padding/dynamical_decoupling.py @@ -47,7 +47,8 @@ class PadDynamicalDecoupling(BasePadding): This pass ensures that the inserted sequence preserves the circuit exactly (including global phase). - .. jupyter-execute:: + .. plot:: + :include-source: import numpy as np from qiskit.circuit import QuantumCircuit @@ -67,8 +68,6 @@ class PadDynamicalDecoupling(BasePadding): ("x", None, 50), ("measure", None, 1000)] ) - .. jupyter-execute:: - # balanced X-X sequence on all qubits dd_sequence = [XGate(), XGate()] pm = PassManager([ALAPScheduleAnalysis(durations), @@ -76,8 +75,6 @@ class PadDynamicalDecoupling(BasePadding): circ_dd = pm.run(circ) timeline_drawer(circ_dd) - .. jupyter-execute:: - # Uhrig sequence on qubit 0 n = 8 dd_sequence = [XGate()] * n diff --git a/qiskit/transpiler/passes/utils/remove_barriers.py b/qiskit/transpiler/passes/utils/remove_barriers.py index 0de332e4145d..53b500ff31c6 100644 --- a/qiskit/transpiler/passes/utils/remove_barriers.py +++ b/qiskit/transpiler/passes/utils/remove_barriers.py @@ -24,7 +24,8 @@ class RemoveBarriers(TransformationPass): Example: - .. jupyter-execute:: + .. plot:: + :include-source: from qiskit import QuantumCircuit from qiskit.transpiler.passes import RemoveBarriers @@ -35,7 +36,7 @@ class RemoveBarriers(TransformationPass): circuit.h(0) circuit = RemoveBarriers()(circuit) - circuit.draw() + circuit.draw('mpl') """ diff --git a/qiskit/visualization/__init__.py b/qiskit/visualization/__init__.py index 041303a4c390..43377c02cc50 100644 --- a/qiskit/visualization/__init__.py +++ b/qiskit/visualization/__init__.py @@ -46,7 +46,8 @@ The following example demonstrates the common usage of these arguments: -.. jupyter-execute:: +.. plot:: + :include-source: from qiskit.visualization import plot_histogram @@ -58,7 +59,14 @@ You can specify ``legend``, ``title``, ``figsize`` and ``color`` by passing to the kwargs. -.. jupyter-execute:: +.. plot:: + :include-source: + + from qiskit.visualization import plot_histogram + + counts1 = {'00': 499, '11': 501} + counts2 = {'00': 511, '11': 489} + data = [counts1, counts2] legend = ['First execution', 'Second execution'] title = 'New histogram' @@ -92,7 +100,8 @@ Here is an example of using :func:`plot_histogram` to visualize measurement outcome counts: -.. jupyter-execute:: +.. plot:: + :include-source: from qiskit.visualization import plot_histogram @@ -132,7 +141,8 @@ Here is an example of using :func:`plot_state_city` to visualize a quantum state: -.. jupyter-execute:: +.. plot:: + :include-source: from qiskit.visualization import plot_state_city @@ -144,10 +154,12 @@ :class:`~qiskit.quantum_info.Statevector` or :class:`~qiskit.quantum_info.DensityMatrix` objects obtained from a :class:`~qiskit.circuit.QuantumCircuit`: -.. jupyter-execute:: +.. plot:: + :include-source: from qiskit import QuantumCircuit - from qiskit.quantum_info import Statevector, DensityMatrix + from qiskit.quantum_info import Statevector + from qiskit.visualization import plot_state_city qc = QuantumCircuit(2) qc.h(0) @@ -157,7 +169,16 @@ state = Statevector(qc) plot_state_city(state) -.. jupyter-execute:: +.. plot:: + :include-source: + + from qiskit import QuantumCircuit + from qiskit.quantum_info import DensityMatrix + from qiskit.visualization import plot_state_city + + qc = QuantumCircuit(2) + qc.h(0) + qc.cx(0,1) # plot using a DensityMatrix state = DensityMatrix(qc) diff --git a/qiskit/visualization/circuit/circuit_visualization.py b/qiskit/visualization/circuit/circuit_visualization.py index ebb0d69bebe2..301cebbd666e 100644 --- a/qiskit/visualization/circuit/circuit_visualization.py +++ b/qiskit/visualization/circuit/circuit_visualization.py @@ -166,7 +166,8 @@ def circuit_drawer( MissingOptionalLibraryError: when the output methods requires non-installed libraries. Example: - .. jupyter-execute:: + .. plot:: + :include-source: from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.tools.visualization import circuit_drawer diff --git a/qiskit/visualization/counts_visualization.py b/qiskit/visualization/counts_visualization.py index 1df49fd80870..fa1a2977dde4 100644 --- a/qiskit/visualization/counts_visualization.py +++ b/qiskit/visualization/counts_visualization.py @@ -99,7 +99,8 @@ def plot_histogram( VisualizationError: Input must be Counts or a dict Examples: - .. jupyter-execute:: + .. plot:: + :include-source: # Plot two counts in the same figure with legends and colors specified. @@ -113,8 +114,6 @@ def plot_histogram( plot_histogram([counts1, counts2], legend=legend, color=['crimson','midnightblue'], title="New Histogram") - .. jupyter-execute:: - # You can sort the bitstrings using different methods. counts = {'001': 596, '011': 211, '010': 50, '000': 117, '101': 33, '111': 8, @@ -126,9 +125,6 @@ def plot_histogram( # Sort by the hamming distance (the number of bit flips to change from # one bitstring to the other) from a target string. hist2 = plot_histogram(counts, sort='hamming', target_string='001') - - display(hist1, hist2) - """ if not isinstance(data, list): data = [data] @@ -214,7 +210,8 @@ def plot_distribution( match the input data. Examples: - .. jupyter-execute:: + .. plot:: + :include-source: # Plot two counts in the same figure with legends and colors specified. @@ -228,8 +225,6 @@ def plot_distribution( plot_distribution([counts1, counts2], legend=legend, color=['crimson','midnightblue'], title="New Distribution") - .. jupyter-execute:: - # You can sort the bitstrings using different methods. counts = {'001': 596, '011': 211, '010': 50, '000': 117, '101': 33, '111': 8, @@ -242,8 +237,6 @@ def plot_distribution( # one bitstring to the other) from a target string. dist2 = plot_distribution(counts, sort='hamming', target_string='001') - display(dist1, dist2) - """ return _plotting_core( data, diff --git a/qiskit/visualization/dag_visualization.py b/qiskit/visualization/dag_visualization.py index 1e0015c4ae76..b3e21fecbbfc 100644 --- a/qiskit/visualization/dag_visualization.py +++ b/qiskit/visualization/dag_visualization.py @@ -48,9 +48,9 @@ def dag_drawer(dag, scale=0.7, filename=None, style="color"): InvalidFileError: when filename provided is not valid Example: - .. jupyter-execute:: + .. plot:: + :include-source: - %matplotlib inline from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.dagcircuit import DAGCircuit from qiskit.converters import circuit_to_dag diff --git a/qiskit/visualization/gate_map.py b/qiskit/visualization/gate_map.py index 1c38ef808ff5..d7652b1f9303 100644 --- a/qiskit/visualization/gate_map.py +++ b/qiskit/visualization/gate_map.py @@ -79,22 +79,16 @@ def plot_gate_map( MissingOptionalLibraryError: if matplotlib not installed. Example: - .. jupyter-execute:: - :hide-code: - :hide-output: - from qiskit.test.ibmq_mock import mock_get_backend - mock_get_backend('FakeVigo') + .. plot:: + :include-source: - .. jupyter-execute:: - - from qiskit import QuantumCircuit, execute, IBMQ + from qiskit import QuantumCircuit, execute + from qiskit.providers.fake_provider import FakeVigoV2 from qiskit.visualization import plot_gate_map - %matplotlib inline - provider = IBMQ.load_account() - accountProvider = IBMQ.get_provider(hub='ibm-q') - backend = accountProvider.get_backend('ibmq_vigo') + backend = FakeVigoV2() + plot_gate_map(backend) """ qubit_coordinates_map = {} @@ -589,10 +583,10 @@ def plot_coupling_map( Example: - .. jupyter-execute:: + .. plot:: + :include-source: from qiskit.visualization import plot_coupling_map - %matplotlib inline num_qubits = 8 qubit_coordinates = [[0, 1], [1, 1], [1, 0], [1, 2], [2, 0], [2, 2], [2, 1], [3, 1]] @@ -767,23 +761,15 @@ def plot_circuit_layout(circuit, backend, view="virtual", qubit_coordinates=None VisualizationError: Circuit has no layout attribute. Example: - .. jupyter-execute:: - :hide-code: - :hide-output: - - from qiskit.test.ibmq_mock import mock_get_backend - mock_get_backend('FakeVigo') - - .. jupyter-execute:: + .. plot:: + :include-source: import numpy as np - from qiskit import QuantumCircuit, IBMQ, transpile + from qiskit import QuantumCircuit, transpile + from qiskit.providers.fake_provider import FakeVigoV2 from qiskit.visualization import plot_histogram, plot_gate_map, plot_circuit_layout from qiskit.tools.monitor import job_monitor import matplotlib.pyplot as plt - %matplotlib inline - - IBMQ.load_account() ghz = QuantumCircuit(3, 3) ghz.h(0) @@ -791,8 +777,7 @@ def plot_circuit_layout(circuit, backend, view="virtual", qubit_coordinates=None ghz.cx(0,idx) ghz.measure(range(3), range(3)) - provider = IBMQ.get_provider(hub='ibm-q') - backend = provider.get_backend('ibmq_vigo') + backend = FakeVigoV2() new_circ_lv3 = transpile(ghz, backend=backend, optimization_level=3) plot_circuit_layout(new_circ_lv3, backend) """ @@ -803,9 +788,11 @@ def plot_circuit_layout(circuit, backend, view="virtual", qubit_coordinates=None if backend_version <= 1: num_qubits = backend.configuration().n_qubits cmap = backend.configuration().coupling_map + cmap_len = len(cmap) else: num_qubits = backend.num_qubits cmap = backend.coupling_map + cmap_len = cmap.graph.num_edges() qubits = [] qubit_labels = [None] * num_qubits @@ -840,7 +827,7 @@ def plot_circuit_layout(circuit, backend, view="virtual", qubit_coordinates=None for k in qubits: qcolors[k] = "k" - lcolors = ["#648fff"] * len(cmap) + lcolors = ["#648fff"] * cmap_len for idx, edge in enumerate(cmap): if edge[0] in qubits and edge[1] in qubits: @@ -880,22 +867,14 @@ def plot_error_map(backend, figsize=(12, 9), show_title=True, qubit_coordinates= MissingOptionalLibraryError: If seaborn is not installed Example: - .. jupyter-execute:: - :hide-code: - :hide-output: - - from qiskit.test.ibmq_mock import mock_get_backend - mock_get_backend('FakeVigo') - - .. jupyter-execute:: + .. plot:: + :include-source: - from qiskit import QuantumCircuit, execute, IBMQ + from qiskit import QuantumCircuit, execute from qiskit.visualization import plot_error_map - %matplotlib inline + from qiskit.providers.fake_provider import FakeVigoV2 - IBMQ.load_account() - provider = IBMQ.get_provider(hub='ibm-q') - backend = provider.get_backend('ibmq_vigo') + backend = FakeVigoV2() plot_error_map(backend) """ import seaborn as sns diff --git a/qiskit/visualization/pulse_v2/interface.py b/qiskit/visualization/pulse_v2/interface.py index eac27fe7bb32..21b7d8a24cb3 100644 --- a/qiskit/visualization/pulse_v2/interface.py +++ b/qiskit/visualization/pulse_v2/interface.py @@ -308,7 +308,8 @@ def draw( Drawing with the default stylesheet. - .. jupyter-execute:: + .. plot:: + :include-source: from qiskit import QuantumCircuit, transpile, schedule from qiskit.visualization.pulse_v2 import draw @@ -325,7 +326,8 @@ def draw( Drawing with the stylesheet suited for publication. - .. jupyter-execute:: + .. plot:: + :include-source: from qiskit import QuantumCircuit, transpile, schedule from qiskit.visualization.pulse_v2 import draw, IQXSimple @@ -342,7 +344,8 @@ def draw( Drawing with the stylesheet suited for program debugging. - .. jupyter-execute:: + .. plot:: + :include-source: from qiskit import QuantumCircuit, transpile, schedule from qiskit.visualization.pulse_v2 import draw, IQXDebugging diff --git a/qiskit/visualization/state_visualization.py b/qiskit/visualization/state_visualization.py index 76e66c53d142..8ef512ada5dd 100644 --- a/qiskit/visualization/state_visualization.py +++ b/qiskit/visualization/state_visualization.py @@ -74,7 +74,8 @@ def plot_state_hinton( VisualizationError: if input is not a valid N-qubit state. Examples: - .. jupyter-execute:: + .. plot:: + :include-source: import numpy as np from qiskit import QuantumCircuit @@ -210,17 +211,20 @@ def plot_bloch_vector(bloch, title="", ax=None, figsize=None, coord_type="cartes MissingOptionalLibraryError: Requires matplotlib. Examples: - .. jupyter-execute:: + .. plot:: + :include-source: from qiskit.visualization import plot_bloch_vector plot_bloch_vector([0,1,0], title="New Bloch Sphere") - .. jupyter-execute:: - - # You can use spherical coordinates instead of cartesian. + .. plot:: + :include-source: import numpy as np + from qiskit.visualization import plot_bloch_vector + + # You can use spherical coordinates instead of cartesian. plot_bloch_vector([1, np.pi/2, np.pi/3], coord_type='spherical') @@ -273,7 +277,8 @@ def plot_bloch_multivector( VisualizationError: if input is not a valid N-qubit state. Examples: - .. jupyter-execute:: + .. plot:: + :include-source: from qiskit import QuantumCircuit from qiskit.quantum_info import Statevector @@ -286,7 +291,16 @@ def plot_bloch_multivector( state = Statevector(qc) plot_bloch_multivector(state) - .. jupyter-execute:: + .. plot:: + :include-source: + + from qiskit import QuantumCircuit + from qiskit.quantum_info import Statevector + from qiskit.visualization import plot_bloch_multivector + + qc = QuantumCircuit(2) + qc.h(0) + qc.x(1) # You can reverse the order of the qubits. @@ -373,7 +387,8 @@ def plot_state_city( VisualizationError: if input is not a valid N-qubit state. Examples: - .. jupyter-execute:: + .. plot:: + :include-source: # You can choose different colors for the real and imaginary parts of the density matrix. @@ -388,13 +403,21 @@ def plot_state_city( state = DensityMatrix(qc) plot_state_city(state, color=['midnightblue', 'crimson'], title="New State City") - .. jupyter-execute:: + .. plot:: + :include-source: # You can make the bars more transparent to better see the ones that are behind # if they overlap. import numpy as np from qiskit.quantum_info import Statevector + from qiskit.visualization import plot_state_city + from qiskit import QuantumCircuit + + qc = QuantumCircuit(2) + qc.h(0) + qc.cx(0, 1) + qc = QuantumCircuit(2) qc.h([0, 1]) @@ -600,7 +623,8 @@ def plot_state_paulivec( VisualizationError: if input is not a valid N-qubit state. Examples: - .. jupyter-execute:: + .. plot:: + :include-source: # You can set a color for all the bars. @@ -615,13 +639,20 @@ def plot_state_paulivec( state = Statevector(qc) plot_state_paulivec(state, color='midnightblue', title="New PauliVec plot") - .. jupyter-execute:: + .. plot:: + :include-source: # If you introduce a list with less colors than bars, the color of the bars will # alternate following the sequence from the list. import numpy as np from qiskit.quantum_info import DensityMatrix + from qiskit import QuantumCircuit + from qiskit.visualization import plot_state_paulivec + + qc = QuantumCircuit(2) + qc.h(0) + qc.cx(0, 1) qc = QuantumCircuit(2) qc.h([0, 1]) @@ -772,7 +803,8 @@ def plot_state_qsphere( QiskitError: Input statevector does not have valid dimensions. Examples: - .. jupyter-execute:: + .. plot:: + :include-source: from qiskit import QuantumCircuit from qiskit.quantum_info import Statevector @@ -785,13 +817,16 @@ def plot_state_qsphere( state = Statevector(qc) plot_state_qsphere(state) - .. jupyter-execute:: + .. plot:: + :include-source: # You can show the phase of each state and use # degrees instead of radians from qiskit.quantum_info import DensityMatrix import numpy as np + from qiskit import QuantumCircuit + from qiskit.visualization import plot_state_qsphere qc = QuantumCircuit(2) qc.h([0, 1]) diff --git a/qiskit/visualization/timeline/interface.py b/qiskit/visualization/timeline/interface.py index fef51b51e22f..2ed3d0cb870a 100644 --- a/qiskit/visualization/timeline/interface.py +++ b/qiskit/visualization/timeline/interface.py @@ -287,7 +287,8 @@ def draw( Drawing with the default stylesheet. - .. jupyter-execute:: + .. plot:: + :include-source: from qiskit import QuantumCircuit, transpile, schedule from qiskit.visualization.timeline import draw @@ -302,7 +303,8 @@ def draw( Drawing with the simple stylesheet. - .. jupyter-execute:: + .. plot:: + :include-source: from qiskit import QuantumCircuit, transpile, schedule from qiskit.visualization.timeline import draw, IQXSimple @@ -317,7 +319,8 @@ def draw( Drawing with the stylesheet suited for program debugging. - .. jupyter-execute:: + .. plot:: + :include-source: from qiskit import QuantumCircuit, transpile, schedule from qiskit.visualization.timeline import draw, IQXDebugging diff --git a/releasenotes/notes/0.12/add-couplingmap-draw-45b8750065719e2c.yaml b/releasenotes/notes/0.12/add-couplingmap-draw-45b8750065719e2c.yaml index 7e0677498338..0e38c9e7a1df 100644 --- a/releasenotes/notes/0.12/add-couplingmap-draw-45b8750065719e2c.yaml +++ b/releasenotes/notes/0.12/add-couplingmap-draw-45b8750065719e2c.yaml @@ -5,7 +5,7 @@ features: :class:`qiskit.transpiler.CouplingMap` to generate a graphviz images from the coupling map graph. For example: - .. jupyter-execute:: + .. code-block:: from qiskit.transpiler import CouplingMap diff --git a/releasenotes/notes/0.12/coupling-map-constructors-d9f66ac45f4ceb1b.yaml b/releasenotes/notes/0.12/coupling-map-constructors-d9f66ac45f4ceb1b.yaml index bdabee8f6e44..88a6f89ce650 100644 --- a/releasenotes/notes/0.12/coupling-map-constructors-d9f66ac45f4ceb1b.yaml +++ b/releasenotes/notes/0.12/coupling-map-constructors-d9f66ac45f4ceb1b.yaml @@ -13,7 +13,7 @@ features: For example, to use the new constructors to get a coupling map of 5 qubits connected in a linear chain you can now run: - .. jupyter-execute:: + .. code-block:: from qiskit.transpiler import CouplingMap diff --git a/releasenotes/notes/0.13/add-pygments-dfe2cd949c237deb.yaml b/releasenotes/notes/0.13/add-pygments-dfe2cd949c237deb.yaml index 480c1f3d8e9a..18cebc04bfbb 100644 --- a/releasenotes/notes/0.13/add-pygments-dfe2cd949c237deb.yaml +++ b/releasenotes/notes/0.13/add-pygments-dfe2cd949c237deb.yaml @@ -5,7 +5,7 @@ features: :mod:`qiskit.tools.jupyter`. This widget is used for visualizing details about circuits built from the circuit library. For example - .. jupyter-execute:: + .. code-block:: from qiskit.circuit.library import XOR import qiskit.tools.jupyter diff --git a/releasenotes/notes/0.13/get_counts-returns-also-dict_list-fcd23da8f3757105.yaml b/releasenotes/notes/0.13/get_counts-returns-also-dict_list-fcd23da8f3757105.yaml index 7b5918802860..ab71ca3426c3 100644 --- a/releasenotes/notes/0.13/get_counts-returns-also-dict_list-fcd23da8f3757105.yaml +++ b/releasenotes/notes/0.13/get_counts-returns-also-dict_list-fcd23da8f3757105.yaml @@ -10,7 +10,7 @@ features: from multiple circuits in the same histogram. For example it is now possible to do something like: - .. jupyter-execute:: + .. code-block:: from qiskit import execute from qiskit import QuantumCircuit diff --git a/releasenotes/notes/0.13/initial_state_draw_parameter-f360ac4e998ee944.yaml b/releasenotes/notes/0.13/initial_state_draw_parameter-f360ac4e998ee944.yaml index 5490e8b75a18..37dabfaa3927 100644 --- a/releasenotes/notes/0.13/initial_state_draw_parameter-f360ac4e998ee944.yaml +++ b/releasenotes/notes/0.13/initial_state_draw_parameter-f360ac4e998ee944.yaml @@ -8,7 +8,7 @@ upgrade: retain the initial state in the output visualization you need to set the ``initial_state`` kwarg to ``True``. For example, running: - .. jupyter-execute:: + .. code-block:: from qiskit import QuantumCircuit @@ -18,7 +18,7 @@ upgrade: This no longer includes the initial state. If you'd like to retain it you can run: - .. jupyter-execute:: + .. code-block:: from qiskit import QuantumCircuit @@ -35,7 +35,7 @@ features: initial state will be included in circuit visualizations for all backends. For example: - .. jupyter-execute:: + .. code-block:: from qiskit import QuantumCircuit diff --git a/releasenotes/notes/0.13/qinfo-states-7f67e2432cf0c12c.yaml b/releasenotes/notes/0.13/qinfo-states-7f67e2432cf0c12c.yaml index 79bd1b9b721e..9a8a84530832 100644 --- a/releasenotes/notes/0.13/qinfo-states-7f67e2432cf0c12c.yaml +++ b/releasenotes/notes/0.13/qinfo-states-7f67e2432cf0c12c.yaml @@ -13,14 +13,14 @@ features: Example - .. jupyter-execute:: + .. code-block:: from qiskit.quantum_info import Statevector state = Statevector.from_label('+0') print(state.to_dict()) - .. jupyter-execute:: + .. code-block:: from qiskit.quantum_info import DensityMatrix @@ -36,14 +36,14 @@ features: Example - .. jupyter-execute:: + .. code-block:: from qiskit.quantum_info import Statevector state = Statevector.from_label('+0') print(state.probabilities()) - .. jupyter-execute:: + .. code-block:: from qiskit.quantum_info import DensityMatrix @@ -58,14 +58,14 @@ features: count-style dictionary array of measurement outcome probabilities in the computational basis for the specified subsystems. - .. jupyter-execute:: + .. code-block:: from qiskit.quantum_info import Statevector state = Statevector.from_label('+0') print(state.probabilities_dict()) - .. jupyter-execute:: + .. code-block:: from qiskit.quantum_info import DensityMatrix @@ -81,7 +81,7 @@ features: Generate a counts dictionary by sampling from a statevector - .. jupyter-execute:: + .. code-block:: from qiskit.quantum_info import Statevector @@ -102,7 +102,7 @@ features: Return the array of measurement outcomes for each sample - .. jupyter-execute:: + .. code-block:: from qiskit.quantum_info import Statevector @@ -128,7 +128,7 @@ features: and collapsing the statevector to the post-measurement computational basis state. For example - .. jupyter-execute:: + .. code-block:: from qiskit.quantum_info import Statevector @@ -150,7 +150,7 @@ features: allows reseting some or all subsystems to the :math:`|0\rangle` state. For example - .. jupyter-execute:: + .. code-block:: from qiskit.quantum_info import Statevector diff --git a/releasenotes/notes/0.13/quibit-transition-visualization-a62d0d119569fa05.yaml b/releasenotes/notes/0.13/quibit-transition-visualization-a62d0d119569fa05.yaml index 9a22579d8f34..12c69ef47c51 100644 --- a/releasenotes/notes/0.13/quibit-transition-visualization-a62d0d119569fa05.yaml +++ b/releasenotes/notes/0.13/quibit-transition-visualization-a62d0d119569fa05.yaml @@ -30,7 +30,7 @@ features: For example: - .. jupyter-execute:: + .. code-block:: from qiskit.visualization import visualize_transition from qiskit import * diff --git a/releasenotes/notes/0.15/circuit-repeat-8db21ef8d8c21cda.yaml b/releasenotes/notes/0.15/circuit-repeat-8db21ef8d8c21cda.yaml index f6d687f45d7e..e88555bc58e4 100644 --- a/releasenotes/notes/0.15/circuit-repeat-8db21ef8d8c21cda.yaml +++ b/releasenotes/notes/0.15/circuit-repeat-8db21ef8d8c21cda.yaml @@ -6,7 +6,7 @@ features: circuit object containing a specified number of repetitions of the original circuit. For example: - .. jupyter-execute:: + .. code-block:: from qiskit.circuit import QuantumCircuit diff --git a/releasenotes/notes/0.15/cregbundle-8c0ae7bd7875dd0f.yaml b/releasenotes/notes/0.15/cregbundle-8c0ae7bd7875dd0f.yaml index 8db9f985b65e..9362bc5cd5a4 100644 --- a/releasenotes/notes/0.15/cregbundle-8c0ae7bd7875dd0f.yaml +++ b/releasenotes/notes/0.15/cregbundle-8c0ae7bd7875dd0f.yaml @@ -7,7 +7,7 @@ upgrade: to ``True``. This means that by default the classical bits in the circuit diagram will now be bundled by default, for example: - .. jupyter-execute:: + .. code-block:: from qiskit.circuit import QuantumCircuit @@ -21,7 +21,7 @@ upgrade: and show each classical bit in the diagram you can set the ``cregbundle`` kwarg to ``False``. For example: - .. jupyter-execute:: + .. code-block:: from qiskit.circuit import QuantumCircuit diff --git a/releasenotes/notes/0.15/equiv-lib-draw-8f3c4bd897a2fa6c.yaml b/releasenotes/notes/0.15/equiv-lib-draw-8f3c4bd897a2fa6c.yaml index d24ffbf326d6..06a6ffb16d94 100644 --- a/releasenotes/notes/0.15/equiv-lib-draw-8f3c4bd897a2fa6c.yaml +++ b/releasenotes/notes/0.15/equiv-lib-draw-8f3c4bd897a2fa6c.yaml @@ -6,7 +6,7 @@ features: method can be used for drawing the contents of an equivalence library, which can be useful for debugging. For example: - .. jupyter-execute:: + .. code-block:: from numpy import pi diff --git a/releasenotes/notes/0.15/mpl-scaling-fix-823c3e3d3cb2d9d1.yaml b/releasenotes/notes/0.15/mpl-scaling-fix-823c3e3d3cb2d9d1.yaml index e9d66f01001c..81ef136fe0f4 100644 --- a/releasenotes/notes/0.15/mpl-scaling-fix-823c3e3d3cb2d9d1.yaml +++ b/releasenotes/notes/0.15/mpl-scaling-fix-823c3e3d3cb2d9d1.yaml @@ -10,7 +10,7 @@ fixes: did not scale with the rest of the image. This has been fixed and all elements of the circuit diagram now scale properly. For example: - .. jupyter-execute:: + .. code-block:: from qiskit import QuantumCircuit circuit = QuantumCircuit(2) diff --git a/releasenotes/notes/0.15/quantumcircuit-compose-without-dag-b19e518a8f2fbeb0.yaml b/releasenotes/notes/0.15/quantumcircuit-compose-without-dag-b19e518a8f2fbeb0.yaml index 0711227d0e85..21eb4cd75585 100644 --- a/releasenotes/notes/0.15/quantumcircuit-compose-without-dag-b19e518a8f2fbeb0.yaml +++ b/releasenotes/notes/0.15/quantumcircuit-compose-without-dag-b19e518a8f2fbeb0.yaml @@ -6,7 +6,7 @@ features: which can be used for prepending the other circuit before the origin circuit instead of appending. For example: - .. jupyter-execute:: + .. code-block:: from qiskit.circuit import QuantumCircuit diff --git a/releasenotes/notes/0.15/to_gate_label-d825a2997a504604.yaml b/releasenotes/notes/0.15/to_gate_label-d825a2997a504604.yaml index 5fc00b44ee94..dda5ed19c4bd 100644 --- a/releasenotes/notes/0.15/to_gate_label-d825a2997a504604.yaml +++ b/releasenotes/notes/0.15/to_gate_label-d825a2997a504604.yaml @@ -6,7 +6,7 @@ features: ``label`` which can be used to set a label for for the output :class:`~qiskit.circuit.Gate` object. For example: - .. jupyter-execute:: + .. code-block:: from qiskit.circuit import QuantumCircuit diff --git a/releasenotes/notes/0.15/updated_mpl_drawer-1498741fc64ac42a.yaml b/releasenotes/notes/0.15/updated_mpl_drawer-1498741fc64ac42a.yaml index 3e1589705f63..497baa921939 100644 --- a/releasenotes/notes/0.15/updated_mpl_drawer-1498741fc64ac42a.yaml +++ b/releasenotes/notes/0.15/updated_mpl_drawer-1498741fc64ac42a.yaml @@ -11,7 +11,7 @@ features: For example: - .. jupyter-execute:: + .. code-block:: from qiskit import QuantumCircuit circuit = QuantumCircuit(2) @@ -27,7 +27,7 @@ features: For example: - .. jupyter-execute:: + .. code-block:: from qiskit import QuantumCircuit circuit = QuantumCircuit(2) @@ -44,7 +44,7 @@ features: For example: - .. jupyter-execute:: + .. code-block:: from qiskit import QuantumCircuit from qiskit.circuit.library.standard_gates import YGate diff --git a/releasenotes/notes/0.16/add-iqx-color-scheme-0de42f0d004fad31.yaml b/releasenotes/notes/0.16/add-iqx-color-scheme-0de42f0d004fad31.yaml index d166d01d1d4e..ab259fb96f22 100644 --- a/releasenotes/notes/0.16/add-iqx-color-scheme-0de42f0d004fad31.yaml +++ b/releasenotes/notes/0.16/add-iqx-color-scheme-0de42f0d004fad31.yaml @@ -16,7 +16,7 @@ features: ``QuantumCircuit.draw`` method or to the ``circuit_drawer`` function. The second way will override the setting in the settings.conf file. For example: - .. jupyter-execute:: + .. code-block:: from qiskit.circuit import QuantumCircuit @@ -38,7 +38,7 @@ features: number of gate types, from one to the entire ``displaycolor`` dict. For example: - .. jupyter-execute:: + .. code-block:: from qiskit.circuit import QuantumCircuit @@ -50,7 +50,7 @@ features: or - .. jupyter-execute:: + .. code-block:: style_dict = {'displaycolor': {'h': '#FA74A6'}} circuit.draw('mpl', style=style_dict) diff --git a/releasenotes/notes/0.16/delay-in-circuit-33f0d81783ac12ea.yaml b/releasenotes/notes/0.16/delay-in-circuit-33f0d81783ac12ea.yaml index d482e3f97e2f..a9ffc4d508df 100644 --- a/releasenotes/notes/0.16/delay-in-circuit-33f0d81783ac12ea.yaml +++ b/releasenotes/notes/0.16/delay-in-circuit-33f0d81783ac12ea.yaml @@ -7,7 +7,7 @@ features: appending delays to circuits. This makes it possible to describe timing-sensitive experiments (e.g. T1/T2 experiment) in the circuit level. - .. jupyter-execute:: + .. code-block:: from qiskit import QuantumCircuit diff --git a/releasenotes/notes/0.16/spherical-coord-bloch-295beddb37ef16a6.yaml b/releasenotes/notes/0.16/spherical-coord-bloch-295beddb37ef16a6.yaml index 827ae55929d2..e9c1452733e2 100644 --- a/releasenotes/notes/0.16/spherical-coord-bloch-295beddb37ef16a6.yaml +++ b/releasenotes/notes/0.16/spherical-coord-bloch-295beddb37ef16a6.yaml @@ -12,7 +12,7 @@ features: radius, ``theta`` is the inclination from +z direction, and ``phi`` is the azimuth from +x direction. For example: - .. jupyter-execute:: + .. code-block:: from numpy import pi @@ -30,11 +30,11 @@ features: # for bloch vector plot_bloch_vector([x,y,z]) - .. jupyter-execute:: + .. code-block:: plot_bloch_vector([x,y,z], coord_type="cartesian") # Same as line above - .. jupyter-execute:: + .. code-block:: # Spherical coordinates, where (r,theta,phi) are spherical coordinates # for bloch vector diff --git a/releasenotes/notes/0.17/add-parameters-and-is_parameterized-to-pulse-d5695dd14e407537.yaml b/releasenotes/notes/0.17/add-parameters-and-is_parameterized-to-pulse-d5695dd14e407537.yaml index 7d4b1fdc6c98..837f2fc898ec 100644 --- a/releasenotes/notes/0.17/add-parameters-and-is_parameterized-to-pulse-d5695dd14e407537.yaml +++ b/releasenotes/notes/0.17/add-parameters-and-is_parameterized-to-pulse-d5695dd14e407537.yaml @@ -11,7 +11,7 @@ features: For example: - .. jupyter-execute:: + .. code-block:: from qiskit.circuit import Parameter from qiskit import pulse diff --git a/releasenotes/notes/0.17/add-piecewise-polynomial-chebyshev-66c82ffe1d749dd6.yaml b/releasenotes/notes/0.17/add-piecewise-polynomial-chebyshev-66c82ffe1d749dd6.yaml index 51ae802c6234..20abb7dc23cf 100644 --- a/releasenotes/notes/0.17/add-piecewise-polynomial-chebyshev-66c82ffe1d749dd6.yaml +++ b/releasenotes/notes/0.17/add-piecewise-polynomial-chebyshev-66c82ffe1d749dd6.yaml @@ -11,7 +11,7 @@ features: For example: - .. jupyter-execute:: + .. code-block:: import numpy as np from qiskit import QuantumCircuit diff --git a/releasenotes/notes/0.17/add_array_to_latex-0b5f655a47f132c0.yaml b/releasenotes/notes/0.17/add_array_to_latex-0b5f655a47f132c0.yaml index 7e9f2bd5578c..d6b9e2270c30 100644 --- a/releasenotes/notes/0.17/add_array_to_latex-0b5f655a47f132c0.yaml +++ b/releasenotes/notes/0.17/add_array_to_latex-0b5f655a47f132c0.yaml @@ -5,7 +5,7 @@ features: the :mod:`qiskit.visualization` module that can be used to represent and visualize vectors and matrices with LaTeX. - .. jupyter-execute:: + .. code-block:: from qiskit.visualization import array_to_latex from numpy import sqrt, exp, pi diff --git a/releasenotes/notes/0.17/add_state_ipython-6fd6305f3db04a23.yaml b/releasenotes/notes/0.17/add_state_ipython-6fd6305f3db04a23.yaml index 7e1ba69e6d45..b561b4a8ea66 100644 --- a/releasenotes/notes/0.17/add_state_ipython-6fd6305f3db04a23.yaml +++ b/releasenotes/notes/0.17/add_state_ipython-6fd6305f3db04a23.yaml @@ -9,13 +9,13 @@ features: is the equivalent output from ``__repr__`` but this default can be changed in a user config file by setting the ``state_drawer`` option. For example: - .. jupyter-execute:: + .. code-block:: from qiskit.quantum_info import DensityMatrix dm = DensityMatrix.from_label('r0') dm.draw('latex') - .. jupyter-execute:: + .. code-block:: from qiskit.quantum_info import Statevector sv = Statevector.from_label('+r') diff --git a/releasenotes/notes/0.17/calling_a_pass-4148f285ea717c74.yaml b/releasenotes/notes/0.17/calling_a_pass-4148f285ea717c74.yaml index 91d252d4f645..14b2ff8a0a34 100644 --- a/releasenotes/notes/0.17/calling_a_pass-4148f285ea717c74.yaml +++ b/releasenotes/notes/0.17/calling_a_pass-4148f285ea717c74.yaml @@ -9,7 +9,7 @@ features: For example, running a single transformation pass, such as :class:`~qiskit.transpiler.passes.BasisTranslator`, can be done with: - .. jupyter-execute:: + .. code-block:: from qiskit import QuantumCircuit from qiskit.transpiler.passes import BasisTranslator @@ -27,7 +27,7 @@ features: needs to be added as a parameter and it might be modified "in-place". For example: - .. jupyter-execute:: + .. code-block:: from qiskit import QuantumCircuit from qiskit.transpiler.passes import Depth diff --git a/releasenotes/notes/0.17/circuit-tensor-f432dcd9302ded9f.yaml b/releasenotes/notes/0.17/circuit-tensor-f432dcd9302ded9f.yaml index fbe98acadf9e..392066bc6318 100644 --- a/releasenotes/notes/0.17/circuit-tensor-f432dcd9302ded9f.yaml +++ b/releasenotes/notes/0.17/circuit-tensor-f432dcd9302ded9f.yaml @@ -10,7 +10,7 @@ features: For example: - .. jupyter-execute:: + .. code-block:: from qiskit import QuantumCircuit top = QuantumCircuit(1) diff --git a/releasenotes/notes/0.17/initial_layout_cp_none-8753d058743eeb79.yaml b/releasenotes/notes/0.17/initial_layout_cp_none-8753d058743eeb79.yaml index dc7eede65a69..14a4ded91365 100644 --- a/releasenotes/notes/0.17/initial_layout_cp_none-8753d058743eeb79.yaml +++ b/releasenotes/notes/0.17/initial_layout_cp_none-8753d058743eeb79.yaml @@ -9,7 +9,7 @@ fixes: :func:`qiskit.compiler.transpile` function honors the ``initial_layout`` argument by embedding the circuit: - .. jupyter-execute:: + .. code-block:: from qiskit import QuantumCircuit, QuantumRegister from qiskit.compiler import transpile @@ -25,7 +25,7 @@ fixes: If the ``initial_layout`` refers to more qubits than in the circuit, the transpiling process will extended the circuit with ancillas. - .. jupyter-execute:: + .. code-block:: from qiskit import QuantumCircuit, QuantumRegister from qiskit.compiler import transpile diff --git a/releasenotes/notes/0.17/initialize_from_int-800e4db98b502baa.yaml b/releasenotes/notes/0.17/initialize_from_int-800e4db98b502baa.yaml index 2bf507ec8061..b4c02ae1d20d 100644 --- a/releasenotes/notes/0.17/initialize_from_int-800e4db98b502baa.yaml +++ b/releasenotes/notes/0.17/initialize_from_int-800e4db98b502baa.yaml @@ -11,7 +11,7 @@ features: :class:`~qiskit.extensions.Initialize` equal to ``5`` will set qubits 0 and 2 to value 1. - .. jupyter-execute:: + .. code-block:: from qiskit.extensions import Initialize diff --git a/releasenotes/notes/0.17/initialize_from_labels-0f18f37188031d83.yaml b/releasenotes/notes/0.17/initialize_from_labels-0f18f37188031d83.yaml index f2c79a6bc2a8..3ad33cd67335 100644 --- a/releasenotes/notes/0.17/initialize_from_labels-0f18f37188031d83.yaml +++ b/releasenotes/notes/0.17/initialize_from_labels-0f18f37188031d83.yaml @@ -10,7 +10,7 @@ features: would initialize qubit 0 to :math:`|1\rangle` and qubit 1 to :math:`|0\rangle`. - .. jupyter-execute:: + .. code-block:: from qiskit.extensions import Initialize diff --git a/releasenotes/notes/0.17/marginal_counts_format-dc20b15d6c04ec94.yaml b/releasenotes/notes/0.17/marginal_counts_format-dc20b15d6c04ec94.yaml index 0dadf8729751..a59dae0eda86 100644 --- a/releasenotes/notes/0.17/marginal_counts_format-dc20b15d6c04ec94.yaml +++ b/releasenotes/notes/0.17/marginal_counts_format-dc20b15d6c04ec94.yaml @@ -7,7 +7,7 @@ features: :attr:`~qiskit.circuit.QuantumCircuit.cregs` in the circuit and missing indices are represented with a ``_``. For example: - .. jupyter-execute:: + .. code-block:: from qiskit import QuantumCircuit, execute, BasicAer, result from qiskit.result.utils import marginal_counts diff --git a/releasenotes/notes/0.17/pauli-operator-76ae910a340a4ad4.yaml b/releasenotes/notes/0.17/pauli-operator-76ae910a340a4ad4.yaml index b4761c0a6d08..f457f8ed9a08 100644 --- a/releasenotes/notes/0.17/pauli-operator-76ae910a340a4ad4.yaml +++ b/releasenotes/notes/0.17/pauli-operator-76ae910a340a4ad4.yaml @@ -14,7 +14,7 @@ features: For example - .. jupyter-execute:: + .. code-block:: from qiskit.quantum_info import Pauli @@ -25,7 +25,7 @@ features: Pauli's can also be directly appended to :class:`~qiskit.circuit.QuantumCircuit` objects - .. jupyter-execute:: + .. code-block:: from qiskit import QuantumCircuit from qiskit.quantum_info import Pauli diff --git a/releasenotes/notes/0.17/randompauli-76928cc17c840aea.yaml b/releasenotes/notes/0.17/randompauli-76928cc17c840aea.yaml index 86af76583516..2d8aea034729 100644 --- a/releasenotes/notes/0.17/randompauli-76928cc17c840aea.yaml +++ b/releasenotes/notes/0.17/randompauli-76928cc17c840aea.yaml @@ -6,7 +6,7 @@ features: of a 2-design circuit from https://arxiv.org/pdf/1803.11173.pdf For instance, this circuit can look like: - .. jupyter-execute:: + .. code-block:: from qiskit.circuit.library import PauliTwoDesign circuit = PauliTwoDesign(4, reps=2, seed=5, insert_barriers=True) diff --git a/releasenotes/notes/0.17/reverse_qargs-f2f3c9a3e1c3aaa0.yaml b/releasenotes/notes/0.17/reverse_qargs-f2f3c9a3e1c3aaa0.yaml index 7088ea66abde..9608d9e6cdc7 100644 --- a/releasenotes/notes/0.17/reverse_qargs-f2f3c9a3e1c3aaa0.yaml +++ b/releasenotes/notes/0.17/reverse_qargs-f2f3c9a3e1c3aaa0.yaml @@ -8,7 +8,7 @@ features: :meth:`qiskit.circuit.QuantumCircuit.reverse_bits` method for N-qubit states. For example: - .. jupyter-execute:: + .. code-block:: from qiskit.circuit.library import QFT from qiskit.quantum_info import Statevector @@ -26,7 +26,7 @@ features: :meth:`qiskit.circuit.QuantumCircuit.reverse_bits` method for N-qubit operators. For example: - .. jupyter-execute:: + .. code-block:: from qiskit.circuit.library import QFT from qiskit.quantum_info import Operator diff --git a/releasenotes/notes/0.17/sorted-circuit-parameters-7607dd7ef4e6cc0e.yaml b/releasenotes/notes/0.17/sorted-circuit-parameters-7607dd7ef4e6cc0e.yaml index 6ceb3a0b4a3e..6efb91e96b45 100644 --- a/releasenotes/notes/0.17/sorted-circuit-parameters-7607dd7ef4e6cc0e.yaml +++ b/releasenotes/notes/0.17/sorted-circuit-parameters-7607dd7ef4e6cc0e.yaml @@ -11,7 +11,7 @@ features: name-sorted order. Previously these methods would only take a dictionary of parameters and values. For example: - .. jupyter-execute:: + .. code-block:: from qiskit.circuit import QuantumCircuit, Parameter diff --git a/releasenotes/notes/0.17/statevector-equiv-ad588688fa260940.yaml b/releasenotes/notes/0.17/statevector-equiv-ad588688fa260940.yaml index b9302bbf0fc6..444c0225f840 100644 --- a/releasenotes/notes/0.17/statevector-equiv-ad588688fa260940.yaml +++ b/releasenotes/notes/0.17/statevector-equiv-ad588688fa260940.yaml @@ -8,7 +8,7 @@ features: :class:`~qiskit.quantum_info.DensityMatrix` object from that circuit, assuming that the qubits are initialized in :math:`|0\rangle`. For example: - .. jupyter-execute:: + .. code-block:: from qiskit import QuantumCircuit from qiskit.quantum_info import Statevector diff --git a/releasenotes/notes/0.18/compose-can-wrap-e839c29e426051e8.yaml b/releasenotes/notes/0.18/compose-can-wrap-e839c29e426051e8.yaml index 57dbaf686fdd..1bf314122c87 100644 --- a/releasenotes/notes/0.18/compose-can-wrap-e839c29e426051e8.yaml +++ b/releasenotes/notes/0.18/compose-can-wrap-e839c29e426051e8.yaml @@ -7,7 +7,7 @@ features: composed circuits should be wrapped into an instruction or not. By default this is ``False``, i.e. no wrapping. For example: - .. jupyter-execute:: + .. code-block:: from qiskit import QuantumCircuit circuit = QuantumCircuit(2) diff --git a/releasenotes/notes/0.18/delay_from_qasm-a6ad4f1fe3f49041.yaml b/releasenotes/notes/0.18/delay_from_qasm-a6ad4f1fe3f49041.yaml index b28e80d554b6..48fa04f04d8d 100644 --- a/releasenotes/notes/0.18/delay_from_qasm-a6ad4f1fe3f49041.yaml +++ b/releasenotes/notes/0.18/delay_from_qasm-a6ad4f1fe3f49041.yaml @@ -8,7 +8,7 @@ fixes: contains an instruction with the name ``delay`` this will be mapped to a :class:`qiskit.circuit.Delay` instruction. For example: - .. jupyter-execute:: + .. code-block:: from qiskit import QuantumCircuit diff --git a/releasenotes/notes/0.18/dynamical-decoupling-3ce6e882954f6d3b.yaml b/releasenotes/notes/0.18/dynamical-decoupling-3ce6e882954f6d3b.yaml index 36b43501823c..63c604e8176d 100644 --- a/releasenotes/notes/0.18/dynamical-decoupling-3ce6e882954f6d3b.yaml +++ b/releasenotes/notes/0.18/dynamical-decoupling-3ce6e882954f6d3b.yaml @@ -8,7 +8,7 @@ features: scheduling). The pass allows control over the sequence of DD gates, the spacing between them, and the qubits to apply on. For example: - .. jupyter-execute:: + .. code-block:: from qiskit.circuit import QuantumCircuit from qiskit.circuit.library import XGate diff --git a/releasenotes/notes/0.18/latex_style_user_math_text-266f9b411317ae6b.yaml b/releasenotes/notes/0.18/latex_style_user_math_text-266f9b411317ae6b.yaml index e0863d05d32a..003b73208371 100644 --- a/releasenotes/notes/0.18/latex_style_user_math_text-266f9b411317ae6b.yaml +++ b/releasenotes/notes/0.18/latex_style_user_math_text-266f9b411317ae6b.yaml @@ -19,7 +19,7 @@ features: with a user-generated name or label. For example, to add subscripts and to change a gate color: - .. jupyter-execute:: + .. code-block:: from qiskit import QuantumCircuit from qiskit.circuit.library import HGate diff --git a/releasenotes/notes/0.18/value-sort-histogram-1b7033bdfe612f94.yaml b/releasenotes/notes/0.18/value-sort-histogram-1b7033bdfe612f94.yaml index a4fe14868a30..daa442a6c521 100644 --- a/releasenotes/notes/0.18/value-sort-histogram-1b7033bdfe612f94.yaml +++ b/releasenotes/notes/0.18/value-sort-histogram-1b7033bdfe612f94.yaml @@ -7,7 +7,7 @@ features: will sort the x axis based on the maximum probability for each bitstring. For example: - .. jupyter-execute:: + .. code-block:: from qiskit.visualization import plot_histogram diff --git a/releasenotes/notes/0.19/add-hexagonal-lattice-couplingmap-d3b65b146b6cd1d1.yaml b/releasenotes/notes/0.19/add-hexagonal-lattice-couplingmap-d3b65b146b6cd1d1.yaml index 477ee8c38f27..25d7990610dd 100644 --- a/releasenotes/notes/0.19/add-hexagonal-lattice-couplingmap-d3b65b146b6cd1d1.yaml +++ b/releasenotes/notes/0.19/add-hexagonal-lattice-couplingmap-d3b65b146b6cd1d1.yaml @@ -6,7 +6,7 @@ features: lattice coupling map. For example, to construct a 2x2 hexagonal lattice coupling map: - .. jupyter-execute:: + .. code-block:: from qiskit.transpiler import CouplingMap cmap = CouplingMap.from_hexagonal_lattice(2, 2) diff --git a/releasenotes/notes/0.19/heavy-hex-heavy-square-coupling-map-29f459b93cd18518.yaml b/releasenotes/notes/0.19/heavy-hex-heavy-square-coupling-map-29f459b93cd18518.yaml index 8d14f2944e32..c48efe55b018 100644 --- a/releasenotes/notes/0.19/heavy-hex-heavy-square-coupling-map-29f459b93cd18518.yaml +++ b/releasenotes/notes/0.19/heavy-hex-heavy-square-coupling-map-29f459b93cd18518.yaml @@ -10,7 +10,7 @@ features: For example: - .. jupyter-execute:: + .. code-block:: from qiskit.transpiler import CouplingMap @@ -18,7 +18,7 @@ features: cmap.draw() - .. jupyter-execute:: + .. code-block:: from qiskit.transpiler import CouplingMap diff --git a/releasenotes/notes/0.19/qasm3_dumps-7475de655e1acb24.yaml b/releasenotes/notes/0.19/qasm3_dumps-7475de655e1acb24.yaml index 4beba8b97fdb..303d1ebf19e7 100644 --- a/releasenotes/notes/0.19/qasm3_dumps-7475de655e1acb24.yaml +++ b/releasenotes/notes/0.19/qasm3_dumps-7475de655e1acb24.yaml @@ -4,7 +4,7 @@ features: Qiskit Terra now has initial support for serializing :class:`.QuantumCircuit`\ s to `OpenQASM 3 `__: - .. jupyter-execute:: + .. code-block:: from qiskit.circuit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import qasm3 @@ -20,7 +20,7 @@ features: user-defined instructions (as subroutines), and the new control-flow constructs also introduced in this release: - .. jupyter-execute:: + .. code-block:: from qiskit.circuit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import qasm3 diff --git a/releasenotes/notes/0.20/add-parameter-prefix-support-to-ZFeatureMap-ZZFeatureMap-ba13832b9a832e88.yaml b/releasenotes/notes/0.20/add-parameter-prefix-support-to-ZFeatureMap-ZZFeatureMap-ba13832b9a832e88.yaml index 2d3e26d2dc4b..2c119c17a7c3 100644 --- a/releasenotes/notes/0.20/add-parameter-prefix-support-to-ZFeatureMap-ZZFeatureMap-ba13832b9a832e88.yaml +++ b/releasenotes/notes/0.20/add-parameter-prefix-support-to-ZFeatureMap-ZZFeatureMap-ba13832b9a832e88.yaml @@ -6,7 +6,7 @@ features: argument ``parameter_prefix``. This new argument is used to set the prefix of parameters of the data encoding circuit. For example: - .. jupyter-execute:: + .. code-block:: from qiskit.circuit.library import ZFeatureMap diff --git a/releasenotes/notes/0.20/iqx-dark-3dd0a500e1801673.yaml b/releasenotes/notes/0.20/iqx-dark-3dd0a500e1801673.yaml index 39a2ea6ff5ed..3188ea6c4a12 100644 --- a/releasenotes/notes/0.20/iqx-dark-3dd0a500e1801673.yaml +++ b/releasenotes/notes/0.20/iqx-dark-3dd0a500e1801673.yaml @@ -7,7 +7,7 @@ features: backend, the output visualization will use a color scheme similar to the the dark mode color scheme used by the IBM Quantum composer. For example: - .. jupyter-execute:: + .. code-block:: from qiskit.circuit import QuantumCircuit from matplotlib.pyplot import show diff --git a/releasenotes/notes/0.20/update-instruction-alignment-passes-ef0f20d4f89f95f3.yaml b/releasenotes/notes/0.20/update-instruction-alignment-passes-ef0f20d4f89f95f3.yaml index 35979e3dddf0..af5f158ecb17 100644 --- a/releasenotes/notes/0.20/update-instruction-alignment-passes-ef0f20d4f89f95f3.yaml +++ b/releasenotes/notes/0.20/update-instruction-alignment-passes-ef0f20d4f89f95f3.yaml @@ -92,7 +92,7 @@ features: 0 └─────────┘ 0 - .. jupyter-execute:: + .. code-block:: from qiskit import QuantumCircuit from qiskit.transpiler import InstructionDurations, PassManager @@ -128,7 +128,7 @@ features: By using the default configuration of passes, the circuit is schedule like below. - .. jupyter-execute:: + .. code-block:: from qiskit import QuantumCircuit from qiskit.transpiler import InstructionDurations, PassManager diff --git a/releasenotes/notes/0.22/add-barrier-label-8e677979cb37461e.yaml b/releasenotes/notes/0.22/add-barrier-label-8e677979cb37461e.yaml index a58832b5d480..66c69e1269d8 100644 --- a/releasenotes/notes/0.22/add-barrier-label-8e677979cb37461e.yaml +++ b/releasenotes/notes/0.22/add-barrier-label-8e677979cb37461e.yaml @@ -8,7 +8,7 @@ features: :meth:`.QuantumCircuit.draw` this label will be printed at the top of the ``barrier``. - .. jupyter-execute:: + .. code-block:: from qiskit import QuantumCircuit diff --git a/releasenotes/notes/0.22/add-reset-simplification-pass-82377d80dd0081fd.yaml b/releasenotes/notes/0.22/add-reset-simplification-pass-82377d80dd0081fd.yaml index 5398ddfc5909..aba311e41ab5 100644 --- a/releasenotes/notes/0.22/add-reset-simplification-pass-82377d80dd0081fd.yaml +++ b/releasenotes/notes/0.22/add-reset-simplification-pass-82377d80dd0081fd.yaml @@ -9,7 +9,7 @@ features: remove the duplicate implicit :class:`~.Measure` from the :class:`~.Reset` operation. For example: - .. jupyter-execute:: + .. code-block:: from qiskit import QuantumCircuit from qiskit.transpiler.passes import ResetAfterMeasureSimplification @@ -19,7 +19,7 @@ features: qc.reset(0) qc.draw('mpl') - .. jupyter-execute:: + .. code-block:: result = ResetAfterMeasureSimplification()(qc) result.draw('mpl') diff --git a/releasenotes/notes/0.22/add-wire-order-to-drawers-657cb54e365c621a.yaml b/releasenotes/notes/0.22/add-wire-order-to-drawers-657cb54e365c621a.yaml index aa8cda12bece..e65acdcca28b 100644 --- a/releasenotes/notes/0.22/add-wire-order-to-drawers-657cb54e365c621a.yaml +++ b/releasenotes/notes/0.22/add-wire-order-to-drawers-657cb54e365c621a.yaml @@ -6,7 +6,7 @@ features: reordering both the quantum and classical bits in the output visualization. For example: - .. jupyter-execute:: + .. code-block:: from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister diff --git a/releasenotes/notes/0.22/plot-hist-797bfaeea2156c53.yaml b/releasenotes/notes/0.22/plot-hist-797bfaeea2156c53.yaml index 978c5437666b..e7d2b1196bd1 100644 --- a/releasenotes/notes/0.22/plot-hist-797bfaeea2156c53.yaml +++ b/releasenotes/notes/0.22/plot-hist-797bfaeea2156c53.yaml @@ -5,7 +5,7 @@ features: This is suitable for ``Counts``, ``QuasiDistribution`` and ``ProbDistribution``. Raw `dict` can be passed as well. For example: - .. jupyter-execute:: + .. code-block:: from qiskit.visualization import plot_distribution @@ -24,7 +24,7 @@ upgrade: equivalent graph. For example, the previous behavior of ``plot_histogram({'00': 512, '11': 500})`` can be re-created with: - .. jupyter-execute:: + .. code-block:: from qiskit.visualization import plot_distribution import matplotlib.pyplot as plt diff --git a/releasenotes/notes/solovay-kitaev-transpiler-pass-bc256c2f3aac28c6.yaml b/releasenotes/notes/solovay-kitaev-transpiler-pass-bc256c2f3aac28c6.yaml index a9bacff16d54..7a3897da44c9 100644 --- a/releasenotes/notes/solovay-kitaev-transpiler-pass-bc256c2f3aac28c6.yaml +++ b/releasenotes/notes/solovay-kitaev-transpiler-pass-bc256c2f3aac28c6.yaml @@ -8,7 +8,7 @@ features: This pass can e.g. be used after compiling to U and CX gates: - .. jupyter-execute:: + .. code-block:: from qiskit import transpile from qiskit.circuit.library import QFT @@ -27,20 +27,21 @@ features: The decomposition can also be used with the unitary synthesis plugin, as the "sk" method on the :class:`~.UnitarySynthesis` transpiler pass: - .. jupyter-execute:: + .. plot:: + :include-source: - from qiskit import QuantumCircuit - from qiskit.quantum_info import Operator - from qiskit.transpiler.passes import UnitarySynthesis + from qiskit import QuantumCircuit + from qiskit.quantum_info import Operator + from qiskit.transpiler.passes import UnitarySynthesis - circuit = QuantumCircuit(1) - circuit.rx(0.8, 0) - unitary = Operator(circuit).data + circuit = QuantumCircuit(1) + circuit.rx(0.8, 0) + unitary = Operator(circuit).data - unitary_circ = QuantumCircuit(1) - unitary_circ.unitary(unitary, [0]) + unitary_circ = QuantumCircuit(1) + unitary_circ.unitary(unitary, [0]) - synth = UnitarySynthesis(basis_gates=["h", "s"], method="sk") - out = synth(unitary_circ) + synth = UnitarySynthesis(basis_gates=["h", "s"], method="sk") + out = synth(unitary_circ) - out.draw('mpl') + out.draw('mpl') diff --git a/requirements-dev.txt b/requirements-dev.txt index 48756e8e97f9..825fed12baba 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -19,7 +19,6 @@ reno>=3.4.0 Sphinx>=3.0.0 qiskit-sphinx-theme>=1.6 sphinx-autodoc-typehints~=1.18,!=1.19.3 -jupyter-sphinx sphinx-design>=0.2.0 pygments>=2.4 scikit-learn>=0.20.0