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

nan min/max to handle possible nan ghosts #923

Merged
merged 2 commits into from
Nov 12, 2024

Conversation

nicolasaunai
Copy link
Member

@nicolasaunai nicolasaunai commented Nov 11, 2024

Summary by CodeRabbit

  • New Features
    • Enhanced calculations for global minimum and maximum values to ignore NaN entries, improving data accuracy.
  • Bug Fixes
    • Improved error handling in the simulation property for better clarity on deserialization issues.
  • Refactor
    • Updated method signatures for better clarity and functionality within the PatchHierarchy class.

@nicolasaunai nicolasaunai added the bug 🔥 Something isn't working label Nov 11, 2024
Copy link

coderabbitai bot commented Nov 11, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

The changes in this pull request involve modifications to the global_min and global_max methods in the PatchHierarchy class located in hierarchy.py. The updates replace the standard min() and max() functions with np.nanmin() and np.nanmax() to ensure that NaN values are ignored during calculations. Additionally, error handling in the sim property method has been improved to raise a RuntimeError with a more descriptive message upon deserialization failure.

Changes

File Path Change Summary
pyphare/pyphare/pharesee/hierarchy/hierarchy.py Updated global_min and global_max methods to use np.nanmin() and np.nanmax(). Enhanced error handling in sim property method.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant PatchHierarchy
    participant Dataset

    User->>PatchHierarchy: Call global_min(qty)
    PatchHierarchy->>Dataset: Calculate np.nanmin(pd.dataset[:])
    Dataset-->>PatchHierarchy: Return minimum value
    PatchHierarchy-->>User: Return global minimum

    User->>PatchHierarchy: Call global_max(qty)
    PatchHierarchy->>Dataset: Calculate np.nanmax(pd.dataset[:])
    Dataset-->>PatchHierarchy: Return maximum value
    PatchHierarchy-->>User: Return global maximum
Loading

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 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.

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.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between e61b34c and de920ac.

📒 Files selected for processing (1)
  • pyphare/pyphare/pharesee/hierarchy/hierarchy.py (2 hunks)

Comment on lines 293 to 297
m = np.nanmax(pd.dataset[:])
first = False
else:
m = max(m, pd.dataset[:].max())
data_and_max = np.concatenate(([m], pd.dataset[:]))
m = np.nanmax(data_and_max)
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Refactor to reduce code duplication with global_min.

The global_max implementation duplicates the logic from global_min. Consider extracting a common utility function to handle both cases.

Here's a suggested refactoring:

+    def _global_minmax(self, qty, operation, time=None):
+        """Helper function for global min/max calculations
+        Args:
+            qty: The quantity to compute min/max for
+            operation: np.nanmin or np.nanmax
+            time: Optional timestamp
+        Returns:
+            The global min or max value
+        Raises:
+            ValueError: If all values are NaN
+        """
+        time = time or self._default_time()
+        values = []
+        for _, lvl in self.levels(time).items():
+            for patch in lvl.patches:
+                values.append(patch.patch_datas[qty].dataset[:])
+        all_values = np.concatenate(values)
+        if np.all(np.isnan(all_values)):
+            raise ValueError("All values are NaN")
+        return operation(all_values)
+
+    def global_min(self, qty, **kwargs):
+        return self._global_minmax(qty, np.nanmin, kwargs.get("time"))
+
+    def global_max(self, qty, **kwargs):
+        return self._global_minmax(qty, np.nanmax, kwargs.get("time"))

This refactoring:

  1. Eliminates code duplication
  2. Improves performance by avoiding repeated array concatenations
  3. Properly handles the all-NaN case
  4. Makes the code more maintainable

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines 278 to 282
m = np.nanmin(pd.dataset[:])
first = False
else:
m = min(m, pd.dataset[:].min())
data_and_min = np.concatenate(([m], pd.dataset[:]))
m = np.nanmin(data_and_min)
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider optimizing the min calculation and handling edge cases.

The current implementation using array concatenation in each iteration is not optimal. Additionally, the case where all values are NaN should be handled explicitly.

Consider this more efficient implementation:

-                    m = np.nanmin(pd.dataset[:])
-                    first = False
-                else:
-                    data_and_min = np.concatenate(([m], pd.dataset[:]))
-                    m = np.nanmin(data_and_min)
+                    m = pd.dataset[:]
+                    first = False
+                else:
+                    m = np.append(m, pd.dataset[:])
+        if np.all(np.isnan(m)):
+            raise ValueError("All values are NaN")
+        return np.nanmin(m)

Committable suggestion skipped: line range outside the PR's diff.

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.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between de920ac and 58570ba.

📒 Files selected for processing (1)
  • pyphare/pyphare/pharesee/hierarchy/hierarchy.py (2 hunks)
🔇 Additional comments (1)
pyphare/pyphare/pharesee/hierarchy/hierarchy.py (1)

293-297: Reduce code duplication with global_min.

The implementation duplicates the logic from global_min.

As suggested in a previous review, consider extracting a common utility function to handle both cases. This would:

  1. Eliminate code duplication
  2. Ensure consistent handling of edge cases
  3. Make the code more maintainable

The previous review comment provided a detailed implementation suggestion.

Comment on lines +278 to +282
m = np.nanmin(pd.dataset[:])
first = False
else:
m = min(m, pd.dataset[:].min())
data_and_min = np.concatenate(([m], pd.dataset[:].flatten()))
m = np.nanmin(data_and_min)
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider optimizing the min calculation and handling edge cases.

While using np.nanmin correctly handles NaN values, the current implementation has some performance concerns:

  1. Concatenating arrays in a loop is inefficient (O(n²) complexity).
  2. No explicit handling for the case where all values are NaN.

Consider this more efficient implementation:

-                    m = np.nanmin(pd.dataset[:])
-                    first = False
-                else:
-                    data_and_min = np.concatenate(([m], pd.dataset[:].flatten()))
-                    m = np.nanmin(data_and_min)
+                    values = pd.dataset[:]
+                    first = False
+                else:
+                    values = np.append(values, pd.dataset[:])
+        if np.all(np.isnan(values)):
+            raise ValueError("All values are NaN")
+        return np.nanmin(values)

Committable suggestion skipped: line range outside the PR's diff.

Copy link
Member

@PhilipDeegan PhilipDeegan left a comment

Choose a reason for hiding this comment

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

Uploading image.png…

@PhilipDeegan PhilipDeegan merged commit c3f0fc3 into PHAREHUB:master Nov 12, 2024
12 checks passed
UCaromel pushed a commit to UCaromel/PHARE that referenced this pull request Nov 13, 2024
* nan min/max to handle possible nan ghosts

* flatten
UCaromel pushed a commit to UCaromel/PHARE that referenced this pull request Nov 13, 2024
* nan min/max to handle possible nan ghosts

* flatten
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug 🔥 Something isn't working
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants