Skip to content

Commit b74bf3b

Browse files
petercorkeclaude
andauthored
chore: format with ruff at line length 88 (#245)
Set line-length to 88 as in RTB, bdsim and sphinx-pyrunblock, add [tool.ruff.format], ignore E501 (the formatter does not wrap strings or comments), and run ruff format over src and tests (46 files). Moved three type: ignore comments onto the lines mypy reports. AGENTS.md says to use ruff. Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
1 parent afc813b commit b74bf3b

48 files changed

Lines changed: 254 additions & 180 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎AGENTS.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,12 @@ description and ask first.
5050
ignores as `# type: ignore[code]` with the specific error code; unused ignores are reported.
5151
Import from the defining submodule (for example `machinevisiontoolbox.base.graphics`), not
5252
through the package's star imports, which mypy cannot follow.
53+
- Formatting and linting: `ruff`, configured in `pyproject.toml` (line length 88, as in RTB,
54+
bdsim and sphinx-pyrunblock). Format with `ruff format src tests` and lint with
55+
`ruff check src tests`; do not use `black`. Format only the files you change, so that a
56+
feature PR carries no unrelated reformatting. CI does not run ruff yet, but the tree is
57+
formatted, so `ruff format --check src tests` passes. `E501` is ignored: the formatter
58+
does not wrap long strings or comments.
5359
- New and changed code uses modern annotation syntax: `X | Y`, `X | None`, `list[X]`,
5460
`dict[K, V]`, not `Union`, `Optional`, `List` or `Dict`. For array arguments use `ArrayLike`
5561
(or `ArrayLike2` for a 2-element value) from `machinevisiontoolbox.mvtb_types`, and put the

‎pyproject.toml‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -119,12 +119,20 @@ testpaths = ["tests"]
119119
addopts = "--tb=short"
120120

121121
[tool.ruff]
122-
line-length = 120
122+
# 88 matches RTB, bdsim and sphinx-pyrunblock
123+
line-length = 88
123124
# the notebooks that reproduce the book code have a bare except in their setup cell
124125
extend-exclude = ["tests/RVC"]
125126

126127
[tool.ruff.lint]
127128
select = ["E", "F", "I", "BLE", "S110"]
129+
# the formatter wraps code but not long strings or comments, so E501 would only
130+
# report what `ruff format` cannot fix
131+
ignore = ["E501"]
132+
133+
[tool.ruff.format]
134+
quote-style = "double"
135+
indent-style = "space"
128136

129137
[tool.ruff.lint.per-file-ignores]
130138
# these files re-export their submodules with star imports on purpose, so that

‎src/machinevisiontoolbox/BagOfWords.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -359,7 +359,7 @@ def _remove_stopwords(self, verbose: bool = True) -> None:
359359

360360
stopfeatures = freq[stopwords].sum()
361361
print(
362-
f"Removing {stopfeatures} features ({stopfeatures/len(self.words) * 100:.1f}%) associated with {self.nstopwords} most frequent words"
362+
f"Removing {stopfeatures} features ({stopfeatures / len(self.words) * 100:.1f}%) associated with {self.nstopwords} most frequent words"
363363
)
364364

365365
k = np.full(index.shape, False, dtype=bool)

‎src/machinevisiontoolbox/BundleAdjust.py‎

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -722,14 +722,12 @@ def build_linear_system(self, x: np.ndarray) -> tuple[Any, Any, Any]:
722722

723723
# loop over views
724724
for view in self.views:
725-
726725
# get camera pose
727726
k = view.index
728727
X = x[k : k + 6]
729728

730729
# loop over all points viewed from this camera
731730
for landmark, edge in view.incidences():
732-
733731
k = landmark.index
734732
P = x[k : k + 3] # get landmark position
735733

@@ -942,14 +940,12 @@ def getresidual(self, x: np.ndarray | None = None) -> np.ndarray:
942940
residual = np.zeros((self.nviews, self.nlandmarks))
943941
# loop over views
944942
for view in self.views:
945-
946943
# get view pose
947944
k = view.index
948945
X = x[k : k + 6]
949946

950947
# loop over all points viewed from this camera
951948
for landmark, edge in view.incidences():
952-
953949
k = landmark.index
954950
P = x[k : k + 3] # get landmark position
955951

‎src/machinevisiontoolbox/Camera.py‎

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -120,9 +120,9 @@ def __init__(
120120
self.pp = pp
121121

122122
if sensorsize is not None:
123-
assert (
124-
self._imagesize is not None
125-
), "imagesize must be set when sensorsize is given"
123+
assert self._imagesize is not None, (
124+
"imagesize must be set when sensorsize is given"
125+
)
126126
self._rhou = sensorsize[0] / self._imagesize[0]
127127
self._rhov = sensorsize[1] / self._imagesize[1]
128128
else:
@@ -1255,7 +1255,9 @@ def _add_collection3d_compat(collection, *args, **kwargs):
12551255
CameraBase._plot_frustum(ax, pose, scale, alpha)
12561256

12571257
elif shape == "camera":
1258-
CameraBase._plot_camera_icon(ax, pose, scale, solid, color, alpha, label)
1258+
CameraBase._plot_camera_icon(
1259+
ax, pose, scale, solid, color, alpha, label
1260+
)
12591261

12601262
if frame is True:
12611263
pose.plot(
@@ -2989,7 +2991,11 @@ def points2E(
29892991
method_int = None
29902992

29912993
E, mask = cv2.findEssentialMat(
2992-
points1=p1.T, points2=p2.T, cameraMatrix=K, method=method_int, **kwargs # type: ignore[arg-type]
2994+
points1=p1.T,
2995+
points2=p2.T,
2996+
cameraMatrix=K,
2997+
method=method_int, # type: ignore[arg-type]
2998+
**kwargs,
29932999
)
29943000
if mask is not None:
29953001
mask = mask.flatten().astype(bool)

‎src/machinevisiontoolbox/ImageCore.py‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -344,7 +344,11 @@ def __init__(
344344
image = image[:, :, 0] # squeeze out singleton plane
345345

346346
if kwargs:
347-
image = convert(image, dtype=dtype if defer_dtype_to_convert else None, **kwargs) # type: ignore[arg-type]
347+
image = convert(
348+
image,
349+
dtype=dtype if defer_dtype_to_convert else None, # type: ignore[arg-type]
350+
**kwargs,
351+
)
348352

349353
# assign the image to the object, copying if requested
350354
if copy:
@@ -497,7 +501,9 @@ def __iter__(self) -> Iterator["Image"]:
497501
"""Iterate over image planes."""
498502
return self.planes()
499503

500-
def __array__(self, dtype: Dtype | None = None, copy: bool | None = None) -> np.ndarray:
504+
def __array__(
505+
self, dtype: Dtype | None = None, copy: bool | None = None
506+
) -> np.ndarray:
501507
"""
502508
Convert to a plain NumPy array
503509

‎src/machinevisiontoolbox/ImageIO.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -774,7 +774,9 @@ def on_click(self, event: Any) -> None:
774774

775775
if title is None:
776776
if self.name is not None and right.name is not None:
777-
title = f"{os.path.basename(self.name)} / {os.path.basename(right.name)}"
777+
title = (
778+
f"{os.path.basename(self.name)} / {os.path.basename(right.name)}"
779+
)
778780
else:
779781
title = "Stereo Pair"
780782
set_window_title(fig, title)

‎src/machinevisiontoolbox/ImagePointFeatures.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1583,7 +1583,7 @@ def __str__(self) -> str:
15831583
s = f"{len(self)} matches"
15841584
if self._inliers is not None:
15851585
ninlier = sum(self._inliers)
1586-
s += f", with {ninlier} ({ninlier/len(self)*100:.1f}%) inliers"
1586+
s += f", with {ninlier} ({ninlier / len(self) * 100:.1f}%) inliers"
15871587
return s
15881588

15891589
def __repr__(self) -> str:

‎src/machinevisiontoolbox/ImageProcessing.py‎

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -671,9 +671,7 @@ def apply_mode(threshold):
671671

672672
fig, axs = plt.subplots(1, 2, figsize=(10, 5))
673673
plt.subplots_adjust(bottom=0.1 if _use_ipywidgets else 0.25)
674-
set_window_title(
675-
fig, "Interactive Image Threshold" if title is None else title
676-
)
674+
set_window_title(fig, "Interactive Image Threshold" if title is None else title)
677675

678676
im = axs[0].imshow(apply_mode(t), cmap="gray")
679677
if mode == "binary":
@@ -1332,12 +1330,14 @@ def paste(
13321330

13331331
# only fg is valid
13341332
fg_mask = cv2.bitwise_and(
1335-
src1=fg_set, src2=cv2.bitwise_xor(src1=bg_set, src2=1) # type: ignore[call-overload]
1333+
src1=fg_set,
1334+
src2=cv2.bitwise_xor(src1=bg_set, src2=1), # type: ignore[call-overload]
13361335
)
13371336

13381337
# only bg is valid
13391338
bg_mask = cv2.bitwise_and(
1340-
src1=cv2.bitwise_xor(src1=fg_set, src2=1), src2=bg_set # type: ignore[call-overload]
1339+
src1=cv2.bitwise_xor(src1=fg_set, src2=1), # type: ignore[call-overload]
1340+
src2=bg_set,
13411341
)
13421342

13431343
# merge them
@@ -1414,7 +1414,6 @@ def invert(self) -> Self:
14141414

14151415

14161416
if __name__ == "__main__":
1417-
14181417
pass
14191418

14201419
# tests = Path(__file__).parent.parent.parent / "tests"

‎src/machinevisiontoolbox/ImageRegionFeatures.py‎

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -188,11 +188,7 @@ def __init__(self, image: Any = None, **kwargs: Any) -> None:
188188
# change. Logged as its own issue (#54), not something this
189189
# compat fix can address.
190190
# -----------------------------------------------------------------
191-
lrtb = (
192-
np.zeros((0, 4), dtype=int)
193-
if len(bboxes) == 0
194-
else np.array(bboxes)
195-
)
191+
lrtb = np.zeros((0, 4), dtype=int) if len(bboxes) == 0 else np.array(bboxes)
196192
lrtb[:, 2:] = lrtb[:, 0:2] + lrtb[:, 2:] # convert to lrtb
197193
self._bboxes = lrtb
198194

@@ -282,7 +278,7 @@ def __str__(self) -> str:
282278
if len(self) != 1:
283279
return f"MSER features, {len(self)} regions"
284280
else:
285-
s = f"MSER feature: u: {self._bboxes[0,0]} - {self._bboxes[0,2]}, v: {self._bboxes[0,1]} - {self._bboxes[0,3]}"
281+
s = f"MSER feature: u: {self._bboxes[0, 0]} - {self._bboxes[0, 2]}, v: {self._bboxes[0, 1]} - {self._bboxes[0, 3]}"
286282
return s
287283

288284
def __repr__(self) -> str:

0 commit comments

Comments
 (0)