Skip to content
This repository has been archived by the owner on Jul 24, 2024. It is now read-only.

Commit

Permalink
Merge branch 'main' into qiskit-1.0-removals
Browse files Browse the repository at this point in the history
  • Loading branch information
kt474 committed Feb 6, 2024
2 parents 92e420c + f537ad7 commit 79256f2
Show file tree
Hide file tree
Showing 18 changed files with 159 additions and 80 deletions.
4 changes: 2 additions & 2 deletions .pylintrc
Original file line number Diff line number Diff line change
Expand Up @@ -548,5 +548,5 @@ min-public-methods=2

# Exceptions that will emit a warning when being caught. Defaults to
# "BaseException, Exception".
overgeneral-exceptions=BaseException,
Exception
overgeneral-exceptions=builtins.BaseException,
builtins.Exception
6 changes: 3 additions & 3 deletions qiskit_ibm_provider/jupyter/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
:hide-output:
from qiskit_ibm_provider.test.ibm_provider_mock import mock_get_backend
mock_get_backend('FakeVigo')
mock_get_backend('Fake1Q')
.. jupyter-execute::
Expand Down Expand Up @@ -71,8 +71,8 @@
if "ipykernel" in sys.modules:

from IPython import get_ipython # pylint: disable=import-error
from qiskit.providers import BackendV2
from .dashboard.dashboard import IBMDashboardMagic
from qiskit.providers.fake_provider.fake_backend import FakeBackendV2 as FakeBackend
from ..ibm_backend import IBMBackend
from .backend_info import backend_widget

Expand All @@ -82,4 +82,4 @@
HTML_FORMATTER = _IP.display_formatter.formatters["text/html"]
# Make backend_widget the html repr for IBM Quantum backends
HTML_FORMATTER.for_type(IBMBackend, backend_widget)
HTML_FORMATTER.for_type(FakeBackend, backend_widget)
HTML_FORMATTER.for_type(BackendV2, backend_widget)
17 changes: 7 additions & 10 deletions qiskit_ibm_provider/jupyter/backend_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,10 @@
"""Interactive backend widget."""

import threading
from typing import Union

import ipyvuetify as vue
from IPython.display import display # pylint: disable=import-error
from qiskit.providers.fake_provider.fake_backend import FakeBackendV2 as FakeBackend

from qiskit.providers import BackendV2
from qiskit_ibm_provider.ibm_backend import IBMBackend
from .config_widget import config_tab
from .gates_widget import gates_tab
Expand All @@ -29,9 +27,7 @@
from ..utils.hgp import to_instance_format


def _async_job_loader(
tab: vue.TabItem, backend: Union[IBMBackend, FakeBackend]
) -> None:
def _async_job_loader(tab: vue.TabItem, backend: BackendV2) -> None:
"""Asynchronous job loader.
Args:
Expand All @@ -41,18 +37,19 @@ def _async_job_loader(
tab.children = [jobs_tab(backend)]


def backend_widget(backend: Union[IBMBackend, FakeBackend]) -> None:
def backend_widget(backend: BackendV2) -> None:
"""Display backend information as a widget.
Args:
backend: Display information about this backend.
"""
vue.theme.dark = False
if isinstance(backend, FakeBackend):
if isinstance(backend, IBMBackend):
instance = backend._api_client._params.instance
else:
# fake backend
cred = backend._credentials
instance = to_instance_format(cred.hub, cred.group, cred.project)
else:
instance = backend._api_client._params.instance
last_tab = vue.TabItem(children=[])
card = vue.Card(
height=600,
Expand Down
8 changes: 2 additions & 6 deletions qiskit_ibm_provider/jupyter/config_widget.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,12 @@

"""Widget for the backend configuration tab."""

from typing import Union

import ipywidgets as wid
from qiskit.providers.fake_provider.fake_backend import FakeBackendV2 as FakeBackend

from qiskit_ibm_provider.ibm_backend import IBMBackend
from qiskit.providers import BackendV2
from qiskit_ibm_provider.visualization.interactive import iplot_gate_map


def config_tab(backend: Union[IBMBackend, FakeBackend]) -> wid.GridBox:
def config_tab(backend: BackendV2) -> wid.GridBox:
"""The backend configuration widget.
Args:
Expand Down
7 changes: 2 additions & 5 deletions qiskit_ibm_provider/jupyter/gates_widget.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,12 @@
"""Widget for backend gates tab."""

import math
from typing import Union

import ipywidgets as wid
from qiskit.providers.fake_provider.fake_backend import FakeBackendV2 as FakeBackend
from qiskit.providers import BackendV2

from qiskit_ibm_provider.ibm_backend import IBMBackend


def gates_tab(backend: Union[IBMBackend, FakeBackend]) -> wid.GridBox:
def gates_tab(backend: BackendV2) -> wid.GridBox:
"""Construct the multiple qubit gate error widget.
Args:
Expand Down
12 changes: 4 additions & 8 deletions qiskit_ibm_provider/jupyter/jobs_widget.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,11 @@
"""Interactive Jobs widget."""

import datetime
from typing import Any, Union
from typing import Any

import ipywidgets as wid
import plotly.graph_objects as go
from qiskit.providers.fake_provider.fake_backend import FakeBackendV2 as FakeBackend

from ..ibm_backend import IBMBackend
from qiskit.providers import BackendV2
from ..visualization.interactive.plotly_wrapper import PlotlyWidget

MONTH_NAMES = {
Expand Down Expand Up @@ -104,9 +102,7 @@ def _job_table_builder(sel_dict: dict) -> str:
return table_html


def _job_summary(
backend: Union[IBMBackend, FakeBackend], **kwargs: Any
) -> PlotlyWidget:
def _job_summary(backend: BackendV2, **kwargs: Any) -> PlotlyWidget:
"""Interactive jobs summary for a backend.
Args:
Expand Down Expand Up @@ -280,7 +276,7 @@ def callback(trace, selection, _): # pylint: disable=unused-argument
return sun_wid


def jobs_tab(backend: Union[IBMBackend, FakeBackend], **kwargs: Any) -> wid.HBox:
def jobs_tab(backend: BackendV2, **kwargs: Any) -> wid.HBox:
"""Construct a widget containing job information for an input backend.
Args:
Expand Down
8 changes: 2 additions & 6 deletions qiskit_ibm_provider/jupyter/qubits_widget.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,11 @@

"""Widget for qubit properties tab."""

from typing import Union

import ipywidgets as wid
from qiskit.providers.fake_provider.fake_backend import FakeBackendV2 as FakeBackend

from qiskit_ibm_provider.ibm_backend import IBMBackend
from qiskit.providers import BackendV2


def qubits_tab(backend: Union[IBMBackend, FakeBackend]) -> wid.VBox:
def qubits_tab(backend: BackendV2) -> wid.VBox:
"""The qubit properties widget.
Args:
Expand Down
45 changes: 45 additions & 0 deletions qiskit_ibm_provider/test/ibm_provider_mock.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021, 2024.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.

"""Mock for qiskit_ibm_provider.IBMProvider."""

from unittest.mock import MagicMock

from qiskit.providers import fake_provider as backend_mocks

import qiskit_ibm_provider


def mock_get_backend(backend):
"""Replace qiskit_ibm_provider.IBMProvider with a mock that returns a single backend.
Note this will set the value of qiskit_ibm_provider.IBMProvider to a MagicMock object. It is
intended to be run as part of docstrings with jupyter-example in a hidden
cell so that later examples which rely on ibm quantum devices so that the docs can
be built without requiring configured credentials. If used outside of this
context be aware that you will have to manually restore qiskit_ibm_provider.IBMProvider the
value to qiskit_ibm_provider.IBMProvider after you finish using your mock.
Args:
backend (str): The class name as a string for the fake device to
return. For example, Fake1Q.
Raises:
NameError: If the specified value of backend
"""
mock_ibm_provider = MagicMock()
if not hasattr(backend_mocks, backend):
raise NameError(
"The specified backend name is not a valid backend from "
"qiskit.providers.fake_provider"
)
fake_backend = getattr(backend_mocks, backend)()
mock_ibm_provider.get_backend.return_value = fake_backend
mock_ibm_provider.return_value = mock_ibm_provider
qiskit_ibm_provider.IBMProvider = mock_ibm_provider
14 changes: 12 additions & 2 deletions qiskit_ibm_provider/transpiler/passes/scheduling/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,13 @@
Below we demonstrate how to schedule and pad a teleportation circuit with delays
for a dynamic circuit backend's execution model:
.. jupyter-execute::
:hide-code:
:hide-output:
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
.. jupyter-execute::
from qiskit.circuit import ClassicalRegister, QuantumCircuit, QuantumRegister
Expand All @@ -41,10 +48,13 @@
from qiskit_ibm_provider.transpiler.passes.scheduling import DynamicCircuitInstructionDurations
from qiskit_ibm_provider.transpiler.passes.scheduling import ALAPScheduleAnalysis
from qiskit_ibm_provider.transpiler.passes.scheduling import PadDelay
from qiskit.providers.fake_provider import FakeJakarta
try:
from qiskit.providers.fake_provider import Fake7QPulseV1
except ImportError:
from qiskit.providers.fake_provider import FakeJakarta as Fake7QPulseV1
backend = FakeJakarta()
backend = Fake7QPulseV1()
# Temporary workaround for mock backends. For real backends this is not required.
backend.configuration().basis_gates.append("if_else")
Expand Down
22 changes: 16 additions & 6 deletions qiskit_ibm_provider/utils/json.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,18 +55,17 @@
)
from qiskit.result import Result
from qiskit.version import __version__ as _terra_version_string
from qiskit.qpy import load
from qiskit.utils import optionals

from ..qpy import (
_write_parameter,
from qiskit.qpy import (
_write_parameter_expression,
_read_parameter_expression,
_read_parameter_expression_v3,
_read_parameter,
load,
dump,
)

from qiskit.qpy.binary_io.value import _write_parameter, _read_parameter

_TERRA_VERSION = tuple(
int(x)
Expand Down Expand Up @@ -224,10 +223,15 @@ def default(self, obj: Any) -> Any: # pylint: disable=arguments-differ
if hasattr(obj, "to_json"):
return {"__type__": "to_json", "__value__": obj.to_json()}
if isinstance(obj, QuantumCircuit):
kwargs = {"use_symengine": optionals.HAS_SYMENGINE}
if _TERRA_VERSION[0] >= 1:
# NOTE: This can be updated only after the server side has
# updated to a newer qiskit version.
kwargs["version"] = 10
value = _serialize_and_encode(
data=obj,
serializer=lambda buff, data: dump(
data, buff, RuntimeEncoder, use_symengine=optionals.HAS_SYMENGINE
data, buff, RuntimeEncoder, **kwargs
), # type: ignore[no-untyped-call]
)
return {"__type__": "QuantumCircuit", "__value__": value}
Expand All @@ -243,17 +247,23 @@ def default(self, obj: Any) -> Any: # pylint: disable=arguments-differ
data=obj,
serializer=_write_parameter_expression,
compress=False,
use_symengine=optionals.HAS_SYMENGINE,
)
return {"__type__": "ParameterExpression", "__value__": value}
if isinstance(obj, Instruction):
kwargs = {"use_symengine": optionals.HAS_SYMENGINE}
if _TERRA_VERSION[0] >= 1:
# NOTE: This can be updated only after the server side has
# updated to a newer qiskit version.
kwargs["version"] = 10
# Append instruction to empty circuit
quantum_register = QuantumRegister(obj.num_qubits)
quantum_circuit = QuantumCircuit(quantum_register)
quantum_circuit.append(obj, quantum_register)
value = _serialize_and_encode(
data=quantum_circuit,
serializer=lambda buff, data: dump(
data, buff, use_symengine=optionals.HAS_SYMENGINE
data, buff, **kwargs
), # type: ignore[no-untyped-call]
)
return {"__type__": "Instruction", "__value__": value}
Expand Down
9 changes: 7 additions & 2 deletions qiskit_ibm_provider/visualization/interactive/error_map.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,15 +60,20 @@ def iplot_error_map(
:hide-output:
from qiskit_ibm_provider.test.ibm_provider_mock import mock_get_backend
mock_get_backend('FakeVigo')
# Generate a mock provider for the sake of this example.
# This line will allow the mocked ``IBMProvider`` to return
# a fake backend in the following cell.
mock_get_backend('FakeOpenPulse2Q')
.. jupyter-execute::
from qiskit_ibm_provider import IBMProvider
from qiskit_ibm_provider.visualization import iplot_error_map
provider = IBMProvider(group='open', project='main')
backend = provider.get_backend('ibmq_vigo')
# Note that this is a mock provider, replace ``FakeOpenPulse2Q``
# with any of the currently available IBM devices.
backend = provider.get_backend('FakeOpenPulse2Q')
iplot_error_map(backend, as_widget=True)
"""
Expand Down
11 changes: 8 additions & 3 deletions qiskit_ibm_provider/visualization/interactive/gate_map.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,15 +64,20 @@ def iplot_gate_map(
:hide-output:
from qiskit_ibm_provider.test.ibm_provider_mock import mock_get_backend
mock_get_backend('FakeVigo')
# Generate a mock provider for the sake of this example.
# This line will allow the mocked ``IBMProvider`` to return
# a fake backend in the following cell.
mock_get_backend('FakeOpenPulse2Q')
.. jupyter-execute::
from qiskit_ibm_provider import IBMProvider
from qiskit_ibm_provider.visualization import iplot_gate_map
provider = IBMProvider(group='open', project='main')
backend = provider.get_backend('ibmq_vigo')
provider = IBMProvider(group='open', project='main')
# Note that this is a mock provider, replace ``FakeOpenPulse2Q``
# with any of the currently available IBM devices.
backend = provider.get_backend('FakeOpenPulse2Q')
iplot_gate_map(backend, as_widget=True)
"""
Expand Down
9 changes: 5 additions & 4 deletions test/fake_account_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,10 @@
from random import randrange
from typing import Dict, Any

from qiskit.providers.fake_provider.backends.poughkeepsie.fake_poughkeepsie import (
FakePoughkeepsie,
)
try:
from qiskit.providers.fake_provider import Fake20QV1
except ImportError:
from qiskit.providers.fake_provider import FakePoughkeepsie as Fake20QV1

from qiskit_ibm_provider.api.exceptions import (
RequestsApiError,
Expand Down Expand Up @@ -452,7 +453,7 @@ def job_final_status(self, job_id, *_args, **_kwargs):

def job_properties(self, *_args, **_kwargs):
"""Return the backend properties of a job."""
props = FakePoughkeepsie().properties().to_dict()
props = Fake20QV1().properties().to_dict()
if self._props_count > 0:
self._props_count -= 1
new_dt = datetime.now() + timedelta(hours=randrange(300))
Expand Down
Loading

0 comments on commit 79256f2

Please sign in to comment.