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: drop support of py3.7. fix: pin scipy constants to version 2018 #774

Closed

Conversation

wanghan-iapcm
Copy link
Contributor

@wanghan-iapcm wanghan-iapcm commented Jan 11, 2025

drop support of py3.7
fix issue #773

Summary by CodeRabbit

  • New Features

    • Enhanced management of physical constants with a centralized dictionary approach.
    • Added a new function to dynamically retrieve physical constants from multiple CODATA releases.
  • Bug Fixes

    • Updated Python version compatibility to require Python 3.8 or above.
  • Refactor

    • Improved constant management structure for better maintainability.
    • Replaced direct constant assignments with a more flexible retrieval method.
    • Adjusted caching behavior in error handling classes.
    • Simplified import statements for type handling by utilizing native Python features.

@wanghan-iapcm wanghan-iapcm requested a review from njzjz January 11, 2025 15:15
@wanghan-iapcm wanghan-iapcm linked an issue Jan 11, 2025 that may be closed by this pull request
Copy link

codspeed-hq bot commented Jan 11, 2025

CodSpeed Performance Report

Merging #774 will not alter performance

Comparing wanghan-iapcm:fix-scipy-const (759d3ab) with devel (25e7e4b)

Summary

✅ 2 untouched benchmarks

Copy link

coderabbitai bot commented Jan 11, 2025

📝 Walkthrough

Walkthrough

The changes in dpdata/unit.py focus on restructuring the management of physical constants. Instead of directly assigning constants from scipy.constants, a new physical_constants dictionary is introduced to store constants from various CODATA releases. A new function scipy_constant_value is implemented to retrieve constant values dynamically, with built-in error checking for obsolete keys. This approach provides a more centralized and flexible method for handling physical constants. Additionally, updates are made to the Python version compatibility in the workflow and documentation, reflecting a shift to support only Python 3.8 and above.

Changes

File Change Summary
dpdata/unit.py - Added physical_constants dictionary to store constants from multiple CODATA releases
- Introduced scipy_constant_value() function for dynamic constant retrieval
- Replaced direct constant assignments with function calls to scipy_constant_value()
.github/workflows/test.yml - Updated Python version matrix: removed "3.7", leaving "3.8" and "3.12"
README.md - Updated Python compatibility statement: changed from "supports Python 3.7 and above" to "supports Python 3.8 and above"
dpdata/stat.py - Changed @lru_cache() to @lru_cache in Errors and MultiErrors classes
pyproject.toml - Removed Python 3.7 classifier
- Updated requires-python to ">=3.8"
- Removed specific version constraint from optional dependencies
docs/make_format.py - Removed conditional imports for Literal, now importing directly from typing
dpdata/system.py - Updated method signatures in System class to use Literal for type safety in __getitem__ overloads
dpdata/utils.py - Updated import statement to include Literal directly from typing

Sequence Diagram

sequenceDiagram
    participant Code as Client Code
    participant Unit as unit.py
    participant Constants as physical_constants

    Code->>Unit: Request constant value
    Unit->>Unit: Call scipy_constant_value()
    Unit->>Constants: Retrieve value by key
    Constants-->>Unit: Return constant value
    Unit-->>Code: Return constant value
Loading

The sequence diagram illustrates how constant values are now retrieved through the scipy_constant_value() function, which acts as an intermediary between the client code and the physical_constants dictionary.

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: 2

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 25e7e4b and 8d14aa9.

📒 Files selected for processing (1)
  • dpdata/unit.py (1 hunks)
🧰 Additional context used
🪛 GitHub Actions: Python package
dpdata/unit.py

[error] 9-9: Failed to access '_codata' attribute from scipy.constants module. The line 'physical_constants.update(constants._codata._physical_constants_2002)' is trying to access a private/non-existent attribute.

dpdata/unit.py Show resolved Hide resolved
Comment on lines +9 to +13
physical_constants.update(constants._codata._physical_constants_2002)
physical_constants.update(constants._codata._physical_constants_2006)
physical_constants.update(constants._codata._physical_constants_2010)
physical_constants.update(constants._codata._physical_constants_2014)
physical_constants.update(constants._codata._physical_constants_2018)
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Avoid accessing private attributes of scipy.constants

Accessing private attributes like constants._codata._physical_constants_2002 is not recommended and leads to errors, as these attributes are not part of the public API and may not be available in all versions of SciPy. The pipeline failure indicates that the _codata attribute is inaccessible.

To fix this issue and pin the constants to the CODATA 2018 values, you can manually define the required constants. Here's how you can modify the code:

-physical_constants = {}
-# use constants up to 2018
-physical_constants.update(constants._codata._physical_constants_2002)
-physical_constants.update(constants._codata._physical_constants_2006)
-physical_constants.update(constants._codata._physical_constants_2010)
-physical_constants.update(constants._codata._physical_constants_2014)
-physical_constants.update(constants._codata._physical_constants_2018)

-# copied from scipy
-def scipy_constant_value(key: str) -> float:
-    constants._codata._check_obsolete(key)
-    return physical_constants[key][0]

+physical_constants = {
+    "Avogadro constant": 6.02214076e23,  # mol^-1
+    "elementary charge": 1.602176634e-19,  # C
+    "atomic unit of length": 5.29177210903e-11,  # m
+    "atomic unit of energy": 4.3597447222071e-18,  # J
+    "Rydberg constant": 10973731.568160,  # m^-1
+    "Planck constant": 6.62607015e-34,  # J·s
+    "speed of light in vacuum": 299792458,  # m·s^-1
+}
+
+def constant_value(key: str) -> float:
+    return physical_constants[key]

This approach ensures that you're using the CODATA 2018 values without relying on private attributes.

📝 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
physical_constants.update(constants._codata._physical_constants_2002)
physical_constants.update(constants._codata._physical_constants_2006)
physical_constants.update(constants._codata._physical_constants_2010)
physical_constants.update(constants._codata._physical_constants_2014)
physical_constants.update(constants._codata._physical_constants_2018)
physical_constants = {
"Avogadro constant": 6.02214076e23, # mol^-1
"elementary charge": 1.602176634e-19, # C
"atomic unit of length": 5.29177210903e-11, # m
"atomic unit of energy": 4.3597447222071e-18, # J
"Rydberg constant": 10973731.568160, # m^-1
"Planck constant": 6.62607015e-34, # J·s
"speed of light in vacuum": 299792458, # m·s^-1
}
def constant_value(key: str) -> float:
return physical_constants[key]
🧰 Tools
🪛 GitHub Actions: Python package

[error] 9-9: Failed to access '_codata' attribute from scipy.constants module. The line 'physical_constants.update(constants._codata._physical_constants_2002)' is trying to access a private/non-existent attribute.

@wanghan-iapcm wanghan-iapcm changed the title fix: pin scipy constants to version 2018 breaking: drop support of py3.7. fix: pin scipy constants to version 2018 Jan 11, 2025
Copy link

codecov bot commented Jan 11, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 85.12%. Comparing base (25e7e4b) to head (759d3ab).

Additional details and impacted files
@@            Coverage Diff             @@
##            devel     #774      +/-   ##
==========================================
- Coverage   85.16%   85.12%   -0.04%     
==========================================
  Files          81       81              
  Lines        7528     7528              
==========================================
- Hits         6411     6408       -3     
- Misses       1117     1120       +3     

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

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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8d14aa9 and 77c19de.

📒 Files selected for processing (4)
  • .github/workflows/test.yml (1 hunks)
  • README.md (1 hunks)
  • dpdata/stat.py (3 hunks)
  • pyproject.toml (1 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
dpdata/stat.py

119-119: Use of functools.lru_cache or functools.cache on methods can lead to memory leaks

(B019)


127-127: Use of functools.lru_cache or functools.cache on methods can lead to memory leaks

(B019)


156-156: Use of functools.lru_cache or functools.cache on methods can lead to memory leaks

(B019)


169-169: Use of functools.lru_cache or functools.cache on methods can lead to memory leaks

(B019)

🔇 Additional comments (4)
.github/workflows/test.yml (1)

12-12: LGTM! Python version update is consistent.

The removal of Python 3.7 from the test matrix aligns with the project's decision to support only Python 3.8 and above.

README.md (1)

11-11: LGTM! Documentation update is accurate.

The README correctly reflects the new minimum Python version requirement of 3.8.

pyproject.toml (1)

30-30: LGTM! Project configuration is properly updated.

The Python version requirement in pyproject.toml is consistent with the changes in other files.

dpdata/stat.py (1)

119-119: Verify the relevance of lru_cache changes.

These changes appear unrelated to the PR's objective of pinning scipy constants to version 2018. Please clarify if these changes are intentional and necessary for this PR.

Also applies to: 127-127, 156-156, 169-169

🧰 Tools
🪛 Ruff (0.8.2)

119-119: Use of functools.lru_cache or functools.cache on methods can lead to memory leaks

(B019)

@@ -116,15 +116,15 @@ class Errors(ErrorsBase):
SYSTEM_TYPE = LabeledSystem

@property
@lru_cache()
@lru_cache
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Remove @lru_cache to prevent potential memory leaks.

Using @lru_cache on methods can lead to memory leaks as it keeps a reference to self, potentially preventing proper garbage collection of class instances. Since these properties compute errors between two systems, the performance benefit of caching might not outweigh the risk of memory leaks.

Apply this diff to fix the issue:

    @property
-    @lru_cache
     def e_errors(self) -> np.ndarray:
         """Energy errors."""

    @property
-    @lru_cache
     def f_errors(self) -> np.ndarray:
         """Force errors."""

    @property
-    @lru_cache
     def e_errors(self) -> np.ndarray:
         """Energy errors."""

    @property
-    @lru_cache
     def f_errors(self) -> np.ndarray:
         """Force errors."""

If caching is necessary for performance reasons, consider:

  1. Using a different caching strategy that doesn't retain references to instances
  2. Implementing manual cache invalidation
  3. Moving the cached computation to a standalone function

Also applies to: 127-127, 156-156, 169-169

🧰 Tools
🪛 Ruff (0.8.2)

119-119: Use of functools.lru_cache or functools.cache on methods can lead to memory leaks

(B019)

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 (1)
dpdata/system.py (1)

14-15: Consider adding docstrings to overloads.

While the type overloads enhance type safety and IDE support, consider adding docstrings to explain the purpose and expected behavior of each overload.

Example:

@overload
def __getitem__(self, key: int | slice | list | np.ndarray) -> System:
+    """Get a subsystem by frame index.
+    
+    Parameters
+    ----------
+    key : int | slice | list | np.ndarray
+        Frame index or indices to select
+        
+    Returns
+    -------
+    System
+        A new system containing only the selected frames
+    """
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 77c19de and 759d3ab.

📒 Files selected for processing (3)
  • docs/make_format.py (1 hunks)
  • dpdata/system.py (1 hunks)
  • dpdata/utils.py (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • docs/make_format.py
🔇 Additional comments (2)
dpdata/utils.py (1)

6-6: LGTM! Import change aligns with Python 3.8+ requirement.

The direct import of Literal from typing is correct as it's natively available in Python 3.8+, which aligns with the PR objective to drop Python 3.7 support.

dpdata/system.py (1)

13-15: LGTM! Import changes improve code organization.

The import changes are well-organized and align with the Python 3.8+ requirement.

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.

[BUG] CICD Failure due to Scipy constant update
1 participant