Skip to content

Commit

Permalink
Melf/add ruff 2024 (#120)
Browse files Browse the repository at this point in the history
* add ruff config file

* ruff fixes I

* ruff fix II

* add ruff precommit

* ruff changes IV

* ruff changes 5

* fix mypy

* add print
  • Loading branch information
cqc-melf authored Oct 23, 2024
1 parent 846fb84 commit 0358cc0
Show file tree
Hide file tree
Showing 31 changed files with 269 additions and 243 deletions.
4 changes: 4 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,7 @@ repos:
- id: check-executables-have-shebangs
- id: check-merge-conflict
- id: detect-private-key
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.6.9
hooks:
- id: ruff
4 changes: 2 additions & 2 deletions docs/build-docs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
#!/usr/bin/env python
import argparse
from datetime import date
import shutil
import subprocess
import sys
from datetime import date
from importlib import import_module
from pathlib import Path
from typing import Any
Expand Down Expand Up @@ -90,7 +90,7 @@ if __name__ == "__main__":
parser.add_argument("-d", "--dest", help="copy artifacts into destination folder")
args = parser.parse_args()

print("Building docs for modules:", MODULE)
print("Building docs for modules:", MODULE) # noqa: T201
build_module_docs()

if args.dest is not None:
Expand Down
12 changes: 4 additions & 8 deletions docs/conf.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,9 @@
import re
from typing import Any
from typing import Dict
from typing import Optional
from typing import Tuple
from typing import Any, Optional
from urllib.parse import urljoin

from docutils import nodes
from docutils.nodes import Element
from docutils.nodes import TextElement
from docutils.nodes import Element, TextElement
from sphinx.application import Sphinx
from sphinx.environment import BuildEnvironment

Expand Down Expand Up @@ -118,10 +114,10 @@ def correct_signature(
what: str,
name: str,
obj: Any,
options: Dict,
options: dict,
signature: str,
return_annotation: str,
) -> Tuple[str, str]:
) -> tuple[str, str]:
new_signature = signature
new_return_annotation = return_annotation
for k, v in app.config.custom_internal_mapping.items():
Expand Down
2 changes: 1 addition & 1 deletion noxfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
import os
import shlex
import sys
from collections.abc import Iterable
from pathlib import Path
from textwrap import dedent
from typing import Iterable

import nox

Expand Down
5 changes: 3 additions & 2 deletions pytket/extensions/aqt/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,11 @@
# See the License for the specific language governing permissions and
# limitations under the License.
"""Backends for processing pytket circuits with AQT devices."""

from .backends import AQTBackend
from .backends.config import (
AQTConfig,
set_aqt_config,
AQTAccessToken,
AQTConfig,
print_available_devices,
set_aqt_config,
)
4 changes: 2 additions & 2 deletions pytket/extensions/aqt/backends/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,6 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Backends for processing pytket circuits with AQT devices
"""
"""Backends for processing pytket circuits with AQT devices"""

from .aqt import AQTBackend
82 changes: 36 additions & 46 deletions pytket/extensions/aqt/backends/aqt.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,66 +14,56 @@
import json
import logging
import time
from typing import Any
from typing import cast
from typing import Dict
from typing import List
from typing import Optional
from typing import Sequence
from typing import Tuple
from typing import Union
from typing_extensions import assert_never
from collections.abc import Sequence
from typing import Any, Optional, Union, cast

import numpy
from qiskit_aqt_provider import api_models, api_models_generated
from qiskit_aqt_provider.aqt_provider import OFFLINE_SIMULATORS
from typing_extensions import assert_never

from pytket.backends import Backend
from pytket.backends import CircuitStatus
from pytket.backends import ResultHandle
from pytket.backends import StatusEnum
from pytket.backends import Backend, CircuitStatus, ResultHandle, StatusEnum
from pytket.backends.backend import KwargTypes
from pytket.backends.backend_exceptions import CircuitNotRunError, CircuitNotValidError
from pytket.backends.backendinfo import BackendInfo
from pytket.backends.backendinfo import fully_connected_backendinfo
from pytket.backends.backendinfo import BackendInfo, fully_connected_backendinfo
from pytket.backends.backendresult import BackendResult
from pytket.backends.resulthandle import _ResultIdTuple
from pytket.circuit import Circuit
from pytket.circuit import OpType
from pytket.circuit import Qubit
from pytket.passes import auto_rebase_pass
from pytket.passes import BasePass
from pytket.passes import DecomposeBoxes
from pytket.passes import EulerAngleReduction
from pytket.passes import FlattenRegisters
from pytket.passes import FullPeepholeOptimise
from pytket.passes import RenameQubitsPass
from pytket.passes import SequencePass
from pytket.passes import SimplifyInitial
from pytket.passes import SynthesiseTket
from pytket.predicates import GateSetPredicate
from pytket.predicates import MaxNQubitsPredicate
from pytket.predicates import NoClassicalControlPredicate
from pytket.predicates import NoFastFeedforwardPredicate
from pytket.predicates import NoMidMeasurePredicate
from pytket.predicates import NoSymbolsPredicate
from pytket.predicates import Predicate
from pytket.circuit import Circuit, OpType, Qubit
from pytket.passes import (
BasePass,
DecomposeBoxes,
EulerAngleReduction,
FlattenRegisters,
FullPeepholeOptimise,
RenameQubitsPass,
SequencePass,
SimplifyInitial,
SynthesiseTket,
auto_rebase_pass,
)
from pytket.predicates import (
GateSetPredicate,
MaxNQubitsPredicate,
NoClassicalControlPredicate,
NoFastFeedforwardPredicate,
NoMidMeasurePredicate,
NoSymbolsPredicate,
Predicate,
)
from pytket.utils import prepare_circuit
from pytket.utils.outcomearray import OutcomeArray

from ..extension_version import __extension_version__
from .aqt_api import (
AqtOfflineApi,
AqtRemoteApi,
AqtMockApi,
AQT_MOCK_DEVICES,
AqtApi,
AqtMockApi,
AqtOfflineApi,
AqtRemoteApi,
unwrap,
)
from .aqt_job_data import PytketAqtJob, PytketAqtJobCircuitData

from ..extension_version import __extension_version__


logger = logging.getLogger(__name__)

AQT_PORTAL_URL = "https://arnica.aqt.eu/api/v1"
Expand All @@ -92,7 +82,7 @@
OpType.Barrier,
}

AQTResult = Tuple[int, List[int]] # (n_qubits, list of readouts)
AQTResult = tuple[int, list[int]] # (n_qubits, list of readouts)

AQT_OFFLINE_SIMULATORS = {sim.id: sim for sim in OFFLINE_SIMULATORS}

Expand Down Expand Up @@ -218,7 +208,7 @@ def print_device_table(cls, access_token: Optional[str] = None) -> None:
@classmethod
def available_devices(
cls, access_token: Optional[str] = None, **kwargs: Any
) -> List[BackendInfo]:
) -> list[BackendInfo]:
"""
See :py:meth:`pytket.backends.Backend.available_devices`.
Supported kwargs: none.
Expand Down Expand Up @@ -246,7 +236,7 @@ def available_devices(
]

@property
def required_predicates(self) -> List[Predicate]:
def required_predicates(self) -> list[Predicate]:
preds = [
NoClassicalControlPredicate(),
NoFastFeedforwardPredicate(),
Expand Down Expand Up @@ -358,7 +348,7 @@ def process_circuits(
n_shots: Union[None, int, Sequence[Optional[int]]] = None,
valid_check: bool = True,
**kwargs: KwargTypes,
) -> List[ResultHandle]:
) -> list[ResultHandle]:
"""
See :py:meth:`pytket.backends.Backend.process_circuits`.
Expand Down Expand Up @@ -418,7 +408,7 @@ def process_circuits(
return handles

def _update_cache_result(
self, handle: ResultHandle, result_dict: Dict[str, BackendResult]
self, handle: ResultHandle, result_dict: dict[str, BackendResult]
) -> None:
if handle in self._cache:
self._cache[handle].update(result_dict)
Expand Down
24 changes: 14 additions & 10 deletions pytket/extensions/aqt/backends/aqt_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,28 +12,32 @@
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import annotations

import json
import uuid
from dataclasses import dataclass
from typing import Protocol, Final, TypeVar
from typing import TYPE_CHECKING, Final, Protocol, TypeVar

import httpx
from qiskit_aqt_provider import AQTProvider, api_models
from qiskit_aqt_provider.api_models_generated import (
JobResponseRRFinished,
JobUser,
RRFinished,
ResultItem,
JobResponseRRFinished,
RRFinished,
)
from qiskit_aqt_provider.aqt_job import AQTJob
from qiskit_aqt_provider.aqt_options import AQTOptions
from qiskit_aqt_provider.aqt_provider import OfflineSimulator
from qiskit_aqt_provider.aqt_resource import AQTResource, OfflineSimulatorResource
from qiskit_aqt_provider.circuit_to_aqt import aqt_to_qiskit_circuit

from .aqt_job_data import PytketAqtJob
from .config import AQTAccessToken

if TYPE_CHECKING:
import httpx
from qiskit_aqt_provider.aqt_provider import OfflineSimulator

from .aqt_job_data import PytketAqtJob


@dataclass
class AqtDevice:
Expand All @@ -57,7 +61,7 @@ def from_aqt_resource(cls, aqt_resource: AQTResource) -> AqtDevice:

def unwrap(obj: T | None) -> T:
if obj is None:
raise ValueError(f"Value cannot be None")
raise ValueError("Value cannot be None")
return obj


Expand Down Expand Up @@ -96,7 +100,7 @@ def get_devices(self) -> list[AqtDevice]:
def print_device_table(self) -> None:
aqt_provider = AQTProvider(access_token=self._access_token)
backend_table = aqt_provider.backends()
print(backend_table)
print(backend_table) # noqa: T201

def post_aqt_job(self, job: PytketAqtJob, aqt_device: AqtDevice) -> str:
aqt_job = _aqt_job_from_pytket_aqt_job(job)
Expand Down Expand Up @@ -142,7 +146,7 @@ def get_devices(self) -> list[AqtDevice]:

def print_device_table(self) -> None:
backend_table = self._aqt_provider.backends()
print(backend_table)
print(backend_table) # noqa: T201

def post_aqt_job(self, aqt_job: PytketAqtJob, aqt_device: AqtDevice) -> str:
circuits = [
Expand Down Expand Up @@ -184,7 +188,7 @@ def get_devices(self) -> list[AqtDevice]:
return AQT_MOCK_DEVICES

def print_device_table(self) -> None:
print("Mock device table")
print("Mock device table") # noqa: T201

def post_aqt_job(self, aqt_job: PytketAqtJob, aqt_device: AqtDevice) -> str:
job_id = str(uuid.uuid4())
Expand Down
4 changes: 3 additions & 1 deletion pytket/extensions/aqt/backends/aqt_job_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,10 @@
# See the License for the specific language governing permissions and
# limitations under the License.
import json
from collections.abc import Sequence
from dataclasses import dataclass
from typing import Optional, Sequence
from typing import Optional

from qiskit_aqt_provider import api_models

from pytket import Circuit
Expand Down
Loading

0 comments on commit 0358cc0

Please sign in to comment.