Skip to content

Conversation

@nicolasaunai
Copy link
Member

@nicolasaunai nicolasaunai commented Jul 26, 2025

See llnl/SAMRAI#292 (comment)

  • test copy indeed occurs before refinement when this variable is set to false.

This PR changes the order of copy and refine operations during schedules. Using fine boundary represent variable boolean set to false in the Variable.

With this PR copies are done before refinement. This is tricky and leaves issues for the refinement operator not to overwrite now previously done copy. These issues are addressed in this PR by setting nans.

Consequently, the PR updates the RefineOperator so that it assigns values only to the nodes that have NaN values.

This thus sets the NaN on construction of NdArrayVectorand on the PatchData ghost box before ghost schedules apply.

Setting NaNs on construction breaks some tests which are fixed so that fields and vecfields they use are properly initialized to 0.

We also see in this PR that in 1D Jx is not used by Ampere (rightfully) and thus used by Ohm (in JxB) with its "cosntruction-initialization value". Now being constructed-init to NaN, J is explicitly set to 0 on init (model init, fine level init and regrid init).

The PR also adds nice plots for debugging when advance test field overlap equal fails.

image

Blue are overlapped PatchData ghost boxes, red box is the overlap box (pyphare one), red markers indicate lower left corner of the cell that fails

  • overwrite_interior now also default behavior for refinement with FieldVariableFillPattern

Note: This PR should probably not being merged as is since master currently have multiple components B and E registered to the same RefineAlgorithm and thus SAMRAI uses the first geometry, which now leaves NaNs (rather than wrong 0s) on the mesh. This should be fixed with TensorFieldData.

- PatchData NaN initialized on construction
- fix tests failing as result of above
- comment a field refinement test (useless, wrong refinement op for E,B)
- debug plots for advance field overlap test
- copy done before refinement (boolean false in variable)
- overwrite_interior false also for refinement is default for
  FieldFillPattern
- J manually init to zero in model init, fine init and regrid init (Jx
  unused in ampere but used in Ohm with its now NaN values)
- Grid/NdarrayVector take default value overrides (for test)
- UsableTensorField is default constructed with zero init.

@nicolasaunai nicolasaunai added this to the 1.0 milestone Jul 26, 2025
@nicolasaunai nicolasaunai added bug 🔥 Something isn't working SAMRAI all issues dealing with the SAMRAI dependency amr labels Jul 26, 2025
@coderabbitai
Copy link

coderabbitai bot commented Jul 26, 2025

📝 Walkthrough

Walkthrough

This update introduces NaN-initialization for floating-point data arrays and grids, with new constructors and concepts enforcing this behavior. It refactors ghost cell filling and refinement routines to avoid overwriting non-NaN values, and updates interfaces to pass full patch level objects instead of level numbers. Additional debug output and zero-initialization are added for improved diagnostics and test reliability.

Changes

Cohort / File(s) Change Summary
NaN Initialization for Floating-Point Arrays/Grids
src/core/data/ndarray/ndarray_vector.hpp, src/core/data/grid/grid.hpp
Introduces a FloatingPoint concept; adds constructors to initialize floating-point arrays and grids with NaN; existing constructors for non-floating-point types are constrained accordingly.
Field and Vector Field Refinement/Interpolation
src/amr/data/field/refine/field_refiner.hpp, src/amr/data/field/refine/electric_field_refiner.hpp
Updates refinement logic to only assign interpolated values if the destination is NaN, preventing overwriting of valid data.
Patch Level Interface Refactor
src/amr/messengers/hybrid_messenger_strategy.hpp, src/amr/messengers/hybrid_messenger.hpp, src/amr/messengers/hybrid_hybrid_messenger_strategy.hpp, src/amr/messengers/mhd_hybrid_messenger_strategy.hpp, src/amr/solvers/solver_ppc.hpp, src/amr/level_initializer/hybrid_level_initializer.hpp
Changes method signatures to accept a PatchLevel object instead of a level number for ghost cell filling; updates implementations and calls accordingly; adds debug output and explicit NaN/zero setting for ghosts.
Field Geometry and Overlap Logic
src/amr/data/field/field_geometry.hpp, src/amr/data/field/field_variable_fill_pattern.hpp
Removes pureInteriorFieldBox logic and replaces it with interiorFieldBox; modifies fill pattern overlap computation to respect the overwrite_interior_ flag and filter overlaps accordingly.
Field Variable Construction
src/amr/data/field/field_variable.hpp
Changes the default value of fineBoundaryRepresentsVariable from true to false in the constructor; adds explanatory comment.
Field Data Copy and Refine Debugging
src/amr/data/field/field_data.hpp, src/amr/data/field/refine/field_refine_operator.hpp
Adds debug print statements to output box states during copy and refine operations for diagnostics.
Hybrid Model and Test Initialization
src/amr/physical_models/hybrid_model.hpp, tests/core/numerics/interpolator/test_main.cpp, tests/core/data/ndarray/test_main.cpp, tests/core/data/tensorfield/test_tensorfield_fixtures.hpp, tests/core/numerics/ion_updater/test_updater.cpp
Ensures zero-initialization of fields and grids in model initialization and test fixtures; updates test code to use explicit zero initialization for reliability.
Simulator and AMR Field Tests
tests/simulator/test_advance.py, tests/simulator/advance/test_fields_advance_1d.py, tests/amr/data/field/refine/CMakeLists.txt
Expands diagnostics and visualization for field overlap assertions; disables some broken field refinement tests; minor parameter and cleanup changes in test code.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Grid
    participant NdArrayVector

    User->>Grid: Construct with floating-point type
    Grid->>NdArrayVector: Initialize internal vector with NaN
    NdArrayVector-->>Grid: Returns NaN-initialized array
    Grid-->>User: Returns NaN-initialized grid
Loading
sequenceDiagram
    participant Solver
    participant HybridMessenger
    participant HybridMessengerStrategy
    participant PatchLevel

    Solver->>HybridMessenger: fillElectricGhosts(E, PatchLevel, fillTime)
    HybridMessenger->>HybridMessengerStrategy: fillElectricGhosts(E, PatchLevel, fillTime)
    HybridMessengerStrategy->>PatchLevel: Set NaN on ghost nodes
    HybridMessengerStrategy->>PatchLevel: Fill electric ghosts
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Suggested reviewers

  • PhilipDeegan

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.


📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6d50a25 and 8c5750d.

📒 Files selected for processing (23)
  • src/amr/data/field/field_data.hpp (1 hunks)
  • src/amr/data/field/field_geometry.hpp (1 hunks)
  • src/amr/data/field/field_variable.hpp (1 hunks)
  • src/amr/data/field/field_variable_fill_pattern.hpp (2 hunks)
  • src/amr/data/field/refine/electric_field_refiner.hpp (8 hunks)
  • src/amr/data/field/refine/field_refine_operator.hpp (1 hunks)
  • src/amr/data/field/refine/field_refiner.hpp (3 hunks)
  • src/amr/level_initializer/hybrid_level_initializer.hpp (2 hunks)
  • src/amr/messengers/hybrid_hybrid_messenger_strategy.hpp (7 hunks)
  • src/amr/messengers/hybrid_messenger.hpp (2 hunks)
  • src/amr/messengers/hybrid_messenger_strategy.hpp (1 hunks)
  • src/amr/messengers/mhd_hybrid_messenger_strategy.hpp (1 hunks)
  • src/amr/physical_models/hybrid_model.hpp (2 hunks)
  • src/amr/solvers/solver_ppc.hpp (6 hunks)
  • src/core/data/grid/grid.hpp (3 hunks)
  • src/core/data/ndarray/ndarray_vector.hpp (3 hunks)
  • tests/amr/data/field/refine/CMakeLists.txt (1 hunks)
  • tests/core/data/ndarray/test_main.cpp (6 hunks)
  • tests/core/data/tensorfield/test_tensorfield_fixtures.hpp (2 hunks)
  • tests/core/numerics/interpolator/test_main.cpp (2 hunks)
  • tests/core/numerics/ion_updater/test_updater.cpp (1 hunks)
  • tests/simulator/advance/test_fields_advance_1d.py (2 hunks)
  • tests/simulator/test_advance.py (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • tests/amr/data/field/refine/CMakeLists.txt
🚧 Files skipped from review as they are similar to previous changes (21)
  • src/amr/level_initializer/hybrid_level_initializer.hpp
  • src/amr/data/field/field_data.hpp
  • src/amr/messengers/mhd_hybrid_messenger_strategy.hpp
  • src/amr/data/field/refine/electric_field_refiner.hpp
  • tests/core/data/ndarray/test_main.cpp
  • src/amr/messengers/hybrid_messenger.hpp
  • src/core/data/ndarray/ndarray_vector.hpp
  • tests/core/data/tensorfield/test_tensorfield_fixtures.hpp
  • tests/core/numerics/ion_updater/test_updater.cpp
  • src/amr/data/field/refine/field_refine_operator.hpp
  • tests/core/numerics/interpolator/test_main.cpp
  • src/amr/messengers/hybrid_messenger_strategy.hpp
  • src/amr/data/field/refine/field_refiner.hpp
  • src/amr/messengers/hybrid_hybrid_messenger_strategy.hpp
  • src/amr/solvers/solver_ppc.hpp
  • src/amr/physical_models/hybrid_model.hpp
  • src/core/data/grid/grid.hpp
  • tests/simulator/advance/test_fields_advance_1d.py
  • src/amr/data/field/field_variable.hpp
  • src/amr/data/field/field_variable_fill_pattern.hpp
  • src/amr/data/field/field_geometry.hpp
🧰 Additional context used
🧠 Learnings (1)
📓 Common learnings
Learnt from: rochSmets
PR: PHAREHUB/PHARE#921
File: src/core/data/ions/ions.hpp:138-142
Timestamp: 2025-02-06T10:52:56.461Z
Learning: In PHARE's physics simulations, handling of zero density cells in velocity calculations must be based on physical requirements rather than simple numerical fixes. The solution must account for population-specific behavior in the bulk velocity computation.
🪛 Ruff (0.12.2)
tests/simulator/test_advance.py

290-290: matplotlib.pyplot imported but unused

Remove unused import: matplotlib.pyplot

(F401)


306-306: Ambiguous variable name: l

(E741)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: build (ubuntu-latest, clang)
  • GitHub Check: build (ubuntu-latest, gcc)
  • GitHub Check: build (macos-13)
  • GitHub Check: build (macos-latest)
  • GitHub Check: build (macos-14)
  • GitHub Check: Analyze (cpp)
🔇 Additional comments (1)
tests/simulator/test_advance.py (1)

290-401: Excellent debugging enhancement for AMR field overlap failures.

This comprehensive debugging code provides valuable visualization and diagnostic capabilities when field overlap tests fail. The matplotlib plotting clearly shows:

  • Overlap boxes and ghost boxes with distinct colors and line styles
  • Failing cell locations marked with different symbols
  • Detailed error metrics and patch information

This will significantly aid in debugging AMR field boundary issues mentioned in the PR objectives.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this 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.

@nicolasaunai
Copy link
Member Author

nicolasaunai commented Jul 26, 2025

(executed on test/functional/harris_2d.py modified with 20 nx cells for it to be fast)

Breakpoint in RefineAlgorithm::registerRefine (for Balgo) indeed shows the internal boolean set to false now:

image

Breakpoint at:

  • magnetic regriding schedule fillData() call
  • continue up to RefineSchedule::recursiveFill()
  • breakpoint at FieldData::copy_() and at FieldRefineOperator::refine()

continue : first hits copy()

image

continue: then hits refine()

image

@nicolasaunai
Copy link
Member Author

MPI test fails : test_overlaped_fields_are_equal_with_min_max_patch_size_of_max_ghosts_5
2D Ex
Max absolute difference: 0.00089797
Mismatched elements: 14 / 162

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

🧹 Nitpick comments (3)
tests/simulator/test_advance.py (3)

290-291: Remove unused matplotlib.pyplot import.

The matplotlib.pyplot import is not used in the current code. Only Rectangle from matplotlib.patches is needed.

-                        import matplotlib.pyplot as plt
-                        from matplotlib.patches import Rectangle
+                        from matplotlib.patches import Rectangle

293-300: Improve variable naming for better readability.

The variable l in the list comprehension is ambiguous. Use more descriptive names for better code clarity.

                        def makerec(lower, upper, dl, fc="none", ec="g", lw=1, ls="-"):
                            origin = (lower[0] * dl[0], lower[1] * dl[1])
                            sizex, sizey = [
-                               (u - l) * d for u, l, d in zip(upper, lower, dl)
+                               (u - low) * d for u, low, d in zip(upper, lower, dl)
                            ]
                            return Rectangle(
                                origin, sizex, sizey, fc=fc, ec=ec, ls=ls, lw=lw
                            )

302-330: Excellent debugging enhancement with minor suggestions.

The comprehensive visualization code provides valuable debugging context for field overlap failures. The implementation correctly highlights failing overlap boxes and generates descriptive plots.

Consider these improvements:

  1. Extract visualization logic: Consider moving this debugging code to a separate method to improve readability and reusability.

  2. Add dimensionality check: The code assumes 2D data when accessing pd1.layout.dl. Add a check for the data dimensionality:

if len(pd1.layout.dl) >= 2:  # Ensure 2D or higher
    # existing plotting code
else:
    print("Visualization skipped: only supports 2D+ data")
  1. Optional conditional execution: Consider adding a flag to control when expensive plotting occurs:
if self.debug_plots:  # or environment variable check
    # plotting code
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 327086d and 49f4c20.

📒 Files selected for processing (1)
  • tests/simulator/test_advance.py (2 hunks)
🧰 Additional context used
🪛 Ruff (0.12.2)
tests/simulator/test_advance.py

290-290: matplotlib.pyplot imported but unused

Remove unused import: matplotlib.pyplot

(F401)


296-296: Ambiguous variable name: l

(E741)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (7)
  • GitHub Check: Analyze (python)
  • GitHub Check: Analyze (cpp)
  • GitHub Check: build (macos-13)
  • GitHub Check: build (macos-latest)
  • GitHub Check: build (macos-14)
  • GitHub Check: build (ubuntu-latest, clang)
  • GitHub Check: build (ubuntu-latest, gcc)

Comment on lines +343 to +404
# if self.rethrow_:
# raise e
# return diff_boxes(slice1, slice2, box)
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 making error handling behavior configurable.

Commenting out the error re-throwing and diff_boxes return significantly changes the test behavior from fail-fast to log-and-continue. While this provides better debugging information, it could mask legitimate test failures.

Consider making this behavior configurable:

-                        # if self.rethrow_:
-                        #     raise e
-                        # return diff_boxes(slice1, slice2, box)
+                        if getattr(self, 'rethrow_', True):
+                            raise e
+                        return diff_boxes(slice1, slice2, box)

This allows debugging mode when needed while preserving the original test semantics by default. You could set self.rethrow_ = False in specific test cases or via environment variables when debugging is required.

📝 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
# if self.rethrow_:
# raise e
# return diff_boxes(slice1, slice2, box)
if getattr(self, 'rethrow_', True):
raise e
return diff_boxes(slice1, slice2, box)
🤖 Prompt for AI Agents
In tests/simulator/test_advance.py around lines 343 to 345, the error handling
code is commented out, changing the behavior from fail-fast to log-and-continue.
To fix this, introduce a configurable flag such as self.rethrow_ that controls
whether to re-raise the exception or continue after logging. Use this flag to
conditionally raise the error or return diff_boxes, allowing tests to run in
either fail-fast or debug mode based on configuration or environment variables.

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

♻️ Duplicate comments (1)
tests/simulator/test_advance.py (1)

353-355: Consider making error handling behavior configurable.

Commenting out the error re-throwing and diff_boxes return significantly changes the test behavior from fail-fast to log-and-continue. While this provides better debugging information, it could mask legitimate test failures.

Consider making this behavior configurable:

-                        # if self.rethrow_:
-                        #     raise e
-                        # return diff_boxes(slice1, slice2, box)
+                        if getattr(self, 'rethrow_', True):
+                            raise e
+                        return diff_boxes(slice1, slice2, box)

This allows debugging mode when needed while preserving the original test semantics by default. You could set self.rethrow_ = False in specific test cases or via environment variables when debugging is required.

🧹 Nitpick comments (3)
tests/simulator/test_advance.py (3)

290-292: Fix unused import and improve import organization.

The matplotlib.pyplot import is unused since the code uses datahier.plot() method instead. Additionally, consider moving these imports to the top of the method or using conditional imports.

-        import matplotlib.pyplot as plt
-        from matplotlib.patches import Rectangle
+        from matplotlib.patches import Rectangle

298-307: Fix ambiguous variable name in lambda function.

The lambda function uses an ambiguous variable name l which reduces code readability.

-                            def makerec(
-                                lower, upper, dl, fc="none", ec="g", lw=1, ls="-"
-                            ):
-                                origin = (lower[0] * dl[0], lower[1] * dl[1])
-                                sizex, sizey = [
-                                    (u - l) * d for u, l, d in zip(upper, lower, dl)
-                                ]
-                                return Rectangle(
-                                    origin, sizex, sizey, fc=fc, ec=ec, ls=ls, lw=lw
-                                )
+                            def makerec(
+                                lower, upper, dl, fc="none", ec="g", lw=1, ls="-"
+                            ):
+                                origin = (lower[0] * dl[0], lower[1] * dl[1])
+                                sizex, sizey = [
+                                    (upper_val - lower_val) * delta for upper_val, lower_val, delta in zip(upper, lower, dl)
+                                ]
+                                return Rectangle(
+                                    origin, sizex, sizey, fc=fc, ec=ec, ls=ls, lw=lw
+                                )

293-342: Consider adding 1D and 3D debugging support.

The debugging visualization code only handles 2D cases. Consider adding support for other dimensions or at least documenting this limitation.

                        if box.ndim == 2:
                            failed_i, failed_j = np.where(
                                np.abs(slice1 - slice2) > 5.5e-15
                            )
+                        elif box.ndim == 1:
+                            failed_i = np.where(np.abs(slice1 - slice2) > 5.5e-15)[0]
+                            print(f"1D debugging: failed indices: {failed_i}")
+                        else:
+                            print(f"Debugging visualization not implemented for {box.ndim}D")
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 49f4c20 and cd7ae1a.

📒 Files selected for processing (2)
  • tests/simulator/advance/test_fields_advance_2d.py (1 hunks)
  • tests/simulator/test_advance.py (1 hunks)
🧰 Additional context used
🪛 Ruff (0.12.2)
tests/simulator/test_advance.py

290-290: matplotlib.pyplot imported but unused

Remove unused import: matplotlib.pyplot

(F401)


303-303: Ambiguous variable name: l

(E741)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (7)
  • GitHub Check: Analyze (python)
  • GitHub Check: Analyze (cpp)
  • GitHub Check: build (macos-latest)
  • GitHub Check: build (macos-14)
  • GitHub Check: build (macos-13)
  • GitHub Check: build (ubuntu-latest, clang)
  • GitHub Check: build (ubuntu-latest, gcc)
🔇 Additional comments (1)
tests/simulator/test_advance.py (1)

290-355: Confirm debug instrumentation isolates MPI overlap discrepancy

The added Rectangle overlays and print statements in tests/simulator/test_advance.py are self-contained (no other MPI-overlap debug patterns detected). Please validate that:

  • The generated PNGs clearly highlight the exact failing cells and hierarchy levels.
  • The console logs (ghost_box, box, interp_order, coarsest_time, failed_i/j) provide enough context to reproduce and pinpoint the numerical mismatch.

After you’ve identified the root cause, consider guarding or removing these heavy debugging blocks behind a verbose/debug flag.

Comment on lines 70 to 71
smallest_patch_size=smallest_patch_size + 1,
largest_patch_size=smallest_patch_size + 1,
Copy link

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Verify the rationale for increasing patch size parameters.

The patch size parameters have been increased by 1 unit for both smallest_patch_size and largest_patch_size. This change affects the hierarchy setup used in the overlap testing.

Please clarify the reasoning behind this adjustment and verify that it's necessary for the fine_boundary_represents_var changes. Run the following script to check if this change is related to the reported MPI test failure:


🏁 Script executed:

#!/bin/bash
# Description: Search for references to patch size parameters and related test failures

# Check for other patch size adjustments in the codebase
rg -A 3 -B 3 "smallest_patch_size.*\+.*1|largest_patch_size.*\+.*1"

# Look for test failure reports or comments about this specific test
rg -A 5 -B 5 "test_overlaped_fields_are_equal_with_min_max_patch_size_of_max_ghosts"

# Search for any comments or documentation about patch size requirements
rg -A 3 -B 3 "patch.*size.*ghost|ghost.*patch.*size"

Length of output: 7513


🏁 Script executed:

#!/bin/bash
# Display the first 100 lines to inspect how patch sizes are set up
head -n 100 tests/simulator/advance/test_fields_advance_2d.py

Length of output: 3102


🏁 Script executed:

#!/bin/bash
# Locate and display the definition of check_patch_size
rg -n "def check_patch_size" -A 10 -B 3 pyphare/pyphare/pharein/simulation.py

Length of output: 585


🏁 Script executed:

#!/bin/bash
# Display the full check_patch_size function for context
sed -n '380,450p' pyphare/pyphare/pharein/simulation.py

Length of output: 2915


🏁 Script executed:

#!/bin/bash
# Display lines 450-550 to capture the end of check_patch_size
sed -n '450,550p' pyphare/pyphare/pharein/simulation.py

Length of output: 3661


Clarify and correct patch-size assignment in the test

It looks like in test_overlaped_fields_are_equal_with_min_max_patch_size_of_max_ghosts you’re doing:

largest_patch_size, smallest_patch_size = check_patch_size(...)

datahier = self.getHierarchy(
    …,
    smallest_patch_size=smallest_patch_size + 1,
    largest_patch_size=smallest_patch_size + 1,
    …
)

– check_patch_size returns (largest_patch_size, smallest_patch_size), but here the first returned value (which is always None when not passed in) is assigned to largest_patch_size and discarded.
– You then use the minimal patch size for both smallest and largest, and bump it by an extra +1.

Please:

  • Confirm that you intentionally ignore the computed largest_patch_size and use the minimal patch size for both parameters.
  • Explain why an additional +1 (beyond the built-in bump in check_patch_size) is required for this test.
  • For clarity, consider unpacking as _, min_ps = check_patch_size(...) and then passing min_ps + 1 to both parameters or use the actual returned largest_patch_size if you intended different min/max values.
  • Add a code comment above the call to document the reason for the extra +1 so future readers understand why the test needs a patch size two cells larger than the max ghost width.
🤖 Prompt for AI Agents
In tests/simulator/advance/test_fields_advance_2d.py around lines 70 to 71, the
unpacking of check_patch_size's return values is confusing and potentially
incorrect because largest_patch_size is assigned the first returned value but
then discarded, and smallest_patch_size is used for both smallest_patch_size and
largest_patch_size parameters with an added +1. To fix this, explicitly unpack
as _, min_ps = check_patch_size(...) to clarify ignoring the first value, then
pass min_ps + 1 to both smallest_patch_size and largest_patch_size parameters.
Add a comment above this call explaining why the extra +1 is necessary, such as
to ensure the patch size is two cells larger than the max ghost width for the
test's correctness.

@nicolasaunai
Copy link
Member Author

Ok right now I think the problem is that if we have the copy done before the refinement and we have this configuration:

patch B below patch A.
patch A height is == ghost cell nbr.
patch A top border is level ghost

then patch B top ghosts go up to patch A top border.
Copy happens before refinement therefore:

patch B gets its ghosts from patch A, up to its top border.

then patch A gets its top level ghost refined, including top border.

This created a mismatch between A top border and B top ghost border.

Note this mismatch disappears if A gets refined before B copies the values, thus consistent with master not failing.

I do not think we can trust box clustering to never give us patches smaller or equal to the ghost size.
Right now, just for the sake of testing, I have set the min patch size to be ghost nbr +1 to see if tests pass (the one failing does pass locally).
But I think we want to revert that to ghost nbr.

What probably is TBD is that level ghost filling should probably never overwrite borders. A priori, border faces are solution values and thus if it didn't probably the test would pass.

TBC.

@nicolasaunai
Copy link
Member Author

now also changed test_advance_field1d.py to have smallest patch size = ghost nbr+1 because that was also failing.

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

♻️ Duplicate comments (1)
tests/simulator/test_advance.py (1)

359-361: Consider making error handling behavior configurable.

Commenting out the error re-throwing and diff_boxes return significantly changes the test behavior from fail-fast to log-and-continue. While this provides better debugging information, it could mask legitimate test failures.

Consider making this behavior configurable:

-                        # if self.rethrow_:
-                        #     raise e
-                        # return diff_boxes(slice1, slice2, box)
+                        if getattr(self, 'rethrow_', True):
+                            raise e
+                        return diff_boxes(slice1, slice2, box)

This allows debugging mode when needed while preserving the original test semantics by default. You could set self.rethrow_ = False in specific test cases or via environment variables when debugging is required.

🧹 Nitpick comments (1)
tests/simulator/test_advance.py (1)

301-310: Fix ambiguous variable name and improve code clarity.

The variable name l in the list comprehension is ambiguous and flagged by static analysis. Also consider adding explicit handling for 3D cases.

Apply this diff to fix the ambiguous variable name:

-                                sizex, sizey = [
-                                    (u - l) * d for u, l, d in zip(upper, lower, dl)
-                                ]
+                                sizex, sizey = [
+                                    (u - low) * d for u, low, d in zip(upper, lower, dl)
+                                ]
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 184232e and 2b2be90.

📒 Files selected for processing (2)
  • tests/simulator/advance/test_fields_advance_1d.py (1 hunks)
  • tests/simulator/test_advance.py (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/simulator/advance/test_fields_advance_1d.py
🧰 Additional context used
🪛 Ruff (0.12.2)
tests/simulator/test_advance.py

290-290: matplotlib.pyplot imported but unused

Remove unused import: matplotlib.pyplot

(F401)


306-306: Ambiguous variable name: l

(E741)

🔇 Additional comments (1)
tests/simulator/test_advance.py (1)

290-292: Conditional imports are appropriate here.

The matplotlib imports are correctly placed inside the exception handler to avoid loading heavy dependencies unless debugging is needed. The static analysis warning about unused matplotlib.pyplot is a false positive - the import is used implicitly through the datahier.plot() calls later in the code.

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

♻️ Duplicate comments (1)
tests/simulator/test_advance.py (1)

394-396: Consider making error handling behavior configurable.

The commented-out error re-throwing significantly changes test behavior from fail-fast to log-and-continue, potentially masking legitimate test failures. This matches a previous review comment about the same issue.

While the enhanced debugging information is valuable, consider making this behavior configurable:

-                        # if self.rethrow_:
-                        #     raise e
-                        # return diff_boxes(slice1, slice2, box)
+                        if getattr(self, 'rethrow_', True):
+                            raise e
+                        return diff_boxes(slice1, slice2, box)

This allows debugging mode when needed while preserving the original test semantics by default.

🧹 Nitpick comments (3)
src/amr/data/field/field_variable_fill_pattern.hpp (1)

107-120: Consider optimizing the dynamic casting and improve code clarity.

The conditional logic correctly implements the intended behavior, but there are some concerns:

  1. Performance: Two separate dynamic_cast operations are performed when overwrite_interior_ is false, which could be expensive in performance-critical paths.

  2. Code clarity: The variable names geom, basic_overlap, and casted could be more descriptive.

Consider this refactor to optimize performance and improve readability:

-        auto geom = pdf.getBoxGeometry(patch_box);
-        auto basic_overlap
-            = pdf.getBoxGeometry(patch_box)->setUpOverlap(overlap_boxes, transformation);
+        auto geom = pdf.getBoxGeometry(patch_box);
+        auto basic_overlap = geom->setUpOverlap(overlap_boxes, transformation);

         if (overwrite_interior_)
             return basic_overlap;

-        auto& overlap         = dynamic_cast<FieldOverlap const&>(*basic_overlap);
-        auto destinationBoxes = overlap.getDestinationBoxContainer();
-        auto& casted          = dynamic_cast<FieldGeometryBase<dimension> const&>(*geom);
-        destinationBoxes.removeIntersections(casted.interiorFieldBox());
+        auto& field_overlap = dynamic_cast<FieldOverlap const&>(*basic_overlap);
+        auto destinationBoxes = field_overlap.getDestinationBoxContainer();
+        auto& field_geometry = dynamic_cast<FieldGeometryBase<dimension> const&>(*geom);
+        destinationBoxes.removeIntersections(field_geometry.interiorFieldBox());

-        return std::make_shared<FieldOverlap>(destinationBoxes, overlap.getTransformation());
+        return std::make_shared<FieldOverlap>(destinationBoxes, field_overlap.getTransformation());

This eliminates the redundant getBoxGeometry call and uses more descriptive variable names.

tests/simulator/test_advance.py (2)

290-292: Remove unused matplotlib.pyplot import.

The matplotlib.pyplot import is unused according to static analysis. The code only uses Rectangle from matplotlib.patches.

-                        import matplotlib.pyplot as plt
-                        from matplotlib.patches import Rectangle
+                        from matplotlib.patches import Rectangle

293-380: Consider extracting visualization logic to a helper method.

The debugging visualization code is quite extensive and could benefit from being extracted to a separate helper method to improve maintainability and readability of the main test method.

Consider creating a helper method like _create_overlap_failure_plots(self, pd1, pd2, box, failed_indices, ilvl, datahier) to encapsulate this visualization logic. This would:

  1. Reduce the complexity of the main test method
  2. Make the visualization code reusable
  3. Improve code organization and readability
  4. Make the test method easier to understand and maintain
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2b2be90 and ce13e57.

📒 Files selected for processing (6)
  • src/amr/data/field/field_geometry.hpp (1 hunks)
  • src/amr/data/field/field_variable_fill_pattern.hpp (1 hunks)
  • src/amr/messengers/hybrid_hybrid_messenger_strategy.hpp (1 hunks)
  • tests/simulator/advance/test_fields_advance_1d.py (1 hunks)
  • tests/simulator/advance/test_fields_advance_2d.py (1 hunks)
  • tests/simulator/test_advance.py (1 hunks)
✅ Files skipped from review due to trivial changes (2)
  • src/amr/messengers/hybrid_hybrid_messenger_strategy.hpp
  • src/amr/data/field/field_geometry.hpp
🚧 Files skipped from review as they are similar to previous changes (2)
  • tests/simulator/advance/test_fields_advance_2d.py
  • tests/simulator/advance/test_fields_advance_1d.py
🧰 Additional context used
📓 Path-based instructions (1)
**/*.hpp

⚙️ CodeRabbit Configuration File

Review the C++ code, point out issues relative to principles of clean code, expressiveness, and performance.

Files:

  • src/amr/data/field/field_variable_fill_pattern.hpp
🪛 Ruff (0.12.2)
tests/simulator/test_advance.py

290-290: matplotlib.pyplot imported but unused

Remove unused import: matplotlib.pyplot

(F401)


306-306: Ambiguous variable name: l

(E741)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (7)
  • GitHub Check: build (macos-latest)
  • GitHub Check: build (macos-14)
  • GitHub Check: build (macos-13)
  • GitHub Check: build (ubuntu-latest, gcc)
  • GitHub Check: build (ubuntu-latest, clang)
  • GitHub Check: Analyze (cpp)
  • GitHub Check: Analyze (python)

Comment on lines 301 to 311
def makerec(
lower, upper, dl, fc="none", ec="g", lw=1, ls="-"
):
origin = (lower[0] * dl[0], lower[1] * dl[1])
sizex, sizey = [
(u - l) * d for u, l, d in zip(upper, lower, dl)
]
return Rectangle(
origin, sizex, sizey, fc=fc, ec=ec, ls=ls, lw=lw
)
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Fix ambiguous variable name and improve function clarity.

The makerec function uses ambiguous variable names like l which violates naming conventions and reduces readability.

                            def makerec(
-                                lower, upper, dl, fc="none", ec="g", lw=1, ls="-"
+                                lower, upper, spacing, fc="none", ec="g", lw=1, ls="-"
                            ):
-                                origin = (lower[0] * dl[0], lower[1] * dl[1])
+                                origin = (lower[0] * spacing[0], lower[1] * spacing[1])
                                sizex, sizey = [
-                                    (u - l) * d for u, l, d in zip(upper, lower, dl)
+                                    (u - lower_val) * spacing_val 
+                                    for u, lower_val, spacing_val in zip(upper, lower, spacing)
                                ]
                                return Rectangle(
                                    origin, sizex, sizey, fc=fc, ec=ec, ls=ls, lw=lw
                                )
📝 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
def makerec(
lower, upper, dl, fc="none", ec="g", lw=1, ls="-"
):
origin = (lower[0] * dl[0], lower[1] * dl[1])
sizex, sizey = [
(u - l) * d for u, l, d in zip(upper, lower, dl)
]
return Rectangle(
origin, sizex, sizey, fc=fc, ec=ec, ls=ls, lw=lw
)
def makerec(
lower, upper, spacing, fc="none", ec="g", lw=1, ls="-"
):
origin = (lower[0] * spacing[0], lower[1] * spacing[1])
sizex, sizey = [
(u - lower_val) * spacing_val
for u, lower_val, spacing_val in zip(upper, lower, spacing)
]
return Rectangle(
origin, sizex, sizey, fc=fc, ec=ec, ls=ls, lw=lw
)
🧰 Tools
🪛 Ruff (0.12.2)

306-306: Ambiguous variable name: l

(E741)

🤖 Prompt for AI Agents
In tests/simulator/test_advance.py around lines 301 to 310, the function makerec
uses ambiguous variable names such as 'l' in the list comprehension. Rename
these variables to more descriptive names like 'lower_bound' or 'lower_val' to
improve readability and adhere to naming conventions. Update all occurrences
within the function accordingly to maintain clarity.

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

♻️ Duplicate comments (2)
tests/simulator/test_advance.py (2)

402-404: Consider making error handling behavior configurable.

Commenting out the error re-throwing and diff_boxes return significantly changes the test behavior from fail-fast to log-and-continue. While this provides better debugging information, it could mask legitimate test failures.


301-310: Fix ambiguous variable name and improve function clarity.

The makerec function uses ambiguous variable names like l which violates naming conventions and reduces readability.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ce13e57 and 98d8f5a.

📒 Files selected for processing (9)
  • src/amr/data/field/field_data.hpp (1 hunks)
  • src/amr/data/field/field_variable.hpp (1 hunks)
  • src/amr/data/field/field_variable_fill_pattern.hpp (2 hunks)
  • src/amr/data/field/refine/field_refine_operator.hpp (1 hunks)
  • src/amr/messengers/hybrid_hybrid_messenger_strategy.hpp (2 hunks)
  • src/amr/solvers/solver_ppc.hpp (1 hunks)
  • tests/simulator/advance/test_fields_advance_1d.py (2 hunks)
  • tests/simulator/advance/test_fields_advance_2d.py (2 hunks)
  • tests/simulator/test_advance.py (1 hunks)
✅ Files skipped from review due to trivial changes (2)
  • src/amr/solvers/solver_ppc.hpp
  • src/amr/messengers/hybrid_hybrid_messenger_strategy.hpp
🚧 Files skipped from review as they are similar to previous changes (4)
  • tests/simulator/advance/test_fields_advance_1d.py
  • src/amr/data/field/field_variable.hpp
  • tests/simulator/advance/test_fields_advance_2d.py
  • src/amr/data/field/field_variable_fill_pattern.hpp
🧰 Additional context used
📓 Path-based instructions (1)
**/*.hpp

⚙️ CodeRabbit Configuration File

Review the C++ code, point out issues relative to principles of clean code, expressiveness, and performance.

Files:

  • src/amr/data/field/refine/field_refine_operator.hpp
  • src/amr/data/field/field_data.hpp
🪛 Ruff (0.12.2)
tests/simulator/test_advance.py

290-290: matplotlib.pyplot imported but unused

Remove unused import: matplotlib.pyplot

(F401)


306-306: Ambiguous variable name: l

(E741)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (7)
  • GitHub Check: build (macos-latest)
  • GitHub Check: build (macos-14)
  • GitHub Check: build (macos-13)
  • GitHub Check: Analyze (cpp)
  • GitHub Check: build (ubuntu-latest, gcc)
  • GitHub Check: build (ubuntu-latest, clang)
  • GitHub Check: Analyze (python)

Comment on lines +401 to +405
std::cout << "copy_ debug all boxes: "
<< "sourceBox: " << sourceBox
<< ", destinationBox: " << destinationBox
<< ", transformedSource: " << transformedSource
<< ", intersectionBox: " << intersectionBox << std::endl;
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 or properly implement debug output

Debug print statements should not be committed to production code. This file already uses the PHARE logging framework (e.g., PHARE_LOG_SCOPE at line 115).

-                        std::cout << "copy_ debug all boxes: "
-                                  << "sourceBox: " << sourceBox
-                                  << ", destinationBox: " << destinationBox
-                                  << ", transformedSource: " << transformedSource
-                                  << ", intersectionBox: " << intersectionBox << std::endl;
+                        // If debug output is needed, use PHARE logging:
+                        // PHARE_LOG_SCOPE(4, "FieldData::copy_::debug_boxes");
+                        // PHARE_LOG_LINE_STR("sourceBox: " << sourceBox
+                        //                   << ", destinationBox: " << destinationBox
+                        //                   << ", transformedSource: " << transformedSource
+                        //                   << ", intersectionBox: " << intersectionBox);
🤖 Prompt for AI Agents
In src/amr/data/field/field_data.hpp around lines 401 to 405, remove the
std::cout debug print statements or replace them with appropriate PHARE logging
calls consistent with the existing logging framework used in the file. This
ensures debug output is managed uniformly and not left as raw console prints in
production code.

Comment on lines +111 to +114
std::cout << "debug refine operator: "
<< "destinationFieldBox: " << destFieldBox
<< ", sourceFieldBox: " << sourceFieldBox << ", box: " << box
<< ", intersectionBox: " << intersectionBox << std::endl;
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 or properly implement debug output

Debug print statements should not be committed to production code. Consider either:

  1. Removing this debug output entirely, or
  2. Using the PHARE logging framework with appropriate log levels
-            std::cout << "debug refine operator: "
-                      << "destinationFieldBox: " << destFieldBox
-                      << ", sourceFieldBox: " << sourceFieldBox << ", box: " << box
-                      << ", intersectionBox: " << intersectionBox << std::endl;
+            // If debug output is needed, use PHARE logging:
+            // PHARE_LOG_SCOPE(4, "refine_operator_debug");
+            // PHARE_LOG_LINE_STR("destinationFieldBox: " << destFieldBox
+            //                   << ", sourceFieldBox: " << sourceFieldBox 
+            //                   << ", box: " << box
+            //                   << ", intersectionBox: " << intersectionBox);
📝 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
std::cout << "debug refine operator: "
<< "destinationFieldBox: " << destFieldBox
<< ", sourceFieldBox: " << sourceFieldBox << ", box: " << box
<< ", intersectionBox: " << intersectionBox << std::endl;
// If debug output is needed, use PHARE logging:
// PHARE_LOG_SCOPE(4, "refine_operator_debug");
// PHARE_LOG_LINE_STR("destinationFieldBox: " << destFieldBox
// << ", sourceFieldBox: " << sourceFieldBox
// << ", box: " << box
// << ", intersectionBox: " << intersectionBox);
🤖 Prompt for AI Agents
In src/amr/data/field/refine/field_refine_operator.hpp around lines 111 to 114,
the code contains a std::cout debug print statement that should not be in
production code. Remove this debug output entirely or replace it with a call to
the PHARE logging framework using an appropriate log level to ensure proper
logging without cluttering standard output.

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

🧹 Nitpick comments (1)
src/amr/messengers/hybrid_hybrid_messenger_strategy.hpp (1)

407-426: Document the NaN initialization strategy.

The ghost layer NaN initialization appears to be implementing the "copy before refinement" behavior. While the implementation looks correct, it would benefit from a comment explaining why ghost values are set to NaN before refinement.

Add a comment before the loop:

// Initialize ghost layer values to NaN before refinement.
// This ensures we can distinguish between values that were copied
// vs. refined when fine_boundary_represents_var is false.
for (auto& comp : E)
{
    // ... existing code
}
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 98d8f5a and 473178f.

📒 Files selected for processing (9)
  • src/amr/data/field/field_variable.hpp (1 hunks)
  • src/amr/data/field/refine/electric_field_refiner.hpp (8 hunks)
  • src/amr/data/field/refine/field_refiner.hpp (3 hunks)
  • src/amr/level_initializer/hybrid_level_initializer.hpp (1 hunks)
  • src/amr/messengers/hybrid_hybrid_messenger_strategy.hpp (4 hunks)
  • src/amr/messengers/hybrid_messenger.hpp (1 hunks)
  • src/amr/messengers/hybrid_messenger_strategy.hpp (1 hunks)
  • src/amr/messengers/mhd_hybrid_messenger_strategy.hpp (1 hunks)
  • src/amr/solvers/solver_ppc.hpp (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/amr/data/field/field_variable.hpp
  • src/amr/solvers/solver_ppc.hpp
🧰 Additional context used
📓 Path-based instructions (1)
**/*.hpp

⚙️ CodeRabbit Configuration File

Review the C++ code, point out issues relative to principles of clean code, expressiveness, and performance.

Files:

  • src/amr/level_initializer/hybrid_level_initializer.hpp
  • src/amr/messengers/mhd_hybrid_messenger_strategy.hpp
  • src/amr/data/field/refine/field_refiner.hpp
  • src/amr/messengers/hybrid_messenger.hpp
  • src/amr/messengers/hybrid_hybrid_messenger_strategy.hpp
  • src/amr/messengers/hybrid_messenger_strategy.hpp
  • src/amr/data/field/refine/electric_field_refiner.hpp
🧬 Code Graph Analysis (2)
src/amr/level_initializer/hybrid_level_initializer.hpp (3)
src/amr/messengers/hybrid_messenger.hpp (4)
  • E (270-274)
  • E (270-271)
  • E (331-331)
  • E (331-331)
src/amr/messengers/hybrid_messenger_strategy.hpp (1)
  • E (70-71)
src/amr/messengers/hybrid_hybrid_messenger_strategy.hpp (8)
  • E (392-428)
  • E (392-393)
  • level (600-625)
  • level (600-603)
  • level (730-742)
  • level (730-730)
  • level (866-881)
  • level (866-866)
src/amr/data/field/refine/field_refiner.hpp (2)
src/amr/data/field/refine/electric_field_refiner.hpp (6)
  • fineIndex (62-65)
  • fineIndex (62-62)
  • fineIndex (66-69)
  • fineIndex (66-66)
  • fineIndex (70-73)
  • fineIndex (70-70)
src/amr/data/field/coarsening/field_coarsen_index_weight.hpp (2)
  • fineIndex (89-92)
  • fineIndex (93-96)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: build (macos-latest)
  • GitHub Check: build (macos-14)
  • GitHub Check: build (macos-13)
  • GitHub Check: build (ubuntu-latest, clang)
  • GitHub Check: build (ubuntu-latest, gcc)
  • GitHub Check: Analyze (cpp)
🔇 Additional comments (6)
src/amr/level_initializer/hybrid_level_initializer.hpp (1)

167-167: LGTM! Interface update aligns with broader refactoring.

The change from passing levelNumber to level is consistent with the updated fillElectricGhosts method signature that now accepts a SAMRAI::hier::PatchLevel object. This provides the method with richer context about the patch level structure.

src/amr/data/field/refine/field_refiner.hpp (1)

94-95: Excellent defensive programming approach!

The addition of NaN checks before field assignment is crucial for the PR's objective of ensuring copy occurs before refinement. This prevents overwriting valid fine field data that may have been copied earlier in the process.

The implementation is consistent across all dimensional cases (1D, 2D, 3D), which ensures uniform behavior throughout the refinement process.

Also applies to: 123-124, 162-164

src/amr/messengers/mhd_hybrid_messenger_strategy.hpp (1)

87-87: Interface update maintains consistency.

The parameter change from int levelNumber to SAMRAI::hier::PatchLevel const& level aligns with the broader interface refactoring across messenger strategies. The empty method body suggests this strategy either doesn't need electric ghost filling or defers implementation.

src/amr/data/field/refine/electric_field_refiner.hpp (1)

97-98: Comprehensive NaN protection implemented correctly.

The systematic addition of NaN checks before all electric field assignments is excellent defensive programming that aligns perfectly with the PR's objective. This ensures that:

  1. Valid data copied before refinement is never overwritten
  2. The Fujimoto et al. 2011 electric field refinement strategy is preserved
  3. All dimensional cases and field components are consistently protected

The implementation is thorough and covers all assignment paths in the electric field refinement logic.

Also applies to: 123-124, 130-132, 146-147, 153-155, 164-165, 169-172, 175-178, 181-186, 215-216, 223-225, 232-234, 240-245, 257-258, 270-272, 279-281, 288-293, 305-306, 313-315, 322-324, 331-336

src/amr/messengers/hybrid_messenger_strategy.hpp (1)

70-71: Foundational interface improvement.

Updating the pure virtual method signature to accept a SAMRAI::hier::PatchLevel const& level instead of an integer provides implementing classes with richer context for electric ghost filling operations. This change drives the consistent interface updates across all messenger strategy implementations.

The enhanced interface enables more sophisticated patch-level-aware ghost filling logic while maintaining clean abstraction.

src/amr/messengers/hybrid_messenger.hpp (1)

270-274: fillElectricGhosts signature is now consistent across the codebase

Verified all occurrences of fillElectricGhosts via high-level search; every definition and call uses
SAMRAI::hier::PatchLevel const& level instead of an int levelNumber, with no legacy signatures remaining.

All set to merge.

#include "amr/data/particles/particles_variable_fill_pattern.hpp"
#include "amr/data/field/time_interpolate/field_linear_time_interpolate.hpp"

#include "amr/resources_manager/amr_utils.hpp"
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 duplicate include.

The header amr/resources_manager/amr_utils.hpp is already included on line 18. This duplicate include should be removed.

-#include "amr/resources_manager/amr_utils.hpp"
📝 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
#include "amr/resources_manager/amr_utils.hpp"
🤖 Prompt for AI Agents
In src/amr/messengers/hybrid_hybrid_messenger_strategy.hpp at line 33, remove
the duplicate include directive for "amr/resources_manager/amr_utils.hpp" since
it is already included at line 18. This will clean up the code and avoid
redundant includes.

Comment on lines +282 to +284
std::cout << "I am fucking regriding level " << levelNumber << " with oldLevel "
<< (oldLevel ? std::to_string(oldLevel->getLevelNumber()) : "null")
<< " at time " << std::setprecision(16) << initDataTime << "\n";
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 debug output and use proper logging.

This debug output should be removed or replaced with proper logging using the PHARE logging framework. Additionally, the language used is inappropriate for production code.

-            std::cout << "I am fucking regriding level " << levelNumber << " with oldLevel "
-                      << (oldLevel ? std::to_string(oldLevel->getLevelNumber()) : "null")
-                      << " at time " << std::setprecision(16) << initDataTime << "\n";
+            PHARE_LOG_LINE_STR("Regridding level " + std::to_string(levelNumber) 
+                               + " with oldLevel " + (oldLevel ? std::to_string(oldLevel->getLevelNumber()) : "null")
+                               + " at time " + std::to_string(initDataTime));
🤖 Prompt for AI Agents
In src/amr/messengers/hybrid_hybrid_messenger_strategy.hpp around lines 282 to
284, remove the debug output that uses std::cout with inappropriate language.
Replace it with a proper logging call using the PHARE logging framework,
ensuring the message is professional and informative, including the levelNumber,
oldLevel status, and initDataTime with appropriate formatting.

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

♻️ Duplicate comments (2)
tests/simulator/test_advance.py (2)

301-307: Fix ambiguous variable name in list comprehension.

The variable name l in the list comprehension is ambiguous and violates naming conventions as noted in previous reviews.

Apply the suggested fix from the previous review:

                            def makerec(
-                                lower, upper, dl, fc="none", ec="g", lw=1, ls="-"
+                                lower, upper, spacing, fc="none", ec="g", lw=1, ls="-"
                            ):
-                                origin = (lower[0] * dl[0], lower[1] * dl[1])
+                                origin = (lower[0] * spacing[0], lower[1] * spacing[1])
                                sizex, sizey = [
-                                    (u - l) * d for u, l, d in zip(upper, lower, dl)
+                                    (u - lower_val) * spacing_val 
+                                    for u, lower_val, spacing_val in zip(upper, lower, spacing)
                                ]

402-404: Error handling behavior change needs careful consideration.

As noted in the previous review, commenting out the error re-throwing fundamentally changes the test behavior from fail-fast to log-and-continue. While this provides better debugging information for the specific issue mentioned in the PR (copy before refinement causing mismatches), it could mask other legitimate test failures.

The previous suggestion to make this configurable is still valid:

-                        # if self.rethrow_:
-                        #     raise e
-                        # return diff_boxes(slice1, slice2, box)
+                        if getattr(self, 'rethrow_', True):
+                            raise e
+                        return diff_boxes(slice1, slice2, box)

This allows debugging mode when investigating the specific AMR refinement timing issues while preserving test integrity by default.

🧹 Nitpick comments (2)
src/core/data/ndarray/ndarray_vector.hpp (1)

273-273: Minor: Remove extra empty line.

There's an unnecessary extra empty line that should be removed for consistency with the surrounding code formatting.

-
tests/simulator/test_advance.py (1)

290-291: Remove unused matplotlib.pyplot import.

The matplotlib.pyplot import is flagged as unused by static analysis, but examining the code shows it's actually used via plt in the exception handling block.

The static analysis tool missed the plt usage. However, consider moving the import closer to its usage for better code organization:

-                        import matplotlib.pyplot as plt
                        from matplotlib.patches import Rectangle
+                        import matplotlib.pyplot as plt
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 473178f and 67ed7ec.

📒 Files selected for processing (2)
  • src/core/data/ndarray/ndarray_vector.hpp (3 hunks)
  • tests/simulator/test_advance.py (2 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.hpp

⚙️ CodeRabbit Configuration File

Review the C++ code, point out issues relative to principles of clean code, expressiveness, and performance.

Files:

  • src/core/data/ndarray/ndarray_vector.hpp
🧠 Learnings (1)
src/core/data/ndarray/ndarray_vector.hpp (1)

Learnt from: PhilipDeegan
PR: #998
File: src/core/utilities/point/point.hpp:195-210
Timestamp: 2025-04-17T14:41:53.643Z
Learning: In src/core/utilities/point/point.hpp, the as_signed() and as_unsigned() methods are intentionally designed to cause compilation errors for unsupported types (only 4-byte types are supported). This forces developers to implement proper conversions themselves when extending the functionality to new types. The comment "else no return cause not yet handled" indicates this is a deliberate design choice.

🪛 Ruff (0.12.2)
tests/simulator/test_advance.py

290-290: matplotlib.pyplot imported but unused

Remove unused import: matplotlib.pyplot

(F401)


306-306: Ambiguous variable name: l

(E741)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (7)
  • GitHub Check: Analyze (python)
  • GitHub Check: Analyze (cpp)
  • GitHub Check: build (ubuntu-latest, gcc)
  • GitHub Check: build (ubuntu-latest, clang)
  • GitHub Check: build (macos-13)
  • GitHub Check: build (macos-14)
  • GitHub Check: build (macos-latest)
🔇 Additional comments (6)
src/core/data/ndarray/ndarray_vector.hpp (5)

229-230: LGTM: Clean concept definition for floating-point types.

The FloatingPoint concept provides a clear and expressive way to constrain template parameters to floating-point types, improving code readability and maintainability.


242-248: LGTM: Proper NaN initialization for floating-point constructors.

The variadic constructor correctly initializes floating-point data with NaN values, which aligns with the PR's objective of handling NaN values explicitly in field operations. The template parameter U with default DataType and the constraint ensure type safety.


250-256: LGTM: Consistent NaN initialization for array-based constructor.

The array-based constructor properly mirrors the variadic constructor's behavior, initializing floating-point data with NaN. The use of std::accumulate with std::multiplies<int> is consistent with the existing pattern.


257-264: LGTM: Clean constraint application for non-floating-point types.

The requires(!FloatingPoint<DataType>) constraint properly excludes floating-point types from this constructor, ensuring clear separation between initialization strategies. The constructor maintains the original behavior for non-floating-point types.


266-271: LGTM: Consistent constraint application.

The array-based constructor for non-floating-point types correctly applies the same constraint, maintaining consistency with the variadic constructor approach.

tests/simulator/test_advance.py (1)

290-404: Enhanced debugging capabilities look comprehensive.

The extensive visual diagnostic additions provide valuable debugging information for AMR field overlap failures. The implementation correctly:

  • Identifies failing cells with proper tolerance checking
  • Creates visual plots with patch boundaries and ghost boxes
  • Marks failing cells with distinct markers
  • Saves diagnostic plots with descriptive filenames
  • Provides detailed textual output for debugging

This will significantly aid in diagnosing the mismatch issues mentioned in the PR objectives.

extra_diag_options["mode"] = "overwrite"
extra_diag_options["dir"] = diag_outputs
self.register_diag_dir_for_cleanup(diag_outputs)
# self.register_diag_dir_for_cleanup(diag_outputs)
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Cleanup registration is disabled - potential resource leak.

Commenting out the cleanup registration may lead to accumulated test artifacts and disk space issues, especially in CI environments where many tests run sequentially.

Consider making cleanup configurable rather than completely disabling it:

-        # self.register_diag_dir_for_cleanup(diag_outputs)
+        if not getattr(self, 'skip_cleanup', False):
+            self.register_diag_dir_for_cleanup(diag_outputs)

This allows selective cleanup disabling for debugging while preserving the default behavior.

📝 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
# self.register_diag_dir_for_cleanup(diag_outputs)
if not getattr(self, 'skip_cleanup', False):
self.register_diag_dir_for_cleanup(diag_outputs)
🤖 Prompt for AI Agents
In tests/simulator/test_advance.py at line 77, the cleanup registration call is
commented out, which can cause resource leaks by leaving test artifacts on disk.
To fix this, re-enable the cleanup registration but make it conditional based on
a configuration flag or environment variable. This way, cleanup runs by default
but can be disabled selectively for debugging without risking disk space issues
in CI.

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)
src/amr/physical_models/hybrid_model.hpp (1)

139-142: LGTM: Clear NaN handling with good documentation.

The explicit zeroing of state.J with detailed comments effectively prevents NaN propagation, particularly for the 1D case where Jx isn't updated by Ampère's law. The comment clearly explains the rationale and the placement after electromagnetic initialization is appropriate.

Consider whether this dimension-specific initialization could be moved to the state.J construction/initialization itself to avoid the initialize-then-zero pattern, but the current approach is clear and functional.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between be9fd39 and 62544d1.

📒 Files selected for processing (1)
  • src/amr/physical_models/hybrid_model.hpp (2 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.hpp

⚙️ CodeRabbit Configuration File

Review the C++ code, point out issues relative to principles of clean code, expressiveness, and performance.

Files:

  • src/amr/physical_models/hybrid_model.hpp
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: build (macos-latest)
  • GitHub Check: build (macos-14)
  • GitHub Check: build (macos-13)
  • GitHub Check: build (ubuntu-latest, gcc)
  • GitHub Check: build (ubuntu-latest, clang)
  • GitHub Check: Analyze (cpp)
🔇 Additional comments (1)
src/amr/physical_models/hybrid_model.hpp (1)

129-129: LGTM: Consistent resource management extension.

Adding state.J to the setOnPatch call properly extends resource management to include the current density field, which is consistent with its usage elsewhere in the class (e.g., lines 162, 169) and supports the initialization improvements in this PR.

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 (2)
tests/core/numerics/interpolator/test_main.cpp (2)

534-536: Simplify the zero initialization syntax.

The explicit zero initialization is good practice for ensuring deterministic test behavior. However, the syntax can be simplified.

Apply this diff to simplify the syntax:

-        (*(&rho)).zero();
-        (*(&rho_c)).zero();
-        v.zero();
+        rho.zero();
+        rho_c.zero();
+        v.zero();

710-712: Simplify the zero initialization syntax.

Same as the 1D version, the explicit zero initialization is good practice but the syntax can be simplified.

Apply this diff to simplify the syntax:

-        (*(&rho)).zero();
-        (*(&rho_c)).zero();
-        v.zero();
+        rho.zero();
+        rho_c.zero();
+        v.zero();
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 62544d1 and 22e3510.

📒 Files selected for processing (2)
  • tests/amr/data/field/refine/CMakeLists.txt (1 hunks)
  • tests/core/numerics/interpolator/test_main.cpp (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • tests/amr/data/field/refine/CMakeLists.txt
🧰 Additional context used
🧠 Learnings (1)
tests/core/numerics/interpolator/test_main.cpp (2)

Learnt from: rochSmets
PR: #921
File: src/core/data/ions/ions.hpp:138-142
Timestamp: 2025-02-06T10:52:56.461Z
Learning: In PHARE's physics simulations, handling of zero density cells in velocity calculations must be based on physical requirements rather than simple numerical fixes. The solution must account for population-specific behavior in the bulk velocity computation.

Learnt from: PhilipDeegan
PR: #790
File: tests/core/data/electrons/test_electrons.cpp:329-329
Timestamp: 2024-10-09T08:32:15.667Z
Learning: The trailing comma in the TYPED_TEST_SUITE macro call is used intentionally to silence a specific warning in Google Test.

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (7)
  • GitHub Check: Analyze (python)
  • GitHub Check: Analyze (cpp)
  • GitHub Check: build (ubuntu-latest, gcc)
  • GitHub Check: build (ubuntu-latest, clang)
  • GitHub Check: build (macos-14)
  • GitHub Check: build (macos-13)
  • GitHub Check: build (macos-latest)

extra_diag_options["mode"] = "overwrite"
extra_diag_options["dir"] = diag_outputs
self.register_diag_dir_for_cleanup(diag_outputs)
# self.register_diag_dir_for_cleanup(diag_outputs)
Copy link
Member

Choose a reason for hiding this comment

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

I was thinking maybe we could have some switch for this to keep the diags even on test pass

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

♻️ Duplicate comments (4)
src/amr/messengers/hybrid_hybrid_messenger_strategy.hpp (4)

33-33: Remove duplicate include.

The header amr/resources_manager/amr_utils.hpp is already included on line 18. This duplicate include should be removed.

-#include "amr/resources_manager/amr_utils.hpp"

282-284: Remove debug output and use proper logging.

This debug output should be removed or replaced with proper logging using the PHARE logging framework. Additionally, the language used is inappropriate for production code.

-            std::cout << "I am fucking regriding level " << levelNumber << " with oldLevel "
-                      << (oldLevel ? std::to_string(oldLevel->getLevelNumber()) : "null")
-                      << " at time " << std::setprecision(16) << initDataTime << "\n";
+            PHARE_LOG_LINE_STR("Regridding level " + std::to_string(levelNumber) 
+                               + " with oldLevel " + (oldLevel ? std::to_string(oldLevel->getLevelNumber()) : "null")
+                               + " at time " + std::to_string(initDataTime));

408-408: Remove debug output.

Replace std::cout with proper logging framework.

-            std::cout << "FILLING ELECTRIC GHOSTS\n";
+            PHARE_LOG_LINE_STR("Filling electric ghosts");

410-439: Fix critical component access bug and remove unused variables.

Multiple issues need to be addressed:

  1. Critical Bug: All three electric field components are incorrectly accessing Component::X
  2. Unused Variables: Ex, Ey, Ez variables are declared but never used
  3. Code Logic: The NaN initialization logic is sound but the component access must be fixed first
                 auto& Ex    = E(core::Component::X);
-                auto& Ey    = E(core::Component::X);
-                auto& Ez    = E(core::Component::X);
+                auto& Ey    = E(core::Component::Y);
+                auto& Ez    = E(core::Component::Z);

Since these variables are unused, consider removing them entirely:

                 auto box    = patch->getBox();
                 auto _      = resourcesManager_->setOnPatch(*patch, E);
-                auto& Ex    = E(core::Component::X);
-                auto& Ey    = E(core::Component::X);
-                auto& Ez    = E(core::Component::X);
                 auto layout = layoutFromPatch<GridLayoutT>(*patch);
🧹 Nitpick comments (4)
src/core/data/grid/grid.hpp (3)

51-58: Review template parameter design and NaN initialization.

The template parameter U = value_type with FloatingPoint<U> constraint seems redundant since U defaults to value_type. Consider simplifying to requires FloatingPoint<value_type>.

Also, verify that static_cast<U>(std::nan("")) is the intended approach for NaN initialization.

-    template<FloatingPoint U = value_type, std::size_t dim>
+    template<std::size_t dim>
+        requires FloatingPoint<value_type>
     Grid(std::string const& name, PhysicalQuantity qty, std::array<std::uint32_t, dim> const& dims,
-         value_type value = static_cast<U>(std::nan("")))
+         value_type value = std::numeric_limits<value_type>::quiet_NaN())

60-67: Consistent template parameter simplification needed.

Same issue as the previous constructor - the template parameter U is redundant. Also consider using std::numeric_limits for NaN generation for better type safety.

-    template<FloatingPoint U = value_type, typename GridLayout_t>
+    template<typename GridLayout_t>
+        requires FloatingPoint<value_type>
     Grid(std::string const& name, GridLayout_t const& layout, PhysicalQuantity qty,
-         value_type value = static_cast<U>(std::nan("")))
+         value_type value = std::numeric_limits<value_type>::quiet_NaN())

51-85: Potential constructor ambiguity concerns.

The constructor overload resolution relies on SFINAE with requires clauses. While this should work correctly, consider whether the split between floating-point and non-floating-point constructors could create maintenance issues or unexpected behavior for users.

Consider documenting this design decision in class comments to help future maintainers understand why constructors are split based on value type, and ensure that the initialization behavior is well-documented for library users.

src/amr/messengers/hybrid_hybrid_messenger_strategy.hpp (1)

365-365: Use const reference for better performance.

The hybridModel should be declared as a const reference since it's not being modified in this context.

-            auto& hybridModel = static_cast<HybridModel&>(model);
+            auto const& hybridModel = static_cast<HybridModel const&>(model);
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between fe90eda and eaa3a65.

📒 Files selected for processing (6)
  • src/amr/messengers/hybrid_hybrid_messenger_strategy.hpp (5 hunks)
  • src/core/data/grid/grid.hpp (3 hunks)
  • src/core/data/ndarray/ndarray_vector.hpp (3 hunks)
  • tests/core/data/ndarray/test_main.cpp (6 hunks)
  • tests/core/data/tensorfield/test_tensorfield_fixtures.hpp (2 hunks)
  • tests/core/numerics/ion_updater/test_updater.cpp (1 hunks)
✅ Files skipped from review due to trivial changes (2)
  • tests/core/data/ndarray/test_main.cpp
  • tests/core/numerics/ion_updater/test_updater.cpp
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/core/data/ndarray/ndarray_vector.hpp
🧰 Additional context used
📓 Path-based instructions (1)
**/*.hpp

⚙️ CodeRabbit Configuration File

Review the C++ code, point out issues relative to principles of clean code, expressiveness, and performance.

Files:

  • tests/core/data/tensorfield/test_tensorfield_fixtures.hpp
  • src/core/data/grid/grid.hpp
  • src/amr/messengers/hybrid_hybrid_messenger_strategy.hpp
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: build (ubuntu-latest, clang)
  • GitHub Check: build (macos-13)
  • GitHub Check: build (ubuntu-latest, gcc)
  • GitHub Check: Analyze (cpp)
  • GitHub Check: build (macos-latest)
  • GitHub Check: build (macos-14)
🔇 Additional comments (7)
tests/core/data/tensorfield/test_tensorfield_fixtures.hpp (2)

17-20: Clear documentation of initialization behavior change.

The added documentation clearly explains the rationale for using zero initialization instead of NaN in test fixtures for convenience. This helps future maintainers understand the design decision.


57-58: No remaining NaN expectations—explicit zero initialization is correct

I’ve verified that the Grid constructor now accepts an explicit initial value and all tensor-field tests have been updated to pass 0. instead of relying on a NaN default. A case-insensitive search for nan/isnan in tests/core/data/tensorfield/ only turned up an outdated comment; no tests actually check for NaN. You can disregard the previous concern about NaN initialization.

src/amr/messengers/hybrid_hybrid_messenger_strategy.hpp (5)

47-47: LGTM: Appropriate include for NaN operations.

The <cmath> include is correctly added to support the std::numeric_limits and NaN operations used throughout the file.


287-291: LGTM: Proper current density initialization.

The code correctly iterates over patches and zeros the current density field J. This ensures consistent initial conditions during regridding operations.


369-373: LGTM: Consistent current density initialization.

The code properly initializes the current density field J to zero after level initialization, maintaining consistency with the regridding method.


404-405: Method signature change looks correct.

The change from accepting an integer level number to accepting a PatchLevel reference is appropriate and aligns with the implementation that iterates over patches in the level.


439-439: Verify GhostRefinerPool::fill signature consistency

We’ve located several calls to fillElectricGhosts and direct uses of elecGhostsRefiners_.fill(...)—some passing a PatchLevel and others an integer. Please confirm whether GhostRefinerPool::fill now expects a SAMRAI::hier::PatchLevel const& (instead of an integer level number) and update all call sites accordingly:

• src/amr/messengers/hybrid_hybrid_messenger_strategy.hpp
– Line 311: elecGhostsRefiners_.fill(E, levelNumber, initDataTime);
– Line 439: elecGhostsRefiners_.fill(E, level.getLevelNumber(), fillTime);
– Line 723: elecGhostsRefiners_.fill(hybridModel.state.electromag.E, levelNumber, initDataTime);
– Line 780: elecGhostsRefiners_.fill(hybridModel.state.electromag.E, levelNumber, time);

• src/amr/level_initializer/hybrid_level_initializer.hpp
hybMessenger.fillElectricGhosts(E, level, 0.);

• src/amr/solvers/solver_ppc.hpp
fromCoarser.fillElectricGhosts(..., level, newTime);

If the fill signature has been updated to take a PatchLevel const&, replace all levelNumber (or level.getLevelNumber()) arguments with level. Otherwise, leave them as integers.

}

template<std::size_t dim>
requires(!FloatingPoint<value_type>)
Copy link

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Verify FloatingPoint concept availability.

The code uses a FloatingPoint concept that must be defined elsewhere. Ensure this concept is properly included and available in the current scope.

Also applies to: 79-79


🏁 Script executed:

#!/bin/bash
# Description: Verify FloatingPoint concept is defined and accessible

# Search for FloatingPoint concept definition
rg -A 5 "concept.*FloatingPoint" src/ --type cpp

# Search for includes that might provide FloatingPoint concept
rg "#include.*concept\|#include.*type_traits" src/core/data/grid/ --type cpp

# Check if it's defined in core/def.hpp
rg "FloatingPoint" src/core/def.hpp

Length of output: 573


Include the FloatingPoint concept’s header in grid.hpp

The FloatingPoint concept is currently defined in src/core/data/ndarray/ndarray_vector.hpp but isn’t brought into scope in src/core/data/grid/grid.hpp. To prevent “undefined identifier” errors around lines 70 and 79, add the appropriate include:

  • File: src/core/data/grid/grid.hpp
    Insert after the existing #include statements:
    #include "../ndarray/ndarray_vector.hpp"  // for FloatingPoint concept

Apply the same change before both occurrences of requires(!FloatingPoint<value_type>).

🤖 Prompt for AI Agents
In src/core/data/grid/grid.hpp at line 70, the FloatingPoint concept is used but
its header is not included, causing undefined identifier errors. Fix this by
adding #include "../ndarray/ndarray_vector.hpp" after the existing #include
statements near the top of the file to bring the FloatingPoint concept into
scope. Apply this inclusion before both lines where
requires(!FloatingPoint<value_type>) appears.

- PatchData NaN initialized on construction
- fix tests failing as result of above
- comment a field refinement test (useless, wrong refinement op for E,B)
- debug plots for advance field overlap test
- copy done before refinement (boolean false in variable)
- overwrite_interior false also for refinement is default for
  FieldFillPattern
- J manually init to zero in model init, fine init and regrid init (Jx
  unused in ampere but used in Ohm with its now NaN values)
- Grid/NdarrayVector take default value overrides (for test)
- UsableTensorField is default constructed with zero init.
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

♻️ Duplicate comments (3)
tests/simulator/test_advance.py (3)

77-77: Cleanup registration is still disabled - resource leak risk remains.

This issue was previously flagged. Consider implementing the suggested configurable approach to allow selective cleanup disabling for debugging while preserving default cleanup behavior.


290-311: Fix ambiguous variable name in makerec function.

The variable l in the list comprehension violates naming conventions and reduces readability, as flagged by static analysis.

Apply this fix to improve readability:

                            def makerec(
-                                lower, upper, dl, fc="none", ec="g", lw=1, ls="-"
+                                lower, upper, spacing, fc="none", ec="g", lw=1, ls="-"
                            ):
-                                origin = (lower[0] * dl[0], lower[1] * dl[1])
+                                origin = (lower[0] * spacing[0], lower[1] * spacing[1])
                                sizex, sizey = [
-                                    (u - l) * d for u, l, d in zip(upper, lower, dl)
+                                    (u - lower_val) * spacing_val 
+                                    for u, lower_val, spacing_val in zip(upper, lower, spacing)
                                ]

402-404: Exception handling behavior change already flagged.

The commented out error re-throwing and diff_boxes return was previously identified as changing test behavior from fail-fast to log-and-continue. The suggested configurable approach should be implemented.

🧹 Nitpick comments (1)
tests/simulator/test_advance.py (1)

290-385: Consider organizing the extensive debugging code into a helper method.

The debugging visualization code is valuable but makes the main test method quite lengthy. Consider extracting this into a separate helper method for better maintainability.

+    def _generate_overlap_failure_diagnostics(self, pd1, pd2, box, ilvl, slice1, slice2, failed_i, failed_j, loc_b1, loc_b2, datahier):
+        """Generate detailed plots and diagnostics for overlap assertion failures."""
+        import matplotlib.pyplot as plt
+        from matplotlib.patches import Rectangle
+        
+        def makerec(lower, upper, spacing, fc="none", ec="g", lw=1, ls="-"):
+            # ... (move the makerec function here)
+        
+        # ... (move all the plotting code here)
+        
     try:
         assert_fp_any_all_close(slice1, slice2, atol=5.5e-15, rtol=0)
         checks += 1
     except AssertionError as e:
-        # ... (replace with call to helper method)
+        if box.ndim == 2:
+            failed_i, failed_j = np.where(np.abs(slice1 - slice2) > 5.5e-15)
+            self._generate_overlap_failure_diagnostics(pd1, pd2, box, ilvl, slice1, slice2, failed_i, failed_j, loc_b1, loc_b2, datahier)
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 197e14c and 6d50a25.

📒 Files selected for processing (24)
  • src/amr/data/field/field_data.hpp (1 hunks)
  • src/amr/data/field/field_geometry.hpp (1 hunks)
  • src/amr/data/field/field_variable.hpp (1 hunks)
  • src/amr/data/field/field_variable_fill_pattern.hpp (2 hunks)
  • src/amr/data/field/refine/electric_field_refiner.hpp (8 hunks)
  • src/amr/data/field/refine/field_refine_operator.hpp (1 hunks)
  • src/amr/data/field/refine/field_refiner.hpp (3 hunks)
  • src/amr/level_initializer/hybrid_level_initializer.hpp (2 hunks)
  • src/amr/messengers/hybrid_hybrid_messenger_strategy.hpp (7 hunks)
  • src/amr/messengers/hybrid_messenger.hpp (2 hunks)
  • src/amr/messengers/hybrid_messenger_strategy.hpp (1 hunks)
  • src/amr/messengers/mhd_hybrid_messenger_strategy.hpp (1 hunks)
  • src/amr/physical_models/hybrid_model.hpp (2 hunks)
  • src/amr/solvers/solver_ppc.hpp (6 hunks)
  • src/core/data/grid/grid.hpp (3 hunks)
  • src/core/data/ndarray/ndarray_vector.hpp (3 hunks)
  • tests/amr/data/field/refine/CMakeLists.txt (1 hunks)
  • tests/core/data/ndarray/test_main.cpp (6 hunks)
  • tests/core/data/tensorfield/test_tensorfield_fixtures.hpp (2 hunks)
  • tests/core/numerics/interpolator/test_main.cpp (2 hunks)
  • tests/core/numerics/ion_updater/test_updater.cpp (1 hunks)
  • tests/simulator/advance/test_fields_advance_1d.py (2 hunks)
  • tests/simulator/advance/test_fields_advance_2d.py (2 hunks)
  • tests/simulator/test_advance.py (2 hunks)
✅ Files skipped from review due to trivial changes (3)
  • src/amr/data/field/refine/field_refine_operator.hpp
  • src/amr/data/field/field_data.hpp
  • tests/amr/data/field/refine/CMakeLists.txt
🚧 Files skipped from review as they are similar to previous changes (20)
  • src/amr/data/field/field_variable.hpp
  • tests/simulator/advance/test_fields_advance_2d.py
  • tests/simulator/advance/test_fields_advance_1d.py
  • src/amr/data/field/field_variable_fill_pattern.hpp
  • src/amr/data/field/refine/field_refiner.hpp
  • src/amr/data/field/field_geometry.hpp
  • src/amr/messengers/hybrid_messenger_strategy.hpp
  • tests/core/numerics/ion_updater/test_updater.cpp
  • src/amr/solvers/solver_ppc.hpp
  • tests/core/numerics/interpolator/test_main.cpp
  • src/amr/messengers/hybrid_hybrid_messenger_strategy.hpp
  • tests/core/data/tensorfield/test_tensorfield_fixtures.hpp
  • src/core/data/grid/grid.hpp
  • src/amr/level_initializer/hybrid_level_initializer.hpp
  • src/amr/messengers/mhd_hybrid_messenger_strategy.hpp
  • src/amr/data/field/refine/electric_field_refiner.hpp
  • tests/core/data/ndarray/test_main.cpp
  • src/amr/physical_models/hybrid_model.hpp
  • src/amr/messengers/hybrid_messenger.hpp
  • src/core/data/ndarray/ndarray_vector.hpp
🧰 Additional context used
🪛 Ruff (0.12.2)
tests/simulator/test_advance.py

290-290: matplotlib.pyplot imported but unused

Remove unused import: matplotlib.pyplot

(F401)


306-306: Ambiguous variable name: l

(E741)

Comment on lines +291 to +295
for (auto& patch : *level)
{
auto _ = resourcesManager_->setOnPatch(*patch, hybridModel.state.J);
hybridModel.state.J.zero();
}
Copy link
Member

Choose a reason for hiding this comment

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

for(auto& /*patch*/: resourcesManager_->enumerate(*level, hybridModel.state.J)
     hybridModel.state.J.zero();

?

Comment on lines +1093 to +1094
auto qty = field.physicalQuantity();
using qty_t = decltype(qty);
Copy link
Member

Choose a reason for hiding this comment

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

            auto const qty      = field.physicalQuantity();
            using qty_t            = std::decay_t<decltype(qty)>;

?

@nicolasaunai
Copy link
Member Author

replaced by #1068

@github-project-automation github-project-automation bot moved this from Do me  👋 to Done 🥳 in PHARE Roadmap Aug 1, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

amr bug 🔥 Something isn't working SAMRAI all issues dealing with the SAMRAI dependency

Projects

Status: Done 🥳

Development

Successfully merging this pull request may close these issues.

2 participants