### Installing Qiskit IBM Runtime Package (Bash) Source: https://github.com/qiskit/qiskit-ibm-runtime/blob/main/README.md This snippet demonstrates the standard method for installing the `qiskit-ibm-runtime` Python package using the `pip` command-line tool. This installation is a prerequisite for interacting with the Qiskit Runtime service and its primitives. ```Bash pip install qiskit-ibm-runtime ``` -------------------------------- ### Installing Towncrier for Release Note Preview Source: https://github.com/qiskit/qiskit-ibm-runtime/blob/main/CONTRIBUTING.md This command installs the Towncrier tool using `pipx`, a utility for installing and running Python applications in isolated environments. Towncrier is used to generate and preview release notes before they are officially published. ```bash pipx install towncrier ``` -------------------------------- ### Getting a Backend from IBMRuntimeService - Python Source: https://github.com/qiskit/qiskit-ibm-runtime/blob/main/release-notes/0.1.0.rst This snippet shows how to retrieve a specific backend using the `IBMRuntimeService.backend()` method, which replaces the `AccountProvider.get_backend` method from the deprecated `qiskit-ibmq-provider` package. It initializes the service and then gets the 'ibmq_qasm_simulator' backend. ```Python service = IBMRuntimeService() backend = service.backend("ibmq_qasm_simulator") ``` -------------------------------- ### Installing Development Dependencies for Qiskit IBM Runtime Source: https://github.com/qiskit/qiskit-ibm-runtime/blob/main/CONTRIBUTING.md This command installs all development-specific dependencies for the Qiskit IBM Runtime project, including tools for testing, linting, and documentation generation. It's installed in 'editable' mode for seamless integration with the development workflow. ```bash pip install -e ".[dev]" ``` -------------------------------- ### Installing Visualization Dependencies for Qiskit IBM Runtime Source: https://github.com/qiskit/qiskit-ibm-runtime/blob/main/CONTRIBUTING.md This command installs additional dependencies specifically required for visualization features of the Qiskit IBM Runtime project. It uses the 'editable' installation mode, similar to core dependencies, for development convenience. ```bash pip install -e ".[visualization]" ``` -------------------------------- ### Install Qiskit IBM Runtime Core Dependencies Source: https://github.com/qiskit/qiskit-ibm-runtime/blob/main/release-notes/0.34.0.rst Installs the core dependencies of the qiskit-ibm-runtime project in editable mode, suitable for development. This command leverages the new pyproject.toml for dependency management. ```Shell pip install -e . ``` -------------------------------- ### Install Qiskit IBM Runtime Visualization Dependencies Source: https://github.com/qiskit/qiskit-ibm-runtime/blob/main/release-notes/0.34.0.rst Installs the visualization-related dependencies for the qiskit-ibm-runtime project in editable mode. This is required for using features like ZNE data visualization. ```Shell pip install -e ".[visualization]" ``` -------------------------------- ### Install Qiskit IBM Runtime Development Dependencies Source: https://github.com/qiskit/qiskit-ibm-runtime/blob/main/release-notes/0.34.0.rst Installs the development dependencies for the qiskit-ibm-runtime project in editable mode. This is useful for contributors and developers working on the library itself. ```Shell pip install -e ".[dev]" ``` -------------------------------- ### Example Release Note: Backend Retrieval Error with Instance Parameter Source: https://github.com/qiskit/qiskit-ibm-runtime/blob/main/CONTRIBUTING.md This Python code snippet illustrates a scenario where attempting to retrieve a backend with a specified instance raises an error if the backend is not found within that instance, even if the user has access to it in a different instance. It serves as an example for documenting API behavior changes in release notes. ```python service.backend('ibm_torino', instance='ibm-q/open/main') # raises error if torino is not in ibm-q/open/main but in a different instance # the user has access to service = QiskitRuntimeService(channel="ibm_quantum", instance="ibm-q/open/main") service.backend('ibm_torino') # raises the same error ``` -------------------------------- ### Installing Core Dependencies for Qiskit IBM Runtime Source: https://github.com/qiskit/qiskit-ibm-runtime/blob/main/CONTRIBUTING.md This command installs the core project dependencies in 'editable' mode, which means changes to the source code are immediately reflected without needing to reinstall the package. This is essential for active development. ```bash pip install -e . ``` -------------------------------- ### Initializing Global QiskitRuntimeService for Primitives - Python Source: https://github.com/qiskit/qiskit-ibm-runtime/blob/main/release-notes/0.12.0.rst This snippet demonstrates how to initialize a QiskitRuntimeService instance and set it as a global service. When a global service is defined, primitives like Sampler will automatically use this service without it needing to be explicitly passed, simplifying configuration for subsequent operations. It shows the setup for the 'ibm_quantum' channel and the initialization of a Sampler with a specified backend. ```python from qiskit_ibm_runtime import QiskitRuntimeService, Sampler service = QiskitRuntimeService(channel="ibm_quantum") # Sampler._service field will be initialized to ``service`` sampler = Sampler(backend="ibmq_qasm_simulator") ``` -------------------------------- ### Accessing Backend Configuration (BackendV1 vs. BackendV2) - Python Source: https://github.com/qiskit/qiskit-ibm-runtime/blob/main/release-notes/0.1.0.rst This example illustrates the difference in accessing backend configuration properties between `BackendV1` and the new `BackendV2` interface implemented by `qiskit_ibm_runtime.IBMBackend`. `BackendV2` provides flatter access, simplifying property retrieval. ```Python # BackendV1: backend.configuration().n_qubits # BackendV2: backend.num_qubits ``` -------------------------------- ### Iterative Quantum Circuit Execution with Qiskit Estimator and Sessions (Python) Source: https://github.com/qiskit/qiskit-ibm-runtime/blob/main/README.md This example demonstrates how to use the Qiskit Session class to perform iterative quantum computations with the Estimator primitive, minimizing queuing delays. It implements a golden search method to find an optimal theta for a quantum circuit, showing how to prepare circuits, define observables, and run jobs within a session. Required dependencies include QiskitRuntimeService, Session, EstimatorV2, SparsePauliOp, QuantumCircuit, Parameter, and numpy. ```Python from qiskit_ibm_runtime import QiskitRuntimeService, Session, EstimatorV2 as Estimator from qiskit.quantum_info import SparsePauliOp from qiskit import QuantumCircuit from qiskit.circuit import Parameter import numpy as np service = QiskitRuntimeService() # 1. A quantum circuit for preparing the quantum state (|000> + e^{itheta} |111>)/rt{2} theta = Parameter('θ') circuit = QuantumCircuit(3) circuit.h(0) # generate superpostion circuit.p(theta,0) # add quantum phase circuit.cx(0, 1) # condition 1st qubit on 0th qubit circuit.cx(0, 2) # condition 2nd qubit on 0th qubit # The observable to be measured M1 = SparsePauliOp.from_list([("XXY", 1), ("XYX", 1), ("YXX", 1), ("YYY", -1)]) gr = (np.sqrt(5) + 1) / 2 # golden ratio thetaa = 0 # lower range of theta thetab = 2*np.pi # upper range of theta tol = 1e-1 # tol # 2: Optimize problem for quantum execution. backend = service.least_busy(operational=True, simulator=False) pm = generate_preset_pass_manager(backend=backend, optimization_level=1) isa_circuit = pm.run(circuit) isa_observables = M1.apply_layout(isa_circuit.layout) # 3. Execute iteratively using the Estimator primitive with Session(backend=backend) as session: estimator = Estimator(mode=session) estimator.options.default_precision = 0.03 # Options can be set using auto-complete. #next test range thetac = thetab - (thetab - thetaa) / gr thetad = thetaa + (thetab - thetaa) / gr while abs(thetab - thetaa) > tol: print(f"max value of M1 is in the range theta = {[thetaa, thetab]}") job = estimator.run([(isa_circuit, isa_observables, [[thetac],[thetad]])]) test = job.result()[0].data.evs if test[0] > test[1]: thetab = thetad else: thetaa = thetac thetac = thetab - (thetab - thetaa) / gr thetad = thetaa + (thetab - thetaa) / gr # Final job to evaluate Estimator at midpoint found using golden search method theta_mid = (thetab + thetaa) / 2 job = estimator.run([(isa_circuit, isa_observables, theta_mid)]) print(f"Session ID is {session.session_id}") print(f"Final Job ID is {job.job_id()}") print(f"Job result is {job.result()[0].data.evs} at theta = {theta_mid}") ``` -------------------------------- ### Running Documentation Style Checks (Shell) Source: https://github.com/qiskit/qiskit-ibm-runtime/blob/main/CONTRIBUTING.md This snippet provides the shell command to run documentation style checks using Vale. This command automatically verifies documentation against IBM Quantum's writing style guide and identifies spelling mistakes. Any words not recognized by Vale can be added to `test/docs/dictionary.txt` to prevent test failures. ```sh make docs-test ``` -------------------------------- ### Example Release Note: Adding `dd_barrier` to PadDynamicalDecoupling Source: https://github.com/qiskit/qiskit-ibm-runtime/blob/main/CONTRIBUTING.md This reStructuredText (RST) snippet provides an example of a release note documenting the addition of an optional `dd_barrier` input to the `PadDynamicalDecoupling` constructor. It explains how this parameter selectively applies dynamical decoupling based on barrier labels. ```rst Add `dd_barrier` optional input to :class:`.PadDynamicalDecoupling` constructor to identify portions of the circuit to apply dynamical decoupling (dd) on selectively. If this string is contained in the label of a barrier in the circuit, dd is applied on the delays ending with it (on the same qubits); otherwise, it is not applied. ``` -------------------------------- ### Activating the Virtual Environment for Qiskit IBM Runtime Source: https://github.com/qiskit/qiskit-ibm-runtime/blob/main/CONTRIBUTING.md This command activates the previously created virtual environment, ensuring that subsequent Python commands and package installations use the isolated environment's packages and executables. It must be run in each new terminal session. ```bash source .venv/bin/activate ``` -------------------------------- ### Setting Primitive Options with Qiskit Runtime Options Class (Python) Source: https://github.com/qiskit/qiskit-ibm-runtime/blob/main/release-notes/0.7.0rc1.rst This example illustrates the usage of the new qiskit_ibm_runtime.Options class to configure primitive settings, such as optimization_level. Options can be passed during the initialization of a primitive (e.g., Sampler) or overridden at the individual job level. This class provides auto-completion for available options, simplifying configuration. ```Python from qiskit_ibm_runtime import Session, Sampler, Options from qiskit.test.reference_circuits import ReferenceCircuits options = Options() options.optimization_level = 3 # This can be done using auto-complete. with Session(backend="ibmq_qasm_simulator") as session: # Pass the options to Sampler. sampler = Sampler(session=session, options=options) # Or at job level. job = sampler.run(circuits=ReferenceCircuits.bell(), shots=4000) ``` -------------------------------- ### Invoking Qiskit Runtime Sampler Primitive (Python) Source: https://github.com/qiskit/qiskit-ibm-runtime/blob/main/README.md This example illustrates the use of `SamplerV2` to execute a quantum circuit and retrieve sampling results. It involves defining a quantum circuit (Bell state), optimizing it for a backend, configuring sampler options like `default_shots`, and running the job to obtain measurement counts from the `pub_result`. ```Python from qiskit import QuantumCircuit from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager from qiskit_ibm_runtime import QiskitRuntimeService, SamplerV2 as Sampler service = QiskitRuntimeService() # 1. A quantum circuit for preparing the quantum state (|00> + |11>)/rt{2} bell = QuantumCircuit(2) bell.h(0) bell.cx(0, 1) bell.measure_all() # 2: Optimize problem for quantum execution. backend = service.least_busy(operational=True, simulator=False) pm = generate_preset_pass_manager(backend=backend, optimization_level=1) isa_circuit = pm.run(bell) # 3. Execute using the Sampler primitive sampler = Sampler(mode=backend) sampler.options.default_shots = 1024 # Options can be set using auto-complete. job = sampler.run([isa_circuit]) print(f"Job ID is {job.job_id()}") pub_result = job.result()[0] print(f"Counts for the meas output register: {pub_result.data.meas.get_counts()}") ``` -------------------------------- ### Creating a Virtual Environment for Qiskit IBM Runtime Source: https://github.com/qiskit/qiskit-ibm-runtime/blob/main/CONTRIBUTING.md This command creates a new Python virtual environment named `.venv` in the current directory, isolating project dependencies to prevent conflicts with system-wide packages. It's a crucial first step for a clean development setup. ```bash python3 -m venv .venv ``` -------------------------------- ### Setting Transpilation Options with Qiskit Runtime Options Class (Python) Source: https://github.com/qiskit/qiskit-ibm-runtime/blob/main/release-notes/0.7.0rc1.rst This example illustrates the updated way to control transpilation settings, specifically skip_transpilation, using the qiskit_ibm_runtime.Options class. This replaces the deprecated direct parameter in primitive constructors. The transpilation attribute within Options allows for fine-grained control over the transpilation process. ```Python from qiskit_ibm_runtime import Options options = Options() # This can be done using auto-complete. options.transpilation.skip_transpilation = True ``` -------------------------------- ### Using Estimator with Deprecated Indices and New Object Parameters (Python) Source: https://github.com/qiskit/qiskit-ibm-runtime/blob/main/release-notes/0.5.0.rst This example illustrates the updated way to pass circuits and observables to the `Estimator` primitive. While `circuit_indices` and `observable_indices` are deprecated, this snippet shows how to use the new `circuits` and `observables` parameters, accepting either indices or the quantum objects themselves. This provides more flexibility and aligns with future API changes. ```python with Estimator( circuits=[qc1, qc2], observables=[H1, H2, H3], service=service, options=options ) as estimator: # pass circuits and observables as indices result = estimator(circuits=[0, 1], observables=[0, 1], parameter_values=[theta1, theta2]) # pass circuits and observables as objects result = estimator(circuits=[qc1, qc2], observables=[H1, H3], parameter_values=[theta1, theta3]) ``` -------------------------------- ### Sphinx Class Documentation Generation Template - Jinja2 Source: https://github.com/qiskit/qiskit-ibm-runtime/blob/main/docs/_templates/autosummary/class.rst This Jinja2 template generates reStructuredText for Sphinx documentation, specifically for Python classes. It uses `autoclass`, `autoattribute`, and `automethod` directives to document a class, its attributes, and its methods. The template iterates through `all_attributes` and `all_methods` to create documentation entries, generally excluding private members (those starting with `_`) but explicitly including certain special methods like `__call__`. ```Jinja2 {# We show all the class's methods and attributes on the same page. By default, we document all methods, including those defined by parent classes. -#} {{ objname | escape | underline }} .. currentmodule:: {{ module }} .. autoclass:: {{ objname }} :no-members: :no-inherited-members: :no-special-members: :show-inheritance: {% block attributes_summary %} {% if attributes %} .. rubric:: Attributes {% for item in all_attributes %} {%- if not item.startswith('_') %} .. autoattribute:: {{ item }} {%- endif -%} {%- endfor %} {% endif %} {% endblock %} {% block methods_summary %} {% if methods %} .. rubric:: Methods {% for item in all_methods %} {%- if not item.startswith('_') or item in ['__call__', '__mul__', '__getitem__', '__len__'] %} .. automethod:: {{ item }} {%- endif -%} {%- endfor %} {% endif %} {% endblock %} ``` -------------------------------- ### Building Qiskit IBM Runtime Documentation Locally Source: https://github.com/qiskit/qiskit-ibm-runtime/blob/main/CONTRIBUTING.md This command uses `tox` to build all the project documentation, including the generated release notes, into the `docs/_build/html` directory. This allows contributors to preview the rendered HTML output of their documentation changes locally. ```bash tox -e docs ``` -------------------------------- ### Managing IBM Quantum Platform Instances with QiskitRuntimeService (Python) Source: https://github.com/qiskit/qiskit-ibm-runtime/blob/main/README.md This snippet illustrates how to manage access to IBM Quantum Platform instances using QiskitRuntimeService. It shows how to list all accessible instances, and how to specify a particular instance at either the service initialization level or when selecting a specific backend, demonstrating how these specifications affect the chosen instance for subsequent operations like Sampler initialization. ```Python # Optional: List all the instances you can access. service = QiskitRuntimeService(channel='ibm_quantum') print(service.instances()) # Optional: Specify the instance at service level. This becomes the default unless overwritten. service = QiskitRuntimeService(channel='ibm_quantum', instance="hub1/group1/project1") backend1 = service.backend("ibmq_manila") # Optional: Specify the instance at the backend level, which overwrites the service-level specification when this backend is used. backend2 = service.backend("ibmq_manila", instance="hub2/group2/project2") sampler1 = Sampler(mode=backend1) # this will use hub1/group1/project1 sampler2 = Sampler(mode=backend2) # this will use hub2/group2/project2 ``` -------------------------------- ### Setting Up Qiskit Runtime Estimator Primitive (Python) Source: https://github.com/qiskit/qiskit-ibm-runtime/blob/main/README.md This code prepares a parameterized quantum circuit and a `SparsePauliOp` observable for use with the `EstimatorV2` primitive. It includes the crucial step of optimizing the circuit and observable for a specific quantum backend using a pass manager, making them ready for expectation value calculations. ```Python from qiskit_ibm_runtime import QiskitRuntimeService, EstimatorV2 as Estimator from qiskit.quantum_info import SparsePauliOp from qiskit import QuantumCircuit from qiskit.circuit import Parameter import numpy as np service = QiskitRuntimeService() # 1. A quantum circuit for preparing the quantum state (|000> + e^{itheta} |111>)/rt{2} theta = Parameter('θ') circuit = QuantumCircuit(3) circuit.h(0) # generate superposition circuit.p(theta, 0) # add quantum phase circuit.cx(0, 1) # condition 1st qubit on 0th qubit circuit.cx(0, 2) # condition 2nd qubit on 0th qubit # The observable to be measured M1 = SparsePauliOp.from_list([("XXY", 1), ("XYX", 1), ("YXX", 1), ("YYY", -1)]) # batch of theta parameters to be executed points = 50 theta1 = [] for x in range(points): theta = [x*2.0*np.pi/50] theta1.append(theta) # 2: Optimize problem for quantum execution. backend = service.least_busy(operational=True, simulator=False) pm = generate_preset_pass_manager(backend=backend, optimization_level=1) isa_circuit = pm.run(circuit) isa_observables = M1.apply_layout(isa_circuit.layout) ``` -------------------------------- ### Initializing QiskitRuntimeService in Qiskit IBM Runtime Source: https://github.com/qiskit/qiskit-ibm-runtime/blob/main/release-notes/0.4.0.rst This snippet shows the current and recommended way to initialize the runtime service using the `QiskitRuntimeService` class. This class replaces `IBMRuntimeService` and provides the same functionality for connecting to the IBM Quantum platform with specified channel, token, and instance. ```python from qiskit_ibm_runtime import QiskitRuntimeService service = QiskitRuntimeService(channel="ibm_cloud", token="...", instance="...") ``` -------------------------------- ### Using Fake Backend for Transpilation and Simulation in Qiskit IBM Runtime (Python) Source: https://github.com/qiskit/qiskit-ibm-runtime/blob/main/release-notes/0.15.0.rst This snippet demonstrates how to use a fake backend from `qiskit_ibm_runtime.fake_provider` for local testing. It shows the process of initializing a `FakeManilaV2` backend, creating a quantum circuit, transpiling it for the fake backend, and then running the transpiled circuit to obtain simulation results. This is useful for testing transpiler passes and performing noisy simulations without accessing real quantum hardware. ```Python from qiskit import QuantumCircuit from qiskit import transpile from qiskit_ibm_runtime.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() # Transpile the ideal circuit to a circuit that can be directly executed by the backend transpiled_circuit = transpile(circuit, backend) # Run the transpiled circuit using the simulated fake backend job = backend.run(transpiled_circuit) counts = job.result().get_counts() ``` -------------------------------- ### Using Sampler for Quantum Circuit Sampling in Qiskit IBM Runtime Source: https://github.com/qiskit/qiskit-ibm-runtime/blob/main/release-notes/0.4.0.rst This snippet illustrates the recommended method for quantum circuit sampling using the `Sampler` class. It demonstrates initializing `Sampler` directly with circuits, parameters, service, and backend options, then executing a sampling job within a context manager. ```python from qiskit_ibm_runtime import QiskitRuntimeService, Sampler service = QiskitRuntimeService(channel="ibm_cloud", token="...", instance="...") with Sampler( circuits=[qc], parameters="...", service=service, options={ "backend": "ibmq_qasm_simulator" }, # or IBMBackend<"ibmq_qasm_simulator"> ) as sampler: result = sampler(circuit_indices=[0], ...) ``` -------------------------------- ### Initializing QiskitRuntimeService with Default Credentials (Python) Source: https://github.com/qiskit/qiskit-ibm-runtime/blob/main/release-notes/0.6.0.rst This snippet demonstrates how to initialize the QiskitRuntimeService class without explicitly passing parameters. It leverages the automatic migration of 'ibm_quantum' channel credentials from the qiskitrc file to a newly created or existing qiskit-ibm.json file, simplifying the transition from qiskit-ibmq-provider. ```python from qiskit_ibm_runtime import QiskitRuntimeService service = QiskitRuntimeService() ``` -------------------------------- ### Instantiating Qiskit Runtime Service from Saved Account (Python) Source: https://github.com/qiskit/qiskit-ibm-runtime/blob/main/README.md This Python code demonstrates how to initialize the `QiskitRuntimeService` without any arguments. This method is used when account credentials have been previously saved to disk or configured via environment variables, allowing the service to automatically discover and use them. ```Python from qiskit_ibm_runtime import QiskitRuntimeService service = QiskitRuntimeService() ``` -------------------------------- ### Connecting to IBM Quantum Runtime Service (Legacy and Cloud) - Python Source: https://github.com/qiskit/qiskit-ibm-runtime/blob/main/release-notes/0.1.0.rst This snippet demonstrates how to initialize the `IBMRuntimeService` for both legacy IBM Quantum accounts and IBM Cloud accounts. It shows the required `auth` type, `token`, and an optional `instance` parameter for cloud accounts. ```Python # Legacy from qiskit_ibm_runtime import IBMRuntimeService service = IBMRuntimeService(auth="legacy", token="abc") # Cloud from qiskit_ibm_runtime import IBMRuntimeService service = IBMRuntimeService(auth="cloud", token="abc", instance="IBM Cloud CRN or Service instance name") ``` -------------------------------- ### Configuring IBM Quantum API Environment Variables (Bash) Source: https://github.com/qiskit/qiskit-ibm-runtime/blob/main/CONTRIBUTING.md This snippet provides sample environment variables required for configuring integration tests against the IBM Quantum API. It includes placeholders for the API token, URL, provider instance (hub/group/project), and the specific Quantum Processing Unit (QPU) to be used. These variables are essential for authenticating and targeting the correct IBM Quantum services. ```bash QISKIT_IBM_TOKEN=... # IBM Quantum API token QISKIT_IBM_URL=https://auth.quantum.ibm.com/api # IBM Quantum API URL QISKIT_IBM_INSTANCE=ibm-q/open/main # IBM Quantum provider to use (hub/group/project) QISKIT_IBM_QPU=... # IBM Quantum Processing Unit to use ``` -------------------------------- ### Accessing and Querying IBM Quantum Backends with QiskitRuntimeService (Python) Source: https://github.com/qiskit/qiskit-ibm-runtime/blob/main/README.md This code demonstrates how to interact with IBM Quantum backends using QiskitRuntimeService. It shows how to list all available quantum devices and simulators accessible to the user, retrieve a specific backend by its name (e.g., 'ibm_brisbane'), and then access its attributes, such as the coupling_map, which provides information about qubit connectivity. ```Python from qiskit_ibm_runtime import QiskitRuntimeService service = QiskitRuntimeService() # Display all backends you have access. print(service.backends()) # Get a specific backend. backend = service.backend('ibm_brisbane') # Print backend coupling map. print(backend.coupling_map) ``` -------------------------------- ### Initializing QiskitRuntimeService for Local Testing in Python Source: https://github.com/qiskit/qiskit-ibm-runtime/blob/main/release-notes/0.26.0.rst This snippet demonstrates how to initialize the `QiskitRuntimeService` to use the local testing mode. By setting the `channel` parameter to 'local', an instance of `QiskitRuntimeLocalService` is returned, enabling local development and testing without connecting to a remote IBM Quantum backend. This is useful for rapid iteration and debugging. ```python service = QiskitRuntimeService(channel="local") ``` -------------------------------- ### Building Release Notes with Towncrier for Preview Source: https://github.com/qiskit/qiskit-ibm-runtime/blob/main/CONTRIBUTING.md This command uses Towncrier to build a preview of the unreleased changelog, generating an `unreleased.rst` file. The `--keep` flag ensures the file is retained after the build, allowing for local inspection of the generated release notes. ```bash towncrier build --version=unreleased --keep ``` -------------------------------- ### Invoking Multiple Primitives in a Qiskit Runtime Session (Python) Source: https://github.com/qiskit/qiskit-ibm-runtime/blob/main/release-notes/0.7.0rc1.rst This snippet demonstrates how to initialize a QiskitRuntimeService and use a Session context manager to run both Sampler and Estimator primitives sequentially within the same session. It shows how to prepare quantum circuits and observables, set global options, and retrieve results from each job. This allows for efficient execution of multiple primitive calls on a specified backend. ```Python from qiskit_ibm_runtime import QiskitRuntimeService, Session, Sampler, Estimator, Options from qiskit.test.reference_circuits import ReferenceCircuits from qiskit.circuit.library import RealAmplitudes from qiskit.quantum_info import SparsePauliOp # Initialize account. service = QiskitRuntimeService() # Set options, which can be overwritten at job level. options = Options(optimization_level=1) # Prepare inputs. bell = ReferenceCircuits.bell() psi = RealAmplitudes(num_qubits=2, reps=2) H1 = SparsePauliOp.from_list([("II", 1), ("IZ", 2), ("XI", 3)]) theta = [0, 1, 1, 2, 3, 5] with Session(service=service, backend="ibmq_qasm_simulator") as session: # Submit a request to the Sampler primitive within the session. sampler = Sampler(session=session, options=options) job = sampler.run(circuits=bell) print(f"Sampler results: {job.result()}") # Submit a request to the Estimator primitive within the session. estimator = Estimator(session=session, options=options) job = estimator.run( circuits=[psi], observables=[H1], parameter_values=[theta] ) print(f"Estimator results: {job.result()}") ``` -------------------------------- ### Executing Unit Tests for Qiskit IBM Runtime Source: https://github.com/qiskit/qiskit-ibm-runtime/blob/main/CONTRIBUTING.md This command runs all unit tests for the Qiskit IBM Runtime project. Unit tests are designed to be fast, stable, and run locally without external system connections, providing basic confidence during development. ```bash make unit-test ``` -------------------------------- ### Initializing IBMRuntimeService in Qiskit IBM Runtime (Deprecated) Source: https://github.com/qiskit/qiskit-ibm-runtime/blob/main/release-notes/0.4.0.rst This snippet demonstrates the deprecated method of initializing the runtime service using the `IBMRuntimeService` class. It requires specifying the channel, token, and instance for authentication and connection to the IBM Quantum platform. ```python from qiskit_ibm_runtime import IBMRuntimeService service = IBMRuntimeService(channel="ibm_cloud", token="...", instance="...") ``` -------------------------------- ### Configuring IBM Cloud API Environment Variables (Bash) Source: https://github.com/qiskit/qiskit-ibm-runtime/blob/main/CONTRIBUTING.md This snippet provides sample environment variables for configuring integration tests against the IBM Cloud API. It includes placeholders for the IBM Cloud API key, the Cloud URL, the CRN (Cloud Resource Name) of the Quantum service instance, and the specific Quantum Processing Unit (QPU). These variables are necessary for authenticating and identifying the target IBM Cloud Quantum service. ```bash QISKIT_IBM_TOKEN=... # IBM Cloud API key QISKIT_IBM_URL=https://cloud.ibm.com # Cloud URL QISKIT_IBM_INSTANCE=crn:v1:bluemix:... # The CRN value of the Quantum service instance QISKIT_IBM_QPU=... # The Quantum Processing Unit to use ``` -------------------------------- ### Configuring Simulator Options with set_backend() in Qiskit IBM Runtime (Python) Source: https://github.com/qiskit/qiskit-ibm-runtime/blob/main/release-notes/0.11.2.rst This snippet demonstrates how to use the `set_backend()` method within `qiskit_ibm_runtime.options.SimulatorOptions` to configure simulator settings, such as incorporating a noise model from a fake backend. It initializes a `FakeManila` backend and applies it to the simulator options, also setting a seed for reproducible simulations. This method simplifies the process of tailoring simulator behavior to specific backend characteristics. ```Python from qiskit.providers.fake_provider import FakeManila from qiskit_aer.noise import NoiseModel # Make a noise model fake_backend = FakeManila() # Set options to include the noise model options = Options() options.simulator.set_backend(fake_backend) options.simulator.seed_simulator = 42 ``` -------------------------------- ### Retrieving Backend with Specific Instance in Qiskit IBM Runtime Source: https://github.com/qiskit/qiskit-ibm-runtime/blob/main/release-notes/0.17.0.rst This snippet demonstrates how to retrieve a backend using `service.backend()` with an explicit `instance` parameter, highlighting that an error is raised if the backend is not found within the specified instance. It also illustrates the same error behavior when the instance is set during `QiskitRuntimeService` initialization and a backend not in that instance is subsequently retrieved. ```Python service.backend('ibm_torino', instance='ibm-q/open/main') # raises error if torino is not in ibm-q/open/main but in a different instance # the user has access to service = QiskitRuntimeService(channel="ibm_quantum", instance="ibm-q/open/main") service.backend('ibm_torino') # raises the same error ``` -------------------------------- ### Setting Qiskit Runtime Account Environment Variables (Bash) Source: https://github.com/qiskit/qiskit-ibm-runtime/blob/main/README.md This Bash snippet shows how to configure Qiskit Runtime service authentication using environment variables. By exporting `QISKIT_IBM_TOKEN`, `QISKIT_IBM_INSTANCE`, and `QISKIT_IBM_CHANNEL`, the `QiskitRuntimeService` can automatically load credentials without explicit input or saving to disk. ```Bash export QISKIT_IBM_TOKEN="MY_IBM_CLOUD_API_KEY" export QISKIT_IBM_INSTANCE="MY_IBM_CLOUD_CRN" export QISKIT_IBM_CHANNEL="ibm_cloud" ``` -------------------------------- ### Configuring Session and Primitive Options in Qiskit Runtime (Python) Source: https://github.com/qiskit/qiskit-ibm-runtime/blob/main/release-notes/0.7.0rc1.rst This snippet demonstrates the updated method for configuring session and primitive options, replacing deprecated constructor parameters. It shows how to set optimization_level and resilience_level using the Options class and how to specify a max_time for the session directly in the Session constructor. This centralizes option management and session duration. ```Python from qiskit_ibm_runtime import Session, Sampler, Options options = Options() # This can be done using auto-complete. option.optimization_level = 3 options.resilience_level = 1 with Session(max_time="2h") as session: # Pass the options to Sampler. sampler = Sampler(session=session, options=options) ``` -------------------------------- ### Executing Integration Tests for Qiskit IBM Runtime Source: https://github.com/qiskit/qiskit-ibm-runtime/blob/main/CONTRIBUTING.md This command executes all integration tests for the Qiskit IBM Runtime project. These tests validate client and API interactions against an external system, offering a high level of confidence in the overall system functionality. ```bash make integration-test ``` -------------------------------- ### Running Code Style and Linting Checks (Shell) Source: https://github.com/qiskit/qiskit-ibm-runtime/blob/main/CONTRIBUTING.md This snippet shows shell commands used to enforce code style guidelines and run linting checks. `make lint` executes Pylint, `make style` applies PEP 8 formatting, and `make mypy` performs static type checking. These commands ensure that code changes adhere to the project's established quality and readability standards before submission. ```sh make lint make style make mypy ``` -------------------------------- ### Saving and Loading Qiskit IBM Runtime Account Details from File (Python) Source: https://github.com/qiskit/qiskit-ibm-runtime/blob/main/release-notes/0.9.1.rst This snippet demonstrates how to save Qiskit IBM Runtime account details to a custom file using `QiskitRuntimeService.save_account()` and then load them using the `QiskitRuntimeService` constructor. The `filename` parameter allows specifying a non-default path for account storage. This is useful for managing multiple accounts or specific file locations. ```python QiskitRuntimeService.save_account(channel="ibm_quantum", filename="~/my_account_file.json", name = "my_account", token="my_token") service = QiskitRuntimeService(channel="ibm_quantum", filename="~/my_account_file.json", name = "my_account",) ``` -------------------------------- ### Defining Custom URL Resolver for QiskitRuntimeService in Python Source: https://github.com/qiskit/qiskit-ibm-runtime/blob/main/release-notes/0.30.0.rst This snippet demonstrates how to define and use a custom URL resolver with the `QiskitRuntimeService` constructor. The `url_resolver` function takes `url`, `instance`, and other arguments, returning a custom API URL. This allows for flexible generation of the Qiskit Runtime API URL based on specific requirements, overriding the default resolution logic. ```python # Define a custom resolver. In this case returns the concatenation of the provided `url` and the `instance` def custom_url_resolver(url, instance, *args, **kwargs): return f"{url}/{instance}" service = QiskitRuntimeService(channel="ibm_quantum", instance="ibm-q/open/main", url="https://baseurl.org" url_resolver=custom_url_resolver) # resulting resolved url will be: `https://baseurl.org/ibm-q/open/main` ``` -------------------------------- ### Using IBMSampler for Quantum Circuit Sampling (Deprecated) Source: https://github.com/qiskit/qiskit-ibm-runtime/blob/main/release-notes/0.4.0.rst This snippet shows the deprecated way to perform quantum circuit sampling using the `IBMSampler` class. It involves initializing `IBMSampler` with a service and backend, and then running a sampling job within a context manager. ```python from qiskit_ibm_runtime import IBMRuntimeService, IBMSampler service = IBMRuntimeService(channel="ibm_cloud", token="...", instance="...") sampler_factory = IBMSampler(service=service, backend="ibmq_qasm_simulator") with sampler_factory(circuits=[qc], parameters="...") as sampler: result = sampler(circuit_indices=[0], ...) ``` -------------------------------- ### Enabling IBM Cloud Account for Current Session (Python) Source: https://github.com/qiskit/qiskit-ibm-runtime/blob/main/README.md This Python code snippet enables an IBM Cloud account for the current session by directly passing credentials to the `QiskitRuntimeService` constructor. This approach is suitable for temporary use or environments where persistent storage of credentials is not desired, requiring `channel`, `token`, and `instance`. ```Python from qiskit_ibm_runtime import QiskitRuntimeService # For an IBM Cloud account. ibm_cloud_service = QiskitRuntimeService(channel="ibm_cloud", token="MY_IBM_CLOUD_API_KEY", instance="MY_IBM_CLOUD_CRN") ``` -------------------------------- ### Enabling IBM Quantum Account for Current Session (Python) Source: https://github.com/qiskit/qiskit-ibm-runtime/blob/main/README.md This snippet demonstrates how to enable an IBM Quantum Platform account for the current Python session by initializing `QiskitRuntimeService` with the `channel` set to 'ibm_quantum' and providing the API `token`. This method is session-specific and does not save credentials persistently. ```Python from qiskit_ibm_runtime import QiskitRuntimeService # For an IBM Quantum account. ibm_quantum_service = QiskitRuntimeService(channel="ibm_quantum", token="MY_IBM_QUANTUM_TOKEN") ``` -------------------------------- ### Accessing QiskitRuntimeService from IBMBackend (Python) Source: https://github.com/qiskit/qiskit-ibm-runtime/blob/main/release-notes/0.5.0.rst This snippet demonstrates how to access the `QiskitRuntimeService` instance associated with an `IBMBackend` object. The `service` property of the `IBMBackend` class provides direct access to the service used to instantiate the backend, useful for managing runtime sessions or service-level configurations. ```python backend = service.get_backend("ibmq_qasm_simulator") backend.service # QiskitRuntimeService instance used to instantiate the backend ``` -------------------------------- ### Retrieving IBMBackend with Fractional Gate Support (Python) Source: https://github.com/qiskit/qiskit-ibm-runtime/blob/main/release-notes/0.24.0.rst This code snippet demonstrates how to retrieve an IBMBackend instance from `QiskitRuntimeService` with the `use_fractional_gates` feature enabled. This opt-in feature allows the backend target to include only fractional gates, potentially leading to shorter circuit depths. Users must disable this feature if using control flow instructions like `if_else` in their circuits. ```python from qiskit_ibm_runtime import QiskitRuntimeService backend = QiskitRuntimeService(channel="ibm_quantum").backends( "name_of_your_backend", use_fractional_gates=True, )[0] ``` -------------------------------- ### Saving IBM Quantum Account Credentials to Disk (Python) Source: https://github.com/qiskit/qiskit-ibm-runtime/blob/main/README.md This snippet illustrates how to save IBM Quantum Platform account credentials to disk using `QiskitRuntimeService.save_account`. It sets the `channel` to 'ibm_quantum' and provides your API `token`, allowing the service to automatically load these credentials for subsequent use. ```Python from qiskit_ibm_runtime import QiskitRuntimeService # Save an IBM Quantum account. QiskitRuntimeService.save_account(channel="ibm_quantum", token="MY_IBM_QUANTUM_TOKEN") ``` -------------------------------- ### Using Estimator for Quantum Expectation Values in Qiskit IBM Runtime Source: https://github.com/qiskit/qiskit-ibm-runtime/blob/main/release-notes/0.4.0.rst This snippet demonstrates the recommended approach for calculating expectation values using the `Estimator` class. It shows how to initialize `Estimator` directly with circuits, observables, parameters, service, and backend options, then execute an estimation job within a context manager. ```python from qiskit_ibm_runtime import QiskitRuntimeService, Estimator service = QiskitRuntimeService(channel="ibm_cloud", token="...", instance="...") with Estimator( circuits=[qc], observables="...", parameters="...", service=service, options={ "backend": "ibmq_qasm_simulator" }, # or IBMBackend<"ibmq_qasm_simulator"> ) as estimator: result = estimator(circuit_indices=[0], ...) ``` -------------------------------- ### Executing Quantum Circuits with Qiskit Estimator Primitive (Python) Source: https://github.com/qiskit/qiskit-ibm-runtime/blob/main/README.md This snippet demonstrates how to execute quantum circuits using the Qiskit Estimator primitive. It sets a resilience level option, runs a job with a parameterized circuit and observable, and then prints the job ID and the resulting expectation values. This approach is suitable for single-shot or batched executions. ```Python estimator = Estimator(backend) estimator.options.resilience_level = 1 # Options can be set using auto-complete. job = estimator.run([(isa_circuit, isa_observables, theta1)]) print(f"Job ID is {job.job_id()}") pub_result = job.result()[0] print(f"Expectation values: {pub_result.data.evs}") ``` -------------------------------- ### Visualizing Qiskit IBM Runtime Execution Spans - Python Source: https://github.com/qiskit/qiskit-ibm-runtime/blob/main/release-notes/0.32.0.rst This snippet demonstrates how to use `draw_execution_spans` to visualize multiple `ExecutionSpans` objects from sampler job data and how to use the convenience method `spans.draw()` to plot a single instance. It requires `ExecutionSpans` objects, typically obtained from job metadata, and outputs a Plotly figure. ```Python from qiskit_ibm_runtime.visualization import draw_execution_spans # use the drawing function on spans from sampler job data spans1 = sampler_job1.result().metadata["execution"]["execution_spans"] spans2 = sampler_job2.result().metadata["execution"]["execution_spans"] draw_execution_spans(spans1, spans2) # convenience to plot just spans1 spans1.draw() ``` -------------------------------- ### Using Sampler with Deprecated Indices and New Object Parameters (Python) Source: https://github.com/qiskit/qiskit-ibm-runtime/blob/main/release-notes/0.5.0.rst This snippet demonstrates the updated method for passing circuits to the `Sampler` primitive. Similar to the `Estimator`, the `circuits` parameter now accepts either indices or the quantum circuit objects directly, replacing the deprecated `circuit_indices`. This change simplifies usage and prepares for future API consistency. ```python with Sampler( circuits=[qc1, qc2], service=service, options=options ) as sampler: # pass circuits as indices result = sampler(circuits=[0, 1], parameter_values=[theta1, theta2]) # pass circuit as objects result = sampler(circuits=[qc1, qc2], parameter_values=[theta2, theta3]) ``` -------------------------------- ### Documenting Deprecated Python Functions with Sphinx Source: https://github.com/qiskit/qiskit-ibm-runtime/blob/main/DEPRECATION.md This Python code snippet illustrates how to use the Sphinx `.. deprecated::` directive within a function's docstring to clearly mark it as deprecated. It includes the version of deprecation, removal timeline, and a suggested alternative, ensuring this information is visible in the API reference documentation. ```Python def deprecated_function(): """ Short description of the deprecated function. .. deprecated:: 0.14.0 The function qiskit_ibm_runtime.deprecated_function() is deprecated since qiskit_ibm_runtime 0.14.0, and will be removed 3 months or more later. Instead, you should use qiskit_ibm_runtime.other_function(). """ # ... the rest of the function ... ``` -------------------------------- ### Saving IBM Cloud Account Credentials to Disk (Python) Source: https://github.com/qiskit/qiskit-ibm-runtime/blob/main/README.md This Python code uses `QiskitRuntimeService.save_account` to persistently store IBM Cloud credentials on disk. It requires specifying the `channel` as 'ibm_cloud', along with your `token` (API key) and `instance` (Cloud Resource Name), enabling automatic authentication in future sessions. ```Python from qiskit_ibm_runtime import QiskitRuntimeService # Save an IBM Cloud account. QiskitRuntimeService.save_account(channel="ibm_cloud", token="MY_IBM_CLOUD_API_KEY", instance="MY_IBM_CLOUD_CRN") ``` -------------------------------- ### Setting Simulator Coupling Map with CouplingMap Object in Qiskit IBM Runtime (Python) Source: https://github.com/qiskit/qiskit-ibm-runtime/blob/main/release-notes/0.11.0.rst This snippet demonstrates the newly supported way to set a simulator's coupling map in Qiskit IBM Runtime using a `CouplingMap` object. This allows for more complex and programmatically generated coupling maps, such as one derived from a linear topology of 10 qubits. ```python options.simulator = {"coupling_map": CouplingMap.from_line(10)} ``` -------------------------------- ### Setting Simulator Coupling Map with List in Qiskit IBM Runtime (Python) Source: https://github.com/qiskit/qiskit-ibm-runtime/blob/main/release-notes/0.11.0.rst This code snippet illustrates the previous method for configuring a simulator's coupling map within Qiskit IBM Runtime options. It uses a list of integer pairs to define the connections between qubits, where each pair represents a directed edge in the coupling map. ```python options.simulator = {"coupling_map": [[0, 1], [1, 0]]} ``` -------------------------------- ### Using IBMEstimator for Quantum Expectation Values (Deprecated) Source: https://github.com/qiskit/qiskit-ibm-runtime/blob/main/release-notes/0.4.0.rst This snippet illustrates the deprecated usage of `IBMEstimator` for calculating expectation values of quantum circuits. It shows how to initialize `IBMEstimator` with a service and backend, and then use it within a context manager to run an estimation job. ```python from qiskit_ibm_runtime import IBMRuntimeService, IBMEstimator service = IBMRuntimeService(channel="ibm_cloud", token="...", instance="...") estimator_factory = IBMEstimator(service=service, backend="ibmq_qasm_simulator") with estimator_factory(circuits=[qc], observables="...", parameters="...") as estimator: result = estimator(circuit_indices=[0], ...) ``` -------------------------------- ### Issuing Deprecation Warning in Python Source: https://github.com/qiskit/qiskit-ibm-runtime/blob/main/DEPRECATION.md This snippet demonstrates how to manually issue a `DeprecationWarning` using Python's standard `warnings` module. It shows how to construct a warning message that includes the deprecation version, removal timeline, and an alternative function, setting `stacklevel=2` to correctly attribute the warning to the calling function. ```Python import warnings def deprecated_function(): warnings.warn( "The function qiskit.deprecated_function() is deprecated since " "qiskit-ibm-runtime 0.14.0, and will be removed 3 months or more later. " "Instead, you should use qiskit.other_function().", category=DeprecationWarning, stacklevel=2, ) # ... the rest of the function ... ``` -------------------------------- ### Testing Deprecated Functionality in Python Source: https://github.com/qiskit/qiskit-ibm-runtime/blob/main/DEPRECATION.md This snippet illustrates how to write a unit test for deprecated functionality in a Python `unittest.TestCase` subclass (specifically `QiskitTestCase`). It uses `self.assertWarns(DeprecationWarning)` as a context manager to ensure that calling the deprecated function issues the expected warning, allowing the test suite to pass while still verifying the function's behavior. ```Python class MyTestSuite(QiskitTestCase): def test_deprecated_function(self): with self.assertWarns(DeprecationWarning): output = deprecated_function() # ... do some things with output ... self.assertEqual(output, expected) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.