From 3bbeaef5e3552d89c4e9dd262c6ec1b64bb68cd5 Mon Sep 17 00:00:00 2001 From: Melf Date: Fri, 4 Oct 2024 14:56:45 +0100 Subject: [PATCH 1/8] add ruff config file --- ruff.toml | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 ruff.toml diff --git a/ruff.toml b/ruff.toml new file mode 100644 index 0000000..f2146f6 --- /dev/null +++ b/ruff.toml @@ -0,0 +1,44 @@ +target-version = "py39" + +line-length = 88 + +extend-exclude = ["examples"] + +select = [ + "E", # pycodestyle Errors + "W", # pycodestyle Warnings + + # "A", # flake8-builtins + # "B", # flake8-Bugbear + # "C4", # flake8-comprehensions + # "COM", # flake8-commas + # "EXE", # flake8-executable + "F", # pyFlakes + # "FA", # flake8-future-annotations + # "FIX", # flake8-fixme + # "FLY", # flynt + "I", # isort + # "INP", # flake8-no-pep420 + # "ISC", # flake8-implicit-str-concat + # "N", # pep8-Naming + # "NPY", # NumPy-specific + # "PERF", # Perflint + # "PGH", # pygrep-hooks + # "PIE", # flake8-pie + # "PL", # pylint + # "PT", # flake8-pytest-style + # "RSE", # flake8-raise + # "RUF", # Ruff-specific + # "S", # flake8-bandit (Security) + "SIM", # flake8-simplify + # "SLF", # flake8-self + "T20", # flake8-print + "TCH", # flake8-type-checking + # "TRY", # tryceratops + "UP", # pyupgrade + # "YTT", # flake8-2020 +] + +[per-file-ignores] +".github/workflows/docs/conf.py" = ["E402"] +"__init__.py" = ["F401"] # module imported but unused (6) From ad9c69ede8a041a04c1e3a0e0950574d32372a09 Mon Sep 17 00:00:00 2001 From: Melf Date: Fri, 4 Oct 2024 14:58:46 +0100 Subject: [PATCH 2/8] add ruff to lint ci check --- .github/workflows/lint.yml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 5290823..518f5b2 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -19,10 +19,13 @@ jobs: - name: Update pip run: pip install --upgrade pip - name: Install black and pylint - run: pip install black pylint + run: pip install black pylint ruff - name: Check files are formatted with black run: | black --check . + - name: Run ruff + run: | + ruff check . - name: Run pylint run: | pylint */ From d5142c0c4cc9d0dc2d8f77716b64fd643923c68e Mon Sep 17 00:00:00 2001 From: Melf Date: Fri, 4 Oct 2024 15:01:45 +0100 Subject: [PATCH 3/8] ruff fixes I --- pytket/extensions/braket/__init__.py | 4 +- pytket/extensions/braket/backends/braket.py | 57 +++++++++++---------- pytket/extensions/braket/backends/config.py | 11 ++-- pytket/extensions/braket/braket_convert.py | 6 ++- setup.py | 5 +- tests/backend_test.py | 12 +++-- tests/conftest.py | 8 +-- tests/convert_test.py | 3 +- 8 files changed, 58 insertions(+), 48 deletions(-) diff --git a/pytket/extensions/braket/__init__.py b/pytket/extensions/braket/__init__.py index 6139c27..43adc7a 100644 --- a/pytket/extensions/braket/__init__.py +++ b/pytket/extensions/braket/__init__.py @@ -16,7 +16,7 @@ """ # _metadata.py is copied to the folder after installation. -from ._metadata import __extension_version__, __extension_name__ -from .braket_convert import tk_to_braket, braket_to_tk +from ._metadata import __extension_name__, __extension_version__ from .backends import BraketBackend from .backends.config import BraketConfig, set_braket_config +from .braket_convert import braket_to_tk, tk_to_braket diff --git a/pytket/extensions/braket/backends/braket.py b/pytket/extensions/braket/backends/braket.py index 8abf37f..e1c3267 100644 --- a/pytket/extensions/braket/backends/braket.py +++ b/pytket/extensions/braket/backends/braket.py @@ -12,67 +12,70 @@ # See the License for the specific language governing permissions and # limitations under the License. -from itertools import permutations import json +import time import warnings +from collections.abc import Iterable, Sequence from enum import Enum -import time +from itertools import permutations from typing import ( - cast, + TYPE_CHECKING, Any, Callable, Dict, - Iterable, List, Optional, - Sequence, - Union, - Tuple, Set, - TYPE_CHECKING, + Tuple, + Union, + cast, ) from uuid import uuid4 + +import boto3 +import numpy as np + import braket # type: ignore +import braket.circuits # type: ignore from braket.aws import AwsDevice, AwsSession # type: ignore from braket.aws.aws_device import AwsDeviceType # type: ignore from braket.aws.aws_quantum_task import AwsQuantumTask # type: ignore -import braket.circuits # type: ignore from braket.circuits.observable import Observable # type: ignore from braket.circuits.qubit_set import QubitSet # type: ignore from braket.circuits.result_type import ResultType # type: ignore from braket.device_schema import DeviceActionType # type: ignore from braket.devices import LocalSimulator # type: ignore from braket.tasks.local_quantum_task import LocalQuantumTask # type: ignore -import boto3 -import numpy as np +from pytket.architecture import Architecture, FullyConnected from pytket.backends import Backend, CircuitStatus, ResultHandle, StatusEnum from pytket.backends.backend import KwargTypes -from pytket.backends.backendinfo import BackendInfo from pytket.backends.backend_exceptions import CircuitNotRunError +from pytket.backends.backendinfo import BackendInfo from pytket.backends.backendresult import BackendResult from pytket.backends.resulthandle import _ResultIdTuple +from pytket.circuit import Circuit, OpType +from pytket.circuit_library import TK1_to_RzRx +from pytket.extensions.braket._metadata import __extension_version__ from pytket.extensions.braket.braket_convert import ( - tk_to_braket, get_avg_characterisation, + tk_to_braket, ) -from pytket.extensions.braket._metadata import __extension_version__ -from pytket.circuit import Circuit, OpType from pytket.passes import ( BasePass, + CliffordSimp, CXMappingPass, + DecomposeBoxes, + FullPeepholeOptimise, + NaivePlacementPass, RebaseCustom, RemoveRedundancies, SequencePass, - SynthesiseTket, - FullPeepholeOptimise, - CliffordSimp, - SquashCustom, - DecomposeBoxes, SimplifyInitial, - NaivePlacementPass, + SquashCustom, + SynthesiseTket, ) -from pytket.circuit_library import TK1_to_RzRx from pytket.pauli import Pauli, QubitPauliString +from pytket.placement import NoiseAwarePlacement from pytket.predicates import ( ConnectivityPredicate, GateSetPredicate, @@ -83,8 +86,6 @@ NoSymbolsPredicate, Predicate, ) -from pytket.architecture import Architecture, FullyConnected -from pytket.placement import NoiseAwarePlacement from pytket.utils import prepare_circuit from pytket.utils.operators import QubitPauliOperator from pytket.utils.outcomearray import OutcomeArray @@ -551,11 +552,11 @@ def _get_backend_info( schema = characteristics["braketSchemaHeader"] if schema == IONQ_SCHEMA: fid = characteristics["fidelity"] - get_node_error: Callable[["Node"], float] = lambda n: 1.0 - cast( + get_node_error: Callable[[Node], float] = lambda n: 1.0 - cast( float, fid["1Q"]["mean"] ) - get_readout_error: Callable[["Node"], float] = lambda n: 0.0 - get_link_error: Callable[["Node", "Node"], float] = ( + get_readout_error: Callable[[Node], float] = lambda n: 0.0 + get_link_error: Callable[[Node, Node], float] = ( lambda n0, n1: 1.0 - cast(float, fid["2Q"]["mean"]) ) elif schema == RIGETTI_SCHEMA: @@ -626,7 +627,7 @@ def _get_backend_info( # Construct a fake coupling map if we have a FullyConnected architecture, # otherwise use the coupling provided by the Architecture class. - coupling: list[tuple["Node", "Node"]] + coupling: list[tuple[Node, Node]] if isinstance(arch, FullyConnected): # cast is needed as mypy does not know that we passed a fixed # integer to `permutations`. diff --git a/pytket/extensions/braket/backends/config.py b/pytket/extensions/braket/backends/config.py index e41ea8a..ecc617b 100644 --- a/pytket/extensions/braket/backends/config.py +++ b/pytket/extensions/braket/backends/config.py @@ -12,8 +12,9 @@ # See the License for the specific language governing permissions and # limitations under the License. -from typing import Any, ClassVar, Dict, Optional, Type from dataclasses import dataclass +from typing import Any, ClassVar, Dict, Optional, Type + from pytket.config import PytketExtConfig @@ -33,10 +34,10 @@ def from_extension_dict( cls: Type["BraketConfig"], ext_dict: Dict[str, Any] ) -> "BraketConfig": return cls( - ext_dict.get("s3_bucket", None), - ext_dict.get("s3_folder", None), - ext_dict.get("device_type", None), - ext_dict.get("provider", None), + ext_dict.get("s3_bucket"), + ext_dict.get("s3_folder"), + ext_dict.get("device_type"), + ext_dict.get("provider"), ) diff --git a/pytket/extensions/braket/braket_convert.py b/pytket/extensions/braket/braket_convert.py index bc5518c..c3aed2f 100644 --- a/pytket/extensions/braket/braket_convert.py +++ b/pytket/extensions/braket/braket_convert.py @@ -16,7 +16,7 @@ """ from typing import ( - cast, + TYPE_CHECKING, Any, Callable, Dict, @@ -24,9 +24,11 @@ Optional, Tuple, TypeVar, - TYPE_CHECKING, + cast, ) + from numpy import pi + from braket.circuits import Circuit as BK_Circuit # type: ignore from pytket.circuit import Circuit, OpType, Qubit diff --git a/setup.py b/setup.py index 98f1fd8..97deaa2 100644 --- a/setup.py +++ b/setup.py @@ -12,9 +12,10 @@ # See the License for the specific language governing permissions and # limitations under the License. -import shutil import os -from setuptools import setup, find_namespace_packages # type: ignore +import shutil + +from setuptools import find_namespace_packages, setup # type: ignore metadata: dict = {} with open("_metadata.py") as fp: diff --git a/tests/backend_test.py b/tests/backend_test.py index 1a33c2e..9f6ba7e 100644 --- a/tests/backend_test.py +++ b/tests/backend_test.py @@ -13,19 +13,21 @@ # limitations under the License. import json +import os from collections import Counter from typing import cast -import os -from hypothesis import given, settings, strategies + import numpy as np import pytest -from pytket.extensions.braket import BraketBackend +from hypothesis import given, settings, strategies + from pytket.architecture import FullyConnected -from pytket.circuit import Circuit, OpType, Qubit, Bit +from pytket.circuit import Bit, Circuit, OpType, Qubit +from pytket.extensions.braket import BraketBackend from pytket.pauli import Pauli, QubitPauliString from pytket.utils.expectations import ( - get_pauli_expectation_value, get_operator_expectation_value, + get_pauli_expectation_value, ) from pytket.utils.operators import QubitPauliOperator diff --git a/tests/conftest.py b/tests/conftest.py index 8becadb..a31f11b 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -12,12 +12,14 @@ # See the License for the specific language governing permissions and # limitations under the License. -from typing import Optional import os -import pytest +from typing import Optional + import boto3 -from braket.aws.aws_session import AwsSession # type: ignore +import pytest from _pytest.fixtures import SubRequest +from braket.aws.aws_session import AwsSession # type: ignore + from pytket.extensions.braket import BraketBackend diff --git a/tests/convert_test.py b/tests/convert_test.py index a869809..244e873 100644 --- a/tests/convert_test.py +++ b/tests/convert_test.py @@ -13,8 +13,9 @@ # limitations under the License. import pytest -from pytket.extensions.braket import braket_to_tk, tk_to_braket + from pytket.circuit import Circuit, OpType +from pytket.extensions.braket import braket_to_tk, tk_to_braket def test_convert() -> None: From 31b441e233040f187a56010a5baa56ccbdb4817b Mon Sep 17 00:00:00 2001 From: Melf Date: Fri, 4 Oct 2024 15:04:13 +0100 Subject: [PATCH 4/8] ruff fix II --- pytket/extensions/braket/backends/braket.py | 157 ++++++++++---------- pytket/extensions/braket/backends/config.py | 4 +- pytket/extensions/braket/braket_convert.py | 33 ++-- 3 files changed, 99 insertions(+), 95 deletions(-) diff --git a/pytket/extensions/braket/backends/braket.py b/pytket/extensions/braket/backends/braket.py index e1c3267..6ab5a51 100644 --- a/pytket/extensions/braket/backends/braket.py +++ b/pytket/extensions/braket/backends/braket.py @@ -19,14 +19,8 @@ from enum import Enum from itertools import permutations from typing import ( - TYPE_CHECKING, Any, - Callable, - Dict, - List, Optional, - Set, - Tuple, Union, cast, ) @@ -53,7 +47,7 @@ from pytket.backends.backendinfo import BackendInfo from pytket.backends.backendresult import BackendResult from pytket.backends.resulthandle import _ResultIdTuple -from pytket.circuit import Circuit, OpType +from pytket.circuit import Circuit, Node, OpType from pytket.circuit_library import TK1_to_RzRx from pytket.extensions.braket._metadata import __extension_version__ from pytket.extensions.braket.braket_convert import ( @@ -92,9 +86,6 @@ from .config import BraketConfig -if TYPE_CHECKING: - from pytket.circuit import Node - # Known schemas for noise characteristics IONQ_SCHEMA = { "name": "braket.device_schema.ionq.ionq_provider_properties", @@ -197,7 +188,7 @@ def _obs_from_qps( circuit: Circuit, pauli: QubitPauliString -) -> Tuple[Observable, QubitSet]: +) -> tuple[Observable, QubitSet]: obs, qbs = [], [] for q, p in pauli.map.items(): obs.append(_observables[p]) @@ -212,12 +203,12 @@ def _obs_from_qpo(operator: QubitPauliOperator, n_qubits: int) -> Observable: def _get_result( completed_task: Union[AwsQuantumTask, LocalQuantumTask], - target_qubits: List[int], - measures: Dict[int, int], + target_qubits: list[int], + measures: dict[int, int], want_state: bool, want_dm: bool, ppcirc: Optional[Circuit] = None, -) -> Dict[str, BackendResult]: +) -> dict[str, BackendResult]: """Get a result from a completed task. :param completed_task: braket task @@ -412,7 +403,7 @@ def __init__( ) arch, self._all_qubits = self._get_arch_info(props, self._device_type) - self._characteristics: Optional[Dict] = None + self._characteristics: Optional[dict] = None if self._device_type == _DeviceType.QPU: self._characteristics = props["provider"] self._backend_info = self._get_backend_info( @@ -464,8 +455,8 @@ def __init__( @staticmethod def _get_gate_set( - supported_ops: Set[str], device_type: _DeviceType - ) -> Tuple[Set[OpType], Set[OpType]]: + supported_ops: set[str], device_type: _DeviceType + ) -> tuple[set[OpType], set[OpType]]: multiqs = set() singleqs = set() if not {"cnot", "rx", "rz", "x"} <= supported_ops: @@ -488,8 +479,8 @@ def _get_gate_set( @staticmethod def _get_arch_info( - device_properties: Dict[str, Any], device_type: _DeviceType - ) -> Tuple[Architecture | FullyConnected, List[int]]: + device_properties: dict[str, Any], device_type: _DeviceType + ) -> tuple[Architecture | FullyConnected, list[int]]: # return the architecture, and all_qubits paradigm = device_properties["paradigm"] n_qubits = paradigm["qubitCount"] @@ -497,7 +488,7 @@ def _get_arch_info( if device_type == _DeviceType.QPU: connectivity = paradigm["connectivity"] if connectivity["fullyConnected"]: - all_qubits: List = list(range(n_qubits)) + all_qubits: list = list(range(n_qubits)) else: schema = device_properties["provider"]["braketSchemaHeader"] connectivity_graph = connectivity["connectivityGraph"] @@ -544,79 +535,91 @@ def _get_backend_info( cls, arch: Architecture | FullyConnected, device_name: str, - singleqs: Set[OpType], - multiqs: Set[OpType], - characteristics: Optional[Dict[str, Any]], + singleqs: set[OpType], + multiqs: set[OpType], + characteristics: Optional[dict[str, Any]], ) -> BackendInfo: if characteristics is not None: schema = characteristics["braketSchemaHeader"] if schema == IONQ_SCHEMA: fid = characteristics["fidelity"] - get_node_error: Callable[[Node], float] = lambda n: 1.0 - cast( - float, fid["1Q"]["mean"] - ) - get_readout_error: Callable[[Node], float] = lambda n: 0.0 - get_link_error: Callable[[Node, Node], float] = ( - lambda n0, n1: 1.0 - cast(float, fid["2Q"]["mean"]) - ) + + def get_node_error(n: Node) -> float: + return 1.0 - cast(float, fid["1Q"]["mean"]) + + def get_readout_error(n: Node) -> float: + return 0.0 + + def get_link_error(n0: Node, n1: Node) -> float: + return 1.0 - cast(float, fid["2Q"]["mean"]) + elif schema == RIGETTI_SCHEMA: specs = characteristics["specs"] specs1q, specs2q = specs["1Q"], specs["2Q"] - get_node_error = lambda n: 1.0 - cast( - float, specs1q[f"{n.index[0]}"].get("f1QRB", 1.0) - ) - get_readout_error = lambda n: 1.0 - cast( - float, specs1q[f"{n.index[0]}"].get("fRO", 1.0) - ) - get_link_error = lambda n0, n1: 1.0 - cast( - float, - specs2q[ - f"{min(n0.index[0],n1.index[0])}-{max(n0.index[0],n1.index[0])}" - ].get("fCZ", 1.0), - ) + + def get_node_error(n): + return 1.0 - cast(float, specs1q[f"{n.index[0]}"].get("f1QRB", 1.0)) + + def get_readout_error(n): + return 1.0 - cast(float, specs1q[f"{n.index[0]}"].get("fRO", 1.0)) + + def get_link_error(n0, n1): + return 1.0 - cast( + float, + specs2q[ + f"{min(n0.index[0], n1.index[0])}-{max(n0.index[0], n1.index[0])}" + ].get("fCZ", 1.0), + ) + elif schema == OQC_SCHEMA: properties = characteristics["properties"] props1q, props2q = properties["one_qubit"], properties["two_qubit"] - get_node_error = lambda n: 1.0 - cast( - float, props1q[f"{n.index[0]}"]["fRB"] - ) - get_readout_error = lambda n: 1.0 - cast( - float, props1q[f"{n.index[0]}"]["fRO"] - ) - get_link_error = lambda n0, n1: 1.0 - cast( - float, props2q[f"{n0.index[0]}-{n1.index[0]}"]["fCX"] - ) + + def get_node_error(n): + return 1.0 - cast(float, props1q[f"{n.index[0]}"]["fRB"]) + + def get_readout_error(n): + return 1.0 - cast(float, props1q[f"{n.index[0]}"]["fRO"]) + + def get_link_error(n0, n1): + return 1.0 - cast( + float, props2q[f"{n0.index[0]}-{n1.index[0]}"]["fCX"] + ) + elif schema == IQM_SCHEMA: properties = characteristics["properties"] props1q = {} - for key in properties["one_qubit"].keys(): + for key in properties["one_qubit"]: node1q = str(int(key) - 1) props1q[node1q] = properties["one_qubit"][key] props2q = {} - for key in properties["two_qubit"].keys(): + for key in properties["two_qubit"]: ind = key.index("-") node2q1, node2q2 = str(int(key[:ind]) - 1), str( int(key[ind + 1 :]) - 1 ) props2q[node2q1 + "-" + node2q2] = properties["two_qubit"][key] - get_node_error = lambda n: 1.0 - cast( - float, props1q[f"{n.index[0]}"]["f1Q_simultaneous_RB"] - ) - get_readout_error = lambda n: 1.0 - cast( - float, props1q[f"{n.index[0]}"]["fRO"] - ) - get_link_error = lambda n0, n1: 1.0 - cast( - float, - props2q[ - f"{min(n0.index[0],n1.index[0])}-{max(n0.index[0],n1.index[0])}" - ]["fCZ"], - ) + + def get_node_error(n): + return 1.0 - cast( + float, props1q[f"{n.index[0]}"]["f1Q_simultaneous_RB"] + ) + + def get_readout_error(n): + return 1.0 - cast(float, props1q[f"{n.index[0]}"]["fRO"]) + + def get_link_error(n0, n1): + return 1.0 - cast( + float, + props2q[ + f"{min(n0.index[0], n1.index[0])}-{max(n0.index[0], n1.index[0])}" + ]["fCZ"], + ) # readout error as symmetric 2x2 matrix - to_sym_mat: Callable[[float], List[List[float]]] = lambda x: [ - [1.0 - x, x], - [x, 1.0 - x], - ] + def to_sym_mat(x: float) -> list[list[float]]: + return [[1.0 - x, x], [x, 1.0 - x]] + node_errors = { node: {optype: get_node_error(node) for optype in singleqs} for node in arch.nodes @@ -662,7 +665,7 @@ def _get_backend_info( return backend_info @property - def required_predicates(self) -> List[Predicate]: + def required_predicates(self) -> list[Predicate]: return self._req_preds def rebase_pass(self) -> BasePass: @@ -735,7 +738,7 @@ def _run( def _to_bkcirc( self, circuit: Circuit - ) -> Tuple[braket.circuits.Circuit, List[int], Dict[int, int]]: + ) -> tuple[braket.circuits.Circuit, list[int], dict[int, int]]: return tk_to_braket( circuit, mapped_qubits=(self._device_type == _DeviceType.QPU), @@ -756,7 +759,7 @@ def process_circuits( n_shots: Union[None, int, Sequence[Optional[int]]] = None, valid_check: bool = True, **kwargs: KwargTypes, - ) -> List[ResultHandle]: + ) -> list[ResultHandle]: """ Supported `kwargs`: - `postprocess`: apply end-of-circuit simplifications and classical @@ -847,7 +850,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) @@ -888,7 +891,7 @@ def circuit_status(self, handle: ResultHandle) -> CircuitStatus: return CircuitStatus(StatusEnum.ERROR, f"Unrecognized state '{state}'") @property - def characterisation(self) -> Optional[Dict[str, Any]]: + def characterisation(self) -> Optional[dict[str, Any]]: node_errors = self._backend_info.all_node_gate_errors edge_errors = self._backend_info.all_edge_gate_errors readout_errors = self._backend_info.all_readout_errors @@ -905,7 +908,7 @@ def backend_info(self) -> BackendInfo: return self._backend_info @classmethod - def available_devices(cls, **kwargs: Any) -> List[BackendInfo]: + def available_devices(cls, **kwargs: Any) -> list[BackendInfo]: """ See :py:meth:`pytket.backends.Backend.available_devices`. Supported kwargs: @@ -1205,10 +1208,10 @@ def get_probabilities( def get_amplitudes( self, circuit: Circuit, - states: List[str], + states: list[str], valid_check: bool = True, **kwargs: KwargTypes, - ) -> Dict[str, complex]: + ) -> dict[str, complex]: """ Compute the complex coefficients of the final state. diff --git a/pytket/extensions/braket/backends/config.py b/pytket/extensions/braket/backends/config.py index ecc617b..6129061 100644 --- a/pytket/extensions/braket/backends/config.py +++ b/pytket/extensions/braket/backends/config.py @@ -13,7 +13,7 @@ # limitations under the License. from dataclasses import dataclass -from typing import Any, ClassVar, Dict, Optional, Type +from typing import Any, ClassVar, Optional from pytket.config import PytketExtConfig @@ -31,7 +31,7 @@ class BraketConfig(PytketExtConfig): @classmethod def from_extension_dict( - cls: Type["BraketConfig"], ext_dict: Dict[str, Any] + cls: type["BraketConfig"], ext_dict: dict[str, Any] ) -> "BraketConfig": return cls( ext_dict.get("s3_bucket"), diff --git a/pytket/extensions/braket/braket_convert.py b/pytket/extensions/braket/braket_convert.py index c3aed2f..0ace531 100644 --- a/pytket/extensions/braket/braket_convert.py +++ b/pytket/extensions/braket/braket_convert.py @@ -19,10 +19,7 @@ TYPE_CHECKING, Any, Callable, - Dict, - List, Optional, - Tuple, TypeVar, cast, ) @@ -39,9 +36,9 @@ def tk_to_braket( tkcirc: Circuit, mapped_qubits: bool = False, - forced_qubits: Optional[List[int]] = None, + forced_qubits: Optional[list[int]] = None, force_ops_on_target_qubits: bool = False, -) -> Tuple[BK_Circuit, List[int], Dict[int, int]]: +) -> tuple[BK_Circuit, list[int], dict[int, int]]: """ Convert a tket :py:class:`Circuit` to a braket circuit. @@ -233,8 +230,8 @@ def braket_to_tk(bkcirc: BK_Circuit) -> Circuit: def get_avg_characterisation( - characterisation: Dict[str, Any] -) -> Dict[str, Dict["Node", float]]: + characterisation: dict[str, Any] +) -> dict[str, dict["Node", float]]: """ Convert gate-specific characterisation into readout, one- and two-qubit errors @@ -245,23 +242,27 @@ def get_avg_characterisation( K = TypeVar("K") V1 = TypeVar("V1") V2 = TypeVar("V2") - map_values_t = Callable[[Callable[[V1], V2], Dict[K, V1]], Dict[K, V2]] - map_values: map_values_t = lambda f, d: {k: f(v) for k, v in d.items()} + Callable[[Callable[[V1], V2], dict[K, V1]], dict[K, V2]] + + def map_values(f, d): + return {k: f(v) for k, v in d.items()} node_errors = cast( - Dict["Node", Dict[OpType, float]], characterisation["NodeErrors"] + dict["Node", dict[OpType, float]], characterisation["NodeErrors"] ) link_errors = cast( - Dict[Tuple["Node", "Node"], Dict[OpType, float]], characterisation["EdgeErrors"] + dict[tuple["Node", "Node"], dict[OpType, float]], characterisation["EdgeErrors"] ) readout_errors = cast( - Dict["Node", List[List[float]]], characterisation["ReadoutErrors"] + dict["Node", list[list[float]]], characterisation["ReadoutErrors"] ) - avg: Callable[[Dict[Any, float]], float] = lambda xs: sum(xs.values()) / len(xs) - avg_mat: Callable[[List[List[float]]], float] = ( - lambda xs: (xs[0][1] + xs[1][0]) / 2.0 - ) + def avg(xs: dict[Any, float]) -> float: + return sum(xs.values()) / len(xs) + + def avg_mat(xs: list[list[float]]) -> float: + return (xs[0][1] + xs[1][0]) / 2.0 + avg_readout_errors = map_values(avg_mat, readout_errors) avg_node_errors = map_values(avg, node_errors) avg_link_errors = map_values(avg, link_errors) From 783b1fe3738bb941c75c36ee41bae70f9c035f1b Mon Sep 17 00:00:00 2001 From: Melf Date: Fri, 4 Oct 2024 15:08:41 +0100 Subject: [PATCH 5/8] fix setup path --- setup.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/setup.py b/setup.py index 97deaa2..1f1ce24 100644 --- a/setup.py +++ b/setup.py @@ -14,6 +14,7 @@ import os import shutil +from pathlib import Path from setuptools import find_namespace_packages, setup # type: ignore @@ -38,7 +39,7 @@ "Tracker": "https://github.com/CQCL/pytket-braket/issues", }, description="Extension for pytket, providing access to Amazon Braket backends", - long_description=open("README.md").read(), + long_description=(Path(__file__).parent / "README.md").read_text(), long_description_content_type="text/markdown", license="Apache 2", packages=find_namespace_packages(include=["pytket.*"]), From 54346d3031832cdfc31bf655f045871f53679e52 Mon Sep 17 00:00:00 2001 From: Melf Date: Fri, 4 Oct 2024 15:34:00 +0100 Subject: [PATCH 6/8] ruff updates III --- pytket/extensions/braket/backends/braket.py | 22 +++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/pytket/extensions/braket/backends/braket.py b/pytket/extensions/braket/backends/braket.py index 6ab5a51..67681e4 100644 --- a/pytket/extensions/braket/backends/braket.py +++ b/pytket/extensions/braket/backends/braket.py @@ -228,7 +228,7 @@ def _get_result( m = result.get_value_by_result_type( ResultType.DensityMatrix(target=target_qubits) ) - if type(completed_task) == AwsQuantumTask: + if type(completed_task) is AwsQuantumTask: kwargs["density_matrix"] = np.array( [[complex(x, y) for x, y in row] for row in m], dtype=complex ) @@ -495,21 +495,21 @@ def _get_arch_info( # Convert strings to ints if schema == IQM_SCHEMA: connectivity_graph = dict( - (int(k) - 1, [int(v) - 1 for v in l]) - for k, l in connectivity_graph.items() + (int(k) - 1, [int(v) - 1 for v in le]) + for k, le in connectivity_graph.items() ) # each connectivity graph key will be an int # connectivity_graph values will be lists all_qubits_set = set() for k, v in connectivity_graph.items(): all_qubits_set.add(k - 1) - for l in v: - all_qubits_set.add(l - 1) + for le in v: + all_qubits_set.add(le - 1) all_qubits = list(all_qubits_set) else: connectivity_graph = dict( - (int(k), [int(v) for v in l]) - for k, l in connectivity_graph.items() + (int(k), [int(v) for v in le]) + for k, le in connectivity_graph.items() ) # each connectivity graph key will be an int # connectivity_graph values will be lists @@ -526,7 +526,7 @@ def _get_arch_info( arch = FullyConnected(len(all_qubits)) else: arch = Architecture( - [(k, v) for k, l in connectivity_graph.items() for v in l] + [(k, v) for k, le in connectivity_graph.items() for v in le] ) return arch, all_qubits @@ -567,7 +567,8 @@ def get_link_error(n0, n1): return 1.0 - cast( float, specs2q[ - f"{min(n0.index[0], n1.index[0])}-{max(n0.index[0], n1.index[0])}" + f"{min(n0.index[0], n1.index[0])}\ +-{max(n0.index[0], n1.index[0])}" ].get("fCZ", 1.0), ) @@ -612,7 +613,8 @@ def get_link_error(n0, n1): return 1.0 - cast( float, props2q[ - f"{min(n0.index[0], n1.index[0])}-{max(n0.index[0], n1.index[0])}" + f"{min(n0.index[0], n1.index[0])}\ +-{max(n0.index[0], n1.index[0])}" ]["fCZ"], ) From 7637c4b42e8bc5b897d8b7257b76966ede8b5829 Mon Sep 17 00:00:00 2001 From: Melf Date: Fri, 4 Oct 2024 16:12:32 +0100 Subject: [PATCH 7/8] fix ruff --- pytket/extensions/braket/braket_convert.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pytket/extensions/braket/braket_convert.py b/pytket/extensions/braket/braket_convert.py index 0ace531..da3cdce 100644 --- a/pytket/extensions/braket/braket_convert.py +++ b/pytket/extensions/braket/braket_convert.py @@ -242,9 +242,9 @@ def get_avg_characterisation( K = TypeVar("K") V1 = TypeVar("V1") V2 = TypeVar("V2") - Callable[[Callable[[V1], V2], dict[K, V1]], dict[K, V2]] + map_values_t = Callable[[Callable[[V1], V2], dict[K, V1]], dict[K, V2]] - def map_values(f, d): + def map_values(f, d) -> map_values_t: return {k: f(v) for k, v in d.items()} node_errors = cast( From 14fba83f6bbb7dfed140d45ea5b6a292168955aa Mon Sep 17 00:00:00 2001 From: Melf Date: Fri, 4 Oct 2024 16:20:07 +0100 Subject: [PATCH 8/8] fix mypy --- pytket/extensions/braket/backends/braket.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pytket/extensions/braket/backends/braket.py b/pytket/extensions/braket/backends/braket.py index 67681e4..38eb616 100644 --- a/pytket/extensions/braket/backends/braket.py +++ b/pytket/extensions/braket/backends/braket.py @@ -557,13 +557,13 @@ def get_link_error(n0: Node, n1: Node) -> float: specs = characteristics["specs"] specs1q, specs2q = specs["1Q"], specs["2Q"] - def get_node_error(n): + def get_node_error(n: Node) -> float: return 1.0 - cast(float, specs1q[f"{n.index[0]}"].get("f1QRB", 1.0)) - def get_readout_error(n): + def get_readout_error(n: Node) -> float: return 1.0 - cast(float, specs1q[f"{n.index[0]}"].get("fRO", 1.0)) - def get_link_error(n0, n1): + def get_link_error(n0: Node, n1: Node) -> float: return 1.0 - cast( float, specs2q[