qiskit-ibm-runtime


Nameqiskit-ibm-runtime JSON
Version 0.33.2 PyPI version JSON
download
home_pagehttps://github.com/Qiskit/qiskit-ibm-runtime
SummaryIBM Quantum client for Qiskit Runtime.
upload_time2024-11-11 20:38:40
maintainerNone
docs_urlNone
authorQiskit Development Team
requires_python>=3.8
licenseApache 2.0
keywords qiskit sdk quantum api runtime ibm
VCS
bugtrack_url
requirements requests requests_ntlm numpy urllib3 python-dateutil websocket-client typing-extensions ibm-platform-services pydantic qiskit
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Qiskit Runtime IBM Client
[![License](https://img.shields.io/github/license/Qiskit/qiskit-ibm-runtime.svg?style=popout-square)](https://opensource.org/licenses/Apache-2.0)
[![CI](https://github.com/Qiskit/qiskit-ibm-runtime/actions/workflows/ci.yml/badge.svg)](https://github.com/Qiskit/qiskit-ibm-runtime/actions/workflows/ci.yml)
[![](https://img.shields.io/github/release/Qiskit/qiskit-ibm-runtime.svg?style=popout-square)](https://github.com/Qiskit/qiskit-ibm-runtime/releases)
[![](https://img.shields.io/pypi/dm/qiskit-ibm-runtime.svg?style=popout-square)](https://pypi.org/project/qiskit-ibm-runtime/)
[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)
[![Coverage Status](https://coveralls.io/repos/github/Qiskit/qiskit-ibm-runtime/badge.svg?branch=main)](https://coveralls.io/github/Qiskit/qiskit-ibm-runtime?branch=main)


**Qiskit** is an open-source SDK for working with quantum computers at the level of extended quantum circuits, operators, and primitives.

**Qiskit IBM Runtime** is a new environment offered by IBM Quantum that streamlines quantum computations and provides optimal
implementations of the Qiskit primitives `sampler` and `estimator` for IBM Quantum hardware. It is designed to use additional classical compute resources to execute quantum circuits with more efficiency on quantum processors, by including near-time computations such as error suppression and error mitigation. Examples of error suppression include dynamical decoupling, noise-aware compilation, error mitigation including readout mitigation, zero-noise extrapolation (ZNE), and probabilistic error cancellation (PEC).

Using the runtime service, a research team at IBM Quantum was able to achieve a 120x speedup
in their lithium hydride simulation. For more information, see the
[IBM Research blog](https://research.ibm.com/blog/120x-quantum-speedup).

This module provides the interface to access the Qiskit Runtime service on IBM Quantum Platform or IBM Cloud.

## Installation

You can install this package using pip:

```bash
pip install qiskit-ibm-runtime
```

## Account setup

### Qiskit Runtime service on IBM Quantum Platform

You will need your IBM Quantum API token to authenticate with the runtime service:

1. Create an IBM Quantum account or log in to your existing account by visiting the [IBM Quantum login page].

1. Copy (and optionally regenerate) your API token from your
   [IBM Quantum account page].

### Qiskit Runtime service on IBM Cloud

The runtime service is now part of the IBM Quantum Services on IBM Cloud. To use this service, you'll
need to create an IBM Cloud account and a quantum service instance.
[This guide](https://cloud.ibm.com/docs/quantum-computing?topic=quantum-computing-get-started)
contains step-by-step instructions, including how to find your
IBM Cloud API key and Cloud Resource Name (CRN), which you will need for authentication.


### Save your account on disk

Once you have the account credentials, you can save them on disk, so you won't have to input
them each time. The credentials are saved in the `$HOME/.qiskit/qiskit-ibm.json` file, where `$HOME` is your home directory.

| :warning: Account credentials are saved in plain text, so only do so if you are using a trusted device. |
|:---------------------------|

 ```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")

# Save an IBM Quantum account.
QiskitRuntimeService.save_account(channel="ibm_quantum", token="MY_IBM_QUANTUM_TOKEN")
```

Once the account is saved on disk, you can instantiate the service without any arguments:

```python
from qiskit_ibm_runtime import QiskitRuntimeService
service = QiskitRuntimeService()
```

### Loading account from environment variables

Alternatively, the service can discover credentials from environment variables:
```bash
export QISKIT_IBM_TOKEN="MY_IBM_CLOUD_API_KEY"
export QISKIT_IBM_INSTANCE="MY_IBM_CLOUD_CRN"
export QISKIT_IBM_CHANNEL="ibm_cloud"
```

Then instantiate the service without any arguments:
```python
from qiskit_ibm_runtime import QiskitRuntimeService
service = QiskitRuntimeService()
```

### Enabling account for current Python session

As another alternative, you can also enable an account just for the current session by instantiating the
service with your credentials.

```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")

# For an IBM Quantum account.
ibm_quantum_service = QiskitRuntimeService(channel="ibm_quantum", token="MY_IBM_QUANTUM_TOKEN")
```

## Primitives

All quantum applications and algorithms level are fundamentally built using these steps:
1. Map classical inputs to a quantum problem
2. Translate problem for optimized quantum execution.
3. Execute the quantum circuits by using a primitive (Estimator or Sampler).
4. Post-process, return result in classical format.

**Primitives** are base-level functions that serve as building blocks for many quantum algorithms and applications.
Primitives accept vectorized inputs, where single circuits can be grouped with array-valued specifications. That is, one circuit can be executed for arrays of n parameter sets, n observables, or both (in the case of the estimator). Each group is called a Primitive Unified Bloc (PUB), and can be represented as a tuple.

The [primitive interfaces](https://docs.quantum.ibm.com/api/qiskit/primitives) are defined in Qiskit.

The IBM Runtime service offers these primitives with additional features, such as built-in error suppression and mitigation.

There are several different options you can specify when calling the primitives. See [Primitive options](https://docs.quantum.ibm.com/api/qiskit-ibm-runtime/options) for more information.

### Primitive versions

Version 2 of the primitives is introduced by `qiskit-ibm-runtime` release 0.21.0. Version 1 of the primitives is no longer supported. Refer to [Migrate to the V2 primitives](https://docs.quantum.ibm.com/migration-guides/v2-primitives) on how to migratie to V2 primitives. The examples below all use V2 primitives.

### Sampler

This primitive takes a list of user circuits (including measurements) as input and returns the sampling output. The type of the output is defined by the program (typically bit-arrays), and the output data is separated by the classical register names.

To invoke the `Sampler` primitive

```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()}")
```

### Estimator

This primitive takes circuits and observables as input, to evaluate expectation values and standard error for a given parameter input. This Estimator allows users to efficiently calculate and interpret expectation values of quantum operators required for many algorithms.

To invoke the `Estimator` primitive:

```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)

# 3. Execute using the Estimator primitive
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}")
```

This code batches together 50 parameters to be executed in a single job. If a user wanted to find the `theta` that optimized the observable, they could plot and observe it occurs at `theta=np.pi/2`. For speed we recommend batching results together (note that depending on your access, there may be limits on the number of circuits, objects, and parameters that you can send).


## Session

In many algorithms and applications, an Estimator needs to be called iteratively without incurring queuing delays on each iteration. To solve this, the IBM Runtime service provides a **Session**. A session starts when the first job within the session is started, and subsequent jobs within the session are prioritized by the scheduler.

You can use the [`qiskit_ibm_runtime.Session`](https://github.com/Qiskit/qiskit-ibm-runtime/blob/main/qiskit_ibm_runtime/session.py) class to start a
session. Consider the same example above and try to find the optimal `theta`. The following example uses the [golden search method](https://en.wikipedia.org/wiki/Golden-section_search) to iteratively find the optimal theta that maximizes the observable.

To invoke the `Estimator` primitive within a session:

```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}")
```

This code returns `Job result is [4.] at theta = 1.575674623307102` using only nine iterations. This is a very powerful extension to the primitives. However, using too much code between iterative calls can lock the QPU and use excessive QPU time, which is expensive. We recommend only using sessions when needed. The Sampler can also be used within a session, but there are not any well-defined examples for this.

## Instances

Access to IBM Quantum Platform channel is controlled by the instances (previously called providers) to which you are assigned. An instance is defined by a hierarchical organization of hub, group, and project. A hub is the top level of a given hierarchy (organization) and contains within it one or more groups. These groups are in turn populated with projects. The combination of hub/group/project is called an instance. Users can belong to more than one instance at any time.

> **_NOTE:_** IBM Cloud instances are different from IBM Quantum Platform instances.  IBM Cloud does not use the hub/group/project structure for user management. To view and create IBM Cloud instances, visit the [IBM Cloud Quantum Instances page](https://cloud.ibm.com/quantum/instances).

To view a list of your instances, visit your [account settings page](https://www.quantum-computing.ibm.com/account) or use the `instances()` method.

You can specify an instance when initializing the service or provider, or when picking a backend:

```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
```

If you do not specify an instance, then the code will select one in the following order:

1. If your account only has access to one instance, it is selected by default.
2. If your account has access to multiple instances, but only one can access the requested backend, the instance with access is selected.
3. In all other cases, the code selects the first instance other than ibm-q/open/main that has access to the backend.

## Access your IBM Quantum backends

A **backend** is a quantum device or simulator capable of running quantum circuits or pulse schedules.

You can query for the backends you have access to. Attributes and methods of the returned instances
provide information, such as qubit counts, error rates, and statuses, of the backends.

```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)
```

## Next Steps

Now you're set up and ready to check out some of the [tutorials].

## Contribution guidelines

If you'd like to contribute to qiskit-ibm-runtime, please take a look at our
[contribution guidelines]. This project adheres to Qiskit's [code of conduct].
By participating, you are expected to uphold to this code.

We use [GitHub issues] for tracking requests and bugs. Please use our [slack]
for discussion and simple questions. To join our Slack community use the
invite link at [ibm.com/quantum/qiskit]. For questions that are more suited for a forum we
use the `Qiskit` tag in [Stack Exchange].

## Authors and Citation

Qiskit Runtime IBM Client is the work of [many people](https://github.com/Qiskit/qiskit-ibm-runtime/graphs/contributors) who contribute to the project at different levels.
If you use Qiskit, please cite as per the included [BibTeX file](https://github.com/Qiskit/qiskit/blob/main/CITATION.bib).

## License

[Apache License 2.0].


[IBM Quantum]: https://www.ibm.com/quantum-computing/
[IBM Quantum login page]:  https://quantum-computing.ibm.com/login
[IBM Quantum account page]: https://quantum-computing.ibm.com/account
[contribution guidelines]: https://github.com/Qiskit/qiskit-ibm-runtime/blob/main/CONTRIBUTING.md
[code of conduct]: https://github.com/Qiskit/qiskit-ibm-runtime/blob/main/CODE_OF_CONDUCT.md
[GitHub issues]: https://github.com/Qiskit/qiskit-ibm-runtime/issues
[slack]: https://qiskit.slack.com
[ibm.com/quantum/qiskit]: https://www.ibm.com/quantum/qiskit
[Stack Exchange]: https://quantumcomputing.stackexchange.com/questions/tagged/qiskit
[many people]: https://github.com/Qiskit/qiskit-ibm-runtime/graphs/contributors
[BibTeX file]: https://github.com/Qiskit/qiskit/blob/master/Qiskit.bib
[Apache License 2.0]: https://github.com/Qiskit/qiskit-ibm-runtime/blob/main/LICENSE.txt
[tutorials]: https://learning.quantum.ibm.com/catalog/tutorials

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/Qiskit/qiskit-ibm-runtime",
    "name": "qiskit-ibm-runtime",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": null,
    "keywords": "qiskit sdk quantum api runtime ibm",
    "author": "Qiskit Development Team",
    "author_email": "qiskit@us.ibm.com",
    "download_url": "https://files.pythonhosted.org/packages/1b/0e/e48b198760d702a378dc43a9f581067153fee16bad041253978516847a75/qiskit_ibm_runtime-0.33.2.tar.gz",
    "platform": null,
    "description": "# Qiskit Runtime IBM Client\n[![License](https://img.shields.io/github/license/Qiskit/qiskit-ibm-runtime.svg?style=popout-square)](https://opensource.org/licenses/Apache-2.0)\n[![CI](https://github.com/Qiskit/qiskit-ibm-runtime/actions/workflows/ci.yml/badge.svg)](https://github.com/Qiskit/qiskit-ibm-runtime/actions/workflows/ci.yml)\n[![](https://img.shields.io/github/release/Qiskit/qiskit-ibm-runtime.svg?style=popout-square)](https://github.com/Qiskit/qiskit-ibm-runtime/releases)\n[![](https://img.shields.io/pypi/dm/qiskit-ibm-runtime.svg?style=popout-square)](https://pypi.org/project/qiskit-ibm-runtime/)\n[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)\n[![Coverage Status](https://coveralls.io/repos/github/Qiskit/qiskit-ibm-runtime/badge.svg?branch=main)](https://coveralls.io/github/Qiskit/qiskit-ibm-runtime?branch=main)\n\n\n**Qiskit** is an open-source SDK for working with quantum computers at the level of extended quantum circuits, operators, and primitives.\n\n**Qiskit IBM Runtime** is a new environment offered by IBM Quantum that streamlines quantum computations and provides optimal\nimplementations of the Qiskit primitives `sampler` and `estimator` for IBM Quantum hardware. It is designed to use additional classical compute resources to execute quantum circuits with more efficiency on quantum processors, by including near-time computations such as error suppression and error mitigation. Examples of error suppression include dynamical decoupling, noise-aware compilation, error mitigation including readout mitigation, zero-noise extrapolation (ZNE), and probabilistic error cancellation (PEC).\n\nUsing the runtime service, a research team at IBM Quantum was able to achieve a 120x speedup\nin their lithium hydride simulation. For more information, see the\n[IBM Research blog](https://research.ibm.com/blog/120x-quantum-speedup).\n\nThis module provides the interface to access the Qiskit Runtime service on IBM Quantum Platform or IBM Cloud.\n\n## Installation\n\nYou can install this package using pip:\n\n```bash\npip install qiskit-ibm-runtime\n```\n\n## Account setup\n\n### Qiskit Runtime service on IBM Quantum Platform\n\nYou will need your IBM Quantum API token to authenticate with the runtime service:\n\n1. Create an IBM Quantum account or log in to your existing account by visiting the [IBM Quantum login page].\n\n1. Copy (and optionally regenerate) your API token from your\n   [IBM Quantum account page].\n\n### Qiskit Runtime service on IBM Cloud\n\nThe runtime service is now part of the IBM Quantum Services on IBM Cloud. To use this service, you'll\nneed to create an IBM Cloud account and a quantum service instance.\n[This guide](https://cloud.ibm.com/docs/quantum-computing?topic=quantum-computing-get-started)\ncontains step-by-step instructions, including how to find your\nIBM Cloud API key and Cloud Resource Name (CRN), which you will need for authentication.\n\n\n### Save your account on disk\n\nOnce you have the account credentials, you can save them on disk, so you won't have to input\nthem each time. The credentials are saved in the `$HOME/.qiskit/qiskit-ibm.json` file, where `$HOME` is your home directory.\n\n| :warning: Account credentials are saved in plain text, so only do so if you are using a trusted device. |\n|:---------------------------|\n\n ```python\nfrom qiskit_ibm_runtime import QiskitRuntimeService\n\n# Save an IBM Cloud account.\nQiskitRuntimeService.save_account(channel=\"ibm_cloud\", token=\"MY_IBM_CLOUD_API_KEY\", instance=\"MY_IBM_CLOUD_CRN\")\n\n# Save an IBM Quantum account.\nQiskitRuntimeService.save_account(channel=\"ibm_quantum\", token=\"MY_IBM_QUANTUM_TOKEN\")\n```\n\nOnce the account is saved on disk, you can instantiate the service without any arguments:\n\n```python\nfrom qiskit_ibm_runtime import QiskitRuntimeService\nservice = QiskitRuntimeService()\n```\n\n### Loading account from environment variables\n\nAlternatively, the service can discover credentials from environment variables:\n```bash\nexport QISKIT_IBM_TOKEN=\"MY_IBM_CLOUD_API_KEY\"\nexport QISKIT_IBM_INSTANCE=\"MY_IBM_CLOUD_CRN\"\nexport QISKIT_IBM_CHANNEL=\"ibm_cloud\"\n```\n\nThen instantiate the service without any arguments:\n```python\nfrom qiskit_ibm_runtime import QiskitRuntimeService\nservice = QiskitRuntimeService()\n```\n\n### Enabling account for current Python session\n\nAs another alternative, you can also enable an account just for the current session by instantiating the\nservice with your credentials.\n\n```python\nfrom qiskit_ibm_runtime import QiskitRuntimeService\n\n# For an IBM Cloud account.\nibm_cloud_service = QiskitRuntimeService(channel=\"ibm_cloud\", token=\"MY_IBM_CLOUD_API_KEY\", instance=\"MY_IBM_CLOUD_CRN\")\n\n# For an IBM Quantum account.\nibm_quantum_service = QiskitRuntimeService(channel=\"ibm_quantum\", token=\"MY_IBM_QUANTUM_TOKEN\")\n```\n\n## Primitives\n\nAll quantum applications and algorithms level are fundamentally built using these steps:\n1. Map classical inputs to a quantum problem\n2. Translate\u00a0problem for optimized\u00a0quantum execution.\n3. Execute the quantum circuits by using a primitive (Estimator or Sampler).\n4. Post-process, return result in classical format.\n\n**Primitives** are base-level functions that serve as building blocks for many quantum algorithms and applications.\nPrimitives accept vectorized inputs, where single circuits can be grouped with array-valued specifications. That is, one circuit can be executed for arrays of n parameter sets, n observables, or both (in the case of the estimator). Each group is called a Primitive Unified Bloc (PUB), and can be represented as a tuple.\n\nThe [primitive interfaces](https://docs.quantum.ibm.com/api/qiskit/primitives) are defined in Qiskit.\n\nThe IBM Runtime service offers these primitives with additional features, such as built-in error suppression and mitigation.\n\nThere are several different options you can specify when calling the primitives. See [Primitive options](https://docs.quantum.ibm.com/api/qiskit-ibm-runtime/options) for more information.\n\n### Primitive versions\n\nVersion 2 of the primitives is introduced by `qiskit-ibm-runtime` release 0.21.0. Version 1 of the primitives is no longer supported. Refer to [Migrate to the V2 primitives](https://docs.quantum.ibm.com/migration-guides/v2-primitives) on how to migratie to V2 primitives. The examples below all use V2 primitives.\n\n### Sampler\n\nThis primitive takes a list of user circuits (including measurements) as input and returns the sampling output. The type of the output is defined by the program (typically bit-arrays), and the output data is separated by the classical register names.\n\nTo invoke the `Sampler` primitive\n\n```python\nfrom qiskit import QuantumCircuit\nfrom qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager\nfrom qiskit_ibm_runtime import QiskitRuntimeService, SamplerV2 as Sampler\n\nservice = QiskitRuntimeService()\n\n# 1. A quantum circuit for preparing the quantum state (|00> + |11>)/rt{2}\nbell = QuantumCircuit(2)\nbell.h(0)\nbell.cx(0, 1)\nbell.measure_all()\n\n# 2: Optimize problem for quantum execution.\nbackend = service.least_busy(operational=True, simulator=False)\npm = generate_preset_pass_manager(backend=backend, optimization_level=1)\nisa_circuit = pm.run(bell)\n\n# 3. Execute using the Sampler primitive\nsampler = Sampler(mode=backend)\nsampler.options.default_shots = 1024  # Options can be set using auto-complete.\njob = sampler.run([isa_circuit])\nprint(f\"Job ID is {job.job_id()}\")\npub_result = job.result()[0]\nprint(f\"Counts for the meas output register: {pub_result.data.meas.get_counts()}\")\n```\n\n### Estimator\n\nThis primitive takes circuits and observables as input, to evaluate expectation values and standard error for a given parameter input. This Estimator allows users to efficiently calculate and interpret expectation values of quantum operators required for many algorithms.\n\nTo invoke the `Estimator` primitive:\n\n```python\nfrom qiskit_ibm_runtime import QiskitRuntimeService, EstimatorV2 as Estimator\nfrom qiskit.quantum_info import SparsePauliOp\nfrom qiskit import QuantumCircuit\nfrom qiskit.circuit import Parameter\nimport numpy as np\n\nservice = QiskitRuntimeService()\n\n# 1. A quantum circuit for preparing the quantum state (|000> + e^{itheta} |111>)/rt{2}\ntheta = Parameter('\u03b8')\ncircuit = QuantumCircuit(3)\ncircuit.h(0) # generate superposition\ncircuit.p(theta, 0) # add quantum phase\ncircuit.cx(0, 1) # condition 1st qubit on 0th qubit\ncircuit.cx(0, 2) # condition 2nd qubit on 0th qubit\n\n# The observable to be measured\nM1 = SparsePauliOp.from_list([(\"XXY\", 1), (\"XYX\", 1), (\"YXX\", 1), (\"YYY\", -1)])\n\n# batch of theta parameters to be executed\npoints = 50\ntheta1 = []\nfor x in range(points):\n    theta = [x*2.0*np.pi/50]\n    theta1.append(theta)\n\n# 2: Optimize problem for quantum execution.\nbackend = service.least_busy(operational=True, simulator=False)\npm = generate_preset_pass_manager(backend=backend, optimization_level=1)\nisa_circuit = pm.run(circuit)\nisa_observables = M1.apply_layout(isa_circuit.layout)\n\n# 3. Execute using the Estimator primitive\nestimator = Estimator(backend)\nestimator.options.resilience_level = 1  # Options can be set using auto-complete.\njob = estimator.run([(isa_circuit, isa_observables, theta1)])\nprint(f\"Job ID is {job.job_id()}\")\npub_result = job.result()[0]\nprint(f\"Expectation values: {pub_result.data.evs}\")\n```\n\nThis code batches together 50 parameters to be executed in a single job. If a user wanted to find the `theta` that optimized the observable, they could plot and observe it occurs at `theta=np.pi/2`. For speed we recommend batching results together (note that depending on your access, there may be limits on the number of circuits, objects, and parameters that you can send).\n\n\n## Session\n\nIn many algorithms and applications, an Estimator needs to be called iteratively without incurring queuing delays on each iteration. To solve this, the IBM Runtime service provides a **Session**. A session starts when the first job within the session is started, and subsequent jobs within the session are prioritized by the scheduler.\n\nYou can use the [`qiskit_ibm_runtime.Session`](https://github.com/Qiskit/qiskit-ibm-runtime/blob/main/qiskit_ibm_runtime/session.py) class to start a\nsession. Consider the same example above and try to find the optimal `theta`. The following example uses the [golden search method](https://en.wikipedia.org/wiki/Golden-section_search) to iteratively find the optimal theta that maximizes the observable.\n\nTo invoke the `Estimator` primitive within a session:\n\n```python\nfrom qiskit_ibm_runtime import QiskitRuntimeService, Session, EstimatorV2 as Estimator\nfrom qiskit.quantum_info import SparsePauliOp\nfrom qiskit import QuantumCircuit\nfrom qiskit.circuit import Parameter\nimport numpy as np\n\nservice = QiskitRuntimeService()\n\n# 1. A quantum circuit for preparing the quantum state (|000> + e^{itheta} |111>)/rt{2}\ntheta = Parameter('\u03b8')\ncircuit = QuantumCircuit(3)\ncircuit.h(0) # generate superpostion\ncircuit.p(theta,0) # add quantum phase\ncircuit.cx(0, 1) # condition 1st qubit on 0th qubit\ncircuit.cx(0, 2) # condition 2nd qubit on 0th qubit\n\n# The observable to be measured\nM1 = SparsePauliOp.from_list([(\"XXY\", 1), (\"XYX\", 1), (\"YXX\", 1), (\"YYY\", -1)])\n\ngr = (np.sqrt(5) + 1) / 2 # golden ratio\nthetaa = 0 # lower range of theta\nthetab = 2*np.pi # upper range of theta\ntol = 1e-1 # tol\n\n# 2: Optimize problem for quantum execution.\nbackend = service.least_busy(operational=True, simulator=False)\npm = generate_preset_pass_manager(backend=backend, optimization_level=1)\nisa_circuit = pm.run(circuit)\nisa_observables = M1.apply_layout(isa_circuit.layout)\n\n# 3. Execute iteratively using the Estimator primitive\nwith Session(backend=backend) as session:\n    estimator = Estimator(mode=session)\n    estimator.options.default_precision = 0.03  # Options can be set using auto-complete.\n    #next test range\n    thetac = thetab - (thetab - thetaa) / gr\n    thetad = thetaa + (thetab - thetaa) / gr\n    while abs(thetab - thetaa) > tol:\n        print(f\"max value of M1 is in the range theta = {[thetaa, thetab]}\")\n        job = estimator.run([(isa_circuit, isa_observables, [[thetac],[thetad]])])\n        test = job.result()[0].data.evs\n        if test[0] > test[1]:\n            thetab = thetad\n        else:\n            thetaa = thetac\n        thetac = thetab - (thetab - thetaa) / gr\n        thetad = thetaa + (thetab - thetaa) / gr\n\n    # Final job to evaluate Estimator at midpoint found using golden search method\n    theta_mid = (thetab + thetaa) / 2\n    job = estimator.run([(isa_circuit, isa_observables, theta_mid)])\n    print(f\"Session ID is {session.session_id}\")\n    print(f\"Final Job ID is {job.job_id()}\")\n    print(f\"Job result is {job.result()[0].data.evs} at theta = {theta_mid}\")\n```\n\nThis code returns `Job result is [4.] at theta = 1.575674623307102` using only nine iterations. This is a very powerful extension to the primitives. However, using too much code between iterative calls can lock the QPU and use excessive QPU time, which is expensive. We recommend only using sessions when needed. The Sampler can also be used within a session, but there are not any well-defined examples for this.\n\n## Instances\n\nAccess to IBM Quantum Platform channel is controlled by the instances (previously called providers) to which you are assigned. An instance is defined by a hierarchical organization of hub, group, and project. A hub is the top level of a given hierarchy (organization) and contains within it one or more groups. These groups are in turn populated with projects. The combination of hub/group/project is called an instance. Users can belong to more than one instance at any time.\n\n> **_NOTE:_** IBM Cloud instances are different from IBM Quantum Platform instances.  IBM Cloud does not use the hub/group/project structure for user management. To view and create IBM Cloud instances, visit the [IBM Cloud Quantum Instances page](https://cloud.ibm.com/quantum/instances).\n\nTo view a list of your instances, visit your [account settings page](https://www.quantum-computing.ibm.com/account) or use the `instances()` method.\n\nYou can specify an instance when initializing the service or provider, or when picking a backend:\n\n```python\n# Optional: List all the instances you can access.\nservice = QiskitRuntimeService(channel='ibm_quantum')\nprint(service.instances())\n\n# Optional: Specify the instance at service level. This becomes the default unless overwritten.\nservice = QiskitRuntimeService(channel='ibm_quantum', instance=\"hub1/group1/project1\")\nbackend1 = service.backend(\"ibmq_manila\")\n\n# Optional: Specify the instance at the backend level, which overwrites the service-level specification when this backend is used.\nbackend2 = service.backend(\"ibmq_manila\", instance=\"hub2/group2/project2\")\n\nsampler1 = Sampler(mode=backend1)    # this will use hub1/group1/project1\nsampler2 = Sampler(mode=backend2)    # this will use hub2/group2/project2\n```\n\nIf you do not specify an instance, then the code will select one in the following order:\n\n1. If your account only has access to one instance, it is selected by default.\n2. If your account has access to multiple instances, but only one can access the requested backend, the instance with access is selected.\n3. In all other cases, the code selects the first instance other than ibm-q/open/main that has access to the backend.\n\n## Access your IBM Quantum backends\n\nA **backend** is a quantum device or simulator capable of running quantum circuits or pulse schedules.\n\nYou can query for the backends you have access to. Attributes and methods of the returned instances\nprovide information, such as qubit counts, error rates, and statuses, of the backends.\n\n```python\nfrom qiskit_ibm_runtime import QiskitRuntimeService\nservice = QiskitRuntimeService()\n\n# Display all backends you have access.\nprint(service.backends())\n\n# Get a specific backend.\nbackend = service.backend('ibm_brisbane')\n\n# Print backend coupling map.\nprint(backend.coupling_map)\n```\n\n## Next Steps\n\nNow you're set up and ready to check out some of the [tutorials].\n\n## Contribution guidelines\n\nIf you'd like to contribute to qiskit-ibm-runtime, please take a look at our\n[contribution guidelines]. This project adheres to Qiskit's [code of conduct].\nBy participating, you are expected to uphold to this code.\n\nWe use [GitHub issues] for tracking requests and bugs. Please use our [slack]\nfor discussion and simple questions. To join our Slack community use the\ninvite link at [ibm.com/quantum/qiskit]. For questions that are more suited for a forum we\nuse the `Qiskit` tag in [Stack Exchange].\n\n## Authors and Citation\n\nQiskit Runtime IBM Client is the work of [many people](https://github.com/Qiskit/qiskit-ibm-runtime/graphs/contributors) who contribute to the project at different levels.\nIf you use Qiskit, please cite as per the included [BibTeX file](https://github.com/Qiskit/qiskit/blob/main/CITATION.bib).\n\n## License\n\n[Apache License 2.0].\n\n\n[IBM Quantum]: https://www.ibm.com/quantum-computing/\n[IBM Quantum login page]:  https://quantum-computing.ibm.com/login\n[IBM Quantum account page]: https://quantum-computing.ibm.com/account\n[contribution guidelines]: https://github.com/Qiskit/qiskit-ibm-runtime/blob/main/CONTRIBUTING.md\n[code of conduct]: https://github.com/Qiskit/qiskit-ibm-runtime/blob/main/CODE_OF_CONDUCT.md\n[GitHub issues]: https://github.com/Qiskit/qiskit-ibm-runtime/issues\n[slack]: https://qiskit.slack.com\n[ibm.com/quantum/qiskit]: https://www.ibm.com/quantum/qiskit\n[Stack Exchange]: https://quantumcomputing.stackexchange.com/questions/tagged/qiskit\n[many people]: https://github.com/Qiskit/qiskit-ibm-runtime/graphs/contributors\n[BibTeX file]: https://github.com/Qiskit/qiskit/blob/master/Qiskit.bib\n[Apache License 2.0]: https://github.com/Qiskit/qiskit-ibm-runtime/blob/main/LICENSE.txt\n[tutorials]: https://learning.quantum.ibm.com/catalog/tutorials\n",
    "bugtrack_url": null,
    "license": "Apache 2.0",
    "summary": "IBM Quantum client for Qiskit Runtime.",
    "version": "0.33.2",
    "project_urls": {
        "Bug Tracker": "https://github.com/Qiskit/qiskit-ibm-runtime/issues",
        "Documentation": "https://docs.quantum.ibm.com/",
        "Homepage": "https://github.com/Qiskit/qiskit-ibm-runtime",
        "Source Code": "https://github.com/Qiskit/qiskit-ibm-runtime"
    },
    "split_keywords": [
        "qiskit",
        "sdk",
        "quantum",
        "api",
        "runtime",
        "ibm"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "3cdb15ba13249d37ab89a6bdaa19c7811c4899fd1c9bc2fe3b899f6025c656cc",
                "md5": "5a6d2364d6b1da06013bbf4a10d8d734",
                "sha256": "fe414429098f49c7caddca31203b801eca0f2b587913eb3583c5b284a6c2c271"
            },
            "downloads": -1,
            "filename": "qiskit_ibm_runtime-0.33.2-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "5a6d2364d6b1da06013bbf4a10d8d734",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8",
            "size": 2943948,
            "upload_time": "2024-11-11T20:38:38",
            "upload_time_iso_8601": "2024-11-11T20:38:38.123182Z",
            "url": "https://files.pythonhosted.org/packages/3c/db/15ba13249d37ab89a6bdaa19c7811c4899fd1c9bc2fe3b899f6025c656cc/qiskit_ibm_runtime-0.33.2-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "1b0ee48b198760d702a378dc43a9f581067153fee16bad041253978516847a75",
                "md5": "940f3569a920c3793123d525c875f316",
                "sha256": "f75bcfee97c4a8014a7999a353b5adc70dccf4b92eafc1cf81fa05a26ea5519b"
            },
            "downloads": -1,
            "filename": "qiskit_ibm_runtime-0.33.2.tar.gz",
            "has_sig": false,
            "md5_digest": "940f3569a920c3793123d525c875f316",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 2844076,
            "upload_time": "2024-11-11T20:38:40",
            "upload_time_iso_8601": "2024-11-11T20:38:40.614148Z",
            "url": "https://files.pythonhosted.org/packages/1b/0e/e48b198760d702a378dc43a9f581067153fee16bad041253978516847a75/qiskit_ibm_runtime-0.33.2.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-11-11 20:38:40",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "Qiskit",
    "github_project": "qiskit-ibm-runtime",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "requirements": [
        {
            "name": "requests",
            "specs": [
                [
                    "~=",
                    "2.27"
                ]
            ]
        },
        {
            "name": "requests_ntlm",
            "specs": [
                [
                    ">=",
                    "1.1.0"
                ]
            ]
        },
        {
            "name": "numpy",
            "specs": [
                [
                    ">=",
                    "1.13"
                ]
            ]
        },
        {
            "name": "urllib3",
            "specs": [
                [
                    ">=",
                    "1.21.1"
                ]
            ]
        },
        {
            "name": "python-dateutil",
            "specs": [
                [
                    ">=",
                    "2.8.0"
                ]
            ]
        },
        {
            "name": "websocket-client",
            "specs": [
                [
                    ">=",
                    "1.5.1"
                ]
            ]
        },
        {
            "name": "typing-extensions",
            "specs": [
                [
                    ">=",
                    "4.0.0"
                ]
            ]
        },
        {
            "name": "ibm-platform-services",
            "specs": [
                [
                    ">=",
                    "0.22.6"
                ]
            ]
        },
        {
            "name": "pydantic",
            "specs": [
                [
                    ">=",
                    "2.5.0"
                ]
            ]
        },
        {
            "name": "qiskit",
            "specs": [
                [
                    ">=",
                    "1.1.0"
                ]
            ]
        }
    ],
    "tox": true,
    "lcname": "qiskit-ibm-runtime"
}
        
Elapsed time: 0.73582s