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
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 6 additions & 4 deletions pyphare/pyphare/pharesee/hierarchy/hierarchy.py
Original file line number Diff line number Diff line change
Expand Up @@ -275,10 +275,11 @@ def global_min(self, qty, **kwargs):
for patch in lvl.patches:
pd = patch.patch_datas[qty]
if first:
m = pd.dataset[:].min()
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)
Comment on lines +278 to +282
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.


return m

Expand All @@ -289,10 +290,11 @@ def global_max(self, qty, **kwargs):
for patch in lvl.patches:
pd = patch.patch_datas[qty]
if first:
m = pd.dataset[:].max()
m = np.nanmax(pd.dataset[:])
first = False
else:
m = max(m, pd.dataset[:].max())
data_and_max = np.concatenate(([m], pd.dataset[:].flatten()))
m = np.nanmax(data_and_max)

return m

Expand Down
Loading