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 #106

Draft
wants to merge 6 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 */
9 changes: 4 additions & 5 deletions pytket/extensions/qulacs/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,12 @@
"""Module for conversion from tket primitives to Qulacs primitives."""

# _metadata.py is copied to the folder after installation.
from ._metadata import __extension_version__, __extension_name__
from contextlib import suppress

from ._metadata import __extension_name__, __extension_version__
from .backends import QulacsBackend

try:
with suppress(ImportError):
from .backends import QulacsGPUBackend
except ImportError:
# warning was already raised
pass

from .qulacs_convert import tk_to_qulacs
46 changes: 24 additions & 22 deletions pytket/extensions/qulacs/backends/qulacs_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,15 @@
"""Methods to allow tket circuits to be ran on the Qulacs simulator
"""

from typing import List, Optional, Sequence, Union, Type, cast
from collections.abc import Sequence
from logging import warning
from random import Random
from typing import Optional, Union, cast
from uuid import uuid4

import numpy as np
from sympy import Expr
from qulacs import Observable, QuantumState, DensityMatrix

from pytket.backends import (
Backend,
CircuitNotRunError,
Expand All @@ -33,38 +35,38 @@
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, OpType, Pauli
from pytket.extensions.qulacs._metadata import __extension_version__
from pytket.extensions.qulacs.qulacs_convert import (
_IBM_GATES,
_MEASURE_GATES,
_ONE_QUBIT_GATES,
_ONE_QUBIT_ROTATIONS,
_TWO_QUBIT_GATES,
tk_to_qulacs,
)
from pytket.passes import (
BasePass,
SynthesiseTket,
SequencePass,
DecomposeBoxes,
FullPeepholeOptimise,
FlattenRegisters,
FullPeepholeOptimise,
SequencePass,
SynthesiseTket,
auto_rebase_pass,
)
from pytket.pauli import QubitPauliString
from pytket.predicates import (
DefaultRegisterPredicate,
GateSetPredicate,
NoClassicalControlPredicate,
NoFastFeedforwardPredicate,
NoMidMeasurePredicate,
NoSymbolsPredicate,
DefaultRegisterPredicate,
Predicate,
)
from pytket.circuit import Pauli
from pytket.passes import auto_rebase_pass
from pytket.pauli import QubitPauliString
from pytket.utils.operators import QubitPauliOperator
from pytket.utils.outcomearray import OutcomeArray
from pytket.extensions.qulacs.qulacs_convert import (
tk_to_qulacs,
_IBM_GATES,
_MEASURE_GATES,
_ONE_QUBIT_GATES,
_TWO_QUBIT_GATES,
_ONE_QUBIT_ROTATIONS,
)
from qulacs import DensityMatrix, Observable, QuantumState

_GPU_ENABLED = True
try:
Expand Down Expand Up @@ -125,7 +127,7 @@ def __init__(
self._GATE_SET,
)
self._result_type = result_type
self._sim: Type[Union[QuantumState, DensityMatrix, "QuantumStateGpu"]]
self._sim: type[Union[QuantumState, DensityMatrix, QuantumStateGpu]]
if result_type == "state_vector":
self._sim = QuantumState
elif result_type == "density_matrix":
Expand All @@ -144,7 +146,7 @@ def backend_info(self) -> Optional["BackendInfo"]:
return self._backend_info

@property
def required_predicates(self) -> List[Predicate]:
def required_predicates(self) -> list[Predicate]:
return [
NoClassicalControlPredicate(),
NoFastFeedforwardPredicate(),
Expand Down Expand Up @@ -188,7 +190,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 @@ -271,7 +273,7 @@ def _sample_quantum_state(
quantum_state: Union[QuantumState, DensityMatrix, "QuantumStateGpu"],
n_shots: int,
rng: Optional[Random],
) -> List[int]:
) -> list[int]:
if rng:
return quantum_state.sampling(n_shots, rng.randint(0, 2**32 - 1))
else:
Expand Down
16 changes: 4 additions & 12 deletions pytket/extensions/qulacs/qulacs_convert.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,10 @@
"""Conversion from to tket circuits to Qulacs circuits
"""
import numpy as np
from qulacs import QuantumCircuit, gate

from pytket.circuit import Circuit, OpType
from pytket.passes import FlattenRegisters
from qulacs import QuantumCircuit, gate

_ONE_QUBIT_GATES = {
OpType.X: gate.X,
Expand Down Expand Up @@ -90,20 +91,11 @@ def tk_to_qulacs(
id2 = index_map[com.qubits[1].index[0]]
add_gate = qulacs_gate(id1, id2)

elif optype in _MEASURE_GATES:
continue
# gate = _MEASURE_GATES[optype]
# qubit = com.qubits[0].index[0]
# bit = com.bits[0].index[0]
# add_gate = (gate(qubit, bit))

elif optype == OpType.Barrier:
elif optype in _MEASURE_GATES or optype == OpType.Barrier:
continue

else:
raise NotImplementedError(
"Gate: {} Not Implemented in Qulacs!".format(optype)
)
raise NotImplementedError(f"Gate: {optype} Not Implemented in Qulacs!")
qulacs_circ.add_gate(add_gate)

return qulacs_circ
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 @@ -37,7 +39,7 @@
"Tracker": "https://github.com/CQCL/pytket-qulacs/issues",
},
description="Extension for pytket, providing access to the Qulacs Simulator",
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
23 changes: 13 additions & 10 deletions tests/test_qulacs_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,26 +12,29 @@
# See the License for the specific language governing permissions and
# limitations under the License.

from collections import Counter
from typing import List, Sequence, Union, Optional, Dict, Any
import warnings
import math
import warnings
from collections import Counter
from collections.abc import Sequence
from datetime import timedelta
from hypothesis import given, strategies, settings
from typing import Any, Optional, Union

import numpy as np
import pytest
from hypothesis import given, settings, strategies

from pytket.backends import ResultHandle
from pytket.circuit import Circuit, BasisOrder, OpType, Qubit
from pytket.pauli import Pauli, QubitPauliString
from pytket.circuit import BasisOrder, Circuit, OpType, Qubit
from pytket.extensions.qulacs import QulacsBackend
from pytket.passes import CliffordSimp
from pytket.pauli import Pauli, QubitPauliString
from pytket.utils.operators import QubitPauliOperator
from pytket.utils.results import KwargTypes
from pytket.extensions.qulacs import QulacsBackend


def make_seeded_QulacsBackend(base: type[QulacsBackend]) -> type:
class SeededQulacsBackend(base): # type: ignore
def __init__(self, seed: int, kwargs: Optional[Dict[str, Any]] = None):
def __init__(self, seed: int, kwargs: Optional[dict[str, Any]] = None):
if kwargs is None:
kwargs = {}
base.__init__(self, **kwargs)
Expand All @@ -43,8 +46,8 @@ def process_circuits(
n_shots: Union[None, int, Sequence[Optional[int]]] = None,
valid_check: bool = True,
**kwargs: KwargTypes
) -> List[ResultHandle]:
if not "seed" in kwargs:
) -> list[ResultHandle]:
if "seed" not in kwargs:
kwargs["seed"] = self._seed
return base.process_circuits(self, circuits, n_shots, valid_check, **kwargs)

Expand Down
1 change: 1 addition & 0 deletions tests/test_qulacs_convert.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import numpy as np
from qulacs import QuantumCircuit, QuantumState
from qulacs.state import inner_product

from pytket.circuit import Circuit, OpType
from pytket.extensions.qulacs import tk_to_qulacs

Expand Down
Loading