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

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 @@ -22,10 +22,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 */
10 changes: 5 additions & 5 deletions pytket/extensions/qujax/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,12 @@
"""

# _metadata.py is copied to the folder after installation.
from ._metadata import __extension_version__, __extension_name__
from ._metadata import __extension_name__, __extension_version__
from .qujax_convert import (
tk_to_qujax,
tk_to_qujax_args,
tk_to_param,
_tk_qubits_to_inds,
print_circuit,
qujax_args_to_tk,
_tk_qubits_to_inds,
tk_to_param,
tk_to_qujax,
tk_to_qujax_args,
)
18 changes: 10 additions & 8 deletions pytket/extensions/qujax/qujax_convert.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,17 +16,19 @@
Methods to allow conversion between qujax and pytket
"""

from typing import Tuple, Sequence, Optional, List, Union, Callable, Any
from collections.abc import Sequence
from functools import wraps
from typing import Any, Callable, Optional, Union

import qujax # type: ignore
from jax import numpy as jnp
from sympy import lambdify, Symbol
from pytket import Qubit, Circuit # type: ignore
from sympy import Symbol, lambdify

import qujax # type: ignore
from pytket import Circuit, Qubit # type: ignore
from pytket._tket.circuit import Command


def _tk_qubits_to_inds(tk_qubits: Sequence[Qubit]) -> Tuple[int, ...]:
def _tk_qubits_to_inds(tk_qubits: Sequence[Qubit]) -> tuple[int, ...]:
"""
Convert Sequence of pytket qubits objects to tuple of integers qubit indices.

Expand Down Expand Up @@ -63,7 +65,7 @@ def g(*args: Any, **kwargs: Any) -> Any:

def _symbolic_command_to_gate_and_param_inds(
command: Command, symbol_map: dict
) -> Tuple[Union[str, Callable[[jnp.ndarray], jnp.ndarray]], Sequence[int]]:
) -> tuple[Union[str, Callable[[jnp.ndarray], jnp.ndarray]], Sequence[int]]:
"""
Convert pytket command to qujax (gate, parameter indices) tuple.

Expand Down Expand Up @@ -108,7 +110,7 @@ def _symbolic_command_to_gate_and_param_inds(
return gate, param_inds


def tk_to_qujax_args(circuit: Circuit, symbol_map: Optional[dict] = None) -> Tuple[
def tk_to_qujax_args(circuit: Circuit, symbol_map: Optional[dict] = None) -> tuple[
Sequence[Union[str, Callable[[jnp.ndarray], jnp.ndarray]]],
Sequence[Sequence[int]],
Sequence[Sequence[int]],
Expand Down Expand Up @@ -292,7 +294,7 @@ def print_circuit(
gate_ind_min: int = 0,
gate_ind_max: int = jnp.inf, # type: ignore
sep_length: int = 1,
) -> List[str]:
) -> list[str]:
"""
Returns and prints basic string representation of circuit.

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 @@ -37,7 +39,7 @@
"Tracker": "https://github.com/CQCL/pytket-qujax/issues",
},
description="Extension for pytket, providing access to qujax functions",
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
25 changes: 16 additions & 9 deletions tests/test_tket.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,20 +12,22 @@
# See the License for the specific language governing permissions and
# limitations under the License.

from typing import Union, Any
from jax import numpy as jnp, jit, grad, random
import qujax # type: ignore
from typing import Any, Union

import pytest
import qujax # type: ignore
from jax import grad, jit, random
from jax import numpy as jnp

from pytket.circuit import Circuit, Qubit
from pytket.pauli import Pauli, QubitPauliString
from pytket.utils import QubitPauliOperator
from pytket.extensions.qujax import (
tk_to_qujax,
tk_to_qujax_args,
qujax_args_to_tk,
tk_to_param,
tk_to_qujax,
tk_to_qujax_args,
)
from pytket.pauli import Pauli, QubitPauliString
from pytket.utils import QubitPauliOperator


def _test_circuit(
Expand Down Expand Up @@ -68,11 +70,16 @@ def _test_circuit(
assert jnp.allclose(test_jit_dm_diag, true_probs)

if param is not None:
cost_func = lambda p: jnp.square(apply_circuit(p)).real.sum()

def cost_func(p):
return jnp.square(apply_circuit(p)).real.sum()

grad_cost_func = grad(cost_func)
assert isinstance(grad_cost_func(param), jnp.ndarray)

cost_jit_func = lambda p: jnp.square(jit_apply_circuit(p)).real.sum()
def cost_jit_func(p):
return jnp.square(jit_apply_circuit(p)).real.sum()

grad_cost_jit_func = grad(cost_jit_func)
assert isinstance(grad_cost_jit_func(param), jnp.ndarray)

Expand Down
17 changes: 12 additions & 5 deletions tests/test_tket_symbolic.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,18 @@
# See the License for the specific language governing permissions and
# limitations under the License.

from typing import Sequence
from collections.abc import Sequence

import pytest
from jax import grad, jit, random
from jax import numpy as jnp
from sympy import Symbol
from jax import numpy as jnp, jit, grad, random

from pytket.circuit import Circuit, OpType
from pytket.extensions.qujax import (
qujax_args_to_tk,
tk_to_qujax,
tk_to_qujax_args,
qujax_args_to_tk,
)


Expand Down Expand Up @@ -69,11 +71,16 @@ def _test_circuit(
assert jnp.allclose(test_jit_dm_diag, true_probs)

if len(params):
cost_func = lambda p: jnp.square(apply_circuit(p)).real.sum()

def cost_func(p):
return jnp.square(apply_circuit(p)).real.sum()

grad_cost_func = grad(cost_func)
assert isinstance(grad_cost_func(params), jnp.ndarray)

cost_jit_func = lambda p: jnp.square(jit_apply_circuit(p)).real.sum()
def cost_jit_func(p):
return jnp.square(jit_apply_circuit(p)).real.sum()

grad_cost_jit_func = grad(cost_jit_func)
assert isinstance(grad_cost_jit_func(params), jnp.ndarray)

Expand Down
Loading