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

nd restart tests #809

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open

Conversation

PhilipDeegan
Copy link
Member

@PhilipDeegan PhilipDeegan commented Feb 8, 2024

  • test bind-to-none for mpirun // tests

Summary by CodeRabbit

  • Chores

    • Updated the HighFive library to use a specific branch (v2.9.0) for better compatibility and stability.
    • Renamed a test file to exclude it from automatic test discovery, enhancing test suite execution.
  • New Features

    • Introduced a new variable PHARE_MPIRUN_POSTFIX in the CMake configuration to customize the mpirun command for test executions.
  • Tests

    • Enhanced simulation tests with improved logic for setting up models and simulations, including new parameters and refined function arguments.
    • Added and updated various test cases to better validate simulation restarts, input validation, and model conservation.

Copy link

coderabbitai bot commented Feb 8, 2024

Walkthrough

The changes encompass updates to CMake configurations, library dependencies, and test suite enhancements. Noteworthy modifications include the introduction of a variable for customizing mpirun, switching to the v2.9.0 branch for HighFive, and enhancing simulation tests with argument adjustments and logic refinements. Furthermore, a test file is renamed to enhance test execution precision.

Changes

File(s) Summary
res/cmake/def.cmake Introduces PHARE_MPIRUN_POSTFIX variable to customize mpirun command.
res/cmake/dep/highfive.cmake Updates HighFive Git clone to v2.9.0 branch; removes outdated code.
subprojects/cppdict Changes commit from 6b02756b9... to 9a4dd2050....
tests/simulator/__init__.py Adds deepcopy import; updates keys, calculations, function arguments; refactors functions.
tests/simulator/test_restarts.py
tests/simulator/test_tagging.py.off
Updates imports, parameters, logic in test_restarts.py; renames file for exclusion from test discovery. Refactors setup and introduces new classes.

A rabbit codes with delight,
CMake tweaks in the moonlight.
Tests refined, dependencies aligned,
Through changes, progress defined. 🐇🌙


Recent Review Details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits Files that changed from the base of the PR and between c930968 and 6bc6069.
Files selected for processing (4)
  • res/cmake/def.cmake (3 hunks)
  • tests/simulator/init.py (4 hunks)
  • tests/simulator/test_restarts.py (12 hunks)
  • tests/simulator/test_tagging.py.off (1 hunks)
Files skipped from review due to trivial changes (1)
  • tests/simulator/test_tagging.py.off
Additional Context Used
Ruff (15)
tests/simulator/__init__.py (5)

7-7: Multiple imports on one line


81-81: Do not assign a lambda expression, use a def


182-182: Undefined name Box


188-188: Undefined name Box


195-195: Undefined name Box

tests/simulator/test_restarts.py (10)

6-6: pathlib.Path imported but unused


13-13: Module level import not at top of file


14-14: Module level import not at top of file


15-15: Module level import not at top of file


17-17: Module level import not at top of file


18-18: Module level import not at top of file


56-56: Ambiguous variable name: l


175-175: Import time from line 3 shadowed by loop variable


341-341: Local variable restart_time is assigned to but never used


442-442: Do not use bare except

Learnings (1)
tests/simulator/test_restarts.py (1)
User: PhilipDeegan
PR: PHAREHUB/PHARE#784
File: tests/simulator/test_restarts.py:333-339
Timestamp: 2023-11-25T19:21:40.002Z
Learning: The user has indicated that minimal changes were made to get the function working, but acknowledges that there may still be redundant code present, such as sleep/wait/advances. The user is open to further streamlining the code.
Additional comments not posted (1)
res/cmake/def.cmake (1)

14-16: Introduction of PHARE_MPIRUN_POSTFIX enhances flexibility in configuring mpirun commands.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

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 as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Review Status

Actionable comments generated: 3

Configuration used: .coderabbit.yaml

Commits Files that changed from the base of the PR and between 618c8f6 and 157bab5.
Files selected for processing (4)
  • res/cmake/def.cmake (3 hunks)
  • tests/simulator/init.py (3 hunks)
  • tests/simulator/test_restarts.py (10 hunks)
  • tests/simulator/test_tagging.py.off (1 hunks)
Files skipped from review due to trivial changes (1)
  • tests/simulator/test_tagging.py.off
Additional comments: 14
tests/simulator/__init__.py (5)
  • 3-3: Ensure the deepcopy import is used within the file to justify its addition.
  • 36-36: The use of deepcopy for kwargs in basicSimulatorArgs is good for preventing side effects on the original argument object.
  • 52-52: The calculation for dl as [1.0 / v for v in cells] assumes uniform cell size across dimensions. Ensure this assumption is valid for all use cases.
  • 58-58: Using deepcopy for kwargs before the update operation ensures that the original kwargs object is not modified, which is a good practice for avoiding side effects.
  • 160-160: Instantiating ElectronModel directly without assigning it or using it in a broader context might indicate an incomplete implementation or a misunderstanding of how models are used within simulations. Verify its purpose and integration.
res/cmake/def.cmake (3)
  • 14-16: The introduction of PHARE_MPIRUN_POSTFIX with a default value --bind-to none is a good practice for making test execution behavior configurable. Ensure that this new variable is documented and that its impact on MPI behavior is clearly understood by users.
  • 188-198: The usage of PHARE_MPIRUN_POSTFIX in add_phare_test, add_python3_test, and add_mpi_python3_test functions ensures that the new variable is applied consistently across different types of tests. This is a good practice for maintaining consistency in test execution behavior.
  • 261-261: The use of PHARE_MPIRUN_POSTFIX in phare_mpi_python3_exec function extends the configurability to Python-based MPI tests, aligning with the changes made for C++ tests. This consistency is beneficial for maintaining a uniform testing environment.
tests/simulator/test_restarts.py (6)
  • 20-20: The addition of populate_simulation import is necessary for the refactored simulation setup logic. Ensure that this import is used appropriately within the file.
  • 27-29: The update to permute function to use supported_dimensions from pyphare.pharein.simulation is a good practice for ensuring compatibility with the supported simulation dimensions. This change enhances the flexibility and maintainability of the test setup.
  • 54-91: The refactoring of setup_model function and related model setup functions to accept *xyz arguments improves the flexibility and readability of the simulation setup. This change allows for more dynamic model configurations based on simulation dimensions.
  • 135-148: The introduction of ModelFunctor and DiagsFunctor classes for organizing model setup and diagnostics setup logic is a good practice for improving modularity and readability of the test code. Ensure that these functors are used consistently across test cases.
  • 277-293: > 📝 NOTE

This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [257-288]

The refactoring of the test_restarts method to handle simulation setup differently, including the use of populate_simulation with updated arguments, enhances the test's clarity and maintainability. Verify that the new setup logic correctly reflects the intended test scenarios.

  • 351-369: > 📝 NOTE

This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [315-384]

The updates to test_restarts_elapsed_time, test_mode_conserve, and test_input_validation_trailing_slash methods for simulation setup changes improve the specificity and clarity of each test case. Ensure that these changes accurately reflect the intended testing scenarios and that all necessary configurations are correctly applied.

Comment on lines +60 to +62
if "refinement" not in kwargs and "refinement_boxes" not in kwargs:
b0 = [[3] * dim, [8] * dim]
args["refinement_boxes"] = {"L0": {"B0": b0}}
Copy link

Choose a reason for hiding this comment

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

The condition to set refinement_boxes if not present introduces a hardcoded refinement box. This might not be suitable for all simulations. Consider making refinement boxes configurable or clearly document this behavior.

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.

Review Status

Actionable comments generated: 1

Configuration used: .coderabbit.yaml

Commits Files that changed from the base of the PR and between 618c8f6 and 3b457ee.
Files selected for processing (4)
  • res/cmake/def.cmake (3 hunks)
  • tests/simulator/init.py (3 hunks)
  • tests/simulator/test_restarts.py (8 hunks)
  • tests/simulator/test_tagging.py.off (1 hunks)
Files skipped from review as they are similar to previous changes (3)
  • res/cmake/def.cmake
  • tests/simulator/init.py
  • tests/simulator/test_tagging.py.off
Additional comments: 10
tests/simulator/test_restarts.py (10)
  • 20-20: Import of populate_simulation is added. Ensure this new function is used appropriately and aligns with the PR objectives.
  • 27-29: The permute function now uses supported_dimensions from pyphare.pharein.simulation. Verify that supported_dimensions provides the expected dimensions for all test cases.
  • 39-51: The simArgs dictionary has been updated with new simulation arguments. Ensure that all keys and values are correctly used in the simulation setup and that there are no typos or logical errors in the values assigned.
  • 54-91: Refactoring of setup_model function to accept *xyz arguments and updates to the model setup logic. Confirm that the new arguments and the refactored logic correctly configure the simulation models as intended.
  • 135-148: Reorganization of the ModelFunctor and DiagsFunctor classes. Ensure that these changes improve modularity and maintainability without introducing any logical errors or inconsistencies.
  • 257-257: Conditional logic for setting refinement_boxes. Ensure that the conditions and the logic for setting refinement_boxes are correct and align with the intended simulation setup.
  • 280-280: Setting of restart_options["timestamps"] directly. Confirm that this direct manipulation of the dictionary is intended and that the value set aligns with the simulation requirements.
  • 315-318: The test_restarts_elapsed_time method has been refactored to use the new simulation setup. Verify that the changes correctly implement the intended test logic and that the elapsed time calculations are accurate.
  • 392-394: The test_mode_conserve method adjusted for simulation setup changes. Ensure that the adjustments correctly implement the conservation mode testing and that the logic aligns with the simulation requirements.
  • 419-421: The test_input_validation_trailing_slash method updated for simulation setup changes. Confirm that the addition of extra slashes to the directory path is handled correctly in the simulation setup and does not introduce any issues.

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.

Review Status

Actionable comments generated: 11

Configuration used: .coderabbit.yaml

Commits Files that changed from the base of the PR and between 3b457ee and a5b43b7.
Files selected for processing (1)
  • tests/simulator/test_restarts.py (8 hunks)

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.

Review Status

Actionable comments generated: 0

Configuration used: .coderabbit.yaml

Commits Files that changed from the base of the PR and between 3b457ee and 2c3bc9a.
Files selected for processing (2)
  • res/cmake/dep/highfive.cmake (1 hunks)
  • tests/simulator/test_restarts.py (8 hunks)
Additional comments: 13
res/cmake/dep/highfive.cmake (2)
  • 9-10: Ensure the branch v2.9.0 of HighFive is the intended version for stability and compatibility with the project. Cloning a specific version is a good practice for reproducible builds.
  • 15-16: Removal of commented-out code for updating HighFive is a good cleanup practice, assuming dynamic updates are no longer required or handled differently.
tests/simulator/test_restarts.py (11)
  • 20-20: Importing populate_simulation directly supports test setup modularity and reusability.
  • 28-28: The commented-out import for supported_dimensions is removed, aligning with the summary. Ensure future support for multiple dimensions is tracked if still intended.
  • 39-51: Refining simArgs with specific simulation parameters and options directly in the test file enhances test clarity and control over simulation setup.
  • 54-91: The setup_model function and its nested functions for defining simulation parameters are well-organized, promoting readability and maintainability. Ensure the ppc parameter's usage aligns with test design intentions.
  • 135-141: The ModelFunctor class provides a clear, encapsulated way to configure the model setup for simulations, enhancing test structure.
  • 143-148: The DiagsFunctor class correctly uses its instance variable timestamps, improving clarity and reducing the risk of bugs related to global variable usage.
  • 181-181: Consider removing or replacing print statements with a logging framework for better control over logging levels and outputs.
  • 257-257: The comment block provides valuable context for the setup of refinement_boxes and time_step_nbr, aiding in understanding the test's intent.
  • 280-282: Refactoring the repeated manipulation of simput dictionary for restart and diagnostic options into a helper function could improve code maintainability.
  • 365-365: Using time.sleep(5) in tests could lead to flaky behavior. Consider a more reliable synchronization mechanism if waiting for a condition.
  • 420-420: Appending slashes to directory paths using string concatenation can lead to errors. Using os.path.join or pathlib for path manipulations ensures cross-platform compatibility.

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.

Review Status

Actionable comments generated: 0

Configuration used: .coderabbit.yaml

Commits Files that changed from the base of the PR and between 618c8f6 and 04d6f73.
Files selected for processing (5)
  • res/cmake/def.cmake (3 hunks)
  • res/cmake/dep/highfive.cmake (1 hunks)
  • tests/simulator/init.py (3 hunks)
  • tests/simulator/test_restarts.py (10 hunks)
  • tests/simulator/test_tagging.py.off (1 hunks)
Files skipped from review as they are similar to previous changes (4)
  • res/cmake/def.cmake
  • res/cmake/dep/highfive.cmake
  • tests/simulator/init.py
  • tests/simulator/test_tagging.py.off
Additional comments: 11
tests/simulator/test_restarts.py (11)
  • 17-17: Consider using relative imports for internal modules to enhance modularity and maintainability.
  • 22-24: The import of supported_dimensions is now used within the permute function. Ensure this change aligns with the intended use cases and that supported_dimensions provides the expected values for dimensions.
  • 34-46: The simArgs dictionary is defined at the module level, which could lead to unintended side effects if modified by any test. Consider moving it inside a function or using a function to generate a fresh copy for each test to ensure isolation.
  • 49-87: The model setup functions (density, bx, by, bz, T, vx, vy, vz, vxalpha, vthxyz) are defined within setup_model but do not utilize the ppc parameter directly. Ensure that the design intention is clear, and consider refactoring if these functions are meant to be more closely integrated with the model setup logic.
  • 130-136: The ModelFunctor class is effectively a wrapper around the setup_model function. Ensure that this level of indirection is necessary for the test design, as it could potentially be simplified.
  • 138-143: The DiagsFunctor class is initialized with timestamps but uses a global timestamps variable in its __call__ method. This could lead to confusion or bugs if the global variable changes. Ensure that the instance variable is used as intended.
  • 176-176: Usage of print for debugging purposes. Consider removing or replacing with a logging framework if this is not intended for the final code.
  • 252-252: The comment block explains the rationale behind setting refinement_boxes and time_step_nbr. Ensure that such explanations are maintained up-to-date with the code logic to avoid confusion.
  • 275-277: The manipulation of simput["restart_options"]["timestamps"] and simput["diag_options"]["options"]["dir"] is repeated in multiple test cases. Consider refactoring this logic into a helper function to reduce duplication and improve maintainability.
  • 360-360: The call to time.sleep(5) in a test case could lead to flaky tests, especially in different execution environments. If this is intended to wait for some condition, consider using a more reliable synchronization mechanism.
  • 415-415: Appending slashes to a directory path using string concatenation can lead to errors or unexpected behavior. Use os.path.join or pathlib for path manipulations to ensure cross-platform compatibility.

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.

Review Status

Actionable comments generated: 0

Configuration used: .coderabbit.yaml

Commits Files that changed from the base of the PR and between 618c8f6 and 0935b00.
Files selected for processing (5)
  • res/cmake/def.cmake (3 hunks)
  • res/cmake/dep/highfive.cmake (1 hunks)
  • tests/simulator/init.py (3 hunks)
  • tests/simulator/test_restarts.py (10 hunks)
  • tests/simulator/test_tagging.py.off (1 hunks)
Files skipped from review as they are similar to previous changes (4)
  • res/cmake/def.cmake
  • res/cmake/dep/highfive.cmake
  • tests/simulator/init.py
  • tests/simulator/test_tagging.py.off
Additional comments: 11
tests/simulator/test_restarts.py (11)
  • 17-17: Consider using relative imports for internal modules to enhance modularity and maintainability.
  • 22-24: The import of supported_dimensions is now uncommented, ensuring its functionality is utilized in the permute function. This change aligns with the objective of refining test configurations.
  • 34-46: The simArgs dictionary is defined at the module level, which could lead to unintended side effects if modified by any test. Consider moving it inside a function or using a function to generate a fresh copy for each test to ensure isolation.
  • 49-87: The model setup functions (density, bx, by, bz, T, vx, vy, vz, vxalpha, vthxyz) are defined within setup_model but do not utilize the ppc parameter. Ensure that the design intention is clear, and consider refactoring if these functions are meant to be more closely integrated with the model setup logic.
  • 130-136: The ModelFunctor class is effectively a wrapper around the setup_model function. Ensure that this level of indirection is necessary for the test design, as it could potentially be simplified.
  • 138-143: The DiagsFunctor class is initialized with timestamps but uses a global timestamps variable in its __call__ method. This could lead to confusion or bugs if the global variable changes. Ensure that the instance variable is used as intended.
  • 176-176: Usage of print for debugging purposes. Consider removing or replacing with a logging framework if this is not intended for the final code.
  • 252-252: The comment block explains the rationale behind setting refinement_boxes and time_step_nbr. Ensure that such explanations are maintained up-to-date with the code logic to avoid confusion.
  • 275-277: The manipulation of simput["restart_options"]["timestamps"] and simput["diag_options"]["options"]["dir"] is repeated in multiple test cases. Consider refactoring this logic into a helper function to reduce duplication and improve maintainability.
  • 358-358: The call to time.sleep(5) in a test case could lead to flaky tests, especially in different execution environments. If this is intended to wait for some condition, consider using a more reliable synchronization mechanism.
  • 413-413: Appending slashes to a directory path using string concatenation can lead to errors or unexpected behavior. Use os.path.join or pathlib for path manipulations to ensure cross-platform compatibility.

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.

Review Status

Actionable comments generated: 0

Configuration used: .coderabbit.yaml

Commits Files that changed from the base of the PR and between 6ff0df7 and c385c4b.
Files selected for processing (5)
  • res/cmake/def.cmake (3 hunks)
  • res/cmake/dep/highfive.cmake (1 hunks)
  • tests/simulator/init.py (4 hunks)
  • tests/simulator/test_restarts.py (12 hunks)
  • tests/simulator/test_tagging.py.off (1 hunks)
Files skipped from review as they are similar to previous changes (3)
  • res/cmake/def.cmake
  • res/cmake/dep/highfive.cmake
  • tests/simulator/test_tagging.py.off
Additional comments: 18
tests/simulator/__init__.py (7)
  • 3-3: Import of deepcopy added.
  • 49-49: Changed final_time to time_step with a hardcoded value of 0.001.
  • 52-52: Updated dl key calculation to be the inverse of cell counts.
  • 58-59: Logic to update args dictionary with kwargs using deepcopy.
  • 60-62: Condition added to set refinement_boxes if not present.
  • 147-160: Refactored populate_simulation function with changes in arguments and logic.
  • 160-160: Replaced ElectronModel instantiation with ph.ElectronModel.
tests/simulator/test_restarts.py (11)
  • 17-17: Added populate_simulation import.
  • 22-23: Updated permute function to use supported_dimensions.
  • 34-46: Modified simArgs dictionary with new simulation setup parameters.
  • 49-86: Refactored model setup functions to accept *xyz arguments.
  • 130-136: Reorganized the ModelFunctor class.
  • 138-143: Reorganized the DiagsFunctor class.
  • 175-176: Usage of print for debugging purposes.
  • 262-262: Comment block explaining the rationale behind setting refinement_boxes and time_step_nbr.
  • 285-287: Manipulation of simput["restart_options"]["timestamps"] and simput["diag_options"]["options"]["dir"] is repeated in multiple test cases.
  • 368-368: Call to time.sleep(5) in a test case.
  • 423-423: Appending slashes to a directory path using string concatenation.

np.testing.assert_allclose(
pd0.dataset[:],
pd1.dataset[:],
atol=1e-14, # 1e-15 fails empirically
Copy link
Member Author

Choose a reason for hiding this comment

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

is flakey, could be 1e-12/13?

Copy link
Member Author

Choose a reason for hiding this comment

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

@PhilipDeegan PhilipDeegan mentioned this pull request Feb 12, 2024
@PHAREHUB PHAREHUB deleted a comment from coderabbitai bot Feb 15, 2024
@PHAREHUB PHAREHUB deleted a comment from coderabbitai bot Apr 4, 2024
@PHAREHUB PHAREHUB deleted a comment from coderabbitai bot Apr 4, 2024
@PHAREHUB PHAREHUB deleted a comment from coderabbitai bot Apr 4, 2024
@PHAREHUB PHAREHUB deleted a comment from coderabbitai bot Apr 4, 2024
@PHAREHUB PHAREHUB deleted a comment from coderabbitai bot Apr 4, 2024
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: 5

Review Status

Configuration used: .coderabbit.yaml

Commits Files that changed from the base of the PR and between 6ff0df7 and e39a7dc.
Files selected for processing (5)
  • res/cmake/def.cmake (3 hunks)
  • subprojects/cppdict (1 hunks)
  • tests/simulator/init.py (4 hunks)
  • tests/simulator/test_restarts.py (12 hunks)
  • tests/simulator/test_tagging.py.off (1 hunks)
Files skipped from review due to trivial changes (2)
  • subprojects/cppdict
  • tests/simulator/test_tagging.py.off
Additional Context Used
Learnings (1)
tests/simulator/test_restarts.py (2)
User: PhilipDeegan"
PR: PHAREHUB/PHARE#784
File: tests/simulator/test_restarts.py:333-339
Timestamp: 2023-11-25T19:21:40.002Z
Learning: The user has indicated that minimal changes were made to get the function working, but acknowledges that there may still be redundant code present, such as sleep/wait/advances. The user is open to further streamlining the code.
User: PhilipDeegan"
PR: PHAREHUB/PHARE#784
File: tests/simulator/test_restarts.py:333-339
Timestamp: 2023-11-25T19:21:58.449Z
Learning: PhilipDeegan has indicated a preference for minimal and efficient code, even after making changes to get a function working. There may be opportunities to remove or optimize parts of the code such as sleep/wait/advances.
Additional comments not posted (10)
tests/simulator/__init__.py (5)

3-3: Add a comment explaining why deepcopy is imported and used.


36-36: Ensure that deepcopy is necessary for copying kwargs to avoid unintended side effects.


49-49: Consider making "time_step" configurable to accommodate different simulation needs.


60-62: Ensure that the hardcoded refinement box is suitable for all simulations or make it configurable.


147-160: Verify that all calls to populate_simulation across the codebase have been updated to match the new signature.

Verification successful

The calls to populate_simulation in test_restarts.py have been updated to match the new signature, as they include the required arguments (ndim, interp, model_fn, diags_fn) and additional keyword arguments unpacked from **simput. This aligns with the updated function signature provided in the review comment.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Search for calls to populate_simulation with incorrect signature.
ast-grep --lang python --pattern $'populate_simulation($_, $_, $_, $_, $$$)'

Length of output: 1925

res/cmake/def.cmake (2)

14-16: Document the purpose of PHARE_MPIRUN_POSTFIX and its default value in the CMake configuration.


188-188: Ensure that the mpirun command with PHARE_MPIRUN_POSTFIX is tested across different environments for compatibility.

tests/simulator/test_restarts.py (3)

49-86: Clarify the design intention of model setup functions not utilizing the ppc parameter and consider refactoring if necessary.


130-136: Evaluate the necessity of the ModelFunctor class as a wrapper around setup_model for potential simplification.


229-229: Consider adjusting the atol value based on empirical results to avoid flaky tests.

Comment on lines +34 to +46
simArgs = dict(
# we are saving at timestep 4, and we have seen that restarted simulations with refinement boxes
# have regridding in places that don't exist in the original simulation
# we compare the immediate next timestep of both simulations with refinement boxes, as we have seen
# in this way neither simulations have any regrids, so are still comparable
time_step_nbr=5, # avoid regrid for refinement boxes https://github.com/LLNL/SAMRAI/issues/199
time_step=timestep,
boundary_types="periodic",
cells=22,
dl=0.3,
diag_options=dict(format="phareh5", options=dict(dir=out, mode="overwrite")),
restart_options=dict(dir=out, mode="overwrite"),
)
Copy link

Choose a reason for hiding this comment

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

Move simArgs inside a function or use a factory function to generate a fresh copy for each test to ensure isolation.

@@ -161,6 +173,7 @@

self.assertGreater(len(timestamps), 0)
for time in timestamps:
print(f"checking time {time}")
Copy link

Choose a reason for hiding this comment

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

Replace debugging print statements with a logging framework if not intended for final code.

- print(f"checking time {time}")
+ # Consider using a logging framework for debug messages

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.

Suggested change
print(f"checking time {time}")
# Consider using a logging framework for debug messages

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

@@ -1,7 +1,10 @@
import unittest

from copy import deepcopy
Copy link

Choose a reason for hiding this comment

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

Consider separating imports on individual lines for clarity.

- from datetime import datetime
+ import datetime

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.

Suggested change
from copy import deepcopy
from copy import deepcopy
import datetime

Comment on lines +285 to +287
simput["restart_options"]["timestamps"] = [timestep * restart_idx]
simput["diag_options"]["options"]["dir"] = local_out
ph.global_vars.sim = None
ph.global_vars.sim = ph.Simulation(**simput)
assert "restart_time" not in ph.global_vars.sim.restart_options
model = setup_model()
dump_all_diags(model.populations, timestamps=np.array(timestamps))
Simulator(ph.global_vars.sim).run().reset()
sim = populate_simulation(
Copy link

Choose a reason for hiding this comment

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

Refactor repeated logic manipulating simput["restart_options"]["timestamps"] and simput["diag_options"]["options"]["dir"] into a helper function to improve code maintainability.

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


from copy import deepcopy


Copy link

Choose a reason for hiding this comment

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

Multiple imports on one line.

- from datetime import datetime
+ import datetime

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.

Suggested change

args = {
"interp_order": interp,
"smallest_patch_size": smallest_patch_size,
"largest_patch_size": [20] * dim,
"time_step_nbr": 1000,
"final_time": 1.0,
"time_step": 0.001,
Copy link

Choose a reason for hiding this comment

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

Consider making time_step configurable to accommodate different simulation needs.

Comment on lines +147 to +160
def populate_simulation(ndim=1, interp=1, model_fn=None, diags_fn=None, **simInput):
ph.global_vars.sim = None
simulation = ph.Simulation(**basicSimulatorArgs(dim, interp, **input))
simulation = ph.Simulation(**basicSimulatorArgs(ndim, interp, **simInput))
extra_pops = {}
if "populations" in input:
for pop, vals in input["populations"].items():
if "populations" in simInput:
for pop, vals in simInput["populations"].items():
extra_pops[pop] = defaultPopulationSettings()
extra_pops[pop].update(vals)

model = makeBasicModel(extra_pops)
if "diags_fn" in input:
input["diags_fn"](model)
model = model_fn() if model_fn else makeBasicModel(extra_pops)
if diags_fn:
diags_fn(model)

ElectronModel(closure="isothermal", Te=0.12)
ph.ElectronModel(closure="isothermal", Te=0.12)
Copy link

Choose a reason for hiding this comment

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

Tip

Codebase Verification

The verification process has identified that the function populate_simulation is still being called with the old signature in two files, which contradicts the expected update across the codebase. Additionally, the new function signature is correctly used in several instances within test_restarts.py. Here are the specific locations that need attention:

  • ./tests/simulator/test_restarts.py:424: Old signature used.
  • ./tests/simulator/data_wrangler.py:25: Old signature used.

It is recommended to update these calls to match the new function signature to ensure consistency and functionality throughout the codebase.

Analysis chain

Ensure all calls to populate_simulation match the new signature and logic.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify all function calls to `populate_simulation` match the new signature.

# Test: Search for the old function signature to find omissions. Expect: No matches.
ast-grep --lang python --pattern $'populate_simulation($_, $_)'
# Test: Search for the new function signature to validate usage. Expect: Matches.
ast-grep --lang python --pattern $'populate_simulation($_, $_, $_, $_, $$$)'

Length of output: 2207

Comment on lines +269 to +275
def hierarchy_by_box(self, hier):
# comparing hierarchies by index isn't always right
box_hier = {i: {} for i in range(len(hier.levels()))}
for ilvl, patches in box_hier.items():
for patch in hier.level(ilvl).patches:
patches[str(patch.box)] = patch
return box_hier
Copy link

@coderabbitai coderabbitai bot May 3, 2024

Choose a reason for hiding this comment

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

Add unit tests for the hierarchy_by_box method to ensure its correctness.

Would you like me to generate unit tests for the hierarchy_by_box method?

Copy link
Member Author

Choose a reason for hiding this comment

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

this is used as part of a test. so it is tested.

Copy link

Choose a reason for hiding this comment

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

@PhilipDeegan, I've verified that the hierarchy_by_box method is indeed invoked in the tests/simulator/test_restarts.py file. Thus, it is being tested as part of the existing tests.

Thank you for the clarification!

Analysis chain
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for invocations of the `hierarchy_by_box` method within the test files.
rg 'hierarchy_by_box' tests/

Length of output: 183

from datetime import timedelta

from pathlib import Path
Copy link

Choose a reason for hiding this comment

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

Remove unused import Path from pathlib.

- from pathlib import Path

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.

Suggested change
from pathlib import Path

Comment on lines +49 to +86
def setup_model(ppc):
def density(*xyz):
return 1.0

def bx(x):
def bx(*xyz):
return 0.0

def S(x, x0, l):
return 0.5 * (1 + np.tanh((x - x0) / l))

def by(x):
def by(*xyz):
L = ph.global_vars.sim.simulation_domain()[0]
v1, v2 = -1, 1.0
return v1 + (v2 - v1) * (S(x, L * 0.25, 1) - S(x, L * 0.75, 1))
return v1 + (v2 - v1) * (S(xyz[0], L * 0.25, 1) - S(xyz[0], L * 0.75, 1))

def bz(x):
def bz(*xyz):
return 0.5

def b2(x):
return bx(x) ** 2 + by(x) ** 2 + bz(x) ** 2
def b2(*xyz):
return bx(xyz[0]) ** 2 + by(xyz[0]) ** 2 + bz(xyz[0]) ** 2

def T(x):
def T(*xyz):
K = 1
return 1 / density(x) * (K - b2(x) * 0.5)
return 1 / density(xyz[0]) * (K - b2(xyz[0]) * 0.5)

def vx(x):
def vx(*xyz):
return 2.0

def vy(x):
def vy(*xyz):
return 0.0

def vz(x):
def vz(*xyz):
return 0.0

def vxalpha(x):
def vxalpha(*xyz):
return 3.0

def vthxyz(x):
return T(x)
def vthxyz(*xyz):
Copy link

Choose a reason for hiding this comment

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

Ensure that the ppc parameter is utilized appropriately within the setup_model function.

Comment on lines +130 to +136
class ModelFunctor:
def __init__(self, ppc=None):
self.nppc = ppc or nppc

def __call__(self):
return setup_model(self.nppc)

Copy link

Choose a reason for hiding this comment

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

Evaluate the necessity of the ModelFunctor class as it primarily wraps the setup_model function.

Comment on lines +229 to +231
atol=1e-14, # 1e-15 fails empirically
rtol=0,
)
Copy link

Choose a reason for hiding this comment

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

Consider making atol configurable to handle potential flakiness in tests.


# autodump false to ignore possible init dump
simulator = Simulator(ph.global_vars.sim, auto_dump=False).initialize()
simulator = Simulator(sim, auto_dump=False).initialize()
Copy link

Choose a reason for hiding this comment

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

Replace time.sleep(5) with a more reliable synchronization mechanism to avoid flaky tests.

Comment on lines +408 to +416
sim = populate_simulation(ndim, interp, model_fn=ModelFunctor(), **simput)
self.assertEqual(len(sim.restart_options["timestamps"]), 1)
self.assertEqual(sim.restart_options["timestamps"][0], 0.004)
Simulator(ph.global_vars.sim).run().reset()

# second simulation (not restarted)
ph.global_vars.sim = None
simput["restart_options"]["mode"] = "conserve"
ph.global_vars.sim = ph.Simulation(**simput)
self.assertEqual(len(ph.global_vars.sim.restart_options["timestamps"]), 0)
sim = populate_simulation(ndim, interp, model_fn=ModelFunctor(), **simput)
self.assertEqual(len(sim.restart_options["timestamps"]), 0)
Copy link

Choose a reason for hiding this comment

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

Clarify the handling of timestamps in the conservation mode to ensure clear and optimal functionality.

@@ -11,6 +11,10 @@ endif() # clang
set (PHARE_LINK_FLAGS )
set (PHARE_BASE_LIBS )

if(NOT DEFINED PHARE_MPIRUN_POSTFIX)
Copy link
Member Author

Choose a reason for hiding this comment

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

without this, running multiple instances of mpirun -n 2 python3 ... effectively only lets run one process, the rest are descheduled until the first is finished

we could not default it here but set it manually in TC builds, or have it as an option defaulted to ON

Copy link
Member Author

Choose a reason for hiding this comment

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

this was moved to the configurator, so to rm

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant