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

Rm #945

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

Rm #945

wants to merge 3 commits into from

Conversation

nicolasaunai
Copy link
Member

@nicolasaunai nicolasaunai commented Jan 30, 2025

Summary by CodeRabbit

Release Notes

  • Type Definitions

    • Introduced new type aliases for resources across multiple components, including ParticlePack_t and view_type in various classes.
    • Enhanced resource management with more explicit type references, such as ResourcesManagerHybrid and ResourcesManagerMHD.
  • Code Structure

    • Renamed several classes and structures from "ResourceUser" to "View", including the transition of ResourcesGuard to ViewGuard.
    • Updated resource management interfaces to improve clarity and type safety.
  • Resource Management

    • Added support for particle pack integration in resources manager.
    • Refined resource allocation and registration mechanisms, including the introduction of HierarchyViews for managing views.
  • Testing

    • Updated test suites to reflect new naming conventions and improved type specificity in resource management.

These changes primarily focus on improving code organization and type management within the resource handling system.

Copy link

coderabbitai bot commented Jan 30, 2025

📝 Walkthrough

Walkthrough

The pull request introduces a comprehensive refactoring of the resource management system across multiple files in the AMR (Adaptive Mesh Refinement) codebase. The primary changes involve renaming and restructuring resource-related classes and types, with a shift from "ResourceUser" to "View" terminology. The modifications enhance type specificity, particularly for particle and field resources, and update the ResourcesManager to support more flexible resource handling with new meta structures and view types.

Changes

File Change Summary
src/amr/data/field/field_data.hpp Added type alias using view_type = Grid_t::field_type in FieldData class.
src/amr/data/particles/particles_data.hpp Added type alias using view_type = typename core::ParticlesPack<ParticleArray> in ParticlesData class.
src/amr/physical_models/hybrid_model.hpp Updated resources_manager_type to include particle_array_type; added type alias using particle_pack_t = core::ParticlesPack<particle_array_type>.
src/amr/resources_manager/field_resource.hpp Renamed struct UserFieldType to FieldViewInfo; added type alias using view_type = patch_data_type::view_type.
src/amr/resources_manager/particle_resource.hpp Renamed template structure from UserParticleType to ParticleViewInfo; updated dimension references. Added type alias using view_type = patch_data_type::view_type.
src/amr/resources_manager/resources_guards.hpp Renamed class ResourcesGuard to ViewGuard; updated template parameters from ResourcesUsers to Views.
src/amr/resources_manager/resources_manager.hpp Updated class definition to inherit from new structures; added ViewMetaWithParticles and ViewMetaMeshOnly; modified multiple method signatures to replace ResourcesView with View.
src/amr/resources_manager/resources_manager_utilities.hpp Renamed references from ResourceView to View across various structures and functions.
tests/amr/messengers/test_messengers.cpp Updated resource manager types to ResourcesManagerHybrid and ResourcesManagerMHD.
tests/amr/models/test_models.cpp Updated ResourcesManagerT to include ParticleArray1D.
tests/amr/resources_manager/test_resources_manager.cpp Added type alias using ParticlePack_t = ParticlesPack<ParticleArray<dim>>; updated structure members from user to view; changed test suite name from aResourceUserCollection to ViewCollection.
tests/amr/resources_manager/test_resources_manager.hpp Renamed class from aResourceUserCollection to ViewCollection; updated member variable and template parameter types.

Sequence Diagram

sequenceDiagram
    participant ResourcesManager
    participant View
    participant Patch
    
    ResourcesManager->>View: registerResources()
    ResourcesManager->>Patch: allocate()
    ResourcesManager->>View: setTime()
    ResourcesManager->>View: getIDs()
Loading

The sequence diagram illustrates the high-level interaction between the ResourcesManager, View, and Patch, showing the key methods involved in resource management after the refactoring.

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

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

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🔭 Outside diff range comments (3)
src/amr/resources_manager/resources_manager.hpp (1)

Line range hint 280-399: Check for null pointer after dynamic_pointer_cast.
In getPatchData_ (line 393 onward), the cast to typename ViewInfo::patch_data_type is unverified. If the variable is incorrectly registered, the cast could fail and result in a nullptr dereference at ->getPointer(). Consider handling a null result before calling getPointer().

 std::shared_ptr<typename ViewInfo::patch_data_type> data =
     std::dynamic_pointer_cast<typename ViewInfo::patch_data_type>(patchData);

-if (!data) // might be null if cast fails
-    return data->getPointer();
+if (!data) {
+    // handle error or throw
+}
+return data->getPointer();
tests/amr/resources_manager/test_resources_manager.cpp (2)

Line range hint 12-24: Revise pricing logic to ensure discounts remain beneficial.

The current implementation has a potential issue where adding a flat $20 fee after applying the discount can result in a higher final price than without a discount, especially for smaller purchases. For example:

  • $100 purchase with 10% discount = $90 + $20 fee = $110 (more than original price)

This could lead to customer dissatisfaction and defeat the purpose of the loyalty program.

Would you like me to propose an alternative implementation that ensures discounts always benefit the customer?


Line range hint 4-9: Fix incorrect test assertion.

The test assertion is incorrect. For a $100 purchase with 15% senior loyalty discount:

  • Discounted amount: $100 * (1 - 0.15) = $85
  • Final amount with fee: $85 + $20 = $105

Apply this fix:

-    self.assertEqual(result, 80, "Senior loyalty discount not applied correctly")
+    self.assertEqual(result, 105, "Senior loyalty discount not applied correctly")
🧹 Nitpick comments (7)
src/amr/resources_manager/resources_manager.hpp (2)

141-226: Consider updating documentation to reflect the new naming convention.
Several comments (e.g., lines 141–147) still refer to “ResourcesViews”. Since the code now uniformly uses “View,” it would be clearer if doc comments matched this terminology.


Line range hint 234-279: Observe potential scaling concerns with time retrieval.
The getTimes and setTime methods iterate over all patch data IDs. For very large systems, performance could degrade. Caching or chunking strategies may be helpful if iteration must scale.

src/amr/resources_manager/resources_guards.hpp (1)

52-61: Favor explicit default moves only if needed.
While defaulting move operations is often fine, confirm that no special resource cleanup logic is required during move operations.

tests/amr/resources_manager/test_resources_manager.hpp (1)

32-33: Consider adding documentation for type aliases.

The type aliases are well-structured, but adding documentation would improve code maintainability.

+    /// Grid type using NdArrayVector for 1D scalar quantities
     using Grid_t         = Grid<NdArrayVector<1>, HybridQuantity::Scalar>;
+    /// Type for managing particle data in 1D
     using ParticlePack_t = ParticlesPack<ParticleArray<1>>;

Also applies to: 35-36

src/amr/resources_manager/resources_manager_utilities.hpp (2)

57-63: Consider adding static_assert for type validation.

The view traits could benefit from compile-time validation.

 template<typename View>
 struct is_final_view
 {
+    static_assert(std::is_class_v<View>, "View must be a class type");
     bool constexpr static value = is_field_v<View> or is_particles_v<View>;
 };

Also applies to: 132-138


95-110: Consider adding noexcept specifier.

The trait structures could benefit from explicit noexcept specifications.

 template<typename View>
-struct has_runtime_views<
+struct has_runtime_views<View, core::tryToInstanciate<decltype(std::declval<View>().getRunTimeViewList())>>
-    View, core::tryToInstanciate<decltype(std::declval<View>().getRunTimeResourcesViewList())>>
-    : std::true_type
+    : std::true_type
 {
+    static constexpr bool value() noexcept { return true; }
 };

Also applies to: 113-129

src/amr/physical_models/hybrid_model.hpp (1)

31-45: Consider grouping related type aliases.

The type aliases could be organized better by grouping related types together.

-    using Interface           = IPhysicalModel<AMR_Types>;
-    using amr_types           = AMR_Types;
-    using electrons_t         = Electrons;
-    using patch_t             = typename AMR_Types::patch_t;
-    using level_t             = typename AMR_Types::level_t;
-    using gridlayout_type     = GridLayoutT;
-    using electromag_type     = Electromag;
-    using vecfield_type       = typename Electromag::vecfield_type;
-    using field_type          = typename vecfield_type::field_type;
-    using grid_type           = Grid_t;
-    using ions_type           = Ions;
-    using particle_array_type = typename Ions::particle_array_type;
-    using particle_pack_t     = core::ParticlesPack<particle_array_type>;
-    using resources_manager_type
-        = amr::ResourcesManager<gridlayout_type, grid_type, particle_pack_t>;
+    // Base types
+    using Interface       = IPhysicalModel<AMR_Types>;
+    using amr_types      = AMR_Types;
+    using patch_t        = typename AMR_Types::patch_t;
+    using level_t        = typename AMR_Types::level_t;
+
+    // Grid and layout types
+    using grid_type      = Grid_t;
+    using gridlayout_type = GridLayoutT;
+
+    // Field types
+    using electromag_type = Electromag;
+    using vecfield_type   = typename Electromag::vecfield_type;
+    using field_type      = typename vecfield_type::field_type;
+
+    // Particle types
+    using electrons_t         = Electrons;
+    using ions_type          = Ions;
+    using particle_array_type = typename Ions::particle_array_type;
+    using particle_pack_t     = core::ParticlesPack<particle_array_type>;
+
+    // Resource management
+    using resources_manager_type
+        = amr::ResourcesManager<gridlayout_type, grid_type, particle_pack_t>;
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ce77d6b and d0c6840.

📒 Files selected for processing (12)
  • src/amr/data/field/field_data.hpp (1 hunks)
  • src/amr/data/particles/particles_data.hpp (1 hunks)
  • src/amr/physical_models/hybrid_model.hpp (2 hunks)
  • src/amr/resources_manager/field_resource.hpp (1 hunks)
  • src/amr/resources_manager/particle_resource.hpp (1 hunks)
  • src/amr/resources_manager/resources_guards.hpp (1 hunks)
  • src/amr/resources_manager/resources_manager.hpp (11 hunks)
  • src/amr/resources_manager/resources_manager_utilities.hpp (2 hunks)
  • tests/amr/messengers/test_messengers.cpp (4 hunks)
  • tests/amr/models/test_models.cpp (2 hunks)
  • tests/amr/resources_manager/test_resources_manager.cpp (8 hunks)
  • tests/amr/resources_manager/test_resources_manager.hpp (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • src/amr/resources_manager/field_resource.hpp
🧰 Additional context used
📓 Path-based instructions (8)
src/amr/data/field/field_data.hpp (1)

Pattern **/*.hpp: Review the C++ code, point out issues relative to principles of clean code, expressiveness, and performance.

src/amr/resources_manager/particle_resource.hpp (1)

Pattern **/*.hpp: Review the C++ code, point out issues relative to principles of clean code, expressiveness, and performance.

src/amr/resources_manager/resources_guards.hpp (1)

Pattern **/*.hpp: Review the C++ code, point out issues relative to principles of clean code, expressiveness, and performance.

src/amr/physical_models/hybrid_model.hpp (1)

Pattern **/*.hpp: Review the C++ code, point out issues relative to principles of clean code, expressiveness, and performance.

tests/amr/resources_manager/test_resources_manager.hpp (1)

Pattern **/*.hpp: Review the C++ code, point out issues relative to principles of clean code, expressiveness, and performance.

src/amr/resources_manager/resources_manager_utilities.hpp (1)

Pattern **/*.hpp: Review the C++ code, point out issues relative to principles of clean code, expressiveness, and performance.

src/amr/data/particles/particles_data.hpp (1)

Pattern **/*.hpp: Review the C++ code, point out issues relative to principles of clean code, expressiveness, and performance.

src/amr/resources_manager/resources_manager.hpp (1)

Pattern **/*.hpp: Review the C++ code, point out issues relative to principles of clean code, expressiveness, and performance.

⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: build (macos-latest)
  • GitHub Check: build (macos-14)
  • GitHub Check: Analyze (cpp)
  • GitHub Check: Analyze (python)
  • GitHub Check: build (ubuntu-latest)
  • GitHub Check: build (macos-13)
🔇 Additional comments (21)
src/amr/resources_manager/resources_manager.hpp (3)

73-96: Clarify dimension and interpolation order types in meta structures.
While ViewMetaWithParticles and ViewMetaMeshOnly correctly derive the dimension and interpolation order from GridLayoutT, it would be prudent to ensure that any downstream usage (e.g., in ResourcesManager) consistently treats dimension as a non-boolean type (like std::size_t). A mismatch, such as declaring it as bool in the derived class, may lead to subtle compilation issues or incorrect behavior.


98-125: Confirm the enum naming of Resource_t and usage in ResourcesInfo.
Introducing Resource_t to distinguish field vs. particle resources is a neat approach. Please ensure all references elsewhere (such as in the “ViewInfoResolver” or user code) use these enum values properly.


Line range hint 408-527: Validate the runtime errors in registerResource_().
If view.name() is not guaranteed to be unique, you risk collisions. If it is unique, consider documenting that requirement explicitly.

src/amr/resources_manager/particle_resource.hpp (1)

12-22: No major concerns; the template structure is consistent.
ParticleViewInfo cleanly maps the resource to variable and patch data types. Ensure all references to ParticleResource::dimension remain consistent, especially if combined with multi-dimensional systems.

src/amr/resources_manager/resources_guards.hpp (2)

18-34: Confirm thread-safety of resource pointer assignment.
The constructor immediately sets resources by calling setResources_ on all provided views. In a concurrent environment, ensure no data races occur if multiple ViewGuards or patches are set simultaneously.


40-46: Destructor usage appears correct.
Resetting view buffers to nullptr ensures that references to patch data do not escape the guard's scope. This is an elegant approach to RAII for resource handles.

tests/amr/resources_manager/test_resources_manager.hpp (2)

28-29: LGTM! Clean transition from ResourcesUsers to View.

The template parameter and member variable renaming improves code clarity by using more descriptive terminology.

Also applies to: 38-38


46-49: LGTM! Consistent usage of view terminology.

The lambda function and its application correctly use the new view-based approach.

Also applies to: 58-58, 63-63

src/amr/resources_manager/resources_manager_utilities.hpp (3)

20-34: LGTM! Well-structured trait definitions.

The is_field and is_particles traits are well-implemented using SFINAE for robust type checking.

Also applies to: 37-53


66-91: LGTM! Well-designed resolver class.

The ViewInfoResolver class effectively handles both field and particle views with proper type resolution.


153-182: LGTM! Clean implementation of name extraction.

The extractNames functions handle both compile-time and runtime views effectively.

tests/amr/models/test_models.cpp (1)

43-43: LGTM! Clear type definitions.

The addition of ParticlePackT and update to ResourcesManagerT improve type safety and clarity.

Also applies to: 54-54

src/amr/physical_models/hybrid_model.hpp (1)

14-14: LGTM! Appropriate header inclusion.

The particle pack header is correctly included for the new functionality.

tests/amr/resources_manager/test_resources_manager.cpp (4)

37-37: LGTM! Type alias improves readability.

The addition of ParticlePack_t type alias enhances code clarity by providing a meaningful name for the particle pack type.


Line range hint 1-2: LGTM! Function implementation is correct.

Simple and clear implementation of subtraction operation.


Line range hint 4-4: Add unit tests for the formula function.

The TODO comment indicates missing test coverage which should be addressed to ensure function correctness.

Would you like me to help generate unit tests for this function?


Line range hint 5-6: LGTM! Formula implementation is correct.

The function correctly implements x^y + z operation.

tests/amr/messengers/test_messengers.cpp (2)

203-207: LGTM! Type aliases improve clarity.

The renaming of resource manager types to ResourcesManagerHybrid and ResourcesManagerMHD enhances code clarity by making the specific model association explicit.


449-454: LGTM! Consistent type naming.

The type alias changes maintain consistency with the earlier renaming, properly separating hybrid and MHD resource manager types.

src/amr/data/particles/particles_data.hpp (1)

115-116: LGTM! Resource type alias improves code organization.

The addition of Resource_t type alias enhances code clarity and maintains consistency with the resource management refactoring across the codebase.

src/amr/data/field/field_data.hpp (1)

49-49: LGTM! Resource type alias maintains consistency.

The addition of Resource_t type alias aligns with the parallel change in ParticlesData, creating a consistent resource type system across the codebase.

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

🧹 Nitpick comments (2)
src/amr/resources_manager/resources_manager.hpp (2)

72-102: Consider adding static assertions for template parameters.

The template structures ViewMetaWithParticles and ViewMetaMeshOnly could benefit from compile-time validation of their template parameters.

Add static assertions to validate template parameters:

 template<typename GridLayoutT, typename GridView_t, typename ParticleView_t>
 struct ViewMetaWithParticles
 {
+    static_assert(GridLayoutT::dimension > 0, "GridLayoutT must have positive dimension");
+    static_assert(GridLayoutT::interp_order > 0, "GridLayoutT must have positive interpolation order");
     static constexpr std::size_t dimension    = GridLayoutT::dimension;
     static constexpr std::size_t interp_order = GridLayoutT::interp_order;

104-125: Consider adding noexcept specifications.

The ResourcesManager class inherits from Super but doesn't specify exception specifications. In modern C++, it's good practice to explicitly declare noexcept for move operations and destructors.

Add noexcept specifications:

-    ResourcesManager(ResourcesManager&&) = delete;
+    ResourcesManager(ResourcesManager&&) noexcept = delete;
-    ResourcesManager& operator=(ResourcesManager&&) = delete;
+    ResourcesManager& operator=(ResourcesManager&&) noexcept = delete;
-    ~ResourcesManager()
+    ~ResourcesManager() noexcept
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d0c6840 and de6c946.

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

Pattern **/*.hpp: Review the C++ code, point out issues relative to principles of clean code, expressiveness, and performance.

⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: build (macos-latest)
  • GitHub Check: build (macos-14)
  • GitHub Check: build (macos-13)
  • GitHub Check: build (ubuntu-latest)
  • GitHub Check: Analyze (cpp)
🔇 Additional comments (1)
src/amr/resources_manager/resources_manager.hpp (1)

487-497: Consider adding bounds checking for buffer access.

The setResourcesInternal_ method sets a buffer without explicit bounds checking, which could lead to buffer overflow issues.

Comment on lines 333 to 350


void makeAllViews(SAMRAI::hier::PatchHierarchy const& hierarchy)
{
for (auto const& [name, rinfo] : nameToResourceInfo_)
{
for (auto level = 0; level < hierarchy.getNumberOfLevels(); ++level)
{
auto patchLevel = hierarchy.getPatchLevel(level);
for (auto patch : *patchLevel)
{
auto const rid = rinfo.id;
auto pdata = patch->getPatchData(rid);
// levelViews_[name].emplace_back(2);
}
}
}
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Incomplete implementation in makeAllViews method.

The makeAllViews method contains a commented-out line suggesting incomplete implementation. This could lead to unexpected behavior.

The line // levelViews_[name].emplace_back(2); appears to be incomplete. Either implement the functionality or remove the method if it's not needed.

Comment on lines 393 to 400
template<typename ViewInfo>
auto getPatchData_(ResourcesInfo const& resourcesVariableInfo,
SAMRAI::hier::Patch const& patch) const
{
auto patchData = patch.getPatchData(resourcesVariableInfo.variable, context_);
return (std::dynamic_pointer_cast<typename ResourceType::patch_data_type>(patchData))
return (std::dynamic_pointer_cast<typename ViewInfo::patch_data_type>(patchData))
->getPointer();
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add null pointer check in getPatchData_ method.

The dynamic pointer cast could return nullptr, but this case isn't handled.

Add null pointer validation:

 auto getPatchData_(ResourcesInfo const& resourcesVariableInfo,
                    SAMRAI::hier::Patch const& patch) const
 {
     auto patchData = patch.getPatchData(resourcesVariableInfo.variable, context_);
-    return (std::dynamic_pointer_cast<typename ViewInfo::patch_data_type>(patchData))
-        ->getPointer();
+    auto typedData = std::dynamic_pointer_cast<typename ViewInfo::patch_data_type>(patchData);
+    if (!typedData) {
+        throw std::runtime_error("Failed to cast patch data to required type");
+    }
+    return typedData->getPointer();
 }
📝 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
template<typename ViewInfo>
auto getPatchData_(ResourcesInfo const& resourcesVariableInfo,
SAMRAI::hier::Patch const& patch) const
{
auto patchData = patch.getPatchData(resourcesVariableInfo.variable, context_);
return (std::dynamic_pointer_cast<typename ResourceType::patch_data_type>(patchData))
return (std::dynamic_pointer_cast<typename ViewInfo::patch_data_type>(patchData))
->getPointer();
}
template<typename ViewInfo>
auto getPatchData_(ResourcesInfo const& resourcesVariableInfo,
SAMRAI::hier::Patch const& patch) const
{
auto patchData = patch.getPatchData(resourcesVariableInfo.variable, context_);
auto typedData = std::dynamic_pointer_cast<typename ViewInfo::patch_data_type>(patchData);
if (!typedData) {
throw std::runtime_error("Failed to cast patch data to required type");
}
return typedData->getPointer();
}

Comment on lines 459 to 480
template<typename View>
void registerResource_(View const& view)
{
using ResourcesResolver_t = ResourceResolver<This, ResourcesView>;
using ViewInfoResolver_t = ViewInfoResolver<This, View>;

if (nameToResourceInfo_.count(view.name()) == 0)
{
ResourcesInfo info;
info.variable = ResourcesResolver_t::make_shared_variable(view);
info.variable = ViewInfoResolver_t::make_shared_variable(view);
info.id = variableDatabase_->registerVariableAndContext(
info.variable, context_, SAMRAI::hier::IntVector::getZero(dimension_));

info.variable, context_, SAMRAI::hier::IntVector::getZero(dimension_));
if constexpr (std::is_same_v<View, GridView_t>)
{
info.type = Resource_t::Field;
}
else if constexpr (std::is_same_v<View, ParticleView_t>)
{
info.type = Resource_t::Particle;
}
nameToResourceInfo_.emplace(view.name(), info);
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance type safety in registerResource_ method.

The type checking for Resource_t could be made more robust using type traits instead of direct type comparison.

Consider refactoring to use type traits:

-                if constexpr (std::is_same_v<View, GridView_t>)
+                if constexpr (traits::is_grid_view_v<View>)
                 {
                     info.type = Resource_t::Field;
                 }
-                else if constexpr (std::is_same_v<View, ParticleView_t>)
+                else if constexpr (traits::is_particle_view_v<View>)
                 {
                     info.type = Resource_t::Particle;
                 }
+                else
+                {
+                    static_assert(always_false_v<View>, "Unsupported view type");
+                }

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





TYPED_TEST_P(aResourceUserCollection, hasPointersValidOnlyWithGuard)
TYPED_TEST_P(ViewCollection, hasPointersValidOnlyWithGuard)

Check notice

Code scanning / CodeQL

Unused static variable Note test

Static variable gtest_hasPointersValidOnlyWithGuard_defined_ is never read.


typedef ::testing::Types<IonPop1DOnly, VecField1DOnly, Ions1DOnly, Electromag1DOnly,
HybridState1DOnly>
MyTypes;
INSTANTIATE_TYPED_TEST_SUITE_P(testResourcesManager, aResourceUserCollection, MyTypes);
INSTANTIATE_TYPED_TEST_SUITE_P(testResourcesManager, ViewCollection, MyTypes);

Check notice

Code scanning / CodeQL

Unused static variable Note test

Static variable gtest_testResourcesManager_ViewCollection is never read.
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 (2)
src/amr/resources_manager/resources_manager.hpp (2)

335-350: ⚠️ Potential issue

Incomplete implementation in makeAllViews method.

The makeAllViews method contains a commented-out line suggesting incomplete implementation. This could lead to unexpected behavior.


393-400: ⚠️ Potential issue

Add null pointer check in getPatchData_ method.

The dynamic pointer cast could return nullptr, but this case isn't handled.

🧹 Nitpick comments (2)
src/amr/resources_manager/resources_manager_utilities.hpp (1)

20-22: Update trait documentation to reflect View terminology.

The documentation comments still reference "ResourceView" instead of "View". Please update these comments to maintain consistency with the new terminology.

Also applies to: 37-39, 113-116

tests/amr/messengers/test_messengers.cpp (1)

466-467: Consider simplifying the shared pointer initialization.

The current initialization uses a temporary variable with explicit type. Consider using auto for better readability.

-    std::shared_ptr<ResourcesManagerHybrid> resourcesManagerHybrid{
-        std::make_shared<ResourcesManagerHybrid>()};
+    auto resourcesManagerHybrid = std::make_shared<ResourcesManagerHybrid>();
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d56ef9e and db8b15f.

📒 Files selected for processing (12)
  • src/amr/data/field/field_data.hpp (1 hunks)
  • src/amr/data/particles/particles_data.hpp (1 hunks)
  • src/amr/physical_models/hybrid_model.hpp (2 hunks)
  • src/amr/resources_manager/field_resource.hpp (1 hunks)
  • src/amr/resources_manager/particle_resource.hpp (1 hunks)
  • src/amr/resources_manager/resources_guards.hpp (1 hunks)
  • src/amr/resources_manager/resources_manager.hpp (11 hunks)
  • src/amr/resources_manager/resources_manager_utilities.hpp (2 hunks)
  • tests/amr/messengers/test_messengers.cpp (4 hunks)
  • tests/amr/models/test_models.cpp (2 hunks)
  • tests/amr/resources_manager/test_resources_manager.cpp (8 hunks)
  • tests/amr/resources_manager/test_resources_manager.hpp (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (7)
  • src/amr/data/field/field_data.hpp
  • src/amr/resources_manager/field_resource.hpp
  • src/amr/resources_manager/particle_resource.hpp
  • tests/amr/models/test_models.cpp
  • src/amr/physical_models/hybrid_model.hpp
  • src/amr/data/particles/particles_data.hpp
  • tests/amr/resources_manager/test_resources_manager.cpp
🧰 Additional context used
📓 Path-based instructions (4)
src/amr/resources_manager/resources_guards.hpp (1)

Pattern **/*.hpp: Review the C++ code, point out issues relative to principles of clean code, expressiveness, and performance.

tests/amr/resources_manager/test_resources_manager.hpp (1)

Pattern **/*.hpp: Review the C++ code, point out issues relative to principles of clean code, expressiveness, and performance.

src/amr/resources_manager/resources_manager_utilities.hpp (1)

Pattern **/*.hpp: Review the C++ code, point out issues relative to principles of clean code, expressiveness, and performance.

src/amr/resources_manager/resources_manager.hpp (1)

Pattern **/*.hpp: Review the C++ code, point out issues relative to principles of clean code, expressiveness, and performance.

⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: build (macos-latest)
  • GitHub Check: build (macos-14)
  • GitHub Check: Analyze (cpp)
  • GitHub Check: Analyze (python)
  • GitHub Check: build (macos-13)
  • GitHub Check: build (ubuntu-latest)
🔇 Additional comments (10)
src/amr/resources_manager/resources_guards.hpp (2)

18-19: Documentation needs to be completed.

The documentation comment for the ViewGuard class is incomplete with a TODO marker. Please provide comprehensive documentation explaining the purpose, usage, and behavior of the ViewGuard class.


20-21: LGTM! Clean class renaming and template parameter updates.

The renaming from ResourcesGuard to ViewGuard and the template parameter changes are consistent throughout the class definition, including move/copy constructors and assignment operators.

Also applies to: 52-56

tests/amr/resources_manager/test_resources_manager.hpp (2)

32-33: LGTM! Clear type aliases enhance code readability.

The type aliases for Grid_t, ParticlePack_t, and Layout provide clear type definitions and improve code maintainability.

Also applies to: 35-36


46-49: LGTM! Consistent lambda function updates.

The lambda function has been correctly updated to use the new view-based terminology, maintaining consistency with the broader refactoring changes.

Also applies to: 58-58

src/amr/resources_manager/resources_manager_utilities.hpp (1)

66-91: LGTM! Well-structured ViewInfoResolver implementation.

The ViewInfoResolver class provides a clean implementation for resolving view types and creating shared variables. The type checking and error handling are appropriate.

src/amr/resources_manager/resources_manager.hpp (1)

471-478: Enhance type safety in registerResource_ method.

Consider using type traits for type checking instead of direct type comparison.

tests/amr/messengers/test_messengers.cpp (4)

203-207: LGTM! Clear type definitions enhancing model-specific resource management.

The change from generic ResourcesManagerT to specific ResourcesManagerHybrid and ResourcesManagerMHD improves type safety and clarity.


256-257: LGTM! Consistent resource manager instantiation.

The instantiation of resource managers aligns with the type definitions, maintaining consistency throughout the code.


449-454: LGTM! Consistent type definitions in test hierarchy.

The type definitions in AfullHybridBasicHierarchy mirror the earlier changes, maintaining consistency across the test framework.


Line range hint 203-467: Verify complete migration from ResourcesManagerT.

Let's ensure all instances of the old type name have been updated.

✅ Verification successful

Remaining ResourcesManagerT usages are safe

The remaining instances are either in test code or used as internal type aliases referencing the correct updated types. No changes needed.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining instances of ResourcesManagerT
rg "ResourcesManagerT" -A 2

Length of output: 1808

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 (2)
src/amr/resources_manager/resources_manager.hpp (2)

333-350: ⚠️ Potential issue

Incomplete implementation in makeAllViews method.

The method iterates over the hierarchy but doesn't perform any meaningful operation. The commented-out code at line 346 suggests incomplete implementation.

Please either:

  1. Complete the implementation by uncommenting and fixing the code at line 346
  2. Remove the method if it's not needed
  3. Add a TODO comment explaining what needs to be implemented

393-400: ⚠️ Potential issue

Add nullptr check for dynamic_pointer_cast.

The dynamic_pointer_cast could return nullptr, which would lead to undefined behavior.

Apply this fix:

 auto getPatchData_(ResourcesInfo const& resourcesVariableInfo,
                    SAMRAI::hier::Patch const& patch) const
 {
     auto patchData = patch.getPatchData(resourcesVariableInfo.variable, context_);
-    return (std::dynamic_pointer_cast<typename ViewInfo::patch_data_type>(patchData))
-        ->getPointer();
+    auto typedData = std::dynamic_pointer_cast<typename ViewInfo::patch_data_type>(patchData);
+    if (!typedData) {
+        throw std::runtime_error("Failed to cast patch data to required type");
+    }
+    return typedData->getPointer();
 }
🧹 Nitpick comments (1)
src/amr/resources_manager/resources_manager.hpp (1)

459-480: Consider using type traits for more robust type checking.

The current implementation uses direct type comparison. Using type traits would make the code more maintainable and extensible.

Consider this enhancement:

 template<typename View>
 void registerResource_(View const& view)
 {
     using ViewInfoResolver_t = ViewInfoResolver<This, View>;

     if (nameToResourceInfo_.count(view.name()) == 0)
     {
         ResourcesInfo info;
         info.variable = ViewInfoResolver_t::make_shared_variable(view);
         info.id       = variableDatabase_->registerVariableAndContext(
             info.variable, context_, SAMRAI::hier::IntVector::getZero(dimension_));

-        if constexpr (is_field_v<View>)
+        if constexpr (traits::is_grid_view_v<View>)
         {
             info.type = Resource_t::Field;
         }
-        else if constexpr (is_particles_v<View>)
+        else if constexpr (traits::is_particle_view_v<View>)
         {
             info.type = Resource_t::Particle;
         }
+        else
+        {
+            static_assert(always_false_v<View>, "Unsupported view type");
+        }
         nameToResourceInfo_.emplace(view.name(), info);
     }
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between db8b15f and e7a8faf.

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

Pattern **/*.hpp: Review the C++ code, point out issues relative to principles of clean code, expressiveness, and performance.

⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: build (macos-latest)
  • GitHub Check: build (macos-14)
  • GitHub Check: build (macos-13)
  • GitHub Check: build (ubuntu-latest)
  • GitHub Check: Analyze (cpp)
  • GitHub Check: Analyze (python)
🔇 Additional comments (2)
src/amr/resources_manager/resources_manager.hpp (2)

70-102: Well-structured type definitions with clear separation of concerns!

The new template structures provide a clean separation between particle and mesh-only views, with appropriate use of static constexpr members and clear type aliases.


104-125: Clean class hierarchy with improved type safety!

The ResourcesManager's inheritance from SuperDispatcher and the addition of the Resource_t enum class enhance type safety and maintainability. The ResourcesInfo struct's new type field provides better resource categorization.

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 (3)
tests/amr/resources_manager/test_resources_manager.hpp (1)

Line range hint 45-57: Consider extracting the lambda to a named function.

The lambda function contains significant logic for registering and allocating resources. Consider extracting it to a named member function for better readability and reusability.

-        auto registerAndAllocate = [this](auto& view) {
-            auto& patchHierarchy = hierarchy->hierarchy;
-
-            resourcesManager.registerResources(view.view);
-
-            double const initDataTime{0.0};
-
-            for (int iLevel = 0; iLevel < patchHierarchy->getNumberOfLevels(); ++iLevel)
-            {
-                auto patchLevel = patchHierarchy->getPatchLevel(iLevel);
-                for (auto& patch : *patchLevel)
-                {
-                    resourcesManager.allocate(view.view, *patch, initDataTime);
-                }
-            }
-        };
+        void registerAndAllocateView(auto& view) {
+            auto& patchHierarchy = hierarchy->hierarchy;
+            resourcesManager.registerResources(view.view);
+
+            double const initDataTime{0.0};
+
+            for (int iLevel = 0; iLevel < patchHierarchy->getNumberOfLevels(); ++iLevel)
+            {
+                auto patchLevel = patchHierarchy->getPatchLevel(iLevel);
+                for (auto& patch : *patchLevel)
+                {
+                    resourcesManager.allocate(view.view, *patch, initDataTime);
+                }
+            }
+        }
src/amr/resources_manager/resources_manager.hpp (2)

391-421: Consider breaking down makeAllViews into smaller functions.

The makeAllViews method is quite long and handles multiple responsibilities. Consider extracting the view creation logic into separate functions for fields and particles.

+    private:
+        void createFieldView_(const std::string& name, std::size_t levelNumber, 
+                            const ResourcesInfo& rinfo, SAMRAI::hier::Patch& patch) {
+            auto viewPtr = getResourcesPtr_<FieldViewInfo>(rinfo, patch);
+            views_.add(name, levelNumber, viewPtr);
+        }
+
+        void createParticleView_(const std::string& name, std::size_t levelNumber,
+                               const ResourcesInfo& rinfo, SAMRAI::hier::Patch& patch) {
+            auto viewPtr = getResourcesPtr_<ParticleViewInfo>(rinfo, patch);
+            views_.add(name, levelNumber, viewPtr);
+        }
+
+    public:
     void makeAllViews(SAMRAI::hier::PatchHierarchy const& hierarchy)
     {
         for (auto const& [name, rinfo] : nameToResourceInfo_)
         {
             for (auto levelNumber = 0; levelNumber < hierarchy.getNumberOfLevels();
                  ++levelNumber)
             {
                 views_.resetLevel(name, levelNumber);
                 auto patchLevel = hierarchy.getPatchLevel(levelNumber);
                 for (auto patch : *patchLevel)
                 {
-                    auto const rid = rinfo.id;
-                    auto pdata     = patch->getPatchData(rid);
-                    // take the name and check if it is a field or a particle
-                    // if it is a field, we can create a FieldView else a particlepack
-                    // and set it on the patch
                     auto resourceType = rinfo.type;
                     if (resourceType == Resource_t::Field)
-                    {
-                        auto viewPtr = getResourcesPtr_<FieldViewInfo>(rinfo, *patch);
-                        views_.add(name, levelNumber, viewPtr);
-                    }
-                    else if (resourceType == Resource_t::Particle)
-                    {
-                        auto viewPtr = getResourcesPtr_<ParticleViewInfo>(rinfo, *patch);
-                        views_.add(name, levelNumber, viewPtr);
-                    }
+                        createFieldView_(name, levelNumber, rinfo, *patch);
+                    else if (resourceType == Resource_t::Particle)
+                        createParticleView_(name, levelNumber, rinfo, *patch);
                 }
             }
         }
     }

542-549: Consider using a switch statement for resource type assignment.

The if-else chain for resource type assignment could be more maintainable using a switch statement with compile-time type traits.

-                if constexpr (is_field_v<View>)
-                {
-                    info.type = Resource_t::Field;
-                }
-                else if constexpr (is_particles_v<View>)
-                {
-                    info.type = Resource_t::Particle;
-                }
+                constexpr auto resource_type = []() {
+                    if constexpr (is_field_v<View>)
+                        return Resource_t::Field;
+                    else if constexpr (is_particles_v<View>)
+                        return Resource_t::Particle;
+                    else
+                        static_assert(always_false_v<View>, "Unsupported view type");
+                }();
+                info.type = resource_type;
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e7a8faf and 7b6d814.

📒 Files selected for processing (9)
  • src/amr/data/field/field_data.hpp (1 hunks)
  • src/amr/data/particles/particles_data.hpp (1 hunks)
  • src/amr/physical_models/hybrid_model.hpp (2 hunks)
  • src/amr/resources_manager/field_resource.hpp (1 hunks)
  • src/amr/resources_manager/particle_resource.hpp (1 hunks)
  • src/amr/resources_manager/resources_manager.hpp (11 hunks)
  • tests/amr/models/test_models.cpp (1 hunks)
  • tests/amr/resources_manager/test_resources_manager.cpp (7 hunks)
  • tests/amr/resources_manager/test_resources_manager.hpp (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (6)
  • src/amr/data/field/field_data.hpp
  • src/amr/data/particles/particles_data.hpp
  • tests/amr/models/test_models.cpp
  • src/amr/physical_models/hybrid_model.hpp
  • src/amr/resources_manager/field_resource.hpp
  • tests/amr/resources_manager/test_resources_manager.cpp
🧰 Additional context used
📓 Path-based instructions (3)
src/amr/resources_manager/particle_resource.hpp (1)

Pattern **/*.hpp: Review the C++ code, point out issues relative to principles of clean code, expressiveness, and performance.

tests/amr/resources_manager/test_resources_manager.hpp (1)

Pattern **/*.hpp: Review the C++ code, point out issues relative to principles of clean code, expressiveness, and performance.

src/amr/resources_manager/resources_manager.hpp (1)

Pattern **/*.hpp: Review the C++ code, point out issues relative to principles of clean code, expressiveness, and performance.

⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: build (macos-latest)
  • GitHub Check: Analyze (cpp)
  • GitHub Check: build (macos-14)
  • GitHub Check: build (ubuntu-latest)
  • GitHub Check: build (macos-13)
  • GitHub Check: Analyze (python)
🔇 Additional comments (6)
src/amr/resources_manager/particle_resource.hpp (2)

14-15: LGTM! Clean template structure definition.

The renaming from UserParticleType to ParticleViewInfo and the template parameter change improve clarity by better expressing the intent.


20-22: Consider implementing the suggested templating improvement.

The TODO comment suggests potential improvements to the template structure. Consider implementing this enhancement to make the link to ParticlePack more flexible.

Would you like me to propose an implementation for this improvement?

tests/amr/resources_manager/test_resources_manager.hpp (2)

28-29: LGTM! Clear test class structure.

The renaming from aResourceUserCollection to ViewCollection improves clarity and aligns with the new terminology.


34-35: LGTM! Proper type definition with particle support.

The ResourcesManager type now correctly includes ParticleArray support, making it more flexible.

src/amr/resources_manager/resources_manager.hpp (2)

26-74: LGTM! Well-structured HierarchyViews implementation.

The HierarchyViews class provides a clean implementation for managing views across different levels, with proper error checking and clear member functions.


465-472: ⚠️ Potential issue

Add null pointer check in getResourcesPtr_ method.

The dynamic pointer cast could return nullptr, but this case isn't handled.

 template<typename ViewInfo>
 auto getResourcesPtr_(ResourcesInfo const& resourcesVariableInfo,
                       SAMRAI::hier::Patch const& patch) const
 {
     auto patchData = patch.getPatchData(resourcesVariableInfo.variable, context_);
-    return (std::dynamic_pointer_cast<typename ViewInfo::patch_data_type>(patchData))
-        ->getPointer();
+    auto typedData = std::dynamic_pointer_cast<typename ViewInfo::patch_data_type>(patchData);
+    if (!typedData) {
+        throw std::runtime_error("Failed to cast patch data to required type");
+    }
+    return typedData->getPointer();
 }

Likely invalid or redundant comment.

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