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

Melf/add ruff 2024 #86

Draft
wants to merge 5 commits into
base: main
Choose a base branch
from
Draft
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
5 changes: 4 additions & 1 deletion .github/workflows/lint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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 */
8 changes: 4 additions & 4 deletions pytket/extensions/cirq/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,13 @@
"""Module for conversion between Google Cirq and tket primitives."""

# _metadata.py is copied to the folder after installation.
from ._metadata import __extension_version__, __extension_name__
from .backends.cirq_convert import cirq_to_tk, tk_to_cirq, process_characterisation
from ._metadata import __extension_name__, __extension_version__
from .backends import (
CirqStateSampleBackend,
CirqStateSimBackend,
CirqCliffordSampleBackend,
CirqCliffordSimBackend,
CirqDensityMatrixSampleBackend,
CirqDensityMatrixSimBackend,
CirqStateSampleBackend,
CirqStateSimBackend,
)
from .backends.cirq_convert import cirq_to_tk, process_characterisation, tk_to_cirq
4 changes: 2 additions & 2 deletions pytket/extensions/cirq/backends/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,10 @@
"""Backends for connecting to Cirq simulators directly from pytket"""

from .cirq import (
CirqStateSampleBackend,
CirqStateSimBackend,
CirqCliffordSampleBackend,
CirqCliffordSimBackend,
CirqDensityMatrixSampleBackend,
CirqDensityMatrixSimBackend,
CirqStateSampleBackend,
CirqStateSimBackend,
)
64 changes: 31 additions & 33 deletions pytket/extensions/cirq/backends/cirq.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,48 +13,49 @@
# limitations under the License.

from abc import abstractmethod
from typing import Sequence, cast, Optional, List, Union
from collections.abc import Sequence
from typing import Optional, Union, cast
from uuid import uuid4

from cirq import ops
from cirq.circuits import Circuit as CirqCircuit
from cirq.devices import NOISE_MODEL_LIKE
from cirq.sim import (
CliffordSimulator,
CliffordSimulatorStepResult,
DensityMatrixSimulator,
Simulator,
)

from cirq import ops
from cirq.value import RANDOM_STATE_OR_SEED_LIKE
from cirq.devices import NOISE_MODEL_LIKE
from cirq.circuits import Circuit as CirqCircuit

from pytket.backends import Backend, CircuitStatus, ResultHandle, StatusEnum
from pytket.backends.backendinfo import BackendInfo
from pytket.backends.backendresult import BackendResult
from pytket.backends.resulthandle import _ResultIdTuple
from pytket.circuit import Circuit, OpType, Qubit
from pytket.transform import Transform
from pytket.circuit_library import CX, TK1_to_PhasedXRz
from pytket.extensions.cirq._metadata import __extension_version__
from pytket.passes import (
BasePass,
auto_rebase_pass,
SequencePass,
RebaseCustom,
SquashCustom,
SynthesiseTket,
DecomposeBoxes,
FlattenRegisters,
RemoveRedundancies,
FullPeepholeOptimise,
RebaseCustom,
RemoveRedundancies,
SequencePass,
SquashCustom,
SynthesiseTket,
auto_rebase_pass,
)
from pytket.circuit_library import TK1_to_PhasedXRz, CX
from pytket.predicates import (
GateSetPredicate,
NoClassicalControlPredicate,
NoFastFeedforwardPredicate,
Predicate,
)
from pytket.backends import Backend, ResultHandle, CircuitStatus, StatusEnum
from pytket.backends.backendresult import BackendResult
from pytket.backends.backendinfo import BackendInfo
from pytket.backends.resulthandle import _ResultIdTuple
from pytket.utils.results import KwargTypes
from pytket.transform import Transform
from pytket.utils.outcomearray import OutcomeArray
from pytket.extensions.cirq._metadata import __extension_version__
from pytket.utils.results import KwargTypes

from .cirq_convert import tk_to_cirq
from .cirq_utils import _get_default_uids

Expand Down Expand Up @@ -93,7 +94,7 @@ def rebase_pass(self) -> BasePass:
return auto_rebase_pass({OpType.CZ, OpType.PhasedX, OpType.Rz})

@property
def required_predicates(self) -> List[Predicate]:
def required_predicates(self) -> list[Predicate]:
preds = [
NoClassicalControlPredicate(),
NoFastFeedforwardPredicate(),
Expand Down Expand Up @@ -153,10 +154,7 @@ def _run_circuit(self, circuit: Circuit, n_shots: int) -> BackendResult:
run = self._simulator.run(cirq_circ, repetitions=n_shots)
run_dict = run.data.to_dict()
c_bits = [
bit
for key in run_dict.keys()
for bit in bit_to_qubit_map.keys()
if str(bit) == key
bit for key in run_dict for bit in bit_to_qubit_map if str(bit) == key
]
individual_readouts = [
list(readout.values()) for readout in run_dict.values()
Expand All @@ -172,7 +170,7 @@ def process_circuits(
n_shots: Union[None, int, Sequence[Optional[int]]] = None,
valid_check: bool = True,
**kwargs: KwargTypes,
) -> List[ResultHandle]:
) -> list[ResultHandle]:
circuits = list(circuits)
n_shots_list = Backend._get_n_shots_as_list(
n_shots,
Expand Down Expand Up @@ -278,7 +276,7 @@ def process_circuits(
n_shots: Optional[Union[int, Sequence[int]]] = None,
valid_check: bool = True,
**kwargs: KwargTypes,
) -> List[ResultHandle]:
) -> list[ResultHandle]:
if n_shots is not None:
raise ValueError("`n_shots` argument is invalid for _CirqSimBackend")

Expand All @@ -297,7 +295,7 @@ def process_circuits(
@abstractmethod
def package_results(
self, circuit: CirqCircuit, q_bits: Sequence[Qubit]
) -> List[BackendResult]:
) -> list[BackendResult]:
"""

:param circuit: The circuit to simulate.
Expand All @@ -309,7 +307,7 @@ def package_results(
"""
...

def _run_circuit_moments(self, circuit: Circuit) -> List[BackendResult]:
def _run_circuit_moments(self, circuit: Circuit) -> list[BackendResult]:
cirq_circ = tk_to_cirq(circuit, copy_all_qubits=True)
_, q_bits = _get_default_uids(cirq_circ, circuit)
return self.package_results(cirq_circ, q_bits)
Expand All @@ -334,7 +332,7 @@ def process_circuits_moments(
circuits: Sequence[Circuit],
valid_check: bool = True,
**kwargs: KwargTypes,
) -> List[ResultHandle]:
) -> list[ResultHandle]:
"""
Submit circuits to the backend for running. The results will be stored
in the backend's result cache to be retrieved by the corresponding
Expand Down Expand Up @@ -385,7 +383,7 @@ def package_result(

def package_results(
self, circuit: CirqCircuit, q_bits: Sequence[Qubit]
) -> List[BackendResult]:
) -> list[BackendResult]:
moments = self._simulator.simulate_moment_steps(
circuit,
qubit_order=ops.QubitOrder.as_qubit_order(ops.QubitOrder.DEFAULT).order_for(
Expand Down Expand Up @@ -422,7 +420,7 @@ def package_result(

def package_results(
self, circuit: CirqCircuit, q_bits: Sequence[Qubit]
) -> List[BackendResult]:
) -> list[BackendResult]:
moments = self._simulator.simulate_moment_steps(circuit)
all_backres = [
BackendResult(
Expand Down Expand Up @@ -483,7 +481,7 @@ def package_result(

def package_results(
self, circuit: CirqCircuit, q_bits: Sequence[Qubit]
) -> List[BackendResult]:
) -> list[BackendResult]:
moments = self._simulator.simulate_moment_steps(
circuit,
qubit_order=ops.QubitOrder.as_qubit_order(ops.QubitOrder.DEFAULT).order_for(
Expand Down
29 changes: 15 additions & 14 deletions pytket/extensions/cirq/backends/cirq_convert.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,18 @@
Devices
"""

from typing import List, Dict, FrozenSet, cast, Any, Union, Type
import cmath
from logging import warning
import re
from cirq.devices import LineQubit, GridQubit
import cirq.ops
from logging import warning
from typing import Any, Union, cast

import cirq_google
from sympy import pi, Basic, Symbol
from sympy import Basic, Symbol, pi

from pytket.circuit import Circuit, OpType, Qubit, Bit, Node
import cirq.ops
from cirq.devices import GridQubit, LineQubit
from pytket.architecture import Architecture
from pytket.circuit import Bit, Circuit, Node, OpType, Qubit

# For translating cirq circuits to tket circuits
cirq_common = cirq.ops.common_gates
Expand Down Expand Up @@ -67,7 +68,7 @@
cirq.ops.PhasedISwapPowGate: OpType.PhasedISWAP,
}
# reverse mapping for convenience
_ops2cirq_mapping: Dict = dict((item[1], item[0]) for item in _cirq2ops_mapping.items())
_ops2cirq_mapping: dict = dict((item[1], item[0]) for item in _cirq2ops_mapping.items())
# spot special rotation gates
_constant_gates = (
cirq_common.CNOT,
Expand Down Expand Up @@ -168,11 +169,11 @@ def cirq_to_tk(circuit: cirq.circuits.Circuit) -> Circuit:
raise NotImplementedError(
"Operation not supported by tket: " + str(op.gate)
) from error
params: List[Union[float, Basic, Symbol]] = []
params: list[Union[float, Basic, Symbol]] = []
elif gatetype in _radian_gates:
try:
optype = _cirq2ops_radians_mapping[
cast(Type[cirq.ops.EigenGate], gatetype)
cast(type[cirq.ops.EigenGate], gatetype)
]
except KeyError as error:
raise NotImplementedError(
Expand Down Expand Up @@ -225,7 +226,7 @@ def tk_to_cirq(tkcirc: Circuit, copy_all_qubits: bool = False) -> cirq.circuits.
for q in tkcirc.qubits:
tkcirc.add_gate(OpType.noop, [q])

qmap: Dict[Qubit, Union[cirq.ops.NamedQubit, LineQubit, GridQubit]] = {}
qmap: dict[Qubit, Union[cirq.ops.NamedQubit, LineQubit, GridQubit]] = {}
line_name = None
grid_name = None
# Since Cirq can only support registers of up to 2 dimensions, we explicitly
Expand All @@ -237,14 +238,14 @@ def tk_to_cirq(tkcirc: Circuit, copy_all_qubits: bool = False) -> cirq.circuits.
if len(qb.index) == 0:
qmap.update({qb: cirq.ops.NamedQubit(qb.reg_name)})
elif len(qb.index) == 1:
if line_name != None and line_name != qb.reg_name:
if line_name is not None and line_name != qb.reg_name:
raise NotImplementedError(
"Cirq can only support a single linear register"
)
line_name = qb.reg_name
qmap.update({qb: LineQubit(qb.index[0])})
elif len(qb.index) == 2 or (len(qb.index) == 3 and is_flat_3d):
if grid_name != None and grid_name != qb.reg_name:
if grid_name is not None and grid_name != qb.reg_name:
raise NotImplementedError(
"Cirq can only support a single grid register"
)
Expand Down Expand Up @@ -308,7 +309,7 @@ def tk_to_cirq(tkcirc: Circuit, copy_all_qubits: bool = False) -> cirq.circuits.
# For converting cirq devices to tket devices


def _sort_row_col(qubits: FrozenSet[GridQubit]) -> List[GridQubit]:
def _sort_row_col(qubits: frozenset[GridQubit]) -> list[GridQubit]:
"""Sort grid qubits first by row then by column"""

return sorted(qubits, key=lambda x: (x.row, x.col))
Expand All @@ -325,7 +326,7 @@ def process_characterisation(
:return: A dictionary containing device characteristics
"""
data = device.metadata
qubits: FrozenSet[GridQubit] = data.qubit_set
qubits: frozenset[GridQubit] = data.qubit_set
qubit_graph = data.nx_graph

qb_map = {q: Node("q", q.row, q.col) for q in qubits}
Expand Down
11 changes: 6 additions & 5 deletions pytket/extensions/cirq/backends/cirq_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,18 @@
"""Shared utility methods for cirq backends.
"""

from typing import Tuple, List, cast
from typing import cast

from cirq.circuits import Circuit as CirqCircuit
from cirq.ops import QubitOrder, MeasurementGate, NamedQubit
from cirq.devices import LineQubit, GridQubit
from cirq.devices import GridQubit, LineQubit
from cirq.ops import MeasurementGate, NamedQubit, QubitOrder
from cirq.protocols import is_measurement
from pytket.circuit import Circuit, Qubit, Bit
from pytket.circuit import Bit, Circuit, Qubit


def _get_default_uids(
cirq_circuit: CirqCircuit, tket_circuit: Circuit
) -> Tuple[List[Bit], List[Qubit]]:
) -> tuple[list[Bit], list[Qubit]]:
if len(tket_circuit.qubit_readout) == 0:
return [], tket_circuit.qubits
else:
Expand Down
44 changes: 44 additions & 0 deletions ruff.toml
Original file line number Diff line number Diff line change
@@ -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)
8 changes: 5 additions & 3 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,11 @@
# 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 pathlib import Path

from setuptools import find_namespace_packages, setup # type: ignore

metadata: dict = {}
with open("_metadata.py") as fp:
Expand All @@ -38,7 +40,7 @@
},
description="Extension for pytket, providing translation to and from the Cirq "
"framework",
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.*"]),
Expand Down
Loading
Loading