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

pylint - partial fix up #212

Merged
merged 9 commits into from
Nov 4, 2024
16 changes: 8 additions & 8 deletions dev_tools/.pylintrc
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,16 @@ output-format=colorized
score=no
reports=no
enable=
# anomalous-backslash-in-string, # TODO: #210 - enable and fix
anomalous-backslash-in-string,
assert-on-tuple,
bad-indentation,
bad-option-value,
bad-reversed-sequence,
bad-super-call,
consider-merging-isinstance,
# consider-using-f-string, # TODO: #210 - enable and fix
consider-using-f-string,
continue-in-finally,
# dangerous-default-value, # TODO: #210 - enable and fix
dangerous-default-value,
docstyle,
duplicate-argument-name,
# expression-not-assigned, # TODO: #210 - enable and fix
Expand All @@ -34,7 +34,7 @@ enable=
nonexistent-operator,
not-in-loop,
# pointless-statement, # TODO: #210 - enable and fix
# redefined-builtin, # TODO: #210 - enable and fix
redefined-builtin,
return-arg-in-generator,
return-in-init,
return-outside-function,
Expand All @@ -46,14 +46,14 @@ enable=
undefined-variable,
# unexpected-keyword-arg, # TODO: #210 - enable and fix
unhashable-dict-key,
# unnecessary-pass, # TODO: #210 - enable and fix
unnecessary-pass,
unreachable,
unrecognized-inline-option,
unused-import,
unnecessary-semicolon,
# unused-variable, # TODO: #210 - enable and fix
# unused-wildcard-import, # TODO: #210 - enable and fix
# wildcard-import, # TODO: #210 - enable and fix
unused-variable,
unused-wildcard-import,
wildcard-import,
wrong-or-nonexistent-copyright-notice,
wrong-import-order,
wrong-import-position,
Expand Down
14 changes: 10 additions & 4 deletions examples/fox_in_a_hole/fox_in_a_hole.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,15 +123,15 @@ def take_random_move(self) -> str:

def history_append_state(self):
"""Append the current state into the history."""
self.history.append("State: {}".format(self.state_to_string()))
self.history.append(f"State: {self.state_to_string()}")

def history_append_move(self, move_str):
"""Append the given move into the history."""
self.history.append(move_str)

def history_append_guess(self, guess):
"""Append the given guess into the history."""
self.history.append("Guess: {}".format(guess))
self.history.append(f"Guess: {guess}")

def run(self):
"""Handles the main game-loop of the Fox-in-a-hole game."""
Expand Down Expand Up @@ -162,7 +162,7 @@ def run(self):
self.history_append_state()

if result:
print("\nCongratulations! You won in {} step(s).\n".format(step_nr + 1))
print(f"\nCongratulations! You won in {step_nr + 1} step(s).\n")
self.print_history()
return

Expand Down Expand Up @@ -249,7 +249,13 @@ class QuantumGame(Game):
(QuantumWorld, [QuantumObject]) -> quantum world, list of holes
"""

def __init__(self, number_of_holes: int = 5, iswap: bool = False, qprob:float = 0.5, seed: Optional[int] = None):
def __init__(
self,
number_of_holes: int = 5,
iswap: bool = False,
qprob: float = 0.5,
seed: Optional[int] = None,
):
if iswap:
self.move_operation = PhasedMove()
self.split_operation = PhasedSplit()
Expand Down
8 changes: 4 additions & 4 deletions examples/quantum_chinese_chess/board.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ def from_fen(cls, fen: str = _INITIAL_FEN) -> "Board":
for char in row:
# Add empty board pieces.
if "1" <= char <= "9":
for i in range(int(char)):
for _ in range(int(char)):
name = f"{chr(col)}{row_index}"
chess_board[name] = Piece(
name, SquareState.EMPTY, Type.EMPTY, Color.NA
Expand Down Expand Up @@ -185,7 +185,7 @@ def add_piece_symbol(
for i in range(row * 9, (row + 1) * 9):
# We only print non-zero probabilities
if probabilities[i] >= 1e-3:
board_string.append("{:.1f} ".format(probabilities[i]))
board_string.append(f"{probabilities[i]:.1f} ")
else:
board_string.append(" ")
board_string += "\b" + _RESET + " \n"
Expand Down Expand Up @@ -231,14 +231,14 @@ def add_piece_symbol(
# space + _FULL_SPACE works for mac terminal and gLinux terminal.
if probabilities[i] >= 1e-3:
board_string.append(
"{:.1f} ".format(probabilities[i]) + _FULL_SPACE
f"{probabilities[i]:.1f} " + _FULL_SPACE
)
else:
board_string.append(" " + _FULL_SPACE)
else:
if probabilities[i] >= 1e-3:
# space + space works for sublime terminus.
board_string.append("{:.1f} ".format(probabilities[i]))
board_string.append(f"{probabilities[i]:.1f} ")
else:
board_string.append(" ")
board_string += "\b" + _RESET + _FULL_SPACE + "\n"
Expand Down
8 changes: 4 additions & 4 deletions examples/quantum_chinese_chess/board_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ def test_init_with_default_fen():

# test English print
assert (
re.sub("\\033\[\d{1,2}m", "", board.to_str(TerminalType.MAC_OR_LINUX)).replace(
re.sub(r"\033\[\d{1,2}m", "", board.to_str(TerminalType.MAC_OR_LINUX)).replace(
"\b", ""
)
== """
Expand All @@ -59,7 +59,7 @@ def test_init_with_default_fen():
# test Chinese print
board.set_language(Language.ZH)
assert (
re.sub("\\033\[\d{1,2}m", "", board.to_str(TerminalType.MAC_OR_LINUX)).replace(
re.sub(r"\033\[\d{1,2}m", "", board.to_str(TerminalType.MAC_OR_LINUX)).replace(
"\b", ""
)
== """
Expand Down Expand Up @@ -87,7 +87,7 @@ def test_init_with_specified_fen():

# test English print
assert (
re.sub("\\033\[\d{1,2}m", "", board.to_str(TerminalType.MAC_OR_LINUX)).replace(
re.sub(r"\033\[\d{1,2}m", "", board.to_str(TerminalType.MAC_OR_LINUX)).replace(
"\b", ""
)
== """
Expand All @@ -109,7 +109,7 @@ def test_init_with_specified_fen():
# test Chinese print
board.set_language(Language.ZH)
assert (
re.sub("\\033\[\d{1,2}m", "", board.to_str(TerminalType.MAC_OR_LINUX)).replace(
re.sub(r"\033\[\d{1,2}m", "", board.to_str(TerminalType.MAC_OR_LINUX)).replace(
"\b", ""
)
== """
Expand Down
4 changes: 1 addition & 3 deletions examples/quantum_chinese_chess/chess.py
Original file line number Diff line number Diff line change
Expand Up @@ -463,9 +463,7 @@ def next_move(self) -> Tuple[bool, str]:
all_boards = self.board.board.get_correlated_histogram()
sorted_boards = sorted(all_boards.items(), key=lambda x: x[1], reverse=True)
for board, count in sorted_boards:
print(
"\n ====== With probability ~ {:.1f} ======".format(count / 100.0)
)
print(f"\n ====== With probability ~ {(count / 100.0):.1f} ======")
print(self.board.to_str(self.terminal, None, list(board)))
elif input_str.lower() == "undo":
if self.undo():
Expand Down
2 changes: 1 addition & 1 deletion examples/quantum_chinese_chess/move.py
Original file line number Diff line number Diff line change
Expand Up @@ -592,7 +592,7 @@ def effect(self, *objects) -> Iterator[cirq.Operation]:
# We loop over all quantum path pieces and check if it could be the only
# occupied piece. The fire could be made if it does, otherwise not.
# TODO(): think a more efficient way of implementing this case.
for index, expect_occupied_path_piece in enumerate(quantum_path_pieces_0):
for _, expect_occupied_path_piece in enumerate(quantum_path_pieces_0):
# TODO(): consider specific cases to save the ancilla.
# Add a new ancilla to indicate whether the fire could be made (value = 1 means it could).
capture_ancilla = world._add_ancilla(expect_occupied_path_piece.name)
Expand Down
12 changes: 10 additions & 2 deletions examples/quantum_chinese_chess/move_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,17 @@

from unitary import alpha

from .move import *
from .move import (
CannonFire,
Jump,
MergeJump,
MergeSlide,
Move,
Slide,
SplitJump,
SplitSlide,
)
from .board import Board
from .piece import Piece
from .enums import (
MoveType,
MoveVariant,
Expand Down
2 changes: 1 addition & 1 deletion examples/quantum_rpg/bb84_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ def test_alice_bob():
""".strip()
)
# Reset input and get the keys
state.file = file = io.StringIO()
state.file = io.StringIO()
key = bb84.solve_bb84(state.state_dict["alice"], state.state_dict["bob"])
state.get_user_input = input_helpers.get_user_input_function(
[f"type {key}", "north", "south", "Quit"]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ def go_directions(path: str) -> World:
cur_room = example_world.current_location.label
direction = Direction.parse(cmd)
assert direction is not None
result = example_world.move(direction)
_result = example_world.move(direction)
assert cmd is not None, f"Moving {cmd} in room {cur_room} not valid"
return example_world

Expand All @@ -67,7 +67,7 @@ def test_consistent_exits():
assert nearby_room is not None, f"Missing room {room_name}"
try:
return_exit = nearby_room.exits[OPPOSITE_DIR[direction]]
except KeyError as e:
except KeyError as _e:
raise KeyError(
f"{room_name} does not have a return exit in {direction} to {location.label}"
)
Expand Down
13 changes: 7 additions & 6 deletions examples/quantum_rpg/main_loop.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,10 @@

class Error(Exception):
"""Base class for locally defined exceptions."""
pass


class AmbiguousCommandError(Error):
"""Raised when entered command is ambiguous."""
pass


class Command(enum.Enum):
Expand Down Expand Up @@ -165,9 +163,11 @@ def loop(self, user_input: Optional[Sequence[str]] = None) -> None:
try:
input_cmd = Command.parse(current_input)
except AmbiguousCommandError:
print(f"Ambiguous command '{current_input}'.",
Command.help(),
file=self.file)
print(
f"Ambiguous command '{current_input}'.",
Command.help(),
file=self.file,
)
print_room_description = False
continue
if input_cmd == Command.QUIT:
Expand All @@ -184,7 +184,8 @@ def loop(self, user_input: Optional[Sequence[str]] = None) -> None:
print(npc_class.__name__, file=self.file)
print(
textwrap.indent(npc_class.quantopedia_entry(), " "),
file=self.file)
file=self.file,
)
print(file=self.file)
print_room_description = False
elif input_cmd == Command.LOAD:
Expand Down
10 changes: 5 additions & 5 deletions examples/quantum_rpg/main_loop_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -551,14 +551,14 @@ def test_item_function():

def test_main_quit():
state = game_state.GameState(party=[], user_input=["4"], file=io.StringIO())
loop = main_loop.main(state)
_loop = main_loop.main(state)

assert state.file.getvalue() == _TITLE


def test_main_help():
state = game_state.GameState(party=[], user_input=["3", "4"], file=io.StringIO())
loop = main_loop.main(state)
_loop = main_loop.main(state)

assert (
state.file.getvalue()
Expand All @@ -570,7 +570,7 @@ def test_main_begin():
state = game_state.GameState(
party=[], user_input=["1", "nova", "n", "Quit"], file=io.StringIO()
)
loop = main_loop.main(state)
_loop = main_loop.main(state)

assert (
state.file.getvalue()
Expand Down Expand Up @@ -611,7 +611,7 @@ def test_main_load():
user_input=["2", "classical3;1;Doug#Analyst#1", "Quit"],
file=io.StringIO(),
)
loop = main_loop.main(state)
_loop = main_loop.main(state)

assert (
state.file.getvalue()
Expand All @@ -636,7 +636,7 @@ def test_main_bad_save_file():
user_input=["2", "", "2", "classical3;1;Doug#Analyst#1", "Quit"],
file=io.StringIO(),
)
loop = main_loop.main(state)
_loop = main_loop.main(state)

assert (
state.file.getvalue()
Expand Down
5 changes: 1 addition & 4 deletions examples/quantum_rpg/qaracter.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@

from typing import cast, Dict, List, Optional, Union
import inspect
import sys

import cirq
from unitary import alpha
Expand Down Expand Up @@ -221,9 +220,7 @@ def from_save_file(
# Avoid circular import
from . import classes

class_tuples = inspect.getmembers(
sys.modules["quantum_rpg.classes"], inspect.isclass
)
class_tuples = inspect.getmembers(classes, inspect.isclass)
new_cls = cls
for cls_name, cls_type in class_tuples:
if cls_name == class_name:
Expand Down
24 changes: 12 additions & 12 deletions unitary/alpha/quantum_world.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ def add_object(self, obj: QuantumObject):
self.compiled_qubits[obj.qubit] = [obj.qubit]
else:
self.compiled_qubits[obj.qubit] = []
for qubit_num in range(num_bits(qudit_dim)):
for _ in range(num_bits(qudit_dim)):
new_obj = self._add_ancilla(obj.qubit.name)
self.compiled_qubits[obj.qubit].append(new_obj.qubit)
obj.initial_effect()
Expand Down Expand Up @@ -385,21 +385,21 @@ def _interpret_result(self, result: Union[int, Iterable[int]]) -> int:
return result_list[0]
return result

def unhook(self, object: QuantumObject) -> None:
"""Replace all usages of the given `object` in the circuit with a new ancilla,
def unhook(self, obj: QuantumObject) -> None:
"""Replace all usages of the given object in the circuit with a new ancilla,
so that
- all former operations on `object` will be applied on the new ancilla;
- future operations on `object` start with its new reset value.
- all former operations on `obj` will be applied on the new ancilla;
- future operations on `obj` start with its new reset value.

Note that we don't do force measurement on it, since we don't care about its
current value but just want to reset it.
"""
# Create a new ancilla.
new_ancilla = self._add_ancilla(object.name)
# Replace operations of the given `object` with the new ancilla.
new_ancilla = self._add_ancilla(obj.name)
# Replace operations of the given `obj` with the new ancilla.
qubit_remapping_dict = {
object.qubit: new_ancilla.qubit,
new_ancilla.qubit: object.qubit,
obj.qubit: new_ancilla.qubit,
new_ancilla.qubit: obj.qubit,
}
self.qubit_remapping_dict.append(qubit_remapping_dict)
self.circuit = self.circuit.transform_qubits(
Expand Down Expand Up @@ -716,12 +716,12 @@ def __getitem__(self, name: str) -> QuantumObject:
raise KeyError(f"{name} did not exist in this world.")
return quantum_object

def __to_state_vector__(self, input: tuple) -> np.ndarray:
def __to_state_vector__(self, input_bits: tuple) -> np.ndarray:
"""Converts the given tuple (of length N) to the corresponding state vector (of length 2**N).
e.g. (0, 1) -> [0, 1, 0, 0]
"""
num = len(input)
index = int("".join([str(i) for i in input]), 2)
num = len(input_bits)
index = int("".join([str(i) for i in input_bits]), 2)
state_vector = np.array([0.0] * (2**num))
state_vector[index] = 1.0
return state_vector
2 changes: 0 additions & 2 deletions unitary/alpha/quantum_world_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -946,8 +946,6 @@ def test_density_matrix(simulator, compile_to_qubits):
],
)
def test_measure_entanglement(simulator, compile_to_qubits):
rho_green = np.reshape([0, 0, 0, 1], (2, 2))
rho_red = np.reshape([1, 0, 0, 0], (2, 2))
light1 = alpha.QuantumObject("red1", Light.RED)
light2 = alpha.QuantumObject("green", Light.GREEN)
light3 = alpha.QuantumObject("red2", Light.RED)
Expand Down
Loading