Skip to content

Make system_idx non-optional in SimState [1/2]#231

Merged
CompRhys merged 3 commits intomainfrom
make-system-idx-non-optional
Aug 7, 2025
Merged

Make system_idx non-optional in SimState [1/2]#231
CompRhys merged 3 commits intomainfrom
make-system-idx-non-optional

Conversation

@curtischong
Copy link
Collaborator

@curtischong curtischong commented Aug 2, 2025

Summary

This is part of my effort to type the codebase. system_idx is only optional during initialization so in the dataclass definition for SimState, I changed it from system_idx: torch.Tensor | None to system_idx: torch.Tensor

More importantly: This PR is the precursor to the one where I fix the SimState concatenation issue #232 (because that PR has a check that disallows torch.Tensor | None attributes. By making system_idx non-optional, I can remove the | None in its definition

To also allow users to pass in a None system_idx in the constructor, I initialize the dataclass with init=False and wrote my own constructor for SimState

Checklist

Before a pull request can be merged, the following items must be checked:

  • Doc strings have been added in the Google docstring format.
    Run ruff on your code.
  • Tests have been added for any new functionality or bug fixes.

We highly recommended installing the pre-commit hooks running in CI locally to speedup the development process. Simply run pip install pre-commit && pre-commit install to install the hooks which will check your code before each commit.

Summary by CodeRabbit

  • Refactor
    • Improved the initialization and validation process for simulation state objects to enhance reliability while maintaining existing functionality.

@cla-bot cla-bot bot added the cla-signed label Aug 2, 2025
@coderabbitai
Copy link

coderabbitai bot commented Aug 2, 2025

Walkthrough

The SimState class in torch_sim/state.py was refactored from using an auto-generated __init__ and __post_init__ to a dataclass with init=False and a manually implemented constructor. Initialization, validation, and processing logic were consolidated into this explicit __init__ method, and unused imports were removed. Additionally, the nvt_nose_hoover_init function in torch_sim/integrators/nvt.py was updated to pass system_idx from the input state to the NVTNoseHooverState constructor.

Changes

Cohort / File(s) Change Summary
SimState Refactor
torch_sim/state.py
Converted SimState to @dataclass(init=False) with an explicit constructor; moved all initialization and validation into __init__; removed __post_init__; removed unused field import.
NVT Integrator Update
torch_sim/integrators/nvt.py
Added system_idx=state.system_idx argument to NVTNoseHooverState initialization in nvt_nose_hoover_init to propagate system indexing.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Poem

A bunny hopped through Python code,
Refactoring the SimState road.
No more post-init, just one clear start,
With checks and shapes all set apart.
Now, with fields so neatly spun,
The state is clear—review is fun!
🐇✨

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.


📜 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 812da25 and fe07159.

📒 Files selected for processing (1)
  • torch_sim/integrators/nvt.py (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • torch_sim/integrators/nvt.py
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch make-system-idx-non-optional

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 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 generate unit tests to generate unit tests for 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: 1

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

85-105: Constructor implementation looks good, but consider the TODO.

The constructor signature correctly maintains backward compatibility while enforcing non-optional system_idx at the class level. The docstring is comprehensive and accurate.

However, the TODO comment on line 90 raises a valid point about potential confusion with positional arguments.

Consider making the constructor keyword-only to prevent argument order mistakes:

 def __init__(
     self,
+    *,
     positions: torch.Tensor,
     masses: torch.Tensor,
     cell: torch.Tensor,
     pbc: bool,  # noqa: FBT001 # TODO(curtis): maybe make the constructor be keyword-only (it can be easy to confuse positions vs masses, etc.)
     atomic_numbers: torch.Tensor,
     system_idx: torch.Tensor | None = None,
 ) -> None:

This would require all arguments to be passed by name, eliminating the confusion mentioned in the TODO.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 16bf8f8 and 74a22a2.

📒 Files selected for processing (1)
  • torch_sim/state.py (5 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (29)
  • GitHub Check: test-examples (examples/scripts/7_Others/7.6_Compare_ASE_to_VV_FIRE.py)
  • GitHub Check: test-examples (examples/scripts/6_Phonons/6.2_QuasiHarmonic_MACE.py)
  • GitHub Check: test-examples (examples/scripts/7_Others/7.4_Velocity_AutoCorrelation.py)
  • GitHub Check: test-examples (examples/scripts/2_Structural_optimization/2.5_MACE_UnitCellFilter_Gradient_Descen...
  • GitHub Check: test-examples (examples/scripts/2_Structural_optimization/2.4_MACE_FIRE.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.12_MACE_NPT_Langevin.py)
  • GitHub Check: test-examples (examples/scripts/3_Dynamics/3.8_MACE_NPT_Nose_Hoover.py)
  • GitHub Check: test-examples (examples/scripts/5_Workflow/5.3_Elastic.py)
  • GitHub Check: test-examples (examples/scripts/3_Dynamics/3.5_MACE_NVT_Nose_Hoover.py)
  • GitHub Check: test-examples (examples/tutorials/autobatching_tutorial.py)
  • GitHub Check: test-examples (examples/tutorials/high_level_tutorial.py)
  • GitHub Check: test-examples (examples/tutorials/low_level_tutorial.py)
  • GitHub Check: test-model (macos-14, 3.12, lowest-direct, mace, tests/test_optimizers_vs_ase.py)
  • GitHub Check: test-model (macos-14, 3.11, highest, mattersim, tests/models/test_mattersim.py)
  • GitHub Check: test-model (macos-14, 3.11, highest, metatomic, tests/models/test_metatomic.py)
  • GitHub Check: test-model (macos-14, 3.11, highest, 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.12, lowest-direct, orb, tests/models/test_orb.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.12, lowest-direct, sevenn, tests/models/test_sevennet.py)
  • GitHub Check: test-model (ubuntu-latest, 3.12, lowest-direct, fairchem, tests/models/test_fairchem.py)
  • GitHub Check: test-model (ubuntu-latest, 3.12, lowest-direct, mace, tests/test_elastic.py)
  • GitHub Check: test-model (ubuntu-latest, 3.11, highest, mace, tests/test_elastic.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, sevenn, tests/models/test_sevennet.py)
  • GitHub Check: test-model (ubuntu-latest, 3.11, highest, fairchem, tests/models/test_fairchem.py)
  • GitHub Check: test-core (ubuntu-latest, 3.12, lowest-direct)
  • GitHub Check: build-docs
🔇 Additional comments (6)
torch_sim/state.py (6)

10-10: LGTM!

The removal of the field import is appropriate since it's no longer needed after switching to a manual constructor.


25-25: LGTM!

Using init=False is the correct approach for implementing a custom constructor while maintaining dataclass benefits.


50-51: LGTM!

The type annotation change correctly reflects that system_idx is now non-optional in the class definition, improving type safety as intended by the PR.

Also applies to: 83-83


106-133: LGTM!

The initialization and validation logic is well-implemented with proper error handling and clear error messages.


134-146: LGTM!

The system_idx initialization correctly provides backward compatibility by defaulting to zeros when not provided, while the validation ensures data integrity.


150-157: LGTM!

The cell shape validation is comprehensive and provides clear error messages.

@curtischong curtischong marked this pull request as draft August 2, 2025 20:48
@curtischong curtischong changed the title Make system_idx non-optional in SimState Make system_idx non-optional in SimState [1/3] Aug 2, 2025
@curtischong curtischong changed the title Make system_idx non-optional in SimState [1/3] Make system_idx non-optional in SimState [1/2] Aug 2, 2025
@curtischong curtischong marked this pull request as ready for review August 3, 2025 00:29
cell=state.cell,
pbc=state.pbc,
atomic_numbers=atomic_numbers,
system_idx=state.system_idx,
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

types caught this bug!

@CompRhys CompRhys merged commit 88abcff into main Aug 7, 2025
93 checks passed
@CompRhys CompRhys deleted the make-system-idx-non-optional branch August 7, 2025 01:43
@coderabbitai coderabbitai bot mentioned this pull request Aug 30, 2025
3 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants