Skip to content

Conversation

jan-janssen
Copy link
Member

@jan-janssen jan-janssen commented Aug 21, 2025

Summary by CodeRabbit

  • Bug Fixes

    • Zero-valued position/velocity vectors are now accepted and applied instead of being ignored, improving handling of explicit zero inputs.
  • Tests

    • Expanded test coverage with an additional structure and updated expected energy values to reflect the extended test sequence.

Copy link

coderabbitai bot commented Aug 21, 2025

Walkthrough

Modify _vector_to_lammps to treat zero-valued vectors as valid input (check now uses vector is not None), so zero vectors are transformed by Prism and flattened; tests extended with a fourth structure (bulk_al_small) and an inserted expected energy value.

Changes

Cohort / File(s) Summary
ASE wrapper vector handling
pylammpsmpi/wrapper/ase.py
Change internal check in _vector_to_lammps(vector, prism) from if vector is not None and np.any(vector) to if vector is not None, allowing zero-valued vectors to be converted (via Prism) and flattened. No public API signatures changed.
Test suite: added structure and energy
tests/test_ase_interface.py
Add bulk_al_small = bulk("Al"), extend self.structure_lst to include it, and insert new expected energy -0.04342932, expanding tests to iterate over four structures.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Caller
  participant ASEWrapper as ASE Wrapper
  participant _Vec as _vector_to_lammps
  participant Prism
  participant LAMMPS as LAMMPS Engine

  Caller->>ASEWrapper: interactive_structure_setter(structure, ...)
  ASEWrapper->>_Vec: _vector_to_lammps(vector, prism)
  alt vector is None
    _Vec->>ASEWrapper: return None
  else vector is not None (including zeros)
    _Vec->>Prism: apply prism conversion (if provided)
    Prism-->>_Vec: transformed vector
    _Vec->>_Vec: flatten() -> 1D array
    _Vec-->>ASEWrapper: return flattened vector
  end
  ASEWrapper->>LAMMPS: create_atoms(pos_vec_or_none, ...)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Poem

A rabbit hops where vectors lay,
Zeroes now join the bright array.
Four crystals hum, one value new—
I nudge the code and blink—adieu! 🐇✨

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.


📜 Recent review details

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

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between beed905 and 20e1463.

📒 Files selected for processing (1)
  • pylammpsmpi/wrapper/ase.py (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • pylammpsmpi/wrapper/ase.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 ase_fix

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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

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

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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.

@jan-janssen jan-janssen requested a review from samwaseda August 21, 2025 11:47
Copy link

codecov bot commented Aug 21, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 82.31%. Comparing base (b212a75) to head (20e1463).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #368      +/-   ##
==========================================
+ Coverage   81.93%   82.31%   +0.37%     
==========================================
  Files           5        5              
  Lines         559      554       -5     
==========================================
- Hits          458      456       -2     
+ Misses        101       98       -3     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

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 (4)
pylammpsmpi/wrapper/ase.py (3)

480-487: np.any(vector) drops legitimate all-zero data; make “None” mean “unset” only

current behavior: all-zero arrays are treated as “absent” and collapsed to None. That’s why you needed a special fallback for positions. A simpler, more predictable rule: only treat vector is None as unset, otherwise transform+flatten regardless of values. This also preserves intentional zero velocities rather than silently omitting them.

Proposed patch:

 def _vector_to_lammps(vector, prism):
-    if vector is not None and np.any(vector):
-        if not _check_ortho_prism(prism=prism):
-            vector = prism.vector_to_lammps(vector)
-        return vector.flatten()
-    else:
-        return None
+    if vector is None:
+        return None
+    if not _check_ortho_prism(prism=prism):
+        vector = prism.vector_to_lammps(vector)
+    return np.asarray(vector).flatten()

This change would also make the new positions fallback unnecessary in most cases, but keeping the defensive fallback is fine.


291-296: Incorrect exception type and broken “missing elements” message

get_lammps_indicies_from_ase_structure will raise a ValueError (not KeyError) if an element in the structure is not mapped; and the current message uses el_dict (always empty here) and expects an Abbreviation attribute on strings. Fix both.

-        except KeyError:
-            missing = set(get_species_symbols(structure)).difference(el_dict.keys())
-            missing = ", ".join([el.Abbreviation for el in missing])
+        except ValueError:
+            present = set(get_species_symbols(structure))
+            allowed = set(el_eam_lst)
+            missing = ", ".join(sorted(present - allowed))
             raise ValueError(
-                f"Structure contains elements [{missing}], that are not present in the potential!"
+                f"Structure contains elements [{missing}] that are not present in the potential!"
             )

142-145: Typos in warning text (“upper trangular”)

Minor wording fix improves clarity and searchability of logs.

-                "Warning: setting upper trangular matrix might slow down the calculation",
+                "Warning: setting an upper triangular matrix might slow down the calculation",

Also applies to: 221-225

tests/test_ase_interface.py (1)

480-489: Expanded structure set and expected energies look consistent; consider naming and coverage tweaks

  • The added bulk_al_small = bulk("Al").repeat([2, 2, 2]) is a nice addition to exercise the triclinic/default cell path; LGTM overall.
  • Minor naming nit: bulk_al_small doesn’t convey why it’s added; bulk_al_skewed or bulk_al_default would be clearer.
  • To fully cover the new positions fallback (and the mirrored fix I suggested), add a test where positions are explicitly set to all zeros to ensure no crash and correct propagation.

Sketch for an extra test:

def test_set_all_zero_positions(self):
    lmp = LammpsASELibrary(working_directory=None, cores=1, comm=None,
                           logger=logging.getLogger("ZeroPosLogger"),
                           log_file=None, library=LammpsLibrary(cores=2),
                           disable_log_file=True)
    structure = bulk("Al", cubic=True)
    lmp.interactive_structure_setter(
        structure=structure, units="lj", dimension=3,
        boundary=" ".join(["p" if c else "f" for c in structure.pbc]),
        atom_style="atomic", el_eam_lst=["Al"], calc_md=False
    )
    zeros = np.zeros_like(structure.positions)
    lmp.interactive_positions_setter(positions=zeros)
    lmp.interactive_lib_command("run 0")
    self.assertTrue(np.allclose(lmp.interactive_positions_getter(), zeros))
📜 Review details

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

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between b212a75 and 16d02c3.

📒 Files selected for processing (2)
  • pylammpsmpi/wrapper/ase.py (1 hunks)
  • tests/test_ase_interface.py (1 hunks)

@samwaseda
Copy link
Member

Could you say what was the problem?

@jan-janssen
Copy link
Member Author

ld you say what was the problem?

Für bulk("Al") there is just a single atom at position [[0, 0, 0]] and still it is a triclinic cell. As a consequence np.any([[0, 0, 0]]) is false and consequently position=None.

@jan-janssen jan-janssen merged commit 950a772 into main Aug 21, 2025
26 of 27 checks passed
@jan-janssen jan-janssen deleted the ase_fix branch August 21, 2025 21:28
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