Skip to content

Commit

Permalink
Enable Ruff SIM rules
Browse files Browse the repository at this point in the history
  • Loading branch information
inducer committed Jan 23, 2025
1 parent 9c5289d commit c8c7552
Show file tree
Hide file tree
Showing 17 changed files with 74 additions and 119 deletions.
5 changes: 1 addition & 4 deletions pymbolic/algorithm.py
Original file line number Diff line number Diff line change
Expand Up @@ -344,10 +344,7 @@ def reduced_row_echelon_form(
"This will stop being supported in 2025.",
DeprecationWarning, stacklevel=2)

if integral:
div_func = operator.floordiv
else:
div_func = operator.truediv
div_func = operator.floordiv if integral else operator.truediv

i = 0
j = 0
Expand Down
11 changes: 5 additions & 6 deletions pymbolic/geometric_algebra/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
THE SOFTWARE.
"""

import contextlib
from abc import ABC, abstractmethod
from collections.abc import Callable, Iterable, Mapping, Sequence
from dataclasses import dataclass
Expand Down Expand Up @@ -361,7 +362,7 @@ def generic_blade_product_weight(a_bits, b_bits, space):
def orthogonal_blade_product_weight(a_bits, b_bits, space):
shared_bits = a_bits & b_bits

if shared_bits == a_bits or shared_bits == b_bits:
if shared_bits in (a_bits, b_bits):
return _shared_metric_coeff(shared_bits, space)
else:
return 0
Expand Down Expand Up @@ -588,7 +589,7 @@ def __init__(

from pytools import single_valued

if data_dict and single_valued(isinstance(k, tuple) for k in data_dict.keys()):
if data_dict and single_valued(isinstance(k, tuple) for k in data_dict):
# data is in non-normalized non-bits tuple form
new_data: dict[int, CoeffT] = {}
for basis_indices, coeff in data_dict.items():
Expand Down Expand Up @@ -630,10 +631,8 @@ def stringify(self, coeff_stringifier, enclosing_prec):

strifier = None
if coeff_stringifier is None:
try:
with contextlib.suppress(AttributeError):
strifier = coeff.stringifier()()
except AttributeError:
pass
else:
strifier = coeff_stringifier

Expand Down Expand Up @@ -1024,7 +1023,7 @@ def get_pure_grade(self):

result = None

for bits in self.data.keys():
for bits in self.data:
grade = bits.bit_count()
if result is None:
result = grade
Expand Down
23 changes: 10 additions & 13 deletions pymbolic/interop/maxima.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ def parse_postfix(self, pstate, min_precedence, left_exp):

next_tag = pstate.next_tag()

if next_tag is p._openpar and p._PREC_CALL > min_precedence:
if next_tag is p._openpar and min_precedence < p._PREC_CALL:
pstate.advance()
pstate.expect_not_end()
if next_tag is p._closepar:
Expand All @@ -170,38 +170,38 @@ def parse_postfix(self, pstate, min_precedence, left_exp):
left_exp = primitives.Call(left_exp, args)

did_something = True
elif next_tag is p._openbracket and p._PREC_CALL > min_precedence:
elif next_tag is p._openbracket and min_precedence < p._PREC_CALL:
pstate.advance()
pstate.expect_not_end()
left_exp = primitives.Subscript(left_exp, self.parse_expression(pstate))
pstate.expect(p._closebracket)
pstate.advance()
did_something = True
elif next_tag is p._dot and p._PREC_CALL > min_precedence:
elif next_tag is p._dot and min_precedence < p._PREC_CALL:
pstate.advance()
pstate.expect(p._identifier)
left_exp = primitives.Lookup(left_exp, pstate.next_str())
pstate.advance()
did_something = True
elif next_tag is p._plus and p._PREC_PLUS > min_precedence:
elif next_tag is p._plus and min_precedence < p._PREC_PLUS:
pstate.advance()
left_exp += self.parse_expression(pstate, p._PREC_PLUS)
did_something = True
elif next_tag is p._minus and p._PREC_PLUS > min_precedence:
elif next_tag is p._minus and min_precedence < p._PREC_PLUS:
pstate.advance()
left_exp -= self.parse_expression(pstate, p._PREC_PLUS)
did_something = True
elif next_tag is p._times and p._PREC_TIMES > min_precedence:
elif next_tag is p._times and min_precedence < p._PREC_TIMES:
pstate.advance()
left_exp *= self.parse_expression(pstate, p._PREC_TIMES)
did_something = True
elif next_tag is p._over and p._PREC_TIMES > min_precedence:
elif next_tag is p._over and min_precedence < p._PREC_TIMES:
pstate.advance()
from pymbolic.primitives import Quotient
left_exp = Quotient(
left_exp, self.parse_expression(pstate, p._PREC_TIMES))
did_something = True
elif next_tag is self.power_sym and p._PREC_POWER > min_precedence:
elif next_tag is self.power_sym and min_precedence < p._PREC_POWER:
pstate.advance()
exponent = self.parse_expression(pstate, p._PREC_POWER)
if left_exp == np.e:
Expand All @@ -210,7 +210,7 @@ def parse_postfix(self, pstate, min_precedence, left_exp):
else:
left_exp **= exponent
did_something = True
elif next_tag is p._comma and p._PREC_COMMA > min_precedence:
elif next_tag is p._comma and min_precedence < p._PREC_COMMA:
# The precedence makes the comma left-associative.

pstate.advance()
Expand Down Expand Up @@ -244,10 +244,7 @@ def set_debug(level):
def _strify_assignments_and_expr(assignments, expr):
strify = MaximaStringifyMapper()

if isinstance(expr, str):
expr_str = expr
else:
expr_str = strify(expr)
expr_str = expr if isinstance(expr, str) else strify(expr)

def make_setup(assignment):
if isinstance(assignment, str):
Expand Down
2 changes: 1 addition & 1 deletion pymbolic/mapper/coefficient.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ def map_quotient(self, expr: p.Quotient) -> CoeffsT:
if len(d_den) > 1 or 1 not in d_den:
raise RuntimeError("nonlinear expression")
val = d_den[1]
for k in d_num.keys():
for k in d_num:
d_num[k] = p.flattened_product((d_num[k], Quotient(1, val)))
return d_num

Expand Down
5 changes: 2 additions & 3 deletions pymbolic/mapper/collector.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,9 +86,8 @@ def exponent(term: Expression) -> ArithmeticExpression:

if isinstance(mul_term, Product):
terms: Sequence[Expression] = mul_term.children
elif isinstance(mul_term, Power | AlgebraicLeaf):
terms = [mul_term]
elif not bool(self.get_dependencies(mul_term)):
elif (isinstance(mul_term, Power | AlgebraicLeaf)
or not bool(self.get_dependencies(mul_term))):
terms = [mul_term]
else:
raise RuntimeError("split_term expects a multiplicative term")
Expand Down
5 changes: 1 addition & 4 deletions pymbolic/mapper/distributor.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,10 +92,7 @@ def dist(prod):
sum = prod.children[len(leading)]
assert isinstance(sum, p.Sum)
rest = prod.children[len(leading)+1:]
if rest:
rest = dist(p.Product(rest))
else:
rest = 1
rest = dist(p.Product(rest)) if rest else 1

result = self.collect(pymbolic.flattened_sum([
pymbolic.flattened_product(leading) * dist(sumchild*rest)
Expand Down
12 changes: 5 additions & 7 deletions pymbolic/mapper/flattener.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,10 +95,9 @@ def map_floor_div(self, expr: p.FloorDiv) -> Expression:
r_den = self.rec_arith(expr.denominator)
if p.is_zero(r_num):
return 0
if p.is_zero(r_den - 1):
# It's the floor function in this case.
if self.is_expr_integer_valued(r_num):
return r_num
if p.is_zero(r_den - 1) and self.is_expr_integer_valued(r_num):
# With a denominator of 1, it's the floor function in this case.
return r_num

return expr.__class__(r_num, r_den)

Expand All @@ -108,10 +107,9 @@ def map_remainder(self, expr: p.Remainder) -> Expression:
assert p.is_arithmetic_expression(r_den)
if p.is_zero(r_num):
return 0
if p.is_zero(r_den - 1):
if p.is_zero(r_den - 1) and self.is_expr_integer_valued(r_num):
# mod 1 is zero for integers, however 3.1 % 1 == .1
if self.is_expr_integer_valued(r_num):
return 0
return 0

return expr.__class__(r_num, r_den)

Expand Down
18 changes: 7 additions & 11 deletions pymbolic/mapper/optimize.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
"""

import ast
import contextlib
from functools import cached_property, lru_cache
from typing import TYPE_CHECKING, TextIO, TypeVar, cast

Expand Down Expand Up @@ -98,14 +99,10 @@ def _get_ast_for_method(f: Callable) -> ast.FunctionDef:


def _replace(obj, **kwargs):
try:
with contextlib.suppress(AttributeError):
kwargs["lineno"] = obj.lineno
except AttributeError:
pass
try:
with contextlib.suppress(AttributeError):
kwargs["col_offsets"] = obj.col_offsets
except AttributeError:
pass

return type(obj)(**{
name: kwargs.get(name, getattr(obj, name))
Expand Down Expand Up @@ -384,11 +381,10 @@ def wrapper(cls: type) -> type:
for name, value in import_module(mod_name).__dict__.items():
if name.startswith("__"):
continue
if name in compile_dict:
if compile_dict[name] is not value:
raise ValueError(
"symbol disagreement in environment: "
f"'{name}', most recently from '{mod_name}'")
if name in compile_dict and compile_dict[name] is not value:
raise ValueError(
"symbol disagreement in environment: "
f"'{name}', most recently from '{mod_name}'")
compile_dict[name] = value

# }}}
Expand Down
8 changes: 2 additions & 6 deletions pymbolic/mapper/stringifier.py
Original file line number Diff line number Diff line change
Expand Up @@ -639,10 +639,7 @@ def map_common_subexpression(
) -> str:
from pymbolic.primitives import CommonSubexpression

if type(expr) is CommonSubexpression:
type_name = "CSE"
else:
type_name = type(expr).__name__
type_name = "CSE" if type(expr) is CommonSubexpression else type(expr).__name__

return self.format(
"%s(%s)", type_name, self.rec(expr.child, PREC_NONE, *args, **kwargs)
Expand Down Expand Up @@ -913,11 +910,10 @@ def map_product(
) -> str:
entries = []
i = 0
from pymbolic.primitives import is_zero

while i < len(expr.children):
child = expr.children[i]
if False and is_zero(child + 1) and i + 1 < len(expr.children):
if False:
# NOTE: That space needs to be there.
# Otherwise two unary minus signs merge into a pre-decrement.
entries.append(
Expand Down
Loading

0 comments on commit c8c7552

Please sign in to comment.