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

add misalignment decoration for DD4hep detector #3891

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

Zequn-SUN
Copy link

@Zequn-SUN Zequn-SUN commented Nov 22, 2024

  • Add misalignment decoration for odd. In this version, a file odd-misalignment-matrix.json is required. The json file includes the identifiers of the misaligned DD4hepDetectorElements, as well as six parameters: the translation parameters in the x, y, and z directions (unit: cm), and the rotation angles along the x, y, and z axes (unit: degree). In the decorator, DD4hepGeometryContext is used to store the misaligned transform matrix.
  • A follow-up PR will be made including the following development:
  • Create an interface to control whether the detector is misaligned.
  • Integrate the functionality to generate misalignment parameters?

Summary by CodeRabbit

  • New Features

    • Introduced the DD4hepAlignmentDecorator class for managing detector alignment.
    • Added the DD4hepGeometryContext class to handle alignment functionalities in the DD4hep framework.
    • New methods for transforming geometries and managing alignment states in the DD4hepDetectorElement and DD4hepGeometryContext classes.
  • Bug Fixes

    • Enhanced error handling for invalid geometrical elements during alignment processing.
  • Documentation

    • Updated comments and method descriptions for clarity on new functionalities.

Copy link

coderabbitai bot commented Nov 22, 2024

Walkthrough

In this pull request, a comprehensive enhancement to the DD4hep detector alignment framework has been introduced. The changes involve adding new classes and methods to support more flexible geometry transformations and misalignment handling. A new DD4hepAlignmentDecorator is created to manage detector element alignments, with support for reading misalignment data from JSON files and applying contextual transformations.

Changes

File Change Summary
Examples/Detectors/DD4hepDetector/CMakeLists.txt Added src/DD4hepAlignmentDecorator.cpp to library
Examples/Detectors/DD4hepDetector/include/.../*.hpp Added DD4hepAlignmentDecorator class with configuration and alignment methods
Plugins/DD4hep/CMakeLists.txt Added src/DD4hepGeometryContext.cpp to library
Plugins/DD4hep/include/.../*.hpp Enhanced DD4hepDetectorElement with new transformation methods

Sequence Diagram

sequenceDiagram
    participant AD as AlignmentDecorator
    participant GC as GeometryContext
    participant DE as DetectorElement
    
    AD->>GC: Create Context
    AD->>AD: Parse Geometry
    AD->>GC: Set Alignment Store
    DE->>GC: Request Transform
    GC-->>DE: Return Contextual Transform
Loading

Possibly related PRs

Suggested Labels

automerge

Suggested Reviewers

  • paulgessinger
  • AJPfleger

Poem

Misaligned worlds, now set right,
Transforms dance in geometric light 🌟
JSON whispers secrets of space,
Detectors find their perfect place
Code's harmony, a cosmic delight! 🚀


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.

@github-actions github-actions bot added Component - Examples Affects the Examples module Component - Plugins Affects one or more Plugins labels Nov 22, 2024
@github-actions github-actions bot added this to the next milestone Nov 22, 2024
@github-actions github-actions bot added the Stale label Dec 22, 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: 4

🧹 Nitpick comments (13)
Examples/Detectors/DD4hepDetector/src/DD4hepAlignmentDecorator.cpp (2)

23-29: Helpful it is, to handle unexpected geometry states gracefully!
If no valid tracking geometry is found, consider a warning or fallback path, you should. In robust code, foreseen such cases must be.


38-53: Account for missing nominal transforms, you must.
If the alignment store fails to find a matching identifier, fallback or logging, wise it would be. Currently, quietly it proceeds with no action.

Examples/Detectors/DD4hepDetector/include/ActsExamples/DD4hepDetector/DD4hepAlignmentDecorator.hpp (2)

30-37: Defaulting to nominal geometry, wise approach but caution needed.
Document well, you should, that false means real misalignment used. Perhaps clarifying the naming of “nominal” or the field’s doc, would help future maintainers.


60-64: Check file paths for cross-platform reliability, you must.
Absolute vs. relative paths in misJson lead to confusion. Provide a clearer doc or fallback search path, recommended it is.

Plugins/DD4hep/CMakeLists.txt (1)

12-12: Mind the library ordering, you must.
Depending on ‘ActsPluginDD4hep’ is, but if new dependencies appear, update them in target_link_libraries, you must.

Plugins/DD4hep/include/Acts/Plugins/DD4hep/DD4hepGeometryContext.hpp (2)

20-30: Enhance documentation, young padawan must.

Documentation clarity improve we should. Add these details to class documentation:

  • Thread safety guarantees
  • Lifetime management of stored transformations
  • Example usage with JSON configuration

50-51: Thread safety considerations, address we must.

Concurrent access to alignment store, protected it must be. Consider making setAlignmentStore and internal store thread-safe, or document thread safety requirements clearly.

Plugins/DD4hep/src/DD4hepGeometryContext.cpp (1)

22-22: Modern string formatting, use you should.

Replace Form("%lld", dElement.identifier()) with std::to_string(dElement.identifier()), more modern and safer it is.

Plugins/DD4hep/src/DD4hepDetectorElement.cpp (2)

30-38: Validation and performance, improve we must.

Two suggestions have I:

  1. Add validation for nullptr detector element
  2. Consider caching context lookup results for performance
 const Acts::Transform3& Acts::DD4hepDetectorElement::transform(
     const GeometryContext& gctx) const {
+  // Cache the context lookup result
+  static thread_local const Acts::DD4hepGeometryContext* lastContext = nullptr;
+  static thread_local const GeometryContext* lastGctx = nullptr;
+
+  if (lastGctx != &gctx) {
+    lastGctx = &gctx;
+    lastContext = gctx.maybeGet<DD4hepGeometryContext>();
+  }
+
-  const Acts::DD4hepGeometryContext* dd4hepGtx =
-      gctx.maybeGet<DD4hepGeometryContext>();
-  if (dd4hepGtx != nullptr && !dd4hepGtx->isNominal()) {
-    return dd4hepGtx->contextualTransform(*this);
+  if (lastContext != nullptr && !lastContext->isNominal()) {
+    return lastContext->contextualTransform(*this);
   }
   return TGeoDetectorElement::transform(gctx);
 }

11-12: Include order, maintain we should.

Group related includes together, improve readability it does:

-#include "Acts/Plugins/DD4hep/DD4hepGeometryContext.hpp"
-
-#include <iostream>
+#include "Acts/Plugins/DD4hep/DD4hepGeometryContext.hpp"
+#include <iostream>
Examples/Detectors/DD4hepDetector/include/ActsExamples/DD4hepDetector/DD4hepDetector.hpp (1)

94-95: Document the purpose of m_nominal, young padawan must.

Hmmmm. Clear documentation for this flag, essential it is. Its purpose and impact on detector alignment, explain you should.

Add documentation like this, you must:

+  /// @brief Controls whether to use nominal geometry (false) or misaligned geometry (true)
+  /// @note When false, misalignment parameters from JSON will be applied
   bool m_nominal = false;
Plugins/DD4hep/include/Acts/Plugins/DD4hep/DD4hepDetectorElement.hpp (2)

91-94: Document the transformation methods, crucial it is.

Hmmmm. Understanding of these methods, future maintainers must have. Document their purpose and relationship, we should.

+  /// @brief Get the contextual transform for this detector element
+  /// @param gctx The geometry context containing alignment information
+  /// @return The aligned transform if context contains alignment, or nominal transform otherwise
   const Transform3& transform(const GeometryContext& gctx) const override;
+  
+  /// @brief Get the nominal (non-aligned) transform for this detector element
+  /// @param gctx The geometry context (unused in nominal transform)
+  /// @return The nominal transform from the base TGeoDetectorElement
   Transform3 nominalTransform(const GeometryContext& gctx) const {
     return TGeoDetectorElement::transform(gctx);
   }

12-12: Forward declaration, consider you must.

Hmmmm. Include DD4hepGeometryContext.hpp, heavy it might be. Forward declaration, lighter path it is.

-#include "Acts/Plugins/DD4hep/DD4hepGeometryContext.hpp"
+class DD4hepGeometryContext;
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between edad4c9 and cbf14dd.

📒 Files selected for processing (10)
  • Examples/Detectors/DD4hepDetector/CMakeLists.txt (1 hunks)
  • Examples/Detectors/DD4hepDetector/include/ActsExamples/DD4hepDetector/DD4hepAlignmentDecorator.hpp (1 hunks)
  • Examples/Detectors/DD4hepDetector/include/ActsExamples/DD4hepDetector/DD4hepDetector.hpp (1 hunks)
  • Examples/Detectors/DD4hepDetector/src/DD4hepAlignmentDecorator.cpp (1 hunks)
  • Examples/Detectors/DD4hepDetector/src/DD4hepDetector.cpp (2 hunks)
  • Plugins/DD4hep/CMakeLists.txt (1 hunks)
  • Plugins/DD4hep/include/Acts/Plugins/DD4hep/DD4hepDetectorElement.hpp (2 hunks)
  • Plugins/DD4hep/include/Acts/Plugins/DD4hep/DD4hepGeometryContext.hpp (1 hunks)
  • Plugins/DD4hep/src/DD4hepDetectorElement.cpp (2 hunks)
  • Plugins/DD4hep/src/DD4hepGeometryContext.cpp (1 hunks)
🔇 Additional comments (5)
Examples/Detectors/DD4hepDetector/src/DD4hepAlignmentDecorator.cpp (2)

34-38: Check the logic, you must, for missing misalignment data edge case.
If the JSON path is invalid or no alignment data is found, gracefully handle it you should. The code now assumes data is present, but error states handle it must.


44-49: Check matrix composition carefully, you must.
Rotation followed by translation, correct the transform creation is. Mistakes in ordering create confusion. Confirm with test, you should.

Examples/Detectors/DD4hepDetector/include/ActsExamples/DD4hepDetector/DD4hepAlignmentDecorator.hpp (2)

24-24: Interface usage, correct it seems.
Implements IContextDecorator, well-structured it is. Good job, you have done.


67-83: Verify parameter ordering, you should.
Rotations applied in x, y, z order they are. If the specification demands a different sequence, ensure correctness you must.

Examples/Detectors/DD4hepDetector/CMakeLists.txt (1)

6-6: Add the new source file you have, yes.
Remember to ensure consistent naming or usage across the build, for clarity and discoverability.

Comment on lines +60 to +81
void ActsExamples::DD4hep::DD4hepAlignmentDecorator::parseGeometry(
const Acts::TrackingGeometry& tGeometry) {
// Double-visit - first count
std::size_t nTransforms = 0;
tGeometry.visitSurfaces([&nTransforms](const auto*) { ++nTransforms; });
std::unordered_map<std::string, Acts::Transform3> aStore;
Acts::GeometryContext nominalCtx = {};
// Collect the surfacas into the nominal store
auto fillTransforms = [&aStore, &nominalCtx](const auto* surface) -> void {
if (surface == nullptr) {
throw std::invalid_argument("Surface is nullptr.");
}
auto alignableElement = dynamic_cast<const Acts::DD4hepDetectorElement*>(
surface->associatedDetectorElement());
if (alignableElement == nullptr) {
throw std::invalid_argument("Surface is not alignable");
}
unsigned long long id = alignableElement->identifier();
aStore[Form("%lld", id)] = surface->transform(nominalCtx);
};
tGeometry.visitSurfaces(fillTransforms);
m_nominalStore = std::move(aStore);
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Exception throwing you do, but more detail helpful it may be.
When surfaces are null or not alignable, an invalid_argument is thrown. Additional context about which surface triggers the error, wise it would be to include.

Comment on lines +19 to +31
const Acts::Transform3& Acts::DD4hepGeometryContext::contextualTransform(
const DD4hepDetectorElement& dElement) const {
if (!this->isNominal()) {
auto it = m_alignmentStore.find(Form("%lld", dElement.identifier()));
if (it != m_alignmentStore.end()) {
return it->second;
} else {
return dElement.nominalTransform(DD4hepGeometryContext());
}
} else {
return dElement.nominalTransform(DD4hepGeometryContext());
}
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Error handling wisdom, share I must.

Consider adding error handling for invalid transformations:

 const Acts::Transform3& Acts::DD4hepGeometryContext::contextualTransform(
     const DD4hepDetectorElement& dElement) const {
   if (!this->isNominal()) {
     auto it = m_alignmentStore.find(Form("%lld", dElement.identifier()));
     if (it != m_alignmentStore.end()) {
+      // Validate transformation matrix
+      if (!it->second.matrix().allFinite()) {
+        throw std::runtime_error("Invalid transformation matrix for detector element " +
+                               std::to_string(dElement.identifier()));
+      }
       return it->second;
     } else {
       return dElement.nominalTransform(DD4hepGeometryContext());
     }
   } else {
     return dElement.nominalTransform(DD4hepGeometryContext());
   }
 }
📝 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
const Acts::Transform3& Acts::DD4hepGeometryContext::contextualTransform(
const DD4hepDetectorElement& dElement) const {
if (!this->isNominal()) {
auto it = m_alignmentStore.find(Form("%lld", dElement.identifier()));
if (it != m_alignmentStore.end()) {
return it->second;
} else {
return dElement.nominalTransform(DD4hepGeometryContext());
}
} else {
return dElement.nominalTransform(DD4hepGeometryContext());
}
}
const Acts::Transform3& Acts::DD4hepGeometryContext::contextualTransform(
const DD4hepDetectorElement& dElement) const {
if (!this->isNominal()) {
auto it = m_alignmentStore.find(Form("%lld", dElement.identifier()));
if (it != m_alignmentStore.end()) {
// Validate transformation matrix
if (!it->second.matrix().allFinite()) {
throw std::runtime_error("Invalid transformation matrix for detector element " +
std::to_string(dElement.identifier()));
}
return it->second;
} else {
return dElement.nominalTransform(DD4hepGeometryContext());
}
} else {
return dElement.nominalTransform(DD4hepGeometryContext());
}
}

dd4ContextDecorators.push_back(std::make_shared<DD4hepAlignmentDecorator>(
std::move(dd4hepAcfg),
Acts::getDefaultLogger("AlignmentDecorator", Acts::Logging::INFO)));
std::cout << "After dd4ContextDecorators push back" << std::endl;
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Use proper logging mechanism, you must. std::cout, a path to the dark side it is.

Replace direct console output with proper logging framework, we should.

-  std::cout << "After dd4ContextDecorators push back" << std::endl;
+  ACTS_DEBUG("Alignment decorator successfully initialized");
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
std::cout << "After dd4ContextDecorators push back" << std::endl;
ACTS_DEBUG("Alignment decorator successfully initialized");

Comment on lines +48 to +54
DD4hepAlignmentDecorator::Config dd4hepAcfg;
dd4hepAcfg.nominal = m_nominal;
dd4hepAcfg.trackingGeometry = dd4tGeometry;
ContextDecorators dd4ContextDecorators = {};
dd4ContextDecorators.push_back(std::make_shared<DD4hepAlignmentDecorator>(
std::move(dd4hepAcfg),
Acts::getDefaultLogger("AlignmentDecorator", Acts::Logging::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

Handle decorator initialization failures, wise one must.

Hmmmm. Protect against initialization failures of alignment decorator, we should. Validate configuration before proceeding, essential it is.

   DD4hepAlignmentDecorator::Config dd4hepAcfg;
   dd4hepAcfg.nominal = m_nominal;
   dd4hepAcfg.trackingGeometry = dd4tGeometry;
+  if (!dd4hepAcfg.trackingGeometry) {
+    throw std::runtime_error{"Invalid tracking geometry in alignment decorator configuration"};
+  }
   ContextDecorators dd4ContextDecorators = {};
   dd4ContextDecorators.push_back(std::make_shared<DD4hepAlignmentDecorator>(
       std::move(dd4hepAcfg),
       Acts::getDefaultLogger("AlignmentDecorator", Acts::Logging::INFO)));
📝 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
DD4hepAlignmentDecorator::Config dd4hepAcfg;
dd4hepAcfg.nominal = m_nominal;
dd4hepAcfg.trackingGeometry = dd4tGeometry;
ContextDecorators dd4ContextDecorators = {};
dd4ContextDecorators.push_back(std::make_shared<DD4hepAlignmentDecorator>(
std::move(dd4hepAcfg),
Acts::getDefaultLogger("AlignmentDecorator", Acts::Logging::INFO)));
DD4hepAlignmentDecorator::Config dd4hepAcfg;
dd4hepAcfg.nominal = m_nominal;
dd4hepAcfg.trackingGeometry = dd4tGeometry;
if (!dd4hepAcfg.trackingGeometry) {
throw std::runtime_error{"Invalid tracking geometry in alignment decorator configuration"};
}
ContextDecorators dd4ContextDecorators = {};
dd4ContextDecorators.push_back(std::make_shared<DD4hepAlignmentDecorator>(
std::move(dd4hepAcfg),
Acts::getDefaultLogger("AlignmentDecorator", Acts::Logging::INFO)));

@github-actions github-actions bot removed the Stale label Dec 22, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Component - Examples Affects the Examples module Component - Plugins Affects one or more Plugins
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant