Skip to content

Commit 3cd17f3

Browse files
authored
Replace isort, flake8, and pyupgrade by ruff (#402)
* Replace isort, flake8, and pyupgrade by ruff * Fix all ruff issues * Last fix
1 parent 85ae3f8 commit 3cd17f3

21 files changed

+188
-148
lines changed

.pre-commit-config.yaml

Lines changed: 5 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -9,19 +9,11 @@ repos:
99
- id: debug-statements
1010
- id: check-ast
1111
- repo: https://github.com/psf/black
12-
rev: 23.1.0
12+
rev: 23.3.0
1313
hooks:
1414
- id: black
15-
- repo: https://github.com/asottile/pyupgrade
16-
rev: v3.3.1
15+
- repo: https://github.com/charliermarsh/ruff-pre-commit
16+
rev: "v0.0.261"
1717
hooks:
18-
- id: pyupgrade
19-
args: ["--py37-plus"]
20-
- repo: https://github.com/PyCQA/isort
21-
rev: 5.12.0
22-
hooks:
23-
- id: isort
24-
- repo: https://github.com/pycqa/flake8
25-
rev: 6.0.0
26-
hooks:
27-
- id: flake8
18+
- id: ruff
19+
args: ["--fix"]

adaptive/_version.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -203,4 +203,4 @@ def make_release_tree(self, base_dir, files):
203203
_write_version(os.path.join(base_dir, p, STATIC_VERSION_FILE))
204204

205205

206-
cmdclass = dict(sdist=_sdist, build_py=_build_py)
206+
cmdclass = {"sdist": _sdist, "build_py": _build_py}

adaptive/learner/average_learner1D.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -612,7 +612,7 @@ def plot(self):
612612
margin = 0.05 * (self.bounds[1] - self.bounds[0])
613613
plot_bounds = (self.bounds[0] - margin, self.bounds[1] + margin)
614614

615-
return p.redim(x=dict(range=plot_bounds))
615+
return p.redim(x={"range": plot_bounds})
616616

617617

618618
def decreasing_dict() -> dict:

adaptive/learner/balancing_learner.py

Lines changed: 24 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,7 @@ def __init__(
105105
# Naively we would make 'function' a method, but this causes problems
106106
# when using executors from 'concurrent.futures' because we have to
107107
# pickle the whole learner.
108-
self.function = partial(dispatch, [l.function for l in self.learners]) # type: ignore
108+
self.function = partial(dispatch, [lrn.function for lrn in self.learners]) # type: ignore
109109

110110
self._ask_cache = {}
111111
self._loss = {}
@@ -130,25 +130,25 @@ def new(self) -> BalancingLearner:
130130
@property
131131
def data(self) -> dict[tuple[int, Any], Any]:
132132
data = {}
133-
for i, l in enumerate(self.learners):
134-
data.update({(i, p): v for p, v in l.data.items()})
133+
for i, lrn in enumerate(self.learners):
134+
data.update({(i, p): v for p, v in lrn.data.items()})
135135
return data
136136

137137
@property
138138
def pending_points(self) -> set[tuple[int, Any]]:
139139
pending_points = set()
140-
for i, l in enumerate(self.learners):
141-
pending_points.update({(i, p) for p in l.pending_points})
140+
for i, lrn in enumerate(self.learners):
141+
pending_points.update({(i, p) for p in lrn.pending_points})
142142
return pending_points
143143

144144
@property
145145
def npoints(self) -> int:
146-
return sum(l.npoints for l in self.learners)
146+
return sum(lrn.npoints for lrn in self.learners)
147147

148148
@property
149149
def nsamples(self):
150150
if hasattr(self.learners[0], "nsamples"):
151-
return sum(l.nsamples for l in self.learners)
151+
return sum(lrn.nsamples for lrn in self.learners)
152152
else:
153153
raise AttributeError(
154154
f"{type(self.learners[0])} as no attribute called `nsamples`."
@@ -187,7 +187,7 @@ def _ask_and_tell_based_on_loss_improvements(
187187
self, n: int
188188
) -> tuple[list[tuple[int, Any]], list[float]]:
189189
selected = [] # tuples ((learner_index, point), loss_improvement)
190-
total_points = [l.npoints + len(l.pending_points) for l in self.learners]
190+
total_points = [lrn.npoints + len(lrn.pending_points) for lrn in self.learners]
191191
for _ in range(n):
192192
to_select = []
193193
for index, learner in enumerate(self.learners):
@@ -212,7 +212,7 @@ def _ask_and_tell_based_on_loss(
212212
self, n: int
213213
) -> tuple[list[tuple[int, Any]], list[float]]:
214214
selected = [] # tuples ((learner_index, point), loss_improvement)
215-
total_points = [l.npoints + len(l.pending_points) for l in self.learners]
215+
total_points = [lrn.npoints + len(lrn.pending_points) for lrn in self.learners]
216216
for _ in range(n):
217217
losses = self._losses(real=False)
218218
index, _ = max(
@@ -235,7 +235,7 @@ def _ask_and_tell_based_on_npoints(
235235
self, n: numbers.Integral
236236
) -> tuple[list[tuple[numbers.Integral, Any]], list[float]]:
237237
selected = [] # tuples ((learner_index, point), loss_improvement)
238-
total_points = [l.npoints + len(l.pending_points) for l in self.learners]
238+
total_points = [lrn.npoints + len(lrn.pending_points) for lrn in self.learners]
239239
for _ in range(n):
240240
index = np.argmin(total_points)
241241
# Take the points from the cache
@@ -356,7 +356,9 @@ def plot(
356356
keys, values_list = cdims
357357
cdims = [dict(zip(keys, values)) for values in values_list]
358358

359-
mapping = {tuple(_cdims.values()): l for l, _cdims in zip(self.learners, cdims)}
359+
mapping = {
360+
tuple(_cdims.values()): lrn for lrn, _cdims in zip(self.learners, cdims)
361+
}
360362

361363
d = defaultdict(list)
362364
for _cdims in cdims:
@@ -526,11 +528,11 @@ def save(
526528
>>> learner.save(combo_fname) # use 'load' in the same way
527529
"""
528530
if isinstance(fname, Iterable):
529-
for l, _fname in zip(self.learners, fname):
530-
l.save(_fname, compress=compress)
531+
for lrn, _fname in zip(self.learners, fname):
532+
lrn.save(_fname, compress=compress)
531533
else:
532-
for l in self.learners:
533-
l.save(fname(l), compress=compress)
534+
for lrn in self.learners:
535+
lrn.save(fname(lrn), compress=compress)
534536

535537
def load(
536538
self,
@@ -554,18 +556,18 @@ def load(
554556
See the example in the `BalancingLearner.save` doc-string.
555557
"""
556558
if isinstance(fname, Iterable):
557-
for l, _fname in zip(self.learners, fname):
558-
l.load(_fname, compress=compress)
559+
for lrn, _fname in zip(self.learners, fname):
560+
lrn.load(_fname, compress=compress)
559561
else:
560-
for l in self.learners:
561-
l.load(fname(l), compress=compress)
562+
for lrn in self.learners:
563+
lrn.load(fname(lrn), compress=compress)
562564

563565
def _get_data(self) -> list[Any]:
564-
return [l._get_data() for l in self.learners]
566+
return [lrn._get_data() for lrn in self.learners]
565567

566568
def _set_data(self, data: list[Any]):
567-
for l, _data in zip(self.learners, data):
568-
l._set_data(_data)
569+
for lrn, _data in zip(self.learners, data):
570+
lrn._set_data(_data)
569571

570572
def __getstate__(self) -> tuple[list[BaseLearner], CDIMS_TYPE, STRATEGY_TYPE]:
571573
return (

adaptive/learner/integrator_coeffs.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -191,4 +191,4 @@ def __getattr__(name):
191191
try:
192192
return _coefficients()[name]
193193
except KeyError:
194-
raise AttributeError(f"module {__name__} has no attribute {name}")
194+
raise AttributeError(f"module {__name__} has no attribute {name}") from None

adaptive/learner/integrator_learner.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -471,7 +471,7 @@ def _ask_and_tell_pending(self, n: int) -> tuple[list[float], list[float]]:
471471
try:
472472
self._fill_stack()
473473
except ValueError:
474-
raise RuntimeError("No way to improve the integral estimate.")
474+
raise RuntimeError("No way to improve the integral estimate.") from None
475475
new_points, new_loss_improvements = self.pop_from_stack(n_left)
476476
points += new_points
477477
loss_improvements += new_loss_improvements
@@ -513,8 +513,8 @@ def _fill_stack(self) -> list[float]:
513513
elif ival.depth == 3 or force_split:
514514
# Always split when depth is maximal or if refining didn't help
515515
self.ivals.remove(ival)
516-
for ival in ival.split():
517-
self.add_ival(ival)
516+
for iv in ival.split():
517+
self.add_ival(iv)
518518
else:
519519
self.add_ival(ival.refine())
520520

adaptive/learner/learner1D.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -829,7 +829,7 @@ def plot(self, *, scatter_or_line: str = "scatter"):
829829
margin = 0.05 * (self.bounds[1] - self.bounds[0])
830830
plot_bounds = (self.bounds[0] - margin, self.bounds[1] + margin)
831831

832-
return p.redim(x=dict(range=plot_bounds))
832+
return p.redim(x={"range": plot_bounds})
833833

834834
def remove_unfinished(self) -> None:
835835
self.pending_points = set()

adaptive/learner/learner2D.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -603,6 +603,7 @@ def ip(self) -> LinearNDInterpolator:
603603
"`learner.ip()` is deprecated, use `learner.interpolator(scaled=True)`."
604604
" This will be removed in v1.0.",
605605
DeprecationWarning,
606+
stacklevel=2,
606607
)
607608
return self.interpolator(scaled=True)
608609

@@ -682,15 +683,15 @@ def _fill_stack(
682683

683684
points_new = []
684685
losses_new = []
685-
for j, _ in enumerate(losses):
686+
for _j, _ in enumerate(losses):
686687
jsimplex = np.argmax(losses)
687688
triangle = ip.tri.points[ip.tri.simplices[jsimplex]]
688689
point_new = choose_point_in_triangle(triangle, max_badness=5)
689690
point_new = tuple(self._unscale(point_new))
690691

691692
# np.clip results in numerical precision problems
692693
# https://github.com/python-adaptive/adaptive/issues/7
693-
clip = lambda x, l, u: max(l, min(u, x)) # noqa: E731
694+
clip = lambda x, lo, up: max(lo, min(up, x)) # noqa: E731
694695
point_new = (
695696
clip(point_new[0], *self.bounds[0]),
696697
clip(point_new[1], *self.bounds[1]),
@@ -818,9 +819,9 @@ def plot(self, n=None, tri_alpha=0):
818819
im = hv.Image([], bounds=lbrt)
819820
tris = hv.EdgePaths([])
820821

821-
im_opts = dict(cmap="viridis")
822-
tri_opts = dict(line_width=0.5, alpha=tri_alpha)
823-
no_hover = dict(plot=dict(inspection_policy=None, tools=[]))
822+
im_opts = {"cmap": "viridis"}
823+
tri_opts = {"line_width": 0.5, "alpha": tri_alpha}
824+
no_hover = {"plot": {"inspection_policy": None, "tools": []}}
824825

825826
return im.opts(style=im_opts) * tris.opts(style=tri_opts, **no_hover)
826827

0 commit comments

Comments
 (0)