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

Fix: pyright error: Type "floating[Any]" is not assignable to return type "ndarray[Unknown, Unknown]" #765

Open
wants to merge 4 commits into
base: devel
Choose a base branch
from

Conversation

wanghan-iapcm
Copy link
Contributor

@wanghan-iapcm wanghan-iapcm commented Dec 10, 2024

Summary by CodeRabbit

  • Chores
    • Updated the version of the ruff-pre-commit repository for improved linting and formatting of Python code.
  • Bug Fixes
    • Adjusted return type annotations for error calculation functions and properties to enhance type consistency across error metrics.
    • Enhanced robustness of the remove_atom_names method by adding an assertion to prevent type-related issues.

Copy link

codspeed-hq bot commented Dec 10, 2024

CodSpeed Performance Report

Merging #765 will not alter performance

Comparing wanghan-iapcm:fix-pyright (c1c93fb) with devel (5423efe)

Summary

✅ 2 untouched benchmarks

Copy link

codecov bot commented Dec 10, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 85.02%. Comparing base (5423efe) to head (c1c93fb).

Additional details and impacted files
@@            Coverage Diff             @@
##            devel     #765      +/-   ##
==========================================
- Coverage   85.15%   85.02%   -0.14%     
==========================================
  Files          81       81              
  Lines        7526     7517       -9     
==========================================
- Hits         6409     6391      -18     
- Misses       1117     1126       +9     

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

Copy link

coderabbitai bot commented Dec 10, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

The changes in this pull request involve updates to three files: .pre-commit-config.yaml, dpdata/stat.py, and dpdata/system.py. The .pre-commit-config.yaml file is modified to update the version of the ruff-pre-commit repository from v0.8.1 to v0.8.2, affecting the linting and formatting hooks for Python code. In dpdata/stat.py, the return type annotations for several functions and properties related to error metrics are changed from np.float64 to np.floating[Any]. Additionally, in dpdata/system.py, an assertion is added to the remove_atom_names method to ensure that the variable picked_atom_idx is not of type np.bool.

Changes

File Change Summary
.pre-commit-config.yaml Updated ruff-pre-commit version from v0.8.1 to v0.8.2. Configuration structure unchanged.
dpdata/stat.py Changed return type annotations for mae, rmse, e_mae, e_rmse, f_mae, and f_rmse from np.float64 to np.floating[Any].
dpdata/system.py Added assertion in remove_atom_names method to ensure picked_atom_idx is not of type np.bool.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant PreCommit
    participant ErrorsBase

    User->>PreCommit: Trigger pre-commit hooks
    PreCommit->>ErrorsBase: Lint and format code
    ErrorsBase-->>PreCommit: Return formatted code
    PreCommit-->>User: Complete pre-commit checks
Loading

📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 099a163 and c1c93fb.

📒 Files selected for processing (1)
  • dpdata/system.py (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • dpdata/system.py

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. (Experiment)
  • @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

🧹 Outside diff range and nitpick comments (1)
dpdata/stat.py (1)

78-93: LGTM: Property type annotations are consistent

The property return types are correctly updated to match the underlying mae/rmse function signatures.

Consider adding type hints to the error arrays in e_errors and f_errors abstract properties to complete the typing chain:

@property
@abstractmethod
-def e_errors(self) -> np.ndarray:
+def e_errors(self) -> np.ndarray[Any, np.dtype[np.floating[Any]]]:
    """Energy errors."""

@property
@abstractmethod
-def f_errors(self) -> np.ndarray:
+def f_errors(self) -> np.ndarray[Any, np.dtype[np.floating[Any]]]:
    """Force errors."""
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 5423efe and 7c14d45.

📒 Files selected for processing (2)
  • .pre-commit-config.yaml (1 hunks)
  • dpdata/stat.py (4 hunks)
✅ Files skipped from review due to trivial changes (1)
  • .pre-commit-config.yaml
🔇 Additional comments (3)
dpdata/stat.py (3)

5-5: LGTM: Required import for type annotations

The addition of typing.Any import is necessary for the updated type annotations.


Line range hint 28-38: LGTM: Consistent type annotation update

The change to np.floating[Any] is consistent with the mae function and correctly represents the return type of the numpy operation chain.


Line range hint 12-22: LGTM: Type annotation matches numpy's behavior

The change from np.float64 to np.floating[Any] is correct as np.mean() can return different floating-point types depending on the input array's dtype.

✅ Verification successful

Let me verify the implementation of the mae function to ensure the return type annotation is correct.


Let me try a different pattern to get the function implementation.


LGTM: Type annotation change is correct

The implementation of mae function uses np.mean(np.abs(errors)) which returns a numpy floating-point type. The change from np.float64 to np.floating[Any] is more accurate as the return type depends on the input array's dtype. This is consistent across the codebase where other functions like rmse and error properties also use the same return type annotation.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify numpy's mean return type behavior
ast-grep --pattern 'np.mean($$$)' | rg -A 2 'mean'

Length of output: 259


Script:

#!/bin/bash
# Get the complete implementation of mae function
ast-grep --pattern 'def mae($_) {
  $$$
}'

Length of output: 44


Script:

#!/bin/bash
# Get the complete implementation of mae function
cat dpdata/stat.py

Length of output: 4633

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

🧹 Outside diff range and nitpick comments (1)
dpdata/system.py (1)

1052-1052: Good addition for type safety, but error message could be more descriptive.

The assertion helps catch cases where picked_atom_idx is a scalar boolean instead of a boolean array, which would cause type errors. This aligns with fixing the Pyright type error mentioned in the PR description.

Consider making the assertion message more descriptive to help developers understand the issue:

-        assert not isinstance(picked_atom_idx, np.bool)
+        assert not isinstance(picked_atom_idx, np.bool), "picked_atom_idx must be a boolean array, not a scalar boolean. This usually happens when all atoms are selected/deselected in the boolean operation."
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 7c14d45 and 099a163.

📒 Files selected for processing (1)
  • dpdata/system.py (1 hunks)

dpdata/system.py Outdated Show resolved Hide resolved
Signed-off-by: Jinzhe Zeng <[email protected]>
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