Skip to content

Commit

Permalink
add ruff formatter (#181)
Browse files Browse the repository at this point in the history
## Description
Adapts ruff formatter as in
https://github.com/cda-tum/mqt-qcec/pull/324/files.

## Checklist:

<!---
This checklist serves as a reminder of a couple of things that ensure
your pull request will be merged swiftly.
-->

- [x] The pull request only contains commits that are related to it.
- [x] I have added appropriate tests and documentation.
- [ ] I have made sure that all CI jobs on GitHub pass.
- [x] The pull request introduces no new warnings and follows the
project's style guidelines.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
  • Loading branch information
lucasberent and pre-commit-ci[bot] authored Oct 31, 2023
1 parent 8570e5a commit f69a4e8
Show file tree
Hide file tree
Showing 20 changed files with 235 additions and 59 deletions.
16 changes: 6 additions & 10 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -49,26 +49,22 @@ repos:
- id: rst-directive-colons
- id: rst-inline-touching-normal

# Run ruff (subsumes pyupgrade, isort, flake8+plugins, and more)
# Python linting and formatting using ruff
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.1.1
rev: v0.1.3
hooks:
- id: ruff
args: ["--fix", "--show-fixes"]

# Run code formatting with Black
- repo: https://github.com/psf/black-pre-commit-mirror
rev: 23.10.0 # Keep in sync with blacken-docs
hooks:
- id: black-jupyter
types_or: [python, pyi, jupyter]
- id: ruff-format
types_or: [python, pyi, jupyter]

# Also run Black on examples in the documentation
- repo: https://github.com/adamchainz/blacken-docs
rev: 1.16.0
hooks:
- id: blacken-docs
additional_dependencies:
- black==23.10.0 # keep in sync with black hook
additional_dependencies: [black==23.*]

# Check static types with mypy
- repo: https://github.com/pre-commit/mirrors-mypy
Expand Down
9 changes: 8 additions & 1 deletion docs/source/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,14 @@
"attr": "tooltip",
"property": "tooltip",
}
exclude_patterns = ["_build", "build", "**.ipynb_checkpoints", "Thumbs.db", ".DS_Store", ".env"]
exclude_patterns = [
"_build",
"build",
"**.ipynb_checkpoints",
"Thumbs.db",
".DS_Store",
".env",
]


class CDAStyle(UnsrtStyle):
Expand Down
6 changes: 5 additions & 1 deletion noxfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,11 @@ def _run_tests(
posargs.append("--cov-config=pyproject.toml")

session.install(
"scikit-build-core[pyproject]<0.6", "setuptools_scm", "pybind11", *install_args, env=env
"scikit-build-core[pyproject]<0.6",
"setuptools_scm",
"pybind11",
*install_args,
env=env,
) # TODO: remove upper cap once scikit-build-core is updated
install_arg = f"-ve.[{','.join(_extras)}]"
session.install("--no-build-isolation", install_arg, *install_args, env=env)
Expand Down
20 changes: 9 additions & 11 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -157,9 +157,6 @@ report.exclude_also = [
'if TYPE_CHECKING:',
]

[tool.black]
line-length = 120

[tool.mypy]
files = ["src/mqt", "test/python"]
mypy_path = ["$MYPY_CONFIG_FILE_DIR/src"]
Expand All @@ -177,8 +174,14 @@ ignore_missing_imports = true


[tool.ruff]
include = ["*.py", "*.pyi", "**/pyproject.toml", "*.ipynb"]
select = [
line-length = 120
extend-include = ["*.ipynb"]
src = ["src"]
preview = true
unsafe-fixes = true

[tool.ruff.lint]
extend-select = [
"E", "F", "W", # flake8
"A", # flake8-builtins
"ANN", # flake8-annotations
Expand Down Expand Up @@ -218,16 +221,11 @@ select = [
]
extend-ignore = [
"ANN101", # Missing type annotation for self in method
"ANN102", # Missing type annotation for cls in classmethod
"E501", # Line too long (Black is enough)
"PLR", # Design related pylint codes
]
src = ["src"]
flake8-unused-arguments.ignore-variadic-names = true
isort.required-imports = ["from __future__ import annotations"]
line-length = 120

[tool.ruff.per-file-ignores]
[tool.ruff.lint.per-file-ignores]
"*.pyi" = ["D"] # pydocstyle
"*.ipynb" = [
"D", # pydocstyle
Expand Down
5 changes: 4 additions & 1 deletion scripts/examples/decoding-performance-simulations.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@

from mqt import qecc

code = qecc.Code("../../examples/lp_(4,8)-[[1024,18,nan]]_hx.txt", "../../examples/lp_(4,8)-[[1024,18,nan]]_hz.txt")
code = qecc.Code(
"../../examples/lp_(4,8)-[[1024,18,nan]]_hx.txt",
"../../examples/lp_(4,8)-[[1024,18,nan]]_hz.txt",
)
code.K = 18
outpath = "./dp-sims-bindings.out"

Expand Down
9 changes: 8 additions & 1 deletion scripts/numerics/code_construct/constructHGPcodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,14 @@
np.savetxt(f"./hgp_{qcode.code_params}_hx.txt", qcode.hx, fmt="%d", newline="\n")

# larger code
a1 = pt.array([[(0), (11), (7), (12)], [(1), (8), (1), (8)], [(11), (0), (4), (8)], [(6), (2), (4), (12)]])
a1 = pt.array(
[
[(0), (11), (7), (12)],
[(1), (8), (1), (8)],
[(11), (0), (4), (8)],
[(6), (2), (4), (12)],
]
)
H = a1.to_binary(lift_parameter=10)
qcode = hgp(H, H, compute_distance=True)
qcode.test()
Expand Down
9 changes: 8 additions & 1 deletion scripts/numerics/code_construct/constructLPcodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,14 @@
import numpy as np
from lifted_hgp import LiftedHgp

a1 = pt.array([[(0), (11), (7), (12)], [(1), (8), (1), (8)], [(11), (0), (4), (8)], [(6), (2), (4), (12)]])
a1 = pt.array(
[
[(0), (11), (7), (12)],
[(1), (8), (1), (8)],
[(11), (0), (4), (8)],
[(6), (2), (4), (12)],
]
)

qcode = LiftedHgp(lift_parameter=32, a=a1, b=a1)
if qcode.test:
Expand Down
24 changes: 20 additions & 4 deletions scripts/numerics/code_construct/lifted_hgp.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,12 @@ def identity(n: int) -> npt.NDArray[np.int_]:
class LiftedHgp(css_code):
"""Lifted Hypergraph Product code."""

def __init__(self, lift_parameter: int, a: npt.NDArray[np.int_], b: npt.NDArray[np.int_] | None = None) -> None:
def __init__(
self,
lift_parameter: int,
a: npt.NDArray[np.int_],
b: npt.NDArray[np.int_] | None = None,
) -> None:
"""Generate the lifted hypergraph product of the protographs a and b."""
self.a = a

Expand All @@ -44,7 +49,10 @@ def __init__(self, lift_parameter: int, a: npt.NDArray[np.int_], b: npt.NDArray[

self.lift_parameter = lift_parameter

super().__init__(self.hx_proto.to_binary(lift_parameter), self.hz_proto.to_binary(lift_parameter))
super().__init__(
self.hx_proto.to_binary(lift_parameter),
self.hz_proto.to_binary(lift_parameter),
)

@property
def protograph(self) -> npt.NDArray[np.int_]:
Expand Down Expand Up @@ -77,7 +85,12 @@ def hz2(self) -> npt.NDArray[np.int_]:
class BiasTailoredLiftedProduct(stab_code):
"""Generate the bias-tailored lifted hypergraph product of the protographs a and b. From Roffe's LDPC library."""

def __init__(self, lift_parameter: int, a: npt.NDArray[np.int_], b: npt.NDArray[np.int_] | None = None) -> None:
def __init__(
self,
lift_parameter: int,
a: npt.NDArray[np.int_],
b: npt.NDArray[np.int_] | None = None,
) -> None:
"""Generate the bias-tailored lifted hypergraph product of the protographs a and b."""
lhgp = LiftedHgp(lift_parameter, a, b)

Expand All @@ -89,7 +102,10 @@ def __init__(self, lift_parameter: int, a: npt.NDArray[np.int_], b: npt.NDArray[
temp2 = pt.hstack([pt.zeros(lhgp.hz1_proto.shape), lhgp.hx2_proto])
self.hz_proto = pt.vstack([temp1, temp2])

super().__init__(self.hx_proto.to_binary(lift_parameter), self.hz_proto.to_binary(lift_parameter))
super().__init__(
self.hx_proto.to_binary(lift_parameter),
self.hz_proto.to_binary(lift_parameter),
)

@property
def protograph(self) -> npt.NDArray[np.int_]:
Expand Down
14 changes: 12 additions & 2 deletions scripts/numerics/visualize/visualizeDecodingRuntime.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,13 @@ def runtime_comparison() -> None:
plt.plot(xfinal[i], yfinal[i], "o", label="UFH, p=" + label, color=col)
start = 0
optimized_parameters, pcov = opt.curve_fit(lin_fun, xfinal[i][start:], yfinal[i][start:])
plt.plot(xfinal[i][start:], lin_fun(xfinal[i][start:], *optimized_parameters), "--", color=col, label=r"$O(n)$")
plt.plot(
xfinal[i][start:],
lin_fun(xfinal[i][start:], *optimized_parameters),
"--",
color=col,
label=r"$O(n)$",
)

# general qlpd decoder data
label = "%2.2f" % pers2
Expand All @@ -149,7 +155,11 @@ def runtime_comparison() -> None:
start = 0
optimized_parameters2, pcov = opt.curve_fit(quad_fun, xfinal2[start:], yfinal2[start:])
plt.plot(
xfinal2[start:], quad_fun(xfinal2[start:], *optimized_parameters2), "--", color="green", label=r"$O(n^{2})$"
xfinal2[start:],
quad_fun(xfinal2[start:], *optimized_parameters2),
"--",
color="green",
label=r"$O(n^{2})$",
)

plt.legend()
Expand Down
31 changes: 26 additions & 5 deletions src/mqt/qecc/cc_decoder/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,22 +17,43 @@ def cli() -> None:
default="hexagon",
help="type of the code lattice (hexagon or square_octagon). Default: hexagon",
)
parser.add_argument("--nr_sims", type=int, default=10000, help="the number of simulations to run. Default: 10000")
parser.add_argument(
"--results_dir", type=str, default="./results", help="the directory to save the results to. Default: ./results"
"--nr_sims",
type=int,
default=10000,
help="the number of simulations to run. Default: 10000",
)
parser.add_argument(
"--decoder", type=str, default="maxsat", help="the decoder to use (maxsat or tn). Default: maxsat"
"--results_dir",
type=str,
default="./results",
help="the directory to save the results to. Default: ./results",
)
parser.add_argument(
"--decoder",
type=str,
default="maxsat",
help="the decoder to use (maxsat or tn). Default: maxsat",
)

parser.add_argument(
"--solver", type=str, default="z3", help="maxsat solver to use (path to a executable). Default: z3"
"--solver",
type=str,
default="z3",
help="maxsat solver to use (path to a executable). Default: z3",
)

args = parser.parse_args()

if args.decoder == "maxsat":
decoder.run(args.type, args.distance, args.error_rate, args.nr_sims, args.results_dir, args.solver)
decoder.run(
args.type,
args.distance,
args.error_rate,
args.nr_sims,
args.results_dir,
args.solver,
)
elif args.decoder == "tn":
tn_decoder.run(args.distance, args.error_rate, args.nr_sims, args.results_dir)
else:
Expand Down
4 changes: 4 additions & 0 deletions src/mqt/qecc/cc_decoder/color_code.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,10 @@ def __init__(self, distance: int, lattice_type: LatticeType) -> None:
self.n = len(self.qubits_to_faces)
self.k = self.L.shape[1]

def __hash__(self) -> int:
"""Compute a hash for the color code."""
return hash(self.H.tobytes())

def __eq__(self, other: object) -> bool:
"""Check if two color codes are equal."""
if not isinstance(other, ColorCode):
Expand Down
7 changes: 6 additions & 1 deletion src/mqt/qecc/cc_decoder/comparison/tn_decoder.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,12 @@
from qecsim.models.generic import BitFlipErrorModel


def run(distance: int, error_rate: float, nr_sims: int = 10000, results_dir: str = "./results_tn") -> None:
def run(
distance: int,
error_rate: float,
nr_sims: int = 10000,
results_dir: str = "./results_tn",
) -> None:
"""Run the decoder for the hexagonal color code.
:param distance: distance to run
Expand Down
9 changes: 8 additions & 1 deletion src/mqt/qecc/cc_decoder/hexagonal_color_code.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,14 @@ def construct_layout(self) -> None:

for idx, (x, y) in enumerate(self.ancilla_qubits):
qbts: list[int] = []
for coord in [(x - 1, y + 1), (x - 2, y), (x - 1, y - 1), (x + 1, y - 1), (x + 2, y), (x + 1, y + 1)]:
for coord in [
(x - 1, y + 1),
(x - 2, y),
(x - 1, y - 1),
(x + 1, y - 1),
(x + 2, y),
(x + 1, y + 1),
]:
if coord in coords_to_idx:
qubit_idx = coords_to_idx[coord]
qbts.append(qubit_idx)
Expand Down
30 changes: 27 additions & 3 deletions src/mqt/qecc/cc_decoder/plots.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,14 @@ def plot_ler_vs_distance(code_dict: dict[float, Any], ax: Axes, pers: list[float
ax.set_xlabel(r"Code distance $\it{d}$")


def threshold_fit(variables: tuple[float, float], b0: float, b1: float, b2: float, mu: float, pth: float) -> float:
def threshold_fit(
variables: tuple[float, float],
b0: float,
b1: float,
b2: float,
mu: float,
pth: float,
) -> float:
"""Compute standard fit function for the threshold."""
p, ell = variables
expr = (p - pth) * (ell ** (1 / mu))
Expand Down Expand Up @@ -84,7 +91,13 @@ def calculate_threshold(
ler_eb_ar = ea[:, logical_idx]

if per_array != [] and ax is not None:
ax.errorbar(per_array, ler_arr, yerr=ler_eb_ar, label="d = " + str(distance), fmt="|")
ax.errorbar(
per_array,
ler_arr,
yerr=ler_eb_ar,
label="d = " + str(distance),
fmt="|",
)

ax.legend()
ax.set_xlabel("Physical error rate")
Expand Down Expand Up @@ -250,7 +263,18 @@ def generate_plots_tn(results_dir: Path, results_file: Path) -> None:
def generate_plots_comp(results_dir: Path, results_file: Path) -> None:
"""Generate plots for the comparison of the different solvers."""
fig, ax = plt.subplots(2, figsize=(12, 12))
cols = ["blue", "orange", "green", "red", "purple", "brown", "pink", "gray", "cyan", "olive"]
cols = [
"blue",
"orange",
"green",
"red",
"purple",
"brown",
"pink",
"gray",
"cyan",
"olive",
]
idx = 0
solver_to_col: dict[str, str] = {}
p_to_col: dict[float, str] = {}
Expand Down
7 changes: 6 additions & 1 deletion src/mqt/qecc/cc_decoder/square_octagon_color_code.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,12 @@ def construct_layout(self) -> None:

for idx, (x, y) in enumerate(self.square_ancilla_qubits):
qbts: list[int] = []
for coord in [(x - 1, y - 1), (x + 1, y - 1), (x + 1, y + 1), (x - 1, y + 1)]:
for coord in [
(x - 1, y - 1),
(x + 1, y - 1),
(x + 1, y + 1),
(x - 1, y + 1),
]:
if coord in coords_to_idx:
qubit_idx = coords_to_idx[coord]
qbts.append(qubit_idx)
Expand Down
Loading

0 comments on commit f69a4e8

Please sign in to comment.