Skip to content

add kirkwood buff analysis#19

Open
MrJulEnergy wants to merge 8 commits intozincware:mainfrom
MrJulEnergy:main
Open

add kirkwood buff analysis#19
MrJulEnergy wants to merge 8 commits intozincware:mainfrom
MrJulEnergy:main

Conversation

@MrJulEnergy
Copy link

@MrJulEnergy MrJulEnergy commented Jul 25, 2025

Summary by CodeRabbit

  • New Features
    • Added Kirkwood-Buff integral calculation with finite size correction for radial distribution function data.
    • Enabled visualization of integrand plots for each RDF pair with saved figures.
    • Introduced thermodynamic observable calculations including chemical potential derivatives, partial molar volumes, and isothermal compressibility.
    • Made KirkwoodBuffAnalysis available as a public API for external use.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 25, 2025

"""

Walkthrough

A new module massband/kirkwood_buff.py was added, defining functions and a class for Kirkwood-Buff integral analysis using RDF data. The public API was updated to export the new KirkwoodBuffAnalysis class. The implementation includes integral computation with finite size corrections, thermodynamic observable calculations, data handling, error logging, and saving plots of the integrand.

Changes

File(s) Change Summary
massband/init.pyi Added import and export of KirkwoodBuffAnalysis to the public API.
massband/kirkwood_buff.py Added functions compute_kirkwood_buff_integrals and calculate_observables; added KirkwoodBuffAnalysis class with dependencies, parameters, outputs, integral computation, observable calculations, error handling, and plotting.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant KirkwoodBuffAnalysis
    participant zntrack
    participant jax
    participant matplotlib

    User->>KirkwoodBuffAnalysis: Instantiate with rdf_data, partial_densities, dr, T
    User->>KirkwoodBuffAnalysis: Call run()
    KirkwoodBuffAnalysis->>zntrack: Access rdf_data and partial_densities dependencies
    KirkwoodBuffAnalysis->>KirkwoodBuffAnalysis: Compute thermal energy kBT and total density rho
    KirkwoodBuffAnalysis->>compute_kirkwood_buff_integrals: Pass rdf_data, dr, figures path
    compute_kirkwood_buff_integrals->>jax: Convert rdf values to arrays
    compute_kirkwood_buff_integrals->>compute_kirkwood_buff_integrals: Compute system size L, radial array r, integrand h_r * u2
    compute_kirkwood_buff_integrals->>jax: Perform trapezoidal integration
    compute_kirkwood_buff_integrals->>matplotlib: Plot integrand and save figure
    compute_kirkwood_buff_integrals-->>KirkwoodBuffAnalysis: Return integral DataFrame, results dict, figure path
    KirkwoodBuffAnalysis->>calculate_observables: Pass integral DataFrame, partial densities, T
    calculate_observables-->>KirkwoodBuffAnalysis: Return observables dict
    KirkwoodBuffAnalysis->>KirkwoodBuffAnalysis: Store results and metrics
    KirkwoodBuffAnalysis-->>User: Outputs available (results, figures)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

A hop, a skip through RDF's tune,
Buff integrals beneath the moon.
With JAX and plots, the numbers gleam,
This rabbit's math fulfills the dream.
From data deep to graphs so bright,
We compute, we plot, with pure delight! 🐇📈
"""

Note

⚡️ Unit Test Generation is now available in beta!

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

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

🪧 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
Contributor

@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 (2)
massband/kirkwood_buff.py (2)

22-22: Address the TODO comment for compressibility calculation.

The TODO comment indicates missing functionality. Consider implementing the isothermal compressibility calculation or creating a separate issue to track this enhancement.

The isothermal compressibility can be calculated from Kirkwood-Buff integrals using:
κ_T = (∑ᵢ∑ⱼ xᵢxⱼ(Gᵢⱼ + Vᵢⱼ))/(ρkT)

Would you like me to help implement this or create a separate issue for tracking?


7-9: Enhance the docstring with more detailed information.

The docstring is too brief for a scientific computation class. Consider adding parameter descriptions, mathematical formula, and usage example.

-    """
-    Calculate the Kirkwood–Buff integral
-    """
+    """
+    Calculate the Kirkwood–Buff integral from radial distribution function data.
+    
+    The Kirkwood-Buff integral is defined as:
+    G_ij = 4π ∫₀^∞ [g_ij(r) - 1] r² dr
+    
+    Parameters
+    ----------
+    rdf : dict
+        Dictionary containing radial distribution function data for different pairs
+    bin_width : float
+        Width of the radial bins in the RDF data
+        
+    Returns
+    -------
+    results : dict
+        Dictionary containing computed Kirkwood-Buff integrals for each pair
+    """
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e28701f and 06fc989.

📒 Files selected for processing (2)
  • massband/__init__.pyi (2 hunks)
  • massband/kirkwood_buff.py (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
massband/__init__.pyi (1)
massband/kirkwood_buff.py (1)
  • KirkwoodBuffAnalysis (6-22)
🔇 Additional comments (2)
massband/__init__.pyi (2)

10-10: LGTM! Clean import addition.

The import follows the existing pattern and correctly exposes the new KirkwoodBuffAnalysis class.


20-20: LGTM! Proper addition to all list.

The class is correctly added to the public API exports, maintaining alphabetical ordering within the list.

Copy link
Contributor

@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 (2)
massband/kirkwood_buff.py (2)

14-14: Fix typo in comment.

-    rdf_data: dict[str, list[float]] = zntrack.deps() # Idealy a rdf with very long ranges is needed!
+    rdf_data: dict[str, list[float]] = zntrack.deps() # Ideally a rdf with very long ranges is needed!

31-32: Use JAX consistently for numerical operations.

For consistency with the rest of the JAX-based implementation, consider using jnp.pi instead of np.pi.

-            w = 4*np.pi * r**2 * (1 - 3/2*x + 1/2*x**3)
+            w = 4*jnp.pi * r**2 * (1 - 3/2*x + 1/2*x**3)
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7a9e135 and 12c2ecd.

📒 Files selected for processing (2)
  • massband/__init__.pyi (2 hunks)
  • massband/kirkwood_buff.py (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • massband/init.pyi
🧰 Additional context used
🪛 Ruff (0.12.2)
massband/kirkwood_buff.py

3-3: scipy.integrate.simpson imported but unused

Remove unused import: scipy.integrate.simpson

(F401)

⏰ 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). (3)
  • GitHub Check: pytest (3.11, ubuntu-latest, 20.15.1)
  • GitHub Check: pytest (3.13, ubuntu-latest, 20.15.1)
  • GitHub Check: pytest (3.12, ubuntu-latest, 20.15.1)
🔇 Additional comments (1)
massband/kirkwood_buff.py (1)

37-46: Well-implemented plotting functionality!

The plotting code properly handles figure creation, uses appropriate labels with LaTeX formatting, and correctly closes figures to prevent memory leaks.

Copy link
Contributor

@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: 4

♻️ Duplicate comments (1)
massband/kirkwood_buff.py (1)

57-57: Consider starting radial coordinate at bin center.

Starting the radial coordinate at 0 can be problematic since the integrand contains r² terms. Consider starting at dr/2 (bin center) to avoid potential numerical issues.

-        r = jnp.arange(0, L, dr)
+        r = jnp.arange(dr/2, L, dr)
🧹 Nitpick comments (2)
massband/kirkwood_buff.py (2)

33-37: Update docstring to include all return values.

The function returns three values but the docstring only documents two. Add documentation for the structures return value.

     Returns
     ----------
         G: pd.DataFrame of Kirkwood-Buff integrals
         results: dict of integrals keyed by "A|B"
+        structures: list of unique structure names sorted alphabetically

103-103: Replace print with logging.

Use logging instead of print statements for consistency with the rest of the module.

-        print(self.partial_densities)
+        log.debug(f"Partial densities: {self.partial_densities}")
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 97d5338 and 27b7ec4.

📒 Files selected for processing (2)
  • massband/__init__.pyi (2 hunks)
  • massband/kirkwood_buff.py (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • massband/init.pyi
🧰 Additional context used
🪛 Ruff (0.12.2)
massband/kirkwood_buff.py

105-105: SyntaxError: Expected ',', found name




class KirkWoodBuffAnalyis(zntrack.Node):
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix typo in class name.

The class name has a typo: "Analyis" should be "Analysis".

-class KirkWoodBuffAnalyis(zntrack.Node):
+class KirkwoodBuffAnalysis(zntrack.Node):

Note: This change will also need to be reflected in the __init__.pyi file where this class is exported.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
class KirkWoodBuffAnalyis(zntrack.Node):
-class KirkWoodBuffAnalyis(zntrack.Node):
+class KirkwoodBuffAnalysis(zntrack.Node):
🤖 Prompt for AI Agents
In massband/kirkwood_buff.py at line 87, correct the typo in the class name from
"KirkWoodBuffAnalyis" to "KirkWoodBuffAnalysis". Also, update the class name
accordingly in the __init__.pyi file where this class is exported to keep the
references consistent.

Copy link
Contributor

@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

♻️ Duplicate comments (1)
massband/kirkwood_buff.py (1)

53-53: Start radial coordinate at bin center instead of 0.

The radial coordinate should start at dr/2 (bin center) rather than 0, as the integrand contains r² terms and RDF values typically represent bin centers.

-        r = jnp.arange(0, L, dr)
+        r = jnp.arange(dr/2, L, dr)
🧹 Nitpick comments (1)
massband/kirkwood_buff.py (1)

236-250: Consider consistent error handling for failed calculations.

The results dictionary construction assumes all observables are successfully calculated. While calculate_observables handles errors by returning string messages, consider checking for these error states before accessing dictionary values.

         self.results = {
             "kbi_integrals": kbi_results,  # Å^3/molecule
-            "dmu_drho": observables["dmu_drho"].to_dict(),  # J*A^3/molecule
+            "dmu_drho": observables["dmu_drho"].to_dict() if isinstance(observables["dmu_drho"], pd.DataFrame) else observables["dmu_drho"],  # J*A^3/molecule
-            "partial_molar_volumes": observables[
-                "partial_molar_volumes"
-            ].to_dict(),  # A^3/molecule
+            "partial_molar_volumes": observables["partial_molar_volumes"].to_dict() if isinstance(observables["partial_molar_volumes"], pd.Series) else observables["partial_molar_volumes"],  # A^3/molecule

This ensures the code handles error states gracefully without attempting to call .to_dict() on error strings.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 27b7ec4 and 4388d43.

📒 Files selected for processing (2)
  • massband/__init__.pyi (2 hunks)
  • massband/kirkwood_buff.py (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • massband/init.pyi
🧰 Additional context used
🧬 Code Graph Analysis (1)
massband/kirkwood_buff.py (2)
massband/rdf_plot.py (1)
  • plot_rdf (15-148)
massband/rdf.py (1)
  • RadialDistributionFunction (236-438)
🔇 Additional comments (1)
massband/kirkwood_buff.py (1)

83-199: Well-implemented calculation of thermodynamic observables.

The function properly implements KB theory calculations with excellent unit tracking, appropriate error handling for singular matrices, and clear documentation. The conversion from Ų/J to Pa⁻¹ is correctly implemented.

Comment on lines +52 to +54
L = len(g_r) * dr
r = jnp.arange(0, L, dr)
h_r = g_r - 1
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Ensure array length compatibility when adjusting radial coordinates.

When starting r at dr/2, ensure that g_r and r arrays have compatible lengths for element-wise operations.

         g_r = jnp.array(g_r)
-        L = len(g_r) * dr
-        r = jnp.arange(0, L, dr)
+        L = len(g_r) * dr
+        r = jnp.arange(dr/2, L + dr/2, dr)[:len(g_r)]

This ensures r has the same length as g_r while properly representing bin centers.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
L = len(g_r) * dr
r = jnp.arange(0, L, dr)
h_r = g_r - 1
g_r = jnp.array(g_r)
L = len(g_r) * dr
r = jnp.arange(dr/2, L + dr/2, dr)[:len(g_r)]
h_r = g_r - 1
🤖 Prompt for AI Agents
In massband/kirkwood_buff.py around lines 52 to 54, the array r is created
starting at 0 which causes a length mismatch with g_r for element-wise
operations. Modify the creation of r to start at dr/2 and ensure its length
matches g_r by adjusting the range accordingly. This will align r as bin centers
and maintain compatibility for operations like h_r = g_r - 1.

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