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

feat: proto axis json converter #4038

Closed
wants to merge 18 commits into from

Conversation

asalzburger
Copy link
Contributor

@asalzburger asalzburger commented Jan 20, 2025

This PR builds on top of #4034 and adds support for JSON/IO for the ProtoAxis.
It also adds the unit test for reading and writing the ProtoAxis, which largely uses the already existing Axis Json support.

--- END COMMIT MESSAGE ---

Any further description goes here, @-mentions are ok here!

  • Use a conventional commits prefix: quick summary
    • We mostly use feat, fix, refactor, docs, chore and build types.
  • A milestone will be assigned by one of the maintainers

Summary by CodeRabbit

Release Notes

  • New Features

    • Added factory methods for creating IAxis instances with equidistant and variable binning.
    • Introduced ProtoAxis class for flexible axis configuration.
    • Added JSON conversion support for ProtoAxis.
  • Improvements

    • Enhanced axis management with new utility methods.
    • Improved error handling for axis creation.
    • Added support for different axis types and boundary configurations.
  • Testing

    • Comprehensive unit tests added for IAxis, ProtoAxis, and JSON conversion functionality.

@asalzburger asalzburger added the 🛑 blocked This item is blocked by another item label Jan 20, 2025
@asalzburger asalzburger added this to the next milestone Jan 20, 2025
Copy link

coderabbitai bot commented Jan 20, 2025

Walkthrough

Enhancements to the ACTS project's axis management system, this pull request introduces. A new ProtoAxis class added is, alongside factory methods for the IAxis interface, enabling more flexible axis creation and configuration. Implementing JSON conversion capabilities, adding comprehensive unit tests, and expanding the utility of axis-related components in the core and plugin libraries, the changes include.

Changes

File Change Summary
Core/include/Acts/Utilities/IAxis.hpp Added virtual destructor and static factory methods for axis creation
Core/include/Acts/Utilities/ProtoAxis.hpp New header defining ProtoAxis class with axis management functionality
Core/src/Utilities/IAxis.cpp, Core/src/Utilities/ProtoAxis.cpp Implementations of new axis-related methods and classes
Plugins/Json/include/Acts/Plugins/Json/ProtoAxisJsonConverter.hpp Added JSON conversion methods for ProtoAxis
Plugins/Json/src/ProtoAxisJsonConverter.cpp Implemented JSON conversion functionality for ProtoAxis
Tests/UnitTests/Core/Utilities/AxesTests.cpp New unit tests for IAxis factory methods
Tests/UnitTests/Core/Utilities/ProtoAxisTests.cpp New unit tests for ProtoAxis functionality
Tests/UnitTests/Plugins/Json/ProtoAxisJsonConverterTests.cpp New unit tests for JSON conversion of ProtoAxis

Suggested labels

automerge, Event Data Model, Track Finding

Suggested reviewers

  • paulgessinger

Possibly related PRs

Poem

Axes of knowledge, spinning bright, 🌟
In ACTS' realm, a coder's delight! 📐
ProtoAxis dances, JSON in hand, 🕺
Binning dimensions across the land 🌈
Code flows like wisdom, pure and true 🧘‍♂️
In the force of development, we pursue! ✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7cefb6e and a60c22a.

📒 Files selected for processing (1)
  • Plugins/Json/src/ProtoAxisJsonConverter.cpp (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • Plugins/Json/src/ProtoAxisJsonConverter.cpp
⏰ Context from checks skipped due to timeout of 90000ms (18)
  • GitHub Check: merge-sentinel
  • GitHub Check: CI Bridge / lcg_106a: [alma9, clang16]
  • GitHub Check: CI Bridge / lcg_106a: [alma9, gcc14]
  • GitHub Check: CI Bridge / lcg_106a: [alma9, gcc13]
  • GitHub Check: CI Bridge / lcg_105: [alma9, clang16]
  • GitHub Check: CI Bridge / lcg_105: [alma9, gcc13]
  • GitHub Check: CI Bridge / linux_ubuntu_2204_clang
  • GitHub Check: CI Bridge / linux_ubuntu_2204
  • GitHub Check: CI Bridge / build_linux_ubuntu
  • GitHub Check: missing_includes
  • GitHub Check: linux_ubuntu_extra (ubuntu2204_clang, 20)
  • GitHub Check: linux_ubuntu
  • GitHub Check: linux_ubuntu_extra (ubuntu2204, 20)
  • GitHub Check: macos
  • GitHub Check: build_debug
  • GitHub Check: CI Bridge / build_exatrkx
  • GitHub Check: CI Bridge / build_exatrkx_cpu
  • GitHub Check: CI Bridge / clang_tidy

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.

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

Actionable comments posted: 2

🧹 Nitpick comments (10)
Core/src/Utilities/IAxis.cpp (2)

34-43: Handle unknown boundary types, you must carefully.

In the default case, a logic error you throw. Consider using an assertion or ensuring all boundary types covered are.

Apply this diff to handle the default case more explicitly:

 switch (aBoundaryType) {
   case Open:
     return std::make_unique<Axis<Equidistant, Open>>(min, max, nbins);
   case Bound:
     return std::make_unique<Axis<Equidistant, Bound>>(min, max, nbins);
   case Closed:
     return std::make_unique<Axis<Equidistant, Closed>>(min, max, nbins);
+  default:
+     throw std::invalid_argument("Invalid AxisBoundaryType provided.");
 }

62-71: Default case handling, improve you should.

In the switch statement, a logic error you throw. Better to validate aBoundaryType before the switch, it may be.

Consider this change:

 if (aBoundaryType != AxisBoundaryType::Open &&
     aBoundaryType != AxisBoundaryType::Bound &&
     aBoundaryType != AxisBoundaryType::Closed) {
   throw std::invalid_argument("Invalid AxisBoundaryType provided.");
 }

 switch (aBoundaryType) {
   case Open:
     return std::make_unique<Axis<Variable, Open>>(edges);
   case Bound:
     return std::make_unique<Axis<Variable, Bound>>(edges);
   case Closed:
     return std::make_unique<Axis<Variable, Closed>>(edges);
 }
Core/include/Acts/Utilities/ProtoAxis.hpp (1)

54-54: Auto-range binning, clarity needed there is.

Placeholder constructor you have for auto-range binning. Ensure that users aware are, that implementation provided is not.

Add a comment to indicate unimplemented status:

 /// @note that auto-range is only supported for equidistant binning
+/// @warning Auto-range binning not yet implemented.
 ProtoAxis(AxisDirection aDir, AxisBoundaryType abType, std::size_t nbins);
Plugins/Json/include/Acts/Plugins/Json/ProtoAxisJsonConverter.hpp (1)

31-31: Documentation clarity, improve you can.

Explain the expected format of the JSON object, you should. Helps users understand how to use fromJson, it does.

Add details about the JSON structure in the documentation comment.

Plugins/Json/src/ProtoAxisJsonConverter.cpp (1)

15-21: Hmmmm, robust this implementation is, but safer it could be!

Check for null pointer or invalid state, we must. Add validation before accessing properties, I suggest.

 nlohmann::json Acts::ProtoAxisJsonConverter::toJson(const Acts::ProtoAxis& pa) {
   nlohmann::json j;
+  if (!pa.getAxis()) {
+    throw std::invalid_argument("Invalid ProtoAxis with null axis");
+  }
   j["axis_dir"] = pa.getAxisDirection();
   j["axis"] = AxisJsonConverter::toJson(pa.getAxis());
   j["autorange"] = pa.isAutorange();
   return j;
 }
Core/src/Utilities/ProtoAxis.cpp (2)

11-22: Clear in purpose this function is, but more descriptive in error, it could be!

Add valid combinations to error message, help future developers it will.

 void checkConsistency(Acts::AxisDirection aDir, Acts::AxisBoundaryType abType) {
   if (abType == Acts::AxisBoundaryType::Closed &&
       aDir != Acts::AxisDirection::AxisPhi &&
       aDir != Acts::AxisDirection::AxisRPhi) {
     std::string msg =
-        "ProtoBinning: Invalid axis boundary type 'Closed' for direction '";
-    msg += axisDirectionName(aDir) + "'.";
+        "ProtoBinning: Invalid axis boundary type 'Closed' for direction '" +
+        axisDirectionName(aDir) + "'. Closed boundary type is only valid for " +
+        "AxisPhi and AxisRPhi directions.";
     throw std::invalid_argument(msg);
   }
 }

56-73: Readable output this provides, but modernize it we could!

Consider using std::format (C++20) or fmt library for cleaner string formatting, I suggest.

 std::string Acts::ProtoAxis::toString() const {
-  std::stringstream ss;
-  ss << "ProtoAxis: " << getAxis().getNBins() << " bins in "
-     << axisDirectionName(m_axisDir);
-  ss << (getAxis().getType() == AxisType::Variable ? ", variable "
-                                                   : ", equidistant ");
+  std::string axisType = getAxis().getType() == AxisType::Variable ? 
+                         "variable" : "equidistant";
+  std::string rangeStr;
   if (!m_autorange) {
     const auto& edges = getAxis().getBinEdges();
-    ss << "within [" << edges.front() << ", " << edges.back() << "]";
+    rangeStr = std::format("within [{}, {}]", edges.front(), edges.back());
   } else {
-    ss << "within automatic range";
+    rangeStr = "within automatic range";
   }
-  return ss.str();
+  return std::format("ProtoAxis: {} bins in {}, {} {}", 
+                    getAxis().getNBins(), 
+                    axisDirectionName(m_axisDir),
+                    axisType,
+                    rangeStr);
 }
Tests/UnitTests/Plugins/Json/ProtoAxisJsonConverterTests.cpp (1)

21-84: Good test coverage you have, but stronger it could become!

Add test cases for error scenarios and edge cases, we should:

  • Invalid JSON format
  • Missing required fields
  • Invalid axis combinations

Example test case to add:

BOOST_AUTO_TEST_CASE(InvalidProtoAxisJsonConversion) {
  using enum Acts::AxisBoundaryType;
  using enum Acts::AxisDirection;

  nlohmann::json invalidJson;  // Empty JSON
  BOOST_CHECK_THROW(Acts::ProtoAxisJsonConverter::fromJson(invalidJson),
                   nlohmann::json::exception);

  // Missing required fields
  invalidJson["axis_dir"] = AxisX;
  BOOST_CHECK_THROW(Acts::ProtoAxisJsonConverter::fromJson(invalidJson),
                   nlohmann::json::exception);
}
Core/include/Acts/Utilities/IAxis.hpp (1)

65-85: Factory methods, well-designed they are! But documentation, improve we must.

Add @throws documentation for error cases in factory methods, help users handle exceptions it will.

   /// Centralized axis factory for equidistant binning
   ///
   /// @param aBoundaryType the axis boundary type
   /// @param min the minimum edge of the axis
   /// @param max the maximum edge of the axis
   /// @param nbins the number of bins
   ///
+  /// @throws std::invalid_argument if min >= max or nbins == 0
   /// @return a unique pointer to the axis
   static std::unique_ptr<IAxis> create(AxisBoundaryType aBoundaryType,
                                        double min, double max,
                                        std::size_t nbins);

   /// Centralized axis factory for variable binning
   ///
   /// @param aBoundaryType the axis boundary type
   /// @param edges are the bin edges
   ///
+  /// @throws std::invalid_argument if edges is empty or not strictly increasing
   /// @return a unique pointer to the axis
   static std::unique_ptr<IAxis> create(AxisBoundaryType aBoundaryType,
                                        const std::vector<double>& edges);
Tests/UnitTests/Core/Utilities/AxesTests.cpp (1)

595-636: Factory method tests, strong they are.

Cover all axis types and boundary conditions, these tests do. Invalid cases well-tested, they are. But missing test for memory management of unique pointers, I sense.

Add test to verify proper cleanup of unique pointers, you should:

// Test memory management
auto axis = IAxis::create(Bound, 0.0, 10., 10);
BOOST_CHECK_NO_THROW(axis.reset());
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2b8572b and 7cefb6e.

📒 Files selected for processing (13)
  • Core/include/Acts/Utilities/IAxis.hpp (3 hunks)
  • Core/include/Acts/Utilities/ProtoAxis.hpp (1 hunks)
  • Core/src/Utilities/CMakeLists.txt (1 hunks)
  • Core/src/Utilities/IAxis.cpp (1 hunks)
  • Core/src/Utilities/ProtoAxis.cpp (1 hunks)
  • Plugins/Json/CMakeLists.txt (1 hunks)
  • Plugins/Json/include/Acts/Plugins/Json/ProtoAxisJsonConverter.hpp (1 hunks)
  • Plugins/Json/src/ProtoAxisJsonConverter.cpp (1 hunks)
  • Tests/UnitTests/Core/Utilities/AxesTests.cpp (1 hunks)
  • Tests/UnitTests/Core/Utilities/CMakeLists.txt (1 hunks)
  • Tests/UnitTests/Core/Utilities/ProtoAxisTests.cpp (1 hunks)
  • Tests/UnitTests/Plugins/Json/CMakeLists.txt (1 hunks)
  • Tests/UnitTests/Plugins/Json/ProtoAxisJsonConverterTests.cpp (1 hunks)
🧰 Additional context used
🪛 cppcheck (2.10-2)
Tests/UnitTests/Core/Utilities/ProtoAxisTests.cpp

[error] 17-17: There is an unknown macro here somewhere. Configuration is required. If BOOST_AUTO_TEST_SUITE is a macro then please configure it.

(unknownMacro)

Tests/UnitTests/Plugins/Json/ProtoAxisJsonConverterTests.cpp

[error] 19-19: There is an unknown macro here somewhere. Configuration is required. If BOOST_AUTO_TEST_SUITE is a macro then please configure it.

(unknownMacro)

⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: merge-sentinel
  • GitHub Check: macos
🔇 Additional comments (16)
Core/src/Utilities/IAxis.cpp (2)

16-44: Proper input validation, you have implemented.

Validates the axis range and number of bins, your code does. Throws exceptions when inputs invalid are. Good practice, this is.


46-72: Edge sorting validation, well done it is.

Checks for at least two edges and that they are sorted, your code does. Exception thrown when invalid inputs detected are. Excellent.

Core/include/Acts/Utilities/ProtoAxis.hpp (3)

35-35: Const correctness, consider you should.

Pass the edges vector by const reference, you do. Good.


60-60: Defaulted move operations, wise choice it is.

Allows efficient resource management, this does.


102-108: Template usage, correct it is.

Creates grid with the appropriate axis type, your code does. Ensures compatibility and efficiency.

Plugins/Json/include/Acts/Plugins/Json/ProtoAxisJsonConverter.hpp (1)

26-26: Function naming, consistency important it is.

toJson function you have. Ensure consistent naming with other JSON converters in the codebase, you must.

Verify that naming conventions aligned are. If different, consider renaming to match.

Core/src/Utilities/ProtoAxis.cpp (2)

24-42: Well-crafted these constructors are! Approve them, I do.

Proper validation and initialization, they maintain.


44-54: Simple yet effective, these getters are!

Clear in purpose and implementation, they remain.

Core/include/Acts/Utilities/IAxis.hpp (1)

24-25: Wise decision, adding virtual destructor is! Prevent memory leaks, it will.

Proper cleanup of derived classes through base pointer, this ensures.

Tests/UnitTests/Core/Utilities/ProtoAxisTests.cpp (3)

19-93: Comprehensive test coverage for EquidistantProtoAxis, I see.

Strong with the Force, these tests are. Cover direct access, IAxis interface, grid creation, and invalid cases, they do. Well-structured and thorough, the test case is.


95-126: Test AutorangeProtoAxis well, you do.

Validate autorange functionality and boundary types correctly, this test does. Clear and focused, the assertions are.


128-178: Test VariableProtoAxis thoroughly, you have.

Cover all aspects of variable axis behavior, these tests do. Invalid cases for different axis directions, they check. Comprehensive validation of edge cases, I sense.

Core/src/Utilities/CMakeLists.txt (1)

10-12: Added source files correctly, you have.

In proper order and alignment with existing files, the additions are.

Tests/UnitTests/Plugins/Json/CMakeLists.txt (1)

13-13: Added unit test correctly, you have.

Follow the established pattern of test declarations, this addition does.

Plugins/Json/CMakeLists.txt (1)

18-18: Properly integrated, the new converter file is, hmmmm.

In the correct alphabetical order, placed it is. With the existing JSON converter components, aligned well it stands.

Tests/UnitTests/Core/Utilities/CMakeLists.txt (1)

30-30: Wisely placed, the new test file is, yes.

In harmony with other tests it stands, alphabetically ordered it remains. The Force is strong with this one.

Core/include/Acts/Utilities/ProtoAxis.hpp Show resolved Hide resolved
Plugins/Json/src/ProtoAxisJsonConverter.cpp Outdated Show resolved Hide resolved
@github-actions github-actions bot added Component - Core Affects the Core module Component - Plugins Affects one or more Plugins labels Jan 20, 2025
Copy link

github-actions bot commented Jan 20, 2025

📊: Physics performance monitoring for a60c22a

Full contents

physmon summary

asalzburger and others added 2 commits January 20, 2025 21:18
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@asalzburger
Copy link
Contributor Author

Superseded.

kodiakhq bot pushed a commit that referenced this pull request Jan 24, 2025
This PR adds json writing/reading to the new ProtoAxis. It supersedes #4038
@paulgessinger paulgessinger modified the milestones: next, v39.0.0 Feb 5, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Component - Core Affects the Core module Component - Plugins Affects one or more Plugins 🛑 blocked This item is blocked by another item
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants