Skip to content

Commit

Permalink
ruff: enable and fix remaining rules
Browse files Browse the repository at this point in the history
  • Loading branch information
alexfikl committed Jul 22, 2024
1 parent b959848 commit 622ff64
Show file tree
Hide file tree
Showing 17 changed files with 76 additions and 111 deletions.
6 changes: 1 addition & 5 deletions boxtree/bounding_box.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,11 +158,7 @@ def __call__(self, particles, radii, wait_for=None):
from pytools import single_valued
coord_dtype = single_valued(coord.dtype for coord in particles)

if radii is None:
radii_tuple = ()
else:
radii_tuple = (radii,)

radii_tuple = () if radii is None else (radii,)
knl = self.get_kernel(dimensions, coord_dtype,
# have_radii:
radii is not None)
Expand Down
6 changes: 1 addition & 5 deletions boxtree/cost.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,11 +154,7 @@ def make_pde_aware_translation_cost_model(dim, nlevels):
p_fmm = np.array([var("p_fmm_lev%d" % i) for i in range(nlevels)])
ncoeffs_fmm = (p_fmm + 1) ** (dim - 1)

if dim == 3:
uses_point_and_shoot = True
else:
uses_point_and_shoot = False

uses_point_and_shoot = dim == 3
return FMMTranslationCostModel(
ncoeffs_fmm_by_level=ncoeffs_fmm,
uses_point_and_shoot=uses_point_and_shoot
Expand Down
6 changes: 1 addition & 5 deletions boxtree/distributed/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -197,11 +197,7 @@ def make_distributed_wrangler(

global_trav_dev, _ = traversal_builder(queue, global_tree_dev)
global_trav_host = global_trav_dev.get(queue)

if tree_in_device_memory:
global_trav = global_trav_dev
else:
global_trav = global_trav_host
global_trav = global_trav_dev if tree_in_device_memory else global_trav_host

# }}}

Expand Down
16 changes: 5 additions & 11 deletions boxtree/pyfmmlib_integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -213,10 +213,8 @@ def wrapper(*args, **kwargs):
def wrapper(*args, **kwargs):
kwargs["iffld"] = self.ifgrad
pot, fld = rout(*args, **kwargs)
if self.ifgrad:
grad = -fld
else:
grad = 0
grad = -fld if self.ifgrad else 0

return pot, grad

# Doesn't work in in Py2
Expand Down Expand Up @@ -254,11 +252,7 @@ def wrapper(*args, **kwargs):
if (ier != 0).any():
raise RuntimeError(f"{name} failed with nonzero ier")

if self.ifgrad:
grad = -fld
else:
grad = 0

grad = -fld if self.ifgrad else 0
return pot, grad

# Doesn't work in in Py2
Expand Down Expand Up @@ -604,11 +598,11 @@ def mem_estimate(order):

ier, rotmatf = (
rotmat_builder(rotmat_order, m2l_rotation_angles))
assert (0 == ier).all()
assert (ier == 0).all()

ier, rotmatb = (
rotmat_builder(rotmat_order, -m2l_rotation_angles))
assert (0 == ier).all()
assert (ier == 0).all()

return (rotmatf, rotmatb, rotmat_order)

Expand Down
9 changes: 3 additions & 6 deletions boxtree/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ def realloc_array(queue, allocator, new_shape, ary, zero_fill=False, wait_for=No
if wait_for is None:
wait_for = []

if zero_fill:
if zero_fill: # noqa: SIM108
array_maker = cl.array.zeros
else:
array_maker = cl.array.empty
Expand Down Expand Up @@ -491,7 +491,7 @@ def __call__(self, queue, allocator, new_shape, ary, src_indices=None,
if debug:
assert int(cl.array.max(dst_indices).get()) < new_shape

if zero_fill:
if zero_fill: # noqa: SIM108
array_maker = cl.array.zeros
else:
array_maker = cl.array.empty
Expand Down Expand Up @@ -897,10 +897,7 @@ def with_queue(self, queue):
def svm_capable(self):
svm_capabilities = \
self.queue.device.get_info(cl.device_info.SVM_CAPABILITIES)
if svm_capabilities & cl.device_svm_capabilities.FINE_GRAIN_BUFFER != 0:
return True
else:
return False
return svm_capabilities & cl.device_svm_capabilities.FINE_GRAIN_BUFFER != 0

@property
def host(self):
Expand Down
2 changes: 1 addition & 1 deletion boxtree/tree.py
Original file line number Diff line number Diff line change
Expand Up @@ -892,7 +892,7 @@ def link_point_sources(queue, tree, point_source_starts, point_sources,

tree_attrs = {}
for attr_name in tree.__class__.fields:
try:
try: # noqa: SIM105
tree_attrs[attr_name] = getattr(tree, attr_name)
except AttributeError:
pass
Expand Down
23 changes: 7 additions & 16 deletions boxtree/tree_build.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,10 +175,7 @@ def __call__(self, queue, particles, kind="adaptive",
raise ValueError(f"unknown tree kind '{kind}'")

# we'll modify this below, so copy it
if wait_for is None:
wait_for = []
else:
wait_for = list(wait_for)
wait_for = [] if wait_for is None else list(wait_for)

dimensions = len(particles)

Expand Down Expand Up @@ -301,10 +298,7 @@ def zeros(shape, dtype):
"dtype")

def combine_srcntgt_arrays(ary1, ary2=None):
if ary2 is None:
dtype = ary1.dtype
else:
dtype = ary2.dtype
dtype = ary1.dtype if ary2 is None else ary2.dtype

result = empty(nsrcntgts, dtype)
if (ary1 is None) or (ary2 is None):
Expand Down Expand Up @@ -365,15 +359,15 @@ def combine_srcntgt_arrays(ary1, ary2=None):
event, = refine_weights.events
prep_events.append(event)
max_leaf_refine_weight = max_particles_in_box
elif specified_refine_weights:
elif specified_refine_weights: # noqa: SIM102
if refine_weights.dtype != refine_weight_dtype:
raise TypeError(
f"refine_weights must have dtype '{refine_weight_dtype}'")

if max_leaf_refine_weight < cl.array.max(refine_weights).get():
raise ValueError(
"entries of refine_weights cannot exceed max_leaf_refine_weight")
if 0 > cl.array.min(refine_weights).get():
if cl.array.min(refine_weights).get() < 0:
raise ValueError("all entries of refine_weights must be nonnegative")
if max_leaf_refine_weight <= 0:
raise ValueError("max_leaf_refine_weight must be positive")
Expand Down Expand Up @@ -607,10 +601,7 @@ def fin_debug(s):

tree_build_proc = ProcessLogger(logger, "tree build")

if total_refine_weight > max_leaf_refine_weight:
level = 1
else:
level = 0
level = 1 if total_refine_weight > max_leaf_refine_weight else 0

# INVARIANTS -- Upon entry to this loop:
#
Expand Down Expand Up @@ -1461,7 +1452,7 @@ def make_arange(start, offset=level_used_box_count):
wait_for=wait_for)
wait_for = [evt]

if srcntgts_have_extent:
if srcntgts_have_extent: # noqa: SIM102
if debug:
assert (
box_srcntgt_counts_nonchild.get()
Expand All @@ -1471,7 +1462,7 @@ def make_arange(start, offset=level_used_box_count):
if debug:
usi_host = user_source_ids.get()
assert (usi_host < nsources).all()
assert (0 <= usi_host).all()
assert (usi_host >= 0).all()
del usi_host

sti_host = srcntgt_target_ids.get()
Expand Down
2 changes: 1 addition & 1 deletion boxtree/tree_build_kernels.py
Original file line number Diff line number Diff line change
Expand Up @@ -1393,7 +1393,7 @@ def get_tree_build_kernel_info(context, dimensions, coord_dtype,
"""

level_restrict = (kind == "adaptive-level-restricted")
adaptive = not (kind == "non-adaptive")
adaptive = (kind != "non-adaptive")

# {{{ preparation

Expand Down
8 changes: 6 additions & 2 deletions boxtree/visualization.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,10 @@ def get_tikz_for_tree(self):
# {{{ traversal plotting

def _draw_box_list(tree_plotter, ibox, starts, lists, key_to_box=None, **kwargs):
rng = kwargs.pop("rng", None)
if rng is None:
rng = np.radnom.default_rng()

default_facecolor = "blue"

if key_to_box is not None:
Expand All @@ -183,7 +187,7 @@ def _draw_box_list(tree_plotter, ibox, starts, lists, key_to_box=None, **kwargs)
"edgecolor": getattr(kwargs, "facecolor", default_facecolor),
"fill": False,
"alpha": 0.5,
"shrink_factor": -0.1+0.1*np.random.rand(),
"shrink_factor": -0.1+0.1*rng.random(),
}
tree_plotter.draw_box(ibox, **actual_kwargs)
return
Expand All @@ -198,7 +202,7 @@ def _draw_box_list(tree_plotter, ibox, starts, lists, key_to_box=None, **kwargs)
"facecolor": default_facecolor,
"linewidth": 0,
"alpha": 0.5,
"shrink_factor": 0.1 + np.random.rand()*0.2,
"shrink_factor": 0.1 + rng.random()*0.2,
}
actual_kwargs.update(kwargs)
print(actual_kwargs["facecolor"], ibox, lists[start:end])
Expand Down
8 changes: 5 additions & 3 deletions examples/cost_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ def demo_cost_model():
Kernel,
)

rng = np.random.default_rng(seed=42)
nsources_list = [1000, 2000, 3000, 4000, 5000]
ntargets_list = [1000, 2000, 3000, 4000, 5000]
dims = 3
Expand All @@ -56,8 +57,9 @@ def fmm_level_to_order(tree, ilevel):
targets = p_normal(queue, ntargets, dims, dtype, seed=18)

from pyopencl.clrandom import PhiloxGenerator
rng = PhiloxGenerator(queue.context, seed=22)
target_radii = rng.uniform(

clrng = PhiloxGenerator(queue.context, seed=22)
target_radii = clrng.uniform(
queue, ntargets, a=0, b=0.05, dtype=dtype
).get()

Expand Down Expand Up @@ -90,7 +92,7 @@ def fmm_level_to_order(tree, ilevel):

timing_data = {}
from boxtree.fmm import drive_fmm
src_weights = np.random.rand(tree.nsources).astype(tree.coord_dtype)
src_weights = rng.random(size=tree.nsources, dtype=tree.coord_dtype)
drive_fmm(wrangler, (src_weights,), timing_data=timing_data)

timing_results.append(timing_data)
Expand Down
25 changes: 11 additions & 14 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -78,25 +78,21 @@ extend-select = [
"E", # pycodestyle
"F", # pyflakes
"G", # flake8-logging-format
"I", # flake8-isort
"N", # pep8-naming
"NPY", # numpy
"Q", # flake8-quotes
"I", # flake8-isort
"UP", # pyupgrade
"RUF", # ruff

# TODO
# "W", # pycodestyle
# "SIM",
"SIM", # flake8-simplify
"UP", # pyupgrade
"W", # pycodestyle
]
extend-ignore = [
"C90", # McCabe complexity
"E221", # multiple spaces before operator
"E226", # missing whitespace around arithmetic operator
"E402", # module-level import not at top of file

# TODO
"NPY002", # legacy numpy rng
"SIM223", # simplify `False and ...` conditional
]

[tool.ruff.lint.flake8-quotes]
Expand All @@ -119,12 +115,13 @@ known-local-folder = [
"boxtree",
]
lines-after-imports = 2
# required-imports = ["from __future__ import annotations"]

[tool.ruff.lint.per-file-ignores]
"doc/**/*.py" = ["I002"]
"examples/**/*.py" = ["I002"]
"setup.py" = ["I002"]
# TODO: enable postponed annotations at some point
# required-imports = ["from __future__ import annotations"]
# [tool.ruff.lint.per-file-ignores]
# "doc/**/*.py" = ["I002"]
# "examples/**/*.py" = ["I002"]
# "setup.py" = ["I002"]

[tool.typos.default]
extend-ignore-re = [
Expand Down
6 changes: 4 additions & 2 deletions test/test_cost_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -383,6 +383,8 @@ def test_estimate_calibration_params(actx_factory):
Kernel,
)

rng = np.random.default_rng(seed=42)

nsources_list = [1000, 2000, 3000, 4000]
ntargets_list = [1000, 2000, 3000, 4000]
dims = 3
Expand Down Expand Up @@ -437,7 +439,7 @@ def fmm_level_to_order(tree, ilevel):

timing_data = {}
from boxtree.fmm import drive_fmm
src_weights = np.random.rand(tree.nsources).astype(tree.coord_dtype)
src_weights = rng.random(size=tree.nsources, dtype=tree.coord_dtype)
drive_fmm(wrangler, (src_weights,), timing_data=timing_data)

timing_results.append(timing_data)
Expand Down Expand Up @@ -564,7 +566,7 @@ def test_cost_model_op_counts_agree_with_constantone_wrangler(

timing_data = {}
from boxtree.fmm import drive_fmm
src_weights = np.random.rand(tree.nsources).astype(tree.coord_dtype)
src_weights = rng.random(size=tree.nsources, dtype=tree.coord_dtype)
drive_fmm(wrangler, (src_weights,), timing_data=timing_data)

cost_model = FMMCostModel(
Expand Down
Loading

0 comments on commit 622ff64

Please sign in to comment.