diff --git a/examples/advection/surface.py b/examples/advection/surface.py index 0b9ddcdd..554df7c8 100644 --- a/examples/advection/surface.py +++ b/examples/advection/surface.py @@ -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() @@ -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: diff --git a/examples/advection/var-velocity.py b/examples/advection/var-velocity.py index 6e8b45d9..9c230106 100644 --- a/examples/advection/var-velocity.py +++ b/examples/advection/var-velocity.py @@ -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, "-") @@ -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) diff --git a/examples/advection/weak.py b/examples/advection/weak.py index e831c4a6..270574fc 100644 --- a/examples/advection/weak.py +++ b/examples/advection/weak.py @@ -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, "-") @@ -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) diff --git a/grudge/array_context.py b/grudge/array_context.py index 8bd51c97..6fc44bf6 100644 --- a/grudge/array_context.py +++ b/grudge/array_context.py @@ -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: @@ -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: @@ -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: diff --git a/grudge/discretization.py b/grudge/discretization.py index 61423a96..7d51e514 100644 --- a/grudge/discretization.py +++ b/grudge/discretization.py @@ -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 diff --git a/grudge/dof_desc.py b/grudge/dof_desc.py index 16232a54..da1f4a41 100644 --- a/grudge/dof_desc.py +++ b/grudge/dof_desc.py @@ -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.""" @@ -147,7 +147,7 @@ class BoundaryDomainTag: # {{{ discretization tag -class _DiscretizationTag: # noqa: N801 +class _DiscretizationTag: pass @@ -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") diff --git a/grudge/geometry/__init__.py b/grudge/geometry/__init__.py index ae0a393c..979915ef 100644 --- a/grudge/geometry/__init__.py +++ b/grudge/geometry/__init__.py @@ -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", diff --git a/grudge/models/advection.py b/grudge/models/advection.py index 999fc2c9..c5cba779 100644 --- a/grudge/models/advection.py +++ b/grudge/models/advection.py @@ -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: @@ -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) diff --git a/grudge/models/em.py b/grudge/models/em.py index 67884a54..c7c5a725 100644 --- a/grudge/models/em.py +++ b/grudge/models/em.py @@ -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 @@ -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 ) # }}} @@ -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 ) # }}} @@ -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) ) # }}} @@ -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) ) # }}} diff --git a/grudge/models/wave.py b/grudge/models/wave.py index a7e484c7..e1c64593 100644 --- a/grudge/models/wave.py +++ b/grudge/models/wave.py @@ -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 @@ -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 diff --git a/grudge/op.py b/grudge/op.py index c640e71c..5052d61a 100644 --- a/grudge/op.py +++ b/grudge/op.py @@ -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", ) diff --git a/grudge/projection.py b/grudge/projection.py index abd37b65..d5ebdd68 100644 --- a/grudge/projection.py +++ b/grudge/projection.py @@ -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. diff --git a/grudge/reductions.py b/grudge/reductions.py index 45b7e150..48780078 100644 --- a/grudge/reductions.py +++ b/grudge/reductions.py @@ -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. @@ -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 ( diff --git a/grudge/tools.py b/grudge/tools.py index 69fd56fa..e12ffeb3 100644 --- a/grudge/tools.py +++ b/grudge/tools.py @@ -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 @@ -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 @@ -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 diff --git a/grudge/trace_pair.py b/grudge/trace_pair.py index d92b3e56..6480cadb 100644 --- a/grudge/trace_pair.py +++ b/grudge/trace_pair.py @@ -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)] # }}} diff --git a/pyproject.toml b/pyproject.toml index 2a257821..293bacf3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -12,6 +12,9 @@ extend-select = [ "NPY", # numpy "Q", # flake8-quotes "W", # pycodestyle + "RUF", + "UP", + "G", ] extend-ignore = [ "C90", # McCabe complexity @@ -21,10 +24,12 @@ extend-ignore = [ "E242", # tab after comma "E402", # module level import not at the top of file ] + [tool.ruff.lint.per-file-ignores] "test/test_grudge.py" = ["B023"] "test/test_op.py" = ["B023"] "test/test_euler_model.py" = ["B023"] +"examples/wave/*.py" = ["G004"] [tool.ruff.lint.flake8-quotes] docstring-quotes = "double" diff --git a/setup.py b/setup.py index 17d6f895..3c9e6488 100644 --- a/setup.py +++ b/setup.py @@ -6,7 +6,7 @@ def main(): version_dict = {} init_filename = "grudge/version.py" - exec(compile(open(init_filename, "r").read(), init_filename, "exec"), + exec(compile(open(init_filename).read(), init_filename, "exec"), version_dict) setup( @@ -16,7 +16,7 @@ def main(): "Discretize discontinuous Galerkin operators quickly, " "on heterogeneous hardware" ), - long_description=open("README.rst", "rt").read(), + long_description=open("README.rst").read(), author="Andreas Kloeckner", author_email="inform@tiker.net", license="MIT", diff --git a/test/mesh_data.py b/test/mesh_data.py index 4190f2f0..58c9b80a 100644 --- a/test/mesh_data.py +++ b/test/mesh_data.py @@ -22,7 +22,7 @@ def get_mesh( class _GmshMeshBuilder(MeshBuilder): - resolutions = [None] + resolutions: ClassVar[Sequence[Hashable]] = [None] def __init__(self, filename: str) -> None: self._mesh_fn = filename @@ -43,7 +43,7 @@ class GmshMeshBuilder3D(_GmshMeshBuilder): class Curve2DMeshBuilder(MeshBuilder): ambient_dim = 2 - resolutions = [16, 32, 64, 128] + resolutions: ClassVar[Sequence[Hashable]] = [16, 32, 64, 128] def get_mesh(self, resolution, mesh_order=None): if mesh_order is None: @@ -76,7 +76,7 @@ def curve_fn(self): class SphereMeshBuilder(MeshBuilder): ambient_dim = 3 - resolutions = [0, 1, 2, 3] + resolutions: ClassVar[Sequence[Hashable]] = [0, 1, 2, 3] radius: float @@ -92,7 +92,7 @@ def get_mesh(self, resolution, mesh_order=4): class SpheroidMeshBuilder(MeshBuilder): ambient_dim = 3 - resolutions = [0, 1, 2, 3] + resolutions: ClassVar[Sequence[Hashable]] = [0, 1, 2, 3] radius: float aspect_ratio: float @@ -111,7 +111,7 @@ def get_mesh(self, resolution, mesh_order=4): class _BoxMeshBuilderBase(MeshBuilder): - resolutions = [4, 8, 16] + resolutions: ClassVar[Sequence[Hashable]] = [4, 8, 16] mesh_order = 1 a = (-0.5, -0.5, -0.5) @@ -140,7 +140,7 @@ class BoxMeshBuilder3D(_BoxMeshBuilderBase): class WarpedRectMeshBuilder(MeshBuilder): - resolutions = [4, 6, 8] + resolutions: ClassVar[Sequence[Hashable]] = [4, 6, 8] def __init__(self, dim): self.dim = dim diff --git a/test/test_dt_utils.py b/test/test_dt_utils.py index a05ce54d..5d99e5ad 100644 --- a/test/test_dt_utils.py +++ b/test/test_dt_utils.py @@ -64,7 +64,7 @@ def test_geometric_factors_regular_refinement(actx_factory, name): elif name == "box3d": builder = mesh_data.BoxMeshBuilder3D() else: - raise ValueError("unknown geometry name: %s" % name) + raise ValueError(f"unknown geometry name: {name}") # }}} @@ -106,7 +106,7 @@ def test_non_geometric_factors(actx_factory, name): elif name == "box3d": builder = mesh_data.BoxMeshBuilder3D() else: - raise ValueError("unknown geometry name: %s" % name) + raise ValueError(f"unknown geometry name: {name}") # }}} diff --git a/test/test_grudge.py b/test/test_grudge.py index 21097d46..9e78c0f7 100644 --- a/test/test_grudge.py +++ b/test/test_grudge.py @@ -182,7 +182,7 @@ def test_mass_surface_area(actx_factory, name): builder = mesh_data.BoxMeshBuilder3D() surface_area = 1.0 else: - raise ValueError("unknown geometry name: %s" % name) + raise ValueError(f"unknown geometry name: {name}") # }}} @@ -205,8 +205,8 @@ def test_mass_surface_area(actx_factory, name): ones_volm = volume_discr.zeros(actx) + 1 approx_surface_area = actx.to_numpy(op.integral(dcoll, dd, ones_volm)) - logger.info("surface: got {:.5e} / expected {:.5e}".format( - approx_surface_area, surface_area)) + logger.info( + f"surface: got {approx_surface_area:.5e} / expected {surface_area:.5e}") # noqa: G004 area_error = abs(approx_surface_area - surface_area) / abs(surface_area) # }}} @@ -267,7 +267,7 @@ def test_mass_operator_inverse(actx_factory, name): elif name == "gh-339-4": builder = mesh_data.GmshMeshBuilder3D("gh-339.msh") else: - raise ValueError("unknown geometry name: %s" % name) + raise ValueError(f"unknown geometry name: {name}") # }}} @@ -348,7 +348,7 @@ def test_face_normal_surface(actx_factory, mesh_name): elif mesh_name == "spheroid": builder = mesh_data.SpheroidMeshBuilder() else: - raise ValueError("unknown mesh name: %s" % mesh_name) + raise ValueError(f"unknown mesh name: {mesh_name}") order = 4 mesh = builder.get_mesh(builder.resolutions[0], order) @@ -612,7 +612,7 @@ def test_surface_divergence_theorem(actx_factory, mesh_name, visualize=False): elif mesh_name == "sphere": builder = mesh_data.SphereMeshBuilder(radius=1.0) else: - raise ValueError("unknown mesh name: %s" % mesh_name) + raise ValueError(f"unknown mesh name: {mesh_name}") # }}} diff --git a/test/test_op.py b/test/test_op.py index 41c7776b..18faedc6 100644 --- a/test/test_op.py +++ b/test/test_op.py @@ -161,7 +161,7 @@ def get_flux(u_tpair): -op.weak_local_grad(dcoll, vol_dd_quad, op.project(dcoll, vol_dd_base, vol_dd_quad, u), nested=nested) - + # noqa: W504 + + op.face_mass(dcoll, allfaces_dd_quad, sum(get_flux( @@ -287,7 +287,7 @@ def get_flux(u_tpair): elif form == "weak": div_u = op.inverse_mass(dcoll, -op.weak_local_div(dcoll, u) - + # noqa: W504 + + op.face_mass(dcoll, dd_allfaces, # Note: no boundary flux terms here because u_ext == u_int == 0