Skip to content

Commit

Permalink
add and fix more ruff rules
Browse files Browse the repository at this point in the history
  • Loading branch information
alexfikl committed Jul 7, 2024
1 parent 6b6e95a commit 865232b
Show file tree
Hide file tree
Showing 18 changed files with 99 additions and 84 deletions.
6 changes: 3 additions & 3 deletions pymbolic/algorithm.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ def fft(x, sign=1,
"instead. wrap_intermediate will stop working in 2023.",
DeprecationWarning, stacklevel=2)

def wrap_intermediate_with_level(level, x): # pylint: disable=function-redefined # noqa: E501
def wrap_intermediate_with_level(level, x): # pylint: disable=function-redefined
return wrap_intermediate(x)

if wrap_intermediate_with_level is None:
Expand Down Expand Up @@ -272,7 +272,7 @@ def csr_matrix_multiply(S, x): # noqa
result = numpy.empty_like(x)

for i in range(h):
result[i] = sum(S.data[idx]*x[S.indices[idx]] # noqa pylint:disable=unsupported-assignment-operation
result[i] = sum(S.data[idx]*x[S.indices[idx]] # pylint:disable=unsupported-assignment-operation
for idx in range(S.indptr[i], S.indptr[i+1]))

return result
Expand Down Expand Up @@ -326,7 +326,7 @@ def gaussian_elimination(mat, rhs):
for i in range(m):
g = gcd_many(*(
[a for a in mat[i] if a]
+ # noqa: W504
+
[a for a in rhs[i] if a]))

mat[i] //= g
Expand Down
3 changes: 2 additions & 1 deletion pymbolic/geometric_algebra/mapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
# This is experimental, undocumented, and could go away any second.
# Consider yourself warned.

from typing import ClassVar, Dict

from pymbolic.geometric_algebra import MultiVector
import pymbolic.geometric_algebra.primitives as prim
Expand Down Expand Up @@ -104,7 +105,7 @@ def map_derivative_source(self, expr):


class StringifyMapper(StringifyMapperBase):
AXES = {0: "x", 1: "y", 2: "z"}
AXES: ClassVar[Dict[int, str]] = {0: "x", 1: "y", 2: "z"}

def map_nabla(self, expr, enclosing_prec):
return f"∇[{expr.nabla_id}]"
Expand Down
4 changes: 3 additions & 1 deletion pymbolic/geometric_algebra/primitives.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@
# This is experimental, undocumented, and could go away any second.
# Consider yourself warned.

from typing import ClassVar, List

from pymbolic.primitives import Expression, Variable


Expand Down Expand Up @@ -84,7 +86,7 @@ class Derivative:
.. automethod:: dnabla
.. automethod:: resolve
"""
_next_id = [0]
_next_id: ClassVar[List[int]] = [0]

def __init__(self):
self.my_id = f"id{self._next_id[0]}"
Expand Down
16 changes: 6 additions & 10 deletions pymbolic/interop/ast.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,9 @@
"""

import ast
from typing import Any, ClassVar, Dict, List, Tuple, Type

import pymbolic.primitives as p
from typing import Tuple, List, Any
from pymbolic.typing import ExpressionT, ScalarT
from pymbolic.mapper import CachedMapper

Expand Down Expand Up @@ -112,7 +113,7 @@ def _neg(x):

class ASTToPymbolic(ASTMapper):

bin_op_map = {
bin_op_map: ClassVar[Dict[Type[ast.operator], Any]] = {
ast.Add: _add,
ast.Sub: _sub,
ast.Mult: _mult,
Expand All @@ -138,7 +139,7 @@ def map_BinOp(self, expr): # noqa

return op_constructor(self.rec(expr.left), self.rec(expr.right))

unary_op_map = {
unary_op_map: ClassVar[Dict[Type[ast.unaryop], Any]] = {
ast.Invert: _neg,
ast.Not: p.LogicalNot,
# ast.UAdd:
Expand All @@ -159,7 +160,7 @@ def map_IfExp(self, expr): # noqa
# (expr test, expr body, expr orelse)
return p.If(self.rec(expr.test), self.rec(expr.body), self.rec(expr.orelse))

comparison_op_map = {
comparison_op_map: ClassVar[Dict[Type[ast.compop], str]] = {
ast.Eq: "==",
ast.NotEq: "!=",
ast.Lt: "<",
Expand Down Expand Up @@ -279,15 +280,10 @@ def map_product(self, expr: p.Product) -> ast.expr:
return self._map_multi_children_op(expr.children, ast.Mult())

def map_constant(self, expr: ScalarT) -> ast.expr:
import sys
if isinstance(expr, bool):
return ast.NameConstant(expr)
else:
# needed because of https://bugs.python.org/issue36280
if sys.version_info < (3, 8):
return ast.Num(expr)
else:
return ast.Constant(expr, None)
return ast.Constant(expr, None)

def map_call(self, expr: p.Call) -> ast.expr:
return ast.Call(
Expand Down
2 changes: 1 addition & 1 deletion pymbolic/interop/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ def map_Derivative(self, expr): # noqa
def map_UnevaluatedExpr(self, expr): # noqa
return self.rec(expr.args[0])

def not_supported(self, expr): # noqa
def not_supported(self, expr):
if isinstance(expr, int):
return expr
elif getattr(expr, "is_Function", False):
Expand Down
14 changes: 9 additions & 5 deletions pymbolic/interop/maxima.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,13 @@
# http://trac.sagemath.org/sage_trac/browser/sage/interfaces/maxima.py

import re
import pytools
from sys import intern
from typing import ClassVar, List, Tuple

import numpy as np

from sys import intern
import pytools

from pymbolic.mapper.stringifier import StringifyMapper
from pymbolic.parser import Parser as ParserBase, FinalizedTuple

Expand Down Expand Up @@ -92,11 +95,12 @@ class MaximaParser(ParserBase):
imag_unit = intern("imag_unit")
euler_number = intern("euler_number")

lex_table = [
lex_table: ClassVar[List[Tuple[str, str]]] = [
(power_sym, pytools.lex.RE(r"\^")),
(imag_unit, pytools.lex.RE(r"%i")),
(euler_number, pytools.lex.RE(r"%e")),
] + ParserBase.lex_table
*ParserBase.lex_table
]

def parse_prefix(self, pstate):
pstate.expect_not_end()
Expand Down Expand Up @@ -212,7 +216,7 @@ def parse_postfix(self, pstate, min_precedence, left_exp):
new_el = self.parse_expression(pstate, p._PREC_COMMA)
if isinstance(left_exp, tuple) \
and not isinstance(left_exp, FinalizedTuple):
left_exp = left_exp + (new_el,)
left_exp = (*left_exp, new_el)
else:
left_exp = (left_exp, new_el)

Expand Down
2 changes: 1 addition & 1 deletion pymbolic/interop/symengine.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ def function_name(self, expr):
# For builtin functions
return type(expr).__name__

def not_supported(self, expr): # noqa
def not_supported(self, expr):
from symengine.lib.symengine_wrapper import \
PyFunction # pylint: disable=E0611
if isinstance(expr, PyFunction) and \
Expand Down
2 changes: 1 addition & 1 deletion pymbolic/interop/sympy.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ class PymbolicToSympyMapper(PymbolicToSympyLikeMapper):
sym = sympy

def raise_conversion_error(self, expr):
raise RuntimeError("do not know how to translate '{expr}' to sympy")
raise RuntimeError(f"do not know how to translate '{expr}' to sympy")

def map_subscript(self, expr):
return self.sym.Indexed(
Expand Down
40 changes: 18 additions & 22 deletions pymbolic/mapper/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,12 @@

from abc import ABC, abstractmethod
from typing import Any, Dict
import pymbolic.primitives as primitives

from immutabledict import immutabledict

import pymbolic.primitives as primitives


__doc__ = """
Basic dispatch
--------------
Expand Down Expand Up @@ -305,23 +308,18 @@ def combine(self, values):
raise NotImplementedError

def map_call(self, expr, *args, **kwargs):
return self.combine(
(self.rec(expr.function, *args, **kwargs),)
+ tuple([
self.rec(child, *args, **kwargs) for child in expr.parameters
])
)
return self.combine((
self.rec(expr.function, *args, **kwargs),
*[self.rec(child, *args, **kwargs) for child in expr.parameters]
))

def map_call_with_kwargs(self, expr, *args, **kwargs):
return self.combine(
(self.rec(expr.function, *args, **kwargs),)
+ tuple([
self.rec(child, *args, **kwargs)
for child in expr.parameters])
+ tuple([
self.rec(child, *args, **kwargs)
for child in expr.kw_parameters.values()])
)
return self.combine((
self.rec(expr.function, *args, **kwargs),
*[self.rec(child, *args, **kwargs) for child in expr.parameters],
*[self.rec(child, *args, **kwargs)
for child in expr.kw_parameters.values()]
))

def map_subscript(self, expr, *args, **kwargs):
return self.combine(
Expand Down Expand Up @@ -351,12 +349,10 @@ def map_power(self, expr, *args, **kwargs):
self.rec(expr.exponent, *args, **kwargs)))

def map_polynomial(self, expr, *args, **kwargs):
return self.combine(
(self.rec(expr.base, *args, **kwargs),)
+ tuple([
self.rec(coeff, *args, **kwargs) for exp, coeff in expr.data
])
)
return self.combine((
self.rec(expr.base, *args, **kwargs),
*[self.rec(coeff, *args, **kwargs) for exp, coeff in expr.data]
))

def map_left_shift(self, expr, *args, **kwargs):
return self.combine((
Expand Down
2 changes: 1 addition & 1 deletion pymbolic/mapper/constant_folder.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ def fold(self, expr, klass, op, constructor):
if constants:
from functools import reduce
constant = reduce(op, constants)
return constructor(tuple([constant]+nonconstants))
return constructor((constant, *nonconstants))
else:
return constructor(tuple(nonconstants))

Expand Down
2 changes: 1 addition & 1 deletion pymbolic/mapper/optimize.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ def _get_def_from_ast_container(container, name, node_type):

@lru_cache
def _get_ast_for_file(filename):
with open(filename, "r") as inf:
with open(filename) as inf:
return ast.parse(inf.read(), filename)


Expand Down
9 changes: 6 additions & 3 deletions pymbolic/mapper/stringifier.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,11 @@
THE SOFTWARE.
"""

from pymbolic.mapper import Mapper, CachedMapper
from typing import ClassVar, Dict

import pymbolic.primitives as p
from pymbolic.mapper import Mapper, CachedMapper


__doc__ = """
.. _prec-constants:
Expand Down Expand Up @@ -161,7 +164,7 @@ def map_call_with_kwargs(self, expr, enclosing_prec, *args, **kwargs):
self.rec(ch, PREC_NONE, *args, **kwargs)
for ch in expr.parameters
])
+ # noqa: W504
+
tuple([
"{}={}".format(name, self.rec(ch, PREC_NONE, *args, **kwargs))
for name, ch in expr.kw_parameters.items()
Expand Down Expand Up @@ -623,7 +626,7 @@ def map_product(self, expr, enclosing_prec, *args, **kwargs):

class LaTeXMapper(StringifyMapper):

COMPARISON_OP_TO_LATEX = {
COMPARISON_OP_TO_LATEX: ClassVar[Dict[str, str]] = {
"==": r"=",
"!=": r"\ne",
"<=": r"\le",
Expand Down
9 changes: 5 additions & 4 deletions pymbolic/mapper/unifier.py
Original file line number Diff line number Diff line change
Expand Up @@ -391,7 +391,7 @@ def partitions(s, k):
return
for subset in map(set, subsets(s, len(s) - k + 1)):
for partition in partitions(s - subset, k - 1):
yield [subset] + partition
yield [subset, *partition]

for partition in partitions(
other_leftovers, len(plain_var_candidates)):
Expand All @@ -410,9 +410,10 @@ def partitions(s, k):
# urecs was not merged in, do it here.
yield from unify_many(urecs, result)

for urec in match_children(
UnificationRecord([]), 0, set(range(len(other.children)))):
yield urec
yield from match_children(
UnificationRecord([]),
0,
set(range(len(other.children))))

def map_sum(self, expr, other, unis):
from pymbolic.primitives import flattened_sum
Expand Down
Loading

0 comments on commit 865232b

Please sign in to comment.