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

Breaking: all plot methods return plt.Axes #3749

Merged
merged 10 commits into from
Apr 12, 2024
Merged

Conversation

janosh
Copy link
Member

@janosh janosh commented Apr 12, 2024

a few plotting methods were overlooked in the return plt to return ax migration #3237.

this PR makes pymatgen's plotting API consistent by returning plt.Axes from all plotting methods

also fixes the return types in many doc strings and adds Returns: section to several doc strings that were missing them

Summary by CodeRabbit

  • Documentation

    • Improved documentation clarity and formatting in plotting utilities.
    • Enhanced readability and maintainability of the code with updated documentation.
  • Refactor

    • Changed variable names for consistency in plotting utilities.
    • Adjusted font sizes and parameters in various plot settings for improved visualization.
  • New Features

    • Updated the get_plot function to return a 3D plot of the Wulff shape.
  • Style

    • Adjusted font sizes and parameters in various plot settings for improved visualization.
    • Enhanced readability and maintainability of the code in plotting utilities.

@janosh janosh added linting Linting and quality assurance data viz PRs and issues about pymatgen plotting functionality docs Documentation, examples, user guides breaking Breaking change labels Apr 12, 2024
Copy link

coderabbitai bot commented Apr 12, 2024

Walkthrough

The recent updates in pymatgen involve refining function signatures, variable names, return types, and plot settings for improved usability and clarity. These changes enhance the overall user experience in materials science computations.

Changes

File Path Change Summary
pymatgen/analysis/wulff.py get_plot returns mpl_toolkits.mplot3d.Axes3D for 3D Wulff shape plot.
pymatgen/util/plotting.py Variable name consistency, return type updates, plot setting adjustments, and documentation improvements.
tests/analysis/test_wulff.py Assertions updated for get_plot to check specific properties of Axes3D object.
tests/util/test_plotting.py Return values assigned to fig and ax, assertions modified to check types and properties.

🐰✨
In the gardens of code, where the data trees grow,
A rabbit hopped by, with updates in tow.
Refining and tweaking, with a meticulous hand,
To make all the structures much grander and grand.
Cheers to the changes, may they be ever so bright,
In the realm of pymatgen, all is now right! 🌟
🐰💻


Recent Review Details

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between 7cac3f6 and b0fd1c1.
Files selected for processing (4)
  • pymatgen/analysis/wulff.py (2 hunks)
  • pymatgen/util/plotting.py (12 hunks)
  • tests/analysis/test_wulff.py (1 hunks)
  • tests/util/test_plotting.py (2 hunks)
Files skipped from review as they are similar to previous changes (2)
  • pymatgen/analysis/wulff.py
  • pymatgen/util/plotting.py
Additional comments not posted (3)
tests/util/test_plotting.py (2)

18-22: Changes align with PR objectives to standardize return types. Good use of conditional assertions based on the availability of pymatviz.


42-48: Thorough testing of Axes properties ensures the plotting function behaves as expected. Good job on ensuring detailed checks.

tests/analysis/test_wulff.py (1)

78-83: Thorough testing of Axes3D properties ensures the plotting function behaves as expected. Good job on ensuring detailed checks.


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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.

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 as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration 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: 13

Actionable comments outside the diff hunks (6)
pymatgen/io/vasp/sets.py (6)

Line range hint 2200-2200: Ensure that MPStaticSet sets the NSW parameter to 0 for static calculations.

-  this.config_dict["INCAR"]["NSW"] = this.nsw;
+  this.config_dict["INCAR"]["NSW"] = 0;  # Ensure no structural relaxations in static calculations

Line range hint 2500-2500: Ensure that MPSOCSet correctly sets the LSORBIT parameter for SOC calculations.

-  this.config_dict["INCAR"]["LSORBIT"] = this.lsorbit;
+  this.config_dict["INCAR"]["LSORBIT"] = true;  # Ensure LSORBIT is always true for SOC calculations

Line range hint 2800-2800: Ensure that MVLScanRelaxSet correctly sets the LASPH parameter for SCAN calculations.

-  this.config_dict["INCAR"]["LASPH"] = this.lasph;
+  this.config_dict["INCAR"]["LASPH"] = true;  # Ensure LASPH is always true for SCAN calculations

Line range hint 3000-3000: Ensure that MPAbsorptionSet correctly sets the NOMEGA parameter for optical calculations.

-  this.config_dict["INCAR"]["NOMEGA"] = this.nomega;
+  this.config_dict["INCAR"]["NOMEGA"] = 1000;  # Ensure NOMEGA is set to a suitable value for optical calculations

Line range hint 3300-3300: Ensure that MVLScanRelaxSet correctly sets the LASPH parameter for SCAN calculations.

-  this.config_dict["INCAR"]["LASPH"] = this.lasph;
+  this.config_dict["INCAR"]["LASPH"] = true;  # Ensure LASPH is always true for SCAN calculations

Line range hint 3500-3500: Ensure that MPAbsorptionSet correctly sets the NOMEGA parameter for optical calculations.

-  this.config_dict["INCAR"]["NOMEGA"] = this.nomega;
+  this.config_dict["INCAR"]["NOMEGA"] = 1000;  # Ensure NOMEGA is set to a suitable value for optical calculations

@@ -812,7 +812,7 @@ def get_magsymops(self, data):

# else check to see if it specifies a magnetic space group
elif bns_name or bns_num:
label = bns_name if bns_name else list(map(int, (bns_num.split("."))))
label = bns_name or list(map(int, (bns_num.split("."))))
Copy link

Choose a reason for hiding this comment

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

Refactor the assignment of label to use a more Pythonic approach.

- label = bns_name or list(map(int, (bns_num.split("."))))
+ label = bns_name if bns_name is not None else list(map(int, bns_num.split(".")))

This change makes the conditional assignment clearer and more in line with common Python practices.


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.

Suggested change
label = bns_name or list(map(int, (bns_num.split("."))))
label = bns_name if bns_name is not None else list(map(int, bns_num.split(".")))

Comment on lines +2291 to +2292

Returns:
Copy link

Choose a reason for hiding this comment

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

The method symm_group_cubic lacks a docstring. Adding a docstring would improve code maintainability by explaining the purpose and usage of this method.

+    """
+    Obtain cubic symmetric equivalents of the list of vectors.
+
+    Args:
+        mat (n by 3 array/matrix): lattice matrix
+
+    Returns:
+        cubic symmetric equivalents of the list of vectors.
+    """

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.

Suggested change
Returns:
"""
Obtain cubic symmetric equivalents of the list of vectors.
Args:
mat (n by 3 array/matrix): lattice matrix
Returns:
cubic symmetric equivalents of the list of vectors.
"""

Comment on lines +2188 to +2189

Returns:
Copy link

Choose a reason for hiding this comment

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

The method reduce_mat lacks a docstring. Adding a docstring would improve code maintainability by explaining the purpose and usage of this method.

+    """
+    Reduce integer array mat's determinant mag times by linear combination
+    of its row vectors, so that the new array after rotation (r_matrix) is
+    still an integer array.
+
+    Args:
+        mat (3 by 3 array): input matrix
+        mag (int): reduce times for the determinant
+        r_matrix (3 by 3 array): rotation matrix
+    """

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.

Suggested change
Returns:
"""
Reduce integer array mat's determinant mag times by linear combination
of its row vectors, so that the new array after rotation (r_matrix) is
still an integer array.
Args:
mat (3 by 3 array): input matrix
mag (int): reduce times for the determinant
r_matrix (3 by 3 array): rotation matrix
"""

Comment on lines +2222 to +2223

Returns:
Copy link

Choose a reason for hiding this comment

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

The method vec_to_surface lacks a docstring. Adding a docstring would improve code maintainability by explaining the purpose and usage of this method.

+    """
+    Transform a float vector to a surface miller index with integers.
+
+    Args:
+        vec (1 by 3 array float vector): input float vector
+
+    Returns:
+        the surface miller index of the input vector.
+    """

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.

Suggested change
Returns:
"""
Transform a float vector to a surface miller index with integers.
Args:
vec (1 by 3 array float vector): input float vector
Returns:
the surface miller index of the input vector.
"""

@@ -121,7 +121,7 @@ def __init__(
"""
self.miller_index = miller_index
self.label = label
self.adsorbates = adsorbates if adsorbates else []
self.adsorbates = adsorbates or []
Copy link

Choose a reason for hiding this comment

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

Consider using if adsorbates is None instead of or for clarity and to avoid unintended behavior if adsorbates is an empty list but not None.

- self.adsorbates = adsorbates or []
+ self.adsorbates = [] if adsorbates is None else adsorbates

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.

Suggested change
self.adsorbates = adsorbates or []
self.adsorbates = [] if adsorbates is None else adsorbates

Ensure proper handling of default values for adsorbates to avoid potential bugs with falsy but valid values.

- self.adsorbates = adsorbates or []
+ self.adsorbates = [] if adsorbates is None else adsorbates

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.

Suggested change
self.adsorbates = adsorbates or []
self.adsorbates = [] if adsorbates is None else adsorbates

@@ -180,7 +180,7 @@
float: The surface energy of the slab.
"""
# Set up
ref_entries = ref_entries if ref_entries else []
ref_entries = ref_entries or []
Copy link

Choose a reason for hiding this comment

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

Use explicit None check for ref_entries to ensure clarity and prevent errors with other falsy values.

- ref_entries = ref_entries or []
+ ref_entries = [] if ref_entries is None else ref_entries

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.

Suggested change
ref_entries = ref_entries or []
ref_entries = [] if ref_entries is None else ref_entries

Explicitly handle None values for ref_entries to avoid potential issues with falsy but non-None values.

- ref_entries = ref_entries or []
+ ref_entries = [] if ref_entries is None else ref_entries

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.

Suggested change
ref_entries = ref_entries or []
ref_entries = [] if ref_entries is None else ref_entries

Ensure ref_entries is handled correctly by explicitly checking for None.

- ref_entries = ref_entries or []
+ ref_entries = [] if ref_entries is None else ref_entries

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.

Suggested change
ref_entries = ref_entries or []
ref_entries = [] if ref_entries is None else ref_entries

To prevent potential logical errors, explicitly check for None when assigning default values.

- ref_entries = ref_entries or []
+ ref_entries = [] if ref_entries is None else ref_entries

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.

Suggested change
ref_entries = ref_entries or []
ref_entries = [] if ref_entries is None else ref_entries

@@ -1794,7 +1794,7 @@ def parse_struct(path_dir):
path_dir: (str) dir containing the boltztrap.struct file

Returns:
(float) volume
float: volume of the structure in Angstrom^3
Copy link

Choose a reason for hiding this comment

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

The function parse_struct should explicitly return a float type for the volume as indicated in the comment. Ensure the return type is consistent with the documentation.

-            return Lattice(
+            return float(Lattice(
                [[Length(float(tokens[i].split()[j]), "bohr").to("ang") for j in range(3)] for i in range(1, 4)]
            ).volume)

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.

Suggested change
float: volume of the structure in Angstrom^3
return float(Lattice(
[[Length(float(tokens[i].split()[j]), "bohr").to("ang") for j in range(3)] for i in range(1, 4)]
).volume)

Comment on lines +2159 to +2167
n_atoms = 0
for idx, line in enumerate(file):
line = line.rstrip("\n")
if idx == 0 and "CUBE" not in line:
raise ValueError("CUBE file format not recognized")

if idx == 2:
tokens = line.split()
natoms = int(tokens[0])
n_atoms = int(tokens[0])
Copy link

Choose a reason for hiding this comment

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

The variable n_atoms is initialized but not used within the read_cube_file function. Consider removing it if it's unnecessary, or ensure it's used appropriately if needed.

-        n_atoms = 0
-        for idx, line in enumerate(file):
-            line = line.rstrip("\n")
-            if idx == 0 and "CUBE" not in line:
-                raise ValueError("CUBE file format not recognized")
-
-            if idx == 2:
-                tokens = line.split()
-                n_atoms = int(tokens[0])
-            if idx == 3:
+        for idx, line in enumerate(file):
+            line = line.rstrip("\n")
+            if idx == 0 and "CUBE" not in line:
+                raise ValueError("CUBE file format not recognized")

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.

Suggested change
n_atoms = 0
for idx, line in enumerate(file):
line = line.rstrip("\n")
if idx == 0 and "CUBE" not in line:
raise ValueError("CUBE file format not recognized")
if idx == 2:
tokens = line.split()
natoms = int(tokens[0])
n_atoms = int(tokens[0])
for idx, line in enumerate(file):
line = line.rstrip("\n")
if idx == 0 and "CUBE" not in line:
raise ValueError("CUBE file format not recognized")

Comment on lines +2181 to +2183
energy_data = np.genfromtxt(filename, skip_header=n_atoms + 6, skip_footer=1)
n_lines_data = len(energy_data)
last_line = np.genfromtxt(filename, skip_header=n_lines_data + natoms + 6)
last_line = np.genfromtxt(filename, skip_header=n_lines_data + n_atoms + 6)
Copy link

Choose a reason for hiding this comment

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

The variable n_lines_data is used to calculate the last_line but is not necessary. You can simplify the code by directly using the skip_header parameter with the appropriate value.

-        n_lines_data = len(energy_data)
-        last_line = np.genfromtxt(filename, skip_header=n_lines_data + n_atoms + 6)
+        last_line = np.genfromtxt(filename, skip_header=len(energy_data) + n_atoms + 6)

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.

Suggested change
energy_data = np.genfromtxt(filename, skip_header=n_atoms + 6, skip_footer=1)
n_lines_data = len(energy_data)
last_line = np.genfromtxt(filename, skip_header=n_lines_data + natoms + 6)
last_line = np.genfromtxt(filename, skip_header=n_lines_data + n_atoms + 6)
energy_data = np.genfromtxt(filename, skip_header=n_atoms + 6, skip_footer=1)
last_line = np.genfromtxt(filename, skip_header=len(energy_data) + n_atoms + 6)

@janosh janosh merged commit 48860fb into master Apr 12, 2024
22 checks passed
@janosh janosh deleted the plot-methods-return-ax branch April 12, 2024 05:41
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
breaking Breaking change data viz PRs and issues about pymatgen plotting functionality docs Documentation, examples, user guides linting Linting and quality assurance
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant