Skip to content

Conversation

janosh
Copy link
Contributor

@janosh janosh commented Jun 10, 2025

adjust ruff config to flag prints in package code

Summary by CodeRabbit

  • Style

    • Removed or suppressed print statements in test files and select modules to reduce unnecessary console output and enforce stricter linting.
    • Updated linter configuration to enforce print statement restrictions globally, allowing exceptions only in example files.
    • Suppressed linter warnings for print statements where necessary using comments or file-level directives.
    • Replaced assertions with explicit error checks raising detailed exceptions for improved error reporting across multiple modules.
    • Improved error handling by replacing assertions with explicit exceptions in model validation, optimization steps, batching logic, and parameter checks.
    • Consolidated symmetry checks into loops with explicit error messages for better clarity and maintainability.
  • Chores

    • Updated pre-commit configuration to use a newer version of the Ruff linter.
    • Removed a script for generating module dependency graphs from documentation static files.

…ions, adjust ruff config to flag prints in package code
@janosh janosh added the linting label Jun 10, 2025
@cla-bot cla-bot bot added the cla-signed Contributor license agreement signed label Jun 10, 2025
Copy link

coderabbitai bot commented Jun 10, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

This update refines linting rules and code cleanliness across the project. It upgrades the Ruff pre-commit hook, tightens enforcement of print statement warnings (except in example files), removes debug print statements from tests, replaces assertions with explicit error raises for better diagnostics, and selectively suppresses linter warnings for necessary print usage in core modules via inline comments or file-level directives. Additionally, a module graph generation script was removed.

Changes

File(s) Change Summary
.pre-commit-config.yaml Updated ruff-pre-commit hook version from v0.11.12 to v0.11.13.
pyproject.toml Removed "T201" (print statement) and other lint codes from global ignore; "T201" now ignored only in examples/**/*.
tests/models/test_morse.py
tests/test_autobatching.py
Removed all debug print statements from test functions.
tests/test_optimizers.py Removed print statements; replaced warnings with strict assertions for convergence in tests; minor refactor.
tests/test_runners.py Replaced print statements with assertions; clarified file extensions and added explanatory comments.
torch_sim/math.py
torch_sim/models/mace.py
torch_sim/optimizers.py
Added # noqa: T201 to required print statements to suppress linter warnings.
torch_sim/models/fairchem.py
torch_sim/workflows/a2c.py
Added file-level # ruff: noqa: T201 to suppress print statement warnings throughout the file.
torch_sim/autobatching.py Replaced asserts with explicit ValueError raises in next_batch method; reformatted method signature; replaced logging with print.
torch_sim/models/interface.py Replaced all asserts with explicit ValueError raises in validate_model_outputs function for better diagnostics.
torch_sim/models/soft_sphere.py Replaced symmetry asserts with explicit ValueError checks in parameter matrices within constructor.
torch_sim/neighbors.py Replaced asserts with explicit ValueError raises for shape and sorting validations.
torch_sim/transforms.py Replaced asserts with explicit ValueError raises for tensor dimensionality and shape checks.
examples/scripts/7_Others/7.1_Soft_sphere_autograd.py Added # ruff: noqa: RUF001 directive; reformatted layout update call to single line.
examples/scripts/7_Others/7.6_Compare_ASE_to_VV_FIRE.py Replaced assertion with explicit ValueError raise for missing optimizer flavor value.
docs/_static/get_module_graph_dot_file.py Deleted entire script for generating colored DOT graph of module dependencies.
codecov.yml Removed ignore directive excluding torch_sim/unbatched from coverage reports.
docs/conf.py Added INP001 to the existing noqa list in the Ruff linter directive comment.

Poem

Hopping through code with linting in mind,
Debug prints removed, only clarity you'll find.
Ruff’s warnings tamed, but prints stay where they're due,
Tests now assert—no more verbose review.
With a twitch of my nose and a hop in my step,
The codebase is cleaner—oh what a prep!
🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 78c3690 and f7d4693.

📒 Files selected for processing (5)
  • codecov.yml (0 hunks)
  • docs/conf.py (1 hunks)
  • pyproject.toml (1 hunks)
  • torch_sim/autobatching.py (4 hunks)
  • torch_sim/neighbors.py (3 hunks)
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (1)
torch_sim/autobatching.py (1)

958-959: Consider addressing function complexity.

While the # noqa: C901 comment suppresses the complexity warning, the underlying complexity issue remains. The function has substantial logic that could potentially benefit from refactoring into smaller, focused methods.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between bdcfd1a and 2549457.

📒 Files selected for processing (11)
  • docs/_static/get_module_graph_dot_file.py (0 hunks)
  • examples/scripts/7_Others/7.1_Soft_sphere_autograd.py (2 hunks)
  • examples/scripts/7_Others/7.6_Compare_ASE_to_VV_FIRE.py (1 hunks)
  • pyproject.toml (1 hunks)
  • torch_sim/autobatching.py (2 hunks)
  • torch_sim/models/fairchem.py (2 hunks)
  • torch_sim/models/interface.py (3 hunks)
  • torch_sim/models/soft_sphere.py (1 hunks)
  • torch_sim/neighbors.py (2 hunks)
  • torch_sim/optimizers.py (8 hunks)
  • torch_sim/transforms.py (1 hunks)
💤 Files with no reviewable changes (1)
  • docs/_static/get_module_graph_dot_file.py
✅ Files skipped from review due to trivial changes (1)
  • examples/scripts/7_Others/7.1_Soft_sphere_autograd.py
🚧 Files skipped from review as they are similar to previous changes (3)
  • pyproject.toml
  • torch_sim/models/fairchem.py
  • torch_sim/optimizers.py
🧰 Additional context used
🧬 Code Graph Analysis (1)
torch_sim/autobatching.py (1)
torch_sim/state.py (2)
  • SimState (26-312)
  • n_batches (161-163)
🪛 GitHub Actions: Build docs
torch_sim/neighbors.py

[error] 113-113: TorchScript compilation failed with NotSupportedError: Don't support conversion in JoinedStr at line 113, related to f-string conversion in raise statement.

🪛 Pylint (3.3.7)
torch_sim/models/interface.py

[refactor] 202-202: Too many local variables (21/15)

(R0914)


[refactor] 202-202: Too many branches (20/12)

(R0912)


[refactor] 202-202: Too many statements (57/50)

(R0915)

⏰ Context from checks skipped due to timeout of 90000ms (7)
  • GitHub Check: test-examples (examples/scripts/6_Phonons/6.1_Phonons_MACE.py)
  • GitHub Check: test-examples (examples/scripts/3_Dynamics/3.2_MACE_NVE.py)
  • GitHub Check: test-examples (examples/scripts/3_Dynamics/3.13_MACE_NVE_non_pbc.py)
  • GitHub Check: test-model (macos-14, 3.12, lowest-direct, mattersim, tests/models/test_mattersim.py)
  • GitHub Check: test-model (macos-14, 3.12, lowest-direct, orb, tests/models/test_orb.py)
  • GitHub Check: test-model (macos-14, 3.12, lowest-direct, sevenn, tests/models/test_sevennet.py)
  • GitHub Check: test-model (macos-14, 3.11, highest, metatomic, tests/models/test_metatomic.py)
🔇 Additional comments (9)
examples/scripts/7_Others/7.6_Compare_ASE_to_VV_FIRE.py (1)

487-488: Excellent improvement to error handling.

Replacing the assertion with explicit conditional checking and ValueError is a significant improvement. This change ensures the validation cannot be disabled with Python's -O flag and provides a more descriptive error message that includes the actual variable value, making debugging easier for users of this example script.

torch_sim/transforms.py (1)

524-527: Strong improvement to input validation.

The replacement of assertions with explicit conditional checks that raise ValueError is an excellent change for library code. The new error messages include the actual shape information (got {mapping.shape}), which will significantly help users debug invalid inputs. This approach ensures validation cannot be bypassed and follows Python conventions for argument validation.

torch_sim/models/soft_sphere.py (1)

645-648: Excellent consolidation and improvement of validation logic.

This change represents a significant improvement in both maintainability and error handling:

  1. Better maintainability: Consolidating the symmetry checks into a loop makes it easier to add new parameter matrices in the future
  2. Improved error reporting: The error message now specifies which matrix failed the symmetry check
  3. Robust validation: Replaces assertions with explicit ValueError raising that cannot be disabled

The use of getattr() with the matrix name provides both flexibility and clear error messages, making this a model example of how to handle similar validation patterns.

torch_sim/models/interface.py (5)

234-236: Excellent improvement to error handling.

The replacement of assertions with explicit conditional checks and informative ValueError exceptions significantly improves debugging and error reporting. This ensures validation checks remain active even with Python optimization flags.


265-272: LGTM - Robust input validation.

The explicit checks for input tensor mutation with detailed error messages provide much better diagnostics than the previous assertions.


275-280: Well-structured validation logic.

The systematic checking of required output keys with explicit exceptions improves code reliability and maintainability.


283-288: Clear and informative shape validation.

The explicit shape validation with descriptive error messages will greatly assist in debugging model implementation issues.


294-317: Comprehensive output consistency validation.

The detailed validation of single-batch vs multi-batch consistency with explicit error messages and tolerance values provides excellent debugging information for model implementations.

torch_sim/autobatching.py (1)

1023-1030: Excellent validation improvements.

The systematic replacement of assertions with explicit ValueError exceptions provides much better error reporting and ensures these critical validations remain active in optimized Python environments. The error messages clearly indicate the expected vs actual values.

@Radical-AI Radical-AI deleted a comment from coderabbitai bot Jun 10, 2025
@Radical-AI Radical-AI deleted a comment from coderabbitai bot Jun 10, 2025
@janosh janosh force-pushed the ruff-disallow-prints branch from adf9f59 to 78c3690 Compare June 10, 2025 17:45
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
tests/models/test_soft_sphere.py (1)

330-332: Make the match regex less brittle

pytest.raises(ValueError, match="is not symmetric") will fail if the error message is re-phrased (e.g. “matrix … is not symmetric”).
A slightly more resilient pattern keeps the essence while tolerating wording tweaks:

-with pytest.raises(ValueError, match="is not symmetric"):
+with pytest.raises(ValueError, match=r"is\s+not\s+symmetric"):

The \s+ wildcard shields the test from minor spacing/punctuation edits without weakening the assertion.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between adf9f59 and 78c3690.

📒 Files selected for processing (2)
  • tests/models/test_soft_sphere.py (1 hunks)
  • torch_sim/neighbors.py (2 hunks)
🧰 Additional context used
🪛 GitHub Check: codecov/patch
torch_sim/neighbors.py

[warning] 112-113: torch_sim/neighbors.py#L112-L113
Added lines #L112 - L113 were not covered by tests


[warning] 218-221: torch_sim/neighbors.py#L218-L221
Added lines #L218 - L221 were not covered by tests

⏰ Context from checks skipped due to timeout of 90000ms (38)
  • GitHub Check: test-examples (examples/tutorials/reporting_tutorial.py)
  • GitHub Check: test-examples (examples/tutorials/low_level_tutorial.py)
  • GitHub Check: test-examples (examples/scripts/2_Structural_optimization/2.7_MACE_FrechetCellFilter_FIRE.py)
  • GitHub Check: test-examples (examples/tutorials/high_level_tutorial.py)
  • GitHub Check: test-examples (examples/tutorials/hybrid_swap_tutorial.py)
  • GitHub Check: test-examples (examples/scripts/2_Structural_optimization/2.4_MACE_FIRE.py)
  • GitHub Check: test-examples (examples/tutorials/autobatching_tutorial.py)
  • GitHub Check: test-examples (examples/scripts/2_Structural_optimization/2.3_MACE_Gradient_Descent.py)
  • GitHub Check: test-examples (examples/scripts/5_Workflow/5.3_Elastic.py)
  • GitHub Check: test-examples (examples/scripts/5_Workflow/5.1_a2c_silicon_batched.py)
  • GitHub Check: test-examples (examples/scripts/3_Dynamics/3.6_MACE_NVT_Nose_Hoover_temp_profile.py)
  • GitHub Check: test-examples (examples/scripts/6_Phonons/6.2_QuasiHarmonic_MACE.py)
  • GitHub Check: test-examples (examples/scripts/3_Dynamics/3.10_Hybrid_swap_mc.py)
  • GitHub Check: test-examples (examples/scripts/4_High_level_api/4.1_high_level_api.py)
  • GitHub Check: test-examples (examples/scripts/3_Dynamics/3.8_MACE_NPT_Nose_Hoover.py)
  • GitHub Check: test-examples (examples/scripts/3_Dynamics/3.12_MACE_NPT_Langevin.py)
  • GitHub Check: test-examples (examples/scripts/7_Others/7.4_Velocity_AutoCorrelation.py)
  • GitHub Check: test-examples (examples/scripts/7_Others/7.6_Compare_ASE_to_VV_FIRE.py)
  • GitHub Check: test-model (macos-14, 3.12, lowest-direct, mace, tests/test_elastic.py)
  • GitHub Check: test-model (ubuntu-latest, 3.12, lowest-direct, sevenn, tests/models/test_sevennet.py)
  • GitHub Check: test-model (ubuntu-latest, 3.12, lowest-direct, orb, tests/models/test_orb.py)
  • GitHub Check: test-model (macos-14, 3.11, highest, mace, tests/test_elastic.py)
  • GitHub Check: test-model (ubuntu-latest, 3.11, highest, sevenn, tests/models/test_sevennet.py)
  • GitHub Check: test-model (ubuntu-latest, 3.11, highest, mace, tests/test_elastic.py)
  • GitHub Check: test-model (ubuntu-latest, 3.12, lowest-direct, mace, tests/test_elastic.py)
  • GitHub Check: test-model (macos-14, 3.11, highest, graphpes, tests/models/test_graphpes.py)
  • GitHub Check: test-model (ubuntu-latest, 3.11, highest, orb, tests/models/test_orb.py)
  • GitHub Check: test-model (ubuntu-latest, 3.11, highest, mace, tests/test_optimizers_vs_ase.py)
  • GitHub Check: test-model (ubuntu-latest, 3.12, lowest-direct, graphpes, tests/models/test_graphpes.py)
  • GitHub Check: test-model (ubuntu-latest, 3.12, lowest-direct, mace, tests/test_optimizers_vs_ase.py)
  • GitHub Check: test-model (ubuntu-latest, 3.11, highest, graphpes, tests/models/test_graphpes.py)
  • GitHub Check: test-model (ubuntu-latest, 3.12, lowest-direct, fairchem, tests/models/test_fairchem.py)
  • GitHub Check: test-model (ubuntu-latest, 3.11, highest, fairchem, tests/models/test_fairchem.py)
  • GitHub Check: test-core (macos-14, 3.11, highest)
  • GitHub Check: test-core (ubuntu-latest, 3.12, lowest-direct)
  • GitHub Check: test-core (ubuntu-latest, 3.11, highest)
  • GitHub Check: test-core (macos-14, 3.12, lowest-direct)
  • GitHub Check: build-docs
🔇 Additional comments (1)
torch_sim/neighbors.py (1)

112-113: raise ValueError inside torch.jit.script can break JIT compilation

TorchScript currently guarantees support only for RuntimeError.
Trying to compile this function will fail with

TorchScriptException: 
Exception cannot be raised from TorchScript code:

in older & some current PyTorch versions.

Safer:

-if face_dist_c.shape != (3,):
-    raise ValueError(f"face_dist_c.shape={face_dist_c.shape} != (3,)")
+if face_dist_c.shape != (3,):
+    raise RuntimeError(f"face_dist_c.shape={face_dist_c.shape} != (3,)")

Same remark applies to the similar checks below.
Please run torch.jit.script(primitive_neighbor_list) locally to confirm.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 112-113: torch_sim/neighbors.py#L112-L113
Added lines #L112 - L113 were not covered by tests

@janosh janosh merged commit d1ce1b2 into main Jun 10, 2025
89 of 91 checks passed
@janosh janosh deleted the ruff-disallow-prints branch June 10, 2025 17:57
@coderabbitai coderabbitai bot mentioned this pull request Aug 14, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
cla-signed Contributor license agreement signed linting
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant