Skip to content

Commit

Permalink
Enable RUF, UP, G ruff lint, fix issues
Browse files Browse the repository at this point in the history
  • Loading branch information
inducer committed Jul 11, 2024
1 parent 09c1cbc commit beab737
Show file tree
Hide file tree
Showing 21 changed files with 91 additions and 104 deletions.
6 changes: 3 additions & 3 deletions examples/advection/surface.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,10 +76,10 @@ def __call__(self, evt, basename, overwrite=True):
if self.ambient_dim == 2:
u = self.actx.to_numpy(flatten(evt.state_component))

filename = "%s.png" % basename
filename = f"{basename}.png"
if not overwrite and os.path.exists(filename):
from meshmode import FileExistsError
raise FileExistsError("output file '%s' already exists" % filename)
raise FileExistsError(f"output file '{filename}' already exists")

ax = self.fig.gca()
ax.grid()
Expand All @@ -92,7 +92,7 @@ def __call__(self, evt, basename, overwrite=True):
self.fig.savefig(filename)
self.fig.clf()
elif self.ambient_dim == 3:
self.vis.write_vtk_file("%s.vtu" % basename, [
self.vis.write_vtk_file(f"{basename}.vtu", [
("u", evt.state_component)
], overwrite=overwrite)
else:
Expand Down
6 changes: 3 additions & 3 deletions examples/advection/var-velocity.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,10 +71,10 @@ def __call__(self, evt, basename, overwrite=True):
if self.dim == 1:
u = self.actx.to_numpy(flatten(evt.state_component))

filename = "%s.png" % basename
filename = f"{basename}.png"
if not overwrite and os.path.exists(filename):
from meshmode import FileExistsError
raise FileExistsError("output file '%s' already exists" % filename)
raise FileExistsError(f"output file '{filename}' already exists")

ax = self.fig.gca()
ax.plot(self.x, u, "-")
Expand All @@ -88,7 +88,7 @@ def __call__(self, evt, basename, overwrite=True):
self.fig.savefig(filename)
self.fig.clf()
else:
self.vis.write_vtk_file("%s.vtu" % basename, [
self.vis.write_vtk_file(f"{basename}.vtu", [
("u", evt.state_component)
], overwrite=overwrite)

Expand Down
6 changes: 3 additions & 3 deletions examples/advection/weak.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,10 +71,10 @@ def __call__(self, evt, basename, overwrite=True):
if self.dim == 1:
u = self.actx.to_numpy(flatten(evt.state_component))

filename = "%s.png" % basename
filename = f"{basename}.png"
if not overwrite and os.path.exists(filename):
from meshmode import FileExistsError
raise FileExistsError("output file '%s' already exists" % filename)
raise FileExistsError(f"output file '{filename}' already exists")

ax = self.fig.gca()
ax.plot(self.x, u, "-")
Expand All @@ -89,7 +89,7 @@ def __call__(self, evt, basename, overwrite=True):
self.fig.savefig(filename)
self.fig.clf()
else:
self.vis.write_vtk_file("%s.vtu" % basename, [
self.vis.write_vtk_file(f"{basename}.vtu", [
("u", evt.state_component)
], overwrite=overwrite)

Expand Down
6 changes: 3 additions & 3 deletions grudge/array_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@
except ImportError:
warn("Your loopy and meshmode branches are mismatched. "
"Please make sure that you have the "
"https://github.com/kaushikcfd/loopy/tree/pytato-array-context-transforms " # noqa
"https://github.com/kaushikcfd/loopy/tree/pytato-array-context-transforms "
"branch of loopy.", stacklevel=1)
_HAVE_FUSION_ACTX = False
else:
Expand Down Expand Up @@ -540,7 +540,7 @@ def _get_single_grid_pytato_actx_class(distributed: bool) -> Type[ArrayContext]:
"(https://github.com/kaushikcfd/loopy/tree/pytato-array-context-transforms) " # noqa
"and meshmode "
"(https://github.com/kaushikcfd/meshmode/tree/pytato-array-context-transforms).",
stacklevel=1) # noqa
stacklevel=1)
# lazy, non-distributed
if not distributed:
if _HAVE_SINGLE_GRID_WORK_BALANCING:
Expand Down Expand Up @@ -572,7 +572,7 @@ def get_reasonable_array_context_class(
"(https://github.com/kaushikcfd/loopy/tree/pytato-array-context-transforms) " # noqa
"and meshmode "
"(https://github.com/kaushikcfd/meshmode/tree/pytato-array-context-transforms).",
stacklevel=1) # noqa
stacklevel=1)
# lazy+fusion, non-distributed

if _HAVE_FUSION_ACTX:
Expand Down
2 changes: 1 addition & 1 deletion grudge/discretization.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
from typing import TYPE_CHECKING, Any, Mapping, Optional, Union
from warnings import warn

import numpy as np # noqa: F401
import numpy as np

from arraycontext import ArrayContext
from meshmode.discretization import Discretization, ElementGroupFactory
Expand Down
6 changes: 3 additions & 3 deletions grudge/dof_desc.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ class VTAG_ALL: # noqa: N801
# {{{ domain tag

@dataclass(frozen=True, eq=True)
class ScalarDomainTag: # noqa: N801
class ScalarDomainTag:
"""A domain tag denoting scalar values."""


Expand Down Expand Up @@ -147,7 +147,7 @@ class BoundaryDomainTag:

# {{{ discretization tag

class _DiscretizationTag: # noqa: N801
class _DiscretizationTag:
pass


Expand Down Expand Up @@ -412,7 +412,7 @@ def _normalize_domain_and_discr_tag(
elif domain in [BTAG_ALL, BTAG_REALLY_ALL, BTAG_NONE]:
domain = BoundaryDomainTag(domain, _contextual_volume_tag)
else:
raise ValueError("domain tag not understood: %s" % domain)
raise ValueError(f"domain tag not understood: {domain}")

if domain is DTAG_SCALAR and discretization_tag is not None:
raise ValueError("cannot have nontrivial discretization tag on scalar")
Expand Down
14 changes: 5 additions & 9 deletions grudge/geometry/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,21 +42,17 @@


__all__ = (
"forward_metric_nth_derivative",
"forward_metric_derivative_mat",
"inverse_metric_derivative_mat",

"area_element",
"first_fundamental_form",
"forward_metric_derivative_mat",
"forward_metric_nth_derivative",
"inverse_first_fundamental_form",

"inverse_metric_derivative_mat",
"inverse_surface_metric_derivative",
"inverse_surface_metric_derivative_mat",
"pseudoscalar",
"area_element",

"mv_normal",
"normal",

"pseudoscalar",
"second_fundamental_form",
"shape_operator",
"summed_curvature",
Expand Down
4 changes: 2 additions & 2 deletions grudge/models/advection.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ def advection_weak_flux(dcoll, flux_type, u_tpair, velocity):
# {{{ constant-coefficient advection

class AdvectionOperatorBase(HyperbolicOperator):
flux_types = ["central", "upwind", "lf"]
flux_types = ("central", "upwind", "lf")

def __init__(self, dcoll, v, inflow_u=None, flux_type="central"):
if flux_type not in self.flux_types:
Expand Down Expand Up @@ -295,7 +295,7 @@ def v_dot_n_tpair(actx, dcoll, velocity, trace_dd):
if trace_dd.domain_tag.tag is FACE_RESTR_INTERIOR:
e = dcoll.opposite_face_connection(trace_dd.domain_tag)(i)
else:
raise ValueError("Unrecognized domain tag: %s" % trace_dd.domain_tag)
raise ValueError(f"Unrecognized domain tag: {trace_dd.domain_tag}")

return TracePair(trace_dd, interior=i, exterior=e)

Expand Down
15 changes: 5 additions & 10 deletions grudge/models/em.py
Original file line number Diff line number Diff line change
Expand Up @@ -286,8 +286,7 @@ def flux(self, wtpair):
),
)
else:
raise ValueError("maxwell: invalid flux_type (%s)"
% self.flux_type)
raise ValueError(f"maxwell: invalid flux_type ({self.flux_type})")

def local_derivatives(self, w):
"""Template for the spatial derivatives of the relevant components of
Expand Down Expand Up @@ -480,8 +479,7 @@ class TMMaxwellOperator(MaxwellOperator):

def get_eh_subset(self):
return (
(False, False, True) # only ez
+ (True, True, False) # hx and hy
(False, False, True, True, True, False) # ez, hx and hy
)

# }}}
Expand All @@ -499,8 +497,7 @@ class TEMaxwellOperator(MaxwellOperator):

def get_eh_subset(self):
return (
(True, True, False) # ex and ey
+ (False, False, True) # only hz
(True, True, False, False, False, True) # ex and ey, only hz
)

# }}}
Expand All @@ -518,8 +515,7 @@ class TE1DMaxwellOperator(MaxwellOperator):

def get_eh_subset(self):
return (
(True, True, False)
+ (False, False, True)
(True, True, False, False, False, True)
)

# }}}
Expand All @@ -537,8 +533,7 @@ class SourceFree1DMaxwellOperator(MaxwellOperator):

def get_eh_subset(self):
return (
(False, True, False)
+ (False, False, True)
(False, True, False, False, False, True)
)

# }}}
Expand Down
4 changes: 2 additions & 2 deletions grudge/models/wave.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ def flux(self, wtpair):
0.5*(u.ext-u.int),
0.5*(normal * np.dot(normal, v.ext-v.int)))
else:
raise ValueError("invalid flux type '%s'" % self.flux_type)
raise ValueError(f"invalid flux type '{self.flux_type}'")

def operator(self, t, w):
dcoll = self.dcoll
Expand Down Expand Up @@ -265,7 +265,7 @@ def flux(self, wtpair):
normal * (np.dot(normal, c.ext * v.ext - c.int * v.int)))

else:
raise ValueError("invalid flux type '%s'" % self.flux_type)
raise ValueError(f"invalid flux type '{self.flux_type}'")

def operator(self, t, w):
dcoll = self.dcoll
Expand Down
53 changes: 24 additions & 29 deletions grudge/op.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,43 +128,38 @@


__all__ = (
"project",
"interp",

"norm",
"nodal_sum",
"nodal_min",
"nodal_max",
"nodal_sum_loc",
"nodal_min_loc",
"nodal_max_loc",
"integral",
"elementwise_sum",
"bdry_trace_pair",
"bv_trace_pair",
"connected_ranks",
"cross_rank_trace_pairs",
"elementwise_integral",
"elementwise_max",
"elementwise_min",
"elementwise_integral",

"project_tracepair",
"tracepair_with_discr_tag",
"elementwise_sum",
"face_mass",
"integral",
"interior_trace_pair",
"interior_trace_pairs",
"local_interior_trace_pair",
"connected_ranks",
"cross_rank_trace_pairs",
"bdry_trace_pair",
"bv_trace_pair",

"local_grad",
"interp",
"inverse_mass",
"local_d_dx",
"local_div",

"weak_local_grad",
"local_grad",
"local_interior_trace_pair",
"mass",
"nodal_max",
"nodal_max_loc",
"nodal_min",
"nodal_min_loc",
"nodal_sum",
"nodal_sum_loc",
"norm",
"project",
"project_tracepair",
"tracepair_with_discr_tag",
"weak_local_d_dx",
"weak_local_div",

"mass",
"inverse_mass",
"face_mass",
"weak_local_grad",
)


Expand Down
4 changes: 2 additions & 2 deletions grudge/projection.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,8 @@

def project(
dcoll: DiscretizationCollection,
src: "ConvertibleToDOFDesc",
tgt: "ConvertibleToDOFDesc", vec) -> ArrayOrContainer:
src: ConvertibleToDOFDesc,
tgt: ConvertibleToDOFDesc, vec) -> ArrayOrContainer:
"""Project from one discretization to another, e.g. from the
volume to the boundary, or from the base to the an overintegrated
quadrature discretization.
Expand Down
10 changes: 5 additions & 5 deletions grudge/reductions.py
Original file line number Diff line number Diff line change
Expand Up @@ -352,7 +352,7 @@ def _apply_elementwise_reduction(
)
else:
@memoize_in(actx, (_apply_elementwise_reduction, dd,
"elementwise_%s_prg" % op_name))
f"elementwise_{op_name}_prg"))
def elementwise_prg():
# FIXME: This computes the reduction value redundantly for each
# output DOF.
Expand All @@ -361,10 +361,10 @@ def elementwise_prg():
"{[iel]: 0 <= iel < nelements}",
"{[idof, jdof]: 0 <= idof, jdof < ndofs}"
],
"""
result[iel, idof] = %s(jdof, operand[iel, jdof])
""" % op_name,
name="grudge_elementwise_%s_knl" % op_name
f"""
result[iel, idof] = {op_name}(jdof, operand[iel, jdof])
""",
name=f"grudge_elementwise_{op_name}_knl"
)
import loopy as lp
from meshmode.transform_metadata import (
Expand Down
10 changes: 5 additions & 5 deletions grudge/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
"""

from functools import partial
from typing import Any, Callable, Optional, Tuple, Union
from typing import Any, Callable

import numpy as np

Expand Down Expand Up @@ -82,7 +82,7 @@ def build_jacobian(

def map_subarrays(
f: Callable[[Any], Any],
in_shape: Tuple[int, ...], out_shape: Tuple[int, ...],
in_shape: tuple[int, ...], out_shape: tuple[int, ...],
ary: Any, *, return_nested: bool = False) -> Any:
"""
Apply a function *f* to subarrays of shape *in_shape* of an
Expand Down Expand Up @@ -175,10 +175,10 @@ def map_subarrays(

def rec_map_subarrays(
f: Callable[[Any], Any],
in_shape: Tuple[int, ...],
out_shape: Tuple[int, ...],
in_shape: tuple[int, ...],
out_shape: tuple[int, ...],
ary: ArrayOrContainer, *,
scalar_cls: Optional[Union[type, Tuple[type]]] = None,
scalar_cls: type | tuple[type] | None = None,
return_nested: bool = False) -> ArrayOrContainer:
r"""
Like :func:`map_subarrays`, but with support for
Expand Down
8 changes: 2 additions & 6 deletions grudge/trace_pair.py
Original file line number Diff line number Diff line change
Expand Up @@ -341,12 +341,8 @@ def interior_trace_pairs(
if volume_dd is None:
volume_dd = DD_VOLUME_ALL

return (
[local_interior_trace_pair(
dcoll, vec, volume_dd=volume_dd)]
+ cross_rank_trace_pairs(
dcoll, vec, comm_tag=comm_tag, volume_dd=volume_dd)
)
return [local_interior_trace_pair(dcoll, vec, volume_dd=volume_dd),
*cross_rank_trace_pairs(dcoll, vec, comm_tag=comm_tag, volume_dd=volume_dd)]

# }}}

Expand Down
Loading

0 comments on commit beab737

Please sign in to comment.