Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Replace isort, flake8, and pyupgrade by ruff #402

Merged
merged 3 commits into from
Apr 7, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 5 additions & 13 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -9,19 +9,11 @@ repos:
- id: debug-statements
- id: check-ast
- repo: https://github.com/psf/black
rev: 23.1.0
rev: 23.3.0
hooks:
- id: black
- repo: https://github.com/asottile/pyupgrade
rev: v3.3.1
- repo: https://github.com/charliermarsh/ruff-pre-commit
rev: "v0.0.261"
hooks:
- id: pyupgrade
args: ["--py37-plus"]
- repo: https://github.com/PyCQA/isort
rev: 5.12.0
hooks:
- id: isort
- repo: https://github.com/pycqa/flake8
rev: 6.0.0
hooks:
- id: flake8
- id: ruff
args: ["--fix"]
2 changes: 1 addition & 1 deletion adaptive/_version.py
Original file line number Diff line number Diff line change
Expand Up @@ -203,4 +203,4 @@ def make_release_tree(self, base_dir, files):
_write_version(os.path.join(base_dir, p, STATIC_VERSION_FILE))


cmdclass = dict(sdist=_sdist, build_py=_build_py)
cmdclass = {"sdist": _sdist, "build_py": _build_py}
2 changes: 1 addition & 1 deletion adaptive/learner/average_learner1D.py
Original file line number Diff line number Diff line change
Expand Up @@ -612,7 +612,7 @@ def plot(self):
margin = 0.05 * (self.bounds[1] - self.bounds[0])
plot_bounds = (self.bounds[0] - margin, self.bounds[1] + margin)

return p.redim(x=dict(range=plot_bounds))
return p.redim(x={"range": plot_bounds})


def decreasing_dict() -> dict:
Expand Down
46 changes: 24 additions & 22 deletions adaptive/learner/balancing_learner.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ def __init__(
# Naively we would make 'function' a method, but this causes problems
# when using executors from 'concurrent.futures' because we have to
# pickle the whole learner.
self.function = partial(dispatch, [l.function for l in self.learners]) # type: ignore
self.function = partial(dispatch, [lrn.function for lrn in self.learners]) # type: ignore

self._ask_cache = {}
self._loss = {}
Expand All @@ -130,25 +130,25 @@ def new(self) -> BalancingLearner:
@property
def data(self) -> dict[tuple[int, Any], Any]:
data = {}
for i, l in enumerate(self.learners):
data.update({(i, p): v for p, v in l.data.items()})
for i, lrn in enumerate(self.learners):
data.update({(i, p): v for p, v in lrn.data.items()})
return data

@property
def pending_points(self) -> set[tuple[int, Any]]:
pending_points = set()
for i, l in enumerate(self.learners):
pending_points.update({(i, p) for p in l.pending_points})
for i, lrn in enumerate(self.learners):
pending_points.update({(i, p) for p in lrn.pending_points})
return pending_points

@property
def npoints(self) -> int:
return sum(l.npoints for l in self.learners)
return sum(lrn.npoints for lrn in self.learners)

@property
def nsamples(self):
if hasattr(self.learners[0], "nsamples"):
return sum(l.nsamples for l in self.learners)
return sum(lrn.nsamples for lrn in self.learners)
else:
raise AttributeError(
f"{type(self.learners[0])} as no attribute called `nsamples`."
Expand Down Expand Up @@ -187,7 +187,7 @@ def _ask_and_tell_based_on_loss_improvements(
self, n: int
) -> tuple[list[tuple[int, Any]], list[float]]:
selected = [] # tuples ((learner_index, point), loss_improvement)
total_points = [l.npoints + len(l.pending_points) for l in self.learners]
total_points = [lrn.npoints + len(lrn.pending_points) for lrn in self.learners]
for _ in range(n):
to_select = []
for index, learner in enumerate(self.learners):
Expand All @@ -212,7 +212,7 @@ def _ask_and_tell_based_on_loss(
self, n: int
) -> tuple[list[tuple[int, Any]], list[float]]:
selected = [] # tuples ((learner_index, point), loss_improvement)
total_points = [l.npoints + len(l.pending_points) for l in self.learners]
total_points = [lrn.npoints + len(lrn.pending_points) for lrn in self.learners]
for _ in range(n):
losses = self._losses(real=False)
index, _ = max(
Expand All @@ -235,7 +235,7 @@ def _ask_and_tell_based_on_npoints(
self, n: numbers.Integral
) -> tuple[list[tuple[numbers.Integral, Any]], list[float]]:
selected = [] # tuples ((learner_index, point), loss_improvement)
total_points = [l.npoints + len(l.pending_points) for l in self.learners]
total_points = [lrn.npoints + len(lrn.pending_points) for lrn in self.learners]
for _ in range(n):
index = np.argmin(total_points)
# Take the points from the cache
Expand Down Expand Up @@ -356,7 +356,9 @@ def plot(
keys, values_list = cdims
cdims = [dict(zip(keys, values)) for values in values_list]

mapping = {tuple(_cdims.values()): l for l, _cdims in zip(self.learners, cdims)}
mapping = {
tuple(_cdims.values()): lrn for lrn, _cdims in zip(self.learners, cdims)
}

d = defaultdict(list)
for _cdims in cdims:
Expand Down Expand Up @@ -526,11 +528,11 @@ def save(
>>> learner.save(combo_fname) # use 'load' in the same way
"""
if isinstance(fname, Iterable):
for l, _fname in zip(self.learners, fname):
l.save(_fname, compress=compress)
for lrn, _fname in zip(self.learners, fname):
lrn.save(_fname, compress=compress)
else:
for l in self.learners:
l.save(fname(l), compress=compress)
for lrn in self.learners:
lrn.save(fname(lrn), compress=compress)

def load(
self,
Expand All @@ -554,18 +556,18 @@ def load(
See the example in the `BalancingLearner.save` doc-string.
"""
if isinstance(fname, Iterable):
for l, _fname in zip(self.learners, fname):
l.load(_fname, compress=compress)
for lrn, _fname in zip(self.learners, fname):
lrn.load(_fname, compress=compress)
else:
for l in self.learners:
l.load(fname(l), compress=compress)
for lrn in self.learners:
lrn.load(fname(lrn), compress=compress)

def _get_data(self) -> list[Any]:
return [l._get_data() for l in self.learners]
return [lrn._get_data() for lrn in self.learners]

def _set_data(self, data: list[Any]):
for l, _data in zip(self.learners, data):
l._set_data(_data)
for lrn, _data in zip(self.learners, data):
lrn._set_data(_data)

def __getstate__(self) -> tuple[list[BaseLearner], CDIMS_TYPE, STRATEGY_TYPE]:
return (
Expand Down
2 changes: 1 addition & 1 deletion adaptive/learner/integrator_coeffs.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,4 +191,4 @@ def __getattr__(name):
try:
return _coefficients()[name]
except KeyError:
raise AttributeError(f"module {__name__} has no attribute {name}")
raise AttributeError(f"module {__name__} has no attribute {name}") from None
6 changes: 3 additions & 3 deletions adaptive/learner/integrator_learner.py
Original file line number Diff line number Diff line change
Expand Up @@ -471,7 +471,7 @@ def _ask_and_tell_pending(self, n: int) -> tuple[list[float], list[float]]:
try:
self._fill_stack()
except ValueError:
raise RuntimeError("No way to improve the integral estimate.")
raise RuntimeError("No way to improve the integral estimate.") from None
new_points, new_loss_improvements = self.pop_from_stack(n_left)
points += new_points
loss_improvements += new_loss_improvements
Expand Down Expand Up @@ -513,8 +513,8 @@ def _fill_stack(self) -> list[float]:
elif ival.depth == 3 or force_split:
# Always split when depth is maximal or if refining didn't help
self.ivals.remove(ival)
for ival in ival.split():
self.add_ival(ival)
for iv in ival.split():
self.add_ival(iv)
else:
self.add_ival(ival.refine())

Expand Down
2 changes: 1 addition & 1 deletion adaptive/learner/learner1D.py
Original file line number Diff line number Diff line change
Expand Up @@ -829,7 +829,7 @@ def plot(self, *, scatter_or_line: str = "scatter"):
margin = 0.05 * (self.bounds[1] - self.bounds[0])
plot_bounds = (self.bounds[0] - margin, self.bounds[1] + margin)

return p.redim(x=dict(range=plot_bounds))
return p.redim(x={"range": plot_bounds})

def remove_unfinished(self) -> None:
self.pending_points = set()
Expand Down
11 changes: 6 additions & 5 deletions adaptive/learner/learner2D.py
Original file line number Diff line number Diff line change
Expand Up @@ -603,6 +603,7 @@ def ip(self) -> LinearNDInterpolator:
"`learner.ip()` is deprecated, use `learner.interpolator(scaled=True)`."
" This will be removed in v1.0.",
DeprecationWarning,
stacklevel=2,
)
return self.interpolator(scaled=True)

Expand Down Expand Up @@ -682,15 +683,15 @@ def _fill_stack(

points_new = []
losses_new = []
for j, _ in enumerate(losses):
for _j, _ in enumerate(losses):
jsimplex = np.argmax(losses)
triangle = ip.tri.points[ip.tri.simplices[jsimplex]]
point_new = choose_point_in_triangle(triangle, max_badness=5)
point_new = tuple(self._unscale(point_new))

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

im_opts = dict(cmap="viridis")
tri_opts = dict(line_width=0.5, alpha=tri_alpha)
no_hover = dict(plot=dict(inspection_policy=None, tools=[]))
im_opts = {"cmap": "viridis"}
tri_opts = {"line_width": 0.5, "alpha": tri_alpha}
no_hover = {"plot": {"inspection_policy": None, "tools": []}}

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

Expand Down
Loading