Skip to content

Commit

Permalink
style: apply ruff pylint checks
Browse files Browse the repository at this point in the history
  • Loading branch information
kmnhan committed Jul 9, 2024
1 parent 1ce4d36 commit 8265b90
Show file tree
Hide file tree
Showing 16 changed files with 51 additions and 46 deletions.
22 changes: 13 additions & 9 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -170,22 +170,26 @@ select = [
# "ARG",
# "PTH",
# "FIX",
# "PLC",
# "PLE",
# "PLW",
"TRY",
"FLY",
"NPY",
"PERF",
# "FURB",
"FURB",
"RUF",
]
ignore = [
"ICN001", # Import conventions
"TRY003", # Long exception messages
"D100", # Missing docstring in public module
"D101", # Missing docstring in public class
"D102", # Missing docstring in public method
"D103", # Missing docstring in public function
"D104", # Missing docstring in public package
"D105", # Missing docstring in magic method
"PLW2901", # Outer variable overwritten by inner target
"ICN001", # Import conventions
"TRY003", # Long exception messages
"D100", # Missing docstring in public module
"D101", # Missing docstring in public class
"D102", # Missing docstring in public method
"D103", # Missing docstring in public function
"D104", # Missing docstring in public package
"D105", # Missing docstring in magic method
]
extend-select = []
allowed-confusables = [
Expand Down
2 changes: 1 addition & 1 deletion src/erlab/accessors/fit.py
Original file line number Diff line number Diff line change
Expand Up @@ -636,7 +636,7 @@ def __call__(self, dim: str, model: lmfit.Model, **kwargs) -> xr.Dataset:
<erlab.accessors.fit.ModelFitDataArrayAccessor.__call__>` for details.
"""
if self._obj.chunks is None is not None:
if self._obj.chunks is not None:
raise ValueError(
"The input DataArray is chunked. Parallel fitting will not offer any "
"performance benefits. Use `modelfit` instead"
Expand Down
4 changes: 2 additions & 2 deletions src/erlab/analysis/fit/functions/dynamic.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ def get_args_kwargs(func: Callable) -> tuple[list[str], dict[str, Any]]:
args_default = {}
sig = inspect.signature(func)
for fnam, fpar in sig.parameters.items():
if fpar.kind == fpar.VAR_POSITIONAL or fpar.kind == fpar.VAR_KEYWORD:
if fpar.kind in (fpar.VAR_POSITIONAL, fpar.VAR_KEYWORD):
raise ValueError(f"varargs '*{fnam}' is not supported")
if fpar.default == fpar.empty:
args.append(fnam)
Expand Down Expand Up @@ -249,7 +249,7 @@ def argnames(self) -> list[str]:
def kwargs(self) -> list[tuple[str, float]]:
kws: list[tuple[str, float]] = []

if self.background == "constant" or self.background == "linear":
if self.background in {"constant", "linear"}:
kws.append(("const_bkg", 0.0))
if self.background == "linear":
kws.append(("lin_bkg", 0.0))
Expand Down
15 changes: 7 additions & 8 deletions src/erlab/analysis/gold.py
Original file line number Diff line number Diff line change
Expand Up @@ -282,18 +282,17 @@ def _fit(data, w):
),
**tqdm_kw,
)
else:
if progress:
with joblib_progress(**tqdm_kw) as _:
fitresults = parallel_obj(
joblib.delayed(_fit)(gold_sel.isel(alpha=i), weights[i])
for i in range(n_fits)
)
else:
elif progress:
with joblib_progress(**tqdm_kw) as _:
fitresults = parallel_obj(
joblib.delayed(_fit)(gold_sel.isel(alpha=i), weights[i])
for i in range(n_fits)
)
else:
fitresults = parallel_obj(
joblib.delayed(_fit)(gold_sel.isel(alpha=i), weights[i])
for i in range(n_fits)
)

if return_full:
return list(fitresults)
Expand Down
2 changes: 1 addition & 1 deletion src/erlab/analysis/kspace.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ def get_kconv_func(
case AxesConfiguration.Type2DA:
func = _kconv_func_type2_da
case _:
ValueError(f"Invalid configuration {configuration}")
raise ValueError(f"Invalid configuration {configuration}")

return func(k_tot, **angle_params)

Expand Down
2 changes: 0 additions & 2 deletions src/erlab/interactive/curvefittingtool.py
Original file line number Diff line number Diff line change
Expand Up @@ -272,7 +272,6 @@ def __init__(
"clicked": self.do_fit,
},
)
#

# label_width = 0
# for w in self._params_init.widgets_of_type(FittingParameterWidget):
Expand Down Expand Up @@ -509,7 +508,6 @@ def __init__(
"clicked": self.do_fit,
},
)
#

# label_width = 0
# for w in self._params_init.widgets_of_type(FittingParameterWidget):
Expand Down
4 changes: 2 additions & 2 deletions src/erlab/interactive/imagetool/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -430,7 +430,7 @@ def _generate_menu_kwargs(self) -> dict:
] = {
"text": "&Center Current Cursor",
"shortcut": "Shift+C",
"triggered": lambda: self.slicer_area.center_cursor(),
"triggered": self.slicer_area.center_cursor,
}
for i, ((t, s), axis, amount) in enumerate(
zip(
Expand Down Expand Up @@ -463,7 +463,7 @@ def _generate_menu_kwargs(self) -> dict:
] = {
"text": "&Center All Cursors",
"shortcut": "Alt+Shift+C",
"triggered": lambda: self.slicer_area.center_all_cursors(),
"triggered": self.slicer_area.center_all_cursors,
"sep_before": True,
}
for i, ((t, s), axis, amount) in enumerate(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3165,7 +3165,7 @@ def __init__(self, data, title=None, *args, **kwargs) -> None:
"L": ("Lock color levels", self.tab2._cmap_lock_button.click),
"S": ("Toggle cursor snap", self.tab1._snap_button.click),
"T": ("Transpose main image", self.tab1._transpose_button[1].click),
"Ctrl+A": ("View All", lambda: self.itool.autoRange()),
"Ctrl+A": ("View All", self.itool.autoRange),
}
for k, v in self.keyboard_shortcuts.items():
sc = QtGui.QShortcut(QtGui.QKeySequence(k), self)
Expand Down
4 changes: 2 additions & 2 deletions src/erlab/interactive/imagetool/controls.py
Original file line number Diff line number Diff line change
Expand Up @@ -648,10 +648,10 @@ def initialize_widgets(self) -> None:
lambda g: self.slicer_area.set_colormap(gamma=g)
)
self.gamma_widget.slider.sliderPressed.connect(
lambda: self.slicer_area.sigWriteHistory.emit()
self.slicer_area.sigWriteHistory.emit
)
self.gamma_widget.spin.editingStarted.connect(
lambda: self.slicer_area.sigWriteHistory.emit()
self.slicer_area.sigWriteHistory.emit
)
self.gamma_widget.setSizePolicy(
QtWidgets.QSizePolicy.Policy.Fixed, QtWidgets.QSizePolicy.Policy.Fixed
Expand Down
20 changes: 11 additions & 9 deletions src/erlab/interactive/imagetool/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -817,12 +817,14 @@ def view_all(self) -> None:
ax.vb.enableAutoRange()
ax.vb.updateAutoRange()

@QtCore.Slot()
@link_slicer
@record_history
def center_all_cursors(self) -> None:
for i in range(self.n_cursors):
self.array_slicer.center_cursor(i)

@QtCore.Slot()
@link_slicer
@record_history
def center_cursor(self) -> None:
Expand Down Expand Up @@ -956,12 +958,11 @@ def update_values(
raise ValueError("DataArray shape does not match")

values = values.values
else:
if self.data.shape != values.shape:
raise ValueError(
"Data shape does not match. Array is "
f"{self.data.shape} but {values.shape} given"
)
elif self.data.shape != values.shape:
raise ValueError(
"Data shape does not match. Array is "
f"{self.data.shape} but {values.shape} given"
)
self.array_slicer._obj[:] = values

if update:
Expand Down Expand Up @@ -1524,7 +1525,7 @@ def __init__(
self.setContextMenuActionVisible(act, False)

save_action = self.vb.menu.addAction("Save data as HDF5")
save_action.triggered.connect(lambda: self.save_current_data())
save_action.triggered.connect(self.save_current_data)

copy_code_action = self.vb.menu.addAction("Copy selection code")
copy_code_action.triggered.connect(self.copy_selection_code)
Expand Down Expand Up @@ -1752,7 +1753,7 @@ def add_cursor(self, update: bool = True) -> None:
lambda v, *, line=c, axis=ax: self.line_drag(line, v.temp_value, axis)
)
c.sigClicked.connect(lambda *, line=c: self.line_click(line))
c.sigDragStarted.connect(lambda: self.slicer_area.sigWriteHistory.emit())
c.sigDragStarted.connect(self.slicer_area.sigWriteHistory.emit)

if update:
self.refresh_cursor(new_cursor)
Expand Down Expand Up @@ -1873,6 +1874,7 @@ def set_active_cursor(self, index: int) -> None:
for i, item in enumerate(self.slicer_data_items):
item.setVisible(i == index)

@QtCore.Slot()
def save_current_data(self, fileName=None) -> None:
default_name = "data"
if self.slicer_area._data is not None:
Expand Down Expand Up @@ -1962,7 +1964,7 @@ def setImageItem(self, *args, **kwargs) -> None:
self._span.setRegion(self.limits)
self._span.blockSignals(False)
self._span.sigRegionChangeStarted.connect(
lambda: self._slicer_area.sigWriteHistory.emit()
self._slicer_area.sigWriteHistory.emit
)
self._span.sigRegionChanged.connect(self.level_change)
self._span.sigRegionChangeFinished.connect(self.level_change_fin)
Expand Down
4 changes: 2 additions & 2 deletions src/erlab/interactive/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -646,7 +646,7 @@ def __init__(
layout.addWidget(self.check)

for spin in (self.spin_value, self.spin_lb, self.spin_ub):
spin.valueChanged.connect(lambda: self.sigParamChanged.emit())
spin.valueChanged.connect(self.sigParamChanged.emit)
self.spin_lb.valueChanged.connect(self._refresh_bounds)
self.spin_ub.valueChanged.connect(self._refresh_bounds)
self.check.stateChanged.connect(self.setFixed)
Expand Down Expand Up @@ -1576,7 +1576,7 @@ def __init__(self, parent: QtWidgets.QWidget | None = None, **kwargs) -> None:

self.add_items(**kwargs)

def __getattribute__(self, __name: str) -> Any:
def __getattribute__(self, __name: str, /) -> Any:
try:
return super().__getattribute__(__name)
except AttributeError:
Expand Down
2 changes: 1 addition & 1 deletion src/erlab/io/plugins/da30.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ def load_zip(
def parse_ini(filename: str | os.PathLike) -> dict:
parser = CasePreservingConfigParser(strict=False)
out = {}
with open(filename) as f:
with open(filename, encoding="utf-8") as f:
parser.read_file(f)
for section in parser.sections():
out[section] = dict(parser.items(section))
Expand Down
2 changes: 1 addition & 1 deletion src/erlab/io/plugins/merlin.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ def identify(self, num: int, data_dir: str | os.PathLike):
)

coord_arr = np.loadtxt(motor_file, skiprows=1)
with open(motor_file) as f:
with open(motor_file, encoding="utf-8") as f:
header = f.readline().strip().split("\t")

if coord_arr.ndim == 1:
Expand Down
2 changes: 1 addition & 1 deletion src/erlab/plotting/general.py
Original file line number Diff line number Diff line change
Expand Up @@ -719,7 +719,7 @@ def plot_slices(
crop: bool = True,
same_limits: bool = False,
axis: Literal[
"on", "off", "equal", "scaled", "tight", "auto", "image", "scaled", "square"
"on", "off", "equal", "scaled", "tight", "auto", "image", "square"
] = "auto",
show_all_labels: bool = False,
colorbar: Literal["none", "right", "rightspan", "all"] = "none",
Expand Down
2 changes: 1 addition & 1 deletion tests/analysis/fit/test_models.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import erlab.analysis.fit.models as models
import numpy as np
import xarray as xr
from erlab.analysis.fit import models


def test_fermi_edge_model():
Expand Down
8 changes: 5 additions & 3 deletions tests/io/test_dataloader.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,9 @@ def test_loader():
)

# Write scan coordinates to a csv file
with open(f"{tmp_dir.name}/data_001_axis.csv", "w", newline="") as file:
with open(
f"{tmp_dir.name}/data_001_axis.csv", "w", newline="", encoding="utf-8"
) as file:
writer = csv.writer(file)
writer.writerow(["Index", "Polar"])

Expand Down Expand Up @@ -144,7 +146,7 @@ def identify(self, num, data_dir):
else:
# If files found, extract coordinate values from the filenames
axis_file = f"{data_dir}/data_{str(num).zfill(3)}_axis.csv"
with open(axis_file) as f:
with open(axis_file, encoding="locale") as f:
header = f.readline().strip().split(",")

coord_arr = np.loadtxt(axis_file, delimiter=",", skiprows=1)
Expand Down Expand Up @@ -288,7 +290,7 @@ def generate_summary(self, data_dir):
erlab.io.loaders.set_data_dir("some_nonexistent_dir")

# Test if the reprs are working
assert erlab.io.loaders.__repr__().startswith("Registered data loaders")
assert repr(erlab.io.loaders).startswith("Registered data loaders")
assert erlab.io.loaders._repr_html_().startswith("<table><thead>")

erlab.io.set_loader("example")
Expand Down

0 comments on commit 8265b90

Please sign in to comment.