Skip to content

Commit

Permalink
Format codebase with black
Browse files Browse the repository at this point in the history
Fixes #411
  • Loading branch information
mhostetter committed Dec 10, 2022
1 parent 253ce89 commit c1fc70c
Show file tree
Hide file tree
Showing 45 changed files with 1,189 additions and 548 deletions.
7 changes: 6 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
{
"python.testing.pytestArgs": ["-c=pyproject.toml", "tests/"],
"python.testing.pytestArgs": [
"-c=pyproject.toml",
"tests/"
],
"python.testing.unittestEnabled": false,
"python.testing.pytestEnabled": true,
"python.linting.pylintEnabled": true,
"python.linting.enabled": true,
"python.formatting.provider": "black",
"editor.formatOnSave": true,
}
4 changes: 2 additions & 2 deletions benchmarks/test_fec.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ def setup_method(self):
self.C_sys = self.code_sys.encode(self.M)
self.C_non_sys = self.code_non_sys.encode(self.M)

self.C_sys[:,0:self.code_sys.t] += self.GF.Random(low=1) # Add t bit errors
self.C_non_sys[:,0:self.code_non_sys.t] += self.GF.Random(low=1) # Add t bit errors
self.C_sys[:, 0 : self.code_sys.t] += self.GF.Random(low=1) # Add t bit errors
self.C_non_sys[:, 0 : self.code_non_sys.t] += self.GF.Random(low=1) # Add t bit errors

def test_encode_systematic(self, benchmark):
benchmark(self.code_sys.encode, self.M)
Expand Down
2 changes: 1 addition & 1 deletion benchmarks/test_field_arithmetic.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ def setup_method(self):
np.random.seed(123456789)
self.x = self.GF.Random(self.N)
self.y = self.GF.Random(self.N, low=1)
self.z = np.random.randint(0, 2*self.GF.order, self.N)
self.z = np.random.randint(0, 2 * self.GF.order, self.N)

def test_add(self, benchmark):
benchmark(np.add, self.x, self.y)
Expand Down
24 changes: 17 additions & 7 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import inspect
import os
import sys

sys.path.insert(0, os.path.abspath("."))
sys.path.insert(0, os.path.abspath(".."))

Expand All @@ -24,6 +25,7 @@
# confuses Sphinx when parsing overloaded functions. When not building the documentation, the @set_module("galois")
# decorator works as intended.
import builtins

setattr(builtins, "__sphinx_build__", True)

import galois
Expand Down Expand Up @@ -124,15 +126,15 @@
"social": [
{
"icon": "fontawesome/brands/github",
"link": "https://github.com/mhostetter/galois"
"link": "https://github.com/mhostetter/galois",
},
{
"icon": "fontawesome/brands/python",
"link": "https://pypi.org/project/galois/"
"link": "https://pypi.org/project/galois/",
},
{
"icon": "fontawesome/brands/twitter",
"link": "https://twitter.com/galois_py"
"link": "https://twitter.com/galois_py",
},
],
"edit_uri": "",
Expand Down Expand Up @@ -172,7 +174,7 @@
],
"analytics": {
"provider": "google",
"property": "G-4FW9NCNFZH"
"property": "G-4FW9NCNFZH",
},
"version_dropdown": True,
"version_json": "../versions.json",
Expand Down Expand Up @@ -283,10 +285,15 @@
# -- Monkey-patching ---------------------------------------------------------

SPECIAL_MEMBERS = [
"__repr__", "__str__", "__int__",
"__call__", "__len__", "__eq__",
"__repr__",
"__str__",
"__int__",
"__call__",
"__len__",
"__eq__",
]


def autodoc_skip_member(app, what, name, obj, skip, options):
"""
Instruct autodoc to skip members that are inherited from np.ndarray.
Expand Down Expand Up @@ -342,6 +349,7 @@ def autodoc_process_bases(app, name, obj, options, bases):
# class properties may be created using `@classmethod @property def foo(cls): return "bar"`. In earlier versions, they must be created
# in the metaclass, however Sphinx cannot find or document them. Adding this workaround allows Sphinx to document them.


def classproperty(obj):
ret = classmethod(obj)
ret.__doc__ = obj.__doc__
Expand All @@ -363,7 +371,9 @@ def classproperty(obj):
setattr(galois._domains._meta.ArrayMeta, p, ArrayMeta_property)


FieldArrayMeta_properties = [member for member in dir(galois.FieldArray) if inspect.isdatadescriptor(getattr(type(galois.FieldArray), member, None))]
FieldArrayMeta_properties = [
member for member in dir(galois.FieldArray) if inspect.isdatadescriptor(getattr(type(galois.FieldArray), member, None))
]
for p in FieldArrayMeta_properties:
# Fetch the class properties from the private metaclasses
if p in ArrayMeta_properties:
Expand Down
8 changes: 4 additions & 4 deletions docs/ipython_with_reprs.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ def run(self) -> List[docutils.nodes.Node]:
ws = " "
new_lines = [
".. md-tab-set::",
""
"",
]

for element_repr, title in zip(element_reprs, titles):
Expand All @@ -58,15 +58,15 @@ def run(self) -> List[docutils.nodes.Node]:
else:
items = first_code_line.rsplit(")", 1)
assert len(items) == 2
items.insert(1, f", repr=\"{element_repr}\")")
items.insert(1, f', repr="{element_repr}")')
new_first_code_line = "".join(items)
new_lines += [
f"{ws}{ws}{ws}{new_first_code_line}",
]
else:
new_lines += [
f"{ws}{ws}{ws}@suppress",
f"{ws}{ws}{ws}{field}.repr(\"{element_repr}\")",
f'{ws}{ws}{ws}{field}.repr("{element_repr}")',
f"{ws}{ws}{ws}{first_code_line}",
]

Expand All @@ -80,7 +80,7 @@ def run(self) -> List[docutils.nodes.Node]:
new_lines += [
f"{ws}{ws}{ws}@suppress",
f"{ws}{ws}{ws}{field}.repr()",
""
"",
]

self.state_machine.insert_input(new_lines, self.state_machine.input_lines.source(0))
Expand Down
11 changes: 8 additions & 3 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
[build-system]
requires = [
"setuptools>=62",
"setuptools >= 62",
"wheel",
"setuptools_scm[toml]>=6.2"
"setuptools_scm[toml] >= 6.2"
]

[project]
Expand Down Expand Up @@ -49,7 +49,8 @@ dynamic = ["version"]

[project.optional-dependencies]
dev = [
"pylint>=2.14",
"pylint >= 2.14",
"black >= 22.8.0",
"pytest",
"pytest-cov[toml]",
"pytest-xdist",
Expand Down Expand Up @@ -104,6 +105,10 @@ disable = [
]
min-similarity-lines = 100

[tool.black]
line-length = 140
exclude = "tests/"

[tool.pytest.ini_options]
minversion = "6.2"
addopts = "-vv --showlocals"
Expand Down
13 changes: 10 additions & 3 deletions scripts/create_conway_polys_database.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,15 @@
cursor = conn.cursor()

cursor.execute(
"""
"""
CREATE TABLE polys (
characteristic INTEGER NOT NULL,
degree INTEGER NOT NULL,
coefficients TEXT NOT NULL,
PRIMARY KEY (characteristic, degree)
)
""")
"""
)

text = requests.get(POLY_TEXT_FILE_URL).text
for line in text.splitlines():
Expand All @@ -35,7 +36,13 @@
characteristic, degree, coefficients = line.split(",", maxsplit=2)
print(f"Conway polynomial for GF({characteristic}^{degree})")

cursor.execute("INSERT INTO polys (characteristic, degree, coefficients) VALUES (?,?,?)", (int(characteristic), int(degree), coefficients))
cursor.execute(
"""
INSERT INTO polys (characteristic, degree, coefficients)
VALUES (?,?,?)
""",
(int(characteristic), int(degree), coefficients),
)

conn.commit()
conn.close()
42 changes: 21 additions & 21 deletions scripts/generate_fec_test_vectors.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def to_int(field, element):
if isinstance(element, sage.rings.finite_rings.element_pari_ffelt.FiniteFieldElement_pari_ffelt):
coeffs = element._vector_()
characteristic = int(field.characteristic())
return sum(int(c)*characteristic**i for i, c in enumerate(coeffs))
return sum(int(c) * characteristic**i for i, c in enumerate(coeffs))
try:
return int(element)
except TypeError:
Expand All @@ -38,7 +38,7 @@ def to_field(field, integer):
for d in range(degree - 1, -1, -1):
q = integer // characteristic**d
l += [f"{q}*x^{d}"]
integer -= q*characteristic**d
integer -= q * characteristic**d
return field(" + ".join(l))
try:
return field.fetch_int(int(integer))
Expand All @@ -57,7 +57,7 @@ def _convert_sage_generator_matrix(F, G, n, k, systematic=True):
G = matrix(G).numpy()
for i in range(G.shape[0]):
for j in range(G.shape[1]):
G[i,j] = to_int(F, G[i,j])
G[i, j] = to_int(F, G[i, j])
G = G.astype(np.int64)

if systematic:
Expand All @@ -66,9 +66,9 @@ def _convert_sage_generator_matrix(F, G, n, k, systematic=True):
G[:, k:] = np.fliplr(G[:, k:])
else:
for i in range(k):
idxs = np.nonzero(G[i,:])[0]
idxs = np.nonzero(G[i, :])[0]
j, k = idxs[0], idxs[-1]
G[i, j:k+1] = np.flip(G[i, j:k+1])
G[i, j : k + 1] = np.flip(G[i, j : k + 1])

return G

Expand All @@ -78,13 +78,13 @@ def _convert_sage_parity_check_matrix(F, H, n, k):
H = matrix(H).numpy()
for i in range(H.shape[0]):
for j in range(H.shape[1]):
H[i,j] = to_int(F, H[i,j])
H[i, j] = to_int(F, H[i, j])
H = H.astype(np.int64)

for i in range(n - k):
idxs = np.nonzero(H[i,:])[0]
idxs = np.nonzero(H[i, :])[0]
j, k = idxs[0], idxs[-1]
H[i, j:k+1] = np.flip(H[i, j:k+1])
H[i, j : k + 1] = np.flip(H[i, j : k + 1])

if H.size == 0:
# The array shape should be (0, n) not (0, 0)
Expand Down Expand Up @@ -169,16 +169,16 @@ def add_bch_lut(folder, q, m, n, d, alpha=None, c=1, systematic=True, rng=1):
messages = rng.integers(0, q, (N, k), dtype=np.int64)
codewords = np.zeros((N, n), dtype=np.int64)
for i in range(N):
message_ = _convert_to_sage_message(F, messages[i,:], k)
message_ = _convert_to_sage_message(F, messages[i, :], k)
if systematic:
codeword_ = C.encode(message_, "Systematic")
else:
codeword_ = C.encode(message_)
codeword = _convert_sage_codeword(F, codeword_, k, systematic=systematic)
codewords[i,:] = codeword
codewords[i, :] = codeword
dict_["encode"] = {
"messages": messages,
"codewords": codewords
"codewords": codewords,
}

# Add shortened encoding vectors
Expand All @@ -190,18 +190,18 @@ def add_bch_lut(folder, q, m, n, d, alpha=None, c=1, systematic=True, rng=1):
messages[:, 0:s] = 0
codewords = np.zeros((N, n), dtype=np.int64)
for i in range(N):
message_ = _convert_to_sage_message(F, messages[i,:], k)
message_ = _convert_to_sage_message(F, messages[i, :], k)
# print(C, list(range(0, s)))
# CC = C.shortened(list(range(0, s))) # The shortened code
if systematic:
codeword_ = C.encode(message_, "Systematic")
else:
codeword_ = C.encode(message_)
codeword = _convert_sage_codeword(F, codeword_, k, systematic=systematic)
codewords[i,:] = codeword
codewords[i, :] = codeword
dict_["encode_shortened"] = {
"messages": messages[:, s:],
"codewords": codewords[:, s:]
"codewords": codewords[:, s:],
}
else:
dict_["encode_shortened"] = {}
Expand Down Expand Up @@ -252,7 +252,7 @@ def add_reed_solomon_lut(folder, q, n, d, alpha=None, c=1, systematic=True, rng=
alpha = to_field(F, alpha)
else:
assert c == 1
alpha_c = alpha ** c
alpha_c = alpha**c
C = codes.ReedSolomonCode(F, ZZ(n), k, primitive_root=alpha_c)
C_cyclic = codes.CyclicCode(code=C)

Expand Down Expand Up @@ -293,16 +293,16 @@ def add_reed_solomon_lut(folder, q, n, d, alpha=None, c=1, systematic=True, rng=
messages = rng.integers(0, q, (N, k), dtype=np.int64)
codewords = np.zeros((N, n), dtype=np.int64)
for i in range(N):
message_ = _convert_to_sage_message(F, messages[i,:], k)
message_ = _convert_to_sage_message(F, messages[i, :], k)
if systematic:
codeword_ = C_cyclic.encode(message_, "Systematic")
else:
codeword_ = C_cyclic.encode(message_)
codeword = _convert_sage_codeword(F, codeword_, k, systematic=systematic)
codewords[i,:] = codeword
codewords[i, :] = codeword
dict_["encode"] = {
"messages": messages,
"codewords": codewords
"codewords": codewords,
}

# Add shortened encoding vectors
Expand All @@ -314,18 +314,18 @@ def add_reed_solomon_lut(folder, q, n, d, alpha=None, c=1, systematic=True, rng=
messages[:, 0:s] = 0
codewords = np.zeros((N, n), dtype=np.int64)
for i in range(N):
message_ = _convert_to_sage_message(F, messages[i,:], k)
message_ = _convert_to_sage_message(F, messages[i, :], k)
# print(C, list(range(0, s)))
# CC = C.shortened(list(range(0, s))) # The shortened code
if systematic:
codeword_ = C.encode(message_, "Systematic")
else:
codeword_ = C.encode(message_)
codeword = _convert_sage_codeword(F, codeword_, k, systematic=systematic)
codewords[i,:] = codeword
codewords[i, :] = codeword
dict_["encode_shortened"] = {
"messages": messages[:, s:],
"codewords": codewords[:, s:]
"codewords": codewords[:, s:],
}
else:
dict_["encode_shortened"] = {}
Expand Down

0 comments on commit c1fc70c

Please sign in to comment.