Skip to content

Commit

Permalink
Merge pull request #14 from qiboteam/refactor_with_abstract_client
Browse files Browse the repository at this point in the history
Rename package and files to qibo-client
  • Loading branch information
scarrazza authored Jan 12, 2024
2 parents ffb3225 + d56442c commit 66dddad
Show file tree
Hide file tree
Showing 11 changed files with 69 additions and 60 deletions.
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ source activate ./env/bin/activate
The `TiiQ Provider` package can be installed through `pip`:

```bash
pip install git+ssh://git@github.com/qiboteam/qibo-tii-provider.git
pip install git+ssh://git@github.com/qiboteam/qibo-client.git
```

## Quickstart
Expand All @@ -37,14 +37,14 @@ registration process.

```python
import qibo
from qibo_tii_provider import TIIProvider
import qibo_client

# create the circuit you want to run
circuit = qibo.models.QFT(5)

# authenticate to server through the client instance
token = "your-tii-qrc-token"
client = TIIProvider(token)
client = qibo_client.TII(token)

# run the circuit
result = client.run_circuit(circuit, nshots=1000, dev="sim")
Expand Down
4 changes: 2 additions & 2 deletions examples/run_error_job.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import qibo

from qibo_tii_provider import TiiProvider
from qibo_client import TII

# create the circuit you want to run
circuit = qibo.models.QFT(11)
Expand All @@ -10,7 +10,7 @@
token = f.read()

# authenticate to server through the client instance
client = TIIProvider(token)
client = TII(token)

# run the circuit
print(f"{'*'*20}\nPost first circuit")
Expand Down
4 changes: 2 additions & 2 deletions examples/run_successful_job.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import qibo

from qibo_tii_provider import TIIProvider
from qibo_client import TII

# create the circuit you want to run
circuit = qibo.models.QFT(5)
Expand All @@ -10,7 +10,7 @@
token = f.read()

# authenticate to server through the client instance
client = TIIProvider(token)
client = TII(token)

# run the circuit
print(f"{'*'*20}\nPost first circuit")
Expand Down
12 changes: 6 additions & 6 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,21 @@ requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"

[tool.poetry]
name = "qibo_tii_provider"
name = "qibo-client"
version = "0.0.1"
description = "Qibo interface to TII quantum hardware."
description = "Qibo client interface."
authors = ["The Qibo team"]
license = "Apache License 2.0"
readme = "README.md"
homepage = "https://qibo.science/"
repository = "https://github.com/qiboteam/qibo-tii-provider/"
documentation = "https://qibo.science/docs/qibo/stable"
repository = "https://github.com/qiboteam/qibo-client/"
documentation = "https://qibo.science/qibo-client/stable"
keywords = []
classifiers = [
"Programming Language :: Python :: 3",
"Topic :: Scientific/Engineering :: Physics",
]
packages = [{ include = "qibo_tii_provider", from = "src" }]
packages = [{ include = "qibo_client", from = "src" }]

[tool.poetry.dependencies]
python = ">=3.9,<3.12"
Expand Down Expand Up @@ -49,7 +49,7 @@ output-format = "colorized"
testpaths = ['tests/']
filterwarnings = ['ignore::RuntimeWarning']
addopts = [
'--cov=src/qibo_tii_provider',
'--cov=src/qibo_client',
'--cov-report=xml',
'--cov-report=html',
]
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@

__version__ = im.version(__package__)

from qibo_tii_provider.tii_qrc_provider import TIIProvider
from .tii import TII
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,9 @@

from .config import JobPostServerError, MalformedResponseError

QRCCLUSTER_IP = os.environ.get("QRCCLUSTER_IP", "login.qrccluster.com")
QRCCLUSTER_PORT = os.environ.get("QRCCLUSTER_PORT", "8010")
RESULTS_BASE_FOLDER = os.environ.get("RESULTS_BASE_FOLDER", "/tmp/qibo_tii_provider")
SECONDS_BETWEEN_CHECKS = os.environ.get("SECONDS_BETWEEN_CHECKS", 2)

BASE_URL = f"http://{QRCCLUSTER_IP}:{QRCCLUSTER_PORT}/"

RESULTS_BASE_FOLDER = Path(RESULTS_BASE_FOLDER)
RESULTS_BASE_FOLDER.mkdir(exist_ok=True)

Expand Down Expand Up @@ -109,14 +105,17 @@ def check_response_has_keys(response: requests.models.Response, keys: List[str])
)


class TIIProvider:
class Client:
"""Class to manage the interaction with the QRC cluster."""

def __init__(self, token: str):
def __init__(self, url: str, token: str):
"""
:param url: the server address
:type url: str
:param token: the authentication token associated to the webapp user
:type: str
:type token: str
"""
self.url = url
self.token = token

self.pid = None
Expand All @@ -130,7 +129,7 @@ def check_client_server_qibo_versions(self):
Raise assertion error if the two versions are not the same.
"""
url = BASE_URL + "qibo_version/"
url = self.url + "qibo_version/"
response = requests.get(url, timeout=TIMEOUT)
response.raise_for_status()
check_response_has_keys(response, ["qibo_version"])
Expand All @@ -148,20 +147,6 @@ def run_circuit(
) -> Optional[np.ndarray]:
"""Run circuit on the cluster.
List of available devices:
- sim
- iqm5q
- spinq10q
- tii1q_b1
- qw25q_gold
- tiidc
- tii2q
- tii2q1
- tii2q2
- tii2q3
- tii2q4
:param circuit: the QASM representation of the circuit to run
:type circuit: Circuit
:param nshots:
Expand Down Expand Up @@ -193,7 +178,7 @@ def _post_circuit(
self, circuit: qibo.Circuit, nshots: int = 100, device: str = "sim"
):
# HTTP request
url = BASE_URL + "run_circuit/"
url = self.url + "run_circuit/"
payload = {
"token": self.token,
"circuit": circuit.raw,
Expand Down Expand Up @@ -223,7 +208,7 @@ def _get_result(self) -> Optional[np.ndarray]:
the job raised an error.
:rtype: Optional[np.ndarray]
"""
url = BASE_URL + f"get_result/{self.pid}/"
url = self.url + f"get_result/{self.pid}/"
response = wait_for_response_to_get_request(url)

# create the job results folder
Expand Down
19 changes: 19 additions & 0 deletions src/qibo_client/tii.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import os

from .qibo_client import Client

QRCCLUSTER_IP = os.environ.get("QRCCLUSTER_IP", "login.qrccluster.com")
QRCCLUSTER_PORT = os.environ.get("QRCCLUSTER_PORT", "8010")
BASE_URL = f"http://{QRCCLUSTER_IP}:{QRCCLUSTER_PORT}/"


def TII(token: str) -> Client:
"""Instantiate a TII Client object.
:param token: the authentication token associated to the webapp user
:type token: str
:return: the client instance connected to the TII server
:rtype: Client
"""
return Client(BASE_URL, token)
35 changes: 13 additions & 22 deletions tests/test_tii_qrc_provider.py → tests/test_qibo_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,27 +4,20 @@
from unittest.mock import Mock, patch

import pytest
import utils_test_tii_qrc_provider as utils
import utils_test_qibo_client as utils
from requests.exceptions import HTTPError

from qibo_tii_provider import tii_qrc_provider
from qibo_tii_provider.config import JobPostServerError, MalformedResponseError
from qibo_client import qibo_client
from qibo_client.config import JobPostServerError, MalformedResponseError

PKG = "qibo_tii_provider.tii_qrc_provider"
PKG = "qibo_client.qibo_client"
LOCAL_URL = "http://localhost:8000/"
FAKE_QIBO_VERSION = "0.0.1"
FAKE_PID = "123"
ARCHIVE_NAME = "file.tar.gz"
TIMEOUT = 1


@pytest.fixture(autouse=True)
def mock_qrccluster_ip():
"""Ensure that all the requests are made on localhost"""
with patch(f"{PKG}.BASE_URL", LOCAL_URL) as _fixture:
yield _fixture


@pytest.fixture(autouse=True)
def mock_qibo():
"""Ensure that all the requests are made on localhost"""
Expand Down Expand Up @@ -112,7 +105,7 @@ def test_check_response_has_keys():
json_data = {"key1": 0, "key2": 1}
status_code = 200
mock_response = utils.MockedResponse(status_code, json_data)
tii_qrc_provider.check_response_has_keys(mock_response, keys)
qibo_client.check_response_has_keys(mock_response, keys)


def test_check_response_has_missing_keys():
Expand All @@ -122,11 +115,11 @@ def test_check_response_has_missing_keys():
status_code = 200
mock_response = utils.MockedResponse(status_code, json_data)
with pytest.raises(MalformedResponseError):
tii_qrc_provider.check_response_has_keys(mock_response, keys)
qibo_client.check_response_has_keys(mock_response, keys)


def _get_tii_client():
return tii_qrc_provider.TIIProvider("valid_token")
return qibo_client.Client(LOCAL_URL, "valid_token")


def test_check_client_server_qibo_versions_with_version_match(mock_request: Mock):
Expand Down Expand Up @@ -202,7 +195,7 @@ def test_wait_for_response_to_get_request(mock_request: Mock):
mock_request.get.side_effect = [keep_waiting] * failed_attempts + [job_done]

with patch(f"{PKG}.SECONDS_BETWEEN_CHECKS", 1e-4):
tii_qrc_provider.wait_for_response_to_get_request(url)
qibo_client.wait_for_response_to_get_request(url)

assert mock_request.get.call_count == failed_attempts + 1

Expand All @@ -220,7 +213,7 @@ def test__write_stream_to_tmp_file_with_simple_text_stream(

assert not archive_path.is_file()

result_path = tii_qrc_provider._write_stream_to_tmp_file(stream)
result_path = qibo_client._write_stream_to_tmp_file(stream)

assert result_path == archive_path
assert result_path.is_file()
Expand All @@ -238,7 +231,7 @@ def test__write_stream_to_tmp_file(mock_tempfile: Mock, archive_path: Path):

assert not archive_path.is_file()

result_path = tii_qrc_provider._write_stream_to_tmp_file(stream)
result_path = qibo_client._write_stream_to_tmp_file(stream)

assert result_path == archive_path
assert result_path.is_file()
Expand All @@ -259,7 +252,7 @@ def test__extract_archive_to_folder_with_non_archive_input(tmp_path):
file_path.write_text("test content")

with pytest.raises(tarfile.ReadError):
tii_qrc_provider._extract_archive_to_folder(file_path, tmp_path)
qibo_client._extract_archive_to_folder(file_path, tmp_path)


@patch(
Expand All @@ -278,7 +271,7 @@ def test__get_result_handles_tarfile_readerror(mock_request, results_base_folder
def test__extract_archive_to_folder(archive_path, results_base_folder):
members, members_contents = utils.create_fake_archive(archive_path)

tii_qrc_provider._extract_archive_to_folder(archive_path, results_base_folder)
qibo_client._extract_archive_to_folder(archive_path, results_base_folder)

result_members = []
result_members_contents = []
Expand All @@ -297,9 +290,7 @@ def test__save_and_unpack_stream_response_to_folder(

assert not archive_path.is_file()

tii_qrc_provider._save_and_unpack_stream_response_to_folder(
stream, results_base_folder
)
qibo_client._save_and_unpack_stream_response_to_folder(stream, results_base_folder)

# the archive should have been removed
assert not archive_path.is_file()
Expand Down
14 changes: 14 additions & 0 deletions tests/test_tii.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
from unittest.mock import Mock, patch

from qibo_client import tii

PKG = "qibo_client.tii"
FAKE_URL = "http://tii.url.com:1234"
FAKE_TOKEN = "fakeToken"


@patch(f"{PKG}.BASE_URL", FAKE_URL)
@patch(f"{PKG}.Client.check_client_server_qibo_versions")
def test_TII(mock_method: Mock):
client = tii.TII(FAKE_TOKEN)
assert client.url == FAKE_URL
File renamed without changes.

0 comments on commit 66dddad

Please sign in to comment.