Skip to content

Commit eb489dd

Browse files
committed
Format code with ruff (56 files)
1 parent f1fbc07 commit eb489dd

57 files changed

Lines changed: 2521 additions & 1682 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

src/mathviz/cli.py

Lines changed: 133 additions & 68 deletions
Large diffs are not rendered by default.

src/mathviz/compiler/__init__.py

Lines changed: 15 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -271,7 +271,9 @@ def __str__(self) -> str:
271271
lines.append(f" JIT Compatible: {self.is_jit_compatible}")
272272
if self.parallelizable_loops:
273273
parallel_count = sum(1 for l in self.parallelizable_loops if l.is_parallelizable)
274-
lines.append(f" Parallelizable Loops: {parallel_count}/{len(self.parallelizable_loops)}")
274+
lines.append(
275+
f" Parallelizable Loops: {parallel_count}/{len(self.parallelizable_loops)}"
276+
)
275277
if self.suggested_optimizations:
276278
lines.append(" Suggested Optimizations:")
277279
for opt in self.suggested_optimizations:
@@ -321,7 +323,9 @@ def __str__(self) -> str:
321323
if self.function_analysis:
322324
lines.append(f" Functions Analyzed: {len(self.function_analysis)}")
323325
if self.call_graph:
324-
lines.append(f" Call Graph: {len(self.call_graph.nodes)} nodes, {len(self.call_graph.edges)} edges")
326+
lines.append(
327+
f" Call Graph: {len(self.call_graph.nodes)} nodes, {len(self.call_graph.edges)} edges"
328+
)
325329
lines.append(f" Generated Code: {len(self.python_code)} characters")
326330
return "\n".join(lines)
327331

@@ -332,14 +336,14 @@ def has_errors(self) -> bool:
332336
def get_jit_compatible_functions(self) -> list[str]:
333337
"""Get names of all JIT-compatible functions."""
334338
return [
335-
name for name, analysis in self.function_analysis.items()
336-
if analysis.is_jit_compatible
339+
name for name, analysis in self.function_analysis.items() if analysis.is_jit_compatible
337340
]
338341

339342
def get_parallelizable_functions(self) -> list[str]:
340343
"""Get names of functions with parallelizable loops."""
341344
return [
342-
name for name, analysis in self.function_analysis.items()
345+
name
346+
for name, analysis in self.function_analysis.items()
343347
if any(loop.is_parallelizable for loop in analysis.parallelizable_loops)
344348
]
345349

@@ -507,9 +511,7 @@ def compile(self, source: str, filename: str = "<string>") -> CompilationResult:
507511
return result
508512

509513
if type_errors:
510-
warnings.append(
511-
f"Type checking found {len(type_errors)} error(s)"
512-
)
514+
warnings.append(f"Type checking found {len(type_errors)} error(s)")
513515

514516
# Stage 4: Build Call Graph
515517
call_graph_builder = CallGraphBuilder()
@@ -625,9 +627,7 @@ def _aggregate_function_analysis(
625627
# Get parallelization analysis
626628
loop_analyses: list[LoopAnalysis] = []
627629
if func_name in parallel_results:
628-
loop_analyses = [
629-
analysis for _, analysis in parallel_results[func_name]
630-
]
630+
loop_analyses = [analysis for _, analysis in parallel_results[func_name]]
631631

632632
# Determine JIT compatibility
633633
is_jit_compatible = is_jit_safe(purity_info) and not purity_info.has_manim_calls()
@@ -674,8 +674,7 @@ def _generate_optimization_suggestions(
674674
)
675675
if analysis.purity.has_manim_calls():
676676
suggestions.append(
677-
f"Function '{analysis.name}' contains Manim calls; "
678-
"move to scene methods"
677+
f"Function '{analysis.name}' contains Manim calls; move to scene methods"
679678
)
680679

681680
# Complexity-based suggestions
@@ -700,14 +699,10 @@ def _generate_optimization_suggestions(
700699
f"reduction variables: {', '.join(loop_analysis.reduction_vars)}"
701700
)
702701
else:
703-
suggestions.append(
704-
f"Loop in '{analysis.name}' can be parallelized with prange"
705-
)
702+
suggestions.append(f"Loop in '{analysis.name}' can be parallelized with prange")
706703
else:
707704
for transform in loop_analysis.suggested_transforms:
708-
suggestions.append(
709-
f"In '{analysis.name}': {transform}"
710-
)
705+
suggestions.append(f"In '{analysis.name}': {transform}")
711706

712707

713708
# =============================================================================
@@ -736,7 +731,7 @@ def compile_source(source: str, optimize: bool = True) -> str:
736731
optimize=optimize,
737732
check_types=True,
738733
analyze_complexity=False, # Skip for simple compilation
739-
auto_parallelize=False, # Skip for simple compilation
734+
auto_parallelize=False, # Skip for simple compilation
740735
strict=False,
741736
)
742737
result = pipeline.compile(source)

src/mathviz/compiler/ast_nodes.py

Lines changed: 33 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -595,15 +595,15 @@ class BinaryOperator(Enum):
595595
OR = auto()
596596

597597
# Set operations (mathematical)
598-
ELEMENT_OF = auto() # ∈
599-
NOT_ELEMENT_OF = auto() # ∉
600-
SUBSET = auto() # ⊆
601-
SUPERSET = auto() # ⊇
602-
PROPER_SUBSET = auto() # ⊂
598+
ELEMENT_OF = auto() # ∈
599+
NOT_ELEMENT_OF = auto() # ∉
600+
SUBSET = auto() # ⊆
601+
SUPERSET = auto() # ⊇
602+
PROPER_SUBSET = auto() # ⊂
603603
PROPER_SUPERSET = auto() # ⊃
604-
UNION = auto() # ∪
605-
INTERSECTION = auto() # ∩
606-
SET_DIFF = auto() # ∖
604+
UNION = auto() # ∪
605+
INTERSECTION = auto() # ∩
606+
SET_DIFF = auto() # ∖
607607

608608
# Membership (Python-style)
609609
IN = auto()
@@ -613,9 +613,9 @@ class BinaryOperator(Enum):
613613
class UnaryOperator(Enum):
614614
"""Unary operator types."""
615615

616-
NEG = auto() # -
617-
NOT = auto() # not
618-
POS = auto() # +
616+
NEG = auto() # -
617+
NOT = auto() # not
618+
POS = auto() # +
619619

620620

621621
@dataclass(frozen=True, slots=True)
@@ -1013,7 +1013,7 @@ class RangePattern(Pattern):
10131013
"""
10141014

10151015
start: Expression # Inclusive start
1016-
end: Expression # Exclusive end (or inclusive with ..=)
1016+
end: Expression # Exclusive end (or inclusive with ..=)
10171017
inclusive: bool = False # True for ..= (inclusive end)
10181018
location: Optional[SourceLocation] = None
10191019

@@ -1332,13 +1332,14 @@ def accept(self, visitor: ASTVisitor) -> Any:
13321332

13331333
class JitMode(Enum):
13341334
"""JIT compilation modes for Numba optimization."""
1335-
NONE = "none" # No JIT compilation
1336-
JIT = "jit" # Standard @jit decorator
1337-
NJIT = "njit" # @njit (nopython=True, faster)
1338-
VECTORIZE = "vectorize" # @vectorize for ufuncs
1335+
1336+
NONE = "none" # No JIT compilation
1337+
JIT = "jit" # Standard @jit decorator
1338+
NJIT = "njit" # @njit (nopython=True, faster)
1339+
VECTORIZE = "vectorize" # @vectorize for ufuncs
13391340
GUVECTORIZE = "guvectorize" # @guvectorize for generalized ufuncs
1340-
STENCIL = "stencil" # @stencil for stencil computations
1341-
CFUNC = "cfunc" # @cfunc for C-callable functions
1341+
STENCIL = "stencil" # @stencil for stencil computations
1342+
CFUNC = "cfunc" # @cfunc for C-callable functions
13421343

13431344

13441345
@dataclass(frozen=True, slots=True)
@@ -1348,14 +1349,15 @@ class JitOptions:
13481349
13491350
These map directly to Numba decorator arguments.
13501351
"""
1352+
13511353
mode: JitMode = JitMode.NONE
1352-
nopython: bool = True # Compile in nopython mode (faster, stricter)
1353-
nogil: bool = False # Release GIL (for parallel execution)
1354-
cache: bool = True # Cache compiled function to disk
1355-
parallel: bool = False # Enable automatic parallelization
1356-
fastmath: bool = False # Use fast math (less precise, faster)
1357-
boundscheck: bool = False # Check array bounds (slower but safer)
1358-
inline: str = "never" # Inlining: "never", "always", or "recursive"
1354+
nopython: bool = True # Compile in nopython mode (faster, stricter)
1355+
nogil: bool = False # Release GIL (for parallel execution)
1356+
cache: bool = True # Cache compiled function to disk
1357+
parallel: bool = False # Enable automatic parallelization
1358+
fastmath: bool = False # Use fast math (less precise, faster)
1359+
boundscheck: bool = False # Check array bounds (slower but safer)
1360+
inline: str = "never" # Inlining: "never", "always", or "recursive"
13591361

13601362
def to_decorator_args(self) -> str:
13611363
"""Generate the decorator argument string."""
@@ -1457,6 +1459,7 @@ def get_test_description(self) -> str | None:
14571459
for attr in self.attributes:
14581460
if attr.name == "test" and attr.arguments:
14591461
from mathviz.compiler.ast_nodes import StringLiteral
1462+
14601463
if isinstance(attr.arguments[0], StringLiteral):
14611464
return attr.arguments[0].value
14621465
return None
@@ -1890,7 +1893,7 @@ class Visibility(Enum):
18901893
"""Visibility modifier for struct fields and methods."""
18911894

18921895
PRIVATE = auto() # Default visibility
1893-
PUBLIC = auto() # pub keyword
1896+
PUBLIC = auto() # pub keyword
18941897

18951898

18961899
@dataclass(frozen=True, slots=True)
@@ -2028,7 +2031,9 @@ class ImplBlock(Statement):
20282031

20292032
target_type: str # The struct/type being implemented
20302033
trait_name: Optional[str] = None # None for inherent impl, trait name for trait impl
2031-
trait_type_args: tuple[TypeAnnotation, ...] = () # Type args for trait (e.g., Float in Mul<Float>)
2034+
trait_type_args: tuple[
2035+
TypeAnnotation, ...
2036+
] = () # Type args for trait (e.g., Float in Mul<Float>)
20322037
methods: tuple[Method, ...] = ()
20332038
associated_types: tuple[AssociatedType, ...] = () # Associated type declarations
20342039
type_params: tuple["TypeParameter", ...] = ()
@@ -2045,6 +2050,7 @@ def is_generic(self) -> bool:
20452050
def is_operator_impl(self) -> bool:
20462051
"""Check if this impl block is for an operator trait."""
20472052
from mathviz.compiler.operators import OPERATOR_TRAITS
2053+
20482054
return self.trait_name is not None and self.trait_name in OPERATOR_TRAITS
20492055

20502056
def accept(self, visitor: ASTVisitor) -> Any:

src/mathviz/compiler/call_graph.py

Lines changed: 5 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -285,9 +285,7 @@ def topological_sort(self) -> list[str]:
285285
# Check if we processed all nodes
286286
if len(result) != len(self.nodes):
287287
cycles = self.find_cycles()
288-
cycle_desc = ", ".join(
289-
" -> ".join(cycle) for cycle in cycles
290-
)
288+
cycle_desc = ", ".join(" -> ".join(cycle) for cycle in cycles)
291289
raise CallGraphError(
292290
f"Cannot compute topological sort: graph contains cycles ({cycle_desc})",
293291
cycles=cycles,
@@ -472,10 +470,7 @@ def get_transitive_callers(self, func: str) -> set[str]:
472470
return visited
473471

474472
def __repr__(self) -> str:
475-
return (
476-
f"CallGraph(nodes={len(self.nodes)}, "
477-
f"edges={len(self.edges)})"
478-
)
473+
return f"CallGraph(nodes={len(self.nodes)}, edges={len(self.edges)})"
479474

480475
def __str__(self) -> str:
481476
lines = ["CallGraph:"]
@@ -592,9 +587,7 @@ def visit_class_def(self, node: ClassDef) -> None:
592587

593588
self._function_scope_stack.pop()
594589
self._current_function = (
595-
self._function_scope_stack[-1]
596-
if self._function_scope_stack
597-
else None
590+
self._function_scope_stack[-1] if self._function_scope_stack else None
598591
)
599592
else:
600593
self.visit(stmt)
@@ -617,9 +610,7 @@ def visit_scene_def(self, node: SceneDef) -> None:
617610

618611
self._function_scope_stack.pop()
619612
self._current_function = (
620-
self._function_scope_stack[-1]
621-
if self._function_scope_stack
622-
else None
613+
self._function_scope_stack[-1] if self._function_scope_stack else None
623614
)
624615
else:
625616
self.visit(stmt)
@@ -641,9 +632,7 @@ def visit_module_decl(self, node: ModuleDecl) -> None:
641632

642633
self._function_scope_stack.pop()
643634
self._current_function = (
644-
self._function_scope_stack[-1]
645-
if self._function_scope_stack
646-
else None
635+
self._function_scope_stack[-1] if self._function_scope_stack else None
647636
)
648637
else:
649638
self.visit(stmt)

0 commit comments

Comments
 (0)