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

Add ruff check to CI and clean up Python #1661

Merged
merged 16 commits into from
Nov 8, 2024
8 changes: 6 additions & 2 deletions .github/workflows/lint.yml
Original file line number Diff line number Diff line change
@@ -15,8 +15,8 @@ jobs:
uses: actions/setup-python@v5
with:
python-version: '3.x'
- name: Install black and pylint
run: pip install black pylint
- name: Install black, pylint and ruff
run: pip install black pylint ruff
- name: Check files are formatted with black
run: |
# Paths specified to avoid formatting submodules
@@ -25,3 +25,7 @@ jobs:
run: |
cd pytket
pylint --ignore-paths=pytket/_tket pytket/
- name: ruff check
run: |
cd pytket
ruff check .
3 changes: 0 additions & 3 deletions pytket/pytket/circuit/__init__.py
Original file line number Diff line number Diff line change
@@ -16,10 +16,7 @@
tket :py:class:`Circuit` data structure.
This module is provided in binary form during the PyPI installation."""
from typing import (
TYPE_CHECKING,
Any,
Tuple,
Type,
Union,
Callable,
Optional,
3 changes: 2 additions & 1 deletion pytket/pytket/passes/passselector.py
Original file line number Diff line number Diff line change
@@ -57,7 +57,8 @@ def apply(self, circ: Circuit) -> Circuit:
try:
p.apply(c)
self._scores.append(self._score_func(c))
except: # in case of any error the pass should be ignored
except: # noqa: E722
# in case of any error the pass should be ignored
self._scores.append(None)

try:
2 changes: 1 addition & 1 deletion pytket/pytket/qasm/qasm.py
Original file line number Diff line number Diff line change
@@ -1818,7 +1818,7 @@ def add_classical_exp_box(self, op: ClassicalExpBox, args: List[Bit]) -> None:
self.mark_as_written(label, f"{out_args[0].reg_name}")
else:
raise QASMUnsupportedError(
f"ClassicalExpBox only supported"
"ClassicalExpBox only supported"
" for writing to a single bit or whole registers."
)

2 changes: 1 addition & 1 deletion pytket/pytket/utils/operators.py
Original file line number Diff line number Diff line change
@@ -231,7 +231,7 @@ def to_list(self) -> List[Dict[str, Any]]:
try:
coeff = complex_to_list(complex(v))
except TypeError:
assert type(Expr(v)) == Expr
assert isinstance(Expr(v), Expr)
coeff = str(v)
ret.append(
{
2 changes: 1 addition & 1 deletion pytket/pytket/wasm/wasm.py
Original file line number Diff line number Diff line change
@@ -125,7 +125,7 @@ def check(self) -> None:
] * entry.return_count
else:
raise ValueError(
f"Only parameter and return values of "
"Only parameter and return values of "
+ f"i{self._int_size} types are"
+ f" allowed, found type: {entry.return_type}"
)
4 changes: 2 additions & 2 deletions pytket/pytket/zx/tensor_eval.py
Original file line number Diff line number Diff line change
@@ -34,7 +34,7 @@

try:
import quimb.tensor as qtn # type: ignore
except ModuleNotFoundError as err:
except ModuleNotFoundError:
warnings.warn(
'Missing package for tensor evaluation of ZX diagrams. Run "pip '
"install 'pytket[ZX]'\" to install the optional dependencies."
@@ -200,7 +200,7 @@ def _tensor_from_basic_diagram(diag: ZXDiagram) -> np.ndarray:
net.full_simplify_(seq="ADCR")
res_ten = net.contract(output_inds=res_indices, optimize="greedy")
result: np.ndarray
if type(res_ten) == qtn.Tensor:
if isinstance(res_ten, qtn.Tensor):
result = res_ten.data
else:
# Scalar
10 changes: 10 additions & 0 deletions pytket/ruff.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
exclude = ["pytket/_tket"]

target-version = "py313"

lint.ignore = [
"E731", # OK to assign to lambdas
"E741", # Allow variable names like "l"
"F401", # Allow importing unused names in init files
"F403", # Allow wildcard imports in init files
]
1 change: 0 additions & 1 deletion pytket/setup.py
Original file line number Diff line number Diff line change
@@ -138,7 +138,6 @@ def run(self):
shutil.rmtree(extdir)
os.makedirs(extdir)

nix_ldflags = os.environ["NIX_LDFLAGS"].split()
build_inputs = os.environ["propagatedBuildInputs"].split()

binders = [f"{l}/lib" for l in build_inputs if "-binders" in l]
1 change: 0 additions & 1 deletion pytket/tests/add_circuit_test.py
Original file line number Diff line number Diff line change
@@ -13,7 +13,6 @@
# limitations under the License.

from pytket import Circuit, OpType
import pytest


def gen_bell_state(reset_start: bool = False) -> Circuit:
1 change: 0 additions & 1 deletion pytket/tests/ansatz_sequence_test.py
Original file line number Diff line number Diff line change
@@ -14,7 +14,6 @@

from typing import Dict, Tuple, List
import numpy as np
import pytest
from pytket import Circuit
from pytket.pauli import Pauli, QubitPauliString
from pytket.circuit import fresh_symbol, OpType, Qubit
14 changes: 7 additions & 7 deletions pytket/tests/backendinfo_test.py
Original file line number Diff line number Diff line change
@@ -64,12 +64,12 @@ def test_gate_errors_options() -> None:
bi = BackendInfo(
"name", "device_name", "version", SquareGrid(3, 4), {OpType.CX, OpType.Rx}
)
assert bi.all_node_gate_errors == None
assert bi.all_edge_gate_errors == None
assert bi.all_readout_errors == None
assert bi.averaged_node_gate_errors == None
assert bi.averaged_edge_gate_errors == None
assert bi.averaged_readout_errors == None
assert bi.all_node_gate_errors is None
assert bi.all_edge_gate_errors is None
assert bi.all_readout_errors is None
assert bi.averaged_node_gate_errors is None
assert bi.averaged_edge_gate_errors is None
assert bi.averaged_readout_errors is None

example_node_error = {Node(0): {OpType.H: 0.3, OpType.X: 0.4}}
example_averaged_readout_errors = {Node(1): 0.4, Node(0): 0.3}
@@ -177,7 +177,7 @@ def test_fullyconnected() -> None:
"name", "device_name", "version", 10, {OpType.CX, OpType.Rx}
)
assert bi.n_nodes == 10
assert type(bi.architecture) == FullyConnected
assert isinstance(bi.architecture, FullyConnected)

# https://github.com/CQCL/tket/issues/390
d = bi.to_dict()
4 changes: 2 additions & 2 deletions pytket/tests/boxes/phase_poly_box_test.py
Original file line number Diff line number Diff line change
@@ -69,8 +69,8 @@ def test_phase_polybox_II() -> None:
c = Circuit(1, 1)
n_qb = 1
qubit_indices = {Qubit(0): 0}
phase_polynomial: PhasePolynomialDict = {(True,): 0.1, (True,): 0.3}
phase_polynomial_alt: PhasePolynomialSequence = [([True], 0.1), ([True], 0.3)]
phase_polynomial: PhasePolynomialDict = {(True,): 0.3}
phase_polynomial_alt: PhasePolynomialSequence = [([True], 0.3)]
linear_transformation = np.array([[1]])
p_box = PhasePolyBox(n_qb, qubit_indices, phase_polynomial, linear_transformation)
p_box_alt = PhasePolyBox(
2 changes: 0 additions & 2 deletions pytket/tests/characterisation_test.py
Original file line number Diff line number Diff line change
@@ -22,8 +22,6 @@
)
from pytket.pauli import Pauli, QubitPauliString, QubitPauliTensor

import pytest


def test_single_cycle_single_frame_randomisation() -> None:
test_fr = FrameRandomisation(
37 changes: 18 additions & 19 deletions pytket/tests/circuit_test.py
Original file line number Diff line number Diff line change
@@ -76,8 +76,7 @@

import numpy as np
from scipy.linalg import block_diag
import sympy
from sympy import Symbol, pi, sympify, functions, Expr, exp
from sympy import Symbol, pi, sympify, Expr, exp
import math
from math import sqrt

@@ -1002,7 +1001,7 @@ def test_commands_of_type() -> None:
def test_empty_circuit() -> None:
circ = Circuit(0)
circt_dict = circ.to_dict()
assert type(circt_dict) == type({})
assert isinstance(circt_dict, dict)
assert len(circt_dict) > 0
assert Circuit(0) == Circuit(0)

@@ -1133,13 +1132,13 @@ def test_clifford_checking() -> None:
cx = c.get_commands()[1].op
assert cx.is_clifford_type()
t = c.get_commands()[2].op
assert t.is_clifford_type() == False
assert not t.is_clifford_type()
rz1 = c.get_commands()[3].op
assert rz1.is_clifford_type() == False
assert not rz1.is_clifford_type()
rz2 = c.get_commands()[4].op
assert rz2.is_clifford_type() == False
assert not rz2.is_clifford_type()
m = c.get_commands()[5].op
assert m.is_clifford_type() == False
assert not m.is_clifford_type()


def test_clifford_evaluation() -> None:
@@ -1150,7 +1149,7 @@ def test_clifford_evaluation() -> None:
iswap = c.get_commands()[1].op
assert iswap.is_clifford()
rz = c.get_commands()[2].op
assert rz.is_clifford() == False
assert not rz.is_clifford()


def test_getting_registers() -> None:
@@ -1423,8 +1422,8 @@ def test_add_circbox_with_registers() -> None:
c0.CCX(breg[0], breg[1], breg[2])
cbox = CircBox(c0)
c = Circuit()
xreg = c.add_q_register("x", 3)
yreg = c.add_q_register("y", 2)
c.add_q_register("x", 3)
c.add_q_register("y", 2)
zreg = c.add_q_register("z", 3)
wreg = c.add_q_register("w", 2)
for qb in c.qubits:
@@ -1442,16 +1441,16 @@ def test_add_circbox_with_registers() -> None:

def test_add_circbox_with_mixed_registers() -> None:
c0 = Circuit()
c0_qreg1 = c0.add_q_register("q1", 2)
c0_qreg2 = c0.add_q_register("q2", 3)
c0_creg1 = c0.add_c_register("c1", 4)
c0_creg2 = c0.add_c_register("c2", 5)
c0.add_q_register("q1", 2)
c0.add_q_register("q2", 3)
c0.add_c_register("c1", 4)
c0.add_c_register("c2", 5)
cbox = CircBox(c0)
c = Circuit()
c_qreg1 = c.add_q_register("q1", 2)
c_qreg2 = c.add_q_register("q2", 3)
c_creg1 = c.add_c_register("c1", 4)
c_creg2 = c.add_c_register("c2", 5)
c.add_q_register("q1", 2)
c.add_q_register("q2", 3)
c.add_c_register("c1", 4)
c.add_c_register("c2", 5)

c.add_circbox_with_regmap(
cbox, qregmap={"q1": "q1", "q2": "q2"}, cregmap={"c1": "c1", "c2": "c2"}
@@ -1537,7 +1536,7 @@ def test_bad_circbox() -> None:
b = circ.add_c_register("b", 5)
c = circ.add_c_register("c", 5)
circ.add_classicalexpbox_register(a | b, c.to_list())
with pytest.raises(RuntimeError) as e:
with pytest.raises(RuntimeError):
_ = CircBox(circ)


27 changes: 13 additions & 14 deletions pytket/tests/classical_test.py
Original file line number Diff line number Diff line change
@@ -29,7 +29,6 @@
BitRegister,
QubitRegister,
Bit,
UnitID,
Circuit,
OpType,
Qubit,
@@ -358,10 +357,10 @@ def test_wasm_12() -> None:


def test_wasm_handler() -> None:
w = wasm.WasmFileHandler("testfile.wasm")
_ = wasm.WasmFileHandler("testfile.wasm")

with pytest.raises(ValueError):
w2 = wasm.WasmFileHandler("notexistingfile.wasm")
_ = wasm.WasmFileHandler("notexistingfile.wasm")


def test_wasm_function_check() -> None:
@@ -452,7 +451,7 @@ def test_wasm_function_check_8() -> None:
c = Circuit(20, 20)
c0 = c.add_c_register("c0", 32)
c1 = c.add_c_register("c1", 4)
c2 = c.add_c_register("c2", 5)
c.add_c_register("c2", 5)

c.add_wasm_to_reg("add_something", w, [c0], [c1])
assert c.depth() == 1
@@ -463,7 +462,7 @@ def test_wasm_function_check_9() -> None:
c = Circuit(20, 20)
c0 = c.add_c_register("c0", 53)
c1 = c.add_c_register("c1", 4)
c2 = c.add_c_register("c2", 5)
c.add_c_register("c2", 5)

with pytest.raises(ValueError):
c.add_wasm_to_reg("add_something", w, [c0], [c1])
@@ -487,7 +486,7 @@ def test_add_wasm_to_reg() -> None:

def test_wasmfilehandler_without_init() -> None:
with pytest.raises(ValueError):
w = wasm.WasmFileHandler("testfile-without-init.wasm")
_ = wasm.WasmFileHandler("testfile-without-init.wasm")


def test_wasmfilehandler_without_init_no_check() -> None:
@@ -507,58 +506,58 @@ def test_wasmfilehandler_without_init_no_check() -> None:

def test_wasmfilehandler_invalid_file_1_c_32() -> None:
with pytest.raises(ValueError):
w = wasm.WasmFileHandler(
_ = wasm.WasmFileHandler(
"wasm-generation/wasmfromcpp/invalid-with-print-1-emcc.wasm", int_size=32
)


def test_wasmfilehandler_invalid_file_1_c_64() -> None:
with pytest.raises(ValueError):
w = wasm.WasmFileHandler(
_ = wasm.WasmFileHandler(
"wasm-generation/wasmfromcpp/invalid-with-print-1-emcc.wasm", int_size=64
)


def test_wasmfilehandler_invalid_file_1_e_32() -> None:
with pytest.raises(ValueError):
w = wasm.WasmFileHandler(
_ = wasm.WasmFileHandler(
"wasm-generation/wasmfromcpp/invalid-with-print-2-emcc.wasm", int_size=32
)


def test_wasmfilehandler_invalid_file_1_e_64() -> None:
with pytest.raises(ValueError):
w = wasm.WasmFileHandler(
_ = wasm.WasmFileHandler(
"wasm-generation/wasmfromcpp/invalid-with-print-2-emcc.wasm", int_size=64
)


def test_wasmfilehandler_invalid_file_1_c_32_no_check() -> None:
w = wasm.WasmFileHandler(
_ = wasm.WasmFileHandler(
"wasm-generation/wasmfromcpp/invalid-with-print-1-emcc.wasm",
int_size=32,
check_file=False,
)


def test_wasmfilehandler_invalid_file_1_c_64_no_check() -> None:
w = wasm.WasmFileHandler(
_ = wasm.WasmFileHandler(
"wasm-generation/wasmfromcpp/invalid-with-print-1-emcc.wasm",
int_size=64,
check_file=False,
)


def test_wasmfilehandler_invalid_file_1_e_32_no_check() -> None:
w = wasm.WasmFileHandler(
_ = wasm.WasmFileHandler(
"wasm-generation/wasmfromcpp/invalid-with-print-2-emcc.wasm",
int_size=32,
check_file=False,
)


def test_wasmfilehandler_invalid_file_1_e_64_no_check() -> None:
w = wasm.WasmFileHandler(
_ = wasm.WasmFileHandler(
"wasm-generation/wasmfromcpp/invalid-with-print-2-emcc.wasm",
int_size=64,
check_file=False,
Loading