Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Harmonize remote and local options & bump to 0.5.0 #23

Merged
merged 3 commits into from
Nov 30, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ name = "qiskit_alice_bob_provider"
authors = [
{name = "Alice & Bob Software Team"},
]
version = "0.4.1"
version = "0.5.0"
description = "Provider for running Qiskit circuits on Alice & Bob QPUs and simulators"
readme = "README.md"
license = {text = "Apache 2.0"}
Expand Down
20 changes: 12 additions & 8 deletions qiskit_alice_bob_provider/remote/backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

from typing import Any, Dict

from pydantic.alias_generators import to_camel, to_snake
from qiskit import QuantumCircuit
from qiskit.providers import BackendV2, Options
from qiskit.transpiler import PassManager, Target
Expand All @@ -26,7 +27,6 @@
from .api.client import ApiClient
from .job import AliceBobRemoteJob
from .qir_to_qiskit import ab_target_to_qiskit_target
from .utils import camel_to_snake_case, snake_to_camel_case


class AliceBobRemoteBackend(BackendV2):
Expand Down Expand Up @@ -67,6 +67,14 @@ def get_translation_stage_plugin(self):
in translation_plugin.StatePreparationPlugin"""
return self._translation_plugin

def update_options(self, option_updates: Dict[str, Any]) -> Options:
options: Options = self.options
for key, value in option_updates.items():
if not hasattr(options, key):
raise ValueError(f'Backend does not support option "{key}"')
options.update_options(**{key: value})
return options

def run(self, run_input: QuantumCircuit, **kwargs) -> AliceBobRemoteJob:
"""Run the quantum circuit on the Alice & Bob backend by calling the
Alice & Bob API.
Expand All @@ -83,11 +91,7 @@ def run(self, run_input: QuantumCircuit, **kwargs) -> AliceBobRemoteJob:
Wait for the results by calling
:func:`AliceBobRemoteJob.result`.
"""
options: Options = self.options
for key, value in kwargs.items():
if not hasattr(options, key):
raise ValueError(f'Backend does not support option "{key}"')
options.update_options(**{key: value})
options = self.update_options(kwargs)
input_params = _ab_input_params_from_options(options)
job = jobs.create_job(self._api_client, self.name, input_params)
run_input = PassManager([EnsurePreparationPass()]).run(run_input)
Expand All @@ -111,7 +115,7 @@ def _options_from_ab_target(ab_target: Dict) -> Options:
"""Extract Qiskit options from an Alice & Bob target description"""
options = Options()
for camel_name, desc in ab_target['inputParams'].items():
name = camel_to_snake_case(camel_name)
name = to_snake(camel_name)
if name == 'nb_shots': # special case
name = 'shots'
options.update_options(**{name: desc['default']})
Expand All @@ -127,7 +131,7 @@ def _ab_input_params_from_options(options: Options) -> Dict:
"""Extract Qiskit options from an Alice & Bob target description"""
input_params: Dict[str, Any] = {}
for snake_name, value in options.__dict__.items():
name = snake_to_camel_case(snake_name)
name = to_camel(snake_name)
if name == 'shots': # special case
name = 'nbShots'
input_params[name] = value
Expand Down
8 changes: 8 additions & 0 deletions qiskit_alice_bob_provider/remote/provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,14 @@ def __init__(
for ab_target in list_targets(client):
self._backends.append(AliceBobRemoteBackend(client, ab_target))

def get_backend(self, name=None, **kwargs) -> AliceBobRemoteBackend:
backend = super().get_backend(name)
# We allow to set the options when getting the backend,
# to align with what we do in the local provider.
if kwargs:
backend.update_options(kwargs)
return backend

def backends(
self, name: Optional[str] = None, **kwargs
) -> List[BackendV2]:
Expand Down
28 changes: 0 additions & 28 deletions qiskit_alice_bob_provider/remote/utils.py

This file was deleted.

6 changes: 4 additions & 2 deletions tests/remote/test_against_real_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,9 @@ def test_happy_path(base_url: str, api_key: str) -> None:
api_key=api_key,
url=base_url,
)
backend = provider.get_backend('EMU:1Q:LESCANNE_2020')
job = execute(c, backend)
backend = provider.get_backend(
'EMU:1Q:LESCANNE_2020', average_nb_photons=6.0
)
job = execute(c, backend, shots=100)
MaxleDrut marked this conversation as resolved.
Show resolved Hide resolved
res = job.result()
res.get_counts()
36 changes: 35 additions & 1 deletion tests/remote/test_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,47 @@

from qiskit_alice_bob_provider.remote.api.client import AliceBobApiException
from qiskit_alice_bob_provider.remote.backend import (
AliceBobRemoteBackend,
_ab_input_params_from_options,
_qiskit_to_qir,
)
from qiskit_alice_bob_provider.remote.provider import AliceBobRemoteProvider


def test_options_validation(mocked_targets) -> None:
def test_get_backend(mocked_targets) -> None:
provider = AliceBobRemoteProvider(api_key='foo')
backend = provider.get_backend('EMU:1Q:LESCANNE_2020')
assert isinstance(backend, AliceBobRemoteBackend)
assert backend.options['average_nb_photons'] == 4.0 # Default value.


def test_get_backend_with_options(mocked_targets) -> None:
provider = AliceBobRemoteProvider(api_key='foo')
backend = provider.get_backend(
'EMU:1Q:LESCANNE_2020', average_nb_photons=6.0
)
assert isinstance(backend, AliceBobRemoteBackend)
assert backend.options['average_nb_photons'] == 6.0


def test_get_backend_options_validation(mocked_targets) -> None:
provider = AliceBobRemoteProvider(api_key='foo')
with pytest.raises(ValueError):
provider.get_backend('EMU:1Q:LESCANNE_2020', average_nb_photons=40)
with pytest.raises(ValueError):
provider.get_backend('EMU:1Q:LESCANNE_2020', average_nb_photons=-1)
with pytest.raises(ValueError):
provider.get_backend('EMU:1Q:LESCANNE_2020', shots=0)
with pytest.raises(ValueError):
provider.get_backend('EMU:1Q:LESCANNE_2020', shots=1e10)
with pytest.raises(ValueError):
provider.get_backend('EMU:1Q:LESCANNE_2020', bad_option=1)


def test_execute_options_validation(mocked_targets) -> None:
# We are permissive in our options sytem, allowing the user to both
# define options when creating the backend and executing.
# We therefore need to test both behaviors.
c = QuantumCircuit(1, 1)
provider = AliceBobRemoteProvider(api_key='foo')
backend = provider.get_backend('EMU:1Q:LESCANNE_2020')
Expand Down
14 changes: 0 additions & 14 deletions tests/remote/test_utils.py

This file was deleted.