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

clean up qubo interface and fix tests #918

Merged
merged 12 commits into from
Mar 7, 2024
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 cirq-superstaq/cirq_superstaq/compiler_output_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,7 @@ def test_read_json_ibmq_warnings() -> None:
assert out.circuits == [circuit]
assert out.pulse_sequences is None

with pytest.warns(
with mock.patch("qiskit.__version__", "2.0.0"), pytest.warns(
UserWarning,
match="Your compiled pulse sequences could not be deserialized. Please let us know",
):
Expand Down
7 changes: 2 additions & 5 deletions cirq-superstaq/cirq_superstaq/daily_integration_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -325,16 +325,13 @@ def test_submit_to_hilbert_qubit_sorting(service: css.Service) -> None:


def test_submit_qubo(service: css.Service) -> None:
test_qubo: dict[tuple[()] | tuple[str | int] | tuple[str | int, str | int], int | float] = {
test_qubo = {
(0,): -1,
(1,): -1,
(2,): -1,
(0, 1): 2,
(1, 2): 2,
}
serialized_result = service.submit_qubo(
test_qubo, target="ss_unconstrained_simulator", repetitions=10
)
result = gss.qubo.read_json_qubo_result(serialized_result)
result = service.submit_qubo(test_qubo, target="ss_unconstrained_simulator", repetitions=10)
assert len(result) == 10
assert {0: 1, 1: 0, 2: 1} in result
3 changes: 1 addition & 2 deletions docs/source/apps/max_sharpe_ratio_optimization.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -1032,8 +1032,7 @@
"source": [
"from qubovert.sim import anneal_qubo\n",
"\n",
"res = client.submit_qubo(obj_QUBO, target=\"ss_unconstrained_simulator\")\n",
"res = gss.qubo.read_json_qubo_result(res)"
"res = client.submit_qubo(obj_QUBO, target=\"ss_unconstrained_simulator\")"
]
},
{
Expand Down
11 changes: 1 addition & 10 deletions general-superstaq/general_superstaq/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,7 @@
)
from general_superstaq.typing import Target

from . import (
qubo,
serialization,
service,
superstaq_client,
superstaq_exceptions,
typing,
validation,
)
from . import serialization, service, superstaq_client, superstaq_exceptions, typing, validation

__all__ = [
"__version__",
Expand All @@ -28,7 +20,6 @@
"SuperstaqUnsuccessfulJobException",
"SuperstaqServerException",
"SuperstaqWarning",
"qubo",
"serialization",
"service",
"superstaq_client",
Expand Down
15 changes: 0 additions & 15 deletions general-superstaq/general_superstaq/qubo.py

This file was deleted.

10 changes: 0 additions & 10 deletions general-superstaq/general_superstaq/qubo_test.py

This file was deleted.

13 changes: 8 additions & 5 deletions general-superstaq/general_superstaq/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@

import numbers
import os
from collections.abc import Sequence
from typing import Any
from collections.abc import Mapping, Sequence
from typing import Any, TypeVar

import general_superstaq as gss

TQuboKey = TypeVar("TQuboKey")


class Service:
"""This class contains all the services that are used to operate Superstaq."""
Expand Down Expand Up @@ -159,12 +161,12 @@ def get_targets(

def submit_qubo(
self,
qubo: dict[tuple[()] | tuple[str | int] | tuple[str | int, str | int], int | float],
qubo: Mapping[tuple[TQuboKey, ...], float],
target: str = "ss_unconstrained_simulator",
repetitions: int = 10,
method: str | None = None,
max_solutions: int = 1000,
) -> dict[str, str]:
) -> list[dict[TQuboKey, int]]:
"""Solves a submitted QUBO problem via annealing.

This method returns any number of specified dictionaries that seek the minimum of
Expand All @@ -186,7 +188,8 @@ def submit_qubo(
Returns:
A dictionary containing the output solutions.
"""
return self._client.submit_qubo(qubo, target, repetitions, method, max_solutions)
result_dict = self._client.submit_qubo(qubo, target, repetitions, method, max_solutions)
return gss.serialization.deserialize(result_dict["solution"])

def aqt_upload_configs(self, pulses: Any, variables: Any) -> str:
"""Uploads configs for AQT.
Expand Down
29 changes: 6 additions & 23 deletions general-superstaq/general_superstaq/service_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,22 +77,12 @@ def test_update_user_role(

@mock.patch(
"general_superstaq.superstaq_client._SuperstaqClient.post_request",
return_value={
"qubo": [
{"keys": ["0"], "value": 1.0},
{"keys": ["1"], "value": 1.0},
{"keys": ["0", "1"], "value": -2.0},
],
"target": "ss_unconstrained_simulator",
"shots": 10,
"method": "dry-run",
"max_solutions": 13,
},
return_value={"solution": gss.serialization.serialize([{0: 1, 1: 1}] * 10)},
)
def test_submit_qubo(
mock_post_request: mock.MagicMock,
) -> None:
example_qubo: dict[tuple[()] | tuple[str | int] | tuple[str | int, str | int], int | float] = {
example_qubo = {
(0,): 1.0,
(1,): 1.0,
(0, 1): -2.0,
Expand All @@ -101,17 +91,10 @@ def test_submit_qubo(
repetitions = 10

service = gss.service.Service(remote_host="http://example.com", api_key="key")
assert service.submit_qubo(example_qubo, target, repetitions=repetitions, method="dry-run") == {
"qubo": [
{"keys": ["0"], "value": 1.0},
{"keys": ["1"], "value": 1.0},
{"keys": ["0", "1"], "value": -2.0},
],
"target": "ss_unconstrained_simulator",
"shots": 10,
"method": "dry-run",
"max_solutions": 13,
}
assert (
service.submit_qubo(example_qubo, target, repetitions=repetitions, method="dry-run")
== [{0: 1, 1: 1}] * 10
)


@mock.patch(
Expand Down
14 changes: 6 additions & 8 deletions general-superstaq/general_superstaq/superstaq_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,13 @@
import urllib
import warnings
from collections.abc import Callable, Mapping, Sequence
from typing import Any
from typing import Any, TypeVar

import requests

import general_superstaq as gss
from general_superstaq.testing import TARGET_LIST

TQuboKey = TypeVar("TQuboKey")


class _SuperstaqClient:
Expand Down Expand Up @@ -335,9 +336,9 @@ def compile(self, json_dict: dict[str, str]) -> dict[str, str]:

def submit_qubo(
self,
qubo: dict[tuple[()] | tuple[str | int] | tuple[str | int, str | int], int | float],
qubo: Mapping[tuple[TQuboKey, ...], float],
bharat-thotakura marked this conversation as resolved.
Show resolved Hide resolved
target: str,
repetitions: int = 1000,
repetitions: int,
method: str | None = None,
max_solutions: int | None = 1000,
) -> dict[str, str]:
Expand All @@ -361,10 +362,7 @@ def submit_qubo(
A dictionary from the POST request.
"""
gss.validation.validate_target(target)
if not (target in TARGET_LIST and TARGET_LIST[target]["supports_submit_qubo"]):
raise gss.SuperstaqException(
f"The provided target, {target}, does not support QUBO submission."
)
gss.validation.validate_qubo(qubo)
gss.validation.validate_integer_param(repetitions)
gss.validation.validate_integer_param(max_solutions)

Expand Down
11 changes: 1 addition & 10 deletions general-superstaq/general_superstaq/superstaq_client_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -646,7 +646,7 @@ def test_superstaq_client_submit_qubo(mock_post: mock.MagicMock) -> None:
api_key="to_my_heart",
)

example_qubo: dict[tuple[()] | tuple[str | int] | tuple[str | int, str | int], int | float] = {
example_qubo = {
("a",): 2.0,
("a", "b"): 1.0,
("b", 0): -5,
Expand All @@ -671,15 +671,6 @@ def test_superstaq_client_submit_qubo(mock_post: mock.MagicMock) -> None:
verify=False,
)

with pytest.raises(gss.SuperstaqException, match="not support QUBO submission."):
client.submit_qubo(
example_qubo,
target="cq_hilbert_qpu",
repetitions=repetitions,
method="dry-run",
max_solutions=1,
)


@mock.patch("requests.post")
def test_superstaq_client_supercheq(mock_post: mock.MagicMock) -> None:
Expand Down
26 changes: 25 additions & 1 deletion general-superstaq/general_superstaq/validation.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
from __future__ import annotations

import numbers
import re
from collections.abc import Sequence
from collections.abc import Mapping, Sequence


def validate_integer_param(integer_param: object, min_val: int = 1) -> None:
Expand Down Expand Up @@ -136,3 +137,26 @@ def validate_noise_type(noise: dict[str, object], n_qubits: int) -> None:
f"{params} must be of the form (p_x, p_y, p_z) such that p_x + p_y + p_z <= 1 "
f'for "asymmetric_depolarize".'
)


def validate_qubo(qubo: object) -> None:
"""Validates that the input can be converted into a valid QUBO.

Args:
qubo: The input value to validate.

Raises:
ValueError: If the provided object cannot be converted into a valid QUBO.
"""
if not isinstance(qubo, Mapping):
raise ValueError("QUBOs must be provided as dict-like objects.")

for key, val in qubo.items():
if not isinstance(key, Sequence) or isinstance(key, str):
raise ValueError(f"{key!r} is not a valid key for a QUBO.")

if len(key) > 2:
raise ValueError(f"QUBOs must be quadratic, but key {key!r} has length {len(key)}.")

if not isinstance(val, numbers.Real):
raise ValueError("QUBO values must be real numbers.")
21 changes: 21 additions & 0 deletions general-superstaq/general_superstaq/validation_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,3 +74,24 @@ def test_validate_noise_type() -> None:
gss.validation.validate_noise_type(
({"type": "asymmetric_depolarize", "params": (0.5, 0.5, 0.5)}), 1
)


def test_validate_qubo() -> None:
with pytest.raises(ValueError, match="QUBOs must be"):
gss.validation.validate_qubo("not-a-dict")

with pytest.raises(ValueError, match="not a valid key"):
gss.validation.validate_qubo({"abc": 123})

with pytest.raises(ValueError, match="must be real numbers"):
gss.validation.validate_qubo({(1, 2): 12 + 3j})

with pytest.raises(ValueError, match="must be real numbers"):
gss.validation.validate_qubo({(1, 2): "abc"})

with pytest.raises(ValueError, match="must be quadratic"):
gss.validation.validate_qubo({(1, 2, 3): 123})

gss.validation.validate_qubo({(1,): 1.2, (2,): 2.3, (1, 2): -3.4})
gss.validation.validate_qubo({("a",): 1, ("b",): 2, ("a", "b"): -3})
gss.validation.validate_qubo({(): 123})
9 changes: 3 additions & 6 deletions qiskit-superstaq/qiskit_superstaq/daily_integration_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ def test_backends(provider: qss.SuperstaqProvider) -> None:
retired=False,
)
assert ibmq_backend_info in result
assert provider.get_backend("ibmq_qasm_simulator").name == "ibmq_qasm_simulator"
assert provider.get_backend("ibmq_qasm_simulator").name() == "ibmq_qasm_simulator"


def test_ibmq_compile(provider: qss.SuperstaqProvider) -> None:
Expand Down Expand Up @@ -281,16 +281,13 @@ def test_submit_to_hilbert_qubit_sorting(provider: qss.SuperstaqProvider) -> Non


def test_submit_qubo(provider: qss.SuperstaqProvider) -> None:
test_qubo: dict[tuple[()] | tuple[str | int] | tuple[str | int, str | int], int | float] = {
test_qubo = {
(0,): -1,
(1,): -1,
(2,): -1,
(0, 1): 2,
(1, 2): 2,
}
serialized_result = provider.submit_qubo(
test_qubo, target="ss_unconstrained_simulator", repetitions=10
)
result = gss.qubo.read_json_qubo_result(serialized_result)
result = provider.submit_qubo(test_qubo, target="ss_unconstrained_simulator", repetitions=10)
assert len(result) == 10
assert {0: 1, 1: 0, 2: 1} in result