Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Faster interface VACF calculation #8

Open
wants to merge 1 commit into
base: devel
Choose a base branch
from

Conversation

lucasdekam
Copy link
Contributor

@lucasdekam lucasdekam commented Feb 25, 2025

Hi, I've added a new class that first saves all the data in memory and computes the VACF only at the end.
Instead of computing it in _conclude I made a separate method, so that users can play around with the settings in a notebook more easily. The calc_vacf function includes a correlation_step parameter similar in MDAnalysis' waterdynamics code. It speeds up calculations, convenient for notebook use.

I also changed calc_power_spectrum to directly convert to 1/cm, given a timestep in ps, as this is the common unit.

The VACF results are the same (given the same data slice and ACF parameters):
image

image

You can remove the deprecated class or keep it. I'll also use the calc_vector_autocorrelation function for water dipole calculations (next PR).

I can add tests in the future.

Copy link

coderabbitai bot commented Feb 25, 2025

Walkthrough

This pull request introduces a new class, InterfaceVACF, to calculate the velocity autocorrelation function (VACF) for hydrogen atoms in a specified interval relative to a surface, while deprecating the previous InterfaceVelocityACF class (now renamed to InterfaceVACFDeprecated). The calc_power_spectrum function is updated to accept a full boolean to control VACF symmetrization and returns wave numbers instead of frequencies. Additionally, a new function calc_vector_autocorrelation is added to the water dynamics module to compute the autocorrelation function for a vector quantity with enhanced documentation.

Changes

File Changes Summary
WatAnalysis/spectrum.py Added new class InterfaceVACF (with methods calc_vacf, _prepare, and _single_frame), deprecated InterfaceVelocityACF (renamed to InterfaceVACFDeprecated), and updated calc_power_spectrum to accept a full parameter and return wave numbers.
WatAnalysis/waterdynamics.py Added new function calc_vector_autocorrelation to calculate the vector autocorrelation function with detailed parameter documentation; updated module documentation for clarity regarding numpy usage.

Sequence Diagram(s)

sequenceDiagram
    participant U as User
    participant I as InterfaceVACF
    participant P as _prepare
    participant S as _single_frame
    participant PS as calc_power_spectrum
    U->>I: Call calc_vacf(parameters)
    I->>P: Prepare data for calculation
    loop For each frame
        I->>S: Process frame data
    end
    I-->>U: Return computed VACF
    U->>PS: Call calc_power_spectrum(vacf, ts, full)
    PS-->>U: Return power spectrum (as wave numbers)
Loading
sequenceDiagram
    participant U as User
    participant C as calc_vector_autocorrelation
    participant V as Vectors
    participant M as Mask
    U->>C: Call calc_vector_autocorrelation(max_tau, delta_tau, step, vectors, mask)
    C->>C: Generate lag times array (tau)
    C->>V: Use vectors for dot product calculations
    C->>M: Apply mask for selection
    C-->>U: Return tau and normalized ACF values
Loading

Poem

In the garden of code I play,
Leaping through functions in a bright array.
VACF computed with careful art,
Autocorrelations set the pace from the start.
With vector magic and spectrum bright,
I hop in joy beneath the coding light! 🐰✨

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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. (Beta)
  • @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: 0

🧹 Nitpick comments (3)
WatAnalysis/spectrum.py (3)

44-76: Refactor suggestion for a more concise if full check.
Lines 66-69 can be condensed into a ternary expression per the static analysis hint. This is optional but improves readability.

Proposed change:

-    if full:
-        full_vacf = vacf
-    else:
-        full_vacf = np.concatenate([vacf[::-1][:-1], vacf])
+    full_vacf = vacf if full else np.concatenate([vacf[::-1][:-1], vacf])
🧰 Tools
🪛 Ruff (0.8.2)

66-69: Use ternary operator full_vacf = vacf if full else np.concatenate([vacf[::-1][:-1], vacf]) instead of if-else-block

Replace if-else-block with full_vacf = vacf if full else np.concatenate([vacf[::-1][:-1], vacf])

(SIM108)


79-193: Deprecation handling suggestion.
This class is marked InterfaceVACFDeprecated but doesn’t raise any deprecation warnings. Adding a DeprecationWarning can help guide users away from the old interface.

+import warnings

 class InterfaceVACFDeprecated(MultiTrajsAnalysisBase):
     def __init__(...):
+        warnings.warn(
+            "InterfaceVACFDeprecated is deprecated and may be removed in a future release.",
+            category=DeprecationWarning,
+            stacklevel=2,
+        )
         ...

278-283: Large array allocations in _prepare.
Notice _oxygen_mask and _hydrogen_velocities can consume significant memory for large trajectories. If memory usage is a concern, consider lazy loading or partial buffering.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5515d88 and 4fcefea.

📒 Files selected for processing (2)
  • WatAnalysis/spectrum.py (3 hunks)
  • WatAnalysis/waterdynamics.py (2 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
WatAnalysis/spectrum.py

66-69: Use ternary operator full_vacf = vacf if full else np.concatenate([vacf[::-1][:-1], vacf]) instead of if-else-block

Replace if-else-block with full_vacf = vacf if full else np.concatenate([vacf[::-1][:-1], vacf])

(SIM108)

🔇 Additional comments (10)
WatAnalysis/waterdynamics.py (3)

2-5: Nice module-level docstring addition.
The descriptive docstring clarifies the purpose of the module and enhances readability.


7-7: Import statement looks good.
Using numpy is essential for vectorized operations and numerical computations in subsequent functions.


271-331: Potential division-by-zero in ACF normalization.
If no vectors are selected or if the zero-lag dot product is 0, then acf[0] will be zero, causing a division-by-zero issue in line 329 (acf /= acf[0]). It's safer to check before normalizing or ensure data availability.

Example adjustment:

    ...
    # Normalize the ACF
-   acf /= acf[0]  # Normalize by the zero-lag value
+   if acf[0] != 0:
+       acf /= acf[0]
+   else:
+       # Handle the zero-lag == 0 scenario, e.g., set ACF to zeros or skip normalization
+       acf[:] = 0
    return tau, acf
WatAnalysis/spectrum.py (7)

2-5: Good module-level docstring update.
It succinctly describes the scope of vibrational spectra computations.


10-10: Import of speed_of_light is appropriate.
Used below for frequency-to-wavenumber conversions. No issues found.


16-16: New import from waterdynamics looks correct.
This import references calc_vector_autocorrelation, aligning with the new VACF logic.


195-234: Comprehensive class docstring.
The explanation of InterfaceVACF parameters and usage is clear, aiding maintainability.


236-283: Validate surf_ids and interval usage in the constructor.
If surf_ids is None or empty, surface-related logic may break. Consider adding checks to ensure they are valid or raise an exception early.


285-329: Index-based surface approach.
Method _single_frame depends on self.surf_ids to compute surf1_z and surf2_z. If surf_ids is out of range or misspecified, it will raise an indexing error. A prior check in the constructor or _prepare ensures robust error handling.


330-376: Ensure hydrogen selection is non-empty in calc_vacf.
If no hydrogens are selected for a given frame, mask_ts[sel_hydrogen_ids] might be empty or cause unexpected results in the autocorrelation. Consider a fallback or user notification if sel_hydrogen_ids is empty.

@lucasdekam lucasdekam changed the base branch from master to devel February 27, 2025 13:36
@lucasdekam
Copy link
Contributor Author

Merge conflict probably requires merging master into devel first

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.

1 participant